@docsxai/engine 0.2.1-rc.1 → 0.3.0-rc.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.
Files changed (94) 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/calibrate.d.ts +2 -2
  13. package/dist/calibrate.js +5 -0
  14. package/dist/cli-commands-authoring.js +23 -4
  15. package/dist/cli-commands-backend.js +2 -2
  16. package/dist/cli-commands-docpack.d.ts +5 -0
  17. package/dist/cli-commands-docpack.js +70 -24
  18. package/dist/cli-commands-pack.d.ts +2 -0
  19. package/dist/cli-commands-pack.js +69 -0
  20. package/dist/cli-commands-session.js +92 -89
  21. package/dist/cli-retired.d.ts +6 -0
  22. package/dist/cli-retired.js +12 -0
  23. package/dist/cli-usage.d.ts +1 -1
  24. package/dist/cli-usage.js +52 -4
  25. package/dist/cli-verify.d.ts +14 -0
  26. package/dist/cli-verify.js +54 -0
  27. package/dist/cli.js +14 -1
  28. package/dist/deprecation.d.ts +19 -0
  29. package/dist/deprecation.js +32 -0
  30. package/dist/diagnose.d.ts +25 -0
  31. package/dist/diagnose.js +69 -3
  32. package/dist/diff-compute.js +1 -0
  33. package/dist/doc-pack-io.d.ts +14 -0
  34. package/dist/doc-pack-io.js +121 -14
  35. package/dist/doc-pack.d.ts +2282 -387
  36. package/dist/doc-pack.js +135 -43
  37. package/dist/doctor-checks.d.ts +1 -1
  38. package/dist/doctor-checks.js +25 -1
  39. package/dist/driver-budget.d.ts +6 -0
  40. package/dist/driver-budget.js +15 -0
  41. package/dist/egress-guard.d.ts +58 -0
  42. package/dist/egress-guard.js +136 -0
  43. package/dist/environment-spec.d.ts +67 -0
  44. package/dist/environment-spec.js +38 -0
  45. package/dist/export/playwright-test.js +42 -10
  46. package/dist/flow-file.d.ts +9 -3
  47. package/dist/flow-file.js +21 -1
  48. package/dist/flow-halt.d.ts +16 -0
  49. package/dist/flow-halt.js +76 -0
  50. package/dist/flow-hidden.d.ts +9 -0
  51. package/dist/flow-hidden.js +20 -0
  52. package/dist/flow-lint.js +91 -1
  53. package/dist/flow-matrix-lint.d.ts +10 -0
  54. package/dist/flow-matrix-lint.js +40 -0
  55. package/dist/flow-matrix.d.ts +44 -0
  56. package/dist/flow-matrix.js +238 -0
  57. package/dist/flow-name-rules.d.ts +15 -0
  58. package/dist/flow-name-rules.js +39 -0
  59. package/dist/flow-runtime.d.ts +52 -22
  60. package/dist/flow-runtime.js +63 -117
  61. package/dist/flow-success.d.ts +3 -0
  62. package/dist/flow-success.js +37 -0
  63. package/dist/flow-tree.d.ts +2 -0
  64. package/dist/flow-tree.js +17 -5
  65. package/dist/flow-wait.d.ts +3 -0
  66. package/dist/flow-wait.js +22 -0
  67. package/dist/index.d.ts +5 -0
  68. package/dist/index.js +5 -0
  69. package/dist/matrix-spec.d.ts +145 -0
  70. package/dist/matrix-spec.js +120 -0
  71. package/dist/page-hide.d.ts +10 -0
  72. package/dist/page-hide.js +45 -0
  73. package/dist/page-settle.d.ts +39 -0
  74. package/dist/page-settle.js +142 -0
  75. package/dist/playwright-driver.d.ts +28 -8
  76. package/dist/playwright-driver.js +73 -28
  77. package/dist/plugins/manifest.d.ts +9 -9
  78. package/dist/run-flows.d.ts +40 -0
  79. package/dist/run-flows.js +129 -0
  80. package/dist/style.d.ts +2 -2
  81. package/dist/upload-path.d.ts +15 -0
  82. package/dist/upload-path.js +63 -0
  83. package/dist/verify-compare.d.ts +43 -0
  84. package/dist/verify-compare.js +237 -0
  85. package/dist/verify-determinism.d.ts +16 -0
  86. package/dist/verify-determinism.js +88 -0
  87. package/dist/verify-report.d.ts +53 -0
  88. package/dist/verify-report.js +141 -0
  89. package/dist/verify-tree.d.ts +27 -0
  90. package/dist/verify-tree.js +95 -0
  91. package/dist/viewer-bin.d.ts +6 -0
  92. package/dist/viewer-bin.js +24 -0
  93. package/dist/zip.d.ts +2 -2
  94. 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();
