@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/payload.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as ServerErrorInfo, r as ServerErrorPayload } from "./types-CimwEFsf.js";
1
+ import { n as ServerErrorInfo, r as ServerErrorPayload } from "./types-mrjoQDOc.js";
2
2
  import { DataResourceKeyInput, FigAssetResourceList, FigNode, Props } from "@bgub/fig";
3
3
  //#region src/payload.d.ts
4
4
  interface PayloadRenderResult {
package/dist/payload.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as deferred, c as streamHighWaterMark, i as createStaticDispatcher, l as withContextValue, n as cloneContextValues, r as componentStack, s as streamFlowBlocked } from "./shared-Bna74_aZ.js";
1
+ import { a as componentStack, d as withContextValue, i as cloneContextValues, l as streamFlowBlocked, n as suppressesImagePreloads, o as createStaticDispatcher, s as deferred, t as imagePreloadFromHostProps, u as streamHighWaterMark } from "./image-preloads-BIFcrqm9.js";
2
2
  import { Fragment, isValidElement } from "@bgub/fig";
3
3
  import { assetResourceDestination, assetResourceKey, checkpointPayloadGraph, clientOnlyHostBehavior, clientReferenceAssets, createPayloadGraphEncodeContext, createRendererDataStore, definePayloadGraphElement, describeInvalidChild, encodePayloadDataEntries, encodePayloadValueWithGraph, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPlainPayloadValue, isPortal, isSuspense, isThenable, isViewTransition, jsonPayloadCodec, readThenable, rollbackPayloadGraph, serializePayloadArray, serializePayloadMap, serializePayloadPlainObject, serializePayloadSet, setCurrentDataStore, setCurrentDispatcher } from "@bgub/fig/internal";
4
4
  //#region src/payload.ts
