@weatherboard/annotation 0.6.0 → 0.7.0

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 (57) hide show
  1. package/ADOPTING.md +50 -4
  2. package/COMPATIBILITY.md +14 -0
  3. package/README.md +51 -2
  4. package/dist/anchor.cjs +1 -1
  5. package/dist/anchor.cjs.map +1 -1
  6. package/dist/anchor.mjs +1 -1
  7. package/dist/anchor.mjs.map +1 -1
  8. package/dist/arming.d.cts +17 -18
  9. package/dist/arming.d.mts +17 -18
  10. package/dist/arming.d.ts +17 -18
  11. package/dist/bootstrap.cjs +1 -1
  12. package/dist/bootstrap.cjs.map +4 -4
  13. package/dist/bootstrap.d.cts +1 -0
  14. package/dist/bootstrap.d.mts +1 -0
  15. package/dist/bootstrap.d.ts +1 -0
  16. package/dist/bootstrap.mjs +1 -1
  17. package/dist/bootstrap.mjs.map +4 -4
  18. package/dist/host.cjs +1 -1
  19. package/dist/host.cjs.map +2 -2
  20. package/dist/host.mjs +1 -1
  21. package/dist/host.mjs.map +2 -2
  22. package/dist/index.cjs +4 -4
  23. package/dist/index.cjs.map +4 -4
  24. package/dist/index.d.cts +9 -3
  25. package/dist/index.d.mts +9 -3
  26. package/dist/index.d.ts +9 -3
  27. package/dist/index.mjs +4 -4
  28. package/dist/index.mjs.map +4 -4
  29. package/dist/markers.cjs.map +1 -1
  30. package/dist/markers.mjs.map +1 -1
  31. package/dist/page-capture.cjs +2 -0
  32. package/dist/page-capture.cjs.map +7 -0
  33. package/dist/page-capture.d.cts +115 -0
  34. package/dist/page-capture.d.mts +115 -0
  35. package/dist/page-capture.d.ts +115 -0
  36. package/dist/page-capture.mjs +2 -0
  37. package/dist/page-capture.mjs.map +7 -0
  38. package/dist/protocol.cjs +1 -1
  39. package/dist/protocol.cjs.map +2 -2
  40. package/dist/protocol.d.cts +12 -0
  41. package/dist/protocol.d.mts +12 -0
  42. package/dist/protocol.d.ts +12 -0
  43. package/dist/protocol.mjs +1 -1
  44. package/dist/protocol.mjs.map +2 -2
  45. package/dist/screenshot.d.cts +56 -7
  46. package/dist/screenshot.d.mts +56 -7
  47. package/dist/screenshot.d.ts +56 -7
  48. package/dist/session.d.cts +7 -0
  49. package/dist/session.d.mts +7 -0
  50. package/dist/session.d.ts +7 -0
  51. package/dist/shortcut.d.cts +52 -0
  52. package/dist/shortcut.d.mts +52 -0
  53. package/dist/shortcut.d.ts +52 -0
  54. package/dist/toolbar.d.cts +13 -0
  55. package/dist/toolbar.d.mts +13 -0
  56. package/dist/toolbar.d.ts +13 -0
  57. package/package.json +13 -3
@@ -168,9 +168,21 @@ export interface AnnotationPayload {
168
168
  failedRequests: NetworkEntry[];
169
169
  featureFlags: Record<string, unknown>;
170
170
  };
171
+ /**
172
+ * `w`/`h` and `canvases` arrive with the in-page viewport capture (A-2385);
173
+ * `canvases` counts the canvases in view and how many read back blank or
174
+ * unreadable, so a black rectangle in the picture is explained, not silent.
175
+ */
171
176
  screenshot?: {
172
177
  dataUrl: string;
173
178
  region: "element" | "viewport";
179
+ w?: number;
180
+ h?: number;
181
+ canvases?: {
182
+ total: number;
183
+ blank: number;
184
+ unreadable: number;
185
+ };
174
186
  };
175
187
  /** The human's words, verbatim. The parent frame fills this in; we never rewrite it. */
176
188
  comment: string;
package/dist/protocol.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var A="1",d="x-weatherboard-annotation-mode",m="first-party",f="data-src",T="data-src-name";function N(t){return t.selection==="region"?"region":"element"}function a(t){try{return JSON.stringify(t)??String(t)}catch{return"[unserialisable]"}}function _(t,e){console.error(`[annotation] ${t}: protocol drift, nothing was acted on: ${a(e)}`)}var i=new Set(["annotate:enable","annotate:disable","annotate:ping"]);function x(t){if(typeof t!="object"||t===null)return!1;let e=t.type;return typeof e=="string"&&i.has(e)}function O(t){if(!t||t==="*")throw new Error("[annotation] a concrete parent origin is required; '*' would broadcast annotation payloads to any embedder.");return t}var s="ai_annotate",r="ai_annotate_armed",E="ai_capture",R="ai_run",y="ai_read",c="1";function b(t=r){return`${t}=${c}; Path=/; SameSite=Lax; Secure`}function h(t){return`${t}=; Path=/; SameSite=Lax; Secure; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`}var u="pits_annotate",p="pits_annotate_armed",g=[s,u],l=[r,p];function I(t){return t.split(";").some(e=>{let n=e.trimStart();return l.some(o=>n.startsWith(`${o}=`))})}function S(t){for(let e of g){let n=t.get(e);if(n!==null&&n.length>0)return n}return null}export{r as ANNOTATION_ARMED_COOKIE,l as ANNOTATION_ARMED_COOKIES,c as ANNOTATION_ARMED_VALUE,d as ANNOTATION_MODE_HEADER,s as ANNOTATION_TOKEN_PARAM,g as ANNOTATION_TOKEN_PARAMS,E as CAPTURE_TOKEN_PARAM,m as FIRST_PARTY_ANNOTATION_MODE,p as LEGACY_ANNOTATION_ARMED_COOKIE,u as LEGACY_ANNOTATION_TOKEN_PARAM,T as NAME_ATTR,y as READ_TOKEN_PARAM,R as REVIEW_RUN_PARAM,A as SDK_VERSION,f as SRC_ATTR,b as armedCookie,O as assertConcreteOrigin,h as clearedCookie,I as isAnnotationArmed,x as isParentMessage,S as readAnnotationToken,N as selectionOf,_ as unhandledMessage};
1
+ var A="1",m="x-weatherboard-annotation-mode",d="first-party",f="data-src",T="data-src-name";function N(t){return t.selection==="region"?"region":"element"}function a(t){try{return JSON.stringify(t)??String(t)}catch{return"[unserialisable]"}}function _(t,e){console.error(`[annotation] ${t}: protocol drift, nothing was acted on: ${a(e)}`)}var i=new Set(["annotate:enable","annotate:disable","annotate:ping"]);function x(t){if(typeof t!="object"||t===null)return!1;let e=t.type;return typeof e=="string"&&i.has(e)}function O(t){if(!t||t==="*")throw new Error("[annotation] a concrete parent origin is required; '*' would broadcast annotation payloads to any embedder.");return t}var s="ai_annotate",r="ai_annotate_armed",E="ai_capture",b="ai_run",R="ai_read",c="1";function y(t=r){return`${t}=${c}; Path=/; SameSite=Lax; Secure`}function h(t){return`${t}=; Path=/; SameSite=Lax; Secure; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`}var u="pits_annotate",p="pits_annotate_armed",g=[s,u],l=[r,p];function I(t){return t.split(";").some(e=>{let n=e.trimStart();return l.some(o=>n.startsWith(`${o}=`))})}function S(t){for(let e of g){let n=t.get(e);if(n!==null&&n.length>0)return n}return null}export{r as ANNOTATION_ARMED_COOKIE,l as ANNOTATION_ARMED_COOKIES,c as ANNOTATION_ARMED_VALUE,m as ANNOTATION_MODE_HEADER,s as ANNOTATION_TOKEN_PARAM,g as ANNOTATION_TOKEN_PARAMS,E as CAPTURE_TOKEN_PARAM,d as FIRST_PARTY_ANNOTATION_MODE,p as LEGACY_ANNOTATION_ARMED_COOKIE,u as LEGACY_ANNOTATION_TOKEN_PARAM,T as NAME_ATTR,R as READ_TOKEN_PARAM,b as REVIEW_RUN_PARAM,A as SDK_VERSION,f as SRC_ATTR,y as armedCookie,O as assertConcreteOrigin,h as clearedCookie,I as isAnnotationArmed,x as isParentMessage,S as readAnnotationToken,N as selectionOf,_ as unhandledMessage};
2
2
  //# sourceMappingURL=protocol.mjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/protocol.ts"],
