@docsxai/engine 0.2.0 → 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 (89) hide show
  1. package/README.md +26 -6
  2. package/dist/address-class.d.ts +14 -0
  3. package/dist/address-class.js +151 -0
  4. package/dist/auth/api-login.js +6 -2
  5. package/dist/backend-client-contracts.d.ts +2 -0
  6. package/dist/calibrate.js +5 -0
  7. package/dist/cli-commands-authoring.js +23 -4
  8. package/dist/cli-commands-backend.js +2 -2
  9. package/dist/cli-commands-docpack.d.ts +5 -0
  10. package/dist/cli-commands-docpack.js +70 -24
  11. package/dist/cli-commands-pack.d.ts +2 -0
  12. package/dist/cli-commands-pack.js +69 -0
  13. package/dist/cli-commands-session.js +92 -88
  14. package/dist/cli-retired.d.ts +6 -0
  15. package/dist/cli-retired.js +12 -0
  16. package/dist/cli-usage.d.ts +1 -1
  17. package/dist/cli-usage.js +53 -5
  18. package/dist/cli-verify.d.ts +14 -0
  19. package/dist/cli-verify.js +54 -0
  20. package/dist/cli.js +14 -1
  21. package/dist/deprecation.d.ts +19 -0
  22. package/dist/deprecation.js +32 -0
  23. package/dist/diagnose.d.ts +25 -0
  24. package/dist/diagnose.js +69 -3
  25. package/dist/diff-compute.js +1 -0
  26. package/dist/doc-pack-io.d.ts +14 -0
  27. package/dist/doc-pack-io.js +121 -14
  28. package/dist/doc-pack.d.ts +2165 -181
  29. package/dist/doc-pack.js +152 -42
  30. package/dist/doctor-checks.d.ts +1 -1
  31. package/dist/doctor-checks.js +29 -5
  32. package/dist/driver-budget.d.ts +6 -0
  33. package/dist/driver-budget.js +15 -0
  34. package/dist/egress-guard.d.ts +58 -0
  35. package/dist/egress-guard.js +136 -0
  36. package/dist/environment-spec.d.ts +67 -0
  37. package/dist/environment-spec.js +38 -0
  38. package/dist/export/playwright-test.js +42 -10
  39. package/dist/flow-file.d.ts +7 -1
  40. package/dist/flow-file.js +21 -1
  41. package/dist/flow-halt.d.ts +16 -0
  42. package/dist/flow-halt.js +76 -0
  43. package/dist/flow-hidden.d.ts +9 -0
  44. package/dist/flow-hidden.js +20 -0
  45. package/dist/flow-lint.js +91 -1
  46. package/dist/flow-matrix-lint.d.ts +10 -0
  47. package/dist/flow-matrix-lint.js +40 -0
  48. package/dist/flow-matrix.d.ts +44 -0
  49. package/dist/flow-matrix.js +238 -0
  50. package/dist/flow-name-rules.d.ts +15 -0
  51. package/dist/flow-name-rules.js +39 -0
  52. package/dist/flow-runtime.d.ts +67 -21
  53. package/dist/flow-runtime.js +72 -110
  54. package/dist/flow-success.d.ts +3 -0
  55. package/dist/flow-success.js +37 -0
  56. package/dist/flow-tree.d.ts +2 -0
  57. package/dist/flow-tree.js +17 -5
  58. package/dist/flow-wait.d.ts +3 -0
  59. package/dist/flow-wait.js +22 -0
  60. package/dist/index.d.ts +6 -0
  61. package/dist/index.js +6 -0
  62. package/dist/matrix-spec.d.ts +145 -0
  63. package/dist/matrix-spec.js +120 -0
  64. package/dist/obstacles.d.ts +33 -0
  65. package/dist/obstacles.js +72 -0
  66. package/dist/page-hide.d.ts +10 -0
  67. package/dist/page-hide.js +45 -0
  68. package/dist/page-nearby-boxes.d.ts +9 -0
  69. package/dist/page-nearby-boxes.js +92 -0
  70. package/dist/page-settle.d.ts +39 -0
  71. package/dist/page-settle.js +142 -0
  72. package/dist/playwright-driver.d.ts +30 -8
  73. package/dist/playwright-driver.js +88 -18
  74. package/dist/run-flows.d.ts +40 -0
  75. package/dist/run-flows.js +129 -0
  76. package/dist/upload-path.d.ts +15 -0
  77. package/dist/upload-path.js +63 -0
  78. package/dist/verify-compare.d.ts +43 -0
  79. package/dist/verify-compare.js +237 -0
  80. package/dist/verify-determinism.d.ts +16 -0
  81. package/dist/verify-determinism.js +88 -0
  82. package/dist/verify-report.d.ts +53 -0
  83. package/dist/verify-report.js +141 -0
  84. package/dist/verify-tree.d.ts +27 -0
  85. package/dist/verify-tree.js +95 -0
  86. package/dist/viewer-bin.d.ts +6 -0
  87. package/dist/viewer-bin.js +24 -0
  88. package/dist/workspace.d.ts +8 -0
  89. package/package.json +7 -6
