@shadow-js/core 0.1.0 → 1.0.0

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 (387) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +2 -2
  3. package/README.md +134 -331
  4. package/dist/dev/action.d.ts +36 -0
  5. package/dist/dev/action.js +90 -0
  6. package/dist/dev/action.js.map +1 -0
  7. package/dist/dev/cache.d.ts +35 -0
  8. package/dist/dev/cache.js +62 -0
  9. package/dist/dev/cache.js.map +1 -0
  10. package/dist/dev/context.d.ts +106 -0
  11. package/dist/dev/context.js +111 -0
  12. package/dist/dev/context.js.map +1 -0
  13. package/dist/dev/effect.d.ts +122 -0
  14. package/dist/dev/effect.js +111 -0
  15. package/dist/dev/effect.js.map +1 -0
  16. package/dist/dev/env.d.ts +29 -0
  17. package/dist/dev/env.js +31 -0
  18. package/dist/dev/env.js.map +1 -0
  19. package/dist/dev/events.d.ts +28 -0
  20. package/dist/dev/events.js +33 -0
  21. package/dist/dev/events.js.map +1 -0
  22. package/dist/dev/extend/index.d.ts +331 -0
  23. package/dist/dev/extend/index.js +317 -0
  24. package/dist/dev/extend/index.js.map +1 -0
  25. package/dist/dev/external-store.d.ts +60 -0
  26. package/dist/dev/external-store.js +60 -0
  27. package/dist/dev/external-store.js.map +1 -0
  28. package/dist/dev/index.d.ts +29 -0
  29. package/dist/dev/index.js +26 -0
  30. package/dist/dev/internal/concurrency.d.ts +213 -0
  31. package/dist/dev/internal/concurrency.js +632 -0
  32. package/dist/dev/internal/concurrency.js.map +1 -0
  33. package/dist/dev/internal/devtools.d.ts +71 -0
  34. package/dist/dev/internal/devtools.js +77 -0
  35. package/dist/dev/internal/devtools.js.map +1 -0
  36. package/dist/dev/internal/diagnostics.d.ts +90 -0
  37. package/dist/dev/internal/diagnostics.js +102 -0
  38. package/dist/dev/internal/diagnostics.js.map +1 -0
  39. package/dist/dev/internal/dispose.d.ts +28 -0
  40. package/dist/dev/internal/dispose.js +49 -0
  41. package/dist/dev/internal/dispose.js.map +1 -0
  42. package/dist/dev/internal/flags.js +11 -0
  43. package/dist/dev/internal/flags.js.map +1 -0
  44. package/dist/dev/internal/graph.d.ts +233 -0
  45. package/dist/dev/internal/graph.js +578 -0
  46. package/dist/dev/internal/graph.js.map +1 -0
  47. package/dist/dev/internal/hydration-flag.d.ts +33 -0
  48. package/dist/dev/internal/hydration-flag.js +46 -0
  49. package/dist/dev/internal/hydration-flag.js.map +1 -0
  50. package/dist/dev/internal/messages.d.ts +56 -0
  51. package/dist/dev/internal/messages.js +54 -0
  52. package/dist/dev/internal/messages.js.map +1 -0
  53. package/dist/dev/internal/owner.d.ts +142 -0
  54. package/dist/dev/internal/owner.js +290 -0
  55. package/dist/dev/internal/owner.js.map +1 -0
  56. package/dist/dev/internal/queue.js +46 -0
  57. package/dist/dev/internal/queue.js.map +1 -0
  58. package/dist/dev/internal/scheduler.d.ts +113 -0
  59. package/dist/dev/internal/scheduler.js +287 -0
  60. package/dist/dev/internal/scheduler.js.map +1 -0
  61. package/dist/dev/internal/state.d.ts +141 -0
  62. package/dist/dev/internal/state.js +28 -0
  63. package/dist/dev/internal/state.js.map +1 -0
  64. package/dist/dev/internal/suspension.d.ts +43 -0
  65. package/dist/dev/internal/suspension.js +45 -0
  66. package/dist/dev/internal/suspension.js.map +1 -0
  67. package/dist/dev/internal/types.d.ts +46 -0
  68. package/dist/dev/list.d.ts +93 -0
  69. package/dist/dev/list.js +282 -0
  70. package/dist/dev/list.js.map +1 -0
  71. package/dist/dev/memo.d.ts +60 -0
  72. package/dist/dev/memo.js +41 -0
  73. package/dist/dev/memo.js.map +1 -0
  74. package/dist/dev/optimistic.d.ts +26 -0
  75. package/dist/dev/optimistic.js +45 -0
  76. package/dist/dev/optimistic.js.map +1 -0
  77. package/dist/dev/ownership.d.ts +204 -0
  78. package/dist/dev/ownership.js +261 -0
  79. package/dist/dev/ownership.js.map +1 -0
  80. package/dist/dev/props.d.ts +134 -0
  81. package/dist/dev/props.js +282 -0
  82. package/dist/dev/props.js.map +1 -0
  83. package/dist/dev/reaction.d.ts +29 -0
  84. package/dist/dev/reaction.js +61 -0
  85. package/dist/dev/reaction.js.map +1 -0
  86. package/dist/dev/reducer.d.ts +41 -0
  87. package/dist/dev/reducer.js +39 -0
  88. package/dist/dev/reducer.js.map +1 -0
  89. package/dist/dev/refs.d.ts +52 -0
  90. package/dist/dev/refs.js +58 -0
  91. package/dist/dev/refs.js.map +1 -0
  92. package/dist/dev/resource.d.ts +135 -0
  93. package/dist/dev/resource.js +177 -0
  94. package/dist/dev/resource.js.map +1 -0
  95. package/dist/dev/selector.d.ts +34 -0
  96. package/dist/dev/selector.js +118 -0
  97. package/dist/dev/selector.js.map +1 -0
  98. package/dist/dev/signal.d.ts +42 -0
  99. package/dist/dev/signal.js +39 -0
  100. package/dist/dev/signal.js.map +1 -0
  101. package/dist/dev/store/index.d.ts +5 -0
  102. package/dist/dev/store/index.js +4 -0
  103. package/dist/dev/store/nodes.js +192 -0
  104. package/dist/dev/store/nodes.js.map +1 -0
  105. package/dist/dev/store/proxies.js +160 -0
  106. package/dist/dev/store/proxies.js.map +1 -0
  107. package/dist/dev/store/read.d.ts +39 -0
  108. package/dist/dev/store/read.js +72 -0
  109. package/dist/dev/store/read.js.map +1 -0
  110. package/dist/dev/store/reconcile.d.ts +73 -0
  111. package/dist/dev/store/reconcile.js +186 -0
  112. package/dist/dev/store/reconcile.js.map +1 -0
  113. package/dist/dev/store/types.d.ts +106 -0
  114. package/dist/dev/store/use-store.d.ts +60 -0
  115. package/dist/dev/store/use-store.js +168 -0
  116. package/dist/dev/store/use-store.js.map +1 -0
  117. package/dist/dev/suspense.d.ts +101 -0
  118. package/dist/dev/suspense.js +45 -0
  119. package/dist/dev/suspense.js.map +1 -0
  120. package/dist/dev/transitions.d.ts +77 -0
  121. package/dist/dev/transitions.js +101 -0
  122. package/dist/dev/transitions.js.map +1 -0
  123. package/dist/prod/action.js +2 -0
  124. package/dist/prod/action.js.map +1 -0
  125. package/dist/prod/cache.js +2 -0
  126. package/dist/prod/cache.js.map +1 -0
  127. package/dist/prod/context.js +2 -0
  128. package/dist/prod/context.js.map +1 -0
  129. package/dist/prod/effect.js +2 -0
  130. package/dist/prod/effect.js.map +1 -0
  131. package/dist/prod/env.js +2 -0
  132. package/dist/prod/env.js.map +1 -0
  133. package/dist/prod/events.js +2 -0
  134. package/dist/prod/events.js.map +1 -0
  135. package/dist/prod/extend/index.js +2 -0
  136. package/dist/prod/extend/index.js.map +1 -0
  137. package/dist/prod/external-store.js +2 -0
  138. package/dist/prod/external-store.js.map +1 -0
  139. package/dist/prod/index.js +1 -0
  140. package/dist/prod/internal/concurrency.js +2 -0
  141. package/dist/prod/internal/concurrency.js.map +1 -0
  142. package/dist/prod/internal/devtools.js +2 -0
  143. package/dist/prod/internal/devtools.js.map +1 -0
  144. package/dist/prod/internal/diagnostics.js +2 -0
  145. package/dist/prod/internal/diagnostics.js.map +1 -0
  146. package/dist/prod/internal/dispose.js +2 -0
  147. package/dist/prod/internal/dispose.js.map +1 -0
  148. package/dist/prod/internal/flags.js +2 -0
  149. package/dist/prod/internal/flags.js.map +1 -0
  150. package/dist/prod/internal/graph.js +2 -0
  151. package/dist/prod/internal/graph.js.map +1 -0
  152. package/dist/prod/internal/hydration-flag.js +2 -0
  153. package/dist/prod/internal/hydration-flag.js.map +1 -0
  154. package/dist/prod/internal/messages.js +2 -0
  155. package/dist/prod/internal/messages.js.map +1 -0
  156. package/dist/prod/internal/owner.js +2 -0
  157. package/dist/prod/internal/owner.js.map +1 -0
  158. package/dist/prod/internal/queue.js +2 -0
  159. package/dist/prod/internal/queue.js.map +1 -0
  160. package/dist/prod/internal/scheduler.js +2 -0
  161. package/dist/prod/internal/scheduler.js.map +1 -0
  162. package/dist/prod/internal/state.js +2 -0
  163. package/dist/prod/internal/state.js.map +1 -0
  164. package/dist/prod/internal/suspension.js +2 -0
  165. package/dist/prod/internal/suspension.js.map +1 -0
  166. package/dist/prod/list.js +2 -0
  167. package/dist/prod/list.js.map +1 -0
  168. package/dist/prod/memo.js +2 -0
  169. package/dist/prod/memo.js.map +1 -0
  170. package/dist/prod/optimistic.js +2 -0
  171. package/dist/prod/optimistic.js.map +1 -0
  172. package/dist/prod/ownership.js +2 -0
  173. package/dist/prod/ownership.js.map +1 -0
  174. package/dist/prod/props.js +2 -0
  175. package/dist/prod/props.js.map +1 -0
  176. package/dist/prod/reaction.js +2 -0
  177. package/dist/prod/reaction.js.map +1 -0
  178. package/dist/prod/reducer.js +2 -0
  179. package/dist/prod/reducer.js.map +1 -0
  180. package/dist/prod/refs.js +2 -0
  181. package/dist/prod/refs.js.map +1 -0
  182. package/dist/prod/resource.js +2 -0
  183. package/dist/prod/resource.js.map +1 -0
  184. package/dist/prod/selector.js +2 -0
  185. package/dist/prod/selector.js.map +1 -0
  186. package/dist/prod/signal.js +2 -0
  187. package/dist/prod/signal.js.map +1 -0
  188. package/dist/prod/store/index.js +1 -0
  189. package/dist/prod/store/nodes.js +2 -0
  190. package/dist/prod/store/nodes.js.map +1 -0
  191. package/dist/prod/store/proxies.js +2 -0
  192. package/dist/prod/store/proxies.js.map +1 -0
  193. package/dist/prod/store/read.js +2 -0
  194. package/dist/prod/store/read.js.map +1 -0
  195. package/dist/prod/store/reconcile.js +2 -0
  196. package/dist/prod/store/reconcile.js.map +1 -0
  197. package/dist/prod/store/use-store.js +2 -0
  198. package/dist/prod/store/use-store.js.map +1 -0
  199. package/dist/prod/suspense.js +2 -0
  200. package/dist/prod/suspense.js.map +1 -0
  201. package/dist/prod/transitions.js +2 -0
  202. package/dist/prod/transitions.js.map +1 -0
  203. package/dist/server/action.js +2 -0
  204. package/dist/server/action.js.map +1 -0
  205. package/dist/server/cache.js +2 -0
  206. package/dist/server/cache.js.map +1 -0
  207. package/dist/server/context.js +2 -0
  208. package/dist/server/context.js.map +1 -0
  209. package/dist/server/effect.js +2 -0
  210. package/dist/server/effect.js.map +1 -0
  211. package/dist/server/env.js +2 -0
  212. package/dist/server/env.js.map +1 -0
  213. package/dist/server/events.js +2 -0
  214. package/dist/server/events.js.map +1 -0
  215. package/dist/server/extend/index.js +2 -0
  216. package/dist/server/extend/index.js.map +1 -0
  217. package/dist/server/external-store.js +2 -0
  218. package/dist/server/external-store.js.map +1 -0
  219. package/dist/server/index.js +1 -0
  220. package/dist/server/internal/concurrency.js +2 -0
  221. package/dist/server/internal/concurrency.js.map +1 -0
  222. package/dist/server/internal/devtools.js +2 -0
  223. package/dist/server/internal/devtools.js.map +1 -0
  224. package/dist/server/internal/diagnostics.js +2 -0
  225. package/dist/server/internal/diagnostics.js.map +1 -0
  226. package/dist/server/internal/dispose.js +2 -0
  227. package/dist/server/internal/dispose.js.map +1 -0
  228. package/dist/server/internal/flags.js +2 -0
  229. package/dist/server/internal/flags.js.map +1 -0
  230. package/dist/server/internal/graph.js +2 -0
  231. package/dist/server/internal/graph.js.map +1 -0
  232. package/dist/server/internal/hydration-flag.js +2 -0
  233. package/dist/server/internal/hydration-flag.js.map +1 -0
  234. package/dist/server/internal/messages.js +2 -0
  235. package/dist/server/internal/messages.js.map +1 -0
  236. package/dist/server/internal/owner.js +2 -0
  237. package/dist/server/internal/owner.js.map +1 -0
  238. package/dist/server/internal/queue.js +2 -0
  239. package/dist/server/internal/queue.js.map +1 -0
  240. package/dist/server/internal/scheduler.js +2 -0
  241. package/dist/server/internal/scheduler.js.map +1 -0
  242. package/dist/server/internal/state.js +2 -0
  243. package/dist/server/internal/state.js.map +1 -0
  244. package/dist/server/internal/suspension.js +2 -0
  245. package/dist/server/internal/suspension.js.map +1 -0
  246. package/dist/server/list.js +2 -0
  247. package/dist/server/list.js.map +1 -0
  248. package/dist/server/memo.js +2 -0
  249. package/dist/server/memo.js.map +1 -0
  250. package/dist/server/optimistic.js +2 -0
  251. package/dist/server/optimistic.js.map +1 -0
  252. package/dist/server/ownership.js +2 -0
  253. package/dist/server/ownership.js.map +1 -0
  254. package/dist/server/props.js +2 -0
  255. package/dist/server/props.js.map +1 -0
  256. package/dist/server/reaction.js +2 -0
  257. package/dist/server/reaction.js.map +1 -0
  258. package/dist/server/reducer.js +2 -0
  259. package/dist/server/reducer.js.map +1 -0
  260. package/dist/server/refs.js +2 -0
  261. package/dist/server/refs.js.map +1 -0
  262. package/dist/server/resource.js +2 -0
  263. package/dist/server/resource.js.map +1 -0
  264. package/dist/server/selector.js +2 -0
  265. package/dist/server/selector.js.map +1 -0
  266. package/dist/server/signal.js +2 -0
  267. package/dist/server/signal.js.map +1 -0
  268. package/dist/server/store/index.js +1 -0
  269. package/dist/server/store/nodes.js +2 -0
  270. package/dist/server/store/nodes.js.map +1 -0
  271. package/dist/server/store/proxies.js +2 -0
  272. package/dist/server/store/proxies.js.map +1 -0
  273. package/dist/server/store/read.js +2 -0
  274. package/dist/server/store/read.js.map +1 -0
  275. package/dist/server/store/reconcile.js +2 -0
  276. package/dist/server/store/reconcile.js.map +1 -0
  277. package/dist/server/store/use-store.js +2 -0
  278. package/dist/server/store/use-store.js.map +1 -0
  279. package/dist/server/suspense.js +2 -0
  280. package/dist/server/suspense.js.map +1 -0
  281. package/dist/server/transitions.js +2 -0
  282. package/dist/server/transitions.js.map +1 -0
  283. package/dist/server-dev/action.js +90 -0
  284. package/dist/server-dev/action.js.map +1 -0
  285. package/dist/server-dev/cache.js +62 -0
  286. package/dist/server-dev/cache.js.map +1 -0
  287. package/dist/server-dev/context.js +108 -0
  288. package/dist/server-dev/context.js.map +1 -0
  289. package/dist/server-dev/effect.js +56 -0
  290. package/dist/server-dev/effect.js.map +1 -0
  291. package/dist/server-dev/env.js +31 -0
  292. package/dist/server-dev/env.js.map +1 -0
  293. package/dist/server-dev/events.js +33 -0
  294. package/dist/server-dev/events.js.map +1 -0
  295. package/dist/server-dev/extend/index.js +317 -0
  296. package/dist/server-dev/extend/index.js.map +1 -0
  297. package/dist/server-dev/external-store.js +46 -0
  298. package/dist/server-dev/external-store.js.map +1 -0
  299. package/dist/server-dev/index.js +26 -0
  300. package/dist/server-dev/internal/concurrency.js +633 -0
  301. package/dist/server-dev/internal/concurrency.js.map +1 -0
  302. package/dist/server-dev/internal/devtools.js +77 -0
  303. package/dist/server-dev/internal/devtools.js.map +1 -0
  304. package/dist/server-dev/internal/diagnostics.js +102 -0
  305. package/dist/server-dev/internal/diagnostics.js.map +1 -0
  306. package/dist/server-dev/internal/dispose.js +49 -0
  307. package/dist/server-dev/internal/dispose.js.map +1 -0
  308. package/dist/server-dev/internal/flags.js +11 -0
  309. package/dist/server-dev/internal/flags.js.map +1 -0
  310. package/dist/server-dev/internal/graph.js +578 -0
  311. package/dist/server-dev/internal/graph.js.map +1 -0
  312. package/dist/server-dev/internal/hydration-flag.js +46 -0
  313. package/dist/server-dev/internal/hydration-flag.js.map +1 -0
  314. package/dist/server-dev/internal/messages.js +54 -0
  315. package/dist/server-dev/internal/messages.js.map +1 -0
  316. package/dist/server-dev/internal/owner.js +290 -0
  317. package/dist/server-dev/internal/owner.js.map +1 -0
  318. package/dist/server-dev/internal/queue.js +46 -0
  319. package/dist/server-dev/internal/queue.js.map +1 -0
  320. package/dist/server-dev/internal/scheduler.js +287 -0
  321. package/dist/server-dev/internal/scheduler.js.map +1 -0
  322. package/dist/server-dev/internal/state.js +28 -0
  323. package/dist/server-dev/internal/state.js.map +1 -0
  324. package/dist/server-dev/internal/suspension.js +45 -0
  325. package/dist/server-dev/internal/suspension.js.map +1 -0
  326. package/dist/server-dev/list.js +282 -0
  327. package/dist/server-dev/list.js.map +1 -0
  328. package/dist/server-dev/memo.js +41 -0
  329. package/dist/server-dev/memo.js.map +1 -0
  330. package/dist/server-dev/optimistic.js +45 -0
  331. package/dist/server-dev/optimistic.js.map +1 -0
  332. package/dist/server-dev/ownership.js +261 -0
  333. package/dist/server-dev/ownership.js.map +1 -0
  334. package/dist/server-dev/props.js +282 -0
  335. package/dist/server-dev/props.js.map +1 -0
  336. package/dist/server-dev/reaction.js +61 -0
  337. package/dist/server-dev/reaction.js.map +1 -0
  338. package/dist/server-dev/reducer.js +39 -0
  339. package/dist/server-dev/reducer.js.map +1 -0
  340. package/dist/server-dev/refs.js +58 -0
  341. package/dist/server-dev/refs.js.map +1 -0
  342. package/dist/server-dev/resource.js +176 -0
  343. package/dist/server-dev/resource.js.map +1 -0
  344. package/dist/server-dev/selector.js +82 -0
  345. package/dist/server-dev/selector.js.map +1 -0
  346. package/dist/server-dev/signal.js +39 -0
  347. package/dist/server-dev/signal.js.map +1 -0
  348. package/dist/server-dev/store/index.js +4 -0
  349. package/dist/server-dev/store/nodes.js +192 -0
  350. package/dist/server-dev/store/nodes.js.map +1 -0
  351. package/dist/server-dev/store/proxies.js +160 -0
  352. package/dist/server-dev/store/proxies.js.map +1 -0
  353. package/dist/server-dev/store/read.js +72 -0
  354. package/dist/server-dev/store/read.js.map +1 -0
  355. package/dist/server-dev/store/reconcile.js +186 -0
  356. package/dist/server-dev/store/reconcile.js.map +1 -0
  357. package/dist/server-dev/store/use-store.js +168 -0
  358. package/dist/server-dev/store/use-store.js.map +1 -0
  359. package/dist/server-dev/suspense.js +45 -0
  360. package/dist/server-dev/suspense.js.map +1 -0
  361. package/dist/server-dev/transitions.js +86 -0
  362. package/dist/server-dev/transitions.js.map +1 -0
  363. package/package.json +111 -50
  364. package/dist/chunk-6Y3CCWOY.js +0 -887
  365. package/dist/chunk-6Y3CCWOY.js.map +0 -1
  366. package/dist/chunk-B5FTYDUG.js +0 -3
  367. package/dist/chunk-B5FTYDUG.js.map +0 -1
  368. package/dist/index.cjs +0 -2000
  369. package/dist/index.cjs.map +0 -1
  370. package/dist/index.d.cts +0 -609
  371. package/dist/index.d.ts +0 -609
  372. package/dist/index.js +0 -1094
  373. package/dist/index.js.map +0 -1
  374. package/dist/jsx-Bugil6CJ.d.cts +0 -151
  375. package/dist/jsx-Bugil6CJ.d.ts +0 -151
  376. package/dist/jsx-dev-runtime.cjs +0 -742
  377. package/dist/jsx-dev-runtime.cjs.map +0 -1
  378. package/dist/jsx-dev-runtime.d.cts +0 -2
  379. package/dist/jsx-dev-runtime.d.ts +0 -2
  380. package/dist/jsx-dev-runtime.js +0 -4
  381. package/dist/jsx-dev-runtime.js.map +0 -1
  382. package/dist/jsx-runtime.cjs +0 -742
  383. package/dist/jsx-runtime.cjs.map +0 -1
  384. package/dist/jsx-runtime.d.cts +0 -36
  385. package/dist/jsx-runtime.d.ts +0 -36
  386. package/dist/jsx-runtime.js +0 -4
  387. package/dist/jsx-runtime.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration-flag.js","names":["isHydrating","rt","withHydration","previous","fn"],"sources":["../../../src/internal/hydration-flag.ts"],"sourcesContent":["import { rt } from \"./state\";\n\n/**\n * Tells whether the code runs while `hydrate()` claims server markup. Read it at creation in a hook\n * whose first render must match the server, as `useExternalStore` does to read its server snapshot.\n *\n * @returns True inside {@link withHydration}, false otherwise.\n * @example\n * import { isHydrating } from \"@shadow-js/core/extend\";\n *\n * function initialWidth(serverWidth: number): number {\n * return isHydrating() ? serverWidth : window.innerWidth;\n * }\n * @see withHydration\n * @since 1.0.0\n */\nexport function isHydrating(): boolean {\n return rt.hydrating;\n}\n\n/**\n * Runs `fn` with the hydration flag set, so the hooks created inside see {@link isHydrating} return\n * true, and restores the previous flag in `finally`. Renderers wrap their hydration pass in it (the\n * `hydrate()` of `@shadow-js/web` does); application code does not need it.\n *\n * @param fn The hydration pass. A throw is rethrown after the flag is restored.\n * @returns What `fn` returns.\n * @example\n * import { isHydrating, withHydration } from \"@shadow-js/core/extend\";\n *\n * const during = withHydration(() => isHydrating()); // true\n * const after = isHydrating(); // false again\n * @since 1.0.0\n */\nexport function withHydration<T>(fn: () => T): T {\n const previous = rt.hydrating;\n rt.hydrating = true;\n try {\n return fn();\n } finally {\n rt.hydrating = previous;\n }\n}\n"],"mappings":"A,gCAgBA,SAAgBA,GAAuB,CACrC,OAAOC,EAAG,SACZ,CAgBA,SAAgBC,EAAiB,EAAgB,CAC/C,IAAMC,EAAWF,EAAG,UACpB,EAAG,UAAY,GACf,GAAI,CACF,OAAOG,EAAG,CACZ,QAAU,CACR,EAAG,UAAYD,CACjB,CACF,C"}
