@botiverse/porthole 0.14.8 → 0.14.10

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 (60) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/annotate/types.d.ts +33 -2
  3. package/dist/annotate/validate.d.ts +6 -1
  4. package/dist/annotate/validate.js +31 -3
  5. package/dist/bridge/bridge.d.ts +6 -0
  6. package/dist/bridge/bridge.js +5 -0
  7. package/dist/check/page-source.js +1 -1
  8. package/dist/config/capabilities.d.ts +16 -2
  9. package/dist/config/capabilities.js +8 -0
  10. package/dist/conformance/harness-source.js +1 -1
  11. package/dist/find/types.d.ts +83 -0
  12. package/dist/find/types.js +29 -0
  13. package/dist/find/validate.d.ts +17 -0
  14. package/dist/find/validate.js +82 -0
  15. package/dist/guide/guide.js +2 -1
  16. package/dist/host/create-host.js +219 -3
  17. package/dist/host/pass-on.js +3 -2
  18. package/dist/host/types.d.ts +54 -1
  19. package/dist/index.d.ts +5 -3
  20. package/dist/index.js +4 -1
  21. package/dist/react/frame.d.ts +45 -1
  22. package/dist/react/frame.js +107 -3
  23. package/dist/react/view.js +2 -0
  24. package/dist/runtime/contract.d.ts +1 -1
  25. package/dist/runtime/contract.js +1 -1
  26. package/dist/shell/annotate.d.ts +5 -1
  27. package/dist/shell/annotate.js +41 -107
  28. package/dist/shell/document.d.ts +3 -3
  29. package/dist/shell/document.js +5 -3
  30. package/dist/shell/find.d.ts +82 -0
  31. package/dist/shell/find.js +725 -0
  32. package/dist/shell/runtime.js +4 -1
  33. package/dist/shell/text.d.ts +17 -0
  34. package/dist/shell/text.js +140 -0
  35. package/docs/ADOPTING.md +112 -0
  36. package/docs/ARCHITECTURE.md +10 -3
  37. package/docs/DECISIONS.md +284 -1
  38. package/docs/DESIGN.md +48 -2
  39. package/docs/THREAT_MODEL.md +61 -5
  40. package/docs/insertion-entry-points.md +17 -0
  41. package/package.json +1 -1
  42. package/src/annotate/types.ts +43 -4
  43. package/src/annotate/validate.ts +34 -3
  44. package/src/bridge/bridge.ts +7 -0
  45. package/src/config/capabilities.ts +13 -1
  46. package/src/find/types.ts +86 -0
  47. package/src/find/validate.ts +101 -0
  48. package/src/guide/guide.ts +3 -1
  49. package/src/host/create-host.ts +235 -3
  50. package/src/host/pass-on.ts +3 -2
  51. package/src/host/types.ts +55 -1
  52. package/src/index.ts +14 -1
  53. package/src/react/frame.tsx +162 -2
  54. package/src/react/view.tsx +3 -0
  55. package/src/runtime/contract.ts +1 -1
  56. package/src/shell/annotate.ts +42 -107
  57. package/src/shell/document.ts +5 -3
  58. package/src/shell/find.ts +731 -0
  59. package/src/shell/runtime.ts +4 -1
  60. package/src/shell/text.ts +140 -0
