@bgub/fig 0.1.0-alpha.5 → 0.1.0-alpha.7

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/dist/{element-BVg1bKOz.d.ts → element-Od8CmsBL.d.ts} +4 -3
  3. package/dist/{element-DmbzNH0T.js → element-wieeFL9f.js} +8 -4
  4. package/dist/{element-DmbzNH0T.js.map → element-wieeFL9f.js.map} +1 -1
  5. package/dist/{hooks-B7BTQWiu.d.ts → hooks-BSqKOOez.d.ts} +9 -2
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.js +3 -3
  8. package/dist/internal.d.ts +4 -4
  9. package/dist/internal.js +28 -5
  10. package/dist/internal.js.map +1 -1
  11. package/dist/jsx-runtime.d.ts +1 -1
  12. package/dist/jsx-runtime.js +1 -1
  13. package/dist/{payload-format-KTNaSI4h.js → payload-format-Dgap54q-.js} +4 -4
  14. package/dist/payload-format-Dgap54q-.js.map +1 -0
  15. package/dist/payload.d.ts +5 -3
  16. package/dist/payload.js +119 -111
  17. package/dist/payload.js.map +1 -1
  18. package/dist/{resource-DskjKeuM.js → resource-BfNHyXun.js} +47 -17
  19. package/dist/resource-BfNHyXun.js.map +1 -0
  20. package/dist/{transition-CC4kjjrU.js → transition-DBjQTorq.js} +7 -7
  21. package/dist/transition-DBjQTorq.js.map +1 -0
  22. package/dist-development/{element-B7mCQIMi.js → element-Bb5fLsPy.js} +8 -4
  23. package/dist-development/{element-B7mCQIMi.js.map → element-Bb5fLsPy.js.map} +1 -1
  24. package/dist-development/index.js +3 -3
  25. package/dist-development/internal.js +28 -5
  26. package/dist-development/internal.js.map +1 -1
  27. package/dist-development/jsx-runtime.js +1 -1
  28. package/dist-development/{payload-format-KTNaSI4h.js → payload-format-Dgap54q-.js} +4 -4
  29. package/dist-development/payload-format-Dgap54q-.js.map +1 -0
  30. package/dist-development/payload.js +119 -111
  31. package/dist-development/payload.js.map +1 -1
  32. package/dist-development/{resource-CP2OynG0.js → resource-Cp01PvqW.js} +47 -17
  33. package/dist-development/resource-Cp01PvqW.js.map +1 -0
  34. package/dist-development/{transition-B4XiOWAj.js → transition-CNVJyoT2.js} +7 -7
  35. package/dist-development/transition-CNVJyoT2.js.map +1 -0
  36. package/package.json +1 -1
  37. package/dist/payload-format-KTNaSI4h.js.map +0 -1
  38. package/dist/resource-DskjKeuM.js.map +0 -1
  39. package/dist/transition-CC4kjjrU.js.map +0 -1
  40. package/dist-development/payload-format-KTNaSI4h.js.map +0 -1
  41. package/dist-development/resource-CP2OynG0.js.map +0 -1
  42. package/dist-development/transition-B4XiOWAj.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { A as Fragment, C as FigNode, j as Key, l as ElementType, y as FigElement } from "./element-BVg1bKOz.js";
1
+ import { A as Fragment, C as FigNode, j as Key, l as ElementType, y as FigElement } from "./element-Od8CmsBL.js";
2
2
  //#region src/jsx-runtime.d.ts
3
3
  type JSXProps = Record<string, unknown>;
4
4
  declare function jsx(type: ElementType, props: JSXProps | null, key?: string | number): FigElement;
@@ -1,4 +1,4 @@
1
- import { M as resolveHostMix, f as Fragment, s as FigElementSymbol } from "./element-DmbzNH0T.js";
1
+ import { N as resolveHostMix, f as Fragment, s as FigElementSymbol } from "./element-wieeFL9f.js";
2
2
  //#region src/jsx-runtime.ts
3
3
  function jsx(type, props, key) {
4
4
  if (props !== null && "key" in props) {
@@ -149,7 +149,7 @@ function encodePayloadValueWithGraph(value, graph) {
149
149
  };
150
150
  }
151
151
  if (typeof value === "function") throw new Error("Functions cannot be serialized into the payload.");
152
- if (Array.isArray(value)) return serializePayloadArray(value, graph, () => value, (item) => encodePayloadValueWithGraph(item, graph));
152
+ if (Array.isArray(value)) return serializePayloadArray(value, graph, (item) => encodePayloadValueWithGraph(item, graph));
153
153
  if (value instanceof Date) {
154
154
  const json = value.toJSON();
155
155
  if (json === null) throw new Error("Invalid Date values cannot be serialized.");
@@ -211,13 +211,13 @@ function definePayloadGraphElement(graph, value) {
211
211
  if (existing !== null) return existing;
212
212
  return definePayloadGraphObject(graph, value);
213
213
  }
214
- function serializePayloadArray(value, graph, entries, encodeChild) {
214
+ function serializePayloadArray(value, graph, encodeChild) {
215
215
  const existing = payloadGraphReference(graph, value);
216
216
  if (existing !== null) return existing;
217
217
  return {
218
218
  $fig: "array",
219
219
  id: definePayloadGraphObject(graph, value),
220
- value: entries().map(encodeChild)
220
+ value: value.map(encodeChild)
221
221
  };
222
222
  }
223
223
  function serializePayloadPlainObject(value, graph, encodeChild) {
@@ -363,4 +363,4 @@ function isPayloadSpecialModel(model) {
363
363
  //#endregion
364
364
  export { serializePayloadArray as _, decodePayloadRecord as a, serializePayloadSet as b, definePayloadGraphElement as c, encodePayloadValueWithGraph as d, errorFromPayloadValue as f, rollbackPayloadGraph as g, jsonPayloadCodec as h, decodePayloadDataEntries as i, encodePayloadDataEntries as l, isPlainPayloadValue as m, checkpointPayloadGraph as n, decodePayloadValue as o, isPayloadSpecialModel as p, createPayloadGraphEncodeContext as r, decodePayloadValueTag as s, assertPayloadCodecMatches as t, encodePayloadValue as u, serializePayloadMap as v, serializePayloadPlainObject as y };
365
365
 
366
- //# sourceMappingURL=payload-format-KTNaSI4h.js.map
366
+ //# sourceMappingURL=payload-format-Dgap54q-.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payload-format-Dgap54q-.js","names":[],"sources":["../src/payload-format.ts"],"sourcesContent":["import type { FigDataHydrationEntry } from \"./data.ts\";\nimport type { Key } from \"./element.ts\";\nimport type {\n FontResource,\n MetaResource,\n ModulePreloadResource,\n PreconnectResource,\n PreloadResource,\n ScriptResource,\n StylesheetResource,\n TitleResource,\n} from \"./resource.ts\";\n\n// Asset resources represented as descriptor data. Optional fields stay optional\n// on the wire; omitted `undefined` values are part of the payload contract, not\n// a serializer implementation detail. Delivery assets prepare eagerly at row\n// arrival; document metadata stays attached to its owning decoded row until\n// that row commits.\nexport type SerializedAssetResource =\n | {\n crossorigin?: StylesheetResource[\"crossorigin\"];\n href: string;\n kind: \"stylesheet\";\n media?: string;\n precedence?: string;\n }\n | {\n as: string;\n crossorigin?: PreloadResource[\"crossorigin\"];\n fetchpriority?: PreloadResource[\"fetchpriority\"];\n href?: string;\n imagesizes?: PreloadResource[\"imagesizes\"];\n imagesrcset?: PreloadResource[\"imagesrcset\"];\n kind: \"preload\";\n referrerpolicy?: PreloadResource[\"referrerpolicy\"];\n type?: string;\n }\n | {\n crossorigin?: ModulePreloadResource[\"crossorigin\"];\n fetchpriority?: ModulePreloadResource[\"fetchpriority\"];\n href: string;\n kind: \"modulepreload\";\n }\n | {\n async?: boolean;\n crossorigin?: ScriptResource[\"crossorigin\"];\n defer?: boolean;\n kind: \"script\";\n module?: boolean;\n src: string;\n }\n | {\n crossorigin?: FontResource[\"crossorigin\"];\n fetchpriority?: FontResource[\"fetchpriority\"];\n href: string;\n kind: \"font\";\n type: string;\n }\n | {\n crossorigin?: PreconnectResource[\"crossorigin\"];\n href: string;\n kind: \"preconnect\";\n }\n | {\n kind: \"title\";\n value: TitleResource[\"value\"];\n }\n | {\n charset?: MetaResource[\"charset\"];\n content?: MetaResource[\"content\"];\n \"http-equiv\"?: MetaResource[\"http-equiv\"];\n key?: string;\n kind: \"meta\";\n name?: MetaResource[\"name\"];\n property?: MetaResource[\"property\"];\n };\n\n/** The `error` row value under the server's `onError` contract. */\nexport interface PayloadErrorValue {\n digest?: string;\n message?: string;\n}\n\n/**\n * Semantic payload row before the internal codec turns it into bytes.\n */\nexport type PayloadRow =\n | { for?: number; tag: \"assets\"; value: SerializedAssetResource[] }\n | {\n id: number;\n tag: \"client\";\n value: {\n id: string;\n assets?: SerializedAssetResource[];\n exportName?: string;\n ssr?: true;\n };\n }\n | { tag: \"data\"; value: PayloadDataHydrationEntry[] }\n | { id: number; tag: \"error\"; value: PayloadErrorValue }\n | { id: number; tag: \"model\"; value: PayloadModel };\n\n/**\n * Transport-safe model value used inside internal payload rows. This is an\n * implementation format, not an application data format.\n */\nexport type PayloadModel =\n | null\n | boolean\n | number\n | string\n | PayloadModel[]\n | { [key: string]: PayloadModel }\n | PayloadElementModel\n | PayloadSpecialModel;\n\nexport type PayloadElementModel = {\n $fig: \"element\";\n id?: number;\n key: Key | null;\n props: PayloadModel;\n type: string | PayloadSpecialModel;\n};\n\nexport type PayloadSpecialModel =\n | { $fig: \"array\"; id: number; value: PayloadModel[] }\n | { $fig: \"bigint\"; value: string }\n | { $fig: \"client\"; id: number }\n | { $fig: \"date\"; value: string }\n | { $fig: \"fragment\" }\n | { $fig: \"lazy\"; id: number }\n | { $fig: \"map\"; entries: Array<[PayloadModel, PayloadModel]>; id: number }\n | { $fig: \"number\"; value: \"Infinity\" | \"-Infinity\" | \"-0\" | \"NaN\" }\n | { $fig: \"object\"; id?: number; value: Record<string, PayloadModel> }\n | { $fig: \"promise\"; id: number }\n | { $fig: \"ref\"; id: number }\n | { $fig: \"set\"; id: number; values: PayloadModel[] }\n | { $fig: \"symbol\"; key: string }\n | { $fig: \"suspense\" }\n | { $fig: \"undefined\" }\n | { $fig: \"view-transition\" };\n\nexport type PayloadValueSpecialModel = Extract<\n PayloadSpecialModel,\n {\n $fig:\n | \"array\"\n | \"bigint\"\n | \"date\"\n | \"map\"\n | \"number\"\n | \"object\"\n | \"ref\"\n | \"set\"\n | \"symbol\"\n | \"undefined\";\n }\n>;\n\nexport type PayloadDataHydrationEntry = Omit<FigDataHydrationEntry, \"value\"> & {\n value: PayloadModel;\n};\n\nexport interface PayloadCodec {\n /**\n * Opaque implementation id, e.g. \"json\" or \"binary\". Fig checks this id at\n * transport boundaries; the encoded byte layout is not a public contract.\n */\n readonly id: string;\n readonly contentType: string;\n /**\n * Creates a streaming row decoder. The decoder calls `onRow` for each\n * complete semantic row. If `onRow` throws, the decoder must propagate that\n * error; when it can already see more complete sibling rows in the same\n * input chunk, it should process those siblings before rethrowing so\n * notifications already implied by earlier rows are not lost.\n */\n createDecoder(onRow: (row: PayloadRow) => void): PayloadRowDecoder;\n encodeRow(row: PayloadRow): Uint8Array;\n}\n\nexport interface PayloadRowDecoder {\n decode(chunk: Uint8Array): void;\n flush(): void;\n}\n\nconst textEncoder = new TextEncoder();\n\n/**\n * Readable development-oriented codec: one JSON payload row per newline.\n */\nexport const jsonPayloadCodec: PayloadCodec = {\n id: \"json\",\n contentType: \"text/x-fig-payload; codec=json; charset=utf-8\",\n createDecoder(onRow) {\n return createJsonPayloadDecoder(onRow);\n },\n encodeRow(row) {\n return textEncoder.encode(`${JSON.stringify(row)}\\n`);\n },\n};\n\nfunction createJsonPayloadDecoder(\n onRow: (row: PayloadRow) => void,\n): PayloadRowDecoder {\n const decoder = new TextDecoder();\n let buffer = \"\";\n let searchStart = 0;\n\n function processBufferedLines(): void {\n let lineStart = 0;\n let firstError: unknown;\n\n for (;;) {\n const newlineIndex = buffer.indexOf(\"\\n\", searchStart);\n if (newlineIndex === -1) {\n searchStart = buffer.length;\n break;\n }\n try {\n processPayloadLine(buffer.slice(lineStart, newlineIndex), onRow);\n } catch (error) {\n firstError ??= error;\n }\n lineStart = newlineIndex + 1;\n searchStart = lineStart;\n }\n\n if (firstError !== undefined) {\n buffer = \"\";\n searchStart = 0;\n throw firstError;\n }\n if (lineStart > 0) {\n buffer = buffer.slice(lineStart);\n searchStart -= lineStart;\n }\n }\n\n return {\n decode(chunk) {\n buffer += decoder.decode(chunk, { stream: true });\n processBufferedLines();\n },\n flush() {\n buffer += decoder.decode();\n if (buffer.length > 0) {\n const line = buffer;\n buffer = \"\";\n searchStart = 0;\n processPayloadLine(line, onRow);\n }\n },\n };\n}\n\nfunction processPayloadLine(\n line: string,\n onRow: (row: PayloadRow) => void,\n): void {\n if (line.length > 0) onRow(JSON.parse(line) as PayloadRow);\n}\n\n/**\n * Extract the codec id from a payload content-type header, or null when the\n * header carries no codec parameter.\n */\nexport function payloadCodecIdFromContentType(\n contentTypeHeader: string,\n): string | null {\n const parts = contentTypeHeader.split(\";\").slice(1);\n for (const part of parts) {\n const [name, rawValue] = part.split(\"=\");\n if (name?.trim().toLowerCase() !== \"codec\") continue;\n const value = rawValue?.trim();\n if (value === undefined || value.length === 0) return null;\n return value.replace(/^\"|\"$/g, \"\");\n }\n return null;\n}\n\n/**\n * Throw when a response content-type declares a codec other than the one this\n * client decodes with. A missing header or codec parameter passes: transports\n * that strip content types stay usable, and mismatches still fail fast when\n * declared.\n */\nexport function assertPayloadCodecMatches(\n codec: PayloadCodec,\n contentTypeHeader: string | null,\n): void {\n if (contentTypeHeader === null) return;\n const received = payloadCodecIdFromContentType(contentTypeHeader);\n if (received === null || received === codec.id) return;\n throw new Error(\n `Payload codec mismatch: producer used \"${received}\" but this client expects \"${codec.id}\".`,\n );\n}\n\n/** Decode an `error` row value into a digest-carrying Error. */\nexport function errorFromPayloadValue(value: PayloadErrorValue): Error & {\n digest?: string;\n} {\n const error = new Error(value.message ?? \"The server render failed.\");\n return value.digest === undefined\n ? error\n : Object.assign(error, { digest: value.digest });\n}\n\nexport interface PayloadGraphEncodeContext {\n // Ids are dense and monotonic: id = position in `defined` + 1, so rollback\n // is popping the stack. A reverse id→object map would be redundant state.\n defined: object[];\n ids: WeakMap<object, number>;\n}\n\ninterface PayloadGraphDecodeContext {\n decodeChild: (model: PayloadModel) => unknown;\n refs: PayloadDecodeRefs;\n}\n\nfunction createPayloadGraphDecodeContext(): PayloadGraphDecodeContext {\n const refs = new Map<number, unknown>();\n const context: PayloadGraphDecodeContext = {\n decodeChild: (model) => decodeModelValue(model, context),\n refs: {\n define(id, create, fill) {\n const value = create();\n refs.set(id, value);\n fill(value);\n return value;\n },\n read(id) {\n if (!refs.has(id)) {\n throw new Error(`Payload referenced unknown object id ${id}.`);\n }\n return refs.get(id);\n },\n },\n };\n return context;\n}\n\nexport function createPayloadGraphEncodeContext(): PayloadGraphEncodeContext {\n return { defined: [], ids: new WeakMap() };\n}\n\nexport function isPlainPayloadValue(value: unknown): boolean {\n return (\n value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"bigint\" ||\n typeof value === \"symbol\"\n );\n}\n\n/**\n * Encode ordinary data values into PayloadModel. Server component references\n * such as Fig elements, promises, and client references are handled by the\n * payload renderer before ordinary values reach this helper.\n */\nexport function encodePayloadValue(value: unknown): PayloadModel {\n return encodePayloadValueWithGraph(value, createPayloadGraphEncodeContext());\n}\n\nexport function encodePayloadValueWithGraph(\n value: unknown,\n graph: PayloadGraphEncodeContext,\n): PayloadModel {\n if (value === null) return null;\n if (value === undefined) return { $fig: \"undefined\" };\n\n if (typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") return encodePayloadNumber(value);\n if (typeof value === \"bigint\") {\n return { $fig: \"bigint\", value: value.toString() };\n }\n if (typeof value === \"symbol\") {\n const key = Symbol.keyFor(value);\n if (key === undefined) {\n throw new Error(\"Only global Symbol.for symbols can be serialized.\");\n }\n return { $fig: \"symbol\", key };\n }\n if (typeof value === \"function\") {\n throw new Error(\"Functions cannot be serialized into the payload.\");\n }\n\n if (Array.isArray(value)) {\n return serializePayloadArray(value, graph, (item) =>\n encodePayloadValueWithGraph(item, graph),\n );\n }\n if (value instanceof Date) {\n const json = value.toJSON();\n if (json === null) {\n throw new Error(\"Invalid Date values cannot be serialized.\");\n }\n return { $fig: \"date\", value: json };\n }\n if (value instanceof Map) {\n return serializePayloadMap(value, graph, ([key, item]) => [\n encodePayloadValueWithGraph(key, graph),\n encodePayloadValueWithGraph(item, graph),\n ]);\n }\n if (value instanceof Set) {\n return serializePayloadSet(value, graph, (item) =>\n encodePayloadValueWithGraph(item, graph),\n );\n }\n\n if (typeof value === \"object\" && value !== null) {\n return serializePayloadPlainObject(value, graph, (child) =>\n encodePayloadValueWithGraph(child, graph),\n );\n }\n\n throw new Error(`Cannot serialize ${typeof value} into the payload.`);\n}\n\nexport function serializePayloadMap(\n value: Map<unknown, unknown>,\n graph: PayloadGraphEncodeContext,\n encodeEntry: (entry: [unknown, unknown]) => [PayloadModel, PayloadModel],\n): PayloadModel {\n const existing = payloadGraphReference(graph, value);\n if (existing !== null) return existing;\n const id = definePayloadGraphObject(graph, value);\n const entries: Array<[PayloadModel, PayloadModel]> = [];\n for (const entry of value) entries.push(encodeEntry(entry));\n return { $fig: \"map\", id, entries };\n}\n\nexport function serializePayloadSet(\n value: Set<unknown>,\n graph: PayloadGraphEncodeContext,\n encodeItem: (value: unknown) => PayloadModel,\n): PayloadModel {\n const existing = payloadGraphReference(graph, value);\n if (existing !== null) return existing;\n const id = definePayloadGraphObject(graph, value);\n const values: PayloadModel[] = [];\n for (const item of value) values.push(encodeItem(item));\n return { $fig: \"set\", id, values };\n}\n\nfunction payloadGraphReference(\n graph: PayloadGraphEncodeContext,\n value: object,\n): PayloadSpecialModel | null {\n const id = graph.ids.get(value);\n return id === undefined ? null : { $fig: \"ref\", id };\n}\n\nfunction definePayloadGraphObject(\n graph: PayloadGraphEncodeContext,\n value: object,\n): number {\n graph.defined.push(value);\n const id = graph.defined.length;\n graph.ids.set(value, id);\n return id;\n}\n\nexport function checkpointPayloadGraph(\n graph: PayloadGraphEncodeContext,\n): number {\n return graph.defined.length;\n}\n\nexport function rollbackPayloadGraph(\n graph: PayloadGraphEncodeContext,\n checkpoint: number,\n): void {\n while (graph.defined.length > checkpoint) {\n graph.ids.delete(graph.defined.pop() as object);\n }\n}\n\nexport function definePayloadGraphElement(\n graph: PayloadGraphEncodeContext,\n value: object,\n): number | PayloadSpecialModel {\n const existing = payloadGraphReference(graph, value);\n if (existing !== null) return existing;\n return definePayloadGraphObject(graph, value);\n}\n\nexport function serializePayloadArray<T>(\n value: readonly T[],\n graph: PayloadGraphEncodeContext,\n encodeChild: (value: T) => PayloadModel,\n): PayloadModel {\n const existing = payloadGraphReference(graph, value);\n if (existing !== null) return existing;\n const id = definePayloadGraphObject(graph, value);\n return { $fig: \"array\", id, value: value.map(encodeChild) };\n}\n\nexport function serializePayloadPlainObject(\n value: object,\n graph: PayloadGraphEncodeContext,\n encodeChild: (value: unknown) => PayloadModel,\n): PayloadModel {\n const existing = payloadGraphReference(graph, value);\n if (existing !== null) return existing;\n const id = definePayloadGraphObject(graph, value);\n return {\n $fig: \"object\",\n id,\n value: encodePayloadRecord(plainPayloadObject(value), encodeChild),\n };\n}\n\nfunction plainPayloadObject(value: object): Record<string, unknown> {\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(\n `Cannot serialize ${prototype?.constructor?.name ?? \"object\"} into the payload.`,\n );\n }\n return value as Record<string, unknown>;\n}\n\nfunction encodePayloadRecord(\n record: Record<string, unknown>,\n encodeChild: (value: unknown) => PayloadModel,\n): Record<string, PayloadModel> {\n const encoded: Record<string, PayloadModel> = {};\n for (const [name, child] of Object.entries(record)) {\n encoded[name] = encodeChild(child);\n }\n return encoded;\n}\n\nfunction encodePayloadNumber(value: number): number | PayloadSpecialModel {\n if (Number.isNaN(value)) return { $fig: \"number\", value: \"NaN\" };\n if (value === Infinity) return { $fig: \"number\", value: \"Infinity\" };\n if (value === -Infinity) return { $fig: \"number\", value: \"-Infinity\" };\n if (Object.is(value, -0)) return { $fig: \"number\", value: \"-0\" };\n return value;\n}\n\n/** Decode values produced by encodePayloadValue. */\nexport function decodePayloadValue(model: PayloadModel): unknown {\n return decodeModelValue(model, createPayloadGraphDecodeContext());\n}\n\nfunction decodeModelValue(\n model: PayloadModel,\n graph: PayloadGraphDecodeContext,\n): unknown {\n if (model === null) return null;\n if (Array.isArray(model))\n return model.map((item) => decodeModelValue(item, graph));\n if (typeof model !== \"object\") return model;\n\n if (isPayloadValueSpecialModel(model)) {\n return decodePayloadValueTag(model, graph.refs, graph.decodeChild);\n }\n\n return decodePayloadRecord(model, graph.decodeChild);\n}\n\nexport function isPayloadValueSpecialModel(\n model: object,\n): model is PayloadValueSpecialModel {\n if (!(\"$fig\" in model)) return false;\n const tag = model.$fig;\n return (\n tag === \"bigint\" ||\n tag === \"array\" ||\n tag === \"date\" ||\n tag === \"map\" ||\n tag === \"number\" ||\n tag === \"object\" ||\n tag === \"ref\" ||\n tag === \"set\" ||\n tag === \"symbol\" ||\n tag === \"undefined\"\n );\n}\n\n// The ref-store seam shared by the two decode entry points: the value codec\n// registers into a per-call refs map, while the stream decoder registers into\n// its request-wide chunk-adjacent store (with rollback on failed fills).\nexport interface PayloadDecodeRefs {\n define<T>(id: number, create: () => T, fill: (value: T) => void): T;\n read(id: number): unknown;\n}\n\nexport function decodePayloadValueTag(\n model: PayloadValueSpecialModel,\n refs: PayloadDecodeRefs,\n decodeChild: (model: PayloadModel) => unknown,\n): unknown {\n switch (model.$fig) {\n case \"array\":\n return refs.define<unknown[]>(\n model.id,\n () => [],\n (value) => {\n for (const item of model.value) value.push(decodeChild(item));\n },\n );\n case \"bigint\":\n return BigInt(model.value);\n case \"date\":\n return new Date(model.value);\n case \"map\":\n return refs.define(\n model.id,\n () => new Map<unknown, unknown>(),\n (value) => {\n for (const [key, item] of model.entries) {\n value.set(decodeChild(key), decodeChild(item));\n }\n },\n );\n case \"number\":\n return decodePayloadNumber(model.value);\n case \"object\": {\n if (model.id === undefined) {\n return decodePayloadRecord(model.value, decodeChild);\n }\n return refs.define(\n model.id,\n () => ({}),\n (value) => {\n for (const [name, child] of Object.entries(model.value)) {\n definePayloadProperty(value, name, decodeChild(child));\n }\n },\n );\n }\n case \"ref\":\n return refs.read(model.id);\n case \"set\":\n return refs.define(\n model.id,\n () => new Set<unknown>(),\n (value) => {\n for (const item of model.values) value.add(decodeChild(item));\n },\n );\n case \"symbol\":\n return Symbol.for(model.key);\n case \"undefined\":\n return undefined;\n }\n}\n\nexport function decodePayloadRecord(\n value: Record<string, PayloadModel>,\n decodeChild: (model: PayloadModel) => unknown,\n): Record<string, unknown> {\n const decoded: Record<string, unknown> = {};\n for (const [name, child] of Object.entries(value)) {\n definePayloadProperty(decoded, name, decodeChild(child));\n }\n return decoded;\n}\n\n// \"__proto__\" must go through defineProperty so a hostile payload key defines\n// an own property instead of mutating the prototype chain via the setter\n// path; every other key gets the identical own data property from plain\n// assignment at a fraction of the cost (this is the decode inner loop).\nexport function definePayloadProperty(\n target: Record<string, unknown>,\n name: string,\n value: unknown,\n): void {\n if (name === \"__proto__\") {\n Object.defineProperty(target, name, {\n configurable: true,\n enumerable: true,\n value,\n writable: true,\n });\n return;\n }\n target[name] = value;\n}\n\nexport function decodePayloadNumber(\n value: \"Infinity\" | \"-Infinity\" | \"-0\" | \"NaN\",\n): number {\n switch (value) {\n case \"Infinity\":\n return Infinity;\n case \"-Infinity\":\n return -Infinity;\n case \"-0\":\n return -0;\n case \"NaN\":\n return NaN;\n }\n}\n\nexport function encodePayloadDataEntries(\n entries: readonly FigDataHydrationEntry[],\n): PayloadDataHydrationEntry[] {\n const graph = createPayloadGraphEncodeContext();\n return entries.map((entry) => ({\n ...entry,\n value: encodePayloadValueWithGraph(entry.value, graph),\n }));\n}\n\nexport function decodePayloadDataEntries(\n entries: readonly PayloadDataHydrationEntry[],\n): FigDataHydrationEntry[] {\n const graph = createPayloadGraphDecodeContext();\n return entries.map((entry) => ({\n ...entry,\n value: decodeModelValue(entry.value, graph),\n }));\n}\n\nexport function isPayloadSpecialModel(\n model: object,\n): model is PayloadElementModel | PayloadSpecialModel {\n if (!(\"$fig\" in model)) return false;\n\n switch (model.$fig) {\n case \"array\":\n case \"bigint\":\n case \"client\":\n case \"date\":\n case \"element\":\n case \"fragment\":\n case \"lazy\":\n case \"map\":\n case \"number\":\n case \"object\":\n case \"promise\":\n case \"ref\":\n case \"set\":\n case \"suspense\":\n case \"symbol\":\n case \"undefined\":\n case \"view-transition\":\n return true;\n default:\n return false;\n }\n}\n"],"mappings":";AA0LA,MAAM,cAAc,IAAI,YAAY;;;;AAKpC,MAAa,mBAAiC;CAC5C,IAAI;CACJ,aAAa;CACb,cAAc,OAAO;EACnB,OAAO,yBAAyB,KAAK;CACvC;CACA,UAAU,KAAK;EACb,OAAO,YAAY,OAAO,GAAG,KAAK,UAAU,GAAG,EA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AG;EAC7B,KAAK,aACH;CACJ;AACF;AAEA,SAAgB,oBACd,OACA,aACyB;CACzB,MAAM,UAAmC,CAAC;CAC1C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,GAC9C,sBAAsB,SAAS,MAAM,YAAY,KAAK,CAAC;CAEzD,OAAO;AACT;AAMA,SAAgB,sBACd,QACA,MACA,OACM;CACN,IAAI,SAAS,aAAa;EACxB,OAAO,eAAe,QAAQ,MAAM;GAClC,cAAc;GACd,YAAY;GACZ;GACA,UAAU;EACZ,CAAC;EACD;CACF;CACA,OAAO,QAAQ;AACjB;AAEA,SAAgB,oBACd,OACQ;CACR,QAAQ,OAAR;EACE,KAAK,YACH,OAAO;EACT,KAAK,aACH,OAAO;EACT,KAAK,MACH,OAAO;EACT,KAAK,OACH,OAAO;CACX;AACF;AAEA,SAAgB,yBACd,SAC6B;CAC7B,MAAM,QAAQ,gCAAgC;CAC9C,OAAO,QAAQ,KAAK,WAAW;EAC7B,GAAG;EACH,OAAO,4BAA4B,MAAM,OAAO,KAAK;CACvD,EAAE;AACJ;AAEA,SAAgB,yBACd,SACyB;CACzB,MAAM,QAAQ,gCAAgC;CAC9C,OAAO,QAAQ,KAAK,WAAW;EAC7B,GAAG;EACH,OAAO,iBAAiB,MAAM,OAAO,KAAK;CAC5C,EAAE;AACJ;AAEA,SAAgB,sBACd,OACoD;CACpD,IAAI,EAAE,UAAU,QAAQ,OAAO;CAE/B,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,mBACH,OAAO;EACT,SACE,OAAO;CACX;AACF"}
package/dist/payload.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Wt as FigDataHydrationEntry, a as AwaitedFigNode, ct as FigAssetResource, l as ElementType } from "./element-BVg1bKOz.js";
2
- //#region src/payload.d.ts
1
+ import { Gt as FigDataHydrationEntry, a as AwaitedFigNode, ct as FigAssetResource, l as ElementType } from "./element-Od8CmsBL.js";
2
+ //#region src/payload-client-reference.d.ts
3
3
  interface PayloadClientReference {
4
4
  assets?: readonly FigAssetResource[];
5
5
  exportName?: string;
@@ -21,6 +21,8 @@ interface PayloadClientReferenceResolver {
21
21
  delete(id: string): boolean;
22
22
  }
23
23
  declare function createPayloadClientReferenceResolver(resolve: ResolveClientReference): PayloadClientReferenceResolver;
24
+ //#endregion
25
+ //#region src/payload.d.ts
24
26
  type PayloadDecodeCompletion = {
25
27
  status: "aborted";
26
28
  } | {
@@ -89,4 +91,4 @@ interface PayloadDecodeOptions {
89
91
  */
90
92
  declare function decodePayloadStream(stream: ReadableStream<Uint8Array>, options?: PayloadDecodeOptions): Promise<AwaitedFigNode>;
91
93
  //#endregion
92
- export { PayloadClientReference, PayloadClientReferenceResolver, PayloadDecodeCompletion, PayloadDecodeOptions, ResolveClientReference, createPayloadClientReferenceResolver, decodePayloadStream };
94
+ export { type PayloadClientReference, type PayloadClientReferenceResolver, PayloadDecodeCompletion, PayloadDecodeOptions, type ResolveClientReference, createPayloadClientReferenceResolver, decodePayloadStream };
package/dist/payload.js CHANGED
@@ -1,7 +1,7 @@
1
- import { I as readPromise, f as Fragment, g as createElement, m as ViewTransition, p as Suspense, s as FigElementSymbol } from "./element-DmbzNH0T.js";
2
- import { b as trackThenable, l as isFigAssetResource, o as assets, t as assetResourceDestination, v as isThenable } from "./resource-DskjKeuM.js";
3
- import { a as decodePayloadRecord, f as errorFromPayloadValue, h as jsonPayloadCodec, i as decodePayloadDataEntries, p as isPayloadSpecialModel, s as decodePayloadValueTag } from "./payload-format-KTNaSI4h.js";
4
- //#region src/payload.ts
1
+ import { L as readPromise, f as Fragment, g as createElement, m as ViewTransition, p as Suspense, s as FigElementSymbol } from "./element-wieeFL9f.js";
2
+ import { s as assets, t as assetResourceDestination, u as isFigAssetResource, x as trackThenable, y as isThenable } from "./resource-BfNHyXun.js";
3
+ import { a as decodePayloadRecord, f as errorFromPayloadValue, h as jsonPayloadCodec, i as decodePayloadDataEntries, p as isPayloadSpecialModel, s as decodePayloadValueTag } from "./payload-format-Dgap54q-.js";
4
+ //#region src/payload-client-reference.ts
5
5
  const resolverEntries = /* @__PURE__ */ new WeakMap();
6
6
  function createPayloadClientReferenceResolver(resolve) {
7
7
  const entries = /* @__PURE__ */ new Map();
@@ -12,8 +12,81 @@ function createPayloadClientReferenceResolver(resolve) {
12
12
  resolverEntries.set(resolver, entries);
13
13
  return resolver;
14
14
  }
15
- const elementGates = /* @__PURE__ */ new WeakMap();
16
- const elementAssets = /* @__PURE__ */ new WeakMap();
15
+ const elementDelivery = /* @__PURE__ */ new WeakMap();
16
+ /** Owns client-reference identity and per-decode delivery state. */
17
+ var PayloadClientReferences = class {
18
+ resolve;
19
+ rows = /* @__PURE__ */ new Map();
20
+ constructor(resolve) {
21
+ this.resolve = resolve;
22
+ }
23
+ register(rowId, reference, gate, assets) {
24
+ const hasDelivery = gate !== null || assets !== null;
25
+ if (hasDelivery) {
26
+ const delivery = {};
27
+ if (gate !== null) delivery.gate = gate;
28
+ if (assets !== null) delivery.assets = assets;
29
+ this.rows.set(rowId, delivery);
30
+ if (gate !== null) gate.then(() => {
31
+ delete delivery.gate;
32
+ if (delivery.assets === void 0) this.rows.delete(rowId);
33
+ });
34
+ }
35
+ return this.resolveComponent(reference, hasDelivery);
36
+ }
37
+ attach(rowId, props) {
38
+ const delivery = this.rows.get(rowId);
39
+ if (delivery !== void 0) elementDelivery.set(props, delivery);
40
+ }
41
+ resolveComponent(reference, hasDelivery) {
42
+ const entries = this.resolve === void 0 ? void 0 : resolverEntries.get(this.resolve);
43
+ const existing = entries?.get(reference.id);
44
+ if (existing !== void 0) return existing;
45
+ let resolved;
46
+ try {
47
+ resolved = this.resolve?.(reference);
48
+ } catch (error) {
49
+ resolved = Promise.reject(error);
50
+ }
51
+ if (resolved === void 0) return function PayloadUnresolvedClientComponent() {
52
+ throw new Error(`Cannot render client reference "${reference.id}" because decodePayloadStream was not configured with a matching resolveClientReference.`);
53
+ };
54
+ if (entries === void 0 && !isThenable(resolved) && !hasDelivery) return resolved;
55
+ const component = clientReferenceWrapper(resolved, reference.id);
56
+ entries?.set(reference.id, component);
57
+ return component;
58
+ }
59
+ };
60
+ function clientReferenceWrapper(resolved, referenceId) {
61
+ let render;
62
+ if (isThenable(resolved)) {
63
+ const pending = Promise.resolve(resolved);
64
+ trackThenable(pending);
65
+ let type = null;
66
+ render = (props) => {
67
+ type ??= clientReferenceType(readPromise(pending), referenceId);
68
+ return createElement(type, props);
69
+ };
70
+ } else render = (props) => createElement(resolved, props);
71
+ function PayloadClientContent(content) {
72
+ if (content.gate !== void 0) readPromise(content.gate);
73
+ return render(content.props);
74
+ }
75
+ return function PayloadClientComponent(props) {
76
+ const delivery = elementDelivery.get(props);
77
+ const content = createElement(PayloadClientContent, {
78
+ gate: delivery?.gate,
79
+ props
80
+ });
81
+ return delivery?.assets === void 0 ? content : assets(delivery.assets, content);
82
+ };
83
+ }
84
+ function clientReferenceType(value, id) {
85
+ if (typeof value === "function") return value;
86
+ throw new Error(`Client reference "${id}" did not resolve to a component.`);
87
+ }
88
+ //#endregion
89
+ //#region src/payload.ts
17
90
  var PayloadDecodeAbortedError = class extends Error {
18
91
  constructor(reason) {
19
92
  super("Payload decode aborted.", reason === void 0 ? void 0 : { cause: reason });
@@ -31,9 +104,15 @@ var PayloadDecodeAbortedError = class extends Error {
31
104
  * cancellation reason.
32
105
  */
33
106
  function decodePayloadStream(stream, options = {}) {
34
- return new PayloadStreamDecode(stream, options).value;
107
+ return new PayloadDecoder(stream, options).value;
35
108
  }
36
109
  const noop = () => void 0;
110
+ function notifyObserver(observer, value) {
111
+ try {
112
+ const result = observer?.(value);
113
+ if (isThenable(result)) Promise.resolve(result).then(noop, noop);
114
+ } catch {}
115
+ }
37
116
  function deferred() {
38
117
  let resolve = noop;
39
118
  let reject = noop;
@@ -51,16 +130,14 @@ function decodeAssetResources(serialized) {
51
130
  const assets = serialized.filter(isFigAssetResource);
52
131
  return assets.length === 0 ? null : assets;
53
132
  }
54
- var PayloadStreamDecode = class {
133
+ var PayloadDecoder = class {
55
134
  options;
56
135
  value;
57
136
  chunks = /* @__PURE__ */ new Map();
58
137
  objectRefs = /* @__PURE__ */ new Map();
59
138
  rowGates = /* @__PURE__ */ new Map();
60
139
  rowAssets = /* @__PURE__ */ new Map();
61
- clientRowGates = /* @__PURE__ */ new Map();
62
- clientRowAssets = /* @__PURE__ */ new Map();
63
- rowDecoder;
140
+ clientReferences;
64
141
  reader = null;
65
142
  done = false;
66
143
  gateRelease = deferred();
@@ -75,9 +152,10 @@ var PayloadStreamDecode = class {
75
152
  };
76
153
  constructor(stream, options) {
77
154
  this.options = options;
78
- this.rowDecoder = jsonPayloadCodec.createDecoder((row) => this.handleRow(row));
155
+ this.clientReferences = new PayloadClientReferences(options.resolveClientReference);
156
+ const rowDecoder = jsonPayloadCodec.createDecoder((row) => this.handleRow(row));
79
157
  this.value = this.chunkPromise(this.getChunk(0));
80
- this.ingest(stream);
158
+ this.ingest(stream, rowDecoder);
81
159
  const signal = options.signal;
82
160
  if (signal !== void 0) if (signal.aborted) this.abort(signal.reason);
83
161
  else {
@@ -94,7 +172,7 @@ var PayloadStreamDecode = class {
94
172
  this.rejectUnresolved(error);
95
173
  this.settle({ status: "aborted" });
96
174
  }
97
- async ingest(stream) {
175
+ async ingest(stream, rowDecoder) {
98
176
  const reader = stream.getReader();
99
177
  this.reader = reader;
100
178
  try {
@@ -102,9 +180,9 @@ var PayloadStreamDecode = class {
102
180
  const { done, value } = await reader.read();
103
181
  if (this.done) return;
104
182
  if (done) break;
105
- this.rowDecoder.decode(value);
183
+ rowDecoder.decode(value);
106
184
  }
107
- this.rowDecoder.flush();
185
+ rowDecoder.flush();
108
186
  this.finishIngestion();
109
187
  } catch (error) {
110
188
  if (this.done) return;
@@ -113,12 +191,7 @@ var PayloadStreamDecode = class {
113
191
  }
114
192
  }
115
193
  finishIngestion() {
116
- let truncated = false;
117
194
  for (const chunk of this.chunks.values()) if (!chunk.arrived) {
118
- truncated = true;
119
- break;
120
- }
121
- if (truncated) {
122
195
  this.failIngestion(/* @__PURE__ */ new Error("Payload stream ended before all referenced rows arrived."));
123
196
  return;
124
197
  }
@@ -133,20 +206,17 @@ var PayloadStreamDecode = class {
133
206
  });
134
207
  }
135
208
  rejectUnresolved(error) {
136
- for (const chunk of this.chunks.values()) {
209
+ for (const [id, chunk] of this.chunks) {
137
210
  if (chunk.arrived) continue;
138
211
  chunk.arrived = true;
139
- this.rejectChunk(chunk, error);
212
+ this.rejectChunk(id, chunk, error);
140
213
  }
141
214
  }
142
215
  settle(result) {
143
216
  if (this.done) return;
144
217
  this.done = true;
145
218
  this.removeAbortListener();
146
- try {
147
- const observed = this.options.onStreamDone?.(result);
148
- if (isThenable(observed)) Promise.resolve(observed).then(noop, noop);
149
- } catch {}
219
+ notifyObserver(this.options.onStreamDone, result);
150
220
  }
151
221
  handleRow(row) {
152
222
  if (this.done) return;
@@ -177,16 +247,8 @@ var PayloadStreamDecode = class {
177
247
  const assets = decodeAssetResources(row.value.assets);
178
248
  if (assets !== null) reference.assets = assets;
179
249
  const retainedAssets = this.retainedAssets(assets);
180
- if (retainedAssets !== null) this.clientRowAssets.set(row.id, retainedAssets);
181
250
  const gate = this.prepareAssets(assets);
182
- if (gate !== null) {
183
- trackThenable(gate);
184
- this.clientRowGates.set(row.id, gate);
185
- gate.then(() => {
186
- this.clientRowGates.delete(row.id);
187
- });
188
- }
189
- const component = this.clientReferenceComponent(reference, gate, retainedAssets !== null);
251
+ const component = this.clientReferences.register(row.id, reference, gate, retainedAssets);
190
252
  chunk.arrived = true;
191
253
  this.fulfillChunk(chunk, component);
192
254
  return;
@@ -196,7 +258,7 @@ var PayloadStreamDecode = class {
196
258
  chunk.arrived = true;
197
259
  this.rowGates.delete(row.id);
198
260
  this.rowAssets.delete(row.id);
199
- this.rejectChunk(chunk, errorFromPayloadValue(row.value));
261
+ this.rejectChunk(row.id, chunk, errorFromPayloadValue(row.value));
200
262
  return;
201
263
  }
202
264
  case "data": {
@@ -210,7 +272,8 @@ var PayloadStreamDecode = class {
210
272
  const retainedAssets = this.retainedAssets(decodedAssets);
211
273
  if (retainedAssets !== null && row.for !== void 0) {
212
274
  const retained = this.rowAssets.get(row.for);
213
- this.rowAssets.set(row.for, retained === void 0 ? retainedAssets : [...retained, ...retainedAssets]);
275
+ if (retained === void 0) this.rowAssets.set(row.for, retainedAssets);
276
+ else retained.push(...retainedAssets);
214
277
  }
215
278
  const gate = this.prepareAssets(decodedAssets);
216
279
  if (gate === null || row.for === void 0) return;
@@ -242,33 +305,14 @@ var PayloadStreamDecode = class {
242
305
  const retained = this.options.retainAssets === true ? assets : assets.filter((resource) => assetResourceDestination(resource) === "head");
243
306
  return retained.length === 0 ? null : retained;
244
307
  }
245
- clientReferenceComponent(reference, gate, retainsAssets) {
246
- const resolve = this.options.resolveClientReference;
247
- const entries = resolve === void 0 ? void 0 : resolverEntries.get(resolve);
248
- const existing = entries?.get(reference.id);
249
- if (existing !== void 0) return existing;
250
- let resolved;
251
- try {
252
- resolved = resolve?.(reference);
253
- } catch (error) {
254
- resolved = Promise.reject(error);
255
- }
256
- if (resolved === void 0) return function PayloadUnresolvedClientComponent() {
257
- throw new Error(`Cannot render client reference "${reference.id}" because decodePayloadStream was not configured with a matching resolveClientReference.`);
258
- };
259
- if (entries === void 0 && gate === null && !isThenable(resolved) && !retainsAssets) return resolved;
260
- const component = clientReferenceWrapper(resolved, reference.id);
261
- entries?.set(reference.id, component);
262
- return component;
263
- }
264
308
  getChunk(id) {
265
309
  const existing = this.chunks.get(id);
266
310
  if (existing !== void 0) return existing;
267
311
  const chunk = {
268
312
  arrived: false,
269
- deferred: null,
270
- id,
271
313
  promise: null,
314
+ reject: null,
315
+ resolve: null,
272
316
  result: { status: "pending" }
273
317
  };
274
318
  this.chunks.set(id, chunk);
@@ -280,10 +324,10 @@ var PayloadStreamDecode = class {
280
324
  else if (chunk.result.status === "rejected") {
281
325
  chunk.promise = Promise.reject(chunk.result.error);
282
326
  chunk.promise.catch(noop);
283
- } else {
284
- chunk.deferred = deferred();
285
- chunk.promise = chunk.deferred.promise;
286
- }
327
+ } else chunk.promise = new Promise((resolve, reject) => {
328
+ chunk.resolve = resolve;
329
+ chunk.reject = reject;
330
+ });
287
331
  trackThenable(chunk.promise);
288
332
  return chunk.promise;
289
333
  }
@@ -293,25 +337,23 @@ var PayloadStreamDecode = class {
293
337
  status: "fulfilled",
294
338
  value
295
339
  };
296
- chunk.deferred?.resolve(value);
340
+ chunk.resolve?.(value);
341
+ chunk.resolve = null;
342
+ chunk.reject = null;
297
343
  }
298
- rejectChunk(chunk, error) {
344
+ rejectChunk(id, chunk, error) {
299
345
  if (chunk.result.status !== "pending") return;
300
346
  chunk.result = {
301
347
  error,
302
348
  status: "rejected"
303
349
  };
304
- if (chunk.deferred !== null) {
305
- chunk.deferred.reject(error);
350
+ if (chunk.reject !== null) {
351
+ chunk.reject(error);
306
352
  chunk.promise?.catch(noop);
307
353
  }
308
- if (chunk.id !== 0 && !(error instanceof PayloadDecodeAbortedError)) this.observeHoleError(error);
309
- }
310
- observeHoleError(error) {
311
- try {
312
- const observed = this.options.onHoleError?.(error);
313
- if (isThenable(observed)) Promise.resolve(observed).then(noop, noop);
314
- } catch {}
354
+ chunk.resolve = null;
355
+ chunk.reject = null;
356
+ if (id !== 0 && !(error instanceof PayloadDecodeAbortedError)) notifyObserver(this.options.onHoleError, error);
315
357
  }
316
358
  readChunkForRender(id) {
317
359
  const chunk = this.getChunk(id);
@@ -355,7 +397,7 @@ var PayloadStreamDecode = class {
355
397
  case "fragment": return Fragment;
356
398
  case "lazy":
357
399
  this.getChunk(model.id);
358
- return createElement(PayloadStreamHole, {
400
+ return createElement(PayloadHole, {
359
401
  decode: this,
360
402
  id: model.id
361
403
  });
@@ -371,10 +413,7 @@ var PayloadStreamDecode = class {
371
413
  }
372
414
  attachElementDelivery(typeModel, props) {
373
415
  if (typeof typeModel === "string" || typeModel.$fig !== "client") return;
374
- const gate = this.clientRowGates.get(typeModel.id);
375
- if (gate !== void 0) elementGates.set(props, gate);
376
- const assets = this.clientRowAssets.get(typeModel.id);
377
- if (assets !== void 0) elementAssets.set(props, assets);
416
+ this.clientReferences.attach(typeModel.id, props);
378
417
  }
379
418
  defineObjectRef(id, create, fill) {
380
419
  if (this.objectRefs.has(id)) return this.objectRefs.get(id);
@@ -389,40 +428,9 @@ var PayloadStreamDecode = class {
389
428
  }
390
429
  }
391
430
  };
392
- function PayloadStreamHole(props) {
431
+ function PayloadHole(props) {
393
432
  return props.decode.readChunkForRender(props.id);
394
433
  }
395
- function clientReferenceWrapper(resolved, referenceId) {
396
- let render;
397
- if (!isThenable(resolved)) render = (props) => createElement(resolved, props);
398
- else {
399
- const pending = Promise.resolve(resolved);
400
- trackThenable(pending);
401
- let type = null;
402
- render = (props) => {
403
- if (type === null) type = clientReferenceType(readPromise(pending), referenceId);
404
- return createElement(type, props);
405
- };
406
- }
407
- function PayloadClientContent(content) {
408
- if (content.gate !== void 0) readPromise(content.gate);
409
- return render(content.props);
410
- }
411
- return function PayloadClientComponent(props) {
412
- return attachElementAssets(props, createElement(PayloadClientContent, {
413
- gate: elementGates.get(props),
414
- props
415
- }));
416
- };
417
- }
418
- function attachElementAssets(props, node) {
419
- const resources = elementAssets.get(props);
420
- return resources === void 0 ? node : assets(resources, node);
421
- }
422
- function clientReferenceType(value, id) {
423
- if (typeof value === "function") return value;
424
- throw new Error(`Client reference "${id}" did not resolve to a component.`);
425
- }
426
434
  //#endregion
427
435
  export { createPayloadClientReferenceResolver, decodePayloadStream };
428
436