@docsxai/engine 0.2.1-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.
Files changed (104) hide show
  1. package/README.md +18 -5
  2. package/dist/address-class.d.ts +14 -0
  3. package/dist/address-class.js +151 -0
  4. package/dist/auth/api-login.d.ts +3 -3
  5. package/dist/auth/email-otp.d.ts +60 -60
  6. package/dist/auth/jwt-injection.d.ts +45 -45
  7. package/dist/auth/pat-header.d.ts +2 -2
  8. package/dist/auth/types.d.ts +2 -2
  9. package/dist/auth/ui-form.d.ts +54 -54
  10. package/dist/auth/webauthn.d.ts +22 -22
  11. package/dist/backend-client-contracts.d.ts +4 -2
  12. package/dist/backend-client-token.js +2 -1
  13. package/dist/calibrate.d.ts +2 -2
  14. package/dist/calibrate.js +5 -0
  15. package/dist/cli-backend-errors.d.ts +7 -0
  16. package/dist/cli-backend-errors.js +65 -0
  17. package/dist/cli-commands-authoring.js +57 -51
  18. package/dist/cli-commands-backend.js +49 -42
  19. package/dist/cli-commands-docpack.d.ts +5 -0
  20. package/dist/cli-commands-docpack.js +106 -66
  21. package/dist/cli-commands-pack.d.ts +2 -0
  22. package/dist/cli-commands-pack.js +65 -0
  23. package/dist/cli-commands-session.js +120 -125
  24. package/dist/cli-messages.d.ts +17 -0
  25. package/dist/cli-messages.js +80 -0
  26. package/dist/cli-retired.d.ts +6 -0
  27. package/dist/cli-retired.js +12 -0
  28. package/dist/cli-run-summary.d.ts +15 -0
  29. package/dist/cli-run-summary.js +33 -0
  30. package/dist/cli-usage.d.ts +1 -1
  31. package/dist/cli-usage.js +78 -5
  32. package/dist/cli-verify.d.ts +14 -0
  33. package/dist/cli-verify.js +54 -0
  34. package/dist/cli.js +15 -2
  35. package/dist/deprecation.d.ts +19 -0
  36. package/dist/deprecation.js +32 -0
  37. package/dist/diagnose.d.ts +25 -0
  38. package/dist/diagnose.js +69 -3
  39. package/dist/diff-compute.js +1 -0
  40. package/dist/doc-pack-io.d.ts +14 -0
  41. package/dist/doc-pack-io.js +121 -14
  42. package/dist/doc-pack.d.ts +2282 -387
  43. package/dist/doc-pack.js +135 -43
  44. package/dist/doctor-checks-plugins.js +4 -3
  45. package/dist/doctor-checks.d.ts +1 -1
  46. package/dist/doctor-checks.js +31 -6
  47. package/dist/doctor.d.ts +2 -0
  48. package/dist/doctor.js +27 -3
  49. package/dist/driver-budget.d.ts +6 -0
  50. package/dist/driver-budget.js +15 -0
  51. package/dist/egress-guard.d.ts +58 -0
  52. package/dist/egress-guard.js +136 -0
  53. package/dist/environment-spec.d.ts +67 -0
  54. package/dist/environment-spec.js +38 -0
  55. package/dist/export/playwright-test.js +42 -10
  56. package/dist/flow-file.d.ts +9 -3
  57. package/dist/flow-file.js +21 -1
  58. package/dist/flow-halt.d.ts +16 -0
  59. package/dist/flow-halt.js +76 -0
  60. package/dist/flow-hidden.d.ts +9 -0
  61. package/dist/flow-hidden.js +20 -0
  62. package/dist/flow-lint.js +91 -1
  63. package/dist/flow-matrix-lint.d.ts +10 -0
  64. package/dist/flow-matrix-lint.js +40 -0
  65. package/dist/flow-matrix.d.ts +44 -0
  66. package/dist/flow-matrix.js +238 -0
  67. package/dist/flow-name-rules.d.ts +15 -0
  68. package/dist/flow-name-rules.js +39 -0
  69. package/dist/flow-runtime.d.ts +52 -22
  70. package/dist/flow-runtime.js +63 -117
  71. package/dist/flow-success.d.ts +3 -0
  72. package/dist/flow-success.js +37 -0
  73. package/dist/flow-tree.d.ts +2 -0
  74. package/dist/flow-tree.js +17 -5
  75. package/dist/flow-wait.d.ts +3 -0
  76. package/dist/flow-wait.js +22 -0
  77. package/dist/index.d.ts +5 -0
  78. package/dist/index.js +5 -0
  79. package/dist/matrix-spec.d.ts +145 -0
  80. package/dist/matrix-spec.js +120 -0
  81. package/dist/page-hide.d.ts +10 -0
  82. package/dist/page-hide.js +45 -0
  83. package/dist/page-settle.d.ts +39 -0
  84. package/dist/page-settle.js +142 -0
  85. package/dist/playwright-driver.d.ts +28 -8
  86. package/dist/playwright-driver.js +73 -28
  87. package/dist/plugins/manifest.d.ts +9 -9
  88. package/dist/run-flows.d.ts +40 -0
  89. package/dist/run-flows.js +129 -0
  90. package/dist/style.d.ts +2 -2
  91. package/dist/upload-path.d.ts +15 -0
  92. package/dist/upload-path.js +63 -0
  93. package/dist/verify-compare.d.ts +43 -0
  94. package/dist/verify-compare.js +237 -0
  95. package/dist/verify-determinism.d.ts +16 -0
  96. package/dist/verify-determinism.js +88 -0
  97. package/dist/verify-report.d.ts +53 -0
  98. package/dist/verify-report.js +141 -0
  99. package/dist/verify-tree.d.ts +27 -0
  100. package/dist/verify-tree.js +95 -0
  101. package/dist/viewer-bin.d.ts +6 -0
  102. package/dist/viewer-bin.js +24 -0
  103. package/dist/zip.d.ts +2 -2
  104. package/package.json +3 -2