@@ -56,7 +56,7 @@ function createPayloadRequest(node, options) {
56
56
  request.pingedTasks.push(createTask(request, 0, {
57
57
  kind: "node",
58
58
  value: node
59
- }, /* @__PURE__ */ new Map(), null));
59
+ }, /* @__PURE__ */ new Map(), false, null));
60
60
  const stream = new ReadableStream({
61
61
  start(controller) {
62
62
  request.controller = controller;
@@ -84,11 +84,12 @@ function createPayloadRequest(node, options) {
84
84
  stream
85
85
  };
86
86
  }
87
- function createTask(request, id, value, contextValues, stack) {
87
+ function createTask(request, id, value, contextValues, imagePreloadsSuppressed, stack) {
88
88
  request.pendingTasks += 1;
89
89
  return {
90
90
  contextValues,
91
91
  id,
92
+ imagePreloadsSuppressed,
92
93
  stack,
93
94
  ...value
94
95
  };
@@ -106,6 +107,7 @@ function retryTask(request, task) {
106
107
  dispatcher: null,
107
108
  pendingAssets: [],
108
109
  request,
110
+ imagePreloadsSuppressed: task.imagePreloadsSuppressed,
109
111
  stack: task.stack
110
112
  };
111
113
  try {
@@ -227,7 +229,7 @@ function serializeNodeOrLazy(node, frame, preserveElementIdentity = false) {
227
229
  }
228
230
  function serializeElement(element, frame, preserveIdentity) {
229
231
  const type = element.type;
230
- if (typeof type === "string") return serializeElementModel(element, type, frame, preserveIdentity, childrenTreeProps);
232
+ if (typeof type === "string") return serializeHostElement(element, type, frame, preserveIdentity);
231
233
  if (type === Fragment) return serializeElementModel(element, { $fig: "fragment" }, frame, preserveIdentity, childrenTreeProps);
232
234
  if (isClientReference(type)) return serializeElementModel(element, {
233
235
  $fig: "client",
@@ -242,6 +244,17 @@ function serializeElement(element, frame, preserveIdentity) {
242
244
  if (typeof type === "function") return serializeFunctionComponent(type, element.props, frame);
243
245
  throw new Error("Unsupported Fig element type during payload render.");
244
246
  }
247
+ function serializeHostElement(element, type, frame, preserveIdentity) {
248
+ const preload = imagePreloadFromHostProps(type, element.props, frame.imagePreloadsSuppressed);
249
+ if (preload !== null) frame.pendingAssets.push(...serializeAssetResources(frame.request, preload));
250
+ const previousImagePreloadsSuppressed = frame.imagePreloadsSuppressed;
251
+ frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed || suppressesImagePreloads(type);
252
+ try {
253
+ return serializeElementModel(element, type, frame, preserveIdentity, childrenTreeProps);
254
+ } finally {
255
+ frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed;
256
+ }
257
+ }
245
258
  function serializeElementModel(element, type, frame, preserveIdentity, treeProps = emptyTreeProps) {
246
259
  const id = preserveIdentity ? definePayloadGraphElement(frame.request.graph, element) : void 0;
247
260
  if (typeof id === "object") return id;
@@ -339,7 +352,7 @@ function outlineTask(frame, value, referenceKind, wakeable, scopedAssets = []) {
339
352
  tag: "assets",
340
353
  value: scopedAssets
341
354
  });
342
- const task = createTask(request, id, value, cloneContextValues(frame.contextValues), stackForError(wakeable, frame.stack));
355
+ const task = createTask(request, id, value, cloneContextValues(frame.contextValues), frame.imagePreloadsSuppressed, stackForError(wakeable, frame.stack));
343
356
  wakeable.then(() => pingTask(request, task), () => pingTask(request, task));
344
357
  return {
345
358
  $fig: referenceKind,
@@ -441,11 +454,14 @@ function serializeAssetResource(resource) {
441
454
  case "preload": {
442
455
  const model = {
443
456
  as: resource.as,
444
- href: resource.href,
445
457
  kind: resource.kind
446
458
  };
447
459
  if (resource.crossorigin !== void 0) model.crossorigin = resource.crossorigin;
448
460
  if (resource.fetchpriority !== void 0) model.fetchpriority = resource.fetchpriority;
461
+ if (resource.href !== void 0) model.href = resource.href;
462
+ if (resource.imagesizes !== void 0) model.imagesizes = resource.imagesizes;
463
+ if (resource.imagesrcset !== void 0) model.imagesrcset = resource.imagesrcset;
464
+ if (resource.referrerpolicy !== void 0) model.referrerpolicy = resource.referrerpolicy;
449
465
  if (resource.type !== void 0) model.type = resource.type;
450
466
  return model;
451
467
  }
@@ -1 +1 @@
1
- {"version":3,"file":"payload.js","names":["invalidChildError"],"sources":["../src/payload.ts"],"sourcesContent":["import type { DataResourceKeyInput } from \"@bgub/fig\";\nimport {\n type AwaitedFigNode,\n type FigAssetResource,\n type FigAssetResourceList,\n type FigClientReference,\n type FigContext,\n type FigDataHydrationEntry,\n type FigElement,\n type FigNode,\n Fragment,\n isValidElement,\n type Props,\n} from \"@bgub/fig\";\nimport {\n assetResourceDestination,\n assetResourceKey,\n checkpointPayloadGraph,\n clientOnlyHostBehavior,\n clientReferenceAssets,\n createRendererDataStore,\n createPayloadGraphEncodeContext,\n type DataStore,\n type DataStoreEntrySnapshot,\n definePayloadGraphElement,\n describeInvalidChild,\n encodePayloadDataEntries,\n encodePayloadValueWithGraph,\n isActivity,\n isAssets,\n isClientReference,\n isContext,\n isErrorBoundary,\n isFigAssetResource,\n isPlainPayloadValue,\n isPortal,\n isSuspense,\n isThenable,\n isViewTransition,\n jsonPayloadCodec,\n type PayloadElementModel,\n type PayloadGraphEncodeContext,\n type PayloadModel,\n type PayloadRow,\n type PayloadSpecialModel,\n type RenderDispatcher,\n readThenable,\n rollbackPayloadGraph,\n serializePayloadArray,\n serializePayloadMap,\n serializePayloadPlainObject,\n serializePayloadSet,\n type SerializedAssetResource,\n setCurrentDataStore,\n setCurrentDispatcher,\n type Thenable,\n} from \"@bgub/fig/internal\";\nimport {\n type ContextValues,\n type StackFrame,\n cloneContextValues,\n componentStack,\n createStaticDispatcher,\n type Deferred,\n deferred,\n errorMessage,\n streamFlowBlocked,\n streamHighWaterMark,\n withContextValue,\n} from \"./shared.ts\";\nimport type { ServerErrorInfo, ServerErrorPayload } from \"./types.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\n\nexport interface PayloadRenderResult {\n allReady: Promise<void>;\n contentType: string;\n stream: ReadableStream<Uint8Array>;\n}\n\nexport type PayloadComponent = (\n props: Props & { children?: FigNode },\n) => FigNode;\n\nexport interface PayloadRenderOptions {\n clientReferenceAssets?: (metadata: { id: string }) => FigAssetResourceList;\n componentAssets?: (\n type: PayloadComponent,\n ) => FigAssetResourceList | undefined;\n dataPartition?: DataResourceKeyInput;\n /**\n * Encoded bytes the result stream buffers before row flushing pauses until\n * the consumer reads (rendering itself never pauses; encoded rows wait\n * queued). Defaults to 65536; values below 1 are clamped to 1.\n */\n highWaterMark?: number;\n signal?: AbortSignal;\n /**\n * Decides what crosses the wire when a server render throws, mirroring the\n * HTML renderer's contract: the returned payload is authoritative. Without\n * a handler, development includes the error message and production sends\n * an empty payload.\n */\n onError?: (\n error: unknown,\n info: ServerErrorInfo,\n ) => ServerErrorPayload | undefined;\n}\n\nclass PayloadRequestCancelledError extends Error {\n constructor() {\n super(\"Payload request cancelled.\");\n this.name = \"PayloadRequestCancelledError\";\n }\n}\n\ntype PayloadRequest = {\n allReady: Deferred<void>;\n cleanupAbortListener(): void;\n clientReferenceRows: Map<string, number>;\n clientReferenceAssets?: (metadata: { id: string }) => FigAssetResourceList;\n componentAssets: PayloadRenderOptions[\"componentAssets\"];\n controller: ReadableStreamDefaultController<Uint8Array> | null;\n dataStore: DataStore<object, null>;\n emittedAssetKeys: Set<string>;\n emittedDataKeys: Set<string>;\n graph: PayloadGraphEncodeContext;\n nextRowId: number;\n nextUseId: number;\n onError: PayloadRenderOptions[\"onError\"];\n pendingDataSnapshots: Map<string, DataStoreEntrySnapshot>;\n pendingTasks: number;\n pingedTasks: Task[];\n queuedRows: Uint8Array[];\n // Reentrancy guard: enqueueing inside flushRows can synchronously invoke\n // the stream's pull handler, which must not restart the drain — queuedRows\n // is spliced only after the loop, so a reentrant pass would re-enqueue the\n // same rows.\n flushingRows: boolean;\n status: \"open\" | \"closed\";\n workScheduled: boolean;\n};\n\ntype Task = {\n contextValues: ContextValues;\n id: number;\n stack: StackFrame | null;\n} & TaskValue;\n\ntype TaskValue =\n | { kind: \"node\"; value: FigNode }\n | { kind: \"node-promise\"; value: Thenable<AwaitedFigNode> }\n | { kind: \"promise\"; value: Thenable };\n\ntype Component = PayloadComponent;\n\ntype RenderFrame = {\n contextValues: ContextValues;\n // Built lazily on the first function component; reused for the whole task\n // (the dispatcher reads context through the frame, so it stays current).\n dispatcher: RenderDispatcher | null;\n // Assets discovered during this attempt whose owning row is not yet known.\n // Assets rows carry `for` — the row id whose reveal depends on them — and\n // the owner is only decided at scope exit: a subtree that completes keeps\n // its assets with the enclosing row, while one that suspends or fails takes\n // the assets discovered inside it to its outlined row. Scope exits happen\n // within the same synchronous attempt, so buffering costs no wire latency.\n pendingAssets: SerializedAssetResource[];\n request: PayloadRequest;\n stack: StackFrame | null;\n};\n\nconst errorStacks = new WeakMap<object, StackFrame>();\nconst childrenTreeProps = new Set([\"children\"]);\nconst emptyTreeProps = new Set<string>();\nconst suspenseTreeProps = new Set([\"children\", \"fallback\"]);\n\nexport function renderToPayloadStream(\n node: FigNode,\n options: PayloadRenderOptions = {},\n): PayloadRenderResult {\n const { request, stream } = createPayloadRequest(node, options);\n return {\n allReady: request.allReady.promise,\n contentType: jsonPayloadCodec.contentType,\n stream,\n };\n}\n\nfunction createPayloadRequest(\n node: FigNode,\n options: PayloadRenderOptions,\n): { request: PayloadRequest; stream: ReadableStream<Uint8Array> } {\n throwIfAborted(options.signal);\n\n const pendingDataSnapshots = new Map<string, DataStoreEntrySnapshot>();\n const request: PayloadRequest = {\n allReady: deferred<void>(),\n cleanupAbortListener: () => undefined,\n clientReferenceRows: new Map(),\n clientReferenceAssets: options.clientReferenceAssets,\n componentAssets: options.componentAssets,\n controller: null,\n dataStore: createRendererDataStore<object, null>({\n getLane: () => null,\n onEntryChange: (entry: DataStoreEntrySnapshot) => {\n pendingDataSnapshots.set(entry.canonicalKey, entry);\n },\n partition: options.dataPartition,\n schedule: () => undefined,\n }),\n emittedAssetKeys: new Set(),\n emittedDataKeys: new Set(),\n graph: createPayloadGraphEncodeContext(),\n nextRowId: 1,\n nextUseId: 0,\n onError: options.onError,\n pendingDataSnapshots,\n pendingTasks: 0,\n pingedTasks: [],\n queuedRows: [],\n flushingRows: false,\n status: \"open\",\n workScheduled: false,\n };\n // allReady also rejects through the stream when a consumer cancels (the\n // normal client-disconnect path); the pre-attached no-op handler keeps it\n // from becoming an unhandled rejection for callers that do not await it\n // (await-ers still observe the rejection).\n void request.allReady.promise.catch(() => undefined);\n\n request.pingedTasks.push(\n createTask(request, 0, { kind: \"node\", value: node }, new Map(), null),\n );\n\n const stream = new ReadableStream<Uint8Array>(\n {\n start(controller) {\n request.controller = controller;\n flushRows(request);\n },\n pull() {\n // The consumer drained below the high-water mark: resume flushing\n // rows that queued while the flow was blocked.\n flushRows(request);\n },\n cancel(reason) {\n abortPayloadRequest(request, reason);\n },\n },\n new ByteLengthQueuingStrategy({\n highWaterMark: streamHighWaterMark(options.highWaterMark),\n }),\n );\n\n const signal = options.signal;\n if (signal !== undefined) {\n const abortListener = () => abortPayloadRequest(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 scheduleWork(request);\n\n return { request, stream };\n}\n\nfunction createTask(\n request: PayloadRequest,\n id: number,\n value: TaskValue,\n contextValues: ContextValues,\n stack: StackFrame | null,\n): Task {\n request.pendingTasks += 1;\n return { contextValues, id, stack, ...value };\n}\n\nfunction performWork(request: PayloadRequest): 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 flushRows(request);\n}\n\nfunction retryTask(request: PayloadRequest, task: Task): void {\n const frame: RenderFrame = {\n contextValues: cloneContextValues(task.contextValues),\n dispatcher: null,\n pendingAssets: [],\n request,\n stack: task.stack,\n };\n\n try {\n let value: PayloadModel;\n switch (task.kind) {\n case \"node\":\n value = serializeNode(task.value, frame);\n break;\n case \"node-promise\":\n value = serializeNode(readThenable(task.value), frame);\n break;\n case \"promise\":\n value = serializeValue(readThenable(task.value), frame);\n break;\n }\n flushFrameAssets(frame, task.id);\n emitDataRows(request);\n emitRow(request, { id: task.id, tag: \"model\", value });\n finishTask(request);\n } catch (error) {\n if (isThenable(error)) {\n // The retry re-discovers nothing already in emittedAssetKeys, so this\n // attempt's assets must ship now; the task still settles into task.id.\n flushFrameAssets(frame, task.id);\n error.then(\n () => pingTask(request, task),\n () => pingTask(request, task),\n );\n return;\n }\n\n flushFrameAssets(frame, task.id);\n emitRow(request, {\n id: task.id,\n tag: \"error\",\n value: errorRowPayload(request, error, task.stack),\n });\n finishTask(request);\n }\n}\n\nfunction finishTask(request: PayloadRequest): void {\n request.pendingTasks -= 1;\n if (request.pendingTasks === 0) request.allReady.resolve(undefined);\n}\n\nfunction emitDataRows(request: PayloadRequest): void {\n const entries: FigDataHydrationEntry[] = [];\n\n for (const snapshot of request.pendingDataSnapshots.values()) {\n // Stream only settled values. A \"refreshing\" entry exposes a transient stale\n // value while its background refresh is in flight; emitting it would mark the\n // key emitted forever and permanently suppress the fresh value. Skipping it\n // lets the entry stream once its refresh settles.\n if (!snapshot.hasValue || snapshot.status === \"refreshing\") continue;\n\n const key = snapshot.canonicalKey;\n if (request.emittedDataKeys.has(key)) {\n request.pendingDataSnapshots.delete(snapshot.canonicalKey);\n continue;\n }\n\n request.emittedDataKeys.add(key);\n request.pendingDataSnapshots.delete(snapshot.canonicalKey);\n entries.push({ key: snapshot.key, value: snapshot.value });\n }\n\n if (entries.length > 0) {\n emitRow(request, { tag: \"data\", value: encodePayloadDataEntries(entries) });\n }\n}\n\nfunction flushFrameAssets(frame: RenderFrame, rowId: number): void {\n if (frame.pendingAssets.length === 0) return;\n const value = frame.pendingAssets.splice(0);\n emitRow(frame.request, { for: rowId, tag: \"assets\", value });\n}\n\nfunction createPayloadDispatcher(frame: RenderFrame): RenderDispatcher {\n const dispatcher = createStaticDispatcher({\n contextValues: frame.contextValues,\n externalStoreError:\n \"useSyncExternalStore requires getServerSnapshot during payload render.\",\n readPromise: readThenable,\n readData(resource, args) {\n return frame.request.dataStore.readData(resource, args, frame);\n },\n preloadData(resource, args) {\n frame.request.dataStore.preloadData(resource, ...args);\n },\n useId() {\n const id = `fig-pl-${frame.request.nextUseId.toString(32)}`;\n frame.request.nextUseId += 1;\n return id;\n },\n updateError: \"State updates are not allowed during payload render.\",\n });\n\n // Serialized components are render-only: they never re-run on the client,\n // so state, effects, and interactivity are meaningless there — dev throws\n // at first use instead of silently freezing initial state into the wire.\n // Reads stay server-safe: readContext/readData/readPromise/preloadData,\n // useMemo, useId, and useSyncExternalStore's getServerSnapshot path (a\n // read, not a subscription — the static dispatcher already requires it).\n if (__DEV__) {\n const throwClientApi = (hook: string) => (): never => {\n throw new Error(\n `${hook} cannot be used during payload render: serialized components are render-only. Move state, effects, and interactivity into a client reference.`,\n );\n };\n dispatcher.useState = throwClientApi(\"useState\");\n dispatcher.useActionState = throwClientApi(\"useActionState\");\n dispatcher.useTransition = throwClientApi(\"useTransition\");\n dispatcher.useStableEvent = throwClientApi(\"useStableEvent\");\n dispatcher.useReactive = throwClientApi(\"useReactive\");\n dispatcher.useBeforePaint = throwClientApi(\"useBeforePaint\");\n dispatcher.useBeforeLayout = throwClientApi(\"useBeforeLayout\");\n }\n\n return dispatcher;\n}\n\nfunction serializeNode(node: FigNode, frame: RenderFrame): PayloadModel {\n if (Array.isArray(node)) {\n return flattenChildArrays(node).map((child) =>\n serializeNodeOrLazy(child, frame),\n );\n }\n\n if (node === null || node === undefined || typeof node === \"boolean\") {\n return node === undefined ? { $fig: \"undefined\" } : node;\n }\n\n if (typeof node === \"string\" || typeof node === \"number\") {\n return node;\n }\n\n if (isPortal(node)) return null;\n if (isValidElement(node)) return serializeElement(node, frame, false);\n if (isThenable(node)) {\n return outlineTask(\n frame,\n { kind: \"node-promise\", value: node },\n \"promise\",\n node,\n );\n }\n\n throw invalidChildError(node);\n}\n\nfunction serializeNodeOrLazy(\n node: FigNode,\n frame: RenderFrame,\n preserveElementIdentity = false,\n): PayloadModel {\n const graphCheckpoint = checkpointPayloadGraph(frame.request.graph);\n const assetCheckpoint = frame.pendingAssets.length;\n try {\n if (!isValidElement(node)) return serializeNode(node, frame);\n return serializeElement(node, frame, preserveElementIdentity);\n } catch (error) {\n rollbackPayloadGraph(frame.request.graph, graphCheckpoint);\n // Assets discovered inside this subtree belong to the outlined row, not\n // the enclosing one: gating the enclosing row would hold the whole tree's\n // reveal on stylesheets only the hole's content needs.\n const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);\n if (isThenable(error)) {\n return outlineTask(\n frame,\n { kind: \"node\", value: node },\n \"lazy\",\n error,\n scopedAssets,\n );\n }\n return outlineError(frame, error, \"lazy\", scopedAssets);\n }\n}\n\nfunction serializeElement(\n element: FigElement,\n frame: RenderFrame,\n preserveIdentity: boolean,\n): PayloadModel {\n const type = element.type;\n\n if (typeof type === \"string\") {\n return serializeElementModel(\n element,\n type,\n frame,\n preserveIdentity,\n childrenTreeProps,\n );\n }\n\n if (type === Fragment) {\n return serializeElementModel(\n element,\n { $fig: \"fragment\" },\n frame,\n preserveIdentity,\n childrenTreeProps,\n );\n }\n\n if (isClientReference(type)) {\n const clientId = emitClientReference(frame.request, type);\n return serializeElementModel(\n element,\n { $fig: \"client\", id: clientId },\n frame,\n preserveIdentity,\n );\n }\n\n if (isContext(type)) {\n return serializeContextProvider(type, element.props, frame);\n }\n\n if (isAssets(type)) {\n return serializeAssets(element.props, frame);\n }\n\n if (isSuspense(type)) {\n return serializeElementModel(\n element,\n { $fig: \"suspense\" },\n frame,\n preserveIdentity,\n suspenseTreeProps,\n );\n }\n\n if (isErrorBoundary(type)) {\n return serializeNode(element.props.children, frame);\n }\n\n if (isActivity(type)) {\n return serializeNode(element.props.children, frame);\n }\n\n if (isViewTransition(type)) {\n return serializeElementModel(\n element,\n { $fig: \"view-transition\" },\n frame,\n preserveIdentity,\n childrenTreeProps,\n );\n }\n\n if (typeof type === \"function\") {\n return serializeFunctionComponent(type, element.props, frame);\n }\n\n throw new Error(\"Unsupported Fig element type during payload render.\");\n}\n\nfunction serializeElementModel(\n element: FigElement,\n type: PayloadElementModel[\"type\"],\n frame: RenderFrame,\n preserveIdentity: boolean,\n treeProps: ReadonlySet<string> = emptyTreeProps,\n): PayloadModel {\n const id = preserveIdentity\n ? definePayloadGraphElement(frame.request.graph, element)\n : undefined;\n if (typeof id === \"object\") return id;\n const model: PayloadElementModel = {\n $fig: \"element\",\n key: element.key,\n props: serializeProps(\n element.props,\n frame,\n treeProps,\n typeof type === \"string\",\n ),\n type,\n };\n if (id !== undefined) model.id = id;\n return model;\n}\n\nfunction serializeFunctionComponent(\n type: Component,\n props: Props,\n frame: RenderFrame,\n): PayloadModel {\n const assetCheckpoint = frame.pendingAssets.length;\n frame.pendingAssets.push(\n ...serializeAssetResources(\n frame.request,\n frame.request.componentAssets?.(type),\n ),\n );\n frame.dispatcher ??= createPayloadDispatcher(frame);\n const previousDispatcher = setCurrentDispatcher(frame.dispatcher);\n const previousDataStore = setCurrentDataStore(frame.request.dataStore);\n const previousStack = frame.stack;\n frame.stack = { name: type.name || \"Anonymous\", parent: previousStack };\n\n try {\n if (\n __DEV__ &&\n \"$$typeof\" in type &&\n type.$$typeof === Symbol.for(\"fig.data-resource\")\n ) {\n throw new Error(\n \"Payload components cannot be rendered inside Payload. Render the underlying server component directly, or mount separate Payload components from the client tree.\",\n );\n }\n const result = type(props);\n if (isThenable(result)) {\n const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);\n return outlineTask(\n frame,\n { kind: \"node-promise\", value: result },\n \"promise\",\n result,\n scopedAssets,\n );\n }\n return serializeNode(result, frame);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n } finally {\n frame.stack = previousStack;\n setCurrentDataStore(previousDataStore);\n setCurrentDispatcher(previousDispatcher);\n }\n}\n\nfunction serializeContextProvider(\n context: FigContext<unknown>,\n props: Props,\n frame: RenderFrame,\n): PayloadModel {\n return withContextValue(frame.contextValues, context, props.value, () =>\n serializeNode(props.children, frame),\n );\n}\n\nfunction serializeAssets(props: Props, frame: RenderFrame): PayloadModel {\n // Buffered, not emitted: the owning row id is decided at scope exit (see\n // RenderFrame.pendingAssets). Dedupe happens here, so a retried subtree\n // does not re-buffer assets an earlier attempt already shipped.\n frame.pendingAssets.push(\n ...serializeAssetResources(frame.request, props.assets),\n );\n return serializeNode(props.children, frame);\n}\n\nfunction serializeProps(\n props: Props,\n frame: RenderFrame,\n treeProps: ReadonlySet<string>,\n hostElement = false,\n): PayloadModel {\n const clientOnlyBehavior = hostElement\n ? clientOnlyHostBehavior(props)\n : undefined;\n if (clientOnlyBehavior !== undefined) {\n throw new Error(\n `Client-only host behavior from ${clientOnlyBehavior} cannot be ` +\n \"serialized in a payload; move it into a client reference.\",\n );\n }\n\n const value: Record<string, PayloadModel> = {};\n for (const name of Object.keys(props)) {\n // A host `mix` already resolved into these props at element creation;\n // the marker itself holds descriptors (functions) and stays server-side.\n // Component `mix` props still serialize (and fail loudly on functions).\n if (hostElement && name === \"mix\") continue;\n const child = props[name];\n value[name] = treeProps.has(name)\n ? serializeTreeProp(child, frame)\n : serializeValue(child, frame);\n }\n return {\n $fig: \"object\",\n value,\n };\n}\n\nfunction serializeTreeProp(value: FigNode, frame: RenderFrame): PayloadModel {\n if (Array.isArray(value)) {\n return flattenChildArrays(value).map((child) =>\n serializeNodeOrLazy(child, frame),\n );\n }\n return serializeNodeOrLazy(value, frame);\n}\n\nfunction serializeValue(value: unknown, frame: RenderFrame): PayloadModel {\n // Scalar values return from the shared encoder before any graph access, so\n // reusing the request graph here is free (no per-value context allocation).\n if (isPlainPayloadValue(value)) {\n return encodePayloadValueWithGraph(value, frame.request.graph);\n }\n\n if (isClientReference(value)) {\n return { $fig: \"client\", id: emitClientReference(frame.request, value) };\n }\n\n if (isValidElement(value)) return serializeNodeOrLazy(value, frame, true);\n if (isPortal(value)) return null;\n if (isThenable(value)) {\n return outlineTask(frame, { kind: \"promise\", value }, \"promise\", value);\n }\n if (typeof value === \"function\") {\n throw new Error(\"Functions cannot be passed to client references.\");\n }\n\n if (typeof value === \"object\" && value !== null) {\n if (value instanceof Date) {\n return encodePayloadValueWithGraph(value, frame.request.graph);\n }\n if (value instanceof Map) {\n return serializePayloadMap(value, frame.request.graph, ([key, item]) => [\n serializeValue(key, frame),\n serializeValue(item, frame),\n ]);\n }\n if (value instanceof Set) {\n return serializePayloadSet(value, frame.request.graph, (item) =>\n serializeValue(item, frame),\n );\n }\n\n if (Array.isArray(value)) {\n return serializePayloadArray(\n value,\n frame.request.graph,\n () => value,\n (item) => serializeValue(item, frame),\n );\n }\n\n return serializePayloadPlainObject(value, frame.request.graph, (child) =>\n serializeValue(child, frame),\n );\n }\n\n throw new Error(`Cannot serialize ${typeof value} into the payload.`);\n}\nfunction outlineTask(\n frame: RenderFrame,\n value: TaskValue,\n referenceKind: \"lazy\" | \"promise\",\n wakeable: Thenable,\n scopedAssets: SerializedAssetResource[] = [],\n): PayloadSpecialModel {\n const request = frame.request;\n const id = request.nextRowId++;\n if (scopedAssets.length > 0) {\n emitRow(request, { for: id, tag: \"assets\", value: scopedAssets });\n }\n const task = createTask(\n request,\n id,\n value,\n cloneContextValues(frame.contextValues),\n stackForError(wakeable, frame.stack),\n );\n\n wakeable.then(\n () => pingTask(request, task),\n () => pingTask(request, task),\n );\n\n return { $fig: referenceKind, id };\n}\n\nfunction outlineError(\n frame: RenderFrame,\n error: unknown,\n referenceKind: \"lazy\" | \"promise\",\n scopedAssets: SerializedAssetResource[],\n): PayloadSpecialModel {\n const request = frame.request;\n const id = request.nextRowId++;\n // Assets first so a decoder that drops gates on error rows sees the row\n // order it expects; the assets still preload even though the row failed.\n if (scopedAssets.length > 0) {\n emitRow(request, { for: id, tag: \"assets\", value: scopedAssets });\n }\n emitRow(request, {\n id,\n tag: \"error\",\n value: errorRowPayload(request, error, frame.stack),\n });\n return { $fig: referenceKind, id };\n}\n\n// The onError return value is authoritative, like the HTML renderer's\n// reportBoundaryError: message crosses the wire only when the handler says\n// so. Without a handler, development keeps the real message for debugging\n// (payload errors never re-execute on the client, so the wire is the only\n// surface) and production sends an empty payload.\nfunction errorRowPayload(\n request: PayloadRequest,\n error: unknown,\n stack: StackFrame | null,\n): ServerErrorPayload {\n const info = {\n componentStack: componentStack(stackForError(error, stack)),\n };\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\" || error === null) 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 (typeof error !== \"object\" || error === null) return fallback;\n return errorStacks.get(error) ?? fallback;\n}\n\nfunction clientReferenceExportName(id: string): string | undefined {\n const hashIndex = id.lastIndexOf(\"#\");\n if (hashIndex === -1) return undefined;\n return id.slice(hashIndex + 1) || undefined;\n}\n\nfunction emitClientReference(\n request: PayloadRequest,\n reference: FigClientReference,\n): number {\n const existing = request.clientReferenceRows.get(reference.id);\n if (existing !== undefined) return existing;\n\n // Resolve assets BEFORE reserving the row id and recording the mapping. A lazy\n // resource thunk (bundler-manifest resolution) may throw; reserving first would\n // leave a row id mapped but never emitted, so a later retry returns the cached\n // id and the client suspends on a chunk that never arrives. Resolving first\n // lets the throw propagate as an ordinary serialization error with no poisoned\n // mapping, so the reference can be retried cleanly.\n const assets = serializeAssetResources(\n request,\n collectClientReferenceAssets(request, reference),\n );\n const value: Extract<PayloadRow, { tag: \"client\" }>[\"value\"] = {\n id: reference.id,\n };\n if (assets.length > 0) value.assets = assets;\n // The \"<module>#<export>\" authoring convention is split here, once, so the\n // wire is self-describing and the client never string-parses ids.\n const exportName = clientReferenceExportName(reference.id);\n if (exportName !== undefined) value.exportName = exportName;\n if (reference.ssr !== undefined) value.ssr = true;\n const id = request.nextRowId++;\n request.clientReferenceRows.set(reference.id, id);\n emitRow(request, {\n id,\n tag: \"client\",\n value,\n });\n return id;\n}\n\nfunction serializeAssetResources(\n request: PayloadRequest,\n value: unknown,\n): SerializedAssetResource[] {\n const input = isFigAssetResource(value)\n ? [value]\n : Array.isArray(value)\n ? value\n : [];\n const resources: SerializedAssetResource[] = [];\n\n for (const resource of input) {\n if (!isFigAssetResource(resource)) continue;\n // Delivery assets are request-global and persistent, so the first\n // definition wins. Metadata is owner-scoped and may legitimately repeat\n // with a different value in another row; the decoder retains those\n // declarations until their owning tree commits.\n if (assetResourceDestination(resource) === \"stream\") {\n const key = assetResourceKey(resource);\n if (request.emittedAssetKeys.has(key)) continue;\n request.emittedAssetKeys.add(key);\n }\n resources.push(serializeAssetResource(resource));\n }\n\n return resources;\n}\n\nfunction collectClientReferenceAssets(\n request: PayloadRequest,\n reference: FigClientReference,\n): readonly FigAssetResource[] {\n const resources = [...clientReferenceAssets(reference)];\n const resolved = request.clientReferenceAssets?.({ id: reference.id });\n if (resolved === undefined) return resources;\n if (isFigAssetResource(resolved)) return [...resources, resolved];\n return Array.isArray(resolved) ? [...resources, ...resolved] : resources;\n}\n\nfunction serializeAssetResource(\n resource: FigAssetResource,\n): SerializedAssetResource {\n // Delivery assets intentionally omit author-supplied `key` and dedupe by\n // their concrete URL. Metadata keeps its owner-local identity when needed.\n // Omitted `undefined` optionals are part of the wire contract, hence the\n // assign-if-defined shape.\n switch (resource.kind) {\n case \"stylesheet\": {\n const model: SerializedAssetResource = {\n href: resource.href,\n kind: resource.kind,\n };\n if (resource.crossorigin !== undefined) {\n model.crossorigin = resource.crossorigin;\n }\n if (resource.media !== undefined) model.media = resource.media;\n if (resource.precedence !== undefined) {\n model.precedence = resource.precedence;\n }\n return model;\n }\n case \"preload\": {\n const model: SerializedAssetResource = {\n as: resource.as,\n href: resource.href,\n kind: resource.kind,\n };\n if (resource.crossorigin !== undefined) {\n model.crossorigin = resource.crossorigin;\n }\n if (resource.fetchpriority !== undefined) {\n model.fetchpriority = resource.fetchpriority;\n }\n if (resource.type !== undefined) model.type = resource.type;\n return model;\n }\n case \"modulepreload\": {\n const model: SerializedAssetResource = {\n href: resource.href,\n kind: resource.kind,\n };\n if (resource.crossorigin !== undefined) {\n model.crossorigin = resource.crossorigin;\n }\n if (resource.fetchpriority !== undefined) {\n model.fetchpriority = resource.fetchpriority;\n }\n return model;\n }\n case \"script\": {\n const model: SerializedAssetResource = {\n kind: resource.kind,\n src: resource.src,\n };\n if (resource.async !== undefined) model.async = resource.async;\n if (resource.crossorigin !== undefined) {\n model.crossorigin = resource.crossorigin;\n }\n if (resource.defer !== undefined) model.defer = resource.defer;\n if (resource.module !== undefined) model.module = resource.module;\n return model;\n }\n case \"font\": {\n const model: SerializedAssetResource = {\n href: resource.href,\n kind: resource.kind,\n type: resource.type,\n };\n if (resource.crossorigin !== undefined) {\n model.crossorigin = resource.crossorigin;\n }\n if (resource.fetchpriority !== undefined) {\n model.fetchpriority = resource.fetchpriority;\n }\n return model;\n }\n case \"preconnect\": {\n const model: SerializedAssetResource = {\n href: resource.href,\n kind: resource.kind,\n };\n if (resource.crossorigin !== undefined) {\n model.crossorigin = resource.crossorigin;\n }\n return model;\n }\n case \"title\":\n return { kind: resource.kind, value: resource.value };\n case \"meta\": {\n const model: SerializedAssetResource = { kind: resource.kind };\n if (resource.charset !== undefined) model.charset = resource.charset;\n if (resource.content !== undefined) model.content = resource.content;\n if (resource[\"http-equiv\"] !== undefined) {\n model[\"http-equiv\"] = resource[\"http-equiv\"];\n }\n if (resource.key !== undefined) model.key = resource.key;\n if (resource.name !== undefined) model.name = resource.name;\n if (resource.property !== undefined) model.property = resource.property;\n return model;\n }\n }\n}\n\nfunction emitRow(request: PayloadRequest, row: PayloadRow): void {\n request.queuedRows.push(jsonPayloadCodec.encodeRow(row));\n flushRows(request);\n}\n\nfunction pingTask(request: PayloadRequest, task: Task): void {\n if (request.status === \"closed\") return;\n request.pingedTasks.push(task);\n scheduleWork(request);\n}\n\nfunction scheduleWork(request: PayloadRequest): void {\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 flushRows(request: PayloadRequest): void {\n if (request.controller === null || request.status === \"closed\") return;\n if (request.flushingRows) return;\n\n request.flushingRows = true;\n try {\n // Row-granular gating: rows already encode one complete wire row each,\n // so stopping between rows keeps every chunk parse-safe for consumers\n // that interleave per chunk.\n let flushed = 0;\n while (\n flushed < request.queuedRows.length &&\n !streamFlowBlocked(request.controller)\n ) {\n request.controller.enqueue(request.queuedRows[flushed]);\n flushed += 1;\n }\n if (flushed === request.queuedRows.length) request.queuedRows.length = 0;\n else if (flushed > 0) {\n request.queuedRows = request.queuedRows.slice(flushed);\n }\n } finally {\n request.flushingRows = false;\n }\n\n // Deliberately not conditioned on flow: close() only marks the end of the\n // queue, so a full queue with no rows left to write still closes here.\n if (request.pendingTasks === 0 && request.queuedRows.length === 0) {\n request.status = \"closed\";\n request.cleanupAbortListener();\n request.dataStore.dispose();\n request.controller.close();\n }\n}\n\nfunction closeWithError(request: PayloadRequest, error: unknown): void {\n if (request.status === \"closed\") return;\n request.cleanupAbortListener();\n request.status = \"closed\";\n request.dataStore.dispose();\n request.allReady.reject(error);\n request.controller?.error(error);\n}\n\nfunction abortPayloadRequest(request: PayloadRequest, reason?: unknown): void {\n closeWithError(request, reason ?? new PayloadRequestCancelledError());\n}\n\n// Wire-format flattening only: unlike the shared collectChildren, this keeps\n// empty children and does NOT merge adjacent text — the client decodes rows\n// and re-collects children itself, so merging here would double-apply. Flat\n// input (the common case) is returned untouched.\nfunction flattenChildArrays(children: FigNode[]): FigNode[] {\n if (!children.some(Array.isArray)) return children;\n\n const collected: FigNode[] = [];\n for (const child of children) {\n if (Array.isArray(child)) {\n for (const nested of flattenChildArrays(child)) collected.push(nested);\n } else {\n collected.push(child);\n }\n }\n return collected;\n}\n\nfunction invalidChildError(value: unknown): Error {\n return new Error(\n `Invalid Fig child in payload render: ${describeInvalidChild(value)}.`,\n );\n}\n\nfunction throwIfAborted(signal?: AbortSignal | null): void {\n if (signal?.aborted) throw new PayloadRequestCancelledError();\n}\n"],"mappings":";;;;AA+GA,IAAM,+BAAN,cAA2C,MAAM;CAC/C,cAAc;EACZ,MAAM,4BAA4B;EAClC,KAAK,OAAO;CACd;AACF;AA0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AAS,OAAO,KAAK;CAC7B,QAAQ,YAAY,MAAM,KAAK;AACjC;AAEA,SAAS,oBAAoB,SAAyB,QAAwB;CAC5E,eAAe,SAAS,UAAU,IAAI,6BAA6B,CAAC;AACtE;AAMA,SAAS,mBAAmB,UAAgC;CAC1D,IAAI,CAAC,SAAS,KAAK,MAAM,OAAO,GAAG,OAAO;CAE1C,MAAM,YAAuB,CAAC;CAC9B,KAAK,MAAM,SAAS,UAClB,IAAI,MAAM,QAAQ,KAAK,GACrB,KAAK,MAAM,UAAU,mBAAmB,KAAK,GAAG,UAAU,KAAK,MAAM;MAErE,UAAU,KAAK,KAAK;CAGxB,OAAO;AACT;AAEA,SAASA,oBAAkB,OAAuB;CAChD,uBAAO,IAAI,MACT,wCAAwC,qBAAqB,KAAK,EAAE,EACtE;AACF;AAEA,SAAS,eAAe,QAAmC;CACzD,IAAI,QAAQ,SAAS,MAAM,IAAI,6BAA6B;AAC9D"}
1
+ {"version":3,"file":"payload.js","names":["invalidChildError"],"sources":["../src/payload.ts"],"sourcesContent":["import type { DataResourceKeyInput } from \"@bgub/fig\";\nimport {\n type AwaitedFigNode,\n type FigAssetResource,\n type FigAssetResourceList,\n type FigClientReference,\n type FigContext,\n type FigDataHydrationEntry,\n type FigElement,\n type FigNode,\n Fragment,\n isValidElement,\n type Props,\n} from \"@bgub/fig\";\nimport {\n assetResourceDestination,\n assetResourceKey,\n checkpointPayloadGraph,\n clientOnlyHostBehavior,\n clientReferenceAssets,\n createRendererDataStore,\n createPayloadGraphEncodeContext,\n type DataStore,\n type DataStoreEntrySnapshot,\n definePayloadGraphElement,\n describeInvalidChild,\n encodePayloadDataEntries,\n encodePayloadValueWithGraph,\n isActivity,\n isAssets,\n isClientReference,\n isContext,\n isErrorBoundary,\n isFigAssetResource,\n isPlainPayloadValue,\n isPortal,\n isSuspense,\n isThenable,\n isViewTransition,\n jsonPayloadCodec,\n type PayloadElementModel,\n type PayloadGraphEncodeContext,\n type PayloadModel,\n type PayloadRow,\n type PayloadSpecialModel,\n type RenderDispatcher,\n readThenable,\n rollbackPayloadGraph,\n serializePayloadArray,\n serializePayloadMap,\n serializePayloadPlainObject,\n serializePayloadSet,\n type SerializedAssetResource,\n setCurrentDataStore,\n setCurrentDispatcher,\n type Thenable,\n} from \"@bgub/fig/internal\";\nimport {\n type ContextValues,\n type StackFrame,\n cloneContextValues,\n componentStack,\n createStaticDispatcher,\n type Deferred,\n deferred,\n errorMessage,\n streamFlowBlocked,\n streamHighWaterMark,\n withContextValue,\n} from \"./shared.ts\";\nimport {\n imagePreloadFromHostProps,\n suppressesImagePreloads,\n} from \"./image-preloads.ts\";\nimport type { ServerErrorInfo, ServerErrorPayload } from \"./types.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\n\nexport interface PayloadRenderResult {\n allReady: Promise<void>;\n contentType: string;\n stream: ReadableStream<Uint8Array>;\n}\n\nexport type PayloadComponent = (\n props: Props & { children?: FigNode },\n) => FigNode;\n\nexport interface PayloadRenderOptions {\n clientReferenceAssets?: (metadata: { id: string }) => FigAssetResourceList;\n componentAssets?: (\n type: PayloadComponent,\n ) => FigAssetResourceList | undefined;\n dataPartition?: DataResourceKeyInput;\n /**\n * Encoded bytes the result stream buffers before row flushing pauses until\n * the consumer reads (rendering itself never pauses; encoded rows wait\n * queued). Defaults to 65536; values below 1 are clamped to 1.\n */\n highWaterMark?: number;\n signal?: AbortSignal;\n /**\n * Decides what crosses the wire when a server render throws, mirroring the\n * HTML renderer's contract: the returned payload is authoritative. Without\n * a handler, development includes the error message and production sends\n * an empty payload.\n */\n onError?: (\n error: unknown,\n info: ServerErrorInfo,\n ) => ServerErrorPayload | undefined;\n}\n\nclass PayloadRequestCancelledError extends Error {\n constructor() {\n super(\"Payload request cancelled.\");\n this.name = \"PayloadRequestCancelledError\";\n }\n}\n\ntype PayloadRequest = {\n allReady: Deferred<void>;\n cleanupAbortListener(): void;\n clientReferenceRows: Map<string, number>;\n clientReferenceAssets?: (metadata: { id: string }) => FigAssetResourceList;\n componentAssets: PayloadRenderOptions[\"componentAssets\"];\n controller: ReadableStreamDefaultController<Uint8Array> | null;\n dataStore: DataStore<object, null>;\n emittedAssetKeys: Set<string>;\n emittedDataKeys: Set<string>;\n graph: PayloadGraphEncodeContext;\n nextRowId: number;\n nextUseId: number;\n onError: PayloadRenderOptions[\"onError\"];\n pendingDataSnapshots: Map<string, DataStoreEntrySnapshot>;\n pendingTasks: number;\n pingedTasks: Task[];\n queuedRows: Uint8Array[];\n // Reentrancy guard: enqueueing inside flushRows can synchronously invoke\n // the stream's pull handler, which must not restart the drain — queuedRows\n // is spliced only after the loop, so a reentrant pass would re-enqueue the\n // same rows.\n flushingRows: boolean;\n status: \"open\" | \"closed\";\n workScheduled: boolean;\n};\n\ntype Task = {\n contextValues: ContextValues;\n id: number;\n imagePreloadsSuppressed: boolean;\n stack: StackFrame | null;\n} & TaskValue;\n\ntype TaskValue =\n | { kind: \"node\"; value: FigNode }\n | { kind: \"node-promise\"; value: Thenable<AwaitedFigNode> }\n | { kind: \"promise\"; value: Thenable };\n\ntype Component = PayloadComponent;\n\ntype RenderFrame = {\n contextValues: ContextValues;\n // Built lazily on the first function component; reused for the whole task\n // (the dispatcher reads context through the frame, so it stays current).\n dispatcher: RenderDispatcher | null;\n // Assets discovered during this attempt whose owning row is not yet known.\n // Assets rows carry `for` — the row id whose reveal depends on them — and\n // the owner is only decided at scope exit: a subtree that completes keeps\n // its assets with the enclosing row, while one that suspends or fails takes\n // the assets discovered inside it to its outlined row. Scope exits happen\n // within the same synchronous attempt, so buffering costs no wire latency.\n pendingAssets: SerializedAssetResource[];\n request: PayloadRequest;\n imagePreloadsSuppressed: boolean;\n stack: StackFrame | null;\n};\n\nconst errorStacks = new WeakMap<object, StackFrame>();\nconst childrenTreeProps = new Set([\"children\"]);\nconst emptyTreeProps = new Set<string>();\nconst suspenseTreeProps = new Set([\"children\", \"fallback\"]);\n\nexport function renderToPayloadStream(\n node: FigNode,\n options: PayloadRenderOptions = {},\n): PayloadRenderResult {\n const { request, stream } = createPayloadRequest(node, options);\n return {\n allReady: request.allReady.promise,\n contentType: jsonPayloadCodec.contentType,\n stream,\n };\n}\n\nfunction createPayloadRequest(\n node: FigNode,\n options: PayloadRenderOptions,\n): { request: PayloadRequest; stream: ReadableStream<Uint8Array> } {\n throwIfAborted(options.signal);\n\n const pendingDataSnapshots = new Map<string, DataStoreEntrySnapshot>();\n const request: PayloadRequest = {\n allReady: deferred<void>(),\n cleanupAbortListener: () => undefined,\n clientReferenceRows: new Map(),\n clientReferenceAssets: options.clientReferenceAssets,\n componentAssets: options.componentAssets,\n controller: null,\n dataStore: createRendererDataStore<object, null>({\n getLane: () => null,\n onEntryChange: (entry: DataStoreEntrySnapshot) => {\n pendingDataSnapshots.set(entry.canonicalKey, entry);\n },\n partition: options.dataPartition,\n schedule: () => undefined,\n }),\n emittedAssetKeys: new Set(),\n emittedDataKeys: new Set(),\n graph: createPayloadGraphEncodeContext(),\n nextRowId: 1,\n nextUseId: 0,\n onError: options.onError,\n pendingDataSnapshots,\n pendingTasks: 0,\n pingedTasks: [],\n queuedRows: [],\n flushingRows: false,\n status: \"open\",\n workScheduled: false,\n };\n // allReady also rejects through the stream when a consumer cancels (the\n // normal client-disconnect path); the pre-attached no-op handler keeps it\n // from becoming an unhandled rejection for callers that do not await it\n // (await-ers still observe the rejection).\n void request.allReady.promise.catch(() => undefined);\n\n request.pingedTasks.push(\n createTask(\n request,\n 0,\n { kind: \"node\", value: node },\n new Map(),\n false,\n null,\n ),\n );\n\n const stream = new ReadableStream<Uint8Array>(\n {\n start(controller) {\n request.controller = controller;\n flushRows(request);\n },\n pull() {\n // The consumer drained below the high-water mark: resume flushing\n // rows that queued while the flow was blocked.\n flushRows(request);\n },\n cancel(reason) {\n abortPayloadRequest(request, reason);\n },\n },\n new ByteLengthQueuingStrategy({\n highWaterMark: streamHighWaterMark(options.highWaterMark),\n }),\n );\n\n const signal = options.signal;\n if (signal !== undefined) {\n const abortListener = () => abortPayloadRequest(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 scheduleWork(request);\n\n return { request, stream };\n}\n\nfunction createTask(\n request: PayloadRequest,\n id: number,\n value: TaskValue,\n contextValues: ContextValues,\n imagePreloadsSuppressed: boolean,\n stack: StackFrame | null,\n): Task {\n request.pendingTasks += 1;\n return { contextValues, id, imagePreloadsSuppressed, stack, ...value };\n}\n\nfunction performWork(request: PayloadRequest): 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 flushRows(request);\n}\n\nfunction retryTask(request: PayloadRequest, task: Task): void {\n const frame: RenderFrame = {\n contextValues: cloneContextValues(task.contextValues),\n dispatcher: null,\n pendingAssets: [],\n request,\n imagePreloadsSuppressed: task.imagePreloadsSuppressed,\n stack: task.stack,\n };\n\n try {\n let value: PayloadModel;\n switch (task.kind) {\n case \"node\":\n value = serializeNode(task.value, frame);\n break;\n case \"node-promise\":\n value = serializeNode(readThenable(task.value), frame);\n break;\n case \"promise\":\n value = serializeValue(readThenable(task.value), frame);\n break;\n }\n flushFrameAssets(frame, task.id);\n emitDataRows(request);\n emitRow(request, { id: task.id, tag: \"model\", value });\n finishTask(request);\n } catch (error) {\n if (isThenable(error)) {\n // The retry re-discovers nothing already in emittedAssetKeys, so this\n // attempt's assets must ship now; the task still settles into task.id.\n flushFrameAssets(frame, task.id);\n error.then(\n () => pingTask(request, task),\n () => pingTask(request, task),\n );\n return;\n }\n\n flushFrameAssets(frame, task.id);\n emitRow(request, {\n id: task.id,\n tag: \"error\",\n value: errorRowPayload(request, error, task.stack),\n });\n finishTask(request);\n }\n}\n\nfunction finishTask(request: PayloadRequest): void {\n request.pendingTasks -= 1;\n if (request.pendingTasks === 0) request.allReady.resolve(undefined);\n}\n\nfunction emitDataRows(request: PayloadRequest): void {\n const entries: FigDataHydrationEntry[] = [];\n\n for (const snapshot of request.pendingDataSnapshots.values()) {\n // Stream only settled values. A \"refreshing\" entry exposes a transient stale\n // value while its background refresh is in flight; emitting it would mark the\n // key emitted forever and permanently suppress the fresh value. Skipping it\n // lets the entry stream once its refresh settles.\n if (!snapshot.hasValue || snapshot.status === \"refreshing\") continue;\n\n const key = snapshot.canonicalKey;\n if (request.emittedDataKeys.has(key)) {\n request.pendingDataSnapshots.delete(snapshot.canonicalKey);\n continue;\n }\n\n request.emittedDataKeys.add(key);\n request.pendingDataSnapshots.delete(snapshot.canonicalKey);\n entries.push({ key: snapshot.key, value: snapshot.value });\n }\n\n if (entries.length > 0) {\n emitRow(request, { tag: \"data\", value: encodePayloadDataEntries(entries) });\n }\n}\n\nfunction flushFrameAssets(frame: RenderFrame, rowId: number): void {\n if (frame.pendingAssets.length === 0) return;\n const value = frame.pendingAssets.splice(0);\n emitRow(frame.request, { for: rowId, tag: \"assets\", value });\n}\n\nfunction createPayloadDispatcher(frame: RenderFrame): RenderDispatcher {\n const dispatcher = createStaticDispatcher({\n contextValues: frame.contextValues,\n externalStoreError:\n \"useSyncExternalStore requires getServerSnapshot during payload render.\",\n readPromise: readThenable,\n readData(resource, args) {\n return frame.request.dataStore.readData(resource, args, frame);\n },\n preloadData(resource, args) {\n frame.request.dataStore.preloadData(resource, ...args);\n },\n useId() {\n const id = `fig-pl-${frame.request.nextUseId.toString(32)}`;\n frame.request.nextUseId += 1;\n return id;\n },\n updateError: \"State updates are not allowed during payload render.\",\n });\n\n // Serialized components are render-only: they never re-run on the client,\n // so state, effects, and interactivity are meaningless there — dev throws\n // at first use instead of silently freezing initial state into the wire.\n // Reads stay server-safe: readContext/readData/readPromise/preloadData,\n // useMemo, useId, and useSyncExternalStore's getServerSnapshot path (a\n // read, not a subscription — the static dispatcher already requires it).\n if (__DEV__) {\n const throwClientApi = (hook: string) => (): never => {\n throw new Error(\n `${hook} cannot be used during payload render: serialized components are render-only. Move state, effects, and interactivity into a client reference.`,\n );\n };\n dispatcher.useState = throwClientApi(\"useState\");\n dispatcher.useActionState = throwClientApi(\"useActionState\");\n dispatcher.useTransition = throwClientApi(\"useTransition\");\n dispatcher.useStableEvent = throwClientApi(\"useStableEvent\");\n dispatcher.useReactive = throwClientApi(\"useReactive\");\n dispatcher.useBeforePaint = throwClientApi(\"useBeforePaint\");\n dispatcher.useBeforeLayout = throwClientApi(\"useBeforeLayout\");\n }\n\n return dispatcher;\n}\n\nfunction serializeNode(node: FigNode, frame: RenderFrame): PayloadModel {\n if (Array.isArray(node)) {\n return flattenChildArrays(node).map((child) =>\n serializeNodeOrLazy(child, frame),\n );\n }\n\n if (node === null || node === undefined || typeof node === \"boolean\") {\n return node === undefined ? { $fig: \"undefined\" } : node;\n }\n\n if (typeof node === \"string\" || typeof node === \"number\") {\n return node;\n }\n\n if (isPortal(node)) return null;\n if (isValidElement(node)) return serializeElement(node, frame, false);\n if (isThenable(node)) {\n return outlineTask(\n frame,\n { kind: \"node-promise\", value: node },\n \"promise\",\n node,\n );\n }\n\n throw invalidChildError(node);\n}\n\nfunction serializeNodeOrLazy(\n node: FigNode,\n frame: RenderFrame,\n preserveElementIdentity = false,\n): PayloadModel {\n const graphCheckpoint = checkpointPayloadGraph(frame.request.graph);\n const assetCheckpoint = frame.pendingAssets.length;\n try {\n if (!isValidElement(node)) return serializeNode(node, frame);\n return serializeElement(node, frame, preserveElementIdentity);\n } catch (error) {\n rollbackPayloadGraph(frame.request.graph, graphCheckpoint);\n // Assets discovered inside this subtree belong to the outlined row, not\n // the enclosing one: gating the enclosing row would hold the whole tree's\n // reveal on stylesheets only the hole's content needs.\n const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);\n if (isThenable(error)) {\n return outlineTask(\n frame,\n { kind: \"node\", value: node },\n \"lazy\",\n error,\n scopedAssets,\n );\n }\n return outlineError(frame, error, \"lazy\", scopedAssets);\n }\n}\n\nfunction serializeElement(\n element: FigElement,\n frame: RenderFrame,\n preserveIdentity: boolean,\n): PayloadModel {\n const type = element.type;\n\n if (typeof type === \"string\") {\n return serializeHostElement(element, type, frame, preserveIdentity);\n }\n\n if (type === Fragment) {\n return serializeElementModel(\n element,\n { $fig: \"fragment\" },\n frame,\n preserveIdentity,\n childrenTreeProps,\n );\n }\n\n if (isClientReference(type)) {\n const clientId = emitClientReference(frame.request, type);\n return serializeElementModel(\n element,\n { $fig: \"client\", id: clientId },\n frame,\n preserveIdentity,\n );\n }\n\n if (isContext(type)) {\n return serializeContextProvider(type, element.props, frame);\n }\n\n if (isAssets(type)) {\n return serializeAssets(element.props, frame);\n }\n\n if (isSuspense(type)) {\n return serializeElementModel(\n element,\n { $fig: \"suspense\" },\n frame,\n preserveIdentity,\n suspenseTreeProps,\n );\n }\n\n if (isErrorBoundary(type)) {\n return serializeNode(element.props.children, frame);\n }\n\n if (isActivity(type)) {\n return serializeNode(element.props.children, frame);\n }\n\n if (isViewTransition(type)) {\n return serializeElementModel(\n element,\n { $fig: \"view-transition\" },\n frame,\n preserveIdentity,\n childrenTreeProps,\n );\n }\n\n if (typeof type === \"function\") {\n return serializeFunctionComponent(type, element.props, frame);\n }\n\n throw new Error(\"Unsupported Fig element type during payload render.\");\n}\n\nfunction serializeHostElement(\n element: FigElement,\n type: string,\n frame: RenderFrame,\n preserveIdentity: boolean,\n): PayloadModel {\n const preload = imagePreloadFromHostProps(\n type,\n element.props,\n frame.imagePreloadsSuppressed,\n );\n if (preload !== null) {\n frame.pendingAssets.push(\n ...serializeAssetResources(frame.request, preload),\n );\n }\n\n const previousImagePreloadsSuppressed = frame.imagePreloadsSuppressed;\n frame.imagePreloadsSuppressed =\n previousImagePreloadsSuppressed || suppressesImagePreloads(type);\n try {\n return serializeElementModel(\n element,\n type,\n frame,\n preserveIdentity,\n childrenTreeProps,\n );\n } finally {\n frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed;\n }\n}\n\nfunction serializeElementModel(\n element: FigElement,\n type: PayloadElementModel[\"type\"],\n frame: RenderFrame,\n preserveIdentity: boolean,\n treeProps: ReadonlySet<string> = emptyTreeProps,\n): PayloadModel {\n const id = preserveIdentity\n ? definePayloadGraphElement(frame.request.graph, element)\n : undefined;\n if (typeof id === \"object\") return id;\n const model: PayloadElementModel = {\n $fig: \"element\",\n key: element.key,\n props: serializeProps(\n element.props,\n frame,\n treeProps,\n typeof type === \"string\",\n ),\n type,\n };\n if (id !== undefined) model.id = id;\n return model;\n}\n\nfunction serializeFunctionComponent(\n type: Component,\n props: Props,\n frame: RenderFrame,\n): PayloadModel {\n const assetCheckpoint = frame.pendingAssets.length;\n frame.pendingAssets.push(\n ...serializeAssetResources(\n frame.request,\n frame.request.componentAssets?.(type),\n ),\n );\n frame.dispatcher ??= createPayloadDispatcher(frame);\n const previousDispatcher = setCurrentDispatcher(frame.dispatcher);\n const previousDataStore = setCurrentDataStore(frame.request.dataStore);\n const previousStack = frame.stack;\n frame.stack = { name: type.name || \"Anonymous\", parent: previousStack };\n\n try {\n if (\n __DEV__ &&\n \"$$typeof\" in type &&\n type.$$typeof === Symbol.for(\"fig.data-resource\")\n ) {\n throw new Error(\n \"Payload components cannot be rendered inside Payload. Render the underlying server component directly, or mount separate Payload components from the client tree.\",\n );\n }\n const result = type(props);\n if (isThenable(result)) {\n const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);\n return outlineTask(\n frame,\n { kind: \"node-promise\", value: result },\n \"promise\",\n result,\n scopedAssets,\n );\n }\n return serializeNode(result, frame);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n } finally {\n frame.stack = previousStack;\n setCurrentDataStore(previousDataStore);\n setCurrentDispatcher(previousDispatcher);\n }\n}\n\nfunction serializeContextProvider(\n context: FigContext<unknown>,\n props: Props,\n frame: RenderFrame,\n): PayloadModel {\n return withContextValue(frame.contextValues, context, props.value, () =>\n serializeNode(props.children, frame),\n );\n}\n\nfunction serializeAssets(props: Props, frame: RenderFrame): PayloadModel {\n // Buffered, not emitted: the owning row id is decided at scope exit (see\n // RenderFrame.pendingAssets). Dedupe happens here, so a retried subtree\n // does not re-buffer assets an earlier attempt already shipped.\n frame.pendingAssets.push(\n ...serializeAssetResources(frame.request, props.assets),\n );\n return serializeNode(props.children, frame);\n}\n\nfunction serializeProps(\n props: Props,\n frame: RenderFrame,\n treeProps: ReadonlySet<string>,\n hostElement = false,\n): PayloadModel {\n const clientOnlyBehavior = hostElement\n ? clientOnlyHostBehavior(props)\n : undefined;\n if (clientOnlyBehavior !== undefined) {\n throw new Error(\n `Client-only host behavior from ${clientOnlyBehavior} cannot be ` +\n \"serialized in a payload; move it into a client reference.\",\n );\n }\n\n const value: Record<string, PayloadModel> = {};\n for (const name of Object.keys(props)) {\n // A host `mix` already resolved into these props at element creation;\n // the marker itself holds descriptors (functions) and stays server-side.\n // Component `mix` props still serialize (and fail loudly on functions).\n if (hostElement && name === \"mix\") continue;\n const child = props[name];\n value[name] = treeProps.has(name)\n ? serializeTreeProp(child, frame)\n : serializeValue(child, frame);\n }\n return {\n $fig: \"object\",\n value,\n };\n}\n\nfunction serializeTreeProp(value: FigNode, frame: RenderFrame): PayloadModel {\n if (Array.isArray(value)) {\n return flattenChildArrays(value).map((child) =>\n serializeNodeOrLazy(child, frame),\n );\n }\n return serializeNodeOrLazy(value, frame);\n}\n\nfunction serializeValue(value: unknown, frame: RenderFrame): PayloadModel {\n // Scalar values return from the shared encoder before any graph access, so\n // reusing the request graph here is free (no per-value context allocation).\n if (isPlainPayloadValue(value)) {\n return encodePayloadValueWithGraph(value, frame.request.graph);\n }\n\n if (isClientReference(value)) {\n return { $fig: \"client\", id: emitClientReference(frame.request, value) };\n }\n\n if (isValidElement(value)) return serializeNodeOrLazy(value, frame, true);\n if (isPortal(value)) return null;\n if (isThenable(value)) {\n return outlineTask(frame, { kind: \"promise\", value }, \"promise\", value);\n }\n if (typeof value === \"function\") {\n throw new Error(\"Functions cannot be passed to client references.\");\n }\n\n if (typeof value === \"object\" && value !== null) {\n if (value instanceof Date) {\n return encodePayloadValueWithGraph(value, frame.request.graph);\n }\n if (value instanceof Map) {\n return serializePayloadMap(value, frame.request.graph, ([key, item]) => [\n serializeValue(key, frame),\n serializeValue(item, frame),\n ]);\n }\n if (value instanceof Set) {\n return serializePayloadSet(value, frame.request.graph, (item) =>\n serializeValue(item, frame),\n );\n }\n\n if (Array.isArray(value)) {\n return serializePayloadArray(\n value,\n frame.request.graph,\n () => value,\n (item) => serializeValue(item, frame),\n );\n }\n\n return serializePayloadPlainObject(value, frame.request.graph, (child) =>\n serializeValue(child, frame),\n );\n }\n\n throw new Error(`Cannot serialize ${typeof value} into the payload.`);\n}\nfunction outlineTask(\n frame: RenderFrame,\n value: TaskValue,\n referenceKind: \"lazy\" | \"promise\",\n wakeable: Thenable,\n scopedAssets: SerializedAssetResource[] = [],\n): PayloadSpecialModel {\n const request = frame.request;\n const id = request.nextRowId++;\n if (scopedAssets.length > 0) {\n emitRow(request, { for: id, tag: \"assets\", value: scopedAssets });\n }\n const task = createTask(\n request,\n id,\n value,\n cloneContextValues(frame.contextValues),\n frame.imagePreloadsSuppressed,\n stackForError(wakeable, frame.stack),\n );\n\n wakeable.then(\n () => pingTask(request, task),\n () => pingTask(request, task),\n );\n\n return { $fig: referenceKind, id };\n}\n\nfunction outlineError(\n frame: RenderFrame,\n error: unknown,\n referenceKind: \"lazy\" | \"promise\",\n scopedAssets: SerializedAssetResource[],\n): PayloadSpecialModel {\n const request = frame.request;\n const id = request.nextRowId++;\n // Assets first so a decoder that drops gates on error rows sees the row\n // order it expects; the assets still preload even though the row failed.\n if (scopedAssets.length > 0) {\n emitRow(request, { for: id, tag: \"assets\", value: scopedAssets });\n }\n emitRow(request, {\n id,\n tag: \"error\",\n value: errorRowPayload(request, error, frame.stack),\n });\n return { $fig: referenceKind, id };\n}\n\n// The onError return value is authoritative, like the HTML renderer's\n// reportBoundaryError: message crosses the wire only when the handler says\n// so. Without a handler, development keeps the real message for debugging\n// (payload errors never re-execute on the client, so the wire is the only\n// surface) and production sends an empty payload.\nfunction errorRowPayload(\n request: PayloadRequest,\n error: unknown,\n stack: StackFrame | null,\n): ServerErrorPayload {\n const info = {\n componentStack: componentStack(stackForError(error, stack)),\n };\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\" || error === null) 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 (typeof error !== \"object\" || error === null) return fallback;\n return errorStacks.get(error) ?? fallback;\n}\n\nfunction clientReferenceExportName(id: string): string | undefined {\n const hashIndex = id.lastIndexOf(\"#\");\n if (hashIndex === -1) return undefined;\n return id.slice(hashIndex + 1) || undefined;\n}\n\nfunction emitClientReference(\n request: PayloadRequest,\n reference: FigClientReference,\n): number {\n const existing = request.clientReferenceRows.get(reference.id);\n if (existing !== undefined) return existing;\n\n // Resolve assets BEFORE reserving the row id and recording the mapping. A lazy\n // resource thunk (bundler-manifest resolution) may throw; reserving first would\n // leave a row id mapped but never emitted, so a later retry returns the cached\n // id and the client suspends on a chunk that never arrives. Resolving first\n // lets the throw propagate as an ordinary serialization error with no poisoned\n // mapping, so the reference can be retried cleanly.\n const assets = serializeAssetResources(\n request,\n collectClientReferenceAssets(request, reference),\n );\n const value: Extract<PayloadRow, { tag: \"client\" }>[\"value\"] = {\n id: reference.id,\n };\n if (assets.length > 0) value.assets = assets;\n // The \"<module>#<export>\" authoring convention is split here, once, so the\n // wire is self-describing and the client never string-parses ids.\n const exportName = clientReferenceExportName(reference.id);\n if (exportName !== undefined) value.exportName = exportName;\n if (reference.ssr !== undefined) value.ssr = true;\n const id = request.nextRowId++;\n request.clientReferenceRows.set(reference.id, id);\n emitRow(request, {\n id,\n tag: \"client\",\n value,\n });\n return id;\n}\n\nfunction serializeAssetResources(\n request: PayloadRequest,\n value: unknown,\n): SerializedAssetResource[] {\n const input = isFigAssetResource(value)\n ? [value]\n : Array.isArray(value)\n ? value\n : [];\n const resources: SerializedAssetResource[] = [];\n\n for (const resource of input) {\n if (!isFigAssetResource(resource)) continue;\n // Delivery assets are request-global and persistent, so the first\n // definition wins. Metadata is owner-scoped and may legitimately repeat\n // with a different value in another row; the decoder retains those\n // declarations until their owning tree commits.\n if (assetResourceDestination(resource) === \"stream\") {\n const key = assetResourceKey(resource);\n if (request.emittedAssetKeys.has(key)) continue;\n request.emittedAssetKeys.add(key);\n }\n resources.push(serializeAssetResource(resource));\n }\n\n return resources;\n}\n\nfunction collectClientReferenceAssets(\n request: PayloadRequest,\n reference: FigClientReference,\n): readonly FigAssetResource[] {\n const resources = [...clientReferenceAssets(reference)];\n const resolved = request.clientReferenceAssets?.({ id: reference.id });\n if (resolved === undefined) return resources;\n if (isFigAssetResource(resolved)) return [...resources, resolved];\n return Array.isArray(resolved) ? [...resources, ...resolved] : resources;\n}\n\nfunction serializeAssetResource(\n resource: FigAssetResource,\n): SerializedAssetResource {\n // Delivery assets intentionally omit author-supplied `key` and dedupe by\n // their concrete URL. Metadata keeps its owner-local identity when needed.\n // Omitted `undefined` optionals are part of the wire contract, hence the\n // assign-if-defined shape.\n switch (resource.kind) {\n case \"stylesheet\": {\n const model: SerializedAssetResource = {\n href: resource.href,\n kind: resource.kind,\n };\n if (resource.crossorigin !== undefined) {\n model.crossorigin = resource.crossorigin;\n }\n if (resource.media !== undefined) model.media = resource.media;\n if (resource.precedence !== undefined) {\n model.precedence = resource.precedence;\n }\n return model;\n }\n case \"preload\": {\n const model: SerializedAssetResource = {\n as: resource.as,\n kind: resource.kind,\n };\n if (resource.crossorigin !== undefined) {\n model.crossorigin = resource.crossorigin;\n }\n if (resource.fetchpriority !== undefined) {\n model.fetchpriority = resource.fetchpriority;\n }\n if (resource.href !== undefined) model.href = resource.href;\n if (resource.imagesizes !== undefined) {\n model.imagesizes = resource.imagesizes;\n }\n if (resource.imagesrcset !== undefined) {\n model.imagesrcset = resource.imagesrcset;\n }\n if (resource.referrerpolicy !== undefined) {\n model.referrerpolicy = resource.referrerpolicy;\n }\n if (resource.type !== undefined) model.type = resource.type;\n return model;\n }\n case \"modulepreload\": {\n const model: SerializedAssetResource = {\n href: resource.href,\n kind: resource.kind,\n };\n if (resource.crossorigin !== undefined) {\n model.crossorigin = resource.crossorigin;\n }\n if (resource.fetchpriority !== undefined) {\n model.fetchpriority = resource.fetchpriority;\n }\n return model;\n }\n case \"script\": {\n const model: SerializedAssetResource = {\n kind: resource.kind,\n src: resource.src,\n };\n if (resource.async !== undefined) model.async = resource.async;\n if (resource.crossorigin !== undefined) {\n model.crossorigin = resource.crossorigin;\n }\n if (resource.defer !== undefined) model.defer = resource.defer;\n if (resource.module !== undefined) model.module = resource.module;\n return model;\n }\n case \"font\": {\n const model: SerializedAssetResource = {\n href: resource.href,\n kind: resource.kind,\n type: resource.type,\n };\n if (resource.crossorigin !== undefined) {\n model.crossorigin = resource.crossorigin;\n }\n if (resource.fetchpriority !== undefined) {\n model.fetchpriority = resource.fetchpriority;\n }\n return model;\n }\n case \"preconnect\": {\n const model: SerializedAssetResource = {\n href: resource.href,\n kind: resource.kind,\n };\n if (resource.crossorigin !== undefined) {\n model.crossorigin = resource.crossorigin;\n }\n return model;\n }\n case \"title\":\n return { kind: resource.kind, value: resource.value };\n case \"meta\": {\n const model: SerializedAssetResource = { kind: resource.kind };\n if (resource.charset !== undefined) model.charset = resource.charset;\n if (resource.content !== undefined) model.content = resource.content;\n if (resource[\"http-equiv\"] !== undefined) {\n model[\"http-equiv\"] = resource[\"http-equiv\"];\n }\n if (resource.key !== undefined) model.key = resource.key;\n if (resource.name !== undefined) model.name = resource.name;\n if (resource.property !== undefined) model.property = resource.property;\n return model;\n }\n }\n}\n\nfunction emitRow(request: PayloadRequest, row: PayloadRow): void {\n request.queuedRows.push(jsonPayloadCodec.encodeRow(row));\n flushRows(request);\n}\n\nfunction pingTask(request: PayloadRequest, task: Task): void {\n if (request.status === \"closed\") return;\n request.pingedTasks.push(task);\n scheduleWork(request);\n}\n\nfunction scheduleWork(request: PayloadRequest): void {\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 flushRows(request: PayloadRequest): void {\n if (request.controller === null || request.status === \"closed\") return;\n if (request.flushingRows) return;\n\n request.flushingRows = true;\n try {\n // Row-granular gating: rows already encode one complete wire row each,\n // so stopping between rows keeps every chunk parse-safe for consumers\n // that interleave per chunk.\n let flushed = 0;\n while (\n flushed < request.queuedRows.length &&\n !streamFlowBlocked(request.controller)\n ) {\n request.controller.enqueue(request.queuedRows[flushed]);\n flushed += 1;\n }\n if (flushed === request.queuedRows.length) request.queuedRows.length = 0;\n else if (flushed > 0) {\n request.queuedRows = request.queuedRows.slice(flushed);\n }\n } finally {\n request.flushingRows = false;\n }\n\n // Deliberately not conditioned on flow: close() only marks the end of the\n // queue, so a full queue with no rows left to write still closes here.\n if (request.pendingTasks === 0 && request.queuedRows.length === 0) {\n request.status = \"closed\";\n request.cleanupAbortListener();\n request.dataStore.dispose();\n request.controller.close();\n }\n}\n\nfunction closeWithError(request: PayloadRequest, error: unknown): void {\n if (request.status === \"closed\") return;\n request.cleanupAbortListener();\n request.status = \"closed\";\n request.dataStore.dispose();\n request.allReady.reject(error);\n request.controller?.error(error);\n}\n\nfunction abortPayloadRequest(request: PayloadRequest, reason?: unknown): void {\n closeWithError(request, reason ?? new PayloadRequestCancelledError());\n}\n\n// Wire-format flattening only: unlike the shared collectChildren, this keeps\n// empty children and does NOT merge adjacent text — the client decodes rows\n// and re-collects children itself, so merging here would double-apply. Flat\n// input (the common case) is returned untouched.\nfunction flattenChildArrays(children: FigNode[]): FigNode[] {\n if (!children.some(Array.isArray)) return children;\n\n const collected: FigNode[] = [];\n for (const child of children) {\n if (Array.isArray(child)) {\n for (const nested of flattenChildArrays(child)) collected.push(nested);\n } else {\n collected.push(child);\n }\n }\n return collected;\n}\n\nfunction invalidChildError(value: unknown): Error {\n return new Error(\n `Invalid Fig child in payload render: ${describeInvalidChild(value)}.`,\n );\n}\n\nfunction throwIfAborted(signal?: AbortSignal | null): void {\n if (signal?.aborted) throw new PayloadRequestCancelledError();\n}\n"],"mappings":";;;;AAmHA,IAAM,+BAAN,cAA2C,MAAM;CAC/C,cAAc;EACZ,MAAM,4BAA4B;EAClC,KAAK,OAAO;CACd;AACF;AA4DA,MAAM,8BAAc,IAAI,QAA4B;AACpD,MAAM,oCAAoB,IAAI,IAAI,CAAC,UAAU,CAAC;AAC9C,MAAM,iCAAiB,IAAI,IAAY;AACvC,MAAM,oCAAoB,IAAI,IAAI,CAAC,YAAY,UAAU,CAAC;AAE1D,SAAgB,sBACd,MACA,UAAgC,CAAC,GACZ;CACrB,MAAM,EAAE,SAAS,WAAW,qBAAqB,MAAM,OAAO;CAC9D,OAAO;EACL,UAAU,QAAQ,SAAS;EAC3B,aAAa,iBAAiB;EAC9B;CACF;AACF;AAEA,SAAS,qBACP,MACA,SACiE;CACjE,eAAe,QAAQ,MAAM;CAE7B,MAAM,uCAAuB,IAAI,IAAoC;CACrE,MAAM,UAA0B;EAC9B,UAAU,SAAe;EACzB,4BAA4B,KAAA;EAC5B,qCAAqB,IAAI,IAAI;EAC7B,uBAAuB,QAAQ;EAC/B,iBAAiB,QAAQ;EACzB,YAAY;EACZ,WAAW,wBAAsC;GAC/C,eAAe;GACf,gBAAgB,UAAkC;IAChD,qBAAqB,IAAI,MAAM,cAAc,KAAK;GACpD;GACA,WAAW,QAAQ;GACnB,gBAAgB,KAAA;EAClB,CAAC;EACD,kCAAkB,IAAI,IAAI;EAC1B,iCAAiB,IAAI,IAAI;EACzB,OAAO,gCAAgC;EACvC,WAAW;EACX,WAAW;EACX,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C,MAAM,YAAuB,CAAC;CAC9B,KAAK,MAAM,SAAS,UAClB,IAAI,MAAM,QAAQ,KAAK,GACrB,KAAK,MAAM,UAAU,mBAAmB,KAAK,GAAG,UAAU,KAAK,MAAM;MAErE,UAAU,KAAK,KAAK;CAGxB,OAAO;AACT;AAEA,SAASA,oBAAkB,OAAuB;CAChD,uBAAO,IAAI,MACT,wCAAwC,qBAAqB,KAAK,EAAE,EACtE;AACF;AAEA,SAAS,eAAe,QAAmC;CACzD,IAAI,QAAQ,SAAS,MAAM,IAAI,6BAA6B;AAC9D"}
@@ -1,4 +1,4 @@
1
- import { DataResourceKeyInput, ElementType, FigAssetResource, FigAssetResourceList, FigClientReference, FigDataHydrationEntry, FigDataStoreController, FigDataStoreHandle, FigNode, Props } from "@bgub/fig";
1
+ import { DataResourceKeyInput, ElementType, FigAssetResource, FigAssetResourceList, FigClientReference, FigDataHydrationEntry, FigDataStoreController, FigDataStoreHandle, FigNode, PreloadResource, Props } from "@bgub/fig";
2
2
  //#region src/render-tree.d.ts
3
3
  type RenderTreeKind = "activity" | "assets" | "client-reference" | "context-provider" | "error-boundary" | "fragment" | "function" | "host" | "root" | "suspense" | "text" | "view-transition";
4
4
  interface RenderTreeNode {
@@ -84,9 +84,12 @@ interface ServerPreloadHeaderOptions {
84
84
  /** Maximum UTF-16 code units in the returned value. Defaults to 2,000. */
85
85
  maxLength?: number;
86
86
  }
87
+ type HeaderPreloadResource = PreloadResource & {
88
+ href: string;
89
+ };
87
90
  type ServerPreloadHeaderResource = Readonly<Exclude<FigAssetResource, {
88
- kind: "meta" | "script" | "title";
89
- }>>;
91
+ kind: "meta" | "preload" | "script" | "title";
92
+ }> | HeaderPreloadResource>;
90
93
  type ServerDocumentRenderResult = ServerStreamRenderResult;
91
94
  interface ServerFragmentRenderResult extends ServerStreamRenderResult {
92
95
  getHead(): string;
@@ -0,0 +1,26 @@
1
+ //#region src/escaping.ts
2
+ function escapeText(value) {
3
+ return value.replace(/[&<>]/g, (character) => {
4
+ if (character === "&") return "&amp;";
5
+ if (character === "<") return "&lt;";
6
+ return "&gt;";
7
+ });
8
+ }
9
+ function escapeAttribute(value) {
10
+ return value.replace(/[&"<>]/g, (character) => {
11
+ if (character === "&") return "&amp;";
12
+ if (character === "\"") return "&quot;";
13
+ if (character === "<") return "&lt;";
14
+ return "&gt;";
15
+ });
16
+ }
17
+ function escapeScriptText(value) {
18
+ return value.replaceAll("<", "\\u003C").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
19
+ }
20
+ function escapeScriptJson(value) {
21
+ return escapeScriptText(JSON.stringify(value));
22
+ }
23
+ //#endregion
24
+ export { escapeText as i, escapeScriptJson as n, escapeScriptText as r, escapeAttribute as t };
25
+
26
+ //# sourceMappingURL=escaping-DAot8sFu.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"escaping-DAot8sFu.js","names":[],"sources":["../src/escaping.ts"],"sourcesContent":["export function escapeText(value: string): string {\n return value.replace(/[&<>]/g, (character) => {\n if (character === \"&\") return \"&amp;\";\n if (character === \"<\") return \"&lt;\";\n return \"&gt;\";\n });\n}\n\nexport function escapeAttribute(value: string): string {\n return value.replace(/[&\"<>]/g, (character) => {\n if (character === \"&\") return \"&amp;\";\n if (character === '\"') return \"&quot;\";\n if (character === \"<\") return \"&lt;\";\n return \"&gt;\";\n });\n}\n\n// Script elements are raw-text elements: HTML entities are not decoded in\n// their contents, so escape only characters that can terminate the element\n// or executable source.\nexport function escapeScriptText(value: string): string {\n return value\n .replaceAll(\"<\", \"\\\\u003C\")\n .replaceAll(\"\\u2028\", \"\\\\u2028\")\n .replaceAll(\"\\u2029\", \"\\\\u2029\");\n}\n\nexport function escapeScriptJson(value: unknown): string {\n return escapeScriptText(JSON.stringify(value));\n}\n"],"mappings":";AAAA,SAAgB,WAAW,OAAuB;CAChD,OAAO,MAAM,QAAQ,WAAW,cAAc;EAC5C,IAAI,cAAc,KAAK,OAAO;EAC9B,IAAI,cAAc,KAAK,OAAO;EAC9B,OAAO;CACT,CAAC;AACH;AAEA,SAAgB,gBAAgB,OAAuB;CACrD,OAAO,MAAM,QAAQ,YAAY,cAAc;EAC7C,IAAI,cAAc,KAAK,OAAO;EAC9B,IAAI,cAAc,MAAK,OAAO;EAC9B,IAAI,cAAc,KAAK,OAAO;EAC9B,OAAO;CACT,CAAC;AACH;AAKA,SAAgB,iBAAiB,OAAuB;CACtD,OAAO,MACJ,WAAW,KAAK,SAAS,CAAC,CAC1B,WAAW,UAAU,SAAS,CAAC,CAC/B,WAAW,UAAU,SAAS;AACnC;AAEA,SAAgB,iBAAiB,OAAwB;CACvD,OAAO,iBAAiB,KAAK,UAAU,KAAK,CAAC;AAC/C"}
@@ -0,0 +1,2 @@
1
+ import { i as escapeText, n as escapeScriptJson, r as escapeScriptText, t as escapeAttribute } from "./escaping-DAot8sFu.js";
2
+ export { escapeAttribute, escapeScriptJson, escapeScriptText, escapeText };
@@ -0,0 +1,164 @@
1
+ import { t as escapeAttribute } from "./escaping-DAot8sFu.js";
2
+ //#region src/shared.ts
3
+ const STREAMED_METADATA_ATTRIBUTE = "data-fig-streamed-metadata";
4
+ function contextStack(values, context) {
5
+ let stack = values.get(context);
6
+ if (stack === void 0) {
7
+ stack = [];
8
+ values.set(context, stack);
9
+ }
10
+ return stack;
11
+ }
12
+ function withContextValue(values, context, value, callback) {
13
+ const stack = contextStack(values, context);
14
+ stack.push(value);
15
+ try {
16
+ return callback();
17
+ } finally {
18
+ stack.pop();
19
+ }
20
+ }
21
+ function readContextValue(values, context) {
22
+ const stack = values.get(context);
23
+ if (stack !== void 0 && stack.length > 0) return stack[stack.length - 1];
24
+ return context.defaultValue;
25
+ }
26
+ function deferred() {
27
+ let resolve = () => void 0;
28
+ let reject = () => void 0;
29
+ return {
30
+ promise: new Promise((innerResolve, innerReject) => {
31
+ resolve = innerResolve;
32
+ reject = innerReject;
33
+ }),
34
+ reject,
35
+ resolve
36
+ };
37
+ }
38
+ function cloneContextValues(values) {
39
+ const clone = /* @__PURE__ */ new Map();
40
+ for (const [context, stack] of values) clone.set(context, [...stack]);
41
+ return clone;
42
+ }
43
+ const DEFAULT_STREAM_HIGH_WATER_MARK = 65536;
44
+ function streamHighWaterMark(option) {
45
+ return Math.max(1, option ?? DEFAULT_STREAM_HIGH_WATER_MARK);
46
+ }
47
+ function streamFlowBlocked(controller) {
48
+ const desiredSize = controller?.desiredSize;
49
+ return typeof desiredSize === "number" && desiredSize <= 0;
50
+ }
51
+ function resolveInitialState(initialState) {
52
+ return typeof initialState === "function" ? initialState() : initialState;
53
+ }
54
+ function createStaticDispatcher(options) {
55
+ return {
56
+ useState(initialState) {
57
+ const value = resolveInitialState(initialState);
58
+ const setState = () => {
59
+ throw new Error(options.updateError);
60
+ };
61
+ return [value, setState];
62
+ },
63
+ useActionState(_action, initialState) {
64
+ const runner = () => {
65
+ throw new Error(options.updateError);
66
+ };
67
+ return [
68
+ initialState,
69
+ runner,
70
+ false
71
+ ];
72
+ },
73
+ useId() {
74
+ return options.useId();
75
+ },
76
+ useDeferredValue(value, _initialValue, _hasInitialValue) {
77
+ return value;
78
+ },
79
+ useMemo(calculate, _deps) {
80
+ return calculate();
81
+ },
82
+ useTransition() {
83
+ const startTransition = (callback) => void callback(new AbortController().signal);
84
+ return [false, startTransition];
85
+ },
86
+ useReactive(_effect, _deps) {},
87
+ useBeforePaint(_effect, _deps) {},
88
+ useBeforeLayout(_effect, _deps) {},
89
+ useSyncExternalStore(_subscribe, _getSnapshot, getServerSnapshot) {
90
+ if (getServerSnapshot === void 0) throw new Error(options.externalStoreError);
91
+ return getServerSnapshot();
92
+ },
93
+ useStableEvent(_handler) {
94
+ return (..._args) => {
95
+ throw new Error("Stable events cannot be called during server render.");
96
+ };
97
+ },
98
+ readContext(context) {
99
+ return readContextValue(options.contextValues, context);
100
+ },
101
+ readData(resource, args) {
102
+ return options.readData(resource, args);
103
+ },
104
+ preloadData(resource, args) {
105
+ options.preloadData(resource, args);
106
+ },
107
+ readPromise(promise) {
108
+ return options.readPromise(promise);
109
+ }
110
+ };
111
+ }
112
+ function errorMessage(error) {
113
+ return error instanceof Error ? error.message : String(error);
114
+ }
115
+ function componentStack(stack) {
116
+ const frames = [];
117
+ for (let frame = stack; frame !== null; frame = frame.parent) frames.push(` at ${frame.name}`);
118
+ return frames.length === 0 ? "" : `\n${frames.join("\n")}`;
119
+ }
120
+ function nonceAttribute(nonce) {
121
+ return nonce === void 0 ? "" : ` nonce="${escapeAttribute(nonce)}"`;
122
+ }
123
+ //#endregion
124
+ //#region src/image-preloads.ts
125
+ function imagePreloadFromHostProps(type, props, suppressed) {
126
+ if (suppressed || type.toLowerCase() !== "img") return null;
127
+ if (props.loading === "lazy" || props.fetchpriority === "low") return null;
128
+ const src = stringProp(props.src);
129
+ const srcset = stringProp(props.srcset);
130
+ if (props.src != null && typeof props.src !== "string" || props.srcset != null && typeof props.srcset !== "string" || !src && !srcset || isDataUrl(src) || isDataUrl(srcset)) return null;
131
+ return {
132
+ as: "image",
133
+ crossorigin: imageCrossorigin(props.crossorigin),
134
+ fetchpriority: imageFetchpriority(props.fetchpriority),
135
+ href: src || void 0,
136
+ imagesizes: srcset ? stringProp(props.sizes) : void 0,
137
+ imagesrcset: srcset || void 0,
138
+ kind: "preload",
139
+ referrerpolicy: stringProp(props.referrerpolicy),
140
+ type: stringProp(props.type)
141
+ };
142
+ }
143
+ function suppressesImagePreloads(type) {
144
+ const normalizedType = type.toLowerCase();
145
+ return normalizedType === "picture" || normalizedType === "noscript";
146
+ }
147
+ function stringProp(value) {
148
+ return typeof value === "string" ? value : void 0;
149
+ }
150
+ function isDataUrl(value) {
151
+ return value?.slice(0, 5).toLowerCase() === "data:";
152
+ }
153
+ function imageCrossorigin(value) {
154
+ if (typeof value !== "string") return void 0;
155
+ if (value === "anonymous" || value === "use-credentials" || value === "") return value;
156
+ return "";
157
+ }
158
+ function imageFetchpriority(value) {
159
+ return value === "high" || value === "auto" ? value : void 0;
160
+ }
161
+ //#endregion
162
+ export { componentStack as a, errorMessage as c, streamHighWaterMark as d, withContextValue as f, cloneContextValues as i, nonceAttribute as l, suppressesImagePreloads as n, createStaticDispatcher as o, STREAMED_METADATA_ATTRIBUTE as r, deferred as s, imagePreloadFromHostProps as t, streamFlowBlocked as u };
163
+
164
+ //# sourceMappingURL=image-preloads-D3OBEaWp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-preloads-D3OBEaWp.js","names":[],"sources":["../src/shared.ts","../src/image-preloads.ts"],"sourcesContent":["import type {\n ActionStateAction,\n ActionStateRunner,\n DependencyList,\n EffectCallback,\n ExternalStoreSubscribe,\n FigContext,\n StateSetter,\n StartTransition,\n} from \"@bgub/fig\";\nimport type {\n DataResource,\n RenderDispatcher,\n StableEventCallerArgs,\n} from \"@bgub/fig/internal\";\nimport { escapeAttribute } from \"./escaping.ts\";\n\nexport type ContextValues = Map<FigContext<unknown>, unknown[]>;\n\nexport const STREAMED_METADATA_ATTRIBUTE = \"data-fig-streamed-metadata\";\n\nexport interface StackFrame {\n name: string;\n parent: StackFrame | null;\n}\n\ninterface StaticDispatcherOptions {\n contextValues: ContextValues;\n externalStoreError: string;\n preloadData<TArgs extends unknown[], TValue>(\n resource: DataResource<TArgs, TValue>,\n args: TArgs,\n ): void;\n readData<TArgs extends unknown[], TValue>(\n resource: DataResource<TArgs, TValue>,\n args: TArgs,\n ): TValue;\n readPromise<T>(promise: PromiseLike<T>): T;\n updateError: string;\n useId(): string;\n}\n\nfunction contextStack(\n values: ContextValues,\n context: FigContext<unknown>,\n): unknown[] {\n let stack = values.get(context);\n\n if (stack === undefined) {\n stack = [];\n values.set(context, stack);\n }\n\n return stack;\n}\n\nexport function withContextValue<T>(\n values: ContextValues,\n context: FigContext<unknown>,\n value: unknown,\n callback: () => T,\n): T {\n const stack = contextStack(values, context);\n stack.push(value);\n\n try {\n return callback();\n } finally {\n stack.pop();\n }\n}\n\nfunction readContextValue<T>(values: ContextValues, context: FigContext<T>): T {\n const stack = values.get(context as FigContext<unknown>);\n if (stack !== undefined && stack.length > 0) {\n return stack[stack.length - 1] as T;\n }\n\n return context.defaultValue;\n}\n\nexport interface Deferred<T> {\n promise: Promise<T>;\n reject: (reason: unknown) => void;\n resolve: (value: T) => void;\n}\n\nexport function deferred<T>(): Deferred<T> {\n let resolve: Deferred<T>[\"resolve\"] = () => undefined;\n let reject: Deferred<T>[\"reject\"] = () => undefined;\n const promise = new Promise<T>((innerResolve, innerReject) => {\n resolve = innerResolve;\n reject = innerReject;\n });\n return { promise, reject, resolve };\n}\n\nexport function cloneContextValues(values: ContextValues): ContextValues {\n const clone: ContextValues = new Map();\n for (const [context, stack] of values) clone.set(context, [...stack]);\n return clone;\n}\n\n// Encoded bytes a render result stream's internal queue holds before flushing\n// pauses (resumed by consumer pulls). Shared by the HTML and payload\n// renderers. Large enough that a healthy consumer never blocks a flush; small\n// enough to bound per-connection buffering when the consumer stalls.\n// Rendering itself never pauses — only writing to the stream does.\nconst DEFAULT_STREAM_HIGH_WATER_MARK = 65536;\n\n// 0 would deadlock: desiredSize never goes positive, and read requests alone\n// do not make it so. 1 byte is the honest pure-pull minimum.\nexport function streamHighWaterMark(option: number | undefined): number {\n return Math.max(1, option ?? DEFAULT_STREAM_HIGH_WATER_MARK);\n}\n\n// Blocked means the stream's internal queue is at or past its high-water\n// mark; completed work then waits un-enqueued until the consumer pulls.\n// desiredSize is null on an errored stream — never blocked, because fatal\n// paths close the request before any further writes.\nexport function streamFlowBlocked(\n controller: ReadableStreamDefaultController<Uint8Array> | null,\n): boolean {\n const desiredSize = controller?.desiredSize;\n return typeof desiredSize === \"number\" && desiredSize <= 0;\n}\n\nfunction resolveInitialState<S>(initialState: S | (() => S)): S {\n return typeof initialState === \"function\"\n ? (initialState as () => S)()\n : initialState;\n}\n\nexport function createStaticDispatcher(\n options: StaticDispatcherOptions,\n): RenderDispatcher {\n return {\n useState<S>(initialState: S | (() => S)): [S, StateSetter<S>] {\n const value = resolveInitialState(initialState);\n const setState: StateSetter<typeof value> = () => {\n throw new Error(options.updateError);\n };\n return [value, setState];\n },\n useActionState<S, Args extends unknown[]>(\n _action: ActionStateAction<S, Args>,\n initialState: S,\n ): [S, ActionStateRunner<Args>, boolean] {\n const runner: ActionStateRunner<Args> = () => {\n throw new Error(options.updateError);\n };\n return [initialState, runner, false];\n },\n useId(): string {\n return options.useId();\n },\n useDeferredValue<T>(\n value: T,\n _initialValue: T | undefined,\n _hasInitialValue: boolean,\n ): T {\n return value;\n },\n useMemo<T>(calculate: () => T, _deps: DependencyList): T {\n return calculate();\n },\n useTransition(): [boolean, StartTransition] {\n // Server transitions run synchronously to completion; the signal never\n // aborts (there is no supersede/unmount lifecycle during a request).\n const startTransition: StartTransition = (\n callback: (signal: AbortSignal) => void | PromiseLike<void>,\n ) => void callback(new AbortController().signal);\n return [false, startTransition];\n },\n useReactive(_effect: EffectCallback, _deps?: DependencyList): void {},\n useBeforePaint(_effect: EffectCallback, _deps?: DependencyList): void {},\n useBeforeLayout(_effect: EffectCallback, _deps?: DependencyList): void {},\n useSyncExternalStore<T>(\n _subscribe: ExternalStoreSubscribe,\n _getSnapshot: () => T,\n getServerSnapshot?: () => T,\n ): T {\n if (getServerSnapshot === undefined) {\n throw new Error(options.externalStoreError);\n }\n\n return getServerSnapshot();\n },\n useStableEvent<Args extends unknown[], Result>(\n _handler: (...args: Args) => Result,\n ): (...args: StableEventCallerArgs<Args>) => Result {\n return (..._args: StableEventCallerArgs<Args>): Result => {\n throw new Error(\"Stable events cannot be called during server render.\");\n };\n },\n readContext<T>(context: FigContext<T>): T {\n return readContextValue(options.contextValues, context);\n },\n readData<TArgs extends unknown[], TValue>(\n resource: DataResource<TArgs, TValue>,\n args: TArgs,\n ): TValue {\n return options.readData(resource, args);\n },\n preloadData<TArgs extends unknown[], TValue>(\n resource: DataResource<TArgs, TValue>,\n args: TArgs,\n ): void {\n options.preloadData(resource, args);\n },\n readPromise<T>(promise: PromiseLike<T>): T {\n return options.readPromise(promise);\n },\n };\n}\n\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function componentStack(stack: StackFrame | null): string {\n const frames: string[] = [];\n for (let frame = stack; frame !== null; frame = frame.parent) {\n frames.push(` at ${frame.name}`);\n }\n return frames.length === 0 ? \"\" : `\\n${frames.join(\"\\n\")}`;\n}\n\nexport function nonceAttribute(nonce: string | undefined): string {\n return nonce === undefined ? \"\" : ` nonce=\"${escapeAttribute(nonce)}\"`;\n}\n","import type { PreloadResource, Props } from \"@bgub/fig\";\n\nexport function imagePreloadFromHostProps(\n type: string,\n props: Props,\n suppressed: boolean,\n): PreloadResource | null {\n if (suppressed || type.toLowerCase() !== \"img\") return null;\n if (props.loading === \"lazy\" || props.fetchpriority === \"low\") return null;\n\n const src = stringProp(props.src);\n const srcset = stringProp(props.srcset);\n if (\n (props.src != null && typeof props.src !== \"string\") ||\n (props.srcset != null && typeof props.srcset !== \"string\") ||\n (!src && !srcset) ||\n isDataUrl(src) ||\n isDataUrl(srcset)\n ) {\n return null;\n }\n\n return {\n as: \"image\",\n crossorigin: imageCrossorigin(props.crossorigin),\n fetchpriority: imageFetchpriority(props.fetchpriority),\n href: src || undefined,\n imagesizes: srcset ? stringProp(props.sizes) : undefined,\n imagesrcset: srcset || undefined,\n kind: \"preload\",\n referrerpolicy: stringProp(props.referrerpolicy),\n type: stringProp(props.type),\n };\n}\n\nexport function suppressesImagePreloads(type: string): boolean {\n const normalizedType = type.toLowerCase();\n return normalizedType === \"picture\" || normalizedType === \"noscript\";\n}\n\nfunction stringProp(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction isDataUrl(value: string | undefined): boolean {\n return value?.slice(0, 5).toLowerCase() === \"data:\";\n}\n\nfunction imageCrossorigin(value: unknown): PreloadResource[\"crossorigin\"] {\n if (typeof value !== \"string\") return undefined;\n if (value === \"anonymous\" || value === \"use-credentials\" || value === \"\") {\n return value;\n }\n return \"\";\n}\n\nfunction imageFetchpriority(value: unknown): PreloadResource[\"fetchpriority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