@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":"nodes.js","names":["notify$1","RESERVED_KEYS","NODES","RAW","isReservedKey","key","isWrappable","value","prototype","unwrapValue","containsProxy","seen","root","stack","container","member","unwrapDeep","first","copies","copyOf","existing","source","made","rootCopy","queue","head","target","raw","known","readRaw","nodeOf","node","signalFor","signals","signal","createSignalNode","trackProperty","isTracking","track","trackKeys","notify","isIndexKey","index","notifyIndicesFrom","from","writeRaw","array","had","before","after","deleteRaw"],"sources":["../../../src/store/nodes.ts"],"sourcesContent":["import {\n createSignalNode,\n isTracking,\n notify as notifySource,\n type SignalNode,\n track,\n} from \"../extend\";\n\n/** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */\nconst RESERVED_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * Tracking state of one plain object or array. Signals are created lazily, on the first read made\n * inside a tracked computation, so untracked data costs one small record per object.\n */\nexport interface NodeState {\n /** One signal per property read in a tracked context, keyed by property name. */\n signals: Map<string, SignalNode<number>> | null;\n /** Notified when a property is added or removed, or an array changes length. */\n keys: SignalNode<number> | null;\n /** The read-only proxy for this object, created on first read. */\n proxy: object | null;\n}\n\n/** Raw object -> its tracking state. Keys are the raw data, so nothing is stamped on user objects. */\nexport const NODES: WeakMap<object, NodeState> = new WeakMap();\n\n/** Any store proxy (read-only or draft) -> the raw object it wraps. */\nexport const RAW: WeakMap<object, object> = new WeakMap();\n\n/** True for the keys that must never be written as own properties. */\nexport function isReservedKey(key: string): boolean {\n return RESERVED_KEYS.has(key);\n}\n\n/** True for the values the store wraps: plain objects (null or Object.prototype) and arrays. */\nexport function isWrappable(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n if (Array.isArray(value)) return true;\n if (value === Object.prototype) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Replaces a store proxy by the raw object it wraps; any other value is returned as is. */\nexport function unwrapValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n return RAW.get(value) ?? value;\n}\n\n/** True when a store proxy (draft or read-only view) sits anywhere inside the plain data `root`. */\nfunction containsProxy(root: object): boolean {\n const seen = new Set<object>([root]);\n const stack: object[] = [root];\n while (stack.length > 0) {\n const container = stack.pop() as object;\n for (const key of Object.keys(container)) {\n const member: unknown = Reflect.get(container, key);\n if (typeof member !== \"object\" || member === null) continue;\n if (RAW.has(member)) return true;\n if (isWrappable(member) && !seen.has(member)) {\n seen.add(member);\n stack.push(member);\n }\n }\n }\n return false;\n}\n\n/**\n * Like {@link unwrapValue}, and also for proxies hidden inside plain data: `draft.todos =\n * draft.todos.filter(...)` assigns an array whose members are drafts, and a draft stored in the\n * data would throw on its next use. Data without proxies is returned as is; otherwise a copy with\n * every proxy replaced by its raw object. Iterative, so nesting depth is not limited by the stack.\n */\nexport function unwrapDeep(value: unknown): unknown {\n const first = unwrapValue(value);\n if (first !== value || !isWrappable(first) || !containsProxy(first)) return first;\n const copies = new Map<object, object>();\n const copyOf = (source: object): object => {\n const existing = copies.get(source);\n if (existing !== undefined) return existing;\n const made: object = Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));\n copies.set(source, made);\n return made;\n };\n const rootCopy = copyOf(first);\n const queue: object[] = [first];\n for (let head = 0; head < queue.length; head += 1) {\n const source = queue[head] as object;\n const target = copies.get(source) as object;\n for (const key of Object.keys(source)) {\n let member: unknown = Reflect.get(source, key);\n if (typeof member === \"object\" && member !== null) {\n const raw = RAW.get(member);\n if (raw !== undefined) member = raw;\n else if (isWrappable(member)) {\n const known = copies.has(member);\n member = copyOf(member);\n if (!known) queue.push(Reflect.get(source, key) as object);\n }\n }\n Object.defineProperty(target, key, {\n value: member,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n return rootCopy;\n}\n\n/** Reads an own or inherited property without tracking and without invoking proxies. */\nexport function readRaw(target: object, key: string): unknown {\n return Reflect.get(target, key);\n}\n\n/** Returns the tracking state of `raw`, creating an empty one on first use. */\nexport function nodeOf(raw: object): NodeState {\n let node = NODES.get(raw);\n if (node === undefined) {\n node = { signals: null, keys: null, proxy: null };\n NODES.set(raw, node);\n }\n return node;\n}\n\nfunction signalFor(node: NodeState, key: string): SignalNode<number> {\n let signals = node.signals;\n if (signals === null) {\n signals = new Map();\n node.signals = signals;\n }\n let signal = signals.get(key);\n if (signal === undefined) {\n signal = createSignalNode(0, false);\n signals.set(key, signal);\n }\n return signal;\n}\n\n/** Subscribes the running computation (if any) to one property of the object. */\nexport function trackProperty(node: NodeState, key: string): void {\n if (!isTracking()) return;\n track(signalFor(node, key));\n}\n\n/** Subscribes the running computation (if any) to the key set of the object. */\nexport function trackKeys(node: NodeState): void {\n if (!isTracking()) return;\n if (node.keys === null) node.keys = createSignalNode(0, false);\n track(node.keys);\n}\n\n/**\n * Notifies the observers of one signal. The same engine steps as a signal write: mark the\n * observers dirty, then request a flush (which the surrounding batch defers).\n */\nfunction notify(signal: SignalNode<number> | null | undefined): void {\n if (signal === undefined || signal === null) return;\n notifySource(signal);\n}\n\nfunction isIndexKey(key: string): boolean {\n const index = Number(key);\n return Number.isInteger(index) && index >= 0 && String(index) === key;\n}\n\n/** Notifies the index signals of an array at or beyond `from` (used when the array shrinks). */\nfunction notifyIndicesFrom(node: NodeState, from: number): void {\n const signals = node.signals;\n if (signals === null) return;\n for (const [key, signal] of signals) {\n if (isIndexKey(key) && Number(key) >= from) notify(signal);\n }\n}\n\n/**\n * Writes one property of a raw object and notifies exactly what changed: the property's signal,\n * the key set when a property appears, and the length when an array's length moves. An equal\n * value (Object.is) writes nothing. Returns whether anything changed.\n */\nexport function writeRaw(target: object, key: string, value: unknown): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n value = unwrapDeep(value);\n const array = Array.isArray(target);\n const had = Object.hasOwn(target, key);\n if (had && Object.is(readRaw(target, key), value)) return false;\n const before = array ? (target as unknown[]).length : 0;\n if (!Reflect.set(target, key, value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: property \"${key}\" is read-only and cannot be written`\n : \"SHADOW_STORE_PROP_READ_ONLY\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n if (!had) notify(node.keys);\n if (array) {\n const after = (target as unknown[]).length;\n if (after !== before) {\n notify(node.signals?.get(\"length\"));\n notify(node.keys);\n if (after < before) notifyIndicesFrom(node, after);\n }\n }\n return true;\n}\n\n/** Deletes one own property of a raw object and notifies its signal and the key set. */\nexport function deleteRaw(target: object, key: string): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be deleted; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_DELETE\",\n );\n }\n if (!Object.hasOwn(target, key)) return true;\n if (!Reflect.deleteProperty(target, key)) {\n throw new TypeError(\n __DEV__ ? `ShadowStore: property \"${key}\" cannot be deleted` : \"SHADOW_STORE_DELETE\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n notify(node.keys);\n return true;\n}\n"],"mappings":"A,+HASA,MAAMC,kBAAqC,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EAgB/EC,kBAAoC,IAAI,QAGxCC,kBAA+B,IAAI,QAGhD,SAAgBC,EAAc,EAAsB,CAClD,OAAOH,EAAc,IAAII,CAAG,CAC9B,CAGA,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AK,IAAI,EACtBe,EAAO,CACT,IAAMG,EAASvB,EAAqB,OAChCuB,IAAUD,IACZR,EAAOT,EAAK,SAAS,IAAI,QAAQ,CAAC,EAClCS,EAAOT,EAAK,IAAI,EACZkB,EAAQD,GAAQL,EAAkBZ,EAAMkB,CAAK,EAErD,CACA,MAAO,EACT,CAGA,SAAgBC,EAAU,EAAgB,EAAsB,CAC9D,GAAI9C,EAAcC,CAAG,EACnB,MAAU,UAGJ,8BACN,EAEF,GAAI,CAAC,OAAO,OAAOqB,EAAQrB,CAAG,EAAG,MAAO,GACxC,GAAI,CAAC,QAAQ,eAAeqB,EAAQrB,CAAG,EACrC,MAAU,UACuD,qBACjE,EAEF,IAAM0B,EAAO7B,EAAM,IAAIwB,CAAM,EAI7B,OAHIK,IAAS,IAAA,KACbS,EAAOT,EAAK,SAAS,IAAI1B,CAAG,CAAC,EAC7BmC,EAAOT,EAAK,IAAI,GACT,EACT,C"}
@@ -0,0 +1,2 @@
1
+ import{RAW as e,deleteRaw as t,isReservedKey as n,isWrappable as r,nodeOf as i,readRaw as a,trackKeys as o,trackProperty as s,unwrapValue as c,writeRaw as l}from"./nodes.js";var u=class{label;open;drafts;handler;constructor(e){this.label=e,this.open=!0,this.drafts=/* @__PURE__ */ new Map,this.handler=_(this)}};function d(e){return typeof e==`symbol`?e.toString():`${e}`,/* @__PURE__ */ TypeError(`SHADOW_STORE_READ_ONLY`)}function f(e,t,n,i){if(!r(n)||!Object.hasOwn(e,t))return n;let a=Reflect.getOwnPropertyDescriptor(e,t);return a!==void 0&&a.configurable===!1&&a.writable===!1?n:i(n)}function p(e,t,n){let i=Reflect.getOwnPropertyDescriptor(e,t);if(i===void 0||typeof t==`symbol`||i.configurable===!1)return i;let a=i.value;return r(a)?{...i,value:n(a)}:i}function m(e,t){return t===`__proto__`&&!Object.hasOwn(e,t)}function h(e,t){for(let n=e;n!==null;n=Object.getPrototypeOf(n)){let e=Reflect.getOwnPropertyDescriptor(n,t);if(e!==void 0)return typeof e.get==`function`}return!1}const g={get(e,t,n){if(typeof t==`symbol`)return Reflect.get(e,t);if(!m(e,t))return s(i(e),t),h(e,t)?Reflect.get(e,t,n):f(e,t,a(e,t),v)},has(e,t){return typeof t!=`symbol`&&s(i(e),t),Reflect.has(e,t)},ownKeys(e){return o(i(e)),Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return p(e,t,v)},set(e,t){throw d(t)},deleteProperty(e,t){throw d(t)},defineProperty(e,t){throw d(t)},setPrototypeOf(){throw d(`[[Prototype]]`)},preventExtensions(){throw d(`[[Extensible]]`)}};function _(e){let r=t=>y(t,e),i=t=>{if(!e.open)throw TypeError(`SHADOW_STORE_DRAFT_STALE`);if(typeof t==`symbol`)throw TypeError(`SHADOW_STORE_SYMBOL_KEY`);return t};return{get(e,t){if(typeof t==`symbol`)return Reflect.get(e,t);if(!m(e,t))return f(e,t,a(e,t),r)},has(e,t){return Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return p(e,t,r)},set(e,t,r){let a=i(t);if(n(a))throw TypeError(`SHADOW_STORE_RESERVED_KEY`);return l(e,a,c(r)),!0},deleteProperty(e,n){return t(e,i(n))},defineProperty(e,t){throw TypeError(`SHADOW_STORE_DEFINE_PROPERTY`)},setPrototypeOf(){throw TypeError(`SHADOW_STORE_PROTOTYPE`)},preventExtensions(){throw TypeError(`SHADOW_STORE_NON_EXTENSIBLE`)}}}function v(t){let n=i(t);if(n.proxy===null){let r=new Proxy(t,g);e.set(r,t),n.proxy=r}return n.proxy}function y(t,n){let r=n.drafts.get(t);if(r!==void 0)return r;let i=new Proxy(t,n.handler);return e.set(i,t),n.drafts.set(t,i),i}export{u as Transaction,y as draftOf,v as readProxyOf};
2
+ //# sourceMappingURL=proxies.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxies.js","names":["Transaction","label","draftHandler","readOnly","key","childOf","isWrappable","value","target","descriptor","wrap","describeChild","hidesPrototype","hasGetter","object","READ_HANDLER","trackProperty","nodeOf","receiver","readRaw","readProxyOf","trackKeys","draftOf","raw","tx","writable","name","isReservedKey","writeRaw","unwrapValue","deleteRaw","node","proxy","RAW","existing"],"sources":["../../../src/store/proxies.ts"],"sourcesContent":["import {\n deleteRaw,\n isReservedKey,\n isWrappable,\n nodeOf,\n RAW,\n readRaw,\n trackKeys,\n trackProperty,\n unwrapValue,\n writeRaw,\n} from \"./nodes\";\n\n/**\n * One `setStore` call. Drafts made for it are cached here, so a draft object keeps its identity\n * inside the update, and they stop accepting writes when the call returns.\n */\nexport class Transaction {\n readonly label: string;\n open: boolean;\n readonly drafts: Map<object, object>;\n readonly handler: ProxyHandler<object>;\n\n constructor(label: string) {\n this.label = label;\n this.open = true;\n this.drafts = new Map();\n this.handler = draftHandler(this);\n }\n}\n\nfunction readOnly(key: string | symbol): TypeError {\n const name = typeof key === \"symbol\" ? key.toString() : `\"${key}\"`;\n return new TypeError(\n __DEV__\n ? `ShadowStore: the store is read-only; ${name} can only be changed inside setStore((draft) => ...)`\n : \"SHADOW_STORE_READ_ONLY\",\n );\n}\n\n/**\n * Returns the value to hand out for `key`: a wrapped object when the value is an own, writable\n * wrappable slot, otherwise the raw value. Frozen slots must return the raw value because a proxy\n * may not report a different value for a non-writable, non-configurable property.\n */\nfunction childOf(\n target: object,\n key: string,\n value: unknown,\n wrap: (raw: object) => object,\n): unknown {\n if (!isWrappable(value) || !Object.hasOwn(target, key)) return value;\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\n if (\n descriptor !== undefined &&\n descriptor.configurable === false &&\n descriptor.writable === false\n ) {\n return value;\n }\n return wrap(value);\n}\n\n/** Descriptor passthrough that wraps the value the same way `get` does. */\nfunction describeChild(\n target: object,\n key: string | symbol,\n wrap: (raw: object) => object,\n): PropertyDescriptor | undefined {\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\n if (descriptor === undefined || typeof key === \"symbol\") return descriptor;\n if (descriptor.configurable === false) return descriptor;\n const value: unknown = descriptor.value;\n if (!isWrappable(value)) return descriptor;\n return { ...descriptor, value: wrap(value) };\n}\n\n/** `__proto__` is only reachable through the prototype chain, so the store never exposes it. */\nfunction hidesPrototype(target: object, key: string): boolean {\n return key === \"__proto__\" && !Object.hasOwn(target, key);\n}\n\n/** True when `key` resolves to an accessor property (own or inherited). */\nfunction hasGetter(target: object, key: string): boolean {\n for (\n let object: object | null = target;\n object !== null;\n object = Object.getPrototypeOf(object)\n ) {\n const descriptor = Reflect.getOwnPropertyDescriptor(object, key);\n if (descriptor !== undefined) return typeof descriptor.get === \"function\";\n }\n return false;\n}\n\n/** Read-only handler: every read subscribes the running computation to the property it touches. */\nconst READ_HANDLER: ProxyHandler<object> = {\n get(target, key, receiver) {\n if (typeof key === \"symbol\") return Reflect.get(target, key);\n if (hidesPrototype(target, key)) return undefined;\n trackProperty(nodeOf(target), key);\n // A getter runs with the store view as `this`, so what it reads is tracked too.\n if (hasGetter(target, key)) return Reflect.get(target, key, receiver);\n return childOf(target, key, readRaw(target, key), readProxyOf);\n },\n has(target, key) {\n if (typeof key !== \"symbol\") trackProperty(nodeOf(target), key);\n return Reflect.has(target, key);\n },\n ownKeys(target) {\n trackKeys(nodeOf(target));\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, key) {\n return describeChild(target, key, readProxyOf);\n },\n set(_target, key) {\n throw readOnly(key);\n },\n deleteProperty(_target, key) {\n throw readOnly(key);\n },\n defineProperty(_target, key) {\n throw readOnly(key);\n },\n setPrototypeOf() {\n throw readOnly(\"[[Prototype]]\");\n },\n preventExtensions() {\n throw readOnly(\"[[Extensible]]\");\n },\n};\n\n/** Draft handler for one transaction: writes go through the notifying helpers. */\nfunction draftHandler(tx: Transaction): ProxyHandler<object> {\n const wrap = (raw: object): object => draftOf(raw, tx);\n /** Throws unless the draft is still inside its update and `key` is a string key. */\n const writable = (key: string | symbol): string => {\n if (!tx.open) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): a draft was used after its setStore() call returned; write only inside the update`\n : \"SHADOW_STORE_DRAFT_STALE\",\n );\n }\n if (typeof key === \"symbol\") {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): symbol keys cannot be written`\n : \"SHADOW_STORE_SYMBOL_KEY\",\n );\n }\n return key;\n };\n return {\n get(target, key) {\n if (typeof key === \"symbol\") return Reflect.get(target, key);\n if (hidesPrototype(target, key)) return undefined;\n return childOf(target, key, readRaw(target, key), wrap);\n },\n has(target, key) {\n return Reflect.has(target, key);\n },\n ownKeys(target) {\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, key) {\n return describeChild(target, key, wrap);\n },\n set(target, key, value) {\n const name = writable(key);\n if (isReservedKey(name)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): \"${name}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n writeRaw(target, name, unwrapValue(value));\n return true;\n },\n deleteProperty(target, key) {\n return deleteRaw(target, writable(key));\n },\n defineProperty(_target, key) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): defineProperty is not supported on drafts; assign the property instead (key \"${String(key)}\")`\n : \"SHADOW_STORE_DEFINE_PROPERTY\",\n );\n },\n setPrototypeOf() {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): drafts cannot change their prototype`\n : \"SHADOW_STORE_PROTOTYPE\",\n );\n },\n preventExtensions() {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): drafts cannot be made non-extensible`\n : \"SHADOW_STORE_NON_EXTENSIBLE\",\n );\n },\n };\n}\n\n/** Returns the read-only proxy of a raw object. The same raw object always yields the same proxy. */\nexport function readProxyOf(raw: object): object {\n const node = nodeOf(raw);\n if (node.proxy === null) {\n const proxy = new Proxy(raw, READ_HANDLER);\n RAW.set(proxy, raw);\n node.proxy = proxy;\n }\n return node.proxy;\n}\n\n/** Returns the draft proxy of a raw object for one transaction. */\nexport function draftOf(raw: object, tx: Transaction): object {\n const existing = tx.drafts.get(raw);\n if (existing !== undefined) return existing;\n const proxy = new Proxy(raw, tx.handler);\n RAW.set(proxy, raw);\n tx.drafts.set(raw, proxy);\n return proxy;\n}\n"],"mappings":"A,8KAiBA,IAAaA,EAAb,KAAyB,CACvB,MACA,KACA,OACA,QAEA,YAAY,EAAe,CACzB,KAAK,MAAQC,EACb,KAAK,KAAO,GACZ,KAAK,uBAAS,IAAI,IAClB,KAAK,QAAUC,EAAa,IAAI,CAClC,CACF,EAEA,SAASC,EAAS,EAAiC,CAEjD,OADa,OAAOC,GAAQ,SAAWA,EAAI,SAAS,EAAI,GAAIA,IACrD,gBAAI,UAGL,wBACN,CACF,CAOA,SAASC,EACP,EACA,EACA,EACA,EACS,CACT,GAAI,CAACC,EAAYC,CAAK,GAAK,CAAC,OAAO,OAAOC,EAAQJ,CAAG,EAAG,OAAOG,EAC/D,IAAME,EAAa,QAAQ,yBAAyBD,EAAQJ,CAAG,EAQ/D,OANEK,IAAe,IAAA,IACfA,EAAW,eAAiB,IAC5BA,EAAW,WAAa,GAEjBF,EAEFG,EAAKH,CAAK,CACnB,CAGA,SAASI,EACP,EACA,EACA,EACgC,CAChC,IAAMF,EAAa,QAAQ,yBAAyBD,EAAQJ,CAAG,EAE/D,GADIK,IAAe,IAAA,IAAa,OAAOL,GAAQ,UAC3CK,EAAW,eAAiB,GAAO,OAAOA,EAC9C,IAAMF,EAAiBE,EAAW,MAElC,OADKH,EAAYC,CAAK,EACf,CAAE,GAAGE,EAAY,MAAOC,EAAKH,CAAK,CAAE,EADXE,CAElC,CAGA,SAASG,EAAe,EAAgB,EAAsB,CAC5D,OAAOR,IAAQ,aAAe,CAAC,OAAO,OAAOI,EAAQJ,CAAG,CAC1D,CAGA,SAASS,EAAU,EAAgB,EAAsB,CACvD,IACE,IAAIC,EAAwBN,EAC5BM,IAAW,KACX,EAAS,OAAO,eAAeA,CAAM,EACrC,CACA,IAAML,EAAa,QAAQ,yBAAyBK,EAAQV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,IAAID,EAAOT,CAAG,EAClBC,EAAG,OAAO,IAAID,EAAKS,CAAK,EACjBA,CACT,C"}
@@ -0,0 +1,2 @@
1
+ import{isReservedKey as e,isWrappable as t,readRaw as n,unwrapValue as r}from"./nodes.js";function i(e){return r(e)}function a(e){return Array.isArray(e)?Array(e.length):{}}function o(i){let o=r(i);if(!t(o))return o;let s=/* @__PURE__ */ new Map,c=a(o);s.set(o,c);let l=[o];for(let i=l.pop();i!==void 0;i=l.pop()){let o=s.get(i);if(o!==void 0)for(let c of Object.keys(i)){if(e(c))continue;let u=r(n(i,c));if(t(u)){let e=s.get(u);e===void 0&&(e=a(u),s.set(u,e),l.push(u)),Reflect.set(o,c,e)}else Reflect.set(o,c,u)}}return c}export{o as snapshot,i as unwrap};
2
+ //# sourceMappingURL=read.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read.js","names":["unwrap","unwrapValue","store","shellOf","value","snapshot","root","isWrappable","copies","out","pending","source","copy","key","isReservedKey","readRaw","child"],"sources":["../../../src/store/read.ts"],"sourcesContent":["import { isReservedKey, isWrappable, readRaw, unwrapValue } from \"./nodes\";\nimport type { Mutable, Store } from \"./types\";\n\n/**\n * Returns the raw data behind a store. Reads and writes on the result bypass tracking and\n * notification, so writing to it is a bug; use it for identity checks and passing data on.\n *\n * @param store A store view. A value that is not a store view is returned as is.\n * @returns The underlying object, without proxies. It is the live data, not a copy.\n * @example\n * import { unwrap, useStore } from \"@shadow-js/core\";\n *\n * const initial = { items: [1, 2, 3] };\n * const [list] = useStore(initial);\n * console.log(unwrap(list) === initial); // true: the store wraps its data in place\n * @see snapshot\n * @since 1.0.0\n */\nexport function unwrap<T>(store: Store<T>): Mutable<T> {\n return unwrapValue(store) as Mutable<T>;\n}\n\n/** A new, empty container of the same kind as `value`, with the same length for arrays. */\nfunction shellOf(value: object): object {\n return Array.isArray(value) ? new Array<unknown>((value as unknown[]).length) : {};\n}\n\n/**\n * Returns a deep plain copy of a store's current data. It reads raw data directly, so it does\n * not subscribe the running computation, and the copy is independent of later writes. Cycles and\n * shared objects are preserved. The walk is iterative, so deep data cannot overflow the stack. Use\n * it to serialize a store, send it to a server or keep an undo history.\n *\n * @param store A store view. A value that is not plain data is returned as is.\n * @returns A plain, untracked deep copy.\n * @example\n * import { snapshot, useStore } from \"@shadow-js/core\";\n *\n * const [form, setForm] = useStore({ name: \"Ada\", tags: [\"admin\"] });\n * const saved = snapshot(form);\n * setForm({ name: \"Grace\" });\n * console.log(saved.name, JSON.stringify(saved)); // Ada {\"name\":\"Ada\",\"tags\":[\"admin\"]}\n * @see unwrap\n * @since 1.0.0\n */\nexport function snapshot<T>(store: Store<T>): Mutable<T> {\n const root = unwrapValue(store);\n if (!isWrappable(root)) return root as Mutable<T>;\n const copies = new Map<object, object>();\n const out: object = shellOf(root);\n copies.set(root, out);\n const pending: object[] = [root];\n for (let source = pending.pop(); source !== undefined; source = pending.pop()) {\n const copy = copies.get(source);\n if (copy === undefined) continue;\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) continue;\n const value = unwrapValue(readRaw(source, key));\n if (isWrappable(value)) {\n let child = copies.get(value);\n if (child === undefined) {\n child = shellOf(value);\n copies.set(value, child);\n pending.push(value);\n }\n Reflect.set(copy, key, child);\n } else {\n Reflect.set(copy, key, value);\n }\n }\n }\n return out as Mutable<T>;\n}\n"],"mappings":"A,0FAkBA,SAAgBA,EAAU,EAA6B,CACrD,OAAOC,EAAYC,CAAK,CAC1B,CAGA,SAASC,EAAQ,EAAuB,CACtC,OAAO,MAAM,QAAQC,CAAK,EAAQ,MAAgBA,EAAoB,MAAM,EAAI,CAAC,CACnF,CAoBA,SAAgBC,EAAY,EAA6B,CACvD,IAAMC,EAAOL,EAAYC,CAAK,EAC9B,GAAI,CAACK,EAAYD,CAAI,EAAG,OAAOA,EAC/B,IAAME,kBAAS,IAAI,IACbC,EAAcN,EAAQG,CAAI,EAChCE,EAAO,IAAIF,EAAMG,CAAG,EACpB,IAAMC,EAAoB,CAACJ,CAAI,EAC/B,IAAK,IAAIK,EAASD,EAAQ,IAAI,EAAGC,IAAW,IAAA,GAAW,EAASD,EAAQ,IAAI,EAAG,CAC7E,IAAME,EAAOJ,EAAO,IAAIG,CAAM,EAC9B,GAAIC,IAAS,IAAA,GACb,IAAK,IAAMC,KAAO,OAAO,KAAKF,CAAM,EAAG,CACrC,GAAIG,EAAcD,CAAG,EAAG,SACxB,IAAMT,EAAQH,EAAYc,EAAQJ,EAAQE,CAAG,CAAC,EAC9C,GAAIN,EAAYH,CAAK,EAAG,CACtB,IAAIY,EAAQR,EAAO,IAAIJ,CAAK,EACxBY,IAAU,IAAA,KACZ,EAAQb,EAAQC,CAAK,EACrBI,EAAO,IAAIJ,EAAOY,CAAK,EACvBN,EAAQ,KAAKN,CAAK,GAEpB,QAAQ,IAAIQ,EAAMC,EAAKG,CAAK,CAC9B,MACE,QAAQ,IAAIJ,EAAMC,EAAKT,CAAK,CAEhC,CACF,CACA,OAAOK,CACT,C"}
@@ -0,0 +1,2 @@
1
+ import{deleteRaw as e,isReservedKey as t,isWrappable as n,unwrapValue as r,writeRaw as i}from"./nodes.js";const a=/* @__PURE__ */ new WeakMap;function o(e){return a.get(e)}function s(e,t){let n={next:e,key:t?.key??`id`,merge:t?.merge===!0},r=()=>{throw TypeError(`SHADOW_STORE_RECONCILE`)};return a.set(r,n),r}function c(e,t){if(n(e))return typeof t==`function`?t(e):Object.hasOwn(e,t)?Reflect.get(e,t):void 0}function l(e,t){return Array.isArray(e)===Array.isArray(t)}function u(e,t,i){let a=r(t.next);if(!n(a)||!l(e,a))throw TypeError(`SHADOW_STORE_RECONCILE_SHAPE`);let o=[],s=/* @__PURE__ */ new Map,c=(e,t)=>{let n=s.get(t);n===void 0&&(n=/* @__PURE__ */ new Set,s.set(t,n)),!n.has(e)&&(n.add(e),o.push({target:e,source:t}))};c(e,a);for(let e=o.pop();e!==void 0;e=o.pop())Array.isArray(e.source)?f(e.target,e.source,t,c):d(e.target,e.source,t,c)}function d(a,o,s,c){for(let e of Object.keys(o)){if(t(e))continue;let s=r(Reflect.get(o,e)),u=Object.hasOwn(a,e),d=u?Reflect.get(a,e):void 0;u&&Object.is(d,s)||(u&&n(d)&&n(s)&&l(d,s)?c(d,s):i(a,e,s))}if(!s.merge)for(let t of Object.keys(a))Object.hasOwn(o,t)||e(a,t)}function f(e,t,a,o){let s=e,u=t,d=s.slice(),f=d.map(e=>c(e,a.key)),p=/* @__PURE__ */ new Map;for(let e=0;e<d.length;e+=1){let t=f[e];t!==void 0&&!p.has(t)&&p.set(t,e)}let m=Array(d.length).fill(!1),h=[];for(let e=0;e<u.length;e+=1){let t=c(r(u[e]),a.key),n=-1;if(t!==void 0){let e=p.get(t);e!==void 0&&m[e]!==!0&&(n=e)}else e<d.length&&f[e]===void 0&&m[e]!==!0&&(n=e);n!==-1&&(m[n]=!0),h.push(n)}let g=[];for(let e=0;e<u.length;e+=1){let t=r(u[e]),i=h[e]??-1;if(i===-1){g.push(t);continue}let a=d[i];n(a)&&n(t)&&l(a,t)?(a!==t&&o(a,t),g.push(a)):g.push(t)}if(a.merge)for(let e=0;e<d.length;e+=1)m[e]!==!0&&g.push(d[e]);for(let t=0;t<g.length;t+=1)i(e,String(t),g[t]);s.length>g.length&&i(e,`length`,g.length)}function p(e){return e}export{u as applyReconcile,p as produce,s as reconcile,o as specOf};
2
+ //# sourceMappingURL=reconcile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reconcile.js","names":["SPECS","specOf","update","reconcile","spec","options","reconciler","identityOf","isWrappable","item","key","sameKind","a","b","applyReconcile","next","unwrapValue","root","stack","seen","enqueue","targets","source","target","frame","mergeArray","mergeObject","isReservedKey","value","had","current","writeRaw","deleteRaw","list","incoming","original","identities","byIdentity","index","identity","used","matches","position","match","found","values","previous","produce"],"sources":["../../../src/store/reconcile.ts"],"sourcesContent":["import { deleteRaw, isReservedKey, isWrappable, unwrapValue, writeRaw } from \"./nodes\";\nimport type { Reconciler } from \"./types\";\n\n/**\n * Options of {@link reconcile}.\n * @since 1.0.0\n */\nexport interface ReconcileOptions {\n /**\n * Identity of array items: the name of a field (`\"id\"`) or a function returning the identity.\n * Items without an identity (not an object, or the field is absent, or the function returns\n * `undefined`) are matched by position.\n * @default \"id\"\n */\n key?: string | ((item: unknown) => unknown);\n /**\n * Keep keys, and array items, that `next` does not contain. When false, keys missing from `next`\n * are deleted and arrays are truncated to its length; when true, unmatched old array items are\n * kept after the new ones.\n * @default false\n */\n merge?: boolean;\n}\n\n/**\n * What a reconciler carries from `reconcile()` to `setStore`. Not re-exported by any entry: only\n * the store setter reads it.\n * @internal\n */\nexport interface ReconcileSpec {\n /** The desired data, as passed to `reconcile()` (it may still be a store proxy). */\n readonly next: unknown;\n /** Identity of array items, resolved from {@link ReconcileOptions.key}. */\n readonly key: string | ((item: unknown) => unknown);\n /** Whether keys and items absent from `next` are kept, from {@link ReconcileOptions.merge}. */\n readonly merge: boolean;\n}\n\n/** Each reconciler function maps to its spec. Keys are the reconciler functions themselves. */\nconst SPECS: WeakMap<object, ReconcileSpec> = new WeakMap();\n\n/**\n * Looks up the spec of a reconciler created by {@link reconcile}. Not re-exported by any entry: the\n * store setter uses it to tell a reconciler from a draft updater.\n *\n * @param update Any function or object passed to `setStore`.\n * @returns The spec, or `undefined` when `update` is not a `reconcile()` result.\n * @internal\n */\nexport function specOf(update: object): ReconcileSpec | undefined {\n return SPECS.get(update);\n}\n\n/**\n * Describes a new value for a store. Passed to `setStore`, it changes only what differs from the\n * current state: objects are merged key by key, arrays are matched by `key` so retained items keep\n * their identity, and unchanged leaves are not written. Nothing is applied until `setStore` runs.\n * Use it to apply fresh server data to a store without re-rendering what did not change.\n *\n * @param next The desired data. Store proxies are accepted and unwrapped.\n * @param options Item identity (`key`) and whether to keep absent keys (`merge`). Undefined uses\n * the defaults (`key: \"id\"`, `merge: false`).\n * @returns A reconciler to pass to `setStore`, alone or as the last argument of a path.\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE`) when the returned reconciler is\n * called directly instead of being passed to `setStore`. `setStore` throws TypeError\n * (`SHADOW_STORE_RECONCILE_SHAPE`) when `next` is not the same kind of container (object or\n * array) as the value it reconciles.\n * @example\n * import { reconcile, useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n *\n * async function refresh(): Promise<void> {\n * const response = await fetch(\"/api/todos\");\n * setTodos(\"items\", reconcile((await response.json()) as Todo[], { key: \"id\" }));\n * }\n * @see useStore\n * @since 1.0.0\n */\nexport function reconcile<T>(next: T, options?: ReconcileOptions): Reconciler<T> {\n const spec: ReconcileSpec = {\n next,\n key: options?.key ?? \"id\",\n merge: options?.merge === true,\n };\n const reconciler: Reconciler<T> = () => {\n throw new TypeError(\n __DEV__\n ? \"ShadowStore: a reconcile() result must be passed to setStore()\"\n : \"SHADOW_STORE_RECONCILE\",\n );\n };\n SPECS.set(reconciler, spec);\n return reconciler;\n}\n\ninterface Frame {\n readonly target: object;\n readonly source: object;\n}\n\n/** Field name or function giving an item's identity; `undefined` means the item has none. */\nfunction identityOf(item: unknown, key: string | ((item: unknown) => unknown)): unknown {\n if (!isWrappable(item)) return undefined;\n if (typeof key === \"function\") return key(item);\n return Object.hasOwn(item, key) ? Reflect.get(item, key) : undefined;\n}\n\n/** Same container kind: both arrays or both objects. */\nfunction sameKind(a: object, b: object): boolean {\n return Array.isArray(a) === Array.isArray(b);\n}\n\n/**\n * Applies a reconciler to the store root. The diff is iterative: pending (target, source) pairs\n * live on an explicit stack, so data nested thousands of levels deep cannot overflow the call\n * stack. Each pair is visited once, which also terminates on cyclic input. Not re-exported by any\n * entry: only the store setter calls it, inside its transaction.\n *\n * @param root The raw (unwrapped) object or array to update in place.\n * @param spec The reconciler's spec, from {@link specOf}.\n * @param label The store label for messages (` (name)`, or an empty string).\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE_SHAPE`) when `spec.next` is not the\n * same kind of container as `root`.\n * @internal\n */\nexport function applyReconcile(root: object, spec: ReconcileSpec, label: string): void {\n const next = unwrapValue(spec.next);\n if (!isWrappable(next) || !sameKind(root, next)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: reconcile() needs data of the same shape as the store root (an object or an array)`\n : \"SHADOW_STORE_RECONCILE_SHAPE\",\n );\n }\n const stack: Frame[] = [];\n const seen = new Map<object, Set<object>>();\n const enqueue = (target: object, source: object): void => {\n let targets = seen.get(source);\n if (targets === undefined) {\n targets = new Set();\n seen.set(source, targets);\n }\n if (targets.has(target)) return;\n targets.add(target);\n stack.push({ target, source });\n };\n\n enqueue(root, next);\n for (let frame = stack.pop(); frame !== undefined; frame = stack.pop()) {\n if (Array.isArray(frame.source)) mergeArray(frame.target, frame.source, spec, enqueue);\n else mergeObject(frame.target, frame.source, spec, enqueue);\n }\n}\n\nfunction mergeObject(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) continue;\n const value = unwrapValue(Reflect.get(source, key));\n const had = Object.hasOwn(target, key);\n const current: unknown = had ? Reflect.get(target, key) : undefined;\n if (had && Object.is(current, value)) continue;\n if (had && isWrappable(current) && isWrappable(value) && sameKind(current, value)) {\n enqueue(current, value);\n continue;\n }\n writeRaw(target, key, value);\n }\n if (spec.merge) return;\n for (const key of Object.keys(target)) {\n if (!Object.hasOwn(source, key)) deleteRaw(target, key);\n }\n}\n\nfunction mergeArray(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n const list = target as unknown[];\n const incoming = source as unknown[];\n // Copy first: matching reads the old positions, while the writes below move items.\n const original = list.slice();\n const identities = original.map((item) => identityOf(item, spec.key));\n const byIdentity = new Map<unknown, number>();\n for (let index = 0; index < original.length; index += 1) {\n const identity = identities[index];\n if (identity !== undefined && !byIdentity.has(identity)) byIdentity.set(identity, index);\n }\n\n const used: boolean[] = new Array<boolean>(original.length).fill(false);\n const matches: number[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const identity = identityOf(item, spec.key);\n let match = -1;\n if (identity !== undefined) {\n const found = byIdentity.get(identity);\n if (found !== undefined && used[found] !== true) match = found;\n } else if (position < original.length && identities[position] === undefined) {\n if (used[position] !== true) match = position;\n }\n if (match !== -1) used[match] = true;\n matches.push(match);\n }\n\n const values: unknown[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const match = matches[position] ?? -1;\n if (match === -1) {\n values.push(item);\n continue;\n }\n const previous = original[match];\n if (isWrappable(previous) && isWrappable(item) && sameKind(previous, item)) {\n if (previous !== item) enqueue(previous, item);\n values.push(previous);\n } else {\n values.push(item);\n }\n }\n if (spec.merge) {\n for (let index = 0; index < original.length; index += 1) {\n if (used[index] !== true) values.push(original[index]);\n }\n }\n\n for (let position = 0; position < values.length; position += 1) {\n writeRaw(target, String(position), values[position]);\n }\n if (list.length > values.length) writeRaw(target, \"length\", values.length);\n}\n\n/**\n * Marks a draft updater. It is the function itself (`setStore(produce((d) => { d.n += 1 }))` is\n * `setStore((d) => { d.n += 1 })`); it exists so code written for other libraries migrates as is.\n *\n * @param update The draft updater: it mutates the draft it receives.\n * @returns `update`, unchanged.\n * @example\n * import { produce, useStore } from \"@shadow-js/core\";\n *\n * const [cart, setCart] = useStore({ items: [] as string[], count: 0 });\n * setCart(\n * produce((draft) => {\n * draft.items.push(\"apple\");\n * draft.count += 1;\n * }),\n * );\n * console.log(cart.count); // 1\n * @see useStore\n * @since 1.0.0\n */\nexport function produce<T>(update: (draft: T) => void): (draft: T) => void {\n return update;\n}\n"],"mappings":"A,0GAuCA,MAAMA,kBAAwC,IAAI,QAUlD,SAAgBC,EAAO,EAA2C,CAChE,OAAOD,EAAM,IAAIE,CAAM,CACzB,CA6BA,SAAgBC,EAAa,EAAS,EAA2C,CAC/E,IAAMC,EAAsB,CAC1B,OACA,IAAKC,GAAS,KAAO,KACrB,MAA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AM,EAAQA,EAC3D,MAAWF,EAAWP,EAAS,QAAUC,EAAWM,KAAc,IAAA,IAC5DF,EAAKE,KAAc,KAAM,EAAQA,GAEnCC,IAAU,KAAI,EAAKA,GAAS,IAChCF,EAAQ,KAAKE,CAAK,CACpB,CAEA,IAAME,EAAoB,CAAC,EAC3B,IAAK,IAAIH,EAAW,EAAGA,EAAWR,EAAS,OAAQ,GAAY,EAAG,CAChE,IAAMzB,EAAOO,EAAYkB,EAASQ,EAAS,EACrCC,EAAQF,EAAQC,IAAa,GACnC,GAAIC,IAAU,GAAI,CAChBE,EAAO,KAAKpC,CAAI,EAChB,QACF,CACA,IAAMqC,EAAWX,EAASQ,GACtBnC,EAAYsC,CAAQ,GAAKtC,EAAYC,CAAI,GAAKE,EAASmC,EAAUrC,CAAI,GACnEqC,IAAarC,GAAMW,EAAQ0B,EAAUrC,CAAI,EAC7CoC,EAAO,KAAKC,CAAQ,GAEpBD,EAAO,KAAKpC,CAAI,CAEpB,CACA,GAAIL,EAAK,MACF,IAAA,IAAIkC,EAAQ,EAAGA,EAAQH,EAAS,OAAQ,GAAS,EAChDK,EAAKF,KAAW,IAAMO,EAAO,KAAKV,EAASG,EAAM,EAIzD,IAAK,IAAII,EAAW,EAAGA,EAAWG,EAAO,OAAQ,GAAY,EAC3Dd,EAASR,EAAQ,OAAOmB,CAAQ,EAAGG,EAAOH,EAAS,EAEjDT,EAAK,OAASY,EAAO,QAAQd,EAASR,EAAQ,SAAUsB,EAAO,MAAM,CAC3E,CAsBA,SAAgBE,EAAW,EAAgD,CACzE,OAAO7C,CACT,C"}
@@ -0,0 +1,2 @@
1
+ import{group as e}from"../internal/scheduler.js";import{untrack as t}from"../ownership.js";import{useSignal as n}from"../signal.js";import{isReservedKey as r,isWrappable as i,unwrapValue as a}from"./nodes.js";import{applyReconcile as o,reconcile as s,specOf as c}from"./reconcile.js";import{Transaction as l,draftOf as u,readProxyOf as d}from"./proxies.js";function f(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function p(e,t){let n=e.from??0,r=e.to??t-1,i=e.by??1;if(!Number.isFinite(i)||i===0)throw TypeError(`SHADOW_STORE_RANGE`);let a=[];for(let e=n;(i>0?e<=r:e>=r)&&(a.push(e),!(a.length>t+1));e+=i);return a}function m(e,t,n){let i=[];if(Array.isArray(e)){if(typeof t==`number`)i.push(t);else if(typeof t==`function`){let n=t;for(let t=0;t<e.length;t+=1)n(e[t],t)&&i.push(t)}else if(Array.isArray(t))i.push(...t);else if(typeof t==`object`&&t)i.push(...p(t,e.length));else throw TypeError(`SHADOW_STORE_PATH_ARRAY`)}else if(typeof t==`string`||typeof t==`number`)i.push(t);else if(Array.isArray(t))i.push(...t);else throw TypeError(`SHADOW_STORE_PATH_OBJECT`);for(let e of i)if(typeof e==`string`&&r(e))throw TypeError(`SHADOW_STORE_PATH_KEY`);return i}function h(e,t,n){let r=t[t.length-1],s=t.slice(0,-1),l=(e,t)=>{for(let u of m(e,s[t],n)){let d=e;if(t===s.length-1){let e=d[u],t=typeof r==`function`?c(r):void 0;if(t!==void 0){i(e)?o(a(e),t,n):d[u]=t.next;continue}let s=typeof r==`function`?r(e):r;f(s)&&i(e)&&!Array.isArray(e)?g(e,s,n):d[u]=s}else{let e=d[u];if(!i(e))throw TypeError(`SHADOW_STORE_PATH_VALUE`);l(e,t+1)}}};l(e,0)}function g(e,t,n){for(let n of Object.keys(t)){if(r(n))throw TypeError(`SHADOW_STORE_ASSIGN_KEY`);e[n]=t[n]}}function _(n,r){let i=a(n);return[d(i),(...n)=>{if(n.length===0)throw TypeError(`SHADOW_STORE_NO_ARGUMENT`);let a=n[0];e(()=>t(()=>{if(n.length>1){let e=new l(r);try{h(u(i,e),n,r)}finally{e.open=!1}}else if(typeof a==`function`){let e=c(a);if(e!==void 0){o(i,e,r);return}let t=new l(r),n;try{n=a(u(i,t))}finally{t.open=!1}n!==void 0&&v(i,n,r)}else v(i,a,r)}))}]}function v(e,t,n){if(Array.isArray(e)){if(!Array.isArray(t))throw TypeError(`SHADOW_STORE_ARRAY_UPDATE`);let r=c(s(t));r!==void 0&&o(e,r,n);return}if(!f(t))throw TypeError(`SHADOW_STORE_UPDATE_ARGUMENT`);let r=new l(n);try{g(u(e,r),t,n)}finally{r.open=!1}}function y(e,t){let r=t?.name===void 0?``:` (${t.name})`,o=a(e);if(i(o))return _(o,r);let[s,c]=n(b(e),t?.name===void 0?void 0:{name:t.name});return[s,e=>c(typeof e==`function`?t=>b(e(t)):b(e))]}function b(e){let t=a(e);return i(t)?d(t):e}export{y as useStore};
2
+ //# sourceMappingURL=use-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-store.js","names":["setStore","isPlainObject","value","prototype","rangeKeys","from","range","to","length","by","keys","i","stepKeys","target","step","filter","key","isReservedKey","applyPath","path","steps","walk","depth","label","holder","previous","spec","specOf","isWrappable","applyReconcile","unwrapValue","next","mergeInto","child","root","source","createDeepStore","initial","readProxyOf","args","first","group","untrack","tx","Transaction","draftOf","result","replaceWith","reconcile","useStore","options","read","write","useSignal","wrapCell","raw"],"sources":["../../../src/store/use-store.ts"],"sourcesContent":["import {\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n group,\n isComputingMemo,\n ShadowError,\n} from \"../extend\";\nimport { untrack } from \"../ownership\";\nimport { useSignal } from \"../signal\";\nimport { isReservedKey, isWrappable, unwrapValue } from \"./nodes\";\nimport { draftOf, readProxyOf, Transaction } from \"./proxies\";\nimport { snapshot } from \"./read\";\nimport { applyReconcile, reconcile, specOf } from \"./reconcile\";\nimport type { MixedInitial, NotMixed, SetStore, Store, StoreResult } from \"./types\";\n\n/**\n * Options of {@link useStore}.\n * @since 1.0.0\n */\nexport interface StoreOptions {\n /**\n * Label shown in error messages and by devtools.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction rangeKeys(range: { from?: number; to?: number; by?: number }, length: number): number[] {\n const from = range.from ?? 0;\n const to = range.to ?? length - 1;\n const by = range.by ?? 1;\n if (!Number.isFinite(by) || by === 0)\n throw new TypeError(\n __DEV__ ? \"ShadowStore: a range needs a non-zero `by`\" : \"SHADOW_STORE_RANGE\",\n );\n const keys: number[] = [];\n for (let i = from; by > 0 ? i <= to : i >= to; i += by) {\n keys.push(i);\n if (keys.length > length + 1) break;\n }\n return keys;\n}\n\n/** The keys one path step addresses on `target` (a draft). */\nfunction stepKeys(target: object, step: unknown, label: string): Array<string | number> {\n const keys: Array<string | number> = [];\n if (Array.isArray(target)) {\n if (typeof step === \"number\") keys.push(step);\n else if (typeof step === \"function\") {\n const filter = step as (item: unknown, index: number) => boolean;\n for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);\n } else if (Array.isArray(step)) keys.push(...(step as number[]));\n else if (typeof step === \"object\" && step !== null)\n keys.push(...rangeKeys(step, target.length));\n else\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an array` : \"SHADOW_STORE_PATH_ARRAY\",\n );\n } else if (typeof step === \"string\" || typeof step === \"number\") {\n keys.push(step);\n } else if (Array.isArray(step)) {\n keys.push(...(step as Array<string | number>));\n } else {\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an object` : \"SHADOW_STORE_PATH_OBJECT\",\n );\n }\n for (const key of keys) {\n if (typeof key === \"string\" && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be used in a path`\n : \"SHADOW_STORE_PATH_KEY\",\n );\n }\n }\n return keys;\n}\n\n/** Writes `value` (or the updater's result) at the end of a path, merging plain objects. */\nfunction applyPath(root: object, path: unknown[], label: string): void {\n const value = path[path.length - 1];\n const steps = path.slice(0, -1);\n const walk = (target: object, depth: number): void => {\n for (const key of stepKeys(target, steps[depth], label)) {\n const holder = target as Record<string | number, unknown>;\n if (depth === steps.length - 1) {\n const previous = holder[key];\n const spec = typeof value === \"function\" ? specOf(value) : undefined;\n if (spec !== undefined) {\n // reconcile(...) at a path diffs only that sub-tree.\n if (isWrappable(previous)) applyReconcile(unwrapValue(previous) as object, spec, label);\n else holder[key] = spec.next;\n continue;\n }\n const next =\n typeof value === \"function\" ? (value as (p: unknown) => unknown)(previous) : value;\n if (isPlainObject(next) && isWrappable(previous) && !Array.isArray(previous)) {\n mergeInto(previous as Record<string, unknown>, next, label);\n } else {\n holder[key] = next;\n }\n } else {\n const child = holder[key];\n if (!isWrappable(child)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the path goes through a value that is not an object`\n : \"SHADOW_STORE_PATH_VALUE\",\n );\n }\n walk(child, depth + 1);\n }\n }\n };\n walk(root, 0);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n label: string,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be assigned`\n : \"SHADOW_STORE_ASSIGN_KEY\",\n );\n }\n target[key] = source[key];\n }\n}\n\n/**\n * Devtools handles of the stores, by store root. Dev builds only: the WeakMap is unused (and dropped)\n * in production, where `__DEV__` is false.\n */\nconst storeHandles = /* @__PURE__ */ new WeakMap<object, Array<{ readonly name: string }>>();\n\nfunction createDeepStore<T extends object>(initial: T, label: string): [Store<T>, SetStore<T>] {\n const root = unwrapValue(initial) as object;\n const store = readProxyOf(root) as Store<T>;\n\n // One untyped entry point for every form of update. It is assignable to SetStore<T> because its\n // parameters accept anything: the typed overloads are the public contract, and the devtools\n // path setter below calls this function directly with a path it built at run time.\n const apply = (...args: unknown[]): void => {\n if (__DEV__ && isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n if (args.length === 0)\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: setStore() needs an argument` : \"SHADOW_STORE_NO_ARGUMENT\",\n );\n const first = args[0];\n group(() =>\n untrack(() => {\n if (args.length > 1) {\n const tx = new Transaction(label);\n try {\n applyPath(draftOf(root, tx), args, label);\n } finally {\n tx.open = false;\n }\n return;\n }\n if (typeof first === \"function\") {\n const spec = specOf(first);\n if (spec !== undefined) {\n applyReconcile(root, spec, label);\n return;\n }\n const tx = new Transaction(label);\n let result: unknown;\n try {\n result = (first as (draft: unknown) => unknown)(draftOf(root, tx));\n } finally {\n tx.open = false;\n }\n if (result !== undefined) replaceWith(root, result, label);\n return;\n }\n replaceWith(root, first, label);\n }),\n );\n };\n const setStore: SetStore<T> = apply;\n if (__DEV__) {\n const handle = {\n name: label === \"\" ? \"store\" : label.replace(/^ \\((.*)\\)$/, \"$1\"),\n snapshot: () => snapshot(store),\n set: (path: readonly (string | number)[], value: unknown) => {\n apply(...path, value);\n },\n };\n // Devtools hold the handle weakly, so the handle must stay reachable exactly as long as the store.\n // The store's proxy and its setter both reach `root`, and a WeakMap value lives as long as its key.\n // A root shared by two stores keeps both handles.\n const anchored = storeHandles.get(root);\n if (anchored === undefined) storeHandles.set(root, [handle]);\n else anchored.push(handle);\n devtoolsReport(DEVTOOLS_EVENT.STORE_CREATED, handle, currentOwner());\n }\n return [store, setStore];\n}\n\n/** `setStore(value)`: an array replaces (diffed in place), a plain object merges its keys. */\nfunction replaceWith(root: object, value: unknown, label: string): void {\n if (Array.isArray(root)) {\n if (!Array.isArray(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: an array store is updated with an array or a function`\n : \"SHADOW_STORE_ARRAY_UPDATE\",\n );\n }\n const spec = specOf(reconcile(value));\n if (spec !== undefined) applyReconcile(root, spec, label);\n return;\n }\n if (!isPlainObject(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: setStore() expects an object, a function or a reconcile() result`\n : \"SHADOW_STORE_UPDATE_ARGUMENT\",\n );\n }\n const tx = new Transaction(label);\n try {\n mergeInto(draftOf(root, tx) as Record<string, unknown>, value, label);\n } finally {\n tx.open = false;\n }\n}\n\n/**\n * The state hook. Pass a single value for a reactive cell, or plain data for a deep store:\n *\n * ```ts\n * const [count, setCount] = useStore(0); // count() / setCount(n => n + 1)\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * todos.items[0]?.done; // tracks exactly this property\n * setTodos((draft) => { draft.items.push(todo); }); // notifies only what changed\n * setTodos(\"items\", (t) => t.id === 3, \"done\", true); // path form\n * ```\n *\n * Reads inside effects, memos and JSX subscribe to the exact value or property read; writes notify\n * exactly the readers of what changed, in one batch. A store wraps plain objects and arrays in\n * place; class instances, `Date`, `Map`, `Set` and functions are single values. A value that may\n * be `null` or another type (`Todo[] | null`) is a single value too: it is replaced as a whole, and\n * plain data assigned to it is read through the same fine-grained proxies a store uses.\n *\n * @param initial Initial value or plain data. Plain objects and arrays are wrapped in place, not\n * copied.\n * @param options `name` labels the store in messages. Undefined uses the default (unnamed).\n * @returns `[read, write]` for a single value, `[store, setStore]` for plain data.\n * @throws ShadowError `WRITE_IN_MEMO` from the setter, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `setStore` throws TypeError (production messages\n * `SHADOW_STORE_*`) for an update it cannot apply: no argument, a bad path step, a path through a\n * value that is not an object, a reserved key such as `__proto__`, or a non-array value for an\n * array store. Writing to the store view itself throws TypeError (`SHADOW_STORE_READ_ONLY`).\n * @example\n * import { useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n *\n * const [count, setCount] = useStore(0);\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * setCount((n) => n + 1);\n * setTodos((draft) => {\n * draft.items.push({ id: 1, title: \"Write docs\", done: false });\n * });\n * setTodos(\"items\", (todo) => todo.id === 1, \"done\", true);\n * console.log(count(), todos.items[0]?.done); // 1 true\n * @see useSignal\n * @see reconcile\n * @since 1.0.0\n */\nexport function useStore<T extends NotMixed<T>>(initial: T, options?: StoreOptions): StoreResult<T>;\nexport function useStore<T>(initial: MixedInitial<T>, options?: StoreOptions): StoreResult<T>;\nexport function useStore(initial: unknown, options?: StoreOptions): unknown {\n const label = options?.name === undefined ? \"\" : ` (${options.name})`;\n const root = unwrapValue(initial);\n if (isWrappable(root)) return createDeepStore(root, label);\n // A single value, which may be plain data later (`Todo[] | null`): objects and arrays that are\n // assigned are wrapped in read proxies, so `todos()?.[0]?.done` tracks exactly what it reads.\n const [read, write] = useSignal<unknown>(\n wrapCell(initial),\n options?.name === undefined ? undefined : { name: options.name },\n );\n const set = (next: unknown): unknown =>\n write(\n typeof next === \"function\"\n ? (previous: unknown) => wrapCell((next as (previous: unknown) => unknown)(previous))\n : wrapCell(next),\n );\n return [read, set];\n}\n\n/** The value a single-value cell holds: plain data becomes its (stable) read proxy. */\nfunction wrapCell(value: unknown): unknown {\n const raw = unwrapValue(value);\n return isWrappable(raw) ? readProxyOf(raw) : value;\n}\n"],"mappings":"A,qWA4BA,SAASC,EAAc,EAAkD,CACvE,GAAI,OAAOC,GAAU,WAAYA,GAAkB,MAAM,QAAQA,CAAK,EAAG,MAAO,GAChF,IAAMC,EAAY,OAAO,eAAeD,CAAK,EAC7C,OAAOC,IAAc,OAAO,WAAaA,IAAc,IACzD,CAEA,SAASC,EAAU,EAAoD,EAA0B,CAC/F,IAAMC,EAAOC,EAAM,MAAQ,EACrBC,EAAKD,EAAM,IAAME,EAAS,EAC1BC,EAAKH,EAAM,IAAM,EACvB,GAAI,CAAC,OAAO,SAASG,CAAE,GAAKA,IAAO,EACjC,MAAU,UACiD,oBAC3D,EACF,IAAMC,EAAiB,CAAC,EACxB,IAAK,IAAIC,EAAIN,GAAMI,EAAK,EAAIE,GAAKJ,EAAKI,GAAKJ,KACzCG,EAAK,KAAKC,CAAC,EACP,IAAK,OAASH,EAAS,IAFkB,GAAKC,GAIpD,OAAOC,CACT,CAGA,SAASE,EAAS,EAAgB,EAAe,EAAuC,CACtF,IAAMF,EAA+B,CAAC,EACtC,GAAI,MAAM,QAAQG,CAAM,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from"./context.js";const t=/* @__PURE__ */ e(null,{name:`Suspense`}),n=/* @__PURE__ */ e(null,{name:`ResourceCache`});export{n as ResourceCacheContext,t as SuspenseContext};
2
+ //# sourceMappingURL=suspense.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"suspense.js","names":["SuspenseContext","ResourceCacheContext"],"sources":["../../src/suspense.ts"],"sourcesContent":["import { type Context, createContext } from \"./context\";\n\n/**\n * Counter protocol between asynchronous sources and the nearest `<Suspense>` boundary.\n * A source calls `increment()` when it starts blocking its readers and `decrement()` exactly once\n * when it settles.\n * @since 1.0.0\n */\nexport interface SuspenseTracker {\n /**\n * Records one more pending source. The boundary shows its fallback while the count is above\n * zero; call it once per source, the first time a reader sees that source pending.\n */\n increment(): void;\n /**\n * Records that one pending source settled (with a value or an error). Call it exactly once per\n * `increment()`; when the count returns to zero the boundary shows its content again.\n */\n decrement(): void;\n /**\n * Called when a transition reads pending data in this boundary. Returns true when the boundary keeps\n * its content meanwhile: the reader then throws the suspension and keeps its previous value until\n * the boundary releases it. Returns false (or is absent) to show the fallback as usual.\n * @default undefined (the boundary never holds its content: the fallback shows as usual)\n */\n hold?(): boolean;\n}\n\n/**\n * The context through which an asynchronous source finds the nearest `<Suspense>` boundary. Each\n * boundary provides its {@link SuspenseTracker}; the value is `null` outside any boundary. Read it\n * when building a data primitive that should hold the boundary while it loads, as `useResource`\n * does.\n *\n * @example\n * import { SuspenseContext, useContext } from \"@shadow-js/core\";\n *\n * function useLoadingHold(promise: Promise<unknown>): void {\n * const tracker = useContext(SuspenseContext); // null outside any <Suspense>\n * if (tracker === null) return;\n * tracker.increment(); // the boundary shows its fallback\n * promise.finally(() => tracker.decrement());\n * }\n * @see useResource\n * @since 1.0.0\n */\nexport const SuspenseContext: Context<SuspenseTracker | null> =\n /* @__PURE__ */ createContext<SuspenseTracker | null>(null, { name: \"Suspense\" });\n\n/**\n * Bridge between resources and the server/hydration runtime. During server rendering it collects\n * in-flight fetches and replays finished ones on the next pass; during hydration it serves the\n * values the server already fetched, so the client does not fetch them again.\n * @since 1.0.0\n */\nexport interface ResourceCache {\n /**\n * Deterministic key for a resource created at this point of the render. `explicit` is the\n * resource's `key` option, or `undefined` when it has none.\n */\n key(explicit: string | undefined): string;\n /** A cached value, wrapped so that `undefined` values are representable. */\n read(key: string): { value: unknown } | undefined;\n /**\n * A fetch started; the cache stores its value under `key` when it resolves. `options.deferStream` is\n * true for a resource that holds the first streamed flush (see `ResourceOptions.deferStream`).\n */\n track(key: string, promise: Promise<unknown>, options?: ResourceTrackOptions): void;\n /**\n * The fetch an earlier pass of the same render started for `key` and that has not settled, when there\n * is one. A resource that finds it waits for that fetch instead of starting another, so a pass that\n * renders again does not fetch twice. Optional: a cache that does not keep earlier fetches omits it.\n */\n pending?(key: string): Promise<unknown> | undefined;\n}\n\n/** What {@link ResourceCache.track} is told about a fetch. @since 1.0.0 */\nexport interface ResourceTrackOptions {\n /** True when the resource was created with `deferStream: true`. */\n readonly deferStream?: boolean | undefined;\n}\n\n/**\n * The context through which `useResource` reaches the renderer's {@link ResourceCache}. Server\n * renderers and hydration provide it; the value is `null` when resources should always fetch. Only\n * a custom renderer needs to provide it.\n *\n * @example\n * import { type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\n *\n * const values = new Map<string, unknown>();\n * let created = 0;\n * const cache: ResourceCache = {\n * key: (explicit) => explicit ?? `resource-${created++}`,\n * read: (key) => (values.has(key) ? { value: values.get(key) } : undefined),\n * track: (key, promise) => void promise.then((value) => values.set(key, value)),\n * };\n * const page = <ResourceCacheContext value={cache}><p>Loading data</p></ResourceCacheContext>;\n * @see useResource\n * @since 1.0.0\n */\nexport const ResourceCacheContext: Context<ResourceCache | null> =\n /* @__PURE__ */ createContext<ResourceCache | null>(null, { name: \"ResourceCache\" });\n"],"mappings":"A,6CA8CA,MAAaA,EACK,kBAAsC,KAAM,CAAE,KAAM,UAAW,CAAC,EAsDrEC,EACK,kBAAoC,KAAM,CAAE,KAAM,eAAgB,CAAC,E"}
@@ -0,0 +1,2 @@
1
+ import{untrack as e}from"./ownership.js";import{useSignal as t}from"./signal.js";import{startTransition as n}from"./internal/concurrency.js";function r(){let[r,i]=t(!1),a=0;return[r,t=>{a+=1,e(()=>i(!0));let r;try{r=n(t)}catch(t){throw--a,a===0&&e(()=>i(!1)),t}return r.then(()=>{--a,a===0&&e(()=>i(!1))})}]}function i(e,t){return e}export{i as useDeferredValue,r as useTransition};
2
+ //# sourceMappingURL=transitions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transitions.js","names":["useTransition","pending","setPending","useSignal","running","untrack","applied","startTransition","fn","error","useDeferredValue","source"],"sources":["../../src/transitions.ts"],"sourcesContent":["import {\n type Accessor,\n createComputation,\n type Equals,\n inTransition,\n registerTransitionLane,\n startTransition,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Options of {@link useDeferredValue}.\n * @since 1.0.0\n */\nexport interface DeferredValueOptions<T> {\n /**\n * Decides whether the deferred value changed: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default \"useDeferredValue\" for the watcher; the value itself is unnamed\n */\n name?: string;\n}\n\n/**\n * Runs `fn` as a transition and reports whether it is pending. Returns `[isPending, start]`:\n * `isPending` is true from `start(fn)` until the transition has been applied (including any Suspense\n * boundary it waits on); `start(fn)` is {@link startTransition} that also updates `isPending`.\n *\n * Use it for updates that may be slow to show (navigating to a page that loads data): the previous\n * screen stays until the new one is ready, and the input stays responsive meanwhile.\n *\n * @returns `[isPending, start]`. `isPending` is an accessor; `start` returns a promise that\n * resolves when the transition has been applied. On the server `start` runs `fn` at once.\n * @throws Nothing itself. `start` rethrows synchronously what `fn` throws, after clearing\n * `isPending` when no other transition of this hook is running.\n * @example\n * import { useSignal, useTransition } from \"@shadow-js/core\";\n *\n * function Tabs() {\n * const [page, setPage] = useSignal(\"home\");\n * const [pending, start] = useTransition();\n * return (\n * <button disabled={pending()} onClick={() => start(() => setPage(\"reports\"))}>\n * {page() === \"reports\" ? \"Reports\" : \"Open reports\"}\n * </button>\n * );\n * }\n * @see startTransition\n * @see useDeferredValue\n * @since 1.0.0\n */\nexport function useTransition(): [Accessor<boolean>, (fn: () => void) => Promise<void>] {\n const [pending, setPending] = useSignal(false);\n let running = 0;\n const start = (fn: () => void): Promise<void> => {\n running += 1;\n // Urgent: the pending state must show before the transition's own work.\n untrack(() => setPending(true));\n let applied: Promise<void>;\n try {\n applied = startTransition(fn);\n } catch (error) {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n throw error;\n }\n return applied.then(() => {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n });\n };\n return [pending, start];\n}\n\n/**\n * Returns a value that follows `source` in the transition lane: it keeps the previous value while\n * urgent updates run, and takes the new value when the lane applies it. Reads of the source are\n * unaffected. On the server it returns the source itself (there is no lane).\n *\n * @param source The value to follow. Tracked by a watcher that runs in the transition lane.\n * @param options Equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the deferred value. It starts as the source's current value.\n * @example\n * import { useDeferredValue, useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const names = [\"Ada\", \"Grace\", \"Linus\"];\n * function Search() {\n * const [query, setQuery] = useSignal(\"\");\n * const deferredQuery = useDeferredValue(query);\n * const results = useMemo(() => names.filter((name) => name.includes(deferredQuery())));\n * return (\n * <label>\n * <input value={query()} onInput={(e) => setQuery(e.currentTarget.value)} />\n * {results().join(\", \")}\n * </label>\n * );\n * }\n * @see useTransition\n * @since 1.0.0\n */\nexport function useDeferredValue<T>(\n source: Accessor<T>,\n options?: DeferredValueOptions<T>,\n): Accessor<T> {\n if (__SERVER__) return source;\n registerTransitionLane();\n const [value, setValue] = useSignal<T>(untrack(source), {\n equals: options?.equals ?? Object.is,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n // The watcher runs in the lane. Its first run (queued at creation) finds the value equal, so it\n // writes nothing; a later run writes the source's value, and an equal value notifies nobody.\n createComputation({\n kind: \"effect\",\n fn: () => source(),\n apply: (next: T) => {\n setValue(() => next);\n },\n lane: true,\n name: options?.name ?? \"useDeferredValue\",\n });\n return value;\n}\n\nexport { inTransition };\n"],"mappings":"A,6IAwDA,SAAgBA,GAAwE,CACtF,GAAM,CAACC,EAASC,GAAcC,EAAU,EAAK,EACzCC,EAAU,EAkBd,MAAO,CAACH,EAjBO,GAAkC,CAC/C,GAAW,EAEXI,MAAcH,EAAW,EAAI,CAAC,EAC9B,IAAII,EACJ,GAAI,CACF,EAAUC,EAAgBC,CAAE,CAC9B,OAASC,EAAO,CAGd,KAFA,IACIL,IAAY,GAAGC,MAAcH,EAAW,EAAK,CAAC,EAC5CO,CACR,CACA,OAAOH,EAAQ,SAAW,CACxB,IACIF,IAAY,GAAGC,MAAcH,EAAW,EAAK,CAAC,CACpD,CAAC,CACH,CACsB,CACxB,CA4BA,SAAgBQ,EACd,EACA,EACa,CACG,OAAOC,CAkBzB,C"}
@@ -0,0 +1,90 @@
1
+ import { handleError } from "./internal/owner.js";
2
+ import { batch } from "./internal/scheduler.js";
3
+ import { untrack } from "./ownership.js";
4
+ import { useSignal } from "./signal.js";
5
+ import { currentOwner } from "./extend/index.js";
6
+ //#region src/action.ts
7
+ function isPromiseLike(value) {
8
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
9
+ }
10
+ /**
11
+ * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,
12
+ * tracks whether it is pending, and commits its result. The ShadowJS form of React's
13
+ * `useActionState` (state, dispatch, pending). `previous` is the last committed state.
14
+ *
15
+ * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a
16
+ * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not
17
+ * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an
18
+ * error boundary can show it. Without an owner the returned promise rejects instead.
19
+ *
20
+ * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.
21
+ * @param initialState The state before the first dispatch.
22
+ * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true
23
+ * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this
24
+ * call has finished, whether it committed or not.
25
+ * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with
26
+ * the action's error. With an owner, the error goes to its error handler, or is reported as an
27
+ * uncaught error (`reportError`) when no handler is registered above it.
28
+ * @example
29
+ * import { useAction } from "@shadow-js/core";
30
+ *
31
+ * const [message, send, sending] = useAction(async (_prev: string, text: string) => {
32
+ * await fetch("/api/messages", { method: "POST", body: text });
33
+ * return `sent: ${text}`;
34
+ * }, "");
35
+ * void send("hello");
36
+ * console.log(sending(), message());
37
+ * @see useOptimistic
38
+ * @see useTransition
39
+ * @since 1.0.0
40
+ */
41
+ function useAction(action, initialState) {
42
+ const owner = currentOwner();
43
+ const [state, setState] = useSignal(initialState);
44
+ const [pending, setPending] = useSignal(false);
45
+ let latest = 0;
46
+ const dispatch = (...args) => {
47
+ latest += 1;
48
+ const id = latest;
49
+ const previous = untrack(state);
50
+ const commit = (value) => {
51
+ if (id !== latest) return;
52
+ batch(() => {
53
+ setState(() => value);
54
+ setPending(false);
55
+ });
56
+ };
57
+ const fail = (error) => {
58
+ if (id !== latest) return;
59
+ setPending(false);
60
+ if (owner === null) throw error;
61
+ handleError(error, owner);
62
+ };
63
+ let result;
64
+ try {
65
+ result = untrack(() => action(previous, ...args));
66
+ } catch (error) {
67
+ if (owner === null) {
68
+ if (id === latest) setPending(false);
69
+ return Promise.reject(error);
70
+ }
71
+ fail(error);
72
+ return Promise.resolve();
73
+ }
74
+ if (!isPromiseLike(result)) {
75
+ commit(result);
76
+ return Promise.resolve();
77
+ }
78
+ setPending(true);
79
+ return Promise.resolve(result).then(commit, fail);
80
+ };
81
+ return [
82
+ state,
83
+ dispatch,
84
+ pending
85
+ ];
86
+ }
87
+ //#endregion
88
+ export { useAction };
89
+
90
+ //# sourceMappingURL=action.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"action.js","names":[],"sources":["../../src/action.ts"],"sourcesContent":["import { type Accessor, batch, currentOwner, handleError } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\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 * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,\n * tracks whether it is pending, and commits its result. The ShadowJS form of React's\n * `useActionState` (state, dispatch, pending). `previous` is the last committed state.\n *\n * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a\n * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not\n * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an\n * error boundary can show it. Without an owner the returned promise rejects instead.\n *\n * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.\n * @param initialState The state before the first dispatch.\n * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true\n * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this\n * call has finished, whether it committed or not.\n * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with\n * the action's error. With an owner, the error goes to its error handler, or is reported as an\n * uncaught error (`reportError`) when no handler is registered above it.\n * @example\n * import { useAction } from \"@shadow-js/core\";\n *\n * const [message, send, sending] = useAction(async (_prev: string, text: string) => {\n * await fetch(\"/api/messages\", { method: \"POST\", body: text });\n * return `sent: ${text}`;\n * }, \"\");\n * void send(\"hello\");\n * console.log(sending(), message());\n * @see useOptimistic\n * @see useTransition\n * @since 1.0.0\n */\nexport function useAction<S, A extends unknown[]>(\n action: (previous: S, ...args: A) => S | PromiseLike<S>,\n initialState: S,\n): [state: Accessor<S>, dispatch: (...args: A) => Promise<void>, pending: Accessor<boolean>] {\n const owner = currentOwner();\n const [state, setState] = useSignal<S>(initialState);\n const [pending, setPending] = useSignal(false);\n let latest = 0;\n\n const dispatch = (...args: A): Promise<void> => {\n latest += 1;\n const id = latest;\n const previous = untrack(state);\n const commit = (value: S): void => {\n if (id !== latest) return;\n batch(() => {\n setState(() => value);\n setPending(false);\n });\n };\n const fail = (error: unknown): void => {\n if (id !== latest) return;\n setPending(false);\n if (owner === null) throw error;\n handleError(error, owner);\n };\n let result: S | PromiseLike<S>;\n try {\n result = untrack(() => action(previous, ...args));\n } catch (error) {\n if (owner === null) {\n // `fail` would rethrow synchronously; without an owner the promise carries the error.\n if (id === latest) setPending(false);\n return Promise.reject(error);\n }\n fail(error);\n return Promise.resolve();\n }\n if (!isPromiseLike<S>(result)) {\n commit(result);\n return Promise.resolve();\n }\n setPending(true);\n return Promise.resolve(result).then(commit, fail);\n };\n return [state, dispatch, pending];\n}\n"],"mappings":";;;;;;AAIA,SAAS,cAAiB,OAAyC;CACjE,OACE,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,UACd,QACA,cAC2F;CAC3F,MAAM,QAAQ,aAAa;CAC3B,MAAM,CAAC,OAAO,YAAY,UAAa,YAAY;CACnD,MAAM,CAAC,SAAS,cAAc,UAAU,KAAK;CAC7C,IAAI,SAAS;CAEb,MAAM,YAAY,GAAG,SAA2B;EAC9C,UAAU;EACV,MAAM,KAAK;EACX,MAAM,WAAW,QAAQ,KAAK;EAC9B,MAAM,UAAU,UAAmB;GACjC,IAAI,OAAO,QAAQ;GACnB,YAAY;IACV,eAAe,KAAK;IACpB,WAAW,KAAK;GAClB,CAAC;EACH;EACA,MAAM,QAAQ,UAAyB;GACrC,IAAI,OAAO,QAAQ;GACnB,WAAW,KAAK;GAChB,IAAI,UAAU,MAAM,MAAM;GAC1B,YAAY,OAAO,KAAK;EAC1B;EACA,IAAI;EACJ,IAAI;GACF,SAAS,cAAc,OAAO,UAAU,GAAG,IAAI,CAAC;EAClD,SAAS,OAAO;GACd,IAAI,UAAU,MAAM;IAElB,IAAI,OAAO,QAAQ,WAAW,KAAK;IACnC,OAAO,QAAQ,OAAO,KAAK;GAC7B;GACA,KAAK,KAAK;GACV,OAAO,QAAQ,QAAQ;EACzB;EACA,IAAI,CAAC,cAAiB,MAAM,GAAG;GAC7B,OAAO,MAAM;GACb,OAAO,QAAQ,QAAQ;EACzB;EACA,WAAW,IAAI;EACf,OAAO,QAAQ,QAAQ,MAAM,CAAC,CAAC,KAAK,QAAQ,IAAI;CAClD;CACA,OAAO;EAAC;EAAO;EAAU;CAAO;AAClC"}
@@ -0,0 +1,62 @@
1
+ import { currentOwner } from "./extend/index.js";
2
+ //#region src/cache.ts
3
+ function sameArgs(a, b) {
4
+ if (a.length !== b.length) return false;
5
+ for (let i = 0; i < a.length; i += 1) if (!Object.is(a[i], b[i])) return false;
6
+ return true;
7
+ }
8
+ /** The outermost owner: the root of the render (a request on the server, the app on the client). */
9
+ function rootOf(owner) {
10
+ let root = owner;
11
+ while (root !== null && root.parent !== null) root = root.parent;
12
+ return root;
13
+ }
14
+ /**
15
+ * Memoizes `fn` per request: within one root (a server render, or the app on the client) the same
16
+ * arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,
17
+ * position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.
18
+ * A call that throws is not kept. Outside any owner nothing is scoped, so `fn` runs every time.
19
+ *
20
+ * Use it to share one data fetch between components rendered in the same request.
21
+ *
22
+ * @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.
23
+ * @param options Per-scope limit. Undefined uses the default.
24
+ * @returns A function with the same signature.
25
+ * @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in
26
+ * production builds). The returned function rethrows what `fn` throws.
27
+ * @example
28
+ * import { cache } from "@shadow-js/core";
29
+ *
30
+ * const loadUser = cache((id: string) =>
31
+ * fetch(`/api/users/${id}`).then((response) => response.json()),
32
+ * );
33
+ * // Two components calling loadUser("u1") in the same render fetch once.
34
+ * @see useResource
35
+ * @since 1.0.0
36
+ */
37
+ function cache(fn, options) {
38
+ const limit = options?.limit ?? 100;
39
+ if (!Number.isInteger(limit) || limit < 1) throw new RangeError("cache: limit must be a positive integer");
40
+ const scopes = /* @__PURE__ */ new WeakMap();
41
+ return (...args) => {
42
+ const root = rootOf(currentOwner());
43
+ if (root === null) return fn(...args);
44
+ let entries = scopes.get(root);
45
+ if (entries === void 0) {
46
+ entries = [];
47
+ scopes.set(root, entries);
48
+ }
49
+ for (const entry of entries) if (sameArgs(entry.args, args)) return entry.value;
50
+ const value = fn(...args);
51
+ entries.push({
52
+ args,
53
+ value
54
+ });
55
+ if (entries.length > limit) entries.shift();
56
+ return value;
57
+ };
58
+ }
59
+ //#endregion
60
+ export { cache };
61
+
62
+ //# sourceMappingURL=cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.js","names":[],"sources":["../../src/cache.ts"],"sourcesContent":["import { currentOwner, type Owner } from \"./extend\";\n\n/** Options of {@link cache}. @since 1.0.0 */\nexport interface CacheOptions {\n /**\n * Most results kept per scope (one root); the oldest is dropped first. A positive integer.\n * @default 100\n */\n limit?: number;\n}\n\ninterface Entry {\n readonly args: readonly unknown[];\n readonly value: unknown;\n}\n\nfunction sameArgs(a: readonly unknown[], b: readonly unknown[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (!Object.is(a[i], b[i])) return false;\n }\n return true;\n}\n\n/** The outermost owner: the root of the render (a request on the server, the app on the client). */\nfunction rootOf(owner: Owner | null): Owner | null {\n let root = owner;\n while (root !== null && root.parent !== null) root = root.parent;\n return root;\n}\n\n/**\n * Memoizes `fn` per request: within one root (a server render, or the app on the client) the same\n * arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,\n * position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.\n * A call that throws is not kept. Outside any owner nothing is scoped, so `fn` runs every time.\n *\n * Use it to share one data fetch between components rendered in the same request.\n *\n * @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.\n * @param options Per-scope limit. Undefined uses the default.\n * @returns A function with the same signature.\n * @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in\n * production builds). The returned function rethrows what `fn` throws.\n * @example\n * import { cache } from \"@shadow-js/core\";\n *\n * const loadUser = cache((id: string) =>\n * fetch(`/api/users/${id}`).then((response) => response.json()),\n * );\n * // Two components calling loadUser(\"u1\") in the same render fetch once.\n * @see useResource\n * @since 1.0.0\n */\nexport function cache<A extends unknown[], R>(\n fn: (...args: A) => R,\n options?: CacheOptions,\n): (...args: A) => R {\n const limit = options?.limit ?? 100;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new RangeError(\n __DEV__ ? \"cache: limit must be a positive integer\" : \"SHADOW_CACHE_LIMIT\",\n );\n }\n const scopes = new WeakMap<Owner, Entry[]>();\n return (...args: A): R => {\n const root = rootOf(currentOwner());\n if (root === null) return fn(...args);\n let entries = scopes.get(root);\n if (entries === undefined) {\n entries = [];\n scopes.set(root, entries);\n }\n for (const entry of entries) {\n if (sameArgs(entry.args, args)) return entry.value as R;\n }\n const value = fn(...args);\n entries.push({ args, value });\n if (entries.length > limit) entries.shift();\n return value;\n };\n}\n"],"mappings":";;AAgBA,SAAS,SAAS,GAAuB,GAAgC;CACvE,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,GACjC,IAAI,CAAC,OAAO,GAAG,EAAE,IAAI,EAAE,EAAE,GAAG,OAAO;CAErC,OAAO;AACT;;AAGA,SAAS,OAAO,OAAmC;CACjD,IAAI,OAAO;CACX,OAAO,SAAS,QAAQ,KAAK,WAAW,MAAM,OAAO,KAAK;CAC1D,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,MACd,IACA,SACmB;CACnB,MAAM,QAAQ,SAAS,SAAS;CAChC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,WACE,yCACZ;CAEF,MAAM,yBAAS,IAAI,QAAwB;CAC3C,QAAQ,GAAG,SAAe;EACxB,MAAM,OAAO,OAAO,aAAa,CAAC;EAClC,IAAI,SAAS,MAAM,OAAO,GAAG,GAAG,IAAI;EACpC,IAAI,UAAU,OAAO,IAAI,IAAI;EAC7B,IAAI,YAAY,KAAA,GAAW;GACzB,UAAU,CAAC;GACX,OAAO,IAAI,MAAM,OAAO;EAC1B;EACA,KAAK,MAAM,SAAS,SAClB,IAAI,SAAS,MAAM,MAAM,IAAI,GAAG,OAAO,MAAM;EAE/C,MAAM,QAAQ,GAAG,GAAG,IAAI;EACxB,QAAQ,KAAK;GAAE;GAAM;EAAM,CAAC;EAC5B,IAAI,QAAQ,SAAS,OAAO,QAAQ,MAAM;EAC1C,OAAO;CACT;AACF"}
@@ -0,0 +1,108 @@
1
+ import { ShadowError } from "./internal/diagnostics.js";
2
+ import { Owner } from "./internal/owner.js";
3
+ import { runWithOwner } from "./ownership.js";
4
+ import { currentOwner } from "./extend/index.js";
5
+ //#region src/context.ts
6
+ /**
7
+ * Creates a context: a value that components read with {@link useContext} without passing it
8
+ * through props. Render the returned component around a subtree to provide a value. The value is
9
+ * read once; pass a signal accessor or a store to provide something reactive. On the server the
10
+ * provider builds its subtree once.
11
+ *
12
+ * @param defaultValue Returned by `useContext` when no provider is above the reader. Undefined
13
+ * (or omitted) means the context has no default, so reading it without a provider throws.
14
+ * @param options A diagnostics name. Undefined uses the default.
15
+ * @returns The context, which is also its provider component.
16
+ * @example
17
+ * import { createContext, useContext } from "@shadow-js/core";
18
+ *
19
+ * const Theme = createContext<"light" | "dark">("light", { name: "Theme" });
20
+ *
21
+ * function Label() {
22
+ * return <p>Theme: {useContext(Theme)}</p>;
23
+ * }
24
+ *
25
+ * const app = <Theme.Provider value="dark"><Label /></Theme.Provider>;
26
+ * @see useContext
27
+ * @since 1.0.0
28
+ */
29
+ function createContext(defaultValue, options) {
30
+ const id = Symbol(options?.name ?? "context");
31
+ const provider = (props) => {
32
+ const scope = new Owner(currentOwner());
33
+ const inherited = scope.context;
34
+ const next = Object.create(inherited);
35
+ next[id] = props.value;
36
+ scope.context = next;
37
+ return runWithOwner(scope, () => {
38
+ {
39
+ const built = props.children;
40
+ return () => built;
41
+ }
42
+ });
43
+ };
44
+ return Object.assign(provider, {
45
+ id,
46
+ defaultValue,
47
+ Provider: provider
48
+ });
49
+ }
50
+ /**
51
+ * Runs `fn` with `value` provided for `context` (as a Provider does), without a render effect: the
52
+ * value is set for the duration of `fn` only, and what `fn` creates sees it. Used where a renderer
53
+ * builds a subtree that must not be re-run by a Provider's effect. `fn` runs untracked, in a new
54
+ * child owner of the current owner that is disposed with it.
55
+ *
56
+ * @param context The context to provide.
57
+ * @param value The value `useContext(context)` returns inside `fn`.
58
+ * @param fn Runs once, synchronously.
59
+ * @returns What `fn` returns.
60
+ * @example
61
+ * import { createContext, useContext } from "@shadow-js/core";
62
+ * import { runWithContext } from "@shadow-js/core/extend";
63
+ *
64
+ * const Theme = createContext("light");
65
+ * const theme = runWithContext(Theme, "dark", () => useContext(Theme));
66
+ * console.log(theme); // "dark"
67
+ * @see createContext
68
+ * @since 1.0.0
69
+ */
70
+ function runWithContext(context, value, fn) {
71
+ const scope = new Owner(currentOwner());
72
+ const next = Object.create(scope.context);
73
+ next[context.id] = value;
74
+ scope.context = next;
75
+ return runWithOwner(scope, fn);
76
+ }
77
+ /**
78
+ * Reads the nearest provided value of `context`. Falls back to its default; throws when there is
79
+ * neither a provider nor a default, because no correct value exists. The lookup follows the current
80
+ * owner, so call it while a component runs (or in an effect or memo it creates), not after an
81
+ * `await` or in an event handler. The read is not tracked.
82
+ *
83
+ * @param context A context made by {@link createContext}.
84
+ * @returns The value of the nearest provider above the current owner, else the default value.
85
+ * @throws ShadowError `CONTEXT_MISSING` when no provider is above the current owner and the
86
+ * context's default is `undefined`.
87
+ * @example
88
+ * import { createContext, useContext } from "@shadow-js/core";
89
+ *
90
+ * const User = createContext<{ name: string }>();
91
+ *
92
+ * function Greeting() {
93
+ * const user = useContext(User); // throws CONTEXT_MISSING without a provider
94
+ * return <p>Hello, {user.name}</p>;
95
+ * }
96
+ * @see createContext
97
+ * @since 1.0.0
98
+ */
99
+ function useContext(context) {
100
+ const map = currentOwner()?.context;
101
+ if (map !== null && map !== void 0 && context.id in map) return map[context.id];
102
+ if (context.defaultValue === void 0) throw new ShadowError("CONTEXT_MISSING");
103
+ return context.defaultValue;
104
+ }
105
+ //#endregion
106
+ export { createContext, runWithContext, useContext };
107
+
108
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","names":[],"sources":["../../src/context.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { currentOwner, Owner, ShadowError } from \"./extend\";\nimport { runWithOwner } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * A context made by {@link createContext}: a value that a subtree receives from the nearest provider\n * above it. The context is itself the provider component; `Provider` is the same function.\n * @since 1.0.0\n */\nexport interface Context<T> {\n /**\n * Renders `children` with `value` provided. The value is read once, when the provider is created;\n * provide an accessor or a store for a value that changes. Returns an accessor of the children.\n */\n (props: { value: T; children?: unknown }): unknown;\n /** The unique key the provided value is stored under, described by the context's `name`. */\n readonly id: symbol;\n /** The value {@link useContext} returns without a provider. `undefined` means none: it throws. */\n readonly defaultValue: T | undefined;\n /** The same component, for code written as `<Ctx.Provider value={...}>`. */\n readonly Provider: (props: { value: T; children?: unknown }) => unknown;\n}\n\n/**\n * Options of {@link createContext}.\n * @since 1.0.0\n */\nexport interface ContextOptions {\n /**\n * Label shown in diagnostics and used as the description of the context's `id` symbol.\n * @default \"context\"\n */\n name?: string;\n}\n\n/**\n * Creates a context: a value that components read with {@link useContext} without passing it\n * through props. Render the returned component around a subtree to provide a value. The value is\n * read once; pass a signal accessor or a store to provide something reactive. On the server the\n * provider builds its subtree once.\n *\n * @param defaultValue Returned by `useContext` when no provider is above the reader. Undefined\n * (or omitted) means the context has no default, so reading it without a provider throws.\n * @param options A diagnostics name. Undefined uses the default.\n * @returns The context, which is also its provider component.\n * @example\n * import { createContext, useContext } from \"@shadow-js/core\";\n *\n * const Theme = createContext<\"light\" | \"dark\">(\"light\", { name: \"Theme\" });\n *\n * function Label() {\n * return <p>Theme: {useContext(Theme)}</p>;\n * }\n *\n * const app = <Theme.Provider value=\"dark\"><Label /></Theme.Provider>;\n * @see useContext\n * @since 1.0.0\n */\nexport function createContext<T>(defaultValue?: T, options?: ContextOptions): Context<T> {\n const id = Symbol(options?.name ?? \"context\");\n const provider = (props: { value: T; children?: unknown }): unknown => {\n const scope = new Owner(currentOwner());\n const inherited = scope.context;\n const next = Object.create(inherited) as Record<symbol, unknown>;\n next[id] = props.value;\n scope.context = next;\n // A render effect, so a children expression that reads signals stays reactive and still sees\n // the provided value. An effect (not a memo) because component setup may legitimately write\n // signals, and errors thrown while building the subtree must reach the error boundaries.\n return runWithOwner(scope, () => {\n if (__SERVER__) {\n // Nothing is reactive on the server: build the subtree once.\n const built = props.children;\n return () => built;\n }\n const [children, setChildren] = useSignal<unknown>(undefined, { equals: false });\n useRenderEffect(\n () => props.children,\n (value) => {\n setChildren(() => value);\n },\n );\n return children;\n });\n };\n return Object.assign(provider, { id, defaultValue, Provider: provider }) as Context<T>;\n}\n\n/**\n * Runs `fn` with `value` provided for `context` (as a Provider does), without a render effect: the\n * value is set for the duration of `fn` only, and what `fn` creates sees it. Used where a renderer\n * builds a subtree that must not be re-run by a Provider's effect. `fn` runs untracked, in a new\n * child owner of the current owner that is disposed with it.\n *\n * @param context The context to provide.\n * @param value The value `useContext(context)` returns inside `fn`.\n * @param fn Runs once, synchronously.\n * @returns What `fn` returns.\n * @example\n * import { createContext, useContext } from \"@shadow-js/core\";\n * import { runWithContext } from \"@shadow-js/core/extend\";\n *\n * const Theme = createContext(\"light\");\n * const theme = runWithContext(Theme, \"dark\", () => useContext(Theme));\n * console.log(theme); // \"dark\"\n * @see createContext\n * @since 1.0.0\n */\nexport function runWithContext<T, R>(context: Context<T>, value: T, fn: () => R): R {\n const scope = new Owner(currentOwner());\n const next = Object.create(scope.context) as Record<symbol, unknown>;\n next[context.id] = value;\n scope.context = next;\n return runWithOwner(scope, fn);\n}\n\n/**\n * Reads the nearest provided value of `context`. Falls back to its default; throws when there is\n * neither a provider nor a default, because no correct value exists. The lookup follows the current\n * owner, so call it while a component runs (or in an effect or memo it creates), not after an\n * `await` or in an event handler. The read is not tracked.\n *\n * @param context A context made by {@link createContext}.\n * @returns The value of the nearest provider above the current owner, else the default value.\n * @throws ShadowError `CONTEXT_MISSING` when no provider is above the current owner and the\n * context's default is `undefined`.\n * @example\n * import { createContext, useContext } from \"@shadow-js/core\";\n *\n * const User = createContext<{ name: string }>();\n *\n * function Greeting() {\n * const user = useContext(User); // throws CONTEXT_MISSING without a provider\n * return <p>Hello, {user.name}</p>;\n * }\n * @see createContext\n * @since 1.0.0\n */\nexport function useContext<T>(context: Context<T>): T {\n const map = currentOwner()?.context;\n if (map !== null && map !== undefined && context.id in map) return map[context.id] as T;\n if (context.defaultValue === undefined) throw new ShadowError(\"CONTEXT_MISSING\");\n return context.defaultValue;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,cAAiB,cAAkB,SAAsC;CACvF,MAAM,KAAK,OAAO,SAAS,QAAQ,SAAS;CAC5C,MAAM,YAAY,UAAqD;EACrE,MAAM,QAAQ,IAAI,MAAM,aAAa,CAAC;EACtC,MAAM,YAAY,MAAM;EACxB,MAAM,OAAO,OAAO,OAAO,SAAS;EACpC,KAAK,MAAM,MAAM;EACjB,MAAM,UAAU;EAIhB,OAAO,aAAa,aAAa;GACf;IAEd,MAAM,QAAQ,MAAM;IACpB,aAAa;GACf;EASF,CAAC;CACH;CACA,OAAO,OAAO,OAAO,UAAU;EAAE;EAAI;EAAc,UAAU;CAAS,CAAC;AACzE;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,eAAqB,SAAqB,OAAU,IAAgB;CAClF,MAAM,QAAQ,IAAI,MAAM,aAAa,CAAC;CACtC,MAAM,OAAO,OAAO,OAAO,MAAM,OAAO;CACxC,KAAK,QAAQ,MAAM;CACnB,MAAM,UAAU;CAChB,OAAO,aAAa,OAAO,EAAE;AAC/B;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,WAAc,SAAwB;CACpD,MAAM,MAAM,aAAa,CAAC,EAAE;CAC5B,IAAI,QAAQ,QAAQ,QAAQ,KAAA,KAAa,QAAQ,MAAM,KAAK,OAAO,IAAI,QAAQ;CAC/E,IAAI,QAAQ,iBAAiB,KAAA,GAAW,MAAM,IAAI,YAAY,iBAAiB;CAC/E,OAAO,QAAQ;AACjB"}
@@ -0,0 +1,56 @@
1
+ import { warn } from "./internal/diagnostics.js";
2
+ //#region src/effect.ts
3
+ function useEffect(first, second, third) {
4
+ if (typeof second === "function") third?.defer, third?.name;
5
+ else {
6
+ if (Array.isArray(second)) warn("EFFECT_DEPS_IGNORED");
7
+ second?.name;
8
+ }
9
+ }
10
+ /**
11
+ * Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and
12
+ * before user effects on every flush. Used for DOM bindings; application code rarely needs it.
13
+ * It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In
14
+ * development, one created outside any owner warns `NO_OWNER_EFFECT`.
15
+ *
16
+ * @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself
17
+ * and may return a cleanup function.
18
+ * @param apply Untracked; receives the value and the previous value (`undefined` on the first
19
+ * run), and may return a cleanup function. Undefined: only `compute` runs.
20
+ * @example
21
+ * import { createRoot, useRenderEffect, useSignal } from "@shadow-js/core";
22
+ *
23
+ * const button = document.createElement("button");
24
+ * createRoot(() => {
25
+ * const [label] = useSignal("Save");
26
+ * useRenderEffect(label, (text) => {
27
+ * button.textContent = text; // runs now, and again when label changes
28
+ * });
29
+ * });
30
+ * @see useEffect
31
+ * @since 1.0.0
32
+ */
33
+ function useRenderEffect(compute, apply) {}
34
+ /**
35
+ * Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never
36
+ * run it again. Its return value, if a function, is the cleanup, which runs when the owner is
37
+ * disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`
38
+ * boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.
39
+ *
40
+ * @param fn Runs once, untracked. It may return a cleanup function.
41
+ * @example
42
+ * import { onMount } from "@shadow-js/core";
43
+ *
44
+ * function SearchBox() {
45
+ * let input: HTMLInputElement | undefined;
46
+ * onMount(() => input?.focus());
47
+ * return <input ref={(el: HTMLInputElement) => (input = el)} />;
48
+ * }
49
+ * @see useEffect
50
+ * @since 1.0.0
51
+ */
52
+ function onMount(fn) {}
53
+ //#endregion
54
+ export { onMount, useEffect, useRenderEffect };
55
+
56
+ //# sourceMappingURL=effect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"effect.js","names":[],"sources":["../../src/effect.ts"],"sourcesContent":["import { type Cleanup, createComputation, currentOwner, warn } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.\n * @since 1.0.0\n */\nexport interface EffectOptions {\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the effect is unnamed)\n */\n name?: string;\n}\n\n/**\n * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.\n * @since 1.0.0\n */\nexport interface DeferredEffectOptions extends EffectOptions {\n /**\n * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only\n * runs for later changes of it.\n * @default false\n */\n defer?: boolean;\n}\n\n/** What a held effect computes while its gate is closed: nothing for `apply` to act on. */\nconst HELD: unique symbol = Symbol(\"held\");\n\n/** The nearest gate above the current owner (see `Owner.gate`), or null. */\nfunction nearestGate(): (() => boolean) | null {\n for (let owner = currentOwner(); owner !== null; owner = owner.parent) {\n if (owner.gate !== null) return owner.gate;\n }\n return null;\n}\n\nfunction createEffect(\n fnIn: (previous: never) => unknown,\n applyIn: ((value: never, previous: never) => unknown) | null,\n render: boolean,\n deferIn: boolean,\n name: string | undefined,\n): void {\n // Effects never run on the server (G-24): no node, no ownership slot, no cost.\n if (__SERVER__) return;\n if (currentOwner() === null) warn(\"NO_OWNER_EFFECT\");\n let fn = fnIn;\n let apply = applyIn;\n let defer = deferIn;\n const gate = render ? null : nearestGate();\n if (gate !== null) {\n // Held until the gate first opens (a Suspense boundary resolving). The gate is only read until\n // then, so later changes of it never re-run the effect.\n let opened = false;\n const held = (): boolean => {\n if (opened) return false;\n if (gate()) return true;\n opened = true;\n return false;\n };\n if (apply === null) {\n const inner = fn;\n fn = (previous) => (held() ? undefined : inner(previous));\n } else {\n const innerFn = fn;\n const innerApply = apply;\n // `defer` skips the first real run, not the held one, so it is handled here.\n let skipFirst = defer;\n defer = false;\n fn = (previous) => (held() ? HELD : innerFn(previous));\n apply = (value, previous) => {\n if ((value as unknown) === HELD) return undefined;\n if (skipFirst) {\n skipFirst = false;\n return undefined;\n }\n return innerApply(value, ((previous as unknown) === HELD ? undefined : previous) as never);\n };\n }\n }\n createComputation({\n kind: \"effect\",\n fn,\n render,\n defer,\n ...(apply === null ? {} : { apply }),\n ...(name === undefined ? {} : { name }),\n });\n}\n\n/**\n * Runs a side effect after rendering and again whenever a tracked signal changes. The first run\n * is deferred to the next flush. Effects never run on the server. Inside a `<Suspense>` boundary\n * that is still showing its fallback, the first run waits until the boundary first shows its content.\n *\n * Two forms: `useEffect(fn)` tracks everything `fn` reads; `useEffect(deps, fn)` tracks only\n * `deps` and runs `fn` untracked. Return a function to clean up before the next run or disposal.\n * An error thrown by the effect goes to the owner's error handler (`onError`, an error boundary).\n * In development, an effect created outside any owner warns `NO_OWNER_EFFECT`: it still runs, but\n * nothing can dispose it.\n *\n * @param fn The effect. Every signal it reads is tracked. It may return a cleanup function.\n * @param options A devtools name. Undefined uses the default.\n * @example\n * import { useEffect, useSignal } from \"@shadow-js/core\";\n *\n * function PageTitle(props: { unread: number }) {\n * const [title] = useSignal(\"Inbox\");\n * useEffect(() => {\n * document.title = `${title()} (${props.unread})`; // re-runs when either changes\n * });\n * return null;\n * }\n * @see useRenderEffect\n * @see onMount\n * @since 1.0.0\n */\nexport function useEffect(fn: () => void | Cleanup, options?: EffectOptions): void;\n/**\n * Explicit-dependency form of {@link useEffect}: tracks only what `deps` reads, and calls `fn`\n * untracked with the new and the previous value of `deps`. Use it when the effect body reads\n * signals that must not re-run it.\n *\n * @param deps Tracked; its result is passed to `fn`.\n * @param fn Untracked; receives the value of `deps` and its previous value (`undefined` when there\n * is none yet). It may return a cleanup function, which runs before the next call or on disposal.\n * @param options `defer` skips the first call; a devtools name. Undefined uses the defaults.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n *\n * function Profile(props: { userId: string }) {\n * useEffect(\n * () => props.userId,\n * (next, previous) => console.log(`switched from ${previous} to ${next}`),\n * { defer: true }, // not called for the first id\n * );\n * return null;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useEffect<T>(\n deps: () => T,\n fn: (value: T, previous: T | undefined) => void | Cleanup,\n options?: DeferredEffectOptions,\n): void;\nexport function useEffect(\n first: () => unknown,\n second?: unknown,\n third?: DeferredEffectOptions,\n): void {\n if (typeof second === \"function\") {\n createEffect(\n first,\n second as (value: never, previous: never) => unknown,\n false,\n third?.defer === true,\n third?.name,\n );\n } else {\n if (Array.isArray(second)) warn(\"EFFECT_DEPS_IGNORED\");\n createEffect(first, null, false, false, (second as EffectOptions | undefined)?.name);\n }\n}\n\n/**\n * Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and\n * before user effects on every flush. Used for DOM bindings; application code rarely needs it.\n * It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In\n * development, one created outside any owner warns `NO_OWNER_EFFECT`.\n *\n * @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself\n * and may return a cleanup function.\n * @param apply Untracked; receives the value and the previous value (`undefined` on the first\n * run), and may return a cleanup function. Undefined: only `compute` runs.\n * @example\n * import { createRoot, useRenderEffect, useSignal } from \"@shadow-js/core\";\n *\n * const button = document.createElement(\"button\");\n * createRoot(() => {\n * const [label] = useSignal(\"Save\");\n * useRenderEffect(label, (text) => {\n * button.textContent = text; // runs now, and again when label changes\n * });\n * });\n * @see useEffect\n * @since 1.0.0\n */\nexport function useRenderEffect<T>(\n compute: () => T,\n apply?: (value: T, previous: T | undefined) => void | Cleanup,\n): void {\n createEffect(\n compute,\n (apply ?? null) as ((value: never, previous: never) => unknown) | null,\n true,\n false,\n undefined,\n );\n}\n\n/**\n * Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never\n * run it again. Its return value, if a function, is the cleanup, which runs when the owner is\n * disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`\n * boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.\n *\n * @param fn Runs once, untracked. It may return a cleanup function.\n * @example\n * import { onMount } from \"@shadow-js/core\";\n *\n * function SearchBox() {\n * let input: HTMLInputElement | undefined;\n * onMount(() => input?.focus());\n * return <input ref={(el: HTMLInputElement) => (input = el)} />;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function onMount(fn: () => void | Cleanup): void {\n createEffect(() => untrack(fn), null, false, false, \"onMount\");\n}\n"],"mappings":";;AAqJA,SAAgB,UACd,OACA,QACA,OACM;CACN,IAAI,OAAO,WAAW,YACpB,OAIS,OACP,OAAO;MAEJ;EACL,IAAI,MAAM,QAAQ,MAAM,GAAG,KAAK,qBAAqB;EACrD,QAA+E;CACjF;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,gBACd,SACA,OACM,CAQR;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,QAAQ,IAAgC,CAExD"}