@livespace/plugin-cli 0.0.0-stage → 0.1.1

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,258 @@
1
+ /**
2
+ * Checks a `plugin-manifest.json` the way the catalog will read it.
3
+ *
4
+ * Ported from Labs' `checkManifest` (livespace-labs/scripts/plugin-manifest.ts), with its messages,
5
+ * minus what only applies to Labs (its 28-character id and its own origin), plus P2-27's keys.
6
+ * A failure is something the registry would refuse or mis-store; a warning is something a person
7
+ * should look at. Pure: no file system, no network.
8
+ */
9
+ import { CATEGORIES, EXPECTED_LOCALES, FIELDS, ID_PATTERN, KEY_ALG, KEY_USES, MAX_KEYS_PER_USE, MIN_RSA_BITS, OBJECT_TYPES, REQUIRED_LOCALE, } from "./schema.js";
10
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
11
+ const HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
12
+ const SVG = /\.svg(?:[?#].*)?$/i;
13
+ const RAW_HTML = /<\/?[a-zA-Z][^>]*>/;
14
+ const LINK = /\[[^\]]*\]\([^)]*\)|<https?:\/\/[^>]*>|https?:\/\/\S+/;
15
+ /** JWK members that only a private key has. One in a manifest is a leaked key. */
16
+ const PRIVATE_MEMBERS = ["d", "p", "q", "dp", "dq", "qi", "oth", "k"];
17
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
18
+ const isText = (v) => typeof v === "string" && v.trim() !== "";
19
+ const isI18n = (v) => isRecord(v) && Object.values(v).every(isText);
20
+ const isTextList = (v) => Array.isArray(v) && v.every(isText);
21
+ const KIND_CHECKS = {
22
+ string: [isText, "must be a non-empty string"],
23
+ i18n: [isI18n, 'must map languages to non-empty texts, e.g. { "en": "…" }'],
24
+ stringList: [isTextList, "must be a list of non-empty strings"],
25
+ objectTypes: [
26
+ (v) => v === null || Array.isArray(v),
27
+ "must be a list of object types, or null for any",
28
+ ],
29
+ keySet: [
30
+ (v) => isRecord(v) && Array.isArray(v.keys),
31
+ 'must be a key set, { "keys": [ … ] }',
32
+ ],
33
+ };
34
+ const parseUrl = (v) => {
35
+ try {
36
+ return new URL(v);
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ };
42
+ /** The bit length of a JWK's base64url modulus. */
43
+ const modulusBits = (n) => Buffer.from(n, "base64url").length * 8;
44
+ export function checkManifest(text) {
45
+ const failures = [];
46
+ const warnings = [];
47
+ const done = (manifest) => ({
48
+ failures,
49
+ warnings,
50
+ manifest: failures.length === 0 ? manifest : null,
51
+ });
52
+ let raw;
53
+ try {
54
+ raw = JSON.parse(text);
55
+ }
56
+ catch (error) {
57
+ failures.push(`plugin-manifest.json is not valid JSON (${error.message}) — a trailing comma is the usual cause`);
58
+ return done(null);
59
+ }
60
+ if (!isRecord(raw)) {
61
+ failures.push("plugin-manifest.json must be a JSON object");
62
+ return done(null);
63
+ }
64
+ const known = new Set(FIELDS.map((f) => f.key));
65
+ for (const key of Object.keys(raw)) {
66
+ if (!known.has(key)) {
67
+ failures.push(`unknown field "${key}" — the catalog schema has no such field (check the spelling)`);
68
+ }
69
+ }
70
+ for (const { key, required, kind } of FIELDS) {
71
+ if (!(key in raw)) {
72
+ if (required) {
73
+ failures.push(`"${key}" is required`);
74
+ }
75
+ continue;
76
+ }
77
+ const [ok, message] = KIND_CHECKS[kind];
78
+ if (!ok(raw[key])) {
79
+ failures.push(`"${key}" ${message}`);
80
+ }
81
+ }
82
+ if (failures.length > 0) {
83
+ return done(null);
84
+ }
85
+ const m = raw;
86
+ if (!ID_PATTERN.test(m.id)) {
87
+ failures.push(`"id" "${m.id}" must be lowercase letters, digits, ".", "_" or "-", starting with a letter or digit, ≤128 chars — it's the catalog key and, as plugin:<id>, the plugin's client id`);
88
+ }
89
+ if (!SEMVER.test(m.version)) {
90
+ failures.push(`"version" "${m.version}" must be semver, e.g. 0.1.0`);
91
+ }
92
+ if (m.type !== "iframe") {
93
+ failures.push('"type" must be "iframe" — native plugins live in Livespace itself');
94
+ }
95
+ checkOrigin(m.iframeOrigin, failures);
96
+ checkObjectTypes(m.allowedObjectTypes, failures);
97
+ checkTexts(m, failures, warnings);
98
+ checkAssets(m, failures, warnings);
99
+ if (m.accentColor !== undefined && !HEX_COLOR.test(m.accentColor)) {
100
+ failures.push('"accentColor" must be a hex colour like #5546b8');
101
+ }
102
+ for (const category of m.categories ?? []) {
103
+ if (!CATEGORIES.includes(category)) {
104
+ warnings.push(`category "${category}" isn't one the catalog uses (${CATEGORIES.join(", ")}) — a typo, or a new one to confirm with the catalog owners?`);
105
+ }
106
+ }
107
+ checkKeys(m, failures, warnings);
108
+ return done(m);
109
+ }
110
+ function checkOrigin(origin, failures) {
111
+ const url = parseUrl(origin);
112
+ if (url === null || url.protocol !== "https:") {
113
+ failures.push(`"iframeOrigin" must be an https origin, like https://plugin.example.com — not ${origin}`);
114
+ return;
115
+ }
116
+ if (url.origin !== origin) {
117
+ failures.push(`"iframeOrigin" must be the origin alone, no path or trailing slash: ${url.origin}, not ${origin}`);
118
+ }
119
+ }
120
+ function checkObjectTypes(types, failures) {
121
+ if (types === null) {
122
+ return;
123
+ }
124
+ if (types.length === 0) {
125
+ failures.push('"allowedObjectTypes" is never empty — list where the plugin may go, or use null for any type');
126
+ return;
127
+ }
128
+ for (const type of types) {
129
+ if (type === "none") {
130
+ failures.push('"allowedObjectTypes" never names "none" — use null for "any type, none included"');
131
+ }
132
+ else if (!OBJECT_TYPES.includes(type)) {
133
+ failures.push(`"allowedObjectTypes" has an unknown type "${type}" — one of ${OBJECT_TYPES.join(", ")}`);
134
+ }
135
+ }
136
+ }
137
+ function checkTexts(m, failures, warnings) {
138
+ for (const key of ["name", "description", "details"]) {
139
+ const text = m[key];
140
+ if (text === undefined) {
141
+ if (key !== "name") {
142
+ warnings.push(`no "${key}" — the catalog card will look unfinished`);
143
+ }
144
+ continue;
145
+ }
146
+ if (!(REQUIRED_LOCALE in text)) {
147
+ failures.push(`"${key}" needs an "${REQUIRED_LOCALE}" text`);
148
+ continue;
149
+ }
150
+ const missing = EXPECTED_LOCALES.filter((lang) => !(lang in text));
151
+ if (missing.length > 0) {
152
+ warnings.push(`"${key}" has no ${missing.join(", ")} text`);
153
+ }
154
+ if (key === "name") {
155
+ continue;
156
+ }
157
+ for (const [lang, value] of Object.entries(text)) {
158
+ if (RAW_HTML.test(value)) {
159
+ warnings.push(`"${key}.${lang}" contains raw HTML, which the catalog filters out — use Markdown instead`);
160
+ }
161
+ if (key === "description" && LINK.test(value)) {
162
+ warnings.push(`"description.${lang}" contains a link, which the catalog strips from the card — put links in "details"`);
163
+ }
164
+ }
165
+ }
166
+ }
167
+ function checkAssets(m, failures, warnings) {
168
+ const origin = parseUrl(m.iframeOrigin)?.origin;
169
+ const assets = [
170
+ ...["iconUrl", "illustrationUrl", "infoUrl"]
171
+ .filter((key) => m[key] !== undefined)
172
+ .map((key) => [key, m[key]]),
173
+ ...(m.additionalImages ?? []).map((url, i) => [
174
+ `additionalImages[${i}]`,
175
+ url,
176
+ ]),
177
+ ];
178
+ if (m.iconUrl === undefined) {
179
+ warnings.push('no "iconUrl" — the catalog card will look unfinished');
180
+ }
181
+ for (const [key, value] of assets) {
182
+ const url = parseUrl(value);
183
+ if (url === null || url.protocol !== "https:") {
184
+ failures.push(`"${key}" must be an https URL, not ${value}`);
185
+ continue;
186
+ }
187
+ if ((key === "iconUrl" || key === "illustrationUrl") &&
188
+ !SVG.test(url.pathname)) {
189
+ failures.push(`"${key}" must be an .svg`);
190
+ }
191
+ if (origin !== undefined && url.origin !== origin) {
192
+ warnings.push(`"${key}" is served from another origin than the plugin (${url.origin}) — fine if intended`);
193
+ }
194
+ }
195
+ }
196
+ function checkKeys(m, failures, warnings) {
197
+ const keys = (m.publicKeys?.keys ?? []);
198
+ const kids = new Map();
199
+ const perUse = { sig: 0, enc: 0 };
200
+ keys.forEach((raw, i) => {
201
+ const at = `publicKeys.keys[${i}]`;
202
+ if (!isRecord(raw)) {
203
+ failures.push(`"${at}" must be a JWK object`);
204
+ return;
205
+ }
206
+ const name = isText(raw.kid) ? raw.kid : at;
207
+ const leaked = PRIVATE_MEMBERS.filter((member) => member in raw);
208
+ if (leaked.length > 0) {
209
+ failures.push(`"${name}" is a PRIVATE key (it has ${leaked.join(", ")}): remove it from the manifest, and rotate it — anyone who has seen this file has the key`);
210
+ }
211
+ if (!isText(raw.kid)) {
212
+ failures.push(`"${at}" needs a "kid"`);
213
+ }
214
+ else {
215
+ kids.set(raw.kid, (kids.get(raw.kid) ?? 0) + 1);
216
+ }
217
+ if (raw.kty !== "RSA") {
218
+ failures.push(`"${name}" must be an RSA key ("kty": "RSA")`);
219
+ }
220
+ if (!KEY_USES.includes(raw.use)) {
221
+ failures.push(`"${name}" has "use" ${JSON.stringify(raw.use)} — "sig" to sign, "enc" to encrypt secrets`);
222
+ }
223
+ else {
224
+ const use = raw.use;
225
+ perUse[use]++;
226
+ if (raw.alg !== KEY_ALG[use]) {
227
+ failures.push(`"${name}" is a "${use}" key, so its "alg" is ${KEY_ALG[use]}, not ${JSON.stringify(raw.alg)}`);
228
+ }
229
+ }
230
+ if (!isText(raw.n) || !isText(raw.e)) {
231
+ failures.push(`"${name}" needs its public "n" and "e"`);
232
+ }
233
+ else if (modulusBits(raw.n) < MIN_RSA_BITS) {
234
+ failures.push(`"${name}" is ${modulusBits(raw.n)} bits — RSA keys need ${MIN_RSA_BITS} or more`);
235
+ }
236
+ });
237
+ for (const [kid, count] of kids) {
238
+ if (count > 1) {
239
+ failures.push(`"publicKeys" lists the kid "${kid}" ${count} times — each key needs its own`);
240
+ }
241
+ }
242
+ for (const use of KEY_USES) {
243
+ if (perUse[use] > MAX_KEYS_PER_USE) {
244
+ failures.push(`"publicKeys" holds at most ${MAX_KEYS_PER_USE} "${use}" keys, for a rotation — retire the oldest`);
245
+ }
246
+ }
247
+ const secrets = m.secretKeys ?? [];
248
+ const duplicates = secrets.filter((key, i) => secrets.indexOf(key) !== i);
249
+ for (const key of new Set(duplicates)) {
250
+ failures.push(`"secretKeys" lists "${key}" twice`);
251
+ }
252
+ if (secrets.length > 0 && perUse.enc === 0) {
253
+ failures.push('"secretKeys" needs an encryption key in "publicKeys" — the admin\'s browser encrypts secrets with it (keys init)');
254
+ }
255
+ if (secrets.length === 0 && perUse.enc > 0) {
256
+ warnings.push('an encryption key but no "secretKeys" — list the config form\'s secret fields, or retire the key');
257
+ }
258
+ }
@@ -0,0 +1,59 @@
1
+ /** Reading and writing a project's `plugin-manifest.json` and `package.json`. */
2
+ import { readFile, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { FIELDS, MANIFEST_FILE } from "./schema.js";
5
+ export const manifestPath = (dir) => join(dir, MANIFEST_FILE);
6
+ const readIfThere = async (path) => {
7
+ try {
8
+ return await readFile(path, "utf8");
9
+ }
10
+ catch (error) {
11
+ if (error.code === "ENOENT") {
12
+ return undefined;
13
+ }
14
+ throw error;
15
+ }
16
+ };
17
+ export const readManifestText = (dir) => readIfThere(manifestPath(dir));
18
+ export async function readPackageJson(dir) {
19
+ const text = await readIfThere(join(dir, "package.json"));
20
+ if (text === undefined) {
21
+ return undefined;
22
+ }
23
+ try {
24
+ const value = JSON.parse(text);
25
+ return typeof value === "object" && value !== null && !Array.isArray(value)
26
+ ? value
27
+ : undefined;
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ /** Fields in schema order, unset ones left out, two-space indent like Labs' writer. */
34
+ export function serializeManifest(manifest) {
35
+ const ordered = {};
36
+ for (const { key } of FIELDS) {
37
+ if (manifest[key] !== undefined) {
38
+ ordered[key] = manifest[key];
39
+ }
40
+ }
41
+ return `${JSON.stringify(ordered, null, 2)}\n`;
42
+ }
43
+ /**
44
+ * `create` refuses an existing file: the `id` in it is the catalog key, and a fresh `init` over it
45
+ * is how a plugin ends up re-keyed. Change one field with `manifest set` instead.
46
+ */
47
+ export async function writeManifest(dir, manifest, { create }) {
48
+ try {
49
+ await writeFile(manifestPath(dir), serializeManifest(manifest), {
50
+ flag: create ? "wx" : "w",
51
+ });
52
+ }
53
+ catch (error) {
54
+ if (error.code === "EEXIST") {
55
+ throw new Error(`${MANIFEST_FILE} already exists — its "id" is the catalog key, so it isn't rewritten. Change a field with \`manifest set\`.`);
56
+ }
57
+ throw error;
58
+ }
59
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * What a project's `package.json` can tell `manifest init`, offered as defaults the user can change.
3
+ * Anything that doesn't fit the manifest is left out rather than guessed at.
4
+ */
5
+ import { ID_PATTERN } from "./schema.js";
6
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
7
+ /** `@acme/Deal Scoring!` → `deal-scoring`, or undefined if nothing usable is left. */
8
+ const idFrom = (name) => {
9
+ const id = name
10
+ .replace(/^@[^/]+\//, "")
11
+ .toLowerCase()
12
+ .replace(/[^a-z0-9._-]+/g, "-")
13
+ .replace(/^[._-]+|[._-]+$/g, "")
14
+ .slice(0, 128)
15
+ .replace(/[._-]+$/, "");
16
+ return ID_PATTERN.test(id) ? id : undefined;
17
+ };
18
+ /** `deal-scoring` → `Deal scoring`. */
19
+ const titleFrom = (id) => {
20
+ const words = id.replace(/[._-]+/g, " ");
21
+ return words.charAt(0).toUpperCase() + words.slice(1);
22
+ };
23
+ export function prefillFrom(pkg) {
24
+ const prefill = {};
25
+ if (typeof pkg.name === "string") {
26
+ const id = idFrom(pkg.name);
27
+ if (id !== undefined) {
28
+ prefill.id = id;
29
+ prefill.name = titleFrom(id);
30
+ }
31
+ }
32
+ if (typeof pkg.version === "string" && SEMVER.test(pkg.version)) {
33
+ prefill.version = pkg.version;
34
+ }
35
+ if (typeof pkg.description === "string" && pkg.description.trim() !== "") {
36
+ prefill.description = pkg.description.trim();
37
+ }
38
+ if (typeof pkg.homepage === "string") {
39
+ try {
40
+ if (new URL(pkg.homepage).protocol === "https:") {
41
+ prefill.infoUrl = pkg.homepage;
42
+ }
43
+ }
44
+ catch {
45
+ // Not a URL: nothing to offer.
46
+ }
47
+ }
48
+ return prefill;
49
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The catalog manifest (`plugin-manifest.json`): its fields, enums and limits.
3
+ *
4
+ * The catalog's own shape is LSC's `docs/openapi/marketplace.json` (`CatalogItemView`) and the
5
+ * registry rows behind it. `publicKeys` and `secretKeys` are P2-27's additions (ls-fe
6
+ * `micro-apps/plugins-2/docs/upstream/plugin-authorization.md` §3–§4).
7
+ *
8
+ * Kept by hand in step with Labs' `livespace-labs/scripts/plugin-manifest.ts`, which checks the same
9
+ * file for Labs plugins. It becomes a package of its own if that turns out to be a burden.
10
+ */
11
+ export const MANIFEST_FILE = "plugin-manifest.json";
12
+ /**
13
+ * Where a catalog plugin may go. `null` in a manifest means any of them, the context-free `none`
14
+ * included; a list never names `none` and is never empty (the registry skips such an entry).
15
+ */
16
+ export const OBJECT_TYPES = [
17
+ "deal",
18
+ "company",
19
+ "person",
20
+ "space",
21
+ "dashboard",
22
+ ];
23
+ /** Livespace's languages, the ones the catalog texts are worth writing in. `en` is the fallback. */
24
+ export const LOCALES = ["en", "pl", "ro", "cs", "es", "sk"];
25
+ export const REQUIRED_LOCALE = "en";
26
+ /** Missing one of these is worth a warning; the rest are optional. Same as Labs'. */
27
+ export const EXPECTED_LOCALES = ["en", "pl", "ro"];
28
+ /**
29
+ * The categories in use across the catalog, offered by the picker. Categories are free strings
30
+ * (English keys), so another one is allowed, with a warning. Not localised anywhere yet (P2-37).
31
+ */
32
+ export const CATEGORIES = [
33
+ "Deal",
34
+ "Analytics and insights",
35
+ "Finance",
36
+ "Productivity",
37
+ "Sales",
38
+ "Communication",
39
+ "Products",
40
+ "Tasks",
41
+ "Sales intelligence",
42
+ "Invoicing",
43
+ "Integrations",
44
+ "Collaboration",
45
+ "AI",
46
+ ];
47
+ /**
48
+ * A catalog key. It's also the plugin's OAuth client id, as `plugin:<id>`, which is what a plugin
49
+ * token's `aud` carries: LSC's `PluginClientId` pattern, without its prefix.
50
+ */
51
+ export const ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,127}$/;
52
+ export const CLIENT_ID_PREFIX = "plugin:";
53
+ export const clientIdOf = (id) => `${CLIENT_ID_PREFIX}${id}`;
54
+ export const KEY_USES = ["sig", "enc"];
55
+ /** Signing is RS256 only (LSC's `PrivateKeyJwtAuthenticator`); secrets are RSA-OAEP-256. */
56
+ export const KEY_ALG = { sig: "RS256", enc: "RSA-OAEP-256" };
57
+ export const MAX_KEYS_PER_USE = 2;
58
+ export const MIN_RSA_BITS = 2048;
59
+ /** Every field, in the order the file is written, with how it is checked. */
60
+ export const FIELDS = [
61
+ { key: "id", required: true, kind: "string" },
62
+ { key: "version", required: true, kind: "string" },
63
+ { key: "type", required: true, kind: "string" },
64
+ { key: "iframeOrigin", required: true, kind: "string" },
65
+ { key: "allowedObjectTypes", required: true, kind: "objectTypes" },
66
+ { key: "name", required: true, kind: "i18n" },
67
+ { key: "description", required: false, kind: "i18n" },
68
+ { key: "details", required: false, kind: "i18n" },
69
+ { key: "categories", required: false, kind: "stringList" },
70
+ { key: "iconUrl", required: false, kind: "string" },
71
+ { key: "illustrationUrl", required: false, kind: "string" },
72
+ { key: "accentColor", required: false, kind: "string" },
73
+ { key: "additionalImages", required: false, kind: "stringList" },
74
+ { key: "infoUrl", required: false, kind: "string" },
75
+ { key: "secretKeys", required: false, kind: "stringList" },
76
+ { key: "publicKeys", required: false, kind: "keySet" },
77
+ ];
@@ -0,0 +1,50 @@
1
+ /** The terminal backend: @clack/prompts. Ctrl-C leaves without writing anything. */
2
+ import * as clack from "@clack/prompts";
3
+ export class Cancelled extends Error {
4
+ constructor() {
5
+ super("Cancelled — nothing was written.");
6
+ this.name = "Cancelled";
7
+ }
8
+ }
9
+ const answered = (value) => {
10
+ if (clack.isCancel(value)) {
11
+ clack.cancel("Cancelled — nothing was written.");
12
+ throw new Cancelled();
13
+ }
14
+ return value;
15
+ };
16
+ export const clackBackend = {
17
+ async text(q) {
18
+ const value = answered(await clack.text({
19
+ message: q.message,
20
+ placeholder: q.placeholder,
21
+ initialValue: q.initial,
22
+ validate: (raw) => {
23
+ const v = (raw ?? "").trim();
24
+ if (v === "") {
25
+ return q.optional ? undefined : "Required";
26
+ }
27
+ return q.validate?.(v);
28
+ },
29
+ })).trim();
30
+ return value === "" ? undefined : value;
31
+ },
32
+ async select(q) {
33
+ return answered(await clack.select({
34
+ message: q.message,
35
+ options: q.options,
36
+ initialValue: q.initial,
37
+ }));
38
+ },
39
+ async multiselect(q) {
40
+ return answered(await clack.multiselect({
41
+ message: q.message,
42
+ options: q.options,
43
+ initialValues: q.initial,
44
+ required: q.required !== false,
45
+ }));
46
+ },
47
+ async confirm(q) {
48
+ return answered(await clack.confirm({ message: q.message, initialValue: q.initial }));
49
+ },
50
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * What the CLI says. In a terminal, clack's framing; otherwise plain lines (warnings and errors on
3
+ * stderr); with `--json`, nothing but the one JSON result on stdout. Never key material.
4
+ */
5
+ import * as clack from "@clack/prompts";
6
+ export const clackOutput = {
7
+ start: (title) => clack.intro(title),
8
+ info: (message) => clack.log.info(message),
9
+ warn: (message) => clack.log.warn(message),
10
+ success: (message) => clack.log.success(message),
11
+ end: (message) => clack.outro(message),
12
+ result: () => { },
13
+ };
14
+ export const plainOutput = {
15
+ start: () => { },
16
+ info: (message) => console.log(message),
17
+ warn: (message) => console.error(`warning: ${message}`),
18
+ success: (message) => console.log(message),
19
+ end: (message) => console.log(message),
20
+ result: () => { },
21
+ };
22
+ export const jsonOutput = {
23
+ start: () => { },
24
+ info: () => { },
25
+ warn: () => { },
26
+ success: () => { },
27
+ end: () => { },
28
+ result: (value) => console.log(JSON.stringify(value, null, 2)),
29
+ };
30
+ /** Collects everything said, for tests. */
31
+ export function recordingOutput() {
32
+ const lines = [];
33
+ let result;
34
+ const out = {
35
+ start: (t) => lines.push(`start: ${t}`),
36
+ info: (m) => lines.push(m),
37
+ warn: (m) => lines.push(`warning: ${m}`),
38
+ success: (m) => lines.push(m),
39
+ end: (m) => lines.push(m),
40
+ result: (v) => {
41
+ result = v;
42
+ },
43
+ };
44
+ return { out, lines, result: () => result };
45
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Every question the CLI asks goes through a Prompter, which answers it from, in order:
3
+ *
4
+ * 1. its flag (`--<name>`), when one was given;
5
+ * 2. the person at the terminal, when there is one (the `backend`);
6
+ * 3. its default, under `--yes`;
7
+ * 4. nothing: the question is recorded as missing.
8
+ *
9
+ * So a run without a terminal never waits on input. An agent or a CI job gets one error, from
10
+ * `assertComplete`, listing every flag it still has to pass, instead of a hang.
11
+ */
12
+ export class MissingAnswers extends Error {
13
+ problems;
14
+ constructor(problems) {
15
+ super(`Some answers are missing or wrong. Pass them as flags, or run in a terminal to be asked:\n${problems.map((p) => ` ${p}`).join("\n")}`);
16
+ this.problems = problems;
17
+ this.name = "MissingAnswers";
18
+ }
19
+ }
20
+ export function createPrompter({ flags, yes = false, backend, }) {
21
+ const problems = [];
22
+ const missing = (name, hint) => problems.push(`--${name} ${hint}`);
23
+ const wrong = (name, why) => problems.push(`--${name}: ${why}`);
24
+ const flag = (name) => {
25
+ const value = flags[name];
26
+ return typeof value === "string" ? value : undefined;
27
+ };
28
+ const list = (value) => value
29
+ .split(",")
30
+ .map((item) => item.trim())
31
+ .filter((item) => item !== "");
32
+ return {
33
+ async text(q) {
34
+ const given = flag(q.name);
35
+ if (given !== undefined) {
36
+ const why = q.validate?.(given);
37
+ if (why !== undefined) {
38
+ wrong(q.name, why);
39
+ }
40
+ return given.trim() === "" ? undefined : given;
41
+ }
42
+ if (backend) {
43
+ return backend.text(q);
44
+ }
45
+ if (q.optional) {
46
+ return yes ? q.initial : undefined;
47
+ }
48
+ if (yes && q.initial !== undefined) {
49
+ return q.initial;
50
+ }
51
+ missing(q.name, `<${q.message.replace(/\?$/, "")}>`);
52
+ return q.initial ?? "";
53
+ },
54
+ async select(q) {
55
+ const given = flag(q.name);
56
+ const values = q.options.map((o) => o.value);
57
+ if (given !== undefined) {
58
+ if (!values.includes(given)) {
59
+ wrong(q.name, `"${given}" isn't one of ${values.join(", ")}`);
60
+ return q.options[0]?.value;
61
+ }
62
+ return given;
63
+ }
64
+ if (backend) {
65
+ return backend.select(q);
66
+ }
67
+ if (yes && q.initial !== undefined) {
68
+ return q.initial;
69
+ }
70
+ missing(q.name, values.join("|"));
71
+ return (q.initial ?? q.options[0]?.value);
72
+ },
73
+ async multiselect(q) {
74
+ const given = flag(q.name);
75
+ const values = q.options.map((o) => o.value);
76
+ if (given !== undefined) {
77
+ const chosen = list(given);
78
+ if (!q.allowOther) {
79
+ for (const value of chosen) {
80
+ if (!values.includes(value)) {
81
+ wrong(q.name, `"${value}" isn't one of ${values.join(", ")}`);
82
+ }
83
+ }
84
+ }
85
+ if (chosen.length === 0 && q.required !== false) {
86
+ wrong(q.name, "needs at least one value");
87
+ }
88
+ return chosen;
89
+ }
90
+ if (backend) {
91
+ return backend.multiselect(q);
92
+ }
93
+ if (yes && q.initial !== undefined) {
94
+ return q.initial;
95
+ }
96
+ if (q.required === false) {
97
+ return [];
98
+ }
99
+ missing(q.name, values.join(","));
100
+ return q.initial ?? [];
101
+ },
102
+ async confirm(q) {
103
+ if (flags[q.name] === true) {
104
+ return true;
105
+ }
106
+ if (flags[`no-${q.name}`] === true) {
107
+ return false;
108
+ }
109
+ if (backend) {
110
+ return backend.confirm(q);
111
+ }
112
+ if (yes && q.initial !== undefined) {
113
+ return q.initial;
114
+ }
115
+ missing(q.name, `or --no-${q.name}`);
116
+ return q.initial ?? false;
117
+ },
118
+ assertComplete() {
119
+ if (problems.length > 0) {
120
+ throw new MissingAnswers(problems);
121
+ }
122
+ },
123
+ };
124
+ }
125
+ /** A backend that answers from a script, recording what was asked. For tests. */
126
+ export function scriptedBackend(answers, asked = []) {
127
+ const answer = (q) => {
128
+ asked.push(q.name);
129
+ if (!(q.name in answers)) {
130
+ throw new Error(`the script has no answer for "${q.name}"`);
131
+ }
132
+ return answers[q.name];
133
+ };
134
+ return {
135
+ text: async (q) => answer(q),
136
+ select: async (q) => answer(q),
137
+ multiselect: async (q) => answer(q),
138
+ confirm: async (q) => answer(q),
139
+ };
140
+ }