effect-browser 0.3.0-beta.23 → 0.3.0-beta.24

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 (134) hide show
  1. package/README.md +124 -5
  2. package/dist/ActionPort.d.mts +1 -1
  3. package/dist/ActionPort.mjs +1 -1
  4. package/dist/{Browser-BKPAbyys.mjs → Browser-CAQFhTkM.mjs} +559 -333
  5. package/dist/Browser-CAQFhTkM.mjs.map +1 -0
  6. package/dist/{Browser-wZhwZSlG.d.mts → Browser-DGR6ZEYo.d.mts} +9 -3
  7. package/dist/Browser.d.mts +1 -1
  8. package/dist/Browser.mjs +1 -1
  9. package/dist/{BrowserEvent-lLqJ3GJS.d.mts → BrowserEvent-C2p-NwuU.d.mts} +30 -6
  10. package/dist/BrowserEvent.d.mts +2 -2
  11. package/dist/BrowserEvent.mjs +20 -1
  12. package/dist/BrowserEvent.mjs.map +1 -1
  13. package/dist/{Change-Ba7INmay.d.mts → Change-CxT1mp2e.d.mts} +13 -2
  14. package/dist/Change.d.mts +1 -1
  15. package/dist/Change.mjs +7 -1
  16. package/dist/Change.mjs.map +1 -1
  17. package/dist/Clock-Du5nP-nK.d.mts +57 -0
  18. package/dist/Clock.d.mts +2 -57
  19. package/dist/Layout.d.mts +2 -0
  20. package/dist/Layout.mjs +81 -0
  21. package/dist/Layout.mjs.map +1 -0
  22. package/dist/Matching-MtcWZ_hA.d.mts +266 -0
  23. package/dist/Matching.d.mts +2 -37
  24. package/dist/Matching.mjs +22 -17
  25. package/dist/Matching.mjs.map +1 -1
  26. package/dist/Overlay-CoGw5tL_.d.mts +27 -0
  27. package/dist/Overlay.d.mts +2 -0
  28. package/dist/Overlay.mjs +30 -0
  29. package/dist/Overlay.mjs.map +1 -0
  30. package/dist/{Page-BF5izr8R.mjs → Page-BaAOshxo.mjs} +3 -1
  31. package/dist/Page-BaAOshxo.mjs.map +1 -0
  32. package/dist/{Page-CvsOEorc.d.mts → Page-CLzh5E9w.d.mts} +158 -6
  33. package/dist/Page.d.mts +2 -2
  34. package/dist/Page.mjs +1 -1
  35. package/dist/PageTime-68UPUZpZ.d.mts +29 -0
  36. package/dist/PageTime.d.mts +2 -0
  37. package/dist/PageTime.mjs +7 -0
  38. package/dist/PageTime.mjs.map +1 -0
  39. package/dist/Pose-2qqGzPvb.d.mts +32 -0
  40. package/dist/Pose.d.mts +2 -0
  41. package/dist/Pose.mjs +44 -0
  42. package/dist/Pose.mjs.map +1 -0
  43. package/dist/Site.d.mts +714 -0
  44. package/dist/Site.mjs +102 -0
  45. package/dist/Site.mjs.map +1 -0
  46. package/dist/{Stillness-CNlvayIo.mjs → Stillness-BwP0RdI4.mjs} +27 -6
  47. package/dist/Stillness-BwP0RdI4.mjs.map +1 -0
  48. package/dist/{Style-AO4V7Czt.mjs → Style-T3ezDYLI.mjs} +25 -2
  49. package/dist/{Style-AO4V7Czt.mjs.map → Style-T3ezDYLI.mjs.map} +1 -1
  50. package/dist/Style.d.mts +15 -2
  51. package/dist/Style.mjs +2 -2
  52. package/dist/Url-B7P-TWwL.d.mts +26 -0
  53. package/dist/Url.d.mts +2 -26
  54. package/dist/{Window-CMddGMt1.d.mts → Window-BDa8MtNP.d.mts} +4 -4
  55. package/dist/Window.d.mts +1 -1
  56. package/dist/{connection-CK83pvqP.mjs → connection-C_jWYIwe.mjs} +2 -2
  57. package/dist/{connection-CK83pvqP.mjs.map → connection-C_jWYIwe.mjs.map} +1 -1
  58. package/dist/{connection-2KHI4_KN.d.mts → connection-Db-YtlbE.d.mts} +2 -2
  59. package/dist/film/Film.d.mts +265 -0
  60. package/dist/film/Film.mjs +246 -0
  61. package/dist/film/Film.mjs.map +1 -0
  62. package/dist/fold.inpage-CyVZQHZL.d.mts +49 -0
  63. package/dist/index.d.mts +11 -8
  64. package/dist/index.mjs +8 -4
  65. package/dist/moment/Moment.d.mts +5 -5
  66. package/dist/plan/index.d.mts +2 -2
  67. package/dist/plan/index.mjs +2 -2
  68. package/dist/policy/Policy.d.mts +1 -1
  69. package/dist/policy/Policy.mjs +1 -1
  70. package/dist/pose.inpage-CLq7Mfdr.mjs +2042 -0
  71. package/dist/pose.inpage-CLq7Mfdr.mjs.map +1 -0
  72. package/dist/presentation/Presentation.d.mts +8 -1
  73. package/dist/presentation/Presentation.mjs +3 -1
  74. package/dist/presentation/Presentation.mjs.map +1 -1
  75. package/dist/presentation/Stage.d.mts +1 -1
  76. package/dist/providers/Cdp.d.mts +2 -2
  77. package/dist/providers/Cdp.mjs +1 -1
  78. package/dist/providers/Chromium.d.mts +1 -1
  79. package/dist/providers/Chromium.mjs +1 -1
  80. package/dist/stillness/Stillness.d.mts +1 -1
  81. package/dist/stillness/Stillness.mjs +1 -1
  82. package/dist/testing/index.d.mts +4 -30
  83. package/dist/testing/index.mjs +8 -2
  84. package/dist/testing/index.mjs.map +1 -1
  85. package/dist/workerd/Cdp.d.mts +2 -2
  86. package/dist/workerd/Cdp.mjs +1 -1
  87. package/package.json +32 -2
  88. package/src/Browser.ts +11 -6
  89. package/src/BrowserEvent.ts +19 -0
  90. package/src/Change.ts +7 -1
  91. package/src/Layout.ts +116 -0
  92. package/src/Matching.ts +24 -15
  93. package/src/Overlay.ts +37 -0
  94. package/src/Page.ts +45 -0
  95. package/src/PageTime.ts +47 -0
  96. package/src/Pose.ts +50 -0
  97. package/src/Site.ts +124 -0
  98. package/src/Style.ts +36 -0
  99. package/src/film/Film.ts +384 -0
  100. package/src/index.ts +4 -0
  101. package/src/internal/input/perform.ts +31 -3
  102. package/src/internal/input/pointer.ts +7 -4
  103. package/src/internal/input/targets.ts +1 -1
  104. package/src/internal/page/bridge.ts +65 -33
  105. package/src/internal/page/clock.inpage.ts +306 -0
  106. package/src/internal/page/compose.inpage.ts +101 -0
  107. package/src/internal/page/context.ts +2 -0
  108. package/src/internal/page/overlay.inpage.ts +96 -0
  109. package/src/internal/page/overlay.ts +89 -0
  110. package/src/internal/page/page.ts +12 -0
  111. package/src/internal/page/pose.inpage.ts +200 -0
  112. package/src/internal/page/pose.ts +80 -0
  113. package/src/internal/page/time.inpage.ts +49 -0
  114. package/src/internal/page/time.ts +122 -0
  115. package/src/internal/page/viewport.ts +3 -2
  116. package/src/internal/pictures/pictures.ts +93 -32
  117. package/src/internal/reading/layout.inpage.ts +193 -0
  118. package/src/internal/reading/layout.ts +101 -0
  119. package/src/internal/reading/names.inpage.ts +15 -0
  120. package/src/internal/reading/outline.inpage.ts +2 -18
  121. package/src/internal/reading/reading.ts +22 -2
  122. package/src/internal/reading/ready.inpage.ts +18 -23
  123. package/src/internal/reading/ready.ts +23 -3
  124. package/src/internal/reading/text.inpage.ts +1 -14
  125. package/src/internal/timeline/changes.inpage.ts +7 -15
  126. package/src/internal/timeline/changes.ts +14 -1
  127. package/src/internal/timeline/record.inpage.ts +15 -6
  128. package/src/presentation/Presentation.ts +13 -0
  129. package/src/stillness/Pixels.ts +26 -0
  130. package/src/stillness/Stillness.ts +30 -5
  131. package/src/testing/page.ts +5 -0
  132. package/dist/Browser-BKPAbyys.mjs.map +0 -1
  133. package/dist/Page-BF5izr8R.mjs.map +0 -1
  134. package/dist/Stillness-CNlvayIo.mjs.map +0 -1
