@shadow-js/web 1.0.0 → 1.0.2

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 (349) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/dev/attributes.d.ts +10 -5
  3. package/dist/dev/attributes.js +28 -51
  4. package/dist/dev/attributes.js.map +1 -1
  5. package/dist/dev/autofocus.d.ts +0 -2
  6. package/dist/dev/autofocus.js +1 -2
  7. package/dist/dev/class-style.d.ts +6 -4
  8. package/dist/dev/class-style.js +25 -9
  9. package/dist/dev/class-style.js.map +1 -1
  10. package/dist/dev/component.d.ts +0 -2
  11. package/dist/dev/component.js +1 -2
  12. package/dist/dev/control-flow/activity.d.ts +0 -2
  13. package/dist/dev/control-flow/activity.js +1 -2
  14. package/dist/dev/control-flow/branch.js +0 -1
  15. package/dist/dev/control-flow/client-only.d.ts +0 -2
  16. package/dist/dev/control-flow/client-only.js +1 -2
  17. package/dist/dev/control-flow/dynamic.d.ts +11 -4
  18. package/dist/dev/control-flow/dynamic.js +57 -41
  19. package/dist/dev/control-flow/dynamic.js.map +1 -1
  20. package/dist/dev/control-flow/error-boundary.d.ts +0 -2
  21. package/dist/dev/control-flow/error-boundary.js +1 -2
  22. package/dist/dev/control-flow/for.d.ts +0 -2
  23. package/dist/dev/control-flow/for.js +1 -2
  24. package/dist/dev/control-flow/fragment.d.ts +0 -2
  25. package/dist/dev/control-flow/fragment.js +1 -2
  26. package/dist/dev/control-flow/hot-link.js +1 -2
  27. package/dist/dev/control-flow/index-list.d.ts +0 -2
  28. package/dist/dev/control-flow/index-list.js +1 -2
  29. package/dist/dev/control-flow/lazy.d.ts +0 -2
  30. package/dist/dev/control-flow/lazy.js +1 -2
  31. package/dist/dev/control-flow/no-hydration.d.ts +0 -2
  32. package/dist/dev/control-flow/no-hydration.js +1 -2
  33. package/dist/dev/control-flow/portal.d.ts +0 -2
  34. package/dist/dev/control-flow/portal.js +3 -2
  35. package/dist/dev/control-flow/portal.js.map +1 -1
  36. package/dist/dev/control-flow/root-errors.d.ts +0 -2
  37. package/dist/dev/control-flow/root-errors.js +1 -2
  38. package/dist/dev/control-flow/show.d.ts +0 -2
  39. package/dist/dev/control-flow/show.js +1 -2
  40. package/dist/dev/control-flow/suspense-list.d.ts +0 -2
  41. package/dist/dev/control-flow/suspense-list.js +1 -2
  42. package/dist/dev/control-flow/suspense.d.ts +0 -2
  43. package/dist/dev/control-flow/suspense.js +1 -2
  44. package/dist/dev/control-flow/switch.d.ts +0 -2
  45. package/dist/dev/control-flow/switch.js +1 -2
  46. package/dist/dev/derived.d.ts +0 -2
  47. package/dist/dev/derived.js +1 -2
  48. package/dist/dev/element.d.ts +0 -2
  49. package/dist/dev/element.js +2 -3
  50. package/dist/dev/element.js.map +1 -1
  51. package/dist/dev/events.d.ts +0 -2
  52. package/dist/dev/events.js +16 -46
  53. package/dist/dev/events.js.map +1 -1
  54. package/dist/dev/head/components.d.ts +0 -2
  55. package/dist/dev/head/components.js +1 -2
  56. package/dist/dev/head/registry.js +1 -2
  57. package/dist/dev/head/server-head.d.ts +0 -2
  58. package/dist/dev/head/server-head.js +1 -2
  59. package/dist/dev/head/sink.js +1 -2
  60. package/dist/dev/head/use-head.d.ts +0 -2
  61. package/dist/dev/head/use-head.js +1 -2
  62. package/dist/dev/head/validate.d.ts +0 -2
  63. package/dist/dev/head/validate.js +1 -2
  64. package/dist/dev/hmr.d.ts +0 -2
  65. package/dist/dev/hmr.js +1 -2
  66. package/dist/dev/hydration.d.ts +0 -2
  67. package/dist/dev/hydration.js +1 -2
  68. package/dist/dev/insert.d.ts +15 -7
  69. package/dist/dev/insert.js +36 -15
  70. package/dist/dev/insert.js.map +1 -1
  71. package/dist/dev/internal/claim.d.ts +2 -3
  72. package/dist/dev/internal/claim.js +19 -4
  73. package/dist/dev/internal/claim.js.map +1 -1
  74. package/dist/dev/internal/css-units.js +1 -2
  75. package/dist/dev/internal/diagnostics.d.ts +7 -5
  76. package/dist/dev/internal/diagnostics.js +15 -6
  77. package/dist/dev/internal/diagnostics.js.map +1 -1
  78. package/dist/dev/internal/early-events.js +21 -4
  79. package/dist/dev/internal/early-events.js.map +1 -1
  80. package/dist/dev/internal/hydration-hooks.d.ts +0 -2
  81. package/dist/dev/internal/hydration-hooks.js +0 -1
  82. package/dist/dev/internal/hydration-scope.d.ts +0 -2
  83. package/dist/dev/internal/hydration-scope.js +1 -2
  84. package/dist/dev/internal/names.d.ts +0 -2
  85. package/dist/dev/internal/names.js +1 -2
  86. package/dist/dev/internal/portal-context.d.ts +0 -2
  87. package/dist/dev/internal/portal-context.js +1 -2
  88. package/dist/dev/internal/react-names.js +26 -63
  89. package/dist/dev/internal/react-names.js.map +1 -1
  90. package/dist/dev/internal/reconcile.d.ts +0 -2
  91. package/dist/dev/internal/reconcile.js +4 -8
  92. package/dist/dev/internal/reconcile.js.map +1 -1
  93. package/dist/dev/internal/stream-context.d.ts +0 -2
  94. package/dist/dev/internal/stream-context.js +1 -2
  95. package/dist/dev/jsx/aria.d.ts +0 -2
  96. package/dist/dev/jsx/component.d.ts +0 -2
  97. package/dist/dev/jsx/events.d.ts +0 -2
  98. package/dist/dev/jsx/global.d.ts +5 -4
  99. package/dist/dev/jsx/html.d.ts +1 -2
  100. package/dist/dev/jsx/intrinsic.d.ts +0 -2
  101. package/dist/dev/jsx/mathml.d.ts +0 -2
  102. package/dist/dev/jsx/svg.d.ts +0 -2
  103. package/dist/dev/jsx/types.d.ts +0 -2
  104. package/dist/dev/jsx-runtime.d.ts +0 -2
  105. package/dist/dev/reactive.d.ts +0 -2
  106. package/dist/dev/reactive.js +1 -2
  107. package/dist/dev/render.d.ts +0 -2
  108. package/dist/dev/render.js +1 -2
  109. package/dist/dev/resource-hints.d.ts +0 -2
  110. package/dist/dev/resource-hints.js +5 -4
  111. package/dist/dev/resource-hints.js.map +1 -1
  112. package/dist/dev/select-value.d.ts +0 -2
  113. package/dist/dev/select-value.js +6 -17
  114. package/dist/dev/select-value.js.map +1 -1
  115. package/dist/dev/server/attributes.d.ts +3 -2
  116. package/dist/dev/server/attributes.js +6 -3
  117. package/dist/dev/server/attributes.js.map +1 -1
  118. package/dist/dev/server/class-style.d.ts +0 -2
  119. package/dist/dev/server/class-style.js +1 -2
  120. package/dist/dev/server/component.d.ts +0 -2
  121. package/dist/dev/server/component.js +1 -2
  122. package/dist/dev/server/derived.d.ts +0 -2
  123. package/dist/dev/server/derived.js +1 -2
  124. package/dist/dev/server/element.d.ts +0 -2
  125. package/dist/dev/server/element.js +9 -6
  126. package/dist/dev/server/element.js.map +1 -1
  127. package/dist/dev/server/errors.js +8 -3
  128. package/dist/dev/server/errors.js.map +1 -1
  129. package/dist/dev/server/escape.d.ts +0 -2
  130. package/dist/dev/server/escape.js +15 -8
  131. package/dist/dev/server/escape.js.map +1 -1
  132. package/dist/dev/server/form-controls.d.ts +0 -2
  133. package/dist/dev/server/form-controls.js +6 -4
  134. package/dist/dev/server/form-controls.js.map +1 -1
  135. package/dist/dev/server/hydration-script.d.ts +0 -2
  136. package/dist/dev/server/hydration-script.js +1 -2
  137. package/dist/dev/server/index.d.ts +2 -1
  138. package/dist/dev/server/index.js +2 -1
  139. package/dist/dev/server/node.d.ts +0 -2
  140. package/dist/dev/server/node.js +1 -2
  141. package/dist/dev/server/portals.d.ts +0 -2
  142. package/dist/dev/server/portals.js +0 -1
  143. package/dist/dev/server/raw-text.d.ts +28 -0
  144. package/dist/dev/server/raw-text.js +66 -0
  145. package/dist/dev/server/raw-text.js.map +1 -0
  146. package/dist/dev/server/render.d.ts +2 -3
  147. package/dist/dev/server/render.js +3 -4
  148. package/dist/dev/server/render.js.map +1 -1
  149. package/dist/dev/server/serialize.d.ts +0 -2
  150. package/dist/dev/server/serialize.js +1 -2
  151. package/dist/dev/server/stream.d.ts +1 -3
  152. package/dist/dev/server/stream.js +3 -4
  153. package/dist/dev/server/stream.js.map +1 -1
  154. package/dist/dev/server.d.ts +2 -1
  155. package/dist/dev/server.js +2 -1
  156. package/dist/dev/spread.d.ts +0 -2
  157. package/dist/dev/spread.js +8 -56
  158. package/dist/dev/spread.js.map +1 -1
  159. package/dist/dev/template.d.ts +0 -2
  160. package/dist/dev/template.js +1 -2
  161. package/dist/dev/view-transition.d.ts +0 -2
  162. package/dist/dev/view-transition.js +1 -2
  163. package/dist/prod/attributes.js +1 -1
  164. package/dist/prod/attributes.js.map +1 -1
  165. package/dist/prod/class-style.js +1 -1
  166. package/dist/prod/class-style.js.map +1 -1
  167. package/dist/prod/control-flow/dynamic.js +1 -1
  168. package/dist/prod/control-flow/dynamic.js.map +1 -1
  169. package/dist/prod/control-flow/portal.js +1 -1
  170. package/dist/prod/control-flow/portal.js.map +1 -1
  171. package/dist/prod/element.js +1 -1
  172. package/dist/prod/element.js.map +1 -1
  173. package/dist/prod/events.js +1 -1
  174. package/dist/prod/events.js.map +1 -1
  175. package/dist/prod/insert.js +1 -1
  176. package/dist/prod/insert.js.map +1 -1
  177. package/dist/prod/internal/claim.js +1 -1
  178. package/dist/prod/internal/claim.js.map +1 -1
  179. package/dist/prod/internal/diagnostics.js +1 -1
  180. package/dist/prod/internal/diagnostics.js.map +1 -1
  181. package/dist/prod/internal/early-events.js +1 -1
  182. package/dist/prod/internal/early-events.js.map +1 -1
  183. package/dist/prod/internal/react-names.js +1 -1
  184. package/dist/prod/internal/react-names.js.map +1 -1
  185. package/dist/prod/internal/reconcile.js +1 -1
  186. package/dist/prod/internal/reconcile.js.map +1 -1
  187. package/dist/prod/resource-hints.js +1 -1
  188. package/dist/prod/resource-hints.js.map +1 -1
  189. package/dist/prod/select-value.js +1 -1
  190. package/dist/prod/select-value.js.map +1 -1
  191. package/dist/prod/server/attributes.js +1 -1
  192. package/dist/prod/server/attributes.js.map +1 -1
  193. package/dist/prod/server/element.js +1 -1
  194. package/dist/prod/server/element.js.map +1 -1
  195. package/dist/prod/server/errors.js +1 -1
  196. package/dist/prod/server/errors.js.map +1 -1
  197. package/dist/prod/server/escape.js +1 -1
  198. package/dist/prod/server/escape.js.map +1 -1
  199. package/dist/prod/server/form-controls.js +2 -2
  200. package/dist/prod/server/form-controls.js.map +1 -1
  201. package/dist/prod/server/index.js +1 -1
  202. package/dist/prod/server/raw-text.js +2 -0
  203. package/dist/prod/server/raw-text.js.map +1 -0
  204. package/dist/prod/server/render.js +1 -1
  205. package/dist/prod/server/render.js.map +1 -1
  206. package/dist/prod/server/stream.js +1 -1
  207. package/dist/prod/server/stream.js.map +1 -1
  208. package/dist/prod/server.js +1 -1
  209. package/dist/prod/spread.js +1 -1
  210. package/dist/prod/spread.js.map +1 -1
  211. package/dist/server/attributes.js +1 -1
  212. package/dist/server/attributes.js.map +1 -1
  213. package/dist/server/class-style.js +1 -1
  214. package/dist/server/class-style.js.map +1 -1
  215. package/dist/server/control-flow/dynamic.js +1 -1
  216. package/dist/server/control-flow/dynamic.js.map +1 -1
  217. package/dist/server/control-flow/portal.js +1 -1
  218. package/dist/server/control-flow/portal.js.map +1 -1
  219. package/dist/server/element.js +1 -1
  220. package/dist/server/element.js.map +1 -1
  221. package/dist/server/events.js +1 -1
  222. package/dist/server/events.js.map +1 -1
  223. package/dist/server/insert.js +1 -1
  224. package/dist/server/insert.js.map +1 -1
  225. package/dist/server/internal/claim.js +1 -1
  226. package/dist/server/internal/claim.js.map +1 -1
  227. package/dist/server/internal/diagnostics.js +1 -1
  228. package/dist/server/internal/diagnostics.js.map +1 -1
  229. package/dist/server/internal/early-events.js +1 -1
  230. package/dist/server/internal/early-events.js.map +1 -1
  231. package/dist/server/internal/react-names.js +1 -1
  232. package/dist/server/internal/react-names.js.map +1 -1
  233. package/dist/server/internal/reconcile.js +1 -1
  234. package/dist/server/internal/reconcile.js.map +1 -1
  235. package/dist/server/resource-hints.js +1 -1
  236. package/dist/server/resource-hints.js.map +1 -1
  237. package/dist/server/select-value.js +1 -1
  238. package/dist/server/select-value.js.map +1 -1
  239. package/dist/server/server/attributes.js +1 -1
  240. package/dist/server/server/attributes.js.map +1 -1
  241. package/dist/server/server/element.js +1 -1
  242. package/dist/server/server/element.js.map +1 -1
  243. package/dist/server/server/errors.js +1 -1
  244. package/dist/server/server/errors.js.map +1 -1
  245. package/dist/server/server/escape.js +1 -1
  246. package/dist/server/server/escape.js.map +1 -1
  247. package/dist/server/server/form-controls.js +2 -2
  248. package/dist/server/server/form-controls.js.map +1 -1
  249. package/dist/server/server/index.js +1 -1
  250. package/dist/server/server/raw-text.js +2 -0
  251. package/dist/server/server/raw-text.js.map +1 -0
  252. package/dist/server/server/render.js +1 -1
  253. package/dist/server/server/render.js.map +1 -1
  254. package/dist/server/server/stream.js +1 -1
  255. package/dist/server/server/stream.js.map +1 -1
  256. package/dist/server/server.js +1 -1
  257. package/dist/server/spread.js +1 -1
  258. package/dist/server/spread.js.map +1 -1
  259. package/dist/server-dev/attributes.js +28 -51
  260. package/dist/server-dev/attributes.js.map +1 -1
  261. package/dist/server-dev/autofocus.js +1 -2
  262. package/dist/server-dev/class-style.js +25 -9
  263. package/dist/server-dev/class-style.js.map +1 -1
  264. package/dist/server-dev/component.js +1 -2
  265. package/dist/server-dev/control-flow/activity.js +1 -2
  266. package/dist/server-dev/control-flow/branch.js +0 -1
  267. package/dist/server-dev/control-flow/client-only.js +1 -2
  268. package/dist/server-dev/control-flow/dynamic.js +23 -12
  269. package/dist/server-dev/control-flow/dynamic.js.map +1 -1
  270. package/dist/server-dev/control-flow/error-boundary.js +1 -2
  271. package/dist/server-dev/control-flow/for.js +1 -2
  272. package/dist/server-dev/control-flow/fragment.js +1 -2
  273. package/dist/server-dev/control-flow/hot-link.js +1 -2
  274. package/dist/server-dev/control-flow/index-list.js +1 -2
  275. package/dist/server-dev/control-flow/lazy.js +1 -2
  276. package/dist/server-dev/control-flow/no-hydration.js +1 -2
  277. package/dist/server-dev/control-flow/portal.js +3 -2
  278. package/dist/server-dev/control-flow/portal.js.map +1 -1
  279. package/dist/server-dev/control-flow/root-errors.js +1 -2
  280. package/dist/server-dev/control-flow/show.js +1 -2
  281. package/dist/server-dev/control-flow/suspense-list.js +1 -2
  282. package/dist/server-dev/control-flow/suspense.js +1 -2
  283. package/dist/server-dev/control-flow/switch.js +1 -2
  284. package/dist/server-dev/derived.js +1 -2
  285. package/dist/server-dev/element.js +4 -3
  286. package/dist/server-dev/element.js.map +1 -1
  287. package/dist/server-dev/events.js +16 -46
  288. package/dist/server-dev/events.js.map +1 -1
  289. package/dist/server-dev/head/components.js +1 -2
  290. package/dist/server-dev/head/registry.js +1 -2
  291. package/dist/server-dev/head/server-head.js +1 -2
  292. package/dist/server-dev/head/sink.js +1 -2
  293. package/dist/server-dev/head/use-head.js +1 -2
  294. package/dist/server-dev/head/validate.js +1 -2
  295. package/dist/server-dev/hydration.js +1 -2
  296. package/dist/server-dev/insert.js +36 -15
  297. package/dist/server-dev/insert.js.map +1 -1
  298. package/dist/server-dev/internal/claim.js +19 -4
  299. package/dist/server-dev/internal/claim.js.map +1 -1
  300. package/dist/server-dev/internal/css-units.js +1 -2
  301. package/dist/server-dev/internal/diagnostics.js +15 -6
  302. package/dist/server-dev/internal/diagnostics.js.map +1 -1
  303. package/dist/server-dev/internal/early-events.js +21 -4
  304. package/dist/server-dev/internal/early-events.js.map +1 -1
  305. package/dist/server-dev/internal/hydration-hooks.js +0 -1
  306. package/dist/server-dev/internal/hydration-scope.js +1 -2
  307. package/dist/server-dev/internal/names.js +1 -2
  308. package/dist/server-dev/internal/portal-context.js +1 -2
  309. package/dist/server-dev/internal/react-names.js +26 -63
  310. package/dist/server-dev/internal/react-names.js.map +1 -1
  311. package/dist/server-dev/internal/reconcile.js +4 -8
  312. package/dist/server-dev/internal/reconcile.js.map +1 -1
  313. package/dist/server-dev/internal/stream-context.js +1 -2
  314. package/dist/server-dev/reactive.js +1 -2
  315. package/dist/server-dev/render.js +1 -2
  316. package/dist/server-dev/resource-hints.js +5 -4
  317. package/dist/server-dev/resource-hints.js.map +1 -1
  318. package/dist/server-dev/select-value.js +6 -17
  319. package/dist/server-dev/select-value.js.map +1 -1
  320. package/dist/server-dev/server/attributes.js +6 -3
  321. package/dist/server-dev/server/attributes.js.map +1 -1
  322. package/dist/server-dev/server/class-style.js +1 -2
  323. package/dist/server-dev/server/component.js +1 -2
  324. package/dist/server-dev/server/derived.js +1 -2
  325. package/dist/server-dev/server/element.js +9 -6
  326. package/dist/server-dev/server/element.js.map +1 -1
  327. package/dist/server-dev/server/errors.js +8 -3
  328. package/dist/server-dev/server/errors.js.map +1 -1
  329. package/dist/server-dev/server/escape.js +15 -8
  330. package/dist/server-dev/server/escape.js.map +1 -1
  331. package/dist/server-dev/server/form-controls.js +6 -4
  332. package/dist/server-dev/server/form-controls.js.map +1 -1
  333. package/dist/server-dev/server/hydration-script.js +1 -2
  334. package/dist/server-dev/server/index.js +2 -1
  335. package/dist/server-dev/server/node.js +1 -2
  336. package/dist/server-dev/server/portals.js +0 -1
  337. package/dist/server-dev/server/raw-text.js +86 -0
  338. package/dist/server-dev/server/raw-text.js.map +1 -0
  339. package/dist/server-dev/server/render.js +3 -4
  340. package/dist/server-dev/server/render.js.map +1 -1
  341. package/dist/server-dev/server/serialize.js +1 -2
  342. package/dist/server-dev/server/stream.js +3 -4
  343. package/dist/server-dev/server/stream.js.map +1 -1
  344. package/dist/server-dev/server.js +2 -1
  345. package/dist/server-dev/spread.js +8 -56
  346. package/dist/server-dev/spread.js.map +1 -1
  347. package/dist/server-dev/template.js +1 -2
  348. package/dist/server-dev/view-transition.js +1 -2
  349. package/package.json +3 -2
