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

evolvedbinary / prosemirror-lwdita / 39f9a6d5-b322-41a9-a821-722344353888

16 Oct 2024 11:06AM UTC coverage: 44.444% (-0.05%) from 44.494%
39f9a6d5-b322-41a9-a821-722344353888

push

circleci

web-flow
Merge pull request #438 from evolvedbinary/feature/app-configuration-new

Create configuration files for Client and Server

175 of 365 branches covered (47.95%)

Branch coverage included in aggregate %.

17 of 38 new or added lines in 4 files covered. (44.74%)

1 existing line in 1 file now uncovered.

325 of 760 relevant lines covered (42.76%)

26.29 hits per line

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

78.18
/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 * as config from '../../app-config.json';
1✔
22
import { showToast } from "../toast";
1✔
23

24
/**
25
 * Fetches the raw content of a document from a GitHub repository.
26
 *
27
 * @param ghrepo - The GitHub repository in the format "owner/repo".
28
 * @param source - The path to the file within the repository.
29
 * @param branch - The branch from which to fetch the document.
30
 * @returns A promise that resolves to the raw content of the document as a string.
31
 *
32
 * @remarks
33
 * This function currently fetches the document from the 'main' branch of the repository.
34
 * should use the GitHub API to dynamically determine the default branch of the repository.
35
 */
36
export const fetchRawDocumentFromGitHub = async (ghrepo: string, source: string, branch: string): Promise<string> => {
2✔
37
  const url = `https://raw.githubusercontent.com/${ghrepo}/${branch}/${source}`;
2✔
38
  const response = await fetch(url);
2✔
39

40
  if (!response.ok) {
2✔
41
    showErrorPage('fileNotFound', '', response.statusText);
1✔
42
  }
43
  //TODO: Handle errors
44
  return response.text();
1✔
45
};
46

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

58
  // convert the jdita document to prosemirror state save
59
  const prosemirrorJson = await jditaToProsemirrorJson(jdita);
1✔
60

61
  return prosemirrorJson;
1✔
62
};
63

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

78
/**
79
 * Exchanges an OAuth code for an access token.
80
 *
81
 * @param code - The OAuth code to exchange for an access token.
82
 * @returns A promise that resolves to the access token as a string.
83
 * @throws Will throw an error if the fetch request fails or if the response is not in the expected format.
84
 */
85
export const exchangeOAuthCodeForAccessToken = async (code: string): Promise<string> => {
1✔
86
  // build the URL to exchange the code for an access token
NEW
87
  const url = config.serverConfig.apiUrl + config.GITHUB_API_ENPOINT_TOKEN + `?code=${code}`;
×
88
  // fetch the access token
89
  const response = await fetch(url);
×
90

91
  // TODO (AvC): This error type might be changed to be more specific depending on
92
  // further error handling
93
  if (!response.ok) {
×
NEW
94
    showToast(config.messageKeys.error.toastGitHubToken + response.statusText, 'error');
×
95
  }
96

97
  const json = await response.json();
×
98
  //TODO: Handle errors
99
  return json.token;
×
100
};
101

102
/**
103
 * Fetches user information from the backend API.
104
 *
105
 * @param token - The authorization token to access the GitHub API.
106
 * @returns A promise that resolves to a record containing user information.
107
 */
108
export const getUserInfo = async (token: string): Promise<Record<string, string>> => {
3✔
109
  const url = config.serverConfig.apiUrl + config.GITHUB_API_ENPOINT_USER;
3✔
110
  const response = await fetch(url, {
3✔
111
    headers: {
112
      'authorization': `Bearer ${token}`
113
    }
114
  });
115

116
  // TODO (AvC): This error type might be changed to be more specific depending on
117
  // further error handling
118
  if (!response.ok) {
3✔
119
    showToast(config.messageKeys.error.toastGitHubUserEndpoint + response.statusText, 'error');
1✔
120
  }
121
  const json = await response.json();
2✔
122
  return json;
2✔
123
};
124

125
/**
126
 * Publishes a document to a specified GitHub repository.
127
 * Makes a POST request to the `/api/github/integration` endpoint with the necessary details to create a pull request.
128
 *
129
 * @param ghrepo - The GitHub repository in the format "owner/repo".
130
 * @param source - The path to the source document.
131
 * @param branch - The branch used as base for the PR.
132
 * @param title - The title of the pull request and the commit message.
133
 * @param desc - The description of the pull request.
134
 * @param changedDocument - The content of the changed document.
135
 * @returns A promise that resolves when the document has been published.
136
 */
137
export const createPrFromContribution = async (ghrepo: string, source: string, branch: string, changedDocument: string, title: string, desc: string): Promise<string> => {
1✔
138
  const authenticatedUserInfo = await getUserInfo(localStorage.getItem('token') as string);
1✔
139

140
  const owner = ghrepo.split('/')[0];
1✔
141
  const repo = ghrepo.split('/')[1];
1✔
142
  const newOwner = authenticatedUserInfo.login;
1✔
143
  const date = new Date();
1✔
144
  const newBranch = config.PETAL_BRANCH_PREFIX + `${date.getFullYear()}${date.getMonth()}${date.getDate()}${date.getHours()}${date.getMinutes()}${date.getSeconds()}`;
1✔
145
  const commitMessage = title;
1✔
146
  const path = source;
1✔
147
  const content = changedDocument;
1✔
148
  const change = {
1✔
149
    path,
150
    content
151
  };
152
  const body = `${desc}` + config.PETAL_COMMIT_MESSAGE_SUFFIX;
1✔
153
  // get the token from the local storage
154
  const token = localStorage.getItem('token');
1✔
155
  // make a post request to  /api/github/integration
156
  const response = await fetch(config.serverConfig.apiUrl + config.GITHUB_API_ENPOINT_INTEGRATION, {
1✔
157
    method: 'POST',
158
    headers: {
159
      'Content-Type': 'application/json',
160
      'Authorization': `Bearer ${token}`
161
    },
162
    body: JSON.stringify({
163
      owner,
164
      repo,
165
      newOwner,
166
      branch,
167
      newBranch,
168
      commitMessage,
169
      change,
170
      title,
171
      body
172
    })
173
  });
174

175
  // TODO (AvC): This error type might be changed to be more specific depending on
176
  // further error handling
177
  if (!response.ok) {
1!
NEW
178
    showToast(config.messageKeys.error.toastGitHubPR + response.statusText, 'error');
×
179
  }
180

181
  const json = await response.json();
1✔
182
  return json.url;
1✔
183
};
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