@shadow-js/web 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/dev/attributes.d.ts +10 -3
  3. package/dist/dev/attributes.js +27 -49
  4. package/dist/dev/attributes.js.map +1 -1
  5. package/dist/dev/class-style.d.ts +15 -6
  6. package/dist/dev/class-style.js +64 -47
  7. package/dist/dev/class-style.js.map +1 -1
  8. package/dist/dev/control-flow/dynamic.d.ts +11 -2
  9. package/dist/dev/control-flow/dynamic.js +57 -40
  10. package/dist/dev/control-flow/dynamic.js.map +1 -1
  11. package/dist/dev/control-flow/error-boundary.js +2 -2
  12. package/dist/dev/control-flow/error-boundary.js.map +1 -1
  13. package/dist/dev/control-flow/portal.d.ts +2 -2
  14. package/dist/dev/control-flow/portal.js +17 -13
  15. package/dist/dev/control-flow/portal.js.map +1 -1
  16. package/dist/dev/control-flow/suspense-list.js +2 -2
  17. package/dist/dev/control-flow/suspense-list.js.map +1 -1
  18. package/dist/dev/control-flow/suspense.js +2 -2
  19. package/dist/dev/control-flow/suspense.js.map +1 -1
  20. package/dist/dev/element.js +6 -3
  21. package/dist/dev/element.js.map +1 -1
  22. package/dist/dev/events.js +15 -44
  23. package/dist/dev/events.js.map +1 -1
  24. package/dist/dev/extend.d.ts +2 -2
  25. package/dist/dev/extend.js +2 -2
  26. package/dist/dev/insert.d.ts +26 -5
  27. package/dist/dev/insert.js +84 -45
  28. package/dist/dev/insert.js.map +1 -1
  29. package/dist/dev/internal/accessor.js +56 -0
  30. package/dist/dev/internal/accessor.js.map +1 -0
  31. package/dist/dev/internal/claim.d.ts +2 -1
  32. package/dist/dev/internal/claim.js +18 -3
  33. package/dist/dev/internal/claim.js.map +1 -1
  34. package/dist/dev/internal/css-units.js +2 -2
  35. package/dist/dev/internal/css-units.js.map +1 -1
  36. package/dist/dev/internal/diagnostics.d.ts +7 -3
  37. package/dist/dev/internal/diagnostics.js +14 -4
  38. package/dist/dev/internal/diagnostics.js.map +1 -1
  39. package/dist/dev/internal/early-events.js +20 -2
  40. package/dist/dev/internal/early-events.js.map +1 -1
  41. package/dist/dev/internal/portal-context.d.ts +9 -0
  42. package/dist/dev/internal/portal-context.js.map +1 -1
  43. package/dist/dev/internal/react-names.js +45 -71
  44. package/dist/dev/internal/react-names.js.map +1 -1
  45. package/dist/dev/internal/reconcile.js +7 -12
  46. package/dist/dev/internal/reconcile.js.map +1 -1
  47. package/dist/dev/jsx/global.d.ts +5 -2
  48. package/dist/dev/jsx/html.d.ts +1 -0
  49. package/dist/dev/resource-hints.js +4 -2
  50. package/dist/dev/resource-hints.js.map +1 -1
  51. package/dist/dev/select-value.js +5 -15
  52. package/dist/dev/select-value.js.map +1 -1
  53. package/dist/dev/server/attributes.d.ts +3 -0
  54. package/dist/dev/server/attributes.js +6 -32
  55. package/dist/dev/server/attributes.js.map +1 -1
  56. package/dist/dev/server/element.js +10 -7
  57. package/dist/dev/server/element.js.map +1 -1
  58. package/dist/dev/server/errors.js +7 -1
  59. package/dist/dev/server/errors.js.map +1 -1
  60. package/dist/dev/server/escape.js +14 -6
  61. package/dist/dev/server/escape.js.map +1 -1
  62. package/dist/dev/server/form-controls.js +5 -2
  63. package/dist/dev/server/form-controls.js.map +1 -1
  64. package/dist/dev/server/index.d.ts +2 -1
  65. package/dist/dev/server/index.js +3 -2
  66. package/dist/dev/server/portals.js +3 -0
  67. package/dist/dev/server/portals.js.map +1 -1
  68. package/dist/dev/server/raw-text.d.ts +28 -0
  69. package/dist/dev/server/raw-text.js +66 -0
  70. package/dist/dev/server/raw-text.js.map +1 -0
  71. package/dist/dev/server/render.d.ts +2 -1
  72. package/dist/dev/server/render.js +3 -3
  73. package/dist/dev/server/render.js.map +1 -1
  74. package/dist/dev/server/stream.d.ts +1 -1
  75. package/dist/dev/server/stream.js +3 -3
  76. package/dist/dev/server/stream.js.map +1 -1
  77. package/dist/dev/server.d.ts +2 -1
  78. package/dist/dev/server.js +3 -2
  79. package/dist/dev/spread.js +56 -81
  80. package/dist/dev/spread.js.map +1 -1
  81. package/dist/dev/template.js +1 -3
  82. package/dist/dev/template.js.map +1 -1
  83. package/dist/dev/view-transition.js +12 -4
  84. package/dist/dev/view-transition.js.map +1 -1
  85. package/dist/prod/attributes.js +1 -1
  86. package/dist/prod/attributes.js.map +1 -1
  87. package/dist/prod/class-style.js +1 -1
  88. package/dist/prod/class-style.js.map +1 -1
  89. package/dist/prod/control-flow/dynamic.js +1 -1
  90. package/dist/prod/control-flow/dynamic.js.map +1 -1
  91. package/dist/prod/control-flow/error-boundary.js +1 -1
  92. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  93. package/dist/prod/control-flow/portal.js +1 -1
  94. package/dist/prod/control-flow/portal.js.map +1 -1
  95. package/dist/prod/control-flow/suspense-list.js +1 -1
  96. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  97. package/dist/prod/control-flow/suspense.js +1 -1
  98. package/dist/prod/control-flow/suspense.js.map +1 -1
  99. package/dist/prod/element.js +1 -1
  100. package/dist/prod/element.js.map +1 -1
  101. package/dist/prod/events.js +1 -1
  102. package/dist/prod/events.js.map +1 -1
  103. package/dist/prod/extend.js +1 -1
  104. package/dist/prod/insert.js +1 -1
  105. package/dist/prod/insert.js.map +1 -1
  106. package/dist/prod/internal/accessor.js +2 -0
  107. package/dist/prod/internal/accessor.js.map +1 -0
  108. package/dist/prod/internal/claim.js +1 -1
  109. package/dist/prod/internal/claim.js.map +1 -1
  110. package/dist/prod/internal/css-units.js +1 -1
  111. package/dist/prod/internal/css-units.js.map +1 -1
  112. package/dist/prod/internal/diagnostics.js +1 -1
  113. package/dist/prod/internal/diagnostics.js.map +1 -1
  114. package/dist/prod/internal/early-events.js +1 -1
  115. package/dist/prod/internal/early-events.js.map +1 -1
  116. package/dist/prod/internal/portal-context.js.map +1 -1
  117. package/dist/prod/internal/react-names.js +1 -1
  118. package/dist/prod/internal/react-names.js.map +1 -1
  119. package/dist/prod/internal/reconcile.js +1 -1
  120. package/dist/prod/internal/reconcile.js.map +1 -1
  121. package/dist/prod/resource-hints.js +1 -1
  122. package/dist/prod/resource-hints.js.map +1 -1
  123. package/dist/prod/select-value.js +1 -1
  124. package/dist/prod/select-value.js.map +1 -1
  125. package/dist/prod/server/attributes.js +1 -1
  126. package/dist/prod/server/attributes.js.map +1 -1
  127. package/dist/prod/server/element.js +1 -1
  128. package/dist/prod/server/element.js.map +1 -1
  129. package/dist/prod/server/errors.js +1 -1
  130. package/dist/prod/server/errors.js.map +1 -1
  131. package/dist/prod/server/escape.js +1 -1
  132. package/dist/prod/server/escape.js.map +1 -1
  133. package/dist/prod/server/form-controls.js +2 -2
  134. package/dist/prod/server/form-controls.js.map +1 -1
  135. package/dist/prod/server/index.js +1 -1
  136. package/dist/prod/server/portals.js +1 -1
  137. package/dist/prod/server/portals.js.map +1 -1
  138. package/dist/prod/server/raw-text.js +2 -0
  139. package/dist/prod/server/raw-text.js.map +1 -0
  140. package/dist/prod/server/render.js +1 -1
  141. package/dist/prod/server/render.js.map +1 -1
  142. package/dist/prod/server/stream.js +1 -1
  143. package/dist/prod/server/stream.js.map +1 -1
  144. package/dist/prod/server.js +1 -1
  145. package/dist/prod/spread.js +1 -1
  146. package/dist/prod/spread.js.map +1 -1
  147. package/dist/prod/template.js +1 -1
  148. package/dist/prod/template.js.map +1 -1
  149. package/dist/prod/view-transition.js +1 -1
  150. package/dist/prod/view-transition.js.map +1 -1
  151. package/dist/server/attributes.js +1 -1
  152. package/dist/server/attributes.js.map +1 -1
  153. package/dist/server/class-style.js +1 -1
  154. package/dist/server/class-style.js.map +1 -1
  155. package/dist/server/control-flow/dynamic.js +1 -1
  156. package/dist/server/control-flow/dynamic.js.map +1 -1
  157. package/dist/server/control-flow/error-boundary.js +1 -1
  158. package/dist/server/control-flow/error-boundary.js.map +1 -1
  159. package/dist/server/control-flow/portal.js +1 -1
  160. package/dist/server/control-flow/portal.js.map +1 -1
  161. package/dist/server/control-flow/suspense-list.js +1 -1
  162. package/dist/server/control-flow/suspense-list.js.map +1 -1
  163. package/dist/server/control-flow/suspense.js +1 -1
  164. package/dist/server/control-flow/suspense.js.map +1 -1
  165. package/dist/server/element.js +1 -1
  166. package/dist/server/element.js.map +1 -1
  167. package/dist/server/events.js +1 -1
  168. package/dist/server/events.js.map +1 -1
  169. package/dist/server/extend.js +1 -1
  170. package/dist/server/insert.js +1 -1
  171. package/dist/server/insert.js.map +1 -1
  172. package/dist/server/internal/accessor.js +2 -0
  173. package/dist/server/internal/accessor.js.map +1 -0
  174. package/dist/server/internal/claim.js +1 -1
  175. package/dist/server/internal/claim.js.map +1 -1
  176. package/dist/server/internal/css-units.js +1 -1
  177. package/dist/server/internal/css-units.js.map +1 -1
  178. package/dist/server/internal/diagnostics.js +1 -1
  179. package/dist/server/internal/diagnostics.js.map +1 -1
  180. package/dist/server/internal/early-events.js +1 -1
  181. package/dist/server/internal/early-events.js.map +1 -1
  182. package/dist/server/internal/portal-context.js.map +1 -1
  183. package/dist/server/internal/react-names.js +1 -1
  184. package/dist/server/internal/react-names.js.map +1 -1
  185. package/dist/server/internal/reconcile.js +1 -1
  186. package/dist/server/internal/reconcile.js.map +1 -1
  187. package/dist/server/resource-hints.js +1 -1
  188. package/dist/server/resource-hints.js.map +1 -1
  189. package/dist/server/select-value.js +1 -1
  190. package/dist/server/select-value.js.map +1 -1
  191. package/dist/server/server/attributes.js +1 -1
  192. package/dist/server/server/attributes.js.map +1 -1
  193. package/dist/server/server/element.js +1 -1
  194. package/dist/server/server/element.js.map +1 -1
  195. package/dist/server/server/errors.js +1 -1
  196. package/dist/server/server/errors.js.map +1 -1
  197. package/dist/server/server/escape.js +1 -1
  198. package/dist/server/server/escape.js.map +1 -1
  199. package/dist/server/server/form-controls.js +2 -2
  200. package/dist/server/server/form-controls.js.map +1 -1
  201. package/dist/server/server/index.js +1 -1
  202. package/dist/server/server/portals.js +1 -1
  203. package/dist/server/server/portals.js.map +1 -1
  204. package/dist/server/server/raw-text.js +2 -0
  205. package/dist/server/server/raw-text.js.map +1 -0
  206. package/dist/server/server/render.js +1 -1
  207. package/dist/server/server/render.js.map +1 -1
  208. package/dist/server/server/stream.js +1 -1
  209. package/dist/server/server/stream.js.map +1 -1
  210. package/dist/server/server.js +1 -1
  211. package/dist/server/spread.js +1 -1
  212. package/dist/server/spread.js.map +1 -1
  213. package/dist/server/template.js +1 -1
  214. package/dist/server/template.js.map +1 -1
  215. package/dist/server/view-transition.js.map +1 -1
  216. package/dist/server-dev/attributes.js +27 -49
  217. package/dist/server-dev/attributes.js.map +1 -1
  218. package/dist/server-dev/class-style.js +64 -47
  219. package/dist/server-dev/class-style.js.map +1 -1
  220. package/dist/server-dev/control-flow/dynamic.js +22 -10
  221. package/dist/server-dev/control-flow/dynamic.js.map +1 -1
  222. package/dist/server-dev/control-flow/error-boundary.js +2 -2
  223. package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
  224. package/dist/server-dev/control-flow/portal.js +17 -13
  225. package/dist/server-dev/control-flow/portal.js.map +1 -1
  226. package/dist/server-dev/control-flow/suspense-list.js +2 -2
  227. package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
  228. package/dist/server-dev/control-flow/suspense.js +2 -2
  229. package/dist/server-dev/control-flow/suspense.js.map +1 -1
  230. package/dist/server-dev/element.js +3 -1
  231. package/dist/server-dev/element.js.map +1 -1
  232. package/dist/server-dev/events.js +15 -44
  233. package/dist/server-dev/events.js.map +1 -1
  234. package/dist/server-dev/extend.js +2 -2
  235. package/dist/server-dev/insert.js +84 -45
  236. package/dist/server-dev/insert.js.map +1 -1
  237. package/dist/server-dev/internal/accessor.js +56 -0
  238. package/dist/server-dev/internal/accessor.js.map +1 -0
  239. package/dist/server-dev/internal/claim.js +18 -3
  240. package/dist/server-dev/internal/claim.js.map +1 -1
  241. package/dist/server-dev/internal/css-units.js +2 -2
  242. package/dist/server-dev/internal/css-units.js.map +1 -1
  243. package/dist/server-dev/internal/diagnostics.js +14 -4
  244. package/dist/server-dev/internal/diagnostics.js.map +1 -1
  245. package/dist/server-dev/internal/early-events.js +20 -2
  246. package/dist/server-dev/internal/early-events.js.map +1 -1
  247. package/dist/server-dev/internal/portal-context.js.map +1 -1
  248. package/dist/server-dev/internal/react-names.js +45 -71
  249. package/dist/server-dev/internal/react-names.js.map +1 -1
  250. package/dist/server-dev/internal/reconcile.js +7 -12
  251. package/dist/server-dev/internal/reconcile.js.map +1 -1
  252. package/dist/server-dev/resource-hints.js +4 -2
  253. package/dist/server-dev/resource-hints.js.map +1 -1
  254. package/dist/server-dev/select-value.js +5 -15
  255. package/dist/server-dev/select-value.js.map +1 -1
  256. package/dist/server-dev/server/attributes.js +6 -32
  257. package/dist/server-dev/server/attributes.js.map +1 -1
  258. package/dist/server-dev/server/element.js +10 -7
  259. package/dist/server-dev/server/element.js.map +1 -1
  260. package/dist/server-dev/server/errors.js +7 -1
  261. package/dist/server-dev/server/errors.js.map +1 -1
  262. package/dist/server-dev/server/escape.js +14 -6
  263. package/dist/server-dev/server/escape.js.map +1 -1
  264. package/dist/server-dev/server/form-controls.js +5 -2
  265. package/dist/server-dev/server/form-controls.js.map +1 -1
  266. package/dist/server-dev/server/index.js +3 -2
  267. package/dist/server-dev/server/portals.js +3 -0
  268. package/dist/server-dev/server/portals.js.map +1 -1
  269. package/dist/server-dev/server/raw-text.js +86 -0
  270. package/dist/server-dev/server/raw-text.js.map +1 -0
  271. package/dist/server-dev/server/render.js +3 -3
  272. package/dist/server-dev/server/render.js.map +1 -1
  273. package/dist/server-dev/server/stream.js +3 -3
  274. package/dist/server-dev/server/stream.js.map +1 -1
  275. package/dist/server-dev/server.js +3 -2
  276. package/dist/server-dev/spread.js +42 -80
  277. package/dist/server-dev/spread.js.map +1 -1
  278. package/dist/server-dev/template.js +1 -3
  279. package/dist/server-dev/template.js.map +1 -1
  280. package/dist/server-dev/view-transition.js.map +1 -1
  281. package/package.json +4 -3
