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

evolvedbinary / prosemirror-lwdita / 023bc3e2-4af4-4248-893d-041993c375bf

03 Apr 2025 01:58PM UTC coverage: 44.526% (+0.4%) from 44.081%
023bc3e2-4af4-4248-893d-041993c375bf

Pull #573

circleci

marmoure
[test] fix broken tests
Pull Request #573: Fix redirect to error pages

170 of 351 branches covered (48.43%)

Branch coverage included in aggregate %.

10 of 22 new or added lines in 2 files covered. (45.45%)

3 existing lines in 2 files now uncovered.

314 of 736 relevant lines covered (42.66%)

27.49 hits per line

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

78.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, URLParams } from "./request";
1✔
21
import { Config } from "../config";
22
import { Localization } from "@evolvedbinary/prosemirror-lwdita-localization";
23
import urijs from "urijs";
1✔
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, urlParams: URLParams): Promise<string> => {
2✔
39
  const { ghrepo, source, branch } = urlParams;
2✔
40
  // GitHub changes the raw api URL from `main` to `refs/heads/main` 
41
  // https://raw.githubusercontent.com/evolvedbinary/prosemirror-lwdita/main/packages/prosemirror-lwdita-demo/example-xdita/02-short-file.xml
42
  // https://raw.githubusercontent.com/evolvedbinary/prosemirror-lwdita/refs/heads/main/packages/prosemirror-lwdita-demo/example-xdita/02-short-file.xml
43
  const url = `https://raw.githubusercontent.com/${ghrepo}/refs/heads/${branch}/${source}`;
2✔
44
  const response = await fetch(url);
2✔
45

46
  if (!response.ok) {
2✔
47
    showErrorPage(config, 'fileNotFoundError', urlParams.referer);
1✔
48
  }
49

50
  return response.text();
1✔
51
};
52

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

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

67
  return prosemirrorJson;
1✔
68
};
69

70
/**
71
 * Fetches a raw document from a GitHub repository and transforms it into a ProseMirror JSON document.
72
 *
73
 * @param config - configuration
74
 * @param ghrepo - The GitHub repository from which to fetch the document.
75
 * @param source - The source path of the document within the repository.
76
 * @param branch - The branch from which to fetch the document.
77
 * @returns A promise that resolves to the transformed ProseMirror JSON document.
78
 */
79
export const fetchAndTransform = async (config: Config, urlParams: URLParams) => {
1✔
80

NEW
81
  const rawDoc = await fetchRawDocumentFromGitHub(config, urlParams);
×
82
  
83
  // update the document with the relative path
UNCOV
84
  const updatedDoc = rawDoc.replace(/href="([^"]+)"/g, (_match, url) => {
×
85
    // https://www.npmjs.com/package/urijs
NEW
86
    return `href="${urijs(url).absoluteTo(urlParams.referer).href()}"`;
×
87
  });
88

NEW
89
  try {
×
NEW
90
    const jsonDoc = await transformGitHubDocumentToProsemirrorJson(updatedDoc);
×
NEW
91
    return jsonDoc;
×
92
  } catch (_error) {
NEW
93
    showErrorPage(config, 'incompatibleXditaFile', urlParams.referer);
×
94
  }
95
};
96

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

113
  return {
×
114
    token: json.token,
115
    installation: json.installation
116
  };
117
};
118

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

135
  const json = await response.json();
3✔
136
  return json;
2✔
137
};
138

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

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

191
  const json = await response.json();
1✔
192
  return json.url;
1✔
193
};
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