tempo-sdk 0.0.77 → 0.0.79
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.
- package/dist/assets/index.js +3 -3
- package/dist/astro/asset-preview-client.js +3 -3
- package/dist/astro.js +2 -2
- package/dist/canvas/astro.js +3 -3
- package/dist/canvas/index.js +5 -5
- package/dist/canvas/interact-projection.js +4 -4
- package/dist/canvas/svelte.js +3 -3
- package/dist/canvas/vue.js +3 -3
- package/dist/{chunk-3T7FO57P.js → chunk-4PGZTWKS.js} +2 -2
- package/dist/{chunk-QSOCNVDB.js → chunk-54P7S7VU.js} +2 -2
- package/dist/{chunk-QSOCNVDB.js.map → chunk-54P7S7VU.js.map} +1 -1
- package/dist/{chunk-6AAE4LYV.js → chunk-5M45Z7K6.js} +20 -5
- package/dist/{chunk-6AAE4LYV.js.map → chunk-5M45Z7K6.js.map} +1 -1
- package/dist/{chunk-LZWIVA5H.js → chunk-BHDCNLCO.js} +2 -2
- package/dist/{chunk-LZWIVA5H.js.map → chunk-BHDCNLCO.js.map} +1 -1
- package/dist/{chunk-PEY472AQ.js → chunk-D3WLLHZU.js} +2 -2
- package/dist/{chunk-CXIW4IKC.js → chunk-I5MJ342V.js} +3 -3
- package/dist/{chunk-GPRSFFH2.js → chunk-JMG5IDS5.js} +2 -2
- package/dist/{chunk-GPRSFFH2.js.map → chunk-JMG5IDS5.js.map} +1 -1
- package/dist/{chunk-TDXWSVCZ.js → chunk-QJA366VX.js} +11 -7
- package/dist/{chunk-TDXWSVCZ.js.map → chunk-QJA366VX.js.map} +1 -1
- package/dist/{chunk-S4YKLZEY.js → chunk-TFPT6T3K.js} +880 -15
- package/dist/chunk-TFPT6T3K.js.map +1 -0
- package/dist/{chunk-WBMO4ZYO.js → chunk-XN2K7GED.js} +288 -129
- package/dist/chunk-XN2K7GED.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/nextjs/plugin.cjs +1 -1
- package/dist/nextjs/plugin.cjs.map +1 -1
- package/dist/nextjs/plugin.js +1 -1
- package/dist/nextjs-loader.cjs +1 -1
- package/dist/nextjs-loader.cjs.map +1 -1
- package/dist/nextjs.cjs +1 -1
- package/dist/nextjs.cjs.map +1 -1
- package/dist/nextjs.js +1 -1
- package/dist/nuxt/runtime/identity.js +1 -1
- package/dist/nuxt.js +1 -1
- package/dist/vue.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-S4YKLZEY.js.map +0 -1
- package/dist/chunk-WBMO4ZYO.js.map +0 -1
- /package/dist/{chunk-3T7FO57P.js.map → chunk-4PGZTWKS.js.map} +0 -0
- /package/dist/{chunk-PEY472AQ.js.map → chunk-D3WLLHZU.js.map} +0 -0
- /package/dist/{chunk-CXIW4IKC.js.map → chunk-I5MJ342V.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../modules/iframe-projection/combined/projection-repair-paths.ts","../../../modules/rate-limiter/browser-frame-clock.ts","../../../modules/rate-limiter/work-scheduler.ts","../../../modules/iframe-projection/html/head-worker-source.ts","../../../modules/iframe-projection/html/head-worker.ts","../../../modules/iframe-projection/html/prepared-head.ts","../../../modules/iframe-projection/html/document-assets.ts","../../../modules/iframe-projection/combined/projection-capture-perf.ts","../../../modules/iframe-projection/html/root-coordinates.ts","../../../modules/iframe-projection/root-color.ts","../../../modules/iframe-projection/combined/projection-full-snapshot.ts","../../../modules/iframe-projection/combined/projection-astro-layers.ts","../../../modules/iframe-projection/combined/enriched-to-serialized-fiber.ts","../../../modules/iframe-projection/combined/projection-semantic-subtree.ts","../../../modules/iframe-projection/combined/projection-svelte-metadata.ts","../../../modules/iframe-projection/combined/projection-svelte-layers.ts","../../../modules/iframe-projection/combined/projection-vue-metadata.ts","../../../modules/iframe-projection/combined/projection-vue-layers.ts","../../../modules/iframe-projection/combined/projection-layer-adapter.ts","../../../modules/iframe-projection/combined/projection-producer.ts","../../../modules/iframe-projection/shared/portal-tracker.ts","../../../modules/iframe-projection/combined/projection-root-accumulator.ts","../../../modules/iframe-projection/combined/document-producer.ts","../../../modules/iframe-projection/combined/layer-framework.ts","../../../modules/iframe-projection/combined/projection-batch.ts","../../../modules/iframe-projection/html/snapshot.ts","../../../modules/iframe-projection/combined/render-identity.ts","../../../modules/iframe-projection/combined/declared-facts.ts","../../../modules/element-overlay/render/layout-kind.ts","../../../modules/iframe-projection/combined/enriched-serialize.ts","../../../modules/iframe-projection/combined/hide-fiber-tree.ts","../../../modules/iframe-projection/combined/watch.ts","../../../modules/iframe-projection/combined/postmessage.ts","../../../modules/iframe-projection/canvas-frames/demand.ts","../../../modules/iframe-projection/canvas-frames/demand-planner.ts","../../../modules/iframe-projection/canvas-frames/draw-tracker.ts","../../../modules/iframe-projection/canvas-frames/port-envelope.ts","../../../modules/iframe-projection/canvas-frames/canvas-registry.ts","../../../modules/iframe-projection/canvas-frames/direct-sampler.ts","../../../modules/iframe-projection/canvas-frames/capture-stream-sampler.ts","../../../modules/iframe-projection/canvas-frames/source.ts","../../../modules/iframe-projection/canvas-frames/port-protocol.ts","../../../modules/iframe-projection/canvas-frames/preserve-drawing-buffer.ts","../canvas/interact-canvas-frames.ts","../canvas/interact-projection.ts"],"sourcesContent":["/** Nearest-first ancestor paths, scoped to one watched root. The producer\n * chooses the first surviving source ancestor and emits its DOM and layers\n * together on the existing ordered stream. */\nexport type ProjectionRepairPaths = readonly (readonly string[])[];\n\nexport function isProjectionRepairPaths(\n value: unknown,\n): value is ProjectionRepairPaths {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every(\n (path) =>\n Array.isArray(path) &&\n path.length > 0 &&\n path.every((id) => typeof id === \"string\" && id.length > 0),\n )\n );\n}\n","/** Hidden Electron windows may suspend rAF while still needing to prepare\n * canvas content. Race only pending frames against a bounded hidden timer;\n * visible windows retain native frame timing. */\nexport function browserFrameClock() {\n let next = 0;\n const pending = new Map<number, () => void>();\n return {\n requestFrame(callback: (time: number) => void): number {\n const id = ++next;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const document = globalThis.document;\n const cleanup = () => {\n cancelAnimationFrame(native);\n clearTimeout(timer);\n document?.removeEventListener(\"visibilitychange\", visibility);\n pending.delete(id);\n };\n const finish = (time: number) => {\n cleanup();\n callback(time);\n };\n const visibility = () => {\n clearTimeout(timer);\n timer = document?.hidden\n ? setTimeout(() => finish(performance.now()), 1000 / 60)\n : undefined;\n };\n const native = requestAnimationFrame(finish);\n pending.set(id, cleanup);\n document?.addEventListener(\"visibilitychange\", visibility);\n visibility();\n return id;\n },\n cancelFrame(id: number) {\n pending.get(id)?.();\n },\n };\n}\n","import { browserFrameClock } from \"./browser-frame-clock\";\n\n/** Cooperative work on one renderer thread. Callbacks contain actual work;\n * async I/O stays outside and queues its continuation here. */\nexport interface WorkSlice {\n hasTime(): boolean;\n /** Reuse this admission across a cheap promise continuation only while its\n * pump still owns time and no queued job is waiting for its turn. */\n canContinue?(): boolean;\n}\nexport type WorkPriority = \"visible\" | \"background\" | \"frame\" | \"input\";\nexport interface WorkOptions {\n priority?: WorkPriority;\n signal?: AbortSignal;\n /** Live demand, including dependencies of the selected surface. */\n foreground?: () => boolean;\n}\nexport interface WorkScheduler {\n /** Run a private resumable preparation; each next() is a bounded step. */\n run<T>(steps: Iterator<unknown, T>, options?: WorkOptions): Promise<T>;\n schedule<T>(work: (slice: WorkSlice) => T, options?: WorkOptions): Promise<T>;\n /** Raise waiting preparation for this lifetime without cancelling it. */\n promote(signal: AbortSignal): void;\n /** Foreground input owns the thread allowance until the last claim releases. */\n claimInteractive(): () => void;\n /** Pause speculative work while a selected surface becomes usable. */\n claimForeground(): () => void;\n hasForeground(): boolean;\n subscribeForeground(listener: () => void): () => void;\n readonly diagnostics: {\n readonly interactiveClaims: number;\n readonly foregroundClaims: number;\n readonly eligibleJobs: number;\n readonly queued: number;\n readonly oldestMs: number;\n readonly slices: number;\n readonly overruns: number;\n readonly maxSliceMs: number;\n };\n dispose(): void;\n}\ninterface IdleDeadlineLike {\n didTimeout: boolean;\n timeRemaining(): number;\n}\nexport interface WorkSchedulerClock {\n now(): number;\n requestFrame(callback: (time: number) => void): number;\n cancelFrame(handle: number): void;\n task(callback: () => void): void;\n requestIdle?(\n callback: (deadline: IdleDeadlineLike) => void,\n options: { timeout: number },\n ): number;\n cancelIdle?(handle: number): void;\n inputPending?(): boolean;\n}\n\nconst browserClock = (): WorkSchedulerClock => ({\n now: () => performance.now(),\n ...browserFrameClock(),\n task: (callback) => {\n const scheduler = (\n globalThis as typeof globalThis & {\n scheduler?: {\n postTask(\n fn: () => void,\n options: { priority: string },\n ): Promise<void>;\n };\n }\n ).scheduler;\n if (scheduler)\n void scheduler.postTask(callback, { priority: \"user-visible\" });\n else setTimeout(callback, 0);\n },\n requestIdle:\n typeof requestIdleCallback === \"function\"\n ? (callback, options) => requestIdleCallback(callback, options)\n : undefined,\n cancelIdle: (handle) => globalThis.cancelIdleCallback?.(handle),\n inputPending: () =>\n (\n globalThis.navigator as\n | (Navigator & {\n scheduling?: {\n isInputPending(options: { includeContinuous: boolean }): boolean;\n };\n })\n | undefined\n )?.scheduling?.isInputPending({ includeContinuous: true }) === true,\n});\n\n/** One shared queue and allowance: timeout expiry and priority change order,\n * never grant a receiver another slice. A step is non-preemptible; overruns\n * are measured so callers can split the offending operation. */\nexport function createWorkScheduler(\n options: {\n clock?: WorkSchedulerClock;\n budgetMs?: number;\n /** Shared per-frame allowance while a selected surface owns readiness. */\n foregroundBudgetMs?: number;\n timeoutMs?: number;\n } = {},\n): WorkScheduler {\n const clock = options.clock ?? browserClock();\n const budget = options.budgetMs ?? 2;\n const foregroundBudget = options.foregroundBudgetMs ?? budget;\n const timeout = options.timeoutMs ?? 50;\n // Resource inventories cross Promise.race/all and several async helpers.\n // Let those bounded microtask chains return without spending a frame per\n // cheap read; elapsed time and the input/deadline checks still bound work.\n const continuationTicks = 32;\n if (!(budget > 0 && Number.isFinite(budget)))\n throw new RangeError(\"budgetMs must be finite and positive\");\n if (!(foregroundBudget > 0 && Number.isFinite(foregroundBudget)))\n throw new RangeError(\"foregroundBudgetMs must be finite and positive\");\n type Job = {\n at: number;\n priority: WorkPriority;\n signal?: AbortSignal;\n foreground?: () => boolean;\n run(slice: WorkSlice): void;\n abort(): void;\n };\n const queues = {\n visible: new Set<Job>(),\n background: new Set<Job>(),\n frame: new Set<Job>(),\n input: new Set<Job>(),\n };\n const interactive = new Set<object>();\n const foreground = new Set<object>();\n const foregroundListeners = new Set<() => void>();\n let frame: number | null = null;\n let idle: number | null = null;\n let taskPending = false;\n let disposed = false;\n let draining = false;\n let blockedUntilFrame = false;\n let spent = 0;\n let frameAt: number | null = null;\n let interval = 1000 / 120;\n let sampledInterval: number | null = null;\n let slices = 0,\n overruns = 0,\n maxSliceMs = 0;\n const count = () =>\n queues.visible.size +\n queues.background.size +\n queues.frame.size +\n queues.input.size;\n const first = (queue: Set<Job>) =>\n queue.values().next().value as Job | undefined;\n const frameBudget = () => (foreground.size ? foregroundBudget : budget);\n const allowance = () =>\n blockedUntilFrame\n ? 0\n : Math.min(\n frameBudget() - spent,\n frameAt === null\n ? frameBudget() - spent\n : frameAt + interval - Math.max(2, interval * 0.35) - clock.now(),\n );\n const remove = (job: Job) => {\n queues[job.priority].delete(job);\n job.signal?.removeEventListener(\"abort\", job.abort);\n };\n const eligible = (job: Job) =>\n !foreground.size || job.foreground?.() === true;\n const candidate = (queue: Set<Job>) => {\n let ordinary: Job | undefined;\n for (const job of queue) {\n if (job.foreground?.()) return job;\n if (!ordinary && eligible(job)) ordinary = job;\n }\n return ordinary;\n };\n const choose = (kind: \"task\" | \"idle\" | \"frame\") => {\n if (kind === \"frame\" && interactive.size && queues.input.size)\n return first(queues.input);\n // Readiness is input preparation, not a frame mutation. It may use a task\n // opportunity while a gesture waits for its surface, with the same budget.\n const urgentInput = candidate(queues.input);\n if (urgentInput?.foreground?.()) return urgentInput;\n if (kind === \"frame\" && queues.input.size) return first(queues.input);\n if (interactive.size) return undefined;\n const candidates = [\n candidate(queues.visible),\n candidate(queues.background),\n ...(kind === \"frame\" ? [candidate(queues.frame)] : []),\n ].filter((job): job is Job => !!job);\n const urgent = candidates.find((job) => job.foreground?.());\n if (urgent) return urgent;\n // Starved work gets the same allowance, ahead of newly visible work.\n return (\n candidates\n .filter((job) => clock.now() - job.at >= timeout)\n .sort((a, b) => a.at - b.at)[0] ??\n (kind === \"frame\" ? candidate(queues.frame) : undefined) ??\n candidate(queues.visible) ??\n candidate(queues.background)\n );\n };\n async function pump(\n kind: \"task\" | \"idle\" | \"frame\",\n deadline?: IdleDeadlineLike,\n ) {\n if (disposed || draining) return;\n draining = true;\n const start = clock.now();\n const forced =\n deadline?.didTimeout === true ||\n [\n first(queues.visible),\n first(queues.background),\n first(queues.frame),\n first(queues.input),\n ].some((job) => job && clock.now() - job.at >= timeout);\n // A delayed native frame may arrive after every render reserve. Once\n // queued work ages out, use what remains of this frame's shared budget\n // so that reserve cannot prevent convergence indefinitely. Continuations\n // and other priorities still spend this same allowance.\n const available = Math.max(0, forced ? frameBudget() - spent : allowance());\n let runningInput = false;\n const hasTime = () =>\n clock.now() - start < Math.min(available, frameBudget() - spent) &&\n (!deadline || deadline.didTimeout || deadline.timeRemaining() > 0) &&\n (runningInput ||\n (kind === \"frame\" && queues.input.size > 0) ||\n forced ||\n !clock.inputPending?.());\n let served = false;\n let active = true;\n // On a slow renderer, choosing an eligible job can consume the allowance\n // before its first step. An overdue job still gets one indivisible step;\n // charge the overrun normally and allow no more work in this frame.\n const owesStep = () => forced && available > 0 && !served;\n try {\n while (owesStep() || hasTime()) {\n let job = choose(kind);\n // Keep short receiver continuations in this same opportunity, while\n // charging their elapsed time and rechecking input/deadline/budget.\n for (let tick = 0; served && !job && tick < continuationTicks; tick++) {\n await Promise.resolve();\n job = choose(kind);\n }\n if (!job || (!owesStep() && !hasTime())) break;\n remove(job);\n runningInput = job.priority === \"input\";\n const current = job;\n job.run({\n hasTime,\n canContinue: () =>\n active &&\n eligible(current) &&\n (!interactive.size || current.priority === \"input\") &&\n hasTime() &&\n choose(kind) === undefined,\n });\n runningInput = false;\n served = true;\n }\n } finally {\n active = false;\n const elapsed = clock.now() - start;\n spent += elapsed;\n // A cheap successful step can resolve through several async layers.\n // Its continuation still owns the unspent allowance; only a pump that\n // found no runnable job needs to wait for the next frame.\n if (!served && elapsed === 0 && count()) blockedUntilFrame = true;\n slices++;\n maxSliceMs = Math.max(maxSliceMs, elapsed);\n if (elapsed > available + 0.25) overruns++;\n draining = false;\n request();\n }\n }\n function request() {\n if (disposed || draining || !count()) return;\n if (interactive.size && !queues.input.size) return;\n if (\n foreground.size &&\n !queues.input.size &&\n !Object.values(queues).some((queue) => candidate(queue))\n )\n return;\n // A frame resets the single aggregate allowance. Work posted by promise\n // continuations before then still spends the previous allowance.\n if (frame === null)\n frame = clock.requestFrame((time) => {\n frame = null;\n const delta = frameAt === null ? null : time - frameAt;\n // A missed frame must not grant more script time on the next one.\n if (delta !== null && delta >= 4 && delta < 250) {\n sampledInterval = Math.min(sampledInterval ?? delta, delta);\n interval = Math.min(1000 / 60, sampledInterval);\n }\n frameAt = time;\n spent = 0;\n blockedUntilFrame = false;\n // Idle opportunities can arrive after the render reserve on every\n // frame. Serve selected preparation at this known opportunity too;\n // fresh and aged work still share the same bounded allowance.\n if (\n queues.input.size ||\n queues.frame.size ||\n candidate(queues.visible)?.foreground?.() === true ||\n candidate(queues.background)?.foreground?.() === true ||\n [first(queues.visible), first(queues.background)].some(\n (job) => job && clock.now() - job.at >= timeout,\n )\n )\n void pump(\"frame\");\n request();\n });\n if (allowance() <= 0) return;\n const urgentInput = candidate(queues.input)?.foreground?.() === true;\n if (interactive.size && !urgentInput) return;\n if (\n (urgentInput ||\n candidate(queues.visible) ||\n candidate(queues.background)?.foreground?.()) &&\n !taskPending\n ) {\n taskPending = true;\n clock.task(() => {\n taskPending = false;\n void pump(\"task\");\n });\n } else if (candidate(queues.background) && idle === null) {\n if (clock.requestIdle)\n idle = clock.requestIdle(\n (deadline) => {\n idle = null;\n void pump(\"idle\", deadline);\n },\n { timeout },\n );\n else if (!taskPending) {\n taskPending = true;\n clock.task(() => {\n taskPending = false;\n void pump(\"task\");\n });\n }\n }\n }\n const scheduler: WorkScheduler = {\n async run<T>(steps: Iterator<unknown, T>, settings: WorkOptions = {}) {\n for (;;) {\n const next = await scheduler.schedule((slice) => {\n let next: IteratorResult<unknown, T>;\n do {\n next = steps.next();\n } while (!next.done && slice.hasTime());\n return next;\n }, settings);\n if (disposed || settings.signal?.aborted)\n throw settings.signal?.reason ?? new Error(\"Work scheduler disposed\");\n if (next.done) return next.value;\n }\n },\n schedule<T>(work: (slice: WorkSlice) => T, settings: WorkOptions = {}) {\n if (disposed || settings.signal?.aborted)\n return Promise.reject(\n settings.signal?.reason ?? new Error(\"Work scheduler disposed\"),\n );\n return new Promise<T>((resolve, reject) => {\n const job: Job = {\n at: clock.now(),\n priority: settings.priority ?? \"visible\",\n signal: settings.signal,\n foreground: settings.foreground,\n abort() {\n remove(job);\n reject(\n settings.signal?.reason ?? new Error(\"Work scheduler disposed\"),\n );\n },\n run(slice) {\n try {\n const value = work(slice);\n if (\n value &&\n typeof (value as { then?: unknown }).then === \"function\"\n )\n throw new TypeError(\"Scheduled work must be synchronous\");\n resolve(value);\n } catch (error) {\n reject(error);\n }\n },\n };\n queues[job.priority].add(job);\n settings.signal?.addEventListener(\"abort\", job.abort, { once: true });\n request();\n });\n },\n hasForeground: () => foreground.size > 0,\n subscribeForeground(listener) {\n foregroundListeners.add(listener);\n return () => {\n foregroundListeners.delete(listener);\n };\n },\n claimForeground() {\n const token = {};\n foreground.add(token);\n if (foreground.size === 1)\n for (const listener of foregroundListeners) listener();\n request();\n return () => {\n if (!foreground.delete(token)) return;\n if (foreground.size === 0)\n for (const listener of foregroundListeners) listener();\n request();\n };\n },\n claimInteractive() {\n const token = {};\n interactive.add(token);\n if (idle !== null) clock.cancelIdle?.(idle);\n idle = null;\n return () => {\n if (!interactive.delete(token)) return;\n request();\n };\n },\n promote(signal) {\n for (const job of queues.background) {\n if (job.signal !== signal) continue;\n queues.background.delete(job);\n job.priority = \"visible\";\n queues.visible.add(job);\n }\n request();\n },\n get diagnostics() {\n return {\n interactiveClaims: interactive.size,\n foregroundClaims: foreground.size,\n eligibleJobs: Object.values(queues).reduce(\n (total, queue) => total + [...queue].filter(eligible).length,\n 0,\n ),\n queued: count(),\n oldestMs: Math.max(\n 0,\n ...Object.values(queues).map((queue) => {\n const job = first(queue);\n return job ? clock.now() - job.at : 0;\n }),\n ),\n slices,\n overruns,\n maxSliceMs,\n };\n },\n dispose() {\n disposed = true;\n if (frame !== null) clock.cancelFrame(frame);\n if (idle !== null) clock.cancelIdle?.(idle);\n for (const queue of Object.values(queues))\n for (const job of queue) job.abort();\n },\n };\n return scheduler;\n}\n","// Generated by: bun modules/iframe-projection/scripts/build-head-worker.ts --write\n// Regeneration is checked by head-worker-source.test.ts.\nexport const HEAD_WORKER_SOURCE =\n \"(function() {\\n \\\"use strict\\\";\\n function extractStyleSourceEvidence(text) {\\n const attributes = {};\\n const clone = {\\n setAttribute: (key, value) => {\\n attributes[key] = value;\\n }\\n };\\n const reference = [\\n ...text.matchAll(/\\\\/\\\\*[#@]\\\\s*sourceMappingURL\\\\s*=\\\\s*(\\\\S+?)\\\\s*\\\\*\\\\//g)\\n ].slice(-1)[0]?.[1];\\n if (!reference || reference.length > 1024 * 1024) return attributes;\\n const inline = /^data:application\\\\/json(?:;charset=[\\\\w-]+)?(;base64)?,(.*)$/is.exec(\\n reference\\n );\\n if (!inline) {\\n try {\\n const url = new URL(reference);\\n if (/^https?:$/.test(url.protocol))\\n clone.setAttribute(\\\"data-projection-css-source-map-url\\\", url.href);\\n } catch {\\n }\\n return attributes;\\n }\\n function compact(raw, depth) {\\n if (!raw || typeof raw !== \\\"object\\\" || depth > 16) return null;\\n const map = raw;\\n if (map.version !== 3) return null;\\n const sources = Array.isArray(map.sources) && map.sources.length <= 4096 && map.sources.every((source) => typeof source === \\\"string\\\") ? map.sources : void 0;\\n const sections = Array.isArray(map.sections) && map.sections.length <= 256 ? map.sections.flatMap((section) => {\\n const nested = section && typeof section === \\\"object\\\" ? compact(section.map, depth + 1) : null;\\n return nested ? [{ map: nested }] : [];\\n }) : void 0;\\n return {\\n version: 3,\\n ...typeof map.file === \\\"string\\\" ? { file: map.file } : {},\\n ...typeof map.sourceRoot === \\\"string\\\" ? { sourceRoot: map.sourceRoot } : {},\\n ...sources ? { sources } : {},\\n ...sections ? { sections } : {}\\n };\\n }\\n try {\\n const json = inline[1] ? new TextDecoder().decode(\\n Uint8Array.from(\\n atob(inline[2]),\\n (character) => character.charCodeAt(0)\\n )\\n ) : decodeURIComponent(inline[2]);\\n const metadata = compact(JSON.parse(json), 0);\\n if (!metadata) return attributes;\\n const serialized = JSON.stringify(metadata);\\n if (serialized.length <= 64 * 1024)\\n clone.setAttribute(\\\"data-projection-css-source-map\\\", serialized);\\n } catch {\\n }\\n return attributes;\\n }\\n function absolutifyCssReferences(cssText, baseHref) {\\n const resolve = (value) => {\\n const trimmed = value.trim();\\n if (!trimmed || trimmed.startsWith(\\\"#\\\") || /^(?:data|blob|javascript):/i.test(trimmed)) {\\n return /^javascript:/i.test(trimmed) ? \\\"\\\" : trimmed;\\n }\\n try {\\n return new URL(trimmed, baseHref).href;\\n } catch {\\n return trimmed;\\n }\\n };\\n return cssText.replace(\\n /url\\\\(\\\\s*([\\\"']?)([^\\\"')]+)\\\\1\\\\s*\\\\)/gi,\\n (_match, quote, value) => `url(${quote}${resolve(value)}${quote})`\\n ).replace(\\n /@import\\\\s+([\\\"'])([^\\\"']+)\\\\1/gi,\\n (_match, quote, value) => `@import ${quote}${resolve(value)}${quote}`\\n );\\n }\\n const scope = globalThis;\\n scope.onmessage = async ({ data }) => {\\n const stages = {};\\n const measure = (name, work) => {\\n if (!data.measure) return work();\\n const start = performance.now();\\n const value = work();\\n stages[name] = performance.now() - start;\\n return value;\\n };\\n try {\\n const metadata = data.metadata ?? measure(\\n \\\"sourceMetadata\\\",\\n () => extractStyleSourceEvidence(data.authored ?? \\\"\\\")\\n );\\n const rawCss = measure(\\\"joinRules\\\", () => data.rules.join(\\\"\\\\n\\\"));\\n const css = measure(\\n \\\"resolveUrls\\\",\\n () => absolutifyCssReferences(rawCss, data.base)\\n );\\n const start = data.measure ? performance.now() : 0;\\n const digest = await crypto.subtle.digest(\\n \\\"SHA-256\\\",\\n new TextEncoder().encode(css)\\n );\\n const hash = Array.from(\\n new Uint8Array(digest),\\n (byte) => byte.toString(16).padStart(2, \\\"0\\\")\\n ).join(\\\"\\\");\\n if (data.measure) stages.resourceHash = performance.now() - start;\\n scope.postMessage({\\n id: data.id,\\n result: { css, hash, metadata, stages }\\n });\\n } catch (error) {\\n scope.postMessage({ id: data.id, error: String(error) });\\n }\\n };\\n})();\\n\";\n","import { HEAD_WORKER_SOURCE } from \"./head-worker-source\";\n\nconst WORKER_TIMEOUT_MS = 30_000;\nexport interface HeadTextInput {\n rules: string[];\n authored?: string;\n base: string;\n metadata?: Record<string, string>;\n measure: boolean;\n}\nexport interface HeadTextResult {\n css: string;\n hash: string;\n metadata: Record<string, string>;\n stages: Record<string, number>;\n}\n\nexport function createHeadWorker() {\n let worker: Worker | undefined;\n let url: string | undefined;\n let sequence = 0;\n const pending = new Map<\n number,\n {\n resolve(value: HeadTextResult): void;\n reject(error: Error): void;\n timer: ReturnType<typeof setTimeout>;\n }\n >();\n const dispose = (error = new Error(\"Head worker stopped\")) => {\n if (worker) {\n worker.onmessage = null;\n worker.onerror = null;\n worker.onmessageerror = null;\n worker.terminate();\n }\n worker = undefined;\n if (url) URL.revokeObjectURL(url);\n url = undefined;\n for (const job of pending.values()) {\n clearTimeout(job.timer);\n job.reject(error);\n }\n pending.clear();\n };\n return {\n process(input: HeadTextInput): Promise<HeadTextResult> {\n if (!worker) {\n url = URL.createObjectURL(\n new Blob([HEAD_WORKER_SOURCE], { type: \"text/javascript\" }),\n );\n try {\n worker = new Worker(url);\n } catch (error) {\n dispose();\n return Promise.reject(error);\n }\n worker.onmessage = ({ data }) => {\n const job = pending.get(data.id);\n if (!job) return;\n pending.delete(data.id);\n clearTimeout(job.timer);\n if (data.error) job.reject(new Error(data.error));\n else job.resolve(data.result);\n };\n worker.onerror = () => dispose();\n worker.onmessageerror = () => dispose();\n }\n return new Promise((resolve, reject) => {\n const id = ++sequence;\n const timer = setTimeout(() => {\n dispose(new Error(\"Head worker timed out after 30000ms\"));\n }, WORKER_TIMEOUT_MS);\n pending.set(id, { resolve, reject, timer });\n try {\n worker!.postMessage({ ...input, id });\n } catch (error) {\n pending.delete(id);\n clearTimeout(timer);\n reject(error);\n }\n });\n },\n dispose,\n };\n}\n","import {\n createWorkScheduler,\n type WorkSchedulerClock,\n} from \"../../rate-limiter/work-scheduler\";\nimport { createHeadWorker, type HeadTextResult } from \"./head-worker\";\nimport {\n beginHeadCapture,\n finishHeadCapture,\n type HeadTiming,\n beginHeadSheet,\n} from \"./head-capture-diagnostics\";\nimport {\n getHeadTracker,\n isDisabledStylesheet,\n resolveUrls,\n shouldIncludeLink,\n type StyleResource,\n} from \"./watch-head\";\n\ntype Source = Element | CSSStyleSheet;\ninterface PreparedStyle {\n node: Element;\n text?: HeadTextResult;\n rules: number;\n markup?: { href: string | null; html: string };\n}\n\n/** One source document owns its preparation, independently of projection epochs.\n * Sessions still receive complete heads. No CSSOM is read to prove a cache hit. */\ntype PreparedHead = ReturnType<typeof buildPreparedHead>;\nconst documents = new WeakMap<\n Document,\n { head: PreparedHead; owners: number }\n>();\nexport function createPreparedHead(\n doc: Document,\n clock?: WorkSchedulerClock,\n): PreparedHead {\n let shared = documents.get(doc);\n if (!shared) {\n shared = { head: buildPreparedHead(doc, clock), owners: 0 };\n documents.set(doc, shared);\n }\n shared.owners++;\n const owner = shared;\n let disposed = false;\n return {\n ...owner.head,\n dispose() {\n if (disposed) return;\n disposed = true;\n if (--owner.owners === 0) {\n owner.head.dispose();\n documents.delete(doc);\n }\n },\n };\n}\nfunction buildPreparedHead(doc: Document, clock?: WorkSchedulerClock) {\n const work = createWorkScheduler({ clock });\n const worker = createHeadWorker();\n const abort = new AbortController();\n const cache = new Map<Source, PreparedStyle>();\n const versions = new Map<Source, number>();\n const mutable = new Set<Source>();\n let consumed = false;\n const metadata = new WeakMap<\n Element,\n { authored: string; value: Record<string, string> }\n >();\n let revision = 0;\n let preparedRevision = -1;\n let base = doc.baseURI;\n let adopted: CSSStyleSheet[] = [];\n let ordered: PreparedStyle[] = [];\n let lastOutput: { ordered: PreparedStyle[]; html: string } | undefined;\n let pending: Promise<void> | undefined;\n let disposed = false;\n const subscription = getHeadTracker().subscribe(doc, (detail) => {\n revision++;\n if (detail.allStyles) {\n cache.clear();\n for (const source of versions.keys()) versions.set(source, revision);\n } else {\n for (const source of [\n ...(detail.elements ?? []),\n ...(detail.sheets ?? []),\n ]) {\n cache.delete(source);\n if (detail.mutable) mutable.add(source);\n versions.set(source, revision);\n }\n }\n });\n const sync = () => {\n getHeadTracker().flushPending?.(doc);\n // Chromium permits push/splice/reverse on this native list without invoking\n // the Document setter. Compare identities/order, never CSS rules or text.\n const currentAdopted = doc.adoptedStyleSheets ?? [];\n if (\n currentAdopted.length !== adopted.length ||\n currentAdopted.some((sheet, index) => sheet !== adopted[index])\n ) {\n adopted = Array.from(currentAdopted);\n revision++;\n }\n if (base !== doc.baseURI) {\n const samePath = base.split(/[?#]/)[0] === doc.baseURI.split(/[?#]/)[0];\n base = doc.baseURI;\n revision++;\n // Direct-render capture changes storyboard/viewport in the URL query.\n // Nonempty relative CSS URLs resolve identically against that same path.\n // Empty/fragment URLs remain unchanged by the legacy CSS transform.\n for (const source of versions.keys()) {\n const value = cache.get(source);\n if (\n !value ||\n !samePath ||\n (\"tagName\" in source && source.tagName !== \"STYLE\")\n ) {\n cache.delete(source);\n versions.set(source, revision);\n }\n }\n }\n };\n\n function* read(\n source: Source,\n timing?: HeadTiming,\n ): Generator<\n undefined,\n {\n node: Element;\n rules: string[] | null;\n authored?: string;\n cssBase: string;\n count: number;\n }\n > {\n const isElement = \"tagName\" in source;\n const node = isElement\n ? (source.cloneNode(false) as Element)\n : doc.createElement(\"style\");\n let sheet: CSSStyleSheet | null;\n let authored: string | undefined;\n let cssBase = base;\n if (isElement) {\n sheet = (source as HTMLStyleElement | HTMLLinkElement).sheet;\n if (source.tagName === \"STYLE\") {\n // Source-map comments disappear from CSSOM; keep authored metadata only.\n authored = source.textContent ?? \"\";\n } else if (source.tagName === \"LINK\")\n cssBase = (source as HTMLLinkElement).href;\n } else {\n sheet = source;\n node.setAttribute(\"data-projection-adopted-stylesheet\", \"true\");\n }\n let list: readonly CSSRule[];\n try {\n if (!sheet) throw new Error(\"No stylesheet\");\n // Pin rule identities/order before yielding. Reading cssText remains\n // sliced: insert/delete/replace during a yield cannot skip or duplicate\n // rules in this generation. Changed declarations converge next generation.\n const started = timing ? performance.now() : 0;\n list = Array.from(sheet.cssRules);\n if (timing) {\n const elapsed = performance.now() - started;\n timing.report.stages.snapshotRuleIdentities =\n (timing.report.stages.snapshotRuleIdentities ?? 0) + elapsed;\n if (timing.sheet) timing.sheet.stages.snapshotRuleIdentities = elapsed;\n }\n } catch {\n if (authored !== undefined)\n return { node, rules: [authored], authored, cssBase, count: 0 };\n return { node, rules: null, cssBase, count: 0 };\n }\n const rules: string[] = [];\n // Never join or transform large CSS strings on this thread.\n for (let offset = 0; offset < list.length; ) {\n const start = timing ? performance.now() : 0;\n const end = Math.min(offset + 32, list.length);\n for (; offset < end; offset++) rules.push(list[offset]!.cssText);\n if (timing) {\n const elapsed = performance.now() - start;\n timing.report.stages.readCssRules =\n (timing.report.stages.readCssRules ?? 0) + elapsed;\n if (timing.sheet)\n timing.sheet.stages.readCssRules =\n (timing.sheet.stages.readCssRules ?? 0) + elapsed;\n }\n yield;\n }\n return { node, rules, authored, cssBase, count: rules.length };\n }\n\n async function prepare(reason: string) {\n const timing = beginHeadCapture(doc);\n if (timing) timing.report.reason = reason;\n try {\n sync();\n const epoch = revision;\n const sources: Source[] = [\n ...Array.from(doc.head?.children ?? []).filter((node) => {\n if (node.tagName === \"LINK\")\n return shouldIncludeLink(node) && !isDisabledStylesheet(node);\n if (node.tagName === \"META\") {\n const name = node.getAttribute(\"name\")?.toLowerCase();\n return (\n node.getAttribute(\"http-equiv\")?.toLowerCase() !==\n \"content-security-policy\" &&\n name !== \"content-security-policy\" &&\n name !== \"theme-color\"\n );\n }\n return node.tagName === \"STYLE\" || node.tagName === \"BASE\";\n }),\n ...adopted,\n ];\n const next: PreparedStyle[] = [];\n for (const source of sources) {\n if (disposed) throw new Error(\"Head preparation stopped\");\n const hit = cache.get(source);\n if (hit) {\n next.push(hit);\n if (timing) timing.report.cacheHits++;\n continue;\n }\n if (timing) timing.report.cacheMisses++;\n const sourceVersion = versions.get(source) ?? revision;\n versions.set(source, sourceVersion);\n const kind = \"tagName\" in source ? source.tagName : \"adopted\";\n const sheetTiming = beginHeadSheet(timing, kind);\n if (sheetTiming?.sheet && \"tagName\" in source)\n sheetTiming.sheet.source = (\n source.getAttribute(\"data-vite-dev-id\") ??\n source.getAttribute(\"href\") ??\n source.id\n )\n .split(/[?#]/)[0]\n .split(\"/\")\n .slice(-2)\n .join(\"/\")\n .slice(0, 256);\n let prepared: PreparedStyle;\n if (kind === \"META\" || kind === \"BASE\") {\n const node = (source as Element).cloneNode(true) as Element;\n resolveUrls(node, base);\n prepared = { node, rules: 0 };\n } else {\n const queued = timing ? performance.now() : 0;\n const input = await work.run(read(source, sheetTiming), {\n signal: abort.signal,\n priority: \"visible\",\n });\n if (timing) timing.report.readWallMs += performance.now() - queued;\n let node = input.node;\n if (input.rules === null) {\n node.removeAttribute(\"crossorigin\");\n resolveUrls(node, base);\n prepared = { node, rules: 0 };\n } else {\n if (kind === \"LINK\") {\n node = doc.createElement(\"style\");\n for (const attribute of Array.from(input.node.attributes)) {\n if (\n ![\n \"as\",\n \"crossorigin\",\n \"fetchpriority\",\n \"href\",\n \"integrity\",\n \"referrerpolicy\",\n \"rel\",\n ].includes(attribute.name.toLowerCase())\n )\n node.setAttribute(attribute.name, attribute.value);\n }\n node.setAttribute(\n \"data-projection-stylesheet-href\",\n input.cssBase,\n );\n }\n const previous =\n \"tagName\" in source ? metadata.get(source) : undefined;\n const authored = input.authored;\n const started = timing ? performance.now() : 0;\n const text = await worker.process({\n rules: input.rules,\n authored:\n authored && authored.length <= 5 * 1024 * 1024 ? authored : \"\",\n base: input.cssBase,\n metadata:\n previous?.authored === authored ? previous?.value : undefined,\n measure: !!timing,\n });\n if (timing) {\n timing.report.workerWallMs += performance.now() - started;\n for (const [stage, elapsed] of Object.entries(text.stages)) {\n timing.report.stages[stage] =\n (timing.report.stages[stage] ?? 0) + elapsed;\n if (sheetTiming?.sheet)\n sheetTiming.sheet.stages[stage] = elapsed;\n }\n }\n node.removeAttribute(\"data-projection-css-source-map\");\n node.removeAttribute(\"data-projection-css-source-map-url\");\n for (const [key, value] of Object.entries(text.metadata))\n node.setAttribute(key, value);\n if (\"tagName\" in source && authored !== undefined)\n metadata.set(source, { authored, value: text.metadata });\n resolveUrls(node, base);\n prepared = { node, text, rules: input.count };\n if (sheetTiming?.sheet) {\n sheetTiming.sheet.rules = input.count;\n sheetTiming.sheet.characters = text.css.length;\n }\n }\n }\n sync();\n if (sourceVersion === versions.get(source)) cache.set(source, prepared);\n next.push(prepared);\n }\n sync();\n // Publish completed work once, even if a newer revision arrived while\n // reading/processing. Keep that invalidation pending for the next pass.\n ordered = next;\n preparedRevision = epoch;\n const retained = new Set(sources);\n for (const source of cache.keys())\n if (!retained.has(source)) cache.delete(source);\n for (const source of versions.keys())\n if (!retained.has(source)) versions.delete(source);\n for (const source of mutable)\n if (!retained.has(source)) mutable.delete(source);\n } finally {\n if (timing) {\n timing.report.revision = revision;\n timing.report.maxSliceSinceDocumentStartMs =\n work.diagnostics.maxSliceMs;\n finishHeadCapture(doc, timing);\n }\n }\n }\n\n return {\n prepare(reason = \"head-request\"): Promise<void> | undefined {\n sync();\n // The outbox re-enters prepare after the promise resolves. Do not start\n // another generation before it has had a chance to publish this one.\n if (preparedRevision >= 0 && !consumed) return;\n if (consumed && mutable.size) {\n revision++;\n for (const source of mutable) {\n cache.delete(source);\n versions.set(source, revision);\n }\n }\n consumed = false;\n if (preparedRevision === revision) return;\n if (!pending)\n pending = prepare(reason).finally(() => {\n pending = undefined;\n });\n return pending;\n },\n hasPendingChanges(): boolean {\n sync();\n return preparedRevision !== revision;\n },\n capture(resource?: StyleResource): string {\n sync();\n if (preparedRevision < 0) throw new Error(\"Head has not been prepared\");\n consumed = true;\n const timing = beginHeadCapture(doc);\n if (timing) {\n timing.report.reason = \"prepared-head-reuse\";\n timing.report.revision = revision;\n timing.report.cacheHits = ordered.length;\n }\n try {\n let changed = lastOutput?.ordered !== ordered;\n const fragments = ordered.map((entry) => {\n const { node, text } = entry;\n if (!text) return node.outerHTML;\n if (\n node.hasAttribute(\"data-projection-adopted-stylesheet\") &&\n !text.css\n )\n return \"\";\n const type = node.getAttribute(\"type\")?.trim().toLowerCase();\n const href =\n !type || type === \"text/css\"\n ? resource?.(text.css, text.hash)\n : null;\n const previous = entry.markup;\n if (previous && previous.href === (href ?? null))\n return previous.html;\n changed = true;\n if (href) {\n const link = doc.createElement(\"link\");\n for (const attribute of Array.from(node.attributes)) {\n if (\n ![\"type\", \"href\", \"rel\", \"integrity\", \"crossorigin\"].includes(\n attribute.name,\n )\n )\n link.setAttribute(attribute.name, attribute.value);\n }\n link.rel = \"stylesheet\";\n link.href = href;\n const html = link.outerHTML;\n entry.markup = { href, html };\n return html;\n }\n node.textContent = text.css.replace(/<\\//gi, \"<\\\\/\");\n const html = node.outerHTML;\n entry.markup = { href: null, html };\n return html;\n });\n if (!changed && lastOutput) return lastOutput.html;\n const html = fragments.filter(Boolean).join(\"\\n\");\n lastOutput = { ordered, html };\n return html;\n } finally {\n if (timing) finishHeadCapture(doc, timing);\n }\n },\n dispose() {\n disposed = true;\n abort.abort();\n subscription.unsubscribe();\n worker.dispose();\n work.dispose();\n cache.clear();\n versions.clear();\n ordered = [];\n },\n };\n}\n","/** Browser-observed resource changes, shared by document consumers. DOM/head\n * mutations already have owners; this fills only their resource-completion gap.\n * A resource entry is a completion signal, never pending-request evidence. */\ntype AssetListener = (target: Element | null) => void;\nconst observers = new WeakMap<\n Document,\n {\n listeners: Set<AssetListener>;\n stop(): void;\n }\n>();\n\nexport function observeDocumentAssets(\n doc: Document,\n listener: AssetListener,\n): () => void {\n let observer = observers.get(doc);\n if (!observer) {\n const listeners = new Set<AssetListener>();\n let active = true;\n const notify = (target: Element | null) => {\n if (active) for (const callback of listeners) callback(target);\n };\n const onResource = (event: Event) => {\n const target = event.target as Element | null;\n if (target?.localName === \"img\" || target?.localName === \"image\")\n notify(target);\n else if (\n target?.localName === \"link\" &&\n (target as HTMLLinkElement).relList.contains(\"stylesheet\")\n )\n notify(null);\n };\n const onFonts = () => notify(null);\n doc.addEventListener(\"load\", onResource, true);\n doc.addEventListener(\"error\", onResource, true);\n for (const type of [\"loading\", \"loadingdone\", \"loadingerror\"])\n doc.fonts?.addEventListener(type, onFonts);\n const PerformanceObserver = doc.defaultView?.PerformanceObserver;\n const performanceObserver = PerformanceObserver\n ? new PerformanceObserver((list) => {\n // CSS is intentionally document-wide: attributing a background/mask/font\n // request to roots would require a resource dependency graph. Images have\n // DOM load/error events above, and unrelated fetch/upload never enters.\n if (\n list\n .getEntries()\n .some(\n (entry) =>\n (entry as PerformanceResourceTiming).initiatorType === \"css\",\n )\n )\n notify(null);\n })\n : null;\n performanceObserver?.observe({ type: \"resource\", buffered: false });\n observer = {\n listeners,\n stop() {\n active = false;\n performanceObserver?.disconnect();\n doc.removeEventListener(\"load\", onResource, true);\n doc.removeEventListener(\"error\", onResource, true);\n for (const type of [\"loading\", \"loadingdone\", \"loadingerror\"])\n doc.fonts?.removeEventListener(type, onFonts);\n },\n };\n observers.set(doc, observer);\n }\n observer.listeners.add(listener);\n let subscribed = true;\n return () => {\n if (!subscribed) return;\n subscribed = false;\n observer.listeners.delete(listener);\n if (observer.listeners.size === 0) {\n observer.stop();\n observers.delete(doc);\n }\n };\n}\n","import type { DomCapture } from \"../html/types\";\nimport { getHeadTracker } from \"../html/watch-head\";\nimport {\n readCaptureFlushCounters,\n readCaptureProducerCardinality,\n} from \"../shared/capture-perf\";\nimport type {\n CaptureProducerPerf,\n CaptureSourceViewportSample,\n ProjectionProducerTrigger,\n} from \"./types\";\n\nexport interface BuildProjectionCapturePerfInput {\n readonly flushStartedAt: number;\n readonly snapshotMs: number;\n readonly identityMs: number;\n readonly html: DomCapture | undefined;\n readonly head?: string;\n readonly fiberNodeCount: number;\n readonly changedNodeEstimate: number;\n readonly fixedWindowTimersOpened: number;\n readonly maxSimultaneousTimers: number;\n readonly flushIntervalMs: number | null;\n readonly rawMutationRecords: number;\n readonly rawStateRecords: number;\n readonly rawPortalRecords: number;\n readonly producerCandidateNodes?: number;\n readonly producerVisitedNodes?: number;\n readonly candidateTargetsBeforeCoalescing: number;\n readonly candidateTargetsAfterCoalescing: number;\n readonly semanticDiscoveryNodesVisited?: number;\n readonly rootsPerBatch: number;\n readonly fullSnapshotReason: string | null;\n readonly triggerReasons?: readonly ProjectionProducerTrigger[];\n readonly sourceViewportSamples?: readonly CaptureSourceViewportSample[];\n /** Closed-projection serializers can provide their already-known totals\n * without constructing a legacy DomCapture solely for instrumentation. */\n readonly htmlChars?: number;\n readonly domNodesSerialized?: number;\n readonly semanticNodesSerialized?: number;\n readonly annotationTargetsSerialized?: number;\n readonly stateTargetsSerialized?: number;\n readonly portalTargetsSerialized?: number;\n readonly observedFileEntries?: number;\n}\n\n/**\n * Assemble the producer receipt exclusively from facts already collected by\n * the real capture. This function performs no discovery traversal and no\n * destination diagnostic read.\n */\nexport function buildProjectionCapturePerf(\n input: BuildProjectionCapturePerfInput,\n): CaptureProducerPerf {\n const flushCounters = readCaptureFlushCounters();\n const cardinality = readCaptureProducerCardinality();\n const headCardinality = getHeadTracker().readPerfSnapshot();\n let htmlChars = input.html?.dom.html.length ?? 0;\n for (const portal of input.html?.portals ?? []) {\n htmlChars += portal.html.length;\n }\n\n return {\n flushStartedAt: input.flushStartedAt,\n flushMs: Date.now() - input.flushStartedAt,\n snapshotMs: input.snapshotMs,\n identityMs: input.identityMs,\n identityNodesVisited: flushCounters.identityNodesVisited,\n sourceVersionDomScanNodes: flushCounters.sourceVersionDomScanNodes,\n sourceVersionFiberSerializeNodes:\n flushCounters.sourceVersionFiberSerializeNodes,\n sourceVersionFiberReductionNodes:\n flushCounters.sourceVersionFiberReductionNodes,\n sourceVersionFallbackScanNodes:\n flushCounters.sourceVersionFallbackScanNodes,\n sourceVersionScanNodes:\n flushCounters.sourceVersionDomScanNodes +\n flushCounters.sourceVersionFiberSerializeNodes +\n flushCounters.sourceVersionFiberReductionNodes +\n flushCounters.sourceVersionFallbackScanNodes,\n styleReadCount: flushCounters.styleReadCount,\n htmlChars: input.htmlChars ?? htmlChars,\n headChars: input.head?.length ?? 0,\n fiberNodeCount: input.fiberNodeCount,\n changedNodeEstimate: input.changedNodeEstimate,\n ...cardinality,\n headObservers: headCardinality.observers,\n headSubscriptions: headCardinality.subscriptions,\n fixedWindowTimersOpened: input.fixedWindowTimersOpened,\n maxSimultaneousTimers: input.maxSimultaneousTimers,\n flushIntervalMs: input.flushIntervalMs,\n rawMutationRecords: input.rawMutationRecords,\n rawStateRecords: input.rawStateRecords,\n rawPortalRecords: input.rawPortalRecords,\n producerCandidateNodes:\n input.producerCandidateNodes ?? input.candidateTargetsBeforeCoalescing,\n producerVisitedNodes:\n input.producerVisitedNodes ?? input.candidateTargetsAfterCoalescing,\n candidateTargetsBeforeCoalescing: input.candidateTargetsBeforeCoalescing,\n candidateTargetsAfterCoalescing: input.candidateTargetsAfterCoalescing,\n semanticDiscoveryNodesVisited: input.semanticDiscoveryNodesVisited ?? 0,\n domNodesSerialized: input.domNodesSerialized ?? null,\n semanticNodesSerialized:\n input.semanticNodesSerialized ?? input.fiberNodeCount,\n annotationTargetsSerialized:\n input.annotationTargetsSerialized ??\n input.html?.declared.containedAnchors.length ??\n 0,\n stateTargetsSerialized:\n input.stateTargetsSerialized ?? input.html?.states.length ?? 0,\n portalTargetsSerialized:\n input.portalTargetsSerialized ?? input.html?.portals?.length ?? 0,\n headSerializations: input.head === undefined ? 0 : 1,\n observedFileEntries:\n input.observedFileEntries ??\n Object.keys(input.html?.declared.observedVersions ?? {}).length,\n batchesEmitted: 1,\n rootsPerBatch: input.rootsPerBatch,\n fullSnapshotReason: input.fullSnapshotReason,\n ...(input.triggerReasons === undefined\n ? {}\n : { triggerReasons: input.triggerReasons }),\n ...(input.sourceViewportSamples === undefined\n ? {}\n : { sourceViewportSamples: input.sourceViewportSamples }),\n };\n}\n","import { capturePortalCoordinateSpace } from \"./watch-portal\";\n\n/** Source viewport facts for a component cropped out of a shared host page. */\nexport interface ProjectionRootCoordinates {\n readonly left: number;\n readonly top: number;\n readonly width: number;\n readonly height: number;\n /** Root origin in a transformed body/html fixed-position containing block.\n * Absent for the ordinary viewport and for older producers. */\n readonly layoutLeft?: number;\n readonly layoutTop?: number;\n}\n\n/** Attribute patches are understood by released clients. A new patch domain\n * would be rejected by their exhaustive wire validators. */\nexport const ROOT_COORDINATES_ATTRIBUTE = \"data-projection-root-coordinates\";\nexport const PROJECTION_ROOT_FRAME_ATTR = \"data-projection-source-viewport\";\n\nexport function parseRootCoordinates(\n value: string | null | undefined,\n): ProjectionRootCoordinates | undefined {\n if (!value) return;\n try {\n const result = JSON.parse(value);\n if (\n !result ||\n ![\"left\", \"top\", \"width\", \"height\"].every(\n (key) =>\n typeof result[key] === \"number\" && Number.isFinite(result[key]),\n ) ||\n result.width <= 0 ||\n result.height <= 0\n )\n return;\n if (\n (result.layoutLeft !== undefined || result.layoutTop !== undefined) &&\n !(\n typeof result.layoutLeft === \"number\" &&\n Number.isFinite(result.layoutLeft) &&\n typeof result.layoutTop === \"number\" &&\n Number.isFinite(result.layoutTop)\n )\n )\n return;\n return result;\n } catch {\n return;\n }\n}\n\nexport function captureRootCoordinates(\n root: Element,\n portals: Iterable<Element> = [],\n): ProjectionRootCoordinates | undefined {\n const doc = root.ownerDocument,\n view = doc.defaultView;\n if (!view || root === doc.body || root === doc.documentElement) return;\n // A viewport carrier can preserve an existing portal stacking context, but\n // must not invent one around a static portal whose children interleave with\n // the component. Keep the released geometry in that unsupported case.\n for (const portal of portals) {\n const css = view.getComputedStyle(portal);\n if (\n css.position === \"fixed\" ||\n css.position === \"sticky\" ||\n (css.position &&\n css.position !== \"static\" &&\n css.zIndex &&\n css.zIndex !== \"auto\")\n )\n continue;\n if (capturePortalCoordinateSpace(root, portal)?.origin === \"viewport\")\n return;\n }\n const rect = root.getBoundingClientRect();\n if (!rect.width || !rect.height) return;\n const containingBlock = [doc.body, doc.documentElement].find((element) => {\n if (!element) return false;\n const css = view.getComputedStyle(element);\n const active = (value: string) => Boolean(value && value !== \"none\");\n return (\n active(css.transform) ||\n active(css.translate) ||\n active(css.rotate) ||\n active(css.scale) ||\n active(css.perspective) ||\n active(css.filter) ||\n active(css.backdropFilter) ||\n /layout|paint|strict|content/.test(css.contain) ||\n /transform|perspective|filter/.test(css.willChange)\n );\n });\n let layout: { layoutLeft: number; layoutTop: number } | undefined;\n if (containingBlock) {\n let element = root as HTMLElement | null,\n left = 0,\n top = 0;\n while (element && element !== containingBlock) {\n left += element.offsetLeft;\n top += element.offsetTop;\n element = element.offsetParent as HTMLElement | null;\n }\n for (\n let parent = root.parentElement;\n parent && parent !== containingBlock;\n parent = parent.parentElement\n ) {\n left -= parent.scrollLeft;\n top -= parent.scrollTop;\n }\n if (\n element === containingBlock &&\n Number.isFinite(left) &&\n Number.isFinite(top)\n )\n layout = { layoutLeft: left, layoutTop: top };\n }\n return {\n left: rect.left,\n top: rect.top,\n width: containingBlock?.clientWidth || view.innerWidth,\n height: containingBlock?.clientHeight || view.innerHeight,\n ...layout,\n };\n}\n\nconst frames = new WeakMap<\n Element,\n {\n wrapper: HTMLElement;\n position: string;\n left: string;\n top: string;\n pointerEvents: string;\n }\n>();\n\n/** Portals share the root's frame so the frame cannot isolate the root's\n * stacking contexts from its external siblings. */\nexport function projectionRootFrame(root: Element): HTMLElement | undefined {\n return frames.get(root)?.wrapper;\n}\n\n/** Resolve a viewport point in the fixed wrapper's actual containing block.\n * Measuring its unit axes also handles translated/scaled/skewed body/html\n * ancestors; their viewport offsets must not be applied a second time. */\nfunction positionFrame(\n wrapper: HTMLElement,\n root: Element,\n x: number,\n y: number,\n): void {\n wrapper.style.left = \"0px\";\n wrapper.style.top = \"0px\";\n const origin = root.getBoundingClientRect();\n wrapper.style.left = \"1px\";\n const horizontal = root.getBoundingClientRect();\n wrapper.style.left = \"0px\";\n wrapper.style.top = \"1px\";\n const vertical = root.getBoundingClientRect();\n const a = horizontal.left - origin.left,\n b = horizontal.top - origin.top;\n const c = vertical.left - origin.left,\n d = vertical.top - origin.top;\n const determinant = a * d - b * c;\n if (!Number.isFinite(determinant) || Math.abs(determinant) < 1e-8) {\n wrapper.style.left = \"0px\";\n wrapper.style.top = \"0px\";\n return;\n }\n const dx = x - origin.left,\n dy = y - origin.top;\n wrapper.style.left = `${(d * dx - c * dy) / determinant}px`;\n wrapper.style.top = `${(a * dy - b * dx) / determinant}px`;\n}\n\n/** One common source viewport surrounds the synthetic root AND its portals.\n * The inverse root offset preserves normal-flow content. Authored nodes keep\n * their parent relationships; portal bodies already have synthetic carriers. */\nexport function applyRootCoordinates(\n root: Element,\n coordinates: ProjectionRootCoordinates | undefined,\n): void {\n const doc = root.ownerDocument;\n if (root === doc.body || root === doc.documentElement) return;\n const style = (root as HTMLElement).style;\n if (!style) return;\n const target = root.getBoundingClientRect();\n let frame = frames.get(root);\n if (!coordinates) {\n if (frame) {\n frame.wrapper.replaceWith(...frame.wrapper.childNodes);\n style.position = frame.position;\n style.left = frame.left;\n style.top = frame.top;\n style.pointerEvents = frame.pointerEvents;\n frames.delete(root);\n }\n return;\n }\n if (!frame || root.parentElement !== frame.wrapper) {\n const wrapper = doc.createElement(\"div\");\n wrapper.setAttribute(PROJECTION_ROOT_FRAME_ATTR, \"\");\n frame = {\n wrapper,\n position: style.position,\n left: style.left,\n top: style.top,\n pointerEvents: style.pointerEvents,\n };\n root.before(wrapper);\n wrapper.append(root);\n frames.set(root, frame);\n }\n const { width, height } = coordinates;\n const left = coordinates.layoutLeft ?? coordinates.left;\n const top = coordinates.layoutTop ?? coordinates.top;\n frame.wrapper.style.cssText = `all:unset;position:fixed;width:${width}px;height:${height}px;transform:translate(0,0);pointer-events:none;color:inherit;font:inherit;`;\n style.position = \"relative\";\n style.left = \"0px\";\n style.top = \"0px\";\n positionFrame(frame.wrapper, root, target.left, target.top);\n // Subtract in the containing block's axes, rather than viewport axes. The\n // root's matching inverse displacement then cancels even under a transform.\n frame.wrapper.style.left = `${parseFloat(frame.wrapper.style.left) - left}px`;\n frame.wrapper.style.top = `${parseFloat(frame.wrapper.style.top) - top}px`;\n style.position = \"relative\";\n style.left = `${left}px`;\n style.top = `${top}px`;\n frame.wrapper.style.setProperty(\"pointer-events\", \"none\", \"important\");\n style.pointerEvents = frame.pointerEvents || \"auto\";\n}\n","/** The source document's own default text colour, carried on the mirrored\n * `<html>` with the full snapshot's root attributes. A mirror is forced onto\n * the embedding app's colour scheme to stay transparent, so its UA default\n * text colour says nothing about the source: a dark source document renders\n * white text that a light one renders black. Optional: a producer that\n * predates this sends nothing and the mirror keeps black. */\nexport const PROJECTION_ROOT_COLOR_ATTR = \"data-tempo-root-color\";\n\nexport function captureProjectionRootColor(\n documentElement: Element,\n): Record<string, string> {\n const color = documentElement.ownerDocument.defaultView\n ?.getComputedStyle(documentElement)\n .color.trim();\n return color ? { [PROJECTION_ROOT_COLOR_ATTR]: color } : {};\n}\n\n/** Only a computed colour is accepted: the attribute also arrives from\n * untrusted HTML documents and is written into a stylesheet. */\nexport function readProjectionRootColor(doc: Document): string | null {\n const color = doc.documentElement?.getAttribute(PROJECTION_ROOT_COLOR_ATTR);\n if (!color || color.length > 80) return null;\n return /^[a-z0-9-]+(\\([a-z0-9\\s.,%/+-]*\\))?$/i.test(color) ? color : null;\n}\n","import {\n captureRootCoordinates,\n type ProjectionRootCoordinates,\n} from \"../html/root-coordinates\";\nimport { captureAttributes, removeScriptTags } from \"../html/capture\";\nimport {\n cloneProjectionDom,\n DOM_ID_ATTR,\n ensureProjectionDomId,\n PROJECTION_ROOT_ATTRIBUTE,\n projectedElements,\n syncProjectionDomIdsToClone,\n underForeignProjectionRoot,\n} from \"../html/watch-dom\";\nimport {\n capturePortalCoordinateSpace,\n PORTAL_ID_ATTR,\n} from \"../html/watch-portal\";\nimport { captureProjectionRootColor } from \"../root-color\";\nimport { cssEscape } from \"./css-escape\";\nimport type { ProjectionLayerAdapter } from \"./projection-layer-adapter\";\nimport type { ProjectionLayerRootSnapshot } from \"./projection-layer-snapshot\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\nimport {\n captureProjectionAncestorIds,\n captureRegionWithoutAnnotations,\n PROJECTION_ROOT_TARGET_ID,\n type ProjectionPortalPatch,\n type ProjectionStatePatch,\n stripSourceAnnotations,\n} from \"./projection-patch\";\n\nexport interface ProjectionFullDomSnapshot {\n readonly coordinates?: ProjectionRootCoordinates;\n /** Children of the watched source wrapper; the wrapper is host plumbing. */\n readonly html: string;\n /** Optional authored attributes for sources whose wrapper is content (for\n * example a static HTML `<body>`), rather than host-only plumbing. */\n readonly rootAttributes?: Readonly<Record<string, string>>;\n /** The watched root's seeded id. Root-level text and comment ids name\n * their parent `$projection-root:<rootDomId>`, and the destination, whose\n * container stands in for the root, learns that scope only from here.\n * Absent from an older producer, whose root text is unscoped, and when the\n * root has no id (it sits inside a contenteditable). */\n readonly rootDomId?: string;\n readonly documentElementAttributes: Readonly<Record<string, string>>;\n /** The source `<body>`'s authored attributes. Portals are mirrored into the\n * destination body, so its classes and data attributes are part of what they\n * render against. Absent for a source document with no body. */\n readonly bodyAttributes?: Readonly<Record<string, string>>;\n readonly baseUrl?: string;\n readonly state: readonly ProjectionStatePatch[];\n readonly portals: readonly ProjectionPortalPatch[];\n}\n\nexport interface ProjectionFullSnapshot {\n /** Files absent from this complete root result, at the evaluated source version.\n * Root-scoped evidence, never a document-wide module-only acknowledgment. */\n readonly absentFiles?: ProjectionObservedFileMap;\n readonly pointerEventsNone?: readonly string[];\n readonly dom: ProjectionFullDomSnapshot;\n readonly layers: ProjectionLayerRootSnapshot;\n readonly observedFiles: ProjectionObservedFileMap;\n}\n\nexport interface ProjectionFullSnapshotCapture {\n readonly snapshot: ProjectionFullSnapshot;\n readonly fiberNodesVisited: number;\n readonly semanticNodesSerialized: number;\n /** Distinct stamped elements the baseline covers. Producer-local: the\n * destination is never told this and never validates against it. */\n readonly hostDomIdCount: number;\n}\n\nexport interface CaptureProjectionFullSnapshotOptions {\n readonly root: Element;\n readonly layerAdapter: ProjectionLayerAdapter;\n readonly fiberTarget?: Element | null;\n readonly portals?: readonly Element[];\n}\n\n/**\n * One self-contained initial/reload/recovery baseline. Every O(N) operation is\n * performed in this single host pass family; ordinary updates never call it.\n * Capture never refuses: whatever the source document looks like — duplicate\n * ids, unstampable elements — is exactly what the destination should show.\n */\nexport function captureProjectionFullSnapshot(\n options: CaptureProjectionFullSnapshotOptions,\n): ProjectionFullSnapshotCapture {\n const fiberTarget = options.fiberTarget ?? options.root.firstElementChild;\n const observedFiles = new ProjectionObservedFileAccumulator();\n const { dom, hostDomIdCount } = captureFullDom(\n options.root,\n options.portals ?? [],\n observedFiles,\n );\n const pointerEventsNone: string[] = [];\n for (const element of projectedElements(options.root)) {\n const id = ensureProjectionDomId(element);\n if (\n id &&\n element.ownerDocument.defaultView?.getComputedStyle(element)\n .pointerEvents === \"none\"\n ) {\n pointerEventsNone.push(id);\n }\n }\n const layerCapture = options.layerAdapter.captureFull(\n options.root,\n fiberTarget,\n {},\n );\n const layers = layerCapture.snapshot;\n observedFiles.merge(layers.observedFiles);\n const completeObservedFileSnapshot = observedFiles.snapshot();\n\n return {\n snapshot: {\n dom,\n layers,\n observedFiles: completeObservedFileSnapshot,\n ...(pointerEventsNone.length > 0 ? { pointerEventsNone } : {}),\n },\n fiberNodesVisited: layerCapture.fiberNodesVisited,\n semanticNodesSerialized: layerCapture.semanticNodesSerialized,\n hostDomIdCount,\n };\n}\n\nfunction captureFullDom(\n root: Element,\n portals: readonly Element[],\n observedFiles: ProjectionObservedFileAccumulator,\n): { dom: ProjectionFullDomSnapshot; hostDomIdCount: number } {\n // React can request a baseline before MutationObserver stamps fresh hosts.\n // Stamp the transported elements first so DOM and layer captures agree.\n for (const scope of [root, ...portals]) {\n for (const element of projectedElements(scope)) {\n ensureProjectionDomId(element);\n }\n }\n const clone = cloneProjectionDom(root);\n syncProjectionDomIdsToClone(root, clone);\n for (const script of clone.querySelectorAll(\"script\")) script.remove();\n // Producer-local, for the batch perf receipt only; never serialized.\n const hostDomIds = stripSourceAnnotations(clone, observedFiles, false);\n\n const portalPatches: ProjectionPortalPatch[] = [];\n for (const portal of portals) {\n if (!portal.isConnected) continue;\n const portalId = portal.getAttribute(PORTAL_ID_ATTR);\n if (!portalId) continue;\n const portalClone = cloneProjectionDom(portal);\n syncProjectionDomIdsToClone(portal, portalClone);\n for (const script of portalClone.querySelectorAll(\"script\"))\n script.remove();\n for (const domId of stripSourceAnnotations(\n portalClone,\n observedFiles,\n true,\n )) {\n hostDomIds.add(domId);\n }\n const coordinateSpace = capturePortalCoordinateSpace(root, portal);\n portalPatches.push({\n kind: \"replace\",\n portalId,\n html: removeScriptTags(portalClone.outerHTML),\n ...(coordinateSpace && { coordinateSpace }),\n });\n }\n\n const body = root.ownerDocument.body;\n const rootDomId = ensureProjectionDomId(root);\n const coordinates = captureRootCoordinates(root, portals);\n const dom: ProjectionFullDomSnapshot = {\n ...(coordinates ? { coordinates } : {}),\n html: removeScriptTags(clone.innerHTML),\n ...(rootDomId ? { rootDomId } : {}),\n documentElementAttributes: {\n ...captureAttributes(root.ownerDocument.documentElement),\n ...captureProjectionRootColor(root.ownerDocument.documentElement),\n },\n ...(body ? { bodyAttributes: captureAttributes(body) } : {}),\n baseUrl: root.ownerDocument.baseURI,\n state: collectFullRuntimeState(root, portals),\n portals: portalPatches,\n };\n return { dom, hostDomIdCount: hostDomIds.size };\n}\n\nfunction collectFullRuntimeState(\n root: Element,\n portals: readonly Element[],\n): ProjectionStatePatch[] {\n const states: ProjectionStatePatch[] = [];\n for (const scope of [root, ...portals]) {\n for (const element of projectedElements(scope)) {\n // A foreign root's own watcher transports its scroll/form state. Reading\n // scroll offsets here forces Chromium to lay out retained hidden trees\n // even though this snapshot only carries their empty boundary element.\n if (element !== scope && element.hasAttribute(PROJECTION_ROOT_ATTRIBUTE))\n continue;\n const targetId = ensureProjectionDomId(element);\n if (!targetId) continue;\n if (element.scrollTop !== 0 || element.scrollLeft !== 0) {\n states.push({\n targetId,\n kind: \"scroll\",\n scrollTop: element.scrollTop,\n scrollLeft: element.scrollLeft,\n });\n }\n if (element instanceof HTMLInputElement) {\n if (element.type === \"checkbox\" || element.type === \"radio\") {\n if (element.checked !== element.defaultChecked) {\n states.push({\n targetId,\n kind: \"checked\",\n checked: element.checked,\n });\n }\n } else if (element.value !== element.defaultValue) {\n states.push({\n targetId,\n kind: \"value\",\n value: element.value,\n selectionStart: element.selectionStart,\n selectionEnd: element.selectionEnd,\n });\n }\n } else if (\n element instanceof HTMLTextAreaElement &&\n element.value !== element.defaultValue\n ) {\n states.push({\n targetId,\n kind: \"value\",\n value: element.value,\n selectionStart: element.selectionStart,\n selectionEnd: element.selectionEnd,\n });\n } else if (element instanceof HTMLSelectElement) {\n const selectedIndices: number[] = [];\n let changed = false;\n for (\n let optionIndex = 0;\n optionIndex < element.options.length;\n optionIndex += 1\n ) {\n const option = element.options[optionIndex];\n if (!option) continue;\n if (option.selected) selectedIndices.push(optionIndex);\n if (option.selected !== option.defaultSelected) changed = true;\n }\n if (changed)\n states.push({ targetId, kind: \"selected\", selectedIndices });\n }\n }\n }\n return states;\n}\n\n/** One element's exact children-region final state. */\nexport interface ProjectionRegionCapture {\n readonly targetId: string;\n readonly html: string;\n /** Current parent-and-up id chain, for continuing the repair ladder. */\n readonly ancestorIds: readonly string[];\n readonly observedFiles: ProjectionObservedFileMap;\n readonly state: readonly ProjectionStatePatch[];\n}\n\n/**\n * Capture one element's region on demand for the destination's scoped repair\n * ladder. Same capture routine as the hot patch builder: scripts stripped,\n * source attributes stripped from the HTML, descendant runtime state\n * included so a morphed repair isn't state-bare. Null when the id no longer\n * names a live element — the destination then climbs further up its known\n * chain.\n */\nexport function captureProjectionRegion(\n root: Element,\n targetId: string,\n portals: readonly Element[] = [],\n): ProjectionRegionCapture | null {\n const element = resolveRegionElement(root, targetId, portals);\n if (!element) return null;\n const observedFiles = new ProjectionObservedFileAccumulator();\n const captured = captureRegionWithoutAnnotations(element, observedFiles);\n return {\n targetId,\n html: captured.html,\n ancestorIds:\n element === root ? [] : captureProjectionAncestorIds(root, element),\n observedFiles: observedFiles.snapshot(),\n state: collectFullRuntimeState(element, []),\n };\n}\n\n/** Ingress validation for the untrusted repair-response wire value. */\nexport function isProjectionRegionCapture(\n value: unknown,\n): value is ProjectionRegionCapture {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const record = value as Record<string, unknown>;\n return (\n typeof record.targetId === \"string\" &&\n typeof record.html === \"string\" &&\n Array.isArray(record.ancestorIds) &&\n record.ancestorIds.every((id) => typeof id === \"string\") &&\n typeof record.observedFiles === \"object\" &&\n record.observedFiles !== null &&\n !Array.isArray(record.observedFiles) &&\n Array.isArray(record.state)\n );\n}\n\nexport function resolveRegionElement(\n root: Element,\n targetId: string,\n portals: readonly Element[],\n): Element | null {\n if (targetId === PROJECTION_ROOT_TARGET_ID) return root;\n const selector = `[${DOM_ID_ATTR}=\"${cssEscape(targetId)}\"]`;\n const scopes = [root, ...portals.filter((portal) => portal.isConnected)];\n for (const scope of scopes) {\n const found = scope.matches(selector)\n ? scope\n : scope.querySelector(selector);\n if (found && !underForeignProjectionRoot(found, scope)) return found;\n }\n return null;\n}\n","import { FiberTag } from \"../fiber/react-types\";\nimport {\n ensureProjectionDomId,\n nextProjectionId,\n PROJECTION_ROOT_ATTRIBUTE,\n} from \"../html/watch-dom\";\nimport {\n captureProjectionDomLayerProps,\n serializeDomLayerNode,\n type ProjectionDomLayerSerializer,\n} from \"./projection-dom-layers\";\nimport {\n readAstroMarker,\n trackAstroSources,\n type AstroBoundaryRecord,\n} from \"./projection-astro-metadata\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\nimport type {\n ProjectionLayerNode,\n ProjectionLayerProps,\n ProjectionLayerRootSnapshot,\n} from \"./projection-layer-snapshot\";\n\nexport const ASTRO_LAYER_ROOT_ID = \"astro:$projection-root\";\n\n/** DOM geometry with server component boundaries. No wrapper elements or global component stack. */\nexport function createProjectionAstroLayerSerializer(\n island?: (\n element: Element,\n files: ProjectionObservedFileMap,\n ) => ProjectionLayerRootSnapshot | null,\n): ProjectionDomLayerSerializer {\n const ids = new WeakMap<object, string>();\n const id = (value: object) => {\n let found = ids.get(value);\n if (!found) {\n found = nextProjectionId();\n ids.set(value, found);\n }\n return found;\n };\n const domOwners = new Map<string, Element>();\n const identity = {\n id: new WeakMap<Element, string>(),\n layerIdForElement: (_root: Element, element: Element) => id(element),\n bindableDomIdForElement(_root: Element, element: Element) {\n const value = ensureProjectionDomId(element);\n if (!value) return null;\n if (!domOwners.has(value)) domOwners.set(value, element);\n return domOwners.get(value) === element ? value : null;\n },\n };\n function session(root: Element, files: ProjectionObservedFileMap) {\n const tracking = trackAstroSources(root.ownerDocument);\n const observed = new ProjectionObservedFileAccumulator();\n observed.merge(files);\n for (const receipt of tracking.moduleSources())\n observed.add(receipt.filepath, receipt.modifiedTs, receipt.sourceVersion);\n const props = (element: Element) => {\n const live: Record<string, unknown> = {\n ...captureProjectionDomLayerProps(element),\n };\n // Native Astro has no Fiber props. Attribute edits must come back in\n // the semantic lane as well as the DOM lane, otherwise history sees a\n // missing value after reload and refuses its own inverse as stale.\n for (const { name, value } of element.attributes) {\n if (\n name === \"class\" ||\n name === \"style\" ||\n name === \"data-dom-id\" ||\n name === \"data-host-layer-id\" ||\n name.startsWith(\"data-tempo-\")\n )\n continue;\n live[name] = value;\n }\n const safe = tracking.owns(element);\n const result = safe\n ? live\n : Object.fromEntries(\n Object.entries(live ?? {}).filter(\n ([key]) =>\n !key.startsWith(\"data-tempo-\") || key === \"data-tempo-locked\",\n ),\n );\n observed.addLayerProps(result);\n return result;\n };\n const component = (\n node: Node,\n boundary: AstroBoundaryRecord,\n children: ProjectionLayerNode[],\n ): ProjectionLayerNode => {\n const source = boundary.source;\n observed.add(source.filepath, source.modifiedTs, source.sourceVersion);\n if (boundary.definition)\n observed.add(\n boundary.definition.filepath,\n boundary.definition.modifiedTs,\n boundary.definition.sourceVersion,\n );\n return {\n kind: \"component\",\n runtime: \"astro\",\n id: id(node),\n key: null,\n name: source.name,\n domId: null,\n elementTag: null,\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.FunctionComponent,\n name: source.name,\n id: id(node),\n },\n },\n props: {\n // Inspector edits are represented as JSON prop fields in the edit\n // tree. Publish the compiler's literal callsite values after each\n // reload so history can validate its inverse against fresh facts.\n ...Object.fromEntries(\n Object.entries(source.literalProps ?? {}).map(([name, value]) => [\n `data-tempo-component-prop-${name}`,\n JSON.stringify(value),\n ]),\n ),\n \"data-tempo-filepath\": source.filepath,\n \"data-tempo-position\": source.position,\n \"data-tempo-modifiedts\": source.modifiedTs,\n \"data-tempo-source-version\": source.sourceVersion,\n ...(source.expressions !== undefined\n ? { \"data-tempo-expr\": source.expressions }\n : {}),\n ...(boundary.definition\n ? {\n \"data-tempo-component-reference\": JSON.stringify([\n \"import\",\n boundary.definition.filepath,\n boundary.definition.exportName ?? \"default\",\n ]),\n }\n : {}),\n },\n children,\n };\n };\n const list = (children: Node[]): ProjectionLayerNode[] => {\n const output: ProjectionLayerNode[] = [];\n const endings = new Map<string, number>();\n for (const [index, node] of children.entries()) {\n const marker = readAstroMarker(node);\n if (marker?.kind === \"e\" && tracking.owns(node))\n endings.set(marker.value.occurrence, index);\n }\n for (let at = 0; at < children.length; at++) {\n const node = children[at]!;\n const marker = readAstroMarker(node);\n if (marker) {\n if (marker.kind === \"b\" && tracking.owns(node)) {\n const end = endings.get(marker.value.occurrence) ?? -1;\n if (end > at) {\n output.push(\n component(\n node,\n marker.value,\n list(children.slice(at + 1, end)),\n ),\n );\n at = end;\n }\n }\n continue;\n }\n if (node instanceof Element) {\n if (\n node.localName === \"script\" ||\n node.hasAttribute(PROJECTION_ROOT_ATTRIBUTE)\n )\n continue;\n const tree = host(node);\n if (tree) output.push(tree);\n } else {\n const tree = serializeDomLayerNode(root, node, identity);\n if (tree) output.push(tree);\n }\n }\n return output;\n };\n const host = (element: Element): ProjectionLayerNode | null => {\n const embedded =\n element.localName === \"astro-island\"\n ? island?.(element, observed.snapshot())\n : null;\n if (embedded) observed.merge(embedded.observedFiles);\n const embeddedNodes =\n embedded?.semantic.kind === \"scope\"\n ? embedded.semantic.fragment.children\n : embedded?.semantic.kind === \"layers\" && embedded.semantic.tree\n ? [embedded.semantic.tree]\n : null;\n const tree = serializeDomLayerNode(\n root,\n element,\n identity,\n undefined,\n embeddedNodes ?? list([...element.childNodes]),\n );\n return tree?.kind === \"host\"\n ? { ...tree, runtime: \"astro\", props: props(element) }\n : tree;\n };\n const rootTree = (): ProjectionLayerNode => ({\n kind: \"fragment\",\n runtime: \"astro\",\n id: id(root),\n key: null,\n name: \"astro-root\",\n domId: null,\n elementTag: null,\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.HostRoot,\n name: \"astro-root\",\n id: ASTRO_LAYER_ROOT_ID,\n },\n },\n props: props(root),\n children: list([...root.childNodes]),\n });\n return { props, host, rootTree, observed };\n }\n return {\n serializeRoot(root, files = {}): ProjectionLayerRootSnapshot {\n const pass = session(root, files);\n const tree = pass.rootTree();\n return {\n semantic: { kind: \"layers\", tree },\n observedFiles: pass.observed.snapshot(),\n };\n },\n capturePatch(root, targets, files = {}) {\n const pass = session(root, files);\n const islandRoot = (target: Element) =>\n target.closest(\"astro-island\") ?? target;\n const structuralCandidates = [\n ...targets.structural.map(islandRoot),\n ...targets.metadata\n .filter((target) => target.closest(\"astro-island\"))\n .map(islandRoot),\n ];\n const structural = [...new Set(structuralCandidates)].filter(\n (target) =>\n (target === root || root.contains(target)) &&\n !structuralCandidates.some(\n (parent) => parent !== target && parent.contains(target),\n ),\n );\n const regions = structural.map((target) => ({\n targetFiberId: target === root ? ASTRO_LAYER_ROOT_ID : id(target),\n targetId:\n target === root\n ? id(root)\n : (identity.bindableDomIdForElement(root, target) ?? id(target)),\n tree: target === root ? pass.rootTree() : pass.host(target),\n observedFiles: pass.observed.snapshot(),\n }));\n const metadata = targets.metadata\n .filter(\n (target) =>\n target !== root &&\n root.contains(target) &&\n !structural.some(\n (parent) => parent === target || parent.contains(target),\n ),\n )\n .map((target) => ({\n targetFiberId: id(target),\n targetId:\n identity.bindableDomIdForElement(root, target) ?? id(target),\n props: pass.props(target),\n }));\n return regions.length || metadata.length\n ? { regions, metadata }\n : undefined;\n },\n };\n}\n","/**\n * Convert an `EnrichedFiberNode` (live capture from the combined watcher)\n * into a `SerializedFiber`-shaped tree that downstream JSX reconstruction\n * tooling (e.g. `@modules/codebase-editor`'s `reconstructJsxFromFiber`)\n * consumes.\n *\n * The combined watcher's default `sanitizeValue` already runs on the source\n * iframe and loses some type information by replacing non-JSON values with\n * marker strings (`\"[Function]\"`, `\"[Element:div]\"`, `\"[ReactElement]\"`,\n * etc.). This converter detects those markers on the parent side and\n * re-encodes them as `{ __type: \"unsupported\", reason }` so the\n * reconstructor can flag them as blockers instead of emitting them as bogus\n * string literals.\n *\n * The output shape is structurally compatible with\n * `@modules/codebase-editor`'s `SerializedFiber` — no direct dependency to\n * keep the module standalone.\n */\nimport { FiberTag, type FiberTagValue } from \"../fiber/react-types\";\nimport { cssEscape } from \"./css-escape\";\nimport type { EnrichedFiberNode } from \"./types\";\n\n// ── Structural mirror of @modules/codebase-editor's SerializedFiber ───\n// Kept type-compatible (string union for tag, __type marker for unsupported\n// values) so callers can pass the result directly to `reconstructJsxFromFiber`\n// without conversion. Duplication is the explicit cost of keeping\n// iframe-projection free of codebase-editor as a dependency.\n\nexport type DetachJsonPrimitive = string | number | boolean | null;\nexport type DetachJsonValue =\n | DetachJsonPrimitive\n | DetachJsonValue[]\n | { [key: string]: DetachJsonValue };\n\nexport type DetachReactElementReference = {\n __type: \"react-element\";\n fiber_id: string;\n};\n\nexport type DetachUnsupportedValue = {\n __type: \"unsupported\";\n reason: string;\n /** Structured kind of the unserializable value, when known. `\"function\"`\n * marks event handlers/callbacks — behavior-only props that fiber\n * reconstruction stubs with a no-op instead of refusing the transfer\n * (mirrors `codebase-editor`'s `UnsupportedSerializableValue.value_type`). */\n value_type?: \"function\";\n};\n\nexport type DetachSerializableValue =\n | DetachJsonValue\n | DetachReactElementReference\n | DetachUnsupportedValue\n | DetachSerializableValue[]\n | { [key: string]: DetachSerializableValue };\n\nexport type DetachFiberTag =\n | \"host\"\n | \"function\"\n | \"class\"\n | \"text\"\n | \"fragment\"\n | \"portal\"\n | \"memo\"\n | \"forward-ref\";\n\nexport interface DetachSerializedFiber {\n fiber_id: string;\n name: string;\n tag: DetachFiberTag | string;\n owner_fiber_id: string | null;\n key?: string | null;\n has_context_dependencies?: boolean;\n props: Record<string, DetachSerializableValue>;\n children: DetachSerializedFiber[];\n source?: {\n file: string;\n position: number;\n };\n}\n\nexport interface EnrichedNodeToSerializedFiberOptions {\n /** When set, every fiber that carries `data-tempo-filepath` +\n * `data-tempo-position` annotations gets its `source` field populated.\n * This is what enables detach-one-level: the orchestrator walks the\n * output tree, follows each descendant component's `source.file` to\n * parse that file's imports, and resolves cross-file identifier\n * references in the rendered subtree (e.g. `<Pill />` inside a\n * `<Wrapper />` whose `Pill` import lives in Wrapper.tsx, not the\n * call-site App.tsx). Without this, descendant components inline as\n * their host JSX instead of staying as JSX tags. */\n preserveSourceAnnotations?: boolean;\n /** Optional iframe document — used to recover text-node children of host\n * elements that the upstream fiber capture filtered out. The combined\n * watcher's default `fiberTags` filter drops HostText so the layer tree\n * stays manageable; for detach we still need text content, so we\n * walk the host element's DOM children and synthesize text fibers from\n * every direct `Text` node. Without this, `<div>Hello</div>` reconstructs\n * as `<div />` and the text disappears. */\n iframeDocument?: Document | null;\n}\n\nexport function enrichedNodeToSerializedFiber(\n node: EnrichedFiberNode,\n options: EnrichedNodeToSerializedFiberOptions = {},\n): DetachSerializedFiber {\n return convertNode(node, null, options);\n}\n\nfunction convertNode(\n node: EnrichedFiberNode,\n ownerFiberId: string | null,\n options: EnrichedNodeToSerializedFiberOptions,\n): DetachSerializedFiber {\n const tag = detachTagFromFiberTag(node.tag);\n const name = node.name;\n const ownerId = node.fiberId;\n\n const props = node.props ? detachPropsFromSanitized(node.props) : {};\n\n const children: DetachSerializedFiber[] = node.children.map((child) =>\n convertNode(child, ownerId, options),\n );\n\n // Recover host-text leaves that the combined watcher's `fiberTags` filter\n // drops. The fiber tree only reports HostComponent/FunctionComponent/...,\n // so a `<div>Hello</div>` arrives as a host fiber with `children: []`.\n // Walk the live DOM under the host's `domId` and synthesize a Text-tagged\n // child fiber for each direct Text node — the reconstructor renders these\n // as escaped JSX text content.\n if (\n tag === \"host\" &&\n children.length === 0 &&\n node.domId &&\n options.iframeDocument\n ) {\n const element = options.iframeDocument.querySelector(\n `[data-dom-id=\"${cssEscape(node.domId)}\"]`,\n );\n if (element) {\n let textIndex = 0;\n for (const childNode of Array.from(element.childNodes)) {\n if (childNode.nodeType === 3 /* Text */) {\n const text = childNode.textContent ?? \"\";\n if (text.length === 0) continue;\n children.push({\n fiber_id: `${node.fiberId}:text-${textIndex++}`,\n name: \"#text\",\n tag: \"text\",\n owner_fiber_id: ownerId,\n props: { text },\n children: [],\n });\n }\n }\n }\n }\n\n const result: DetachSerializedFiber = {\n fiber_id: node.fiberId,\n name,\n tag,\n owner_fiber_id: ownerFiberId,\n props,\n children,\n };\n if (node.hasContextDependencies) {\n result.has_context_dependencies = true;\n }\n\n if (options.preserveSourceAnnotations) {\n const source = detachSourceFromProps(node.props);\n if (source) result.source = source;\n }\n\n return result;\n}\n\nexport function detachTagFromFiberTag(\n tag: FiberTagValue,\n): DetachFiberTag | string {\n switch (tag) {\n case FiberTag.HostComponent:\n return \"host\";\n case FiberTag.HostText:\n return \"text\";\n case FiberTag.FunctionComponent:\n case FiberTag.IndeterminateComponent:\n return \"function\";\n case FiberTag.ClassComponent:\n return \"class\";\n case FiberTag.Fragment:\n return \"fragment\";\n case FiberTag.HostPortal:\n return \"portal\";\n case FiberTag.MemoComponent:\n case FiberTag.SimpleMemoComponent:\n return \"memo\";\n case FiberTag.ForwardRef:\n return \"forward-ref\";\n default:\n return String(tag);\n }\n}\n\nconst SANITIZED_MARKER_PATTERNS: {\n match: RegExp;\n reason: (raw: string) => string;\n value_type?: DetachUnsupportedValue[\"value_type\"];\n}[] = [\n {\n match: /^\\[Function\\]$/,\n reason: () => \"Functions cannot be serialized to JSX\",\n value_type: \"function\",\n },\n {\n match: /^\\[Symbol:.*\\]$/,\n reason: (raw) => `Symbols cannot be serialized to JSX: ${raw}`,\n },\n {\n match: /^\\[Element:.*\\]$/,\n reason: (raw) => `DOM elements cannot be serialized to JSX: ${raw}`,\n },\n {\n match: /^\\[Node:.*\\]$/,\n reason: (raw) => `DOM nodes cannot be serialized to JSX: ${raw}`,\n },\n {\n match: /^\\[Object\\]$/,\n reason: () => \"Object could not be JSON-serialized\",\n },\n {\n match: /^\\[Array\\(\\d+\\)\\]$/,\n reason: (raw) => `Large array cannot be serialized: ${raw}`,\n },\n {\n match: /^\\[ReactElement\\]$/,\n reason: () => \"Inline React elements in props cannot be reconstructed\",\n },\n];\n\nfunction classifyMaybeMarker(raw: string): DetachUnsupportedValue | null {\n for (const { match, reason, value_type } of SANITIZED_MARKER_PATTERNS) {\n if (match.test(raw)) {\n const marker: DetachUnsupportedValue = {\n __type: \"unsupported\",\n reason: reason(raw),\n };\n if (value_type) marker.value_type = value_type;\n return marker;\n }\n }\n return null;\n}\n\nconst TEMPO_DATA_PROP_PREFIX = \"data-tempo-\";\n\nexport function detachPropsFromSanitized(\n source: Record<string, unknown>,\n): Record<string, DetachSerializableValue> {\n const out: Record<string, DetachSerializableValue> = {};\n for (const [key, value] of Object.entries(source)) {\n if (key === \"children\") continue;\n // `data-tempo-*` props are Tempo's source-annotation channel and aren't\n // part of the user's authored JSX; stripping them keeps detached output\n // clean (the canvas will re-stamp them on the next HMR cycle).\n if (key.startsWith(TEMPO_DATA_PROP_PREFIX)) continue;\n out[key] = convertValue(value);\n }\n return out;\n}\n\nfunction convertValue(value: unknown): DetachSerializableValue {\n if (value === null || value === undefined) return null;\n if (typeof value === \"string\") {\n const marker = classifyMaybeMarker(value);\n if (marker) return marker;\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") return value;\n\n if (Array.isArray(value)) {\n return value.map((entry) => convertValue(entry));\n }\n\n if (typeof value === \"object\") {\n const out: Record<string, DetachSerializableValue> = {};\n for (const [key, entry] of Object.entries(\n value as Record<string, unknown>,\n )) {\n out[key] = convertValue(entry);\n }\n return out;\n }\n\n // Functions, symbols, etc. shouldn't survive sanitizeValue on the source\n // side, but guard defensively so the converter never produces a non-JSON\n // primitive type.\n return {\n __type: \"unsupported\",\n reason: `Unsupported runtime type: ${typeof value}`,\n };\n}\n\nexport function detachSourceFromProps(\n props: Record<string, unknown> | undefined,\n): { file: string; position: number } | null {\n if (!props) return null;\n const file = props[\"data-tempo-filepath\"];\n const position = props[\"data-tempo-position\"];\n if (typeof file !== \"string\" || file.length === 0) return null;\n const pos = typeof position === \"number\" ? position : Number(position);\n if (!Number.isFinite(pos)) return null;\n return { file, position: pos };\n}\n","/**\n * Cold, operation-scoped React semantic capture.\n *\n * The hot projection stream intentionally carries only destination-ready\n * layer facts. Copy, duplicate, drag, and detach occasionally need runtime\n * props for one selected branch. This serializer performs that richer walk\n * only when one of those operations explicitly asks for it, and returns only\n * the selected Fiber subtree rather than retaining or transporting a full\n * document Fiber tree.\n */\n\nimport type { Fiber, FiberProps } from \"../fiber/react-types\";\nimport { FiberTag } from \"../fiber/react-types\";\nimport { getDisplayName, getProps, sanitizeProps } from \"../fiber/serialize\";\nimport {\n detachPropsFromSanitized,\n detachSourceFromProps,\n detachTagFromFiberTag,\n type DetachSerializedFiber,\n type DetachSerializableValue,\n} from \"./enriched-to-serialized-fiber\";\nimport { isProjectionLayerFiber } from \"./projection-layer-snapshot\";\n\nexport interface ProjectionSemanticFiberIdentity {\n /** Return the already-published identity without allocating a new one. */\n knownFiberId(fiber: Fiber): string | null;\n /** Allocate/recover the stable identity for a node inside the result. */\n fiberId(fiber: Fiber): string;\n}\n\n/** Structural guard used at transport boundaries. Runtime prop values are\n * already structured-cloned by the bridge, so the protocol only needs to pin\n * the closed tree envelope here. */\nexport function isProjectionSemanticSubtree(\n value: unknown,\n): value is DetachSerializedFiber {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const node = value as Record<string, unknown>;\n if (\n typeof node.fiber_id !== \"string\" ||\n typeof node.name !== \"string\" ||\n typeof node.tag !== \"string\" ||\n (node.owner_fiber_id !== null && typeof node.owner_fiber_id !== \"string\") ||\n !node.props ||\n typeof node.props !== \"object\" ||\n Array.isArray(node.props) ||\n !Array.isArray(node.children)\n ) {\n return false;\n }\n if (\n node.source !== undefined &&\n (!node.source ||\n typeof node.source !== \"object\" ||\n Array.isArray(node.source) ||\n typeof (node.source as Record<string, unknown>).file !== \"string\" ||\n typeof (node.source as Record<string, unknown>).position !== \"number\")\n ) {\n return false;\n }\n return node.children.every(isProjectionSemanticSubtree);\n}\n\n/**\n * Resolve one currently committed, previously published semantic node and\n * serialize only that node and its rendered descendants. Without\n * `descendants` it serializes the node alone, with no children: a reader of\n * one component's props must not pay for everything it renders.\n */\nexport function captureProjectionSemanticSubtree(\n committedRoot: Fiber,\n targetFiberId: string | { readonly mode: \"context\" },\n identity: ProjectionSemanticFiberIdentity,\n options: { readonly descendants?: boolean } = {},\n): (DetachSerializedFiber & { truncated?: boolean }) | null {\n if (typeof targetFiberId !== \"string\") {\n return captureSemanticSubtree(committedRoot);\n }\n const target = findCurrentFiberByPublishedId(\n committedRoot,\n targetFiberId,\n identity.knownFiberId,\n );\n if (!target || !isProjectionLayerFiber(target)) return null;\n return serializeIncludedFiber(\n target,\n null,\n identity,\n options.descendants !== false,\n );\n}\n\nfunction findCurrentFiberByPublishedId(\n root: Fiber,\n targetFiberId: string,\n knownFiberId: (fiber: Fiber) => string | null,\n): Fiber | null {\n if (knownFiberId(root) === targetFiberId) return root;\n for (let child = root.child; child; child = child.sibling) {\n const found = findCurrentFiberByPublishedId(\n child,\n targetFiberId,\n knownFiberId,\n );\n if (found) return found;\n }\n return null;\n}\n\nfunction serializeIncludedFiber(\n fiber: Fiber,\n ownerFiberId: string | null,\n identity: ProjectionSemanticFiberIdentity,\n descendants = true,\n): DetachSerializedFiber {\n const fiberId = identity.fiberId(fiber);\n const normalizedProps = normalizeTempoDataSet(getProps(fiber));\n const sanitized = sanitizeProps(normalizedProps) ?? {};\n const children = descendants\n ? serializeChildren(fiber, fiberId, identity)\n : [];\n // React omits a HostText Fiber for the common single-primitive-child fast\n // path (`<button>Save</button>`). `sanitizeProps` correctly removes the\n // structural `children` prop, so preserve that authored output as the same\n // synthetic text leaf the old DOM-assisted detach capture produced. This\n // stays local to the selected host node and avoids a document/tree query.\n if (\n descendants &&\n fiber.tag === FiberTag.HostComponent &&\n children.length === 0\n ) {\n const text = directPrimitiveChild(normalizedProps?.children);\n if (text !== null) {\n children.push({\n fiber_id: `${fiberId}:text-0`,\n name: \"#text\",\n tag: \"text\",\n owner_fiber_id: fiberId,\n props: { text },\n children: [],\n });\n }\n }\n const result: DetachSerializedFiber = {\n fiber_id: fiberId,\n name: getDisplayName(fiber),\n tag: detachTagFromFiberTag(fiber.tag),\n owner_fiber_id: ownerFiberId,\n props:\n fiber.tag === FiberTag.HostText\n ? { text: readHostText(fiber) }\n : detachPropsFromSanitized(sanitized),\n children,\n };\n if (fiber.key !== null) result.key = fiber.key;\n if (hasContextDependencies(fiber)) {\n result.has_context_dependencies = true;\n }\n const source = detachSourceFromProps(normalizedProps ?? undefined);\n if (source) result.source = source;\n return result;\n}\n\nfunction directPrimitiveChild(value: unknown): string | null {\n if (typeof value === \"string\") return value.length > 0 ? value : null;\n return typeof value === \"number\" ? String(value) : null;\n}\n\nfunction serializeChildren(\n parent: Fiber,\n ownerFiberId: string,\n identity: ProjectionSemanticFiberIdentity,\n): DetachSerializedFiber[] {\n const children: DetachSerializedFiber[] = [];\n for (let child = parent.child; child; child = child.sibling) {\n children.push(...serializeBranch(child, ownerFiberId, identity));\n }\n return children;\n}\n\n/**\n * Mirror the layer stream's include filter: non-layer React wrappers are\n * transparent and promote their descendants. HostText is the one deliberate\n * addition because edit operations need authored text even though the layer\n * panel does not model text as a standalone layer.\n */\nfunction serializeBranch(\n fiber: Fiber,\n ownerFiberId: string,\n identity: ProjectionSemanticFiberIdentity,\n): DetachSerializedFiber[] {\n if (isProjectionLayerFiber(fiber) || fiber.tag === FiberTag.HostText) {\n return [serializeIncludedFiber(fiber, ownerFiberId, identity)];\n }\n\n const promoted: DetachSerializedFiber[] = [];\n for (let child = fiber.child; child; child = child.sibling) {\n promoted.push(...serializeBranch(child, ownerFiberId, identity));\n }\n return promoted;\n}\n\nfunction readHostText(fiber: Fiber): string {\n if (typeof fiber.memoizedProps === \"string\") return fiber.memoizedProps;\n return fiber.stateNode instanceof Text ? fiber.stateNode.textContent : \"\";\n}\n\nfunction hasContextDependencies(fiber: Fiber): boolean {\n const dependencies = fiber.dependencies;\n return Boolean(\n dependencies &&\n typeof dependencies === \"object\" &&\n (dependencies as { firstContext?: unknown }).firstContext,\n );\n}\n\n/** Lift react-native-web's dataSet annotation carrier into the same flat keys\n * used by DOM and ordinary React fibers before source extraction. */\nfunction normalizeTempoDataSet(props: FiberProps | null): FiberProps | null {\n const dataSet = props?.dataSet;\n if (!props || !dataSet || typeof dataSet !== \"object\") return props;\n\n let extracted: Record<string, unknown> | null = null;\n let remaining: Record<string, unknown> | null = null;\n for (const [key, value] of Object.entries(\n dataSet as Record<string, unknown>,\n )) {\n if (key.startsWith(\"tempo\")) {\n (extracted ??= {})[\n `data-${key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`\n ] = value;\n } else {\n (remaining ??= {})[key] = value;\n }\n }\n if (!extracted) return props;\n\n const normalized = { ...props, ...extracted };\n if (remaining) normalized.dataSet = remaining;\n else delete normalized.dataSet;\n return normalized;\n}\n\n/** Root context is cold and JSON-safe before the bridge sees it. Budget the\n * walk itself, including transparent fibers and values that cannot be kept,\n * so consumer pruning cannot hide unbounded producer work. */\nfunction captureSemanticSubtree(\n committedRoot: Fiber,\n): DetachSerializedFiber & { truncated: boolean } {\n const result: DetachSerializedFiber & { truncated: boolean } = {\n fiber_id: \"\",\n name: \"\",\n tag: \"fragment\",\n owner_fiber_id: null,\n props: {},\n children: [],\n truncated: false,\n };\n const encoder = new TextEncoder();\n // Leave room for the reply envelope, delimiters, and the truncation flag.\n let remaining = 256 * 1024 - 1024;\n let nodes = 0;\n const seen = new Set<object>();\n function value(\n input: unknown,\n depth: number,\n dataSet = false,\n ): DetachSerializableValue | undefined {\n if (remaining < 2) {\n result.truncated = true;\n return undefined;\n }\n if (\n typeof input === \"function\" ||\n typeof input === \"symbol\" ||\n input === undefined\n )\n return undefined;\n if (\n input === null ||\n typeof input === \"boolean\" ||\n typeof input === \"number\" ||\n typeof input === \"string\"\n ) {\n let output = input;\n if (typeof input === \"string\" && input.length > 2000) {\n result.truncated = true;\n output = input.slice(0, 2000);\n }\n if (typeof output === \"number\" && !Number.isFinite(output))\n return undefined;\n const bytes = encoder.encode(JSON.stringify(output)).byteLength + 1;\n if (bytes > remaining) {\n result.truncated = true;\n return undefined;\n }\n remaining -= bytes;\n return output;\n }\n if (typeof input !== \"object\") return undefined;\n if (depth >= 6 || seen.has(input)) {\n result.truncated = true;\n return undefined;\n }\n const array = Array.isArray(input);\n const prototype = Object.getPrototypeOf(input);\n if (!array && prototype !== Object.prototype && prototype !== null)\n return undefined;\n seen.add(input);\n remaining -= 2;\n const output:\n | DetachSerializableValue[]\n | Record<string, DetachSerializableValue> = array ? [] : {};\n let keys = 0;\n for (const key in input) {\n if (!Object.prototype.hasOwnProperty.call(input, key)) continue;\n if (++keys > (array ? 50 : 40) || remaining <= 0) {\n result.truncated = true;\n break;\n }\n const internal =\n key === \"children\" ||\n key === \"data-dom-id\" ||\n key.startsWith(\"data-tempo-\") ||\n (dataSet && key.startsWith(\"tempo\")) ||\n key.startsWith(\"__\") ||\n key === \"_owner\" ||\n key === \"$$typeof\";\n if (internal) continue;\n if (key.length > 2000) {\n result.truncated = true;\n continue;\n }\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (!descriptor || !(\"value\" in descriptor)) continue;\n const bytes = array\n ? 0\n : encoder.encode(JSON.stringify(key)).byteLength + 2;\n if (bytes > remaining) {\n result.truncated = true;\n break;\n }\n remaining -= bytes;\n const entry = value(descriptor.value, depth + 1, key === \"dataSet\");\n if (entry === undefined) continue;\n if (Array.isArray(output)) output.push(entry);\n else\n Object.defineProperty(output, key, { value: entry, enumerable: true });\n }\n seen.delete(input);\n return output;\n }\n const pending = [{ fiber: committedRoot, children: result.children }];\n const visited = new Set<Fiber>();\n while (pending.length) {\n if (nodes >= 1500 || remaining <= 0) {\n result.truncated = true;\n break;\n }\n const { fiber, children } = pending.pop()!;\n if (visited.has(fiber)) {\n result.truncated = true;\n continue;\n }\n visited.add(fiber);\n nodes++;\n // The registered root's sibling belongs to another watch, not this reply.\n if (fiber !== committedRoot && fiber.sibling)\n pending.push({ fiber: fiber.sibling, children });\n let nested = children;\n if (isProjectionLayerFiber(fiber) || fiber.tag === FiberTag.HostText) {\n const name = getDisplayName(fiber);\n const node: DetachSerializedFiber = {\n fiber_id: \"\",\n name: name.slice(0, 2000),\n tag: detachTagFromFiberTag(fiber.tag),\n owner_fiber_id: null,\n props: {},\n children: [],\n };\n if (name.length > 2000) result.truncated = true;\n const props = fiber.memoizedProps;\n const dataSet =\n props && typeof props === \"object\"\n ? Object.getOwnPropertyDescriptor(props, \"dataSet\")?.value\n : undefined;\n // Read only the annotation keys so source extraction cannot bypass the\n // context value walk's object bounds by enumerating a large dataSet.\n const source = detachSourceFromProps(\n dataSet && typeof dataSet === \"object\"\n ? {\n \"data-tempo-filepath\":\n Object.getOwnPropertyDescriptor(dataSet, \"tempoFilepath\")?.value ??\n props[\"data-tempo-filepath\"],\n \"data-tempo-position\":\n Object.getOwnPropertyDescriptor(dataSet, \"tempoPosition\")?.value ??\n props[\"data-tempo-position\"],\n }\n : props && typeof props === \"object\"\n ? props\n : undefined,\n );\n if (source) {\n node.source = {\n file: source.file.slice(0, 2000),\n position: source.position,\n };\n if (source.file.length > 2000) result.truncated = true;\n }\n const component =\n node.tag !== \"host\" && node.tag !== \"text\" && node.tag !== \"fragment\";\n if (component)\n node.has_context_dependencies = hasContextDependencies(fiber);\n const bytes = encoder.encode(JSON.stringify(node)).byteLength + 1;\n if (bytes > remaining) {\n result.truncated = true;\n break;\n }\n remaining -= bytes;\n if (component && props && typeof props === \"object\") {\n node.props =\n (value(props, 0) as\n | Record<string, DetachSerializableValue>\n | undefined) ?? {};\n }\n children.push(node);\n nested = node.children;\n }\n if (fiber.child) pending.push({ fiber: fiber.child, children: nested });\n }\n return result;\n}\n","/**\n * Narrow reader for Svelte 5's development-only element metadata.\n *\n * Keep every access to `__svelte_meta` in this file. It is an intentionally\n * isolated compatibility boundary: callers receive validated records and do\n * not depend on Svelte runtime object shapes directly.\n */\n\nexport const TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE =\n \"data-tempo-svelte-source-registry\";\n\nexport interface SvelteDevStackEntry {\n readonly type: string;\n readonly file: string;\n readonly line: number;\n readonly column: number;\n readonly componentTag?: string;\n readonly parent: SvelteDevStackEntry | null;\n}\n\nexport interface SvelteElementMetadata {\n readonly loc: {\n readonly file: string;\n readonly line: number;\n readonly column: number;\n };\n readonly parent: SvelteDevStackEntry | null;\n}\n\nexport interface SvelteComponentSourceRecord {\n readonly kind: \"component\";\n readonly name: string;\n readonly line: number;\n readonly column: number;\n readonly position: number;\n readonly className?: string;\n readonly style?: string;\n readonly locked?: boolean;\n /** Attributes written as expressions, as the SDK's `data-tempo-expr`. */\n readonly expressions?: string;\n readonly supportsClassName: boolean;\n readonly supportsStyle: boolean;\n}\n\nexport interface SvelteHostSourceRecord {\n readonly kind: \"host\";\n readonly name: string;\n readonly line: number;\n readonly column: number;\n readonly position: number;\n readonly className?: string;\n readonly style?: string;\n readonly expressions?: string;\n readonly supportsClassName: boolean;\n readonly supportsStyle: boolean;\n}\n\nexport interface SvelteSourceRegistryRecord {\n readonly filename: string;\n readonly filepath: string;\n readonly modifiedTs: number;\n readonly sourceVersion: string;\n readonly components: readonly SvelteComponentSourceRecord[];\n readonly hosts: readonly SvelteHostSourceRecord[];\n}\n\nexport interface SvelteSourceRegistry {\n resolveComponent(entry: SvelteDevStackEntry): {\n source: SvelteSourceRegistryRecord;\n component: SvelteComponentSourceRecord;\n } | null;\n resolveHost(metadata: SvelteElementMetadata): {\n source: SvelteSourceRegistryRecord;\n host: SvelteHostSourceRecord;\n } | null;\n}\n\nexport type SvelteRuntimeMetadataValidation =\n | { readonly kind: \"supported\" }\n | { readonly kind: \"unavailable\"; readonly message: string };\n\nexport function validateSvelteRuntimeMetadata(\n root: Element,\n): SvelteRuntimeMetadataValidation {\n if (\n !root.querySelector(`template[${TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE}]`)\n ) {\n return {\n kind: \"unavailable\",\n message:\n \"Svelte Canvas layers require a supported Svelte 5 development build with Tempo's Svelte preprocessor enabled. No source registry was found in the rendered root; confirm apps[0].uiFramework is set to svelte and the app is not serving a production/minified build.\",\n };\n }\n const renderedElements = [\n root,\n ...Array.from(root.querySelectorAll<Element>(\"*\")),\n ].filter(\n (element) => !element.hasAttribute(TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE),\n );\n const authoredHosts = renderedElements.filter(\n (element) =>\n element.hasAttribute(\"data-tempo-filepath\") &&\n element.hasAttribute(\"data-tempo-position\"),\n );\n for (const host of authoredHosts) {\n if (readSvelteElementMetadata(host) === null) {\n return {\n kind: \"unavailable\",\n message:\n \"Svelte Canvas layers require a supported Svelte 5 development build with runtime source metadata. Confirm the app uses Tempo's Svelte preprocessor before its other preprocessors and is not serving a production/minified build.\",\n };\n }\n }\n if (\n renderedElements.length > 1 &&\n renderedElements.every(\n (element) => readSvelteElementMetadata(element) === null,\n )\n ) {\n return {\n kind: \"unavailable\",\n message:\n \"Svelte Canvas layers require a supported Svelte 5 development build with runtime source metadata. The rendered root contains source registry data but no Svelte element metadata; confirm the app is not serving a production/minified build.\",\n };\n }\n return { kind: \"supported\" };\n}\n\nexport function readSvelteElementMetadata(\n element: Element,\n): SvelteElementMetadata | null {\n const value = (element as Element & { __svelte_meta?: unknown })\n .__svelte_meta;\n if (!isRecord(value) || !isLocation(value.loc)) return null;\n const parent = readStackEntry(value.parent, new Set());\n if (value.parent != null && parent === null) return null;\n return { loc: value.loc, parent };\n}\n\nexport function readSvelteComponentChain(\n element: Node,\n): readonly SvelteDevStackEntry[] {\n // Svelte stamps elements only. The next host or trailing registry template\n // supplies the component stack for leading, interleaved and trailing text.\n let host: Node | null = element;\n let starts = 0;\n if (!(host instanceof Element)) {\n do {\n host = host.nextSibling;\n if (\n host?.nodeType === 8 &&\n host.nodeValue === TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE\n )\n starts += 1;\n } while (host && !(host instanceof Element));\n if (!(host instanceof Element)) return [];\n }\n const metadata = readSvelteElementMetadata(host);\n const chain: SvelteDevStackEntry[] = [];\n for (let entry = metadata?.parent ?? null; entry; entry = entry.parent) {\n if (entry.type === \"component\") chain.push(entry);\n }\n chain.reverse();\n // Each start comment crossed enters a component after this node. Its stack\n // cannot own the preceding text. The comment itself belongs to that component.\n chain.length = Math.max(0, chain.length - starts);\n return chain;\n}\n\nexport function collectSvelteSourceRegistry(\n root: Element,\n): SvelteSourceRegistry {\n const records: SvelteSourceRegistryRecord[] = [];\n for (const element of root.querySelectorAll(\n `template[${TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE}]`,\n )) {\n const raw = element.getAttribute(TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE);\n if (!raw) continue;\n const parsed = parseRegistryRecord(raw);\n if (parsed) records.push(parsed);\n }\n\n return {\n resolveComponent(entry) {\n const file = normalizeFile(entry.file);\n for (let index = records.length - 1; index >= 0; index -= 1) {\n const source = records[index]!;\n if (!sameRuntimeFile(file, normalizeFile(source.filename))) continue;\n const component = source.components.find(\n (candidate) =>\n candidate.line === entry.line &&\n candidate.column === entry.column &&\n (entry.componentTag === undefined ||\n candidate.name === entry.componentTag),\n );\n if (component) return { source, component };\n }\n return null;\n },\n resolveHost(metadata) {\n const file = normalizeFile(metadata.loc.file);\n for (let index = records.length - 1; index >= 0; index -= 1) {\n const source = records[index]!;\n if (!sameRuntimeFile(file, normalizeFile(source.filename))) continue;\n const host = source.hosts.find(\n (candidate) =>\n candidate.line === metadata.loc.line &&\n candidate.column === metadata.loc.column,\n );\n if (host) return { source, host };\n }\n return null;\n },\n };\n}\n\nfunction parseRegistryRecord(value: string): SvelteSourceRegistryRecord | null {\n try {\n const parsed: unknown = JSON.parse(value);\n if (\n !isRecord(parsed) ||\n typeof parsed.filename !== \"string\" ||\n typeof parsed.filepath !== \"string\" ||\n !isNonNegativeInteger(parsed.modifiedTs) ||\n typeof parsed.sourceVersion !== \"string\" ||\n parsed.sourceVersion.length === 0 ||\n !Array.isArray(parsed.components) ||\n !Array.isArray(parsed.hosts)\n ) {\n return null;\n }\n const components = parsed.components\n .map(parseComponentRecord)\n .filter(\n (record): record is SvelteComponentSourceRecord => record !== null,\n );\n const hosts = parsed.hosts\n .map(parseHostRecord)\n .filter((record): record is SvelteHostSourceRecord => record !== null);\n return {\n filename: parsed.filename,\n filepath: parsed.filepath,\n modifiedTs: parsed.modifiedTs,\n sourceVersion: parsed.sourceVersion,\n components,\n hosts,\n };\n } catch {\n return null;\n }\n}\n\nfunction parseHostRecord(value: unknown): SvelteHostSourceRecord | null {\n const common = parseSourceTargetRecord(value, \"host\");\n return common ? { kind: \"host\", ...common } : null;\n}\n\nfunction parseComponentRecord(\n value: unknown,\n): SvelteComponentSourceRecord | null {\n const common = parseSourceTargetRecord(value, \"component\");\n return common ? { kind: \"component\", ...common } : null;\n}\n\nfunction parseSourceTargetRecord(\n value: unknown,\n kind: \"component\" | \"host\",\n): Omit<SvelteComponentSourceRecord, \"kind\"> | null {\n if (\n !isRecord(value) ||\n value.kind !== kind ||\n typeof value.name !== \"string\" ||\n !isPositiveInteger(value.line) ||\n !isNonNegativeInteger(value.column) ||\n !isNonNegativeInteger(value.position) ||\n typeof value.supportsClassName !== \"boolean\" ||\n typeof value.supportsStyle !== \"boolean\"\n ) {\n return null;\n }\n return {\n name: value.name,\n line: value.line,\n column: value.column,\n position: value.position,\n ...(typeof value.className === \"string\"\n ? { className: value.className }\n : {}),\n ...(typeof value.style === \"string\" ? { style: value.style } : {}),\n ...(typeof value.locked === \"boolean\" ? { locked: value.locked } : {}),\n ...(typeof value.expressions === \"string\"\n ? { expressions: value.expressions }\n : {}),\n supportsClassName: value.supportsClassName,\n supportsStyle: value.supportsStyle,\n };\n}\n\nfunction readStackEntry(\n value: unknown,\n seen: Set<object>,\n depth = 0,\n): SvelteDevStackEntry | null {\n if (!isRecord(value)) return value == null ? null : null;\n if (seen.has(value) || depth >= 512) return null;\n seen.add(value);\n if (\n typeof value.type !== \"string\" ||\n typeof value.file !== \"string\" ||\n !isPositiveInteger(value.line) ||\n !isNonNegativeInteger(value.column) ||\n (value.componentTag !== undefined && typeof value.componentTag !== \"string\")\n ) {\n return null;\n }\n const parent = readStackEntry(value.parent, seen, depth + 1);\n if (value.parent != null && parent === null) return null;\n // Preserve the runtime object's identity. Descendant host elements from one\n // component invocation share this exact stack entry, which is how the layer\n // serializer interns a multi-root component once instead of duplicating it.\n return value as unknown as SvelteDevStackEntry;\n}\n\nfunction normalizeFile(value: string): string {\n return value.replace(/^file:\\/\\//, \"\").replace(/\\\\/g, \"/\");\n}\n\nfunction sameRuntimeFile(left: string, right: string): boolean {\n return (\n left === right || left.endsWith(`/${right}`) || right.endsWith(`/${left}`)\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isLocation(value: unknown): value is SvelteElementMetadata[\"loc\"] {\n return (\n isRecord(value) &&\n typeof value.file === \"string\" &&\n isPositiveInteger(value.line) &&\n isNonNegativeInteger(value.column)\n );\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return Number.isInteger(value) && (value as number) >= 0;\n}\n\nfunction isPositiveInteger(value: unknown): value is number {\n return Number.isInteger(value) && (value as number) > 0;\n}\n","import { FiberTag } from \"../fiber/react-types\";\nimport { ensureProjectionDomId, nextProjectionId } from \"../html/watch-dom\";\nimport {\n captureProjectionDomLayerProps,\n invocationSourceLayerProps,\n parseInlineStyle,\n serializeDomLayerNode,\n type ProjectionDomLayerSerializer,\n type ProjectionDomLayerTargets,\n} from \"./projection-dom-layers\";\nimport type {\n ProjectionLayerNode,\n ProjectionLayerProps,\n ProjectionLayerRootSnapshot,\n} from \"./projection-layer-snapshot\";\nimport {\n collectSvelteSourceRegistry,\n readSvelteComponentChain,\n readSvelteElementMetadata,\n TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE,\n type SvelteComponentSourceRecord,\n type SvelteDevStackEntry,\n type SvelteHostSourceRecord,\n type SvelteSourceRegistryRecord,\n} from \"./projection-svelte-metadata\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\nimport type { ProjectionLayerPatch } from \"./projection-root-accumulator\";\n\nexport const SVELTE_LAYER_ROOT_ID = \"svelte:$projection-root\";\n\ninterface ResolvedComponent {\n readonly runtime: SvelteDevStackEntry;\n readonly source: SvelteSourceRegistryRecord;\n readonly component: SvelteComponentSourceRecord;\n}\n\ninterface ResolvedHost {\n readonly source: SvelteSourceRegistryRecord;\n readonly host: SvelteHostSourceRecord;\n}\n\n/**\n * Svelte's adapter deliberately implements the DOM serializer contract: DOM\n * mutations remain the observation authority, while Svelte's development\n * parent stack supplies the component nodes missing from DOM ancestry.\n */\nexport function createProjectionSvelteLayerSerializer(): ProjectionDomLayerSerializer {\n const ids = new WeakMap<object, string>();\n\n function id(value: object): string {\n const existing = ids.get(value);\n if (existing) return existing;\n const assigned = nextProjectionId();\n ids.set(value, assigned);\n return assigned;\n }\n\n // Host identities follow runtime objects, not authored offsets. The canvas\n // resolves continuity across replacement from its own layer structure.\n const hostId = (element: Element): string =>\n ensureProjectionDomId(element) ?? id(element);\n\n const createSession = (\n root: Element,\n observedFiles: ProjectionObservedFileMap,\n ) => {\n const registry = collectSvelteSourceRegistry(root);\n const observed = new ProjectionObservedFileAccumulator();\n observed.merge(observedFiles);\n const resolveChain = (element: Node): readonly ResolvedComponent[] =>\n readSvelteComponentChain(element).flatMap((runtime) => {\n const resolved = registry.resolveComponent(runtime);\n if (resolved) {\n observed.add(\n resolved.source.filepath,\n resolved.source.modifiedTs,\n resolved.source.sourceVersion,\n );\n }\n return resolved ? [{ runtime, ...resolved }] : [];\n });\n const resolveHost = (element: Element): ResolvedHost | null => {\n const metadata = readSvelteElementMetadata(element);\n if (!metadata) return null;\n const resolved = registry.resolveHost(metadata);\n if (resolved) {\n observed.add(\n resolved.source.filepath,\n resolved.source.modifiedTs,\n resolved.source.sourceVersion,\n );\n }\n return resolved;\n };\n const isSourceHost = (element: Element): boolean =>\n isAnnotatedSvelteSourceHost(element) || resolveHost(element) !== null;\n\n const serializeElementList = (\n elements: readonly Node[],\n activeChain: readonly ResolvedComponent[],\n ): ProjectionLayerNode[] => {\n const nodes: ProjectionLayerNode[] = [];\n let index = 0;\n while (index < elements.length) {\n const element = elements[index]!;\n const chain = resolveChain(element);\n const next = firstNewComponent(chain, activeChain);\n if (next) {\n const grouped: Node[] = [];\n while (index < elements.length) {\n // Non-elements between roots belong to their common component.\n // Look ahead so trailing separators still belong to the parent.\n let nextIndex = index;\n while (\n nextIndex < elements.length &&\n !(elements[nextIndex] instanceof Element) &&\n resolveChain(elements[nextIndex]!).length === 0\n )\n nextIndex += 1;\n const candidate = elements[nextIndex];\n if (!candidate) break;\n const candidateNext = firstNewComponent(\n resolveChain(candidate),\n activeChain,\n );\n if (candidateNext?.runtime !== next.runtime) break;\n grouped.push(...elements.slice(index, nextIndex + 1));\n index = nextIndex + 1;\n }\n nodes.push(\n serializeComponentNode(\n next,\n serializeElementList(grouped, [...activeChain, next]),\n id(next.runtime),\n ),\n );\n continue;\n }\n if (!(element instanceof Element)) {\n const text = serializeDomLayerNode(root, element);\n if (text) nodes.push(text);\n index += 1;\n continue;\n }\n nodes.push(\n serializeHostNode(\n element,\n chain,\n resolveHost(element),\n serializeElementList,\n id,\n observed,\n ),\n );\n index += 1;\n }\n return nodes;\n };\n\n const serializeHost = (\n element: Element,\n activeChain: readonly ResolvedComponent[] = resolveChain(element),\n ): ProjectionLayerNode =>\n serializeHostNode(\n element,\n activeChain,\n resolveHost(element),\n serializeElementList,\n id,\n observed,\n );\n\n return {\n isSourceHost,\n resolveChain,\n hostId,\n serializeElementList,\n serializeHost,\n captureHostProps(element: Element): ProjectionLayerProps | undefined {\n return captureSvelteHostProps(element, resolveHost(element), observed);\n },\n observedFiles(\n files?: ProjectionObservedFileMap,\n ): ProjectionObservedFileMap {\n observed.merge(files);\n return observed.snapshot();\n },\n };\n };\n\n const serialize = (\n root: Element,\n observedFiles: ProjectionObservedFileMap,\n ): ProjectionLayerRootSnapshot => {\n const session = createSession(root, observedFiles);\n return {\n semantic: {\n kind: \"layers\",\n tree: {\n kind: \"fragment\",\n runtime: \"svelte\",\n id: id(root),\n key: null,\n name: \"svelte-root\",\n domId: null,\n elementTag: null,\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.HostRoot,\n name: \"svelte-root\",\n id: SVELTE_LAYER_ROOT_ID,\n },\n },\n children: session.serializeElementList(visibleChildren(root), []),\n },\n },\n observedFiles: session.observedFiles(),\n };\n };\n\n return {\n serializeRoot: serialize,\n capturePatch(\n root: Element,\n targets: ProjectionDomLayerTargets,\n observedFiles: ProjectionObservedFileMap = {},\n ): ProjectionLayerPatch | undefined {\n if (targets.structural.length === 0 && targets.metadata.length === 0) {\n return undefined;\n }\n const session = createSession(root, observedFiles);\n const sourceHost = session.isSourceHost;\n const structuralTargets = new Set(\n targets.structural\n .filter((target) => target === root || root.contains(target))\n .map((target) => nearestPublishedHost(root, target, sourceHost)),\n );\n const coalesced = Array.from(structuralTargets).filter(\n (candidate) =>\n candidate === root ||\n !Array.from(structuralTargets).some(\n (other) => other !== candidate && other.contains(candidate),\n ),\n );\n const regionTrees = coalesced.map((target) => {\n const targetFiberId =\n target === root ? SVELTE_LAYER_ROOT_ID : session.hostId(target);\n if (target === root) {\n const snapshot = serialize(root, observedFiles);\n session.observedFiles(snapshot.observedFiles);\n return {\n targetFiberId,\n targetId: id(root),\n tree:\n snapshot.semantic.kind === \"layers\"\n ? snapshot.semantic.tree\n : null,\n };\n }\n return {\n targetFiberId,\n targetId: ensureProjectionDomId(target) ?? id(target),\n tree: session.serializeHost(target),\n };\n });\n const metadata = targets.metadata.flatMap((target) => {\n if (\n target === root ||\n !root.contains(target) ||\n !sourceHost(target) ||\n coalesced.some((region) => region === root || region.contains(target))\n ) {\n return [];\n }\n const targetFiberId = session.hostId(target);\n return [\n {\n targetFiberId,\n targetId: ensureProjectionDomId(target) ?? id(target),\n props: session.captureHostProps(target),\n },\n ];\n });\n if (regionTrees.length === 0 && metadata.length === 0) return undefined;\n const patchObservedFiles = session.observedFiles();\n const regions = regionTrees.map((region) => ({\n ...region,\n observedFiles: patchObservedFiles,\n }));\n return {\n ...(regions.length > 0 ? { regions } : {}),\n ...(metadata.length > 0 ? { metadata } : {}),\n };\n },\n };\n}\n\nfunction nearestPublishedHost(\n root: Element,\n target: Element,\n isSourceHost: (element: Element) => boolean,\n): Element {\n for (\n let current: Element | null = target;\n current;\n current = current.parentElement\n ) {\n if (current === root) return root;\n if (isSourceHost(current)) return current;\n if (!root.contains(current)) break;\n }\n return root;\n}\n\nfunction serializeHostNode(\n element: Element,\n chain: readonly ResolvedComponent[],\n resolvedHost: ResolvedHost | null,\n serializeElementList: (\n elements: readonly Node[],\n activeChain: readonly ResolvedComponent[],\n ) => ProjectionLayerNode[],\n id: (value: object) => string,\n observedFiles: ProjectionObservedFileAccumulator,\n): ProjectionLayerNode {\n const name = element.tagName.toLowerCase();\n const domId = ensureProjectionDomId(element);\n\n return {\n kind: \"host\",\n runtime: \"svelte\",\n id: domId ?? id(element),\n key: null,\n name,\n domId,\n elementTag: name,\n props: captureSvelteHostProps(element, resolvedHost, observedFiles),\n source: {\n kind: \"react-fiber\",\n fiber: { tag: FiberTag.HostComponent, name, id: domId ?? id(element) },\n },\n children: serializeElementList(visibleChildren(element), chain),\n };\n}\n\nfunction serializeComponentNode(\n resolved: ResolvedComponent,\n children: readonly ProjectionLayerNode[],\n id: string,\n): ProjectionLayerNode {\n const { source, component } = resolved;\n const props = invocationSourceLayerProps(source, component);\n return {\n kind: \"component\",\n runtime: \"svelte\",\n id,\n key: null,\n name: component.name,\n domId: null,\n elementTag: null,\n props,\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.FunctionComponent,\n name: component.name,\n id,\n },\n },\n children,\n };\n}\n\nfunction visibleChildren(parent: Element): Node[] {\n const visible: Node[] = [];\n for (const child of Array.from(parent.childNodes)) {\n if (!(child instanceof Element)) {\n if (child.nodeType === 3 || child.nodeType === 8) visible.push(child);\n continue;\n }\n if (\n child.localName === \"script\" ||\n child.hasAttribute(TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE)\n )\n continue;\n visible.push(child);\n }\n return visible;\n}\n\nfunction isAnnotatedSvelteSourceHost(element: Element): boolean {\n return (\n element.hasAttribute(\"data-tempo-filepath\") &&\n element.hasAttribute(\"data-tempo-position\")\n );\n}\n\nfunction captureSvelteHostProps(\n element: Element,\n resolved: ResolvedHost | null,\n observedFiles: ProjectionObservedFileAccumulator,\n): ProjectionLayerProps | undefined {\n const live = captureProjectionDomLayerProps(element, observedFiles);\n if (!resolved) return live;\n const { source, host } = resolved;\n const recordedStyle =\n host.style && live?.style === undefined\n ? parseInlineStyle(host.style)\n : undefined;\n return {\n ...live,\n ...(host.className && live?.className === undefined\n ? { className: host.className }\n : {}),\n ...(recordedStyle ? { style: recordedStyle } : {}),\n \"data-tempo-filepath\": source.filepath,\n \"data-tempo-position\": host.position,\n \"data-tempo-modifiedts\": source.modifiedTs,\n \"data-tempo-source-version\": source.sourceVersion,\n \"data-tempo-supports-classname\": host.supportsClassName,\n \"data-tempo-supports-style\": host.supportsStyle,\n ...(host.expressions !== undefined\n ? { \"data-tempo-expr\": host.expressions }\n : {}),\n };\n}\n\nfunction firstNewComponent(\n chain: readonly ResolvedComponent[],\n active: readonly ResolvedComponent[],\n): ResolvedComponent | null {\n for (const component of chain) {\n if (!active.some((candidate) => candidate.runtime === component.runtime)) {\n return component;\n }\n }\n return null;\n}\n","/**\n * Narrow reader for Vue 3's development-build runtime objects.\n *\n * Keep every access to Vue internals in this file: a container's\n * `__vue_app__` and `_vnode`, an element's `__vnode` and\n * `__vueParentComponent`, an instance's `subTree`, `vnode`, `parent` and\n * `type`, a vnode's `ctx`, shape flags and children, `type.__file` and\n * `type.__hmrId`, and the page's `__VUE_HMR_RUNTIME__`. It is an isolated\n * compatibility boundary: callers receive validated records and opaque\n * instance handles, and never depend on Vue object shapes.\n *\n * The reader imports nothing from \"vue\". The producer runs from the frame\n * preload and never shares the page's Vue module, so vnode kinds are matched\n * structurally: shape-flag bits, and the vnode type symbols Vue has\n * registered with Symbol.for since 3.3. Shapes are feature-detected,\n * traversal is depth-bounded, nothing Vue owns is mutated (the HMR runtime's\n * two entry points are wrapped, see `createVueHotUpdateObserver`), and\n * unknown vnode kinds are skipped.\n */\n\nimport {\n readTempoVueInvocationMarker,\n TEMPO_VUE_SOURCE_REGISTRY_GLOBAL,\n type TempoVueComponentSourceRecord,\n type TempoVueHostSourceRecord,\n type TempoVueSourceRegistryRecord,\n type VueRootFallthrough,\n} from \"@modules/vue-editor/records\";\nimport { PROJECTION_ROOT_ATTRIBUTE } from \"../html/watch-dom\";\n\nexport interface VueSourceRegistry {\n byFilepath(filepath: string): TempoVueSourceRegistryRecord | null;\n byFilename(filename: string): TempoVueSourceRegistryRecord | null;\n}\n\ndeclare const vueComponentInstanceBrand: unique symbol;\n\n/** A live Vue component instance. Callers use it only as identity (a\n * WeakMap key) and hand it back to this reader. */\nexport interface VueComponentInstance {\n readonly [vueComponentInstanceBrand]: true;\n}\n\n/**\n * What a component instance or a Vue element renders, flattened to what a\n * layer tree shows. Fragments (v-for, `<template v-if>`, slots, multi-root\n * components), Suspense (its active branch), Teleport (its children, wherever\n * they mount), KeepAlive and the async-component wrapper are transparent.\n * Authored template comments are kept, as the Svelte and DOM lanes keep\n * theirs; Vue's own comment placeholders and unknown vnode kinds are dropped\n * (see `isAuthoredComment`). A fragment's empty anchor text nodes are kept\n * as text (see `visit`).\n */\nexport type VueRenderedNode =\n | { readonly kind: \"component\"; readonly instance: VueComponentInstance }\n | { readonly kind: \"element\"; readonly element: Element }\n | { readonly kind: \"text\"; readonly node: Text }\n | { readonly kind: \"comment\"; readonly node: Comment }\n /** DOM Vue inserted without vnodes. A stringified static chunk keeps its\n * compile-time stamps (`authored`); v-html markup and DOM a script put in\n * an element Vue renders empty are not authored. */\n | { readonly kind: \"dom\"; readonly node: Node; readonly authored: boolean };\n\nexport interface VueInvocation {\n /** The registry record of the template that wrote the invocation. */\n readonly source: TempoVueSourceRegistryRecord;\n readonly component: TempoVueComponentSourceRecord;\n}\n\nexport interface VueResolvedHost {\n readonly source: TempoVueSourceRegistryRecord;\n readonly host: TempoVueHostSourceRecord;\n}\n\nexport interface VueComponentDefinition {\n /** Absolute definition file, or null for render-function components. */\n readonly filename: string | null;\n readonly name: string;\n}\n\nexport type VueRuntimeMetadataValidation =\n | { readonly kind: \"supported\" }\n | { readonly kind: \"unavailable\"; readonly message: string };\n\n// ShapeFlags from @vue/shared, unchanged across Vue 3.\nconst SHAPE_ELEMENT = 1;\nconst SHAPE_COMPONENT = 2 | 4; // functional | stateful\nconst SHAPE_TEXT_CHILDREN = 8;\nconst SHAPE_ARRAY_CHILDREN = 16;\nconst SHAPE_TELEPORT = 64;\nconst SHAPE_SUSPENSE = 128;\n\nconst FRAGMENT = Symbol.for(\"v-fgt\");\nconst TEXT = Symbol.for(\"v-txt\");\nconst STATIC = Symbol.for(\"v-stc\");\nconst COMMENT = Symbol.for(\"v-cmt\");\n/** The text a development build gives a `v-if` placeholder comment. */\nconst V_IF_PLACEHOLDER_TEXT = \"v-if\";\n\nconst MAX_DEPTH = 512;\n\nconst SUPPORTED_RUNTIME =\n \"Vue Canvas layers require a Vue 3.3+ development build served with Tempo's Vue plugin (tempoVuePlugin from tempo-sdk/vue).\";\n\nexport function validateVueRuntimeMetadata(\n root: Element,\n): VueRuntimeMetadataValidation {\n const containers = readVueAppContainers(root);\n // The observed (\"auto\") adapter picks Vue only from a mounted app's\n // container, so it reports this only after that app is gone while its\n // .vue-stamped elements stay in the document (an unmount, or an app that\n // failed during an update or hot reload). No config setting changes that.\n if (containers.length === 0) {\n return unavailable(\n `${SUPPORTED_RUNTIME} No mounted Vue 3 app was found in the rendered root: the Vue app that rendered it is no longer mounted (it was unmounted, or failed during an update or hot reload, while its elements stayed in the page). Reload the board and read the page's console for the error that stopped the app; on a component board, confirm the storyboard is a VueStoryboard from tempo-sdk/canvas/vue.`,\n );\n }\n // An app served without Tempo's Vue plugin (no stamps, no registry) is the\n // Vue twin of a React app served without tempoVitePlugin: its layers are\n // published without source identity, never refused. The identity probe,\n // not the projection, is where \"instrument the app\" is reported. Stamps\n // without their registry are a different thing: the plugin annotated the\n // templates but the registry records never ran (a torn-down runtime), and\n // the layers those stamps promise cannot be built.\n if (\n readVueSourceRegistry(root) === null &&\n containers.some(carriesTempoVueStamps)\n ) {\n return unavailable(\n `${SUPPORTED_RUNTIME} The page carries Tempo's Vue source stamps but no Vue source registry, so the stamps cannot be resolved; reload the document, and confirm every .vue module is served by the same Vite server that stamped it.`,\n );\n }\n for (const container of containers) {\n const version = readAppVersion(container);\n if (version !== null && !isSupportedVueVersion(version)) {\n return unavailable(\n `${SUPPORTED_RUNTIME} The rendered app runs Vue ${version}; upgrade the app to Vue 3.3 or newer.`,\n );\n }\n const instance = readRawRootInstance(container);\n if (instance === null) {\n return unavailable(\n `${SUPPORTED_RUNTIME} A Vue app container has no live root component; confirm the app mounted without an error.`,\n );\n }\n if (instance.vapor === true) {\n return unavailable(\n `${SUPPORTED_RUNTIME} Vue Vapor components are not supported on the Canvas yet; render this storyboard with the virtual-DOM runtime (createApp, no vapor attribute).`,\n );\n }\n if (!hasDevelopmentHooks(root, container)) {\n return unavailable(\n `${SUPPORTED_RUNTIME} The rendered app carries no Vue element metadata; confirm the app is not serving a production/minified build.`,\n );\n }\n }\n return { kind: \"supported\" };\n}\n\n/** Elements under `root` that hold a mounted app, in document order. A\n * route document may hold several; each VueStoryboard mounts one. An app\n * mounted inside another app's DOM, or inside another projection root, is\n * that one's content, so the walk descends into neither.\n *\n * Found by `__vue_app__`, as the layer serializer finds them, not by\n * `data-v-app`: only `createApp().mount` adds that attribute. A hydrated\n * server-rendered app (`createSSRApp().mount`, how Nuxt mounts `#__nuxt`)\n * carries the property alone, and a route document of one was reported as\n * having no Vue app at all. */\nexport function readVueAppContainers(root: Element): Element[] {\n const containers: Element[] = [];\n const visit = (element: Element): void => {\n const isForeignRoot =\n element !== root && element.hasAttribute(PROJECTION_ROOT_ATTRIBUTE);\n if (isForeignRoot) return;\n if (isVueAppContainer(element)) {\n containers.push(element);\n return;\n }\n for (const child of Array.from(element.children)) visit(child);\n };\n visit(root);\n return containers;\n}\n\n/** Whether Tempo's Vue plugin stamped anything the app rendered: the host\n * stamps are the plugin's only trace in the DOM (invocation markers live on\n * vnode props). */\nfunction carriesTempoVueStamps(container: Element): boolean {\n return (\n container.querySelector(\"[data-tempo-filepath][data-tempo-position]\") !==\n null\n );\n}\n\n/** `__vue_app__` exists while an app is mounted, in every build. */\nexport function isVueAppContainer(element: Element): boolean {\n return isRecord((element as { __vue_app__?: unknown }).__vue_app__);\n}\n\n/** Whether Vue's renderer mounted this element itself. False for elements of\n * a stringified static chunk and for DOM Vue did not render. */\nexport function isVueRenderedElement(element: Element): boolean {\n return isRecord((element as { __vnode?: unknown }).__vnode);\n}\n\n/** The live root instance. Never `app._instance`: a root HMR reload renders\n * a cloned root vnode into the container and leaves `app._instance` pointing\n * at the unmounted old instance. `container._vnode` is what render() wrote\n * last. */\nexport function readVueRootInstance(\n container: Element,\n): VueComponentInstance | null {\n return opaque(readRawRootInstance(container));\n}\n\n/** The component instance whose render mounted `node`: its slot consumer\n * for slotted content. Elements of a stringified static chunk carry no\n * back-pointer and borrow the nearest ancestor's; a static chunk directly in\n * the app container belongs to the app's root instance. */\nexport function readVueOwnerInstance(node: Node): VueComponentInstance | null {\n let element: Element | null =\n node.nodeType === 1 ? (node as Element) : node.parentElement;\n for (let depth = 0; element && depth < MAX_DEPTH; depth += 1) {\n const owner = (element as { __vueParentComponent?: unknown })\n .__vueParentComponent;\n if (isRawInstance(owner)) return opaque(owner);\n if (isVueAppContainer(element)) return readVueRootInstance(element);\n element = element.parentElement;\n }\n return null;\n}\n\n/** The instance whose subtree renders `instance` (its slot consumer for a\n * slotted component), or null for an app root. */\nexport function readVueParentInstance(\n instance: VueComponentInstance,\n): VueComponentInstance | null {\n const parent = raw(instance).parent;\n return isRawInstance(parent) ? opaque(parent) : null;\n}\n\nexport function isVueInstanceUnmounted(\n instance: VueComponentInstance,\n): boolean {\n return raw(instance).isUnmounted === true;\n}\n\n/** True for an app root that is runtime plumbing rather than a user\n * component: a render-function root with no definition file, such as the one\n * VueStoryboard creates to mount the storyboard's component. */\nexport function isVueAnonymousAppRoot(instance: VueComponentInstance): boolean {\n return (\n readVueParentInstance(instance) === null &&\n readDefinitionFile(raw(instance).type) === null\n );\n}\n\n/** The id plugin-vue hot-updates this instance's definition by. */\nexport function readVueHotUpdateId(\n instance: VueComponentInstance,\n): string | null {\n const type = raw(instance).type;\n const id = isRecord(type) ? type.__hmrId : undefined;\n return typeof id === \"string\" && id.length > 0 ? id : null;\n}\n\nexport function readVueInstanceOutput(\n instance: VueComponentInstance,\n): readonly VueRenderedNode[] {\n const value = raw(instance);\n // Vue 3.6 Vapor instances render a block, not a vnode subtree.\n if (value.vapor === true) return [];\n const output: VueRenderedNode[] = [];\n visit(value.subTree, output, 0);\n return output;\n}\n\n/** What one Vue-rendered element holds, or null when the element has no\n * vnode of its own (a static chunk element, or DOM Vue did not render). */\nexport function readVueElementOutput(\n element: Element,\n): readonly VueRenderedNode[] | null {\n const vnode = readElementVNode(element);\n if (!vnode) return null;\n if (\n shapeFlag(vnode) & SHAPE_ARRAY_CHILDREN &&\n Array.isArray(vnode.children)\n ) {\n const output: VueRenderedNode[] = [];\n for (const child of vnode.children) visit(child, output, 1);\n return output;\n }\n // String children and v-text exist only as DOM text. v-html markup has no\n // vnodes, and neither does DOM a script added to an element Vue renders\n // empty (a chart library's mount point): both are unowned DOM. An element\n // Vue rendered itself got here through a Teleport and belongs to its\n // owner; an empty text node is a Teleport target anchor.\n const props = isRecord(vnode.props) ? vnode.props : {};\n const markup = props.innerHTML != null;\n const text =\n Boolean(shapeFlag(vnode) & SHAPE_TEXT_CHILDREN) ||\n props.textContent != null;\n const output: VueRenderedNode[] = [];\n for (const node of Array.from(element.childNodes)) {\n if (node.nodeType === 3) {\n if (markup) output.push({ kind: \"dom\", node, authored: false });\n else if (text || node.nodeValue)\n output.push({ kind: \"text\", node: node as Text });\n } else if (node.nodeType === 8) {\n // v-html markup's comments are its own DOM, as the DOM lane shows\n // them. Elsewhere a comment node carries no vnode back-pointer, so an\n // authored comment a Teleport moved in (which its owner already\n // lists) cannot be told from one a script added; neither is listed.\n if (markup) output.push({ kind: \"dom\", node, authored: false });\n } else if (node.nodeType === 1 && !isVueRenderedElement(node as Element)) {\n output.push({ kind: \"dom\", node, authored: false });\n }\n }\n return output;\n}\n\nexport function readVueDefinition(\n instance: VueComponentInstance,\n): VueComponentDefinition {\n const type = raw(instance).type;\n const named = type as {\n readonly name?: unknown;\n readonly displayName?: unknown;\n readonly __name?: unknown;\n };\n const filename = readDefinitionFile(type);\n // Built-ins can be functions with an empty name, so empty means absent.\n // A functional component is named by displayName first, as Vue names it.\n const declared =\n typeof type === \"function\"\n ? (nonEmptyString(named.displayName) ?? nonEmptyString(named.name))\n : nonEmptyString(named.name);\n return {\n filename,\n name:\n declared ??\n nonEmptyString(named.__name) ??\n (filename ? basename(filename) : null) ??\n \"Anonymous\",\n };\n}\n\n/** The invocation that created `instance`: the marker's offset, looked up in\n * the registry record of the template that wrote it. That template is the\n * vnode's render context, past any async-component wrapper (which re-creates\n * the inner vnode with the invocation's props). */\nexport function readVueInvocation(\n instance: VueComponentInstance,\n registry: VueSourceRegistry,\n): VueInvocation | null {\n const vnode = raw(instance).vnode;\n if (!isRecord(vnode)) return null;\n const position = readInvocationPosition(vnode.props);\n if (position === null) return null;\n let owner = vnode.ctx;\n for (\n let depth = 0;\n isRawInstance(owner) && isTransparentWrapper(owner) && depth < MAX_DEPTH;\n depth += 1\n ) {\n owner = isRecord(owner.vnode) ? owner.vnode.ctx : null;\n }\n if (!isRawInstance(owner)) return null;\n const filename = readDefinitionFile(owner.type);\n const source = filename ? registry.byFilename(filename) : null;\n const component = source ? componentAt(source, position) : null;\n return source && component ? { source, component } : null;\n}\n\n/** A host's own stamps, resolved against its file's registry record. */\nexport function readVueHostRecord(\n element: Element,\n registry: VueSourceRegistry,\n): VueResolvedHost | null {\n const filepath = element.getAttribute(\"data-tempo-filepath\");\n const position = Number(element.getAttribute(\"data-tempo-position\") ?? \"\");\n if (!filepath || !Number.isInteger(position)) return null;\n const source = registry.byFilepath(filepath);\n const host = source ? hostAt(source, position) : null;\n return source && host ? { source, host } : null;\n}\n\n/**\n * Whether a `class` / `style` written on this invocation reaches rendered\n * DOM. The invocation record answers for the call site (no `v-bind=\"obj\"`,\n * literal or absent); the invoked file's root decides the rest. A single\n * element root receives fallthrough attributes; a single component root\n * hands them on, so its own root decides; multi-root, `inheritAttrs: false`,\n * explicit `$attrs` binding and unknown definitions (no registry record) do\n * not forward reliably and answer false.\n */\nexport function readVueComponentStyleCapability(\n instance: VueComponentInstance,\n invocation: VueInvocation,\n registry: VueSourceRegistry,\n): { readonly supportsClassName: boolean; readonly supportsStyle: boolean } {\n const forwards = forwardsRootAttributes(raw(instance), registry);\n return {\n supportsClassName: invocation.component.supportsClassName && forwards,\n supportsStyle: invocation.component.supportsStyle && forwards,\n };\n}\n\nconst parsedRecords = new WeakMap<object, ParsedSourceRecord | null>();\n\ninterface ParsedSourceRecord {\n readonly record: TempoVueSourceRegistryRecord;\n readonly hosts: ReadonlyMap<number, TempoVueHostSourceRecord>;\n readonly components: ReadonlyMap<number, TempoVueComponentSourceRecord>;\n}\n\n/** The page's registry, read through the observed document's own window:\n * the producer's realm can differ from the page's (interact iframes). Each\n * module evaluation replaces its file's entry, so parsed records are cached\n * by entry identity. Null when the page registered nothing. */\nexport function readVueSourceRegistry(root: Element): VueSourceRegistry | null {\n const view = root.ownerDocument.defaultView as\n | (Window & { [TEMPO_VUE_SOURCE_REGISTRY_GLOBAL]?: unknown })\n | null;\n const value = view?.[TEMPO_VUE_SOURCE_REGISTRY_GLOBAL];\n if (!isRecord(value)) return null;\n const byFilepath = new Map<string, TempoVueSourceRegistryRecord>();\n for (const entry of Object.values(value)) {\n const parsed = parseRecordCached(entry);\n if (parsed) byFilepath.set(parsed.filepath, parsed);\n }\n let byFilename: Map<string, TempoVueSourceRegistryRecord> | null = null;\n return {\n byFilepath: (filepath) => byFilepath.get(filepath) ?? null,\n byFilename(filename) {\n if (!byFilename) {\n byFilename = new Map();\n for (const record of byFilepath.values())\n byFilename.set(normalizeFile(record.filename), record);\n }\n return byFilename.get(normalizeFile(filename)) ?? null;\n },\n };\n}\n\nconst HOT_UPDATE_LISTENERS = Symbol.for(\n \"tempo.iframe-projection.vue-hot-update-listeners\",\n);\n\ntype HotUpdateListener = (hotUpdateId: string) => void;\n\n/**\n * Hears plugin-vue's hot updates. plugin-vue calls\n * `__VUE_HMR_RUNTIME__.rerender(id, render)` for a template-only edit and\n * `.reload(id, component)` otherwise, looking both up at call time, so\n * wrapping the two entry points observes every update. rerender patches\n * synchronously; reload queues the remount on Vue's scheduler. Listeners\n * run in a macrotask after the call, when both have settled.\n *\n * `sync` is idempotent and also attaches to a runtime that replaced the\n * previous one (a second Vue copy on the page); `stop` detaches everywhere.\n * The Svelte lane has no counterpart to share: a Svelte hot update remounts\n * DOM and rewrites its in-DOM registry `<template>`, which the mutation\n * lane already attributes.\n */\nexport function createVueHotUpdateObserver(listener: HotUpdateListener): {\n sync(root: Element): void;\n stop(): void;\n} {\n const attached = new Set<Set<HotUpdateListener>>();\n return {\n sync(root) {\n const view = root.ownerDocument.defaultView;\n const runtime = view\n ? (view as { __VUE_HMR_RUNTIME__?: unknown }).__VUE_HMR_RUNTIME__\n : undefined;\n if (!view || !isRecord(runtime)) return;\n const listeners = hotUpdateListeners(view, runtime);\n listeners.add(listener);\n attached.add(listeners);\n },\n stop() {\n for (const listeners of attached) listeners.delete(listener);\n attached.clear();\n },\n };\n}\n\nfunction hotUpdateListeners(\n view: Window,\n runtime: Record<PropertyKey, unknown>,\n): Set<HotUpdateListener> {\n // Duck-typed: a producer in another realm may have installed the set.\n const existing = runtime[HOT_UPDATE_LISTENERS] as\n | Set<HotUpdateListener>\n | undefined;\n if (typeof existing?.add === \"function\") return existing;\n const listeners = new Set<HotUpdateListener>();\n Object.defineProperty(runtime, HOT_UPDATE_LISTENERS, {\n value: listeners,\n configurable: true,\n });\n for (const method of [\"rerender\", \"reload\"] as const) {\n const original = runtime[method];\n if (typeof original !== \"function\") continue;\n runtime[method] = function observedHotUpdate(\n this: unknown,\n ...args: unknown[]\n ) {\n try {\n return original.apply(this, args);\n } finally {\n const hotUpdateId = String(args[0]);\n if (listeners.size > 0)\n view.setTimeout(() => {\n for (const notify of [...listeners]) {\n try {\n notify(hotUpdateId);\n } catch {\n // One root's failure must not stop another root's baseline.\n }\n }\n }, 0);\n }\n };\n }\n return listeners;\n}\n\ninterface RawInstance extends Record<string, unknown> {\n readonly type: unknown;\n}\n\nfunction raw(instance: VueComponentInstance): RawInstance {\n return instance as unknown as RawInstance;\n}\n\nfunction opaque(instance: RawInstance | null): VueComponentInstance | null {\n return instance as unknown as VueComponentInstance | null;\n}\n\nfunction isRawInstance(value: unknown): value is RawInstance {\n return (\n isRecord(value) &&\n (isRecord(value.type) || typeof value.type === \"function\") &&\n (isRecord(value.vnode) || value.vapor === true)\n );\n}\n\nfunction readRawRootInstance(container: Element): RawInstance | null {\n const vnode = (container as { _vnode?: unknown })._vnode;\n const instance = isRecord(vnode) ? vnode.component : null;\n return isRawInstance(instance) ? instance : null;\n}\n\n/** KeepAlive and the defineAsyncComponent wrapper are real components with\n * no authored identity of their own: the layer tree shows what they hold. */\nfunction isTransparentWrapper(instance: RawInstance): boolean {\n const type = instance.type;\n if (!isRecord(type) && typeof type !== \"function\") return false;\n const wrapper = type as { __isKeepAlive?: unknown; __asyncLoader?: unknown };\n return (\n wrapper.__isKeepAlive === true ||\n typeof wrapper.__asyncLoader === \"function\"\n );\n}\n\nfunction visit(value: unknown, output: VueRenderedNode[], depth: number): void {\n if (!isRecord(value) || depth > MAX_DEPTH) return;\n const flags = shapeFlag(value);\n if (flags & SHAPE_COMPONENT) {\n const instance = value.component;\n // A component vnode without an instance has not mounted yet.\n if (!isRawInstance(instance)) return;\n if (isTransparentWrapper(instance)) {\n if (instance.vapor !== true) visit(instance.subTree, output, depth + 1);\n return;\n }\n output.push({\n kind: \"component\",\n instance: instance as unknown as VueComponentInstance,\n });\n return;\n }\n if (flags & SHAPE_SUSPENSE) {\n // The pending branch renders offscreen; only the active one is shown.\n const suspense = value.suspense;\n if (isRecord(suspense)) visit(suspense.activeBranch, output, depth + 1);\n return;\n }\n if (flags & SHAPE_TELEPORT) {\n visitChildren(value.children, output, depth);\n return;\n }\n if (flags & SHAPE_ELEMENT) {\n if (isNode(value.el) && value.el.nodeType === 1)\n output.push({ kind: \"element\", element: value.el as Element });\n return;\n }\n if (value.type === FRAGMENT) {\n // A fragment's start and end anchors are empty text nodes. Text layers\n // are addressed by their position among the parent's child nodes, and\n // markup cannot carry an empty text node, so the mirror restores one\n // only from its own text leaf. Dropping the anchors shifted every later\n // text sibling: a slot's fallback text rendered twice in the mirror.\n pushTextNode(value.el, output);\n visitChildren(value.children, output, depth);\n pushTextNode(value.anchor, output);\n return;\n }\n if (value.type === TEXT) {\n pushTextNode(value.el, output);\n return;\n }\n if (value.type === COMMENT) {\n if (isAuthoredComment(value) && isNode(value.el) && value.el.nodeType === 8)\n output.push({ kind: \"comment\", node: value.el as Comment });\n return;\n }\n if (value.type === STATIC) {\n // A stringified static chunk is one vnode over the DOM range el..anchor.\n // Its comments have no vnode; the build kept them, so they are authored.\n let node = isNode(value.el) ? value.el : null;\n for (let count = 0; node && count < 100_000; count += 1) {\n if (node.nodeType === 1 || node.nodeType === 3 || node.nodeType === 8)\n output.push({ kind: \"dom\", node, authored: true });\n if (node === value.anchor) break;\n node = node.nextSibling;\n }\n }\n // Unknown vnode kinds are skipped.\n}\n\n/**\n * Whether a Comment vnode is a comment the template wrote. An authored\n * `<!-- text -->` compiles to `createCommentVNode(\" text \")`: a plain vnode\n * whose children are its text. Every other Comment vnode is Vue's\n * placeholder for something that rendered nothing:\n * - a `v-if` chain with no branch taken renders\n * `createCommentVNode(\"v-if\", true)`, a block (`dynamicChildren` is an\n * array). Inside `v-once` block tracking is off, so the same placeholder\n * is a plain vnode there and only its text tells it apart;\n * - a component, slot outlet or `<component :is>` that renders nothing\n * normalizes to a Comment vnode with no text.\n * An authored comment spelled exactly `<!--v-if-->` therefore reads as a\n * placeholder: nothing at runtime tells it from one inside `v-once`.\n */\nfunction isAuthoredComment(vnode: Record<string, unknown>): boolean {\n const text = vnode.children;\n if (typeof text !== \"string\") return false;\n if (Array.isArray(vnode.dynamicChildren)) return false;\n return text !== V_IF_PLACEHOLDER_TEXT;\n}\n\n/**\n * The vnode Vue rendered `element` from. A component's root element starts\n * with its own element vnode, but after the parent updates, the dev build's\n * `traverseStaticChildren` points `__vnode` at the component's vnode, whose\n * `el` is that same root. Its children then read as slots, and the element's\n * fragment anchors would be lost; the element's own vnode is the end of the\n * component's `subTree` chain.\n */\nfunction readElementVNode(element: Element): Record<string, unknown> | null {\n let vnode = (element as { __vnode?: unknown }).__vnode;\n for (\n let depth = 0;\n isRecord(vnode) && shapeFlag(vnode) & SHAPE_COMPONENT && depth < MAX_DEPTH;\n depth += 1\n ) {\n const instance: unknown = vnode.component;\n vnode = isRecord(instance) ? instance.subTree : null;\n }\n return isRecord(vnode) && vnode.el === element ? vnode : null;\n}\n\nfunction pushTextNode(value: unknown, output: VueRenderedNode[]): void {\n if (isNode(value) && value.nodeType === 3)\n output.push({ kind: \"text\", node: value as Text });\n}\n\nfunction visitChildren(\n children: unknown,\n output: VueRenderedNode[],\n depth: number,\n): void {\n if (!Array.isArray(children)) return;\n for (const child of children) visit(child, output, depth + 1);\n}\n\nfunction readInvocationPosition(props: unknown): number | null {\n if (!isRecord(props)) return null;\n const hook = props.onVnodeBeforeMount;\n // A user's own @vue:before-mount on the same invocation makes it an array.\n // tempoVuePlugin's marker, `@vue:before-mount=\"function __tempo_c<offset>(){}\"`,\n // compiles to this reserved prop: never in attrs, never on the DOM.\n for (const handler of Array.isArray(hook) ? hook : [hook]) {\n if (typeof handler !== \"function\") continue;\n const position = readTempoVueInvocationMarker(handler.name);\n if (position !== null) return position;\n }\n return null;\n}\n\nfunction forwardsRootAttributes(\n instance: RawInstance,\n registry: VueSourceRegistry,\n): boolean {\n let current: RawInstance | null = instance;\n for (let depth = 0; current && depth < MAX_DEPTH; depth += 1) {\n const filename = readDefinitionFile(current.type);\n const record = filename ? registry.byFilename(filename) : null;\n if (record?.rootFallthrough === \"single-element\") return true;\n if (record?.rootFallthrough !== \"single-component\") return false;\n current = rootComponentInstance(current);\n }\n return false;\n}\n\n/** The component a single-component root renders, past KeepAlive and the\n * async wrapper, which hand attributes on unchanged. */\nfunction rootComponentInstance(instance: RawInstance): RawInstance | null {\n let vnode = instance.subTree;\n for (let depth = 0; isRecord(vnode) && depth < MAX_DEPTH; depth += 1) {\n if (!(shapeFlag(vnode) & SHAPE_COMPONENT)) return null;\n const child = vnode.component;\n if (!isRawInstance(child)) return null;\n if (!isTransparentWrapper(child)) return child;\n vnode = child.subTree;\n }\n return null;\n}\n\nfunction hasDevelopmentHooks(root: Element, container: Element): boolean {\n // Vue defines __VUE_HMR_RUNTIME__ in every development build, even one\n // whose only content is a stringified static chunk (no element vnodes).\n const view = root.ownerDocument.defaultView as {\n __VUE_HMR_RUNTIME__?: unknown;\n } | null;\n if (isRecord(view?.__VUE_HMR_RUNTIME__)) return true;\n const elements = container.querySelectorAll(\"*\");\n if (elements.length === 0) return true;\n for (const element of elements) {\n if (isRecord((element as { __vnode?: unknown }).__vnode)) return true;\n }\n return false;\n}\n\nfunction readAppVersion(container: Element): string | null {\n const app = (container as { __vue_app__?: unknown }).__vue_app__;\n return isRecord(app) && typeof app.version === \"string\" ? app.version : null;\n}\n\n/** Fragment and Text vnode types are Symbol.for-registered from 3.3 on;\n * before that a separately bundled reader cannot recognize them. */\nfunction isSupportedVueVersion(version: string): boolean {\n const [major, minor] = version.split(\".\").map(Number);\n return major === 3 && (minor ?? 0) >= 3;\n}\n\nfunction parseRecordCached(\n value: unknown,\n): TempoVueSourceRegistryRecord | null {\n if (!isRecord(value)) return null;\n let parsed = parsedRecords.get(value);\n if (parsed === undefined) {\n parsed = parseRecord(value);\n parsedRecords.set(value, parsed);\n }\n return parsed?.record ?? null;\n}\n\nfunction componentAt(\n record: TempoVueSourceRegistryRecord,\n position: number,\n): TempoVueComponentSourceRecord | null {\n return indexFor(record)?.components.get(position) ?? null;\n}\n\nfunction hostAt(\n record: TempoVueSourceRegistryRecord,\n position: number,\n): TempoVueHostSourceRecord | null {\n return indexFor(record)?.hosts.get(position) ?? null;\n}\n\nconst recordIndexes = new WeakMap<\n TempoVueSourceRegistryRecord,\n ParsedSourceRecord\n>();\n\nfunction indexFor(\n record: TempoVueSourceRegistryRecord,\n): ParsedSourceRecord | null {\n return recordIndexes.get(record) ?? null;\n}\n\nfunction parseRecord(\n value: Record<string, unknown>,\n): ParsedSourceRecord | null {\n if (\n typeof value.filename !== \"string\" ||\n value.filename.length === 0 ||\n typeof value.filepath !== \"string\" ||\n value.filepath.length === 0 ||\n !isNonNegativeInteger(value.modifiedTs) ||\n typeof value.sourceVersion !== \"string\" ||\n value.sourceVersion.length === 0 ||\n !Array.isArray(value.components) ||\n !Array.isArray(value.hosts)\n ) {\n return null;\n }\n const components = value.components\n .map(parseComponent)\n .filter((entry): entry is TempoVueComponentSourceRecord => entry !== null);\n const hosts = value.hosts\n .map(parseHost)\n .filter((entry): entry is TempoVueHostSourceRecord => entry !== null);\n const record: TempoVueSourceRegistryRecord = {\n filename: value.filename,\n filepath: value.filepath,\n modifiedTs: value.modifiedTs,\n sourceVersion: value.sourceVersion,\n components,\n hosts,\n rootFallthrough: isRootFallthrough(value.rootFallthrough)\n ? value.rootFallthrough\n : \"unknown\",\n };\n const parsed: ParsedSourceRecord = {\n record,\n hosts: new Map(hosts.map((host) => [host.position, host])),\n components: new Map(\n components.map((component) => [component.position, component]),\n ),\n };\n recordIndexes.set(record, parsed);\n return parsed;\n}\n\n/** The fields a registry entry must carry for either kind, read from page\n * data the reader does not trust. */\nfunction readTargetFields(value: unknown, kind: \"component\" | \"host\") {\n if (\n !isRecord(value) ||\n value.kind !== kind ||\n typeof value.name !== \"string\" ||\n !isNonNegativeInteger(value.position) ||\n typeof value.supportsClassName !== \"boolean\" ||\n typeof value.supportsStyle !== \"boolean\"\n ) {\n return null;\n }\n return {\n name: value.name,\n position: value.position,\n className:\n typeof value.className === \"string\" ? value.className : undefined,\n style: typeof value.style === \"string\" ? value.style : undefined,\n supportsClassName: value.supportsClassName,\n supportsStyle: value.supportsStyle,\n };\n}\n\nfunction parseHost(value: unknown): TempoVueHostSourceRecord | null {\n const fields = readTargetFields(value, \"host\");\n return fields && { kind: \"host\", ...fields };\n}\n\nfunction parseComponent(value: unknown): TempoVueComponentSourceRecord | null {\n const fields = readTargetFields(value, \"component\");\n if (!fields || !isRecord(value)) return null;\n // Only an invocation carries these; a host's facts are its DOM stamp.\n return {\n kind: \"component\",\n ...fields,\n locked: typeof value.locked === \"boolean\" ? value.locked : undefined,\n expressions:\n typeof value.expressions === \"string\" ? value.expressions : undefined,\n literalProps: readLiteralProps(value.literalProps),\n };\n}\n\n/** An invocation's literal props, kept only when every value is JSON: the\n * layer publishes each one `JSON.stringify`'d. */\nfunction readLiteralProps(\n value: unknown,\n): TempoVueComponentSourceRecord[\"literalProps\"] {\n if (!isRecord(value) || !Object.values(value).every(isJsonValue))\n return undefined;\n return value as TempoVueComponentSourceRecord[\"literalProps\"];\n}\n\nfunction isJsonValue(value: unknown, depth = 0): boolean {\n if (depth > MAX_DEPTH) return false;\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\")\n return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (Array.isArray(value))\n return value.every((item) => isJsonValue(item, depth + 1));\n return (\n isRecord(value) &&\n Object.getPrototypeOf(value) === Object.prototype &&\n Object.values(value).every((item) => isJsonValue(item, depth + 1))\n );\n}\n\nconst ROOT_FALLTHROUGHS: ReadonlySet<unknown> = new Set<VueRootFallthrough>([\n \"single-element\",\n \"single-component\",\n \"multi-root\",\n \"inherit-attrs-false\",\n \"explicit-attrs\",\n \"unknown\",\n]);\n\nfunction isRootFallthrough(value: unknown): value is VueRootFallthrough {\n return ROOT_FALLTHROUGHS.has(value);\n}\n\nfunction readDefinitionFile(type: unknown): string | null {\n if (!isRecord(type) && typeof type !== \"function\") return null;\n const file = (type as { __file?: unknown }).__file;\n return typeof file === \"string\" && file.length > 0\n ? normalizeFile(file)\n : null;\n}\n\nfunction shapeFlag(vnode: Record<string, unknown>): number {\n return typeof vnode.shapeFlag === \"number\" ? vnode.shapeFlag : 0;\n}\n\nfunction basename(filename: string): string {\n return filename.slice(filename.lastIndexOf(\"/\") + 1).replace(/\\.[^.]+$/, \"\");\n}\n\nfunction normalizeFile(value: string): string {\n return value.replace(/^file:\\/\\//, \"\").replace(/\\\\/g, \"/\");\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction unavailable(message: string): VueRuntimeMetadataValidation {\n return { kind: \"unavailable\", message };\n}\n\nfunction isNode(value: unknown): value is Node {\n return isRecord(value) && typeof value.nodeType === \"number\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return Number.isInteger(value) && (value as number) >= 0;\n}\n","import { FiberTag } from \"../fiber/react-types\";\nimport {\n ensureProjectionDomId,\n nextProjectionId,\n PROJECTION_ROOT_ATTRIBUTE,\n} from \"../html/watch-dom\";\nimport {\n captureProjectionDomLayerProps,\n invocationSourceLayerProps,\n type ProjectionDomLayerSerializer,\n type ProjectionDomLayerTargets,\n serializeDomLayerNode,\n} from \"./projection-dom-layers\";\nimport type {\n ProjectionLayerMetadataSnapshot,\n ProjectionLayerNode,\n ProjectionLayerProps,\n ProjectionLayerRegionSnapshot,\n ProjectionLayerRootSnapshot,\n} from \"./projection-layer-snapshot\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\nimport { SOURCE_ANNOTATION_ATTRIBUTES } from \"./projection-patch\";\nimport type { ProjectionLayerPatch } from \"./projection-root-accumulator\";\nimport {\n createVueHotUpdateObserver,\n isVueAnonymousAppRoot,\n isVueAppContainer,\n isVueInstanceUnmounted,\n isVueRenderedElement,\n readVueComponentStyleCapability,\n readVueDefinition,\n readVueElementOutput,\n readVueHostRecord,\n readVueHotUpdateId,\n readVueInstanceOutput,\n readVueInvocation,\n readVueOwnerInstance,\n readVueParentInstance,\n readVueRootInstance,\n readVueSourceRegistry,\n type VueComponentInstance,\n type VueRenderedNode,\n type VueSourceRegistry,\n} from \"./projection-vue-metadata\";\n\nexport const VUE_LAYER_ROOT_ID = \"vue:$projection-root\";\n\nexport interface ProjectionVueLayerSerializer\n extends ProjectionDomLayerSerializer {\n /** Requests a full baseline after each Vue hot update that touched a\n * published component: template offsets and new instances change without\n * a DOM mutation this lane can attribute. */\n observeBaselineRequests(request: () => void): () => void;\n}\n\ninterface CaptureSession {\n readonly root: Element;\n readonly registry: VueSourceRegistry | null;\n readonly observed: ProjectionObservedFileAccumulator;\n}\n\n/** Where a structural change is republished: the whole root, one app\n * container (its root component is plumbing), or one published component. */\ntype RegionAnchor =\n | { readonly kind: \"root\" }\n | { readonly kind: \"container\"; readonly container: Element }\n | {\n readonly kind: \"component\";\n readonly instance: VueComponentInstance;\n readonly container: Element;\n };\n\nconst ROOT_ANCHOR: RegionAnchor = { kind: \"root\" };\n\n/**\n * Vue's adapter keeps the DOM serializer contract: MutationObserver stays the\n * observation authority, and the tree comes from the mounted vnode graph.\n * Component layers interleave with host layers in DOM order, the way React's\n * fibers do; the DOM outside the app containers (the SDK's mount wrappers)\n * publishes as plain hosts.\n *\n * Identity follows runtime objects: one id per component instance, one per\n * element (its projection DOM id). Repeated occurrences and keyed reorders\n * keep their ids; a script hot update creates new instances and new ids.\n */\nexport function createProjectionVueLayerSerializer(): ProjectionVueLayerSerializer {\n const ids = new WeakMap<object, string>();\n // What the last full and later regions published, so a patch target\n // anchors at a node the destination knows and a hot update knows whether\n // it touched this root.\n let publishedInstances = new WeakSet<VueComponentInstance>();\n // Each published host and whether it was authored (stamps trusted).\n let publishedHosts = new WeakMap<Element, boolean>();\n let publishedHotUpdateIds = new Set<string>();\n let requestBaseline: (() => void) | null = null;\n const hotUpdates = createVueHotUpdateObserver((hotUpdateId) => {\n if (publishedHotUpdateIds.has(hotUpdateId)) requestBaseline?.();\n });\n\n function id(value: object): string {\n const existing = ids.get(value);\n if (existing) return existing;\n const assigned = nextProjectionId();\n ids.set(value, assigned);\n return assigned;\n }\n\n function hostLayerId(session: CaptureSession, element: Element): string {\n return domIdFor(session, element) ?? id(element);\n }\n\n /** Teleported output can mount outside the watched root. It is not in\n * this root's mirror, so it binds without a destination element. */\n function domIdFor(session: CaptureSession, element: Element): string | null {\n return session.root.contains(element)\n ? ensureProjectionDomId(element)\n : null;\n }\n\n function createSession(\n root: Element,\n observedFiles: ProjectionObservedFileMap,\n ): CaptureSession {\n // The page loads Vue after the watch starts; attach on every capture.\n if (requestBaseline) hotUpdates.sync(root);\n const observed = new ProjectionObservedFileAccumulator();\n observed.merge(observedFiles);\n return { root, registry: readVueSourceRegistry(root), observed };\n }\n\n function rootNode(session: CaptureSession): ProjectionLayerNode {\n const { root } = session;\n return {\n kind: \"fragment\",\n runtime: \"vue\",\n id: id(root),\n key: null,\n name: \"vue-root\",\n domId: null,\n elementTag: null,\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.HostRoot,\n name: \"vue-root\",\n id: VUE_LAYER_ROOT_ID,\n },\n },\n children: isVueAppContainer(root)\n ? appChildren(session, root)\n : outsideAppChildren(session, root),\n };\n }\n\n /** DOM between the watched root and the app containers: the SDK's hidden\n * mount wrappers on a storyboard, a route document's own markup. */\n function outsideAppChildren(\n session: CaptureSession,\n parent: Element,\n ): ProjectionLayerNode[] {\n const nodes: ProjectionLayerNode[] = [];\n for (const child of Array.from(parent.childNodes)) {\n if (child.nodeType === 3 || child.nodeType === 8) {\n const text = serializeDomLayerNode(session.root, child);\n if (text) nodes.push(text);\n continue;\n }\n if (child.nodeType !== 1) continue;\n const element = child as Element;\n // Another root's element ends this root's tree, as in the DOM lane.\n if (\n element.localName === \"script\" ||\n element.hasAttribute(PROJECTION_ROOT_ATTRIBUTE)\n )\n continue;\n if (isVueAppContainer(element)) {\n nodes.push(hostNode(session, element, appChildren(session, element)));\n continue;\n }\n // Content a Teleport moved here belongs to the component that owns it.\n if (isVueRenderedElement(element)) continue;\n nodes.push(\n hostNode(session, element, outsideAppChildren(session, element)),\n );\n }\n return nodes;\n }\n\n function appChildren(\n session: CaptureSession,\n container: Element,\n ): ProjectionLayerNode[] {\n const instance = readVueRootInstance(container);\n if (!instance) return outsideAppChildren(session, container);\n // VueStoryboard's render-function root only mounts the user's component.\n return isVueAnonymousAppRoot(instance)\n ? rendered(session, readVueInstanceOutput(instance))\n : [componentNode(session, instance)];\n }\n\n function rendered(\n session: CaptureSession,\n nodes: readonly VueRenderedNode[],\n ): ProjectionLayerNode[] {\n const layers: ProjectionLayerNode[] = [];\n for (const node of nodes) {\n if (node.kind === \"component\")\n layers.push(componentNode(session, node.instance));\n else if (node.kind === \"element\")\n layers.push(\n hostNode(\n session,\n node.element,\n rendered(session, readVueElementOutput(node.element) ?? []),\n ),\n );\n else if (node.kind === \"text\" || node.kind === \"comment\")\n layers.push(...characterDataNode(session, node.node));\n else layers.push(...unownedDom(session, node.node, node.authored));\n }\n return layers;\n }\n\n /** DOM without vnodes: a static chunk (authored, stamps and comments\n * intact) or v-html markup and script-added DOM (not authored, no source\n * identity). */\n function unownedDom(\n session: CaptureSession,\n node: Node,\n authored: boolean,\n ): ProjectionLayerNode[] {\n if (node.nodeType === 3 || node.nodeType === 8)\n return characterDataNode(session, node);\n if (node.nodeType !== 1) return [];\n const element = node as Element;\n if (element.localName === \"script\") return [];\n const children = Array.from(element.childNodes).flatMap((child) =>\n unownedDom(session, child, authored),\n );\n return [hostNode(session, element, children, authored)];\n }\n\n /** A text or comment layer. One a Teleport mounted outside the root has\n * no address in this root: a positional id would stamp its foreign\n * parent. */\n function characterDataNode(\n session: CaptureSession,\n node: Node,\n ): ProjectionLayerNode[] {\n if (!session.root.contains(node)) return [];\n const text = serializeDomLayerNode(session.root, node);\n return text ? [text] : [];\n }\n\n function componentNode(\n session: CaptureSession,\n instance: VueComponentInstance,\n ): ProjectionLayerNode {\n publishedInstances.add(instance);\n const hotUpdateId = readVueHotUpdateId(instance);\n if (hotUpdateId) publishedHotUpdateIds.add(hotUpdateId);\n const { name } = readVueDefinition(instance);\n const layerId = id(instance);\n const props = componentProps(session, instance);\n return {\n kind: \"component\",\n runtime: \"vue\",\n id: layerId,\n key: null,\n name,\n domId: null,\n elementTag: null,\n ...(props ? { props } : {}),\n source: {\n kind: \"react-fiber\",\n fiber: { tag: FiberTag.FunctionComponent, name, id: layerId },\n },\n children: rendered(session, readVueInstanceOutput(instance)),\n };\n }\n\n /** The invocation's source identity, or none: a component created from a\n * render function in script (the storyboard's own component included) has\n * no authored call site, and an unresolved one is never guessed. */\n function componentProps(\n session: CaptureSession,\n instance: VueComponentInstance,\n ): ProjectionLayerProps | undefined {\n const { registry } = session;\n const invocation = registry ? readVueInvocation(instance, registry) : null;\n if (!registry || !invocation) return undefined;\n const { source, component } = invocation;\n session.observed.add(\n source.filepath,\n source.modifiedTs,\n source.sourceVersion,\n );\n const capability = readVueComponentStyleCapability(\n instance,\n invocation,\n registry,\n );\n return {\n ...invocationSourceLayerProps(source, component),\n \"data-tempo-supports-classname\": capability.supportsClassName,\n \"data-tempo-supports-style\": capability.supportsStyle,\n };\n }\n\n function hostNode(\n session: CaptureSession,\n element: Element,\n children: readonly ProjectionLayerNode[],\n authored = true,\n ): ProjectionLayerNode {\n publishedHosts.set(element, authored);\n const name = element.tagName.toLowerCase();\n const domId = domIdFor(session, element);\n const layerId = domId ?? id(element);\n return {\n kind: \"host\",\n runtime: \"vue\",\n id: layerId,\n key: null,\n name,\n domId,\n elementTag: name,\n props: hostProps(session, element, authored),\n source: {\n kind: \"react-fiber\",\n fiber: { tag: FiberTag.HostComponent, name, id: layerId },\n },\n children,\n };\n }\n\n function hostProps(\n session: CaptureSession,\n element: Element,\n authored: boolean,\n ): ProjectionLayerProps | undefined {\n if (!authored) {\n // Markup Vue did not compile can carry copied stamps; they prove\n // nothing about where it was written.\n const live = captureProjectionDomLayerProps(element);\n const unlocated = Object.fromEntries(\n Object.entries(live ?? {}).filter(\n ([key]) => !SOURCE_ANNOTATION_ATTRIBUTES.has(key),\n ),\n );\n return Object.keys(unlocated).length > 0\n ? (unlocated as ProjectionLayerProps)\n : undefined;\n }\n const live = captureProjectionDomLayerProps(element, session.observed);\n const resolved = session.registry\n ? readVueHostRecord(element, session.registry)\n : null;\n if (!resolved) return live;\n // The live props already carry the host's `data-tempo-expr` stamp,\n // the only place its facts are written.\n const { host } = resolved;\n return {\n ...live,\n \"data-tempo-supports-classname\": host.supportsClassName,\n \"data-tempo-supports-style\": host.supportsStyle,\n };\n }\n\n /** Republish the nearest published component that owns a change. Its\n * subtree holds the target's whole Vue-rendered structure; a component\n * mounted in this flush is covered by its parent's own mutation. */\n function regionAnchorFor(\n session: CaptureSession,\n target: Element,\n ): RegionAnchor {\n const { root } = session;\n if (target === root) return ROOT_ANCHOR;\n const container = nearestContainer(root, target);\n // Outside every app only the SDK's wrappers live; they rarely change.\n if (!container) return ROOT_ANCHOR;\n const appAnchor: RegionAnchor =\n container === root ? ROOT_ANCHOR : { kind: \"container\", container };\n if (target === container) return appAnchor;\n for (\n let instance = readVueOwnerInstance(target);\n instance;\n instance = readVueParentInstance(instance)\n ) {\n if (isVueInstanceUnmounted(instance)) continue;\n if (publishedInstances.has(instance))\n return { kind: \"component\", instance, container };\n }\n return appAnchor;\n }\n\n function serializeRegion(\n session: CaptureSession,\n anchor: RegionAnchor,\n ): Omit<ProjectionLayerRegionSnapshot, \"observedFiles\"> {\n switch (anchor.kind) {\n case \"root\":\n return {\n targetFiberId: VUE_LAYER_ROOT_ID,\n targetId: id(session.root),\n tree: rootNode(session),\n };\n case \"container\": {\n const layerId = hostLayerId(session, anchor.container);\n return {\n targetFiberId: layerId,\n targetId: layerId,\n tree: hostNode(\n session,\n anchor.container,\n appChildren(session, anchor.container),\n ),\n };\n }\n case \"component\": {\n const layerId = id(anchor.instance);\n return {\n targetFiberId: layerId,\n targetId: layerId,\n tree: componentNode(session, anchor.instance),\n };\n }\n }\n }\n\n return {\n serializeRoot(root, observedFiles = {}) {\n publishedInstances = new WeakSet();\n publishedHosts = new WeakMap();\n publishedHotUpdateIds = new Set();\n const session = createSession(root, observedFiles);\n const tree = rootNode(session);\n return {\n semantic: { kind: \"layers\", tree },\n observedFiles: session.observed.snapshot(),\n } satisfies ProjectionLayerRootSnapshot;\n },\n capturePatch(\n root: Element,\n targets: ProjectionDomLayerTargets,\n observedFiles: ProjectionObservedFileMap = {},\n ): ProjectionLayerPatch | undefined {\n if (targets.structural.length === 0 && targets.metadata.length === 0) {\n return undefined;\n }\n const session = createSession(root, observedFiles);\n const inRoot = (element: Element) =>\n element === root || root.contains(element);\n const anchors = targets.structural\n .filter(inRoot)\n .map((target) => regionAnchorFor(session, target));\n // A changed host this lane never published (DOM a script added inside\n // a Vue element) has no layer to update.\n const metadataTargets = targets.metadata.filter(\n (target) =>\n target !== root && inRoot(target) && publishedHosts.has(target),\n );\n const regions = widestAnchors(anchors);\n const regionTrees = regions.map((anchor) =>\n serializeRegion(session, anchor),\n );\n const metadata: ProjectionLayerMetadataSnapshot[] = metadataTargets\n .filter(\n (target) =>\n !regions.some((anchor) => anchorCovers(anchor, target, root)),\n )\n .map((target) => {\n const layerId = hostLayerId(session, target);\n return {\n targetFiberId: layerId,\n targetId: layerId,\n props: hostProps(\n session,\n target,\n publishedHosts.get(target) === true,\n ),\n };\n });\n if (regionTrees.length === 0 && metadata.length === 0) return undefined;\n const patchObservedFiles = session.observed.snapshot();\n return {\n ...(regionTrees.length > 0\n ? {\n regions: regionTrees.map((region) => ({\n ...region,\n observedFiles: patchObservedFiles,\n })),\n }\n : {}),\n ...(metadata.length > 0 ? { metadata } : {}),\n };\n },\n observeBaselineRequests(request) {\n requestBaseline = request;\n return () => {\n if (requestBaseline === request) requestBaseline = null;\n hotUpdates.stop();\n };\n },\n };\n}\n\nfunction nearestContainer(root: Element, target: Element): Element | null {\n for (\n let current: Element | null = target;\n current;\n current = current.parentElement\n ) {\n if (isVueAppContainer(current)) return current;\n if (current === root) return null;\n }\n return null;\n}\n\n/** Drop every anchor another anchor's region already republishes. */\nfunction widestAnchors(anchors: readonly RegionAnchor[]): RegionAnchor[] {\n if (anchors.some((anchor) => anchor.kind === \"root\")) return [ROOT_ANCHOR];\n const unique = anchors.filter(\n (anchor, index) =>\n anchors.findIndex((other) => sameAnchor(other, anchor)) === index,\n );\n return unique.filter(\n (anchor) =>\n !unique.some(\n (other) => !sameAnchor(other, anchor) && anchorContains(other, anchor),\n ),\n );\n}\n\nfunction sameAnchor(left: RegionAnchor, right: RegionAnchor): boolean {\n if (left.kind === \"root\" || right.kind === \"root\")\n return left.kind === right.kind;\n if (left.kind === \"container\" && right.kind === \"container\")\n return left.container === right.container;\n return (\n left.kind === \"component\" &&\n right.kind === \"component\" &&\n left.instance === right.instance\n );\n}\n\nfunction anchorContains(outer: RegionAnchor, inner: RegionAnchor): boolean {\n if (outer.kind === \"root\") return true;\n if (inner.kind === \"root\") return false;\n if (outer.kind === \"container\") return outer.container === inner.container;\n if (inner.kind === \"container\") return false;\n for (\n let instance = readVueParentInstance(inner.instance);\n instance;\n instance = readVueParentInstance(instance)\n ) {\n if (instance === outer.instance) return true;\n }\n return false;\n}\n\n/** Whether a region already carries this host's current props. */\nfunction anchorCovers(\n anchor: RegionAnchor,\n target: Element,\n root: Element,\n): boolean {\n if (anchor.kind === \"root\") return true;\n if (anchor.kind === \"container\")\n return anchor.container === target || anchor.container.contains(target);\n if (!root.contains(target)) return false;\n for (\n let instance = readVueOwnerInstance(target);\n instance;\n instance = readVueParentInstance(instance)\n ) {\n if (instance === anchor.instance) return true;\n }\n return false;\n}\n","import { getCommittedFiberRoots } from \"../fiber/watch\";\nimport {\n ASTRO_LAYER_ROOT_ID,\n createProjectionAstroLayerSerializer,\n} from \"./projection-astro-layers\";\nimport { trackAstroSources } from \"./projection-astro-metadata\";\nimport { underForeignProjectionRoot } from \"../html/watch-dom\";\nimport { getFiberFromElement } from \"../fiber/capture\";\nimport { type Fiber, type FiberRoot, FiberTag } from \"../fiber/react-types\";\nimport {\n isTransientFiberResolutionError,\n resolveCommittedFiber,\n} from \"../fiber/serialize\";\nimport type { DetachSerializedFiber } from \"./enriched-to-serialized-fiber\";\nimport type { LayerFramework } from \"./layer-framework\";\nimport type { CombinedProjectionProblem } from \"./projection-batch\";\nimport {\n createProjectionDomLayerSerializer,\n DOM_LAYER_ROOT_ID,\n type ProjectionDomLayerSerializer,\n type ProjectionDomLayerTargets,\n} from \"./projection-dom-layers\";\nimport {\n ascendToAnnotatedComponentRoot,\n createProjectionLayerSerializer,\n isProjectionLayerFiber,\n PROJECTION_SCOPE_TARGET,\n type ProjectionLayerMetadataSnapshot,\n type ProjectionLayerProps,\n type ProjectionLayerRegionSerializationResult,\n type ProjectionLayerRootSnapshot,\n projectionLayerRoots,\n} from \"./projection-layer-snapshot\";\nimport type { ProjectionObservedFileMap } from \"./projection-observed-files\";\nimport type { ProjectionLayerPatch } from \"./projection-root-accumulator\";\nimport { captureProjectionSemanticSubtree } from \"./projection-semantic-subtree\";\nimport {\n createProjectionSvelteLayerSerializer,\n SVELTE_LAYER_ROOT_ID,\n} from \"./projection-svelte-layers\";\nimport {\n readSvelteElementMetadata,\n TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE,\n validateSvelteRuntimeMetadata,\n} from \"./projection-svelte-metadata\";\nimport {\n createProjectionVueLayerSerializer,\n VUE_LAYER_ROOT_ID,\n} from \"./projection-vue-layers\";\nimport {\n isVueAppContainer,\n validateVueRuntimeMetadata,\n} from \"./projection-vue-metadata\";\n\nexport interface ProjectionLayerTarget {\n readonly element: Element;\n readonly fiberSelector?: string;\n readonly scope?: \"contents\" | \"subtree\";\n}\n\nexport interface ProjectionLayerFullCapture {\n readonly snapshot: ProjectionLayerRootSnapshot;\n readonly fiberNodesVisited: number;\n readonly semanticNodesSerialized: number;\n}\n\n/**\n * The sole framework-specific seam in combined projection. The producer owns\n * scheduling and the common DOM transaction; an adapter owns only the source\n * of semantic layers and their identity.\n */\nexport interface ProjectionLayerAdapter {\n /** Physical portal ownership crosses logical subtree boundaries. */\n portalClosure?(root: Fiber): { required: boolean; nodesVisited: number };\n readonly layerFramework: LayerFramework;\n readonly retainDomMutationTargets: boolean;\n readProblem(root: Element): CombinedProjectionProblem | null;\n /** Runtime signals that invalidate the published tree without a DOM\n * mutation the patch lane can attribute (a Vue hot update rewrites\n * template offsets and replaces instances). The producer answers each\n * request with one full baseline for this root; the returned function\n * stops the requests. */\n observeBaselineRequests?(request: () => void): () => void;\n captureFull(\n root: Element,\n fiberTarget: Element | null,\n observedFiles: ProjectionObservedFileMap,\n ): ProjectionLayerFullCapture;\n capturePatch(\n root: Element,\n targets: ProjectionDomLayerTargets,\n observedFiles: ProjectionObservedFileMap,\n ): ProjectionLayerPatch | undefined;\n resolveCommittedRoot(\n fiberRoot: FiberRoot | undefined,\n target: ProjectionLayerTarget,\n ): Fiber | null;\n resolveElementCandidate(element: Element): Fiber | null;\n layerSourceId(fiber: Fiber): string | null;\n captureRegion(fiber: Fiber): ProjectionLayerRegionSerializationResult | null;\n captureMetadata(\n fiber: Fiber,\n options?: {\n readonly sourceAnnotations?: \"fiber\" | \"live-host\";\n /** Reuse this pass's host read; null avoids rereading a known none. */\n readonly layoutMode?: ProjectionLayerProps[\"layoutMode\"] | null;\n },\n ): ProjectionLayerMetadataSnapshot | null;\n captureSemanticSubtree(\n target: ProjectionLayerTarget,\n targetLayerSourceId: string | { readonly mode: \"context\" },\n options?: { readonly descendants?: boolean },\n ): (DetachSerializedFiber & { truncated?: boolean }) | null;\n}\n\n/** The DOM-backed lanes are handed the watched root on every capture. */\nexport function createProjectionLayerAdapter(\n layerFramework: \"dom\" | \"svelte\" | \"vue\",\n): ProjectionLayerAdapter;\n/** The React lane names text directly under the watched root through the\n * scoped root sentinel, so it must be built knowing that root. */\nexport function createProjectionLayerAdapter(\n layerFramework: LayerFramework,\n watchedRoot: Element,\n scope?: \"contents\" | \"subtree\",\n): ProjectionLayerAdapter;\nexport function createProjectionLayerAdapter(\n layerFramework: LayerFramework,\n watchedRoot?: Element,\n scope?: \"contents\" | \"subtree\",\n): ProjectionLayerAdapter {\n switch (layerFramework) {\n case \"auto\":\n case \"react\":\n // The overloads make this unreachable from typed callers.\n if (!watchedRoot)\n throw new Error(\n `The ${layerFramework} layer adapter needs its watched root`,\n );\n return layerFramework === \"auto\"\n ? createObservedLayerAdapter(watchedRoot, scope)\n : createReactLayerAdapter(watchedRoot, scope);\n case \"svelte\":\n return createDomBackedLayerAdapter(\n \"svelte\",\n createProjectionSvelteLayerSerializer(),\n (root) => {\n const validation = validateSvelteRuntimeMetadata(root);\n return validation.kind === \"unavailable\"\n ? {\n reason: \"svelte-layer-metadata-unavailable\",\n message: validation.message,\n }\n : null;\n },\n scope,\n );\n case \"vue\":\n return createDomBackedLayerAdapter(\n \"vue\",\n createProjectionVueLayerSerializer(),\n (root) => {\n const validation = validateVueRuntimeMetadata(root);\n return validation.kind === \"unavailable\"\n ? {\n reason: \"layer-metadata-unavailable\",\n framework: \"vue\",\n message: validation.message,\n }\n : null;\n },\n scope,\n );\n case \"astro\": {\n if (!watchedRoot)\n throw new Error(\"The Astro layer adapter needs its watched root\");\n const react = createReactLayerAdapter(watchedRoot, scope);\n const svelte = createProjectionSvelteLayerSerializer();\n const dom = createDomBackedLayerAdapter(\n \"astro\",\n createProjectionAstroLayerSerializer((element, files) => {\n const renderer = element.getAttribute(\"renderer-url\") ?? \"\";\n if (renderer.includes(\"svelte\"))\n return svelte.serializeRoot(element, files);\n if (\n renderer.includes(\"react\") ||\n getCommittedFiberRoots().some(\n ({ containerInfo }) => containerInfo === element,\n )\n )\n return react.captureFull(element, element.firstElementChild, files)\n .snapshot;\n return null;\n }),\n () => null,\n scope,\n );\n return {\n ...react,\n ...dom,\n portalClosure: react.portalClosure,\n resolveCommittedRoot: react.resolveCommittedRoot,\n resolveElementCandidate: react.resolveElementCandidate,\n layerSourceId: react.layerSourceId,\n captureRegion: react.captureRegion,\n captureMetadata: react.captureMetadata,\n captureSemanticSubtree: (target, id, options) =>\n react.captureSemanticSubtree(target, id, options) ??\n dom.captureSemanticSubtree(target, id, options),\n };\n }\n case \"dom\":\n return createDomBackedLayerAdapter(\n \"dom\",\n createProjectionDomLayerSerializer(),\n () => null,\n scope,\n );\n }\n}\n\nfunction createReactLayerAdapter(\n watchedRoot: Element,\n scope?: \"contents\" | \"subtree\",\n): ProjectionLayerAdapter {\n const serializer = createProjectionLayerSerializer(\n watchedRoot,\n scope !== undefined,\n scope === \"subtree\",\n );\n const missingFiberFallback = createProjectionDomLayerSerializer();\n let hasFiber = false;\n function documentScopeRegion(): ProjectionLayerRegionSerializationResult {\n const result = serializer.serializeContents();\n if (result.snapshot.semantic.kind !== \"scope\")\n throw new Error(\"Missing contents scope\");\n return {\n region: {\n targetFiberId: PROJECTION_SCOPE_TARGET,\n targetId: PROJECTION_SCOPE_TARGET,\n tree: null,\n scope: result.snapshot.semantic.fragment,\n observedFiles: result.snapshot.observedFiles,\n },\n fiberNodesVisited: result.fiberNodesVisited,\n semanticNodesSerialized: result.semanticNodesSerialized,\n };\n }\n return {\n portalClosure: (fiber) => serializer.portalClosure(fiber),\n get layerFramework() {\n return hasFiber ? \"react\" : \"dom\";\n },\n // Raw descendants have no commit fibers. Their DOM mutations still need\n // semantic regions, rooted at the nearest published React ancestor.\n retainDomMutationTargets: true,\n readProblem: () => null,\n captureFull(root, fiberTarget, observedFiles) {\n const committed =\n scope !== undefined\n ? resolveScopeFiber(root)\n : resolveFullCaptureFiber(root, fiberTarget);\n hasFiber = Boolean(committed);\n if (!committed && scope !== undefined)\n return serializer.serializeContents();\n if (!committed) {\n const snapshot = missingFiberFallback.serializeRoot(\n root,\n observedFiles,\n );\n return {\n snapshot:\n scope !== undefined\n ? contentsSnapshot(snapshot, scope === \"subtree\")\n : snapshot,\n fiberNodesVisited: 0,\n semanticNodesSerialized: countLayerNodes(snapshot),\n };\n }\n const serialized = serializer.serialize(committed);\n return {\n snapshot: serialized.snapshot,\n fiberNodesVisited: serialized.fiberNodesVisited,\n semanticNodesSerialized: serialized.semanticNodesSerialized,\n };\n },\n capturePatch: (root, targets, observedFiles) =>\n scope !== undefined && !resolveScopeFiber(root)\n ? targets.structural.length || targets.metadata.length\n ? { regions: [documentScopeRegion().region] }\n : undefined\n : hasFiber\n ? undefined\n : normalizeContentsPatch(\n missingFiberFallback.capturePatch(root, targets, observedFiles),\n scope,\n ),\n resolveCommittedRoot(fiberRoot, target) {\n const fiber = resolveWatchedCommittedFiber(fiberRoot, {\n ...target,\n scope,\n });\n hasFiber = fiber !== null;\n return fiber;\n },\n resolveElementCandidate(element) {\n let raw = getFiberFromElement(element);\n for (\n let parent = element.parentElement;\n !raw && parent;\n parent = parent.parentElement\n )\n raw = getFiberFromElement(parent);\n if (!raw) return null;\n const committed = resolveCommittedFiberOrNull(raw);\n if (!committed) return null;\n let current: Fiber | null = committed;\n while (current && !isProjectionLayerFiber(current)) {\n current = current.return;\n }\n return current;\n },\n layerSourceId: serializer.fiberId,\n captureRegion: (fiber) =>\n scope !== undefined && !resolveScopeFiber(watchedRoot)\n ? documentScopeRegion()\n : serializer.serializeRegion(fiber),\n captureMetadata: serializer.captureMetadata,\n captureSemanticSubtree(target, targetLayerSourceId, options) {\n let current = resolveWatchedCommittedFiber(undefined, {\n ...target,\n scope,\n });\n if (!current && scope !== undefined) {\n const roots = getCommittedFiberRoots().filter(\n ({ containerInfo }) =>\n containerInfo instanceof Element &&\n target.element.contains(containerInfo) &&\n !underForeignProjectionRoot(containerInfo, target.element),\n );\n if (typeof targetLayerSourceId === \"string\") {\n for (const root of roots) {\n const captured = captureProjectionSemanticSubtree(\n root.current,\n targetLayerSourceId,\n {\n fiberId: serializer.fiberId,\n knownFiberId: serializer.knownFiberId,\n },\n options,\n );\n if (captured) return captured;\n }\n return null;\n }\n // This separate, legacy cold-context API returns one React root.\n // It does not determine the scope or membership of the watch stream.\n current = roots[0]?.current ?? null;\n }\n if (!current) return null;\n if (typeof targetLayerSourceId !== \"string\") {\n let root = current;\n while (root.return) root = root.return;\n const container = (root.stateNode as FiberRoot | null)?.containerInfo;\n if (\n container &&\n (container === target.element || target.element.contains(container))\n )\n current = root;\n }\n return captureProjectionSemanticSubtree(\n current,\n targetLayerSourceId,\n {\n fiberId: serializer.fiberId,\n knownFiberId: serializer.knownFiberId,\n },\n options,\n );\n },\n };\n}\n\n/** A selector names a DOM endpoint, but one React component can return several\n * sibling endpoints. Their nearest shared committed Fiber is the only capture\n * root that can describe the whole watched slot without inventing its hidden\n * host wrapper as a user layer. */\nfunction resolveFullCaptureFiber(\n root: Element,\n fiberTarget: Element | null,\n): Fiber | null {\n const firstRaw = fiberTarget ? getFiberFromElement(fiberTarget) : null;\n if (!firstRaw) return null;\n const first = resolveCommittedFiber(firstRaw);\n // A nested selector names a narrower authored slot. Only direct endpoints\n // can be sibling returns of the component that owns the watched root.\n if (!fiberTarget || fiberTarget.parentElement !== root)\n return ascendToAnnotatedComponentRoot(first);\n const others: Fiber[] = [];\n for (const endpoint of Array.from(root.childNodes)) {\n if (endpoint === fiberTarget) continue;\n // Loose text beside the endpoint is part of the same return; text\n // nothing rendered has no fiber and is skipped below.\n const isText = endpoint.nodeType === 3;\n const isElement = endpoint instanceof Element;\n if (!isText && !isElement) continue;\n if (isElement && endpoint.getAttribute(\"data-tempo-hide-fiber\") === \"true\")\n continue;\n const raw = getFiberFromElement(endpoint as Element);\n if (!raw) continue;\n const committed = resolveCommittedFiber(raw);\n others.push(committed);\n }\n if (others.length === 0) return ascendToAnnotatedComponentRoot(first);\n // A createRoot container owns the entire return, including a fragment\n // flattened into sibling fibers. Its HostRoot is a valid content boundary\n // only when that container is exactly the watched element.\n const boundaryRaw = getFiberFromElement(root);\n const boundary = boundaryRaw ? resolveCommittedFiber(boundaryRaw) : null;\n const ownsContainer =\n boundary?.tag === FiberTag.HostRoot &&\n (boundary.stateNode as FiberRoot).containerInfo === root;\n // Siblings belong to the same return when they share a fiber below the\n // watched root's own: the body's returns are its direct children whatever\n // file each one's host is stamped from (a library component's host carries\n // that library's file; the sibling beside it carries the body's). The\n // watched root and everything above it never describe the slot's content.\n const common = [first, ...ancestorFibers(first)].find(\n (candidate) =>\n (boundary === null || !fiberOrAncestor(boundary, candidate)) &&\n others.every((fiber) => fiberOrAncestor(fiber, candidate)),\n );\n return ascendToAnnotatedComponentRoot(\n common ?? (ownsContainer ? boundary : first),\n );\n}\n\nfunction ancestorFibers(fiber: Fiber): Fiber[] {\n const ancestors: Fiber[] = [];\n for (let parent = fiber.return; parent; parent = parent.return) {\n ancestors.push(parent);\n }\n return ancestors;\n}\n\nfunction fiberOrAncestor(fiber: Fiber, candidate: Fiber): boolean {\n for (let current: Fiber | null = fiber; current; current = current.return) {\n if (\n current === candidate ||\n current.alternate === candidate ||\n current === candidate.alternate\n )\n return true;\n }\n return false;\n}\n\n/**\n * A runtime the observed adapter can hand a root to, besides React, and what\n * the prefix walk does with that runtime's elements. Each decision is the\n * probe's own; none follows from where it sits in the list.\n */\ninterface ObservedRuntimeProbe {\n readonly adapter: ProjectionLayerAdapter;\n /** The runtime's own mount metadata on this element of the prefix: the\n * walk stops and the root is this runtime's. */\n claims(element: Element): boolean;\n /** An element the runtime's mount writes beside its content that holds no\n * content of its own (Svelte's source-registry `<template>`). The walk is\n * transparent to it: it never descends into one. */\n isTransparent(element: Element): boolean;\n /** Keeps an already-active runtime in charge of its own authored file once\n * its metadata is gone, so the loss stays its typed problem instead of a\n * silent fall back to React. */\n authorsFile(filepath: string): boolean;\n}\n\n/**\n * Observation is source-owned. Keep each serializer for the root's lifetime so\n * temporarily switching authority never reuses an id for a different element.\n * A runtime's own metadata, not the presence of an installed framework,\n * identifies its root; explicit legacy requests still retain their failure\n * contract. React is the fallback: an authored host ends the prefix walk, so\n * a committed React tree keeps its root, and a Vue or Svelte island below an\n * authored React root is never that root's authority.\n */\nfunction createObservedLayerAdapter(\n watchedRoot: Element,\n scope?: \"contents\" | \"subtree\",\n): ProjectionLayerAdapter {\n const react = createReactLayerAdapter(watchedRoot, scope);\n // An Astro document belongs to the Astro adapter, which hands each island to\n // its renderer's serializer itself; the probes only decide other documents.\n const astro = createProjectionLayerAdapter(\"astro\", watchedRoot, scope);\n // An SDK mount never marks one element for both runtimes: a Vue app's\n // container is React's mount div, Svelte's metadata sits on what Svelte\n // renders. Only a hand-mounted app could; then the earlier probe claims it.\n const probes: readonly ObservedRuntimeProbe[] = [\n {\n adapter: createProjectionLayerAdapter(\"vue\", watchedRoot, scope),\n // `__vue_app__` marks a mounted app's container in every build.\n claims: isVueAppContainer,\n // A Vue mount writes nothing beside the app's container.\n isTransparent: () => false,\n authorsFile: (filepath) => filepath.endsWith(\".vue\"),\n },\n {\n adapter: createProjectionLayerAdapter(\"svelte\", watchedRoot, scope),\n claims: (element) => readSvelteElementMetadata(element) !== null,\n isTransparent: (element) =>\n element.hasAttribute(TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE),\n authorsFile: (filepath) => filepath.endsWith(\".svelte\"),\n },\n ];\n let active = react;\n return {\n portalClosure: (fiber) =>\n active.portalClosure?.(fiber) ?? { required: false, nodesVisited: 0 },\n get layerFramework() {\n return active.layerFramework;\n },\n get retainDomMutationTargets() {\n return active.retainDomMutationTargets;\n },\n readProblem: (root) => active.readProblem(root),\n observeBaselineRequests(request) {\n const stops = [react, astro, ...probes.map((probe) => probe.adapter)].map(\n (adapter) =>\n adapter.observeBaselineRequests?.(() => {\n if (active === adapter) request();\n }),\n );\n return () => {\n for (const stop of stops) stop?.();\n };\n },\n captureFull: (root, target, files) =>\n active.captureFull(root, target, files),\n capturePatch: (root, targets, files) =>\n active.capturePatch(root, targets, files),\n resolveCommittedRoot(fiberRoot, target) {\n active = trackAstroSources(target.element.ownerDocument).hasAstro()\n ? astro\n : (probeTransparentPrefix(target.element, probes, active) ?? react);\n return active.resolveCommittedRoot(fiberRoot, target);\n },\n resolveElementCandidate: (element) =>\n active.resolveElementCandidate(element),\n layerSourceId: (fiber) => active.layerSourceId(fiber),\n captureRegion: (fiber) => active.captureRegion(fiber),\n captureMetadata: (fiber, options) => active.captureMetadata(fiber, options),\n captureSemanticSubtree: (target, id, options) =>\n active.captureSemanticSubtree(target, id, options),\n };\n}\n\n/**\n * The SDK mounts Vue and Svelte beneath unannotated React host wrappers\n * (`data-tempo-hide-fiber`, no stamps). Follow only that prefix: the first\n * element a probe claims names the runtime, the first authored host ends the\n * walk (React's, unless the active runtime authors its file), and each step\n * descends into the first child no probe is transparent to.\n */\nfunction probeTransparentPrefix(\n root: Element,\n probes: readonly ObservedRuntimeProbe[],\n active: ProjectionLayerAdapter,\n): ProjectionLayerAdapter | null {\n let element: Element | undefined = root;\n while (element) {\n const current: Element = element;\n const claimed = probes.find((probe) => probe.claims(current));\n if (claimed) return claimed.adapter;\n const filepath = current.getAttribute(\"data-tempo-filepath\");\n if (filepath && current.hasAttribute(\"data-tempo-position\")) {\n // Metadata loss remains a typed failure for this authored root,\n // but replacing it with an authored React root changes authority.\n const keeper = probes.find(\n (probe) => probe.adapter === active && probe.authorsFile(filepath),\n );\n return keeper?.adapter ?? null;\n }\n element = Array.from(current.children).find(\n (child) => !probes.some((probe) => probe.isTransparent(child)),\n );\n }\n return null;\n}\n\nfunction createDomBackedLayerAdapter(\n layerFramework: \"svelte\" | \"vue\" | \"astro\" | \"dom\",\n serializer: ProjectionDomLayerSerializer,\n readProblem: (root: Element) => CombinedProjectionProblem | null,\n scope?: \"contents\" | \"subtree\",\n): ProjectionLayerAdapter {\n return {\n layerFramework,\n retainDomMutationTargets: true,\n readProblem,\n observeBaselineRequests:\n serializer.observeBaselineRequests?.bind(serializer),\n captureFull(root, _fiberTarget, observedFiles) {\n const snapshot = serializer.serializeRoot(root, observedFiles);\n return {\n snapshot:\n scope !== undefined\n ? contentsSnapshot(snapshot, scope === \"subtree\")\n : snapshot,\n fiberNodesVisited: 0,\n semanticNodesSerialized: countLayerNodes(snapshot),\n };\n },\n capturePatch: (root, targets, files) =>\n normalizeContentsPatch(\n serializer.capturePatch(root, targets, files),\n scope,\n ),\n resolveCommittedRoot: () => null,\n resolveElementCandidate: () => null,\n layerSourceId: () => null,\n captureRegion: () => null,\n captureMetadata: () => null,\n captureSemanticSubtree(target, id, options) {\n if (layerFramework !== \"astro\") return null;\n type Node = import(\"./projection-layer-snapshot\").ProjectionLayerNode;\n const roots = projectionLayerRoots(\n serializer.serializeRoot(target.element),\n );\n const find = (nodes: readonly Node[]): Node | undefined => {\n for (const node of nodes) {\n if (node.id === id) return node;\n const child = find(node.children ?? []);\n if (child) return child;\n }\n };\n const selected = typeof id === \"string\" ? find(roots) : roots[0];\n if (!selected) return null;\n let count = 0;\n const serialize = (\n node: Node,\n parent: string | null,\n ): DetachSerializedFiber => {\n count++;\n // Transport source facts only. Astro.props stays on the server; the\n // checked source planner specializes authored literals when detaching.\n const props = Object.fromEntries(\n Object.entries(node.props ?? {}).filter(\n ([name, value]) =>\n name.startsWith(\"data-tempo-\") &&\n [\"string\", \"number\", \"boolean\"].includes(typeof value),\n ),\n ) as DetachSerializedFiber[\"props\"];\n const file = props[\"data-tempo-filepath\"],\n position = Number(props[\"data-tempo-position\"]);\n return {\n fiber_id: node.id,\n name: node.name ?? \"#text\",\n tag: node.kind === \"component\" ? \"function\" : node.kind,\n owner_fiber_id: parent,\n props:\n node.content === undefined\n ? props\n : { ...props, text: node.content },\n ...(typeof file === \"string\" && Number.isSafeInteger(position)\n ? { source: { file, position } }\n : {}),\n children:\n options?.descendants === false || count > 5000\n ? []\n : (node.children ?? []).map((child) => serialize(child, node.id)),\n };\n };\n const captured = serialize(selected, null);\n return { ...captured, ...(count > 5000 ? { truncated: true } : {}) };\n },\n };\n}\n\nfunction countLayerNodes(snapshot: ProjectionLayerRootSnapshot): number {\n const visit = (\n node: import(\"./projection-layer-snapshot\").ProjectionLayerNode,\n ): number =>\n 1 + (node.children ?? []).reduce((total, child) => total + visit(child), 0);\n return projectionLayerRoots(snapshot).reduce(\n (sum, node) => sum + visit(node),\n 0,\n );\n}\n\nfunction resolveWatchedCommittedFiber(\n fiberRoot: FiberRoot | undefined,\n target: ProjectionLayerTarget,\n): Fiber | null {\n if (target.scope !== undefined) {\n const current = resolveScopeFiber(target.element);\n if (!current || !fiberRoot) return current;\n let top = current;\n while (top.return) top = top.return;\n return top === fiberRoot.current || top === fiberRoot.current.alternate\n ? current\n : null;\n }\n // Search only this root's subtree. The root itself wins when descendants\n // share its selector (Canvas and mounted storyboard shells do).\n const element = target.fiberSelector\n ? target.element.matches(target.fiberSelector)\n ? target.element\n : target.element.querySelector(target.fiberSelector)\n : (target.element.firstElementChild ?? target.element);\n if (!element) return null;\n if (\n fiberRoot &&\n (fiberRoot.containerInfo === element ||\n element.contains(fiberRoot.containerInfo))\n ) {\n return fiberRoot.current;\n }\n let committed: Fiber | null;\n try {\n committed = resolveFullCaptureFiber(target.element, element);\n } catch (error) {\n if (isTransientFiberResolutionError(error)) return null;\n throw error;\n }\n if (!committed) return null;\n if (!fiberRoot) return committed;\n let root = committed;\n while (root.return) root = root.return;\n return root === fiberRoot.current || root === fiberRoot.current.alternate\n ? committed\n : null;\n}\n\nexport function resolveCommittedFiberOrNull(fiber: Fiber): Fiber | null {\n try {\n return resolveCommittedFiber(fiber);\n } catch (error) {\n if (!isTransientFiberResolutionError(error)) throw error;\n return null;\n }\n}\n\nfunction resolveScopeFiber(root: Element): Fiber | null {\n const raw = getFiberFromElement(root);\n return raw ? resolveCommittedFiberOrNull(raw) : null;\n}\nfunction contentsSnapshot(\n snapshot: ProjectionLayerRootSnapshot,\n includeRoot = false,\n): ProjectionLayerRootSnapshot {\n if (snapshot.semantic.kind !== \"layers\") return snapshot;\n const tree = snapshot.semantic.tree;\n return {\n ...snapshot,\n semantic: {\n kind: \"scope\",\n fragment: {\n kind: \"fragment\",\n children: tree\n ? !includeRoot && tree.kind === \"fragment\"\n ? tree.children\n : [tree]\n : [],\n },\n },\n };\n}\n\nfunction normalizeContentsPatch(\n patch: ProjectionLayerPatch | undefined,\n scope?: \"contents\" | \"subtree\",\n): ProjectionLayerPatch | undefined {\n if (!patch || scope === undefined) return patch;\n return {\n ...patch,\n regions: patch.regions?.map((region) =>\n region.targetFiberId === DOM_LAYER_ROOT_ID ||\n region.targetFiberId === SVELTE_LAYER_ROOT_ID ||\n region.targetFiberId === VUE_LAYER_ROOT_ID ||\n region.targetFiberId === ASTRO_LAYER_ROOT_ID\n ? {\n ...region,\n targetId: PROJECTION_SCOPE_TARGET,\n tree: null,\n scope: {\n kind: \"fragment\",\n children:\n scope === \"subtree\"\n ? region.tree\n ? [region.tree]\n : []\n : (region.tree?.children ?? []),\n },\n }\n : region,\n ),\n };\n}\n","import type {\n CombinedProjectionBatch,\n CombinedProjectionProblem,\n} from \"./projection-batch\";\nimport type { ProjectionFullSnapshot } from \"./projection-full-snapshot\";\nimport type { ProjectionRootPatch } from \"./projection-root-accumulator\";\nimport type { ProjectionProducerTrigger } from \"./types\";\n\nexport const PROJECTION_FLUSH_WINDOW_MS = 500;\n\ntype Stop = () => void;\n\nexport interface ProjectionFlushTiming {\n readonly flushStartedAt: number;\n readonly flushIntervalMs: number | null;\n readonly fixedWindowTimersOpened: number;\n readonly maxSimultaneousTimers: number;\n}\n\nexport interface ProjectionProducerFlushContext extends ProjectionFlushTiming {\n readonly candidateRootCount: number;\n readonly initialForSession: boolean;\n readonly fullRequested: boolean;\n readonly triggerReasons: readonly ProjectionProducerTrigger[];\n}\n\nexport interface ProjectionProducerScheduler {\n now(): number;\n schedule(callback: () => void, delayMs: number): Stop;\n}\n\ntype CapturedRoot =\n | {\n readonly kind: \"full\";\n readonly snapshot: ProjectionFullSnapshot;\n readonly unchanged?: boolean;\n }\n | { readonly kind: \"patch\"; readonly patch: ProjectionRootPatch }\n | { readonly kind: \"problem\"; readonly problem: CombinedProjectionProblem }\n | null;\n\ninterface OutboxOptions {\n readonly scheduler?: ProjectionProducerScheduler;\n readonly flushWindowMs?: number;\n /** Bound background serialization per turn. Root registration schedules its\n * baseline; explicit requests still flush immediately ahead of siblings. */\n readonly maxRootsPerFlush?: number;\n /**\n * Keep the scheduler armed after every flush while a session has roots,\n * instead of arming it on the first record after a flush. With a flush\n * on the animation frame this makes the flush the frame's: a mutation\n * made in the frame's own callbacks (a rAF-driven animation) is sent in\n * that frame, where arming on the record would send it in the next. An\n * armed callback that finds nothing pending costs nothing; a timer\n * window should not use it.\n */\n readonly keepArmed?: boolean;\n readonly onError?: (error: unknown) => void;\n captureRoot(\n rootId: string,\n context: ProjectionProducerFlushContext,\n ): CapturedRoot;\n prepareHead?(context: {\n initialForSession: boolean;\n triggerReasons: readonly ProjectionProducerTrigger[];\n }): Promise<void> | undefined;\n /** A completed prepared head may precede mutations received during its work.\n * Retain those as a following head update rather than discarding that work. */\n hasPendingHead?(): boolean;\n captureHead(context: ProjectionProducerFlushContext): string | undefined;\n /** The document's module version facts for this batch: every record when\n * the batch carries a full, otherwise the ones that changed. Reading them\n * forgets nothing; the producer does that when the batch is emitted. */\n captureModules?(\n includesFull: boolean,\n ): CombinedProjectionBatch[\"modules\"] | undefined;\n emit(batch: CombinedProjectionBatch): void;\n}\n\nexport interface ProjectionOutbox {\n /** Emit an explicitly requested regional repair even while its failed\n * predecessor owes credit. The repair still uses the same sequence stream. */\n requestRepair(rootId: string): void;\n bindSession(sessionId: string): void;\n addRoot(\n rootId: string,\n receiverCredit?: boolean,\n userInitiated?: boolean,\n knownHead?: { readonly sessionId: string; readonly headRevision: number },\n ): void;\n removeRoot(rootId: string): void;\n setRootSize(rootId: string, size: { width: number; height: number }): void;\n record(activity: {\n readonly rootIds?: readonly string[];\n readonly head?: boolean;\n readonly assetRootIds?: readonly string[];\n /** Module version facts changed; they flush even with no DOM change. */\n readonly modules?: boolean;\n readonly trigger?: ProjectionProducerTrigger;\n }): void;\n /** One current self-contained baseline for one root. `includeHead` also\n * re-sends the document head to that root's lane without making healthy\n * sibling roots reload it. */\n requestFull(\n rootId: string,\n options?: {\n readonly includeHead?: boolean;\n readonly trigger?: ProjectionProducerTrigger;\n },\n ): void;\n /**\n * The far end committed the batch `sequence` of `sessionId` for `rootId`.\n * From a root's first acknowledgement on, that root's patches are\n * credit-gated: one patch in flight, the next flushed only once the\n * previous is acknowledged, so a slow far end receives fewer, larger\n * patches (the accumulator keeps reducing to final state) instead of a\n * backlog. A root nobody acknowledges is never gated. A full always goes\n * out and resets the root's credit: it is the recovery path.\n */\n acknowledge(sessionId: string, rootId: string, sequence: number): void;\n stop(): void;\n}\n\nconst defaultScheduler: ProjectionProducerScheduler = {\n now: () =>\n typeof performance === \"undefined\" ? Date.now() : performance.now(),\n schedule(callback, delayMs) {\n const timer = setTimeout(callback, delayMs);\n return () => clearTimeout(timer);\n },\n};\n\nexport interface ProjectionFixedWindow {\n schedule(): void;\n flushNow(): void;\n cancel(): void;\n reset(): void;\n stop(): void;\n}\n\n/** @internal One non-resetting timer shared by live and static sources. */\nexport function createProjectionFixedWindow(options: {\n readonly scheduler?: ProjectionProducerScheduler;\n readonly flushWindowMs?: number;\n hasPending(): boolean;\n /** Arm the next window after this one whether or not work is pending. */\n keepArmed?(): boolean;\n flush(timing: ProjectionFlushTiming): void;\n}): ProjectionFixedWindow {\n const scheduler = options.scheduler ?? defaultScheduler;\n const windowMs = options.flushWindowMs ?? PROJECTION_FLUSH_WINDOW_MS;\n if (windowMs < 0) throw new Error(\"flushWindowMs must be non-negative\");\n let cancelTimer: Stop | undefined;\n let stopped = false;\n let flushing = false;\n let flushAgain = false;\n let timersOpened = 0;\n let lastFlushAt: number | null = null;\n\n const cancel = () => {\n cancelTimer?.();\n cancelTimer = undefined;\n };\n const schedule = () => {\n if (stopped || cancelTimer) return;\n if (!options.hasPending() && !options.keepArmed?.()) return;\n timersOpened += 1;\n cancelTimer = scheduler.schedule(() => {\n cancelTimer = undefined;\n flushNow();\n }, windowMs);\n };\n // Every flush, scheduled or explicit, ends by arming the next window\n // while the caller wants it armed; nothing else owns the re-arm.\n function flushNow(): void {\n cancel();\n if (flushing) {\n flushAgain = true;\n return;\n }\n if (!stopped && options.hasPending()) {\n flushing = true;\n do {\n flushAgain = false;\n const now = scheduler.now();\n const timing: ProjectionFlushTiming = {\n flushStartedAt: Date.now(),\n flushIntervalMs: lastFlushAt === null ? null : now - lastFlushAt,\n fixedWindowTimersOpened: timersOpened,\n maxSimultaneousTimers: timersOpened > 0 ? 1 : 0,\n };\n lastFlushAt = now;\n timersOpened = 0;\n options.flush(timing);\n } while (flushAgain && !stopped && options.hasPending());\n flushing = false;\n }\n if (options.keepArmed?.()) schedule();\n }\n\n return {\n schedule,\n flushNow,\n cancel,\n reset() {\n cancel();\n timersOpened = 0;\n lastFlushAt = null;\n },\n stop() {\n stopped = true;\n cancel();\n },\n };\n}\n\n/** @internal Ordered outbox for the one live-document producer. */\nexport function createProjectionOutbox(\n options: OutboxOptions,\n): ProjectionOutbox {\n const rootLimit = options.maxRootsPerFlush ?? Infinity;\n if (rootLimit < 1 || (rootLimit !== Infinity && !Number.isInteger(rootLimit)))\n throw new Error(\"maxRootsPerFlush must be a positive integer\");\n const roots = new Set<string>();\n const headProofRoots = new Set<string>();\n const dirty = new Set<string>();\n const full = new Set<string>();\n const requested = new Set<string>();\n const foregroundRoots = new Set<string>();\n const assets = new Set<string>();\n const sizes = new Map<string, { width: number; height: number }>();\n const emittedSizes = new Map<string, { width: number; height: number }>();\n let dirtyHead = false;\n let dirtyModules = false;\n const dirtyHeadRoots = new Set<string>();\n const triggerReasons = new Set<ProjectionProducerTrigger>();\n let sessionId: string | undefined;\n let sequence = 0;\n // Credit: the sequence of the patch each root has in flight, and the\n // roots the far end has acknowledged at least once (see acknowledge).\n const awaitingAck = new Map<string, number>();\n const credited = new Set<string>();\n const requiredCredit = new Set<string>();\n let revision = 0;\n const rootRevisions = new Map<string, number>();\n let headRevision = 0;\n let lastHead: string | undefined;\n let preparingHead = false;\n let headPrepared = false;\n let stopped = false;\n let fixedWindow: ProjectionFixedWindow;\n\n const sizePending = (rootId: string): boolean => {\n const size = sizes.get(rootId);\n const emitted = emittedSizes.get(rootId);\n return (\n size !== undefined &&\n (size.width !== emitted?.width || size.height !== emitted?.height)\n );\n };\n const gated = (rootId: string): boolean =>\n credited.has(rootId) && awaitingAck.has(rootId) && !full.has(rootId);\n const hasWork = () =>\n !preparingHead &&\n roots.size > 0 &&\n (dirtyHead ||\n dirtyModules ||\n dirtyHeadRoots.size > 0 ||\n [...dirty].some((rootId) => !gated(rootId)) ||\n assets.size > 0 ||\n [...roots].some(sizePending));\n const report = (error: unknown) => {\n try {\n options.onError?.(error);\n } catch {\n // Reporting cannot break recovery or cleanup.\n }\n };\n const assertActive = () => {\n if (stopped) throw new Error(\"Projection producer has been stopped\");\n };\n\n const restore = (\n failedSession: string,\n rootIds: readonly string[],\n includeHeadForAllRoots: boolean,\n headRootIds: readonly string[],\n failedTriggers: readonly ProjectionProducerTrigger[],\n ) => {\n if (stopped || sessionId !== failedSession) return;\n for (const rootId of rootIds) {\n if (!roots.has(rootId)) continue;\n dirty.add(rootId);\n // Capture drains source-local candidates, so an unsent patch can only be\n // retried honestly as a current baseline.\n full.add(rootId);\n }\n dirtyHead ||= includeHeadForAllRoots;\n if (!dirtyHead) {\n for (const rootId of headRootIds) {\n if (roots.has(rootId)) dirtyHeadRoots.add(rootId);\n }\n }\n for (const trigger of failedTriggers) triggerReasons.add(trigger);\n triggerReasons.add(\"retry-after-error\");\n fixedWindow.schedule();\n };\n\n const flushOnce = (timing: ProjectionFlushTiming) => {\n const activeSession = sessionId;\n if (stopped || !activeSession || !hasWork()) return;\n if (!headPrepared && (dirtyHead || dirtyHeadRoots.size > 0)) {\n try {\n const preparation = options.prepareHead?.({\n initialForSession: sequence === 0,\n triggerReasons: [...triggerReasons],\n });\n if (preparation) {\n preparingHead = true;\n void preparation.then(\n () => {\n preparingHead = false;\n headPrepared = true;\n if (!stopped) fixedWindow.flushNow();\n },\n (error) => {\n preparingHead = false;\n if (!stopped) {\n report(error);\n fixedWindow.schedule();\n }\n },\n );\n return;\n }\n } catch (error) {\n report(error);\n fixedWindow.schedule();\n return;\n }\n }\n headPrepared = false;\n // An explicitly requested baseline must not pay for every unrelated dirty\n // root. Preserve their candidates for the next normal opportunity.\n const requestedRoots = [...requested].filter((rootId) => dirty.has(rootId));\n const rootIds = (requestedRoots.length ? requestedRoots : [...dirty])\n .filter((rootId) => !gated(rootId))\n .slice(0, rootLimit);\n const fullRootIds = new Set(full);\n const includeHeadForAllRoots = dirtyHead;\n const headRootIds = includeHeadForAllRoots ? [] : [...dirtyHeadRoots];\n const includeHead = includeHeadForAllRoots || headRootIds.length > 0;\n const currentTriggers = [...triggerReasons];\n const assetRootIds = [...assets];\n assets.clear();\n const context: ProjectionProducerFlushContext = {\n ...timing,\n candidateRootCount: rootIds.length,\n initialForSession: sequence === 0,\n fullRequested: false,\n triggerReasons: currentTriggers,\n };\n for (const rootId of rootIds) {\n dirty.delete(rootId);\n full.delete(rootId);\n requested.delete(rootId);\n }\n dirtyHead = false;\n const includeModules = dirtyModules;\n dirtyModules = false;\n dirtyHeadRoots.clear();\n triggerReasons.clear();\n\n try {\n // Carry missed pixel-only changes into the next full baseline too. The\n // ordinary asset-only message still leaves HTML capture reuse alone.\n for (const rootId of assetRootIds) {\n if (roots.has(rootId)) rootRevisions.set(rootId, ++revision);\n }\n const changes: CombinedProjectionBatch[\"roots\"][number][] = [];\n for (const rootId of rootIds) {\n if (!roots.has(rootId)) continue;\n const captured = options.captureRoot(rootId, {\n ...context,\n fullRequested: fullRootIds.has(rootId),\n });\n if (!roots.has(rootId) || !captured) continue;\n if (\n captured.kind !== \"full\" ||\n !captured.unchanged ||\n !rootRevisions.has(rootId)\n )\n rootRevisions.set(rootId, ++revision);\n const contentRevision = rootRevisions.get(rootId)!;\n if (captured.kind === \"full\") {\n changes.push({\n rootId,\n contentRevision,\n kind: \"full\",\n snapshot: captured.snapshot,\n });\n } else {\n changes.push({ rootId, contentRevision, ...captured });\n }\n }\n if (stopped || sessionId !== activeSession) return;\n const emittedHeadRootIds = includeHeadForAllRoots ? [] : headRootIds;\n const shouldCaptureHead = includeHead;\n const head = shouldCaptureHead ? options.captureHead(context) : undefined;\n if (stopped || sessionId !== activeSession) return;\n // CSSOM/resource observations may change paint without changing the\n // serialized head. A scoped baseline alone is not such evidence.\n if (head !== undefined && (head !== lastHead || includeHeadForAllRoots)) {\n lastHead = head;\n headRevision = ++revision;\n }\n if (shouldCaptureHead && options.hasPendingHead?.()) {\n dirtyHead = true;\n fixedWindow.schedule();\n }\n const includesFull = changes.some((change) => change.kind === \"full\");\n const modules =\n includeModules || includesFull\n ? options.captureModules?.(includesFull)\n : undefined;\n const pendingSizeRootIds = [...roots].filter(sizePending);\n const fullSizeRootIds = changes\n .filter((change) => change.kind === \"full\")\n .map((change) => change.rootId);\n const batchSizes: Record<string, { width: number; height: number }> =\n Object.create(null);\n for (const rootId of [...pendingSizeRootIds, ...fullSizeRootIds]) {\n const size = sizes.get(rootId);\n if (roots.has(rootId) && size) batchSizes[rootId] = size;\n }\n if (\n Object.keys(batchSizes).length === 0 &&\n changes.length === 0 &&\n head === undefined &&\n assetRootIds.length === 0 &&\n modules === undefined\n )\n return;\n const emittedSequence = sequence;\n options.emit({\n sessionId: activeSession,\n sequence: emittedSequence,\n ...(head === undefined ? {} : { head, headRevision }),\n ...(head === undefined &&\n changes.some(\n (root) => root.kind === \"full\" && headProofRoots.has(root.rootId),\n )\n ? { headRevision }\n : {}),\n ...(head !== undefined && emittedHeadRootIds.length > 0\n ? { headRootIds: emittedHeadRootIds }\n : {}),\n roots: changes,\n ...(Object.keys(batchSizes).length > 0 ? { sizes: batchSizes } : {}),\n ...(assetRootIds.length > 0 ? { assetRootIds } : {}),\n ...(modules ? { modules } : {}),\n });\n if (sessionId === activeSession && sequence === emittedSequence) {\n sequence += 1;\n for (const [rootId, size] of Object.entries(batchSizes)) {\n if (!roots.has(rootId)) continue;\n emittedSizes.set(rootId, size);\n }\n for (const change of changes) {\n // A problem is not a DOM commit the receiver can acknowledge. If a\n // recovery full superseded an in-flight patch but captured a problem,\n // release that old debt too so the healthy retry can be captured.\n if (change.kind === \"problem\") {\n awaitingAck.delete(change.rootId);\n continue;\n }\n if (change.kind === \"patch\" || credited.has(change.rootId))\n awaitingAck.set(change.rootId, emittedSequence);\n else awaitingAck.delete(change.rootId);\n }\n }\n } catch (error) {\n if (sessionId === activeSession) {\n for (const id of assetRootIds) if (roots.has(id)) assets.add(id);\n // The producer forgets module facts only once a batch is emitted.\n dirtyModules ||= includeModules;\n }\n report(error);\n restore(\n activeSession,\n rootIds,\n includeHeadForAllRoots,\n headRootIds,\n currentTriggers,\n );\n }\n if (rootLimit !== Infinity && hasWork()) fixedWindow.schedule();\n };\n\n fixedWindow = createProjectionFixedWindow({\n scheduler: options.scheduler,\n flushWindowMs: options.flushWindowMs,\n hasPending: hasWork,\n keepArmed: () =>\n options.keepArmed === true && sessionId !== undefined && roots.size > 0,\n flush: flushOnce,\n });\n\n return {\n bindSession(nextSessionId) {\n assertActive();\n if (!nextSessionId)\n throw new Error(\"Projection session ID must not be empty\");\n if (sessionId === nextSessionId) return;\n fixedWindow.reset();\n awaitingAck.clear();\n credited.clear();\n for (const rootId of requiredCredit) credited.add(rootId);\n emittedSizes.clear();\n dirty.clear();\n requested.clear();\n assets.clear();\n full.clear();\n dirtyHeadRoots.clear();\n triggerReasons.clear();\n dirtyHead = true;\n triggerReasons.add(\"session-bind\");\n sessionId = nextSessionId;\n sequence = 0;\n for (const rootId of roots.keys()) {\n dirty.add(rootId);\n full.add(rootId);\n if (foregroundRoots.has(rootId)) requested.add(rootId);\n }\n fixedWindow.schedule();\n },\n addRoot(rootId, receiverCredit = false, userInitiated = false, knownHead) {\n assertActive();\n if (!rootId) throw new Error(\"Projection root ID must not be empty\");\n if (roots.has(rootId)) return;\n roots.add(rootId);\n if (knownHead) headProofRoots.add(rootId);\n if (userInitiated) foregroundRoots.add(rootId);\n if (receiverCredit) {\n requiredCredit.add(rootId);\n credited.add(rootId);\n }\n if (!sessionId) return;\n dirty.add(rootId);\n full.add(rootId);\n triggerReasons.add(\"root-added\");\n // A root that joined after the last head emission has no copy of the\n // document head. Re-send it only to that root; existing sibling lanes\n // already hold the document-global state.\n if (\n !dirtyHead &&\n (!knownHead ||\n knownHead.sessionId !== sessionId ||\n knownHead.headRevision !== headRevision)\n )\n dirtyHeadRoots.add(rootId);\n if (userInitiated) {\n requested.add(rootId);\n fixedWindow.flushNow();\n } else if (sequence === 0 || rootLimit !== Infinity)\n fixedWindow.schedule();\n else fixedWindow.flushNow();\n },\n setRootSize(rootId, size) {\n assertActive();\n const previous = sizes.get(rootId);\n if (previous?.width === size.width && previous.height === size.height)\n return;\n sizes.set(rootId, size);\n if (sessionId) fixedWindow.schedule();\n },\n removeRoot(rootId) {\n foregroundRoots.delete(rootId);\n if (stopped) return;\n sizes.delete(rootId);\n emittedSizes.delete(rootId);\n roots.delete(rootId);\n headProofRoots.delete(rootId);\n rootRevisions.delete(rootId);\n awaitingAck.delete(rootId);\n credited.delete(rootId);\n requiredCredit.delete(rootId);\n dirty.delete(rootId);\n requested.delete(rootId);\n assets.delete(rootId);\n full.delete(rootId);\n dirtyHeadRoots.delete(rootId);\n if (!hasWork()) {\n if (roots.size === 0) {\n fixedWindow.cancel();\n dirtyHead = false;\n dirtyModules = false;\n }\n triggerReasons.clear();\n }\n },\n record(activity) {\n // The document can outlive its last observed root. A later root gets a\n // fresh head in its baseline; publishing here would have no receiver.\n if (stopped || !sessionId || roots.size === 0) return;\n dirtyHead ||= activity.head === true;\n dirtyModules ||= activity.modules === true;\n for (const id of activity.assetRootIds ?? [])\n if (roots.has(id)) assets.add(id);\n for (const rootId of activity.rootIds ?? []) {\n if (roots.has(rootId)) dirty.add(rootId);\n }\n triggerReasons.add(activity.trigger ?? \"dom-mutation\");\n fixedWindow.schedule();\n },\n requestRepair(rootId) {\n assertActive();\n if (!sessionId || !roots.has(rootId)) return;\n awaitingAck.delete(rootId);\n dirty.add(rootId);\n requested.add(rootId);\n triggerReasons.add(\"receiver-baseline\");\n fixedWindow.flushNow();\n },\n requestFull(rootId, options) {\n assertActive();\n if (!sessionId || !roots.has(rootId)) return;\n dirty.add(rootId);\n requested.add(rootId);\n full.add(rootId);\n triggerReasons.add(options?.trigger ?? \"receiver-baseline\");\n if (options?.includeHead && !dirtyHead) dirtyHeadRoots.add(rootId);\n fixedWindow.flushNow();\n if (hasWork()) fixedWindow.schedule();\n },\n acknowledge(ackSessionId, rootId, ackSequence) {\n if (\n stopped ||\n !sessionId ||\n ackSessionId !== sessionId ||\n !roots.has(rootId)\n )\n return;\n credited.add(rootId);\n if (awaitingAck.get(rootId) !== ackSequence) return;\n awaitingAck.delete(rootId);\n if (dirty.has(rootId)) fixedWindow.schedule();\n },\n stop() {\n if (stopped) return;\n stopped = true;\n fixedWindow.stop();\n roots.clear();\n headProofRoots.clear();\n foregroundRoots.clear();\n sizes.clear();\n emittedSizes.clear();\n rootRevisions.clear();\n awaitingAck.clear();\n credited.clear();\n requiredCredit.clear();\n lastHead = undefined;\n assets.clear();\n dirty.clear();\n requested.clear();\n full.clear();\n dirtyHeadRoots.clear();\n dirtyHead = false;\n triggerReasons.clear();\n sessionId = undefined;\n },\n };\n}\n","/**\n * Portal Tracker\n *\n * Watches document.body for new subtrees and determines which watched element\n * (if any) they belong to by walking up the React fiber ancestry.\n *\n * ## How it works\n *\n * React portals render content outside their component's DOM location, but the\n * fiber tree maintains the logical parent-child relationship. When a new element\n * appears in body:\n *\n * 1. Get its fiber via getFiberFromElement\n * 2. Walk up fiber.return chain, collecting DOM nodes from stateNode\n * 3. Check if any collected DOM node is within a registered watcher's element\n * 4. If yes, notify that watcher\n *\n * ## Usage\n *\n * ```ts\n * const tracker = getPortalTracker();\n * const unregister = tracker.register({\n * element: myWatchedElement,\n * onPortalFound: (portalRoot) => startWatchingPortal(portalRoot),\n * onPortalRemoved: (portalRoot) => stopWatchingPortal(portalRoot),\n * });\n * ```\n */\n\nimport { getFiberFromElement } from \"../fiber/capture\";\nimport type { Fiber } from \"../fiber/react-types\";\nimport {\n PROJECTION_ROOT_ATTRIBUTE,\n underForeignProjectionRoot,\n} from \"../html/watch-dom\";\n\n// Note: This module depends on the fiber module for React fiber tree traversal.\n// Both modules are at the same level (siblings in the module structure).\n\nexport interface PortalWatcher {\n /** The DOM element being watched for HTML projection */\n element: Element;\n /** Called when a portal belonging to this element is detected */\n onPortalFound: (portalRoot: Element) => void;\n /** Called when a tracked portal is removed from the DOM */\n onPortalRemoved: (portalRoot: Element) => void;\n}\n\nexport interface PortalTracker {\n /**\n * Register a watcher. Immediately scans existing body children for matches.\n * @returns Unregister function\n */\n register(watcher: PortalWatcher): () => void;\n\n /** Stop tracking and clean up. Call when done with all watching. */\n destroy(): void;\n}\n\n/** Module-level singleton */\nlet instance: PortalTrackerImpl | null = null;\n\n/**\n * Get the singleton PortalTracker instance.\n * Creates one if it doesn't exist.\n */\nexport function getPortalTracker(): PortalTracker {\n if (!instance) {\n instance = new PortalTrackerImpl();\n }\n return instance;\n}\n\n/**\n * Reset the singleton. For testing only.\n * @internal\n */\nexport function _resetPortalTrackerForTesting(): void {\n instance?.destroy();\n instance = null;\n}\n\n/** Whether React logically owns `candidate` below `root`, across portals. */\nexport function isElementOwnedByRoot(\n candidate: Element,\n root: Element,\n): boolean {\n const fiber = getFiberFromElement(candidate);\n if (!fiber) return false;\n\n let current: Fiber | null = fiber.return;\n while (current) {\n if (\n current.stateNode instanceof Element &&\n (current.stateNode === root || root.contains(current.stateNode))\n ) {\n return true;\n }\n current = current.return;\n }\n\n return false;\n}\n\n/**\n * Finds the topmost portal roots owned by `root`. Portal targets may be nested\n * below arbitrary non-React containers, so body-child-only scans are not\n * sufficient.\n */\nexport function findOwnedPortalRoots(root: Element): Element[] {\n const body = root.ownerDocument?.body;\n if (!body) return [];\n\n const portals: Element[] = [];\n const visit = (candidate: Element): void => {\n if (candidate === root || root.contains(candidate)) return;\n if (isElementOwnedByRoot(candidate, root)) {\n portals.push(candidate);\n return;\n }\n // Match the observer's ownership boundary. Full snapshots must not scan\n // the retained React trees of every other storyboard for this root's portals.\n if (candidate.hasAttribute(PROJECTION_ROOT_ATTRIBUTE)) return;\n for (const child of Array.from(candidate.children)) visit(child);\n };\n\n for (const child of Array.from(body.children)) visit(child);\n return portals;\n}\n\nclass PortalTrackerImpl implements PortalTracker {\n private watchers = new Set<PortalWatcher>();\n private trackedPortals = new Map<Element, Set<PortalWatcher>>(); // portal element -> subscribed watchers\n private observer: MutationObserver | null = null;\n private pendingScanRoots = new Set<Element>();\n private scanScheduled = false;\n\n register(watcher: PortalWatcher): () => void {\n this.watchers.add(watcher);\n\n // Start observing if this is the first watcher\n if (this.watchers.size === 1) {\n this.startObserving();\n }\n\n // Initial scan: custom portal targets may be nested below body children.\n for (const child of Array.from(document.body.children)) {\n this.scanElementTree(child, watcher);\n }\n\n return () => this.unregister(watcher);\n }\n\n private unregister(watcher: PortalWatcher): void {\n this.watchers.delete(watcher);\n\n // Remove this watcher from all tracked portal subscriptions\n for (const [portal, owners] of this.trackedPortals) {\n owners.delete(watcher);\n if (owners.size === 0) {\n this.trackedPortals.delete(portal);\n }\n }\n\n // Stop observing if no watchers remain\n if (this.watchers.size === 0) {\n this.stopObserving();\n }\n }\n\n destroy(): void {\n this.stopObserving();\n this.watchers.clear();\n this.trackedPortals.clear();\n this.pendingScanRoots.clear();\n }\n\n private startObserving(): void {\n if (this.observer) return;\n\n this.observer = new MutationObserver(this.handleMutations);\n this.observer.observe(document.body, { childList: true, subtree: 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 // Handle added nodes\n for (const node of mutation.addedNodes) {\n if (node instanceof Element) {\n // React attaches __reactFiber$* keys after DOM insertion. Coalesce a\n // mutation batch so nested additions are scanned only once.\n this.scheduleScan(node);\n }\n }\n\n // Handle removed nodes\n for (const node of mutation.removedNodes) {\n if (node instanceof Element) {\n for (const [portal, owners] of this.trackedPortals) {\n if (portal !== node && !node.contains(portal)) continue;\n for (const owner of owners) {\n owner.onPortalRemoved(portal);\n }\n this.trackedPortals.delete(portal);\n }\n }\n }\n }\n };\n\n private scheduleScan(element: Element): void {\n this.pendingScanRoots.add(element);\n if (this.scanScheduled) return;\n\n this.scanScheduled = true;\n queueMicrotask(() => {\n this.scanScheduled = false;\n const roots = Array.from(this.pendingScanRoots);\n this.pendingScanRoots.clear();\n\n // Scan only topmost pending roots. Ancestor membership avoids comparing\n // every pair of elements in a wide mutation batch.\n const pending = new Set(roots);\n for (const root of roots) {\n // An add+remove in one observer batch must not create a detached ghost.\n if (!root.isConnected) continue;\n let inPending = false;\n for (\n let ancestor = root.parentElement;\n ancestor;\n ancestor = ancestor.parentElement\n ) {\n if (pending.has(ancestor)) {\n inPending = true;\n break;\n }\n }\n if (inPending) continue;\n this.scanElementTree(root);\n }\n });\n }\n\n /**\n * Scan until a topmost owned portal is found. Mutations inside an already\n * tracked portal are handled by that portal's own watcher.\n */\n private scanElementTree(element: Element, onlyWatcher?: PortalWatcher): void {\n const requestedWatchers = onlyWatcher\n ? this.watchers.has(onlyWatcher)\n ? [onlyWatcher]\n : []\n : Array.from(this.watchers);\n // Whether a watcher's root or an owned portal contains an element is\n // decided once for the scanned subtree, not once per element: a\n // subtree of a thousand added elements on a host with sixty watched\n // roots otherwise needs sixty thousand `contains` walks. Only a watcher\n // root or a tracked portal that lies inside the\n // subtree can contain some of its elements and not others, and those\n // are checked per element.\n const inside = (candidate: Element) =>\n candidate !== element && element.contains(candidate);\n const perElement = requestedWatchers.filter((watcher) =>\n inside(watcher.element),\n );\n const settled = requestedWatchers.filter(\n (watcher) =>\n !perElement.includes(watcher) &&\n watcher.element !== element &&\n !watcher.element.contains(element) &&\n !this.isInsidePortalOwnedByWatcher(element, watcher),\n );\n const portalsInside = Array.from(this.trackedPortals.keys()).some(inside);\n this.scanElementTreeForWatchers(\n element,\n settled,\n perElement,\n portalsInside,\n );\n }\n\n private scanElementTreeForWatchers(\n element: Element,\n settledWatchers: readonly PortalWatcher[],\n perElementWatchers: readonly PortalWatcher[],\n portalsInside: boolean,\n ): void {\n const eligibleWatchers = [\n ...(portalsInside\n ? settledWatchers.filter(\n (watcher) => !this.isInsidePortalOwnedByWatcher(element, watcher),\n )\n : settledWatchers),\n ...perElementWatchers.filter(\n (watcher) =>\n watcher.element !== element &&\n !watcher.element.contains(element) &&\n !this.isInsidePortalOwnedByWatcher(element, watcher),\n ),\n ];\n if (eligibleWatchers.length === 0) return;\n\n const matchedWatchers = this.checkElement(element, eligibleWatchers);\n // Projection roots are ownership boundaries. Their ordinary descendants\n // cannot be portals of another root (checkElement stops at this same\n // boundary). Avoid walking every other storyboard for each registration.\n if (element.hasAttribute(PROJECTION_ROOT_ATTRIBUTE)) return;\n const descendantSettled = settledWatchers.filter(\n (watcher) => !matchedWatchers.has(watcher),\n );\n const descendantPerElement = perElementWatchers.filter(\n (watcher) => !matchedWatchers.has(watcher),\n );\n if (descendantSettled.length + descendantPerElement.length === 0) return;\n\n for (const child of Array.from(element.children)) {\n this.scanElementTreeForWatchers(\n child,\n descendantSettled,\n descendantPerElement,\n portalsInside,\n );\n }\n }\n\n private isInsidePortalOwnedByWatcher(\n element: Element,\n watcher: PortalWatcher,\n ): boolean {\n for (const [portal, owners] of this.trackedPortals) {\n if (\n owners.has(watcher) &&\n (portal === element || portal.contains(element))\n ) {\n return true;\n }\n }\n return false;\n }\n\n /** Check ownership with one fiber walk, even when many roots are watched. */\n private checkElement(\n element: Element,\n watchers: readonly PortalWatcher[],\n ): Set<PortalWatcher> {\n const matched = new Set<PortalWatcher>();\n const fiber = getFiberFromElement(element);\n if (!fiber) return matched;\n\n let current: Fiber | null = fiber.return;\n while (current && matched.size < watchers.length) {\n const host = current.stateNode;\n if (host instanceof Element) {\n for (const watcher of watchers) {\n if (\n !matched.has(watcher) &&\n (host === watcher.element ||\n (watcher.element.contains(host) &&\n !underForeignProjectionRoot(host, watcher.element)))\n ) {\n matched.add(watcher);\n }\n }\n // A portal rendered below another root's element is that root's\n // content: nothing watched above that element owns it.\n if (host.hasAttribute(PROJECTION_ROOT_ATTRIBUTE)) break;\n }\n current = current.return;\n }\n\n if (matched.size === 0) return matched;\n let owners = this.trackedPortals.get(element);\n if (!owners) {\n owners = new Set<PortalWatcher>();\n this.trackedPortals.set(element, owners);\n }\n for (const watcher of matched) {\n if (!this.watchers.has(watcher) || owners.has(watcher)) continue;\n owners.add(watcher);\n watcher.onPortalFound(element);\n }\n\n return matched;\n }\n}\n","import {\n captureRootCoordinates,\n ROOT_COORDINATES_ATTRIBUTE,\n type ProjectionRootCoordinates,\n} from \"../html/root-coordinates\";\nimport {\n type DomWatcher,\n drainProjectionDomMutations,\n type ProjectionDomMutation,\n underForeignProjectionRoot,\n watchDom,\n} from \"../html/watch-dom\";\nimport { type PortalWatcherHandle, watchPortal } from \"../html/watch-portal\";\nimport { findLowestCommonAncestor } from \"../html/selectors\";\nimport {\n drainProjectionStateEvents,\n type StateWatcher,\n watchState,\n} from \"../html/watch-state\";\nimport { getPortalTracker } from \"../shared/portal-tracker\";\nimport type {\n ProjectionLayerMetadataSnapshot,\n ProjectionLayerRegionSnapshot,\n} from \"./projection-layer-snapshot\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\nimport {\n captureProjectionMutationPatch,\n captureProjectionPortalCoordinates,\n captureProjectionPortalRegion,\n captureProjectionStatePatch,\n PROJECTION_ROOT_TARGET_ID,\n type ProjectionDomPatch,\n type ProjectionPortalPatch,\n type ProjectionStatePatch,\n} from \"./projection-patch\";\n\nexport interface ProjectionLayerPatch {\n readonly regions?: readonly ProjectionLayerRegionSnapshot[];\n readonly metadata?: readonly ProjectionLayerMetadataSnapshot[];\n /** What the layer lane alone observed: its regions' files and the stamps\n * on its metadata. The patch's own `observedFiles` merges the DOM lane\n * in, so a receiver that needs both lanes reads this beside it. */\n readonly observedFiles?: ProjectionObservedFileMap;\n}\n\nexport interface ProjectionRootPatch {\n /** Explicit ancestor repairs, captured with this patch's matching semantic\n * regions. They satisfy preceding misses covered by these ancestor IDs. */\n readonly repairedAncestors?: readonly string[];\n /** Files absent from this complete root result, at the evaluated source version.\n * Root-scoped evidence, never a document-wide module-only acknowledgment. */\n readonly absentFiles?: ProjectionObservedFileMap;\n readonly dom?: readonly ProjectionDomPatch[];\n /** Ids among placed and re-attributed elements whose source computed\n * pointer-events is none. Absent when empty. */\n readonly pointerEventsNone?: readonly string[];\n readonly state?: readonly ProjectionStatePatch[];\n readonly portals?: readonly ProjectionPortalPatch[];\n readonly layers?: ProjectionLayerPatch;\n readonly observedFiles?: ProjectionObservedFileMap;\n}\n\nexport type ProjectionRootPatchResult =\n | {\n readonly kind: \"patch\";\n readonly patch: ProjectionRootPatch;\n /** DOM-derived metadata targets retained only for local Fiber capture. */\n readonly localMetadataTargets: readonly Element[];\n /** Exact source-realm targets for synthetic DOM Layers. They never\n * cross transport, so duplicate DOM ids remain unambiguous. */\n readonly localDomLayerTargets?: {\n readonly structural: readonly Element[];\n readonly metadata: readonly Element[];\n };\n }\n | { readonly kind: \"empty\" };\n\nexport interface ProjectionPortalRegistration {\n readonly onPortalFound: (portal: Element) => void;\n readonly onPortalRemoved: (portal: Element) => void;\n}\n\nexport interface CreateProjectionRootAccumulatorOptions {\n readonly root: Element;\n readonly onChange: (trigger: ProjectionRootActivityTrigger) => void;\n /** Injection seam; the default delegates to the document portal tracker. */\n readonly registerPortals?: (\n registration: ProjectionPortalRegistration,\n ) => () => void;\n}\n\nexport type ProjectionRootActivityTrigger =\n | \"dom-mutation\"\n | \"state-event\"\n | \"portal-mutation\"\n | \"portal-coordinate-change\";\n\nexport interface ProjectionRootAccumulator {\n capturePatch(options?: {\n readonly regionalChildLists?: boolean;\n readonly retainDomLayerTargets?: boolean;\n }): ProjectionRootPatchResult;\n /**\n * Retain DOM records already queued for this root and return their count.\n * This is called synchronously at React's commit boundary; the caller owns\n * the scheduling signal for those records.\n */\n takePendingDomRecords(): number;\n /** Whether this root currently owns any portal. Document-wide changes that\n * can move a portal without mutating it (new styling) only need to schedule\n * the roots that answer yes. */\n hasPortals(): boolean;\n hasCoordinateFrame(): boolean;\n rememberCoordinates(coordinates: ProjectionRootCoordinates | undefined): void;\n /** Current live portal roots for an explicit full baseline. */\n portalElements(): readonly Element[];\n /** Counters already maintained by observers; performs no discovery work. */\n perfSnapshot(): {\n readonly rawMutationRecords: number;\n readonly rawStateRecords: number;\n readonly rawPortalRecords: number;\n readonly candidateTargets: number;\n };\n stop(): void;\n}\n\n/**\n * One root-local final-state accumulator. Observer callbacks only retain exact\n * source targets and signal the document scheduler; serialization happens once\n * when the scheduler flushes.\n */\nexport function createProjectionRootAccumulator(\n options: CreateProjectionRootAccumulatorOptions,\n): ProjectionRootAccumulator {\n const dom: DomWatcher = watchDom(options.root, () =>\n options.onChange(\"dom-mutation\"),\n );\n const state: StateWatcher = watchState(options.root, () =>\n options.onChange(\"state-event\"),\n );\n const portals = new Map<Element, PortalWatcherHandle>();\n const dirtyPortals = new Set<Element>();\n const removedPortals = new Map<string, ProjectionPortalPatch>();\n /** The coordinate space the destination last received per live portal,\n * serialized. Both sides of the comparison are built by the same capture\n * routine, so key order is fixed and the string is a sound identity — and\n * one that stays exhaustive if the coordinate space grows a field. */\n const sentPortalCoordinates = new Map<Element, string>();\n let stopped = false;\n let sentCoordinates: string | undefined;\n const hasCoordinateFrame = () => sentCoordinates !== undefined;\n\n // A host positions the watched root by styling an ANCESTOR of it (a\n // storyboard's frame carries the layout position), so the root can move in\n // its viewport without one mutation inside the watched subtree. Every\n // portal's coordinate space moves with it, and nothing else would notice.\n const ancestorsOf = (element: Element): Element[] => {\n const chain: Element[] = [];\n for (\n let ancestor = element.parentElement;\n ancestor;\n ancestor = ancestor.parentElement\n ) {\n chain.push(ancestor);\n }\n return chain;\n };\n const sameChain = (chain: Element[], other: Element[]): boolean =>\n chain.length === other.length &&\n chain.every((element, index) => element === other[index]);\n let observedAncestors: Element[] = [];\n const frameWatcher = new MutationObserver((records) => {\n if (stopped) return;\n // childList is observed only to notice the root being re-parented, which\n // moves it under ancestors this observer has never seen. Sibling churn\n // under an unchanged chain is not a coordinate signal, so it must not\n // become one — the chain is compared before anything is reported.\n let reparented = false;\n if (records.some((record) => record.type === \"childList\")) {\n const chain = ancestorsOf(options.root);\n reparented = !sameChain(chain, observedAncestors);\n if (reparented) observeAncestors(chain);\n }\n const restyled = records.some((record) => record.type === \"attributes\");\n if (!reparented && !restyled) return;\n if (portals.size === 0 && !hasCoordinateFrame()) return;\n options.onChange(\"portal-coordinate-change\");\n });\n function observeAncestors(chain: Element[]): void {\n frameWatcher.disconnect();\n observedAncestors = chain;\n for (const ancestor of chain) {\n frameWatcher.observe(ancestor, {\n attributes: true,\n attributeFilter: [\"style\", \"class\"],\n childList: true,\n });\n }\n }\n observeAncestors(ancestorsOf(options.root));\n const view = options.root.ownerDocument.defaultView;\n const invalidateCoordinates = () => {\n if (!stopped && (hasCoordinateFrame() || portals.size > 0))\n options.onChange(\"portal-coordinate-change\");\n };\n const onScroll = (event: Event) => {\n const target = event.target as Node | null;\n if (target?.contains?.(options.root)) invalidateCoordinates();\n };\n view?.addEventListener(\"resize\", invalidateCoordinates);\n view?.addEventListener(\"scroll\", onScroll, true);\n\n const registerPortals =\n options.registerPortals ??\n ((registration: ProjectionPortalRegistration) =>\n getPortalTracker().register({\n element: options.root,\n ...registration,\n }));\n const unregisterPortals = registerPortals({\n onPortalFound(portal) {\n if (stopped || portals.has(portal)) return;\n // No coordinate root: this lane captures a portal's frame with its\n // body, from the patch builder, rather than through the handle's own\n // legacy-envelope flush.\n const handle = watchPortal(portal, () => {\n dirtyPortals.add(portal);\n options.onChange(\"portal-mutation\");\n });\n portals.set(portal, handle);\n dirtyPortals.add(portal);\n options.onChange(\"portal-mutation\");\n },\n onPortalRemoved(portal) {\n const handle = portals.get(portal);\n if (!handle) return;\n removedPortals.set(handle.id, {\n kind: \"remove\",\n portalId: handle.id,\n });\n dirtyPortals.delete(portal);\n portals.delete(portal);\n sentPortalCoordinates.delete(portal);\n handle.stop();\n options.onChange(\"portal-mutation\");\n },\n });\n\n return {\n takePendingDomRecords() {\n if (stopped) return 0;\n return dom.takePendingRecords();\n },\n hasCoordinateFrame,\n rememberCoordinates(coordinates) {\n sentCoordinates = coordinates ? JSON.stringify(coordinates) : undefined;\n },\n hasPortals() {\n return !stopped && portals.size > 0;\n },\n capturePatch(captureOptions) {\n if (stopped) throw new Error(\"Projection root accumulator has stopped\");\n // A requestFull may run before the observer microtask. Drain the same\n // observers, never infer unchanged content from an undelivered callback.\n dom.takePendingRecords();\n for (const [portal, handle] of portals) {\n if (handle.takePendingDomRecords() > 0) dirtyPortals.add(portal);\n }\n const domMutations = drainProjectionDomMutations(dom);\n let localDomLayerTargets = collectDomLayerTargets(\n options.root,\n captureOptions?.retainDomLayerTargets\n ? domMutations\n : domMutations.filter(\n (mutation) =>\n mutation.type === \"childList\" &&\n [\n ...(mutation.addedNodes ?? []),\n ...(mutation.removedNodes ?? []),\n ].some((node) => node.nodeType === 3 || node.nodeType === 8),\n ),\n );\n const mutationPatch = captureProjectionMutationPatch(\n options.root,\n domMutations,\n captureOptions,\n );\n const localMetadataTargets = [...mutationPatch.localMetadataTargets];\n const metadata = [...(mutationPatch.layers?.metadata ?? [])];\n\n const states: ProjectionStatePatch[] = [];\n for (const event of drainProjectionStateEvents(state)) {\n // Scroll and input events bubble up from another root's content;\n // that root's own state watcher publishes them.\n if (underForeignProjectionRoot(event.element, options.root)) continue;\n const captured = captureProjectionStatePatch(\n options.root,\n event.element,\n event.eventKind,\n );\n if (captured) states.push(captured);\n }\n\n const portalPatches = Array.from(removedPortals.values());\n const observedFiles = new ProjectionObservedFileAccumulator();\n observedFiles.merge(mutationPatch.observedFiles);\n const layerObservedFiles = new ProjectionObservedFileAccumulator();\n layerObservedFiles.merge(mutationPatch.layers?.observedFiles);\n removedPortals.clear();\n const resentPortals = new Set<Element>();\n for (const portal of dirtyPortals) {\n const handle = portals.get(portal);\n if (!handle) continue;\n const pending = handle.clearPendingChanges();\n const targets = collectDomLayerTargets(portal, pending.dom);\n localDomLayerTargets = {\n structural: [\n ...localDomLayerTargets.structural,\n ...targets.structural,\n ],\n metadata: [...localDomLayerTargets.metadata, ...targets.metadata],\n };\n // The portal body already carries final DOM structure. Its mutations\n // still owe the same semantic targets and text metadata as the root.\n const portalMutationPatch = captureProjectionMutationPatch(\n portal,\n pending.dom.filter((mutation) => mutation.type !== \"childList\"),\n );\n localMetadataTargets.push(...portalMutationPatch.localMetadataTargets);\n metadata.push(...(portalMutationPatch.layers?.metadata ?? []));\n const captured = captureProjectionPortalRegion(\n portal,\n false,\n options.root,\n );\n if (!captured) continue;\n resentPortals.add(portal);\n if (\n captured.portal.kind === \"replace\" &&\n captured.portal.coordinateSpace\n ) {\n sentPortalCoordinates.set(\n portal,\n JSON.stringify(captured.portal.coordinateSpace),\n );\n }\n portalPatches.push(captured.portal);\n observedFiles.merge(captured.observedFiles);\n layerObservedFiles.merge(captured.observedFiles);\n // The body is a fresh element on the destination, so every scroll\n // offset the source holds has to travel with it — not only the ones\n // that fired as events since the last flush.\n states.push(...captured.state);\n for (const event of pending.state) {\n const statePatch = captureProjectionStatePatch(\n portal,\n event.element,\n event.eventKind,\n );\n if (statePatch) states.push(statePatch);\n }\n }\n dirtyPortals.clear();\n\n // The root can move, and new styling can move a portal, without either\n // one mutating the portal. Portals whose body this patch already carries\n // are current; the rest are worth a coordinate refresh, but only when\n // the frame actually moved — re-sending a body would cost destination\n // focus and edit state, and re-sending an unchanged frame is noise.\n for (const portal of portals.keys()) {\n if (resentPortals.has(portal)) continue;\n const coordinates = captureProjectionPortalCoordinates(\n options.root,\n portal,\n );\n if (!coordinates) continue;\n const measured = JSON.stringify(coordinates.coordinateSpace);\n if (sentPortalCoordinates.get(portal) === measured) continue;\n sentPortalCoordinates.set(portal, measured);\n portalPatches.push(coordinates);\n }\n\n const observedSnapshot = observedFiles.snapshot();\n for (const snapshot of metadata)\n layerObservedFiles.addLayerProps(snapshot.props);\n const layerObservedSnapshot = layerObservedFiles.snapshot();\n const layers: ProjectionLayerPatch = {\n ...(metadata.length > 0 ? { metadata } : {}),\n ...(Object.keys(layerObservedSnapshot).length > 0\n ? { observedFiles: layerObservedSnapshot }\n : {}),\n };\n const coordinates = captureRootCoordinates(options.root, portals.keys());\n const measuredCoordinates = coordinates\n ? JSON.stringify(coordinates)\n : undefined;\n const coordinatesChanged = measuredCoordinates !== sentCoordinates;\n sentCoordinates = measuredCoordinates;\n const domPatches = [...mutationPatch.dom];\n if (coordinatesChanged)\n domPatches.push({\n kind: \"attributes\",\n targetId: PROJECTION_ROOT_TARGET_ID,\n attributes: {\n [ROOT_COORDINATES_ATTRIBUTE]: measuredCoordinates ?? null,\n },\n });\n const patch: ProjectionRootPatch = {\n ...(Object.keys(layers).length > 0 ? { layers } : {}),\n ...(domPatches.length > 0 ? { dom: domPatches } : {}),\n ...(mutationPatch.pointerEventsNone\n ? { pointerEventsNone: mutationPatch.pointerEventsNone }\n : {}),\n ...(states.length > 0 ? { state: states } : {}),\n ...(portalPatches.length > 0 ? { portals: portalPatches } : {}),\n ...(Object.keys(observedSnapshot).length > 0\n ? { observedFiles: observedSnapshot }\n : {}),\n };\n const hasLocalDomLayerTargets =\n localDomLayerTargets !== undefined &&\n (localDomLayerTargets.structural.length > 0 ||\n localDomLayerTargets.metadata.length > 0);\n const hasLocalMetadataTargets = localMetadataTargets.length > 0;\n return Object.keys(patch).length === 0 &&\n !hasLocalDomLayerTargets &&\n !hasLocalMetadataTargets\n ? { kind: \"empty\" }\n : {\n kind: \"patch\",\n patch,\n localMetadataTargets,\n ...(hasLocalDomLayerTargets ? { localDomLayerTargets } : {}),\n };\n },\n portalElements() {\n return Array.from(portals.keys());\n },\n perfSnapshot() {\n return {\n rawMutationRecords: dom.mutationRecordCount,\n rawStateRecords: state.stateRecordCount,\n rawPortalRecords:\n removedPortals.size +\n Array.from(portals.values()).reduce(\n (count, portal) => count + portal.pendingRecordCount(),\n 0,\n ),\n candidateTargets:\n dom.mutatedElements.size + dom.addedElementCount + dirtyPortals.size,\n };\n },\n stop() {\n if (stopped) return;\n stopped = true;\n unregisterPortals();\n frameWatcher.disconnect();\n view?.removeEventListener(\"resize\", invalidateCoordinates);\n view?.removeEventListener(\"scroll\", onScroll, true);\n dom.stop();\n state.stop();\n for (const portal of portals.values()) portal.stop();\n portals.clear();\n dirtyPortals.clear();\n removedPortals.clear();\n sentPortalCoordinates.clear();\n },\n };\n}\n\nfunction collectDomLayerTargets(\n root: Element,\n mutations: readonly ProjectionDomMutation[],\n): {\n readonly structural: readonly Element[];\n readonly metadata: readonly Element[];\n} {\n const structural = new Set<Element>();\n const metadata = new Set<Element>();\n for (const mutation of mutations) {\n const target =\n mutation.target instanceof Element\n ? mutation.target\n : mutation.target.parentElement;\n if (!target || (target !== root && !root.contains(target))) continue;\n if (mutation.type === \"childList\") {\n structural.add(target);\n for (const removed of mutation.removedNodes ?? []) {\n if (!root.contains(removed) || removed.parentNode === target) continue;\n // A move back to its Fiber parent looks ordinary in the current tree.\n // The removed-node record is the evidence of the other physical slot;\n // publish both slots together so region order cannot remint the layer.\n const common = findLowestCommonAncestor(new Set([target, removed]));\n if (common) structural.add(common);\n }\n } else if (mutation.type === \"attributes\") metadata.add(target);\n }\n return {\n structural: Array.from(structural),\n metadata: Array.from(metadata),\n };\n}\n","import type { WorkSchedulerClock } from \"../../rate-limiter\";\nimport { createPreparedHead } from \"../html/prepared-head\";\nimport { getFiberFromElement } from \"../fiber/capture\";\nimport { type Fiber, type FiberRoot, FiberTag } from \"../fiber/react-types\";\nimport { resolveCommittedFiber } from \"../fiber/serialize\";\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport { initHook } from \"../fiber/watch\";\nimport { observeDocumentAssets } from \"../html/document-assets\";\nimport {\n seedProjectionIds,\n underForeignProjectionRoot,\n} from \"../html/watch-dom\";\nimport { captureHead, getHeadTracker } from \"../html/watch-head\";\nimport {\n registerCaptureRootObserver,\n registerDocumentCaptureProducer,\n resetCaptureFlushCounters,\n} from \"../shared/capture-perf\";\nimport type { DetachSerializedFiber } from \"./enriched-to-serialized-fiber\";\nimport type { LayerFramework } from \"./layer-framework\";\nimport type {\n CombinedProjectionBatch,\n CombinedProjectionProblem,\n ProjectionRenderErrorProblem,\n} from \"./projection-batch\";\nimport { buildProjectionCapturePerf } from \"./projection-capture-perf\";\nimport {\n flutterViewRootOf,\n isFlutterViewRoot,\n} from \"./projection-flutter-layers\";\nimport {\n captureProjectionFullSnapshot,\n captureProjectionRegion,\n type ProjectionRegionCapture,\n resolveRegionElement,\n} from \"./projection-full-snapshot\";\nimport {\n createProjectionLayerAdapter,\n type ProjectionLayerAdapter,\n resolveCommittedFiberOrNull,\n} from \"./projection-layer-adapter\";\nimport {\n isProjectionLayerFiber,\n isProjectionRootFiber,\n layerPropsEqual,\n PROJECTION_SCOPE_TARGET,\n type ProjectionLayerMetadataSnapshot,\n type ProjectionLayerNode,\n type ProjectionLayerProps,\n type ProjectionLayerRegionSnapshot,\n projectionLayerRoots,\n recordEqual,\n svgLayerAttributesOf,\n} from \"./projection-layer-snapshot\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\nimport { PROJECTION_ROOT_TARGET_ID } from \"./projection-patch\";\nimport {\n isProjectionPendingOnly,\n isProjectionUnavailableOnly,\n} from \"./projection-pending\";\nimport {\n createProjectionOutbox,\n type ProjectionProducerFlushContext,\n type ProjectionProducerScheduler,\n} from \"./projection-producer\";\nimport type { ProjectionRepairPaths } from \"./projection-repair\";\nimport {\n createProjectionRootAccumulator,\n type ProjectionRootAccumulator,\n type ProjectionRootPatch,\n} from \"./projection-root-accumulator\";\nimport type {\n CaptureProducerPerf,\n CaptureSourceViewportSample,\n EnrichedFiberConstraint,\n EnrichedFiberNode,\n} from \"./types\";\n\n/** The old customization fields remain accepted at the public SDK boundary,\n * but the document producer deliberately emits one closed DTO. */\nexport interface CombinedProjectionRootOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n rootId: string;\n /** Capture the exact endpoint contents under an observation-only fragment. */\n scope?: \"contents\" | \"subtree\";\n /** The DOM endpoint. A root is `{rootId, element}` or\n * `{rootId, fiberSelector}`: without an element the fiber selector names\n * the endpoint in the producer's document, and the root follows it across\n * replacements the way a `selector` root does. Content below another\n * projection root's element inside the endpoint is never this root's. */\n element?: Element;\n /** Fixed semantic-layer authority for this watcher lifetime. */\n layerFramework: LayerFramework;\n selector?: string;\n /** Owns endpoint-local resources before its first full, including after\n * selector replacement. Cleanup runs on removal, unwatch, or stop. */\n onRootAttached?: (element: Element) => () => void;\n serialize?: SerializeFn<T>;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n /** This receiver acknowledges every committed baseline and patch. */\n receiverCredit?: boolean;\n /** A selected root's opening baseline precedes background serialization. */\n userInitiated?: boolean;\n /** The receiver retains this document head; stale proofs fall back to a\n * self-contained baseline. No proof preserves the legacy behavior. */\n knownHead?: { readonly sessionId: string; readonly headRevision: number };\n hideFiberProp?: string;\n}\n\n/** A root the producer holds: its endpoint has been resolved. */\ntype OwnedRootOptions<T extends EnrichedFiberConstraint> =\n CombinedProjectionRootOptions<T> & { readonly element: Element };\n\nexport type {\n CombinedProjectionBatch,\n CombinedProjectionProblem,\n ProjectionRenderErrorProblem,\n} from \"./projection-batch\";\n\nexport interface CreateCombinedDocumentProducerOptions {\n document: Document;\n /** Optional resource emission while CSSOM is already materialized in the source. */\n styleResource?: (css: string, hash?: string) => string | null;\n /** Live Electron producers prepare CSS off-thread; synchronous SDK callers retain their contract. */\n prepareHead?: boolean;\n headWorkClock?: WorkSchedulerClock;\n /** Return only after the batch has been synchronously handed to transport. */\n emit(batch: CombinedProjectionBatch): void;\n scheduler?: ProjectionProducerScheduler;\n flushWindowMs?: number;\n /** Keep the document animation-frame flush armed while roots are watched. */\n keepArmed?: boolean;\n /** Yield between bounded groups of root captures on a busy shared host. */\n maxRootsPerFlush?: number;\n onError?: (error: unknown) => void;\n}\n\nexport interface CombinedDocumentProducer<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n requestRepair(rootId: string, paths: ProjectionRepairPaths): void;\n bindSession(sessionId: string): void;\n watchRoot(options: CombinedProjectionRootOptions<T>): void;\n unwatchRoot(rootId: string): void;\n setRootSize(rootId: string, size: { width: number; height: number }): void;\n /** One current self-contained baseline for one root. `includeHead` makes the\n * baseline self-contained for a receiver document that may have been\n * replaced, and scopes that forced head to this root's lane.\n * Every baseline names its root: a document-wide baseline would make one\n * root's mount or recovery re-serialize its healthy siblings.\n *\n * Set `includeHead` only when the receiver cannot vouch for its document's\n * projected head, such as a fresh mount or document replacement. Ordinary\n * repair and manual refresh leave it off: head CSS may remain unchanged, so\n * replacement cannot wait for a future mutation, while an intact receiver\n * should not reload working stylesheets (TEM-1815). */\n requestFull(\n rootId: string,\n options?: { readonly includeHead?: boolean },\n ): void;\n acknowledge(sessionId: string, rootId: string, sequence: number): void;\n /** Cold query for one selected branch; never enters the hot batch stream.\n * `descendants: false` captures the selected node alone. */\n captureSemanticSubtree(\n rootId: string,\n targetFiberId: string | { readonly mode: \"context\" },\n options?: { readonly descendants?: boolean },\n ): (DetachSerializedFiber & { truncated?: boolean }) | null;\n /** Cold scoped-repair query: one element's exact current children-region\n * final state, or null when the id no longer exists. Never enters the hot\n * batch stream. */\n captureRegion(\n rootId: string,\n targetId: string,\n ): ProjectionRegionCapture | null;\n stop(): void;\n}\n\ninterface RootRuntime<T extends EnrichedFiberConstraint> {\n repairPaths: ProjectionRepairPaths;\n readonly options: OwnedRootOptions<T>;\n readonly layerAdapter: ProjectionLayerAdapter;\n dormant: boolean;\n accumulator: ProjectionRootAccumulator | null;\n stopObserver: (() => void) | null;\n stopAttachment: (() => void) | null;\n references: number;\n committedFiber: Fiber | null;\n renderError: ProjectionRenderErrorProblem | null;\n layerProblem: CombinedProjectionProblem | null;\n readonly pendingRegions: Map<string, Fiber>;\n readonly filePresence: Map<string, number>;\n readonly disappearedFiles: Set<string>;\n readonly publishedHostProps: Map<\n string,\n {\n readonly file?: string;\n readonly className: ProjectionLayerProps[\"className\"];\n readonly layoutMode: ProjectionLayerProps[\"layoutMode\"];\n readonly style: ProjectionLayerProps[\"style\"];\n readonly svg: Readonly<Record<string, string>> | undefined;\n readonly children: readonly string[];\n }\n >;\n readonly pendingMetadata: Map<\n string,\n {\n readonly fiber: Fiber;\n readonly sourceAnnotations: \"fiber\" | \"live-host\";\n readonly layoutOnly: boolean;\n }\n >;\n semanticDiscoveryNodesVisited: number;\n /** The reason last reported for a marker-only root (`suspended` or\n * `unavailable`), from that drain until the one that finds content again,\n * so one waiting episode costs one problem per reason (and one per full\n * requested during it). Null: content. */\n waitingEpisode: \"suspended\" | \"unavailable\" | null;\n /** A full asked for while suspended, carried to the drain that can serve it.\n * The flush consumes its request set before capture, so without this a\n * baseline requested mid-episode would be dropped. */\n deferredFullRequest: boolean;\n /** Authority of the last published baseline, not a renderer declaration. */\n publishedLayerFramework: LayerFramework | null;\n /** Small document-wide facts carried by fulls but outside the root observer. */\n publishedDocumentContext?: string;\n}\n\ninterface RootCaptureStats {\n readonly perf: CaptureProducerPerf;\n}\n\n/** How long after a module evaluated the producer reports its version\n * (V2-498). A module evaluating is not the DOM having it, and no signal\n * says when the DOM has it in every case, so every module fact, a first\n * evaluation, a hot one, or one React Refresh has re-rendered, waits the\n * same grace (user decision 2026-09-26). DOM stamps prove at once. */\nexport const MODULE_EVALUATED_GRACE_MS = 3000;\n\n/**\n * One producer for one source document. Observer callbacks retain source-realm\n * targets; the fixed scheduler asks for their current final state once. Full\n * snapshots exist only for initial registration, explicit synchronization,\n * reload, and recovery.\n */\nexport function createCombinedDocumentProducer<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(options: CreateCombinedDocumentProducerOptions): CombinedDocumentProducer<T> {\n const reactHook = initHook();\n const preparedHead = options.prepareHead\n ? createPreparedHead(options.document, options.headWorkClock)\n : undefined;\n const roots = new Map<string, RootRuntime<T>>();\n const captureStats = new WeakMap<object, RootCaptureStats>();\n let stopped = false;\n // Nothing is observed or minted before a session is bound: the first\n // capture after a bind is a baseline that supersedes any earlier record,\n // and an id minted earlier would not carry the session's seed.\n let sessionBound = false;\n let rootLifecycleObserver: MutationObserver | null = null;\n let headPerfContext: ProjectionProducerFlushContext | null = null;\n let headSnapshotMs = 0;\n const sourceWindow = options.document.defaultView;\n const pendingSourceViewportSamples: CaptureSourceViewportSample[] = [];\n\n function recordSourceViewport(): void {\n if (!sourceWindow) return;\n const sample: CaptureSourceViewportSample = {\n at: Date.now(),\n width: sourceWindow.innerWidth,\n height: sourceWindow.innerHeight,\n devicePixelRatio: sourceWindow.devicePixelRatio,\n };\n const previous =\n pendingSourceViewportSamples[pendingSourceViewportSamples.length - 1];\n if (\n previous?.width === sample.width &&\n previous.height === sample.height &&\n previous.devicePixelRatio === sample.devicePixelRatio\n ) {\n return;\n }\n if (pendingSourceViewportSamples.length < 16) {\n pendingSourceViewportSamples.push(sample);\n } else {\n pendingSourceViewportSamples[15] = sample;\n }\n }\n\n recordSourceViewport();\n\n // Module version records (V2-498). The SDK appends to every annotated\n // module a statement that pushes {file, modifiedTs, sourceVersion} onto\n // the document's `__TEMPO_MODULE_VERSIONS__` log when it evaluates. Each\n // record becomes a fact the grace after its evaluation.\n const moduleVersions = new Map<\n string,\n {\n readonly modifiedTs: number;\n readonly sourceVersion?: string;\n readonly evaluatedAt: number;\n /** The grace has passed: the fact may be sent. */\n reportable: boolean;\n }\n >();\n const unsentModuleFiles = new Set<string>();\n let moduleGraceTimer: ReturnType<typeof setTimeout> | null = null;\n let moduleLogRead = 0;\n const moduleLog = openModuleVersionLog();\n\n /** The document's log, created if no module has evaluated yet. Its `push`\n * is wrapped so an evaluation is read at once, which dates it; `stop`\n * puts the previous `push` back. */\n function openModuleVersionLog(): {\n readonly entries: unknown[];\n close(): void;\n } | null {\n if (!sourceWindow) return null;\n const global = sourceWindow as unknown as {\n __TEMPO_MODULE_VERSIONS__?: unknown;\n };\n global.__TEMPO_MODULE_VERSIONS__ ??= [];\n const log = global.__TEMPO_MODULE_VERSIONS__;\n if (!Array.isArray(log)) return null;\n const ownPush = Object.hasOwn(log, \"push\");\n const push = log.push;\n const wrapped = function (this: unknown[], ...entries: unknown[]) {\n const length = push.apply(this, entries);\n readModuleEvaluations();\n return length;\n };\n log.push = wrapped;\n return {\n entries: log,\n close() {\n // A producer created later wrapped ours; leave its chain intact.\n if (log.push !== wrapped) return;\n if (ownPush) log.push = push;\n else delete (log as { push?: unknown }).push;\n },\n };\n }\n\n function readModuleEvaluations(): void {\n if (!moduleLog || stopped) return;\n const entries = moduleLog.entries;\n const now = Date.now();\n let read = false;\n for (; moduleLogRead < entries.length; moduleLogRead += 1) {\n const entry = entries[moduleLogRead] as {\n file?: unknown;\n modifiedTs?: unknown;\n sourceVersion?: unknown;\n } | null;\n if (\n typeof entry?.file !== \"string\" ||\n typeof entry.modifiedTs !== \"number\"\n )\n continue;\n moduleVersions.set(entry.file, {\n modifiedTs: entry.modifiedTs,\n ...(typeof entry.sourceVersion === \"string\"\n ? { sourceVersion: entry.sourceVersion }\n : {}),\n evaluatedAt: now,\n reportable: false,\n });\n read = true;\n }\n if (read) scheduleModuleGrace(MODULE_EVALUATED_GRACE_MS);\n }\n\n /** One timer at a time: evaluations are dated in order, so the pending\n * timer is always due first, and each pass re-arms for the next due. */\n function scheduleModuleGrace(delayMs: number): void {\n if (moduleGraceTimer !== null) return;\n moduleGraceTimer = setTimeout(() => {\n moduleGraceTimer = null;\n reportModulesPastGrace();\n }, delayMs);\n }\n\n /** Every record past the grace becomes a fact. */\n function reportModulesPastGrace(): void {\n if (stopped) return;\n const now = Date.now();\n let changed = false;\n let nextDueMs: number | null = null;\n for (const [file, record] of moduleVersions) {\n if (record.reportable) continue;\n const dueMs = record.evaluatedAt + MODULE_EVALUATED_GRACE_MS - now;\n if (dueMs > 0) {\n nextDueMs = Math.min(nextDueMs ?? dueMs, dueMs);\n continue;\n }\n record.reportable = true;\n unsentModuleFiles.add(file);\n changed = true;\n }\n if (nextDueMs !== null) scheduleModuleGrace(nextDueMs);\n if (changed) core.record({ modules: true, trigger: \"module-evaluated\" });\n }\n\n function captureAbsentFiles(\n runtime: RootRuntime<T>,\n observed: ProjectionObservedFileMap,\n full: boolean,\n ): ProjectionObservedFileMap | undefined {\n const absent: Record<\n string,\n { modifiedTs: number; sourceVersion?: string }\n > = {};\n // Fulls already establish the entire scope (including a new document).\n // Patches only report files whose last published contribution disappeared.\n const files = full ? moduleVersions.keys() : runtime.disappearedFiles;\n for (const file of files) {\n if (runtime.filePresence.has(file) || observed[file]) continue;\n const evaluated = moduleVersions.get(file);\n if (evaluated)\n absent[file] = {\n modifiedTs: evaluated.modifiedTs,\n ...(evaluated.sourceVersion\n ? { sourceVersion: evaluated.sourceVersion }\n : {}),\n };\n }\n runtime.disappearedFiles.clear();\n return Object.keys(absent).length ? absent : undefined;\n }\n\n const core = createProjectionOutbox({\n hasPendingHead: preparedHead\n ? () => preparedHead.hasPendingChanges()\n : undefined,\n prepareHead: preparedHead\n ? (context) =>\n preparedHead.prepare(\n context.initialForSession\n ? \"session-baseline\"\n : context.triggerReasons.join(\",\") || \"baseline-request\",\n )\n : undefined,\n emit(batch) {\n recordSourceViewport();\n const sourceViewportSamples = pendingSourceViewportSamples.splice(0);\n const rootPerf = batch.roots.flatMap((change) => {\n const payload =\n change.kind === \"full\"\n ? change.snapshot\n : change.kind === \"patch\"\n ? change.patch\n : change.problem;\n return typeof payload === \"object\" && payload !== null\n ? [captureStats.get(payload)?.perf].filter(\n (perf): perf is CaptureProducerPerf => perf !== undefined,\n )\n : [];\n });\n const perf = aggregateBatchPerf(\n rootPerf,\n batch.head,\n headPerfContext,\n headSnapshotMs,\n batch.roots.length,\n sourceViewportSamples,\n );\n headPerfContext = null;\n headSnapshotMs = 0;\n const emitted: CombinedProjectionBatch = {\n sessionId: batch.sessionId,\n sequence: batch.sequence,\n ...(batch.head === undefined ? {} : { head: batch.head }),\n ...(batch.headRootIds === undefined\n ? {}\n : { headRootIds: batch.headRootIds }),\n ...(perf ? { perf } : {}),\n roots: batch.roots,\n ...(batch.sizes ? { sizes: batch.sizes } : {}),\n ...(batch.assetRootIds ? { assetRootIds: batch.assetRootIds } : {}),\n ...(batch.headRevision !== undefined\n ? { headRevision: batch.headRevision }\n : {}),\n ...(batch.modules ? { modules: batch.modules } : {}),\n };\n options.emit(emitted);\n for (const file of Object.keys(batch.modules ?? {}))\n unsentModuleFiles.delete(file);\n },\n captureModules(includesFull) {\n readModuleEvaluations();\n const files = includesFull\n ? [...moduleVersions.keys()]\n : [...unsentModuleFiles];\n const facts: Record<\n string,\n { modifiedTs: number; sourceVersion?: string }\n > = {};\n for (const file of files) {\n const record = moduleVersions.get(file);\n if (!record?.reportable) continue;\n facts[file] = {\n modifiedTs: record.modifiedTs,\n ...(record.sourceVersion === undefined\n ? {}\n : { sourceVersion: record.sourceVersion }),\n };\n }\n return Object.keys(facts).length > 0 ? facts : undefined;\n },\n scheduler: options.scheduler,\n flushWindowMs: options.flushWindowMs,\n keepArmed: options.keepArmed,\n maxRootsPerFlush: options.maxRootsPerFlush,\n onError: options.onError,\n captureRoot(rootId, flushContext) {\n readModuleEvaluations();\n const runtime = roots.get(rootId);\n if (runtime && !runtime.options.element.isConnected) {\n makeRootDormant(runtime);\n }\n if (runtime?.dormant) return null;\n if (!runtime?.accumulator) {\n return {\n kind: \"problem\",\n problem: { reason: \"missing-fiber-target\" },\n };\n }\n const accumulator = runtime.accumulator;\n const openingRoot = runtime.publishedLayerFramework === null;\n const observation = accumulator.perfSnapshot();\n resetCaptureFlushCounters();\n const captureStartedAt = Date.now();\n const renderError = readProjectionRenderError(runtime.options.element);\n if (renderError) {\n runtime.renderError = renderError;\n // Consume all pre-error candidates. They describe a DOM state that is\n // intentionally never published, and the eventual full baseline\n // supersedes them.\n runtime.accumulator.capturePatch();\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n runtime.semanticDiscoveryNodesVisited = 0;\n captureStats.set(renderError, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes: 0,\n domNodes: 0,\n htmlChars: 0,\n states: 0,\n portals: 0,\n observedFiles: 0,\n candidatesAfter: 0,\n fullReason: fullReason(flushContext, openingRoot),\n }),\n });\n return { kind: \"problem\", problem: renderError };\n }\n\n runtime.committedFiber = runtime.layerAdapter.resolveCommittedRoot(\n undefined,\n runtime.options,\n );\n const layerProblem = runtime.layerAdapter.readProblem(\n runtime.options.element,\n );\n if (layerProblem) {\n runtime.layerProblem = layerProblem;\n runtime.accumulator.capturePatch();\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n runtime.semanticDiscoveryNodesVisited = 0;\n captureStats.set(layerProblem, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes: 0,\n domNodes: 0,\n htmlChars: 0,\n states: 0,\n portals: 0,\n observedFiles: 0,\n candidatesAfter: 0,\n fullReason: null,\n }),\n });\n return { kind: \"problem\", problem: layerProblem };\n }\n const recoveredFromLayerProblem = runtime.layerProblem !== null;\n runtime.layerProblem = null;\n\n // A Tempo Suspense boundary showing only its pending marker has no\n // representable state: the content it will show is still loading. Report\n // that and HOLD this flush's work — leaving the accumulator undrained is\n // what re-queues it, so the next drain sees these records alongside the\n // content commit. Because the episode ends by serving a full baseline,\n // the held records are then consumed and superseded wholesale — and a\n // root-element attribute mutated during the episode is lost with them,\n // since document-lane fulls carry no rootAttributes (the recorded\n // bounded edge of this design). Retained semantic candidates need no\n // special handling: `captureSemanticRegions` already drops any fiber\n // the committed root no longer contains. A root showing only the\n // unavailable marker is held the same way and reported as\n // `unavailable`: its content waits on something outside the page for\n // an unknown time, which the destination must not time out. A change\n // of reason within one episode (a Flutter board's starting → loading)\n // is reported once more, and so is a full requested during it: that\n // is a destination asking for this root's state (a receiver that\n // subscribed mid-episode), and over a minutes-long unavailable\n // episode silence would read to it as a host that never sends.\n const waiting = isProjectionUnavailableOnly(runtime.options.element)\n ? \"unavailable\"\n : isProjectionPendingOnly(runtime.options.element)\n ? \"suspended\"\n : null;\n if (waiting !== null) {\n runtime.deferredFullRequest ||= flushContext.fullRequested;\n if (runtime.waitingEpisode === waiting && !flushContext.fullRequested)\n return null;\n runtime.waitingEpisode = waiting;\n const problem = { reason: waiting } as const;\n captureStats.set(problem, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes: 0,\n domNodes: 0,\n htmlChars: 0,\n states: 0,\n portals: 0,\n observedFiles: 0,\n candidatesAfter: 0,\n fullReason: null,\n }),\n });\n return { kind: \"problem\", problem };\n }\n\n // Ending an episode means the subtree was just rebuilt from nothing, so\n // every fiber in it is new. A patch would carry semantic regions naming\n // ids the destination has never published, which it can only answer with\n // a resync baseline — one wasted round trip per suspense resolution.\n // Serve the baseline directly instead.\n const endedSuspendedEpisode = runtime.waitingEpisode !== null;\n runtime.waitingEpisode = null;\n\n // A normal patch flush can observe an unmounted root, so discard facts\n // it no longer publishes.\n if (\n runtime.committedFiber === null &&\n runtime.layerAdapter.layerFramework === \"react\"\n )\n clearPublishedHostProps(runtime);\n\n const fullRequested =\n flushContext.fullRequested ||\n runtime.deferredFullRequest ||\n endedSuspendedEpisode ||\n recoveredFromLayerProblem ||\n runtime.publishedLayerFramework !== runtime.layerAdapter.layerFramework;\n /** One current self-contained baseline for this root; it supersedes\n * every pending region, metadata and observer-local candidate. */\n const serveFull = (unchanged: boolean) => {\n runtime.repairPaths = [];\n runtime.deferredFullRequest = false;\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n runtime.semanticDiscoveryNodesVisited = 0;\n const fiberTarget = resolveFiberTarget(runtime.options);\n const captured = captureProjectionFullSnapshot({\n root: runtime.options.element,\n fiberTarget,\n portals: accumulator.portalElements(),\n layerAdapter: runtime.layerAdapter,\n });\n const { snapshot } = captured;\n accumulator.rememberCoordinates(snapshot.dom.coordinates);\n const documentContext = JSON.stringify([\n snapshot.dom.documentElementAttributes,\n snapshot.dom.bodyAttributes,\n snapshot.dom.baseUrl,\n ]);\n const sameDocumentContext =\n runtime.publishedDocumentContext === documentContext;\n runtime.publishedDocumentContext = documentContext;\n runtime.publishedLayerFramework = runtime.layerAdapter.layerFramework;\n clearPublishedHostProps(runtime);\n for (const tree of projectionLayerRoots(snapshot.layers))\n rememberPublishedHostProps(runtime, tree);\n const absentFiles = captureAbsentFiles(\n runtime,\n snapshot.observedFiles,\n true,\n );\n if (absentFiles) Object.assign(snapshot, { absentFiles });\n captureStats.set(snapshot, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes: captured.semanticNodesSerialized,\n domNodes: captured.hostDomIdCount,\n htmlChars:\n snapshot.dom.html.length +\n snapshot.dom.portals.reduce(\n (sum, portal) =>\n sum + (portal.kind === \"replace\" ? portal.html.length : 0),\n 0,\n ),\n states: snapshot.dom.state.length,\n portals: snapshot.dom.portals.length,\n observedFiles: Object.keys(snapshot.observedFiles).length,\n candidatesAfter: 1,\n fullReason: fullReason(flushContext, openingRoot),\n }),\n });\n return {\n kind: \"full\",\n snapshot,\n unchanged: unchanged && sameDocumentContext,\n } as const;\n };\n const repairs: { element: Element; capture: ProjectionRegionCapture }[] =\n [];\n let repairNeedsFull = false;\n for (const path of runtime.repairPaths) {\n const anchor = [...path, PROJECTION_ROOT_TARGET_ID].find((id) =>\n resolveRegionElement(\n runtime.options.element,\n id,\n accumulator.portalElements(),\n ),\n )!;\n if (anchor === PROJECTION_ROOT_TARGET_ID) {\n repairNeedsFull = true;\n break;\n }\n const element = resolveRegionElement(\n runtime.options.element,\n anchor,\n accumulator.portalElements(),\n )!;\n const capture = captureProjectionRegion(\n runtime.options.element,\n anchor,\n accumulator.portalElements(),\n );\n if (capture) repairs.push({ element, capture });\n }\n if (fullRequested || repairNeedsFull) {\n // Consume observer-local candidates because this baseline supersedes\n // them with one current self-contained state.\n const accumulated = runtime.accumulator.capturePatch();\n const unchanged =\n accumulated.kind === \"empty\" &&\n runtime.pendingRegions.size === 0 &&\n (runtime.pendingMetadata.size === 0 ||\n ([...runtime.pendingMetadata.values()].every(\n (entry) => entry.layoutOnly,\n ) &&\n captureSemanticMetadata(runtime, new Set()).length === 0)) &&\n !endedSuspendedEpisode &&\n !recoveredFromLayerProblem &&\n runtime.publishedLayerFramework ===\n runtime.layerAdapter.layerFramework;\n return serveFull(unchanged);\n }\n\n let accumulated = runtime.accumulator.capturePatch({\n // MutationObserver's parent is stable across a React commit. The\n // unkeyed child ids React may reuse within that parent are not.\n regionalChildLists: true,\n retainDomLayerTargets: runtime.layerAdapter.retainDomMutationTargets,\n });\n if (repairs.length) {\n const previous = accumulated.kind === \"patch\" ? accumulated : null;\n const patch = previous?.patch;\n const files = new ProjectionObservedFileAccumulator();\n files.merge(patch?.observedFiles);\n for (const { capture } of repairs) files.merge(capture.observedFiles);\n accumulated = {\n kind: \"patch\",\n patch: {\n ...patch,\n dom: [\n ...(patch?.dom ?? []),\n ...repairs.map(({ capture }) => ({\n kind: \"children\" as const,\n targetId: capture.targetId,\n html: capture.html,\n ancestorIds: capture.ancestorIds,\n })),\n ],\n state: [\n ...(patch?.state ?? []),\n ...repairs.flatMap(({ capture }) => capture.state),\n ],\n observedFiles: files.snapshot(),\n repairedAncestors: repairs.map(({ capture }) => capture.targetId),\n },\n localMetadataTargets: previous?.localMetadataTargets ?? [],\n localDomLayerTargets: {\n structural: [\n ...(previous?.localDomLayerTargets?.structural ?? []),\n ...repairs.map(({ element }) => element),\n ],\n metadata: previous?.localDomLayerTargets?.metadata ?? [],\n },\n };\n }\n runtime.repairPaths = [];\n if (accumulated.kind === \"patch\") {\n for (const element of accumulated.localMetadataTargets) {\n runtime.semanticDiscoveryNodesVisited += addElementFiberCandidate(\n runtime,\n element,\n );\n }\n }\n\n if (\n accumulated.kind === \"patch\" &&\n runtime.layerAdapter.layerFramework === \"react\"\n ) {\n const targets = accumulated.localDomLayerTargets;\n // Nothing under a Flutter view root is a published layer, so a\n // mutation there (the engine attaching or restyling its view) is\n // the root's to rebuild; a region below it would name an unknown\n // node (projection-flutter-layers.ts).\n const atFlutterRoot = (target: Element) =>\n flutterViewRootOf(target) ?? target;\n for (const target of targets?.structural ?? []) {\n const element = atFlutterRoot(target);\n let candidate = runtime.layerAdapter.resolveElementCandidate(element);\n if (!candidate) continue;\n for (const child of Array.from(element.children)) {\n const moved = runtime.layerAdapter.resolveElementCandidate(child);\n if (!moved) continue;\n // An imperatively moved host still has its original Fiber parent.\n // Capture both slots together so the binding moves in one region.\n let common: Fiber | null = candidate;\n while (common && !fiberContains(common, moved))\n common = common.return;\n if (common) candidate = common;\n }\n addRegion(runtime, candidate);\n }\n for (const target of targets?.metadata ?? []) {\n const element = atFlutterRoot(target);\n const candidate =\n runtime.layerAdapter.resolveElementCandidate(element);\n if (!candidate) continue;\n // A Flutter view root's attributes change only when the SDK\n // runtime added its view or stored a new widget snapshot for it\n // (its rev). The snapshot is the root's whole subtree, so it is a\n // region, not metadata on one node (projection-flutter-layers.ts).\n if (isFlutterViewRoot(element)) {\n addRegion(runtime, candidate);\n continue;\n }\n // A raw descendant has no semantic Fiber node to receive metadata.\n // Replace its nearest annotated ancestor's DOM-backed subtree.\n if (getFiberFromElement(element)) continue;\n addRegion(runtime, candidate);\n }\n }\n // The loops above may have found the root rebuilt from nothing (its top\n // element remounted). A patch would name never-published ids; the\n // baseline supersedes this flush's candidates instead.\n if (runtime.deferredFullRequest) return serveFull(false);\n const regions = captureSemanticRegions(runtime);\n const metadata = captureSemanticMetadata(runtime, regions.coveredFibers);\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n\n const basePatch =\n accumulated.kind === \"patch\" ? accumulated.patch : ({} as const);\n const observedFiles = new ProjectionObservedFileAccumulator();\n observedFiles.merge(basePatch.observedFiles);\n const layerObservedFiles = new ProjectionObservedFileAccumulator();\n layerObservedFiles.merge(basePatch.layers?.observedFiles);\n for (const region of regions.snapshots) {\n observedFiles.merge(region.observedFiles);\n layerObservedFiles.merge(region.observedFiles);\n }\n const adapterLayerPatch = runtime.layerAdapter.capturePatch(\n runtime.options.element,\n accumulated.kind === \"patch\"\n ? (accumulated.localDomLayerTargets ?? {\n structural: [],\n metadata: [],\n })\n : { structural: [], metadata: [] },\n observedFiles.snapshot(),\n );\n for (const region of adapterLayerPatch?.regions ?? []) {\n if (region.scope) clearPublishedHostProps(runtime);\n else forgetPublishedSubtree(runtime, region.targetFiberId);\n for (const tree of region.scope?.children ?? [region.tree])\n rememberPublishedHostProps(runtime, tree);\n observedFiles.merge(region.observedFiles);\n layerObservedFiles.merge(region.observedFiles);\n }\n for (const snapshot of adapterLayerPatch?.metadata ?? metadata) {\n if (adapterLayerPatch && snapshot.props)\n updatePublishedMetadata(runtime, snapshot);\n observedFiles.addLayerProps(snapshot.props);\n layerObservedFiles.addLayerProps(snapshot.props);\n }\n const observedSnapshot = observedFiles.snapshot();\n const layerObservedSnapshot = layerObservedFiles.snapshot();\n const patch: ProjectionRootPatch = {\n ...basePatch,\n ...(adapterLayerPatch\n ? { layers: adapterLayerPatch }\n : regions.snapshots.length > 0 || metadata.length > 0\n ? {\n layers: {\n ...(regions.snapshots.length > 0\n ? { regions: regions.snapshots }\n : {}),\n ...(metadata.length > 0 ? { metadata } : {}),\n },\n }\n : {}),\n ...(Object.keys(observedSnapshot).length > 0\n ? { observedFiles: observedSnapshot }\n : {}),\n };\n if (basePatch.layers?.metadata?.length) {\n Object.assign(patch, {\n layers: {\n ...patch.layers,\n metadata: [\n ...(patch.layers?.metadata ?? []).filter(\n (entry) => entry.content === undefined,\n ),\n ...basePatch.layers.metadata,\n ],\n },\n });\n }\n if (Object.keys(layerObservedSnapshot).length > 0) {\n Object.assign(patch, {\n layers: { ...patch.layers, observedFiles: layerObservedSnapshot },\n });\n }\n\n const absentFiles = captureAbsentFiles(runtime, observedSnapshot, false);\n if (absentFiles) Object.assign(patch, { absentFiles });\n\n if (Object.keys(patch).length === 0) {\n runtime.semanticDiscoveryNodesVisited = 0;\n return null;\n }\n\n const semanticNodes = regions.semanticNodesSerialized;\n const semanticDiscoveryNodesVisited =\n runtime.semanticDiscoveryNodesVisited;\n runtime.semanticDiscoveryNodesVisited = 0;\n captureStats.set(patch, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes,\n domNodes: patch.dom?.length ?? 0,\n htmlChars: patchHtmlChars(patch),\n states: patch.state?.length ?? 0,\n portals: patch.portals?.length ?? 0,\n observedFiles: Object.keys(observedSnapshot).length,\n candidatesAfter:\n (patch.dom?.length ?? 0) +\n regions.snapshots.length +\n metadata.length,\n semanticDiscoveryNodesVisited,\n fullReason: null,\n }),\n });\n return { kind: \"patch\", patch };\n },\n captureHead(flushContext) {\n // The head describes the document, not any one root. A root that cannot\n // render still shares the stylesheets its healthy siblings render with.\n if (flushContext.candidateRootCount === 0) resetCaptureFlushCounters();\n const startedAt = Date.now();\n const head = preparedHead\n ? preparedHead.capture(options.styleResource)\n : captureHead(options.document, options.styleResource);\n headSnapshotMs = Date.now() - startedAt;\n headPerfContext = flushContext;\n return head;\n },\n });\n\n function recordReactCommit(commit: FiberRoot): void {\n if (stopped || !sessionBound) return;\n const affectedRootIds: string[] = [];\n let retainedDomRecords = false;\n for (const [rootId, runtime] of roots) {\n if (runtime.dormant) continue;\n const current = runtime.layerAdapter.resolveCommittedRoot(\n commit,\n runtime.options,\n );\n if (\n !current &&\n runtime.options.scope !== undefined &&\n commit.containerInfo instanceof Element &&\n runtime.options.element.contains(commit.containerInfo) &&\n !underForeignProjectionRoot(\n commit.containerInfo,\n runtime.options.element,\n )\n ) {\n // A DOM-owned scope can contain independent React roots. No one of\n // them becomes the scope identity; publish their complete forest.\n runtime.pendingRegions.set(PROJECTION_SCOPE_TARGET, commit.current);\n retainedDomRecords =\n (runtime.accumulator?.takePendingDomRecords() ?? 0) > 0 ||\n retainedDomRecords;\n affectedRootIds.push(rootId);\n continue;\n }\n if (!current || current === runtime.committedFiber) continue;\n if (\n runtime.renderError !== null ||\n readProjectionRenderError(runtime.options.element) !== null\n ) {\n // MutationObserver owns the explicit problem/clear transition. Keep\n // Fiber identity current without racing an ordinary patch against it.\n runtime.committedFiber = current;\n continue;\n }\n if (\n runtime.committedFiber &&\n (!fiberContains(runtime.committedFiber, current) ||\n (!fiberPair(runtime.committedFiber, current) &&\n runtime.publishedHostProps.has(\n runtime.layerAdapter.layerSourceId(runtime.committedFiber) ?? \"\",\n )))\n ) {\n // Replacing a published capture root replaces the whole layer tree,\n // even with a surviving descendant (several returns became one).\n // Patching only that descendant would leave its old siblings attached.\n // Unpublished plumbing can still narrow onto a newly visible child.\n runtime.deferredFullRequest = true;\n }\n if (runtime.committedFiber) {\n runtime.semanticDiscoveryNodesVisited += recordCommitSemanticChanges(\n runtime,\n commit,\n runtime.committedFiber,\n current,\n );\n // React and MutationObserver are independent authorities. Record the\n // commit's semantic regions, then drain already-queued DOM records into\n // the same fixed window. Each stream contributes only its own domain.\n retainedDomRecords =\n (runtime.accumulator?.takePendingDomRecords() ?? 0) > 0 ||\n retainedDomRecords;\n }\n runtime.committedFiber = current;\n affectedRootIds.push(rootId);\n }\n if (affectedRootIds.length > 0) {\n core.record({ rootIds: affectedRootIds, trigger: \"react-commit\" });\n if (retainedDomRecords) {\n core.record({ rootIds: affectedRootIds, trigger: \"dom-mutation\" });\n }\n }\n }\n\n function startRootObserver(rootId: string, runtime: RootRuntime<T>): void {\n if (runtime.stopAttachment === null && runtime.options.onRootAttached)\n runtime.stopAttachment = runtime.options.onRootAttached(\n runtime.options.element,\n );\n if (!sessionBound || runtime.accumulator) return;\n const unregisterRootObserver = registerCaptureRootObserver();\n try {\n const accumulator = createProjectionRootAccumulator({\n root: runtime.options.element,\n onChange(trigger) {\n if (!runtime.options.element.isConnected) {\n makeRootDormant(runtime);\n return;\n }\n const renderError = readProjectionRenderError(\n runtime.options.element,\n );\n if (renderError) {\n if (runtime.renderError === null) {\n runtime.renderError = renderError;\n // Problems are ordered events but do not wait for the hot window.\n core.requestFull(rootId, { trigger: \"render-problem\" });\n }\n return;\n }\n if (runtime.renderError !== null) {\n runtime.renderError = null;\n // This root's stream resumes on its own baseline. A sibling still\n // in a problem state owns its own recovery and never delays this\n // one.\n core.requestFull(rootId, { trigger: \"render-recovery\" });\n return;\n }\n core.record({ rootIds: [rootId], trigger });\n },\n });\n runtime.accumulator = accumulator;\n // A runtime signal the patch lane cannot attribute (a Vue hot update)\n // supersedes this root's tree with one baseline.\n const stopBaselineRequests =\n runtime.layerAdapter.observeBaselineRequests?.(() => {\n if (stopped || runtime.dormant) return;\n core.requestFull(rootId, { trigger: \"runtime-hot-update\" });\n }) ?? null;\n runtime.stopObserver = () => {\n try {\n accumulator.stop();\n } finally {\n stopBaselineRequests?.();\n unregisterRootObserver();\n if (runtime.accumulator === accumulator) runtime.accumulator = null;\n runtime.stopObserver = null;\n }\n };\n } catch (error) {\n unregisterRootObserver();\n throw error;\n }\n }\n\n function createRootRuntime(\n rootOptions: OwnedRootOptions<T>,\n references: number,\n ): RootRuntime<T> {\n const layerAdapter = createProjectionLayerAdapter(\n rootOptions.layerFramework,\n rootOptions.element,\n rootOptions.scope,\n );\n return {\n repairPaths: [],\n options: rootOptions,\n layerAdapter,\n dormant: false,\n accumulator: null,\n stopObserver: null,\n stopAttachment: null,\n references,\n committedFiber: layerAdapter.resolveCommittedRoot(undefined, rootOptions),\n renderError: readProjectionRenderError(rootOptions.element),\n layerProblem: null,\n pendingRegions: new Map(),\n filePresence: new Map(),\n disappearedFiles: new Set(),\n publishedHostProps: new Map(),\n pendingMetadata: new Map(),\n semanticDiscoveryNodesVisited: 0,\n waitingEpisode: null,\n deferredFullRequest: false,\n publishedLayerFramework: null,\n };\n }\n\n function stopRootObserver(runtime: RootRuntime<T>): void {\n runCleanup(runtime.stopObserver ?? (() => {}));\n const stopAttachment = runtime.stopAttachment;\n runtime.stopAttachment = null;\n if (stopAttachment) runCleanup(stopAttachment);\n }\n\n function makeRootDormant(runtime: RootRuntime<T>): void {\n if (runtime.dormant) return;\n stopRootObserver(runtime);\n runtime.dormant = true;\n clearPublishedHostProps(runtime);\n runtime.committedFiber = null;\n runtime.renderError = null;\n runtime.layerProblem = null;\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n runtime.semanticDiscoveryNodesVisited = 0;\n runtime.waitingEpisode = null;\n runtime.deferredFullRequest = false;\n }\n\n function rebindRoot(\n rootId: string,\n previous: RootRuntime<T>,\n rootOptions: OwnedRootOptions<T>,\n references: number,\n ): RootRuntime<T> {\n // A hot-swap can replace the selector's element wholesale. Treat that as\n // element succession: the logical root survives, but Fiber identity must\n // restart from a fresh serializer and a fresh full baseline.\n makeRootDormant(previous);\n const runtime = createRootRuntime(rootOptions, references);\n roots.set(rootId, runtime);\n try {\n startRootObserver(rootId, runtime);\n } catch (error) {\n stopRootObserver(runtime);\n roots.set(rootId, previous);\n throw error;\n }\n core.requestFull(rootId, { trigger: \"selector-rebind\" });\n return runtime;\n }\n\n function reconcileSelectorRoots(): void {\n if (stopped) return;\n for (const [rootId, runtime] of roots) {\n const selector = runtime.options.selector;\n if (selector === undefined) continue;\n if (!runtime.dormant && !runtime.options.element.isConnected) {\n makeRootDormant(runtime);\n }\n if (!runtime.dormant) continue;\n const element = options.document.querySelector(selector);\n if (!element?.isConnected) continue;\n rebindRoot(\n rootId,\n runtime,\n { ...runtime.options, element },\n runtime.references,\n );\n }\n }\n\n function syncRootLifecycleObserver(): void {\n const hasSelectorRoots = Array.from(roots.values()).some(\n (runtime) => runtime.options.selector !== undefined,\n );\n if (hasSelectorRoots && !rootLifecycleObserver) {\n rootLifecycleObserver = new MutationObserver(reconcileSelectorRoots);\n rootLifecycleObserver.observe(options.document, {\n childList: true,\n subtree: true,\n });\n } else if (!hasSelectorRoots && rootLifecycleObserver) {\n rootLifecycleObserver.disconnect();\n rootLifecycleObserver = null;\n }\n }\n\n function resolveOwnedRootOptions(\n rootOptions: CombinedProjectionRootOptions<T>,\n ): OwnedRootOptions<T> {\n if (\n rootOptions.scope !== undefined &&\n rootOptions.fiberSelector !== undefined\n )\n throw new Error(\n \"A contents watch has one scope; it cannot also specify a fiberSelector\",\n );\n // A fiber-only root is owned by its fiber selector: the same element is\n // the DOM endpoint, and the same heal follows it across replacements.\n const selector =\n rootOptions.selector ??\n (rootOptions.element === undefined\n ? rootOptions.fiberSelector\n : undefined);\n if (selector === undefined) {\n if (rootOptions.element === undefined) {\n throw new Error(\n `Projection root ${JSON.stringify(rootOptions.rootId)} needs an element or a fiberSelector`,\n );\n }\n return { ...rootOptions, element: rootOptions.element };\n }\n const element = options.document.querySelector(selector);\n if (!element) {\n throw new Error(\n `Projection root selector ${JSON.stringify(selector)} did not match`,\n );\n }\n return { ...rootOptions, selector, element };\n }\n\n function runCleanup(cleanup: () => void): void {\n try {\n cleanup();\n } catch (error) {\n try {\n options.onError?.(error);\n } catch {\n // Cleanup must continue when error reporting itself fails.\n }\n }\n }\n\n let stopReactCommits: () => void = () => {};\n let stopHeadChanges: () => void = () => {};\n const stopAssets = observeDocumentAssets(options.document, (target) => {\n if (stopped) return;\n const assetRootIds: string[] = [];\n for (const [id, root] of roots) {\n if (root.dormant || !root.options.element.isConnected) continue;\n if (\n target === null ||\n (root.options.element.contains(target) &&\n !underForeignProjectionRoot(target, root.options.element)) ||\n root.accumulator\n ?.portalElements()\n .some((portal) => portal.contains(target))\n )\n assetRootIds.push(id);\n }\n if (assetRootIds.length > 0) core.record({ assetRootIds });\n });\n sourceWindow?.addEventListener(\"resize\", recordSourceViewport);\n try {\n stopReactCommits = reactHook.onCommit(recordReactCommit);\n const headSubscription = getHeadTracker().subscribe(\n options.document,\n () => {\n if (stopped) return;\n // New styling can move a portal without mutating it, so the roots that\n // own portals ride in the same batch as the head that moved them —\n // their capture refreshes any portal frame the styling changed.\n const rootIds: string[] = [];\n for (const [rootId, runtime] of roots) {\n if (\n runtime.accumulator?.hasPortals() ||\n runtime.accumulator?.hasCoordinateFrame()\n )\n rootIds.push(rootId);\n }\n core.record({\n head: true,\n rootIds,\n trigger: \"head-mutation\",\n });\n },\n );\n stopHeadChanges = () => headSubscription.unsubscribe();\n } catch (error) {\n stopAssets();\n runCleanup(stopReactCommits);\n moduleLog?.close();\n sourceWindow?.removeEventListener(\"resize\", recordSourceViewport);\n core.stop();\n preparedHead?.dispose();\n throw error;\n }\n const unregisterDocumentProducer = registerDocumentCaptureProducer(\n options.document,\n );\n\n return {\n bindSession(sessionId) {\n core.bindSession(sessionId);\n seedProjectionIds(sessionId);\n sessionBound = true;\n for (const [rootId, runtime] of roots) {\n if (!runtime.dormant) startRootObserver(rootId, runtime);\n }\n },\n setRootSize: (rootId, size) => core.setRootSize(rootId, size),\n watchRoot(requestedRootOptions) {\n if (stopped) throw new Error(\"Projection producer has been stopped\");\n const rootOptions = resolveOwnedRootOptions(requestedRootOptions);\n const existing = roots.get(rootOptions.rootId);\n if (existing) {\n if (\n existing.options.element === rootOptions.element &&\n existing.options.scope === rootOptions.scope &&\n existing.options.fiberSelector === rootOptions.fiberSelector &&\n existing.options.selector === rootOptions.selector\n ) {\n existing.references += 1;\n return;\n }\n if (\n existing.options.element !== rootOptions.element &&\n !existing.options.element.isConnected\n ) {\n rebindRoot(\n rootOptions.rootId,\n existing,\n rootOptions,\n existing.references + 1,\n );\n syncRootLifecycleObserver();\n return;\n }\n throw new Error(\n `Projection root ${JSON.stringify(rootOptions.rootId)} has conflicting options`,\n );\n }\n const runtime = createRootRuntime(rootOptions, 1);\n roots.set(rootOptions.rootId, runtime);\n try {\n startRootObserver(rootOptions.rootId, runtime);\n // A component can inject CSS in the same commit that admits its root.\n // Drain the existing shared observer before trusting a retained head.\n if (rootOptions.knownHead)\n getHeadTracker().flushPending?.(options.document);\n core.addRoot(\n rootOptions.rootId,\n rootOptions.receiverCredit,\n rootOptions.userInitiated,\n rootOptions.knownHead,\n );\n syncRootLifecycleObserver();\n } catch (error) {\n roots.delete(rootOptions.rootId);\n core.removeRoot(rootOptions.rootId);\n stopRootObserver(runtime);\n syncRootLifecycleObserver();\n throw error;\n }\n },\n unwatchRoot(rootId) {\n const runtime = roots.get(rootId);\n if (!runtime) return;\n runtime.references -= 1;\n if (runtime.references > 0) return;\n roots.delete(rootId);\n core.removeRoot(rootId);\n stopRootObserver(runtime);\n syncRootLifecycleObserver();\n },\n requestRepair(rootId, paths) {\n const runtime = roots.get(rootId);\n if (!runtime || stopped) return;\n runtime.repairPaths = [...runtime.repairPaths, ...paths];\n core.requestRepair(rootId);\n },\n requestFull: (rootId, requestOptions) =>\n core.requestFull(rootId, {\n ...requestOptions,\n trigger: \"receiver-baseline\",\n }),\n acknowledge: (sessionId, rootId, sequence) =>\n core.acknowledge(sessionId, rootId, sequence),\n captureSemanticSubtree(rootId, targetFiberId, options) {\n if (stopped) throw new Error(\"Projection producer has been stopped\");\n const runtime = roots.get(rootId);\n if (!runtime || runtime.dormant || !runtime.options.element.isConnected) {\n return null;\n }\n const current = runtime.layerAdapter.resolveCommittedRoot(\n undefined,\n runtime.options,\n );\n if (!current && runtime.options.scope === undefined) return null;\n runtime.committedFiber = current;\n return runtime.layerAdapter.captureSemanticSubtree(\n runtime.options,\n targetFiberId,\n options,\n );\n },\n captureRegion(rootId, targetId) {\n if (stopped) throw new Error(\"Projection producer has been stopped\");\n const runtime = roots.get(rootId);\n if (!runtime || runtime.dormant || !runtime.options.element.isConnected) {\n return null;\n }\n return captureProjectionRegion(\n runtime.options.element,\n targetId,\n runtime.accumulator?.portalElements() ?? [],\n );\n },\n stop() {\n if (stopped) return;\n stopped = true;\n core.stop();\n preparedHead?.dispose();\n for (const runtime of roots.values()) {\n stopRootObserver(runtime);\n }\n rootLifecycleObserver?.disconnect();\n rootLifecycleObserver = null;\n runCleanup(stopReactCommits);\n if (moduleGraceTimer !== null) clearTimeout(moduleGraceTimer);\n moduleGraceTimer = null;\n moduleLog?.close();\n runCleanup(stopHeadChanges);\n runCleanup(stopAssets);\n sourceWindow?.removeEventListener(\"resize\", recordSourceViewport);\n unregisterDocumentProducer();\n roots.clear();\n },\n };\n}\n\nfunction readProjectionRenderError(\n root: Element,\n): ProjectionRenderErrorProblem | null {\n const selector = '[data-render-error=\"true\"]';\n // A storyboard's error sentinel sits inside its content slot; it is that\n // root's problem, never the page root's above it.\n const sentinel = root.matches(selector)\n ? root\n : Array.from(root.querySelectorAll(selector)).find(\n (candidate) => !underForeignProjectionRoot(candidate, root),\n );\n if (!sentinel) return null;\n return {\n reason: \"render-error\",\n message: sentinel.getAttribute(\"data-render-error-message\"),\n };\n}\n\nfunction resolveFiberTarget<T extends EnrichedFiberConstraint>(\n options: OwnedRootOptions<T>,\n): Element | null {\n // Search only this root's subtree. The root itself wins when descendants\n // share its selector (Canvas and mounted storyboard shells do).\n return options.fiberSelector\n ? options.element.matches(options.fiberSelector)\n ? options.element\n : options.element.querySelector(options.fiberSelector)\n : (options.element.firstElementChild ?? options.element);\n}\n\n/**\n * React's development FiberRoot exposes both the exact scheduling Fibers and\n * their valid before/after generations only while `onCommitFiberRoot` is\n * executing. Discover the affected semantic regions at that boundary, then\n * defer serialization of those regions until the fixed final-state window\n * closes. Later commits can reuse both Fiber generations, so deferring the\n * comparison itself would lose the earlier change.\n *\n * The fallback is the changed watched endpoint itself. It preserves\n * correctness for renderers that do not expose updater tracking, while Tempo's\n * normal development renderer takes the exact K-candidate path.\n */\nfunction recordCommitSemanticChanges<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n commit: FiberRoot,\n previousRoot: Fiber,\n currentRoot: Fiber,\n): number {\n const candidates: Fiber[] = [];\n let tracked = false;\n for (const scheduled of commit.memoizedUpdaters ?? []) {\n tracked = true;\n const candidate = resolveCommittedFiberOrNull(scheduled);\n if (!candidate) {\n // The commit unmounted its own scheduling component, so there is no\n // representable candidate for it. Its removal still changed the watched\n // tree: fall back to the whole watched root rather than dropping it.\n retainSemanticCandidate(candidates, currentRoot);\n continue;\n }\n if (fiberWithinRoot(currentRoot, candidate)) {\n retainSemanticCandidate(candidates, candidate);\n } else if (\n fiberContains(candidate, currentRoot) ||\n fiberContains(scheduled, previousRoot)\n ) {\n // The scheduling component wraps the selected projection boundary. Its\n // exact representable candidate is the watched root, never that outside\n // owner or any of its siblings.\n retainSemanticCandidate(candidates, currentRoot);\n }\n }\n // Without updater tracking the changed watched endpoint is the candidate.\n // With it, a commit whose updaters all lie in another root's element below\n // this one (content under the page root) changed nothing here.\n if (!tracked) retainSemanticCandidate(candidates, currentRoot);\n\n let nodesVisited = 0;\n for (const candidate of candidates) {\n const currentCandidate = resolveCommittedFiberOrNull(candidate);\n if (!currentCandidate) {\n const rootBoundary = nearestProjectionBoundary(runtime, currentRoot);\n if (rootBoundary) addRegion(runtime, rootBoundary);\n continue;\n }\n const previousCandidate = currentCandidate.alternate;\n if (!previousCandidate) {\n const boundary = nearestProjectionBoundary(runtime, currentCandidate);\n if (boundary) addRegion(runtime, boundary);\n continue;\n }\n nodesVisited += collectChangedSemanticFibers(\n previousCandidate,\n currentCandidate,\n runtime,\n );\n }\n return nodesVisited;\n}\n\nfunction retainSemanticCandidate(candidates: Fiber[], candidate: Fiber): void {\n for (const existing of candidates) {\n if (fiberPair(existing, candidate) || fiberContains(existing, candidate)) {\n return;\n }\n }\n for (let index = candidates.length - 1; index >= 0; index -= 1) {\n const existing = candidates[index];\n if (existing && fiberContains(candidate, existing)) {\n candidates.splice(index, 1);\n }\n }\n candidates.push(candidate);\n}\n\nfunction collectChangedSemanticFibers<T extends EnrichedFiberConstraint>(\n previous: Fiber,\n current: Fiber,\n runtime: RootRuntime<T>,\n): number {\n let nodesVisited = 0;\n const visit = (before: Fiber, after: Fiber, boundary: Fiber): void => {\n nodesVisited += 1;\n if (before === after) return;\n if (\n isProjectionRootFiber(after) &&\n !(\n runtime.options.scope !== undefined &&\n runtime.committedFiber &&\n fiberPair(after, runtime.committedFiber)\n )\n )\n return;\n const nextBoundary = isProjectionLayerFiber(after) ? after : boundary;\n if (!fiberPair(before, after)) {\n addRegion(runtime, nextBoundary);\n return;\n }\n if (\n !projectionPropsEqual(\n before,\n after,\n runtime.layerAdapter,\n runtime.publishedHostProps,\n )\n ) {\n addMetadata(runtime, after, \"fiber\");\n } else if (\n after.tag === FiberTag.HostComponent &&\n runtime.publishedHostProps.has(\n runtime.layerAdapter.layerSourceId(after) ?? \"\",\n )\n ) {\n // Parent selectors can change a child's layout without changing its own\n // props. Check those modes after React's commit, when style reads can\n // share one settled layout; unchanged modes emit no metadata.\n addMetadata(runtime, after, \"fiber\", true);\n }\n if (before.child === after.child) return;\n\n let oldChild = before.child;\n let newChild = after.child;\n while (oldChild && newChild) {\n if (!fiberPair(oldChild, newChild)) {\n addRegion(runtime, nextBoundary);\n return;\n }\n visit(oldChild, newChild, nextBoundary);\n oldChild = oldChild.sibling;\n newChild = newChild.sibling;\n }\n if (oldChild || newChild) addRegion(runtime, nextBoundary);\n };\n\n const boundary = nearestProjectionBoundary(runtime, current);\n if (boundary) visit(previous, current, boundary);\n return nodesVisited;\n}\n\nfunction fiberPair(left: Fiber, right: Fiber): boolean {\n return left === right || left.alternate === right || right.alternate === left;\n}\n\nfunction nearestProjectionBoundary<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n fiber: Fiber,\n): Fiber | null {\n let current: Fiber | null = fiber;\n while (current) {\n if (runtime.committedFiber && fiberPair(current, runtime.committedFiber))\n return current;\n if (isProjectionLayerFiber(current)) {\n if (current.tag === FiberTag.HostComponent) return current;\n // Repeated component ids in the published parent's child list are\n // separate DOM runs. Update their annotations together at the host.\n let child = current;\n let split = false;\n for (let parent = current.return; parent; parent = parent.return) {\n const atRoot =\n runtime.committedFiber && fiberPair(parent, runtime.committedFiber);\n if (!atRoot && !isProjectionLayerFiber(parent)) continue;\n const parentId = runtime.layerAdapter.layerSourceId(parent);\n const childId = runtime.layerAdapter.layerSourceId(child);\n const children = parentId\n ? runtime.publishedHostProps.get(parentId)?.children\n : undefined;\n if (children && childId)\n split ||= children.indexOf(childId) !== children.lastIndexOf(childId);\n if (parent.tag === FiberTag.HostComponent || atRoot)\n return split ? parent : current;\n child = parent;\n }\n return current;\n }\n current = current.return;\n }\n return null;\n}\n\nfunction addElementFiberCandidate<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n element: Element,\n): number {\n const candidate = runtime.layerAdapter.resolveElementCandidate(element);\n if (!candidate) return 0;\n // DOM observation is not evidence that the Fiber tree changed. React's\n // commit stream owns semantic regions. The only intentional crossover is a\n // source annotation stamped directly on a host element, whose exact live\n // value must update that one already-published semantic node.\n addMetadata(runtime, candidate, \"live-host\");\n return 1;\n}\n\nfunction addRegion<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n fiber: Fiber,\n): void {\n fiber = nearestProjectionBoundary(runtime, fiber) ?? fiber;\n // Only a boundary spanning portal membership or physical placement needs\n // closed old/new ownership. A change inside surviving content stays local.\n const closure = runtime.layerAdapter.portalClosure?.(fiber);\n runtime.semanticDiscoveryNodesVisited += closure?.nodesVisited ?? 0;\n if (runtime.committedFiber && closure?.required)\n fiber = runtime.committedFiber;\n // A region lives strictly inside the watched root. A candidate at or above\n // it (the root element's own childList record resolves to the page-root\n // layer around it when the root's top element was remounted) means the\n // subtree was rebuilt from nothing: like the end of a suspended episode,\n // serve the baseline instead of a patch naming never-published ids.\n // Letting the ancestor in as a region would evict the correct in-root\n // region and then be dropped as out-of-root at capture, leaving DOM ops\n // alone. Anything unrelated is another root's business.\n if (runtime.committedFiber && !fiberContains(runtime.committedFiber, fiber)) {\n if (fiberContains(fiber, runtime.committedFiber))\n runtime.deferredFullRequest = true;\n return;\n }\n const id = runtime.layerAdapter.layerSourceId(fiber);\n if (id === null) return;\n for (const existing of runtime.pendingRegions.values()) {\n if (fiberContains(existing, fiber)) return;\n }\n for (const [existingId, existing] of runtime.pendingRegions) {\n if (fiberContains(fiber, existing))\n runtime.pendingRegions.delete(existingId);\n }\n runtime.pendingRegions.set(id, fiber);\n}\n\nfunction addMetadata<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n fiber: Fiber,\n sourceAnnotations: \"fiber\" | \"live-host\",\n layoutOnly = false,\n): void {\n if (!isProjectionLayerFiber(fiber)) return;\n if (\n runtime.options.scope === \"contents\" &&\n runtime.committedFiber &&\n fiberPair(fiber, runtime.committedFiber)\n )\n return;\n const boundary = nearestProjectionBoundary(runtime, fiber);\n if (boundary && boundary !== fiber) {\n addRegion(runtime, boundary);\n return;\n }\n const id = runtime.layerAdapter.layerSourceId(fiber);\n if (id === null) return;\n const existing = runtime.pendingMetadata.get(id);\n runtime.pendingMetadata.set(id, {\n fiber,\n layoutOnly: layoutOnly && (existing?.layoutOnly ?? true),\n sourceAnnotations:\n existing?.sourceAnnotations === \"live-host\" ||\n sourceAnnotations === \"live-host\"\n ? \"live-host\"\n : \"fiber\",\n });\n}\n\n/** Like fiberContains, but another root's element between the two ends this\n * root's subtree: what lies below it is that root's. */\nfunction fiberWithinRoot(root: Fiber, candidate: Fiber): boolean {\n for (\n let current: Fiber | null = candidate;\n current;\n current = current.return\n ) {\n if (current === root || current.alternate === root) return true;\n if (isProjectionRootFiber(current)) return false;\n }\n return false;\n}\n\nfunction fiberContains(ancestor: Fiber, candidate: Fiber): boolean {\n for (\n let current: Fiber | null = candidate;\n current;\n current = current.return\n ) {\n if (current === ancestor || current.alternate === ancestor) return true;\n }\n return false;\n}\n\nfunction projectionPropsEqual(\n before: Fiber,\n after: Fiber,\n adapter: ProjectionLayerAdapter,\n publishedHostProps: RootRuntime<EnrichedFiberNode>[\"publishedHostProps\"],\n): boolean {\n const id = adapter.layerSourceId(after);\n const published = id === null ? undefined : publishedHostProps.get(id);\n // Commit discovery runs synchronously inside React. Compare semantic props\n // and cheap live attributes here, without forcing computed layout for every\n // host in the candidate subtree. Changed metadata and DOM observations read\n // the actual layout mode later in the normal serialization window.\n const layoutMode = published?.layoutMode ?? null;\n const right = adapter.captureMetadata(after, { layoutMode })?.props;\n const left = adapter.captureMetadata(before, { layoutMode })?.props;\n // Alternates share the live element, already changed before the commit hook.\n // Only the published capture can supply the old class, style and SVG\n // attributes. The alternate capture is still needed for every other prop.\n // Without a published entry there are no prior live host props to compare.\n const liveHostPropsEqual =\n published === undefined ||\n (published.className === right?.className &&\n published.layoutMode === right?.layoutMode &&\n recordEqual(published.style, right?.style) &&\n recordEqual(published.svg, svgLayerAttributesOf(right)));\n return liveHostPropsEqual && layerPropsEqual(left, right);\n}\n\nfunction replacePublishedFile<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n previous: string | undefined,\n next: string | undefined,\n): void {\n if (previous === next) return;\n if (previous) {\n const count = (runtime.filePresence.get(previous) ?? 1) - 1;\n if (count) runtime.filePresence.set(previous, count);\n else {\n runtime.filePresence.delete(previous);\n runtime.disappearedFiles.add(previous);\n }\n }\n if (next)\n runtime.filePresence.set(next, (runtime.filePresence.get(next) ?? 0) + 1);\n}\nfunction clearPublishedHostProps<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n): void {\n for (const file of runtime.filePresence.keys())\n runtime.disappearedFiles.add(file);\n runtime.filePresence.clear();\n runtime.publishedHostProps.clear();\n}\nfunction forgetPublishedSubtree<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n rootId: string,\n): void {\n const retired = [rootId];\n while (retired.length) {\n const id = retired.pop()!;\n const previous = runtime.publishedHostProps.get(id);\n retired.push(...(previous?.children ?? []));\n replacePublishedFile(runtime, previous?.file, undefined);\n runtime.publishedHostProps.delete(id);\n }\n}\nfunction rememberPublishedHostProps<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n tree: ProjectionLayerNode | null,\n): void {\n const pending = tree ? [tree] : [];\n while (pending.length > 0) {\n const node = pending.pop()!;\n const id = node.source?.fiber.id ?? node.id;\n const file = node.props?.[\"data-tempo-filepath\"];\n replacePublishedFile(\n runtime,\n runtime.publishedHostProps.get(id)?.file,\n file,\n );\n runtime.publishedHostProps.set(id, {\n file,\n className: node.props?.className,\n layoutMode: node.props?.layoutMode,\n style: node.props?.style,\n svg: svgLayerAttributesOf(node.props),\n children: (node.children ?? []).map(\n (child) => child.source?.fiber.id ?? child.id,\n ),\n });\n pending.push(...(node.children ?? []));\n }\n}\nfunction updatePublishedMetadata<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n metadata: ProjectionLayerMetadataSnapshot,\n): void {\n if (!metadata.props) return;\n const previous = runtime.publishedHostProps.get(metadata.targetFiberId);\n if (!previous) return;\n const file = metadata.props[\"data-tempo-filepath\"];\n replacePublishedFile(runtime, previous.file, file);\n runtime.publishedHostProps.set(metadata.targetFiberId, {\n file,\n className: metadata.props.className,\n layoutMode: metadata.props.layoutMode,\n style: metadata.props.style,\n svg: svgLayerAttributesOf(metadata.props),\n children: previous.children,\n });\n}\n\nfunction captureSemanticRegions<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n): {\n readonly snapshots: ProjectionLayerRegionSnapshot[];\n readonly coveredFibers: ReadonlySet<Fiber>;\n readonly semanticNodesSerialized: number;\n} {\n const snapshots: ProjectionLayerRegionSnapshot[] = [];\n const coveredFibers = new Set<Fiber>();\n let semanticNodesSerialized = 0;\n for (const retainedFiber of runtime.pendingRegions.values()) {\n const fiber = resolveCommittedFiber(retainedFiber);\n if (\n runtime.committedFiber &&\n !fiberContains(runtime.committedFiber, fiber)\n ) {\n continue;\n }\n const serialized = runtime.layerAdapter.captureRegion(fiber);\n if (!serialized) continue;\n // A replacement root can have a new id, so its old subtree cannot be\n // reached through the new region target. The whole root is being captured.\n if (runtime.committedFiber && fiberPair(fiber, runtime.committedFiber)) {\n clearPublishedHostProps(runtime);\n }\n // A region replaces the published subtree, not just the surviving Fibers.\n // Retire its old child IDs before remembering the new serialization.\n forgetPublishedSubtree(runtime, serialized.region.targetFiberId);\n snapshots.push(serialized.region);\n for (const tree of serialized.region.scope?.children ?? [\n serialized.region.tree,\n ])\n rememberPublishedHostProps(runtime, tree);\n coveredFibers.add(fiber);\n semanticNodesSerialized += serialized.semanticNodesSerialized;\n }\n return { snapshots, coveredFibers, semanticNodesSerialized };\n}\n\nfunction captureSemanticMetadata<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n coveredFibers: ReadonlySet<Fiber>,\n): ProjectionLayerMetadataSnapshot[] {\n const snapshots: ProjectionLayerMetadataSnapshot[] = [];\n for (const retained of runtime.pendingMetadata.values()) {\n if (\n Array.from(coveredFibers).some((region) =>\n fiberContains(region, retained.fiber),\n )\n ) {\n continue;\n }\n const fiber = resolveCommittedFiber(retained.fiber);\n if (\n runtime.committedFiber &&\n !fiberContains(runtime.committedFiber, fiber)\n ) {\n continue;\n }\n const metadata = runtime.layerAdapter.captureMetadata(fiber, {\n sourceAnnotations: retained.sourceAnnotations,\n });\n if (metadata) {\n if (\n retained.layoutOnly &&\n runtime.publishedHostProps.get(metadata.targetFiberId)?.layoutMode ===\n metadata.props?.layoutMode\n )\n continue;\n snapshots.push(metadata);\n updatePublishedMetadata(runtime, metadata);\n }\n }\n return snapshots;\n}\n\nfunction patchHtmlChars(patch: ProjectionRootPatch): number {\n let chars = 0;\n for (const change of patch.dom ?? []) {\n if (change.kind === \"children\" || change.kind === \"place\") {\n chars += change.html.length;\n }\n }\n for (const portal of patch.portals ?? []) {\n if (portal.kind === \"replace\") chars += portal.html.length;\n }\n return chars;\n}\n\nfunction fullReason(\n context: ProjectionProducerFlushContext,\n openingRoot: boolean,\n): string {\n return context.initialForSession\n ? \"initial\"\n : openingRoot\n ? \"root-added\"\n : \"explicit-full\";\n}\n\nfunction makePerf(input: {\n readonly flushContext: ProjectionProducerFlushContext;\n readonly observation: ReturnType<ProjectionRootAccumulator[\"perfSnapshot\"]>;\n readonly snapshotMs: number;\n readonly semanticNodes: number;\n readonly domNodes: number;\n readonly htmlChars: number;\n readonly states: number;\n readonly portals: number;\n readonly observedFiles: number;\n readonly candidatesAfter: number;\n readonly semanticDiscoveryNodesVisited?: number;\n readonly fullReason: string | null;\n}): CaptureProducerPerf {\n return buildProjectionCapturePerf({\n flushStartedAt: input.flushContext.flushStartedAt,\n snapshotMs: input.snapshotMs,\n identityMs: 0,\n html: undefined,\n fiberNodeCount: input.semanticNodes,\n changedNodeEstimate: input.observation.candidateTargets,\n fixedWindowTimersOpened: input.flushContext.fixedWindowTimersOpened,\n maxSimultaneousTimers: input.flushContext.maxSimultaneousTimers,\n flushIntervalMs: input.flushContext.flushIntervalMs,\n rawMutationRecords: input.observation.rawMutationRecords,\n rawStateRecords: input.observation.rawStateRecords,\n rawPortalRecords: input.observation.rawPortalRecords,\n candidateTargetsBeforeCoalescing: input.observation.candidateTargets,\n candidateTargetsAfterCoalescing: input.candidatesAfter,\n semanticDiscoveryNodesVisited: input.semanticDiscoveryNodesVisited ?? 0,\n rootsPerBatch: input.flushContext.candidateRootCount,\n fullSnapshotReason: input.fullReason,\n triggerReasons: input.flushContext.triggerReasons,\n htmlChars: input.htmlChars,\n domNodesSerialized: input.domNodes,\n semanticNodesSerialized: input.semanticNodes,\n annotationTargetsSerialized: 0,\n stateTargetsSerialized: input.states,\n portalTargetsSerialized: input.portals,\n observedFileEntries: input.observedFiles,\n });\n}\n\nfunction aggregateBatchPerf(\n roots: readonly CaptureProducerPerf[],\n head: string | undefined,\n context: ProjectionProducerFlushContext | null,\n capturedHeadMs: number,\n rootsPerBatch: number,\n sourceViewportSamples: readonly CaptureSourceViewportSample[],\n): CaptureProducerPerf | undefined {\n if (roots.length === 0) {\n if (!context) return undefined;\n return buildProjectionCapturePerf({\n flushStartedAt: context.flushStartedAt,\n snapshotMs: capturedHeadMs,\n identityMs: 0,\n html: undefined,\n head,\n fiberNodeCount: 0,\n changedNodeEstimate: 0,\n fixedWindowTimersOpened: context.fixedWindowTimersOpened,\n maxSimultaneousTimers: context.maxSimultaneousTimers,\n flushIntervalMs: context.flushIntervalMs,\n rawMutationRecords: 0,\n rawStateRecords: 0,\n rawPortalRecords: 0,\n candidateTargetsBeforeCoalescing: 0,\n candidateTargetsAfterCoalescing: 0,\n rootsPerBatch: 0,\n fullSnapshotReason: null,\n triggerReasons: context.triggerReasons,\n sourceViewportSamples,\n domNodesSerialized: 0,\n semanticNodesSerialized: 0,\n annotationTargetsSerialized: 0,\n stateTargetsSerialized: 0,\n portalTargetsSerialized: 0,\n observedFileEntries: 0,\n });\n }\n const sum = (read: (perf: CaptureProducerPerf) => number): number =>\n roots.reduce((total, perf) => total + read(perf), 0);\n const max = (read: (perf: CaptureProducerPerf) => number): number =>\n Math.max(...roots.map(read));\n const first = roots[0];\n if (!first) return undefined;\n const flushStartedAt = context?.flushStartedAt ?? first.flushStartedAt;\n const reasons = new Set(roots.map((perf) => perf.fullSnapshotReason));\n return {\n flushStartedAt,\n flushMs: Date.now() - flushStartedAt,\n snapshotMs: sum((perf) => perf.snapshotMs) + capturedHeadMs,\n headSnapshotMs: capturedHeadMs,\n identityMs: sum((perf) => perf.identityMs),\n identityNodesVisited: sum((perf) => perf.identityNodesVisited),\n sourceVersionDomScanNodes: sum((perf) => perf.sourceVersionDomScanNodes),\n sourceVersionFiberSerializeNodes: sum(\n (perf) => perf.sourceVersionFiberSerializeNodes,\n ),\n sourceVersionFiberReductionNodes: sum(\n (perf) => perf.sourceVersionFiberReductionNodes,\n ),\n sourceVersionFallbackScanNodes: sum(\n (perf) => perf.sourceVersionFallbackScanNodes,\n ),\n sourceVersionScanNodes: sum((perf) => perf.sourceVersionScanNodes),\n styleReadCount: sum((perf) => perf.styleReadCount),\n htmlChars: sum((perf) => perf.htmlChars),\n headChars: head?.length ?? 0,\n fiberNodeCount: sum((perf) => perf.fiberNodeCount),\n changedNodeEstimate: sum((perf) => perf.changedNodeEstimate),\n activeDocumentProducers: max((perf) => perf.activeDocumentProducers),\n activeRootObservers: max((perf) => perf.activeRootObservers),\n headObservers: max((perf) => perf.headObservers),\n headSubscriptions: max((perf) => perf.headSubscriptions),\n reactCommitSubscriptions: max((perf) => perf.reactCommitSubscriptions),\n fixedWindowTimersOpened:\n context?.fixedWindowTimersOpened ?? first.fixedWindowTimersOpened,\n maxSimultaneousTimers:\n context?.maxSimultaneousTimers ?? first.maxSimultaneousTimers,\n flushIntervalMs: context?.flushIntervalMs ?? first.flushIntervalMs,\n rawMutationRecords: sum((perf) => perf.rawMutationRecords),\n rawStateRecords: sum((perf) => perf.rawStateRecords),\n rawPortalRecords: sum((perf) => perf.rawPortalRecords),\n producerCandidateNodes: sum((perf) => perf.producerCandidateNodes),\n producerVisitedNodes: sum((perf) => perf.producerVisitedNodes),\n candidateTargetsBeforeCoalescing: sum(\n (perf) => perf.candidateTargetsBeforeCoalescing,\n ),\n candidateTargetsAfterCoalescing: sum(\n (perf) => perf.candidateTargetsAfterCoalescing,\n ),\n semanticDiscoveryNodesVisited: sum(\n (perf) => perf.semanticDiscoveryNodesVisited ?? 0,\n ),\n domNodesSerialized: roots.some((perf) => perf.domNodesSerialized === null)\n ? null\n : sum((perf) => perf.domNodesSerialized ?? 0),\n semanticNodesSerialized: sum((perf) => perf.semanticNodesSerialized),\n annotationTargetsSerialized: sum(\n (perf) => perf.annotationTargetsSerialized,\n ),\n stateTargetsSerialized: sum((perf) => perf.stateTargetsSerialized),\n portalTargetsSerialized: sum((perf) => perf.portalTargetsSerialized),\n headSerializations: head === undefined ? 0 : 1,\n observedFileEntries: sum((perf) => perf.observedFileEntries),\n batchesEmitted: 1,\n rootsPerBatch,\n fullSnapshotReason:\n reasons.size === 1 ? first.fullSnapshotReason : \"mixed-full\",\n triggerReasons: context?.triggerReasons ?? first.triggerReasons,\n sourceViewportSamples,\n };\n}\n","/**\n * What a watch asks the producer to observe. \"auto\" is the request the V2\n * canvas makes for every root, the page root included: the producer reads\n * the runtime off the document and reports it, and never takes a framework\n * from the canvas or from project configuration. \"dom\" asks for the whole\n * document as DOM layers (external routes, HTML files): a choice of\n * coverage, not a claim about the runtime. \"react\", \"svelte\", \"vue\" and\n * \"astro\" are explicit requests (the V1 canvas makes them) and go with it. A\n * change of observation authority publishes a baseline before that\n * authority's deltas.\n */\nexport const LAYER_FRAMEWORKS = [\n \"react\",\n \"svelte\",\n \"vue\",\n \"astro\",\n \"dom\",\n \"auto\",\n] as const;\n\nexport type LayerFramework = (typeof LAYER_FRAMEWORKS)[number];\n\nexport function isLayerFramework(value: unknown): value is LayerFramework {\n return LAYER_FRAMEWORKS.includes(value as LayerFramework);\n}\n","import type { ProjectionFullSnapshot } from \"./projection-full-snapshot\";\nimport type { ProjectionObservedFileMap } from \"./projection-observed-files\";\nimport type { ProjectionRootPatch } from \"./projection-root-accumulator\";\nimport type { CaptureProducerPerf } from \"./types\";\n\nexport type ProjectionBatchEnvelope = ArrayBuffer;\n\n/**\n * The single ordered message emitted by one document-scoped projection\n * producer. Sequence numbers are contiguous within a lifecycle-owned session.\n */\nexport interface CombinedProjectionBatch {\n readonly sessionId: string;\n readonly sequence: number;\n /** Exact final head HTML, applied through the staging path. */\n readonly head?: string;\n /** Opaque host resource transfer, acknowledged after the renderer owns the head. */\n readonly headLease?: string;\n /** Producer-owned head evidence, independent of baseline delivery. Missing\n * revisions are unknown and must conservatively invalidate capture reuse.\n * A knownHead watch also gets this proof on headless full baselines. */\n readonly headRevision?: number;\n /** When present, the head is recovery work for only these roots. Normal\n * source head mutations omit this field and still fan out document-wide. */\n readonly headRootIds?: readonly string[];\n /** Pixel-only invalidation; carries no DOM replacement and leaves HTML valid. */\n readonly assetRootIds?: readonly string[];\n /** Observational batch receipt; it is not ordering or correctness state. */\n readonly perf?: CaptureProducerPerf;\n readonly roots: readonly ProjectionRootChange[];\n readonly sizes?: Readonly<Record<string, { width: number; height: number }>>;\n /**\n * Module version facts for the whole document, keyed by the annotation's\n * `data-tempo-filepath` (V2-498). Every root of the document reads them,\n * whether or not the batch names it. These are informational: only a root\n * result can prove rendered presence or absence. A fact says the module\n * evaluated at `modifiedTs` at least the producer's grace\n * (MODULE_EVALUATED_GRACE_MS) ago. A batch carrying a full reports every\n * reportable record; others report only what changed.\n */\n readonly modules?: Readonly<\n Record<\n string,\n {\n readonly modifiedTs: number;\n readonly sourceVersion?: string;\n }\n >\n >;\n}\n\n/** One immutable envelope index shared by all root consumers. Payloads stay\n * lazy: indexing reads root IDs only, never snapshot or patch getters. */\nconst rootIndexes = new WeakMap<\n CombinedProjectionBatch,\n ReadonlyMap<string, ProjectionRootChange>\n>();\nexport function projectionRootChange(\n batch: CombinedProjectionBatch,\n rootId: string,\n): ProjectionRootChange | null {\n let index = rootIndexes.get(batch);\n if (!index) {\n const entries = new Map<string, ProjectionRootChange>();\n for (const root of batch.roots)\n if (!entries.has(root.rootId)) entries.set(root.rootId, root);\n rootIndexes.set(batch, (index = entries));\n }\n return index.get(rootId) ?? null;\n}\n\n/** Encoded size known without touching lazy payload getters. Null for object\n * batches; callers must account those while preparing their payload. This is\n * a byte estimate, not a claim about the runtime heap retained by the envelope. */\nconst rootBytes = new WeakMap<object, number>();\nexport function projectionRootEncodedBytes(\n root: ProjectionRootChange,\n): number | null {\n return rootBytes.get(root) ?? null;\n}\n\n/**\n * Root-local work carried by a ProjectionBatch: `full` is a self-contained\n * baseline for the root, `patch` is incremental operations against the\n * baseline already applied, and `problem` reports a source state that has no\n * representable DOM.\n */\nexport type ProjectionRootChange = { readonly contentRevision?: number } & (\n | {\n readonly rootId: string;\n readonly kind: \"full\";\n readonly snapshot: ProjectionFullSnapshot;\n }\n | {\n readonly rootId: string;\n readonly kind: \"patch\";\n readonly patch: ProjectionRootPatch;\n }\n | {\n readonly rootId: string;\n readonly kind: \"problem\";\n readonly problem: CombinedProjectionProblem;\n }\n);\n\nexport interface ProjectionRenderErrorProblem {\n readonly reason: \"render-error\";\n readonly message: string | null;\n}\n\n/** The runtimes whose layers come from development metadata a build can\n * lack. React's fibers and plain DOM always exist. */\nexport type RuntimeMetadataLayerFramework = \"svelte\" | \"vue\";\n\n/**\n * The only problems a producer can report are real source states: a rendered\n * error boundary, a root whose runtime was torn down mid-flush, a root whose\n * Tempo-owned Suspense boundary is showing its pending marker — content is\n * coming, the current DOM is not representable, and nothing is wrong, including a Svelte or Vue root without development metadata. There are\n * no representational refusals — every representable DOM state is emitted and\n * the destination converges on it. `unavailable` is the same state with no\n * bound on the wait: the root shows only the unavailable marker\n * (`projection-pending.ts`), its content waits on something outside the page,\n * and the destination must hold last-good without timing it out.\n\n */\nexport type CombinedProjectionProblem =\n | { readonly reason: \"missing-fiber-target\" }\n | { readonly reason: \"suspended\" }\n | { readonly reason: \"unavailable\" }\n | {\n /** Svelte keeps its released wire spelling: older clients reject an\n * unknown problem discriminator instead of displaying the failure. */\n readonly reason: \"svelte-layer-metadata-unavailable\";\n readonly message: string;\n }\n | {\n readonly reason: \"layer-metadata-unavailable\";\n readonly framework: RuntimeMetadataLayerFramework;\n readonly message: string;\n }\n | ProjectionRenderErrorProblem;\n\n/**\n * Wire-only buffer: little-endian u32 header byte length, UTF-8 JSON header,\n * then UTF-8 JSON root segments. Segment offsets start after the header.\n * Header roots carry rootId, kind, observedFiles and segment { offset, length };\n * Full roots also carry pointerEventsNone: true when the segment has that fact.\n * Problem roots carry problem instead. Other batch fields stay in the header.\n * Lazy root views retain the whole buffer until the last root is released.\n * V2-177 reports 11.4 MiB higher sampled heap in its 52-root experiment.\n */\nexport function encodeProjectionBatch(\n batch: CombinedProjectionBatch,\n): ProjectionBatchEnvelope {\n const encoder = new TextEncoder();\n const segments: Uint8Array[] = [];\n let offset = 0;\n const roots = batch.roots.map((root) => {\n if (root.kind === \"problem\") return root;\n const { observedFiles, absentFiles, ...payload } =\n root.kind === \"full\" ? root.snapshot : root.patch;\n const bytes = encoder.encode(JSON.stringify(payload));\n const segment = { offset, length: bytes.byteLength };\n segments.push(bytes);\n offset += bytes.byteLength;\n return {\n rootId: root.rootId,\n kind: root.kind,\n contentRevision: root.contentRevision,\n observedFiles,\n ...(absentFiles !== undefined ? { absentFiles } : {}),\n ...(root.kind === \"full\" && payload.pointerEventsNone !== undefined\n ? { pointerEventsNone: true }\n : {}),\n segment,\n };\n });\n const header = encoder.encode(JSON.stringify({ ...batch, roots }));\n const buffer: ProjectionBatchEnvelope = new ArrayBuffer(\n 4 + header.byteLength + offset,\n );\n new DataView(buffer).setUint32(0, header.byteLength, true);\n const bytes = new Uint8Array(buffer);\n bytes.set(header, 4);\n offset = 4 + header.byteLength;\n for (const segment of segments) {\n bytes.set(segment, offset);\n offset += segment.byteLength;\n }\n return buffer;\n}\n\n/**\n * This seam certifies object batches whole and envelope headers on arrival.\n * Envelope root payloads certify on first field read, and a failure throws\n * into the receiver's apply recovery.\n * Past this seam, appliers never refuse.\n */\nexport function decodeCombinedProjectionBatch(\n value: unknown,\n): CombinedProjectionBatch | null {\n let segments: Uint8Array | null = null;\n const isEnvelope =\n value instanceof ArrayBuffer ||\n Object.prototype.toString.call(value) === \"[object ArrayBuffer]\";\n if (isEnvelope) {\n const envelope = readEnvelopeHeader(value as ArrayBuffer);\n if (!envelope) return null;\n value = envelope.header;\n segments = envelope.segments;\n }\n if (!isRecord(value)) return null;\n const sessionId = normalizeIdentity(value.sessionId);\n if (\n sessionId === null ||\n typeof value.sequence !== \"number\" ||\n !Number.isSafeInteger(value.sequence) ||\n value.sequence < 0 ||\n !Array.isArray(value.roots) ||\n (value.head !== undefined && typeof value.head !== \"string\") ||\n (value.headLease !== undefined &&\n (typeof value.headLease !== \"string\" ||\n value.headLease.length > 256 ||\n typeof value.head !== \"string\")) ||\n !isOptionalRevision(value.headRevision) ||\n (value.headRootIds !== undefined &&\n (!Array.isArray(value.headRootIds) || typeof value.head !== \"string\")) ||\n (value.assetRootIds !== undefined &&\n (!Array.isArray(value.assetRootIds) ||\n value.assetRootIds.length === 0 ||\n value.assetRootIds.some((id) => normalizeIdentity(id) === null) ||\n new Set(value.assetRootIds).size !== value.assetRootIds.length)) ||\n (value.perf !== undefined && !isRecord(value.perf))\n )\n return null;\n\n if (value.modules !== undefined) {\n if (!isRecord(value.modules)) return null;\n for (const fact of Object.values(value.modules)) {\n if (\n !isRecord(fact) ||\n typeof fact.modifiedTs !== \"number\" ||\n !Number.isFinite(fact.modifiedTs) ||\n (fact.sourceVersion !== undefined &&\n typeof fact.sourceVersion !== \"string\")\n )\n return null;\n }\n }\n\n if (value.sizes !== undefined) {\n if (!isRecord(value.sizes)) return null;\n for (const [rootId, size] of Object.entries(value.sizes)) {\n if (\n normalizeIdentity(rootId) === null ||\n !isRecord(size) ||\n typeof size.width !== \"number\" ||\n typeof size.height !== \"number\" ||\n !Number.isFinite(size.width) ||\n !Number.isFinite(size.height) ||\n size.width <= 0 ||\n size.height <= 0\n )\n return null;\n }\n }\n\n const roots: CombinedProjectionBatch[\"roots\"][number][] = [];\n const ranges: { offset: number; length: number }[] = [];\n for (const rawRoot of value.roots) {\n const root = segments\n ? lazyRootChange(rawRoot, segments)\n : decodeProjectionRootChange(rawRoot);\n if (!root) return null;\n if (segments && root.kind !== \"problem\") {\n const { offset, length } = rawRoot.segment;\n const overlaps = ranges.some(\n (range) =>\n offset < range.offset + range.length &&\n range.offset < offset + length,\n );\n if (overlaps) return null;\n ranges.push({ offset, length });\n }\n roots.push(root);\n }\n\n const headRootIds: string[] = [];\n if (Array.isArray(value.headRootIds)) {\n const seen = new Set<string>();\n for (const rawRootId of value.headRootIds) {\n const rootId = normalizeIdentity(rawRootId);\n if (rootId === null || seen.has(rootId)) return null;\n seen.add(rootId);\n headRootIds.push(rootId);\n }\n if (headRootIds.length === 0) return null;\n }\n return {\n sessionId,\n sequence: value.sequence,\n ...(typeof value.head === \"string\" ? { head: value.head } : {}),\n ...(typeof value.headLease === \"string\"\n ? { headLease: value.headLease }\n : {}),\n ...(value.headRevision !== undefined\n ? { headRevision: value.headRevision as number }\n : {}),\n ...(headRootIds.length > 0 ? { headRootIds } : {}),\n ...(Array.isArray(value.assetRootIds)\n ? { assetRootIds: value.assetRootIds }\n : {}),\n ...(isRecord(value.perf)\n ? { perf: value.perf as unknown as CaptureProducerPerf }\n : {}),\n roots,\n ...(value.sizes === undefined\n ? {}\n : { sizes: value.sizes as CombinedProjectionBatch[\"sizes\"] }),\n ...(value.modules === undefined\n ? {}\n : { modules: value.modules as CombinedProjectionBatch[\"modules\"] }),\n };\n}\n\nfunction readEnvelopeHeader(\n buffer: ArrayBuffer,\n): { header: unknown; segments: Uint8Array } | null {\n try {\n const length = new DataView(buffer).getUint32(0, true);\n const header: unknown = JSON.parse(\n new TextDecoder().decode(new Uint8Array(buffer, 4, length)),\n );\n return { header, segments: new Uint8Array(buffer, 4 + length) };\n } catch {\n return null;\n }\n}\n\nfunction lazyRootChange(\n rawRoot: unknown,\n segments: Uint8Array,\n): ProjectionRootChange | null {\n if (!isRecord(rawRoot)) return null;\n if (rawRoot.kind === \"problem\") return decodeProjectionRootChange(rawRoot);\n const rootId = normalizeIdentity(rawRoot.rootId);\n const kind = rawRoot.kind;\n const segment = rawRoot.segment;\n const observedFiles = rawRoot.observedFiles;\n const absentFiles = rawRoot.absentFiles;\n const validObservedFiles =\n kind === \"full\"\n ? isProjectionObservedFileMap(observedFiles)\n : observedFiles === undefined ||\n isProjectionObservedFileMap(observedFiles);\n if (\n !rootId ||\n !isOptionalRevision(rawRoot.contentRevision) ||\n (kind !== \"full\" && kind !== \"patch\") ||\n !validObservedFiles ||\n (absentFiles !== undefined && !isProjectionObservedFileMap(absentFiles)) ||\n !isRecord(segment) ||\n typeof segment.offset !== \"number\" ||\n typeof segment.length !== \"number\" ||\n !Number.isSafeInteger(segment.offset) ||\n !Number.isSafeInteger(segment.length) ||\n segment.offset < 0 ||\n segment.length < 0 ||\n segment.offset + segment.length > segments.byteLength\n )\n return null;\n\n const bytes = segments.subarray(\n segment.offset,\n segment.offset + segment.length,\n );\n const key = kind === \"full\" ? \"snapshot\" : \"patch\";\n const payload: Record<string, unknown> = {\n ...(observedFiles === undefined ? {} : { observedFiles }),\n ...(absentFiles === undefined ? {} : { absentFiles }),\n };\n let decoded: Record<string, unknown> | undefined;\n let error: Error | undefined;\n function decodeOnce(): Record<string, unknown> {\n if (error) throw error;\n if (decoded) return decoded;\n try {\n const segment = JSON.parse(new TextDecoder().decode(bytes));\n if (\n !isRecord(segment) ||\n Object.prototype.hasOwnProperty.call(segment, \"observedFiles\") ||\n Object.prototype.hasOwnProperty.call(segment, \"absentFiles\")\n )\n throw new Error();\n const root = decodeProjectionRootChange({\n rootId,\n kind,\n [key]: {\n ...segment,\n ...(observedFiles === undefined ? {} : { observedFiles }),\n ...(absentFiles === undefined ? {} : { absentFiles }),\n },\n });\n if (!root || root.kind === \"problem\") throw new Error();\n decoded = (root.kind === \"full\"\n ? root.snapshot\n : root.patch) as unknown as Record<string, unknown>;\n return decoded;\n } catch {\n error = new Error(\n `Invalid deferred projection root: ${rootId} (${kind})`,\n );\n throw error;\n }\n }\n\n const fields =\n kind === \"full\"\n ? [\"dom\", \"layers\", \"pointerEventsNone\"]\n : [\n \"dom\",\n \"state\",\n \"portals\",\n \"layers\",\n \"pointerEventsNone\",\n \"repairedAncestors\",\n ];\n for (const field of fields) {\n // Keep key enumeration lazy even when a full omits the optional fact.\n if (\n kind === \"full\" &&\n field === \"pointerEventsNone\" &&\n rawRoot.pointerEventsNone !== true\n )\n continue;\n Object.defineProperty(payload, field, {\n enumerable: true,\n get() {\n return decodeOnce()[field];\n },\n });\n }\n const revision =\n rawRoot.contentRevision === undefined\n ? {}\n : { contentRevision: rawRoot.contentRevision as number };\n const result: ProjectionRootChange =\n kind === \"full\"\n ? {\n rootId,\n kind,\n ...revision,\n snapshot: payload as unknown as ProjectionFullSnapshot,\n }\n : { rootId, kind, ...revision, patch: payload as ProjectionRootPatch };\n rootBytes.set(result, bytes.byteLength);\n return result;\n}\n\nfunction decodeProjectionRootChange(\n value: unknown,\n): CombinedProjectionBatch[\"roots\"][number] | null {\n if (!isRecord(value)) return null;\n const rootId = normalizeIdentity(value.rootId);\n if (!rootId || !isOptionalRevision(value.contentRevision)) return null;\n const revision =\n value.contentRevision === undefined\n ? {}\n : { contentRevision: value.contentRevision as number };\n if (\n value.kind === \"full\" &&\n Object.hasOwn(value, \"snapshot\") &&\n isProjectionFullSnapshot(value.snapshot)\n ) {\n return { rootId, ...revision, kind: \"full\", snapshot: value.snapshot };\n }\n if (\n value.kind === \"patch\" &&\n Object.hasOwn(value, \"patch\") &&\n isProjectionRootPatch(value.patch)\n ) {\n return { rootId, ...revision, kind: \"patch\", patch: value.patch };\n }\n if (\n value.kind === \"problem\" &&\n Object.hasOwn(value, \"problem\") &&\n isCombinedProjectionProblem(value.problem)\n ) {\n return { rootId, ...revision, kind: \"problem\", problem: value.problem };\n }\n return null;\n}\n\nfunction isOptionalRevision(value: unknown): boolean {\n return (\n value === undefined ||\n (typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0)\n );\n}\n\nfunction isProjectionFullSnapshot(\n value: unknown,\n): value is ProjectionFullSnapshot {\n if (\n !isRecord(value) ||\n !isRecord(value.dom) ||\n !isRecord(value.layers) ||\n !isProjectionObservedFileMap(value.observedFiles) ||\n (value.absentFiles !== undefined &&\n !isProjectionObservedFileMap(value.absentFiles))\n ) {\n return false;\n }\n const dom = value.dom;\n return (\n typeof dom.html === \"string\" &&\n (dom.coordinates === undefined || isRootCoordinates(dom.coordinates)) &&\n (dom.rootAttributes === undefined || isStringRecord(dom.rootAttributes)) &&\n (dom.rootDomId === undefined || typeof dom.rootDomId === \"string\") &&\n isStringRecord(dom.documentElementAttributes) &&\n (dom.bodyAttributes === undefined || isStringRecord(dom.bodyAttributes)) &&\n (dom.baseUrl === undefined || typeof dom.baseUrl === \"string\") &&\n Array.isArray(dom.state) &&\n Array.isArray(dom.portals)\n );\n}\n\nfunction isProjectionRootPatch(value: unknown): value is ProjectionRootPatch {\n if (!isRecord(value)) return false;\n const domains = Object.keys(value);\n const allowedDomains = new Set([\n \"repairedAncestors\",\n \"dom\",\n \"state\",\n \"portals\",\n \"layers\",\n \"observedFiles\",\n \"absentFiles\",\n \"pointerEventsNone\",\n ]);\n return (\n domains.length > 0 &&\n domains.every((domain) => allowedDomains.has(domain)) &&\n (value.repairedAncestors === undefined ||\n (Array.isArray(value.repairedAncestors) &&\n value.repairedAncestors.every((id) => typeof id === \"string\"))) &&\n (value.absentFiles === undefined ||\n isProjectionObservedFileMap(value.absentFiles)) &&\n (value.pointerEventsNone === undefined ||\n (Array.isArray(value.pointerEventsNone) &&\n value.pointerEventsNone.every((id) => typeof id === \"string\"))) &&\n (value.dom === undefined || Array.isArray(value.dom)) &&\n (value.state === undefined || Array.isArray(value.state)) &&\n (value.portals === undefined || Array.isArray(value.portals)) &&\n (value.layers === undefined || isRecord(value.layers)) &&\n (value.observedFiles === undefined ||\n isProjectionObservedFileMap(value.observedFiles))\n );\n}\n\nfunction isCombinedProjectionProblem(\n value: unknown,\n): value is CombinedProjectionProblem {\n if (!isRecord(value)) return false;\n switch (value.reason) {\n case \"render-error\":\n return value.message === null || typeof value.message === \"string\";\n case \"svelte-layer-metadata-unavailable\":\n return typeof value.message === \"string\";\n case \"layer-metadata-unavailable\":\n return (\n (value.framework === \"svelte\" || value.framework === \"vue\") &&\n typeof value.message === \"string\"\n );\n case \"missing-fiber-target\":\n case \"suspended\":\n case \"unavailable\":\n return true;\n default:\n return false;\n }\n}\n\nfunction isProjectionObservedFileMap(\n value: unknown,\n): value is ProjectionObservedFileMap {\n if (!isRecord(value)) return false;\n return Object.entries(value).every(\n ([filepath, fact]) =>\n filepath.length > 0 &&\n isRecord(fact) &&\n typeof fact.modifiedTs === \"number\" &&\n Number.isFinite(fact.modifiedTs) &&\n (fact.sourceVersion === undefined ||\n (typeof fact.sourceVersion === \"string\" &&\n fact.sourceVersion.length > 0)),\n );\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n return (\n isRecord(value) &&\n Object.values(value).every((entry) => typeof entry === \"string\")\n );\n}\n\nfunction normalizeIdentity(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isRootCoordinates(value: unknown): boolean {\n return (\n isRecord(value) &&\n [\"left\", \"top\", \"width\", \"height\"].every(\n (key) => typeof value[key] === \"number\" && Number.isFinite(value[key]),\n ) &&\n (value.width as number) > 0 &&\n (value.height as number) > 0 &&\n ((value.layoutLeft === undefined && value.layoutTop === undefined) ||\n (typeof value.layoutLeft === \"number\" &&\n Number.isFinite(value.layoutLeft) &&\n typeof value.layoutTop === \"number\" &&\n Number.isFinite(value.layoutTop)))\n );\n}\n","/**\n * Projection Snapshot\n *\n * Shared one-shot snapshot used by:\n * - capture APIs (single event)\n * - watch initial emission (first event in stream)\n */\n\nimport { findOwnedPortalRoots } from \"../shared/portal-tracker\";\nimport {\n captureWithSupplementalRoots,\n collectElementStates,\n removeScriptTags,\n} from \"./capture\";\nimport type { DomCapture, PortalUpdate } from \"./types\";\nimport { captureHead } from \"./watch-head\";\nimport {\n capturePortalCoordinateSpace,\n getOrAssignPortalId,\n} from \"./watch-portal\";\n\nexport function captureProjectionSnapshot(\n element: Element,\n supplementalRoots?: readonly Element[],\n): DomCapture {\n return {\n ...captureProjectionBodySnapshot(element, supplementalRoots),\n head: captureHead(element.ownerDocument ?? document),\n };\n}\n\n/**\n * Capture one complete root without re-reading document-scoped head state.\n *\n * A document producer calls this once per dirty root and captures the head at\n * most once for the enclosing batch. The legacy one-shot API above remains\n * self-contained for callers that truly need a single root plus head.\n */\nexport function captureProjectionBodySnapshot(\n element: Element,\n supplementalRoots?: readonly Element[],\n): Omit<DomCapture, \"head\"> {\n const { updates: portals, elements: portalElements } = supplementalRoots\n ? captureKnownPortals(supplementalRoots, element)\n : capturePortals(element);\n const baseCapture = captureWithSupplementalRoots(element, portalElements);\n\n return {\n ...baseCapture,\n portalsComplete: true,\n ...(portals.length > 0 ? { portals } : {}),\n };\n}\n\nexport function collectProjectionPortalElements(root: Element): Element[] {\n return capturePortals(root).elements;\n}\n\nfunction captureKnownPortals(\n roots: readonly Element[],\n ownerRoot: Element,\n): CapturedPortals {\n const updates: PortalUpdate[] = [];\n const elements: Element[] = [];\n for (const root of roots) {\n if (!root.isConnected) continue;\n const id = getOrAssignPortalId(root);\n const coordinateSpace = capturePortalCoordinateSpace(ownerRoot, root);\n updates.push({\n id,\n selector: \"\",\n html: removeScriptTags(root.outerHTML),\n states: collectElementStates(root, { includeDocumentScroll: false }),\n ...(coordinateSpace && { coordinateSpace }),\n });\n elements.push(root);\n }\n return { updates, elements };\n}\n\ninterface CapturedPortals {\n updates: PortalUpdate[];\n /** Live portal root elements, for declared-facts computation. */\n elements: Element[];\n}\n\nfunction capturePortals(root: Element): CapturedPortals {\n return captureKnownPortals(findOwnedPortalRoots(root), root);\n}\n","import { getFiberFromElement } from \"../fiber/capture\";\nimport { FiberTag } from \"../fiber/react-types\";\nimport {\n isTransientFiberResolutionError,\n resolveCommittedFiber,\n} from \"../fiber/serialize\";\nimport { countIdentityNodeVisited } from \"../shared/capture-perf\";\nimport type {\n EnrichedFiberConstraint,\n RenderHostIdentity,\n RenderHostIdentityDeclaration,\n} from \"./types\";\n\nconst SOURCE_IDENTITY_KEYS = [\n \"data-tempo-filepath\",\n \"data-tempo-position\",\n \"data-tempo-modifiedts\",\n \"data-tempo-source-version\",\n] as const;\n\ntype SourceIdentityKey = (typeof SOURCE_IDENTITY_KEYS)[number];\n\nfunction normalizeIdentityValue(value: unknown): string | undefined {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return String(value);\n }\n return undefined;\n}\n\nfunction sourceIdentityFromProps(\n props: Readonly<Record<string, unknown>> | undefined,\n): Partial<Record<SourceIdentityKey, string>> | undefined {\n if (!props) return undefined;\n const source: Partial<Record<SourceIdentityKey, string>> = {};\n for (const key of SOURCE_IDENTITY_KEYS) {\n const value = normalizeIdentityValue(props[key]);\n if (value !== undefined) source[key] = value;\n }\n return Object.keys(source).length > 0 ? source : undefined;\n}\n\nfunction sourceIdentityFromElement(\n element: Element,\n): Partial<Record<SourceIdentityKey, string>> | undefined {\n const source: Partial<Record<SourceIdentityKey, string>> = {};\n for (const key of SOURCE_IDENTITY_KEYS) {\n const value = element.getAttribute(key);\n if (value !== null) source[key] = value;\n }\n return Object.keys(source).length > 0 ? source : undefined;\n}\n\nfunction isContentEditableBoundary(\n props: Readonly<Record<string, unknown>> | undefined,\n): boolean {\n if (!props) return false;\n return (\n (props.contentEditable !== null && props.contentEditable !== undefined) ||\n (props.contenteditable !== null && props.contenteditable !== undefined)\n );\n}\n\nfunction finalizeDeclaration(\n hosts: RenderHostIdentity[],\n missingDomIdCount: number,\n): RenderHostIdentityDeclaration {\n const counts = new Map<string, number>();\n for (const host of hosts) {\n counts.set(host.domId, (counts.get(host.domId) ?? 0) + 1);\n }\n const duplicateDomIds = [...counts]\n .filter(([, count]) => count > 1)\n .map(([domId]) => domId)\n .sort();\n hosts.sort((left, right) => left.domId.localeCompare(right.domId));\n return { hosts, missingDomIdCount, duplicateDomIds };\n}\n\nexport function declareFiberHostIdentity<T extends EnrichedFiberConstraint>(\n tree: T,\n): RenderHostIdentityDeclaration {\n const hosts: RenderHostIdentity[] = [];\n let missingDomIdCount = 0;\n const visit = (node: EnrichedFiberConstraint): void => {\n countIdentityNodeVisited();\n if (node.insideContentEditable) return;\n const renderNode = node as EnrichedFiberConstraint & {\n tag?: number;\n name?: string;\n };\n if (renderNode.tag === FiberTag.HostComponent) {\n if (!node.domId) {\n missingDomIdCount += 1;\n } else {\n hosts.push({\n domId: node.domId,\n tag: renderNode.name?.toLowerCase() ?? \"\",\n source: sourceIdentityFromProps(node.props),\n });\n }\n if (isContentEditableBoundary(node.props)) return;\n }\n for (const child of node.children) {\n visit(child as EnrichedFiberConstraint);\n }\n };\n visit(tree);\n return finalizeDeclaration(hosts, missingDomIdCount);\n}\n\nexport function declareDomHostIdentity(\n captureRoot: Element,\n supplementalRoots: readonly Element[],\n): RenderHostIdentityDeclaration {\n const hosts: RenderHostIdentity[] = [];\n let missingDomIdCount = 0;\n const seenElements = new Set<Element>();\n const visit = (element: Element): void => {\n if (seenElements.has(element)) return;\n seenElements.add(element);\n countIdentityNodeVisited();\n const rawFiber = getFiberFromElement(element);\n if (rawFiber) {\n try {\n const fiber = resolveCommittedFiber(rawFiber);\n if (\n fiber.tag === FiberTag.HostComponent &&\n fiber.stateNode === element\n ) {\n const domId = element.getAttribute(\"data-dom-id\");\n if (!domId) {\n missingDomIdCount += 1;\n } else {\n hosts.push({\n domId,\n tag: element.localName.toLowerCase(),\n source: sourceIdentityFromElement(element),\n });\n }\n }\n } catch (error) {\n if (!isTransientFiberResolutionError(error)) throw error;\n // React can detach an alternate between DOM enumeration and this\n // identity read. Make the atomic candidate incomplete instead of\n // surfacing capture internals as an application runtime error.\n missingDomIdCount += 1;\n }\n }\n if (element.getAttribute(\"contenteditable\") !== null) return;\n for (const child of element.children) visit(child);\n };\n // The root snapshot serializes `captureRoot.innerHTML`, so the root itself\n // is outside the HTML arm even when it is a React-owned CanvasHost wrapper.\n // Portal snapshots use `outerHTML` and therefore include their roots.\n for (const child of captureRoot.children) visit(child);\n for (const root of supplementalRoots) visit(root);\n return finalizeDeclaration(hosts, missingDomIdCount);\n}\n\nexport function hostIdentityDeclarationsMatch(\n left: RenderHostIdentityDeclaration,\n right: RenderHostIdentityDeclaration,\n): boolean {\n if (\n left.missingDomIdCount !== 0 ||\n right.missingDomIdCount !== 0 ||\n left.duplicateDomIds.length !== 0 ||\n right.duplicateDomIds.length !== 0 ||\n left.hosts.length !== right.hosts.length\n ) {\n return false;\n }\n for (let index = 0; index < left.hosts.length; index += 1) {\n const leftHost = left.hosts[index];\n const rightHost = right.hosts[index];\n if (\n !leftHost ||\n !rightHost ||\n leftHost.domId !== rightHost.domId ||\n leftHost.tag !== rightHost.tag ||\n JSON.stringify(leftHost.source ?? {}) !==\n JSON.stringify(rightHost.source ?? {})\n ) {\n return false;\n }\n }\n return true;\n}\n","/**\n * Declared Capture Facts — fiber half\n *\n * The layers half of a combined capture declares its own observed source\n * versions, computed by walking the enriched fiber tree's annotated props\n * (the same props the DOM half reads as attributes). See\n * specs/canvas-determinism.md §4.\n */\n\nimport type { DomCapture } from \"../html/types\";\nimport type { CombinedCapture, EnrichedFiberConstraint } from \"./types\";\nimport {\n declareDomHostIdentity,\n declareFiberHostIdentity,\n hostIdentityDeclarationsMatch,\n} from \"./render-identity\";\n\n/** Both per-file version signals a fiber walk observes, mirroring\n * `computeDeclaredFacts` on the DOM side: the numeric mtime (`observedVersions`)\n * and the content-version token (`observedSourceVersions`, co-located with the\n * MAX-mtime element). Keys in both are the raw stamped filepath spellings\n * (consumers canonicalize on read). */\nexport interface FiberObservedVersions {\n observedVersions: Record<string, number>;\n observedSourceVersions: Record<string, string>;\n}\n\nexport interface RenderDeclarationScope {\n captureRoot: Element;\n supplementalRoots: readonly Element[];\n renderMode?: \"static-dom\";\n}\n\nexport function createRenderDeclarationScope(\n captureRoot: Element,\n supplementalRoots: readonly Element[],\n): RenderDeclarationScope {\n return {\n captureRoot,\n supplementalRoots,\n ...(captureRoot.getAttribute(\"data-tempo-render-mode\") === \"static-dom\" && {\n renderMode: \"static-dom\" as const,\n }),\n };\n}\n\n/**\n * Per-file MAX `data-tempo-modifiedts` among a walked fiber tree's annotated\n * props, plus the shared `data-tempo-source-version` token\n * co-located with each file's newest (MAX-mtime) node. Keys are the raw\n * stamped filepath spellings (consumers canonicalize on read), mirroring\n * `computeDeclaredFacts` on the DOM side.\n */\nexport function computeObservedVersionsFromFiber<\n T extends EnrichedFiberConstraint,\n>(tree: T): FiberObservedVersions {\n const observedVersions: Record<string, number> = {};\n const observedSourceVersions: Record<string, string> = {};\n\n const record = (\n filepath: unknown,\n modifiedTsRaw: unknown,\n sourceVersionRaw: unknown,\n ): void => {\n if (typeof filepath !== \"string\" || filepath.length === 0) return;\n const modifiedTs =\n typeof modifiedTsRaw === \"number\"\n ? modifiedTsRaw\n : typeof modifiedTsRaw === \"string\"\n ? Number(modifiedTsRaw)\n : NaN;\n if (Number.isNaN(modifiedTs)) return;\n const existing = observedVersions[filepath];\n if (existing === undefined || modifiedTs > existing) {\n observedVersions[filepath] = modifiedTs;\n // The token rides the file's newest render — same co-location rule the\n // DOM-side walker uses. A newest node without a token clears any stale\n // token from an older render (old-SDK / mid-HMR mixed tree).\n if (typeof sourceVersionRaw === \"string\" && sourceVersionRaw.length > 0) {\n observedSourceVersions[filepath] = sourceVersionRaw;\n } else {\n delete observedSourceVersions[filepath];\n }\n }\n };\n\n const visit = (node: EnrichedFiberConstraint): void => {\n const props = node.props;\n record(\n props?.[\"data-tempo-filepath\"],\n props?.[\"data-tempo-modifiedts\"],\n props?.[\"data-tempo-source-version\"],\n );\n for (const child of node.children) {\n visit(child as EnrichedFiberConstraint);\n }\n };\n\n visit(tree);\n return { observedVersions, observedSourceVersions };\n}\n\n/** Build the completeness facts shared by standing and one-shot captures.\n * `undefined` means the fiber arm was not sampled; `null` means it was sampled\n * and no root existed. Static DOM is authoritative only for a full HTML scope\n * in a document where React never registered a renderer. */\nexport function computeRenderDeclarations<T extends EnrichedFiberConstraint>(\n fiber: T | null | undefined,\n html: DomCapture | undefined,\n hasReactRenderer: boolean,\n document?: Document | null,\n identityScope?: RenderDeclarationScope,\n): Pick<\n CombinedCapture<T>,\n \"fiberDeclared\" | \"renderDeclared\" | \"renderIdentity\"\n> {\n const domIdentity = identityScope\n ? declareDomHostIdentity(\n identityScope.captureRoot,\n identityScope.supplementalRoots,\n )\n : undefined;\n const fiberIdentity = fiber ? declareFiberHostIdentity(fiber) : undefined;\n const identityMatching =\n domIdentity && fiberIdentity\n ? hostIdentityDeclarationsMatch(domIdentity, fiberIdentity)\n : undefined;\n return {\n ...(fiber !== undefined && {\n fiberDeclared: fiber\n ? {\n complete: true as const,\n ...(document && {\n domConsistent:\n identityMatching ??\n fiberHostIdentitiesAreLive(fiber, document),\n }),\n ...(fiberIdentity && { hostIdentity: fiberIdentity }),\n ...computeObservedVersionsFromFiber(fiber),\n }\n : null,\n }),\n ...(fiber\n ? { renderDeclared: { complete: true, kind: \"fiber\" } as const }\n : (identityScope?.renderMode === \"static-dom\" || !hasReactRenderer) &&\n html?.declared.complete === true\n ? {\n renderDeclared: {\n complete: true,\n kind: \"static-dom\",\n } as const,\n }\n : {}),\n ...(domIdentity && {\n renderIdentity: {\n dom: domIdentity,\n ...(fiberIdentity && { fiber: fiberIdentity }),\n ...(identityMatching !== undefined && {\n matching: identityMatching,\n }),\n },\n }),\n };\n}\n\n/** A React commit can leave `FiberRoot.current` describing host nodes that\n * have already been detached. A fiber arm is visible proof only when every\n * host identity it serialized still exists in the producer's live document. */\nexport function fiberHostIdentitiesAreLive<T extends EnrichedFiberConstraint>(\n fiber: T,\n document: Document,\n): boolean {\n const liveDomIds = new Set(\n Array.from(document.querySelectorAll<HTMLElement>(\"[data-dom-id]\"))\n .filter((element) => element.isConnected)\n .map((element) => element.getAttribute(\"data-dom-id\"))\n .filter((domId): domId is string => domId !== null),\n );\n const seenFiberDomIds = new Set<string>();\n const visit = (node: EnrichedFiberConstraint): boolean => {\n if (node.domId) {\n if (seenFiberDomIds.has(node.domId) || !liveDomIds.has(node.domId)) {\n return false;\n }\n seenFiberDomIds.add(node.domId);\n }\n return node.children.every((child) =>\n visit(child as EnrichedFiberConstraint),\n );\n };\n return visit(fiber);\n}\n","/**\n * Layout Kind\n *\n * Classifies a DOM element's container layout based on its computed styles,\n * and provides matching SVG icon markup for each kind.\n *\n * The four kinds mirror the \"draw\" tools in a typical design canvas:\n * - grid → display: grid\n * - row → flex stacking children vertically (flex-direction: column)\n * - column → flex stacking children horizontally (flex-direction: row)\n * - div → any other element that still counts as a layout parent\n * (position: relative|sticky|absolute)\n *\n * Plain statically positioned non-flex/non-grid elements are NOT layout\n * parents — drawing a child into them has no meaningful placement behavior,\n * so they return null.\n *\n * Naming follows the stacking metaphor: a \"row\" is one of a set of rows stacked\n * vertically, and a \"column\" is one of a set of columns placed side-by-side.\n */\n\nexport type ElementLayoutKind = \"row\" | \"column\" | \"grid\" | \"div\";\n\nexport function getElementLayoutKind(\n el: Element,\n style: CSSStyleDeclaration = getComputedStyle(el),\n): ElementLayoutKind | null {\n if (/grid/.test(style.display)) return \"grid\";\n if (/flex/.test(style.display)) {\n return /^column/.test(style.flexDirection) ? \"row\" : \"column\";\n }\n if (\n style.position === \"relative\" ||\n style.position === \"sticky\" ||\n style.position === \"absolute\"\n ) {\n return \"div\";\n }\n return null;\n}\n\n/** Static 12×12 SVG markup for each layout kind, stroked with `currentColor`\n * so the pill's text color drives the icon color. Shapes mirror the canvas\n * draw-tool icons (div / row / column / grid) — a filled rectangle split\n * into one, two stacked, two side-by-side, or four quadrants. */\nexport const LAYOUT_KIND_SVG: Record<ElementLayoutKind, string> = {\n div:\n '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">' +\n '<rect x=\"1.5\" y=\"1.5\" width=\"13\" height=\"13\" rx=\"3\" stroke=\"currentColor\"/>' +\n \"</svg>\",\n row:\n '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">' +\n '<rect x=\"1.5\" y=\"1.5\" width=\"13\" height=\"5.75\" rx=\"2\" stroke=\"currentColor\"/>' +\n '<rect x=\"1.5\" y=\"8.75\" width=\"13\" height=\"5.75\" rx=\"2\" stroke=\"currentColor\"/>' +\n \"</svg>\",\n column:\n '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">' +\n '<rect x=\"1.5\" y=\"1.5\" width=\"5.75\" height=\"13\" rx=\"2\" stroke=\"currentColor\"/>' +\n '<rect x=\"8.75\" y=\"1.5\" width=\"5.75\" height=\"13\" rx=\"2\" stroke=\"currentColor\"/>' +\n \"</svg>\",\n grid:\n '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">' +\n '<rect x=\"1.5\" y=\"1.5\" width=\"5.75\" height=\"5.75\" rx=\"1.5\" stroke=\"currentColor\"/>' +\n '<rect x=\"8.75\" y=\"1.5\" width=\"5.75\" height=\"5.75\" rx=\"1.5\" stroke=\"currentColor\"/>' +\n '<rect x=\"1.5\" y=\"8.75\" width=\"5.75\" height=\"5.75\" rx=\"1.5\" stroke=\"currentColor\"/>' +\n '<rect x=\"8.75\" y=\"8.75\" width=\"5.75\" height=\"5.75\" rx=\"1.5\" stroke=\"currentColor\"/>' +\n \"</svg>\",\n};\n","/**\n * Enriched Fiber Serializer\n *\n * Extends the default serializer with domId extraction from HostComponent\n * fibers and sanitized props from all component fibers.\n *\n * The domId comes from the `data-dom-id` attribute that the HTML watcher's\n * MutationObserver assigns to all DOM elements. By the time the debounce\n * fires and captureTree calls this serializer, the MutationObserver has\n * already assigned IDs (MutationObserver fires as microtask, debounce fires\n * as macrotask via setTimeout).\n */\n\nimport { getElementLayoutKind } from \"../../element-overlay/render/layout-kind\";\nimport type { Fiber } from \"../fiber/react-types\";\nimport {\n getDisplayName,\n getDomElement,\n getProps,\n getTag,\n sanitizeProps,\n} from \"../fiber/serialize\";\nimport type { SerializeFn } from \"../fiber/types\";\nimport { ensureProjectionDomId, readProjectionDomId } from \"../html/watch-dom\";\nimport { countCaptureStyleRead } from \"../shared/capture-perf\";\nimport type { EnrichedFiberNode } from \"./types\";\n\nlet nextFiberId = 1;\nlet fiberIdMap = new WeakMap<Fiber, string>();\n\n/**\n * Returns a stable ID for a fiber across re-renders.\n * React alternates current/work-in-progress fibers, so both alternates share one ID.\n */\nexport function getFiberId(fiber: Fiber): string {\n let id = fiberIdMap.get(fiber);\n if (id) return id;\n\n if (fiber.alternate) {\n id = fiberIdMap.get(fiber.alternate);\n if (id) {\n fiberIdMap.set(fiber, id);\n return id;\n }\n }\n\n id = String(nextFiberId++);\n fiberIdMap.set(fiber, id);\n if (fiber.alternate) {\n fiberIdMap.set(fiber.alternate, id);\n }\n return id;\n}\n\n/**\n * Test-only state reset for deterministic fiberId assertions.\n */\nexport function _resetFiberIdStateForTesting(): void {\n nextFiberId = 1;\n fiberIdMap = new WeakMap<Fiber, string>();\n}\n\n/**\n * Default enriched serializer for the combined module.\n *\n * Produces nodes with name, tag, domId (for HostComponents), and sanitized props.\n *\n * @example\n * ```ts\n * // Extend with additional fields:\n * interface MyNode extends EnrichedFiberNode { key?: string; }\n * const mySerialize: SerializeFn<MyNode> = (fiber) => ({\n * ...enrichedSerialize(fiber),\n * key: fiber.key ?? undefined,\n * });\n * ```\n */\n/**\n * react-native-web View/Text host components carry Tempo's source annotations in\n * a `dataSet` object instead of flat `data-*` props — RNW only flattens\n * dataSet→data-* onto the host DOM node, so the component fiber still reports\n * `dataSet`. Lift the `tempo*` keys out to flat `data-tempo-*` here, at capture,\n * so every downstream consumer (source extraction, modifiedts tracking, layer\n * building) sees one uniform shape and never has to know about `dataSet`. User\n * dataSet keys are preserved.\n */\nfunction normalizeTempoDataSet(\n props: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n const dataSet = props?.dataSet;\n if (!props || !dataSet || typeof dataSet !== \"object\") return props;\n\n let extracted: Record<string, unknown> | null = null;\n let remaining: Record<string, unknown> | null = null;\n for (const [key, value] of Object.entries(\n dataSet as Record<string, unknown>,\n )) {\n if (key.startsWith(\"tempo\")) {\n // \"tempoFilepath\" -> \"data-tempo-filepath\" (matches RNW's hyphenation).\n (extracted ??= {})[\n `data-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`\n ] = value;\n } else {\n (remaining ??= {})[key] = value;\n }\n }\n if (!extracted) return props;\n\n const out = { ...props, ...extracted };\n if (remaining) out.dataSet = remaining;\n else delete out.dataSet;\n return out;\n}\n\nexport const enrichedSerialize: SerializeFn<EnrichedFiberNode> = (fiber) => {\n const domElement = getDomElement(fiber);\n const allocatedDomId = domElement ? readProjectionDomId(domElement) : null;\n return {\n fiberId: getFiberId(fiber),\n name: getDisplayName(fiber),\n tag: getTag(fiber),\n ...(hasContextDependencies(fiber) && { hasContextDependencies: true }),\n ...(domElement && {\n domId:\n (allocatedDomId ? ensureProjectionDomId(domElement) : null) ??\n undefined,\n ...(hasContentEditableAncestor(domElement) && {\n insideContentEditable: true,\n }),\n layoutKind: layoutKindWithCountedStyleRead(domElement),\n }),\n props: normalizeTempoDataSet(sanitizeProps(getProps(fiber))),\n };\n};\n\n/** getElementLayoutKind's default style parameter is one getComputedStyle\n * call per host element — counted as a capture-path style read. */\nfunction layoutKindWithCountedStyleRead(element: Element) {\n countCaptureStyleRead();\n return getElementLayoutKind(element) ?? undefined;\n}\n\nfunction hasContentEditableAncestor(element: Element): boolean {\n let current = element.parentElement;\n while (current) {\n if (current.getAttribute(\"contenteditable\") !== null) return true;\n current = current.parentElement;\n }\n return false;\n}\n\nfunction hasContextDependencies(fiber: Fiber): boolean {\n const dependencies = fiber.dependencies;\n if (!dependencies || typeof dependencies !== \"object\") {\n return false;\n }\n\n return Boolean((dependencies as { firstContext?: unknown }).firstContext);\n}\n","import type { FiberRoot } from \"../fiber/react-types\";\nimport { serializeTree } from \"../fiber/serialize\";\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport { captureTree, getCommittedFiberRoots } from \"../fiber/watch\";\nimport type { EnrichedFiberConstraint } from \"./types\";\n\nconst shouldHideFiberNode = (\n node: { props?: Record<string, unknown> },\n hideFiberProp: string | undefined,\n): boolean => {\n if (!hideFiberProp) {\n return false;\n }\n\n const value = node.props?.[hideFiberProp];\n return value === true || value === \"true\";\n};\n\nconst filterHiddenFiberNode = <T extends EnrichedFiberConstraint>(\n node: T,\n hideFiberProp: string,\n): T[] => {\n const children = node.children.flatMap((child) =>\n filterHiddenFiberNode(child as T, hideFiberProp),\n );\n return shouldHideFiberNode(node, hideFiberProp)\n ? children\n : [{ ...node, children } as T];\n};\n\nexport const filterHiddenFiberTree = <T extends EnrichedFiberConstraint>(\n tree: T | null,\n hideFiberProp?: string,\n): T | null => {\n if (!tree || !hideFiberProp) {\n return tree;\n }\n\n return filterHiddenFiberNode(tree, hideFiberProp)[0] ?? null;\n};\n\nexport const captureCombinedFiberTree = <\n T extends EnrichedFiberConstraint,\n>(options: {\n serialize: SerializeFn<T>;\n selector?: string;\n /** DOM scope whose contained React roots make up one document-level render. */\n rootElement?: Element;\n tags?: FiberTagValue[];\n hideFiberProp?: string;\n}): T | null => {\n const rootElement = options.rootElement;\n if (options.selector || !rootElement) {\n const tree = captureTree<T>({\n serialize: options.serialize,\n selector: options.selector,\n tags: options.tags,\n });\n return filterHiddenFiberTree(tree, options.hideFiberProp);\n }\n\n const roots = getCommittedFiberRoots().filter((root) =>\n rootBelongsToElement(root, rootElement),\n );\n const firstRoot = roots[0];\n if (!firstRoot) return null;\n const trees = roots\n .flatMap((root) =>\n serializeRootBranches(root, options.serialize, options.tags),\n )\n .flatMap((tree) =>\n options.hideFiberProp\n ? filterHiddenFiberNode(tree, options.hideFiberProp)\n : [tree],\n );\n\n if (trees.length === 0) {\n return {\n ...options.serialize(firstRoot.current),\n domId: undefined,\n props: undefined,\n children: [],\n } as unknown as T;\n }\n if (trees.length === 1) return trees[0] ?? null;\n\n // CombinedCapture has one tree-shaped layers arm. Use a real serialized\n // HostRoot as its fragment-like aggregate and place each independent root\n // below it. Consumers therefore see every root without inventing an opaque\n // second wire shape or falsely declaring one root to be the whole document.\n return {\n ...options.serialize(firstRoot.current),\n fiberId: \"__tempo_document_fiber_roots__\",\n domId: undefined,\n props: undefined,\n children: trees,\n } as unknown as T;\n};\n\nfunction rootBelongsToElement(root: FiberRoot, element: Element): boolean {\n const container = root.containerInfo;\n return container === element || element.contains(container);\n}\n\nfunction serializeRootBranches<T extends EnrichedFiberConstraint>(\n root: FiberRoot,\n serialize: SerializeFn<T>,\n tags: FiberTagValue[] | undefined,\n): T[] {\n const tagSet = tags && tags.length > 0 ? new Set(tags) : null;\n const branches: T[] = [];\n for (let fiber = root.current.child; fiber; fiber = fiber.sibling) {\n const tree = serializeTree(fiber, serialize);\n if (!tree) continue;\n branches.push(...filterTreeBranches(tree, tagSet));\n }\n return branches;\n}\n\n/** Filter one serialized branch while preserving every promoted child. The\n * generic fiber utility returns a single tree and therefore cannot represent\n * an excluded Fragment/HostRoot with multiple included children. */\nfunction filterTreeBranches<T extends EnrichedFiberConstraint>(\n tree: T,\n tags: ReadonlySet<FiberTagValue> | null,\n): T[] {\n if (!tags || !(\"tag\" in tree)) return [tree];\n const children = tree.children.flatMap((child) =>\n filterTreeBranches(child as T, tags),\n );\n return tags.has((tree as T & { tag: FiberTagValue }).tag)\n ? [{ ...tree, children } as T]\n : children;\n}\n","/**\n * Reverse-skew adapter for pre-projection-batch interact frames.\n *\n * Current Tempo clients consume the document producer's closed, regional\n * ProjectionBatch stream directly. Deployed older clients still ask the\n * newest workspace SDK for `start-combined-watcher`, so this adapter uses the\n * document producer only as a change clock and materializes the old complete\n * CombinedCapture envelope at that one compatibility boundary.\n */\n\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport { initHook } from \"../fiber/watch\";\nimport { ROOT_COORDINATES_ATTRIBUTE } from \"../html/root-coordinates\";\nimport { PROJECTION_ROOT_TARGET_ID } from \"./projection-patch\";\nimport {\n captureProjectionSnapshot,\n collectProjectionPortalElements,\n} from \"../html/snapshot\";\nimport type { DomCapture } from \"../html/types\";\nimport {\n computeRenderDeclarations,\n createRenderDeclarationScope,\n} from \"./declared-facts\";\nimport {\n createCombinedDocumentProducer,\n type CombinedProjectionBatch,\n} from \"./document-producer\";\nimport { enrichedSerialize } from \"./enriched-serialize\";\nimport { captureCombinedFiberTree } from \"./hide-fiber-tree\";\nimport { nextRealmCaptureSequence, REALM_DOCUMENT_EPOCH } from \"./realm-epoch\";\nimport type {\n CombinedCapture,\n CombinedCaptureProvenance,\n CombinedWatchTrigger,\n EnrichedFiberConstraint,\n EnrichedFiberNode,\n} from \"./types\";\n\nconst LEGACY_FLUSH_WINDOW_MS = 50;\nlet nextLegacyWatchId = 1;\n\nexport interface CombinedWatchOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n debounceDelay?: number;\n /** Retained on the old wire; the fixed document scheduler supersedes it. */\n maxWait?: number;\n serialize?: SerializeFn<T>;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n hideFiberProp?: string;\n}\n\nexport type ResumeFlushPolicy = \"if-dirty\" | \"always\" | \"never\";\n\nexport interface CombinedWatchResumeOptions {\n flush?: ResumeFlushPolicy;\n triggers?: readonly CombinedWatchTrigger[];\n}\n\nexport type CombinedWatchHandle = (() => void) & {\n stop: () => void;\n pause: () => void;\n resume: (options?: CombinedWatchResumeOptions) => void;\n setPaused: (paused: boolean, options?: CombinedWatchResumeOptions) => void;\n};\n\nfunction realmHasReactRenderer(\n element: Element,\n localHook: ReturnType<typeof initHook>,\n): boolean {\n const view = element.ownerDocument.defaultView as\n | (Window & {\n __REACT_DEVTOOLS_GLOBAL_HOOK__?: { renderers?: Map<unknown, unknown> };\n })\n | null;\n return view && view !== window\n ? (view.__REACT_DEVTOOLS_GLOBAL_HOOK__?.renderers?.size ?? 0) > 0\n : (localHook.hook.renderers?.size ?? 0) > 0;\n}\n\nfunction captureLegacyEnvelope<T extends EnrichedFiberConstraint>(\n element: Element,\n hook: ReturnType<typeof initHook>,\n options: CombinedWatchOptions<T>,\n provenance: CombinedCaptureProvenance,\n coordinateOnlyPortalIds: ReadonlySet<string>,\n): CombinedCapture<T> {\n const supplementalRoots = collectProjectionPortalElements(element);\n const html = withCoordinateOnlyPortals(\n captureProjectionSnapshot(element, supplementalRoots),\n coordinateOnlyPortalIds,\n );\n const fiber = captureCombinedFiberTree<T>({\n rootElement: element,\n selector: options.fiberSelector,\n tags: options.fiberTags,\n hideFiberProp: options.hideFiberProp,\n serialize:\n options.serialize ?? (enrichedSerialize as unknown as SerializeFn<T>),\n });\n return {\n html,\n fiber,\n ...computeRenderDeclarations(\n fiber,\n html,\n realmHasReactRenderer(element, hook),\n element.ownerDocument,\n createRenderDeclarationScope(element, supplementalRoots),\n ),\n provenance,\n documentEpoch: REALM_DOCUMENT_EPOCH,\n sequence: nextRealmCaptureSequence(),\n };\n}\n\nfunction triggersForBatch(\n batch: CombinedProjectionBatch,\n): CombinedWatchTrigger[] {\n const triggers = new Set<CombinedWatchTrigger>();\n if (batch.head !== undefined) triggers.add(\"head\");\n for (const change of batch.roots) {\n if (change.kind !== \"patch\") {\n triggers.add(\"dom\");\n triggers.add(\"fiber\");\n continue;\n }\n const patch = change.patch;\n // The attribute carrier is transport metadata, not an authored DOM edit.\n // Preserve the legacy head-only provenance for coordinate refreshes.\n if (\n patch.dom?.some(\n (change) =>\n change.kind !== \"attributes\" ||\n change.targetId !== PROJECTION_ROOT_TARGET_ID ||\n Object.keys(change.attributes).some(\n (name) => name !== ROOT_COORDINATES_ATTRIBUTE,\n ),\n )\n )\n triggers.add(\"dom\");\n if (patch.state?.length) triggers.add(\"state\");\n for (const portal of patch.portals ?? []) {\n // A portal moved by new styling is the head's doing, and this envelope\n // reports it as one refreshed coordinate space, not as portal content.\n if (portal.kind === \"replace\" && portal.coordinatesOnly) continue;\n // A portal is an arm of the same Fiber tree this envelope re-serializes\n // whole, so its content always arrives with a current fiber.\n triggers.add(\"portal\");\n triggers.add(\"fiber\");\n }\n if (patch.layers) triggers.add(\"fiber\");\n }\n return triggers.size > 0 ? [...triggers] : [\"dom\", \"fiber\"];\n}\n\n/** Portal ids this batch refreshed coordinates for without resending their\n * bodies. The old envelope always re-serializes every portal, so those are\n * downgraded back to coordinate-only updates to keep the destination's focus\n * and edit state inside an unchanged portal. */\nfunction coordinateOnlyPortalIds(batch: CombinedProjectionBatch): Set<string> {\n const ids = new Set<string>();\n for (const change of batch.roots) {\n if (change.kind !== \"patch\") continue;\n for (const portal of change.patch.portals ?? []) {\n if (portal.kind === \"replace\" && portal.coordinatesOnly) {\n ids.add(portal.portalId);\n }\n }\n }\n return ids;\n}\n\nfunction withCoordinateOnlyPortals(\n capture: DomCapture,\n portalIds: ReadonlySet<string>,\n): DomCapture {\n if (portalIds.size === 0 || !capture.portals) return capture;\n return {\n ...capture,\n portals: capture.portals.map((portal) =>\n portalIds.has(portal.id)\n ? { ...portal, html: \"\", states: [], coordinatesOnly: true }\n : portal,\n ),\n };\n}\n\n/** @deprecated Retained only for old clients talking to a new interact frame. */\nexport function watchCombined<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(\n element: Element,\n onChange: (capture: CombinedCapture<T>) => void,\n options: CombinedWatchOptions<T> = {},\n): CombinedWatchHandle {\n const rootId = `legacy-combined-root-${nextLegacyWatchId++}`;\n const sessionId = `legacy-combined-session-${nextLegacyWatchId++}`;\n const hook = initHook();\n let stopped = false;\n let paused = false;\n let dirtyWhilePaused = false;\n let resumeTriggers: readonly CombinedWatchTrigger[] | undefined;\n\n const producer = createCombinedDocumentProducer<T>({\n document: element.ownerDocument,\n flushWindowMs: options.debounceDelay ?? LEGACY_FLUSH_WINDOW_MS,\n emit(batch) {\n if (stopped) return;\n if (paused) {\n dirtyWhilePaused = true;\n return;\n }\n const provenance: CombinedCaptureProvenance =\n batch.sequence === 0\n ? { kind: \"initial\" }\n : {\n kind: \"watch\",\n triggers: resumeTriggers\n ? [...resumeTriggers]\n : triggersForBatch(batch),\n };\n resumeTriggers = undefined;\n onChange(\n captureLegacyEnvelope(\n element,\n hook,\n options,\n provenance,\n coordinateOnlyPortalIds(batch),\n ),\n );\n },\n });\n producer.bindSession(sessionId);\n producer.watchRoot({\n rootId,\n element,\n // The legacy envelope covers the whole watched subtree, including\n // independent React roots; its change clock must observe that same scope.\n scope: \"subtree\",\n layerFramework: realmHasReactRenderer(element, hook) ? \"react\" : \"dom\",\n });\n // Preserve the legacy API's synchronous initial emission while keeping the\n // document producer as the sole observer/scheduler owner.\n producer.requestFull(rootId);\n\n const stop = () => {\n if (stopped) return;\n stopped = true;\n producer.stop();\n };\n const pause = () => {\n if (stopped || paused) return;\n paused = true;\n // The producer may have retained observer records that have not reached\n // its fixed-window callback yet. Conservatively rebuild once on resume;\n // the old destination values correctness over compatibility-path work.\n dirtyWhilePaused = true;\n };\n const resume = (resumeOptions?: CombinedWatchResumeOptions) => {\n if (stopped || !paused) return;\n paused = false;\n const policy = resumeOptions?.flush ?? \"if-dirty\";\n const shouldFlush =\n policy === \"always\" || (policy === \"if-dirty\" && dirtyWhilePaused);\n dirtyWhilePaused = false;\n if (shouldFlush) {\n resumeTriggers = [\"dom\", ...(resumeOptions?.triggers ?? [])];\n producer.requestFull(rootId);\n }\n };\n const setPaused = (\n nextPaused: boolean,\n resumeOptions?: CombinedWatchResumeOptions,\n ) => (nextPaused ? pause() : resume(resumeOptions));\n\n return Object.assign(stop, { stop, pause, resume, setPaused });\n}\n\n/**\n * Selector lifecycle for the old interact command. HMR may replace the target\n * element without replacing the document, so the binding is re-resolved and\n * the replacement begins with one complete legacy envelope.\n */\nexport function watchCombinedSelector<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(\n root: Document | Element,\n selector: string | undefined,\n onChange: (capture: CombinedCapture<T>) => void,\n options: CombinedWatchOptions<T> = {},\n): CombinedWatchHandle {\n const documentRoot = root.nodeType === 9;\n let activeElement: Element | null = null;\n let activeWatcher: CombinedWatchHandle | null = null;\n let targetObserver: MutationObserver | null = null;\n let stopped = false;\n let paused = false;\n let dirtyWhilePaused = false;\n let hasBound = false;\n\n const getTarget = () =>\n selector\n ? root.querySelector(selector)\n : documentRoot\n ? (root as Document).body\n : (root as Element);\n const disconnect = () => {\n targetObserver?.disconnect();\n targetObserver = null;\n };\n const stopActive = () => {\n activeWatcher?.stop();\n activeWatcher = null;\n activeElement = null;\n };\n // Observe the selector scope, not only the target's current parent: Vite\n // HMR can replace both the target and its parent in one mutation. Every\n // reconcile disconnects first, so each path that keeps watching must re-arm.\n const armSelectorObserver = () => {\n if (!selector) return;\n targetObserver = new MutationObserver(reconcile);\n targetObserver.observe(root, { childList: true, subtree: true });\n };\n\n const reconcile = () => {\n if (stopped) return;\n const target = getTarget();\n if (\n activeElement &&\n (!activeElement.isConnected || activeElement !== target)\n ) {\n stopActive();\n dirtyWhilePaused = true;\n }\n disconnect();\n if (!target || paused) {\n if (!paused && selector) {\n targetObserver = new MutationObserver(reconcile);\n targetObserver.observe(root, {\n attributes: true,\n childList: true,\n subtree: true,\n });\n }\n return;\n }\n // Still watching the same target: nothing to rebind, but `disconnect()`\n // above dropped the selector observer, and every capture ends in a\n // reconcile — leaving it dropped blinds the watcher to the first target\n // swap after the first change.\n if (activeWatcher) {\n armSelectorObserver();\n return;\n }\n\n const rebind = hasBound;\n hasBound = true;\n activeElement = target;\n activeWatcher = watchCombined(\n target,\n (capture) => {\n if (!target.isConnected || target !== getTarget()) {\n reconcile();\n return;\n }\n onChange(\n rebind && capture.provenance?.kind === \"initial\"\n ? {\n ...capture,\n provenance: {\n kind: \"watch\",\n triggers: [\"selector-rebind\"],\n },\n }\n : capture,\n );\n queueMicrotask(reconcile);\n },\n options,\n );\n armSelectorObserver();\n };\n\n reconcile();\n const stop = () => {\n if (stopped) return;\n stopped = true;\n disconnect();\n stopActive();\n };\n const pause = () => {\n if (stopped || paused) return;\n paused = true;\n dirtyWhilePaused = true;\n disconnect();\n activeWatcher?.pause();\n };\n const resume = (resumeOptions?: CombinedWatchResumeOptions) => {\n if (stopped || !paused) return;\n paused = false;\n if (activeWatcher) {\n activeWatcher.resume(resumeOptions);\n dirtyWhilePaused = false;\n } else if (\n (resumeOptions?.flush ?? \"if-dirty\") === \"always\" ||\n dirtyWhilePaused\n ) {\n dirtyWhilePaused = false;\n reconcile();\n }\n queueMicrotask(reconcile);\n };\n const setPaused = (\n nextPaused: boolean,\n resumeOptions?: CombinedWatchResumeOptions,\n ) => (nextPaused ? pause() : resume(resumeOptions));\n return Object.assign(stop, { stop, pause, resume, setPaused });\n}\n","import {\n isProjectionRepairPaths,\n type ProjectionRepairPaths,\n} from \"./projection-repair-paths\";\n/**\n * Document Projection PostMessage Interface\n *\n * Provides one ordered ProjectionBatch stream carrying exact DOM, head, and\n * semantic-layer changes from a source iframe to its destination.\n *\n * ## Usage\n *\n * ### Source Side (in iframe)\n * ```ts\n * import { initHook } from '@modules/iframe-projection/fiber';\n * initHook(); // Before React loads\n *\n * import { startCombinedSourceInterface } from '@modules/iframe-projection/combined/postmessage';\n * startCombinedSourceInterface();\n * ```\n *\n * ### Dest Side (parent window)\n * ```ts\n * import { watchProjectionBatchesIframe } from '@modules/iframe-projection/combined/postmessage';\n *\n * const watcher = await watchProjectionBatchesIframe(iframe, {\n * sessionId: 'source-document-1',\n * rootId: 'storyboard-1',\n * selector: '#root',\n * onBatch: (batch) => destination.enqueue(batch),\n * });\n *\n * watcher.stop();\n * ```\n */\n\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport {\n type CombinedDocumentProducer,\n type CombinedProjectionBatch,\n createCombinedDocumentProducer,\n} from \"./document-producer\";\nimport type { DetachSerializedFiber } from \"./enriched-to-serialized-fiber\";\nimport { isLayerFramework, type LayerFramework } from \"./layer-framework\";\nimport { trackAstroSources } from \"./projection-astro-metadata\";\nimport {\n decodeCombinedProjectionBatch,\n encodeProjectionBatch,\n type ProjectionBatchEnvelope,\n} from \"./projection-batch\";\nimport {\n isProjectionRegionCapture,\n type ProjectionRegionCapture,\n} from \"./projection-full-snapshot\";\nimport { isProjectionSemanticSubtree } from \"./projection-semantic-subtree\";\nimport type {\n CombinedCapture,\n EnrichedFiberConstraint,\n EnrichedFiberNode,\n} from \"./types\";\nimport { type CombinedWatchHandle, watchCombinedSelector } from \"./watch\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Message Types\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Marker to identify our messages (shared across all iframe-projection protocols) */\nconst MESSAGE_MARKER = \"__iframeProjection\" as const;\n\ninterface BaseMessage {\n [MESSAGE_MARKER]: true;\n}\n\n// Handshake\ninterface CombinedSourceReadyMessage extends BaseMessage {\n type: \"combined-source-ready\";\n}\ninterface CombinedPingCommand extends BaseMessage {\n type: \"combined-ping\";\n}\ninterface CombinedPongResponse extends BaseMessage {\n type: \"combined-pong\";\n}\n\n// Watcher lifecycle\ninterface StartCombinedWatcherCommand extends BaseMessage {\n type: \"start-combined-watcher\";\n requestId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n}\ninterface CombinedWatcherStartedResponse extends BaseMessage {\n type: \"combined-watcher-started\";\n requestId: string;\n watcherId: string;\n}\ninterface StopCombinedWatcherCommand extends BaseMessage {\n type: \"stop-combined-watcher\";\n watcherId: string;\n}\ninterface SetCombinedWatcherPausedCommand extends BaseMessage {\n type: \"set-combined-watcher-paused\";\n watcherId: string;\n paused: boolean;\n}\ninterface CombinedWatcherStoppedResponse extends BaseMessage {\n type: \"combined-watcher-stopped\";\n watcherId: string;\n}\n\n// Exact document projection lifecycle. The same command names are used by the\n// iframe and Electron page bridges; only their delivery mechanism differs.\ninterface StartProjectionWatcherCommand extends BaseMessage {\n type: \"start-projection-watcher\";\n requestId: string;\n sessionId: string;\n rootId: string;\n layerFramework: LayerFramework;\n scope?: \"contents\" | \"subtree\";\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n}\ninterface ProjectionWatcherStartedResponse extends BaseMessage {\n type: \"projection-watcher-started\";\n requestId: string;\n watcherId: string;\n}\ninterface RequestProjectionFullCommand extends BaseMessage {\n type: \"request-projection-full\";\n watcherId: string;\n includeHead?: boolean;\n}\ninterface CaptureProjectionSemanticSubtreeCommand extends BaseMessage {\n type: \"capture-projection-semantic-subtree\";\n requestId: string;\n watcherId: string;\n targetFiberId?: string;\n mode?: \"context\";\n}\ninterface ProjectionSemanticSubtreeResponse extends BaseMessage {\n type: \"projection-semantic-subtree-response\";\n requestId: string;\n subtree: (DetachSerializedFiber & { truncated?: boolean }) | null;\n error?: string;\n}\ninterface CaptureProjectionRegionCommand extends BaseMessage {\n type: \"capture-projection-region\";\n requestId: string;\n watcherId: string;\n targetId: string;\n}\ninterface ProjectionRegionResponse extends BaseMessage {\n type: \"projection-region-response\";\n requestId: string;\n region: ProjectionRegionCapture | null;\n error?: string;\n}\ninterface StopProjectionWatcherCommand extends BaseMessage {\n type: \"stop-projection-watcher\";\n watcherId: string;\n}\ninterface CancelProjectionWatcherCommand extends BaseMessage {\n type: \"cancel-projection-watcher\";\n requestId: string;\n}\ninterface ProjectionWatcherStoppedResponse extends BaseMessage {\n type: \"projection-watcher-stopped\";\n watcherId: string;\n}\n\n// Data\ninterface CombinedUpdateMessage extends BaseMessage {\n type: \"combined-update\";\n watcherId: string;\n capture: CombinedCapture;\n}\ninterface ProjectionBatchUpdateMessage extends BaseMessage {\n type: \"projection-batch\";\n batch: CombinedProjectionBatch | ProjectionBatchEnvelope;\n}\n\n// Error\ninterface CombinedErrorMessage extends BaseMessage {\n type: \"combined-error\";\n error: string;\n requestId?: string;\n watcherId?: string;\n}\n\ntype CombinedMessage =\n | CombinedSourceReadyMessage\n | CombinedPingCommand\n | CombinedPongResponse\n | StartCombinedWatcherCommand\n | CombinedWatcherStartedResponse\n | StopCombinedWatcherCommand\n | SetCombinedWatcherPausedCommand\n | CombinedWatcherStoppedResponse\n | CombinedUpdateMessage\n | StartProjectionWatcherCommand\n | ProjectionWatcherStartedResponse\n | RequestProjectionFullCommand\n | CaptureProjectionSemanticSubtreeCommand\n | ProjectionSemanticSubtreeResponse\n | CaptureProjectionRegionCommand\n | ProjectionRegionResponse\n | StopProjectionWatcherCommand\n | CancelProjectionWatcherCommand\n | ProjectionWatcherStoppedResponse\n | ProjectionBatchUpdateMessage\n | CombinedErrorMessage;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Type Guards\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isMessage(data: unknown): data is CombinedMessage {\n return (\n typeof data === \"object\" &&\n data !== null &&\n MESSAGE_MARKER in data &&\n (data as any)[MESSAGE_MARKER] === true\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Source Side (iframe)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Active watchers by ID */\nconst combinedWatchers = new Map<string, CombinedWatchHandle>();\n\nlet nextCombinedWatcherId = 1;\nlet combinedSourceInitialized = false;\nlet combinedSourceCleanup: (() => void) | null = null;\n\nfunction installWhenDocumentBodyReady(install: () => () => void): () => void {\n let cancelled = false;\n let installedCleanup: (() => void) | null = null;\n let animationFrameId: number | null = null;\n let listeningForDomReady = false;\n\n const init = () => {\n listeningForDomReady = false;\n animationFrameId = null;\n if (cancelled) return;\n if (document.body) {\n installedCleanup = install();\n return;\n }\n animationFrameId = requestAnimationFrame(init);\n };\n\n if (document.readyState === \"loading\") {\n listeningForDomReady = true;\n document.addEventListener(\"DOMContentLoaded\", init);\n } else {\n init();\n }\n\n return () => {\n if (cancelled) return;\n cancelled = true;\n if (listeningForDomReady) {\n document.removeEventListener(\"DOMContentLoaded\", init);\n listeningForDomReady = false;\n }\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId);\n animationFrameId = null;\n }\n installedCleanup?.();\n installedCleanup = null;\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\ntype ProjectionSourceEventType =\n | \"projection-watcher-started\"\n | \"projection-watcher-stopped\"\n | \"projection-batch\"\n | \"projection-semantic-subtree-response\"\n | \"projection-region-response\"\n | \"error\";\n\ninterface ProjectionSourceController {\n /** Returns true when the payload belongs to the exact projection protocol. */\n handleCommand(payload: unknown): boolean;\n stop(): void;\n}\n\n/**\n * Source-side ownership shared by postMessage iframes and Electron pages.\n * There is one producer per live source document; the transports only forward\n * its closed ProjectionBatch DTO and lifecycle commands.\n */\nfunction createProjectionSourceController<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(options: {\n document: Document;\n watcherIdPrefix: string;\n serialize?: SerializeFn<T>;\n hideFiberProp?: string;\n layerFramework?: LayerFramework;\n send(type: ProjectionSourceEventType, payload: Record<string, unknown>): void;\n}): ProjectionSourceController {\n type WatcherRegistration = {\n readonly rootId: string;\n readonly sessionId: string;\n readonly requestId: string;\n };\n\n const watchers = new Map<string, WatcherRegistration>();\n const pendingBatches: CombinedProjectionBatch[] = [];\n let nextWatcherId = 1;\n let producer: CombinedDocumentProducer<T> | null = null;\n let sessionId: string | null = null;\n let watchesEstablishing = 0;\n let stopped = false;\n\n const sendError = (\n error: unknown,\n scope: { requestId?: string; watcherId?: string } = {},\n ): void => {\n options.send(\"error\", {\n ...scope,\n error: error instanceof Error ? error.message : String(error),\n });\n };\n\n const publishBatch = (batch: CombinedProjectionBatch): void => {\n if (stopped) return;\n // A newly registered root can request an immediate full after sequence\n // zero. Keep acknowledgement ahead of any batch that registration causes.\n if (watchesEstablishing > 0) {\n pendingBatches.push(batch);\n return;\n }\n options.send(\"projection-batch\", { batch: encodeProjectionBatch(batch) });\n };\n\n const flushPendingBatches = (): void => {\n if (stopped || watchesEstablishing > 0) return;\n for (const batch of pendingBatches.splice(0)) {\n publishBatch(batch);\n }\n };\n\n const getProducer = (\n requestedSessionId: string,\n ): CombinedDocumentProducer<T> => {\n if (sessionId !== null && sessionId !== requestedSessionId) {\n if (watchers.size > 0) {\n throw new Error(\n \"A source document cannot bind two projection sessions at once\",\n );\n }\n producer?.stop();\n producer = null;\n sessionId = null;\n pendingBatches.length = 0;\n }\n producer ??= createCombinedDocumentProducer<T>({\n document: options.document,\n emit: publishBatch,\n onError: (error) => sendError(error),\n });\n return producer;\n };\n\n const stopWatcher = (watcherId: string): void => {\n const registration = watchers.get(watcherId);\n if (!registration) return;\n producer?.unwatchRoot(registration.rootId);\n watchers.delete(watcherId);\n if (watchers.size === 0) {\n // An iframe or pooled page can remain alive after its destination\n // detaches. No observer, React subscription, or timer survives idle.\n producer?.stop();\n producer = null;\n sessionId = null;\n pendingBatches.length = 0;\n }\n options.send(\"projection-watcher-stopped\", { watcherId });\n };\n\n return {\n handleCommand(payload) {\n if (stopped || !isRecord(payload) || typeof payload.type !== \"string\") {\n return false;\n }\n\n if (payload.type === \"start-projection-watcher\") {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n const requestedSessionId =\n typeof payload.sessionId === \"string\" ? payload.sessionId.trim() : \"\";\n const rootId =\n typeof payload.rootId === \"string\" ? payload.rootId.trim() : \"\";\n const layerFramework = isLayerFramework(payload.layerFramework)\n ? payload.layerFramework\n : null;\n if (!requestId || !requestedSessionId || !rootId || !layerFramework) {\n sendError(\n new Error(\n \"Exact projection watch requires requestId, sessionId, rootId, and layerFramework\",\n ),\n requestId ? { requestId } : {},\n );\n return true;\n }\n\n const selector =\n typeof payload.selector === \"string\" ? payload.selector : undefined;\n const fiberSelector =\n typeof payload.fiberSelector === \"string\"\n ? payload.fiberSelector\n : undefined;\n const fiberTags = Array.isArray(payload.fiberTags)\n ? (payload.fiberTags as FiberTagValue[])\n : undefined;\n const watcherId = `${options.watcherIdPrefix}-${nextWatcherId++}`;\n watchesEstablishing += 1;\n const establish = (element: Element) => {\n let watched = false;\n try {\n const activeProducer = getProducer(requestedSessionId);\n activeProducer.watchRoot({\n rootId,\n element,\n layerFramework: options.layerFramework ?? layerFramework,\n scope:\n payload.scope === \"contents\" || payload.scope === \"subtree\"\n ? payload.scope\n : undefined,\n serialize: options.serialize,\n fiberSelector:\n options.layerFramework === \"dom\" ? undefined : fiberSelector,\n fiberTags:\n options.layerFramework === \"dom\" ? undefined : fiberTags,\n hideFiberProp:\n options.layerFramework === \"dom\"\n ? undefined\n : options.hideFiberProp,\n });\n watched = true;\n if (sessionId !== requestedSessionId) {\n activeProducer.bindSession(requestedSessionId);\n sessionId = requestedSessionId;\n }\n watchers.set(watcherId, {\n rootId,\n sessionId: requestedSessionId,\n requestId,\n });\n options.send(\"projection-watcher-started\", {\n requestId,\n watcherId,\n });\n } catch (error) {\n if (watched) producer?.unwatchRoot(rootId);\n sendError(error, { requestId });\n } finally {\n watchesEstablishing -= 1;\n flushPendingBatches();\n }\n };\n const body = options.document.body;\n if (!selector) {\n if (body) establish(body);\n else {\n watchesEstablishing -= 1;\n sendError(new Error(\"Element not found: body\"), { requestId });\n }\n return true;\n }\n // A root named by selector may not have rendered when the request\n // arrives: a direct-render guest answers ready before React commits\n // its storyboard. The watch waits for the element instead of\n // failing the request, and the requester's own timeout bounds it.\n let found: Element | null;\n try {\n found = options.document.querySelector(selector);\n } catch (error) {\n watchesEstablishing -= 1;\n sendError(error, { requestId });\n return true;\n }\n if (found) {\n establish(found);\n return true;\n }\n const observer = new MutationObserver(() => {\n const element = options.document.querySelector(selector);\n if (!element) return;\n observer.disconnect();\n if (stopped) watchesEstablishing -= 1;\n else establish(element);\n });\n observer.observe(options.document, {\n childList: true,\n subtree: true,\n attributes: true,\n });\n return true;\n }\n\n if (\n payload.type === \"request-projection-full\" ||\n payload.type === \"request-projection-repair\"\n ) {\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n const registration = watcherId ? watchers.get(watcherId) : undefined;\n if (!registration || registration.sessionId !== sessionId) {\n if (watcherId) {\n sendError(new Error(\"Projection watcher is not active\"), {\n watcherId,\n });\n }\n return true;\n }\n if (payload.type === \"request-projection-repair\") {\n if (isProjectionRepairPaths(payload.paths))\n producer?.requestRepair(registration.rootId, payload.paths);\n } else if (payload.includeHead === true) {\n producer?.requestFull(registration.rootId, { includeHead: true });\n } else {\n producer?.requestFull(registration.rootId);\n }\n return true;\n }\n\n if (payload.type === \"capture-projection-semantic-subtree\") {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n const targetFiberId =\n typeof payload.targetFiberId === \"string\"\n ? payload.targetFiberId.trim()\n : \"\";\n const registration = watcherId ? watchers.get(watcherId) : undefined;\n const context = payload.mode === \"context\";\n const valid = context\n ? payload.targetFiberId === undefined\n : payload.mode === undefined && !!targetFiberId;\n if (!requestId || !registration || !valid) {\n if (requestId) {\n options.send(\"projection-semantic-subtree-response\", {\n requestId,\n subtree: null,\n error:\n \"Semantic subtree capture requires an active watcher and targetFiberId\",\n });\n }\n return true;\n }\n try {\n const subtree = producer?.captureSemanticSubtree(\n registration.rootId,\n context ? { mode: \"context\" } : targetFiberId,\n { descendants: payload.descendants !== false },\n );\n options.send(\"projection-semantic-subtree-response\", {\n requestId,\n subtree: subtree ?? null,\n });\n } catch (error) {\n options.send(\"projection-semantic-subtree-response\", {\n requestId,\n subtree: null,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return true;\n }\n\n if (payload.type === \"capture-projection-region\") {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n const targetId =\n typeof payload.targetId === \"string\" ? payload.targetId.trim() : \"\";\n const registration = watcherId ? watchers.get(watcherId) : undefined;\n if (!requestId || !registration || !targetId) {\n if (requestId) {\n options.send(\"projection-region-response\", {\n requestId,\n region: null,\n error: \"Region capture requires an active watcher and targetId\",\n });\n }\n return true;\n }\n try {\n const region = producer?.captureRegion(registration.rootId, targetId);\n options.send(\"projection-region-response\", {\n requestId,\n region: region ?? null,\n });\n } catch (error) {\n options.send(\"projection-region-response\", {\n requestId,\n region: null,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return true;\n }\n\n if (payload.type === \"stop-projection-watcher\") {\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n if (watcherId) stopWatcher(watcherId);\n return true;\n }\n\n if (payload.type === \"cancel-projection-watcher\") {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n if (!requestId) return true;\n const entry = Array.from(watchers).find(\n ([, registration]) => registration.requestId === requestId,\n );\n if (entry) stopWatcher(entry[0]);\n return true;\n }\n\n return false;\n },\n stop() {\n if (stopped) return;\n stopped = true;\n producer?.stop();\n producer = null;\n sessionId = null;\n watchers.clear();\n pendingBatches.length = 0;\n },\n };\n}\n\nexport interface CombinedSourceOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n targetOrigin?: string;\n /** Custom fiber serializer used for all watchers started via postMessage */\n serialize?: SerializeFn<T>;\n /** Hide fibers whose serialized props contain this truthy prop */\n hideFiberProp?: string;\n}\n\n/**\n * Starts the combined source-side postMessage interface.\n *\n * IMPORTANT: Call initHook() BEFORE React loads, then call this after DOM is ready.\n *\n * @param options - Source options\n * @returns Cleanup function\n */\nexport function startCombinedSourceInterface<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(options: CombinedSourceOptions<T> = {}): () => void {\n if (typeof document !== \"undefined\") trackAstroSources(document);\n const { targetOrigin = \"*\", serialize, hideFiberProp } = options;\n\n if (combinedSourceInitialized) {\n console.warn(\"[combined-postmessage:source] Already initialized\");\n return combinedSourceCleanup || (() => {});\n }\n\n if (typeof window === \"undefined\" || window.parent === window) {\n console.log(\"[combined-postmessage:source] Not in iframe, skipping\");\n return () => {};\n }\n\n combinedSourceInitialized = true;\n let disposeDeferredInstall = () => {};\n let disposed = false;\n const cleanup = () => {\n if (disposed) return;\n disposed = true;\n disposeDeferredInstall();\n if (combinedSourceCleanup === cleanup) {\n combinedSourceCleanup = null;\n combinedSourceInitialized = false;\n }\n };\n combinedSourceCleanup = cleanup;\n const deferredInstall = installWhenDocumentBodyReady(() =>\n initCombinedSourceInterface(targetOrigin, serialize, hideFiberProp),\n );\n if (disposed) deferredInstall();\n else disposeDeferredInstall = deferredInstall;\n return cleanup;\n}\n\nfunction initCombinedSourceInterface<T extends EnrichedFiberConstraint>(\n targetOrigin: string,\n serialize?: SerializeFn<T>,\n hideFiberProp?: string,\n): () => void {\n (window as any).__IFRAME_PROJECTION_COMBINED_INTERFACE_ACTIVE__ = true;\n\n const send = (msg: CombinedMessage) => {\n if (\"batch\" in msg && msg.batch instanceof ArrayBuffer) {\n window.parent.postMessage(\n { ...msg, [MESSAGE_MARKER]: true },\n targetOrigin,\n [msg.batch],\n );\n return;\n }\n window.parent.postMessage({ ...msg, [MESSAGE_MARKER]: true }, targetOrigin);\n };\n const projectionSource = createProjectionSourceController<T>({\n document,\n watcherIdPrefix: \"iframe-projection-watcher\",\n serialize,\n hideFiberProp,\n send(type, payload) {\n if (type === \"error\") {\n send({\n type: \"combined-error\",\n [MESSAGE_MARKER]: true,\n ...(payload as Omit<\n CombinedErrorMessage,\n typeof MESSAGE_MARKER | \"type\"\n >),\n });\n return;\n }\n send({\n type,\n [MESSAGE_MARKER]: true,\n ...payload,\n } as CombinedMessage);\n },\n });\n\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n if (!isMessage(data)) return;\n if (projectionSource.handleCommand(data)) return;\n\n switch (data.type) {\n case \"combined-ping\":\n send({ type: \"combined-pong\", [MESSAGE_MARKER]: true });\n break;\n\n case \"start-combined-watcher\": {\n const {\n requestId,\n selector,\n fiberSelector,\n fiberTags,\n debounceDelay,\n maxWait,\n } = data;\n const watcherId = `combined-watcher-${nextCombinedWatcherId++}`;\n\n try {\n const pendingCaptures: CombinedCapture[] = [];\n let established = false;\n const watcher = watchCombinedSelector(\n document,\n selector,\n (capture) => {\n if (!established) {\n pendingCaptures.push(capture);\n return;\n }\n send({\n type: \"combined-update\",\n [MESSAGE_MARKER]: true,\n watcherId,\n capture,\n });\n },\n {\n debounceDelay,\n maxWait,\n ...(serialize && {\n serialize: serialize as unknown as SerializeFn<any>,\n }),\n fiberSelector,\n fiberTags,\n hideFiberProp,\n },\n );\n\n combinedWatchers.set(watcherId, watcher);\n send({\n type: \"combined-watcher-started\",\n [MESSAGE_MARKER]: true,\n requestId,\n watcherId,\n });\n established = true;\n for (const capture of pendingCaptures) {\n send({\n type: \"combined-update\",\n [MESSAGE_MARKER]: true,\n watcherId,\n capture,\n });\n }\n console.log(\n `[combined-postmessage:source] Started ${watcherId} on ${selector || \"body\"}`,\n );\n } catch (err) {\n send({\n type: \"combined-error\",\n [MESSAGE_MARKER]: true,\n requestId,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n break;\n }\n\n case \"stop-combined-watcher\": {\n const { watcherId } = data;\n const watcher = combinedWatchers.get(watcherId);\n\n if (watcher) {\n watcher.stop();\n combinedWatchers.delete(watcherId);\n send({\n type: \"combined-watcher-stopped\",\n [MESSAGE_MARKER]: true,\n watcherId,\n });\n console.log(`[combined-postmessage:source] Stopped ${watcherId}`);\n }\n break;\n }\n\n case \"set-combined-watcher-paused\": {\n const watcher = combinedWatchers.get(data.watcherId);\n watcher?.setPaused(data.paused);\n break;\n }\n }\n };\n\n window.addEventListener(\"message\", handleMessage);\n\n send({ type: \"combined-source-ready\", [MESSAGE_MARKER]: true });\n console.log(\n \"[combined-postmessage:source] Ready, sent combined-source-ready\",\n );\n\n return () => {\n window.removeEventListener(\"message\", handleMessage);\n projectionSource.stop();\n for (const [id, watcher] of combinedWatchers) {\n watcher.stop();\n console.log(`[combined-postmessage:source] Stopped ${id}`);\n }\n combinedWatchers.clear();\n delete (window as any).__IFRAME_PROJECTION_COMBINED_INTERFACE_ACTIVE__;\n console.log(\"[combined-postmessage:source] Cleaned up\");\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Deprecated CombinedCapture destination compatibility\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Handle for the pre-ProjectionBatch combined transport.\n *\n * @deprecated New projection consumers should use {@link ProjectionBatchWatcher}.\n * This remains an opt-in transport adapter for independent library consumers\n * and deployed destinations; it is not used by the Canvas hot path.\n */\nexport interface CombinedWatcher {\n id: string;\n stop: () => void;\n pause: () => void;\n resume: () => void;\n setPaused: (paused: boolean) => void;\n}\n\n/** @deprecated Use {@link WatchProjectionBatchesIframeOptions}. */\nexport interface WatchCombinedIframeOptions {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n targetOrigin?: string;\n onUpdate: (capture: CombinedCapture) => void;\n onError?: (error: Error) => void;\n}\n\n/** @deprecated Use {@link WatchProjectionBatchesPageOptions}. */\nexport interface WatchCombinedPageOptions {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n /** Cancels source-readiness and watcher establishment. */\n signal?: AbortSignal;\n onUpdate: (capture: CombinedCapture) => void;\n onError?: (error: Error) => void;\n}\n\n/**\n * Options for a cold, one-shot complete DOM + Fiber capture.\n *\n * @deprecated Exact live projection should use ProjectionBatch. This cold\n * query remains useful when a complete compatibility envelope is the result.\n */\nexport interface CaptureCombinedPageOptions {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n}\n\ntype LegacyCombinedChannelCommand =\n | { type: \"ping\" }\n | {\n type: \"start-watcher\";\n requestId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n }\n | { type: \"set-watcher-paused\"; watcherId: string; paused: boolean }\n | { type: \"stop-watcher\"; watcherId: string }\n | {\n type: \"capture\";\n requestId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n };\n\ntype LegacyCombinedChannelEvent =\n | { type: \"ready\" }\n | { type: \"watcher-started\"; requestId: string; watcherId: string }\n | { type: \"update\"; watcherId: string; capture: CombinedCapture }\n | {\n type: \"capture-response\";\n requestId: string;\n capture: CombinedCapture | null;\n }\n | {\n type: \"error\";\n error: string;\n requestId: unknown;\n watcherId: unknown;\n };\n\ninterface LegacyCombinedChannel {\n readonly readinessTimeoutMessage: string;\n nextWatcherRequestId(): string;\n nextCaptureRequestId(): string;\n send(command: LegacyCombinedChannelCommand): void;\n listen(listener: (event: LegacyCombinedChannelEvent) => void): () => void;\n}\n\nfunction normalizeLegacyCombinedChannelEvent(\n value: unknown,\n): LegacyCombinedChannelEvent | null {\n if (!isRecord(value) || typeof value.type !== \"string\") return null;\n switch (value.type) {\n case \"combined-source-ready\":\n case \"combined-pong\":\n case \"source-ready\":\n case \"pong\":\n return { type: \"ready\" };\n case \"combined-watcher-started\":\n case \"watcher-started\":\n return typeof value.requestId === \"string\" &&\n typeof value.watcherId === \"string\"\n ? {\n type: \"watcher-started\",\n requestId: value.requestId,\n watcherId: value.watcherId,\n }\n : null;\n case \"combined-update\":\n return typeof value.watcherId === \"string\" && isRecord(value.capture)\n ? {\n type: \"update\",\n watcherId: value.watcherId,\n capture: value.capture as unknown as CombinedCapture,\n }\n : null;\n case \"capture-response\":\n return typeof value.requestId === \"string\"\n ? {\n type: \"capture-response\",\n requestId: value.requestId,\n capture: isRecord(value.capture)\n ? (value.capture as unknown as CombinedCapture)\n : null,\n }\n : null;\n case \"combined-error\":\n case \"error\":\n return typeof value.error === \"string\"\n ? {\n type: \"error\",\n error: value.error,\n requestId: value.requestId,\n watcherId: value.watcherId,\n }\n : null;\n default:\n return null;\n }\n}\n\ntype ChannelResolution<T> =\n | { status: \"success\"; value: T }\n | { status: \"failure\"; error: Error }\n | undefined;\n\n/** The only thing a request/response wait needs of its transport. */\ninterface ListenableChannel<TEvent> {\n listen(listener: (event: TEvent) => void): () => void;\n}\n\n/**\n * Resolve one request against a channel: send, then settle on the first event\n * `receive` recognises. Without `retryInterval` the send happens once and\n * `timeout` bounds the wait; with it the send repeats until `timeout` elapses,\n * which is how a listener that may not exist yet is reached.\n *\n * The listener is registered before the first send so a synchronous reply\n * cannot be missed, and is removed on every exit path including one that\n * settles during registration.\n */\nfunction waitForChannelEvent<TEvent, T>(\n channel: ListenableChannel<TEvent>,\n options: {\n timeout: number;\n timeoutError: string;\n abortError: () => Error;\n signal?: AbortSignal;\n retryInterval?: number;\n send(): void;\n onAbort?: () => void;\n receive(event: TEvent): ChannelResolution<T>;\n },\n): Promise<T> {\n return new Promise((resolve, reject) => {\n if (options.signal?.aborted) {\n reject(options.abortError());\n return;\n }\n\n const startedAt = Date.now();\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let removeListener: (() => void) | null = null;\n let cleanupPending = false;\n\n const cleanup = (): void => {\n if (timer !== null) clearTimeout(timer);\n timer = null;\n options.signal?.removeEventListener(\"abort\", onAbort);\n if (removeListener) {\n bestEffort(removeListener);\n removeListener = null;\n } else {\n cleanupPending = true;\n }\n };\n const fail = (error: Error): void => {\n if (settled) return;\n settled = true;\n cleanup();\n reject(error);\n };\n const succeed = (value: T): void => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve(value);\n };\n const onAbort = (): void => {\n bestEffort(() => options.onAbort?.());\n fail(options.abortError());\n };\n const receive = (event: TEvent): void => {\n if (settled) return;\n let resolution: ChannelResolution<T>;\n try {\n resolution = options.receive(event);\n } catch (error) {\n fail(errorFromUnknown(error));\n return;\n }\n if (resolution?.status === \"failure\") fail(resolution.error);\n else if (resolution?.status === \"success\") succeed(resolution.value);\n };\n\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const registeredListener = channel.listen(receive);\n if (cleanupPending) bestEffort(registeredListener);\n else removeListener = registeredListener;\n } catch (error) {\n fail(errorFromUnknown(error));\n return;\n }\n if (settled) return;\n\n const send = (): void => {\n if (settled) return;\n if (\n options.retryInterval !== undefined &&\n Date.now() - startedAt > options.timeout\n ) {\n fail(new Error(options.timeoutError));\n return;\n }\n try {\n options.send();\n } catch (error) {\n fail(errorFromUnknown(error));\n return;\n }\n if (!settled && options.retryInterval !== undefined) {\n timer = setTimeout(send, options.retryInterval);\n }\n };\n\n if (options.retryInterval === undefined) {\n timer = setTimeout(\n () => fail(new Error(options.timeoutError)),\n options.timeout,\n );\n }\n send();\n });\n}\n\nfunction waitForLegacyCombinedSourceReady(\n channel: LegacyCombinedChannel,\n timeout: number,\n signal?: AbortSignal,\n): Promise<void> {\n return waitForChannelEvent(channel, {\n timeout,\n signal,\n timeoutError: channel.readinessTimeoutMessage,\n abortError: combinedSetupAbortError,\n retryInterval: 100,\n send: () => channel.send({ type: \"ping\" }),\n receive: (event) =>\n event.type === \"ready\"\n ? { status: \"success\", value: undefined }\n : undefined,\n });\n}\n\nfunction requestLegacyCombinedWatcher(\n channel: LegacyCombinedChannel,\n options: Omit<\n Extract<LegacyCombinedChannelCommand, { type: \"start-watcher\" }>,\n \"type\" | \"requestId\"\n >,\n timeout: number,\n signal?: AbortSignal,\n): Promise<string> {\n const requestId = channel.nextWatcherRequestId();\n return waitForChannelEvent(channel, {\n timeout,\n signal,\n timeoutError: \"Timeout waiting for combined watcher to start\",\n abortError: combinedSetupAbortError,\n send: () => channel.send({ type: \"start-watcher\", requestId, ...options }),\n receive: (event) => {\n if (event.type === \"watcher-started\" && event.requestId === requestId) {\n return { status: \"success\", value: event.watcherId };\n }\n if (\n event.type === \"error\" &&\n (event.requestId === undefined || event.requestId === requestId)\n ) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n return undefined;\n },\n });\n}\n\nasync function watchLegacyCombinedChannel(\n channel: LegacyCombinedChannel,\n options: {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n signal?: AbortSignal;\n onUpdate(capture: CombinedCapture): void;\n onError?(error: Error): void;\n },\n): Promise<CombinedWatcher> {\n const timeout = options.timeout ?? 10000;\n await waitForLegacyCombinedSourceReady(channel, timeout, options.signal);\n\n let stopped = false;\n let watcherId: string | null = null;\n const pendingUpdates = new Map<string, CombinedCapture[]>();\n const removeListener = channel.listen((event) => {\n if (stopped) return;\n if (event.type === \"update\") {\n if (watcherId === null) {\n const updates = pendingUpdates.get(event.watcherId) ?? [];\n updates.push(event.capture);\n pendingUpdates.set(event.watcherId, updates);\n } else if (event.watcherId === watcherId) {\n options.onUpdate(event.capture);\n }\n return;\n }\n if (\n watcherId !== null &&\n event.type === \"error\" &&\n (event.watcherId === undefined || event.watcherId === watcherId)\n ) {\n options.onError?.(new Error(event.error));\n }\n });\n\n try {\n watcherId = await requestLegacyCombinedWatcher(\n channel,\n {\n selector: options.selector,\n fiberSelector: options.fiberSelector,\n fiberTags: options.fiberTags,\n debounceDelay: options.debounceDelay,\n maxWait: options.maxWait,\n },\n timeout,\n options.signal,\n );\n } catch (error) {\n stopped = true;\n bestEffort(removeListener);\n throw error;\n }\n\n const activeWatcherId = watcherId;\n if (options.signal?.aborted) {\n stopped = true;\n bestEffort(removeListener);\n bestEffort(() =>\n channel.send({ type: \"stop-watcher\", watcherId: activeWatcherId }),\n );\n throw combinedSetupAbortError();\n }\n\n for (const capture of pendingUpdates.get(activeWatcherId) ?? []) {\n options.onUpdate(capture);\n }\n pendingUpdates.clear();\n\n const setPaused = (paused: boolean): void => {\n if (stopped) return;\n bestEffort(() =>\n channel.send({\n type: \"set-watcher-paused\",\n watcherId: activeWatcherId,\n paused,\n }),\n );\n };\n return {\n id: activeWatcherId,\n pause: () => setPaused(true),\n resume: () => setPaused(false),\n setPaused,\n stop() {\n if (stopped) return;\n stopped = true;\n bestEffort(removeListener);\n bestEffort(() =>\n channel.send({ type: \"stop-watcher\", watcherId: activeWatcherId }),\n );\n },\n };\n}\n\nasync function captureLegacyCombinedChannel(\n channel: LegacyCombinedChannel,\n options: CaptureCombinedPageOptions,\n): Promise<CombinedCapture | null> {\n const timeout = options.timeout ?? 10000;\n await waitForLegacyCombinedSourceReady(channel, timeout);\n const requestId = channel.nextCaptureRequestId();\n return waitForChannelEvent(channel, {\n timeout,\n timeoutError: \"Timeout waiting for combined capture response\",\n abortError: combinedSetupAbortError,\n send: () =>\n channel.send({\n type: \"capture\",\n requestId,\n selector: options.selector,\n fiberSelector: options.fiberSelector,\n fiberTags: options.fiberTags,\n }),\n receive: (event) => {\n if (event.type === \"capture-response\" && event.requestId === requestId) {\n return { status: \"success\", value: event.capture };\n }\n if (\n event.type === \"error\" &&\n (event.requestId === undefined || event.requestId === requestId)\n ) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n return undefined;\n },\n });\n}\n\ntype ProjectionChannelCommand =\n | { type: \"ping\" }\n | {\n type: \"start-projection-watcher\";\n requestId: string;\n sessionId: string;\n rootId: string;\n layerFramework: LayerFramework;\n scope?: \"contents\" | \"subtree\";\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n }\n | { type: \"cancel-projection-watcher\"; requestId: string }\n | {\n type: \"request-projection-repair\";\n watcherId: string;\n paths: ProjectionRepairPaths;\n }\n | {\n type: \"request-projection-full\";\n watcherId: string;\n includeHead?: boolean;\n }\n | {\n type: \"capture-projection-semantic-subtree\";\n requestId: string;\n watcherId: string;\n targetFiberId?: string;\n mode?: \"context\";\n }\n | {\n type: \"capture-projection-region\";\n requestId: string;\n watcherId: string;\n targetId: string;\n }\n | { type: \"stop-projection-watcher\"; watcherId: string };\n\ntype ProjectionChannelEvent =\n | { type: \"ready\" }\n | { type: \"watcher-started\"; requestId: string; watcherId: string }\n | { type: \"batch\"; batch: unknown }\n | {\n type: \"semantic-subtree\";\n requestId: string;\n subtree: unknown;\n error?: string;\n }\n | {\n type: \"region\";\n requestId: string;\n region: unknown;\n error?: string;\n }\n | {\n type: \"error\";\n error: string;\n requestId: unknown;\n watcherId: unknown;\n };\n\ninterface ProjectionChannel {\n readonly readinessTimeoutMessage: string;\n nextWatcherRequestId(): string;\n send(command: ProjectionChannelCommand): void;\n listen(listener: (event: ProjectionChannelEvent) => void): () => void;\n}\n\ninterface ProjectionChannelWatchOptions {\n sessionId: string;\n rootId: string;\n layerFramework: LayerFramework;\n scope?: \"contents\" | \"subtree\";\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n signal?: AbortSignal;\n onBatch(batch: CombinedProjectionBatch): void;\n onError?(error: Error): void;\n}\n\nfunction normalizeProjectionChannelEvent(\n value: unknown,\n): ProjectionChannelEvent | null {\n if (!isRecord(value) || typeof value.type !== \"string\") return null;\n switch (value.type) {\n case \"combined-source-ready\":\n case \"combined-pong\":\n case \"source-ready\":\n case \"pong\":\n return { type: \"ready\" };\n case \"projection-watcher-started\":\n return typeof value.requestId === \"string\" &&\n typeof value.watcherId === \"string\"\n ? {\n type: \"watcher-started\",\n requestId: value.requestId,\n watcherId: value.watcherId,\n }\n : null;\n case \"projection-batch\":\n return { type: \"batch\", batch: value.batch };\n case \"projection-semantic-subtree-response\":\n return typeof value.requestId === \"string\"\n ? {\n type: \"semantic-subtree\",\n requestId: value.requestId,\n subtree: value.subtree,\n error: typeof value.error === \"string\" ? value.error : undefined,\n }\n : null;\n case \"projection-region-response\":\n return typeof value.requestId === \"string\"\n ? {\n type: \"region\",\n requestId: value.requestId,\n region: value.region,\n error: typeof value.error === \"string\" ? value.error : undefined,\n }\n : null;\n case \"combined-error\":\n case \"error\":\n return typeof value.error === \"string\"\n ? {\n type: \"error\",\n error: value.error,\n requestId: value.requestId,\n watcherId: value.watcherId,\n }\n : null;\n default:\n return null;\n }\n}\n\nfunction errorFromUnknown(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction bestEffort(action: () => void): void {\n try {\n action();\n } catch {\n // Reload and destruction are normal transport teardown boundaries.\n }\n}\n\nasync function waitForProjectionChannelReady(\n channel: ProjectionChannel,\n timeout: number,\n signal?: AbortSignal,\n): Promise<void> {\n await waitForChannelEvent(channel, {\n signal,\n timeout,\n timeoutError: channel.readinessTimeoutMessage,\n abortError: combinedSetupAbortError,\n retryInterval: 100,\n send: () => channel.send({ type: \"ping\" }),\n receive: (event) =>\n event.type === \"ready\"\n ? { status: \"success\", value: undefined }\n : undefined,\n });\n}\n\nfunction requestProjectionChannelWatcher(\n channel: ProjectionChannel,\n options: {\n sessionId: string;\n rootId: string;\n layerFramework: LayerFramework;\n scope?: \"contents\" | \"subtree\";\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n },\n timeout: number,\n signal?: AbortSignal,\n): Promise<string> {\n const requestId = channel.nextWatcherRequestId();\n return waitForChannelEvent(channel, {\n signal,\n timeout,\n timeoutError: \"Timeout waiting for projection watcher to start\",\n abortError: combinedSetupAbortError,\n onAbort: () =>\n channel.send({ type: \"cancel-projection-watcher\", requestId }),\n send: () =>\n channel.send({\n type: \"start-projection-watcher\",\n requestId,\n ...options,\n }),\n receive: (event) => {\n if (event.type === \"watcher-started\" && event.requestId === requestId) {\n return { status: \"success\", value: event.watcherId };\n }\n if (\n event.type === \"error\" &&\n (event.requestId === undefined || event.requestId === requestId)\n ) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n return undefined;\n },\n });\n}\n\nlet nextProjectionSemanticQueryRequestId = 1;\n\nfunction requestProjectionChannelSemanticSubtree(\n channel: ProjectionChannel,\n watcherId: string,\n targetFiberId: string | { readonly mode: \"context\" },\n timeout: number,\n signal: AbortSignal,\n options?: { readonly descendants?: boolean },\n): Promise<(DetachSerializedFiber & { truncated?: boolean }) | null> {\n const requestId = `projection-semantic-query-${nextProjectionSemanticQueryRequestId++}`;\n return waitForChannelEvent(channel, {\n signal,\n timeout,\n timeoutError: \"Timeout waiting for projection semantic subtree\",\n abortError: () => new Error(\"Projection semantic query was cancelled\"),\n send: () =>\n channel.send({\n type: \"capture-projection-semantic-subtree\",\n requestId,\n watcherId,\n ...(typeof targetFiberId === \"string\"\n ? { targetFiberId }\n : { mode: \"context\" as const }),\n // A producer that predates this field answers with the whole subtree.\n ...(options?.descendants === false ? { descendants: false } : {}),\n }),\n receive: (event) => {\n if (event.type !== \"semantic-subtree\" || event.requestId !== requestId) {\n return undefined;\n }\n if (event.error) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n if (\n event.subtree !== null &&\n (!isProjectionSemanticSubtree(event.subtree) ||\n (typeof targetFiberId !== \"string\" &&\n (typeof (event.subtree as { truncated?: unknown }).truncated !==\n \"boolean\" ||\n new TextEncoder().encode(JSON.stringify(event.subtree))\n .byteLength >\n 256 * 1024)))\n ) {\n return {\n status: \"failure\",\n error: new Error(\n \"Projection source returned an invalid semantic subtree\",\n ),\n };\n }\n return { status: \"success\", value: event.subtree };\n },\n });\n}\n\nlet nextProjectionRegionQueryRequestId = 1;\n\nfunction requestProjectionChannelRegion(\n channel: ProjectionChannel,\n watcherId: string,\n targetId: string,\n timeout: number,\n signal: AbortSignal,\n): Promise<ProjectionRegionCapture | null> {\n const requestId = `projection-region-query-${nextProjectionRegionQueryRequestId++}`;\n return waitForChannelEvent(channel, {\n signal,\n timeout,\n timeoutError: \"Timeout waiting for projection region capture\",\n abortError: () => new Error(\"Projection region query was cancelled\"),\n send: () =>\n channel.send({\n type: \"capture-projection-region\",\n requestId,\n watcherId,\n targetId,\n }),\n receive: (event) => {\n if (event.type !== \"region\" || event.requestId !== requestId) {\n return undefined;\n }\n if (event.error) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n if (event.region !== null && !isProjectionRegionCapture(event.region)) {\n return {\n status: \"failure\",\n error: new Error(\n \"Projection source returned an invalid region capture\",\n ),\n };\n }\n return { status: \"success\", value: event.region };\n },\n });\n}\n\nasync function watchProjectionChannel(\n channel: ProjectionChannel,\n options: ProjectionChannelWatchOptions,\n): Promise<ProjectionBatchWatcher> {\n const {\n sessionId,\n rootId,\n layerFramework,\n scope,\n selector,\n fiberSelector,\n fiberTags,\n timeout = 10000,\n signal,\n onBatch,\n onError,\n } = options;\n const normalizedSessionId = sessionId.trim();\n const normalizedRootId = rootId.trim();\n if (!normalizedSessionId) {\n throw new Error(\"Projection session ID must not be empty\");\n }\n if (!normalizedRootId) {\n throw new Error(\"Projection root ID must not be empty\");\n }\n\n await waitForProjectionChannelReady(channel, timeout, signal);\n\n let stopped = false;\n let watcherId: string | null = null;\n const pendingBatches: CombinedProjectionBatch[] = [];\n const removeListener = channel.listen((event) => {\n if (stopped) return;\n if (event.type === \"batch\") {\n const batch = decodeCombinedProjectionBatch(event.batch);\n if (!batch || batch.sessionId !== normalizedSessionId) return;\n if (watcherId === null) pendingBatches.push(batch);\n else onBatch(batch);\n return;\n }\n if (\n watcherId !== null &&\n event.type === \"error\" &&\n (event.watcherId === undefined || event.watcherId === watcherId)\n ) {\n onError?.(new Error(event.error));\n }\n });\n\n try {\n watcherId = await requestProjectionChannelWatcher(\n channel,\n {\n sessionId: normalizedSessionId,\n rootId: normalizedRootId,\n layerFramework,\n scope,\n selector,\n fiberSelector,\n fiberTags,\n },\n timeout,\n signal,\n );\n } catch (error) {\n stopped = true;\n bestEffort(removeListener);\n throw error;\n }\n\n const activeWatcherId = watcherId;\n if (signal?.aborted) {\n stopped = true;\n bestEffort(removeListener);\n bestEffort(() =>\n channel.send({\n type: \"stop-projection-watcher\",\n watcherId: activeWatcherId,\n }),\n );\n throw combinedSetupAbortError();\n }\n\n for (const batch of pendingBatches) onBatch(batch);\n pendingBatches.length = 0;\n // Every in-flight on-demand query (semantic subtree and region capture),\n // so stopping the watcher cancels them instead of leaving them to time out.\n const pendingQueryControllers = new Set<AbortController>();\n\n return {\n id: activeWatcherId,\n requestRepair(paths) {\n if (!stopped)\n bestEffort(() =>\n channel.send({\n type: \"request-projection-repair\",\n watcherId: activeWatcherId,\n paths,\n }),\n );\n },\n requestFull(options) {\n if (stopped) return;\n bestEffort(() =>\n channel.send({\n type: \"request-projection-full\",\n watcherId: activeWatcherId,\n ...(options?.includeHead ? { includeHead: true } : {}),\n }),\n );\n },\n captureSemanticSubtree(targetFiberId, options) {\n if (stopped) {\n return Promise.reject(new Error(\"Projection watcher has been stopped\"));\n }\n const normalizedTargetFiberId =\n typeof targetFiberId === \"string\"\n ? targetFiberId.trim()\n : targetFiberId;\n if (!normalizedTargetFiberId) {\n return Promise.reject(\n new Error(\"Projection semantic target ID must not be empty\"),\n );\n }\n const controller = new AbortController();\n pendingQueryControllers.add(controller);\n return requestProjectionChannelSemanticSubtree(\n channel,\n activeWatcherId,\n normalizedTargetFiberId,\n timeout,\n controller.signal,\n options,\n ).finally(() => pendingQueryControllers.delete(controller));\n },\n captureRegion(targetId) {\n if (stopped) {\n return Promise.reject(new Error(\"Projection watcher has been stopped\"));\n }\n const normalizedTargetId = targetId.trim();\n if (!normalizedTargetId) {\n return Promise.reject(\n new Error(\"Projection region target ID must not be empty\"),\n );\n }\n const controller = new AbortController();\n pendingQueryControllers.add(controller);\n return requestProjectionChannelRegion(\n channel,\n activeWatcherId,\n normalizedTargetId,\n timeout,\n controller.signal,\n ).finally(() => pendingQueryControllers.delete(controller));\n },\n stop() {\n if (stopped) return;\n stopped = true;\n for (const controller of pendingQueryControllers) controller.abort();\n pendingQueryControllers.clear();\n bestEffort(removeListener);\n bestEffort(() =>\n channel.send({\n type: \"stop-projection-watcher\",\n watcherId: activeWatcherId,\n }),\n );\n },\n };\n}\n\nlet nextLegacyIframeWatcherRequestId = 1;\n\nfunction createIframeLegacyCombinedChannel(\n contentWindow: Window,\n targetOrigin: string,\n): LegacyCombinedChannel {\n return {\n readinessTimeoutMessage:\n \"Timeout waiting for combined iframe source - did you call startCombinedSourceInterface()?\",\n nextWatcherRequestId: () =>\n `combined-watch-req-${nextLegacyIframeWatcherRequestId++}`,\n nextCaptureRequestId: () => {\n throw new Error(\"The legacy iframe transport has no one-shot capture\");\n },\n send(command) {\n let wireCommand: Record<string, unknown>;\n switch (command.type) {\n case \"ping\":\n wireCommand = { type: \"combined-ping\" };\n break;\n case \"start-watcher\":\n wireCommand = { ...command, type: \"start-combined-watcher\" };\n break;\n case \"set-watcher-paused\":\n wireCommand = {\n ...command,\n type: \"set-combined-watcher-paused\",\n };\n break;\n case \"stop-watcher\":\n wireCommand = { ...command, type: \"stop-combined-watcher\" };\n break;\n case \"capture\":\n throw new Error(\n \"The legacy iframe transport has no one-shot capture\",\n );\n }\n contentWindow.postMessage(\n { ...wireCommand, [MESSAGE_MARKER]: true },\n targetOrigin,\n );\n },\n listen(listener) {\n const handleMessage = (event: MessageEvent): void => {\n if (event.source !== contentWindow || !isMessage(event.data)) return;\n const normalized = normalizeLegacyCombinedChannelEvent(event.data);\n if (normalized) listener(normalized);\n };\n window.addEventListener(\"message\", handleMessage);\n return () => window.removeEventListener(\"message\", handleMessage);\n },\n };\n}\n\n/**\n * Watch an iframe through the pre-ProjectionBatch complete-capture protocol.\n *\n * @deprecated Use {@link watchProjectionBatchesIframe}. This adapter is\n * intentionally isolated from the exact Canvas projection path.\n */\nexport function watchCombinedIframe(\n iframe: HTMLIFrameElement,\n options: WatchCombinedIframeOptions,\n): Promise<CombinedWatcher> {\n const contentWindow = iframe.contentWindow;\n if (!contentWindow) {\n return Promise.reject(new Error(\"Cannot access iframe contentWindow\"));\n }\n return watchLegacyCombinedChannel(\n createIframeLegacyCombinedChannel(\n contentWindow,\n options.targetOrigin ?? \"*\",\n ),\n options,\n );\n}\n\nlet nextProjectionIframeWatcherRequestId = 1;\n\nfunction createIframeProjectionChannel(\n contentWindow: Window,\n targetOrigin: string,\n): ProjectionChannel {\n return {\n readinessTimeoutMessage:\n \"Timeout waiting for combined iframe source - did you call startCombinedSourceInterface()?\",\n nextWatcherRequestId: () =>\n `projection-iframe-watch-${nextProjectionIframeWatcherRequestId++}`,\n send(command) {\n const wireCommand =\n command.type === \"ping\"\n ? { type: \"combined-ping\", [MESSAGE_MARKER]: true }\n : { ...command, [MESSAGE_MARKER]: true };\n contentWindow.postMessage(wireCommand, targetOrigin);\n },\n listen(listener) {\n const handleMessage = (event: MessageEvent): void => {\n if (event.source !== contentWindow || !isMessage(event.data)) return;\n const normalized = normalizeProjectionChannelEvent(event.data);\n if (normalized) listener(normalized);\n };\n window.addEventListener(\"message\", handleMessage);\n return () => window.removeEventListener(\"message\", handleMessage);\n },\n };\n}\n\n/**\n * Subscribe directly to the iframe document's ordered ProjectionBatch stream.\n * Source capture remains live during destination previews; the watcher exposes\n * only explicit full recovery and teardown, never source-side pause/resume.\n */\nexport function watchProjectionBatchesIframe(\n iframe: HTMLIFrameElement,\n options: WatchProjectionBatchesIframeOptions,\n): Promise<ProjectionBatchWatcher> {\n const contentWindow = iframe.contentWindow;\n if (!contentWindow) {\n return Promise.reject(new Error(\"Cannot access iframe contentWindow\"));\n }\n return watchProjectionChannel(\n createIframeProjectionChannel(contentWindow, options.targetOrigin ?? \"*\"),\n options,\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Webview Support (Electron IPC instead of postMessage)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface PageMessageHandle {\n send: (channel: string, ...args: unknown[]) => void;\n on: (channel: string, callback: (...args: unknown[]) => void) => () => void;\n}\n\nexport interface CombinedWebviewBridge {\n sendToHost: (channel: string, payload: unknown) => void;\n onCommand: (handler: (payload: unknown) => void) => () => void;\n}\n\nexport interface CombinedWebviewSourceOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n serialize?: SerializeFn<T>;\n hideFiberProp?: string;\n layerFramework?: LayerFramework;\n}\n\n/**\n * One exact document-projection subscription over the frame-pool page bridge.\n * Source observation remains current while destination-local preview queues\n * pause; the transport itself has no pause operation.\n */\nexport interface ProjectionBatchWatcher {\n requestRepair(paths: ProjectionRepairPaths): void;\n readonly id: string;\n requestFull(options?: { readonly includeHead?: boolean }): void;\n /** Cold source-side capture of exactly one selected semantic branch, or of\n * the selected node alone with `descendants: false`. */\n captureSemanticSubtree(\n targetFiberId: string | { readonly mode: \"context\" },\n options?: { readonly descendants?: boolean },\n ): Promise<(DetachSerializedFiber & { truncated?: boolean }) | null>;\n /** Cold scoped-repair capture of one element's exact children region; null\n * when the id no longer exists at the source. */\n captureRegion(targetId: string): Promise<ProjectionRegionCapture | null>;\n stop(): void;\n}\n\nexport interface WatchProjectionBatchesIframeOptions {\n /** Lifecycle-owned identity. A reloaded iframe receives a new session. */\n sessionId: string;\n /** Stable identity used by the Canvas destination to route root-local work. */\n rootId: string;\n layerFramework: LayerFramework;\n scope?: \"contents\" | \"subtree\";\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n targetOrigin?: string;\n /** Cancels source-readiness and watcher establishment. */\n signal?: AbortSignal;\n onBatch(batch: CombinedProjectionBatch): void;\n onError?(error: Error): void;\n}\n\nexport interface WatchProjectionBatchesPageOptions {\n /** Lifecycle-owned identity. A reloaded document receives a new session. */\n sessionId: string;\n /** Stable identity used by the Canvas destination to route root-local work. */\n rootId: string;\n layerFramework: LayerFramework;\n scope?: \"contents\" | \"subtree\";\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n /** Cancels source-readiness and watcher establishment. */\n signal?: AbortSignal;\n onBatch(batch: CombinedProjectionBatch): void;\n onError?(error: Error): void;\n}\n\nlet webviewCombinedSourceInitialized = false;\nlet webviewCombinedSourceCleanup: (() => void) | null = null;\n\nexport function startCombinedSourceWebviewInterface<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(\n bridge: CombinedWebviewBridge,\n options: CombinedWebviewSourceOptions<T> = {},\n): () => void {\n if (typeof document !== \"undefined\") trackAstroSources(document);\n if (webviewCombinedSourceInitialized) {\n console.warn(\"[combined-postmessage:webview-source] Already initialized\");\n return webviewCombinedSourceCleanup || (() => {});\n }\n\n webviewCombinedSourceInitialized = true;\n let disposeDeferredInstall = () => {};\n let disposed = false;\n const cleanup = () => {\n if (disposed) return;\n disposed = true;\n disposeDeferredInstall();\n if (webviewCombinedSourceCleanup === cleanup) {\n webviewCombinedSourceCleanup = null;\n webviewCombinedSourceInitialized = false;\n }\n };\n webviewCombinedSourceCleanup = cleanup;\n const deferredInstall = installWhenDocumentBodyReady(() =>\n initCombinedWebviewSourceInterface(bridge, options),\n );\n if (disposed) deferredInstall();\n else disposeDeferredInstall = deferredInstall;\n return cleanup;\n}\n\nfunction initCombinedWebviewSourceInterface<T extends EnrichedFiberConstraint>(\n bridge: CombinedWebviewBridge,\n options: CombinedWebviewSourceOptions<T>,\n): () => void {\n (window as any).__IFRAME_PROJECTION_COMBINED_WEBVIEW_INTERFACE_ACTIVE__ =\n true;\n\n const send = (type: string, payload: Record<string, unknown>) => {\n bridge.sendToHost(\"combined-projection:update\", { type, ...payload });\n };\n\n const projectionSource = createProjectionSourceController<T>({\n document,\n watcherIdPrefix: \"webview-projection-watcher\",\n serialize: options.serialize,\n hideFiberProp: options.hideFiberProp,\n layerFramework: options.layerFramework,\n send,\n });\n const legacyWatchers = new Map<string, CombinedWatchHandle>();\n let nextLegacyWatcherId = 1;\n\n const handleCommand = (payload: unknown) => {\n if (!isRecord(payload) || typeof payload.type !== \"string\") {\n return;\n }\n if (projectionSource.handleCommand(payload)) return;\n\n switch (payload.type) {\n case \"ping\": {\n send(\"pong\", {});\n break;\n }\n\n // Deprecated compatibility commands are deliberately handled after the\n // exact projection controller. They instantiate their own compatibility\n // envelope only when an old destination explicitly requests one.\n case \"start-watcher\": {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n const selector =\n typeof payload.selector === \"string\" ? payload.selector : undefined;\n const fiberSelector =\n typeof payload.fiberSelector === \"string\"\n ? payload.fiberSelector\n : undefined;\n const fiberTags = Array.isArray(payload.fiberTags)\n ? (payload.fiberTags as FiberTagValue[])\n : undefined;\n const debounceDelay =\n typeof payload.debounceDelay === \"number\"\n ? payload.debounceDelay\n : undefined;\n const maxWait =\n typeof payload.maxWait === \"number\" ? payload.maxWait : undefined;\n const watcherId = `webview-combined-watcher-${nextLegacyWatcherId++}`;\n\n try {\n const pendingCaptures: CombinedCapture<T>[] = [];\n let established = false;\n const watcher = watchCombinedSelector<T>(\n document,\n selector,\n (capture) => {\n if (!established) {\n pendingCaptures.push(capture);\n return;\n }\n send(\"combined-update\", { watcherId, capture });\n },\n {\n debounceDelay,\n maxWait,\n fiberSelector,\n fiberTags,\n serialize: options.serialize,\n hideFiberProp: options.hideFiberProp,\n },\n );\n legacyWatchers.set(watcherId, watcher);\n send(\"watcher-started\", {\n watcherId,\n ...(requestId ? { requestId } : {}),\n });\n established = true;\n for (const capture of pendingCaptures) {\n send(\"combined-update\", { watcherId, capture });\n }\n } catch (error) {\n send(\"error\", {\n ...(requestId ? { requestId } : {}),\n error: error instanceof Error ? error.message : String(error),\n });\n }\n break;\n }\n\n case \"stop-watcher\": {\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n if (!watcherId) break;\n const watcher = legacyWatchers.get(watcherId);\n if (!watcher) break;\n watcher.stop();\n legacyWatchers.delete(watcherId);\n send(\"watcher-stopped\", { watcherId });\n break;\n }\n\n case \"set-watcher-paused\": {\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n if (!watcherId) break;\n legacyWatchers.get(watcherId)?.setPaused(payload.paused === true);\n break;\n }\n\n case \"capture\": {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n if (!requestId) break;\n const selector =\n typeof payload.selector === \"string\" ? payload.selector : undefined;\n const fiberSelector =\n typeof payload.fiberSelector === \"string\"\n ? payload.fiberSelector\n : undefined;\n const fiberTags = Array.isArray(payload.fiberTags)\n ? (payload.fiberTags as FiberTagValue[])\n : undefined;\n\n try {\n let capture: CombinedCapture<T> | null = null;\n const watcher = watchCombinedSelector<T>(\n document,\n selector,\n (nextCapture) => {\n capture ??= nextCapture;\n },\n {\n fiberSelector,\n fiberTags,\n serialize: options.serialize,\n hideFiberProp: options.hideFiberProp,\n },\n );\n watcher.stop();\n send(\"capture-response\", { requestId, capture });\n } catch (error) {\n send(\"capture-response\", {\n requestId,\n capture: null,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n break;\n }\n }\n };\n\n const removeListener = bridge.onCommand(handleCommand);\n send(\"source-ready\", {});\n\n return () => {\n removeListener();\n projectionSource.stop();\n for (const watcher of legacyWatchers.values()) watcher.stop();\n legacyWatchers.clear();\n delete (window as any)\n .__IFRAME_PROJECTION_COMBINED_WEBVIEW_INTERFACE_ACTIVE__;\n };\n}\n\nlet nextLegacyPageWatcherRequestId = 1;\nlet nextLegacyPageCaptureRequestId = 1;\n\nfunction createPageLegacyCombinedChannel(\n page: PageMessageHandle,\n): LegacyCombinedChannel {\n return {\n readinessTimeoutMessage:\n \"Timeout waiting for combined source - did you call startCombinedSourceWebviewInterface()?\",\n nextWatcherRequestId: () =>\n `combined-page-watch-${nextLegacyPageWatcherRequestId++}`,\n nextCaptureRequestId: () =>\n `combined-capture-${nextLegacyPageCaptureRequestId++}`,\n send(command) {\n page.send(\"combined-projection:command\", command);\n },\n listen(listener) {\n return page.on(\"combined-projection:update\", (message) => {\n const normalized = normalizeLegacyCombinedChannelEvent(message);\n if (normalized) listener(normalized);\n });\n },\n };\n}\n\n/**\n * Watch a frame-pool page through the pre-ProjectionBatch complete-capture\n * protocol.\n *\n * @deprecated Use {@link watchProjectionBatchesPage}. This adapter is opt-in\n * and does not participate in the Canvas projection stream.\n */\nexport function watchCombinedPage(\n page: PageMessageHandle,\n options: WatchCombinedPageOptions,\n): Promise<CombinedWatcher> {\n return watchLegacyCombinedChannel(\n createPageLegacyCombinedChannel(page),\n options,\n );\n}\n\n/**\n * Capture one complete compatibility envelope from a frame-pool page.\n *\n * @deprecated Prefer exact ProjectionBatch streaming for live projection.\n * This remains a cold query and creates no persistent destination model.\n */\nexport function captureCombinedPage(\n page: PageMessageHandle,\n options: CaptureCombinedPageOptions = {},\n): Promise<CombinedCapture | null> {\n return captureLegacyCombinedChannel(\n createPageLegacyCombinedChannel(page),\n options,\n );\n}\n\n/**\n * Subscribe to the exact document producer owned by a frame-pool page.\n * Transport stays structural: it forwards ProjectionBatch and never rebuilds\n * a CombinedCapture compatibility envelope in the Canvas renderer.\n */\nexport function watchProjectionBatchesPage(\n page: PageMessageHandle,\n options: WatchProjectionBatchesPageOptions,\n): Promise<ProjectionBatchWatcher> {\n return watchProjectionChannel(createPageProjectionChannel(page), options);\n}\n\nlet nextProjectionPageWatcherRequestId = 1;\n\nfunction createPageProjectionChannel(\n page: PageMessageHandle,\n): ProjectionChannel {\n return {\n readinessTimeoutMessage:\n \"Timeout waiting for combined source - did you call startCombinedSourceWebviewInterface()?\",\n nextWatcherRequestId: () =>\n `projection-page-watch-${nextProjectionPageWatcherRequestId++}`,\n send(command) {\n page.send(\"combined-projection:command\", command);\n },\n listen(listener) {\n return page.on(\"combined-projection:update\", (message) => {\n const normalized = normalizeProjectionChannelEvent(message);\n if (normalized) listener(normalized);\n });\n },\n };\n}\n\nfunction combinedSetupAbortError(): Error {\n const error = new Error(\"Combined watcher setup aborted\");\n error.name = \"AbortError\";\n return error;\n}\n","/**\n * The demand vocabulary: what the host wants from one canvas, and why a\n * canvas cannot be mirrored.\n *\n * Its own leaf module because every side of the lane speaks it — the\n * planner, the source, the wire, the sampler — and none of them should\n * have to import another's module for the words.\n */\n\n/**\n * Frames sent but not yet acknowledged, per canvas, plus at most one read\n * in flight. Bounds transferred GPU memory when the destination stalls;\n * the source does not read again until a credit comes back, and the canvas\n * itself buffers the latest state.\n */\nexport const DEFAULT_CANVAS_FRAME_MAX_IN_FLIGHT = 2;\n\n/**\n * The lane is \"active\" while an enabled canvas was drawn on within this\n * window. Activity is what lets the host raise the source compositor rate\n * only while something is actually animating.\n */\nexport const DEFAULT_CANVAS_ACTIVITY_WINDOW_MS = 2_000;\n\n/**\n * What the host wants from one canvas. A complete replacement per update:\n * the whole map is sent every time, and a canvas absent from the map is\n * disabled.\n */\nexport interface CanvasFrameDemand {\n /** False: no sampling, no baseline, no compositor activity from this canvas. */\n readonly enabled: boolean;\n /** Requested output bitmap size (≤ source; the destination scales it back up). */\n readonly width: number;\n readonly height: number;\n readonly maxFps: number;\n}\n\n/** The one canonical \"not wanted\" value; every disabled entry compares equal. */\nexport const DISABLED_CANVAS_FRAME_DEMAND: CanvasFrameDemand = Object.freeze({\n enabled: false,\n width: 0,\n height: 0,\n maxFps: 0,\n});\n\n/**\n * Why a canvas cannot be mirrored; the destination must not present its\n * last frame as live. `tainted` and `unsupported` last until the element is\n * replaced; `unreadable` is retried on the canvas's next draw.\n */\nexport type CanvasFrameUnavailableReason =\n | \"tainted\"\n | \"unreadable\"\n | \"unsupported\";\n","/**\n * Pure demand planning: from where the mirrored canvases sit on screen,\n * decide which ones want pixels, at what size, and how often.\n *\n * No DOM here. The caller supplies the presentation viewport, the world →\n * screen transform, one storyboard's world origin, the device pixel ratio,\n * and each mirrored canvas's local rect (CSS px inside the projection\n * document, which equal world units) plus its authored source size.\n *\n * Rules:\n * - Enabled iff the presentation is visible, the element box and source\n * are both non-empty, and the canvas's screen rect, grown by `margin`,\n * intersects the viewport. A canvas with any part on screen streams.\n * - ALWAYS the complete rectangle: the bitmap covers the whole canvas at\n * the density its full displayed size needs, never a crop of the visible\n * part. Width/height = min(source, ceil(box × zoom × dpr) rounded up to\n * `sizeStep`). Never upscaled above the source. The aspect follows the\n * element box, so CSS stretching is honored by construction.\n * - Rate: `lowFps` when the displayed physical area is at most\n * `lowFpsArea`, else `maxFps`. A thumbnail does not need 30 fps.\n *\n * Two hysteresis knobs keep the demand map stable under pan and zoom:\n * - `MARGIN` (CSS px) grows every screen rect before the intersection\n * test, so a canvas hovering at the viewport edge does not flap between\n * enabled and disabled on every wheel tick.\n * - `SIZE_STEP` rounds the requested size up to a multiple, so a small\n * zoom change does not reallocate bitmaps at a new size on every frame.\n *\n * The numbers are the plan's, not the caller's: a second set of knobs would\n * be a second demand policy, and the host already decides what it wants\n * through the geometry it hands over.\n */\n\nimport { type CanvasFrameDemand, DISABLED_CANVAS_FRAME_DEMAND } from \"./demand\";\n\n/** Edge-flap hysteresis, CSS px. */\nconst MARGIN = 48;\n/** Allocation-churn hysteresis, output px. */\nconst SIZE_STEP = 32;\n/** Rate asked of a canvas whose displayed area is above `LOW_FPS_AREA`. */\nconst MAX_FPS = 30;\nconst LOW_FPS = 15;\n/** Physical px² at or below which `LOW_FPS` applies. */\nconst LOW_FPS_AREA = 96 * 96;\n/**\n * Largest canvas edge the wire accepts, in either direction. Chromium's\n * per-edge canvas limit is 32 767 px (its area limit, 16 384², is a\n * separate matter: a 20 000 × 100 canvas is legal), so a plan past this\n * edge names a bitmap no destination could hold.\n */\nconst MAX_EDGE = 32_767;\n\n/** screen = world × zoom + (x, y) */\nexport interface CanvasFrameView {\n readonly x: number;\n readonly y: number;\n readonly zoom: number;\n}\n\nexport interface CanvasFrameCanvasGeometry {\n readonly targetId: string;\n /** The element box inside the projection document, in CSS px (= world units). */\n readonly localRect: {\n readonly left: number;\n readonly top: number;\n readonly width: number;\n readonly height: number;\n };\n /** Authored `canvas.width/height`. */\n readonly sourceWidth: number;\n readonly sourceHeight: number;\n}\n\nexport interface CanvasFrameDemandPlanInput {\n readonly viewport: { readonly width: number; readonly height: number };\n readonly view: CanvasFrameView;\n /** The storyboard's world origin; local rects are relative to it. */\n readonly origin: { readonly x: number; readonly y: number };\n readonly devicePixelRatio: number;\n readonly presentationVisible: boolean;\n readonly canvases: readonly CanvasFrameCanvasGeometry[];\n}\n\nfunction roundUpToStep(value: number): number {\n return Math.ceil(Math.ceil(value) / SIZE_STEP) * SIZE_STEP;\n}\n\nexport function planCanvasFrameDemand(\n input: CanvasFrameDemandPlanInput,\n): Record<string, CanvasFrameDemand> {\n const { zoom } = input.view;\n const dpr = input.devicePixelRatio;\n\n const plan: Record<string, CanvasFrameDemand> = {};\n for (const canvas of input.canvases) {\n const { localRect } = canvas;\n const hasArea =\n localRect.width > 0 &&\n localRect.height > 0 &&\n canvas.sourceWidth > 0 &&\n canvas.sourceHeight > 0;\n // A NaN zoom or ratio (a store read before layout) would plan a NaN\n // size, which the wire guard would refuse; it is a disabled canvas.\n const scaleOk =\n Number.isFinite(zoom) && zoom > 0 && Number.isFinite(dpr) && dpr > 0;\n if (!input.presentationVisible || !hasArea || !scaleOk) {\n plan[canvas.targetId] = DISABLED_CANVAS_FRAME_DEMAND;\n continue;\n }\n\n const screenLeft = (input.origin.x + localRect.left) * zoom + input.view.x;\n const screenTop = (input.origin.y + localRect.top) * zoom + input.view.y;\n const screenWidth = localRect.width * zoom;\n const screenHeight = localRect.height * zoom;\n const onScreen =\n screenLeft + screenWidth + MARGIN > 0 &&\n screenTop + screenHeight + MARGIN > 0 &&\n screenLeft - MARGIN < input.viewport.width &&\n screenTop - MARGIN < input.viewport.height;\n if (!onScreen) {\n plan[canvas.targetId] = DISABLED_CANVAS_FRAME_DEMAND;\n continue;\n }\n\n const physicalWidth = screenWidth * dpr;\n const physicalHeight = screenHeight * dpr;\n // Capped at the source and at the wire's edge: a source wider than the\n // edge is legal for the page but not for the lane, and a plan the guard\n // refuses would be worse than a smaller frame.\n plan[canvas.targetId] = {\n enabled: true,\n width: Math.min(\n canvas.sourceWidth,\n MAX_EDGE,\n roundUpToStep(physicalWidth),\n ),\n height: Math.min(\n canvas.sourceHeight,\n MAX_EDGE,\n roundUpToStep(physicalHeight),\n ),\n maxFps:\n physicalWidth * physicalHeight <= LOW_FPS_AREA ? LOW_FPS : MAX_FPS,\n };\n }\n return plan;\n}\n","/**\n * Draw tracking in the source realm: know which canvases were drawn on since\n * they were last sampled, so a static canvas is never sampled twice.\n *\n * The tracker wraps the drawing methods of every canvas context type and\n * marks the context's canvas dirty AFTER the native call returns. A canvas\n * carries a monotonic revision that bumps once per clean→dirty transition;\n * a sampler records the revision when it starts a read (`captureStarted`,\n * which also clears the flag) and compares later. Draws that land while a\n * read is in flight bump the revision again, so nothing is lost.\n *\n * What counts as a draw (measured in DRAW-TRACKING.md, 2026-09-06):\n * - 2D: the rasterizing calls (fillRect, drawImage, putImageData, …) and\n * `reset`. Setting fillStyle or a transform is state, not a draw.\n * - WebGL/WebGL2: clear, the draw* family, blitFramebuffer, clearBuffer*,\n * and the draw methods of extension objects (instancing, multi-draw).\n * - bitmaprenderer: transferFromImageBitmap.\n * - Width/height setters and attribute writes (they wipe the backing store).\n * - WebGPU: every canvas configured on a queue is marked on that queue's\n * submit/writeTexture/copyExternalImageToTexture. Command buffers name\n * their targets only inside the GPU process, so this is conservative:\n * a static canvas sharing a queue with an animating one is re-sampled.\n *\n * What it cannot see: a canvas that called `transferControlToOffscreen` is\n * drawn from a worker realm where these hooks do not exist; such a canvas is\n * reported untracked and the lane watches its paints instead.\n *\n * Precondition: the patches must land on the prototypes the PAGE uses,\n * before any page script runs. A context-isolated preload patches its own\n * world's prototypes and sees nothing (`patchedCount` is still positive\n * there, so the caller must check isolation itself); page code that\n * captured `CanvasRenderingContext2D.prototype.fillRect` earlier calls the\n * original and bypasses the wrapper, which nothing here can detect.\n *\n * Cost: one extra call frame per draw call plus an O(1) flag check once the\n * canvas is dirty. Measured at ~8–9 % relative source CPU in a 1.44 M\n * draw-calls/s fixture with no delivered-FPS loss.\n *\n * Several trackers may stack on the same prototypes (a test harness, a\n * second install). Each wrapper calls the function it replaced through a\n * link it owns, so disposing any tracker unlinks its wrapper from the chain\n * wherever it sits, and the last one standing restores the original.\n */\n\nexport interface CanvasDirtyTracker {\n /** Monotonic per canvas; bumps once per clean→dirty transition. */\n revision(canvas: HTMLCanvasElement): number;\n /**\n * Fires once per clean→dirty transition (coalesced), never per draw\n * call; also fires when the canvas loses tracking\n * (`transferControlToOffscreen`), whether or not it was already dirty.\n */\n subscribe(canvas: HTMLCanvasElement, listener: () => void): () => void;\n /**\n * Mark a capture start: clears the dirty flag so later draws bump the\n * revision again. Returns the revision captured.\n */\n captureStarted(canvas: HTMLCanvasElement): number;\n /** False once the canvas transferred control to a worker (document hooks cannot see its draws). */\n isTracked(canvas: HTMLCanvasElement): boolean;\n}\n\nexport interface InstalledDrawTracker extends CanvasDirtyTracker {\n /** Methods and setters this install wrapped; 0 means the scope has no canvas API at all. */\n readonly patchedCount: number;\n dispose(): void;\n}\n\ninterface CanvasState {\n revision: number;\n dirty: boolean;\n /** Created on first subscribe; most canvases never get one. */\n listeners: Set<() => void> | null;\n}\n\n/**\n * `WeakRef` is ES2021 and this module compiles against the ES2020 lib, so\n * the global is named here; every runtime the tracker patches has had it\n * since Chromium 84.\n */\ninterface WeakReference<T extends object> {\n deref(): T | undefined;\n}\nconst WeakReferenceCtor = (\n globalThis as unknown as {\n WeakRef: new <T extends object>(target: T) => WeakReference<T>;\n }\n).WeakRef;\n\ninterface GpuContextState {\n readonly canvas: object;\n queue: object | null;\n reference: WeakReference<object> | null;\n}\n\ntype AnyFunction = (this: unknown, ...args: unknown[]) => unknown;\ntype Prototype = Record<string, unknown>;\n\n/**\n * The function a wrapper replaced, kept as a property so any tracker can\n * relink around any other's wrapper. Shared across installs by name.\n */\nconst INNER = Symbol.for(\"iframe-projection.canvas-frames.draw-tracker.inner\");\ntype Linked = AnyFunction & { [INNER]?: AnyFunction };\n\nconst METHODS_2D = [\n \"clearRect\",\n \"fillRect\",\n \"strokeRect\",\n \"fill\",\n \"stroke\",\n \"fillText\",\n \"strokeText\",\n \"drawImage\",\n \"putImageData\",\n \"reset\",\n \"drawFocusIfNeeded\",\n] as const;\n\nconst METHODS_GL = [\n \"clear\",\n \"drawArrays\",\n \"drawElements\",\n \"drawArraysInstanced\",\n \"drawElementsInstanced\",\n \"drawRangeElements\",\n \"blitFramebuffer\",\n \"clearBufferfv\",\n \"clearBufferiv\",\n \"clearBufferuiv\",\n \"clearBufferfi\",\n] as const;\n\n/** Extension methods that rasterize; everything else on an extension is state. */\nconst GL_EXTENSION_DRAW_METHOD = /^(multiDraw|drawArrays|drawElements)/;\n\nconst GPU_QUEUE_WRITE_METHODS = [\n \"submit\",\n \"writeTexture\",\n \"copyExternalImageToTexture\",\n] as const;\n\nfunction prototypeOf(scope: object, constructorName: string): Prototype | null {\n const ctor = (scope as Record<string, unknown>)[constructorName];\n if (typeof ctor !== \"function\") return null;\n const prototype = (ctor as { prototype?: unknown }).prototype;\n return typeof prototype === \"object\" && prototype !== null\n ? (prototype as Prototype)\n : null;\n}\n\nfunction canvasOf(context: unknown): object | null {\n const canvas = (context as { canvas?: unknown } | null)?.canvas;\n return typeof canvas === \"object\" && canvas !== null ? canvas : null;\n}\n\n/**\n * Take `wrapper` out of the chain that currently sits at `current`: the\n * function whose inner link is `wrapper` gets `wrapper`'s own inner\n * instead. Returns the function that should now sit at the head (the same\n * `current`, or `wrapper`'s inner when `wrapper` was the head).\n */\nfunction unlink(current: unknown, wrapper: Linked): unknown {\n if (current === wrapper) return wrapper[INNER];\n let outer = current as Linked | undefined;\n while (typeof outer === \"function\" && outer[INNER] !== wrapper) {\n outer = outer[INNER];\n }\n if (typeof outer === \"function\") outer[INNER] = wrapper[INNER];\n return current;\n}\n\nexport function installDrawTracker(\n scope: typeof globalThis = globalThis,\n): InstalledDrawTracker {\n const states = new WeakMap<object, CanvasState>();\n const untracked = new WeakSet<object>();\n const restores: (() => void)[] = [];\n /** Owner → names already wrapped by THIS install, so a shared prototype is wrapped once per install. */\n const wrapped = new WeakMap<object, Set<string>>();\n let patchedCount = 0;\n\n const stateOf = (canvas: object): CanvasState => {\n let state = states.get(canvas);\n if (!state) {\n state = { revision: 0, dirty: false, listeners: null };\n states.set(canvas, state);\n }\n return state;\n };\n\n const notify = (state: CanvasState): void => {\n if (!state.listeners) return;\n for (const listener of state.listeners) listener();\n };\n\n const mark = (canvas: object | null): void => {\n if (!canvas) return;\n const state = stateOf(canvas);\n // The common case in a render loop: already dirty, nothing to do.\n if (state.dirty) return;\n state.dirty = true;\n state.revision += 1;\n notify(state);\n };\n\n const alreadyWrapped = (owner: object, name: string): boolean => {\n const names = wrapped.get(owner) ?? new Set<string>();\n if (names.has(name)) return true;\n names.add(name);\n wrapped.set(owner, names);\n return false;\n };\n\n /**\n * Replace the `value` (a method) or the `set` (a setter) of `owner[name]`\n * with a wrapper that runs `after` once the call it links to returned\n * normally. `this`, arguments, return value and exceptions pass through\n * untouched; an exception skips `after` (nothing was drawn).\n */\n const wrap = (\n owner: object | null,\n name: string,\n key: \"value\" | \"set\",\n after: (self: unknown, args: unknown[], result: unknown) => void,\n ): void => {\n if (!owner || alreadyWrapped(owner, name)) return;\n const descriptor = Object.getOwnPropertyDescriptor(owner, name);\n const original = descriptor?.[key];\n if (typeof original !== \"function\") return;\n const wrapper: Linked = function (this: unknown, ...args: unknown[]) {\n const result = Reflect.apply(\n wrapper[INNER] ?? (original as AnyFunction),\n this,\n args,\n );\n after(this, args, result);\n return result;\n };\n wrapper[INNER] = original as AnyFunction;\n Object.defineProperty(owner, name, { ...descriptor, [key]: wrapper });\n patchedCount += 1;\n restores.push(() => {\n const current = Object.getOwnPropertyDescriptor(owner, name)?.[key];\n const head = unlink(current, wrapper);\n if (head !== current) {\n Object.defineProperty(owner, name, { ...descriptor, [key]: head });\n }\n });\n };\n const markContextCanvas = (context: unknown) => mark(canvasOf(context));\n /** A size write wipes the backing store, whatever value it carries. */\n const markSelf = (self: unknown) => mark(self as object);\n\n // ── 2D and bitmaprenderer ─────────────────────────────────────────────\n for (const type of [\n \"CanvasRenderingContext2D\",\n \"OffscreenCanvasRenderingContext2D\",\n ]) {\n const prototype = prototypeOf(scope, type);\n for (const name of METHODS_2D) {\n wrap(prototype, name, \"value\", markContextCanvas);\n }\n }\n wrap(\n prototypeOf(scope, \"ImageBitmapRenderingContext\"),\n \"transferFromImageBitmap\",\n \"value\",\n markContextCanvas,\n );\n\n // ── WebGL, including extension objects ────────────────────────────────\n // Extension objects share a prototype per extension type, so the wrapper\n // lives on that prototype and finds its canvas through the extension\n // instance (`this`), recorded when getExtension handed it out.\n const extensionCanvas = new WeakMap<object, object>();\n const markExtensionCanvas = (extension: unknown) => {\n if (typeof extension !== \"object\" || extension === null) return;\n mark(extensionCanvas.get(extension) ?? null);\n };\n for (const type of [\"WebGLRenderingContext\", \"WebGL2RenderingContext\"]) {\n const prototype = prototypeOf(scope, type);\n for (const name of METHODS_GL) {\n wrap(prototype, name, \"value\", markContextCanvas);\n }\n wrap(prototype, \"getExtension\", \"value\", (context, _args, extension) => {\n if (typeof extension !== \"object\" || extension === null) return;\n const canvas = canvasOf(context);\n if (canvas) extensionCanvas.set(extension, canvas);\n for (const owner of [extension, Object.getPrototypeOf(extension)]) {\n if (!owner) continue;\n for (const name of Object.getOwnPropertyNames(owner)) {\n if (GL_EXTENSION_DRAW_METHOD.test(name)) {\n wrap(owner, name, \"value\", markExtensionCanvas);\n }\n }\n }\n });\n }\n\n // ── Backing-store changes that are not draw calls ─────────────────────\n const gpuContexts = new WeakMap<object, GpuContextState>();\n for (const type of [\"HTMLCanvasElement\", \"OffscreenCanvas\"]) {\n const prototype = prototypeOf(scope, type);\n wrap(prototype, \"width\", \"set\", markSelf);\n wrap(prototype, \"height\", \"set\", markSelf);\n wrap(prototype, \"getContext\", \"value\", (canvas, args, context) => {\n if (args[0] !== \"webgpu\" || typeof context !== \"object\" || !context) {\n return;\n }\n // `getContext` returns the same context on every call; resetting its\n // state here would orphan the queue subscription a previous\n // `configure` recorded (one leaked WeakRef per lookup).\n if (gpuContexts.has(context)) return;\n gpuContexts.set(context, {\n canvas: canvas as object,\n queue: null,\n reference: null,\n });\n });\n }\n wrap(\n prototypeOf(scope, \"HTMLCanvasElement\"),\n \"transferControlToOffscreen\",\n \"value\",\n (canvas) => {\n untracked.add(canvas as object);\n // Losing tracking is its own event, not a dirty transition: the\n // subscriber must hear it even when the canvas is already dirty (a\n // `canvas.width = canvas.width` right before the transfer), or it\n // never switches to watching the worker's paints.\n const state = stateOf(canvas as object);\n if (state.dirty) notify(state);\n else mark(canvas as object);\n },\n );\n\n const observer =\n typeof scope.MutationObserver === \"function\" && scope.document\n ? new scope.MutationObserver((records) => {\n for (const record of records) {\n const target = record.target as Element;\n if (target.localName === \"canvas\") mark(target);\n }\n })\n : null;\n observer?.observe(scope.document, {\n subtree: true,\n attributes: true,\n attributeFilter: [\"width\", \"height\"],\n });\n\n // ── WebGPU: queue submissions dirty every canvas on that queue ────────\n const queueCanvases = new WeakMap<object, Set<WeakReference<object>>>();\n\n const detachFromQueue = (state: GpuContextState) => {\n if (state.queue && state.reference) {\n queueCanvases.get(state.queue)?.delete(state.reference);\n }\n state.queue = null;\n state.reference = null;\n };\n const gpuContextPrototype = prototypeOf(scope, \"GPUCanvasContext\");\n wrap(gpuContextPrototype, \"configure\", \"value\", (context, args) => {\n const state = gpuContexts.get(context as object);\n if (!state) return;\n detachFromQueue(state);\n const queue = (args[0] as { device?: { queue?: object } } | undefined)\n ?.device?.queue;\n if (queue) {\n const canvases = queueCanvases.get(queue) ?? new Set();\n queueCanvases.set(queue, canvases);\n state.queue = queue;\n state.reference = new WeakReferenceCtor(state.canvas);\n canvases.add(state.reference);\n }\n mark(state.canvas);\n });\n wrap(gpuContextPrototype, \"unconfigure\", \"value\", (context) => {\n const state = gpuContexts.get(context as object);\n if (!state) return;\n detachFromQueue(state);\n mark(state.canvas);\n });\n const markQueueCanvases = (queue: unknown) => {\n const canvases = queueCanvases.get(queue as object);\n if (!canvases) return;\n for (const reference of canvases) {\n const canvas = reference.deref();\n if (canvas) mark(canvas);\n else canvases.delete(reference);\n }\n };\n for (const name of GPU_QUEUE_WRITE_METHODS) {\n wrap(prototypeOf(scope, \"GPUQueue\"), name, \"value\", markQueueCanvases);\n }\n\n return {\n patchedCount,\n revision: (canvas) => states.get(canvas)?.revision ?? 0,\n subscribe(canvas, listener) {\n const state = stateOf(canvas);\n state.listeners ??= new Set();\n state.listeners.add(listener);\n return () => {\n state.listeners?.delete(listener);\n };\n },\n captureStarted(canvas) {\n const state = stateOf(canvas);\n state.dirty = false;\n return state.revision;\n },\n isTracked: (canvas) => !untracked.has(canvas),\n dispose() {\n observer?.disconnect();\n for (const restore of restores) restore();\n restores.length = 0;\n },\n };\n}\n","/**\n * Handing a `MessagePort` to another window.\n *\n * A `postMessage` with a transfer list is the only way to move a port into\n * a document you do not share a realm with, and every listener on that\n * window sees the message: the envelope names which port this is, and the\n * receiver accepts it only from the window it already trusts (its parent,\n * or itself for a preload relay). An envelope from anyone else is not\n * merely ignored — the port it carried is closed, or the sender's end\n * would stay open forever waiting for a lane that will never be served.\n */\n\nexport interface PortEnvelopeEvent {\n readonly source: unknown;\n readonly data: unknown;\n readonly ports?: readonly MessagePort[];\n}\n\nexport interface PortEnvelopeTarget {\n postMessage(\n message: unknown,\n targetOrigin: string,\n transfer?: Transferable[],\n ): void;\n}\n\nexport interface PortEnvelope<TFields extends object> {\n readonly type: string;\n is(value: unknown): value is { readonly type: string } & TFields;\n /**\n * Our envelope from `trustedSource` with a port → `{ fields, port }`.\n * Our envelope from anyone else, or without a port → closes the port it\n * carried and returns null. Not our envelope → null, untouched.\n */\n accept(\n event: PortEnvelopeEvent,\n trustedSource: unknown,\n ): { fields: TFields; port: MessagePort } | null;\n post(target: PortEnvelopeTarget, fields: TFields, port: MessagePort): void;\n}\n\nexport function definePortEnvelope<\n TFields extends object = Record<never, never>,\n>(type: string): PortEnvelope<TFields> {\n // The fields are trusted structure written by our own code on the other\n // side; the type is what tells us it IS our code.\n const is = (value: unknown): value is { readonly type: string } & TFields =>\n typeof value === \"object\" &&\n value !== null &&\n (value as { type?: unknown }).type === type;\n\n return {\n type,\n is,\n accept(event, trustedSource) {\n if (!is(event.data)) return null;\n const port = event.ports?.[0] ?? null;\n if (event.source !== trustedSource || !port) {\n port?.close();\n return null;\n }\n const fields: Record<string, unknown> = {\n ...(event.data as Record<string, unknown>),\n };\n delete fields.type;\n return { fields: fields as unknown as TFields, port };\n },\n post(target, fields, port) {\n target.postMessage({ type, ...fields }, \"*\", [port]);\n },\n };\n}\n\n/**\n * Same-renderer handoff of a canvas lane port to a child browsing context\n * (an in-DOM interact `<iframe>`): the host keeps one end of a\n * `MessageChannel` and posts the other to the child's window, which serves\n * the lane on it.\n */\nexport const CANVAS_FRAME_LANE_WINDOW_PORT = definePortEnvelope(\n \"canvas-frames:window-port\",\n);\n","/**\n * Discovery of `<canvas>` elements under one projection root.\n *\n * Reports each canvas exactly once on entry and once on exit, following\n * subtree insertions/removals through a MutationObserver. Only childList\n * mutations are observed; canvas resizes are visible on the frames\n * themselves (each frame carries its own dimensions). Stopping is not an\n * exit: the caller knows what it is holding, and whether those ids are\n * worth a removal notice is its call, not the registry's.\n */\n\nexport interface CanvasRegistryCallbacks {\n onAdded(canvas: HTMLCanvasElement): void;\n onRemoved(canvas: HTMLCanvasElement): void;\n}\n\nfunction isCanvas(node: Node): node is HTMLCanvasElement {\n return node.nodeType === 1 && (node as Element).localName === \"canvas\";\n}\n\nfunction collectCanvases(scope: Node, into: HTMLCanvasElement[]): void {\n if (scope.nodeType !== 1) return;\n if (isCanvas(scope)) into.push(scope);\n for (const canvas of (scope as Element).querySelectorAll(\"canvas\")) {\n into.push(canvas);\n }\n}\n\n/** Returns a disposer; stopping only disconnects, it reports no removals. */\nexport function watchCanvasElements(\n root: Element,\n callbacks: CanvasRegistryCallbacks,\n): () => void {\n const canvases = new Set<HTMLCanvasElement>();\n let stopped = false;\n\n const add = (canvas: HTMLCanvasElement) => {\n if (canvases.has(canvas) || !root.contains(canvas)) return;\n canvases.add(canvas);\n callbacks.onAdded(canvas);\n };\n const remove = (canvas: HTMLCanvasElement) => {\n if (!canvases.delete(canvas)) return;\n callbacks.onRemoved(canvas);\n };\n\n const handleMutations: MutationCallback = (records) => {\n if (stopped) return;\n const removedCandidates: HTMLCanvasElement[] = [];\n const addedCandidates: HTMLCanvasElement[] = [];\n for (const record of records) {\n for (const node of record.removedNodes) {\n collectCanvases(node, removedCandidates);\n }\n for (const node of record.addedNodes) {\n collectCanvases(node, addedCandidates);\n }\n }\n // A move (remove + add in one batch) must not flap; decide by the final\n // connected position, not by the order of records.\n for (const canvas of removedCandidates) {\n if (!root.contains(canvas)) remove(canvas);\n }\n for (const canvas of addedCandidates) add(canvas);\n };\n\n const observer = new MutationObserver(handleMutations);\n observer.observe(root, { childList: true, subtree: true });\n\n const initial: HTMLCanvasElement[] = [];\n collectCanvases(root, initial);\n for (const canvas of initial) add(canvas);\n\n return () => {\n if (stopped) return;\n stopped = true;\n observer.disconnect();\n };\n}\n","/**\n * The direct read: one `createImageBitmap` of the canvas, downsampled to\n * the demanded size in the same call. The canvas itself is the buffer while\n * the destination is busy, so no intermediate frames pile up. Why this and\n * not capture: see the `l-d10` lineage card in system.html.\n *\n * Reading a WebGL canvas after it composited needs `preserveDrawingBuffer`\n * (see `preserve-drawing-buffer.ts`); with the default attributes the read\n * comes back blank.\n */\n\nimport type { CanvasFrameUnavailableReason } from \"./demand\";\n\nexport interface CanvasSampleSize {\n readonly width: number;\n readonly height: number;\n}\n\n/** A canvas read at `size`; throws like `createImageBitmap` (see `classifyCanvasSampleError`). */\nexport type CanvasSampleReader = (\n canvas: HTMLCanvasElement,\n size: CanvasSampleSize,\n) => Promise<ImageBitmap | null>;\n\nexport function resizeOptionsFor(\n source: CanvasSampleSize,\n size: CanvasSampleSize,\n): ImageBitmapOptions {\n // Never upscale: a demand above the source (a stale plan after the page\n // shrank its canvas) reads the source as is.\n const width = Math.min(size.width, source.width);\n const height = Math.min(size.height, source.height);\n // Asking for the source size verbatim is a plain copy; the resize path is\n // only worth its filter when it actually shrinks.\n if (source.width === width && source.height === height) return {};\n return { resizeWidth: width, resizeHeight: height, resizeQuality: \"low\" };\n}\n\nexport const sampleCanvasDirect: CanvasSampleReader = (canvas, size) => {\n const scope = canvas.ownerDocument.defaultView ?? globalThis;\n return scope.createImageBitmap(canvas, resizeOptionsFor(canvas, size));\n};\n\n/**\n * A `SecurityError` means the canvas is tainted (cross-origin content was\n * drawn into it) and will stay unreadable until it is recreated; anything\n * else (a lost context, a transient allocation failure) may clear on the\n * next draw.\n */\nexport function classifyCanvasSampleError(\n error: unknown,\n): CanvasFrameUnavailableReason {\n const name = (error as { name?: unknown } | null)?.name;\n return name === \"SecurityError\" ? \"tainted\" : \"unreadable\";\n}\n","/**\n * Paint watching for canvases the draw tracker cannot see: a canvas that\n * transferred control to a worker is drawn from a realm where the\n * document's draw hooks do not exist, and a notification bridge from that\n * worker was measured reading stale pixels (DRAW-TRACKING.md). For such a\n * canvas `captureStream()` is the dirty signal: it yields one `VideoFrame`\n * per paint of the placeholder, read at its present point.\n *\n * This is a dirty source and a latest-frame holder, not a second pipeline.\n * The reader loop keeps only the newest frame (closing the previous one,\n * converting nothing) and tells the watcher the canvas painted; the\n * watcher's one loop then reads the held frame through `read()` after its\n * credit and rate gates, at the demanded size. Why not the primary path:\n * capture reads the full-size surface per paint, measured far slower than\n * a direct downsampling read (see the `l-d10` lineage card in\n * system.html).\n *\n * `requestFrame()` on a track whose canvas never repaints yields nothing,\n * so the first frame after enabling is a direct read of the placeholder\n * (the watcher's job, through `sampleCanvasDirect`).\n */\n\nimport {\n type CanvasSampleSize,\n classifyCanvasSampleError,\n resizeOptionsFor,\n} from \"./direct-sampler\";\nimport type { CanvasFrameUnavailableReason } from \"./demand\";\n\ntype TrackProcessorConstructor = new (init: {\n track: MediaStreamTrack;\n}) => { readonly readable: ReadableStream<VideoFrame> };\n\nexport interface CanvasPaintWatcherCallbacks {\n /** The canvas painted; the newest frame is held until `read`. */\n onPaint(): void;\n /**\n * The stream is over for good (the canvas is tainted, the track ended,\n * capture threw). No more paints will come. Fires from a later task,\n * never before the factory returned, so the caller always holds the\n * watcher it is about; the caller's `stop()` releases any held frame.\n */\n onEnded(reason: CanvasFrameUnavailableReason): void;\n}\n\nexport interface CanvasPaintWatcher {\n /**\n * Convert the held paint at `size` and release it; null when nothing is\n * held. Throws when the conversion fails (the frame is closed either\n * way): that paint is lost, the next one is not.\n */\n read(size: CanvasSampleSize): Promise<ImageBitmap | null>;\n stop(): void;\n}\n\n/** Null when this runtime cannot watch paints (no `MediaStreamTrackProcessor`). */\nexport type CanvasPaintWatcherFactory = (\n canvas: HTMLCanvasElement,\n callbacks: CanvasPaintWatcherCallbacks,\n) => CanvasPaintWatcher | null;\n\nexport const watchCanvasPaints: CanvasPaintWatcherFactory = (\n canvas,\n callbacks,\n) => {\n const scope = (canvas.ownerDocument.defaultView ??\n globalThis) as typeof globalThis;\n const Processor = (scope as { MediaStreamTrackProcessor?: unknown })\n .MediaStreamTrackProcessor as TrackProcessorConstructor | undefined;\n if (\n typeof Processor !== \"function\" ||\n typeof scope.createImageBitmap !== \"function\"\n ) {\n return null;\n }\n\n let stopped = false;\n let held: VideoFrame | null = null;\n let stream: MediaStream | null = null;\n let reader: ReadableStreamDefaultReader<VideoFrame> | null = null;\n\n const run = async () => {\n if (stopped) return;\n let track: MediaStreamTrack | undefined;\n try {\n // Throws SecurityError on a tainted canvas.\n stream = canvas.captureStream();\n track = stream.getVideoTracks()[0];\n if (!track) {\n callbacks.onEnded(\"unreadable\");\n return;\n }\n reader = new Processor({ track }).readable.getReader();\n while (!stopped) {\n const result = await reader.read();\n if (result.done) {\n if (!stopped) callbacks.onEnded(\"unreadable\");\n return;\n }\n if (stopped) {\n result.value.close();\n return;\n }\n // Only the newest paint matters: the canvas is a complete final\n // state, and the watcher reads it when credit and rate allow.\n held?.close();\n held = result.value;\n callbacks.onPaint();\n }\n } catch (error) {\n if (!stopped) callbacks.onEnded(classifyCanvasSampleError(error));\n } finally {\n track?.stop();\n }\n };\n // Off a microtask so a synchronous `captureStream()` throw reports\n // through `onEnded` after the caller holds this watcher, not before.\n void Promise.resolve().then(run);\n\n return {\n async read(size) {\n const frame = held;\n held = null;\n if (!frame) return null;\n try {\n // Resize at conversion: the full-size frame is closed right after,\n // so only the demanded pixels stay alive.\n const source = {\n width: frame.displayWidth,\n height: frame.displayHeight,\n };\n return await scope.createImageBitmap(\n frame,\n resizeOptionsFor(source, size),\n );\n } finally {\n frame.close();\n }\n },\n stop() {\n if (stopped) return;\n stopped = true;\n held?.close();\n held = null;\n void reader?.cancel().catch(() => {});\n for (const track of stream?.getTracks() ?? []) track.stop();\n },\n };\n};\n","/**\n * Source side of the canvas pixel lane: watch one projection root and hand\n * the emitter one frame per demanded, drawn-on canvas, as fast as the\n * demand's rate and the destination's credit allow.\n *\n * Three gates, all checked before any pixel is copied:\n * - Demand. The host says per canvas whether it wants pixels and at what\n * size and rate (`updateDemand`). A disabled canvas is never read, not\n * even for a baseline.\n * - Dirty. A canvas is read only when its revision moved since the last\n * read. A tracked canvas gets its revision from the draw tracker (see\n * `draw-tracker.ts`); an untracked one (worker-owned, or no tracker at\n * all) from its paint watcher (`capture-stream-sampler.ts`), which also\n * holds the newest paint for the read. Enabling and a demand size\n * change force the revision stale, so a static canvas is read exactly\n * once per enable.\n * - Credit. At most `maxInFlight` frames are unacknowledged per canvas.\n * While the destination is behind, nothing is read: the canvas (or\n * the held paint) is the buffer, and one read at the next credit\n * catches up.\n *\n * One pipeline, one loop. On any wake (a draw or paint notification, an\n * ack, a demand update, a discovery) every runnable canvas whose due time\n * has passed is read in a fresh TASK posted right then; a canvas due later\n * waits on one timer at the earliest due time and is read when it fires.\n * Reads never run inside the rendering step: a draw notification fires\n * inside the page's animation-frame callback, and a read there, or on the\n * microtask after that callback, copies a frame another callback of the\n * same tick has not finished (measured as torn frames when two rAF loops\n * share a canvas). A posted task runs after every callback of the tick.\n * Nothing spins while nothing is runnable. At most ONE read is in flight\n * per canvas, which is what makes a baseline safe: it is an ordinary read\n * with the revision forced stale, so a slow baseline can never land on top\n * of a newer live frame.\n *\n * Rate: the next due time advances one interval from the SCHEDULED one,\n * so a late or early wake never shifts the phase and the average never\n * exceeds `maxFps`; it re-anchors to now only when more than one interval\n * behind (a stall for credit).\n *\n * Activity is what the PAGE does: the lane is active while an enabled\n * canvas went dirty (a draw, or a paint of an untracked canvas) within\n * `activityWindowMs`. It is raised when the notification arrives, never\n * from an emission, so a destination that withholds acks does not hide an\n * animating page, and a forced read of a static chart raises nothing. The\n * host uses the transitions to hold the source compositor at a live rate\n * only while something is animating.\n */\n\nimport { ensureProjectionDomId } from \"../html/watch-dom\";\nimport { watchCanvasElements } from \"./canvas-registry\";\nimport {\n type CanvasPaintWatcher,\n type CanvasPaintWatcherFactory,\n watchCanvasPaints,\n} from \"./capture-stream-sampler\";\nimport {\n type CanvasFrameDemand,\n type CanvasFrameUnavailableReason,\n DEFAULT_CANVAS_ACTIVITY_WINDOW_MS,\n DEFAULT_CANVAS_FRAME_MAX_IN_FLIGHT,\n DISABLED_CANVAS_FRAME_DEMAND,\n} from \"./demand\";\nimport {\n type CanvasSampleReader,\n type CanvasSampleSize,\n classifyCanvasSampleError,\n sampleCanvasDirect,\n} from \"./direct-sampler\";\nimport type { CanvasDirtyTracker } from \"./draw-tracker\";\n\nexport interface CanvasFrameEmission {\n readonly targetId: string;\n readonly frameId: number;\n readonly bitmap: ImageBitmap;\n /** Authored `canvas.width/height` when the read started. */\n readonly sourceWidth: number;\n readonly sourceHeight: number;\n}\n\nexport interface CanvasFrameEmitter {\n /**\n * Ownership of `bitmap` passes to the emitter on true (transfer). On\n * false the watcher closes the bitmap and releases the frame's credit.\n */\n frame(emission: CanvasFrameEmission): boolean;\n /**\n * The source has no pixels for this id any more: the canvas left the\n * document, became empty (width or height 0), or — with a `reason` —\n * cannot be read at all. The destination drops and clears whatever it\n * retained; a later frame repopulates it.\n */\n removed(targetId: string, reason?: CanvasFrameUnavailableReason): void;\n activity(active: boolean): void;\n}\n\nexport interface CanvasFrameScheduler {\n now(): number;\n setTimeout(callback: () => void, ms: number): unknown;\n clearTimeout(handle: unknown): void;\n /**\n * Run `callback` in a fresh task, after the current one and after every\n * animation-frame callback of the current tick. A MessageChannel hop,\n * not a timer: timers are clamped and reordered, a port message is not.\n */\n post(callback: () => void): void;\n}\n\nexport interface WatchCanvasFramesOptions {\n /** Without a tracker every canvas is untracked and watched through captureStream. */\n tracker?: CanvasDirtyTracker;\n /** Read a canvas at a size. Default: `createImageBitmap` with resize. */\n sampleCanvas?: CanvasSampleReader;\n /** Paint watcher for untracked canvases. Default: `captureStream`. */\n watchPaints?: CanvasPaintWatcherFactory;\n maxInFlight?: number;\n activityWindowMs?: number;\n /** Defaults to the root window's clock and timers plus a MessageChannel. */\n scheduler?: CanvasFrameScheduler;\n}\n\nexport interface CanvasFrameWatcherStopOptions {\n /**\n * Report every watched canvas as removed. Use when the root itself went\n * away (its ids will never be addressed again) but not when the lane is\n * released and the destination should keep its last pixels.\n */\n notifyRemovals?: boolean;\n}\n\nexport interface CanvasFrameWatcher {\n /** The destination consumed a frame; releases its credit. Unknown ids are ignored. */\n ack(targetId: string, frameId: number): void;\n /** Complete replacement: a watched canvas absent from `entries` is disabled. */\n updateDemand(entries: Record<string, CanvasFrameDemand>): void;\n stop(options?: CanvasFrameWatcherStopOptions): void;\n}\n\ninterface WatchedCanvas {\n readonly canvas: HTMLCanvasElement;\n readonly targetId: string;\n demand: CanvasFrameDemand;\n /** Revision at the last read start; -1 forces the next read. */\n sampledRevision: number;\n /** One read in flight at most. */\n pending: boolean;\n /** Invalidates a read that spans a disabled -> enabled demand cycle. */\n demandGeneration: number;\n nextDueAt: number;\n nextFrameId: number;\n /** Frame ids sent and not yet acked; credit = fewer than maxInFlight. */\n readonly outstanding: Set<number>;\n /** The tracker saw this canvas's draws at the last notification. */\n tracked: boolean;\n /** Paint watcher of an untracked canvas; null while tracked or disabled. */\n paints: CanvasPaintWatcher | null;\n /** The untracked canvas's revision: one bump per paint. */\n paintRevision: number;\n /** Paint watchers restarted since the last enable (at most one). */\n paintRestarts: number;\n paintRestartTimer: unknown;\n /** The paint stream ended twice: no more watchers until the next demand toggle. */\n paintsExhausted: boolean;\n unsubscribe: (() => void) | null;\n /** Tainted or unsupported: never read again until the element is re-added. */\n terminal: boolean;\n unavailableReported: boolean;\n removed: boolean;\n /** Tracker revision when the activity expiry last re-armed its flag (see `armActivityExpiry`). */\n armedRevision: number;\n}\n\n/**\n * The lane's own clock and timers, plus a MessageChannel for `post`. The\n * caller closes what it creates: the channel keeps `view` alive otherwise.\n */\nexport function createDefaultScheduler(\n view: typeof globalThis = globalThis,\n): CanvasFrameScheduler & { close(): void } {\n const Channel = view.MessageChannel ?? MessageChannel;\n const channel = new Channel();\n const queued: (() => void)[] = [];\n channel.port1.onmessage = () => queued.shift()?.();\n return {\n now: () => performance.now(),\n setTimeout: (callback, ms) => view.setTimeout(callback, ms),\n clearTimeout: (handle) =>\n view.clearTimeout(handle as ReturnType<typeof setTimeout>),\n post(callback) {\n queued.push(callback);\n channel.port2.postMessage(null);\n },\n close() {\n queued.length = 0;\n channel.port1.close();\n channel.port2.close();\n },\n };\n}\n\n/**\n * A paint stream that ended for a non-terminal reason (the track ended,\n * the reader closed) gets ONE fresh watcher this long after, while the\n * canvas is still enabled. A second end is treated as terminal until the\n * next demand toggle: there is no dirty transition to try again on, and\n * retrying forever would hide a broken source.\n */\nconst PAINT_RESTART_DELAY_MS = 1_000;\n\nexport function watchCanvasFrames(\n root: Element,\n emitter: CanvasFrameEmitter,\n options: WatchCanvasFramesOptions = {},\n): CanvasFrameWatcher {\n // A provided scheduler is the caller's to close; a default one is ours.\n const own = options.scheduler\n ? null\n : createDefaultScheduler(\n (root.ownerDocument.defaultView ?? globalThis) as typeof globalThis,\n );\n const scheduler = options.scheduler ?? (own as CanvasFrameScheduler);\n const tracker = options.tracker ?? null;\n const sampleCanvas = options.sampleCanvas ?? sampleCanvasDirect;\n const watchPaints = options.watchPaints ?? watchCanvasPaints;\n const maxInFlight = options.maxInFlight ?? DEFAULT_CANVAS_FRAME_MAX_IN_FLIGHT;\n const activityWindowMs =\n options.activityWindowMs ?? DEFAULT_CANVAS_ACTIVITY_WINDOW_MS;\n\n const watched = new Map<HTMLCanvasElement, WatchedCanvas>();\n let demand: Record<string, CanvasFrameDemand> = {};\n let stopped = false;\n\n // ── Per-canvas predicates ─────────────────────────────────────────────\n /** The tracker that sees this canvas's draws, or null (untracked). */\n const trackerOf = (entry: WatchedCanvas): CanvasDirtyTracker | null =>\n tracker?.isTracked(entry.canvas) ? tracker : null;\n const revisionOf = (entry: WatchedCanvas) =>\n trackerOf(entry)?.revision(entry.canvas) ?? entry.paintRevision;\n /**\n * The lane is in the business of this canvas's pixels: the host wants\n * them and they can still be read. A canvas that is not served is never\n * read, never watched for paints, and its draws hold nothing.\n */\n const isServed = (entry: WatchedCanvas) =>\n entry.demand.enabled &&\n !entry.removed &&\n !entry.terminal &&\n !entry.paintsExhausted;\n const isRunnable = (entry: WatchedCanvas) =>\n isServed(entry) &&\n !entry.pending &&\n entry.outstanding.size < maxInFlight &&\n revisionOf(entry) !== entry.sampledRevision;\n\n // ── Activity: one expiry timer keyed on the latest dirty notification ─\n let active = false;\n let lastDirtyAt = Number.NEGATIVE_INFINITY;\n let activityTimer: unknown = null;\n\n /**\n * The tracker notifies once per clean→dirty transition and a read is\n * what cleans. A canvas the lane cannot read (no credit, a read in\n * flight) therefore stays dirty and its page's further draws are\n * invisible. Before letting activity lapse, re-arm the flag of every\n * such canvas (the loop still sees it dirty: its sampled revision did\n * not move) and wait one more window; a draw in that window notifies\n * again. Returns whether any of them was drawn on since the last re-arm.\n */\n const rearmBlockedCanvases = (): boolean => {\n let drawnSinceRearm = false;\n for (const entry of watched.values()) {\n // A canvas the lane does not serve is never read, so its draws are\n // not its business: re-arming it would hold the compositor for nothing.\n if (!isServed(entry)) continue;\n const seenBy = trackerOf(entry);\n if (!seenBy) continue;\n const revision = seenBy.revision(entry.canvas);\n if (revision === entry.sampledRevision) continue;\n if (revision !== entry.armedRevision) drawnSinceRearm = true;\n entry.armedRevision = revision;\n seenBy.captureStarted(entry.canvas);\n }\n return drawnSinceRearm;\n };\n const armActivityExpiry = (ms: number) => {\n activityTimer = scheduler.setTimeout(() => {\n activityTimer = null;\n const remaining = lastDirtyAt + activityWindowMs - scheduler.now();\n if (remaining > 0) {\n armActivityExpiry(remaining);\n return;\n }\n if (rearmBlockedCanvases()) {\n armActivityExpiry(activityWindowMs);\n return;\n }\n active = false;\n emitter.activity(false);\n }, ms);\n };\n const touchActivity = () => {\n lastDirtyAt = scheduler.now();\n if (!active) {\n active = true;\n emitter.activity(true);\n }\n if (activityTimer === null) armActivityExpiry(activityWindowMs);\n };\n\n // ── Unavailable ───────────────────────────────────────────────────────\n const reportUnavailable = (\n entry: WatchedCanvas,\n reason: CanvasFrameUnavailableReason,\n ) => {\n // Tainted and unsupported are permanent for this element; unreadable\n // retries on the next dirty transition. Each is reported once per\n // failure streak.\n if (reason !== \"unreadable\") entry.terminal = true;\n if (entry.unavailableReported) return;\n entry.unavailableReported = true;\n emitter.removed(entry.targetId, reason);\n };\n\n // ── Untracked canvases: the paint watcher is the dirty source ─────────\n const stopPaints = (entry: WatchedCanvas) => {\n entry.paints?.stop();\n entry.paints = null;\n if (entry.paintRestartTimer !== null) {\n scheduler.clearTimeout(entry.paintRestartTimer);\n entry.paintRestartTimer = null;\n }\n };\n /** The stream ended: one bounded restart, then exhausted until the next demand toggle. */\n const onPaintsEnded = (\n entry: WatchedCanvas,\n reason: CanvasFrameUnavailableReason,\n ) => {\n stopPaints(entry);\n if (entry.removed || stopped) return;\n reportUnavailable(entry, reason);\n if (entry.terminal) return;\n if (entry.paintRestarts > 0) {\n entry.paintsExhausted = true;\n return;\n }\n entry.paintRestarts += 1;\n entry.paintRestartTimer = scheduler.setTimeout(() => {\n entry.paintRestartTimer = null;\n syncPaints(entry);\n // A fresh watcher holds nothing yet: read the placeholder once.\n if (entry.paints) {\n entry.sampledRevision = -1;\n wake(entry);\n }\n }, PAINT_RESTART_DELAY_MS);\n };\n const startPaints = (entry: WatchedCanvas) => {\n const watcher = watchPaints(entry.canvas, {\n onPaint: () => {\n if (entry.removed || stopped) return;\n entry.paintRevision += 1;\n onDirty(entry);\n },\n onEnded: (reason) => onPaintsEnded(entry, reason),\n });\n if (!watcher) {\n reportUnavailable(entry, \"unsupported\");\n return;\n }\n entry.paints = watcher;\n };\n /** Keep the paint watcher running exactly while an untracked canvas is served. */\n const syncPaints = (entry: WatchedCanvas) => {\n const wantsPaints = isServed(entry) && trackerOf(entry) === null;\n if (wantsPaints && !entry.paints) startPaints(entry);\n else if (!wantsPaints && entry.paints) stopPaints(entry);\n };\n\n // ── The loop ──────────────────────────────────────────────────────────\n let readPosted = false;\n let dueTimer: unknown = null;\n let dueTimerAt = Number.POSITIVE_INFINITY;\n\n const clearDueTimer = () => {\n if (dueTimer !== null) scheduler.clearTimeout(dueTimer);\n dueTimer = null;\n dueTimerAt = Number.POSITIVE_INFINITY;\n };\n const armDueTimer = (at: number, now: number) => {\n if (at === Number.POSITIVE_INFINITY) {\n clearDueTimer();\n return;\n }\n if (dueTimer !== null && dueTimerAt <= at) return;\n clearDueTimer();\n dueTimerAt = at;\n dueTimer = scheduler.setTimeout(() => {\n dueTimer = null;\n dueTimerAt = Number.POSITIVE_INFINITY;\n readDue();\n }, at - now);\n };\n const postRead = () => {\n if (readPosted) return;\n readPosted = true;\n scheduler.post(readDue);\n };\n\n /** Wake for one canvas: read it in a task if due, else wait for its due time. */\n const wake = (entry: WatchedCanvas) => {\n if (stopped || !isRunnable(entry)) return;\n const now = scheduler.now();\n if (now >= entry.nextDueAt) postRead();\n else armDueTimer(entry.nextDueAt, now);\n };\n /** Wake for every canvas. */\n const schedule = () => {\n if (stopped) return;\n const now = scheduler.now();\n let earliest = Number.POSITIVE_INFINITY;\n let anyDue = false;\n for (const entry of watched.values()) {\n if (!isRunnable(entry)) continue;\n if (now >= entry.nextDueAt) anyDue = true;\n else earliest = Math.min(earliest, entry.nextDueAt);\n }\n if (anyDue) postRead();\n armDueTimer(earliest, now);\n };\n const readDue = () => {\n readPosted = false;\n if (stopped) return;\n const now = scheduler.now();\n for (const entry of watched.values()) {\n if (isRunnable(entry) && now >= entry.nextDueAt) beginRead(entry, now);\n }\n schedule();\n };\n\n const onDirty = (entry: WatchedCanvas) => {\n // A canvas the lane does not serve is never read: its draws must not\n // hold the compositor.\n if (!isServed(entry)) return;\n touchActivity();\n wake(entry);\n };\n\n // ── Reading ───────────────────────────────────────────────────────────\n const readEntry = async (\n entry: WatchedCanvas,\n size: CanvasSampleSize,\n ): Promise<ImageBitmap | null> => {\n try {\n const paint = await entry.paints?.read(size);\n if (paint) return paint;\n } catch {\n // One paint failed to convert; the next paint is a fresh chance.\n return null;\n }\n // A tracked canvas, or an untracked one that has not painted since it\n // was enabled: read the element itself (for a worker-owned canvas,\n // its placeholder).\n return sampleCanvas(entry.canvas, size);\n };\n\n const beginRead = (entry: WatchedCanvas, now: number) => {\n const interval = entry.demand.maxFps > 0 ? 1000 / entry.demand.maxFps : 0;\n const dueAgain = entry.nextDueAt + interval;\n entry.nextDueAt = now < dueAgain + interval ? dueAgain : now + interval;\n entry.sampledRevision =\n trackerOf(entry)?.captureStarted(entry.canvas) ?? entry.paintRevision;\n const sourceWidth = entry.canvas.width;\n const sourceHeight = entry.canvas.height;\n const demandGeneration = entry.demandGeneration;\n // An empty canvas has no pixels, and the destination must not keep\n // showing the last frame over a source that has none (its repaint would\n // also write the old size back over the DOM stream's `width=\"0\"`). The\n // next dirty transition (a resize back) reads it again.\n if (sourceWidth <= 0 || sourceHeight <= 0) {\n emitter.removed(entry.targetId);\n return;\n }\n\n entry.pending = true;\n void readEntry(entry, {\n width: entry.demand.width,\n height: entry.demand.height,\n }).then(\n (bitmap) => {\n entry.pending = false;\n if (bitmap) {\n if (demandGeneration !== entry.demandGeneration) {\n bitmap.close();\n } else {\n entry.unavailableReported = false;\n deliver(entry, bitmap, sourceWidth, sourceHeight);\n }\n }\n schedule();\n },\n (error) => {\n entry.pending = false;\n // A read that outlived its entry says nothing: the element may have\n // been re-added under the same id, and a removal here would clear\n // the frames its replacement already delivered.\n if (\n demandGeneration === entry.demandGeneration &&\n !entry.removed &&\n !stopped\n ) {\n reportUnavailable(entry, classifyCanvasSampleError(error));\n }\n schedule();\n },\n );\n };\n\n const deliver = (\n entry: WatchedCanvas,\n bitmap: ImageBitmap,\n sourceWidth: number,\n sourceHeight: number,\n ) => {\n // A read that outlived its demand is closed, not sent. A read whose\n // demand SIZE changed meanwhile is still sent: a complete lower-res\n // frame is better than none, and the next read carries the new size.\n if (stopped || !isServed(entry)) {\n bitmap.close();\n return;\n }\n entry.nextFrameId += 1;\n const frameId = entry.nextFrameId;\n entry.outstanding.add(frameId);\n const delivered = emitter.frame({\n targetId: entry.targetId,\n frameId,\n bitmap,\n sourceWidth,\n sourceHeight,\n });\n if (!delivered) {\n bitmap.close();\n entry.outstanding.delete(frameId);\n }\n };\n\n // ── Demand transitions ────────────────────────────────────────────────\n const applyDemand = (entry: WatchedCanvas, next: CanvasFrameDemand) => {\n const previous = entry.demand;\n entry.demand = next;\n if (previous.enabled !== next.enabled) entry.demandGeneration += 1;\n const sizeChanged =\n previous.width !== next.width || previous.height !== next.height;\n // Enabling must yield exactly one fresh frame even for a static canvas;\n // a new size must too, or a zoomed-in static canvas would stay blurry.\n if (next.enabled && (!previous.enabled || sizeChanged)) {\n entry.sampledRevision = -1;\n }\n // A demand toggle is the one thing that gives an exhausted paint\n // stream another go.\n if (next.enabled && !previous.enabled) {\n entry.paintRestarts = 0;\n entry.paintsExhausted = false;\n }\n syncPaints(entry);\n };\n\n // ── Discovery ─────────────────────────────────────────────────────────\n const track = (canvas: HTMLCanvasElement) => {\n const targetId = ensureProjectionDomId(canvas);\n // An element the DOM stream cannot address (inside a contenteditable\n // editor) has no mirrored counterpart to paint into.\n if (!targetId) return;\n const entry: WatchedCanvas = {\n canvas,\n targetId,\n demand: DISABLED_CANVAS_FRAME_DEMAND,\n sampledRevision: -1,\n pending: false,\n demandGeneration: 0,\n nextDueAt: 0,\n nextFrameId: 0,\n outstanding: new Set(),\n tracked: tracker?.isTracked(canvas) ?? false,\n paints: null,\n paintRevision: 0,\n paintRestarts: 0,\n paintRestartTimer: null,\n paintsExhausted: false,\n unsubscribe: null,\n terminal: false,\n unavailableReported: false,\n removed: false,\n armedRevision: -1,\n };\n watched.set(canvas, entry);\n entry.unsubscribe =\n tracker?.subscribe(canvas, () => {\n // Also fires when the canvas loses tracking\n // (transferControlToOffscreen), dirty or not: from then on its\n // paints are the dirty source, so the watcher must start here. The\n // revision changes meaning at that edge (tracker revision before,\n // paint count after), so the last read is forced stale rather than\n // compared across the two: a stall for credit that spans the\n // transfer would otherwise leave the placeholder pixels up until the\n // worker's next paint.\n if (entry.tracked && trackerOf(entry) === null) {\n entry.tracked = false;\n entry.sampledRevision = -1;\n }\n syncPaints(entry);\n onDirty(entry);\n }) ?? null;\n applyDemand(entry, demand[targetId] ?? DISABLED_CANVAS_FRAME_DEMAND);\n wake(entry);\n };\n\n const untrack = (canvas: HTMLCanvasElement, notify: boolean) => {\n const entry = watched.get(canvas);\n if (!entry) return;\n entry.removed = true;\n watched.delete(canvas);\n entry.unsubscribe?.();\n entry.unsubscribe = null;\n stopPaints(entry);\n if (notify) emitter.removed(entry.targetId);\n };\n\n const stopRegistry = watchCanvasElements(root, {\n onAdded: (canvas) => {\n if (!stopped) track(canvas);\n },\n onRemoved: (canvas) => untrack(canvas, true),\n });\n\n return {\n ack(targetId, frameId) {\n for (const entry of watched.values()) {\n if (entry.targetId !== targetId) continue;\n // Only an outstanding id is a credit; stale and duplicate acks are noise.\n if (entry.outstanding.delete(frameId)) wake(entry);\n return;\n }\n },\n updateDemand(entries) {\n if (stopped) return;\n demand = entries;\n for (const entry of watched.values()) {\n applyDemand(\n entry,\n entries[entry.targetId] ?? DISABLED_CANVAS_FRAME_DEMAND,\n );\n }\n schedule();\n },\n stop(stopOptions = {}) {\n if (stopped) return;\n stopped = true;\n stopRegistry();\n for (const entry of [...watched.values()]) {\n untrack(entry.canvas, stopOptions.notifyRemovals ?? false);\n }\n clearDueTimer();\n if (activityTimer !== null) scheduler.clearTimeout(activityTimer);\n activityTimer = null;\n // The destination keeps its last pixels; only the compositor hold must\n // be released.\n if (active) {\n active = false;\n emitter.activity(false);\n }\n own?.close();\n },\n };\n}\n","/**\n * The canvas pixel lane over one `MessagePort`: the wire contract and both\n * of its ends.\n *\n * The DOM projection serializes a `<canvas>` as an empty tag — its pixels\n * live in a GPU buffer `outerHTML` cannot carry. This lane runs BESIDE the\n * ordered ProjectionBatch stream and moves those pixels as transferred\n * `ImageBitmap`s, addressed by the same `data-dom-id` the DOM stream stamps\n * on the element. Why a separate port: batches flush on a fixed 500 ms\n * window and carry ordering receipts; pixels arrive up to 30 times a second\n * and must never queue behind DOM work. The lane has no ordering contract\n * of its own — every frame is a complete final state, so a dropped or\n * reordered frame is repaired by the next one.\n *\n * Transport-agnostic: whoever can put a `MessagePort` in both realms (a\n * same-document `MessageChannel`, a frame-pool port relayed across\n * processes, a main-brokered webview port) gets the lane.\n *\n * Trust runs one way. The host is the trusted side: its commands are\n * accepted on their `kind` alone, and the planner refuses to plan a size\n * no canvas could have. A frame from the guest is checked for the two\n * things the destination would otherwise crash on — a real `ImageBitmap`\n * and an id to file it under.\n *\n * The server owns the demand map for the life of a lane: when the host\n * re-renders and the projection root is replaced, the new watcher starts\n * with the last demand and frames flow again without the host resending.\n * The watcher for a detached root is stopped WITH removal notices, because\n * its ids will never be addressed again and the destination's retained\n * bitmaps for them would otherwise live until the sink is disposed.\n */\n\nimport {\n type CanvasFrameDemand,\n type CanvasFrameUnavailableReason,\n DISABLED_CANVAS_FRAME_DEMAND,\n} from \"./demand\";\nimport type { CanvasFrameSink } from \"./sink\";\nimport {\n type CanvasFrameScheduler,\n type CanvasFrameWatcher,\n createDefaultScheduler,\n type WatchCanvasFramesOptions,\n watchCanvasFrames,\n} from \"./source\";\n\n/**\n * Frame-pool channel on which the host delivers the lane's `MessagePort` to\n * the guest (`event.ports[0]`). One port per storyboard lane.\n */\nexport const CANVAS_FRAME_LANE_PORT_CHANNEL = \"canvas-frames:port\" as const;\n\n// ── Host → guest ────────────────────────────────────────────────────────────\n\ninterface CanvasFrameLaneStartCommand {\n readonly kind: \"canvas-frames:start\";\n /** Projection root whose subtree is watched for `<canvas>` elements. */\n readonly rootId: string;\n /** Optional explicit root selector; the guest otherwise resolves `rootId`. */\n readonly selector?: string;\n}\n\n/** Complete replacement of the demand map; a targetId absent here is disabled. */\ninterface CanvasFrameLaneDemandCommand {\n readonly kind: \"canvas-frames:demand\";\n readonly entries: Record<string, CanvasFrameDemand>;\n}\n\n/** The destination painted (or discarded) a frame; releases one credit. */\ninterface CanvasFrameLaneAckCommand {\n readonly kind: \"canvas-frames:ack\";\n readonly targetId: string;\n readonly frameId: number;\n}\n\ntype CanvasFrameLaneCommand =\n | CanvasFrameLaneStartCommand\n | CanvasFrameLaneDemandCommand\n | CanvasFrameLaneAckCommand;\n\n// ── Guest → host ────────────────────────────────────────────────────────────\n\n/** One complete frame of one canvas. `bitmap` rides the transfer list. */\ninterface CanvasFrameEvent {\n readonly kind: \"canvas-frames:frame\";\n readonly targetId: string;\n /** Monotonic per canvas; echoed by the ack. */\n readonly frameId: number;\n /** Authored `canvas.width/height` at sample time; the destination keeps these. */\n readonly sourceWidth: number;\n readonly sourceHeight: number;\n readonly bitmap: ImageBitmap;\n}\n\n/**\n * The source has no pixels for this id any more: the canvas left the\n * document, became empty (width or height 0), or — with a `reason` — cannot\n * be read at all. The destination drops its retained frame and clears the\n * mirrored element either way; a later frame for the same id repopulates it.\n */\ninterface CanvasRemovedEvent {\n readonly kind: \"canvas-frames:removed\";\n readonly targetId: string;\n readonly reason?: CanvasFrameUnavailableReason;\n}\n\n/** The lane's canvases are (no longer) being drawn on. Drives the compositor hold. */\ninterface CanvasActivityEvent {\n readonly kind: \"canvas-frames:activity\";\n readonly active: boolean;\n}\n\ntype CanvasFrameLaneEvent =\n | CanvasFrameEvent\n | CanvasRemovedEvent\n | CanvasActivityEvent;\n\n/**\n * The slice of `MessagePort` both ends use; tests supply in-memory pairs.\n *\n * `onmessage` is declared through a method signature so a real DOM\n * `MessagePort` is assignable without a cast: under `strictFunctionTypes`\n * a property typed `(event: { data: unknown }) => void` rejects the DOM's\n * `(this: MessagePort, ev: MessageEvent) => any` (parameters are checked\n * contravariantly), while method parameters stay bivariant. The lane only\n * ever reads `event.data`, so the wider DOM event is safe.\n */\nexport interface CanvasFrameLanePort {\n postMessage(message: unknown, transfer?: Transferable[]): void;\n onmessage:\n | { bivarianceHack(event: { data: unknown }): void }[\"bivarianceHack\"]\n | null;\n start?(): void;\n close(): void;\n /** `close` fires when the far port is closed or its realm is destroyed. */\n addEventListener?(type: \"close\", listener: () => void): void;\n removeEventListener?(type: \"close\", listener: () => void): void;\n}\n\n// ── Guards ──────────────────────────────────────────────────────────────────\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * The host side is our own planner, so a command is taken on its kind and\n * the switch that follows reads the fields its kind promises.\n */\nfunction isLaneCommand(value: unknown): value is CanvasFrameLaneCommand {\n return (\n isRecord(value) &&\n typeof value.kind === \"string\" &&\n value.kind.startsWith(\"canvas-frames:\")\n );\n}\n\n/**\n * A real `ImageBitmap`. Realms without the constructor (a worker that never\n * created one, a DOM test environment) fall back to the one thing the lane\n * relies on: something it can `close()`.\n */\nfunction isImageBitmap(value: unknown): value is ImageBitmap {\n if (typeof ImageBitmap === \"function\") return value instanceof ImageBitmap;\n return isRecord(value) && typeof value.close === \"function\";\n}\n\nconst UNAVAILABLE_REASONS: ReadonlySet<unknown> = new Set([\n \"tainted\",\n \"unreadable\",\n \"unsupported\",\n]);\n\n/** Something to paint, and an id to file it under. */\nfunction isFrameEvent(value: unknown): value is CanvasFrameEvent {\n return (\n isRecord(value) &&\n typeof value.targetId === \"string\" &&\n Number.isInteger(value.frameId) &&\n (value.frameId as number) > 0 &&\n isImageBitmap(value.bitmap)\n );\n}\n\n// ── Demand equality ─────────────────────────────────────────────────────────\n\nfunction demandsEqual(a: CanvasFrameDemand, b: CanvasFrameDemand): boolean {\n if (!a.enabled && !b.enabled) return true;\n return (\n a.enabled === b.enabled &&\n a.width === b.width &&\n a.height === b.height &&\n a.maxFps === b.maxFps\n );\n}\n\n/**\n * Equality under the wire's semantics: an absent entry is a disabled one,\n * and every disabled entry is the same disabled entry.\n */\nexport function canvasFrameDemandsEqual(\n a: Record<string, CanvasFrameDemand>,\n b: Record<string, CanvasFrameDemand>,\n): boolean {\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]);\n for (const key of keys) {\n const left = a[key] ?? DISABLED_CANVAS_FRAME_DEMAND;\n const right = b[key] ?? DISABLED_CANVAS_FRAME_DEMAND;\n if (!demandsEqual(left, right)) return false;\n }\n return true;\n}\n\n/** The rate the host must hold the source at: the fastest enabled canvas. */\nfunction highestEnabledMaxFps(\n entries: Record<string, CanvasFrameDemand>,\n): number | null {\n let highest: number | null = null;\n for (const entry of Object.values(entries)) {\n if (!entry.enabled) continue;\n highest = highest === null ? entry.maxFps : Math.max(highest, entry.maxFps);\n }\n return highest;\n}\n\n// ── Guest (source) ──────────────────────────────────────────────────────────\n\nexport interface ServeCanvasFramesOptions extends WatchCanvasFramesOptions {\n /**\n * Locate the projection root for a lane. Called again whenever the root\n * leaves the document (a host re-render replaces it) until it resolves.\n */\n resolveRoot(rootId: string, selector?: string): Element | null;\n /** How often an unresolved or detached root is re-resolved (one `isConnected` read). */\n rootPollMs?: number;\n}\n\nconst DEFAULT_ROOT_POLL_MS = 250;\n\n/**\n * Serve lane commands arriving on `port` for this source document. Returns\n * a disposer; the port is closed on dispose.\n */\nexport function serveCanvasFramesOverPort(\n port: CanvasFrameLanePort,\n options: ServeCanvasFramesOptions,\n): () => void {\n const { resolveRoot, rootPollMs, ...watchOptions } = options;\n // A provided scheduler is the caller's to close; a default one is ours,\n // and the watcher shares it rather than opening a second channel.\n const own = options.scheduler ? null : createDefaultScheduler();\n const scheduler = options.scheduler ?? (own as CanvasFrameScheduler);\n const pollMs = rootPollMs ?? DEFAULT_ROOT_POLL_MS;\n\n let disposed = false;\n let rootId: string | null = null;\n let selector: string | undefined;\n let demand: Record<string, CanvasFrameDemand> = {};\n let root: Element | null = null;\n let watcher: CanvasFrameWatcher | null = null;\n let pollTimer: unknown = null;\n\n const send = (event: CanvasFrameLaneEvent, transfer?: Transferable[]) => {\n if (disposed) return false;\n try {\n port.postMessage(event, transfer);\n return true;\n } catch {\n return false;\n }\n };\n\n const startWatcher = (current: Element) => {\n const started = watchCanvasFrames(\n current,\n {\n frame: ({ targetId, frameId, bitmap, sourceWidth, sourceHeight }) =>\n send(\n {\n kind: \"canvas-frames:frame\",\n targetId,\n frameId,\n sourceWidth,\n sourceHeight,\n bitmap,\n },\n [bitmap],\n ),\n removed: (targetId, reason) =>\n void send({ kind: \"canvas-frames:removed\", targetId, reason }),\n activity: (active) =>\n void send({ kind: \"canvas-frames:activity\", active }),\n },\n { ...watchOptions, scheduler },\n );\n // Only a watcher that started owns the root; a throw above leaves the\n // root unresolved so the next poll tries again.\n watcher = started;\n root = current;\n started.updateDemand(demand);\n };\n\n const stopLane = () => {\n watcher?.stop();\n watcher = null;\n root = null;\n rootId = null;\n if (pollTimer !== null) scheduler.clearTimeout(pollTimer);\n pollTimer = null;\n };\n\n const ensureRoot = () => {\n if (rootId === null || disposed) return;\n pollTimer = null;\n try {\n if (root && !root.isConnected) {\n // The old ids are gone for good: tell the destination so it drops\n // their retained bitmaps instead of holding them until dispose.\n watcher?.stop({ notifyRemovals: true });\n watcher = null;\n root = null;\n }\n if (!root) {\n const resolved = resolveRoot(rootId, selector);\n if (resolved) startWatcher(resolved);\n }\n } finally {\n // Keep watching for the root to appear, or to be replaced later. Also\n // after a watcher failed to start: the poll is what retries it.\n pollTimer = scheduler.setTimeout(ensureRoot, pollMs);\n }\n };\n\n const handle = (command: CanvasFrameLaneCommand) => {\n switch (command.kind) {\n case \"canvas-frames:start\": {\n stopLane();\n rootId = command.rootId;\n selector = command.selector;\n demand = {};\n ensureRoot();\n return;\n }\n case \"canvas-frames:demand\": {\n if (rootId === null) return;\n demand = command.entries;\n watcher?.updateDemand(command.entries);\n return;\n }\n case \"canvas-frames:ack\":\n watcher?.ack(command.targetId, command.frameId);\n return;\n }\n };\n\n port.onmessage = (event) => {\n if (disposed) return;\n const command = event.data;\n if (!isLaneCommand(command)) return;\n try {\n handle(command);\n } catch (error) {\n // Nothing the host can do with this: a failed start is retried by the\n // root poll, and every other command is idempotent.\n console.warn(\"[canvas-frames] lane command failed\", error);\n }\n };\n port.start?.();\n\n return () => {\n if (disposed) return;\n disposed = true;\n stopLane();\n own?.close();\n port.onmessage = null;\n try {\n port.close();\n } catch {\n // Already closed by the far side.\n }\n };\n}\n\n/**\n * Serve every lane port a transport delivers, for the life of the\n * subscription: each port gets its own lane, a closed port disposes its\n * lane, and the returned disposer unsubscribes and disposes what is left.\n */\nexport function serveCanvasFrameLanes(\n subscribePorts: (deliver: (port: MessagePort) => void) => () => void,\n options: ServeCanvasFramesOptions,\n): () => void {\n const lanes = new Set<() => void>();\n\n const unsubscribe = subscribePorts((port) => {\n const dispose = serveCanvasFramesOverPort(port, options);\n const disposeOnce = () => {\n if (!lanes.delete(disposeOnce)) return;\n dispose();\n };\n lanes.add(disposeOnce);\n // The host went away (its document unloaded, or it released the lane).\n port.addEventListener?.(\"close\", disposeOnce, { once: true });\n });\n\n return () => {\n unsubscribe();\n for (const dispose of [...lanes]) dispose();\n };\n}\n\n// ── Host (destination) ──────────────────────────────────────────────────────\n\n/**\n * What a canvas stream tells its listener. Per canvas the order is\n * `canvas-added`, then frames, then `canvas-removed`; a `canvas-removed`\n * can arrive for a canvas never announced (the guest found it unreadable\n * before it delivered a frame). `disconnected` is the last event of a\n * stream: the document behind it went, or its owner closed it.\n */\nexport type CanvasStreamEvent =\n | {\n readonly kind: \"canvas-added\";\n readonly id: string;\n readonly sourceWidth: number;\n readonly sourceHeight: number;\n }\n | {\n readonly kind: \"frame\";\n readonly id: string;\n readonly frameId: number;\n /** Authored `canvas.width/height` at sample time; a canvas can be resized between frames. */\n readonly sourceWidth: number;\n readonly sourceHeight: number;\n /** The listener's once delivered: paint it or close it, then `ack`. */\n readonly bitmap: ImageBitmap;\n }\n | {\n readonly kind: \"canvas-removed\";\n readonly id: string;\n readonly reason?: CanvasFrameUnavailableReason;\n }\n | { readonly kind: \"activity\"; readonly active: boolean }\n | { readonly kind: \"disconnected\" };\n\n/**\n * The live `<canvas>` pixels of one projection root in one document, the\n * claim-side face of the lane. Opened and closed by whoever owns the\n * document edge (a claim, a frame handle); a consumer subscribes, asks for\n * what it wants, and acks what it took. The stream retains no frame: a\n * bitmap belongs to the listener as soon as it is delivered, and with no\n * listener the stream closes and acks it itself.\n */\nexport interface CanvasStream {\n subscribe(listener: (event: CanvasStreamEvent) => void): () => void;\n /**\n * What to sample, as a complete replacement: an id absent or null is not\n * wanted. Posted only when it differs from the last map. A consumer that\n * stops listening withdraws its demand, or the guest keeps sampling for\n * nobody.\n */\n setDemand(entries: Record<string, CanvasFrameDemand | null>): void;\n /** The frame was painted or dropped; releases one of the canvas's credits. */\n ack(id: string, frameId: number): void;\n}\n\n/**\n * Open a stream over `port` and start the lane for `rootId`. The returned\n * `close` is the owner's: it closes the port, which is what stops the\n * source, and ends the stream with `disconnected` if the far side had not\n * already. `onStreamingRate` reports the rate the source must be held at\n * while its canvases animate: the fastest enabled canvas's `maxFps`, or\n * null when nothing is animating (no activity, the far port closed, the\n * stream closed). Fires only on a change.\n */\nexport function createCanvasStream(\n port: CanvasFrameLanePort,\n options: {\n rootId: string;\n selector?: string;\n onStreamingRate?(rate: number | null): void;\n },\n): CanvasStream & { close(): void } {\n const listeners = new Set<(event: CanvasStreamEvent) => void>();\n const announced = new Set<string>();\n let closed = false;\n let disconnected = false;\n let active = false;\n let demand: Record<string, CanvasFrameDemand> = {};\n let lastRate: number | null = null;\n\n const emit = (event: CanvasStreamEvent) => {\n for (const listener of [...listeners]) listener(event);\n };\n\n const post = (command: CanvasFrameLaneCommand) => {\n if (closed) return;\n try {\n port.postMessage(command);\n } catch {\n // The far side is gone; the owner's close will follow.\n }\n };\n\n const syncStreamingRate = () => {\n const rate = active ? highestEnabledMaxFps(demand) : null;\n if (rate === lastRate) return;\n lastRate = rate;\n options.onStreamingRate?.(rate);\n };\n\n const disconnect = () => {\n if (disconnected) return;\n disconnected = true;\n active = false;\n syncStreamingRate();\n emit({ kind: \"disconnected\" });\n };\n\n const ack = (id: string, frameId: number) =>\n post({ kind: \"canvas-frames:ack\", targetId: id, frameId });\n\n port.onmessage = (event) => {\n if (closed) return;\n const message = event.data;\n if (!isRecord(message)) return;\n switch (message.kind) {\n case \"canvas-frames:frame\": {\n if (!isFrameEvent(message)) return;\n const { targetId: id, frameId, sourceWidth, sourceHeight } = message;\n if (!announced.has(id)) {\n announced.add(id);\n emit({ kind: \"canvas-added\", id, sourceWidth, sourceHeight });\n }\n if (listeners.size === 0) {\n message.bitmap.close();\n ack(id, frameId);\n return;\n }\n emit({\n kind: \"frame\",\n id,\n frameId,\n sourceWidth,\n sourceHeight,\n bitmap: message.bitmap,\n });\n return;\n }\n case \"canvas-frames:removed\": {\n if (typeof message.targetId !== \"string\") return;\n announced.delete(message.targetId);\n emit({\n kind: \"canvas-removed\",\n id: message.targetId,\n ...(UNAVAILABLE_REASONS.has(message.reason)\n ? { reason: message.reason as CanvasFrameUnavailableReason }\n : {}),\n });\n return;\n }\n case \"canvas-frames:activity\":\n if (typeof message.active !== \"boolean\") return;\n active = message.active;\n syncStreamingRate();\n emit({ kind: \"activity\", active });\n return;\n }\n };\n // A guest document that reloads takes its port end with it and nothing\n // closes ours: without this the last `activity: true` would hold the\n // source rate until the owner closed the stream.\n port.addEventListener?.(\"close\", disconnect);\n port.start?.();\n post({\n kind: \"canvas-frames:start\",\n rootId: options.rootId,\n ...(options.selector === undefined ? {} : { selector: options.selector }),\n });\n\n return {\n subscribe(listener) {\n if (closed) return () => {};\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n setDemand(entries) {\n if (closed) return;\n const next: Record<string, CanvasFrameDemand> = {};\n for (const [id, entry] of Object.entries(entries)) {\n if (entry) next[id] = entry;\n }\n if (canvasFrameDemandsEqual(demand, next)) return;\n demand = next;\n post({ kind: \"canvas-frames:demand\", entries: next });\n syncStreamingRate();\n },\n ack,\n close() {\n if (closed) return;\n disconnect();\n closed = true;\n port.onmessage = null;\n port.removeEventListener?.(\"close\", disconnect);\n try {\n port.close();\n } catch {\n // Already closed by the far side.\n }\n listeners.clear();\n },\n };\n}\n\n/**\n * Paint a stream into a sink: every frame is accepted (the sink owns the\n * bitmap from then on) and acked, and a removed canvas is removed. A\n * disconnect changes nothing on the destination: what is on screen stays\n * until a frame from the next document or a commit replaces it. The sink\n * stays the caller's to repaint after commits and to dispose.\n */\nexport function paintCanvasStream(\n stream: CanvasStream,\n sink: CanvasFrameSink,\n): () => void {\n return stream.subscribe((event) => {\n switch (event.kind) {\n case \"frame\":\n sink.accept(event.id, event.bitmap, {\n width: event.sourceWidth,\n height: event.sourceHeight,\n });\n stream.ack(event.id, event.frameId);\n return;\n case \"canvas-removed\":\n sink.remove(event.id);\n return;\n }\n });\n}\n","/**\n * Force `preserveDrawingBuffer: true` on every WebGL context created in a\n * source document.\n *\n * With the WebGL default (`false`) the drawing buffer is cleared after the\n * compositor consumes it, so a canvas drawn once — a one-shot visualization,\n * a static shader — reads back blank from `createImageBitmap(canvas)` the\n * moment a lane wants its baseline. `captureStream()` cannot help either: a\n * canvas that never repaints yields no frame. Preserving the buffer is the\n * only way to read such a canvas after the fact.\n *\n * The price: Chromium keeps the back buffer alive across presents (one extra\n * copy per frame for WebGL canvases), and the page's own semantics move: a\n * render loop that relies on the implicit clear between frames (never calls\n * `gl.clear`) accumulates frames, and `getContextAttributes()` reports the\n * forced value. Storyboard sources are mirrors, not the user's shipping page,\n * so the trade is accepted for every source document.\n *\n * Must run before any page script (a preload); patching after a context\n * exists cannot change its attributes.\n */\n\nexport const PRESERVE_DRAWING_BUFFER_SOURCE = String.raw`(scope => {\n const WEBGL_CONTEXT_IDS = new Set([\"webgl\", \"webgl2\", \"experimental-webgl\"]);\n const prototype = scope.HTMLCanvasElement?.prototype;\n if (!prototype) return () => {};\n const original = prototype.getContext;\n if (typeof original !== \"function\") return () => {};\n // Forward every argument unchanged except WebGL's preservation attribute.\n const patched = function (contextId, attributes, ...rest) {\n const forced = WEBGL_CONTEXT_IDS.has(contextId)\n ? {\n ...(typeof attributes === \"object\" && attributes !== null\n ? attributes\n : {}),\n preserveDrawingBuffer: true,\n }\n : attributes;\n return original.call(this, contextId, forced, ...rest);\n };\n prototype.getContext = patched;\n\n return () => {\n if (prototype.getContext === patched) prototype.getContext = original;\n };\n})`;\n\ntype CanvasHookInstaller = (scope: {\n HTMLCanvasElement?: typeof HTMLCanvasElement;\n}) => () => void;\nlet install: CanvasHookInstaller | undefined;\n\nexport function installPreserveDrawingBuffer(\n scope: { HTMLCanvasElement?: typeof HTMLCanvasElement } = globalThis,\n): () => void {\n install ??= new Function(\n `return ${PRESERVE_DRAWING_BUFFER_SOURCE}`,\n )() as CanvasHookInstaller;\n return install(scope);\n}\n","/**\n * Page-realm guest side of the live `<canvas>` pixel lane, for Tempo's\n * component **interact** iframe.\n *\n * Pooled offscreen frames get this lane from their Electron preload. An\n * interact iframe has no preload — it is the user's own page — so the lane is\n * installed from here, by the head-prepended `/@tempo/interact-projection`\n * module script, and the port arrives as a `postMessage` transfer from the\n * parent window instead of over the frame-pool channel.\n *\n * Running as a page script rather than a preload costs one thing:\n * `installPreserveDrawingBuffer` only affects contexts created after it, so a\n * WebGL context created earlier reads back blank. The plugin prepends this\n * script to `<head>`, ahead of the app's own module scripts, so that gap stays\n * theoretical. (`installDrawTracker` wraps the context PROTOTYPES, so contexts\n * created before it are tracked either way.)\n */\n\nimport {\n CANVAS_FRAME_LANE_WINDOW_PORT,\n installDrawTracker,\n installPreserveDrawingBuffer,\n serveCanvasFrameLanes,\n} from \"../../../modules/iframe-projection/canvas-frames/index.ts\";\n\n/**\n * Patch this document's canvas APIs and serve every lane port the parent\n * delivers. Returns a disposer that stops the lanes and restores the patches.\n */\nexport function installTempoInteractCanvasFrameLane(): () => void {\n const restoreDrawingBuffer = installPreserveDrawingBuffer(globalThis);\n const tracker = installDrawTracker(globalThis);\n\n const disposeLanes = serveCanvasFrameLanes(\n (deliver) => {\n // Only this document's parent may hand it a lane port; a sibling frame\n // or an injected script cannot (`accept` closes anyone else's port).\n const onMessage = (event: MessageEvent) => {\n const hit = CANVAS_FRAME_LANE_WINDOW_PORT.accept(event, window.parent);\n if (hit) deliver(hit.port);\n };\n window.addEventListener(\"message\", onMessage);\n return () => window.removeEventListener(\"message\", onMessage);\n },\n {\n tracker,\n // The interact producer's projection root is the document body unless\n // the renderer named a capture selector, so the rootId is never used.\n resolveRoot: (_rootId, selector) =>\n selector ? document.querySelector(selector) : document.body,\n },\n );\n\n return () => {\n disposeLanes();\n tracker.dispose();\n restoreDrawingBuffer();\n };\n}\n","import { startCombinedSourceInterface } from \"../../../modules/iframe-projection/combined/postmessage.ts\";\nimport type { FiberRoot } from \"../../../modules/iframe-projection/fiber/react-types.ts\";\nimport { initHook } from \"../../../modules/iframe-projection/fiber/watch.ts\";\nimport { installTempoInteractCanvasFrameLane } from \"./interact-canvas-frames.ts\";\nimport { isTempoInteractFrameName } from \"./interact-frame.ts\";\n\nconst PENDING_ROOTS_KEY = \"__tempoPendingFiberRoots\";\n\ntype BootstrapHook = ReturnType<typeof initHook>[\"hook\"] & {\n [PENDING_ROOTS_KEY]?: Map<number, FiberRoot>;\n};\n\n/**\n * Starts the combined DOM + React source used by Tempo's direct interact iframe.\n * The Vite plugin installs a synchronous hook first; replaying its latest roots\n * here closes the small gap while this lazy client module is loading.\n */\nexport function installTempoInteractProjectionSource(): () => void {\n if (\n typeof window === \"undefined\" ||\n window.parent === window ||\n !isTempoInteractFrameName(window.name)\n ) {\n return () => {};\n }\n\n const hookInterface = initHook();\n const hook = hookInterface.hook as BootstrapHook;\n const pendingRoots = hook[PENDING_ROOTS_KEY];\n if (pendingRoots) {\n hookInterface.seedCommittedRoots(pendingRoots);\n pendingRoots.clear();\n delete hook[PENDING_ROOTS_KEY];\n }\n\n // The DOM projection mirrors a `<canvas>` as an empty element; this lane\n // carries its pixels. Installed before the projection source so the canvas\n // prototypes are patched as early in the document as this script runs.\n const disposeCanvasFrames = installTempoInteractCanvasFrameLane();\n const disposeProjection = startCombinedSourceInterface();\n\n return () => {\n disposeProjection();\n disposeCanvasFrames();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKO,SAAS,wBACd,OACgC;AAChC,SACE,MAAM,QAAQ,KAAK,KACnB,MAAM,SAAS,KACf,MAAM;AAAA,IACJ,CAAC,SACC,MAAM,QAAQ,IAAI,KAClB,KAAK,SAAS,KACd,KAAK,MAAM,CAAC,OAAO,OAAO,OAAO,YAAY,GAAG,SAAS,CAAC;AAAA,EAC9D;AAEJ;;;ACfO,SAAS,oBAAoB;AAClC,MAAI,OAAO;AACX,QAAM,UAAU,oBAAI,IAAwB;AAC5C,SAAO;AAAA,IACL,aAAa,UAA0C;AACrD,YAAM,KAAK,EAAE;AACb,UAAI;AACJ,YAAMA,YAAW,WAAW;AAC5B,YA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eFile","isNonNegativeInteger","instance","live","raw","visit","options","visit","coordinates","perf","absentFiles","accumulated","patch","options","visit","boundary","bytes","visit","visit","document","normalizeTempoDataSet","hasContextDependencies","coordinateOnlyPortalIds","change","install","isRecord","isRecord"]}
|