@@ -0,0 +1,120 @@
1
+ // Flow matrix schema: the `matrix:` block, the `only:` / `skip:` variant selectors, and the
2
+ // `variant` record `annotations.json` carries. A leaf module (imports zod and the environment
3
+ // schema); `doc-pack.ts` re-exports it. Expansion itself lives in `flow-matrix.ts`.
4
+ import { z } from "zod";
5
+ import { ColorScheme, LocaleTag, VIEWPORT_PRESETS, ViewportPreset, } from "./environment-spec.js";
6
+ /** Most variants one flow may expand to. A flow over the cap is rejected at parse time. */
7
+ export const MAX_MATRIX_VARIANTS = 64;
8
+ /** A viewport's matrix name: also a directory segment, so no dots, slashes or capitals. */
9
+ const ViewportName = z
10
+ .string()
11
+ .regex(/^[a-z0-9][a-z0-9-]*$/, "must be lowercase letters, digits and dashes (e.g. mobile-390)");
12
+ /** A matrix viewport: a preset name, or a size with an optional name (default `<width>x<height>`). */
13
+ export const MatrixViewport = z.union([
14
+ ViewportPreset,
15
+ z
16
+ .object({
17
+ name: ViewportName.optional(),
18
+ width: z.number().int().positive(),
19
+ height: z.number().int().positive(),
20
+ })
21
+ .strict(),
22
+ ]);
23
+ export function resolveMatrixViewport(entry) {
24
+ if (typeof entry === "string")
25
+ return { name: entry, ...VIEWPORT_PRESETS[entry] };
26
+ return {
27
+ name: entry.name ?? `${entry.width}x${entry.height}`,
28
+ width: entry.width,
29
+ height: entry.height,
30
+ };
31
+ }
32
+ const axisList = (item) => z.array(item).min(1).max(MAX_MATRIX_VARIANTS);
33
+ function duplicates(values) {
34
+ const seen = new Set();
35
+ const dupes = new Set();
36
+ for (const v of values) {
37
+ if (seen.has(v))
38
+ dupes.add(v);
39
+ seen.add(v);
40
+ }
41
+ return [...dupes];
42
+ }
43
+ /**
44
+ * The `matrix:` block of a flow-file. Each axis is a bounded list; the flow expands to the product
45
+ * of the axes it names. Locale and viewport entries must be unique (locales ignoring case,
46
+ * viewports by name), and the product may not pass {@link MAX_MATRIX_VARIANTS}.
47
+ */
48
+ export const MatrixSpec = z
49
+ .object({
50
+ locales: axisList(LocaleTag).optional(),
51
+ color_schemes: axisList(ColorScheme).optional(),
52
+ viewports: axisList(MatrixViewport).optional(),
53
+ })
54
+ .strict()
55
+ .superRefine((m, ctx) => {
56
+ const sizes = [m.locales, m.color_schemes, m.viewports].map((l) => l?.length);
57
+ if (sizes.every((n) => n === undefined)) {
58
+ ctx.addIssue({
59
+ code: "custom",
60
+ message: "`matrix` needs at least one of `locales`, `color_schemes`, `viewports`",
61
+ });
62
+ return;
63
+ }
64
+ const lists = [
65
+ ["locales", m.locales?.map((l) => l.toLowerCase())],
66
+ ["color_schemes", m.color_schemes],
67
+ ["viewports", m.viewports?.map((v) => resolveMatrixViewport(v).name)],
68
+ ];
69
+ for (const [key, values] of lists) {
70
+ const dupes = values ? duplicates(values) : [];
71
+ if (dupes.length) {
72
+ ctx.addIssue({
73
+ code: "custom",
74
+ path: [key],
75
+ message: `duplicate entries: ${dupes.map((d) => `"${d}"`).join(", ")}`,
76
+ });
77
+ }
78
+ }
79
+ const product = sizes.reduce((n, s) => n * (s ?? 1), 1);
80
+ if (product > MAX_MATRIX_VARIANTS) {
81
+ ctx.addIssue({
82
+ code: "custom",
83
+ message: `matrix expands to ${product} variants (${sizes
84
+ .map((s, i) => `${["locales", "color_schemes", "viewports"][i]}: ${s ?? 0}`)
85
+ .join(", ")}); the limit is ${MAX_MATRIX_VARIANTS}`,
86
+ });
87
+ }
88
+ });
89
+ /**
90
+ * Which variants a step or annotation applies to (`only`) or is dropped from (`skip`). A clause
91
+ * names axes; it matches a variant when every axis it names matches (any value in the list).
92
+ * `viewport` values are matrix viewport names, `locale` values match exactly or by language
93
+ * (`es` matches `es-ES`).
94
+ */
95
+ export const VariantSelector = z
96
+ .object({
97
+ viewport: z.array(ViewportName).min(1).optional(),
98
+ color_scheme: z.array(ColorScheme).min(1).optional(),
99
+ locale: z.array(LocaleTag).min(1).optional(),
100
+ })
101
+ .strict()
102
+ .refine((s) => Object.keys(s).length > 0, {
103
+ message: "name at least one of `viewport`, `color_scheme`, `locale`",
104
+ });
105
+ /** The variant a run executed, recorded as `variant` in `annotations.json`. */
106
+ export const VariantInfo = z
107
+ .object({
108
+ id: z.string().min(1),
109
+ locale: LocaleTag.optional(),
110
+ color_scheme: ColorScheme.optional(),
111
+ viewport: z
112
+ .object({
113
+ name: z.string().min(1),
114
+ width: z.number().int().positive(),
115
+ height: z.number().int().positive(),
116
+ })
117
+ .strict()
118
+ .optional(),
119
+ })
120
+ .strict();
@@ -0,0 +1,33 @@
1
+ import { type BoundingBox } from "./doc-pack.js";
2
+ /** How far from the target (CSS px) page content still counts as an obstacle. */
3
+ export declare const OBSTACLE_RADIUS = 320;
4
+ /** The most obstacles one annotation records; the ones nearest the target win. */
5
+ export declare const OBSTACLE_LIMIT = 40;
6
+ /** What a driver reports about the content around a target. Every box is in screenshot pixels. */
7
+ export interface NearbyBoxes {
8
+ /** Screenshot size (viewport × device scale factor). */
9
+ image: {
10
+ width: number;
11
+ height: number;
12
+ };
13
+ /** Device scale factor: screenshot pixels per CSS pixel. */
14
+ scale: number;
15
+ /** Boxes of visible text and interactive elements, the target and its subtree already left out. */
16
+ boxes: BoundingBox[];
17
+ }
18
+ export interface SelectOptions {
19
+ /** Distance cut-off in CSS px. Default {@link OBSTACLE_RADIUS}. */
20
+ radius?: number;
21
+ /** Cap on the number of boxes. Default {@link OBSTACLE_LIMIT}. */
22
+ limit?: number;
23
+ }
24
+ /**
25
+ * Pick the obstacles for one annotation. `target` is the annotation's own box (screenshot px).
26
+ *
27
+ * Boxes are rounded outward to whole pixels, clipped to the image, and dropped when empty, when
28
+ * farther than the radius from the target, when they sit entirely inside the target, or when
29
+ * another kept box already covers them (a label inside a button). Duplicates collapse to one. If
30
+ * more than the limit remain, the nearest to the target are kept. The result is sorted by y, x,
31
+ * width, height.
32
+ */
33
+ export declare function selectObstacles(scan: NearbyBoxes, target: BoundingBox, options?: SelectOptions): BoundingBox[];
@@ -0,0 +1,72 @@
1
+ // Obstacle selection — the pure half of `annotations.obstacles`.
2
+ //
3
+ // A driver reports the boxes of visible text and controls near an annotation's target
4
+ // ({@link NearbyBoxes}). This module turns that raw scan into the `obstacles` array written on an
5
+ // annotation record: boxes in screenshot pixels that a burned callout must not cover. No IO, no
6
+ // browser: same scan in, same boxes out, so the doc pack stays byte-identical across runs.
7
+ import { MAX_OBSTACLES } from "./doc-pack.js";
8
+ /** How far from the target (CSS px) page content still counts as an obstacle. */
9
+ export const OBSTACLE_RADIUS = 320;
10
+ /** The most obstacles one annotation records; the ones nearest the target win. */
11
+ export const OBSTACLE_LIMIT = MAX_OBSTACLES;
12
+ const EPSILON = 1e-6;
13
+ const edges = (b) => ({
14
+ left: b.x,
15
+ top: b.y,
16
+ right: b.x + b.width,
17
+ bottom: b.y + b.height,
18
+ });
19
+ /** Integer box that contains `b`, clipped to the image; `null` when nothing of it is left. */
20
+ function clipOutward(b, image) {
21
+ const e = edges(b);
22
+ const left = Math.max(0, Math.floor(e.left + EPSILON));
23
+ const top = Math.max(0, Math.floor(e.top + EPSILON));
24
+ const right = Math.min(image.width, Math.ceil(e.right - EPSILON));
25
+ const bottom = Math.min(image.height, Math.ceil(e.bottom - EPSILON));
26
+ if (right <= left || bottom <= top)
27
+ return null;
28
+ return { x: left, y: top, width: right - left, height: bottom - top };
29
+ }
30
+ /** Straight-line gap between two boxes; 0 when they touch or overlap. */
31
+ function gap(a, b) {
32
+ const ea = edges(a);
33
+ const eb = edges(b);
34
+ const dx = Math.max(0, ea.left - eb.right, eb.left - ea.right);
35
+ const dy = Math.max(0, ea.top - eb.bottom, eb.top - ea.bottom);
36
+ return Math.hypot(dx, dy);
37
+ }
38
+ /** True when `inner` lies entirely inside `outer` (equal boxes count). */
39
+ function contains(outer, inner) {
40
+ const o = edges(outer);
41
+ const i = edges(inner);
42
+ return o.left <= i.left && o.top <= i.top && o.right >= i.right && o.bottom >= i.bottom;
43
+ }
44
+ const byPosition = (a, b) => a.y - b.y || a.x - b.x || a.width - b.width || a.height - b.height;
45
+ /**
46
+ * Pick the obstacles for one annotation. `target` is the annotation's own box (screenshot px).
47
+ *
48
+ * Boxes are rounded outward to whole pixels, clipped to the image, and dropped when empty, when
49
+ * farther than the radius from the target, when they sit entirely inside the target, or when
50
+ * another kept box already covers them (a label inside a button). Duplicates collapse to one. If
51
+ * more than the limit remain, the nearest to the target are kept. The result is sorted by y, x,
52
+ * width, height.
53
+ */
54
+ export function selectObstacles(scan, target, options = {}) {
55
+ const radius = (options.radius ?? OBSTACLE_RADIUS) * scan.scale;
56
+ const limit = options.limit ?? OBSTACLE_LIMIT;
57
+ const unique = new Map();
58
+ for (const raw of scan.boxes) {
59
+ const box = clipOutward(raw, scan.image);
60
+ if (!box || contains(target, box) || gap(box, target) > radius)
61
+ continue;
62
+ unique.set(`${box.x},${box.y},${box.width},${box.height}`, box);
63
+ }
64
+ const candidates = [...unique.values()];
65
+ const exposed = candidates.filter((box) => !candidates.some((other) => other !== box && contains(other, box)));
66
+ return exposed
67
+ .map((box) => ({ box, distance: gap(box, target) }))
68
+ .sort((a, b) => a.distance - b.distance || byPosition(a.box, b.box))
69
+ .slice(0, limit)
70
+ .map(({ box }) => box)
71
+ .sort(byPosition);
72
+ }
@@ -0,0 +1,10 @@
1
+ /** Attribute that marks an element hidden by a `hide` step. The stylesheet rule keys on it. */
2
+ export declare const HIDDEN_ATTR = "data-docsxai-hidden";
3
+ /**
4
+ * Mark `els` hidden and make sure each one's root carries the rule that hides marked elements.
5
+ * Throws, before marking anything, when the page can't take a constructable stylesheet: leaving
6
+ * the element visible would put exactly what the step meant to remove into the screenshot.
7
+ */
8
+ export declare function markHidden(els: unknown[], attr: string): void;
9
+ /** Remove the hidden mark from `els`; the stylesheet stays, and matches nothing. */
10
+ export declare function unmarkHidden(els: unknown[], attr: string): void;
@@ -0,0 +1,45 @@
1
+ // In-page helpers behind `BrowserDriver.hideElements` / `showElements`.
2
+ //
3
+ // Both functions run inside the page (Playwright serializes them with `locator.evaluateAll`), so
4
+ // they stay self-contained: no imports of values, no references to module scope. They are fixed
5
+ // engine code. The flow supplies only a selector, which Playwright resolves to elements outside
6
+ // the page; nothing from the flow reaches the page as CSS or script.
7
+ //
8
+ // Hiding is `visibility: hidden !important`, applied through a constructable stylesheet adopted
9
+ // onto the element's own root (the document, or the shadow root the element lives in) and keyed
10
+ // by a data attribute. Visibility keeps the element's box, so nothing around it reflows, and it
11
+ // inherits into a shadow tree, so hiding a host hides its contents too. Constructable stylesheets
12
+ // and attribute writes are not blocked by a page's Content-Security-Policy; a `<style>` element
13
+ // would be. `transition: none` on the element and its descendants keeps the hide instant: a page
14
+ // that gives every element a tiny `transition-duration` (the usual reduced-motion reset) would
15
+ // otherwise hold `visibility: visible` for one more frame, long enough for a check that runs right
16
+ // after the step to see the element. The attribute name is reserved (see the flow-file reference). The DOM lib isn't in this package's TypeScript config, so the shapes used are local.
17
+ /** Attribute that marks an element hidden by a `hide` step. The stylesheet rule keys on it. */
18
+ export const HIDDEN_ATTR = "data-docsxai-hidden";
19
+ /**
20
+ * Mark `els` hidden and make sure each one's root carries the rule that hides marked elements.
21
+ * Throws, before marking anything, when the page can't take a constructable stylesheet: leaving
22
+ * the element visible would put exactly what the step meant to remove into the screenshot.
23
+ */
24
+ export function markHidden(els, attr) {
25
+ const sheetCtor = globalThis.CSSStyleSheet;
26
+ const roots = els.map((el) => el.getRootNode());
27
+ if (!sheetCtor || roots.some((r) => !r || !Array.isArray(r.adoptedStyleSheets))) {
28
+ throw new Error("docsxai: cannot hide: this browser has no constructable stylesheets (CSSStyleSheet / adoptedStyleSheets) for the element's document or shadow root");
29
+ }
30
+ for (const [i, el] of els.entries()) {
31
+ const root = roots[i];
32
+ el.setAttribute(attr, "");
33
+ const present = root.adoptedStyleSheets.some((s) => s.cssRules[0]?.cssText.startsWith(`[${attr}]`));
34
+ if (present)
35
+ continue;
36
+ const sheet = new sheetCtor();
37
+ sheet.replaceSync(`[${attr}] { visibility: hidden !important; } [${attr}], [${attr}] * { transition: none !important; }`);
38
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
39
+ }
40
+ }
41
+ /** Remove the hidden mark from `els`; the stylesheet stays, and matches nothing. */
42
+ export function unmarkHidden(els, attr) {
43
+ for (const el of els)
44
+ el.removeAttribute(attr);
45
+ }
@@ -0,0 +1,9 @@
1
+ import { type NearbyBoxes } from "./obstacles.js";
2
+ /**
3
+ * Boxes of the visible text and interactive elements within `radius` CSS px of `targetArg`, in
4
+ * screenshot pixels. Text is measured per rendered line (the text itself, not its block), so a
5
+ * paragraph beside the target contributes the lines that are there. Left out: anything inside the
6
+ * target, interactive elements that contain it, hidden or fully clipped content, scripts and styles.
7
+ * The result is in document order; `selectObstacles` sorts, clips and caps it.
8
+ */
9
+ export declare function collectNearbyBoxes(targetArg: unknown, radius: number): NearbyBoxes;
@@ -0,0 +1,92 @@
1
+ // In-page scan behind `BrowserDriver.nearbyBoxes`.
2
+ //
3
+ // `collectNearbyBoxes` runs inside the page (Playwright serializes it with `locator.evaluate`), so
4
+ // it must stay self-contained: no imports of values, no references to module scope. It imports no
5
+ // Playwright either; the driver is the only module that does. The DOM lib isn't in this package's
6
+ // TypeScript config, so the few DOM shapes it touches are declared locally.
7
+ /**
8
+ * Boxes of the visible text and interactive elements within `radius` CSS px of `targetArg`, in
9
+ * screenshot pixels. Text is measured per rendered line (the text itself, not its block), so a
10
+ * paragraph beside the target contributes the lines that are there. Left out: anything inside the
11
+ * target, interactive elements that contain it, hidden or fully clipped content, scripts and styles.
12
+ * The result is in document order; `selectObstacles` sorts, clips and caps it.
13
+ */
14
+ export function collectNearbyBoxes(targetArg, radius) {
15
+ const target = targetArg;
16
+ const doc = target.ownerDocument;
17
+ const view = doc.defaultView;
18
+ const dpr = view.devicePixelRatio || 1;
19
+ const t = target.getBoundingClientRect();
20
+ const near = {
21
+ left: t.left - radius,
22
+ top: t.top - radius,
23
+ right: t.right + radius,
24
+ bottom: t.bottom + radius,
25
+ };
26
+ const boxes = [];
27
+ // Add `r` (viewport CSS px) when `owner` renders it: visible, not clipped away by an ancestor's
28
+ // overflow, and inside the viewport. `clipSelf` lets the owner's own overflow clip text it holds.
29
+ const add = (r, owner, clipSelf) => {
30
+ let { left, top, right, bottom } = r;
31
+ left = Math.max(left, 0);
32
+ top = Math.max(top, 0);
33
+ right = Math.min(right, view.innerWidth);
34
+ bottom = Math.min(bottom, view.innerHeight);
35
+ for (let cur = owner; cur; cur = cur.parentElement) {
36
+ const cs = view.getComputedStyle(cur);
37
+ if (cs.display === "none" || cs.opacity === "0")
38
+ return;
39
+ if (cur === owner && cs.visibility !== "visible")
40
+ return;
41
+ const clips = cs.overflow !== "visible" || cs.overflowX !== "visible" || cs.overflowY !== "visible";
42
+ if (clips && (cur !== owner || clipSelf)) {
43
+ const cr = cur.getBoundingClientRect();
44
+ left = Math.max(left, cr.left);
45
+ top = Math.max(top, cr.top);
46
+ right = Math.min(right, cr.right);
47
+ bottom = Math.min(bottom, cr.bottom);
48
+ }
49
+ }
50
+ if (right <= left || bottom <= top)
51
+ return;
52
+ if (right < near.left || left > near.right || bottom < near.top || top > near.bottom)
53
+ return;
54
+ boxes.push({
55
+ x: left * dpr,
56
+ y: top * dpr,
57
+ width: (right - left) * dpr,
58
+ height: (bottom - top) * dpr,
59
+ });
60
+ };
61
+ const controls = doc.querySelectorAll('a[href], button, input:not([type="hidden"]), select, textarea, summary, ' +
62
+ '[role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="switch"], ' +
63
+ '[role="tab"], [role="menuitem"], [role="combobox"], [role="option"], ' +
64
+ '[contenteditable=""], [contenteditable="true"], [tabindex]:not([tabindex^="-"])');
65
+ for (let i = 0; i < controls.length; i++) {
66
+ const el = controls[i];
67
+ if (el === target || target.contains(el) || el.contains(target))
68
+ continue;
69
+ add(el.getBoundingClientRect(), el, false);
70
+ }
71
+ if (doc.body) {
72
+ const range = doc.createRange();
73
+ const walker = doc.createTreeWalker(doc.body, 4); // NodeFilter.SHOW_TEXT
74
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
75
+ const text = n;
76
+ const owner = text.parentElement;
77
+ if (!owner || !/\S/.test(text.nodeValue ?? "") || target.contains(n))
78
+ continue;
79
+ if (/^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(owner.tagName))
80
+ continue;
81
+ range.selectNodeContents(n);
82
+ const lines = range.getClientRects();
83
+ for (let i = 0; i < lines.length; i++)
84
+ add(lines[i], owner, true);
85
+ }
86
+ }
87
+ return {
88
+ image: { width: Math.round(view.innerWidth * dpr), height: Math.round(view.innerHeight * dpr) },
89
+ scale: dpr,
90
+ boxes,
91
+ };
92
+ }
@@ -0,0 +1,39 @@
1
+ /** Pause between two polls, in ms. */
2
+ export declare const SETTLE_POLL_INTERVAL_MS = 50;
3
+ /** Consecutive calm polls that count as settled. */
4
+ export declare const SETTLE_STABLE_POLLS = 2;
5
+ /** Most elements one poll reads boxes for. */
6
+ export declare const SETTLE_MAX_VISITED = 4000;
7
+ /** Budget when the step sets no `timeout_ms`, in ms. */
8
+ export declare const SETTLE_DEFAULT_TIMEOUT_MS = 10000;
9
+ export interface SettleArgs {
10
+ timeoutMs: number;
11
+ pollMs: number;
12
+ stablePolls: number;
13
+ maxVisited: number;
14
+ }
15
+ export interface SettleOutcome {
16
+ settled: boolean;
17
+ /** Polls run. Capped at `ceil(timeoutMs / pollMs)`. */
18
+ polls: number;
19
+ /** What was still unsettled at the last poll: `fonts`, `images` and `layout`. Empty when settled. */
20
+ pending: string[];
21
+ /** Visible images still loading at the last poll. */
22
+ pendingImages: number;
23
+ }
24
+ /**
25
+ * Resolves with the page's state once it settles or the budget is spent. Every clock and promise
26
+ * in here (`Date.now`, `setTimeout`, `document.fonts.ready`) belongs to the page and a page can
27
+ * stall or override them, so the deadline in this function is a courtesy. The bound that holds is
28
+ * the Node-side `budgetMs + 2000` guard in `runSettle`.
29
+ */
30
+ export declare function awaitSettled(a: SettleArgs): Promise<SettleOutcome>;
31
+ /** The message a driver rejects with when the budget runs out; the runtime's halt-cause hint keys on its start. */
32
+ export declare function settleFailure(timeoutMs: number, outcome: SettleOutcome): string;
33
+ /**
34
+ * Run the settle poll through `evaluate` (the driver's page-evaluate of {@link awaitSettled}) and
35
+ * reject with {@link settleFailure} when it does not settle. The in-page poll keeps its own
36
+ * deadline; the outer timer covers a page that never answers (a blocked main thread), where that
37
+ * deadline cannot fire.
38
+ */
39
+ export declare function runSettle(evaluate: (args: SettleArgs) => Promise<SettleOutcome>, timeoutMs?: number): Promise<void>;
@@ -0,0 +1,142 @@
1
+ // In-page poll behind `BrowserDriver.waitForSettled`.
2
+ //
3
+ // `awaitSettled` runs inside the page (Playwright serializes it with `page.evaluate`), so it must
4
+ // stay self-contained: no imports of values, no references to module scope. It is fixed engine
5
+ // code that takes four numbers and nothing else: no selector and no flow value reaches the page.
6
+ // The DOM lib isn't in this package's TypeScript config, so the few DOM shapes it touches are
7
+ // declared locally.
8
+ //
9
+ // Settled means all of these hold on {@link SETTLE_STABLE_POLLS} polls in a row: no web font is
10
+ // loading, every `<img>` inside the viewport has finished loading, and the boxes of the elements
11
+ // inside the viewport did not move between two animation frames. A poll is one animation frame
12
+ // plus a fixed pause, repeated until the budget runs out. The geometry read is a box walk over the
13
+ // light DOM and open shadow roots, capped at `maxVisited` elements so a huge page stays cheap.
14
+ /** Pause between two polls, in ms. */
15
+ export const SETTLE_POLL_INTERVAL_MS = 50;
16
+ /** Consecutive calm polls that count as settled. */
17
+ export const SETTLE_STABLE_POLLS = 2;
18
+ /** Most elements one poll reads boxes for. */
19
+ export const SETTLE_MAX_VISITED = 4000;
20
+ /** Budget when the step sets no `timeout_ms`, in ms. */
21
+ export const SETTLE_DEFAULT_TIMEOUT_MS = 10_000;
22
+ /**
23
+ * Resolves with the page's state once it settles or the budget is spent. Every clock and promise
24
+ * in here (`Date.now`, `setTimeout`, `document.fonts.ready`) belongs to the page and a page can
25
+ * stall or override them, so the deadline in this function is a courtesy. The bound that holds is
26
+ * the Node-side `budgetMs + 2000` guard in `runSettle`.
27
+ */
28
+ export async function awaitSettled(a) {
29
+ const g = globalThis;
30
+ const deadline = Date.now() + a.timeoutMs;
31
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
32
+ // rAF is throttled in a hidden tab, so a timer backs the frame up and the poll still advances.
33
+ const frame = () => new Promise((resolve) => {
34
+ let done = false;
35
+ const finish = () => {
36
+ if (!done) {
37
+ done = true;
38
+ resolve();
39
+ }
40
+ };
41
+ g.requestAnimationFrame(finish);
42
+ setTimeout(finish, 250);
43
+ });
44
+ /** Boxes of the viewport-visible elements as a flat number list, plus how many images still load. */
45
+ const read = () => {
46
+ const boxes = [];
47
+ let pendingImages = 0;
48
+ let visited = 0;
49
+ const stack = g.document.body ? [g.document.body] : [];
50
+ while (stack.length > 0 && visited < a.maxVisited) {
51
+ const el = stack.pop();
52
+ visited++;
53
+ for (let i = el.children.length - 1; i >= 0; i--)
54
+ stack.push(el.children[i]);
55
+ if (el.shadowRoot) {
56
+ for (let i = el.shadowRoot.children.length - 1; i >= 0; i--)
57
+ stack.push(el.shadowRoot.children[i]);
58
+ }
59
+ const r = el.getBoundingClientRect();
60
+ // display:none (and detached) elements report a zero box at the origin; they paint nothing.
61
+ if (r.width === 0 && r.height === 0 && r.left === 0 && r.top === 0)
62
+ continue;
63
+ if (r.bottom < 0 || r.right < 0 || r.top >= g.innerHeight || r.left >= g.innerWidth)
64
+ continue;
65
+ // An image still loading can have no size yet, so it counts from the position it sits at.
66
+ if (el.tagName === "IMG" && el.complete === false)
67
+ pendingImages++;
68
+ if (r.width > 0 && r.height > 0)
69
+ boxes.push(r.left, r.top, r.width, r.height);
70
+ }
71
+ return { boxes, pendingImages };
72
+ };
73
+ const sameBoxes = (x, y) => x.length === y.length && x.every((v, i) => Math.abs(v - y[i]) <= 0.5);
74
+ // Fonts the page asked for so far. Fonts requested later show up as `loading` on a later poll.
75
+ const fonts = g.document.fonts;
76
+ if (fonts)
77
+ await Promise.race([fonts.ready, pause(Math.max(0, deadline - Date.now()))]);
78
+ let previous = null;
79
+ let calm = 0;
80
+ let polls = 0;
81
+ let pending = ["layout"];
82
+ let pendingImages = 0;
83
+ const maxPolls = Math.max(1, Math.ceil(a.timeoutMs / a.pollMs));
84
+ while (polls < maxPolls && Date.now() < deadline) {
85
+ await frame();
86
+ polls++;
87
+ const now = read();
88
+ pendingImages = now.pendingImages;
89
+ pending = [];
90
+ if (fonts && fonts.status === "loading")
91
+ pending.push("fonts");
92
+ if (now.pendingImages > 0)
93
+ pending.push("images");
94
+ if (previous === null || !sameBoxes(previous, now.boxes))
95
+ pending.push("layout");
96
+ previous = now.boxes;
97
+ calm = pending.length === 0 ? calm + 1 : 0;
98
+ if (calm >= a.stablePolls)
99
+ return { settled: true, polls, pending: [], pendingImages: 0 };
100
+ await pause(a.pollMs);
101
+ }
102
+ return { settled: false, polls, pending, pendingImages };
103
+ }
104
+ /** The message a driver rejects with when the budget runs out; the runtime's halt-cause hint keys on its start. */
105
+ export function settleFailure(timeoutMs, outcome) {
106
+ const still = outcome.pending.map((p) => p === "fonts"
107
+ ? "web fonts still loading"
108
+ : p === "images"
109
+ ? `${outcome.pendingImages} visible image(s) still loading`
110
+ : "layout of the visible elements still changing");
111
+ const detail = still.length > 0 ? `: ${still.join("; ")}` : "";
112
+ return `settled: page did not settle within ${timeoutMs} ms after ${outcome.polls} poll(s)${detail}`;
113
+ }
114
+ /**
115
+ * Run the settle poll through `evaluate` (the driver's page-evaluate of {@link awaitSettled}) and
116
+ * reject with {@link settleFailure} when it does not settle. The in-page poll keeps its own
117
+ * deadline; the outer timer covers a page that never answers (a blocked main thread), where that
118
+ * deadline cannot fire.
119
+ */
120
+ export async function runSettle(evaluate, timeoutMs) {
121
+ const budgetMs = timeoutMs ?? SETTLE_DEFAULT_TIMEOUT_MS;
122
+ let guard;
123
+ const unresponsive = new Promise((_, reject) => {
124
+ guard = setTimeout(() => reject(new Error(`settled: page did not settle within ${budgetMs} ms (the page stopped responding)`)), budgetMs + 2000);
125
+ });
126
+ try {
127
+ const outcome = await Promise.race([
128
+ evaluate({
129
+ timeoutMs: budgetMs,
130
+ pollMs: SETTLE_POLL_INTERVAL_MS,
131
+ stablePolls: SETTLE_STABLE_POLLS,
132
+ maxVisited: SETTLE_MAX_VISITED,
133
+ }),
134
+ unresponsive,
135
+ ]);
136
+ if (!outcome.settled)
137
+ throw new Error(settleFailure(budgetMs, outcome));
138
+ }
139
+ finally {
140
+ clearTimeout(guard);
141
+ }
142
+ }
@@ -1,7 +1,9 @@
1
1
  import { type Browser, type BrowserContext, type Page } from "playwright-core";