@@ -1 +1 @@
1
- {"version":3,"file":"stream.js","names":["RENDER_ID","script","nonce","body","renderToStream","renderId","options","timeoutMs","signal","portals","portalCollectorFor","encoder","passes","disposeAll","errors","pass","error","canceled","timer","cancelRender","settled","fetching","push","controller","text","renderPass","cache","key","resourceKey","explicit","promise","entry","value","trackOptions","sink","boundary","reporters","createRoot","stop","attachRootErrors","StreamContext","withPortalSink","ResourceCacheContext","runWithServerHead","withScope","createRootScope","escape","code","rejectAbort","abort","reject","SsrError","onAbort","cleanup","reason","answer","round","held","untrack","failRemaining","strikes","settledBefore","current","emitted","html","data","serialize"],"sources":["../../../src/server/stream.ts"],"sourcesContent":["import {\n createRoot,\n type ResourceCache,\n ResourceCacheContext,\n type ResourceTrackOptions,\n untrack,\n} from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { type StreamBoundary, StreamContext, type StreamSink } from \"../internal/stream-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"./escape\";\nimport { portalCollectorFor, type ServerPortals, withPortalSink } from \"./portals\";\nimport { serialize } from \"./serialize\";\n\n/**\n * Options of {@link renderToStream}.\n * @since 1.0.0\n */\nexport interface StreamOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * CSP nonce for the inline swap scripts. Characters outside letters, digits, `+`, `/`, `=`, `_` and\n * `-` are removed before it is written.\n * @default undefined (the scripts get no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Upper bound for the whole stream, in milliseconds, a positive finite number. When it runs out, the stream errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT`.\n * @default 30000\n */\n readonly timeoutMs?: number;\n /**\n * Aborts the render: the stream errors with the signal's reason and every pending fetch is abandoned.\n * @default undefined (the render is bounded only by `timeoutMs`)\n */\n readonly signal?: AbortSignal;\n /**\n * Collects the tags `useHead`, `<Title>`, ... register while the shell renders (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Called with the shell markup as soon as it is ready, before it is enqueued: the moment to write\n * the document head and choose the response status.\n * @default undefined (no callback)\n */\n readonly onShellReady?: (shell: string) => void;\n /**\n * Collects the markup of the portals the stream produces (see {@link createServerPortals}). The stream\n * does not write it: once the stream has ended, emit `portals.html()` at the end of `<body>`.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the stream caught, once per caught error. An error in the shell\n * happens before the first chunk, so the caller can still choose the response status; an error in a later\n * boundary happens after the shell and changes only that boundary (its fallback stays).\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the stream does not error on that error and the markup lacks\n * the part that failed.\n * @default undefined (the error ends the stream in its `error` state)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * The most shell renders a stream makes while resources hold its first flush. Each render uses the held\n * values the one before resolved, so a chain of held resources is bounded like a boundary waterfall.\n */\nconst MAX_SHELL_PASSES = 10;\n\n/**\n * One render of the shell: its markup, the boundaries still pending in it, the keys it asked for and the\n * fetches it started. Only the answering pass (the one the stream sends) reports its errors; the others\n * are discarded, and their fetches stay alive so a later pass can join them.\n */\ninterface ShellPass {\n html: string;\n boundaries: StreamBoundary[];\n readonly requested: Set<string>;\n /** The fetches this render started that hold the first flush (`deferStream`), by key. */\n readonly held: Array<{ readonly key: string; readonly entry: Promise<void> }>;\n /** The fetches this render started that the stream is still waiting for. */\n readonly inFlight: Set<Promise<void>>;\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n answered: boolean;\n dispose: () => void;\n}\n\n/**\n * The constant swap runtime. `$S(id)` replaces the fallback of boundary `id` (the nodes between\n * its `<!--[b:id-->` and `<!--]-->` comments) with the content of `<template id=\"s:id\">`; with a\n * second argument the boundary failed on the server and keeps its fallback for the client.\n */\nconst SWAP_RUNTIME =\n 'window.$S=function(i,f){var t=document.getElementById(\"s:\"+i);if(!t)return;' +\n \"if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){\" +\n 'if(c.data===\"[b:\"+i){var d=1,n=c.nextSibling,e=null;while(n){' +\n 'if(n.nodeType===8){if(n.data.charAt(0)===\"[\"){d++}else if(n.data===\"]\"){d--;if(d===0){e=n;break}}}' +\n \"n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);\" +\n \"e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};\";\n\nfunction script(body: string, nonce: string | undefined): string {\n const attribute =\n nonce === undefined ? \"\" : ` nonce=\"${nonce.replace(/[^A-Za-z0-9+/=_-]/g, \"\")}\"`;\n return `<script${attribute}>${body}</script>`;\n}\n\n/**\n * Renders an app as a stream of HTML, for the fastest first byte: the shell first (pending Suspense\n * boundaries show their fallback), then one chunk per boundary as its data arrives, in the order the\n * data settles, and finally, when resources resolved, a\n * `<script type=\"application/json\" data-sh=\"RENDER_ID\">` block with their values. The page works without JavaScript: each chunk is a `<template>` that a\n * tiny inline script swaps in for the fallback. A boundary whose data can no longer arrive keeps its\n * fallback for the client.\n *\n * @param code Builds the app.\n * @param options Hydration-key prefix, nonce, time budget, abort signal, collectors, shell callback\n * and error reporters. Undefined uses the defaults of {@link StreamOptions}.\n * @returns A byte stream of the app markup, to be placed inside your document. Canceling it stops\n * the render.\n * @throws TypeError, synchronously, for an invalid `renderId` or `timeoutMs`. The stream itself errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT` when `timeoutMs` runs out, with the signal's reason when\n * `signal` aborts, and with an error no boundary caught when `onUncaughtError` is not set.\n * @example\n * import { createComponent, renderToStream } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * function handle(request: Request): Response {\n * const stream = renderToStream(() => createComponent(App, {}), { signal: request.signal });\n * return new Response(stream, { headers: { \"content-type\": \"text/html\" } });\n * }\n * @see renderToStringAsync\n * @since 1.0.0\n */\nexport function renderToStream(\n code: () => unknown,\n options: StreamOptions = {},\n): ReadableStream<Uint8Array> {\n const renderId = options.renderId ?? \"0\";\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n const signal = options.signal;\n const portals = portalCollectorFor(options.portals);\n const encoder = new TextEncoder();\n // Every render of the shell, kept until the stream ends: a later pass joins the fetches an earlier one started.\n const passes: ShellPass[] = [];\n const disposeAll = (): void => {\n const errors: unknown[] = [];\n for (const pass of passes.splice(0)) {\n try {\n pass.dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0)\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, \"Stream cleanup failed.\");\n };\n let canceled = false;\n // Cleared when the stream ends or is canceled, so a finished render never keeps the process alive.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancelRender: (reason: unknown) => void = () => undefined;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const settled = new Map<string, unknown>();\n // The fetch each key was last started with: a render that finds it unsettled joins it (ResourceCache.pending).\n const fetching = new Map<string, Promise<unknown>>();\n const push = (text: string): void => {\n if (signal?.aborted) throw signal.reason;\n if (!canceled) controller.enqueue(encoder.encode(text));\n };\n\n /** Renders the shell once. Its resources, boundaries and errors belong to this pass alone. */\n const renderPass = (): ShellPass => {\n const pass: ShellPass = {\n html: \"\",\n boundaries: [],\n requested: new Set<string>(),\n held: [],\n inFlight: new Set<Promise<void>>(),\n caught: [],\n uncaught: [],\n answered: false,\n dispose: () => undefined,\n };\n passes.push(pass);\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n pass.requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise, trackOptions?: ResourceTrackOptions) => {\n fetching.set(key, promise);\n const entry = promise.then(\n (value) => {\n settled.set(key, value);\n },\n () => undefined,\n );\n pass.inFlight.add(entry);\n void entry.finally(() => pass.inFlight.delete(entry));\n if (trackOptions?.deferStream === true) pass.held.push({ key, entry });\n },\n pending: (key) => fetching.get(key),\n };\n const sink: StreamSink = {\n defer: (boundary: StreamBoundary) => {\n pass.boundaries.push(boundary);\n },\n };\n // Errors of a pass that is not the answer are held back: the answering pass reports them, once.\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n if (pass.answered) options.onCaughtError?.(error);\n else pass.caught.push(error);\n },\n ...(options.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n if (pass.answered) options.onUncaughtError?.(error);\n else pass.uncaught.push(error);\n },\n }),\n };\n options.head?.clear();\n portals?.clear();\n pass.html = createRoot((stop) => {\n pass.dispose = stop;\n // Attached to the root of this render, so every boundary of it reports through these.\n attachRootErrors(reporters);\n const view = StreamContext({\n value: sink,\n get children() {\n return withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(options.head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n );\n },\n });\n return ((view as () => unknown)() as () => string)();\n });\n return pass;\n };\n\n let rejectAbort: (reason: unknown) => void = () => undefined;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n timer = setTimeout(\n () =>\n reject(\n new SsrError(\"SSR_TIMEOUT\", `The stream did not finish within ${timeoutMs} ms.`),\n ),\n timeoutMs,\n );\n });\n const onAbort = (): void =>\n rejectAbort(signal?.reason ?? new Error(\"The render was aborted.\"));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const cleanup = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n disposeAll();\n };\n // Wake a held shell or boundary immediately; late resource settlement must not render again.\n cancelRender = (reason) => {\n rejectAbort(reason);\n cleanup();\n };\n // Marks the abort handled for a render that has already finished (the stream closed, the timer\n // is cleared) and no longer awaits it. While the loop below awaits `abort`, its rejection is\n // rethrown there into `controller.error`, so a timeout or an abort is reported to the reader.\n abort.catch(() => undefined);\n\n try {\n if (signal?.aborted) throw signal.reason;\n // The shell is sent once the resources it holds have settled: a held render that finds a\n // value renders again with it, so the value is in the first chunk and not behind a fallback.\n let answer = renderPass();\n for (let round = 1; answer.held.length > 0; round += 1) {\n await Promise.race([abort, Promise.allSettled(answer.held.map((held) => held.entry))]);\n // No held value arrived (each held fetch failed): this render is the answer, with its fallbacks.\n if (!answer.held.some((held) => settled.has(held.key))) break;\n if (round >= MAX_SHELL_PASSES) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept holding the stream after ${MAX_SHELL_PASSES} shell renders; flatten the data flow.`,\n );\n }\n answer = renderPass();\n }\n\n answer.answered = true;\n untrack(() => {\n for (const error of answer.caught) options.onCaughtError?.(error);\n for (const error of answer.uncaught) options.onUncaughtError?.(error);\n options.onShellReady?.(answer.html);\n });\n push(\n answer.boundaries.length > 0\n ? answer.html + script(SWAP_RUNTIME, options.nonce)\n : answer.html,\n );\n\n const failRemaining = (): void => {\n // Nothing can make progress (failed resources): leave the fallbacks for the client.\n for (const boundary of answer.boundaries.splice(0)) {\n push(\n `<template id=\"s:${boundary.id}\"></template>` +\n script(`$S(${JSON.stringify(boundary.id)},1)`, options.nonce),\n );\n }\n };\n let strikes = 0;\n while (answer.boundaries.length > 0) {\n if (answer.inFlight.size === 0) {\n failRemaining();\n break;\n }\n const settledBefore = settled.size;\n await Promise.race([abort, Promise.race([...answer.inFlight])]);\n const current = answer.boundaries;\n answer.boundaries = [];\n let emitted = false;\n for (const boundary of current) {\n const html = boundary.rebuild();\n if (html === null) continue;\n emitted = true;\n push(\n `<template id=\"s:${boundary.id}\">${html}</template>` +\n script(`$S(${JSON.stringify(boundary.id)})`, options.nonce),\n );\n }\n // Rounds that settle nothing new and emit nothing (only rejections) are bounded.\n strikes = settled.size === settledBefore && !emitted ? strikes + 1 : 0;\n if (answer.boundaries.length > 0 && strikes >= 2) failRemaining();\n }\n\n const data: Record<string, unknown> = {};\n for (const key of answer.requested) {\n if (!settled.has(key)) continue;\n Object.defineProperty(data, key, {\n value: settled.get(key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n if (Object.keys(data).length > 0) {\n push(`<script type=\"application/json\" data-sh=\"${renderId}\">${serialize(data)}</script>`);\n }\n cleanup();\n if (!canceled) controller.close();\n } catch (error) {\n cleanup();\n if (!canceled) controller.error(error);\n }\n },\n cancel(reason) {\n canceled = true;\n cancelRender(reason);\n },\n });\n}\n"],"mappings":"A,6iBA6EA,MAAMA,EAAY,mBAwClB,SAASC,EAAO,EAAc,EAAmC,CAG/D,MAAO,UADLC,IAAU,IAAA,GAAY,GAAK,WAAWA,EAAM,QAAQ,qBAAsB,EAAE,EAAE,GACrD,GAAGC,EAAK,WACrC,CA+BA,SAAgBC,EACd,EACA,EAAyB,CAAC,EACE,CAC5B,IAAMC,EAAWC,EAAQ,UAAY,IACrC,GAAI,OAAOD,GAAa,UAAY,CAACL,EAAU,KAAKK,CAAQ,EAC1D,MAAU,UAAU,oEAAoE,EAE1F,IAAME,EAAYD,EAAQ,WAAa,IACvC,GAAI,OAAOC,GAAc,UAAY,EAAEA,EAAY,IAAM,CAAC,OAAO,SAASA,CAAS,EACjF,MAAU,UAAU,6DAA6D,EAEnF,IAAMC,EAASF,EAAQ,OACjBG,EAAUC,EAAmBJ,EAAQ,OAAO,EAC5CK,EAAU,IAAI,YAEdC,EAAsB,CAAC,EACvBC,MAAyB,CAC7B,IAAMC,EAAoB,CAAC,EAC3B,IAAK,IAAMC,KAAQH,EAAO,OAAO,CAAC,EAChC,GAAI,CACFG,EAAK,QAAQ,CACf,OAASC,EAAO,CACdF,EAAO,KAAKE,CAAK,CACnB,CAEF,GAAIF,EAAO,OAAS,EAClB,MAAMA,EAAO,SAAW,EAAIA,EAAO,GAAS,eAAeA,EAAQ,wBAAwB,CAC/F,EACIG,EAAW,GAEXC,EACAC,MAAgD,IAAA,GAEpD,OAAO,IAAI,eAA2B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AK,CAC9D,EACF,CAEA,EAAUc,EAAQ,OAASyC,GAAiB,CAACE,EAAUH,EAAU,EAAI,EACjEL,EAAO,WAAW,OAAS,GAAKK,GAAW,GAAGD,EAAc,CAClE,CAEA,IAAMM,EAAgC,CAAC,EACvC,IAAK,IAAMtC,KAAO4B,EAAO,UAClBnC,EAAQ,IAAIO,CAAG,GACpB,OAAO,eAAesC,EAAMtC,EAAK,CAC/B,MAAOP,EAAQ,IAAIO,CAAG,EACtB,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EAEC,OAAO,KAAKsC,CAAI,CAAC,CAAC,OAAS,GAC7B3C,EAAK,4CAA4CjB,EAAS,IAAI6D,EAAUD,CAAI,EAAE,WAAU,EAE1FZ,EAAQ,EACHpC,GAAUM,EAAW,MAAM,CAClC,OAASP,EAAO,CACdqC,EAAQ,EACHpC,GAAUM,EAAW,MAAMP,CAAK,CACvC,CACF,EACA,OAAO,EAAQ,CACb,EAAW,GACXG,EAAamC,CAAM,CACrB,CACF,CAAC,CACH,C"}
1
+ {"version":3,"file":"stream.js","names":["RENDER_ID","script","nonce","body","renderToStream","renderId","options","timeoutMs","signal","portals","portalCollectorFor","encoder","passes","disposeAll","errors","pass","error","canceled","timer","cancelRender","settled","fetching","push","controller","text","renderPass","cache","key","resourceKey","explicit","promise","entry","value","trackOptions","sink","boundary","reporters","createRoot","stop","attachRootErrors","StreamContext","withPortalSink","ResourceCacheContext","runWithServerHead","withScope","createRootScope","escape","code","rejectAbort","abort","reject","SsrError","MAX_TIMER_MS","onAbort","cleanup","reason","answer","round","held","untrack","failRemaining","strikes","settledBefore","current","emitted","html","data","serialize"],"sources":["../../../src/server/stream.ts"],"sourcesContent":["import {\n createRoot,\n type ResourceCache,\n ResourceCacheContext,\n type ResourceTrackOptions,\n untrack,\n} from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { type StreamBoundary, StreamContext, type StreamSink } from \"../internal/stream-context\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"./escape\";\nimport { portalCollectorFor, type ServerPortals, withPortalSink } from \"./portals\";\nimport { serialize } from \"./serialize\";\n\n/**\n * Options of {@link renderToStream}.\n * @since 1.0.0\n */\nexport interface StreamOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * CSP nonce for the inline swap scripts. Characters outside letters, digits, `+`, `/`, `=`, `_` and\n * `-` are removed before it is written.\n * @default undefined (the scripts get no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Upper bound for the whole stream, in milliseconds, a positive finite number (values above 2147483647 count as 2147483647). When it runs out, the stream errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT`.\n * @default 30000\n */\n readonly timeoutMs?: number;\n /**\n * Aborts the render: the stream errors with the signal's reason and every pending fetch is abandoned.\n * @default undefined (the render is bounded only by `timeoutMs`)\n */\n readonly signal?: AbortSignal;\n /**\n * Collects the tags `useHead`, `<Title>`, ... register while the shell renders (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Called with the shell markup as soon as it is ready, before it is enqueued: the moment to write\n * the document head and choose the response status.\n * @default undefined (no callback)\n */\n readonly onShellReady?: (shell: string) => void;\n /**\n * Collects the markup of the portals the stream produces (see {@link createServerPortals}). The stream\n * does not write it: once the stream has ended, emit `portals.html()` at the end of `<body>`.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the stream caught, once per caught error. An error in the shell\n * happens before the first chunk, so the caller can still choose the response status; an error in a later\n * boundary happens after the shell and changes only that boundary (its fallback stays).\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the stream does not error on that error and the markup lacks\n * the part that failed.\n * @default undefined (the error ends the stream in its `error` state)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * The most shell renders a stream makes while resources hold its first flush. Each render uses the held\n * values the one before resolved, so a chain of held resources is bounded like a boundary waterfall.\n */\nconst MAX_SHELL_PASSES = 10;\n\n/**\n * One render of the shell: its markup, the boundaries still pending in it, the keys it asked for and the\n * fetches it started. Only the answering pass (the one the stream sends) reports its errors; the others\n * are discarded, and their fetches stay alive so a later pass can join them.\n */\ninterface ShellPass {\n html: string;\n boundaries: StreamBoundary[];\n readonly requested: Set<string>;\n /** The fetches this render started that hold the first flush (`deferStream`), by key. */\n readonly held: Array<{ readonly key: string; readonly entry: Promise<void> }>;\n /** The fetches this render started that the stream is still waiting for. */\n readonly inFlight: Set<Promise<void>>;\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n answered: boolean;\n dispose: () => void;\n}\n\n/**\n * The constant swap runtime. `$S(id)` replaces the fallback of boundary `id` (the nodes between\n * its `<!--[b:id-->` and `<!--]-->` comments) with the content of `<template id=\"s:id\">`; with a\n * second argument the boundary failed on the server and keeps its fallback for the client.\n */\nconst SWAP_RUNTIME =\n 'window.$S=function(i,f){var t=document.getElementById(\"s:\"+i);if(!t)return;' +\n \"if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){\" +\n 'if(c.data===\"[b:\"+i){var d=1,n=c.nextSibling,e=null;while(n){' +\n 'if(n.nodeType===8){if(n.data.charAt(0)===\"[\"){d++}else if(n.data===\"]\"){d--;if(d===0){e=n;break}}}' +\n \"n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);\" +\n \"e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};\";\n\nfunction script(body: string, nonce: string | undefined): string {\n const attribute =\n nonce === undefined ? \"\" : ` nonce=\"${nonce.replace(/[^A-Za-z0-9+/=_-]/g, \"\")}\"`;\n return `<script${attribute}>${body}</script>`;\n}\n\n/**\n * Renders an app as a stream of HTML, for the fastest first byte: the shell first (pending Suspense\n * boundaries show their fallback), then one chunk per boundary as its data arrives, in the order the\n * data settles, and finally, when resources resolved, a\n * `<script type=\"application/json\" data-sh=\"RENDER_ID\">` block with their values. The page works without JavaScript: each chunk is a `<template>` that a\n * tiny inline script swaps in for the fallback. A boundary whose data can no longer arrive keeps its\n * fallback for the client.\n *\n * @param code Builds the app.\n * @param options Hydration-key prefix, nonce, time budget, abort signal, collectors, shell callback\n * and error reporters. Undefined uses the defaults of {@link StreamOptions}.\n * @returns A byte stream of the app markup, to be placed inside your document. Canceling it stops\n * the render.\n * @throws TypeError, synchronously, for an invalid `renderId` or `timeoutMs`. The stream itself errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT` when `timeoutMs` runs out, with the signal's reason when\n * `signal` aborts, and with an error no boundary caught when `onUncaughtError` is not set.\n * @example\n * import { createComponent, renderToStream } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * function handle(request: Request): Response {\n * const stream = renderToStream(() => createComponent(App, {}), { signal: request.signal });\n * return new Response(stream, { headers: { \"content-type\": \"text/html\" } });\n * }\n * @see renderToStringAsync\n * @since 1.0.0\n */\nexport function renderToStream(\n code: () => unknown,\n options: StreamOptions = {},\n): ReadableStream<Uint8Array> {\n const renderId = options.renderId ?? \"0\";\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n const signal = options.signal;\n const portals = portalCollectorFor(options.portals);\n const encoder = new TextEncoder();\n // Every render of the shell, kept until the stream ends: a later pass joins the fetches an earlier one started.\n const passes: ShellPass[] = [];\n const disposeAll = (): void => {\n const errors: unknown[] = [];\n for (const pass of passes.splice(0)) {\n try {\n pass.dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0)\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, \"Stream cleanup failed.\");\n };\n let canceled = false;\n // Cleared when the stream ends or is canceled, so a finished render never keeps the process alive.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancelRender: (reason: unknown) => void = () => undefined;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const settled = new Map<string, unknown>();\n // The fetch each key was last started with: a render that finds it unsettled joins it (ResourceCache.pending).\n const fetching = new Map<string, Promise<unknown>>();\n const push = (text: string): void => {\n if (signal?.aborted) throw signal.reason;\n if (!canceled) controller.enqueue(encoder.encode(text));\n };\n\n /** Renders the shell once. Its resources, boundaries and errors belong to this pass alone. */\n const renderPass = (): ShellPass => {\n const pass: ShellPass = {\n html: \"\",\n boundaries: [],\n requested: new Set<string>(),\n held: [],\n inFlight: new Set<Promise<void>>(),\n caught: [],\n uncaught: [],\n answered: false,\n dispose: () => undefined,\n };\n passes.push(pass);\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n pass.requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise, trackOptions?: ResourceTrackOptions) => {\n fetching.set(key, promise);\n const entry = promise.then(\n (value) => {\n settled.set(key, value);\n },\n () => undefined,\n );\n pass.inFlight.add(entry);\n void entry.finally(() => pass.inFlight.delete(entry));\n if (trackOptions?.deferStream === true) pass.held.push({ key, entry });\n },\n pending: (key) => fetching.get(key),\n };\n const sink: StreamSink = {\n defer: (boundary: StreamBoundary) => {\n pass.boundaries.push(boundary);\n },\n };\n // Errors of a pass that is not the answer are held back: the answering pass reports them, once.\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n if (pass.answered) options.onCaughtError?.(error);\n else pass.caught.push(error);\n },\n ...(options.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n if (pass.answered) options.onUncaughtError?.(error);\n else pass.uncaught.push(error);\n },\n }),\n };\n options.head?.clear();\n portals?.clear();\n pass.html = createRoot((stop) => {\n pass.dispose = stop;\n // Attached to the root of this render, so every boundary of it reports through these.\n attachRootErrors(reporters);\n const view = StreamContext({\n value: sink,\n get children() {\n return withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(options.head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n );\n },\n });\n return ((view as () => unknown)() as () => string)();\n });\n return pass;\n };\n\n let rejectAbort: (reason: unknown) => void = () => undefined;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n timer = setTimeout(\n () =>\n reject(\n new SsrError(\"SSR_TIMEOUT\", `The stream did not finish within ${timeoutMs} ms.`),\n ),\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n const onAbort = (): void =>\n rejectAbort(signal?.reason ?? new Error(\"The render was aborted.\"));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const cleanup = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n disposeAll();\n };\n // Wake a held shell or boundary immediately; late resource settlement must not render again.\n cancelRender = (reason) => {\n rejectAbort(reason);\n cleanup();\n };\n // Marks the abort handled for a render that has already finished (the stream closed, the timer\n // is cleared) and no longer awaits it. While the loop below awaits `abort`, its rejection is\n // rethrown there into `controller.error`, so a timeout or an abort is reported to the reader.\n abort.catch(() => undefined);\n\n try {\n if (signal?.aborted) throw signal.reason;\n // The shell is sent once the resources it holds have settled: a held render that finds a\n // value renders again with it, so the value is in the first chunk and not behind a fallback.\n let answer = renderPass();\n for (let round = 1; answer.held.length > 0; round += 1) {\n await Promise.race([abort, Promise.allSettled(answer.held.map((held) => held.entry))]);\n // No held value arrived (each held fetch failed): this render is the answer, with its fallbacks.\n if (!answer.held.some((held) => settled.has(held.key))) break;\n if (round >= MAX_SHELL_PASSES) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept holding the stream after ${MAX_SHELL_PASSES} shell renders; flatten the data flow.`,\n );\n }\n answer = renderPass();\n }\n\n answer.answered = true;\n untrack(() => {\n for (const error of answer.caught) options.onCaughtError?.(error);\n for (const error of answer.uncaught) options.onUncaughtError?.(error);\n options.onShellReady?.(answer.html);\n });\n push(\n answer.boundaries.length > 0\n ? answer.html + script(SWAP_RUNTIME, options.nonce)\n : answer.html,\n );\n\n const failRemaining = (): void => {\n // Nothing can make progress (failed resources): leave the fallbacks for the client.\n for (const boundary of answer.boundaries.splice(0)) {\n push(\n `<template id=\"s:${boundary.id}\"></template>` +\n script(`$S(${JSON.stringify(boundary.id)},1)`, options.nonce),\n );\n }\n };\n let strikes = 0;\n while (answer.boundaries.length > 0) {\n if (answer.inFlight.size === 0) {\n failRemaining();\n break;\n }\n const settledBefore = settled.size;\n await Promise.race([abort, Promise.race([...answer.inFlight])]);\n const current = answer.boundaries;\n answer.boundaries = [];\n let emitted = false;\n for (const boundary of current) {\n const html = boundary.rebuild();\n if (html === null) continue;\n emitted = true;\n push(\n `<template id=\"s:${boundary.id}\">${html}</template>` +\n script(`$S(${JSON.stringify(boundary.id)})`, options.nonce),\n );\n }\n // Rounds that settle nothing new and emit nothing (only rejections) are bounded.\n strikes = settled.size === settledBefore && !emitted ? strikes + 1 : 0;\n if (answer.boundaries.length > 0 && strikes >= 2) failRemaining();\n }\n\n const data: Record<string, unknown> = {};\n for (const key of answer.requested) {\n if (!settled.has(key)) continue;\n Object.defineProperty(data, key, {\n value: settled.get(key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n if (Object.keys(data).length > 0) {\n push(`<script type=\"application/json\" data-sh=\"${renderId}\">${serialize(data)}</script>`);\n }\n cleanup();\n if (!canceled) controller.close();\n } catch (error) {\n cleanup();\n if (!canceled) controller.error(error);\n }\n },\n cancel(reason) {\n canceled = true;\n cancelRender(reason);\n },\n });\n}\n"],"mappings":"A,+jBA6EA,MAAMA,EAAY,mBAwClB,SAASC,EAAO,EAAc,EAAmC,CAG/D,MAAO,UADLC,IAAU,IAAA,GAAY,GAAK,WAAWA,EAAM,QAAQ,qBAAsB,EAAE,EAAE,GACrD,GAAGC,EAAK,WACrC,CA+BA,SAAgBC,EACd,EACA,EAAyB,CAAC,EACE,CAC5B,IAAMC,EAAWC,EAAQ,UAAY,IACrC,GAAI,OAAOD,GAAa,UAAY,CAACL,EAAU,KAAKK,CAAQ,EAC1D,MAAU,UAAU,oEAAoE,EAE1F,IAAME,EAAYD,EAAQ,WAAa,IACvC,GAAI,OAAOC,GAAc,UAAY,EAAEA,EAAY,IAAM,CAAC,OAAO,SAASA,CAAS,EACjF,MAAU,UAAU,6DAA6D,EAEnF,IAAMC,EAASF,EAAQ,OACjBG,EAAUC,EAAmBJ,EAAQ,OAAO,EAC5CK,EAAU,IAAI,YAEdC,EAAsB,CAAC,EACvBC,MAAyB,CAC7B,IAAMC,EAAoB,CAAC,EAC3B,IAAK,IAAMC,KAAQH,EAAO,OAAO,CAAC,EAChC,GAAI,CACFG,EAAK,QAAQ,CACf,OAASC,EAAO,CACdF,EAAO,KAAKE,CAAK,CACnB,CAEF,GAAIF,EAAO,OAAS,EAClB,MAAMA,EAAO,SAAW,EAAIA,EAAO,GAAS,eAAeA,EAAQ,wBAAwB,CAC/F,EACIG,EAAW,GAEXC,EACAC,MAAgD,IAAA,GAEpD,OAAO,IAAI,eAA2B,CACpC,MAAM,MAAM,EAAY,CACtB,IAAMC,kBAAU,IAAI,IAEdC,kBAAW,IAAI,IACfC,EAAQ,GAAuB,CACnC,GAAId,GAAQ,QAAS,MAAMA,EAAO,OAC7BS,GAAUM,EAAW,QAAQZ,EAAQ,OAAOa,CAAI,CAAC,CACxD,EAGMC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vC,KAAO6B,EAAO,UAClBpC,EAAQ,IAAIO,CAAG,GACpB,OAAO,eAAeuC,EAAMvC,EAAK,CAC/B,MAAOP,EAAQ,IAAIO,CAAG,EACtB,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EAEC,OAAO,KAAKuC,CAAI,CAAC,CAAC,OAAS,GAC7B5C,EAAK,4CAA4CjB,EAAS,IAAI8D,EAAUD,CAAI,EAAE,WAAU,EAE1FZ,EAAQ,EACHrC,GAAUM,EAAW,MAAM,CAClC,OAASP,EAAO,CACdsC,EAAQ,EACHrC,GAAUM,EAAW,MAAMP,CAAK,CACvC,CACF,EACA,OAAO,EAAQ,CACb,EAAW,GACXG,EAAaoC,CAAM,CACrB,CACF,CAAC,CACH,C"}
@@ -1 +1 @@
1
- import{escape as e}from"./server/escape.js";import{ssrAttribute as t}from"./server/attributes.js";import{ssrClass as n,ssrStyle as r}from"./server/class-style.js";import{ssrSelectValue as i,ssrTextArea as a}from"./server/form-controls.js";import{ssr as o,ssrElement as s,ssrHydrationKey as c,ssrRaw as l}from"./server/element.js";import{createServerPortals as u}from"./server/portals.js";import{normalizeTags as d}from"./head/validate.js";import{createServerHead as f}from"./head/server-head.js";import{createComponent as p,memo as m}from"./server/component.js";import{derived as h}from"./server/derived.js";import{HydrationScript as g,generateHydrationScript as _}from"./server/hydration-script.js";import{renderToString as v,renderToStringAsync as y}from"./server/render.js";import{deserialize as b,serialize as x}from"./server/serialize.js";import{renderToStream as S}from"./server/stream.js";import{mergeProps as C}from"./server/index.js";export{g as HydrationScript,p as createComponent,f as createServerHead,u as createServerPortals,h as derived,b as deserialize,e as escape,_ as generateHydrationScript,m as memo,C as mergeProps,d as normalizeTags,S as renderToStream,v as renderToString,y as renderToStringAsync,x as serialize,o as ssr,t as ssrAttribute,n as ssrClass,s as ssrElement,c as ssrHydrationKey,l as ssrRaw,i as ssrSelectValue,r as ssrStyle,a as ssrTextArea};
1
+ import{escape as e}from"./server/escape.js";import{ssrAttribute as t}from"./server/attributes.js";import{ssrClass as n,ssrStyle as r}from"./server/class-style.js";import{ssrSelectValue as i,ssrTextArea as a}from"./server/form-controls.js";import{ssrRawText as o}from"./server/raw-text.js";import{ssr as s,ssrElement as c,ssrHydrationKey as l,ssrRaw as u}from"./server/element.js";import{createServerPortals as d}from"./server/portals.js";import{normalizeTags as f}from"./head/validate.js";import{createServerHead as p}from"./head/server-head.js";import{createComponent as m,memo as h}from"./server/component.js";import{derived as g}from"./server/derived.js";import{HydrationScript as _,generateHydrationScript as v}from"./server/hydration-script.js";import{renderToString as y,renderToStringAsync as b}from"./server/render.js";import{deserialize as x,serialize as S}from"./server/serialize.js";import{renderToStream as C}from"./server/stream.js";import{mergeProps as w}from"./server/index.js";export{_ as HydrationScript,m as createComponent,p as createServerHead,d as createServerPortals,g as derived,x as deserialize,e as escape,v as generateHydrationScript,h as memo,w as mergeProps,f as normalizeTags,C as renderToStream,y as renderToString,b as renderToStringAsync,S as serialize,s as ssr,t as ssrAttribute,n as ssrClass,c as ssrElement,l as ssrHydrationKey,u as ssrRaw,o as ssrRawText,i as ssrSelectValue,r as ssrStyle,a as ssrTextArea};
@@ -1,2 +1,2 @@
1
- import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,classList as a,style as o}from"./class-style.js";import{claims as s}from"./internal/hydration-hooks.js";import{bindRegion as c,createRegion as l}from"./insert.js";import{IGNORED_KEYS as u,attributeName as d,eventPlan as f}from"./internal/react-names.js";import{bindEvent as p}from"./events.js";import{selectShows as m,setSelectValue as h}from"./select-value.js";import{onCleanup as g,untrack as _,useRenderEffect as v}from"@shadow-js/core";function y(e){return typeof e!=`object`||!e?``:w(Reflect.get(e,`__html`))}const b=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]);function x(e){return e.length>2&&e.startsWith(`on`)}function S(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function C(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e}function w(e){return e==null?``:String(e)}function T(e,t){let n=[];if(typeof e!=`object`||!e)return n;let r,i=!1;for(let a of Object.keys(e))b.has(S(a))||u.has(a)||(a===`children`?t&&(r=Reflect.get(e,a),i=!0):n.push([a,Reflect.get(e,a)]));return i&&!n.some(([e])=>e===`value`)&&n.push([`value`,r]),n}function E(e){let t=e.refCleanup;t!==void 0&&(e.refCleanup=void 0,_(t))}function D(e,t,n,s,c){if(t===`ref`){if(E(s),typeof n==`function`){let t=n,r=_(()=>t(e));typeof r==`function`&&(s.refCleanup=r)}}else if(t===`autoFocus`)s.autoFocused||(s.autoFocused=!0,r(e,n));else if(t===`class`||t===`className`)i(e,n,c);else if(t===`style`)s.styleValue=o(e,n,s.styleValue);else if(t===`classList`)s.classListValue=a(e,C(n),s.classListValue);else if(x(t)){s.unbinders.get(t)?.(),s.unbinders.delete(t);let r=f(t,e.localName,e.getAttribute(`type`)?.toLowerCase()??null),i=r.passive&&typeof n==`function`?{handleEvent:n,passive:!0}:n,a=p(e,r.type,i,!0,r.capture);a!==void 0&&s.unbinders.set(t,a)}else t===`innerHTML`?e.innerHTML=w(n):t===`dangerouslySetInnerHTML`?e.innerHTML=y(n):t===`textContent`?e.textContent=w(n):!c&&(t===`value`||t===`defaultValue`)&&e instanceof HTMLSelectElement?h(e,n):!c&&k.has(t)&&t in e?(j(e,t,n,c)&&Reflect.set(e,t,A.has(t)?n??``:!!n),t===`value`&&e instanceof HTMLInputElement&&(e.defaultValue=w(n))):O(e,t,n,c)}function O(r,i,a,o){if(i.startsWith(`prop:`))Reflect.set(r,i.slice(5),a);else if(i.startsWith(`attr:`))e(r,i.slice(5),a);else if(i.startsWith(`bool:`))n(r,i.slice(5),a);else{let n=d(i,o);n.startsWith(`xlink:`)?t(r,`http://www.w3.org/1999/xlink`,n,a):e(r,n,a)}}const k=/* @__PURE__ */ new Set([`value`,`checked`,`selected`,`muted`,`indeterminate`,`defaultValue`,`defaultChecked`]),A=/* @__PURE__ */ new Set([`value`,`defaultValue`]);function j(e,t,n,r){if(r||!k.has(t)||!(t in e))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!m(e,n);let i=Reflect.get(e,t);return A.has(t)?i!==w(n):i!==!!n}function M(e,t,n,r){t===`ref`?E(n):t!==`autoFocus`&&(t===`class`||t===`className`?i(e,void 0,r):t===`style`?n.styleValue=o(e,void 0,n.styleValue):t===`classList`?n.classListValue=a(e,void 0,n.classListValue):x(t)?(n.unbinders.get(t)?.(),n.unbinders.delete(t)):t===`innerHTML`||t===`dangerouslySetInnerHTML`||t===`textContent`?e.textContent=``:!r&&k.has(t)&&t in e?Reflect.set(e,t,A.has(t)?``:!1):O(e,t,void 0,r))}function N(e,t,n,r){let i=/* @__PURE__ */ new Set;for(let[a,o]of t)i.add(a),!(n.values.has(a)&&Object.is(n.values.get(a),o)&&!j(e,a,o,r))&&(n.values.set(a,o),D(e,a,o,n,r));for(let t of[...n.values.keys()])i.has(t)||(n.values.delete(t),M(e,t,n,r))}function P(e,t,n=!1,r=!1){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let i=()=>typeof t==`function`?t():t,a=e.localName===`textarea`;if(!r&&!a){let t=s.current.isClaiming()?s.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,n=l(e,null,t);c(n,()=>i()?.children)}let o={values:/* @__PURE__ */ new Map,unbinders:/* @__PURE__ */ new Map,styleValue:void 0,classListValue:void 0,refCleanup:void 0};g(()=>{for(let e of o.unbinders.values())e();o.unbinders.clear(),E(o)}),v(()=>T(i(),a),t=>{N(e,t,o,n)})}export{P as spread};
1
+ import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,asRecord as a,classList as o,style as s}from"./class-style.js";import{claims as c}from"./internal/hydration-hooks.js";import{bindRegion as l,createRegion as u}from"./insert.js";import{IGNORED_KEYS as d,attributeName as f,eventPlan as p}from"./internal/react-names.js";import{bindEvent as m}from"./events.js";import{plainText as h,setSelectValue as g}from"./select-value.js";import{onCleanup as _,untrack as v,useRenderEffect as y}from"@shadow-js/core";function b(e){return typeof e!=`object`||!e?``:h(Reflect.get(e,`__html`))}const x=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]);function S(e){return e.length>2&&e.startsWith(`on`)}function C(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function w(e,t){let n=[];if(typeof e!=`object`||!e)return n;let r,i=!1;for(let a of Object.keys(e))x.has(C(a))||d.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 T(e){let t=e.refCleanup;t!==void 0&&(e.refCleanup=void 0,v(t))}function E(e,t,n,c,l){if(t===`ref`){if(T(c),typeof n==`function`){let t=n,r=v(()=>t(e));typeof r==`function`&&(c.refCleanup=r)}}else if(t===`autoFocus`)c.autoFocused||(c.autoFocused=!0,r(e,n));else if(t===`class`||t===`className`)i(e,n,l);else if(t===`style`)c.styleValue=s(e,n,c.styleValue);else if(t===`classList`)c.classListValue=o(e,a(n),c.classListValue);else if(S(t)){c.unbinders.get(t)?.(),c.unbinders.delete(t);let r=p(t,e.localName,e.getAttribute(`type`)?.toLowerCase()??null),i=r.passive&&typeof n==`function`?{handleEvent:n,passive:!0}:n,a=m(e,r.type,i,!0,r.capture);a!==void 0&&c.unbinders.set(t,a)}else t===`innerHTML`||t===`dangerouslySetInnerHTML`?e.innerHTML=t===`innerHTML`?h(n):b(n):t===`textContent`?e.textContent=h(n):!l&&(t===`value`||t===`defaultValue`)&&e instanceof HTMLSelectElement?g(e,n):!l&&O.has(t)&&t in e?(A(e,t,n,l)&&Reflect.set(e,t,k.has(t)?n??``:!!n),t===`value`&&e instanceof HTMLInputElement&&(e.defaultValue=h(n))):D(e,t,n,l)}function D(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=f(i,o);n.startsWith(`xlink:`)?t(r,`http://www.w3.org/1999/xlink`,n,a):e(r,n,a)}}const O=/* @__PURE__ */ new Set([`value`,`checked`,`selected`,`muted`,`indeterminate`,`defaultValue`,`defaultChecked`]),k=/* @__PURE__ */ new Set([`value`,`defaultValue`]);function A(e,t,n,r){if(r||!O.has(t)||!(t in e))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!0;let i=Reflect.get(e,t);return k.has(t)?i!==h(n):i!==!!n}function j(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)&&!A(e,a,o,r))&&(n.values.set(a,o),E(e,a,o,n,r));for(let t of[...n.values.keys()])i.has(t)||(n.values.delete(t),E(e,t,void 0,n,r))}function M(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=c.current.isClaiming()?c.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,n=u(e,null,t);l(n,()=>i()?.children)}let o={values:/* @__PURE__ */ new Map,unbinders:/* @__PURE__ */ new Map,styleValue:void 0,classListValue:void 0,refCleanup:void 0};_(()=>{for(let e of o.unbinders.values())e();o.unbinders.clear(),T(o)}),y(()=>w(i(),a),t=>{j(e,t,o,n)})}export{M as spread};
2
2
  //# sourceMappingURL=spread.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"spread.js","names":["innerHtmlValue","value","plainText","FORBIDDEN_NAMES","isEventKey","key","nameOf","colon","asRecord","readEntries","entries","props","hasValue","IGNORED_KEYS","textarea","runRefCleanup","cleanup","state","untrack","applyKey","callRef","el","autoFocus","applyClass","svg","style","classList","plan","eventPlan","handler","unbind","bindEvent","setSelectValue","LIVE_PROPERTIES","liveDiffers","STRING_PROPERTIES","writeKey","setAttribute","setBoolAttribute","wire","attributeName","setAttributeNS","selectShows","live","clearKey","applyEntries","current","spread","read","skipChildren","initial","claims","region","createRegion","bindRegion","onCleanup","useRenderEffect","isSVG"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS } from \"./internal/react-names\";\nimport { selectShows, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Narrows an object value to a record of keys; arrays and primitives are not class maps. */\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n\n/** Text for innerHTML and textContent: null and undefined become the empty string. */\nfunction plainText(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.has(nameOf(key)) || IGNORED_KEYS.has(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\") {\n el.innerHTML = plainText(value);\n return;\n }\n if (key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.has(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.has(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * {@link clearKey} undoes a prop.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES: ReadonlySet<string> = new Set([\n \"value\",\n \"checked\",\n \"selected\",\n \"muted\",\n \"indeterminate\",\n \"defaultValue\",\n \"defaultChecked\",\n]);\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES: ReadonlySet<string> = new Set([\"value\", \"defaultValue\"]);\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.has(key) || !(key in el)) return false;\n if (key === \"value\" && el instanceof HTMLSelectElement) return !selectShows(el, value);\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.has(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/** Undoes a prop that disappeared from the props object. */\nfunction clearKey(el: Element, key: string, state: SpreadState, svg: boolean): void {\n if (key === \"ref\") {\n runRefCleanup(state);\n return;\n }\n // A focus request is not a state: removing the prop does not unfocus the element.\n if (key === \"autoFocus\") return;\n if (key === \"class\" || key === \"className\") {\n applyClass(el, undefined, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, undefined, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, undefined, state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\" || key === \"textContent\") {\n el.textContent = \"\";\n return;\n }\n if (!svg && LIVE_PROPERTIES.has(key) && key in el) {\n Reflect.set(el, key, STRING_PROPERTIES.has(key) ? \"\" : false);\n return;\n }\n writeKey(el, key, undefined, svg);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n clearKey(el, key, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const textarea = el.localName === \"textarea\";\n if (!skipChildren && !textarea) {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n }\n const state: SpreadState = {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":"A,mlBAcA,SAASA,EAAe,EAAwB,CAE9C,OADsB,OAAOC,GAAU,WAAnCA,EAAoD,GACjDC,EAAU,QAAQ,IAAID,EAAO,QAAQ,CAAC,CAC/C,CAGA,MAAME,kBAAkB,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EAezE,SA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,GAAU,WAAcA,EAAwB,EAAIA,EAClFG,EAAWO,EAAG,YAAc,WAClC,GAAI,CAAC4B,GAAgB,CAACnC,EAAU,CAE9B,IAAMoC,EAAUC,EAAO,QAAQ,WAAW,EACrCA,EAAO,QAAQ,WAAW9B,EAAI,IAAI,GAAK,MAAM,KAAKA,EAAG,UAAU,EAChE,IAAA,GACE+B,EAASC,EAAahC,EAAI,KAAM6B,CAAO,EAC7CI,EAAWF,MAAeJ,EAAK,CAAC,EAA6C,QAAQ,CACvF,CACA,IAAM/B,EAAqB,CACzB,uBAAQ,IAAI,IACZ,0BAAW,IAAI,IACf,WAAY,IAAA,GACZ,eAAgB,IAAA,GAChB,WAAY,IAAA,EACd,EAEAsC,MAAgB,CACd,IAAK,IAAMzB,KAAUb,EAAM,UAAU,OAAO,EAAGa,EAAO,EACtDb,EAAM,UAAU,MAAM,EACtBF,EAAcE,CAAK,CACrB,CAAC,EACDuC,MACQ/C,EAAYuC,EAAK,EAAGlC,CAAQ,EACjC,GAAY,CACX+B,EAAaxB,EAAIX,EAASO,EAAOwC,CAAK,CACxC,CACF,CACF,C"}
