@fictjs/ssr 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"file":"render-core-D0nOT_Pe.js","names":["g"],"sources":["../src/node-require.ts","../src/globals.ts","../src/html-serializer.ts","../src/stream-bridge.ts","../src/render-core.ts"],"sourcesContent":["declare const __FICT_NODE_REQUIRE__: ((specifier: string) => unknown) | undefined\n\n/**\n * Resolve Node's module-local `require` without introducing a Node builtin\n * import into the edge-compatible ESM build.\n *\n * The CJS build replaces `__FICT_NODE_REQUIRE__` with its local `require`.\n * Source/ESM execution can still opt in through a host-provided global.\n */\nexport function getNodeRequire(): ((specifier: string) => unknown) | null {\n if (typeof __FICT_NODE_REQUIRE__ === 'function') {\n return __FICT_NODE_REQUIRE__\n }\n\n const direct = (globalThis as Record<string, unknown>).require\n if (typeof direct === 'function') {\n return direct as (specifier: string) => unknown\n }\n\n try {\n return Function('return typeof require === \"function\" ? require : null')() as\n | ((specifier: string) => unknown)\n | null\n } catch {\n return null\n }\n}\n","import { __fictGetCurrentSSRSession } from '@fictjs/runtime/internal'\n\nimport { getNodeRequire } from './node-require'\n\ninterface GlobalSnapshot {\n key: string\n exists: boolean\n value: unknown\n}\n\nexport function installGlobals(window: Window, document: Document): () => void {\n const win = window as Window & {\n Node?: typeof Node\n Element?: typeof Element\n HTMLElement?: typeof HTMLElement\n SVGElement?: typeof SVGElement\n Document?: typeof Document\n DocumentFragment?: typeof DocumentFragment\n Text?: typeof Text\n Comment?: typeof Comment\n Range?: typeof Range\n Event?: typeof Event\n CustomEvent?: typeof CustomEvent\n MutationObserver?: typeof MutationObserver\n DOMParser?: typeof DOMParser\n getComputedStyle?: Window['getComputedStyle']\n }\n\n const required: Record<string, unknown> = {\n window: win,\n document,\n self: win,\n Node: win.Node,\n Element: win.Element,\n HTMLElement: win.HTMLElement,\n SVGElement: win.SVGElement,\n Document: win.Document,\n DocumentFragment: win.DocumentFragment,\n Text: win.Text,\n Comment: win.Comment,\n }\n\n const optional: Record<string, unknown> = {\n Range: win.Range,\n Event: win.Event,\n CustomEvent: win.CustomEvent,\n MutationObserver: win.MutationObserver,\n DOMParser: win.DOMParser,\n getComputedStyle: win.getComputedStyle?.bind(win),\n }\n\n const missing = Object.entries(required)\n .filter(([, value]) => value === undefined)\n .map(([key]) => key)\n\n if (missing.length) {\n throw new Error(`[fict/ssr] Missing DOM globals: ${missing.join(', ')}`)\n }\n\n const globals = { ...required, ...optional }\n const keys = Object.keys(globals)\n\n const snapshot = captureGlobals(keys)\n for (const key of keys) {\n const value = globals[key]\n if (value !== undefined) {\n ;(globalThis as Record<string, unknown>)[key] = value\n }\n }\n\n return () => restoreGlobals(snapshot)\n}\n\nexport function installManifest(manifest?: Record<string, string> | string): () => void {\n if (!manifest) return () => {}\n\n let resolved: Record<string, string>\n if (typeof manifest === 'string') {\n const raw = readTextFileFromPath(manifest)\n resolved = JSON.parse(raw) as Record<string, string>\n } else {\n resolved = manifest\n }\n\n const session = __fictGetCurrentSSRSession()\n if (session) {\n const previous = session.manifest\n session.manifest = resolved\n\n return () => {\n session.manifest = previous\n }\n }\n\n const key = '__FICT_MANIFEST__'\n const snapshot = {\n exists: Object.prototype.hasOwnProperty.call(globalThis, key),\n value: (globalThis as Record<string, unknown>)[key],\n }\n ;(globalThis as Record<string, unknown>)[key] = resolved\n\n return () => {\n if (snapshot.exists) {\n ;(globalThis as Record<string, unknown>)[key] = snapshot.value\n } else {\n delete (globalThis as Record<string, unknown>)[key]\n }\n }\n}\n\nfunction captureGlobals(keys: string[]): GlobalSnapshot[] {\n const snapshot: GlobalSnapshot[] = []\n for (const key of keys) {\n const exists = Object.prototype.hasOwnProperty.call(globalThis, key)\n const value = (globalThis as Record<string, unknown>)[key]\n snapshot.push({ key, exists, value })\n }\n return snapshot\n}\n\nfunction restoreGlobals(snapshot: GlobalSnapshot[]): void {\n for (const entry of snapshot) {\n if (entry.exists) {\n ;(globalThis as Record<string, unknown>)[entry.key] = entry.value\n } else {\n delete (globalThis as Record<string, unknown>)[entry.key]\n }\n }\n}\n\nfunction readTextFileFromPath(path: string): string {\n const g = globalThis as Record<string, unknown>\n\n const deno = g.Deno as { readTextFileSync?: (path: string) => string } | undefined\n if (deno && typeof deno.readTextFileSync === 'function') {\n return deno.readTextFileSync(path)\n }\n\n const nodeRequire = getNodeRequire()\n if (nodeRequire) {\n const fs = nodeRequire('node:fs') as {\n readFileSync: (path: string, encoding: string) => string\n }\n return fs.readFileSync(path, 'utf8')\n }\n\n throw new Error(\n '[fict/ssr] `manifest` as file path is only supported when Deno.readTextFileSync or CommonJS require is available. ' +\n 'Pass a manifest object in Node ESM or edge runtimes.',\n )\n}\n","import { assertValidDOMAttributeName, assertValidDOMElementName } from '@fictjs/runtime/internal'\n\nconst HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'\nconst SVG_NAMESPACE = 'http://www.w3.org/2000/svg'\nconst MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'\nconst MATHML_TEXT_INTEGRATION_EXCEPTIONS = new Set(['mglyph', 'malignmark'])\n\nconst HTML_VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'basefont',\n 'bgsound',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'keygen',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n])\n\n// In these elements, character references are not decoded by the HTML parser.\n// Escaping the whole text as `&lt;` would therefore change executable script,\n// stylesheet, and fallback content. Neutralize only an actual matching end tag.\nconst HTML_RAW_TEXT_ELEMENTS = new Set([\n 'iframe',\n 'noembed',\n 'noframes',\n 'noscript',\n 'script',\n 'style',\n 'xmp',\n])\nconst HTML_RCDATA_ELEMENTS = new Set(['textarea', 'title'])\n\nconst HTML_TABLE_SECTION_ELEMENTS = new Set(['tbody', 'thead', 'tfoot'])\nconst HTML_TEXT_ONLY_ELEMENTS = new Set([\n ...HTML_RAW_TEXT_ELEMENTS,\n 'plaintext',\n 'textarea',\n 'title',\n])\nconst HTML_DOCUMENT_STRUCTURE_ELEMENTS = new Set(['frameset', 'head', 'html'])\nconst HTML_UNSAFE_RESUMABLE_HOST_PARENTS = new Set([\n 'colgroup',\n 'option',\n 'optgroup',\n 'select',\n 'table',\n 'tr',\n ...HTML_TABLE_SECTION_ELEMENTS,\n ...HTML_TEXT_ONLY_ELEMENTS,\n ...HTML_DOCUMENT_STRUCTURE_ELEMENTS,\n])\n// This list only covers confirmed native HTML algorithms that require direct\n// children. Generic CSS selectors, Shadow DOM slotting, and DOM child APIs\n// cannot be made transparent with a denylist and remain range-v3 concerns.\nconst HTML_HOST_SENSITIVE_CONTEXT_CHILDREN = new Map([\n ['details', new Set(['summary'])],\n ['fieldset', new Set(['legend'])],\n ['audio', new Set(['source', 'track'])],\n ['video', new Set(['source', 'track'])],\n ['ruby', new Set(['rp', 'rt'])],\n ['figure', new Set(['figcaption'])],\n ['map', new Set(['area'])],\n])\n\ninterface ParserSensitiveHostContext {\n descendants: ReadonlySet<string>\n barriers?: ReadonlySet<string>\n}\n\n// The tree-builder stops its backwards list-item scan at special elements\n// other than address/div/p. A nested list or section therefore contains its\n// own li/dt/dd tokens without closing an outer item.\nconst HTML_LIST_ITEM_SCAN_BARRIERS = new Set([\n 'applet',\n 'article',\n 'aside',\n 'blockquote',\n 'button',\n 'caption',\n 'center',\n 'colgroup',\n 'details',\n 'dl',\n 'fieldset',\n 'figure',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hgroup',\n 'hr',\n 'main',\n 'marquee',\n 'menu',\n 'nav',\n 'object',\n 'ol',\n 'pre',\n 'search',\n 'section',\n 'select',\n 'table',\n 'tbody',\n 'td',\n 'tfoot',\n 'th',\n 'thead',\n 'tr',\n 'ul',\n])\n\n// These start tags consult parser state outside the custom-element subtree.\n// When one appears below <fict-host>, the browser can close an ancestor, eject\n// content from the host, or discard the component root even though the server\n// DOM allowed the programmatic nesting.\nconst HTML_PARSER_SENSITIVE_HOST_CONTEXTS = new Map<string, ParserSensitiveHostContext>([\n [\n 'p',\n {\n descendants: new Set([\n 'address',\n 'article',\n 'aside',\n 'blockquote',\n 'center',\n 'dd',\n 'details',\n 'dialog',\n 'dir',\n 'div',\n 'dl',\n 'dt',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hgroup',\n 'hr',\n 'li',\n 'listing',\n 'main',\n 'menu',\n 'nav',\n 'ol',\n 'p',\n 'plaintext',\n 'pre',\n 'search',\n 'section',\n 'summary',\n 'table',\n 'ul',\n 'xmp',\n ]),\n },\n ],\n ['a', { descendants: new Set(['a']) }],\n ['button', { descendants: new Set(['button']) }],\n ['li', { descendants: new Set(['li']), barriers: HTML_LIST_ITEM_SCAN_BARRIERS }],\n ['dt', { descendants: new Set(['dt', 'dd']), barriers: HTML_LIST_ITEM_SCAN_BARRIERS }],\n ['dd', { descendants: new Set(['dt', 'dd']), barriers: HTML_LIST_ITEM_SCAN_BARRIERS }],\n ['nobr', { descendants: new Set(['nobr']) }],\n ['form', { descendants: new Set(['form']) }],\n [\n 'caption',\n {\n descendants: new Set([\n 'caption',\n 'col',\n 'colgroup',\n 'tbody',\n 'td',\n 'tfoot',\n 'th',\n 'thead',\n 'tr',\n ]),\n barriers: new Set(['table']),\n },\n ],\n [\n 'td',\n {\n descendants: new Set([\n 'caption',\n 'col',\n 'colgroup',\n 'tbody',\n 'td',\n 'tfoot',\n 'th',\n 'thead',\n 'tr',\n ]),\n barriers: new Set(['table']),\n },\n ],\n [\n 'th',\n {\n descendants: new Set([\n 'caption',\n 'col',\n 'colgroup',\n 'tbody',\n 'td',\n 'tfoot',\n 'th',\n 'thead',\n 'tr',\n ]),\n barriers: new Set(['table']),\n },\n ],\n])\n\nconst STREAM_BOUNDARY_START_PREFIX = 'fict:suspense-start:'\nconst STREAM_BOUNDARY_END_PREFIX = 'fict:suspense-end:'\nconst SCRIPT_SUPPORTING_ELEMENTS = ['script', 'template']\nconst HTML_STREAM_BOUNDARY_ALLOWED_CHILDREN = new Map([\n [\n 'table',\n new Set(['caption', 'colgroup', 'tbody', 'tfoot', 'thead', ...SCRIPT_SUPPORTING_ELEMENTS]),\n ],\n ['tbody', new Set(['tr', ...SCRIPT_SUPPORTING_ELEMENTS])],\n ['thead', new Set(['tr', ...SCRIPT_SUPPORTING_ELEMENTS])],\n ['tfoot', new Set(['tr', ...SCRIPT_SUPPORTING_ELEMENTS])],\n ['tr', new Set(['td', 'th', ...SCRIPT_SUPPORTING_ELEMENTS])],\n ['colgroup', new Set(['col', 'template'])],\n ['select', new Set(['hr', 'optgroup', 'option', ...SCRIPT_SUPPORTING_ELEMENTS])],\n ['optgroup', new Set(['option', ...SCRIPT_SUPPORTING_ELEMENTS])],\n ['option', new Set<string>()],\n])\nconst HTML_STREAM_BOUNDARY_TEXT_CONTEXTS = new Set(['option', 'optgroup', 'select'])\n\nconst ELEMENT_NODE = 1\nconst TEXT_NODE = 3\nconst CDATA_SECTION_NODE = 4\nconst PROCESSING_INSTRUCTION_NODE = 7\nconst COMMENT_NODE = 8\nconst DOCUMENT_NODE = 9\nconst DOCUMENT_TYPE_NODE = 10\nconst DOCUMENT_FRAGMENT_NODE = 11\n\n/**\n * Serialize a DOM subtree as HTML without relying on the host DOM's\n * `innerHTML`/`outerHTML` implementation. Some lightweight server DOMs do not\n * escape ampersands in attributes or matching end tags in raw-text elements,\n * so their output can produce a different (and unsafe) tree when a browser\n * parses it again.\n */\nexport function serializeHtmlNode(node: Node, parentElement: Element | null = null): string {\n switch (node.nodeType) {\n case ELEMENT_NODE:\n return serializeElement(node as Element, parentElement)\n case TEXT_NODE:\n case CDATA_SECTION_NODE:\n return serializeText(node.nodeValue ?? '', parentElement)\n case COMMENT_NODE:\n return serializeComment(node.nodeValue ?? '')\n case DOCUMENT_NODE:\n case DOCUMENT_FRAGMENT_NODE:\n return serializeHtmlChildren(node)\n case DOCUMENT_TYPE_NODE:\n return serializeDocumentType(node as DocumentType)\n case PROCESSING_INSTRUCTION_NODE:\n // HTML has no processing-instruction syntax: `<?...>` is parsed as a\n // bogus comment only until the first `>`, so arbitrary PI data could\n // otherwise reopen markup. Preserve it as an inert HTML comment.\n return serializeComment(`?${node.nodeName} ${node.nodeValue ?? ''}?`)\n default:\n return ''\n }\n}\n\nexport function serializeHtmlChildren(parent: Node): string {\n const parentElement = parent.nodeType === ELEMENT_NODE ? (parent as Element) : null\n return serializeHtmlNodes(parent.childNodes, parentElement)\n}\n\nexport function serializeHtmlNodes(\n nodes: Iterable<Node>,\n parentElement: Element | null = null,\n): string {\n if (parentElement && isHtmlElement(parentElement)) {\n const parentTagName = (parentElement.localName || parentElement.tagName).toLowerCase()\n assertSafeStreamingBoundaryContext(parentElement, parentTagName)\n }\n\n let html = ''\n for (const node of nodes) html += serializeHtmlNode(node, parentElement)\n\n // Adjacent DOM text nodes remain separate in memory but are concatenated in\n // the HTML byte stream. Re-check the complete child serialization so an end\n // tag split across text-node boundaries cannot evade raw-text escaping.\n const rawTextTagName = getRawTextTagName(parentElement)\n return rawTextTagName ? escapeRawTextEndTag(html, rawTextTagName) : html\n}\n\nfunction serializeElement(element: Element, serializedParent: Element | null): string {\n const localName = element.localName || element.tagName\n const tagName = element.prefix ? `${element.prefix}:${localName}` : localName\n const isHtml = isHtmlElement(element)\n const normalizedTagName = tagName.toLowerCase()\n assertSafeResumableHostContext(element, serializedParent)\n if (isHtml && normalizedTagName === 'plaintext') {\n throw new Error(\n '[fict/ssr] Cannot serialize HTML <plaintext>. The HTML syntax has no closing tag for this element, so a browser would consume every following tag, ancestor closing tag, and snapshot script as text. Use <pre> for preformatted HTML content or return a text/plain response instead.',\n )\n }\n assertValidDOMElementName(tagName, !isHtml, isHtml ? undefined : element.namespaceURI)\n let html = `<${tagName}`\n\n for (const attribute of Array.from(element.attributes)) {\n assertValidDOMAttributeName(\n attribute.name,\n attribute.namespaceURI != null,\n attribute.namespaceURI ?? undefined,\n )\n html += ` ${attribute.name}=\"${escapeAttributeValue(attribute.value)}\"`\n }\n\n if (isHtml && HTML_VOID_ELEMENTS.has(normalizedTagName)) {\n assertEmptyHtmlVoidElement(element, normalizedTagName)\n return `${html}>`\n }\n\n html += '>'\n const childSource =\n isHtml && normalizedTagName === 'template' && 'content' in element\n ? ((element as HTMLTemplateElement).content ?? element)\n : element\n if (childSource !== element) {\n assertSafeTemplateContent(childSource)\n }\n html += serializeHtmlChildren(childSource)\n if (\n isHtml &&\n (HTML_RAW_TEXT_ELEMENTS.has(normalizedTagName) || HTML_RCDATA_ELEMENTS.has(normalizedTagName))\n ) {\n // Serialize first so more specific resumable-scope and streaming-boundary diagnostics win.\n // The accumulated string is still local and is never returned when this validation fails.\n assertTextOnlyHtmlChildren(childSource, normalizedTagName)\n }\n html += `</${tagName}>`\n return html\n}\n\nfunction assertTextOnlyHtmlChildren(element: Node, tagName: string): void {\n for (const child of Array.from(element.childNodes)) {\n if (child.nodeType === TEXT_NODE || child.nodeType === CDATA_SECTION_NODE) continue\n const childDescription =\n child.nodeType === ELEMENT_NODE\n ? `<${((child as Element).localName || (child as Element).tagName).toLowerCase()}>`\n : child.nodeType === COMMENT_NODE\n ? 'a comment'\n : `a ${child.nodeName || `nodeType ${child.nodeType}`} node`\n throw new Error(\n `[fict/ssr] Cannot serialize HTML <${tagName}> with ${childDescription} child. The HTML parser treats this element's contents as text, so non-text DOM nodes cannot round-trip and would silently disappear. Provide string/textContent content instead.`,\n )\n }\n}\n\nfunction assertEmptyHtmlVoidElement(element: Element, tagName: string): void {\n const childCount = element.childNodes.length\n if (childCount === 0) return\n\n const feature = findResumableFeature(element)\n const discardedResumableState = describeDiscardedResumableFeature(feature)\n throw new Error(\n `[fict/ssr] Cannot serialize <${tagName}> with ${childCount} child node${childCount === 1 ? '' : 's'}. ` +\n `HTML void elements cannot contain children, and browsers omit every child when serializing or parsing <${tagName}>.${discardedResumableState} ` +\n `Remove all children from <${tagName}> and move the content outside the void element.`,\n )\n}\n\nfunction assertSafeStreamingBoundaryContext(element: Element, contextTag: string): void {\n if (HTML_TEXT_ONLY_ELEMENTS.has(contextTag)) {\n const marker = findStreamingBoundaryMarker(element)\n if (!marker) return\n throw new Error(\n `[fict/ssr] Cannot serialize a streaming Suspense boundary inside <${contextTag}>. ` +\n `The HTML parser treats its comment markers as text in this context, so the streamed patch can never find boundary ${JSON.stringify(marker.id)}. ` +\n `Move the streaming boundary outside <${contextTag}> and update this element through an outer component.`,\n )\n }\n\n const allowedChildren = HTML_STREAM_BOUNDARY_ALLOWED_CHILDREN.get(contextTag)\n if (!allowedChildren) return\n\n const children = Array.from(element.childNodes)\n for (let index = 0; index < children.length; index++) {\n const start = parseStreamingBoundaryMarker(children[index])\n if (start?.kind !== 'start') continue\n\n let endIndex = index + 1\n while (endIndex < children.length) {\n const end = parseStreamingBoundaryMarker(children[endIndex])\n if (end?.kind === 'end' && end.id === start.id) break\n endIndex++\n }\n if (endIndex === children.length) {\n throw new Error(\n `[fict/ssr] Cannot serialize streaming Suspense boundary ${JSON.stringify(start.id)} inside <${contextTag}> because its sibling end marker is missing.`,\n )\n }\n\n for (let contentIndex = index + 1; contentIndex < endIndex; contentIndex++) {\n const invalidContent = describeInvalidBoundaryContent(\n children[contentIndex]!,\n allowedChildren,\n HTML_STREAM_BOUNDARY_TEXT_CONTEXTS.has(contextTag),\n )\n if (!invalidContent) continue\n throw new Error(\n `[fict/ssr] Cannot serialize a streaming Suspense boundary inside <${contextTag}> with direct ${invalidContent} content. ` +\n `The HTML parser reparents or discards that content, so the boundary markers no longer describe one patchable sibling range. ` +\n getStreamingBoundaryRewriteSuggestion(contextTag, invalidContent),\n )\n }\n }\n}\n\nfunction describeInvalidBoundaryContent(\n node: Node,\n allowedElements: ReadonlySet<string>,\n allowText: boolean,\n): string | null {\n if (node.nodeType === COMMENT_NODE) return null\n if (node.nodeType === TEXT_NODE || node.nodeType === CDATA_SECTION_NODE) {\n return allowText || !(node.nodeValue ?? '').trim() ? null : 'non-whitespace text'\n }\n if (node.nodeType !== ELEMENT_NODE) return `node type ${node.nodeType}`\n\n const element = node as Element\n const tagName = (element.localName || element.tagName).toLowerCase()\n return isHtmlElement(element) && allowedElements.has(tagName) ? null : `<${tagName}>`\n}\n\nfunction getStreamingBoundaryRewriteSuggestion(contextTag: string, invalidContent: string): string {\n if (contextTag === 'table' && invalidContent === '<tr>') {\n return 'Wrap the boundary and rows in an explicit <tbody>.'\n }\n if (contextTag === 'table' && invalidContent === '<col>') {\n return 'Wrap the boundary and columns in an explicit <colgroup>.'\n }\n if (HTML_TABLE_SECTION_ELEMENTS.has(contextTag)) {\n return `Wrap cells in a native <tr>, or move the boundary outside <${contextTag}>.`\n }\n if (contextTag === 'tr') {\n return 'Render only native <td> or <th> roots inside this boundary.'\n }\n if (contextTag === 'colgroup') {\n return 'Render only native <col> roots inside this boundary.'\n }\n if (contextTag === 'select' || contextTag === 'optgroup' || contextTag === 'option') {\n return 'Use only portable native option content, or move the boundary outside <select>.'\n }\n return `Move the boundary outside <${contextTag}> or wrap its content in a parser-stable native container.`\n}\n\nfunction assertSafeResumableHostContext(element: Element, serializedParent: Element | null): void {\n if (!isResumableFictHost(element)) return\n\n const foreignNamespace = getResumableHostForeignNamespace(element, serializedParent)\n if (foreignNamespace) {\n const scopeId = element.getAttribute('data-fict-s') ?? '<unknown>'\n const namespaceDescription =\n foreignNamespace.kind === 'other'\n ? `foreign namespace ${JSON.stringify(foreignNamespace.uri)}`\n : `the ${foreignNamespace.kind} namespace`\n const semanticRisk =\n foreignNamespace.kind === 'SVG'\n ? 'A custom element wrapper is not structurally transparent in SVG and can suppress the graphics it contains after HTML parsing.'\n : foreignNamespace.kind === 'MathML'\n ? 'A custom element wrapper is not structurally transparent in MathML and can replace the intended operands of fixed-arity layout elements after HTML parsing.'\n : 'A custom element wrapper is not guaranteed to be structurally transparent in foreign content after HTML parsing.'\n throw new Error(\n `[fict/ssr] Cannot serialize resumable <fict-host> scope ${JSON.stringify(scopeId)} in ${namespaceDescription}. ` +\n `${semanticRisk} Range-based scope anchors (range-v3) are required for resumable components in foreign content; ` +\n 'move the component boundary outside the foreign-content subtree until that protocol is available.',\n )\n }\n\n const parent = serializedParent ?? element.parentElement\n if (!parent || !isHtmlElement(parent)) return\n\n const contextTag = (parent.localName || parent.tagName).toLowerCase()\n if (HTML_UNSAFE_RESUMABLE_HOST_PARENTS.has(contextTag)) {\n const scopeId = element.getAttribute('data-fict-s') ?? '<unknown>'\n throw new Error(\n `[fict/ssr] Cannot serialize resumable <fict-host> scope ${JSON.stringify(scopeId)} inside <${contextTag}>. ` +\n `The HTML parser will not preserve that host at this location, so its scope would target different DOM after parsing. ` +\n getResumableHostRewriteSuggestion(contextTag),\n )\n }\n\n assertSafeHostParserStateContext(element, parent)\n assertSafeHostSensitiveHtmlContext(element, contextTag)\n}\n\nfunction isResumableFictHost(element: Element): boolean {\n return (\n (element.localName || element.tagName).toLowerCase() === 'fict-host' &&\n element.hasAttribute('data-fict-host') &&\n !!element.getAttribute('data-fict-s')\n )\n}\n\nfunction assertSafeHostParserStateContext(host: Element, parent: Element): void {\n let ancestor: Element | null = parent\n while (ancestor) {\n if (isHtmlElement(ancestor)) {\n const contextTag = (ancestor.localName || ancestor.tagName).toLowerCase()\n const rule = HTML_PARSER_SENSITIVE_HOST_CONTEXTS.get(contextTag)\n if (rule) {\n const sensitiveTag = findParserSensitiveDescendant(host, rule)\n if (sensitiveTag) {\n const scopeId = host.getAttribute('data-fict-s') ?? '<unknown>'\n throw new Error(\n `[fict/ssr] Cannot serialize resumable <fict-host> scope ${JSON.stringify(scopeId)} inside <${contextTag}> with descendant <${sensitiveTag}>. ` +\n `The HTML parser applies <${sensitiveTag}> start-tag rules outside the custom-element boundary, so it will close or reparent the ancestor, eject content from the host, or discard the component root. ` +\n `Move the component boundary outside <${contextTag}>, or make the component own that element. ` +\n 'Range-based scope anchors (range-v3) are required to preserve this boundary without an element wrapper.',\n )\n }\n }\n }\n ancestor = ancestor.parentElement\n }\n}\n\nfunction findParserSensitiveDescendant(\n host: Element,\n rule: ParserSensitiveHostContext,\n): string | null {\n const pending = Array.from(host.children)\n while (pending.length > 0) {\n const element = pending.shift()!\n if (!isHtmlElement(element)) continue\n\n const tagName = (element.localName || element.tagName).toLowerCase()\n if (rule.descendants.has(tagName)) return tagName\n if (\n tagName === 'template' ||\n tagName === 'svg' ||\n tagName === 'math' ||\n HTML_TEXT_ONLY_ELEMENTS.has(tagName) ||\n rule.barriers?.has(tagName)\n ) {\n continue\n }\n pending.unshift(...Array.from(element.children))\n }\n return null\n}\n\nfunction assertSafeHostSensitiveHtmlContext(host: Element, contextTag: string): void {\n let sensitiveDescription: string\n if (contextTag === 'picture') {\n sensitiveDescription = 'the native <source> and <img> structure'\n } else {\n const sensitiveTags = HTML_HOST_SENSITIVE_CONTEXT_CHILDREN.get(contextTag)\n if (!sensitiveTags) return\n\n const sensitiveTag = findTransparentDirectChildTag(host, sensitiveTags)\n if (!sensitiveTag) return\n sensitiveDescription = `a transparent direct <${sensitiveTag}> child`\n }\n\n const scopeId = host.getAttribute('data-fict-s') ?? '<unknown>'\n throw new Error(\n `[fict/ssr] Cannot serialize resumable <fict-host> scope ${JSON.stringify(scopeId)} as a component boundary inside <${contextTag}> around ${sensitiveDescription}. ` +\n `${getHostSensitiveContextRisk(contextTag)} CSS display: contents removes only the host's box; it does not make the host transparent to these DOM rules. ` +\n `Move the component boundary outside <${contextTag}> and make the component own <${contextTag}>, so its sensitive content remains native direct children. ` +\n 'Range-based scope anchors (range-v3) are required to keep a resumable boundary at this position without an element wrapper.',\n )\n}\n\nfunction findTransparentDirectChildTag(\n host: Element,\n sensitiveTags: ReadonlySet<string>,\n): string | null {\n for (const child of Array.from(host.children)) {\n if (!isHtmlElement(child)) continue\n\n // Only an uninterrupted chain of Fict's own scope hosts is transparent in\n // the future range protocol. Ordinary elements and unmarked user-created\n // <fict-host> elements remain real structural barriers.\n if (isResumableFictHost(child)) {\n const nestedTag = findTransparentDirectChildTag(child, sensitiveTags)\n if (nestedTag) return nestedTag\n continue\n }\n\n const childTag = (child.localName || child.tagName).toLowerCase()\n if (sensitiveTags.has(childTag)) return childTag\n }\n return null\n}\n\nfunction getHostSensitiveContextRisk(contextTag: string): string {\n switch (contextTag) {\n case 'picture':\n return 'Browsers select picture candidates from its direct <source>/<img> structure, so a wrapper can silently select the fallback image.'\n case 'details':\n return 'Only a direct <summary> child provides the native disclosure control, so wrapping it prevents activation from toggling <details>.'\n case 'fieldset':\n return 'A direct <legend> supplies the fieldset name and its first-legend disabled-state exemption, both of which a wrapper removes.'\n case 'audio':\n case 'video':\n return `Browsers discover <source> and <track> from direct <${contextTag}> children, so wrapped media resources and text tracks are ignored.`\n case 'ruby':\n return 'Ruby annotation layout depends on direct <rt>/<rp> structure, and wrappers cause annotations to render as ordinary inline content in some browsers.'\n case 'figure':\n return 'A direct <figcaption> provides the accessible name of <figure>, which is lost through a wrapper.'\n case 'map':\n return 'Browser image-map and areas-collection behavior diverges when <area> is hidden behind a wrapper.'\n default:\n return 'This HTML context assigns semantics through native direct-child relationships that an element wrapper changes.'\n }\n}\n\ntype ResumableHostForeignNamespace = { kind: 'SVG' | 'MathML' } | { kind: 'other'; uri: string }\n\nfunction getResumableHostForeignNamespace(\n element: Element,\n serializedParent: Element | null,\n): ResumableHostForeignNamespace | null {\n const directNamespace = classifyForeignNamespace(element.namespaceURI)\n if (directNamespace) return directNamespace\n\n // linkedom currently reports MathML elements as XHTML. Recover the browser\n // parser context from ancestry so a MathML host cannot evade validation.\n // Foreign-content integration points are intentional HTML islands. An HTML\n // host below one remains valid unless a nearer foreign element establishes a\n // new context.\n let ancestor = serializedParent ?? element.parentElement\n let descendantLocalName: string | null = null\n while (ancestor) {\n const localName = (ancestor.localName || ancestor.tagName).toLowerCase()\n if (localName === 'foreignobject' || localName === 'title' || localName === 'desc') {\n return null\n }\n if (\n localName === 'mi' ||\n localName === 'mo' ||\n localName === 'mn' ||\n localName === 'ms' ||\n localName === 'mtext'\n ) {\n if (\n MATHML_TEXT_INTEGRATION_EXCEPTIONS.has(descendantLocalName ?? '') ||\n findTransparentDirectRootTag(element, MATHML_TEXT_INTEGRATION_EXCEPTIONS)\n ) {\n return { kind: 'MathML' }\n }\n return null\n }\n if (localName === 'annotation-xml') {\n const encoding = ancestor.getAttribute('encoding')?.toLowerCase()\n if (encoding === 'text/html' || encoding === 'application/xhtml+xml') return null\n }\n\n const ancestorNamespace = classifyForeignNamespace(ancestor.namespaceURI)\n if (ancestorNamespace) return ancestorNamespace\n if (localName === 'svg') return { kind: 'SVG' }\n if (localName === 'math') return { kind: 'MathML' }\n descendantLocalName = localName\n ancestor = ancestor.parentElement\n }\n return null\n}\n\nfunction findTransparentDirectRootTag(host: Element, tagNames: ReadonlySet<string>): string | null {\n for (const child of Array.from(host.children)) {\n if (isResumableFictHost(child)) {\n const nestedTag = findTransparentDirectRootTag(child, tagNames)\n if (nestedTag) return nestedTag\n continue\n }\n\n const childTag = (child.localName || child.tagName).toLowerCase()\n if (tagNames.has(childTag)) return childTag\n }\n return null\n}\n\nfunction classifyForeignNamespace(\n namespaceURI: string | null,\n): ResumableHostForeignNamespace | null {\n if (namespaceURI === null || namespaceURI === HTML_NAMESPACE) return null\n if (namespaceURI === SVG_NAMESPACE) return { kind: 'SVG' }\n if (namespaceURI === MATHML_NAMESPACE) return { kind: 'MathML' }\n return { kind: 'other', uri: namespaceURI }\n}\n\nfunction getResumableHostRewriteSuggestion(contextTag: string): string {\n if (contextTag === 'table') {\n return 'Move the component outside <table>, or make it own the complete table while keeping table sections as native elements.'\n }\n if (HTML_TABLE_SECTION_ELEMENTS.has(contextTag)) {\n return 'Move the component into a native <td> or <th> within the row, or move its resumable boundary outside the table.'\n }\n if (contextTag === 'tr') {\n return 'Move the component inside a native <td> or <th>, rather than using a component as a direct row child.'\n }\n if (contextTag === 'colgroup') {\n return 'Move the component outside <colgroup>, or make it own the complete table and render <col> elements natively.'\n }\n if (contextTag === 'select' || contextTag === 'optgroup' || contextTag === 'option') {\n return 'Move the component outside <select>, or make it own the complete select while rendering option structure natively.'\n }\n if (HTML_TEXT_ONLY_ELEMENTS.has(contextTag)) {\n return `Move the component outside <${contextTag}> and make it own that element; bind its value or text content instead of nesting a component inside it.`\n }\n return 'Move the component into <body> content, outside document-structure elements.'\n}\n\ntype SerializedResumableFeature =\n | { kind: 'scope'; detail: string }\n | { kind: 'event'; detail: string }\n | { kind: 'boundary'; detail: string }\n\ninterface StreamingBoundaryMarker {\n kind: 'start' | 'end'\n id: string\n}\n\nfunction describeDiscardedResumableFeature(feature: SerializedResumableFeature | null): string {\n if (!feature) return ''\n if (feature.kind === 'scope') {\n return ` The discarded children contain a resumable scope (${feature.detail}), which would leave orphaned snapshot state.`\n }\n if (feature.kind === 'event') {\n return ` The discarded children contain a resumable event (${feature.detail}), which would disappear from the parsed document.`\n }\n return ` The discarded children contain a streaming Suspense boundary (${feature.detail}), which would leave an unpatchable stream.`\n}\n\nfunction assertSafeTemplateContent(content: DocumentFragment | Element): void {\n const feature = findResumableFeature(content)\n if (!feature) return\n\n if (feature.kind === 'boundary') {\n throw new Error(\n `[fict/ssr] Cannot serialize <template> content containing a streaming Suspense boundary (${feature.detail}). ` +\n 'Native template content can be cloned more than once, which duplicates the stream boundary id and makes patch targeting ambiguous. ' +\n 'Move the streaming boundary outside <template>.',\n )\n }\n\n const label = feature.kind === 'scope' ? 'resumable scope' : 'resumable event'\n throw new Error(\n `[fict/ssr] Cannot serialize <template> content containing a ${label} (${feature.detail}). ` +\n 'Native template content can be cloned more than once, but the current resumability protocol assigns only one runtime scope to each server scope id. ' +\n 'Move the resumable component or event outside <template>.',\n )\n}\n\nfunction findResumableFeature(root: Node): SerializedResumableFeature | null {\n for (const child of Array.from(root.childNodes)) {\n const boundary = parseStreamingBoundaryMarker(child)\n if (boundary) {\n return {\n kind: 'boundary',\n detail: `${boundary.kind} id ${JSON.stringify(boundary.id)}`,\n }\n }\n if (child.nodeType !== ELEMENT_NODE) continue\n const element = child as Element\n const scopeId = element.getAttribute('data-fict-s')\n if (scopeId) {\n return { kind: 'scope', detail: `data-fict-s=${JSON.stringify(scopeId)}` }\n }\n const resumeQrl = element.getAttribute('data-fict-h')\n if (resumeQrl) {\n return { kind: 'scope', detail: `data-fict-h=${JSON.stringify(resumeQrl)}` }\n }\n for (const attribute of Array.from(element.attributes)) {\n if (attribute.value && attribute.name.startsWith('on:') && attribute.name.length > 3) {\n return { kind: 'event', detail: attribute.name }\n }\n }\n\n const childRoot =\n isHtmlElement(element) &&\n (element.localName || element.tagName).toLowerCase() === 'template' &&\n 'content' in element\n ? ((element as HTMLTemplateElement).content ?? element)\n : element\n const nested = findResumableFeature(childRoot)\n if (nested) return nested\n }\n return null\n}\n\nfunction findStreamingBoundaryMarker(root: Node): StreamingBoundaryMarker | null {\n for (const child of Array.from(root.childNodes)) {\n const marker = parseStreamingBoundaryMarker(child)\n if (marker) return marker\n if (child.nodeType !== ELEMENT_NODE) continue\n\n const element = child as Element\n const childRoot =\n isHtmlElement(element) &&\n (element.localName || element.tagName).toLowerCase() === 'template' &&\n 'content' in element\n ? ((element as HTMLTemplateElement).content ?? element)\n : element\n const nested = findStreamingBoundaryMarker(childRoot)\n if (nested) return nested\n }\n return null\n}\n\nfunction parseStreamingBoundaryMarker(node: Node | undefined): StreamingBoundaryMarker | null {\n if (!node || node.nodeType !== COMMENT_NODE) return null\n const value = node.nodeValue ?? ''\n if (value.startsWith(STREAM_BOUNDARY_START_PREFIX)) {\n const id = value.slice(STREAM_BOUNDARY_START_PREFIX.length)\n return id ? { kind: 'start', id } : null\n }\n if (value.startsWith(STREAM_BOUNDARY_END_PREFIX)) {\n const id = value.slice(STREAM_BOUNDARY_END_PREFIX.length)\n return id ? { kind: 'end', id } : null\n }\n return null\n}\n\nfunction serializeText(value: string, parentElement: Element | null): string {\n const rawTextTagName = getRawTextTagName(parentElement)\n if (rawTextTagName) return escapeRawTextEndTag(value, rawTextTagName)\n\n return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n}\n\nfunction escapeRawTextEndTag(value: string, tagName: string): string {\n const endTag = new RegExp(`</${tagName}(?=[\\\\t\\\\n\\\\f\\\\r />])`, 'gi')\n return value.replace(endTag, match => `<\\\\/${match.slice(2)}`)\n}\n\nfunction escapeAttributeValue(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n}\n\nfunction serializeComment(value: string): string {\n // `--`, a trailing `-`, and leading `>` / `->` are not valid in an HTML\n // comment. In particular, `<!--><script>...` exits the comment immediately,\n // so an otherwise inert DOM Comment could become active markup when the SSR\n // output is parsed by a browser.\n // Use a lookahead so every overlapping pair in a longer hyphen run is\n // separated. A non-overlapping /--/ replacement leaves `-->` behind for\n // inputs such as `--->`, which lets following markup escape the comment.\n let safe = value.replace(/-(?=-)/g, '- ').replace(/-$/, '- ')\n if (safe.startsWith('>') || safe.startsWith('->')) {\n safe = ` ${safe}`\n }\n return `<!--${safe}-->`\n}\n\nfunction serializeDocumentType(doctype: DocumentType): string {\n const name = doctype.name || 'html'\n assertValidDOMElementName(name, true)\n if (doctype.publicId) {\n const system = doctype.systemId ? ` \"${escapeAttributeValue(doctype.systemId)}\"` : ''\n return `<!DOCTYPE ${name} PUBLIC \"${escapeAttributeValue(doctype.publicId)}\"${system}>`\n }\n if (doctype.systemId) {\n return `<!DOCTYPE ${name} SYSTEM \"${escapeAttributeValue(doctype.systemId)}\">`\n }\n return `<!DOCTYPE ${name}>`\n}\n\nfunction isHtmlElement(element: Element): boolean {\n return element.namespaceURI === null || element.namespaceURI === HTML_NAMESPACE\n}\n\nfunction getRawTextTagName(element: Element | null): string | null {\n if (!element || !isHtmlElement(element)) return null\n const tagName = (element.localName || element.tagName).toLowerCase()\n return HTML_RAW_TEXT_ELEMENTS.has(tagName) ? tagName : null\n}\n","import { getNodeRequire } from './node-require'\n\ninterface NodePassThroughLike {\n pipe: (destination: NodeJS.WritableStream) => unknown\n write: (chunk: string | Uint8Array) => boolean\n end: (...args: unknown[]) => unknown\n destroy?: (error?: Error) => void\n on?: (event: 'error', listener: (error: Error) => void) => unknown\n}\n\nexport interface StreamWriter {\n write: (chunk: string) => void | Promise<void>\n close: () => void\n abort: (reason?: unknown) => void\n}\n\nexport interface QueuedTextStream {\n stream: ReadableStream<Uint8Array>\n writer: StreamWriter\n}\n\nexport interface QueuedTextStreamOptions {\n onCancel?: (reason?: unknown) => void\n}\n\nexport function createQueuedTextStream(options: QueuedTextStreamOptions = {}): QueuedTextStream {\n const encoder = new TextEncoder()\n const queue: Uint8Array[] = []\n let controller: ReadableStreamDefaultController<Uint8Array> | null = null\n let closed = false\n let aborted: unknown\n const readyResolvers: (() => void)[] = []\n\n const resolveReady = () => {\n if (!controller || (controller.desiredSize ?? 1) <= 0) return\n while (readyResolvers.length > 0) {\n readyResolvers.shift()?.()\n }\n }\n\n const drainReady = () => {\n while (readyResolvers.length > 0) {\n readyResolvers.shift()?.()\n }\n }\n\n const abortQueue = (reason?: unknown, notifyController = true) => {\n if (closed || aborted !== undefined) return\n aborted = reason ?? new Error('Stream aborted')\n queue.length = 0\n drainReady()\n if (notifyController) {\n controller?.error(aborted)\n }\n }\n\n const stream = new ReadableStream<Uint8Array>({\n start(ctrl) {\n controller = ctrl\n for (const chunk of queue) {\n ctrl.enqueue(chunk)\n }\n queue.length = 0\n if (aborted !== undefined) {\n ctrl.error(aborted)\n return\n }\n if (closed) {\n ctrl.close()\n }\n },\n pull() {\n resolveReady()\n },\n cancel(reason?: unknown) {\n abortQueue(reason, false)\n options.onCancel?.(reason)\n },\n })\n\n const writer: StreamWriter = {\n write(chunk) {\n if (closed || aborted !== undefined) return\n const data = encoder.encode(chunk)\n if (controller) {\n controller.enqueue(data)\n if ((controller.desiredSize ?? 1) <= 0) {\n return new Promise<void>(resolve => {\n readyResolvers.push(resolve)\n })\n }\n } else {\n queue.push(data)\n }\n return undefined\n },\n close() {\n if (closed || aborted !== undefined) return\n closed = true\n drainReady()\n controller?.close()\n },\n abort(reason?: unknown) {\n abortQueue(reason)\n },\n }\n\n return { stream, writer }\n}\n\nexport interface PipeBridge {\n pipe: (\n writable: NodeJS.WritableStream,\n options?: { onError?: (reason?: unknown) => void },\n ) => void\n write: (chunk: string) => void | Promise<void>\n close: () => void\n abort: (reason?: unknown) => void\n}\n\nexport function createPipeBridge(): PipeBridge {\n const nodeBridge = createNodePipeBridge()\n if (nodeBridge) return nodeBridge\n\n const targets = new Set<NodeJS.WritableStream>()\n const buffer: string[] = []\n let state: 'open' | 'closed' | 'aborted' = 'open'\n let abortReason: Error | null = null\n // Propagates downstream-sink failures to the render so it can abort instead of\n // hanging on a backed-up source (see docs/preview-degradation-audit.md G1).\n let sinkErrorHandler: ((reason?: unknown) => void) | undefined\n\n const safeWrite = (target: NodeJS.WritableStream, chunk: string): void | Promise<void> => {\n try {\n const ready = target.write(chunk)\n if (ready === false) {\n return new Promise(resolve => {\n const withOnce = target as NodeJS.WritableStream & {\n once?: (event: 'drain', listener: () => void) => unknown\n }\n if (typeof withOnce.once === 'function') {\n withOnce.once('drain', resolve)\n } else {\n resolve()\n }\n })\n }\n } catch (error) {\n // Surface the sink failure to the render (abort), then keep lifecycle deterministic.\n sinkErrorHandler?.(error)\n }\n return undefined\n }\n\n const safeEnd = (target: NodeJS.WritableStream) => {\n try {\n target.end()\n } catch {\n // Ignore end errors from downstream writable.\n }\n }\n\n const safeDestroy = (target: NodeJS.WritableStream, reason: Error) => {\n const withDestroy = target as NodeJS.WritableStream & { destroy?: (error?: Error) => void }\n if (typeof withDestroy.destroy === 'function') {\n try {\n withDestroy.destroy(reason)\n } catch {\n // Ignore destroy errors from downstream writable.\n }\n return\n }\n safeEnd(target)\n }\n\n return {\n pipe(writable, options) {\n targets.add(writable)\n if (options?.onError) {\n sinkErrorHandler = options.onError\n if (typeof (writable as { on?: unknown }).on === 'function') {\n writable.on('error', options.onError)\n }\n }\n if (buffer.length > 0) {\n for (const chunk of buffer) {\n safeWrite(writable, chunk)\n }\n buffer.length = 0\n }\n if (state === 'closed') {\n safeEnd(writable)\n } else if (state === 'aborted') {\n safeDestroy(writable, abortReason ?? new Error('Stream aborted'))\n }\n },\n write(chunk) {\n if (state !== 'open') return\n if (targets.size === 0) {\n buffer.push(chunk)\n return\n }\n const pending: Promise<void>[] = []\n for (const target of targets) {\n const result = safeWrite(target, chunk)\n if (result) pending.push(result)\n }\n return pending.length > 0 ? Promise.all(pending).then(() => undefined) : undefined\n },\n close() {\n if (state !== 'open') return\n state = 'closed'\n for (const target of targets) {\n safeEnd(target)\n }\n if (targets.size > 0) {\n buffer.length = 0\n }\n },\n abort(reason?: unknown) {\n if (state !== 'open') return\n state = 'aborted'\n abortReason = reason instanceof Error ? reason : new Error('Stream aborted')\n for (const target of targets) {\n safeDestroy(target, abortReason)\n }\n buffer.length = 0\n },\n }\n}\n\nfunction createNodePipeBridge(): PipeBridge | null {\n const nodeRequire = getNodeRequire()\n if (!nodeRequire) return null\n try {\n const streamModule = nodeRequire('node:stream') as {\n PassThrough?: new (...args: unknown[]) => NodePassThroughLike\n }\n if (!streamModule.PassThrough) return null\n const passThrough = new streamModule.PassThrough()\n\n // `destroy(error)` emits an asynchronous `error` event on Node streams.\n // This PassThrough is an internal implementation detail, so consumers\n // cannot attach a listener to it. Keep an internal listener installed to\n // prevent an explicit render abort from becoming an uncaught exception;\n // the public readiness promises still reject with the same reason.\n passThrough.on?.('error', () => {})\n\n const buffer: string[] = []\n let piped = false\n let state: 'open' | 'closed' | 'aborted' = 'open'\n let abortReason: Error | null = null\n // Pending backpressure 'drain' resolvers. If the sink dies the PassThrough\n // never drains, so these must be flushed on sink-error/abort to release the\n // render's write chain (otherwise allReady hangs — audit G1).\n const pendingDrains = new Set<() => void>()\n const flushDrains = () => {\n for (const resolve of pendingDrains) resolve()\n pendingDrains.clear()\n }\n\n const writeToPassThrough = (chunk: string): void | Promise<void> => {\n if (passThrough.write(chunk) === false) {\n return new Promise<void>(resolve => {\n const settle = () => {\n pendingDrains.delete(settle)\n resolve()\n }\n pendingDrains.add(settle)\n const withOnce = passThrough as NodePassThroughLike & {\n once?: (event: 'drain', listener: () => void) => unknown\n }\n if (typeof withOnce.once === 'function') {\n withOnce.once('drain', settle)\n } else {\n settle()\n }\n })\n }\n return undefined\n }\n\n const flushBuffer = (): void | Promise<void> => {\n if (buffer.length === 0) return undefined\n const pending: Promise<void>[] = []\n for (const chunk of buffer) {\n const result = writeToPassThrough(chunk)\n if (result) pending.push(result)\n }\n buffer.length = 0\n return pending.length > 0 ? Promise.all(pending).then(() => undefined) : undefined\n }\n\n const destroyPassThrough = (error: Error) => {\n if (typeof passThrough.destroy === 'function') {\n passThrough.destroy(error)\n } else {\n passThrough.end()\n }\n }\n\n return {\n pipe(writable, options) {\n piped = true\n passThrough.pipe(writable)\n // A downstream sink that errors mid-stream would otherwise back up the\n // source PassThrough and hang the render; route it to the render's abort.\n const onError = options?.onError\n if (onError && typeof (writable as { on?: unknown }).on === 'function') {\n writable.on('error', (err: unknown) => {\n flushDrains()\n onError(err)\n })\n }\n\n if (state === 'aborted') {\n destroyPassThrough(abortReason ?? new Error('Stream aborted'))\n return\n }\n\n const flushed = flushBuffer()\n if (state === 'closed') {\n if (flushed) {\n void flushed.then(() => passThrough.end())\n } else {\n passThrough.end()\n }\n }\n },\n write(chunk) {\n if (state !== 'open') return\n if (!piped) {\n buffer.push(chunk)\n return undefined\n }\n return writeToPassThrough(chunk)\n },\n close() {\n if (state !== 'open') return\n state = 'closed'\n if (!piped) return\n passThrough.end()\n },\n abort(reason?: unknown) {\n if (state !== 'open') return\n state = 'aborted'\n abortReason = reason instanceof Error ? reason : new Error('Stream aborted')\n buffer.length = 0\n flushDrains()\n if (piped) {\n destroyPassThrough(abortReason)\n }\n },\n }\n } catch {\n return null\n }\n}\n","import { render } from '@fictjs/runtime'\nimport type { FictNode } from '@fictjs/runtime'\nimport {\n __fictDisableSSR,\n __fictEnableSSR,\n __fictCreateSSRSession,\n __fictGetScopeRegistry,\n __fictRetainSSRSession,\n __fictRunWithSSRSession,\n __fictSerializeSSRState,\n __fictSerializeSSRStateForScopes,\n __fictSetSSRScopeIdentifierPrefix,\n __fictSetSSRStreamHooks,\n assertValidDOMAttributeName,\n assertValidDOMElementName,\n} from '@fictjs/runtime/internal'\nimport { parseHTML } from 'linkedom'\n\nimport { installGlobals, installManifest } from './globals'\nimport { serializeHtmlChildren, serializeHtmlNode, serializeHtmlNodes } from './html-serializer'\nimport { createPipeBridge, createQueuedTextStream, type StreamWriter } from './stream-bridge'\nimport { createStreamRuntimeCode } from './stream-runtime'\n\nconst DEFAULT_HTML = '<!doctype html><html><head></head><body></body></html>'\nconst SVG_HTML_INTEGRATION_POINTS = new Set(['foreignobject', 'title', 'desc'])\nconst MATHML_TEXT_INTEGRATION_POINTS = new Set(['mi', 'mo', 'mn', 'ms', 'mtext'])\nconst IDENTIFIER_PREFIX_PATTERN = /^[A-Za-z0-9_.:-]+$/\nlet streamTailMarkerId = 0\nlet scopeIdentifierSequence = 0\nlet streamIdentifierSequence = 0\nconst ssrIdentifierSeed = createIdentifierSeed()\n\ntype StreamPatchNamespace = 'svg' | 'mathml' | null\n\nexport interface SSRDom {\n window: Window\n document: Document\n}\n\nexport interface RenderToStringOptions {\n /**\n * Provide a pre-created DOM (document + window). If omitted, a new DOM is\n * created per render using `html`.\n */\n dom?: SSRDom\n /**\n * Provide a document directly. If `window` is omitted, `document.defaultView`\n * will be used when available.\n */\n document?: Document\n /**\n * Provide a window directly. If `document` is omitted, `window.document` is used.\n */\n window?: Window\n /**\n * HTML template used when creating a new DOM.\n */\n html?: string\n /**\n * Provide a container element to render into.\n */\n container?: HTMLElement\n /**\n * Tag name for the auto-created container.\n */\n containerTag?: string\n /**\n * id applied to the auto-created container.\n */\n containerId?: string\n /**\n * Additional attributes applied to the auto-created container.\n */\n containerAttributes?: Record<string, string | number | boolean | null | undefined>\n /**\n * Return the container element including its outer tag.\n */\n includeContainer?: boolean\n /**\n * Return a full HTML document string (doctype + documentElement.outerHTML).\n */\n fullDocument?: boolean\n /**\n * Override doctype when `fullDocument` is true. Use `null` to omit.\n */\n doctype?: string | null\n /**\n * Expose DOM globals (window/document/Node/Element/etc) during render.\n * Defaults to false. Set to true only for compatibility with components\n * that still read process-global DOM objects during server rendering.\n */\n exposeGlobals?: boolean\n /**\n * Manifest mapping module URLs to built client chunk URLs.\n * Can be an object or a path to a JSON file.\n * File path mode requires Deno sync filesystem access or a CommonJS\n * environment where `require('node:fs')` is available. Pass an object when\n * rendering from Node ESM or edge runtimes.\n */\n manifest?: Record<string, string> | string\n /**\n * Include the SSR snapshot script for resumability.\n * Defaults to true.\n */\n includeSnapshot?: boolean\n /**\n * Script element id for the snapshot.\n */\n snapshotScriptId?: string\n /**\n * Where to append the snapshot script when not returning full document.\n * Defaults to 'container'.\n */\n snapshotTarget?: 'container' | 'body' | 'head'\n /**\n * Nonce applied to generated <script> tags for CSP compatibility.\n */\n scriptNonce?: string\n /**\n * Stable namespace for resumable scope identifiers in `data-fict-s` and\n * snapshot payloads. Set this when independently cached or separately rendered\n * outputs can share a document, and keep it unique within that document.\n * This does not change streaming Suspense patch identifiers.\n *\n * Values must contain 1-128 ASCII letters, digits, `_`, `.`, `:`, or `-`, and\n * must not contain `--`. When omitted, each render gets an automatic edge-safe\n * namespace.\n */\n scopeIdentifierPrefix?: string\n}\n\nexport interface RenderToStreamOptions extends RenderToStringOptions {\n /**\n * Streaming mode:\n * - 'shell': send fallback shell first, then patch resolved boundaries\n * - 'all': wait for all suspense boundaries, then send full HTML\n */\n mode?: 'shell' | 'all'\n /**\n * Called once the initial shell has been written.\n */\n onShellReady?: () => void\n /**\n * Called once all pending boundaries resolve and the stream completes.\n */\n onAllReady?: () => void\n /**\n * Called when an error occurs during streaming.\n */\n onError?: (err: unknown) => void\n /**\n * Abort signal to cancel the stream.\n */\n signal?: AbortSignal\n /**\n * How to load the streaming patch runtime.\n * Defaults to 'inline'. Use 'external' with streamRuntimeSrc for strict CSP.\n */\n streamRuntime?: 'inline' | 'external'\n /**\n * External streaming patch runtime URL when streamRuntime is 'external'.\n */\n streamRuntimeSrc?: string\n /**\n * How resolved Suspense patch chunks are applied.\n * Defaults to 'inline' for inline runtimes and 'observer' for external runtimes.\n */\n streamPatchMode?: 'inline' | 'observer'\n /**\n * Stable namespace for Suspense patch identifiers. Set this when independently\n * cached or separately rendered streams can share a document, and keep it unique\n * within that document. This does not change resumable scope identifiers.\n *\n * Values must contain 1-128 ASCII letters, digits, `_`, `.`, `:`, or `-`, and\n * must not contain `--`. When omitted, each shell stream gets an automatic\n * edge-safe namespace.\n */\n streamIdentifierPrefix?: string\n}\n\nexport interface PipeableStream {\n pipe: (writable: NodeJS.WritableStream) => void\n abort: (reason?: unknown) => void\n shellReady: Promise<void>\n allReady: Promise<void>\n}\n\nexport interface PartialPrerenderResult {\n /**\n * Complete shell HTML (fallbacks + markers + initial snapshot scripts).\n *\n * @experimental Preview API for v1.0; the access pattern may change before\n * this becomes stable.\n */\n shell: string\n /**\n * Stream of deferred patch chunks and incremental snapshots.\n */\n stream: ReadableStream<Uint8Array>\n shellReady: Promise<void>\n allReady: Promise<void>\n abort: (reason?: unknown) => void\n}\n\nexport interface RenderToDocumentResult extends SSRDom {\n html: string\n container: HTMLElement\n dispose: () => void\n}\n\ninterface StreamingControlOptions {\n includeTailInShell?: boolean\n onShellFlushed?: () => void\n}\n\nexport function createSSRDocument(html: string = DEFAULT_HTML): SSRDom {\n const window = parseHTML(html) as Window & typeof globalThis\n const document = window.document as Document | undefined\n if (!window || !document) {\n throw new Error('[fict/ssr] Failed to create DOM. Missing window or document.')\n }\n return { window, document }\n}\n\nexport function renderToDocument(\n view: () => FictNode,\n options: RenderToStringOptions = {},\n): RenderToDocumentResult {\n const session = __fictCreateSSRSession()\n return __fictRunWithSSRSession(session, () => renderToDocumentInSession(view, options))\n}\n\nfunction renderToDocumentInSession(\n view: () => FictNode,\n options: RenderToStringOptions,\n): RenderToDocumentResult {\n validateScopeIdentifierPrefix(options.scopeIdentifierPrefix)\n const scopeIdentifierPrefix = resolveScopeIdentifierPrefix(options.scopeIdentifierPrefix)\n const includeSnapshot = options.includeSnapshot !== false\n\n // Always enable SSR mode during server rendering.\n // This ensures SSR-specific code paths (list rendering, etc.) work correctly\n // regardless of whether state snapshots are included.\n __fictEnableSSR()\n __fictSetSSRScopeIdentifierPrefix(scopeIdentifierPrefix)\n\n let dom: SSRDom\n let restoreGlobals = () => {}\n let restoreManifest = () => {}\n let container: HTMLElement\n let teardown = () => {}\n\n try {\n dom = resolveDom(options)\n const { document, window } = dom\n\n const shouldExpose = options.exposeGlobals === true\n restoreGlobals = shouldExpose ? installGlobals(window, document) : () => {}\n restoreManifest = installManifest(options.manifest)\n\n container = resolveContainer(document, options)\n teardown = render(view, container)\n\n if (includeSnapshot) {\n const state = __fictSerializeSSRState()\n injectSnapshot(document, container, state, options)\n }\n } catch (error) {\n // Clean up SSR state and globals on any error\n __fictDisableSSR()\n cleanupRenderResources(teardown, restoreGlobals, restoreManifest, true)\n throw error\n }\n\n // SSR rendering complete - disable SSR mode\n __fictDisableSSR()\n\n let html: string\n try {\n html = serializeOutput(dom.document, container!, options)\n } catch (error) {\n cleanupRenderResources(teardown, restoreGlobals, restoreManifest, true)\n throw error\n }\n\n const dispose = () => cleanupRenderResources(teardown, restoreGlobals, restoreManifest, false)\n\n return { html, document: dom.document, window: dom.window, container: container!, dispose }\n}\n\nexport function renderToString(view: () => FictNode, options: RenderToStringOptions = {}): string {\n const result = renderToDocument(view, options)\n const html = result.html\n result.dispose()\n return html\n}\n\nexport async function renderToStringAsync(\n view: () => FictNode,\n options: RenderToStringOptions = {},\n): Promise<string> {\n let html = ''\n const renderResult = startStreamingRender(\n view,\n {\n ...options,\n mode: 'all',\n // Streaming defaults to a full document, while the string APIs default\n // to the rendered container's children. Preserve renderToString's\n // output contract unless the caller explicitly requests a document.\n fullDocument: options.fullDocument ?? false,\n },\n {\n write(chunk) {\n html += chunk\n },\n close() {},\n abort() {},\n },\n )\n\n // `allReady` is the async stability point: every registered Suspense\n // boundary has resolved and its final DOM has been rendered. Await\n // `shellReady` as well so render failures settle both readiness promises\n // without leaving an unobserved rejection.\n await Promise.all([renderResult.shellReady, renderResult.allReady])\n return html\n}\n\nexport function renderToStream(\n view: () => FictNode,\n options: RenderToStreamOptions = {},\n): ReadableStream<Uint8Array> {\n validateScopeIdentifierPrefix(options.scopeIdentifierPrefix)\n validateStreamIdentifierPrefix(options.streamIdentifierPrefix)\n const encoder = new TextEncoder()\n let controller: ReadableStreamDefaultController<Uint8Array> | null = null\n let abortRender: ((reason?: unknown) => void) | null = null\n const readyResolvers: (() => void)[] = []\n\n const drainBackpressure = () => {\n while (readyResolvers.length > 0) {\n readyResolvers.shift()?.()\n }\n }\n\n const resolveBackpressure = () => {\n if (!controller || (controller.desiredSize ?? 1) <= 0) return\n drainBackpressure()\n }\n\n const closeController = () => {\n abortRender = null\n drainBackpressure()\n if (!controller) return\n try {\n controller.close()\n } finally {\n controller = null\n }\n }\n\n const errorController = (reason?: unknown) => {\n abortRender = null\n drainBackpressure()\n if (!controller) return\n try {\n controller.error(reason)\n } finally {\n controller = null\n }\n }\n\n const stream = new ReadableStream<Uint8Array>({\n start(ctrl) {\n controller = ctrl\n const started = startStreamingRender(view, options, {\n write(chunk) {\n if (!controller) return\n controller.enqueue(encoder.encode(chunk))\n if ((controller.desiredSize ?? 1) <= 0) {\n return new Promise<void>(resolve => {\n readyResolvers.push(resolve)\n })\n }\n return undefined\n },\n close() {\n closeController()\n },\n abort(reason?: unknown) {\n errorController(reason)\n },\n })\n abortRender = started.abort\n // renderToStream doesn't expose readiness promises, so consume rejections\n // to avoid unhandled promise noise when streaming aborts.\n started.shellReady.catch(() => undefined)\n started.allReady.catch(() => undefined)\n },\n pull() {\n resolveBackpressure()\n },\n cancel(reason?: unknown) {\n const abort = abortRender\n controller = null\n drainBackpressure()\n abort?.(reason ?? new Error('Stream canceled'))\n },\n })\n\n return stream\n}\n\nexport function renderToPipeableStream(\n view: () => FictNode,\n options: RenderToStreamOptions = {},\n): PipeableStream {\n const bridge = createPipeBridge()\n const { shellReady, allReady, abort } = startStreamingRender(view, options, {\n write(chunk) {\n return bridge.write(chunk)\n },\n close() {\n bridge.close()\n },\n abort(reason?: unknown) {\n bridge.abort(reason)\n },\n })\n\n return {\n pipe(writable) {\n // Route downstream-sink errors to abort so a failing sink rejects\n // shellReady/allReady and runs cleanup instead of hanging the render.\n bridge.pipe(writable, { onError: abort })\n },\n abort,\n shellReady,\n allReady,\n }\n}\n\n/**\n * @experimental Preview API for v1.0; the return shape may change before this\n * becomes stable.\n */\nexport function renderToPartial(\n view: () => FictNode,\n options: RenderToStreamOptions = {},\n): PartialPrerenderResult {\n const partialOptions: RenderToStreamOptions = {\n ...options,\n mode: 'shell',\n fullDocument: options.fullDocument ?? true,\n }\n\n let shell = ''\n let shellPhase = true\n let abortPartial: ((reason?: unknown) => void) | null = null\n const queued = createQueuedTextStream({\n onCancel(reason) {\n abortPartial?.(reason ?? new Error('Stream canceled'))\n },\n })\n\n const { shellReady, allReady, abort } = startStreamingRender(\n view,\n partialOptions,\n {\n write(chunk) {\n if (shellPhase) {\n shell += chunk\n return\n }\n return queued.writer.write(chunk)\n },\n close() {\n queued.writer.close()\n },\n abort(reason?: unknown) {\n queued.writer.abort(reason)\n },\n },\n {\n includeTailInShell: true,\n onShellFlushed() {\n shellPhase = false\n },\n },\n )\n abortPartial = abort\n\n return {\n shell,\n stream: queued.stream,\n shellReady,\n allReady,\n abort,\n }\n}\n\nfunction resolveDom(options: RenderToStringOptions): SSRDom {\n if (options.dom) {\n return options.dom\n }\n\n if (options.document && options.window) {\n return { document: options.document, window: options.window }\n }\n\n if (options.document) {\n const window =\n options.window ??\n (options.document.defaultView as Window | null) ??\n (options.document as Document & { defaultView?: Window | null }).defaultView ??\n undefined\n if (!window) {\n throw new Error(\n '[fict/ssr] A window is required when providing a document without defaultView.',\n )\n }\n return { document: options.document, window }\n }\n\n if (options.window) {\n return { document: options.window.document, window: options.window }\n }\n\n return createSSRDocument(options.html)\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as PromiseLike<unknown>).then === 'function'\n )\n}\n\nfunction cleanupRenderResources(\n teardown: () => void,\n restoreGlobals: () => void,\n restoreManifest: () => void,\n suppressErrors: boolean,\n): void {\n let failed = false\n let firstError: unknown\n for (const cleanup of [teardown, restoreGlobals, restoreManifest]) {\n try {\n cleanup()\n } catch (error) {\n if (!failed) {\n failed = true\n firstError = error\n }\n }\n }\n if (failed && !suppressErrors) throw firstError\n}\n\nfunction startStreamingRender(\n view: () => FictNode,\n options: RenderToStreamOptions,\n writer: StreamWriter,\n control: StreamingControlOptions = {},\n): { shellReady: Promise<void>; allReady: Promise<void>; abort: (reason?: unknown) => void } {\n const session = __fictCreateSSRSession()\n const releaseSession = __fictRetainSSRSession()\n try {\n return __fictRunWithSSRSession(session, () =>\n startStreamingRenderInSession(session, view, options, writer, releaseSession, control),\n )\n } catch (error) {\n releaseSession()\n throw error\n }\n}\n\ntype SSRSession = ReturnType<typeof __fictCreateSSRSession>\n\nfunction startStreamingRenderInSession(\n session: SSRSession,\n view: () => FictNode,\n options: RenderToStreamOptions,\n writer: StreamWriter,\n releaseSession: () => void,\n control: StreamingControlOptions = {},\n): { shellReady: Promise<void>; allReady: Promise<void>; abort: (reason?: unknown) => void } {\n const runInSession = <T>(fn: () => T): T => __fictRunWithSSRSession(session, fn)\n const resolvedOptions: RenderToStreamOptions = {\n ...options,\n // Streaming requires a real document; default to fullDocument when unspecified.\n fullDocument: options.fullDocument ?? true,\n }\n\n let resolveShell!: () => void\n let rejectShell!: (err: unknown) => void\n let resolveAll!: () => void\n let rejectAll!: (err: unknown) => void\n let shellSettled = false\n\n const shellReady = new Promise<void>((res, rej) => {\n resolveShell = () => {\n if (shellSettled) return\n shellSettled = true\n res()\n }\n rejectShell = err => {\n if (shellSettled) return\n shellSettled = true\n rej(err)\n }\n })\n const allReady = new Promise<void>((res, rej) => {\n resolveAll = res\n rejectAll = rej\n })\n\n let dom: SSRDom | null = null\n let restoreGlobals = () => {}\n let restoreManifest = () => {}\n let teardown = () => {}\n let container: HTMLElement | null = null\n let closed = false\n let tailHtml = ''\n let wroteShell = false\n let shellCarriesTail = false\n let writeChain: Promise<void> | null = null\n let writeFailed = false\n let failureReported = false\n let cleaned = false\n let removeAbortListener = () => {}\n let canFinalize = false\n\n validateScopeIdentifierPrefix(options.scopeIdentifierPrefix)\n validateStreamIdentifierPrefix(options.streamIdentifierPrefix)\n const mode = options.mode ?? 'shell'\n const scopeIdentifierPrefix = resolveScopeIdentifierPrefix(options.scopeIdentifierPrefix)\n const streamIdentifierPrefix =\n mode === 'shell' ? resolveStreamIdentifierPrefix(options.streamIdentifierPrefix) : null\n const includeSnapshot = options.includeSnapshot !== false\n const sentScopeSnapshots = new Map<string, string>()\n\n const boundaryMap = new Map<string, { start: Comment; end: Comment; pending: boolean }>()\n let boundaryId = 0\n let pendingCount = 0\n\n const handleWriteError = (error: unknown) => {\n if (writeFailed) return\n reportErrorAndAbort(error)\n }\n\n const enqueueWrite = (chunk: string): void => {\n if (writeFailed) return\n const trackWrite = (promise: Promise<void>) => {\n const tracked = promise.then(\n () => {\n if (writeChain === tracked) {\n writeChain = null\n }\n },\n error => {\n if (writeChain === tracked) {\n writeChain = null\n }\n handleWriteError(error)\n },\n )\n writeChain = tracked\n }\n const writeAsync = () => Promise.resolve(writer.write(chunk)).then(() => undefined)\n\n if (writeChain) {\n trackWrite(writeChain.then(writeAsync))\n return\n }\n\n try {\n const result = writer.write(chunk)\n if (isPromiseLike(result)) {\n trackWrite(\n result.then(\n () => undefined,\n error => {\n throw error\n },\n ),\n )\n }\n } catch (error) {\n handleWriteError(error)\n }\n }\n\n const afterWrites = (fn: () => void): void => {\n const pending = writeChain\n if (!pending) {\n if (!writeFailed) {\n fn()\n }\n return\n }\n void pending.then(() => {\n if (!writeFailed) {\n fn()\n }\n })\n }\n\n const markShellReady = (): void => {\n afterWrites(() => {\n try {\n control.onShellFlushed?.()\n } catch (error) {\n reportErrorAndAbort(error)\n return\n }\n resolveShell()\n callLifecycleCallback(options.onShellReady)\n })\n }\n\n const writeSnapshotForScopes = (scopeIds: string[]): void => {\n runInSession(() => {\n if (!includeSnapshot || scopeIds.length === 0) return\n const registry = __fictGetScopeRegistry()\n const pending = Array.from(new Set(scopeIds)).filter(id => registry.has(id))\n if (pending.length === 0) return\n const snapshot = __fictSerializeSSRStateForScopes(pending)\n const changedScopes = Object.create(null) as typeof snapshot.scopes\n const changedSignatures = new Map<string, string>()\n for (const [id, scope] of Object.entries(snapshot.scopes)) {\n const signature = JSON.stringify(scope)\n if (sentScopeSnapshots.get(id) === signature) continue\n changedScopes[id] = scope\n changedSignatures.set(id, signature)\n }\n const ids = Object.keys(changedScopes)\n if (ids.length === 0) return\n const chunk = buildIncrementalSnapshotChunk(\n { ...snapshot, scopes: changedScopes },\n resolvedOptions,\n )\n if (chunk) {\n enqueueWrite(chunk)\n }\n for (const id of ids) {\n sentScopeSnapshots.set(id, changedSignatures.get(id)!)\n }\n })\n }\n\n const writeSnapshotForBoundary = (start: Comment, end: Comment): void => {\n runInSession(() => {\n // Include scope hosts that become visible in this patch plus the owning\n // ancestor scopes whose state may have changed while resolving it. Avoid\n // publishing unrelated live sibling revisions without a matching DOM patch.\n const scopes = collectPatchScopeIds(start, end)\n writeSnapshotForScopes(scopes)\n })\n }\n\n const writeRemainingSnapshots = (): void => {\n runInSession(() => {\n const scopes = Array.from(__fictGetScopeRegistry().keys())\n writeSnapshotForScopes(scopes)\n })\n }\n\n const cleanup = () => {\n if (cleaned) return\n cleaned = true\n try {\n removeAbortListener()\n } catch {\n // Cleanup must remain best-effort so readiness promises always settle.\n }\n removeAbortListener = () => {}\n try {\n runInSession(() => {\n __fictSetSSRStreamHooks(null)\n __fictDisableSSR()\n })\n } catch {\n // Continue with owner/global cleanup even if session reset fails.\n }\n try {\n cleanupRenderResources(teardown, restoreGlobals, restoreManifest, true)\n } finally {\n releaseSession()\n }\n }\n\n const reportErrorAndAbort = (error: unknown) => {\n if (failureReported) {\n abort(error)\n return\n }\n failureReported = true\n let abortReason = error\n try {\n options.onError?.(error)\n } catch (onErrorFailure) {\n abortReason = onErrorFailure\n }\n abort(abortReason)\n }\n\n const callLifecycleCallback = (callback: (() => void) | undefined): void => {\n try {\n callback?.()\n } catch (error) {\n reportErrorAndAbort(error)\n }\n }\n\n const finalize = () => {\n if (closed) return\n\n if (mode === 'all' && dom && container && !wroteShell) {\n let fullHtml: string\n try {\n if (includeSnapshot) {\n const snapshot = __fictSerializeSSRState()\n injectSnapshot(dom.document, container, snapshot, resolvedOptions)\n }\n fullHtml = serializeOutput(dom.document, container, resolvedOptions)\n } catch (error) {\n reportErrorAndAbort(error)\n return\n }\n\n closed = true\n enqueueWrite(fullHtml)\n afterWrites(() => {\n try {\n writer.close()\n } catch (error) {\n reportErrorAndAbort(error)\n return\n }\n cleanup()\n resolveShell()\n resolveAll()\n callLifecycleCallback(options.onShellReady)\n callLifecycleCallback(options.onAllReady)\n })\n return\n }\n\n try {\n writeRemainingSnapshots()\n } catch (error) {\n reportErrorAndAbort(error)\n return\n }\n if (writeFailed) return\n closed = true\n\n if (tailHtml) {\n enqueueWrite(tailHtml)\n }\n\n afterWrites(() => {\n try {\n writer.close()\n } catch (error) {\n reportErrorAndAbort(error)\n return\n }\n cleanup()\n resolveAll()\n callLifecycleCallback(options.onAllReady)\n })\n }\n\n const maybeFinalize = () => {\n if (canFinalize && pendingCount === 0) {\n finalize()\n }\n }\n\n const registerStreamBoundary = (start: Comment, end: Comment): string => {\n const localId = `s${++boundaryId}`\n const id = streamIdentifierPrefix ? `${streamIdentifierPrefix}:${localId}` : localId\n boundaryMap.set(id, { start, end, pending: false })\n return id\n }\n\n const hooks = {\n registerBoundary: registerStreamBoundary,\n registerErrorBoundary: registerStreamBoundary,\n boundaryPending(id: string) {\n const entry = boundaryMap.get(id)\n if (!entry || entry.pending) return\n entry.pending = true\n pendingCount++\n },\n boundaryResolved(id: string) {\n const entry = boundaryMap.get(id)\n if (!entry) return\n if (entry.pending) {\n entry.pending = false\n pendingCount = Math.max(0, pendingCount - 1)\n }\n if (mode === 'shell' && wroteShell) {\n try {\n if (dom) {\n writeSnapshotForBoundary(entry.start, entry.end)\n const content = serializeBetween(entry.start, entry.end)\n enqueueWrite(buildPatchChunk(id, content, resolvedOptions))\n }\n } catch (error) {\n reportErrorAndAbort(error)\n return\n }\n }\n maybeFinalize()\n },\n boundaryAbandoned(id: string) {\n const entry = boundaryMap.get(id)\n if (!entry) return\n boundaryMap.delete(id)\n if (entry.pending) {\n pendingCount = Math.max(0, pendingCount - 1)\n }\n maybeFinalize()\n },\n onError(err: unknown) {\n reportErrorAndAbort(err)\n },\n }\n\n const abort = (reason?: unknown) => {\n const abortReason = reason ?? new Error('Stream aborted')\n if (!cleaned) {\n closed = true\n writeFailed = true\n cleanup()\n try {\n writer.abort(abortReason)\n } catch {\n // A broken sink must not prevent readiness promises from rejecting.\n }\n }\n // Always settle. A late sink error can arrive after finalize() set `closed`\n // but before its (stalled) write chain resolves; rejecting an already-settled\n // promise is a no-op, so this is safe and prevents allReady from hanging.\n rejectShell(abortReason)\n rejectAll(abortReason)\n }\n\n if (options.signal) {\n if (options.signal.aborted) {\n abort(options.signal.reason)\n return { shellReady, allReady, abort }\n } else {\n const onAbort = () => abort(options.signal?.reason)\n options.signal.addEventListener('abort', onAbort, { once: true })\n removeAbortListener = () => options.signal?.removeEventListener('abort', onAbort)\n }\n }\n\n try {\n __fictEnableSSR()\n __fictSetSSRScopeIdentifierPrefix(scopeIdentifierPrefix)\n __fictSetSSRStreamHooks(hooks)\n\n dom = resolveDom(resolvedOptions)\n restoreGlobals =\n resolvedOptions.exposeGlobals === true ? installGlobals(dom.window, dom.document) : () => {}\n restoreManifest = installManifest(resolvedOptions.manifest)\n\n container = resolveContainer(dom.document, resolvedOptions)\n teardown = render(view, container)\n\n if (mode === 'all') {\n canFinalize = true\n maybeFinalize()\n return { shellReady, allReady, abort }\n }\n\n // shell-first mode\n const streamRuntime = boundaryMap.size > 0 ? buildStreamRuntimeScript(resolvedOptions) : ''\n if (resolvedOptions.fullDocument) {\n const split = serializeStreamingDocument(dom.document, container, resolvedOptions)\n if (!split) {\n throw new Error('[fict/ssr] Failed to locate the document body for streaming output.')\n }\n if (control.includeTailInShell) {\n enqueueWrite(split.head + streamRuntime)\n tailHtml = split.tail\n shellCarriesTail = true\n } else {\n enqueueWrite(split.head + streamRuntime)\n tailHtml = split.tail\n }\n } else {\n const shellHtml = serializeOutput(dom.document, container, resolvedOptions)\n enqueueWrite(shellHtml + streamRuntime)\n }\n if (writeFailed) return { shellReady, allReady, abort }\n wroteShell = true\n writeSnapshotForScopes(Array.from(__fictGetScopeRegistry().keys()))\n if (shellCarriesTail && tailHtml) {\n enqueueWrite(tailHtml)\n tailHtml = ''\n shellCarriesTail = false\n }\n markShellReady()\n\n // If no pending boundaries, finalize immediately.\n canFinalize = true\n maybeFinalize()\n } catch (err) {\n reportErrorAndAbort(err)\n }\n\n return { shellReady, allReady, abort }\n}\n\nfunction resolveContainer(document: Document, options: RenderToStringOptions): HTMLElement {\n if (options.container) {\n if (options.container.ownerDocument && options.container.ownerDocument !== document) {\n throw new Error('[fict/ssr] Provided container belongs to a different document.')\n }\n return options.container\n }\n\n const tag = options.containerTag ?? 'div'\n assertValidDOMElementName(tag)\n const container = document.createElement(tag)\n if (options.containerId) {\n container.setAttribute('id', options.containerId)\n }\n if (options.containerAttributes) {\n for (const [name, value] of Object.entries(options.containerAttributes)) {\n assertValidDOMAttributeName(name)\n if (value === null || value === undefined || value === false) continue\n container.setAttribute(name, value === true ? '' : String(value))\n }\n }\n\n if (document.body) {\n document.body.appendChild(container)\n }\n\n return container\n}\n\nfunction buildStreamRuntimeScript(options: RenderToStreamOptions): string {\n const nonce = renderNonceAttribute(options)\n if (options.streamRuntime === 'external') {\n if (!options.streamRuntimeSrc) {\n throw new Error('[fict/ssr] streamRuntimeSrc is required when streamRuntime is \"external\".')\n }\n return `<script${nonce} src=\"${escapeAttribute(options.streamRuntimeSrc)}\" data-fict-stream-runtime data-fict-stream-observer></script>`\n }\n\n return `<script${nonce}>${createStreamRuntimeCode({\n observerMode: resolveStreamPatchMode(options) === 'observer',\n })}</script>`\n}\n\nfunction buildPatchChunk(\n id: string,\n content: { html: string; namespace: StreamPatchNamespace },\n options: RenderToStreamOptions,\n): string {\n const namespaceAttribute = content.namespace\n ? ` data-fict-patch-namespace=\"${content.namespace}\"`\n : ''\n const html =\n content.namespace === 'svg'\n ? `<svg>${content.html}</svg>`\n : content.namespace === 'mathml'\n ? `<math>${content.html}</math>`\n : content.html\n const template = `<template data-fict-suspense=\"${escapeAttribute(id)}\"${namespaceAttribute}>${html}</template>`\n if (resolveStreamPatchMode(options) === 'observer') {\n return template\n }\n return `${template}<script${renderNonceAttribute(options)}>__FICT_STREAM.apply(\"${escapeScriptString(id)}\")</script>`\n}\n\nfunction resolveStreamPatchMode(options: RenderToStreamOptions): 'inline' | 'observer' {\n if (options.streamPatchMode) return options.streamPatchMode\n return options.streamRuntime === 'external' ? 'observer' : 'inline'\n}\n\nfunction resolveStreamIdentifierPrefix(configured: string | undefined): string {\n if (configured !== undefined) return configured\n\n return `f${ssrIdentifierSeed}.${(++streamIdentifierSequence).toString(36)}`\n}\n\nfunction validateStreamIdentifierPrefix(configured: unknown): void {\n validateIdentifierPrefix('streamIdentifierPrefix', configured)\n}\n\nfunction resolveScopeIdentifierPrefix(configured: string | undefined): string {\n if (configured !== undefined) return configured\n\n return `r${ssrIdentifierSeed}.${(++scopeIdentifierSequence).toString(36)}`\n}\n\nfunction validateScopeIdentifierPrefix(configured: unknown): void {\n validateIdentifierPrefix('scopeIdentifierPrefix', configured)\n}\n\nfunction validateIdentifierPrefix(option: string, configured: unknown): void {\n if (configured === undefined) return\n if (\n typeof configured !== 'string' ||\n configured.length === 0 ||\n configured.length > 128 ||\n !IDENTIFIER_PREFIX_PATTERN.test(configured) ||\n configured.includes('--')\n ) {\n throw new TypeError(\n `[fict/ssr] ${option} must contain 1-128 ASCII letters, digits, \"_\", \".\", \":\", or \"-\", and must not contain \"--\".`,\n )\n }\n}\n\nfunction createIdentifierSeed(): string {\n try {\n const uuid = globalThis.crypto?.randomUUID?.()\n const normalized = uuid?.replace(/[^A-Za-z0-9]/g, '')\n if (normalized) return normalized\n } catch {\n // Fall through for edge runtimes that expose a partial or guarded Crypto object.\n }\n\n const random = Math.random().toString(36).slice(2) || '0'\n return `${Date.now().toString(36)}${random}`\n}\n\nfunction serializeBetween(\n start: Comment,\n end: Comment,\n): { html: string; namespace: StreamPatchNamespace } {\n const parentElement =\n start.parentElement ?? (start.parentNode?.nodeType === 1 ? (start.parentNode as Element) : null)\n const nodes: Node[] = []\n let node = start.nextSibling\n while (node && node !== end) {\n nodes.push(node)\n node = node.nextSibling\n }\n const namespace = resolveStreamPatchNamespace(parentElement)\n return { html: serializeHtmlNodes(nodes, parentElement), namespace }\n}\n\nfunction collectPatchScopeIds(start: Comment, end: Comment): string[] {\n const ids = new Set<string>()\n const addScopeId = (element: Element) => {\n const id = element.getAttribute('data-fict-s')\n if (id) ids.add(id)\n }\n const addVisibleSubtree = (element: Element) => {\n addScopeId(element)\n for (const descendant of element.querySelectorAll('[data-fict-s]')) {\n addScopeId(descendant)\n }\n }\n\n const parentElement =\n start.parentElement ?? (start.parentNode?.nodeType === 1 ? (start.parentNode as Element) : null)\n let ancestor = parentElement\n while (ancestor) {\n addScopeId(ancestor)\n ancestor = ancestor.parentElement\n }\n\n let node = start.nextSibling\n while (node && node !== end) {\n if (node.nodeType === 1) {\n addVisibleSubtree(node as Element)\n }\n node = node.nextSibling\n }\n\n return Array.from(ids)\n}\n\nfunction resolveStreamPatchNamespace(parentElement: Element | null): StreamPatchNamespace {\n if (!parentElement) return null\n\n // linkedom currently reports MathML elements as XHTML. Recover the parser\n // context from tag ancestry. Walking from the boundary outward also lets a\n // nested <svg>/<math> override an older HTML integration point.\n let element: Element | null = parentElement\n let descendantLocalName: string | null = null\n while (element) {\n const localName = element.localName.toLowerCase()\n if (SVG_HTML_INTEGRATION_POINTS.has(localName)) return null\n if (MATHML_TEXT_INTEGRATION_POINTS.has(localName)) {\n if (descendantLocalName === 'mglyph' || descendantLocalName === 'malignmark') {\n return 'mathml'\n }\n return null\n }\n if (isHtmlAnnotationIntegrationPoint(element)) return null\n if (localName === 'svg') return 'svg'\n if (localName === 'math') return 'mathml'\n descendantLocalName = localName\n element = element.parentElement\n }\n return null\n}\n\nfunction isHtmlAnnotationIntegrationPoint(element: Element): boolean {\n if (element.localName.toLowerCase() !== 'annotation-xml') return false\n const encoding = element.getAttribute('encoding')?.toLowerCase()\n return encoding === 'text/html' || encoding === 'application/xhtml+xml'\n}\n\nfunction serializeStreamingDocument(\n document: Document,\n container: HTMLElement,\n options: RenderToStringOptions,\n): { head: string; tail: string } | null {\n const body = document.body\n if (!body) return null\n\n const marker = document.createComment('')\n body.appendChild(marker)\n const markerSeed = `fict:stream-tail:${++streamTailMarkerId}`\n let markerText = markerSeed\n\n try {\n // A structural marker identifies the actual end of body without mistaking\n // matching text inside raw-text elements or comments for a closing tag.\n // If user HTML already contains the marker, doubling the marker guarantees\n // a unique finite marker after logarithmically many retries.\n while (true) {\n marker.data = markerText\n const html = serializeOutput(document, container, options)\n const serializedMarker = `<!--${markerText}-->`\n const idx = html.indexOf(serializedMarker)\n if (idx !== -1 && html.indexOf(serializedMarker, idx + serializedMarker.length) === -1) {\n return {\n head: html.slice(0, idx),\n tail: html.slice(idx + serializedMarker.length),\n }\n }\n markerText += markerText\n }\n } finally {\n marker.parentNode?.removeChild(marker)\n }\n}\n\nfunction buildIncrementalSnapshotChunk(\n state: ReturnType<typeof __fictSerializeSSRState>,\n options: RenderToStringOptions,\n): string {\n const json = serializeSnapshotForScript(state)\n const nonce = renderNonceAttribute(options)\n if (options.snapshotTarget === 'head') {\n const jsonLiteral = JSON.stringify(json)\n const setNonce =\n options.scriptNonce !== undefined\n ? `s.setAttribute('nonce',${serializeScriptStringLiteral(options.scriptNonce)});`\n : ''\n return `<script${nonce}>(function(){var s=document.createElement('script');s.type='application/json';s.setAttribute('data-fict-snapshot','');${setNonce}s.textContent=${jsonLiteral};(document.head||document.documentElement).appendChild(s);}())</script>`\n }\n return `<script${nonce} type=\"application/json\" data-fict-snapshot>${json}</script>`\n}\n\nfunction serializeOutput(\n document: Document,\n container: HTMLElement,\n options: RenderToStringOptions,\n): string {\n if (options.fullDocument) {\n const doctype = serializeDoctype(document, options.doctype)\n const html = document.documentElement\n ? serializeHtmlNode(document.documentElement)\n : serializeHtmlNode(container)\n return doctype ? `${doctype}${html}` : html\n }\n\n if (options.includeContainer) {\n return serializeHtmlNode(container)\n }\n\n return serializeHtmlChildren(container)\n}\n\nfunction injectSnapshot(\n document: Document,\n container: HTMLElement,\n state: ReturnType<typeof __fictSerializeSSRState>,\n options: RenderToStringOptions,\n): void {\n const script = document.createElement('script')\n script.type = 'application/json'\n script.id = options.snapshotScriptId ?? '__FICT_SNAPSHOT__'\n if (options.scriptNonce !== undefined) {\n script.setAttribute('nonce', options.scriptNonce)\n }\n script.textContent = serializeSnapshotForScript(state)\n\n if (options.fullDocument) {\n if (options.snapshotTarget === 'head' && document.head) {\n document.head.appendChild(script)\n return\n }\n if (document.body) {\n document.body.appendChild(script)\n return\n }\n }\n\n const target = options.snapshotTarget ?? 'container'\n if (target === 'body' && document.body) {\n document.body.appendChild(script)\n return\n }\n if (target === 'head' && document.head) {\n document.head.appendChild(script)\n return\n }\n\n container.appendChild(script)\n}\n\nfunction serializeSnapshotForScript(state: ReturnType<typeof __fictSerializeSSRState>): string {\n return JSON.stringify(state)\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029')\n}\n\nfunction serializeScriptStringLiteral(value: string): string {\n return JSON.stringify(value)\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029')\n}\n\nfunction renderNonceAttribute(options: RenderToStringOptions): string {\n return options.scriptNonce === undefined ? '' : ` nonce=\"${escapeAttribute(options.scriptNonce)}\"`\n}\n\nfunction escapeAttribute(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n}\n\nfunction escapeScriptString(value: string): string {\n return value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/</g, '\\\\u003c')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029')\n}\n\nfunction serializeDoctype(document: Document, override?: string | null): string {\n if (override === null) return ''\n if (override !== undefined) return override\n\n const doctype = document.doctype\n if (!doctype) return ''\n return serializeHtmlNode(doctype)\n}\n"],"mappings":";;;;;;;;;;;;AASA,SAAgB,iBAA0D;CACxE,IAAI,OAAO,0BAA0B,YACnC,OAAO;CAGT,MAAM,SAAU,WAAuC;CACvD,IAAI,OAAO,WAAW,YACpB,OAAO;CAGT,IAAI;EACF,OAAO,SAAS,yDAAuD,CAAC,CAAC;CAG3E,QAAQ;EACN,OAAO;CACT;AACF;;;AChBA,SAAgB,eAAe,QAAgB,UAAgC;CAC7E,MAAM,MAAM;CAiBZ,MAAM,WAAoC;EACxC,QAAQ;EACR;EACA,MAAM;EACN,MAAM,IAAI;EACV,SAAS,IAAI;EACb,aAAa,IAAI;EACjB,YAAY,IAAI;EAChB,UAAU,IAAI;EACd,kBAAkB,IAAI;EACtB,MAAM,IAAI;EACV,SAAS,IAAI;CACf;CAEA,MAAM,WAAoC;EACxC,OAAO,IAAI;EACX,OAAO,IAAI;EACX,aAAa,IAAI;EACj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