@@ -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,7 @@
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 { EGRESS_DENY_PRIVATE_ENV, EGRESS_GUARD_ENV, envFlagOff, envFlagOn, } from "./egress-guard.js";
11
12
  import { FlowFileError, parseFlowFile } from "./flow-file.js";
12
13
  import { chromiumExecutablePath } from "./playwright-driver.js";
13
14
  import { resolveViewerBin, VIEWER_BIN_ENV, VIEWER_BIN_NAME, VIEWER_PACKAGE } from "./viewer-bin.js";
@@ -317,7 +318,7 @@ export async function checkViewer(env, resolveFrom) {
317
318
  fix: `install ${VIEWER_PACKAGE} next to the engine (a global \`docsxai\` install ships it), or point ${VIEWER_BIN_ENV} at its bin script`,
318
319
  };
319
320
  }
320
- /** DOCSX_* env vars the docsxai packages read (engine + backend). */
321
+ /** DOCSX_* env vars the docsxai packages read (engine, viewer, backend + mcp). */
321
322
  export const KNOWN_DOCSX_ENV_VARS = [
322
323
  "DOCSX_TOKEN",
323
324
  "DOCSX_CACHE_KEY",
@@ -326,7 +327,29 @@ export const KNOWN_DOCSX_ENV_VARS = [
326
327
  "DOCSX_DATA_DIR",
327
328
  "DOCSX_OAUTH_AUTO_APPROVE",
328
329
  "DOCSX_WEBHOOK_SECRET",
330
+ "DOCSX_OXIPNG_BIN",
331
+ "DOCSX_BACKEND_DENY_PRIVATE_APP_URL",
332
+ "DOCSX_EGRESS_GUARD",
333
+ "DOCSX_EGRESS_DENY_PRIVATE",
334
+ "DOCSX_MCP_TOKEN",
329
335
  ];
336
+ /** On/off switches: `1`, `true` or `yes` turns one on; anything else non-empty, `0`/`false`/`no` aside, is read as off. */
337
+ const FLAG_ENV_VARS = [
338
+ "DOCSX_BACKEND_DENY_PRIVATE_APP_URL",
339
+ EGRESS_GUARD_ENV,
340
+ EGRESS_DENY_PRIVATE_ENV,
341
+ ];
342
+ function misspelledFlags(env) {
343
+ return FLAG_ENV_VARS.filter((k) => {
344
+ const v = env[k];
345
+ return v !== undefined && v.trim() !== "" && !envFlagOn(v) && !envFlagOff(v);
346
+ }).map((k) => ({
347
+ name: "env",
348
+ ok: false,
349
+ detail: `${k}=${JSON.stringify(env[k])} is not an on/off value, so the switch is off`,
350
+ fix: "use 1, true or yes to turn it on, or unset it",
351
+ }));
352
+ }
330
353
  export function checkEnv(env) {
331
354
  const set = Object.keys(env)
332
355
  .filter((k) => k.startsWith("DOCSX_"))
@@ -341,6 +364,7 @@ export function checkEnv(env) {
341
364
  if (known.length > 0) {
342
365
  checks.push({ name: "env", ok: true, detail: `set: ${known.join(", ")}` });
343
366
  }
367
+ checks.push(...misspelledFlags(env));
344
368
  const cacheKey = env.DOCSX_CACHE_KEY;
345
369
  if (cacheKey) {
346
370
  const decoded = Buffer.from(cacheKey, "base64");
@@ -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>;
@@ -0,0 +1,136 @@
1
+ // Opt-in request guard for the browser a run drives. With `DOCSX_EGRESS_GUARD=1` (or an explicit
2
+ // `egressGuard` option on `launchPlaywrightSession`) every request the page makes is checked
3
+ // before it leaves: documents, subresources, fetches and each redirect hop (Chromium reports a
4
+ // redirect as a new request). A request whose host is, or resolves to, a link-local or
5
+ // cloud-metadata address is aborted; with `DOCSX_EGRESS_DENY_PRIVATE=1` loopback, RFC 1918, CGNAT
6
+ // and unique-local addresses are aborted too. A lookup that fails or returns nothing aborts the
7
+ // request.
8
+ //
9
+ // WebSocket connections go through the same check (`routeWebSocket`). What the run's output says is
10
+ // generic ("address not allowed"): the resolved address stays in the `detail` argument of
11
+ // `onBlock`, which nothing writes to stderr.
12
+ //
13
+ // Not covered: the name is resolved here and again by the browser, so a DNS answer that changes
14
+ // between the two (DNS rebinding) gets through. Put an egress firewall under a hosted
15
+ // deployment. This module has no Playwright import: the driver hands it a context.
16
+ import { lookup as dnsLookup } from "node:dns/promises";
17
+ import { hostProblem, parseIpv4, parseIpv6 } from "./address-class.js";
18
+ export const EGRESS_GUARD_ENV = "DOCSX_EGRESS_GUARD";
19
+ export const EGRESS_DENY_PRIVATE_ENV = "DOCSX_EGRESS_DENY_PRIVATE";
20
+ /** True for `1`, `true` and `yes` in any case. */
21
+ export function envFlagOn(value) {
22
+ return value !== undefined && /^(?:1|true|yes)$/i.test(value.trim());
23
+ }
24
+ /** True for `0`, `false` and `no` in any case, the spellings that say off on purpose. */
25
+ export function envFlagOff(value) {
26
+ return value !== undefined && /^(?:0|false|no)$/i.test(value.trim());
27
+ }
28
+ /** The guard `env` asks for, or undefined when `DOCSX_EGRESS_GUARD` is not on. */
29
+ export function egressGuardFromEnv(env) {
30
+ if (!envFlagOn(env[EGRESS_GUARD_ENV]))
31
+ return undefined;
32
+ return { denyPrivate: envFlagOn(env[EGRESS_DENY_PRIVATE_ENV]) };
33
+ }
34
+ /** An explicit option wins; otherwise the process environment decides. */
35
+ export function resolveEgressGuard(explicit, env = process.env) {
36
+ return explicit ?? egressGuardFromEnv(env);
37
+ }
38
+ /** Default longest wait for a hostname lookup. */
39
+ export const LOOKUP_TIMEOUT_MS = 5000;
40
+ /** `work`, or a rejection once `ms` have passed. */
41
+ function withDeadline(work, ms) {
42
+ let timer;
43
+ const deadline = new Promise((_, reject) => {
44
+ timer = setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms);
45
+ });
46
+ return Promise.race([work, deadline]).finally(() => clearTimeout(timer));
47
+ }
48
+ const defaultLookup = async (hostname) => (await dnsLookup(hostname, { all: true, verbatim: true })).map((a) => a.address);
49
+ /** Schemes that never leave the browser. */
50
+ const INERT_SCHEMES = new Set(["data:", "blob:", "about:"]);
51
+ const NETWORK_SCHEMES = new Set(["http:", "https:", "ws:", "wss:"]);
52
+ /** Why a request to `rawUrl` must not go out, or null when it may. */
53
+ export async function requestProblem(rawUrl, opts = {}) {
54
+ let url;
55
+ try {
56
+ url = new URL(rawUrl);
57
+ }
58
+ catch {
59
+ return "the URL does not parse";
60
+ }
61
+ if (INERT_SCHEMES.has(url.protocol))
62
+ return null;
63
+ if (!NETWORK_SCHEMES.has(url.protocol))
64
+ return `the ${url.protocol} scheme is not allowed`;
65
+ const denyPrivate = opts.denyPrivate === true;
66
+ const host = url.hostname.replace(/\.+$/, "");
67
+ const direct = hostProblem(host, denyPrivate);
68
+ if (direct)
69
+ return `${host} is a ${direct} address`;
70
+ if (parseIpv4(host) || parseIpv6(host))
71
+ return null;
72
+ let addresses;
73
+ try {
74
+ const pending = Promise.resolve().then(() => (opts.lookup ?? defaultLookup)(host));
75
+ addresses = await withDeadline(pending, opts.lookupTimeoutMs ?? LOOKUP_TIMEOUT_MS);
76
+ }
77
+ catch (e) {
78
+ return `${host} did not resolve (${e.message}), refused`;
79
+ }
80
+ if (addresses.length === 0)
81
+ return `${host} resolved to no address, refused`;
82
+ for (const address of addresses) {
83
+ const problem = hostProblem(address, denyPrivate);
84
+ if (problem)
85
+ return `${host} resolves to ${address}, a ${problem} address`;
86
+ }
87
+ return null;
88
+ }
89
+ /** Context options a guarded context needs: a service worker's own fetches are not routed. */
90
+ export function egressContextOptions(guard) {
91
+ return guard ? { serviceWorkers: "block" } : {};
92
+ }
93
+ /** What the run's output says about a refused request. */
94
+ export const BLOCKED_REASON = "address not allowed";
95
+ /** `rawUrl` without userinfo, query and fragment, safe to print. */
96
+ export function printableUrl(rawUrl) {
97
+ try {
98
+ const url = new URL(rawUrl);
99
+ url.username = "";
100
+ url.password = "";
101
+ url.search = "";
102
+ url.hash = "";
103
+ return url.href;
104
+ }
105
+ catch {
106
+ return "<unparseable URL>";
107
+ }
108
+ }
109
+ /** Route every request and WebSocket of `context` through {@link requestProblem}; a no-op without a guard. */
110
+ export async function installEgressGuard(context, guard) {
111
+ if (!guard)
112
+ return;
113
+ /** The detail of why `rawUrl` is refused, or null; reports a refusal. A failed check refuses. */
114
+ const refusal = async (rawUrl) => {
115
+ const detail = await requestProblem(rawUrl, guard).catch((e) => `the check failed (${e.message}), refused`);
116
+ if (detail === null)
117
+ return null;
118
+ const shown = printableUrl(rawUrl);
119
+ if (guard.onBlock)
120
+ guard.onBlock(shown, BLOCKED_REASON, detail);
121
+ else
122
+ process.stderr.write(`egress-guard: blocked ${shown}: ${BLOCKED_REASON}\n`);
123
+ return detail;
124
+ };
125
+ await context.route(/.*/, async (route) => {
126
+ if ((await refusal(route.request().url())) === null)
127
+ return route.continue();
128
+ return route.abort("blockedbyclient");
129
+ });
130
+ await context.routeWebSocket(/.*/, async (ws) => {
131
+ if ((await refusal(ws.url())) === null)
132
+ ws.connectToServer();
133
+ else
134
+ await ws.close();
135
+ });
136
+ }
@@ -0,0 +1,67 @@
1
+ import { z } from "zod";
2
+ export declare const ViewportSize: z.ZodObject<{
3
+ width: z.ZodNumber;
4
+ height: z.ZodNumber;
5
+ }, "strict", z.ZodTypeAny, {
6
+ width: number;
7
+ height: number;
8
+ }, {
9
+ width: number;
10
+ height: number;
11
+ }>;
12
+ export type ViewportSize = z.infer<typeof ViewportSize>;
13
+ export declare const ViewportPreset: z.ZodEnum<["desktop", "tablet", "mobile"]>;
14
+ export type ViewportPreset = z.infer<typeof ViewportPreset>;
15
+ /** Named viewport presets — `desktop` 1440×900, `tablet` 834×1112, `mobile` 390×844. */
16
+ export declare const VIEWPORT_PRESETS: Record<ViewportPreset, ViewportSize>;
17
+ /** BCP-47 language tag (e.g. `en-GB`); shared by `environment.locale`, matrix locales and `copy_by_locale` keys. */
18
+ export declare const LocaleTag: z.ZodString;
19
+ export declare const ColorScheme: z.ZodEnum<["light", "dark"]>;
20
+ export type ColorScheme = z.infer<typeof ColorScheme>;
21
+ /**
22
+ * Deterministic execution environment for a flow. All fields optional; applied at browser-context
23
+ * creation (so the whole flow runs under them). With `extends`, the child flow's `environment`
24
+ * wins per-key over the parent's (a child can pin just `viewport` and inherit the parent's clock).
25
+ */
26
+ export declare const EnvironmentSpec: z.ZodObject<{
27
+ /** ISO-8601 instant the page clock is frozen at — `new Date()` etc. return this for the whole run. */
28
+ clock: z.ZodOptional<z.ZodString>;
29
+ /** BCP-47 language tag (e.g. `en-GB`). */
30
+ locale: z.ZodOptional<z.ZodString>;
31
+ /** IANA timezone (e.g. `Europe/Amsterdam`). */
32
+ timezone: z.ZodOptional<z.ZodString>;
33
+ /** `{ width, height }` in CSS pixels, or a named preset — see {@link VIEWPORT_PRESETS}. */
34
+ viewport: z.ZodOptional<z.ZodUnion<[z.ZodEnum<["desktop", "tablet", "mobile"]>, z.ZodObject<{
35
+ width: z.ZodNumber;
36
+ height: z.ZodNumber;
37
+ }, "strict", z.ZodTypeAny, {
38
+ width: number;
39
+ height: number;
40
+ }, {
41
+ width: number;
42
+ height: number;
43
+ }>]>>;
44
+ color_scheme: z.ZodOptional<z.ZodEnum<["light", "dark"]>>;
45
+ reduced_motion: z.ZodOptional<z.ZodBoolean>;
46
+ }, "strict", z.ZodTypeAny, {
47
+ clock?: string | undefined;
48
+ locale?: string | undefined;
49
+ timezone?: string | undefined;
50
+ viewport?: {
51
+ width: number;
52
+ height: number;
53
+ } | "desktop" | "tablet" | "mobile" | undefined;
54
+ color_scheme?: "light" | "dark" | undefined;
55
+ reduced_motion?: boolean | undefined;
56
+ }, {
57
+ clock?: string | undefined;
58
+ locale?: string | undefined;
59
+ timezone?: string | undefined;
60
+ viewport?: {
61
+ width: number;
62
+ height: number;
63
+ } | "desktop" | "tablet" | "mobile" | undefined;
64
+ color_scheme?: "light" | "dark" | undefined;
65
+ reduced_motion?: boolean | undefined;
66
+ }>;
67
+ export type EnvironmentSpec = z.infer<typeof EnvironmentSpec>;