1
+ {"version":3,"file":"spread.js","names":["innerHtmlValue","value","plainText","FORBIDDEN_NAMES","isEventKey","key","nameOf","colon","readEntries","entries","props","hasValue","IGNORED_KEYS","textarea","runRefCleanup","cleanup","state","untrack","applyKey","callRef","el","autoFocus","applyClass","svg","style","classList","asRecord","plan","eventPlan","handler","unbind","bindEvent","setSelectValue","LIVE_PROPERTIES","liveDiffers","STRING_PROPERTIES","writeKey","setAttribute","setBoolAttribute","wire","attributeName","setAttributeNS","live","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, asRecord, 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 { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = 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/** 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\" || key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = key === \"innerHTML\" ? plainText(value) : innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.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 * a prop that disappeared is undone.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n 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 // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.has(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref cleanup\n // runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const 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 ()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,EAAIX,EAASO,EAAOuC,CAAK,CACxC,CACF,CACF,C"}
@@ -1,37 +1,19 @@
1
- import { invalidAttributeName, warnOnce } from "./internal/diagnostics.js";
2
- //#region src/attributes.ts
1
+ import { SRCDOC_DYNAMIC_DETAIL, invalidAttributeName, warnOnce } from "./internal/diagnostics.js";
2
+ // src/attributes.ts
3
3
  /** Names that can appear in markup: an XML-name subset without `@` or whitespace. */
4
4
  const ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;
5
5
  /**
6
6
  * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values
7
7
  * (`animate`, `set`) are checked too: with `attributeName="href"` they write an `href` by animation.
8
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
- ]);
9
+ const URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;
10
+ /**
11
+ * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings "true" and "false"
12
+ * rather than a present or absent attribute.
13
+ */
14
+ const STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;
29
15
  /** URL prefixes (after normalization) that are never written. */
30
- const UNSAFE_URL_PREFIXES = [
31
- "javascript:",
32
- "data:text/html",
33
- "vbscript:"
34
- ];
16
+ const UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\/html|vbscript:)/;
35
17
  /**
36
18
  * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the
37
19
  * ones that come from spread, so no unvalidated name reaches `setAttribute`.
@@ -40,32 +22,23 @@ const UNSAFE_URL_PREFIXES = [
40
22
  function assertAttributeName(name) {
41
23
  if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);
42
24
  }
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. */
25
+ /** Removes C0 and C1 control characters (`\p{Cc}`), which browsers ignore inside a URL scheme. */
48
26
  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;