2
2
  import { type BoundingBox, type EnvironmentSpec, type ViewportSize } from "./doc-pack.js";
3
+ import { type EgressGuardOptions } from "./egress-guard.js";
3
4
  import { type ActionableState, type BrowserDriver, type ResolvedRedaction } from "./flow-runtime.js";
4
5
  import { type StorageState } from "./auth.js";
6
+ import { type NearbyBoxes } from "./obstacles.js";
5
7
  /**
6
8
  * The cached Chromium binary path, or `undefined` when `playwright-core` has none installed.
7
9
  *
@@ -37,6 +39,11 @@ export interface PlaywrightSessionOptions {
37
39
  chromiumArgs?: string[];
38
40
  /** Doc-pack root that screenshot paths are resolved against. */
39
41
  docPackRoot?: string;
42
+ /**
43
+ * Where screenshots are written, when that differs from `docPackRoot` (which keeps resolving
44
+ * `upload` sources). `run --verify-determinism` points it at an isolated per-run root. Default: `docPackRoot`.
45
+ */
46
+ outputRoot?: string;
40
47
  /** If set, attach to a running Chrome at this CDP endpoint (e.g. `http://localhost:9222`) instead of launching one. `close()` won't close it. */
41
48
  connectOverCdp?: string;
42
49
  /**
@@ -48,6 +55,8 @@ export interface PlaywrightSessionOptions {
48
55
  environment?: EnvironmentSpec;
49
56
  /** Extra `browser.newContext` options — see {@link SessionContextOptions}. Ignored with `connectOverCdp`. */
