@superintern/sites 0.0.0-stage → 0.1.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 +27 -0
- package/LICENSE +21 -0
- package/README.md +151 -2
- package/bin/sites.mjs +214 -0
- package/package.json +39 -4
- package/src/cli/api.mjs +348 -0
- package/src/cli/commands.mjs +1266 -0
- package/src/cli/environments.mjs +104 -0
- package/src/cli/git.mjs +258 -0
- package/src/cli/keys.mjs +137 -0
- package/src/cli/names.mjs +33 -0
- package/src/cli/package-info.mjs +22 -0
- package/src/cli/prompt.mjs +88 -0
|
@@ -0,0 +1,1266 @@
|
|
|
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 page:");
|
|
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(` getRows(${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
|
+
/**
|
|
532
|
+
* What a site's build calls to read the CRM on a person's computer: one line
|
|
533
|
+
* of JSON, `{"url", "token", "expires_at"}`, and nothing else. The build
|
|
534
|
+
* finds this command in the clone's `sites.datahelper` setting.
|
|
535
|
+
*
|
|
536
|
+
* This is the one command that prints a credential, and the website key is
|
|
537
|
+
* still never printed. The difference is what each can do. The pass printed
|
|
538
|
+
* here ends by itself in about two hours and reads only what the business
|
|
539
|
+
* already made public for its site to show; it cannot change anything, make,
|
|
540
|
+
* push or publish a site, or read the rest of the CRM. The website key does
|
|
541
|
+
* not end and can do all of that to every site of the business, so it stays
|
|
542
|
+
* in the key store and is only ever sent to the service.
|
|
543
|
+
*
|
|
544
|
+
* @param {Context} ctx @param {{ site?: string, slug?: string }} [options]
|
|
545
|
+
*/
|
|
546
|
+
export async function dataToken(ctx, options = {}) {
|
|
547
|
+
const slug = await siteSlug(ctx, [options.slug, options.site], "sites data-token --site <slug>");
|
|
548
|
+
const { pass } = await crmPass(ctx, slug);
|
|
549
|
+
// Nothing has been printed before this line, and nothing follows it.
|
|
550
|
+
ctx.out(jsonText({ url: pass.url, token: pass.token, expires_at: pass.expires_at }));
|
|
551
|
+
return 0;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* Inside a site's folder: set, or set again, the two lines that tie the
|
|
556
|
+
* clone to this copy of the command. Needs no key and calls no service.
|
|
557
|
+
* @param {Context} ctx
|
|
558
|
+
*/
|
|
559
|
+
export async function link(ctx) {
|
|
560
|
+
const here = await siteHere(ctx);
|
|
561
|
+
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`.");
|
|
562
|
+
if (!here.slug) throw new CliError(elsewhere(here.environment));
|
|
563
|
+
const identity = { node: ctx.self.node, script: ctx.self.script, environment: ctx.environment.name };
|
|
564
|
+
try {
|
|
565
|
+
await linkClone({
|
|
566
|
+
git: ctx.git,
|
|
567
|
+
dir: ctx.cwd,
|
|
568
|
+
gitBase: ctx.environment.git,
|
|
569
|
+
helper: helperCommand(identity),
|
|
570
|
+
dataHelper: dataHelperCommand({ ...identity, slug: here.slug }),
|
|
571
|
+
});
|
|
572
|
+
} catch (error) {
|
|
573
|
+
if (error instanceof GitError) throw new CliError("This folder's git settings could not be changed. What git said is above.");
|
|
574
|
+
throw error;
|
|
575
|
+
}
|
|
576
|
+
ctx.out(`${here.slug} (${ctx.environment.name}) now uses this copy of sites: ${ctx.self.script}`);
|
|
577
|
+
ctx.out(" git push asks it for your key.");
|
|
578
|
+
ctx.out(" The site's build asks it for a short pass to read the business's public CRM tables.");
|
|
579
|
+
ctx.out("Nothing outside this folder's .git/config was changed, and no key was written.");
|
|
580
|
+
return 0;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* The site a command is about: the one named (after the command, or with
|
|
585
|
+
* `--site`; both is fine when they agree), or the one whose folder this is.
|
|
586
|
+
* @param {Context} ctx @param {Array<string | undefined>} given @param {string} usage "sites tables <slug>"
|
|
587
|
+
*/
|
|
588
|
+
async function siteSlug(ctx, given, usage) {
|
|
589
|
+
const slugs = [...new Set(given.filter((value) => String(value ?? "").trim() !== "").map((value) => checkedSlug(ctx, value)))];
|
|
590
|
+
if (slugs.length > 1) throw new CliError(`Two sites were named, "${slugs[0]}" and "${slugs[1]}". Name one.`);
|
|
591
|
+
if (slugs[0] !== undefined) return slugs[0];
|
|
592
|
+
const here = await siteHere(ctx);
|
|
593
|
+
if (here?.slug) return here.slug;
|
|
594
|
+
if (here) throw new CliError(elsewhere(here.environment));
|
|
595
|
+
throw new CliError(`Which site? Run this inside the site's folder, or give its name: ${usage}`);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** @param {Array<string | undefined>} given whether a site was named at all */
|
|
599
|
+
function named(given) {
|
|
600
|
+
return given.some((value) => String(value ?? "").trim() !== "");
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** @param {string} environment */
|
|
604
|
+
function elsewhere(environment) {
|
|
605
|
+
return `This folder is a site on ${environment}. Run the command again with: --env ${environment}`;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* The site whose clone the command is run in, from the clone's `origin`
|
|
610
|
+
* address: its slug, or (with no slug) which other environment it is on, or
|
|
611
|
+
* null when this is no site's folder.
|
|
612
|
+
* @param {Context} ctx
|
|
613
|
+
* @returns {Promise<{ slug: string | null, environment: string } | null>}
|
|
614
|
+
*/
|
|
615
|
+
async function siteHere(ctx) {
|
|
616
|
+
/** @type {string} */
|
|
617
|
+
let url;
|
|
618
|
+
try {
|
|
619
|
+
const origin = await ctx.git(["config", "--get", "remote.origin.url"], { cwd: ctx.cwd, quiet: true });
|
|
620
|
+
if (origin.code !== 0) return null;
|
|
621
|
+
url = origin.stdout.trim();
|
|
622
|
+
} catch {
|
|
623
|
+
return null;
|
|
624
|
+
}
|
|
625
|
+
const slug = slugOfGitUrl(ctx.environment, url);
|
|
626
|
+
if (slug !== null) {
|
|
627
|
+
try {
|
|
628
|
+
return { slug: checkedSlug(ctx, slug), environment: ctx.environment.name };
|
|
629
|
+
} catch {
|
|
630
|
+
return null; // the starter, or another name no site can have
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
const other = environmentOfGitUrl(url);
|
|
634
|
+
return other && other !== ctx.environment.name ? { slug: null, environment: other } : null;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** @param {Context} ctx whether the clone here names a command for its build to call */
|
|
638
|
+
async function hasDataHelper(ctx) {
|
|
639
|
+
try {
|
|
640
|
+
const set = await ctx.git(["config", "--local", "--get", DATA_HELPER_SETTING], { cwd: ctx.cwd, quiet: true });
|
|
641
|
+
return set.code === 0 && set.stdout.trim() !== "";
|
|
642
|
+
} catch {
|
|
643
|
+
return false;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* A pass to read the CRM of a site's business, for the saved key.
|
|
649
|
+
* @param {Context} ctx @param {string} slug
|
|
650
|
+
*/
|
|
651
|
+
async function crmPass(ctx, slug) {
|
|
652
|
+
const api = await signedIn(ctx);
|
|
653
|
+
const site = await findSite(ctx, api, slug);
|
|
654
|
+
try {
|
|
655
|
+
return { api, pass: await api.dataPass(site.id) };
|
|
656
|
+
} catch (error) {
|
|
657
|
+
throw dataProblem(ctx, error, slug, "pass");
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/** @param {Context} ctx @param {string} slug */
|
|
662
|
+
async function crmData(ctx, slug) {
|
|
663
|
+
const { api, pass } = await crmPass(ctx, slug);
|
|
664
|
+
return api.data(pass);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/**
|
|
668
|
+
* @param {Context} ctx @param {Awaited<ReturnType<typeof crmData>>} data @param {string} slug
|
|
669
|
+
* @returns {Promise<{ tables?: import("./api.mjs").CrmTable[] }>}
|
|
670
|
+
*/
|
|
671
|
+
async function readTables(ctx, data, slug) {
|
|
672
|
+
try {
|
|
673
|
+
return await askAgain(ctx, () => data.tables());
|
|
674
|
+
} catch (error) {
|
|
675
|
+
throw dataProblem(ctx, error, slug, "tables");
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/** How often a read that the service asks to have again (409) is sent once more. */
|
|
680
|
+
const ASKED_AGAIN = 3;
|
|
681
|
+
|
|
682
|
+
/**
|
|
683
|
+
* The service answers 409 when what it was reading changed under it, and
|
|
684
|
+
* means "ask again". A few tries, a moment apart; then its sentence is shown.
|
|
685
|
+
* @template T
|
|
686
|
+
* @param {Context} ctx @param {() => Promise<T>} read
|
|
687
|
+
* @returns {Promise<T>}
|
|
688
|
+
*/
|
|
689
|
+
async function askAgain(ctx, read) {
|
|
690
|
+
for (let again = 0; ; again += 1) {
|
|
691
|
+
try {
|
|
692
|
+
return await read();
|
|
693
|
+
} catch (error) {
|
|
694
|
+
if (!(error instanceof ApiError) || error.status !== 409 || again >= ASKED_AGAIN) throw error;
|
|
695
|
+
await ctx.sleep(500 * (again + 1));
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* The table someone means: by its id, then by its name whatever the capitals,
|
|
702
|
+
* then by its slug.
|
|
703
|
+
* @param {import("./api.mjs").CrmTable[]} found @param {string} wanted
|
|
704
|
+
*/
|
|
705
|
+
function findTable(found, wanted) {
|
|
706
|
+
const text = wanted.trim();
|
|
707
|
+
const same = (/** @type {unknown} */ value) => typeof value === "string" && value.trim().toLowerCase() === text.toLowerCase();
|
|
708
|
+
return (
|
|
709
|
+
found.find((one) => one.id === text) ??
|
|
710
|
+
found.find((one) => typeof one.name === "string" && one.name.trim() === text) ??
|
|
711
|
+
found.find((one) => same(one.name)) ??
|
|
712
|
+
found.find((one) => one.slug === text) ??
|
|
713
|
+
found.find((one) => same(one.slug)) ??
|
|
714
|
+
null
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* What to type after `sites rows` for a table: its name, or its slug, or its
|
|
720
|
+
* id, whichever is the first that can be typed as printed and finds it.
|
|
721
|
+
* @param {import("./api.mjs").CrmTable[]} found @param {import("./api.mjs").CrmTable} one
|
|
722
|
+
*/
|
|
723
|
+
function wordFor(found, one) {
|
|
724
|
+
for (const word of [one.name, one.slug, one.id]) {
|
|
725
|
+
if (typeof word === "string" && word !== "" && oneLine(word) === word && findTable(found, word) === one) return word;
|
|
726
|
+
}
|
|
727
|
+
return null;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/** @param {string} slug what "no public table" means, and what the owner does about it */
|
|
731
|
+
const NO_TABLES = (slug) => [
|
|
732
|
+
`The business behind ${slug} has made no table public, so there is nothing in its CRM that this site may show yet.`,
|
|
733
|
+
"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.",
|
|
734
|
+
];
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* Turn a failure to read the CRM into a line the person can act on.
|
|
738
|
+
* @param {Context} ctx @param {unknown} error @param {string} slug
|
|
739
|
+
* @param {"pass" | "tables" | "rows"} step asking for the pass, or reading with it
|
|
740
|
+
* @returns {Error}
|
|
741
|
+
*/
|
|
742
|
+
function dataProblem(ctx, error, slug, step) {
|
|
743
|
+
if (!(error instanceof ApiError)) return /** @type {Error} */ (error);
|
|
744
|
+
if (error.status === 429 || error.code === "rate_limited") return new CliError(`Too many requests in a short time. ${error.message}`);
|
|
745
|
+
if (error.status === 401) {
|
|
746
|
+
return step === "pass"
|
|
747
|
+
? new CliError("Your key was not accepted. Save a working one with: sites login")
|
|
748
|
+
: // The key was accepted a moment ago, so it is not the key.
|
|
749
|
+
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.`);
|
|
750
|
+
}
|
|
751
|
+
if (error.status === 404) {
|
|
752
|
+
// The site was found a moment ago. For a table, the service's sentence names the public ones.
|
|
753
|
+
if (step === "rows" && error.code === "not_found") return new CliError(`${error.message}\nSee what the site may show with: sites tables ${slug}`);
|
|
754
|
+
// Anything else that is missing is the route: a service from before sites could read the CRM.
|
|
755
|
+
return new CliError(
|
|
756
|
+
`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.`,
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
// The service writes its messages for a person; pass them on.
|
|
760
|
+
return new CliError(error.message);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/** @param {Context} ctx @param {string | number | undefined} value */
|
|
764
|
+
function rowLimit(ctx, value) {
|
|
765
|
+
if (value === undefined) return ROWS_SHOWN;
|
|
766
|
+
const number = Number(value);
|
|
767
|
+
if (!Number.isInteger(number) || number < 1) throw new CliError(`--limit needs a whole number from 1 to ${ROWS_MOST}.`);
|
|
768
|
+
if (number > ROWS_MOST) ctx.note(`Showing ${ROWS_MOST}: that is the most this command shows.`);
|
|
769
|
+
return Math.min(number, ROWS_MOST);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* The name pages read each table by (`getRows("events")`): made from the
|
|
774
|
+
* table's name, or its slug when the name has no letter a list's name can
|
|
775
|
+
* hold (one in another script, say), or "table". No two tables in one
|
|
776
|
+
* listing get the same name: a second one gets a 2, a third a 3.
|
|
777
|
+
* @param {import("./api.mjs").CrmTable[]} found
|
|
778
|
+
*/
|
|
779
|
+
function listNames(found) {
|
|
780
|
+
const valid = /^[a-z][a-z0-9_-]*$/;
|
|
781
|
+
/** @type {Set<string>} */
|
|
782
|
+
const taken = new Set();
|
|
783
|
+
return found.map((one) => {
|
|
784
|
+
const made = String(one.name ?? "")
|
|
785
|
+
.normalize("NFD")
|
|
786
|
+
.replace(/\p{M}+/gu, "") // "Événements" is "evenements", not "e-ve-nements"
|
|
787
|
+
.toLowerCase()
|
|
788
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
789
|
+
.replace(/^-+|-+$/g, "");
|
|
790
|
+
const slug = String(one.slug ?? "");
|
|
791
|
+
const base = valid.test(made) ? made : valid.test(slug) ? slug : "table";
|
|
792
|
+
let name = base;
|
|
793
|
+
for (let count = 2; taken.has(name); count += 1) name = `${base}${count}`;
|
|
794
|
+
taken.add(name);
|
|
795
|
+
return name;
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** @param {import("./api.mjs").CrmColumn} column its unit and options, when it has them */
|
|
800
|
+
function columnNotes(column) {
|
|
801
|
+
const notes = [];
|
|
802
|
+
if (column.unit) notes.push(`unit: ${oneLine(column.unit)}`);
|
|
803
|
+
if (Array.isArray(column.options) && column.options.length > 0) {
|
|
804
|
+
notes.push(`options: ${column.options.map((option) => oneLine(optionName(option))).join(", ")}`);
|
|
805
|
+
}
|
|
806
|
+
if (column.result) notes.push(`gives: ${oneLine(column.result)}`);
|
|
807
|
+
return notes.join("; ");
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/** @param {unknown} option an option as the service sends it: a word, or an object that names it */
|
|
811
|
+
function optionName(option) {
|
|
812
|
+
if (option !== null && typeof option === "object") {
|
|
813
|
+
const named = /** @type {Record<string, unknown>} */ (option);
|
|
814
|
+
return named.label ?? named.name ?? named.value ?? named.id ?? JSON.stringify(option);
|
|
815
|
+
}
|
|
816
|
+
return option;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/** @param {unknown} value a field's value on one line, cut when it is long */
|
|
820
|
+
function shownValue(value) {
|
|
821
|
+
if (value === null || value === undefined || value === "") return "(empty)";
|
|
822
|
+
const characters = [...oneLine(typeof value === "string" ? value : JSON.stringify(value))];
|
|
823
|
+
if (characters.length <= VALUE_SHOWN) return characters.join("");
|
|
824
|
+
return `${characters.slice(0, VALUE_SHOWN).join("")}… (${characters.length} characters; --json shows all of it)`;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/** @param {number} count */
|
|
828
|
+
function items(count) {
|
|
829
|
+
return count === 1 ? "1 item" : `${count} items`;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/** Text from the service on one line: control characters removed, line breaks turned into spaces. @param {unknown} text */
|
|
833
|
+
function oneLine(text) {
|
|
834
|
+
return printable(text ?? "").replace(/\s+/g, " ").trim();
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/**
|
|
838
|
+
* As one word of a command line someone can copy. In single quotes nothing
|
|
839
|
+
* is special to a shell (not `!`, not `$`), so only the quote itself is escaped.
|
|
840
|
+
* @param {string} text
|
|
841
|
+
*/
|
|
842
|
+
function shellWord(text) {
|
|
843
|
+
return /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(text) ? text : `'${text.replaceAll("'", `'\\''`)}'`;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/**
|
|
847
|
+
* JSON that is safe to print: the few control characters JSON leaves as they
|
|
848
|
+
* are become escapes, which read back as the same text.
|
|
849
|
+
* @param {unknown} value @param {number} [indent]
|
|
850
|
+
*/
|
|
851
|
+
function jsonText(value, indent) {
|
|
852
|
+
return JSON.stringify(value, null, indent).replace(/[\u007f-\u009f\u2028\u2029]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
// ---------------------------------------------------------------- waiting for a build
|
|
856
|
+
|
|
857
|
+
/**
|
|
858
|
+
* @param {Context} ctx @param {import("./api.mjs").Api} api @param {import("./api.mjs").Site} site
|
|
859
|
+
* @param {{ commit?: string, timeoutSeconds?: number }} options
|
|
860
|
+
*/
|
|
861
|
+
async function waitForBuild(ctx, api, site, options) {
|
|
862
|
+
const slug = site.slug;
|
|
863
|
+
const head = options.commit ? null : await localHead(ctx, slug);
|
|
864
|
+
if (head && !head.pushed) {
|
|
865
|
+
throw new CliError(`Your latest commit here (${short(head.commit)}) has not been pushed, so nothing will build it. Send it with: git push`);
|
|
866
|
+
}
|
|
867
|
+
let commit = options.commit ?? head?.commit;
|
|
868
|
+
const deadline = ctx.now() + (options.timeoutSeconds ?? 900) * 1000;
|
|
869
|
+
let said = "";
|
|
870
|
+
const say = (/** @type {string} */ line) => {
|
|
871
|
+
if (line !== said) ctx.note(line);
|
|
872
|
+
said = line;
|
|
873
|
+
};
|
|
874
|
+
|
|
875
|
+
for (;;) {
|
|
876
|
+
const [versions, builds] = await Promise.all([api.versions(site.id, { limit: 20 }), api.builds(site.id, { limit: 10 })]).catch((error) => {
|
|
877
|
+
throw friendly(error, slug);
|
|
878
|
+
});
|
|
879
|
+
|
|
880
|
+
// With no commit to look for (not run inside the site's folder), follow the newest build.
|
|
881
|
+
commit ??= builds?.[0]?.commit_sha ?? versions[0]?.commit_sha;
|
|
882
|
+
const wanted = commit;
|
|
883
|
+
const matches = (/** @type {string} */ sha) => wanted !== undefined && (sha === wanted || sha.startsWith(wanted));
|
|
884
|
+
|
|
885
|
+
const version = versions.find((candidate) => matches(candidate.commit_sha));
|
|
886
|
+
if (version?.state === "ready") {
|
|
887
|
+
ctx.out(`Built: version ${version.number} (commit ${short(version.commit_sha)}) passed its checks and is ready.`);
|
|
888
|
+
ctx.out(`Put it online with: sites publish ${slug}`);
|
|
889
|
+
return 0;
|
|
890
|
+
}
|
|
891
|
+
if (version?.state === "rejected") {
|
|
892
|
+
ctx.out(`Version ${version.number} (commit ${short(version.commit_sha)}) was built but cannot be published:`);
|
|
893
|
+
for (const line of problems(version)) ctx.out(` ${line}`);
|
|
894
|
+
ctx.out("Fix what is listed, commit, push, and wait again.");
|
|
895
|
+
return 1;
|
|
896
|
+
}
|
|
897
|
+
if (version?.state === "failed") {
|
|
898
|
+
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.`);
|
|
899
|
+
ctx.out("Push again (an empty commit will do) to send it once more.");
|
|
900
|
+
return 1;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
const build = builds?.find((candidate) => matches(candidate.commit_sha));
|
|
904
|
+
if (build?.state === "failed") {
|
|
905
|
+
ctx.out(`The build of commit ${short(build.commit_sha)} failed${whyFailed(build)}.`);
|
|
906
|
+
for (const line of failureLines(build)) ctx.out(` ${line}`);
|
|
907
|
+
ctx.out(afterFailure(build, slug));
|
|
908
|
+
return 1;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
if (ctx.now() >= deadline) {
|
|
912
|
+
ctx.out(
|
|
913
|
+
wanted
|
|
914
|
+
? `Commit ${short(wanted)} has still not been built. Check again later with: sites status ${slug}`
|
|
915
|
+
: `${slug} has no build yet. A build starts when you push.`,
|
|
916
|
+
);
|
|
917
|
+
return 2;
|
|
918
|
+
}
|
|
919
|
+
say(
|
|
920
|
+
!wanted
|
|
921
|
+
? "Waiting for a build to start…"
|
|
922
|
+
: build
|
|
923
|
+
? `Commit ${short(wanted)} is ${build.state === "queued" ? "waiting to be built" : "being built"}…`
|
|
924
|
+
: `Waiting for the build of commit ${short(wanted)} to start…`,
|
|
925
|
+
);
|
|
926
|
+
await ctx.sleep(5000);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
// ---------------------------------------------------------------- helpers
|
|
931
|
+
|
|
932
|
+
/**
|
|
933
|
+
* @param {Context} ctx
|
|
934
|
+
* @returns {Promise<import("./api.mjs").Api>}
|
|
935
|
+
*/
|
|
936
|
+
async function signedIn(ctx) {
|
|
937
|
+
const key = await ctx.keys.get(ctx.environment.name);
|
|
938
|
+
if (!key) throw new CliError(`No key is saved for ${ctx.environment.name}. Run: sites login${ctx.environment.name === "test" ? "" : ` --env ${ctx.environment.name}`}`);
|
|
939
|
+
return tidied(ctx.api(key));
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
/**
|
|
943
|
+
* The API, with everything it says about sites, versions and builds made
|
|
944
|
+
* safe to print: names, states, addresses and commit ids come from the
|
|
945
|
+
* service, and through it from whoever named the site or pushed to it.
|
|
946
|
+
* The CRM's replies are left as they came (`--json` prints them); what is
|
|
947
|
+
* shown from them is cleaned where it is shown.
|
|
948
|
+
* @param {import("./api.mjs").Api} api
|
|
949
|
+
* @returns {import("./api.mjs").Api}
|
|
950
|
+
*/
|
|
951
|
+
function tidied(api) {
|
|
952
|
+
const clean = (/** @type {(...args: any[]) => Promise<unknown>} */ call) => async (/** @type {any[]} */ ...args) => tidy(await call(...args));
|
|
953
|
+
return /** @type {import("./api.mjs").Api} */ ({
|
|
954
|
+
...Object.fromEntries(Object.entries(api).map(([name, call]) => [name, clean(/** @type {any} */ (call))])),
|
|
955
|
+
dataPass: api.dataPass,
|
|
956
|
+
data: api.data,
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
/**
|
|
961
|
+
* Every piece of text in a reply made printable. A build's own output
|
|
962
|
+
* (`failure`) keeps its line breaks; everything else is one line.
|
|
963
|
+
* @param {unknown} value @param {boolean} [lines]
|
|
964
|
+
* @returns {unknown}
|
|
965
|
+
*/
|
|
966
|
+
function tidy(value, lines = false) {
|
|
967
|
+
if (typeof value === "string") return lines ? printableLines(value) : printable(value).trim();
|
|
968
|
+
if (Array.isArray(value)) return value.map((each) => tidy(each, lines));
|
|
969
|
+
if (value !== null && typeof value === "object") {
|
|
970
|
+
return Object.fromEntries(Object.entries(value).map(([name, each]) => [name, tidy(each, lines || name === "failure")]));
|
|
971
|
+
}
|
|
972
|
+
return value;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
/**
|
|
976
|
+
* A slug that could be a site on this environment. The service has the last
|
|
977
|
+
* word (it reserves more names); this only catches what can never work.
|
|
978
|
+
* @param {Context} ctx @param {string | undefined} value
|
|
979
|
+
*/
|
|
980
|
+
function checkedSlug(ctx, value) {
|
|
981
|
+
const slug = String(value ?? "").trim().toLowerCase();
|
|
982
|
+
if (slug === "") throw new CliError("Which site? Give its name, for example: sites status my-shop");
|
|
983
|
+
if (!/^[a-z0-9](?:[a-z0-9]|-(?!-)){1,38}[a-z0-9]$/.test(slug)) {
|
|
984
|
+
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.`);
|
|
985
|
+
}
|
|
986
|
+
const problem = nameProblem(slug, ctx.environment.name, ctx.environment.sitesDomain);
|
|
987
|
+
if (problem) throw new CliError(`"${slug}" cannot be a site's name: ${problem}.`);
|
|
988
|
+
return slug;
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
/**
|
|
992
|
+
* @param {Context} ctx @param {import("./api.mjs").Api} api @param {string} slug
|
|
993
|
+
* @returns {Promise<import("./api.mjs").Site>}
|
|
994
|
+
*/
|
|
995
|
+
async function findSite(ctx, api, slug) {
|
|
996
|
+
/** @type {import("./api.mjs").Site | null} */
|
|
997
|
+
let site;
|
|
998
|
+
try {
|
|
999
|
+
site = await api.findSite(slug);
|
|
1000
|
+
} catch (error) {
|
|
1001
|
+
// The list of sites is missing only while hosted sites are switched off: that is not about this site.
|
|
1002
|
+
throw friendly(error, error instanceof ApiError && error.status === 404 ? undefined : slug);
|
|
1003
|
+
}
|
|
1004
|
+
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`);
|
|
1005
|
+
return site;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
/**
|
|
1009
|
+
* A site's files are copied in from the starter when it is made. When they
|
|
1010
|
+
* are not there yet, ask the service to finish, and wait until they are.
|
|
1011
|
+
* @param {Context} ctx @param {import("./api.mjs").Api} api @param {import("./api.mjs").Site} site
|
|
1012
|
+
* @param {string} notReady what to say when they are still not there after a minute
|
|
1013
|
+
*/
|
|
1014
|
+
async function waitUntilCloneable(ctx, api, site, notReady) {
|
|
1015
|
+
let current = site;
|
|
1016
|
+
const deadline = ctx.now() + 60_000;
|
|
1017
|
+
let said = false;
|
|
1018
|
+
while (current.git?.ready === false) {
|
|
1019
|
+
if (ctx.now() >= deadline) throw new CliError(notReady);
|
|
1020
|
+
if (!said) ctx.note("Getting the site's files ready…");
|
|
1021
|
+
said = true;
|
|
1022
|
+
try {
|
|
1023
|
+
current = await api.prepareRepository(site.id);
|
|
1024
|
+
} catch (error) {
|
|
1025
|
+
const code = error instanceof ApiError ? error.code : "";
|
|
1026
|
+
// Being made right now, or the attempt failed and may be made again: both pass.
|
|
1027
|
+
if (code !== "repository_in_progress" && code !== "repository_failed") {
|
|
1028
|
+
throw new CliError(`${notReady}\n(${friendly(error, site.slug).message})`);
|
|
1029
|
+
}
|
|
1030
|
+
await ctx.sleep(3000);
|
|
1031
|
+
current = code === "repository_in_progress" ? await api.getSite(site.id) : current;
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
return current;
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* @param {Context} ctx @param {import("./api.mjs").Site} site @param {string} dir
|
|
1038
|
+
*/
|
|
1039
|
+
async function clone(ctx, site, dir) {
|
|
1040
|
+
// The site's name goes into an address and into a command line the build
|
|
1041
|
+
// runs: one from the service is held to the same rule as one typed.
|
|
1042
|
+
/** @type {string} */
|
|
1043
|
+
let slug;
|
|
1044
|
+
try {
|
|
1045
|
+
slug = checkedSlug(ctx, site.slug);
|
|
1046
|
+
} catch {
|
|
1047
|
+
throw new CliError(`The service named this site "${printable(site.slug)}", which cannot be a site's name. Nothing was brought here.`);
|
|
1048
|
+
}
|
|
1049
|
+
const ours = gitUrl(ctx.environment, slug);
|
|
1050
|
+
// Use the address the service gives only when it is on our own git address.
|
|
1051
|
+
const url = site.git?.url && site.git.url.startsWith(`${ctx.environment.git}/`) ? site.git.url : ours;
|
|
1052
|
+
await cloneSite({
|
|
1053
|
+
git: ctx.git,
|
|
1054
|
+
url,
|
|
1055
|
+
gitBase: ctx.environment.git,
|
|
1056
|
+
dir,
|
|
1057
|
+
helper: helperCommand({ node: ctx.self.node, script: ctx.self.script, environment: ctx.environment.name }),
|
|
1058
|
+
dataHelper: dataHelperCommand({ node: ctx.self.node, script: ctx.self.script, environment: ctx.environment.name, slug }),
|
|
1059
|
+
starterUrl: gitUrl(ctx.environment, STARTER_SLUG),
|
|
1060
|
+
});
|
|
1061
|
+
ctx.note(`The remote "${STARTER_REMOTE}" is the project every site starts from. To take its newest version: git fetch ${STARTER_REMOTE} && git merge ${STARTER_REMOTE}/main`);
|
|
1062
|
+
|
|
1063
|
+
// Git on this computer may not know who is committing; then it guesses (on
|
|
1064
|
+
// a Mac, from the account's name and the computer's network address) or, on
|
|
1065
|
+
// Linux, refuses to commit. Commits in this folder are then signed as the
|
|
1066
|
+
// business, with an address that is never delivered (".invalid").
|
|
1067
|
+
// Cut by characters, not UTF-16 units, so an emoji at the end is not split.
|
|
1068
|
+
const name = Array.from(printable(site.name ?? "").trim()).slice(0, 80).join("").trim();
|
|
1069
|
+
// Git refuses a name with no letter or digit in it ("<>", "."): the slug then.
|
|
1070
|
+
const signer = /[\p{L}\p{N}]/u.test(name) ? name : slug;
|
|
1071
|
+
/** @type {string[]} */
|
|
1072
|
+
let made;
|
|
1073
|
+
try {
|
|
1074
|
+
made = await ensureIdentity({ git: ctx.git, dir, identity: { name: signer, email: `${slug}@sites.invalid` } });
|
|
1075
|
+
} catch (error) {
|
|
1076
|
+
// The files are here; only the signature is missing, which git will say on the first commit.
|
|
1077
|
+
if (!(error instanceof GitError)) throw error;
|
|
1078
|
+
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.`);
|
|
1079
|
+
return;
|
|
1080
|
+
}
|
|
1081
|
+
if (made.length > 0) {
|
|
1082
|
+
const what = made.includes("user.name")
|
|
1083
|
+
? `so commits in this folder are signed "${signer}"`
|
|
1084
|
+
: `so commits in this folder use the address ${slug}@sites.invalid`;
|
|
1085
|
+
ctx.note(
|
|
1086
|
+
`Git had no ${made.map((setting) => (setting === "user.name" ? "name" : "email")).join(" or ")} on this computer, ${what}. ` +
|
|
1087
|
+
'To sign them as yourself, in this folder: git config user.name "<your name>" && git config user.email "<your email>"',
|
|
1088
|
+
);
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
/**
|
|
1093
|
+
* The latest commit of the site's clone, when the command is run inside it.
|
|
1094
|
+
* @param {Context} ctx @param {string} slug
|
|
1095
|
+
* @returns {Promise<{ commit: string, pushed: boolean } | null>}
|
|
1096
|
+
*/
|
|
1097
|
+
async function localHead(ctx, slug) {
|
|
1098
|
+
try {
|
|
1099
|
+
const origin = await ctx.git(["config", "--get", "remote.origin.url"], { cwd: ctx.cwd, quiet: true });
|
|
1100
|
+
if (origin.code !== 0 || origin.stdout.trim() !== gitUrl(ctx.environment, slug)) return null;
|
|
1101
|
+
const head = await ctx.git(["rev-parse", "HEAD"], { cwd: ctx.cwd, quiet: true });
|
|
1102
|
+
if (head.code !== 0) return null;
|
|
1103
|
+
const commit = head.stdout.trim();
|
|
1104
|
+
// Where git last saw the site's main branch: moved by every push and fetch.
|
|
1105
|
+
const remote = await ctx.git(["rev-parse", "--verify", "--quiet", "refs/remotes/origin/main"], { cwd: ctx.cwd, quiet: true });
|
|
1106
|
+
const contained = await ctx.git(["merge-base", "--is-ancestor", commit, "refs/remotes/origin/main"], { cwd: ctx.cwd, quiet: true });
|
|
1107
|
+
return { commit, pushed: remote.code === 0 && contained.code === 0 };
|
|
1108
|
+
} catch {
|
|
1109
|
+
return null;
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/**
|
|
1114
|
+
* When the service refuses a key for one action while the key itself still
|
|
1115
|
+
* works, say that, not "your key was not accepted": saving the key again
|
|
1116
|
+
* would change nothing.
|
|
1117
|
+
* @param {import("./api.mjs").Api} api @param {unknown} error @param {string} action "put a site online"
|
|
1118
|
+
* @returns {Promise<CliError | null>}
|
|
1119
|
+
*/
|
|
1120
|
+
async function keyMayNot(api, error, action) {
|
|
1121
|
+
if (!(error instanceof ApiError) || error.status !== 401) return null;
|
|
1122
|
+
try {
|
|
1123
|
+
await api.me();
|
|
1124
|
+
} catch {
|
|
1125
|
+
return null; // the key really is not accepted: the usual message is right
|
|
1126
|
+
}
|
|
1127
|
+
return new CliError(
|
|
1128
|
+
`Your key works, but a key is not allowed to ${action}. For now that needs a person signed in to SuperIntern. Nothing was changed.`,
|
|
1129
|
+
3,
|
|
1130
|
+
);
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
/**
|
|
1134
|
+
* Turn a failure from the API into a line the person can act on.
|
|
1135
|
+
* @param {unknown} error @param {string} [slug]
|
|
1136
|
+
* @returns {Error}
|
|
1137
|
+
*/
|
|
1138
|
+
function friendly(error, slug) {
|
|
1139
|
+
if (!(error instanceof ApiError)) return /** @type {Error} */ (error);
|
|
1140
|
+
switch (error.code) {
|
|
1141
|
+
case "not_authenticated":
|
|
1142
|
+
return new CliError("Your key was not accepted. Save a working one with: sites login");
|
|
1143
|
+
case "unreachable":
|
|
1144
|
+
return new CliError(error.message);
|
|
1145
|
+
case "not_found":
|
|
1146
|
+
return new CliError(slug ? `There is no site called "${slug}" that your key can use.` : "Hosted sites are not available for this key.");
|
|
1147
|
+
case "slug_taken":
|
|
1148
|
+
return new CliError(`The name "${slug}" is already taken. Choose another.`);
|
|
1149
|
+
case "publish_in_progress":
|
|
1150
|
+
return new CliError(`${slug} is already being published. Wait a minute and check: sites status ${slug}`);
|
|
1151
|
+
case "rate_limited":
|
|
1152
|
+
return new CliError(`Too many changes in a short time. ${error.message}`);
|
|
1153
|
+
default:
|
|
1154
|
+
// The service writes its messages for a person; pass them on.
|
|
1155
|
+
return new CliError(error.message);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
/** @param {import("./api.mjs").Site} site */
|
|
1160
|
+
function addressOf(site) {
|
|
1161
|
+
if (site.url) return site.url;
|
|
1162
|
+
const domain = site.domains?.find((d) => d.kind === "free" && d.state === "active") ?? site.domains?.[0];
|
|
1163
|
+
return domain ? `https://${domain.hostname}` : null;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
/** @param {import("./api.mjs").Site} site */
|
|
1167
|
+
function describeState(site) {
|
|
1168
|
+
const live = site.live_version;
|
|
1169
|
+
switch (site.state) {
|
|
1170
|
+
case "live":
|
|
1171
|
+
return live ? `Online, serving version ${live.number} (commit ${short(live.commit_sha)})${live.published_at ? `, published ${when(live.published_at)}` : ""}.` : "Online.";
|
|
1172
|
+
case "offline":
|
|
1173
|
+
return `Offline: visitors see "This site is offline".${live ? ` Publishing again serves version ${live.number}.` : ""}`;
|
|
1174
|
+
case "suspended":
|
|
1175
|
+
return "Suspended by SuperIntern. It cannot be published until that is lifted.";
|
|
1176
|
+
default:
|
|
1177
|
+
return "Not published yet.";
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
/** @param {import("./api.mjs").Build} build */
|
|
1182
|
+
function describeBuild(build) {
|
|
1183
|
+
const what = { queued: "waiting to start", running: "running", succeeded: "finished", failed: `failed${whyFailed(build)}` }[build.state] ?? build.state;
|
|
1184
|
+
return `${what} (commit ${short(build.commit_sha)}${build.finished_at || build.started_at ? `, ${when(build.finished_at ?? build.started_at)}` : ""})`;
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
/**
|
|
1188
|
+
* The reasons a build can fail for (`failure.step`), in words, and whether
|
|
1189
|
+
* the site's own files are what has to change.
|
|
1190
|
+
* @type {Record<string, { what: string, site: boolean }>}
|
|
1191
|
+
*/
|
|
1192
|
+
const BUILD_FAILURES = {
|
|
1193
|
+
contract_failed: { what: "the site breaks one of the rules every site must keep (see CONTRACT.md)", site: true },
|
|
1194
|
+
install_failed: { what: "its packages could not be installed", site: true },
|
|
1195
|
+
build_failed: { what: "the site could not be built", site: true },
|
|
1196
|
+
too_large: { what: "the built site is too large", site: true },
|
|
1197
|
+
timeout: { what: "the build took too long", site: true },
|
|
1198
|
+
checks: { what: "the built site did not pass the safety checks", site: true },
|
|
1199
|
+
fetch_failed: { what: "the site's files could not be fetched for the build", site: false },
|
|
1200
|
+
invalid_env: { what: "the build was not set up correctly", site: false },
|
|
1201
|
+
internal_error: { what: "the build service had a problem", site: false },
|
|
1202
|
+
queue: { what: "the build could not be started", site: false },
|
|
1203
|
+
};
|
|
1204
|
+
|
|
1205
|
+
/** @param {import("./api.mjs").Build} build ": the site could not be built", or the reason as sent when it is a new one */
|
|
1206
|
+
function whyFailed(build) {
|
|
1207
|
+
const step = build.failure?.step;
|
|
1208
|
+
if (!step) return "";
|
|
1209
|
+
const known = Object.hasOwn(BUILD_FAILURES, step) ? BUILD_FAILURES[step] : undefined;
|
|
1210
|
+
return known ? `: ${known.what}` : ` at "${printable(step)}"`;
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
/** @param {import("./api.mjs").Build} build @param {string} slug what to do about a failed build */
|
|
1214
|
+
function afterFailure(build, slug) {
|
|
1215
|
+
const step = build.failure?.step ?? "";
|
|
1216
|
+
const known = Object.hasOwn(BUILD_FAILURES, step) ? BUILD_FAILURES[step] : undefined;
|
|
1217
|
+
if (known && !known.site) {
|
|
1218
|
+
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.`;
|
|
1219
|
+
}
|
|
1220
|
+
if (step === "checks") return `Fix what is listed, commit, push, and wait again: sites status ${slug} --wait`;
|
|
1221
|
+
return "Run `npm run check` in the site's folder to see the same problem here, fix it, commit and push.";
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
/** @param {import("./api.mjs").Build | undefined} build */
|
|
1225
|
+
function failureLines(build) {
|
|
1226
|
+
if (!build || build.state !== "failed" || !build.failure) return [];
|
|
1227
|
+
const lines = [];
|
|
1228
|
+
if (build.failure.message) lines.push(...String(build.failure.message).split("\n"));
|
|
1229
|
+
if (build.failure.log_tail) lines.push(...build.failure.log_tail.trimEnd().split("\n").slice(-30));
|
|
1230
|
+
return lines.map(printable);
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
/**
|
|
1234
|
+
* Why a version cannot be published, in the service's own words.
|
|
1235
|
+
* @param {import("./api.mjs").Version | undefined} version
|
|
1236
|
+
*/
|
|
1237
|
+
function problems(version) {
|
|
1238
|
+
if (!version || version.state === "ready") return [];
|
|
1239
|
+
return (version.gate?.findings ?? []).filter((finding) => finding.severity === "reject").map((finding) => printable(finding.message));
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
/** @param {string | undefined} sha */
|
|
1243
|
+
function short(sha) {
|
|
1244
|
+
return (sha ?? "").slice(0, 7);
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
/** @param {string | null | undefined} iso */
|
|
1248
|
+
function when(iso) {
|
|
1249
|
+
if (!iso) return "";
|
|
1250
|
+
const date = new Date(iso);
|
|
1251
|
+
if (Number.isNaN(date.getTime())) return "";
|
|
1252
|
+
const month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][date.getUTCMonth()];
|
|
1253
|
+
const two = (/** @type {number} */ n) => String(n).padStart(2, "0");
|
|
1254
|
+
return `${date.getUTCDate()} ${month} ${date.getUTCFullYear()} ${two(date.getUTCHours())}:${two(date.getUTCMinutes())} UTC`;
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
/** @param {string[][]} rows */
|
|
1258
|
+
function table(rows) {
|
|
1259
|
+
const widths = rows[0]?.map((_, column) => Math.max(...rows.map((row) => (row[column] ?? "").length))) ?? [];
|
|
1260
|
+
return rows.map((row) => row.map((cell, column) => cell.padEnd(widths[column] ?? 0)).join(" ").trimEnd());
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/** @param {Context} ctx @param {string} dir */
|
|
1264
|
+
function shown(ctx, dir) {
|
|
1265
|
+
return dir.startsWith(`${ctx.cwd}/`) ? dir.slice(ctx.cwd.length + 1) : dir;
|
|
1266
|
+
}
|