@botiverse/porthole 0.14.7 → 0.14.9

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 (87) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/dist/bridge/bridge.d.ts +6 -0
  3. package/dist/bridge/bridge.js +5 -0
  4. package/dist/check/files.js +2 -0
  5. package/dist/check/lint.js +82 -3
  6. package/dist/check/page-source.js +1 -1
  7. package/dist/compile/policy.d.ts +17 -6
  8. package/dist/compile/policy.js +22 -7
  9. package/dist/config/capabilities.d.ts +16 -2
  10. package/dist/config/capabilities.js +8 -0
  11. package/dist/config/schema.d.ts +13 -0
  12. package/dist/config/validate.js +15 -0
  13. package/dist/conformance/harness-source.js +1 -1
  14. package/dist/conformance/kit.d.ts +5 -0
  15. package/dist/conformance/kit.js +21 -0
  16. package/dist/conformance/limits.js +10 -5
  17. package/dist/conformance/probes.js +139 -28
  18. package/dist/conformance/served.js +25 -4
  19. package/dist/find/types.d.ts +83 -0
  20. package/dist/find/types.js +29 -0
  21. package/dist/find/validate.d.ts +17 -0
  22. package/dist/find/validate.js +82 -0
  23. package/dist/guide/guide.js +2 -1
  24. package/dist/guide/limits.js +8 -1
  25. package/dist/host/create-host.js +249 -4
  26. package/dist/host/pass-on.js +3 -2
  27. package/dist/host/types.d.ts +51 -0
  28. package/dist/index.d.ts +4 -2
  29. package/dist/index.js +4 -1
  30. package/dist/presets/presets.d.ts +6 -0
  31. package/dist/presets/presets.js +6 -0
  32. package/dist/react/frame.d.ts +43 -0
  33. package/dist/react/frame.js +107 -3
  34. package/dist/react/view.js +2 -0
  35. package/dist/runtime/contract.d.ts +1 -1
  36. package/dist/runtime/contract.js +1 -1
  37. package/dist/server/files.js +4 -3
  38. package/dist/server/server.js +4 -1
  39. package/dist/shell/annotate.js +2 -95
  40. package/dist/shell/document.d.ts +3 -3
  41. package/dist/shell/document.js +5 -3
  42. package/dist/shell/find.d.ts +82 -0
  43. package/dist/shell/find.js +725 -0
  44. package/dist/shell/plan.d.ts +5 -0
  45. package/dist/shell/plan.js +2 -0
  46. package/dist/shell/runtime.d.ts +30 -1
  47. package/dist/shell/runtime.js +789 -105
  48. package/dist/shell/text.d.ts +17 -0
  49. package/dist/shell/text.js +140 -0
  50. package/docs/ADOPTING.md +103 -0
  51. package/docs/ARCHITECTURE.md +10 -3
  52. package/docs/DECISIONS.md +513 -1
  53. package/docs/DESIGN.md +40 -4
  54. package/docs/THREAT_MODEL.md +75 -6
  55. package/docs/insertion-entry-points.md +112 -0
  56. package/package.json +1 -1
  57. package/src/bridge/bridge.ts +7 -0
  58. package/src/check/files.ts +2 -0
  59. package/src/check/lint.ts +97 -8
  60. package/src/compile/policy.ts +23 -6
  61. package/src/config/capabilities.ts +13 -1
  62. package/src/config/schema.ts +13 -0
  63. package/src/config/validate.ts +16 -0
  64. package/src/conformance/kit.ts +22 -0
  65. package/src/conformance/limits.ts +10 -5
  66. package/src/conformance/probes.ts +149 -28
  67. package/src/conformance/served.ts +24 -4
  68. package/src/find/types.ts +86 -0
  69. package/src/find/validate.ts +101 -0
  70. package/src/guide/guide.ts +3 -1
  71. package/src/guide/limits.ts +9 -1
  72. package/src/host/create-host.ts +267 -4
  73. package/src/host/pass-on.ts +3 -2
  74. package/src/host/types.ts +52 -0
  75. package/src/index.ts +13 -0
  76. package/src/presets/presets.ts +15 -0
  77. package/src/react/frame.tsx +160 -1
  78. package/src/react/view.tsx +3 -0
  79. package/src/runtime/contract.ts +1 -1
  80. package/src/server/files.ts +8 -2
  81. package/src/server/server.ts +4 -1
  82. package/src/shell/annotate.ts +3 -95
  83. package/src/shell/document.ts +5 -3
  84. package/src/shell/find.ts +731 -0
  85. package/src/shell/plan.ts +7 -0
  86. package/src/shell/runtime.ts +792 -105
  87. package/src/shell/text.ts +140 -0
