@bgub/fig-server 0.1.0-alpha.1 → 0.1.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{shared-Bna74_aZ.js → image-preloads-BIFcrqm9.js} +40 -2
- package/dist/image-preloads-BIFcrqm9.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +68 -12
- package/dist/index.js.map +1 -1
- package/dist/payload.d.ts +1 -1
- package/dist/payload.js +22 -6
- package/dist/payload.js.map +1 -1
- package/dist/{types-CimwEFsf.d.ts → types-mrjoQDOc.d.ts} +6 -3
- package/dist-development/escaping-DAot8sFu.js +26 -0
- package/dist-development/escaping-DAot8sFu.js.map +1 -0
- package/dist-development/html-entry.js +2 -0
- package/dist-development/image-preloads-D3OBEaWp.js +164 -0
- package/dist-development/image-preloads-D3OBEaWp.js.map +1 -0
- package/dist-development/index.js +1764 -0
- package/dist-development/index.js.map +1 -0
- package/dist-development/payload.js +602 -0
- package/dist-development/payload.js.map +1 -0
- package/package.json +8 -4
- package/dist/shared-Bna74_aZ.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["writeRuntime","writeScript"],"sources":["../src/html.ts","../src/preload-header.ts","../src/asset-registry.ts","../src/protocol.ts","../src/renderer-flush.ts","../src/renderer.ts","../src/render-tree.ts","../src/index.ts"],"sourcesContent":["import type { Props } from \"@bgub/fig\";\nimport { isPortal } from \"@bgub/fig/internal\";\nimport { escapeAttribute, escapeText } from \"./escaping.ts\";\n\nexport {\n escapeAttribute,\n escapeScriptJson,\n escapeScriptText,\n escapeText,\n} from \"./escaping.ts\";\n\ninterface HtmlSink {\n write(chunk: string): void;\n}\n\nconst voidElements = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\nexport function writeText(value: string, sink: HtmlSink): void {\n sink.write(escapeText(value));\n}\n\nexport function writeElementStart(\n type: string,\n props: Props,\n sink: HtmlSink,\n inheritedProps: Props = {},\n): void {\n validateTagName(type);\n sink.write(`<${type}${serializeAttributes(type, props, inheritedProps)}>`);\n}\n\nexport function writeElementEnd(type: string, sink: HtmlSink): void {\n sink.write(`</${type}>`);\n}\n\nexport function isVoidElement(type: string): boolean {\n return voidElements.has(type);\n}\n\nexport function hasRenderableChild(node: unknown): boolean {\n if (Array.isArray(node)) return node.some(hasRenderableChild);\n if (isPortal(node)) return false;\n return !emptyChild(node);\n}\n\nexport function formTextContent(type: string, props: Props): string | null {\n if (type !== \"textarea\") return null;\n\n const value = props.value !== undefined ? props.value : props.defaultValue;\n return formString(value);\n}\n\nexport function unsafeHTMLContent(props: Props): string | null {\n const value = props.unsafeHTML;\n if (emptyValue(value)) return null;\n if (typeof value === \"string\") return value;\n throw new Error(\"The unsafeHTML prop must be a string during server render.\");\n}\n\nfunction serializeAttributes(\n type: string,\n props: Props,\n inheritedProps: Props,\n): string {\n let attributes = \"\";\n\n for (const name of Object.keys(props)) {\n const value = props[name];\n if (reservedProp(name)) continue;\n if (name === \"value\" && props.defaultValue !== undefined) continue;\n if (name === \"checked\" && props.defaultChecked !== undefined) continue;\n\n if (name === \"style\") {\n const style = serializeStyle(value);\n if (style !== \"\") attributes += serializeAttribute(\"style\", style);\n continue;\n }\n\n attributes += serializeProp(type, name, value);\n }\n\n if (\n type === \"option\" &&\n props.selected === undefined &&\n optionSelected(optionValue(props), inheritedProps)\n ) {\n attributes += \" selected\";\n }\n\n return attributes;\n}\n\nfunction serializeProp(type: string, name: string, value: unknown): string {\n if ((type === \"textarea\" || type === \"select\") && valueProp(name)) {\n return \"\";\n }\n\n let attributeName = name;\n let attributeValue = value;\n\n if (valueProp(name)) {\n attributeName = \"value\";\n if (serializableAttributeValue(value)) attributeValue = String(value);\n } else if (name === \"defaultChecked\") {\n attributeName = \"checked\";\n attributeValue = value === true ? true : null;\n } else if (type === \"option\" && name === \"selected\") {\n attributeValue = value === true ? true : null;\n }\n\n if (emptyValue(attributeValue)) return \"\";\n\n validateAttributeName(attributeName);\n if (attributeValue === true) return ` ${attributeName}`;\n if (serializableAttributeValue(attributeValue)) {\n return serializeAttribute(attributeName, String(attributeValue));\n }\n\n throw new Error(`Cannot serialize prop \"${name}\" to HTML.`);\n}\n\nfunction optionSelected(value: unknown, selectProps: Props): boolean {\n const selectValue =\n selectProps.value !== undefined\n ? selectProps.value\n : selectProps.defaultValue;\n if (emptyValue(selectValue)) return false;\n\n const optionValue = formString(value);\n if (optionValue === null) return false;\n\n return selectedValueSet(selectValue).has(optionValue);\n}\n\nfunction optionValue(props: Props): string | null {\n return props.value === undefined\n ? optionTextValue(props.children)\n : formString(props.value);\n}\n\nfunction optionTextValue(node: unknown): string | null {\n if (typeof node === \"string\" || typeof node === \"number\") {\n return String(node);\n }\n if (Array.isArray(node)) {\n let text = \"\";\n for (const child of node) {\n const childText = optionTextValue(child);\n if (childText === null) return null;\n text += childText;\n }\n return text;\n }\n return null;\n}\n\nfunction formString(value: unknown): string | null {\n if (emptyValue(value)) return null;\n if (serializableAttributeValue(value)) return String(value);\n return null;\n}\n\nfunction selectedValueSet(value: unknown): Set<string> {\n return new Set(Array.isArray(value) ? value.map(String) : [String(value)]);\n}\n\nfunction serializableAttributeValue(value: unknown): boolean {\n return (\n value === true ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\"\n );\n}\n\nfunction emptyValue(value: unknown): boolean {\n return value === null || value === undefined || value === false;\n}\n\nfunction emptyChild(value: unknown): boolean {\n return value === null || value === undefined || typeof value === \"boolean\";\n}\n\nfunction serializeAttribute(name: string, value: string): string {\n return ` ${name}=\"${escapeAttribute(value)}\"`;\n}\n\nfunction serializeStyle(value: unknown): string {\n if (emptyValue(value)) return \"\";\n if (typeof value !== \"object\" || value === null) {\n throw new Error(\"The style prop must be an object during server render.\");\n }\n\n let serialized = \"\";\n for (const [name, item] of Object.entries(value)) {\n if (emptyValue(item)) continue;\n if (\n typeof item !== \"string\" &&\n typeof item !== \"number\" &&\n typeof item !== \"bigint\"\n ) {\n throw new Error(`Cannot serialize style property \"${name}\" to HTML.`);\n }\n\n if (serialized !== \"\") serialized += \";\";\n serialized += `${styleName(name)}:${String(item)}`;\n }\n\n return serialized;\n}\n\nfunction reservedProp(name: string): boolean {\n return (\n name === \"children\" ||\n name === \"key\" ||\n name === \"mix\" ||\n name === \"bind\" ||\n name === \"suppressHydrationWarning\" ||\n name === \"unsafeHTML\" ||\n /^on[A-Z]/.test(name)\n );\n}\n\nfunction valueProp(name: string): boolean {\n return name === \"value\" || name === \"defaultValue\";\n}\n\nfunction styleName(name: string): string {\n if (name.startsWith(\"--\")) return name;\n return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n\nfunction validateTagName(name: string): void {\n if (!/^[A-Za-z][A-Za-z0-9:._-]*$/.test(name)) {\n throw new Error(`Invalid HTML tag name \"${name}\".`);\n }\n}\n\nfunction validateAttributeName(name: string): void {\n if (/[\\s\"'<>/=]/.test(name)) {\n throw new Error(`Invalid HTML attribute name \"${name}\".`);\n }\n}\n","import type { FigAssetResource, PreloadResource } from \"@bgub/fig\";\nimport type {\n ServerPreloadHeaderOptions,\n ServerPreloadHeaderResource,\n} from \"./types.ts\";\n\ntype DeliveryResource = Exclude<FigAssetResource, { kind: \"meta\" | \"title\" }>;\n\nexport interface PreloadHeaderEntry {\n readonly resource: ServerPreloadHeaderResource;\n readonly value: string;\n}\n\nconst DEFAULT_LENGTH = 2_000;\nconst HEX_ESCAPE = /^[0-9A-Fa-f]{2}$/;\nconst PARAMETER_TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst URI_REFERENCE_PUNCTUATION = \"-._~:/?#[]@!$&'()*+,;=\";\n\nexport function createPreloadHeaderEntries(\n resources: Iterable<DeliveryResource>,\n isEarlyImage?: (resource: PreloadResource) => boolean,\n): PreloadHeaderEntry[] {\n const preconnects: PreloadHeaderEntry[] = [];\n const criticalPreloads: PreloadHeaderEntry[] = [];\n const stylesheets: PreloadHeaderEntry[] = [];\n const remaining: PreloadHeaderEntry[] = [];\n\n for (const resource of resources) {\n if (!isServerPreloadHeaderResource(resource)) continue;\n const value = preloadHeaderValue(resource);\n if (value === null) continue;\n const entry = { resource, value };\n\n if (resource.kind === \"preconnect\") {\n preconnects.push(entry);\n } else if (\n resource.kind === \"font\" ||\n (resource.kind === \"preload\" &&\n (resource.as === \"font\" ||\n (resource.as === \"image\" &&\n (resource.fetchpriority === \"high\" ||\n isEarlyImage?.(resource) === true))))\n ) {\n criticalPreloads.push(entry);\n } else if (resource.kind === \"stylesheet\") {\n stylesheets.push(entry);\n } else {\n remaining.push(entry);\n }\n }\n\n return [...preconnects, ...criticalPreloads, ...stylesheets, ...remaining];\n}\n\nexport function formatPreloadHeader(\n entries: readonly PreloadHeaderEntry[],\n options: ServerPreloadHeaderOptions = {},\n): string | undefined {\n const maxLength = normalizedLength(options.maxLength);\n if (maxLength === 0) return undefined;\n\n const seen = new Set<string>();\n const values: string[] = [];\n let length = 0;\n\n for (const entry of entries) {\n if (options.filter !== undefined && !options.filter(entry.resource)) {\n continue;\n }\n if (seen.has(entry.value)) continue;\n\n const addedLength = entry.value.length + (values.length === 0 ? 0 : 2);\n if (length + addedLength > maxLength) continue;\n\n seen.add(entry.value);\n values.push(entry.value);\n length += addedLength;\n }\n\n return values.length === 0 ? undefined : values.join(\", \");\n}\n\nfunction preloadHeaderValue(\n resource: ServerPreloadHeaderResource,\n): string | null {\n switch (resource.kind) {\n case \"stylesheet\":\n return serializeLink(resource.href, [\n [\"rel\", \"preload\"],\n [\"as\", \"style\"],\n [\"crossorigin\", resource.crossorigin],\n [\"media\", resource.media],\n ]);\n case \"preload\":\n return serializeLink(resource.href, [\n [\"rel\", \"preload\"],\n [\"as\", resource.as],\n [\"crossorigin\", resource.crossorigin],\n [\"type\", resource.type],\n [\"fetchpriority\", resource.fetchpriority],\n [\"referrerpolicy\", resource.referrerpolicy],\n ]);\n case \"modulepreload\":\n return serializeLink(resource.href, [\n [\"rel\", \"modulepreload\"],\n [\"as\", \"script\"],\n [\"crossorigin\", resource.crossorigin],\n [\"fetchpriority\", resource.fetchpriority],\n ]);\n case \"font\":\n return serializeLink(resource.href, [\n [\"rel\", \"preload\"],\n [\"as\", \"font\"],\n [\"crossorigin\", resource.crossorigin ?? \"anonymous\"],\n [\"type\", resource.type],\n [\"fetchpriority\", resource.fetchpriority],\n ]);\n case \"preconnect\":\n return serializeLink(resource.href, [\n [\"rel\", \"preconnect\"],\n [\"crossorigin\", resource.crossorigin],\n ]);\n }\n}\n\nfunction isServerPreloadHeaderResource(\n resource: DeliveryResource,\n): resource is ServerPreloadHeaderResource {\n if (resource.kind === \"script\") return false;\n return (\n resource.kind !== \"preload\" ||\n (resource.href !== undefined &&\n (resource.as !== \"image\" || !resource.imagesrcset))\n );\n}\n\nfunction serializeLink(\n target: string,\n parameters: ReadonlyArray<readonly [name: string, value?: string]>,\n): string | null {\n const encodedTarget = encodeLinkTarget(target);\n if (encodedTarget === null) return null;\n\n const parts = [`<${encodedTarget}>`];\n for (const [name, value] of parameters) {\n if (value === undefined) continue;\n const parameter = serializeParameter(name, value);\n if (parameter === null) return null;\n parts.push(parameter);\n }\n return parts.join(\"; \");\n}\n\nfunction serializeParameter(name: string, value: string): string | null {\n if (value === \"\") return name;\n if (hasInvalidParameterCharacter(value)) return null;\n if (PARAMETER_TOKEN.test(value)) return `${name}=${value}`;\n return `${name}=\"${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"')}\"`;\n}\n\nfunction encodeLinkTarget(value: string): string | null {\n if (value === \"\") return null;\n let encoded = \"\";\n\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code <= 0x20 || code === 0x7f) return null;\n\n const character = value[index];\n if (\n character === \"%\" &&\n HEX_ESCAPE.test(value.slice(index + 1, index + 3))\n ) {\n encoded += value.slice(index, index + 3);\n index += 2;\n continue;\n }\n if (\n (code >= 0x30 && code <= 0x39) ||\n (code >= 0x41 && code <= 0x5a) ||\n (code >= 0x61 && code <= 0x7a) ||\n URI_REFERENCE_PUNCTUATION.includes(character)\n ) {\n encoded += character;\n continue;\n }\n\n const codePoint = value.codePointAt(index);\n if (codePoint === undefined) return null;\n const symbol = String.fromCodePoint(codePoint);\n if (symbol.length === 2) index += 1;\n try {\n encoded += encodeURIComponent(symbol);\n } catch {\n return null;\n }\n }\n return encoded;\n}\n\nfunction hasInvalidParameterCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code < 0x20 || code === 0x7f || code > 0xff) return true;\n }\n return false;\n}\n\nfunction normalizedLength(value: number | undefined): number {\n if (value === undefined || Number.isNaN(value)) return DEFAULT_LENGTH;\n return Math.max(0, Math.floor(value));\n}\n","import {\n type FigAssetResource,\n type PreloadResource,\n type Props,\n} from \"@bgub/fig\";\nimport {\n assetResourceHostAttributes,\n assetResourceKey,\n HYDRATION_SKIP_ATTRIBUTE,\n} from \"@bgub/fig/internal\";\nimport { writeElementEnd, writeElementStart, writeText } from \"./html.ts\";\nimport {\n createPreloadHeaderEntries,\n type PreloadHeaderEntry,\n} from \"./preload-header.ts\";\nimport { STREAMED_METADATA_ATTRIBUTE } from \"./shared.ts\";\n\nexport type MetadataSnapshotEntry =\n | readonly [key: string, kind: \"title\", value: string]\n | readonly [\n key: string,\n kind: \"meta\",\n attributes: ReadonlyArray<readonly [name: string, value: string]>,\n ];\n\ntype MetadataResource = Extract<FigAssetResource, { kind: \"meta\" | \"title\" }>;\ntype DeliveryResource = Exclude<FigAssetResource, MetadataResource>;\n\nexport interface HeadMetadataHtml {\n preamble: string;\n metadata: string;\n}\n\nexport class AssetResourceRegistry {\n private readonly earlyImageKeys = new Set<string>();\n private readonly emittedResources = new Set<string>();\n private readonly deliveryResources = new Map<string, DeliveryResource>();\n private readonly metadataByOwner = new Map<\n object,\n readonly MetadataResource[]\n >();\n private readonly stylesheetIds = new Map<string, string>();\n private nextStylesheetId = 0;\n\n constructor(private readonly identifierPrefix: string) {}\n\n register(resource: FigAssetResource): void {\n if (isMetadataResource(resource)) return;\n this.canonical(resource);\n }\n\n registerAutomaticImage(resource: PreloadResource): void {\n const { key, resource: current } = this.canonical(resource);\n if (\n this.earlyImageKeys.size < 10 ||\n (current.kind === \"preload\" &&\n current.as === \"image\" &&\n current.fetchpriority === \"high\")\n ) {\n this.earlyImageKeys.add(key);\n }\n }\n\n isEarlyImage(resource: PreloadResource): boolean {\n return this.earlyImageKeys.has(assetResourceKey(resource));\n }\n\n activateMetadata(\n owner: object,\n resources: readonly FigAssetResource[],\n ): void {\n const metadata = resources.filter(isMetadataResource);\n if (metadata.length === 0) {\n this.metadataByOwner.delete(owner);\n return;\n }\n // Map.set preserves an existing key's position, so updating an owner does\n // not steal precedence from owners activated later.\n this.metadataByOwner.set(owner, metadata);\n }\n\n releaseMetadata(owner: object): void {\n this.metadataByOwner.delete(owner);\n }\n\n write(resource: FigAssetResource, sink: AssetSink): string | null {\n if (isMetadataResource(resource)) return null;\n\n const { key, resource: current } = this.canonical(resource);\n const id = this.revealBlockerId(key, current);\n\n if (this.emittedResources.has(key)) return id;\n\n this.emittedResources.add(key);\n writeAssetTag(sink, current, id);\n return id;\n }\n\n headHtml(nonce?: string, streamMetadata = false): string {\n const { preamble, metadata } = this.headMetadataHtml(nonce, streamMetadata);\n return preamble + metadata;\n }\n\n headMetadataHtml(nonce?: string, streamMetadata = false): HeadMetadataHtml {\n const buckets: Record<MetadataPhase, string[]> = {\n charset: [],\n parser: [],\n viewport: [],\n metadata: [],\n };\n\n for (const resource of this.visibleMetadata().values()) {\n const bucket = buckets[metadataPhase(resource)];\n writeAssetTag(\n { nonce, streamMetadata, write: (chunk) => bucket.push(chunk) },\n resource,\n null,\n );\n }\n\n return {\n preamble: [\n ...buckets.charset,\n ...buckets.parser,\n ...buckets.viewport,\n ].join(\"\"),\n metadata: buckets.metadata.join(\"\"),\n };\n }\n\n metadataSnapshot(): MetadataSnapshotEntry[] {\n const snapshot: MetadataSnapshotEntry[] = [];\n for (const [key, resource] of this.visibleMetadata()) {\n if (resource.kind === \"title\") {\n snapshot.push([key, resource.kind, resource.value]);\n } else {\n snapshot.push([key, resource.kind, metadataAttributes(resource)]);\n }\n }\n return snapshot;\n }\n\n preloadHeaderEntries(): PreloadHeaderEntry[] {\n return createPreloadHeaderEntries(\n this.deliveryResources.values(),\n (resource) => this.isEarlyImage(resource),\n );\n }\n\n private visibleMetadata(): Map<string, MetadataResource> {\n const visible = new Map<string, MetadataResource>();\n for (const metadata of this.metadataByOwner.values()) {\n for (const resource of metadata) {\n visible.set(assetResourceKey(resource), resource);\n }\n }\n return visible;\n }\n\n private canonical(resource: DeliveryResource): {\n key: string;\n resource: DeliveryResource;\n } {\n const key = assetResourceKey(resource);\n const current = this.deliveryResources.get(key);\n\n if (current !== undefined) {\n if (assetSignature(current) !== assetSignature(resource)) {\n const promoted = promoteCompatibleImagePreload(current, resource);\n if (promoted === null) {\n throw new AssetResourceConflictError(key, current, resource);\n }\n this.deliveryResources.set(key, promoted);\n return { key, resource: promoted };\n }\n\n return { key, resource: current };\n }\n\n this.deliveryResources.set(key, resource);\n return { key, resource };\n }\n\n private revealBlockerId(\n key: string,\n resource: FigAssetResource,\n ): string | null {\n if (resource.kind !== \"stylesheet\") return null;\n if (resource.blocking === \"none\") return null;\n\n return this.stylesheetIdFor(key);\n }\n\n private stylesheetIdFor(key: string): string {\n const current = this.stylesheetIds.get(key);\n if (current !== undefined) return current;\n\n const id =\n this.identifierPrefix === \"\"\n ? `r-${this.nextStylesheetId}`\n : `${this.identifierPrefix}-r-${this.nextStylesheetId}`;\n this.nextStylesheetId += 1;\n this.stylesheetIds.set(key, id);\n return id;\n }\n}\n\nexport class AssetResourceConflictError extends Error {\n constructor(\n key: string,\n current: FigAssetResource,\n incoming: FigAssetResource,\n ) {\n super(\n `Conflicting Fig resource for key \"${key}\". Existing: ${JSON.stringify(\n current,\n )}. Incoming: ${JSON.stringify(incoming)}.`,\n );\n }\n}\n\ninterface AssetSink {\n nonce?: string;\n streamMetadata?: boolean;\n write(chunk: string): void;\n}\n\nfunction writeAssetTag(\n sink: AssetSink,\n resource: FigAssetResource,\n id: string | null,\n): void {\n switch (resource.kind) {\n case \"title\":\n writeElementStart(\n \"title\",\n {\n [HYDRATION_SKIP_ATTRIBUTE]: true,\n [STREAMED_METADATA_ATTRIBUTE]: sink.streamMetadata\n ? assetResourceKey(resource)\n : undefined,\n },\n sink,\n );\n writeText(resource.value, sink);\n writeElementEnd(\"title\", sink);\n return;\n case \"meta\":\n writeElementStart(\n \"meta\",\n {\n charset: resource.charset,\n name: resource.name,\n property: resource.property,\n \"http-equiv\": resource[\"http-equiv\"],\n content: resource.content,\n [HYDRATION_SKIP_ATTRIBUTE]: true,\n [STREAMED_METADATA_ATTRIBUTE]: sink.streamMetadata\n ? assetResourceKey(resource)\n : undefined,\n \"data-fig-resource-key\": resource.key,\n },\n sink,\n );\n return;\n default: {\n // The attribute set is shared with the client's head insertion; only\n // the server-side reveal-blocker id and nonce are appended here.\n const props: Props = {\n [HYDRATION_SKIP_ATTRIBUTE]: true,\n ...Object.fromEntries(assetResourceHostAttributes(resource)),\n };\n if (resource.kind === \"stylesheet\" && id !== null) props.id = id;\n\n const tag = resource.kind === \"script\" ? \"script\" : \"link\";\n writeElementStart(tag, withNonce(sink, props), sink);\n if (tag === \"script\") writeElementEnd(\"script\", sink);\n }\n }\n}\n\nfunction isMetadataResource(\n resource: FigAssetResource,\n): resource is MetadataResource {\n return resource.kind === \"title\" || resource.kind === \"meta\";\n}\n\ntype MetadataPhase = \"charset\" | \"parser\" | \"viewport\" | \"metadata\";\n\nfunction metadataPhase(resource: MetadataResource): MetadataPhase {\n if (resource.kind === \"title\") return \"metadata\";\n if (resource.charset !== undefined) return \"charset\";\n if (\n normalizedMetadataName(resource[\"http-equiv\"]) === \"content-security-policy\"\n ) {\n return \"parser\";\n }\n if (normalizedMetadataName(resource.name) === \"viewport\") return \"viewport\";\n return \"metadata\";\n}\n\nfunction normalizedMetadataName(value: string | undefined): string | undefined {\n return value?.trim().toLowerCase();\n}\n\nfunction metadataAttributes(\n resource: Extract<FigAssetResource, { kind: \"meta\" }>,\n): Array<readonly [string, string]> {\n const attributes: Array<readonly [string, string | undefined]> = [\n [\"charset\", resource.charset],\n [\"name\", resource.name],\n [\"property\", resource.property],\n [\"http-equiv\", resource[\"http-equiv\"]],\n [\"content\", resource.content],\n [\"data-fig-resource-key\", resource.key],\n ];\n return attributes.filter(\n (entry): entry is readonly [string, string] => entry[1] !== undefined,\n );\n}\n\nfunction withNonce(sink: AssetSink, props: Props): Props {\n return sink.nonce === undefined ? props : { ...props, nonce: sink.nonce };\n}\n\nfunction assetSignature(resource: FigAssetResource): string {\n switch (resource.kind) {\n case \"stylesheet\":\n return signature(\n resource.kind,\n resource.href,\n resource.media ?? \"\",\n resource.precedence ?? \"\",\n resource.crossorigin ?? \"\",\n resource.blocking ?? \"reveal\",\n );\n case \"preload\": {\n const imagesrcset =\n resource.as === \"image\" ? resource.imagesrcset || undefined : undefined;\n return signature(\n resource.kind,\n imagesrcset === undefined ? (resource.href ?? \"\") : \"\",\n resource.as,\n resource.type ?? \"\",\n resource.crossorigin ?? \"\",\n resource.fetchpriority ?? \"\",\n imagesrcset ?? \"\",\n imagesrcset === undefined ? \"\" : (resource.imagesizes ?? \"\"),\n resource.referrerpolicy ?? \"\",\n );\n }\n case \"modulepreload\":\n return signature(\n resource.kind,\n resource.href,\n resource.crossorigin ?? \"\",\n resource.fetchpriority ?? \"\",\n );\n case \"font\":\n // Mirror the preload-as-font signature: a font shares the preload-font key\n // space (see assetResourceKey), so an equivalent preload(href, \"font\") must\n // produce the same signature and dedupe rather than raising a conflict.\n return signature(\n \"preload\",\n resource.href,\n \"font\",\n resource.type,\n resource.crossorigin ?? \"anonymous\",\n resource.fetchpriority ?? \"\",\n \"\",\n \"\",\n \"\",\n );\n case \"preconnect\":\n return signature(\n resource.kind,\n resource.href,\n resource.crossorigin ?? \"\",\n );\n case \"script\":\n return signature(\n resource.kind,\n resource.src,\n resource.module === true,\n resource.async !== false,\n resource.defer === true,\n resource.crossorigin ?? \"\",\n );\n case \"title\":\n return signature(resource.kind, resource.value);\n case \"meta\":\n return signature(\n resource.kind,\n resource.charset ?? \"\",\n resource.name ?? \"\",\n resource.property ?? \"\",\n resource[\"http-equiv\"] ?? \"\",\n resource.content ?? \"\",\n );\n }\n\n return unsupportedAssetResource(resource);\n}\n\nfunction promoteCompatibleImagePreload(\n current: DeliveryResource,\n incoming: DeliveryResource,\n): DeliveryResource | null {\n if (\n current.kind !== \"preload\" ||\n incoming.kind !== \"preload\" ||\n current.as !== \"image\" ||\n incoming.as !== \"image\" ||\n assetSignature({\n ...current,\n fetchpriority: incoming.fetchpriority,\n }) !== assetSignature(incoming)\n ) {\n return null;\n }\n\n const currentPriority =\n current.fetchpriority === \"auto\" ? undefined : current.fetchpriority;\n const incomingPriority =\n incoming.fetchpriority === \"auto\" ? undefined : incoming.fetchpriority;\n if (currentPriority === incomingPriority) return current;\n if (currentPriority === \"low\" || incomingPriority === \"low\") return null;\n return currentPriority === \"high\"\n ? current\n : { ...current, fetchpriority: \"high\" };\n}\n\nfunction unsupportedAssetResource(resource: FigAssetResource): never {\n throw new Error(`Unsupported asset resource kind: ${resource.kind}`);\n}\n\nfunction signature(...values: Array<string | boolean>): string {\n return JSON.stringify(values);\n}\n","import {\n EARLY_EVENT_HANDLER_PROPERTY,\n EARLY_EVENT_QUEUE_PROPERTY,\n HYDRATION_SKIP_ATTRIBUTE,\n REPLAYABLE_EVENT_TYPES,\n SUSPENSE_CLIENT_MARKER,\n SUSPENSE_COMPLETED_MARKER,\n SUSPENSE_END_MARKER,\n SUSPENSE_MARKER_PREFIX,\n VIEW_TRANSITION_CLASS_ATTRIBUTE,\n VIEW_TRANSITION_NAME_ATTRIBUTE,\n VIEW_TRANSITION_PENDING_PROPERTY,\n VIEW_TRANSITION_TIMEOUT_MS,\n} from \"@bgub/fig/internal\";\nimport { escapeAttribute, escapeScriptJson } from \"./escaping.ts\";\nimport { nonceAttribute, STREAMED_METADATA_ATTRIBUTE } from \"./shared.ts\";\n\ninterface ProtocolRequest {\n identifierPrefix: string;\n nonce?: string;\n runtimeName: string;\n runtimeWritten: boolean;\n}\n\ntype WriteChunk = (chunk: string) => void;\ntype IdentifierRequest = Pick<ProtocolRequest, \"identifierPrefix\">;\n\n// Runtime ops, in order: r=resource gate, s=fill partial segment, c=reveal\n// boundary, x=client-render boundary, ac/ax=the Activity-aware variants. The\n// boundary markers sit in the activity's inert <template>, whose `.content`\n// DocumentFragment is unreachable by getElementById, so Activity-aware ops first\n// search that fragment and then fall back to the light DOM if the activity has\n// already revealed and unpacked.\nexport function serverRuntimeCodeFor(runtimeName: string): string {\n return `globalThis[${jsString(runtimeName)}]??={r(a,f){let n=0,d=()=>{--n||f()};for(let i of a){let e=document.getElementById(i);if(e&&e.tagName==='LINK'&&e.rel==='stylesheet'&&!e.sheet){n++;e.addEventListener('load',d,{once:true});e.addEventListener('error',d,{once:true})}}n||f()},q(e,a){if(e&&e.nodeType===1){if(e.hasAttribute&&e.hasAttribute('${VIEW_TRANSITION_NAME_ATTRIBUTE}'))a.push([e,e.getAttribute('${VIEW_TRANSITION_NAME_ATTRIBUTE}'),e.getAttribute('${VIEW_TRANSITION_CLASS_ATTRIBUTE}')]);if(e.querySelectorAll)for(let x of e.querySelectorAll('[${VIEW_TRANSITION_NAME_ATTRIBUTE}]'))a.push([x,x.getAttribute('${VIEW_TRANSITION_NAME_ATTRIBUTE}'),x.getAttribute('${VIEW_TRANSITION_CLASS_ATTRIBUTE}')])}},g(r){let a=[];this.q(r,a);return a},h(b){let a=[],d=0;for(let e=b;e;){if(e.nodeType===8){if(e.data.indexOf('${SUSPENSE_MARKER_PREFIX}')===0)d++;else if(e.data==='${SUSPENSE_END_MARKER}'){if(d===0)break;d--}}else this.q(e,a);e=e.nextSibling}return a},a(l){for(let x of l){let e=x[0],s=e.style;x[3]=s.viewTransitionName;x[4]=s.viewTransitionClass;s.viewTransitionName=x[1];if(x[2])s.viewTransitionClass=x[2]}},u(l){for(let x of l){let e=x[0],s=e.style;s.viewTransitionName=x[3]||'';s.viewTransitionClass=x[4]||'';!(e.getAttribute&&e.getAttribute('style'))&&e.removeAttribute&&e.removeAttribute('style')}},z(l){for(let f of l)f()},j(t,r){let p=t&&(t.ready||t.finished);p&&p.then?p.then(r,()=>{let f=t&&t.finished;f&&f.then?f.then(r,r):r()}):r()},v(b,s,f){let o=this.h(b),n=this.g(s);if(!o.length&&!n.length){f();return}let d=document,w=d.startViewTransition;if(typeof w!='function'){f();return}let p=d.${VIEW_TRANSITION_PENDING_PROPERTY},pw=p&&(p.finished||p.ready);if(pw&&pw.then){let q=0,i,g=()=>{if(q)return;q=1;clearTimeout(i);d.${VIEW_TRANSITION_PENDING_PROPERTY}===p&&(d.${VIEW_TRANSITION_PENDING_PROPERTY}=null);this.v(b,s,f)};i=setTimeout(g,${VIEW_TRANSITION_TIMEOUT_MS});pw.then(g,g);return}this.a(o);let m=0,l=[],r=()=>{this.u(o);this.u(n);this.z(l)};try{let t=w.call(d,()=>{m=1;f(l);this.a(n)});if(t){d.${VIEW_TRANSITION_PENDING_PROPERTY}=t;let c=()=>{d.${VIEW_TRANSITION_PENDING_PROPERTY}===t&&(d.${VIEW_TRANSITION_PENDING_PROPERTY}=null)},cw=t.finished||t.ready;cw&&cw.then?cw.then(c,c):c()}this.j(t,r)}catch(e){r();if(m)throw e;f()}},m(a){let h=document.head,e=new Map;for(let n of h.querySelectorAll('[${STREAMED_METADATA_ATTRIBUTE}]'))e.set(n.getAttribute('${STREAMED_METADATA_ATTRIBUTE}'),n);for(let d of a){let k=d[0],t=d[1],v=d[2],n=e.get(k);if(!n||n.tagName.toLowerCase()!==t){n&&n.remove();n=document.createElement(t);n.setAttribute('${STREAMED_METADATA_ATTRIBUTE}',k);n.setAttribute('${HYDRATION_SKIP_ATTRIBUTE}','');h.appendChild(n)}e.delete(k);if(t==='title')n.textContent=v;else{for(let x of Array.from(n.attributes))if(x.name!=='${STREAMED_METADATA_ATTRIBUTE}'&&x.name!=='${HYDRATION_SKIP_ATTRIBUTE}')n.removeAttribute(x.name);for(let x of v)n.setAttribute(x[0],x[1])}}for(let n of e.values())n.remove()},s(p,s){p=document.getElementById(p);s=document.getElementById(s);if(!p||!s)return;this.v(p,s,()=>{while(s.firstChild)p.parentNode.insertBefore(s.firstChild,p);p.remove();s.remove()})},f(r,i){if(!r)return null;if(r.id===i)return r;for(let e of r.querySelectorAll?r.querySelectorAll('[id]'):[])if(e.id===i)return e;return null},b(t,b){let e=document.getElementById(t),r=e&&(e.content||e);return this.f(r,b)||document.getElementById(b)},c(b,s,m){let x=document.getElementById(b),y=document.getElementById(s);this.v(x,y,r=>this.o(x,y,r,m))},o(b,s,l,m){if(!b||!s)return;let a=b.previousSibling||b,p=a.parentNode,c=s.content||s;if(!p)return;let r=a.nodeType===8&&a.__figRetry;if(!r&&m)this.m(m);while(c.firstChild)p.insertBefore(c.firstChild,b);for(let e=b,d=0;e;){if(e.nodeType===8){if(e.data.indexOf('${SUSPENSE_MARKER_PREFIX}')===0)d++;else if(e.data==='${SUSPENSE_END_MARKER}'){if(d===0)break;d--}}let x=e.nextSibling;e.remove();e=x}s.remove();if(a.nodeType===8){a.data='${SUSPENSE_COMPLETED_MARKER}';if(r){if(l)l.push(r);else r()}}},x(b,d,m){this.y(document.getElementById(b),d,m)},y(b,d,m){if(!b)return;let s=b.previousSibling;if(s&&s.nodeType===8){s.data='${SUSPENSE_CLIENT_MARKER}';if(d)b.dataset.dgst=d;if(m)b.dataset.msg=m;s.__figRetry&&s.__figRetry()}},ac(t,b,s,m){let x=this.b(t,b),y=document.getElementById(s);this.v(x,y,r=>this.o(x,y,r,m))},ax(t,b,d,m){this.y(this.b(t,b),d,m)}}`;\n}\n\nexport function writeRuntime(\n request: ProtocolRequest,\n write: WriteChunk,\n): void {\n if (request.runtimeWritten) return;\n request.runtimeWritten = true;\n writeScript(request, serverRuntimeCodeFor(request.runtimeName), write);\n}\n\nexport function writeScript(\n request: Pick<ProtocolRequest, \"nonce\">,\n code: string,\n write: WriteChunk,\n): void {\n write(\n `<script ${HYDRATION_SKIP_ATTRIBUTE}=\"\"${nonceAttribute(request.nonce)}>${code}</script>`,\n );\n}\n\n// Queues replayable events that fire before the client bundle executes so\n// hydration can honor a user's first interaction instead of losing it. Sits\n// first in <head> — capture must be live before any content paints. The\n// first hydration root drains the queue and removes these listeners\n// (fig-dom's adoptEarlyEvents); a document without a client bundle just\n// carries a small inert array.\nexport function earlyEventCaptureCode(): string {\n const types = REPLAYABLE_EVENT_TYPES.map((type) => `'${type}'`).join(\",\");\n return `(d=>{if(d.${EARLY_EVENT_QUEUE_PROPERTY})return;let q=d.${EARLY_EVENT_QUEUE_PROPERTY}=[],h=d.${EARLY_EVENT_HANDLER_PROPERTY}=e=>{q.push(e)};for(let t of [${types}])d.addEventListener(t,h,!0)})(document)`;\n}\n\nexport function earlyEventCaptureMarkup(\n request: Pick<ProtocolRequest, \"nonce\">,\n): string {\n return `<script ${HYDRATION_SKIP_ATTRIBUTE}=\"\"${nonceAttribute(request.nonce)}>${earlyEventCaptureCode()}</script>`;\n}\n\nexport function placeholderMarkup(\n request: IdentifierRequest,\n id: number,\n): string {\n return templateMarkup(placeholderId(request, id));\n}\n\nexport function boundaryPlaceholderMarkup(\n request: IdentifierRequest,\n id: number,\n): string {\n return templateMarkup(boundaryId(request, id));\n}\n\nfunction templateMarkup(id: string): string {\n return `<template id=\"${escapeAttribute(id)}\"></template>`;\n}\n\nexport function segmentContainerStartMarkup(\n request: IdentifierRequest,\n id: number,\n): string {\n const escapedId = escapeAttribute(segmentId(request, id));\n return `<div hidden id=\"${escapedId}\">`;\n}\n\nexport function activityId(request: IdentifierRequest, id: number): string {\n return prefixedId(request, \"a\", id);\n}\n\nexport function placeholderId(request: IdentifierRequest, id: number): string {\n return prefixedId(request, \"p\", id);\n}\n\nexport function segmentId(request: IdentifierRequest, id: number): string {\n return prefixedId(request, \"s\", id);\n}\n\nexport function boundaryId(request: IdentifierRequest, id: number): string {\n return prefixedId(request, \"b\", id);\n}\n\nexport function jsString(value: string): string {\n return escapeScriptJson(value);\n}\n\nfunction prefixedId(\n request: IdentifierRequest,\n kind: string,\n id: number,\n): string {\n return request.identifierPrefix === \"\"\n ? `${kind}-${id}`\n : `${request.identifierPrefix}-${kind}-${id}`;\n}\n","import {\n SUSPENSE_CLIENT_MARKER,\n SUSPENSE_COMPLETED_MARKER,\n SUSPENSE_END_MARKER,\n SUSPENSE_PENDING_PREFIX,\n} from \"@bgub/fig/internal\";\nimport { escapeAttribute, escapeScriptJson } from \"./escaping.ts\";\nimport {\n boundaryId,\n boundaryPlaceholderMarkup,\n jsString,\n placeholderId,\n placeholderMarkup,\n segmentContainerStartMarkup,\n segmentId,\n writeRuntime as writeProtocolRuntime,\n writeScript as writeProtocolScript,\n} from \"./protocol.ts\";\nimport type { Request, Segment, SuspenseBoundary } from \"./renderer.ts\";\nimport { streamFlowBlocked } from \"./shared.ts\";\n\nexport const documentHeadMarker = Symbol(\"fig.document-head\");\nexport const leadingNewlineStartMarker = Symbol(\"fig.leading-newline-start\");\nexport const leadingNewlineEndMarker = Symbol(\"fig.leading-newline-end\");\n\nexport type SegmentChunk =\n | string\n | typeof documentHeadMarker\n | typeof leadingNewlineStartMarker\n | typeof leadingNewlineEndMarker\n | { value: string };\n\nconst RUNTIME_REF = \"__figSSR\";\nconst textEncoder = new TextEncoder();\n\nexport function flushCompletedQueues(request: Request): void {\n if (request.controller === null || request.status === \"closed\") return;\n if (request.pendingRootTasks > 0) return;\n if (request.prerender && request.pendingTasks > 0) return;\n if (request.flushing) return;\n\n request.flushing = true;\n try {\n sealHead(request);\n\n // The shell flushes ungated: the queue is empty before the first enqueue,\n // and shell latency outranks flow control.\n if (request.completedRootSegment !== null) {\n flushSegment(request, request.completedRootSegment);\n request.completedRootSegment = null;\n flushWriteBuffer(request);\n }\n\n // Stop at the first blocked drain; the stream's pull handler re-enters\n // here when the consumer makes room.\n if (\n !drainBoundaryQueue(\n request,\n request.clientRenderedBoundaries,\n flushClientRenderedBoundary,\n ) &&\n !drainBoundaryQueue(\n request,\n request.completedBoundaries,\n flushCompletedBoundary,\n )\n ) {\n drainBoundaryQueue(\n request,\n request.partialBoundaries,\n flushPartialBoundary,\n );\n }\n\n flushWriteBuffer(request);\n } finally {\n request.flushing = false;\n }\n\n // Deliberately not conditioned on flow: close() only marks the end of the\n // queue, so a full queue with nothing left to write still closes here.\n if (\n request.pendingTasks === 0 &&\n request.completedBoundaries.size === 0 &&\n request.clientRenderedBoundaries.size === 0 &&\n request.partialBoundaries.size === 0\n ) {\n request.cleanupAbortListener();\n request.status = \"closed\";\n request.dataStore.dispose();\n request.controller.close();\n }\n}\n\nexport function sealHead(request: Request): void {\n if (request.headSnapshot !== null) return;\n\n activateVisibleMetadata(request, request.rootSegment);\n const metadata = request.assetRegistry.headMetadataHtml(\n request.nonce,\n !request.prerender && request.pendingTasks > 0,\n );\n request.headSnapshot = {\n ...metadata,\n preloadHeaderEntries: request.assetRegistry.preloadHeaderEntries(),\n };\n request.headReady.resolve(metadata.preamble + metadata.metadata);\n}\n\nfunction flushSegment(request: Request, segment: Segment): void {\n if (segment.status === \"flushed\") return;\n if (segment.boundary !== null) {\n flushSuspenseBoundary(request, segment, segment.boundary);\n return;\n }\n\n flushSubtree(request, segment);\n}\n\nfunction flushSubtree(request: Request, segment: Segment): void {\n segment.parentFlushed = true;\n\n if (segment.status === \"pending\" || segment.status === \"rendering\") {\n request.write(\n placeholderMarkup(request, ensureSegmentId(request, segment)),\n );\n return;\n }\n\n if (segment.status === \"flushed\") return;\n\n segment.status = \"flushed\";\n if (request.document === null || segment !== request.rootSegment) {\n flushSegmentAssets(request, segment);\n }\n let chunkIndex = 0;\n\n for (const child of segment.children) {\n for (; chunkIndex < child.index; chunkIndex += 1) {\n writeChunk(request, segment.chunks[chunkIndex], segment);\n }\n flushSegment(request, child);\n }\n\n for (; chunkIndex < segment.chunks.length; chunkIndex += 1) {\n writeChunk(request, segment.chunks[chunkIndex], segment);\n }\n}\n\nfunction flushSuspenseBoundary(\n request: Request,\n segment: Segment,\n boundary: SuspenseBoundary,\n): void {\n boundary.parentFlushed = true;\n\n if (boundary.status === \"completed\") {\n request.write(`<!--${SUSPENSE_COMPLETED_MARKER}-->`);\n flushBoundaryContent(request, boundary);\n request.write(`<!--${SUSPENSE_END_MARKER}-->`);\n segment.status = \"flushed\";\n return;\n }\n\n if (request.prerender && boundary.status === \"client-rendered\") {\n // Static prerender does not hoist assets discovered only in failed content:\n // the retry path loads them on demand, and pure-static consumers see only\n // the fallback.\n request.write(`<!--${SUSPENSE_CLIENT_MARKER}-->`);\n request.write(clientRenderedBoundaryPlaceholderMarkup(request, boundary));\n flushSubtree(request, segment);\n request.write(`<!--${SUSPENSE_END_MARKER}-->`);\n return;\n }\n\n const boundaryIdValue = ensureBoundaryId(request, boundary);\n flushSegmentAssets(request, boundary.contentSegment);\n request.write(`<!--${SUSPENSE_PENDING_PREFIX}${boundaryIdValue}-->`);\n request.write(boundaryPlaceholderMarkup(request, boundaryIdValue));\n flushSubtree(request, segment);\n request.write(`<!--${SUSPENSE_END_MARKER}-->`);\n\n if (boundary.status === \"client-rendered\") {\n request.clientRenderedBoundaries.add(boundary);\n } else if (boundary.completedSegments.length > 0) {\n request.partialBoundaries.add(boundary);\n }\n}\n\nfunction flushBoundaryContent(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n for (const segment of boundary.completedSegments) {\n flushSegment(request, segment);\n }\n boundary.completedSegments = [];\n}\n\nfunction clientRenderedBoundaryPlaceholderMarkup(\n request: Request,\n boundary: SuspenseBoundary,\n): string {\n const id = escapeAttribute(\n boundaryId(request, ensureBoundaryId(request, boundary)),\n );\n const digest = boundary.error?.digest;\n const message = boundary.error?.message;\n const digestAttr =\n digest === undefined || digest === \"\"\n ? \"\"\n : ` data-dgst=\"${escapeAttribute(digest)}\"`;\n const messageAttr =\n message === undefined || message === \"\"\n ? \"\"\n : ` data-msg=\"${escapeAttribute(message)}\"`;\n\n return `<template id=\"${id}\"${digestAttr}${messageAttr}></template>`;\n}\n\nfunction flushCompletedBoundary(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n flushPartialBoundary(request, boundary);\n writeBoundaryRevealScript(request, boundary);\n}\n\nfunction flushPartialBoundary(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n for (const segment of boundary.completedSegments) {\n flushBoundarySegment(request, boundary, segment);\n }\n boundary.completedSegments = [];\n}\n\nfunction flushBoundarySegment(\n request: Request,\n boundary: SuspenseBoundary,\n segment: Segment,\n): void {\n ensureBoundaryId(request, boundary);\n const blockingIds = flushSegmentContainer(request, segment);\n\n if (segment !== boundary.contentSegment) {\n writeSegmentRevealScript(request, segment, blockingIds);\n }\n}\n\nfunction writeSegmentRevealScript(\n request: Request,\n segment: Segment,\n blockingIds: string[],\n): void {\n const id = ensureSegmentId(request, segment);\n writeRuntime(request);\n // Partial segments — including those of a hidden-Activity boundary — stage and\n // fill in light-DOM hidden divs; only the boundary's final reveal (`ac`) moves\n // the assembled content into the inert activity template.\n writeScript(\n request,\n withAssetGate(\n blockingIds,\n `${RUNTIME_REF}.s(${jsString(placeholderId(request, id))},${jsString(\n segmentId(request, id),\n )})`,\n ),\n );\n}\n\nfunction writeBoundaryRevealScript(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n const blockingIds = flushSegmentAssets(request, boundary.contentSegment);\n const metadata = switchBoundaryMetadata(request, boundary);\n const metadataArgument = metadata === null ? \"\" : `,${metadata}`;\n writeRuntime(request);\n const boundaryRef = jsString(\n boundaryId(request, ensureBoundaryId(request, boundary)),\n );\n const contentRef = jsString(\n segmentId(request, ensureSegmentId(request, boundary.contentSegment)),\n );\n // Inside a hidden Activity the boundary markers live in the activity\n // template's inert content; reveal the completion there with `ac`.\n const call =\n boundary.activityId === null\n ? `${RUNTIME_REF}.c(${boundaryRef},${contentRef}${metadataArgument})`\n : `${RUNTIME_REF}.ac(${jsString(boundary.activityId)},${boundaryRef},${contentRef}${metadataArgument})`;\n writeScript(request, withAssetGate(blockingIds, call));\n}\n\nfunction switchBoundaryMetadata(\n request: Request,\n boundary: SuspenseBoundary,\n): string | null {\n // A nested boundary may complete while an ancestor's primary content is\n // still staged. Its segment fill is useful, but its metadata is not visible;\n // the ancestor reveal traversal will activate the settled branch later.\n if (!boundary.metadataVisible) return null;\n\n const before = escapeScriptJson(request.assetRegistry.metadataSnapshot());\n const fallback = boundary.fallbackSegment;\n if (fallback !== null) {\n request.assetRegistry.releaseMetadata(fallback);\n for (const child of fallback.children) {\n deactivateMetadataTree(request, child);\n }\n }\n activateVisibleMetadata(request, boundary.contentSegment);\n const after = escapeScriptJson(request.assetRegistry.metadataSnapshot());\n return before === after ? null : after;\n}\n\nfunction activateVisibleMetadata(request: Request, segment: Segment): void {\n if (segment.status === \"pending\" || segment.status === \"rendering\") return;\n\n const boundary = segment.boundary;\n if (boundary !== null) {\n boundary.metadataVisible = true;\n if (boundary.status === \"completed\") {\n activateVisibleMetadata(request, boundary.contentSegment);\n return;\n }\n }\n\n request.assetRegistry.activateMetadata(segment, segment.assetResources);\n for (const child of segment.children) {\n activateVisibleMetadata(request, child);\n }\n}\n\nfunction deactivateMetadataTree(request: Request, segment: Segment): void {\n request.assetRegistry.releaseMetadata(segment);\n for (const child of segment.children) deactivateMetadataTree(request, child);\n\n const boundary = segment.boundary;\n if (boundary === null) return;\n boundary.metadataVisible = false;\n deactivateMetadataTree(request, boundary.contentSegment);\n}\n\nfunction flushSegmentContainer(request: Request, segment: Segment): string[] {\n if (segment.status === \"flushed\") return [];\n const blockingIds = flushSegmentAssets(request, segment);\n\n request.write(\n segmentContainerStartMarkup(request, ensureSegmentId(request, segment)),\n );\n flushSegment(request, segment);\n request.write(\"</div>\");\n return blockingIds;\n}\n\nfunction flushSegmentAssets(request: Request, segment: Segment): string[] {\n const blockingIds = new Set<string>();\n collectSegmentAssets(request, segment, blockingIds);\n return [...blockingIds];\n}\n\nfunction collectSegmentAssets(\n request: Request,\n segment: Segment,\n blockingIds: Set<string>,\n): void {\n if (segment.status !== \"pending\" && segment.status !== \"rendering\") {\n flushAssetList(request, segment.assetResources, blockingIds);\n }\n\n for (const child of segment.children) {\n collectSegmentAssets(request, child, blockingIds);\n }\n}\n\nfunction flushAssetList(\n request: Request,\n resources: Segment[\"assetResources\"],\n blockingIds: Set<string>,\n): void {\n for (const resource of resources) {\n const id = request.assetRegistry.write(resource, request);\n if (id !== null) blockingIds.add(id);\n }\n}\n\nfunction withAssetGate(blockingIds: string[], call: string): string {\n if (blockingIds.length === 0) return call;\n return `${RUNTIME_REF}.r([${blockingIds.map(jsString).join(\",\")}],()=>{${call}})`;\n}\n\nfunction flushClientRenderedBoundary(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n if (boundary.id === null) return;\n writeRuntime(request);\n const boundaryRef = jsString(boundaryId(request, boundary.id));\n const digest = jsString(boundary.error?.digest ?? \"\");\n const message = jsString(boundary.error?.message ?? \"\");\n const call =\n boundary.activityId === null\n ? `${RUNTIME_REF}.x(${boundaryRef},${digest},${message})`\n : `${RUNTIME_REF}.ax(${jsString(boundary.activityId)},${boundaryRef},${digest},${message})`;\n writeScript(request, call);\n}\n\n// A boundary deliberately stays in the queue while it flushes so a re-add\n// during its own flush is a no-op (Set semantics), then leaves afterwards.\n// Returns true when the drain stopped because the flow is blocked; blocked\n// boundaries stay queued for the next pull-driven pass. Gating sits between\n// boundaries — never mid-buffer — so every chunk still ends on complete\n// markup.\nfunction drainBoundaryQueue(\n request: Request,\n queue: Set<SuspenseBoundary>,\n flush: (request: Request, boundary: SuspenseBoundary) => void,\n): boolean {\n for (;;) {\n if (streamFlowBlocked(request.controller)) return true;\n const first = queue.values().next();\n if (first.done === true) return false;\n flush(request, first.value);\n queue.delete(first.value);\n // One encoded enqueue per drained boundary: keeps chunk boundaries at\n // meaningful stream points (consumers interleave companion content per\n // chunk) while still coalescing the per-attribute writes within.\n flushWriteBuffer(request);\n }\n}\n\nfunction writeRuntime(request: Request): void {\n writeProtocolRuntime(request, (chunk) => request.write(chunk));\n}\n\n// Classic <script> elements share the page's global lexical environment, so a\n// top-level `let` would redeclare across op scripts and throw; the IIFE keeps\n// a per-script binding that async op callbacks (the stylesheet gate) close\n// over even if a later stream rebinds the runtime name.\nfunction writeScript(request: Request, code: string): void {\n writeProtocolScript(\n request,\n `(__figSSR=>{${code}})(globalThis[${jsString(request.runtimeName)}])`,\n (chunk) => request.write(chunk),\n );\n}\n\nfunction writeChunk(\n request: Request,\n chunk: SegmentChunk,\n segment: Segment,\n): void {\n if (chunk === leadingNewlineStartMarker) {\n request.leadingNewlineStack.push(false);\n return;\n }\n if (chunk === leadingNewlineEndMarker) {\n request.leadingNewlineStack.pop();\n return;\n }\n if (typeof chunk === \"object\") {\n request.write(\n request.leadingNewlineStack.at(-1) === false &&\n chunk.value.startsWith(\"\\n\")\n ? `\\n${chunk.value}`\n : chunk.value,\n );\n return;\n }\n if (chunk !== documentHeadMarker) {\n request.write(chunk);\n return;\n }\n\n if (request.document === null) return;\n\n const metadata =\n request.headSnapshot ??\n request.assetRegistry.headMetadataHtml(request.nonce);\n const [beforeMetadata, afterMetadata] = partitionHeadAssets(\n request,\n segment.assetResources,\n );\n const blockingIds = new Set<string>();\n request.write(metadata.preamble);\n flushAssetList(request, beforeMetadata, blockingIds);\n request.write(metadata.metadata);\n flushAssetList(request, afterMetadata, blockingIds);\n}\n\nfunction partitionHeadAssets(\n request: Request,\n resources: Segment[\"assetResources\"],\n): [\n beforeMetadata: Segment[\"assetResources\"],\n afterMetadata: Segment[\"assetResources\"],\n] {\n const preconnects: Segment[\"assetResources\"] = [];\n const criticalPreloads: Segment[\"assetResources\"] = [];\n const stylesheets: Segment[\"assetResources\"] = [];\n const afterMetadata: Segment[\"assetResources\"] = [];\n\n for (const resource of resources) {\n if (resource.kind === \"preconnect\") {\n preconnects.push(resource);\n } else if (\n resource.kind === \"font\" ||\n (resource.kind === \"preload\" &&\n (resource.as === \"font\" ||\n (resource.as === \"image\" &&\n (resource.fetchpriority === \"high\" ||\n request.assetRegistry.isEarlyImage(resource)))))\n ) {\n criticalPreloads.push(resource);\n } else if (resource.kind === \"stylesheet\") {\n stylesheets.push(resource);\n } else {\n afterMetadata.push(resource);\n }\n }\n\n return [[...preconnects, ...criticalPreloads, ...stylesheets], afterMetadata];\n}\n\nfunction flushWriteBuffer(request: Request): void {\n if (request.writeBuffer.length === 0 || request.controller === null) return;\n request.controller.enqueue(textEncoder.encode(request.writeBuffer.join(\"\")));\n request.writeBuffer = [];\n}\n\nfunction ensureSegmentId(request: Request, segment: Segment): number {\n segment.id ??= request.nextSegmentId++;\n return segment.id;\n}\n\nfunction ensureBoundaryId(\n request: Request,\n boundary: SuspenseBoundary,\n): number {\n boundary.id ??= request.nextBoundaryId++;\n return boundary.id;\n}\n","import {\n type ComponentType,\n createElement,\n type ElementType,\n type FigAssetResource,\n type FigClientReference,\n type FigContext,\n type FigElement,\n type FigNode,\n Fragment,\n isValidElement,\n type PreloadResource,\n type Props,\n type ViewTransitionProps,\n} from \"@bgub/fig\";\nimport {\n ACTIVITY_TEMPLATE_ATTRIBUTE,\n assetResourceFromHostProps,\n attachDataStore,\n collectChildren,\n createRendererDataStore,\n type FigDataStore,\n invalidChildError,\n isActivity,\n isAssets,\n isClientReference,\n isContext,\n isErrorBoundary,\n isFigAssetResource,\n isPortal,\n isSuspense,\n isThenable,\n isViewTransition,\n type NormalizedChild,\n type RenderDispatcher,\n readThenable,\n setCurrentDataStore,\n setCurrentDispatcher,\n type Thenable,\n TEXT_SEPARATOR_DATA,\n validateInstanceNesting,\n validateTextNesting,\n VIEW_TRANSITION_CLASS_ATTRIBUTE,\n VIEW_TRANSITION_NAME_ATTRIBUTE,\n} from \"@bgub/fig/internal\";\nimport {\n AssetResourceRegistry,\n type HeadMetadataHtml,\n} from \"./asset-registry.ts\";\nimport {\n escapeAttribute,\n formTextContent,\n hasRenderableChild,\n isVoidElement,\n unsafeHTMLContent,\n writeElementEnd,\n writeElementStart,\n writeText,\n} from \"./html.ts\";\nimport {\n imagePreloadFromHostProps,\n suppressesImagePreloads,\n} from \"./image-preloads.ts\";\nimport { activityId, earlyEventCaptureMarkup } from \"./protocol.ts\";\nimport {\n formatPreloadHeader,\n type PreloadHeaderEntry,\n} from \"./preload-header.ts\";\nimport {\n documentHeadMarker,\n flushCompletedQueues,\n leadingNewlineEndMarker,\n leadingNewlineStartMarker,\n sealHead,\n type SegmentChunk,\n} from \"./renderer-flush.ts\";\nimport {\n type ContextValues,\n type StackFrame,\n cloneContextValues,\n componentStack,\n createStaticDispatcher,\n type Deferred,\n deferred,\n streamHighWaterMark,\n withContextValue,\n errorMessage,\n} from \"./shared.ts\";\nimport type { RenderTreeNode } from \"./render-tree.ts\";\nimport type {\n ServerErrorPayload,\n ServerFragmentRenderResult,\n ServerRenderOptions,\n} from \"./types.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\n\ninterface HeadSnapshot extends HeadMetadataHtml {\n readonly preloadHeaderEntries: readonly PreloadHeaderEntry[];\n}\n\nexport interface Request {\n abortableTasks: Set<Task>;\n allReady: Deferred<void>;\n cleanupAbortListener(): void;\n completedBoundaries: Set<SuspenseBoundary>;\n completedRootSegment: Segment | null;\n controller: ReadableStreamDefaultController<Uint8Array> | null;\n dataStore: FigDataStore;\n fatalError: unknown;\n identifierPrefix: string;\n // Flush-time parser state for nested <pre>/<textarea> hosts. Rendering may\n // complete child segments out of order; only logical flush order can decide\n // which text is the parser's first child.\n leadingNewlineStack: boolean[];\n nextBoundaryId: number;\n nextSegmentId: number;\n nextActivityId: number;\n nextViewTransitionId: number;\n nonce?: string;\n onError?: ServerRenderOptions[\"onError\"];\n pendingRootTasks: number;\n pendingTasks: number;\n pingedTasks: Task[];\n rootSegment: Segment;\n runtimeName: string;\n runtimeWritten: boolean;\n headReady: Deferred<string>;\n // Set exactly once, when the shell completes and the head is sealed; also\n // the \"head is sealed\" flag.\n headSnapshot: HeadSnapshot | null;\n shellReady: Deferred<void>;\n status: \"open\" | \"aborting\" | \"closed\";\n clientRenderedBoundaries: Set<SuspenseBoundary>;\n clientReferenceFallback?: ServerRenderOptions[\"clientReferenceFallback\"];\n partialBoundaries: Set<SuspenseBoundary>;\n prerender: boolean;\n componentAssets?: ServerRenderOptions[\"assets\"];\n document: DocumentState | null;\n assetRegistry: AssetResourceRegistry;\n resolveAssetKey?: ServerRenderOptions[\"resolveAssetKey\"];\n workScheduled: boolean;\n // Reentrancy guard: enqueueing inside a flush pass can synchronously invoke\n // the stream's pull handler, which must not restart the pass — a boundary\n // stays in its queue while it flushes, so a reentrant drain would emit it\n // twice.\n flushing: boolean;\n // Chunks accumulate here per flush pass and leave as one encoded enqueue,\n // instead of one tiny Uint8Array per attribute/text write.\n writeBuffer: string[];\n write(chunk: string): void;\n}\n\n// Render-scope state shared by queued tasks and live frames; forked (with\n// context values cloned) whenever work is spawned or resumed.\ninterface RenderScope {\n abortSet: Set<Task>;\n boundary: SuspenseBoundary | null;\n contextValues: ContextValues;\n // The nearest enclosing hidden Activity's template id, or null when not inside\n // one. Threaded so suspended content streamed for that boundary can be revealed\n // into the activity template's inert content.\n hiddenActivityId: string | null;\n // Logical host-ancestor tags (nearest first) for DOM-nesting validation.\n // Suspended segments stream into staging nodes but are moved into place on\n // the client, so their spawn-point ancestors stay authoritative.\n hostAncestors: readonly string[];\n // Namespace inherited by the next host element. Unlike dev-only nesting\n // ancestry this is runtime semantics: asset lowering applies only to HTML.\n hostNamespace: HostNamespace;\n // True inside HTML <picture> and <noscript>, where an <img> does not name a\n // standalone preload candidate.\n imagePreloadsSuppressed: boolean;\n idPath: string;\n pendingLeadingNewline: boolean;\n selectProps: Props | null;\n stack: StackFrame | null;\n // Where collected render-tree nodes attach; null when no collector was\n // passed. Forked into suspended tasks so resumed content lands under its\n // boundary's node.\n treeParent: RenderTreeNode | null;\n viewTransition: ServerViewTransitionContext | null;\n}\n\ninterface Task extends RenderScope {\n // Index of the suspended child within its original normalized children\n // sequence. Resuming id-path numbering here keeps useId paths identical to\n // the never-suspending render (and to client fiber indices).\n childIndexBase: number;\n node: FigNode;\n segment: Segment;\n}\n\nexport interface Segment {\n readonly boundary: SuspenseBoundary | null;\n children: Segment[];\n chunks: SegmentChunk[];\n id: number | null;\n index: number;\n // True when the trailing edge of everything written so far — including the\n // inherited parent position for spawned segments — is document text. The\n // next text write must lead with TEXT_SEPARATOR so the browser's parser\n // does not merge the two into one DOM text node.\n lastPushedText: boolean;\n parentFlushed: boolean;\n assetResources: FigAssetResource[];\n status: SegmentStatus;\n // Spawned suspended segments splice between their parent's chunks, so text\n // may directly follow their end; when such a segment completes ending in\n // text, it closes with a trailing TEXT_SEPARATOR.\n textEmbedded: boolean;\n write(chunk: SegmentChunk): void;\n}\n\nexport interface SuspenseBoundary {\n // Non-null when this boundary lives inside a hidden Activity: the activity\n // template id its streamed completion must be revealed into. See `ac`/`ax` in\n // protocol.ts.\n activityId: string | null;\n completedSegments: Segment[];\n contentSegment: Segment;\n error: ServerErrorPayload | null;\n fallbackSegment: Segment | null;\n fallbackAbortableTasks: Set<Task>;\n id: number | null;\n parentFlushed: boolean;\n pendingTasks: number;\n status: BoundaryStatus;\n metadataVisible: boolean;\n}\n\ntype BoundaryStatus = \"pending\" | \"completed\" | \"client-rendered\";\ntype SegmentStatus = \"pending\" | \"rendering\" | \"completed\" | \"flushed\";\ntype HostNamespace = \"html\" | \"mathml\" | \"svg\";\n\ninterface RenderFrame extends RenderScope {\n dispatcher: RenderDispatcher | null;\n localIdCounter: number;\n request: Request;\n segment: Segment;\n}\n\ninterface DocumentState {\n hasHead: boolean;\n}\n\ninterface ServerViewTransitionContext {\n className: string | null;\n index: number;\n name: string;\n}\n\nconst errorStacks = new WeakMap<object, StackFrame>();\n// Emitted between two adjacent text writes that come from different\n// normalized text children (component seams, resumed suspended segments).\n// The HTML parser merges back-to-back character data into ONE DOM text node,\n// while the client tree keeps one text fiber per normalized child (see\n// collectChildren in @bgub/fig) — the comment keeps the nodes apart so each\n// fiber can claim its own during hydration. The comment data is the shared\n// TEXT_SEPARATOR_DATA protocol constant that fig-dom's hydration cursor\n// skips (and only that; suspense markers use the fig:suspense prefixes).\nconst TEXT_SEPARATOR = `<!--${TEXT_SEPARATOR_DATA}-->`;\nlet nextRuntimeId = 0;\n\nexport function createServerRenderRequest(\n node: FigNode,\n options: ServerRenderOptions = {},\n mode: { document?: boolean; prerender?: boolean } = {},\n): ServerFragmentRenderResult {\n throwIfAborted(options.signal);\n\n const shellReady = deferred<void>();\n const headReady = deferred<string>();\n const allReady = deferred<void>();\n // The readiness promises also reject through the stream; pre-attached\n // no-op handlers keep the ones a caller does not await from becoming\n // unhandled rejections (await-ers still observe the rejection).\n void shellReady.promise.catch(() => undefined);\n void headReady.promise.catch(() => undefined);\n void allReady.promise.catch(() => undefined);\n const rootSegment = createSegment(0, null);\n const dataStoreHost = {\n getLane: () => null,\n partition: options.dataPartition,\n schedule: () => undefined,\n };\n const dataStore =\n options.dataStore === undefined\n ? createRendererDataStore<object, null>(dataStoreHost)\n : attachDataStore(options.dataStore, dataStoreHost, options.initialData);\n\n const request: Request = {\n abortableTasks: new Set<Task>(),\n allReady,\n cleanupAbortListener: () => undefined,\n completedBoundaries: new Set(),\n completedRootSegment: null,\n controller: null,\n dataStore,\n fatalError: null,\n identifierPrefix: options.identifierPrefix ?? \"\",\n leadingNewlineStack: [],\n nextBoundaryId: 0,\n nextSegmentId: 0,\n nextActivityId: 0,\n nextViewTransitionId: 0,\n nonce: options.nonce,\n onError: options.onError,\n pendingRootTasks: 0,\n pendingTasks: 0,\n pingedTasks: [],\n rootSegment,\n runtimeName: createRuntimeName(options.identifierPrefix),\n runtimeWritten: false,\n headReady,\n headSnapshot: null,\n shellReady,\n status: \"open\",\n clientRenderedBoundaries: new Set(),\n clientReferenceFallback: options.clientReferenceFallback,\n partialBoundaries: new Set(),\n prerender: mode.prerender === true,\n componentAssets: options.assets,\n document: mode.document === true ? { hasHead: false } : null,\n assetRegistry: new AssetResourceRegistry(options.identifierPrefix ?? \"\"),\n resolveAssetKey: options.resolveAssetKey,\n workScheduled: false,\n flushing: false,\n writeBuffer: [],\n write(chunk) {\n if (chunk !== \"\" && this.leadingNewlineStack.length > 0) {\n this.leadingNewlineStack[this.leadingNewlineStack.length - 1] = true;\n }\n this.writeBuffer.push(chunk);\n },\n };\n if (options.dataStore === undefined && options.initialData !== undefined) {\n request.dataStore.hydrate(options.initialData);\n }\n\n rootSegment.parentFlushed = true;\n const rootTask = createTask(request, node, rootSegment, {\n abortSet: request.abortableTasks,\n boundary: null,\n contextValues: new Map(),\n hiddenActivityId: null,\n hostAncestors: [],\n hostNamespace: \"html\",\n imagePreloadsSuppressed: false,\n idPath: \"\",\n pendingLeadingNewline: false,\n selectProps: null,\n stack: null,\n treeParent: options.renderTree?.tree ?? null,\n viewTransition: null,\n });\n request.pingedTasks.push(rootTask);\n\n const stream = new ReadableStream<Uint8Array>(\n {\n start(streamController) {\n request.controller = streamController;\n flushCompletedQueues(request);\n },\n pull() {\n // The consumer drained below the high-water mark: resume flushing\n // whatever completed while the flow was blocked.\n flushCompletedQueues(request);\n },\n cancel(reason) {\n // The consumer is gone: drop the sink before aborting so the abort\n // pass does not enqueue into (or close) a cancelled stream.\n request.controller = null;\n request.writeBuffer = [];\n abort(request, reason);\n request.status = \"closed\";\n },\n },\n new ByteLengthQueuingStrategy({\n highWaterMark: streamHighWaterMark(options.highWaterMark),\n }),\n );\n\n if (options.signal !== undefined) {\n const signal = options.signal;\n const abortListener = () => abort(request, signal.reason);\n signal.addEventListener(\"abort\", abortListener, { once: true });\n request.cleanupAbortListener = () => {\n signal.removeEventListener(\"abort\", abortListener);\n request.cleanupAbortListener = () => undefined;\n };\n }\n\n request.workScheduled = true;\n queueMicrotask(() => {\n request.workScheduled = false;\n performWork(request);\n });\n\n return {\n abort: (reason?: unknown) => abort(request, reason),\n allReady: allReady.promise,\n contentType: \"text/html; charset=utf-8\",\n data: request.dataStore,\n getData: () => request.dataStore.snapshot(),\n getPreloadHeader: (headerOptions) =>\n request.headSnapshot === null\n ? undefined\n : formatPreloadHeader(\n request.headSnapshot.preloadHeaderEntries,\n headerOptions,\n ),\n getHead: () => {\n const snapshot = request.headSnapshot;\n return snapshot === null\n ? request.assetRegistry.headHtml(request.nonce)\n : snapshot.preamble + snapshot.metadata;\n },\n headReady: headReady.promise,\n shellReady: shellReady.promise,\n stream,\n };\n}\n\nfunction createTask(\n request: Request,\n node: FigNode,\n segment: Segment,\n scope: RenderScope,\n childIndexBase = 0,\n): Task {\n request.pendingTasks += 1;\n if (scope.boundary === null) {\n request.pendingRootTasks += 1;\n } else {\n scope.boundary.pendingTasks += 1;\n }\n\n const task: Task = { ...scope, childIndexBase, node, segment };\n request.abortableTasks.add(task);\n scope.abortSet.add(task);\n return task;\n}\n\n// Copies a scope for spawned or resumed work. Context values are cloned so\n// the fork observes the provider stack as of the fork point.\nfunction forkScope(scope: RenderScope): RenderScope {\n return {\n abortSet: scope.abortSet,\n boundary: scope.boundary,\n contextValues: cloneContextValues(scope.contextValues),\n hiddenActivityId: scope.hiddenActivityId,\n hostAncestors: scope.hostAncestors,\n hostNamespace: scope.hostNamespace,\n imagePreloadsSuppressed: scope.imagePreloadsSuppressed,\n idPath: scope.idPath,\n pendingLeadingNewline: scope.pendingLeadingNewline,\n selectProps: scope.selectProps,\n stack: scope.stack,\n treeParent: scope.treeParent,\n // Forked branches get their own surface-index cursor from the same\n // snapshot. A Suspense fallback and its streamed content then produce\n // the SAME name sequence, so the reveal pairs (morphs) them instead of\n // cross-fading two differently suffixed names — and names stay\n // deterministic under parallel task completion.\n viewTransition:\n scope.viewTransition === null ? null : { ...scope.viewTransition },\n };\n}\n\nfunction createSegment(\n index: number,\n boundary: SuspenseBoundary | null,\n textSeams: { lastPushedText: boolean; textEmbedded: boolean } = {\n lastPushedText: false,\n textEmbedded: false,\n },\n): Segment {\n return {\n boundary,\n children: [],\n chunks: [],\n id: null,\n index,\n lastPushedText: textSeams.lastPushedText,\n parentFlushed: false,\n assetResources: [],\n status: \"pending\",\n textEmbedded: textSeams.textEmbedded,\n write(chunk) {\n // Every non-text write (tags, comments, scripts) breaks text adjacency;\n // renderNode's text path re-marks the flag after writing text.\n this.lastPushedText = false;\n this.chunks.push(chunk);\n },\n };\n}\n\nfunction createBoundary(\n fallbackAbortableTasks: Set<Task>,\n contentSegment: Segment,\n): SuspenseBoundary {\n return {\n activityId: null,\n completedSegments: [],\n contentSegment,\n error: null,\n fallbackSegment: null,\n fallbackAbortableTasks,\n id: null,\n parentFlushed: false,\n pendingTasks: 0,\n status: \"pending\",\n metadataVisible: false,\n };\n}\n\nfunction performWork(request: Request): void {\n if (request.status === \"closed\") return;\n\n const tasks = request.pingedTasks;\n request.pingedTasks = [];\n\n for (const task of tasks) retryTask(request, task);\n\n flushCompletedQueues(request);\n}\n\nfunction retryTask(request: Request, task: Task): void {\n if (task.segment.status !== \"pending\") return;\n\n task.segment.status = \"rendering\";\n const frame = createRenderFrame(request, task.segment, forkScope(task));\n\n try {\n renderChildSequence(collectChildren(task.node), frame, task.childIndexBase);\n completeSegmentText(task.segment);\n task.segment.status = \"completed\";\n detachTask(request, task);\n finishedTask(request, task);\n } catch (error) {\n detachTask(request, task);\n task.segment.status = \"completed\";\n erroredTask(request, task, error);\n }\n}\n\nfunction createRenderFrame(\n request: Request,\n segment: Segment,\n scope: RenderScope,\n): RenderFrame {\n return {\n ...scope,\n dispatcher: null,\n localIdCounter: 0,\n request,\n segment,\n };\n}\n\nfunction createServerDispatcher(frame: RenderFrame): RenderDispatcher {\n return createStaticDispatcher({\n contextValues: frame.contextValues,\n externalStoreError:\n \"useSyncExternalStore requires getServerSnapshot during server render.\",\n readPromise(promise) {\n throwIfAborting(frame.request);\n return readThenable(promise);\n },\n readData(resource, args) {\n throwIfAborting(frame.request);\n return frame.request.dataStore.readData(resource, args, frame);\n },\n preloadData(resource, args) {\n throwIfAborting(frame.request);\n frame.request.dataStore.preloadData(resource, ...args);\n },\n useId() {\n const id = `${frame.request.identifierPrefix}fig-${frame.idPath}-${frame.localIdCounter.toString(32)}`;\n frame.localIdCounter += 1;\n return id;\n },\n updateError: \"State updates are not allowed during server render.\",\n });\n}\n\nfunction renderNode(node: FigNode, frame: RenderFrame): void {\n if (Array.isArray(node)) {\n renderChildren(node, frame);\n return;\n }\n\n if (node === null || node === undefined || typeof node === \"boolean\") {\n return;\n }\n\n if (typeof node === \"string\" || typeof node === \"number\") {\n const text = String(node);\n if (frame.request.document !== null && !frame.request.document.hasHead) {\n if (text.trim() !== \"\") throw invalidDocumentShellError();\n }\n if (__DEV__ && frame.hostNamespace === \"html\") {\n validateTextNesting(text, frame.hostAncestors);\n }\n if (text !== \"\") {\n if (frame.treeParent !== null) {\n frame.treeParent.children.push({\n children: [],\n key: null,\n kind: \"text\",\n name: \"#text\",\n props: { nodeValue: text },\n });\n }\n // Directly adjacent text from a different fiber: separate it so the\n // browser's parser yields one DOM text node per client text fiber.\n if (frame.segment.lastPushedText) frame.segment.write(TEXT_SEPARATOR);\n if (consumePendingLeadingNewline(frame)) {\n writeLeadingNewlineText(text, frame.segment);\n } else {\n writeText(text, frame.segment);\n }\n frame.segment.lastPushedText = true;\n }\n return;\n }\n\n if (isPortal(node)) return;\n\n if (isValidElement(node)) {\n renderElement(node, frame);\n return;\n }\n\n if (isThenable(node)) {\n renderChildren(readThenable(node), frame);\n return;\n }\n\n throw invalidChildError(node);\n}\n\nfunction renderChildren(node: FigNode, frame: RenderFrame): void {\n renderChildSequence(collectChildren(node), frame);\n}\n\nfunction renderChildSequence(\n children: NormalizedChild[],\n frame: RenderFrame,\n // Non-zero when resuming a suspended task: `children` starts at the\n // suspended child's original index, so id-path segments stay stable.\n indexBase = 0,\n): void {\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n try {\n withIdSegment(frame, indexBase + index, () => renderNode(child, frame));\n } catch (error) {\n if (isThenable(error)) {\n spawnSuspendedTask(frame, child, error, indexBase + index);\n continue;\n }\n\n throw error;\n }\n }\n}\n\n// A spawned segment cannot know what follows its splice point once its\n// parent resumes (or what a sibling spawned segment will start with), so a\n// segment ending in text conservatively closes with a separator; hydration\n// skips any it did not need.\nfunction completeSegmentText(segment: Segment): void {\n if (segment.textEmbedded && segment.lastPushedText) {\n segment.write(TEXT_SEPARATOR);\n }\n}\n\nfunction withIdSegment<T>(\n frame: RenderFrame,\n index: number,\n callback: () => T,\n): T {\n const previousIdPath = frame.idPath;\n const segment = index.toString(32);\n frame.idPath =\n previousIdPath === \"\" ? segment : `${previousIdPath}-${segment}`;\n\n try {\n return callback();\n } finally {\n frame.idPath = previousIdPath;\n }\n}\n\nfunction renderElement(element: FigElement, frame: RenderFrame): void {\n if (frame.treeParent === null) {\n renderElementKind(element, frame);\n return;\n }\n\n const treeNode = collectedTreeNode(element);\n frame.treeParent.children.push(treeNode);\n const previousTreeParent = frame.treeParent;\n frame.treeParent = treeNode;\n try {\n renderElementKind(element, frame);\n } finally {\n frame.treeParent = previousTreeParent;\n }\n}\n\nfunction collectedTreeNode(element: FigElement): RenderTreeNode {\n const { children: _children, ...ownProps } = element.props;\n const [name, kind] = collectedNameAndKind(element.type);\n return {\n children: [],\n key: element.key ?? null,\n kind,\n name,\n props: ownProps,\n };\n}\n\nfunction collectedNameAndKind(type: unknown): [string, RenderTreeNode[\"kind\"]] {\n if (typeof type === \"string\") return [type, \"host\"];\n if (type === Fragment) return [\"Fragment\", \"fragment\"];\n if (isContext(type)) return [\"Context.Provider\", \"context-provider\"];\n if (isAssets(type)) return [\"Assets\", \"assets\"];\n if (isSuspense(type)) return [\"Suspense\", \"suspense\"];\n if (isErrorBoundary(type)) return [\"ErrorBoundary\", \"error-boundary\"];\n if (isActivity(type)) return [\"Activity\", \"activity\"];\n if (isViewTransition(type)) return [\"ViewTransition\", \"view-transition\"];\n if (isClientReference(type)) {\n const name = type.id.slice(type.id.lastIndexOf(\"#\") + 1);\n return [name || \"ClientReference\", \"client-reference\"];\n }\n if (typeof type === \"function\") {\n return [type.name === \"\" ? \"Anonymous\" : type.name, \"function\"];\n }\n return [\"Anonymous\", \"function\"];\n}\n\nfunction renderElementKind(element: FigElement, frame: RenderFrame): void {\n const type = element.type;\n\n if (typeof type === \"string\") {\n renderHostElement(type, element.props, frame);\n return;\n }\n\n if (type === Fragment) {\n renderChildren(element.props.children, frame);\n return;\n }\n\n if (isContext(type)) {\n renderContextProvider(type, element.props, frame);\n return;\n }\n\n if (isAssets(type)) {\n renderAssets(element.props, frame);\n return;\n }\n\n if (isSuspense(type)) {\n renderSuspense(element.props, frame);\n return;\n }\n\n if (isErrorBoundary(type)) {\n renderChildren(element.props.children, frame);\n return;\n }\n\n if (isClientReference(type)) {\n renderClientReference(type, element.props, frame);\n return;\n }\n\n if (isActivity(type)) {\n renderActivity(element.props, frame);\n return;\n }\n\n if (isViewTransition(type)) {\n renderViewTransition(element.props, frame);\n return;\n }\n\n if (typeof type === \"function\") {\n renderFunctionComponent(type, element.props, frame);\n return;\n }\n\n throw new Error(\n `Unsupported Fig element type: ${describeElementType(type)}.`,\n );\n}\n\nfunction renderFunctionComponent(\n type: ComponentType,\n props: Props,\n frame: RenderFrame,\n): void {\n frame.dispatcher ??= createServerDispatcher(frame);\n const previousDispatcher = setCurrentDispatcher(frame.dispatcher);\n const previousDataStore = setCurrentDataStore(frame.request.dataStore);\n const previousStack = frame.stack;\n const previousLocalIdCounter = frame.localIdCounter;\n frame.stack = { name: type.name || \"Anonymous\", parent: previousStack };\n frame.localIdCounter = 0;\n\n try {\n renderComponentAssets(type, frame);\n renderChildren(type(props), frame);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n } finally {\n frame.stack = previousStack;\n frame.localIdCounter = previousLocalIdCounter;\n setCurrentDataStore(previousDataStore);\n setCurrentDispatcher(previousDispatcher);\n }\n}\n\nfunction renderClientReference(\n type: FigClientReference,\n props: Props,\n frame: RenderFrame,\n): void {\n if (type.ssr !== undefined) {\n renderComponentAssets(type, frame);\n renderElement(createElement(type.ssr, props), frame);\n return;\n }\n\n const fallback = frame.request.clientReferenceFallback;\n if (fallback === undefined) {\n renderFunctionComponent(type, props, frame);\n return;\n }\n\n renderComponentAssets(type, frame);\n renderChildren(fallback(type, props), frame);\n}\n\nfunction renderComponentAssets(type: ElementType, frame: RenderFrame): void {\n const key = isClientReference(type)\n ? type.id\n : frame.request.resolveAssetKey?.(type);\n if (key !== undefined) {\n renderAssetValue(frame.request.componentAssets?.[key], frame);\n }\n}\n\nfunction renderContextProvider(\n context: FigContext<unknown>,\n props: Props,\n frame: RenderFrame,\n): void {\n withContextValue(frame.contextValues, context, props.value, () =>\n renderChildren(props.children, frame),\n );\n}\n\nfunction renderAssets(props: Props, frame: RenderFrame): void {\n renderAssetValue(props.assets, frame);\n renderChildren(props.children, frame);\n}\n\nfunction renderAssetValue(value: unknown, frame: RenderFrame): void {\n if (value === undefined || value === null || value === false) return;\n\n for (const resource of Array.isArray(value) ? value : [value]) {\n if (!isFigAssetResource(resource)) {\n throw new Error(\"The assets prop must contain Fig asset resources.\");\n }\n\n try {\n frame.request.assetRegistry.register(resource);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n }\n\n frame.segment.assetResources.push(resource);\n }\n}\n\nfunction renderAutomaticImagePreload(\n resource: PreloadResource,\n frame: RenderFrame,\n): void {\n try {\n frame.request.assetRegistry.registerAutomaticImage(resource);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n }\n frame.segment.assetResources.push(resource);\n}\n\nfunction renderSuspense(props: Props, frame: RenderFrame): void {\n consumePendingLeadingNewline(frame);\n const fallbackAbortableTasks = new Set<Task>();\n const contentSegment = createSegment(0, null);\n const boundary = createBoundary(fallbackAbortableTasks, contentSegment);\n boundary.activityId = frame.hiddenActivityId;\n const parentSegment = frame.segment;\n const boundarySegment = createSegment(parentSegment.chunks.length, boundary);\n boundary.fallbackSegment = boundarySegment;\n parentSegment.children.push(boundarySegment);\n // The boundary always flushes comment markers around its content, so text\n // on either side of it never merges; no separators needed at this seam.\n parentSegment.lastPushedText = false;\n\n contentSegment.parentFlushed = true;\n const contentFrame = createRenderFrame(frame.request, contentSegment, {\n ...forkScope(frame),\n boundary,\n });\n\n try {\n renderChildren(props.children, contentFrame);\n contentSegment.status = \"completed\";\n boundary.completedSegments.push(contentSegment);\n if (boundary.pendingTasks === 0) boundary.status = \"completed\";\n } catch (error) {\n // Suspensions never reach here: renderChildSequence is the single\n // suspend seam and contentFrame always has a boundary, so it spawns a\n // suspended task and continues instead of throwing.\n contentSegment.status = \"completed\";\n markBoundaryClientRendered(frame.request, boundary, error, frame.stack);\n }\n\n // Surfaces after the boundary must not reuse suffixes the branches\n // already claimed. Suspended content tasks may still allocate past this\n // watermark; those deep-tail collisions are accepted (the browser skips\n // pairing for duplicated names rather than breaking the reveal).\n const advanceSurfaceWatermark = (branch: RenderFrame): void => {\n if (frame.viewTransition !== null && branch.viewTransition !== null) {\n frame.viewTransition.index = Math.max(\n frame.viewTransition.index,\n branch.viewTransition.index,\n );\n }\n };\n advanceSurfaceWatermark(contentFrame);\n\n if (boundary.status === \"completed\") return;\n\n const fallbackFrame = createRenderFrame(frame.request, boundarySegment, {\n ...forkScope(frame),\n abortSet: fallbackAbortableTasks,\n });\n\n try {\n renderChildren(props.fallback, fallbackFrame);\n boundarySegment.status = \"completed\";\n } catch (error) {\n if (boundary.pendingTasks > 0) {\n for (const task of Array.from(boundary.fallbackAbortableTasks)) {\n abortTask(frame.request, task);\n }\n }\n throw error;\n } finally {\n advanceSurfaceWatermark(fallbackFrame);\n }\n}\n\nfunction renderViewTransition(props: Props, frame: RenderFrame): void {\n const previousViewTransition = frame.viewTransition;\n frame.viewTransition = createServerViewTransition(props, frame.request);\n\n try {\n renderChildren(props.children, frame);\n } finally {\n frame.viewTransition = previousViewTransition;\n }\n}\n\nfunction createServerViewTransition(\n props: ViewTransitionProps,\n request: Request,\n): ServerViewTransitionContext {\n return {\n className: serverViewTransitionClass(props),\n index: 0,\n name:\n props.name === undefined || props.name === \"auto\"\n ? `fig-vt-${request.nextViewTransitionId++}`\n : props.name,\n };\n}\n\nfunction serverViewTransitionClass(props: ViewTransitionProps): string | null {\n const className = props.default;\n if (className === undefined || className === \"auto\" || className === \"none\") {\n return null;\n }\n\n return className;\n}\n\nfunction renderActivity(props: Props, frame: RenderFrame): void {\n if (props.mode !== \"hidden\") {\n renderChildren(props.children, frame);\n return;\n }\n\n // Hidden Activity content streams inside an inert template so neither\n // elements nor bare text render before hydration; the client keeps the\n // boundary dehydrated until reveal. The template carries an id so Suspense\n // boundaries that suspend inside it can stream their completions into this\n // inert content (see `ac`/`ax` in protocol.ts).\n const id = activityId(frame.request, frame.request.nextActivityId++);\n frame.segment.write(\n `<template ${ACTIVITY_TEMPLATE_ATTRIBUTE}=\"\" id=\"${escapeAttribute(id)}\">`,\n );\n const previousHiddenActivityId = frame.hiddenActivityId;\n frame.hiddenActivityId = id;\n try {\n renderChildren(props.children, frame);\n } finally {\n frame.hiddenActivityId = previousHiddenActivityId;\n }\n frame.segment.write(\"</template>\");\n}\n\nfunction renderHostElement(\n type: string,\n props: Props,\n frame: RenderFrame,\n): void {\n const namespace = hostElementNamespace(type, frame.hostNamespace);\n if (namespace === \"html\" && renderHostAsset(type, props, frame)) return;\n\n if (__DEV__ && namespace === \"html\") {\n validateInstanceNesting(type, frame.hostAncestors);\n }\n\n const document = frame.request.document;\n\n if (document !== null && !document.hasHead) {\n if (type !== \"html\" && type !== \"head\") throw invalidDocumentShellError();\n }\n\n if (document !== null && type === \"html\") {\n frame.segment.write(\"<!doctype html>\");\n }\n if (document !== null && type === \"head\") {\n document.hasHead = true;\n }\n\n const isVoid = namespace === \"html\" && isVoidElement(type);\n const unsafeHTML = unsafeHTMLContent(props);\n\n // hasRenderableChild is an O(children) scan; only the error checks need it.\n if (isVoid && hasRenderableChild(props.children)) {\n throw new Error(`Void element <${type}> cannot have children.`);\n }\n if (isVoid && unsafeHTML !== null) {\n throw new Error(`Void element <${type}> cannot have unsafeHTML.`);\n }\n if (unsafeHTML !== null && hasRenderableChild(props.children)) {\n throw new Error(\"Host elements cannot have both unsafeHTML and children.\");\n }\n\n if (namespace === \"html\") {\n const imagePreload = imagePreloadFromHostProps(\n type,\n props,\n frame.imagePreloadsSuppressed,\n );\n if (imagePreload !== null) {\n renderAutomaticImagePreload(imagePreload, frame);\n }\n }\n\n consumePendingLeadingNewline(frame);\n const viewTransition = frame.viewTransition;\n const hostProps =\n viewTransition === null\n ? props\n : viewTransitionHostProps(props, viewTransition);\n writeElementStart(type, hostProps, frame.segment, frame.selectProps ?? {});\n if (document !== null && type === \"head\") {\n // First thing in <head>: events must be capturable before any content\n // can paint, or a user's first interaction races bundle execution.\n frame.segment.write(earlyEventCaptureMarkup(frame.request));\n }\n if (isVoid) return;\n\n const previousPendingLeadingNewline = frame.pendingLeadingNewline;\n const tracksLeadingNewline = leadingNewlineStrippedHost(type);\n frame.pendingLeadingNewline = tracksLeadingNewline;\n\n if (unsafeHTML !== null) {\n frame.segment.write(\n consumePendingLeadingNewline(frame)\n ? preserveParserStrippedLeadingNewline(unsafeHTML)\n : unsafeHTML,\n );\n frame.pendingLeadingNewline = previousPendingLeadingNewline;\n writeElementEnd(type, frame.segment);\n return;\n }\n\n const formText = namespace === \"html\" ? formTextContent(type, props) : null;\n if (formText !== null) {\n writeText(\n consumePendingLeadingNewline(frame)\n ? preserveParserStrippedLeadingNewline(formText)\n : formText,\n frame.segment,\n );\n frame.pendingLeadingNewline = previousPendingLeadingNewline;\n writeElementEnd(type, frame.segment);\n return;\n }\n\n const previousSelectProps = frame.selectProps;\n if (namespace === \"html\" && type === \"select\") frame.selectProps = props;\n const previousHostAncestors = frame.hostAncestors;\n const previousHostNamespace = frame.hostNamespace;\n const previousImagePreloadsSuppressed = frame.imagePreloadsSuppressed;\n const previousViewTransition = frame.viewTransition;\n if (viewTransition !== null) frame.viewTransition = null;\n if (__DEV__) {\n frame.hostAncestors = [type, ...previousHostAncestors];\n }\n frame.hostNamespace = childHostNamespace(type, namespace);\n frame.imagePreloadsSuppressed =\n previousImagePreloadsSuppressed ||\n (namespace === \"html\" && suppressesImagePreloads(type));\n if (tracksLeadingNewline) {\n frame.segment.chunks.push(leadingNewlineStartMarker);\n }\n\n try {\n // Suspensions are handled inside renderChildSequence (the single suspend\n // seam), so no thenable can reach this frame; plain errors propagate.\n renderChildren(props.children, frame);\n } finally {\n frame.selectProps = previousSelectProps;\n frame.hostAncestors = previousHostAncestors;\n frame.hostNamespace = previousHostNamespace;\n frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed;\n frame.viewTransition = previousViewTransition;\n frame.pendingLeadingNewline = previousPendingLeadingNewline;\n }\n if (tracksLeadingNewline) {\n frame.segment.chunks.push(leadingNewlineEndMarker);\n }\n if (document !== null && type === \"head\") {\n writeDocumentHeadMarker(frame.segment);\n }\n writeElementEnd(type, frame.segment);\n}\n\nfunction hostElementNamespace(\n type: string,\n parent: HostNamespace,\n): HostNamespace {\n const normalizedType = type.toLowerCase();\n if (normalizedType === \"svg\") return \"svg\";\n if (normalizedType === \"math\") return \"mathml\";\n return parent;\n}\n\nfunction childHostNamespace(\n type: string,\n namespace: HostNamespace,\n): HostNamespace {\n return namespace === \"svg\" && type.toLowerCase() === \"foreignobject\"\n ? \"html\"\n : namespace;\n}\n\nfunction renderHostAsset(\n type: string,\n props: Props,\n frame: RenderFrame,\n): boolean {\n const resource = assetResourceFromHostProps(type, props);\n if (resource === null) return false;\n\n renderAssetValue(resource, frame);\n return true;\n}\n\nfunction viewTransitionHostProps(\n props: Props,\n viewTransition: ServerViewTransitionContext,\n): Props {\n const index = viewTransition.index++;\n const name =\n index === 0 ? viewTransition.name : `${viewTransition.name}_${index}`;\n const nextProps: Props = {\n ...props,\n [VIEW_TRANSITION_NAME_ATTRIBUTE]: name,\n };\n\n if (viewTransition.className !== null) {\n nextProps[VIEW_TRANSITION_CLASS_ATTRIBUTE] = viewTransition.className;\n }\n\n return nextProps;\n}\n\nfunction spawnSuspendedTask(\n frame: RenderFrame,\n node: FigNode,\n thenable: Thenable,\n childIndexBase: number,\n): void {\n const request = frame.request;\n // The spawned segment splices between the parent's text chunks: it adopts\n // the parent's trailing-text state (so its own leading text writes a\n // separator against the text before the splice point) and marks itself\n // text-embedded (so completeSegmentText appends a trailing separator when\n // it ends in text). The parent's cursor resets — the seam is now owned by\n // the spawned segment.\n const segment = createSegment(frame.segment.chunks.length, null, {\n lastPushedText: frame.segment.lastPushedText,\n textEmbedded: true,\n });\n frame.segment.lastPushedText = false;\n frame.segment.children.push(segment);\n\n const task = createTask(\n request,\n node,\n segment,\n forkScope(frame),\n childIndexBase,\n );\n thenable.then(\n () => pingTask(request, task),\n () => pingTask(request, task),\n );\n}\n\nfunction pingTask(request: Request, task: Task): void {\n if (request.status === \"closed\" || request.status === \"aborting\") return;\n request.pingedTasks.push(task);\n // Many thenables settling in one tick ping many tasks; one performWork\n // pass drains them all, so schedule at most one.\n if (request.workScheduled) return;\n request.workScheduled = true;\n queueMicrotask(() => {\n request.workScheduled = false;\n performWork(request);\n });\n}\n\nfunction finishedTask(request: Request, task: Task): void {\n request.pendingTasks -= 1;\n\n const boundary = task.boundary;\n if (boundary === null) {\n request.pendingRootTasks -= 1;\n if (\n task.segment === request.rootSegment ||\n request.completedRootSegment === null\n ) {\n request.completedRootSegment = request.rootSegment;\n }\n if (request.pendingRootTasks === 0) finishRootShell(request);\n } else {\n boundary.pendingTasks -= 1;\n\n if (task.segment.parentFlushed) {\n enqueueUnique(boundary.completedSegments, task.segment);\n }\n\n if (!completeBoundaryIfReady(request, boundary) && boundary.parentFlushed) {\n request.partialBoundaries.add(boundary);\n }\n }\n\n if (request.pendingTasks === 0) request.allReady.resolve(undefined);\n}\n\nfunction erroredTask(request: Request, task: Task, error: unknown): void {\n request.pendingTasks -= 1;\n\n const boundary = task.boundary;\n if (boundary === null) {\n request.pendingRootTasks -= 1;\n fatalError(request, error);\n return;\n }\n\n boundary.pendingTasks -= 1;\n markBoundaryClientRendered(request, boundary, error, task.stack);\n\n if (request.pendingTasks === 0) request.allReady.resolve(undefined);\n}\n\nfunction detachTask(request: Request, task: Task): void {\n task.abortSet.delete(task);\n request.abortableTasks.delete(task);\n}\n\nfunction abortTask(request: Request, task: Task): void {\n if (!request.abortableTasks.delete(task)) return;\n\n task.segment.status = \"completed\";\n task.abortSet.delete(task);\n request.pendingTasks -= 1;\n\n const boundary = task.boundary;\n if (boundary === null) {\n request.pendingRootTasks -= 1;\n if (request.pendingRootTasks === 0) finishRootShell(request);\n } else {\n boundary.pendingTasks -= 1;\n completeBoundaryIfReady(request, boundary);\n }\n\n if (request.pendingTasks === 0) request.allReady.resolve(undefined);\n}\n\nfunction completeBoundaryIfReady(\n request: Request,\n boundary: SuspenseBoundary,\n): boolean {\n if (boundary.pendingTasks !== 0 || boundary.status !== \"pending\") {\n return false;\n }\n\n boundary.status = \"completed\";\n abortFallbackTasks(request, boundary);\n if (boundary.parentFlushed) request.completedBoundaries.add(boundary);\n return true;\n}\n\nfunction abortFallbackTasks(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n for (const fallbackTask of Array.from(boundary.fallbackAbortableTasks)) {\n abortTask(request, fallbackTask);\n }\n}\n\nfunction markBoundaryClientRendered(\n request: Request,\n boundary: SuspenseBoundary,\n error: unknown,\n stack: StackFrame | null,\n payload?: ServerErrorPayload,\n): void {\n if (boundary.status !== \"client-rendered\") {\n boundary.status = \"client-rendered\";\n boundary.error = payload ?? reportBoundaryError(request, error, stack);\n }\n\n boundary.completedSegments = [];\n request.completedBoundaries.delete(boundary);\n request.partialBoundaries.delete(boundary);\n\n for (const task of Array.from(request.abortableTasks)) {\n if (task.boundary === boundary) abortTask(request, task);\n }\n\n for (const task of Array.from(boundary.fallbackAbortableTasks)) {\n abortTask(request, task);\n }\n\n if (boundary.parentFlushed) {\n request.clientRenderedBoundaries.add(boundary);\n }\n}\n\nfunction abort(request: Request, reason?: unknown): void {\n if (request.status === \"closed\") return;\n request.cleanupAbortListener();\n request.status = \"aborting\";\n request.dataStore.dispose();\n const error = abortError(reason);\n request.fatalError = error;\n\n if (request.pendingRootTasks > 0) {\n fatalError(request, error);\n return;\n }\n\n for (const task of Array.from(request.abortableTasks)) {\n const boundary = task.boundary;\n if (boundary !== null) {\n markBoundaryClientRendered(request, boundary, error, task.stack, {});\n }\n }\n\n request.abortableTasks.clear();\n request.pendingTasks = 0;\n request.allReady.resolve(undefined);\n flushCompletedQueues(request);\n}\n\nfunction fatalError(request: Request, error: unknown): void {\n if (request.status === \"closed\") return;\n\n request.cleanupAbortListener();\n request.status = \"closed\";\n request.dataStore.dispose();\n request.fatalError = error;\n request.headReady.reject(error);\n request.shellReady.reject(error);\n request.allReady.reject(error);\n request.controller?.error(error);\n}\n\nfunction finishRootShell(request: Request): void {\n if (request.document !== null && !request.document.hasHead) {\n fatalError(request, invalidDocumentShellError());\n return;\n }\n\n if (!request.prerender) sealHead(request);\n request.shellReady.resolve(undefined);\n}\n\nfunction enqueueUnique<T>(queue: T[], item: T): void {\n if (!queue.includes(item)) queue.push(item);\n}\n\nfunction reportBoundaryError(\n request: Request,\n error: unknown,\n stack: StackFrame | null,\n): ServerErrorPayload {\n const info = { componentStack: componentStack(stackForError(error, stack)) };\n if (request.onError === undefined) {\n return __DEV__ ? { message: errorMessage(error) } : {};\n }\n\n try {\n return request.onError(error, info) ?? {};\n } catch {\n return {};\n }\n}\n\nfunction recordErrorStack(error: unknown, stack: StackFrame | null): void {\n if (stack === null) return;\n if (typeof error !== \"object\" && typeof error !== \"function\") return;\n if (error === null || isThenable(error)) return;\n if (!errorStacks.has(error)) errorStacks.set(error, stack);\n}\n\nfunction stackForError(\n error: unknown,\n fallback: StackFrame | null,\n): StackFrame | null {\n if (\n (typeof error !== \"object\" && typeof error !== \"function\") ||\n error === null\n ) {\n return fallback;\n }\n\n return errorStacks.get(error) ?? fallback;\n}\n\nfunction createRuntimeName(identifierPrefix: string | undefined): string {\n const id = nextRuntimeId.toString(36);\n nextRuntimeId += 1;\n const prefix = identifierPrefix?.replace(/[^A-Za-z0-9_$]/g, \"_\") ?? \"\";\n return prefix === \"\" ? `__figSSR_${id}` : `__figSSR_${prefix}_${id}`;\n}\n\nfunction writeDocumentHeadMarker(segment: Segment): void {\n segment.lastPushedText = false;\n segment.chunks.push(documentHeadMarker);\n}\n\nfunction consumePendingLeadingNewline(frame: RenderFrame): boolean {\n const pending = frame.pendingLeadingNewline;\n frame.pendingLeadingNewline = false;\n return pending;\n}\n\nfunction leadingNewlineStrippedHost(type: string): boolean {\n return type === \"pre\" || type === \"textarea\";\n}\n\nfunction writeLeadingNewlineText(text: string, segment: Segment): void {\n writeText(text, {\n write(value) {\n segment.write({ value });\n },\n });\n}\n\nfunction preserveParserStrippedLeadingNewline(text: string): string {\n return text.startsWith(\"\\n\") ? `\\n${text}` : text;\n}\n\nfunction invalidDocumentShellError(): Error {\n return new Error(\n \"renderToDocumentStream requires the root to render an <html> document with a <head>.\",\n );\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted === true) throw abortReason(signal.reason);\n}\n\nfunction throwIfAborting(request: Request): void {\n if (request.status === \"aborting\") throw abortReason(request.fatalError);\n}\n\nfunction abortError(reason: unknown): Error {\n if (reason instanceof Error) return reason;\n return new Error(\n typeof reason === \"string\" ? reason : \"Server render was aborted.\",\n );\n}\n\nfunction abortReason(reason: unknown): unknown {\n return reason ?? new Error(\"Server render was aborted.\");\n}\n\nfunction describeElementType(type: ElementType): string {\n if (typeof type === \"symbol\") return String(type);\n if (typeof type === \"function\") return type.name || \"anonymous function\";\n return typeof type;\n}\n","// Optional render-tree collection: a caller-owned collector the renderer\n// fills with the component structure as it renders, one node per element or\n// text child. The collector is readable at any point — a subtree rendered\n// later in document order (a DevTools panel in an aside, for example) sees\n// everything rendered before it, so prerendering introspection UI needs no\n// second pass. Suspended content attaches under its boundary when the task\n// resumes; content still pending when the collector is read simply is not\n// there yet.\nexport type RenderTreeKind =\n | \"activity\"\n | \"assets\"\n | \"client-reference\"\n | \"context-provider\"\n | \"error-boundary\"\n | \"fragment\"\n | \"function\"\n | \"host\"\n | \"root\"\n | \"suspense\"\n | \"text\"\n | \"view-transition\";\n\nexport interface RenderTreeNode {\n children: RenderTreeNode[];\n key: string | number | null;\n kind: RenderTreeKind;\n name: string;\n props: Record<string, unknown>;\n}\n\nexport interface RenderTreeCollector {\n readonly tree: RenderTreeNode;\n}\n\nexport function createRenderTreeCollector(): RenderTreeCollector {\n return {\n tree: {\n children: [],\n key: null,\n kind: \"root\",\n name: \"Root\",\n props: {},\n },\n };\n}\n","import type { FigNode } from \"@bgub/fig\";\nimport { createServerRenderRequest } from \"./renderer.ts\";\nimport type {\n ServerDocumentRenderResult,\n ServerFragmentRenderResult,\n ServerPrerenderOptions,\n ServerPrerenderResult,\n ServerRenderOptions,\n} from \"./types.ts\";\n\nexport {\n createRenderTreeCollector,\n type RenderTreeCollector,\n type RenderTreeKind,\n type RenderTreeNode,\n} from \"./render-tree.ts\";\n\n// The four render entry points form one grid: render + To + (Document?) +\n// output form. Stream results are returned synchronously — a shell failure\n// rejects `shellReady` (and the stream); there is no callback channel.\n\nexport function renderToStream(\n node: FigNode,\n options: ServerRenderOptions = {},\n): ServerFragmentRenderResult {\n return createServerRenderRequest(node, options);\n}\n\nexport function renderToDocumentStream(\n node: FigNode,\n options: ServerRenderOptions = {},\n): ServerDocumentRenderResult {\n const request = createServerRenderRequest(node, options, {\n document: true,\n });\n\n // Document mode owns the head: expose the stream result without the\n // fragment-only head accessors.\n return {\n abort: (reason) => request.abort(reason),\n allReady: request.allReady,\n contentType: request.contentType,\n data: request.data,\n getData: () => request.getData(),\n getPreloadHeader: (headerOptions) =>\n request.getPreloadHeader(headerOptions),\n shellReady: request.shellReady,\n stream: request.stream,\n };\n}\n\n/**\n * The streamed output, buffered: awaits `allReady` and concatenates exactly\n * the bytes a streaming client would have received — including the inline\n * streaming runtime and boundary-reveal scripts when the tree suspends past\n * the shell. Right for caching responses and snapshotting wire output; it is\n * NOT React's `renderToString` (use `prerender` for settled, script-free\n * static markup).\n */\nexport async function renderToHtml(\n node: FigNode,\n options: ServerRenderOptions = {},\n): Promise<string> {\n const result = renderToStream(node, options);\n await result.allReady;\n return readStreamToString(result.stream);\n}\n\n/** Document-mode {@link renderToHtml}: the streamed document, buffered. */\nexport async function renderToDocumentHtml(\n node: FigNode,\n options: ServerRenderOptions = {},\n): Promise<string> {\n const result = renderToDocumentStream(node, options);\n await result.allReady;\n return readStreamToString(result.stream);\n}\n\n/**\n * Settled static HTML: waits for all async work before flushing, so completed\n * Suspense content is emitted in logical position without streaming scripts.\n */\nexport async function prerender(\n node: FigNode,\n options: ServerPrerenderOptions = {},\n): Promise<ServerPrerenderResult> {\n const { document = false, ...renderOptions } = options;\n const result = createServerRenderRequest(node, renderOptions, {\n document,\n prerender: true,\n });\n\n await result.allReady;\n const html = await readStreamToString(result.stream);\n\n return {\n data: result.getData(),\n head: document ? \"\" : result.getHead(),\n html,\n };\n}\n\nasync function readStreamToString(\n stream: ReadableStream<Uint8Array>,\n): Promise<string> {\n const reader = stream.getReader();\n const textDecoder = new TextDecoder();\n let output = \"\";\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return output + textDecoder.decode();\n output += textDecoder.decode(value, { stream: true });\n }\n}\n\nexport type {\n ServerDocumentRenderResult,\n ServerErrorInfo,\n ServerErrorPayload,\n ServerFragmentRenderResult,\n ServerPreloadHeaderOptions,\n ServerPreloadHeaderResource,\n ServerPrerenderOptions,\n ServerPrerenderResult,\n ServerRenderOptions,\n} from \"./types.ts\";\n"],"mappings":";;;;;AAeA,MAAM,+BAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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