tempo-sdk 0.0.93 → 0.0.99

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 (48) hide show
  1. package/dist/assets/index.js +3 -3
  2. package/dist/astro/asset-preview-client.js +3 -3
  3. package/dist/astro.js +2 -2
  4. package/dist/canvas/astro.js +3 -3
  5. package/dist/canvas/index.js +36 -7
  6. package/dist/canvas/index.js.map +1 -1
  7. package/dist/canvas/interact-projection.js +4 -4
  8. package/dist/canvas/svelte.js +3 -3
  9. package/dist/canvas/vue.js +3 -3
  10. package/dist/{chunk-Y7EHQREO.js → chunk-27WT3XUG.js} +2 -2
  11. package/dist/{chunk-Y7EHQREO.js.map → chunk-27WT3XUG.js.map} +1 -1
  12. package/dist/{chunk-M7OOVEAR.js → chunk-6HYKKP5N.js} +3 -2
  13. package/dist/{chunk-M7OOVEAR.js.map → chunk-6HYKKP5N.js.map} +1 -1
  14. package/dist/{chunk-N5MWY4H6.js → chunk-CYDF4LYJ.js} +2 -2
  15. package/dist/{chunk-N5MWY4H6.js.map → chunk-CYDF4LYJ.js.map} +1 -1
  16. package/dist/{chunk-XB6GU4CE.js → chunk-I7VF4ZOV.js} +48 -37
  17. package/dist/chunk-I7VF4ZOV.js.map +1 -0
  18. package/dist/{chunk-HNNZM2XM.js → chunk-MIXQVPDH.js} +461 -185
  19. package/dist/chunk-MIXQVPDH.js.map +1 -0
  20. package/dist/{chunk-GHNHPVEI.js → chunk-SGTGDLOX.js} +2 -2
  21. package/dist/{chunk-GHNHPVEI.js.map → chunk-SGTGDLOX.js.map} +1 -1
  22. package/dist/chunk-T364NBR3.js +1440 -0
  23. package/dist/chunk-T364NBR3.js.map +1 -0
  24. package/dist/{chunk-FZVJVL3T.js → chunk-X5DJKVBT.js} +10 -17
  25. package/dist/chunk-X5DJKVBT.js.map +1 -0
  26. package/dist/{chunk-CVUNZBRV.js → chunk-ZT7HJ6YU.js} +3 -3
  27. package/dist/{chunk-3L4RRKC3.js → chunk-ZW26VZHX.js} +42 -3
  28. package/dist/chunk-ZW26VZHX.js.map +1 -0
  29. package/dist/index.js +2 -2
  30. package/dist/nextjs/plugin.cjs +1 -1
  31. package/dist/nextjs/plugin.cjs.map +1 -1
  32. package/dist/nextjs/plugin.js +1 -1
  33. package/dist/nextjs-loader.cjs +1 -1
  34. package/dist/nextjs-loader.cjs.map +1 -1
  35. package/dist/nextjs.cjs +1 -1
  36. package/dist/nextjs.cjs.map +1 -1
  37. package/dist/nextjs.js +1 -1
  38. package/dist/nuxt/runtime/identity.js +1 -1
  39. package/dist/nuxt.js +1 -1
  40. package/dist/vue.js +1 -1
  41. package/package.json +1 -1
  42. package/dist/chunk-3L4RRKC3.js.map +0 -1
  43. package/dist/chunk-FZVJVL3T.js.map +0 -1
  44. package/dist/chunk-HNNZM2XM.js.map +0 -1
  45. package/dist/chunk-LEBVQBDH.js +0 -643
  46. package/dist/chunk-LEBVQBDH.js.map +0 -1
  47. package/dist/chunk-XB6GU4CE.js.map +0 -1
  48. /package/dist/{chunk-CVUNZBRV.js.map → chunk-ZT7HJ6YU.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../modules/iframe-projection/html/faithful-css-text.ts","../../../modules/iframe-projection/html/runtime-mutations-runtime.js","../../../modules/iframe-projection/html/runtime-mutations.ts","../../../modules/iframe-projection/html/declared-facts.ts","../../../modules/iframe-projection/shared/capture-perf.ts","../../../modules/iframe-projection/html/displayability.ts","../../../modules/iframe-projection/html/selectors.ts","../../../modules/iframe-projection/html/capture.ts"],"sourcesContent":["/**\n * Stylesheet text that parses back into what the browser holds.\n *\n * `rule.cssText` says which rules exist and what they declare, and it is\n * current after any CSSOM edit. It is wrong in one situation, which it reports\n * itself. A shorthand holding a `var()` cannot be split into longhands until\n * the variable is known, so once a sibling longhand is overridden the browser\n * prints the waiting longhands EMPTY:\n *\n * h1 { background: linear-gradient(#fff, var(--end)); background-clip: text }\n * prints as\n * h1 { background-image: ; ...; background-clip: text; }\n *\n * Parsed again, that print has no background at all. No API reads the waiting\n * value back, so it exists only in what the browser was TOLD: the text a rule\n * was parsed from, or a shorthand assigned later. This file keeps both.\n *\n * They are used only for a rule whose print dropped values, and only after\n * the browser, parsing the replacement, prints exactly what the live rule\n * prints. Every other rule keeps its own print, so a deleted rule stays\n * deleted and a runtime edit stays current.\n *\n * The aim is never to emit CSS that means something else. Whatever cannot be\n * shown to match keeps the browser's print: two texts that print alike, an\n * order that decides which declaration wins, a removal no text can spell, and\n * any document whose writes were not all seen.\n *\n * Cost is kept off the page. The hooks that report writes do constant work\n * per call. Pairing a rule with its text needs an index of the stylesheet's\n * rules; a small one is built when first needed, a large one in short slices\n * between the page's own tasks. Until it is ready the rule keeps the\n * browser's print, and an announcement asks for a new capture.\n */\n\n/** The text a rule was parsed from. */\ninterface ParsedRule {\n text: string;\n /** What the browser prints for `text`. Undefined until first needed. */\n printed?: string | null;\n /** Whether the text's own variable shorthands were recorded as assignments. */\n seeded?: boolean;\n}\n\ninterface Assignment {\n value: string;\n important: boolean;\n}\n\n/**\n * What a page tells the browser about its styles, as reported by the runtime\n * hooks (`runtime-mutations-runtime.js`) from the page's own realm.\n */\nexport interface CssInputs {\n /** `[property key on a declaration, CSS property]` for every shorthand. */\n namedShorthands(): [string, string][];\n /**\n * Before a rule's declarations, selector or child rules change. `block` is\n * the rule's own declarations when those are what is about to change.\n */\n ruleChanging(rule: CSSRule, block?: CSSStyleDeclaration): void;\n /**\n * After a rule was inserted. `text` is what the page passed, and undefined\n * when it was not a string or the method takes none: the hooks never\n * convert a caller's argument a second time.\n */\n ruleInserted(\n parent: { cssRules: CSSRuleList },\n index: number,\n text: string | undefined,\n ): void;\n sheetReplaced(sheet: CSSStyleSheet, text: string | undefined): void;\n /** After `name` was set or removed on a rule's declarations. */\n declarationWritten(\n rule: CSSRule,\n block: CSSStyleDeclaration,\n name: string | undefined,\n ): void;\n /** After a rule's declarations were replaced through `cssText`. */\n declarationsReplaced(rule: CSSRule, text: string | undefined): void;\n /**\n * The page read a rule's declaration object while named shorthand writes\n * cannot be seen. Any later write through it may go unreported.\n */\n declarationsExposed(rule: CSSRule): void;\n}\n\n/**\n * Tempo's privileged side: the bytes this page RECEIVED for a stylesheet URL,\n * or null. It must never make a new request, which the page, its service\n * worker or its server could answer differently.\n */\nexport type StylesheetTextReader = (url: string) => Promise<string | null>;\n\nexport interface CssSources {\n /** `rule.cssText`, or text that reproduces the rule when that print dropped values. */\n ruleText(rule: CSSRule): string;\n readonly inputs: CssInputs;\n /**\n * Hooks now report every write (`observeCssInputs`). Sheet text is trusted\n * from here on. Unless they arrived before any of the page's scripts, the\n * stylesheets that exist already may have been written unseen, so their\n * text is never trusted; a sheet created or replaced later is.\n */\n startObserving(options: { beforePageScripts: boolean }): void;\n /** Those hooks stopped. Later writes go unseen, so sheet text is never trusted again. */\n stopObserving(): void;\n /**\n * For a producer in another world, which is told only THAT the page wrote a\n * style. Sheet text is trusted until the first such announcement, and\n * never after. Call before any of the page's scripts.\n */\n markWritesUnreported(): void;\n readonly writesUnreported: boolean;\n readStylesheetsWith(reader: StylesheetTextReader | undefined): void;\n}\n\n/** The event `runtime-mutations.ts` names CSS_RUNTIME_MUTATION. */\nconst CSS_RUNTIME_MUTATION = \"tempo:css-runtime-mutation\";\n\n/**\n * A print with an empty value: `name: ;` or `name: !important;`. An empty\n * custom property (`--tw-pan-x: ;`) is a real value, not a lost one.\n */\nexport function dropsValues(cssText: string): boolean {\n // Nearly every print has no empty value at all; only those pay for the\n // second test, which rules out custom properties.\n return (\n /: (?: !important)?;/.test(cssText) &&\n /(?<![\\w-])(?!--)-?[a-zA-Z][\\w-]*: (?: !important)?;/.test(cssText)\n );\n}\n\nconst BACKSLASH = 92;\nconst SLASH = 47;\nconst STAR = 42;\nconst DOUBLE_QUOTE = 34;\nconst SINGLE_QUOTE = 39;\nconst OPEN_PAREN = 40;\nconst CLOSE_PAREN = 41;\nconst OPEN_BRACKET = 91;\nconst CLOSE_BRACKET = 93;\nconst OPEN_BRACE = 123;\nconst CLOSE_BRACE = 125;\nconst SEMICOLON = 59;\nconst SPACE = 32;\n\n/** Stylesheets are megabytes of mostly ordinary characters: test these first. */\nconst mayStartInert = (code: number) =>\n code === BACKSLASH ||\n code === SLASH ||\n code === DOUBLE_QUOTE ||\n code === SINGLE_QUOTE ||\n code === OPEN_PAREN;\n\n/**\n * Index just past a comment, string, escape or unquoted `url()` starting at\n * `index`, or `index` itself when none starts there. Their contents never\n * open or close a block.\n */\nfunction pastInert(text: string, index: number): number {\n const code = text.charCodeAt(index);\n if (code === BACKSLASH) return index + 2;\n if (code === SLASH && text.charCodeAt(index + 1) === STAR) {\n const end = text.indexOf(\"*/\", index + 2);\n return end < 0 ? text.length : end + 2;\n }\n if (code === DOUBLE_QUOTE || code === SINGLE_QUOTE) {\n let at = index + 1;\n while (at < text.length && text.charCodeAt(at) !== code)\n at += text.charCodeAt(at) === BACKSLASH ? 2 : 1;\n return at + 1;\n }\n const isUrl =\n code === OPEN_PAREN &&\n index >= 3 &&\n text.slice(index - 3, index).toLowerCase() === \"url\";\n if (!isUrl || /^\\(\\s*[\"']/.test(text.slice(index, index + 16))) return index;\n let at = index + 1;\n while (at < text.length && text.charCodeAt(at) !== CLOSE_PAREN)\n at += text.charCodeAt(at) === BACKSLASH ? 2 : 1;\n return at + 1;\n}\n\n/** Characters scanned between two chances for a sliced reader to pause. */\nconst SCAN_STEP = 32 * 1024;\n\n/**\n * The top-level items of CSS text, in order: each rule up to its closing\n * brace, each declaration or statement up to its semicolon. Between items,\n * and every SCAN_STEP characters inside a long one, it yields `null` so a\n * reader working in slices can stop there.\n */\nfunction* cssItems(text: string): Generator<string | null> {\n const customProperty = /\\s*--/y;\n let depth = 0;\n let start = 0;\n let hasContent = false;\n let index = 0;\n let nextPause = SCAN_STEP;\n function* end() {\n const item = text.slice(start, index).trim();\n if (item && item !== \";\") yield item;\n start = index;\n hasContent = false;\n }\n while (index < text.length) {\n if (index >= nextPause) {\n nextPause = index + SCAN_STEP;\n yield null;\n }\n const code = text.charCodeAt(index);\n const next = mayStartInert(code) ? pastInert(text, index) : index;\n if (next !== index) {\n // A comment ahead of an item's first character belongs to no item.\n const isLeadingComment = !hasContent && depth === 0 && code === SLASH;\n if (isLeadingComment) start = next;\n else hasContent = true;\n index = next;\n continue;\n }\n index++;\n if (code === OPEN_BRACE || code === OPEN_PAREN || code === OPEN_BRACKET) {\n depth++;\n hasContent = true;\n } else if (\n code === CLOSE_BRACE ||\n code === CLOSE_PAREN ||\n code === CLOSE_BRACKET\n ) {\n depth = Math.max(0, depth - 1);\n if (code !== CLOSE_BRACE || depth !== 0) continue;\n // A custom property may hold a {} block and still ends at its semicolon.\n customProperty.lastIndex = start;\n if (!customProperty.test(text)) yield* end();\n } else if (code === SEMICOLON && depth === 0) yield* end();\n else if (code > SPACE) hasContent = true;\n }\n yield* end();\n}\n\n/**\n * Splits CSS into its top-level items: each rule up to its closing brace,\n * each declaration or statement up to its semicolon. Works on a stylesheet,\n * on a rule's body, and on a printed declaration block.\n *\n * It only finds boundaries. A wrong boundary is harmless to callers here,\n * because the browser confirms every item before it is used.\n */\nexport function splitCssItems(text: string): string[] {\n const items: string[] = [];\n for (const item of cssItems(text)) if (item !== null) items.push(item);\n return items;\n}\n\n/** Where a rule's block opens, or -1 for text that is only declarations. */\nfunction blockOpen(ruleText: string): number {\n let depth = 0;\n for (let index = 0; index < ruleText.length; ) {\n const code = ruleText.charCodeAt(index);\n const next = mayStartInert(code) ? pastInert(ruleText, index) : index;\n if (next !== index) {\n index = next;\n continue;\n }\n index++;\n if (code === OPEN_BRACE && depth === 0) return index - 1;\n if (code === OPEN_PAREN || code === OPEN_BRACKET) depth++;\n else if (code === CLOSE_PAREN || code === CLOSE_BRACKET) depth--;\n }\n return -1;\n}\n\nfunction ruleBody(ruleText: string): string | undefined {\n const open = blockOpen(ruleText);\n if (open < 0) return undefined;\n return ruleText.slice(open + 1, ruleText.lastIndexOf(\"}\"));\n}\n\nconst isRuleItem = (item: string) =>\n item.startsWith(\"@\")\n ? !/^@charset\\b/i.test(item)\n : item.endsWith(\"}\") && !item.startsWith(\"--\");\n\n/** Conditional and layer rules hold rules; they have no declarations of their own. */\nconst GROUP_PRELUDE =\n /^@(?:media|supports|layer|container|scope|starting-style|document)\\b/i;\n\n/** A rule that only groups other rules, as opposed to one with its own text. */\nconst isGroupRule = (rule: CSSRule) =>\n \"cssRules\" in rule && !(\"style\" in rule) && !(\"appendRule\" in rule);\n\n/** A rule's own declarations come before its first nested rule. */\nfunction ownDeclarations(bodyItems: string[]): string[] {\n const firstRule = bodyItems.findIndex(isRuleItem);\n return firstRule < 0 ? bodyItems : bodyItems.slice(0, firstRule);\n}\n\nfunction parseDeclaration(\n item: string,\n): { name: string; value: string; important: boolean } | null {\n const colon = item.indexOf(\":\");\n if (colon < 0) return null;\n const name = item.slice(0, colon).trim();\n let value = item.slice(colon + 1).trim();\n if (value.endsWith(\";\")) value = value.slice(0, -1).trimEnd();\n const important = /!\\s*important$/i.exec(value);\n if (important) value = value.slice(0, important.index).trimEnd();\n return {\n name: name.startsWith(\"--\") ? name : name.toLowerCase(),\n value,\n important: important !== null,\n };\n}\n\n/**\n * Every rule in a stylesheet's text that has text of its own, at any depth:\n * the body of a conditional or layer rule is read for the rules inside it.\n * Only rules holding a function are kept, since a waiting value always comes\n * from one such as var(). Yields `null` where a sliced reader may pause.\n */\nfunction* ruleTexts(text: string): Generator<string | null> {\n for (const item of cssItems(text)) {\n if (item === null || !isRuleItem(item)) {\n yield null;\n continue;\n }\n if (GROUP_PRELUDE.test(item)) {\n const body = ruleBody(item);\n if (body !== undefined) yield* ruleTexts(body);\n continue;\n }\n yield item.includes(\"(\") ? item : null;\n }\n}\n\n/**\n * The browser as the judge. A private stylesheet nothing renders parses\n * candidate text, and its print is compared with the live rule's.\n */\nfunction createCssEngine(view: Window & typeof globalThis) {\n const sheet = new view.CSSStyleSheet();\n sheet.insertRule(\"a {}\", 0);\n sheet.insertRule(\"a {}\", 1);\n // Separate blocks: asking about a shorthand must not disturb a replay.\n const probe = (sheet.cssRules[0] as CSSStyleRule).style;\n const work = (sheet.cssRules[1] as CSSStyleRule).style;\n const longhands = new Map<string, string[] | null>();\n\n const longhandsOf = (property: string): string[] | null => {\n let known = longhands.get(property);\n if (known === undefined) {\n probe.cssText = \"\";\n probe.setProperty(property, \"inherit\");\n known = probe.length > 1 ? Array.from(probe) : null;\n longhands.set(property, known);\n }\n return known;\n };\n\n return {\n sheet,\n probe,\n work,\n longhandsOf,\n /** What the browser prints for a rule parsed from `text`; null when it parses to none. */\n printRule(text: string): string | null {\n try {\n const index = sheet.insertRule(text, sheet.cssRules.length);\n const printed = sheet.cssRules[index]!.cssText;\n sheet.deleteRule(index);\n return printed;\n } catch {\n return null;\n }\n },\n /**\n * The value just written to shorthand `name`, when its longhands now wait\n * on it. Right after the write every longhand waits on the same value, so\n * the browser still prints it whole. Null for anything else.\n */\n waitingShorthand(block: CSSStyleDeclaration, name: string): string | null {\n const parts = longhandsOf(name);\n if (!parts) return null;\n const value = block.getPropertyValue(name);\n const isWaiting =\n value !== \"\" && block.getPropertyValue(parts[0]!) === \"\";\n return isWaiting ? value : null;\n },\n };\n}\n\ntype CssEngine = ReturnType<typeof createCssEngine>;\n\nconst MAX_SHEET_TEXT_LENGTH = 5 * 1024 * 1024;\n/** Text indexed inside the call that needs it: about 2 ms of work. */\nconst INLINE_INDEX_LENGTH = 64 * 1024;\n/** One background slice of indexing, between the page's own tasks. */\nconst INDEX_SLICE_MS = 4;\n\n/** `margin-inline-start`, `block-size`, `border-start-end-radius`, … */\nconst FLOW_RELATIVE =\n /(?:^|-)(?:inline|block)(?:-|$)|-(?:start|end)-(?:start|end)-/;\n\n/** Marks Tempo's own \"a repair is ready\" announcement, which is no page write. */\nconst REPAIR_READY = \"repairReady\";\n\nconst documents = new WeakMap<Document, CssSources>();\n\n/** One document's record of what its browser was told. */\nexport function cssSourcesFor(doc: Document): CssSources {\n let sources = documents.get(doc);\n if (!sources) {\n sources = createCssSources(doc);\n documents.set(doc, sources);\n }\n return sources;\n}\n\n/** Where a document's linked stylesheet bytes come from. Without one, none are read. */\nexport function provideStylesheetText(\n doc: Document,\n reader: StylesheetTextReader | undefined,\n): void {\n cssSourcesFor(doc).readStylesheetsWith(reader);\n}\n\nfunction createCssSources(doc: Document): CssSources {\n let parsed = new WeakMap<CSSRule, ParsedRule>();\n let assigned = new WeakMap<CSSRule, Map<string, Assignment>>();\n /** Text given to `replace()`, a style element's text, or a link's bytes. */\n let sheetTexts = new WeakMap<CSSStyleSheet, string>();\n /**\n * Rules created by an insert after their sheet was parsed. They, and rules\n * inside them, never came from the sheet's text, however alike they print.\n */\n let insertedLater = new WeakSet<CSSRule>();\n /** Rules whose own declarations, selector or child rules were written. */\n let editedRules = new WeakSet<CSSRule>();\n /** A rule's print just before its first edit, while its text described it. */\n let printBeforeEdit = new WeakMap<CSSRule, string>();\n /**\n * The text an insert was given, until a background slice learns whether\n * the rule's print lost a value. Only then is it kept, as `parsed`.\n */\n let insertTexts = new WeakMap<CSSRule, string>();\n let insertQueue: CSSRule[] = [];\n /** Rules a write may have reached without a report. */\n let unobservable = new WeakSet<CSSRule>();\n let checkedBeforeChange = new WeakSet<CSSRule>();\n /** Rules first seen through a selector or structural change. */\n let awaitingDeclarations = new WeakSet<CSSRule>();\n /** Sheet text is trusted only while every write is seen. */\n let trusted = false;\n /** Sheets that existed before late hooks arrived: written unseen, maybe. */\n let preexisting = new WeakSet<CSSStyleSheet>();\n let everStopped = false;\n let writesUnreported = false;\n let reader: StylesheetTextReader | undefined;\n const linkReads = new WeakSet<CSSStyleSheet>();\n /**\n * Each sheet's rules by what the browser prints for them, for prints that\n * dropped values. Null for a print more than one text produces, and null\n * `byPrint` while a large index is still being built.\n */\n const indexes = new WeakMap<\n CSSStyleSheet,\n { text: string; byPrint: Map<string, string | null> | null }\n >();\n\n let engine: CssEngine | null | undefined;\n /**\n * Null where stylesheets cannot be constructed, and where the engine prints\n * every value (a test DOM): there is nothing to repair, so nothing is kept.\n */\n const engineOrNull = (): CssEngine | null => {\n if (engine !== undefined) return engine;\n // The hooks see the engine's own first writes: answer them \"not ready\".\n engine = null;\n try {\n const candidate = createCssEngine(\n doc.defaultView as Window & typeof globalThis,\n );\n candidate.work.cssText = \"margin: var(--m); margin-top: 0\";\n if (dropsValues(candidate.work.cssText)) engine = candidate;\n } catch {\n // Stays null.\n }\n return engine;\n };\n const isScratch = (rule: CSSRule) =>\n engine != null && rule.parentStyleSheet === engine.sheet;\n\n /** Asks for a new capture of `sheet`: a repair for it just became possible. */\n const announceRepair = (sheet: CSSStyleSheet) => {\n const view = doc.defaultView;\n if (!view) return;\n doc.dispatchEvent(\n new view.CustomEvent(CSS_RUNTIME_MUTATION, {\n detail: {\n ownerNode: sheet.ownerNode,\n sheet,\n mutable: false,\n [REPAIR_READY]: true,\n },\n }),\n );\n };\n\n /** Adds one rule text to an index under construction. */\n const addToIndex = (\n css: CssEngine,\n byPrint: Map<string, string | null>,\n chunk: string,\n ) => {\n const print = css.printRule(chunk);\n if (print === null || !dropsValues(print)) return;\n const known = byPrint.get(print);\n byPrint.set(print, known === undefined || known === chunk ? chunk : null);\n };\n\n /**\n * The index of `sheet`'s text, or undefined while it is not ready. A large\n * text is indexed in slices after the current task, then announced.\n */\n const indexFor = (\n css: CssEngine,\n sheet: CSSStyleSheet,\n text: string,\n ): Map<string, string | null> | undefined => {\n const known = indexes.get(sheet);\n if (known?.text === text) return known.byPrint ?? undefined;\n const byPrint = new Map<string, string | null>();\n if (text.length <= INLINE_INDEX_LENGTH) {\n for (const chunk of ruleTexts(text))\n if (chunk !== null) addToIndex(css, byPrint, chunk);\n indexes.set(sheet, { text, byPrint });\n return byPrint;\n }\n const entry = { text, byPrint: null as Map<string, string | null> | null };\n indexes.set(sheet, entry);\n const chunks = ruleTexts(text);\n const view = doc.defaultView;\n const step = () => {\n if (indexes.get(sheet) !== entry) return;\n const deadline = performance.now() + INDEX_SLICE_MS;\n for (;;) {\n const next = chunks.next();\n if (next.done) {\n entry.byPrint = byPrint;\n announceRepair(sheet);\n return;\n }\n if (next.value !== null) addToIndex(css, byPrint, next.value);\n if (performance.now() >= deadline) break;\n }\n view?.setTimeout(step, 0);\n };\n view?.setTimeout(step, 0);\n return undefined;\n };\n\n /** Reads a link's bytes from Tempo's privileged side, once per loaded sheet. */\n const readLinkText = (sheet: CSSStyleSheet) => {\n const link = sheet.ownerNode as HTMLLinkElement | null;\n const url = sheet.href;\n if (!reader || !url || link?.tagName !== \"LINK\" || linkReads.has(sheet))\n return;\n linkReads.add(sheet);\n let reading: Promise<string | null>;\n try {\n reading = Promise.resolve(reader(url));\n } catch {\n return;\n }\n reading.then(\n (text) => {\n const isCurrent =\n typeof text === \"string\" &&\n text.length <= MAX_SHEET_TEXT_LENGTH &&\n link.sheet === sheet;\n if (!isCurrent) return;\n sheetTexts.set(sheet, text);\n announceRepair(sheet);\n },\n () => {},\n );\n };\n\n const sheetTextOf = (sheet: CSSStyleSheet): string | undefined => {\n let text = sheetTexts.get(sheet);\n const owner = sheet.ownerNode as Element | null;\n if (text === undefined && owner?.tagName === \"STYLE\") {\n // Read once: a style element parses new text into a new sheet object.\n text = owner.textContent ?? \"\";\n sheetTexts.set(sheet, text);\n }\n if (text === undefined) readLinkText(sheet);\n return text !== undefined && text.length <= MAX_SHEET_TEXT_LENGTH\n ? text\n : undefined;\n };\n\n /** Records `name` when its longhands now wait on it, and forgets it otherwise. */\n const note = (\n css: CssEngine,\n entries: Map<string, Assignment>,\n block: CSSStyleDeclaration,\n name: string,\n ) => {\n const value = css.waitingShorthand(block, name);\n entries.delete(name);\n if (value === null) return;\n const important = block.getPropertyPriority(name) === \"important\";\n entries.set(name, { value, important });\n };\n\n /**\n * Parsed declarations are assignments too. Replaying them records the\n * variable shorthands a rule started with, so a later edit to the same rule\n * still knows them. Assignments already observed came later and win.\n */\n const seedAssignments = (rule: CSSRule, declarations: string[]) => {\n const css = engineOrNull();\n if (!css) return;\n const seeds = new Map<string, Assignment>();\n css.work.cssText = \"\";\n for (const item of declarations) {\n const declaration = parseDeclaration(item);\n if (!declaration) continue;\n const priority = declaration.important ? \"important\" : \"\";\n css.work.setProperty(declaration.name, declaration.value, priority);\n if (!declaration.name.startsWith(\"--\"))\n note(css, seeds, css.work, declaration.name);\n }\n if (!seeds.size) return;\n assigned.set(rule, new Map([...seeds, ...(assigned.get(rule) ?? [])]));\n };\n\n const assignmentsOf = (rule: CSSRule) => {\n const source = parsed.get(rule);\n if (source && !source.seeded) {\n source.seeded = true;\n const body = ruleBody(source.text);\n if (body !== undefined)\n seedAssignments(rule, ownDeclarations(splitCssItems(body)));\n }\n return assigned.get(rule);\n };\n\n /** Keeps an inserted rule's text when its print lost a value; else drops it. */\n const settleInsert = (rule: CSSRule) => {\n const text = insertTexts.get(rule);\n if (text === undefined) return;\n insertTexts.delete(rule);\n // An edited rule's whole shorthands were read before its first write.\n if (\n !editedRules.has(rule) &&\n !parsed.has(rule) &&\n dropsValues(rule.cssText)\n )\n parsed.set(rule, { text });\n };\n /** Settles queued inserts in slices after the current task. */\n const settleInsertsLater = () => {\n if (insertQueue.length !== 1) return;\n const view = doc.defaultView;\n const step = () => {\n const deadline = performance.now() + INDEX_SLICE_MS;\n while (insertQueue.length && performance.now() < deadline)\n settleInsert(insertQueue.shift()!);\n if (insertQueue.length) view?.setTimeout(step, 0);\n };\n view?.setTimeout(step, 0);\n };\n\n /** Inserted after parsing, itself or through a rule it sits in. */\n const cameFromInsert = (rule: CSSRule) => {\n for (let at: CSSRule | null = rule; at; at = at.parentRule)\n if (insertedLater.has(at)) return true;\n return false;\n };\n\n /** The text `rule` was parsed from: its insert's, or its sheet's. */\n const sourceOf = (css: CssEngine, rule: CSSRule): ParsedRule | undefined => {\n if (!trusted || unobservable.has(rule)) return undefined;\n settleInsert(rule);\n const known = parsed.get(rule);\n if (known) return known;\n if (isGroupRule(rule) || cameFromInsert(rule)) return undefined;\n // An edited rule pairs by the print it had while its text described it.\n const print = editedRules.has(rule)\n ? printBeforeEdit.get(rule)\n : rule.cssText;\n const sheet = rule.parentStyleSheet;\n if (print === undefined || !dropsValues(print) || !sheet) return undefined;\n if (preexisting.has(sheet)) return undefined;\n const text = sheetTextOf(sheet);\n if (text === undefined) return undefined;\n const chunk = indexFor(css, sheet, text)?.get(print);\n if (!chunk) return undefined;\n const source = { text: chunk, printed: print };\n parsed.set(rule, source);\n return source;\n };\n\n /**\n * Declarations whose waiting longhands are replaced by the shorthands they\n * wait on. `items` is the live print, so the answer is current: anything\n * the assignments cannot account for returns that print unchanged.\n */\n const declarationsText = (\n css: CssEngine,\n rule: CSSRule,\n items: string[],\n ): string => {\n const printed = items.join(\" \");\n const names = items.map((item) => parseDeclaration(item)?.name ?? \"\");\n const waiting = new Set(\n items.flatMap((item, at) => {\n const isEmpty = parseDeclaration(item)?.value === \"\";\n return isEmpty && !names[at]!.startsWith(\"--\") ? [names[at]!] : [];\n }),\n );\n const entries =\n waiting.size && trusted && !unobservable.has(rule)\n ? assignmentsOf(rule)\n : undefined;\n if (!entries) return printed;\n\n // Newest first: a longhand waits on the last shorthand that set it.\n // Each shorthand goes just before the first of its longhands in the live\n // order, so every explicit longhand still follows and overrides it. An\n // older shorthand that shares a longhand with a newer one also goes\n // before it, or the older value would win.\n const placed: { at: number; longhands: string[]; declaration: string }[] =\n [];\n const covered = new Set<string>();\n for (const [name, entry] of [...entries].reverse()) {\n const longhands = css.longhandsOf(name) ?? [];\n const mine = longhands.filter(\n (longhand) => waiting.has(longhand) && !covered.has(longhand),\n );\n if (!mine.length) continue;\n for (const longhand of mine) covered.add(longhand);\n const newerOverlapping = placed\n .filter((newer) => newer.longhands.some((l) => longhands.includes(l)))\n .map((newer) => newer.at);\n const at = Math.min(\n names.findIndex((item) => longhands.includes(item)),\n ...newerOverlapping,\n );\n const priority = entry.important ? \" !important\" : \"\";\n const declaration = `${name}: ${entry.value}${priority};`;\n placed.push({ at, longhands, declaration });\n }\n // `placed` is newest first; at one position the oldest is written first.\n const shorthandsAt = (at: number) =>\n placed\n .filter((shorthand) => shorthand.at === at)\n .map((shorthand) => shorthand.declaration)\n .reverse();\n if (covered.size !== waiting.size) return printed;\n\n const candidate = items\n .flatMap((item, at) => [\n ...shorthandsAt(at),\n ...(waiting.has(names[at]!) ? [] : [item]),\n ])\n .join(\" \");\n css.work.cssText = candidate;\n const reprinted = splitCssItems(css.work.cssText);\n // Between a flow-relative property and its physical counterpart the later\n // declaration wins, so there the order must survive exactly. Elsewhere\n // every longhand appears once and order decides nothing.\n const orderDecides = names.some((name) => FLOW_RELATIVE.test(name));\n const [got, want] = orderDecides\n ? [reprinted, items]\n : [reprinted.sort(), [...items].sort()];\n const isSame =\n got.length === want.length && got.every((item, at) => item === want[at]);\n return isSame ? candidate : printed;\n };\n\n /** A rule's own declarations and each child, made faithful one by one. */\n const rebuild = (css: CssEngine, rule: CSSRule, printed: string): string => {\n const open = blockOpen(printed);\n // Declarations nested after a child rule print with no block of their own.\n if (open < 0) return declarationsText(css, rule, splitCssItems(printed));\n const items = splitCssItems(\n printed.slice(open + 1, printed.lastIndexOf(\"}\")),\n );\n const own = ownDeclarations(items);\n const children =\n \"cssRules\" in rule\n ? Array.from((rule as CSSGroupingRule).cssRules, (child) =>\n ruleText(child),\n )\n : [];\n const hasUnreadChildren = own.length !== items.length && !children.length;\n if (hasUnreadChildren) return printed;\n const body = [declarationsText(css, rule, own), ...children];\n return `${printed.slice(0, open)}{ ${body.filter(Boolean).join(\" \")} }`;\n };\n\n function ruleText(rule: CSSRule): string {\n const printed = rule.cssText;\n if (!dropsValues(printed)) return printed;\n const css = engineOrNull();\n if (!css) return printed;\n const source = sourceOf(css, rule);\n if (source && !editedRules.has(rule)) {\n if (source.printed === undefined)\n source.printed = css.printRule(source.text);\n if (source.printed === printed) return source.text;\n }\n return rebuild(css, rule, printed);\n }\n\n /**\n * Until its first declaration write, the browser still prints each of a\n * rule's variable shorthands whole. Keep them before one is broken apart.\n */\n const keepWholeShorthands = (\n css: CssEngine,\n rule: CSSRule,\n block: CSSStyleDeclaration,\n printed: string,\n ) => {\n const entries = assigned.get(rule) ?? new Map<string, Assignment>();\n for (const item of ownDeclarations(\n splitCssItems(ruleBody(printed) ?? \"\"),\n )) {\n const name = parseDeclaration(item)?.name;\n if (name && !name.startsWith(\"--\")) note(css, entries, block, name);\n }\n if (entries.size) assigned.set(rule, entries);\n };\n\n /** Everything a write invalidates, or keeps for later, before it happens. */\n const beforeFirstChange = (\n rule: CSSRule,\n block: CSSStyleDeclaration | undefined,\n ) => {\n // A grouping rule has no text of its own to keep; its rules pair alone.\n settleInsert(rule);\n if (!(\"style\" in rule) || parsed.has(rule)) return;\n const printed = rule.cssText;\n // Pairing waits for a capture. The print it needs is the one from now.\n if (dropsValues(printed)) {\n printBeforeEdit.set(rule, printed);\n return;\n }\n // A waiting value always comes from a function such as var().\n if (!printed.includes(\"(\")) return;\n const css = engineOrNull();\n if (!css) return;\n if (block) keepWholeShorthands(css, rule, block, printed);\n else awaitingDeclarations.add(rule);\n };\n\n const inputs: CssInputs = {\n namedShorthands() {\n const css = engineOrNull();\n if (!css) return [];\n const keys = new Map<string, string>();\n for (const key in css.work) {\n const property = key\n .replace(/^webkit(?=[A-Z])/, \"-webkit\")\n .replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n if (!css.longhandsOf(property)) continue;\n keys.set(key, property);\n keys.set(property, property);\n if (key.startsWith(\"webkit\")) keys.set(`W${key.slice(1)}`, property);\n }\n return [...keys];\n },\n ruleChanging(rule, block) {\n if (isScratch(rule)) return;\n if (!checkedBeforeChange.has(rule)) {\n checkedBeforeChange.add(rule);\n beforeFirstChange(rule, block);\n } else if (block && awaitingDeclarations.delete(rule)) {\n const css = engineOrNull();\n if (css) keepWholeShorthands(css, rule, block, rule.cssText);\n }\n // One write can replace another and print the same empty values, so a\n // rule's parsed text is never used whole again, whatever it prints. The\n // same holds for every rule that holds it as text: a keyframes rule, a\n // style rule with nested rules. A grouping rule never pairs, so it is\n // never read here.\n editedRules.add(rule);\n for (let at = rule.parentRule; at; at = at.parentRule) {\n if (isGroupRule(at) || editedRules.has(at)) continue;\n if (!checkedBeforeChange.has(at)) {\n checkedBeforeChange.add(at);\n beforeFirstChange(at, undefined);\n }\n editedRules.add(at);\n }\n },\n ruleInserted(parent, index, text) {\n if (parent === engine?.sheet) return;\n const rule = parent.cssRules[index];\n if (!rule) return;\n insertedLater.add(rule);\n // Only text whose print lost a value is worth keeping, and finding\n // out costs a print: that happens later, not in the page's call. A rule\n // that loses a value later is read just before that write.\n if (text === undefined || !text.includes(\"(\") || isGroupRule(rule))\n return;\n insertTexts.set(rule, text);\n insertQueue.push(rule);\n settleInsertsLater();\n },\n sheetReplaced(sheet, text) {\n if (sheet === engine?.sheet) return;\n // Its rules are new, parsed from text this record just received.\n preexisting.delete(sheet);\n if (text === undefined) sheetTexts.delete(sheet);\n else sheetTexts.set(sheet, text);\n },\n declarationWritten(rule, block, name) {\n if (isScratch(rule)) return;\n if (name === undefined) {\n // An unknown property was written: no recorded shorthand is certain.\n assigned.delete(rule);\n return;\n }\n const css = name.startsWith(\"--\") ? null : engineOrNull();\n if (!css) return;\n const property = name.toLowerCase();\n let entries = assigned.get(rule);\n if (!entries) {\n if (css.waitingShorthand(block, property) === null) return;\n entries = new Map();\n assigned.set(rule, entries);\n }\n note(css, entries, block, property);\n },\n declarationsReplaced(rule, text) {\n if (isScratch(rule)) return;\n assigned.delete(rule);\n if (text?.includes(\"(\")) seedAssignments(rule, splitCssItems(text));\n },\n declarationsExposed(rule) {\n if (isScratch(rule)) return;\n // A rule held as one text (a keyframes rule, a style rule with nested\n // rules) could hide the unseen write too.\n for (let at: CSSRule | null = rule; at; at = at.parentRule)\n if (!isGroupRule(at)) unobservable.add(at);\n },\n };\n\n /** Clears what the hooks reported. Indexes depend on text alone and stay. */\n const forgetReports = () => {\n parsed = new WeakMap();\n assigned = new WeakMap();\n sheetTexts = new WeakMap();\n insertTexts = new WeakMap();\n insertQueue = [];\n insertedLater = new WeakSet();\n editedRules = new WeakSet();\n printBeforeEdit = new WeakMap();\n unobservable = new WeakSet();\n checkedBeforeChange = new WeakSet();\n awaitingDeclarations = new WeakSet();\n };\n\n return {\n ruleText,\n inputs,\n startObserving({ beforePageScripts }) {\n if (everStopped) return;\n trusted = true;\n if (beforePageScripts) return;\n for (const sheet of Array.from(doc.styleSheets)) preexisting.add(sheet);\n for (const sheet of doc.adoptedStyleSheets ?? []) preexisting.add(sheet);\n },\n stopObserving() {\n everStopped = true;\n trusted = false;\n forgetReports();\n },\n markWritesUnreported() {\n if (writesUnreported) return;\n writesUnreported = true;\n trusted = !everStopped;\n // Listening from now on, so a write the page makes before any producer\n // subscribes still ends the trust.\n doc.addEventListener(CSS_RUNTIME_MUTATION, (event) => {\n const detail = (event as CustomEvent).detail;\n if (detail?.[REPAIR_READY] || !trusted) return;\n trusted = false;\n everStopped = true;\n forgetReports();\n });\n },\n get writesUnreported() {\n return writesUnreported;\n },\n readStylesheetsWith(next) {\n reader = next;\n },\n };\n}\n","/** Primary browser runtime; also emitted for isolated page injection. It must\n * stay self-contained. Ordinary producers call it without dynamic evaluation.\n *\n * `inputs` is the same-realm record of what the page tells the browser about\n * its styles (`CssInputs` in faithful-css-text.ts). An injected copy has none:\n * it only announces that something changed. */\nexport function installRuntimeMutations(scope, inputs) {\n const doc = scope.document;\n const undo = [];\n let active = true;\n const emit = (target, kind, detail) => {\n if (active)\n target.dispatchEvent(\n detail\n ? new scope.CustomEvent(kind, { bubbles: true, detail })\n : new scope.Event(kind, { bubbles: true }),\n );\n };\n const form = (target) => {\n if (target instanceof scope.HTMLOptionElement)\n target = target.closest(\"select\");\n if (target && target.isConnected)\n emit(target, \"tempo:form-runtime-mutation\");\n };\n const css = (target, mutable = false) => {\n const sheet =\n target instanceof scope.CSSStyleSheet ? target : target.parentStyleSheet;\n if (\n target === doc ||\n (sheet &&\n (sheet.ownerNode?.isConnected ||\n doc.adoptedStyleSheets.includes(sheet)))\n )\n emit(doc, \"tempo:css-runtime-mutation\", {\n ownerNode: sheet?.ownerNode ?? null,\n sheet: sheet ?? null,\n mutable,\n });\n };\n const cssChanged = (target) => css(target);\n // Reporting must never reach the page: a failure in it is ours, not the\n // application's, and its call has to finish exactly as the native did. No\n // closure per call: CSS-in-JS and dynamic style rules write very often.\n const report = (name, a, b, c) => {\n if (!inputs || !active) return;\n try {\n inputs[name](a, b, c);\n } catch {}\n };\n // A caller's argument is converted once, by the native. Only what is\n // already a string is reported; anything else is reported as unknown.\n const text = (value) => (typeof value === \"string\" ? value : undefined);\n /** `changed` runs when the value differs afterwards; `told` after every set. */\n const setter = (proto, key, changed, before, told) => {\n if (!proto) return;\n const original = Object.getOwnPropertyDescriptor(proto, key);\n if (!original?.set || !original.configurable) return;\n const set = function (value) {\n const previous = original.get?.call(this);\n before?.(this);\n original.set.call(this, value);\n if (key === \"adoptedStyleSheets\" || previous !== original.get?.call(this))\n changed(this);\n told?.(this, value);\n };\n Object.defineProperty(proto, key, { ...original, set });\n undo.push(() => {\n if (Object.getOwnPropertyDescriptor(proto, key)?.set === set)\n Object.defineProperty(proto, key, original);\n });\n };\n const method = (proto, key, changed, before) => {\n if (!proto) return;\n const original = Object.getOwnPropertyDescriptor(proto, key);\n if (typeof original?.value !== \"function\" || !original.configurable) return;\n const value = function (...args) {\n before?.(this);\n const result = original.value.apply(this, args);\n if (result instanceof scope.Promise)\n result.then(\n () => changed(this, args, result),\n () => {},\n );\n else changed(this, args, result);\n return result;\n };\n Object.defineProperty(proto, key, { ...original, value });\n undo.push(() => {\n if (Object.getOwnPropertyDescriptor(proto, key)?.value === value)\n Object.defineProperty(proto, key, original);\n });\n };\n for (const [type, keys] of [\n [\"HTMLInputElement\", [\"value\", \"checked\", \"valueAsNumber\", \"valueAsDate\"]],\n [\"HTMLTextAreaElement\", [\"value\"]],\n [\"HTMLSelectElement\", [\"value\", \"selectedIndex\"]],\n [\"HTMLOptionElement\", [\"selected\"]],\n ])\n for (const key of keys) setter(scope[type]?.prototype, key, form);\n for (const type of [\"HTMLInputElement\", \"HTMLTextAreaElement\"])\n method(scope[type]?.prototype, \"setRangeText\", form);\n for (const key of [\"stepUp\", \"stepDown\"])\n method(scope.HTMLInputElement?.prototype, key, form);\n // CSSOM edits do not create MutationRecords, including declaration setters.\n const ruleChanging = (rule) => report(\"ruleChanging\", rule);\n const inserted = (parent, args, index) => {\n css(parent);\n if (typeof index === \"number\")\n report(\"ruleInserted\", parent, index, text(args[0]));\n };\n method(scope.CSSStyleSheet?.prototype, \"insertRule\", inserted);\n // The legacy insert takes a selector and a declaration block, not rule text.\n method(scope.CSSStyleSheet?.prototype, \"addRule\", (sheet, args) => {\n css(sheet);\n const index =\n typeof args[2] === \"number\" ? args[2] : sheet.cssRules.length - 1;\n report(\"ruleInserted\", sheet, index, undefined);\n });\n for (const key of [\"deleteRule\", \"removeRule\"])\n method(scope.CSSStyleSheet?.prototype, key, cssChanged);\n for (const key of [\"replace\", \"replaceSync\"])\n method(scope.CSSStyleSheet?.prototype, key, (sheet, args) => {\n css(sheet);\n report(\"sheetReplaced\", sheet, text(args[0]));\n });\n method(\n scope.CSSGroupingRule?.prototype,\n \"insertRule\",\n inserted,\n ruleChanging,\n );\n method(\n scope.CSSGroupingRule?.prototype,\n \"deleteRule\",\n cssChanged,\n ruleChanging,\n );\n const declarations = scope.CSSStyleDeclaration?.prototype;\n // The unhooked calls: the named shorthand accessors below forward to them.\n const setProperty = declarations?.setProperty;\n const getPropertyValue = declarations?.getPropertyValue;\n const ruleStyle = scope.CSSStyleRule\n ? Object.getOwnPropertyDescriptor(scope.CSSStyleRule.prototype, \"style\")\n ?.get\n : undefined;\n const writing = (block) => {\n const rule = block.parentRule;\n if (rule) report(\"ruleChanging\", rule, block);\n };\n const written = (block, name) => {\n const rule = block.parentRule;\n if (!rule) return;\n css(rule);\n report(\"declarationWritten\", rule, block, text(name));\n };\n setter(\n declarations,\n \"cssText\",\n (block) => {\n if (block.parentRule) css(block.parentRule);\n },\n writing,\n // Told even when the print is unchanged: one variable shorthand can\n // replace another and print exactly the same empty values.\n (block, value) => {\n const rule = block.parentRule;\n // The setter treats null as the empty string.\n if (rule)\n report(\"declarationsReplaced\", rule, value === null ? \"\" : text(value));\n },\n );\n for (const key of [\"setProperty\", \"removeProperty\"])\n method(\n declarations,\n key,\n (block, args) => written(block, args[0]),\n writing,\n );\n // Typed OM writes reach a rule's declarations without any call above. A\n // map is tied to its rule when the page first asks the rule for it.\n const rulesOfMaps = new WeakMap();\n const mapOf =\n scope.CSSStyleRule &&\n Object.getOwnPropertyDescriptor(scope.CSSStyleRule.prototype, \"styleMap\");\n if (mapOf?.get && mapOf.configurable && ruleStyle) {\n const get = function () {\n const map = mapOf.get.call(this);\n rulesOfMaps.set(map, this);\n return map;\n };\n const proto = scope.CSSStyleRule.prototype;\n Object.defineProperty(proto, \"styleMap\", { ...mapOf, get });\n undo.push(() => {\n if (Object.getOwnPropertyDescriptor(proto, \"styleMap\")?.get === get)\n Object.defineProperty(proto, \"styleMap\", mapOf);\n });\n const mapWriting = (map) => {\n const rule = rulesOfMaps.get(map);\n if (rule) report(\"ruleChanging\", rule, ruleStyle.call(rule));\n };\n for (const key of [\"set\", \"append\", \"delete\"])\n method(\n scope.StylePropertyMap?.prototype,\n key,\n (map, args) => {\n const rule = rulesOfMaps.get(map);\n if (!rule) return;\n css(rule);\n report(\n \"declarationWritten\",\n rule,\n ruleStyle.call(rule),\n text(args[0]),\n );\n },\n mapWriting,\n );\n method(\n scope.StylePropertyMap?.prototype,\n \"clear\",\n (map) => {\n const rule = rulesOfMaps.get(map);\n if (!rule) return;\n css(rule);\n report(\"declarationsReplaced\", rule, \"\");\n },\n mapWriting,\n );\n }\n // A named SHORTHAND write is the one declaration write whose value cannot\n // be read back later: `style.background = \"…var(--x)\"` followed by any\n // longhand leaves the browser printing empty values. A prototype accessor\n // is found before Chromium's own-property lookup, and is how the CSSOM\n // specification defines these properties (they forward to setProperty and\n // getPropertyValue). Longhands keep the native path.\n // The accessors forward to the two calls captured above, so they are only\n // installed where the caller says no page script has run yet. As a second\n // guard, a frozen prototype or a replaced call leaves the prototype as is.\n const printSource = scope.Function?.prototype.toString;\n const isNative = (call) =>\n typeof call === \"function\" &&\n typeof printSource === \"function\" &&\n printSource.call(call).includes(\"[native code]\");\n const canDefine =\n inputs &&\n declarations &&\n Object.isExtensible(declarations) &&\n isNative(setProperty) &&\n isNative(getPropertyValue);\n let namedShorthands = [];\n if (canDefine)\n try {\n namedShorthands = inputs.namedShorthands();\n } catch {}\n let accessorsInstalled = false;\n for (const [key, property] of namedShorthands) {\n if (key in declarations) continue;\n const accessor = {\n configurable: true,\n enumerable: true,\n get() {\n return getPropertyValue.call(this, property);\n },\n set(value) {\n writing(this);\n setProperty.call(this, property, value);\n written(this, property);\n },\n };\n Object.defineProperty(declarations, key, accessor);\n accessorsInstalled = true;\n undo.push(() => {\n if (\n Object.getOwnPropertyDescriptor(declarations, key)?.set === accessor.set\n )\n delete declarations[key];\n });\n }\n // Chromium's named declaration properties are own data properties, not\n // prototype setters. Observe exposure without proxying/changing native identity.\n // Receivers conservatively reread exposed sheets on the next head request.\n // Without the accessors above, a write through the object the page now\n // holds may never be reported, so the rule is reported as exposed.\n for (const proto of [\n scope.CSSStyleRule?.prototype,\n scope.CSSKeyframeRule?.prototype,\n ]) {\n const original = proto && Object.getOwnPropertyDescriptor(proto, \"style\");\n if (!original?.get || !original.configurable) continue;\n const get = function () {\n css(this, true);\n if (!accessorsInstalled) report(\"declarationsExposed\", this);\n return original.get.call(this);\n };\n Object.defineProperty(proto, \"style\", { ...original, get });\n undo.push(() => {\n if (Object.getOwnPropertyDescriptor(proto, \"style\")?.get === get)\n Object.defineProperty(proto, \"style\", original);\n });\n }\n setter(scope.CSSStyleRule?.prototype, \"selectorText\", css, ruleChanging);\n setter(scope.CSSKeyframeRule?.prototype, \"keyText\", css, ruleChanging);\n method(\n scope.CSSKeyframesRule?.prototype,\n \"appendRule\",\n (rule, args) => {\n css(rule);\n report(\"ruleInserted\", rule, rule.cssRules.length - 1, text(args[0]));\n },\n ruleChanging,\n );\n method(\n scope.CSSKeyframesRule?.prototype,\n \"deleteRule\",\n cssChanged,\n ruleChanging,\n );\n setter(scope.MediaList?.prototype, \"mediaText\", () => css(doc));\n for (const key of [\"appendMedium\", \"deleteMedium\"])\n method(scope.MediaList?.prototype, key, () => css(doc));\n setter(scope.Document?.prototype, \"adoptedStyleSheets\", css);\n setter(scope.StyleSheet?.prototype, \"disabled\", css);\n // `style.disabled` switches the element's sheet without its own setter.\n setter(scope.HTMLStyleElement?.prototype, \"disabled\", (style) => {\n if (style.sheet) css(style.sheet);\n });\n method(scope.HTMLFormElement?.prototype, \"reset\", (target) => {\n for (const element of target.elements) form(element);\n });\n const dispose = () => {\n if (!active) return;\n active = false;\n for (const restore of undo.reverse()) restore();\n };\n return dispose;\n}\n","import {\n cssSourcesFor,\n type CssInputs,\n type CssSources,\n} from \"./faithful-css-text\";\nimport { installRuntimeMutations } from \"./runtime-mutations-runtime.js\";\nexport { provideStylesheetText } from \"./faithful-css-text\";\nexport { RUNTIME_MUTATION_SOURCE } from \"./runtime-mutations-source\";\n\n/** Browser-only mutation hooks shared by ordinary and isolated producers.\n * Notifications carry no values or authority: receivers read the actual DOM.\n * Private events avoid firing application input/change handlers. No polling.\n * The fixed source also installs in an isolated guest's page realm before JS.\n *\n * The one thing a receiver cannot read back from the DOM is a variable\n * shorthand whose longhands were overridden. Hooks installed before any of a\n * page's scripts (`observeCssInputs`) therefore also report what the page\n * tells the browser about its styles.\n */\nexport const FORM_RUNTIME_MUTATION = \"tempo:form-runtime-mutation\";\nexport const CSS_RUNTIME_MUTATION = \"tempo:css-runtime-mutation\";\n\n/**\n * Whether the desktop preloads observe named shorthand writes. With it on, a\n * page that has not run yet gets accessors on `CSSStyleDeclaration.prototype`\n * for named shorthand properties (`style.margin`, `style.background`), the\n * shape the CSSOM specification gives them. Without it, a named shorthand\n * assignment holding `var()` followed by a longhand prints empty values and\n * cannot be repaired.\n *\n * What a page can observe with it on, each measured in\n * faithful-css-text.playwright.ts: a spread or `Object.entries` of a\n * declaration object no longer includes shorthand keys, and a shorthand has\n * no own property descriptor. Firefox and Safari answer those the same way\n * natively. One more answer matches neither: `CSSStyleDeclaration.prototype`\n * itself now owns the shorthand names (Firefox keeps them on\n * `CSSStyleProperties.prototype`).\n *\n * Set this to false to leave the prototype untouched everywhere.\n */\nexport const OBSERVES_NAMED_SHORTHAND_WRITES = true;\n\nconst owners = new WeakMap<\n Document,\n { count: number; stop(): void; sources?: CssSources }\n>();\n\nfunction observe(\n doc: Document,\n recording?: {\n sources: CssSources;\n inputs: CssInputs;\n beforePageScripts: boolean;\n },\n): () => void {\n const view = doc.defaultView;\n if (!view) return () => {};\n let owner = owners.get(doc);\n if (!owner) {\n owner = {\n count: 0,\n stop: installRuntimeMutations(view, recording?.inputs),\n sources: recording?.sources,\n };\n owners.set(doc, owner);\n recording?.sources.startObserving({\n beforePageScripts: recording.beforePageScripts,\n });\n }\n owner.count++;\n const shared = owner;\n let released = false;\n return () => {\n if (released) return;\n released = true;\n if (--shared.count === 0) {\n shared.stop();\n // Writes are no longer reported, so recorded text can go stale.\n shared.sources?.stopObserving();\n owners.delete(doc);\n }\n };\n}\n\n/** Multiple root/head watchers share one set of hooks in their browser realm. */\nexport function observeRuntimeMutations(doc: Document): () => void {\n return observe(doc);\n}\n\n/**\n * Observes a SOURCE document: its mutations, and what its page tells the\n * browser about its styles. A write made before this is never seen, so if\n * hooks already exist this only shares them, and no stylesheet text is\n * trusted.\n *\n * `beforePageScripts` is the caller's promise that none of the page's scripts\n * has run (a preload). Without it, the stylesheets that already exist may have\n * been written unseen and are never repaired from text. `namedShorthands`\n * installs the accessors described at OBSERVES_NAMED_SHORTHAND_WRITES, and is\n * honored only with that promise, since they forward to calls a page script\n * could have replaced.\n */\nexport function observeCssInputs(\n doc: Document,\n {\n beforePageScripts = false,\n namedShorthands = false,\n }: { beforePageScripts?: boolean; namedShorthands?: boolean } = {},\n): () => void {\n const sources = cssSourcesFor(doc);\n // In an isolated world these hooks would patch prototypes the page never\n // uses. The page's own copy announces writes; nothing can report them.\n if (sources.writesUnreported || owners.has(doc)) return observe(doc);\n const inputs =\n namedShorthands && beforePageScripts\n ? sources.inputs\n : { ...sources.inputs, namedShorthands: () => [] };\n return observe(doc, { sources, inputs, beforePageScripts });\n}\n\n/**\n * For a producer in an isolated world: the page's style writes cannot be\n * reported to it, only announced. Call before any of the page's scripts.\n */\nexport function markCssWritesUnreported(doc: Document): void {\n cssSourcesFor(doc).markWritesUnreported();\n}\n","/**\n * Declared Capture Facts (producer-side)\n *\n * Computes the `DeclaredCaptureFacts` a capture producer attaches to its\n * `DomCapture`. Everything here reads the LIVE DOM the producer already\n * holds — never the serialized HTML string — so the facts are ground truth\n * rather than a re-parse of the payload. See specs/canvas-determinism.md §4.\n */\n\nimport type { DeclaredCaptureFacts } from \"./types\";\n\n/** Every source kind uses character offsets in the same annotation contract. */\nconst SOURCE_ANNOTATED_SELECTOR = \"[data-tempo-filepath]\";\n\n/**\n * Compute the declared facts for a capture.\n *\n * @param targetElement - The element whose subtree is serialized into\n * `dom.html` (the mutation LCA for scoped captures, or the capture root\n * for whole-surface ones).\n * @param captureRoot - The watched root. `complete` is `targetElement ===\n * captureRoot`. The render-error probe searches the WHOLE root (the error\n * overlay is a surface-level fact, not necessarily inside the scoped LCA).\n * @param scopeSelector - The selector the producer already computed for\n * `targetElement` relative to `captureRoot` (\"\" for whole-surface).\n * Surfaced as `scopeSelector` only when the capture is not complete.\n * @param portalElements - Live portal root elements whose content the\n * producer also serializes into `portals`. Their annotations count toward\n * `observedVersions`/`containedAnchors` exactly as the DOM subtree's do.\n */\nexport function computeDeclaredFacts(\n targetElement: Element,\n captureRoot: Element,\n scopeSelector: string,\n portalElements: readonly Element[],\n): DeclaredCaptureFacts {\n const observedVersions: Record<string, number> = {};\n const observedSourceVersions: Record<string, string> = {};\n const anchorSet = new Set<string>();\n\n const visit = (element: Element): void => {\n const filepath = element.getAttribute(\"data-tempo-filepath\");\n if (filepath == null || filepath.length === 0) return;\n\n const modifiedTsRaw = element.getAttribute(\"data-tempo-modifiedts\");\n if (modifiedTsRaw != null) {\n const modifiedTs = Number(modifiedTsRaw);\n if (!Number.isNaN(modifiedTs)) {\n const existing = observedVersions[filepath];\n if (existing === undefined || modifiedTs > existing) {\n observedVersions[filepath] = modifiedTs;\n // Co-locate the content-version token with the newest render: it\n // rides the same element that just set the file's MAX modifiedts.\n // Clear a stale token from an older render when the newest element\n // carries none (a mid-HMR mixed tree, or an old-SDK element).\n const version = element.getAttribute(\"data-tempo-source-version\");\n if (version != null && version.length > 0) {\n observedSourceVersions[filepath] = version;\n } else {\n delete observedSourceVersions[filepath];\n }\n }\n }\n }\n\n const position = element.getAttribute(\"data-tempo-position\");\n if (position != null && position.length > 0) {\n anchorSet.add(`${filepath} ${position}`);\n }\n };\n\n // The serialized population: the target subtree (including the target\n // element itself, whose annotations travel in `dom.attributes`) plus every\n // portal root and its descendants.\n const walkRoots: readonly Element[] = [targetElement, ...portalElements];\n for (const root of walkRoots) {\n if (root.matches(SOURCE_ANNOTATED_SELECTOR)) visit(root);\n for (const annotated of root.querySelectorAll(SOURCE_ANNOTATED_SELECTOR)) {\n visit(annotated);\n }\n }\n\n const complete = targetElement === captureRoot;\n\n return {\n complete,\n scopeSelector: complete ? null : scopeSelector,\n observedVersions,\n observedSourceVersions,\n containedAnchors: Array.from(anchorSet),\n renderError: computeRenderError(captureRoot),\n };\n}\n\n/**\n * Render-error boundary state for a capture root. Non-null iff a\n * `[data-render-error=\"true\"]` element exists anywhere in the live root\n * subtree (or is the root itself); its `data-render-error-message` becomes\n * `message` when present.\n */\nfunction computeRenderError(\n captureRoot: Element,\n): DeclaredCaptureFacts[\"renderError\"] {\n const errorElement = captureRoot.matches('[data-render-error=\"true\"]')\n ? captureRoot\n : captureRoot.querySelector('[data-render-error=\"true\"]');\n if (!errorElement) return null;\n return {\n message: errorElement.getAttribute(\"data-render-error-message\"),\n };\n}\n","/**\n * Capture-flush perf counters.\n *\n * Module-local mutable counters incremented by the hot paths that run inside\n * a combined-watch flush: the displayability walk's getComputedStyle reads,\n * the layout-kind style read during fiber serialization, and the\n * render-identity declaration walks. The flush resets them before capturing\n * and reads them after, shipping the totals on the emitted capture's `perf`\n * field — so the paths themselves never thread perf parameters through their\n * signatures. Increment-only: no DOM reads, no allocation.\n *\n * The same functions also run outside a flush (one-shot capture APIs); those\n * increments are simply discarded by the next flush's reset.\n */\n\ninterface CaptureFlushCounters {\n styleReadCount: number;\n identityNodesVisited: number;\n sourceVersionDomScanNodes: number;\n sourceVersionFiberSerializeNodes: number;\n sourceVersionFiberReductionNodes: number;\n sourceVersionFallbackScanNodes: number;\n}\n\nconst counters: CaptureFlushCounters = {\n styleReadCount: 0,\n identityNodesVisited: 0,\n sourceVersionDomScanNodes: 0,\n sourceVersionFiberSerializeNodes: 0,\n sourceVersionFiberReductionNodes: 0,\n sourceVersionFallbackScanNodes: 0,\n};\n\nconst producerReferencesByDocument = new Map<Document, number>();\nlet activeDocumentProducers = 0;\nlet activeRootObservers = 0;\nlet activeReactCommitSubscriptions = 0;\n\n/** Register one document producer and its one React commit subscription. */\nexport function registerDocumentCaptureProducer(\n document: Document,\n): () => void {\n const references = producerReferencesByDocument.get(document) ?? 0;\n if (references === 0) activeDocumentProducers += 1;\n producerReferencesByDocument.set(document, references + 1);\n activeReactCommitSubscriptions += 1;\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n const current = producerReferencesByDocument.get(document) ?? 0;\n if (current <= 1) {\n producerReferencesByDocument.delete(document);\n activeDocumentProducers = Math.max(0, activeDocumentProducers - 1);\n } else {\n producerReferencesByDocument.set(document, current - 1);\n }\n activeReactCommitSubscriptions = Math.max(\n 0,\n activeReactCommitSubscriptions - 1,\n );\n };\n}\n\n/** Register one independently observed projection root. */\nexport function registerCaptureRootObserver(): () => void {\n activeRootObservers += 1;\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n activeRootObservers = Math.max(0, activeRootObservers - 1);\n };\n}\n\nexport function readCaptureProducerCardinality(): {\n activeDocumentProducers: number;\n activeRootObservers: number;\n reactCommitSubscriptions: number;\n} {\n return {\n activeDocumentProducers,\n activeRootObservers,\n reactCommitSubscriptions: activeReactCommitSubscriptions,\n };\n}\n\n/** @internal Test isolation for producer ownership counters. */\nexport function _resetCaptureProducerCardinalityForTesting(): void {\n producerReferencesByDocument.clear();\n activeDocumentProducers = 0;\n activeRootObservers = 0;\n activeReactCommitSubscriptions = 0;\n}\n\n/** One getComputedStyle call on the capture path. */\nexport function countCaptureStyleRead(): void {\n counters.styleReadCount += 1;\n}\n\n/** One element/node visited by a render-identity declaration walk. */\nexport function countIdentityNodeVisited(): void {\n counters.identityNodesVisited += 1;\n}\n\nexport function countSourceVersionDomScanNode(): void {\n counters.sourceVersionDomScanNodes += 1;\n}\n\nexport function countSourceVersionFiberSerializeNode(): void {\n counters.sourceVersionFiberSerializeNodes += 1;\n}\n\nexport function countSourceVersionFiberReductionNode(): void {\n counters.sourceVersionFiberReductionNodes += 1;\n}\n\nexport function countSourceVersionFallbackScanNode(): void {\n counters.sourceVersionFallbackScanNodes += 1;\n}\n\nexport function resetCaptureFlushCounters(): void {\n counters.styleReadCount = 0;\n counters.identityNodesVisited = 0;\n counters.sourceVersionDomScanNodes = 0;\n counters.sourceVersionFiberSerializeNodes = 0;\n counters.sourceVersionFiberReductionNodes = 0;\n counters.sourceVersionFallbackScanNodes = 0;\n}\n\nexport function readCaptureFlushCounters(): Readonly<CaptureFlushCounters> {\n return { ...counters };\n}\n","import { countCaptureStyleRead } from \"../shared/capture-perf\";\nimport type { CaptureDisplayability } from \"./types\";\n\n/** Elements whose descendants do not contribute projected pixels/content. */\nconst IGNORED_CONTENT_TAGS = new Set([\n \"DATALIST\",\n \"LINK\",\n \"META\",\n \"NOSCRIPT\",\n \"SCRIPT\",\n \"STYLE\",\n \"TEMPLATE\",\n]);\n\nconst VISUAL_ASSET_TAGS = new Set([\n \"AUDIO\",\n \"CANVAS\",\n \"EMBED\",\n \"IFRAME\",\n \"IMG\",\n \"INPUT\",\n \"OBJECT\",\n \"SELECT\",\n \"SVG\",\n \"TEXTAREA\",\n \"VIDEO\",\n]);\n\n/**\n * Measures displayable structure in a live, styled document.\n *\n * The capture root itself is excluded because `DomCapture.dom.html` contains\n * its children. Supplemental roots are included because portal updates carry\n * each portal root's `outerHTML`. A null result means no browsing context was\n * available, so callers must omit the proof rather than infer it from markup.\n */\nexport function measureComputedDisplayability(\n captureRoot: Element,\n supplementalRoots: readonly Element[] = [],\n): CaptureDisplayability | null {\n const doc = captureRoot.ownerDocument;\n const view = doc.defaultView;\n if (\n !view ||\n !captureRoot.isConnected ||\n supplementalRoots.some(\n (root) => root.ownerDocument !== doc || !root.isConnected,\n )\n ) {\n return null;\n }\n\n const result: CaptureDisplayability = {\n version: 1,\n elementCount: 0,\n paintedElementCount: 0,\n nonEmptyTextNodeCount: 0,\n visualAssetCount: 0,\n };\n\n try {\n const rootBlocked = hasBlockingElementInChain(captureRoot, view);\n const rootTextVisible =\n !rootBlocked && elementHasVisibleComputedVisibility(captureRoot, view);\n for (const child of Array.from(captureRoot.childNodes)) {\n visitNode(child, rootBlocked, rootTextVisible, view, result);\n }\n\n for (const supplementalRoot of supplementalRoots) {\n visitNode(\n supplementalRoot,\n hasBlockingElementInChain(supplementalRoot.parentElement, view),\n true,\n view,\n result,\n );\n }\n } catch {\n // A producer declaration is proof. If style inspection is unavailable for\n // any part of the render domain, omit the whole profile conservatively.\n return null;\n }\n\n return result;\n}\n\nfunction visitNode(\n node: Node,\n blockedByAncestor: boolean,\n parentTextVisible: boolean,\n view: Window,\n result: CaptureDisplayability,\n): void {\n if (node.nodeType === 3) {\n if (\n !blockedByAncestor &&\n parentTextVisible &&\n (node.textContent?.trim().length ?? 0) > 0\n ) {\n result.nonEmptyTextNodeCount += 1;\n }\n return;\n }\n if (node.nodeType !== 1) return;\n\n const element = node as Element;\n const blocked = blockedByAncestor || elementBlocksSubtree(element, view);\n if (blocked) return;\n\n const visible = elementHasVisibleComputedVisibility(element, view);\n if (visible) {\n result.elementCount += 1;\n if (elementPaintsOwnPixels(element, view)) {\n result.paintedElementCount = (result.paintedElementCount ?? 0) + 1;\n }\n if (VISUAL_ASSET_TAGS.has(element.tagName)) {\n result.visualAssetCount += 1;\n }\n }\n\n for (const child of Array.from(element.childNodes)) {\n visitNode(child, false, visible, view, result);\n }\n}\n\nfunction elementPaintsOwnPixels(element: Element, view: Window): boolean {\n countCaptureStyleRead();\n const style = view.getComputedStyle(element);\n if (colorCanPaint(style.backgroundColor)) return true;\n if (style.backgroundImage && style.backgroundImage !== \"none\") return true;\n if (style.boxShadow && style.boxShadow !== \"none\") return true;\n if (\n style.outlineStyle !== \"none\" &&\n parseFloat(style.outlineWidth) > 0 &&\n colorCanPaint(style.outlineColor)\n ) {\n return true;\n }\n for (const side of [\"Top\", \"Right\", \"Bottom\", \"Left\"] as const) {\n if (\n style[`border${side}Style`] !== \"none\" &&\n parseFloat(style[`border${side}Width`]) > 0 &&\n colorCanPaint(style[`border${side}Color`])\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction colorCanPaint(value: string): boolean {\n const normalized = value.trim().toLowerCase().replace(/ /g, \"\");\n if (!normalized || normalized === \"transparent\") return false;\n return !(\n /^rgba\\([^)]*,0(?:\\.0+)?\\)$/.test(normalized) ||\n /^rgb\\([^)]*\\/0(?:\\.0+)?\\)$/.test(normalized)\n );\n}\n\nfunction hasBlockingElementInChain(\n start: Element | null,\n view: Window,\n): boolean {\n for (let element = start; element; element = element.parentElement) {\n if (elementBlocksSubtree(element, view)) return true;\n }\n return false;\n}\n\nfunction elementBlocksSubtree(element: Element, view: Window): boolean {\n if (IGNORED_CONTENT_TAGS.has(element.tagName)) return true;\n if (element.hasAttribute(\"hidden\")) return true;\n if (element.tagName === \"DIALOG\" && !element.hasAttribute(\"open\")) {\n return true;\n }\n if (\n element.tagName === \"INPUT\" &&\n element.getAttribute(\"type\")?.trim().toLowerCase() === \"hidden\"\n ) {\n return true;\n }\n\n countCaptureStyleRead();\n const style = view.getComputedStyle(element);\n const opacity = style.opacity.trim();\n return (\n style.display === \"none\" ||\n (opacity.length > 0 && Number(opacity) <= 0) ||\n style.getPropertyValue(\"content-visibility\") === \"hidden\"\n );\n}\n\nfunction elementHasVisibleComputedVisibility(\n element: Element,\n view: Window,\n): boolean {\n countCaptureStyleRead();\n const visibility = view.getComputedStyle(element).visibility;\n return visibility !== \"hidden\" && visibility !== \"collapse\";\n}\n","/**\n * CSS Selector Utilities\n *\n * Pure functions for generating CSS selectors.\n */\n\n/**\n * Generates a unique CSS selector path for an element.\n *\n * Uses nth-of-type notation when needed for uniqueness among siblings.\n *\n * @param element - Element to generate selector for\n * @param root - Optional root element to stop at (selector will be relative to this)\n * @returns CSS selector path (e.g., \"body > div > button:nth-of-type(2)\")\n *\n * @example\n * ```ts\n * generateSelector(document.querySelector('button'));\n * // \"body > div > button\"\n *\n * generateSelector(button, container);\n * // \"div > button\" (relative to container)\n * ```\n */\nexport function generateSelector(element: Element, root?: Element): string {\n // Special cases for well-known elements\n if (!root) {\n if (element === document.documentElement) return \":root\";\n if (element === document.head) return \"head\";\n if (element === document.body) return \"body\";\n }\n\n // If element is the root, return empty string\n if (root && element === root) return \"\";\n\n const parts: string[] = [];\n let current: Element | null = element;\n const stopAt = root ?? document.documentElement;\n\n while (current && current !== stopAt) {\n const parent: Element | null = current.parentElement;\n if (!parent) break;\n\n const tagName = current.tagName.toLowerCase();\n\n // Count same-type siblings to determine if :nth-of-type is needed\n let index = 1;\n let sibling = current.previousElementSibling;\n while (sibling) {\n if (sibling.tagName === current.tagName) index++;\n sibling = sibling.previousElementSibling;\n }\n\n let sameTypeSiblings = 0;\n for (const child of parent.children) {\n if (child.tagName === current.tagName) sameTypeSiblings++;\n }\n\n if (sameTypeSiblings > 1) {\n parts.unshift(`${tagName}:nth-of-type(${index})`);\n } else {\n parts.unshift(tagName);\n }\n\n current = parent;\n }\n\n // Handle edge cases\n if (parts.length === 0) {\n if (element === document.body) return \"body\";\n if (element === document.head) return \"head\";\n return \"\";\n }\n\n const path = parts.join(\" > \");\n\n // Anchor to root with :scope so querySelector matches at the correct depth.\n // Without this, \"div > div > div:nth-of-type(2)\" is ambiguous — it can match\n // any ancestor chain of divs at any depth within the subtree, not just the\n // specific depth from the root. :scope pins the first segment to a direct\n // child of the querySelector target.\n if (root) return `:scope > ${path}`;\n\n return path;\n}\n\n/**\n * Finds the Lowest Common Ancestor (LCA) of a set of nodes.\n *\n * The LCA is the deepest element that is an ancestor of all provided nodes.\n * Useful for determining the minimal subtree that contains all mutations.\n *\n * @param nodes - Set of DOM nodes to find common ancestor for\n * @returns The LCA element, or null if no common ancestor found\n */\nexport function findLowestCommonAncestor(nodes: Set<Node>): Element | null {\n if (nodes.size === 0) return null;\n\n // Build ancestor chains for each node (from root to node)\n const ancestorChains: Element[][] = [];\n\n for (const node of nodes) {\n const chain: Element[] = [];\n let current: Node | null =\n node instanceof Element ? node : node.parentElement;\n\n while (current && current !== document) {\n if (current instanceof Element) {\n chain.unshift(current);\n }\n current = current.parentNode;\n }\n\n if (chain.length > 0) {\n ancestorChains.push(chain);\n }\n }\n\n if (ancestorChains.length === 0) {\n return document.documentElement;\n }\n\n // Find the deepest common ancestor by comparing chains\n let lca: Element = document.documentElement;\n const firstChain = ancestorChains[0]!;\n const minLength = Math.min(...ancestorChains.map((c) => c.length));\n\n for (let i = 0; i < minLength; i++) {\n const candidate = firstChain[i];\n if (candidate && ancestorChains.every((chain) => chain[i] === candidate)) {\n lca = candidate;\n } else {\n break;\n }\n }\n\n return lca;\n}\n","/**\n * DOM Capture\n *\n * One-shot capture of DOM content and element states.\n */\n\nimport { computeDeclaredFacts } from \"./declared-facts\";\nimport { measureComputedDisplayability } from \"./displayability\";\nimport { generateSelector } from \"./selectors\";\nimport type { DomCapture, ElementState } from \"./types\";\n\nexport interface CollectElementStatesOptions {\n /** Whether to include document-level scroll via the :root selector. */\n includeDocumentScroll?: boolean;\n}\n\n/**\n * Captures the current state of an element as a DomCapture.\n *\n * @param element - Element to capture\n * @returns DomCapture containing HTML and element states\n *\n * @example\n * ```ts\n * const snapshot = capture(document.body);\n * // { dom: { selector: \"body\", html: \"...\" }, states: [...] }\n * ```\n */\nexport function capture(element: Element): DomCapture {\n return captureWithSupplementalRoots(element, []);\n}\n\n/** Internal complete-capture primitive used when a higher-level producer also\n * serializes supplemental roots such as owned React portals. */\nexport function captureWithSupplementalRoots(\n element: Element,\n supplementalRoots: readonly Element[],\n): DomCapture {\n // Sync form state to attributes before serializing\n syncFormStateToAttributes(element);\n\n // Selector relative to itself = \"\" (this IS the container)\n const selector = generateSelector(element, element);\n // Use innerHTML - we capture the children, not the container itself\n const html = removeScriptTags(element.innerHTML);\n const attributes = captureAttributes(element);\n const documentElementAttributes = element.ownerDocument\n ? captureAttributes(element.ownerDocument.documentElement)\n : undefined;\n const bodyAttributes = element.ownerDocument?.body\n ? captureAttributes(element.ownerDocument.body)\n : undefined;\n const baseUrl = element.ownerDocument?.baseURI;\n const states = collectElementStates(element);\n const displayability = measureComputedDisplayability(\n element,\n supplementalRoots,\n );\n\n return {\n // Whole-surface one-shot: the element is both the capture root and the\n // serialized scope, so `complete` is true and there is no scope selector.\n declared: computeDeclaredFacts(element, element, \"\", supplementalRoots),\n ...(displayability && { displayability }),\n dom: {\n selector,\n html,\n attributes,\n documentElementAttributes,\n bodyAttributes,\n },\n states,\n baseUrl,\n };\n}\n\n/**\n * Syncs form element state (DOM properties) to HTML attributes.\n *\n * Form elements like checkboxes, selects, and inputs have runtime state\n * that isn't reflected in their HTML attributes. This syncs that state\n * to attributes so it survives serialization.\n */\nfunction syncFormStateToAttributes(root: Element): void {\n // Checkboxes and radios\n for (const input of root.querySelectorAll(\n 'input[type=\"checkbox\"], input[type=\"radio\"]',\n )) {\n const el = input as HTMLInputElement;\n if (el.checked) {\n el.setAttribute(\"checked\", \"\");\n } else {\n el.removeAttribute(\"checked\");\n }\n }\n\n // Text inputs\n for (const input of root.querySelectorAll(\n 'input:not([type=\"checkbox\"]):not([type=\"radio\"])',\n )) {\n const el = input as HTMLInputElement;\n if (el.value !== el.getAttribute(\"value\")) {\n el.setAttribute(\"value\", el.value);\n }\n }\n\n // Textareas\n for (const textarea of root.querySelectorAll(\"textarea\")) {\n const el = textarea as HTMLTextAreaElement;\n if (el.value !== el.textContent) {\n el.textContent = el.value;\n }\n if (el.hasAttribute(\"value\")) {\n el.removeAttribute(\"value\");\n }\n }\n\n // Selects\n for (const select of root.querySelectorAll(\"select\")) {\n const el = select as HTMLSelectElement;\n for (const option of el.options) {\n if (option.selected) {\n option.setAttribute(\"selected\", \"\");\n } else {\n option.removeAttribute(\"selected\");\n }\n }\n }\n}\n\n/**\n * Removes all script tags from HTML string.\n */\nexport function removeScriptTags(html: string): string {\n return html.replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/gi, \"\");\n}\n\n/**\n * Captures attributes from an element into a serializable map.\n */\nexport function captureAttributes(element: Element): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const attr of Array.from(element.attributes)) {\n attrs[attr.name] = attr.value;\n }\n return attrs;\n}\n\n/**\n * Collects current element states from a root element.\n *\n * Walks form elements and scrollable containers to collect their runtime state.\n */\nexport function collectElementStates(\n root: Element,\n options: CollectElementStatesOptions = {},\n): ElementState[] {\n const { includeDocumentScroll = true } = options;\n const states: ElementState[] = [];\n\n // Collect form states\n for (const input of root.querySelectorAll(\"input\")) {\n const el = input as HTMLInputElement;\n const isCheckable = el.type === \"checkbox\" || el.type === \"radio\";\n const hasNonDefault = isCheckable\n ? el.checked !== el.defaultChecked\n : el.value !== el.defaultValue;\n\n if (hasNonDefault) {\n const selector = generateSelector(el, root);\n if (isCheckable) {\n states.push({ selector, checked: el.checked });\n } else {\n states.push({ selector, value: el.value });\n }\n }\n }\n\n for (const textarea of root.querySelectorAll(\"textarea\")) {\n const el = textarea as HTMLTextAreaElement;\n if (el.value !== el.defaultValue) {\n const selector = generateSelector(el, root);\n states.push({ selector, value: el.value });\n }\n }\n\n for (const select of root.querySelectorAll(\"select\")) {\n const el = select as HTMLSelectElement;\n for (const option of el.options) {\n if (option.selected !== option.defaultSelected) {\n const selector = generateSelector(option, root);\n states.push({ selector, selected: option.selected });\n }\n }\n }\n\n // Collect scroll states - always include root and document-level scroll\n // so that scrolling back to 0 is properly communicated.\n states.push({\n selector: \"\",\n scrollTop: root.scrollTop,\n scrollLeft: root.scrollLeft,\n });\n\n // Check document-level scroll (scrollingElement, usually <html>)\n // This handles the common case where scroll is on documentElement, not body\n if (includeDocumentScroll) {\n const scrollingEl = root.ownerDocument?.scrollingElement;\n if (scrollingEl && scrollingEl !== root) {\n states.push({\n selector: \":root\",\n scrollTop: scrollingEl.scrollTop,\n scrollLeft: scrollingEl.scrollLeft,\n });\n }\n }\n\n for (const el of root.querySelectorAll(\"*\")) {\n if (el.scrollTop > 0 || el.scrollLeft > 0) {\n const selector = generateSelector(el, root);\n states.push({\n selector,\n scrollTop: el.scrollTop,\n scrollLeft: el.scrollLeft,\n });\n }\n }\n\n return states;\n}\n"],"mappings":";AAqHA,IAAM,uBAAuB;AAMtB,SAAS,YAAY,SAA0B;AAGpD,SACE,sBAAsB,KAAK,OAAO,KAClC,sDAAsD,KAAK,OAAO;AAEtE;AAEA,IAAM,YAAY;AAClB,IAAM,QAAQ;AACd,IAAM,OAAO;AACb,IAAM,eAAe;AACrB,IAAM,eAAe;AACrB,IAAM,aAAa;AACnB,IAAM,cAAc;AACpB,IAAM,eAAe;AACrB,IAAM,gBAAgB;AACtB,IAAM,aAAa;AACnB,IAAM,cAAc;AACpB,IAAM,YAAY;AAClB,IAAM,QAAQ;AAGd,IAAM,gBAAgB,CAAC,SACrB,SAAS,aACT,SAAS,SACT,SAAS,gBACT,SAAS,gBACT,SAAS;AAOX,SAAS,UAAU,MAAc,OAAuB;AACtD,QAAM,OAAO,KAAK,WAAW,KAAK;AAClC,MAAI,SAAS,UAAW,QAAO,QAAQ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,QAAI,eAAe,gBAAgB,MAAM;AACvC,aAAO,KAAK;AAAA,QACV,UAAU;AAAA,QACV,WAAW,YAAY;AAAA,QACvB,YAAY,YAAY;AAAA,MAC1B,CAAC;AAAA,IACH;AAAA,EACF;AAEA,aAAW,MAAM,KAAK,iBAAiB,GAAG,GAAG;AAC3C,QAAI,GAAG,YAAY,KAAK,GAAG,aAAa,GAAG;AACzC,YAAM,WAAW,iBAAiB,IAAI,IAAI;AAC1C,aAAO,KAAK;AAAA,QACV;AAAA,QACA,WAAW,GAAG;AAAA,QACd,YAAY,GAAG;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT;","names":["at","CSS_RUNTIME_MUTATION","document"]}