@@ -0,0 +1,101 @@
1
+ import { parseRect } from "../annotate/validate.ts";
2
+ import {
3
+ FIND_LIMITS as LIMITS,
4
+ type FindDirection,
5
+ type FindOptions,
6
+ type FindReport,
7
+ type FindResult,
8
+ } from "./types.ts";
9
+
10
+ /**
11
+ * The host's checks on find in page (P131): what it sends (a query and its options) and what a
12
+ * frame says back. A frame's word is rebuilt from known fields only, within `FIND_LIMITS`, and is
13
+ * null for anything else: dropped whole, never repaired.
14
+ */
15
+
16
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
17
+ value !== null && typeof value === "object" && !Array.isArray(value);
18
+
19
+ const whole = (value: unknown, max: number): value is number =>
20
+ typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max;
21
+
22
+ /** An answer to `porthole/find.query`, or an `updated`'s numbers; null if malformed. */
23
+ export function parseFindResult(value: unknown): FindResult | null {
24
+ if (!isRecord(value)) {
25
+ return null;
26
+ }
27
+ const { total, active, capped, rect } = value;
28
+ if (!whole(total, LIMITS.matches) || !whole(active, total)) {
29
+ return null;
30
+ }
31
+ if ((total === 0) !== (active === 0)) {
32
+ return null;
33
+ }
34
+ if (capped !== undefined && capped !== true && capped !== false) {
35
+ return null;
36
+ }
37
+ // Capped only at the limit: fewer matches were all of them.
38
+ if (capped === true && total !== LIMITS.matches) {
39
+ return null;
40
+ }
41
+ const box = rect === undefined || active === 0 ? undefined : parseRect(rect);
42
+ if (box === null) {
43
+ return null;
44
+ }
45
+ return {
46
+ total,
47
+ active,
48
+ ...(capped === true ? { capped: true as const } : {}),
49
+ ...(box === undefined ? {} : { rect: box }),
50
+ };
51
+ }
52
+
53
+ /** A report from the frame, checked; null if malformed (it is then dropped). */
54
+ export function parseFindReport(value: unknown): FindReport | null {
55
+ if (!isRecord(value)) {
56
+ return null;
57
+ }
58
+ switch (value.type) {
59
+ case "requested":
60
+ return { type: "requested" };
61
+ case "updated": {
62
+ // No box: where the current match is goes only with an answer to the host's own query.
63
+ const { rect: _rect, ...numbers } = value;
64
+ const result = parseFindResult(numbers);
65
+ return result === null ? null : { type: "updated", ...result };
66
+ }
67
+ default:
68
+ return null;
69
+ }
70
+ }
71
+
72
+ const DIRECTIONS: readonly FindDirection[] = ["next", "prev", "none"];
73
+
74
+ /**
75
+ * A query and its options as the host gives them, checked before they go to the frame; throws a
76
+ * `TypeError` for a query that isn't text, is longer than `FIND_LIMITS.query`, or options that
77
+ * aren't these. The query goes as it is (the shell trims it and loosens its spacing).
78
+ */
79
+ export function checkFindQuery(
80
+ query: unknown,
81
+ options: FindOptions | undefined,
82
+ ): { query: string; direction: FindDirection; caseSensitive: boolean } {
83
+ if (typeof query !== "string" || query.length > LIMITS.query) {
84
+ throw new TypeError(`find.query: the query is text, at most ${LIMITS.query} characters`);
85
+ }
86
+ if (options !== undefined && !isRecord(options)) {
87
+ throw new TypeError("find.query: options are { direction?, caseSensitive? }");
88
+ }
89
+ const direction: unknown = options?.direction ?? "none";
90
+ if (!(DIRECTIONS as readonly unknown[]).includes(direction)) {
91
+ throw new TypeError('find.query: direction is "next", "prev" or "none"');
92
+ }
93
+ const caseSensitive: unknown = options?.caseSensitive ?? false;
94
+ if (typeof caseSensitive !== "boolean") {
95
+ throw new TypeError("find.query: caseSensitive is true or false");
96
+ }
97
+ return { query, direction: direction as FindDirection, caseSensitive };
98
+ }
99
+
100
+ /** Whether a query finds nothing by its words alone: empty, or only spaces (it clears). */
101
+ export const blankQuery = (query: string): boolean => query.trim() === "";
@@ -444,6 +444,8 @@ const ENTRIES: { readonly [N in CapabilityName]: (c: Context, gates: readonly Ga
444
444
  : `- Copying: the request porthole/copy-text with { text } (at most ${MAX_COPY_CHARS.toLocaleString("en-US")} characters) copies text to the person's clipboard, and the app shows them what was copied; nothing else in the ${c.noun} can write the clipboard. ${gateWords(gates, "the text")}`,
445
445
  annotate: (c) =>
446
446
  `- Comments: the person may point at parts of the ${c.noun} to comment on them. Give headings and the parts that matter stable ids (id="revenue"), so comments stay on them when the ${c.noun} is written again.`,
447
+ find: (c) =>
448
+ `- Find: the person may search the ${c.noun}'s words with the app's own find bar (Cmd+F or Ctrl+F), which highlights them where they are. Keep the words they would look for as text (not in images or a canvas). A ${c.noun} that handles Cmd+F or Ctrl+F itself (preventDefault) keeps the key.`,
447
449
  reportError: (c) =>
448
450
  `- ${manualLimits(c.config, "").find((limit) => limit.id === "errors")?.text ?? ""}`,
449
451
  resize: () => "",
@@ -456,7 +458,7 @@ const ENTRIES: { readonly [N in CapabilityName]: (c: Context, gates: readonly Ga
456
458
  };
457
459
 
458
460
  /** The shell's own capabilities, which content never calls by name: taught as they are. */
459
- const SHELL_OWN: readonly CapabilityName[] = ["annotate", "reportError", "resize"];
461
+ const SHELL_OWN: readonly CapabilityName[] = ["annotate", "find", "reportError", "resize"];
460
462
 
461
463
  function interactive(c: Context): string {
462
464
  const { config, noun } = c;
@@ -11,6 +11,8 @@ import {
11
11
  hasMarker,
12
12
  parseReport,
13
13
  } from "../annotate/validate.ts";
14
+ import { FIND_LIMITS, FIND_METHODS, type FindReport, type FindResult } from "../find/types.ts";
15
+ import { blankQuery, checkFindQuery, parseFindReport, parseFindResult } from "../find/validate.ts";
14
16
  import {
15
17
  createBridge,
16
18
  onceConsent,
@@ -46,6 +48,7 @@ import { checkDeclaration } from "../runtime/declaration.ts";
46
48
  import { parseViewer } from "../runtime/levels.ts";
47
49
  import type {
48
50
  AnnotationControls,
51
+ FindControls,
49
52
  HostErrorKind,
50
53
  DisplayEvents,
51
54
  DisplayHandle,
@@ -88,6 +91,12 @@ const REPORTS: Readonly<Record<string, AnnotationReport["type"]>> = {
88
91
  [ANNOTATE_METHODS.tracked]: "tracked",
89
92
  };
90
93
 
94
+ /** What the frame says of find in page unasked (P131), by method. */
95
+ const FIND_REPORTS: Readonly<Record<string, FindReport["type"]>> = {
96
+ [FIND_METHODS.requested]: "requested",
97
+ [FIND_METHODS.updated]: "updated",
98
+ };
99
+
91
100
  /** The most `tracked` reports a second the host takes (P112): one per animation frame at 60 Hz. */
92
101
  export const TRACKED_PER_SECOND = 60;
93
102
 
@@ -228,6 +237,21 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
228
237
  // The mark the host follows (P112), and when it took each `tracked` in the last second.
229
238
  let tracking: string | null = null;
230
239
  const trackedTimes: number[] = [];
240
+ // Find in page (P131): the query shown (for the content it was asked of only: a new run or
241
+ // other content forgets it), whether the host takes the shortcut (kept for every frame the
242
+ // display runs), and the queries asked and not yet answered.
243
+ const finds = config.capabilities.find !== undefined;
244
+ let findShown: { readonly query: string; readonly caseSensitive: boolean } | null = null;
245
+ let takesShortcut = false;
246
+ let nextFind = 1;
247
+ const findsAsked = new Map<
248
+ string,
249
+ {
250
+ readonly params: Record<string, unknown>;
251
+ readonly resolve: (result: FindResult | "unsupported") => void;
252
+ timer: ReturnType<typeof setTimeout>;
253
+ }
254
+ >();
231
255
  let handshaken = false;
232
256
  let storageTold = false;
233
257
  const toFrame = (method: string, params: Record<string, unknown>) => {
@@ -235,6 +259,87 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
235
259
  surface.transport.send({ jsonrpc: "2.0", method, params });
236
260
  }
237
261
  };
262
+ /** A query asked of the frame running now (once it finished its handshake). */
263
+ const sendFind = (id: string, params: Record<string, unknown>) => {
264
+ if (handshaken && surface !== null) {
265
+ surface.transport.send({ jsonrpc: "2.0", id, method: FIND_METHODS.query, params });
266
+ }
267
+ };
268
+ /** Answers a query asked, once; a later answer for it is dropped. */
269
+ const settleFind = (id: string, result: FindResult | "unsupported") => {
270
+ const asked = findsAsked.get(id);
271
+ if (asked !== undefined) {
272
+ findsAsked.delete(id);
273
+ clearTimeout(asked.timer);
274
+ asked.resolve(result);
275
+ }
276
+ };
277
+ /**
278
+ * Asks the frame a query: at once where one finished its handshake, else when one does
279
+ * (its load's time and the answer's). No answer in time, an error (an older shell's "isn't
280
+ * offered here"), or one malformed: `"unsupported"`.
281
+ */
282
+ const askFind = (params: Record<string, unknown>): Promise<FindResult | "unsupported"> =>
283
+ new Promise((resolve) => {
284
+ const id = `porthole-find-${nextFind++}`;
285
+ const wait = handshaken ? FIND_LIMITS.timeoutMs : timeoutMs + FIND_LIMITS.timeoutMs;
286
+ findsAsked.set(id, {
287
+ params,
288
+ resolve,
289
+ timer: setTimeout(() => settleFind(id, "unsupported"), wait),
290
+ });
291
+ sendFind(id, params);
292
+ });
293
+ /**
294
+ * A new frame's find (after its handshake): the shortcut, and the latest of the queries
295
+ * asked while it loaded (those it superseded answered `"unsupported"`, never sent). A query
296
+ * cleared since it was asked is answered as nothing found, unasked. The query shown before
297
+ * this run is never given again: a run's frame may show other content (forgetFind).
298
+ */
299
+ const giveFind = () => {
300
+ if (!finds) {
301
+ return;
302
+ }
303
+ if (takesShortcut) {
304
+ toFrame(FIND_METHODS.handled, { handled: true });
305
+ }
306
+ if (findShown === null) {
307
+ for (const id of findsAsked.keys()) {
308
+ settleFind(id, { total: 0, active: 0 });
309
+ }
310
+ return;
311
+ }
312
+ const waiting = [...findsAsked];
313
+ for (const [id] of waiting.slice(0, -1)) {
314
+ settleFind(id, "unsupported");
315
+ }
316
+ const last = waiting.at(-1);
317
+ if (last !== undefined) {
318
+ const [id, asked] = last;
319
+ clearTimeout(asked.timer);
320
+ asked.timer = setTimeout(() => settleFind(id, "unsupported"), FIND_LIMITS.timeoutMs);
321
+ sendFind(id, asked.params);
322
+ }
323
+ };
324
+ /**
325
+ * The content the query was asked of is gone (P131): a new run (a reload, a restart after
326
+ * the content navigated away, a new location) or other content. The query is forgotten and
327
+ * what waits is answered `"unsupported"`, so a new page is never searched with the last
328
+ * one's query unless the host asks it again; `clearFrame` also clears the frame running now.
329
+ */
330
+ const forgetFind = (clearFrame: boolean) => {
331
+ if (!finds) {
332
+ return;
333
+ }
334
+ const had = findShown !== null || findsAsked.size > 0;
335
+ findShown = null;
336
+ for (const id of findsAsked.keys()) {
337
+ settleFind(id, "unsupported");
338
+ }
339
+ if (clearFrame && had) {
340
+ toFrame(FIND_METHODS.clear, {});
341
+ }
342
+ };
238
343
  const giveAnnotations = () => {
239
344
  if (marks.length > 0) {
240
345
  toFrame(ANNOTATE_METHODS.show, {
@@ -284,7 +389,9 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
284
389
  };
285
390
  /**
286
391
  * Every box a report carries, clamped to the frame's viewport as it is now (P104): the page
287
- * places the host's own UI nowhere outside its frame.
392
+ * places the host's own UI nowhere outside its frame. A mark's `documentRect` and the
393
+ * document's `scroll` (P132) pass as they were checked: where a mark is in the document,
394
+ * offscreen too, which a clamp would erase; the host clips what it draws from them.
288
395
  */
289
396
  const withinFrame = (report: AnnotationReport): AnnotationReport => {
290
397
  const viewport = frameViewport();
@@ -295,7 +402,7 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
295
402
  return { ...report, rect: clampRect(report.rect, viewport) };
296
403
  case "anchored":
297
404
  return {
298
- type: "anchored",
405
+ ...report,
299
406
  results: report.results.map((result) =>
300
407
  result.rect === undefined
301
408
  ? result
@@ -385,7 +492,7 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
385
492
  if (results.length === 0) {
386
493
  return;
387
494
  }
388
- report = { type: "anchored", results };
495
+ report = { ...report, results };
389
496
  break;
390
497
  }
391
498
  case "activated": {
@@ -405,6 +512,98 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
405
512
  }
406
513
  void through.call("annotate", withinFrame(report));
407
514
  };
515
+ /**
516
+ * What the frame says of find (P131): an answer to a query asked (its own id only, checked,
517
+ * its box clamped to the frame), or a report unasked, taken only while the host asked for it
518
+ * (the shortcut while the host takes it and the page's focus is in the frame; a changed count
519
+ * while a query is shown), then through the bridge's gates.
520
+ */
521
+ const onFind = (
522
+ raw: unknown,
523
+ through: HostFunctionBridge,
524
+ focused: () => boolean | undefined,
525
+ ) => {
526
+ if (!isRecord(raw) || raw.jsonrpc !== "2.0") {
527
+ return;
528
+ }
529
+ if (typeof raw.method !== "string") {
530
+ // Its own entries only: an id the host never asked is no answer.
531
+ const id = raw.id;
532
+ if (typeof id !== "string" || !findsAsked.has(id)) {
533
+ return;
534
+ }
535
+ const result = "error" in raw || !("result" in raw) ? null : parseFindResult(raw.result);
536
+ settleFind(
537
+ id,
538
+ result === null
539
+ ? "unsupported"
540
+ : result.rect === undefined
541
+ ? result
542
+ : { ...result, rect: clampRect(result.rect, frameViewport()) },
543
+ );
544
+ return;
545
+ }
546
+ if ("id" in raw) {
547
+ return;
548
+ }
549
+ const type = Object.hasOwn(FIND_REPORTS, raw.method) ? FIND_REPORTS[raw.method] : undefined;
550
+ if (type === undefined) {
551
+ return;
552
+ }
553
+ const report = parseFindReport({ ...(isRecord(raw.params) ? raw.params : {}), type });
554
+ if (report === null) {
555
+ void through.call("find", null);
556
+ return;
557
+ }
558
+ if (report.type === "requested") {
559
+ // The person's key in the frame: the page's focus is there (where the platform can tell),
560
+ // so a page can't bring the host's find bar up while the person types beside it.
561
+ let inFrame: boolean | undefined;
562
+ try {
563
+ inFrame = focused();
564
+ } catch {
565
+ inFrame = false;
566
+ }
567
+ if (!takesShortcut || inFrame === false) {
568
+ return;
569
+ }
570
+ } else if (findShown === null) {
571
+ return;
572
+ }
573
+ void through.call("find", report);
574
+ };
575
+ const find: FindControls = {
576
+ query(query, given) {
577
+ if (!finds) {
578
+ return Promise.resolve("unsupported");
579
+ }
580
+ let checked: ReturnType<typeof checkFindQuery>;
581
+ try {
582
+ checked = checkFindQuery(query, given);
583
+ } catch (error) {
584
+ return Promise.reject(error);
585
+ }
586
+ if (blankQuery(checked.query)) {
587
+ findShown = null;
588
+ toFrame(FIND_METHODS.clear, {});
589
+ return Promise.resolve({ total: 0, active: 0 });
590
+ }
591
+ findShown = { query: checked.query, caseSensitive: checked.caseSensitive };
592
+ return askFind({ ...checked });
593
+ },
594
+ clear() {
595
+ if (finds) {
596
+ findShown = null;
597
+ toFrame(FIND_METHODS.clear, {});
598
+ }
599
+ },
600
+ takeShortcut(take) {
601
+ if (finds) {
602
+ takesShortcut = take;
603
+ toFrame(FIND_METHODS.handled, { handled: takesShortcut });
604
+ }
605
+ },
606
+ };
408
607
  const needsAnnotate = (operation: string) => {
409
608
  if (!annotates) {
410
609
  throw new TypeError(`annotations.${operation}: the config doesn't declare annotate`);
@@ -550,6 +749,14 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
550
749
  case "annotation":
551
750
  emit("annotation", event.report);
552
751
  return;
752
+ case "find":
753
+ if (event.report.type === "requested") {
754
+ emit("findRequested", undefined);
755
+ } else {
756
+ const { type: _type, ...result } = event.report;
757
+ emit("findUpdated", result);
758
+ }
759
+ return;
553
760
  }
554
761
  };
555
762
 
@@ -745,6 +952,9 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
745
952
  if (annotates) {
746
953
  created.transport.listen((raw) => onAnnotation(raw, opening));
747
954
  }
955
+ if (finds) {
956
+ created.transport.listen((raw) => onFind(raw, opening, () => created.focused?.()));
957
+ }
748
958
  // Whether the page used storage (P111): once per run, the page's word (a count, no more).
749
959
  created.transport.listen((raw) => {
750
960
  if (
@@ -777,6 +987,7 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
777
987
  if (!handshaken) {
778
988
  handshaken = true;
779
989
  giveAnnotations();
990
+ giveFind();
780
991
  }
781
992
  emit("initialized", undefined);
782
993
  }
@@ -791,6 +1002,8 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
791
1002
 
792
1003
  const run = () => {
793
1004
  stop();
1005
+ // Each run is a new frame, maybe of other content: it starts with no query (P131).
1006
+ forgetFind(false);
794
1007
  if (destroyed) {
795
1008
  return;
796
1009
  }
@@ -879,6 +1092,7 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
879
1092
  const controls = {
880
1093
  displayId: mount.displayId,
881
1094
  annotations,
1095
+ find,
882
1096
  setTheme(next: ColorScheme) {
883
1097
  if (themeless) {
884
1098
  return;
@@ -922,6 +1136,9 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
922
1136
  destroyed = true;
923
1137
  stop();
924
1138
  listeners.clear();
1139
+ for (const id of findsAsked.keys()) {
1140
+ settleFind(id, "unsupported");
1141
+ }
925
1142
  },
926
1143
  };
927
1144
 
@@ -931,6 +1148,10 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
931
1148
  get(target, key, receiver) {
932
1149
  if (typeof key === "string" && !(key in target) && !BASE_KEYS.has(key)) {
933
1150
  return (...args: unknown[]) => {
1151
+ // Other content (not the content so far, continued): the query was the last one's.
1152
+ if (key === "setContent" && !continues(replay.get(key)?.[0], args[0])) {
1153
+ forgetFind(true);
1154
+ }
934
1155
  replay.delete(key);
935
1156
  replay.set(key, args);
936
1157
  const operation = (connection as unknown as Record<string, unknown> | null)?.[key];
@@ -946,6 +1167,17 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
946
1167
  };
947
1168
  }
948
1169
 
1170
+ /**
1171
+ * Whether `next` is the content `before` was, continued (P131): the same, or more of it (the next
1172
+ * part of a streamed page). Nothing given before: anything continues it.
1173
+ */
1174
+ function continues(before: unknown, next: unknown): boolean {
1175
+ return (
1176
+ before === undefined ||
1177
+ (typeof before === "string" && typeof next === "string" && next.startsWith(before))
1178
+ );
1179
+ }
1180
+
949
1181
  /** The host's nonce option, read now (`HostOptions.nonce`). */
950
1182
  function nonceOf(nonce: HostOptions["nonce"]): { nonce?: string } {
951
1183
  const value = typeof nonce === "function" ? nonce() : nonce;
@@ -15,8 +15,9 @@ const KINDS: readonly EgressKind[] = ["connect", "script", "style", "img", "font
15
15
  * conversation and context (`sendPrompt`, `setModelContext`), and the host's data services, which
16
16
  * may be someone else's (`callTool`, `readData`, `subscribeData`: their arguments are the page's).
17
17
  * Not here: the person's own clipboard and disk (`copyText`, `downloadFile`), the host's own UI
18
- * (`annotate`, `resize`, `comments`: the composer is the person's, under the host's duties), and
19
- * what only reads (`user`). `reportError` is one where the config sends errors to the agent.
18
+ * (`annotate`, `find`, `resize`, `comments`: the composer is the person's, under the host's
19
+ * duties), and what only reads (`user`). `reportError` is one where the config sends errors to the
20
+ * agent.
20
21
  */
21
22
  const CARRIERS: readonly CapabilityName[] = [
22
23
  "db",
package/src/host/types.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { AnnotateMode, AnnotationMark, AnnotationReport } from "../annotate/types.ts";
2
+ import type { FindOptions, FindResult } from "../find/types.ts";
2
3
  import type { Refused } from "../bridge/refusal.ts";
3
4
  import type {
4
5
  Confirm,
@@ -126,6 +127,8 @@ export type HostErrorKind =
126
127
  | "mount"
127
128
  /** An annotation call was refused (an invalid mark, an unknown id). */
128
129
  | "annotations"
130
+ /** A find call was refused (a query too long, options that aren't these: P131). */
131
+ | "find"
129
132
  /**
130
133
  * A frame status (`porthole/notifications/frame-status`) the host didn't take, since it came
131
134
  * from the frame's content, not from a page of Porthole's server (P124): never shown, never an
@@ -238,6 +241,53 @@ export interface DisplayEvents {
238
241
  * content's word: UI hints, never permissions.
239
242
  */
240
243
  readonly annotation: AnnotationReport;
244
+ /**
245
+ * The person pressed Cmd+F (Apple) or Ctrl+F (elsewhere) with the keyboard in the frame (`find`,
246
+ * P131): open the host's find bar. Only while the host takes the shortcut
247
+ * (`find.takeShortcut(true)`, which stops the browser's own find there) and the page's focus is
248
+ * in the frame (where the platform can tell). The content's word: it can say it without the key,
249
+ * or keep the key; open the bar, nothing more.
250
+ */
251
+ readonly findRequested: undefined;
252
+ /**
253
+ * The matches of the query shown changed without the host asking (`find`, P131): the content
254
+ * changed (more of it, or the page's own changes). At most once a second, from an honest shell.
255
+ * The content's word: a find bar's numbers.
256
+ */
257
+ readonly findUpdated: FindResult;
258
+ }
259
+
260
+ /**
261
+ * Find in page on a display whose config declares `find` (P131): the host draws the find bar,
262
+ * the frame finds and highlights. The query is posted into the frame, where the content can read
263
+ * it. Where the config doesn't declare `find`, `query` answers `"unsupported"` and the rest do
264
+ * nothing. The shortcut is kept and given to every frame the display runs. The query holds only for
265
+ * the content it was asked of: a new run (`reload()`, a restart after the content navigated away,
266
+ * a new location) or other content (`setContent` with content that doesn't continue what was
267
+ * given) forgets it and answers what waits `"unsupported"`, and nothing is found there until the
268
+ * host asks again: clear your find bar then.
269
+ */
270
+ export interface FindControls {
271
+ /**
272
+ * Finds `query` in the content's text (case-insensitive by default, any spacing), highlights
273
+ * every match, makes one current (the first in view for a new query; the next or previous one
274
+ * with `direction`), scrolls it into view, and answers where they stand. An empty query (or
275
+ * only spaces) clears, and answers no matches. `"unsupported"` where the frame can't find: the
276
+ * config doesn't declare `find`, the frame's shell is older (it answered that it doesn't know
277
+ * the request), it failed, it didn't answer in `FIND_LIMITS.timeoutMs` once it ran, a later
278
+ * query superseded it before it ran (only the latest is searched: show the answer to your latest
279
+ * query only), or the content it was asked of is gone (a new run, other content). Rejects
280
+ * with a `TypeError` for a query longer than `FIND_LIMITS.query`, or options that aren't these.
281
+ */
282
+ query(query: string, options?: FindOptions): Promise<FindResult | "unsupported">;
283
+ /** Removes the highlights and forgets the query (the find bar closed). */
284
+ clear(): void;
285
+ /**
286
+ * Whether the host draws its own find bar for this display (default no): while it does, Cmd+F
287
+ * or Ctrl+F in the frame doesn't open the browser's own find, and the display says
288
+ * `findRequested` instead. A page that handles the key itself keeps it.
289
+ */
290
+ takeShortcut(take: boolean): void;
241
291
  }
242
292
 
243
293
  /**
@@ -256,7 +306,9 @@ export interface AnnotationControls {
256
306
  * Follows one shown mark (P112): while it moves (a scroll, a layout change) the display reports
257
307
  * `{ type: "tracked", id, rect }` at most once per animation frame (60 a second), its box clamped
258
308
  * to the frame, for that mark only; `null` stops. One at a time: a new id replaces the last.
259
- * Throws for an id no shown mark has; a `show` without it, or `clear`, stops it.
309
+ * Throws for an id no shown mark has; a `show` without it, or `clear`, stops it. From a newer
310
+ * shell (P132) each also carries the mark's `documentRect` and the document's `scroll`, so
311
+ * following one mark tells how far the document scrolled, for every mark placed by `documentRect`.
260
312
  */
261
313
  track(id: string | null): void;
262
314
  /** Removes every mark. */
@@ -285,6 +337,8 @@ export interface DisplayControls {
285
337
  ): () => void;
286
338
  /** Annotations (`annotate`): throws on use where the config doesn't declare it. */
287
339
  readonly annotations: AnnotationControls;
340
+ /** Find in page (`find`, P131): `"unsupported"` where the config doesn't declare it. */
341
+ readonly find: FindControls;
288
342
  /** Runs the content again from the start, in a new frame. */
289
343
  reload(): void;
290
344
  /**
package/src/index.ts CHANGED
@@ -319,6 +319,7 @@ export {
319
319
  } from "./host/locator.ts";
320
320
  export type {
321
321
  AnnotationControls,
322
+ FindControls,
322
323
  DisplayControls,
323
324
  DisplayEvents,
324
325
  FrameBlock,
@@ -341,9 +342,21 @@ export {
341
342
  type AnnotationMarkKind,
342
343
  type AnnotationRect,
343
344
  type AnnotationReport,
345
+ type AnnotationScroll,
344
346
  type AnnotationSelector,
345
347
  type CssSelector,
346
348
  type TextPositionSelector,
347
349
  type TextQuoteSelector,
348
350
  } from "./annotate/types.ts";
349
- export { parseAnchor, parseRect, parseReport } from "./annotate/validate.ts";
351
+ export { parseAnchor, parseRect, parseReport, parseScroll } from "./annotate/validate.ts";
352
+
353
+ // Find in page (P131): the host's find bar, the frame's matches, and the host's checks on both.
354
+ export {
355
+ FIND_LIMITS,
356
+ FIND_METHODS,
357
+ type FindDirection,
358
+ type FindOptions,
359
+ type FindReport,
360
+ type FindResult,
361
+ } from "./find/types.ts";
362
+ export { parseFindReport, parseFindResult } from "./find/validate.ts";