package/dist/doc-pack.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // <project>/docs/<flow>/<step>.md — step write-ups (user-facing prose)
6
6
  // <project>/docs/<flow>/screenshots/<step>.png
7
7
  // <project>/docs/<flow>/annotations.json — per-step annotation records (this module's AnnotationsFile)
8
+ // A flow with a `matrix` writes the two lines above under docs/<flow>/<variant>/ instead.
8
9
  // <project>/docs/style.yaml + style.json — style artifact (canonical + derived)
9
10
  // <project>/docs/locators.yaml — locator manifest (one canonical locator per step)
10
11
  // <project>/auth/strategy.yaml — target-site auth-strategy descriptor
@@ -12,6 +13,11 @@
12
13
  // Runtime validation is done with zod; the exported TS types are inferred from the schemas
13
14
  // so the two never drift.
14
15
  import { z } from "zod";
16
+ import { EnvironmentSpec, LocaleTag } from "./environment-spec.js";
17
+ import { hasTrailingDot, isWindowsDeviceName } from "./flow-name-rules.js";
18
+ import { MatrixSpec, VariantInfo, VariantSelector } from "./matrix-spec.js";
19
+ export { ColorScheme, EnvironmentSpec, LocaleTag, VIEWPORT_PRESETS, ViewportPreset, ViewportSize, } from "./environment-spec.js";
20
+ export { MAX_MATRIX_VARIANTS, MatrixSpec, MatrixViewport, VariantInfo, VariantSelector, } from "./matrix-spec.js";
15
21
  // ---------------------------------------------------------------------------
16
22
  // Shared
17
23
  // ---------------------------------------------------------------------------
@@ -41,15 +47,46 @@ export const ActionType = z.enum([
41
47
  "check",
42
48
  "uncheck",
43
49
  "wait",
50
+ "hide",
51
+ "show",
44
52
  ]);
53
+ /** Bounds for a step's `timeout_ms`, in milliseconds. 30 s is Playwright's own default wait. */
54
+ export const STEP_TIMEOUT_MIN_MS = 100;
55
+ export const STEP_TIMEOUT_MAX_MS = 30_000;
56
+ /** Actions whose `target` wait `timeout_ms` can bound (`show` acts instantly; `navigate`/`wait` have no target wait). */
57
+ const TARGET_WAIT_ACTIONS = new Set([
58
+ "click",
59
+ "fill",
60
+ "upload",
61
+ "press",
62
+ "hover",
63
+ "select",
64
+ "check",
65
+ "uncheck",
66
+ "hide",
67
+ ]);
68
+ /** True when a step's `timeout_ms` bounds something: its target wait, a `wait_for: settled`, or a `wait` step's own `wait_for` selector. */
69
+ function stepTimeoutHasEffect(s) {
70
+ if (s.wait_for === "settled")
71
+ return true;
72
+ if (TARGET_WAIT_ACTIONS.has(s.action))
73
+ return s.target !== undefined;
74
+ const w = s.wait_for;
75
+ return (s.action === "wait" &&
76
+ w !== undefined &&
77
+ typeof w === "object" &&
78
+ "selector" in w &&
79
+ w.timeout_ms === undefined);
80
+ }
45
81
  /**
46
- * What to wait for after a step's action settles. `network_idle` / `element_stable` / `load` are named
47
- * primitives; `{ selector }` waits for an element to appear (Playwright's default timeout, ~30s) — give it
82
+ * What to wait for after a step's action settles. `network_idle` / `element_stable` / `load` / `settled` are
83
+ * named primitives (`settled` = fonts loaded, visible images loaded, viewport layout still, bounded by the
84
+ * step's `timeout_ms`); `{ selector }` waits for an element to appear (Playwright's default timeout, ~30s) — give it
48
85
  * `timeout_ms` to override that (e.g. waiting on a multi-minute backend op that mounts a "done" element);
49
86
  * `{ timeout_ms }` alone is a blind sleep (last resort — for animations, not state).
50
87
  */
51
88
  export const WaitSpec = z.union([
52
- z.enum(["network_idle", "element_stable", "load"]),
89
+ z.enum(["network_idle", "element_stable", "load", "settled"]),
53
90
  z.object({ timeout_ms: z.number().int().positive() }).strict(),
54
91
  z.object({ selector: LocatorRef, timeout_ms: z.number().int().positive().optional() }).strict(),
55
92
  ]);
@@ -64,41 +101,6 @@ export const SuccessSpec = z.union([
64
101
  ]);
65
102
  export const NudgeOffset = z.object({ x: z.number(), y: z.number() }).strict();
66
103
  // ---------------------------------------------------------------------------
