@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,1331 @@
1
+ // What each `sites` command does. Everything it touches (the API, the key
2
+ // store, git, the screen, the clock) is handed in, so the tests run the real
3
+ // commands against a stand-in.
4
+
5
+ import { resolve } from "node:path";
6
+
7
+ import { ApiError, pathWord, printable, printableLines } from "./api.mjs";
8
+ import { environmentOfGitUrl, gitUrl, slugOfGitUrl } from "./environments.mjs";
9
+ import { answerCredentialRequest, cloneSite, DATA_HELPER_SETTING, dataHelperCommand, ensureIdentity, GitError, helperCommand, linkClone, STARTER_REMOTE } from "./git.mjs";
10
+ import { checkedKey } from "./keys.mjs";
11
+ import { nameProblem } from "./names.mjs";
12
+ import { NotInteractive } from "./prompt.mjs";
13
+
14
+ /** The starter's name at the git address: readable with any working key, never writable. */
15
+ const STARTER_SLUG = "site-starter";
16
+
17
+ /** How many rows `sites rows` shows unless told, and the most it shows. */
18
+ const ROWS_SHOWN = 5;
19
+ const ROWS_MOST = 50;
20
+
21
+ /** A field's value is shown up to this many characters; `--json` has all of it. */
22
+ const VALUE_SHOWN = 200;
23
+
24
+ /** An error the person can act on. Shown as one line, with no stack. */
25
+ export class CliError extends Error {
26
+ /** @param {string} message @param {number} [exitCode] */
27
+ constructor(message, exitCode = 1) {
28
+ super(message);
29
+ this.name = "CliError";
30
+ this.exitCode = exitCode;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * @typedef {object} Context
36
+ * @property {import("./environments.mjs").CliEnvironment} environment
37
+ * @property {import("./keys.mjs").KeyStore} keys
38
+ * @property {(key: string) => import("./api.mjs").Api} api
39
+ * @property {import("./git.mjs").GitRunner} git
40
+ * @property {(line?: string) => void} out what was asked for
41
+ * @property {(line?: string) => void} note everything else (progress, hints)
42
+ * @property {string} cwd
43
+ * @property {{ node: string, script: string }} self how git can run this command again
44
+ * @property {() => Promise<string>} readSecret
45
+ * @property {(question: string) => Promise<string>} ask one line the person types; rejects with `NotInteractive` when nobody can
46
+ * @property {(url: string) => Promise<void>} openUrl
47
+ * @property {(ms: number) => Promise<void>} sleep
48
+ * @property {() => number} now
49
+ */
50
+
51
+ // ---------------------------------------------------------------- keys
52
+
53
+ /**
54
+ * Save a key for this environment, after checking that it works.
55
+ * @param {Context} ctx @param {{ check?: boolean }} [options]
56
+ */
57
+ export async function login(ctx, options = {}) {
58
+ const key = checkedKey(await ctx.readSecret());
59
+
60
+ if (options.check !== false) {
61
+ const api = tidied(ctx.api(key));
62
+ /** @type {Array<{ id: string, name?: string }> | null} */
63
+ let agents = null;
64
+ let readOnly = false;
65
+ try {
66
+ const me = await api.me();
67
+ agents = me.agents;
68
+ readOnly = me.key?.can_write === false;
69
+ } catch (error) {
70
+ if (!(error instanceof ApiError)) throw error;
71
+ if (error.code === "not_authenticated" || error.status === 401) {
72
+ throw new CliError("That key was not accepted. Nothing was saved.");
73
+ }
74
+ if (error.status !== 404) throw new CliError(`The key could not be checked: ${error.message} Nothing was saved.`);
75
+ // No such call on this service: fall back to asking for the sites.
76
+ try {
77
+ await api.listSites();
78
+ } catch (second) {
79
+ if (second instanceof ApiError && (second.code === "not_authenticated" || second.status === 401)) {
80
+ throw new CliError("That key was not accepted. Nothing was saved.");
81
+ }
82
+ throw new CliError(
83
+ `The key could not be checked: hosted sites are not available on ${ctx.environment.name} for this key yet. ` +
84
+ "Nothing was saved. To save it without the check, run: sites login --no-check",
85
+ );
86
+ }
87
+ }
88
+ await ctx.keys.set(ctx.environment.name, key);
89
+ ctx.out(`Key saved in ${ctx.keys.where}, for ${ctx.environment.name}.`);
90
+ if (agents && agents.length > 0) {
91
+ const names = agents.map((agent) => agent.name || agent.id).join(", ");
92
+ ctx.out(
93
+ readOnly
94
+ ? `It can look at the sites of ${names}, and fetch their files. It cannot make a site or push changes: that needs a key that may change sites.`
95
+ : `It can make sites for: ${names}.`,
96
+ );
97
+ }
98
+ return 0;
99
+ }
100
+
101
+ await ctx.keys.set(ctx.environment.name, key);
102
+ ctx.out(`Key saved in ${ctx.keys.where}, for ${ctx.environment.name}. It was not checked.`);
103
+ return 0;
104
+ }
105
+
106
+ /** @param {Context} ctx */
107
+ export async function logout(ctx) {
108
+ const removed = await ctx.keys.remove(ctx.environment.name);
109
+ ctx.out(removed ? `The key for ${ctx.environment.name} was removed from ${ctx.keys.where}.` : `There was no key saved for ${ctx.environment.name}.`);
110
+ return 0;
111
+ }
112
+
113
+ /**
114
+ * Git's request for the key (see git.mjs). Prints the answer and nothing else.
115
+ * @param {Context} ctx @param {string} action @param {string} input
116
+ */
117
+ export async function gitCredential(ctx, action, input) {
118
+ // Only ask the key store when git wants a key; "store" and "erase" need none.
119
+ const key = action === "get" ? await ctx.keys.get(ctx.environment.name).catch(() => null) : null;
120
+ const answer = answerCredentialRequest({ action, input, gitBase: ctx.environment.git, key });
121
+ if (answer) process.stdout.write(answer);
122
+ return 0;
123
+ }
124
+
125
+ // ---------------------------------------------------------------- sites
126
+
127
+ /**
128
+ * Make a site and bring its files to this computer.
129
+ * @param {Context} ctx @param {string} slugArg @param {{ name?: string, dir?: string }} options
130
+ */
131
+ export async function newSite(ctx, slugArg, options) {
132
+ const slug = checkedSlug(ctx, slugArg);
133
+ const name = (options.name ?? "").trim();
134
+ if (name === "") throw new CliError('Say what the business is called: sites new <slug> --name "Business name"');
135
+ const dir = resolve(ctx.cwd, options.dir ?? slug);
136
+ const api = await signedIn(ctx);
137
+
138
+ /** @type {import("./api.mjs").Site} */
139
+ let site;
140
+ try {
141
+ site = await api.createSite({ slug, name });
142
+ } catch (error) {
143
+ throw friendly(error, slug);
144
+ }
145
+ ctx.note(`Made the site "${site.name ?? printable(name)}" (${slug}).`);
146
+
147
+ site = await waitUntilCloneable(ctx, api, site, `The site was made, but its files are not ready yet. In a minute, run: sites clone ${slug}`);
148
+ try {
149
+ await clone(ctx, site, dir);
150
+ } catch (error) {
151
+ if (!(error instanceof GitError)) throw error;
152
+ throw new CliError(`The site was made, but its files could not be brought here: ${error.message}\nTo try again: sites clone ${slug}`);
153
+ }
154
+
155
+ ctx.out(`${slug} is ready to work on in ${dir}`);
156
+ ctx.out("");
157
+ ctx.out("Next:");
158
+ ctx.out(` cd ${shown(ctx, dir)}`);
159
+ ctx.out(" npm install --ignore-scripts");
160
+ ctx.out(" npm run dev # work on the site at http://localhost:4321");
161
+ ctx.out(" sites tables # what the business's CRM lets the site show");
162
+ ctx.out(" npm run check # before every push");
163
+ ctx.out(" git push # sends your work; it does not change the live site");
164
+ ctx.out(` sites status ${slug} --wait # wait for the push to be built`);
165
+ ctx.out(` sites publish ${slug} # put the built version online`);
166
+ return 0;
167
+ }
168
+
169
+ /**
170
+ * Bring an existing site's files to this computer.
171
+ * @param {Context} ctx @param {string} slugArg @param {{ dir?: string }} options
172
+ */
173
+ export async function cloneExisting(ctx, slugArg, options) {
174
+ const slug = checkedSlug(ctx, slugArg);
175
+ const dir = resolve(ctx.cwd, options.dir ?? slug);
176
+ const api = await signedIn(ctx);
177
+ const site = await waitUntilCloneable(ctx, api, await findSite(ctx, api, slug), `The files of ${slug} are not ready yet. Try again in a minute: sites clone ${slug}`);
178
+ try {
179
+ await clone(ctx, site, dir);
180
+ } catch (error) {
181
+ if (error instanceof GitError) throw new CliError(error.message);
182
+ throw error;
183
+ }
184
+ ctx.out(`${slug} is in ${dir}`);
185
+ return 0;
186
+ }
187
+
188
+ /** @param {Context} ctx @param {{ json?: boolean }} [options] */
189
+ export async function list(ctx, options = {}) {
190
+ const api = await signedIn(ctx);
191
+ /** @type {import("./api.mjs").Site[]} */
192
+ let sites;
193
+ try {
194
+ sites = await api.listSites();
195
+ } catch (error) {
196
+ throw friendly(error);
197
+ }
198
+ if (options.json) {
199
+ ctx.out(jsonText({ environment: ctx.environment.name, sites }, 2));
200
+ return 0;
201
+ }
202
+ if (sites.length === 0) {
203
+ ctx.out(`No sites yet on ${ctx.environment.name}. Make one with: sites new <slug> --name "Business name"`);
204
+ return 0;
205
+ }
206
+ const rows = sites.map((site) => [site.slug, site.state, addressOf(site) ?? "", site.live_version ? `version ${site.live_version.number}` : "nothing published"]);
207
+ for (const line of table([["SITE", "STATE", "ADDRESS", "SERVING"], ...rows])) ctx.out(line);
208
+ return 0;
209
+ }
210
+
211
+ /**
212
+ * A site's state, its builds and its versions; with `wait`, until the build
213
+ * of one commit has finished. The site is the one named, or, with no name,
214
+ * the one whose folder this is.
215
+ * @param {Context} ctx @param {string | undefined} slugArg
216
+ * @param {{ json?: boolean, wait?: boolean, commit?: string, timeoutSeconds?: number }} [options]
217
+ */
218
+ export async function status(ctx, slugArg, options = {}) {
219
+ const slug = await siteSlug(ctx, [slugArg], "sites status <slug>");
220
+ const api = await signedIn(ctx);
221
+ const site = await findSite(ctx, api, slug);
222
+
223
+ if (options.wait) return waitForBuild(ctx, api, site, options);
224
+
225
+ const [versions, builds] = await Promise.all([api.versions(site.id, { limit: 10 }), api.builds(site.id, { limit: 5 })]).catch((error) => {
226
+ throw friendly(error, slug);
227
+ });
228
+ if (options.json) {
229
+ ctx.out(jsonText({ environment: ctx.environment.name, site, builds, versions }, 2));
230
+ return 0;
231
+ }
232
+
233
+ ctx.out(`${site.slug} ${site.state} ${addressOf(site) ?? ""}`);
234
+ ctx.out(describeState(site));
235
+
236
+ const latestBuild = builds?.[0];
237
+ if (latestBuild) {
238
+ ctx.out("");
239
+ ctx.out(`Latest build: ${describeBuild(latestBuild)}`);
240
+ for (const line of failureLines(latestBuild)) ctx.out(` ${line}`);
241
+ }
242
+
243
+ ctx.out("");
244
+ if (versions.length === 0) {
245
+ ctx.out("No versions yet. A version appears after a push has been built.");
246
+ } else {
247
+ ctx.out("Versions (newest first)");
248
+ for (const version of versions) {
249
+ ctx.out(` ${String(version.number).padStart(3)} ${version.state.padEnd(8)} ${short(version.commit_sha)} ${when(version.created_at)}${version.is_live ? " live" : ""}`);
250
+ for (const finding of problems(version)) ctx.out(` ${finding}`);
251
+ }
252
+ }
253
+
254
+ const head = await localHead(ctx, slug);
255
+ if (head && !versions.some((version) => version.commit_sha === head.commit)) {
256
+ ctx.out("");
257
+ ctx.out(
258
+ head.pushed
259
+ ? `Your latest commit here (${short(head.commit)}) has no version yet. If you just pushed, wait for it: sites status ${slug} --wait`
260
+ : `Your latest commit here (${short(head.commit)}) has not been pushed. Send it with: git push`,
261
+ );
262
+ }
263
+ if ((await siteHere(ctx))?.slug === slug && !(await hasDataHelper(ctx))) {
264
+ ctx.out("");
265
+ ctx.out("This folder is not set up for the site's build to read the business's CRM (it has no sites.datahelper). Set it up with: sites link");
266
+ }
267
+ return 0;
268
+ }
269
+
270
+ /**
271
+ * Put a built version online.
272
+ * @param {Context} ctx @param {string} slugArg @param {{ version?: string }} [options]
273
+ */
274
+ export async function publish(ctx, slugArg, options = {}) {
275
+ const slug = checkedSlug(ctx, slugArg);
276
+ const api = await signedIn(ctx);
277
+ const site = await findSite(ctx, api, slug);
278
+
279
+ /** @type {import("./api.mjs").Version[]} */
280
+ let versions;
281
+ try {
282
+ versions = await api.versions(site.id, { limit: 100 });
283
+ } catch (error) {
284
+ throw friendly(error, slug);
285
+ }
286
+
287
+ /** @type {string | undefined} */
288
+ let versionId;
289
+ if (options.version !== undefined) {
290
+ const number = Number(options.version);
291
+ const chosen = Number.isInteger(number) ? versions.find((version) => version.number === number) : undefined;
292
+ if (!chosen) throw new CliError(`${slug} has no version ${options.version}. See them with: sites status ${slug}`);
293
+ if (chosen.state !== "ready") {
294
+ throw new CliError([`Version ${chosen.number} cannot be published: it is ${chosen.state}.`, ...problems(chosen).map((line) => ` ${line}`)].join("\n"));
295
+ }
296
+ versionId = chosen.id;
297
+ } else if (!versions.some((version) => version.state === "ready")) {
298
+ throw new CliError(
299
+ versions.length === 0
300
+ ? `${slug} has nothing to publish yet. Push your work, then wait for it to be built: sites status ${slug} --wait`
301
+ : [`${slug} has no version that passed its checks.`, ...problems(versions[0]).map((line) => ` ${line}`), `Fix what is listed, push again, then: sites status ${slug} --wait`].join("\n"),
302
+ );
303
+ }
304
+
305
+ /** @type {import("./api.mjs").Site} */
306
+ let live;
307
+ try {
308
+ live = await api.publish(site.id, versionId);
309
+ } catch (error) {
310
+ throw (await keyMayNot(api, error, "put a site online")) ?? friendly(error, slug);
311
+ }
312
+
313
+ const served = live.live_version ?? versions.find((version) => version.id === versionId) ?? versions.find((version) => version.state === "ready");
314
+ ctx.out(`Published${served ? ` version ${served.number} (commit ${short(served.commit_sha)})` : ""} at ${addressOf(live) ?? addressOf(site) ?? slug}`);
315
+ ctx.out("It can take up to a minute to show everywhere.");
316
+
317
+ const newest = versions[0];
318
+ // A higher number that is ready belongs to an older push built side by side: nothing to say.
319
+ if (served && newest && newest.number > served.number && newest.state !== "ready" && versionId === undefined) {
320
+ ctx.note(`Version ${newest.number} is newer but is ${newest.state}, so it was not published. See why: sites status ${slug}`);
321
+ }
322
+ const head = await localHead(ctx, slug);
323
+ if (head && served && head.commit !== served.commit_sha) {
324
+ ctx.note(
325
+ head.pushed
326
+ ? `Your latest commit here (${short(head.commit)}) is not the one now online. If it was pushed a moment ago, wait for its build: sites status ${slug} --wait`
327
+ : `Your latest commit here (${short(head.commit)}) has not been pushed, so it is not online.`,
328
+ );
329
+ }
330
+ return 0;
331
+ }
332
+
333
+ /** @param {Context} ctx @param {string} slugArg */
334
+ export async function unpublish(ctx, slugArg) {
335
+ const slug = checkedSlug(ctx, slugArg);
336
+ const api = await signedIn(ctx);
337
+ const site = await findSite(ctx, api, slug);
338
+ try {
339
+ await api.unpublish(site.id);
340
+ } catch (error) {
341
+ if (error instanceof ApiError && error.code === "not_published") {
342
+ ctx.out(`${slug} is not online, so there was nothing to take offline.`);
343
+ return 0;
344
+ }
345
+ throw (await keyMayNot(api, error, "take a site offline")) ?? friendly(error, slug);
346
+ }
347
+ ctx.out(`${slug} is offline. Visitors see "This site is offline". Its versions are kept; bring it back with: sites publish ${slug}`);
348
+ ctx.out("It can take up to a minute to show everywhere.");
349
+ return 0;
350
+ }
351
+
352
+ /**
353
+ * Remove a site for good, once the person has typed its name (or passed
354
+ * `--yes`, for a script).
355
+ * @param {Context} ctx @param {string} slugArg @param {{ yes?: boolean }} [options]
356
+ */
357
+ export async function remove(ctx, slugArg, options = {}) {
358
+ const slug = checkedSlug(ctx, slugArg);
359
+ const api = await signedIn(ctx);
360
+ const site = await findSite(ctx, api, slug);
361
+
362
+ if (!options.yes) {
363
+ const address = addressOf(site);
364
+ ctx.note(`This removes ${slug} for good: ${address ? `${address} stops showing it at once, and it` : "it"} can't be published again.`);
365
+ ctx.note(`Its files are kept. Your business can use the name ${slug} again straight away.`);
366
+ let typed;
367
+ try {
368
+ typed = await ctx.ask(`Type ${slug} to remove it: `);
369
+ } catch (error) {
370
+ if (error instanceof NotInteractive) {
371
+ throw new CliError(`Nothing was removed. To remove ${slug} from a script, add --yes.`, 2);
372
+ }
373
+ throw error;
374
+ }
375
+ if (typed.trim().toLowerCase() !== slug) {
376
+ throw new CliError(`That isn't ${slug}, so nothing was removed.`);
377
+ }
378
+ }
379
+
380
+ /** @type {import("./api.mjs").RemovedSite} */
381
+ let removed;
382
+ try {
383
+ removed = await api.removeSite(site.id, slug);
384
+ } catch (error) {
385
+ throw (await keyMayNot(api, error, "remove a site")) ?? friendly(error, slug);
386
+ }
387
+ ctx.out(`${slug} has been removed, and no longer counts towards your sites.`);
388
+ if (removed?.removal_finished === false) {
389
+ ctx.note("Its address may take a little longer to stop answering. That finishes by itself.");
390
+ }
391
+ const free = when(removed?.name_free_for_others_at);
392
+ ctx.note(
393
+ `Your business can make a new site called ${slug} now${free ? `; anyone else could take the name from ${free}` : ""}. A copy of its files on this computer is not touched.`,
394
+ );
395
+ return 0;
396
+ }
397
+
398
+ /** @param {Context} ctx @param {string} slugArg */
399
+ export async function open(ctx, slugArg) {
400
+ const slug = checkedSlug(ctx, slugArg);
401
+ const site = await findSite(ctx, await signedIn(ctx), slug);
402
+ const address = addressOf(site);
403
+ if (!address) throw new CliError(`${slug} has no address yet.`);
404
+ if (site.state !== "live") ctx.note(`${slug} is ${site.state}, so the address will not show the site. Put it online with: sites publish ${slug}`);
405
+ ctx.out(address);
406
+ await ctx.openUrl(address);
407
+ return 0;
408
+ }
409
+
410
+ // ---------------------------------------------------------------- the business's CRM
411
+
412
+ /**
413
+ * What the site may show: the tables its business made public in its CRM.
414
+ * @param {Context} ctx @param {string | undefined} slugArg @param {{ json?: boolean, site?: string }} [options]
415
+ */
416
+ export async function tables(ctx, slugArg, options = {}) {
417
+ const slug = await siteSlug(ctx, [slugArg, options.site], "sites tables <slug>");
418
+ const data = await crmData(ctx, slug);
419
+ const reply = await readTables(ctx, data, slug);
420
+ if (options.json) {
421
+ ctx.out(jsonText(reply, 2));
422
+ return 0;
423
+ }
424
+
425
+ const found = Array.isArray(reply?.tables) ? reply.tables : [];
426
+ if (found.length === 0) {
427
+ for (const line of NO_TABLES(slug)) ctx.out(line);
428
+ return 0;
429
+ }
430
+
431
+ ctx.out(`${slug} may show ${found.length === 1 ? "1 table" : `${found.length} tables`} from the business's CRM.`);
432
+ for (const one of found) {
433
+ ctx.out("");
434
+ ctx.out([oneLine(one.name), typeof one.row_count === "number" ? items(one.row_count) : "", when(one.updated) ? `changed ${when(one.updated)}` : ""].filter(Boolean).join(" "));
435
+ if (one.description) ctx.out(` ${oneLine(one.description)}`);
436
+ const columns = (Array.isArray(one.columns) ? one.columns : []).map((column) => [
437
+ ` ${oneLine(column.key)}`,
438
+ oneLine(column.type ?? ""),
439
+ JSON.stringify(oneLine(column.label ?? column.key)),
440
+ columnNotes(column),
441
+ ]);
442
+ for (const line of table(columns)) ctx.out(line);
443
+ }
444
+
445
+ const asked = named([slugArg, options.site]) ? ` ${slug}` : "";
446
+ const example = found.map((one) => wordFor(found, one)).find((word) => word !== null);
447
+ if (example) {
448
+ ctx.out("");
449
+ ctx.out(`See real values before you write a page: sites rows ${shellWord(example)}${asked}`);
450
+ }
451
+ ctx.out("");
452
+ ctx.out("To show a table on the site, add its line under crmTables in src/site.config.ts, then read it in a data page (one with export const prerender = false):");
453
+ const lists = listNames(found);
454
+ found.forEach((one, index) => {
455
+ const list = lists[index] ?? "table";
456
+ if (index > 0) ctx.out("");
457
+ ctx.out(` ${/^[a-z][a-z0-9_]*$/.test(list) ? list : JSON.stringify(list)}: ${JSON.stringify(oneLine(one.name))},`);
458
+ ctx.out(` await loadRows(Astro, ${JSON.stringify(list)})`);
459
+ });
460
+ return 0;
461
+ }
462
+
463
+ /**
464
+ * The first rows of one table, so real values can be seen before a page is written.
465
+ * @param {Context} ctx @param {string | undefined} tableArg @param {string | undefined} slugArg
466
+ * @param {{ json?: boolean, limit?: string | number, site?: string }} [options]
467
+ */
468
+ export async function rows(ctx, tableArg, slugArg, options = {}) {
469
+ const wanted = String(tableArg ?? "").trim();
470
+ if (wanted === "") throw new CliError("Which table? For example: sites rows Events. See the tables with: sites tables");
471
+ const limit = rowLimit(ctx, options.limit);
472
+ const slug = await siteSlug(ctx, [slugArg, options.site], "sites rows <table> <slug>");
473
+ const data = await crmData(ctx, slug);
474
+
475
+ // The table is looked up in the list and asked for by its id: what was
476
+ // typed (a name can hold a "/", or be "..") never becomes part of an address.
477
+ const listing = await readTables(ctx, data, slug);
478
+ const found = Array.isArray(listing?.tables) ? listing.tables : [];
479
+ const one = findTable(found, wanted);
480
+ const asked = named([slugArg, options.site]) ? ` ${slug}` : "";
481
+ if (!one) {
482
+ throw new CliError(
483
+ found.length === 0
484
+ ? NO_TABLES(slug).join("\n")
485
+ : `"${oneLine(wanted)}" is not a table this site may show. It may show: ${found.map((each) => oneLine(each.name)).join(", ")}.\nSee them with their columns: sites tables${asked}`,
486
+ );
487
+ }
488
+ const id = one.id;
489
+ if (!pathWord(id)) throw new CliError(`The service gave "${oneLine(one.name)}" no id to ask for it by. That is the service's problem, not the site's: stop and report it.`);
490
+
491
+ /** @type {{ table?: import("./api.mjs").CrmTable, rows?: import("./api.mjs").CrmRow[], total?: number, next_cursor?: string | null }} */
492
+ let reply;
493
+ try {
494
+ reply = await askAgain(ctx, () => data.rows(id, { limit }));
495
+ } catch (error) {
496
+ throw dataProblem(ctx, error, slug, "rows");
497
+ }
498
+ if (options.json) {
499
+ ctx.out(jsonText(reply, 2));
500
+ return 0;
501
+ }
502
+
503
+ const name = oneLine(reply?.table?.name ?? one.name);
504
+ const shownRows = (Array.isArray(reply?.rows) ? reply.rows : []).slice(0, limit);
505
+ if (shownRows.length === 0) {
506
+ ctx.out(`"${name}" has no items the site may show yet.`);
507
+ ctx.out("To change that, the owner opens the table in SuperIntern and makes the items to show public.");
508
+ return 0;
509
+ }
510
+ const total = typeof reply.total === "number" ? reply.total : reply.table?.row_count;
511
+ const more = typeof total === "number" ? total > shownRows.length : Boolean(reply.next_cursor);
512
+ ctx.out(`${name}: ${typeof total === "number" ? `${items(total)}, ` : ""}${more ? `the first ${shownRows.length}` : "all shown"}`);
513
+
514
+ // Fields in the order of the table's columns, then any the reply did not describe.
515
+ const described = reply.table?.columns ?? one.columns;
516
+ const order = (Array.isArray(described) ? described : []).map((column) => column.key);
517
+ for (const row of shownRows) {
518
+ const fields = row.fields && typeof row.fields === "object" ? row.fields : {};
519
+ const keys = [...order.filter((key) => Object.hasOwn(fields, key)), ...Object.keys(fields).filter((key) => !order.includes(key))];
520
+ ctx.out("");
521
+ ctx.out(`${oneLine(row.name ?? "") || "(no name)"}${row.slug ? ` slug: ${oneLine(row.slug)}` : ""}`);
522
+ for (const line of table(keys.map((key) => [` ${oneLine(key)}`, shownValue(fields[key])]))) ctx.out(line);
523
+ }
524
+ if (more && limit < ROWS_MOST) {
525
+ ctx.out("");
526
+ ctx.out(`For more, add --limit <n> (at most ${ROWS_MOST}).`);
527
+ }
528
+ return 0;
529
+ }
530
+
531
+ /** The switches `sites accounts` takes, as the service names them. */
532
+ const SIGN_IN_FLAGS = /** @type {const} */ ([
533
+ ["signIn", "enabled", "Customer accounts"],
534
+ ["passwords", "passwords", "Passwords"],
535
+ ["google", "google", "Google"],
536
+ ["microsoft", "microsoft", "Microsoft"],
537
+ ]);
538
+
539
+ /**
540
+ * Show whether customers may sign in to the site, and switch it: customer
541
+ * accounts (a code by email), passwords, Google and Microsoft. Only what is
542
+ * given changes. The same switches as the website's Settings tab.
543
+ * @param {Context} ctx @param {string | undefined} slugArg
544
+ * @param {{ signIn?: string, passwords?: string, google?: string, microsoft?: string, json?: boolean }} [options]
545
+ */
546
+ export async function accounts(ctx, slugArg, options = {}) {
547
+ /** @type {Record<string, boolean>} */
548
+ const changes = {};
549
+ for (const [option, name, label] of SIGN_IN_FLAGS) {
550
+ const value = options[option];
551
+ if (value === undefined) continue;
552
+ const word = String(value).trim().toLowerCase();
553
+ if (word !== "on" && word !== "off") {
554
+ throw new CliError(`${label}: say on or off, as in --${option === "signIn" ? "sign-in" : option} on.`);
555
+ }
556
+ changes[name] = word === "on";
557
+ }
558
+ const slug = await siteSlug(ctx, [slugArg], "sites accounts <slug>");
559
+ const api = await signedIn(ctx);
560
+ const site = await findSite(ctx, api, slug);
561
+ let state;
562
+ try {
563
+ state = Object.keys(changes).length ? await api.switchSignIn(site.id, changes) : await api.signInSwitches(site.id);
564
+ } catch (error) {
565
+ if (error instanceof ApiError && error.status === 403 && error.code === "read_only") {
566
+ throw new CliError("Your key can only look at websites. Make one that can change websites (Website, Keys), then: sites login", 3);
567
+ }
568
+ if (error instanceof ApiError && (error.status === 403 || (error.status === 404 && error.code !== "not_found"))) {
569
+ throw new CliError(
570
+ `This service doesn't let a key switch customer accounts yet. Switch them in SuperIntern: the website's Settings tab, Customer accounts. Nothing was changed.`,
571
+ 3,
572
+ );
573
+ }
574
+ throw (await keyMayNot(api, error, "switch customer accounts")) ?? friendly(error, slug);
575
+ }
576
+ if (options.json) {
577
+ ctx.out(jsonText(state, 2));
578
+ return 0;
579
+ }
580
+ const word = (/** @type {unknown} */ on) => (on ? "on" : "off");
581
+ const providers = state?.providers ?? {};
582
+ ctx.out(`Customer accounts on ${slug}: ${word(state?.enabled)}`);
583
+ ctx.out(` Passwords: ${word(state?.passwords)}`);
584
+ for (const [name, label] of /** @type {const} */ ([["google", "Google"], ["microsoft", "Microsoft"]])) {
585
+ const provider = providers[name] ?? {};
586
+ ctx.out(` ${`${label}:`.padEnd(11)} ${word(provider.enabled)}${provider.available === false ? " (not available yet)" : ""}`);
587
+ }
588
+ if (state?.enabled) {
589
+ ctx.out(`Customers sign in at ${addressOf(site)}/sign-in. Everyone who signs in is added to your People.`);
590
+ } else {
591
+ ctx.out(`Switch them on with: sites accounts ${slug} --sign-in on --passwords on`);
592
+ }
593
+ return 0;
594
+ }
595
+
596
+ /**
597
+ * What a site's build calls to read the CRM on a person's computer: one line
598
+ * of JSON, `{"url", "token", "expires_at"}`, and nothing else. The build
599
+ * finds this command in the clone's `sites.datahelper` setting.
600
+ *
601
+ * This is the one command that prints a credential, and the website key is
602
+ * still never printed. The difference is what each can do. The pass printed
603
+ * here ends by itself in about two hours and reads only what the business
604
+ * already made public for its site to show; it cannot change anything, make,
605
+ * push or publish a site, or read the rest of the CRM. The website key does
606
+ * not end and can do all of that to every site of the business, so it stays
607
+ * in the key store and is only ever sent to the service.
608
+ *
609
+ * @param {Context} ctx @param {{ site?: string, slug?: string }} [options]
610
+ */
611
+ export async function dataToken(ctx, options = {}) {
612
+ const slug = await siteSlug(ctx, [options.slug, options.site], "sites data-token --site <slug>");
613
+ const { pass } = await crmPass(ctx, slug);
614
+ // Nothing has been printed before this line, and nothing follows it.
615
+ ctx.out(jsonText({ url: pass.url, token: pass.token, expires_at: pass.expires_at }));
616
+ return 0;
617
+ }
618
+
619
+ /**
620
+ * Inside a site's folder: set, or set again, the two lines that tie the
621
+ * clone to this copy of the command. Needs no key and calls no service.
622
+ * @param {Context} ctx
623
+ */
624
+ export async function link(ctx) {
625
+ const here = await siteHere(ctx);
626
+ if (!here) throw new CliError("This is not a site's folder. Run `sites link` inside a folder made by `sites new` or `sites clone`.");
627
+ if (!here.slug) throw new CliError(elsewhere(here.environment));
628
+ const identity = { node: ctx.self.node, script: ctx.self.script, environment: ctx.environment.name };
629
+ try {
630
+ await linkClone({
631
+ git: ctx.git,
632
+ dir: ctx.cwd,
633
+ gitBase: ctx.environment.git,
634
+ helper: helperCommand(identity),
635
+ dataHelper: dataHelperCommand({ ...identity, slug: here.slug }),
636
+ });
637
+ } catch (error) {
638
+ if (error instanceof GitError) throw new CliError("This folder's git settings could not be changed. What git said is above.");
639
+ throw error;
640
+ }
641
+ ctx.out(`${here.slug} (${ctx.environment.name}) now uses this copy of sites: ${ctx.self.script}`);
642
+ ctx.out(" git push asks it for your key.");
643
+ ctx.out(" The site's build asks it for a short pass to read the business's public CRM tables.");
644
+ ctx.out("Nothing outside this folder's .git/config was changed, and no key was written.");
645
+ return 0;
646
+ }
647
+
648
+ /**
649
+ * The site a command is about: the one named (after the command, or with
650
+ * `--site`; both is fine when they agree), or the one whose folder this is.
651
+ * @param {Context} ctx @param {Array<string | undefined>} given @param {string} usage "sites tables <slug>"
652
+ */
653
+ async function siteSlug(ctx, given, usage) {
654
+ const slugs = [...new Set(given.filter((value) => String(value ?? "").trim() !== "").map((value) => checkedSlug(ctx, value)))];
655
+ if (slugs.length > 1) throw new CliError(`Two sites were named, "${slugs[0]}" and "${slugs[1]}". Name one.`);
656
+ if (slugs[0] !== undefined) return slugs[0];
657
+ const here = await siteHere(ctx);
658
+ if (here?.slug) return here.slug;
659
+ if (here) throw new CliError(elsewhere(here.environment));
660
+ throw new CliError(`Which site? Run this inside the site's folder, or give its name: ${usage}`);
661
+ }
662
+
663
+ /** @param {Array<string | undefined>} given whether a site was named at all */
664
+ function named(given) {
665
+ return given.some((value) => String(value ?? "").trim() !== "");
666
+ }
667
+
668
+ /** @param {string} environment */
669
+ function elsewhere(environment) {
670
+ return `This folder is a site on ${environment}. Run the command again with: --env ${environment}`;
671
+ }
672
+
673
+ /**
674
+ * The site whose clone the command is run in, from the clone's `origin`
675
+ * address: its slug, or (with no slug) which other environment it is on, or
676
+ * null when this is no site's folder.
677
+ * @param {Context} ctx
678
+ * @returns {Promise<{ slug: string | null, environment: string } | null>}
679
+ */
680
+ async function siteHere(ctx) {
681
+ /** @type {string} */
682
+ let url;
683
+ try {
684
+ const origin = await ctx.git(["config", "--get", "remote.origin.url"], { cwd: ctx.cwd, quiet: true });
685
+ if (origin.code !== 0) return null;
686
+ url = origin.stdout.trim();
687
+ } catch {
688
+ return null;
689
+ }
690
+ const slug = slugOfGitUrl(ctx.environment, url);
691
+ if (slug !== null) {
692
+ try {
693
+ return { slug: checkedSlug(ctx, slug), environment: ctx.environment.name };
694
+ } catch {
695
+ return null; // the starter, or another name no site can have
696
+ }
697
+ }
698
+ const other = environmentOfGitUrl(url);
699
+ return other && other !== ctx.environment.name ? { slug: null, environment: other } : null;
700
+ }
701
+
702
+ /** @param {Context} ctx whether the clone here names a command for its build to call */
703
+ async function hasDataHelper(ctx) {
704
+ try {
705
+ const set = await ctx.git(["config", "--local", "--get", DATA_HELPER_SETTING], { cwd: ctx.cwd, quiet: true });
706
+ return set.code === 0 && set.stdout.trim() !== "";
707
+ } catch {
708
+ return false;
709
+ }
710
+ }
711
+
712
+ /**
713
+ * A pass to read the CRM of a site's business, for the saved key.
714
+ * @param {Context} ctx @param {string} slug
715
+ */
716
+ async function crmPass(ctx, slug) {
717
+ const api = await signedIn(ctx);
718
+ const site = await findSite(ctx, api, slug);
719
+ try {
720
+ return { api, pass: await api.dataPass(site.id) };
721
+ } catch (error) {
722
+ throw dataProblem(ctx, error, slug, "pass");
723
+ }
724
+ }
725
+
726
+ /** @param {Context} ctx @param {string} slug */
727
+ async function crmData(ctx, slug) {
728
+ const { api, pass } = await crmPass(ctx, slug);
729
+ return api.data(pass);
730
+ }
731
+
732
+ /**
733
+ * @param {Context} ctx @param {Awaited<ReturnType<typeof crmData>>} data @param {string} slug
734
+ * @returns {Promise<{ tables?: import("./api.mjs").CrmTable[] }>}
735
+ */
736
+ async function readTables(ctx, data, slug) {
737
+ try {
738
+ return await askAgain(ctx, () => data.tables());
739
+ } catch (error) {
740
+ throw dataProblem(ctx, error, slug, "tables");
741
+ }
742
+ }
743
+
744
+ /** How often a read that the service asks to have again (409) is sent once more. */
745
+ const ASKED_AGAIN = 3;
746
+
747
+ /**
748
+ * The service answers 409 when what it was reading changed under it, and
749
+ * means "ask again". A few tries, a moment apart; then its sentence is shown.
750
+ * @template T
751
+ * @param {Context} ctx @param {() => Promise<T>} read
752
+ * @returns {Promise<T>}
753
+ */
754
+ async function askAgain(ctx, read) {
755
+ for (let again = 0; ; again += 1) {
756
+ try {
757
+ return await read();
758
+ } catch (error) {
759
+ if (!(error instanceof ApiError) || error.status !== 409 || again >= ASKED_AGAIN) throw error;
760
+ await ctx.sleep(500 * (again + 1));
761
+ }
762
+ }
763
+ }
764
+
765
+ /**
766
+ * The table someone means: by its id, then by its name whatever the capitals,
767
+ * then by its slug.
768
+ * @param {import("./api.mjs").CrmTable[]} found @param {string} wanted
769
+ */
770
+ function findTable(found, wanted) {
771
+ const text = wanted.trim();
772
+ const same = (/** @type {unknown} */ value) => typeof value === "string" && value.trim().toLowerCase() === text.toLowerCase();
773
+ return (
774
+ found.find((one) => one.id === text) ??
775
+ found.find((one) => typeof one.name === "string" && one.name.trim() === text) ??
776
+ found.find((one) => same(one.name)) ??
777
+ found.find((one) => one.slug === text) ??
778
+ found.find((one) => same(one.slug)) ??
779
+ null
780
+ );
781
+ }
782
+
783
+ /**
784
+ * What to type after `sites rows` for a table: its name, or its slug, or its
785
+ * id, whichever is the first that can be typed as printed and finds it.
786
+ * @param {import("./api.mjs").CrmTable[]} found @param {import("./api.mjs").CrmTable} one
787
+ */
788
+ function wordFor(found, one) {
789
+ for (const word of [one.name, one.slug, one.id]) {
790
+ if (typeof word === "string" && word !== "" && oneLine(word) === word && findTable(found, word) === one) return word;
791
+ }
792
+ return null;
793
+ }
794
+
795
+ /** @param {string} slug what "no public table" means, and what the owner does about it */
796
+ const NO_TABLES = (slug) => [
797
+ `The business behind ${slug} has made no table public, so there is nothing in its CRM that this site may show yet.`,
798
+ "To change that, the owner opens the table in SuperIntern and makes it public, along with the columns and the items the site should show. Then run this again.",
799
+ ];
800
+
801
+ /**
802
+ * Turn a failure to read the CRM into a line the person can act on.
803
+ * @param {Context} ctx @param {unknown} error @param {string} slug
804
+ * @param {"pass" | "tables" | "rows"} step asking for the pass, or reading with it
805
+ * @returns {Error}
806
+ */
807
+ function dataProblem(ctx, error, slug, step) {
808
+ if (!(error instanceof ApiError)) return /** @type {Error} */ (error);
809
+ if (error.status === 429 || error.code === "rate_limited") return new CliError(`Too many requests in a short time. ${error.message}`);
810
+ if (error.status === 401) {
811
+ return step === "pass"
812
+ ? new CliError("Your key was not accepted. Save a working one with: sites login")
813
+ : // The key was accepted a moment ago, so it is not the key.
814
+ new CliError(`The service did not accept the pass it had just given to read the CRM: ${error.message} Your key is not the problem. Run the command again; if it happens twice, stop and report it.`);
815
+ }
816
+ if (error.status === 404) {
817
+ // The site was found a moment ago. For a table, the service's sentence names the public ones.
818
+ if (step === "rows" && error.code === "not_found") return new CliError(`${error.message}\nSee what the site may show with: sites tables ${slug}`);
819
+ // Anything else that is missing is the route: a service from before sites could read the CRM.
820
+ return new CliError(
821
+ `The service on ${ctx.environment.name} cannot give sites their CRM data yet. Nothing is wrong with your key or with the site, and saving the key again will not change it.`,
822
+ );
823
+ }
824
+ // The service writes its messages for a person; pass them on.
825
+ return new CliError(error.message);
826
+ }
827
+
828
+ /** @param {Context} ctx @param {string | number | undefined} value */
829
+ function rowLimit(ctx, value) {
830
+ if (value === undefined) return ROWS_SHOWN;
831
+ const number = Number(value);
832
+ if (!Number.isInteger(number) || number < 1) throw new CliError(`--limit needs a whole number from 1 to ${ROWS_MOST}.`);
833
+ if (number > ROWS_MOST) ctx.note(`Showing ${ROWS_MOST}: that is the most this command shows.`);
834
+ return Math.min(number, ROWS_MOST);
835
+ }
836
+
837
+ /**
838
+ * The name pages read each table by (`loadRows(Astro, "events")`): made from the
839
+ * table's name, or its slug when the name has no letter a list's name can
840
+ * hold (one in another script, say), or "table". No two tables in one
841
+ * listing get the same name: a second one gets a 2, a third a 3.
842
+ * @param {import("./api.mjs").CrmTable[]} found
843
+ */
844
+ function listNames(found) {
845
+ const valid = /^[a-z][a-z0-9_-]*$/;
846
+ /** @type {Set<string>} */
847
+ const taken = new Set();
848
+ return found.map((one) => {
849
+ const made = String(one.name ?? "")
850
+ .normalize("NFD")
851
+ .replace(/\p{M}+/gu, "") // "Événements" is "evenements", not "e-ve-nements"
852
+ .toLowerCase()
853
+ .replace(/[^a-z0-9]+/g, "-")
854
+ .replace(/^-+|-+$/g, "");
855
+ const slug = String(one.slug ?? "");
856
+ const base = valid.test(made) ? made : valid.test(slug) ? slug : "table";
857
+ let name = base;
858
+ for (let count = 2; taken.has(name); count += 1) name = `${base}${count}`;
859
+ taken.add(name);
860
+ return name;
861
+ });
862
+ }
863
+
864
+ /** @param {import("./api.mjs").CrmColumn} column its unit and options, when it has them */
865
+ function columnNotes(column) {
866
+ const notes = [];
867
+ if (column.unit) notes.push(`unit: ${oneLine(column.unit)}`);
868
+ if (Array.isArray(column.options) && column.options.length > 0) {
869
+ notes.push(`options: ${column.options.map((option) => oneLine(optionName(option))).join(", ")}`);
870
+ }
871
+ if (column.result) notes.push(`gives: ${oneLine(column.result)}`);
872
+ return notes.join("; ");
873
+ }
874
+
875
+ /** @param {unknown} option an option as the service sends it: a word, or an object that names it */
876
+ function optionName(option) {
877
+ if (option !== null && typeof option === "object") {
878
+ const named = /** @type {Record<string, unknown>} */ (option);
879
+ return named.label ?? named.name ?? named.value ?? named.id ?? JSON.stringify(option);
880
+ }
881
+ return option;
882
+ }
883
+
884
+ /** @param {unknown} value a field's value on one line, cut when it is long */
885
+ function shownValue(value) {
886
+ if (value === null || value === undefined || value === "") return "(empty)";
887
+ const characters = [...oneLine(typeof value === "string" ? value : JSON.stringify(value))];
888
+ if (characters.length <= VALUE_SHOWN) return characters.join("");
889
+ return `${characters.slice(0, VALUE_SHOWN).join("")}… (${characters.length} characters; --json shows all of it)`;
890
+ }
891
+
892
+ /** @param {number} count */
893
+ function items(count) {
894
+ return count === 1 ? "1 item" : `${count} items`;
895
+ }
896
+
897
+ /** Text from the service on one line: control characters removed, line breaks turned into spaces. @param {unknown} text */
898
+ function oneLine(text) {
899
+ return printable(text ?? "").replace(/\s+/g, " ").trim();
900
+ }
901
+
902
+ /**
903
+ * As one word of a command line someone can copy. In single quotes nothing
904
+ * is special to a shell (not `!`, not `$`), so only the quote itself is escaped.
905
+ * @param {string} text
906
+ */
907
+ function shellWord(text) {
908
+ return /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(text) ? text : `'${text.replaceAll("'", `'\\''`)}'`;
909
+ }
910
+
911
+ /**
912
+ * JSON that is safe to print: the few control characters JSON leaves as they
913
+ * are become escapes, which read back as the same text.
914
+ * @param {unknown} value @param {number} [indent]
915
+ */
916
+ function jsonText(value, indent) {
917
+ return JSON.stringify(value, null, indent).replace(/[\u007f-\u009f\u2028\u2029]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
918
+ }
919
+
920
+ // ---------------------------------------------------------------- waiting for a build
921
+
922
+ /**
923
+ * @param {Context} ctx @param {import("./api.mjs").Api} api @param {import("./api.mjs").Site} site
924
+ * @param {{ commit?: string, timeoutSeconds?: number }} options
925
+ */
926
+ async function waitForBuild(ctx, api, site, options) {
927
+ const slug = site.slug;
928
+ const head = options.commit ? null : await localHead(ctx, slug);
929
+ if (head && !head.pushed) {
930
+ throw new CliError(`Your latest commit here (${short(head.commit)}) has not been pushed, so nothing will build it. Send it with: git push`);
931
+ }
932
+ let commit = options.commit ?? head?.commit;
933
+ const deadline = ctx.now() + (options.timeoutSeconds ?? 900) * 1000;
934
+ let said = "";
935
+ const say = (/** @type {string} */ line) => {
936
+ if (line !== said) ctx.note(line);
937
+ said = line;
938
+ };
939
+
940
+ for (;;) {
941
+ const [versions, builds] = await Promise.all([api.versions(site.id, { limit: 20 }), api.builds(site.id, { limit: 10 })]).catch((error) => {
942
+ throw friendly(error, slug);
943
+ });
944
+
945
+ // With no commit to look for (not run inside the site's folder), follow the newest build.
946
+ commit ??= builds?.[0]?.commit_sha ?? versions[0]?.commit_sha;
947
+ const wanted = commit;
948
+ const matches = (/** @type {string} */ sha) => wanted !== undefined && (sha === wanted || sha.startsWith(wanted));
949
+
950
+ const version = versions.find((candidate) => matches(candidate.commit_sha));
951
+ if (version?.state === "ready") {
952
+ ctx.out(`Built: version ${version.number} (commit ${short(version.commit_sha)}) passed its checks and is ready.`);
953
+ ctx.out(`Put it online with: sites publish ${slug}`);
954
+ return 0;
955
+ }
956
+ if (version?.state === "rejected") {
957
+ ctx.out(`Version ${version.number} (commit ${short(version.commit_sha)}) was built but cannot be published:`);
958
+ for (const line of problems(version)) ctx.out(` ${line}`);
959
+ ctx.out("Fix what is listed, commit, push, and wait again.");
960
+ return 1;
961
+ }
962
+ if (version?.state === "failed") {
963
+ ctx.out(`Version ${version.number} (commit ${short(version.commit_sha)}) was built, but its checks could not finish. That is not a problem with the site.`);
964
+ ctx.out("Push again (an empty commit will do) to send it once more.");
965
+ return 1;
966
+ }
967
+
968
+ const build = builds?.find((candidate) => matches(candidate.commit_sha));
969
+ if (build?.state === "failed") {
970
+ ctx.out(`The build of commit ${short(build.commit_sha)} failed${whyFailed(build)}.`);
971
+ for (const line of failureLines(build)) ctx.out(` ${line}`);
972
+ ctx.out(afterFailure(build, slug));
973
+ return 1;
974
+ }
975
+
976
+ if (ctx.now() >= deadline) {
977
+ ctx.out(
978
+ wanted
979
+ ? `Commit ${short(wanted)} has still not been built. Check again later with: sites status ${slug}`
980
+ : `${slug} has no build yet. A build starts when you push.`,
981
+ );
982
+ return 2;
983
+ }
984
+ say(
985
+ !wanted
986
+ ? "Waiting for a build to start…"
987
+ : build
988
+ ? `Commit ${short(wanted)} is ${build.state === "queued" ? "waiting to be built" : "being built"}…`
989
+ : `Waiting for the build of commit ${short(wanted)} to start…`,
990
+ );
991
+ await ctx.sleep(5000);
992
+ }
993
+ }
994
+
995
+ // ---------------------------------------------------------------- helpers
996
+
997
+ /**
998
+ * @param {Context} ctx
999
+ * @returns {Promise<import("./api.mjs").Api>}
1000
+ */
1001
+ async function signedIn(ctx) {
1002
+ const key = await ctx.keys.get(ctx.environment.name);
1003
+ if (!key) throw new CliError(`No key is saved for ${ctx.environment.name}. Run: sites login${ctx.environment.name === "test" ? "" : ` --env ${ctx.environment.name}`}`);
1004
+ return tidied(ctx.api(key));
1005
+ }
1006
+
1007
+ /**
1008
+ * The API, with everything it says about sites, versions and builds made
1009
+ * safe to print: names, states, addresses and commit ids come from the
1010
+ * service, and through it from whoever named the site or pushed to it.
1011
+ * The CRM's replies are left as they came (`--json` prints them); what is
1012
+ * shown from them is cleaned where it is shown.
1013
+ * @param {import("./api.mjs").Api} api
1014
+ * @returns {import("./api.mjs").Api}
1015
+ */
1016
+ function tidied(api) {
1017
+ const clean = (/** @type {(...args: any[]) => Promise<unknown>} */ call) => async (/** @type {any[]} */ ...args) => tidy(await call(...args));
1018
+ return /** @type {import("./api.mjs").Api} */ ({
1019
+ ...Object.fromEntries(Object.entries(api).map(([name, call]) => [name, clean(/** @type {any} */ (call))])),
1020
+ dataPass: api.dataPass,
1021
+ data: api.data,
1022
+ });
1023
+ }
1024
+
1025
+ /**
1026
+ * Every piece of text in a reply made printable. A build's own output
1027
+ * (`failure`) keeps its line breaks; everything else is one line.
1028
+ * @param {unknown} value @param {boolean} [lines]
1029
+ * @returns {unknown}
1030
+ */
1031
+ function tidy(value, lines = false) {
1032
+ if (typeof value === "string") return lines ? printableLines(value) : printable(value).trim();
1033
+ if (Array.isArray(value)) return value.map((each) => tidy(each, lines));
1034
+ if (value !== null && typeof value === "object") {
1035
+ return Object.fromEntries(Object.entries(value).map(([name, each]) => [name, tidy(each, lines || name === "failure")]));
1036
+ }
1037
+ return value;
1038
+ }
1039
+
1040
+ /**
1041
+ * A slug that could be a site on this environment. The service has the last
1042
+ * word (it reserves more names); this only catches what can never work.
1043
+ * @param {Context} ctx @param {string | undefined} value
1044
+ */
1045
+ function checkedSlug(ctx, value) {
1046
+ const slug = String(value ?? "").trim().toLowerCase();
1047
+ if (slug === "") throw new CliError("Which site? Give its name, for example: sites status my-shop");
1048
+ if (!/^[a-z0-9](?:[a-z0-9]|-(?!-)){1,38}[a-z0-9]$/.test(slug)) {
1049
+ throw new CliError(`"${value}" cannot be a site's name. Use 3 to 40 lowercase letters, digits and single hyphens, starting and ending with a letter or digit.`);
1050
+ }
1051
+ const problem = nameProblem(slug, ctx.environment.name, ctx.environment.sitesDomain);
1052
+ if (problem) throw new CliError(`"${slug}" cannot be a site's name: ${problem}.`);
1053
+ return slug;
1054
+ }
1055
+
1056
+ /**
1057
+ * @param {Context} ctx @param {import("./api.mjs").Api} api @param {string} slug
1058
+ * @returns {Promise<import("./api.mjs").Site>}
1059
+ */
1060
+ async function findSite(ctx, api, slug) {
1061
+ /** @type {import("./api.mjs").Site | null} */
1062
+ let site;
1063
+ try {
1064
+ site = await api.findSite(slug);
1065
+ } catch (error) {
1066
+ // The list of sites is missing only while hosted sites are switched off: that is not about this site.
1067
+ throw friendly(error, error instanceof ApiError && error.status === 404 ? undefined : slug);
1068
+ }
1069
+ if (!site) throw new CliError(`There is no site called "${slug}" on ${ctx.environment.name} that your key can use. See yours with: sites list`);
1070
+ return site;
1071
+ }
1072
+
1073
+ /**
1074
+ * A site's files are copied in from the starter when it is made. When they
1075
+ * are not there yet, ask the service to finish, and wait until they are.
1076
+ * @param {Context} ctx @param {import("./api.mjs").Api} api @param {import("./api.mjs").Site} site
1077
+ * @param {string} notReady what to say when they are still not there after a minute
1078
+ */
1079
+ async function waitUntilCloneable(ctx, api, site, notReady) {
1080
+ let current = site;
1081
+ const deadline = ctx.now() + 60_000;
1082
+ let said = false;
1083
+ while (current.git?.ready === false) {
1084
+ if (ctx.now() >= deadline) throw new CliError(notReady);
1085
+ if (!said) ctx.note("Getting the site's files ready…");
1086
+ said = true;
1087
+ try {
1088
+ current = await api.prepareRepository(site.id);
1089
+ } catch (error) {
1090
+ const code = error instanceof ApiError ? error.code : "";
1091
+ // Being made right now, or the attempt failed and may be made again: both pass.
1092
+ if (code !== "repository_in_progress" && code !== "repository_failed") {
1093
+ throw new CliError(`${notReady}\n(${friendly(error, site.slug).message})`);
1094
+ }
1095
+ await ctx.sleep(3000);
1096
+ current = code === "repository_in_progress" ? await api.getSite(site.id) : current;
1097
+ }
1098
+ }
1099
+ return current;
1100
+ }
1101
+ /**
1102
+ * @param {Context} ctx @param {import("./api.mjs").Site} site @param {string} dir
1103
+ */
1104
+ async function clone(ctx, site, dir) {
1105
+ // The site's name goes into an address and into a command line the build
1106
+ // runs: one from the service is held to the same rule as one typed.
1107
+ /** @type {string} */
1108
+ let slug;
1109
+ try {
1110
+ slug = checkedSlug(ctx, site.slug);
1111
+ } catch {
1112
+ throw new CliError(`The service named this site "${printable(site.slug)}", which cannot be a site's name. Nothing was brought here.`);
1113
+ }
1114
+ const ours = gitUrl(ctx.environment, slug);
1115
+ // Use the address the service gives only when it is on our own git address.
1116
+ const url = site.git?.url && site.git.url.startsWith(`${ctx.environment.git}/`) ? site.git.url : ours;
1117
+ await cloneSite({
1118
+ git: ctx.git,
1119
+ url,
1120
+ gitBase: ctx.environment.git,
1121
+ dir,
1122
+ helper: helperCommand({ node: ctx.self.node, script: ctx.self.script, environment: ctx.environment.name }),
1123
+ dataHelper: dataHelperCommand({ node: ctx.self.node, script: ctx.self.script, environment: ctx.environment.name, slug }),
1124
+ starterUrl: gitUrl(ctx.environment, STARTER_SLUG),
1125
+ });
1126
+ ctx.note(`The remote "${STARTER_REMOTE}" is the template every site starts from, to read what it has now. Never merge it into the site: it would bring the template's sample content back (and a site made since 18 Nov 2026 shares no history with it, so git refuses). In a site built on the site kit, the platform's parts (chat, shop, sign-in, the checks) come from the kit: SuperIntern installs smaller updates itself, and a bigger one waits in the draft for the owner to publish.`);
1127
+
1128
+ // Git on this computer may not know who is committing; then it guesses (on
1129
+ // a Mac, from the account's name and the computer's network address) or, on
1130
+ // Linux, refuses to commit. Commits in this folder are then signed as the
1131
+ // business, with an address that is never delivered (".invalid").
1132
+ // Cut by characters, not UTF-16 units, so an emoji at the end is not split.
1133
+ const name = Array.from(printable(site.name ?? "").trim()).slice(0, 80).join("").trim();
1134
+ // Git refuses a name with no letter or digit in it ("<>", "."): the slug then.
1135
+ const signer = /[\p{L}\p{N}]/u.test(name) ? name : slug;
1136
+ /** @type {string[]} */
1137
+ let made;
1138
+ try {
1139
+ made = await ensureIdentity({ git: ctx.git, dir, identity: { name: signer, email: `${slug}@sites.invalid` } });
1140
+ } catch (error) {
1141
+ // The files are here; only the signature is missing, which git will say on the first commit.
1142
+ if (!(error instanceof GitError)) throw error;
1143
+ ctx.note(`Git's name and email for this folder could not be set (${error.message}). If git asks who you are when you commit, set them in this folder with git config.`);
1144
+ return;
1145
+ }
1146
+ if (made.length > 0) {
1147
+ const what = made.includes("user.name")
1148
+ ? `so commits in this folder are signed "${signer}"`
1149
+ : `so commits in this folder use the address ${slug}@sites.invalid`;
1150
+ ctx.note(
1151
+ `Git had no ${made.map((setting) => (setting === "user.name" ? "name" : "email")).join(" or ")} on this computer, ${what}. ` +
1152
+ 'To sign them as yourself, in this folder: git config user.name "<your name>" && git config user.email "<your email>"',
1153
+ );
1154
+ }
1155
+ }
1156
+
1157
+ /**
1158
+ * The latest commit of the site's clone, when the command is run inside it.
1159
+ * @param {Context} ctx @param {string} slug
1160
+ * @returns {Promise<{ commit: string, pushed: boolean } | null>}
1161
+ */
1162
+ async function localHead(ctx, slug) {
1163
+ try {
1164
+ const origin = await ctx.git(["config", "--get", "remote.origin.url"], { cwd: ctx.cwd, quiet: true });
1165
+ if (origin.code !== 0 || origin.stdout.trim() !== gitUrl(ctx.environment, slug)) return null;
1166
+ const head = await ctx.git(["rev-parse", "HEAD"], { cwd: ctx.cwd, quiet: true });
1167
+ if (head.code !== 0) return null;
1168
+ const commit = head.stdout.trim();
1169
+ // Where git last saw the site's main branch: moved by every push and fetch.
1170
+ const remote = await ctx.git(["rev-parse", "--verify", "--quiet", "refs/remotes/origin/main"], { cwd: ctx.cwd, quiet: true });
1171
+ const contained = await ctx.git(["merge-base", "--is-ancestor", commit, "refs/remotes/origin/main"], { cwd: ctx.cwd, quiet: true });
1172
+ return { commit, pushed: remote.code === 0 && contained.code === 0 };
1173
+ } catch {
1174
+ return null;
1175
+ }
1176
+ }
1177
+
1178
+ /**
1179
+ * When the service refuses a key for one action while the key itself still
1180
+ * works, say that, not "your key was not accepted": saving the key again
1181
+ * would change nothing.
1182
+ * @param {import("./api.mjs").Api} api @param {unknown} error @param {string} action "put a site online"
1183
+ * @returns {Promise<CliError | null>}
1184
+ */
1185
+ async function keyMayNot(api, error, action) {
1186
+ if (!(error instanceof ApiError) || error.status !== 401) return null;
1187
+ try {
1188
+ await api.me();
1189
+ } catch {
1190
+ return null; // the key really is not accepted: the usual message is right
1191
+ }
1192
+ return new CliError(
1193
+ `Your key works, but a key is not allowed to ${action}. For now that needs a person signed in to SuperIntern. Nothing was changed.`,
1194
+ 3,
1195
+ );
1196
+ }
1197
+
1198
+ /**
1199
+ * Turn a failure from the API into a line the person can act on.
1200
+ * @param {unknown} error @param {string} [slug]
1201
+ * @returns {Error}
1202
+ */
1203
+ function friendly(error, slug) {
1204
+ if (!(error instanceof ApiError)) return /** @type {Error} */ (error);
1205
+ switch (error.code) {
1206
+ case "not_authenticated":
1207
+ return new CliError("Your key was not accepted. Save a working one with: sites login");
1208
+ case "unreachable":
1209
+ return new CliError(error.message);
1210
+ case "not_found":
1211
+ return new CliError(slug ? `There is no site called "${slug}" that your key can use.` : "Hosted sites are not available for this key.");
1212
+ case "slug_taken":
1213
+ return new CliError(`The name "${slug}" is already taken. Choose another.`);
1214
+ case "publish_in_progress":
1215
+ return new CliError(`${slug} is already being published. Wait a minute and check: sites status ${slug}`);
1216
+ case "rate_limited":
1217
+ return new CliError(`Too many changes in a short time. ${error.message}`);
1218
+ default:
1219
+ // The service writes its messages for a person; pass them on.
1220
+ return new CliError(error.message);
1221
+ }
1222
+ }
1223
+
1224
+ /** @param {import("./api.mjs").Site} site */
1225
+ function addressOf(site) {
1226
+ if (site.url) return site.url;
1227
+ const domain = site.domains?.find((d) => d.kind === "free" && d.state === "active") ?? site.domains?.[0];
1228
+ return domain ? `https://${domain.hostname}` : null;
1229
+ }
1230
+
1231
+ /** @param {import("./api.mjs").Site} site */
1232
+ function describeState(site) {
1233
+ const live = site.live_version;
1234
+ switch (site.state) {
1235
+ case "live":
1236
+ return live ? `Online, serving version ${live.number} (commit ${short(live.commit_sha)})${live.published_at ? `, published ${when(live.published_at)}` : ""}.` : "Online.";
1237
+ case "offline":
1238
+ return `Offline: visitors see "This site is offline".${live ? ` Publishing again serves version ${live.number}.` : ""}`;
1239
+ case "suspended":
1240
+ return "Suspended by SuperIntern. It cannot be published until that is lifted.";
1241
+ default:
1242
+ return "Not published yet.";
1243
+ }
1244
+ }
1245
+
1246
+ /** @param {import("./api.mjs").Build} build */
1247
+ function describeBuild(build) {
1248
+ const what = { queued: "waiting to start", running: "running", succeeded: "finished", failed: `failed${whyFailed(build)}` }[build.state] ?? build.state;
1249
+ return `${what} (commit ${short(build.commit_sha)}${build.finished_at || build.started_at ? `, ${when(build.finished_at ?? build.started_at)}` : ""})`;
1250
+ }
1251
+
1252
+ /**
1253
+ * The reasons a build can fail for (`failure.step`), in words, and whether
1254
+ * the site's own files are what has to change.
1255
+ * @type {Record<string, { what: string, site: boolean }>}
1256
+ */
1257
+ const BUILD_FAILURES = {
1258
+ contract_failed: { what: "the site breaks one of the rules every site must keep (see CONTRACT.md)", site: true },
1259
+ install_failed: { what: "its packages could not be installed", site: true },
1260
+ build_failed: { what: "the site could not be built", site: true },
1261
+ too_large: { what: "the built site is too large", site: true },
1262
+ timeout: { what: "the build took too long", site: true },
1263
+ checks: { what: "the built site did not pass the safety checks", site: true },
1264
+ fetch_failed: { what: "the site's files could not be fetched for the build", site: false },
1265
+ invalid_env: { what: "the build was not set up correctly", site: false },
1266
+ internal_error: { what: "the build service had a problem", site: false },
1267
+ queue: { what: "the build could not be started", site: false },
1268
+ };
1269
+
1270
+ /** @param {import("./api.mjs").Build} build ": the site could not be built", or the reason as sent when it is a new one */
1271
+ function whyFailed(build) {
1272
+ const step = build.failure?.step;
1273
+ if (!step) return "";
1274
+ const known = Object.hasOwn(BUILD_FAILURES, step) ? BUILD_FAILURES[step] : undefined;
1275
+ return known ? `: ${known.what}` : ` at "${printable(step)}"`;
1276
+ }
1277
+
1278
+ /** @param {import("./api.mjs").Build} build @param {string} slug what to do about a failed build */
1279
+ function afterFailure(build, slug) {
1280
+ const step = build.failure?.step ?? "";
1281
+ const known = Object.hasOwn(BUILD_FAILURES, step) ? BUILD_FAILURES[step] : undefined;
1282
+ if (known && !known.site) {
1283
+ return `That is not a problem with the site. Send it once more: git commit --allow-empty -m "Build again" && git push. If it fails the same way, stop and report it.`;
1284
+ }
1285
+ if (step === "checks") return `Fix what is listed, commit, push, and wait again: sites status ${slug} --wait`;
1286
+ return "Run `npm run check` in the site's folder to see the same problem here, fix it, commit and push.";
1287
+ }
1288
+
1289
+ /** @param {import("./api.mjs").Build | undefined} build */
1290
+ function failureLines(build) {
1291
+ if (!build || build.state !== "failed" || !build.failure) return [];
1292
+ const lines = [];
1293
+ if (build.failure.message) lines.push(...String(build.failure.message).split("\n"));
1294
+ if (build.failure.log_tail) lines.push(...build.failure.log_tail.trimEnd().split("\n").slice(-30));
1295
+ return lines.map(printable);
1296
+ }
1297
+
1298
+ /**
1299
+ * Why a version cannot be published, in the service's own words.
1300
+ * @param {import("./api.mjs").Version | undefined} version
1301
+ */
1302
+ function problems(version) {
1303
+ if (!version || version.state === "ready") return [];
1304
+ return (version.gate?.findings ?? []).filter((finding) => finding.severity === "reject").map((finding) => printable(finding.message));
1305
+ }
1306
+
1307
+ /** @param {string | undefined} sha */
1308
+ function short(sha) {
1309
+ return (sha ?? "").slice(0, 7);
1310
+ }
1311
+
1312
+ /** @param {string | null | undefined} iso */
1313
+ function when(iso) {
1314
+ if (!iso) return "";
1315
+ const date = new Date(iso);
1316
+ if (Number.isNaN(date.getTime())) return "";
1317
+ const month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][date.getUTCMonth()];
1318
+ const two = (/** @type {number} */ n) => String(n).padStart(2, "0");
1319
+ return `${date.getUTCDate()} ${month} ${date.getUTCFullYear()} ${two(date.getUTCHours())}:${two(date.getUTCMinutes())} UTC`;
1320
+ }
1321
+
1322
+ /** @param {string[][]} rows */
1323
+ function table(rows) {
1324
+ const widths = rows[0]?.map((_, column) => Math.max(...rows.map((row) => (row[column] ?? "").length))) ?? [];
1325
+ return rows.map((row) => row.map((cell, column) => cell.padEnd(widths[column] ?? 0)).join(" ").trimEnd());
1326
+ }
1327
+
1328
+ /** @param {Context} ctx @param {string} dir */
1329
+ function shown(ctx, dir) {
1330
+ return dir.startsWith(`${ctx.cwd}/`) ? dir.slice(ctx.cwd.length + 1) : dir;
1331
+ }