@@ -2,8 +2,11 @@ import {
2
2
  PROJECTION_PENDING_ATTRIBUTE,
3
3
  PROJECTION_ROOT_ATTRIBUTE,
4
4
  PROJECTION_SCOPE_ROLE,
5
- PROJECTION_UNAVAILABLE_ATTRIBUTE
6
- } from "./chunk-3L4RRKC3.js";
5
+ PROJECTION_UNAVAILABLE_ATTRIBUTE,
6
+ canvasClientProtocol,
7
+ isPreV3CanvasClient,
8
+ v2StoryboardSlotPosition
9
+ } from "./chunk-ZW26VZHX.js";
7
10
 
8
11
  // canvas/ids.ts
9
12
  function normalizeId(value, label) {
@@ -790,18 +793,6 @@ function installStoryboardVisibilityObserver() {
790
793
  };
791
794
  }
792
795
 
793
- // canvas/client-protocol.ts
794
- var CANVAS_CLIENT_PROTOCOL_PARAM = "canvasProtocol";
795
- function canvasClientProtocol() {
796
- if (typeof window === "undefined") return 1;
797
- const value = new URLSearchParams(window.location.search).get(
798
- CANVAS_CLIENT_PROTOCOL_PARAM
799
- );
800
- if (value === null) return 1;
801
- const protocol = Number(value.trim());
802
- return Number.isInteger(protocol) && protocol >= 1 ? protocol : 1;
803
- }
804
-
805
796
  // canvas/v1-client-compat.ts