27
+ return text.replace(/\p{Cc}/gu, "");
55
28
  }
56
29
  /** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */
57
30
  function isUnsafeUrl(value) {
58
- const normalized = stripControls(value).trim().toLowerCase();
59
- return UNSAFE_URL_PREFIXES.some((prefix) => normalized.startsWith(prefix));
31
+ return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());
60
32
  }
61
33
  /**
62
34
  * Reports whether writing `value` to the attribute `name` would run script: the URL check that
63
35
  * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer
64
36
  * 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
37
+ * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control
66
38
  * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or
67
39
  * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,
68
- * each `;`-separated entry of `values` on its own.
40
+ * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the
41
+ * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).
69
42
  *
70
43
  * @param name Attribute name, in any case.
71
44
  * @param value The text that would be written.
@@ -81,14 +54,14 @@ function isUnsafeUrl(value) {
81
54
  */
82
55
  function isUnsafeUrlAttribute(name, value) {
83
56
  const lowerName = name.toLowerCase();
84
- if (!URL_ATTRIBUTES.has(lowerName)) return false;
57
+ if (!URL_ATTRIBUTES.test(lowerName)) return false;
85
58
  return lowerName === "values" ? value.split(";").some(isUnsafeUrl) : isUnsafeUrl(value);
86
59
  }