50
57
  contextOptions?: SessionContextOptions;
58
+ /** Refuse requests to link-local and metadata addresses (see `egress-guard.ts`). Default: `DOCSX_EGRESS_GUARD` in the environment decides. */
59
+ egressGuard?: EgressGuardOptions;
51
60
  }
52
61
  /** Map an {@link EnvironmentSpec} to the Playwright context options it pins (clock excluded — that's a page-level install). */
53
62
  export declare function environmentContextOptions(env: EnvironmentSpec): {
@@ -72,18 +81,30 @@ export declare function launchPlaywrightSession(opts?: PlaywrightSessionOptions)
72
81
  export declare class PlaywrightDriver implements BrowserDriver {
73
82
  private readonly page;
74
83
  private readonly docPackRoot;
75
- constructor(page: Page, docPackRoot?: string);
84
+ private readonly outputRoot;
85
+ constructor(page: Page, docPackRoot?: string, outputRoot?: string);
76
86
  goto(url: string): Promise<void>;
77
- click(selector: string): Promise<void>;
78
- fill(selector: string, value: string): Promise<void>;
79
- upload(selector: string, filePath: string): Promise<void>;
80
- press(selector: string | null, key: string): Promise<void>;
81
- hover(selector: string): Promise<void>;
82
- selectOption(selector: string, value: string): Promise<void>;
83
- setChecked(selector: string, checked: boolean): Promise<void>;
87
+ click(selector: string, timeoutMs?: number): Promise<void>;
88
+ fill(selector: string, value: string, timeoutMs?: number): Promise<void>;
89
+ upload(selector: string, filePath: string, timeoutMs?: number): Promise<void>;
90
+ press(selector: string | null, key: string, timeoutMs?: number): Promise<void>;
91
+ hover(selector: string, timeoutMs?: number): Promise<void>;
92
+ selectOption(selector: string, value: string, timeoutMs?: number): Promise<void>;
93
+ setChecked(selector: string, checked: boolean, timeoutMs?: number): Promise<void>;
94
+ /** Selectors a `hide` step registered; re-applied before every screenshot (see {@link syncHidden}). */
95
+ private readonly hidden;
96
+ hideElements(selector: string, timeoutMs?: number): Promise<void>;
97
+ showElements(selector: string | null): Promise<void>;
98
+ /**
99
+ * Re-mark every element a registered selector matches right now. Navigation drops the marks and
100
+ * a framework re-render can replace the elements, so the registry (not the DOM) is the source of
101
+ * truth and the marks are rebuilt from it. Unmark first so a `show` takes effect.
102
+ */
103
+ private syncHidden;
84
104
  waitForNetworkIdle(): Promise<void>;
85
105
  waitForLoad(): Promise<void>;
86
106
  waitForElementStable(selector: string): Promise<void>;
107
+ waitForSettled(timeoutMs?: number): Promise<void>;
87
108
  waitForSelector(selector: string, timeoutMs?: number): Promise<void>;
88
109
  waitForTimeout(ms: number): Promise<void>;
89
110
  isVisible(selector: string): Promise<boolean>;
@@ -93,6 +114,7 @@ export declare class PlaywrightDriver implements BrowserDriver {
93
114
  count(selector: string): Promise<number>;
94
115
  textOf(selector: string): Promise<string | null>;
95
116
  boundingBox(selector: string, timeoutMs?: number): Promise<BoundingBox | null>;
117
+ nearbyBoxes(selector: string, radius: number, timeoutMs?: number): Promise<NearbyBoxes | null>;
96
118
  screenshot(relPath: string, redactions?: ResolvedRedaction[]): Promise<void>;
97
119
  /**
98
120
  * Resolve redactions to pixel rects in the screenshot's device-pixel space: selector entries via