// A VERB ROW'S FORM, AS ARGV (lane palette, L8a): the one function that turns // a row of the registry (lib/cli/verbs.mjs) and a form's values into the // words `umtool` is run with -- on the server by POST /api/cli (which never // takes argv from a page), and in the palette for its "Copy as CLI" line, so // the line copied is the command that runs. // // Pure, no imports: the route, the page and node --test read it alike. /** How the copied line names the CLI: from the repository's root. */ export const CLI_PREFIX = "node umtool/bin/umtool.mjs"; const STRING_MAX = 2000; const TEXT_MAX = 50_000; const LIST_MAX = 200; const PAIR_KEY = /^[A-Za-z_*][\w.*[\]<>-]*$/; const FLAG_KEY = /^[A-Za-z][\w-]*$/; const NUMBER = /^-?(\d+\.?\d*|\.\d+)$/; /** A bare file or id name: no directory, no `..`, no leading dot (`--out`, a take's id, a reel's name). */ const BARE = /^[A-Za-z0-9_][\w.+-]*$/; /** A `..` segment, a home or an absolute path inside a value: a page may not name a path outside the project. */ const ESCAPES = /(^|[\\/])\.\.([\\/]|$)|^~[\\/]|^[\\/]/; /** An `@file` reference anywhere in a value -- `@x`, `post-json:@x`, `a=@x`, `a,@x` (review, L8a): a CLI reads it. */ const AT_REF = /(^|[:=,;])\s*['"]?@/; /** A timeline entry's id (`timeline order`: an id, never a file the CLI would read from its cwd). */ const ENTRY_ID = /^[A-Za-z0-9_][\w:-]*$/; /** A share URL or a / (`new --from` from a page: never a file). */ const REF = /^(https?:\/\/\S+|[a-z0-9][a-z0-9_-]*\/[A-Za-z0-9_-]+)$/; const isFlag = (a) => a.name.startsWith("--"); const isRun = (a) => a.type === "list" || a.type === "pairs" || a.type === "flagpairs"; /** A list-shaped value: an array, or lines of a textarea. */ function linesOf(v) { if (Array.isArray(v)) return v.map((x) => String(x).trim()).filter(Boolean); if (typeof v === "string") return v.split(/\r?\n/).map((x) => x.trim()).filter(Boolean); return null; } /** Whether a form value is empty (left out of argv). */ function absent(a, v) { if (v === undefined || v === null || v === false) return true; if (a.type === "boolean" && (v === "false" || v === "off" || v === "")) return true; if (typeof v === "string") return a.type === "text" ? v.trim() === "" : v.trim() === ""; if (Array.isArray(v)) return v.length === 0 || (isRun(a) && linesOf(v).length === 0); return false; } class FormError extends Error { constructor(message, field) { super(message); this.field = field; } } /** One word of argv from a plain value: no NUL, bounded, and never read as a flag. */ function word(a, raw, { what = a.name, max = STRING_MAX, strictAt = atStrict(a) } = {}) { const s = String(raw); if (s.includes("\0")) throw new FormError(`${what}: a NUL byte`, a.name); if (s.length > max) throw new FormError(`${what}: longer than ${max} characters`, a.name); // `-` alone is a value (`--after -`); a negative number is a value; anything else that starts with a // dash would be read as a flag by umtool's parsers. if (/^-./.test(s) && !NUMBER.test(s.trim())) throw new FormError(`${what}: a value may not start with "-" (it would be read as a flag)`, a.name); // `@file` reads a file wherever it is: a terminal's, never a form's (paste what the file holds) -- at the start, // or inside a value a CLI splits (`post-json:@…`, `a=@…`, `a,@…`). if (strictAt && !a.allowAt && AT_REF.test(s)) throw new FormError(`${what}: @file reads a file -- from a terminal only; paste what it holds`, a.name); return s; } /** * Whether an arg's values are checked for `@file` anywhere: a positional (the CLIs that read `@file` read it from * a positional or a key=value), a list's items, a row's `atFile` arg. A flag's words and a positional's free prose * (`text`, not atFile) are a person's words ("@grok said …"); `allowAt` is a handle (`@grok`) or a lexicon word. */ function atStrict(a) { if (a.allowAt) return false; if (a.atFile) return true; if (a.type === "list" || a.type === "pairs") return true; return !isFlag(a) && a.type !== "text"; } /** A timeline entry's id: no dot, no slash -- never a file name. */ function entryId(a, raw) { const s = word(a, String(raw).trim()); if (!ENTRY_ID.test(s)) throw new FormError(`${a.name}: "${s}" is not an entry's id`, a.name); return s; } /** A bare name: one word, no directory. */ function bare(a, raw, what = a.name) { const s = word(a, String(raw).trim(), { what }); if (!BARE.test(s) || s.includes("..")) throw new FormError(`${what}: a bare name (letters, digits, . _ - +; no directory, no leading dot)`, a.name); return s; } /** A key=value value from a page: never `@file`, never a path out of the project. */ function pairValue(a, value, what) { const v = value.trim().replace(/^['"]/, ""); if (AT_REF.test(v)) throw new FormError(`${what}: @file reads a file -- from a terminal only; paste what it holds`, a.name); if (ESCAPES.test(v)) throw new FormError(`${what}: a path outside the project (.., ~ or /) -- from a terminal only`, a.name); return value; } /** One key=value word. */ function pairWord(a, line) { const at = line.indexOf("="); const key = at > 0 ? line.slice(0, at).trim() : ""; if (!PAIR_KEY.test(key)) throw new FormError(`${a.name}: "${line}" is not key=value`, a.name); return word(a, `${key}=${pairValue(a, line.slice(at + 1), key)}`, { max: TEXT_MAX }); } /** A share URL or a /: never a file. */ function refWord(a, raw) { const s = word(a, raw); if (!REF.test(s)) throw new FormError(`${a.name}: a share URL or / (a file only from a terminal)`, a.name); return s; } /** The words one arg's value makes, flag included. */ function wordsOf(a, v) { const flag = isFlag(a) ? [a.name] : []; switch (a.type) { case "boolean": { if (v === true || v === "true" || v === "on") return flag; throw new FormError(`${a.name}: on or off`, a.name); } case "number": { const s = String(v).trim(); if (!NUMBER.test(s) || !Number.isFinite(Number(s))) throw new FormError(`${a.name}: a number`, a.name); return [...flag, s]; } case "choice": { const s = String(v).trim(); if (!(a.choices ?? []).includes(s)) throw new FormError(`${a.name}: one of ${(a.choices ?? []).join(", ")}`, a.name); return [...flag, s]; } case "json": { const s = String(v); try { JSON.parse(s); } catch { throw new FormError(`${a.name}: not JSON`, a.name); } return [...flag, word(a, s, { max: TEXT_MAX })]; } case "text": return [...flag, word(a, String(v), { max: TEXT_MAX })]; case "project": case "string": return [...flag, word(a, String(v).trim())]; case "name": if (a.literals?.includes(String(v).trim())) return [...flag, String(v).trim()]; return [...flag, bare(a, v)]; case "path": { // A file of the project, relative to its directory. The SERVER confines it (realpath inside the // project: app/api/cli/route.ts) and runs it as the absolute path it found; here it is one word. const s = word(a, String(v).trim()); if (a.literals?.includes(s)) return [...flag, s]; if (s.startsWith("@")) throw new FormError(`${a.name}: a file of the project, by its path (no @)`, a.name); return [...flag, s]; } case "ref": return [...flag, refWord(a, String(v).trim())]; case "list": case "pairs": case "flagpairs": { const lines = linesOf(v); if (!lines) throw new FormError(`${a.name}: one value per line`, a.name); if (lines.length > LIST_MAX) throw new FormError(`${a.name}: more than ${LIST_MAX} values`, a.name); const out = []; for (const line of lines) { if (a.type === "list") { const w = a.item === "id" ? entryId(a, line) : a.item === "name" ? bare(a, line) : a.item === "pair" ? pairWord(a, line) : a.item === "ref" ? refWord(a, line) : word(a, line); out.push(...(isFlag(a) ? [a.name, w] : [w])); continue; } const at = line.indexOf("="); const key = at > 0 ? line.slice(0, at).trim() : ""; if (a.type === "pairs") { out.push(pairWord(a, line)); } else { if (!FLAG_KEY.test(key)) throw new FormError(`${a.name}: "${line}" is not key=value`, a.name); out.push(`--${key}`, word(a, pairValue(a, line.slice(at + 1).trim(), `--${key}`), { what: `--${key}`, max: TEXT_MAX })); } } return out; } default: throw new FormError(`${a.name}: an arg of unknown type ${a.type}`, a.name); } } /** * A row and a form's values to argv (the words after `umtool`). * * @param {{ verb: string, args: Array>, shape?: string }} row * @param {Record} values name -> string | number | boolean | string[] * @returns {{ ok: true, argv: string[] } | { ok: false, error: string, field?: string }} */ export function buildArgv(row, values = {}) { try { if (!values || typeof values !== "object" || Array.isArray(values)) throw new FormError("the values are an object of name: value"); const args = row.args ?? []; const known = new Set(args.map((a) => a.name)); for (const k of Object.keys(values)) if (!known.has(k)) throw new FormError(`umtool ${row.verb} takes no "${k}"`, k); for (const k of Object.keys(values)) { const v = values[k]; const ok = v === null || ["string", "number", "boolean"].includes(typeof v) || (Array.isArray(v) && v.every((x) => typeof x === "string")); if (!ok) throw new FormError(`${k}: a string, a number, on/off or a list of strings`, k); } const given = (a) => !absent(a, values[a.name]); for (const a of args) if (a.required && !given(a)) throw new FormError(`${a.name} is required`, a.name); // An empty optional positional before a given one would shift every word after it. const positionals = args.filter((a) => !isFlag(a)); const plain = positionals.filter((a) => a.type !== "pairs"); for (let i = 0; i < plain.length; i += 1) { if (!given(plain[i]) && plain.slice(i + 1).some(given)) { throw new FormError(`${plain[i].name} is needed before ${plain.slice(i + 1).find(given).name}`, plain[i].name); } } const argv = []; const placed = new Set(); const shape = (row.shape ?? row.verb).split(/\s+/).filter(Boolean); for (const t of shape) { const m = /^<(.+)>$/.exec(t); if (!m) { argv.push(t); continue; } const a = positionals.find((x) => x.name === m[1]); if (!a) throw new FormError(`the shape of ${row.verb} names <${m[1]}>, which is not one of its args`); placed.add(a.name); if (given(a)) argv.push(...wordsOf(a, values[a.name])); } for (const a of positionals) if (!placed.has(a.name) && given(a)) argv.push(...wordsOf(a, values[a.name])); for (const a of args) if (isFlag(a) && given(a)) argv.push(...wordsOf(a, values[a.name])); return { ok: true, argv }; } catch (e) { if (e instanceof FormError) return { ok: false, error: e.message, ...(e.field ? { field: e.field } : {}) }; throw e; } } /** A word as a POSIX shell reads it back. */ export function shellQuote(s) { const v = String(s); if (v !== "" && /^[\w@%+=:,./-]+$/.test(v)) return v; return `'${v.replace(/'/g, `'\\''`)}'`; } /** The line to paste into a terminal at the repository's root. */ export const cliLine = (argv) => [CLI_PREFIX, ...argv.map(shellQuote)].join(" "); /** The row's arguments as a usage line reads them: ` [--start N] [--lock]`. */ export function synopsis(row) { const args = row.args ?? []; const meta = (a) => a.type === "choice" ? (a.choices ?? []).join("|") : a.type === "number" ? "N" : a.type === "json" ? "JSON" : a.name.replace(/^--/, "").toUpperCase(); const one = (a) => { if (a.type === "pairs") return a.required ? "key=value…" : "[key=value…]"; if (a.type === "flagpairs") return a.required ? "--key value…" : "[--key value…]"; if (!isFlag(a)) { const w = a.type === "choice" ? (a.choices ?? []).join("|") : `<${a.name}>`; const s = a.type === "list" ? `${w}…` : w; return a.required ? s : `[${s}]`; } const s = a.type === "boolean" ? a.name : `${a.name} ${meta(a)}${a.type === "list" ? "…" : ""}`; return a.required ? s : `[${s}]`; }; const positionals = args.filter((a) => !isFlag(a)); const placed = new Set(); const head = (row.shape ?? row.verb).split(/\s+/).filter(Boolean).map((t) => { const m = /^<(.+)>$/.exec(t); const a = m && positionals.find((x) => x.name === m[1]); if (!a) return t; placed.add(a.name); return one(a); }); return [...head, ...positionals.filter((a) => !placed.has(a.name)).map(one), ...args.filter(isFlag).map(one)].join(" "); } /** * Whether these values make the row do something with no undo (a row's `confirm`): the sentence to * confirm with, or null. `confirm: { what, when?: [arg names, any of them given], unless?: [arg names] }`; * no `when`: always. * @returns {string | null} */ export function confirmOf(row, values = {}) { const c = row.confirm; if (!c) return null; const args = row.args ?? []; const given = (name) => { const a = args.find((x) => x.name === name); return !!a && !absent(a, values?.[name]); }; if (c.unless?.some(given)) return null; if (c.when && !c.when.some(given)) return null; return c.what; } /** The row's path args a page gave: the server confines each. */ export function pathArgsOf(row, values = {}) { return (row.args ?? []).filter((a) => a.type === "path" && !absent(a, values?.[a.name]) && !a.literals?.includes(String(values[a.name]).trim())); }