67
- // Execution environment (`environment:` block)
68
- // ---------------------------------------------------------------------------
69
- export const ViewportSize = z
70
- .object({ width: z.number().int().positive(), height: z.number().int().positive() })
71
- .strict();
72
- export const ViewportPreset = z.enum(["desktop", "tablet", "mobile"]);
73
- /** Named viewport presets — `desktop` 1440×900, `tablet` 834×1112, `mobile` 390×844. */
74
- export const VIEWPORT_PRESETS = {
75
- desktop: { width: 1440, height: 900 },
76
- tablet: { width: 834, height: 1112 },
77
- mobile: { width: 390, height: 844 },
78
- };
79
- /**
80
- * Deterministic execution environment for a flow. All fields optional; applied at browser-context
81
- * creation (so the whole flow runs under them). With `extends`, the child flow's `environment`
82
- * wins per-key over the parent's (a child can pin just `viewport` and inherit the parent's clock).
83
- */
84
- export const EnvironmentSpec = z
85
- .object({
86
- /** ISO-8601 instant the page clock is frozen at — `new Date()` etc. return this for the whole run. */
87
- clock: z.string().datetime({ offset: true, local: true }).optional(),
88
- /** BCP-47 language tag (e.g. `en-GB`). */
89
- locale: z
90
- .string()
91
- .regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]+)*$/, "must be a BCP-47 language tag (e.g. en-GB)")
92
- .optional(),
93
- /** IANA timezone (e.g. `Europe/Amsterdam`). */
94
- timezone: z.string().min(1).optional(),
95
- /** `{ width, height }` in CSS pixels, or a named preset — see {@link VIEWPORT_PRESETS}. */
96
- viewport: z.union([ViewportPreset, ViewportSize]).optional(),
97
- color_scheme: z.enum(["light", "dark"]).optional(),
98
- reduced_motion: z.boolean().optional(),
99
- })
100
- .strict();
101
- // ---------------------------------------------------------------------------
102
104
  // Redactions (`redactions:` — flow-level and per-step)
103
105
  // ---------------------------------------------------------------------------
104
106
  export const RedactionStyle = z.enum(["box", "pixelate"]);
@@ -123,6 +125,36 @@ export const RedactionSpec = z.union([
123
125
  z.object({ selector: LocatorRef, style: RedactionStyle.optional() }).strict(),
124
126
  z.object({ region: RedactionRegion, style: RedactionStyle.optional() }).strict(),
125
127
  ]);
128
+ /** Most `obstacles` one annotation record may carry (the writer keeps the nearest this many). */
129
+ export const MAX_OBSTACLES = 40;
130
+ /** Bounds of `placement.max_width`, the widest outer callout box the burner may use, in screenshot px. */
131
+ export const MIN_CALLOUT_WIDTH = 120;
132
+ export const MAX_CALLOUT_WIDTH = 560;
133
+ /** Widest `placement.obstacle_radius` (CSS px) a flow may ask the obstacle scan for. */
134
+ export const MAX_OBSTACLE_RADIUS = 2000;
135
+ /**
136
+ * Optional per-annotation placement settings for the burner. Every key is optional and an empty or
137
+ * absent object changes nothing. The interactive viewer ignores them; `obstacle_radius` and
138
+ * `obstacle_limit` steer the capture-time obstacle scan, the rest steer `docsxai-viewer burn`.
139
+ */
140
+ export const AnnotationPlacement = z
141
+ .object({
142
+ /** Put the callout inside the target when the target is big enough to hold it (no arrow). */
143
+ inside: z.boolean().optional(),
144
+ /** Only try this side of the target (falls back to the usual order when nothing fits there). */
145
+ side: z.enum(["top", "bottom", "left", "right"]).optional(),
146
+ /** Where along the target's edge the callout sits: flush with its start, centred, or flush with its end. */
147
+ align: z.enum(["start", "center", "end"]).optional(),
148
+ /** `nudge` moves only the callout: the arrow stays on the target and a stem joins the two. */
149
+ pin_arrow: z.boolean().optional(),
150
+ /** Widest outer callout box in px (default 280, narrower on small screenshots with obstacles). */
151
+ max_width: z.number().finite().min(MIN_CALLOUT_WIDTH).max(MAX_CALLOUT_WIDTH).optional(),
152
+ /** CSS px around the target the obstacle scan covers (default 320). Read by `docsxai run`. */
153
+ obstacle_radius: z.number().finite().min(0).max(MAX_OBSTACLE_RADIUS).optional(),
154
+ /** Most obstacles recorded for this annotation (default {@link MAX_OBSTACLES}). Read by `docsxai run`. */
155
+ obstacle_limit: z.number().int().min(1).max(MAX_OBSTACLES).optional(),
156
+ })
157
+ .strict();
126
158
  export const StepAnnotation = z