806
797
  function isV1CanvasClient() {
807
798
  return canvasClientProtocol() < 2;
@@ -1124,8 +1115,10 @@ function StoryboardSlot({
1124
1115
  status
1125
1116
  }) : {
1126
1117
  position: "absolute",
1127
- left: placement?.left ?? (fixed ? layout.x : 0),
1128
- top: placement?.top ?? (fixed ? layout.y : 0),
1118
+ // Canvas placement belongs to the renderer. Source components
1119
+ // share an origin so their DOM never encodes canvas coordinates.
1120
+ // A protocol-2 client measures the slot where 0.0.94 put it.
1121
+ ...isPreV3CanvasClient() ? v2StoryboardSlotPosition({ layout, placement, fixed }) : { left: 0, top: 0 },
1129
1122
  ...fixed ? { width: renderWidth, height: renderHeight } : {},
1130
1123
  zIndex: layout.zIndex,
1131
1124
  // A hidden shell is already out of hit testing. It must not also
@@ -1312,4 +1305,4 @@ export {
1312
1305
  HtmlStoryboard,
1313
1306
  StoryboardSlot
1314
1307
  };
1315
- //# sourceMappingURL=chunk-FZVJVL3T.js.map
1308
+ //# sourceMappingURL=chunk-X5DJKVBT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../canvas/ids.ts","../canvas/canvas.tsx","../canvas/runtime-context.ts","../canvas/storyboard.tsx","../canvas/admission-budget.ts","../canvas/canvas-pending-marker.tsx","../canvas/portal-tracking.ts","../canvas/render-error-recovery.ts","../canvas/responsive-slot-size.ts","../canvas/storyboard-visibility.ts","../canvas/v1-client-compat.ts"],"sourcesContent":["export function normalizeId(value: string | undefined, label: string): string {\n const normalized = value?.trim();\n if (!normalized) {\n throw new Error(`${label} is required.`);\n }\n return normalized;\n}\n\n/** Canvas and editor previews use the same key for an unkeyed declaration. */\nexport function getStoryboardKey(id: string): string {\n return `storyboard:${id}`;\n}\n","import {\n Children,\n cloneElement,\n createContext,\n isValidElement,\n useContext,\n useMemo,\n type HTMLAttributes,\n type ReactNode,\n} from \"react\";\n\nimport { getStoryboardKey, normalizeId } from \"./ids\";\n\n/**\n * What the canvas needs from the page beside its storyboards, stamped on the\n * Canvas element as one JSON attribute; each Storyboard shell carries its\n * own. The projection carries both as ordinary layer props; the canvas\n * validates what it reads, so nothing is checked here.\n */\nexport interface CanvasDeclaration {\n path: string;\n /** Absent when the Canvas has no name; the canvas then names the page\n * after its file. */\n name?: string;\n backgroundColor?: string;\n defaultViewport?: { x: number; y: number; zoom: number };\n}\n\ntype CanvasIdentity = {\n path: string;\n};\n\nconst CanvasIdentityContext = createContext<CanvasIdentity | null>(null);\n\nexport function getCanvasStoryboardRenderId(\n canvasPath: string,\n storyboardId: string,\n): string {\n return `canvas:${encodeURIComponent(\n normalizeId(canvasPath, \"Canvas path\"),\n )}#storyboard:${encodeURIComponent(\n normalizeId(storyboardId, \"Storyboard id\"),\n )}`;\n}\n\nexport function useCanvasIdentity(): CanvasIdentity | null {\n return useContext(CanvasIdentityContext);\n}\n\nexport function useCanvasStoryboardRenderId(storyboardId: string): string {\n const canvas = useCanvasIdentity();\n const normalizedId = normalizeId(storyboardId, \"Storyboard id\");\n return canvas\n ? getCanvasStoryboardRenderId(canvas.path, normalizedId)\n : normalizedId;\n}\n\nexport function Canvas({\n children,\n name,\n path,\n backgroundColor,\n defaultViewport,\n ...sourceAnnotations\n}: {\n children?: ReactNode;\n name?: string;\n path?: string;\n backgroundColor?: string;\n defaultViewport?: { x: number; y: number; zoom: number };\n} & Record<`data-tempo-${string}`, unknown>) {\n const contextIdentity = useCanvasIdentity();\n // A Canvas without a name, or with a blank one, still declares its page\n // and the canvas names it after its file (V2-446). Throwing here kept the\n // page root from ever publishing, so the page stayed loading.\n const canvasName = name?.trim() || undefined;\n const canvasPath =\n path === undefined\n ? contextIdentity?.path\n : normalizeId(path, \"Canvas path\");\n\n if (!canvasPath) {\n throw new Error(\n '<Canvas> must be rendered inside <CanvasContext path=\"...\"> or receive a path prop.',\n );\n }\n\n const identity = useMemo(() => ({ path: canvasPath }), [canvasPath]);\n const declaration: CanvasDeclaration = {\n path: canvasPath,\n ...(canvasName ? { name: canvasName } : {}),\n backgroundColor,\n defaultViewport,\n };\n\n // Key each storyboard child by its declared id so React reconciles slots\n // by STORYBOARD IDENTITY rather than child position. Canvas files declare\n // storyboards as static JSX siblings (no keys), and positional\n // reconciliation reuses one storyboard's slot DOM node for another when\n // an edit inserts or removes a sibling above it — but slot DOM identity\n // is load-bearing: capture watchers, portal tracking, and the pool's\n // render-content wrappers all anchor to the slot node, and a reused node\n // silently starts feeding one storyboard's pipeline with another's\n // render.\n const keyedChildren = useMemo(() => {\n const automatic = new Set<string>();\n const flattened = Children.map(children, (child) => {\n if (isValidElement(child) && child.key == null) {\n const id = (child.props as { id?: unknown }).id;\n if (typeof id === \"string\" && id.length) automatic.add(id);\n }\n return child;\n });\n // Apply automatic keys AFTER Children.map: keys returned from its callback\n // are combined with the original sibling position, so deleting a board\n // would otherwise remount every unkeyed sibling after it. Authored keys\n // retain React's normal nested-array scoping.\n return flattened?.map((child) => {\n if (!isValidElement(child)) return child;\n const id = (child.props as { id?: unknown }).id;\n return typeof id === \"string\" && automatic.has(id)\n ? cloneElement(child, { key: getStoryboardKey(id) })\n : child;\n });\n }, [children]);\n\n return (\n <CanvasIdentityContext.Provider value={identity}>\n <div\n {...(sourceAnnotations as HTMLAttributes<HTMLDivElement>)}\n data-tempo-canvas={canvasName}\n data-tempo-canvas-path={canvasPath}\n data-tempo-canvas-declaration={JSON.stringify(declaration)}\n >\n {keyedChildren}\n </div>\n </CanvasIdentityContext.Provider>\n );\n}\n\nexport function CanvasContext({\n children,\n path,\n}: {\n children?: ReactNode;\n path: string;\n}) {\n const canvasPath = normalizeId(path, \"Canvas path\");\n const identity = useMemo(() => ({ path: canvasPath }), [canvasPath]);\n return (\n <CanvasIdentityContext.Provider value={identity}>\n {children}\n </CanvasIdentityContext.Provider>\n );\n}\n","import { createContext, useCallback, useContext } from \"react\";\n\nimport { useCanvasStoryboardRenderId } from \"./canvas\";\nimport type { V1RenderSizeCompat } from \"./v1-client-compat\";\n\nexport type CanvasHostRuntimeError = {\n message: string;\n stack?: string;\n componentStack?: string;\n};\n\nexport type CanvasHostRuntimeSize = V1RenderSizeCompat & {\n width?: number | string;\n height?: number | string;\n revision?: number;\n};\n\nexport type CanvasHostRuntimePlacement = {\n left: number;\n top: number;\n};\n\nexport type CanvasHostRuntime = {\n getStoryboardStatus(storyboardId: string): \"active\" | \"cached\" | \"unmounted\";\n getStoryboardSize(storyboardId: string): CanvasHostRuntimeSize | undefined;\n getStoryboardPlacement(\n storyboardId: string,\n ): CanvasHostRuntimePlacement | undefined;\n /** Reset capture-only inputs after imports, before a fresh user-tree mount.\n * Only the direct URL's selected storyboard may reset the document RNG. */\n prepareStoryboardCapture?(storyboardId: string): void;\n markStoryboardRendered(storyboardId: string): void;\n markStoryboardUnmounted(storyboardId: string): void;\n reportStoryboardError(\n storyboardId: string,\n error: CanvasHostRuntimeError,\n ): void;\n clearStoryboardError(storyboardId: string): void;\n reportCanvasImportError(\n canvasPath: string,\n error: CanvasHostRuntimeError,\n ): void;\n clearCanvasImportError(canvasPath: string): void;\n /**\n * Declares a canvas path as a problem-attribution candidate while its\n * boundary is mounted. Host-level Vite diagnostics that uniquely name a\n * registered canvas's source are scoped to that canvas instead of being\n * shown host-wide on every sibling. Returns the unregister disposer.\n */\n registerCanvasProblemScope(canvasPath: string): () => void;\n};\n\nexport const CanvasHostContext = createContext<CanvasHostRuntime | null>(null);\n\nexport function useRequiredCanvasHost(): CanvasHostRuntime {\n const host = useContext(CanvasHostContext);\n if (!host) {\n throw new Error(\n \"Tempo canvas components must be rendered inside <CanvasHost>.\",\n );\n }\n return host;\n}\n\nexport function useActiveState(storyboardId: string): boolean {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return host.getStoryboardStatus(renderId) !== \"unmounted\";\n}\n\nexport function useStoryboardStatus(\n storyboardId: string,\n): \"active\" | \"cached\" | \"unmounted\" {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return host.getStoryboardStatus(renderId);\n}\n\nexport function useStoryboardRendered(storyboardId: string): () => void {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return useCallback(() => {\n host.markStoryboardRendered(renderId);\n }, [host, renderId]);\n}\n\nexport function useStoryboardUnmounted(storyboardId: string): () => void {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const { markStoryboardUnmounted } = useRequiredCanvasHost();\n return useCallback(() => {\n markStoryboardUnmounted(renderId);\n }, [markStoryboardUnmounted, renderId]);\n}\n\nexport function useStoryboardErrorReporter(storyboardId: string): {\n reportError(error: CanvasHostRuntimeError): void;\n clearError(): void;\n} {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n const reportError = useCallback(\n (error: CanvasHostRuntimeError) => {\n host.reportStoryboardError(renderId, error);\n },\n [host, renderId],\n );\n const clearError = useCallback(() => {\n host.clearStoryboardError(renderId);\n }, [host, renderId]);\n return { reportError, clearError };\n}\n\nexport function useStoryboardSize(\n storyboardId: string,\n): CanvasHostRuntimeSize | undefined {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return host.getStoryboardSize(renderId);\n}\n\nexport function useStoryboardPlacement(\n storyboardId: string,\n): CanvasHostRuntimePlacement | undefined {\n const renderId = useCanvasStoryboardRenderId(storyboardId);\n const host = useRequiredCanvasHost();\n return host.getStoryboardPlacement(renderId);\n}\n","import {\n Children,\n Component,\n type ComponentType,\n cloneElement,\n type ErrorInfo,\n isValidElement,\n type ReactNode,\n Suspense,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { PROJECTION_ROOT_ATTRIBUTE } from \"../../../modules/iframe-projection/combined/projection-layer-snapshot\";\nimport { PROJECTION_SCOPE_ROLE } from \"../../../modules/iframe-projection/fiber/projection-scope\";\n\nimport type { TempoStoryboard } from \"../page\";\nimport { beginAdmissionWindow } from \"./admission-budget\";\nimport { useCanvasIdentity, useCanvasStoryboardRenderId } from \"./canvas\";\nimport { CanvasPendingMarker } from \"./canvas-pending-marker\";\nimport {\n syncStoryboardPortals,\n trackStoryboardPortals,\n} from \"./portal-tracking\";\nimport { useRenderErrorRecovery } from \"./render-error-recovery\";\nimport { observeResponsiveSlotSize } from \"./responsive-slot-size\";\nimport {\n useRequiredCanvasHost,\n useStoryboardErrorReporter,\n useStoryboardPlacement,\n useStoryboardRendered,\n useStoryboardSize,\n useStoryboardStatus,\n useStoryboardUnmounted,\n} from \"./runtime-context\";\nimport { installStoryboardVisibilityObserver } from \"./storyboard-visibility\";\nimport {\n isV1CanvasClient,\n type V1LayoutCompat,\n v1SourceAnnotations,\n v1StoryboardSlotStyle,\n} from \"./v1-client-compat\";\nimport {\n isPreV3CanvasClient,\n v2StoryboardSlotPosition,\n} from \"./v2-client-compat\";\n\nexport interface StoryboardLayout extends V1LayoutCompat {\n x: number;\n y: number;\n width?: number;\n height?: number;\n zIndex?: number;\n}\n\n/** A storyboard's declaration as its shell stamps it (one JSON attribute):\n * the Storyboard callsite's props, without the source annotations. */\nexport interface StoryboardDeclaration {\n id: string;\n name?: string;\n kind: \"component\" | \"route\" | \"html\";\n layout: {\n x: number;\n y: number;\n width?: number;\n height?: number;\n zIndex?: number;\n };\n route?: string;\n filepath?: string;\n /** @deprecated Retained for v2 clients; prefer filepath for local HTML. */\n src?: string;\n vrt?: boolean;\n uiFramework?: \"svelte\" | \"vue\" | \"astro\";\n /** A Flutter board's `lib/<file>.dart#<function>`: its whole content, so a\n * duplicate needs it to write the same board. */\n preview?: string;\n previewKey?: string;\n}\n\nexport interface StoryboardVrtIgnoreRegion {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * Opt-in visual-regression tracking config (TEM-1775). The `vrt` prop is a\n * static, build-time mark read by AST enumeration (`parseCanvasFile`) — it\n * has no runtime behavior. Values must be literals to be tracked.\n */\nexport interface StoryboardVrtConfig {\n /** Per-storyboard pixelmatch threshold override (0..0.5). */\n threshold?: number;\n /** Temporarily untracked without losing config. */\n skip?: boolean;\n /** Regions (storyboard-local px) excluded from comparison. */\n ignore?: StoryboardVrtIgnoreRegion[];\n}\n\nexport function Storyboard<Props extends object = object>({\n id,\n name,\n component,\n layout,\n props,\n vrt,\n ...annotations\n}: {\n id: string;\n component: ComponentType<Props>;\n layout: StoryboardLayout;\n name?: string;\n props?: Props;\n [annotation: `data-tempo-${string}`]: unknown;\n /** Opt this storyboard into visual regression testing (static mark). */\n vrt?: boolean | StoryboardVrtConfig;\n} & Record<`data-tempo-${string}`, unknown>) {\n const Component = component as ComponentType<Props>;\n const content = isV1CanvasClient() ? (\n <Component\n {...(props ?? ({} as Props))}\n {...v1SourceAnnotations(annotations)}\n />\n ) : (\n <Component {...(props ?? ({} as Props))} />\n );\n\n return (\n <StoryboardSlot\n data-tempo-hide-fiber=\"true\"\n id={id}\n name={name}\n layout={layout}\n kind=\"component\"\n vrt={!!vrt}\n >\n <ProjectionContent>{content}</ProjectionContent>\n </StoryboardSlot>\n );\n}\n\nexport function LegacyStoryboardV1({\n id,\n storyboard,\n}: {\n id: string;\n storyboard: TempoStoryboard;\n}) {\n return (\n <StoryboardSlot\n data-tempo-hide-fiber=\"true\"\n id={id}\n name={storyboard.name}\n layout={storyboard.layout}\n kind=\"component\"\n >\n <LegacyStoryboardV1Render render={storyboard.render} />\n </StoryboardSlot>\n );\n}\n\nfunction LegacyStoryboardV1Render({\n render,\n}: {\n render: TempoStoryboard[\"render\"];\n}) {\n return <>{render()}</>;\n}\n\nexport function RouteStoryboard({\n id,\n name,\n route,\n layout,\n ...annotations\n}: {\n id: string;\n route: string;\n layout: StoryboardLayout & { width: number; height: number };\n name?: string;\n} & Record<`data-tempo-${string}`, unknown>) {\n return (\n <StoryboardSlot\n data-tempo-hide-fiber=\"true\"\n id={id}\n name={name}\n layout={layout}\n kind=\"route\"\n route={route}\n />\n );\n}\n\nexport function HtmlStoryboard({\n id,\n name,\n filepath,\n src,\n layout,\n vrt,\n ...annotations\n}: {\n id: string;\n layout: StoryboardLayout & { width: number; height: number };\n filepath?: string;\n /** @deprecated Retained for v2 clients; prefer filepath for local HTML. */\n src?: string;\n name?: string;\n /** Opt this local HTML storyboard into visual regression testing. */\n vrt?: boolean | StoryboardVrtConfig;\n} & Record<`data-tempo-${string}`, unknown>) {\n return (\n <StoryboardSlot\n data-tempo-hide-fiber=\"true\"\n id={id}\n name={name}\n layout={layout}\n kind=\"html\"\n filepath={filepath}\n src={src}\n vrt={!!vrt}\n />\n );\n}\n\n/**\n * The shell every storyboard kind renders. It is SDK plumbing between the\n * public component (the callsite the compiler annotates) and the shell\n * element, so every caller hides its fiber: the projection then sees the\n * public component as the shell's parent, which the canvas reads as the\n * storyboard's root layer.\n */\nexport function StoryboardSlot({\n children,\n id,\n kind,\n layout,\n name,\n route,\n filepath,\n src,\n vrt,\n uiFramework,\n preview,\n previewKey,\n keepLayoutWhenParked,\n}: {\n \"data-tempo-hide-fiber\": \"true\";\n vrt?: boolean;\n uiFramework?: \"svelte\" | \"vue\" | \"astro\";\n preview?: string;\n previewKey?: string;\n /** A parked (cached) board stays hidden but keeps its layout box instead of\n * leaving layout. For content an engine renders from that box; see where\n * the shell's `display` is chosen. */\n keepLayoutWhenParked?: boolean;\n\n children?: ReactNode;\n id: string;\n kind: \"component\" | \"route\" | \"html\";\n layout: StoryboardLayout;\n name?: string;\n route?: string;\n filepath?: string;\n /** @deprecated Retained for v2 clients; prefer filepath for local HTML. */\n src?: string;\n}) {\n const renderId = useCanvasStoryboardRenderId(id);\n const canvas = useCanvasIdentity();\n const status = useStoryboardStatus(id);\n const renderSize = useStoryboardSize(id);\n const placement = useStoryboardPlacement(id);\n const markRendered = useStoryboardRendered(id);\n const markUnmounted = useStoryboardUnmounted(id);\n const { reportError, clearError } = useStoryboardErrorReporter(id);\n const legacyResponsive = layout.intrinsicSizing === \"root-element\";\n const declaredWidth = legacyResponsive ? undefined : layout.width;\n const declaredHeight = legacyResponsive ? undefined : layout.height;\n // An explicit runtime entry owns the slot even when it carries no size.\n const renderWidth =\n renderSize === undefined ? declaredWidth : renderSize.width;\n const renderHeight =\n renderSize === undefined ? declaredHeight : renderSize.height;\n const fixed = renderWidth !== undefined && renderHeight !== undefined;\n const renderRevision = renderSize?.revision ?? 0;\n const resetKey = `${renderId}:${renderRevision}`;\n const contentRef = useRef<HTMLDivElement | null>(null);\n // Phase 1 commits this slot's own elements with no user code under them, so\n // the projection root can register off a DOM node that exists whatever the\n // storyboard's component does; phase 2 admits the user tree one task later,\n // by which point the registration command has been answered. Keying the\n // admission by render id gives every projection identity its own phase 1.\n // Server rendering has no live document to register against and no event\n // loop to keep responsive, so there the whole tree is admitted at once.\n const [admittedRenderId, setAdmittedRenderId] = useState<string | null>(\n typeof document === \"undefined\" ? renderId : null,\n );\n const admitted = admittedRenderId === renderId;\n // Phase one installs this before phase two admits application effects.\n useLayoutEffect(() => {\n if (!isV1CanvasClient()) installStoryboardVisibilityObserver();\n }, []);\n const errorBoundaryRef = useRef<StoryboardErrorBoundary | null>(null);\n const lastReportedCommitRef = useRef<string | null>(null);\n const previousChildrenRef = useRef(children);\n const [recoveryRevision, setRecoveryRevision] = useState(0);\n const commitKey = `${resetKey}:${recoveryRevision}`;\n // Bumping the recovery revision after a successful boundary reset remounts\n // the commit signal, so a recovery is re-reported (clearError) instead of\n // being swallowed by the commit-key dedupe.\n const retryRenderNow = useCallback(() => {\n if (!errorBoundaryRef.current?.retry()) return false;\n setRecoveryRevision((revision) => revision + 1);\n return true;\n }, []);\n const { noteRenderError, noteRecovered } =\n useRenderErrorRecovery(retryRenderNow);\n const handleRenderError = useCallback(\n (error: { message: string; stack?: string; componentStack?: string }) => {\n noteRenderError();\n reportError(error);\n },\n [noteRenderError, reportError],\n );\n // React finishes the remaining layout effects after capturing a sibling\n // layout-effect error, so the commit signal is provisional. Report success\n // in the next task, after the boundary has had a chance to record the error.\n const pendingRenderedReportRef = useRef<ReturnType<typeof setTimeout> | null>(\n null,\n );\n const handleRendered = useCallback(\n (reportedCommitKey: string, active: boolean) => {\n if (pendingRenderedReportRef.current !== null) {\n clearTimeout(pendingRenderedReportRef.current);\n }\n pendingRenderedReportRef.current = setTimeout(() => {\n pendingRenderedReportRef.current = null;\n if (errorBoundaryRef.current?.hasError()) return;\n noteRecovered();\n // A clean commit proves recovery whether or not the slot is shown:\n // a parked board whose code was fixed has recovered too. Only the\n // render acknowledgement below waits for an active slot. Clearing\n // there as well left a parked broken board's error up forever,\n // since nothing activates a board while it shows an error.\n clearError();\n if (!active) return;\n if (lastReportedCommitRef.current === reportedCommitKey) return;\n lastReportedCommitRef.current = reportedCommitKey;\n markRendered();\n }, 0);\n },\n [clearError, markRendered, noteRecovered],\n );\n useEffect(\n () => () => {\n if (pendingRenderedReportRef.current !== null) {\n clearTimeout(pendingRenderedReportRef.current);\n pendingRenderedReportRef.current = null;\n }\n },\n [],\n );\n useLayoutEffect(() => {\n if (status === \"active\") return;\n // React state/effects survive caching, but activation must earn a new\n // runtime acknowledgement after its visible geometry commits. Eviction\n // can also remount content under the same commit key.\n lastReportedCommitRef.current = null;\n if (pendingRenderedReportRef.current !== null) {\n clearTimeout(pendingRenderedReportRef.current);\n pendingRenderedReportRef.current = null;\n }\n }, [status]);\n const renderChildren = useMemo(() => {\n if (isValidElement(children)) return cloneElement(children);\n return Children.map(children, (child) =>\n isValidElement(child) ? cloneElement(child) : child,\n );\n }, [children]);\n\n useLayoutEffect(() => {\n if (\n isV1CanvasClient() ||\n fixed ||\n status !== \"active\" ||\n !contentRef.current\n )\n return;\n return observeResponsiveSlotSize(contentRef.current);\n }, [fixed, renderId, status]);\n\n useEffect(() => markUnmounted, [markUnmounted]);\n\n // A passive effect, deliberately: React flushes these in a scheduler task of\n // their own, so the microtask checkpoint between phase 1's commit and this\n // admission is where the frame's registration observer gets to run.\n useEffect(() => {\n setAdmittedRenderId(renderId);\n }, [renderId]);\n\n useEffect(() => {\n const childrenChanged = previousChildrenRef.current !== children;\n previousChildrenRef.current = children;\n if (childrenChanged) retryRenderNow();\n }, [children, retryRenderNow]);\n\n useEffect(() => {\n if (!contentRef.current || status === \"unmounted\") return;\n return trackStoryboardPortals(renderId, contentRef.current, status);\n }, [renderId, status]);\n\n useEffect(() => {\n if (status === \"unmounted\") return;\n syncStoryboardPortals(renderId, status);\n }, [renderId, status]);\n\n // The shell is this storyboard's declaration on the page root's layer\n // stream, so it exists whether or not the content renders; the annotated\n // Storyboard callsite above it carries the source facts.\n const declaration = JSON.stringify({\n id: id.trim(),\n name,\n kind,\n layout: {\n x: layout.x,\n y: layout.y,\n width: declaredWidth,\n height: declaredHeight,\n zIndex: layout.zIndex,\n },\n route,\n filepath,\n src,\n vrt,\n uiFramework,\n preview,\n previewKey,\n } satisfies StoryboardDeclaration);\n\n if (status === \"unmounted\")\n return (\n <div\n data-tempo-storyboard-declaration={declaration}\n data-tempo-storyboard-id={id}\n hidden\n />\n );\n return (\n <div\n data-render-id={renderId}\n data-render-status={status}\n data-tempo-storyboard-render-id={renderId}\n data-tempo-storyboard-declaration={declaration}\n data-tempo-storyboard-id={id}\n data-tempo-canvas-path={canvas?.path}\n data-tempo-storyboard-name={name}\n data-tempo-storyboard-kind={kind}\n data-tempo-storyboard-route={route}\n data-tempo-storyboard-filepath={filepath}\n data-tempo-storyboard-src={src}\n style={\n isV1CanvasClient()\n ? v1StoryboardSlotStyle({\n kind,\n layout,\n renderSize,\n placement,\n status,\n })\n : {\n position: \"absolute\",\n // Canvas placement belongs to the renderer. Source components\n // share an origin so their DOM never encodes canvas coordinates.\n // A protocol-2 client measures the slot where 0.0.94 put it.\n ...(isPreV3CanvasClient()\n ? v2StoryboardSlotPosition({ layout, placement, fixed })\n : { left: 0, top: 0 }),\n ...(fixed ? { width: renderWidth, height: renderHeight } : {}),\n zIndex: layout.zIndex,\n // A hidden shell is already out of hit testing. It must not also\n // say pointer-events none: the producer records every element's\n // computed pointer-events as an app fact, and a full taken while\n // a restored shell is still cached would mark all of its content\n // click-through.\n visibility: status === \"active\" ? \"visible\" : \"hidden\",\n // Keep React/DOM state, but remove parked pages from layout:\n // with `display: none` an application's geometry reads cannot\n // force layout of a parked page (content-visibility still lets\n // them, on every animation frame). A board an engine renders\n // from its box (`keepLayoutWhenParked`, a Flutter view) must\n // keep that box: at 0x0 the engine stops painting and lays its\n // widgets out again, which changes the board's content and\n // loses its frames. It stays hidden by `visibility` above.\n display:\n status === \"cached\" && !keepLayoutWhenParked\n ? \"none\"\n : undefined,\n }\n }\n >\n <div\n data-render-content={renderId}\n // Phase 2's marker: the producer registers off the shell but waits for\n // this before opening its watch, so no baseline is ever taken from the\n // placeholder-only phase 1. Released V2 producers only watch this\n // marker, not data-render-status: withdraw it while display:none\n // parks the slot, then restore it with the active layout in one commit.\n data-render-admitted={\n admitted && (isV1CanvasClient() || status === \"active\")\n ? \"true\"\n : undefined\n }\n data-tempo-render-mode={kind === \"html\" ? \"static-dom\" : undefined}\n data-tempo-hide-fiber=\"true\"\n // The content root's own element: the page root above it stops\n // here, so a storyboard's content is published by one root only.\n {...{ [PROJECTION_ROOT_ATTRIBUTE]: \"true\" }}\n ref={contentRef}\n style={{ width: \"100%\", height: \"100%\" }}\n >\n <StoryboardErrorBoundary\n ref={errorBoundaryRef}\n onError={handleRenderError}\n resetKey={resetKey}\n >\n {admitted ? (\n <Suspense fallback={<CanvasPendingMarker />}>\n <StoryboardAdmission renderId={renderId}>\n {renderChildren}\n </StoryboardAdmission>\n <StoryboardCommitSignal\n key={commitKey}\n commitKey={commitKey}\n active={status === \"active\"}\n onCommit={handleRendered}\n />\n </Suspense>\n ) : (\n // An established watch can rebind to this shell after a remount,\n // before the passive admission effect runs. Mark that loading\n // phase so it holds the preview instead of publishing an empty\n // baseline. Admitted components may still intentionally return null.\n <CanvasPendingMarker />\n )}\n </StoryboardErrorBoundary>\n </div>\n </div>\n );\n}\n\n/** Opens the admission budget for the user tree React is about to render\n * under it. Rendering this component is what arms the counter, so it must sit\n * directly above the user tree and below the error boundary that catches the\n * budget's throw. */\nfunction StoryboardAdmission({\n children,\n renderId,\n}: {\n children?: ReactNode;\n renderId: string;\n}) {\n const host = useRequiredCanvasHost();\n // Imports can consume random values on a cold page but stay cached on a\n // reused page. Reset once, after those imports and before the user tree's\n // render/effects; ordinary updates must keep advancing the same sequence.\n useState(() => host.prepareStoryboardCapture?.(renderId));\n beginAdmissionWindow();\n return children;\n}\n\nfunction StoryboardCommitSignal({\n commitKey,\n active,\n onCommit,\n}: {\n commitKey: string;\n active: boolean;\n onCommit(commitKey: string, active: boolean): void;\n}) {\n const onCommitRef = useRef(onCommit);\n onCommitRef.current = onCommit;\n useLayoutEffect(() => {\n onCommitRef.current(commitKey, active);\n }, [commitKey, active]);\n return null;\n}\n\ntype StoryboardErrorBoundaryProps = {\n children?: ReactNode;\n onError(error: {\n message: string;\n stack?: string;\n componentStack?: string;\n }): void;\n resetKey: string;\n};\n\ntype StoryboardErrorBoundaryState = {\n error: Error | null;\n componentStack?: string;\n resetKey: string;\n};\n\n/** React emits one component-stack frame per fiber, so a storyboard that\n * recursed until it hit the admission budget produces a megabyte of stack in\n * which every frame after the first few is the same repeated line. The whole\n * string is reported onto the storyboard's problem lane and read back by the\n * Tempo renderer, so it is cut where it stops being evidence. */\nconst maxReportedComponentStackFrames = 40;\n\nfunction boundComponentStack(\n componentStack: string | null | undefined,\n): string | undefined {\n if (!componentStack) return undefined;\n const frames = componentStack.split(\"\\n\");\n if (frames.length <= maxReportedComponentStackFrames) return componentStack;\n const dropped = frames.length - maxReportedComponentStackFrames;\n return [\n ...frames.slice(0, maxReportedComponentStackFrames),\n ` ... ${dropped} more frames`,\n ].join(\"\\n\");\n}\n\nclass StoryboardErrorBoundary extends Component<\n StoryboardErrorBoundaryProps,\n StoryboardErrorBoundaryState\n> {\n state: StoryboardErrorBoundaryState = {\n error: null,\n componentStack: undefined,\n resetKey: this.props.resetKey,\n };\n\n static getDerivedStateFromError(error: Error) {\n return { error };\n }\n\n static getDerivedStateFromProps(\n props: StoryboardErrorBoundaryProps,\n state: StoryboardErrorBoundaryState,\n ) {\n if (props.resetKey !== state.resetKey) {\n return {\n error: null,\n componentStack: undefined,\n resetKey: props.resetKey,\n };\n }\n return null;\n }\n\n componentDidCatch(error: Error, info: ErrorInfo) {\n const componentStack = boundComponentStack(info.componentStack);\n this.setState({ componentStack });\n this.props.onError({\n message: error.message,\n stack: error.stack,\n componentStack,\n });\n }\n\n hasError(): boolean {\n return this.state.error !== null;\n }\n\n retry(): boolean {\n if (!this.state.error) return false;\n this.setState((state) =>\n state.error\n ? { error: null, componentStack: undefined, resetKey: state.resetKey }\n : null,\n );\n return true;\n }\n\n render() {\n if (this.state.error) {\n return (\n <div\n data-render-error=\"true\"\n data-render-error-message={this.state.error.message}\n style={{ width: \"100%\", height: \"100%\" }}\n />\n );\n }\n return this.props.children;\n }\n}\n\n/** Declares the hosted invocation's output without adding a DOM wrapper or\n * passing framework instrumentation into the user's component props. */\nconst ProjectionContent = Object.assign(\n function ProjectionContent({ children }: { children: ReactNode }) {\n return children;\n },\n { [PROJECTION_SCOPE_ROLE]: \"output\" as const },\n);\nObject.assign(StoryboardAdmission, { [PROJECTION_SCOPE_ROLE]: \"transparent\" });\nObject.assign(StoryboardCommitSignal, {\n [PROJECTION_SCOPE_ROLE]: \"transparent\",\n});\nObject.assign(StoryboardErrorBoundary, {\n [PROJECTION_SCOPE_ROLE]: \"transparent\",\n});\n","import * as React from \"react\";\n\n/**\n * A bound on how much render work can happen in one uninterrupted burst.\n *\n * A user can write `const Loop = () => <Loop/>` — or split the same cycle\n * across two modules that import each other — into any storyboard file. React\n * then allocates fibers until the renderer dies at V8's 4 GB heap limit. No\n * timer, watchdog, or IPC message can intervene, because the render loop is\n * synchronous and never yields the thread: nothing else in the document runs\n * again, ever. The bound therefore has to be enforced from inside the render\n * itself.\n *\n * React transitions its hooks dispatcher on entry to and exit from every\n * function component (`renderWithHooks` / `finishRenderingHooks` both assign\n * `ReactSharedInternals.H`), so an accessor on that one property counts render\n * work across arbitrary user code with nothing injected into user modules.\n * Past the budget the accessor throws, which is an ordinary render-phase\n * throw: React unwinds to the nearest storyboard error boundary, every sibling\n * in the same pass still renders and commits, and an infinite recursion\n * becomes one storyboard showing a problem instead of a dead canvas.\n *\n * The counter re-arms on the first microtask after any step, which is what\n * makes the bound *per burst* rather than per render pass. A synchronous React\n * pass never reaches a microtask checkpoint, so a runaway drains one budget and\n * throws, while ordinary work is handed a full budget again the moment the\n * thread returns to the event loop. Bounding bursts rather than passes is what\n * catches the common case: a user edits an already-mounted storyboard into a\n * recursive one, and Fast Refresh re-renders that component's own fiber without\n * ever re-rendering the storyboard slot above it.\n */\n\n/**\n * Dispatcher transitions one burst may spend. React transitions twice per\n * function component, so this is roughly 50k component instantiations: orders\n * of magnitude above any real storyboard (a large one costs a few thousand)\n * and orders of magnitude below the fiber count that exhausts the heap.\n */\nexport const admissionRenderStepBudget = 100_000;\n\n/** Thrown from inside the render that exceeded {@link admissionRenderStepBudget}. */\nexport class AdmissionBudgetError extends Error {\n constructor() {\n super(\n \"This storyboard renders itself recursively: it kept creating \" +\n \"components without ever finishing a render. Check for a component \" +\n \"that returns itself, or two components that render each other.\",\n );\n this.name = \"AdmissionBudgetError\";\n }\n}\n\n/**\n * Where React keeps the current hooks dispatcher: `H` on React 19's client\n * internals, `ReactCurrentDispatcher.current` on React 18. Both are assigned\n * on every function component render, which is the only property of them this\n * module depends on.\n */\nfunction findDispatcherSlot(): {\n holder: Record<string, unknown>;\n key: string;\n} | null {\n const react = React as unknown as Record<string, Record<string, unknown>>;\n const modern =\n react.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;\n if (modern && \"H\" in modern) return { holder: modern, key: \"H\" };\n const legacy = react.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED\n ?.ReactCurrentDispatcher as Record<string, unknown> | undefined;\n if (legacy && \"current\" in legacy) return { holder: legacy, key: \"current\" };\n return null;\n}\n\nlet stepsRemaining = admissionRenderStepBudget;\nlet rearmScheduled = false;\nlet counterState: \"uninstalled\" | \"installed\" | \"unavailable\" = \"uninstalled\";\n\nfunction scheduleRearm(): void {\n if (rearmScheduled) return;\n rearmScheduled = true;\n queueMicrotask(() => {\n rearmScheduled = false;\n stepsRemaining = admissionRenderStepBudget;\n });\n}\n\nfunction installCounter(): boolean {\n if (counterState !== \"uninstalled\") return counterState === \"installed\";\n const slot = findDispatcherSlot();\n if (!slot) {\n // A React whose dispatcher lives somewhere else still renders storyboards\n // correctly; it just runs without this bound. Failing open is deliberate:\n // an internals rename must never stop storyboards from rendering, and the\n // projection stall watchdog remains the outcome-based net underneath.\n counterState = \"unavailable\";\n return false;\n }\n const { holder, key } = slot;\n let dispatcher = holder[key];\n Object.defineProperty(holder, key, {\n configurable: true,\n get: () => dispatcher,\n set: (value: unknown) => {\n dispatcher = value;\n scheduleRearm();\n stepsRemaining -= 1;\n if (stepsRemaining > 0) return;\n // Re-arming as it throws lets React's unwinding assignments through, and\n // hands React's one automatic retry of the failed root a fresh budget so\n // the retry trips the same way and the boundary finally sees the error.\n stepsRemaining = admissionRenderStepBudget;\n throw new AdmissionBudgetError();\n },\n });\n counterState = \"installed\";\n return true;\n}\n\n/**\n * Charges the storyboard about to render its own budget, so one pass covering\n * many storyboards cannot accumulate their work into a single overrun. Called\n * during render, immediately above the user tree.\n */\nexport function beginAdmissionWindow(): void {\n if (!installCounter()) return;\n stepsRemaining = admissionRenderStepBudget;\n}\n","import { PROJECTION_SCOPE_ROLE } from \"../../../modules/iframe-projection/fiber/projection-scope\";\nimport {\n PROJECTION_PENDING_ATTRIBUTE,\n PROJECTION_UNAVAILABLE_ATTRIBUTE,\n} from \"../../../modules/iframe-projection/combined/projection-pending\";\n\n/**\n * The placeholder Tempo-owned admission and Suspense boundaries render\n * while they wait.\n *\n * A not-yet-admitted or suspended subtree reaches the DOM as an empty one,\n * which is indistinguishable from a subtree that intentionally emptied. This\n * marker makes the difference observable to the projection producer, which treats a root\n * whose children are all markers as pending and holds the mirror's last-good\n * content instead of publishing the blank.\n *\n * Only Tempo's own boundaries render it. A user's Suspense inside their\n * storyboard keeps mirroring faithfully: their fallback — even `null` —\n * renders inside the root with no marker beside it, so their loading state\n * stays a real state the mirror shows.\n *\n * It carries no layout of its own: the host document must look the same with a\n * subtree pending as it does with that subtree absent.\n */\nexport function CanvasPendingMarker() {\n return (\n <div\n {...{ [PROJECTION_PENDING_ATTRIBUTE]: \"\" }}\n data-tempo-hide-fiber=\"true\"\n style={{ display: \"none\" }}\n aria-hidden=\"true\"\n />\n );\n}\n\n// Both the wrapper and its sentinel host are SDK plumbing, never authored layers.\nObject.assign(CanvasPendingMarker, { [PROJECTION_SCOPE_ROLE]: \"transparent\" });\n\n/**\n * What a Tempo-owned board renders while its content is unavailable for an\n * unknown time (a Flutter board while `flutter run` compiles), instead of\n * the pending marker, whose contract is \"paints in seconds\".\n *\n * It is ordinary content: the board commits it, so the canvas sees a live\n * board that answers, and reads the marker as \"nothing to show or\n * photograph\". The canvas then shows its own loading presentation and owes\n * no screenshot, and a capture of the board is a typed discard\n * (canvas-host-operations.ts). The board paints nothing of its own; the wait\n * is reported by the dev server, in the canvas's loading bar.\n *\n * Hidden and empty, like the pending marker, and never a layer:\n * `data-tempo-hide-fiber` hides only the element that carries it, so any\n * child (an element or a text node) would reach the Layers panel.\n */\nexport function CanvasUnavailableMarker() {\n return (\n <div\n {...{ [PROJECTION_UNAVAILABLE_ATTRIBUTE]: \"\" }}\n data-tempo-hide-fiber=\"true\"\n style={{ display: \"none\" }}\n aria-hidden=\"true\"\n />\n );\n}\n\nObject.assign(CanvasUnavailableMarker, {\n [PROJECTION_SCOPE_ROLE]: \"transparent\",\n});\n","type FiberLike = {\n return: FiberLike | null;\n stateNode: unknown;\n};\n\ntype PortalWatcher = {\n element: Element;\n onPortalFound(portalRoot: Element): void;\n onPortalRemoved(portalRoot: Element): void;\n};\n\ntype PortalInlineStyleValue = {\n value: string;\n priority: string;\n};\n\ntype PortalInlineStyle = {\n visibility: PortalInlineStyleValue;\n pointerEvents: PortalInlineStyleValue;\n contentVisibility: PortalInlineStyleValue;\n transition: PortalInlineStyleValue;\n animation: PortalInlineStyleValue;\n};\n\ntype PortalManagedProperty = {\n // The PortalInlineStyle field that holds this property's saved baseline.\n key: keyof PortalInlineStyle;\n // The CSS property name as written in inline styles.\n cssName: string;\n // The value forced (with !important) while the portal is hidden.\n hiddenValue: string;\n};\n\n// Single source of truth for the inline-style properties this module overrides\n// to hide cached/inactive portals, so the hide path and the restore path can't\n// drift out of sync.\nconst PORTAL_MANAGED_PROPERTIES: readonly PortalManagedProperty[] = [\n { key: \"visibility\", cssName: \"visibility\", hiddenValue: \"hidden\" },\n { key: \"pointerEvents\", cssName: \"pointer-events\", hiddenValue: \"none\" },\n {\n key: \"contentVisibility\",\n cssName: \"content-visibility\",\n hiddenValue: \"hidden\",\n },\n { key: \"transition\", cssName: \"transition\", hiddenValue: \"none\" },\n { key: \"animation\", cssName: \"animation\", hiddenValue: \"none\" },\n];\n\nconst portalElementsByRenderId = new Map<string, Set<Element>>();\nconst portalOwnerRenderIdsByElement = new Map<Element, Set<string>>();\nconst portalInlineStyleByElement = new Map<Element, PortalInlineStyle>();\nconst renderStatusById = new Map<string, \"active\" | \"cached\">();\nconst projectionPortalIdAttribute = \"data-projection-portal-id\";\nlet nextSdkPortalId = 1;\n\nfunction escapeAttributeValue(value: string): string {\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\nfunction ensureProjectionPortalId(portalRoot: Element): string {\n const existingId = portalRoot.getAttribute(projectionPortalIdAttribute);\n if (existingId) return existingId;\n\n const id = `tempo-sdk-portal-${nextSdkPortalId++}`;\n portalRoot.setAttribute(projectionPortalIdAttribute, id);\n return id;\n}\n\nfunction buildProjectionPortalSelector(portalRoot: Element): string {\n return `[${projectionPortalIdAttribute}=\"${escapeAttributeValue(\n ensureProjectionPortalId(portalRoot),\n )}\"]`;\n}\n\nfunction findFiberKey(element: Element): string | null {\n return (\n Object.keys(element).find(\n (key) =>\n key.startsWith(\"__reactFiber$\") ||\n key.startsWith(\"__reactInternalInstance$\"),\n ) ?? null\n );\n}\n\nfunction findContainerKey(element: Element): string | null {\n return Object.keys(element).find((key) => key.startsWith(\"__reactContainer$\")) ?? null;\n}\n\nfunction getFiberFromElement(element: Element): FiberLike | null {\n const fiberKey = findFiberKey(element);\n if (fiberKey) {\n return (\n (element as unknown as Record<string, FiberLike | undefined>)[fiberKey] ??\n null\n );\n }\n\n const containerKey = findContainerKey(element);\n if (containerKey) {\n return (\n (element as unknown as Record<string, FiberLike | undefined>)[\n containerKey\n ] ?? null\n );\n }\n\n return null;\n}\n\nclass PortalTracker {\n private readonly watchers = new Set<PortalWatcher>();\n private readonly ownerWatchersByPortalRoot = new Map<\n Element,\n Set<PortalWatcher>\n >();\n private observer: MutationObserver | null = null;\n\n register(watcher: PortalWatcher): () => void {\n this.watchers.add(watcher);\n\n if (this.watchers.size === 1) {\n this.startObserving();\n }\n\n if (typeof document !== \"undefined\" && document.body) {\n this.checkExistingElements();\n queueMicrotask(() => this.checkExistingElements());\n }\n\n return () => this.unregister(watcher);\n }\n\n private checkExistingElements(): void {\n if (typeof document === \"undefined\" || !document.body) return;\n for (const child of Array.from(document.body.children)) {\n this.checkElement(child);\n }\n }\n\n private unregister(watcher: PortalWatcher): void {\n this.watchers.delete(watcher);\n\n for (const [portalRoot, owners] of this.ownerWatchersByPortalRoot) {\n owners.delete(watcher);\n if (owners.size === 0) {\n this.ownerWatchersByPortalRoot.delete(portalRoot);\n }\n }\n\n if (this.watchers.size === 0) {\n this.stopObserving();\n }\n }\n\n private startObserving(): void {\n if (\n this.observer ||\n typeof document === \"undefined\" ||\n !document.body ||\n typeof MutationObserver === \"undefined\"\n ) {\n return;\n }\n\n this.observer = new MutationObserver(this.handleMutations);\n this.observer.observe(document.body, { childList: true });\n }\n\n private stopObserving(): void {\n this.observer?.disconnect();\n this.observer = null;\n }\n\n private handleMutations = (mutations: MutationRecord[]): void => {\n for (const mutation of mutations) {\n for (const node of mutation.addedNodes) {\n if (node instanceof Element) {\n queueMicrotask(() => this.checkElement(node));\n }\n }\n\n for (const node of mutation.removedNodes) {\n if (!(node instanceof Element)) continue;\n const owners = this.ownerWatchersByPortalRoot.get(node);\n if (!owners) continue;\n for (const owner of owners) {\n owner.onPortalRemoved(node);\n }\n this.ownerWatchersByPortalRoot.delete(node);\n }\n }\n };\n\n private checkElement(element: Element): void {\n const ancestorDomNodes = this.getDomAncestorsViaFiber(element);\n if (ancestorDomNodes.length === 0) return;\n\n let owners = this.ownerWatchersByPortalRoot.get(element);\n for (const watcher of this.watchers) {\n const belongsToWatcher = ancestorDomNodes.some(\n (node) => watcher.element.contains(node) || watcher.element === node,\n );\n if (!belongsToWatcher) continue;\n\n if (!owners) {\n owners = new Set<PortalWatcher>();\n this.ownerWatchersByPortalRoot.set(element, owners);\n }\n if (owners.has(watcher)) continue;\n\n owners.add(watcher);\n watcher.onPortalFound(element);\n }\n }\n\n private getDomAncestorsViaFiber(element: Element): Element[] {\n const fiber = getFiberFromElement(element);\n if (!fiber) return [];\n\n const domNodes: Element[] = [];\n let current: FiberLike | null = fiber.return;\n while (current) {\n if (current.stateNode instanceof Element) {\n domNodes.push(current.stateNode);\n }\n current = current.return;\n }\n return domNodes;\n }\n}\n\nlet portalTracker: PortalTracker | null = null;\n\nfunction getPortalTracker(): PortalTracker {\n if (!portalTracker) {\n portalTracker = new PortalTracker();\n }\n return portalTracker;\n}\n\nfunction getStylablePortalElement(\n portalRoot: Element,\n): HTMLElement | SVGElement | null {\n if (portalRoot instanceof HTMLElement || portalRoot instanceof SVGElement) {\n return portalRoot;\n }\n return null;\n}\n\nfunction ensurePortalInlineStyle(portalRoot: Element): PortalInlineStyle {\n const existing = portalInlineStyleByElement.get(portalRoot);\n if (existing) return existing;\n\n const stylableElement = getStylablePortalElement(portalRoot);\n const baseline = {\n visibility: readInlineStyleValue(stylableElement, \"visibility\"),\n pointerEvents: readInlineStyleValue(stylableElement, \"pointer-events\"),\n contentVisibility: readInlineStyleValue(\n stylableElement,\n \"content-visibility\",\n ),\n transition: readInlineStyleValue(stylableElement, \"transition\"),\n animation: readInlineStyleValue(stylableElement, \"animation\"),\n };\n portalInlineStyleByElement.set(portalRoot, baseline);\n return baseline;\n}\n\nfunction readInlineStyleValue(\n element: HTMLElement | SVGElement | null,\n propertyName: string,\n): PortalInlineStyleValue {\n return {\n value: element?.style.getPropertyValue(propertyName) ?? \"\",\n priority: element?.style.getPropertyPriority(propertyName) ?? \"\",\n };\n}\n\nfunction restoreInlineStyleValue(\n style: CSSStyleDeclaration,\n propertyName: string,\n baseline: PortalInlineStyleValue,\n): void {\n if (baseline.value) {\n style.setProperty(propertyName, baseline.value, baseline.priority);\n return;\n }\n style.removeProperty(propertyName);\n}\n\nfunction restorePortalInlineStyle(portalRoot: Element): void {\n const stylableElement = getStylablePortalElement(portalRoot);\n const baseline = portalInlineStyleByElement.get(portalRoot);\n if (!stylableElement || !baseline) return;\n\n for (const property of PORTAL_MANAGED_PROPERTIES) {\n restoreInlineStyleValue(\n stylableElement.style,\n property.cssName,\n baseline[property.key],\n );\n }\n}\n\nfunction syncPortalVisibility(portalRoot: Element): void {\n const owners = portalOwnerRenderIdsByElement.get(portalRoot);\n if (!owners || owners.size === 0) {\n restorePortalInlineStyle(portalRoot);\n portalInlineStyleByElement.delete(portalRoot);\n return;\n }\n\n const stylableElement = getStylablePortalElement(portalRoot);\n if (!stylableElement) return;\n\n const shouldBeVisible = [...owners].some(\n (renderId) => renderStatusById.get(renderId) === \"active\",\n );\n\n if (shouldBeVisible) {\n restorePortalInlineStyle(portalRoot);\n portalInlineStyleByElement.delete(portalRoot);\n return;\n }\n\n ensurePortalInlineStyle(portalRoot);\n for (const property of PORTAL_MANAGED_PROPERTIES) {\n stylableElement.style.setProperty(\n property.cssName,\n property.hiddenValue,\n \"important\",\n );\n }\n}\n\nfunction trackPortal(renderId: string, portalRoot: Element): void {\n ensureProjectionPortalId(portalRoot);\n\n const portals = portalElementsByRenderId.get(renderId) ?? new Set<Element>();\n portals.add(portalRoot);\n portalElementsByRenderId.set(renderId, portals);\n\n const owners = portalOwnerRenderIdsByElement.get(portalRoot) ?? new Set<string>();\n owners.add(renderId);\n portalOwnerRenderIdsByElement.set(portalRoot, owners);\n syncPortalVisibility(portalRoot);\n}\n\nfunction untrackPortal(renderId: string, portalRoot: Element): void {\n const portals = portalElementsByRenderId.get(renderId);\n if (!portals) return;\n\n portals.delete(portalRoot);\n if (portals.size === 0) {\n portalElementsByRenderId.delete(renderId);\n }\n\n const owners = portalOwnerRenderIdsByElement.get(portalRoot);\n if (owners) {\n owners.delete(renderId);\n if (owners.size === 0) {\n portalOwnerRenderIdsByElement.delete(portalRoot);\n }\n }\n syncPortalVisibility(portalRoot);\n}\n\nexport function releaseStoryboardPortals(renderId: string): void {\n const portals = portalElementsByRenderId.get(renderId);\n if (!portals) {\n renderStatusById.delete(renderId);\n return;\n }\n\n for (const portalRoot of [...portals]) {\n untrackPortal(renderId, portalRoot);\n }\n renderStatusById.delete(renderId);\n}\n\nexport function getStoryboardPortalSelectors(renderId: string): string[] {\n const portals = portalElementsByRenderId.get(renderId);\n if (!portals) return [];\n return [...portals]\n .filter((portalRoot) => portalRoot.isConnected)\n .map(buildProjectionPortalSelector);\n}\n\nexport function syncStoryboardPortals(\n renderId: string,\n status: \"active\" | \"cached\",\n): void {\n renderStatusById.set(renderId, status);\n const portals = portalElementsByRenderId.get(renderId);\n if (!portals) return;\n for (const portalRoot of portals) {\n syncPortalVisibility(portalRoot);\n }\n}\n\nexport function trackStoryboardPortals(\n renderId: string,\n element: Element,\n status: \"active\" | \"cached\",\n): () => void {\n syncStoryboardPortals(renderId, status);\n const unregister = getPortalTracker().register({\n element,\n onPortalFound(portalRoot) {\n trackPortal(renderId, portalRoot);\n },\n onPortalRemoved(portalRoot) {\n untrackPortal(renderId, portalRoot);\n },\n });\n\n return () => {\n unregister();\n releaseStoryboardPortals(renderId);\n };\n}\n","import { useCallback, useEffect, useRef } from \"react\";\n\n/**\n * Self-contained recovery for storyboard render errors.\n *\n * A render error unmounts the throwing subtree, so React Fast Refresh alone\n * cannot repair it: refresh only re-renders mounted fibers, and the fixed\n * component has none. The design shell repairs this by advancing the render\n * revision (which resets the boundary), but a host page without the shell —\n * a direct `/tempo-host?canvasPath=...` document — has no revision driver at\n * all. Recovery must therefore be armed from inside the SDK:\n *\n * - a retry timer with exponential backoff, armed while a boundary is\n * errored — the universal mechanism, needing no signal from anyone; and\n * - an immediate retry on an HMR beat, when one is observable — new code\n * just arrived, so waiting out the backoff would be pure latency.\n *\n * The beat arrives over a window-global bus (create-if-absent on both sides,\n * mirroring the host-recovery feed) from the devserver-generated Vite\n * recovery adapter, which owns `import.meta.hot`. This module must stay free\n * of literal `import.meta` itself: the built bundle is force-resolved into\n * Expo's Metro web bundle, which runs as a classic script where that token\n * is a parse error that kills the whole document (TEM-1409). The beat is\n * best-effort by design — hosts without the adapter (Expo, a bare\n * `/tempo-host?canvasPath=...` document) never see one. That asymmetry is\n * why the backoff cap stays low: without a beat, the cap IS the worst-case\n * fix-to-recovery latency.\n */\n\n/** First retry after a fresh error; also the rung the ladder resets to. */\nexport const renderErrorRetryBaseDelayMs = 1_000;\n/**\n * Backoff cap. Doubling stops here (1s → 2s → 4s → 8s) so a persistently\n * broken storyboard costs at most one re-render per 8s — negligible even for\n * expensive trees — while a fix still becomes visible within 8s when no HMR\n * beat is observable.\n */\nexport const renderErrorRetryMaxDelayMs = 8_000;\n\ntype RenderErrorRecoveryBeatBus = {\n emit(): void;\n subscribe(listener: () => void): () => void;\n};\n\nconst BEAT_BUS_KEY = \"__tempoRenderErrorRecoveryBeatBus\";\n\nfunction createBeatBus(): RenderErrorRecoveryBeatBus {\n const listeners = new Set<() => void>();\n return {\n emit() {\n for (const listener of [...listeners]) listener();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n\n// The beat is a document-lifetime fact, not a per-storyboard one, and its\n// producer (the generated Vite adapter) must not import the SDK — so the bus\n// lives on the window global with create-if-absent semantics on both sides,\n// exactly like the host-recovery feed: whichever party evaluates first\n// creates it, the other reuses it.\nfunction getRenderErrorRecoveryBeatBus(): RenderErrorRecoveryBeatBus {\n const globals = globalThis as typeof globalThis & {\n [BEAT_BUS_KEY]?: RenderErrorRecoveryBeatBus;\n };\n return (globals[BEAT_BUS_KEY] ??= createBeatBus());\n}\n\n/**\n * Announces \"new code may have arrived\" to every errored boundary. Exported\n * so tests can drive beats directly; production beats come from the\n * devserver-generated Vite recovery adapter emitting on the shared bus.\n */\nexport function emitRenderErrorRecoveryBeat(): void {\n getRenderErrorRecoveryBeatBus().emit();\n}\n\n/**\n * Owns the retry schedule for one storyboard's error boundary. The caller\n * reports the boundary's state transitions (`noteRenderError` from every\n * catch, `noteRecovered` from every healthy commit) and supplies `retryNow`,\n * which resets the boundary and returns whether it was actually errored.\n *\n * The normal still-broken loop is: timer fires → retry → children throw →\n * catch calls `noteRenderError` → next rung is armed. A retry that sticks\n * leads to a commit, whose `noteRecovered` clears the pending state and\n * resets the ladder.\n */\nexport function useRenderErrorRecovery(retryNow: () => boolean): {\n noteRenderError(): void;\n noteRecovered(): void;\n} {\n const retryNowRef = useRef(retryNow);\n retryNowRef.current = retryNow;\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const nextDelayRef = useRef(renderErrorRetryBaseDelayMs);\n const erroredRef = useRef(false);\n\n const clearTimer = useCallback(() => {\n if (timerRef.current === null) return;\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }, []);\n\n const noteRenderError = useCallback(() => {\n erroredRef.current = true;\n // A pending timer already covers this error (e.g. a children-change\n // retry failed while the scheduled one was still counting down).\n if (timerRef.current !== null) return;\n const delay = nextDelayRef.current;\n nextDelayRef.current = Math.min(delay * 2, renderErrorRetryMaxDelayMs);\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n retryNowRef.current();\n }, delay);\n }, []);\n\n const noteRecovered = useCallback(() => {\n erroredRef.current = false;\n nextDelayRef.current = renderErrorRetryBaseDelayMs;\n clearTimer();\n }, [clearTimer]);\n\n useEffect(() => {\n const onBeat = () => {\n // Fresh code deserves a fresh ladder: whether the immediate retry\n // below succeeds or re-catches, the next scheduled attempt starts\n // from the base delay again.\n nextDelayRef.current = renderErrorRetryBaseDelayMs;\n if (!erroredRef.current) return;\n clearTimer();\n retryNowRef.current();\n };\n const unsubscribe = getRenderErrorRecoveryBeatBus().subscribe(onBeat);\n return () => {\n unsubscribe();\n clearTimer();\n };\n }, [clearTimer]);\n\n return { noteRenderError, noteRecovered };\n}\n","/**\n * Absolutely positioned component roots do not contribute to shrink-to-fit\n * layout. Give a responsive slot a minimum enclosing their positive extents,\n * so the slot, projection size and capture selector all describe the same box.\n * Authored elements are never restyled. Fixed slots never install this helper.\n */\nexport function observeResponsiveSlotSize(content: HTMLElement): () => void {\n const slot = content.parentElement;\n const view = content.ownerDocument.defaultView;\n if (!slot || !view) return () => {};\n const previousWidth = slot.style.minWidth;\n const previousHeight = slot.style.minHeight;\n const previousContentHeight = content.style.minHeight;\n // A percentage height does not resolve against a parent's min-height.\n // The capture selector is the content wrapper, so it must share that minimum.\n content.style.minHeight = \"inherit\";\n const roots = new Set<Element>();\n let disposed = false;\n let scheduledFrame: number | null = null;\n\n const measure = () => {\n if (disposed) return;\n for (const root of roots) {\n if (root.parentElement !== content) {\n resize.unobserve(root);\n roots.delete(root);\n }\n }\n for (const root of content.children) {\n if (!roots.has(root)) {\n roots.add(root);\n resize.observe(root, { box: \"border-box\" });\n }\n }\n // Measure natural layout each time. Measuring against our previous minimum\n // would prevent shrinking and retain a phantom box after removing the root.\n slot.style.minWidth = previousWidth;\n slot.style.minHeight = previousHeight;\n const natural = slot.getBoundingClientRect();\n let width = natural.width;\n let height = natural.height;\n for (const root of roots) {\n if (view.getComputedStyle(root).position !== \"absolute\") continue;\n const rect = root.getBoundingClientRect();\n if (rect.width <= 0 || rect.height <= 0) continue;\n width = Math.max(width, rect.right - natural.left);\n height = Math.max(height, rect.bottom - natural.top);\n }\n if (width > natural.width) slot.style.minWidth = `${Math.ceil(width)}px`;\n if (height > natural.height)\n slot.style.minHeight = `${Math.ceil(height)}px`;\n };\n // A root can resize during layout (fonts, stylesheets, responsive CSS).\n // Resizing its observed ancestor in the same delivery causes skipped resize\n // notifications. Coalesce later measurements before the next paint instead.\n const scheduleMeasure = () => {\n if (disposed || scheduledFrame !== null) return;\n scheduledFrame = view.requestAnimationFrame(() => {\n scheduledFrame = null;\n measure();\n });\n };\n const resize = new view.ResizeObserver(scheduleMeasure);\n const mutations = new view.MutationObserver((records) => {\n // Descendant edits are covered by the root's ResizeObserver. Only root\n // replacement and root attributes can change the bounds without resizing.\n if (\n records.some((record) =>\n record.type === \"childList\"\n ? record.target === content\n : record.target.parentElement === content,\n )\n )\n scheduleMeasure();\n });\n resize.observe(slot, { box: \"border-box\" });\n // Position/class edits and root replacement need a measure even when the\n // zero-size wrapper itself never receives a ResizeObserver notification.\n mutations.observe(content, {\n childList: true,\n subtree: true,\n attributes: true,\n });\n measure();\n return () => {\n disposed = true;\n if (scheduledFrame !== null) view.cancelAnimationFrame(scheduledFrame);\n resize.disconnect();\n mutations.disconnect();\n content.style.minHeight = previousContentHeight;\n slot.style.minWidth = previousWidth;\n slot.style.minHeight = previousHeight;\n };\n}\n","const FRAME = \"[data-tempo-storyboard-render-id]\";\nlet installed = false;\n\n/** The shared source document lays storyboards out at canvas coordinates.\n * App observers with an implicit viewport must instead see their own frame,\n * including its clipping and scroll containers. Keep explicit app roots and\n * targets outside storyboards on the browser's ordinary path. */\nexport function installStoryboardVisibilityObserver(): void {\n if (\n installed ||\n typeof window === \"undefined\" ||\n !window.IntersectionObserver\n )\n return;\n installed = true;\n const NativeObserver = window.IntersectionObserver;\n window.IntersectionObserver = class extends NativeObserver {\n private readonly scopes = new Map<\n Element,\n { observer: IntersectionObserver; targets: Set<Element> }\n >();\n private readonly targetScopes = new Map<Element, Element>();\n private readonly callback: IntersectionObserverCallback;\n private readonly init: IntersectionObserverInit;\n\n constructor(\n callback: IntersectionObserverCallback,\n options?: IntersectionObserverInit,\n ) {\n if (typeof callback !== \"function\")\n throw new TypeError(\"Expected an IntersectionObserver callback\");\n const init = { ...options };\n let owner: IntersectionObserver;\n super((entries) => callback.call(owner, entries, owner), init);\n owner = this;\n this.callback = callback;\n this.init = init;\n }\n\n override observe(target: Element): void {\n let root = this.root === null ? target.closest(FRAME) : null;\n // A fixed descendant may escape the frame's containing-block chain.\n // Observe inside that fixed box instead of changing app layout to make\n // the frame a containing block. A fixed target itself uses the viewport.\n for (\n let node: Element | null = target;\n root && node !== root;\n node = node.parentElement\n ) {\n if (!node) break;\n if (getComputedStyle(node).position === \"fixed\") {\n root = node === target ? null : node;\n break;\n }\n }\n if (!root) {\n this.unobserve(target);\n super.observe(target);\n return;\n }\n if (this.targetScopes.get(target) === root) return;\n this.unobserve(target);\n let scope = this.scopes.get(root);\n if (!scope) {\n scope = {\n observer: new NativeObserver(\n (entries) => this.callback.call(this, entries, this),\n {\n ...this.init,\n root,\n rootMargin: this.rootMargin,\n threshold: [...this.thresholds],\n },\n ),\n targets: new Set(),\n };\n this.scopes.set(root, scope);\n }\n scope.observer.observe(target);\n scope.targets.add(target);\n this.targetScopes.set(target, root);\n }\n\n override unobserve(target: Element): void {\n const root = this.targetScopes.get(target);\n if (root) {\n const scope = this.scopes.get(root)!;\n scope.observer.unobserve(target);\n scope.targets.delete(target);\n this.targetScopes.delete(target);\n if (!scope.targets.size) {\n scope.observer.disconnect();\n this.scopes.delete(root);\n }\n }\n super.unobserve(target);\n }\n\n override disconnect(): void {\n for (const scope of this.scopes.values()) scope.observer.disconnect();\n this.scopes.clear();\n this.targetScopes.clear();\n super.disconnect();\n }\n\n override takeRecords(): IntersectionObserverEntry[] {\n return [\n ...super.takeRecords(),\n ...[...this.scopes.values()].flatMap(({ observer }) =>\n observer.takeRecords(),\n ),\n ].sort((a, b) => a.time - b.time);\n }\n };\n}\n","/**\n * @deprecated V1 client compat.\n *\n * Everything a released V1 Tempo client (app 0.0.114, driving tempo-sdk\n * 0.0.51 behavior) still expects from this host and that V2 no longer does.\n * A workspace's installed tempo-sdk follows registry `latest` independently\n * of the desktop app's update cadence, so a V1 client keeps loading hosts\n * built from this SDK until the force-upgrade floor ages it out.\n *\n * Every call site gates on `isV1CanvasClient()`, so a V2 client runs today's\n * code paths untouched. Delete this file once no protocol-1 client is\n * supported; the compiler then lists every call site to remove.\n */\nimport type { CSSProperties } from \"react\";\n\nimport { canvasClientProtocol } from \"./client-protocol\";\nimport type {\n CanvasHostRuntimePlacement,\n CanvasHostRuntimeSize,\n} from \"./runtime-context\";\nimport type { StoryboardLayout } from \"./storyboard\";\n\n/** The layout spelling a V1 client still writes and type-checks\n * (`tsc --noEmit` over canvases against `TempoStoryboard`). */\nexport type V1LayoutCompat = {\n /** @deprecated A legacy responsive marker: the width and height beside it\n * are first-paint hints, not a frame. V2 reads the triple as responsive. */\n intrinsicSizing?: \"root-element\";\n};\n\n/** The V1 render request's hug flag: the slot hugs its rendered root, with\n * the supplied width and height as its minimum. */\nexport type V1RenderSizeCompat = {\n /** @deprecated V2 clients never send it. */\n intrinsicSize?: boolean;\n};\n\nexport function isV1CanvasClient(): boolean {\n return canvasClientProtocol() < 2;\n}\n\n/** The render command's `intrinsicSize`, read the way 0.0.51 did. */\nexport function v1RenderRequestSize(\n payload: Record<string, unknown>,\n): V1RenderSizeCompat {\n return { intrinsicSize: payload.intrinsicSize === true ? true : undefined };\n}\n\n// `intrinsicSize=1` (or any value but \"0\"/\"false\") is the direct-URL spelling\n// of the render command's flag, so a V1 capture driver expresses an intrinsic\n// capture before the storyboard mounts instead of resizing it afterwards.\nfunction readDirectUrlFlag(value: string | null): boolean {\n if (value === null) return false;\n const normalized = value.trim().toLowerCase();\n return normalized !== \"0\" && normalized !== \"false\";\n}\n\n/** The direct URL's size, read the way 0.0.51 did: no size params means no\n * runtime entry (the slot keeps its declared box), a lone dimension is an\n * error, and `intrinsicSize` rides along. */\nexport function v1DirectUrlSize(\n params: URLSearchParams,\n readDimension: (value: string) => number | string,\n): CanvasHostRuntimeSize | undefined {\n const width = params.get(\"width\")?.trim();\n const height = params.get(\"height\")?.trim();\n const intrinsicSize = readDirectUrlFlag(params.get(\"intrinsicSize\"));\n if (!width && !height) {\n return intrinsicSize ? { intrinsicSize: true, revision: 1 } : undefined;\n }\n if (!width || !height) {\n throw new Error(\"Direct URL width and height must be provided together\");\n }\n return {\n width: readDimension(width),\n height: readDimension(height),\n ...(intrinsicSize ? { intrinsicSize: true } : {}),\n revision: 1,\n };\n}\n\n/** The `data-tempo-*` annotations of a Storyboard callsite. 0.0.51 forwarded\n * them onto the rendered component, and the V1 client roots the storyboard's\n * layer tree at the outermost annotated component and edits the callsite's\n * `props` through it. */\nexport function v1SourceAnnotations(\n props: Record<string, unknown>,\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(props).filter(([key]) => key.startsWith(\"data-tempo-\")),\n );\n}\n\n/** The storyboard shell's inline style as 0.0.51 computed it: a runtime\n * entry without a size keeps the declared box, an intrinsic slot hugs its\n * content, and a cached slot is click-through. */\nexport function v1StoryboardSlotStyle(slot: {\n kind: \"component\" | \"route\" | \"html\";\n layout: StoryboardLayout;\n renderSize: CanvasHostRuntimeSize | undefined;\n placement: CanvasHostRuntimePlacement | undefined;\n status: \"active\" | \"cached\";\n}): CSSProperties {\n const { kind, layout, renderSize, placement, status } = slot;\n const renderWidth = renderSize?.width;\n const renderHeight = renderSize?.height;\n const intrinsicSize =\n renderSize?.intrinsicSize ??\n (kind === \"component\" && layout.intrinsicSizing === \"root-element\");\n return {\n position: \"absolute\",\n left: placement?.left ?? layout.x,\n top: placement?.top ?? layout.y,\n width: intrinsicSize ? \"max-content\" : (renderWidth ?? layout.width),\n height: intrinsicSize ? \"max-content\" : (renderHeight ?? layout.height),\n minWidth: intrinsicSize ? renderWidth : undefined,\n minHeight: intrinsicSize ? renderHeight : undefined,\n zIndex: layout.zIndex,\n visibility: status === \"active\" ? \"visible\" : \"hidden\",\n pointerEvents: status === \"active\" ? \"auto\" : \"none\",\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;AAChC,SAAK,MAAM,QAAQ;AAAA,MACjB,SAAS,MAAM;AAAA,MACf,OAAO,MAAM;AAAA,MACb;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,WAAoB;AAClB,WAAO,KAAK,MAAM,UAAU;AAAA,EAC9B;AAAA,EAEA,QAAiB;AACf,QAAI,CAAC,KAAK,MAAM,MAAO,QAAO;AAC9B,SAAK;AAAA,MAAS,CAAC,UACb,MAAM,QACF,EAAE,OAAO,MAAM,gBAAgB,QAAW,UAAU,MAAM,SAAS,IACnE;AAAA,IACN;AACA,WAAO;AAAA,EACT;AAAA,EAEA,SAAS;AACP,QAAI,KAAK,MAAM,OAAO;AACpB,aACE,gBAAAF;AAAA,QAAC;AAAA;AAAA,UACC,qBAAkB;AAAA,UAClB,6BAA2B,KAAK,MAAM,MAAM;AAAA,UAC5C,OAAO,EAAE,OAAO,QAAQ,QAAQ,OAAO;AAAA;AAAA,MACzC;AAAA,IAEJ;AACA,WAAO,KAAK,MAAM;AAAA,EACpB;AACF;AAIA,IAAM,oBAAoB,OAAO;AAAA,EAC/B,SAASS,mBAAkB,EAAE,SAAS,GAA4B;AAChE,WAAO;AAAA,EACT;AAAA,EACA,EAAE,CAAC,qBAAqB,GAAG,SAAkB;AAC/C;AACA,OAAO,OAAO,qBAAqB,EAAE,CAAC,qBAAqB,GAAG,cAAc,CAAC;AAC7E,OAAO,OAAO,wBAAwB;AAAA,EACpC,CAAC,qBAAqB,GAAG;AAC3B,CAAC;AACD,OAAO,OAAO,yBAAyB;AAAA,EACrC,CAAC,qBAAqB,GAAG;AAC3B,CAAC;","names":["createContext","useContext","createContext","useContext","Children","cloneElement","isValidElement","useCallback","useEffect","useMemo","useRef","jsx","useCallback","jsx","Component","useRef","useCallback","useEffect","useMemo","isValidElement","cloneElement","Children","ProjectionContent"]}
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  captureHead
3
- } from "./chunk-XB6GU4CE.js";
3
+ } from "./chunk-I7VF4ZOV.js";
4
4
  import {
5
5
  capture
6
- } from "./chunk-LEBVQBDH.js";
6
+ } from "./chunk-T364NBR3.js";
7
7
 
8
8
  // assets/preview-snapshot.ts
9
9
  function captureAssetPreview(root) {
@@ -35,4 +35,4 @@ function captureAssetPreview(root) {
35
35
  export {
36
36
  captureAssetPreview
37
37
  };
38
- //# sourceMappingURL=chunk-CVUNZBRV.js.map
38
+ //# sourceMappingURL=chunk-ZT7HJ6YU.js.map