@superintern/sites 0.0.0-stage → 0.2.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.
@@ -0,0 +1,377 @@
1
+ // The site API, as the `sites` command uses it.
2
+ //
3
+ // Every address and shape the command relies on is in this one file, and
4
+ // follows the service's own description of its API. Change them here.
5
+
6
+ export class ApiError extends Error {
7
+ /**
8
+ * @param {string} message the API's own sentence, written for a person
9
+ * @param {{ status: number, code: string, body?: any }} detail
10
+ */
11
+ constructor(message, detail) {
12
+ super(message);
13
+ this.name = "ApiError";
14
+ this.status = detail.status;
15
+ /** What code branches on. */
16
+ this.code = detail.code;
17
+ this.body = detail.body;
18
+ }
19
+ }
20
+
21
+ /**
22
+ * @typedef {object} Site
23
+ * @property {string} id
24
+ * @property {string} slug
25
+ * @property {string} [name]
26
+ * @property {"draft" | "live" | "offline" | "suspended"} state
27
+ * @property {string} [url]
28
+ * @property {Array<{ hostname: string, kind: string, state: string }>} [domains]
29
+ * @property {Version | null} [live_version]
30
+ * @property {{ url?: string, ready?: boolean }} [git] where its files are, and whether they are there yet
31
+ */
32
+
33
+ /**
34
+ * @typedef {object} Version
35
+ * @property {string} id
36
+ * @property {number} number
37
+ * @property {string} commit_sha
38
+ * @property {"pending" | "ready" | "rejected" | "failed"} state
39
+ * @property {boolean} [is_live]
40
+ * @property {string} [created_at]
41
+ * @property {string | null} [published_at]
42
+ * @property {{ decision?: string, findings?: Array<{ code: string, severity: string, path?: string, message: string }> }} [gate]
43
+ */
44
+
45
+ /**
46
+ * @typedef {object} Build
47
+ * @property {string} id
48
+ * @property {string} commit_sha
49
+ * @property {"queued" | "running" | "succeeded" | "failed"} state
50
+ * @property {string} [created_at]
51
+ * @property {string} [started_at]
52
+ * @property {string} [finished_at]
53
+ * @property {string} [version_id]
54
+ * @property {{ step?: string, message?: string, log_tail?: string }} [failure]
55
+ */
56
+
57
+ /**
58
+ * A short-lived pass to read what one site's business made public in its CRM.
59
+ * @typedef {object} DataPass
60
+ * @property {string} url where to read, always on the site API
61
+ * @property {string} token `sdat_…`; lasts about two hours
62
+ * @property {string | null} expires_at
63
+ */
64
+
65
+ /**
66
+ * @typedef {object} CrmColumn
67
+ * @property {string} key
68
+ * @property {string} [label]
69
+ * @property {string} [type]
70
+ * @property {string} [unit]
71
+ * @property {unknown[]} [options]
72
+ * @property {string} [result]
73
+ * @property {string} [description]
74
+ */
75
+
76
+ /**
77
+ * @typedef {object} CrmTable
78
+ * @property {string} [id]
79
+ * @property {string} name
80
+ * @property {string} [slug]
81
+ * @property {number} [row_count]
82
+ * @property {string} [updated]
83
+ * @property {CrmColumn[]} [columns]
84
+ * @property {string} [item_noun]
85
+ * @property {string} [description]
86
+ */
87
+
88
+ /**
89
+ * @typedef {object} CrmRow
90
+ * @property {string} [id]
91
+ * @property {string} [slug]
92
+ * @property {string} [name]
93
+ * @property {Record<string, unknown>} [fields]
94
+ * @property {string} [updated]
95
+ */
96
+
97
+ /**
98
+ * Text from the service, safe to print inside one line: control characters
99
+ * removed, and a line break turned into a space.
100
+ * @param {unknown} text
101
+ */
102
+ export function printable(text) {
103
+ return String(text)
104
+ .replace(/[\r\n]+/g, " ")
105
+ // eslint-disable-next-line no-control-regex
106
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "");
107
+ }
108
+
109
+ /** The same for a log of several lines: its line breaks are kept. @param {unknown} text */
110
+ export function printableLines(text) {
111
+ return String(text)
112
+ .split(/\r?\n/)
113
+ .map(printable)
114
+ .join("\n");
115
+ }
116
+
117
+ /**
118
+ * Whether a word from the service can be one part of an address: never
119
+ * empty, never `.` or `..`, and nothing that would start another part.
120
+ * @param {unknown} word
121
+ * @returns {word is string}
122
+ */
123
+ export function pathWord(word) {
124
+ return typeof word === "string" && /^[\w.~-]+$/.test(word) && word !== "." && word !== "..";
125
+ }
126
+
127
+ /**
128
+ * One call. `bearer` goes to `url` and nowhere else.
129
+ * @param {typeof fetch} doFetch
130
+ * @param {string} url
131
+ * @param {{ method: string, bearer: string, json?: unknown }} options
132
+ * @returns {Promise<any>}
133
+ */
134
+ async function send(doFetch, url, { method, bearer, json }) {
135
+ /** @type {Record<string, string>} */
136
+ const headers = { Authorization: `Bearer ${bearer}`, Accept: "application/json" };
137
+ /** @type {string | undefined} */
138
+ let body;
139
+ if (json !== undefined) {
140
+ headers["Content-Type"] = "application/json";
141
+ body = JSON.stringify(json);
142
+ }
143
+
144
+ /** @type {Response} */
145
+ let response;
146
+ try {
147
+ // A redirect could carry the key to another address: never follow one.
148
+ response = await doFetch(url, { method, headers, body, redirect: "manual" });
149
+ } catch {
150
+ throw new ApiError(`${new URL(url).host} could not be reached. Check your connection and try again.`, {
151
+ status: 0,
152
+ code: "unreachable",
153
+ });
154
+ }
155
+
156
+ const text = await response.text();
157
+ /** @type {any} */
158
+ let data = null;
159
+ try {
160
+ data = text === "" ? null : JSON.parse(text);
161
+ } catch {
162
+ // not JSON: an error page from in front of the API
163
+ }
164
+ if (response.ok && data !== null) return data;
165
+
166
+ const error = data?.error;
167
+ throw new ApiError(
168
+ typeof error?.message === "string" && error.message !== ""
169
+ ? printable(error.message)
170
+ : `The service answered ${response.status}. Try again in a moment.`,
171
+ { status: response.status, code: typeof error?.code === "string" ? error.code : `http_${response.status}`, body: data },
172
+ );
173
+ }
174
+
175
+ /**
176
+ * @param {{ base: string, key: string, fetch?: typeof fetch }} options
177
+ */
178
+ export function createApi({ base, key, fetch: doFetch = fetch }) {
179
+ /**
180
+ * A website key (scope sites.read or sites.write). The same key is the git address's password.
181
+ * @param {string} method @param {string} path @param {unknown} [json]
182
+ * @returns {Promise<any>}
183
+ */
184
+ const call = (method, path, json) => send(doFetch, `${base}/sites/v1${path}`, { method, bearer: key, json });
185
+
186
+ /** Where a site's CRM data is read when the service names no address of its own. */
187
+ const dataBase = `${base}/sites/v1/data`;
188
+
189
+ return {
190
+ /**
191
+ * Whose key this is, which agents it works on, and whether it may change
192
+ * anything (`can_write`) or only read.
193
+ * @returns {Promise<{ key?: { name?: string, prefix?: string, can_write?: boolean }, agents: Array<{ id: string, name?: string }> }>}
194
+ */
195
+ async me() {
196
+ const data = await call("GET", "/me");
197
+ return { key: data.key, agents: Array.isArray(data.agents) ? data.agents : [] };
198
+ },
199
+
200
+ /**
201
+ * Sites the key may see. A key names its own agent, so none is needed.
202
+ * @param {{ agentId?: string }} [options]
203
+ * @returns {Promise<Site[]>}
204
+ */
205
+ async listSites(options = {}) {
206
+ const query = options.agentId ? `?agent_id=${encodeURIComponent(options.agentId)}` : "";
207
+ return (await call("GET", `/sites${query}`)).sites ?? [];
208
+ },
209
+
210
+ /**
211
+ * One site by its slug, or null.
212
+ * @param {string} slug
213
+ * @returns {Promise<Site | null>}
214
+ */
215
+ async findSite(slug) {
216
+ const sites = (await call("GET", `/sites?slug=${encodeURIComponent(slug)}`)).sites ?? [];
217
+ // Never trust the filter alone: a server that ignores it returns every site.
218
+ return sites.find((/** @type {Site} */ site) => site.slug === slug) ?? null;
219
+ },
220
+
221
+ /**
222
+ * The site belongs to the key's own business: no agent is named.
223
+ * @param {{ slug: string, name?: string }} input
224
+ * @returns {Promise<Site>}
225
+ */
226
+ async createSite(input) {
227
+ return (await call("POST", "/sites", { slug: input.slug, name: input.name })).site;
228
+ },
229
+
230
+ /**
231
+ * Finish making a site's repository, for a site whose `git.ready` is
232
+ * false. Refusals: `repository_in_progress` (wait), `repository_failed`
233
+ * (try again), `repository_unavailable`.
234
+ * @param {string} id @returns {Promise<Site>}
235
+ */
236
+ async prepareRepository(id) {
237
+ return (await call("POST", `/sites/${encodeURIComponent(id)}/repository`)).site;
238
+ },
239
+
240
+ /** @param {string} id @returns {Promise<Site>} */
241
+ async getSite(id) {
242
+ return (await call("GET", `/sites/${encodeURIComponent(id)}`)).site;
243
+ },
244
+
245
+ /**
246
+ * Newest first.
247
+ * @param {string} id @param {{ limit?: number }} [options]
248
+ * @returns {Promise<Version[]>}
249
+ */
250
+ async versions(id, options = {}) {
251
+ return (await call("GET", `/sites/${encodeURIComponent(id)}/versions?limit=${options.limit ?? 20}`)).versions ?? [];
252
+ },
253
+
254
+ /**
255
+ * Newest first; null when the service has no build information.
256
+ * @param {string} id @param {{ limit?: number }} [options]
257
+ * @returns {Promise<Build[] | null>}
258
+ */
259
+ async builds(id, options = {}) {
260
+ try {
261
+ return (await call("GET", `/sites/${encodeURIComponent(id)}/builds?limit=${options.limit ?? 10}`)).builds ?? [];
262
+ } catch (error) {
263
+ // The site was found a moment ago, so "not found" here is the route.
264
+ if (error instanceof ApiError && error.status === 404) return null;
265
+ throw error;
266
+ }
267
+ },
268
+
269
+ /**
270
+ * Serve a version; the newest ready one when none is named.
271
+ * Needs a key that may change sites.
272
+ * @param {string} id @param {string} [versionId]
273
+ * @returns {Promise<Site>}
274
+ */
275
+ async publish(id, versionId) {
276
+ return (await call("POST", `/sites/${encodeURIComponent(id)}/publish`, versionId ? { version_id: versionId } : {})).site;
277
+ },
278
+
279
+ /** @param {string} id @returns {Promise<Site>} */
280
+ async unpublish(id) {
281
+ return (await call("POST", `/sites/${encodeURIComponent(id)}/unpublish`, {})).site;
282
+ },
283
+
284
+ /**
285
+ * Remove a site for good. The service asks for its slug again, as the
286
+ * person typed it, so an id from the wrong place removes nothing.
287
+ * Needs a key that may change sites.
288
+ * @param {string} id @param {string} slug
289
+ * @returns {Promise<RemovedSite>}
290
+ */
291
+ async removeSite(id, slug) {
292
+ return (await call("POST", `/sites/${encodeURIComponent(id)}/remove`, { confirm: slug })).site;
293
+ },
294
+
295
+ /**
296
+ * Whether customers may sign in to the site, and how: `{enabled,
297
+ * passwords, providers: {google: {enabled, available}, microsoft: …}}`.
298
+ * A key that may only look is enough.
299
+ * @param {string} id @returns {Promise<SignInSwitches>}
300
+ */
301
+ async signInSwitches(id) {
302
+ return call("GET", `/sites/${encodeURIComponent(id)}/customers/sign-in`);
303
+ },
304
+
305
+ /**
306
+ * Switch customer sign-in: only what is sent changes (`enabled`,
307
+ * `passwords`, `google`, `microsoft`, each true or false). Needs a key that
308
+ * may change sites.
309
+ * @param {string} id @param {Partial<Record<"enabled" | "passwords" | "google" | "microsoft", boolean>>} changes
310
+ * @returns {Promise<SignInSwitches>}
311
+ */
312
+ async switchSignIn(id, changes) {
313
+ return call("POST", `/sites/${encodeURIComponent(id)}/customers/sign-in`, changes);
314
+ },
315
+
316
+ /**
317
+ * A pass to read what this site's business made public in its CRM. A key
318
+ * that may only look (`sites.read`) is enough.
319
+ * @param {string} id @returns {Promise<DataPass>}
320
+ */
321
+ async dataPass(id) {
322
+ const data = await call("POST", `/sites/${encodeURIComponent(id)}/data-token`);
323
+ const token = data?.token;
324
+ if (typeof token !== "string" || !/^[\x21-\x7e]{8,4096}$/.test(token)) {
325
+ throw new ApiError("The service's answer held no pass to read the CRM. Try again in a moment.", { status: 200, code: "no_token" });
326
+ }
327
+ // The pass is only ever sent to, and handed on with, an address on the
328
+ // site API itself: one the service names elsewhere is not used.
329
+ const named = typeof data.url === "string" ? data.url.replace(/\/+$/, "") : "";
330
+ const ours = named === dataBase || (named.startsWith(`${base}/`) && /^[\w./~-]+$/.test(named.slice(base.length)) && !named.includes(".."));
331
+ return { url: ours ? named : dataBase, token, expires_at: typeof data.expires_at === "string" ? printable(data.expires_at).trim() : null };
332
+ },
333
+
334
+ /**
335
+ * Read with a pass from dataPass(). The replies are returned as they came.
336
+ * @param {DataPass} pass
337
+ */
338
+ data(pass) {
339
+ /** @param {string} path @returns {Promise<any>} */
340
+ const read = (path) => send(doFetch, `${pass.url}${path}`, { method: "GET", bearer: pass.token });
341
+ return {
342
+ /** @returns {Promise<{ tables?: CrmTable[] }>} */
343
+ tables: () => read("/tables"),
344
+ /**
345
+ * A table is asked for by its id, from tables(): a name can hold a
346
+ * `/`, which no address can carry as one part.
347
+ * @param {string} tableId
348
+ * @param {{ limit?: number }} [options]
349
+ * @returns {Promise<{ table?: CrmTable, rows?: CrmRow[], total?: number, next_cursor?: string | null }>}
350
+ */
351
+ async rows(tableId, options = {}) {
352
+ if (!pathWord(tableId)) throw new Error("That is not a table's id, so nothing was asked for.");
353
+ return read(`/tables/${tableId}/rows?limit=${options.limit ?? 5}`);
354
+ },
355
+ };
356
+ },
357
+ };
358
+ }
359
+
360
+ /**
361
+ * What the service says about a site it has removed.
362
+ * @typedef {object} RemovedSite
363
+ * @property {string} id
364
+ * @property {string} slug
365
+ * @property {boolean} removal_finished false while its address or files are still being cleared away
366
+ * @property {string | null} name_free_for_others_at when another business may take its name
367
+ */
368
+
369
+ /**
370
+ * Customer sign-in on a site.
371
+ * @typedef {object} SignInSwitches
372
+ * @property {boolean} enabled customers may sign in, with a code by email
373
+ * @property {boolean} passwords they may also choose a password
374
+ * @property {Record<string, { enabled?: boolean, available?: boolean }>} [providers] Google and Microsoft
375
+ */
376
+
377
+ /** @typedef {ReturnType<typeof createApi>} Api */