127
159
  .object({
128
160
  copy: z.string().min(1),
@@ -134,6 +166,8 @@ export const StepAnnotation = z
134
166
  * Image-space pixels; small values (5–40 px in either direction) typically suffice.
135
167
  */
136
168
  nudge: NudgeOffset.optional(),
169
+ /** Optional burner placement settings — see {@link AnnotationPlacement}. Copied onto the annotation record. */
170
+ placement: AnnotationPlacement.optional(),
137
171
  /**
138
172
  * Optional override: the locator to anchor the halo/arrow to. Default = the step's `target`. Use this on
139
173
  * a step whose action *transitions the UI* — the action target vanishes (gets unmounted / replaced) and
@@ -141,6 +175,19 @@ export const StepAnnotation = z
141
175
  * surviving / appearing element.
142
176
  */
143
177
  target: LocatorRef.optional(),
178
+ /**
179
+ * Call-out text per locale, keyed by BCP-47 tag (`es`, `fr-CA`). `copy` stays required and is the
180
+ * fallback. A variant takes its locale's entry (exact tag, then the language subtag), else `copy`.
181
+ * The variant locale is the matrix locale, or `environment.locale` when the flow has no matrix locales.
182
+ */
183
+ copy_by_locale: z
184
+ .record(LocaleTag, z.string().min(1))
185
+ .refine((m) => Object.keys(m).length > 0, { message: "needs at least one locale" })
186
+ .optional(),
187
+ /** Variants this call-out is kept for. Needs a `matrix`; see {@link VariantSelector}. */
188
+ only: VariantSelector.optional(),
189
+ /** Variants this call-out is dropped from. Needs a `matrix`; see {@link VariantSelector}. */
190
+ skip: VariantSelector.optional(),
144
191
  })
145
192
  .strict();
146
193
  export const Step = z
@@ -155,7 +202,16 @@ export const Step = z
155
202
  * this over a permissive comma-selector that no-ops on one branch.
156
203
  */
157
204
  optional: z.boolean().optional(),
158
- /** Locator ref (`$name`) or inline selector. Optional for actions like `navigate` (uses `value`) or `wait`. */
205
+ /**
206
+ * How long, in ms, this step waits for its `target` before giving up (100–30000). Unset keeps the
207
+ * driver default (Playwright's 30 s), so existing flows run exactly as before. The reason to set it
208
+ * is an `optional: true` step whose target is usually absent: a short value (e.g. 1500) skips it fast
209
+ * instead of holding the run for the full default. On a `wait` step it bounds the `wait_for`
210
+ * `{ selector }` wait when that has no `timeout_ms` of its own. With `wait_for: settled` it is that wait's
211
+ * whole budget (default 10 s), on any action. Rejected where it would bound nothing.
212
+ */
213
+ timeout_ms: z.number().int().min(STEP_TIMEOUT_MIN_MS).max(STEP_TIMEOUT_MAX_MS).optional(),
214
+ /** Locator ref (`$name`) or inline selector. Optional for actions like `navigate` (uses `value`), `wait`, and `show` (no target = show everything hidden). */
159
215
  target: LocatorRef.optional(),
160
216
  /** Action payload: text for `fill`, file path for `upload`, key for `press`, path/URL for `navigate`, option for `select`. */
161
217
  value: z.string().optional(),
@@ -172,17 +228,45 @@ export const Step = z
172
228
  annotations: z.array(StepAnnotation).min(1).optional(),
173
229
  /** Extra redactions for this step's screenshots, additive on top of the flow-level list. */
174
230
  redactions: z.array(RedactionSpec).min(1).optional(),
231
+ /** Variants this step runs for (the others skip it). Needs a `matrix`; see {@link VariantSelector}. */
232
+ only: VariantSelector.optional(),
233
+ /** Variants this step is dropped from. Needs a `matrix`; see {@link VariantSelector}. */
234
+ skip: VariantSelector.optional(),
175
235
  })
176
236
  .strict()
177
237
  .refine((s) => !(s.annotation && s.annotations), {
178
238
  message: "step has both `annotation` and `annotations`; use one (`annotations: [...]` for the multi-callout form)",
179
239
  path: ["annotations"],
240
+ })
241
+ .refine((s) => s.timeout_ms === undefined || stepTimeoutHasEffect(s), {
242
+ message: "`timeout_ms` has no effect on this step: it bounds the wait for a `target` (click, fill, upload, press, hover, select, check, uncheck, hide), a `wait_for: settled`, or a `wait` step's `wait_for: { selector }` that has no `timeout_ms` of its own",
243
+ path: ["timeout_ms"],
180
244
  });
181
245
  /** A precondition the flow assumes (e.g. `{ logged_in_as: "editor" }`, `{ feature_flag: "recap.enabled" }`). */
182
246
  export const Prerequisite = z.record(z.string(), z.union([z.string(), z.boolean()]));
247
+ /** Longest flow name. The name is a directory and file name under the workspace. */
248
+ export const MAX_FLOW_NAME_LENGTH = 64;
249
+ /**
250
+ * A flow's name is a path segment: it names `flows/<name>.flow.yaml` and `docs/<name>/`, and
251
+ * `run` writes under both. It starts with a letter or digit, then letters, digits, `.`, `_` and `-`
252
+ * (so `Board_1.v2` is fine), never contains `..`, and is at most {@link MAX_FLOW_NAME_LENGTH} long.
253
+ * A slash, a backslash, a leading dot and an absolute path are all outside that set. A trailing
254
+ * `.` and a Windows device name (`con`, `nul`, `com1`, `lpt1`, ..., with or without an extension
255
+ * part) are refused too, since Windows cannot create them.
256
+ */
257
+ export const FlowName = z
258
+ .string()
259
+ .min(1)
260
+ .max(MAX_FLOW_NAME_LENGTH)
261
+ .regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, "must start with a letter or digit and use only letters, digits, `.`, `_` and `-`")
262
+ .refine((n) => !n.includes(".."), { message: "must not contain `..`" })
263
+ .refine((n) => !hasTrailingDot(n), { message: "must not end with `.`" })
264
+ .refine((n) => !isWindowsDeviceName(n), {
265
+ message: "must not be a Windows device name (con, prn, aux, nul, com1-9, lpt1-9)",
266
+ });
183
267
  export const FlowFile = z