87
60
  /** Text to write for `value`, or null when the attribute must be removed. */
88
61
  function attributeText(lowerName, value) {
89
62
  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" : "";
63
+ if (value === false) return STRING_VALUED.test(lowerName) ? "false" : null;
64
+ if (value === true) return STRING_VALUED.test(lowerName) ? "true" : "";
92
65
  return String(value);
93
66
  }
94
67
  /** The part of a qualified name after the prefix (`xlink:href` gives `href`). */
@@ -105,6 +78,8 @@ function commit(el, namespace, qualified, value) {
105
78
  else el.removeAttributeNS(namespace, localPart(qualified));
106
79
  return;
107
80
  }
81
+ if (/^on./.test(lowerName)) return;
82
+ if (lowerName === "srcdoc") warnOnce("SRCDOC_DYNAMIC", SRCDOC_DYNAMIC_DETAIL);
108
83
  if (isUnsafeUrlAttribute(lowerName, text)) {
109
84
  warnOnce("UNSAFE_URL_BLOCKED", `Blocked a script URL in the "${qualified}" attribute.`);
110
85
  return;
@@ -117,7 +92,13 @@ function commit(el, namespace, qualified, value) {
117
92
  * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a
118
93
  * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the
119
94
  * 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`.
95
+ * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with
96
+ * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.
97
+ *
98
+ * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like
99
+ * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a
100
+ * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with
101
+ * `SRCDOC_DYNAMIC` for every value written here.
121
102
  *
122
103
  * @param el Target element.
123
104
  * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.
@@ -185,12 +166,8 @@ function setAttributeNS(el, namespace, name, value) {
185
166
  */
186
167
  function setBoolAttribute(el, name, value) {
187
168
  assertAttributeName(name);
188
- const present = el.hasAttribute(name);
189
- if (value) {
190
- if (!present) el.setAttribute(name, "");
191
- } else if (present) el.removeAttribute(name);
169
+ el.toggleAttribute(name, Boolean(value));
192
170
  }
193
- //#endregion
194
171
  export { assertAttributeName, isUnsafeUrlAttribute, setAttribute, setAttributeNS, setBoolAttribute };
195
172
 
196
173
  //# sourceMappingURL=attributes.js.map
@@ -1 +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.setAttribute(name, \"\");\n } else if (present) {\n el.removeAttribute(name);\n }\n}\n"],"mappings":";;;AAGA,MAAM,iBAAiB;;;;;AAMvB,MAAM,iCAAiB,IAAI,IAAI;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,wCAAwB,IAAI,IAAI;CAAC;CAAa;CAAc;AAAiB,CAAC;;AAGpF,MAAM,sBAAsB;CAAC;CAAe;CAAkB;AAAW;;;;;;AAOzE,SAAgB,oBAAoB,MAAoB;CACtD,IAAI,CAAC,eAAe,KAAK,IAAI,GAAG,MAAM,qBAAqB,IAAI;AACjE;;AAGA,SAAS,eAAe,WAA4B;CAClD,OACE,UAAU,WAAW,OAAO,KAC5B,UAAU,WAAW,OAAO,KAC5B,sBAAsB,IAAI,SAAS;AAEvC;;AAGA,SAAS,cAAc,MAAsB;CAC3C,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,MAAM;EACvB,MAAM,OAAO,KAAK,WAAW,CAAC;EAC9B,IAAI,OAAO,OAAS,OAAO,OAAQ,OAAO,MAAO,QAAQ;CAC3D;CACA,OAAO;AACT;;AAGA,SAAS,YAAY,OAAwB;CAC3C,MAAM,aAAa,cAAc,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY;CAC3D,OAAO,oBAAoB,MAAM,WAAW,WAAW,WAAW,MAAM,CAAC;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C9B;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,eAAe,IAAa,WAAmB,MAAc,OAAsB;CACjG,oBAAoB,IAAI;CACxB,OAAO,IAAI,cAAc,KAAK,OAAO,WAAW,MAAM,KAAK;AAC7D;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,iBAAiB,IAAa,MAAc,OAAsB;CAChF,oBAAoB,IAAI;CACxB,MAAM,UAAU,GAAG,aAAa,IAAI;CACpC,IAAI,OACE;MAAA,CAAC,SAAS,GAAG,aAAa,MAAM,EAAE;CAAA,OACjC,IAAI,SACT,GAAG,gBAAgB,IAAI;AAE3B"}
1
+ {"version":3,"file":"attributes.js","names":[],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, 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 = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|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/** Removes C0 and C1 control characters (`\\p{Cc}`), which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n return text.replace(/\\p{Cc}/gu, \"\");\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 return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());\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`, `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. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\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.test(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 STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(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 // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\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`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\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 el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":";;;AAGA,MAAM,iBAAiB;;;;;AAMvB,MAAM,iBAAiB;;;;;AAMvB,MAAM,gBAAgB;;AAGtB,MAAM,sBAAsB;;;;;;AAO5B,SAAgB,oBAAoB,MAAoB;CACtD,IAAI,CAAC,eAAe,KAAK,IAAI,GAAG,MAAM,qBAAqB,IAAI;AACjE;;AAGA,SAAS,cAAc,MAAsB;CAC3C,OAAO,KAAK,QAAQ,YAAY,EAAE;AACpC;;AAGA,SAAS,YAAY,OAAwB;CAC3C,OAAO,oBAAoB,KAAK,cAAc,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC;AAC3E;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,qBAAqB,MAAc,OAAwB;CACzE,MAAM,YAAY,KAAK,YAAY;CACnC,IAAI,CAAC,eAAe,KAAK,SAAS,GAAG,OAAO;CAE5C,OAAO,cAAc,WAAW,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,WAAW,IAAI,YAAY,KAAK;AACxF;;AAGA,SAAS,cAAc,WAAmB,OAA+B;CACvE,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,IAAI,UAAU,OAAO,OAAO,cAAc,KAAK,SAAS,IAAI,UAAU;CACtE,IAAI,UAAU,MAAM,OAAO,cAAc,KAAK,SAAS,IAAI,SAAS;CACpE,OAAO,OAAO,KAAK;AACrB;;AAGA,SAAS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
- //#region src/autofocus.ts
3
+ // src/autofocus.ts
4
4
  /**
5
5
  * Focuses an element written with `autoFocus` (React parity) once it is inserted into the document
6
6
  * by a client render or update. The compiler calls this for an `autoFocus` attribute and for
@@ -39,7 +39,6 @@ function autoFocus(el, enabled) {
39
39
  if (el.isConnected && free && (el instanceof HTMLElement || el instanceof SVGElement)) el.focus();
40
40
  });
41
41
  }
42
- //#endregion
43
42
  export { autoFocus };
44
43
 
45
44
  //# sourceMappingURL=autofocus.js.map
@@ -1,6 +1,6 @@
1
1
  import { cssValueText } from "./internal/css-units.js";
2
2
  import { HTML_NS } from "./internal/names.js";
3
- //#region src/class-style.ts
3
+ // src/class-style.ts
4
4
  /** Appends the truthy class names of `value` (strings, numbers, nested arrays, objects) to `parts`. */
5
5
  function collectClasses(root, parts) {
6
6
  const frames = [[root]];
@@ -80,11 +80,15 @@ function applyClass(el, value, svg) {
80
80
  function className(el, value) {
81
81
  applyClass(el, value, el.namespaceURI !== HTML_NS);
82
82
  }
83
- /** Narrows an object value to a record of keys; arrays and primitives are not class maps. */
83
+ /** Narrows an object value to a record of keys; arrays and primitives are not class maps. @internal */
84
84
  function asRecord(value) {
85
85
  if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
86
86
  return value;
87
87
  }
88
+ /** Whether `key` is switched on in `map`: own properties only, so a key named `constructor` reads as it was written. */
89
+ function enabled(map, key) {
90
+ return Object.hasOwn(map, key) && Boolean(map[key]);
91
+ }
88
92
  /**
89
93
  * Toggles individual classes from an object: the helper compiled templates call for `classList`.
90
94
  * Unlike {@link className}, it leaves classes it did not set alone: only keys whose truthiness
@@ -110,8 +114,8 @@ function classList(el, value, prev) {
110
114
  const before = prev ?? {};
111
115
  const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(next)]);
112
116
  for (const key of keys) {
113
- const now = Boolean(next[key]);
114
- if (now === Boolean(before[key])) continue;
117
+ const now = enabled(next, key);
118
+ if (now === enabled(before, key)) continue;
115
119
  for (const token of key.split(/\s+/)) if (token !== "") el.classList.toggle(token, now);
116
120
  }
117
121
  return next;
@@ -158,11 +162,15 @@ function setStyleProperty(el, name, value) {
158
162
  *
159
163
  * @param el HTML or SVG element.
160
164
  * @param value An object of properties (camelCase, kebab-case or custom names). A string replaces
161
- * `cssText`. `null`, `undefined` and `false` remove the `style` attribute.
165
+ * `cssText`. An array of strings and objects (not nested; `null`, `undefined`, `false` and `""`
166
+ * items are skipped) is written in order, so a later declaration wins, exactly as `ssrStyle` writes it
167
+ * on the server. `null`, `undefined` and `false` remove the `style` attribute.
162
168
  * @param prev The value returned by the previous call. Undefined (the first call) diffs against an
163
- * empty style. When it is a string, `cssText` is cleared before the object is written.
169
+ * empty style. When it is a string or an array, `cssText` is cleared before the object is written.
164
170
  * @returns What to pass back as `prev` next time: a shallow copy of an object value, otherwise
165
171
  * `value` itself.
172
+ * @throws TypeError (production message `SHADOW_STYLE_ITEM`) when an array holds a nested array or a
173
+ * value that is not a string or an object.
166
174
  * @example
167
175
  * import { style } from "@shadow-js/web";
168
176
  *
@@ -181,9 +189,18 @@ function style(el, value, prev) {
181
189
  el.style.cssText = String(value);
182
190
  return value;
183
191
  }
192
+ if (Array.isArray(value)) {
193
+ el.style.cssText = "";
194
+ for (const item of value) if (typeof item === "string") el.style.cssText += `;${item}`;
195
+ else if (item !== null && item !== void 0 && item !== false) {
196
+ if (typeof item !== "object" || Array.isArray(item)) throw new TypeError("style(): an array holds only strings and objects.");
197
+ style(el, item, {});
198
+ }
199
+ return value;
200
+ }
184
201
  const next = { ...value };
185
202
  const before = asRecord(prev) ?? {};
186
- if (typeof prev === "string") el.style.cssText = "";
203
+ if (typeof prev === "string" || Array.isArray(prev)) el.style.cssText = "";
187
204
  const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(next)]);
188
205
  for (const key of keys) {
189
206
  if (Object.is(before[key], next[key])) continue;
@@ -191,7 +208,6 @@ function style(el, value, prev) {
191
208
  }
192
209
  return next;
193
210
  }
194
- //#endregion
195
- export { applyClass, classList, className, setStyleProperty, style, toCssProperty };
211
+ export { applyClass, asRecord, classList, className, setStyleProperty, style, toCssProperty };
196
212
 
197
213
  //# sourceMappingURL=class-style.js.map