4
- "sourcesContent": ["/**\n * The annotation postMessage protocol (A-36).\n *\n * Mirrors `docs/contracts/types.ts`. That file is the\n * cross-component contract; this is the runtime copy the product bundle ships,\n * because the product cannot import from a docs directory. Changing a shape\n * here is a change to both \u2014 say so in the PR.\n */\n\nexport const SDK_VERSION = \"1\";\n\n/**\n * A hosted document declares first-party annotation support with this exact\n * response header. It describes the BUILD, never a token, cookie or attempt.\n */\nexport const ANNOTATION_MODE_HEADER = \"x-weatherboard-annotation-mode\";\nexport const FIRST_PARTY_ANNOTATION_MODE = \"first-party\";\n\n/**\n * ===========================================================================\n * THE ATTRIBUTES \u2014 THE OTHER WIRE (A-186)\n * ===========================================================================\n *\n * These live in `protocol.ts`, not in `target.ts` where they are read, because\n * they are a contract between TWO PACKAGES that a consumer installs separately:\n * `@weatherboard/annotation-next` WRITES them at build time and this package\n * READS them at runtime. Two spellings of `data-src` is not a bug anybody\n * catches \u2014 the transform runs, the attributes appear, and every capture comes\n * back with no source ref at all, which is indistinguishable from the transform\n * not running.\n *\n * `annotation-next` imports these from `@weatherboard/annotation/protocol`\n * rather than declaring its own, which is why the subpath has no DOM in it: a\n * build tool importing the page SDK to learn two strings would be absurd.\n */\nexport const SRC_ATTR = \"data-src\";\nexport const NAME_ATTR = \"data-src-name\";\n\nexport interface SourceRef {\n file: string;\n line: number;\n column?: number;\n}\n\nexport interface BuildInfo {\n /** Mandatory. Feedback not pinned to a revision is ambiguous the moment someone merges. */\n gitSha: string;\n /**\n * Where this build came from.\n *\n * `\"development\"` was added in A-37, when the SDK was first mounted in a\n * real app and the two halves turned out not to agree: `resolveBuildInfo` in\n * `resolveBuildInfo` in the product's own Next config package \u2014 the module\n * that stamps the build-env variable, and the only producer of this field \u2014\n * emits\n * `production | preview | development`, mirroring `VERCEL_ENV`. This union\n * instead offered `\"staging\"`, which nothing produces: a staging deploy IS a\n * Vercel preview and reports itself as one. Widening rather than forcing the\n * mount to lie: a locally-annotated build calling itself a preview would put\n * someone's laptop in the corpus as though it were a deployment.\n */\n env: \"production\" | \"preview\" | \"staging\" | \"development\";\n branch?: string;\n /** Set when reviewing an agent's preview deploy, so feedback routes to that run's session. */\n previewRunId?: string;\n}\n\nexport interface ConsoleEntry {\n level: \"error\" | \"warn\";\n message: string;\n stack?: string;\n at: string;\n}\n\nexport interface NetworkEntry {\n url: string;\n method: string;\n status: number;\n at: string;\n}\n\nexport interface TargetInfo {\n /**\n * What the reviewer selected \u2014 one element, or an area (A-179).\n *\n * -------------------------------------------------------------------------\n * WHY THIS EXISTS RATHER THAN BEING INFERRED\n * -------------------------------------------------------------------------\n *\n * A region capture and an element capture are the same SHAPE: a bounding box,\n * a chain of source refs, a DOM path. Nothing in the values distinguishes\n * them, and the two mean opposite things about the chain \u2014 for an element it\n * is ANCESTORS, innermost first, so entry two contains entry one; for a\n * region it is SIBLINGS the rectangle happened to cross, which contain\n * nothing of each other.\n *\n * A reader that guesses will describe a region's siblings as a call-site\n * chain, which is a confident false statement about the page. `describeCapture`\n * hands that description to a model that writes acceptance criteria from it.\n *\n * -------------------------------------------------------------------------\n * WHY IT IS OPTIONAL, AND WHY ABSENT MEANS `element`\n * -------------------------------------------------------------------------\n *\n * The two halves of this protocol live in different repositories and deploy\n * independently (see the note on the legacy parameter names below). Every\n * capture in the store today, and every capture from a product bundle that\n * predates region selection, has no such field \u2014 and all of them are element\n * captures. Absent therefore has to mean `element`, or this field would\n * retroactively make the entire history ambiguous.\n *\n * Required-with-a-default would have the same effect and a worse failure: an\n * older bundle omits it, the type says it is there, and every reader believes\n * a value nobody sent.\n */\n selection?: \"element\" | \"region\";\n source?: SourceRef;\n /**\n * Every `data-src` from the clicked element up to the document root, innermost\n * first \u2014 an addition to the contract, and the reason is structural.\n *\n * Only host elements carry a ref (A-33), so `source` names the file that\n * *writes the markup*. For a composed design-system component that is\n * `MediaCard.tsx`, not the `GuideDetailCard.tsx` a human would say they\n * clicked. The chain is what lets the PM agent and the coding agent see both,\n * and pick the call site over the leaf when the feedback is about content\n * rather than the component itself.\n */\n sourceChain?: SourceRef[];\n componentName?: string;\n /** CSS selector fallback, for when no ancestor carries a ref at all. */\n domPath: string;\n boundingBox: { x: number; y: number; w: number; h: number };\n /** Truncated to 200 characters. */\n textContent?: string;\n}\n\n/**\n * What kind of capture this is, with the default applied once (A-189).\n *\n * `selection` is optional and **absent means `element`** \u2014 every capture taken\n * before A-179, and everything the managed product's live bundle emits today,\n * has no such field. Any other default would retroactively reclassify the whole\n * history as regions, silently.\n *\n * A function rather than a documented convention because the default is the\n * kind of thing two readers implement slightly differently and neither notices:\n * one writes `=== \"region\"`, another writes `?? \"element\"`, a third forgets and\n * treats `undefined` as falsy in a branch that meant something else. This is\n * the protocol's answer, and `compatibility.test.ts` replays every recorded\n * payload through it.\n */\nexport function selectionOf(target: Pick<TargetInfo, \"selection\">): \"element\" | \"region\" {\n return target.selection === \"region\" ? \"region\" : \"element\";\n}\n\nexport interface AnnotationPayload {\n schemaVersion: 1;\n capturedAt: string;\n build: BuildInfo;\n page: {\n url: string;\n /** The matched route pattern, not the resolved URL. */\n route: string;\n viewport: { w: number; h: number; dpr: number };\n userAgent: string;\n };\n target: TargetInfo;\n state: {\n consoleErrors: ConsoleEntry[];\n failedRequests: NetworkEntry[];\n featureFlags: Record<string, unknown>;\n };\n screenshot?: { dataUrl: string; region: \"element\" | \"viewport\" };\n /** The human's words, verbatim. The parent frame fills this in; we never rewrite it. */\n comment: string;\n}\n\nexport type ParentToFrame =\n | { type: \"annotate:enable\" }\n | { type: \"annotate:disable\" }\n | { type: \"annotate:ping\" };\n\nexport type FrameToParent =\n | { type: \"annotate:ready\"; sdkVersion: string; build: BuildInfo }\n | { type: \"annotate:hover\"; target: TargetInfo }\n | { type: \"annotate:capture\"; payload: AnnotationPayload }\n | { type: \"annotate:cancel\" };\n\n/**\n * A message that got past both guards and matched no `case` (A-359).\n *\n * ===========================================================================\n * THE DEFECT\n * ===========================================================================\n *\n * `host.ts` and `sdk.ts` hold the two halves of this protocol, one `switch`\n * each, and neither had a `default`. Measured before the fix: adding\n * `| { type: \"annotate:probe\" }` to `ParentToFrame` and\n * `| { type: \"annotate:pong\" }` to `FrameToParent`, then running\n * `tsc --noEmit` in this package, gave exit 0 and zero errors. A message type\n * added to the union is dropped on the floor by whichever half was not\n * updated, and the two halves are the only things in the world that can\n * disagree about what a message means.\n *\n * ===========================================================================\n * WHY IT DOES NOT THROW, WHERE THE MANAGER'S TWO EQUIVALENTS DO\n * ===========================================================================\n *\n * This is the house pattern with one deliberate departure, and the departure is\n * the boundary rather than taste.\n *\n * Both switches run inside a `message` listener, reached from `postMessage`.\n * The host's listener runs in the management console over a frame that may be\n * serving anything; the SDK's runs in a product page we do not own. A throw\n * there does not propagate to a caller \u2014 there is no caller \u2014 it becomes an\n * uncaught error on somebody else's page, once per message. Any party that can\n * reach this branch can therefore reach it repeatedly, and the loudest\n * available answer would be handing them a way to fill a product's error\n * reporting with our noise.\n *\n * The narrower reason the throw would buy little: `isFrameMessage` and\n * `isParentMessage` gate on fixed sets of type strings, so a message an\n * outsider invents never reaches the switch at all. What DOES reach it is a\n * type in the guard's set with no `case` \u2014 which is our own two lists having\n * drifted apart, in this repository, in the commit that widened one of them.\n *\n * So the answer is: act on nothing, and say so. Acting on nothing is what a\n * trust boundary owes an input it does not understand; saying so is what makes\n * this different from the silent drop that was there before, which is\n * indistinguishable from the message never having been sent.\n *\n * `console.error` rather than a callback, because both call sites are inside\n * listeners with no error channel of their own, and because in the frame the\n * SDK's own `StateCollector` patches `console.error` \u2014 so the drift is\n * collected into the very next annotation payload, where somebody debugging\n * exactly this will already be looking.\n *\n * The type-level half of the guard is NOT here. It is `const unhandled: never`\n * in each `default` branch, which is what makes a widened union a compile\n * error; this function only makes the runtime half observable, and it is\n * exported so `exhaustive.test.ts` can call it. Both halves are pinned\n * separately, because deleting either leaves the other looking correct.\n */\n/**\n * `JSON.stringify` that cannot throw, for any input at all (A-359 cycle 2).\n *\n * ===========================================================================\n * WHY THIS IS NEEDED \u2014 THE DEFECT IT REPLACES\n * ===========================================================================\n *\n * `unhandledMessage` interpolated `JSON.stringify(message)` unguarded, and so\n * became the thing it was written to prevent. `postMessage` serialises with\n * the STRUCTURED CLONE algorithm, and structured clone PRESERVES CYCLES where\n * JSON cannot represent them \u2014 so `{a: {b: a}}` survives a `postMessage`\n * intact, arrives at that branch, and `JSON.stringify` throws `Converting\n * circular structure to JSON` from inside a `message` listener on a page this\n * SDK is a guest on, once per message, at the sender's discretion.\n *\n * Every word of the argument on `unhandledMessage` was correct, and the\n * implementation defeated it on its own terms. Both cases are pinned in\n * `exhaustive.test.ts` and both were confirmed RED before this existed.\n *\n * ===========================================================================\n * WHY NOT `describeArg`, WHICH DOES THIS ALREADY \u2014 TWO REASONS, ONE MEASURED\n * ===========================================================================\n *\n * `describeArg` in `state.ts` solves the same problem and its comment names\n * the same hazard, so reusing it was the first thing tried rather than a road\n * not taken. It was reverted for two reasons, and the second is the one that\n * decided it:\n *\n * 1. MEASURED, by running `node build.mjs` on both: reuse costs protocol\n * 869 -> 1008 (+139) and host 649 -> 793 (+144). This local version costs\n * +39 and +37. `describeArg` is built for console ARGUMENTS \u2014 strings,\n * Errors, a prototype walk for named objects \u2014 and almost none of that is\n * reachable for a wire message, so the extra 100 bytes per entry point buy\n * nothing here. In a package with a per-entry gzip budget that is not a\n * rounding error.\n * 2. THIS MODULE HAS NO IMPORTS AND THAT IS A PROPERTY WORTH KEEPING.\n * `protocol.ts` is the pure wire contract \u2014 it mirrors\n * `docs/contracts/types.ts`, `annotation-next` imports it so a build tool\n * can learn two strings without pulling in a DOM, and `state.ts` already\n * imports FROM it. Importing back the other way makes the contract depend\n * on the console-patching state collector and closes a module cycle that\n * is only invisible because `state.ts`'s side of it is `import type`.\n *\n * The cost of the choice, stated rather than left for somebody to find: there\n * are now two safe-stringify helpers in this package. They cannot drift in a\n * way that matters \u2014 each is a total function with one behaviour and its own\n * test \u2014 but if a third appears, that is the moment to put one in a module\n * both can depend on, rather than making the contract depend on the collector.\n *\n * The fallback is a constant, deliberately. Reaching for `String(message)` or\n * a constructor name in the `catch` is the obvious way to say something more\n * useful, and it is how this function would learn to throw again: the input\n * that got us here is one whose property access already threw.\n */\nfunction safeJson(message: unknown): string {\n try {\n return JSON.stringify(message) ?? String(message);\n } catch {\n return \"[unserialisable]\";\n }\n}\n\nexport function unhandledMessage(half: \"host\" | \"frame\", message: unknown): void {\n /**\n * `safeJson` RATHER THAN A BARE `JSON.stringify`, AND THAT IS THE WHOLE\n * DIFFERENCE BETWEEN THIS FUNCTION AND ITS FIRST DRAFT (A-359 cycle 2).\n *\n * The first draft interpolated `JSON.stringify(message)` unguarded, which\n * made this function do the thing it exists to avoid. The full argument, the\n * measurement, and why `describeArg` was tried and reverted are on\n * `safeJson` above rather than repeated here.\n *\n * Short on purpose too, and the shortness is measured rather than stylistic.\n * This package ships inside a product's bundle and this package's own\n * `build.mjs` enforces a gzip budget per entry point; the first draft of this\n * sentence was 230 characters and put `protocol`, `host` and `index` over\n * theirs at once. What it must still carry is which half, what arrived, and\n * that nothing was done with it \u2014 the last being the only thing that\n * distinguishes this from the silent drop it replaced.\n */\n console.error(`[annotation] ${half}: protocol drift, nothing was acted on: ${safeJson(message)}`);\n}\n\nconst PARENT_TYPES = new Set([\"annotate:enable\", \"annotate:disable\", \"annotate:ping\"]);\n\n/**\n * Is this a message we recognise?\n *\n * Origin is checked separately and first \u2014 a well-formed message from the wrong\n * origin is the case this guard must not be trusted to catch.\n */\nexport function isParentMessage(data: unknown): data is ParentToFrame {\n if (typeof data !== \"object\" || data === null) return false;\n const type = (data as { type?: unknown }).type;\n return typeof type === \"string\" && PARENT_TYPES.has(type);\n}\n\n/**\n * Reject wildcards outright rather than treating them as \"any origin\".\n *\n * `postMessage(msg, \"*\")` broadcasts the payload to whatever happens to be\n * framing us, and an annotation payload carries page content, console errors and\n * failed request URLs. The spec's rule is no wildcards in either direction; this\n * makes it impossible to configure one by accident.\n */\nexport function assertConcreteOrigin(origin: string): string {\n if (!origin || origin === \"*\") {\n throw new Error(\n \"[annotation] a concrete parent origin is required; '*' would broadcast \" +\n \"annotation payloads to any embedder.\",\n );\n }\n return origin;\n}\n\n/**\n * The query parameter that arms the SDK in a managed product, and the cookie\n * that records it.\n *\n * THESE LIVE IN THE PROTOCOL BECAUSE THE TWO HALVES ARE NOW IN DIFFERENT\n * REPOSITORIES. The managed product's middleware looks for the parameter and\n * sets the cookie; the management app appends the parameter and the SDK reads\n * the cookie. While both halves were one monorepo, a test could read the other\n * side's source and assert the strings matched \u2014 that gate does not survive a\n * repository split, and a mismatch produces no error at all: the frame loads,\n * the cookie is never set, the SDK never boots, and the reviewer sees \"waiting\n * for the page to announce itself\" with nothing to go on.\n *\n * So they stop being two spellings that agree and become one exported\n * constant. A managed product that imports this package cannot drift from it.\n */\nexport const ANNOTATION_TOKEN_PARAM = \"ai_annotate\";\nexport const ANNOTATION_ARMED_COOKIE = \"ai_annotate_armed\";\n\n/**\n * The CAPTURE token's query parameter (A-240).\n *\n * -------------------------------------------------------------------------\n * WHY IT IS HERE AND NOT WHERE IT IS WRITTEN\n * -------------------------------------------------------------------------\n *\n * A second name on the same wire, and a second credential \u2014 see\n * `docs/plans/first-party-annotation.md` \u00A7 *Authentication*. `ai_annotate`\n * answers *should this page offer an annotation UI at all*; this one answers\n * *may this capture become an issue*. Different secrets, different lifetimes,\n * different blast radii, and deliberately not folded into one token.\n *\n * It lives beside `ANNOTATION_TOKEN_PARAM` for that constant's own reason,\n * stated at length above: the console WRITES it into a deep link and the\n * product's bundle READS it, the two halves ship from different repositories,\n * and a mismatch produces no error anywhere \u2014 the reviewer writes a post-it,\n * clicks send, and the ingest rejects an unsigned capture. One exported\n * constant is the only thing that makes those two spellings unable to drift.\n *\n * It has no legacy spelling because it has never had another one: nothing has\n * shipped it yet. It is exported here BEFORE its writer needs it precisely so\n * the writer never has a reason to spell it itself.\n */\nexport const CAPTURE_TOKEN_PARAM = \"ai_capture\";\n\n/**\n * The run under review, when the console knows of one (A-241).\n *\n * Third name on the same wire, here for the reason the two above are: the\n * console writes it and the product's bundle reads it, from two repositories.\n * `apps/manager/src/lib/request-changes.ts` spells it itself today and its own\n * comment asks for exactly this \u2014 the constant to move into the package so the\n * writer has no reason to spell it. **That deletion is not this slice's**\n * (A-243/A-244 are merged and settled), so for now there are two definitions of\n * one string, and `protocol.test.ts` is the only thing standing between them\n * and a silent divergence. Nothing about it is signed: the ingest already\n * treats it as attacker-supplied text and files on it rather than routing on it.\n */\nexport const REVIEW_RUN_PARAM = \"ai_run\";\n\n/**\n * The READ token's query parameter (A-277).\n *\n * ===========================================================================\n * WHY THE MARKER LAYER GETS ITS OWN CREDENTIAL AND NOT `ai_capture`\n * ===========================================================================\n *\n * Fourth name on the same wire, and the reason it is a fourth is A-276's\n * disclosure decision rather than tidiness. The capture token is minted for\n * WRITING and lives four hours so a reviewer can work through a session; reusing\n * it for the read would make one leaked deep link a write capability AND a read\n * capability over every reviewer's comments on that origin for the same window.\n * The scope is a signed field, `verifyCaptureToken` requires an expectation at\n * every call site, and the read endpoint refuses a write claim \u2014 so handing\n * `ai_capture` to the reader does not degrade to a read, it fails.\n *\n * The read claim's TTL is ONE hour rather than four (`READ_TOKEN_TTL_S`), which\n * is the practical consequence a reader of this constant should know: the\n * toolbar outlives the markers, so a reviewer who leaves a tab open all\n * afternoon will find the count line saying it cannot read before they find the\n * Send button broken. That is the intended ordering \u2014 the shorter credential is\n * the one that discloses other people's words.\n *\n * Exported here for the reason the three above are: the console writes it into a\n * deep link and the product's bundle reads it, from two repositories, and a\n * mismatch produces no error anywhere \u2014 just a page with no markers, which is\n * indistinguishable from nine other causes.\n */\nexport const READ_TOKEN_PARAM = \"ai_read\";\n\n/**\n * The arming cookie, as a `Set-Cookie` value (A-241).\n *\n * ===========================================================================\n * IT GOT SIMPLER BY MOVING FIRST-PARTY, AND THAT IS THE WHOLE POINT\n * ===========================================================================\n *\n * Framed, this had to be `SameSite=None; Secure` with no `Partitioned` \u2014 a\n * genuine cross-site cookie, which A-211 records would have broken on its own\n * under Chrome's third-party cookie work, independently of the auth problem\n * that killed the frame. Top-level at the product's own origin it is an\n * ordinary cookie and none of that applies.\n *\n * Each attribute, and why:\n *\n * - **`SameSite=Lax`.** The reviewer arrives by clicking *Request changes* in\n * the console, which is a top-level cross-site GET navigation \u2014 the one case\n * `Lax` still sends on. `Strict` would withhold the cookie on that very first\n * render, so the toolbar would be missing on the page the link opened and\n * appear only after an internal click; that reads as a broken deploy.\n * - **`Secure`.** It is a marker rather than a credential, but a marker that\n * travels in clear is a marker an attacker on the path can set.\n * - **`Path=/`.** Arming survives the reviewer navigating the whole app, which\n * is the point of a cookie rather than a URL parameter.\n * - **No `Max-Age` / `Expires`.** Session-scoped: closing the tab disarms.\n *\n * ===========================================================================\n * WHAT IS *NOT* HERE: `HttpOnly`, AND THE TOKEN\n * ===========================================================================\n *\n * No `HttpOnly`, deliberately. Page script both READS this (`isAnnotationArmed`\n * decides whether a toolbar exists) and CLEARS it (*Done* disarms). An\n * `HttpOnly` arming cookie makes *Done* impossible from the page, which is the\n * one control the reviewer has.\n *\n * That is affordable only because THE VALUE IS A MARKER AND NEVER THE TOKEN.\n * The value is a constant and there is no argument that supplies one: the\n * middleware compares the URL parameter against its secret and then calls this,\n * and what it stores is *yes*, not *what was presented*. The single parameter\n * is the cookie's NAME, and it exists only so a product mid-migration can write\n * the legacy spelling \u2014 it is not a value slot wearing a different label, and\n * `arming.test.ts` pins which side of the `=` it lands on.\n *\n * This is a shape argument, not a guarantee about callers. Nothing stops a\n * determined caller passing a secret as the name; what the signature removes is\n * the ACCIDENT \u2014 the middleware author with a verified token in hand and one\n * parameter available, reaching for the obvious.\n */\nexport const ANNOTATION_ARMED_VALUE = \"1\";\n\nexport function armedCookie(name: string = ANNOTATION_ARMED_COOKIE): string {\n return `${name}=${ANNOTATION_ARMED_VALUE}; Path=/; SameSite=Lax; Secure`;\n}\n\n/**\n * The same cookie, expired \u2014 what *Done* and a disarm write.\n *\n * `Max-Age=0` AND an `Expires` in the past, because they are read by different\n * things and the pair is what every browser honours. The path must match the\n * one set above or the browser stores a second cookie and the first survives \u2014\n * a *Done* button that does nothing and reports success.\n */\nexport function clearedCookie(name: string): string {\n return `${name}=; Path=/; SameSite=Lax; Secure; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;\n}\n\n/**\n * The names these used to have (A-98).\n *\n * -------------------------------------------------------------------------\n * WHY THE RENAME, AND WHY IT COULD NOT JUST BE DONE\n * -------------------------------------------------------------------------\n *\n * They were `pits_annotate` and `pits_annotate_armed` \u2014 one managed product's\n * initialism, in a contract every managed product's bundle has to implement.\n * Onboarding a second product meant asking an unrelated codebase to adopt the\n * first product's name in its cookies and its query strings. That is the bug\n * A-98 is about, and it is a bug in a wire protocol rather than in a variable\n * name, which is what makes it expensive.\n *\n * The two halves live in DIFFERENT REPOSITORIES and deploy independently. A\n * clean rename is therefore a breaking change to every product bundle\n * simultaneously, and its failure mode is silence: the frame loads, the cookie\n * is never set, the SDK never boots, and the reviewer sees \"waiting for the\n * page to announce itself\" with nothing to go on. Nothing throws, nothing logs,\n * and the natural reading is that the agent broke the site.\n *\n * -------------------------------------------------------------------------\n * THE MIGRATION: READ BOTH, WRITE BOTH, THEN STOP WRITING THE OLD ONE\n * -------------------------------------------------------------------------\n *\n * 1. **Now.** Every reader accepts either name. Every writer emits BOTH, so a\n * product still running the old bundle arms on the legacy name and one\n * running the new bundle arms on the new one. Deploy order stops mattering,\n * which is the whole point \u2014 there is no window in which a reviewer sees the\n * silent failure above.\n * 2. **After every managed product's bundle is on this version** (A-102). Drop\n * the legacy names from the writers, then from the readers. Two steps, not\n * one: a reader that stops accepting the old name before the writers stop\n * emitting it re-creates the outage in the other direction.\n *\n * The legacy names are exported rather than inlined so the deletion in step 2\n * is `git grep LEGACY_` rather than an archaeology exercise.\n */\nexport const LEGACY_ANNOTATION_TOKEN_PARAM = \"pits_annotate\";\nexport const LEGACY_ANNOTATION_ARMED_COOKIE = \"pits_annotate_armed\";\n\n/**\n * ===========================================================================\n * AND THE NAMES ARE NOT CHANGING AGAIN FOR THE PUBLISHED PACKAGE (A-184)\n * ===========================================================================\n *\n * When this becomes `@weatherboard/annotation` the obvious next thought is that\n * the wire names should match the package \u2014 `weatherboard_annotate`. They\n * should not, and the reason is the migration described above rather than\n * taste.\n *\n * That migration is STILL IN FLIGHT. Readers accept both spellings; writers\n * emit both; step 2 waits on every managed product's bundle being current.\n * A third spelling introduced now does not replace the second, it joins it:\n * every reader accepts three names, every writer emits three, and the window in\n * which a product can be on any of them widens instead of closing.\n *\n * The cost is not the code. It is that each rename buys another instance of the\n * failure this file exists to prevent \u2014 the frame loads, the cookie is never\n * set, the SDK never boots, and the reviewer sees \"waiting for the page to\n * announce itself\" with nothing to go on. Twice is a migration. Three times is\n * a habit, and the third one would be paid by consumers who never asked for\n * either.\n *\n * `ai_annotate` is already product-neutral, which was the entire point of A-98.\n * A published package needs names that name no product; it does not need names\n * that name the package. Nobody reading a query string cares which npm scope\n * the library came from.\n *\n * The one real objection is collision: `ai_` is a common prefix and some other\n * tool could plausibly use it. That is survivable by construction \u2014 arming\n * requires the parameter to carry a token the product compares exactly, so a\n * coincidental `?ai_annotate=` from an unrelated tool arms nothing. A colliding\n * COOKIE cannot false-positive either; `isAnnotationArmed` matches on the\n * delimiter rather than by substring, for exactly this reason.\n *\n * If a rename is ever genuinely warranted, it happens ONCE, after step 2 has\n * landed and the reader accepts one name again \u2014 not layered on top of an\n * unfinished one.\n */\n\n/** Both spellings of the query parameter, current first. */\nexport const ANNOTATION_TOKEN_PARAMS = [\n ANNOTATION_TOKEN_PARAM,\n LEGACY_ANNOTATION_TOKEN_PARAM,\n] as const;\n\n/** Both spellings of the cookie, current first. */\nexport const ANNOTATION_ARMED_COOKIES = [\n ANNOTATION_ARMED_COOKIE,\n LEGACY_ANNOTATION_ARMED_COOKIE,\n] as const;\n\n/**\n * Whether a cookie jar carries the armed cookie, under either name.\n *\n * Delimiter-aware rather than a substring test: a cookie named\n * `not_ai_annotate_armed`, or another cookie whose VALUE contains the name,\n * satisfies `includes` \u2014 and arming an annotation channel on a coincidence is\n * not a failure anyone would think to look for.\n */\nexport function isAnnotationArmed(cookie: string): boolean {\n return cookie\n .split(\";\")\n .some((entry) => {\n const trimmed = entry.trimStart();\n return ANNOTATION_ARMED_COOKIES.some((name) => trimmed.startsWith(`${name}=`));\n });\n}\n\n/**\n * The arming token from a URL's query string, under either name.\n *\n * Current name wins when both are present. They should never disagree \u2014 the\n * management app writes both from one value \u2014 but if they ever do, the one this\n * version of the protocol owns is the one to believe.\n */\nexport function readAnnotationToken(params: URLSearchParams): string | null {\n for (const name of ANNOTATION_TOKEN_PARAMS) {\n const value = params.get(name);\n if (value !== null && value.length > 0) return value;\n }\n return null;\n}\n"],
5
- "mappings": "AASO,IAAMA,EAAc,IAMdC,EAAyB,iCACzBC,EAA8B,cAmB9BC,EAAW,WACXC,EAAY,gBAoHlB,SAASC,EAAYC,EAA6D,CACvF,OAAOA,EAAO,YAAc,SAAW,SAAW,SACpD,CAgJA,SAASC,EAASC,EAA0B,CAC1C,GAAI,CACF,OAAO,KAAK,UAAUA,CAAO,GAAK,OAAOA,CAAO,CAClD,MAAQ,CACN,MAAO,kBACT,CACF,CAEO,SAASC,EAAiBC,EAAwBF,EAAwB,CAkB/E,QAAQ,MAAM,gBAAgBE,CAAI,2CAA2CH,EAASC,CAAO,CAAC,EAAE,CAClG,CAEA,IAAMG,EAAe,IAAI,IAAI,CAAC,kBAAmB,mBAAoB,eAAe,CAAC,EAQ9E,SAASC,EAAgBC,EAAsC,CACpE,GAAI,OAAOA,GAAS,UAAYA,IAAS,KAAM,MAAO,GACtD,IAAMC,EAAQD,EAA4B,KAC1C,OAAO,OAAOC,GAAS,UAAYH,EAAa,IAAIG,CAAI,CAC1D,CAUO,SAASC,EAAqBC,EAAwB,CAC3D,GAAI,CAACA,GAAUA,IAAW,IACxB,MAAM,IAAI,MACR,6GAEF,EAEF,OAAOA,CACT,CAkBO,IAAMC,EAAyB,cACzBC,EAA0B,oBA0B1BC,EAAsB,aAetBC,EAAmB,SA8BnBC,EAAmB,UAkDnBC,EAAyB,IAE/B,SAASC,EAAYC,EAAeN,EAAiC,CAC1E,MAAO,GAAGM,CAAI,IAAIF,CAAsB,gCAC1C,CAUO,SAASG,EAAcD,EAAsB,CAClD,MAAO,GAAGA,CAAI,mFAChB,CAwCO,IAAME,EAAgC,gBAChCC,EAAiC,sBA2CjCC,EAA0B,CACrCX,EACAS,CACF,EAGaG,EAA2B,CACtCX,EACAS,CACF,EAUO,SAASG,EAAkBC,EAAyB,CACzD,OAAOA,EACJ,MAAM,GAAG,EACT,KAAMC,GAAU,CACf,IAAMC,EAAUD,EAAM,UAAU,EAChC,OAAOH,EAAyB,KAAML,GAASS,EAAQ,WAAW,GAAGT,CAAI,GAAG,CAAC,CAC/E,CAAC,CACL,CASO,SAASU,EAAoBC,EAAwC,CAC1E,QAAWX,KAAQI,EAAyB,CAC1C,IAAMQ,EAAQD,EAAO,IAAIX,CAAI,EAC7B,GAAIY,IAAU,MAAQA,EAAM,OAAS,EAAG,OAAOA,CACjD,CACA,OAAO,IACT",
4
+ "sourcesContent": ["/**\n * The annotation postMessage protocol (A-36).\n *\n * Mirrors `docs/contracts/types.ts`. That file is the\n * cross-component contract; this is the runtime copy the product bundle ships,\n * because the product cannot import from a docs directory. Changing a shape\n * here is a change to both \u2014 say so in the PR.\n */\n\nexport const SDK_VERSION = \"1\";\n\n/**\n * A hosted document declares first-party annotation support with this exact\n * response header. It describes the BUILD, never a token, cookie or attempt.\n */\nexport const ANNOTATION_MODE_HEADER = \"x-weatherboard-annotation-mode\";\nexport const FIRST_PARTY_ANNOTATION_MODE = \"first-party\";\n\n/**\n * ===========================================================================\n * THE ATTRIBUTES \u2014 THE OTHER WIRE (A-186)\n * ===========================================================================\n *\n * These live in `protocol.ts`, not in `target.ts` where they are read, because\n * they are a contract between TWO PACKAGES that a consumer installs separately:\n * `@weatherboard/annotation-next` WRITES them at build time and this package\n * READS them at runtime. Two spellings of `data-src` is not a bug anybody\n * catches \u2014 the transform runs, the attributes appear, and every capture comes\n * back with no source ref at all, which is indistinguishable from the transform\n * not running.\n *\n * `annotation-next` imports these from `@weatherboard/annotation/protocol`\n * rather than declaring its own, which is why the subpath has no DOM in it: a\n * build tool importing the page SDK to learn two strings would be absurd.\n */\nexport const SRC_ATTR = \"data-src\";\nexport const NAME_ATTR = \"data-src-name\";\n\nexport interface SourceRef {\n file: string;\n line: number;\n column?: number;\n}\n\nexport interface BuildInfo {\n /** Mandatory. Feedback not pinned to a revision is ambiguous the moment someone merges. */\n gitSha: string;\n /**\n * Where this build came from.\n *\n * `\"development\"` was added in A-37, when the SDK was first mounted in a\n * real app and the two halves turned out not to agree: `resolveBuildInfo` in\n * `resolveBuildInfo` in the product's own Next config package \u2014 the module\n * that stamps the build-env variable, and the only producer of this field \u2014\n * emits\n * `production | preview | development`, mirroring `VERCEL_ENV`. This union\n * instead offered `\"staging\"`, which nothing produces: a staging deploy IS a\n * Vercel preview and reports itself as one. Widening rather than forcing the\n * mount to lie: a locally-annotated build calling itself a preview would put\n * someone's laptop in the corpus as though it were a deployment.\n */\n env: \"production\" | \"preview\" | \"staging\" | \"development\";\n branch?: string;\n /** Set when reviewing an agent's preview deploy, so feedback routes to that run's session. */\n previewRunId?: string;\n}\n\nexport interface ConsoleEntry {\n level: \"error\" | \"warn\";\n message: string;\n stack?: string;\n at: string;\n}\n\nexport interface NetworkEntry {\n url: string;\n method: string;\n status: number;\n at: string;\n}\n\nexport interface TargetInfo {\n /**\n * What the reviewer selected \u2014 one element, or an area (A-179).\n *\n * -------------------------------------------------------------------------\n * WHY THIS EXISTS RATHER THAN BEING INFERRED\n * -------------------------------------------------------------------------\n *\n * A region capture and an element capture are the same SHAPE: a bounding box,\n * a chain of source refs, a DOM path. Nothing in the values distinguishes\n * them, and the two mean opposite things about the chain \u2014 for an element it\n * is ANCESTORS, innermost first, so entry two contains entry one; for a\n * region it is SIBLINGS the rectangle happened to cross, which contain\n * nothing of each other.\n *\n * A reader that guesses will describe a region's siblings as a call-site\n * chain, which is a confident false statement about the page. `describeCapture`\n * hands that description to a model that writes acceptance criteria from it.\n *\n * -------------------------------------------------------------------------\n * WHY IT IS OPTIONAL, AND WHY ABSENT MEANS `element`\n * -------------------------------------------------------------------------\n *\n * The two halves of this protocol live in different repositories and deploy\n * independently (see the note on the legacy parameter names below). Every\n * capture in the store today, and every capture from a product bundle that\n * predates region selection, has no such field \u2014 and all of them are element\n * captures. Absent therefore has to mean `element`, or this field would\n * retroactively make the entire history ambiguous.\n *\n * Required-with-a-default would have the same effect and a worse failure: an\n * older bundle omits it, the type says it is there, and every reader believes\n * a value nobody sent.\n */\n selection?: \"element\" | \"region\";\n source?: SourceRef;\n /**\n * Every `data-src` from the clicked element up to the document root, innermost\n * first \u2014 an addition to the contract, and the reason is structural.\n *\n * Only host elements carry a ref (A-33), so `source` names the file that\n * *writes the markup*. For a composed design-system component that is\n * `MediaCard.tsx`, not the `GuideDetailCard.tsx` a human would say they\n * clicked. The chain is what lets the PM agent and the coding agent see both,\n * and pick the call site over the leaf when the feedback is about content\n * rather than the component itself.\n */\n sourceChain?: SourceRef[];\n componentName?: string;\n /** CSS selector fallback, for when no ancestor carries a ref at all. */\n domPath: string;\n boundingBox: { x: number; y: number; w: number; h: number };\n /** Truncated to 200 characters. */\n textContent?: string;\n}\n\n/**\n * What kind of capture this is, with the default applied once (A-189).\n *\n * `selection` is optional and **absent means `element`** \u2014 every capture taken\n * before A-179, and everything the managed product's live bundle emits today,\n * has no such field. Any other default would retroactively reclassify the whole\n * history as regions, silently.\n *\n * A function rather than a documented convention because the default is the\n * kind of thing two readers implement slightly differently and neither notices:\n * one writes `=== \"region\"`, another writes `?? \"element\"`, a third forgets and\n * treats `undefined` as falsy in a branch that meant something else. This is\n * the protocol's answer, and `compatibility.test.ts` replays every recorded\n * payload through it.\n */\nexport function selectionOf(target: Pick<TargetInfo, \"selection\">): \"element\" | \"region\" {\n return target.selection === \"region\" ? \"region\" : \"element\";\n}\n\nexport interface AnnotationPayload {\n schemaVersion: 1;\n capturedAt: string;\n build: BuildInfo;\n page: {\n url: string;\n /** The matched route pattern, not the resolved URL. */\n route: string;\n viewport: { w: number; h: number; dpr: number };\n userAgent: string;\n };\n target: TargetInfo;\n state: {\n consoleErrors: ConsoleEntry[];\n failedRequests: NetworkEntry[];\n featureFlags: Record<string, unknown>;\n };\n /**\n * `w`/`h` and `canvases` arrive with the in-page viewport capture (A-2385);\n * `canvases` counts the canvases in view and how many read back blank or\n * unreadable, so a black rectangle in the picture is explained, not silent.\n */\n screenshot?: {\n dataUrl: string;\n region: \"element\" | \"viewport\";\n w?: number;\n h?: number;\n canvases?: { total: number; blank: number; unreadable: number };\n };\n /** The human's words, verbatim. The parent frame fills this in; we never rewrite it. */\n comment: string;\n}\n\nexport type ParentToFrame =\n | { type: \"annotate:enable\" }\n | { type: \"annotate:disable\" }\n | { type: \"annotate:ping\" };\n\nexport type FrameToParent =\n | { type: \"annotate:ready\"; sdkVersion: string; build: BuildInfo }\n | { type: \"annotate:hover\"; target: TargetInfo }\n | { type: \"annotate:capture\"; payload: AnnotationPayload }\n | { type: \"annotate:cancel\" };\n\n/**\n * A message that got past both guards and matched no `case` (A-359).\n *\n * ===========================================================================\n * THE DEFECT\n * ===========================================================================\n *\n * `host.ts` and `sdk.ts` hold the two halves of this protocol, one `switch`\n * each, and neither had a `default`. Measured before the fix: adding\n * `| { type: \"annotate:probe\" }` to `ParentToFrame` and\n * `| { type: \"annotate:pong\" }` to `FrameToParent`, then running\n * `tsc --noEmit` in this package, gave exit 0 and zero errors. A message type\n * added to the union is dropped on the floor by whichever half was not\n * updated, and the two halves are the only things in the world that can\n * disagree about what a message means.\n *\n * ===========================================================================\n * WHY IT DOES NOT THROW, WHERE THE MANAGER'S TWO EQUIVALENTS DO\n * ===========================================================================\n *\n * This is the house pattern with one deliberate departure, and the departure is\n * the boundary rather than taste.\n *\n * Both switches run inside a `message` listener, reached from `postMessage`.\n * The host's listener runs in the management console over a frame that may be\n * serving anything; the SDK's runs in a product page we do not own. A throw\n * there does not propagate to a caller \u2014 there is no caller \u2014 it becomes an\n * uncaught error on somebody else's page, once per message. Any party that can\n * reach this branch can therefore reach it repeatedly, and the loudest\n * available answer would be handing them a way to fill a product's error\n * reporting with our noise.\n *\n * The narrower reason the throw would buy little: `isFrameMessage` and\n * `isParentMessage` gate on fixed sets of type strings, so a message an\n * outsider invents never reaches the switch at all. What DOES reach it is a\n * type in the guard's set with no `case` \u2014 which is our own two lists having\n * drifted apart, in this repository, in the commit that widened one of them.\n *\n * So the answer is: act on nothing, and say so. Acting on nothing is what a\n * trust boundary owes an input it does not understand; saying so is what makes\n * this different from the silent drop that was there before, which is\n * indistinguishable from the message never having been sent.\n *\n * `console.error` rather than a callback, because both call sites are inside\n * listeners with no error channel of their own, and because in the frame the\n * SDK's own `StateCollector` patches `console.error` \u2014 so the drift is\n * collected into the very next annotation payload, where somebody debugging\n * exactly this will already be looking.\n *\n * The type-level half of the guard is NOT here. It is `const unhandled: never`\n * in each `default` branch, which is what makes a widened union a compile\n * error; this function only makes the runtime half observable, and it is\n * exported so `exhaustive.test.ts` can call it. Both halves are pinned\n * separately, because deleting either leaves the other looking correct.\n */\n/**\n * `JSON.stringify` that cannot throw, for any input at all (A-359 cycle 2).\n *\n * ===========================================================================\n * WHY THIS IS NEEDED \u2014 THE DEFECT IT REPLACES\n * ===========================================================================\n *\n * `unhandledMessage` interpolated `JSON.stringify(message)` unguarded, and so\n * became the thing it was written to prevent. `postMessage` serialises with\n * the STRUCTURED CLONE algorithm, and structured clone PRESERVES CYCLES where\n * JSON cannot represent them \u2014 so `{a: {b: a}}` survives a `postMessage`\n * intact, arrives at that branch, and `JSON.stringify` throws `Converting\n * circular structure to JSON` from inside a `message` listener on a page this\n * SDK is a guest on, once per message, at the sender's discretion.\n *\n * Every word of the argument on `unhandledMessage` was correct, and the\n * implementation defeated it on its own terms. Both cases are pinned in\n * `exhaustive.test.ts` and both were confirmed RED before this existed.\n *\n * ===========================================================================\n * WHY NOT `describeArg`, WHICH DOES THIS ALREADY \u2014 TWO REASONS, ONE MEASURED\n * ===========================================================================\n *\n * `describeArg` in `state.ts` solves the same problem and its comment names\n * the same hazard, so reusing it was the first thing tried rather than a road\n * not taken. It was reverted for two reasons, and the second is the one that\n * decided it:\n *\n * 1. MEASURED, by running `node build.mjs` on both: reuse costs protocol\n * 869 -> 1008 (+139) and host 649 -> 793 (+144). This local version costs\n * +39 and +37. `describeArg` is built for console ARGUMENTS \u2014 strings,\n * Errors, a prototype walk for named objects \u2014 and almost none of that is\n * reachable for a wire message, so the extra 100 bytes per entry point buy\n * nothing here. In a package with a per-entry gzip budget that is not a\n * rounding error.\n * 2. THIS MODULE HAS NO IMPORTS AND THAT IS A PROPERTY WORTH KEEPING.\n * `protocol.ts` is the pure wire contract \u2014 it mirrors\n * `docs/contracts/types.ts`, `annotation-next` imports it so a build tool\n * can learn two strings without pulling in a DOM, and `state.ts` already\n * imports FROM it. Importing back the other way makes the contract depend\n * on the console-patching state collector and closes a module cycle that\n * is only invisible because `state.ts`'s side of it is `import type`.\n *\n * The cost of the choice, stated rather than left for somebody to find: there\n * are now two safe-stringify helpers in this package. They cannot drift in a\n * way that matters \u2014 each is a total function with one behaviour and its own\n * test \u2014 but if a third appears, that is the moment to put one in a module\n * both can depend on, rather than making the contract depend on the collector.\n *\n * The fallback is a constant, deliberately. Reaching for `String(message)` or\n * a constructor name in the `catch` is the obvious way to say something more\n * useful, and it is how this function would learn to throw again: the input\n * that got us here is one whose property access already threw.\n */\nfunction safeJson(message: unknown): string {\n try {\n return JSON.stringify(message) ?? String(message);\n } catch {\n return \"[unserialisable]\";\n }\n}\n\nexport function unhandledMessage(half: \"host\" | \"frame\", message: unknown): void {\n /**\n * `safeJson` RATHER THAN A BARE `JSON.stringify`, AND THAT IS THE WHOLE\n * DIFFERENCE BETWEEN THIS FUNCTION AND ITS FIRST DRAFT (A-359 cycle 2).\n *\n * The first draft interpolated `JSON.stringify(message)` unguarded, which\n * made this function do the thing it exists to avoid. The full argument, the\n * measurement, and why `describeArg` was tried and reverted are on\n * `safeJson` above rather than repeated here.\n *\n * Short on purpose too, and the shortness is measured rather than stylistic.\n * This package ships inside a product's bundle and this package's own\n * `build.mjs` enforces a gzip budget per entry point; the first draft of this\n * sentence was 230 characters and put `protocol`, `host` and `index` over\n * theirs at once. What it must still carry is which half, what arrived, and\n * that nothing was done with it \u2014 the last being the only thing that\n * distinguishes this from the silent drop it replaced.\n */\n console.error(`[annotation] ${half}: protocol drift, nothing was acted on: ${safeJson(message)}`);\n}\n\nconst PARENT_TYPES = new Set([\"annotate:enable\", \"annotate:disable\", \"annotate:ping\"]);\n\n/**\n * Is this a message we recognise?\n *\n * Origin is checked separately and first \u2014 a well-formed message from the wrong\n * origin is the case this guard must not be trusted to catch.\n */\nexport function isParentMessage(data: unknown): data is ParentToFrame {\n if (typeof data !== \"object\" || data === null) return false;\n const type = (data as { type?: unknown }).type;\n return typeof type === \"string\" && PARENT_TYPES.has(type);\n}\n\n/**\n * Reject wildcards outright rather than treating them as \"any origin\".\n *\n * `postMessage(msg, \"*\")` broadcasts the payload to whatever happens to be\n * framing us, and an annotation payload carries page content, console errors and\n * failed request URLs. The spec's rule is no wildcards in either direction; this\n * makes it impossible to configure one by accident.\n */\nexport function assertConcreteOrigin(origin: string): string {\n if (!origin || origin === \"*\") {\n throw new Error(\n \"[annotation] a concrete parent origin is required; '*' would broadcast \" +\n \"annotation payloads to any embedder.\",\n );\n }\n return origin;\n}\n\n/**\n * The query parameter that arms the SDK in a managed product, and the cookie\n * that records it.\n *\n * THESE LIVE IN THE PROTOCOL BECAUSE THE TWO HALVES ARE NOW IN DIFFERENT\n * REPOSITORIES. The managed product's middleware looks for the parameter and\n * sets the cookie; the management app appends the parameter and the SDK reads\n * the cookie. While both halves were one monorepo, a test could read the other\n * side's source and assert the strings matched \u2014 that gate does not survive a\n * repository split, and a mismatch produces no error at all: the frame loads,\n * the cookie is never set, the SDK never boots, and the reviewer sees \"waiting\n * for the page to announce itself\" with nothing to go on.\n *\n * So they stop being two spellings that agree and become one exported\n * constant. A managed product that imports this package cannot drift from it.\n */\nexport const ANNOTATION_TOKEN_PARAM = \"ai_annotate\";\nexport const ANNOTATION_ARMED_COOKIE = \"ai_annotate_armed\";\n\n/**\n * The CAPTURE token's query parameter (A-240).\n *\n * -------------------------------------------------------------------------\n * WHY IT IS HERE AND NOT WHERE IT IS WRITTEN\n * -------------------------------------------------------------------------\n *\n * A second name on the same wire, and a second credential \u2014 see\n * `docs/plans/first-party-annotation.md` \u00A7 *Authentication*. `ai_annotate`\n * answers *should this page offer an annotation UI at all*; this one answers\n * *may this capture become an issue*. Different secrets, different lifetimes,\n * different blast radii, and deliberately not folded into one token.\n *\n * It lives beside `ANNOTATION_TOKEN_PARAM` for that constant's own reason,\n * stated at length above: the console WRITES it into a deep link and the\n * product's bundle READS it, the two halves ship from different repositories,\n * and a mismatch produces no error anywhere \u2014 the reviewer writes a post-it,\n * clicks send, and the ingest rejects an unsigned capture. One exported\n * constant is the only thing that makes those two spellings unable to drift.\n *\n * It has no legacy spelling because it has never had another one: nothing has\n * shipped it yet. It is exported here BEFORE its writer needs it precisely so\n * the writer never has a reason to spell it itself.\n */\nexport const CAPTURE_TOKEN_PARAM = \"ai_capture\";\n\n/**\n * The run under review, when the console knows of one (A-241).\n *\n * Third name on the same wire, here for the reason the two above are: the\n * console writes it and the product's bundle reads it, from two repositories.\n * `apps/manager/src/lib/request-changes.ts` spells it itself today and its own\n * comment asks for exactly this \u2014 the constant to move into the package so the\n * writer has no reason to spell it. **That deletion is not this slice's**\n * (A-243/A-244 are merged and settled), so for now there are two definitions of\n * one string, and `protocol.test.ts` is the only thing standing between them\n * and a silent divergence. Nothing about it is signed: the ingest already\n * treats it as attacker-supplied text and files on it rather than routing on it.\n */\nexport const REVIEW_RUN_PARAM = \"ai_run\";\n\n/**\n * The READ token's query parameter (A-277).\n *\n * ===========================================================================\n * WHY THE MARKER LAYER GETS ITS OWN CREDENTIAL AND NOT `ai_capture`\n * ===========================================================================\n *\n * Fourth name on the same wire, and the reason it is a fourth is A-276's\n * disclosure decision rather than tidiness. The capture token is minted for\n * WRITING and lives four hours so a reviewer can work through a session; reusing\n * it for the read would make one leaked deep link a write capability AND a read\n * capability over every reviewer's comments on that origin for the same window.\n * The scope is a signed field, `verifyCaptureToken` requires an expectation at\n * every call site, and the read endpoint refuses a write claim \u2014 so handing\n * `ai_capture` to the reader does not degrade to a read, it fails.\n *\n * The read claim's TTL is ONE hour rather than four (`READ_TOKEN_TTL_S`), which\n * is the practical consequence a reader of this constant should know: the\n * toolbar outlives the markers, so a reviewer who leaves a tab open all\n * afternoon will find the count line saying it cannot read before they find the\n * Send button broken. That is the intended ordering \u2014 the shorter credential is\n * the one that discloses other people's words.\n *\n * Exported here for the reason the three above are: the console writes it into a\n * deep link and the product's bundle reads it, from two repositories, and a\n * mismatch produces no error anywhere \u2014 just a page with no markers, which is\n * indistinguishable from nine other causes.\n */\nexport const READ_TOKEN_PARAM = \"ai_read\";\n\n/**\n * The arming cookie, as a `Set-Cookie` value (A-241).\n *\n * ===========================================================================\n * IT GOT SIMPLER BY MOVING FIRST-PARTY, AND THAT IS THE WHOLE POINT\n * ===========================================================================\n *\n * Framed, this had to be `SameSite=None; Secure` with no `Partitioned` \u2014 a\n * genuine cross-site cookie, which A-211 records would have broken on its own\n * under Chrome's third-party cookie work, independently of the auth problem\n * that killed the frame. Top-level at the product's own origin it is an\n * ordinary cookie and none of that applies.\n *\n * Each attribute, and why:\n *\n * - **`SameSite=Lax`.** The reviewer arrives by clicking *Request changes* in\n * the console, which is a top-level cross-site GET navigation \u2014 the one case\n * `Lax` still sends on. `Strict` would withhold the cookie on that very first\n * render, so the toolbar would be missing on the page the link opened and\n * appear only after an internal click; that reads as a broken deploy.\n * - **`Secure`.** It is a marker rather than a credential, but a marker that\n * travels in clear is a marker an attacker on the path can set.\n * - **`Path=/`.** Arming survives the reviewer navigating the whole app, which\n * is the point of a cookie rather than a URL parameter.\n * - **No `Max-Age` / `Expires`.** Session-scoped: closing the tab disarms.\n *\n * ===========================================================================\n * WHAT IS *NOT* HERE: `HttpOnly`, AND THE TOKEN\n * ===========================================================================\n *\n * No `HttpOnly`, deliberately. Page script both READS this (`isAnnotationArmed`\n * decides whether a toolbar exists) and CLEARS it (*Done* disarms). An\n * `HttpOnly` arming cookie makes *Done* impossible from the page, which is the\n * one control the reviewer has.\n *\n * That is affordable only because THE VALUE IS A MARKER AND NEVER THE TOKEN.\n * The value is a constant and there is no argument that supplies one: the\n * middleware compares the URL parameter against its secret and then calls this,\n * and what it stores is *yes*, not *what was presented*. The single parameter\n * is the cookie's NAME, and it exists only so a product mid-migration can write\n * the legacy spelling \u2014 it is not a value slot wearing a different label, and\n * `arming.test.ts` pins which side of the `=` it lands on.\n *\n * This is a shape argument, not a guarantee about callers. Nothing stops a\n * determined caller passing a secret as the name; what the signature removes is\n * the ACCIDENT \u2014 the middleware author with a verified token in hand and one\n * parameter available, reaching for the obvious.\n */\nexport const ANNOTATION_ARMED_VALUE = \"1\";\n\nexport function armedCookie(name: string = ANNOTATION_ARMED_COOKIE): string {\n return `${name}=${ANNOTATION_ARMED_VALUE}; Path=/; SameSite=Lax; Secure`;\n}\n\n/**\n * The same cookie, expired \u2014 what *Done* and a disarm write.\n *\n * `Max-Age=0` AND an `Expires` in the past, because they are read by different\n * things and the pair is what every browser honours. The path must match the\n * one set above or the browser stores a second cookie and the first survives \u2014\n * a *Done* button that does nothing and reports success.\n */\nexport function clearedCookie(name: string): string {\n return `${name}=; Path=/; SameSite=Lax; Secure; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;\n}\n\n/**\n * The names these used to have (A-98).\n *\n * -------------------------------------------------------------------------\n * WHY THE RENAME, AND WHY IT COULD NOT JUST BE DONE\n * -------------------------------------------------------------------------\n *\n * They were `pits_annotate` and `pits_annotate_armed` \u2014 one managed product's\n * initialism, in a contract every managed product's bundle has to implement.\n * Onboarding a second product meant asking an unrelated codebase to adopt the\n * first product's name in its cookies and its query strings. That is the bug\n * A-98 is about, and it is a bug in a wire protocol rather than in a variable\n * name, which is what makes it expensive.\n *\n * The two halves live in DIFFERENT REPOSITORIES and deploy independently. A\n * clean rename is therefore a breaking change to every product bundle\n * simultaneously, and its failure mode is silence: the frame loads, the cookie\n * is never set, the SDK never boots, and the reviewer sees \"waiting for the\n * page to announce itself\" with nothing to go on. Nothing throws, nothing logs,\n * and the natural reading is that the agent broke the site.\n *\n * -------------------------------------------------------------------------\n * THE MIGRATION: READ BOTH, WRITE BOTH, THEN STOP WRITING THE OLD ONE\n * -------------------------------------------------------------------------\n *\n * 1. **Now.** Every reader accepts either name. Every writer emits BOTH, so a\n * product still running the old bundle arms on the legacy name and one\n * running the new bundle arms on the new one. Deploy order stops mattering,\n * which is the whole point \u2014 there is no window in which a reviewer sees the\n * silent failure above.\n * 2. **After every managed product's bundle is on this version** (A-102). Drop\n * the legacy names from the writers, then from the readers. Two steps, not\n * one: a reader that stops accepting the old name before the writers stop\n * emitting it re-creates the outage in the other direction.\n *\n * The legacy names are exported rather than inlined so the deletion in step 2\n * is `git grep LEGACY_` rather than an archaeology exercise.\n */\nexport const LEGACY_ANNOTATION_TOKEN_PARAM = \"pits_annotate\";\nexport const LEGACY_ANNOTATION_ARMED_COOKIE = \"pits_annotate_armed\";\n\n/**\n * ===========================================================================\n * AND THE NAMES ARE NOT CHANGING AGAIN FOR THE PUBLISHED PACKAGE (A-184)\n * ===========================================================================\n *\n * When this becomes `@weatherboard/annotation` the obvious next thought is that\n * the wire names should match the package \u2014 `weatherboard_annotate`. They\n * should not, and the reason is the migration described above rather than\n * taste.\n *\n * That migration is STILL IN FLIGHT. Readers accept both spellings; writers\n * emit both; step 2 waits on every managed product's bundle being current.\n * A third spelling introduced now does not replace the second, it joins it:\n * every reader accepts three names, every writer emits three, and the window in\n * which a product can be on any of them widens instead of closing.\n *\n * The cost is not the code. It is that each rename buys another instance of the\n * failure this file exists to prevent \u2014 the frame loads, the cookie is never\n * set, the SDK never boots, and the reviewer sees \"waiting for the page to\n * announce itself\" with nothing to go on. Twice is a migration. Three times is\n * a habit, and the third one would be paid by consumers who never asked for\n * either.\n *\n * `ai_annotate` is already product-neutral, which was the entire point of A-98.\n * A published package needs names that name no product; it does not need names\n * that name the package. Nobody reading a query string cares which npm scope\n * the library came from.\n *\n * The one real objection is collision: `ai_` is a common prefix and some other\n * tool could plausibly use it. That is survivable by construction \u2014 arming\n * requires the parameter to carry a token the product compares exactly, so a\n * coincidental `?ai_annotate=` from an unrelated tool arms nothing. A colliding\n * COOKIE cannot false-positive either; `isAnnotationArmed` matches on the\n * delimiter rather than by substring, for exactly this reason.\n *\n * If a rename is ever genuinely warranted, it happens ONCE, after step 2 has\n * landed and the reader accepts one name again \u2014 not layered on top of an\n * unfinished one.\n */\n\n/** Both spellings of the query parameter, current first. */\nexport const ANNOTATION_TOKEN_PARAMS = [\n ANNOTATION_TOKEN_PARAM,\n LEGACY_ANNOTATION_TOKEN_PARAM,\n] as const;\n\n/** Both spellings of the cookie, current first. */\nexport const ANNOTATION_ARMED_COOKIES = [\n ANNOTATION_ARMED_COOKIE,\n LEGACY_ANNOTATION_ARMED_COOKIE,\n] as const;\n\n/**\n * Whether a cookie jar carries the armed cookie, under either name.\n *\n * Delimiter-aware rather than a substring test: a cookie named\n * `not_ai_annotate_armed`, or another cookie whose VALUE contains the name,\n * satisfies `includes` \u2014 and arming an annotation channel on a coincidence is\n * not a failure anyone would think to look for.\n */\nexport function isAnnotationArmed(cookie: string): boolean {\n return cookie\n .split(\";\")\n .some((entry) => {\n const trimmed = entry.trimStart();\n return ANNOTATION_ARMED_COOKIES.some((name) => trimmed.startsWith(`${name}=`));\n });\n}\n\n/**\n * The arming token from a URL's query string, under either name.\n *\n * Current name wins when both are present. They should never disagree \u2014 the\n * management app writes both from one value \u2014 but if they ever do, the one this\n * version of the protocol owns is the one to believe.\n */\nexport function readAnnotationToken(params: URLSearchParams): string | null {\n for (const name of ANNOTATION_TOKEN_PARAMS) {\n const value = params.get(name);\n if (value !== null && value.length > 0) return value;\n }\n return null;\n}\n"],
5
+ "mappings": "AASO,IAAMA,EAAc,IAMdC,EAAyB,iCACzBC,EAA8B,cAmB9BC,EAAW,WACXC,EAAY,gBAoHlB,SAASC,EAAYC,EAA6D,CACvF,OAAOA,EAAO,YAAc,SAAW,SAAW,SACpD,CA2JA,SAASC,EAASC,EAA0B,CAC1C,GAAI,CACF,OAAO,KAAK,UAAUA,CAAO,GAAK,OAAOA,CAAO,CAClD,MAAQ,CACN,MAAO,kBACT,CACF,CAEO,SAASC,EAAiBC,EAAwBF,EAAwB,CAkB/E,QAAQ,MAAM,gBAAgBE,CAAI,2CAA2CH,EAASC,CAAO,CAAC,EAAE,CAClG,CAEA,IAAMG,EAAe,IAAI,IAAI,CAAC,kBAAmB,mBAAoB,eAAe,CAAC,EAQ9E,SAASC,EAAgBC,EAAsC,CACpE,GAAI,OAAOA,GAAS,UAAYA,IAAS,KAAM,MAAO,GACtD,IAAMC,EAAQD,EAA4B,KAC1C,OAAO,OAAOC,GAAS,UAAYH,EAAa,IAAIG,CAAI,CAC1D,CAUO,SAASC,EAAqBC,EAAwB,CAC3D,GAAI,CAACA,GAAUA,IAAW,IACxB,MAAM,IAAI,MACR,6GAEF,EAEF,OAAOA,CACT,CAkBO,IAAMC,EAAyB,cACzBC,EAA0B,oBA0B1BC,EAAsB,aAetBC,EAAmB,SA8BnBC,EAAmB,UAkDnBC,EAAyB,IAE/B,SAASC,EAAYC,EAAeN,EAAiC,CAC1E,MAAO,GAAGM,CAAI,IAAIF,CAAsB,gCAC1C,CAUO,SAASG,EAAcD,EAAsB,CAClD,MAAO,GAAGA,CAAI,mFAChB,CAwCO,IAAME,EAAgC,gBAChCC,EAAiC,sBA2CjCC,EAA0B,CACrCX,EACAS,CACF,EAGaG,EAA2B,CACtCX,EACAS,CACF,EAUO,SAASG,EAAkBC,EAAyB,CACzD,OAAOA,EACJ,MAAM,GAAG,EACT,KAAMC,GAAU,CACf,IAAMC,EAAUD,EAAM,UAAU,EAChC,OAAOH,EAAyB,KAAML,GAASS,EAAQ,WAAW,GAAGT,CAAI,GAAG,CAAC,CAC/E,CAAC,CACL,CASO,SAASU,EAAoBC,EAAwC,CAC1E,QAAWX,KAAQI,EAAyB,CAC1C,IAAMQ,EAAQD,EAAO,IAAIX,CAAI,EAC7B,GAAIY,IAAU,MAAQA,EAAM,OAAS,EAAG,OAAOA,CACjD,CACA,OAAO,IACT",
6
6
  "names": ["SDK_VERSION", "ANNOTATION_MODE_HEADER", "FIRST_PARTY_ANNOTATION_MODE", "SRC_ATTR", "NAME_ATTR", "selectionOf", "target", "safeJson", "message", "unhandledMessage", "half", "PARENT_TYPES", "isParentMessage", "data", "type", "assertConcreteOrigin", "origin", "ANNOTATION_TOKEN_PARAM", "ANNOTATION_ARMED_COOKIE", "CAPTURE_TOKEN_PARAM", "REVIEW_RUN_PARAM", "READ_TOKEN_PARAM", "ANNOTATION_ARMED_VALUE", "armedCookie", "name", "clearedCookie", "LEGACY_ANNOTATION_TOKEN_PARAM", "LEGACY_ANNOTATION_ARMED_COOKIE", "ANNOTATION_TOKEN_PARAMS", "ANNOTATION_ARMED_COOKIES", "isAnnotationArmed", "cookie", "entry", "trimmed", "readAnnotationToken", "params", "value"]