184
268
  .object({
185
- name: z.string().min(1),
269
+ name: FlowName,
186
270
  /**
187
271
  * Name of another flow whose steps run *first* (composition). The parent's `locators` + `prerequisites`
188
272
  * are merged in (this flow wins on collisions); step ids must be unique across the merge. Chains allowed
@@ -190,12 +274,18 @@ export const FlowFile = z
190
274
  * Typical use: factor out a shared preamble (Library → open a video → editor) so dependent flows don't
191
275
  * re-walk it every run. (`run --stop-after` operates on the merged step list.)
192
276
  */
193
- extends: z.string().min(1).optional(),
277
+ extends: FlowName.optional(),
194
278
  /**
195
279
  * Deterministic execution environment (frozen clock, locale, timezone, viewport, color scheme,
196
280
  * reduced motion). With `extends`, merged per-key — this flow's keys win over the parent's.
197
281
  */
198
282
  environment: EnvironmentSpec.optional(),
283
+ /**
284
+ * Expands the flow into variants: the product of the listed locales, color schemes and viewports.
285
+ * Each variant runs under its own `environment` override and writes to `docs/<flow>/<variant>/`.
286
+ * Not inherited through `extends`. See `flow-matrix.ts`.
287
+ */
288
+ matrix: MatrixSpec.optional(),
199
289
  /** Areas masked on every screenshot this flow produces (incl. halt shots). See {@link RedactionSpec}. */
200
290
  redactions: z.array(RedactionSpec).min(1).optional(),
201
291
  prerequisites: z.array(Prerequisite).default([]),
@@ -216,8 +306,6 @@ export const BoundingBox = z
216
306
  height: z.number().finite().nonnegative(),
217
307
  })
218
308
  .strict();
219
- /** Most `obstacles` one annotation record may carry (the writer keeps the nearest this many). */
220
- export const MAX_OBSTACLES = 40;
221
309
  export const AnnotationRecord = z
222
310
  .object({
223
311
  step: z.string().min(1),
@@ -237,6 +325,8 @@ export const AnnotationRecord = z
237
325
  * carries the same field.
238
326
  */
239
327
  obstacles: z.array(BoundingBox).max(MAX_OBSTACLES).optional(),
328
+ /** Optional burner placement settings (inside the target, side, alignment, pinned arrow, width) — see {@link AnnotationPlacement}. */
329
+ placement: AnnotationPlacement.optional(),
240
330
  /** 1-based index of this annotation *within its step's screenshot* — set only when the step has > 1 annotation, so the viewer can render a numbered badge. Absent → render as a plain (un-numbered) halo. */
241
331
  index: z.number().int().positive().optional(),
242
332
  })
@@ -245,6 +335,8 @@ export const AnnotationsFile = z
245
335
  .object({
246
336
  schema: z.literal("docsxai/annotations@1"),
247
337
  flow: z.string().min(1),
338
+ /** The matrix variant these annotations belong to. Absent for a flow without a `matrix`. */
339
+ variant: VariantInfo.optional(),
248
340
  annotations: z.array(AnnotationRecord),
249
341
  })
250
342
  .strict();
@@ -3,6 +3,7 @@
3
3
  // the environment and workspace-content probes, with its own dependency set
4
4
  // (the plugin runtime + lock + manifest domain).
5
5
  import { promises as fs } from "node:fs";
6
+ import { shellQuote } from "./cli-messages.js";
6
7
  import { isApiVersionCompatible, RUNTIME_API_VERSION } from "./plugins/manifest.js";
7
8
  import { PLUGINS_LOCK_FILE, PluginsConfigError, PluginsLockError, readPluginsLock, readWorkspacePluginsConfig, verifyLock, } from "./plugins/lock.js";
8
9
  import { resolvePluginSources } from "./plugins/runtime.js";
@@ -46,7 +47,7 @@ export async function checkPlugins(workspaceDir) {
46
47
  name: "plugins",
47
48
  ok: false,
48
49
  detail: e.message,
49
- fix: `re-pin: docsxai plugins sync ${workspaceDir}`,
50
+ fix: `re-pin: docsxai plugins sync ${shellQuote(workspaceDir)}`,
50
51
  },
51
52
  ];
52
53
  }
@@ -58,7 +59,7 @@ export async function checkPlugins(workspaceDir) {
58
59
  name: "plugins",
59
60
  ok: false,
60
61
  detail: `${PLUGINS_LOCK_FILE} missing (${cfg.sources.length} plugin(s) configured — no reproducibility pin)`,
61
- fix: `docsxai plugins sync ${workspaceDir}`,
62
+ fix: `docsxai plugins sync ${shellQuote(workspaceDir)}`,
62
63
  });
63
64
  }
64
65
  const resolutions = await resolvePluginSources(workspaceDir, cfg.sources);
