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

evolvedbinary / prosemirror-lwdita / 329e73a4-fefe-4dc6-abb3-4f2579b459dd

30 Oct 2024 11:18AM UTC coverage: 43.954% (-0.08%) from 44.032%
329e73a4-fefe-4dc6-abb3-4f2579b459dd

Pull #479

circleci

marmoure
bugfix] only replace relative urls
Pull Request #479: Images should point to the base url

175 of 369 branches covered (47.43%)

Branch coverage included in aggregate %.

1 of 4 new or added lines in 1 file covered. (25.0%)

1 existing line in 1 file now uncovered.

323 of 764 relevant lines covered (42.28%)

26.48 hits per line

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

75.0
/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, referer: string) => {
1✔
79
  const rawDoc = await fetchRawDocumentFromGitHub(config, ghrepo, source, branch);
×
80
  // update the document with the relative path
81

NEW
82
  const updatedDoc = rawDoc.replace(/href="([^"]+)"/g, (_match, url) => {
×
83
    // https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
NEW
84
    return `href="${new URL(url, referer).href}"`;
×
85
  });
86

NEW
87
  const jsonDoc = await transformGitHubDocumentToProsemirrorJson(updatedDoc);
×
UNCOV
88
  return jsonDoc;
×
89
};
90

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

106
  // TODO (AvC): This error type might be changed to be more specific depending on
107
  // further error handling
108
  if (!response.ok) {
×
109
    showToast(localization.t("error.toastGitHubToken") + response.statusText, 'error');
×
110
  }
111

112
  const json = await response.json();
×
113
  //TODO: Handle errors
114
  return {
×
115
    token: json.token,
116
    installation: json.installation
117
  };
118
};
119

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

136
  // TODO (AvC): This error type might be changed to be more specific depending on
137
  // further error handling
138
  if (!response.ok) {
3✔
139
    showToast(localization.t("error.toastGitHubUserEndpoint") + response.statusText, 'error');
1✔
140
  }
141
  const json = await response.json();
2✔
142
  return json;
2✔
143
};
144

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

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

197
  // TODO (AvC): This error type might be changed to be more specific depending on
198
  // further error handling
199
  if (!response.ok) {
1!
200
    showToast(localization.t("error.toastGitHubPR") + response.statusText, 'error');
×
201
  }
202

203
  const json = await response.json();
1✔
204
  return json.url;
1✔
205
};
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