7
7
  }
@@ -1,10 +1,16 @@
1
1
  /**
2
2
  * Screenshot capture for the annotation payload (A-31).
3
3
  *
4
- * WHAT THIS ACTUALLY CAPTURES — READ THIS BEFORE BELIEVING THE FIELD NAME.
5
- * This is not a page rasteriser. It captures the bitmap of a single
4
+ * A-2385 CHANGED WHAT THIS CAPTURES FIRST: the VIEWPORT, rendered in the page
5
+ * by `page-capture.ts` (with its one approved dependency, loaded on demand).
6
+ * Everything below this paragraph describes the FALLBACK, which runs when the
7
+ * page render is unavailable, fails or times out, and which was the whole of
8
+ * this module until then.
9
+ *
10
+ * WHAT THE FALLBACK CAPTURES — READ THIS BEFORE BELIEVING THE FIELD NAME.
11
+ * It is not a page rasteriser. It captures the bitmap of a single
6
12
  * `<img>`, `<canvas>` or `<video>` at or around the clicked element, and
7
- * nothing else. Click a heading and the payload has no screenshot.
13
+ * nothing else. Click a heading and the fallback has no screenshot.
8
14
  *
9
15
  * WHY NOT html2canvas, WHICH THE SPEC SUGGESTS. `spec/02` offers html2canvas or
10
16
  * "`element.toDataURL` via an offscreen canvas where feasible". html2canvas is a
@@ -31,6 +37,23 @@
31
37
  * with `screenshot` absent from an otherwise complete payload, never with a
32
38
  * capture the reviewer loses.
33
39
  */