@@ -106,7 +107,7 @@ export async function checkPlugins(workspaceDir) {
106
107
  if (mismatch) {
107
108
  issues.push({
108
109
  detail: mismatch,
109
- fix: `after auditing the change: docsxai plugins sync ${workspaceDir}`,
110
+ fix: `after auditing the change: docsxai plugins sync ${shellQuote(workspaceDir)}`,
110
111
  });
111
112
  }
112
113
  else {
@@ -50,7 +50,7 @@ export declare function checkFlows(workspaceDir: string): Promise<DoctorCheck>;
50
50
  export declare function checkAuth(workspaceDir: string, now: number): Promise<DoctorCheck[]>;
51
51
  export declare function checkBackend(workspaceDir: string, config: Record<string, unknown> | null, env: NodeJS.ProcessEnv, fetchImpl: typeof globalThis.fetch): Promise<DoctorCheck>;
52
52
  export declare function checkViewer(env: NodeJS.ProcessEnv, resolveFrom?: string[]): Promise<DoctorCheck>;
53
- /** DOCSX_* env vars the docsxai packages read (engine + backend). */
53
+ /** DOCSX_* env vars the docsxai packages read (engine, viewer, backend + mcp). */
54
54
  export declare const KNOWN_DOCSX_ENV_VARS: ReadonlyArray<string>;
55
55
  export declare function checkEnv(env: NodeJS.ProcessEnv): DoctorCheck[];
56
56
  export {};
@@ -8,6 +8,8 @@
8
8
  import { existsSync, promises as fs } from "node:fs";
9
9
  import * as path from "node:path";
10
10
  import { parseAuthStrategyFile } from "./auth.js";
11
+ import { shellQuote } from "./cli-messages.js";
12
+ import { EGRESS_DENY_PRIVATE_ENV, EGRESS_GUARD_ENV, envFlagOff, envFlagOn, } from "./egress-guard.js";
11
13
  import { FlowFileError, parseFlowFile } from "./flow-file.js";
12
14
  import { chromiumExecutablePath } from "./playwright-driver.js";
13
15
  import { resolveViewerBin, VIEWER_BIN_ENV, VIEWER_BIN_NAME, VIEWER_PACKAGE } from "./viewer-bin.js";
@@ -86,7 +88,7 @@ export async function checkWorkspace(workspaceDir) {
86
88
  name: "workspace",
87
89
  ok: false,
88
90
  detail: `${configPath} is not valid JSON: ${e.message}`,
89
- fix: `fix the JSON (or re-scaffold with \`docsxai init ${workspaceDir} --force\`)`,
91
+ fix: `fix the JSON (or re-scaffold with \`docsxai init ${shellQuote(workspaceDir)} --force\`)`,
90
92
  },
91
93
  config: null,
92
94
  present: true,
@@ -149,7 +151,7 @@ export async function checkFlows(workspaceDir) {
149
151
  name: "flows",
150
152
  ok: false,
151
153
  detail: `${entry} does not parse: ${msg}`,
152
- fix: `fix the flow-file (then \`docsxai lint ${workspaceDir}\` for the full static report)`,
154
+ fix: `fix the flow-file (then \`docsxai lint ${shellQuote(workspaceDir)}\` for the full static report)`,
153
155
  };
154
156
  }
155
157
  }
@@ -203,7 +205,7 @@ export async function checkAuth(workspaceDir, now) {
203
205
  name: "auth",
204
206
  ok: true,
205
207
  info: true,
206
- detail: `no cached session for role "${role}" — \`docsxai capture-auth ${workspaceDir}\` before \`run\``,
208
+ detail: `no cached session for role "${role}" — \`docsxai capture-auth ${shellQuote(workspaceDir)}\` before \`run\``,
207
209
  });
208
210
  return checks;
209
211
  }
@@ -220,7 +222,7 @@ export async function checkAuth(workspaceDir, now) {
220
222
  name: "auth",
221
223
  ok: false,
222
224
  detail: `cached session ${sessionPath} is corrupt (no expiresAt)`,
223
- fix: `re-capture: docsxai capture-auth ${workspaceDir}`,
225
+ fix: `re-capture: docsxai capture-auth ${shellQuote(workspaceDir)}`,
224
226
  });
225
227
  }
226
228
  else if (expiresAt <= now) {
@@ -228,7 +230,7 @@ export async function checkAuth(workspaceDir, now) {
228
230
  name: "auth",
229
231
  ok: false,
230
232
  detail: `cached session for role "${role}" expired ${new Date(expiresAt).toISOString()}`,
231
- fix: `re-capture: docsxai capture-auth ${workspaceDir}`,
233
+ fix: `re-capture: docsxai capture-auth ${shellQuote(workspaceDir)}`,
232
234
  });
233
235
  }
234
236
  else {
@@ -317,7 +319,7 @@ export async function checkViewer(env, resolveFrom) {
317
319
  fix: `install ${VIEWER_PACKAGE} next to the engine (a global \`docsxai\` install ships it), or point ${VIEWER_BIN_ENV} at its bin script`,
318
320
  };
319
321
  }