@@ -1,2 +1,2 @@
1
- import{childScope as e,withScope as t}from"../internal/hydration-scope.js";import{SsrError as n}from"./errors.js";import{escape as r}from"./escape.js";import{PortalContext as i}from"../internal/portal-context.js";var a=class{entries=/* @__PURE__ */ new Map;add(e,t){if(!this.entries.has(e)&&this.entries.size>=256)throw new n(`SSR_PORTAL_LIMIT`,`A render produced more than 256 portals; close some overlays or raise the limit.`);this.entries.set(e,t)}clear(){this.entries.clear()}html(){let e=``;for(let[t,n]of this.entries)e+=`<!--portal:${t}-->${n}<!--/portal:${t}-->`;return e}};const o=/* @__PURE__ */ new WeakMap;function s(){let e=new a,t={html:()=>e.html()};return o.set(t,e),t}function c(e){let t=o.get(e);if(t===void 0)throw TypeError(`portals must be created with createServerPortals().`);return t}function l(n,i,a){if(a===null||n===void 0)return;let o=t(e(n),()=>r(i()));a.add(n,o)}function u(e,t){return i({value:e,get children(){return t()}})()}function d(e){if(e===void 0)return null;let t=c(e);return t.clear(),t}export{a as PortalCollector,c as collectorOf,s as createServerPortals,d as portalCollectorFor,l as renderServerPortal,u as withPortalSink};
1
+ import{childScope as e,withScope as t}from"../internal/hydration-scope.js";import{SsrError as n}from"./errors.js";import{escape as r}from"./escape.js";import{PortalContext as i}from"../internal/portal-context.js";var a=class{entries=/* @__PURE__ */ new Map;add(e,t){if(!this.entries.has(e)&&this.entries.size>=256)throw new n(`SSR_PORTAL_LIMIT`,`A render produced more than 256 portals; close some overlays or raise the limit.`);this.entries.set(e,t)}clear(){this.entries.clear()}render(e,t){l(e,t,this)}html(){let e=``;for(let[t,n]of this.entries)e+=`<!--portal:${t}-->${n}<!--/portal:${t}-->`;return e}};const o=/* @__PURE__ */ new WeakMap;function s(){let e=new a,t={html:()=>e.html()};return o.set(t,e),t}function c(e){let t=o.get(e);if(t===void 0)throw TypeError(`portals must be created with createServerPortals().`);return t}function l(n,i,a){if(a===null||n===void 0)return;let o=t(e(n),()=>r(i()));a.add(n,o)}function u(e,t){return i({value:e,get children(){return t()}})()}function d(e){if(e===void 0)return null;let t=c(e);return t.clear(),t}export{a as PortalCollector,c as collectorOf,s as createServerPortals,d as portalCollectorFor,l as renderServerPortal,u as withPortalSink};
2
2
  //# sourceMappingURL=portals.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"portals.js","names":["PortalCollector","key","SsrError","html","out","collectors","createServerPortals","collector","portals","collectorOf","renderServerPortal","sink","withScope","childScope","escape","children","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 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,MAAe,CACb,IAAIC,EAAM,GACV,IAAK,GAAM,CAACH,EAAKE,KAAS,KAAK,QAC7B,GAAO,cAAcF,EAAI,KAAKE,EAAK,cAAcF,EAAI,KAEvD,OAAOG,CACT,CACF,EAEA,MAAMC,kBAAa,IAAI,QAmBvB,SAAgBC,GAAqC,CACnD,IAAMC,EAAY,IAAIP,EAChBQ,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,SAAgBG,EACd,EACA,EACA,EACM,CACN,GAAIC,IAAS,MAAQV,IAAQ,IAAA,GAAW,OACxC,IAAME,EAAOS,EAAUC,EAAWZ,CAAG,MAASa,EAAOC,EAAS,CAAC,CAAC,EAChEJ,EAAK,IAAIV,EAAKE,CAAI,CACpB,CAOA,SAAgBa,EAAkB,EAAyB,EAAmB,CAO5E,OANaC,EAAc,CACzB,MAAON,EACP,IAAI,UAAW,CACb,OAAOO,EAAM,CACf,CACF,CACW,CAAC,CAAa,CAC3B,CAOA,SAAgBC,EAAmB,EAA4D,CAC7F,GAAIX,IAAY,IAAA,GAAW,OAAO,KAClC,IAAMD,EAAYE,EAAYD,CAAO,EAErC,OADAD,EAAU,MAAM,EACTA,CACT,C"}
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"}
@@ -0,0 +1,2 @@
1
+ import{invalid as e}from"./errors.js";import{SsrNode as t,isSsrNode as n}from"./node.js";import{render as r,resolveValue as i}from"./escape.js";const a=/* @__PURE__ */ new Set([`script`,`style`]),o={script:/<\/(script)|<!--/gi,style:/<\/(style)/gi};function s(e,t){return t.replace(o[e],e=>e===`<!--`?`<\\u0021--`:`<\\/${e.slice(2)}`)}function c(e,t){return s(e.toLowerCase()===`script`?`script`:`style`,r(t,e=>e))}function l(e,t){let r=i(t);return n(r)?r.t:c(e,r)}function u(n,r){if(typeof n!=`string`||!a.has(n.toLowerCase()))throw e(`INVALID_RAW_TEXT_TAG`,`ssrRawText(): the tag must be script or style.`);return new t(c(n,r))}export{l as rawElementContent,c as rawTextContent,u as ssrRawText};
2
+ //# sourceMappingURL=raw-text.js.map
@@ -0,0 +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,2 +1,2 @@
1
- import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{SsrError as r}from"./errors.js";import{escape as i}from"./escape.js";import{attachRootErrors as a}from"../control-flow/root-errors.js";import{portalCollectorFor as o,withPortalSink as s}from"./portals.js";import{runWithServerHead as c}from"../head/server-head.js";import{ResourceCacheContext as l,createRoot as u}from"@shadow-js/core";const d=/^[A-Za-z0-9_-]+$/;function f(e){if(typeof e!=`string`||!d.test(e))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);return e}function p(e){return{...e?.onCaughtError===void 0?{}:{onCaughtError:e.onCaughtError},...e?.onUncaughtError===void 0?{}:{onUncaughtError:e.onUncaughtError}}}function m(t,r,o,u,d,f){return a(f),s(d,()=>l({value:o,get children(){return c(u,()=>n(e(r),()=>i(t())))}}))()}function h(e,t){let n=f(t?.renderId??`0`),r=o(t?.portals),i=p(t);return u(a=>{try{return m(e,n,null,t?.head,r,i)}finally{a()}})}function g(e,n,r,i,a,o){let s=/* @__PURE__ */ new Set,c=[],l={caught:[],uncaught:[]},d={onCaughtError:e=>{l.caught.push(e)},...o.onUncaughtError===void 0?{}:{onUncaughtError:e=>{l.uncaught.push(e)}}},f=/* @__PURE__ */ new Set,p={key:e=>{let n=t(e);return s.add(n),n},read:e=>r.has(e)?{value:r.get(e)}:void 0,track:(e,t)=>{f.has(e)||(f.add(e),c.push({key:e,promise:t}))}};return u(t=>(i?.clear(),a?.clear(),{html:m(e,n,p,i,a,d),requested:s,tracked:c,errors:l,dispose:t}))}function _(e,t){for(let n of e.caught)t.onCaughtError?.(n);for(let n of e.uncaught)t.onUncaughtError?.(n)}function v(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function y(e,t){let n={};for(let r of e)t.has(r)&&v(n,r,t.get(r));return n}function b(e){if(e.canceled)throw new r(`SSR_TIMEOUT`,`The render was canceled after its time budget.`)}async function x(e,t,n,i,a,o,s){let c=/* @__PURE__ */ new Map;for(let l=1;;l+=1){b(i);let u=g(e,t,c,a,o,s);if(i.roots.push(u.dispose),u.tracked.length===0)return u.dispose(),_(u.errors,s),{html:u.html,data:y(u.requested,c)};let d=await Promise.allSettled(u.tracked.map(e=>e.promise));b(i);let f=!1;if(d.forEach((e,t)=>{let n=u.tracked[t];n!==void 0&&e.status===`fulfilled`&&(c.has(n.key)||(f=!0),c.set(n.key,e.value))}),u.dispose(),!f)return _(u.errors,s),{html:u.html,data:y(u.requested,c)};if(l>=n)throw new r(`SSR_BOUNDARY_WATERFALL`,`Resources kept loading new resources after ${n} passes; raise maxPasses or flatten the data flow.`)}}function S(e){let t=e?.timeoutMs??1e4,n=e?.maxPasses??10;if(typeof t!=`number`||!(t>0)||!Number.isFinite(t))throw TypeError(`render options: timeoutMs must be a positive finite number.`);if(!Number.isInteger(n)||n<1)throw TypeError(`render options: maxPasses must be an integer of at least 1.`);return{timeoutMs:t,maxPasses:n}}async function C(e,t){let n=f(t?.renderId??`0`),{timeoutMs:i,maxPasses:a}=S(t),s={canceled:!1,roots:[]},c,l=new Promise((e,t)=>{c=setTimeout(()=>{s.canceled=!0,t(new r(`SSR_TIMEOUT`,`The render did not finish within ${i} ms.`))},i)});try{let r=o(t?.portals);return await Promise.race([x(e,n,a,s,t?.head,r,p(t)),l])}finally{clearTimeout(c),s.canceled=!0;for(let e of s.roots.splice(0))e()}}export{h as renderToString,C as renderToStringAsync};
1
+ import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as r,SsrError as i}from"./errors.js";import{escape as a}from"./escape.js";import{attachRootErrors as o}from"../control-flow/root-errors.js";import{runWithServerHead as s}from"../head/server-head.js";import{portalCollectorFor as c,withPortalSink as l}from"./portals.js";import{ResourceCacheContext as u,createRoot as d}from"@shadow-js/core";const f=/^[A-Za-z0-9_-]+$/;function p(e){if(typeof e!=`string`||!f.test(e))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);return e}function m(e){return{...e?.onCaughtError===void 0?{}:{onCaughtError:e.onCaughtError},...e?.onUncaughtError===void 0?{}:{onUncaughtError:e.onUncaughtError}}}function h(t,r,i,c,d,f){return o(f),l(d,()=>u({value:i,get children(){return s(c,()=>n(e(r),()=>a(t())))}}))()}function g(e,t){let n=p(t?.renderId??`0`),r=c(t?.portals),i=m(t);return d(a=>{try{return h(e,n,null,t?.head,r,i)}finally{a()}})}function _(e,n,r,i,a,o){let s=/* @__PURE__ */ new Set,c=[],l={caught:[],uncaught:[]},u={onCaughtError:e=>{l.caught.push(e)},...o.onUncaughtError===void 0?{}:{onUncaughtError:e=>{l.uncaught.push(e)}}},f=/* @__PURE__ */ new Set,p={key:e=>{let n=t(e);return s.add(n),n},read:e=>r.has(e)?{value:r.get(e)}:void 0,track:(e,t)=>{f.has(e)||(f.add(e),c.push({key:e,promise:t}))}};return d(t=>(i?.clear(),a?.clear(),{html:h(e,n,p,i,a,u),requested:s,tracked:c,errors:l,dispose:t}))}function v(e,t){for(let n of e.caught)t.onCaughtError?.(n);for(let n of e.uncaught)t.onUncaughtError?.(n)}function y(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function b(e,t){let n={};for(let r of e)t.has(r)&&y(n,r,t.get(r));return n}function x(e){if(e.canceled)throw new i(`SSR_TIMEOUT`,`The render was canceled after its time budget.`)}async function S(e,t,n,r,a,o,s){let c=/* @__PURE__ */ new Map;for(let l=1;;l+=1){x(r);let u=_(e,t,c,a,o,s);if(r.roots.push(u.dispose),u.tracked.length===0)return u.dispose(),v(u.errors,s),{html:u.html,data:b(u.requested,c)};let d=await Promise.allSettled(u.tracked.map(e=>e.promise));x(r);let f=!1;if(d.forEach((e,t)=>{let n=u.tracked[t];n!==void 0&&e.status===`fulfilled`&&(c.has(n.key)||(f=!0),c.set(n.key,e.value))}),u.dispose(),!f)return v(u.errors,s),{html:u.html,data:b(u.requested,c)};if(l>=n)throw new i(`SSR_BOUNDARY_WATERFALL`,`Resources kept loading new resources after ${n} passes; raise maxPasses or flatten the data flow.`)}}function C(e){let t=e?.timeoutMs??1e4,n=e?.maxPasses??10;if(typeof t!=`number`||!(t>0)||!Number.isFinite(t))throw TypeError(`render options: timeoutMs must be a positive finite number.`);if(!Number.isInteger(n)||n<1)throw TypeError(`render options: maxPasses must be an integer of at least 1.`);return{timeoutMs:t,maxPasses:n}}async function w(e,t){let n=p(t?.renderId??`0`),{timeoutMs:a,maxPasses:o}=C(t),s={canceled:!1,roots:[]},l,u=new Promise((e,t)=>{l=setTimeout(()=>{s.canceled=!0,t(new i(`SSR_TIMEOUT`,`The render did not finish within ${a} ms.`))},Math.min(a,r))});try{let r=c(t?.portals);return await Promise.race([S(e,n,o,s,t?.head,r,m(t)),u])}finally{clearTimeout(l),s.canceled=!0;for(let e of s.roots.splice(0))e()}}export{g as renderToString,w as renderToStringAsync};
2
2
  //# sourceMappingURL=render.js.map
@@ -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"],"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 { 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.\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 job.canceled = true;\n reject(new SsrError(\"SSR_TIMEOUT\", `The render did not finish within ${timeoutMs} ms.`));\n }, timeoutMs);\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,ubAuFA,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,CAAC,EAAI,CAAE,cAAeA,EAAQ,aAAc,EACvF,GAAIA,GAAS,kBAAoB,IAAA,GAAY,CAAC,EAAI,CAAE,gBAAiBA,EAAQ,eAAgB,CAC/F,CACF,CAOA,SAASC,EACP,EACA,EACA,EACA,EACA,EACA,EACQ,CAGR,OAFAC,EAAiBC,CAAS,EAGxBC,EAAeC,MACbC,EAAqB,CACnB,MAAOC,EACP,IAAI,UAAW,CACb,OAAOC,EAAkBC,MACvBC,EAAUC,EAAgBb,CAAQ,MAASc,EAAOC,EAAK,CAAC,CAAC,CAC3D,CACF,CACF,CAAC,CACH,CAAC,CACD,CACJ,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,EAAGlB,EAAQ,CACrD,CACF,C"}
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,CAAC,EAAI,CAAE,cAAeA,EAAQ,aAAc,EACvF,GAAIA,GAAS,kBAAoB,IAAA,GAAY,CAAC,EAAI,CAAE,gBAAiBA,EAAQ,eAAgB,CAC/F,CACF,CAOA,SAASC,EACP,EACA,EACA,EACA,EACA,EACA,EACQ,CAGR,OAFAC,EAAiBC,CAAS,EAGxBC,EAAeC,MACbC,EAAqB,CACnB,MAAOC,EACP,IAAI,UAAW,CACb,OAAOC,EAAkBC,MACvBC,EAAUC,EAAgBb,CAAQ,MAASc,EAAOC,EAAK,CAAC,CAAC,CAC3D,CACF,CACF,CAAC,CACH,CAAC,CACD,CACJ,CA0BA,SAAgBC,EAAe,EAAqB,EAAiC,CACnF,IAAMhB,EAAWD,EAAcG,GAAS,UAAY,GAAG,EACjDK,EAAUU,E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withScope as n}from"../internal/hydration-scope.js";import{SsrError as r}from"./errors.js";import{escape as i}from"./escape.js";import{StreamContext as a}from"../internal/stream-context.js";import{attachRootErrors as o}from"../control-flow/root-errors.js";import{portalCollectorFor as s,withPortalSink as c}from"./portals.js";import{runWithServerHead as l}from"../head/server-head.js";import{serialize as u}from"./serialize.js";import{ResourceCacheContext as d,createRoot as f,untrack as p}from"@shadow-js/core";const m=/^[A-Za-z0-9_-]+$/;function h(e,t){return`<script${t===void 0?``:` nonce="${t.replace(/[^A-Za-z0-9+/=_-]/g,``)}"`}>${e}<\/script>`}function g(g,_={}){let v=_.renderId??`0`;if(typeof v!=`string`||!m.test(v))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);let y=_.timeoutMs??3e4;if(typeof y!=`number`||!(y>0)||!Number.isFinite(y))throw TypeError(`render options: timeoutMs must be a positive finite number.`);let b=_.signal,x=s(_.portals),S=new TextEncoder,C=[],w=()=>{let e=[];for(let t of C.splice(0))try{t.dispose()}catch(t){e.push(t)}if(e.length>0)throw e.length===1?e[0]:AggregateError(e,`Stream cleanup failed.`)},T=!1,E,D=()=>void 0;return new ReadableStream({async start(s){let m=/* @__PURE__ */ new Map,O=/* @__PURE__ */ new Map,k=e=>{if(b?.aborted)throw b.reason;T||s.enqueue(S.encode(e))},A=()=>{let r={html:``,boundaries:[],requested:/* @__PURE__ */ new Set,held:[],inFlight:/* @__PURE__ */ new Set,caught:[],uncaught:[],answered:!1,dispose:()=>void 0};C.push(r);let s={key:e=>{let n=t(e);return r.requested.add(n),n},read:e=>m.has(e)?{value:m.get(e)}:void 0,track:(e,t,n)=>{O.set(e,t);let i=t.then(t=>{m.set(e,t)},()=>void 0);r.inFlight.add(i),i.finally(()=>r.inFlight.delete(i)),n?.deferStream===!0&&r.held.push({key:e,entry:i})},pending:e=>O.get(e)},u={defer:e=>{r.boundaries.push(e)}},p={onCaughtError:e=>{r.answered?_.onCaughtError?.(e):r.caught.push(e)},..._.onUncaughtError===void 0?{}:{onUncaughtError:e=>{r.answered?_.onUncaughtError?.(e):r.uncaught.push(e)}}};return _.head?.clear(),x?.clear(),r.html=f(t=>(r.dispose=t,o(p),a({value:u,get children(){return c(x,()=>d({value:s,get children(){return l(_.head,()=>n(e(v),()=>i(g())))}}))}})()())),r},j=()=>void 0,M=new Promise((e,t)=>{j=t,E=setTimeout(()=>t(new r(`SSR_TIMEOUT`,`The stream did not finish within ${y} ms.`)),y)}),N=()=>j(b?.reason??/* @__PURE__ */ Error(`The render was aborted.`));b?.addEventListener(`abort`,N,{once:!0});let P=()=>{clearTimeout(E),b?.removeEventListener(`abort`,N),w()};D=e=>{j(e),P()},M.catch(()=>void 0);try{if(b?.aborted)throw b.reason;let e=A();for(let t=1;e.held.length>0&&(await Promise.race([M,Promise.allSettled(e.held.map(e=>e.entry))]),e.held.some(e=>m.has(e.key)));t+=1){if(t>=10)throw new r(`SSR_BOUNDARY_WATERFALL`,`Resources kept holding the stream after 10 shell renders; flatten the data flow.`);e=A()}e.answered=!0,p(()=>{for(let t of e.caught)_.onCaughtError?.(t);for(let t of e.uncaught)_.onUncaughtError?.(t);_.onShellReady?.(e.html)}),k(e.boundaries.length>0?e.html+h(`window.$S=function(i,f){var t=document.getElementById("s:"+i);if(!t)return;if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){if(c.data==="[b:"+i){var d=1,n=c.nextSibling,e=null;while(n){if(n.nodeType===8){if(n.data.charAt(0)==="["){d++}else if(n.data==="]"){d--;if(d===0){e=n;break}}}n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};`,_.nonce):e.html);let t=()=>{for(let t of e.boundaries.splice(0))k(`<template id="s:${t.id}"></template>`+h(`$S(${JSON.stringify(t.id)},1)`,_.nonce))},n=0;for(;e.boundaries.length>0;){if(e.inFlight.size===0){t();break}let r=m.size;await Promise.race([M,Promise.race([...e.inFlight])]);let i=e.boundaries;e.boundaries=[];let a=!1;for(let e of i){let t=e.rebuild();t!==null&&(a=!0,k(`<template id="s:${e.id}">${t}</template>`+h(`$S(${JSON.stringify(e.id)})`,_.nonce)))}n=m.size===r&&!a?n+1:0,e.boundaries.length>0&&n>=2&&t()}let i={};for(let t of e.requested)m.has(t)&&Object.defineProperty(i,t,{value:m.get(t),enumerable:!0,writable:!0,configurable:!0});Object.keys(i).length>0&&k(`<script type="application/json" data-sh="${v}">${u(i)}<\/script>`),P(),T||s.close()}catch(e){P(),T||s.error(e)}},cancel(e){T=!0,D(e)}})}export{g as renderToStream};
1
+ import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as r,SsrError as i}from"./errors.js";import{escape as a}from"./escape.js";import{StreamContext as o}from"../internal/stream-context.js";import{attachRootErrors as s}from"../control-flow/root-errors.js";import{runWithServerHead as c}from"../head/server-head.js";import{portalCollectorFor as l,withPortalSink as u}from"./portals.js";import{serialize as d}from"./serialize.js";import{ResourceCacheContext as f,createRoot as p,untrack as m}from"@shadow-js/core";const h=/^[A-Za-z0-9_-]+$/;function g(e,t){return`<script${t===void 0?``:` nonce="${t.replace(/[^A-Za-z0-9+/=_-]/g,``)}"`}>${e}<\/script>`}function _(_,v={}){let y=v.renderId??`0`;if(typeof y!=`string`||!h.test(y))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);let b=v.timeoutMs??3e4;if(typeof b!=`number`||!(b>0)||!Number.isFinite(b))throw TypeError(`render options: timeoutMs must be a positive finite number.`);let x=v.signal,S=l(v.portals),C=new TextEncoder,w=[],T=()=>{let e=[];for(let t of w.splice(0))try{t.dispose()}catch(t){e.push(t)}if(e.length>0)throw e.length===1?e[0]:AggregateError(e,`Stream cleanup failed.`)},E=!1,D,O=()=>void 0;return new ReadableStream({async start(l){let h=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=e=>{if(x?.aborted)throw x.reason;E||l.enqueue(C.encode(e))},j=()=>{let r={html:``,boundaries:[],requested:/* @__PURE__ */ new Set,held:[],inFlight:/* @__PURE__ */ new Set,caught:[],uncaught:[],answered:!1,dispose:()=>void 0};w.push(r);let i={key:e=>{let n=t(e);return r.requested.add(n),n},read:e=>h.has(e)?{value:h.get(e)}:void 0,track:(e,t,n)=>{k.set(e,t);let i=t.then(t=>{h.set(e,t)},()=>void 0);r.inFlight.add(i),i.finally(()=>r.inFlight.delete(i)),n?.deferStream===!0&&r.held.push({key:e,entry:i})},pending:e=>k.get(e)},l={defer:e=>{r.boundaries.push(e)}},d={onCaughtError:e=>{r.answered?v.onCaughtError?.(e):r.caught.push(e)},...v.onUncaughtError===void 0?{}:{onUncaughtError:e=>{r.answered?v.onUncaughtError?.(e):r.uncaught.push(e)}}};return v.head?.clear(),S?.clear(),r.html=p(t=>(r.dispose=t,s(d),o({value:l,get children(){return u(S,()=>f({value:i,get children(){return c(v.head,()=>n(e(y),()=>a(_())))}}))}})()())),r},M=()=>void 0,N=new Promise((e,t)=>{M=t,D=setTimeout(()=>t(new i(`SSR_TIMEOUT`,`The stream did not finish within ${b} ms.`)),Math.min(b,r))}),P=()=>M(x?.reason??/* @__PURE__ */ Error(`The render was aborted.`));x?.addEventListener(`abort`,P,{once:!0});let F=()=>{clearTimeout(D),x?.removeEventListener(`abort`,P),T()};O=e=>{M(e),F()},N.catch(()=>void 0);try{if(x?.aborted)throw x.reason;let e=j();for(let t=1;e.held.length>0&&(await Promise.race([N,Promise.allSettled(e.held.map(e=>e.entry))]),e.held.some(e=>h.has(e.key)));t+=1){if(t>=10)throw new i(`SSR_BOUNDARY_WATERFALL`,`Resources kept holding the stream after 10 shell renders; flatten the data flow.`);e=j()}e.answered=!0,m(()=>{for(let t of e.caught)v.onCaughtError?.(t);for(let t of e.uncaught)v.onUncaughtError?.(t);v.onShellReady?.(e.html)}),A(e.boundaries.length>0?e.html+g(`window.$S=function(i,f){var t=document.getElementById("s:"+i);if(!t)return;if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){if(c.data==="[b:"+i){var d=1,n=c.nextSibling,e=null;while(n){if(n.nodeType===8){if(n.data.charAt(0)==="["){d++}else if(n.data==="]"){d--;if(d===0){e=n;break}}}n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};`,v.nonce):e.html);let t=()=>{for(let t of e.boundaries.splice(0))A(`<template id="s:${t.id}"></template>`+g(`$S(${JSON.stringify(t.id)},1)`,v.nonce))},n=0;for(;e.boundaries.length>0;){if(e.inFlight.size===0){t();break}let r=h.size;await Promise.race([N,Promise.race([...e.inFlight])]);let i=e.boundaries;e.boundaries=[];let a=!1;for(let e of i){let t=e.rebuild();t!==null&&(a=!0,A(`<template id="s:${e.id}">${t}</template>`+g(`$S(${JSON.stringify(e.id)})`,v.nonce)))}n=h.size===r&&!a?n+1:0,e.boundaries.length>0&&n>=2&&t()}let r={};for(let t of e.requested)h.has(t)&&Object.defineProperty(r,t,{value:h.get(t),enumerable:!0,writable:!0,configurable:!0});Object.keys(r).length>0&&A(`<script type="application/json" data-sh="${y}">${d(r)}<\/script>`),F(),E||l.close()}catch(e){F(),E||l.error(e)}},cancel(e){E=!0,O(e)}})}export{_ as renderToStream};
2
2
  //# sourceMappingURL=stream.js.map
