• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

evolvedbinary / prosemirror-lwdita / dfc54cea-d06c-41f1-96d8-2f3959f889f9

28 Oct 2024 05:13PM UTC coverage: 44.032% (-0.2%) from 44.19%
dfc54cea-d06c-41f1-96d8-2f3959f889f9

push

circleci

web-flow
Merge pull request #468 from evolvedbinary/refactor/further-configuration-improvements

Improvements to Configuration and Localisation

175 of 369 branches covered (47.43%)

Branch coverage included in aggregate %.

24 of 46 new or added lines in 4 files covered. (52.17%)

1 existing line in 1 file now uncovered.

323 of 762 relevant lines covered (42.39%)

26.55 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

77.78
/packages/prosemirror-lwdita/src/github-integration/github.plugin.ts
1
/*!
2
Copyright (C) 2020 Evolved Binary
3

4
This program is free software: you can redistribute it and/or modify
5
it under the terms of the GNU Affero General Public License as
6
published by the Free Software Foundation, either version 3 of the
7
License, or (at your option) any later version.
8

9
This program is distributed in the hope that it will be useful,
10
but WITHOUT ANY WARRANTY; without even the implied warranty of
11
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
GNU Affero General Public License for more details.
13

14
You should have received a copy of the GNU Affero General Public License
15
along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
*/
17

18
import { xditaToJdita } from "@evolvedbinary/lwdita-xdita";
1✔
19
import { document as jditaToProsemirrorJson } from "../document";
1✔
20
import { showErrorPage } from "./request";
1✔
21
import { showToast } from "../toast";
1✔
22
import { Config } from "../config";
23
import { Localization } from "@evolvedbinary/prosemirror-lwdita-localization";
24

25
/**
26
 * Fetches the raw content of a document from a GitHub repository.
27
 *
28
 * @param config - configuration
29
 * @param ghrepo - The GitHub repository in the format "owner/repo".
30
 * @param source - The path to the file within the repository.
31
 * @param branch - The branch from which to fetch the document.
32
 * @returns A promise that resolves to the raw content of the document as a string.
33
 *
34
 * @remarks
35
 * This function currently fetches the document from the 'main' branch of the repository.
36
 * should use the GitHub API to dynamically determine the default branch of the repository.
37
 */
38
export const fetchRawDocumentFromGitHub = async (config: Config, ghrepo: string, source: string, branch: string): Promise<string> => {
2✔
39
  // GitHub changes the raw api URL from `main` to `refs/heads/main` 
40
  // https://raw.githubusercontent.com/evolvedbinary/prosemirror-lwdita/main/packages/prosemirror-lwdita-demo/example-xdita/02-short-file.xml
41
  // https://raw.githubusercontent.com/evolvedbinary/prosemirror-lwdita/refs/heads/main/packages/prosemirror-lwdita-demo/example-xdita/02-short-file.xml
42
  const url = `https://raw.githubusercontent.com/${ghrepo}/refs/heads/${branch}/${source}`;
2✔
43
  const response = await fetch(url);
2✔
44

45
  if (!response.ok) {
2✔
46
    showErrorPage(config, 'fileNotFound', '', response.statusText);
1✔
47
  }
48
  //TODO: Handle errors
49
  return response.text();
1✔
50
};
51

52
/**
53
 * Transforms a raw GitHub document into a ProseMirror state save.
54
 *
55
 * @param rawDocument - The raw xdita document as a string.
56
 * @returns A promise that resolves to a record containing the ProseMirror state save.
57
 */
58
// eslint-disable-next-line @typescript-eslint/no-explicit-any
59
export const transformGitHubDocumentToProsemirrorJson = async (rawDocument: string): Promise<Record<string, any>> => {
1✔
60
  // convert the raw xdita document to jdita
61
  const jdita = await xditaToJdita(rawDocument);
1✔
62

63
  // convert the jdita document to prosemirror state save
64
  const prosemirrorJson = await jditaToProsemirrorJson(jdita);
1✔
65

66
  return prosemirrorJson;
1✔
67
};
68

69
/**
70
 * Fetches a raw document from a GitHub repository and transforms it into a ProseMirror JSON document.
71
 *
72
 * @param config - configuration
73
 * @param ghrepo - The GitHub repository from which to fetch the document.
74
 * @param source - The source path of the document within the repository.
75
 * @param branch - The branch from which to fetch the document.
76
 * @returns A promise that resolves to the transformed ProseMirror JSON document.
77
 */
78
export const fetchAndTransform = async (config: Config, ghrepo: string, source: string, branch: string) => {
1✔
NEW
79
  const rawDoc = await fetchRawDocumentFromGitHub(config, ghrepo, source, branch);
×
80
  const jsonDoc = await transformGitHubDocumentToProsemirrorJson(rawDoc);
×
81
  return jsonDoc;
×
82
};
83