320
- /** DOCSX_* env vars the docsxai packages read (engine + backend). */
322
+ /** DOCSX_* env vars the docsxai packages read (engine, viewer, backend + mcp). */
321
323
  export const KNOWN_DOCSX_ENV_VARS = [
322
324
  "DOCSX_TOKEN",
323
325
  "DOCSX_CACHE_KEY",
@@ -326,7 +328,29 @@ export const KNOWN_DOCSX_ENV_VARS = [
326
328
  "DOCSX_DATA_DIR",
327
329
  "DOCSX_OAUTH_AUTO_APPROVE",
328
330
  "DOCSX_WEBHOOK_SECRET",
331
+ "DOCSX_OXIPNG_BIN",
332
+ "DOCSX_BACKEND_DENY_PRIVATE_APP_URL",
333
+ "DOCSX_EGRESS_GUARD",
334
+ "DOCSX_EGRESS_DENY_PRIVATE",
335
+ "DOCSX_MCP_TOKEN",
329
336
  ];
337
+ /** On/off switches: `1`, `true` or `yes` turns one on; anything else non-empty, `0`/`false`/`no` aside, is read as off. */
338
+ const FLAG_ENV_VARS = [
339
+ "DOCSX_BACKEND_DENY_PRIVATE_APP_URL",
340
+ EGRESS_GUARD_ENV,
341
+ EGRESS_DENY_PRIVATE_ENV,
342
+ ];
343
+ function misspelledFlags(env) {
344
+ return FLAG_ENV_VARS.filter((k) => {
345
+ const v = env[k];
346
+ return v !== undefined && v.trim() !== "" && !envFlagOn(v) && !envFlagOff(v);
347
+ }).map((k) => ({
348
+ name: "env",
349
+ ok: false,
350
+ detail: `${k}=${JSON.stringify(env[k])} is not an on/off value, so the switch is off`,
351
+ fix: "use 1, true or yes to turn it on, or unset it",
352
+ }));
353
+ }
330
354
  export function checkEnv(env) {
331
355
  const set = Object.keys(env)
332
356
  .filter((k) => k.startsWith("DOCSX_"))
@@ -341,6 +365,7 @@ export function checkEnv(env) {
341
365
  if (known.length > 0) {
342
366
  checks.push({ name: "env", ok: true, detail: `set: ${known.join(", ")}` });
343
367
  }
368
+ checks.push(...misspelledFlags(env));
344
369
  const cacheKey = env.DOCSX_CACHE_KEY;
345
370
  if (cacheKey) {
346
371
  const decoded = Buffer.from(cacheKey, "base64");
package/dist/doctor.d.ts CHANGED
@@ -3,5 +3,7 @@ export * from "./doctor-checks.js";
3
3
  export * from "./doctor-checks-plugins.js";
4
4
  export declare function buildDoctorChecks(opts?: DoctorOptions): Promise<DoctorCheck[]>;
5
5
  export declare function formatDoctorChecks(checks: DoctorCheck[]): string;
6
+ /** What `docsxai doctor --help` prints: the usage line from `docsxai --help`, then what the rows mean. */
7
+ export declare function doctorHelp(): string;
6
8
  /** `docsxai doctor [<workspace-dir>]` — returns the process exit code. */
7
9
  export declare function runDoctor(args: string[]): Promise<number>;
package/dist/doctor.js CHANGED
@@ -11,6 +11,7 @@
11
11
  // every doctor symbol stays importable from ./doctor.js.
12
12
  import { checkAuth, checkBackend, checkChromium, checkEnv, checkFlows, checkNode, checkViewer, checkWorkspace, probeChromium, } from "./doctor-checks.js";
13
13
  import { checkPlugins } from "./doctor-checks-plugins.js";
14
+ import { commandUsage } from "./cli-messages.js";
14
15
  // Re-export the probe catalogue's public surface so importers keep reaching it
15
16
  // through ./doctor.js (its original home) — no importer or test changes. The
16
17
  // plugin-runtime probe lives in its own sibling but is re-exported here too.
@@ -41,20 +42,43 @@ export async function buildDoctorChecks(opts = {}) {
41
42
  }
42
43
  export function formatDoctorChecks(checks) {
43
44
  let out = "docsxai doctor — environment & workspace health\n\n";
44
- let allOk = true;
45
+ let failed = 0;
45
46
  for (const c of checks) {
46
47
  if (!c.ok)
47
- allOk = false;
48
+ failed++;
48
49
  const glyph = c.info ? "−" : c.ok ? "✓" : "✗";
49
50
  out += ` ${glyph} ${c.name.padEnd(10)} ${c.detail}\n`;
50
51
  if (!c.ok && c.fix)
51
52
  out += ` fix: ${c.fix}\n`;
52
53
  }
53
- out += `\n${allOk ? "all checks passed" : "fix the ✗ items above"}\n`;
54
+ const infos = checks.filter((c) => c.info).length;
55
+ const scored = checks.length - infos;
56
+ out +=
57
+ failed === 0
58
+ ? `\ndoctor: all checks passed (${scored} checks, ${infos} informational)\n`
59
+ : `\ndoctor: fix the ✗ items above and run docsxai doctor again (${failed} of ${scored} checks failed)\n`;
54
60
  return out;
55
61
  }
62
+ /** What `docsxai doctor --help` prints: the usage line from `docsxai --help`, then what the rows mean. */
63
+ export function doctorHelp() {
64
+ return `${commandUsage("doctor")
65
+ .map((l) => `usage: ${l}\n`)
66
+ .join("")}
67
+ Checks Node, Chromium, the workspace config, flow-files, cached sessions, the backend (when
68
+ backend_url is set), plugin declarations, the viewer bin and DOCSX_* env. Runs no flow, no plugin
69
+ code and no browser.
70
+
71
+ ✓ passed ✗ failed, with a one-line fix − informational, never fails
72
+
73
+ Exit 0 when no row failed, 1 otherwise.
74
+ `;
75
+ }
56
76
  /** `docsxai doctor [<workspace-dir>]` — returns the process exit code. */
57
77
  export async function runDoctor(args) {
78
+ if (args.includes("--help") || args.includes("-h")) {
79
+ process.stdout.write(doctorHelp());
80
+ return 0;
81
+ }
58
82
  const positionals = args.filter((a) => !a.startsWith("--"));
59
83
  const checks = await buildDoctorChecks(positionals[0] ? { workspaceDir: positionals[0] } : {});
60
84
  process.stdout.write(formatDoctorChecks(checks));
@@ -0,0 +1,6 @@
1
+ /** Rejects with a timeout error if `work` takes longer than `ms` (no limit when `ms` is undefined). */
2
+ export declare function withTimeout<T>(work: Promise<T>, ms: number | undefined): Promise<T>;
3
+ /** Playwright per-call options for a step's `timeout_ms`; empty when unset so the default is untouched. */
4
+ export declare function budget(timeoutMs: number | undefined): {
5
+ timeout?: number;
6
+ };
@@ -0,0 +1,15 @@
1
+ // Per-call time budgets for the Playwright driver's page calls.
2
+ /** Rejects with a timeout error if `work` takes longer than `ms` (no limit when `ms` is undefined). */
3
+ export function withTimeout(work, ms) {
4
+ if (ms === undefined)
5
+ return work;
6
+ let timer;
7
+ const timeout = new Promise((_, reject) => {
8
+ timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms);
9
+ });
10
+ return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
11
+ }
12
+ /** Playwright per-call options for a step's `timeout_ms`; empty when unset so the default is untouched. */
13
+ export function budget(timeoutMs) {
14
+ return timeoutMs === undefined ? {} : { timeout: timeoutMs };
15
+ }
@@ -0,0 +1,58 @@
1
+ export declare const EGRESS_GUARD_ENV = "DOCSX_EGRESS_GUARD";
2
+ export declare const EGRESS_DENY_PRIVATE_ENV = "DOCSX_EGRESS_DENY_PRIVATE";
3
+ /** Resolves a hostname to every address it has. */
4
+ export type HostLookup = (hostname: string) => Promise<string[]>;
5
+ export interface EgressGuardOptions {
6
+ /** Also refuse loopback, private-network and unique-local addresses. Default false. */
7
+ denyPrivate?: boolean;
8
+ /** Hostname resolver; tests inject one. Default: `dns.lookup` returning all addresses. */
9
+ lookup?: HostLookup;
10
+ /** Longest a lookup may take before the request is refused. Default {@link LOOKUP_TIMEOUT_MS}. */
11
+ lookupTimeoutMs?: number;
12
+ /**
13
+ * Told about each refused request: the URL without userinfo, query or fragment, the generic
14
+ * reason, and the detail (host and resolved address) that must not reach a tenant.
15
+ */
16
+ onBlock?: (url: string, reason: string, detail: string) => void;
17
+ }
18
+ /** True for `1`, `true` and `yes` in any case. */
19
+ export declare function envFlagOn(value: string | undefined): boolean;
20
+ /** True for `0`, `false` and `no` in any case, the spellings that say off on purpose. */
21
+ export declare function envFlagOff(value: string | undefined): boolean;
22
+ /** The guard `env` asks for, or undefined when `DOCSX_EGRESS_GUARD` is not on. */
23
+ export declare function egressGuardFromEnv(env: NodeJS.ProcessEnv): EgressGuardOptions | undefined;
24
+ /** An explicit option wins; otherwise the process environment decides. */
25
+ export declare function resolveEgressGuard(explicit: EgressGuardOptions | undefined, env?: NodeJS.ProcessEnv): EgressGuardOptions | undefined;
26
+ /** Default longest wait for a hostname lookup. */
27
+ export declare const LOOKUP_TIMEOUT_MS = 5000;
28
+ /** Why a request to `rawUrl` must not go out, or null when it may. */
29
+ export declare function requestProblem(rawUrl: string, opts?: EgressGuardOptions): Promise<string | null>;
30
+ /** The part of a Playwright `Route` the guard uses. */
31
+ export interface GuardRoute {
32
+ request(): {
33
+ url(): string;
34
+ };
35
+ abort(errorCode?: string): Promise<void>;
36
+ continue(): Promise<void>;
37
+ }
38
+ /** The part of a Playwright `WebSocketRoute` the guard uses. */
39
+ export interface GuardWebSocket {
40
+ url(): string;
41
+ close(): Promise<void>;
42
+ connectToServer(): unknown;
43
+ }
44
+ /** The part of a Playwright `BrowserContext` the guard uses. */
45
+ export interface GuardableContext {
46
+ route(url: RegExp, handler: (route: GuardRoute) => Promise<void>): Promise<void>;
47
+ routeWebSocket(url: RegExp, handler: (ws: GuardWebSocket) => Promise<void>): Promise<void>;
48
+ }
49
+ /** Context options a guarded context needs: a service worker's own fetches are not routed. */
50
+ export declare function egressContextOptions(guard: EgressGuardOptions | undefined): {
51
+ serviceWorkers?: "block";
52
+ };
53
+ /** What the run's output says about a refused request. */
54
+ export declare const BLOCKED_REASON = "address not allowed";
55
+ /** `rawUrl` without userinfo, query and fragment, safe to print. */
56
+ export declare function printableUrl(rawUrl: string): string;
57
+ /** Route every request and WebSocket of `context` through {@link requestProblem}; a no-op without a guard. */
58
+ export declare function installEgressGuard(context: GuardableContext, guard: EgressGuardOptions | undefined): Promise<void>;