@@ -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","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 { 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. 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 timeoutMs,\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,6iBA6EA,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,GAAI,OAAOD,GAAa,UAAY,CAACL,EAAU,KAAKK,CAAQ,EAC1D,MAAU,UAAU,oEAAoE,EAE1F,IAAME,EAAYD,EAAQ,WAAa,IACvC,GAAI,OAAOC,GAAc,UAAY,EAAEA,EAAY,IAAM,CAAC,OAAO,SAASA,CAAS,EACjF,MAAU,UAAU,6DAA6D,EAEnF,IAAMC,EAASF,EAAQ,OACjBG,EAAUC,EAAmBJ,EAAQ,OAAO,EAC5CK,EAAU,IAAI,YAEdC,EAAsB,CAAC,EACvBC,MAAyB,CAC7B,IAAMC,EAAoB,CAAC,EAC3B,IAAK,IAAMC,KAAQH,EAAO,OAAO,CAAC,EAChC,GAAI,CACFG,EAAK,QAAQ,CACf,OAASC,EAAO,CACdF,EAAO,KAAKE,CAAK,CACnB,CAEF,GAAIF,EAAO,OAAS,EAClB,MAAMA,EAAO,SAAW,EAAIA,EAAO,GAAS,eAAeA,EAAQ,wBAAwB,CAC/F,EACIG,EAAW,GAEXC,EACAC,MAAgD,IAAA,GAEpD,OAAO,IAAI,eAA2B,CACpC,MAAM,MAAM,EAAY,CACtB,IAAMC,kBAAU,IAAI,IAEdC,kBAAW,IAAI,IACfC,EAAQ,GAAuB,CACnC,GAAId,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KK,GAAW,GAAGD,EAAc,CAClE,CAEA,IAAMM,EAAgC,CAAC,EACvC,IAAK,IAAMtC,KAAO4B,EAAO,UAClBnC,EAAQ,IAAIO,CAAG,GACpB,OAAO,eAAesC,EAAMtC,EAAK,CAC/B,MAAOP,EAAQ,IAAIO,CAAG,EACtB,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EAEC,OAAO,KAAKsC,CAAI,CAAC,CAAC,OAAS,GAC7B3C,EAAK,4CAA4CjB,EAAS,IAAI6D,EAAUD,CAAI,EAAE,WAAU,EAE1FZ,EAAQ,EACHpC,GAAUM,EAAW,MAAM,CAClC,OAASP,EAAO,CACdqC,EAAQ,EACHpC,GAAUM,EAAW,MAAMP,CAAK,CACvC,CACF,EACA,OAAO,EAAQ,CACb,EAAW,GACXG,EAAamC,CAAM,CACrB,CACF,CAAC,CACH,C"}
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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AAIO,CAAG,EACtB,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EAEC,OAAO,KAAKuC,CAAI,CAAC,CAAC,OAAS,GAC7B5C,EAAK,4CAA4CjB,EAAS,IAAI8D,EAAUD,CAAI,EAAE,WAAU,EAE1FZ,EAAQ,EACHrC,GAAUM,EAAW,MAAM,CAClC,OAASP,EAAO,CACdsC,EAAQ,EACHrC,GAAUM,EAAW,MAAMP,CAAK,CACvC,CACF,EACA,OAAO,EAAQ,CACb,EAAW,GACXG,EAAaoC,CAAM,CACrB,CACF,CAAC,CACH,C"}
@@ -1 +1 @@
1
- import{escape as e}from"./server/escape.js";import{ssrAttribute as t}from"./server/attributes.js";import{ssrClass as n,ssrStyle as r}from"./server/class-style.js";import{ssrSelectValue as i,ssrTextArea as a}from"./server/form-controls.js";import{ssr as o,ssrElement as s,ssrHydrationKey as c,ssrRaw as l}from"./server/element.js";import{createServerPortals as u}from"./server/portals.js";import{normalizeTags as d}from"./head/validate.js";import{createServerHead as f}from"./head/server-head.js";import{createComponent as p,memo as m}from"./server/component.js";import{derived as h}from"./server/derived.js";import{HydrationScript as g,generateHydrationScript as _}from"./server/hydration-script.js";import{renderToString as v,renderToStringAsync as y}from"./server/render.js";import{deserialize as b,serialize as x}from"./server/serialize.js";import{renderToStream as S}from"./server/stream.js";import{mergeProps as C}from"./server/index.js";export{g as HydrationScript,p as createComponent,f as createServerHead,u as createServerPortals,h as derived,b as deserialize,e as escape,_ as generateHydrationScript,m as memo,C as mergeProps,d as normalizeTags,S as renderToStream,v as renderToString,y as renderToStringAsync,x as serialize,o as ssr,t as ssrAttribute,n as ssrClass,s as ssrElement,c as ssrHydrationKey,l as ssrRaw,i as ssrSelectValue,r as ssrStyle,a as ssrTextArea};
1
+ import{escape as e}from"./server/escape.js";import{ssrAttribute as t}from"./server/attributes.js";import{ssrClass as n,ssrStyle as r}from"./server/class-style.js";import{ssrSelectValue as i,ssrTextArea as a}from"./server/form-controls.js";import{ssrRawText as o}from"./server/raw-text.js";import{ssr as s,ssrElement as c,ssrHydrationKey as l,ssrRaw as u}from"./server/element.js";import{normalizeTags as d}from"./head/validate.js";import{createServerHead as f}from"./head/server-head.js";import{createComponent as p,memo as m}from"./server/component.js";import{derived as h}from"./server/derived.js";import{HydrationScript as g,generateHydrationScript as _}from"./server/hydration-script.js";import{createServerPortals as v}from"./server/portals.js";import{renderToString as y,renderToStringAsync as b}from"./server/render.js";import{deserialize as x,serialize as S}from"./server/serialize.js";import{renderToStream as C}from"./server/stream.js";import{mergeProps as w}from"./server/index.js";export{g as HydrationScript,p as createComponent,f as createServerHead,v as createServerPortals,h as derived,x as deserialize,e as escape,_ as generateHydrationScript,m as memo,w as mergeProps,d as normalizeTags,C as renderToStream,y as renderToString,b as renderToStringAsync,S as serialize,s as ssr,t as ssrAttribute,n as ssrClass,c as ssrElement,l as ssrHydrationKey,u as ssrRaw,o as ssrRawText,i as ssrSelectValue,r as ssrStyle,a as ssrTextArea};
@@ -1,2 +1,2 @@
1
- import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,classList as a,style as o}from"./class-style.js";import{claims as s}from"./internal/hydration-hooks.js";import{bindRegion as c,createRegion as l}from"./insert.js";import{IGNORED_KEYS as u,attributeName as d,eventPlan as f}from"./internal/react-names.js";import{bindEvent as p}from"./events.js";import{selectShows as m,setSelectValue as h}from"./select-value.js";import{onCleanup as g,untrack as _,useRenderEffect as v}from"@shadow-js/core";function y(e){return typeof e!=`object`||!e?``:w(Reflect.get(e,`__html`))}const b=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]);function x(e){return e.length>2&&e.startsWith(`on`)}function S(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function C(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}function w(e){return e==null?``:String(e)}function T(e,t){let n=[];if(typeof e!=`object`||!e)return n;let r,i=!1;for(let a of Object.keys(e))b.has(S(a))||u.has(a)||(a===`children`?t&&(r=Reflect.get(e,a),i=!0):n.push([a,Reflect.get(e,a)]));return i&&!n.some(([e])=>e===`value`)&&n.push([`value`,r]),n}function E(e){let t=e.refCleanup;t!==void 0&&(e.refCleanup=void 0,_(t))}function D(e,t,n,s,c){if(t===`ref`){if(E(s),typeof n==`function`){let t=n,r=_(()=>t(e));typeof r==`function`&&(s.refCleanup=r)}}else if(t===`autoFocus`)s.autoFocused||(s.autoFocused=!0,r(e,n));else if(t===`class`||t===`className`)i(e,n,c);else if(t===`style`)s.styleValue=o(e,n,s.styleValue);else if(t===`classList`)s.classListValue=a(e,C(n),s.classListValue);else if(x(t)){s.unbinders.get(t)?.(),s.unbinders.delete(t);let r=f(t,e.localName,e.getAttribute(`type`)?.toLowerCase()??null),i=r.passive&&typeof n==`function`?{handleEvent:n,passive:!0}:n,a=p(e,r.type,i,!0,r.capture);a!==void 0&&s.unbinders.set(t,a)}else t===`innerHTML`?e.innerHTML=w(n):t===`dangerouslySetInnerHTML`?e.innerHTML=y(n):t===`textContent`?e.textContent=w(n):!c&&(t===`value`||t===`defaultValue`)&&e instanceof HTMLSelectElement?h(e,n):!c&&k.has(t)&&t in e?(j(e,t,n,c)&&Reflect.set(e,t,A.has(t)?n??``:!!n),t===`value`&&e instanceof HTMLInputElement&&(e.defaultValue=w(n))):O(e,t,n,c)}function O(r,i,a,o){if(i.startsWith(`prop:`))Reflect.set(r,i.slice(5),a);else if(i.startsWith(`attr:`))e(r,i.slice(5),a);else if(i.startsWith(`bool:`))n(r,i.slice(5),a);else{let n=d(i,o);n.startsWith(`xlink:`)?t(r,`http://www.w3.org/1999/xlink`,n,a):e(r,n,a)}}const k=/* @__PURE__ */ new Set([`value`,`checked`,`selected`,`muted`,`indeterminate`,`defaultValue`,`defaultChecked`]),A=/* @__PURE__ */ new Set([`value`,`defaultValue`]);function j(e,t,n,r){if(r||!k.has(t)||!(t in e))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!m(e,n);let i=Reflect.get(e,t);return A.has(t)?i!==w(n):i!==!!n}function M(e,t,n,r){t===`ref`?E(n):t!==`autoFocus`&&(t===`class`||t===`className`?i(e,void 0,r):t===`style`?n.styleValue=o(e,void 0,n.styleValue):t===`classList`?n.classListValue=a(e,void 0,n.classListValue):x(t)?(n.unbinders.get(t)?.(),n.unbinders.delete(t)):t===`innerHTML`||t===`dangerouslySetInnerHTML`||t===`textContent`?e.textContent=``:!r&&k.has(t)&&t in e?Reflect.set(e,t,A.has(t)?``:!1):O(e,t,void 0,r))}function N(e,t,n,r){let i=/* @__PURE__ */ new Set;for(let[a,o]of t)i.add(a),!(n.values.has(a)&&Object.is(n.values.get(a),o)&&!j(e,a,o,r))&&(n.values.set(a,o),D(e,a,o,n,r));for(let t of[...n.values.keys()])i.has(t)||(n.values.delete(t),M(e,t,n,r))}function P(e,t,n=!1,r=!1){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let i=()=>typeof t==`function`?t():t,a=e.localName===`textarea`;if(!r&&!a){let t=s.current.isClaiming()?s.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,n=l(e,null,t);c(n,()=>i()?.children)}let o={values:/* @__PURE__ */ new Map,unbinders:/* @__PURE__ */ new Map,styleValue:void 0,classListValue:void 0,refCleanup:void 0};g(()=>{for(let e of o.unbinders.values())e();o.unbinders.clear(),E(o)}),v(()=>T(i(),a),t=>{N(e,t,o,n)})}export{P as spread};
1
+ import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,asRecord as a,classList as o,style as s}from"./class-style.js";import{claims as c}from"./internal/hydration-hooks.js";import{bindRegion as l,createRegion as u,watchCommits as d}from"./insert.js";import{IGNORED_KEYS as f,attributeName as p,eventPlan as m,isFlagAttribute as h}from"./internal/react-names.js";import{bindEvent as g}from"./events.js";import{plainText as _,setSelectValue as v}from"./select-value.js";import{onCleanup as y,untrack as b,useRenderEffect as x}from"@shadow-js/core";function S(e){return typeof e!=`object`||!e?``:_(Reflect.get(e,`__html`))}const C=/^(?:__proto__|constructor|prototype)$/;function w(e){return e.length>2&&e.startsWith(`on`)}function T(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function E(e,t){let n=[];if(typeof e!=`object`||!e)return n;let r,i=!1;for(let a of Object.keys(e))C.test(T(a))||f.test(a)||(a===`children`?t&&(r=Reflect.get(e,a),i=!0):n.push([a,Reflect.get(e,a)]));return i&&!n.some(([e])=>e===`value`)&&n.push([`value`,r]),n}function D(e){let t=e.refCleanup;t!==void 0&&(e.refCleanup=void 0,b(t))}function O(e,t,n,c,l){if(t===`ref`){if(D(c),typeof n==`function`){let t=n,r=b(()=>t(e));typeof r==`function`&&(c.refCleanup=r)}}else if(t===`autoFocus`)c.autoFocused||(c.autoFocused=!0,r(e,n));else if(t===`class`||t===`className`)i(e,n,l);else if(t===`style`)c.styleValue=s(e,n,c.styleValue);else if(t===`classList`)c.classListValue=o(e,a(n),c.classListValue);else if(w(t)){c.unbinders.get(t)?.(),c.unbinders.delete(t);let r=m(t,e.localName,e.getAttribute(`type`)?.toLowerCase()??null),i=r.passive&&typeof n==`function`?{handleEvent:n,passive:!0}:n,a=g(e,r.type,i,!0,r.capture);a!==void 0&&c.unbinders.set(t,a)}else t===`innerHTML`||t===`dangerouslySetInnerHTML`?e.innerHTML=t===`innerHTML`?_(n):S(n):t===`textContent`?e.textContent=_(n):!l&&(t===`value`||t===`defaultValue`)&&e instanceof HTMLSelectElement?v(e,n):!l&&A.test(t)&&t in e?(M(e,t,n,l)&&Reflect.set(e,t,j.test(t)?n??``:!!n),t===`value`&&e instanceof HTMLInputElement&&(e.defaultValue=_(n))):k(e,t,n,l)}function k(r,i,a,o){if(i.startsWith(`prop:`))Reflect.set(r,i.slice(5),a);else if(i.startsWith(`attr:`))e(r,i.slice(5),a);else if(i.startsWith(`bool:`))n(r,i.slice(5),a);else{let s=p(i,o);h(s,a)?n(r,s,a):s.startsWith(`xlink:`)?t(r,`http://www.w3.org/1999/xlink`,s,a):e(r,s,a)}}const A=/^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/,j=/^(?:value|defaultValue)$/;function M(e,t,n,r){if(r||!A.test(t)||!(t in e))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!0;let i=Reflect.get(e,t);return j.test(t)?i!==_(n):i!==!!n}function N(e,t,n,r){let i=/* @__PURE__ */ new Set;for(let[a,o]of t)i.add(a),!(n.values.has(a)&&Object.is(n.values.get(a),o)&&!M(e,a,o,r))&&(n.values.set(a,o),O(e,a,o,n,r));for(let t of[...n.values.keys()])i.has(t)||(n.values.delete(t),O(e,t,void 0,n,r))}function P(e,t,n=!1,r=!1){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let i=()=>typeof t==`function`?t():t,a=I();if(!r&&e.localName!==`textarea`){let t=c.current.isClaiming()?c.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,r=u(e,null,t);l(r,()=>i()?.children),F(e,n,a)}R(e,i,n,a)}function F(e,t,n){!t&&e instanceof HTMLSelectElement&&d(e,()=>{let t=n.values.has(`value`)?`value`:`defaultValue`;n.values.has(t)&&v(e,n.values.get(t))})}function I(){return{values:/* @__PURE__ */ new Map,unbinders:/* @__PURE__ */ new Map,styleValue:void 0,classListValue:void 0,refCleanup:void 0}}function L(e,t,n){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let r=I();F(e,n,r),R(e,()=>typeof t==`function`?t():t,n,r)}function R(e,t,n,r){let i=e.localName===`textarea`;y(()=>{for(let e of r.unbinders.values())e();r.unbinders.clear(),D(r)}),x(()=>E(t(),i),t=>{N(e,t,r,n)})}export{P as spread,L as spreadProps};
2
2
  //# sourceMappingURL=spread.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"spread.js","names":["innerHtmlValue","value","plainText","FORBIDDEN_NAMES","isEventKey","key","nameOf","colon","asRecord","readEntries","entries","props","hasValue","IGNORED_KEYS","textarea","runRefCleanup","cleanup","state","untrack","applyKey","callRef","el","autoFocus","applyClass","svg","style","classList","plan","eventPlan","handler","unbind","bindEvent","setSelectValue","LIVE_PROPERTIES","liveDiffers","STRING_PROPERTIES","writeKey","setAttribute","setBoolAttribute","wire","attributeName","setAttributeNS","selectShows","live","clearKey","applyEntries","current","spread","read","skipChildren","initial","claims","region","createRegion","bindRegion","onCleanup","useRenderEffect","isSVG"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS } from \"./internal/react-names\";\nimport { selectShows, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. */\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Text for innerHTML and textContent: null and undefined become the empty string. */\nfunction plainText(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.has(nameOf(key)) || IGNORED_KEYS.has(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\") {\n el.innerHTML = plainText(value);\n return;\n }\n if (key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.has(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.has(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * {@link clearKey} undoes a prop.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES: ReadonlySet<string> = new Set([\n \"value\",\n \"checked\",\n \"selected\",\n \"muted\",\n \"indeterminate\",\n \"defaultValue\",\n \"defaultChecked\",\n]);\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES: ReadonlySet<string> = new Set([\"value\", \"defaultValue\"]);\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.has(key) || !(key in el)) return false;\n if (key === \"value\" && el instanceof HTMLSelectElement) return !selectShows(el, value);\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.has(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/** Undoes a prop that disappeared from the props object. */\nfunction clearKey(el: Element, key: string, state: SpreadState, svg: boolean): void {\n if (key === \"ref\") {\n runRefCleanup(state);\n return;\n }\n // A focus request is not a state: removing the prop does not unfocus the element.\n if (key === \"autoFocus\") return;\n if (key === \"class\" || key === \"className\") {\n applyClass(el, undefined, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, undefined, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, undefined, state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\" || key === \"textContent\") {\n el.textContent = \"\";\n return;\n }\n if (!svg && LIVE_PROPERTIES.has(key) && key in el) {\n Reflect.set(el, key, STRING_PROPERTIES.has(key) ? \"\" : false);\n return;\n }\n writeKey(el, key, undefined, svg);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n clearKey(el, key, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const textarea = el.localName === \"textarea\";\n if (!skipChildren && !textarea) {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n }\n const state: SpreadState = {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":"A,mlBAcA,SAASA,EAAe,EAAwB,CAE9C,OADsB,OAAOC,GAA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,EAAO,EAAa,EAAgB,EAAQ,GAAO,EAAe,GAAa,CAC7F,GAAIpC,IAAU,MAAS,OAAOA,GAAU,UAAY,OAAOA,GAAU,WAAa,OAGlF,IAAMqC,MAAuB,OAAOrC,GAAU,WAAcA,EAAwB,EAAIA,EAClFG,EAAWO,EAAG,YAAc,WAClC,GAAI,CAAC4B,GAAgB,CAACnC,EAAU,CAE9B,IAAMoC,EAAUC,EAAO,QAAQ,WAAW,EACrCA,EAAO,QAAQ,WAAW9B,EAAI,IAAI,GAAK,MAAM,KAAKA,EAAG,UAAU,EAChE,IAAA,GACE+B,EAASC,EAAahC,EAAI,KAAM6B,CAAO,EAC7CI,EAAWF,MAAeJ,EAAK,CAAC,EAA6C,QAAQ,CACvF,CACA,IAAM/B,EAAqB,CACzB,uBAAQ,IAAI,IACZ,0BAAW,IAAI,IACf,WAAY,IAAA,GACZ,eAAgB,IAAA,GAChB,WAAY,IAAA,EACd,EAEAsC,MAAgB,CACd,IAAK,IAAMzB,KAAUb,EAAM,UAAU,OAAO,EAAGa,EAAO,EACtDb,EAAM,UAAU,MAAM,EACtBF,EAAcE,CAAK,CACrB,CAAC,EACDuC,MACQ/C,EAAYuC,EAAK,EAAGlC,CAAQ,EACjC,GAAY,CACX+B,EAAaxB,EAAIX,EAASO,EAAOwC,CAAK,CACxC,CACF,CACF,C"}
1
+ {"version":3,"file":"spread.js","names":["innerHtmlValue","value","plainText","FORBIDDEN_NAMES","isEventKey","key","nameOf","colon","readEntries","entries","props","hasValue","IGNORED_KEYS","textarea","runRefCleanup","cleanup","state","untrack","applyKey","callRef","el","autoFocus","applyClass","svg","style","classList","asRecord","plan","eventPlan","handler","unbind","bindEvent","setSelectValue","LIVE_PROPERTIES","liveDiffers","STRING_PROPERTIES","writeKey","setAttribute","setBoolAttribute","wire","attributeName","isFlagAttribute","setAttributeNS","live","applyEntries","current","spread","read","newState","skipChildren","initial","claims","region","createRegion","bindRegion","followOptions","isSVG","applyProps","watchCommits","spreadProps","onCleanup","useRenderEffect"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(nameOf(key)) || IGNORED_KEYS.test(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = key === \"innerHTML\" ? plainText(value) : innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * a prop that disappeared is undone.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref cleanup\n // runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":"A,soBAcA,SAASA,EAAe,EAAwB,CAE9C,OADsB,OAAOC,GAAU,WAAnCA,EAAoD,GACjDC,EAAU,QAAQ,IAAID,EAAO,QAAQ,CAAC,CAC/C,CAGA,MAAME,EAAkB,wCAexB,SAASC,EAAW,EAAsB,CACxC,OAAOC,E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AK,EAC9ByC,EACErC,MACO,OAAOV,GAAU,WAAcA,EAAwB,EAAIA,EAClE8C,EACAxC,CACF,CACF,CAEA,SAASyC,EAAW,EAAa,EAAqB,EAAgB,EAA0B,CAC9F,IAAM5C,EAAWO,EAAG,YAAc,WAElCwC,MAAgB,CACd,IAAK,IAAM9B,KAAUd,EAAM,UAAU,OAAO,EAAGc,EAAO,EACtDd,EAAM,UAAU,MAAM,EACtBF,EAAcE,CAAK,CACrB,CAAC,EACD6C,MACQrD,EAAYuC,EAAK,EAAGlC,CAAQ,EACjC,GAAY,CACX+B,EAAaxB,EAAIX,EAASO,EAAOwC,CAAK,CACxC,CACF,CACF,C"}
@@ -1,2 +1,2 @@
1
- import{MATHML_NS as e}from"./internal/names.js";import{nextKey as t}from"./internal/hydration-scope.js";import{claims as n}from"./internal/hydration-hooks.js";function r(e,t){let n=document,r=e=>{let r=n.createElementNS(t,e.localName);for(let t of Array.from(e.attributes))r.setAttribute(t.name,t.value);return r},i=r(e),a=[[e,i]];for(;a.length>0;){let e=a.pop();if(e===void 0)break;let[t,i]=e;for(let e of Array.from(t.childNodes))if(e instanceof Element){let t=r(e);i.appendChild(t),a.push([e,t])}else e instanceof Text&&i.appendChild(n.createTextNode(e.data))}return i}function i(t,n){let i=document.createElement(`template`),a=n&1?`svg`:n&2?`math`:null;if(a===null)return i.innerHTML=t,Array.from(i.content.childNodes);i.innerHTML=`<${a}>${t}</${a}>`;let o=i.content.firstChild;return o instanceof Element?a===`math`&&o.namespaceURI!==`http://www.w3.org/1998/Math/MathML`?Array.from(r(o,e).childNodes):Array.from(o.childNodes):[]}function a(e,r=0){let a=!!(r&4),o,s=e=>a?document.importNode(e,!0):e.cloneNode(!0);return()=>{let a=n.current.claimElement(t());if(a!==null)return a;let c=o??=i(e,r);if(c.length===1){let[e]=c;if(e!==void 0)return s(e)}let l=document.createDocumentFragment();for(let e of c)l.appendChild(s(e));return l}}export{a as template};
1
+ import{MATHML_NS as e}from"./internal/names.js";import{nextKey as t}from"./internal/hydration-scope.js";import{claims as n}from"./internal/hydration-hooks.js";function r(e,t){let n=document,r=e=>{let r=n.createElementNS(t,e.localName);for(let t of Array.from(e.attributes))r.setAttribute(t.name,t.value);return r},i=r(e),a=[[e,i]];for(;a.length>0;){let[e,t]=a.pop();for(let i of Array.from(e.childNodes))if(i instanceof Element){let e=r(i);t.appendChild(e),a.push([i,e])}else i instanceof Text&&t.appendChild(n.createTextNode(i.data))}return i}function i(t,n){let i=document.createElement(`template`),a=n&1?`svg`:n&2?`math`:null;if(a===null)return i.innerHTML=t,Array.from(i.content.childNodes);i.innerHTML=`<${a}>${t}</${a}>`;let o=i.content.firstChild;return o instanceof Element?a===`math`&&o.namespaceURI!==`http://www.w3.org/1998/Math/MathML`?Array.from(r(o,e).childNodes):Array.from(o.childNodes):[]}function a(e,r=0){let a=!!(r&4),o,s=e=>a?document.importNode(e,!0):e.cloneNode(!0);return()=>{let a=n.current.claimElement(t());if(a!==null)return a;let c=o??=i(e,r);if(c.length===1){let[e]=c;if(e!==void 0)return s(e)}let l=document.createDocumentFragment();for(let e of c)l.appendChild(s(e));return l}}export{a as template};
2
2
  //# sourceMappingURL=template.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"template.js","names":["inNamespace","doc","copyOf","copy","namespace","element","attribute","root","source","stack","pair","from","to","child","parse","holder","wrapper","flags","html","MATHML_NS","template","importNode","roots","node","claimed","claims","nextKey","parsed","only","fragment"],"sources":["../../src/template.ts"],"sourcesContent":["import { checkClaimedTag } from \"./internal/claim\";\nimport { warnOnce } from \"./internal/diagnostics\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { MATHML_NS, TEMPLATE_IMPORT_NODE, TEMPLATE_MATHML, TEMPLATE_SVG } from \"./internal/names\";\n\n/** One start tag: its name, then its attribute text (group 1). */\nconst START_TAG =\n /<[a-zA-Z][^\\s/>]*((?:\\s+[^\\s\"'>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?)*)\\s*\\/?>/g;\n/** One attribute inside the attribute text of a start tag: its name (group 1). */\nconst ATTRIBUTE = /([^\\s\"'>/=]+)(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?/g;\n\n/**\n * Development check for the markup a template is parsed from. The HTML parser keeps the first of two\n * same-named attributes and drops the rest, so `class` and `className` on one element (both compiled\n * to `class`) lose one silently. Warns `DUPLICATE_CLASS_ATTRIBUTE` once; the first attribute still wins.\n */\nfunction warnDuplicateClass(html: string): void {\n for (const tag of html.matchAll(START_TAG)) {\n const attributes = [...(tag[1] ?? \"\").matchAll(ATTRIBUTE)];\n const classes = attributes.filter((match) => match[1]?.toLowerCase() === \"class\");\n if (classes.length < 2) continue;\n const name = /^<([^\\s/>]+)/.exec(tag[0])?.[1] ?? \"element\";\n warnOnce(\n \"DUPLICATE_CLASS_ATTRIBUTE\",\n `<${name}> has two class attributes (class and className both write class). The parser drops the second; keep one.`,\n );\n return;\n }\n}\n\n/**\n * Copies an element subtree into `namespace`, iteratively. Used only when the engine parsed a\n * MathML wrapper as HTML (some DOM implementations do not parse foreign content).\n */\nfunction inNamespace(source: Element, namespace: string): Element {\n const doc = document;\n const copyOf = (element: Element): Element => {\n const copy = doc.createElementNS(namespace, element.localName);\n for (const attribute of Array.from(element.attributes)) {\n copy.setAttribute(attribute.name, attribute.value);\n }\n return copy;\n };\n const root = copyOf(source);\n const stack: Array<[Element, Element]> = [[source, root]];\n while (stack.length > 0) {\n const pair = stack.pop();\n if (pair === undefined) break;\n const [from, to] = pair;\n for (const child of Array.from(from.childNodes)) {\n if (child instanceof Element) {\n const copy = copyOf(child);\n to.appendChild(copy);\n stack.push([child, copy]);\n } else if (child instanceof Text) {\n to.appendChild(doc.createTextNode(child.data));\n }\n }\n }\n return root;\n}\n\n/** Parses the markup once and returns its top-level nodes. SVG and MathML are parsed in a wrapper. */\nfunction parse(html: string, flags: number): Node[] {\n if (__DEV__) warnDuplicateClass(html);\n const holder = document.createElement(\"template\");\n const wrapper =\n (flags & TEMPLATE_SVG) !== 0 ? \"svg\" : (flags & TEMPLATE_MATHML) !== 0 ? \"math\" : null;\n if (wrapper === null) {\n holder.innerHTML = html;\n return Array.from(holder.content.childNodes);\n }\n holder.innerHTML = `<${wrapper}>${html}</${wrapper}>`;\n const root = holder.content.firstChild;\n if (!(root instanceof Element)) return [];\n if (wrapper === \"math\" && root.namespaceURI !== MATHML_NS) {\n return Array.from(inNamespace(root, MATHML_NS).childNodes);\n }\n return Array.from(root.childNodes);\n}\n\n/**\n * Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the\n * static part of every element tree. The markup is parsed on the first call and cloned on every call\n * after that, so creating a template touches no DOM. Each call draws the next hydration key; during\n * `hydrate()` it returns the server's element for that key instead of a clone.\n *\n * @param html Markup of one or more sibling roots. It is trusted: it is parsed as written, never\n * escaped.\n * @param flags Bit set: `1` parses the content inside `<svg>` so it gets the SVG namespace, `2` does\n * the same for MathML, `4` clones with `document.importNode` (needed for custom elements).\n * Default: `0` (HTML, `cloneNode`).\n * @returns A function that returns a new, detached node on every call: the root itself when the\n * markup has one root, otherwise a `DocumentFragment` holding the roots.\n * @example\n * import { template } from \"@shadow-js/web\";\n *\n * const makeCard = template(`<div class=\"card\"><h2></h2></div>`);\n * const card = makeCard() as HTMLDivElement;\n * (card.firstChild as HTMLElement).textContent = \"Title\";\n * document.body.append(card);\n * @since 1.0.0\n */\nexport function template(html: string, flags = 0): () => Node {\n const importNode = (flags & TEMPLATE_IMPORT_NODE) !== 0;\n let roots: Node[] | undefined;\n // Development holds the parsed roots weakly: the browser never frees an evaluated module, so a\n // hot-updated template would otherwise keep its parsed copy alive for the whole session. Only the\n // `__DEV__` branches reach this helper and `weakRoots`, so production builds carry neither.\n let weakRoots: WeakRef<Node[]> | undefined;\n const devRoots = (): Node[] => {\n const live = weakRoots?.deref();\n if (live !== undefined) return live;\n const fresh = parse(html, flags);\n weakRoots = new WeakRef(fresh);\n return fresh;\n };\n const copy = (node: Node): Node =>\n importNode ? document.importNode(node, true) : node.cloneNode(true);\n return () => {\n // While hydrating, the next template root is the server's element, not a clone.\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null) {\n if (__DEV__) {\n // The template's only root names the tag the server element must have.\n const parsed = devRoots();\n const [only] = parsed;\n if (parsed.length === 1 && only instanceof Element)\n checkClaimedTag(claimed, only.localName);\n }\n return claimed;\n }\n // biome-ignore lint/suspicious/noAssignInExpressions: the first call parses the template once; the assignment is the cache.\n const parsed = __DEV__ ? devRoots() : (roots ??= parse(html, flags));\n if (parsed.length === 1) {\n const [only] = parsed;\n if (only !== undefined) return copy(only);\n }\n const fragment = document.createDocumentFragment();\n for (const root of parsed) fragment.appendChild(copy(root));\n return fragment;\n };\n}\n"],"mappings":"A,+JAmCA,SAASA,EAAY,EAAiB,EAA4B,CAChE,IAAMC,EAAM,SACNC,EAAU,GAA8B,CAC5C,IAAMC,EAAOF,EAAI,gBAAgBG,EAAWC,EAAQ,SAAS,EAC7D,IAAK,IAAMC,KAAa,MAAM,KAAKD,EAAQ,UAAU,EACnDF,EAAK,aAAaG,EAAU,KAAMA,EAAU,KAAK,EAEnD,OAAOH,CACT,EACMI,EAAOL,EAAOM,CAAM,EACpBC,EAAmC,CAAC,CAACD,EAAQD,CAAI,CAAC,EACxD,KAAOE,EAAM,OAAS,GAAG,CACvB,IAAMC,EAAOD,EAAM,IAAI,EACvB,GAAIC,IAAS,IAAA,GAAW,MACxB,GAAM,CAACC,EAAMC,GAAMF,EACnB,IAAK,IAAMG,KAAS,MAAM,KAAKF,EAAK,UAAU,EAC5C,GAAIE,aAAiB,QAAS,CAC5B,IAAMV,EAAOD,EAAOW,CAAK,EACzBD,EAAG,YAAYT,CAAI,EACnBM,EAAM,KAAK,CAACI,EAAOV,CAAI,CAAC,CAC1B,MAAWU,aAAiB,MAC1BD,EAAG,YAAYX,EAAI,eAAeY,EAAM,IAAI,CAAC,CAGnD,CACA,OAAON,CACT,CAGA,SAASO,EAAM,EAAc,EAAuB,CAElD,IAAMC,EAAS,SAAS,cAAc,UAAU,EAC1CC,EACHC,EAAA,EAA8B,MAASA,EAAA,EAAiC,OAAS,KACpF,GAAID,IAAY,KAEd,MADA,GAAO,UAAYE,EACZ,MAAM,KAAKH,EAAO,QAAQ,UAAU,EAE7C,EAAO,UAAY,IAAIC,EAAQ,GAAGE,EAAK,IAAIF,EAAQ,GACnD,IAAMT,EAAOQ,EAAO,QAAQ,WAK5B,OAJMR,aAAgB,QAClBS,IAAY,QAAUT,EAAK,eAAA,qCACtB,MAAM,KAAKP,EAAYO,EAAMY,CAAS,CAAC,CAAC,UAAU,EAEpD,MAAM,KAAKZ,EAAK,UAAU,EAJM,CAAC,CAK1C,CAwBA,SAAgBa,EAAS,EAAc,EAAQ,EAAe,CAC5D,IAAMC,EAAA,GAAcJ,EAAA,GAChBK,EAYEnB,EAAQ,GACZkB,EAAa,SAAS,WAAWE,EAAM,EAAI,EAAIA,EAAK,UAAU,EAAI,EACpE,UAAa,CAEX,IAAMC,EAAUC,EAAO,QAAQ,aAAaC,EAAQ,CAAC,EACrD,GAAIF,IAAY,KAQd,OAAOA,EAGT,IAAMG,EAAiC,IAAUb,EAAMI,EAAMD,CAAK,EAClE,GAAIU,EAAO,SAAW,EAAG,CACvB,GAAM,CAACC,GAAQD,EACf,GAAIC,IAAS,IAAA,GAAW,OAAOzB,EAAKyB,CAAI,CAC1C,CACA,IAAMC,EAAW,SAAS,uBAAuB,EACjD,IAAK,IAAMtB,KAAQoB,EAAQE,EAAS,YAAY1B,EAAKI,CAAI,CAAC,EAC1D,OAAOsB,CACT,CACF,C"}
1
+ {"version":3,"file":"template.js","names":["inNamespace","doc","copyOf","copy","namespace","element","attribute","root","source","stack","from","to","child","parse","holder","wrapper","flags","html","MATHML_NS","template","importNode","roots","node","claimed","claims","nextKey","parsed","only","fragment"],"sources":["../../src/template.ts"],"sourcesContent":["import { checkClaimedTag } from \"./internal/claim\";\nimport { warnOnce } from \"./internal/diagnostics\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { MATHML_NS, TEMPLATE_IMPORT_NODE, TEMPLATE_MATHML, TEMPLATE_SVG } from \"./internal/names\";\n\n/** One start tag: its name, then its attribute text (group 1). */\nconst START_TAG =\n /<[a-zA-Z][^\\s/>]*((?:\\s+[^\\s\"'>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?)*)\\s*\\/?>/g;\n/** One attribute inside the attribute text of a start tag: its name (group 1). */\nconst ATTRIBUTE = /([^\\s\"'>/=]+)(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?/g;\n\n/**\n * Development check for the markup a template is parsed from. The HTML parser keeps the first of two\n * same-named attributes and drops the rest, so `class` and `className` on one element (both compiled\n * to `class`) lose one silently. Warns `DUPLICATE_CLASS_ATTRIBUTE` once; the first attribute still wins.\n */\nfunction warnDuplicateClass(html: string): void {\n for (const tag of html.matchAll(START_TAG)) {\n const attributes = [...(tag[1] ?? \"\").matchAll(ATTRIBUTE)];\n const classes = attributes.filter((match) => match[1]?.toLowerCase() === \"class\");\n if (classes.length < 2) continue;\n const name = /^<([^\\s/>]+)/.exec(tag[0])?.[1] ?? \"element\";\n warnOnce(\n \"DUPLICATE_CLASS_ATTRIBUTE\",\n `<${name}> has two class attributes (class and className both write class). The parser drops the second; keep one.`,\n );\n return;\n }\n}\n\n/**\n * Copies an element subtree into `namespace`, iteratively. Used only when the engine parsed a\n * MathML wrapper as HTML (some DOM implementations do not parse foreign content).\n */\nfunction inNamespace(source: Element, namespace: string): Element {\n const doc = document;\n const copyOf = (element: Element): Element => {\n const copy = doc.createElementNS(namespace, element.localName);\n for (const attribute of Array.from(element.attributes)) {\n copy.setAttribute(attribute.name, attribute.value);\n }\n return copy;\n };\n const root = copyOf(source);\n const stack: Array<[Element, Element]> = [[source, root]];\n while (stack.length > 0) {\n const [from, to] = stack.pop() as [Element, Element];\n for (const child of Array.from(from.childNodes)) {\n if (child instanceof Element) {\n const copy = copyOf(child);\n to.appendChild(copy);\n stack.push([child, copy]);\n } else if (child instanceof Text) {\n to.appendChild(doc.createTextNode(child.data));\n }\n }\n }\n return root;\n}\n\n/** Parses the markup once and returns its top-level nodes. SVG and MathML are parsed in a wrapper. */\nfunction parse(html: string, flags: number): Node[] {\n if (__DEV__) warnDuplicateClass(html);\n const holder = document.createElement(\"template\");\n const wrapper =\n (flags & TEMPLATE_SVG) !== 0 ? \"svg\" : (flags & TEMPLATE_MATHML) !== 0 ? \"math\" : null;\n if (wrapper === null) {\n holder.innerHTML = html;\n return Array.from(holder.content.childNodes);\n }\n holder.innerHTML = `<${wrapper}>${html}</${wrapper}>`;\n const root = holder.content.firstChild;\n if (!(root instanceof Element)) return [];\n if (wrapper === \"math\" && root.namespaceURI !== MATHML_NS) {\n return Array.from(inNamespace(root, MATHML_NS).childNodes);\n }\n return Array.from(root.childNodes);\n}\n\n/**\n * Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the\n * static part of every element tree. The markup is parsed on the first call and cloned on every call\n * after that, so creating a template touches no DOM. Each call draws the next hydration key; during\n * `hydrate()` it returns the server's element for that key instead of a clone.\n *\n * @param html Markup of one or more sibling roots. It is trusted: it is parsed as written, never\n * escaped.\n * @param flags Bit set: `1` parses the content inside `<svg>` so it gets the SVG namespace, `2` does\n * the same for MathML, `4` clones with `document.importNode` (needed for custom elements).\n * Default: `0` (HTML, `cloneNode`).\n * @returns A function that returns a new, detached node on every call: the root itself when the\n * markup has one root, otherwise a `DocumentFragment` holding the roots.\n * @example\n * import { template } from \"@shadow-js/web\";\n *\n * const makeCard = template(`<div class=\"card\"><h2></h2></div>`);\n * const card = makeCard() as HTMLDivElement;\n * (card.firstChild as HTMLElement).textContent = \"Title\";\n * document.body.append(card);\n * @since 1.0.0\n */\nexport function template(html: string, flags = 0): () => Node {\n const importNode = (flags & TEMPLATE_IMPORT_NODE) !== 0;\n let roots: Node[] | undefined;\n // Development holds the parsed roots weakly: the browser never frees an evaluated module, so a\n // hot-updated template would otherwise keep its parsed copy alive for the whole session. Only the\n // `__DEV__` branches reach this helper and `weakRoots`, so production builds carry neither.\n let weakRoots: WeakRef<Node[]> | undefined;\n const devRoots = (): Node[] => {\n const live = weakRoots?.deref();\n if (live !== undefined) return live;\n const fresh = parse(html, flags);\n weakRoots = new WeakRef(fresh);\n return fresh;\n };\n const copy = (node: Node): Node =>\n importNode ? document.importNode(node, true) : node.cloneNode(true);\n return () => {\n // While hydrating, the next template root is the server's element, not a clone.\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null) {\n if (__DEV__) {\n // The template's only root names the tag the server element must have.\n const parsed = devRoots();\n const [only] = parsed;\n if (parsed.length === 1 && only instanceof Element)\n checkClaimedTag(claimed, only.localName);\n }\n return claimed;\n }\n // biome-ignore lint/suspicious/noAssignInExpressions: the first call parses the template once; the assignment is the cache.\n const parsed = __DEV__ ? devRoots() : (roots ??= parse(html, flags));\n if (parsed.length === 1) {\n const [only] = parsed;\n if (only !== undefined) return copy(only);\n }\n const fragment = document.createDocumentFragment();\n for (const root of parsed) fragment.appendChild(copy(root));\n return fragment;\n };\n}\n"],"mappings":"A,+JAmCA,SAASA,EAAY,EAAiB,EAA4B,CAChE,IAAMC,EAAM,SACNC,EAAU,GAA8B,CAC5C,IAAMC,EAAOF,EAAI,gBAAgBG,EAAWC,EAAQ,SAAS,EAC7D,IAAK,IAAMC,KAAa,MAAM,KAAKD,EAAQ,UAAU,EACnDF,EAAK,aAAaG,EAAU,KAAMA,EAAU,KAAK,EAEnD,OAAOH,CACT,EACMI,EAAOL,EAAOM,CAAM,EACpBC,EAAmC,CAAC,CAACD,EAAQD,CAAI,CAAC,EACxD,KAAOE,EAAM,OAAS,GAAG,CACvB,GAAM,CAACC,EAAMC,GAAMF,EAAM,IAAI,EAC7B,IAAK,IAAMG,KAAS,MAAM,KAAKF,EAAK,UA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,OAAOqB,CACT,CACF,C"}
@@ -1,2 +1,2 @@
1
- import{flushSync as e,untrack as t,useEffect as n,useId as r}from"@shadow-js/core";function i(t,n){let r=typeof document>`u`?void 0:document;if(r===void 0||typeof r.startViewTransition!=`function`){try{e(t)}catch(e){return Promise.reject(e)}return Promise.resolve()}let i,a=()=>{try{e(t)}catch(e){i={error:e}}},o=n?.types;return r.startViewTransition(o===void 0||o.length===0?a:{update:a,types:[...o]}).finished.then(()=>{if(i!==void 0)throw i.error})}function a(e){let i,a=!1,c=()=>(a||(a=!0,i=t(()=>e.children)),i),l=document.createTextNode(``),u=document.createTextNode(``),d=e.name===!0?`vt-${r()}`:void 0;return n(()=>{let t=o(l,u);t!==null&&(s(t,`view-transition-name`,d??(typeof e.name==`string`?e.name:void 0)),s(t,`view-transition-class`,e.class))}),()=>[l,c(),u]}function o(e,t){for(let n=e.nextSibling;n!==null&&n!==t;n=n.nextSibling)if(n.nodeType===1)return n;return null}function s(e,t,n){n===void 0||n===``?e.style.removeProperty(t):e.style.setProperty(t,n)}export{a as ViewTransition,i as startViewTransition};
1
+ import{watchCommits as e}from"./insert.js";import{flushSync as t,untrack as n,useEffect as r,useId as i}from"@shadow-js/core";function a(e,n){let r=typeof document>`u`?void 0:document;if(r===void 0||typeof r.startViewTransition!=`function`){try{t(e)}catch(e){return Promise.reject(e)}return Promise.resolve()}let i,a=()=>{try{t(e)}catch(e){i={error:e}}},o=n?.types;return r.startViewTransition(o===void 0||o.length===0?a:{update:a,types:[...o]}).finished.then(()=>{if(i!==void 0)throw i.error})}function o(t){let a,o=!1,l=()=>(o||(o=!0,a=n(()=>t.children)),a),u=document.createTextNode(``),d=document.createTextNode(``),f=t.name===!0?`vt-${i()}`:void 0;return r(()=>{let n=f??(typeof t.name==`string`?t.name:void 0),r=t.class,i=()=>{let e=s(u,d);e!==null&&(c(e,`view-transition-name`,n),c(e,`view-transition-class`,r))};i();let a=u.parentNode;a!==null&&e(a,i)}),()=>[u,l(),d]}function s(e,t){for(let n=e.nextSibling;n!==null&&n!==t;n=n.nextSibling)if(n.nodeType===1)return n;return null}function c(e,t,n){n===void 0||n===``?e.style.removeProperty(t):e.style.setProperty(t,n)}export{o as ViewTransition,a as startViewTransition};
2
2
  //# sourceMappingURL=view-transition.js.map