@shadow-js/web 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (611) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE +21 -0
  3. package/README.md +190 -2
  4. package/dist/dev/attributes.d.ts +88 -0
  5. package/dist/dev/attributes.js +195 -0
  6. package/dist/dev/attributes.js.map +1 -0
  7. package/dist/dev/autofocus.d.ts +30 -0
  8. package/dist/dev/autofocus.js +44 -0
  9. package/dist/dev/autofocus.js.map +1 -0
  10. package/dist/dev/class-style.d.ts +87 -0
  11. package/dist/dev/class-style.js +196 -0
  12. package/dist/dev/class-style.js.map +1 -0
  13. package/dist/dev/component.d.ts +21 -0
  14. package/dist/dev/component.js +41 -0
  15. package/dist/dev/component.js.map +1 -0
  16. package/dist/dev/control-flow/activity.d.ts +56 -0
  17. package/dist/dev/control-flow/activity.js +135 -0
  18. package/dist/dev/control-flow/activity.js.map +1 -0
  19. package/dist/dev/control-flow/branch.js +103 -0
  20. package/dist/dev/control-flow/branch.js.map +1 -0
  21. package/dist/dev/control-flow/client-only.d.ts +46 -0
  22. package/dist/dev/control-flow/client-only.js +49 -0
  23. package/dist/dev/control-flow/client-only.js.map +1 -0
  24. package/dist/dev/control-flow/dynamic.d.ts +80 -0
  25. package/dist/dev/control-flow/dynamic.js +133 -0
  26. package/dist/dev/control-flow/dynamic.js.map +1 -0
  27. package/dist/dev/control-flow/error-boundary.d.ts +70 -0
  28. package/dist/dev/control-flow/error-boundary.js +114 -0
  29. package/dist/dev/control-flow/error-boundary.js.map +1 -0
  30. package/dist/dev/control-flow/for.d.ts +78 -0
  31. package/dist/dev/control-flow/for.js +22 -0
  32. package/dist/dev/control-flow/for.js.map +1 -0
  33. package/dist/dev/control-flow/fragment.d.ts +36 -0
  34. package/dist/dev/control-flow/fragment.js +30 -0
  35. package/dist/dev/control-flow/fragment.js.map +1 -0
  36. package/dist/dev/control-flow/hot-link.js +63 -0
  37. package/dist/dev/control-flow/hot-link.js.map +1 -0
  38. package/dist/dev/control-flow/index-list.d.ts +46 -0
  39. package/dist/dev/control-flow/index-list.js +30 -0
  40. package/dist/dev/control-flow/index-list.js.map +1 -0
  41. package/dist/dev/control-flow/index.d.ts +15 -0
  42. package/dist/dev/control-flow/lazy.d.ts +56 -0
  43. package/dist/dev/control-flow/lazy.js +63 -0
  44. package/dist/dev/control-flow/lazy.js.map +1 -0
  45. package/dist/dev/control-flow/no-hydration.d.ts +37 -0
  46. package/dist/dev/control-flow/no-hydration.js +57 -0
  47. package/dist/dev/control-flow/no-hydration.js.map +1 -0
  48. package/dist/dev/control-flow/portal.d.ts +67 -0
  49. package/dist/dev/control-flow/portal.js +133 -0
  50. package/dist/dev/control-flow/portal.js.map +1 -0
  51. package/dist/dev/control-flow/root-errors.d.ts +23 -0
  52. package/dist/dev/control-flow/root-errors.js +32 -0
  53. package/dist/dev/control-flow/root-errors.js.map +1 -0
  54. package/dist/dev/control-flow/show.d.ts +99 -0
  55. package/dist/dev/control-flow/show.js +17 -0
  56. package/dist/dev/control-flow/show.js.map +1 -0
  57. package/dist/dev/control-flow/suspense-list.d.ts +63 -0
  58. package/dist/dev/control-flow/suspense-list.js +104 -0
  59. package/dist/dev/control-flow/suspense-list.js.map +1 -0
  60. package/dist/dev/control-flow/suspense.d.ts +51 -0
  61. package/dist/dev/control-flow/suspense.js +101 -0
  62. package/dist/dev/control-flow/suspense.js.map +1 -0
  63. package/dist/dev/control-flow/switch.d.ts +83 -0
  64. package/dist/dev/control-flow/switch.js +89 -0
  65. package/dist/dev/control-flow/switch.js.map +1 -0
  66. package/dist/dev/derived.d.ts +50 -0
  67. package/dist/dev/derived.js +33 -0
  68. package/dist/dev/derived.js.map +1 -0
  69. package/dist/dev/element.d.ts +38 -0
  70. package/dist/dev/element.js +104 -0
  71. package/dist/dev/element.js.map +1 -0
  72. package/dist/dev/events.d.ts +85 -0
  73. package/dist/dev/events.js +264 -0
  74. package/dist/dev/events.js.map +1 -0
  75. package/dist/dev/extend.d.ts +12 -0
  76. package/dist/dev/extend.js +12 -0
  77. package/dist/dev/head/components.d.ts +135 -0
  78. package/dist/dev/head/components.js +169 -0
  79. package/dist/dev/head/components.js.map +1 -0
  80. package/dist/dev/head/registry.js +67 -0
  81. package/dist/dev/head/registry.js.map +1 -0
  82. package/dist/dev/head/server-head.d.ts +52 -0
  83. package/dist/dev/head/server-head.js +75 -0
  84. package/dist/dev/head/server-head.js.map +1 -0
  85. package/dist/dev/head/sink.js +95 -0
  86. package/dist/dev/head/sink.js.map +1 -0
  87. package/dist/dev/head/use-head.d.ts +33 -0
  88. package/dist/dev/head/use-head.js +83 -0
  89. package/dist/dev/head/use-head.js.map +1 -0
  90. package/dist/dev/head/validate.d.ts +83 -0
  91. package/dist/dev/head/validate.js +267 -0
  92. package/dist/dev/head/validate.js.map +1 -0
  93. package/dist/dev/hmr.d.ts +80 -0
  94. package/dist/dev/hmr.js +123 -0
  95. package/dist/dev/hmr.js.map +1 -0
  96. package/dist/dev/hydration.d.ts +59 -0
  97. package/dist/dev/hydration.js +119 -0
  98. package/dist/dev/hydration.js.map +1 -0
  99. package/dist/dev/index.d.ts +45 -0
  100. package/dist/dev/index.js +34 -0
  101. package/dist/dev/insert.d.ts +95 -0
  102. package/dist/dev/insert.js +356 -0
  103. package/dist/dev/insert.js.map +1 -0
  104. package/dist/dev/internal/claim.d.ts +104 -0
  105. package/dist/dev/internal/claim.js +356 -0
  106. package/dist/dev/internal/claim.js.map +1 -0
  107. package/dist/dev/internal/css-units.js +25 -0
  108. package/dist/dev/internal/css-units.js.map +1 -0
  109. package/dist/dev/internal/diagnostics.d.ts +28 -0
  110. package/dist/dev/internal/diagnostics.js +37 -0
  111. package/dist/dev/internal/diagnostics.js.map +1 -0
  112. package/dist/dev/internal/early-events.js +75 -0
  113. package/dist/dev/internal/early-events.js.map +1 -0
  114. package/dist/dev/internal/hydration-hooks.d.ts +41 -0
  115. package/dist/dev/internal/hydration-hooks.js +26 -0
  116. package/dist/dev/internal/hydration-hooks.js.map +1 -0
  117. package/dist/dev/internal/hydration-scope.d.ts +129 -0
  118. package/dist/dev/internal/hydration-scope.js +155 -0
  119. package/dist/dev/internal/hydration-scope.js.map +1 -0
  120. package/dist/dev/internal/names.d.ts +31 -0
  121. package/dist/dev/internal/names.js +34 -0
  122. package/dist/dev/internal/names.js.map +1 -0
  123. package/dist/dev/internal/portal-context.d.ts +37 -0
  124. package/dist/dev/internal/portal-context.js +27 -0
  125. package/dist/dev/internal/portal-context.js.map +1 -0
  126. package/dist/dev/internal/react-names.js +115 -0
  127. package/dist/dev/internal/react-names.js.map +1 -0
  128. package/dist/dev/internal/reconcile.d.ts +38 -0
  129. package/dist/dev/internal/reconcile.js +121 -0
  130. package/dist/dev/internal/reconcile.js.map +1 -0
  131. package/dist/dev/internal/stream-context.d.ts +45 -0
  132. package/dist/dev/internal/stream-context.js +22 -0
  133. package/dist/dev/internal/stream-context.js.map +1 -0
  134. package/dist/dev/jsx/aria.d.ts +70 -0
  135. package/dist/dev/jsx/component.d.ts +87 -0
  136. package/dist/dev/jsx/events.d.ts +362 -0
  137. package/dist/dev/jsx/global.d.ts +209 -0
  138. package/dist/dev/jsx/html.d.ts +877 -0
  139. package/dist/dev/jsx/intrinsic.d.ts +57 -0
  140. package/dist/dev/jsx/mathml.d.ts +184 -0
  141. package/dist/dev/jsx/svg.d.ts +605 -0
  142. package/dist/dev/jsx/types.d.ts +174 -0
  143. package/dist/dev/jsx-dev-runtime.d.ts +10 -0
  144. package/dist/dev/jsx-dev-runtime.js +0 -0
  145. package/dist/dev/jsx-runtime.d.ts +92 -0
  146. package/dist/dev/jsx-runtime.js +0 -0
  147. package/dist/dev/reactive.d.ts +108 -0
  148. package/dist/dev/reactive.js +84 -0
  149. package/dist/dev/reactive.js.map +1 -0
  150. package/dist/dev/render.d.ts +34 -0
  151. package/dist/dev/render.js +51 -0
  152. package/dist/dev/render.js.map +1 -0
  153. package/dist/dev/resource-hints.d.ts +143 -0
  154. package/dist/dev/resource-hints.js +199 -0
  155. package/dist/dev/resource-hints.js.map +1 -0
  156. package/dist/dev/select-value.d.ts +22 -0
  157. package/dist/dev/select-value.js +50 -0
  158. package/dist/dev/select-value.js.map +1 -0
  159. package/dist/dev/server/attributes.d.ts +31 -0
  160. package/dist/dev/server/attributes.js +154 -0
  161. package/dist/dev/server/attributes.js.map +1 -0
  162. package/dist/dev/server/class-style.d.ts +44 -0
  163. package/dist/dev/server/class-style.js +172 -0
  164. package/dist/dev/server/class-style.js.map +1 -0
  165. package/dist/dev/server/component.d.ts +40 -0
  166. package/dist/dev/server/component.js +71 -0
  167. package/dist/dev/server/component.js.map +1 -0
  168. package/dist/dev/server/derived.d.ts +39 -0
  169. package/dist/dev/server/derived.js +25 -0
  170. package/dist/dev/server/derived.js.map +1 -0
  171. package/dist/dev/server/element.d.ts +87 -0
  172. package/dist/dev/server/element.js +215 -0
  173. package/dist/dev/server/element.js.map +1 -0
  174. package/dist/dev/server/errors.js +25 -0
  175. package/dist/dev/server/errors.js.map +1 -0
  176. package/dist/dev/server/escape.d.ts +28 -0
  177. package/dist/dev/server/escape.js +118 -0
  178. package/dist/dev/server/escape.js.map +1 -0
  179. package/dist/dev/server/form-controls.d.ts +48 -0
  180. package/dist/dev/server/form-controls.js +192 -0
  181. package/dist/dev/server/form-controls.js.map +1 -0
  182. package/dist/dev/server/hydration-script.d.ts +63 -0
  183. package/dist/dev/server/hydration-script.js +58 -0
  184. package/dist/dev/server/hydration-script.js.map +1 -0
  185. package/dist/dev/server/index.d.ts +16 -0
  186. package/dist/dev/server/index.js +16 -0
  187. package/dist/dev/server/node.d.ts +11 -0
  188. package/dist/dev/server/node.js +20 -0
  189. package/dist/dev/server/node.js.map +1 -0
  190. package/dist/dev/server/portals.d.ts +44 -0
  191. package/dist/dev/server/portals.js +98 -0
  192. package/dist/dev/server/portals.js.map +1 -0
  193. package/dist/dev/server/render.d.ts +127 -0
  194. package/dist/dev/server/render.js +255 -0
  195. package/dist/dev/server/render.js.map +1 -0
  196. package/dist/dev/server/serialize.d.ts +43 -0
  197. package/dist/dev/server/serialize.js +314 -0
  198. package/dist/dev/server/serialize.js.map +1 -0
  199. package/dist/dev/server/stream.d.ts +92 -0
  200. package/dist/dev/server/stream.js +234 -0
  201. package/dist/dev/server/stream.js.map +1 -0
  202. package/dist/dev/server.d.ts +16 -0
  203. package/dist/dev/server.js +16 -0
  204. package/dist/dev/spread.d.ts +47 -0
  205. package/dist/dev/spread.js +295 -0
  206. package/dist/dev/spread.js.map +1 -0
  207. package/dist/dev/template.d.ts +24 -0
  208. package/dist/dev/template.js +119 -0
  209. package/dist/dev/template.js.map +1 -0
  210. package/dist/dev/view-transition.d.ts +95 -0
  211. package/dist/dev/view-transition.js +120 -0
  212. package/dist/dev/view-transition.js.map +1 -0
  213. package/dist/prod/attributes.js +2 -0
  214. package/dist/prod/attributes.js.map +1 -0
  215. package/dist/prod/autofocus.js +2 -0
  216. package/dist/prod/autofocus.js.map +1 -0
  217. package/dist/prod/class-style.js +2 -0
  218. package/dist/prod/class-style.js.map +1 -0
  219. package/dist/prod/component.js +2 -0
  220. package/dist/prod/component.js.map +1 -0
  221. package/dist/prod/control-flow/activity.js +2 -0
  222. package/dist/prod/control-flow/activity.js.map +1 -0
  223. package/dist/prod/control-flow/branch.js +2 -0
  224. package/dist/prod/control-flow/branch.js.map +1 -0
  225. package/dist/prod/control-flow/client-only.js +2 -0
  226. package/dist/prod/control-flow/client-only.js.map +1 -0
  227. package/dist/prod/control-flow/dynamic.js +2 -0
  228. package/dist/prod/control-flow/dynamic.js.map +1 -0
  229. package/dist/prod/control-flow/error-boundary.js +2 -0
  230. package/dist/prod/control-flow/error-boundary.js.map +1 -0
  231. package/dist/prod/control-flow/for.js +2 -0
  232. package/dist/prod/control-flow/for.js.map +1 -0
  233. package/dist/prod/control-flow/fragment.js +2 -0
  234. package/dist/prod/control-flow/fragment.js.map +1 -0
  235. package/dist/prod/control-flow/hot-link.js +2 -0
  236. package/dist/prod/control-flow/hot-link.js.map +1 -0
  237. package/dist/prod/control-flow/index-list.js +2 -0
  238. package/dist/prod/control-flow/index-list.js.map +1 -0
  239. package/dist/prod/control-flow/lazy.js +2 -0
  240. package/dist/prod/control-flow/lazy.js.map +1 -0
  241. package/dist/prod/control-flow/no-hydration.js +2 -0
  242. package/dist/prod/control-flow/no-hydration.js.map +1 -0
  243. package/dist/prod/control-flow/portal.js +2 -0
  244. package/dist/prod/control-flow/portal.js.map +1 -0
  245. package/dist/prod/control-flow/root-errors.js +2 -0
  246. package/dist/prod/control-flow/root-errors.js.map +1 -0
  247. package/dist/prod/control-flow/show.js +2 -0
  248. package/dist/prod/control-flow/show.js.map +1 -0
  249. package/dist/prod/control-flow/suspense-list.js +2 -0
  250. package/dist/prod/control-flow/suspense-list.js.map +1 -0
  251. package/dist/prod/control-flow/suspense.js +2 -0
  252. package/dist/prod/control-flow/suspense.js.map +1 -0
  253. package/dist/prod/control-flow/switch.js +2 -0
  254. package/dist/prod/control-flow/switch.js.map +1 -0
  255. package/dist/prod/derived.js +2 -0
  256. package/dist/prod/derived.js.map +1 -0
  257. package/dist/prod/element.js +2 -0
  258. package/dist/prod/element.js.map +1 -0
  259. package/dist/prod/events.js +2 -0
  260. package/dist/prod/events.js.map +1 -0
  261. package/dist/prod/extend.js +1 -0
  262. package/dist/prod/head/components.js +2 -0
  263. package/dist/prod/head/components.js.map +1 -0
  264. package/dist/prod/head/registry.js +2 -0
  265. package/dist/prod/head/registry.js.map +1 -0
  266. package/dist/prod/head/server-head.js +2 -0
  267. package/dist/prod/head/server-head.js.map +1 -0
  268. package/dist/prod/head/sink.js +2 -0
  269. package/dist/prod/head/sink.js.map +1 -0
  270. package/dist/prod/head/use-head.js +2 -0
  271. package/dist/prod/head/use-head.js.map +1 -0
  272. package/dist/prod/head/validate.js +2 -0
  273. package/dist/prod/head/validate.js.map +1 -0
  274. package/dist/prod/hmr.js +2 -0
  275. package/dist/prod/hmr.js.map +1 -0
  276. package/dist/prod/hydration.js +2 -0
  277. package/dist/prod/hydration.js.map +1 -0
  278. package/dist/prod/index.js +1 -0
  279. package/dist/prod/insert.js +2 -0
  280. package/dist/prod/insert.js.map +1 -0
  281. package/dist/prod/internal/claim.js +2 -0
  282. package/dist/prod/internal/claim.js.map +1 -0
  283. package/dist/prod/internal/css-units.js +2 -0
  284. package/dist/prod/internal/css-units.js.map +1 -0
  285. package/dist/prod/internal/diagnostics.js +2 -0
  286. package/dist/prod/internal/diagnostics.js.map +1 -0
  287. package/dist/prod/internal/early-events.js +2 -0
  288. package/dist/prod/internal/early-events.js.map +1 -0
  289. package/dist/prod/internal/hydration-hooks.js +2 -0
  290. package/dist/prod/internal/hydration-hooks.js.map +1 -0
  291. package/dist/prod/internal/hydration-scope.js +2 -0
  292. package/dist/prod/internal/hydration-scope.js.map +1 -0
  293. package/dist/prod/internal/names.js +2 -0
  294. package/dist/prod/internal/names.js.map +1 -0
  295. package/dist/prod/internal/portal-context.js +2 -0
  296. package/dist/prod/internal/portal-context.js.map +1 -0
  297. package/dist/prod/internal/react-names.js +2 -0
  298. package/dist/prod/internal/react-names.js.map +1 -0
  299. package/dist/prod/internal/reconcile.js +2 -0
  300. package/dist/prod/internal/reconcile.js.map +1 -0
  301. package/dist/prod/internal/stream-context.js +2 -0
  302. package/dist/prod/internal/stream-context.js.map +1 -0
  303. package/dist/prod/jsx-dev-runtime.js +0 -0
  304. package/dist/prod/jsx-runtime.js +0 -0
  305. package/dist/prod/reactive.js +2 -0
  306. package/dist/prod/reactive.js.map +1 -0
  307. package/dist/prod/render.js +2 -0
  308. package/dist/prod/render.js.map +1 -0
  309. package/dist/prod/resource-hints.js +2 -0
  310. package/dist/prod/resource-hints.js.map +1 -0
  311. package/dist/prod/select-value.js +2 -0
  312. package/dist/prod/select-value.js.map +1 -0
  313. package/dist/prod/server/attributes.js +2 -0
  314. package/dist/prod/server/attributes.js.map +1 -0
  315. package/dist/prod/server/class-style.js +2 -0
  316. package/dist/prod/server/class-style.js.map +1 -0
  317. package/dist/prod/server/component.js +2 -0
  318. package/dist/prod/server/component.js.map +1 -0
  319. package/dist/prod/server/derived.js +2 -0
  320. package/dist/prod/server/derived.js.map +1 -0
  321. package/dist/prod/server/element.js +2 -0
  322. package/dist/prod/server/element.js.map +1 -0
  323. package/dist/prod/server/errors.js +2 -0
  324. package/dist/prod/server/errors.js.map +1 -0
  325. package/dist/prod/server/escape.js +2 -0
  326. package/dist/prod/server/escape.js.map +1 -0
  327. package/dist/prod/server/form-controls.js +3 -0
  328. package/dist/prod/server/form-controls.js.map +1 -0
  329. package/dist/prod/server/hydration-script.js +2 -0
  330. package/dist/prod/server/hydration-script.js.map +1 -0
  331. package/dist/prod/server/index.js +1 -0
  332. package/dist/prod/server/node.js +2 -0
  333. package/dist/prod/server/node.js.map +1 -0
  334. package/dist/prod/server/portals.js +2 -0
  335. package/dist/prod/server/portals.js.map +1 -0
  336. package/dist/prod/server/render.js +2 -0
  337. package/dist/prod/server/render.js.map +1 -0
  338. package/dist/prod/server/serialize.js +2 -0
  339. package/dist/prod/server/serialize.js.map +1 -0
  340. package/dist/prod/server/stream.js +2 -0
  341. package/dist/prod/server/stream.js.map +1 -0
  342. package/dist/prod/server.js +1 -0
  343. package/dist/prod/spread.js +2 -0
  344. package/dist/prod/spread.js.map +1 -0
  345. package/dist/prod/template.js +2 -0
  346. package/dist/prod/template.js.map +1 -0
  347. package/dist/prod/view-transition.js +2 -0
  348. package/dist/prod/view-transition.js.map +1 -0
  349. package/dist/server/attributes.js +2 -0
  350. package/dist/server/attributes.js.map +1 -0
  351. package/dist/server/autofocus.js +2 -0
  352. package/dist/server/autofocus.js.map +1 -0
  353. package/dist/server/class-style.js +2 -0
  354. package/dist/server/class-style.js.map +1 -0
  355. package/dist/server/component.js +2 -0
  356. package/dist/server/component.js.map +1 -0
  357. package/dist/server/control-flow/activity.js +2 -0
  358. package/dist/server/control-flow/activity.js.map +1 -0
  359. package/dist/server/control-flow/branch.js +2 -0
  360. package/dist/server/control-flow/branch.js.map +1 -0
  361. package/dist/server/control-flow/client-only.js +2 -0
  362. package/dist/server/control-flow/client-only.js.map +1 -0
  363. package/dist/server/control-flow/dynamic.js +2 -0
  364. package/dist/server/control-flow/dynamic.js.map +1 -0
  365. package/dist/server/control-flow/error-boundary.js +2 -0
  366. package/dist/server/control-flow/error-boundary.js.map +1 -0
  367. package/dist/server/control-flow/for.js +2 -0
  368. package/dist/server/control-flow/for.js.map +1 -0
  369. package/dist/server/control-flow/fragment.js +2 -0
  370. package/dist/server/control-flow/fragment.js.map +1 -0
  371. package/dist/server/control-flow/index-list.js +2 -0
  372. package/dist/server/control-flow/index-list.js.map +1 -0
  373. package/dist/server/control-flow/lazy.js +2 -0
  374. package/dist/server/control-flow/lazy.js.map +1 -0
  375. package/dist/server/control-flow/no-hydration.js +2 -0
  376. package/dist/server/control-flow/no-hydration.js.map +1 -0
  377. package/dist/server/control-flow/portal.js +2 -0
  378. package/dist/server/control-flow/portal.js.map +1 -0
  379. package/dist/server/control-flow/root-errors.js +2 -0
  380. package/dist/server/control-flow/root-errors.js.map +1 -0
  381. package/dist/server/control-flow/show.js +2 -0
  382. package/dist/server/control-flow/show.js.map +1 -0
  383. package/dist/server/control-flow/suspense-list.js +2 -0
  384. package/dist/server/control-flow/suspense-list.js.map +1 -0
  385. package/dist/server/control-flow/suspense.js +2 -0
  386. package/dist/server/control-flow/suspense.js.map +1 -0
  387. package/dist/server/control-flow/switch.js +2 -0
  388. package/dist/server/control-flow/switch.js.map +1 -0
  389. package/dist/server/derived.js +2 -0
  390. package/dist/server/derived.js.map +1 -0
  391. package/dist/server/element.js +2 -0
  392. package/dist/server/element.js.map +1 -0
  393. package/dist/server/events.js +2 -0
  394. package/dist/server/events.js.map +1 -0
  395. package/dist/server/extend.js +1 -0
  396. package/dist/server/head/components.js +2 -0
  397. package/dist/server/head/components.js.map +1 -0
  398. package/dist/server/head/registry.js +2 -0
  399. package/dist/server/head/registry.js.map +1 -0
  400. package/dist/server/head/server-head.js +2 -0
  401. package/dist/server/head/server-head.js.map +1 -0
  402. package/dist/server/head/sink.js +2 -0
  403. package/dist/server/head/sink.js.map +1 -0
  404. package/dist/server/head/use-head.js +2 -0
  405. package/dist/server/head/use-head.js.map +1 -0
  406. package/dist/server/head/validate.js +2 -0
  407. package/dist/server/head/validate.js.map +1 -0
  408. package/dist/server/hydration.js +2 -0
  409. package/dist/server/hydration.js.map +1 -0
  410. package/dist/server/index.js +1 -0
  411. package/dist/server/insert.js +2 -0
  412. package/dist/server/insert.js.map +1 -0
  413. package/dist/server/internal/claim.js +2 -0
  414. package/dist/server/internal/claim.js.map +1 -0
  415. package/dist/server/internal/css-units.js +2 -0
  416. package/dist/server/internal/css-units.js.map +1 -0
  417. package/dist/server/internal/diagnostics.js +2 -0
  418. package/dist/server/internal/diagnostics.js.map +1 -0
  419. package/dist/server/internal/early-events.js +2 -0
  420. package/dist/server/internal/early-events.js.map +1 -0
  421. package/dist/server/internal/hydration-hooks.js +2 -0
  422. package/dist/server/internal/hydration-hooks.js.map +1 -0
  423. package/dist/server/internal/hydration-scope.js +2 -0
  424. package/dist/server/internal/hydration-scope.js.map +1 -0
  425. package/dist/server/internal/names.js +2 -0
  426. package/dist/server/internal/names.js.map +1 -0
  427. package/dist/server/internal/portal-context.js +2 -0
  428. package/dist/server/internal/portal-context.js.map +1 -0
  429. package/dist/server/internal/react-names.js +2 -0
  430. package/dist/server/internal/react-names.js.map +1 -0
  431. package/dist/server/internal/reconcile.js +2 -0
  432. package/dist/server/internal/reconcile.js.map +1 -0
  433. package/dist/server/internal/stream-context.js +2 -0
  434. package/dist/server/internal/stream-context.js.map +1 -0
  435. package/dist/server/reactive.js +2 -0
  436. package/dist/server/reactive.js.map +1 -0
  437. package/dist/server/render.js +2 -0
  438. package/dist/server/render.js.map +1 -0
  439. package/dist/server/resource-hints.js +2 -0
  440. package/dist/server/resource-hints.js.map +1 -0
  441. package/dist/server/select-value.js +2 -0
  442. package/dist/server/select-value.js.map +1 -0
  443. package/dist/server/server/attributes.js +2 -0
  444. package/dist/server/server/attributes.js.map +1 -0
  445. package/dist/server/server/class-style.js +2 -0
  446. package/dist/server/server/class-style.js.map +1 -0
  447. package/dist/server/server/component.js +2 -0
  448. package/dist/server/server/component.js.map +1 -0
  449. package/dist/server/server/derived.js +2 -0
  450. package/dist/server/server/derived.js.map +1 -0
  451. package/dist/server/server/element.js +2 -0
  452. package/dist/server/server/element.js.map +1 -0
  453. package/dist/server/server/errors.js +2 -0
  454. package/dist/server/server/errors.js.map +1 -0
  455. package/dist/server/server/escape.js +2 -0
  456. package/dist/server/server/escape.js.map +1 -0
  457. package/dist/server/server/form-controls.js +3 -0
  458. package/dist/server/server/form-controls.js.map +1 -0
  459. package/dist/server/server/hydration-script.js +2 -0
  460. package/dist/server/server/hydration-script.js.map +1 -0
  461. package/dist/server/server/index.js +1 -0
  462. package/dist/server/server/node.js +2 -0
  463. package/dist/server/server/node.js.map +1 -0
  464. package/dist/server/server/portals.js +2 -0
  465. package/dist/server/server/portals.js.map +1 -0
  466. package/dist/server/server/render.js +2 -0
  467. package/dist/server/server/render.js.map +1 -0
  468. package/dist/server/server/serialize.js +2 -0
  469. package/dist/server/server/serialize.js.map +1 -0
  470. package/dist/server/server/stream.js +2 -0
  471. package/dist/server/server/stream.js.map +1 -0
  472. package/dist/server/server.js +1 -0
  473. package/dist/server/spread.js +2 -0
  474. package/dist/server/spread.js.map +1 -0
  475. package/dist/server/template.js +2 -0
  476. package/dist/server/template.js.map +1 -0
  477. package/dist/server/view-transition.js +2 -0
  478. package/dist/server/view-transition.js.map +1 -0
  479. package/dist/server-dev/attributes.js +195 -0
  480. package/dist/server-dev/attributes.js.map +1 -0
  481. package/dist/server-dev/autofocus.js +44 -0
  482. package/dist/server-dev/autofocus.js.map +1 -0
  483. package/dist/server-dev/class-style.js +196 -0
  484. package/dist/server-dev/class-style.js.map +1 -0
  485. package/dist/server-dev/component.js +41 -0
  486. package/dist/server-dev/component.js.map +1 -0
  487. package/dist/server-dev/control-flow/activity.js +40 -0
  488. package/dist/server-dev/control-flow/activity.js.map +1 -0
  489. package/dist/server-dev/control-flow/branch.js +103 -0
  490. package/dist/server-dev/control-flow/branch.js.map +1 -0
  491. package/dist/server-dev/control-flow/client-only.js +49 -0
  492. package/dist/server-dev/control-flow/client-only.js.map +1 -0
  493. package/dist/server-dev/control-flow/dynamic.js +105 -0
  494. package/dist/server-dev/control-flow/dynamic.js.map +1 -0
  495. package/dist/server-dev/control-flow/error-boundary.js +114 -0
  496. package/dist/server-dev/control-flow/error-boundary.js.map +1 -0
  497. package/dist/server-dev/control-flow/for.js +22 -0
  498. package/dist/server-dev/control-flow/for.js.map +1 -0
  499. package/dist/server-dev/control-flow/fragment.js +30 -0
  500. package/dist/server-dev/control-flow/fragment.js.map +1 -0
  501. package/dist/server-dev/control-flow/hot-link.js +56 -0
  502. package/dist/server-dev/control-flow/hot-link.js.map +1 -0
  503. package/dist/server-dev/control-flow/index-list.js +30 -0
  504. package/dist/server-dev/control-flow/index-list.js.map +1 -0
  505. package/dist/server-dev/control-flow/lazy.js +63 -0
  506. package/dist/server-dev/control-flow/lazy.js.map +1 -0
  507. package/dist/server-dev/control-flow/no-hydration.js +39 -0
  508. package/dist/server-dev/control-flow/no-hydration.js.map +1 -0
  509. package/dist/server-dev/control-flow/portal.js +133 -0
  510. package/dist/server-dev/control-flow/portal.js.map +1 -0
  511. package/dist/server-dev/control-flow/root-errors.js +32 -0
  512. package/dist/server-dev/control-flow/root-errors.js.map +1 -0
  513. package/dist/server-dev/control-flow/show.js +17 -0
  514. package/dist/server-dev/control-flow/show.js.map +1 -0
  515. package/dist/server-dev/control-flow/suspense-list.js +99 -0
  516. package/dist/server-dev/control-flow/suspense-list.js.map +1 -0
  517. package/dist/server-dev/control-flow/suspense.js +118 -0
  518. package/dist/server-dev/control-flow/suspense.js.map +1 -0
  519. package/dist/server-dev/control-flow/switch.js +89 -0
  520. package/dist/server-dev/control-flow/switch.js.map +1 -0
  521. package/dist/server-dev/derived.js +33 -0
  522. package/dist/server-dev/derived.js.map +1 -0
  523. package/dist/server-dev/element.js +65 -0
  524. package/dist/server-dev/element.js.map +1 -0
  525. package/dist/server-dev/events.js +264 -0
  526. package/dist/server-dev/events.js.map +1 -0
  527. package/dist/server-dev/extend.js +12 -0
  528. package/dist/server-dev/head/components.js +169 -0
  529. package/dist/server-dev/head/components.js.map +1 -0
  530. package/dist/server-dev/head/registry.js +67 -0
  531. package/dist/server-dev/head/registry.js.map +1 -0
  532. package/dist/server-dev/head/server-head.js +75 -0
  533. package/dist/server-dev/head/server-head.js.map +1 -0
  534. package/dist/server-dev/head/sink.js +95 -0
  535. package/dist/server-dev/head/sink.js.map +1 -0
  536. package/dist/server-dev/head/use-head.js +83 -0
  537. package/dist/server-dev/head/use-head.js.map +1 -0
  538. package/dist/server-dev/head/validate.js +267 -0
  539. package/dist/server-dev/head/validate.js.map +1 -0
  540. package/dist/server-dev/hydration.js +119 -0
  541. package/dist/server-dev/hydration.js.map +1 -0
  542. package/dist/server-dev/index.js +34 -0
  543. package/dist/server-dev/insert.js +356 -0
  544. package/dist/server-dev/insert.js.map +1 -0
  545. package/dist/server-dev/internal/claim.js +356 -0
  546. package/dist/server-dev/internal/claim.js.map +1 -0
  547. package/dist/server-dev/internal/css-units.js +25 -0
  548. package/dist/server-dev/internal/css-units.js.map +1 -0
  549. package/dist/server-dev/internal/diagnostics.js +37 -0
  550. package/dist/server-dev/internal/diagnostics.js.map +1 -0
  551. package/dist/server-dev/internal/early-events.js +75 -0
  552. package/dist/server-dev/internal/early-events.js.map +1 -0
  553. package/dist/server-dev/internal/hydration-hooks.js +26 -0
  554. package/dist/server-dev/internal/hydration-hooks.js.map +1 -0
  555. package/dist/server-dev/internal/hydration-scope.js +155 -0
  556. package/dist/server-dev/internal/hydration-scope.js.map +1 -0
  557. package/dist/server-dev/internal/names.js +34 -0
  558. package/dist/server-dev/internal/names.js.map +1 -0
  559. package/dist/server-dev/internal/portal-context.js +27 -0
  560. package/dist/server-dev/internal/portal-context.js.map +1 -0
  561. package/dist/server-dev/internal/react-names.js +115 -0
  562. package/dist/server-dev/internal/react-names.js.map +1 -0
  563. package/dist/server-dev/internal/reconcile.js +121 -0
  564. package/dist/server-dev/internal/reconcile.js.map +1 -0
  565. package/dist/server-dev/internal/stream-context.js +22 -0
  566. package/dist/server-dev/internal/stream-context.js.map +1 -0
  567. package/dist/server-dev/reactive.js +84 -0
  568. package/dist/server-dev/reactive.js.map +1 -0
  569. package/dist/server-dev/render.js +51 -0
  570. package/dist/server-dev/render.js.map +1 -0
  571. package/dist/server-dev/resource-hints.js +199 -0
  572. package/dist/server-dev/resource-hints.js.map +1 -0
  573. package/dist/server-dev/select-value.js +50 -0
  574. package/dist/server-dev/select-value.js.map +1 -0
  575. package/dist/server-dev/server/attributes.js +154 -0
  576. package/dist/server-dev/server/attributes.js.map +1 -0
  577. package/dist/server-dev/server/class-style.js +172 -0
  578. package/dist/server-dev/server/class-style.js.map +1 -0
  579. package/dist/server-dev/server/component.js +71 -0
  580. package/dist/server-dev/server/component.js.map +1 -0
  581. package/dist/server-dev/server/derived.js +25 -0
  582. package/dist/server-dev/server/derived.js.map +1 -0
  583. package/dist/server-dev/server/element.js +215 -0
  584. package/dist/server-dev/server/element.js.map +1 -0
  585. package/dist/server-dev/server/errors.js +25 -0
  586. package/dist/server-dev/server/errors.js.map +1 -0
  587. package/dist/server-dev/server/escape.js +118 -0
  588. package/dist/server-dev/server/escape.js.map +1 -0
  589. package/dist/server-dev/server/form-controls.js +192 -0
  590. package/dist/server-dev/server/form-controls.js.map +1 -0
  591. package/dist/server-dev/server/hydration-script.js +58 -0
  592. package/dist/server-dev/server/hydration-script.js.map +1 -0
  593. package/dist/server-dev/server/index.js +16 -0
  594. package/dist/server-dev/server/node.js +20 -0
  595. package/dist/server-dev/server/node.js.map +1 -0
  596. package/dist/server-dev/server/portals.js +98 -0
  597. package/dist/server-dev/server/portals.js.map +1 -0
  598. package/dist/server-dev/server/render.js +255 -0
  599. package/dist/server-dev/server/render.js.map +1 -0
  600. package/dist/server-dev/server/serialize.js +314 -0
  601. package/dist/server-dev/server/serialize.js.map +1 -0
  602. package/dist/server-dev/server/stream.js +234 -0
  603. package/dist/server-dev/server/stream.js.map +1 -0
  604. package/dist/server-dev/server.js +16 -0
  605. package/dist/server-dev/spread.js +295 -0
  606. package/dist/server-dev/spread.js.map +1 -0
  607. package/dist/server-dev/template.js +119 -0
  608. package/dist/server-dev/template.js.map +1 -0
  609. package/dist/server-dev/view-transition.js +89 -0
  610. package/dist/server-dev/view-transition.js.map +1 -0
  611. package/package.json +136 -4
