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

evolvedbinary / prosemirror-lwdita / 107169a0-71be-4383-ba02-27153cc3d8ae

31 Oct 2025 05:49PM UTC coverage: 47.627% (-0.3%) from 47.96%
107169a0-71be-4383-ba02-27153cc3d8ae

push

circleci

web-flow
Merge pull request #513 from evolvedbinary/dependabot/npm_and_yarn/fetch-mock-12.2.0

Bump fetch-mock from 11.1.5 to 12.2.0

211 of 411 branches covered (51.34%)

Branch coverage included in aggregate %.

361 of 790 relevant lines covered (45.7%)

49.97 hits per line

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

71.7
/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
import { Global } from '../global'
25

26
/**
27
 * Fetches the raw content of a document from a GitHub repository.
28
 *
29
 * @param config - configuration
30
 * @param urlParams - Object containing ghrepo, source, branch.
31
 * @returns A promise that resolves to the raw content of the document as a string.
32
 *
33
 * @remarks
34
 * This function currently fetches the document from the 'main' branch of the repository.
35
 * should use the GitHub API to dynamically determine the default branch of the repository.
36
 */
37
export const fetchRawDocumentFromGitHub = async (config: Config, urlParams: URLParams): Promise<string> => {
2✔
38
  const { ghrepo, source, branch } = urlParams;
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, 'fileNotFoundError', urlParams.referrer);
×
47
  }
48

49
  return response.text();
2✔
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 urlParams - Object containing ghrepo, source, branch.
74
 * @returns A promise that resolves to the transformed ProseMirror JSON document.
75
 */
76
export const fetchAndTransform = async (config: Config, urlParams: URLParams) => {
1✔
77

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

86
  try {
×
87
    const jsonDoc = await transformGitHubDocumentToProsemirrorJson(updatedDoc);
×
88
    return jsonDoc;
×
89
  } catch (_error) {
90
    showErrorPage(config, 'incompatibleXditaFile', urlParams.referrer);
×
91
  }
92
};
93

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

110
  return {
×
111
    token: json.token,
112
    installation: json.installation
113
  };
114
};
115

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

132
  const json = await response.json();
2✔
133
  return json;
2✔
134
};
135

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

169
  // make a post request to  /api/github/integration
170
  const response = await fetch(config.server.api.baseUrl + config.server.api.endpoint.integration, {
1✔
171
    method: 'POST',
172
    headers: {
173
      'Content-Type': 'application/json',
174
      'Authorization': `Bearer ${token}`
175
    },
176
    body: JSON.stringify({
177
      owner,
178
      repo,
179
      newOwner,
180
      branch,
181
      newBranch,
182
      commitMessage,
183
      change,
184
      title,
185
      body
186
    })
187
  });
188

189
  const json = await response.json();
1✔
190
  if(!json.url) {
1!
191
    throw new Error(localization.t("error.toastGitHubPR") + json.error);
×
192
  }
193
  return json.url;
1✔
194
};
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