@@ -0,0 +1,731 @@
1
+ import { TEXT_INDEX } from "./text.ts";
2
+
3
+ /**
4
+ * The matches of a query in the document's text (P131), spliced into the find runtime: `text` is
5
+ * the text index's (`textIndex().text`), `query` the person's words. Case-insensitive unless
6
+ * `caseSensitive` (Unicode simple case folding, `u` and `i`, so a match keeps the text's own
7
+ * offsets), and loose about spacing as annotations' `squash` is: the query is trimmed, and each
8
+ * run of white space in it matches any run of white space in the text. Everything else is
9
+ * literal (no pattern syntax reaches the expression). Matches don't overlap, in document order.
10
+ *
11
+ * `keep(start, end)` says whether a match counts (the runtime: whether it has a box on screen,
12
+ * and its range), null if not; at most `most` are kept, and at most ten times that many are
13
+ * looked at (`capped`: it stopped there, and there may be more). The platform's own `RegExp`,
14
+ * its `exec` and `Reflect.apply` come in as taken before content ran, and so do the list the
15
+ * spans go in and how one is added (`list`, `push`: the shell's prototype-less `listOf` and
16
+ * `pushTo`); nothing else is called on a prototype content could replace (only indexing,
17
+ * comparisons and `length`).
18
+ */
19
+ export const FIND_MATCH = String.raw`(text, query, caseSensitive, most, keep, Pattern, exec, apply, list, push) => {
20
+ const SPACE = new Pattern("^\\s$", "u");
21
+ const SYNTAX = "\\^$.*+?()[]{}|/";
22
+ let source = "";
23
+ let space = false;
24
+ for (let i = 0; i < query.length; i += 1) {
25
+ const c = query[i];
26
+ if (apply(exec, SPACE, [c]) !== null) {
27
+ space = source !== "";
28
+ continue;
29
+ }
30
+ if (space) {
31
+ source += "\\s+";
32
+ space = false;
33
+ }
34
+ let special = false;
35
+ for (let j = 0; j < SYNTAX.length && !special; j += 1) {
36
+ special = SYNTAX[j] === c;
37
+ }
38
+ source += special ? "\\" + c : c;
39
+ }
40
+ const spans = list();
41
+ if (source === "") {
42
+ return { spans, capped: false };
43
+ }
44
+ const pattern = new Pattern(source, caseSensitive === true ? "gu" : "giu");
45
+ let looked = 0;
46
+ for (let found = apply(exec, pattern, [text]); found !== null; found = apply(exec, pattern, [text])) {
47
+ const start = found.index;
48
+ const end = start + found[0].length;
49
+ if (end === start) {
50
+ pattern.lastIndex = start + 1;
51
+ continue;
52
+ }
53
+ if (spans.length === most || looked === most * 10) {
54
+ return { spans, capped: true };
55
+ }
56
+ looked += 1;
57
+ const kept = keep(start, end);
58
+ if (kept !== null) {
59
+ push(spans, { start, end, kept });
60
+ }
61
+ }
62
+ return { spans, capped: false };
63
+ }`;
64
+
65
+ /**
66
+ * Whether a key is the find shortcut (P131), spliced into the find runtime: Cmd+F on Apple's
67
+ * platforms (`apple`), Ctrl+F elsewhere, with no Alt, no Shift and not the other of the two. The
68
+ * letter is `key`'s; on a layout whose letters aren't Latin (Cyrillic, Greek), the key in F's
69
+ * place (`code`), as browsers find there too. Comparisons only.
70
+ */
71
+ export const FIND_SHORTCUT = String.raw`(apple, key, code, meta, ctrl, alt, shift) => {
72
+ if (alt === true || shift === true || (apple ? !(meta === true && ctrl !== true) : !(ctrl === true && meta !== true))) {
73
+ return false;
74
+ }
75
+ if (key === "f" || key === "F") {
76
+ return true;
77
+ }
78
+ const latin = typeof key === "string" && key.length === 1 && ((key >= "a" && key <= "z") || (key >= "A" && key <= "Z"));
79
+ return !latin && code === "KeyF";
80
+ }`;
81
+
82
+ /**
83
+ * Only the latest query (P131), spliced into the find runtime: what the shell does with each
84
+ * query the host asks. A search is synchronous and, on a large page, long (hundreds of ms), so a
85
+ * bar that asks at every key builds a queue of messages behind it. A query that comes while none
86
+ * waits, and not within `quiet` ms of the end of the last one run, is run at once (answered
87
+ * before any content's listener could answer it). Otherwise it waits for the next task, after the
88
+ * messages already queued: a later query (or a clear, `drop`) supersedes it, and the one it
89
+ * superseded is answered `superseded(id)` at once (an error; the host makes it `"unsupported"`).
90
+ * So a burst is at most the query running and the latest, never each in turn.
91
+ *
92
+ * `later(run, wait)` and `time()` are the shell's kept timers and clock, `run(id, request)` runs
93
+ * and answers a query; `request` is what the runtime read from the host's message when it came
94
+ * (read once, never again). Comparisons and its own closures only.
95
+ */
96
+ export const FIND_LATEST = String.raw`(later, time, quiet, run, superseded) => {
97
+ let waiting = null;
98
+ let scheduled = false;
99
+ let ended = null;
100
+ const runNow = (id, request) => {
101
+ run(id, request);
102
+ ended = time();
103
+ };
104
+ const runWaiting = () => {
105
+ scheduled = false;
106
+ const next = waiting;
107
+ waiting = null;
108
+ if (next !== null) {
109
+ runNow(next.id, next.request);
110
+ }
111
+ };
112
+ return {
113
+ ask: (id, request) => {
114
+ if (waiting === null && !scheduled && (ended === null || time() - ended >= quiet)) {
115
+ runNow(id, request);
116
+ return;
117
+ }
118
+ if (waiting !== null) {
119
+ superseded(waiting.id);
120
+ }
121
+ waiting = { id, request };
122
+ if (!scheduled) {
123
+ scheduled = true;
124
+ later(runWaiting, 0);
125
+ }
126
+ },
127
+ drop: () => {
128
+ if (waiting !== null) {
129
+ const gone = waiting.id;
130
+ waiting = null;
131
+ superseded(gone);
132
+ }
133
+ },
134
+ };
135
+ }`;
136
+
137
+ /**
138
+ * The style of the shell's layers over the content (annotations' and find's): inline and
139
+ * important, so the content's own style sheets can't hide, shrink or move it by accident (its
140
+ * scripts can, P104). The annotation runtime carries the same text (a test holds them equal).
141
+ */
142
+ export const LAYER_STYLE =
143
+ "position:fixed!important;inset:0!important;width:auto!important;height:auto!important;min-width:0!important;min-height:0!important;max-width:none!important;max-height:none!important;display:block!important;visibility:visible!important;opacity:1!important;pointer-events:none!important;z-index:2147483647!important;overflow:hidden!important;margin:0!important;padding:0!important;border:0!important;background:none!important;transform:none!important;scale:none!important;translate:none!important;rotate:none!important;zoom:1!important;clip-path:none!important;mask:none!important;filter:none!important;content-visibility:visible!important;contain:none!important";
144
+
145
+ /**
146
+ * The shell's find in page (P131), spliced into the shell's runtime (`__FIND__`) when the config
147
+ * declares `find`, so it runs before any content does, with the DOM's own functions as they were.
148
+ * Plain ES2020 like the rest of the shell; no template literals (it sits in one).
149
+ *
150
+ * The host drives it (`porthole/find.query`, a request; `porthole/find.clear|handled`) and it
151
+ * says (`porthole/find.requested|updated`):
152
+ * - a query: its matches in the document's text (annotations' text index: the body's text nodes,
153
+ * without scripts, styles, noscript, templates), case-insensitive and loose about spacing,
154
+ * those with a box on screen, at most 1,000; each is drawn in a layer of the shell's own (a
155
+ * closed shadow root, over the content, as annotations' marks are; never the CSS Custom
156
+ * Highlight API, which content can read and rewrite: P053, P104), the current one apart, again
157
+ * at each scroll, resize and change of the content; the answer is how many and which, and the
158
+ * current one's box once it was scrolled into view (its scrolling ancestors first, then the
159
+ * window, centred); only the latest of a burst is searched, the ones it superseded answered
160
+ * with an error (`FIND_LATEST`);
161
+ * - a change of the content while a query is shown: found again once it settles (at most a
162
+ * second late), the current match kept by its place, and the host told when the count or the
163
+ * current one changed, at most once a second;
164
+ * - the shortcut: while the host says it draws its own find bar (`handled`), Cmd+F (Apple) or
165
+ * Ctrl+F (elsewhere) in the frame that the page didn't take itself (it called preventDefault)
166
+ * stops the browser's own find and is told (`requested`); otherwise the key is left alone.
167
+ *
168
+ * Every built-in it calls once content may have run is one it took before (the DOM's methods and
169
+ * getters, the timers, `postMessage`, `Map`, `RegExp`), called through the shell's `callOf`
170
+ * (P129); its lists are the shell's prototype-less ones, and what it reads from the host's message
171
+ * (the event's fields, the request's own properties) is read once and only as a string, a number
172
+ * or a boolean. The nodes of its layer go in only through the shell's guarded insertion methods
173
+ * (P130: `createElement`, `attachShadow`, `appendChild`, `replaceChildren`, the `textContent`
174
+ * setter, taken after the shell wrapped them), and it inserts nothing into the content's own
175
+ * trees.
176
+ *
177
+ * It shares the realm with the content, which can read the query, change what matches, hide the
178
+ * layer, keep the key from it or say `requested` itself: the host takes what it says as a find
179
+ * bar's numbers, never as facts.
180
+ */
181
+ export const FIND_RUNTIME = String.raw`if (declared("find")) {
182
+ (() => {
183
+ // quiet: a query this soon (ms) after the last search ended may have others queued behind it.
184
+ const LIMIT = { query: 256, matches: 1000, boxes: 50, drawn: 2000, quiet: 16 };
185
+ const M = {
186
+ query: "porthole/find.query",
187
+ clear: "porthole/find.clear",
188
+ handled: "porthole/find.handled",
189
+ requested: "porthole/find.requested",
190
+ updated: "porthole/find.updated",
191
+ };
192
+ // The DOM's own functions, taken before content runs and called only through callOf (P129).
193
+ // The insertion methods and createElement are the shell's guarded ones (P130), wrapped by
194
+ // step 3 before this runs: the layer's nodes go in the way any node does.
195
+ const setterOf = (proto, name) => {
196
+ const descriptor = proto ? Object.getOwnPropertyDescriptor(proto, name) : undefined;
197
+ return descriptor && typeof descriptor.set === "function" ? descriptor.set : null;
198
+ };
199
+ const createRange = Document.prototype.createRange;
200
+ const createTreeWalker = Document.prototype.createTreeWalker;
201
+ const createElement = Document.prototype.createElement;
202
+ const attachShadow = Element.prototype.attachShadow;
203
+ const setAttributeOn = Element.prototype.setAttribute;
204
+ const appendTo = Node.prototype.appendChild;
205
+ const parentElementOf = getterOf(Node.prototype, "parentElement");
206
+ const documentElementOf = getterOf(Document.prototype, "documentElement");
207
+ const bodyOf = getterOf(Document.prototype, "body");
208
+ const replaceIn = Element.prototype.replaceChildren;
209
+ const replaceInRoot = DocumentFragment.prototype.replaceChildren;
210
+ const textContentTo = setterOf(Node.prototype, "textContent");
211
+ const classNameTo = setterOf(Element.prototype, "className");
212
+ const nonceTo = setterOf(HTMLElement.prototype, "nonce");
213
+ const styleOf = getterOf(HTMLElement.prototype, "style");
214
+ const cssTextOf = getterOf(CSSStyleDeclaration.prototype, "cssText");
215
+ const cssTextTo = setterOf(CSSStyleDeclaration.prototype, "cssText");
216
+ const propertyValueIn = CSSStyleDeclaration.prototype.getPropertyValue;
217
+ const rangeRect = Range.prototype.getBoundingClientRect;
218
+ const rangeRects = Range.prototype.getClientRects;
219
+ // A range's boundary getters are AbstractRange's where an engine has it.
220
+ const startContainerOf = getterOf(typeof AbstractRange === "function" ? AbstractRange.prototype : Range.prototype, "startContainer");
221
+ const elementRect = Element.prototype.getBoundingClientRect;
222
+ const listLength = getterOf(typeof DOMRectList === "function" ? DOMRectList.prototype : null, "length");
223
+ const listItem = typeof DOMRectList === "function" ? DOMRectList.prototype.item : null;
224
+ const itemOf = (list, i) => (listItem === null ? list[i] : callOf(listItem, list, [i]));
225
+ const leftOf = getterOf(DOMRectReadOnly.prototype, "left");
226
+ const topOf = getterOf(DOMRectReadOnly.prototype, "top");
227
+ const widthOf = getterOf(DOMRectReadOnly.prototype, "width");
228
+ const heightOf = getterOf(DOMRectReadOnly.prototype, "height");
229
+ const clientWidthOf = getterOf(Element.prototype, "clientWidth");
230
+ const clientHeightOf = getterOf(Element.prototype, "clientHeight");
231
+ const clientTopOf = getterOf(Element.prototype, "clientTop");
232
+ const clientLeftOf = getterOf(Element.prototype, "clientLeft");
233
+ const scrollWidthOf = getterOf(Element.prototype, "scrollWidth");
234
+ const scrollHeightOf = getterOf(Element.prototype, "scrollHeight");
235
+ const computedOf = window.getComputedStyle;
236
+ const scrollWindow = window.scrollBy;
237
+ const scrollElement = Element.prototype.scrollBy;
238
+ const Pattern = RegExp;
239
+ const execOf = RegExp.prototype.exec;
240
+ const BLANK = /^\s*$/u;
241
+ const keyOf = getterOf(typeof KeyboardEvent === "function" ? KeyboardEvent.prototype : null, "key");
242
+ const codeOf = getterOf(typeof KeyboardEvent === "function" ? KeyboardEvent.prototype : null, "code");
243
+ const metaOf = getterOf(typeof KeyboardEvent === "function" ? KeyboardEvent.prototype : null, "metaKey");
244
+ const ctrlOf = getterOf(typeof KeyboardEvent === "function" ? KeyboardEvent.prototype : null, "ctrlKey");
245
+ const altOf = getterOf(typeof KeyboardEvent === "function" ? KeyboardEvent.prototype : null, "altKey");
246
+ const shiftOf = getterOf(typeof KeyboardEvent === "function" ? KeyboardEvent.prototype : null, "shiftKey");
247
+ const preventedOf = getterOf(Event.prototype, "defaultPrevented");
248
+ const messageDataOf = getterOf(MessageEvent.prototype, "data");
249
+ const messageOriginOf = getterOf(MessageEvent.prototype, "origin");
250
+ const messageSourceOf = getterOf(MessageEvent.prototype, "source");
251
+ const removedNodesOf = getterOf(recordProto, "removedNodes");
252
+ // The platform's preventDefault, kept before a tab's shell locks its own over it (P099).
253
+ const stopFind = preventNavigation;
254
+ const timeoutIn = window.setTimeout;
255
+ const clearTimeoutIn = window.clearTimeout;
256
+ const animationFrameIn = window.requestAnimationFrame;
257
+ const later = (run, wait) => callOf(timeoutIn, window, [run, wait]);
258
+ const cancelLater = (timer) => callOf(clearTimeoutIn, window, [timer]);
259
+ const nextFrame = (run) => callOf(animationFrameIn, window, [run]);
260
+ const clock = Date.now;
261
+ const time = () => callOf(clock, Date, []);
262
+ // Read once: content can replace window.parent (it is [Replaceable]), never what was read.
263
+ const parentWindow = window.parent;
264
+ const framed = parentWindow !== window;
265
+ const postIn = parentWindow.postMessage;
266
+ const post = (message) => callOf(postIn, parentWindow, [message, "*"]);
267
+ // Whose shortcut it is: Cmd on Apple's platforms, Ctrl elsewhere (read before content runs).
268
+ const apple = callOf(execOf, /Mac|iPhone|iPad|iPod/, [NativeString(navigator.platform || "")]) !== null;
269
+ const tell = (method, params) => {
270
+ if (framed) {
271
+ post({ jsonrpc: "2.0", method, params });
272
+ }
273
+ };
274
+ // kind is "result" or "error": a literal's own property, never one set through a prototype.
275
+ const answer = (id, kind, body) => {
276
+ if (framed) {
277
+ post({ jsonrpc: "2.0", id, [kind]: body });
278
+ }
279
+ };
280
+ // Through the platform's getter, taken now; where an engine has none there, as the object says.
281
+ const get = (getter, target, name) => (getter === null ? target[name] : callOf(getter, target, []));
282
+ // A box's number, read once: only a number is used.
283
+ const numberOf = (value) => (typeof value === "number" ? value : 0);
284
+ const lesser = (a, b) => (a < b ? a : b);
285
+ const greater = (a, b) => (a > b ? a : b);
286
+ const boxOf = (rect) => ({ x: numberOf(get(leftOf, rect, "left")), y: numberOf(get(topOf, rect, "top")), width: numberOf(get(widthOf, rect, "width")), height: numberOf(get(heightOf, rect, "height")) });
287
+ // A range's boxes (its lines), at most LIMIT.boxes; those of no size left out.
288
+ const boxesOf = (range) => {
289
+ const list = callOf(rangeRects, range, []);
290
+ const count = lesser(numberOf(get(listLength, list, "length")), LIMIT.boxes);
291
+ const out = listOf();
292
+ for (let i = 0; i < count; i += 1) {
293
+ const each = boxOf(itemOf(list, i));
294
+ if (each.width > 0 || each.height > 0) {
295
+ pushTo(out, each);
296
+ }
297
+ }
298
+ return out;
299
+ };
300
+ const rootElement = () => (documentElementOf === null ? document.documentElement : callOf(documentElementOf, document, []));
301
+ const bodyElement = () => (bodyOf === null ? document.body : callOf(bodyOf, document, []));
302
+ const viewport = () => {
303
+ const root = rootElement();
304
+ return { width: numberOf(get(clientWidthOf, root, "clientWidth")), height: numberOf(get(clientHeightOf, root, "clientHeight")) };
305
+ };
306
+ // An own property of what the host sent, read once (a structured clone's own data property),
307
+ // never one from a prototype content could fill.
308
+ const own = (object, name) => (object !== null && typeof object === "object" && callOf(hasOwn, object, [name]) ? object[name] : undefined);
309
+
310
+ ${TEXT_INDEX}
311
+ const findMatches = ${FIND_MATCH};
312
+ const isShortcut = ${FIND_SHORTCUT};
313
+ const keepLatest = ${FIND_LATEST};
314
+
315
+ // The shell's own layer, over the content, apart from annotations' (P053): a match is a
316
+ // light warm fill with a thin edge, the current one stronger with a ring, so both read on a
317
+ // light page and a dark one and neither looks like a comment's mark (yellow, underlined).
318
+ const STYLE = ".hit{position:absolute;border-radius:2px;background:rgba(255,159,10,.28);box-shadow:inset 0 0 0 1px rgba(217,119,6,.5)}.hit.current{background:rgba(255,120,0,.5);box-shadow:0 0 0 2px rgb(234,88,12)}";
319
+ const LAYER_STYLE = "${LAYER_STYLE}";
320
+ // An element's inline style, through the kept getter and setter (CSSOM, which a CSP's
321
+ // style-src doesn't govern, unlike a style attribute).
322
+ const styleText = (element) => get(cssTextOf, get(styleOf, element, "style"), "cssText");
323
+ const setStyle = (element, text) => {
324
+ const style = get(styleOf, element, "style");
325
+ if (cssTextTo === null) {
326
+ style.cssText = text;
327
+ } else {
328
+ callOf(cssTextTo, style, [text]);
329
+ }
330
+ };
331
+ let layer = null;
332
+ let shadow = null;
333
+ let parts = null;
334
+ const ensureLayer = () => {
335
+ if (layer === null) {
336
+ layer = callOf(createElement, document, ["div"]);
337
+ callOf(setAttributeOn, layer, ["aria-hidden", "true"]);
338
+ callOf(setAttributeOn, layer, ["data-porthole-find", ""]);
339
+ shadow = callOf(attachShadow, layer, [{ mode: "closed" }]);
340
+ const style = callOf(createElement, document, ["style"]);
341
+ if (nonce !== "") {
342
+ if (nonceTo === null) {
343
+ callOf(setAttributeOn, style, ["nonce", nonce]);
344
+ } else {
345
+ callOf(nonceTo, style, [nonce]);
346
+ }
347
+ }
348
+ if (textContentTo === null) {
349
+ style.textContent = STYLE;
350
+ } else {
351
+ callOf(textContentTo, style, [STYLE]);
352
+ }
353
+ parts = callOf(createElement, document, ["div"]);
354
+ callOf(replaceInRoot, shadow, [style, parts]);
355
+ }
356
+ if (styleText(layer) !== LAYER_STYLE) {
357
+ setStyle(layer, LAYER_STYLE);
358
+ }
359
+ if (!connected(layer)) {
360
+ callOf(appendTo, rootElement(), [layer]);
361
+ }
362
+ };
363
+
364
+ // What is shown: the query, its matches ({ start, end, range }), the current one (from 1).
365
+ let shown = null;
366
+ let matches = listOf();
367
+ let capped = false;
368
+ let active = 0;
369
+ // Whether the host draws its own find bar: then the shortcut is the host's.
370
+ let handled = false;
371
+
372
+ const draw = () => {
373
+ if (matches.length === 0) {
374
+ if (parts !== null) {
375
+ callOf(replaceIn, parts, []);
376
+ }
377
+ return;
378
+ }
379
+ ensureLayer();
380
+ const seen = viewport();
381
+ // The others first, then the current match, so it is drawn over them.
382
+ const drawn = listOf();
383
+ const current = listOf();
384
+ for (let i = 0; i < matches.length && drawn.length < LIMIT.drawn; i += 1) {
385
+ const outer = boxOf(callOf(rangeRect, matches[i].range, []));
386
+ // Only what is in view is drawn; the rest again as it comes into view.
387
+ if (outer.y + outer.height < 0 || outer.y > seen.height || outer.x + outer.width < 0 || outer.x > seen.width) {
388
+ continue;
389
+ }
390
+ const mine = i + 1 === active;
391
+ const rects = boxesOf(matches[i].range);
392
+ for (let j = 0; j < rects.length; j += 1) {
393
+ const rect = rects[j];
394
+ const each = callOf(createElement, document, ["div"]);
395
+ if (classNameTo === null) {
396
+ callOf(setAttributeOn, each, ["class", mine ? "hit current" : "hit"]);
397
+ } else {
398
+ callOf(classNameTo, each, [mine ? "hit current" : "hit"]);
399
+ }
400
+ setStyle(each, "left:" + rect.x + "px;top:" + rect.y + "px;width:" + rect.width + "px;height:" + rect.height + "px");
401
+ pushTo(mine ? current : drawn, each);
402
+ }
403
+ }
404
+ for (let i = 0; i < current.length; i += 1) {
405
+ pushTo(drawn, current[i]);
406
+ }
407
+ callOf(replaceIn, parts, drawn);
408
+ };
409
+ let drawing = false;
410
+ const redraw = () => {
411
+ if (!drawing && matches.length > 0) {
412
+ drawing = true;
413
+ nextFrame(() => {
414
+ drawing = false;
415
+ draw();
416
+ });
417
+ }
418
+ };
419
+ window.addEventListener("resize", redraw);
420
+ window.addEventListener("scroll", redraw, true);
421
+
422
+ // Every match of the query shown, found again: those with a box (text that is drawn).
423
+ const search = () => {
424
+ const index = textIndex();
425
+ const found = findMatches(index.text, shown.query, shown.caseSensitive, LIMIT.matches, (start, end) => {
426
+ const range = rangeAt(index, start, end);
427
+ return range !== null && boxesOf(range).length > 0 ? range : null;
428
+ }, Pattern, execOf, callOf, listOf, pushTo);
429
+ const next = listOf();
430
+ for (let i = 0; i < found.spans.length; i += 1) {
431
+ const each = found.spans[i];
432
+ pushTo(next, { start: each.start, end: each.end, range: each.kept });
433
+ }
434
+ matches = next;
435
+ capped = found.capped;
436
+ };
437
+ // The first match at or after where the person is reading (the viewport's top), 0-based.
438
+ const firstInView = () => {
439
+ for (let i = 0; i < matches.length; i += 1) {
440
+ const outer = boxOf(callOf(rangeRect, matches[i].range, []));
441
+ if (outer.y + outer.height > 0) {
442
+ return i;
443
+ }
444
+ }
445
+ return 0;
446
+ };
447
+ // The current match after the matches were found again: by its place, moved as asked.
448
+ const choose = (before, direction) => {
449
+ const count = matches.length;
450
+ if (count === 0) {
451
+ return 0;
452
+ }
453
+ if (before < 0) {
454
+ const first = firstInView();
455
+ return direction === "prev" ? ((first - 1 + count) % count) + 1 : first + 1;
456
+ }
457
+ let at = 0;
458
+ while (at < count && matches[at].start < before) {
459
+ at += 1;
460
+ }
461
+ if (direction === "next") {
462
+ return ((at < count && matches[at].start === before ? at + 1 : at) % count) + 1;
463
+ }
464
+ if (direction === "prev") {
465
+ return ((at - 1 + count) % count) + 1;
466
+ }
467
+ return (at < count ? at : count - 1) + 1;
468
+ };
469
+ // Into view, centred where it is out of it: each scrolling ancestor, innermost first, then
470
+ // the window. Instantly (a page's smooth scrolling would leave it where it was measured).
471
+ const scrollBy = (scroll, target, dx, dy) => {
472
+ try {
473
+ callOf(scroll, target, [{ left: dx, top: dy, behavior: "instant" }]);
474
+ } catch (_) {
475
+ try {
476
+ callOf(scroll, target, [dx, dy]);
477
+ } catch (_) {}
478
+ }
479
+ };
480
+ const SCROLLS = bare(null);
481
+ SCROLLS.auto = 1;
482
+ SCROLLS.scroll = 1;
483
+ SCROLLS.overlay = 1;
484
+ const centre = (from, size, start, length) => (from < start || from + size > start + length ? from - start - (length - lesser(size, length)) / 2 : 0);
485
+ const reveal = (range) => {
486
+ let node = get(startContainerOf, range, "startContainer");
487
+ if (node !== null && typeOf(node) !== 1) {
488
+ node = get(parentElementOf, node, "parentElement");
489
+ }
490
+ const body = bodyElement();
491
+ const root = rootElement();
492
+ for (let hops = 0; node !== null && node !== body && node !== root && hops < 64; hops += 1) {
493
+ const style = callOf(computedOf, window, [node]);
494
+ const down = SCROLLS[callOf(propertyValueIn, style, ["overflow-y"])] === 1 && numberOf(get(scrollHeightOf, node, "scrollHeight")) > numberOf(get(clientHeightOf, node, "clientHeight"));
495
+ const across = SCROLLS[callOf(propertyValueIn, style, ["overflow-x"])] === 1 && numberOf(get(scrollWidthOf, node, "scrollWidth")) > numberOf(get(clientWidthOf, node, "clientWidth"));
496
+ if (down || across) {
497
+ const outer = boxOf(callOf(elementRect, node, []));
498
+ const at = boxOf(callOf(rangeRect, range, []));
499
+ const dy = down ? centre(at.y, at.height, outer.y + numberOf(get(clientTopOf, node, "clientTop")), numberOf(get(clientHeightOf, node, "clientHeight"))) : 0;
500
+ const dx = across ? centre(at.x, at.width, outer.x + numberOf(get(clientLeftOf, node, "clientLeft")), numberOf(get(clientWidthOf, node, "clientWidth"))) : 0;
501
+ if (dx !== 0 || dy !== 0) {
502
+ scrollBy(scrollElement, node, dx, dy);
503
+ }
504
+ }
505
+ node = get(parentElementOf, node, "parentElement");
506
+ }
507
+ const seen = viewport();
508
+ const at = boxOf(callOf(rangeRect, range, []));
509
+ const dy = centre(at.y, at.height, 0, seen.height);
510
+ const dx = centre(at.x, at.width, 0, seen.width);
511
+ if (dx !== 0 || dy !== 0) {
512
+ scrollBy(scrollWindow, window, dx, dy);
513
+ }
514
+ };
515
+ // An object with no prototype, so no property set on it reaches a setter content put on
516
+ // Object.prototype; the host gets it as a plain object.
517
+ const resultOf = (withBox) => {
518
+ const result = bare(null);
519
+ result.total = matches.length;
520
+ result.active = active;
521
+ if (capped) {
522
+ result.capped = true;
523
+ }
524
+ if (withBox && active > 0) {
525
+ result.rect = boxOf(callOf(rangeRect, matches[active - 1].range, []));
526
+ }
527
+ return result;
528
+ };
529
+
530
+ // Told: the numbers the host last had (an answer or an update), so a change of the content
531
+ // that moves nothing tells nothing; at most one update a second, the latest.
532
+ let told = "";
533
+ let toldAt = 0;
534
+ let tellTimer = 0;
535
+ const keyOfResult = () => matches.length + ":" + active + ":" + capped;
536
+ const tellUpdated = () => {
537
+ if (shown === null || keyOfResult() === told) {
538
+ return;
539
+ }
540
+ const wait = toldAt + 1000 - time();
541
+ if (wait > 0) {
542
+ if (tellTimer === 0) {
543
+ tellTimer = later(() => {
544
+ tellTimer = 0;
545
+ tellUpdated();
546
+ }, wait);
547
+ }
548
+ return;
549
+ }
550
+ told = keyOfResult();
551
+ toldAt = time();
552
+ tell(M.updated, resultOf(false));
553
+ };
554
+
555
+ // Found again once a run of changes settles (150 ms quiet), at most a second late.
556
+ let searchTimer = 0;
557
+ let deadline = 0;
558
+ const again = () => {
559
+ searchTimer = 0;
560
+ deadline = 0;
561
+ if (shown === null) {
562
+ return;
563
+ }
564
+ const before = active > 0 ? matches[active - 1].start : -1;
565
+ search();
566
+ active = choose(before, "none");
567
+ draw();
568
+ tellUpdated();
569
+ };
570
+ const scheduleSearch = () => {
571
+ const now = time();
572
+ if (deadline === 0) {
573
+ deadline = now + 1000;
574
+ }
575
+ cancelLater(searchTimer);
576
+ searchTimer = later(again, greater(0, lesser(150, deadline - now)));
577
+ };
578
+ // The layer's own changes are none of the content's: a record of the layer, or one that only
579
+ // adds or removes it, is passed over. Read through the kept getters.
580
+ const ownChange = (record) => {
581
+ if (get(recordTargetOf, record, "target") === layer) {
582
+ return true;
583
+ }
584
+ const added = get(addedNodesOf, record, "addedNodes");
585
+ const removed = get(removedNodesOf, record, "removedNodes");
586
+ const addedCount = countOf(added);
587
+ const removedCount = countOf(removed);
588
+ return addedCount + removedCount === 1 && (addedCount === 1 ? added[0] === layer : removed[0] === layer);
589
+ };
590
+ const contentWatch = new MutationObserver((records) => {
591
+ if (shown === null) {
592
+ return;
593
+ }
594
+ for (let i = 0; i < records.length; i += 1) {
595
+ if (ownChange(records[i])) {
596
+ continue;
597
+ }
598
+ scheduleSearch();
599
+ return;
600
+ }
601
+ });
602
+ callOf(observeIn, contentWatch, [document, { childList: true, subtree: true, characterData: true }]);
603
+
604
+ const clear = () => {
605
+ shown = null;
606
+ matches = listOf();
607
+ capped = false;
608
+ active = 0;
609
+ told = "";
610
+ cancelLater(searchTimer);
611
+ searchTimer = 0;
612
+ deadline = 0;
613
+ cancelLater(tellTimer);
614
+ tellTimer = 0;
615
+ draw();
616
+ };
617
+ // What the host asked, read when its message comes: each of the request's fields once, as
618
+ // its own property; only a string is a query. Kept as these values (a query that waits is
619
+ // never read from the message again).
620
+ const requestOf = (params) => {
621
+ const asked = own(params, "query");
622
+ const askedCase = own(params, "caseSensitive");
623
+ const askedDirection = own(params, "direction");
624
+ return {
625
+ words: typeof asked === "string" ? callOf(sliceOf, asked, [0, LIMIT.query]) : "",
626
+ caseSensitive: askedCase === true,
627
+ direction: askedDirection === "next" || askedDirection === "prev" ? askedDirection : "none",
628
+ };
629
+ };
630
+ // A query: its matches found (again, for the same words), the current one chosen, brought
631
+ // into view when it moved or isn't in view, and drawn; answered with where they stand.
632
+ const query = (request) => {
633
+ const words = request.words;
634
+ const caseSensitive = request.caseSensitive;
635
+ const direction = request.direction;
636
+ // No words at all clears: nothing drawn, nothing followed.
637
+ if (callOf(execOf, BLANK, [words]) !== null) {
638
+ clear();
639
+ return { total: 0, active: 0 };
640
+ }
641
+ const same = shown !== null && shown.query === words && shown.caseSensitive === caseSensitive;
642
+ const before = same && active > 0 ? matches[active - 1].start : -1;
643
+ shown = { query: words, caseSensitive };
644
+ search();
645
+ active = choose(before, direction);
646
+ // Brought into view after a move or for a new query (one already in view stays where it is).
647
+ if (active > 0 && (direction !== "none" || !same)) {
648
+ reveal(matches[active - 1].range);
649
+ }
650
+ draw();
651
+ told = keyOfResult();
652
+ return resultOf(true);
653
+ };
654
+ // Only the latest query: one the person moved past before it ran is answered as superseded
655
+ // (an error the host makes "unsupported"), never searched (FIND_LATEST).
656
+ const latest = keepLatest(
657
+ later,
658
+ time,
659
+ LIMIT.quiet,
660
+ (id, request) => {
661
+ try {
662
+ answer(id, "result", query(request));
663
+ } catch (_) {
664
+ answer(id, "error", { code: -32603, message: "find failed" });
665
+ }
666
+ },
667
+ (id) => answer(id, "error", { code: -32800, message: "superseded by a later query" }),
668
+ );
669
+
670
+ // The shortcut, after the page's own listeners (on the window, as the event bubbles): one
671
+ // the page took (preventDefault) is the page's own find. Read through the platform's
672
+ // getters, kept now; a key the page makes up (isTrusted is false) is none.
673
+ window.addEventListener("keydown", (event) => {
674
+ if (!handled || !event.isTrusted || get(preventedOf, event, "defaultPrevented") === true) {
675
+ return;
676
+ }
677
+ if (!isShortcut(apple, get(keyOf, event, "key"), get(codeOf, event, "code"), get(metaOf, event, "metaKey"), get(ctrlOf, event, "ctrlKey"), get(altOf, event, "altKey"), get(shiftOf, event, "shiftKey"))) {
678
+ return;
679
+ }
680
+ callOf(stopFind, event, []);
681
+ tell(M.requested, {});
682
+ });
683
+
684
+ // Only the plan's origins: an indexed loop over the plan's own list.
685
+ const fromHost = (origin) => {
686
+ for (let i = 0; i < plan.origins.length; i += 1) {
687
+ if (plan.origins[i] === origin) {
688
+ return true;
689
+ }
690
+ }
691
+ return false;
692
+ };
693
+ window.addEventListener("message", (event) => {
694
+ // The event's fields, each read once through the kept getters.
695
+ if (get(messageSourceOf, event, "source") !== parentWindow || !fromHost(get(messageOriginOf, event, "origin"))) {
696
+ return;
697
+ }
698
+ const data = get(messageDataOf, event, "data");
699
+ if (data === null || typeof data !== "object" || own(data, "jsonrpc") !== "2.0") {
700
+ return;
701
+ }
702
+ const method = own(data, "method");
703
+ if (typeof method !== "string") {
704
+ return;
705
+ }
706
+ const sent = own(data, "params");
707
+ const params = sent !== null && typeof sent === "object" ? sent : bare(null);
708
+ switch (method) {
709
+ case M.query: {
710
+ // A request: read now; answered at once, before any content's listener could answer
711
+ // it, unless a burst of queries is queued behind a long search (then the latest only).
712
+ const id = own(data, "id");
713
+ if (typeof id !== "string" && typeof id !== "number") {
714
+ return;
715
+ }
716
+ latest.ask(id, requestOf(params));
717
+ break;
718
+ }
719
+ case M.clear:
720
+ latest.drop();
721
+ clear();
722
+ break;
723
+ case M.handled:
724
+ handled = own(params, "handled") === true;
725
+ break;
726
+ default:
727
+ break;
728
+ }
729
+ });
730
+ })();
731
+ }`;