@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,39 @@
1
+ import { Mutable, Store } from "./types.js";
2
+ //#region src/store/read.d.ts
3
+ /**
4
+ * Returns the raw data behind a store. Reads and writes on the result bypass tracking and
5
+ * notification, so writing to it is a bug; use it for identity checks and passing data on.
6
+ *
7
+ * @param store A store view. A value that is not a store view is returned as is.
8
+ * @returns The underlying object, without proxies. It is the live data, not a copy.
9
+ * @example
10
+ * import { unwrap, useStore } from "@shadow-js/core";
11
+ *
12
+ * const initial = { items: [1, 2, 3] };
13
+ * const [list] = useStore(initial);
14
+ * console.log(unwrap(list) === initial); // true: the store wraps its data in place
15
+ * @see snapshot
16
+ * @since 1.0.0
17
+ */
18
+ export declare function unwrap<T>(store: Store<T>): Mutable<T>;
19
+ /**
20
+ * Returns a deep plain copy of a store's current data. It reads raw data directly, so it does
21
+ * not subscribe the running computation, and the copy is independent of later writes. Cycles and
22
+ * shared objects are preserved. The walk is iterative, so deep data cannot overflow the stack. Use
23
+ * it to serialize a store, send it to a server or keep an undo history.
24
+ *
25
+ * @param store A store view. A value that is not plain data is returned as is.
26
+ * @returns A plain, untracked deep copy.
27
+ * @example
28
+ * import { snapshot, useStore } from "@shadow-js/core";
29
+ *
30
+ * const [form, setForm] = useStore({ name: "Ada", tags: ["admin"] });
31
+ * const saved = snapshot(form);
32
+ * setForm({ name: "Grace" });
33
+ * console.log(saved.name, JSON.stringify(saved)); // Ada {"name":"Ada","tags":["admin"]}
34
+ * @see unwrap
35
+ * @since 1.0.0
36
+ */
37
+ export declare function snapshot<T>(store: Store<T>): Mutable<T>;
38
+ //#endregion
39
+ //# sourceMappingURL=read.d.ts.map
@@ -0,0 +1,72 @@
1
+ import { isReservedKey, isWrappable, readRaw, unwrapValue } from "./nodes.js";
2
+ //#region src/store/read.ts
3
+ /**
4
+ * Returns the raw data behind a store. Reads and writes on the result bypass tracking and
5
+ * notification, so writing to it is a bug; use it for identity checks and passing data on.
6
+ *
7
+ * @param store A store view. A value that is not a store view is returned as is.
8
+ * @returns The underlying object, without proxies. It is the live data, not a copy.
9
+ * @example
10
+ * import { unwrap, useStore } from "@shadow-js/core";
11
+ *
12
+ * const initial = { items: [1, 2, 3] };
13
+ * const [list] = useStore(initial);
14
+ * console.log(unwrap(list) === initial); // true: the store wraps its data in place
15
+ * @see snapshot
16
+ * @since 1.0.0
17
+ */
18
+ function unwrap(store) {
19
+ return unwrapValue(store);
20
+ }
21
+ /** A new, empty container of the same kind as `value`, with the same length for arrays. */
22
+ function shellOf(value) {
23
+ return Array.isArray(value) ? new Array(value.length) : {};
24
+ }
25
+ /**
26
+ * Returns a deep plain copy of a store's current data. It reads raw data directly, so it does
27
+ * not subscribe the running computation, and the copy is independent of later writes. Cycles and
28
+ * shared objects are preserved. The walk is iterative, so deep data cannot overflow the stack. Use
29
+ * it to serialize a store, send it to a server or keep an undo history.
30
+ *
31
+ * @param store A store view. A value that is not plain data is returned as is.
32
+ * @returns A plain, untracked deep copy.
33
+ * @example
34
+ * import { snapshot, useStore } from "@shadow-js/core";
35
+ *
36
+ * const [form, setForm] = useStore({ name: "Ada", tags: ["admin"] });
37
+ * const saved = snapshot(form);
38
+ * setForm({ name: "Grace" });
39
+ * console.log(saved.name, JSON.stringify(saved)); // Ada {"name":"Ada","tags":["admin"]}
40
+ * @see unwrap
41
+ * @since 1.0.0
42
+ */
43
+ function snapshot(store) {
44
+ const root = unwrapValue(store);
45
+ if (!isWrappable(root)) return root;
46
+ const copies = /* @__PURE__ */ new Map();
47
+ const out = shellOf(root);
48
+ copies.set(root, out);
49
+ const pending = [root];
50
+ for (let source = pending.pop(); source !== void 0; source = pending.pop()) {
51
+ const copy = copies.get(source);
52
+ if (copy === void 0) continue;
53
+ for (const key of Object.keys(source)) {
54
+ if (isReservedKey(key)) continue;
55
+ const value = unwrapValue(readRaw(source, key));
56
+ if (isWrappable(value)) {
57
+ let child = copies.get(value);
58
+ if (child === void 0) {
59
+ child = shellOf(value);
60
+ copies.set(value, child);
61
+ pending.push(value);
62
+ }
63
+ Reflect.set(copy, key, child);
64
+ } else Reflect.set(copy, key, value);
65
+ }
66
+ }
67
+ return out;
68
+ }
69
+ //#endregion
70
+ export { snapshot, unwrap };
71
+
72
+ //# sourceMappingURL=read.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read.js","names":[],"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":";;;;;;;;;;;;;;;;;AAkBA,SAAgB,OAAU,OAA6B;CACrD,OAAO,YAAY,KAAK;AAC1B;;AAGA,SAAS,QAAQ,OAAuB;CACtC,OAAO,MAAM,QAAQ,KAAK,IAAI,IAAI,MAAgB,MAAoB,MAAM,IAAI,CAAC;AACnF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,SAAY,OAA6B;CACvD,MAAM,OAAO,YAAY,KAAK;CAC9B,IAAI,CAAC,YAAY,IAAI,GAAG,OAAO;CAC/B,MAAM,yBAAS,IAAI,IAAoB;CACvC,MAAM,MAAc,QAAQ,IAAI;CAChC,OAAO,IAAI,MAAM,GAAG;CACpB,MAAM,UAAoB,CAAC,IAAI;CAC/B,KAAK,IAAI,SAAS,QAAQ,IAAI,GAAG,WAAW,KAAA,GAAW,SAAS,QAAQ,IAAI,GAAG;EAC7E,MAAM,OAAO,OAAO,IAAI,MAAM;EAC9B,IAAI,SAAS,KAAA,GAAW;EACxB,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG;GACrC,IAAI,cAAc,GAAG,GAAG;GACxB,MAAM,QAAQ,YAAY,QAAQ,QAAQ,GAAG,CAAC;GAC9C,IAAI,YAAY,KAAK,GAAG;IACtB,IAAI,QAAQ,OAAO,IAAI,KAAK;IAC5B,IAAI,UAAU,KAAA,GAAW;KACvB,QAAQ,QAAQ,KAAK;KACrB,OAAO,IAAI,OAAO,KAAK;KACvB,QAAQ,KAAK,KAAK;IACpB;IACA,QAAQ,IAAI,MAAM,KAAK,KAAK;GAC9B,OACE,QAAQ,IAAI,MAAM,KAAK,KAAK;EAEhC;CACF;CACA,OAAO;AACT"}
@@ -0,0 +1,73 @@
1
+ import { Reconciler } from "./types.js";
2
+ //#region src/store/reconcile.d.ts
3
+ /**
4
+ * Options of {@link reconcile}.
5
+ * @since 1.0.0
6
+ */
7
+ export interface ReconcileOptions {
8
+ /**
9
+ * Identity of array items: the name of a field (`"id"`) or a function returning the identity.
10
+ * Items without an identity (not an object, or the field is absent, or the function returns
11
+ * `undefined`) are matched by position.
12
+ * @default "id"
13
+ */
14
+ key?: string | ((item: unknown) => unknown);
15
+ /**
16
+ * Keep keys, and array items, that `next` does not contain. When false, keys missing from `next`
17
+ * are deleted and arrays are truncated to its length; when true, unmatched old array items are
18
+ * kept after the new ones.
19
+ * @default false
20
+ */
21
+ merge?: boolean;
22
+ }
23
+ /**
24
+ * Describes a new value for a store. Passed to `setStore`, it changes only what differs from the
25
+ * current state: objects are merged key by key, arrays are matched by `key` so retained items keep
26
+ * their identity, and unchanged leaves are not written. Nothing is applied until `setStore` runs.
27
+ * Use it to apply fresh server data to a store without re-rendering what did not change.
28
+ *
29
+ * @param next The desired data. Store proxies are accepted and unwrapped.
30
+ * @param options Item identity (`key`) and whether to keep absent keys (`merge`). Undefined uses
31
+ * the defaults (`key: "id"`, `merge: false`).
32
+ * @returns A reconciler to pass to `setStore`, alone or as the last argument of a path.
33
+ * @throws TypeError (production message `SHADOW_STORE_RECONCILE`) when the returned reconciler is
34
+ * called directly instead of being passed to `setStore`. `setStore` throws TypeError
35
+ * (`SHADOW_STORE_RECONCILE_SHAPE`) when `next` is not the same kind of container (object or
36
+ * array) as the value it reconciles.
37
+ * @example
38
+ * import { reconcile, useStore } from "@shadow-js/core";
39
+ *
40
+ * interface Todo { id: number; title: string; done: boolean }
41
+ * const [todos, setTodos] = useStore({ items: [] as Todo[] });
42
+ *
43
+ * async function refresh(): Promise<void> {
44
+ * const response = await fetch("/api/todos");
45
+ * setTodos("items", reconcile((await response.json()) as Todo[], { key: "id" }));
46
+ * }
47
+ * @see useStore
48
+ * @since 1.0.0
49
+ */
50
+ export declare function reconcile<T>(next: T, options?: ReconcileOptions): Reconciler<T>;
51
+ /**
52
+ * Marks a draft updater. It is the function itself (`setStore(produce((d) => { d.n += 1 }))` is
53
+ * `setStore((d) => { d.n += 1 })`); it exists so code written for other libraries migrates as is.
54
+ *
55
+ * @param update The draft updater: it mutates the draft it receives.
56
+ * @returns `update`, unchanged.
57
+ * @example
58
+ * import { produce, useStore } from "@shadow-js/core";
59
+ *
60
+ * const [cart, setCart] = useStore({ items: [] as string[], count: 0 });
61
+ * setCart(
62
+ * produce((draft) => {
63
+ * draft.items.push("apple");
64
+ * draft.count += 1;
65
+ * }),
66
+ * );
67
+ * console.log(cart.count); // 1
68
+ * @see useStore
69
+ * @since 1.0.0
70
+ */
71
+ export declare function produce<T>(update: (draft: T) => void): (draft: T) => void;
72
+ //#endregion
73
+ //# sourceMappingURL=reconcile.d.ts.map
@@ -0,0 +1,186 @@
1
+ import { deleteRaw, isReservedKey, isWrappable, unwrapValue, writeRaw } from "./nodes.js";
2
+ //#region src/store/reconcile.ts
3
+ /** Each reconciler function maps to its spec. Keys are the reconciler functions themselves. */
4
+ const SPECS = /* @__PURE__ */ new WeakMap();
5
+ /**
6
+ * Looks up the spec of a reconciler created by {@link reconcile}. Not re-exported by any entry: the
7
+ * store setter uses it to tell a reconciler from a draft updater.
8
+ *
9
+ * @param update Any function or object passed to `setStore`.
10
+ * @returns The spec, or `undefined` when `update` is not a `reconcile()` result.
11
+ * @internal
12
+ */
13
+ function specOf(update) {
14
+ return SPECS.get(update);
15
+ }
16
+ /**
17
+ * Describes a new value for a store. Passed to `setStore`, it changes only what differs from the
18
+ * current state: objects are merged key by key, arrays are matched by `key` so retained items keep
19
+ * their identity, and unchanged leaves are not written. Nothing is applied until `setStore` runs.
20
+ * Use it to apply fresh server data to a store without re-rendering what did not change.
21
+ *
22
+ * @param next The desired data. Store proxies are accepted and unwrapped.
23
+ * @param options Item identity (`key`) and whether to keep absent keys (`merge`). Undefined uses
24
+ * the defaults (`key: "id"`, `merge: false`).
25
+ * @returns A reconciler to pass to `setStore`, alone or as the last argument of a path.
26
+ * @throws TypeError (production message `SHADOW_STORE_RECONCILE`) when the returned reconciler is
27
+ * called directly instead of being passed to `setStore`. `setStore` throws TypeError
28
+ * (`SHADOW_STORE_RECONCILE_SHAPE`) when `next` is not the same kind of container (object or
29
+ * array) as the value it reconciles.
30
+ * @example
31
+ * import { reconcile, useStore } from "@shadow-js/core";
32
+ *
33
+ * interface Todo { id: number; title: string; done: boolean }
34
+ * const [todos, setTodos] = useStore({ items: [] as Todo[] });
35
+ *
36
+ * async function refresh(): Promise<void> {
37
+ * const response = await fetch("/api/todos");
38
+ * setTodos("items", reconcile((await response.json()) as Todo[], { key: "id" }));
39
+ * }
40
+ * @see useStore
41
+ * @since 1.0.0
42
+ */
43
+ function reconcile(next, options) {
44
+ const spec = {
45
+ next,
46
+ key: options?.key ?? "id",
47
+ merge: options?.merge === true
48
+ };
49
+ const reconciler = () => {
50
+ throw new TypeError("ShadowStore: a reconcile() result must be passed to setStore()");
51
+ };
52
+ SPECS.set(reconciler, spec);
53
+ return reconciler;
54
+ }
55
+ /** Field name or function giving an item's identity; `undefined` means the item has none. */
56
+ function identityOf(item, key) {
57
+ if (!isWrappable(item)) return void 0;
58
+ if (typeof key === "function") return key(item);
59
+ return Object.hasOwn(item, key) ? Reflect.get(item, key) : void 0;
60
+ }
61
+ /** Same container kind: both arrays or both objects. */
62
+ function sameKind(a, b) {
63
+ return Array.isArray(a) === Array.isArray(b);
64
+ }
65
+ /**
66
+ * Applies a reconciler to the store root. The diff is iterative: pending (target, source) pairs
67
+ * live on an explicit stack, so data nested thousands of levels deep cannot overflow the call
68
+ * stack. Each pair is visited once, which also terminates on cyclic input. Not re-exported by any
69
+ * entry: only the store setter calls it, inside its transaction.
70
+ *
71
+ * @param root The raw (unwrapped) object or array to update in place.
72
+ * @param spec The reconciler's spec, from {@link specOf}.
73
+ * @param label The store label for messages (` (name)`, or an empty string).
74
+ * @throws TypeError (production message `SHADOW_STORE_RECONCILE_SHAPE`) when `spec.next` is not the
75
+ * same kind of container as `root`.
76
+ * @internal
77
+ */
78
+ function applyReconcile(root, spec, label) {
79
+ const next = unwrapValue(spec.next);
80
+ if (!isWrappable(next) || !sameKind(root, next)) throw new TypeError(`ShadowStore${label}: reconcile() needs data of the same shape as the store root (an object or an array)`);
81
+ const stack = [];
82
+ const seen = /* @__PURE__ */ new Map();
83
+ const enqueue = (target, source) => {
84
+ let targets = seen.get(source);
85
+ if (targets === void 0) {
86
+ targets = /* @__PURE__ */ new Set();
87
+ seen.set(source, targets);
88
+ }
89
+ if (targets.has(target)) return;
90
+ targets.add(target);
91
+ stack.push({
92
+ target,
93
+ source
94
+ });
95
+ };
96
+ enqueue(root, next);
97
+ for (let frame = stack.pop(); frame !== void 0; frame = stack.pop()) if (Array.isArray(frame.source)) mergeArray(frame.target, frame.source, spec, enqueue);
98
+ else mergeObject(frame.target, frame.source, spec, enqueue);
99
+ }
100
+ function mergeObject(target, source, spec, enqueue) {
101
+ for (const key of Object.keys(source)) {
102
+ if (isReservedKey(key)) continue;
103
+ const value = unwrapValue(Reflect.get(source, key));
104
+ const had = Object.hasOwn(target, key);
105
+ const current = had ? Reflect.get(target, key) : void 0;
106
+ if (had && Object.is(current, value)) continue;
107
+ if (had && isWrappable(current) && isWrappable(value) && sameKind(current, value)) {
108
+ enqueue(current, value);
109
+ continue;
110
+ }
111
+ writeRaw(target, key, value);
112
+ }
113
+ if (spec.merge) return;
114
+ for (const key of Object.keys(target)) if (!Object.hasOwn(source, key)) deleteRaw(target, key);
115
+ }
116
+ function mergeArray(target, source, spec, enqueue) {
117
+ const list = target;
118
+ const incoming = source;
119
+ const original = list.slice();
120
+ const identities = original.map((item) => identityOf(item, spec.key));
121
+ const byIdentity = /* @__PURE__ */ new Map();
122
+ for (let index = 0; index < original.length; index += 1) {
123
+ const identity = identities[index];
124
+ if (identity !== void 0 && !byIdentity.has(identity)) byIdentity.set(identity, index);
125
+ }
126
+ const used = new Array(original.length).fill(false);
127
+ const matches = [];
128
+ for (let position = 0; position < incoming.length; position += 1) {
129
+ const identity = identityOf(unwrapValue(incoming[position]), spec.key);
130
+ let match = -1;
131
+ if (identity !== void 0) {
132
+ const found = byIdentity.get(identity);
133
+ if (found !== void 0 && used[found] !== true) match = found;
134
+ } else if (position < original.length && identities[position] === void 0) {
135
+ if (used[position] !== true) match = position;
136
+ }
137
+ if (match !== -1) used[match] = true;
138
+ matches.push(match);
139
+ }
140
+ const values = [];
141
+ for (let position = 0; position < incoming.length; position += 1) {
142
+ const item = unwrapValue(incoming[position]);
143
+ const match = matches[position] ?? -1;
144
+ if (match === -1) {
145
+ values.push(item);
146
+ continue;
147
+ }
148
+ const previous = original[match];
149
+ if (isWrappable(previous) && isWrappable(item) && sameKind(previous, item)) {
150
+ if (previous !== item) enqueue(previous, item);
151
+ values.push(previous);
152
+ } else values.push(item);
153
+ }
154
+ if (spec.merge) {
155
+ for (let index = 0; index < original.length; index += 1) if (used[index] !== true) values.push(original[index]);
156
+ }
157
+ for (let position = 0; position < values.length; position += 1) writeRaw(target, String(position), values[position]);
158
+ if (list.length > values.length) writeRaw(target, "length", values.length);
159
+ }
160
+ /**
161
+ * Marks a draft updater. It is the function itself (`setStore(produce((d) => { d.n += 1 }))` is
162
+ * `setStore((d) => { d.n += 1 })`); it exists so code written for other libraries migrates as is.
163
+ *
164
+ * @param update The draft updater: it mutates the draft it receives.
165
+ * @returns `update`, unchanged.
166
+ * @example
167
+ * import { produce, useStore } from "@shadow-js/core";
168
+ *
169
+ * const [cart, setCart] = useStore({ items: [] as string[], count: 0 });
170
+ * setCart(
171
+ * produce((draft) => {
172
+ * draft.items.push("apple");
173
+ * draft.count += 1;
174
+ * }),
175
+ * );
176
+ * console.log(cart.count); // 1
177
+ * @see useStore
178
+ * @since 1.0.0
179
+ */
180
+ function produce(update) {
181
+ return update;
182
+ }
183
+ //#endregion
184
+ export { applyReconcile, produce, reconcile, specOf };
185
+
186
+ //# sourceMappingURL=reconcile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reconcile.js","names":[],"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":"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"}
@@ -0,0 +1,106 @@
1
+ import { Accessor, Setter } from "../internal/types.js";
2
+ //#region src/store/types.d.ts
3
+ /** Values that are never wrapped in a store view: primitives, functions and built-in objects. */
4
+ type Opaque = string | number | bigint | boolean | symbol | null | undefined | ((...args: never[]) => unknown) | Date | RegExp | Map<unknown, unknown> | Set<unknown> | WeakMap<object, unknown> | WeakSet<object> | Promise<unknown>;
5
+ /**
6
+ * Read-only view of `T`. Reads through it subscribe to the exact property read; writes are a type
7
+ * error and throw at runtime outside `setStore`.
8
+ * @since 1.0.0
9
+ */
10
+ export type Store<T> = T extends Opaque ? T : { readonly [K in keyof T]: Store<T[K]>; };
11
+ /**
12
+ * Writable counterpart of a value: `readonly` is removed at every depth. Used for the raw results
13
+ * of `unwrap` and `snapshot`, because inference from a {@link Store} type yields a readonly shape.
14
+ * @since 1.0.0
15
+ */
16
+ export type Mutable<T> = T extends Opaque ? T : { -readonly [K in keyof T]: Mutable<T[K]>; };
17
+ /** Brand that marks a `reconcile()` result at the type level. Never present at runtime. */
18
+ declare const reconcilerBrand: unique symbol;
19
+ /**
20
+ * Value produced by {@link reconcile}. It can only be passed to a store's `setStore`.
21
+ * @since 1.0.0
22
+ */
23
+ export type Reconciler<T> = ((draft: T) => void) & {
24
+ readonly [reconcilerBrand]?: (value: T) => void;
25
+ };
26
+ /**
27
+ * True for values `useStore` wraps in a deep, fine-grained store (plain objects and arrays). Used by
28
+ * {@link StoreResult}; not re-exported by an entry.
29
+ * @since 1.0.0
30
+ */
31
+ export type IsPlainData<T> = [T] extends [Opaque] ? false : [T] extends [readonly unknown[]] ? true : [T] extends [object] ? true : false;
32
+ /**
33
+ * True when `T` mixes plain data with opaque members (for example `Todo[] | null`). Used by
34
+ * {@link StoreResult} and {@link NotMixed}; not re-exported by an entry.
35
+ * @since 1.0.0
36
+ */
37
+ export type IsMixed<T> = [T] extends [Opaque] ? false : [Extract<T, Opaque>] extends [never] ? false : true;
38
+ /** Index forms of a path step on an array: a position, a filter, several positions or a range. */
39
+ type ArrayStep<U> = number | ((item: U, index: number) => boolean) | readonly number[] | {
40
+ from?: number;
41
+ to?: number;
42
+ by?: number;
43
+ };
44
+ type Step<T> = T extends readonly (infer U)[] ? ArrayStep<U> : keyof T | readonly (keyof T)[];
45
+ type Next<T, K> = T extends readonly (infer U)[] ? U : K extends readonly (infer E)[] ? E extends keyof T ? T[E] : never : K extends keyof T ? T[K] : never;
46
+ /**
47
+ * What a path's last step accepts: a value, an updater, a `reconcile()` result, or a partial object
48
+ * that is merged. Used by {@link SetStore}; not re-exported by an entry.
49
+ * @since 1.0.0
50
+ */
51
+ export type Leaf<V> = V | ((previous: V) => V) | Reconciler<V> | (V extends object ? Partial<V> : never);
52
+ /**
53
+ * Updates a store. Every form is one batched, fine-grained transaction:
54
+ *
55
+ * - `setStore((draft) => { draft.items.push(x) })` mutates a draft; returning a value replaces
56
+ * (reconciles) instead.
57
+ * - `setStore({ title: "x" })` merges keys into an object; `setStore([...])` replaces an array.
58
+ * - `setStore(reconcile(next))` diffs `next` into the store.
59
+ * - `setStore("todos", 2, "done", true)` writes at a path of up to four steps, fully type-checked;
60
+ * a step may be a key, several keys, an array filter `(item) => item.done`, or a range
61
+ * `{ from, to, by }`; the last argument may be a value, an updater, or a partial object that is
62
+ * merged. Deeper or dynamic paths go through a draft function.
63
+ * @since 1.0.0
64
+ */
65
+ export interface SetStore<T> {
66
+ /**
67
+ * Draft form: `update` mutates a draft of the whole store. Returning a value instead replaces
68
+ * the store with it (an array is reconciled, a plain object is merged).
69
+ */
70
+ (update: (draft: T) => void | T | Partial<T>): void;
71
+ /** Reconcile form: diffs the data given to {@link reconcile} into the store. */
72
+ (update: Reconciler<T>): void;
73
+ /** Value form: an array replaces an array store (diffed in place); an object merges its keys. */
74
+ (value: T extends readonly unknown[] ? T : Partial<T>): void;
75
+ /** Path form with one step: `a` selects the keys or items, `value` is the leaf update. */
76
+ <A extends Step<T>>(a: A, value: Leaf<Next<T, A>>): void;
77
+ /** Path form with two steps. */
78
+ <A extends Step<T>, B extends Step<Next<T, A>>>(a: A, b: B, value: Leaf<Next<Next<T, A>, B>>): void;
79
+ /** Path form with three steps. */
80
+ <A extends Step<T>, B extends Step<Next<T, A>>, C extends Step<Next<Next<T, A>, B>>>(a: A, b: B, c: C, value: Leaf<Next<Next<Next<T, A>, B>, C>>): void;
81
+ /** Path form with four steps, the deepest typed path; deeper updates use the draft form. */
82
+ <A extends Step<T>, B extends Step<Next<T, A>>, C extends Step<Next<Next<T, A>, B>>, D extends Step<Next<Next<Next<T, A>, B>, C>>>(a: A, b: B, c: C, d: D, value: Leaf<Next<Next<Next<Next<T, A>, B>, C>, D>>): void;
83
+ }
84
+ /**
85
+ * What `useStore(initial)` returns: `[store, setStore]` for plain data, and an `[accessor, setter]`
86
+ * pair for a single value, including a value that may be plain data or `null` (`Todo[] | null`).
87
+ * @since 1.0.0
88
+ */
89
+ export type StoreResult<T> = IsMixed<T> extends true ? [Accessor<Store<T>>, Setter<T>] : IsPlainData<T> extends true ? [Store<Mutable<T>>, SetStore<Mutable<T>>] : [Accessor<T>, Setter<T>];
90
+ /**
91
+ * Constraint of the first `useStore` overload: `T` must not mix plain data with opaque members.
92
+ * A union such as `Todo[] | null` is a single value that starts as one of its non-data members
93
+ * and is replaced by the setter (second overload), because data passed as the initial value would
94
+ * make a store at run time.
95
+ * @since 1.0.0
96
+ */
97
+ export type NotMixed<T> = IsMixed<T> extends true ? never : unknown;
98
+ /**
99
+ * The initial value of a mixed `T`: only its opaque members (`null`, `undefined`, primitives). The
100
+ * parameter type of the second `useStore` overload; not re-exported by an entry.
101
+ * @since 1.0.0
102
+ */
103
+ export type MixedInitial<T> = Extract<T, Opaque>;
104
+ //#endregion
105
+ export {};
106
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,60 @@
1
+ import { MixedInitial, NotMixed, StoreResult } from "./types.js";
2
+ //#region src/store/use-store.d.ts
3
+ /**
4
+ * Options of {@link useStore}.
5
+ * @since 1.0.0
6
+ */
7
+ export interface StoreOptions {
8
+ /**
9
+ * Label shown in error messages and by devtools.
10
+ * @default undefined (the store is unnamed)
11
+ */
12
+ name?: string;
13
+ }
14
+ /**
15
+ * The state hook. Pass a single value for a reactive cell, or plain data for a deep store:
16
+ *
17
+ * ```ts
18
+ * const [count, setCount] = useStore(0); // count() / setCount(n => n + 1)
19
+ * const [todos, setTodos] = useStore({ items: [] as Todo[] });
20
+ * todos.items[0]?.done; // tracks exactly this property
21
+ * setTodos((draft) => { draft.items.push(todo); }); // notifies only what changed
22
+ * setTodos("items", (t) => t.id === 3, "done", true); // path form
23
+ * ```
24
+ *
25
+ * Reads inside effects, memos and JSX subscribe to the exact value or property read; writes notify
26
+ * exactly the readers of what changed, in one batch. A store wraps plain objects and arrays in
27
+ * place; class instances, `Date`, `Map`, `Set` and functions are single values. A value that may
28
+ * be `null` or another type (`Todo[] | null`) is a single value too: it is replaced as a whole, and
29
+ * plain data assigned to it is read through the same fine-grained proxies a store uses.
30
+ *
31
+ * @param initial Initial value or plain data. Plain objects and arrays are wrapped in place, not
32
+ * copied.
33
+ * @param options `name` labels the store in messages. Undefined uses the default (unnamed).
34
+ * @returns `[read, write]` for a single value, `[store, setStore]` for plain data.
35
+ * @throws ShadowError `WRITE_IN_MEMO` from the setter, in development builds only, when it is called
36
+ * while a {@link useMemo} computation runs. `setStore` throws TypeError (production messages
37
+ * `SHADOW_STORE_*`) for an update it cannot apply: no argument, a bad path step, a path through a
38
+ * value that is not an object, a reserved key such as `__proto__`, or a non-array value for an
39
+ * array store. Writing to the store view itself throws TypeError (`SHADOW_STORE_READ_ONLY`).
40
+ * @example
41
+ * import { useStore } from "@shadow-js/core";
42
+ *
43
+ * interface Todo { id: number; title: string; done: boolean }
44
+ *
45
+ * const [count, setCount] = useStore(0);
46
+ * const [todos, setTodos] = useStore({ items: [] as Todo[] });
47
+ * setCount((n) => n + 1);
48
+ * setTodos((draft) => {
49
+ * draft.items.push({ id: 1, title: "Write docs", done: false });
50
+ * });
51
+ * setTodos("items", (todo) => todo.id === 1, "done", true);
52
+ * console.log(count(), todos.items[0]?.done); // 1 true
53
+ * @see useSignal
54
+ * @see reconcile
55
+ * @since 1.0.0
56
+ */
57
+ export declare function useStore<T extends NotMixed<T>>(initial: T, options?: StoreOptions): StoreResult<T>;
58
+ export declare function useStore<T>(initial: MixedInitial<T>, options?: StoreOptions): StoreResult<T>;
59
+ //#endregion
60
+ //# sourceMappingURL=use-store.d.ts.map