@@ -0,0 +1,2042 @@
1
+ //#region src/internal/reading/context.inpage.ts
2
+ const context = (names, walked) => {
3
+ const { clean, isButton, isDocument, isHtml, isInput, isRoot } = names;
4
+ const { isSelect, isTextArea, roleOf, textOf } = names;
5
+ const { visible } = walked;
6
+ const known = () => ({
7
+ headers: /* @__PURE__ */ new Map(),
8
+ headings: /* @__PURE__ */ new Map()
9
+ });
10
+ const unspoken = "button,select,textarea,option,script,style,noscript,template,[role=button],[role=menuitem],[role=option],[role=tab],[role=switch],[role=checkbox],[role=radio],[aria-hidden=true]";
11
+ const groups = "tr,li,article,fieldset,form,section,dialog,[role=row],[role=listitem],[role=group],[role=region],[role=dialog],[role=alertdialog]";
12
+ /** The visible text just before (or after) a target within `scope`, nearest kept, ≤120 characters. */
13
+ const textBeside = (target, scope, backwards) => {
14
+ const walker = target.ownerDocument.createTreeWalker(scope, NodeFilter.SHOW_TEXT);
15
+ const labels = isInput(target) || isTextArea(target) || isSelect(target) || isButton(target) ? Array.from(target.labels ?? []) : [];
16
+ let text = "";
17
+ walker.currentNode = target;
18
+ for (let steps = 0; steps < 400 && text.replace(/\s+/g, "").length < 120; steps++) {
19
+ const node = backwards ? walker.previousNode() : walker.nextNode();
20
+ if (node === null) break;
21
+ const parent = node.parentElement;
22
+ if (parent === null || target.contains(parent) || parent.closest(unspoken) !== null || isHtml(parent) && parent.isContentEditable || labels.some((label) => label.contains(parent)) || !visible(parent)) continue;
23
+ text = backwards ? `${node.textContent ?? ""} ${text}` : `${text} ${node.textContent ?? ""}`;
24
+ }
25
+ const words = text.replace(/\s+/g, " ").trim();
26
+ return words.length <= 120 ? words : backwards ? `…${words.slice(-119).trimStart()}` : `${words.slice(0, 119).trimEnd()}…`;
27
+ };
28
+ /** The nearest visible heading before `target` in tree order, within `scope`. */
29
+ const headingBefore = (target, scope, read = known()) => {
30
+ let headings = read.headings.get(scope);
31
+ if (headings === void 0) {
32
+ headings = Array.from(scope.querySelectorAll("h1,h2,h3,h4,h5,h6,[role=heading]")).filter((element) => roleOf(element) === "heading");
33
+ read.headings.set(scope, headings);
34
+ }
35
+ for (const heading of headings.toReversed()) {
36
+ if ((heading.compareDocumentPosition(target) & Node.DOCUMENT_POSITION_FOLLOWING) === 0) continue;
37
+ const text = visible(heading) ? clean(textOf(heading), 120) : "";
38
+ if (text !== "") return text;
39
+ }
40
+ };
41
+ /** Whether an element is pinned to the viewport, where the markup around it says nothing. */
42
+ const pinned = (element) => {
43
+ if (!isHtml(element)) return false;
44
+ let top = element;
45
+ while (top.offsetParent !== null && isHtml(top.offsetParent)) top = top.offsetParent;
46
+ return top !== element.ownerDocument.body && top !== element.ownerDocument.documentElement && getComputedStyle(top).position === "fixed";
47
+ };
48
+ const span = (cell) => Math.max(1, Number(cell.getAttribute("colspan")) || 1);
49
+ const tables = "table,[role=table],[role=grid],[role=treegrid]";
50
+ /** A cell's row and column names, or nothing when it is not in a table with either. */
51
+ const tableContext = (cell, read) => {
52
+ const row = cell.closest("tr,[role=row]");
53
+ const table = row?.closest(tables);
54
+ if (row === null || row === void 0 || table === null || table === void 0) return {};
55
+ let header = read.headers.get(table);
56
+ if (header === void 0) {
57
+ const first = table.querySelector("thead tr, tr:has(> th), [role=row]:has(> [role=columnheader])");
58
+ header = first?.closest(tables) === table ? first : null;
59
+ read.headers.set(table, header);
60
+ }
61
+ if (row === header) return {};
62
+ const cells = Array.from(row.children);
63
+ const index = cells.indexOf(cell);
64
+ const lettered = (other) => /\p{L}/u.test(textOf(other));
65
+ const named = cells.find((other) => other.matches("th,[role=rowheader]") && lettered(other)) ?? cells.find((other) => other !== cell && lettered(other));
66
+ let left = cells.slice(0, index).reduce((sum, other) => sum + span(other), 0);
67
+ const over = index === -1 || header === null ? void 0 : Array.from(header.children).find((candidate) => (left -= span(candidate)) < 0);
68
+ return {
69
+ row: named === void 0 || named === cell ? void 0 : clean(textOf(named), 60) || void 0,
70
+ column: over === void 0 ? void 0 : clean(textOf(over), 60) || void 0
71
+ };
72
+ };
73
+ /** Where text around an element is read: its dialog, else its own tree, never across a shadow root. */
74
+ const treeOf = (element) => {
75
+ const root = element.getRootNode();
76
+ return element.closest("dialog,[role=dialog],[role=alertdialog]") ?? (isDocument(root) ? root.body ?? root : isRoot(root) ? root : element.ownerDocument);
77
+ };
78
+ /** The words around an element that say which one it is. */
79
+ const contextOf = (element, read = known()) => {
80
+ const cell = element.closest("td,th,[role=cell],[role=gridcell],[role=rowheader],[role=columnheader]");
81
+ const table = cell === null ? {} : tableContext(cell, read);
82
+ const parent = element.parentElement;
83
+ const scope = element.closest(groups) ?? (parent === null || parent === element.ownerDocument.body || parent.tagName === "HTML" ? void 0 : parent);
84
+ const beside = table.row !== void 0 || table.column !== void 0 || scope === void 0 ? "" : textBeside(element, scope, true);
85
+ const heading = pinned(element) ? void 0 : headingBefore(element, treeOf(element), read);
86
+ return {
87
+ ...table,
88
+ label: beside.length > 40 ? `…${beside.slice(-39).trimStart()}` : beside || void 0,
89
+ heading: heading === void 0 ? void 0 : clean(heading, 60)
90
+ };
91
+ };
92
+ return {
93
+ contextOf,
94
+ groups,
95
+ headingBefore,
96
+ known,
97
+ textBeside,
98
+ treeOf
99
+ };
100
+ };
101
+ //#endregion
102
+ //#region src/internal/reading/controls.inpage.ts
103
+ const controls = (names, subjects, texts) => {
104
+ const { clean, isInput, isSelect, isTextArea, refFor, textEntry } = names;
105
+ const { stateOf } = subjects;
106
+ const { shown } = texts;
107
+ const states = (element, role) => {
108
+ const { level, ...flags } = stateOf(element, role);
109
+ const held = Object.entries(flags).flatMap(([name, value]) => value === true ? [name] : []);
110
+ return [...level === void 0 ? [] : [`level=${level}`], ...held].map((name) => ` [${name}]`).join("");
111
+ };
112
+ const valueOf = (element) => {
113
+ if (isSelect(element)) {
114
+ const selected = Array.from(element.selectedOptions, (option) => clean(option.text, 40));
115
+ const options = Array.from(element.options).slice(0, 12).map((option) => clean(option.text, 40));
116
+ const more = element.options.length > 12 ? ` +${element.options.length - 12} more` : "";
117
+ return ` value=${JSON.stringify(selected.join(", "))} options=${JSON.stringify(options.join(" | ") + more)}`;
118
+ }
119
+ const value = isInput(element) || isTextArea(element) ? shown(element, true) : void 0;
120
+ return value === void 0 || value === "" ? "" : ` value=${JSON.stringify(clean(value, 80))}`;
121
+ };
122
+ /** A control as a value, as its outline line shows it. */
123
+ const controlOf = (element, role, kind, name) => {
124
+ const { disabled, checked } = stateOf(element, role);
125
+ const select = isSelect(element) ? element : void 0;
126
+ const value = select !== void 0 ? Array.from(select.selectedOptions, (option) => clean(option.text, 80)).join(", ") : isInput(element) || isTextArea(element) ? clean(shown(element, true), 200) : "";
127
+ const editable = textEntry(element);
128
+ return {
129
+ ref: refFor(element),
130
+ kind,
131
+ name,
132
+ value,
133
+ ...select === void 0 ? {} : {
134
+ options: Array.from(select.options).slice(0, 64).map((option) => clean(option.text, 80)),
135
+ optionCount: select.options.length
136
+ },
137
+ ...disabled ? { disabled } : {},
138
+ ...checked === void 0 ? {} : { checked },
139
+ ...editable ? { editable } : {}
140
+ };
141
+ };
142
+ /**
143
+ * The elements a selector matches, each read whole, so one inside another that matched is left
144
+ * to it; or why the selector is not CSS.
145
+ */
146
+ const rootsOf = (selector) => {
147
+ let matched;
148
+ try {
149
+ matched = Array.from(document.querySelectorAll(selector));
150
+ } catch {
151
+ return { invalid: `${JSON.stringify(selector)} is not a CSS selector` };
152
+ }
153
+ return matched.filter((root) => !matched.some((other) => other !== root && other.contains(root)));
154
+ };
155
+ return {
156
+ controlOf,
157
+ rootsOf,
158
+ states,
159
+ valueOf
160
+ };
161
+ };
162
+ //#endregion
163
+ //#region src/internal/reading/expect.inpage.ts
164
+ const expectations = (names, subjected, matching) => {
165
+ const { isInput, isSelect, isTextArea, roleOf, textOf } = names;
166
+ const { elementsOf, stateOf } = subjected;
167
+ const markOf = (elements) => matching.mark(elements.map((element) => {
168
+ const { focused: _focused, ...state } = stateOf(element, roleOf(element));
169
+ const value = isInput(element) || isSelect(element) || isTextArea(element) ? element.value : "";
170
+ return `${textOf(element)}\u0000${value}\u0000${JSON.stringify(state)}\u0001`;
171
+ }));
172
+ /**
173
+ * What `find` matches, looked at every 100 ms until `want` holds of it or `millis` have passed,
174
+ * with its mark then. It gives no refs.
175
+ */
176
+ const until = async (request, want, millis) => {
177
+ const deadline = performance.now() + millis;
178
+ for (;;) {
179
+ const elements = elementsOf(request);
180
+ if ("invalid" in elements) return elements;
181
+ const mark = markOf(elements);
182
+ const met = want === "some" ? elements.length > 0 : want === "none" ? elements.length === 0 : mark !== want.other;
183
+ const left = deadline - performance.now();
184
+ if (met || left <= 0) return {
185
+ met,
186
+ mark
187
+ };
188
+ const { promise, resolve } = Promise.withResolvers();
189
+ setTimeout(resolve, Math.min(100, left));
190
+ await promise;
191
+ }
192
+ };
193
+ return { until };
194
+ };
195
+ //#endregion
196
+ //#region src/internal/reading/layout.inpage.ts
197
+ const layout = (names, walked, subjected, matching, placing) => {
198
+ const { isDisabled, isOwn, nameOf, refFor, roleOf, textOf } = names;
199
+ const { boxOf, inView, visible } = walked;
200
+ const most = 200;
201
+ const area = (element) => {
202
+ const { width, height } = element.getBoundingClientRect();
203
+ return width * height;
204
+ };
205
+ const chosen = (elements, choose) => choose === "first" ? elements[0] : choose === "last" ? elements.at(-1) : elements.reduce((best, element) => best === void 0 || (choose === "smallest" ? area(element) < area(best) : area(element) > area(best)) ? element : best, void 0);
206
+ const fixed = (element) => {
207
+ for (let at = element; at !== null; at = at.parentElement) if (getComputedStyle(at).position === "fixed") return true;
208
+ return false;
209
+ };
210
+ const words = (element, wanted, dx, dy) => {
211
+ const parts = [];
212
+ let text = "";
213
+ const walker = element.ownerDocument.createTreeWalker(element, NodeFilter.SHOW_TEXT);
214
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
215
+ parts.push({
216
+ node,
217
+ start: text.length
218
+ });
219
+ text += node.nodeValue ?? "";
220
+ }
221
+ const pattern = typeof wanted === "string" ? new RegExp(wanted.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "giu") : new RegExp(wanted.source, wanted.flags.replace(/[gy]/g, "") + "g");
222
+ const at = (index, end) => {
223
+ const part = parts.findLast(({ start }) => end ? start < index : start <= index) ?? parts[0];
224
+ return part === void 0 ? [element, 0] : [part.node, index - part.start];
225
+ };
226
+ const found = [];
227
+ for (const match of text.matchAll(pattern)) {
228
+ if (found.length === most) break;
229
+ if (match[0] === "") continue;
230
+ const range = element.ownerDocument.createRange();
231
+ range.setStart(...at(match.index, false));
232
+ range.setEnd(...at(match.index + match[0].length, true));
233
+ const { x, y, width, height } = range.getBoundingClientRect();
234
+ if (width > 0 || height > 0) found.push({
235
+ text: match[0],
236
+ box: {
237
+ x: x + dx,
238
+ y: y + dy,
239
+ width,
240
+ height
241
+ }
242
+ });
243
+ }
244
+ return found;
245
+ };
246
+ const selected = (pick) => {
247
+ let elements;
248
+ try {
249
+ elements = Array.from(document.querySelectorAll(pick.selector));
250
+ } catch {
251
+ return { invalid: `${JSON.stringify(pick.selector)} is not a CSS selector` };
252
+ }
253
+ const rules = matching.compile(pick);
254
+ return elements.filter((element) => {
255
+ const role = roleOf(element, pick.role !== null);
256
+ const box = boxOf(element);
257
+ return !isOwn(element) && box.width * box.height > 0 && visible(element) && (pick.scope === "document" || inView(new DOMRect(box.x, box.y, box.width, box.height))) && (pick.state !== "enabled" || !isDisabled(element)) && rules({
258
+ role,
259
+ name: () => nameOf(element, role),
260
+ text: () => textOf(element),
261
+ context: () => placing.contextOf(element)
262
+ });
263
+ });
264
+ };
265
+ const read = (picks) => {
266
+ const places = [];
267
+ const missing = [];
268
+ for (const pick of picks) {
269
+ const elements = pick.selector === null ? subjected.elementsOf(pick) : selected({
270
+ ...pick,
271
+ selector: pick.selector
272
+ });
273
+ if ("invalid" in elements) return { invalid: `${pick.id}: ${elements.invalid}` };
274
+ const element = chosen(elements, pick.choose);
275
+ if (element === void 0) {
276
+ missing.push(pick.id);
277
+ continue;
278
+ }
279
+ const role = roleOf(element, pick.role !== null);
280
+ const box = boxOf(element);
281
+ const own = element.getBoundingClientRect();
282
+ places.push({
283
+ id: pick.id,
284
+ ref: refFor(element),
285
+ subject: {
286
+ role,
287
+ name: nameOf(element, role),
288
+ tag: element.tagName.toLowerCase(),
289
+ context: placing.contextOf(element)
290
+ },
291
+ box,
292
+ fixed: fixed(element),
293
+ words: pick.words === null ? void 0 : words(element, pick.words, box.x - own.x, box.y - own.y)
294
+ });
295
+ }
296
+ return { layout: {
297
+ url: location.href,
298
+ viewport: {
299
+ width: innerWidth,
300
+ height: innerHeight
301
+ },
302
+ scroll: {
303
+ x: scrollX,
304
+ y: scrollY
305
+ },
306
+ scale: devicePixelRatio,
307
+ places,
308
+ missing
309
+ } };
310
+ };
311
+ return { read };
312
+ };
313
+ //#endregion
314
+ //#region src/internal/reading/names.inpage.ts
315
+ /**
316
+ * In the page: the foundation the other parts build on. It gives elements refs and reads the
317
+ * roles, names and states that the outline and the input checks report.
318
+ *
319
+ * Every `*.inpage.ts` part runs inside the page. The page receives it as source text, so it must
320
+ * stay self-contained: it uses only its parameters, the DOM and what it defines itself.
321
+ */
322
+ const elements = () => {
323
+ const isInput = (element) => element.tagName === "INPUT";
324
+ const isTextArea = (element) => element.tagName === "TEXTAREA";
325
+ const isSelect = (element) => element.tagName === "SELECT";
326
+ const isFrame = (element) => element.tagName === "IFRAME";
327
+ const isHtml = (element) => "innerText" in element;
328
+ const isButton = (element) => element.tagName === "BUTTON";
329
+ const isLabel = (element) => element.tagName === "LABEL";
330
+ const textOf = (element) => isHtml(element) ? element.innerText : element.textContent ?? "";
331
+ const isElement = (node) => node.nodeType === Node.ELEMENT_NODE;
332
+ const isDocument = (node) => node.nodeType === Node.DOCUMENT_NODE;
333
+ /** The native fields and editable regions that can receive typed text. */
334
+ const textEntry = (element) => isInput(element) && ![
335
+ "button",
336
+ "reset",
337
+ "submit",
338
+ "image",
339
+ "checkbox",
340
+ "radio",
341
+ "file",
342
+ "range",
343
+ "color",
344
+ "hidden"
345
+ ].includes(element.type) || isTextArea(element) || isHtml(element) && element.isContentEditable;
346
+ const own = /* @__PURE__ */ new WeakSet();
347
+ const adopt = (node) => own.add(node);
348
+ /** Whether a node is the library's own, or inside a shadow root of one of its own. */
349
+ const isOwn = (node) => {
350
+ const root = node.getRootNode();
351
+ return own.has(node) || root instanceof ShadowRoot && own.has(root.host);
352
+ };
353
+ const clean = (value, max = 160) => {
354
+ const text = (value ?? "").replace(/\s+/g, " ").trim();
355
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
356
+ };
357
+ return {
358
+ adopt,
359
+ clean,
360
+ isInput,
361
+ isTextArea,
362
+ isSelect,
363
+ isFrame,
364
+ isHtml,
365
+ isButton,
366
+ isLabel,
367
+ textOf,
368
+ isElement,
369
+ isDocument,
370
+ isOwn,
371
+ textEntry
372
+ };
373
+ };
374
+ const names = (native) => {
375
+ const { clean, isInput, isTextArea, isSelect, isFrame, textOf, isElement } = native;
376
+ const byElement = /* @__PURE__ */ new WeakMap();
377
+ const byRef = /* @__PURE__ */ new Map();
378
+ const refs = { next: 1 };
379
+ const interactiveRoles = new Set("button link checkbox radio tab menuitem menuitemcheckbox menuitemradio option switch slider combobox listbox textbox searchbox spinbutton treeitem".split(" "));
380
+ const containers = {
381
+ HEADER: "banner",
382
+ NAV: "navigation",
383
+ MAIN: "main",
384
+ ASIDE: "complementary",
385
+ FOOTER: "contentinfo",
386
+ FORM: "form",
387
+ DIALOG: "dialog"
388
+ };
389
+ const valueRoles = new Set("combobox listbox option textbox searchbox spinbutton slider".split(" "));
390
+ /**
391
+ * A label's own words, without the options or values of the controls inside it, native or
392
+ * scripted, such as the custom select Browserbase puts in place of a native one.
393
+ */
394
+ const labelText = (label) => {
395
+ let text = "";
396
+ const collect = (node) => {
397
+ for (const child of Array.from(node.childNodes)) if (child.nodeType === Node.TEXT_NODE) text += child.textContent ?? "";
398
+ else if (isElement(child) && ![
399
+ "SELECT",
400
+ "TEXTAREA",
401
+ "INPUT",
402
+ "SCRIPT",
403
+ "STYLE"
404
+ ].includes(child.tagName) && !valueRoles.has(roleOf(child) ?? "")) collect(child);
405
+ };
406
+ collect(label);
407
+ return text;
408
+ };
409
+ const roleOf = (element, structural = false) => {
410
+ const explicit = element.getAttribute("role");
411
+ if (explicit !== null && explicit.trim() !== "") return explicit.trim().split(/\s+/)[0] ?? null;
412
+ const tag = element.tagName;
413
+ if (tag === "A") return element.hasAttribute("href") ? "link" : null;
414
+ if (tag === "BUTTON" || tag === "SUMMARY") return "button";
415
+ if (isSelect(element)) return element.multiple ? "listbox" : "combobox";
416
+ if (tag === "TEXTAREA") return "textbox";
417
+ if (isInput(element)) {
418
+ const type = element.type;
419
+ if (type === "hidden" || type === "color" || type === "file") return null;
420
+ if (type === "checkbox" || type === "radio") return type;
421
+ if (type === "range") return "slider";
422
+ if (type === "number") return "spinbutton";
423
+ if (type === "search") return "searchbox";
424
+ if (type === "button" || type === "submit" || type === "reset" || type === "image") return "button";
425
+ return "textbox";
426
+ }
427
+ if (/^H[1-6]$/.test(tag)) return "heading";
428
+ if (tag === "IMG") return "img";
429
+ if (tag === "CANVAS") return "canvas";
430
+ if (tag === "IFRAME") return "iframe";
431
+ if (element.getAttribute("contenteditable") === "true") return "textbox";
432
+ if (structural) {
433
+ if (tag === "TH") return element.getAttribute("scope") === "row" ? "rowheader" : "columnheader";
434
+ const roles = {
435
+ TABLE: "table",
436
+ TR: "row",
437
+ TD: "cell",
438
+ TBODY: "rowgroup",
439
+ THEAD: "rowgroup",
440
+ TFOOT: "rowgroup",
441
+ UL: "list",
442
+ OL: "list",
443
+ MENU: "list",
444
+ LI: "listitem"
445
+ };
446
+ if (roles[tag] !== void 0) return roles[tag];
447
+ }
448
+ return containers[tag] ?? null;
449
+ };
450
+ const nameOf = (element, role) => {
451
+ const labelledBy = element.getAttribute("aria-labelledby");
452
+ if (labelledBy !== null) {
453
+ const text = labelledBy.split(/\s+/).map((id) => {
454
+ const labelling = element.ownerDocument.getElementById(id);
455
+ return labelling === null ? "" : labelText(labelling);
456
+ }).join(" ");
457
+ if (clean(text) !== "") return clean(text);
458
+ }
459
+ const label = element.getAttribute("aria-label");
460
+ if (label !== null && clean(label) !== "") return clean(label);
461
+ if (isInput(element) || isTextArea(element) || isSelect(element)) {
462
+ const labels = element.labels === null ? "" : Array.from(element.labels, labelText).join(" ");
463
+ if (clean(labels) !== "") return clean(labels);
464
+ if (isInput(element) && (element.type === "button" || element.type === "submit" || element.type === "reset")) return clean(element.value);
465
+ return clean(element.getAttribute("placeholder") ?? element.getAttribute("title") ?? element.getAttribute("name"));
466
+ }
467
+ if (role === "img") return clean(element.getAttribute("alt") ?? element.getAttribute("title"));
468
+ if (role === "iframe") return clean(element.getAttribute("title") ?? element.getAttribute("name"));
469
+ if (role === null || interactiveRoles.has(role) || role === "heading") {
470
+ const text = isSecret(element) ? "" : clean(textOf(element), 120);
471
+ if (text !== "") return text;
472
+ const titled = element.querySelector("[title],img[alt],svg title");
473
+ const fallback = titled === null ? null : titled.tagName === "IMG" ? titled.getAttribute("alt") : titled.tagName.toLowerCase() === "title" ? titled.textContent : titled.getAttribute("title");
474
+ return clean(element.getAttribute("title") ?? fallback);
475
+ }
476
+ return "";
477
+ };
478
+ const isDisabled = (element) => element.matches(":disabled") || element.getAttribute("aria-disabled") === "true";
479
+ const refFor = (element) => {
480
+ const known = byElement.get(element);
481
+ if (known !== void 0 && byRef.get(known)?.deref() === element) return known;
482
+ const ref = `e${refs.next++}`;
483
+ byElement.set(element, ref);
484
+ byRef.set(ref, new WeakRef(element));
485
+ return ref;
486
+ };
487
+ const lookup = (ref) => {
488
+ const element = byRef.get(ref)?.deref();
489
+ return element !== void 0 && element.isConnected && inCurrentDocument(element) ? element : void 0;
490
+ };
491
+ const describe = (element) => {
492
+ const id = element.id === "" ? "" : `#${element.id}`;
493
+ const name = clean(nameOf(element, roleOf(element)), 40);
494
+ return `<${element.tagName.toLowerCase()}${id}>${name === "" ? "" : ` "${name}"`}`;
495
+ };
496
+ const isRoot = (node) => node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE;
497
+ const parentOf = (element) => {
498
+ const root = element.getRootNode();
499
+ return element.parentElement ?? (isRoot(root) && "host" in root ? root.host : null);
500
+ };
501
+ const activeElement = () => {
502
+ let active = document.activeElement;
503
+ while (active !== null) {
504
+ const inner = active.shadowRoot?.activeElement ?? (isFrame(active) ? active.contentDocument?.activeElement : null);
505
+ if (inner === null || inner === void 0 || inner === active) return active;
506
+ active = inner;
507
+ }
508
+ return null;
509
+ };
510
+ const inCurrentDocument = (element) => {
511
+ let owner = element.ownerDocument;
512
+ while (owner !== document) {
513
+ const frame = owner.defaultView?.frameElement;
514
+ if (frame === null || frame === void 0 || !frame.isConnected || isFrame(frame) && frame.contentDocument !== owner) return false;
515
+ owner = frame.ownerDocument;
516
+ }
517
+ return true;
518
+ };
519
+ const secretToken = /(?:^|\s)(?:current-password|new-password|one-time-code|cc-number|cc-csc|cc-exp(?:-month|-year)?)(?=\s|$)/i;
520
+ const secrets = /* @__PURE__ */ new WeakSet();
521
+ /**
522
+ * A field the DOM marks as secret, now or before: by its type, its autocomplete tokens, or a
523
+ * style that shows dots for what it holds, as a PIN field may.
524
+ */
525
+ const isSecret = (element) => {
526
+ if (isInput(element) && element.type === "password" || secretToken.test(element.getAttribute("autocomplete") ?? "") || (isInput(element) || isTextArea(element)) && !/^(none)?$/.test(getComputedStyle(element).getPropertyValue("-webkit-text-security"))) secrets.add(element);
527
+ return secrets.has(element);
528
+ };
529
+ return {
530
+ ...native,
531
+ activeElement,
532
+ containers,
533
+ describe,
534
+ inCurrentDocument,
535
+ interactiveRoles,
536
+ isDisabled,
537
+ isRoot,
538
+ isSecret,
539
+ lookup,
540
+ nameOf,
541
+ parentOf,
542
+ refFor,
543
+ refs,
544
+ roleOf
545
+ };
546
+ };
547
+ //#endregion
548
+ //#region src/internal/reading/outline.inpage.ts
549
+ const outline = (names, walked, subjects, texts, controlling, url) => {
550
+ const { clean, containers, isFrame, nameOf, refFor, roleOf, textOf } = names;
551
+ const { visit } = walked;
552
+ const { isControl } = subjects;
553
+ const { cut } = texts;
554
+ const textBlocks = /^(?:P|LI|TD|TH|DT|DD|LABEL|SPAN|BLOCKQUOTE|FIGCAPTION|CAPTION|PRE|STRONG|EM|B|I|SMALL|TIME|CODE|LEGEND)$/;
555
+ const nested = "a[href],button,input,select,textarea,summary,[role],[onclick],[tabindex],[contenteditable],canvas,iframe";
556
+ const noise = /^[\s|•·\-–—,.:;()[\]{}"'/\\]*$/;
557
+ /** Text inside a control's label is already that control's name. */
558
+ const inControlLabel = (element) => {
559
+ const label = element.closest("label");
560
+ return label !== null && label.control !== null;
561
+ };
562
+ const hrefOf = (element) => {
563
+ if (element.tagName !== "A") return "";
564
+ const raw = element.getAttribute("href") ?? "";
565
+ if (raw === "" || raw.startsWith("javascript:")) return "";
566
+ try {
567
+ const { origin, href } = new URL(raw, element.ownerDocument.baseURI);
568
+ const reported = url.redact(href);
569
+ const own = origin === location.origin && reported.startsWith(origin);
570
+ return ` -> ${clean(own ? reported.slice(origin.length) : reported, 80)}`;
571
+ } catch {
572
+ return "";
573
+ }
574
+ };
575
+ const snapshot = (request) => {
576
+ const roots = request.within === null ? [null] : controlling.rootsOf(request.within);
577
+ if ("invalid" in roots) return roots;
578
+ const width = window.innerWidth;
579
+ const height = window.innerHeight;
580
+ const query = request.query === null ? null : request.query.toLowerCase();
581
+ const lines = [];
582
+ const controls = [];
583
+ let above = 0;
584
+ let below = 0;
585
+ const placement = (rect) => {
586
+ if (request.full) return "in";
587
+ if (rect.bottom <= 0) return "above";
588
+ if (rect.top >= height) return "below";
589
+ if (rect.right <= 0 || rect.left >= width) return "aside";
590
+ return "in";
591
+ };
592
+ const count = (rect) => {
593
+ const where = placement(rect);
594
+ if (where === "above") above++;
595
+ if (where === "below") below++;
596
+ return where;
597
+ };
598
+ const emit = (depth, line, rect) => {
599
+ if (count(rect) !== "in") return false;
600
+ if (query !== null && !line.toLowerCase().includes(query)) return false;
601
+ lines.push(`${" ".repeat(Math.min(depth, 8))}- ${line}`);
602
+ return true;
603
+ };
604
+ const control = (element, rect, role, depth) => {
605
+ const name = nameOf(element, role);
606
+ const kind = role ?? "clickable";
607
+ const box = request.boxes || role === "canvas" || role === "iframe" ? ` ${Math.round(rect.width)}x${Math.round(rect.height)} at (${Math.round(rect.x)},${Math.round(rect.y)})` : "";
608
+ const line = placement(rect) === "in" ? `${kind}${name === "" ? "" : ` ${JSON.stringify(name)}`} [ref=${refFor(element)}]${controlling.states(element, role)}${controlling.valueOf(element)}${hrefOf(element)}${box}` : kind;
609
+ if (emit(depth, line, rect)) controls.push(controlling.controlOf(element, role, kind, name));
610
+ if (isFrame(element)) {
611
+ const body = element.contentDocument?.body;
612
+ if ((body === null || body === void 0) && placement(rect) === "in") lines.push(`${" ".repeat(Math.min(depth + 1, 8))}- (another site's frame: use a screenshot and coordinates)`);
613
+ return {
614
+ depth: depth + 1,
615
+ insidePointer: false,
616
+ controls: false
617
+ };
618
+ }
619
+ if ([
620
+ "INPUT",
621
+ "SELECT",
622
+ "TEXTAREA",
623
+ "CANVAS",
624
+ "IMG"
625
+ ].includes(element.tagName)) return void 0;
626
+ return {
627
+ depth: depth + 1,
628
+ insidePointer: true,
629
+ controls: true
630
+ };
631
+ };
632
+ const enter = (element, style, rect, { depth, insidePointer }) => {
633
+ const role = roleOf(element);
634
+ if (isControl(element, role, style, rect, insidePointer)) return control(element, rect, role, depth);
635
+ if (role === "heading") {
636
+ emit(depth, `heading ${JSON.stringify(nameOf(element, role))}${controlling.states(element, role)}`, rect);
637
+ return;
638
+ }
639
+ if (role === "img") {
640
+ const alt = nameOf(element, role);
641
+ if (alt !== "") emit(depth, `img ${JSON.stringify(alt)}`, rect);
642
+ return;
643
+ }
644
+ let inner = depth;
645
+ if (role !== null && (containers[element.tagName] !== void 0 || role === "dialog")) {
646
+ const label = element.getAttribute("aria-label");
647
+ if (emit(depth, `${role}${label === null ? "" : ` ${JSON.stringify(clean(label))}`}:`, rect)) inner = depth + 1;
648
+ }
649
+ if (textBlocks.test(element.tagName) && element.querySelector(nested) === null) {
650
+ if (inControlLabel(element)) return void 0;
651
+ const text = clean(textOf(element), 300);
652
+ if (text !== "" && !noise.test(text)) emit(inner, `text: ${text}`, rect);
653
+ return;
654
+ }
655
+ let own = "";
656
+ for (const node of Array.from(element.childNodes)) if (node.nodeType === Node.TEXT_NODE) own += node.textContent ?? "";
657
+ own = clean(own, 300);
658
+ if (own !== "" && !noise.test(own) && !inControlLabel(element)) emit(inner, `text: ${own}`, rect);
659
+ return {
660
+ depth: inner,
661
+ insidePointer: insidePointer || style.cursor === "pointer",
662
+ controls: false
663
+ };
664
+ };
665
+ const visitor = {
666
+ enter,
667
+ admit: (child, place) => !place.controls || child.matches(nested) || child.querySelector(nested) !== null,
668
+ outside: count
669
+ };
670
+ for (const root of roots) visit(root, !request.full, {
671
+ depth: 0,
672
+ insidePointer: false,
673
+ controls: false
674
+ }, visitor);
675
+ const outlined = cut(lines.join("\n"), request.maxChars);
676
+ return { snapshot: {
677
+ ...outlined,
678
+ url: location.href,
679
+ title: document.title,
680
+ above,
681
+ below,
682
+ viewport: {
683
+ width,
684
+ height
685
+ },
686
+ scroll: {
687
+ y: Math.round(window.scrollY),
688
+ height: Math.round(document.documentElement.scrollHeight)
689
+ },
690
+ controls: controls.filter((control) => outlined.text.includes(`[ref=${control.ref}]`))
691
+ } };
692
+ };
693
+ const viewport = () => ({
694
+ width: window.innerWidth,
695
+ height: window.innerHeight
696
+ });
697
+ return {
698
+ snapshot,
699
+ viewport
700
+ };
701
+ };
702
+ //#endregion
703
+ //#region src/internal/reading/ready.inpage.ts
704
+ const ready = (walked, texts, kept) => {
705
+ const { inView, visible } = walked;
706
+ let copy;
707
+ const boxed = (element) => {
708
+ const rect = element.getBoundingClientRect();
709
+ return rect.width * rect.height > 0 && inView(rect);
710
+ };
711
+ const showing = (elements) => Array.from(elements).filter((element) => boxed(element) && visible(element));
712
+ const drawn = (canvas) => {
713
+ copy ??= new OffscreenCanvas(32, 32).getContext("2d", { willReadFrequently: true });
714
+ if (copy === null) return true;
715
+ try {
716
+ copy.clearRect(0, 0, 32, 32);
717
+ copy.imageSmoothingQuality = "high";
718
+ copy.drawImage(canvas, 0, 0, 32, 32);
719
+ return new Uint32Array(copy.getImageData(0, 0, 32, 32).data.buffer).some((pixel) => pixel !== 0);
720
+ } catch {
721
+ return true;
722
+ }
723
+ };
724
+ const content = () => showing(document.querySelectorAll("video, iframe, embed, object")).length > 0 || showing(document.querySelectorAll("img, svg")).some((picture) => {
725
+ const { width, height } = picture.getBoundingClientRect();
726
+ return width > 64 && height > 64;
727
+ }) || (texts.read({
728
+ ref: null,
729
+ maxChars: 1,
730
+ unmask: false
731
+ })?.text ?? "") !== "" || showing(document.querySelectorAll("canvas")).some(drawn);
732
+ const painted = () => {
733
+ const { promise, resolve } = Promise.withResolvers();
734
+ if (document.visibilityState === "hidden") resolve(false);
735
+ else requestAnimationFrame(() => resolve(true));
736
+ return promise;
737
+ };
738
+ const check = (quietMillis, clock) => painted().then((paints) => {
739
+ const waiting = [];
740
+ const held = clock !== null && !document.dispatchEvent(new CustomEvent(clock, {
741
+ detail: { op: "holds" },
742
+ cancelable: true
743
+ }));
744
+ if (document.readyState === "loading") waiting.push("load");
745
+ if (!paints) waiting.push("paint");
746
+ if (document.getAnimations().some((animation) => {
747
+ const effect = animation.effect;
748
+ return (animation.playState === "running" || held && animation.playState === "paused") && effect !== null && Number.isFinite(effect.getComputedTiming().endTime) && "target" in effect && effect.target instanceof Element && boxed(effect.target);
749
+ })) waiting.push("animations");
750
+ if (Array.from(document.images).some((image) => !image.complete && boxed(image))) waiting.push("images");
751
+ if (document.fonts.status !== "loaded") waiting.push("fonts");
752
+ if (showing(document.querySelectorAll("[aria-busy=true]")).length > 0) waiting.push("busy");
753
+ if (!content()) waiting.push("content");
754
+ if (kept.changing() > performance.timeOrigin + performance.now() - quietMillis) waiting.push("changing");
755
+ return waiting;
756
+ });
757
+ /**
758
+ * Check until the page is ready, or for `millis`, and say what it is still waiting for; with
759
+ * `quietMillis`, until nothing the record saw in view has changed for that long, too.
760
+ */
761
+ const wait = async (millis, quietMillis = 0, clock = null) => {
762
+ const until = performance.now() + millis;
763
+ for (;;) {
764
+ const waiting = await check(quietMillis, clock);
765
+ if (waiting.length === 0 || performance.now() >= until) return waiting;
766
+ const { promise, resolve } = Promise.withResolvers();
767
+ setTimeout(resolve, Math.min(50, until - performance.now()));
768
+ await promise;
769
+ }
770
+ };
771
+ /**
772
+ * One task, then a frame: what the page's handlers for input did at once has run, a navigation
773
+ * one of them started in a timer has been asked for, and their effect has painted. Says whether
774
+ * the page painted, which a hidden one does not.
775
+ */
776
+ const settle = () => {
777
+ const { promise, resolve } = Promise.withResolvers();
778
+ setTimeout(resolve, 0);
779
+ return promise.then(painted);
780
+ };
781
+ return {
782
+ wait,
783
+ settle
784
+ };
785
+ };
786
+ //#endregion
787
+ //#region src/internal/reading/subjects.inpage.ts
788
+ const states = (names) => (element, role) => {
789
+ const { isDisabled, isInput } = names;
790
+ const given = (attribute) => {
791
+ const value = element.getAttribute(attribute);
792
+ return value === "true" || (value === "false" ? false : void 0);
793
+ };
794
+ const checkable = element.hasAttribute("aria-checked") || [
795
+ "checkbox",
796
+ "radio",
797
+ "switch",
798
+ "menuitemcheckbox",
799
+ "menuitemradio"
800
+ ].includes(role ?? "");
801
+ return {
802
+ disabled: isDisabled(element),
803
+ checked: checkable ? isInput(element) && element.checked || element.getAttribute("aria-checked") === "true" : void 0,
804
+ expanded: given("aria-expanded"),
805
+ selected: given("aria-selected"),
806
+ pressed: given("aria-pressed"),
807
+ focused: element.ownerDocument.activeElement === element,
808
+ level: role === "heading" ? Number(element.getAttribute("aria-level")) || Number(/^H([1-6])$/.exec(element.tagName)?.[1]) || 2 : void 0
809
+ };
810
+ };
811
+ const subjects = (names, walked, matching, placing, stateOf) => {
812
+ const { isDisabled, nameOf, refFor, roleOf, textOf } = names;
813
+ const { acts, boxOf, controlOf, hitAt, inView } = walked;
814
+ const { contextOf, known } = placing;
815
+ /** What the outline lists as a control, with a ref: something a person would act on. */
816
+ const isControl = (element, role, style, rect, insidePointer) => acts(element, role) || style.cursor === "pointer" && !insidePointer && rect.width > 0 && rect.height > 0;
817
+ /**
818
+ * The elements in scope that match a query, in tree order. Without text, an element matches
819
+ * when it has a role or is a control. With text, any element can, but text inside a control or
820
+ * heading is that control's or heading's, and an element is left out when one inside it
821
+ * matches too: the smallest element showing the text is found, not each one around it.
822
+ */
823
+ const matched = (request) => {
824
+ const { at } = request;
825
+ const matches = matching.compile(request);
826
+ const byText = request.text !== null;
827
+ const viewport = request.scope === "viewport";
828
+ const read = known();
829
+ if (request.selector !== null) try {
830
+ document.querySelector(request.selector);
831
+ } catch {
832
+ return { invalid: `${JSON.stringify(request.selector)} is not a CSS selector` };
833
+ }
834
+ const eligible = (element) => (request.selector === null || element.matches(request.selector)) && (request.state !== "enabled" || !isDisabled(element));
835
+ const entries = [];
836
+ const open = [];
837
+ const named = (entry) => entry.name ??= nameOf(entry.element, entry.role);
838
+ const placed = (entry) => entry.context ??= contextOf(entry.element, read);
839
+ const judge = (entry, text) => matches({
840
+ role: entry.role,
841
+ name: () => named(entry),
842
+ text,
843
+ context: () => placed(entry)
844
+ });
845
+ const hit = at === null ? null : hitAt(document, at.x, at.y);
846
+ if (hit !== null) {
847
+ const element = controlOf(hit);
848
+ const { x, y, width, height } = boxOf(element);
849
+ const entry = {
850
+ element,
851
+ rect: new DOMRect(x, y, width, height),
852
+ role: roleOf(element, request.role !== null),
853
+ matched: false
854
+ };
855
+ entry.matched = eligible(element) && judge(entry, () => textOf(element));
856
+ entries.push(entry);
857
+ }
858
+ if (at === null) walked.visit(null, viewport, {
859
+ pointer: false,
860
+ owned: false
861
+ }, {
862
+ enter: (element, style, rect, state) => {
863
+ const role = roleOf(element, request.role !== null);
864
+ const control = isControl(element, role, style, rect, state.pointer);
865
+ const unit = control || role === "heading";
866
+ const entry = eligible(element) && (byText ? unit || !state.owned : request.selector !== null || role !== null || control) && (!viewport || inView(rect)) ? {
867
+ element,
868
+ rect,
869
+ role,
870
+ matched: false
871
+ } : void 0;
872
+ if (entry !== void 0) entries.push(entry);
873
+ open.push({
874
+ entry,
875
+ inline: style.display === "inline",
876
+ parts: [],
877
+ inside: false
878
+ });
879
+ return {
880
+ pointer: state.pointer || style.cursor === "pointer",
881
+ owned: state.owned || unit
882
+ };
883
+ },
884
+ text: byText ? (node) => open.at(-1)?.parts.push(node.textContent ?? "") : void 0,
885
+ leave: () => {
886
+ const closed = open.pop();
887
+ const parent = open.at(-1);
888
+ if (closed === void 0) return;
889
+ const { entry } = closed;
890
+ const text = closed.parts.join("");
891
+ if (parent !== void 0) parent.parts.push(closed.inline ? text : ` ${text} `);
892
+ if (entry !== void 0 && !(byText && closed.inside)) entry.matched = judge(entry, () => text);
893
+ if (parent !== void 0) parent.inside ||= closed.inside || entry?.matched === true;
894
+ }
895
+ });
896
+ return {
897
+ entries: entries.filter((entry) => entry.matched),
898
+ named,
899
+ placed
900
+ };
901
+ };
902
+ const find = (request) => {
903
+ const result = matched(request);
904
+ if (result.invalid !== void 0) return { invalid: result.invalid };
905
+ const { entries, named, placed } = result;
906
+ return { found: entries.map((entry) => ({
907
+ ref: refFor(entry.element),
908
+ subject: {
909
+ role: entry.role,
910
+ name: named(entry),
911
+ tag: entry.element.tagName.toLowerCase(),
912
+ context: placed(entry)
913
+ },
914
+ box: {
915
+ x: Math.round(entry.rect.x),
916
+ y: Math.round(entry.rect.y),
917
+ width: Math.round(entry.rect.width),
918
+ height: Math.round(entry.rect.height)
919
+ },
920
+ inViewport: inView(entry.rect),
921
+ state: stateOf(entry.element, entry.role)
922
+ })) };
923
+ };
924
+ /** The elements `find` would find, in tree order, with no refs given. */
925
+ const elementsOf = (request) => {
926
+ const result = matched(request);
927
+ return result.invalid !== void 0 ? { invalid: result.invalid } : result.entries.map((entry) => entry.element);
928
+ };
929
+ return {
930
+ find,
931
+ elementsOf,
932
+ isControl,
933
+ stateOf
934
+ };
935
+ };
936
+ //#endregion
937
+ //#region src/internal/reading/text.inpage.ts
938
+ const text = (names, walked) => {
939
+ const { isHtml, isInput, isSecret, isSelect, isTextArea, lookup } = names;
940
+ const valueless = [
941
+ "checkbox",
942
+ "radio",
943
+ "button",
944
+ "submit",
945
+ "reset",
946
+ "image",
947
+ "file"
948
+ ];
949
+ /** What a field holds, or undefined for an element that holds nothing entered. */
950
+ const valueOf = (element) => {
951
+ if (isInput(element)) return valueless.includes(element.type) ? void 0 : element.value;
952
+ if (isTextArea(element)) return element.value;
953
+ if (isSelect(element)) return Array.from(element.selectedOptions, (option) => option.text).join(", ");
954
+ const parent = element.parentElement;
955
+ return isHtml(element) && element.isContentEditable && !(parent !== null && isHtml(parent) && parent.isContentEditable) ? element.innerText : void 0;
956
+ };
957
+ /** What a field shows: `••••` unless `unmask`, and always for a secret field; "" when empty. */
958
+ const shown = (element, unmask) => {
959
+ const value = valueOf(element);
960
+ if (value === void 0 || value.trim() === "") return value === void 0 ? void 0 : "";
961
+ return unmask && !isSecret(element) ? value : "••••";
962
+ };
963
+ /** Lines cut after the last whole line within `max` characters, or at `max` when none is. */
964
+ const cut = (lines, max) => {
965
+ if (lines.length <= max) return {
966
+ text: lines,
967
+ truncated: false
968
+ };
969
+ const end = lines.lastIndexOf("\n", max);
970
+ return {
971
+ text: lines.slice(0, end > 0 ? end : max),
972
+ truncated: true
973
+ };
974
+ };
975
+ /**
976
+ * What the viewport, or one element whole, shows as text: a line per block, table cells apart by
977
+ * a tab, and each field as `shown` gives it.
978
+ */
979
+ const lines = (root, unmask) => {
980
+ const lines = [];
981
+ let line = "";
982
+ const end = () => {
983
+ const words = line.replace(/[^\S\t]+/g, " ").replace(/ ?\t ?/g, " ").trim();
984
+ if (words !== "") lines.push(words);
985
+ line = "";
986
+ };
987
+ walked.visit(root, root === null, false, {
988
+ enter: (element, style) => {
989
+ const { display } = style;
990
+ const value = shown(element, unmask);
991
+ const block = !display.startsWith("inline") && display !== "contents" && display !== "table-cell";
992
+ if (display === "table-cell") line += " ";
993
+ if (block || element.tagName === "BR") end();
994
+ if (value === void 0 && !(isInput(element) && valueless.includes(element.type))) return block;
995
+ const label = isInput(element) && /^(button|submit|reset)$/.test(element.type);
996
+ line += ` ${value ?? (label ? element.value : "")} `;
997
+ if (block) end();
998
+ },
999
+ text: (node) => {
1000
+ line += node.textContent ?? "";
1001
+ },
1002
+ leave: (_, block) => {
1003
+ if (block) end();
1004
+ }
1005
+ });
1006
+ end();
1007
+ return lines.join("\n");
1008
+ };
1009
+ const read = (request) => {
1010
+ const root = request.ref === null ? null : lookup(request.ref);
1011
+ return root === void 0 ? null : {
1012
+ ...cut(lines(root, request.unmask), request.maxChars),
1013
+ url: location.href,
1014
+ title: document.title
1015
+ };
1016
+ };
1017
+ return {
1018
+ cut,
1019
+ lines,
1020
+ read,
1021
+ shown
1022
+ };
1023
+ };
1024
+ //#endregion
1025
+ //#region src/internal/reading/walk.inpage.ts
1026
+ const walk = (names) => {
1027
+ const { interactiveRoles, isElement, isFrame, isInput, parentOf, roleOf } = names;
1028
+ const skipped = new Set("SCRIPT STYLE NOSCRIPT TEMPLATE HEAD META LINK SVG".split(" "));
1029
+ /** Whether a box, in top-document pixels, meets the viewport. */
1030
+ const inView = (rect, width = innerWidth, height = innerHeight) => rect.right > 0 && rect.bottom > 0 && rect.left < width && rect.top < height;
1031
+ /** Whether an element reached on its own shows, by the walk's rule and its ancestors'. */
1032
+ const visible = (element) => {
1033
+ if (element.closest("[aria-hidden=true]") !== null) return false;
1034
+ if (element.checkVisibility({
1035
+ opacityProperty: true,
1036
+ visibilityProperty: true
1037
+ })) return true;
1038
+ if (getComputedStyle(element).display !== "contents") return false;
1039
+ for (let node = element; node !== null; node = parentOf(node)) {
1040
+ const style = getComputedStyle(node);
1041
+ if (style.display === "none" || style.opacity === "0" || node === element && style.visibility !== "visible") return false;
1042
+ }
1043
+ return true;
1044
+ };
1045
+ const untransformed = (frame, rect) => {
1046
+ if (rect.width !== frame.offsetWidth || rect.height !== frame.offsetHeight) return false;
1047
+ let ancestor = frame;
1048
+ while (ancestor !== null) {
1049
+ const style = (ancestor.ownerDocument.defaultView ?? window).getComputedStyle(ancestor);
1050
+ if (style.transform !== "none" || style.scale !== "none" || style.rotate !== "none" || style.perspective !== "none" || style.zoom !== "1") return false;
1051
+ ancestor = parentOf(ancestor);
1052
+ }
1053
+ return true;
1054
+ };
1055
+ /** The element painted at a point, inside shadow roots and same-origin frames. */
1056
+ const hitAt = (root, x, y) => {
1057
+ let hit = root.elementFromPoint(x, y);
1058
+ while (hit?.shadowRoot !== null && hit?.shadowRoot !== void 0) {
1059
+ const inner = hit.shadowRoot.elementFromPoint(x, y);
1060
+ if (inner === null || inner === hit) break;
1061
+ hit = inner;
1062
+ }
1063
+ if (hit !== null && isFrame(hit)) {
1064
+ const document = hit.contentDocument;
1065
+ if (document !== null) {
1066
+ const rect = hit.getBoundingClientRect();
1067
+ if (untransformed(hit, rect)) return hitAt(document, x - rect.left - hit.clientLeft, y - rect.top - hit.clientTop) ?? hit;
1068
+ }
1069
+ }
1070
+ return hit;
1071
+ };
1072
+ /** Whether its role or a click handler makes an element a control. */
1073
+ const acts = (element, role) => isInput(element) && element.type !== "hidden" || role !== null && (interactiveRoles.has(role) || role === "canvas" || role === "iframe") || element.hasAttribute("onclick");
1074
+ const controlOf = (hit) => {
1075
+ let element = hit;
1076
+ while (element !== null) {
1077
+ if (acts(element, roleOf(element))) return element;
1078
+ element = parentOf(element);
1079
+ }
1080
+ return hit;
1081
+ };
1082
+ /** An element's box in top-document viewport pixels, through the frames around it. */
1083
+ const boxOf = (element) => {
1084
+ const { x, y, width, height } = element.getBoundingClientRect();
1085
+ const frame = element.ownerDocument.defaultView?.frameElement ?? null;
1086
+ if (frame === null) return {
1087
+ x,
1088
+ y,
1089
+ width,
1090
+ height
1091
+ };
1092
+ const outer = boxOf(frame);
1093
+ return {
1094
+ x: x + outer.x + frame.clientLeft,
1095
+ y: y + outer.y + frame.clientTop,
1096
+ width,
1097
+ height
1098
+ };
1099
+ };
1100
+ /** What is painted where pinned things sit, what is pinned in view, and every element holding it. */
1101
+ const painted = (width, height) => {
1102
+ const keep = /* @__PURE__ */ new Set();
1103
+ const hold = (element) => {
1104
+ for (let node = element; node !== null && !keep.has(node); node = parentOf(node) ?? node.ownerDocument.defaultView?.frameElement ?? null) keep.add(node);
1105
+ };
1106
+ for (const y of [
1107
+ 8,
1108
+ 48,
1109
+ height / 2,
1110
+ height - 48,
1111
+ height - 8
1112
+ ]) for (const x of [
1113
+ 8,
1114
+ 48,
1115
+ width / 4,
1116
+ width / 2,
1117
+ width * 3 / 4,
1118
+ width - 48,
1119
+ width - 8
1120
+ ]) if (x >= 0 && y >= 0 && x < width && y < height) {
1121
+ hold(hitAt(document, x, y));
1122
+ for (const beneath of document.elementsFromPoint(x, y)) hold(beneath);
1123
+ }
1124
+ for (const element of Array.from(document.querySelectorAll(":modal, :popover-open"))) hold(element);
1125
+ for (const element of Array.from(document.querySelectorAll("[style*=\"fixed\" i]"))) if (inView(element.getBoundingClientRect(), width, height)) hold(element);
1126
+ return keep;
1127
+ };
1128
+ /**
1129
+ * Visit `root` and what it holds, or the whole document when `root` is null. With `viewport`,
1130
+ * a subtree outside the viewport is skipped, as described above.
1131
+ */
1132
+ const visit = (root, viewport, state, visitor) => {
1133
+ const { innerWidth: width, innerHeight: height } = window;
1134
+ let keep;
1135
+ const children = (parent, inner, dx, dy) => {
1136
+ const nodes = visitor.text === void 0 ? parent.children : parent.childNodes;
1137
+ for (const node of Array.from(nodes)) if (node.nodeType === Node.TEXT_NODE) visitor.text?.(node, inner);
1138
+ else if (isElement(node) && (visitor.admit === void 0 || visitor.admit(node, inner))) one(node, inner, dx, dy);
1139
+ };
1140
+ const one = (element, outer, dx, dy) => {
1141
+ if (skipped.has(element.tagName.toUpperCase())) return;
1142
+ const local = element.getBoundingClientRect();
1143
+ const rect = new DOMRect(local.x + dx, local.y + dy, local.width, local.height);
1144
+ if (viewport && local.width > 0 && local.height > 0 && !inView(rect, width, height) && !(keep ??= painted(width, height)).has(element)) {
1145
+ visitor.outside?.(rect);
1146
+ return;
1147
+ }
1148
+ const style = getComputedStyle(element);
1149
+ if (style.display === "none" || style.opacity === "0" || element.getAttribute("aria-hidden") === "true") return;
1150
+ if (!visible(element)) {
1151
+ for (const child of Array.from(element.children)) one(child, outer, dx, dy);
1152
+ return;
1153
+ }
1154
+ const inner = visitor.enter(element, style, rect, outer);
1155
+ if (inner === void 0) return;
1156
+ if (isFrame(element)) {
1157
+ const body = element.contentDocument?.body;
1158
+ if (body !== null && body !== void 0) children(body, inner, rect.x, rect.y);
1159
+ } else {
1160
+ if (element.shadowRoot !== null) children(element.shadowRoot, inner, dx, dy);
1161
+ children(element, inner, dx, dy);
1162
+ }
1163
+ visitor.leave?.(element, inner);
1164
+ };
1165
+ if (root === null) children(document, state, 0, 0);
1166
+ else one(root, state, 0, 0);
1167
+ };
1168
+ return {
1169
+ acts,
1170
+ boxOf,
1171
+ controlOf,
1172
+ hitAt,
1173
+ inView,
1174
+ visible,
1175
+ visit
1176
+ };
1177
+ };
1178
+ //#endregion
1179
+ //#region src/internal/timeline/changes.inpage.ts
1180
+ const changes = (names, walked, placing, kept, seeing, marking, recorder) => {
1181
+ const { clean, isInput, roleOf, nameOf } = names;
1182
+ const groups = "tr,[role=row],form,dialog,[role=dialog],[role=alertdialog]";
1183
+ /** Whether `element` lies in what an input on `target` acted on, its group, or what it controls. */
1184
+ const local = (target, element) => {
1185
+ const controls = target.closest("[aria-controls]")?.getAttribute("aria-controls") ?? "";
1186
+ const group = target.closest(groups);
1187
+ return target.contains(element) || group?.contains(element) === true || controls.split(/\s+/).some((id) => id !== "" && document.getElementById(id)?.contains(element) === true);
1188
+ };
1189
+ /** What an element sits in, or sat in as it went. */
1190
+ const parentOf = (key) => key instanceof Element ? key.isConnected ? key.parentElement : marking.placeOf(key) ?? null : null;
1191
+ const fluxMillis = 1e4;
1192
+ const stillMillis = 2e3;
1193
+ /**
1194
+ * Each input a change may follow, with what the page did before it: what changed in the 10 s
1195
+ * before, the parents that gained or lost a child then, and whether nothing changed, and nothing
1196
+ * was let go, in the 2 s before. What holds the input's target, as a menu holds its item, came
1197
+ * with it, so it counts only as changing itself.
1198
+ */
1199
+ const before = () => {
1200
+ const inputs = recorder.inputs();
1201
+ if (inputs.length === 0) return [];
1202
+ const { tracks, losses } = kept.recent();
1203
+ return inputs.map(({ at, target }) => {
1204
+ const changed = /* @__PURE__ */ new Set();
1205
+ const moved = /* @__PURE__ */ new Set();
1206
+ let still = losses.every((lost) => lost >= at || lost < at - stillMillis);
1207
+ for (const { key, kind, initial, samples } of tracks) {
1208
+ const prior = samples.flatMap(({ at: when, shown }, index) => kind === "value" || when >= at || when < at - fluxMillis ? [] : [shown === null || (index === 0 ? initial : samples[index - 1]?.shown) === null]);
1209
+ if (prior.length > 0) changed.add(key);
1210
+ if (prior.length === 0 || key instanceof Element && key.contains(target)) continue;
1211
+ if (prior.includes(true)) moved.add(parentOf(key));
1212
+ if (samples.some(({ at: when }) => when < at && when >= at - stillMillis)) still = false;
1213
+ }
1214
+ return {
1215
+ at,
1216
+ target,
1217
+ changed,
1218
+ moved,
1219
+ still
1220
+ };
1221
+ });
1222
+ };
1223
+ /** The input a change followed, on the page's clock, where `Change.cause`'s rule names one. */
1224
+ const causeOf = (one, element, inputs) => {
1225
+ const parent = parentOf(one.track.key);
1226
+ for (const input of inputs.toReversed()) {
1227
+ const after = one.startedAt - input.at;
1228
+ if (after < 0) continue;
1229
+ if (after > 3e3) break;
1230
+ if (!(one.track.known >= input.at - fluxMillis || input.changed.has(one.track.key) || parent !== null && input.moved.has(parent)) && (local(input.target, element) || after <= 500 && input.still)) return input.at;
1231
+ }
1232
+ };
1233
+ const describe = (one, known, unmask, inputs) => {
1234
+ const { track, kind, before, after, lowest, highest, ...times } = one;
1235
+ const element = track.key instanceof Element ? track.key : null;
1236
+ const where = element?.isConnected === true ? element : marking.placeOf(track.key) ?? null;
1237
+ const box = where === null ? void 0 : walked.boxOf(where);
1238
+ const role = element === null ? null : roleOf(element);
1239
+ const field = kind === "value";
1240
+ const checkable = element !== null && isInput(element) && /^(checkbox|radio)$/.test(element.type);
1241
+ const masked = (value) => value === void 0 || !field || unmask || checkable || value === "" ? value : "••••";
1242
+ return {
1243
+ ...times,
1244
+ kind,
1245
+ subject: {
1246
+ role,
1247
+ name: element === null ? "" : field ? nameOf(element, role) : clean(element.getAttribute("aria-label"), 120),
1248
+ tag: element === null ? "title" : element.tagName.toLowerCase(),
1249
+ context: kind === "title" || where === null ? {} : placing.contextOf(where, known)
1250
+ },
1251
+ box: box === void 0 || box.width === 0 && box.height === 0 ? void 0 : box,
1252
+ before: masked(before),
1253
+ after: masked(after),
1254
+ lowest: field ? void 0 : lowest,
1255
+ highest: field ? void 0 : highest,
1256
+ cause: field || where === null ? void 0 : causeOf(one, where, inputs)
1257
+ };
1258
+ };
1259
+ /** What changed after `since`, up to `until`, and no later than now. */
1260
+ const read = (request) => {
1261
+ const now = performance.timeOrigin + performance.now();
1262
+ recorder.start();
1263
+ seeing.settle();
1264
+ const until = Math.min(request.until ?? now, now);
1265
+ const { from, dropped, folded } = kept.read(request.since ?? Number.NEGATIVE_INFINITY, until, now);
1266
+ const known = placing.known();
1267
+ const inputs = before();
1268
+ return {
1269
+ until,
1270
+ from,
1271
+ dropped,
1272
+ records: folded.map((one) => describe(one, known, request.unmask, inputs))
1273
+ };
1274
+ };
1275
+ return { read };
1276
+ };
1277
+ //#endregion
1278
+ //#region src/internal/timeline/fold.inpage.ts
1279
+ const fold = () => {
1280
+ /** The one number some words show, such as 61240 in "$61,240"; none for none or several. */
1281
+ const number = (words) => {
1282
+ const found = words.match(/[-+−]?\d[\d,]*(?:\.\d+)?/g);
1283
+ const value = Number(found?.length === 1 ? found[0]?.replaceAll(",", "").replace("−", "-") : "");
1284
+ return found?.length === 1 && Number.isFinite(value) ? [value] : [];
1285
+ };
1286
+ /** A track's changes after `since`, up to `until`, if one was seen in view. */
1287
+ const over = (track, since, until) => {
1288
+ const inside = track.samples.filter((sample) => sample.at > since && sample.at <= until);
1289
+ const first = inside[0];
1290
+ const last = inside.at(-1);
1291
+ if (first === void 0 || last === void 0 || !inside.some((sample) => sample.seen === true)) return void 0;
1292
+ const prior = track.samples[track.samples.indexOf(first) - 1];
1293
+ const lost = track.known <= since ? track.known : void 0;
1294
+ const start = prior === void 0 ? lost === void 0 ? void 0 : track.initial : prior.shown;
1295
+ const words = [start, ...inside.map((sample) => sample.shown)].filter((each) => typeof each === "string");
1296
+ const numbers = words.flatMap(number);
1297
+ const ranged = inside.length > 1 && numbers.length === words.length;
1298
+ const kind = track.kind !== "content" ? track.kind : last.shown === null ? start === null ? "brief" : "disappeared" : start === null ? "appeared" : "text";
1299
+ return {
1300
+ track,
1301
+ kind,
1302
+ startedAt: first.at,
1303
+ at: last.at,
1304
+ before: kind === "disappeared" ? words.at(-1) : start ?? void 0,
1305
+ after: kind === "brief" ? words.at(-1) : last.shown ?? void 0,
1306
+ count: inside.length,
1307
+ lowest: ranged ? words[numbers.indexOf(Math.min(...numbers))] : void 0,
1308
+ highest: ranged ? words[numbers.indexOf(Math.max(...numbers))] : void 0,
1309
+ earlier: prior?.at ?? (lost === Number.NEGATIVE_INFINITY ? void 0 : lost)
1310
+ };
1311
+ };
1312
+ /**
1313
+ * How readily a track gives way when the record is full: one that holds no change first, then
1314
+ * one that keeps changing, one never seen in view and one that has gone; news never does.
1315
+ */
1316
+ const rank = ({ samples: [only, ...more] }) => only === void 0 ? 4 : more.length > 0 ? 3 : only.seen === false ? 2 : only.shown === null ? 1 : 0;
1317
+ return {
1318
+ number,
1319
+ over,
1320
+ rank
1321
+ };
1322
+ };
1323
+ //#endregion
1324
+ //#region src/internal/timeline/history.inpage.ts
1325
+ const history = (folding, bounds = {
1326
+ tracks: 256,
1327
+ samples: 32,
1328
+ retention: 6e4
1329
+ }) => {
1330
+ const { tracks: maxTracks, samples: maxSamples, retention } = bounds;
1331
+ const tracks = /* @__PURE__ */ new Map();
1332
+ let refused = /* @__PURE__ */ new WeakSet();
1333
+ let losses = [];
1334
+ let lastLoss = Number.NEGATIVE_INFINITY;
1335
+ const gone = [];
1336
+ let begun;
1337
+ const lose = (at, count) => {
1338
+ const last = losses.at(-1);
1339
+ if (count <= 0) return;
1340
+ lastLoss = Math.max(lastLoss, at);
1341
+ if (last?.[0] === at) last[1] += count;
1342
+ else losses.push([at, count]);
1343
+ if (losses.length > 256) losses.shift();
1344
+ };
1345
+ const latest = (track) => track.samples.at(-1)?.at ?? Number.NEGATIVE_INFINITY;
1346
+ const drop = (track) => {
1347
+ tracks.delete(track.key);
1348
+ gone.push(track.key);
1349
+ };
1350
+ let version = 0;
1351
+ let barren = -1;
1352
+ /** What gives way for a newcomer: one that holds no change, then one that keeps changing. */
1353
+ const victim = () => {
1354
+ let chosen;
1355
+ let rank = 0;
1356
+ for (const track of barren === version ? [] : tracks.values()) {
1357
+ const next = folding.rank(track);
1358
+ if (next > rank) [chosen, rank] = [track, next];
1359
+ if (rank === 4) break;
1360
+ }
1361
+ if (chosen === void 0) barren = version;
1362
+ return chosen;
1363
+ };
1364
+ const evict = (track) => {
1365
+ drop(track);
1366
+ if (track.samples.length > 0) refused.add(track.key);
1367
+ for (const sample of track.samples) lose(sample.at, 1);
1368
+ };
1369
+ /** A key the record cannot keep: its change is counted. */
1370
+ const refuse = (key, at) => {
1371
+ refused.add(key);
1372
+ lose(at, 1);
1373
+ };
1374
+ /**
1375
+ * A new state for `key` at `at`: its sample, or none when it is no change or finds no room.
1376
+ * `initial` says what a key not yet kept showed before.
1377
+ */
1378
+ const note = (key, kind, at, shown, initial) => {
1379
+ let track = tracks.get(key);
1380
+ if (track === void 0) {
1381
+ const full = !refused.has(key) && tracks.size >= maxTracks;
1382
+ const out = full ? victim() : void 0;
1383
+ if (refused.has(key) || full && out === void 0) return refuse(key, at);
1384
+ const before = initial();
1385
+ if (shown !== void 0 && shown === before) return void 0;
1386
+ if (out !== void 0) evict(out);
1387
+ track = {
1388
+ key,
1389
+ kind,
1390
+ initial: before,
1391
+ known: Number.NEGATIVE_INFINITY,
1392
+ samples: []
1393
+ };
1394
+ tracks.set(key, track);
1395
+ }
1396
+ const { samples } = track;
1397
+ version++;
1398
+ if (samples.at(-1)?.at === at) samples.pop();
1399
+ const previous = samples.length === 0 ? track.initial : samples.at(-1)?.shown;
1400
+ if (shown !== void 0 && shown === previous) return void 0;
1401
+ const oldest = samples.length >= maxSamples ? samples.shift() : void 0;
1402
+ if (oldest !== void 0) {
1403
+ track.initial = oldest.shown;
1404
+ track.known = oldest.at;
1405
+ lose(oldest.at, 1);
1406
+ }
1407
+ const sample = {
1408
+ at,
1409
+ shown,
1410
+ seen: void 0
1411
+ };
1412
+ samples.push(sample);
1413
+ return sample;
1414
+ };
1415
+ /** Judge a sample as the page rendered it; a state that repeats the one before is no change. */
1416
+ const settle = (key, sample, shown, seen) => {
1417
+ const track = tracks.get(key);
1418
+ version++;
1419
+ if (sample.shown === void 0) sample.shown = shown;
1420
+ if (sample.seen === void 0) sample.seen = seen;
1421
+ if (track === void 0) return;
1422
+ let previous = track.initial;
1423
+ const changes = track.samples.filter((each) => {
1424
+ const same = each.shown !== void 0 && each.shown === previous;
1425
+ if (!same) previous = each.shown;
1426
+ return !same;
1427
+ });
1428
+ track.samples.splice(0, track.samples.length, ...changes);
1429
+ };
1430
+ /**
1431
+ * The window after `since`, up to `until`: where the record is whole, how many changes in it the
1432
+ * record let go, and each element's changes, oldest first by when they began.
1433
+ */
1434
+ const read = (since, until, now) => {
1435
+ for (const track of tracks.values()) if (latest(track) < now - retention) drop(track);
1436
+ return {
1437
+ from: Math.min(until, Math.max(begun ?? now, now - retention, lastLoss)),
1438
+ dropped: losses.reduce((sum, [at, count]) => at > since && at <= until ? sum + count : sum, 0),
1439
+ folded: [...tracks.values()].flatMap((track) => folding.over(track, since, until) ?? []).toSorted((left, right) => left.startedAt - right.startedAt)
1440
+ };
1441
+ };
1442
+ /** When something in view last changed, or something not yet judged; for a wait for stillness. */
1443
+ const changing = () => Math.max(begun ?? Number.NEGATIVE_INFINITY, ...Array.from(tracks.values(), (track) => track.samples.findLast((sample) => sample.seen !== false)?.at ?? Number.NEGATIVE_INFINITY));
1444
+ return {
1445
+ begin: (at) => {
1446
+ begun = at;
1447
+ },
1448
+ begun: () => begun !== void 0,
1449
+ clear: () => {
1450
+ for (const track of tracks.values()) drop(track);
1451
+ refused = /* @__PURE__ */ new WeakSet();
1452
+ losses = [];
1453
+ lastLoss = Number.NEGATIVE_INFINITY;
1454
+ begun = void 0;
1455
+ },
1456
+ changing,
1457
+ /** Keys whose tracks went since this was last asked, for the recorder to stop watching. */
1458
+ forgotten: () => gone.splice(0),
1459
+ has: (key) => tracks.has(key),
1460
+ /** Whether the record has let `key` go: its later changes are counted, never kept. */
1461
+ refuses: (key) => refused.has(key),
1462
+ lose,
1463
+ note,
1464
+ read,
1465
+ /** Each element's history, and when the record let changes go, for a read to judge causes. */
1466
+ recent: () => ({
1467
+ tracks: [...tracks.values()],
1468
+ losses: losses.map(([at]) => at)
1469
+ }),
1470
+ /** A track moves to the element that took its key's place, as a re-rendered price does. */
1471
+ rekey: (from, to) => {
1472
+ const track = tracks.get(from);
1473
+ if (track === void 0 || tracks.has(to)) return false;
1474
+ tracks.delete(from);
1475
+ track.key = to;
1476
+ tracks.set(to, track);
1477
+ return true;
1478
+ },
1479
+ settle
1480
+ };
1481
+ };
1482
+ //#endregion
1483
+ //#region src/internal/timeline/marks.inpage.ts
1484
+ const marks = (names, kept, seeing) => {
1485
+ const { clean, isElement, isHtml } = names;
1486
+ const unwritten = new Set("SCRIPT STYLE NOSCRIPT TEMPLATE TITLE".split(" "));
1487
+ const hiding = /display\s*:\s*none|visibility\s*:\s*hidden|opacity\s*:\s*0(?![.\d])/i;
1488
+ let places = /* @__PURE__ */ new WeakMap();
1489
+ let title = "";
1490
+ const words = (text) => clean(text, 200) || null;
1491
+ const content = (element, at, shown, initial) => {
1492
+ const sample = kept.note(element, "content", at, shown, initial);
1493
+ if (sample !== void 0) seeing.look(element, sample);
1494
+ };
1495
+ /** What a text-only element said before this batch: its text with the batch undone. */
1496
+ const before = (leaf, records) => {
1497
+ let nodes = Array.from(leaf.childNodes);
1498
+ const old = /* @__PURE__ */ new Map();
1499
+ for (const record of records.toReversed()) if (record.type === "characterData") old.set(record.target, record.oldValue ?? "");
1500
+ else {
1501
+ const added = new Set(Array.from(record.addedNodes));
1502
+ nodes = nodes.filter((node) => !added.has(node));
1503
+ const next = record.nextSibling === null ? -1 : nodes.indexOf(record.nextSibling);
1504
+ nodes.splice(next === -1 ? nodes.length : next, 0, ...Array.from(record.removedNodes));
1505
+ }
1506
+ return words(nodes.map((node) => old.get(node) ?? node.textContent).join(""));
1507
+ };
1508
+ const attribute = (element, { attributeName: name, oldValue: old }, at) => {
1509
+ const was = name === "hidden" ? old !== null : name === "aria-hidden" ? old === "true" : name === "open" ? element.tagName === "DIALOG" && old === null : name === "style" && hiding.test(old ?? "");
1510
+ if (name === "style" && !was && !hiding.test(element.getAttribute("style") ?? "")) return;
1511
+ const state = seeing.state(element);
1512
+ if (!kept.has(element) && !was && state === void 0 && name !== "open") return seeing.glance(element);
1513
+ content(element, at, void 0, () => was || state === false ? null : name === "open" && old === null ? words(element.querySelector(":scope > summary")?.textContent) : words(element.textContent));
1514
+ };
1515
+ /** What one mutation added to and removed from `target`. */
1516
+ const nodes = (change, target, batch) => {
1517
+ const added = Array.from(change.addedNodes).slice(0, 64);
1518
+ const removed = Array.from(change.removedNodes).slice(0, 64);
1519
+ const text = [...added, ...removed].some((node) => !isElement(node) && /\S/.test(node.textContent ?? ""));
1520
+ kept.lose(batch.at, Math.max(change.addedNodes.length, change.removedNodes.length) - 64);
1521
+ if (text) batch.owners.add(target);
1522
+ removed.forEach((gone, index) => {
1523
+ const node = added[index];
1524
+ if (!isElement(gone)) return;
1525
+ batch.left.add(gone);
1526
+ if (node !== void 0 && isElement(node) && kept.rekey(gone, node)) seeing.unwatch(gone);
1527
+ else if (kept.has(gone)) {
1528
+ places.set(gone, target);
1529
+ const sample = kept.note(gone, "content", batch.at, null, () => void 0);
1530
+ if (sample !== void 0) sample.seen = seeing.viewed(gone);
1531
+ seeing.unwatch(gone);
1532
+ }
1533
+ });
1534
+ for (const node of added) if (isElement(node) && isHtml(node) && !unwritten.has(node.tagName) && !node.isContentEditable) {
1535
+ if (kept.has(node) || !text && !batch.left.has(node)) {
1536
+ batch.arrived.add(node);
1537
+ content(node, batch.at, void 0, () => null);
1538
+ }
1539
+ }
1540
+ };
1541
+ /** Whether `element` is inside something this batch added, which tells it with its own words. */
1542
+ const inside = (element, arrived) => {
1543
+ for (let up = element.parentElement; arrived.size > 0 && up !== null; up = up.parentElement) if (arrived.has(up)) return true;
1544
+ return false;
1545
+ };
1546
+ const ownerOf = (change) => change.type === "characterData" ? change.target.parentElement : change.target;
1547
+ /** Mark what one batch of mutations changed, at `at`. */
1548
+ const mark = (records, at) => {
1549
+ const batch = {
1550
+ at,
1551
+ owners: /* @__PURE__ */ new Set(),
1552
+ arrived: /* @__PURE__ */ new Set(),
1553
+ left: /* @__PURE__ */ new Set()
1554
+ };
1555
+ let byOwner;
1556
+ for (const change of records) {
1557
+ const target = ownerOf(change);
1558
+ if (target === null || !isElement(target) || inside(target, batch.arrived)) continue;
1559
+ const known = kept.has(target) || kept.refuses(target);
1560
+ if (change.type !== "attributes") if (change.type === "characterData" || target.childElementCount === 0 && known) batch.owners.add(target);
1561
+ else nodes(change, target, batch);
1562
+ else if (isHtml(target) && target !== document.body && target !== document.documentElement) attribute(target, change, at);
1563
+ }
1564
+ for (const owner of batch.owners) {
1565
+ const leaf = owner.childElementCount === 0;
1566
+ if (kept.refuses(owner)) kept.lose(at, 1);
1567
+ if (kept.refuses(owner) || !isHtml(owner) || unwritten.has(owner.tagName)) continue;
1568
+ if (owner === document.body || owner.isContentEditable) continue;
1569
+ if (batch.arrived.has(owner) || inside(owner, batch.arrived)) continue;
1570
+ content(owner, at, leaf ? words(owner.textContent) : void 0, () => {
1571
+ byOwner ??= Map.groupBy(records, ownerOf);
1572
+ return leaf ? before(owner, byOwner.get(owner) ?? []) : void 0;
1573
+ });
1574
+ }
1575
+ if (document.title === title) return;
1576
+ const previous = words(title);
1577
+ const sample = kept.note(document, "title", at, words(title = document.title), () => previous);
1578
+ if (sample !== void 0) sample.seen = true;
1579
+ };
1580
+ return {
1581
+ mark,
1582
+ /** Where a removed element was, which gives its context. */
1583
+ placeOf: (key) => places.get(key),
1584
+ /** Start afresh, from the document's title now. */
1585
+ reset: () => {
1586
+ places = /* @__PURE__ */ new WeakMap();
1587
+ title = document.title;
1588
+ }
1589
+ };
1590
+ };
1591
+ //#endregion
1592
+ //#region src/internal/timeline/record.inpage.ts
1593
+ const record = (names, texts, kept, seeing, marking) => {
1594
+ const { isElement, isInput } = names;
1595
+ const epoch = () => performance.timeOrigin + performance.now();
1596
+ const declared = "[role=alert],[role=status],[role=log],[role=dialog],[role=alertdialog],[aria-live],dialog,[popover]";
1597
+ let running = false;
1598
+ let lastRead = 0;
1599
+ let focused = /* @__PURE__ */ new WeakMap();
1600
+ const inputs = [];
1601
+ const targetOf = (event) => {
1602
+ const target = event.composedPath()[0];
1603
+ return target instanceof Node && isElement(target) ? target : void 0;
1604
+ };
1605
+ /** A field's value as the record keeps it: a secret one's as `••••`, a box's checked or not. */
1606
+ const valueOf = (field) => isInput(field) && (field.type === "checkbox" || field.type === "radio") ? field.checked ? "checked" : "not checked" : texts.shown(field, true);
1607
+ const onFocus = (event) => {
1608
+ const field = targetOf(event);
1609
+ const value = field === void 0 ? void 0 : valueOf(field);
1610
+ if (field !== void 0 && value !== void 0) focused.set(field, value);
1611
+ };
1612
+ const onValue = (event) => {
1613
+ const field = targetOf(event);
1614
+ const value = field === void 0 ? void 0 : valueOf(field);
1615
+ if (field === void 0 || value === void 0) return;
1616
+ const sample = kept.note(field, "value", epoch(), value, () => focused.get(field) ?? null);
1617
+ if (sample !== void 0) seeing.look(field, sample);
1618
+ };
1619
+ const note = (target) => {
1620
+ inputs.push({
1621
+ at: epoch(),
1622
+ target
1623
+ });
1624
+ if (inputs.length > 8) inputs.shift();
1625
+ };
1626
+ const onInput = (event) => {
1627
+ const target = targetOf(event);
1628
+ if (event.isTrusted && target !== void 0) note(target);
1629
+ };
1630
+ const listeners = [
1631
+ ["focusin", onFocus],
1632
+ ["input", onValue],
1633
+ ["change", onValue],
1634
+ ["pointerdown", onInput],
1635
+ ["keydown", onInput]
1636
+ ];
1637
+ const options = {
1638
+ capture: true,
1639
+ passive: true
1640
+ };
1641
+ const stop = () => {
1642
+ running = false;
1643
+ document.removeEventListener("DOMContentLoaded", begin);
1644
+ observer.disconnect();
1645
+ for (const [type, listener] of listeners) document.removeEventListener(type, listener, options);
1646
+ seeing.clear();
1647
+ kept.clear();
1648
+ kept.forgotten();
1649
+ inputs.length = 0;
1650
+ focused = /* @__PURE__ */ new WeakMap();
1651
+ };
1652
+ const observer = new MutationObserver((records) => {
1653
+ const at = epoch();
1654
+ if (at - lastRead > 12e4) stop();
1655
+ else marking.mark(records, at);
1656
+ });
1657
+ const begin = () => {
1658
+ if (!running || kept.begun()) return;
1659
+ observer.observe(document, {
1660
+ subtree: true,
1661
+ childList: true,
1662
+ characterData: true,
1663
+ characterDataOldValue: true,
1664
+ attributeFilter: [
1665
+ "hidden",
1666
+ "open",
1667
+ "aria-hidden",
1668
+ "class",
1669
+ "style"
1670
+ ],
1671
+ attributeOldValue: true
1672
+ });
1673
+ for (const [type, listener] of listeners) document.addEventListener(type, listener, options);
1674
+ marking.reset();
1675
+ for (const element of Array.from(document.querySelectorAll(declared)).slice(0, 64)) seeing.glance(element, true);
1676
+ kept.begin(epoch());
1677
+ };
1678
+ return {
1679
+ stop,
1680
+ /** Record from now, once the document is parsed; each read keeps the record going. */
1681
+ start: () => {
1682
+ lastRead = epoch();
1683
+ if (running) return;
1684
+ running = true;
1685
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", begin, { once: true });
1686
+ else begin();
1687
+ },
1688
+ /**
1689
+ * Keep an input at `target` now, as a trusted one is kept: what a site does through its own
1690
+ * app, whose events the page sees as untrusted, so its changes can name their cause.
1691
+ */
1692
+ note,
1693
+ inputs: () => inputs
1694
+ };
1695
+ };
1696
+ //#endregion
1697
+ //#region src/internal/timeline/sight.inpage.ts
1698
+ const sight = (names, walked, texts, kept) => {
1699
+ const { clean } = names;
1700
+ const { visible } = walked;
1701
+ let viewed = /* @__PURE__ */ new WeakMap();
1702
+ let watching = /* @__PURE__ */ new WeakSet();
1703
+ let states = /* @__PURE__ */ new WeakMap();
1704
+ const waiting = /* @__PURE__ */ new Map();
1705
+ /** What an element shows: its words, if its style shows it. */
1706
+ const shownBy = (element) => element.isConnected && visible(element) ? clean(texts.lines(element, false), 200) || null : null;
1707
+ /** Settle what waited on an element; its words are read once, if one of them needs them. */
1708
+ const judge = (element, pending, seen, was) => {
1709
+ const shown = pending.some((sample) => sample.shown === void 0) ? shownBy(element) : void 0;
1710
+ for (const sample of pending) {
1711
+ const now = sample.shown === void 0 ? shown : sample.shown;
1712
+ kept.settle(element, sample, now, now === null ? was : seen);
1713
+ }
1714
+ };
1715
+ const observer = new IntersectionObserver((entries) => {
1716
+ for (const { target, isIntersecting } of entries) {
1717
+ const was = viewed.get(target) ?? false;
1718
+ const seen = isIntersecting && visible(target);
1719
+ const pending = waiting.get(target);
1720
+ viewed.set(target, seen);
1721
+ waiting.delete(target);
1722
+ if (pending !== void 0) judge(target, pending, seen, was);
1723
+ if (!kept.has(target)) {
1724
+ states.set(target, visible(target));
1725
+ unwatch(target);
1726
+ }
1727
+ }
1728
+ });
1729
+ /** Watch an element, asking for a fresh report even if it is watched already. */
1730
+ const watch = (element) => {
1731
+ watching.add(element);
1732
+ observer.unobserve(element);
1733
+ observer.observe(element);
1734
+ };
1735
+ const unwatch = (element) => {
1736
+ watching.delete(element);
1737
+ observer.unobserve(element);
1738
+ };
1739
+ return {
1740
+ /** Judge a sample at once if what it shows and whether it is in view are known, else on render. */
1741
+ look: (element, sample) => {
1742
+ const view = viewed.get(element);
1743
+ if (sample.shown !== void 0 && view !== void 0 && watching.has(element)) {
1744
+ sample.seen = view;
1745
+ return;
1746
+ }
1747
+ waiting.set(element, [...waiting.get(element) ?? [], sample]);
1748
+ watch(element);
1749
+ },
1750
+ /**
1751
+ * Look at an element once, for its state when it next changes: as it renders, or `now`, by its
1752
+ * style, as for the few the record looks at as it starts.
1753
+ */
1754
+ glance: (element, now = false) => {
1755
+ if (now) states.set(element, visible(element));
1756
+ if (!watching.has(element)) watch(element);
1757
+ },
1758
+ /** Whether the style of an element looked at once showed it, if it was. */
1759
+ state: (element) => states.get(element),
1760
+ /** Whether a watched element was in view as the page last rendered it. */
1761
+ viewed: (element) => viewed.get(element) ?? false,
1762
+ unwatch,
1763
+ /** Judge now what the page has not rendered since it changed, as a hidden tab never does. */
1764
+ settle: () => {
1765
+ for (const [element, pending] of waiting) {
1766
+ const seen = element.isConnected && walked.inView(element.getBoundingClientRect()) && visible(element);
1767
+ judge(element, pending, seen, viewed.get(element) ?? false);
1768
+ viewed.set(element, seen);
1769
+ }
1770
+ waiting.clear();
1771
+ for (const key of kept.forgotten()) if (key instanceof Element) unwatch(key);
1772
+ },
1773
+ clear: () => {
1774
+ observer.disconnect();
1775
+ waiting.clear();
1776
+ viewed = /* @__PURE__ */ new WeakMap();
1777
+ watching = /* @__PURE__ */ new WeakSet();
1778
+ states = /* @__PURE__ */ new WeakMap();
1779
+ }
1780
+ };
1781
+ };
1782
+ //#endregion
1783
+ //#region src/internal/page/compose.inpage.ts
1784
+ /** Compose the parts; refs go on from `next`, as a script installed before left them. */
1785
+ const compose = (parts, next) => {
1786
+ const named = parts.names(parts.elements());
1787
+ if (next !== void 0) named.refs.next = next;
1788
+ const walked = parts.walk(named);
1789
+ const placing = parts.context(named, walked);
1790
+ const matching = parts.match();
1791
+ const subjected = parts.subjects(named, walked, matching, placing, parts.states(named));
1792
+ const texts = parts.text(named, walked);
1793
+ const controlled = parts.controls(named, subjected, texts);
1794
+ const kept = parts.history(parts.fold());
1795
+ const seeing = parts.sight(named, walked, texts, kept);
1796
+ const marking = parts.marks(named, kept, seeing);
1797
+ const recorder = parts.record(named, texts, kept, seeing, marking);
1798
+ const url = parts.addresses();
1799
+ const read = parts.outline(named, walked, subjected, texts, controlled, url);
1800
+ const readiness = parts.ready(walked, texts, kept);
1801
+ const overlaid = parts.overlay(named);
1802
+ const posing = parts.pose(named);
1803
+ return {
1804
+ named,
1805
+ walked,
1806
+ placing,
1807
+ overlaid,
1808
+ posing,
1809
+ recorder,
1810
+ url,
1811
+ reads: {
1812
+ refs: named.refs,
1813
+ snapshot: read.snapshot,
1814
+ find: subjected.find,
1815
+ layout: parts.layout(named, walked, subjected, matching, placing).read,
1816
+ overlay: overlaid.draw,
1817
+ pose: posing.set,
1818
+ unpose: posing.clear,
1819
+ until: parts.expectations(named, subjected, matching).until,
1820
+ text: texts.read,
1821
+ record: recorder.start,
1822
+ stopRecord: recorder.stop,
1823
+ changes: parts.changes(named, walked, placing, kept, seeing, marking, recorder).read,
1824
+ ready: readiness.wait,
1825
+ settle: readiness.settle,
1826
+ viewport: read.viewport
1827
+ }
1828
+ };
1829
+ };
1830
+ //#endregion
1831
+ //#region src/internal/page/overlay.inpage.ts
1832
+ const overlay = (names) => {
1833
+ const svgNamespace = "http://www.w3.org/2000/svg";
1834
+ let host;
1835
+ let root;
1836
+ const mount = () => {
1837
+ if (host === void 0 || root === void 0) {
1838
+ host = document.createElement("div");
1839
+ root = host.attachShadow({ mode: "closed" });
1840
+ names.adopt(host);
1841
+ const sheet = new CSSStyleSheet();
1842
+ sheet.replaceSync("svg { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible }");
1843
+ root.adoptedStyleSheets = [sheet];
1844
+ }
1845
+ const zoom = Number(getComputedStyle(document.documentElement).zoom) || 1;
1846
+ for (const [name, value] of Object.entries({
1847
+ all: "initial",
1848
+ display: "block",
1849
+ position: "fixed",
1850
+ left: "0",
1851
+ top: "0",
1852
+ width: "100vw",
1853
+ height: "100vh",
1854
+ "pointer-events": "none",
1855
+ "z-index": "2147483647",
1856
+ contain: "strict",
1857
+ zoom: String(1 / zoom)
1858
+ })) host.style.setProperty(name, value, "important");
1859
+ if (host.parentNode !== document.documentElement) document.documentElement.append(host);
1860
+ return root;
1861
+ };
1862
+ const boxes = (drawing) => Array.from(drawing.children).slice(0, 32).map((part) => {
1863
+ const { x, y, width, height } = part.getBoundingClientRect();
1864
+ return {
1865
+ x,
1866
+ y,
1867
+ width,
1868
+ height
1869
+ };
1870
+ }).filter((box) => box.width > 0 && box.height > 0);
1871
+ /**
1872
+ * Draw an SVG document over the viewport, in place of what was drawn, or take the layer away
1873
+ * with null. Says where the drawing's parts are. Its scripts and handlers are dropped.
1874
+ */
1875
+ const draw = (markup) => {
1876
+ if (markup === null) {
1877
+ host?.remove();
1878
+ return [];
1879
+ }
1880
+ const parsed = new DOMParser().parseFromString(markup, "image/svg+xml");
1881
+ const drawing = parsed.documentElement;
1882
+ if (parsed.getElementsByTagName("parsererror").length > 0 || drawing.namespaceURI !== svgNamespace || drawing.localName !== "svg") throw new Error("the overlay's markup is not an SVG document");
1883
+ for (const script of Array.from(drawing.getElementsByTagName("script"))) script.remove();
1884
+ for (const element of [drawing, ...Array.from(drawing.querySelectorAll("*"))]) for (const attribute of Array.from(element.attributes)) if (/^on/i.test(attribute.name)) element.removeAttribute(attribute.name);
1885
+ const shown = document.importNode(drawing, true);
1886
+ mount().replaceChildren(shown);
1887
+ return boxes(shown);
1888
+ };
1889
+ return {
1890
+ draw,
1891
+ mount
1892
+ };
1893
+ };
1894
+ //#endregion
1895
+ //#region src/internal/page/pose.inpage.ts
1896
+ /** A pose as the page takes it, each part left out made the one that changes nothing. */
1897
+ const poseRequest = (pose) => ({
1898
+ ref: pose.ref,
1899
+ dx: pose.dx ?? 0,
1900
+ dy: pose.dy ?? 0,
1901
+ sx: pose.sx ?? 1,
1902
+ sy: pose.sy ?? 1,
1903
+ rotate: pose.rotate ?? 0,
1904
+ origin: pose.origin ?? null
1905
+ });
1906
+ const pose = (names) => {
1907
+ const posed = /* @__PURE__ */ new Map();
1908
+ const isHtml = (element) => "offsetWidth" in element;
1909
+ const laidOut = (element, applied) => {
1910
+ const style = getComputedStyle(element);
1911
+ const [cx = 0, cy = 0] = style.transformOrigin.split(" ").map(Number.parseFloat);
1912
+ const own = style.transform === "none" ? new DOMMatrix() : new DOMMatrix(style.transform);
1913
+ const whole = applied === void 0 ? own : new DOMMatrix().translate(applied.x, applied.y).rotate(applied.rotate).scale(applied.sx, applied.sy).multiply(own);
1914
+ const drawn = element.getBoundingClientRect();
1915
+ const plain = whole.isIdentity;
1916
+ const width = plain ? drawn.width : element.offsetWidth;
1917
+ const height = plain ? drawn.height : element.offsetHeight;
1918
+ let left = Infinity;
1919
+ let top = Infinity;
1920
+ for (const [x, y] of [
1921
+ [0, 0],
1922
+ [width, 0],
1923
+ [0, height],
1924
+ [width, height]
1925
+ ]) {
1926
+ const corner = whole.transformPoint({
1927
+ x: x - cx,
1928
+ y: y - cy
1929
+ });
1930
+ left = Math.min(left, corner.x + cx);
1931
+ top = Math.min(top, corner.y + cy);
1932
+ }
1933
+ const origin = {
1934
+ x: drawn.x - left + cx,
1935
+ y: drawn.y - top + cy
1936
+ };
1937
+ const middle = own.transformPoint({
1938
+ x: width / 2 - cx,
1939
+ y: height / 2 - cy
1940
+ });
1941
+ return {
1942
+ origin,
1943
+ middle: {
1944
+ x: origin.x + middle.x,
1945
+ y: origin.y + middle.y
1946
+ }
1947
+ };
1948
+ };
1949
+ const apply = (element, request) => {
1950
+ const known = posed.get(element);
1951
+ const { origin, middle } = laidOut(element, known?.applied);
1952
+ const about = request.origin ?? middle;
1953
+ const away = {
1954
+ x: about.x - origin.x,
1955
+ y: about.y - origin.y
1956
+ };
1957
+ const turned = new DOMMatrix().rotate(request.rotate).scale(request.sx, request.sy).transformPoint(away);
1958
+ const applied = {
1959
+ x: request.dx + away.x - turned.x,
1960
+ y: request.dy + away.y - turned.y,
1961
+ rotate: request.rotate,
1962
+ sx: request.sx,
1963
+ sy: request.sy
1964
+ };
1965
+ const frame = {
1966
+ translate: `${applied.x}px ${applied.y}px`,
1967
+ rotate: `${applied.rotate}deg`,
1968
+ scale: `${applied.sx} ${applied.sy}`
1969
+ };
1970
+ if (known === void 0) {
1971
+ const effect = new KeyframeEffect(element, [frame, frame], {
1972
+ duration: Infinity,
1973
+ fill: "both"
1974
+ });
1975
+ const animation = new Animation(effect, document.timeline);
1976
+ animation.play();
1977
+ posed.set(element, {
1978
+ animation,
1979
+ effect,
1980
+ applied
1981
+ });
1982
+ } else {
1983
+ known.effect.setKeyframes([frame, frame]);
1984
+ known.applied = applied;
1985
+ }
1986
+ };
1987
+ const takeOff = (element) => {
1988
+ posed.get(element)?.animation.cancel();
1989
+ posed.delete(element);
1990
+ };
1991
+ /**
1992
+ * The elements `requests` name, or the first that names none in the current document, or one
1993
+ * that is not an HTML element; then, to apply them, a function that poses them and takes poses
1994
+ * off every other element.
1995
+ */
1996
+ const prepare = (requests) => {
1997
+ const elements = [];
1998
+ for (const request of requests) {
1999
+ const element = names.lookup(request.ref);
2000
+ const { dx, dy, sx, sy, rotate, origin } = request;
2001
+ if (element === void 0) return { stale: request.ref };
2002
+ if (!isHtml(element)) return { invalid: `${request.ref} is not an HTML element` };
2003
+ if (![
2004
+ dx,
2005
+ dy,
2006
+ sx,
2007
+ sy,
2008
+ rotate,
2009
+ origin?.x ?? 0,
2010
+ origin?.y ?? 0
2011
+ ].every(Number.isFinite)) return { invalid: `${request.ref}'s pose is not finite numbers` };
2012
+ elements.push(element);
2013
+ }
2014
+ return { apply: () => {
2015
+ for (const element of Array.from(posed.keys())) if (!elements.includes(element)) takeOff(element);
2016
+ requests.forEach((request, index) => {
2017
+ const element = elements[index];
2018
+ if (element !== void 0) apply(element, request);
2019
+ });
2020
+ } };
2021
+ };
2022
+ const set = (requests) => {
2023
+ const prepared = prepare(requests);
2024
+ if ("apply" in prepared) {
2025
+ prepared.apply();
2026
+ return {};
2027
+ }
2028
+ return prepared;
2029
+ };
2030
+ const clear = () => {
2031
+ for (const element of Array.from(posed.keys())) takeOff(element);
2032
+ };
2033
+ return {
2034
+ prepare,
2035
+ set,
2036
+ clear
2037
+ };
2038
+ };
2039
+ //#endregion
2040
+ export { context as S, elements as _, sight as a, expectations as b, history as c, walk as d, text as f, outline as g, ready as h, compose as i, fold as l, subjects as m, poseRequest as n, record as o, states as p, overlay as r, marks as s, pose as t, changes as u, names as v, controls as x, layout as y };
2041
+
2042
+ //# sourceMappingURL=pose.inpage-CLq7Mfdr.mjs.map