tempo-sdk 0.0.19 → 0.0.20

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../modules/iframe-projection/fiber/react-types.ts","../../../../modules/iframe-projection/fiber/serialize.ts","../../../../modules/iframe-projection/fiber/capture.ts","../../../../modules/iframe-projection/fiber/utils.ts","../../../../modules/iframe-projection/fiber/watch.ts","../../../../modules/iframe-projection/combined/realm-epoch.ts","../../../../modules/iframe-projection/html/declared-facts.ts","../../../../modules/iframe-projection/html/displayability.ts","../../../../modules/iframe-projection/html/selectors.ts","../../../../modules/iframe-projection/html/capture.ts","../../../../modules/iframe-projection/html/watch-head.ts","../../../../modules/iframe-projection/html/watch-dom.ts","../../../../modules/iframe-projection/html/watch-state.ts","../../../../modules/iframe-projection/html/watch-portal.ts","../../../../modules/iframe-projection/html/snapshot.ts","../../../../modules/iframe-projection/shared/portal-tracker.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","../../canvas/interact-projection.ts"],"sourcesContent":["/**\n * React Internal Types\n *\n * These types are copied from React's source code. They are internal to React\n * and not exported publicly, so we define them here for type safety.\n *\n * ## Sources\n *\n * - Fiber, FiberRoot: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactInternalTypes.js\n * - WorkTags: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactWorkTags.js\n * - Hooks: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberHooks.js\n * - Memo/ForwardRef/Lazy: https://github.com/facebook/react/blob/main/packages/react/src/\n *\n * ## Stability\n *\n * These structures have been stable since React 16 (Fiber architecture).\n * Major changes are rare, but this file should be updated if React's\n * internals change significantly.\n */\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fiber Tags (WorkTag)\n// From: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactWorkTags.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * React Fiber tag values (WorkTag).\n *\n * These identify what kind of node a fiber represents and determine:\n * - How React processes the fiber during reconciliation\n * - What `stateNode` contains (DOM node, class instance, null)\n * - How `memoizedState` is structured (hooks list, class state, etc.)\n */\nexport const FiberTag = {\n /** Function component: `function MyComponent(props) { ... }` */\n FunctionComponent: 0,\n\n /** Class component: `class MyComponent extends React.Component` */\n ClassComponent: 1,\n\n /**\n * Component not yet determined to be function or class.\n * React resolves this on first render, then updates the tag.\n */\n IndeterminateComponent: 2,\n\n /** Root of a React tree (created by createRoot/render) */\n HostRoot: 3,\n\n /** React Portal: renders children into a different DOM container */\n HostPortal: 4,\n\n /** DOM element: div, span, button, etc. */\n HostComponent: 5,\n\n /** Text node: string/number children */\n HostText: 6,\n\n /** React.Fragment or <>...</> */\n Fragment: 7,\n\n /** StrictMode, ConcurrentMode, etc. */\n Mode: 8,\n\n /** Context.Consumer (legacy pattern) */\n ContextConsumer: 9,\n\n /** Context.Provider */\n ContextProvider: 10,\n\n /** React.forwardRef wrapper */\n ForwardRef: 11,\n\n /** React.Profiler for performance measurements */\n Profiler: 12,\n\n /** React.Suspense boundary */\n SuspenseComponent: 13,\n\n /** React.memo() wrapper */\n MemoComponent: 14,\n\n /** Simplified memo (internal optimization) */\n SimpleMemoComponent: 15,\n\n /** React.lazy() wrapper for code splitting */\n LazyComponent: 16,\n\n /** Incomplete class component (errored during render) */\n IncompleteClassComponent: 17,\n\n /** Dehydrated Suspense boundary (server-rendered) */\n DehydratedFragment: 18,\n\n /** SuspenseList for coordinating reveal order */\n SuspenseListComponent: 19,\n\n /** Scope component (experimental) */\n ScopeComponent: 21,\n\n /** Offscreen component (experimental, powers Activity) */\n OffscreenComponent: 22,\n\n /** Legacy hidden component (deprecated) */\n LegacyHiddenComponent: 23,\n\n /** Cache component (experimental) */\n CacheComponent: 24,\n\n /** Tracing marker (experimental) */\n TracingMarkerComponent: 25,\n\n /** Hoistable elements like <title>, <meta> (React 18.3+) */\n HostHoistable: 26,\n\n /** Singleton elements like <html>, <head>, <body> (React 18.3+) */\n HostSingleton: 27,\n} as const;\n\nexport type FiberTagValue = (typeof FiberTag)[keyof typeof FiberTag];\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Component Types (fiber.type)\n// From: https://github.com/facebook/react/blob/main/packages/react/src/\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** A React function component */\nexport interface FunctionComponent<P = Record<string, unknown>> {\n (props: P): unknown; // Returns ReactNode\n displayName?: string;\n name?: string;\n}\n\n/** A React class component constructor */\nexport interface ClassComponent<P = Record<string, unknown>> {\n new (props: P): { render(): unknown };\n displayName?: string;\n name?: string;\n}\n\n/**\n * React.memo() wrapper.\n * From: https://github.com/facebook/react/blob/main/packages/react/src/ReactMemo.js\n */\nexport interface MemoComponent<P = Record<string, unknown>> {\n $$typeof: symbol; // Symbol.for('react.memo')\n type: FunctionComponent<P> | ClassComponent<P>;\n compare: ((prevProps: P, nextProps: P) => boolean) | null;\n}\n\n/**\n * React.forwardRef() wrapper.\n * From: https://github.com/facebook/react/blob/main/packages/react/src/ReactForwardRef.js\n */\nexport interface ForwardRefComponent<P = Record<string, unknown>> {\n $$typeof: symbol; // Symbol.for('react.forward_ref')\n render: FunctionComponent<P>;\n displayName?: string;\n}\n\n/**\n * React.lazy() wrapper.\n * From: https://github.com/facebook/react/blob/main/packages/react/src/ReactLazy.js\n */\nexport interface LazyComponent {\n $$typeof: symbol; // Symbol.for('react.lazy')\n _payload: {\n _status: -1 | 0 | 1 | 2; // Uninitialized, Pending, Resolved, Rejected\n _result: unknown;\n };\n _init: (payload: unknown) => FunctionComponent | ClassComponent;\n}\n\n/**\n * Context.Provider type.\n */\nexport interface ContextProvider<T = unknown> {\n $$typeof: symbol; // Symbol.for('react.provider') or Symbol.for('react.context')\n _context: {\n Provider: unknown;\n Consumer: unknown;\n _currentValue: T;\n displayName?: string;\n };\n}\n\n/** All possible values for fiber.type */\nexport type FiberType =\n | string // HostComponent: \"div\", \"span\", etc.\n | FunctionComponent\n | ClassComponent\n | MemoComponent\n | ForwardRefComponent\n | LazyComponent\n | ContextProvider\n | symbol // Fragment, StrictMode, Profiler, etc.\n | null; // HostText\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hooks (fiber.memoizedState for FunctionComponent)\n// From: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberHooks.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * React Hook object (linked list node).\n *\n * For function components, fiber.memoizedState is the head of a linked list\n * of Hook objects, one for each hook call in the component.\n */\nexport interface Hook {\n /**\n * The current value of this hook. Contents depend on hook type:\n * - useState/useReducer: the state value\n * - useRef: { current: T }\n * - useMemo: [memoizedValue, dependencies]\n * - useCallback: [callback, dependencies]\n * - useEffect/useLayoutEffect: Effect object\n * - useContext: the context value\n */\n memoizedState: unknown;\n\n /** Base state for updates (used during state transitions) */\n baseState: unknown;\n\n /** Base queue of updates */\n baseQueue: HookUpdate | null;\n\n /** Queue of pending updates. Present for useState/useReducer, null for others */\n queue: HookQueue | null;\n\n /** Next hook in the linked list */\n next: Hook | null;\n}\n\n/**\n * Update queue for useState/useReducer.\n */\nexport interface HookQueue<S = unknown, A = unknown> {\n pending: HookUpdate<S, A> | null;\n lanes: number;\n dispatch: ((action: A) => void) | null;\n lastRenderedReducer: ((state: S, action: A) => S) | null;\n lastRenderedState: S | null;\n}\n\n/**\n * A state update object (circular linked list).\n */\nexport interface HookUpdate<S = unknown, A = unknown> {\n lane: number;\n revertLane: number;\n action: A;\n hasEagerState: boolean;\n eagerState: S | null;\n next: HookUpdate<S, A>;\n}\n\n/**\n * Effect hook object (memoizedState for useEffect/useLayoutEffect).\n */\nexport interface Effect {\n /** Effect type tag (HasEffect, Passive, Layout, etc.) */\n tag: number;\n /** The effect function */\n create: () => (() => void) | void;\n /** The cleanup function returned by create */\n destroy: (() => void) | undefined;\n /** Dependencies array */\n deps: unknown[] | null;\n /** Next effect in the circular linked list */\n next: Effect;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Ref Types\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Ref object created by useRef or createRef */\nexport interface RefObject<T = unknown> {\n current: T;\n}\n\n/** Callback ref function */\nexport type RefCallback<T = unknown> = (instance: T | null) => void;\n\n/** All possible values for fiber.ref */\nexport type FiberRef<T = unknown> = RefObject<T> | RefCallback<T> | null;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Props Type\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Props object passed to components */\nexport type FiberProps = Record<string, unknown> & {\n children?: unknown;\n};\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fiber\n// From: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactInternalTypes.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * React Fiber node.\n *\n * A fiber is a unit of work in React's rendering engine. It maintains\n * component identity, state, tree relationships, and scheduling information.\n *\n * ## Key Properties for Serialization\n *\n * - `tag`: What kind of fiber (use FiberTag constants)\n * - `type`: The component function/class or DOM tag string\n * - `key`: React key prop for reconciliation\n * - `stateNode`: DOM element (HostComponent) or class instance (ClassComponent)\n * - `memoizedProps`: Current props\n * - `memoizedState`: Hooks linked list (FunctionComponent) or state object (ClassComponent)\n * - `child`/`sibling`/`return`: Tree navigation\n */\nexport interface Fiber {\n // ─── Core Identity ─────────────────────────────────────────────────────────\n\n /** Fiber type tag (FunctionComponent, HostComponent, etc.) */\n tag: FiberTagValue;\n\n /** Unique key among siblings (from key prop) */\n key: string | null;\n\n /** Element type for reconciliation (usually same as type) */\n elementType: FiberType;\n\n /**\n * The resolved function/class/string for this fiber.\n * - FunctionComponent: the function\n * - ClassComponent: the class constructor\n * - HostComponent: tag string (\"div\", \"span\", etc.)\n * - HostText: null\n */\n type: FiberType;\n\n /**\n * Local state associated with this fiber.\n * - HostComponent: the DOM Element\n * - HostText: the DOM Text node\n * - ClassComponent: the class instance\n * - HostRoot: the FiberRoot\n * - FunctionComponent: null\n */\n stateNode: Element | Text | object | null;\n\n // ─── Tree Structure ────────────────────────────────────────────────────────\n\n /** Parent fiber (\"return\" because processing returns to parent) */\n return: Fiber | null;\n\n /** First child (head of children linked list) */\n child: Fiber | null;\n\n /** Next sibling */\n sibling: Fiber | null;\n\n /** Position among siblings */\n index: number;\n\n // ─── Props and State ───────────────────────────────────────────────────────\n\n /** Ref attached to this fiber */\n ref: FiberRef;\n\n /** Ref cleanup function (React 19+) */\n refCleanup: (() => void) | null;\n\n /** Input props being processed */\n pendingProps: FiberProps;\n\n /** Props from most recent completed render */\n memoizedProps: FiberProps;\n\n /** Update queue */\n updateQueue: unknown;\n\n /**\n * State from most recent completed render.\n * - FunctionComponent: Hook linked list (first hook)\n * - ClassComponent: state object\n * - HostRoot: element to render\n */\n memoizedState: Hook | object | null;\n\n /** Context and event dependencies */\n dependencies: unknown;\n\n // ─── Effects and Flags ─────────────────────────────────────────────────────\n\n /** Bitfield of effects needed on this fiber */\n flags: number;\n\n /** Aggregate flags from descendants */\n subtreeFlags: number;\n\n /** Fibers to delete */\n deletions: Fiber[] | null;\n\n // ─── Scheduling ────────────────────────────────────────────────────────────\n\n /** Update lanes for this fiber */\n lanes: number;\n\n /** Aggregate lanes from descendants */\n childLanes: number;\n\n // ─── Alternate (Double Buffering) ──────────────────────────────────────────\n\n /**\n * Link to corresponding fiber in the alternate tree.\n *\n * React maintains current (on screen) and work-in-progress trees.\n * After commit, if you're on FiberRoot.current, alternate points to OLD tree.\n */\n alternate: Fiber | null;\n\n // ─── Mode ──────────────────────────────────────────────────────────────────\n\n /** Bitfield for StrictMode, ConcurrentMode, etc. */\n mode: number;\n\n // ─── Profiling (dev/profiling builds) ──────────────────────────────────────\n\n actualDuration?: number;\n actualStartTime?: number;\n selfBaseDuration?: number;\n treeBaseDuration?: number;\n\n // ─── Debug (dev only) ──────────────────────────────────────────────────────\n\n _debugInfo?: unknown;\n _debugOwner?: Fiber | null;\n _debugStack?: Error | null;\n _debugTask?: unknown;\n _debugNeedsRemount?: boolean;\n _debugHookTypes?: string[] | null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// FiberRoot\n// From: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactInternalTypes.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * FiberRoot - the root object for a React tree.\n *\n * Created by createRoot() or ReactDOM.render(). The `current` property\n * always points to the committed fiber tree (HostRoot fiber).\n */\nexport interface FiberRoot {\n /** The HostRoot fiber of the committed tree */\n current: Fiber;\n\n /** The DOM container element */\n containerInfo: Element;\n\n /** Whether this root is hydrating */\n hydrate: boolean;\n\n /** Pending work lanes */\n pendingLanes: number;\n\n /** Scheduler callback */\n callbackNode: unknown;\n callbackPriority: number;\n\n /** Suspense ping cache */\n pingCache: unknown;\n\n /** Completed work ready to commit */\n finishedWork: Fiber | null;\n\n /** Legacy context */\n context: object | null;\n pendingContext: object | null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DevTools Hook\n// From: https://github.com/facebook/react/blob/main/packages/react-devtools-shared/src/hook.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * React renderer info passed to hook.inject().\n */\nexport interface ReactRenderer {\n version: string;\n rendererPackageName?: string;\n bundleType?: number; // 0 = production, 1 = development\n findFiberByHostInstance?: (instance: unknown) => Fiber | null;\n}\n\n/**\n * The React DevTools global hook.\n *\n * Must be installed on `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` BEFORE\n * React loads. React checks for this exactly once at initialization.\n */\nexport interface DevToolsHook {\n /** Must be true for modern React (16+) to inject */\n supportsFiber: boolean;\n\n /** Map of renderer ID -> renderer info */\n renderers: Map<number, ReactRenderer>;\n\n /** Called by React to register itself. Returns renderer ID. */\n inject(renderer: ReactRenderer): number;\n\n /**\n * Called by React after each commit.\n * fiberRoot.current points to the freshly committed tree.\n */\n onCommitFiberRoot(\n rendererId: number,\n fiberRoot: FiberRoot,\n priority?: number,\n didError?: boolean\n ): void;\n\n /** Called when a fiber is about to unmount */\n onCommitFiberUnmount?(rendererId: number, fiber: Fiber): void;\n\n /** Dead code elimination check */\n checkDCE?(fn: Function): void;\n\n /** Called when render is scheduled */\n onScheduleFiberRoot?(): void;\n}\n\ndeclare global {\n interface Window {\n __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook;\n }\n}\n","/**\n * Fiber Serialization Helpers\n *\n * Utility functions for extracting data from React Fiber nodes.\n * Use these to build your custom serialize functions.\n *\n * @example\n * ```ts\n * import { getDisplayName, getTag, getProps, getKey } from './serialize';\n *\n * const mySerialize: SerializeFn<MyNode> = (fiber) => ({\n * name: getDisplayName(fiber),\n * tag: getTag(fiber),\n * key: getKey(fiber),\n * props: getProps(fiber),\n * });\n * ```\n */\n\nimport type { Fiber, FiberProps, Hook, FunctionComponent, ClassComponent, MemoComponent, ForwardRefComponent, FiberTagValue } from \"./react-types\";\nimport { FiberTag } from \"./react-types\";\nimport type { DefaultFiberNode, SerializeFn } from \"./types\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Name Resolution\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the display name of a fiber.\n *\n * Resolution order:\n * 1. type.displayName (explicit name set on component)\n * 2. type.name (function/class name)\n * 3. Wrapped component name (for memo/forwardRef)\n * 4. Tag-based fallback (\"Fragment\", \"#text\", etc.)\n */\nexport function getDisplayName(fiber: Fiber): string {\n const { type, tag } = fiber;\n\n // HostComponent: DOM elements have string type\n if (typeof type === \"string\") {\n return type;\n }\n\n // HostText: text nodes\n if (tag === FiberTag.HostText) {\n return \"#text\";\n }\n\n // Function/Class components\n if (typeof type === \"function\") {\n const fn = type as FunctionComponent | ClassComponent;\n return fn.displayName || fn.name || \"Anonymous\";\n }\n\n // Object types (memo, forwardRef, lazy, context)\n if (type && typeof type === \"object\") {\n // React.memo\n if (\"type\" in type && (type as MemoComponent).type) {\n const inner = (type as MemoComponent).type;\n if (typeof inner === \"function\") {\n return (inner as FunctionComponent).displayName || (inner as FunctionComponent).name || \"Memo\";\n }\n }\n\n // React.forwardRef\n if (\"render\" in type && (type as ForwardRefComponent).render) {\n const render = (type as ForwardRefComponent).render;\n return (type as ForwardRefComponent).displayName || render.displayName || render.name || \"ForwardRef\";\n }\n\n // Context.Provider\n if (\"_context\" in type) {\n const ctx = (type as { _context: { displayName?: string } })._context;\n return ctx.displayName ? `${ctx.displayName}.Provider` : \"Context.Provider\";\n }\n }\n\n // Tag-based fallbacks\n const tagNames: Partial<Record<number, string>> = {\n [FiberTag.HostRoot]: \"HostRoot\",\n [FiberTag.Fragment]: \"Fragment\",\n [FiberTag.Mode]: \"Mode\",\n [FiberTag.ContextConsumer]: \"Context.Consumer\",\n [FiberTag.ContextProvider]: \"Context.Provider\",\n [FiberTag.Profiler]: \"Profiler\",\n [FiberTag.SuspenseComponent]: \"Suspense\",\n [FiberTag.SuspenseListComponent]: \"SuspenseList\",\n [FiberTag.OffscreenComponent]: \"Offscreen\",\n };\n\n return tagNames[tag] || `Unknown(${tag})`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Basic Accessors\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Get the fiber's tag value */\nexport function getTag(fiber: Fiber): FiberTagValue {\n return fiber.tag as FiberTagValue;\n}\n\n/** Get the fiber's key (null if not set) */\nexport function getKey(fiber: Fiber): string | null {\n return fiber.key;\n}\n\n/** Get the fiber's index among siblings */\nexport function getIndex(fiber: Fiber): number {\n return fiber.index;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Props\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the fiber's current props.\n *\n * Returns memoizedProps which reflect the most recent render.\n */\nexport function getProps(fiber: Fiber): FiberProps {\n return fiber.memoizedProps;\n}\n\n/**\n * Sanitize props for serialization.\n *\n * - Removes `children` (handled separately in tree)\n * - Converts functions to \"[Function]\"\n * - Converts DOM elements to \"[Element:tagName]\"\n * - Converts React elements to \"[ReactElement]\"\n * - Deep clones serializable objects\n * - Falls back to \"[Object]\" for non-serializable values\n */\nexport function sanitizeProps(props: FiberProps | null): Record<string, unknown> | undefined {\n if (!props) return undefined;\n\n const result: Record<string, unknown> = {};\n let hasProps = false;\n\n for (const [key, value] of Object.entries(props)) {\n // Skip children - handled in tree structure\n if (key === \"children\") continue;\n\n hasProps = true;\n result[key] = sanitizeValue(value);\n }\n\n return hasProps ? result : undefined;\n}\n\n/**\n * Sanitize a single value for serialization.\n */\nexport function sanitizeValue(value: unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n if (typeof value === \"function\") {\n return \"[Function]\";\n }\n\n if (typeof value === \"symbol\") {\n return `[Symbol:${value.description ?? \"\"}]`;\n }\n\n if (value instanceof Element) {\n return `[Element:${value.tagName.toLowerCase()}${value.id ? `#${value.id}` : \"\"}]`;\n }\n\n if (value instanceof Node) {\n return `[Node:${value.nodeName}]`;\n }\n\n if (Array.isArray(value)) {\n // For small arrays, serialize contents\n if (value.length <= 10) {\n return value.map(sanitizeValue);\n }\n return `[Array(${value.length})]`;\n }\n\n if (typeof value === \"object\") {\n // React element\n if (\"$$typeof\" in value) {\n return \"[ReactElement]\";\n }\n\n // Try to deep clone\n try {\n return JSON.parse(JSON.stringify(value));\n } catch {\n return \"[Object]\";\n }\n }\n\n // Primitives pass through\n return value;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// State Node (DOM Element)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the DOM element for a HostComponent fiber.\n *\n * Returns null for non-host fibers or if stateNode isn't an Element.\n */\nexport function getDomElement(fiber: Fiber): Element | null {\n if (fiber.tag !== FiberTag.HostComponent) {\n return null;\n }\n return fiber.stateNode instanceof Element ? fiber.stateNode : null;\n}\n\n/**\n * Get the Text node for a HostText fiber.\n */\nexport function getTextNode(fiber: Fiber): Text | null {\n if (fiber.tag !== FiberTag.HostText) {\n return null;\n }\n return fiber.stateNode instanceof Text ? fiber.stateNode : null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hooks (Function Components)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the hooks linked list for a function component.\n *\n * Returns null for non-function components or components without hooks.\n */\nexport function getHooks(fiber: Fiber): Hook | null {\n if (fiber.tag !== FiberTag.FunctionComponent) {\n return null;\n }\n // memoizedState is the head of the hooks linked list\n return fiber.memoizedState as Hook | null;\n}\n\n/**\n * Iterate over all hooks in a function component.\n *\n * @example\n * ```ts\n * for (const hook of iterateHooks(fiber)) {\n * console.log(hook.memoizedState);\n * }\n * ```\n */\nexport function* iterateHooks(fiber: Fiber): Generator<Hook> {\n let hook = getHooks(fiber);\n let count = 0;\n const maxHooks = 100; // Safety limit\n\n while (hook && count < maxHooks) {\n yield hook;\n hook = hook.next;\n count++;\n }\n}\n\n/**\n * Extract hook values as an array.\n *\n * Returns array of memoizedState values for each hook.\n */\nexport function getHookValues(fiber: Fiber): unknown[] {\n const values: unknown[] = [];\n for (const hook of iterateHooks(fiber)) {\n values.push(hook.memoizedState);\n }\n return values;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Tree Navigation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Iterate over a fiber's children.\n *\n * @example\n * ```ts\n * for (const child of iterateChildren(fiber)) {\n * console.log(getDisplayName(child));\n * }\n * ```\n */\nexport function* iterateChildren(fiber: Fiber): Generator<Fiber> {\n let child = fiber.child;\n while (child) {\n yield child;\n child = child.sibling;\n }\n}\n\n/**\n * Get all children as an array.\n */\nexport function getChildren(fiber: Fiber): Fiber[] {\n return [...iterateChildren(fiber)];\n}\n\n/**\n * Walk up the tree to find the root fiber.\n *\n * Important: Uses FiberRoot.current to get the committed tree,\n * avoiding stale data from the work-in-progress tree.\n */\nexport function findRootFiber(fiber: Fiber): Fiber {\n // Walk up to HostRoot\n let current = fiber;\n while (current.return) {\n current = current.return;\n }\n\n // HostRoot's stateNode is FiberRoot, which has `.current`\n // pointing to the committed tree's root\n const stateNode = current.stateNode;\n if (\n stateNode &&\n typeof stateNode === \"object\" &&\n \"current\" in stateNode &&\n (stateNode as { current: Fiber }).current\n ) {\n return (stateNode as { current: Fiber }).current;\n }\n\n return current;\n}\n\n/**\n * Resolve a fiber to its committed-tree version.\n *\n * React double-buffers fibers: each host instance has up to two fiber\n * objects (`fiber` and `fiber.alternate`) that swap the \"current\" role on\n * every commit. The `__reactFiber$` pointer a DOM element carries is stamped\n * once at mount and never re-pointed, so after an odd number of commits it\n * refers to the NON-committed generation — its `memoizedProps` (and the\n * whole subtree walked from it) are one commit stale.\n *\n * Both generations' HostRoot fibers share one `FiberRoot` stateNode, but a\n * bailout can also make the generations share intermediate child lists. Walk\n * both return paths and use parent-child membership to preserve which original\n * endpoint each path represents, matching React's own current-fiber slow path.\n *\n * A fiber with no alternate that fails the check is kept as-is (a freshly\n * mounted node exists in only one generation; a detached fiber has no\n * better answer).\n */\nexport function resolveCommittedFiber(fiber: Fiber): Fiber {\n const alternate = fiber.alternate;\n if (!alternate) {\n return fiber;\n }\n\n let a = fiber;\n let b = alternate;\n for (;;) {\n const parentA = a.return;\n if (!parentA) break;\n const parentB = parentA.alternate;\n if (!parentB) {\n const nextParent = parentA.return;\n if (nextParent) {\n a = nextParent;\n b = nextParent;\n continue;\n }\n break;\n }\n\n if (parentA.child === parentB.child) {\n for (let child = parentA.child; child; child = child.sibling) {\n if (child === a) return fiber;\n if (child === b) return alternate;\n }\n throw new Error(\"Unable to resolve a mounted React fiber\");\n }\n\n if (a.return !== b.return) {\n a = parentA;\n b = parentB;\n } else {\n let found = false;\n for (let child = parentA.child; child; child = child.sibling) {\n if (child === a) {\n found = true;\n a = parentA;\n b = parentB;\n break;\n }\n if (child === b) {\n found = true;\n a = parentB;\n b = parentA;\n break;\n }\n }\n if (!found) {\n for (let child = parentB.child; child; child = child.sibling) {\n if (child === a) {\n found = true;\n a = parentB;\n b = parentA;\n break;\n }\n if (child === b) {\n found = true;\n a = parentA;\n b = parentB;\n break;\n }\n }\n }\n if (!found) {\n throw new Error(\"React fiber is absent from both parent generations\");\n }\n }\n\n if (a.alternate !== b) {\n throw new Error(\"React return fibers are not paired alternates\");\n }\n }\n\n if (a.tag !== FiberTag.HostRoot) {\n throw new Error(\"Unable to resolve an unmounted React fiber\");\n }\n const fiberRoot = a.stateNode as { current?: Fiber } | null;\n return fiberRoot?.current === a ? fiber : alternate;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Type Guards\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Check if fiber is a function component */\nexport function isFunctionComponent(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.FunctionComponent;\n}\n\n/** Check if fiber is a class component */\nexport function isClassComponent(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.ClassComponent;\n}\n\n/** Check if fiber is a React component (function or class) */\nexport function isComponent(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.FunctionComponent || fiber.tag === FiberTag.ClassComponent;\n}\n\n/** Check if fiber is a DOM element */\nexport function isHostComponent(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.HostComponent;\n}\n\n/** Check if fiber is a text node */\nexport function isHostText(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.HostText;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Default Serializer\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Default serialize function.\n *\n * Produces nodes with just name and tag - the minimal representation.\n */\nexport const defaultSerialize: SerializeFn<DefaultFiberNode> = (fiber) => ({\n name: getDisplayName(fiber),\n tag: getTag(fiber),\n});\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Tree Serialization\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Options for serializeTree.\n */\nexport interface SerializeOptions {\n /** Maximum depth to traverse (default: unlimited) */\n maxDepth?: number;\n /** Whether to skip text nodes (default: true) */\n skipText?: boolean;\n}\n\n/**\n * Serialize a fiber tree using the provided serialize function.\n *\n * This is the core serialization function. It handles:\n * - Recursive tree traversal via child/sibling links\n * - Building children arrays\n * - Depth limiting\n * - Optional text node skipping\n *\n * @param fiber - Root fiber to serialize from\n * @param serialize - Function to serialize each fiber\n * @param options - Serialization options\n */\nexport function serializeTree<T extends { children: T[] }>(\n fiber: Fiber,\n serialize: (fiber: Fiber) => Omit<T, \"children\">,\n options: SerializeOptions = {}\n): T | null {\n const { maxDepth = Infinity, skipText = true } = options;\n\n function serializeNode(f: Fiber, depth: number): T | null {\n if (depth > maxDepth) return null;\n\n // Optionally skip text nodes\n if (skipText && f.tag === FiberTag.HostText) {\n return null;\n }\n\n // Serialize this node (without children)\n const nodeData = serialize(f);\n\n // Recursively serialize children\n const children: T[] = [];\n for (const child of iterateChildren(f)) {\n const serialized = serializeNode(child, depth + 1);\n if (serialized) {\n children.push(serialized);\n }\n }\n\n // Combine node data with children\n return { ...nodeData, children } as T;\n }\n\n return serializeNode(fiber, 0);\n}\n","/**\n * Fiber Tree Capture\n *\n * One-shot capture of a React fiber tree from a DOM element.\n *\n * @example\n * ```ts\n * // Default capture (name + tag)\n * const tree = capture(document.getElementById('root'));\n *\n * // Custom capture with more data\n * const tree = capture(rootEl, (fiber) => ({\n * name: getDisplayName(fiber),\n * tag: fiber.tag,\n * props: sanitizeProps(fiber.memoizedProps),\n * }));\n * ```\n */\n\nimport type { Fiber } from \"./react-types\";\nimport { FiberTag } from \"./react-types\";\nimport type { FiberNode, FiberNodeConstraint, DefaultFiberNode, SerializeFn } from \"./types\";\nimport { defaultSerialize, serializeTree, findRootFiber, type SerializeOptions } from \"./serialize\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fiber Access from DOM\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Find the React fiber key on a DOM element.\n *\n * React attaches fibers to DOM elements using keys like `__reactFiber$abc123`.\n * The suffix is unique per React instance but consistent across all elements.\n */\nfunction findFiberKey(element: Element): string | null {\n return (\n Object.keys(element).find(\n (k) => k.startsWith(\"__reactFiber$\") || k.startsWith(\"__reactInternalInstance$\")\n ) ?? null\n );\n}\n\n/**\n * Find the React container key on a root element.\n *\n * Root containers (like #root) have `__reactContainer$` instead of `__reactFiber$`.\n */\nfunction findContainerKey(element: Element): string | null {\n return Object.keys(element).find((k) => k.startsWith(\"__reactContainer$\")) ?? null;\n}\n\n/**\n * Get the React fiber from a DOM element.\n *\n * Works with both regular elements (__reactFiber$) and\n * root containers (__reactContainer$).\n */\nexport function getFiberFromElement(element: Element): Fiber | null {\n // Try standard fiber key first\n const fiberKey = findFiberKey(element);\n if (fiberKey) {\n return (element as unknown as Record<string, Fiber>)[fiberKey] ?? null;\n }\n\n // For root containers, try container key\n const containerKey = findContainerKey(element);\n if (containerKey) {\n return (element as unknown as Record<string, Fiber>)[containerKey] ?? null;\n }\n\n return null;\n}\n\n/**\n * Check if React fiber data is available on this element.\n */\nexport function hasFiber(element: Element): boolean {\n return findFiberKey(element) !== null || findContainerKey(element) !== null;\n}\n\n/**\n * Check if any element in the document has React fiber data.\n *\n * Useful for detecting if React is present and has rendered.\n */\nexport function isReactAvailable(): boolean {\n const elements = document.querySelectorAll(\"*\");\n for (const el of elements) {\n if (hasFiber(el)) return true;\n }\n return false;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Capture\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Options for capture().\n */\nexport interface CaptureOptions extends SerializeOptions {\n /**\n * Whether to start from the committed root fiber.\n *\n * If true (default), walks up from the element's fiber to find the\n * root, then uses FiberRoot.current to ensure we're reading from\n * the committed tree (not the stale work-in-progress tree).\n *\n * If false, starts directly from the element's fiber.\n */\n fromRoot?: boolean;\n}\n\n/**\n * Capture the fiber tree from a DOM element.\n *\n * ## Default Behavior\n *\n * Returns nodes with `name`, `tag`, and `children`. This is the minimal\n * representation that captures the tree structure.\n *\n * ## Custom Serialization\n *\n * Pass a serialize function to control exactly what data each node has.\n * Your function receives the raw Fiber and returns everything except\n * `children` (we handle the recursion).\n *\n * @param element - DOM element to capture from\n * @param serialize - Optional custom serialize function\n * @param options - Capture options\n *\n * @example\n * ```ts\n * // Default capture\n * const tree = capture(document.getElementById('root'));\n * // tree: { name: \"App\", tag: 0, children: [...] }\n *\n * // Custom capture with props\n * interface MyNode {\n * name: string;\n * tag: number;\n * props?: Record<string, unknown>;\n * children: MyNode[];\n * }\n *\n * const tree = capture<MyNode>(rootEl, (fiber) => ({\n * name: getDisplayName(fiber),\n * tag: fiber.tag,\n * props: sanitizeProps(fiber.memoizedProps),\n * }));\n * ```\n */\nexport function capture(\n element: Element,\n options?: CaptureOptions\n): FiberNode<DefaultFiberNode> | null;\n\nexport function capture<T extends FiberNodeConstraint>(\n element: Element,\n serialize: SerializeFn<T>,\n options?: CaptureOptions\n): FiberNode<T> | null;\n\nexport function capture<T extends FiberNodeConstraint = DefaultFiberNode>(\n element: Element,\n serializeOrOptions?: SerializeFn<T> | CaptureOptions,\n maybeOptions?: CaptureOptions\n): FiberNode<T> | null {\n // Parse overloaded arguments\n let serialize: SerializeFn<T>;\n let options: CaptureOptions;\n\n if (typeof serializeOrOptions === \"function\") {\n serialize = serializeOrOptions;\n options = maybeOptions ?? {};\n } else {\n serialize = defaultSerialize as unknown as SerializeFn<T>;\n options = serializeOrOptions ?? {};\n }\n\n const { fromRoot = true, ...serializeOptions } = options;\n\n // Get fiber from element\n let fiber = getFiberFromElement(element);\n if (!fiber) {\n return null;\n }\n\n // Navigate to committed root if requested\n if (fromRoot) {\n const root = findRootFiber(fiber);\n // Start from first child of HostRoot (the app component)\n if (root.tag === FiberTag.HostRoot && root.child) {\n fiber = root.child;\n } else {\n fiber = root;\n }\n }\n\n // Serialize the tree\n return serializeTree(fiber, serialize, serializeOptions);\n}\n","/**\n * Fiber Tree Utilities\n *\n * Utility functions for working with serialized fiber trees.\n */\n\nimport type { FiberNodeConstraint, FiberTagValue } from \"./types\";\n\n/**\n * Filter a fiber tree, removing nodes with excluded tags.\n *\n * When a node is filtered out, its children are promoted to take its place\n * (recursively filtered as well). This allows hiding wrapper nodes like\n * Fragment, Mode, or ContextProvider while preserving the tree structure.\n *\n * @param tree - The root node (or null)\n * @param excludeTags - Set of tag values to exclude\n * @returns The filtered tree, or null if root was filtered and had no children\n *\n * @example\n * ```ts\n * import { FiberTag } from './types';\n *\n * // Filter out Fragment (7) and Mode (8) nodes\n * const filtered = filterTree(tree, new Set([\n * FiberTag.Fragment,\n * FiberTag.Mode,\n * ]));\n * ```\n *\n * @example\n * ```ts\n * // Hide common wrapper nodes\n * const WRAPPER_TAGS = new Set([\n * 7, // Fragment\n * 8, // Mode\n * 10, // ContextProvider\n * 11, // ForwardRef\n * 14, // MemoComponent\n * 15, // SimpleMemoComponent\n * ]);\n * const filtered = filterTree(tree, WRAPPER_TAGS);\n * ```\n */\nexport function filterTree<T extends FiberNodeConstraint & { tag: number }>(\n tree: T | null,\n excludeTags: Set<number>\n): T | null {\n if (tree === null) return null;\n\n // If root is excluded, promote its children (but there can only be one root)\n if (excludeTags.has(tree.tag)) {\n // Recursively filter children and return the first one (promoting it to root)\n const filteredChildren = filterChildren(tree.children, excludeTags);\n return filteredChildren.length > 0 ? filteredChildren[0]! : null;\n }\n\n // Root is not excluded, filter its children\n return {\n ...tree,\n children: filterChildren(tree.children, excludeTags),\n };\n}\n\n/**\n * Filter an array of children, promoting grandchildren when a child is filtered.\n */\nfunction filterChildren<T extends FiberNodeConstraint & { tag: number }>(\n children: T[],\n excludeTags: Set<number>\n): T[] {\n const result: T[] = [];\n\n for (const child of children) {\n if (excludeTags.has(child.tag)) {\n // Child is excluded - promote its filtered children\n const grandchildren = filterChildren(child.children, excludeTags);\n result.push(...grandchildren);\n } else {\n // Child is kept - recursively filter its children\n result.push({\n ...child,\n children: filterChildren(child.children, excludeTags),\n });\n }\n }\n\n return result;\n}\n\n/**\n * Common wrapper tags that can be hidden without losing semantic information.\n */\nexport const WRAPPER_TAGS = new Set([\n 7, // Fragment\n 8, // Mode (StrictMode)\n 10, // ContextProvider\n 11, // ForwardRef\n 14, // MemoComponent\n 15, // SimpleMemoComponent\n]);\n\n/**\n * Create a filter set from tag values.\n * Convenience function for creating filter sets.\n */\nexport function createTagFilter(...tags: number[]): Set<number> {\n return new Set(tags);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Include-based Filtering\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Filter a fiber tree to only include nodes with specified tags.\n *\n * When a node is NOT in includeTags, it is removed and its children are\n * promoted to take its place (recursively filtered as well). This is the\n * inverse of filterTree which excludes tags.\n *\n * @param tree - The root node (or null)\n * @param includeTags - Set of tag values to keep\n * @returns The filtered tree, or null if root was filtered and had no children\n *\n * @example\n * ```ts\n * import { FiberTag } from './types';\n *\n * // Keep only FunctionComponent (0) and HostComponent (5) nodes\n * const filtered = filterTreeInclude(tree, new Set([\n * FiberTag.FunctionComponent,\n * FiberTag.HostComponent,\n * ]));\n * ```\n */\nexport function filterTreeInclude<T extends FiberNodeConstraint & { tag: FiberTagValue }>(\n tree: T | null,\n includeTags: Set<FiberTagValue>\n): T | null {\n if (tree === null) return null;\n\n // If root is NOT included, promote its children (but there can only be one root)\n if (!includeTags.has(tree.tag)) {\n const filteredChildren = filterChildrenInclude(tree.children, includeTags);\n return filteredChildren.length > 0 ? filteredChildren[0]! : null;\n }\n\n // Root is included, filter its children\n return {\n ...tree,\n children: filterChildrenInclude(tree.children, includeTags),\n };\n}\n\n/**\n * Filter an array of children, promoting grandchildren when a child is not included.\n */\nfunction filterChildrenInclude<T extends FiberNodeConstraint & { tag: FiberTagValue }>(\n children: T[],\n includeTags: Set<FiberTagValue>\n): T[] {\n const result: T[] = [];\n\n for (const child of children) {\n if (!includeTags.has(child.tag)) {\n // Child is NOT included - promote its filtered children\n const grandchildren = filterChildrenInclude(child.children, includeTags);\n result.push(...grandchildren);\n } else {\n // Child is included - keep it, recursively filter its children\n result.push({\n ...child,\n children: filterChildrenInclude(child.children, includeTags),\n });\n }\n }\n\n return result;\n}\n","/**\n * Fiber Tree Watching\n *\n * Stream fiber tree snapshots on React commits.\n *\n * ## Setup (Recommended)\n *\n * For guaranteed capture, call initHook() BEFORE React loads:\n *\n * ```ts\n * // At the VERY TOP of your entry file, before any React imports:\n * import { initHook } from '@modules/iframe-projection/fiber';\n *\n * initHook(); // Idempotent - safe to call multiple times\n *\n * // Now safe to import React\n * import React from 'react';\n * ```\n *\n * ## Watching\n *\n * After React mounts, call watch() to start receiving snapshots.\n * watch() will auto-initialize the hook if not already done.\n *\n * ```ts\n * const { stop } = watch((snapshot) => {\n * console.log('Tree updated:', snapshot.tree);\n * parent.postMessage(snapshot, '*');\n * });\n *\n * // Later: stop watching\n * stop();\n * ```\n *\n * ## How It Works\n *\n * - If no hook exists: creates one (works if called before React)\n * - If hook exists (e.g., DevTools extension): wraps it (works after React)\n * - If already initialized by us: reuses existing (idempotent)\n */\n\nimport { getFiberFromElement } from \"./capture\";\nimport type {\n DevToolsHook,\n Fiber,\n FiberRoot,\n ReactRenderer,\n} from \"./react-types\";\nimport { FiberTag } from \"./react-types\";\nimport {\n defaultSerialize,\n resolveCommittedFiber,\n serializeTree,\n type SerializeOptions,\n} from \"./serialize\";\nimport type {\n DefaultFiberNode,\n FiberNodeConstraint,\n FiberSnapshot,\n FiberTagValue,\n SerializeFn,\n} from \"./types\";\nimport { filterTreeInclude } from \"./utils\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// One-shot Capture (for validation)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Options for captureTree().\n */\nexport interface CaptureTreeOptions<\n T extends FiberNodeConstraint = DefaultFiberNode,\n> extends SerializeOptions {\n /**\n * CSS selector for the element to capture.\n * If not provided, captures the entire tree.\n */\n selector?: string;\n\n /**\n * Custom serialization function.\n * If not provided, uses defaultSerialize (name + tag).\n */\n serialize?: SerializeFn<T>;\n\n /**\n * Only include nodes with these tags in the tree.\n * Other nodes are filtered out and their children promoted.\n */\n tags?: FiberTagValue[];\n}\n\n/**\n * Capture the current fiber tree (one-shot).\n *\n * This uses the same logic as watch() to find the starting fiber,\n * ensuring consistency between watched deltas and captured snapshots.\n * Useful for validation that delta merging produces correct results.\n *\n * @returns The serialized tree, or null if no React root found\n *\n * @example\n * ```ts\n * // Capture full tree\n * const tree = captureTree();\n *\n * // Capture with same options as watcher\n * const tree = captureTree({ tags: [FiberTag.FunctionComponent] });\n * ```\n */\nexport function captureTree<T extends FiberNodeConstraint = DefaultFiberNode>(\n options: CaptureTreeOptions<T> = {},\n): T | null {\n const { selector, serialize, tags, ...serializeOptions } = options;\n const serializeFn =\n serialize ?? (defaultSerialize as unknown as SerializeFn<T>);\n const tagSet = tags && tags.length > 0 ? new Set(tags) : null;\n\n // Get hook\n const hook = getHook();\n if (!hook) return null;\n\n // Find a fiber root - try multiple approaches\n let fiberRoot: FiberRoot | null = null;\n\n // 1. Try lastCommittedRoots (populated by our hook)\n for (const roots of lastCommittedRoots.values()) {\n for (const root of roots) {\n if (root.current) {\n fiberRoot = root;\n break;\n }\n }\n if (fiberRoot) break;\n }\n\n // 2. Try renderer.getFiberRoots() if available\n if (!fiberRoot) {\n for (const [_id, renderer] of hook.renderers) {\n const roots = (renderer as any).getFiberRoots?.();\n if (roots) {\n for (const root of roots) {\n if (root?.current) {\n fiberRoot = root;\n break;\n }\n }\n }\n if (fiberRoot) break;\n }\n }\n\n if (!fiberRoot) return null;\n\n // Find start fiber\n let startFiber: Fiber | null = null;\n\n if (selector) {\n // With selector: find element and get its fiber, resolved to the\n // committed generation — the element's raw fiber pointer alternates\n // between the two double-buffered fibers as commits land, and the\n // stale one reads props from the PREVIOUS commit.\n const element = document.querySelector(selector);\n if (element) {\n const rawFiber = getFiberFromElement(element);\n startFiber = rawFiber ? resolveCommittedFiber(rawFiber) : null;\n }\n } else {\n // No selector: use first child of HostRoot (same as watch)\n const rootFiber = fiberRoot.current;\n if (rootFiber && rootFiber.tag === FiberTag.HostRoot && rootFiber.child) {\n startFiber = rootFiber.child;\n } else if (rootFiber) {\n startFiber = rootFiber;\n }\n }\n\n if (!startFiber) return null;\n\n // Serialize the tree\n let tree = serializeTree(startFiber, serializeFn, serializeOptions);\n\n // Apply tag filtering if specified\n if (tree && tagSet && \"tag\" in tree) {\n const filtered = filterTreeInclude(\n tree as unknown as FiberNodeConstraint & { tag: FiberTagValue },\n tagSet,\n );\n tree = filtered as unknown as typeof tree;\n }\n\n return tree;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hook Initialization\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Symbol to mark hooks we've initialized */\nconst HOOK_MARKER = Symbol.for(\"iframe-projection-fiber-hook\");\n\n/** Handler types */\ntype CommitHandler = (\n fiberRoot: FiberRoot,\n rendererId: number,\n didError: boolean,\n) => void;\ntype InjectHandler = (renderer: ReactRenderer, rendererId: number) => void;\ntype UnmountHandler = (fiber: Fiber, rendererId: number) => void;\n\n/**\n * Interface returned by initHook() for registering callbacks.\n */\nexport interface HookInterface {\n /** Add a handler called on each React commit. Returns unsubscribe function. */\n onCommit: (handler: CommitHandler) => () => void;\n /** Add a handler called when React registers. Returns unsubscribe function. */\n onInject: (handler: InjectHandler) => () => void;\n /** Add a handler called when a fiber unmounts. Returns unsubscribe function. */\n onUnmount: (handler: UnmountHandler) => () => void;\n /** The underlying DevTools hook object */\n hook: DevToolsHook;\n /** Seed commits captured by a synchronous pre-module bootstrap. This updates\n * iframe-projection's cache without re-delivering them to a wrapped hook. */\n seedCommittedRoots: (roots: Iterable<readonly [number, FiberRoot]>) => void;\n}\n\n/** Extended hook type with our marker */\ninterface MarkedHook extends DevToolsHook {\n [HOOK_MARKER]: HookInterface;\n}\n\n/** Cached interface (module-level singleton) */\nlet cachedInterface: HookInterface | null = null;\n\n/** Every live committed fiber root per renderer ID. One React renderer can own\n * multiple roots in the same document (micro-frontends, portals mounted through\n * separate roots, and test harnesses all do this). */\nconst lastCommittedRoots = new Map<number, Set<FiberRoot>>();\n\nfunction rememberCommittedRoot(rendererId: number, root: FiberRoot): void {\n const roots = lastCommittedRoots.get(rendererId) ?? new Set<FiberRoot>();\n for (const previous of roots) {\n if (previous !== root && previous.containerInfo === root.containerInfo) {\n roots.delete(previous);\n }\n }\n // A HostRoot with no child is still a live, authoritative `root.render(null)`\n // result. Retain it; document-scope filtering excludes roots whose containers\n // no longer belong to the watched surface.\n roots.add(root);\n lastCommittedRoots.set(rendererId, roots);\n}\n\n/** Current roots captured by the hook, in commit-insertion order. */\nexport function getCommittedFiberRoots(): FiberRoot[] {\n return [...lastCommittedRoots.values()].flatMap((roots) => [...roots]);\n}\n\n/**\n * Reset the hook state. For testing only.\n * @internal\n */\nexport function _resetHookForTesting(): void {\n cachedInterface = null;\n lastCommittedRoots.clear();\n}\n\n/**\n * Initialize the DevTools hook for fiber watching.\n *\n * This function is idempotent - safe to call multiple times:\n * - If no hook exists: creates a new one\n * - If a hook exists (e.g., DevTools extension): wraps it\n * - If already initialized by us: returns existing interface\n *\n * For best results, call this BEFORE React loads. But if React DevTools\n * extension is installed, calling after React loads still works.\n *\n * @example\n * ```ts\n * // At top of entry file (before React):\n * initHook();\n *\n * // Or get the interface for manual handler registration:\n * const { onCommit } = initHook();\n * const unsubscribe = onCommit((root, id) => console.log('Commit!'));\n * ```\n */\nexport function initHook(): HookInterface {\n // Return cached if available\n if (cachedInterface) {\n return cachedInterface;\n }\n\n // Check for existing hook\n const existing =\n typeof window !== \"undefined\"\n ? (window as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook })\n .__REACT_DEVTOOLS_GLOBAL_HOOK__\n : undefined;\n\n // Already initialized by us (in case cachedInterface was cleared somehow)\n if (existing && HOOK_MARKER in existing) {\n cachedInterface = (existing as MarkedHook)[HOOK_MARKER];\n return cachedInterface;\n }\n\n // Create handler sets\n const commitHandlers = new Set<CommitHandler>();\n const injectHandlers = new Set<InjectHandler>();\n const unmountHandlers = new Set<UnmountHandler>();\n\n // Helper to create add/remove functions\n const createRegistrar =\n <T>(set: Set<T>) =>\n (handler: T): (() => void) => {\n set.add(handler);\n return () => set.delete(handler);\n };\n\n // Callbacks that dispatch to all registered handlers\n const callbacks: HookCallbacks = {\n onCommit: (root, id, didError) => {\n // Store for immediate snapshots when watch() starts\n rememberCommittedRoot(id, root);\n commitHandlers.forEach((h) => h(root, id, didError));\n },\n onInject: (renderer, id) => injectHandlers.forEach((h) => h(renderer, id)),\n onUnmount: (fiber, id) => unmountHandlers.forEach((h) => h(fiber, id)),\n };\n\n let hook: DevToolsHook;\n\n if (existing) {\n // Wrap existing hook (preserves DevTools extension functionality)\n wrapDevToolsHook(existing, callbacks);\n hook = existing;\n } else {\n // Create new hook\n hook = createDevToolsHook(callbacks);\n if (typeof window !== \"undefined\") {\n (\n window as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook }\n ).__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook;\n }\n }\n\n // Build interface\n const hookInterface: HookInterface = {\n onCommit: createRegistrar(commitHandlers),\n onInject: createRegistrar(injectHandlers),\n onUnmount: createRegistrar(unmountHandlers),\n hook,\n seedCommittedRoots(roots) {\n for (const [rendererId, root] of roots) {\n rememberCommittedRoot(rendererId, root);\n }\n },\n };\n\n // Mark the hook so we recognize it later\n (hook as MarkedHook)[HOOK_MARKER] = hookInterface;\n cachedInterface = hookInterface;\n\n return hookInterface;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DevTools Hook\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Callbacks for DevTools hook events.\n */\nexport interface HookCallbacks {\n /** Called when React injects a renderer */\n onInject?: (renderer: ReactRenderer, id: number) => void;\n /** Called after each React commit */\n onCommit?: (\n fiberRoot: FiberRoot,\n rendererId: number,\n didError: boolean,\n ) => void;\n /** Called when a fiber unmounts */\n onUnmount?: (fiber: Fiber, rendererId: number) => void;\n}\n\n/**\n * Create a React DevTools hook.\n *\n * Install this on `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` BEFORE React loads.\n * React checks for this hook exactly once at initialization time.\n *\n * @param callbacks - Optional callbacks for hook events\n *\n * @example\n * ```ts\n * // Basic usage - just install the hook\n * window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = createDevToolsHook();\n *\n * // With callbacks\n * window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = createDevToolsHook({\n * onCommit: (root, id) => console.log('Commit!', root),\n * });\n * ```\n */\nexport function createDevToolsHook(callbacks?: HookCallbacks): DevToolsHook {\n const hook: DevToolsHook = {\n supportsFiber: true,\n renderers: new Map(),\n\n inject(renderer: ReactRenderer): number {\n const id = this.renderers.size + 1;\n this.renderers.set(id, renderer);\n callbacks?.onInject?.(renderer, id);\n return id;\n },\n\n onCommitFiberRoot(\n rendererId: number,\n fiberRoot: FiberRoot,\n _priority?: number,\n didError?: boolean,\n ): void {\n callbacks?.onCommit?.(fiberRoot, rendererId, didError === true);\n },\n\n onCommitFiberUnmount(rendererId: number, fiber: Fiber): void {\n callbacks?.onUnmount?.(fiber, rendererId);\n },\n\n // Required stubs for React compatibility\n checkDCE(_fn: Function): void {},\n onScheduleFiberRoot(): void {},\n };\n\n return hook;\n}\n\n/**\n * Wrap an existing DevTools hook to intercept events.\n *\n * Use this when React DevTools extension is already installed.\n * Preserves the original hook's functionality while adding your callbacks.\n *\n * @example\n * ```ts\n * if (window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {\n * wrapDevToolsHook(window.__REACT_DEVTOOLS_GLOBAL_HOOK__, {\n * onCommit: (root) => console.log('Commit intercepted!'),\n * });\n * }\n * ```\n */\nexport function wrapDevToolsHook(\n hook: DevToolsHook,\n callbacks: HookCallbacks,\n): void {\n // Wrap inject\n if (callbacks.onInject) {\n const original = hook.inject.bind(hook);\n hook.inject = function (renderer: ReactRenderer): number {\n const id = original(renderer);\n callbacks.onInject!(renderer, id);\n return id;\n };\n }\n\n // Wrap onCommitFiberRoot\n if (callbacks.onCommit) {\n const original = hook.onCommitFiberRoot?.bind(hook);\n hook.onCommitFiberRoot = function (\n rendererId: number,\n fiberRoot: FiberRoot,\n priority?: number,\n didError?: boolean,\n ): void {\n callbacks.onCommit!(fiberRoot, rendererId, didError === true);\n original?.(rendererId, fiberRoot, priority, didError);\n };\n }\n\n // Wrap onCommitFiberUnmount\n if (callbacks.onUnmount) {\n const original = hook.onCommitFiberUnmount?.bind(hook);\n hook.onCommitFiberUnmount = function (\n rendererId: number,\n fiber: Fiber,\n ): void {\n callbacks.onUnmount!(fiber, rendererId);\n original?.(rendererId, fiber);\n };\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hook Access\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the installed DevTools hook, if any.\n */\nexport function getHook(): DevToolsHook | null {\n if (typeof window === \"undefined\") return null;\n return window.__REACT_DEVTOOLS_GLOBAL_HOOK__ ?? null;\n}\n\n/**\n * Check if React has connected to the hook.\n */\nexport function isReactConnected(): boolean {\n const hook = getHook();\n return hook !== null && hook.renderers.size > 0;\n}\n\n/**\n * Snapshot for diagnostics: whether {@link initHook} installed our marked hook on\n * `window.__REACT_DEVTOOLS_GLOBAL_HOOK__`, and whether React has registered a renderer.\n */\nexport function getFiberHookInjectionStatus(): {\n injected: boolean;\n reactConnected: boolean;\n} {\n const hook = getHook();\n if (!hook) {\n return { injected: false, reactConnected: false };\n }\n const injected = HOOK_MARKER in hook;\n const reactConnected = hook.renderers.size > 0;\n return { injected, reactConnected };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Watch\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Options for watch().\n */\nexport interface WatchOptions<T extends FiberNodeConstraint = DefaultFiberNode>\n extends SerializeOptions {\n /**\n * Callback receiving snapshots after each relevant commit.\n */\n onChange: (snapshot: FiberSnapshot<T>) => void;\n\n /**\n * CSS selector for the element to watch.\n * If not provided, watches the entire tree.\n *\n * When set, uses fiber flags for O(1) change detection:\n * - Checks `fiber.flags | fiber.subtreeFlags` to determine if subtree changed\n * - Only serializes when the subtree actually has changes\n * - Falls back to full serialization if element not found (may appear later)\n */\n selector?: string;\n\n /**\n * Only watch a specific renderer ID.\n * If not set, watches all renderers.\n */\n rendererId?: number;\n\n /**\n * Custom serialization function.\n * If not provided, uses defaultSerialize (name + tag).\n */\n serialize?: SerializeFn<T>;\n\n /**\n * Only include nodes with these tags in the tree.\n * Other nodes are filtered out and their children promoted.\n * @example tags: [FiberTag.FunctionComponent, FiberTag.HostComponent]\n */\n tags?: FiberTagValue[];\n}\n\n/**\n * Result of calling watch().\n */\nexport interface WatchHandle {\n /** Stop watching for updates */\n stop: () => void;\n}\n\n/**\n * Watch for fiber tree changes.\n *\n * Calls onChange with a FiberSnapshot after each React commit.\n * The snapshot contains a monotonically increasing sequence number\n * and the full serialized tree (or subtree if selector is specified).\n *\n * Automatically initializes the hook if not already done (via initHook()).\n *\n * @param options - Watch options including onChange callback\n *\n * @example\n * ```ts\n * // Default watch (name + tag)\n * const { stop } = watch({\n * onChange: (snapshot) => {\n * console.log(`Commit #${snapshot.sequence}:`, snapshot.tree);\n * }\n * });\n *\n * // Watch a specific subtree with tag filtering\n * const { stop } = watch({\n * selector: '#my-component',\n * tags: [FiberTag.FunctionComponent],\n * onChange: (snapshot) => sendToParent(snapshot),\n * });\n * ```\n */\nexport function watch<T extends FiberNodeConstraint = DefaultFiberNode>(\n options: WatchOptions<T>,\n): WatchHandle {\n const {\n onChange,\n selector,\n rendererId,\n serialize,\n tags,\n ...serializeOptions\n } = options;\n const serializeFn =\n serialize ?? (defaultSerialize as unknown as SerializeFn<T>);\n const tagSet = tags && tags.length > 0 ? new Set(tags) : null;\n\n // Initialize hook (idempotent) and get commit handler registrar\n const { onCommit } = initHook();\n\n // State\n let sequence = 0;\n let hasEmittedInitial = false;\n\n /**\n * React fiber flags that indicate actual RENDER changes (content changed).\n *\n * For delta optimization, we need to distinguish:\n * 1. RENDER flags: Indicate the component's output changed (affects DOM)\n * 2. EFFECT flags: Just mean effects need to run (don't affect DOM structure)\n * 3. STATIC flags: Always present on fibers with certain effect types\n *\n * We only care about RENDER flags when finding the minimal changed subtree,\n * because effect-only changes don't affect what gets serialized.\n *\n * RENDER flags (content changed):\n * Placement = 2 - Node needs to be inserted\n * Update = 4 - Node needs to update (state/props changed)\n * ChildDeletion = 16 - Child was deleted\n * ContentReset = 32 - Text content needs reset\n * Callback = 64 - Has callback (class components)\n * DidCapture = 128 - Error boundary captured error\n * ForceClientRender = 256 - Force client render\n * Ref = 512 - Ref changed\n * Snapshot = 1024 - Needs snapshot (getSnapshotBeforeUpdate)\n *\n * EFFECT flags (excluded - don't indicate content change):\n * Passive = 2048 - useEffect needs to run\n * Visibility = 8192 - Visibility changed (offscreen)\n * StoreConsistency = 32768 - Concurrent mode store check\n *\n * STATIC flags (excluded - always present, not work indicators):\n * RefStatic = 0x400000 (bit 22)\n * PassiveStatic = 0x800000 (bit 23)\n */\n const RENDER_CHANGE_FLAGS =\n 2 | // Placement\n 4 | // Update\n 16 | // ChildDeletion\n 32 | // ContentReset\n // 64 | // Callback - lifecycle callback, doesn't affect serialized output\n 128 | // DidCapture\n 256; // ForceClientRender\n // 512 | // Ref - ref changes don't affect serialized output\n // 1024; // Snapshot - getSnapshotBeforeUpdate, doesn't affect serialized output\n // = 2038 = 0x7F6\n\n /**\n * Check if a fiber subtree has changes using fiber flags.\n * Returns true if the subtree has any pending work (flags set).\n *\n * React's fiber.flags indicates work on this fiber.\n * React's fiber.subtreeFlags aggregates flags from all descendants.\n * If both are 0, nothing in the subtree changed.\n */\n const hasSubtreeChanges = (fiber: Fiber): boolean => {\n // flags and subtreeFlags are bitmasks indicating pending work\n // Mask out static flags (PassiveStatic, RefStatic, etc.) to get actual work flags\n const flags = ((fiber as any).flags ?? 0) & RENDER_CHANGE_FLAGS;\n const subtreeFlags =\n ((fiber as any).subtreeFlags ?? 0) & RENDER_CHANGE_FLAGS;\n return (flags | subtreeFlags) !== 0;\n };\n\n /**\n * Count how many \"filtered roots\" a fiber contributes to the filtered tree.\n * If the fiber is included, it contributes 1.\n * If filtered out, its children's contributions are summed (they get promoted).\n */\n const countFilteredRoots = (\n fiber: Fiber,\n includeTags: Set<FiberTagValue>,\n ): number => {\n if (includeTags.has(fiber.tag)) {\n return 1;\n }\n // Fiber is filtered out, count children's contributions\n let count = 0;\n let child = fiber.child;\n while (child) {\n count += countFilteredRoots(child, includeTags);\n child = child.sibling;\n }\n return count;\n };\n\n /**\n * Find all first-level changed subtrees.\n * Stops at the first changed node in each branch (doesn't descend further).\n * Returns array of { fiber, path } - may be multiple if siblings changed.\n *\n * \"First-level\" means we stop at the first changed node in each branch.\n * This emits a delta for EACH first-level changed node instead of finding\n * a common ancestor. The benefit is smaller payloads and naturally correct\n * paths even with tag filtering.\n *\n * Key properties:\n * 1. Never returns filtered-out nodes (only returns where isIncluded === true)\n * 2. Multiple deltas per commit possible, but never overlapping subtrees\n * 3. Path is built as we descend with proper offset tracking\n * 4. When a filtered-out node has direct changes, all its included\n * descendants are emitted (since we don't know exactly what changed)\n */\n const findChangedSubtrees = (\n startFiber: Fiber,\n includeTags: Set<FiberTagValue> | null,\n ): Array<{ fiber: Fiber; path: number[] }> => {\n const results: Array<{ fiber: Fiber; path: number[] }> = [];\n\n /**\n * @param currentPath Path to the nearest included ancestor\n * @param pendingOffset When inside a filtered-out node, the offset from\n * preceding siblings that needs to be added to path.\n * undefined means \"no pending offset\" (path is complete).\n * @param forceEmit When true, emit this node if included (used when a\n * filtered-out ancestor has direct changes)\n */\n const collect = (\n fiber: Fiber,\n currentPath: number[],\n pendingOffset: number | undefined,\n forceEmit: boolean,\n ): void => {\n const flags = ((fiber as any).flags ?? 0) & RENDER_CHANGE_FLAGS;\n const subtreeFlags =\n ((fiber as any).subtreeFlags ?? 0) & RENDER_CHANGE_FLAGS;\n const isIncluded = !includeTags || includeTags.has(fiber.tag);\n\n // If this node is included AND either:\n // - has direct changes, OR\n // - we're forced to emit (filtered ancestor had changes)\n // → collect it with the accumulated path\n if (isIncluded && (flags !== 0 || forceEmit)) {\n // Add pendingOffset to path if we have one (meaning we traversed\n // through filtered ancestors). undefined means path is already complete.\n const finalPath =\n pendingOffset !== undefined\n ? [...currentPath, pendingOffset]\n : currentPath;\n results.push({ fiber, path: finalPath });\n return;\n }\n\n // If this node is filtered out but has direct changes,\n // we need to emit all its included descendants\n const shouldForceChildren = !isIncluded && flags !== 0;\n\n // If no changes anywhere in subtree and not forcing → done\n if ((flags | subtreeFlags) === 0 && !forceEmit) {\n return;\n }\n\n // Descend into children\n let child = fiber.child;\n let filteredIndex = 0;\n\n while (child) {\n const childIsIncluded = !includeTags || includeTags.has(child.tag);\n // Compute child's index: add any pending offset to current filtered index\n const childIndex = (pendingOffset ?? 0) + filteredIndex;\n\n if (childIsIncluded) {\n // Child is included: if parent is included, add index to path and clear\n // pending. If parent is filtered, pass index as pending offset.\n collect(\n child,\n isIncluded ? [...currentPath, childIndex] : currentPath,\n isIncluded ? undefined : childIndex,\n shouldForceChildren || forceEmit,\n );\n } else {\n // Child is filtered out: pass accumulated offset to its descendants\n collect(\n child,\n currentPath,\n childIndex,\n shouldForceChildren || forceEmit,\n );\n }\n\n // Advance filtered index (account for promotion when filtering)\n filteredIndex += includeTags\n ? countFilteredRoots(child, includeTags)\n : 1;\n\n child = child.sibling;\n }\n };\n\n collect(startFiber, [], undefined, false);\n return results;\n };\n\n /**\n * Find the starting fiber for serialization.\n * If selector is specified, finds that element's fiber.\n * Otherwise returns the app component (first child of HostRoot).\n */\n const findStartFiber = (\n fiberRoot: FiberRoot,\n ): { fiber: Fiber | null; fromSelector: boolean } => {\n if (selector) {\n const element = document.querySelector(selector);\n if (element) {\n const fiber = getFiberFromElement(element);\n if (fiber) {\n // The element's raw fiber pointer is stamped once at mount and\n // alternates between the two double-buffered generations as\n // commits land; resolve to the committed one so serialized props\n // are never one commit stale.\n return { fiber: resolveCommittedFiber(fiber), fromSelector: true };\n }\n }\n // Selector specified but element not found - return null\n return { fiber: null, fromSelector: true };\n }\n\n // No selector - use full tree starting from app component\n const rootFiber = fiberRoot.current;\n if (rootFiber.tag === FiberTag.HostRoot && rootFiber.child) {\n return { fiber: rootFiber.child, fromSelector: false };\n }\n return { fiber: rootFiber, fromSelector: false };\n };\n\n // Handler for commits\n const handleCommit = (fiberRoot: FiberRoot, id: number): void => {\n if (rendererId !== undefined && id !== rendererId) return;\n\n // Find starting fiber (full tree or selector subtree)\n const { fiber: startFiber, fromSelector } = findStartFiber(fiberRoot);\n\n // Skip if no render changes in the tree (effect-only commits don't need re-serialization)\n // But always allow the first emission (for immediate snapshot on watch() start)\n if (hasEmittedInitial && startFiber && !hasSubtreeChanges(startFiber)) {\n return;\n }\n\n // Find all changed subtrees (may be multiple if siblings changed)\n // Falls back to full tree if no flags set or first emission\n const changedSubtrees =\n startFiber && hasSubtreeChanges(startFiber)\n ? findChangedSubtrees(startFiber, tagSet)\n : [{ fiber: startFiber, path: [] as number[] }];\n\n // If no changed subtrees found (can happen with filtering), emit full tree\n const subtreesToEmit =\n changedSubtrees.length > 0\n ? changedSubtrees\n : [{ fiber: startFiber, path: [] as number[] }];\n\n // Emit a delta for each changed subtree\n for (const { fiber, path } of subtreesToEmit) {\n if (!fiber) continue;\n\n let tree = serializeTree(fiber, serializeFn, serializeOptions);\n\n // Apply tag filtering if specified\n if (tree && tagSet && \"tag\" in tree) {\n const filtered = filterTreeInclude(\n tree as unknown as FiberNodeConstraint & { tag: FiberTagValue },\n tagSet,\n );\n tree = filtered as unknown as typeof tree;\n }\n\n if (!tree) continue; // Skip if filtering removed everything\n\n const snapshot: FiberSnapshot<T> = {\n sequence: sequence++,\n tree,\n path,\n };\n\n hasEmittedInitial = true;\n onChange(snapshot);\n }\n };\n\n // Register handler and get unsubscribe function\n const unsubscribe = onCommit(handleCommit);\n\n // Emit immediate snapshot if we have a last committed root\n if (rendererId !== undefined) {\n for (const root of lastCommittedRoots.get(rendererId) ?? []) {\n handleCommit(root, rendererId);\n }\n } else {\n // Emit for all renderers\n for (const [id, roots] of lastCommittedRoots) {\n for (const root of roots) {\n handleCommit(root, id);\n }\n }\n }\n\n return {\n stop: unsubscribe,\n };\n}\n","/**\n * Identity of this JS realm (one document evaluation), stamped on every\n * emitted capture. A consumer seeing the epoch change across captures of the\n * same logical watch has OBSERVED a document replacement — the signal is\n * carried by the capture itself, so it survives watch re-creation, relay\n * coalescing, and frame discards that strip replay-time markers like\n * `producerReset`.\n */\nexport const REALM_DOCUMENT_EPOCH = `${Date.now().toString(36)}-${Math.random()\n .toString(36)\n .slice(2, 10)}`;\n\nlet nextCaptureSequence = 0;\n\n/** Monotonic across every combined watcher and one-shot capture in this realm.\n * Watch restarts must not reset ordering: a delayed capture from the retired\n * watcher can otherwise arrive after and overwrite newer visible pixels. */\nexport function nextRealmCaptureSequence(): number {\n return nextCaptureSequence++;\n}\n","/**\n * Declared Capture Facts (producer-side)\n *\n * Computes the `DeclaredCaptureFacts` a capture producer attaches to its\n * `DomCapture`. Everything here reads the LIVE DOM the producer already\n * holds — never the serialized HTML string — so the facts are ground truth\n * rather than a re-parse of the payload. See specs/canvas-determinism.md §4.\n */\n\nimport type { DeclaredCaptureFacts } from \"./types\";\n\n/**\n * Two annotation namespaces stamp the source-mapped iframe DOM:\n * - JSX: `data-tempo-filepath` + `data-tempo-position` + `data-tempo-modifiedts`\n * - HTML: `data-tempo-html-filepath` + `data-tempo-html-offset` +\n * `data-tempo-html-modifiedts`\n * A single element may carry BOTH (an HTML element nested inside a JSX host\n * that also got source-located), so each namespace is read independently.\n */\nconst SOURCE_ANNOTATED_SELECTOR =\n \"[data-tempo-filepath], [data-tempo-html-filepath]\";\n\ninterface AnnotationNamespace {\n filepathAttr: string;\n positionAttr: string;\n modifiedTsAttr: string;\n sourceVersionAttr: string;\n}\n\nconst NAMESPACES: readonly AnnotationNamespace[] = [\n {\n filepathAttr: \"data-tempo-filepath\",\n positionAttr: \"data-tempo-position\",\n modifiedTsAttr: \"data-tempo-modifiedts\",\n sourceVersionAttr: \"data-tempo-source-version\",\n },\n {\n filepathAttr: \"data-tempo-html-filepath\",\n positionAttr: \"data-tempo-html-offset\",\n modifiedTsAttr: \"data-tempo-html-modifiedts\",\n sourceVersionAttr: \"data-tempo-html-source-version\",\n },\n];\n\n/**\n * Compute the declared facts for a capture.\n *\n * @param targetElement - The element whose subtree is serialized into\n * `dom.html` (the mutation LCA for scoped captures, or the capture root\n * for whole-surface ones).\n * @param captureRoot - The watched root. `complete` is `targetElement ===\n * captureRoot`. The render-error probe searches the WHOLE root (the error\n * overlay is a surface-level fact, not necessarily inside the scoped LCA).\n * @param scopeSelector - The selector the producer already computed for\n * `targetElement` relative to `captureRoot` (\"\" for whole-surface).\n * Surfaced as `scopeSelector` only when the capture is not complete.\n * @param portalElements - Live portal root elements whose content the\n * producer also serializes into `portals`. Their annotations count toward\n * `observedVersions`/`containedAnchors` exactly as the DOM subtree's do.\n */\nexport function computeDeclaredFacts(\n targetElement: Element,\n captureRoot: Element,\n scopeSelector: string,\n portalElements: readonly Element[],\n): DeclaredCaptureFacts {\n const observedVersions: Record<string, number> = {};\n const observedSourceVersions: Record<string, string> = {};\n const anchorSet = new Set<string>();\n\n const visit = (element: Element): void => {\n for (const ns of NAMESPACES) {\n const filepath = element.getAttribute(ns.filepathAttr);\n if (filepath == null || filepath.length === 0) continue;\n\n const modifiedTsRaw = element.getAttribute(ns.modifiedTsAttr);\n if (modifiedTsRaw != null) {\n const modifiedTs = Number(modifiedTsRaw);\n if (!Number.isNaN(modifiedTs)) {\n const existing = observedVersions[filepath];\n if (existing === undefined || modifiedTs > existing) {\n observedVersions[filepath] = modifiedTs;\n // Co-locate the content-version token with the newest render: it\n // rides the same element that just set the file's MAX modifiedts.\n // Clear a stale token from an older render when the newest element\n // carries none (a mid-HMR mixed tree, or an old-SDK element).\n const version = element.getAttribute(ns.sourceVersionAttr);\n if (version != null && version.length > 0) {\n observedSourceVersions[filepath] = version;\n } else {\n delete observedSourceVersions[filepath];\n }\n }\n }\n }\n\n const position = element.getAttribute(ns.positionAttr);\n if (position != null && position.length > 0) {\n anchorSet.add(`${filepath} ${position}`);\n }\n }\n };\n\n // The serialized population: the target subtree (including the target\n // element itself, whose annotations travel in `dom.attributes`) plus every\n // portal root and its descendants.\n const walkRoots: readonly Element[] = [targetElement, ...portalElements];\n for (const root of walkRoots) {\n if (root.matches(SOURCE_ANNOTATED_SELECTOR)) visit(root);\n for (const annotated of root.querySelectorAll(SOURCE_ANNOTATED_SELECTOR)) {\n visit(annotated);\n }\n }\n\n const complete = targetElement === captureRoot;\n\n return {\n complete,\n scopeSelector: complete ? null : scopeSelector,\n observedVersions,\n observedSourceVersions,\n containedAnchors: Array.from(anchorSet),\n renderError: computeRenderError(captureRoot),\n };\n}\n\n/**\n * Render-error boundary state for a capture root. Non-null iff a\n * `[data-render-error=\"true\"]` element exists anywhere in the live root\n * subtree (or is the root itself); its `data-render-error-message` becomes\n * `message` when present.\n */\nfunction computeRenderError(\n captureRoot: Element,\n): DeclaredCaptureFacts[\"renderError\"] {\n const errorElement = captureRoot.matches('[data-render-error=\"true\"]')\n ? captureRoot\n : captureRoot.querySelector('[data-render-error=\"true\"]');\n if (!errorElement) return null;\n return {\n message: errorElement.getAttribute(\"data-render-error-message\"),\n };\n}\n","import type { CaptureDisplayability } from \"./types\";\n\n/** Elements whose descendants do not contribute projected pixels/content. */\nconst IGNORED_CONTENT_TAGS = new Set([\n \"DATALIST\",\n \"LINK\",\n \"META\",\n \"NOSCRIPT\",\n \"SCRIPT\",\n \"STYLE\",\n \"TEMPLATE\",\n]);\n\nconst VISUAL_ASSET_TAGS = new Set([\n \"AUDIO\",\n \"CANVAS\",\n \"EMBED\",\n \"IFRAME\",\n \"IMG\",\n \"INPUT\",\n \"OBJECT\",\n \"SELECT\",\n \"SVG\",\n \"TEXTAREA\",\n \"VIDEO\",\n]);\n\n/**\n * Measures displayable structure in a live, styled document.\n *\n * The capture root itself is excluded because `DomCapture.dom.html` contains\n * its children. Supplemental roots are included because portal updates carry\n * each portal root's `outerHTML`. A null result means no browsing context was\n * available, so callers must omit the proof rather than infer it from markup.\n */\nexport function measureComputedDisplayability(\n captureRoot: Element,\n supplementalRoots: readonly Element[] = [],\n): CaptureDisplayability | null {\n const doc = captureRoot.ownerDocument;\n const view = doc.defaultView;\n if (\n !view ||\n !captureRoot.isConnected ||\n supplementalRoots.some(\n (root) => root.ownerDocument !== doc || !root.isConnected,\n )\n ) {\n return null;\n }\n\n const result: CaptureDisplayability = {\n version: 1,\n elementCount: 0,\n paintedElementCount: 0,\n nonEmptyTextNodeCount: 0,\n visualAssetCount: 0,\n };\n\n try {\n const rootBlocked = hasBlockingElementInChain(captureRoot, view);\n const rootTextVisible =\n !rootBlocked && elementHasVisibleComputedVisibility(captureRoot, view);\n for (const child of Array.from(captureRoot.childNodes)) {\n visitNode(child, rootBlocked, rootTextVisible, view, result);\n }\n\n for (const supplementalRoot of supplementalRoots) {\n visitNode(\n supplementalRoot,\n hasBlockingElementInChain(supplementalRoot.parentElement, view),\n true,\n view,\n result,\n );\n }\n } catch {\n // A producer declaration is proof. If style inspection is unavailable for\n // any part of the render domain, omit the whole profile conservatively.\n return null;\n }\n\n return result;\n}\n\nfunction visitNode(\n node: Node,\n blockedByAncestor: boolean,\n parentTextVisible: boolean,\n view: Window,\n result: CaptureDisplayability,\n): void {\n if (node.nodeType === 3) {\n if (\n !blockedByAncestor &&\n parentTextVisible &&\n (node.textContent?.trim().length ?? 0) > 0\n ) {\n result.nonEmptyTextNodeCount += 1;\n }\n return;\n }\n if (node.nodeType !== 1) return;\n\n const element = node as Element;\n const blocked = blockedByAncestor || elementBlocksSubtree(element, view);\n if (blocked) return;\n\n const visible = elementHasVisibleComputedVisibility(element, view);\n if (visible) {\n result.elementCount += 1;\n if (elementPaintsOwnPixels(element, view)) {\n result.paintedElementCount = (result.paintedElementCount ?? 0) + 1;\n }\n if (VISUAL_ASSET_TAGS.has(element.tagName)) {\n result.visualAssetCount += 1;\n }\n }\n\n for (const child of Array.from(element.childNodes)) {\n visitNode(child, false, visible, view, result);\n }\n}\n\nfunction elementPaintsOwnPixels(element: Element, view: Window): boolean {\n const style = view.getComputedStyle(element);\n if (colorCanPaint(style.backgroundColor)) return true;\n if (style.backgroundImage && style.backgroundImage !== \"none\") return true;\n if (style.boxShadow && style.boxShadow !== \"none\") return true;\n if (\n style.outlineStyle !== \"none\" &&\n parseFloat(style.outlineWidth) > 0 &&\n colorCanPaint(style.outlineColor)\n ) {\n return true;\n }\n for (const side of [\"Top\", \"Right\", \"Bottom\", \"Left\"] as const) {\n if (\n style[`border${side}Style`] !== \"none\" &&\n parseFloat(style[`border${side}Width`]) > 0 &&\n colorCanPaint(style[`border${side}Color`])\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction colorCanPaint(value: string): boolean {\n const normalized = value.trim().toLowerCase().replace(/ /g, \"\");\n if (!normalized || normalized === \"transparent\") return false;\n return !(\n /^rgba\\([^)]*,0(?:\\.0+)?\\)$/.test(normalized) ||\n /^rgb\\([^)]*\\/0(?:\\.0+)?\\)$/.test(normalized)\n );\n}\n\nfunction hasBlockingElementInChain(\n start: Element | null,\n view: Window,\n): boolean {\n for (let element = start; element; element = element.parentElement) {\n if (elementBlocksSubtree(element, view)) return true;\n }\n return false;\n}\n\nfunction elementBlocksSubtree(element: Element, view: Window): boolean {\n if (IGNORED_CONTENT_TAGS.has(element.tagName)) return true;\n if (element.hasAttribute(\"hidden\")) return true;\n if (element.tagName === \"DIALOG\" && !element.hasAttribute(\"open\")) {\n return true;\n }\n if (\n element.tagName === \"INPUT\" &&\n element.getAttribute(\"type\")?.trim().toLowerCase() === \"hidden\"\n ) {\n return true;\n }\n\n const style = view.getComputedStyle(element);\n const opacity = style.opacity.trim();\n return (\n style.display === \"none\" ||\n (opacity.length > 0 && Number(opacity) <= 0) ||\n style.getPropertyValue(\"content-visibility\") === \"hidden\"\n );\n}\n\nfunction elementHasVisibleComputedVisibility(\n element: Element,\n view: Window,\n): boolean {\n const visibility = view.getComputedStyle(element).visibility;\n return visibility !== \"hidden\" && visibility !== \"collapse\";\n}\n","/**\n * CSS Selector Utilities\n *\n * Pure functions for generating CSS selectors.\n */\n\n/**\n * Generates a unique CSS selector path for an element.\n *\n * Uses nth-of-type notation when needed for uniqueness among siblings.\n *\n * @param element - Element to generate selector for\n * @param root - Optional root element to stop at (selector will be relative to this)\n * @returns CSS selector path (e.g., \"body > div > button:nth-of-type(2)\")\n *\n * @example\n * ```ts\n * generateSelector(document.querySelector('button'));\n * // \"body > div > button\"\n *\n * generateSelector(button, container);\n * // \"div > button\" (relative to container)\n * ```\n */\nexport function generateSelector(element: Element, root?: Element): string {\n // Special cases for well-known elements\n if (!root) {\n if (element === document.documentElement) return \":root\";\n if (element === document.head) return \"head\";\n if (element === document.body) return \"body\";\n }\n\n // If element is the root, return empty string\n if (root && element === root) return \"\";\n\n const parts: string[] = [];\n let current: Element | null = element;\n const stopAt = root ?? document.documentElement;\n\n while (current && current !== stopAt) {\n const parent: Element | null = current.parentElement;\n if (!parent) break;\n\n const tagName = current.tagName.toLowerCase();\n\n // Count same-type siblings to determine if :nth-of-type is needed\n let index = 1;\n let sibling = current.previousElementSibling;\n while (sibling) {\n if (sibling.tagName === current.tagName) index++;\n sibling = sibling.previousElementSibling;\n }\n\n let sameTypeSiblings = 0;\n for (const child of parent.children) {\n if (child.tagName === current.tagName) sameTypeSiblings++;\n }\n\n if (sameTypeSiblings > 1) {\n parts.unshift(`${tagName}:nth-of-type(${index})`);\n } else {\n parts.unshift(tagName);\n }\n\n current = parent;\n }\n\n // Handle edge cases\n if (parts.length === 0) {\n if (element === document.body) return \"body\";\n if (element === document.head) return \"head\";\n return \"\";\n }\n\n const path = parts.join(\" > \");\n\n // Anchor to root with :scope so querySelector matches at the correct depth.\n // Without this, \"div > div > div:nth-of-type(2)\" is ambiguous — it can match\n // any ancestor chain of divs at any depth within the subtree, not just the\n // specific depth from the root. :scope pins the first segment to a direct\n // child of the querySelector target.\n if (root) return `:scope > ${path}`;\n\n return path;\n}\n\n/**\n * Finds the Lowest Common Ancestor (LCA) of a set of nodes.\n *\n * The LCA is the deepest element that is an ancestor of all provided nodes.\n * Useful for determining the minimal subtree that contains all mutations.\n *\n * @param nodes - Set of DOM nodes to find common ancestor for\n * @returns The LCA element, or null if no common ancestor found\n */\nexport function findLowestCommonAncestor(nodes: Set<Node>): Element | null {\n if (nodes.size === 0) return null;\n\n // Build ancestor chains for each node (from root to node)\n const ancestorChains: Element[][] = [];\n\n for (const node of nodes) {\n const chain: Element[] = [];\n let current: Node | null =\n node instanceof Element ? node : node.parentElement;\n\n while (current && current !== document) {\n if (current instanceof Element) {\n chain.unshift(current);\n }\n current = current.parentNode;\n }\n\n if (chain.length > 0) {\n ancestorChains.push(chain);\n }\n }\n\n if (ancestorChains.length === 0) {\n return document.documentElement;\n }\n\n // Find the deepest common ancestor by comparing chains\n let lca: Element = document.documentElement;\n const firstChain = ancestorChains[0]!;\n const minLength = Math.min(...ancestorChains.map((c) => c.length));\n\n for (let i = 0; i < minLength; i++) {\n const candidate = firstChain[i];\n if (candidate && ancestorChains.every((chain) => chain[i] === candidate)) {\n lca = candidate;\n } else {\n break;\n }\n }\n\n return lca;\n}\n","/**\n * DOM Capture\n *\n * One-shot capture of DOM content and element states.\n */\n\nimport { computeDeclaredFacts } from \"./declared-facts\";\nimport { measureComputedDisplayability } from \"./displayability\";\nimport { generateSelector } from \"./selectors\";\nimport type { DomCapture, ElementState } from \"./types\";\n\nexport interface CollectElementStatesOptions {\n /** Whether to include document-level scroll via the :root selector. */\n includeDocumentScroll?: boolean;\n}\n\n/**\n * Captures the current state of an element as a DomCapture.\n *\n * @param element - Element to capture\n * @returns DomCapture containing HTML and element states\n *\n * @example\n * ```ts\n * const snapshot = capture(document.body);\n * // { dom: { selector: \"body\", html: \"...\" }, states: [...] }\n * ```\n */\nexport function capture(element: Element): DomCapture {\n return captureWithSupplementalRoots(element, []);\n}\n\n/** Internal complete-capture primitive used when a higher-level producer also\n * serializes supplemental roots such as owned React portals. */\nexport function captureWithSupplementalRoots(\n element: Element,\n supplementalRoots: readonly Element[],\n): DomCapture {\n // Sync form state to attributes before serializing\n syncFormStateToAttributes(element);\n\n // Selector relative to itself = \"\" (this IS the container)\n const selector = generateSelector(element, element);\n // Use innerHTML - we capture the children, not the container itself\n const html = removeScriptTags(element.innerHTML);\n const attributes = captureAttributes(element);\n const documentElementAttributes = element.ownerDocument\n ? captureAttributes(element.ownerDocument.documentElement)\n : undefined;\n const baseUrl = element.ownerDocument?.baseURI;\n const states = collectElementStates(element);\n const displayability = measureComputedDisplayability(\n element,\n supplementalRoots,\n );\n\n return {\n // Whole-surface one-shot: the element is both the capture root and the\n // serialized scope, so `complete` is true and there is no scope selector.\n declared: computeDeclaredFacts(element, element, \"\", supplementalRoots),\n ...(displayability && { displayability }),\n dom: { selector, html, attributes, documentElementAttributes },\n states,\n baseUrl,\n };\n}\n\n/**\n * Syncs form element state (DOM properties) to HTML attributes.\n *\n * Form elements like checkboxes, selects, and inputs have runtime state\n * that isn't reflected in their HTML attributes. This syncs that state\n * to attributes so it survives serialization.\n */\nfunction syncFormStateToAttributes(root: Element): void {\n // Checkboxes and radios\n for (const input of root.querySelectorAll(\n 'input[type=\"checkbox\"], input[type=\"radio\"]',\n )) {\n const el = input as HTMLInputElement;\n if (el.checked) {\n el.setAttribute(\"checked\", \"\");\n } else {\n el.removeAttribute(\"checked\");\n }\n }\n\n // Text inputs\n for (const input of root.querySelectorAll(\n 'input:not([type=\"checkbox\"]):not([type=\"radio\"])',\n )) {\n const el = input as HTMLInputElement;\n if (el.value !== el.getAttribute(\"value\")) {\n el.setAttribute(\"value\", el.value);\n }\n }\n\n // Textareas\n for (const textarea of root.querySelectorAll(\"textarea\")) {\n const el = textarea as HTMLTextAreaElement;\n if (el.value !== el.textContent) {\n el.textContent = el.value;\n }\n if (el.hasAttribute(\"value\")) {\n el.removeAttribute(\"value\");\n }\n }\n\n // Selects\n for (const select of root.querySelectorAll(\"select\")) {\n const el = select as HTMLSelectElement;\n for (const option of el.options) {\n if (option.selected) {\n option.setAttribute(\"selected\", \"\");\n } else {\n option.removeAttribute(\"selected\");\n }\n }\n }\n}\n\n/**\n * Removes all script tags from HTML string.\n */\nexport function removeScriptTags(html: string): string {\n return html.replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/gi, \"\");\n}\n\n/**\n * Captures attributes from an element into a serializable map.\n */\nexport function captureAttributes(element: Element): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const attr of Array.from(element.attributes)) {\n attrs[attr.name] = attr.value;\n }\n return attrs;\n}\n\n/**\n * Collects current element states from a root element.\n *\n * Walks form elements and scrollable containers to collect their runtime state.\n */\nexport function collectElementStates(\n root: Element,\n options: CollectElementStatesOptions = {},\n): ElementState[] {\n const { includeDocumentScroll = true } = options;\n const states: ElementState[] = [];\n\n // Collect form states\n for (const input of root.querySelectorAll(\"input\")) {\n const el = input as HTMLInputElement;\n const isCheckable = el.type === \"checkbox\" || el.type === \"radio\";\n const hasNonDefault = isCheckable\n ? el.checked !== el.defaultChecked\n : el.value !== el.defaultValue;\n\n if (hasNonDefault) {\n const selector = generateSelector(el, root);\n if (isCheckable) {\n states.push({ selector, checked: el.checked });\n } else {\n states.push({ selector, value: el.value });\n }\n }\n }\n\n for (const textarea of root.querySelectorAll(\"textarea\")) {\n const el = textarea as HTMLTextAreaElement;\n if (el.value !== el.defaultValue) {\n const selector = generateSelector(el, root);\n states.push({ selector, value: el.value });\n }\n }\n\n for (const select of root.querySelectorAll(\"select\")) {\n const el = select as HTMLSelectElement;\n for (const option of el.options) {\n if (option.selected !== option.defaultSelected) {\n const selector = generateSelector(option, root);\n states.push({ selector, selected: option.selected });\n }\n }\n }\n\n // Collect scroll states - always include root and document-level scroll\n // so that scrolling back to 0 is properly communicated.\n states.push({\n selector: \"\",\n scrollTop: root.scrollTop,\n scrollLeft: root.scrollLeft,\n });\n\n // Check document-level scroll (scrollingElement, usually <html>)\n // This handles the common case where scroll is on documentElement, not body\n if (includeDocumentScroll) {\n const scrollingEl = root.ownerDocument?.scrollingElement;\n if (scrollingEl && scrollingEl !== root) {\n states.push({\n selector: \":root\",\n scrollTop: scrollingEl.scrollTop,\n scrollLeft: scrollingEl.scrollLeft,\n });\n }\n }\n\n for (const el of root.querySelectorAll(\"*\")) {\n if (el.scrollTop > 0 || el.scrollLeft > 0) {\n const selector = generateSelector(el, root);\n states.push({\n selector,\n scrollTop: el.scrollTop,\n scrollLeft: el.scrollLeft,\n });\n }\n }\n\n return states;\n}\n","/**\n * Head Capture Utility\n *\n * Captures relevant <head> content from a document, excluding scripts\n * and resolving relative URLs to absolute.\n *\n * ## Shared Observer Pattern\n *\n * Uses a singleton HeadTracker that maintains one MutationObserver per document,\n * shared across all subscriptions. This avoids creating 50+ observers when there\n * are many watchers on the same page.\n */\n\n/** Elements to include from <head> */\nconst INCLUDE_TAGS = new Set([\"STYLE\", \"META\", \"BASE\", \"LINK\"]);\n\n/** Link rel values to include (stylesheet-related) */\nconst INCLUDE_LINK_RELS = new Set([\"stylesheet\"]);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Head Tracker (Shared Observer)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * A subscription to head changes for a specific document.\n * Each subscription maintains its own hasMutations flag since they flush independently.\n */\nexport interface HeadSubscription {\n /** Whether there have been mutations since last flush */\n hasMutations: boolean;\n /** Flush and get head content. Returns content if isInitial or if mutations occurred. */\n flush(isInitial: boolean): string | undefined;\n /** Unsubscribe from head changes */\n unsubscribe(): void;\n}\n\nexport interface HeadMutationDetails {\n /** Vite stylesheet module ids whose style/link nodes changed in this batch. */\n stylesheetPaths: string[];\n}\n\n/**\n * Singleton tracker that manages shared MutationObservers for head watching.\n * One observer per document, shared across all subscriptions.\n */\nexport interface HeadTracker {\n /** Subscribe to head changes for a document */\n subscribe(\n doc: Document,\n onMutation: (details: HeadMutationDetails) => void,\n ): HeadSubscription;\n /** Clean up all observers */\n destroy(): void;\n}\n\n/** Module-level singleton */\nlet instance: HeadTrackerImpl | null = null;\n\n/**\n * Get the singleton HeadTracker instance.\n */\nexport function getHeadTracker(): HeadTracker {\n if (!instance) {\n instance = new HeadTrackerImpl();\n }\n return instance;\n}\n\n/**\n * Reset the singleton. For testing only.\n * @internal\n */\nexport function _resetHeadTrackerForTesting(): void {\n instance?.destroy();\n instance = null;\n}\n\n/** Internal subscription implementation */\nclass HeadSubscriptionImpl implements HeadSubscription {\n hasMutations = false;\n private doc: Document;\n private callback: (details: HeadMutationDetails) => void;\n private onUnsubscribe: () => void;\n\n constructor(\n doc: Document,\n callback: (details: HeadMutationDetails) => void,\n onUnsubscribe: () => void,\n ) {\n this.doc = doc;\n this.callback = callback;\n this.onUnsubscribe = onUnsubscribe;\n }\n\n flush(isInitial: boolean): string | undefined {\n if (!isInitial && !this.hasMutations) {\n return undefined;\n }\n this.hasMutations = false;\n return captureHead(this.doc);\n }\n\n unsubscribe(): void {\n this.onUnsubscribe();\n }\n\n /** Called by tracker when relevant mutation detected */\n notifyMutation(details: HeadMutationDetails): void {\n this.hasMutations = true;\n this.callback(details);\n }\n}\n\n/** Per-document observer state */\ninterface DocObserverState {\n observer: MutationObserver;\n subscriptions: Set<HeadSubscriptionImpl>;\n}\n\nclass HeadTrackerImpl implements HeadTracker {\n private docObservers = new Map<Document, DocObserverState>();\n\n subscribe(\n doc: Document,\n onMutation: (details: HeadMutationDetails) => void,\n ): HeadSubscription {\n let docState = this.docObservers.get(doc);\n\n // Create observer for this document if first subscription\n if (!docState) {\n docState = this.createDocObserver(doc);\n this.docObservers.set(doc, docState);\n }\n\n const subscription = new HeadSubscriptionImpl(doc, onMutation, () => {\n this.unsubscribe(doc, subscription);\n });\n docState.subscriptions.add(subscription);\n\n return subscription;\n }\n\n private createDocObserver(doc: Document): DocObserverState {\n const subscriptions = new Set<HeadSubscriptionImpl>();\n const head = doc.head;\n\n const observer = new MutationObserver((mutations) => {\n if (!head) {\n return;\n }\n const details = this.readRelevantMutations(mutations, head);\n if (!details) return;\n // Notify all subscriptions for this document\n for (const sub of subscriptions) {\n sub.notifyMutation(details);\n }\n });\n\n if (head) {\n observer.observe(head, {\n childList: true,\n subtree: true,\n attributes: true,\n characterData: true,\n });\n }\n\n return { observer, subscriptions };\n }\n\n private unsubscribe(doc: Document, sub: HeadSubscriptionImpl): void {\n const docState = this.docObservers.get(doc);\n if (!docState) return;\n\n docState.subscriptions.delete(sub);\n\n // Disconnect observer if no more subscriptions for this document\n if (docState.subscriptions.size === 0) {\n docState.observer.disconnect();\n this.docObservers.delete(doc);\n }\n }\n\n /**\n * Check if mutations contain changes to elements we care about.\n * This filtering runs once per mutation batch (not once per subscription).\n */\n private readRelevantMutations(\n mutations: MutationRecord[],\n head: HTMLHeadElement,\n ): HeadMutationDetails | null {\n let relevant = false;\n const stylesheetPaths = new Set<string>();\n const collectStylesheetPath = (node: Node | null): void => {\n const element =\n node instanceof Element ? node : (node?.parentElement ?? null);\n if (!element) return;\n const candidates = [\n element,\n ...element.querySelectorAll(\n \"style[data-vite-dev-id], link[rel~='stylesheet']\",\n ),\n ];\n for (const candidate of candidates) {\n if (candidate instanceof HTMLStyleElement) {\n const id = candidate.getAttribute(\"data-vite-dev-id\")?.trim();\n if (id) stylesheetPaths.add(id);\n } else if (\n candidate instanceof HTMLLinkElement &&\n shouldIncludeLink(candidate)\n ) {\n const href = candidate.getAttribute(\"href\")?.trim() || candidate.href;\n if (href) stylesheetPaths.add(href);\n }\n }\n };\n\n for (const mutation of mutations) {\n const target = mutation.target;\n const element = target instanceof Element ? target : target.parentElement;\n\n if (!element || (!head.contains(element) && target !== head)) continue;\n\n // Check if this is a relevant element (one we would capture)\n const tagName = element.tagName;\n if (INCLUDE_TAGS.has(tagName)) {\n // For LINK, check if it's a stylesheet\n if (tagName === \"LINK\") {\n if (!shouldIncludeLink(element)) continue;\n }\n relevant = true;\n collectStylesheetPath(element);\n }\n\n // Also trigger for childList mutations on head itself (added/removed elements)\n if (mutation.type === \"childList\" && target === head) {\n relevant = true;\n }\n if (mutation.type === \"childList\") {\n for (const node of mutation.addedNodes) collectStylesheetPath(node);\n for (const node of mutation.removedNodes) collectStylesheetPath(node);\n }\n }\n return relevant ? { stylesheetPaths: [...stylesheetPaths] } : null;\n }\n\n destroy(): void {\n for (const docState of this.docObservers.values()) {\n docState.observer.disconnect();\n docState.subscriptions.clear();\n }\n this.docObservers.clear();\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Legacy API (Backward Compatibility)\n// These functions delegate to the shared tracker for backward compatibility\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * State for a head watcher instance.\n * @deprecated Use getHeadTracker().subscribe() instead for better performance\n */\nexport interface HeadWatcher {\n /** The document being watched */\n doc: Document;\n /** Whether there have been mutations since last flush */\n hasMutations: boolean;\n /** Stop watching */\n stop: () => void;\n}\n\n/**\n * Starts watching a document's <head> for mutations.\n * @deprecated Use getHeadTracker().subscribe() instead for better performance\n */\nexport function watchHead(doc: Document, onMutation: () => void): HeadWatcher {\n const subscription = getHeadTracker().subscribe(doc, onMutation);\n\n // Wrap subscription in legacy HeadWatcher interface\n return {\n doc,\n get hasMutations() {\n return subscription.hasMutations;\n },\n set hasMutations(value: boolean) {\n subscription.hasMutations = value;\n },\n stop: () => subscription.unsubscribe(),\n };\n}\n\n/**\n * Checks if watcher has any pending head mutations.\n * @deprecated Access subscription.hasMutations directly\n */\nexport function hasPendingHeadChanges(watcher: HeadWatcher): boolean {\n return watcher.hasMutations;\n}\n\n/**\n * Flushes the head watcher, returning captured head content if there were changes.\n * @deprecated Use subscription.flush() directly\n */\nexport function flushHeadWatcher(\n watcher: HeadWatcher,\n isInitial: boolean,\n): string | undefined {\n if (!isInitial && !watcher.hasMutations) {\n return undefined;\n }\n watcher.hasMutations = false;\n return captureHead(watcher.doc);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Head Capture\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Captures the <head> content from a document.\n *\n * - Includes: <style>, <link rel=\"stylesheet\">, <meta>, <base>\n * - Excludes: <script>, <title>, <link rel=\"icon/preload/etc\">\n * - Resolves relative URLs to absolute using document.baseURI\n *\n * @param doc - The document to capture head from\n * @returns Serialized head content (innerHTML for destination <head>)\n */\nexport function captureHead(doc: Document): string {\n const head = doc.head;\n if (!head) return \"\";\n\n const baseURI = doc.baseURI;\n const fragments: string[] = [];\n\n for (const child of Array.from(head.children)) {\n const tagName = child.tagName;\n\n // Skip non-included tags\n if (!INCLUDE_TAGS.has(tagName)) continue;\n\n // For <link>, only include stylesheets\n if (tagName === \"LINK\") {\n if (!shouldIncludeLink(child)) continue;\n }\n\n // Exclude Content-Security-Policy meta tags (they block srcdoc assets)\n if (tagName === \"META\") {\n const httpEquiv = child.getAttribute(\"http-equiv\")?.toLowerCase();\n const name = child.getAttribute(\"name\")?.toLowerCase();\n if (\n httpEquiv === \"content-security-policy\" ||\n name === \"content-security-policy\"\n ) {\n continue;\n }\n }\n\n // Clone and resolve URLs\n const clone = child.cloneNode(true) as Element;\n materializeStyleElementCssom(child, clone);\n resolveUrls(clone, baseURI);\n\n // Strip crossorigin from stylesheet links so they load in no-cors mode\n // in srcdoc projection iframes (which have a null origin that won't\n // match any server's Access-Control-Allow-Origin header)\n if (tagName === \"LINK\") {\n clone.removeAttribute(\"crossorigin\");\n }\n\n fragments.push(clone.outerHTML);\n }\n\n fragments.push(...captureAdoptedStyleSheets(doc));\n\n return fragments.join(\"\\n\");\n}\n\n/**\n * CSS-in-JS and framework runtimes can insert rules through CSSOM APIs, leaving\n * the DOM <style> text empty. Clone-time materialization preserves those rules\n * without mutating the live host document.\n */\nfunction materializeStyleElementCssom(source: Element, clone: Element): void {\n if (source.tagName !== \"STYLE\" || clone.tagName !== \"STYLE\") {\n return;\n }\n\n const style = source as HTMLStyleElement;\n const text = style.textContent ?? \"\";\n if (text.trim().length > 0) {\n return;\n }\n\n const cssText = serializeCssRules(style.sheet);\n if (cssText) {\n clone.textContent = cssText;\n }\n}\n\nfunction captureAdoptedStyleSheets(doc: Document): string[] {\n const sheets = Array.from(doc.adoptedStyleSheets ?? []);\n if (sheets.length === 0) {\n return [];\n }\n\n const fragments: string[] = [];\n for (const sheet of sheets) {\n const cssText = serializeCssRules(sheet);\n if (!cssText) {\n continue;\n }\n const style = doc.createElement(\"style\");\n style.setAttribute(\"data-projection-adopted-stylesheet\", \"true\");\n style.textContent = cssText;\n fragments.push(style.outerHTML);\n }\n return fragments;\n}\n\nfunction serializeCssRules(sheet: CSSStyleSheet | null): string {\n if (!sheet) {\n return \"\";\n }\n\n try {\n return Array.from(sheet.cssRules)\n .map((rule) => rule.cssText)\n .join(\"\\n\");\n } catch {\n // Cross-origin or otherwise unreadable stylesheet.\n return \"\";\n }\n}\n\nfunction shouldIncludeLink(element: Element): boolean {\n const rel = element.getAttribute(\"rel\");\n if (!rel) {\n return false;\n }\n return rel\n .toLowerCase()\n .split(/\\s+/)\n .some((token) => INCLUDE_LINK_RELS.has(token));\n}\n\n/**\n * Resolves relative URLs in an element to absolute URLs.\n */\nfunction resolveUrls(element: Element, baseURI: string): void {\n // Skip URL resolution if baseURI is not a valid HTTP(S) URL\n // (e.g., in test environments where baseURI is \"about:blank\")\n if (!baseURI || !baseURI.startsWith(\"http\")) {\n return;\n }\n\n // Resolve href attribute (for <link>, <base>)\n const href = element.getAttribute(\"href\");\n if (href && !isAbsoluteUrl(href)) {\n try {\n element.setAttribute(\"href\", new URL(href, baseURI).href);\n } catch {\n // Keep original href if URL resolution fails\n }\n }\n\n // Resolve src attribute (for future-proofing)\n const src = element.getAttribute(\"src\");\n if (src && !isAbsoluteUrl(src)) {\n try {\n element.setAttribute(\"src\", new URL(src, baseURI).href);\n } catch {\n // Keep original src if URL resolution fails\n }\n }\n}\n\n/**\n * Checks if a URL is absolute.\n */\nfunction isAbsoluteUrl(url: string): boolean {\n return /^(https?:)?\\/\\//i.test(url) || url.startsWith(\"data:\");\n}\n","/**\n * DOM Watcher\n *\n * Tracks DOM mutations using MutationObserver.\n * Collects mutated elements for later flushing.\n * Assigns unique data-dom-id attributes for reference tracking.\n */\n\nimport { findLowestCommonAncestor } from \"./selectors\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DOM ID Assignment\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Attribute name for DOM element IDs */\nexport const DOM_ID_ATTR = \"data-dom-id\";\n\n// Module-level singleton state for ID generation (shared across all watchers)\nlet sessionHash: string | null = null;\nlet idCounter = 0;\n\n/**\n * Gets or generates the session hash (idempotent).\n * Returns the same 4-character hash for all calls within this context.\n */\nfunction getOrCreateSessionHash(): string {\n if (sessionHash === null) {\n sessionHash = Math.random().toString(36).substring(2, 6);\n }\n return sessionHash;\n}\n\n/**\n * Gets the current session hash.\n * Creates one if it doesn't exist yet.\n */\nexport function getSessionHash(): string {\n return getOrCreateSessionHash();\n}\n\n/**\n * Resets the session state. Primarily for testing.\n * @internal\n */\nexport function _resetSessionState(): void {\n sessionHash = null;\n idCounter = 0;\n}\n\n/**\n * Assigns a unique data-dom-id to an element.\n * ONLY assigns if the element doesn't already have one.\n * @returns The assigned or existing ID\n */\nfunction assignDomId(element: Element): string {\n const existing = element.getAttribute(DOM_ID_ATTR);\n if (existing !== null) {\n return existing;\n }\n\n const id = `${getOrCreateSessionHash()}-${idCounter++}`;\n element.setAttribute(DOM_ID_ATTR, id);\n return id;\n}\n\n/**\n * Returns true if the element itself has contenteditable set.\n * This is a cheap own-property check (no ancestor traversal).\n */\nfunction isContentEditableRoot(element: Element): boolean {\n return element.getAttribute(\"contenteditable\") !== null;\n}\n\n/**\n * Returns true if any ancestor (excluding the element itself) carries\n * contenteditable. Used to keep mutation-time inserts inside an editor's\n * subtree from receiving data-dom-id, while still stamping a freshly\n * mounted contenteditable element when it's added at the top of an\n * `assignDomIdToTree` call.\n */\nfunction hasContentEditableAncestor(element: Element): boolean {\n let current: Element | null = element.parentElement;\n while (current) {\n if (current.getAttribute(\"contenteditable\") !== null) {\n return true;\n }\n current = current.parentElement;\n }\n return false;\n}\n\n/**\n * Assigns data-dom-id to an element and its descendants.\n *\n * Stamps a contenteditable element itself (so it remains addressable as\n * a layer — selectable on the canvas, resolvable from the layers panel),\n * but never descends into its subtree: editors like ProseMirror own\n * their internal DOM and will destroy/recreate children that receive\n * foreign attributes, creating a MutationObserver feedback loop.\n *\n * If `root` is already inside a contenteditable subtree (e.g. a node\n * added by an editor via mutation), it is left untouched entirely.\n */\nfunction assignDomIdToTree(root: Element): void {\n if (hasContentEditableAncestor(root)) {\n return;\n }\n assignDomId(root);\n if (isContentEditableRoot(root)) {\n return;\n }\n // Use a manual TreeWalker-style loop so we can stamp contenteditable\n // boundaries without descending into them, without an ancestor check\n // on every element.\n const stack: Element[] = [];\n for (let i = root.children.length - 1; i >= 0; i--) {\n stack.push(root.children[i] as Element);\n }\n while (stack.length > 0) {\n const element = stack.pop()!;\n assignDomId(element);\n if (isContentEditableRoot(element)) {\n continue;\n }\n for (let i = element.children.length - 1; i >= 0; i--) {\n stack.push(element.children[i] as Element);\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DOM Watcher\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * State for a DOM watcher instance.\n */\nexport interface DomWatcher {\n /** The root element being watched */\n root: Element;\n /** Set of elements that have mutated since last flush */\n mutatedElements: Set<Element>;\n /** Stop watching */\n stop: () => void;\n}\n\n/**\n * Starts watching an element for DOM mutations.\n *\n * Mutations are collected in a Set and can be flushed via getDirtyElements().\n * The watcher does NOT debounce or automatically trigger updates - that's\n * the responsibility of the combined watch.ts.\n *\n * @param root - Element to watch\n * @param onMutation - Called when any mutation occurs (for triggering flush)\n * @returns DomWatcher instance\n *\n * @example\n * ```ts\n * const watcher = watchDom(document.body, () => {\n * // Mutation detected - schedule a flush\n * scheduleDebouncedFlush();\n * });\n *\n * // Later, get what changed and clear\n * const { lca, elements } = watcher.flush();\n * ```\n */\nexport function watchDom(\n root: Element,\n onMutation: () => void\n): DomWatcher {\n const mutatedElements = new Set<Element>();\n\n // Assign IDs to all existing elements in the tree\n assignDomIdToTree(root);\n\n const observer = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n const target =\n mutation.target instanceof Element\n ? mutation.target\n : mutation.target.parentElement;\n\n if (target && root.contains(target)) {\n mutatedElements.add(target);\n }\n\n if (mutation.type === \"childList\") {\n // Assign IDs to newly added elements and their entire subtrees.\n // assignDomIdToTree skips contenteditable subtrees, so editors\n // like ProseMirror won't get foreign attributes.\n for (const node of mutation.addedNodes) {\n if (node instanceof Element && root.contains(node)) {\n assignDomIdToTree(node);\n }\n }\n\n // Track parent for childList mutations\n if (mutation.target instanceof Element && root.contains(mutation.target)) {\n mutatedElements.add(mutation.target);\n }\n }\n }\n\n if (mutatedElements.size > 0) {\n onMutation();\n }\n });\n\n observer.observe(root, {\n childList: true,\n subtree: true,\n attributes: true,\n characterData: true,\n });\n\n return {\n root,\n mutatedElements,\n stop: () => {\n observer.disconnect();\n mutatedElements.clear();\n },\n };\n}\n\n/**\n * Flushes the watcher, returning the LCA of all mutations and clearing state.\n *\n * @returns The lowest common ancestor of all mutations, or null if no mutations\n */\nexport function flushDomWatcher(watcher: DomWatcher): Element | null {\n if (watcher.mutatedElements.size === 0) {\n return null;\n }\n\n const lca = findLowestCommonAncestor(watcher.mutatedElements);\n watcher.mutatedElements.clear();\n\n // If LCA is outside our root (shouldn't happen, but safety check)\n if (lca && !watcher.root.contains(lca) && lca !== watcher.root) {\n return watcher.root;\n }\n\n return lca;\n}\n\n/**\n * Checks if watcher has any pending mutations.\n */\nexport function hasPendingMutations(watcher: DomWatcher): boolean {\n return watcher.mutatedElements.size > 0;\n}\n","/**\n * State Watcher\n *\n * Tracks element state changes (form values, scroll positions) via events.\n * Much more efficient than DOM traversal - only tracks elements that received events.\n */\n\nimport type { ElementState } from \"./types\";\nimport { generateSelector } from \"./selectors\";\n\n/**\n * State for a state watcher instance.\n */\nexport interface StateWatcher {\n /** The root element being watched */\n root: Element;\n /** Elements that have received scroll events */\n scrolledElements: Set<Element>;\n /** Elements that have received input/change events */\n changedFormElements: Set<Element>;\n /** Stop watching */\n stop: () => void;\n}\n\n/**\n * Starts watching an element for state changes (form input, scroll).\n *\n * Uses event listeners in capture phase to catch all events.\n * Changes are collected in Sets and can be flushed via flushStateWatcher().\n *\n * @param root - Element to watch\n * @param onStateChange - Called when any state change occurs (for triggering flush)\n * @returns StateWatcher instance\n */\nexport function watchState(\n root: Element,\n onStateChange: () => void\n): StateWatcher {\n const scrolledElements = new Set<Element>();\n const changedFormElements = new Set<Element>();\n\n const handleScroll = (event: Event) => {\n const target = event.target;\n if (target instanceof Element && root.contains(target)) {\n scrolledElements.add(target);\n onStateChange();\n } else if (target === document) {\n // Document-level scroll - scrollingElement is usually <html> which doesn't\n // satisfy root.contains() when root is <body>. We track this specially.\n const scrollTarget = document.scrollingElement || document.documentElement;\n if (scrollTarget) {\n // Use a marker for document-level scroll (we'll handle it specially in flush)\n scrolledElements.add(scrollTarget);\n onStateChange();\n }\n }\n };\n\n const handleFormChange = (event: Event) => {\n if (event.target instanceof Element && root.contains(event.target)) {\n changedFormElements.add(event.target);\n onStateChange();\n }\n };\n\n // Use capture phase to catch all events\n document.addEventListener(\"scroll\", handleScroll, true);\n document.addEventListener(\"input\", handleFormChange, true);\n document.addEventListener(\"change\", handleFormChange, true);\n\n return {\n root,\n scrolledElements,\n changedFormElements,\n stop: () => {\n document.removeEventListener(\"scroll\", handleScroll, true);\n document.removeEventListener(\"input\", handleFormChange, true);\n document.removeEventListener(\"change\", handleFormChange, true);\n scrolledElements.clear();\n changedFormElements.clear();\n },\n };\n}\n\n/**\n * Flushes the state watcher, collecting current states and clearing tracking.\n *\n * Only returns states for elements that have changed since last flush.\n * Elements with non-default state are re-added to tracking to ensure\n * they're reported again if HTML is replaced.\n *\n * @param watcher - The state watcher to flush\n * @returns Array of element states\n */\nexport function flushStateWatcher(watcher: StateWatcher): ElementState[] {\n const { root, scrolledElements, changedFormElements } = watcher;\n const states: ElementState[] = [];\n\n // Swap to fresh sets\n const scrolled = new Set(scrolledElements);\n const changed = new Set(changedFormElements);\n scrolledElements.clear();\n changedFormElements.clear();\n\n // Process scrolled elements\n for (const el of scrolled) {\n // Check for document-level scroll (scrollingElement, usually <html>)\n const isDocumentScroll =\n el === document.scrollingElement || el === document.documentElement;\n\n // Skip elements not in root, unless it's document-level scroll\n if (!isDocumentScroll && !root.contains(el)) continue;\n\n // For document-level scroll, use special \":root\" selector\n // For elements within root, generate relative selector\n const selector = isDocumentScroll ? \":root\" : generateSelector(el, root);\n states.push({\n selector,\n scrollTop: el.scrollTop,\n scrollLeft: el.scrollLeft,\n });\n }\n\n // Process changed form elements\n for (const el of changed) {\n if (!root.contains(el)) continue;\n\n if (el instanceof HTMLInputElement) {\n const isCheckable = el.type === \"checkbox\" || el.type === \"radio\";\n const hasNonDefault = isCheckable\n ? el.checked !== el.defaultChecked\n : el.value !== el.defaultValue;\n\n if (hasNonDefault) {\n const selector = generateSelector(el, root);\n if (isCheckable) {\n states.push({ selector, checked: el.checked });\n } else {\n states.push({ selector, value: el.value });\n }\n changedFormElements.add(el);\n }\n } else if (el instanceof HTMLTextAreaElement) {\n if (el.value !== el.defaultValue) {\n const selector = generateSelector(el, root);\n states.push({ selector, value: el.value });\n changedFormElements.add(el);\n }\n } else if (el instanceof HTMLSelectElement) {\n let hasNonDefault = false;\n for (const option of el.options) {\n if (option.selected !== option.defaultSelected) {\n const selector = generateSelector(option, root);\n states.push({ selector, selected: option.selected });\n hasNonDefault = true;\n }\n }\n if (hasNonDefault) {\n changedFormElements.add(el);\n }\n }\n }\n\n return states;\n}\n\n/**\n * Checks if watcher has any pending state changes.\n */\nexport function hasPendingStateChanges(watcher: StateWatcher): boolean {\n return watcher.scrolledElements.size > 0 || watcher.changedFormElements.size > 0;\n}\n","/**\n * Portal Element Watcher\n *\n * Wraps MutationObserver for a single portal element.\n * Reuses the same watch-dom and watch-state logic but scoped to the portal.\n */\n\nimport { watchDom, flushDomWatcher, hasPendingMutations } from \"./watch-dom\";\nimport {\n watchState,\n flushStateWatcher,\n hasPendingStateChanges,\n} from \"./watch-state\";\nimport { generateSelector } from \"./selectors\";\nimport type { PortalUpdate } from \"./types\";\nimport { removeScriptTags } from \"./capture\";\n\n/** Counter for generating unique portal IDs */\nlet portalIdCounter = 0;\n\n/** Attribute name for portal ID */\nexport const PORTAL_ID_ATTR = \"data-projection-portal-id\";\n\n/**\n * Reset portal ID counter. For testing only.\n * @internal\n */\nexport function _resetPortalIdCounter(): void {\n portalIdCounter = 0;\n}\n\nexport interface PortalWatcherHandle {\n /** The portal's unique ID */\n id: string;\n\n /** The portal root element */\n element: Element;\n\n /** Check if there are pending changes */\n hasPendingChanges(): boolean;\n\n /** Flush changes and get update (or null if no changes) */\n flush(isInitial?: boolean): PortalUpdate | null;\n\n /** Stop watching */\n stop(): void;\n}\n\n/**\n * Start watching a portal element for changes.\n *\n * @param element - The portal root element (direct child of body)\n * @param onTrigger - Called when mutations are detected (for debounce integration)\n */\nexport function watchPortal(\n element: Element,\n onTrigger: () => void\n): PortalWatcherHandle {\n // Assign or retrieve stable ID\n let id = element.getAttribute(PORTAL_ID_ATTR);\n if (!id) {\n id = `portal-${++portalIdCounter}`;\n element.setAttribute(PORTAL_ID_ATTR, id);\n }\n\n // Start watchers\n const domWatcher = watchDom(element, onTrigger);\n const stateWatcher = watchState(element, onTrigger);\n\n return {\n id,\n element,\n\n hasPendingChanges(): boolean {\n return (\n hasPendingMutations(domWatcher) || hasPendingStateChanges(stateWatcher)\n );\n },\n\n flush(isInitial = false): PortalUpdate | null {\n const hasDomChanges = hasPendingMutations(domWatcher);\n const hasStateChanges = hasPendingStateChanges(stateWatcher);\n\n if (!isInitial && !hasDomChanges && !hasStateChanges) {\n return null;\n }\n\n // Get LCA of mutations or use root for initial\n let targetElement = element;\n if (!isInitial && hasDomChanges) {\n const lca = flushDomWatcher(domWatcher);\n if (lca && element.contains(lca)) {\n targetElement = lca;\n }\n } else {\n flushDomWatcher(domWatcher);\n }\n\n // Collect states\n const states = flushStateWatcher(stateWatcher);\n\n // Generate selector relative to portal root\n const selector = generateSelector(targetElement, element);\n // Use outerHTML to capture the portal root element itself, not just its children.\n // This is important because the portal root often has critical styling (e.g., position: fixed\n // for modal overlays) that must be preserved in the projection.\n const html = removeScriptTags(targetElement.outerHTML);\n\n return { id, selector, html, states };\n },\n\n stop(): void {\n domWatcher.stop();\n stateWatcher.stop();\n },\n };\n}\n\n/**\n * Create a \"removed\" update for a portal that was removed from DOM.\n */\nexport function createPortalRemovedUpdate(id: string): PortalUpdate {\n return {\n id,\n selector: \"\",\n html: \"\",\n states: [],\n removed: true,\n };\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 { getFiberFromElement } from \"../fiber/capture\";\nimport type { Fiber } from \"../fiber/react-types\";\nimport {\n captureWithSupplementalRoots,\n collectElementStates,\n removeScriptTags,\n} from \"./capture\";\nimport type { DomCapture, PortalUpdate } from \"./types\";\nimport { captureHead } from \"./watch-head\";\nimport { PORTAL_ID_ATTR } from \"./watch-portal\";\n\nlet nextPortalId = 1;\n\nexport function captureProjectionSnapshot(\n element: Element,\n supplementalRoots?: readonly Element[],\n): DomCapture {\n const head = captureHead(element.ownerDocument ?? document);\n const { updates: portals, elements: portalElements } = supplementalRoots\n ? captureKnownPortals(supplementalRoots)\n : capturePortals(element);\n const baseCapture = captureWithSupplementalRoots(element, portalElements);\n\n return {\n ...baseCapture,\n portalsComplete: true,\n head,\n ...(portals.length > 0 ? { portals } : {}),\n };\n}\n\nexport function collectProjectionPortalElements(root: Element): Element[] {\n return capturePortals(root).elements;\n}\n\nfunction captureKnownPortals(roots: readonly Element[]): 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 updates.push({\n id,\n selector: \"\",\n html: removeScriptTags(root.outerHTML),\n states: collectElementStates(root, { includeDocumentScroll: false }),\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 const doc = root.ownerDocument;\n const body = doc?.body;\n if (!body) return { updates: [], elements: [] };\n\n const updates: PortalUpdate[] = [];\n const elements: Element[] = [];\n for (const child of Array.from(body.children)) {\n if (child === root || root.contains(child)) {\n continue;\n }\n if (!isPortalForRoot(child, root)) {\n continue;\n }\n\n const id = getOrAssignPortalId(child);\n updates.push({\n id,\n selector: \"\",\n html: removeScriptTags(child.outerHTML),\n states: collectElementStates(child, { includeDocumentScroll: false }),\n });\n elements.push(child);\n }\n\n return { updates, elements };\n}\n\nfunction isPortalForRoot(candidate: Element, root: Element): boolean {\n const fiber = getFiberFromElement(candidate);\n if (!fiber) {\n return false;\n }\n\n let current: Fiber | null = fiber.return;\n while (current) {\n if (current.stateNode instanceof Element) {\n const ancestor = current.stateNode;\n if (ancestor === root || root.contains(ancestor)) {\n return true;\n }\n }\n current = current.return;\n }\n\n return false;\n}\n\nfunction getOrAssignPortalId(element: Element): string {\n const existing = element.getAttribute(PORTAL_ID_ATTR);\n if (existing) {\n return existing;\n }\n\n const id = `portal-${nextPortalId++}`;\n element.setAttribute(PORTAL_ID_ATTR, id);\n return id;\n}\n","/**\n * Portal Tracker\n *\n * Watches document.body for new children 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\";\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\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\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: check existing body children\n for (const child of Array.from(document.body.children)) {\n this.checkElement(child);\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 }\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 });\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 // Defer check to allow React to attach fiber\n // React attaches __reactFiber$* keys after DOM insertion\n queueMicrotask(() => this.checkElement(node));\n }\n }\n\n // Handle removed nodes\n for (const node of mutation.removedNodes) {\n if (node instanceof Element) {\n const owners = this.trackedPortals.get(node);\n if (owners) {\n for (const owner of owners) {\n owner.onPortalRemoved(node);\n }\n this.trackedPortals.delete(node);\n }\n }\n }\n }\n };\n\n /**\n * Check if an element is a portal belonging to any registered watcher.\n */\n private checkElement(element: Element): void {\n // Get DOM ancestors via fiber tree\n const ancestorDomNodes = this.getDomAncestorsViaFiber(element);\n if (ancestorDomNodes.length === 0) return; // Not a React element\n\n let owners = this.trackedPortals.get(element);\n\n // Check against each watcher\n for (const watcher of this.watchers) {\n const belongsToWatcher = ancestorDomNodes.some(\n (node) => watcher.element.contains(node) || watcher.element === node\n );\n\n if (belongsToWatcher) {\n if (!owners) {\n owners = new Set<PortalWatcher>();\n this.trackedPortals.set(element, owners);\n }\n if (owners.has(watcher)) {\n continue;\n }\n owners.add(watcher);\n watcher.onPortalFound(element);\n }\n }\n }\n\n /**\n * Walk up the fiber tree from an element and collect all DOM nodes encountered.\n *\n * React fibers form a tree where fiber.return points to the parent.\n * For HostComponent fibers (DOM elements), stateNode is the DOM Element.\n * By collecting these, we get the \"DOM ancestry\" through React's logical tree,\n * which differs from actual DOM ancestry for portals.\n */\n private getDomAncestorsViaFiber(element: Element): Element[] {\n const fiber = getFiberFromElement(element);\n if (!fiber) return [];\n\n const domNodes: Element[] = [];\n let current: Fiber | null = fiber.return;\n\n while (current) {\n if (current.stateNode instanceof Element) {\n domNodes.push(current.stateNode);\n }\n current = current.return;\n }\n\n return domNodes;\n }\n}\n","import { getFiberFromElement } from \"../fiber/capture\";\nimport { FiberTag } from \"../fiber/react-types\";\nimport { resolveCommittedFiber } from \"../fiber/serialize\";\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 \"data-tempo-html-filepath\",\n \"data-tempo-html-offset\",\n \"data-tempo-html-modifiedts\",\n \"data-tempo-html-source-version\",\n] as const;\n\nconst TRANSIENT_FIBER_RESOLUTION_ERRORS = new Set([\n \"Unable to resolve a mounted React fiber\",\n \"React fiber is absent from both parent generations\",\n \"React return fibers are not paired alternates\",\n \"Unable to resolve an unmounted React fiber\",\n]);\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 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 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 (\n !(error instanceof Error) ||\n !TRANSIENT_FIBER_RESOLUTION_ERRORS.has(error.message)\n ) {\n throw error;\n }\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` / `data-tempo-html-modifiedts` among\n * a walked fiber tree's annotated props, across BOTH namespaces, plus the\n * `data-tempo-source-version` / `data-tempo-html-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 record(\n props?.[\"data-tempo-html-filepath\"],\n props?.[\"data-tempo-html-modifiedts\"],\n props?.[\"data-tempo-html-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 { SerializeFn } from \"../fiber/types\";\nimport type { Fiber } from \"../fiber/react-types\";\nimport type { EnrichedFiberNode } from \"./types\";\nimport {\n getDisplayName,\n getTag,\n getDomElement,\n sanitizeProps,\n getProps,\n} from \"../fiber/serialize\";\nimport { DOM_ID_ATTR } from \"../html/watch-dom\";\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 return {\n fiberId: getFiberId(fiber),\n name: getDisplayName(fiber),\n tag: getTag(fiber),\n ...(hasContextDependencies(fiber) && { hasContextDependencies: true }),\n ...(domElement && {\n domId: domElement.getAttribute(DOM_ID_ATTR) ?? undefined,\n ...(hasContentEditableAncestor(domElement) && {\n insideContentEditable: true,\n }),\n layoutKind: getElementLayoutKind(domElement) ?? undefined,\n }),\n props: normalizeTempoDataSet(sanitizeProps(getProps(fiber))),\n };\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(\n (dependencies as { firstContext?: unknown }).firstContext,\n );\n}\n","import type { Fiber, FiberRoot } from \"../fiber/react-types\";\nimport { getProps, 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\ntype SourceVersionFiberNode = EnrichedFiberConstraint & {\n props?: Record<string, unknown>;\n children: SourceVersionFiberNode[];\n};\n\nconst sourceVersionSerialize: SerializeFn<SourceVersionFiberNode> = (\n fiber: Fiber,\n) => ({\n fiberId: \"\",\n props: getProps(fiber) as Record<string, unknown> | undefined,\n});\n\nexport const captureCombinedFiberSourceVersion = (options: {\n selector?: string;\n rootElement?: Element;\n tags?: FiberTagValue[];\n hideFiberProp?: string;\n}): number | null => {\n const tree = captureCombinedFiberTree<SourceVersionFiberNode>({\n serialize: sourceVersionSerialize,\n selector: options.selector,\n rootElement: options.rootElement,\n tags: options.tags,\n hideFiberProp: options.hideFiberProp,\n });\n if (!tree) return null;\n\n let max: number | null = null;\n const updateMax = (mtimeRaw: unknown): void => {\n const value =\n typeof mtimeRaw === \"number\"\n ? mtimeRaw\n : typeof mtimeRaw === \"string\"\n ? parseInt(mtimeRaw, 10)\n : NaN;\n if (!Number.isNaN(value) && (max === null || value > max)) {\n max = value;\n }\n };\n const visit = (node: SourceVersionFiberNode): void => {\n updateMax(node.props?.[\"data-tempo-modifiedts\"]);\n updateMax(node.props?.[\"data-tempo-html-modifiedts\"]);\n for (const child of node.children) visit(child);\n };\n\n visit(tree);\n return max;\n};\n","/**\n * Combined DOM + Fiber Watcher\n *\n * Composes the lower-level HTML watchers (DOM, state, head, portal) with\n * the fiber hook's onCommit into a single debounced stream of CombinedCapture\n * objects.\n *\n * The combined watch owns the debounce. All 5 trigger sources feed into a\n * single triggerFlush().\n */\n\nimport { getFiberFromElement } from \"../fiber/capture\";\nimport type { Fiber, FiberRoot } from \"../fiber/react-types\";\nimport { resolveCommittedFiber } from \"../fiber/serialize\";\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport { initHook } from \"../fiber/watch\";\nimport { captureAttributes, removeScriptTags } from \"../html/capture\";\nimport { computeDeclaredFacts } from \"../html/declared-facts\";\nimport { measureComputedDisplayability } from \"../html/displayability\";\nimport { generateSelector } from \"../html/selectors\";\nimport { captureProjectionSnapshot } from \"../html/snapshot\";\nimport type { DomCapture, PortalUpdate } from \"../html/types\";\nimport {\n flushDomWatcher,\n hasPendingMutations,\n watchDom,\n} from \"../html/watch-dom\";\nimport { getHeadTracker } from \"../html/watch-head\";\nimport {\n createPortalRemovedUpdate,\n type PortalWatcherHandle,\n watchPortal,\n} from \"../html/watch-portal\";\nimport {\n flushStateWatcher,\n hasPendingStateChanges,\n watchState,\n} from \"../html/watch-state\";\nimport { getPortalTracker } from \"../shared/portal-tracker\";\nimport {\n computeRenderDeclarations,\n createRenderDeclarationScope,\n} from \"./declared-facts\";\nimport { enrichedSerialize } from \"./enriched-serialize\";\nimport {\n captureCombinedFiberSourceVersion,\n captureCombinedFiberTree,\n} from \"./hide-fiber-tree\";\nimport {\n nextRealmCaptureSequence,\n REALM_DOCUMENT_EPOCH,\n} from \"./realm-epoch\";\nimport type {\n CombinedCapture,\n CombinedCaptureProvenance,\n CombinedSourceVersion,\n CombinedWatchTrigger,\n EnrichedFiberConstraint,\n EnrichedFiberNode,\n} from \"./types\";\n\n/** Default debounce delay (ms) */\nconst DEBOUNCE_DELAY = 50;\n\n/** Max wait before forcing a flush (ms) */\nconst MAX_WAIT = 250;\n\n/**\n * Fiber flags that indicate render-affecting changes (content changed).\n * Copied from fiber/watch.ts — just a bitmask constant.\n */\nconst RENDER_CHANGE_FLAGS =\n 2 | // Placement\n 4 | // Update\n 16 | // ChildDeletion\n 32 | // ContentReset\n 128 | // DidCapture\n 256; // ForceClientRender\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Options\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface CombinedWatchOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n /** Debounce delay in ms (default: 50) */\n debounceDelay?: number;\n /** Max wait before forcing flush in ms (default: 250) */\n maxWait?: number;\n /** Custom fiber serializer (default: enrichedSerialize) */\n serialize?: SerializeFn<T>;\n /** CSS selector for fiber tree root (default: full tree) */\n fiberSelector?: string;\n /** Fiber tag whitelist filter */\n fiberTags?: FiberTagValue[];\n /** Hide fibers whose serialized props contain this truthy prop */\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\n// ─────────────────────────────────────────────────────────────────────────────\n// Combined Watch\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Watch an element for both DOM changes and React fiber tree changes.\n *\n * All trigger sources (DOM mutations, state changes, head changes, portal\n * changes, fiber commits) feed into a single debounce timer, producing\n * CombinedCapture objects from the same flush moment. The watcher does not\n * interpret mtimes or decide whether a capture is safe to reconcile; consumers\n * own that policy.\n *\n * @param element - Element to watch for DOM changes\n * @param onChange - Called with CombinedCapture when changes are flushed\n * @param options - Watch options\n * @returns Cleanup function\n */\n\n/** React-renderer presence must be judged in the WATCHED element's realm. A\n * parent-realm watcher (direct iframe watching) would otherwise report its\n * own document's React and let a pending child React shell masquerade as a\n * complete static document. Same-realm watchers keep the local hook. */\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 if (view && view !== window) {\n return (view.__REACT_DEVTOOLS_GLOBAL_HOOK__?.renderers?.size ?? 0) > 0;\n }\n return localHook.hook.renderers.size > 0;\n}\n\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 {\n debounceDelay = DEBOUNCE_DELAY,\n maxWait = MAX_WAIT,\n serialize,\n fiberSelector,\n fiberTags,\n hideFiberProp,\n } = options;\n\n const serializeFn =\n serialize ?? (enrichedSerialize as unknown as SerializeFn<T>);\n const reactHook = initHook();\n\n let debounceTimer: ReturnType<typeof setTimeout> | null = null;\n let maxWaitTimer: ReturnType<typeof setTimeout> | null = null;\n let fiberDirty = false;\n let paused = false;\n let stopped = false;\n let dirtyWhilePaused = false;\n // Portal tracking\n const portalWatchers = new Map<Element, PortalWatcherHandle>();\n const pendingPortalRemovals: string[] = [];\n const portalWatchersNeedingInitialFlush = new Set<PortalWatcherHandle>();\n\n // ── Debounce ──────────────────────────────────────────────────────────────\n\n const clearFlushTimers = () => {\n if (debounceTimer) {\n clearTimeout(debounceTimer);\n debounceTimer = null;\n }\n if (maxWaitTimer) {\n clearTimeout(maxWaitTimer);\n maxWaitTimer = null;\n }\n };\n\n const scheduleFlush = () => {\n if (stopped) {\n return;\n }\n if (paused) {\n dirtyWhilePaused = true;\n clearFlushTimers();\n return;\n }\n\n if (debounceTimer) {\n clearTimeout(debounceTimer);\n debounceTimer = null;\n }\n debounceTimer = setTimeout(flush, debounceDelay);\n\n if (!maxWaitTimer) {\n maxWaitTimer = setTimeout(flush, maxWait);\n }\n };\n\n const triggerFlush = (_trigger: CombinedWatchTrigger) => scheduleFlush();\n\n // ── Flush ─────────────────────────────────────────────────────────────────\n\n const captureFiberTree = (): T | null =>\n captureCombinedFiberTree<T>({\n serialize: serializeFn,\n selector: fiberSelector,\n rootElement: element,\n tags: fiberTags,\n hideFiberProp,\n });\n\n const watchedFiberForCommit = (fiberRoot: FiberRoot): Fiber | null => {\n const target = fiberSelector\n ? element.ownerDocument?.querySelector(fiberSelector)\n : element;\n if (!target) return null;\n // Document-level route watches bind to `body`, while React normally mounts\n // into a nested container such as `#root`. That root still belongs wholly\n // to the watched surface, so its commits must drive combined captures.\n // Selector-scoped watches inside a root continue through the element-fiber\n // branch below and therefore do not acquire sibling-root commits.\n if (\n fiberRoot.containerInfo === target ||\n target.contains(fiberRoot.containerInfo)\n ) {\n return fiberRoot.current;\n }\n const rawFiber = getFiberFromElement(target);\n if (!rawFiber) return null;\n const committed = resolveCommittedFiber(rawFiber);\n let root: Fiber = committed;\n while (root.return) root = root.return;\n return root === fiberRoot.current ? committed : null;\n };\n\n const fiberHasRenderChanges = (fiber: Fiber): boolean =>\n ((((fiber as { flags?: number }).flags ?? 0) |\n ((fiber as { subtreeFlags?: number }).subtreeFlags ?? 0)) &\n RENDER_CHANGE_FLAGS) !==\n 0;\n\n const getCurrentSourceVersion = (options: {\n html: boolean;\n fiber: boolean;\n }): CombinedSourceVersion => ({\n ...(options.html && {\n htmlModifiedTs:\n getMaxModifiedTsFromElements([\n element,\n ...Array.from(portalWatchers.keys()),\n ]) ?? undefined,\n }),\n ...(options.fiber && {\n fiberModifiedTs:\n captureCombinedFiberSourceVersion({\n selector: fiberSelector,\n rootElement: element,\n tags: fiberTags,\n hideFiberProp,\n }) ?? undefined,\n }),\n });\n\n const emitCapture = (\n capture: Omit<CombinedCapture<T>, \"sequence\">,\n provenance: CombinedCaptureProvenance,\n ): void => {\n onChange({\n ...capture,\n provenance,\n documentEpoch: REALM_DOCUMENT_EPOCH,\n sequence: nextRealmCaptureSequence(),\n });\n };\n\n const hasDirtySources = (): boolean =>\n hasPendingMutations(domWatcher) ||\n hasPendingStateChanges(stateWatcher) ||\n pendingPortalRemovals.length > 0 ||\n portalWatchersNeedingInitialFlush.size > 0 ||\n Array.from(portalWatchers.values()).some((w) => w.hasPendingChanges()) ||\n headSubscription.hasMutations ||\n fiberDirty;\n\n const flush = (\n isFirstFlush = false,\n additionalTriggers: readonly CombinedWatchTrigger[] = [],\n ) => {\n if (stopped) {\n return;\n }\n if (paused) {\n dirtyWhilePaused = true;\n clearFlushTimers();\n return;\n }\n clearFlushTimers();\n\n if (isFirstFlush) {\n // First emission: full snapshot of both sides\n flushDomWatcher(domWatcher);\n flushStateWatcher(stateWatcher);\n for (const handle of portalWatchers.values()) {\n handle.flush(true);\n }\n pendingPortalRemovals.length = 0;\n portalWatchersNeedingInitialFlush.clear();\n fiberDirty = false;\n\n const sourceVersion = getCurrentSourceVersion({\n html: true,\n fiber: true,\n });\n const html = captureProjectionSnapshot(\n element,\n Array.from(portalWatchers.keys()),\n );\n const fiber = captureFiberTree();\n const captureSourceVersion = {\n htmlModifiedTs:\n sourceVersion.htmlModifiedTs ??\n getMaxModifiedTsFromHtml(html) ??\n undefined,\n fiberModifiedTs:\n sourceVersion.fiberModifiedTs ??\n getMaxModifiedTsFromFiber(fiber) ??\n undefined,\n };\n\n emitCapture(\n {\n html,\n fiber: fiber ?? null,\n ...computeRenderDeclarations(\n fiber,\n html,\n realmHasReactRenderer(element, reactHook),\n element.ownerDocument,\n createRenderDeclarationScope(\n element,\n Array.from(portalWatchers.keys()),\n ),\n ),\n sourceVersion: captureSourceVersion,\n },\n { kind: \"initial\" },\n );\n return;\n }\n\n // Check dirty flags\n const hasDomChanges = hasPendingMutations(domWatcher);\n const hasStateChanges = hasPendingStateChanges(stateWatcher);\n const hasPortalChanges =\n pendingPortalRemovals.length > 0 ||\n portalWatchersNeedingInitialFlush.size > 0 ||\n Array.from(portalWatchers.values()).some((w) => w.hasPendingChanges());\n const hasHeadChanges = headSubscription.hasMutations;\n const hasFiberChanges = fiberDirty;\n if (\n !hasDomChanges &&\n !hasStateChanges &&\n !hasPortalChanges &&\n !hasHeadChanges &&\n !hasFiberChanges\n ) {\n return;\n }\n\n const sourceVersion =\n hasDomChanges || hasFiberChanges\n ? getCurrentSourceVersion({\n html: hasDomChanges,\n fiber: hasFiberChanges,\n })\n : undefined;\n\n // ── HTML capture (if any HTML-side sources are dirty) ─────────────────\n\n let htmlCapture: DomCapture | undefined;\n\n if (hasFiberChanges) {\n // A fiber-affecting observation is one atomic render candidate. Capture\n // the whole DOM in the same synchronous turn as the fiber walk below so\n // the destination never has to combine independently sampled versions.\n htmlCapture = captureProjectionSnapshot(\n element,\n Array.from(portalWatchers.keys()),\n );\n flushDomWatcher(domWatcher);\n flushStateWatcher(stateWatcher);\n pendingPortalRemovals.length = 0;\n portalWatchersNeedingInitialFlush.clear();\n for (const handle of portalWatchers.values()) handle.flush(false);\n headSubscription.flush(false);\n } else if (\n hasDomChanges ||\n hasStateChanges ||\n hasPortalChanges ||\n hasHeadChanges\n ) {\n let targetElement = element;\n if (hasDomChanges) {\n const lca = flushDomWatcher(domWatcher);\n if (lca && element.contains(lca)) {\n targetElement = lca;\n }\n } else {\n flushDomWatcher(domWatcher);\n }\n\n const states = flushStateWatcher(stateWatcher);\n\n const selector = generateSelector(targetElement, element);\n const html = removeScriptTags(targetElement.innerHTML);\n const attributes = captureAttributes(targetElement);\n const rootAttributes =\n element === targetElement ? undefined : captureAttributes(element);\n const documentElementAttributes = element.ownerDocument\n ? captureAttributes(element.ownerDocument.documentElement)\n : undefined;\n const baseUrl = element.ownerDocument?.baseURI;\n\n // Collect portal updates\n const portals: PortalUpdate[] = [];\n for (const id of pendingPortalRemovals) {\n portals.push(createPortalRemovedUpdate(id));\n }\n pendingPortalRemovals.length = 0;\n\n for (const handle of portalWatchers.values()) {\n const needsInitialFlush = portalWatchersNeedingInitialFlush.has(handle);\n const update = handle.flush(needsInitialFlush);\n if (update) portals.push(update);\n portalWatchersNeedingInitialFlush.delete(handle);\n }\n\n const head = headSubscription.flush(false);\n\n const portalElements = Array.from(portalWatchers.keys());\n const declared = computeDeclaredFacts(\n targetElement,\n element,\n selector,\n portalElements,\n );\n const displayability = declared.complete\n ? measureComputedDisplayability(element, portalElements)\n : null;\n htmlCapture = {\n declared,\n ...(displayability && { displayability }),\n dom: {\n selector,\n html,\n attributes,\n rootAttributes,\n documentElementAttributes,\n },\n states,\n baseUrl,\n ...(portals.length > 0 && { portals }),\n ...(head !== undefined && { head }),\n };\n } else {\n // Clear pending HTML state even if we're not emitting HTML\n flushDomWatcher(domWatcher);\n flushStateWatcher(stateWatcher);\n }\n\n // ── Fiber capture (if fiber dirty) ────────────────────────────────────\n\n let fiberCapture: T | null | undefined;\n\n if (hasFiberChanges) {\n fiberDirty = false;\n const tree = captureFiberTree();\n fiberCapture = tree ?? null;\n }\n\n const triggers = new Set<CombinedWatchTrigger>([\n ...(hasDomChanges ? ([\"dom\"] as const) : []),\n ...(hasStateChanges ? ([\"state\"] as const) : []),\n ...(hasHeadChanges ? ([\"head\"] as const) : []),\n ...(hasPortalChanges ? ([\"portal\"] as const) : []),\n ...(hasFiberChanges ? ([\"fiber\"] as const) : []),\n ...additionalTriggers,\n ]);\n emitCapture(\n {\n ...(htmlCapture !== undefined && { html: htmlCapture }),\n ...(fiberCapture !== undefined && {\n fiber: fiberCapture,\n }),\n ...computeRenderDeclarations(\n fiberCapture,\n htmlCapture,\n realmHasReactRenderer(element, reactHook),\n element.ownerDocument,\n createRenderDeclarationScope(\n element,\n Array.from(portalWatchers.keys()),\n ),\n ),\n ...(sourceVersion && { sourceVersion }),\n },\n { kind: \"watch\", triggers: [...triggers] },\n );\n };\n\n // ── Start watchers ──────────────────────────────────────────────────────\n\n const domWatcher = watchDom(element, () => triggerFlush(\"dom\"));\n const stateWatcher = watchState(element, () => triggerFlush(\"state\"));\n const headSubscription = getHeadTracker().subscribe(\n element.ownerDocument!,\n () => triggerFlush(\"head\"),\n );\n // A direct parent-realm iframe watch subscribes to a child document. The\n // shared head tracker still receives those mutations, but its tag filtering\n // uses constructors from the parent realm, so a Vite <style> text\n // replacement can be missed. Observe the head with the watched document's\n // own MutationObserver and mark the shared subscription dirty so the normal\n // combined flush captures the updated stylesheet.\n const watchedDocument = element.ownerDocument;\n const watchedWindow = watchedDocument?.defaultView;\n const crossRealmHeadObserver =\n watchedWindow && watchedWindow !== window && watchedDocument.head\n ? new watchedWindow.MutationObserver(() => {\n headSubscription.hasMutations = true;\n triggerFlush(\"head\");\n })\n : null;\n crossRealmHeadObserver?.observe(watchedDocument.head, {\n childList: true,\n subtree: true,\n attributes: true,\n characterData: true,\n });\n\n // Portal tracking\n const portalTracker = getPortalTracker();\n const unregisterPortalWatcher = portalTracker.register({\n element,\n onPortalFound: (portalRoot) => {\n const handle = watchPortal(portalRoot, () => triggerFlush(\"portal\"));\n portalWatchers.set(portalRoot, handle);\n portalWatchersNeedingInitialFlush.add(handle);\n triggerFlush(\"portal\");\n },\n onPortalRemoved: (portalRoot) => {\n const handle = portalWatchers.get(portalRoot);\n if (handle) {\n handle.stop();\n pendingPortalRemovals.push(handle.id);\n portalWatchers.delete(portalRoot);\n triggerFlush(\"portal\");\n }\n },\n });\n\n // Fiber commit handler\n const { onCommit } = reactHook;\n const unsubFiber = onCommit((fiberRoot: FiberRoot) => {\n const watchedFiber = watchedFiberForCommit(fiberRoot);\n if (!watchedFiber) return;\n const hasRenderChanges = fiberHasRenderChanges(watchedFiber);\n if (!hasRenderChanges) return;\n fiberDirty = true;\n scheduleFlush();\n });\n\n // Send initial capture immediately\n flush(true);\n\n // ── Cleanup ─────────────────────────────────────────────────────────────\n\n const stop = () => {\n if (stopped) {\n return;\n }\n stopped = true;\n clearFlushTimers();\n domWatcher.stop();\n stateWatcher.stop();\n crossRealmHeadObserver?.disconnect();\n headSubscription.unsubscribe();\n unregisterPortalWatcher();\n unsubFiber();\n for (const handle of portalWatchers.values()) {\n handle.stop();\n }\n portalWatchers.clear();\n };\n\n const pause = () => {\n if (stopped || paused) {\n return;\n }\n dirtyWhilePaused =\n dirtyWhilePaused ||\n debounceTimer !== null ||\n maxWaitTimer !== null ||\n hasDirtySources();\n paused = true;\n clearFlushTimers();\n };\n\n const resume = (resumeOptions?: CombinedWatchResumeOptions) => {\n if (stopped) {\n return;\n }\n const flushPolicy = resumeOptions?.flush ?? \"if-dirty\";\n const shouldFlush =\n flushPolicy === \"always\" ||\n (flushPolicy === \"if-dirty\" && (dirtyWhilePaused || hasDirtySources()));\n dirtyWhilePaused = false;\n paused = false;\n if (shouldFlush) {\n flush(false, resumeOptions?.triggers);\n }\n };\n\n return Object.assign(stop, {\n stop,\n pause,\n resume,\n setPaused: (\n nextPaused: boolean,\n setPausedOptions?: CombinedWatchResumeOptions,\n ) => {\n if (nextPaused) {\n pause();\n } else {\n resume(setPausedOptions);\n }\n },\n });\n}\n\n/**\n * Watch a selector that may transiently disappear from its document.\n *\n * This is the selector-aware layer used by iframe/webview transports. The\n * element-level watchCombined API intentionally remains bound to the Element it\n * was handed; this wrapper owns re-selecting the target when app HMR replaces a\n * root node inside the same document.\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 isDocumentRoot = root.nodeType === 9;\n let activeElement: Element | null = null;\n let activeWatcher: CombinedWatchHandle | null = null;\n let stopped = false;\n let paused = false;\n let dirtyWhilePaused = false;\n let activeParentObserver: MutationObserver | null = null;\n let missingTargetObserver: MutationObserver | null = null;\n let hasBoundOnce = false;\n\n const getTarget = (): Element | null => {\n if (selector) {\n return root.querySelector(selector);\n }\n if (isDocumentRoot) {\n return (root as Document).body;\n }\n return root as Element;\n };\n\n const stopActiveWatcher = () => {\n activeParentObserver?.disconnect();\n activeParentObserver = null;\n activeWatcher?.stop();\n activeWatcher = null;\n activeElement = null;\n };\n\n const stopMissingTargetObserver = () => {\n missingTargetObserver?.disconnect();\n missingTargetObserver = null;\n };\n\n const observeMissingTarget = () => {\n if (stopped || paused || !selector || missingTargetObserver) {\n return;\n }\n missingTargetObserver = new MutationObserver(reconcileTarget);\n missingTargetObserver.observe(root, {\n attributes: true,\n childList: true,\n subtree: true,\n });\n };\n\n const observeActiveParent = (element: Element) => {\n activeParentObserver?.disconnect();\n activeParentObserver = null;\n const parent = element.parentElement;\n if (!parent || !selector) {\n return;\n }\n activeParentObserver = new MutationObserver(reconcileTarget);\n activeParentObserver.observe(parent, { childList: true });\n };\n\n const bindTarget = (element: Element) => {\n stopMissingTargetObserver();\n activeElement = element;\n observeActiveParent(element);\n const isRebind = hasBoundOnce;\n hasBoundOnce = true;\n activeWatcher = watchCombined(\n element,\n (capture) => {\n if (!element.isConnected || element !== getTarget()) {\n reconcileTarget();\n return;\n }\n onChange({\n ...capture,\n ...(isRebind && capture.provenance?.kind === \"initial\"\n ? {\n provenance: {\n kind: \"watch\" as const,\n triggers: [\"selector-rebind\" as const],\n },\n }\n : {}),\n });\n // Re-verify the binding after every emission. Two real-world ways\n // the bound element stops being the selector's target while the\n // watcher keeps emitting:\n // - app HMR replaced the element AND its parent (the parent\n // childList observer never fires); the DOM half goes silent on\n // the detached node while the fiber side keeps committing, so\n // every capture is fiber-only and the replacement's HTML never\n // reaches the destination;\n // - React reconciled the element onto a DIFFERENT identity (a\n // sibling insert/remove repositions unkeyed children), so the\n // still-connected node now renders other content and the\n // captures feed the destination someone else's render.\n // `reconcileTarget` re-selects, tears down the stale binding, and\n // the fresh bind's initial flush carries the full new snapshot.\n },\n options,\n );\n if (paused) {\n activeWatcher.pause();\n dirtyWhilePaused = true;\n }\n };\n\n const reconcileTarget = () => {\n if (stopped) {\n return;\n }\n\n const nextElement = getTarget();\n const activeDetached = activeElement !== null && !activeElement.isConnected;\n const activeChanged =\n activeElement !== null && activeElement !== nextElement;\n\n if (activeDetached || activeChanged) {\n stopActiveWatcher();\n dirtyWhilePaused = true;\n }\n\n if (!nextElement) {\n observeMissingTarget();\n return;\n }\n\n stopMissingTargetObserver();\n\n if (!activeWatcher) {\n if (paused) {\n dirtyWhilePaused = true;\n return;\n }\n bindTarget(nextElement);\n }\n };\n\n reconcileTarget();\n\n const stop = () => {\n if (stopped) {\n return;\n }\n stopped = true;\n stopMissingTargetObserver();\n stopActiveWatcher();\n };\n\n const pause = () => {\n if (stopped || paused) {\n return;\n }\n paused = true;\n dirtyWhilePaused = true;\n stopMissingTargetObserver();\n activeWatcher?.pause();\n };\n\n const resume = (resumeOptions?: CombinedWatchResumeOptions) => {\n if (stopped) {\n return;\n }\n paused = false;\n if (activeWatcher) {\n activeWatcher.resume(resumeOptions);\n dirtyWhilePaused = false;\n reconcileTarget();\n return;\n }\n\n const flushPolicy = resumeOptions?.flush ?? \"if-dirty\";\n const shouldFlush =\n flushPolicy === \"always\" ||\n (flushPolicy === \"if-dirty\" && dirtyWhilePaused);\n dirtyWhilePaused = false;\n if (shouldFlush) {\n reconcileTarget();\n } else {\n observeMissingTarget();\n }\n };\n\n return Object.assign(stop, {\n stop,\n pause,\n resume,\n setPaused: (\n nextPaused: boolean,\n setPausedOptions?: CombinedWatchResumeOptions,\n ) => {\n if (nextPaused) {\n pause();\n } else {\n resume(setPausedOptions);\n }\n },\n });\n}\n\nfunction getMaxModifiedTsFromElements(\n elements: readonly Element[],\n): number | null {\n let max: number | null = null;\n const updateMax = (mtimeRaw: string | null): void => {\n if (mtimeRaw == null) return;\n const value = parseInt(mtimeRaw, 10);\n if (!Number.isNaN(value) && (max === null || value > max)) {\n max = value;\n }\n };\n const visit = (element: Element): void => {\n updateMax(element.getAttribute(\"data-tempo-modifiedts\"));\n updateMax(element.getAttribute(\"data-tempo-html-modifiedts\"));\n };\n for (const element of elements) {\n visit(element);\n for (const child of element.querySelectorAll(\n \"[data-tempo-modifiedts], [data-tempo-html-modifiedts]\",\n )) {\n visit(child);\n }\n }\n return max;\n}\n\nfunction getMaxModifiedTsFromHtml(capture: DomCapture): number | null {\n let max: number | null = null;\n const visitHtml = (html: string): void => {\n const tagRe = /<[^>]*data-tempo-(?:html-)?modifiedts=\"(\\d+)\"[^>]*>/g;\n for (\n let match = tagRe.exec(html);\n match !== null;\n match = tagRe.exec(html)\n ) {\n const modifiedTs = match[1];\n if (modifiedTs) {\n updateMax(parseInt(modifiedTs, 10));\n }\n }\n };\n const updateMax = (value: number): void => {\n if (!Number.isNaN(value) && (max === null || value > max)) {\n max = value;\n }\n };\n visitHtml(capture.dom.html);\n for (const portal of capture.portals ?? []) {\n visitHtml(portal.html);\n }\n return max;\n}\n\nfunction getMaxModifiedTsFromFiber<T extends EnrichedFiberConstraint>(\n tree: T | null,\n): number | null {\n if (!tree) return null;\n let max: number | null = null;\n const updateMax = (mtimeRaw: unknown): void => {\n const value =\n typeof mtimeRaw === \"number\"\n ? mtimeRaw\n : typeof mtimeRaw === \"string\"\n ? parseInt(mtimeRaw, 10)\n : NaN;\n if (!Number.isNaN(value) && (max === null || value > max)) {\n max = value;\n }\n };\n const visit = (node: EnrichedFiberConstraint): void => {\n const props = node.props;\n updateMax(props?.[\"data-tempo-modifiedts\"]);\n updateMax(props?.[\"data-tempo-html-modifiedts\"]);\n for (const child of node.children) {\n visit(child as EnrichedFiberConstraint);\n }\n };\n visit(tree);\n return max;\n}\n","/**\n * Combined PostMessage Interface\n *\n * Provides a postMessage interface for combined HTML + fiber projection\n * between iframes. Follows the same patterns as the HTML and fiber\n * postMessage interfaces.\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 { watchCombinedIframe } from '@modules/iframe-projection/combined/postmessage';\n *\n * const watcher = await watchCombinedIframe(iframe, {\n * onUpdate: (capture) => {\n * if (capture.html) applyDom(target, capture.html);\n * if (capture.fiber) renderTree(capture.fiber);\n * }\n * });\n *\n * watcher.stop();\n * ```\n */\n\nimport type { SerializeFn, FiberTagValue } from \"../fiber/types\";\nimport { initHook } from \"../fiber/watch\";\nimport {\n nextRealmCaptureSequence,\n REALM_DOCUMENT_EPOCH,\n} from \"./realm-epoch\";\nimport type {\n CombinedCapture,\n EnrichedFiberConstraint,\n EnrichedFiberNode,\n} from \"./types\";\nimport {\n watchCombinedSelector,\n type CombinedWatchHandle,\n} from \"./watch\";\nimport {\n computeRenderDeclarations,\n createRenderDeclarationScope,\n} from \"./declared-facts\";\nimport {\n captureProjectionSnapshot,\n collectProjectionPortalElements,\n} from \"../html/snapshot\";\nimport { enrichedSerialize } from \"./enriched-serialize\";\nimport { captureCombinedFiberTree } from \"./hide-fiber-tree\";\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// Data\ninterface CombinedUpdateMessage extends BaseMessage {\n type: \"combined-update\";\n watcherId: string;\n capture: CombinedCapture;\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 | 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\nfunction isMessageType<T extends CombinedMessage[\"type\"]>(\n data: unknown,\n type: T,\n): data is Extract<CombinedMessage, { type: T }> {\n return isMessage(data) && data.type === type;\n}\n\nconst isCombinedSourceReady = (d: unknown): d is CombinedSourceReadyMessage =>\n isMessageType(d, \"combined-source-ready\");\nconst isCombinedPong = (d: unknown): d is CombinedPongResponse =>\n isMessageType(d, \"combined-pong\");\nconst isCombinedWatcherStarted = (\n d: unknown,\n): d is CombinedWatcherStartedResponse =>\n isMessageType(d, \"combined-watcher-started\");\nconst isCombinedUpdate = (d: unknown): d is CombinedUpdateMessage =>\n isMessageType(d, \"combined-update\");\nconst isCombinedError = (d: unknown): d is CombinedErrorMessage =>\n isMessageType(d, \"combined-error\");\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\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 const {\n targetOrigin = \"*\",\n serialize,\n hideFiberProp,\n } = 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(\n targetOrigin,\n serialize,\n hideFiberProp,\n ),\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 window.parent.postMessage({ ...msg, [MESSAGE_MARKER]: true }, targetOrigin);\n };\n\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n if (!isMessage(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 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// Dest Side (parent window)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Watcher handle returned by watchCombinedIframe */\nexport interface CombinedWatcher {\n /** The watcher's unique ID */\n id: string;\n /** Stop watching and clean up */\n stop: () => void;\n /** Temporarily coalesce updates without serializing/sending captures. */\n pause: () => void;\n /** Resume updates and emit one latest capture if changes happened while paused. */\n resume: () => void;\n /** Convenience setter for pause/resume. */\n setPaused: (paused: boolean) => void;\n}\n\n/** Options for watchCombinedIframe */\nexport interface WatchCombinedIframeOptions {\n /** CSS selector for element to watch (default: \"body\") */\n selector?: string;\n /** CSS selector for fiber tree root */\n fiberSelector?: string;\n /** Fiber tag whitelist filter */\n fiberTags?: FiberTagValue[];\n /** Debounce delay in ms */\n debounceDelay?: number;\n /** Max wait before forcing flush in ms */\n maxWait?: number;\n /** Timeout for waiting for source to be ready (default: 10000ms) */\n timeout?: number;\n /** Target origin for postMessage (default: '*') */\n targetOrigin?: string;\n /** Called when combined updates are received */\n onUpdate: (capture: CombinedCapture) => void;\n /** Called if an error occurs */\n onError?: (error: Error) => void;\n}\n\n/**\n * Watch an iframe for combined DOM + fiber changes.\n *\n * Handles all the coordination automatically:\n * 1. Waits for the iframe's combined source interface to be ready\n * 2. Starts a combined watcher\n * 3. Calls onUpdate whenever DOM or fiber changes\n *\n * @param iframe - The iframe element to watch\n * @param options - Watch options\n * @returns Promise that resolves to a CombinedWatcher handle\n */\nexport async function watchCombinedIframe(\n iframe: HTMLIFrameElement,\n options: WatchCombinedIframeOptions,\n): Promise<CombinedWatcher> {\n const {\n selector,\n fiberSelector,\n fiberTags,\n debounceDelay,\n maxWait,\n timeout = 10000,\n targetOrigin = \"*\",\n onUpdate,\n onError,\n } = options;\n\n const contentWindow = iframe.contentWindow;\n if (!contentWindow) {\n throw new Error(\"Cannot access iframe contentWindow\");\n }\n\n const send = (msg: CombinedMessage) => {\n contentWindow.postMessage({ ...msg, [MESSAGE_MARKER]: true }, targetOrigin);\n };\n\n // Step 1: Wait for source ready\n await waitForCombinedSourceReady(contentWindow, timeout, targetOrigin);\n\n let stopped = false;\n let watcherId: string | null = null;\n const pendingUpdates = new Map<string, CombinedCapture[]>();\n const handleMessage = (event: MessageEvent) => {\n if (stopped) return;\n if (event.source !== contentWindow) return;\n\n const data = event.data;\n\n if (isCombinedUpdate(data)) {\n if (watcherId === null) {\n const updates = pendingUpdates.get(data.watcherId) ?? [];\n updates.push(data.capture);\n pendingUpdates.set(data.watcherId, updates);\n return;\n }\n if (data.watcherId === watcherId) {\n onUpdate(data.capture);\n }\n }\n\n if (\n watcherId !== null &&\n isCombinedError(data) &&\n (data.watcherId === undefined || data.watcherId === watcherId)\n ) {\n onError?.(new Error(data.error));\n }\n };\n\n window.addEventListener(\"message\", handleMessage);\n\n try {\n watcherId = await requestCombinedWatcher(\n contentWindow,\n {\n selector,\n fiberSelector,\n fiberTags,\n debounceDelay,\n maxWait,\n },\n timeout,\n targetOrigin,\n );\n } catch (error) {\n stopped = true;\n window.removeEventListener(\"message\", handleMessage);\n throw error;\n }\n if (watcherId === null) {\n stopped = true;\n window.removeEventListener(\"message\", handleMessage);\n throw new Error(\"Combined watcher started without a watcher id\");\n }\n\n const activeWatcherId = watcherId;\n for (const capture of pendingUpdates.get(activeWatcherId) ?? []) {\n onUpdate(capture);\n }\n pendingUpdates.clear();\n\n return {\n id: activeWatcherId,\n pause: () => {\n if (stopped) return;\n send({\n type: \"set-combined-watcher-paused\",\n [MESSAGE_MARKER]: true,\n watcherId: activeWatcherId,\n paused: true,\n });\n },\n resume: () => {\n if (stopped) return;\n send({\n type: \"set-combined-watcher-paused\",\n [MESSAGE_MARKER]: true,\n watcherId: activeWatcherId,\n paused: false,\n });\n },\n setPaused: (paused) => {\n if (stopped) return;\n send({\n type: \"set-combined-watcher-paused\",\n [MESSAGE_MARKER]: true,\n watcherId: activeWatcherId,\n paused,\n });\n },\n stop: () => {\n if (stopped) return;\n stopped = true;\n window.removeEventListener(\"message\", handleMessage);\n send({\n type: \"stop-combined-watcher\",\n [MESSAGE_MARKER]: true,\n watcherId: activeWatcherId,\n });\n },\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nasync function waitForCombinedSourceReady(\n contentWindow: Window,\n timeout: number,\n targetOrigin: string,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const startTime = Date.now();\n let resolved = false;\n\n const cleanup = () => {\n resolved = true;\n window.removeEventListener(\"message\", handleMessage);\n };\n\n const handleMessage = (event: MessageEvent) => {\n if (resolved) return;\n if (event.source !== contentWindow) return;\n\n if (isCombinedPong(event.data) || isCombinedSourceReady(event.data)) {\n console.log(\n `[combined-postmessage:dest] Source ready (${event.data.type})`,\n );\n cleanup();\n resolve();\n }\n };\n\n window.addEventListener(\"message\", handleMessage);\n\n const sendPing = () => {\n if (resolved) return;\n\n if (Date.now() - startTime > timeout) {\n cleanup();\n reject(\n new Error(\n \"Timeout waiting for combined iframe source - did you call startCombinedSourceInterface()?\",\n ),\n );\n return;\n }\n\n contentWindow.postMessage(\n { type: \"combined-ping\", [MESSAGE_MARKER]: true },\n targetOrigin,\n );\n\n setTimeout(sendPing, 100);\n };\n\n sendPing();\n });\n}\n\nlet nextCombinedWatcherRequestId = 1;\n\nasync function requestCombinedWatcher(\n contentWindow: Window,\n options: {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n },\n timeout: number,\n targetOrigin: string,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const requestId = `combined-watch-req-${nextCombinedWatcherRequestId++}`;\n const startTime = Date.now();\n let resolved = false;\n\n const cleanup = () => {\n resolved = true;\n window.removeEventListener(\"message\", handleMessage);\n };\n\n const handleMessage = (event: MessageEvent) => {\n if (resolved) return;\n if (event.source !== contentWindow) return;\n\n if (\n isCombinedWatcherStarted(event.data) &&\n event.data.requestId === requestId\n ) {\n console.log(\n `[combined-postmessage:dest] Watcher started: ${event.data.watcherId}`,\n );\n cleanup();\n resolve(event.data.watcherId);\n }\n\n if (\n isCombinedError(event.data) &&\n (event.data.requestId === undefined ||\n event.data.requestId === requestId)\n ) {\n cleanup();\n reject(new Error(event.data.error));\n }\n };\n\n window.addEventListener(\"message\", handleMessage);\n\n const checkTimeout = () => {\n if (resolved) return;\n if (Date.now() - startTime > timeout) {\n cleanup();\n reject(new Error(\"Timeout waiting for combined watcher to start\"));\n return;\n }\n setTimeout(checkTimeout, 100);\n };\n checkTimeout();\n\n contentWindow.postMessage(\n {\n type: \"start-combined-watcher\",\n [MESSAGE_MARKER]: true,\n requestId,\n selector: options.selector,\n fiberSelector: options.fiberSelector,\n fiberTags: options.fiberTags,\n debounceDelay: options.debounceDelay,\n maxWait: options.maxWait,\n },\n targetOrigin,\n );\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}\n\nconst webviewCombinedWatchers = new Map<string, CombinedWatchHandle>();\nlet nextWebviewCombinedWatcherId = 1;\nlet webviewCombinedSourceInitialized = false;\nlet webviewCombinedSourceCleanup: (() => void) | null = null;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport function startCombinedSourceWebviewInterface<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(\n bridge: CombinedWebviewBridge,\n options: CombinedWebviewSourceOptions<T> = {},\n): () => void {\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 serializeFn =\n options.serialize ?? (enrichedSerialize as unknown as SerializeFn<T>);\n\n const send = (type: string, payload: Record<string, unknown>) => {\n bridge.sendToHost(\"combined-projection:update\", { type, ...payload });\n };\n\n const handleCommand = (payload: unknown) => {\n if (!isRecord(payload) || typeof payload.type !== \"string\") {\n return;\n }\n\n switch (payload.type) {\n case \"ping\": {\n send(\"pong\", {});\n break;\n }\n\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-${nextWebviewCombinedWatcherId++}`;\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: serializeFn,\n hideFiberProp: options.hideFiberProp,\n },\n );\n\n webviewCombinedWatchers.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) return;\n\n const watcher = webviewCombinedWatchers.get(watcherId);\n if (!watcher) return;\n watcher.stop();\n webviewCombinedWatchers.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 const paused = payload.paused === true;\n if (!watcherId) return;\n webviewCombinedWatchers.get(watcherId)?.setPaused(paused);\n break;\n }\n\n case \"capture\": {\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\n if (!requestId) return;\n\n try {\n const element = selector\n ? document.querySelector(selector)\n : document.body;\n if (!element) {\n send(\"capture-response\", {\n requestId,\n capture: null,\n error: `Element not found: ${selector}`,\n });\n return;\n }\n\n const supplementalRoots = collectProjectionPortalElements(element);\n const html = captureProjectionSnapshot(element, supplementalRoots);\n const fiber =\n captureCombinedFiberTree<T>({\n serialize: serializeFn,\n selector: fiberSelector,\n rootElement: element,\n tags: fiberTags,\n hideFiberProp: options.hideFiberProp,\n }) ?? null;\n const capture: CombinedCapture<T> = {\n html,\n fiber,\n ...computeRenderDeclarations(\n fiber,\n html,\n initHook().hook.renderers.size > 0,\n element.ownerDocument,\n createRenderDeclarationScope(element, supplementalRoots),\n ),\n documentEpoch: REALM_DOCUMENT_EPOCH,\n sequence: nextRealmCaptureSequence(),\n };\n\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 for (const [watcherId, watcher] of webviewCombinedWatchers) {\n watcher.stop();\n console.log(`[combined-postmessage:webview-source] Stopped ${watcherId}`);\n }\n webviewCombinedWatchers.clear();\n delete (window as any)\n .__IFRAME_PROJECTION_COMBINED_WEBVIEW_INTERFACE_ACTIVE__;\n };\n}\n\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\nexport async function watchCombinedPage(\n page: PageMessageHandle,\n options: WatchCombinedPageOptions,\n): Promise<CombinedWatcher> {\n const {\n selector,\n fiberSelector,\n fiberTags,\n debounceDelay,\n maxWait,\n timeout = 10000,\n signal,\n onUpdate,\n onError,\n } = options;\n\n const send = (type: string, payload: Record<string, unknown> = {}) => {\n page.send(\"combined-projection:command\", { type, ...payload });\n };\n\n await waitForCombinedPageSourceReady(page, timeout, send, signal);\n\n let stopped = false;\n let watcherId: string | null = null;\n const pendingUpdates = new Map<string, CombinedCapture[]>();\n const removeListener = page.on(\"combined-projection:update\", (message) => {\n if (stopped) return;\n if (!isRecord(message) || typeof message.type !== \"string\") return;\n\n if (\n message.type === \"combined-update\" &&\n typeof message.watcherId === \"string\"\n ) {\n const capture = message.capture as CombinedCapture | undefined;\n if (!capture) return;\n if (watcherId === null) {\n const updates = pendingUpdates.get(message.watcherId) ?? [];\n updates.push(capture);\n pendingUpdates.set(message.watcherId, updates);\n return;\n }\n if (message.watcherId === watcherId) onUpdate(capture);\n }\n\n // Only accept errors scoped to this watcher (by watcherId) or\n // unscoped errors (no watcherId field). This prevents errors from\n // other active watchers or captures from mutating this watcher's state.\n if (\n watcherId !== null &&\n message.type === \"error\" &&\n typeof message.error === \"string\"\n ) {\n if (!(\"watcherId\" in message) || message.watcherId === watcherId) {\n onError?.(new Error(message.error));\n }\n }\n });\n\n try {\n watcherId = await requestCombinedPageWatcher(\n page,\n {\n selector,\n fiberSelector,\n fiberTags,\n debounceDelay,\n maxWait,\n },\n timeout,\n send,\n signal,\n );\n } catch (error) {\n stopped = true;\n removeListener();\n throw error;\n }\n if (watcherId === null) {\n stopped = true;\n removeListener();\n throw new Error(\"Combined watcher started without a watcher id\");\n }\n\n if (signal?.aborted) {\n stopped = true;\n removeListener();\n try {\n send(\"stop-watcher\", { watcherId });\n } catch {\n // The aborted setup may already own a destroyed page.\n }\n throw combinedSetupAbortError();\n }\n\n const activeWatcherId = watcherId;\n for (const capture of pendingUpdates.get(activeWatcherId) ?? []) {\n onUpdate(capture);\n }\n pendingUpdates.clear();\n\n return {\n id: activeWatcherId,\n pause: () => {\n if (stopped) return;\n try {\n send(\"set-watcher-paused\", {\n watcherId: activeWatcherId,\n paused: true,\n });\n } catch {\n // no-op when page has already been destroyed\n }\n },\n resume: () => {\n if (stopped) return;\n try {\n send(\"set-watcher-paused\", {\n watcherId: activeWatcherId,\n paused: false,\n });\n } catch {\n // no-op when page has already been destroyed\n }\n },\n setPaused: (paused) => {\n if (stopped) return;\n try {\n send(\"set-watcher-paused\", { watcherId: activeWatcherId, paused });\n } catch {\n // no-op when page has already been destroyed\n }\n },\n stop: () => {\n if (stopped) return;\n stopped = true;\n removeListener();\n try {\n send(\"stop-watcher\", { watcherId: activeWatcherId });\n } catch {\n // no-op when page has already been destroyed\n }\n },\n };\n}\n\nexport interface CaptureCombinedPageOptions {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n}\n\nlet nextCombinedPageCaptureRequestId = 1;\n\nexport async function captureCombinedPage(\n page: PageMessageHandle,\n options: CaptureCombinedPageOptions = {},\n): Promise<CombinedCapture | null> {\n const { selector, fiberSelector, fiberTags, timeout = 10000 } = options;\n\n const send = (type: string, payload: Record<string, unknown> = {}) => {\n page.send(\"combined-projection:command\", { type, ...payload });\n };\n\n await waitForCombinedPageSourceReady(page, timeout, send);\n\n return new Promise((resolve, reject) => {\n const requestId = `combined-capture-${nextCombinedPageCaptureRequestId++}`;\n let resolved = false;\n\n const cleanup = () => {\n if (resolved) return;\n resolved = true;\n removeListener();\n clearTimeout(timeoutId);\n };\n\n const timeoutId = setTimeout(() => {\n cleanup();\n reject(new Error(\"Timeout waiting for combined capture response\"));\n }, timeout);\n\n const removeListener = page.on(\"combined-projection:update\", (message) => {\n if (resolved) return;\n if (!isRecord(message) || typeof message.type !== \"string\") return;\n\n if (\n message.type === \"capture-response\" &&\n message.requestId === requestId\n ) {\n cleanup();\n resolve(\n (message.capture as CombinedCapture | null | undefined) ?? null,\n );\n }\n\n // Only accept errors scoped to this request (by requestId) or\n // unscoped errors (no requestId field). This prevents errors from\n // other active captures or watchers from rejecting this request.\n if (message.type === \"error\" && typeof message.error === \"string\") {\n if (!(\"requestId\" in message) || message.requestId === requestId) {\n cleanup();\n reject(new Error(message.error));\n }\n }\n });\n\n send(\"capture\", {\n requestId,\n selector,\n fiberSelector,\n fiberTags,\n });\n });\n}\n\nasync function waitForCombinedPageSourceReady(\n page: PageMessageHandle,\n timeout: number,\n send: (type: string, payload?: Record<string, unknown>) => void,\n signal?: AbortSignal,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const startTime = Date.now();\n let settled = false;\n let removeListener: (() => void) | null = null;\n let cleanupPending = false;\n let pingTimer: ReturnType<typeof setTimeout> | null = null;\n\n const cleanup = () => {\n if (pingTimer !== null) {\n clearTimeout(pingTimer);\n pingTimer = null;\n }\n signal?.removeEventListener(\"abort\", onAbort);\n if (removeListener) {\n try {\n removeListener();\n } catch {\n // The page may have been destroyed with the listener registration.\n }\n removeListener = null;\n return;\n }\n cleanupPending = true;\n };\n const succeed = () => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve();\n };\n const fail = (error: Error) => {\n if (settled) return;\n settled = true;\n cleanup();\n reject(error);\n };\n const onAbort = () => fail(combinedSetupAbortError());\n\n if (signal?.aborted) {\n fail(combinedSetupAbortError());\n return;\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n try {\n removeListener = page.on(\"combined-projection:update\", (message) => {\n if (settled) return;\n if (!isRecord(message) || typeof message.type !== \"string\") return;\n if (message.type === \"pong\" || message.type === \"source-ready\") {\n succeed();\n }\n });\n } catch (error) {\n fail(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n if (cleanupPending && removeListener) {\n try {\n removeListener();\n } catch {\n // The page may have been destroyed with the listener registration.\n }\n removeListener = null;\n }\n\n const sendPing = () => {\n if (settled) return;\n if (Date.now() - startTime > timeout) {\n fail(\n new Error(\n \"Timeout waiting for combined source - did you call startCombinedSourceWebviewInterface()?\",\n ),\n );\n return;\n }\n try {\n send(\"ping\");\n } catch (error) {\n fail(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n if (!settled) pingTimer = setTimeout(sendPing, 100);\n };\n\n sendPing();\n });\n}\n\nlet nextCombinedPageWatcherRequestId = 1;\n\nasync function requestCombinedPageWatcher(\n page: PageMessageHandle,\n options: {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n },\n timeout: number,\n send: (type: string, payload?: Record<string, unknown>) => void,\n signal?: AbortSignal,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const requestId = `combined-page-watch-${nextCombinedPageWatcherRequestId++}`;\n let settled = false;\n let removeListener: (() => void) | null = null;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const cleanup = () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n signal?.removeEventListener(\"abort\", onAbort);\n try {\n removeListener?.();\n } catch {\n // The page may have been destroyed with the listener registration.\n }\n removeListener = null;\n };\n const succeed = (watcherId: string) => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve(watcherId);\n };\n const fail = (error: Error) => {\n if (settled) return;\n settled = true;\n cleanup();\n reject(error);\n };\n const onAbort = () => fail(combinedSetupAbortError());\n\n if (signal?.aborted) {\n fail(combinedSetupAbortError());\n return;\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n try {\n removeListener = page.on(\"combined-projection:update\", (message) => {\n if (settled) return;\n if (!isRecord(message) || typeof message.type !== \"string\") return;\n\n if (\n message.type === \"watcher-started\" &&\n message.requestId === requestId &&\n typeof message.watcherId === \"string\"\n ) {\n succeed(message.watcherId);\n }\n\n if (message.type === \"error\" && typeof message.error === \"string\") {\n fail(new Error(message.error));\n }\n });\n } catch (error) {\n fail(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n\n timeoutId = setTimeout(\n () => fail(new Error(\"Timeout waiting for combined watcher to start\")),\n timeout,\n );\n\n try {\n send(\"start-watcher\", {\n requestId,\n selector: options.selector,\n fiberSelector: options.fiberSelector,\n fiberTags: options.fiberTags,\n debounceDelay: options.debounceDelay,\n maxWait: options.maxWait,\n });\n } catch (error) {\n fail(error instanceof Error ? error : new Error(String(error)));\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","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 { 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 return startCombinedSourceInterface();\n}\n"],"mappings":";;;;;AAiCO,IAAM,WAAW;AAAA;AAAA,EAEtB,mBAAmB;AAAA;AA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