@@ -0,0 +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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EAAMf,EAAU+C,EAAWV,EAAKnC,GAAS,KAAMK,EAASN,EAAYC,CAAO,CAAC,EACtFkD,CACF,CAAC,CACH,QAAU,CACR,aAAaD,CAAK,EAClB,EAAI,SAAW,GACf,IAAK,IAAMhC,KAAWkB,EAAI,MAAM,OAAO,CAAC,EAAGlB,EAAQ,CACrD,CACF,C"}
@@ -0,0 +1,2 @@
1
+ import{invalid as e}from"./errors.js";const t=/[<>&\u2028\u2029]/g;function n(e){return e.replace(t,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function r(e){return Number.isFinite(e)&&!Object.is(e,-0)?e:{$:`num`,v:Object.is(e,-0)?`-0`:String(e)}}const i=/* @__PURE__ */ new Map([[`Int8Array`,Int8Array],[`Uint8Array`,Uint8Array],[`Uint8ClampedArray`,Uint8ClampedArray],[`Int16Array`,Int16Array],[`Uint16Array`,Uint16Array],[`Int32Array`,Int32Array],[`Uint32Array`,Uint32Array],[`Float32Array`,Float32Array],[`Float64Array`,Float64Array],[`BigInt64Array`,BigInt64Array],[`BigUint64Array`,BigUint64Array],[`DataView`,DataView]]);function a(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function o(e){let t;try{t=atob(e)}catch{throw f(`binary data is not valid base64.`)}let n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function s(e){for(let[t,n]of i)if(e instanceof n)return t}function c(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function l(t){let i=[],o=/* @__PURE__ */ new Map,l=[],u=e=>{let t=o.get(e);if(t!==void 0)return t;let n=i.length;return i.push(null),o.set(e,n),l.push({value:e,slot:n}),n},d=t=>{if(t===void 0)return{$:`u`};if(t===null||typeof t==`boolean`||typeof t==`string`)return t;if(typeof t==`number`)return r(t);if(typeof t==`bigint`)return{$:`big`,v:t.toString()};if(typeof t==`object`)return{$:`ref`,i:u(t)};throw e(`UNSERIALIZABLE_VALUE`,`A ${typeof t} cannot be serialized.`)},f=t=>{if(t instanceof Date)return{$:`date`,v:d(t.getTime())};if(t instanceof ArrayBuffer)return{$:`buf`,v:a(new Uint8Array(t))};if(ArrayBuffer.isView(t)){let e=s(t);if(e!==void 0)return{$:`bin`,k:e,v:a(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}}if(t instanceof URL)return{$:`url`,v:t.href};if(t instanceof Map){let e=[];for(let[n,r]of t)e.push([d(n),d(r)]);return{$:`map`,e}}if(t instanceof Set){let e=[];for(let n of t)e.push(d(n));return{$:`set`,e}}if(Array.isArray(t)){let e=[];for(let n=0;n<t.length;n+=1)e.push(d(t[n]));return{$:`arr`,e}}if(!c(t))throw e(`UNSERIALIZABLE_VALUE`,`Only plain objects, arrays, Map, Set, Date, URL, ArrayBuffer and typed arrays can be serialized.`);let n=[];for(let e of Object.keys(t))n.push([e,d(Reflect.get(t,e))]);return{$:`obj`,e:n}},p=d(t);for(let e=0;e<l.length;e+=1){let t=l[e];if(t===void 0)break;i[t.slot]=f(t.value)}return n(JSON.stringify({r:p,t:i}))}function u(e,t){return Object.hasOwn(e,t)?Reflect.get(e,t):void 0}function d(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function f(e){return/* @__PURE__ */ TypeError(`deserialize(): ${e}`)}function p(e){if(e===null||typeof e==`boolean`||typeof e==`string`||typeof e==`number`)return e;if(!d(e))throw f(`unexpected value.`);let t=u(e,`$`);if(t!==`u`){if(t===`num`){let t=u(e,`v`);if(t===`NaN`)return NaN;if(t===`Infinity`)return 1/0;if(t===`-Infinity`)return-1/0;if(t===`-0`)return-0;throw f(`unknown number.`)}if(t===`big`){let t=u(e,`v`);if(typeof t!=`string`)throw f(`bigint without digits.`);return BigInt(t)}throw f(`unknown tag.`)}}function m(e,t){if(d(e)&&u(e,`$`)===`ref`){let n=u(e,`i`);if(typeof n!=`number`||!Number.isInteger(n)||n<0||n>=t.length)throw f(`reference outside the table.`);return t[n]}return p(e)}function h(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function g(e){if(!d(e))throw f(`table entry is not an object.`);let t=u(e,`$`);if(t===`obj`)return Object.create(null);if(t===`arr`)return[];if(t===`map`)return/* @__PURE__ */ new Map;if(t===`set`)return/* @__PURE__ */ new Set;if(t===`date`){let t=p(u(e,`v`));if(typeof t!=`number`)throw f(`date without a time.`);return new Date(t)}if(t===`buf`||t===`bin`){let n=u(e,`v`);if(typeof n!=`string`)throw f(`binary entry without data.`);let r=o(n),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);if(t===`buf`)return a;let s=u(e,`k`),c=typeof s==`string`?i.get(s):void 0;if(c===void 0)throw f(`unknown binary kind.`);try{return new c(a)}catch{throw f(`binary data does not fit its type.`)}}if(t===`url`){let t=u(e,`v`);if(typeof t!=`string`)throw f(`url without an href.`);return new URL(t)}throw f(`unknown table entry.`)}function _(e,t,n){let r=u(e,`$`);if(r===`date`||r===`url`||r===`buf`||r===`bin`)return;let i=u(e,`e`);if(!Array.isArray(i))throw f(`entry without a list.`);if(r===`obj`&&typeof t==`object`&&t)for(let e of i){if(!Array.isArray(e)||e.length!==2||typeof e[0]!=`string`)throw f(`object entry is not a key and value.`);h(t,e[0],m(e[1],n))}else if(r===`arr`&&Array.isArray(t))for(let e of i)t.push(m(e,n));else if(r===`map`&&t instanceof Map)for(let e of i){if(!Array.isArray(e)||e.length!==2)throw f(`map entry is not a pair.`);t.set(m(e[0],n),m(e[1],n))}else if(r===`set`&&t instanceof Set)for(let e of i)t.add(m(e,n));else throw f(`entry does not match its tag.`)}function v(e){let t=JSON.parse(e);if(!d(t))throw f(`payload is not an object.`);let n=u(t,`t`);if(!Array.isArray(n))throw f(`payload has no table.`);let r=[];for(let e of n)r.push(g(e));for(let e=0;e<n.length;e+=1){let t=n[e];d(t)&&_(t,r[e],r)}return m(u(t,`r`),r)}export{v as deserialize,l as serialize};
2
+ //# sourceMappingURL=serialize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serialize.js","names":["UNSAFE_TEXT","escapeForScript","json","char","encodeNumber","value","BINARY_KINDS","toBase64","binary","offset","bytes","fromBase64","text","malformed","i","binaryKindOf","name","ctor","isPlainObject","proto","serialize","table","index","queue","slotOf","existing","slot","encodeValue","invalid","encodeEntry","kind","pairs","key","item","items","root","data","head","entry","own","record","isRecord","detail","decodeScalar","tag","decodeValue","defineOwn","target","createEntry","time","buffer","href","fillEntry","pair","deserialize","payload","made"],"sources":["../../../src/server/serialize.ts"],"sourcesContent":["import { invalid } from \"./errors\";\n\n/*\n * Wire format: {\"r\": <value>, \"t\": [<entry>, ...]}. Containers (objects, arrays, Map, Set, Date,\n * URL) live in the table and refer to each other by index, so cycles and shared references keep\n * their identity and the walk needs no recursion. A value is a JSON primitive, or a tagged object:\n * {\"$\":\"u\"} undefined\n * {\"$\":\"num\",\"v\":\"NaN\"|\"Infinity\"|\"-Infinity\"|\"-0\"}\n * {\"$\":\"big\",\"v\":\"<decimal>\"} bigint\n * {\"$\":\"ref\",\"i\":<index>} a table entry\n * Table entries are {\"$\":\"obj\",\"e\":[[key,value],...]}, {\"$\":\"arr\",\"e\":[...]},\n * {\"$\":\"map\",\"e\":[[key,value],...]}, {\"$\":\"set\",\"e\":[...]}, {\"$\":\"date\",\"v\":<number>},\n * {\"$\":\"url\",\"v\":\"<href>\"}. Plain objects are read with own properties only and rebuilt with a\n * null prototype, so \"__proto__\" or \"constructor\" keys are ordinary data.\n */\n\n/** Characters that may not appear raw in the output: they would end a script element or a line. */\nconst UNSAFE_TEXT = /[<>&\\u2028\\u2029]/g;\n\n/** Escapes text for `<script type=\"application/json\">`: the JSON stays valid, the markup cannot close. */\nfunction escapeForScript(json: string): string {\n return json.replace(\n UNSAFE_TEXT,\n (char) => `\\\\u${char.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\n/** Encodes a number that JSON cannot carry exactly. */\nfunction encodeNumber(value: number): unknown {\n if (Number.isFinite(value) && !Object.is(value, -0)) return value;\n return { $: \"num\", v: Object.is(value, -0) ? \"-0\" : String(value) };\n}\n\n/** Binary types the wire format carries, by the name written on the wire. */\ntype BinaryConstructor = new (buffer: ArrayBuffer) => ArrayBufferView;\nconst BINARY_KINDS: ReadonlyMap<string, BinaryConstructor> = new Map<string, BinaryConstructor>([\n [\"Int8Array\", Int8Array],\n [\"Uint8Array\", Uint8Array],\n [\"Uint8ClampedArray\", Uint8ClampedArray],\n [\"Int16Array\", Int16Array],\n [\"Uint16Array\", Uint16Array],\n [\"Int32Array\", Int32Array],\n [\"Uint32Array\", Uint32Array],\n [\"Float32Array\", Float32Array],\n [\"Float64Array\", Float64Array],\n [\"BigInt64Array\", BigInt64Array],\n [\"BigUint64Array\", BigUint64Array],\n [\"DataView\", DataView],\n]);\n\n/** Base64 of `bytes`, converted in chunks so a large buffer cannot overflow the call stack. */\nfunction toBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let offset = 0; offset < bytes.length; offset += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));\n }\n return btoa(binary);\n}\n\n/** Bytes of a base64 text; malformed text throws a TypeError. */\nfunction fromBase64(text: string): Uint8Array {\n let binary: string;\n try {\n binary = atob(text);\n } catch {\n throw malformed(\"binary data is not valid base64.\");\n }\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/** The wire name of a typed array or DataView, or undefined for anything else. */\nfunction binaryKindOf(value: object): string | undefined {\n for (const [name, ctor] of BINARY_KINDS) {\n if (value instanceof ctor) return name;\n }\n return undefined;\n}\n\n/** True for plain objects: prototype is Object.prototype or none. */\nfunction isPlainObject(value: object): boolean {\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Serializes data for embedding in a page, as JSON that is safe inside a\n * `<script type=\"application/json\">` element. It carries what JSON cannot: undefined, NaN,\n * infinities, -0, bigint, Date, URL, Map, Set, ArrayBuffer, typed arrays and DataView (copied: views\n * that shared a buffer come back as independent copies), plus shared references and cycles between\n * plain objects and arrays. Read it back with {@link deserialize}.\n *\n * @param data The value to serialize.\n * @returns JSON text with `<`, `>`, `&`, U+2028 and U+2029 written as `\\u` escapes, so it cannot\n * close the script element.\n * @throws TypeError `UNSERIALIZABLE_VALUE` for a function, a symbol, or an object that is not one of\n * the supported kinds (a class instance, for example).\n * @example\n * import { serialize } from \"@shadow-js/web/server\";\n *\n * const data = { user: { name: \"Ada\" }, seen: new Set([1, 2]), at: new Date(0) };\n * const tag = `<script type=\"application/json\" id=\"data\">${serialize(data)}</script>`;\n * @see deserialize\n * @since 1.0.0\n */\nexport function serialize(data: unknown): string {\n const table: unknown[] = [];\n const index = new Map<object, number>();\n const queue: Array<{ readonly value: object; readonly slot: number }> = [];\n\n const slotOf = (value: object): number => {\n const existing = index.get(value);\n if (existing !== undefined) return existing;\n const slot = table.length;\n table.push(null);\n index.set(value, slot);\n queue.push({ value, slot });\n return slot;\n };\n\n const encodeValue = (value: unknown): unknown => {\n if (value === undefined) return { $: \"u\" };\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") return value;\n if (typeof value === \"number\") return encodeNumber(value);\n if (typeof value === \"bigint\") return { $: \"big\", v: value.toString() };\n if (typeof value === \"object\") return { $: \"ref\", i: slotOf(value) };\n throw invalid(\"UNSERIALIZABLE_VALUE\", `A ${typeof value} cannot be serialized.`);\n };\n\n const encodeEntry = (value: object): unknown => {\n if (value instanceof Date) return { $: \"date\", v: encodeValue(value.getTime()) };\n if (value instanceof ArrayBuffer) return { $: \"buf\", v: toBase64(new Uint8Array(value)) };\n if (ArrayBuffer.isView(value)) {\n const kind = binaryKindOf(value);\n if (kind !== undefined) {\n const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n return { $: \"bin\", k: kind, v: toBase64(bytes) };\n }\n }\n if (value instanceof URL) return { $: \"url\", v: value.href };\n if (value instanceof Map) {\n const pairs: unknown[] = [];\n for (const [key, item] of value) pairs.push([encodeValue(key), encodeValue(item)]);\n return { $: \"map\", e: pairs };\n }\n if (value instanceof Set) {\n const items: unknown[] = [];\n for (const item of value) items.push(encodeValue(item));\n return { $: \"set\", e: items };\n }\n if (Array.isArray(value)) {\n const items: unknown[] = [];\n // An index loop, so holes in a sparse array become undefined instead of being skipped.\n for (let i = 0; i < value.length; i += 1) items.push(encodeValue(value[i]));\n return { $: \"arr\", e: items };\n }\n if (!isPlainObject(value)) {\n throw invalid(\n \"UNSERIALIZABLE_VALUE\",\n \"Only plain objects, arrays, Map, Set, Date, URL, ArrayBuffer and typed arrays can be serialized.\",\n );\n }\n const pairs: unknown[] = [];\n for (const key of Object.keys(value)) pairs.push([key, encodeValue(Reflect.get(value, key))]);\n return { $: \"obj\", e: pairs };\n };\n\n const root = encodeValue(data);\n for (let head = 0; head < queue.length; head += 1) {\n const entry = queue[head];\n if (entry === undefined) break;\n table[entry.slot] = encodeEntry(entry.value);\n }\n return escapeForScript(JSON.stringify({ r: root, t: table }));\n}\n\n/** Reads an own property of a parsed JSON object; never reaches the prototype chain. */\nfunction own(record: object, key: string): unknown {\n return Object.hasOwn(record, key) ? Reflect.get(record, key) : undefined;\n}\n\n/** True for a non-null, non-array object. */\nfunction isRecord(value: unknown): value is object {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Throws the TypeError for a payload that is not in the wire format. */\nfunction malformed(detail: string): TypeError {\n return new TypeError(`deserialize(): ${detail}`);\n}\n\n/** Decodes a value that cannot refer to other entries (used while the table is created). */\nfunction decodeScalar(value: unknown): unknown {\n if (\n value === null ||\n typeof value === \"boolean\" ||\n typeof value === \"string\" ||\n typeof value === \"number\"\n ) {\n return value;\n }\n if (!isRecord(value)) throw malformed(\"unexpected value.\");\n const tag = own(value, \"$\");\n if (tag === \"u\") return undefined;\n if (tag === \"num\") {\n const text = own(value, \"v\");\n if (text === \"NaN\") return Number.NaN;\n if (text === \"Infinity\") return Number.POSITIVE_INFINITY;\n if (text === \"-Infinity\") return Number.NEGATIVE_INFINITY;\n if (text === \"-0\") return -0;\n throw malformed(\"unknown number.\");\n }\n if (tag === \"big\") {\n const text = own(value, \"v\");\n if (typeof text !== \"string\") throw malformed(\"bigint without digits.\");\n return BigInt(text);\n }\n throw malformed(\"unknown tag.\");\n}\n\n/**\n * Rebuilds a value from the table. Plain objects get a null prototype; their keys are defined as\n * own data properties, so no key can reach or replace a prototype.\n */\nfunction decodeValue(value: unknown, table: readonly unknown[]): unknown {\n if (isRecord(value) && own(value, \"$\") === \"ref\") {\n const slot = own(value, \"i\");\n if (typeof slot !== \"number\" || !Number.isInteger(slot) || slot < 0 || slot >= table.length) {\n throw malformed(\"reference outside the table.\");\n }\n return table[slot];\n }\n return decodeScalar(value);\n}\n\n/** Defines an own data property; never assigns, so no setter or prototype is involved. */\nfunction defineOwn(target: object, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** Creates an empty container for a table entry, or the value of a scalar entry. */\nfunction createEntry(entry: unknown): unknown {\n if (!isRecord(entry)) throw malformed(\"table entry is not an object.\");\n const tag = own(entry, \"$\");\n if (tag === \"obj\") return Object.create(null) as object;\n if (tag === \"arr\") return [];\n if (tag === \"map\") return new Map<unknown, unknown>();\n if (tag === \"set\") return new Set<unknown>();\n if (tag === \"date\") {\n const time = decodeScalar(own(entry, \"v\"));\n if (typeof time !== \"number\") throw malformed(\"date without a time.\");\n return new Date(time);\n }\n if (tag === \"buf\" || tag === \"bin\") {\n const text = own(entry, \"v\");\n if (typeof text !== \"string\") throw malformed(\"binary entry without data.\");\n const bytes = fromBase64(text);\n // A copy that owns exactly these bytes, so a view never exposes a larger buffer.\n const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n if (tag === \"buf\") return buffer;\n const kind = own(entry, \"k\");\n const ctor = typeof kind === \"string\" ? BINARY_KINDS.get(kind) : undefined;\n if (ctor === undefined) throw malformed(\"unknown binary kind.\");\n try {\n return new ctor(buffer as ArrayBuffer);\n } catch {\n throw malformed(\"binary data does not fit its type.\");\n }\n }\n if (tag === \"url\") {\n const href = own(entry, \"v\");\n if (typeof href !== \"string\") throw malformed(\"url without an href.\");\n return new URL(href);\n }\n throw malformed(\"unknown table entry.\");\n}\n\n/** Fills one container from its entry list. Date and URL entries are already complete. */\nfunction fillEntry(entry: object, target: unknown, table: readonly unknown[]): void {\n const tag = own(entry, \"$\");\n if (tag === \"date\" || tag === \"url\" || tag === \"buf\" || tag === \"bin\") return;\n const items = own(entry, \"e\");\n if (!Array.isArray(items)) throw malformed(\"entry without a list.\");\n if (tag === \"obj\" && target !== null && typeof target === \"object\") {\n for (const pair of items) {\n if (!Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== \"string\") {\n throw malformed(\"object entry is not a key and value.\");\n }\n defineOwn(target, pair[0], decodeValue(pair[1], table));\n }\n } else if (tag === \"arr\" && Array.isArray(target)) {\n for (const item of items) target.push(decodeValue(item, table));\n } else if (tag === \"map\" && target instanceof Map) {\n for (const pair of items) {\n if (!Array.isArray(pair) || pair.length !== 2) throw malformed(\"map entry is not a pair.\");\n target.set(decodeValue(pair[0], table), decodeValue(pair[1], table));\n }\n } else if (tag === \"set\" && target instanceof Set) {\n for (const item of items) target.add(decodeValue(item, table));\n } else {\n throw malformed(\"entry does not match its tag.\");\n }\n}\n\n/**\n * Rebuilds the value {@link serialize} wrote, with its shared references and cycles. Plain objects\n * come back with a null prototype (so a `__proto__` key is ordinary data), and malformed input throws\n * instead of producing a partial value. No code is evaluated.\n *\n * @param text JSON text produced by {@link serialize}.\n * @returns The rebuilt value.\n * @throws SyntaxError when `text` is not JSON; TypeError when the JSON is not in the format\n * `serialize` writes.\n * @example\n * import { deserialize, serialize } from \"@shadow-js/web/server\";\n *\n * const copy = deserialize(serialize({ tags: new Set([\"a\"]), total: 10n })) as {\n * tags: Set<string>;\n * total: bigint;\n * };\n * copy.tags.has(\"a\"); // true\n * @see serialize\n * @since 1.0.0\n */\nexport function deserialize(text: string): unknown {\n const payload: unknown = JSON.parse(text);\n if (!isRecord(payload)) throw malformed(\"payload is not an object.\");\n const table = own(payload, \"t\");\n if (!Array.isArray(table)) throw malformed(\"payload has no table.\");\n const made: unknown[] = [];\n for (const entry of table) made.push(createEntry(entry));\n for (let slot = 0; slot < table.length; slot += 1) {\n const entry = table[slot];\n if (isRecord(entry)) fillEntry(entry, made[slot], made);\n }\n return decodeValue(own(payload, \"r\"), made);\n}\n"],"mappings":"A,sCAiBA,MAAMA,EAAc,qBAGpB,SAASC,EAAgB,EAAsB,CAC7C,OAAOC,EAAK,QACVF,EACC,GAAS,MAAMG,EAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,GACjE,CACF,CAGA,SAASC,EAAa,EAAwB,CAE5C,OADI,OAAO,SAASC,CAAK,GAAK,CAAC,OAAO,GAAGA,EAAO,EAAE,EAAUA,EACrD,CAAE,EAAG,MAAO,EAAG,OAAO,GAAGA,EAAO,EAAE,EAAI,KAAO,OAAOA,CAAK,CAAE,CACpE,CAIA,MAAMC,kBAAuD,IAAI,IAA+B,CAC9F,CAAC,YAAa,SAAS,EACvB,CAAC,aAAc,UAAU,EACzB,CAAC,oBAAqB,iBAAiB,EACvC,CAAC,aAAc,UAAU,EACzB,CAAC,cAAe,WAAW,EAC3B,CAAC,aAAc,UAAU,EACzB,CAAC,cAAe,WAAW,EAC3B,CAAC,eAAgB,YAAY,EAC7B,CAAC,eAAgB,YAAY,EAC7B,CAAC,gBAAiB,aAAa,EAC/B,CAAC,iBAAkB,cAAc,EACjC,CAAC,WAAY,QAAQ,CACvB,CAAC,EAGD,SAASC,EAAS,EAA2B,CAC3C,IAAIC,EAAS,GACb,IAAK,IAAIC,EAAS,EAAGA,EAASC,EAAM,OAAQ,GAAU,MACpD,GAAU,OAAO,aAAa,GAAGA,EAAM,SAASD,EAAQA,EAAS,KAAM,CA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IuB,IAAQ,OAAS,MAAM,QAAQG,CAAM,EAC9C,IAAK,IAAMd,KAAQC,EAAOa,EAAO,KAAKF,EAAYZ,EAAMZ,CAAK,CAAC,OACzD,GAAIuB,IAAQ,OAASG,aAAkB,IAC5C,IAAK,IAAMM,KAAQnB,EAAO,CACxB,GAAI,CAAC,MAAM,QAAQmB,CAAI,GAAKA,EAAK,SAAW,EAAG,MAAMxC,EAAU,0BAA0B,EACzFkC,EAAO,IAAIF,EAAYQ,EAAK,GAAIhC,CAAK,EAAGwB,EAAYQ,EAAK,GAAIhC,CAAK,CAAC,CACrE,MACK,GAAIuB,IAAQ,OAASG,aAAkB,IAC5C,IAAK,IAAMd,KAAQC,EAAOa,EAAO,IAAIF,EAAYZ,EAAMZ,CAAK,CAAC,OAE7D,MAAMR,EAAU,+BAA+B,CAEnD,CAsBA,SAAgByC,EAAY,EAAuB,CACjD,IAAMC,EAAmB,KAAK,MAAM3C,CAAI,EACxC,GAAI,CAAC6B,EAASc,CAAO,EAAG,MAAM1C,EAAU,2BAA2B,EACnE,IAAMQ,EAAQkB,EAAIgB,EAAS,GAAG,EAC9B,GAAI,CAAC,MAAM,QAAQlC,CAAK,EAAG,MAAMR,EAAU,uBAAuB,EAClE,IAAM2C,EAAkB,CAAC,EACzB,IAAK,IAAMlB,KAASjB,EAAOmC,EAAK,KAAKR,EAAYV,CAAK,CAAC,EACvD,IAAK,IAAIZ,EAAO,EAAGA,EAAOL,EAAM,OAAQ,GAAQ,EAAG,CACjD,IAAMiB,EAAQjB,EAAMK,GAChBe,EAASH,CAAK,GAAGc,EAAUd,EAAOkB,EAAK9B,GAAO8B,CAAI,CACxD,CACA,OAAOX,EAAYN,EAAIgB,EAAS,GAAG,EAAGC,CAAI,CAC5C,C"}
@@ -0,0 +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{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};
2
+ //# sourceMappingURL=stream.js.map
@@ -0,0 +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,CAAC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C,CAAM,CACrB,CACF,CAAC,CACH,C"}
@@ -0,0 +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};
@@ -0,0 +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};
2
+ //# sourceMappingURL=spread.js.map
@@ -0,0 +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,G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uB,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"}
@@ -0,0 +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};
2
+ //# sourceMappingURL=template.js.map
@@ -0,0 +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"}
@@ -0,0 +1,2 @@
1
+ import{flushSync as e}from"@shadow-js/core";function t(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 n(e){return()=>e.children}export{n as ViewTransition,t as startViewTransition};
2
+ //# sourceMappingURL=view-transition.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"view-transition.js","names":["startViewTransition","doc","flushSync","update","error","failure","callback","types","options","ViewTransition","props"],"sources":["../../src/view-transition.ts"],"sourcesContent":["import { type Accessor, flushSync, untrack, useEffect, useId } from \"@shadow-js/core\";\n\n/** The subset of `Document` the View Transitions API adds (not yet in every TypeScript lib). */\ntype ViewTransitionDocument = Document & {\n startViewTransition?: (callback: (() => void) | { update: () => void; types?: string[] }) => {\n finished: Promise<unknown>;\n };\n};\n\n/**\n * Options of {@link startViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionOptions {\n /**\n * Transition types for this update. CSS selects phases with `:active-view-transition-type(name)`,\n * so one update can animate differently from another (for example forward and back navigation).\n * Ignored where the browser has no View Transitions API.\n * @default undefined (no types: the update runs as a plain transition)\n */\n readonly types?: readonly string[];\n}\n\n/**\n * Runs `update` inside a browser view transition, so the change animates from the old screen to the\n * new one, and resolves when the animation has finished. Without the API (older browsers, or a\n * server) the update runs at once and the promise resolves. Motion preferences are handled by the\n * browser and by the CSS of the page (`prefers-reduced-motion`).\n *\n * The update runs synchronously inside the transition's callback, flushed with {@link flushSync},\n * so the new DOM is what the browser captures. An error thrown by the update rejects the promise.\n *\n * @param update Changes the state the page shows. Called once, synchronously inside the transition\n * (or at once without the API).\n * @param options `types` for CSS phase selectors; see {@link ViewTransitionOptions}. Undefined\n * starts a transition without types.\n * @returns A promise that resolves when the transition has finished (or at once without the API).\n * It rejects with the error `update` threw.\n * @throws Nothing synchronously. An error thrown by `update` rejects the returned promise.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { startViewTransition } from \"@shadow-js/web\";\n *\n * const [, setPage] = useSignal(\"home\");\n * async function openSettings() {\n * await startViewTransition(() => setPage(\"settings\"), { types: [\"forward\"] });\n * }\n * @see ViewTransition\n * @since 1.0.0\n */\nexport function startViewTransition(\n update: () => void,\n options?: ViewTransitionOptions,\n): Promise<void> {\n const doc = typeof document === \"undefined\" ? undefined : (document as ViewTransitionDocument);\n if (doc === undefined || typeof doc.startViewTransition !== \"function\") {\n try {\n flushSync(update);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve();\n }\n let failure: { readonly error: unknown } | undefined;\n const callback = (): void => {\n try {\n flushSync(update);\n } catch (error) {\n failure = { error };\n }\n };\n const types = options?.types;\n const transition = doc.startViewTransition(\n types === undefined || types.length === 0 ? callback : { update: callback, types: [...types] },\n );\n return transition.finished.then(() => {\n if (failure !== undefined) throw failure.error;\n });\n}\n\n/**\n * Props of {@link ViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionProps {\n /**\n * The transition name (`view-transition-name`). Elements with the same name in the old and the new\n * screen are animated as one (`share`); an element that appears or disappears with a name animates\n * in (`enter`) or out (`exit`). `true` makes a unique name.\n * @default undefined (no inline `view-transition-name` is set on the element)\n */\n readonly name?: string | true;\n /**\n * The transition class (`view-transition-class`), to style a group of named elements at once.\n * @default undefined (no inline `view-transition-class` is set)\n */\n readonly class?: string;\n /**\n * The content. Its first element receives the name and class.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Gives the first element of its children a view transition name and class, so the browser animates\n * that element between the old and the new screen: it enters (an element that appears with the name),\n * exits (one that disappears), updates (the same name with new content) and shares (the same name on\n * both screens, moved or resized). The phases are the browser's own; select them in CSS with\n * `::view-transition-old(name)`, `::view-transition-new(name)` and `:active-view-transition-type()`.\n * `exit=\"none\"` is not offered: the browser decides an exit before the update runs.\n *\n * No wrapper element is added. Without the browser API the name and class are only styles, so the\n * component renders correctly everywhere.\n *\n * @param props See {@link ViewTransitionProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ViewTransition } from \"@shadow-js/web\";\n *\n * function Hero() {\n * const [src] = useSignal(\"/hero.png\");\n * return (\n * <ViewTransition name=\"hero\">\n * <img src={src()} />\n * </ViewTransition>\n * );\n * }\n * @see startViewTransition\n * @since 1.0.0\n */\nexport function ViewTransition(props: ViewTransitionProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // Built once, when the parent first renders it (as Activity does): the server builds it at the same point.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = untrack(() => props.children);\n }\n return built;\n };\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const generated = props.name === true ? `vt-${useId()}` : undefined;\n // Runs after the DOM is committed, so the element it styles exists.\n useEffect(() => {\n const element = firstElementBetween(start, end);\n if (element === null) return;\n const name = generated ?? (typeof props.name === \"string\" ? props.name : undefined);\n setOrClear(element, \"view-transition-name\", name);\n setOrClear(element, \"view-transition-class\", props.class);\n });\n return () => [start, contentValue(), end];\n}\n\n/** The first element between two anchors, or null. */\nfunction firstElementBetween(start: Node, end: Node): HTMLElement | null {\n for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) {\n if (node.nodeType === 1) return node as HTMLElement;\n }\n return null;\n}\n\nfunction setOrClear(element: HTMLElement, property: string, value: string | undefined): void {\n if (value === undefined || value === \"\") element.style.removeProperty(property);\n else element.style.setProperty(property, value);\n}\n"],"mappings":"A,4CAkDA,SAAgBA,EACd,EACA,EACe,CACf,IAAMC,EAAM,OAAO,SAAa,IAAc,IAAA,GAAa,SAC3D,GAAIA,IAAQ,IAAA,IAAa,OAAOA,EAAI,qBAAwB,WAAY,CACtE,GAAI,CACFC,EAAUC,CAAM,CAClB,OAASC,EAAO,CACd,OAAO,QAAQ,OAAOA,CAAK,CAC7B,CACA,OAAO,QAAQ,QAAQ,CACzB,CACA,IAAIC,EACEC,MAAuB,CAC3B,GAAI,CACFJ,EAAUC,CAAM,CAClB,OAASC,EAAO,CACd,EAAU,CAAE,OAAM,CACpB,CACF,EACMG,EAAQC,GAAS,MAIvB,OAHmBP,EAAI,oBACrBM,IAAU,IAAA,IAAaA,EAAM,SAAW,EAAID,EAAW,CAAE,OAAQA,EAAU,MAAO,CAAC,GAAGC,CAAK,CAAE,CAE/E,CAAC,CAAC,SAAS,SAAW,CACpC,GAAIF,IAAY,IAAA,GAAW,MAAMA,EAAQ,KAC3C,CAAC,CACH,CAsDA,SAAgBI,EAAe,EAA+C,CAC5D,UAAaC,EAAM,QAuBrC,C"}
@@ -0,0 +1,195 @@
1
+ import { invalidAttributeName, warnOnce } from "./internal/diagnostics.js";
2
+ // src/attributes.ts
3
+ /** Names that can appear in markup: an XML-name subset without `@` or whitespace. */
4
+ const ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;
5
+ /**
6
+ * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values
7
+ * (`animate`, `set`) are checked too: with `attributeName="href"` they write an `href` by animation.
8
+ */
9
+ const URL_ATTRIBUTES = /* @__PURE__ */ new Set([
10
+ "href",
11
+ "src",
12
+ "action",
13
+ "formaction",
14
+ "xlink:href",
15
+ "srcdoc",
16
+ "poster",
17
+ "data",
18
+ "values",
19
+ "from",
20
+ "to",
21
+ "by"
22
+ ]);
23
+ /** Enumerated attributes where `false` is a real value ("false") rather than an absence. */
24
+ const ENUMERATED_ATTRIBUTES = /* @__PURE__ */ new Set([
25
+ "draggable",
26
+ "spellcheck",
27
+ "contenteditable"
28
+ ]);
29
+ /** URL prefixes (after normalization) that are never written. */
30
+ const UNSAFE_URL_PREFIXES = [
31
+ "javascript:",
32
+ "data:text/html",
33
+ "vbscript:"
34
+ ];
35
+ /**
36
+ * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the
37
+ * ones that come from spread, so no unvalidated name reaches `setAttribute`.
38
+ * @internal
39
+ */
40
+ function assertAttributeName(name) {
41
+ if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);
42
+ }
43
+ /** True for `aria-*`, `data-*` and the enumerated attributes: their boolean values are strings. */
44
+ function isStringValued(lowerName) {
45
+ return lowerName.startsWith("aria-") || lowerName.startsWith("data-") || ENUMERATED_ATTRIBUTES.has(lowerName);
46
+ }
47
+ /** Removes C0 and C1 control characters. Written as a loop so no control character appears in a regex. */
48
+ function stripControls(text) {
49
+ let kept = "";
50
+ for (const char of text) {
51
+ const code = char.charCodeAt(0);
52
+ if (code > 31 && (code < 127 || code > 159)) kept += char;
53
+ }
54
+ return kept;
55
+ }
56
+ /** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */
57
+ function isUnsafeUrl(value) {
58
+ const normalized = stripControls(value).trim().toLowerCase();
59
+ return UNSAFE_URL_PREFIXES.some((prefix) => normalized.startsWith(prefix));
60
+ }
61
+ /**
62
+ * Reports whether writing `value` to the attribute `name` would run script: the URL check that
63
+ * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer
64
+ * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,
65
+ * `formaction`, `xlink:href`, `srcdoc`, `poster`, `data`) are unsafe when, after removing control
66
+ * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or
67
+ * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,
68
+ * each `;`-separated entry of `values` on its own.
69
+ *
70
+ * @param name Attribute name, in any case.
71
+ * @param value The text that would be written.
72
+ * @returns `true` when the value must not be written; `false` for every other attribute or value.
73
+ * @example
74
+ * import { isUnsafeUrlAttribute } from "@shadow-js/web/extend";
75
+ *
76
+ * isUnsafeUrlAttribute("href", " JavaScript:alert(1)"); // true
77
+ * isUnsafeUrlAttribute("href", "https://example.com"); // false
78
+ * isUnsafeUrlAttribute("title", "javascript:alert(1)"); // false: not a URL attribute
79
+ * @see setAttribute
80
+ * @since 1.0.0
81
+ */
82
+ function isUnsafeUrlAttribute(name, value) {
83
+ const lowerName = name.toLowerCase();
84
+ if (!URL_ATTRIBUTES.has(lowerName)) return false;
85
+ return lowerName === "values" ? value.split(";").some(isUnsafeUrl) : isUnsafeUrl(value);
86
+ }
87
+ /** Text to write for `value`, or null when the attribute must be removed. */
88
+ function attributeText(lowerName, value) {
89
+ if (value === null || value === void 0) return null;
90
+ if (value === false) return isStringValued(lowerName) ? "false" : null;
91
+ if (value === true) return isStringValued(lowerName) ? "true" : "";
92
+ return String(value);
93
+ }
94
+ /** The part of a qualified name after the prefix (`xlink:href` gives `href`). */
95
+ function localPart(qualified) {
96
+ const colon = qualified.indexOf(":");
97
+ return colon === -1 ? qualified : qualified.slice(colon + 1);
98
+ }
99
+ /** Writes or removes one attribute, applying the value rules and the URL check. */
100
+ function commit(el, namespace, qualified, value) {
101
+ const lowerName = qualified.toLowerCase();
102
+ const text = attributeText(lowerName, value);
103
+ if (text === null) {
104
+ if (namespace === null) el.removeAttribute(qualified);
105
+ else el.removeAttributeNS(namespace, localPart(qualified));
106
+ return;
107
+ }
108
+ if (isUnsafeUrlAttribute(lowerName, text)) {
109
+ warnOnce("UNSAFE_URL_BLOCKED", `Blocked a script URL in the "${qualified}" attribute.`);
110
+ return;
111
+ }
112
+ if (namespace === null) {
113
+ if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);
114
+ } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) el.setAttributeNS(namespace, qualified, text);
115
+ }
116
+ /**
117
+ * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a
118
+ * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the
119
+ * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is
120
+ * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`.
121
+ *
122
+ * @param el Target element.
123
+ * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.
124
+ * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes
125
+ * `"false"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes
126
+ * `""` (or `"true"` for those same names). Any other value is written as `String(value)`.
127
+ * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.
128
+ * @example
129
+ * import { setAttribute } from "@shadow-js/web";
130
+ *
131
+ * const link = document.createElement("a");
132
+ * setAttribute(link, "href", "https://example.com");
133
+ * setAttribute(link, "aria-hidden", false); // aria-hidden="false"
134
+ * setAttribute(link, "title", null); // removes title
135
+ * @see setBoolAttribute
136
+ * @see setAttributeNS
137
+ * @since 1.0.0
138
+ */
139
+ function setAttribute(el, name, value) {
140
+ assertAttributeName(name);
141
+ commit(el, null, name, value);
142
+ }
143
+ /**
144
+ * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules
145
+ * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for
146
+ * `xlink:href`).
147
+ *
148
+ * @param el Target element.
149
+ * @param namespace Namespace URI. `""` means no namespace, which behaves exactly like
150
+ * {@link setAttribute}.
151
+ * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.
152
+ * @param value The value, with the same rules as {@link setAttribute}.
153
+ * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.
154
+ * @example
155
+ * import { setAttributeNS } from "@shadow-js/web";
156
+ *
157
+ * const XLINK = "http://www.w3.org/1999/xlink";
158
+ * const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
159
+ * setAttributeNS(use, XLINK, "xlink:href", "#icon-star");
160
+ * setAttributeNS(use, XLINK, "xlink:href", null); // removes it
161
+ * @see setAttribute
162
+ * @since 1.0.0
163
+ */
164
+ function setAttributeNS(el, namespace, name, value) {
165
+ assertAttributeName(name);
166
+ commit(el, namespace === "" ? null : namespace, name, value);
167
+ }
168
+ /**
169
+ * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled
170
+ * templates call for the `bool:` prefix. A truthy value sets the attribute to `""`, a falsy value
171
+ * removes it; the DOM is touched only when presence changes. No URL check applies.
172
+ *
173
+ * @param el Target element.
174
+ * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.
175
+ * @param value Any value: only its truthiness is read.
176
+ * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.
177
+ * @example
178
+ * import { setBoolAttribute } from "@shadow-js/web";
179
+ *
180
+ * const button = document.createElement("button");
181
+ * setBoolAttribute(button, "disabled", true); // disabled=""
182
+ * setBoolAttribute(button, "disabled", 0); // removed
183
+ * @see setAttribute
184
+ * @since 1.0.0
185
+ */
186
+ function setBoolAttribute(el, name, value) {
187
+ assertAttributeName(name);
188
+ const present = el.hasAttribute(name);
189
+ if (value) {
190
+ if (!present) el.setAttribute(name, "");
191
+ } else if (present) el.removeAttribute(name);
192
+ }
193
+ export { assertAttributeName, isUnsafeUrlAttribute, setAttribute, setAttributeNS, setBoolAttribute };
194
+
195
+ //# sourceMappingURL=attributes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attributes.js","names":[],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"srcdoc\",\n \"poster\",\n \"data\",\n \"values\",\n \"from\",\n \"to\",\n \"by\",\n]);\n\n/** Enumerated attributes where `false` is a real value (\"false\") rather than an absence. */\nconst ENUMERATED_ATTRIBUTES = new Set([\"draggable\", \"spellcheck\", \"contenteditable\"]);\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = [\"javascript:\", \"data:text/html\", \"vbscript:\"];\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** True for `aria-*`, `data-*` and the enumerated attributes: their boolean values are strings. */\nfunction isStringValued(lowerName: string): boolean {\n return (\n lowerName.startsWith(\"aria-\") ||\n lowerName.startsWith(\"data-\") ||\n ENUMERATED_ATTRIBUTES.has(lowerName)\n );\n}\n\n/** Removes C0 and C1 control characters. Written as a loop so no control character appears in a regex. */\nfunction stripControls(text: string): string {\n let kept = \"\";\n for (const char of text) {\n const code = char.charCodeAt(0);\n if (code > 0x1f && (code < 0x7f || code > 0x9f)) kept += char;\n }\n return kept;\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n const normalized = stripControls(value).trim().toLowerCase();\n return UNSAFE_URL_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `srcdoc`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own.\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.has(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return isStringValued(lowerName) ? \"false\" : null;\n if (value === true) return isStringValued(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n if (isUnsafeUrlAttribute(lowerName, text)) {\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n const present = el.hasAttribute(name);\n if (value) {\n if (!present) el.setA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G,gBAAgB,IAAI;AAE3B"}
@@ -0,0 +1,44 @@
1
+ import { onMount } from "@shadow-js/core";
2
+ import { isHydrating } from "@shadow-js/core/extend";
3
+ // src/autofocus.ts
4
+ /**
5
+ * Focuses an element written with `autoFocus` (React parity) once it is inserted into the document
6
+ * by a client render or update. The compiler calls this for an `autoFocus` attribute and for
7
+ * `autoFocus` keys of a spread, so an app that never uses `autoFocus` never reaches this code. Call it
8
+ * yourself only for elements you create by hand, inside an owner (a component or a root): the focus
9
+ * is requested with `onMount`, so development builds warn with `NO_OWNER_EFFECT` without one.
10
+ *
11
+ * The rules, which match React's for `autoFocus`:
12
+ * - Once per element: the focus is requested when the element is created, after the owner has been
13
+ * flushed. Moving the element later (a keyed reorder) does not focus it again.
14
+ * - An element that is not connected when its owner flushes (a detached root) is not focused.
15
+ * - During hydration the server markup already carries `autofocus`, so the element focuses only when
16
+ * nothing else has the focus (the document's active element is the body or null). A user's focus
17
+ * is never taken away by hydration.
18
+ *
19
+ * @param el The element. Only `HTMLElement` and `SVGElement` are focused; for any other element, and
20
+ * for one that cannot take focus, the call does nothing.
21
+ * @param enabled The `autoFocus` value: falsy values (`false`, `undefined`, `""`, `0`) do nothing.
22
+ * @example
23
+ * import { autoFocus, render } from "@shadow-js/web";
24
+ *
25
+ * render(() => {
26
+ * const input = document.createElement("input");
27
+ * autoFocus(input, true); // focused once the root has mounted it
28
+ * return input;
29
+ * }, document.body);
30
+ * @since 1.0.0
31
+ */
32
+ function autoFocus(el, enabled) {
33
+ if (!enabled) return;
34
+ const hydrating = isHydrating();
35
+ onMount(() => {
36
+ const doc = el.ownerDocument;
37
+ const active = doc.activeElement;
38
+ const free = !hydrating || active === null || active === doc.body;
39
+ if (el.isConnected && free && (el instanceof HTMLElement || el instanceof SVGElement)) el.focus();
40
+ });
41
+ }
42
+ export { autoFocus };
43
+
44
+ //# sourceMappingURL=autofocus.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"autofocus.js","names":[],"sources":["../../src/autofocus.ts"],"sourcesContent":["import { onMount } from \"@shadow-js/core\";\nimport { isHydrating } from \"@shadow-js/core/extend\";\n\n/**\n * Focuses an element written with `autoFocus` (React parity) once it is inserted into the document\n * by a client render or update. The compiler calls this for an `autoFocus` attribute and for\n * `autoFocus` keys of a spread, so an app that never uses `autoFocus` never reaches this code. Call it\n * yourself only for elements you create by hand, inside an owner (a component or a root): the focus\n * is requested with `onMount`, so development builds warn with `NO_OWNER_EFFECT` without one.\n *\n * The rules, which match React's for `autoFocus`:\n * - Once per element: the focus is requested when the element is created, after the owner has been\n * flushed. Moving the element later (a keyed reorder) does not focus it again.\n * - An element that is not connected when its owner flushes (a detached root) is not focused.\n * - During hydration the server markup already carries `autofocus`, so the element focuses only when\n * nothing else has the focus (the document's active element is the body or null). A user's focus\n * is never taken away by hydration.\n *\n * @param el The element. Only `HTMLElement` and `SVGElement` are focused; for any other element, and\n * for one that cannot take focus, the call does nothing.\n * @param enabled The `autoFocus` value: falsy values (`false`, `undefined`, `\"\"`, `0`) do nothing.\n * @example\n * import { autoFocus, render } from \"@shadow-js/web\";\n *\n * render(() => {\n * const input = document.createElement(\"input\");\n * autoFocus(input, true); // focused once the root has mounted it\n * return input;\n * }, document.body);\n * @since 1.0.0\n */\nexport function autoFocus(el: Element, enabled: unknown): void {\n if (!enabled) return;\n const hydrating = isHydrating();\n onMount(() => {\n const doc = el.ownerDocument;\n const active = doc.activeElement;\n // Hydration focuses only when nothing has the focus: the body or no element.\n const free = !hydrating || active === null || active === doc.body;\n if (el.isConnected && free && (el instanceof HTMLElement || el instanceof SVGElement)) {\n el.focus();\n }\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,UAAU,IAAa,SAAwB;CAC7D,IAAI,CAAC,SAAS;CACd,MAAM,YAAY,YAAY;CAC9B,cAAc;EACZ,MAAM,MAAM,GAAG;EACf,MAAM,SAAS,IAAI;EAEnB,MAAM,OAAO,CAAC,aAAa,WAAW,QAAQ,WAAW,IAAI;EAC7D,IAAI,GAAG,eAAe,SAAS,cAAc,eAAe,cAAc,aACxE,GAAG,MAAM;CAEb,CAAC;AACH"}