@@ -0,0 +1,2 @@
1
+ const e={NO_OWNER_EFFECT:`An effect was created outside any owner, so it can never be disposed. Create it inside a component or createRoot().`,NO_OWNER_CLEANUP:`onCleanup() was called outside any owner, so the cleanup will never run.`,NO_OWNER_ERROR:`onError() was called outside any owner, so the handler can never be reached.`,WRITE_IN_MEMO:`A signal was written inside a useMemo() computation. Derive values from sources instead, or write from an effect.`,CYCLE_DETECTED:`A reactive cycle was detected: a computation read itself while it was running.`,INFINITE_LOOP:`Effects kept re-triggering each other for more than 1000 passes; the flush was aborted.`,FLUSH_IN_EFFECT:`flushSync() was called while a flush was already running; the call was ignored.`,RUN_WITH_DISPOSED_OWNER:`runWithOwner() was called with an owner that is already disposed; the callback ran without an owner.`,DUPLICATE_CORE:`More than one copy of @shadow-js/core is loaded. Signals created by one copy are invisible to the other.`,CONTEXT_MISSING:`useContext() found no provider and the context has no default value.`,NO_OWNER_ID:`useId() was called outside any owner; the id is not stable across server and client.`,EACH_KEY_DUPLICATE:`Duplicate key in a keyed list; later duplicates get fresh rows each update.`,EFFECT_DEPS_IGNORED:`useEffect(fn, [deps]) ignores the array and re-runs on any signal it reads; use useEffect(deps, fn).`};function t(e){return`SHADOW_${e}`}export{e as MESSAGES,t as formatMessage};
2
+ //# sourceMappingURL=messages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messages.js","names":["MESSAGES","formatMessage","code"],"sources":["../../../src/internal/messages.ts"],"sourcesContent":["/**\n * The diagnostic catalog: every code the runtime throws (as {@link ShadowError}) or warns with\n * (through {@link warn}), mapped to its development text. Read it to show or match a diagnostic by\n * code. {@link formatMessage} reads it only in development builds, so production bundles keep the\n * code (`SHADOW_<CODE>`) and drop the text (R-CODE-8) unless your own code imports this object.\n *\n * @example\n * import { MESSAGES, type MessageCode } from \"@shadow-js/core/extend\";\n *\n * function explain(code: MessageCode): string {\n * return `${code}: ${MESSAGES[code]}`;\n * }\n * @see formatMessage\n * @since 1.0.0\n */\nexport const MESSAGES = {\n NO_OWNER_EFFECT:\n \"An effect was created outside any owner, so it can never be disposed. Create it inside a component or createRoot().\",\n NO_OWNER_CLEANUP: \"onCleanup() was called outside any owner, so the cleanup will never run.\",\n NO_OWNER_ERROR: \"onError() was called outside any owner, so the handler can never be reached.\",\n WRITE_IN_MEMO:\n \"A signal was written inside a useMemo() computation. Derive values from sources instead, or write from an effect.\",\n CYCLE_DETECTED: \"A reactive cycle was detected: a computation read itself while it was running.\",\n INFINITE_LOOP:\n \"Effects kept re-triggering each other for more than 1000 passes; the flush was aborted.\",\n FLUSH_IN_EFFECT:\n \"flushSync() was called while a flush was already running; the call was ignored.\",\n RUN_WITH_DISPOSED_OWNER:\n \"runWithOwner() was called with an owner that is already disposed; the callback ran without an owner.\",\n DUPLICATE_CORE:\n \"More than one copy of @shadow-js/core is loaded. Signals created by one copy are invisible to the other.\",\n CONTEXT_MISSING: \"useContext() found no provider and the context has no default value.\",\n NO_OWNER_ID:\n \"useId() was called outside any owner; the id is not stable across server and client.\",\n EACH_KEY_DUPLICATE: \"Duplicate key in a keyed list; later duplicates get fresh rows each update.\",\n EFFECT_DEPS_IGNORED:\n \"useEffect(fn, [deps]) ignores the array and re-runs on any signal it reads; use useEffect(deps, fn).\",\n} as const;\n\n/**\n * A diagnostic code: one key of {@link MESSAGES}, such as `\"WRITE_IN_MEMO\"`. {@link ShadowError}\n * carries one in its `code` field, and {@link warn} takes one.\n * @since 1.0.0\n */\nexport type MessageCode = keyof typeof MESSAGES;\n\n/**\n * Turns a diagnostic code into the text the runtime throws or logs: the full sentence in development\n * builds and only a stable code in production builds, so message strings never reach user bundles.\n * Use it when a custom primitive reports a core diagnostic in its own way.\n *\n * @param code The diagnostic code.\n * @returns `[shadow <CODE>] <text>` in development builds, `SHADOW_<CODE>` in production builds.\n * @example\n * import { formatMessage } from \"@shadow-js/core/extend\";\n *\n * const text = formatMessage(\"CONTEXT_MISSING\");\n * // development: \"[shadow CONTEXT_MISSING] useContext() found no provider ...\"\n * // production: \"SHADOW_CONTEXT_MISSING\"\n * @see MESSAGES\n * @since 1.0.0\n */\nexport function formatMessage(code: MessageCode): string {\n return __DEV__ ? `[shadow ${code}] ${MESSAGES[code]}` : `SHADOW_${code}`;\n}\n"],"mappings":"AAeA,MAAaA,EAAW,CACtB,gBACE,sHACF,iBAAkB,2EAClB,eAAgB,+EAChB,cACE,oHACF,eAAgB,iFAChB,cACE,0FACF,gBACE,kFACF,wBACE,uGACF,eACE,2GACF,gBAAiB,uEACjB,YACE,uFACF,mBAAoB,8EACpB,oBACE,sGACJ,EAyBA,SAAgBC,EAAc,EAA2B,CACvD,MAAwD,UAAUC,GACpE,C"}
@@ -0,0 +1,2 @@
1
+ import{rt as e}from"./state.js";var t=class{parent;lastChild=null;prevSibling=null;nextSibling=null;cleanups=null;context;errorHandlers=null;childCount=0;idCount=0;index;depth;idPrefix;disposed=!1;gate=null;pauses=0;constructor(e){if(this.parent=e,this.context=e===null?null:e.context,this.depth=e===null?0:e.depth+1,this.pauses=e===null?0:e.pauses,e===null)this.index=0;else{this.index=e.childCount,e.childCount+=1;let t=e.lastChild;this.prevSibling=t,t!==null&&(t.nextSibling=this),e.lastChild=this}}reportDisposed(){}release(){}disposeSelf(){if(this.disposed)return;this.disposed=!0;let e=this.parent;if(e!==null){let t=this.prevSibling,n=this.nextSibling;t!==null&&(t.nextSibling=n),n===null?e.lastChild=t:n.prevSibling=t,this.prevSibling=null,this.nextSibling=null}this.release(),this.reportDisposed(),this.runCleanups()}runCleanups(){let t=this.cleanups;if(t===null)return;this.cleanups=null;let r=e.owner,i=e.listener;e.owner=null,e.listener=null;try{if(typeof t==`function`)n(t,this);else for(let e=t.length-1;e>=0;--e){let r=t[e];r!==void 0&&n(r,this)}}finally{e.owner=r,e.listener=i}}};function n(e,t){try{e()}catch(e){s(e,t)}}function r(e,t){let n=e.cleanups;n===null?e.cleanups=t:typeof n==`function`?e.cleanups=[n,t]:n.push(t)}function i(e){for(;;){let t=e.lastChild;if(t===null)return;o(t)}}function a(){if(--e.disposing,e.disposing>0||e.flushing||e.uncaught.length===0)return;let t=e.uncaught;throw e.uncaught=[],t.length===1?t[0]:AggregateError(t,`SHADOW_DISPOSE_ERRORS`)}function o(t){e.disposing+=1;try{let e=t;for(;;){for(;e.lastChild!==null;)e=e.lastChild;let n=e.parent;if(e.disposeSelf(),e===t||n===null)break;e=n}}finally{a()}}function s(t,n){let r=t;for(let t=n;t!==null;t=t.parent){let n=t.errorHandlers;if(n!==null)for(let t=n.length-1;t>=0;--t){let i=n[t];if(i===void 0)continue;let a=e.listener;try{e.listener=null,i(r);return}catch(e){r=e}finally{e.listener=a}}}l(r)}function c(e){for(let t=e;t!==null;t=t.parent){let e=t.errorHandlers;if(e!==null&&e.length>0)return!0}return!1}function l(t){if(e.flushing||e.disposing>0)e.uncaught.push(t);else throw t}export{t as Owner,r as addCleanup,i as disposeChildren,o as disposeTree,s as handleError,c as hasErrorHandler};
2
+ //# sourceMappingURL=owner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"owner.js","names":["Owner","parent","last","prev","next","cleanups","previousOwner","rt","previousListener","runCleanup","i","cleanup","error","handleError","owner","addCleanup","existing","disposeChildren","child","disposeTree","finishDisposal","errors","node","root","current","from","handlers","handler","reportUncaught","hasErrorHandler"],"sources":["../../../src/internal/owner.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { rt } from \"./state\";\nimport type { Cleanup, ErrorHandler } from \"./types\";\n\n/**\n * The context values an owner sees, keyed by the symbol of each context. A provider creates a map\n * whose prototype is its parent's map, so a lookup is one property read and never walks owners.\n * @since 1.0.0\n */\nexport type ContextMap = Record<symbol, unknown>;\n\n/**\n * A node in the ownership tree: it owns the effects, memos and owners created under it, their\n * cleanups and error handlers, and disposes them together. Create one with `createOwner` and end it\n * with `disposeOwner`; the class is exported for `instanceof` checks and for reading its state.\n * Computations (`ComputationNode`) are owners too. Children are a doubly linked list so detaching one\n * is O(1); disposal walks the tree iteratively because its depth is user controlled (R-CODE-11).\n *\n * @example\n * import { createOwner, disposeOwner, Owner } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * console.log(owner instanceof Owner, owner.depth); // true 0\n * disposeOwner(owner);\n * console.log(owner.disposed); // true\n * @see createOwner\n * @see disposeOwner\n * @since 1.0.0\n */\nexport class Owner {\n /** The owner this node was created under, or null for a root. Kept after disposal. */\n parent: Owner | null;\n /** The newest child that is still alive, or null when there is none. */\n lastChild: Owner | null = null;\n /** The next older sibling that is still alive, or null. */\n prevSibling: Owner | null = null;\n /** The next newer sibling that is still alive, or null. */\n nextSibling: Owner | null = null;\n /**\n * The cleanups registered with `addCleanup` or `onCleanup`: null for none, a function for one, an\n * array (oldest first) for several. Emptied when they run.\n */\n cleanups: Cleanup | Cleanup[] | null = null;\n /** The context values this node sees: inherited from the parent at creation, null for a root. */\n context: ContextMap | null;\n /**\n * The handlers registered with `onError` or `catchError`, oldest first (they are tried newest\n * first), or null for none. A computation clears them before each run.\n */\n errorHandlers: ErrorHandler[] | null = null;\n /** Number of children ever created; gives each child a stable index for useId(). */\n childCount = 0;\n /** Number of ids useId() has handed out from this owner. */\n idCount = 0;\n /** Position among the parent's children, assigned at creation. */\n index: number;\n /** Distance from the root: 0 for a root, the parent's depth plus one otherwise. */\n depth: number;\n /**\n * The hydration-scope prefix of a component's owner, set by the renderer. When present, useId()\n * builds the ids below it from this prefix instead of the owner path.\n * @default undefined\n */\n idPrefix: string | undefined;\n /** True once the node has been disposed. */\n disposed = false;\n /**\n * While this returns true, user effects (and `onMount`) created below this owner wait: they do\n * not run until it returns false for the first time. Suspense sets it so the effects of content\n * that is still loading are held back. The read is tracked.\n */\n gate: (() => boolean) | null = null;\n /**\n * Number of pauses (Activity hidden) that cover this node. Inherited at creation, and changed for a\n * whole subtree by `pauseOwner`/`resumeOwner`. Above zero, effects wait and memos keep their value.\n */\n pauses = 0;\n\n /**\n * Creates an owner and links it as the newest child of `parent`. It inherits the parent's context\n * and pauses.\n * @param parent The owner to attach to, or null for a root.\n */\n constructor(parent: Owner | null) {\n this.parent = parent;\n this.context = parent === null ? null : parent.context;\n this.depth = parent === null ? 0 : parent.depth + 1;\n this.pauses = parent === null ? 0 : parent.pauses;\n if (parent === null) {\n this.index = 0;\n } else {\n this.index = parent.childCount;\n parent.childCount += 1;\n const last = parent.lastChild;\n this.prevSibling = last;\n if (last !== null) last.nextSibling = this;\n parent.lastChild = this;\n }\n // Computations report themselves (with their kind); plain owners and subclasses of it here.\n if (__DEV__ && new.target === Owner) {\n report(DEVTOOLS_EVENT.OWNER_CREATED, this, parent, parent === null ? \"root\" : \"owner\");\n }\n }\n\n /** Tells devtools this node is gone. Computations override it with their own event. */\n protected reportDisposed(): void {\n if (__DEV__) report(DEVTOOLS_EVENT.OWNER_DISPOSED, this);\n }\n\n /** Hook for subclasses: release graph edges before the node is marked disposed. */\n protected release(): void {\n // Plain owners hold no graph edges.\n }\n\n /**\n * Disposes this node only (children must already be gone).\n * @internal\n */\n disposeSelf(): void {\n if (this.disposed) return;\n this.disposed = true;\n // Detach first: a cleanup that throws must never leave a dead node in the tree (R-CODE-5).\n const parent = this.parent;\n if (parent !== null) {\n const prev = this.prevSibling;\n const next = this.nextSibling;\n if (prev !== null) prev.nextSibling = next;\n if (next !== null) next.prevSibling = prev;\n else parent.lastChild = prev;\n this.prevSibling = null;\n this.nextSibling = null;\n }\n this.release();\n this.reportDisposed();\n this.runCleanups();\n }\n\n /**\n * Runs own cleanups newest first, untracked, isolating failures.\n * @internal\n */\n runCleanups(): void {\n const cleanups = this.cleanups;\n if (cleanups === null) return;\n this.cleanups = null;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = null;\n rt.listener = null;\n try {\n if (typeof cleanups === \"function\") {\n runCleanup(cleanups, this);\n } else {\n for (let i = cleanups.length - 1; i >= 0; i -= 1) {\n const cleanup = cleanups[i];\n if (cleanup !== undefined) runCleanup(cleanup, this);\n }\n }\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n }\n}\n\nfunction runCleanup(cleanup: Cleanup, owner: Owner): void {\n try {\n cleanup();\n } catch (error) {\n handleError(error, owner);\n }\n}\n\n/**\n * Registers `cleanup` on an explicit owner. It runs when the owner is disposed or, when the owner is a\n * computation, before its next run. Cleanups run newest first, untracked and with no current owner;\n * one that throws goes to {@link handleError} for that owner and does not stop the others. Use it\n * where `onCleanup` cannot be called: the owner is not the current one, or the code must not warn.\n * Unlike `onCleanup`, nothing checks that the owner is still alive: a cleanup added to a disposed\n * owner never runs.\n *\n * @param owner The owner whose disposal runs the cleanup.\n * @param cleanup The function to run.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * export function useInterval(tick: () => void, ms: number): void {\n * const owner = currentOwner();\n * const timer = setInterval(tick, ms);\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see disposeOwner\n * @since 1.0.0\n */\nexport function addCleanup(owner: Owner, cleanup: Cleanup): void {\n const existing = owner.cleanups;\n if (existing === null) owner.cleanups = cleanup;\n else if (typeof existing === \"function\") owner.cleanups = [existing, cleanup];\n else existing.push(cleanup);\n}\n\n/**\n * Disposes every child of `owner` (newest first), keeping `owner` itself alive.\n * @internal\n */\nexport function disposeChildren(owner: Owner): void {\n for (;;) {\n const child = owner.lastChild;\n if (child === null) return;\n disposeTree(child);\n }\n}\n\n/** Rethrows what disposal collected once the outermost disposal is finished. */\nfunction finishDisposal(): void {\n rt.disposing -= 1;\n if (rt.disposing > 0 || rt.flushing || rt.uncaught.length === 0) return;\n const errors = rt.uncaught;\n rt.uncaught = [];\n if (errors.length === 1) throw errors[0];\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while disposing.\" : \"SHADOW_DISPOSE_ERRORS\",\n );\n}\n\n/**\n * Disposes `root` and everything below it: children first, then own cleanups, newest first.\n * Iterative post-order walk: a leaf is disposed, which re-links its parent's `lastChild`\n * to the previous sibling, so the loop naturally visits the remaining subtree. The public\n * `disposeOwner` (dispose.ts) wraps it with the flush that follows.\n * @internal\n */\nexport function disposeTree(root: Owner): void {\n rt.disposing += 1;\n try {\n let node: Owner = root;\n for (;;) {\n while (node.lastChild !== null) node = node.lastChild;\n const parent: Owner | null = node.parent;\n node.disposeSelf();\n if (node === root || parent === null) break;\n node = parent;\n }\n } finally {\n finishDisposal();\n }\n}\n\n/**\n * Routes `error` to the nearest handler registered with `catchError` or `onError`, searching `from`\n * and then its ancestors, newest handler first on each owner. Handlers run untracked and restore\n * the caller's tracking even when they rethrow. Use it for errors that happen outside\n * any computation (a rejected promise, an event callback), so they reach the same boundary as errors\n * thrown during rendering. A handler that throws hands its own error to the next handler up the\n * chain. With no handler left the error is uncaught: collected until the running flush or disposal\n * ends (which then throws it), or thrown at once otherwise.\n *\n * @param error The thrown value.\n * @param from The owner where the error happened. Null searches no handler: the error is uncaught.\n * @throws The error (or the last error a handler threw) when no handler catches it and no flush or\n * disposal is running.\n * @example\n * import { currentOwner, handleError } from \"@shadow-js/core/extend\";\n *\n * export function useSaveOnLoad(save: () => Promise<void>): void {\n * const owner = currentOwner();\n * save().catch((error: unknown) => handleError(error, owner));\n * }\n * @since 1.0.0\n */\nexport function handleError(error: unknown, from: Owner | null): void {\n if (__DEV__) report(DEVTOOLS_EVENT.ERROR, from, error, codeOf(error));\n let current = error;\n for (let owner = from; owner !== null; owner = owner.parent) {\n const handlers = owner.errorHandlers;\n if (handlers === null) continue;\n for (let i = handlers.length - 1; i >= 0; i -= 1) {\n const handler = handlers[i];\n if (handler === undefined) continue;\n const previousListener = rt.listener;\n try {\n rt.listener = null;\n return void handler(current);\n } catch (next) {\n current = next;\n } finally {\n rt.listener = previousListener;\n }\n }\n }\n reportUncaught(current);\n}\n\n/**\n * True when `handleError(_, from)` would reach a handler registered by catchError()/onError().\n * @internal\n */\nexport function hasErrorHandler(from: Owner | null): boolean {\n for (let owner = from; owner !== null; owner = owner.parent) {\n const handlers = owner.errorHandlers;\n if (handlers !== null && handlers.length > 0) return true;\n }\n return false;\n}\n\n/**\n * The diagnostic code of a ShadowJS error, for devtools. Reads an own data property only: a getter on a thrown\n * value would run user code inside the error path, and a throw there would replace the error being handled.\n */\nfunction codeOf(error: unknown): unknown {\n if (typeof error !== \"object\" || error === null) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(error, \"code\");\n return descriptor !== undefined && \"value\" in descriptor ? descriptor.value : undefined;\n}\n\nfunction reportUncaught(error: unknown): void {\n if (rt.flushing || rt.disposing > 0) rt.uncaught.push(error);\n else throw error;\n}\n"],"mappings":"A,gCA6BA,IAAaA,EAAb,KAAmB,CAEjB,OAEA,UAA0B,KAE1B,YAA4B,KAE5B,YAA4B,KAK5B,SAAuC,KAEvC,QAKA,cAAuC,KAEvC,WAAa,EAEb,QAAU,EAEV,MAEA,MAMA,SAEA,SAAW,GAMX,KAA+B,KAK/B,OAAS,EAOT,YAAY,EAAsB,CAKhC,GAJA,KAAK,OAASC,EACd,KAAK,QAAUA,IAAW,KAAO,KAAOA,EAAO,QAC/C,KAAK,MAAQA,IAAW,KAAO,EAAIA,EAAO,MAAQ,EAClD,KAAK,OAASA,IAAW,KAAO,EAAIA,EAAO,OACvCA,IAAW,KACb,KAAK,MAAQ,MACR,CACL,KAAK,MAAQA,EAAO,WACpB,EAAO,YAAc,EACrB,IAAMC,EAAOD,EAAO,UACpB,KAAK,YAAcC,EACfA,IAAS,OAAM,EAAK,YAAc,MACtC,EAAO,UAAY,IACrB,CAKF,CAGA,gBAAiC,CAEjC,CAGA,SAA0B,CAE1B,CAMA,aAAoB,CAClB,GAAI,KAAK,SAAU,OACnB,KAAK,SAAW,GAEhB,IAAMD,EAAS,KAAK,OACpB,GAAIA,IAAW,KAAM,CACnB,IAAME,EAAO,KAAK,YACZC,EAAO,KAAK,YACdD,IAAS,OAAM,EAAK,YAAcC,GAClCA,IAAS,KACR,EAAO,UAAYD,E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C,EAAG,WAAa,EAChB,GAAI,CACF,IAAIG,EAAcC,EAClB,OAAS,CACP,KAAOD,EAAK,YAAc,MAAM,EAAOA,EAAK,UAC5C,IAAMrB,EAAuBqB,EAAK,OAElC,GADAA,EAAK,YAAY,EACbA,IAASC,GAAQtB,IAAW,KAAM,MACtC,EAAOA,CACT,CACF,QAAU,CACRmB,EAAe,CACjB,CACF,CAwBA,SAAgBP,EAAY,EAAgB,EAA0B,CAEpE,IAAIW,EAAUZ,EACd,IAAK,IAAIE,EAAQW,EAAMX,IAAU,KAAM,EAAQA,EAAM,OAAQ,CAC3D,IAAMY,EAAWZ,EAAM,cACvB,GAAIY,IAAa,KACjB,IAAK,IAAIhB,EAAIgB,EAAS,OAAS,EAAGhB,GAAK,EAAG,IAAQ,CAChD,IAAMiB,EAAUD,EAAShB,GACzB,GAAIiB,IAAY,IAAA,GAAW,SAC3B,IAAMnB,EAAmBD,EAAG,SAC5B,GAAI,CACF,EAAG,SAAW,KACPoB,EAAaH,CAAO,EAA3B,MACF,OAASpB,EAAM,CACb,EAAUA,CACZ,QAAU,CACR,EAAG,SAAWI,CAChB,CACF,CACF,CACAoB,EAAeJ,CAAO,CACxB,CAMA,SAAgBK,EAAgB,EAA6B,CAC3D,IAAK,IAAIf,EAAQW,EAAMX,IAAU,KAAM,EAAQA,EAAM,OAAQ,CAC3D,IAAMY,EAAWZ,EAAM,cACvB,GAAIY,IAAa,MAAQA,EAAS,OAAS,EAAG,MAAO,EACvD,CACA,MAAO,EACT,CAYA,SAASE,EAAe,EAAsB,CAC5C,GAAIrB,EAAG,UAAYA,EAAG,UAAY,EAAGA,EAAG,SAAS,KAAKK,CAAK,OACtD,MAAMA,CACb,C"}
@@ -0,0 +1,2 @@
1
+ import{FLAG_PARKED as e,FLAG_TRANSITION as t}from"./flags.js";import{rt as n}from"./state.js";const r=[],i=[];function a(a,o){if(a.flags&2)return;let s=o||!!(a.flags&512),c=n.hooks;c!==null&&(s||a.pauses>0)?c.place(a,s):(a.flags=a.flags&~(e|t)|2,a.flags&16?r.push(a):i.push(a))}function o(e){a(e,n.inTransition)}function s(){return r.length>0||i.length>0}function c(){for(let e of[r,i]){for(let n of e)n.flags&=~(2|t),n.state=0;e.length=0}n.hooks?.clear()}export{c as clearQueues,o as enqueue,s as hasPending,a as place,r as renderQueue,i as userQueue};
2
+ //# sourceMappingURL=queue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue.js","names":["renderQueue","userQueue","place","effect","inLane","lane","hooks","rt","FLAG_PARKED","FLAG_TRANSITION","enqueue","hasPending","clearQueues","queue"],"sources":["../../../src/internal/queue.ts"],"sourcesContent":["import { CLEAN, FLAG_LANE, FLAG_PARKED, FLAG_QUEUED, FLAG_RENDER, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { rt } from \"./state\";\n\n/** Urgent effects waiting for the next flush, split by phase (render effects run first). */\nexport const renderQueue: Computation[] = [];\nexport const userQueue: Computation[] = [];\n\n/**\n * Puts an effect where it belongs. `lane` says the write that marked it was a transition write;\n * effects with FLAG_LANE always go to the lane. Lane and paused effects are handed to the transition\n * hooks (their queues live there); everything else is queued here, with no hook involved.\n */\nexport function place(effect: Computation, lane: boolean): void {\n if ((effect.flags & FLAG_QUEUED) !== 0) return;\n const inLane = lane || (effect.flags & FLAG_LANE) !== 0;\n const hooks = rt.hooks;\n if (hooks !== null && (inLane || effect.pauses > 0)) {\n hooks.place(effect, inLane);\n return;\n }\n effect.flags = (effect.flags & ~(FLAG_PARKED | FLAG_TRANSITION)) | FLAG_QUEUED;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n}\n\n/** Queues an effect for the current write: a transition write joins the lane. */\nexport function enqueue(effect: Computation): void {\n place(effect, rt.inTransition);\n}\n\n/** True when an urgent effect is waiting. */\nexport function hasPending(): boolean {\n return renderQueue.length > 0 || userQueue.length > 0;\n}\n\n/** Drops everything queued (used when a flush is aborted by the loop guard). */\nexport function clearQueues(): void {\n for (const queue of [renderQueue, userQueue]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n // Back to CLEAN so the next write can notify (and re-queue) this effect again.\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n rt.hooks?.clear();\n}\n"],"mappings":"A,8FAKA,MAAaA,EAA6B,CAAC,EAC9BC,EAA2B,CAAC,EAOzC,SAAgBC,EAAM,EAAqB,EAAqB,CAC9D,GAAKC,EAAO,MAAA,EAA4B,OACxC,IAAMC,EAASC,GAAA,GAASF,EAAO,MAAA,KACzBG,EAAQC,EAAG,MACbD,IAAU,OAASF,GAAUD,EAAO,OAAS,GAC/CG,EAAM,MAAMH,EAAQC,CAAM,GAG5B,EAAO,MAASD,EAAO,MAAQ,EAAEK,EAAcC,GAAA,EAC1CN,EAAO,MAAA,GAA4BH,EAAY,KAAKG,CAAM,EAC1DF,EAAU,KAAKE,CAAM,EAC5B,CAGA,SAAgBO,EAAQ,EAA2B,CACjDR,EAAMC,EAAQI,EAAG,YAAY,CAC/B,CAGA,SAAgBI,GAAsB,CACpC,OAAOX,EAAY,OAAS,GAAKC,EAAU,OAAS,CACtD,CAGA,SAAgBW,GAAoB,CAClC,IAAK,IAAMC,IAAS,CAACb,EAAaC,CAAS,EAAG,CAC5C,IAAK,IAAME,KAAUU,EACnB,EAAO,OAAS,EAAA,EAAgBJ,GAEhC,EAAO,MAAA,EAET,EAAM,OAAS,CACjB,CACAF,EAAG,OAAO,MAAM,CAClB,C"}
@@ -0,0 +1,2 @@
1
+ import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_TRANSITION as n}from"./flags.js";import{rt as r}from"./state.js";import{handleError as i}from"./owner.js";import{clearQueues as a,hasPending as o,renderQueue as s,userQueue as c}from"./queue.js";import{recompute as l,updateIfNecessary as u}from"./graph.js";const d=1e3;let f=!1;function p(e,t){return e.depth-t.depth||e.seq-t.seq}function m(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n!==void 0&&r!==void 0&&p(n,r)>0)return!1}return!0}function h(e){let r=e.splice(0,e.length);m(r)||r.sort(p);for(let e of r)if(e.flags&=-3,!(e.flags&4)){if(e.pauses>0)e.flags=e.flags&~n|t;else try{e.state===2?l(e):u(e)}catch(t){i(t,e)}}return r.length}function g(e){let[t]=e;throw e.length===1?t:AggregateError(e,`SHADOW_FLUSH_ERRORS`)}function _(){if(r.flushing)return;r.flushing=!0;let t=0,n=0;try{for(;o();){let i=!1;for(;s.length>0;){if(t+=1,t>1e3){i=!0;break}n+=h(s)}if(!i&&c.length>0&&(t+=1,t>1e3?i=!0:n+=h(c)),i){a(),r.uncaught.push(new e(`INFINITE_LOOP`));break}}}finally{r.flushing=!1}let i=r.uncaught;i.length>0&&(r.uncaught=[],g(i))}function v(e){typeof reportError==`function`?reportError(e):queueMicrotask(()=>Promise.reject(e))}function y(){if(f=!1,o())try{_()}catch(e){v(e)}}function b(){r.inTransition||r.batchDepth>0||r.flushing||f||(f=!0,queueMicrotask(y))}function x(e){r.batchDepth+=1;try{return e()}finally{--r.batchDepth,r.batchDepth===0&&o()&&b()}}function S(e,t){return AggregateError([e,t],`SHADOW_BATCH_ERRORS`)}function C(e){r.batchDepth+=1;let t,n,i=!1;try{t=e()}catch(e){i=!0,n=e}finally{--r.batchDepth}if(r.batchDepth===0&&!r.flushing&&o())try{_()}catch(e){throw i?S(n,e):e}if(i)throw n;return t}function w(e){if(r.flushing)return e===void 0?void 0:e();r.batchDepth+=1;let t,n,i=!1;try{t=e===void 0?void 0:e()}catch(e){i=!0,n=e}finally{--r.batchDepth}try{_()}catch(e){throw i?S(n,e):e}if(i)throw n;return t}export{d as MAX_FLUSH_PASSES,C as batch,p as byCreation,_ as flush,w as flushSync,x as group,m as isOrdered,v as reportUncaught,b as schedule};
2
+ //# sourceMappingURL=scheduler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scheduler.js","names":["MAX_FLUSH_PASSES","microtaskScheduled","byCreation","a","b","isOrdered","i","list","previous","current","drain","batch","queue","effect","FLAG_TRANSITION","FLAG_PARKED","recompute","updateIfNecessary","error","handleError","raise","first","errors","flush","rt","passes","runs","hasPending","aborted","renderQueue","userQueue","clearQueues","ShadowError","reportUncaught","runScheduled","schedule","group","fn","combine","primary","secondary","result","failure","failed","flushSync"],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/**\n * Effects mostly arrive in creation order already; checking is O(n), sorting is not.\n * @internal\n */\nexport function isOrdered(list: readonly Computation[]): boolean {\n for (let i = 1; i < list.length; i += 1) {\n const previous = list[i - 1];\n const current = list[i];\n if (previous !== undefined && current !== undefined && byCreation(previous, current) > 0) {\n return false;\n }\n }\n return true;\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n if (!isOrdered(batch)) batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n try {\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n let aborted = false;\n // Render passes count too: a render effect that keeps writing its own source must abort.\n while (renderQueue.length > 0) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n aborted = true;\n break;\n }\n runs += drain(renderQueue);\n }\n if (!aborted && userQueue.length > 0) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) aborted = true;\n else runs += drain(userQueue);\n }\n if (aborted) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batchDepth > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batchDepth += 1;\n try {\n return fn();\n } finally {\n rt.batchDepth -= 1;\n if (rt.batchDepth === 0 && hasPending()) schedule();\n }\n}\n\nfunction combine(primary: unknown, secondary: unknown): unknown {\n return new AggregateError(\n [primary, secondary],\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n if (rt.batchDepth === 0 && !rt.flushing && hasPending()) {\n try {\n flush();\n } catch (error) {\n if (failed) throw combine(failure, error);\n throw error;\n }\n }\n if (failed) throw failure;\n return result as T;\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n try {\n flush();\n } catch (error) {\n if (failed) throw combine(failure, error);\n throw error;\n }\n if (failed) throw failure;\n return result as T;\n}\n"],"mappings":"A,6UAaA,MAAaA,EAAmB,IAEhC,IAAIC,EAAqB,GAMzB,SAAgBC,EAAW,EAAgB,EAAwB,CACjE,OAAOC,EAAE,MAAQC,EAAE,OAASD,EAAE,IAAMC,EAAE,GACxC,CAMA,SAAgBC,EAAU,EAAuC,CAC/D,IAAK,IAAIC,EAAI,EAAGA,EAAIC,EAAK,OAAQ,GAAK,EAAG,CACvC,IAAMC,EAAWD,EAAKD,EAAI,GACpBG,EAAUF,EAAKD,GACrB,GAAIE,IAAa,IAAA,IAAaC,IAAY,IAAA,IAAaP,EAAWM,EAAUC,CAAO,EAAI,EACrF,MAAO,EAEX,CACA,MAAO,EACT,CAGA,SAASC,EAAM,EAA8B,CAC3C,IAAMC,EAAQC,EAAM,OAAO,EAAGA,EAAM,MAAM,EACrCP,EAAUM,CAAK,GAAGA,EAAM,KAAKT,CAAU,EAC5C,IAAK,IAAMW,KAAUF,EAEnB,GADA,EAAO,OAAS,GACX,IAAO,MA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WAAa,GAAKA,EAAG,UAAYvB,IAC3D,EAAqB,GACrB,eAAeiC,CAAY,EAC7B,CAuBA,SAAgBE,EAAS,EAAgB,CACvC,EAAG,YAAc,EACjB,GAAI,CACF,OAAOC,EAAG,CACZ,QAAU,CACR,IAAG,WACCb,EAAG,aAAe,GAAKG,EAAW,GAAGQ,EAAS,CACpD,CACF,CAEA,SAASG,EAAQ,EAAkB,EAA6B,CAC9D,OAAW,eACT,CAACC,EAASC,CAAS,EACkC,qBACvD,CACF,CAwBA,SAAgB7B,EAAS,EAAgB,CACvC,EAAG,YAAc,EACjB,IAAI8B,EACAC,EACAC,EAAS,GACb,GAAI,CACF,EAASN,EAAG,CACd,OAASnB,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,QAAU,CACR,IAAG,UACL,CACA,GAAIM,EAAG,aAAe,GAAK,CAACA,EAAG,UAAYG,EAAW,EACpD,GAAI,CACFJ,EAAM,CACR,OAASL,EAAO,CAEd,MADIyB,EAAcL,EAAQI,EAASxB,CAAK,EAClCA,CACR,CAEF,GAAIyB,EAAQ,MAAMD,EAClB,OAAOD,CACT,CAyBA,SAAgBG,EAAoB,EAAiB,CACnD,GAAIpB,EAAG,SAEL,OAAQa,IAAO,IAAA,GAAY,IAAA,GAAYA,EAAG,EAE5C,EAAG,YAAc,EACjB,IAAII,EACAC,EACAC,EAAS,GACb,GAAI,CACF,EAASN,IAAO,IAAA,GAAY,IAAA,GAAYA,EAAG,CAC7C,OAASnB,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,QAAU,CACR,IAAG,UACL,CACA,GAAI,CACFK,EAAM,CACR,OAASL,EAAO,CAEd,MADIyB,EAAcL,EAAQI,EAASxB,CAAK,EAClCA,CACR,CACA,GAAIyB,EAAQ,MAAMD,EAClB,OAAOD,CACT,C"}
@@ -0,0 +1,2 @@
1
+ const e={owner:null,listener:null,running:null,batchDepth:0,flushing:!1,recomputeDepth:0,disposing:0,uncaught:[],inTransition:!1,hydrating:!1,hooks:null};let t=0;function n(){return t+=1,t}export{n as nextSequence,e as rt};
2
+ //# sourceMappingURL=state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.js","names":["rt","counter","nextSequence"],"sources":["../../../src/internal/state.ts"],"sourcesContent":["import type { Computation } from \"./graph\";\nimport type { Owner } from \"./owner\";\n\n/**\n * A hold for a value a transition builds while its reads wait for data (a `Show` branch built during a\n * transition): the reads that wait count against this hold, not against the Suspense boundary around\n * the value, so the shown value stays until the hold settles. Created by `createTransitionHold`.\n * @since 1.0.0\n */\nexport interface TransitionHold {\n /** Runs `fn` with this hold as the Suspense boundary of the reads inside it. */\n run<T>(fn: () => T): T;\n /** Reads still waiting for data. */\n count(): number;\n /** True once a read in the hold was held (the value is then pending, not ready). */\n engaged(): boolean;\n /** Ends the hold without waking anything (the value is being dropped). */\n drop(): void;\n}\n\n/**\n * The choice a branch slot (Show, Switch) shows: its index, and what decides a rebuild. Renderers\n * extend it with what they need to build the branch.\n * @since 1.0.0\n */\nexport interface SlotChoice {\n /** Which branch is chosen: its position among the slot's branches, or the renderer's fallback index. */\n readonly index: number;\n /** True when the branch is rebuilt whenever `when` changes identity; false when only `index` counts. */\n readonly keyed: boolean;\n /** The condition value that selected the branch. */\n readonly when: unknown;\n}\n\n/**\n * The record of a branch's owner that its accessors read: the value and whether it is being torn down.\n * @since 1.0.0\n */\nexport interface SlotOwned {\n /** The index of the branch this record belongs to (see {@link SlotChoice.index}). */\n index: number;\n /** The latest condition value while the branch is shown; what its accessor returns during teardown. */\n value: unknown;\n /** True while the branch is torn down: its accessor then returns `value` instead of throwing. */\n disposing: boolean;\n}\n\n/**\n * A branch a slot shows, or builds during a transition. A branch without `dispose` is torn down by its memo.\n * @since 1.0.0\n */\nexport interface SlotBranch<C extends SlotChoice> {\n /** The choice the branch was built for. */\n readonly choice: C;\n /** The record its accessors read. */\n readonly owned: SlotOwned;\n /** What the branch produced: the value the slot's output returns while the branch is shown. */\n readonly result: unknown;\n /**\n * Tears the branch down. Set for the branches a transition built: they live under the holder, not\n * under the memo.\n * @default undefined (the slot's memo tears the branch down)\n */\n readonly dispose?: () => void;\n /**\n * The hold a transition built the branch under; null when none of its reads was held.\n * @default undefined (a memo-owned branch has no hold)\n */\n readonly hold?: TransitionHold | null;\n}\n\n/**\n * What a slot's output memo keeps: the branch on screen (its result is the value the output returns).\n * @since 1.0.0\n */\nexport interface SlotState<C extends SlotChoice> {\n /** The branch on screen, or undefined before the first build and while the memo rebuilds it. */\n live: SlotBranch<C> | undefined;\n}\n\n/**\n * The transition layer of one slot, from `transitionHooks()?.slotSwap(...)`: it keeps the shown\n * branch while a transition builds the next one (see `slotSwap` in concurrency.ts).\n * @since 1.0.0\n */\nexport interface SlotSwap<C extends SlotChoice> {\n /**\n * Runs one pass of the slot's memo for `choice`. True when a transition keeps the shown value. False\n * when the usual path follows: the branch on screen has been retired and `state.live` is cleared.\n */\n step(choice: C): boolean;\n}\n\n/**\n * The hold of one Suspense boundary: engaged by a transition read, released when its data arrived.\n * From `transitionHooks()?.boundaryHold()`.\n * @since 1.0.0\n */\nexport interface BoundaryHold {\n /** Engages the hold (a second call changes nothing) so the boundary keeps its content; returns true. */\n engage(): boolean;\n /** When engaged: wakes the readers that waited, then ends the hold. Otherwise does nothing. */\n release(): void;\n /** True while the hold is engaged. */\n holding(): boolean;\n}\n\n/**\n * The transition machinery the engine calls through `rt.hooks`: transition lanes, pauses (Activity)\n * and suspensions (Suspense holds). It is created by the first call of an API that needs it (see\n * concurrency.ts), so an application that never calls one of those APIs carries none of their code.\n * Renderers reach it through `transitionHooks()`.\n * @since 1.0.0\n */\nexport interface Hooks {\n /** The transition layer of one branch slot (see `slotSwap` in concurrency.ts). */\n slotSwap<C extends SlotChoice>(\n state: SlotState<C>,\n build: (choice: C, owned: SlotOwned, eager: boolean) => unknown,\n same: (a: C, b: C) => boolean,\n parent: Owner | null,\n ): SlotSwap<C>;\n /** A Suspense boundary's hold (see `boundaryHold` in concurrency.ts). */\n boundaryHold(): BoundaryHold;\n /** Queues an effect that is due in the transition lane, or parks it while its owner is paused. */\n place(effect: Computation, inLane: boolean): void;\n /** An urgent write reached an effect that waits in the lane or is parked: it moves to the urgent queue. */\n promote(effect: Computation): void;\n /** Forgets the lane queues (the flush loop guard). */\n clear(): void;\n /** Keeps `node` for a transition when `error` is a suspension; returns false for any other error. */\n suspend(node: Computation, error: unknown): boolean;\n /** The engine side of `holdReader`: throws the suspension sentinel when `tracker.hold()` is true. */\n holdReader(tracker: { hold?(): boolean }): void;\n /** The engine side of `startTransition` in the browser. */\n startTransition(fn: () => void): Promise<void>;\n /** The engine side of `beginHold`: counts one more Suspense hold. */\n beginHold(): void;\n /** The engine side of `endHold`: counts one hold less and settles the lane. */\n endHold(): void;\n /** The engine side of `wakeSuspended`. */\n wakeSuspended(): void;\n /** The engine side of `pauseOwner`. */\n pause(owner: Owner): void;\n /** The engine side of `resumeOwner`. */\n resume(owner: Owner): void;\n /** The engine side of `createTransitionHold`. */\n createHold(onSettled: () => void): TransitionHold;\n}\n\n/**\n * The runtime registers (R-CODE-4): the only module-level mutable state of core besides\n * monotonic counters. Every write is paired with a `finally` restore (R-CODE-5).\n */\nexport const rt: {\n /** Owner that adopts newly created nodes. */\n owner: Owner | null;\n /** Computation that records the signals it reads; null while untracked. */\n listener: Computation | null;\n /** Computation currently executing, tracked or not (used by the write-in-memo guard). */\n running: Computation | null;\n /** Nesting depth of batch()/flushSync() calls. */\n batchDepth: number;\n /** True while the flush loop is draining the effect queues. */\n flushing: boolean;\n /** Nesting depth of memo recomputation, used to switch to iterative pulls. */\n recomputeDepth: number;\n /** Nesting depth of disposals in progress; errors raised meanwhile are collected, not thrown. */\n disposing: number;\n /** Errors nobody handled during the current flush or disposal; rethrown once it completes. */\n uncaught: unknown[];\n /** True while a transition callback or a transition-lane run is active: writes made now join the lane. */\n inTransition: boolean;\n /** True while `hydrate()` claims server markup (useExternalStore reads its server snapshot). */\n hydrating: boolean;\n /** The transition machinery, or null until an API that needs it is first called. */\n hooks: Hooks | null;\n} = {\n owner: null,\n listener: null,\n running: null,\n batchDepth: 0,\n flushing: false,\n recomputeDepth: 0,\n disposing: 0,\n uncaught: [],\n inTransition: false,\n hydrating: false,\n hooks: null,\n};\n\nlet counter = 0;\n/** Monotonic creation sequence; orders sibling effects (G-16). */\nexport function nextSequence(): number {\n counter += 1;\n return counter;\n}\n"],"mappings":"AA0JA,MAAaA,EAuBT,CACF,MAAO,KACP,SAAU,KACV,QAAS,KACT,WAAY,EACZ,SAAU,GACV,eAAgB,EAChB,UAAW,EACX,SAAU,CAAC,EACX,aAAc,GACd,UAAW,GACX,MAAO,IACT,EAEA,IAAIC,EAAU,EAEd,SAAgBC,GAAuB,CAErC,MADA,IAAW,EACJD,CACT,C"}
@@ -0,0 +1,2 @@
1
+ const e=/* @__PURE__ */ Object.freeze({suspended:!0});function t(t){return t===e}export{e as SUSPENSION,t as isSuspension};
2
+ //# sourceMappingURL=suspension.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"suspension.js","names":["SUSPENSION","isSuspension","value"],"sources":["../../../src/internal/suspension.ts"],"sourcesContent":["/**\n * The value a reader throws when a transition reads data that is still loading inside a Suspense\n * boundary that is showing content. The reader keeps its previous value (a memo keeps its value, an\n * effect leaves the DOM as it is) until the boundary releases it. A single frozen object: identity is\n * the test, so user code cannot forge it. {@link holdReader} throws it for you; a custom primitive\n * that catches errors must let it through, which {@link isSuspension} checks.\n *\n * @example\n * import { SUSPENSION } from \"@shadow-js/core/extend\";\n *\n * function rethrowIfHeld(error: unknown): void {\n * if (error === SUSPENSION) throw error; // not a failure: the boundary resumes the reader later\n * }\n * @see isSuspension\n * @since 1.0.0\n */\nexport const SUSPENSION: { readonly suspended: true } = /* @__PURE__ */ Object.freeze({\n suspended: true as const,\n});\n\n/**\n * Tells whether a caught value is the suspension sentinel rather than an error. Use it in a custom\n * primitive's `catch` so a transition's held read is passed on instead of being reported as a\n * failure.\n *\n * @param value The caught value.\n * @returns True when `value` is {@link SUSPENSION}.\n * @example\n * import { isSuspension } from \"@shadow-js/core/extend\";\n *\n * function attempt(run: () => void, onError: (error: unknown) => void): void {\n * try {\n * run();\n * } catch (error) {\n * if (isSuspension(error)) throw error;\n * onError(error);\n * }\n * }\n * @since 1.0.0\n */\nexport function isSuspension(value: unknown): boolean {\n return value === SUSPENSION;\n}\n"],"mappings":"AAgBA,MAAaA,EAA2D,uBAAO,OAAO,CACpF,UAAW,EACb,CAAC,EAsBD,SAAgBC,EAAa,EAAyB,CACpD,OAAOC,IAAUF,CACnB,C"}
@@ -0,0 +1,2 @@
1
+ import"./internal/diagnostics.js";import{Owner as e}from"./internal/owner.js";import{readSignal as t}from"./internal/graph.js";import{createRoot as n,getOwner as r,onCleanup as i,runWithOwner as a,untrack as o}from"./ownership.js";import{disposeTree as s}from"./internal/dispose.js";import{createSignalNode as c,writeSignal as l}from"./extend/index.js";import{useMemo as u}from"./memo.js";var d=class{key;first;item;index;value=void 0;dispose=f;itemNode=null;indexNode=null;constructor(e,t,n,r){this.key=e,this.first=t,this.item=n,this.index=r}readItem(){return this.itemNode??=c(this.item,Object.is),t(this.itemNode)}readIndex(){return this.indexNode??=c(this.index,Object.is),t(this.indexNode)}setItem(e){this.item=e,this.itemNode!==null&&l(this.itemNode,e,{allowInMemo:!0})}setIndex(e){this.index=e,this.indexNode!==null&&l(this.indexNode,e,{allowInMemo:!0})}};function f(){}function p(e,t,n){let r=n?.key;return h(e,r===void 0?{keyOf:e=>e,distinct:!1}:{keyOf:e=>r(e),distinct:!0},(e,n,i)=>t(r===void 0?e:n,i),n?.fallback)}function m(e,t,n){return h(e,{keyOf:(e,t)=>t,distinct:!1},(e,n,r)=>t(n,o(r)),n?.fallback)}function h(t,n,a,c){let l=new e(r());i(()=>{s(l)});let d=[],f;return u(()=>{let e=g(t()),r=Array.isArray(e)?Array.prototype.slice.call(e):e,i=o(()=>_(r,n)),s=b(d,i),u=[],p=[],m;try{i.forEach((e,t)=>{let n=s[t]??-1,r=n===-1?void 0:d[n];if(r!==void 0){p.push({row:r,item:e.item,position:t,fresh:!1});return}let i=x(l,e.key,e.first,e.item,t,a);u.push(i),p.push({row:i,item:e.item,position:t,fresh:!0})}),i.length===0&&c!==void 0&&(m=f??S(l,c))}catch(e){let t=[];for(let e of u)C(e.dispose,t);throw m!==void 0&&m!==f&&C(m.dispose,t),w(e,t)}let h=[],v=d,y=f;d=p.map(e=>e.row),f=m;let E=new Uint8Array(v.length);for(let e of s)e!==-1&&(E[e]=1);v.forEach((e,t)=>{E[t]!==1&&C(e.dispose,h)}),y!==void 0&&y!==m&&C(y.dispose,h);for(let e of p){if(e.fresh)continue;let t=e.row;t.index!==e.position&&t.setIndex(e.position),Object.is(t.item,e.item)||t.setItem(e.item)}return T(h),m===void 0?d.map(e=>e.value):[m.value]},{lazy:!0,allowWrites:!0})}function g(e){return e==null||e===!1?[]:e}function _(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let[i,a]of e.entries()){let e=t.keyOf(a,i),o=!0;t.distinct&&(r.has(e)?o=!1:r.add(e)),n.push({item:a,key:e,first:o})}return n}function v(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function y(e,t){return e!==void 0&&t!==void 0&&e.first&&t.first&&v(e.key,t.key)}function b(e,t){let n=e.length,r=t.length,i=new Int32Array(r).fill(-1),a=0;for(;a<n&&a<r&&y(e[a],t[a]);)i[a]=a,a+=1;let o=n-1,s=r-1;for(;o>=a&&s>=a&&y(e[o],t[s]);)i[s]=o,--o,--s;if(a>o||a>s)return i;let c=/* @__PURE__ */ new Map,l=new Int32Array(n).fill(-1);for(let t=o;t>=a;--t){let n=e[t];n!==void 0&&n.first&&(l[t]=c.get(n.key)??-1,c.set(n.key,t))}for(let e=a;e<=s;e+=1){let n=t[e];if(n===void 0||!n.first)continue;let r=c.get(n.key);r!==void 0&&r!==-1&&(i[e]=r,c.set(n.key,l[r]??-1))}return i}function x(e,t,r,i,s,c){let l=new d(t,r,i,s),u=()=>l.readItem(),f=()=>l.readIndex();return a(e,()=>n(e=>{l.dispose=e,l.value=o(()=>c(i,u,f))})),l}function S(e,t){return a(e,()=>n(e=>({value:o(t),dispose:e})))}function C(e,t){try{e()}catch(e){t.push(e)}}function w(e,t){return t.length===0?e:AggregateError([e,...t],`SHADOW_MAP_ERRORS`)}function T(e){if(e.length!==0)throw e.length===1?e[0]:AggregateError(e,`SHADOW_LIST_DISPOSE_ERRORS`)}export{m as indexArray,p as mapArray};
2
+ //# sourceMappingURL=list.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"list.js","names":["Row","noop","key","first","item","index","createSignalNode","readSignal","next","writeSignal","mapArray","keyOf","options","listRows","list","map","readItem","readIndex","indexArray","position","untrack","holder","Owner","getOwner","onCleanup","disposeTree","rows","emptyFallback","useMemo","source","listItems","items","entries","toEntries","keying","reuse","matchRows","created","staged","nextFallback","from","kept","entry","row","openRow","build","fallback","openFallback","error","failures","disposeCollecting","combineFailures","previousRows","previousFallback","stage","throwFailures","value","seen","sameKey","a","b","canReuse","m","old","n","start","oldEnd","newEnd","heads","chain","i","j","head","runWithOwner","createRoot","dispose","primary"],"sources":["../../src/list.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n disposeOwner,\n Owner,\n readSignal,\n type SignalNode,\n warn,\n writeSignal,\n} from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { createRoot, getOwner, onCleanup, runWithOwner, untrack } from \"./ownership\";\n\n/**\n * A list as the list primitives read it. `null`, `undefined` and `false` count as an empty list.\n * @since 1.0.0\n */\nexport type ListSource<T> = () => readonly T[] | null | undefined | false;\n\n/**\n * One mapped row: its own root, its mapped value, and the signals behind `item()` and `index()`. The signals are created\n * by the first read, so a row whose callback never reads its index (or, unkeyed, its item) allocates neither.\n */\nclass Row<T, U> {\n /** Reuse key: the item itself (unkeyed), `key(item)` (keyed) or the position (indexed). */\n readonly key: unknown;\n /** False for a later copy of a key in a keyed list. Such a row is never reused. */\n readonly first: boolean;\n /** Item last written to the row. Kept as a plain field so an unchanged item skips the signal. */\n item: T;\n /** Index last written to the row. */\n index: number;\n value: U = undefined as U;\n dispose: () => void = noop;\n /** Created by the first `item()` read; null until then. */\n private itemNode: SignalNode<T> | null = null;\n /** Created by the first `index()` read; null until then. */\n private indexNode: SignalNode<number> | null = null;\n\n constructor(key: unknown, first: boolean, item: T, index: number) {\n this.key = key;\n this.first = first;\n this.item = item;\n this.index = index;\n }\n\n readItem(): T {\n this.itemNode ??= createSignalNode(this.item, Object.is);\n return readSignal(this.itemNode);\n }\n\n readIndex(): number {\n this.indexNode ??= createSignalNode(this.index, Object.is);\n return readSignal(this.indexNode);\n }\n\n /** List bookkeeping, not a user write: allowed while the list memo computes. */\n setItem(next: T): void {\n this.item = next;\n if (this.itemNode !== null) writeSignal(this.itemNode, next, { allowInMemo: true });\n }\n\n setIndex(next: number): void {\n this.index = next;\n if (this.indexNode !== null) writeSignal(this.indexNode, next, { allowInMemo: true });\n }\n}\n\n/** The dispose of a row whose root has not been made yet. */\nfunction noop(): void {\n // Replaced by the root's own dispose before the row is used.\n}\n\n/** One incoming item of a list update, with the key it is matched by. */\ninterface Entry<T> {\n readonly item: T;\n readonly key: unknown;\n readonly first: boolean;\n}\n\n/** How incoming items are matched against the rows of the previous update. */\ninterface Keying<T> {\n /** Reuse key of the item at `position`. User code, so it runs untracked. */\n readonly keyOf: (item: T, position: number) => unknown;\n /** Keyed lists: only the first copy of a key may reuse a row. Otherwise copies pair up in order. */\n readonly distinct: boolean;\n}\n\n/** The row shown while the list is empty, in its own root. */\ninterface Fallback<U> {\n readonly value: U;\n readonly dispose: () => void;\n}\n\n/** A row chosen by one update, in output order. */\ninterface Staged<T, U> {\n readonly row: Row<T, U>;\n readonly item: T;\n readonly position: number;\n readonly fresh: boolean;\n}\n\n/**\n * Maps each item of a list to a row that lives as long as the item does. Rows whose key survives\n * an update keep their mapped value; new items get new rows; removed items have their rows disposed.\n *\n * Unkeyed: rows are matched by item reference, and `map` receives the item value. Equal primitives\n * pair up in order of occurrence. The returned accessor is lazy and memoized: rows are created and\n * disposed when it is read, so a list nobody reads keeps removed rows alive until the next read.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `index()` follows the row.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [users] = useSignal([{ name: \"Ada\" }, { name: \"Linus\" }]);\n * const names = mapArray(users, (user, index) => `${index() + 1}. ${user.name}`);\n * console.log(names()); // [\"1. Ada\", \"2. Linus\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T, index: () => number) => U,\n options?: { key?: undefined; fallback?: () => U },\n): Accessor<U[]>;\n/**\n * Keyed form: rows are matched by `key(item)`. `map` receives an accessor, so a new object under\n * the same key updates `item()` without re-creating the row. A duplicate key warns in dev and its\n * later copies get fresh rows on every update (dev warning `EACH_KEY_DUPLICATE`, once). Keys\n * compare like `Map` keys, so `NaN` matches `NaN`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per new row, untracked, in the row's own root. `item()` and `index()` follow\n * the row.\n * @param options `key` identifies each item and runs untracked; `fallback` is shown while the list\n * is empty.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map`, `key` or a row cleanup threw;\n * several errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, mapArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [todos] = useSignal([{ id: 1, title: \"Write docs\" }]);\n * const rows = mapArray(todos, (todo) => `#${todo().id} ${todo().title}`, {\n * key: (todo) => todo.id,\n * });\n * console.log(rows()); // [\"#1 Write docs\"]\n * });\n * @see indexArray\n * @since 1.0.0\n */\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: () => number) => U,\n options: { key: (item: T) => unknown; fallback?: () => U },\n): Accessor<U[]>;\nexport function mapArray<T, U>(\n list: ListSource<T>,\n map: (item: T | (() => T), index: () => number) => U,\n options?: { key?: ((item: T) => unknown) | undefined; fallback?: (() => U) | undefined },\n): Accessor<U[]> {\n const keyOf = options?.key;\n return listRows(\n list,\n keyOf === undefined\n ? { keyOf: (item: T) => item, distinct: false }\n : { keyOf: (item: T) => keyOf(item), distinct: true },\n (item, readItem, readIndex) => map(keyOf === undefined ? item : readItem, readIndex),\n options?.fallback,\n );\n}\n\n/**\n * Maps each position of a list to a row. Rows are created and removed only when the length\n * changes; the row at position `i` stays, and its `item()` accessor follows the value at `i`.\n *\n * @param list Source list. `null`, `undefined` and `false` are an empty list.\n * @param map Runs once per position, untracked, in the row's own root.\n * @param options `fallback` is shown while the list is empty. Undefined: an empty list maps to `[]`.\n * @returns Accessor of the mapped rows, in the order of the input.\n * @throws Nothing itself. Reading the accessor rethrows what `map` or a row cleanup threw; several\n * errors at once arrive as one `AggregateError`.\n * @example\n * import { createRoot, indexArray, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [values] = useSignal([\"a\", \"b\"]);\n * const cells = indexArray(values, (value, index) => `${index}: ${value()}`);\n * console.log(cells()); // [\"0: a\", \"1: b\"]\n * });\n * @see mapArray\n * @since 1.0.0\n */\nexport function indexArray<T, U>(\n list: ListSource<T>,\n map: (item: () => T, index: number) => U,\n options?: { fallback?: () => U },\n): Accessor<U[]> {\n return listRows(\n list,\n { keyOf: (_item: T, position: number) => position, distinct: false },\n (_item, readItem, readIndex) => map(readItem, untrack(readIndex)),\n options?.fallback,\n );\n}\n\n/**\n * The shared engine. The memo tracks `list()` and reconciles the previous rows against the new\n * items; each row is a child of a private holder owner, so the memo's own recomputation never\n * disposes rows, and disposing the list's owner disposes the holder with every row in it.\n */\nfunction listRows<T, U>(\n list: ListSource<T>,\n keying: Keying<T>,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n fallback: (() => U) | undefined,\n): Accessor<U[]> {\n const holder = new Owner(getOwner());\n onCleanup(() => {\n disposeOwner(holder);\n });\n let rows: Row<T, U>[] = [];\n let emptyFallback: Fallback<U> | undefined;\n return useMemo<U[]>(\n () => {\n // Reading the list's contents is tracked, so a store array (proxy) updates the list when an\n // item is pushed, removed or replaced; user key functions then run untracked.\n const source = listItems(list());\n const items: readonly unknown[] = Array.isArray(source)\n ? Array.prototype.slice.call(source)\n : source;\n const entries = untrack(() => toEntries(items as readonly never[], keying));\n const reuse = matchRows(rows, entries);\n const created: Row<T, U>[] = [];\n const staged: Staged<T, U>[] = [];\n let nextFallback: Fallback<U> | undefined;\n try {\n entries.forEach((entry, position) => {\n const from = reuse[position] ?? -1;\n const kept = from === -1 ? undefined : rows[from];\n if (kept !== undefined) {\n staged.push({ row: kept, item: entry.item, position, fresh: false });\n return;\n }\n const row = openRow(holder, entry.key, entry.first, entry.item, position, build);\n created.push(row);\n staged.push({ row, item: entry.item, position, fresh: true });\n });\n if (entries.length === 0 && fallback !== undefined) {\n nextFallback = emptyFallback ?? openFallback(holder, fallback);\n }\n } catch (error) {\n // Nothing above touched the previous state, so only the rows made in this pass go.\n const failures: unknown[] = [];\n for (const row of created) disposeCollecting(row.dispose, failures);\n if (nextFallback !== undefined && nextFallback !== emptyFallback) {\n disposeCollecting(nextFallback.dispose, failures);\n }\n throw combineFailures(error, failures);\n }\n\n // Commit. Writes to retained rows come last, after every creation has succeeded.\n const failures: unknown[] = [];\n const previousRows = rows;\n const previousFallback = emptyFallback;\n rows = staged.map((stage) => stage.row);\n emptyFallback = nextFallback;\n const kept = new Uint8Array(previousRows.length);\n for (const from of reuse) {\n if (from !== -1) kept[from] = 1;\n }\n previousRows.forEach((row, from) => {\n if (kept[from] !== 1) disposeCollecting(row.dispose, failures);\n });\n if (previousFallback !== undefined && previousFallback !== nextFallback) {\n disposeCollecting(previousFallback.dispose, failures);\n }\n for (const stage of staged) {\n if (stage.fresh) continue;\n const row = stage.row;\n if (row.index !== stage.position) row.setIndex(stage.position);\n if (!Object.is(row.item, stage.item)) row.setItem(stage.item);\n }\n throwFailures(failures);\n if (nextFallback !== undefined) return [nextFallback.value];\n return rows.map((row) => row.value);\n },\n // The row callbacks build children (components, refs, directives): setup may write signals.\n { lazy: true, allowWrites: true },\n );\n}\n\n/** Treats `null`, `undefined` and `false` as an empty list. */\nfunction listItems<T>(value: readonly T[] | null | undefined | false): readonly T[] {\n return value === null || value === undefined || value === false ? [] : value;\n}\n\n/** Computes each item's reuse key. Keyed lists flag later copies of a key and warn once. */\nfunction toEntries<T>(items: readonly T[], keying: Keying<T>): Entry<T>[] {\n const entries: Entry<T>[] = [];\n const seen = new Set<unknown>();\n let duplicate = false;\n for (const [position, item] of items.entries()) {\n const key = keying.keyOf(item, position);\n let first = true;\n if (keying.distinct) {\n if (seen.has(key)) {\n first = false;\n duplicate = true;\n } else {\n seen.add(key);\n }\n }\n entries.push({ item, key, first });\n }\n if (duplicate) warn(\"EACH_KEY_DUPLICATE\");\n return entries;\n}\n\n/** Keys compare like `Map` keys: `NaN` matches `NaN`. */\nfunction sameKey(a: unknown, b: unknown): boolean {\n return a === b || (Number.isNaN(a) && Number.isNaN(b));\n}\n\nfunction canReuse<T, U>(row: Row<T, U> | undefined, entry: Entry<T> | undefined): boolean {\n return (\n row !== undefined &&\n entry !== undefined &&\n row.first &&\n entry.first &&\n sameKey(row.key, entry.key)\n );\n}\n\n/**\n * Pairs each new position with the old row it reuses; -1 means a fresh row is needed. The prefix\n * and suffix runs settle append, prepend, remove and swap at the ends in one step each. The middle\n * is matched through a Map from key to the chain of old positions with that key (earliest first),\n * so the whole pass is linear on average. Iterative throughout.\n */\nfunction matchRows<T, U>(old: readonly Row<T, U>[], next: readonly Entry<T>[]): Int32Array {\n const m = old.length;\n const n = next.length;\n const reuse = new Int32Array(n).fill(-1);\n let start = 0;\n while (start < m && start < n && canReuse(old[start], next[start])) {\n reuse[start] = start;\n start += 1;\n }\n let oldEnd = m - 1;\n let newEnd = n - 1;\n while (oldEnd >= start && newEnd >= start && canReuse(old[oldEnd], next[newEnd])) {\n reuse[newEnd] = oldEnd;\n oldEnd -= 1;\n newEnd -= 1;\n }\n if (start > oldEnd || start > newEnd) return reuse;\n\n const heads = new Map<unknown, number>();\n const chain = new Int32Array(m).fill(-1);\n for (let i = oldEnd; i >= start; i -= 1) {\n const row = old[i];\n if (row === undefined || !row.first) continue;\n chain[i] = heads.get(row.key) ?? -1;\n heads.set(row.key, i);\n }\n for (let j = start; j <= newEnd; j += 1) {\n const entry = next[j];\n if (entry === undefined || !entry.first) continue;\n const head = heads.get(entry.key);\n if (head === undefined || head === -1) continue;\n reuse[j] = head;\n heads.set(entry.key, chain[head] ?? -1);\n }\n return reuse;\n}\n\n/**\n * Creates one row in its own root under the holder. The row exists before `build` runs, so a read of `item()` or\n * `index()` during the build sees the final values. The root is detached from the memo on purpose.\n */\nfunction openRow<T, U>(\n holder: Owner,\n key: unknown,\n first: boolean,\n item: T,\n index: number,\n build: (item: T, readItem: () => T, readIndex: () => number) => U,\n): Row<T, U> {\n const row = new Row<T, U>(key, first, item, index);\n const readItem = (): T => row.readItem();\n const readIndex = (): number => row.readIndex();\n runWithOwner(holder, () =>\n createRoot((dispose) => {\n row.dispose = dispose;\n row.value = untrack(() => build(item, readItem, readIndex));\n }),\n );\n return row;\n}\n\n/** Creates the empty-list row in its own root under the holder. */\nfunction openFallback<U>(holder: Owner, fallback: () => U): Fallback<U> {\n return runWithOwner(holder, () =>\n createRoot((dispose) => ({ value: untrack(fallback), dispose })),\n );\n}\n\n/** Disposes one row root. A throwing cleanup is collected so that the other rows still go. */\nfunction disposeCollecting(dispose: () => void, failures: unknown[]): void {\n try {\n dispose();\n } catch (error) {\n failures.push(error);\n }\n}\n\nfunction combineFailures(primary: unknown, failures: readonly unknown[]): unknown {\n if (failures.length === 0) return primary;\n return new AggregateError(\n [primary, ...failures],\n __DEV__ ? \"Several errors were thrown while mapping a list.\" : \"SHADOW_MAP_ERRORS\",\n );\n}\n\n/** Rethrows the one disposal failure, or all of them together. */\nfunction throwFailures(failures: readonly unknown[]): void {\n if (failures.length === 0) return;\n if (failures.length === 1) throw failures[0];\n throw new AggregateError(\n failures,\n __DEV__\n ? \"Several errors were thrown while disposing list rows.\"\n : \"SHADOW_LIST_DISPOSE_ERRORS\",\n );\n}\n"],"mappings":"A,qYAuBA,IAAMA,EAAN,KAAgB,CAEd,IAEA,MAEA,KAEA,MACA,MAAW,IAAA,GACX,QAAsBC,EAEtB,SAAyC,KAEzC,UAA+C,KAE/C,YAAY,EAAc,EAAgB,EAAS,EAAe,CAChE,KAAK,IAAMC,EACX,KAAK,MAAQC,EACb,KAAK,KAAOC,EACZ,KAAK,MAAQC,CACf,CAEA,UAAc,CAEZ,MADA,MAAK,WAAaC,EAAiB,KAAK,KAAM,OAAO,EAAE,EAChDC,EAAW,KAAK,QAAQ,CACjC,CAEA,WAAoB,CAElB,MADA,MAAK,YAAcD,EAAiB,KAAK,MAAO,OAAO,EAAE,EAClDC,EAAW,KAAK,SAAS,CAClC,CAGA,QAAQ,EAAe,CACrB,KAAK,KAAOC,EACR,KAAK,WAAa,MAAMC,EAAY,KAAK,SAAUD,EAAM,CAAE,YAAa,EAAK,CAAC,CACpF,CAEA,SAAS,EAAoB,CAC3B,KAAK,MAAQA,EACT,KAAK,YAAc,MAAMC,EAAY,KAAK,UAAWD,EAAM,CAAE,YAAa,EAAK,CAAC,CACtF,CACF,EAGA,SAASP,GAAa,CAEtB,CA6FA,SAAgBS,EACd,EACA,EACA,EACe,CACf,IAAMC,EAAQC,GAAS,IACvB,OAAOC,EACLC,EACAH,IAAU,IAAA,GACN,CAAE,MAAQ,GAAYP,EAAM,SAAU,EAAM,EAC5C,CAAE,MAAQ,GAAYO,EAAMP,CAAI,EAAG,SAAU,EAAK,GACrD,EAAM,EAAU,IAAcW,EAAIJ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t}from"./extend/index.js";function n(n,r){let i=e({kind:`memo`,fn:n,equals:r?.equals===void 0?Object.is:r.equals,lazy:r?.lazy===!0,allowWrites:r?.allowWrites===!0,...r?.name===void 0?{}:{name:r.name}});return()=>t(i)}export{n as useMemo};
2
+ //# sourceMappingURL=memo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memo.js","names":["useMemo","node","createComputation","options","readComputation"],"sources":["../../src/memo.ts"],"sourcesContent":["import { type Accessor, createComputation, type Equals, readComputation } from \"./extend\";\n\n/**\n * Options of {@link useMemo}.\n * @since 1.0.0\n */\nexport interface MemoOptions<T> {\n /**\n * Decides whether a recomputation changed the value: readers are notified only when it returns\n * `false`. `false` always propagates.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Skip the initial computation until the first read. Without it the memo computes once when it\n * is created.\n * @default false\n */\n lazy?: boolean;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the memo is unnamed)\n */\n name?: string;\n /**\n * Turn off the development check that rejects signal writes while this memo computes. Set it for\n * a memo that builds children (components, `ref` callbacks, directives), where the code that runs\n * is setup and may write a counter or a registry; the control-flow components do. A memo that\n * derives a value must leave it off.\n * @default false\n */\n allowWrites?: boolean;\n}\n\n/**\n * Creates a cached derivation that recomputes only when a dependency actually changed.\n * Dependencies are discovered on every run, so branches that are not taken are not tracked.\n * A memo that throws inside an error boundary (an ancestor `onError` or `catchError`) reports the\n * error there and keeps its previous value; without a boundary it stores the error and rethrows it\n * to every reader.\n *\n * @param fn Computation; receives the previous value (`undefined` on the first run).\n * @param options Equality override, `lazy`, `allowWrites` and a devtools name. Undefined uses the\n * defaults.\n * @returns An accessor returning the current, always fresh value.\n * @throws ShadowError `CYCLE_DETECTED` from the accessor when the memo reads itself while it\n * computes. Outside an error boundary the accessor also rethrows the error `fn` threw on its last\n * run.\n * @example\n * import { useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(2);\n * const doubled = useMemo(() => count() * 2);\n * setCount(5);\n * console.log(doubled()); // 10\n * @see useSignal\n * @since 1.0.0\n */\nexport function useMemo<T>(\n fn: (previous: T | undefined) => T,\n options?: MemoOptions<T>,\n): Accessor<T> {\n const node = createComputation({\n kind: \"memo\",\n fn: fn as (previous: never) => unknown,\n equals: (options?.equals === undefined ? Object.is : options.equals) as Equals<unknown>,\n lazy: options?.lazy === true,\n allowWrites: options?.allowWrites === true,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n return () => readComputation<T>(node);\n}\n"],"mappings":"A,2EA0DA,SAAgBA,EACd,EACA,EACa,CACb,IAAMC,EAAOC,EAAkB,CAC7B,KAAM,OACF,KACJ,OAASC,GAAS,SAAW,IAAA,GAAY,OAAO,GAAKA,EAAQ,OAC7D,KAAMA,GAAS,OAAS,GACxB,YAAaA,GAAS,cAAgB,GACtC,GAAIA,GAAS,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAMA,EAAQ,IAAK,CAC9D,CAAC,EACD,UAAaC,EAAmBH,CAAI,CACtC,C"}
@@ -0,0 +1,2 @@
1
+ import{useSignal as e}from"./signal.js";import{useMemo as t}from"./memo.js";function n(n,r){let[i,a]=e([]);return[t(()=>{let e=n();for(let t of i())e=r(e,t.action);return e}),(e,t)=>{let n={action:e};a(e=>[...e,n]);let r=()=>{a(e=>e.filter(e=>e!==n))};t.then(r,r)}]}export{n as useOptimistic};
2
+ //# sourceMappingURL=optimistic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"optimistic.js","names":["useOptimistic","pending","setPending","useSignal","useMemo","current","source","entry","reducer","list","drop","item","settled"],"sources":["../../src/optimistic.ts"],"sourcesContent":["import type { Accessor } from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Optimistic state: shows `reducer` applied over the real value for every action whose\n * `settled` promise is still pending. When the promise settles (either way) the action is\n * dropped and the view falls back to the real source, which is where the confirmed result lives.\n *\n * @param source The authoritative value, tracked.\n * @param reducer Pure function combining the current state with one pending action. It runs for\n * every pending action, in the order they were applied, each time the state recomputes.\n * @returns `[state, apply]`. `state` is a memo; `apply(action, settled)` adds the action at once\n * and drops it when `settled` resolves or rejects. Pass the mutation's promise as `settled`.\n * @example\n * import { useOptimistic, useSignal } from \"@shadow-js/core\";\n *\n * const [todos, setTodos] = useSignal<string[]>([]);\n * const [shown, addTodo] = useOptimistic(todos, (list, text: string) => [...list, text]);\n * const save = (text: string) =>\n * fetch(\"/api/todos\", { method: \"POST\", body: text }).then(() => setTodos((l) => [...l, text]));\n * addTodo(\"milk\", save(\"milk\")); // shown() includes \"milk\" at once\n * @see useAction\n * @since 1.0.0\n */\nexport function useOptimistic<T, A>(\n source: Accessor<T>,\n reducer: (state: T, action: A) => T,\n): [Accessor<T>, (action: A, settled: Promise<unknown>) => void] {\n const [pending, setPending] = useSignal<ReadonlyArray<{ action: A }>>([]);\n const state = useMemo(() => {\n let current = source();\n for (const entry of pending()) current = reducer(current, entry.action);\n return current;\n });\n const apply = (action: A, settled: Promise<unknown>): void => {\n const entry = { action };\n setPending((list) => [...list, entry]);\n const drop = (): void => {\n setPending((list) => list.filter((item) => item !== entry));\n };\n settled.then(drop, drop);\n };\n return [state, apply];\n}\n"],"mappings":"A,4EAyBA,SAAgBA,EACd,EACA,EAC+D,CAC/D,GAAM,CAACC,EAASC,GAAcC,EAAwC,CAAC,CAAC,EAcxE,MAAO,CAbOC,MAAc,CAC1B,IAAIC,EAAUC,EAAO,EACrB,IAAK,IAAMC,KAASN,EAAQ,EAAG,EAAUO,EAAQH,EAASE,EAAM,MAAM,EACtE,OAAOF,CACT,CASQ,GARO,EAAW,IAAoC,CAC5D,IAAME,EAAQ,CAAE,QAAO,EACvBL,EAAY,GAAS,CAAC,GAAGO,EAAMF,CAAK,CAAC,EACrC,IAAMG,MAAmB,CACvBR,EAAY,GAASO,EAAK,OAAQ,GAASE,IAASJ,CAAK,CAAC,CAC5D,EACAK,EAAQ,KAAKF,EAAMA,CAAI,CACzB,CACoB,CACtB,C"}
@@ -0,0 +1,2 @@
1
+ import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t,addCleanup as n,handleError as r}from"./internal/owner.js";import{disposeTree as i}from"./internal/dispose.js";import{currentOwner as a,runInScope as o}from"./extend/index.js";function s(e){return o({listener:null},e)}function c(e,n){let r=n?.detached===!0,s=a(),c=new t(r?null:s);r&&(c.context=s===null?null:s.context);try{return o({owner:c,listener:null},()=>e(()=>i(c)))}catch(e){throw i(c),e}}function l(){return a()}function u(e,t){let n=e;return n?.disposed&&(n=null),o({owner:n,listener:null},t)}function d(e){let t=a();t!==null&&n(t,e)}function f(e){let t=a();t!==null&&(t.errorHandlers===null?t.errorHandlers=[e]:t.errorHandlers.push(e))}function p(e,n){let i=new t(a());i.errorHandlers=[n];try{return u(i,e)}catch(e){r(e,i);return}}function m(){let t=a();if(t===null)throw new e(`NO_OWNER_ID`);for(let e=t;e!==null;e=e.parent){if(e.idPrefix===void 0)continue;let t=e.idCount;return e.idCount+=1,`s${e.idPrefix}${t}`}let n=[];for(let e=t;e!==null;e=e.parent)n.push(e.index);n.reverse();let r=t.idCount;return t.idCount+=1,`s${n.join(`-`)}_${r}`}export{p as catchError,c as createRoot,l as getOwner,d as onCleanup,f as onError,u as runWithOwner,s as untrack,m as useId};
2
+ //# sourceMappingURL=ownership.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ownership.js","names":["disposeOwner","untrack","runInScope","fn","createRoot","detached","options","current","currentOwner","root","Owner","disposeTree","error","getOwner","runWithOwner","target","owner","onCleanup","addCleanup","onError","handler","catchError","scope","handleError","useId","ShadowError","host","hosted","path","node","sequence"],"sources":["../../src/ownership.ts"],"sourcesContent":["import {\n addCleanup,\n type Cleanup,\n currentOwner,\n disposeOwner,\n type ErrorHandler,\n handleError,\n Owner,\n runInScope,\n ShadowError,\n warn,\n} from \"./extend\";\n\nexport type { Owner };\n\n/**\n * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an\n * effect or a memo to read a value without re-running when that value changes. The current owner\n * is kept, so effects and cleanups created inside `fn` are still owned.\n *\n * @param fn The function to run untracked.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { untrack, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const [unit] = useSignal(\"clicks\");\n * useEffect(() => {\n * // Re-runs when `count` changes, never when `unit` changes.\n * console.log(`${count()} ${untrack(unit)}`);\n * });\n * setCount(1);\n * @see useEvent\n * @since 1.0.0\n */\nexport function untrack<T>(fn: () => T): T {\n return runInScope({ listener: null }, fn);\n}\n\n/**\n * Options of {@link createRoot}.\n * @since 1.0.0\n */\nexport interface RootOptions {\n /**\n * When true, the root is not attached to the current owner: it outlives that owner and is\n * disposed only through the `dispose` function passed to the body. It still sees the context\n * values provided above the current owner.\n * @default false (the root is a child of the current owner and is disposed with it)\n */\n detached?: boolean;\n}\n\n/**\n * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is\n * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use\n * it for code that runs outside a component, such as an app entry point, a test or a module that\n * owns long-lived effects.\n *\n * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.\n * @param options `detached` keeps the root out of the current owner. Undefined uses the default\n * (attached).\n * @returns Whatever `fn` returns.\n * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are\n * disposed.\n * @example\n * import { createRoot, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const dispose = createRoot((dispose) => {\n * useEffect(() => console.log(count()));\n * return dispose;\n * });\n * setCount(1);\n * dispose(); // the effect stops and its cleanups run\n * @see getOwner\n * @since 1.0.0\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T, options?: RootOptions): T {\n const detached = options?.detached === true;\n const current = currentOwner();\n const root = new Owner(detached ? null : current);\n if (detached) root.context = current === null ? null : current.context;\n try {\n return runInScope({ owner: root, listener: null }, () => fn(() => disposeOwner(root)));\n } catch (error) {\n disposeOwner(root);\n throw error;\n }\n}\n\n/**\n * Returns the owner that currently adopts new effects, memos and cleanups. Capture it while a\n * component or root runs, then hand it to {@link runWithOwner} from code that runs later.\n *\n * @returns The current owner, or `null` outside any owner (at module scope, or in a callback that\n * runs after an `await` or a timer).\n * @example\n * import { getOwner, onCleanup, runWithOwner } from \"@shadow-js/core\";\n *\n * function Poller() {\n * const owner = getOwner();\n * setTimeout(() => {\n * runWithOwner(owner, () => onCleanup(() => console.log(\"poller disposed\")));\n * }, 1000);\n * return null;\n * }\n * @see runWithOwner\n * @since 1.0.0\n */\nexport function getOwner(): Owner | null {\n return currentOwner();\n}\n\n/**\n * Runs `fn` with `owner` as the current owner, untracked. Use it to restore ownership after an\n * `await` or inside callbacks that outlive the synchronous run, so that effects, cleanups and\n * context reads inside `fn` attach to that owner. A disposed owner is ignored: `fn` then runs\n * without an owner, and development builds warn `RUN_WITH_DISPOSED_OWNER`.\n *\n * @param owner The owner to make current, usually captured with {@link getOwner}. `null` runs `fn`\n * without an owner.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { createContext, getOwner, runWithOwner, useContext } from \"@shadow-js/core\";\n *\n * const Locale = createContext(\"en\");\n *\n * function Clock() {\n * const owner = getOwner();\n * queueMicrotask(() => {\n * const locale = runWithOwner(owner, () => useContext(Locale));\n * console.log(new Date().toLocaleTimeString(locale));\n * });\n * return null;\n * }\n * @see getOwner\n * @since 1.0.0\n */\nexport function runWithOwner<T>(owner: Owner | null, fn: () => T): T {\n let target = owner;\n if (target?.disposed) {\n warn(\"RUN_WITH_DISPOSED_OWNER\");\n target = null;\n }\n return runInScope({ owner: target, listener: null }, fn);\n}\n\n/**\n * Registers `fn` to run when the current owner is disposed or, for an effect or memo, before it\n * re-runs. Cleanups run newest first and untracked; one that throws does not stop the others, and\n * its error goes to the nearest error handler ({@link onError}, {@link catchError}). Outside any owner the call does nothing, because\n * nothing would ever run the cleanup; development builds warn `NO_OWNER_CLEANUP`.\n *\n * @param fn The cleanup to register.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const timer = setInterval(() => console.log(\"tick\"), 1000);\n * onCleanup(() => clearInterval(timer));\n * return null;\n * }\n * @see onMount\n * @since 1.0.0\n */\nexport function onCleanup(fn: Cleanup): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_CLEANUP\");\n return;\n }\n addCleanup(owner, fn);\n}\n\n/**\n * Registers an error handler on the current owner. It receives errors thrown in this owner's scope\n * (its effects, memos, cleanups and child owners) that no closer handler took. Handlers on the same\n * owner are tried newest first; a handler that throws passes its own error to the next handler up.\n * Outside any owner the call does nothing; development builds warn `NO_OWNER_ERROR`.\n *\n * @param handler Receives the error, untracked. Throw from it to pass an error on to the next handler.\n * @example\n * import { onError, useEffect } from \"@shadow-js/core\";\n *\n * function Dashboard() {\n * onError((error) => console.error(\"dashboard failed:\", error));\n * useEffect(() => {\n * throw new Error(\"widget crashed\"); // reaches the handler above\n * });\n * return null;\n * }\n * @see catchError\n * @since 1.0.0\n */\nexport function onError(handler: ErrorHandler): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_ERROR\");\n return;\n }\n if (owner.errorHandlers === null) owner.errorHandlers = [handler];\n else owner.errorHandlers.push(handler);\n}\n\n/**\n * Runs `fn` inside a new child scope whose errors go to `handler`: errors thrown synchronously by\n * `fn`, and later errors of the effects, memos and cleanups it created. The scope is disposed with\n * the current owner. Use it to contain the failures of one part of a component tree.\n *\n * @param fn The function to run; it runs untracked, with the new scope as owner.\n * @param handler Receives each error, untracked. Throw from it to pass the error on to the next handler up.\n * @returns Whatever `fn` returns, or `undefined` when `fn` threw and `handler` took the error.\n * @throws Rethrows the error `handler` throws when no handler above takes it (outside a flush).\n * @example\n * import { catchError, useEffect } from \"@shadow-js/core\";\n *\n * function Widget() {\n * return catchError(\n * () => {\n * useEffect(() => {\n * throw new Error(\"network down\");\n * });\n * return \"ready\";\n * },\n * (error) => console.error(\"widget failed:\", error),\n * );\n * }\n * @see onError\n * @since 1.0.0\n */\nexport function catchError<T>(fn: () => T, handler: ErrorHandler): T | undefined {\n const scope = new Owner(currentOwner());\n scope.errorHandlers = [handler];\n try {\n return runWithOwner(scope, fn);\n } catch (error) {\n return void handleError(error, scope);\n }\n}\n\n/**\n * Returns an id that is identical on server and client for the same position in the owner tree.\n * The id uses only letters, digits, `-` and `_`, so it is valid in `id`, `for`, `aria-*` references\n * and in `querySelector(\"#\" + id)` without escaping. Use it to link a label to its input, or an\n * element to its `aria-describedby` target, in markup that is rendered on the server and hydrated.\n *\n * @returns A new id, unique within the root; each call on the same owner returns the next one.\n * @throws ShadowError `NO_OWNER_ID` when called outside any owner, because no stable id exists\n * there.\n * @example\n * import { useId } from \"@shadow-js/core\";\n *\n * function EmailField() {\n * const id = useId();\n * return (\n * <>\n * <label for={id}>Email</label>\n * <input id={id} type=\"email\" />\n * </>\n * );\n * }\n * @since 1.0.0\n */\nexport function useId(): string {\n const owner = currentOwner();\n if (owner === null) throw new ShadowError(\"NO_OWNER_ID\");\n // An owner with an id prefix (a component the renderer put in a hydration scope) hosts the ids of\n // everything below it: the prefix already encodes where the component is, and the owners between\n // here and there (effects exist in the browser, not on the server) must not leak into the id.\n for (let host: Owner | null = owner; host !== null; host = host.parent) {\n if (host.idPrefix === undefined) continue;\n const hosted = host.idCount;\n host.idCount += 1;\n return `s${host.idPrefix}${hosted}`;\n }\n const path: number[] = [];\n for (let node: Owner | null = owner; node !== null; node = node.parent) path.push(node.index);\n path.reverse();\n const sequence = owner.idCount;\n owner.idCount += 1;\n return `s${path.join(\"-\")}_${sequence}`;\n}\n"],"mappings":"A,0PAmCA,SAAgBC,EAAW,EAAgB,CACzC,OAAOC,EAAW,CAAE,SAAU,IAAK,EAAGC,CAAE,CAC1C,CAyCA,SAAgBC,EAAc,EAAgC,EAA0B,CACtF,IAAMC,EAAWC,GAAS,WAAa,GACjCC,EAAUC,EAAa,EACv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AWC,GAC7B,CACA,IAAMC,EAAiB,CAAC,EACxB,IAAK,IAAIC,EAAqBb,EAAOa,IAAS,KAAM,EAAOA,EAAK,OAAQD,EAAK,KAAKC,EAAK,KAAK,EAC5FD,EAAK,QAAQ,EACb,IAAME,EAAWd,EAAM,QAEvB,MADA,GAAM,SAAW,EACV,IAAIY,EAAK,KAAK,GAAG,EAAE,GAAGE,GAC/B,C"}
@@ -0,0 +1,2 @@
1
+ import{untrack as e}from"./ownership.js";import{useMemo as t}from"./memo.js";const n=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),r=/* @__PURE__ */ new WeakSet;function i(e){return e==null||e===!1}function a(e){return Reflect.ownKeys(e).filter(t=>!n.has(t)&&Object.prototype.propertyIsEnumerable.call(e,t))}function o(e,t,n){Object.defineProperty(e,t,{enumerable:!0,configurable:!0,get:n})}function s(e){let t=typeof e==`function`?e():e;if(!i(t)){if(typeof t==`object`&&t)return t;throw TypeError(`SHADOW_MERGE_SOURCE`)}}function c(e){let t=[];for(let n of e){let e=s(n);e!==void 0&&t.push(e)}return t}function l(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r===void 0||!(t in r))continue;let i=Reflect.get(r,t);if(i!==void 0)return i}}function u(e){let t=/* @__PURE__ */ new Set,n=[];for(let r of e)for(let e of a(r))t.has(e)||(t.add(e),n.push(e));return n}let d=0;const f=/* @__PURE__ */ new Map;function p(e,t){let n=f.get(e);if(n!==void 0)return n;let r=t();return f.set(e,r),r}function m(e){d+=1;try{return e()}finally{--d,d===0&&f.clear()}}function h(e){let t={};return new Proxy(t,{get(n,r){return m(()=>{let n=p(t,e);return n.keys.has(r)?n.read(r):Reflect.get(t,r)})},has(n,r){return m(()=>p(t,e).keys.has(r)||Reflect.has(t,r))},ownKeys(){return m(()=>[...p(t,e).keys])},getOwnPropertyDescriptor(n,r){return m(()=>{if(p(t,e).keys.has(r))return{enumerable:!0,configurable:!0,get:()=>m(()=>p(t,e).read(r))}})},set:()=>!1,defineProperty:()=>!1,deleteProperty:()=>!1})}function g(...e){let t=[],n=!1;for(let r of e)if(!i(r)){if(typeof r==`function`)n=!0;else if(typeof r!=`object`)throw TypeError(`SHADOW_MERGE_SOURCES`);t.push(r)}if(!n){let e=c(t),n={};for(let t of u(e))o(n,t,()=>l(e,t));return n}let a=h(()=>{let e=c(t);return{keys:new Set(u(e)),read:t=>l(e,t)}});return r.add(a),a}function _(e,...t){let i=/* @__PURE__ */ new Set,s=[];for(let r of t){let t={};for(let a of r)n.has(a)||(i.add(a),o(t,a,()=>Reflect.get(e,a)));s.push(t)}let c=()=>a(e).filter(e=>!i.has(e)),l=t=>Reflect.get(e,t);if(r.has(e)){let e=h(()=>({keys:new Set(c()),read:l}));return[...s,e]}let u={};for(let e of c())o(u,e,()=>l(e));return[...s,u]}function v(e){let t=[],n=[],r=/* @__PURE__ */ new Set,i=e,a=0;for(;;){if(typeof i==`function`){if(a>=1e3)throw TypeError(`SHADOW_CHILDREN_LAYERS`);i=i(),a+=1;continue}if(Array.isArray(i)){if(r.has(i))throw TypeError(`SHADOW_CHILDREN_CYCLE`);r.add(i),n.push({items:i,next:0,layer:a})}else i!=null&&typeof i!=`boolean`&&t.push(i);let e=!1;for(;!e;){let o=n.at(-1);if(o===void 0)return t;o.next<o.items.length?(i=o.items[o.next],o.next+=1,a=o.layer,e=!0):(n.pop(),r.delete(o.items))}}}function y(n){let r=t(()=>v(n),{allowWrites:!0});return Object.assign(()=>{let e=r();return e.length===1?e[0]:e.length===0?void 0:e},{toArray:()=>[...r()],count:()=>r().length,map:t=>r().map((n,r)=>e(()=>t(n,r))),forEach:t=>{r().forEach((n,r)=>{e(()=>t(n,r))})},only:()=>{let e=r();if(e.length!==1)throw TypeError(`SHADOW_CHILDREN_ONLY`);return e[0]}})}export{y as children,g as mergeProps,_ as splitProps};
2
+ //# sourceMappingURL=props.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"props.js","names":["UNSAFE_KEYS","DYNAMIC_PROPS","isEmptySource","value","ownEnumerableKeys","source","key","defineGetter","target","read","resolveSource","resolveAll","resolved","sources","object","readMerged","index","objects","mergedKeys","seen","keys","readDepth","readStates","stateOf","known","view","state","load","duringRead","run","liveView","mergeProps","inputs","dynamic","merged","splitProps","listed","groups","group","picked","props","restKeys","readRest","rest","flattenChildren","leaves","frames","open","fn","layer","advanced","top","children","memo","useMemo","untrack","leaf"],"sources":["../../src/props.ts"],"sourcesContent":["import { useMemo } from \"./memo\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Keys that never take part in a merge or a split. Reading them through a props object that came\n * from JSON or from user input could reach `Object.prototype`, so they are skipped everywhere.\n */\nconst UNSAFE_KEYS: ReadonlySet<PropertyKey> = new Set<PropertyKey>([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Results of mergeProps (and splitProps over them) that have at least one function source. Their\n * key set can change between reads, so splitProps builds a live rest object for them. A WeakSet is\n * bounded by the garbage collector.\n */\nconst DYNAMIC_PROPS = new WeakSet<object>();\n\n/** Longest chain of nested accessors that children() follows before it gives up. */\nconst MAX_FUNCTION_LAYERS = 1000;\n\n/**\n * A value accepted by {@link mergeProps}: an object, a function that returns one (called at every\n * read, so it can be reactive), or `null`, `undefined` or `false`, which are skipped. Use it to type\n * a helper that collects sources before merging them.\n * @since 1.0.0\n */\nexport type MergeSource = object | null | undefined | false;\n\n/** The props object a source stands for; functions contribute their return type. */\ntype PropsOf<S> = S extends (...args: never[]) => infer R\n ? Exclude<R, null | undefined | false>\n : S extends null | undefined | false\n ? object\n : S;\n\n/** Later keys replace earlier ones; a later key that may be `undefined` keeps the earlier type too. */\ntype Overlay<A, B> = {\n [K in keyof A | keyof B]: K extends keyof B\n ? K extends keyof A\n ? undefined extends B[K]\n ? Exclude<B[K], undefined> | A[K]\n : B[K]\n : B[K]\n : K extends keyof A\n ? A[K]\n : never;\n};\n\n/**\n * The type of `mergeProps(...sources)`, folded left to right: a later source's key replaces an\n * earlier one, and a later key that may be `undefined` keeps the earlier type as well.\n * @since 1.0.0\n */\nexport type MergeProps<T extends readonly unknown[], Acc = object> = T extends readonly [\n infer Head,\n ...infer Rest,\n]\n ? MergeProps<Rest, Overlay<Acc, PropsOf<Head>>>\n : Acc;\n\n/**\n * The type of `splitProps(props, ...keyLists)`: one object per key list, picking those keys, then\n * the rest without any listed key.\n * @since 1.0.0\n */\nexport type SplitProps<T extends object, K extends readonly (readonly (keyof T)[])[]> = [\n ...{ [I in keyof K]: Pick<T, Extract<K[I][number], keyof T>> },\n Omit<T, K[number][number]>,\n];\n\n/**\n * The value returned by {@link children}: calling it yields one leaf, an array of several leaves,\n * or `undefined` for none; `toArray()` always returns an array. The methods mirror React's\n * `Children` helpers.\n * @since 1.0.0\n */\nexport interface ResolvedChildren {\n /**\n * The current children: one leaf, an array of several leaves, or `undefined` when there is none.\n * The read is tracked like a memo read.\n */\n (): unknown;\n /** A fresh array of the leaves, without `null`, `undefined` or booleans. */\n toArray(): unknown[];\n /** Number of leaves, zero or more (the React `Children.count`). */\n count(): number;\n /** Maps each leaf with its index; the callback runs untracked (React `Children.map`). */\n map<U>(fn: (leaf: unknown, index: number) => U): U[];\n /** Visits each leaf with its index; the callback runs untracked (React `Children.forEach`). */\n forEach(fn: (leaf: unknown, index: number) => void): void;\n /**\n * The single leaf (React `Children.only`). Throws a TypeError (production message\n * `SHADOW_CHILDREN_ONLY`) when there is not exactly one leaf.\n */\n only(): unknown;\n}\n\n/** Whether a source stands for nothing and is skipped. */\nfunction isEmptySource(value: unknown): value is null | undefined | false {\n return value === null || value === undefined || value === false;\n}\n\n/** Own enumerable string and symbol keys, minus the unsafe ones. Reads no getter. */\nfunction ownEnumerableKeys(source: object): Key[] {\n return Reflect.ownKeys(source).filter(\n (key) => !UNSAFE_KEYS.has(key) && Object.prototype.propertyIsEnumerable.call(source, key),\n );\n}\n\n/** Defines an enumerable getter; the target is a fresh object, so this never hits a setter. */\nfunction defineGetter(target: object, key: PropertyKey, read: () => unknown): void {\n Object.defineProperty(target, key, { enumerable: true, configurable: true, get: read });\n}\n\n/** The object a source stands for at this moment, or `undefined` when it is skipped. */\nfunction resolveSource(source: object): object | undefined {\n const value: unknown = typeof source === \"function\" ? (source as () => unknown)() : source;\n if (isEmptySource(value)) return undefined;\n if (typeof value === \"object\" && value !== null) return value;\n throw new TypeError(\n __DEV__\n ? \"mergeProps: a source function must return an object, null, undefined or false\"\n : \"SHADOW_MERGE_SOURCE\",\n );\n}\n\n/** The sources that stand for an object right now, in order; skipped ones are dropped. */\nfunction resolveAll(sources: readonly object[]): object[] {\n const resolved: object[] = [];\n for (const source of sources) {\n const object = resolveSource(source);\n if (object !== undefined) resolved.push(object);\n }\n return resolved;\n}\n\n/**\n * Reads one merged key: the right-most object that has the key and a value other than `undefined`\n * wins. Each getter is read at most once.\n */\nfunction readMerged(objects: readonly object[], key: Key): unknown {\n for (let index = objects.length - 1; index >= 0; index -= 1) {\n const source = objects[index];\n if (source === undefined || !(key in source)) continue;\n const value: unknown = Reflect.get(source, key);\n if (value !== undefined) return value;\n }\n return undefined;\n}\n\n/** Every merged key in first-occurrence order. Reads no getter. */\nfunction mergedKeys(objects: readonly object[]): Key[] {\n const seen = new Set<Key>();\n const keys: Key[] = [];\n for (const source of objects) {\n for (const key of ownEnumerableKeys(source)) {\n if (seen.has(key)) continue;\n seen.add(key);\n keys.push(key);\n }\n }\n return keys;\n}\n\n/** A property name as a Proxy trap sees it. */\ntype Key = string | symbol;\n\n/** The key set and the reader that a live view uses for one access. */\ninterface LiveState {\n readonly keys: ReadonlySet<Key>;\n read(key: Key): unknown;\n}\n\n/**\n * A Proxy whose key set and values are recomputed on every access: `load` runs once per trap, so\n * a function source is called once per access. The target is an ordinary object, so prototype\n * lookups keep their usual meaning, and every write is refused because props are read-only.\n */\n/**\n * How deep the live reads are running, and the state each live view computed during the outermost\n * read. A view's traps read the views beneath it, and those read the views beneath them: without a\n * cache every trap recomputes each level below, and a few nested components (a chain of `{...props}`\n * forwards) take exponential time. Within one outermost read a view's state is computed once, so a\n * read costs time linear in the number of views. The cache is dropped when that read returns, so each\n * read still sees the current values.\n */\nlet readDepth = 0;\nconst readStates = new Map<object, LiveState>();\n\nfunction stateOf(view: object, load: () => LiveState): LiveState {\n const known = readStates.get(view);\n if (known !== undefined) return known;\n const state = load();\n readStates.set(view, state);\n return state;\n}\n\nfunction duringRead<T>(run: () => T): T {\n readDepth += 1;\n try {\n return run();\n } finally {\n readDepth -= 1;\n if (readDepth === 0) readStates.clear();\n }\n}\n\nfunction liveView(load: () => LiveState): object {\n const target: object = {};\n return new Proxy(target, {\n get(_target, key) {\n return duringRead(() => {\n const state = stateOf(target, load);\n return state.keys.has(key) ? state.read(key) : (Reflect.get(target, key) as unknown);\n });\n },\n has(_target, key) {\n return duringRead(() => stateOf(target, load).keys.has(key) || Reflect.has(target, key));\n },\n ownKeys() {\n return duringRead(() => [...stateOf(target, load).keys]);\n },\n getOwnPropertyDescriptor(_target, key) {\n return duringRead(() => {\n if (!stateOf(target, load).keys.has(key)) return undefined;\n return {\n enumerable: true,\n configurable: true,\n get: () => duringRead(() => stateOf(target, load).read(key)),\n };\n });\n },\n set: () => false,\n defineProperty: () => false,\n deleteProperty: () => false,\n });\n}\n\n/**\n * Merges props objects into one getter-preserving object. Reading a key returns the value from the\n * right-most source that has it, unless that value is `undefined`, in which case the next source\n * to the left is tried. Nothing is copied at merge time, so reads stay reactive. Use it to give\n * component props defaults without reading them in the component body.\n *\n * Sources may be objects, `null`, `undefined` or `false` (skipped), or functions that return an\n * object. A function is called on every read, which is how spreads such as `{...props()}` stay\n * reactive. Keys named `__proto__`, `constructor` or `prototype` are ignored.\n *\n * @param sources The props objects, from lowest to highest priority.\n * @returns A read-only object whose keys are the union of the sources' own enumerable keys. With a\n * function source, the key set is recomputed on every access.\n * @throws TypeError (production message `SHADOW_MERGE_SOURCES`) when a source is not an object, a\n * function, `null`, `undefined` or `false`. A read of the result throws TypeError (production\n * message `SHADOW_MERGE_SOURCE`) when a function source returns anything else.\n * @example\n * import { mergeProps } from \"@shadow-js/core\";\n *\n * function Button(props: { size?: \"sm\" | \"md\"; label: string }) {\n * const merged = mergeProps({ size: \"md\" as const }, props);\n * return <button class={`btn-${merged.size}`}>{merged.label}</button>;\n * }\n * @see splitProps\n * @since 1.0.0\n */\nexport function mergeProps<T extends readonly MergeSource[]>(...sources: T): MergeProps<T>;\nexport function mergeProps(...sources: readonly MergeSource[]): object {\n const inputs: object[] = [];\n let dynamic = false;\n for (const source of sources) {\n if (isEmptySource(source)) continue;\n if (typeof source === \"function\") {\n dynamic = true;\n } else if (typeof source !== \"object\") {\n throw new TypeError(\n __DEV__\n ? \"mergeProps: sources must be objects, functions, or null, undefined or false\"\n : \"SHADOW_MERGE_SOURCES\",\n );\n }\n inputs.push(source);\n }\n if (!dynamic) {\n const objects = resolveAll(inputs);\n const merged: object = {};\n for (const key of mergedKeys(objects)) {\n defineGetter(merged, key, () => readMerged(objects, key));\n }\n return merged;\n }\n const view = liveView(() => {\n const objects = resolveAll(inputs);\n return { keys: new Set(mergedKeys(objects)), read: (key) => readMerged(objects, key) };\n });\n DYNAMIC_PROPS.add(view);\n return view;\n}\n\n/**\n * Splits props into one getter-preserving object per key list, followed by an object holding every\n * other key. Each group reads its keys from `props` at access time, so reactivity is preserved. A\n * key listed in two groups appears in both and never in the rest. A listed key that `props` does not\n * have is still present in its group, as `undefined`. Use it to separate the props a component\n * consumes from the ones it forwards to an element.\n *\n * @param props The props to split; plain objects, Proxies and {@link mergeProps} results work.\n * @param keys One or more key lists. Keys named `__proto__`, `constructor` or `prototype` are\n * ignored.\n * @returns `[...groups, rest]`, in the order the key lists were given.\n * @example\n * import { splitProps } from \"@shadow-js/core\";\n *\n * function Field(props: { label: string; value: string; placeholder?: string }) {\n * const [own, input] = splitProps(props, [\"label\"]);\n * return (\n * <label>\n * {own.label}\n * <input {...input} />\n * </label>\n * );\n * }\n * @see mergeProps\n * @since 1.0.0\n */\nexport function splitProps<T extends object, const K extends readonly (readonly (keyof T)[])[]>(\n props: T,\n ...keys: K\n): SplitProps<T, K>;\nexport function splitProps(props: object, ...keys: readonly (readonly PropertyKey[])[]): object[] {\n const listed = new Set<PropertyKey>();\n const groups: object[] = [];\n for (const group of keys) {\n const picked: object = {};\n for (const key of group) {\n if (UNSAFE_KEYS.has(key)) continue;\n listed.add(key);\n defineGetter(picked, key, () => Reflect.get(props, key) as unknown);\n }\n groups.push(picked);\n }\n const restKeys = (): Key[] => ownEnumerableKeys(props).filter((key) => !listed.has(key));\n const readRest = (key: Key): unknown => Reflect.get(props, key) as unknown;\n if (DYNAMIC_PROPS.has(props)) {\n const rest = liveView(() => ({ keys: new Set(restKeys()), read: readRest }));\n return [...groups, rest];\n }\n const rest: object = {};\n for (const key of restKeys()) defineGetter(rest, key, () => readRest(key));\n return [...groups, rest];\n}\n\n/** One level of a children walk: an array being read and the function-layer depth it sits at. */\ninterface Frame {\n readonly items: readonly unknown[];\n next: number;\n readonly layer: number;\n}\n\n/**\n * Resolves children without recursion: arrays flatten in order, accessors are called until a plain\n * value appears, and `null`, `undefined` and booleans are dropped. A cyclic array or more than\n * {@link MAX_FUNCTION_LAYERS} nested accessors is a TypeError.\n */\nfunction flattenChildren(fn: () => unknown): unknown[] {\n const leaves: unknown[] = [];\n const frames: Frame[] = [];\n const open = new Set<readonly unknown[]>();\n let value: unknown = fn;\n let layer = 0;\n for (;;) {\n if (typeof value === \"function\") {\n if (layer >= MAX_FUNCTION_LAYERS) {\n throw new TypeError(\n __DEV__\n ? `children(): more than ${MAX_FUNCTION_LAYERS} nested accessors; a function child may return itself`\n : \"SHADOW_CHILDREN_LAYERS\",\n );\n }\n value = (value as () => unknown)();\n layer += 1;\n continue;\n }\n if (Array.isArray(value)) {\n if (open.has(value))\n throw new TypeError(\n __DEV__ ? \"children(): an array contains itself\" : \"SHADOW_CHILDREN_CYCLE\",\n );\n open.add(value);\n frames.push({ items: value, next: 0, layer });\n } else if (value !== null && value !== undefined && typeof value !== \"boolean\") {\n leaves.push(value);\n }\n let advanced = false;\n while (!advanced) {\n const top = frames.at(-1);\n if (top === undefined) return leaves;\n if (top.next < top.items.length) {\n value = top.items[top.next];\n top.next += 1;\n layer = top.layer;\n advanced = true;\n } else {\n frames.pop();\n open.delete(top.items);\n }\n }\n }\n}\n\n/**\n * Memoizes a `props.children` getter so that it is read at most once per change of its\n * dependencies. Arrays are flattened, accessors are called, and `null`, `undefined` and booleans\n * are dropped. The memo is created in the current owner, so nodes created while resolving are\n * disposed with it. Use it when a component inspects or rearranges its children.\n *\n * @param fn The lazy children accessor, usually `() => props.children`.\n * @returns A {@link ResolvedChildren} accessor with `toArray()`, `count()`, `map()`, `forEach()`\n * and `only()`.\n * @throws TypeError from the returned accessor and its methods when the children contain an array\n * that contains itself (production message `SHADOW_CHILDREN_CYCLE`) or more than 1000 nested\n * accessors (`SHADOW_CHILDREN_LAYERS`). `only()` throws TypeError (`SHADOW_CHILDREN_ONLY`) unless\n * there is exactly one leaf.\n * @example\n * import { children } from \"@shadow-js/core\";\n *\n * function Steps(props: { children?: unknown }) {\n * const steps = children(() => props.children);\n * return (\n * <ol aria-label={`${steps.count()} steps`}>\n * {steps.map((step) => <li>{step as Node | string}</li>)}\n * </ol>\n * );\n * }\n * @since 1.0.0\n */\nexport function children(fn: () => unknown): ResolvedChildren {\n const memo = useMemo(() => flattenChildren(fn), { allowWrites: true });\n const accessor = (): unknown => {\n const leaves = memo();\n if (leaves.length === 1) return leaves[0];\n return leaves.length === 0 ? undefined : leaves;\n };\n return Object.assign(accessor, {\n toArray: (): unknown[] => [...memo()],\n count: (): number => memo().length,\n map: <U>(fn: (leaf: unknown, index: number) => U): U[] =>\n memo().map((leaf, index) => untrack(() => fn(leaf, index))),\n forEach: (fn: (leaf: unknown, index: number) => void): void => {\n memo().forEach((leaf, index) => {\n untrack(() => fn(leaf, index));\n });\n },\n only: (): unknown => {\n const leaves = memo();\n if (leaves.length !== 1) {\n throw new TypeError(\n __DEV__\n ? `children().only(): expected one child, received ${leaves.length}`\n :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BA,SAAgBC,EAAS,EAAqC,CAC5D,IAAMC,EAAOC,MAAcV,EAAgBI,CAAE,EAAG,CAAE,YAAa,EAAK,CAAC,EAMrE,OAAO,OAAO,WALkB,CAC9B,IAAMH,EAASQ,EAAK,EAEpB,OADIR,EAAO,SAAW,EAAUA,EAAO,GAChCA,EAAO,SAAW,EAAI,IAAA,GAAYA,CAC3C,EAC+B,CAC7B,YAA0B,CAAC,GAAGQ,EAAK,CAAC,EACpC,UAAqBA,EAAK,CAAC,CAAC,OAC5B,IAAS,GACPA,EAAK,CAAC,CAAC,KAAK,EAAM,IAAUE,MAAcP,EAAGQ,EAAMxC,CAAK,CAAC,CAAC,EAC5D,QAAU,GAAqD,CAC7DqC,EAAK,CAAC,CAAC,SAAS,EAAM,IAAU,CAC9BE,MAAcP,EAAGQ,EAAMxC,CAAK,CAAC,CAC/B,CAAC,CACH,EACA,SAAqB,CACnB,IAAM6B,EAASQ,EAAK,EACpB,GAAIR,EAAO,SAAW,EACpB,MAAU,UAGJ,sBACN,EAEF,OAAOA,EAAO,EAChB,CACF,CAAC,CACH,C"}
@@ -0,0 +1,2 @@
1
+ import{untrack as e}from"./ownership.js";import{disposeTree as t}from"./internal/dispose.js";import{createComputation as n,createOwner as r,currentOwner as i,runInScope as a}from"./extend/index.js";function o(o){let s=i(),c=null;return i=>{c!==null&&t(c);let l=r(s);c=l;let u=!0;a({owner:l,listener:null},()=>{n({kind:`effect`,render:!0,owner:l,fn:()=>{u?(u=!1,i()):e(o)}})})}}export{o as useReaction};
2
+ //# sourceMappingURL=reaction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reaction.js","names":["useReaction","owner","currentOwner","scope","disposeTree","next","createOwner","tracking","runInScope","createComputation","track","untrack","onInvalidate"],"sources":["../../src/reaction.ts"],"sourcesContent":["import {\n createComputation,\n createOwner,\n currentOwner,\n disposeOwner,\n type Owner,\n runInScope,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Creates a tracker that reports the first change of what it reads. `useReaction(onInvalidate)`\n * returns `track(fn)`: `fn` runs at once (synchronously) and the signals it reads are recorded.\n * The first change of any of them calls `onInvalidate` once, untracked, and then nothing is\n * observed until `track` is called again. The ShadowJS form of Solid's `createReaction`.\n *\n * Use it when the work that follows a change is not a pure rerun of `fn` (for example, re-fetching\n * after a change and then deciding what to track next). For ordinary effects use `useEffect`.\n *\n * @param onInvalidate Called once, untracked, after a change of a tracked read.\n * @returns `track(fn)`. Each call replaces the previous tracking. Tracking lives in a child of the\n * owner that called `useReaction`, so it stops when that owner is disposed.\n * @example\n * import { useReaction, useSignal } from \"@shadow-js/core\";\n *\n * function Results() {\n * const [filters] = useSignal({ query: \"\" });\n * const [stale, setStale] = useSignal(false);\n * const track = useReaction(() => setStale(true));\n * track(() => filters()); // the first change of filters marks the results stale\n * return <p>{stale() ? \"Refresh to update\" : \"Up to date\"}</p>;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useReaction(onInvalidate: () => void): (track: () => void) => void {\n const owner = currentOwner();\n let scope: Owner | null = null;\n return (track: () => void): void => {\n if (scope !== null) disposeOwner(scope);\n const next = createOwner(owner);\n scope = next;\n let tracking = true;\n runInScope({ owner: next, listener: null }, () => {\n createComputation({\n kind: \"effect\",\n render: true,\n owner: next,\n fn: () => {\n if (tracking) {\n tracking = false;\n track();\n return undefined;\n }\n untrack(onInvalidate);\n return undefined;\n },\n });\n });\n };\n}\n"],"mappings":"A,sMAmCA,SAAgBA,EAAY,EAAuD,CACjF,IAAMC,EAAQC,EAAa,EACvBC,EAAsB,KAC1B,MAAQ,IAA4B,CAC9BA,IAAU,MAAMC,EAAaD,CAAK,EACtC,IAAME,EAAOC,EAAYL,CAAK,EAC9B,EAAQI,EACR,IAAIE,EAAW,GACfC,EAAW,CAAE,MAAOH,EAAM,SAAU,IAAK,MAAS,CAChDI,EAAkB,CAChB,KAAM,SACN,OAAQ,GACR,MAAOJ,EACP,OAAU,CACJE,GACF,EAAW,GACXG,EAAM,GAGRC,EAAQC,CAAY,CAEtB,CACF,CAAC,CACH,CAAC,CACH,CACF,C"}
@@ -0,0 +1,2 @@
1
+ import{useSignal as e}from"./signal.js";function t(t,n,r){let[i,a]=e(n,{equals:r?.equals??Object.is,...r?.name===void 0?{}:{name:r.name}});return[i,e=>{a(n=>t(n,e))}]}export{t as useReducer};
2
+ //# sourceMappingURL=reducer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reducer.js","names":["useReducer","state","setState","useSignal","initialState","options","reducer","previous","action"],"sources":["../../src/reducer.ts"],"sourcesContent":["import type { Accessor, Equals } from \"./extend\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useReducer}. @since 1.0.0 */\nexport interface ReducerOptions {\n /**\n * Decides whether a new state is a change: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the state is unnamed)\n */\n name?: string;\n}\n\n/**\n * A state cell whose writes go through a reducer: `dispatch(action)` stores\n * `reducer(state, action)`. Equivalent to `useSignal` with the transition written in one place,\n * which keeps every state change of a complex value (a form, a queue) in one function. Reads are\n * fresh immediately after `dispatch`, like every write.\n *\n * @param reducer Pure function `(state, action) => next`.\n * @param initialState Starting state, stored as is.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns `[state, dispatch]`; `state()` tracks, `dispatch(action)` returns nothing. The reducer\n * runs untracked, once per dispatch.\n * @throws ShadowError `WRITE_IN_MEMO` from `dispatch`, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `dispatch` also rethrows what the reducer throws.\n * @example\n * import { useReducer } from \"@shadow-js/core\";\n *\n * type Action = \"inc\" | \"dec\";\n * const [count, dispatch] = useReducer((n: number, a: Action) => (a === \"inc\" ? n + 1 : n - 1), 0);\n * dispatch(\"inc\");\n * console.log(count()); // 1\n * @see useSignal\n * @since 1.0.0\n */\nexport function useReducer<S, A>(\n reducer: (state: S, action: A) => S,\n initialState: S,\n options?: ReducerOptions,\n): [Accessor<S>, (action: A) => void] {\n const [state, setState] = useSignal<S>(initialState, {\n equals: (options?.equals ?? Object.is) as Equals<S>,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n const dispatch = (action: A): void => {\n setState((previous) => reducer(previous, action));\n };\n return [state, dispatch];\n}\n"],"mappings":"A,wCAwCA,SAAgBA,EACd,EACA,EACA,EACoC,CACpC,GAAM,CAACC,EAAOC,GAAYC,EAAaC,EAAc,CACnD,OAASC,GAAS,QAAU,OAAO,GACnC,GAAIA,GAAS,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAMA,EAAQ,IAAK,CAC9D,CAAC,EAID,MAAO,CAACJ,EAHU,GAAoB,CACpCC,EAAU,GAAaI,EAAQC,EAAUC,CAAM,CAAC,CAClD,CACuB,CACzB,C"}
@@ -0,0 +1,2 @@
1
+ import{onCleanup as e,untrack as t}from"./ownership.js";function n(){let e,t=(t=>{e=t});return Object.defineProperty(t,"current",{get:()=>e,enumerable:!0}),t}function r(n,r){n!=null&&(n(t(r)),e(()=>n(void 0)))}export{n as createRef,r as useImperativeHandle};
2
+ //# sourceMappingURL=refs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refs.js","names":["createRef","current","ref","value","useImperativeHandle","untrack","create","onCleanup"],"sources":["../../src/refs.ts"],"sourcesContent":["import { onCleanup, untrack } from \"./ownership\";\n\n/**\n * A ref object that is also a ref callback: pass it as `ref={r}` (the renderer calls it with the\n * element) and read the element as `r.current`. `undefined` when nothing is attached.\n * @since 1.0.0\n */\nexport interface Ref<T> {\n /** Stores `value` as `current`; `undefined` clears it. The renderer calls it with the element. */\n (value: T | undefined): void;\n /** The value last passed to the ref, or `undefined` when nothing is attached. Not reactive. */\n readonly current: T | undefined;\n}\n\n/**\n * Creates a {@link Ref}. Calling it with a value stores the value; calling it with `undefined`\n * clears it. The same object works as a plain ref callback, so no `forwardRef` is needed.\n * @returns A callable ref with a `current` getter, `undefined` until the ref is called.\n * @example\n * import { createRef } from \"@shadow-js/core\";\n *\n * function SearchBox() {\n * const input = createRef<HTMLInputElement>();\n * return <input ref={input} onKeyDown={() => input.current?.select()} />;\n * }\n * @see useImperativeHandle\n * @since 1.0.0\n */\nexport function createRef<T>(): Ref<T> {\n let current: T | undefined;\n const ref = ((value: T | undefined): void => {\n current = value;\n }) as Ref<T>;\n Object.defineProperty(ref, \"current\", { get: () => current, enumerable: true });\n return ref;\n}\n\n/**\n * Publishes an imperative handle to a ref: `create()` runs once, untracked, and its result is\n * passed to `ref`; when the owner is disposed `ref` receives `undefined`. Components run once, so\n * the handle never needs refreshing: put live state behind accessors inside the handle.\n *\n * A missing `ref` is accepted and `create` does not run, so forwarding an optional ref needs no\n * branch.\n *\n * @param ref The ref callback (a {@link Ref}, or any function of the handle). `null` or `undefined`\n * makes the call a no-op.\n * @param create Builds the handle. Runs once, untracked.\n * @example\n * import { createRef, useImperativeHandle } from \"@shadow-js/core\";\n *\n * function FancyInput(props: { ref?: (handle: { focus(): void } | undefined) => void }) {\n * const input = createRef<HTMLInputElement>();\n * useImperativeHandle(props.ref, () => ({ focus: () => input.current?.focus() }));\n * return <input ref={input} />;\n * }\n * @see createRef\n * @since 1.0.0\n */\nexport function useImperativeHandle<T>(\n ref: ((value: T | undefined) => void) | null | undefined,\n create: () => T,\n): void {\n if (ref === undefined || ref === null) return;\n ref(untrack(create));\n onCleanup(() => ref(undefined));\n}\n"],"mappings":"A,wDA4BA,SAAgBA,GAAuB,CACrC,IAAIC,EACEC,GAAQ,GAA+B,CAC3C,EAAUC,CACZ,GAEA,OADA,OAAO,eAAeD,EAAK,UAAW,CAAE,QAAWD,EAAS,WAAY,EAAK,CAAC,EACvEC,CACT,CAwBA,SAAgBE,EACd,EACA,EACM,CACFF,GAA6B,OACjCA,EAAIG,EAAQC,CAAM,CAAC,EACnBC,MAAgBL,EAAI,IAAA,EAAS,CAAC,EAChC,C"}
@@ -0,0 +1,2 @@
1
+ import{readSignal as e}from"./internal/graph.js";import{batch as t}from"./internal/scheduler.js";import{onCleanup as n,untrack as r}from"./ownership.js";import{useContext as i}from"./context.js";import{ResourceCacheContext as a,SuspenseContext as o}from"./suspense.js";import{holdReader as s,inTransition as c}from"./internal/concurrency.js";import{createSignalNode as l,currentListener as u,writeSignal as d}from"./extend/index.js";function f(t,n){let r=l(t,n?Object.is:!1);return[()=>e(r),e=>{d(r,e,{allowInMemo:!0})}]}function p(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function m(e,l,d){let m=typeof l==`function`,h=m?typeof e==`function`?e:()=>e:()=>!0,g=e,_=m?l:(e,t)=>g(t),v=(m?d:l)??{},y=`initialValue`in v,[b,x]=f(v.initialValue,!1),[S,C]=f(y?`ready`:`unresolved`,!0),w=e=>{C(e)},[T,E]=f(void 0,!1),D=i(a),O=D===null?void 0:D.key(v.key),k=D!==null&&O!==void 0?D.read(O):void 0,A=!1,j=0,M,N=!1,P=y,F=/* @__PURE__ */ new Set,I=()=>{if(F.size===0)return;let e=[...F];F.clear();for(let t of e)t.decrement()},L=(e,n)=>N||e!==j?!1:(t(n),I(),!0),R=(e,n)=>{if(k!==void 0&&!A&&!n)return A=!0,P=!0,t(()=>{x(k.value),w(`ready`)}),Promise.resolve(k.value);M?.abort();let i=new AbortController;M=i,j+=1;let a=j;t(()=>{w(P?`refreshing`:`pending`),E(void 0)});let o;try{let t=n||D===null||O===void 0?void 0:D.pending?.(O);o=t===void 0?r(()=>_(e,{signal:i.signal,refetching:n,value:r(b)})):t}catch(e){return L(a,()=>{E(e),w(`errored`)}),Promise.resolve(void 0)}if(p(o))return D!==null&&O!==void 0&&D.track(O,Promise.resolve(o),{deferStream:v.deferStream}),Promise.resolve(o).then(e=>L(a,()=>{P=!0,x(e),w(`ready`)})?e:void 0,e=>{L(a,()=>{E(e),w(`errored`)})});let s=o,c=L(a,()=>{P=!0,x(s),w(`ready`)});return Promise.resolve(c?s:void 0)},z=e=>{e===!1||e==null?(M?.abort(),j+=1,I(),w(P?`ready`:`unresolved`)):R(e,P)},B=(()=>{let e=S();if(e===`errored`)throw T();if(e===`pending`){let e=i(o);e!==null&&!F.has(e)&&(F.add(e),e.increment()),e!==null&&u()!==null&&c()&&s(e)}return b()});return Object.defineProperties(B,{state:{get:S},loading:{get:()=>S()===`pending`||S()===`refreshing`},error:{get:T},latest:{get:b},refetch:{value:()=>{let e=r(h);return e===!1||e==null?Promise.resolve(void 0):R(e,P)}},mutate:{value:e=>{let n;return t(()=>{n=typeof e==`function`?e(r(b)):e,M?.abort(),j+=1,P=!0,x(n),E(void 0),w(`ready`)}),I(),n}}}),z(r(h)),n(()=>{N=!0,M?.abort(),I()}),B}export{m as useResource};
2
+ //# sourceMappingURL=resource.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource.js","names":["cell","node","createSignalNode","initial","distinct","readSignal","writeSignal","next","isPromiseLike","value","useResource","hasSource","second","source","first","oneShot","fetcher","info","options","third","hasInitial","setValue","state","writeState","setState","failure","setFailure","cache","useContext","ResourceCacheContext","cacheKey","cached","usedCache","version","controller","disposed","hasValue","holders","release","held","tracker","settle","id","batch","apply","load","refetching","current","output","joined","untrack","input","error","result","immediate","applied","onSource","read","SuspenseContext","currentListener","inTransition","holdReader","resolved","onCleanup"],"sources":["../../src/resource.ts"],"sourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n createSignalNode,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = createSignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n batch(apply);\n release();\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? (next as (previous: T | undefined) => T)(untrack(value))\n : next;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n release();\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n release();\n });\n return read;\n}\n"],"mappings":"A,ibAkGA,SAASA,EAAQ,EAAY,EAAqD,CAChF,IAAMC,EAAOC,EAAoBC,EAASC,EAAW,OAAO,GAAK,EAAK,EACtE,MAAO,KACCC,EAAWJ,CAAI,EACpB,GAAS,CACRK,EAAYL,EAAMM,EAAM,CAAE,YAAa,EAAK,CAAC,CAC/C,CACF,CACF,CAEA,SAASC,EAAiB,EAAyC,CACjE,OACEC,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAC/C,OAAQA,EAA6B,MAAS,UAElD,CAiFA,SAAgB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AQ,CACtB,EACMqB,OAAc,CAClB,IAAMV,EAAUzB,EAAM,EACtB,GAAIyB,IAAY,UAAW,MAAMtB,EAAQ,EACzC,GAAIsB,IAAY,UAAW,CACzB,IAAMP,EAAUZ,EAAW8B,CAAe,EACtClB,IAAY,MAAQ,CAACH,EAAQ,IAAIG,CAAO,IAC1CH,EAAQ,IAAIG,CAAO,EACnBA,EAAQ,UAAU,GAIhBA,IAAY,MAAQmB,EAAgB,IAAM,MAAQC,EAAa,GAAGC,EAAWrB,CAAO,CAC1F,CACA,OAAO/B,EAAM,CACf,GAgDA,OA9CA,OAAO,iBAAiBgD,EAAM,CAC5B,MAAO,CAAE,IAAKnC,CAAM,EACpB,QAAS,CAAE,QAAWA,EAAM,IAAM,WAAaA,EAAM,IAAM,YAAa,EACxE,MAAO,CAAE,IAAKG,CAAQ,EACtB,OAAQ,CAAE,IAAKhB,CAAM,EACrB,QAAS,CACP,UAAqC,CACnC,IAAM0C,EAAQD,EAAQrC,CAAM,EAI5B,OAHIsC,IAAU,IAASA,GAAU,KACxB,QAAQ,QAAQ,IAAA,EAAS,EAE3BN,EAAKM,EAAOf,CAAQ,CAC7B,CACF,EACA,OAAQ,CACN,MAAQ,GAAkD,CACxD,IAAI0B,EAcJ,OAbAnB,MAAY,CACV,EACE,OAAOpC,GAAS,WACXA,EAAwC2C,EAAQzC,CAAK,CAAC,EACvDF,EACN2B,GAAY,MAAM,EAClB,GAAW,EACX,EAAW,GACXb,EAASyC,CAAa,EACtBpC,EAAW,IAAA,EAAS,EACpBF,EAAS,OAAO,CAClB,CAAC,EACDc,EAAQ,EACDwB,CACT,CACF,CACF,CAAC,EAMeN,EAASN,EAAQrC,CAAM,CAAC,EAExCkD,MAAgB,CACd,EAAW,GACX7B,GAAY,MAAM,EAClBI,EAAQ,CACV,CAAC,EACMmB,CACT,C"}
@@ -0,0 +1,2 @@
1
+ import{track as e}from"./internal/graph.js";import{onCleanup as t,untrack as n}from"./ownership.js";import"./effect.js";import{isTracking as r}from"./extend/index.js";var i=class{kind=0;observers=null;stamp=0;subscribers=0;key;value;constructor(e,t){this.key=e,this.value=t}};function a(a,o){let s=/* @__PURE__ */ new Map,c=(e,t)=>o===void 0?e===t:o(e,t),l=()=>n(a),u=e=>{--e.subscribers,e.subscribers===0&&s.get(e.key)===e&&s.delete(e.key)},d=e=>{let t=new i(e,c(e,l()));return s.set(e,t),t};return n=>{if(!r())return c(n,a());let i=s.get(n)??d(n);return i.subscribers+=1,t(()=>u(i)),e(i),i.value}}export{a as useSelector};
2
+ //# sourceMappingURL=selector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"selector.js","names":["Entry","key","value","useSelector","entries","matches","equals","currentValue","untrack","source","release","entry","create","isTracking","onCleanup","track"],"sources":["../../src/selector.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { isTracking, notify, type SourceNode, track } from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\n\n/**\n * The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the\n * shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.\n */\nclass Entry implements SourceNode {\n /** A source with no sources of its own, like a signal. */\n readonly kind = 0;\n observers: SourceNode[\"observers\"] = null;\n stamp = 0;\n /** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */\n subscribers = 0;\n\n /** The key this entry answers for. */\n readonly key: unknown;\n /** Whether the key matches the selected value. */\n value: boolean;\n\n constructor(key: unknown, value: boolean) {\n this.key = key;\n this.value = value;\n }\n}\n\n/** Writes a key's boolean and notifies its readers only when it actually changed. */\nfunction setEntry(entry: Entry, selected: boolean): void {\n if (entry.value === selected) return;\n entry.value = selected;\n notify(entry);\n}\n\n/**\n * Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the\n * current source value. Reading it inside an effect or memo subscribes only to that key's boolean,\n * so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the\n * default equality. A custom `equals` costs one call per registered key per change.\n *\n * The source is tracked by a render-phase effect in the current owner. Create the selector before\n * its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked\n * context reads the source directly and creates no subscription. The default equality is `===`,\n * so `NaN` never matches.\n *\n * @param source The value that selects keys. Tracked.\n * @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.\n * @returns `isSelected(key)`.\n * @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still\n * updated and the error goes to the owner's error handler. In development, a selector created\n * outside any owner warns `NO_OWNER_EFFECT`.\n * @example\n * import { mapArray, useSelector, useSignal } from \"@shadow-js/core\";\n *\n * function Rows(props: { ids: number[] }) {\n * const [selectedId, setSelectedId] = useSignal(1);\n * const isSelected = useSelector(selectedId);\n * return mapArray(() => props.ids, (id) => (\n * <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>\n * ));\n * }\n * @see mapArray\n * @since 1.0.0\n */\nexport function useSelector<T, K = T>(\n source: () => T,\n equals?: (key: K, value: T) => boolean,\n): (key: K) => boolean {\n const entries = new Map<unknown, Entry>();\n /** The value the entries were last reconciled against; `null` until the first successful apply. */\n let last: { readonly value: T } | null = null;\n\n const matches = (key: K, value: T): boolean =>\n equals === undefined ? (key as unknown) === value : equals(key, value);\n\n const currentValue = (): T => (last === null ? untrack(source) : last.value);\n\n const release = (entry: Entry): void => {\n entry.subscribers -= 1;\n if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);\n };\n\n const create = (key: K): Entry => {\n const entry = new Entry(key, matches(key, currentValue()));\n entries.set(key, entry);\n return entry;\n };\n\n const isSelected = (key: K): boolean => {\n if (!isTracking()) return matches(key, source());\n const entry = entries.get(key) ?? create(key);\n entry.subscribers += 1;\n onCleanup(() => release(entry));\n track(entry);\n return entry.value;\n };\n\n useRenderEffect(\n () => source(),\n (next) => {\n const previous = last;\n last = { value: next };\n if (previous !== null && equals === undefined) {\n // Default equality: only the entries for the previous and the next key can change.\n if (previous.value === next) return;\n const before = entries.get(previous.value);\n if (before !== undefined) setEntry(before, before.key === next);\n const after = entries.get(next);\n if (after !== undefined) setEntry(after, after.key === next);\n return;\n }\n // Custom equality, or the first successful value: every registered key is checked. A\n // failing equals does not stop the others; its error is rethrown once they are all updated.\n let failed = false;\n let failure: unknown;\n for (const entry of entries.values()) {\n let selected: boolean;\n try {\n selected = matches(entry.key as K, next);\n } catch (error) {\n if (!failed) {\n failed = true;\n failure = error;\n }\n continue;\n }\n setEntry(entry, selected);\n }\n if (failed) throw failure;\n },\n );\n\n return isSelected;\n}\n"],"mappings":"A,uKAQA,IAAMA,EAAN,KAAkC,CAEhC,KAAgB,EAChB,UAAqC,KACrC,MAAQ,EAER,YAAc,EAGd,IAEA,MAEA,YAAY,EAAc,EAAgB,CACxC,KAAK,IAAMC,EACX,KAAK,MAAQC,CACf,CACF,EAuCA,SAAgBC,EACd,EACA,EACqB,CACrB,IAAMC,kBAAU,IAAI,IAIdC,GAAW,EAAQ,IACvBC,IAAW,IAAA,GAAaL,IAAoBC,EAAQI,EAAOL,EAAKC,CAAK,EAEjEK,MAAyCC,EAAQC,CAAM,EAEvDC,EAAW,GAAuB,CACtC,IAAM,YACFC,EAAM,cAAgB,GAAKP,EAAQ,IAAIO,EAAM,GAAG,IAAMA,GAAOP,EAAQ,OAAOO,EAAM,GAAG,CAC3F,EAEMC,EAAU,GAAkB,CAChC,IAAMD,EAAQ,IAAIX,EAAMC,EAAKI,EAAQJ,EAAKM,EAAa,CAAC,CAAC,EAEzD,OADAH,EAAQ,IAAIH,EAAKU,CAAK,EACfA,CACT,EA8CA,MA5CoB,IAAoB,CACtC,GAAI,CAACE,EAAW,EAAG,OAAOR,EAAQJ,EAAKQ,EAAO,CAAC,EAC/C,IAAME,EAAQP,EAAQ,IAAIH,CAAG,GAAKW,EAAOX,CAAG,EAI5C,MAHA,GAAM,aAAe,EACrBa,MAAgBJ,EAAQC,CAAK,CAAC,EAC9BI,EAAMJ,CAAK,EACJA,EAAM,KACf,CAsCF,C"}
@@ -0,0 +1,2 @@
1
+ import{readSignal as e}from"./internal/graph.js";import{untrack as t}from"./ownership.js";import{createSignalNode as n,writeSignal as r}from"./extend/index.js";function i(i,a){let o=a?.equals===void 0?Object.is:a.equals,s=n(i,o,a?.name);return[()=>e(s),(e=>{let n=typeof e==`function`?t(()=>e(s.value)):e;return r(s,n),n})]}export{i as useSignal};
2
+ //# sourceMappingURL=signal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signal.js","names":["useSignal","equals","options","signal","createSignalNode","value","readSignal","resolved","next","untrack","writeSignal"],"sources":["../../src/signal.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n type Equals,\n readSignal,\n type Setter,\n writeSignal,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useSignal}.\n * @since 1.0.0\n */\nexport interface SignalOptions<T> {\n /**\n * Decides whether a write is a change: readers are notified only when it returns `false`.\n * `false` notifies on every write, even of the same value.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name?: string;\n}\n\n/**\n * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads\n * inside effects and memos subscribe them; writes notify them. Works at module scope.\n *\n * @param value Initial value.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs\n * untracked, and returns the value it stored.\n * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is\n * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * setCount((n) => n + 1);\n * console.log(count()); // 1\n * @see useStore\n * @see useMemo\n * @since 1.0.0\n */\nexport function useSignal<T>(value: T, options?: SignalOptions<T>): [Accessor<T>, Setter<T>] {\n const equals: Equals<T> = options?.equals === undefined ? Object.is : options.equals;\n const signal = createSignalNode<T>(value, equals, options?.name);\n const read: Accessor<T> = () => readSignal(signal);\n const write = ((next: unknown) => {\n const resolved = (\n typeof next === \"function\" ? untrack(() => (next as (prev: T) => T)(signal.value)) : next\n ) as T;\n writeSignal(signal, resolved);\n return resolved;\n }) as Setter<T>;\n return [read, write];\n}\n"],"mappings":"A,gKAgDA,SAAgBA,EAAa,EAAU,EAAsD,CAC3F,IAAMC,EAAoBC,GAAS,SAAW,IAAA,GAAY,OAAO,GAAKA,EAAQ,OACxEC,EAASC,EAAoBC,EAAOJ,EAAQC,GAAS,IAAI,EAS/D,MAAO,KARyBI,EAAWH,CAAM,GACjC,GAAkB,CAChC,IAAMI,EACJ,OAAOC,GAAS,WAAaC,MAAeD,EAAwBL,EAAO,KAAK,CAAC,EAAIK,EAGvF,OADAE,EAAYP,EAAQI,CAAQ,EACrBA,CACT,EACmB,CACrB,C"}
@@ -0,0 +1 @@
1
+ import{snapshot as e,unwrap as t}from"./read.js";import{produce as n,reconcile as r}from"./reconcile.js";import{useStore as i}from"./use-store.js";export{n as produce,r as reconcile,e as snapshot,t as unwrap,i as useStore};
@@ -0,0 +1,2 @@
1
+ import{track as e}from"../internal/graph.js";import{createSignalNode as t,isTracking as n,notify as r}from"../extend/index.js";const i=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),a=/* @__PURE__ */ new WeakMap,o=/* @__PURE__ */ new WeakMap;function s(e){return i.has(e)}function c(e){if(typeof e!=`object`||!e)return!1;if(Array.isArray(e))return!0;if(e===Object.prototype)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function l(e){return typeof e!=`object`||!e?e:o.get(e)??e}function u(e){let t=/* @__PURE__ */ new Set([e]),n=[e];for(;n.length>0;){let e=n.pop();for(let r of Object.keys(e)){let i=Reflect.get(e,r);if(typeof i==`object`&&i){if(o.has(i))return!0;c(i)&&!t.has(i)&&(t.add(i),n.push(i))}}}return!1}function d(e){let t=l(e);if(t!==e||!c(t)||!u(t))return t;let n=/* @__PURE__ */ new Map,r=e=>{let t=n.get(e);if(t!==void 0)return t;let r=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return n.set(e,r),r},i=r(t),a=[t];for(let e=0;e<a.length;e+=1){let t=a[e],i=n.get(t);for(let e of Object.keys(t)){let s=Reflect.get(t,e);if(typeof s==`object`&&s){let i=o.get(s);if(i!==void 0)s=i;else if(c(s)){let i=n.has(s);s=r(s),i||a.push(Reflect.get(t,e))}}Object.defineProperty(i,e,{value:s,enumerable:!0,writable:!0,configurable:!0})}}return i}function f(e,t){return Reflect.get(e,t)}function p(e){let t=a.get(e);return t===void 0&&(t={signals:null,keys:null,proxy:null},a.set(e,t)),t}function m(e,n){let r=e.signals;r===null&&(r=/* @__PURE__ */ new Map,e.signals=r);let i=r.get(n);return i===void 0&&(i=t(0,!1),r.set(n,i)),i}function h(t,r){n()&&e(m(t,r))}function g(r){n()&&(r.keys===null&&(r.keys=t(0,!1)),e(r.keys))}function _(e){e!=null&&r(e)}function v(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&String(t)===e}function y(e,t){let n=e.signals;if(n!==null)for(let[e,r]of n)v(e)&&Number(e)>=t&&_(r)}function b(e,t,n){if(s(t))throw TypeError(`SHADOW_STORE_RESERVED_KEY`);n=d(n);let r=Array.isArray(e),i=Object.hasOwn(e,t);if(i&&Object.is(f(e,t),n))return!1;let o=r?e.length:0;if(!Reflect.set(e,t,n))throw TypeError(`SHADOW_STORE_PROP_READ_ONLY`);let c=a.get(e);if(c===void 0)return!0;if(_(c.signals?.get(t)),i||_(c.keys),r){let t=e.length;t!==o&&(_(c.signals?.get(`length`)),_(c.keys),t<o&&y(c,t))}return!0}function x(e,t){if(s(t))throw TypeError(`SHADOW_STORE_RESERVED_DELETE`);if(!Object.hasOwn(e,t))return!0;if(!Reflect.deleteProperty(e,t))throw TypeError(`SHADOW_STORE_DELETE`);let n=a.get(e);return n===void 0||(_(n.signals?.get(t)),_(n.keys)),!0}export{a as NODES,o as RAW,x as deleteRaw,s as isReservedKey,c as isWrappable,p as nodeOf,f as readRaw,g as trackKeys,h as trackProperty,d as unwrapDeep,l as unwrapValue,b as writeRaw};
2
+ //# sourceMappingURL=nodes.js.map