84
/**
85
 * Exchanges an OAuth code for an access token.
86
 *
87
 * @param config - configuration
88
 * @param localization - localization
89
 * @param code - The OAuth code to exchange for an access token.
90
 * @returns A promise that resolves to the access token as a string.
91
 * @throws Will throw an error if the fetch request fails or if the response is not in the expected format.
92
 */
93
export const exchangeOAuthCodeForAccessToken = async (config: Config, localization: Localization, code: string): Promise<{token: string, installation: boolean}> => {
1✔
94
  // build the URL to exchange the code for an access token
NEW
95
  const url = config.server.api.baseUrl + config.server.api.endpoint.token + `?code=${code}`;
×
96
  // fetch the access token
97
  const response = await fetch(url);
×
98

99
  // TODO (AvC): This error type might be changed to be more specific depending on
100
  // further error handling
101
  if (!response.ok) {
×
NEW
102
    showToast(localization.t("error.toastGitHubToken") + response.statusText, 'error');
×
103
  }
104

105
  const json = await response.json();
×
106
  //TODO: Handle errors
107
  return {
×
108
    token: json.token,
109
    installation: json.installation
110
  };
111
};
112

113
/**
114
 * Fetches user information from the backend API.
115
 *
116
 * @param config - configuration
117
 * @param localization - localization
118
 * @param token - The authorization token to access the GitHub API.
119
 * @returns A promise that resolves to a record containing user information.
120
 */
121
export const getUserInfo = async (config: Config, localization: Localization, token: string): Promise<Record<string, string>> => {
3✔
122
  const url = config.server.api.baseUrl + config.server.api.endpoint.user;
3✔
123
  const response = await fetch(url, {
3✔
124
    headers: {
125
      'authorization': `Bearer ${token}`
126
    }
127
  });
128

129
  // TODO (AvC): This error type might be changed to be more specific depending on
130
  // further error handling
131
  if (!response.ok) {
3✔
132
    showToast(localization.t("error.toastGitHubUserEndpoint") + response.statusText, 'error');
1✔
133
  }
134
  const json = await response.json();
2✔
135
  return json;
2✔
136
};
137

138
/**
139
 * Publishes a document to a specified GitHub repository.
140
 * Makes a POST request to the `/api/github/integration` endpoint with the necessary details to create a pull request.
141
 *
142
 * @param config - configuration
143
 * @param localization - localization
144
 * @param ghrepo - The GitHub repository in the format "owner/repo".
145
 * @param source - The path to the source document.
146
 * @param branch - The branch used as base for the PR.
147
 * @param title - The title of the pull request and the commit message.
148
 * @param desc - The description of the pull request.
149
 * @param changedDocument - The content of the changed document.
150
 * @returns A promise that resolves when the document has been published.
151
 */
152
export const createPrFromContribution = async (config: Config, localization: Localization, ghrepo: string, source: string, branch: string, changedDocument: string, title: string, desc: string): Promise<string> => {
1✔
153
  const authenticatedUserInfo = await getUserInfo(config, localization, localStorage.getItem('token') as string);
1✔
154

155
  const owner = ghrepo.split('/')[0];
1✔
156
  const repo = ghrepo.split('/')[1];
1✔
157
  const newOwner = authenticatedUserInfo.login;
1✔
158
  const date = new Date();
1✔
159
  const newBranch = config.git.branchPrefix + `${date.getFullYear()}${date.getMonth()}${date.getDate()}${date.getHours()}${date.getMinutes()}${date.getSeconds()}`;
1✔
160
  const commitMessage = title;
1✔
161
  const path = source;
1✔
162
  const content = changedDocument;
1✔
163
  const change = {
1✔
164
    path,
165
    content
166
  };
167
  const body = `${desc}` + config.git.commitMessageSuffix;
1✔
168
  // get the token from the local storage
169
  const token = localStorage.getItem('token');
1✔
170
  // make a post request to  /api/github/integration
171
  const response = await fetch(config.server.api.baseUrl + config.server.api.endpoint.integration, {
1✔
172
    method: 'POST',
173
    headers: {
174
      'Content-Type': 'application/json',
175
      'Authorization': `Bearer ${token}`
176
    },
177
    body: JSON.stringify({
178
      owner,
179
      repo,
180
      newOwner,
181
      branch,
182
      newBranch,
183
      commitMessage,
184
      change,
185
      title,
186
      body
187
    })
188
  });
189

190
  // TODO (AvC): This error type might be changed to be more specific depending on
191
  // further error handling
192
  if (!response.ok) {
1!
NEW
193
    showToast(localization.t("error.toastGitHubPR") + response.statusText, 'error');
×
194
  }
195

196
  const json = await response.json();
1✔
197
  return json.url;
1✔
198
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc