@shadow-js/web 1.0.6 → 1.1.1

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 (222) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/dev/attributes.d.ts +1 -2
  4. package/dist/dev/autofocus.d.ts +1 -2
  5. package/dist/dev/class-style.d.ts +1 -2
  6. package/dist/dev/component.d.ts +1 -2
  7. package/dist/dev/control-flow/activity.d.ts +1 -2
  8. package/dist/dev/control-flow/client-only.d.ts +1 -2
  9. package/dist/dev/control-flow/dynamic.d.ts +1 -2
  10. package/dist/dev/control-flow/error-boundary.d.ts +1 -2
  11. package/dist/dev/control-flow/for.d.ts +1 -2
  12. package/dist/dev/control-flow/fragment.d.ts +1 -2
  13. package/dist/dev/control-flow/index-list.d.ts +1 -2
  14. package/dist/dev/control-flow/lazy.d.ts +1 -2
  15. package/dist/dev/control-flow/no-hydration.d.ts +1 -2
  16. package/dist/dev/control-flow/portal.d.ts +1 -2
  17. package/dist/dev/control-flow/portal.js.map +1 -1
  18. package/dist/dev/control-flow/root-errors.d.ts +2 -3
  19. package/dist/dev/control-flow/show.d.ts +1 -2
  20. package/dist/dev/control-flow/suspense-list.d.ts +2 -3
  21. package/dist/dev/control-flow/suspense.d.ts +1 -2
  22. package/dist/dev/control-flow/switch.d.ts +1 -2
  23. package/dist/dev/derived.d.ts +1 -2
  24. package/dist/dev/element.d.ts +1 -2
  25. package/dist/dev/events.d.ts +1 -2
  26. package/dist/dev/extend.d.ts +9 -0
  27. package/dist/dev/head/components.d.ts +1 -2
  28. package/dist/dev/head/server-head.d.ts +2 -3
  29. package/dist/dev/head/use-head.d.ts +1 -2
  30. package/dist/dev/head/validate.d.ts +1 -2
  31. package/dist/dev/hmr.d.ts +1 -2
  32. package/dist/dev/hmr.js.map +1 -1
  33. package/dist/dev/hydration.d.ts +1 -2
  34. package/dist/dev/insert.d.ts +1 -2
  35. package/dist/dev/insert.js.map +1 -1
  36. package/dist/dev/internal/claim.d.ts +1 -2
  37. package/dist/dev/internal/diagnostics.d.ts +1 -2
  38. package/dist/dev/internal/hydration-hooks.d.ts +1 -2
  39. package/dist/dev/internal/hydration-scope.d.ts +1 -2
  40. package/dist/dev/internal/names.d.ts +1 -2
  41. package/dist/dev/internal/portal-context.d.ts +1 -2
  42. package/dist/dev/internal/reconcile.d.ts +1 -2
  43. package/dist/dev/internal/reconcile.js.map +1 -1
  44. package/dist/dev/internal/stream-context.d.ts +1 -2
  45. package/dist/dev/jsx/aria.d.ts +7 -2
  46. package/dist/dev/jsx/component.d.ts +7 -2
  47. package/dist/dev/jsx/events.d.ts +1 -2
  48. package/dist/dev/jsx/global.d.ts +11 -2
  49. package/dist/dev/jsx/html.d.ts +8 -2
  50. package/dist/dev/jsx/intrinsic.d.ts +10 -2
  51. package/dist/dev/jsx/mathml.d.ts +8 -2
  52. package/dist/dev/jsx/svg.d.ts +13 -2
  53. package/dist/dev/jsx/types.d.ts +1 -2
  54. package/dist/dev/jsx-dev-runtime.d.ts +6 -0
  55. package/dist/dev/jsx-runtime.d.ts +13 -2
  56. package/dist/dev/reactive.d.ts +1 -2
  57. package/dist/dev/render.d.ts +1 -2
  58. package/dist/dev/resource-hints.d.ts +1 -2
  59. package/dist/dev/select-value.d.ts +1 -2
  60. package/dist/dev/server/attributes.d.ts +1 -2
  61. package/dist/dev/server/class-style.d.ts +1 -2
  62. package/dist/dev/server/component.d.ts +1 -2
  63. package/dist/dev/server/derived.d.ts +1 -2
  64. package/dist/dev/server/element.d.ts +1 -2
  65. package/dist/dev/server/errors.js.map +1 -1
  66. package/dist/dev/server/escape.d.ts +1 -2
  67. package/dist/dev/server/form-controls.d.ts +1 -2
  68. package/dist/dev/server/hydration-script.d.ts +1 -2
  69. package/dist/dev/server/index.d.ts +7 -2
  70. package/dist/dev/server/index.js +2 -2
  71. package/dist/dev/server/node.d.ts +1 -2
  72. package/dist/dev/server/node.js.map +1 -1
  73. package/dist/dev/server/portals.d.ts +1 -2
  74. package/dist/dev/server/portals.js.map +1 -1
  75. package/dist/dev/server/raw-text.d.ts +1 -2
  76. package/dist/dev/server/render.d.ts +1 -2
  77. package/dist/dev/server/serialize.d.ts +1 -2
  78. package/dist/dev/server/stream.d.ts +1 -2
  79. package/dist/dev/server/stream.js.map +1 -1
  80. package/dist/dev/server.d.ts +1 -0
  81. package/dist/dev/spread.d.ts +1 -2
  82. package/dist/dev/template.d.ts +1 -2
  83. package/dist/dev/view-transition.d.ts +1 -2
  84. package/dist/prod/attributes.js.map +1 -1
  85. package/dist/prod/autofocus.js.map +1 -1
  86. package/dist/prod/class-style.js.map +1 -1
  87. package/dist/prod/component.js.map +1 -1
  88. package/dist/prod/control-flow/activity.js.map +1 -1
  89. package/dist/prod/control-flow/branch.js.map +1 -1
  90. package/dist/prod/control-flow/client-only.js.map +1 -1
  91. package/dist/prod/control-flow/dynamic.js.map +1 -1
  92. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  93. package/dist/prod/control-flow/for.js.map +1 -1
  94. package/dist/prod/control-flow/fragment.js.map +1 -1
  95. package/dist/prod/control-flow/hot-link.js.map +1 -1
  96. package/dist/prod/control-flow/index-list.js.map +1 -1
  97. package/dist/prod/control-flow/lazy.js.map +1 -1
  98. package/dist/prod/control-flow/no-hydration.js.map +1 -1
  99. package/dist/prod/control-flow/portal.js.map +1 -1
  100. package/dist/prod/control-flow/root-errors.js.map +1 -1
  101. package/dist/prod/control-flow/show.js.map +1 -1
  102. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  103. package/dist/prod/control-flow/suspense.js.map +1 -1
  104. package/dist/prod/control-flow/switch.js.map +1 -1
  105. package/dist/prod/derived.js.map +1 -1
  106. package/dist/prod/element.js.map +1 -1
  107. package/dist/prod/events.js.map +1 -1
  108. package/dist/prod/head/components.js.map +1 -1
  109. package/dist/prod/head/registry.js.map +1 -1
  110. package/dist/prod/head/server-head.js.map +1 -1
  111. package/dist/prod/head/sink.js.map +1 -1
  112. package/dist/prod/head/use-head.js.map +1 -1
  113. package/dist/prod/head/validate.js.map +1 -1
  114. package/dist/prod/hmr.js.map +1 -1
  115. package/dist/prod/hydration.js.map +1 -1
  116. package/dist/prod/insert.js.map +1 -1
  117. package/dist/prod/internal/accessor.js.map +1 -1
  118. package/dist/prod/internal/claim.js.map +1 -1
  119. package/dist/prod/internal/css-units.js.map +1 -1
  120. package/dist/prod/internal/diagnostics.js.map +1 -1
  121. package/dist/prod/internal/early-events.js.map +1 -1
  122. package/dist/prod/internal/hydration-hooks.js.map +1 -1
  123. package/dist/prod/internal/hydration-scope.js.map +1 -1
  124. package/dist/prod/internal/portal-context.js.map +1 -1
  125. package/dist/prod/internal/react-names.js.map +1 -1
  126. package/dist/prod/internal/reconcile.js.map +1 -1
  127. package/dist/prod/internal/stream-context.js.map +1 -1
  128. package/dist/prod/reactive.js.map +1 -1
  129. package/dist/prod/render.js.map +1 -1
  130. package/dist/prod/resource-hints.js.map +1 -1
  131. package/dist/prod/select-value.js.map +1 -1
  132. package/dist/prod/server/attributes.js.map +1 -1
  133. package/dist/prod/server/class-style.js.map +1 -1
  134. package/dist/prod/server/component.js.map +1 -1
  135. package/dist/prod/server/derived.js.map +1 -1
  136. package/dist/prod/server/element.js.map +1 -1
  137. package/dist/prod/server/errors.js.map +1 -1
  138. package/dist/prod/server/escape.js.map +1 -1
  139. package/dist/prod/server/form-controls.js.map +1 -1
  140. package/dist/prod/server/hydration-script.js.map +1 -1
  141. package/dist/prod/server/node.js.map +1 -1
  142. package/dist/prod/server/portals.js.map +1 -1
  143. package/dist/prod/server/raw-text.js.map +1 -1
  144. package/dist/prod/server/render.js.map +1 -1
  145. package/dist/prod/server/serialize.js.map +1 -1
  146. package/dist/prod/server/stream.js.map +1 -1
  147. package/dist/prod/spread.js.map +1 -1
  148. package/dist/prod/template.js.map +1 -1
  149. package/dist/prod/view-transition.js.map +1 -1
  150. package/dist/server/attributes.js.map +1 -1
  151. package/dist/server/autofocus.js.map +1 -1
  152. package/dist/server/class-style.js.map +1 -1
  153. package/dist/server/component.js.map +1 -1
  154. package/dist/server/control-flow/activity.js.map +1 -1
  155. package/dist/server/control-flow/branch.js.map +1 -1
  156. package/dist/server/control-flow/client-only.js.map +1 -1
  157. package/dist/server/control-flow/dynamic.js.map +1 -1
  158. package/dist/server/control-flow/error-boundary.js.map +1 -1
  159. package/dist/server/control-flow/for.js.map +1 -1
  160. package/dist/server/control-flow/fragment.js.map +1 -1
  161. package/dist/server/control-flow/index-list.js.map +1 -1
  162. package/dist/server/control-flow/lazy.js.map +1 -1
  163. package/dist/server/control-flow/no-hydration.js.map +1 -1
  164. package/dist/server/control-flow/portal.js.map +1 -1
  165. package/dist/server/control-flow/root-errors.js.map +1 -1
  166. package/dist/server/control-flow/show.js.map +1 -1
  167. package/dist/server/control-flow/suspense-list.js.map +1 -1
  168. package/dist/server/control-flow/suspense.js.map +1 -1
  169. package/dist/server/control-flow/switch.js.map +1 -1
  170. package/dist/server/derived.js.map +1 -1
  171. package/dist/server/element.js.map +1 -1
  172. package/dist/server/events.js.map +1 -1
  173. package/dist/server/head/components.js.map +1 -1
  174. package/dist/server/head/registry.js.map +1 -1
  175. package/dist/server/head/server-head.js.map +1 -1
  176. package/dist/server/head/sink.js.map +1 -1
  177. package/dist/server/head/use-head.js.map +1 -1
  178. package/dist/server/head/validate.js.map +1 -1
  179. package/dist/server/hydration.js.map +1 -1
  180. package/dist/server/insert.js.map +1 -1
  181. package/dist/server/internal/accessor.js.map +1 -1
  182. package/dist/server/internal/claim.js.map +1 -1
  183. package/dist/server/internal/css-units.js.map +1 -1
  184. package/dist/server/internal/diagnostics.js.map +1 -1
  185. package/dist/server/internal/early-events.js.map +1 -1
  186. package/dist/server/internal/hydration-hooks.js.map +1 -1
  187. package/dist/server/internal/hydration-scope.js.map +1 -1
  188. package/dist/server/internal/portal-context.js.map +1 -1
  189. package/dist/server/internal/react-names.js.map +1 -1
  190. package/dist/server/internal/reconcile.js.map +1 -1
  191. package/dist/server/internal/stream-context.js.map +1 -1
  192. package/dist/server/reactive.js.map +1 -1
  193. package/dist/server/render.js.map +1 -1
  194. package/dist/server/resource-hints.js.map +1 -1
  195. package/dist/server/select-value.js.map +1 -1
  196. package/dist/server/server/attributes.js.map +1 -1
  197. package/dist/server/server/class-style.js.map +1 -1
  198. package/dist/server/server/component.js.map +1 -1
  199. package/dist/server/server/derived.js.map +1 -1
  200. package/dist/server/server/element.js.map +1 -1
  201. package/dist/server/server/errors.js.map +1 -1
  202. package/dist/server/server/escape.js.map +1 -1
  203. package/dist/server/server/form-controls.js.map +1 -1
  204. package/dist/server/server/hydration-script.js.map +1 -1
  205. package/dist/server/server/node.js.map +1 -1
  206. package/dist/server/server/portals.js.map +1 -1
  207. package/dist/server/server/raw-text.js.map +1 -1
  208. package/dist/server/server/render.js.map +1 -1
  209. package/dist/server/server/serialize.js.map +1 -1
  210. package/dist/server/server/stream.js.map +1 -1
  211. package/dist/server/spread.js.map +1 -1
  212. package/dist/server/template.js.map +1 -1
  213. package/dist/server/view-transition.js.map +1 -1
  214. package/dist/server-dev/control-flow/portal.js.map +1 -1
  215. package/dist/server-dev/insert.js.map +1 -1
  216. package/dist/server-dev/internal/reconcile.js.map +1 -1
  217. package/dist/server-dev/server/errors.js.map +1 -1
  218. package/dist/server-dev/server/index.js +2 -2
  219. package/dist/server-dev/server/node.js.map +1 -1
  220. package/dist/server-dev/server/portals.js.map +1 -1
  221. package/dist/server-dev/server/stream.js.map +1 -1
  222. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":["SsrError","code","invalid","MAX_TIMER_MS"],"sources":["../../../src/server/errors.ts"],"sourcesContent":["/** Diagnostic codes raised by the server renderer. @internal */\nexport type SsrErrorCode = \"SSR_BOUNDARY_WATERFALL\" | \"SSR_PORTAL_LIMIT\" | \"SSR_TIMEOUT\";\n\n/**\n * Error thrown by the server renderer, carrying a stable code. Dev builds carry the full text;\n * production builds keep only the code (the same split as core's diagnostics).\n * @internal\n */\nexport class SsrError extends Error {\n readonly code: SsrErrorCode;\n constructor(code: SsrErrorCode, detail: string) {\n super(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n this.name = \"SsrError\";\n this.code = code;\n }\n}\n\n/**\n * A TypeError for input the renderer refuses: a value that could become unsafe markup, or a\n * malformed argument. Dev builds carry the detail; production builds keep the code.\n * @internal\n */\nexport function invalid(code: string, detail: string): TypeError {\n return new TypeError(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n}\n\n/**\n * The longest delay `setTimeout` honors: larger values fire after one millisecond. A budget above it\n * (`Number.MAX_SAFE_INTEGER` for \"no limit\") is clamped here instead of ending every render at once.\n * @internal\n */\nexport const MAX_TIMER_MS = 2_147_483_647;\n"],"mappings":"AAQA,IAAaA,EAAb,cAA8B,KAAM,CAClC,KACA,YAAY,EAAoB,EAAgB,CAC9C,MAA+C,UAAUC,GAAM,EAC/D,KAAK,KAAO,WACZ,KAAK,KAAOA,CACd,CACF,EAOA,SAAgBC,EAAQ,EAAc,EAA2B,CAC/D,MAAO,gBAAI,UAAmD,UAAUD,GAAM,CAChF,CAOA,MAAaE,EAAe,W"}
1
+ {"version":3,"file":"errors.js","names":["SsrError","code","detail","invalid","MAX_TIMER_MS"],"sources":["../../../src/server/errors.ts"],"sourcesContent":["/** Diagnostic codes raised by the server renderer. @internal */\nexport type SsrErrorCode = \"SSR_BOUNDARY_WATERFALL\" | \"SSR_PORTAL_LIMIT\" | \"SSR_TIMEOUT\";\n\n/**\n * Error thrown by the server renderer, carrying a stable code. Dev builds carry the full text;\n * production builds keep only the code (the same split as core's diagnostics).\n * @internal\n */\nexport class SsrError extends Error {\n readonly code: SsrErrorCode;\n constructor(code: SsrErrorCode, detail: string) {\n super(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n this.name = \"SsrError\";\n this.code = code;\n }\n}\n\n/**\n * A TypeError for input the renderer refuses: a value that could become unsafe markup, or a\n * malformed argument. Dev builds carry the detail; production builds keep the code.\n * @internal\n */\nexport function invalid(code: string, detail: string): TypeError {\n return new TypeError(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n}\n\n/**\n * The longest delay `setTimeout` honors: larger values fire after one millisecond. A budget above it\n * (`Number.MAX_SAFE_INTEGER` for \"no limit\") is clamped here instead of ending every render at once.\n * @internal\n */\nexport const MAX_TIMER_MS = 2_147_483_647;\n"],"mappings":"AAQA,IAAaA,EAAb,cAA8B,KAAM,CACzB,KACT,YAAYC,EAAoBC,EAAgB,CAC9C,MAA+C,UAAUD,GAAM,EAC/D,KAAK,KAAO,WACZ,KAAK,KAAOA,CACd,CACF,EAOA,SAAgBE,EAAQF,EAAcC,EAA2B,CAC/D,MAAO,gBAAI,UAAmD,UAAUD,GAAM,CAChF,CAOA,MAAaG,EAAe,W"}
@@ -1 +1 @@
1
- {"version":3,"file":"escape.js","names":["accessor","HTML_ESCAPES","HTML_SPECIAL","escapeHtml","text","char","resolveValue","current","value","layer","untrack","appendLeaf","out","invalid","isSsrNode","escape","render","frames","cursors","open","item","resolved","next","found","top","frame","cursor"],"sources":["../../../src/server/escape.ts"],"sourcesContent":["import { untrack } from \"@shadow-js/core\";\nimport { invalid } from \"./errors\";\nimport { isSsrNode } from \"./node\";\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\n\nconst HTML_SPECIAL = /[&<>\"']/g;\n\n/** Longest chain of accessors that returns accessors; longer chains are a bug in user code. */\nconst MAX_ACCESSOR_LAYERS = 1000;\n\n/**\n * Escapes the five HTML-significant characters. Escaping `&` too means entity-looking text is\n * written literally, and the result is safe in text and in quoted attribute values alike.\n * @internal\n */\nexport function escapeHtml(text: string): string {\n return text.replace(HTML_SPECIAL, (char) => HTML_ESCAPES[char] ?? char);\n}\n\n/**\n * Calls accessors until a plain value remains. Accessors run untracked; a chain longer than\n * {@link MAX_ACCESSOR_LAYERS} throws instead of looping.\n * @internal\n */\nexport function resolveValue(value: unknown): unknown {\n let current = value;\n for (let layer = 0; typeof current === \"function\"; layer += 1) {\n if (layer >= MAX_ACCESSOR_LAYERS) {\n throw new TypeError(\"An accessor returns accessors more than 1000 levels deep.\");\n }\n const accessor = current as () => unknown;\n current = untrack(accessor);\n }\n return current;\n}\n\n/** Writes the markup for one resolved value that is not an array; `text` encodes the text of a string. */\nfunction appendLeaf(value: unknown, out: string[], text: (value: string) => string): void {\n if (value === null || value === undefined || typeof value === \"boolean\") return;\n if (typeof value === \"string\") {\n out.push(text(value));\n return;\n }\n // Numbers and bigints never contain markup characters.\n if (typeof value === \"number\" || typeof value === \"bigint\") {\n out.push(String(value));\n return;\n }\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be rendered.\");\n }\n if (isSsrNode(value)) {\n out.push(value.t);\n return;\n }\n // Any other object is not trusted markup. Dev fails loudly; production renders nothing.\n if (typeof value === \"object\") {\n if (__DEV__) {\n throw invalid(\n \"UNRECOGNIZED_INSERT_VALUE\",\n \"A plain object cannot be rendered. Use a string, a number, an array or an SsrNode.\",\n );\n }\n return;\n }\n out.push(text(String(value)));\n}\n\n/**\n * Converts any value a JSX child may hold to escaped HTML: the helper compiled server output calls\n * for every dynamic child, and what the renderers call on the app's result.\n *\n * - Strings are escaped (`& < > \" '`); numbers and bigints are written as they are; `null`,\n * `undefined` and booleans render nothing.\n * - `SsrNode` values (from `ssr`, `ssrRaw` and the other helpers) pass through unchanged: they were\n * escaped when they were built.\n * - Accessors are called (untracked) and their result is rendered; a chain of more than 1000\n * accessors returning accessors throws.\n * - Arrays are flattened in order, with an explicit stack, so nesting depth is not limited by the\n * call stack.\n * - Plain objects throw in development builds and render nothing in production builds.\n *\n * @param value The value to render.\n * @returns The escaped markup.\n * @throws TypeError when an array contains itself, for a symbol (`UNRECOGNIZED_INSERT_VALUE`), for an\n * object that is not an `SsrNode` (`UNRECOGNIZED_INSERT_VALUE`, development builds only), and for an\n * accessor chain deeper than 1000.\n * @example\n * import { escape } from \"@shadow-js/web/server\";\n *\n * const name = () => \"<Ada>\";\n * escape([\"Hello, \", name, null, 3]); // \"Hello, &lt;Ada&gt;3\"\n * @since 1.0.0\n */\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nexport function escape(value: unknown): string {\n return render(value, escapeHtml);\n}\n\n/**\n * {@link escape} with the encoding of strings left to the caller: the walk over accessors, arrays and\n * trusted nodes that every kind of text shares (an element's text is encoded one way, a script's another).\n * @internal\n */\nexport function render(value: unknown, text: (value: string) => string): string {\n const out: string[] = [];\n const frames: unknown[][] = [];\n const cursors: number[] = [];\n const open = new Set<unknown[]>();\n let item: unknown = value;\n for (;;) {\n const resolved = resolveValue(item);\n if (Array.isArray(resolved)) {\n if (open.has(resolved)) throw new TypeError(\"escape(): an array contains itself.\");\n open.add(resolved);\n frames.push(resolved);\n cursors.push(0);\n } else {\n appendLeaf(resolved, out, text);\n }\n // Find the next item, closing every array that has no items left.\n let next: unknown;\n let found = false;\n while (!found && frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined) break;\n if (cursor < frame.length) {\n cursors[top] = cursor + 1;\n next = frame[cursor];\n found = true;\n } else {\n frames.pop();\n cursors.pop();\n open.delete(frame);\n }\n }\n if (!found) return out.join(\"\");\n item = next;\n }\n}\n"],"mappings":"A,sHAIA,MAAMC,EAAiD,CACrD,IAAK,QACL,IAAK,OACL,IAAK,OACL,IAAK,SACL,IAAK,OACP,EAEMC,EAAe,WAUrB,SAAgBC,EAAW,EAAsB,CAC/C,OAAOC,EAAK,QAAQF,EAAe,GAASD,EAAaI,IAASA,CAAI,CACxE,CAOA,SAAgBC,EAAa,EAAyB,CACpD,IAAIC,EAAUC,EACd,IAAK,IAAIC,EAAQ,EAAG,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MACrBC,EAASD,EAAM,QACjB,EAAQD,GAAOE,EAAS,EACxB,EAAOD,EAAMC,GACb,EAAQ,KAERT,EAAO,IAAI,EACXC,EAAQ,IAAI,EACZC,EAAK,OAAOM,CAAK,EAErB,CACA,GAAI,CAACF,EAAO,OAAOX,EAAI,KAAK,EAAE,EAC9B,EAAOU,CACT,CACF,C"}
1
+ {"version":3,"file":"escape.js","names":["accessor","invalid","isSsrNode","untrack","HTML_ESCAPES","HTML_SPECIAL","escapeHtml","text","char","resolveValue","value","current","layer","appendLeaf","out","escape","render","frames","cursors","open","item","resolved","next","found","top","frame","cursor"],"sources":["../../../src/server/escape.ts"],"sourcesContent":["import { untrack } from \"@shadow-js/core\";\nimport { invalid } from \"./errors\";\nimport { isSsrNode } from \"./node\";\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\n\nconst HTML_SPECIAL = /[&<>\"']/g;\n\n/** Longest chain of accessors that returns accessors; longer chains are a bug in user code. */\nconst MAX_ACCESSOR_LAYERS = 1000;\n\n/**\n * Escapes the five HTML-significant characters. Escaping `&` too means entity-looking text is\n * written literally, and the result is safe in text and in quoted attribute values alike.\n * @internal\n */\nexport function escapeHtml(text: string): string {\n return text.replace(HTML_SPECIAL, (char) => HTML_ESCAPES[char] ?? char);\n}\n\n/**\n * Calls accessors until a plain value remains. Accessors run untracked; a chain longer than\n * {@link MAX_ACCESSOR_LAYERS} throws instead of looping.\n * @internal\n */\nexport function resolveValue(value: unknown): unknown {\n let current = value;\n for (let layer = 0; typeof current === \"function\"; layer += 1) {\n if (layer >= MAX_ACCESSOR_LAYERS) {\n throw new TypeError(\"An accessor returns accessors more than 1000 levels deep.\");\n }\n const accessor = current as () => unknown;\n current = untrack(accessor);\n }\n return current;\n}\n\n/** Writes the markup for one resolved value that is not an array; `text` encodes the text of a string. */\nfunction appendLeaf(value: unknown, out: string[], text: (value: string) => string): void {\n if (value === null || value === undefined || typeof value === \"boolean\") return;\n if (typeof value === \"string\") {\n out.push(text(value));\n return;\n }\n // Numbers and bigints never contain markup characters.\n if (typeof value === \"number\" || typeof value === \"bigint\") {\n out.push(String(value));\n return;\n }\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be rendered.\");\n }\n if (isSsrNode(value)) {\n out.push(value.t);\n return;\n }\n // Any other object is not trusted markup. Dev fails loudly; production renders nothing.\n if (typeof value === \"object\") {\n if (__DEV__) {\n throw invalid(\n \"UNRECOGNIZED_INSERT_VALUE\",\n \"A plain object cannot be rendered. Use a string, a number, an array or an SsrNode.\",\n );\n }\n return;\n }\n out.push(text(String(value)));\n}\n\n/**\n * Converts any value a JSX child may hold to escaped HTML: the helper compiled server output calls\n * for every dynamic child, and what the renderers call on the app's result.\n *\n * - Strings are escaped (`& < > \" '`); numbers and bigints are written as they are; `null`,\n * `undefined` and booleans render nothing.\n * - `SsrNode` values (from `ssr`, `ssrRaw` and the other helpers) pass through unchanged: they were\n * escaped when they were built.\n * - Accessors are called (untracked) and their result is rendered; a chain of more than 1000\n * accessors returning accessors throws.\n * - Arrays are flattened in order, with an explicit stack, so nesting depth is not limited by the\n * call stack.\n * - Plain objects throw in development builds and render nothing in production builds.\n *\n * @param value The value to render.\n * @returns The escaped markup.\n * @throws TypeError when an array contains itself, for a symbol (`UNRECOGNIZED_INSERT_VALUE`), for an\n * object that is not an `SsrNode` (`UNRECOGNIZED_INSERT_VALUE`, development builds only), and for an\n * accessor chain deeper than 1000.\n * @example\n * import { escape } from \"@shadow-js/web/server\";\n *\n * const name = () => \"<Ada>\";\n * escape([\"Hello, \", name, null, 3]); // \"Hello, &lt;Ada&gt;3\"\n * @since 1.0.0\n */\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nexport function escape(value: unknown): string {\n return render(value, escapeHtml);\n}\n\n/**\n * {@link escape} with the encoding of strings left to the caller: the walk over accessors, arrays and\n * trusted nodes that every kind of text shares (an element's text is encoded one way, a script's another).\n * @internal\n */\nexport function render(value: unknown, text: (value: string) => string): string {\n const out: string[] = [];\n const frames: unknown[][] = [];\n const cursors: number[] = [];\n const open = new Set<unknown[]>();\n let item: unknown = value;\n for (;;) {\n const resolved = resolveValue(item);\n if (Array.isArray(resolved)) {\n if (open.has(resolved)) throw new TypeError(\"escape(): an array contains itself.\");\n open.add(resolved);\n frames.push(resolved);\n cursors.push(0);\n } else {\n appendLeaf(resolved, out, text);\n }\n // Find the next item, closing every array that has no items left.\n let next: unknown;\n let found = false;\n while (!found && frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined) break;\n if (cursor < frame.length) {\n cursors[top] = cursor + 1;\n next = frame[cursor];\n found = true;\n } else {\n frames.pop();\n cursors.pop();\n open.delete(frame);\n }\n }\n if (!found) return out.join(\"\");\n item = next;\n }\n}\n"],"mappings":"A,sHAIA,MAAMI,EAAiD,CACrD,IAAK,QACL,IAAK,OACL,IAAK,OACL,IAAK,SACL,IAAK,OACP,EAEMC,EAAe,WAUrB,SAAgBC,EAAWC,EAAsB,CAC/C,OAAOA,EAAK,QAAQF,EAAeG,GAASJ,EAAaI,IAASA,CAAI,CACxE,CAOA,SAAgBC,EAAaC,EAAyB,CACpD,IAAIC,EAAUD,EACd,IAAK,IAAIE,EAAQ,EAAG,OAAOD,GAAY,WAAYC,GAAS,EAAG,CAC7D,GAAIA,GAAS,IACX,MAAU,UAAU,2DAA2D,EAGjFD,EAAUR,EAAQH,CAAQ,CAC5B,CACA,OAAOW,CACT,CAGA,SAASE,EAAWH,EAAgBI,EAAeP,EAAuC,CACxF,GAAIG,GAAU,MAA+B,OAAOA,GAAU,UAC9D,IAAI,OAAOA,GAAU,SACnBI,EAAI,KAAKP,EAAKG,CAAK,CAAC,OAItB,GAAI,OAAOA,GAAU,UAAY,OAA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eHtml","resolveValue","first","html","ssrTextArea","SsrNode","wantedValues","resolved","values","item","one","WHITESPACE","ENTITY","NAMED_ENTITIES","TAGS","decodeEntities","text","named","whole","code","decimal","hex","tagEnd","quote","index","from","char","optionText","boundary","boundaries","markOptions","out","copied","at","found","attribute","start","attributesFrom","end","source","selectedAt","selectedEnd","match","name","matches","wanted","slash","ssrSelectValue","markSelectedOptions","escape","children"],"sources":["../../../src/server/form-controls.ts"],"sourcesContent":["import { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { SsrNode } from \"./node\";\n\n/**\n * Server markup for the controls whose state is not an attribute. A browser ignores `value` on a\n * `<textarea>` and on a `<select>`: the textarea's text is its content, and the select's value is\n * the `selected` flag of its options. These helpers write that markup, so the server HTML shows the\n * same state the client sets and a form posted without JavaScript sends it.\n */\n\n/** Text of a value for a textarea: null and undefined are empty, everything else is its string. */\nfunction valueText(value: unknown): string {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be a form control value.\");\n }\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Markup of a textarea's content. The HTML parser drops one newline directly after `<textarea>`,\n * so a value that starts with a line break gets one more; its content is then exactly the value.\n * @internal\n */\nexport function textareaContent(value: unknown): string {\n return keepLeadingNewline(escapeHtml(valueText(resolveValue(value))));\n}\n\n/** Content markup of a textarea with the line break its parser would drop kept. @internal */\nexport function keepLeadingNewline(html: string): string {\n const first = html.charAt(0);\n return first === \"\\n\" || first === \"\\r\" ? `\\n${html}` : html;\n}\n\n/**\n * Renders the content of a `<textarea>` from its value: the helper compiled server output calls for\n * `<textarea value={...}>` and `defaultValue`, since a browser ignores a `value` attribute on a\n * textarea. The text is escaped, and a value that starts with a line break gets one more, because\n * the HTML parser drops the first one.\n *\n * @param value The value, or an accessor of it. `null` and `undefined` give an empty textarea;\n * anything else is written as `String(value)`.\n * @returns The escaped content as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol.\n * @example\n * import { renderToString, ssr, ssrTextArea } from \"@shadow-js/web/server\";\n *\n * const bio = \"Loves <b>tags</b>\";\n * const html = renderToString(() => ssr([\"<textarea>\", \"</textarea>\"], ssrTextArea(bio)));\n * // \"<textarea>Loves &lt;b&gt;tags&lt;/b&gt;</textarea>\"\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function ssrTextArea(value: unknown): SsrNode {\n return new SsrNode(textareaContent(value));\n}\n\n/** The values a select value stands for: an array lists them (`multiple`), anything else is one. */\nfunction wantedValues(value: unknown): { values: Set<string>; many: boolean } {\n const resolved = resolveValue(value);\n if (!Array.isArray(resolved)) return { values: new Set([valueText(resolved)]), many: false };\n const values = new Set<string>();\n for (const item of resolved) {\n const one = resolveValue(item);\n if (one !== null && one !== undefined) values.add(valueText(one));\n }\n return { values, many: true };\n}\n\n/** Characters of the HTML spec's \"ASCII whitespace\". */\nconst WHITESPACE = /[ \\t\\n\\f\\r]+/g;\n/** Entities our own escaping writes, plus numeric references and `&nbsp;` from trusted raw markup. */\nconst ENTITY = /&(?:#(\\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi;\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\n/** Comments and tags inside an option's text (the region markers the compiler writes). */\nconst TAGS = /<!--[\\s\\S]*?-->|<[^>]*>/g;\n/**\n * The next option or optgroup tag, start or end: where an option's text ends. Sources of global\n * expressions, built per call so no `lastIndex` outlives it.\n */\nconst OPTION_BOUNDARY = \"<\\\\/?(?:option|optgroup)(?=[\\\\s/>])\";\n/** One attribute of a start tag: name, then an optional quoted or bare value. */\nconst ATTRIBUTE = \"\\\\s+([^\\\\s\\\"'<>/=]+)(?:\\\\s*=\\\\s*(?:\\\"([^\\\"]*)\\\"|'([^']*)'|([^\\\\s\\\"'=<>`]+)))?\";\n\nfunction decodeEntities(text: string): string {\n return text.replace(ENTITY, (whole, decimal?: string, hex?: string, named?: string) => {\n if (named !== undefined) return NAMED_ENTITIES[named.toLowerCase()] ?? whole;\n const code = decimal !== undefined ? Number(decimal) : Number.parseInt(hex ?? \"\", 16);\n return Number.isInteger(code) &&\n code >= 0 &&\n code <= 0x10ffff &&\n !(code >= 0xd800 && code <= 0xdfff)\n ? String.fromCodePoint(code)\n : whole;\n });\n}\n\n/** Index of the `>` that ends the start tag whose attributes begin at `from`, or -1. Quotes are skipped. */\nfunction tagEnd(html: string, from: number): number {\n let quote = \"\";\n for (let index = from; index < html.length; index += 1) {\n const char = html.charAt(index);\n if (quote !== \"\") {\n if (char === quote) quote = \"\";\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \">\") {\n return index;\n }\n }\n return -1;\n}\n\n/** The text an option without a `value` attribute stands for: its text content, whitespace collapsed. */\nfunction optionText(html: string, from: number, boundaries: RegExp): string {\n boundaries.lastIndex = from;\n const boundary = boundaries.exec(html);\n const raw = html.slice(from, boundary === null ? html.length : boundary.index);\n return decodeEntities(raw.replace(TAGS, \"\")).replace(WHITESPACE, \" \").trim();\n}\n\n/**\n * Rewrites the option start tags of `html` so that exactly the wanted ones carry `selected`. The\n * input is markup this runtime produced (text and attribute values are escaped, so `<option` is\n * always a tag); only the `selected` attribute is added or removed, and nothing from the wanted\n * values is ever written.\n */\nfunction markOptions(html: string, wanted: { values: Set<string>; many: boolean }): string {\n let out = \"\";\n let copied = 0;\n let at = 0;\n let found = false;\n const attribute = new RegExp(ATTRIBUTE, \"g\");\n const boundaries = new RegExp(OPTION_BOUNDARY, \"gi\");\n for (;;) {\n const start = html.indexOf(\"<option\", at);\n if (start === -1) break;\n const attributesFrom = start + 7;\n at = attributesFrom;\n if (!/[\\s/>]/.test(html.charAt(attributesFrom))) continue;\n const end = tagEnd(html, attributesFrom);\n if (end === -1) break;\n const source = html.slice(attributesFrom, end);\n let value: string | undefined;\n let selectedAt = -1;\n let selectedEnd = -1;\n attribute.lastIndex = 0;\n for (let match = attribute.exec(source); match !== null; match = attribute.exec(source)) {\n const name = (match[1] ?? \"\").toLowerCase();\n if (name === \"selected\") {\n selectedAt = match.index;\n selectedEnd = match.index + match[0].length;\n } else if (name === \"value\" && value === undefined) {\n value = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n }\n // A scalar behaves like `select.value = x`: the first option with that value wins.\n const matches =\n (wanted.many || !found) && wanted.values.has(value ?? optionText(html, end + 1, boundaries));\n if (matches) found = true;\n if (matches && selectedAt === -1) {\n const slash = source.endsWith(\"/\") ? source.length - 1 : source.length;\n out += `${html.slice(copied, attributesFrom + slash)} selected`;\n copied = attributesFrom + slash;\n } else if (!matches && selectedAt !== -1) {\n out += html.slice(copied, attributesFrom + selectedAt);\n copied = attributesFrom + selectedEnd;\n }\n at = end;\n }\n return copied === 0 ? html : out + html.slice(copied);\n}\n\n/**\n * The options of a `<select>` with the ones its value stands for marked `selected`. A browser\n * ignores a `value` attribute on `<select>`, so the server flags the options instead: the option\n * whose `value` attribute equals the value (or, with no such attribute, whose text does) is\n * selected, and every other option loses `selected`. An array selects every listed option, for\n * `<select multiple>`; a single value selects the first match, like `select.value = x`. `null`\n * and `undefined` stand for the empty string. Options inside `<optgroup>`, control flow and\n * components are found because the search runs on the serialized children. Values are compared,\n * never written, so they cannot add markup.\n *\n * @param value The select's `value`, or an accessor of it. Entries of an array are compared as\n * strings; `null` and `undefined` entries are skipped.\n * @param children The select's children (an `SsrNode`, or anything `escape` accepts).\n * @returns The children with the `selected` flags set, as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol, and the errors of\n * {@link escape} for the children.\n * @example\n * import { renderToString, ssr, ssrRaw, ssrSelectValue } from \"@shadow-js/web/server\";\n *\n * const options = ssrRaw(`<option value=\"red\">Red</option><option value=\"blue\">Blue</option>`);\n * const html = renderToString(() => ssr([\"<select>\", \"</select>\"], ssrSelectValue(\"blue\", options)));\n * // '<select><option value=\"red\">Red</option><option value=\"blue\" selected>Blue</option></select>'\n * @see setSelectValue\n * @since 1.0.0\n */\nexport function ssrSelectValue(value: unknown, children: unknown): SsrNode {\n return new SsrNode(markSelectedOptions(value, escape(children)));\n}\n\n/** {@link ssrSelectValue} on markup that is already escaped. @internal */\nexport function markSelectedOptions(value: unknown, html: string): string {\n return markOptions(html, wantedValues(value));\n}\n"],"mappings":"A,iJAaA,SAASA,EAAU,EAAwB,CACzC,GAAI,OAAOC,GAAU,SACnB,MAAMC,EAAQ,4BAA6B,0CAA0C,EAEvF,OAAOD,GAAU,KAA8B,GAAK,OAAOA,CAAK,CAClE,CAOA,SAAgBE,EAAgB,EAAwB,CACtD,OAAOC,EAAmBC,EAAWL,EAAUM,EAAaL,CAAK,CAAC,CAAC,CAAC,CACtE,CAGA,SAAgBG,EAAmB,EAAsB,CACvD,IAAMG,EAAQC,EAAK,OAAO,CAAC,EAC3B,OAAOD,IAAU;GAAQA,IAAU,KAAO,KAAKC,IAASA,CAC1D,CAqBA,SAAgBC,EAAY,EAAyB,CACnD,OAAO,IAAIC,EAAQP,EAAgBF,CAAK,CAAC,CAC3C,CAGA,SAASU,EAAa,EAAwD,CAC5E,IAAMC,EAAWN,EAAaL,CAAK,EACnC,GAAI,CAAC,MAAM,QAAQW,CAAQ,EAAG,MAAO,CAAE,uBAAQ,IAAI,IAAI,CAACZ,EAAUY,CAAQ,CAAC,CAAC,EAAG,KAAM,EAAM,EAC3F,IAAMC,kBAAS,IAAI,IACnB,IAAK,IAAMC,KAAQF,EAAU,CAC3B,IAAMG,EAAMT,EAAaQ,CAAI,EACzBC,GAAQ,MAA2BF,EAAO,IAAIb,EAAUe,CAAG,CAAC,CAClE,CACA,MAAO,CAAE,SAAQ,KAAM,EAAK,CAC9B,CAGA,MAAMC,EAAa,gBAEbC,EAAS,0D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Ae,EAAgB,EAA4B,CACzE,OAAO,IAAI1C,EAAQ2C,EAAoBpD,EAAOqD,EAAOC,CAAQ,CAAC,CAAC,CACjE,CAGA,SAAgBF,EAAoB,EAAgB,EAAsB,CACxE,OAAOlB,EAAY3B,EAAMG,EAAaV,CAAK,CAAC,CAC9C,C"}
1
+ {"version":3,"file":"form-controls.js","names":["invalid","escape","escapeHtml","resolveValue","SsrNode","valueText","value","textareaContent","keepLeadingNewline","html","first","ssrTextArea","wantedValues","resolved","values","item","one","WHITESPACE","ENTITY","NAMED_ENTITIES","TAGS","decodeEntities","text","whole","decimal","hex","named","code","tagEnd","from","quote","index","char","optionText","boundaries","boundary","markOptions","wanted","out","copied","at","found","attribute","start","attributesFrom","end","source","selectedAt","selectedEnd","match","name","matches","slash","ssrSelectValue","children","markSelectedOptions"],"sources":["../../../src/server/form-controls.ts"],"sourcesContent":["import { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { SsrNode } from \"./node\";\n\n/**\n * Server markup for the controls whose state is not an attribute. A browser ignores `value` on a\n * `<textarea>` and on a `<select>`: the textarea's text is its content, and the select's value is\n * the `selected` flag of its options. These helpers write that markup, so the server HTML shows the\n * same state the client sets and a form posted without JavaScript sends it.\n */\n\n/** Text of a value for a textarea: null and undefined are empty, everything else is its string. */\nfunction valueText(value: unknown): string {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be a form control value.\");\n }\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Markup of a textarea's content. The HTML parser drops one newline directly after `<textarea>`,\n * so a value that starts with a line break gets one more; its content is then exactly the value.\n * @internal\n */\nexport function textareaContent(value: unknown): string {\n return keepLeadingNewline(escapeHtml(valueText(resolveValue(value))));\n}\n\n/** Content markup of a textarea with the line break its parser would drop kept. @internal */\nexport function keepLeadingNewline(html: string): string {\n const first = html.charAt(0);\n return first === \"\\n\" || first === \"\\r\" ? `\\n${html}` : html;\n}\n\n/**\n * Renders the content of a `<textarea>` from its value: the helper compiled server output calls for\n * `<textarea value={...}>` and `defaultValue`, since a browser ignores a `value` attribute on a\n * textarea. The text is escaped, and a value that starts with a line break gets one more, because\n * the HTML parser drops the first one.\n *\n * @param value The value, or an accessor of it. `null` and `undefined` give an empty textarea;\n * anything else is written as `String(value)`.\n * @returns The escaped content as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol.\n * @example\n * import { renderToString, ssr, ssrTextArea } from \"@shadow-js/web/server\";\n *\n * const bio = \"Loves <b>tags</b>\";\n * const html = renderToString(() => ssr([\"<textarea>\", \"</textarea>\"], ssrTextArea(bio)));\n * // \"<textarea>Loves &lt;b&gt;tags&lt;/b&gt;</textarea>\"\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function ssrTextArea(value: unknown): SsrNode {\n return new SsrNode(textareaContent(value));\n}\n\n/** The values a select value stands for: an array lists them (`multiple`), anything else is one. */\nfunction wantedValues(value: unknown): { values: Set<string>; many: boolean } {\n const resolved = resolveValue(value);\n if (!Array.isArray(resolved)) return { values: new Set([valueText(resolved)]), many: false };\n const values = new Set<string>();\n for (const item of resolved) {\n const one = resolveValue(item);\n if (one !== null && one !== undefined) values.add(valueText(one));\n }\n return { values, many: true };\n}\n\n/** Characters of the HTML spec's \"ASCII whitespace\". */\nconst WHITESPACE = /[ \\t\\n\\f\\r]+/g;\n/** Entities our own escaping writes, plus numeric references and `&nbsp;` from trusted raw markup. */\nconst ENTITY = /&(?:#(\\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi;\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\n/** Comments and tags inside an option's text (the region markers the compiler writes). */\nconst TAGS = /<!--[\\s\\S]*?-->|<[^>]*>/g;\n/**\n * The next option or optgroup tag, start or end: where an option's text ends. Sources of global\n * expressions, built per call so no `lastIndex` outlives it.\n */\nconst OPTION_BOUNDARY = \"<\\\\/?(?:option|optgroup)(?=[\\\\s/>])\";\n/** One attribute of a start tag: name, then an optional quoted or bare value. */\nconst ATTRIBUTE = \"\\\\s+([^\\\\s\\\"'<>/=]+)(?:\\\\s*=\\\\s*(?:\\\"([^\\\"]*)\\\"|'([^']*)'|([^\\\\s\\\"'=<>`]+)))?\";\n\nfunction decodeEntities(text: string): string {\n return text.replace(ENTITY, (whole, decimal?: string, hex?: string, named?: string) => {\n if (named !== undefined) return NAMED_ENTITIES[named.toLowerCase()] ?? whole;\n const code = decimal !== undefined ? Number(decimal) : Number.parseInt(hex ?? \"\", 16);\n return Number.isInteger(code) &&\n code >= 0 &&\n code <= 0x10ffff &&\n !(code >= 0xd800 && code <= 0xdfff)\n ? String.fromCodePoint(code)\n : whole;\n });\n}\n\n/** Index of the `>` that ends the start tag whose attributes begin at `from`, or -1. Quotes are skipped. */\nfunction tagEnd(html: string, from: number): number {\n let quote = \"\";\n for (let index = from; index < html.length; index += 1) {\n const char = html.charAt(index);\n if (quote !== \"\") {\n if (char === quote) quote = \"\";\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \">\") {\n return index;\n }\n }\n return -1;\n}\n\n/** The text an option without a `value` attribute stands for: its text content, whitespace collapsed. */\nfunction optionText(html: string, from: number, boundaries: RegExp): string {\n boundaries.lastIndex = from;\n const boundary = boundaries.exec(html);\n const raw = html.slice(from, boundary === null ? html.length : boundary.index);\n return decodeEntities(raw.replace(TAGS, \"\")).replace(WHITESPACE, \" \").trim();\n}\n\n/**\n * Rewrites the option start tags of `html` so that exactly the wanted ones carry `selected`. The\n * input is markup this runtime produced (text and attribute values are escaped, so `<option` is\n * always a tag); only the `selected` attribute is added or removed, and nothing from the wanted\n * values is ever written.\n */\nfunction markOptions(html: string, wanted: { values: Set<string>; many: boolean }): string {\n let out = \"\";\n let copied = 0;\n let at = 0;\n let found = false;\n const attribute = new RegExp(ATTRIBUTE, \"g\");\n const boundaries = new RegExp(OPTION_BOUNDARY, \"gi\");\n for (;;) {\n const start = html.indexOf(\"<option\", at);\n if (start === -1) break;\n const attributesFrom = start + 7;\n at = attributesFrom;\n if (!/[\\s/>]/.test(html.charAt(attributesFrom))) continue;\n const end = tagEnd(html, attributesFrom);\n if (end === -1) break;\n const source = html.slice(attributesFrom, end);\n let value: string | undefined;\n let selectedAt = -1;\n let selectedEnd = -1;\n attribute.lastIndex = 0;\n for (let match = attribute.exec(source); match !== null; match = attribute.exec(source)) {\n const name = (match[1] ?? \"\").toLowerCase();\n if (name === \"selected\") {\n selectedAt = match.index;\n selectedEnd = match.index + match[0].length;\n } else if (name === \"value\" && value === undefined) {\n value = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n }\n // A scalar behaves like `select.value = x`: the first option with that value wins.\n const matches =\n (wanted.many || !found) && wanted.values.has(value ?? optionText(html, end + 1, boundaries));\n if (matches) found = true;\n if (matches && selectedAt === -1) {\n const slash = source.endsWith(\"/\") ? source.length - 1 : source.length;\n out += `${html.slice(copied, attributesFrom + slash)} selected`;\n copied = attributesFrom + slash;\n } else if (!matches && selectedAt !== -1) {\n out += html.slice(copied, attributesFrom + selectedAt);\n copied = attributesFrom + selectedEnd;\n }\n at = end;\n }\n return copied === 0 ? html : out + html.slice(copied);\n}\n\n/**\n * The options of a `<select>` with the ones its value stands for marked `selected`. A browser\n * ignores a `value` attribute on `<select>`, so the server flags the options instead: the option\n * whose `value` attribute equals the value (or, with no such attribute, whose text does) is\n * selected, and every other option loses `selected`. An array selects every listed option, for\n * `<select multiple>`; a single value selects the first match, like `select.value = x`. `null`\n * and `undefined` stand for the empty string. Options inside `<optgroup>`, control flow and\n * components are found because the search runs on the serialized children. Values are compared,\n * never written, so they cannot add markup.\n *\n * @param value The select's `value`, or an accessor of it. Entries of an array are compared as\n * strings; `null` and `undefined` entries are skipped.\n * @param children The select's children (an `SsrNode`, or anything `escape` accepts).\n * @returns The children with the `selected` flags set, as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol, and the errors of\n * {@link escape} for the children.\n * @example\n * import { renderToString, ssr, ssrRaw, ssrSelectValue } from \"@shadow-js/web/server\";\n *\n * const options = ssrRaw(`<option value=\"red\">Red</option><option value=\"blue\">Blue</option>`);\n * const html = renderToString(() => ssr([\"<select>\", \"</select>\"], ssrSelectValue(\"blue\", options)));\n * // '<select><option value=\"red\">Red</option><option value=\"blue\" selected>Blue</option></select>'\n * @see setSelectValue\n * @since 1.0.0\n */\nexport function ssrSelectValue(value: unknown, children: unknown): SsrNode {\n return new SsrNode(markSelectedOptions(value, escape(children)));\n}\n\n/** {@link ssrSelectValue} on markup that is already escaped. @internal */\nexport function markSelectedOptions(value: unknown, html: string): string {\n return markOptions(html, wantedValues(value));\n}\n"],"mappings":"A,iJAaA,SAASK,EAAUC,EAAwB,CACzC,GAAI,OAAOA,GAAU,SACnB,MAAMN,EAAQ,4BAA6B,0CAA0C,EAEvF,OAAOM,GAAU,KAA8B,GAAK,OAAOA,CAAK,CAClE,CAOA,SAAgBC,EAAgBD,EAAwB,CACtD,OAAOE,EAAmBN,EAAWG,EAAUF,EAAaG,CAAK,CAAC,CAAC,CAAC,CACtE,CAGA,SAAgBE,EAAmBC,EAAsB,CACvD,IAAMC,EAAQD,EAAK,OAAO,CAAC,EAC3B,OAAOC,IAAU;GAAQA,IAAU,KAAO,KAAKD,IAASA,CAC1D,CAqBA,SAAgBE,EAAYL,EAAyB,CACnD,OAAO,IAAIF,EAAQG,EAAgBD,CAAK,CAAC,CAC3C,CAGA,SAASM,EAAaN,EAAwD,CAC5E,IAAMO,EAAWV,EAAaG,CAAK,EACnC,GAAI,CAAC,MAAM,QAAQO,CAAQ,EAAG,MAAO,CAAE,uBAAQ,IAAI,IAAI,CAACR,EAAUQ,CAAQ,CA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AO,OAChER,GAAO,GAAG7B,EAAK,MAAM8B,EAAQK,EAAiBQ,CAAK,EAAE,WACrDb,EAASK,EAAiBQ,CAC5B,KAAW,CAACD,GAAWJ,IAAe,KACpCT,GAAO7B,EAAK,MAAM8B,EAAQK,EAAiBG,CAAU,EACrDR,EAASK,EAAiBI,GAE5BR,EAAKK,CACP,CACA,OAAON,IAAW,EAAI9B,EAAO6B,EAAM7B,EAAK,MAAM8B,CAAM,CACtD,CA2BA,SAAgBc,EAAe/C,EAAgBgD,EAA4B,CACzE,OAAO,IAAIlD,EAAQmD,EAAoBjD,EAAOL,EAAOqD,CAAQ,CAAC,CAAC,CACjE,CAGA,SAAgBC,EAAoBjD,EAAgBG,EAAsB,CACxE,OAAO2B,EAAY3B,EAAMG,EAAaN,CAAK,CAAC,CAC9C,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"hydration-script.js","names":["NONCE","generateHydrationScript","nonce","options","attribute","names","DEFAULT_EARLY_EVENTS","captureScriptBody","HydrationScript","ssrRaw","props"],"sources":["../../../src/server/hydration-script.ts"],"sourcesContent":["import { captureScriptBody, DEFAULT_EARLY_EVENTS } from \"../internal/early-events\";\nimport { ssrRaw } from \"./element\";\n\n/**\n * Options of {@link generateHydrationScript} and {@link HydrationScript}.\n * @since 1.0.0\n */\nexport interface HydrationScriptOptions {\n /**\n * CSP nonce for the script. It is written only when it is a plain token (letters, digits, `+`, `/`,\n * `=`, `_`, `-`); any other value is ignored and the script gets no nonce.\n * @default undefined (no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Event types to capture before hydration. Only plain lower-case names (`[a-z]+`) are kept; others\n * are skipped.\n * @default [\"click\", \"input\"]\n */\n readonly eventNames?: readonly string[];\n}\n\nconst NONCE = /^[A-Za-z0-9+/=_-]+$/;\n\n/**\n * Returns the inline `<script>` that records the events a user makes before the app has hydrated, so\n * `hydrate()` can replay them once its handlers are attached (a click made while the bundle loads is\n * not lost). Put it in the `<head>` of the server-rendered page, before the bundle.\n *\n * @param options The CSP nonce and the event types to capture. Undefined uses the defaults of\n * {@link HydrationScriptOptions}.\n * @returns The script element as a string of markup.\n * @example\n * import { generateHydrationScript, renderToString } from \"@shadow-js/web/server\";\n *\n * function page(app: () => unknown, nonce: string): string {\n * const body = renderToString(app);\n * return `<html><head>${generateHydrationScript({ nonce })}</head><body>${body}</body></html>`;\n * }\n * @see HydrationScript\n * @since 1.0.0\n */\nexport function generateHydrationScript(options: HydrationScriptOptions = {}): string {\n const nonce = options.nonce;\n const attribute = nonce !== undefined && NONCE.test(nonce) ? ` nonce=\"${nonce}\"` : \"\";\n const names = options.eventNames ?? DEFAULT_EARLY_EVENTS;\n return `<script${attribute}>${captureScriptBody(names)}</script>`;\n}\n\n/**\n * {@link generateHydrationScript} as a component, for a document rendered with server JSX:\n * `<HydrationScript nonce={nonce} />` in the `<head>`.\n *\n * @param props The CSP nonce and the event types to capture. Undefined uses the defaults of\n * {@link HydrationScriptOptions}.\n * @returns The script as trusted raw markup.\n * @example\n * import { createComponent, HydrationScript, renderToString } from \"@shadow-js/web/server\";\n *\n * function Document() {\n * return (\n * <html>\n * <head>\n * <HydrationScript nonce=\"r4nd0m\" />\n * </head>\n * <body>Hello</body>\n * </html>\n * );\n * }\n * const html = renderToString(() => createComponent(Document, {}));\n * @see generateHydrationScript\n * @since 1.0.0\n */\nexport function HydrationScript(props: HydrationScriptOptions = {}): unknown {\n return ssrRaw(generateHydrationScript(props));\n}\n"],"mappings":"A,gIAsBA,MAAMA,EAAQ,sBAoBd,SAAgBC,EAAwB,EAAkC,CAAC,EAAW,CACpF,IAAMC,EAAQC,EAAQ,MAChBC,EAAYF,IAAU,IAAA,IAAaF,EAAM,KAAKE,CAAK,EAAI,WAAWA,EAAM,GAAK,GAC7EG,EAAQF,EAAQ,YAAcG,EACpC,MAAO,UAAUF,EAAU,GAAGG,EAAkBF,CAAK,EAAE,WACzD,CA0BA,SAAgBG,EAAgB,EAAgC,CAAC,EAAY,CAC3E,OAAOC,EAAOR,EAAwBS,CAAK,CAAC,CAC9C,C"}
1
+ {"version":3,"file":"hydration-script.js","names":["DEFAULT_EARLY_EVENTS","captureScriptBody","ssrRaw","NONCE","generateHydrationScript","options","nonce","attribute","names","HydrationScript","props"],"sources":["../../../src/server/hydration-script.ts"],"sourcesContent":["import { captureScriptBody, DEFAULT_EARLY_EVENTS } from \"../internal/early-events\";\nimport { ssrRaw } from \"./element\";\n\n/**\n * Options of {@link generateHydrationScript} and {@link HydrationScript}.\n * @since 1.0.0\n */\nexport interface HydrationScriptOptions {\n /**\n * CSP nonce for the script. It is written only when it is a plain token (letters, digits, `+`, `/`,\n * `=`, `_`, `-`); any other value is ignored and the script gets no nonce.\n * @default undefined (no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Event types to capture before hydration. Only plain lower-case names (`[a-z]+`) are kept; others\n * are skipped.\n * @default [\"click\", \"input\"]\n */\n readonly eventNames?: readonly string[];\n}\n\nconst NONCE = /^[A-Za-z0-9+/=_-]+$/;\n\n/**\n * Returns the inline `<script>` that records the events a user makes before the app has hydrated, so\n * `hydrate()` can replay them once its handlers are attached (a click made while the bundle loads is\n * not lost). Put it in the `<head>` of the server-rendered page, before the bundle.\n *\n * @param options The CSP nonce and the event types to capture. Undefined uses the defaults of\n * {@link HydrationScriptOptions}.\n * @returns The script element as a string of markup.\n * @example\n * import { generateHydrationScript, renderToString } from \"@shadow-js/web/server\";\n *\n * function page(app: () => unknown, nonce: string): string {\n * const body = renderToString(app);\n * return `<html><head>${generateHydrationScript({ nonce })}</head><body>${body}</body></html>`;\n * }\n * @see HydrationScript\n * @since 1.0.0\n */\nexport function generateHydrationScript(options: HydrationScriptOptions = {}): string {\n const nonce = options.nonce;\n const attribute = nonce !== undefined && NONCE.test(nonce) ? ` nonce=\"${nonce}\"` : \"\";\n const names = options.eventNames ?? DEFAULT_EARLY_EVENTS;\n return `<script${attribute}>${captureScriptBody(names)}</script>`;\n}\n\n/**\n * {@link generateHydrationScript} as a component, for a document rendered with server JSX:\n * `<HydrationScript nonce={nonce} />` in the `<head>`.\n *\n * @param props The CSP nonce and the event types to capture. Undefined uses the defaults of\n * {@link HydrationScriptOptions}.\n * @returns The script as trusted raw markup.\n * @example\n * import { createComponent, HydrationScript, renderToString } from \"@shadow-js/web/server\";\n *\n * function Document() {\n * return (\n * <html>\n * <head>\n * <HydrationScript nonce=\"r4nd0m\" />\n * </head>\n * <body>Hello</body>\n * </html>\n * );\n * }\n * const html = renderToString(() => createComponent(Document, {}));\n * @see generateHydrationScript\n * @since 1.0.0\n */\nexport function HydrationScript(props: HydrationScriptOptions = {}): unknown {\n return ssrRaw(generateHydrationScript(props));\n}\n"],"mappings":"A,gIAsBA,MAAMG,EAAQ,sBAoBd,SAAgBC,EAAwBC,EAAkC,CAAC,EAAW,CACpF,IAAMC,EAAQD,EAAQ,MAChBE,EAAYD,IAAU,IAAA,IAAaH,EAAM,KAAKG,CAAK,EAAI,WAAWA,EAAM,GAAK,GAC7EE,EAAQH,EAAQ,YAAcL,EACpC,MAAO,UAAUO,EAAU,GAAGN,EAAkBO,CAAK,EAAE,WACzD,CA0BA,SAAgBC,EAAgBC,EAAgC,CAAC,EAAY,CAC3E,OAAOR,EAAOE,EAAwBM,CAAK,CAAC,CAC9C,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","names":["SsrNode","t","isSsrNode","value"],"sources":["../../../src/server/node.ts"],"sourcesContent":["/**\n * Markup that is already safe to insert: the only value `escape` writes without encoding.\n * A class instance, not a `{ t }` shape, so a plain object parsed from user input can never be\n * mistaken for trusted markup.\n * @internal\n */\nexport class SsrNode {\n readonly t: string;\n constructor(t: string) {\n this.t = t;\n }\n}\n\n/** True for values created by the server helpers. @internal */\nexport function isSsrNode(value: unknown): value is SsrNode {\n return value instanceof SsrNode;\n}\n"],"mappings":"AAMA,IAAaA,EAAb,KAAqB,CACnB,EACA,YAAY,EAAW,CACrB,KAAK,EAAIC,CACX,CACF,EAGA,SAAgBC,EAAU,EAAkC,CAC1D,OAAOC,aAAiBH,CAC1B,C"}
1
+ {"version":3,"file":"node.js","names":["SsrNode","t","isSsrNode","value"],"sources":["../../../src/server/node.ts"],"sourcesContent":["/**\n * Markup that is already safe to insert: the only value `escape` writes without encoding.\n * A class instance, not a `{ t }` shape, so a plain object parsed from user input can never be\n * mistaken for trusted markup.\n * @internal\n */\nexport class SsrNode {\n readonly t: string;\n constructor(t: string) {\n this.t = t;\n }\n}\n\n/** True for values created by the server helpers. @internal */\nexport function isSsrNode(value: unknown): value is SsrNode {\n return value instanceof SsrNode;\n}\n"],"mappings":"AAMA,IAAaA,EAAb,KAAqB,CACV,EACT,YAAYC,EAAW,CACrB,KAAK,EAAIA,CACX,CACF,EAGA,SAAgBC,EAAUC,EAAkC,CAC1D,OAAOA,aAAiBH,CAC1B,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"portals.js","names":["PortalCollector","key","SsrError","html","renderServerPortal","children","out","collectors","createServerPortals","collector","portals","collectorOf","sink","withScope","childScope","escape","withPortalSink","PortalContext","build","portalCollectorFor"],"sources":["../../../src/server/portals.ts"],"sourcesContent":["import { childScope, withScope } from \"../internal/hydration-scope\";\nimport { PortalContext, type PortalSink } from \"../internal/portal-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\n\n/**\n * The most portals one render may produce. A page with more open overlays than this is a bug, and the\n * collector refuses to grow without a bound.\n * @internal\n */\nexport const MAX_SERVER_PORTALS = 256;\n\n/**\n * The markup of the portals a server render produced (see {@link createServerPortals}). Pass it to\n * the render as its `portals` option, then emit `html()` at the end of `<body>`, after the app markup.\n * The client adopts each block when it hydrates the portal that wrote it.\n *\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<!doctype html><html><body><div id=\"app\">${app}</div>${portals.html()}</body></html>`;\n * @since 1.0.0\n */\nexport interface ServerPortals {\n /**\n * The collected blocks, in the order the render produced them: each is `<!--portal:KEY-->` markup\n * `<!--/portal:KEY-->`. Emit it once, at the end of `<body>`.\n * @returns The markup; empty when no portal was rendered.\n */\n html(): string;\n}\n\n/** The collector behind a {@link ServerPortals}: what a renderer writes into while it renders. @internal */\nexport class PortalCollector implements PortalSink {\n private readonly entries = new Map<string, string>();\n\n add(key: string, html: string): void {\n if (!this.entries.has(key) && this.entries.size >= MAX_SERVER_PORTALS) {\n throw new SsrError(\n \"SSR_PORTAL_LIMIT\",\n `A render produced more than ${MAX_SERVER_PORTALS} portals; close some overlays or raise the limit.`,\n );\n }\n this.entries.set(key, html);\n }\n\n /** Forgets what an earlier pass of the same render wrote. */\n clear(): void {\n this.entries.clear();\n }\n\n render(key: string | undefined, children: () => unknown): void {\n renderServerPortal(key, children, this);\n }\n\n html(): string {\n let out = \"\";\n for (const [key, html] of this.entries) {\n out += `<!--portal:${key}-->${html}<!--/portal:${key}-->`;\n }\n return out;\n }\n}\n\nconst collectors = new WeakMap<ServerPortals, PortalCollector>();\n\n/**\n * Creates the collector a server render writes its portals into. Without one, a `Portal` renders\n * nothing on the server. Create one per request: a render clears it before it starts, and one render\n * may produce at most 256 portals (more throw an `SsrError` whose `code` is `SSR_PORTAL_LIMIT`).\n *\n * @returns A new, empty {@link ServerPortals}.\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<body><div id=\"app\">${app}</div>${portals.html()}</body>`;\n * @since 1.0.0\n */\nexport function createServerPortals(): ServerPortals {\n const collector = new PortalCollector();\n const portals: ServerPortals = { html: () => collector.html() };\n collectors.set(portals, collector);\n return portals;\n}\n\n/**\n * The collector behind a `portals` option.\n * @throws TypeError when the value did not come from {@link createServerPortals}.\n * @internal\n */\nexport function collectorOf(portals: ServerPortals): PortalCollector {\n const collector = collectors.get(portals);\n if (collector === undefined) {\n throw new TypeError(\"portals must be created with createServerPortals().\");\n }\n return collector;\n}\n\n/**\n * The server half of a `Portal`: renders its content into the render's collector. The content gets its\n * own hydration scope, so the keys of the siblings do not depend on whether the portal rendered. Writes\n * nothing when the render has no collector or the portal has no key (no render scope).\n *\n * @param key The portal's key, from `nextKey()` at the call site.\n * @param children Reads the portal's content. A thunk, because reading a JSX child builds it, and the\n * content must be built inside its own scope.\n * @param sink The collector the portal context provides (null for a render without one).\n * @internal\n */\nexport function renderServerPortal(\n key: string | undefined,\n children: () => unknown,\n sink: PortalSink | null,\n): void {\n if (sink === null || key === undefined) return;\n const html = withScope(childScope(key), () => escape(children()));\n sink.add(key, html);\n}\n\n/**\n * Runs `build` with the portal sink provided, and returns what `build` returns (the render's accessor).\n * A null sink provides nothing, so the portals of that render write nothing.\n * @internal\n */\nexport function withPortalSink<T>(sink: PortalSink | null, build: () => T): T {\n const view = PortalContext({\n value: sink,\n get children() {\n return build();\n },\n });\n return (view as () => T)();\n}\n\n/**\n * The collector a renderer writes into for one call: null without a `portals` option, else the cleared\n * collector.\n * @internal\n */\nexport function portalCollectorFor(portals: ServerPortals | undefined): PortalCollector | null {\n if (portals === undefined) return null;\n const collector = collectorOf(portals);\n collector.clear();\n return collector;\n}\n"],"mappings":"A,qNAuCA,IAAaA,EAAb,KAAmD,CACjD,wBAA2B,IAAI,IAE/B,IAAI,EAAa,EAAoB,CACnC,GAAI,CAAC,KAAK,QAAQ,IAAIC,CAAG,GAAK,KAAK,QAAQ,MAAA,IACzC,MAAM,IAAIC,EACR,mBACA,kFACF,EAEF,KAAK,QAAQ,IAAID,EAAKE,CAAI,CAC5B,CAGA,OAAc,CACZ,KAAK,QAAQ,MAAM,CACrB,CAEA,OAAO,EAAyB,EAA+B,CAC7DC,EAAmBH,EAAKI,EAAU,IAAI,CACxC,CAEA,MAAe,CACb,IAAIC,EAAM,GACV,IAAK,GAAM,CAACL,EAAKE,KAAS,KAAK,QAC7B,GAAO,cAAcF,EAAI,KAAKE,EAAK,cAAcF,EAAI,KAEvD,OAAOK,CACT,CACF,EAEA,MAAMC,kBAAa,IAAI,QAmBvB,SAAgBC,GAAqC,CACnD,IAAMC,EAAY,IAAIT,EAChBU,EAAyB,CAAE,SAAYD,EAAU,KAAK,CAAE,EAE9D,OADAF,EAAW,IAAIG,EAASD,CAAS,EAC1BC,CACT,CAOA,SAAgBC,EAAY,EAAyC,CACnE,IAAMF,EAAYF,EAAW,IAAIG,CAAO,EACxC,GAAID,IAAc,IAAA,GAChB,MAAU,UAAU,qDAAqD,EAE3E,OAAOA,CACT,CAaA,SAAgBL,EACd,EACA,EACA,EACM,CACN,GAAIQ,IAAS,MAAQX,IAAQ,IAAA,GAAW,OACxC,IAAME,EAAOU,EAAUC,EAAWb,CAAG,MAASc,EAAOV,EAAS,CAAC,CAAC,EAChEO,EAAK,IAAIX,EAAKE,CAAI,CACpB,CAOA,SAAgBa,EAAkB,EAAyB,EAAmB,CAO5E,OANaC,EAAc,CACzB,MAAOL,EACP,IAAI,UAAW,CACb,OAAOM,EAAM,CACf,CACF,CACW,CAAC,CAAa,CAC3B,CAOA,SAAgBC,EAAmB,EAA4D,CAC7F,GAAIT,IAAY,IAAA,GAAW,OAAO,KAClC,IAAMD,EAAYE,EAAYD,CAAO,EAErC,OADAD,EAAU,MAAM,EACTA,CACT,C"}
1
+ {"version":3,"file":"portals.js","names":["childScope","withScope","PortalContext","SsrError","escape","PortalCollector","key","html","children","renderServerPortal","out","collectors","createServerPortals","collector","portals","collectorOf","sink","withPortalSink","build","portalCollectorFor"],"sources":["../../../src/server/portals.ts"],"sourcesContent":["import { childScope, withScope } from \"../internal/hydration-scope\";\nimport { PortalContext, type PortalSink } from \"../internal/portal-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\n\n/**\n * The most portals one render may produce. A page with more open overlays than this is a bug, and the\n * collector refuses to grow without a bound.\n * @internal\n */\nexport const MAX_SERVER_PORTALS = 256;\n\n/**\n * The markup of the portals a server render produced (see {@link createServerPortals}). Pass it to\n * the render as its `portals` option, then emit `html()` at the end of `<body>`, after the app markup.\n * The client adopts each block when it hydrates the portal that wrote it.\n *\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<!doctype html><html><body><div id=\"app\">${app}</div>${portals.html()}</body></html>`;\n * @since 1.0.0\n */\nexport interface ServerPortals {\n /**\n * The collected blocks, in the order the render produced them: each is `<!--portal:KEY-->` markup\n * `<!--/portal:KEY-->`. Emit it once, at the end of `<body>`.\n * @returns The markup; empty when no portal was rendered.\n */\n html(): string;\n}\n\n/** The collector behind a {@link ServerPortals}: what a renderer writes into while it renders. @internal */\nexport class PortalCollector implements PortalSink {\n private readonly entries = new Map<string, string>();\n\n add(key: string, html: string): void {\n if (!this.entries.has(key) && this.entries.size >= MAX_SERVER_PORTALS) {\n throw new SsrError(\n \"SSR_PORTAL_LIMIT\",\n `A render produced more than ${MAX_SERVER_PORTALS} portals; close some overlays or raise the limit.`,\n );\n }\n this.entries.set(key, html);\n }\n\n /** Forgets what an earlier pass of the same render wrote. */\n clear(): void {\n this.entries.clear();\n }\n\n render(key: string | undefined, children: () => unknown): void {\n renderServerPortal(key, children, this);\n }\n\n html(): string {\n let out = \"\";\n for (const [key, html] of this.entries) {\n out += `<!--portal:${key}-->${html}<!--/portal:${key}-->`;\n }\n return out;\n }\n}\n\nconst collectors = new WeakMap<ServerPortals, PortalCollector>();\n\n/**\n * Creates the collector a server render writes its portals into. Without one, a `Portal` renders\n * nothing on the server. Create one per request: a render clears it before it starts, and one render\n * may produce at most 256 portals (more throw an `SsrError` whose `code` is `SSR_PORTAL_LIMIT`).\n *\n * @returns A new, empty {@link ServerPortals}.\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<body><div id=\"app\">${app}</div>${portals.html()}</body>`;\n * @since 1.0.0\n */\nexport function createServerPortals(): ServerPortals {\n const collector = new PortalCollector();\n const portals: ServerPortals = { html: () => collector.html() };\n collectors.set(portals, collector);\n return portals;\n}\n\n/**\n * The collector behind a `portals` option.\n * @throws TypeError when the value did not come from {@link createServerPortals}.\n * @internal\n */\nexport function collectorOf(portals: ServerPortals): PortalCollector {\n const collector = collectors.get(portals);\n if (collector === undefined) {\n throw new TypeError(\"portals must be created with createServerPortals().\");\n }\n return collector;\n}\n\n/**\n * The server half of a `Portal`: renders its content into the render's collector. The content gets its\n * own hydration scope, so the keys of the siblings do not depend on whether the portal rendered. Writes\n * nothing when the render has no collector or the portal has no key (no render scope).\n *\n * @param key The portal's key, from `nextKey()` at the call site.\n * @param children Reads the portal's content. A thunk, because reading a JSX child builds it, and the\n * content must be built inside its own scope.\n * @param sink The collector the portal context provides (null for a render without one).\n * @internal\n */\nexport function renderServerPortal(\n key: string | undefined,\n children: () => unknown,\n sink: PortalSink | null,\n): void {\n if (sink === null || key === undefined) return;\n const html = withScope(childScope(key), () => escape(children()));\n sink.add(key, html);\n}\n\n/**\n * Runs `build` with the portal sink provided, and returns what `build` returns (the render's accessor).\n * A null sink provides nothing, so the portals of that render write nothing.\n * @internal\n */\nexport function withPortalSink<T>(sink: PortalSink | null, build: () => T): T {\n const view = PortalContext({\n value: sink,\n get children() {\n return build();\n },\n });\n return (view as () => T)();\n}\n\n/**\n * The collector a renderer writes into for one call: null without a `portals` option, else the cleared\n * collector.\n * @internal\n */\nexport function portalCollectorFor(portals: ServerPortals | undefined): PortalCollector | null {\n if (portals === undefined) return null;\n const collector = collectorOf(portals);\n collector.clear();\n return collector;\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ClC,IAAMD,EAAYE,EAAYD,CAAO,EAErC,OADAD,EAAU,MAAM,EACTA,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"raw-text.js","names":["RAW_TEXT_ELEMENTS","CLOSING_TAG","neutralize","text","tag","match","rawTextContent","render","value","rawElementContent","resolved","resolveValue","isSsrNode","ssrRawText","invalid","SsrNode"],"sources":["../../../src/server/raw-text.ts"],"sourcesContent":["import { invalid } from \"./errors\";\nimport { render, resolveValue } from \"./escape\";\nimport { isSsrNode, SsrNode } from \"./node\";\n\n/**\n * Elements whose content the HTML parser reads as text and nothing else: `script` and `style` (raw text, no\n * entities) and `title` and `textarea` (entities only). Neither kind can hold a comment, so the region markers\n * that delimit a dynamic child elsewhere would show up as literal text inside them.\n */\nconst TEXT_ONLY_ELEMENTS: ReadonlySet<string> = new Set([\"script\", \"style\", \"title\", \"textarea\"]);\n\n/**\n * True for an HTML element whose content is text only, so its children are written without region markers\n * and the client adopts the text as it is. Pass the tag in any letter case; SVG elements of the same names\n * are ordinary elements and are not text only.\n * @internal\n */\nexport function isTextOnlyElement(tag: string): boolean {\n return TEXT_ONLY_ELEMENTS.has(tag.toLowerCase());\n}\n\n/** The elements whose text the parser reads raw. */\nconst RAW_TEXT_ELEMENTS: ReadonlySet<string> = new Set([\"script\", \"style\"]);\n\n/** The closing tag of a script or style in any case, and the `<!--` that opens a script's double-escaped state. */\nconst CLOSING_TAG = {\n script: /<\\/(script)|<!--/gi,\n style: /<\\/(style)/gi,\n} as const;\n\n/**\n * Keeps raw text from ending its element or the script data state. `</script` and `</style` get a backslash that\n * CSS, JavaScript and JSON all read as the character itself (`<\\/style` is `</style` in a string, a comment or a\n * selector escape), and `<!--` in a script becomes `<\\u0021--`: `\\!` is no JSON escape, and a script that holds\n * JSON data (`application/json`, `ld+json`) must still parse. The text means what it meant and the parser does\n * not see a tag. Entities would instead change the text: raw text has none.\n */\nfunction neutralize(tag: \"script\" | \"style\", text: string): string {\n return text.replace(CLOSING_TAG[tag], (match: string) =>\n match === \"<!--\" ? \"<\\\\u0021--\" : `<\\\\/${match.slice(2)}`,\n );\n}\n\n/** The text of a child value for a `script` or `style`: strings unescaped, the whole checked by {@link neutralize}. @internal */\nexport function rawTextContent(tag: string, value: unknown): string {\n return neutralize(\n tag.toLowerCase() === \"script\" ? \"script\" : \"style\",\n render(value, (text) => text),\n );\n}\n\n/**\n * The content of a `script` or `style` element made by `ssrElement`. A node the compiler built (`ssr`, `ssrRaw`)\n * is the application's own markup and is left as it is; any other value is raw text and is checked.\n * @internal\n */\nexport function rawElementContent(tag: string, value: unknown): string {\n const resolved = resolveValue(value);\n return isSsrNode(resolved) ? resolved.t : rawTextContent(tag, resolved);\n}\n\n/**\n * Writes the children of a `<script>` or `<style>` element: the helper compiled server output calls for a\n * dynamic child of one. The browser reads these elements' content as raw text, so the value is written\n * as it is (`a > b` stays `a > b`; HTML entities would corrupt the stylesheet or the code) with no region\n * markers around it, and the client adopts the text when it hydrates. Only one thing is changed: a closing tag of\n * the element, in any letter case (`</style`, `</SCRIPT`), and `<!--` in a script, would end the element\n * early or hide its end, so each is rewritten (`<\\/style`, `<\\u0021--`) to text that CSS, JavaScript and JSON read as the same characters.\n *\n * Accessors are called untracked, arrays are flattened, `null`, `undefined` and booleans write nothing, and\n * a symbol throws, as in {@link escape}.\n *\n * @param tag The element, `\"script\"` or `\"style\"` (any letter case).\n * @param value The child value: a string, a number, an array, an accessor or `null`.\n * @returns The text as a trusted `SsrNode`.\n * @throws TypeError `INVALID_RAW_TEXT_TAG` when `tag` is not `script` or `style`, and the errors of\n * {@link escape} for the value.\n * @example\n * import { renderToString, ssr, ssrRawText } from \"@shadow-js/web/server\";\n *\n * const css = \"a > b { color: red } </style><script>alert(1)</script>\";\n * const html = renderToString(() => ssr([\"<style>\", \"</style>\"], ssrRawText(\"style\", css)));\n * // \"<style>a > b { color: red } <\\/style><script>alert(1)</script></style>\"\n * @see escape\n * @since 1.0.2\n */\nexport function ssrRawText(tag: \"script\" | \"style\", value: unknown): SsrNode {\n if (typeof tag !== \"string\" || !RAW_TEXT_ELEMENTS.has(tag.toLowerCase())) {\n throw invalid(\"INVALID_RAW_TEXT_TAG\", \"ssrRawText(): the tag must be script or style.\");\n }\n return new SsrNode(rawTextContent(tag, value));\n}\n"],"mappings":"A,gJAsBA,MAAMA,kBAAyC,IAAI,IAAI,CAAC,SAAU,OAAO,CAAC,EAGpEC,EAAc,CAClB,OAAQ,qBACR,MAAO,cACT,EASA,SAASC,EAAW,EAAyB,EAAsB,CACjE,OAAOC,EAAK,QAAQF,EAAYG,GAAO,GACrCC,IAAU,OAAS,aAAe,OAAOA,EAAM,MAAM,CAAC,GACxD,CACF,CAGA,SAAgBC,EAAe,EAAa,EAAwB,CAClE,OAAOJ,EACLE,EAAI,YAAY,IAAM,SAAW,SAAW,QAC5CG,EAAOC,EAAQ,GAASL,CAAI,CAC9B,CACF,CAOA,SAAgBM,EAAkB,EAAa,EAAwB,CACrE,IAAMC,EAAWC,EAAaH,CAAK,EACnC,OAAOI,EAAUF,CAAQ,EAAIA,EAAS,EAAIJ,EAAeF,EAAKM,CAAQ,CACxE,CA2BA,SAAgBG,EAAW,EAAyB,EAAyB,CAC3E,GAAI,OAAOT,GAAQ,UAAY,CAACJ,EAAkB,IAAII,EAAI,YAAY,CAAC,EACrE,MAAMU,EAAQ,uBAAwB,gDAAgD,EAExF,OAAO,IAAIC,EAAQT,EAAeF,EAAKI,CAAK,CAAC,CAC/C,C"}
1
+ {"version":3,"file":"raw-text.js","names":["invalid","render","resolveValue","SsrNode","isSsrNode","RAW_TEXT_ELEMENTS","CLOSING_TAG","neutralize","tag","text","match","rawTextContent","value","rawElementContent","resolved","ssrRawText"],"sources":["../../../src/server/raw-text.ts"],"sourcesContent":["import { invalid } from \"./errors\";\nimport { render, resolveValue } from \"./escape\";\nimport { isSsrNode, SsrNode } from \"./node\";\n\n/**\n * Elements whose content the HTML parser reads as text and nothing else: `script` and `style` (raw text, no\n * entities) and `title` and `textarea` (entities only). Neither kind can hold a comment, so the region markers\n * that delimit a dynamic child elsewhere would show up as literal text inside them.\n */\nconst TEXT_ONLY_ELEMENTS: ReadonlySet<string> = new Set([\"script\", \"style\", \"title\", \"textarea\"]);\n\n/**\n * True for an HTML element whose content is text only, so its children are written without region markers\n * and the client adopts the text as it is. Pass the tag in any letter case; SVG elements of the same names\n * are ordinary elements and are not text only.\n * @internal\n */\nexport function isTextOnlyElement(tag: string): boolean {\n return TEXT_ONLY_ELEMENTS.has(tag.toLowerCase());\n}\n\n/** The elements whose text the parser reads raw. */\nconst RAW_TEXT_ELEMENTS: ReadonlySet<string> = new Set([\"script\", \"style\"]);\n\n/** The closing tag of a script or style in any case, and the `<!--` that opens a script's double-escaped state. */\nconst CLOSING_TAG = {\n script: /<\\/(script)|<!--/gi,\n style: /<\\/(style)/gi,\n} as const;\n\n/**\n * Keeps raw text from ending its element or the script data state. `</script` and `</style` get a backslash that\n * CSS, JavaScript and JSON all read as the character itself (`<\\/style` is `</style` in a string, a comment or a\n * selector escape), and `<!--` in a script becomes `<\\u0021--`: `\\!` is no JSON escape, and a script that holds\n * JSON data (`application/json`, `ld+json`) must still parse. The text means what it meant and the parser does\n * not see a tag. Entities would instead change the text: raw text has none.\n */\nfunction neutralize(tag: \"script\" | \"style\", text: string): string {\n return text.replace(CLOSING_TAG[tag], (match: string) =>\n match === \"<!--\" ? \"<\\\\u0021--\" : `<\\\\/${match.slice(2)}`,\n );\n}\n\n/** The text of a child value for a `script` or `style`: strings unescaped, the whole checked by {@link neutralize}. @internal */\nexport function rawTextContent(tag: string, value: unknown): string {\n return neutralize(\n tag.toLowerCase() === \"script\" ? \"script\" : \"style\",\n render(value, (text) => text),\n );\n}\n\n/**\n * The content of a `script` or `style` element made by `ssrElement`. A node the compiler built (`ssr`, `ssrRaw`)\n * is the application's own markup and is left as it is; any other value is raw text and is checked.\n * @internal\n */\nexport function rawElementContent(tag: string, value: unknown): string {\n const resolved = resolveValue(value);\n return isSsrNode(resolved) ? resolved.t : rawTextContent(tag, resolved);\n}\n\n/**\n * Writes the children of a `<script>` or `<style>` element: the helper compiled server output calls for a\n * dynamic child of one. The browser reads these elements' content as raw text, so the value is written\n * as it is (`a > b` stays `a > b`; HTML entities would corrupt the stylesheet or the code) with no region\n * markers around it, and the client adopts the text when it hydrates. Only one thing is changed: a closing tag of\n * the element, in any letter case (`</style`, `</SCRIPT`), and `<!--` in a script, would end the element\n * early or hide its end, so each is rewritten (`<\\/style`, `<\\u0021--`) to text that CSS, JavaScript and JSON read as the same characters.\n *\n * Accessors are called untracked, arrays are flattened, `null`, `undefined` and booleans write nothing, and\n * a symbol throws, as in {@link escape}.\n *\n * @param tag The element, `\"script\"` or `\"style\"` (any letter case).\n * @param value The child value: a string, a number, an array, an accessor or `null`.\n * @returns The text as a trusted `SsrNode`.\n * @throws TypeError `INVALID_RAW_TEXT_TAG` when `tag` is not `script` or `style`, and the errors of\n * {@link escape} for the value.\n * @example\n * import { renderToString, ssr, ssrRawText } from \"@shadow-js/web/server\";\n *\n * const css = \"a > b { color: red } </style><script>alert(1)</script>\";\n * const html = renderToString(() => ssr([\"<style>\", \"</style>\"], ssrRawText(\"style\", css)));\n * // \"<style>a > b { color: red } <\\/style><script>alert(1)</script></style>\"\n * @see escape\n * @since 1.0.2\n */\nexport function ssrRawText(tag: \"script\" | \"style\", value: unknown): SsrNode {\n if (typeof tag !== \"string\" || !RAW_TEXT_ELEMENTS.has(tag.toLowerCase())) {\n throw invalid(\"INVALID_RAW_TEXT_TAG\", \"ssrRawText(): the tag must be script or style.\");\n }\n return new SsrNode(rawTextContent(tag, value));\n}\n"],"mappings":"A,gJAsBA,MAAMK,kBAAyC,IAAI,IAAI,CAAC,SAAU,OAAO,CAAC,EAGpEC,EAAc,CAClB,OAAQ,qBACR,MAAO,cACT,EASA,SAASC,EAAWC,EAAyBC,EAAsB,CACjE,OAAOA,EAAK,QAAQH,EAAYE,GAAOE,GACrCA,IAAU,OAAS,aAAe,OAAOA,EAAM,MAAM,CAAC,GACxD,CACF,CAGA,SAAgBC,EAAeH,EAAaI,EAAwB,CAClE,OAAOL,EACLC,EAAI,YAAY,IAAM,SAAW,SAAW,QAC5CP,EAAOW,EAAQH,GAASA,CAAI,CAC9B,CACF,CAOA,SAAgBI,EAAkBL,EAAaI,EAAwB,CACrE,IAAME,EAAWZ,EAAaU,CAAK,EACnC,OAAOR,EAAUU,CAAQ,EAAIA,EAAS,EAAIH,EAAeH,EAAKM,CAAQ,CACxE,CA2BA,SAAgBC,EAAWP,EAAyBI,EAAyB,CAC3E,GAAI,OAAOJ,GAAQ,UAAY,CAACH,EAAkB,IAAIG,EAAI,YAAY,CAAC,EACrE,MAAMR,EAAQ,uBAAwB,gDAAgD,EAExF,OAAO,IAAIG,EAAQQ,EAAeH,EAAKI,CAAK,CAAC,CAC/C,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"render.js","names":["RENDER_ID","checkRenderId","renderId","reportersOf","options","renderMarkup","attachRootErrors","reporters","withPortalSink","portals","ResourceCacheContext","cache","runWithServerHead","head","withScope","createRootScope","escape","code","renderToString","portalCollectorFor","createRoot","dispose","runPass","requested","tracked","errors","error","user","seen","key","resourceKey","explicit","settled","reportPass","defineData","target","collectData","data","assertActive","job","SsrError","runPasses","pass","current","results","entry","advanced","index","result","maxPasses","checkAsyncOptions","timeoutMs","renderToStringAsync","timer","expired","reject","MAX_TIMER_MS"],"sources":["../../../src/server/render.ts"],"sourcesContent":["import { createRoot, type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\nimport {\n type PortalCollector,\n portalCollectorFor,\n type ServerPortals,\n withPortalSink,\n} from \"./portals\";\n\n/**\n * Options of {@link renderToString}, and the base of {@link AsyncRenderOptions}.\n * @since 1.0.0\n */\nexport interface RenderOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Give each app rendered into the\n * same page its own id, and pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * Collects the tags `useHead`, `<Title>`, `<Meta>`, ... register while rendering (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Collects the markup of the portals the render produces (see {@link createServerPortals}). Emit\n * `portals.html()` at the end of `<body>` once the render is done.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the render caught. The boundary's fallback is in the markup,\n * so the caller can answer the request with the status of the error. Called once per caught error.\n * For {@link renderToStringAsync} only the last pass is reported.\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the render does not throw that error and the markup\n * lacks the part that failed.\n * @default undefined (the error propagates out of the render)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\n/**\n * Options of {@link renderToStringAsync}: the {@link RenderOptions} plus the limits of the multi-pass\n * render.\n * @since 1.0.0\n */\nexport interface AsyncRenderOptions extends RenderOptions {\n /**\n * Upper bound for the whole render, in milliseconds: a positive finite number. Values above the\n * timer range (2147483647, about 24.8 days) count as 2147483647.\n * @default 10000\n */\n readonly timeoutMs?: number;\n /**\n * Maximum number of render passes: an integer of at least 1. Each pass renders with the resource\n * values the previous passes resolved.\n * @default 10\n */\n readonly maxPasses?: number;\n}\n\n/**\n * What {@link renderToStringAsync} resolves to: the markup and the resource data to embed for\n * hydration.\n * @since 1.0.0\n */\nexport interface AsyncRenderResult {\n /** The markup of the last pass. */\n readonly html: string;\n /**\n * The resolved resource values the last pass read, keyed as the client looks them up. Embed it in\n * the page with {@link serialize} and pass it to `hydrate()` as its `data` option, so the client\n * reuses the values instead of fetching again.\n */\n readonly data: Record<string, unknown>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_PASSES = 10;\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\n\n/** Validates a render id: it is written into markup, so only plain tokens are accepted. */\nfunction checkRenderId(renderId: string): string {\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n return renderId;\n}\n\n/**\n * The reporters of a render, in the shape the root takes them. An `onUncaughtError` is set only when the\n * caller gave one: a root with a handler does not rethrow, so without one the error must keep propagating.\n */\nfunction reportersOf(options: RenderOptions | undefined): RootErrorOptions {\n return {\n ...(options?.onCaughtError === undefined ? {} : { onCaughtError: options.onCaughtError }),\n ...(options?.onUncaughtError === undefined ? {} : { onUncaughtError: options.onUncaughtError }),\n };\n}\n\n/**\n * Runs `code` under the render's resource cache and returns the escaped markup. The root scope\n * is entered inside the provider, so accessors evaluated during escaping see the same cache.\n * Must run inside the root that is being rendered: the reporters are attached to it.\n */\nfunction renderMarkup(\n code: () => unknown,\n renderId: string,\n cache: ResourceCache | null,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n reporters: RootErrorOptions,\n): string {\n attachRootErrors(reporters);\n // The provider returns an accessor; reading it surfaces an error thrown while rendering.\n return (\n withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n ) as () => string\n )();\n}\n\n/**\n * Renders an app to an HTML string synchronously: the simplest server render, for pages whose data\n * is already at hand. Suspense boundaries whose resources are still pending render their fallback\n * (use {@link renderToStringAsync} or {@link renderToStream} to wait for data). Effects never run.\n * The root is disposed before this returns, and an error from `code` propagates after that cleanup.\n *\n * @param code Builds the app: returns a component result, an `SsrNode`, text or an array.\n * @param options Hydration-key prefix, head and portal collectors, and error reporters. Undefined uses\n * the defaults of {@link RenderOptions}.\n * @returns The escaped markup of the app.\n * @throws TypeError for an invalid `renderId`, for `portals` not created by\n * {@link createServerPortals}, or for a value that cannot be rendered (see {@link escape}). An error\n * no boundary caught propagates unless `onUncaughtError` is set.\n * @example\n * import { createComponent, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * const html = renderToString(() => createComponent(App, {}));\n * @see renderToStringAsync\n * @see renderToStream\n * @since 1.0.0\n */\nexport function renderToString(code: () => unknown, options?: RenderOptions): string {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const portals = portalCollectorFor(options?.portals);\n const reporters = reportersOf(options);\n return createRoot((dispose) => {\n try {\n return renderMarkup(code, renderId, null, options?.head, portals, reporters);\n } finally {\n dispose();\n }\n });\n}\n\n/** The errors one pass reported to its root, kept until the pass is known to be the answer. */\ninterface PassErrors {\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n}\n\n/** One render pass: its markup, the keys it asked for, and the fetches it started. */\ninterface Pass {\n readonly html: string;\n readonly requested: Set<string>;\n readonly tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }>;\n readonly errors: PassErrors;\n readonly dispose: () => void;\n}\n\n/**\n * Runs one pass. The root stays alive until the caller disposes it, so fetches are not aborted. The\n * pass records its errors instead of reporting them: every pass renders the same boundaries again, so\n * only the answering pass (see {@link reportPass}) reports.\n */\nfunction runPass(\n code: () => unknown,\n renderId: string,\n settled: ReadonlyMap<string, unknown>,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Pass {\n const requested = new Set<string>();\n const tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }> = [];\n const errors: PassErrors = { caught: [], uncaught: [] };\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n errors.caught.push(error);\n },\n // Recorded only when the caller reports uncaught errors; otherwise the error must still throw.\n ...(user.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n errors.uncaught.push(error);\n },\n }),\n };\n const seen = new Set<string>();\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise) => {\n if (seen.has(key)) return;\n seen.add(key);\n tracked.push({ key, promise });\n },\n };\n return createRoot((dispose) => {\n // Every pass registers the same tags and portals again: only the last pass counts.\n head?.clear();\n portals?.clear();\n const html = renderMarkup(code, renderId, cache, head, portals, reporters);\n return { html, requested, tracked, errors, dispose };\n });\n}\n\n/**\n * Hands the errors of the answering pass to the caller's reporters, in the order they happened. Called\n * once per render, so each caught error is reported once even when several passes rendered it.\n */\nfunction reportPass(errors: PassErrors, user: RootErrorOptions): void {\n for (const error of errors.caught) user.onCaughtError?.(error);\n for (const error of errors.uncaught) user.onUncaughtError?.(error);\n}\n\n/** Records a value under a key with defineProperty, so keys such as \"__proto__\" stay data. */\nfunction defineData(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** The values of `settled` that the pass asked for. */\nfunction collectData(\n requested: ReadonlySet<string>,\n settled: ReadonlyMap<string, unknown>,\n): Record<string, unknown> {\n const data: Record<string, unknown> = {};\n for (const key of requested) {\n if (settled.has(key)) defineData(data, key, settled.get(key));\n }\n return data;\n}\n\n/** Shared state of one async render: its cancellation flag and the roots still alive. */\ninterface Job {\n canceled: boolean;\n readonly roots: Array<() => void>;\n}\n\nfunction assertActive(job: Job): void {\n if (job.canceled)\n throw new SsrError(\"SSR_TIMEOUT\", \"The render was canceled after its time budget.\");\n}\n\n/**\n * The multi-pass algorithm. Pass N renders with the values resolved so far; the fetches it starts\n * are awaited, and another pass runs only if one of them produced a value that the next render can\n * use. A pass with no new value is final: its markup is the answer.\n */\nasync function runPasses(\n code: () => unknown,\n renderId: string,\n maxPasses: number,\n job: Job,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Promise<AsyncRenderResult> {\n const settled = new Map<string, unknown>();\n for (let pass = 1; ; pass += 1) {\n assertActive(job);\n const current = runPass(code, renderId, settled, head, portals, user);\n job.roots.push(current.dispose);\n if (current.tracked.length === 0) {\n current.dispose();\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n const results = await Promise.allSettled(current.tracked.map((entry) => entry.promise));\n assertActive(job);\n let advanced = false;\n results.forEach((result, index) => {\n const entry = current.tracked[index];\n if (entry === undefined || result.status !== \"fulfilled\") return;\n if (!settled.has(entry.key)) advanced = true;\n settled.set(entry.key, result.value);\n });\n current.dispose();\n if (!advanced) {\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n if (pass >= maxPasses) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept loading new resources after ${maxPasses} passes; raise maxPasses or flatten the data flow.`,\n );\n }\n }\n}\n\n/** Validates the numeric options. */\nfunction checkAsyncOptions(options: AsyncRenderOptions | undefined): {\n timeoutMs: number;\n maxPasses: number;\n} {\n const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxPasses = options?.maxPasses ?? DEFAULT_MAX_PASSES;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n if (!Number.isInteger(maxPasses) || maxPasses < 1) {\n throw new TypeError(\"render options: maxPasses must be an integer of at least 1.\");\n }\n return { timeoutMs, maxPasses };\n}\n\n/**\n * Renders an app to an HTML string once its data has loaded: each pass renders with the resource\n * values found so far, the fetches it starts are awaited, and another pass runs while one of them\n * produced a new value. Resources that reject are not cached and render their fallback. The error\n * reporters (`onCaughtError`, `onUncaughtError`) are called once, for the pass that gives the answer.\n *\n * @param code Builds the app.\n * @param options The {@link RenderOptions} plus `timeoutMs` and `maxPasses`. Undefined uses the\n * defaults of {@link AsyncRenderOptions}.\n * @returns A promise of the final markup and the resolved resource values, to embed in the page.\n * @throws TypeError (synchronously rejected) for an invalid `renderId`, `timeoutMs` or `maxPasses`.\n * The promise rejects with an `Error` named `SsrError` whose `code` is `SSR_BOUNDARY_WATERFALL` when\n * more than `maxPasses` passes are needed, or `SSR_TIMEOUT` when the time budget runs out; and with\n * the error of a failing render.\n * @example\n * import { createComponent, renderToStringAsync, serialize } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * async function page(): Promise<string> {\n * const { html, data } = await renderToStringAsync(() => createComponent(App, {}));\n * return `${html}<script type=\"application/json\" data-sh=\"0\">${serialize(data)}</script>`;\n * }\n * @see renderToString\n * @see renderToStream\n * @since 1.0.0\n */\nexport async function renderToStringAsync(\n code: () => unknown,\n options?: AsyncRenderOptions,\n): Promise<AsyncRenderResult> {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const { timeoutMs, maxPasses } = checkAsyncOptions(options);\n const job: Job = { canceled: false, roots: [] };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => {\n job.canceled = true;\n reject(new SsrError(\"SSR_TIMEOUT\", `The render did not finish within ${timeoutMs} ms.`));\n },\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n try {\n const portals = portalCollectorFor(options?.portals);\n return await Promise.race([\n runPasses(code, renderId, maxPasses, job, options?.head, portals, reportersOf(options)),\n expired,\n ]);\n } finally {\n clearTimeout(timer);\n job.canceled = true;\n for (const dispose of job.roots.splice(0)) dispose();\n }\n}\n"],"mappings":"A,ycAwFA,MAEMA,EAAY,mBAGlB,SAASC,EAAc,EAA0B,CAC/C,GAAI,OAAOC,GAAa,UAAY,CAACF,EAAU,KAAKE,CAAQ,EAC1D,MAAU,UAAU,oEAAoE,EAE1F,OAAOA,CACT,CAMA,SAASC,EAAY,EAAsD,CACzE,MAAO,CACL,GAAIC,GAAS,gBAAkB,IAAA,GAAY,C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,EAAI,SAAW,GACfC,EAAO,IAAIf,EAAS,cAAe,oCAAoCW,EAAU,KAAK,CAAC,CACzF,EACA,KAAK,IAAIA,EAAWK,CAAY,CAClC,CACF,CAAC,EACD,GAAI,CACF,IAAM/C,EAAUU,EAAmBf,GAAS,OAAO,EACnD,OAAO,MAAM,QAAQ,KAAK,CACxBqC,EAAUxB,EAAMf,EAAU+C,EAAWV,EAAKnC,GAAS,KAAMK,EAASN,EAAYC,CAAO,CAAC,EACtFkD,CACF,CAAC,CACH,QAAU,CACR,aAAaD,CAAK,EAClB,EAAI,SAAW,GACf,IAAK,IAAMhC,KAAWkB,EAAI,MAAM,OAAO,CAAC,EAAGlB,EAAQ,CACrD,CACF,C"}
1
+ {"version":3,"file":"render.js","names":["attachRootErrors","runWithServerHead","createRootScope","resourceKey","withScope","MAX_TIMER_MS","SsrError","escape","portalCollectorFor","withPortalSink","ResourceCacheContext","createRoot","RENDER_ID","checkRenderId","renderId","reportersOf","options","renderMarkup","code","cache","head","portals","reporters","renderToString","dispose","runPass","settled","user","requested","tracked","errors","error","seen","explicit","key","promise","reportPass","defineData","target","value","collectData","data","assertActive","job","runPasses","maxPasses","pass","current","results","entry","advanced","result","index","checkAsyncOptions","timeoutMs","renderToStringAsync","timer","expired","_resolve","reject"],"sources":["../../../src/server/render.ts"],"sourcesContent":["import { createRoot, type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\nimport {\n type PortalCollector,\n portalCollectorFor,\n type ServerPortals,\n withPortalSink,\n} from \"./portals\";\n\n/**\n * Options of {@link renderToString}, and the base of {@link AsyncRenderOptions}.\n * @since 1.0.0\n */\nexport interface RenderOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Give each app rendered into the\n * same page its own id, and pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * Collects the tags `useHead`, `<Title>`, `<Meta>`, ... register while rendering (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Collects the markup of the portals the render produces (see {@link createServerPortals}). Emit\n * `portals.html()` at the end of `<body>` once the render is done.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the render caught. The boundary's fallback is in the markup,\n * so the caller can answer the request with the status of the error. Called once per caught error.\n * For {@link renderToStringAsync} only the last pass is reported.\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the render does not throw that error and the markup\n * lacks the part that failed.\n * @default undefined (the error propagates out of the render)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\n/**\n * Options of {@link renderToStringAsync}: the {@link RenderOptions} plus the limits of the multi-pass\n * render.\n * @since 1.0.0\n */\nexport interface AsyncRenderOptions extends RenderOptions {\n /**\n * Upper bound for the whole render, in milliseconds: a positive finite number. Values above the\n * timer range (2147483647, about 24.8 days) count as 2147483647.\n * @default 10000\n */\n readonly timeoutMs?: number;\n /**\n * Maximum number of render passes: an integer of at least 1. Each pass renders with the resource\n * values the previous passes resolved.\n * @default 10\n */\n readonly maxPasses?: number;\n}\n\n/**\n * What {@link renderToStringAsync} resolves to: the markup and the resource data to embed for\n * hydration.\n * @since 1.0.0\n */\nexport interface AsyncRenderResult {\n /** The markup of the last pass. */\n readonly html: string;\n /**\n * The resolved resource values the last pass read, keyed as the client looks them up. Embed it in\n * the page with {@link serialize} and pass it to `hydrate()` as its `data` option, so the client\n * reuses the values instead of fetching again.\n */\n readonly data: Record<string, unknown>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_PASSES = 10;\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\n\n/** Validates a render id: it is written into markup, so only plain tokens are accepted. */\nfunction checkRenderId(renderId: string): string {\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n return renderId;\n}\n\n/**\n * The reporters of a render, in the shape the root takes them. An `onUncaughtError` is set only when the\n * caller gave one: a root with a handler does not rethrow, so without one the error must keep propagating.\n */\nfunction reportersOf(options: RenderOptions | undefined): RootErrorOptions {\n return {\n ...(options?.onCaughtError === undefined ? {} : { onCaughtError: options.onCaughtError }),\n ...(options?.onUncaughtError === undefined ? {} : { onUncaughtError: options.onUncaughtError }),\n };\n}\n\n/**\n * Runs `code` under the render's resource cache and returns the escaped markup. The root scope\n * is entered inside the provider, so accessors evaluated during escaping see the same cache.\n * Must run inside the root that is being rendered: the reporters are attached to it.\n */\nfunction renderMarkup(\n code: () => unknown,\n renderId: string,\n cache: ResourceCache | null,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n reporters: RootErrorOptions,\n): string {\n attachRootErrors(reporters);\n // The provider returns an accessor; reading it surfaces an error thrown while rendering.\n return (\n withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n ) as () => string\n )();\n}\n\n/**\n * Renders an app to an HTML string synchronously: the simplest server render, for pages whose data\n * is already at hand. Suspense boundaries whose resources are still pending render their fallback\n * (use {@link renderToStringAsync} or {@link renderToStream} to wait for data). Effects never run.\n * The root is disposed before this returns, and an error from `code` propagates after that cleanup.\n *\n * @param code Builds the app: returns a component result, an `SsrNode`, text or an array.\n * @param options Hydration-key prefix, head and portal collectors, and error reporters. Undefined uses\n * the defaults of {@link RenderOptions}.\n * @returns The escaped markup of the app.\n * @throws TypeError for an invalid `renderId`, for `portals` not created by\n * {@link createServerPortals}, or for a value that cannot be rendered (see {@link escape}). An error\n * no boundary caught propagates unless `onUncaughtError` is set.\n * @example\n * import { createComponent, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * const html = renderToString(() => createComponent(App, {}));\n * @see renderToStringAsync\n * @see renderToStream\n * @since 1.0.0\n */\nexport function renderToString(code: () => unknown, options?: RenderOptions): string {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const portals = portalCollectorFor(options?.portals);\n const reporters = reportersOf(options);\n return createRoot((dispose) => {\n try {\n return renderMarkup(code, renderId, null, options?.head, portals, reporters);\n } finally {\n dispose();\n }\n });\n}\n\n/** The errors one pass reported to its root, kept until the pass is known to be the answer. */\ninterface PassErrors {\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n}\n\n/** One render pass: its markup, the keys it asked for, and the fetches it started. */\ninterface Pass {\n readonly html: string;\n readonly requested: Set<string>;\n readonly tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }>;\n readonly errors: PassErrors;\n readonly dispose: () => void;\n}\n\n/**\n * Runs one pass. The root stays alive until the caller disposes it, so fetches are not aborted. The\n * pass records its errors instead of reporting them: every pass renders the same boundaries again, so\n * only the answering pass (see {@link reportPass}) reports.\n */\nfunction runPass(\n code: () => unknown,\n renderId: string,\n settled: ReadonlyMap<string, unknown>,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Pass {\n const requested = new Set<string>();\n const tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }> = [];\n const errors: PassErrors = { caught: [], uncaught: [] };\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n errors.caught.push(error);\n },\n // Recorded only when the caller reports uncaught errors; otherwise the error must still throw.\n ...(user.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n errors.uncaught.push(error);\n },\n }),\n };\n const seen = new Set<string>();\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise) => {\n if (seen.has(key)) return;\n seen.add(key);\n tracked.push({ key, promise });\n },\n };\n return createRoot((dispose) => {\n // Every pass registers the same tags and portals again: only the last pass counts.\n head?.clear();\n portals?.clear();\n const html = renderMarkup(code, renderId, cache, head, portals, reporters);\n return { html, requested, tracked, errors, dispose };\n });\n}\n\n/**\n * Hands the errors of the answering pass to the caller's reporters, in the order they happened. Called\n * once per render, so each caught error is reported once even when several passes rendered it.\n */\nfunction reportPass(errors: PassErrors, user: RootErrorOptions): void {\n for (const error of errors.caught) user.onCaughtError?.(error);\n for (const error of errors.uncaught) user.onUncaughtError?.(error);\n}\n\n/** Records a value under a key with defineProperty, so keys such as \"__proto__\" stay data. */\nfunction defineData(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** The values of `settled` that the pass asked for. */\nfunction collectData(\n requested: ReadonlySet<string>,\n settled: ReadonlyMap<string, unknown>,\n): Record<string, unknown> {\n const data: Record<string, unknown> = {};\n for (const key of requested) {\n if (settled.has(key)) defineData(data, key, settled.get(key));\n }\n return data;\n}\n\n/** Shared state of one async render: its cancellation flag and the roots still alive. */\ninterface Job {\n canceled: boolean;\n readonly roots: Array<() => void>;\n}\n\nfunction assertActive(job: Job): void {\n if (job.canceled)\n throw new SsrError(\"SSR_TIMEOUT\", \"The render was canceled after its time budget.\");\n}\n\n/**\n * The multi-pass algorithm. Pass N renders with the values resolved so far; the fetches it starts\n * are awaited, and another pass runs only if one of them produced a value that the next render can\n * use. A pass with no new value is final: its markup is the answer.\n */\nasync function runPasses(\n code: () => unknown,\n renderId: string,\n maxPasses: number,\n job: Job,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Promise<AsyncRenderResult> {\n const settled = new Map<string, unknown>();\n for (let pass = 1; ; pass += 1) {\n assertActive(job);\n const current = runPass(code, renderId, settled, head, portals, user);\n job.roots.push(current.dispose);\n if (current.tracked.length === 0) {\n current.dispose();\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n const results = await Promise.allSettled(current.tracked.map((entry) => entry.promise));\n assertActive(job);\n let advanced = false;\n results.forEach((result, index) => {\n const entry = current.tracked[index];\n if (entry === undefined || result.status !== \"fulfilled\") return;\n if (!settled.has(entry.key)) advanced = true;\n settled.set(entry.key, result.value);\n });\n current.dispose();\n if (!advanced) {\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n if (pass >= maxPasses) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept loading new resources after ${maxPasses} passes; raise maxPasses or flatten the data flow.`,\n );\n }\n }\n}\n\n/** Validates the numeric options. */\nfunction checkAsyncOptions(options: AsyncRenderOptions | undefined): {\n timeoutMs: number;\n maxPasses: number;\n} {\n const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxPasses = options?.maxPasses ?? DEFAULT_MAX_PASSES;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n if (!Number.isInteger(maxPasses) || maxPasses < 1) {\n throw new TypeError(\"render options: maxPasses must be an integer of at least 1.\");\n }\n return { timeoutMs, maxPasses };\n}\n\n/**\n * Renders an app to an HTML string once its data has loaded: each pass renders with the resource\n * values found so far, the fetches it starts are awaited, and another pass runs while one of them\n * produced a new value. Resources that reject are not cached and render their fallback. The error\n * reporters (`onCaughtError`, `onUncaughtError`) are called once, for the pass that gives the answer.\n *\n * @param code Builds the app.\n * @param options The {@link RenderOptions} plus `timeoutMs` and `maxPasses`. Undefined uses the\n * defaults of {@link AsyncRenderOptions}.\n * @returns A promise of the final markup and the resolved resource values, to embed in the page.\n * @throws TypeError (synchronously rejected) for an invalid `renderId`, `timeoutMs` or `maxPasses`.\n * The promise rejects with an `Error` named `SsrError` whose `code` is `SSR_BOUNDARY_WATERFALL` when\n * more than `maxPasses` passes are needed, or `SSR_TIMEOUT` when the time budget runs out; and with\n * the error of a failing render.\n * @example\n * import { createComponent, renderToStringAsync, serialize } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * async function page(): Promise<string> {\n * const { html, data } = await renderToStringAsync(() => createComponent(App, {}));\n * return `${html}<script type=\"application/json\" data-sh=\"0\">${serialize(data)}</script>`;\n * }\n * @see renderToString\n * @see renderToStream\n * @since 1.0.0\n */\nexport async function renderToStringAsync(\n code: () => unknown,\n options?: AsyncRenderOptions,\n): Promise<AsyncRenderResult> {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const { timeoutMs, maxPasses } = checkAsyncOptions(options);\n const job: Job = { canceled: false, roots: [] };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => {\n job.canceled = true;\n reject(new SsrError(\"SSR_TIMEOUT\", `The render did not finish within ${timeoutMs} ms.`));\n },\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n try {\n const portals = portalCollectorFor(options?.portals);\n return await Promise.race([\n runPasses(code, renderId, maxPasses, job, options?.head, portals, reportersOf(options)),\n expired,\n ]);\n } finally {\n clearTimeout(timer);\n job.canceled = true;\n for (const dispose of job.roots.splice(0)) dispose();\n }\n}\n"],"mappings":"A,ycAwFA,MAEMY,EAAY,mBAGlB,SAASC,EAAcC,EAA0B,CAC/C,GAAI,OAAOA,GAAa,UAAY,CAACF,EAAU,KAAKE,CAAQ,EAC1D,MAAU,UAAU,oEAAoE,EAE1F,OAAOA,CACT,CAMA,SAASC,EAAYC,EAAsD,CACzE,MAAO,CACL,GAAIA,GAAS,gBAAkB,IAAA,GAAY,CAAC,EAAI,CAAE,cAAeA,EAAQ,aAAc,EACvF,GAAIA,GAAS,kBAAo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AUC,IAAW,CACvDH,EAAQ,eACA,CACJb,EAAI,SAAW,GACfgB,EAAO,IAAIrD,EAAS,cAAe,oCAAoCgD,EAAU,KAAK,CAAC,CACzF,EACA,KAAK,IAAIA,EAAWjD,CAAY,CAClC,CACF,CAAC,EACD,GAAI,CACF,IAAMgB,EAAUb,EAAmBQ,GAAS,OAAO,EACnD,OAAO,MAAM,QAAQ,KAAK,CACxB4B,EAAU1B,EAAMJ,EAAU+B,EAAWF,EAAK3B,GAAS,KAAMK,EAASN,EAAYC,CAAO,CAAC,EACtFyC,CACF,CAAC,CACH,QAAU,CACR,aAAaD,CAAK,EAClBb,EAAI,SAAW,GACf,IAAK,IAAMnB,KAAWmB,EAAI,MAAM,OAAO,CAAC,EAAGnB,EAAQ,CACrD,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"serialize.js","names":["UNSAFE_TEXT","escapeForScript","json","char","encodeNumber","value","BINARY_KINDS","toBase64","binary","offset","bytes","fromBase64","text","malformed","i","binaryKindOf","name","ctor","isPlainObject","proto","serialize","table","index","queue","slotOf","existing","slot","encodeValue","invalid","encodeEntry","kind","pairs","key","item","items","root","data","head","entry","own","record","isRecord","detail","decodeScalar","tag","decodeValue","defineOwn","target","createEntry","time","buffer","href","fillEntry","pair","deserialize","payload","made"],"sources":["../../../src/server/serialize.ts"],"sourcesContent":["import { invalid } from \"./errors\";\n\n/*\n * Wire format: {\"r\": <value>, \"t\": [<entry>, ...]}. Containers (objects, arrays, Map, Set, Date,\n * URL) live in the table and refer to each other by index, so cycles and shared references keep\n * their identity and the walk needs no recursion. A value is a JSON primitive, or a tagged object:\n * {\"$\":\"u\"} undefined\n * {\"$\":\"num\",\"v\":\"NaN\"|\"Infinity\"|\"-Infinity\"|\"-0\"}\n * {\"$\":\"big\",\"v\":\"<decimal>\"} bigint\n * {\"$\":\"ref\",\"i\":<index>} a table entry\n * Table entries are {\"$\":\"obj\",\"e\":[[key,value],...]}, {\"$\":\"arr\",\"e\":[...]},\n * {\"$\":\"map\",\"e\":[[key,value],...]}, {\"$\":\"set\",\"e\":[...]}, {\"$\":\"date\",\"v\":<number>},\n * {\"$\":\"url\",\"v\":\"<href>\"}. Plain objects are read with own properties only and rebuilt with a\n * null prototype, so \"__proto__\" or \"constructor\" keys are ordinary data.\n */\n\n/** Characters that may not appear raw in the output: they would end a script element or a line. */\nconst UNSAFE_TEXT = /[<>&\\u2028\\u2029]/g;\n\n/** Escapes text for `<script type=\"application/json\">`: the JSON stays valid, the markup cannot close. */\nfunction escapeForScript(json: string): string {\n return json.replace(\n UNSAFE_TEXT,\n (char) => `\\\\u${char.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\n/** Encodes a number that JSON cannot carry exactly. */\nfunction encodeNumber(value: number): unknown {\n if (Number.isFinite(value) && !Object.is(value, -0)) return value;\n return { $: \"num\", v: Object.is(value, -0) ? \"-0\" : String(value) };\n}\n\n/** Binary types the wire format carries, by the name written on the wire. */\ntype BinaryConstructor = new (buffer: ArrayBuffer) => ArrayBufferView;\nconst BINARY_KINDS: ReadonlyMap<string, BinaryConstructor> = new Map<string, BinaryConstructor>([\n [\"Int8Array\", Int8Array],\n [\"Uint8Array\", Uint8Array],\n [\"Uint8ClampedArray\", Uint8ClampedArray],\n [\"Int16Array\", Int16Array],\n [\"Uint16Array\", Uint16Array],\n [\"Int32Array\", Int32Array],\n [\"Uint32Array\", Uint32Array],\n [\"Float32Array\", Float32Array],\n [\"Float64Array\", Float64Array],\n [\"BigInt64Array\", BigInt64Array],\n [\"BigUint64Array\", BigUint64Array],\n [\"DataView\", DataView],\n]);\n\n/** Base64 of `bytes`, converted in chunks so a large buffer cannot overflow the call stack. */\nfunction toBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let offset = 0; offset < bytes.length; offset += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));\n }\n return btoa(binary);\n}\n\n/** Bytes of a base64 text; malformed text throws a TypeError. */\nfunction fromBase64(text: string): Uint8Array {\n let binary: string;\n try {\n binary = atob(text);\n } catch {\n throw malformed(\"binary data is not valid base64.\");\n }\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/** The wire name of a typed array or DataView, or undefined for anything else. */\nfunction binaryKindOf(value: object): string | undefined {\n for (const [name, ctor] of BINARY_KINDS) {\n if (value instanceof ctor) return name;\n }\n return undefined;\n}\n\n/** True for plain objects: prototype is Object.prototype or none. */\nfunction isPlainObject(value: object): boolean {\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Serializes data for embedding in a page, as JSON that is safe inside a\n * `<script type=\"application/json\">` element. It carries what JSON cannot: undefined, NaN,\n * infinities, -0, bigint, Date, URL, Map, Set, ArrayBuffer, typed arrays and DataView (copied: views\n * that shared a buffer come back as independent copies), plus shared references and cycles between\n * plain objects and arrays. Read it back with {@link deserialize}.\n *\n * @param data The value to serialize.\n * @returns JSON text with `<`, `>`, `&`, U+2028 and U+2029 written as `\\u` escapes, so it cannot\n * close the script element.\n * @throws TypeError `UNSERIALIZABLE_VALUE` for a function, a symbol, or an object that is not one of\n * the supported kinds (a class instance, for example).\n * @example\n * import { serialize } from \"@shadow-js/web/server\";\n *\n * const data = { user: { name: \"Ada\" }, seen: new Set([1, 2]), at: new Date(0) };\n * const tag = `<script type=\"application/json\" id=\"data\">${serialize(data)}</script>`;\n * @see deserialize\n * @since 1.0.0\n */\nexport function serialize(data: unknown): string {\n const table: unknown[] = [];\n const index = new Map<object, number>();\n const queue: Array<{ readonly value: object; readonly slot: number }> = [];\n\n const slotOf = (value: object): number => {\n const existing = index.get(value);\n if (existing !== undefined) return existing;\n const slot = table.length;\n table.push(null);\n index.set(value, slot);\n queue.push({ value, slot });\n return slot;\n };\n\n const encodeValue = (value: unknown): unknown => {\n if (value === undefined) return { $: \"u\" };\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") return value;\n if (typeof value === \"number\") return encodeNumber(value);\n if (typeof value === \"bigint\") return { $: \"big\", v: value.toString() };\n if (typeof value === \"object\") return { $: \"ref\", i: slotOf(value) };\n throw invalid(\"UNSERIALIZABLE_VALUE\", `A ${typeof value} cannot be serialized.`);\n };\n\n const encodeEntry = (value: object): unknown => {\n if (value instanceof Date) return { $: \"date\", v: encodeValue(value.getTime()) };\n if (value instanceof ArrayBuffer) return { $: \"buf\", v: toBase64(new Uint8Array(value)) };\n if (ArrayBuffer.isView(value)) {\n const kind = binaryKindOf(value);\n if (kind !== undefined) {\n const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n return { $: \"bin\", k: kind, v: toBase64(bytes) };\n }\n }\n if (value instanceof URL) return { $: \"url\", v: value.href };\n if (value instanceof Map) {\n const pairs: unknown[] = [];\n for (const [key, item] of value) pairs.push([encodeValue(key), encodeValue(item)]);\n return { $: \"map\", e: pairs };\n }\n if (value instanceof Set) {\n const items: unknown[] = [];\n for (const item of value) items.push(encodeValue(item));\n return { $: \"set\", e: items };\n }\n if (Array.isArray(value)) {\n const items: unknown[] = [];\n // An index loop, so holes in a sparse array become undefined instead of being skipped.\n for (let i = 0; i < value.length; i += 1) items.push(encodeValue(value[i]));\n return { $: \"arr\", e: items };\n }\n if (!isPlainObject(value)) {\n throw invalid(\n \"UNSERIALIZABLE_VALUE\",\n \"Only plain objects, arrays, Map, Set, Date, URL, ArrayBuffer and typed arrays can be serialized.\",\n );\n }\n const pairs: unknown[] = [];\n for (const key of Object.keys(value)) pairs.push([key, encodeValue(Reflect.get(value, key))]);\n return { $: \"obj\", e: pairs };\n };\n\n const root = encodeValue(data);\n for (let head = 0; head < queue.length; head += 1) {\n const entry = queue[head];\n if (entry === undefined) break;\n table[entry.slot] = encodeEntry(entry.value);\n }\n return escapeForScript(JSON.stringify({ r: root, t: table }));\n}\n\n/** Reads an own property of a parsed JSON object; never reaches the prototype chain. */\nfunction own(record: object, key: string): unknown {\n return Object.hasOwn(record, key) ? Reflect.get(record, key) : undefined;\n}\n\n/** True for a non-null, non-array object. */\nfunction isRecord(value: unknown): value is object {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Throws the TypeError for a payload that is not in the wire format. */\nfunction malformed(detail: string): TypeError {\n return new TypeError(`deserialize(): ${detail}`);\n}\n\n/** Decodes a value that cannot refer to other entries (used while the table is created). */\nfunction decodeScalar(value: unknown): unknown {\n if (\n value === null ||\n typeof value === \"boolean\" ||\n typeof value === \"string\" ||\n typeof value === \"number\"\n ) {\n return value;\n }\n if (!isRecord(value)) throw malformed(\"unexpected value.\");\n const tag = own(value, \"$\");\n if (tag === \"u\") return undefined;\n if (tag === \"num\") {\n const text = own(value, \"v\");\n if (text === \"NaN\") return Number.NaN;\n if (text === \"Infinity\") return Number.POSITIVE_INFINITY;\n if (text === \"-Infinity\") return Number.NEGATIVE_INFINITY;\n if (text === \"-0\") return -0;\n throw malformed(\"unknown number.\");\n }\n if (tag === \"big\") {\n const text = own(value, \"v\");\n if (typeof text !== \"string\") throw malformed(\"bigint without digits.\");\n return BigInt(text);\n }\n throw malformed(\"unknown tag.\");\n}\n\n/**\n * Rebuilds a value from the table. Plain objects get a null prototype; their keys are defined as\n * own data properties, so no key can reach or replace a prototype.\n */\nfunction decodeValue(value: unknown, table: readonly unknown[]): unknown {\n if (isRecord(value) && own(value, \"$\") === \"ref\") {\n const slot = own(value, \"i\");\n if (typeof slot !== \"number\" || !Number.isInteger(slot) || slot < 0 || slot >= table.length) {\n throw malformed(\"reference outside the table.\");\n }\n return table[slot];\n }\n return decodeScalar(value);\n}\n\n/** Defines an own data property; never assigns, so no setter or prototype is involved. */\nfunction defineOwn(target: object, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** Creates an empty container for a table entry, or the value of a scalar entry. */\nfunction createEntry(entry: unknown): unknown {\n if (!isRecord(entry)) throw malformed(\"table entry is not an object.\");\n const tag = own(entry, \"$\");\n if (tag === \"obj\") return Object.create(null) as object;\n if (tag === \"arr\") return [];\n if (tag === \"map\") return new Map<unknown, unknown>();\n if (tag === \"set\") return new Set<unknown>();\n if (tag === \"date\") {\n const time = decodeScalar(own(entry, \"v\"));\n if (typeof time !== \"number\") throw malformed(\"date without a time.\");\n return new Date(time);\n }\n if (tag === \"buf\" || tag === \"bin\") {\n const text = own(entry, \"v\");\n if (typeof text !== \"string\") throw malformed(\"binary entry without data.\");\n const bytes = fromBase64(text);\n // A copy that owns exactly these bytes, so a view never exposes a larger buffer.\n const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n if (tag === \"buf\") return buffer;\n const kind = own(entry, \"k\");\n const ctor = typeof kind === \"string\" ? BINARY_KINDS.get(kind) : undefined;\n if (ctor === undefined) throw malformed(\"unknown binary kind.\");\n try {\n return new ctor(buffer as ArrayBuffer);\n } catch {\n throw malformed(\"binary data does not fit its type.\");\n }\n }\n if (tag === \"url\") {\n const href = own(entry, \"v\");\n if (typeof href !== \"string\") throw malformed(\"url without an href.\");\n return new URL(href);\n }\n throw malformed(\"unknown table entry.\");\n}\n\n/** Fills one container from its entry list. Date and URL entries are already complete. */\nfunction fillEntry(entry: object, target: unknown, table: readonly unknown[]): void {\n const tag = own(entry, \"$\");\n if (tag === \"date\" || tag === \"url\" || tag === \"buf\" || tag === \"bin\") return;\n const items = own(entry, \"e\");\n if (!Array.isArray(items)) throw malformed(\"entry without a list.\");\n if (tag === \"obj\" && target !== null && typeof target === \"object\") {\n for (const pair of items) {\n if (!Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== \"string\") {\n throw malformed(\"object entry is not a key and value.\");\n }\n defineOwn(target, pair[0], decodeValue(pair[1], table));\n }\n } else if (tag === \"arr\" && Array.isArray(target)) {\n for (const item of items) target.push(decodeValue(item, table));\n } else if (tag === \"map\" && target instanceof Map) {\n for (const pair of items) {\n if (!Array.isArray(pair) || pair.length !== 2) throw malformed(\"map entry is not a pair.\");\n target.set(decodeValue(pair[0], table), decodeValue(pair[1], table));\n }\n } else if (tag === \"set\" && target instanceof Set) {\n for (const item of items) target.add(decodeValue(item, table));\n } else {\n throw malformed(\"entry does not match its tag.\");\n }\n}\n\n/**\n * Rebuilds the value {@link serialize} wrote, with its shared references and cycles. Plain objects\n * come back with a null prototype (so a `__proto__` key is ordinary data), and malformed input throws\n * instead of producing a partial value. No code is evaluated.\n *\n * @param text JSON text produced by {@link serialize}.\n * @returns The rebuilt value.\n * @throws SyntaxError when `text` is not JSON; TypeError when the JSON is not in the format\n * `serialize` writes.\n * @example\n * import { deserialize, serialize } from \"@shadow-js/web/server\";\n *\n * const copy = deserialize(serialize({ tags: new Set([\"a\"]), total: 10n })) as {\n * tags: Set<string>;\n * total: bigint;\n * };\n * copy.tags.has(\"a\"); // true\n * @see serialize\n * @since 1.0.0\n */\nexport function deserialize(text: string): unknown {\n const payload: unknown = JSON.parse(text);\n if (!isRecord(payload)) throw malformed(\"payload is not an object.\");\n const table = own(payload, \"t\");\n if (!Array.isArray(table)) throw malformed(\"payload has no table.\");\n const made: unknown[] = [];\n for (const entry of table) made.push(createEntry(entry));\n for (let slot = 0; slot < table.length; slot += 1) {\n const entry = table[slot];\n if (isRecord(entry)) fillEntry(entry, made[slot], made);\n }\n return decodeValue(own(payload, \"r\"), made);\n}\n"],"mappings":"A,sCAiBA,MAAMA,EAAc,qBAGpB,SAASC,EAAgB,EAAsB,CAC7C,OAAOC,EAAK,QACVF,EACC,GAAS,MAAMG,EAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,GACjE,CACF,CAGA,SAASC,EAAa,EAAwB,CAE5C,OADI,OAAO,SAASC,CAAK,GAAK,CAAC,OAAO,GAAGA,EAAO,EAAE,EAAUA,EACrD,CAAE,EAAG,MAAO,EAAG,OAAO,GAAGA,EAAO,EAAE,EAAI,KAAO,OAAOA,CAAK,CAAE,CACpE,CAIA,MAAMC,kBAAuD,I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EAAG,MAAMR,EAAU,uBAAuB,EAClE,IAAM2C,EAAkB,CAAC,EACzB,IAAK,IAAMlB,KAASjB,EAAOmC,EAAK,KAAKR,EAAYV,CAAK,CAAC,EACvD,IAAK,IAAIZ,EAAO,EAAGA,EAAOL,EAAM,OAAQ,GAAQ,EAAG,CACjD,IAAMiB,EAAQjB,EAAMK,GAChBe,EAASH,CAAK,GAAGc,EAAUd,EAAOkB,EAAK9B,GAAO8B,CAAI,CACxD,CACA,OAAOX,EAAYN,EAAIgB,EAAS,GAAG,EAAGC,CAAI,CAC5C,C"}
1
+ {"version":3,"file":"serialize.js","names":["invalid","UNSAFE_TEXT","escapeForScript","json","char","encodeNumber","value","BINARY_KINDS","toBase64","bytes","binary","offset","fromBase64","text","malformed","i","binaryKindOf","name","ctor","isPlainObject","proto","serialize","data","table","index","queue","slotOf","existing","slot","encodeValue","encodeEntry","kind","pairs","key","item","items","root","head","entry","own","record","isRecord","detail","decodeScalar","tag","decodeValue","defineOwn","target","createEntry","time","buffer","href","fillEntry","pair","deserialize","payload","made"],"sources":["../../../src/server/serialize.ts"],"sourcesContent":["import { invalid } from \"./errors\";\n\n/*\n * Wire format: {\"r\": <value>, \"t\": [<entry>, ...]}. Containers (objects, arrays, Map, Set, Date,\n * URL) live in the table and refer to each other by index, so cycles and shared references keep\n * their identity and the walk needs no recursion. A value is a JSON primitive, or a tagged object:\n * {\"$\":\"u\"} undefined\n * {\"$\":\"num\",\"v\":\"NaN\"|\"Infinity\"|\"-Infinity\"|\"-0\"}\n * {\"$\":\"big\",\"v\":\"<decimal>\"} bigint\n * {\"$\":\"ref\",\"i\":<index>} a table entry\n * Table entries are {\"$\":\"obj\",\"e\":[[key,value],...]}, {\"$\":\"arr\",\"e\":[...]},\n * {\"$\":\"map\",\"e\":[[key,value],...]}, {\"$\":\"set\",\"e\":[...]}, {\"$\":\"date\",\"v\":<number>},\n * {\"$\":\"url\",\"v\":\"<href>\"}. Plain objects are read with own properties only and rebuilt with a\n * null prototype, so \"__proto__\" or \"constructor\" keys are ordinary data.\n */\n\n/** Characters that may not appear raw in the output: they would end a script element or a line. */\nconst UNSAFE_TEXT = /[<>&\\u2028\\u2029]/g;\n\n/** Escapes text for `<script type=\"application/json\">`: the JSON stays valid, the markup cannot close. */\nfunction escapeForScript(json: string): string {\n return json.replace(\n UNSAFE_TEXT,\n (char) => `\\\\u${char.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\n/** Encodes a number that JSON cannot carry exactly. */\nfunction encodeNumber(value: number): unknown {\n if (Number.isFinite(value) && !Object.is(value, -0)) return value;\n return { $: \"num\", v: Object.is(value, -0) ? \"-0\" : String(value) };\n}\n\n/** Binary types the wire format carries, by the name written on the wire. */\ntype BinaryConstructor = new (buffer: ArrayBuffer) => ArrayBufferView;\nconst BINARY_KINDS: ReadonlyMap<string, BinaryConstructor> = new Map<string, BinaryConstructor>([\n [\"Int8Array\", Int8Array],\n [\"Uint8Array\", Uint8Array],\n [\"Uint8ClampedArray\", Uint8ClampedArray],\n [\"Int16Array\", Int16Array],\n [\"Uint16Array\", Uint16Array],\n [\"Int32Array\", Int32Array],\n [\"Uint32Array\", Uint32Array],\n [\"Float32Array\", Float32Array],\n [\"Float64Array\", Float64Array],\n [\"BigInt64Array\", BigInt64Array],\n [\"BigUint64Array\", BigUint64Array],\n [\"DataView\", DataView],\n]);\n\n/** Base64 of `bytes`, converted in chunks so a large buffer cannot overflow the call stack. */\nfunction toBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let offset = 0; offset < bytes.length; offset += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));\n }\n return btoa(binary);\n}\n\n/** Bytes of a base64 text; malformed text throws a TypeError. */\nfunction fromBase64(text: string): Uint8Array {\n let binary: string;\n try {\n binary = atob(text);\n } catch {\n throw malformed(\"binary data is not valid base64.\");\n }\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/** The wire name of a typed array or DataView, or undefined for anything else. */\nfunction binaryKindOf(value: object): string | undefined {\n for (const [name, ctor] of BINARY_KINDS) {\n if (value instanceof ctor) return name;\n }\n return undefined;\n}\n\n/** True for plain objects: prototype is Object.prototype or none. */\nfunction isPlainObject(value: object): boolean {\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Serializes data for embedding in a page, as JSON that is safe inside a\n * `<script type=\"application/json\">` element. It carries what JSON cannot: undefined, NaN,\n * infinities, -0, bigint, Date, URL, Map, Set, ArrayBuffer, typed arrays and DataView (copied: views\n * that shared a buffer come back as independent copies), plus shared references and cycles between\n * plain objects and arrays. Read it back with {@link deserialize}.\n *\n * @param data The value to serialize.\n * @returns JSON text with `<`, `>`, `&`, U+2028 and U+2029 written as `\\u` escapes, so it cannot\n * close the script element.\n * @throws TypeError `UNSERIALIZABLE_VALUE` for a function, a symbol, or an object that is not one of\n * the supported kinds (a class instance, for example).\n * @example\n * import { serialize } from \"@shadow-js/web/server\";\n *\n * const data = { user: { name: \"Ada\" }, seen: new Set([1, 2]), at: new Date(0) };\n * const tag = `<script type=\"application/json\" id=\"data\">${serialize(data)}</script>`;\n * @see deserialize\n * @since 1.0.0\n */\nexport function serialize(data: unknown): string {\n const table: unknown[] = [];\n const index = new Map<object, number>();\n const queue: Array<{ readonly value: object; readonly slot: number }> = [];\n\n const slotOf = (value: object): number => {\n const existing = index.get(value);\n if (existing !== undefined) return existing;\n const slot = table.length;\n table.push(null);\n index.set(value, slot);\n queue.push({ value, slot });\n return slot;\n };\n\n const encodeValue = (value: unknown): unknown => {\n if (value === undefined) return { $: \"u\" };\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") return value;\n if (typeof value === \"number\") return encodeNumber(value);\n if (typeof value === \"bigint\") return { $: \"big\", v: value.toString() };\n if (typeof value === \"object\") return { $: \"ref\", i: slotOf(value) };\n throw invalid(\"UNSERIALIZABLE_VALUE\", `A ${typeof value} cannot be serialized.`);\n };\n\n const encodeEntry = (value: object): unknown => {\n if (value instanceof Date) return { $: \"date\", v: encodeValue(value.getTime()) };\n if (value instanceof ArrayBuffer) return { $: \"buf\", v: toBase64(new Uint8Array(value)) };\n if (ArrayBuffer.isView(value)) {\n const kind = binaryKindOf(value);\n if (kind !== undefined) {\n const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n return { $: \"bin\", k: kind, v: toBase64(bytes) };\n }\n }\n if (value instanceof URL) return { $: \"url\", v: value.href };\n if (value instanceof Map) {\n const pairs: unknown[] = [];\n for (const [key, item] of value) pairs.push([encodeValue(key), encodeValue(item)]);\n return { $: \"map\", e: pairs };\n }\n if (value instanceof Set) {\n const items: unknown[] = [];\n for (const item of value) items.push(encodeValue(item));\n return { $: \"set\", e: items };\n }\n if (Array.isArray(value)) {\n const items: unknown[] = [];\n // An index loop, so holes in a sparse array become undefined instead of being skipped.\n for (let i = 0; i < value.length; i += 1) items.push(encodeValue(value[i]));\n return { $: \"arr\", e: items };\n }\n if (!isPlainObject(value)) {\n throw invalid(\n \"UNSERIALIZABLE_VALUE\",\n \"Only plain objects, arrays, Map, Set, Date, URL, ArrayBuffer and typed arrays can be serialized.\",\n );\n }\n const pairs: unknown[] = [];\n for (const key of Object.keys(value)) pairs.push([key, encodeValue(Reflect.get(value, key))]);\n return { $: \"obj\", e: pairs };\n };\n\n const root = encodeValue(data);\n for (let head = 0; head < queue.length; head += 1) {\n const entry = queue[head];\n if (entry === undefined) break;\n table[entry.slot] = encodeEntry(entry.value);\n }\n return escapeForScript(JSON.stringify({ r: root, t: table }));\n}\n\n/** Reads an own property of a parsed JSON object; never reaches the prototype chain. */\nfunction own(record: object, key: string): unknown {\n return Object.hasOwn(record, key) ? Reflect.get(record, key) : undefined;\n}\n\n/** True for a non-null, non-array object. */\nfunction isRecord(value: unknown): value is object {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Throws the TypeError for a payload that is not in the wire format. */\nfunction malformed(detail: string): TypeError {\n return new TypeError(`deserialize(): ${detail}`);\n}\n\n/** Decodes a value that cannot refer to other entries (used while the table is created). */\nfunction decodeScalar(value: unknown): unknown {\n if (\n value === null ||\n typeof value === \"boolean\" ||\n typeof value === \"string\" ||\n typeof value === \"number\"\n ) {\n return value;\n }\n if (!isRecord(value)) throw malformed(\"unexpected value.\");\n const tag = own(value, \"$\");\n if (tag === \"u\") return undefined;\n if (tag === \"num\") {\n const text = own(value, \"v\");\n if (text === \"NaN\") return Number.NaN;\n if (text === \"Infinity\") return Number.POSITIVE_INFINITY;\n if (text === \"-Infinity\") return Number.NEGATIVE_INFINITY;\n if (text === \"-0\") return -0;\n throw malformed(\"unknown number.\");\n }\n if (tag === \"big\") {\n const text = own(value, \"v\");\n if (typeof text !== \"string\") throw malformed(\"bigint without digits.\");\n return BigInt(text);\n }\n throw malformed(\"unknown tag.\");\n}\n\n/**\n * Rebuilds a value from the table. Plain objects get a null prototype; their keys are defined as\n * own data properties, so no key can reach or replace a prototype.\n */\nfunction decodeValue(value: unknown, table: readonly unknown[]): unknown {\n if (isRecord(value) && own(value, \"$\") === \"ref\") {\n const slot = own(value, \"i\");\n if (typeof slot !== \"number\" || !Number.isInteger(slot) || slot < 0 || slot >= table.length) {\n throw malformed(\"reference outside the table.\");\n }\n return table[slot];\n }\n return decodeScalar(value);\n}\n\n/** Defines an own data property; never assigns, so no setter or prototype is involved. */\nfunction defineOwn(target: object, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** Creates an empty container for a table entry, or the value of a scalar entry. */\nfunction createEntry(entry: unknown): unknown {\n if (!isRecord(entry)) throw malformed(\"table entry is not an object.\");\n const tag = own(entry, \"$\");\n if (tag === \"obj\") return Object.create(null) as object;\n if (tag === \"arr\") return [];\n if (tag === \"map\") return new Map<unknown, unknown>();\n if (tag === \"set\") return new Set<unknown>();\n if (tag === \"date\") {\n const time = decodeScalar(own(entry, \"v\"));\n if (typeof time !== \"number\") throw malformed(\"date without a time.\");\n return new Date(time);\n }\n if (tag === \"buf\" || tag === \"bin\") {\n const text = own(entry, \"v\");\n if (typeof text !== \"string\") throw malformed(\"binary entry without data.\");\n const bytes = fromBase64(text);\n // A copy that owns exactly these bytes, so a view never exposes a larger buffer.\n const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n if (tag === \"buf\") return buffer;\n const kind = own(entry, \"k\");\n const ctor = typeof kind === \"string\" ? BINARY_KINDS.get(kind) : undefined;\n if (ctor === undefined) throw malformed(\"unknown binary kind.\");\n try {\n return new ctor(buffer as ArrayBuffer);\n } catch {\n throw malformed(\"binary data does not fit its type.\");\n }\n }\n if (tag === \"url\") {\n const href = own(entry, \"v\");\n if (typeof href !== \"string\") throw malformed(\"url without an href.\");\n return new URL(href);\n }\n throw malformed(\"unknown table entry.\");\n}\n\n/** Fills one container from its entry list. Date and URL entries are already complete. */\nfunction fillEntry(entry: object, target: unknown, table: readonly unknown[]): void {\n const tag = own(entry, \"$\");\n if (tag === \"date\" || tag === \"url\" || tag === \"buf\" || tag === \"bin\") return;\n const items = own(entry, \"e\");\n if (!Array.isArray(items)) throw malformed(\"entry without a list.\");\n if (tag === \"obj\" && target !== null && typeof target === \"object\") {\n for (const pair of items) {\n if (!Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== \"string\") {\n throw malformed(\"object entry is not a key and value.\");\n }\n defineOwn(target, pair[0], decodeValue(pair[1], table));\n }\n } else if (tag === \"arr\" && Array.isArray(target)) {\n for (const item of items) target.push(decodeValue(item, table));\n } else if (tag === \"map\" && target instanceof Map) {\n for (const pair of items) {\n if (!Array.isArray(pair) || pair.length !== 2) throw malformed(\"map entry is not a pair.\");\n target.set(decodeValue(pair[0], table), decodeValue(pair[1], table));\n }\n } else if (tag === \"set\" && target instanceof Set) {\n for (const item of items) target.add(decodeValue(item, table));\n } else {\n throw malformed(\"entry does not match its tag.\");\n }\n}\n\n/**\n * Rebuilds the value {@link serialize} wrote, with its shared references and cycles. Plain objects\n * come back with a null prototype (so a `__proto__` key is ordinary data), and malformed input throws\n * instead of producing a partial value. No code is evaluated.\n *\n * @param text JSON text produced by {@link serialize}.\n * @returns The rebuilt value.\n * @throws SyntaxError when `text` is not JSON; TypeError when the JSON is not in the format\n * `serialize` writes.\n * @example\n * import { deserialize, serialize } from \"@shadow-js/web/server\";\n *\n * const copy = deserialize(serialize({ tags: new Set([\"a\"]), total: 10n })) as {\n * tags: Set<string>;\n * total: bigint;\n * };\n * copy.tags.has(\"a\"); // true\n * @see serialize\n * @since 1.0.0\n */\nexport function deserialize(text: string): unknown {\n const payload: unknown = JSON.parse(text);\n if (!isRecord(payload)) throw malformed(\"payload is not an object.\");\n const table = own(payload, \"t\");\n if (!Array.isArray(table)) throw malformed(\"payload has no table.\");\n const made: unknown[] = [];\n for (const entry of table) made.push(createEntry(entry));\n for (let slot = 0; slot < table.length; slot += 1) {\n const entry = table[slot];\n if (isRecord(entry)) fillEntry(entry, made[slot], made);\n }\n return decodeValue(own(payload, \"r\"), made);\n}\n"],"mappings":"A,sCAiBA,MAAMC,EAAc,qBAGpB,SAASC,EAAgBC,EAAsB,CAC7C,OAAOA,EAAK,QACVF,EACCG,GAAS,MAAMA,EAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,GACjE,CACF,CAGA,SAASC,EAAaC,EAAwB,CAE5C,OADI,OAAO,SAASA,CAAK,GAAK,CAAC,OAAO,GAAGA,EAAO,EAAE,EAAUA,EACrD,CAAE,EAAG,MAAO,EAAG,OAAO,GAAGA,EAAO,EAAE,EAAI,KAAO,OAAOA,CAAK,CAAE,CACpE,CAIA,MAAMC,kBAAuD,IAAI,IAA+B,CAC9F,CAAC,YAAa,SAAS,EACvB,CAAC,aAAc,UAAU,EACzB,CAAC,oBAAqB,iBAAiB,EACvC,CAAC,aAAc,UAAU,EACzB,CAAC,cAAe,WAAW,EA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,EAAYV,CAAK,CAAC,EACvD,IAAK,IAAIV,EAAO,EAAGA,EAAOL,EAAM,OAAQK,GAAQ,EAAG,CACjD,IAAMU,EAAQf,EAAMK,GAChBa,EAASH,CAAK,GAAGc,EAAUd,EAAOkB,EAAK5B,GAAO4B,CAAI,CACxD,CACA,OAAOX,EAAYN,EAAIgB,EAAS,GAAG,EAAGC,CAAI,CAC5C,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"stream.js","names":["RENDER_ID","script","nonce","body","renderToStream","renderId","options","timeoutMs","signal","portals","portalCollectorFor","encoder","passes","disposeAll","errors","pass","error","canceled","timer","cancelRender","settled","fetching","push","controller","text","renderPass","cache","key","resourceKey","explicit","promise","entry","value","trackOptions","sink","boundary","reporters","createRoot","stop","attachRootErrors","StreamContext","withPortalSink","ResourceCacheContext","runWithServerHead","withScope","createRootScope","escape","code","rejectAbort","abort","reject","SsrError","MAX_TIMER_MS","onAbort","cleanup","reason","answer","round","held","untrack","failRemaining","strikes","settledBefore","current","emitted","html","data","serialize"],"sources":["../../../src/server/stream.ts"],"sourcesContent":["import {\n createRoot,\n type ResourceCache,\n ResourceCacheContext,\n type ResourceTrackOptions,\n untrack,\n} from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { type StreamBoundary, StreamContext, type StreamSink } from \"../internal/stream-context\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"./escape\";\nimport { portalCollectorFor, type ServerPortals, withPortalSink } from \"./portals\";\nimport { serialize } from \"./serialize\";\n\n/**\n * Options of {@link renderToStream}.\n * @since 1.0.0\n */\nexport interface StreamOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * CSP nonce for the inline swap scripts. Characters outside letters, digits, `+`, `/`, `=`, `_` and\n * `-` are removed before it is written.\n * @default undefined (the scripts get no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Upper bound for the whole stream, in milliseconds, a positive finite number (values above 2147483647 count as 2147483647). When it runs out, the stream errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT`.\n * @default 30000\n */\n readonly timeoutMs?: number;\n /**\n * Aborts the render: the stream errors with the signal's reason and every pending fetch is abandoned.\n * @default undefined (the render is bounded only by `timeoutMs`)\n */\n readonly signal?: AbortSignal;\n /**\n * Collects the tags `useHead`, `<Title>`, ... register while the shell renders (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Called with the shell markup as soon as it is ready, before it is enqueued: the moment to write\n * the document head and choose the response status.\n * @default undefined (no callback)\n */\n readonly onShellReady?: (shell: string) => void;\n /**\n * Collects the markup of the portals the stream produces (see {@link createServerPortals}). The stream\n * does not write it: once the stream has ended, emit `portals.html()` at the end of `<body>`.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the stream caught, once per caught error. An error in the shell\n * happens before the first chunk, so the caller can still choose the response status; an error in a later\n * boundary happens after the shell and changes only that boundary (its fallback stays).\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the stream does not error on that error and the markup lacks\n * the part that failed.\n * @default undefined (the error ends the stream in its `error` state)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * The most shell renders a stream makes while resources hold its first flush. Each render uses the held\n * values the one before resolved, so a chain of held resources is bounded like a boundary waterfall.\n */\nconst MAX_SHELL_PASSES = 10;\n\n/**\n * One render of the shell: its markup, the boundaries still pending in it, the keys it asked for and the\n * fetches it started. Only the answering pass (the one the stream sends) reports its errors; the others\n * are discarded, and their fetches stay alive so a later pass can join them.\n */\ninterface ShellPass {\n html: string;\n boundaries: StreamBoundary[];\n readonly requested: Set<string>;\n /** The fetches this render started that hold the first flush (`deferStream`), by key. */\n readonly held: Array<{ readonly key: string; readonly entry: Promise<void> }>;\n /** The fetches this render started that the stream is still waiting for. */\n readonly inFlight: Set<Promise<void>>;\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n answered: boolean;\n dispose: () => void;\n}\n\n/**\n * The constant swap runtime. `$S(id)` replaces the fallback of boundary `id` (the nodes between\n * its `<!--[b:id-->` and `<!--]-->` comments) with the content of `<template id=\"s:id\">`; with a\n * second argument the boundary failed on the server and keeps its fallback for the client.\n */\nconst SWAP_RUNTIME =\n 'window.$S=function(i,f){var t=document.getElementById(\"s:\"+i);if(!t)return;' +\n \"if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){\" +\n 'if(c.data===\"[b:\"+i){var d=1,n=c.nextSibling,e=null;while(n){' +\n 'if(n.nodeType===8){if(n.data.charAt(0)===\"[\"){d++}else if(n.data===\"]\"){d--;if(d===0){e=n;break}}}' +\n \"n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);\" +\n \"e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};\";\n\nfunction script(body: string, nonce: string | undefined): string {\n const attribute =\n nonce === undefined ? \"\" : ` nonce=\"${nonce.replace(/[^A-Za-z0-9+/=_-]/g, \"\")}\"`;\n return `<script${attribute}>${body}</script>`;\n}\n\n/**\n * Renders an app as a stream of HTML, for the fastest first byte: the shell first (pending Suspense\n * boundaries show their fallback), then one chunk per boundary as its data arrives, in the order the\n * data settles, and finally, when resources resolved, a\n * `<script type=\"application/json\" data-sh=\"RENDER_ID\">` block with their values. The page works without JavaScript: each chunk is a `<template>` that a\n * tiny inline script swaps in for the fallback. A boundary whose data can no longer arrive keeps its\n * fallback for the client.\n *\n * @param code Builds the app.\n * @param options Hydration-key prefix, nonce, time budget, abort signal, collectors, shell callback\n * and error reporters. Undefined uses the defaults of {@link StreamOptions}.\n * @returns A byte stream of the app markup, to be placed inside your document. Canceling it stops\n * the render.\n * @throws TypeError, synchronously, for an invalid `renderId` or `timeoutMs`. The stream itself errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT` when `timeoutMs` runs out, with the signal's reason when\n * `signal` aborts, and with an error no boundary caught when `onUncaughtError` is not set.\n * @example\n * import { createComponent, renderToStream } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * function handle(request: Request): Response {\n * const stream = renderToStream(() => createComponent(App, {}), { signal: request.signal });\n * return new Response(stream, { headers: { \"content-type\": \"text/html\" } });\n * }\n * @see renderToStringAsync\n * @since 1.0.0\n */\nexport function renderToStream(\n code: () => unknown,\n options: StreamOptions = {},\n): ReadableStream<Uint8Array> {\n const renderId = options.renderId ?? \"0\";\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n const signal = options.signal;\n const portals = portalCollectorFor(options.portals);\n const encoder = new TextEncoder();\n // Every render of the shell, kept until the stream ends: a later pass joins the fetches an earlier one started.\n const passes: ShellPass[] = [];\n const disposeAll = (): void => {\n const errors: unknown[] = [];\n for (const pass of passes.splice(0)) {\n try {\n pass.dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0)\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, \"Stream cleanup failed.\");\n };\n let canceled = false;\n // Cleared when the stream ends or is canceled, so a finished render never keeps the process alive.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancelRender: (reason: unknown) => void = () => undefined;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const settled = new Map<string, unknown>();\n // The fetch each key was last started with: a render that finds it unsettled joins it (ResourceCache.pending).\n const fetching = new Map<string, Promise<unknown>>();\n const push = (text: string): void => {\n if (signal?.aborted) throw signal.reason;\n if (!canceled) controller.enqueue(encoder.encode(text));\n };\n\n /** Renders the shell once. Its resources, boundaries and errors belong to this pass alone. */\n const renderPass = (): ShellPass => {\n const pass: ShellPass = {\n html: \"\",\n boundaries: [],\n requested: new Set<string>(),\n held: [],\n inFlight: new Set<Promise<void>>(),\n caught: [],\n uncaught: [],\n answered: false,\n dispose: () => undefined,\n };\n passes.push(pass);\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n pass.requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise, trackOptions?: ResourceTrackOptions) => {\n fetching.set(key, promise);\n const entry = promise.then(\n (value) => {\n settled.set(key, value);\n },\n () => undefined,\n );\n pass.inFlight.add(entry);\n void entry.finally(() => pass.inFlight.delete(entry));\n if (trackOptions?.deferStream === true) pass.held.push({ key, entry });\n },\n pending: (key) => fetching.get(key),\n };\n const sink: StreamSink = {\n defer: (boundary: StreamBoundary) => {\n pass.boundaries.push(boundary);\n },\n };\n // Errors of a pass that is not the answer are held back: the answering pass reports them, once.\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n if (pass.answered) options.onCaughtError?.(error);\n else pass.caught.push(error);\n },\n ...(options.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n if (pass.answered) options.onUncaughtError?.(error);\n else pass.uncaught.push(error);\n },\n }),\n };\n options.head?.clear();\n portals?.clear();\n pass.html = createRoot((stop) => {\n pass.dispose = stop;\n // Attached to the root of this render, so every boundary of it reports through these.\n attachRootErrors(reporters);\n const view = StreamContext({\n value: sink,\n get children() {\n return withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(options.head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n );\n },\n });\n return ((view as () => unknown)() as () => string)();\n });\n return pass;\n };\n\n let rejectAbort: (reason: unknown) => void = () => undefined;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n timer = setTimeout(\n () =>\n reject(\n new SsrError(\"SSR_TIMEOUT\", `The stream did not finish within ${timeoutMs} ms.`),\n ),\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n const onAbort = (): void =>\n rejectAbort(signal?.reason ?? new Error(\"The render was aborted.\"));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const cleanup = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n disposeAll();\n };\n // Wake a held shell or boundary immediately; late resource settlement must not render again.\n cancelRender = (reason) => {\n rejectAbort(reason);\n cleanup();\n };\n // Marks the abort handled for a render that has already finished (the stream closed, the timer\n // is cleared) and no longer awaits it. While the loop below awaits `abort`, its rejection is\n // rethrown there into `controller.error`, so a timeout or an abort is reported to the reader.\n abort.catch(() => undefined);\n\n try {\n if (signal?.aborted) throw signal.reason;\n // The shell is sent once the resources it holds have settled: a held render that finds a\n // value renders again with it, so the value is in the first chunk and not behind a fallback.\n let answer = renderPass();\n for (let round = 1; answer.held.length > 0; round += 1) {\n await Promise.race([abort, Promise.allSettled(answer.held.map((held) => held.entry))]);\n // No held value arrived (each held fetch failed): this render is the answer, with its fallbacks.\n if (!answer.held.some((held) => settled.has(held.key))) break;\n if (round >= MAX_SHELL_PASSES) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept holding the stream after ${MAX_SHELL_PASSES} shell renders; flatten the data flow.`,\n );\n }\n answer = renderPass();\n }\n\n answer.answered = true;\n untrack(() => {\n for (const error of answer.caught) options.onCaughtError?.(error);\n for (const error of answer.uncaught) options.onUncaughtError?.(error);\n options.onShellReady?.(answer.html);\n });\n push(\n answer.boundaries.length > 0\n ? answer.html + script(SWAP_RUNTIME, options.nonce)\n : answer.html,\n );\n\n const failRemaining = (): void => {\n // Nothing can make progress (failed resources): leave the fallbacks for the client.\n for (const boundary of answer.boundaries.splice(0)) {\n push(\n `<template id=\"s:${boundary.id}\"></template>` +\n script(`$S(${JSON.stringify(boundary.id)},1)`, options.nonce),\n );\n }\n };\n let strikes = 0;\n while (answer.boundaries.length > 0) {\n if (answer.inFlight.size === 0) {\n failRemaining();\n break;\n }\n const settledBefore = settled.size;\n await Promise.race([abort, Promise.race([...answer.inFlight])]);\n const current = answer.boundaries;\n answer.boundaries = [];\n let emitted = false;\n for (const boundary of current) {\n const html = boundary.rebuild();\n if (html === null) continue;\n emitted = true;\n push(\n `<template id=\"s:${boundary.id}\">${html}</template>` +\n script(`$S(${JSON.stringify(boundary.id)})`, options.nonce),\n );\n }\n // Rounds that settle nothing new and emit nothing (only rejections) are bounded.\n strikes = settled.size === settledBefore && !emitted ? strikes + 1 : 0;\n if (answer.boundaries.length > 0 && strikes >= 2) failRemaining();\n }\n\n const data: Record<string, unknown> = {};\n for (const key of answer.requested) {\n if (!settled.has(key)) continue;\n Object.defineProperty(data, key, {\n value: settled.get(key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n if (Object.keys(data).length > 0) {\n push(`<script type=\"application/json\" data-sh=\"${renderId}\">${serialize(data)}</script>`);\n }\n cleanup();\n if (!canceled) controller.close();\n } catch (error) {\n cleanup();\n if (!canceled) controller.error(error);\n }\n },\n cancel(reason) {\n canceled = true;\n cancelRender(reason);\n },\n });\n}\n"],"mappings":"A,+jBA6EA,MAAMA,EAAY,mBAwClB,SAASC,EAAO,EAAc,EAAmC,CAG/D,MAAO,UADLC,IAAU,IAAA,GAAY,GAAK,WAAWA,EAAM,QAAQ,qBAAsB,EAAE,EAAE,GACrD,GAAGC,EAAK,WACrC,CA+BA,SAAgBC,EACd,EACA,EAAyB,CAAC,EACE,CAC5B,IAAMC,EAAWC,EAAQ,UAAY,IACrC,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K,CACvC,CACF,EACA,OAAO,EAAQ,CACb,EAAW,GACXG,EAAaoC,CAAM,CACrB,CACF,CAAC,CACH,C"}
1
+ {"version":3,"file":"stream.js","names":["attachRootErrors","runWithServerHead","createRootScope","resourceKey","withScope","StreamContext","MAX_TIMER_MS","SsrError","escape","portalCollectorFor","withPortalSink","serialize","ResourceCacheContext","createRoot","untrack","RENDER_ID","script","body","nonce","renderToStream","code","options","renderId","timeoutMs","signal","portals","encoder","passes","disposeAll","errors","pass","error","canceled","timer","cancelRender","controller","settled","fetching","push","text","renderPass","cache","explicit","key","promise","trackOptions","entry","value","sink","boundary","reporters","stop","rejectAbort","abort","_resolve","reject","onAbort","cleanup","reason","answer","round","held","failRemaining","strikes","settledBefore","current","emitted","html","data"],"sources":["../../../src/server/stream.ts"],"sourcesContent":["import {\n createRoot,\n type ResourceCache,\n ResourceCacheContext,\n type ResourceTrackOptions,\n untrack,\n} from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { type StreamBoundary, StreamContext, type StreamSink } from \"../internal/stream-context\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"./escape\";\nimport { portalCollectorFor, type ServerPortals, withPortalSink } from \"./portals\";\nimport { serialize } from \"./serialize\";\n\n/**\n * Options of {@link renderToStream}.\n * @since 1.0.0\n */\nexport interface StreamOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * CSP nonce for the inline swap scripts. Characters outside letters, digits, `+`, `/`, `=`, `_` and\n * `-` are removed before it is written.\n * @default undefined (the scripts get no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Upper bound for the whole stream, in milliseconds, a positive finite number (values above 2147483647 count as 2147483647). When it runs out, the stream errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT`.\n * @default 30000\n */\n readonly timeoutMs?: number;\n /**\n * Aborts the render: the stream errors with the signal's reason and every pending fetch is abandoned.\n * @default undefined (the render is bounded only by `timeoutMs`)\n */\n readonly signal?: AbortSignal;\n /**\n * Collects the tags `useHead`, `<Title>`, ... register while the shell renders (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Called with the shell markup as soon as it is ready, before it is enqueued: the moment to write\n * the document head and choose the response status.\n * @default undefined (no callback)\n */\n readonly onShellReady?: (shell: string) => void;\n /**\n * Collects the markup of the portals the stream produces (see {@link createServerPortals}). The stream\n * does not write it: once the stream has ended, emit `portals.html()` at the end of `<body>`.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the stream caught, once per caught error. An error in the shell\n * happens before the first chunk, so the caller can still choose the response status; an error in a later\n * boundary happens after the shell and changes only that boundary (its fallback stays).\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the stream does not error on that error and the markup lacks\n * the part that failed.\n * @default undefined (the error ends the stream in its `error` state)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * The most shell renders a stream makes while resources hold its first flush. Each render uses the held\n * values the one before resolved, so a chain of held resources is bounded like a boundary waterfall.\n */\nconst MAX_SHELL_PASSES = 10;\n\n/**\n * One render of the shell: its markup, the boundaries still pending in it, the keys it asked for and the\n * fetches it started. Only the answering pass (the one the stream sends) reports its errors; the others\n * are discarded, and their fetches stay alive so a later pass can join them.\n */\ninterface ShellPass {\n html: string;\n boundaries: StreamBoundary[];\n readonly requested: Set<string>;\n /** The fetches this render started that hold the first flush (`deferStream`), by key. */\n readonly held: Array<{ readonly key: string; readonly entry: Promise<void> }>;\n /** The fetches this render started that the stream is still waiting for. */\n readonly inFlight: Set<Promise<void>>;\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n answered: boolean;\n dispose: () => void;\n}\n\n/**\n * The constant swap runtime. `$S(id)` replaces the fallback of boundary `id` (the nodes between\n * its `<!--[b:id-->` and `<!--]-->` comments) with the content of `<template id=\"s:id\">`; with a\n * second argument the boundary failed on the server and keeps its fallback for the client.\n */\nconst SWAP_RUNTIME =\n 'window.$S=function(i,f){var t=document.getElementById(\"s:\"+i);if(!t)return;' +\n \"if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){\" +\n 'if(c.data===\"[b:\"+i){var d=1,n=c.nextSibling,e=null;while(n){' +\n 'if(n.nodeType===8){if(n.data.charAt(0)===\"[\"){d++}else if(n.data===\"]\"){d--;if(d===0){e=n;break}}}' +\n \"n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);\" +\n \"e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};\";\n\nfunction script(body: string, nonce: string | undefined): string {\n const attribute =\n nonce === undefined ? \"\" : ` nonce=\"${nonce.replace(/[^A-Za-z0-9+/=_-]/g, \"\")}\"`;\n return `<script${attribute}>${body}</script>`;\n}\n\n/**\n * Renders an app as a stream of HTML, for the fastest first byte: the shell first (pending Suspense\n * boundaries show their fallback), then one chunk per boundary as its data arrives, in the order the\n * data settles, and finally, when resources resolved, a\n * `<script type=\"application/json\" data-sh=\"RENDER_ID\">` block with their values. The page works without JavaScript: each chunk is a `<template>` that a\n * tiny inline script swaps in for the fallback. A boundary whose data can no longer arrive keeps its\n * fallback for the client.\n *\n * @param code Builds the app.\n * @param options Hydration-key prefix, nonce, time budget, abort signal, collectors, shell callback\n * and error reporters. Undefined uses the defaults of {@link StreamOptions}.\n * @returns A byte stream of the app markup, to be placed inside your document. Canceling it stops\n * the render.\n * @throws TypeError, synchronously, for an invalid `renderId` or `timeoutMs`. The stream itself errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT` when `timeoutMs` runs out, with the signal's reason when\n * `signal` aborts, and with an error no boundary caught when `onUncaughtError` is not set.\n * @example\n * import { createComponent, renderToStream } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * function handle(request: Request): Response {\n * const stream = renderToStream(() => createComponent(App, {}), { signal: request.signal });\n * return new Response(stream, { headers: { \"content-type\": \"text/html\" } });\n * }\n * @see renderToStringAsync\n * @since 1.0.0\n */\nexport function renderToStream(\n code: () => unknown,\n options: StreamOptions = {},\n): ReadableStream<Uint8Array> {\n const renderId = options.renderId ?? \"0\";\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n const signal = options.signal;\n const portals = portalCollectorFor(options.portals);\n const encoder = new TextEncoder();\n // Every render of the shell, kept until the stream ends: a later pass joins the fetches an earlier one started.\n const passes: ShellPass[] = [];\n const disposeAll = (): void => {\n const errors: unknown[] = [];\n for (const pass of passes.splice(0)) {\n try {\n pass.dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0)\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, \"Stream cleanup failed.\");\n };\n let canceled = false;\n // Cleared when the stream ends or is canceled, so a finished render never keeps the process alive.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancelRender: (reason: unknown) => void = () => undefined;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const settled = new Map<string, unknown>();\n // The fetch each key was last started with: a render that finds it unsettled joins it (ResourceCache.pending).\n const fetching = new Map<string, Promise<unknown>>();\n const push = (text: string): void => {\n if (signal?.aborted) throw signal.reason;\n if (!canceled) controller.enqueue(encoder.encode(text));\n };\n\n /** Renders the shell once. Its resources, boundaries and errors belong to this pass alone. */\n const renderPass = (): ShellPass => {\n const pass: ShellPass = {\n html: \"\",\n boundaries: [],\n requested: new Set<string>(),\n held: [],\n inFlight: new Set<Promise<void>>(),\n caught: [],\n uncaught: [],\n answered: false,\n dispose: () => undefined,\n };\n passes.push(pass);\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n pass.requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise, trackOptions?: ResourceTrackOptions) => {\n fetching.set(key, promise);\n const entry = promise.then(\n (value) => {\n settled.set(key, value);\n },\n () => undefined,\n );\n pass.inFlight.add(entry);\n void entry.finally(() => pass.inFlight.delete(entry));\n if (trackOptions?.deferStream === true) pass.held.push({ key, entry });\n },\n pending: (key) => fetching.get(key),\n };\n const sink: StreamSink = {\n defer: (boundary: StreamBoundary) => {\n pass.boundaries.push(boundary);\n },\n };\n // Errors of a pass that is not the answer are held back: the answering pass reports them, once.\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n if (pass.answered) options.onCaughtError?.(error);\n else pass.caught.push(error);\n },\n ...(options.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n if (pass.answered) options.onUncaughtError?.(error);\n else pass.uncaught.push(error);\n },\n }),\n };\n options.head?.clear();\n portals?.clear();\n pass.html = createRoot((stop) => {\n pass.dispose = stop;\n // Attached to the root of this render, so every boundary of it reports through these.\n attachRootErrors(reporters);\n const view = StreamContext({\n value: sink,\n get children() {\n return withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(options.head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n );\n },\n });\n return ((view as () => unknown)() as () => string)();\n });\n return pass;\n };\n\n let rejectAbort: (reason: unknown) => void = () => undefined;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n timer = setTimeout(\n () =>\n reject(\n new SsrError(\"SSR_TIMEOUT\", `The stream did not finish within ${timeoutMs} ms.`),\n ),\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n const onAbort = (): void =>\n rejectAbort(signal?.reason ?? new Error(\"The render was aborted.\"));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const cleanup = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n disposeAll();\n };\n // Wake a held shell or boundary immediately; late resource settlement must not render again.\n cancelRender = (reason) => {\n rejectAbort(reason);\n cleanup();\n };\n // Marks the abort handled for a render that has already finished (the stream closed, the timer\n // is cleared) and no longer awaits it. While the loop below awaits `abort`, its rejection is\n // rethrown there into `controller.error`, so a timeout or an abort is reported to the reader.\n abort.catch(() => undefined);\n\n try {\n if (signal?.aborted) throw signal.reason;\n // The shell is sent once the resources it holds have settled: a held render that finds a\n // value renders again with it, so the value is in the first chunk and not behind a fallback.\n let answer = renderPass();\n for (let round = 1; answer.held.length > 0; round += 1) {\n await Promise.race([abort, Promise.allSettled(answer.held.map((held) => held.entry))]);\n // No held value arrived (each held fetch failed): this render is the answer, with its fallbacks.\n if (!answer.held.some((held) => settled.has(held.key))) break;\n if (round >= MAX_SHELL_PASSES) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept holding the stream after ${MAX_SHELL_PASSES} shell renders; flatten the data flow.`,\n );\n }\n answer = renderPass();\n }\n\n answer.answered = true;\n untrack(() => {\n for (const error of answer.caught) options.onCaughtError?.(error);\n for (const error of answer.uncaught) options.onUncaughtError?.(error);\n options.onShellReady?.(answer.html);\n });\n push(\n answer.boundaries.length > 0\n ? answer.html + script(SWAP_RUNTIME, options.nonce)\n : answer.html,\n );\n\n const failRemaining = (): void => {\n // Nothing can make progress (failed resources): leave the fallbacks for the client.\n for (const boundary of answer.boundaries.splice(0)) {\n push(\n `<template id=\"s:${boundary.id}\"></template>` +\n script(`$S(${JSON.stringify(boundary.id)},1)`, options.nonce),\n );\n }\n };\n let strikes = 0;\n while (answer.boundaries.length > 0) {\n if (answer.inFlight.size === 0) {\n failRemaining();\n break;\n }\n const settledBefore = settled.size;\n await Promise.race([abort, Promise.race([...answer.inFlight])]);\n const current = answer.boundaries;\n answer.boundaries = [];\n let emitted = false;\n for (const boundary of current) {\n const html = boundary.rebuild();\n if (html === null) continue;\n emitted = true;\n push(\n `<template id=\"s:${boundary.id}\">${html}</template>` +\n script(`$S(${JSON.stringify(boundary.id)})`, options.nonce),\n );\n }\n // Rounds that settle nothing new and emit nothing (only rejections) are bounded.\n strikes = settled.size === settledBefore && !emitted ? strikes + 1 : 0;\n if (answer.boundaries.length > 0 && strikes >= 2) failRemaining();\n }\n\n const data: Record<string, unknown> = {};\n for (const key of answer.requested) {\n if (!settled.has(key)) continue;\n Object.defineProperty(data, key, {\n value: settled.get(key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n if (Object.keys(data).length > 0) {\n push(`<script type=\"application/json\" data-sh=\"${renderId}\">${serialize(data)}</script>`);\n }\n cleanup();\n if (!canceled) controller.close();\n } catch (error) {\n cleanup();\n if (!canceled) controller.error(error);\n }\n },\n cancel(reason) {\n canceled = true;\n cancelRender(reason);\n },\n });\n}\n"],"mappings":"A,+jBA6EA,MAAMe,EAAY,mBAwClB,SAASC,EAAOC,EAAcC,EAAmC,CAG/D,MAAO,UADLA,IAAU,IAAA,GAAY,GAAK,WAAWA,EAAM,QAAQ,qBAAsB,EAAE,EAAE,GACrD,GAAGD,EAAK,WACrC,CA+BA,SAAgBE,EACdC,EACAC,EAAyB,CAAC,EACE,CAC5B,IAAMC,EAAWD,EAAQ,UAAY,IACrC,GAAI,OAAOC,GAAa,UAAY,CAACP,EAAU,KAAKO,CAAQ,EAC1D,MAAU,UAAU,oEAAoE,EAE1F,IAAMC,EAAYF,EAAQ,WAAa,IACvC,GAAI,OAAOE,GAAc,UAAY,EAAEA,EAAY,IAAM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