@bright-logic-digital/site-editor 0.0.0-stage → 1.0.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/LICENSE +4 -0
- package/README.md +318 -2
- package/bin/cli.js +92 -0
- package/bin/copy-editor.js +211 -0
- package/bin/node-version.js +20 -0
- package/bin/site-config.js +46 -0
- package/bin/site-editor.js +16 -0
- package/editor/admin.css +438 -0
- package/editor/api.js +138 -0
- package/editor/app.js +1178 -0
- package/editor/asset-map.js +38 -0
- package/editor/boot.js +72 -0
- package/editor/copy.js +239 -0
- package/editor/drafts.js +67 -0
- package/editor/format.js +80 -0
- package/editor/forms.js +918 -0
- package/editor/images.js +212 -0
- package/editor/index.html +27 -0
- package/editor/model.js +152 -0
- package/editor/pages.js +297 -0
- package/editor/photos.js +232 -0
- package/editor/publish.js +45 -0
- package/editor/shared/rules.js +118 -0
- package/editor/shared/site.js +128 -0
- package/editor/shared/validate.js +303 -0
- package/editor/signin.js +154 -0
- package/editor/status.js +90 -0
- package/editor/uploads.js +91 -0
- package/guide/check.js +233 -0
- package/hosts/next.js +19 -0
- package/hosts/pages.js +20 -0
- package/hosts/shared.js +42 -0
- package/package.json +91 -4
- package/server/blob-sha.js +10 -0
- package/server/changes.js +24 -0
- package/server/check-content.js +197 -0
- package/server/config.js +97 -0
- package/server/dispatch.js +207 -0
- package/server/github.js +149 -0
- package/server/handlers.js +364 -0
- package/server/index.js +153 -0
- package/server/local-repo.js +171 -0
- package/server/mapped-repo.js +48 -0
- package/server/memory-repo.js +104 -0
- package/server/path-map.js +26 -0
- package/server/signin/access.js +329 -0
- package/server/signin/code-store.sql +60 -0
- package/server/signin/code.js +192 -0
- package/server/signin/codes.js +171 -0
- package/server/signin/refusal.js +76 -0
- package/server/signin/session.js +90 -0
- package/tests/fixtures/image-files.json +14 -0
- package/tests/fixtures/slugs.json +202 -0
- package/tests/fixtures/validation.json +12734 -0
- package/types/bin/cli.d.ts +1 -0
- package/types/bin/copy-editor.d.ts +32 -0
- package/types/bin/node-version.d.ts +8 -0
- package/types/bin/site-config.d.ts +17 -0
- package/types/bin/site-editor.d.ts +2 -0
- package/types/editor/api.d.ts +37 -0
- package/types/editor/copy.d.ts +153 -0
- package/types/editor/shared/rules.d.ts +33 -0
- package/types/editor/shared/site.d.ts +35 -0
- package/types/editor/shared/validate.d.ts +19 -0
- package/types/guide/check.d.ts +31 -0
- package/types/hosts/next.d.ts +12 -0
- package/types/hosts/pages.d.ts +9 -0
- package/types/hosts/shared.d.ts +21 -0
- package/types/server/blob-sha.d.ts +1 -0
- package/types/server/changes.d.ts +2 -0
- package/types/server/check-content.d.ts +16 -0
- package/types/server/config.d.ts +46 -0
- package/types/server/dispatch.d.ts +51 -0
- package/types/server/github.d.ts +27 -0
- package/types/server/handlers.d.ts +116 -0
- package/types/server/index.d.ts +75 -0
- package/types/server/local-repo.d.ts +16 -0
- package/types/server/mapped-repo.d.ts +10 -0
- package/types/server/memory-repo.d.ts +28 -0
- package/types/server/path-map.d.ts +3 -0
- package/types/server/signin/access.d.ts +68 -0
- package/types/server/signin/code.d.ts +44 -0
- package/types/server/signin/codes.d.ts +98 -0
- package/types/server/signin/refusal.d.ts +122 -0
- package/types/server/signin/session.d.ts +29 -0
package/server/config.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The settings (environment variables) as the emailed-code sign-in reads
|
|
3
|
+
// them: values are not trimmed and every listed address must be one. The
|
|
4
|
+
// Access sign-in keeps its own reading (signin/access.js). Also whether
|
|
5
|
+
// this is local editing mode, which both kinds share.
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @typedef {object} AdminConfig
|
|
9
|
+
* @property {string} token
|
|
10
|
+
* @property {string} repo
|
|
11
|
+
* @property {string} branch
|
|
12
|
+
* @property {string[]} emails
|
|
13
|
+
* @property {string} secret
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** @typedef {Record<string, string | undefined>} Env */
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @typedef {object} ReadOptions
|
|
20
|
+
* @property {"vercel" | null} [liveBranchGuard] "vercel" (the default):
|
|
21
|
+
* GITHUB_BRANCH may be main only when VERCEL_ENV is "production". null: no guard.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const ADDRESS = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
25
|
+
const BRANCH = /^[A-Za-z0-9._-]+$/;
|
|
26
|
+
const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Trimmed, lower-cased address, or null when the input is not one.
|
|
30
|
+
* @param {unknown} input
|
|
31
|
+
* @returns {string | null}
|
|
32
|
+
*/
|
|
33
|
+
export function normalizeEmail(input) {
|
|
34
|
+
if (typeof input !== "string") return null;
|
|
35
|
+
const email = input.trim().toLowerCase();
|
|
36
|
+
return ADDRESS.test(email) ? email : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The NAMES of the settings that are missing or malformed, plus the guard's
|
|
41
|
+
* own words when it is what refuses. Never a value. Empty when the
|
|
42
|
+
* configuration is usable.
|
|
43
|
+
* @param {Env} env
|
|
44
|
+
* @param {ReadOptions} [options]
|
|
45
|
+
* @returns {string[]}
|
|
46
|
+
*/
|
|
47
|
+
export function configProblems(env, { liveBranchGuard = "vercel" } = {}) {
|
|
48
|
+
/** @type {string[]} */
|
|
49
|
+
const problems = [];
|
|
50
|
+
const { GITHUB_TOKEN: token, GITHUB_REPO: repo, GITHUB_BRANCH: branch } = env;
|
|
51
|
+
const { ADMIN_EMAILS: emails, ADMIN_SESSION_SECRET: secret } = env;
|
|
52
|
+
if (!token) problems.push("GITHUB_TOKEN");
|
|
53
|
+
if (!repo || !REPO.test(repo)) problems.push("GITHUB_REPO");
|
|
54
|
+
if (!branch || !BRANCH.test(branch)) problems.push("GITHUB_BRANCH");
|
|
55
|
+
if (!emails || !emails.split(",").every((entry) => normalizeEmail(entry))) {
|
|
56
|
+
problems.push("ADMIN_EMAILS");
|
|
57
|
+
}
|
|
58
|
+
if (!secret || secret.length < 32) problems.push("ADMIN_SESSION_SECRET");
|
|
59
|
+
// A preview must never commit to the live branch.
|
|
60
|
+
if (liveBranchGuard === "vercel" && branch === "main" && env.VERCEL_ENV !== "production") {
|
|
61
|
+
problems.push("GITHUB_BRANCH may not be main outside production");
|
|
62
|
+
}
|
|
63
|
+
return problems;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The editor's configuration, or null unless every part is present and valid
|
|
68
|
+
* (exactly when configProblems is not empty). Values are not trimmed.
|
|
69
|
+
* @param {Env} env
|
|
70
|
+
* @param {ReadOptions} [options]
|
|
71
|
+
* @returns {AdminConfig | null}
|
|
72
|
+
*/
|
|
73
|
+
export function readAdminConfig(env, options) {
|
|
74
|
+
if (configProblems(env, options).length > 0) return null;
|
|
75
|
+
return {
|
|
76
|
+
token: /** @type {string} */ (env.GITHUB_TOKEN),
|
|
77
|
+
repo: /** @type {string} */ (env.GITHUB_REPO),
|
|
78
|
+
branch: /** @type {string} */ (env.GITHUB_BRANCH),
|
|
79
|
+
emails: /** @type {string} */ (env.ADMIN_EMAILS)
|
|
80
|
+
.split(",")
|
|
81
|
+
.map((entry) => /** @type {string} */ (normalizeEmail(entry))),
|
|
82
|
+
secret: /** @type {string} */ (env.ADMIN_SESSION_SECRET),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Local editing mode: true exactly when ADMIN_LOCAL is "1", NODE_ENV is not
|
|
88
|
+
* "production" (a missing NODE_ENV counts as not production) and VERCEL is
|
|
89
|
+
* unset or empty. So ADMIN_LOCAL must never be set on a deployed host.
|
|
90
|
+
* @param {Env} env
|
|
91
|
+
* @returns {boolean}
|
|
92
|
+
*/
|
|
93
|
+
export function isLocalMode(env) {
|
|
94
|
+
return (
|
|
95
|
+
env.ADMIN_LOCAL === "1" && env.NODE_ENV !== "production" && !env.VERCEL
|
|
96
|
+
);
|
|
97
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The editor's API: every /api/admin/* request comes through
|
|
3
|
+
// handleAdminRequest, which checks, in this order, that the request came from
|
|
4
|
+
// the editor's own origin, that the editor is configured, that the caller is
|
|
5
|
+
// signed in with a listed address, and only then runs the route. How a
|
|
6
|
+
// caller signs in is the sign-in provider's (signin/refusal.js has the
|
|
7
|
+
// contract); this file knows nothing else about either kind. Everything
|
|
8
|
+
// outside (the repository, the sign-in, the clock, the log) is passed in, so
|
|
9
|
+
// this file only decides. Every answer is built with respond(), so every one
|
|
10
|
+
// carries Cache-Control: no-store. Nothing here logs or returns a code, a
|
|
11
|
+
// session, a token or a setting's value; a refused configuration logs the
|
|
12
|
+
// settings' names.
|
|
13
|
+
import { isLocalMode } from "./config.js";
|
|
14
|
+
import {
|
|
15
|
+
MAX_UPLOAD_CHARS,
|
|
16
|
+
badRequest,
|
|
17
|
+
crossSiteFailure,
|
|
18
|
+
failure,
|
|
19
|
+
getDoc,
|
|
20
|
+
getState,
|
|
21
|
+
getStatus,
|
|
22
|
+
photoTooLarge,
|
|
23
|
+
postPublish,
|
|
24
|
+
postUpload,
|
|
25
|
+
respond,
|
|
26
|
+
} from "./handlers.js";
|
|
27
|
+
import { SignInRefused, failureLine, notConfigured } from "./signin/refusal.js";
|
|
28
|
+
|
|
29
|
+
/** @typedef {import("./signin/refusal.js").SignInProvider} SignInProvider */
|
|
30
|
+
/** @typedef {import("./signin/refusal.js").SignInContext} SignInContext */
|
|
31
|
+
/** @typedef {import("./signin/refusal.js").GithubSettings} GithubSettings */
|
|
32
|
+
/** @typedef {import("./signin/refusal.js").SiteConfig} SiteConfig */
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @typedef {object} Repo
|
|
36
|
+
* @property {() => Promise<{ commit: string, files: Map<string, string> }>} head
|
|
37
|
+
* @property {(sha: string) => Promise<string>} readText
|
|
38
|
+
* @property {(base64: string) => Promise<string>} createBlob
|
|
39
|
+
* @property {(input: { parent: string, changes: unknown[], message: string }) => Promise<string>} commit
|
|
40
|
+
* @property {(ancestor: string, descendant: string) => Promise<boolean>} contains
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @typedef {object} AdminDeps
|
|
45
|
+
* @property {Record<string, string | undefined>} env the settings, for this request
|
|
46
|
+
* @property {SiteConfig} config the site's config, already checked
|
|
47
|
+
* @property {SignInProvider} signIn
|
|
48
|
+
* @property {(settings: GithubSettings) => Repo} repoFor the site's repository
|
|
49
|
+
* @property {() => number} now
|
|
50
|
+
* @property {(line: string) => void} log
|
|
51
|
+
* @property {{ user: string, repo: Repo }} [local] set only when the site
|
|
52
|
+
* offers local mode; used only when the settings ask for it
|
|
53
|
+
*/
|
|
54
|
+
|
|
55
|
+
const PREFIX = "/api/admin/";
|
|
56
|
+
/** The most characters a publish request's body may hold. */
|
|
57
|
+
export const MAX_PUBLISH_CHARS = 500000;
|
|
58
|
+
|
|
59
|
+
// URL reports the IPv6 loopback with its brackets.
|
|
60
|
+
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
61
|
+
// A Host header naming this computer: one of those, with or without a port.
|
|
62
|
+
const LOCAL_HOST_HEADER = /^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d{1,5})?$/i;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Whether a request was asked of this computer: its address names this
|
|
66
|
+
* computer, and so does its Host header when it carries one.
|
|
67
|
+
* @param {Request} request
|
|
68
|
+
*/
|
|
69
|
+
function askedOfThisComputer(request) {
|
|
70
|
+
if (!LOCAL_HOSTS.has(new URL(request.url).hostname)) return false;
|
|
71
|
+
const host = request.headers.get("Host");
|
|
72
|
+
return host === null || LOCAL_HOST_HEADER.test(host);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const NOT_THIS_COMPUTER = () =>
|
|
76
|
+
failure(403, "forbidden", "The local editor only answers on this computer.");
|
|
77
|
+
const NOT_FOUND = () => failure(404, "not_found", "That address does not exist.");
|
|
78
|
+
const PUBLISH_TOO_LARGE = () =>
|
|
79
|
+
failure(413, "too_large", "This is too much to publish at once. Publish fewer pages at a time.");
|
|
80
|
+
const UPSTREAM = () =>
|
|
81
|
+
failure(502, "upstream",
|
|
82
|
+
"The place the site is stored did not answer properly. Please try again in a few minutes.");
|
|
83
|
+
const SERVER_ERROR = () => failure(500, "server_error", "Something went wrong. Please try again.");
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Step 6: the editor's routes, for a caller already known to be allowed.
|
|
87
|
+
* @param {Request} request
|
|
88
|
+
* @param {string} name
|
|
89
|
+
* @param {Repo} repo
|
|
90
|
+
* @param {string} user
|
|
91
|
+
* @param {SiteConfig} config
|
|
92
|
+
*/
|
|
93
|
+
async function route(request, name, repo, user, config) {
|
|
94
|
+
const query = new URL(request.url).searchParams;
|
|
95
|
+
const method = request.method;
|
|
96
|
+
if (method === "GET" && name === "state") return respond(await getState(repo, user));
|
|
97
|
+
if (method === "GET" && name === "doc") return respond(await getDoc(repo, query.get("path")));
|
|
98
|
+
if (method === "GET" && name === "status") {
|
|
99
|
+
return respond(await getStatus(repo, query.get("mine"), query.get("deployed")));
|
|
100
|
+
}
|
|
101
|
+
if (method === "POST" && name === "upload") {
|
|
102
|
+
if (Number(request.headers.get("Content-Length")) > MAX_UPLOAD_CHARS) {
|
|
103
|
+
return respond(photoTooLarge());
|
|
104
|
+
}
|
|
105
|
+
// postUpload checks the length of what was read too, since a client can
|
|
106
|
+
// omit or misstate Content-Length.
|
|
107
|
+
return respond(await postUpload(repo, query.get("name"), await request.text()));
|
|
108
|
+
}
|
|
109
|
+
if (method === "POST" && name === "publish") {
|
|
110
|
+
const type = request.headers.get("Content-Type") ?? "";
|
|
111
|
+
if (!type.toLowerCase().startsWith("application/json")) return respond(badRequest());
|
|
112
|
+
if (Number(request.headers.get("Content-Length")) > MAX_PUBLISH_CHARS) {
|
|
113
|
+
return respond(PUBLISH_TOO_LARGE());
|
|
114
|
+
}
|
|
115
|
+
const text = await request.text();
|
|
116
|
+
if (text.length > MAX_PUBLISH_CHARS) return respond(PUBLISH_TOO_LARGE());
|
|
117
|
+
/** @type {unknown} */
|
|
118
|
+
let body;
|
|
119
|
+
try {
|
|
120
|
+
body = JSON.parse(text);
|
|
121
|
+
} catch {
|
|
122
|
+
return respond(badRequest());
|
|
123
|
+
}
|
|
124
|
+
return respond(await postPublish(repo, user, body, { maxPublishFiles: config.maxPublishFiles }));
|
|
125
|
+
}
|
|
126
|
+
return respond(NOT_FOUND());
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* @param {Request} request
|
|
131
|
+
* @param {AdminDeps} deps
|
|
132
|
+
* @returns {Promise<Response>}
|
|
133
|
+
*/
|
|
134
|
+
export async function handleAdminRequest(request, deps) {
|
|
135
|
+
const { env, config, signIn, log } = deps;
|
|
136
|
+
const { pathname } = new URL(request.url);
|
|
137
|
+
const name = pathname.startsWith(PREFIX) ? pathname.slice(PREFIX.length) : "";
|
|
138
|
+
try {
|
|
139
|
+
// 1. Anything that can change something must come from the editor's origin.
|
|
140
|
+
const crossSite = crossSiteFailure(request);
|
|
141
|
+
if (crossSite) {
|
|
142
|
+
// Neither is secret: the site's own origin and the header the browser sent.
|
|
143
|
+
const sent = request.headers.get("Origin");
|
|
144
|
+
log(`admin: cross-site request refused: origin ${new URL(request.url).origin}, `
|
|
145
|
+
+ `Origin header ${sent === null ? "(none)" : JSON.stringify(sent)}`);
|
|
146
|
+
return respond(crossSite);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// 2. Local mode: no sign-in, the working tree. isLocalMode is true only
|
|
150
|
+
// when ADMIN_LOCAL is "1", NODE_ENV is not "production" (a missing
|
|
151
|
+
// NODE_ENV counts as not production) and VERCEL is unset. Then the
|
|
152
|
+
// request's address and its Host header, when it has one, must both name
|
|
153
|
+
// this computer; otherwise it is refused rather than falling through to
|
|
154
|
+
// sign-in. The address alone is not enough: next dev builds it from the
|
|
155
|
+
// address it listens on, not from the request. The Host check stops
|
|
156
|
+
// another machine's browser and DNS rebinding. It does not stop a script
|
|
157
|
+
// on the same network that forges the header, so local mode is safe only
|
|
158
|
+
// with the dev server listening on this computer alone (next dev -H
|
|
159
|
+
// 127.0.0.1), and ADMIN_LOCAL must never be set on a deployed host.
|
|
160
|
+
if (deps.local && isLocalMode(env)) {
|
|
161
|
+
if (!askedOfThisComputer(request)) return respond(NOT_THIS_COMPUTER());
|
|
162
|
+
return await route(request, name, deps.local.repo, deps.local.user, config);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// 3. Configuration.
|
|
166
|
+
const problems = signIn.problems(env, config);
|
|
167
|
+
if (problems.length > 0) {
|
|
168
|
+
// The settings' names only, never a value.
|
|
169
|
+
log(`admin: not configured: ${problems.join(", ")}`);
|
|
170
|
+
return respond(notConfigured());
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// 4. The sign-in's own routes, which need no sign-in.
|
|
174
|
+
/** @type {SignInContext} */
|
|
175
|
+
const ctx = { env, config, now: deps.now, log };
|
|
176
|
+
const answer = await signIn.route(request, name, ctx);
|
|
177
|
+
if (answer) return answer;
|
|
178
|
+
|
|
179
|
+
// 5. A signed-in, listed address: the provider checks both, and refuses
|
|
180
|
+
// with SignInRefused. Any other error is answered as one (step 7). This
|
|
181
|
+
// fails closed: an address that is not one, or a refusal that is not
|
|
182
|
+
// 401 or 403, is a fault in the provider and never reaches a route.
|
|
183
|
+
/** @type {unknown} */
|
|
184
|
+
let user;
|
|
185
|
+
try {
|
|
186
|
+
user = await signIn.user(request, ctx);
|
|
187
|
+
} catch (err) {
|
|
188
|
+
if (!(err instanceof SignInRefused)) throw err;
|
|
189
|
+
if (err.status !== 401 && err.status !== 403) {
|
|
190
|
+
throw new Error(`sign-in provider fault: refused with status ${Number(err.status)}`);
|
|
191
|
+
}
|
|
192
|
+
return respond(failure(err.status, err.code, err.message));
|
|
193
|
+
}
|
|
194
|
+
if (typeof user !== "string" || user === "") {
|
|
195
|
+
// Never the value itself: it could be anything.
|
|
196
|
+
throw new Error("sign-in provider fault: user() gave no address");
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// 6. The route.
|
|
200
|
+
return await route(request, name, deps.repoFor(signIn.github(env)), user, config);
|
|
201
|
+
} catch (err) {
|
|
202
|
+
// 7. Fixed words; the detail goes only to the log.
|
|
203
|
+
log(failureLine(`${request.method} ${name || "(none)"}`, err));
|
|
204
|
+
const code = /** @type {{ code?: unknown } | null} */ (err)?.code;
|
|
205
|
+
return respond(code === "upstream" ? UPSTREAM() : SERVER_ERROR());
|
|
206
|
+
}
|
|
207
|
+
}
|
package/server/github.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// GitHub storage adapter behind the Repo interface. Runs in Workers and Node.
|
|
2
|
+
import { checkChanges } from "./changes.js";
|
|
3
|
+
|
|
4
|
+
const API = "https://api.github.com";
|
|
5
|
+
const JSON_MEDIA = "application/vnd.github+json";
|
|
6
|
+
// A blob in this form is the file's own bytes, not JSON with base64 in it.
|
|
7
|
+
const RAW_MEDIA = "application/vnd.github.raw+json";
|
|
8
|
+
// Refuses bytes that are not UTF-8 rather than putting U+FFFD in their place.
|
|
9
|
+
const UTF8 = new TextDecoder("utf-8", { fatal: true });
|
|
10
|
+
|
|
11
|
+
export class RepoMoved extends Error {
|
|
12
|
+
constructor(message = "The branch moved since it was read") {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "RepoMoved";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function upstream(message, status) {
|
|
19
|
+
const err = new Error(message);
|
|
20
|
+
err.code = "upstream";
|
|
21
|
+
if (status !== undefined) err.status = status;
|
|
22
|
+
return err;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const encodePath = (path) => path.split("/").map(encodeURIComponent).join("/");
|
|
26
|
+
|
|
27
|
+
/** identity: { name, email } sent as author and committer, or null to send
|
|
28
|
+
* neither (GitHub then records the token's owner). userAgent: the site's
|
|
29
|
+
* own name for its requests (config.commit). */
|
|
30
|
+
export function createGithubRepo({ token, repo, branch, fetch, identity = null, userAgent }) {
|
|
31
|
+
if (typeof userAgent !== "string" || userAgent === "") {
|
|
32
|
+
throw new TypeError("createGithubRepo needs a userAgent");
|
|
33
|
+
}
|
|
34
|
+
const who = identity ? { author: identity, committer: identity } : {};
|
|
35
|
+
const base = `${API}/repos/${repo}`;
|
|
36
|
+
const ref = `heads/${encodePath(branch)}`;
|
|
37
|
+
const treeShas = new Map(); // commit sha -> tree sha
|
|
38
|
+
|
|
39
|
+
// The response, asking for the media type given.
|
|
40
|
+
async function send(method, path, payload, accept = JSON_MEDIA) {
|
|
41
|
+
try {
|
|
42
|
+
return await fetch(`${base}/${path}`, {
|
|
43
|
+
method,
|
|
44
|
+
headers: {
|
|
45
|
+
Authorization: `Bearer ${token}`,
|
|
46
|
+
"User-Agent": userAgent,
|
|
47
|
+
Accept: accept,
|
|
48
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
49
|
+
...(payload === undefined ? {} : { "Content-Type": "application/json" }),
|
|
50
|
+
},
|
|
51
|
+
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
|
52
|
+
});
|
|
53
|
+
} catch {
|
|
54
|
+
throw upstream("Could not reach GitHub");
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Returns {status, body}. Statuses in `tolerate` are returned, others throw.
|
|
59
|
+
async function call(method, path, payload, tolerate = []) {
|
|
60
|
+
const res = await send(method, path, payload);
|
|
61
|
+
if (tolerate.includes(res.status)) return { status: res.status, body: null };
|
|
62
|
+
if (!res.ok) throw upstream(`GitHub answered ${res.status}`, res.status);
|
|
63
|
+
let body;
|
|
64
|
+
try {
|
|
65
|
+
body = await res.json();
|
|
66
|
+
} catch {
|
|
67
|
+
throw upstream("GitHub sent a reply that is not JSON", res.status);
|
|
68
|
+
}
|
|
69
|
+
return { status: res.status, body };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function need(value, what) {
|
|
73
|
+
if (typeof value !== "string" || !value) throw upstream(`GitHub reply is missing ${what}`);
|
|
74
|
+
return value;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function head() {
|
|
78
|
+
const { body: refBody } = await call("GET", `git/ref/${ref}`);
|
|
79
|
+
const commit = need(refBody?.object?.sha, "the branch commit");
|
|
80
|
+
const { body } = await call("GET", `git/trees/${commit}?recursive=1`);
|
|
81
|
+
if (body?.truncated === true) throw upstream("GitHub returned a partial file tree");
|
|
82
|
+
if (!Array.isArray(body?.tree)) throw upstream("GitHub reply is missing the file tree");
|
|
83
|
+
treeShas.set(commit, need(body.sha, "the tree sha"));
|
|
84
|
+
const files = new Map();
|
|
85
|
+
for (const e of body.tree) if (e.type === "blob") files.set(e.path, e.sha);
|
|
86
|
+
return { commit, files };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The file with this blob sha, as text. Asked for raw, so the bytes are
|
|
90
|
+
* decoded once, natively: this runs on every load and every publish. */
|
|
91
|
+
async function readText(sha) {
|
|
92
|
+
const res = await send("GET", `git/blobs/${sha}`, undefined, RAW_MEDIA);
|
|
93
|
+
if (!res.ok) throw upstream(`GitHub answered ${res.status}`, res.status);
|
|
94
|
+
let bytes;
|
|
95
|
+
try {
|
|
96
|
+
bytes = await res.arrayBuffer();
|
|
97
|
+
} catch {
|
|
98
|
+
throw upstream("GitHub's reply could not be read", res.status);
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
return UTF8.decode(bytes);
|
|
102
|
+
} catch {
|
|
103
|
+
throw upstream("GitHub sent a file that is not UTF-8 text");
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function createBlob(base64) {
|
|
108
|
+
const { body } = await call("POST", "git/blobs", { content: base64, encoding: "base64" });
|
|
109
|
+
return need(body?.sha, "the blob sha");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function treeEntry(change) {
|
|
113
|
+
const entry = { path: change.path, mode: "100644", type: "blob" };
|
|
114
|
+
if (change.remove) return { ...entry, sha: null };
|
|
115
|
+
if (typeof change.text === "string") return { ...entry, content: change.text };
|
|
116
|
+
return { ...entry, sha: change.sha };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function commit({ parent, changes, message }) {
|
|
120
|
+
checkChanges(changes);
|
|
121
|
+
let baseTree = treeShas.get(parent);
|
|
122
|
+
if (!baseTree) {
|
|
123
|
+
const { body } = await call("GET", `git/commits/${parent}`);
|
|
124
|
+
baseTree = need(body?.tree?.sha, "the parent tree");
|
|
125
|
+
}
|
|
126
|
+
const { body: tree } = await call("POST", "git/trees", {
|
|
127
|
+
base_tree: baseTree,
|
|
128
|
+
tree: changes.map(treeEntry),
|
|
129
|
+
});
|
|
130
|
+
const { body: made } = await call("POST", "git/commits", {
|
|
131
|
+
message,
|
|
132
|
+
tree: need(tree?.sha, "the new tree sha"),
|
|
133
|
+
parents: [parent],
|
|
134
|
+
...who,
|
|
135
|
+
});
|
|
136
|
+
const sha = need(made?.sha, "the new commit sha");
|
|
137
|
+
const { status } = await call("PATCH", `git/refs/${ref}`, { sha, force: false }, [409, 422]);
|
|
138
|
+
if (status === 409 || status === 422) throw new RepoMoved();
|
|
139
|
+
return sha;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function contains(ancestor, descendant) {
|
|
143
|
+
const { status, body } = await call("GET", `compare/${ancestor}...${descendant}`, undefined, [404]);
|
|
144
|
+
if (status === 404) return false;
|
|
145
|
+
return body?.status === "ahead" || body?.status === "identical";
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return { head, readText, createBlob, commit, contains };
|
|
149
|
+
}
|