40
+ import type { CanvasRead, CanvasReadout, PageRenderer } from "./page-capture.cjs";
41
+ /** Widest viewport image we send, in pixels (A-2385). A 1440px laptop at 2x renders at 1600. */
42
+ export declare const MAX_VIEWPORT_WIDTH = 1600;
43
+ /** The decoded viewport image, not its data URL: what Linear stores (A-2385). */
44
+ export declare const MAX_VIEWPORT_IMAGE_BYTES: number;
45
+ /**
46
+ * The longest data URL a viewport screenshot can be. The manager's size limits
47
+ * are derived from this, so the client cap and the server cap are one number.
48
+ */
49
+ export declare const MAX_VIEWPORT_DATA_URL_LENGTH: number;
50
+ /**
51
+ * How long the page render may take before the element bitmap is used
52
+ * instead. Rendering clones the DOM and inlines its images and fonts, which on
53
+ * a heavy page is a second or two; the composer is open meanwhile, so the
54
+ * reviewer is not waiting on it.
55
+ */
56
+ export declare const VIEWPORT_TIMEOUT_MS = 4000;
34
57
  /** The canvas surface this module needs. Narrow so tests need no browser. */
35
58
  export interface CanvasLike {
36
59
  width: number;
@@ -67,6 +90,11 @@ export interface CaptureCandidate {
67
90
  export type Screenshot = {
68
91
  dataUrl: string;
69
92
  region: "element" | "viewport";
93
+ /** Pixel size of the encoded image (viewport captures, A-2385). */
94
+ w?: number;
95
+ h?: number;
96
+ /** What the canvases in the viewport read back as (viewport captures, A-2385). */
97
+ canvases?: CanvasReadout;
70
98
  };
71
99
  /**
72
100
  * The byte budget for the encoded data URL.
@@ -118,6 +146,18 @@ export interface ScreenshotOptions {
118
146
  * reachable from a fake DOM object alone.
119
147
  */
120
148
  createCanvas?: () => CanvasLike | null;
149
+ /**
150
+ * Render the viewport (A-2385). On by default; `false` keeps only the element
151
+ * bitmap below, which is what this module did before.
152
+ */
153
+ page?: boolean;
154
+ /** Viewport image caps: width in pixels and decoded bytes. */
155
+ maxViewportWidth?: number;
156
+ maxViewportBytes?: number;
157
+ viewportTimeoutMs?: number;
158
+ /** Injected so tests need neither a browser nor the library. */
159
+ loadRenderer?: () => Promise<PageRenderer>;
160
+ readCanvas?: (canvas: unknown) => CanvasRead;
121
161
  }
122
162
  interface ResolvedOptions {
123
163
  enabled: boolean;
@@ -125,6 +165,15 @@ interface ResolvedOptions {
125
165
  maxEdge: number;
126
166
  timeoutMs: number;
127
167
  createCanvas: () => CanvasLike | null;
168
+ /** The document to render, or null where there is none (a test, a server). */
169
+ doc: Document | null;
170
+ page: boolean;
171
+ maxViewportWidth: number;
172
+ maxViewportBytes: number;
173
+ viewportTimeoutMs: number;
174
+ /** Null for the real library / the real canvas read. */
175
+ loadRenderer: (() => Promise<PageRenderer>) | null;
176
+ readCanvas: ((canvas: unknown) => CanvasRead) | null;
128
177
  }
129
178
  export declare function resolveScreenshotOptions(options: ScreenshotOptions | false | undefined, doc?: Document): ResolvedOptions;
130
179
  export declare function isMediaElement(el: CaptureCandidate | null | undefined): boolean;
@@ -162,10 +211,10 @@ export declare function fitWithin(size: {
162
211
  */
163
212
  export declare function captureScreenshotSync(el: CaptureCandidate | null, options: ResolvedOptions): Screenshot | null;
164
213
  /**
165
- * The entry point the SDK calls. Resolves to a screenshot or to null, within
166
- * `timeoutMs`, and never rejects.
214
+ * The entry point the SDK calls. Resolves to the viewport, or failing that to
215
+ * the element bitmap within `timeoutMs`, or to null, and never rejects.
167
216
  */
168
- export declare function captureScreenshot(el: CaptureCandidate | null, options: ResolvedOptions): Promise<Screenshot | null>;
217
+ export declare function captureScreenshot(el: CaptureCandidate | null, options: ResolvedOptions, ignore?: ((el: Element) => boolean) | null): Promise<Screenshot | null>;
169
218
  /**
170
219
  * Merge a capture into a payload, or hand the payload back untouched.
171
220
  *
@@ -176,7 +225,7 @@ export declare function captureScreenshot(el: CaptureCandidate | null, options:
176
225
  * rather than set to `undefined` (which `JSON.stringify` drops anyway, but
177
226
  * which reads as "we tried and got nothing" to anyone inspecting the object).
178
227
  */
179
- export declare function attachScreenshot<T extends object>(payload: T, el: CaptureCandidate | null, options: ResolvedOptions): Promise<T & {
228
+ export declare function attachScreenshot<T extends object>(payload: T, el: CaptureCandidate | null, options: ResolvedOptions, ignore?: ((el: Element) => boolean) | null): Promise<T & {
180
229
  screenshot?: Screenshot;
181
230
  }>;
182
231
  export {};
@@ -1,10 +1,16 @@
1
1
  /**
2
2
  * Screenshot capture for the annotation payload (A-31).
3
3
  *
4
- * WHAT THIS ACTUALLY CAPTURES — READ THIS BEFORE BELIEVING THE FIELD NAME.
5
- * This is not a page rasteriser. It captures the bitmap of a single
4
+ * A-2385 CHANGED WHAT THIS CAPTURES FIRST: the VIEWPORT, rendered in the page
5
+ * by `page-capture.ts` (with its one approved dependency, loaded on demand).
6
+ * Everything below this paragraph describes the FALLBACK, which runs when the
7
+ * page render is unavailable, fails or times out, and which was the whole of
8
+ * this module until then.
9
+ *
10
+ * WHAT THE FALLBACK CAPTURES — READ THIS BEFORE BELIEVING THE FIELD NAME.
11
+ * It is not a page rasteriser. It captures the bitmap of a single
6
12
  * `<img>`, `<canvas>` or `<video>` at or around the clicked element, and
7
- * nothing else. Click a heading and the payload has no screenshot.
13
+ * nothing else. Click a heading and the fallback has no screenshot.
8
14
  *
9
15
  * WHY NOT html2canvas, WHICH THE SPEC SUGGESTS. `spec/02` offers html2canvas or
10
16
  * "`element.toDataURL` via an offscreen canvas where feasible". html2canvas is a
@@ -31,6 +37,23 @@
31
37
  * with `screenshot` absent from an otherwise complete payload, never with a
32
38
  * capture the reviewer loses.
33
39
  */
40
+ import type { CanvasRead, CanvasReadout, PageRenderer } from "./page-capture.mjs";
41
+ /** Widest viewport image we send, in pixels (A-2385). A 1440px laptop at 2x renders at 1600. */
42
+ export declare const MAX_VIEWPORT_WIDTH = 1600;
43
+ /** The decoded viewport image, not its data URL: what Linear stores (A-2385). */
44
+ export declare const MAX_VIEWPORT_IMAGE_BYTES: number;
45
+ /**
46
+ * The longest data URL a viewport screenshot can be. The manager's size limits
47
+ * are derived from this, so the client cap and the server cap are one number.
48
+ */
49
+ export declare const MAX_VIEWPORT_DATA_URL_LENGTH: number;
50
+ /**
51
+ * How long the page render may take before the element bitmap is used
52
+ * instead. Rendering clones the DOM and inlines its images and fonts, which on
53
+ * a heavy page is a second or two; the composer is open meanwhile, so the
54
+ * reviewer is not waiting on it.
55
+ */
56
+ export declare const VIEWPORT_TIMEOUT_MS = 4000;
34
57
  /** The canvas surface this module needs. Narrow so tests need no browser. */
35
58
  export interface CanvasLike {
36
59
  width: number;
@@ -67,6 +90,11 @@ export interface CaptureCandidate {
67
90
  export type Screenshot = {
68
91
  dataUrl: string;
69
92
  region: "element" | "viewport";
93
+ /** Pixel size of the encoded image (viewport captures, A-2385). */
94
+ w?: number;
95
+ h?: number;
96
+ /** What the canvases in the viewport read back as (viewport captures, A-2385). */
97
+ canvases?: CanvasReadout;
70
98
  };
71
99
  /**
72
100
  * The byte budget for the encoded data URL.
@@ -118,6 +146,18 @@ export interface ScreenshotOptions {
118
146
  * reachable from a fake DOM object alone.
119
147
  */
120
148
  createCanvas?: () => CanvasLike | null;
149
+ /**
150
+ * Render the viewport (A-2385). On by default; `false` keeps only the element
151
+ * bitmap below, which is what this module did before.
152
+ */
153
+ page?: boolean;
154
+ /** Viewport image caps: width in pixels and decoded bytes. */
155
+ maxViewportWidth?: number;
156
+ maxViewportBytes?: number;
157
+ viewportTimeoutMs?: number;
158
+ /** Injected so tests need neither a browser nor the library. */
159
+ loadRenderer?: () => Promise<PageRenderer>;
160
+ readCanvas?: (canvas: unknown) => CanvasRead;
121
161
  }
122
162
  interface ResolvedOptions {
123
163
  enabled: boolean;
@@ -125,6 +165,15 @@ interface ResolvedOptions {
125
165
  maxEdge: number;
126
166
  timeoutMs: number;
127
167
  createCanvas: () => CanvasLike | null;
168
+ /** The document to render, or null where there is none (a test, a server). */
169
+ doc: Document | null;
170
+ page: boolean;
171
+ maxViewportWidth: number;
172
+ maxViewportBytes: number;
173
+ viewportTimeoutMs: number;
174
+ /** Null for the real library / the real canvas read. */
175
+ loadRenderer: (() => Promise<PageRenderer>) | null;
176
+ readCanvas: ((canvas: unknown) => CanvasRead) | null;
128
177
  }
129
178
  export declare function resolveScreenshotOptions(options: ScreenshotOptions | false | undefined, doc?: Document): ResolvedOptions;
130
179
  export declare function isMediaElement(el: CaptureCandidate | null | undefined): boolean;
@@ -162,10 +211,10 @@ export declare function fitWithin(size: {
162
211
  */
163
212
  export declare function captureScreenshotSync(el: CaptureCandidate | null, options: ResolvedOptions): Screenshot | null;
164
213
  /**
165
- * The entry point the SDK calls. Resolves to a screenshot or to null, within
166
- * `timeoutMs`, and never rejects.
214
+ * The entry point the SDK calls. Resolves to the viewport, or failing that to
215
+ * the element bitmap within `timeoutMs`, or to null, and never rejects.
167
216
  */
168
- export declare function captureScreenshot(el: CaptureCandidate | null, options: ResolvedOptions): Promise<Screenshot | null>;
217
+ export declare function captureScreenshot(el: CaptureCandidate | null, options: ResolvedOptions, ignore?: ((el: Element) => boolean) | null): Promise<Screenshot | null>;
169
218
  /**
170
219
  * Merge a capture into a payload, or hand the payload back untouched.
171
220
  *
@@ -176,7 +225,7 @@ export declare function captureScreenshot(el: CaptureCandidate | null, options:
176
225
  * rather than set to `undefined` (which `JSON.stringify` drops anyway, but
177
226
  * which reads as "we tried and got nothing" to anyone inspecting the object).
178
227
  */
179
- export declare function attachScreenshot<T extends object>(payload: T, el: CaptureCandidate | null, options: ResolvedOptions): Promise<T & {
228
+ export declare function attachScreenshot<T extends object>(payload: T, el: CaptureCandidate | null, options: ResolvedOptions, ignore?: ((el: Element) => boolean) | null): Promise<T & {
180
229
  screenshot?: Screenshot;
181
230
  }>;
182
231
  export {};
@@ -1,10 +1,16 @@
1
1
  /**
2
2
  * Screenshot capture for the annotation payload (A-31).
3
3
  *
4
- * WHAT THIS ACTUALLY CAPTURES — READ THIS BEFORE BELIEVING THE FIELD NAME.
5
- * This is not a page rasteriser. It captures the bitmap of a single
4
+ * A-2385 CHANGED WHAT THIS CAPTURES FIRST: the VIEWPORT, rendered in the page
5
+ * by `page-capture.ts` (with its one approved dependency, loaded on demand).
6
+ * Everything below this paragraph describes the FALLBACK, which runs when the
7
+ * page render is unavailable, fails or times out, and which was the whole of
8
+ * this module until then.
9
+ *
10
+ * WHAT THE FALLBACK CAPTURES — READ THIS BEFORE BELIEVING THE FIELD NAME.
11
+ * It is not a page rasteriser. It captures the bitmap of a single
6
12
  * `<img>`, `<canvas>` or `<video>` at or around the clicked element, and
7
- * nothing else. Click a heading and the payload has no screenshot.
13
+ * nothing else. Click a heading and the fallback has no screenshot.
8
14
  *
9
15
  * WHY NOT html2canvas, WHICH THE SPEC SUGGESTS. `spec/02` offers html2canvas or
10
16
  * "`element.toDataURL` via an offscreen canvas where feasible". html2canvas is a
@@ -31,6 +37,23 @@
31
37
  * with `screenshot` absent from an otherwise complete payload, never with a
32
38
  * capture the reviewer loses.
33
39
  */
40
+ import type { CanvasRead, CanvasReadout, PageRenderer } from "./page-capture.js";
41
+ /** Widest viewport image we send, in pixels (A-2385). A 1440px laptop at 2x renders at 1600. */
42
+ export declare const MAX_VIEWPORT_WIDTH = 1600;
43
+ /** The decoded viewport image, not its data URL: what Linear stores (A-2385). */
44
+ export declare const MAX_VIEWPORT_IMAGE_BYTES: number;
45
+ /**
46
+ * The longest data URL a viewport screenshot can be. The manager's size limits
47
+ * are derived from this, so the client cap and the server cap are one number.
48
+ */
49
+ export declare const MAX_VIEWPORT_DATA_URL_LENGTH: number;
50
+ /**
51
+ * How long the page render may take before the element bitmap is used
52
+ * instead. Rendering clones the DOM and inlines its images and fonts, which on
53
+ * a heavy page is a second or two; the composer is open meanwhile, so the
54
+ * reviewer is not waiting on it.
55
+ */
56
+ export declare const VIEWPORT_TIMEOUT_MS = 4000;
34
57
  /** The canvas surface this module needs. Narrow so tests need no browser. */
35
58
  export interface CanvasLike {
36
59
  width: number;
@@ -67,6 +90,11 @@ export interface CaptureCandidate {
67
90
  export type Screenshot = {
68
91
  dataUrl: string;
69
92
  region: "element" | "viewport";
93
+ /** Pixel size of the encoded image (viewport captures, A-2385). */
94
+ w?: number;
95
+ h?: number;
96
+ /** What the canvases in the viewport read back as (viewport captures, A-2385). */
97
+ canvases?: CanvasReadout;
70
98
  };
71
99
  /**
72
100
  * The byte budget for the encoded data URL.
@@ -118,6 +146,18 @@ export interface ScreenshotOptions {
118
146
  * reachable from a fake DOM object alone.
119
147
  */
120
148
  createCanvas?: () => CanvasLike | null;
149
+ /**
150
+ * Render the viewport (A-2385). On by default; `false` keeps only the element
151
+ * bitmap below, which is what this module did before.
152
+ */
153
+ page?: boolean;
154
+ /** Viewport image caps: width in pixels and decoded bytes. */
155
+ maxViewportWidth?: number;
156
+ maxViewportBytes?: number;
157
+ viewportTimeoutMs?: number;
158
+ /** Injected so tests need neither a browser nor the library. */
159
+ loadRenderer?: () => Promise<PageRenderer>;
160
+ readCanvas?: (canvas: unknown) => CanvasRead;
121
161
  }
122
162
  interface ResolvedOptions {
123
163
  enabled: boolean;
@@ -125,6 +165,15 @@ interface ResolvedOptions {
125
165
  maxEdge: number;
126
166
  timeoutMs: number;
127
167
  createCanvas: () => CanvasLike | null;
168
+ /** The document to render, or null where there is none (a test, a server). */
169
+ doc: Document | null;
170
+ page: boolean;
171
+ maxViewportWidth: number;
172
+ maxViewportBytes: number;
173
+ viewportTimeoutMs: number;
174
+ /** Null for the real library / the real canvas read. */
175
+ loadRenderer: (() => Promise<PageRenderer>) | null;
176
+ readCanvas: ((canvas: unknown) => CanvasRead) | null;
128
177
  }
129
178
  export declare function resolveScreenshotOptions(options: ScreenshotOptions | false | undefined, doc?: Document): ResolvedOptions;
130
179
  export declare function isMediaElement(el: CaptureCandidate | null | undefined): boolean;
@@ -162,10 +211,10 @@ export declare function fitWithin(size: {
162
211
  */
163
212
  export declare function captureScreenshotSync(el: CaptureCandidate | null, options: ResolvedOptions): Screenshot | null;
164
213
  /**
165
- * The entry point the SDK calls. Resolves to a screenshot or to null, within
166
- * `timeoutMs`, and never rejects.
214
+ * The entry point the SDK calls. Resolves to the viewport, or failing that to
215
+ * the element bitmap within `timeoutMs`, or to null, and never rejects.
167
216
  */
168
- export declare function captureScreenshot(el: CaptureCandidate | null, options: ResolvedOptions): Promise<Screenshot | null>;
217
+ export declare function captureScreenshot(el: CaptureCandidate | null, options: ResolvedOptions, ignore?: ((el: Element) => boolean) | null): Promise<Screenshot | null>;
169
218
  /**
170
219
  * Merge a capture into a payload, or hand the payload back untouched.
171
220
  *
@@ -176,7 +225,7 @@ export declare function captureScreenshot(el: CaptureCandidate | null, options:
176
225
  * rather than set to `undefined` (which `JSON.stringify` drops anyway, but
177
226
  * which reads as "we tried and got nothing" to anyone inspecting the object).
178
227
  */
179
- export declare function attachScreenshot<T extends object>(payload: T, el: CaptureCandidate | null, options: ResolvedOptions): Promise<T & {
228
+ export declare function attachScreenshot<T extends object>(payload: T, el: CaptureCandidate | null, options: ResolvedOptions, ignore?: ((el: Element) => boolean) | null): Promise<T & {
180
229
  screenshot?: Screenshot;
181
230
  }>;
182
231
  export {};
@@ -8,3 +8,10 @@ export declare const ANNOTATION_ATTEMPT_GLOBAL = "__weatherboardAnnotationAttemp
8
8
  export declare const ANNOTATION_STARTUP_STATUS_ID = "ai-annotation-startup-status";
9
9
  /** Small enough to remain in the root entry point for Done's full teardown. */
10
10
  export declare function clearAnnotationBootstrap(win: Window | null, storage: Pick<Storage, "removeItem"> | null, doc?: Document): void;
11
+ /**
12
+ * A credential-free note that the shortcut asked to open the toolbar but had
13
+ * to re-arm first (A-2384). The value is the request time in epoch ms; the
14
+ * next armed mount in this tab opens the toolbar once if it is fresh.
15
+ */
16
+ export declare const ANNOTATION_OPEN_INTENT_STORAGE_KEY = "ai.annotation.open";
17
+ export declare const OPEN_INTENT_TTL_MS: number;
@@ -8,3 +8,10 @@ export declare const ANNOTATION_ATTEMPT_GLOBAL = "__weatherboardAnnotationAttemp
8
8
  export declare const ANNOTATION_STARTUP_STATUS_ID = "ai-annotation-startup-status";
9
9
  /** Small enough to remain in the root entry point for Done's full teardown. */
10
10
  export declare function clearAnnotationBootstrap(win: Window | null, storage: Pick<Storage, "removeItem"> | null, doc?: Document): void;
11
+ /**
12
+ * A credential-free note that the shortcut asked to open the toolbar but had
13
+ * to re-arm first (A-2384). The value is the request time in epoch ms; the
14
+ * next armed mount in this tab opens the toolbar once if it is fresh.
15
+ */
16
+ export declare const ANNOTATION_OPEN_INTENT_STORAGE_KEY = "ai.annotation.open";
17
+ export declare const OPEN_INTENT_TTL_MS: number;
package/dist/session.d.ts CHANGED
@@ -8,3 +8,10 @@ export declare const ANNOTATION_ATTEMPT_GLOBAL = "__weatherboardAnnotationAttemp
8
8
  export declare const ANNOTATION_STARTUP_STATUS_ID = "ai-annotation-startup-status";
9
9
  /** Small enough to remain in the root entry point for Done's full teardown. */
10
10
  export declare function clearAnnotationBootstrap(win: Window | null, storage: Pick<Storage, "removeItem"> | null, doc?: Document): void;
11
+ /**
12
+ * A credential-free note that the shortcut asked to open the toolbar but had
13
+ * to re-arm first (A-2384). The value is the request time in epoch ms; the
14
+ * next armed mount in this tab opens the toolbar once if it is fresh.
15
+ */
16
+ export declare const ANNOTATION_OPEN_INTENT_STORAGE_KEY = "ai.annotation.open";
17
+ export declare const OPEN_INTENT_TTL_MS: number;
@@ -0,0 +1,52 @@
1
+ import type { BuildInfo } from "./protocol.cjs";
2
+ /**
3
+ * The in-app shortcut's pre-arm half (A-2384).
4
+ *
5
+ * WHY THIS LIVES IN `./bootstrap` AND NOT IN `mountAnnotation`
6
+ * A host loads the toolbar behind a dynamic `import()` that only an armed page
7
+ * reaches (ADOPTING.md, step 6). On an ordinary staging page there is no
8
+ * marker, so nothing from the index entry point is loaded, and a listener
9
+ * there cannot hear the chord. This one is installed by the small, statically
10
+ * imported entry point on every annotatable page, armed or not.
11
+ *
12
+ * ONE DECISION, MADE BY WHOEVER IS MOUNTED
13
+ * The mounted toolbar's own listener toggles the toolbar when the page is armed
14
+ * with a fresh token, and calls `preventDefault()`. This listener waits for the
15
+ * dispatch to finish and re-arms only if nothing claimed the chord: no toolbar
16
+ * loaded, a toolbar whose token is missing or within five minutes of expiry,
17
+ * or a toolbar the reviewer ended with Done. So the two listeners cannot both
18
+ * act, and freshness is judged in exactly one place.
19
+ *
20
+ * WHAT RE-ARMING IS
21
+ * A top-level navigation to Studio's `/annotate/arm`, which checks the signed-in
22
+ * reviewer, mints the tokens and redirects back to the return path with them in
23
+ * the query; the host's middleware arms on that request and the bootstrap
24
+ * script strips the query. The only thing this side carries is a return path
25
+ * with every annotation parameter removed, plus a credential-free open intent
26
+ * in session storage so the armed mount on return opens the toolbar.
27
+ *
28
+ * PRODUCTION
29
+ * `isAnnotatableBuild` refuses production at install: no listener is added.
30
+ */
31
+ /** The default chord: Command or Control, Shift and the full stop. */
32
+ export declare const DEFAULT_HOTKEY = "Mod+Shift+Period";
33
+ /** Exact modifiers and a KeyboardEvent code or key, such as Mod+Shift+Period. */
34
+ export declare function matchesHotkey(event: Pick<KeyboardEvent, "key" | "code" | "metaKey" | "ctrlKey" | "shiftKey" | "altKey" | "repeat">, chord: string): boolean;
35
+ export interface AnnotationShortcutOptions {
36
+ /** The same build the mount is given. Production installs nothing. */
37
+ build: Pick<BuildInfo, "env">;
38
+ /**
39
+ * Studio's arm endpoint for this product's staging target, for example
40
+ * `https://studio.example/annotate/arm?product=<product-id>&target=staging`. Absolute
41
+ * http(s), and carrying no `return`: the shortcut adds it.
42
+ */
43
+ armUrl: string;
44
+ /** The chord. The mount must be given the same one. */
45
+ hotkey: string;
46
+ /** Defaults to the ambient `document`. */
47
+ doc?: Document;
48
+ }
49
+ /** The URL the chord navigates to: `armUrl` plus a token-free return path. */
50
+ export declare function annotationArmUrl(armUrl: string, current: string): string;
51
+ /** Install the pre-arm listener. Returns its removal. */
52
+ export declare function installAnnotationShortcut(options: AnnotationShortcutOptions): () => void;