@docsxai/engine 0.3.0-rc.1 → 0.3.0-rc.2

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.
@@ -9,7 +9,6 @@
9
9
  // diff — drift report against a baseline (the after-vs-before)
10
10
  import { promises as fs } from "node:fs";
11
11
  import * as path from "node:path";
12
- import { FlowFileError } from "./flow-file.js";
13
12
  import { diffDocPacks, formatDriftReportMarkdown, formatDriftReportText, severityAtLeast, } from "./diff.js";
14
13
  import { projectDocPackToAdf } from "./export/adf.js";
15
14
  import { exportWorkspaceFlowsAsPlaywrightTests } from "./export/playwright-test.js";
@@ -17,16 +16,18 @@ import { runViewerBin } from "./viewer-bin.js";
17
16
  import { ZipError, zipDocPack } from "./zip.js";
18
17
  import { resolveWorkspacePath } from "./workspace.js";
19
18
  import { parseFlags } from "./cli-shared.js";
20
- import { USAGE } from "./cli-usage.js";
19
+ import { shellQuote, usageError, withNext } from "./cli-messages.js";
21
20
  export async function cmdRender(args) {
22
21
  const { positionals } = parseFlags(args);
23
22
  const projectDir = positionals[0];
24
- if (!projectDir) {
25
- process.stderr.write("render: missing <project-dir>\n\n" + USAGE + "\n");
26
- return 2;
27
- }
23
+ if (!projectDir)
24
+ return usageError("render", "missing <workspace-dir>");
28
25
  const docsDir = resolveWorkspacePath(projectDir, "docs");
29
26
  const outDir = resolveWorkspacePath(projectDir, ".viewer");
27
+ if (!(await fs.stat(docsDir).then((s) => s.isDirectory(), () => false))) {
28
+ const note = withNext(`warning — ${docsDir} does not exist, so the viewer will be empty`, `docsxai run ${shellQuote(projectDir)}`);
29
+ process.stderr.write(`render: ${note}\n`);
30
+ }
30
31
  const code = await runViewerBin("render", ["build", docsDir, outDir]);
31
32
  if (code === 0) {
32
33
  process.stdout.write(`render: open ${path.join(outDir, "index.html")} (the index links the flows; each flow page shows the screenshots — hover a pulsing halo to read its callout)\n`);
@@ -78,13 +79,12 @@ function parseBurnArgs(args) {
78
79
  */
79
80
  export async function cmdBurn(args) {
80
81
  const parsed = parseBurnArgs(args);
81
- if (typeof parsed === "string") {
82
- process.stderr.write(`burn: ${parsed}\n\n${USAGE}\n`);
83
- return 2;
84
- }
82
+ if (typeof parsed === "string")
83
+ return usageError("burn", parsed);
85
84
  const docsDir = resolveWorkspacePath(parsed.workspace, "docs");
86
85
  if (!(await fs.stat(docsDir).then((s) => s.isDirectory(), () => false))) {
87
- process.stderr.write(`burn: ${parsed.workspace} has no docs/ directory (expected ${docsDir}). Run \`docsxai run\` first.\n`);
86
+ const note = withNext(`${parsed.workspace} has no docs/ directory (expected ${docsDir})`, `docsxai run ${shellQuote(parsed.workspace)}`);
87
+ process.stderr.write(`burn: ${note}\n`);
88
88
  return 1;
89
89
  }
90
90
  return runViewerBin("burn", [
@@ -98,10 +98,8 @@ export async function cmdBurn(args) {
98
98
  }
99
99
  export async function cmdZip(args) {
100
100
  const { positionals, flags } = parseFlags(args);
101
- if (!positionals[0]) {
102
- process.stderr.write(`zip: missing <workspace-dir>\n`);
103
- return 2;
104
- }
101
+ if (!positionals[0])
102
+ return usageError("zip", "missing <workspace-dir>");
105
103
  const projectDir = positionals[0];
106
104
  const output = typeof flags.get("out") === "string"
107
105
  ? flags.get("out")
@@ -115,7 +113,12 @@ export async function cmdZip(args) {
115
113
  }
116
114
  catch (e) {
117
115
  if (e instanceof ZipError) {
118
- process.stderr.write(`zip: ${e.message}\n`);
116
+ const next = /nothing to zip/.test(e.message)
117
+ ? `docsxai run ${shellQuote(projectDir)}`
118
+ : /doesn't exist/.test(e.message)
119
+ ? `docsxai init ${shellQuote(projectDir)} (or fix the path)`
120
+ : undefined;
121
+ process.stderr.write(`zip: ${next ? withNext(e.message, next) : e.message}\n`);
119
122
  return 1;
120
123
  }
121
124
  throw e;
@@ -129,23 +132,21 @@ export async function cmdExport(args) {
129
132
  case "playwright":
130
133
  return cmdExportPlaywright(rest);
131
134
  default:
132
- process.stderr.write(`export: unknown format "${format ?? ""}" — supported: adf, playwright\n`);
133
- return 2;
135
+ return usageError("export", format === undefined
136
+ ? "missing format — supported: adf, playwright"
137
+ : `unknown format "${format}" — supported: adf, playwright`);
134
138
  }
135
139
  }
136
140
  async function cmdExportAdf(rest) {
137
141
  const { positionals, flags } = parseFlags(rest);
138
- if (!positionals[0]) {
139
- process.stderr.write(`export adf: missing <workspace-dir>\n`);
140
- return 2;
141
- }
142
+ if (!positionals[0])
143
+ return usageError("export adf", "missing <workspace-dir>");
142
144
  const projectDir = positionals[0];
143
145
  const modeFlag = flags.get("mode");
144
146
  let mode = "single";
145
147
  if (typeof modeFlag === "string") {
146
148
  if (modeFlag !== "single" && modeFlag !== "page-tree") {
147
- process.stderr.write(`export adf: --mode must be "single" or "page-tree" (got "${modeFlag}")\n`);
148
- return 2;
149
+ return usageError("export adf", `--mode must be "single" or "page-tree" (got "${modeFlag}")`);
149
150
  }
150
151
  mode = modeFlag;
151
152
  }
@@ -175,16 +176,14 @@ async function cmdExportAdf(rest) {
175
176
  return 0;
176
177
  }
177
178
  catch (e) {
178
- process.stderr.write(`export adf: ${e.message}\n`);
179
+ process.stderr.write(`export adf: ${withNext(e.message, `docsxai lint ${shellQuote(projectDir)}`)}\n`);
179
180
  return 1;
180
181
  }
181
182
  }
182
183
  async function cmdExportPlaywright(rest) {
183
184
  const { positionals, flags } = parseFlags(rest);
184
- if (!positionals[0]) {
185
- process.stderr.write(`export playwright: missing <workspace-dir>\n`);
186
- return 2;
187
- }
185
+ if (!positionals[0])
186
+ return usageError("export playwright", "missing <workspace-dir>");
188
187
  const projectDir = positionals[0];
189
188
  const flow = flags.get("flow");
190
189
  const outFlag = flags.get("out");
@@ -204,11 +203,7 @@ async function cmdExportPlaywright(rest) {
204
203
  return 0;
205
204
  }
206
205
  catch (e) {
207
- if (e instanceof FlowFileError) {
208
- process.stderr.write(`export playwright: ${e.message}\n`);
209
- return 1;
210
- }
211
- process.stderr.write(`export playwright: ${e.message}\n`);
206
+ process.stderr.write(`export playwright: ${withNext(e.message, `docsxai lint ${shellQuote(projectDir)}`)}\n`);
212
207
  return 1;
213
208
  }
214
209
  }
@@ -226,10 +221,8 @@ async function copyIfExists(src, dest) {
226
221
  }
227
222
  export async function cmdBaseline(args) {
228
223
  const { positionals, flags } = parseFlags(args);
229
- if (!positionals[0]) {
230
- process.stderr.write(`baseline: missing <workspace-dir>\n`);
231
- return 2;
232
- }
224
+ if (!positionals[0])
225
+ return usageError("baseline", "missing <workspace-dir>");
233
226
  const projectDir = positionals[0];
234
227
  const outFlag = flags.get("out");
235
228
  const outDir = typeof outFlag === "string"
@@ -268,6 +261,10 @@ export async function cmdBaseline(args) {
268
261
  }
269
262
  }
270
263
  process.stdout.write(`baseline: snapshotted ${copied} file${copied === 1 ? "" : "s"} to ${outDir}\n`);
264
+ if (copied === 0) {
265
+ const note = withNext("warning — no flows/ or docs/ files found to snapshot", `docsxai run ${shellQuote(projectDir)}`);
266
+ process.stderr.write(`baseline: ${note}\n`);
267
+ }
271
268
  return 0;
272
269
  }
273
270
  catch (e) {
@@ -277,10 +274,8 @@ export async function cmdBaseline(args) {
277
274
  }
278
275
  export async function cmdDiff(args) {
279
276
  const { positionals, flags } = parseFlags(args);
280
- if (!positionals[0]) {
281
- process.stderr.write(`diff: missing <workspace-dir>\n`);
282
- return 2;
283
- }
277
+ if (!positionals[0])
278
+ return usageError("diff", "missing <workspace-dir>");
284
279
  const projectDir = positionals[0];
285
280
  const againstFlag = flags.get("against");
286
281
  const againstDir = typeof againstFlag === "string"
@@ -288,15 +283,13 @@ export async function cmdDiff(args) {
288
283
  : resolveWorkspacePath(projectDir, ".baseline");
289
284
  const format = typeof flags.get("format") === "string" ? flags.get("format") : "text";
290
285
  if (format !== "json" && format !== "md" && format !== "text") {
291
- process.stderr.write(`diff: --format must be json | md | text (got "${format}")\n`);
292
- return 2;
286
+ return usageError("diff", `--format must be json | md | text (got "${format}")`);
293
287
  }
294
288
  const failOnFlag = flags.get("fail-on");
295
289
  let failOn = null;
296
290
  if (failOnFlag !== undefined) {
297
291
  if (failOnFlag !== "warn" && failOnFlag !== "fail") {
298
- process.stderr.write(`diff: --fail-on must be warn | fail (got "${String(failOnFlag)}")\n`);
299
- return 2;
292
+ return usageError("diff", `--fail-on must be warn | fail (got "${String(failOnFlag)}")`);
300
293
  }
301
294
  failOn = failOnFlag;
302
295
  }
@@ -304,7 +297,8 @@ export async function cmdDiff(args) {
304
297
  await fs.access(path.join(againstDir, "flows"));
305
298
  }
306
299
  catch {
307
- process.stderr.write(`diff: no baseline at ${againstDir} — run \`docsxai baseline ${projectDir}\` first (or pass --against <dir>)\n`);
300
+ const note = withNext(`no baseline at ${againstDir}`, `docsxai baseline ${shellQuote(projectDir)} (or pass --against <dir>)`);
301
+ process.stderr.write(`diff: ${note}\n`);
308
302
  return 2;
309
303
  }
310
304
  try {
@@ -3,7 +3,7 @@
3
3
  // committed pack. The logic lives in `@docsxai/viewer` (it owns the burner); like `burn`, these
4
4
  // validate the argv edge and run the viewer's command through the shared bin resolution, so the
5
5
  // engine still does not depend on the viewer.
6
- import { USAGE } from "./cli-usage.js";
6
+ import { usageError } from "./cli-messages.js";
7
7
  import { runViewerBin } from "./viewer-bin.js";
8
8
  /** Parse argv against a spec. Returns the argv to pass on (flags in the order given) or the usage-error message. */
9
9
  function checkArgs(args, spec) {
@@ -33,10 +33,6 @@ function checkArgs(args, spec) {
33
33
  return `unexpected argument "${positionals[1]}"`;
34
34
  return { dir: positionals[0], rest };
35
35
  }
36
- function usageError(command, message) {
37
- process.stderr.write(`${command}: ${message}\n\n${USAGE}\n`);
38
- return 2;
39
- }
40
36
  /** `pack` — burn, optimise, hash-name and write the screenshot pack; with `--check`, compare instead of write. */
41
37
  export async function cmdPack(args) {
42
38
  if (args.includes("--check"))
@@ -20,7 +20,8 @@ import { listFlowFiles, parseFlags } from "./cli-shared.js";
20
20
  import { emitVerifyReport, parseVerifyArgs } from "./cli-verify.js";
21
21
  import { verifyDeterminism } from "./verify-determinism.js";
22
22
  import { VerifyTreeError } from "./verify-tree.js";
23
- import { USAGE } from "./cli-usage.js";
23
+ import { shellQuote, usageError, withNext } from "./cli-messages.js";
24
+ import { reportRun } from "./cli-run-summary.js";
24
25
  async function loadAuthStorageState(projectDir) {
25
26
  const descriptorPath = resolveWorkspacePath(projectDir, "auth", "strategy.yaml");
26
27
  let text;
@@ -35,17 +36,14 @@ async function loadAuthStorageState(projectDir) {
35
36
  const cache = await resolveStateCache(descriptor.roles[role], projectDir);
36
37
  const state = await cache.load(role);
37
38
  if (!state) {
38
- throw new Error(`auth/strategy.yaml configures role "${role}" but no valid cached session was found at ${path.join(projectDir, ".auth", role + ".json")}.\n` +
39
- `Capture one first (calibration's auth step, e.g. the manual-capture flow).`);
39
+ throw new Error(withNext(`auth/strategy.yaml configures role "${role}" but there is no valid cached session at ${path.join(projectDir, ".auth", role + ".json")} (missing or expired)`, `docsxai capture-auth ${shellQuote(projectDir)}`));
40
40
  }
41
41
  return state;
42
42
  }
43
43
  export async function cmdRun(args) {
44
44
  const { positionals, flags } = parseFlags(args);
45
- if (!positionals[0]) {
46
- process.stderr.write("run: missing <project-dir>\n\n" + USAGE + "\n");
47
- return 2;
48
- }
45
+ if (!positionals[0])
46
+ return usageError("run", "missing <workspace-dir>");
49
47
  const projectDir = positionals[0];
50
48
  const onlyFlow = typeof flags.get("flow") === "string" ? flags.get("flow") : undefined;
51
49
  const stopAfter = typeof flags.get("stop-after") === "string" ? flags.get("stop-after") : undefined;
@@ -55,14 +53,11 @@ export async function cmdRun(args) {
55
53
  const pause = flags.get("pause") === true;
56
54
  const headed = flags.get("headed") === true || pause; // --pause implies --headed
57
55
  if (startFrom && !onlyFlow) {
58
- process.stderr.write(`run: --start-from requires --flow <name> (single-flow calibration aid)\n`);
59
- return 2;
56
+ return usageError("run", "--start-from requires --flow <name> (single-flow calibration aid)");
60
57
  }
61
58
  const verify = parseVerifyArgs(flags);
62
- if (typeof verify === "string") {
63
- process.stderr.write(`run: ${verify}\n\n${USAGE}\n`);
64
- return 2;
65
- }
59
+ if (typeof verify === "string")
60
+ return usageError("run", verify);
66
61
  const wsCfg = await loadWorkspaceConfig(projectDir);
67
62
  const baseURL = (typeof flags.get("base-url") === "string" ? flags.get("base-url") : undefined) ??
68
63
  wsCfg?.app_url;
@@ -91,6 +86,7 @@ export async function cmdRun(args) {
91
86
  const flows = [];
92
87
  const units = [];
93
88
  const matrixFlows = new Set();
89
+ const knownFlows = [];
94
90
  let flowCount = 0;
95
91
  for (const fp of flowPaths) {
96
92
  let flow;
@@ -102,11 +98,12 @@ export async function cmdRun(args) {
102
98
  }
103
99
  catch (e) {
104
100
  if (e instanceof FlowFileError) {
105
- process.stderr.write(`run: ${e.message}\n`);
101
+ process.stderr.write(`run: ${withNext(e.message, `docsxai lint ${shellQuote(projectDir)}`)}\n`);
106
102
  return 1;
107
103
  }
108
104
  throw e;
109
105
  }
106
+ knownFlows.push(flow.name);
110
107
  if (onlyFlow && flow.name !== onlyFlow)
111
108
  continue;
112
109
  flowCount++;
@@ -117,8 +114,8 @@ export async function cmdRun(args) {
117
114
  }
118
115
  if (flowCount === 0) {
119
116
  process.stderr.write(onlyFlow
120
- ? `run: no flow named "${onlyFlow}"\n`
121
- : `run: no flow-files in ${projectDir}/flows\n`);
117
+ ? `run: no flow named "${onlyFlow}" (flows: ${knownFlows.join(", ") || "none"})\n`
118
+ : `run: ${withNext(`no flow-files in ${projectDir}/flows`, `docsxai calibrate ${shellQuote(projectDir)} --from <flow.yaml>`)}\n`);
122
119
  return 1;
123
120
  }
124
121
  try {
@@ -209,6 +206,7 @@ export async function cmdRun(args) {
209
206
  progress: (line) => process.stdout.write(line),
210
207
  });
211
208
  const anyFailed = failures.length > 0;
209
+ reportRun({ projectDir, noun, total: units.length, okCount, failures });
212
210
  // Backend-bound workspaces get a run record appended; offline-tolerant (warn, never fail the run).
213
211
  const history = await recordRunHistory({
214
212
  workspaceDir: projectDir,
@@ -224,16 +222,13 @@ export async function cmdRun(args) {
224
222
  export async function cmdCaptureAuth(args) {
225
223
  const { positionals, flags } = parseFlags(args);
226
224
  const projectDir = positionals[0];
227
- if (!projectDir) {
228
- process.stderr.write("capture-auth: missing <project-dir>\n\n" + USAGE + "\n");
229
- return 2;
230
- }
225
+ if (!projectDir)
226
+ return usageError("capture-auth", "missing <workspace-dir>");
231
227
  const wsCfg = await loadWorkspaceConfig(projectDir);
232
228
  const baseURL = (typeof flags.get("base-url") === "string" ? flags.get("base-url") : undefined) ??
233
229
  wsCfg?.app_url;
234
230
  if (!baseURL) {
235
- process.stderr.write("capture-auth: --base-url <url> is required (or set app_url in the workspace's .docsxai.json)\n");
236
- return 2;
231
+ return usageError("capture-auth", "--base-url <url> is required (or set app_url in the workspace's .docsxai.json)");
237
232
  }
238
233
  const headless = flags.get("headless") === true;
239
234
  const ignoreHTTPSErrors = flags.get("ignore-https-errors") === true || !!wsCfg?.ignore_https_errors;
@@ -248,7 +243,7 @@ export async function cmdCaptureAuth(args) {
248
243
  descriptorText = await fs.readFile(descriptorPath, "utf8");
249
244
  }
250
245
  catch {
251
- process.stderr.write(`capture-auth: no auth descriptor at ${descriptorPath}\n`);
246
+ process.stderr.write(`capture-auth: ${withNext(`no auth descriptor at ${descriptorPath}`, "write auth/strategy.yaml (`docsxai init <new-dir>` scaffolds an example to copy)")}\n`);
252
247
  return 1;
253
248
  }
254
249
  let role;
@@ -261,7 +256,8 @@ export async function cmdCaptureAuth(args) {
261
256
  : descriptor.default_role;
262
257
  const ra = descriptor.roles[role];
263
258
  if (!ra) {
264
- process.stderr.write(`capture-auth: role "${role}" not in ${descriptorPath}\n`);
259
+ const roles = Object.keys(descriptor.roles).join(", ");
260
+ process.stderr.write(`capture-auth: role "${role}" not in ${descriptorPath} (roles: ${roles}); pass --role <name>\n`);
265
261
  return 1;
266
262
  }
267
263
  roleAuth = ra;
@@ -320,10 +316,8 @@ export async function cmdInit(args) {
320
316
  const { positionals, flags } = parseFlags(args);
321
317
  const persistTmp = flags.get("persist") === "tmp";
322
318
  const dir = positionals[0];
323
- if (!persistTmp && !dir) {
324
- process.stderr.write("init: missing <workspace-dir> (or use --persist tmp)\n\n" + USAGE + "\n");
325
- return 2;
326
- }
319
+ if (!persistTmp && !dir)
320
+ return usageError("init", "missing <workspace-dir> (or use --persist tmp)");
327
321
  const str = (k) => typeof flags.get(k) === "string" ? flags.get(k) : undefined;
328
322
  const auth = str("auth");
329
323
  if (auth !== undefined && auth !== "manual-capture" && auth !== "none") {
@@ -353,33 +347,31 @@ export async function cmdInit(args) {
353
347
  force: flags.get("force") === true,
354
348
  });
355
349
  process.stdout.write(`init: workspace ${r.ephemeral ? "(ephemeral) " : ""}at ${r.dir}\n created: ${r.created.join(", ")}\n`);
356
- process.stdout.write(` next: ${appUrl ? "" : "(set app_url in .docsxai.json, then) "}docsxai capture-auth ${r.dir} → …calibrate… → docsxai run ${r.dir} → docsxai render ${r.dir}\n`);
350
+ process.stdout.write(` next: ${appUrl ? "" : "(set app_url in .docsxai.json, then) "}docsxai capture-auth ${shellQuote(r.dir)} → …calibrate… → docsxai run ${shellQuote(r.dir)} → docsxai render ${shellQuote(r.dir)}\n`);
357
351
  return 0;
358
352
  }
359
353
  catch (e) {
360
- process.stderr.write(`init: ${e.message}\n`);
354
+ process.stderr.write(`init: ${e.message.replace(/^init: /, "")}\n`);
361
355
  return 1;
362
356
  }
363
357
  }
364
358
  export async function cmdCalibrate(args) {
365
359
  const { positionals, flags } = parseFlags(args);
366
360
  const workspaceDir = positionals[0];
367
- if (!workspaceDir) {
368
- process.stderr.write("calibrate: missing <workspace-dir>\n\n" + USAGE + "\n");
369
- return 2;
370
- }
361
+ if (!workspaceDir)
362
+ return usageError("calibrate", "missing <workspace-dir>");
371
363
  const from = typeof flags.get("from") === "string" ? flags.get("from") : undefined;
372
364
  if (!from) {
373
- process.stderr.write("calibrate: --from <flow.md|.yaml> is required (the structured flow-guide)\n");
374
- return 2;
365
+ return usageError("calibrate", "--from <flow.md|.yaml> is required (the structured flow-guide)");
375
366
  }
376
367
  const flowName = typeof flags.get("name") === "string" ? flags.get("name") : undefined;
377
368
  let text;
378
369
  try {
379
370
  text = await fs.readFile(from, "utf8");
380
371
  }
381
- catch {
382
- process.stderr.write(`calibrate: cannot read ${from}\n`);
372
+ catch (e) {
373
+ const code = e.code ?? "unreadable";
374
+ process.stderr.write(`calibrate: cannot read ${from} (${code}); check the path\n`);
383
375
  return 1;
384
376
  }
385
377
  try {
@@ -392,11 +384,11 @@ export async function cmdCalibrate(args) {
392
384
  process.stdout.write(`calibrate: wrote ${r.flowFilePath} (${r.flow.steps.length} steps)\n`);
393
385
  if (r.wroteStyle)
394
386
  process.stdout.write(`calibrate: wrote default ${r.stylePath}\n`);
395
- process.stdout.write(` next: docsxai run ${workspaceDir} (then: docsxai render ${workspaceDir})\n`);
387
+ process.stdout.write(` next: docsxai run ${shellQuote(workspaceDir)} (then: docsxai render ${shellQuote(workspaceDir)})\n`);
396
388
  return 0;
397
389
  }
398
390
  catch (e) {
399
- process.stderr.write(`calibrate: ${e.message}\n`);
391
+ process.stderr.write(`calibrate: ${withNext(e.message, `fix ${shellQuote(from)}, then docsxai calibrate ${shellQuote(workspaceDir)} --from ${shellQuote(from)}`)}\n`);
400
392
  return 1;
401
393
  }
402
394
  }
@@ -0,0 +1,17 @@
1
+ /** The usage lines of the command named by the first word of `label` (`pack --check` gives both `pack` lines). */
2
+ export declare function commandUsage(label: string): string[];
3
+ /** Print `<label>: <message>`, the command's usage line and a pointer to `--help` on stderr. Returns exit code 2. */
4
+ export declare function usageError(label: string, message: string): number;
5
+ /**
6
+ * `text` with every C0 control character, DEL and C1 control character removed, so text that came
7
+ * from a backend or a flow file cannot move the cursor, recolour the terminal or set its title. A
8
+ * newline, carriage return or tab becomes a space, so the text stays on its own line. With
9
+ * `multiline`, newlines and tabs are kept (the carriage return is still dropped).
10
+ */
11
+ export declare function sanitizeForTerminal(text: string, multiline?: boolean): string;
12
+ /** `value` as one shell word: left bare when it is made of safe characters, else single-quoted. */
13
+ export declare function shellQuote(value: string): string;
14
+ /** `message` followed by the indented line naming the command to run next. */
15
+ export declare function withNext(message: string, next: string): string;
16
+ /** `raw` without user:password, query or fragment, for printing a URL the operator typed. */
17
+ export declare function redactUrl(raw: string): string;
@@ -0,0 +1,80 @@
1
+ // Shared wording for CLI errors. A failing command says what failed, why, and the next command to
2
+ // run, in that order, on `<command>: ` lines with an indented `next:` line. Usage errors show the
3
+ // failing command's own usage line instead of the whole help text. Leaf: imports only the help text.
4
+ import { USAGE } from "./cli-usage.js";
5
+ /** The `Usage:` entries of `docsxai --help`, one whitespace-normalised line per entry. */
6
+ function usageEntries() {
7
+ const start = USAGE.indexOf("Usage:\n");
8
+ const end = USAGE.indexOf("\n\nNotes:");
9
+ if (start < 0 || end < 0)
10
+ return [];
11
+ const entries = [];
12
+ for (const line of USAGE.slice(start + "Usage:\n".length, end).split("\n")) {
13
+ if (/^ {2}docsxai /.test(line))
14
+ entries.push(line.trim());
15
+ else if (entries.length > 0)
16
+ entries[entries.length - 1] += ` ${line.trim()}`;
17
+ }
18
+ return entries.map((e) => e.replace(/\s+/g, " "));
19
+ }
20
+ /** The usage lines of the command named by the first word of `label` (`pack --check` gives both `pack` lines). */
21
+ export function commandUsage(label) {
22
+ const name = label.split(" ")[0];
23
+ return usageEntries().filter((e) => e.split(" ")[1] === name);
24
+ }
25
+ /** Print `<label>: <message>`, the command's usage line and a pointer to `--help` on stderr. Returns exit code 2. */
26
+ export function usageError(label, message) {
27
+ const lines = commandUsage(label).map((l, i) => `${i === 0 ? "usage: " : " "}${l}\n`);
28
+ process.stderr.write(`${label}: ${message}\n${lines.join("")}run \`docsxai --help\` for every flag and an example\n`);
29
+ return 2;
30
+ }
31
+ function isControl(code) {
32
+ return code < 0x20 || (code >= 0x7f && code <= 0x9f);
33
+ }
34
+ /**
35
+ * `text` with every C0 control character, DEL and C1 control character removed, so text that came
36
+ * from a backend or a flow file cannot move the cursor, recolour the terminal or set its title. A
37
+ * newline, carriage return or tab becomes a space, so the text stays on its own line. With
38
+ * `multiline`, newlines and tabs are kept (the carriage return is still dropped).
39
+ */
40
+ export function sanitizeForTerminal(text, multiline = false) {
41
+ let out = "";
42
+ for (const ch of text) {
43
+ const code = ch.codePointAt(0);
44
+ if (code === 0x0a || code === 0x09)
45
+ out += multiline ? ch : " ";
46
+ else if (code === 0x0d)
47
+ out += multiline ? "" : " ";
48
+ else if (!isControl(code))
49
+ out += ch;
50
+ }
51
+ return out;
52
+ }
53
+ /** `value` as one shell word: left bare when it is made of safe characters, else single-quoted. */
54
+ export function shellQuote(value) {
55
+ const v = sanitizeForTerminal(value);
56
+ return /^[\w./@:+-]+$/.test(v) ? v : `'${v.replace(/'/g, "'\\''")}'`;
57
+ }
58
+ /** `message` followed by the indented line naming the command to run next. */
59
+ export function withNext(message, next) {
60
+ return `${sanitizeForTerminal(message, true)}\n next: ${sanitizeForTerminal(next)}`;
61
+ }
62
+ /** `raw` without user:password, query or fragment, for printing a URL the operator typed. */
63
+ export function redactUrl(raw) {
64
+ const invalid = "<invalid url>";
65
+ try {
66
+ const u = new URL(raw);
67
+ // An `@` in the path means the operator's userinfo held a `/` (or `\`): the URL parser read
68
+ // everything after it as a path, so the secret sits in the pathname.
69
+ if (u.pathname.includes("@"))
70
+ return invalid;
71
+ u.username = "";
72
+ u.password = "";
73
+ u.search = "";
74
+ u.hash = "";
75
+ return sanitizeForTerminal(u.toString().replace(/\/$/, ""));
76
+ }
77
+ catch {
78
+ return invalid;
79
+ }
80
+ }
@@ -0,0 +1,15 @@
1
+ import { type FlowFailure } from "./run-flows.js";
2
+ export interface RunSummaryInput {
3
+ projectDir: string;
4
+ /** `flows` or `flow variants`. */
5
+ noun: string;
6
+ /** How many units were attempted. */
7
+ total: number;
8
+ okCount: number;
9
+ failures: FlowFailure[];
10
+ }
11
+ /** The command to run for a failure: `diagnose` for a halted step, `doctor` when the browser never started. */
12
+ export declare function nextForFailure(projectDir: string, f: FlowFailure): string;
13
+ export declare function formatRunSummary(input: RunSummaryInput): string;
14
+ /** Write the summary on the stream that fits the outcome. */
15
+ export declare function reportRun(input: RunSummaryInput): void;
@@ -0,0 +1,33 @@
1
+ // The closing line of a plain `docsxai run`: how many flows (or flow variants) finished, where the
2
+ // outputs went, and for each failure the command that digs into it. Success goes to stdout with the
3
+ // progress lines; a failure goes to stderr with the halt messages it summarises.
4
+ import * as path from "node:path";
5
+ import { sanitizeForTerminal, shellQuote } from "./cli-messages.js";
6
+ /** The command to run for a failure: `diagnose` for a halted step, `doctor` when the browser never started. */
7
+ export function nextForFailure(projectDir, f) {
8
+ const dir = shellQuote(projectDir);
9
+ if (f.step === null)
10
+ return `docsxai doctor ${dir}`;
11
+ const slash = f.flow.indexOf("/");
12
+ const flow = slash === -1 ? f.flow : f.flow.slice(0, slash);
13
+ const variant = slash === -1 ? "" : ` --variant ${shellQuote(f.flow.slice(slash + 1))}`;
14
+ return `docsxai diagnose ${dir} --flow ${shellQuote(flow)} --step ${shellQuote(f.step)}${variant}`;
15
+ }
16
+ export function formatRunSummary(input) {
17
+ const { projectDir, noun, total, okCount, failures } = input;
18
+ const where = path.join(projectDir, "docs");
19
+ const unit = total === 1 ? noun.replace(/s$/, "") : noun;
20
+ if (failures.length === 0)
21
+ return `run: ${okCount} of ${total} ${unit} ok, outputs in ${where}\n`;
22
+ const lines = [
23
+ `run: ${failures.length} of ${total} ${unit} failed, ${okCount} ok; outputs in ${where}`,
24
+ ];
25
+ for (const f of failures)
26
+ lines.push(` ${sanitizeForTerminal(f.flow)}: next: ${nextForFailure(projectDir, f)}`);
27
+ return lines.join("\n") + "\n";
28
+ }
29
+ /** Write the summary on the stream that fits the outcome. */
30
+ export function reportRun(input) {
31
+ const text = formatRunSummary(input);
32
+ (input.failures.length === 0 ? process.stdout : process.stderr).write(text);
33
+ }