@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,118 @@
1
+ import { track } from "./internal/graph.js";
2
+ import { onCleanup, untrack } from "./ownership.js";
3
+ import { useRenderEffect } from "./effect.js";
4
+ import { isTracking, notify } from "./extend/index.js";
5
+ //#region src/selector.ts
6
+ /**
7
+ * The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the
8
+ * shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.
9
+ */
10
+ var Entry = class {
11
+ /** A source with no sources of its own, like a signal. */
12
+ kind = 0;
13
+ observers = null;
14
+ stamp = 0;
15
+ /** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */
16
+ subscribers = 0;
17
+ /** The key this entry answers for. */
18
+ key;
19
+ /** Whether the key matches the selected value. */
20
+ value;
21
+ constructor(key, value) {
22
+ this.key = key;
23
+ this.value = value;
24
+ }
25
+ };
26
+ /** Writes a key's boolean and notifies its readers only when it actually changed. */
27
+ function setEntry(entry, selected) {
28
+ if (entry.value === selected) return;
29
+ entry.value = selected;
30
+ notify(entry);
31
+ }
32
+ /**
33
+ * Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the
34
+ * current source value. Reading it inside an effect or memo subscribes only to that key's boolean,
35
+ * so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the
36
+ * default equality. A custom `equals` costs one call per registered key per change.
37
+ *
38
+ * The source is tracked by a render-phase effect in the current owner. Create the selector before
39
+ * its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked
40
+ * context reads the source directly and creates no subscription. The default equality is `===`,
41
+ * so `NaN` never matches.
42
+ *
43
+ * @param source The value that selects keys. Tracked.
44
+ * @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.
45
+ * @returns `isSelected(key)`.
46
+ * @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still
47
+ * updated and the error goes to the owner's error handler. In development, a selector created
48
+ * outside any owner warns `NO_OWNER_EFFECT`.
49
+ * @example
50
+ * import { mapArray, useSelector, useSignal } from "@shadow-js/core";
51
+ *
52
+ * function Rows(props: { ids: number[] }) {
53
+ * const [selectedId, setSelectedId] = useSignal(1);
54
+ * const isSelected = useSelector(selectedId);
55
+ * return mapArray(() => props.ids, (id) => (
56
+ * <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>
57
+ * ));
58
+ * }
59
+ * @see mapArray
60
+ * @since 1.0.0
61
+ */
62
+ function useSelector(source, equals) {
63
+ const entries = /* @__PURE__ */ new Map();
64
+ /** The value the entries were last reconciled against; `null` until the first successful apply. */
65
+ let last = null;
66
+ const matches = (key, value) => equals === void 0 ? key === value : equals(key, value);
67
+ const currentValue = () => last === null ? untrack(source) : last.value;
68
+ const release = (entry) => {
69
+ entry.subscribers -= 1;
70
+ if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);
71
+ };
72
+ const create = (key) => {
73
+ const entry = new Entry(key, matches(key, currentValue()));
74
+ entries.set(key, entry);
75
+ return entry;
76
+ };
77
+ const isSelected = (key) => {
78
+ if (!isTracking()) return matches(key, source());
79
+ const entry = entries.get(key) ?? create(key);
80
+ entry.subscribers += 1;
81
+ onCleanup(() => release(entry));
82
+ track(entry);
83
+ return entry.value;
84
+ };
85
+ useRenderEffect(() => source(), (next) => {
86
+ const previous = last;
87
+ last = { value: next };
88
+ if (previous !== null && equals === void 0) {
89
+ if (previous.value === next) return;
90
+ const before = entries.get(previous.value);
91
+ if (before !== void 0) setEntry(before, before.key === next);
92
+ const after = entries.get(next);
93
+ if (after !== void 0) setEntry(after, after.key === next);
94
+ return;
95
+ }
96
+ let failed = false;
97
+ let failure;
98
+ for (const entry of entries.values()) {
99
+ let selected;
100
+ try {
101
+ selected = matches(entry.key, next);
102
+ } catch (error) {
103
+ if (!failed) {
104
+ failed = true;
105
+ failure = error;
106
+ }
107
+ continue;
108
+ }
109
+ setEntry(entry, selected);
110
+ }
111
+ if (failed) throw failure;
112
+ });
113
+ return isSelected;
114
+ }
115
+ //#endregion
116
+ export { useSelector };
117
+
118
+ //# sourceMappingURL=selector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"selector.js","names":[],"sources":["../../src/selector.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { isTracking, notify, type SourceNode, track } from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\n\n/**\n * The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the\n * shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.\n */\nclass Entry implements SourceNode {\n /** A source with no sources of its own, like a signal. */\n readonly kind = 0;\n observers: SourceNode[\"observers\"] = null;\n stamp = 0;\n /** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */\n subscribers = 0;\n\n /** The key this entry answers for. */\n readonly key: unknown;\n /** Whether the key matches the selected value. */\n value: boolean;\n\n constructor(key: unknown, value: boolean) {\n this.key = key;\n this.value = value;\n }\n}\n\n/** Writes a key's boolean and notifies its readers only when it actually changed. */\nfunction setEntry(entry: Entry, selected: boolean): void {\n if (entry.value === selected) return;\n entry.value = selected;\n notify(entry);\n}\n\n/**\n * Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the\n * current source value. Reading it inside an effect or memo subscribes only to that key's boolean,\n * so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the\n * default equality. A custom `equals` costs one call per registered key per change.\n *\n * The source is tracked by a render-phase effect in the current owner. Create the selector before\n * its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked\n * context reads the source directly and creates no subscription. The default equality is `===`,\n * so `NaN` never matches.\n *\n * @param source The value that selects keys. Tracked.\n * @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.\n * @returns `isSelected(key)`.\n * @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still\n * updated and the error goes to the owner's error handler. In development, a selector created\n * outside any owner warns `NO_OWNER_EFFECT`.\n * @example\n * import { mapArray, useSelector, useSignal } from \"@shadow-js/core\";\n *\n * function Rows(props: { ids: number[] }) {\n * const [selectedId, setSelectedId] = useSignal(1);\n * const isSelected = useSelector(selectedId);\n * return mapArray(() => props.ids, (id) => (\n * <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>\n * ));\n * }\n * @see mapArray\n * @since 1.0.0\n */\nexport function useSelector<T, K = T>(\n source: () => T,\n equals?: (key: K, value: T) => boolean,\n): (key: K) => boolean {\n const entries = new Map<unknown, Entry>();\n /** The value the entries were last reconciled against; `null` until the first successful apply. */\n let last: { readonly value: T } | null = null;\n\n const matches = (key: K, value: T): boolean =>\n equals === undefined ? (key as unknown) === value : equals(key, value);\n\n const currentValue = (): T => (last === null ? untrack(source) : last.value);\n\n const release = (entry: Entry): void => {\n entry.subscribers -= 1;\n if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);\n };\n\n const create = (key: K): Entry => {\n const entry = new Entry(key, matches(key, currentValue()));\n entries.set(key, entry);\n return entry;\n };\n\n const isSelected = (key: K): boolean => {\n if (!isTracking()) return matches(key, source());\n const entry = entries.get(key) ?? create(key);\n entry.subscribers += 1;\n onCleanup(() => release(entry));\n track(entry);\n return entry.value;\n };\n\n useRenderEffect(\n () => source(),\n (next) => {\n const previous = last;\n last = { value: next };\n if (previous !== null && equals === undefined) {\n // Default equality: only the entries for the previous and the next key can change.\n if (previous.value === next) return;\n const before = entries.get(previous.value);\n if (before !== undefined) setEntry(before, before.key === next);\n const after = entries.get(next);\n if (after !== undefined) setEntry(after, after.key === next);\n return;\n }\n // Custom equality, or the first successful value: every registered key is checked. A\n // failing equals does not stop the others; its error is rethrown once they are all updated.\n let failed = false;\n let failure: unknown;\n for (const entry of entries.values()) {\n let selected: boolean;\n try {\n selected = matches(entry.key as K, next);\n } catch (error) {\n if (!failed) {\n failed = true;\n failure = error;\n }\n continue;\n }\n setEntry(entry, selected);\n }\n if (failed) throw failure;\n },\n );\n\n return isSelected;\n}\n"],"mappings":";;;;;;;;;AAQA,IAAM,QAAN,MAAkC;;CAEhC,OAAgB;CAChB,YAAqC;CACrC,QAAQ;;CAER,cAAc;;CAGd;;CAEA;CAEA,YAAY,KAAc,OAAgB;EACxC,KAAK,MAAM;EACX,KAAK,QAAQ;CACf;AACF;;AAGA,SAAS,SAAS,OAAc,UAAyB;CACvD,IAAI,MAAM,UAAU,UAAU;CAC9B,MAAM,QAAQ;CACd,OAAO,KAAK;AACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,YACd,QACA,QACqB;CACrB,MAAM,0BAAU,IAAI,IAAoB;;CAExC,IAAI,OAAqC;CAEzC,MAAM,WAAW,KAAQ,UACvB,WAAW,KAAA,IAAa,QAAoB,QAAQ,OAAO,KAAK,KAAK;CAEvE,MAAM,qBAAyB,SAAS,OAAO,QAAQ,MAAM,IAAI,KAAK;CAEtE,MAAM,WAAW,UAAuB;EACtC,MAAM,eAAe;EACrB,IAAI,MAAM,gBAAgB,KAAK,QAAQ,IAAI,MAAM,GAAG,MAAM,OAAO,QAAQ,OAAO,MAAM,GAAG;CAC3F;CAEA,MAAM,UAAU,QAAkB;EAChC,MAAM,QAAQ,IAAI,MAAM,KAAK,QAAQ,KAAK,aAAa,CAAC,CAAC;EACzD,QAAQ,IAAI,KAAK,KAAK;EACtB,OAAO;CACT;CAEA,MAAM,cAAc,QAAoB;EACtC,IAAI,CAAC,WAAW,GAAG,OAAO,QAAQ,KAAK,OAAO,CAAC;EAC/C,MAAM,QAAQ,QAAQ,IAAI,GAAG,KAAK,OAAO,GAAG;EAC5C,MAAM,eAAe;EACrB,gBAAgB,QAAQ,KAAK,CAAC;EAC9B,MAAM,KAAK;EACX,OAAO,MAAM;CACf;CAEA,sBACQ,OAAO,IACZ,SAAS;EACR,MAAM,WAAW;EACjB,OAAO,EAAE,OAAO,KAAK;EACrB,IAAI,aAAa,QAAQ,WAAW,KAAA,GAAW;GAE7C,IAAI,SAAS,UAAU,MAAM;GAC7B,MAAM,SAAS,QAAQ,IAAI,SAAS,KAAK;GACzC,IAAI,WAAW,KAAA,GAAW,SAAS,QAAQ,OAAO,QAAQ,IAAI;GAC9D,MAAM,QAAQ,QAAQ,IAAI,IAAI;GAC9B,IAAI,UAAU,KAAA,GAAW,SAAS,OAAO,MAAM,QAAQ,IAAI;GAC3D;EACF;EAGA,IAAI,SAAS;EACb,IAAI;EACJ,KAAK,MAAM,SAAS,QAAQ,OAAO,GAAG;GACpC,IAAI;GACJ,IAAI;IACF,WAAW,QAAQ,MAAM,KAAU,IAAI;GACzC,SAAS,OAAO;IACd,IAAI,CAAC,QAAQ;KACX,SAAS;KACT,UAAU;IACZ;IACA;GACF;GACA,SAAS,OAAO,QAAQ;EAC1B;EACA,IAAI,QAAQ,MAAM;CACpB,CACF;CAEA,OAAO;AACT"}
@@ -0,0 +1,42 @@
1
+ import { Accessor, Equals, Setter } from "./internal/types.js";
2
+ //#region src/signal.d.ts
3
+ /**
4
+ * Options of {@link useSignal}.
5
+ * @since 1.0.0
6
+ */
7
+ export interface SignalOptions<T> {
8
+ /**
9
+ * Decides whether a write is a change: readers are notified only when it returns `false`.
10
+ * `false` notifies on every write, even of the same value.
11
+ * @default Object.is
12
+ */
13
+ equals?: Equals<T>;
14
+ /**
15
+ * Label shown by devtools and diagnostics.
16
+ * @default undefined (the signal is unnamed)
17
+ */
18
+ name?: string;
19
+ }
20
+ /**
21
+ * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads
22
+ * inside effects and memos subscribe them; writes notify them. Works at module scope.
23
+ *
24
+ * @param value Initial value.
25
+ * @param options Equality override and a devtools name. Undefined uses the defaults.
26
+ * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs
27
+ * untracked, and returns the value it stored.
28
+ * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is
29
+ * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).
30
+ * @example
31
+ * import { useSignal } from "@shadow-js/core";
32
+ *
33
+ * const [count, setCount] = useSignal(0);
34
+ * setCount((n) => n + 1);
35
+ * console.log(count()); // 1
36
+ * @see useStore
37
+ * @see useMemo
38
+ * @since 1.0.0
39
+ */
40
+ export declare function useSignal<T>(value: T, options?: SignalOptions<T>): [Accessor<T>, Setter<T>];
41
+ //#endregion
42
+ //# sourceMappingURL=signal.d.ts.map
@@ -0,0 +1,39 @@
1
+ import { readSignal } from "./internal/graph.js";
2
+ import { untrack } from "./ownership.js";
3
+ import { createSignalNode, writeSignal } from "./extend/index.js";
4
+ //#region src/signal.ts
5
+ /**
6
+ * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads
7
+ * inside effects and memos subscribe them; writes notify them. Works at module scope.
8
+ *
9
+ * @param value Initial value.
10
+ * @param options Equality override and a devtools name. Undefined uses the defaults.
11
+ * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs
12
+ * untracked, and returns the value it stored.
13
+ * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is
14
+ * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).
15
+ * @example
16
+ * import { useSignal } from "@shadow-js/core";
17
+ *
18
+ * const [count, setCount] = useSignal(0);
19
+ * setCount((n) => n + 1);
20
+ * console.log(count()); // 1
21
+ * @see useStore
22
+ * @see useMemo
23
+ * @since 1.0.0
24
+ */
25
+ function useSignal(value, options) {
26
+ const equals = options?.equals === void 0 ? Object.is : options.equals;
27
+ const signal = createSignalNode(value, equals, options?.name);
28
+ const read = () => readSignal(signal);
29
+ const write = ((next) => {
30
+ const resolved = typeof next === "function" ? untrack(() => next(signal.value)) : next;
31
+ writeSignal(signal, resolved);
32
+ return resolved;
33
+ });
34
+ return [read, write];
35
+ }
36
+ //#endregion
37
+ export { useSignal };
38
+
39
+ //# sourceMappingURL=signal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signal.js","names":[],"sources":["../../src/signal.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n type Equals,\n readSignal,\n type Setter,\n writeSignal,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useSignal}.\n * @since 1.0.0\n */\nexport interface SignalOptions<T> {\n /**\n * Decides whether a write is a change: readers are notified only when it returns `false`.\n * `false` notifies on every write, even of the same value.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name?: string;\n}\n\n/**\n * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads\n * inside effects and memos subscribe them; writes notify them. Works at module scope.\n *\n * @param value Initial value.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs\n * untracked, and returns the value it stored.\n * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is\n * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * setCount((n) => n + 1);\n * console.log(count()); // 1\n * @see useStore\n * @see useMemo\n * @since 1.0.0\n */\nexport function useSignal<T>(value: T, options?: SignalOptions<T>): [Accessor<T>, Setter<T>] {\n const equals: Equals<T> = options?.equals === undefined ? Object.is : options.equals;\n const signal = createSignalNode<T>(value, equals, options?.name);\n const read: Accessor<T> = () => readSignal(signal);\n const write = ((next: unknown) => {\n const resolved = (\n typeof next === \"function\" ? untrack(() => (next as (prev: T) => T)(signal.value)) : next\n ) as T;\n writeSignal(signal, resolved);\n return resolved;\n }) as Setter<T>;\n return [read, write];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,UAAa,OAAU,SAAsD;CAC3F,MAAM,SAAoB,SAAS,WAAW,KAAA,IAAY,OAAO,KAAK,QAAQ;CAC9E,MAAM,SAAS,iBAAoB,OAAO,QAAQ,SAAS,IAAI;CAC/D,MAAM,aAA0B,WAAW,MAAM;CACjD,MAAM,UAAU,SAAkB;EAChC,MAAM,WACJ,OAAO,SAAS,aAAa,cAAe,KAAwB,OAAO,KAAK,CAAC,IAAI;EAEvF,YAAY,QAAQ,QAAQ;EAC5B,OAAO;CACT;CACA,OAAO,CAAC,MAAM,KAAK;AACrB"}
@@ -0,0 +1,5 @@
1
+ import { Mutable, Reconciler, SetStore, Store, StoreResult } from "./types.js";
2
+ import { snapshot, unwrap } from "./read.js";
3
+ import { ReconcileOptions, produce, reconcile } from "./reconcile.js";
4
+ import { StoreOptions, useStore } from "./use-store.js";
5
+ export { type Mutable, type ReconcileOptions, type Reconciler, type SetStore, type Store, type StoreOptions, type StoreResult, produce, reconcile, snapshot, unwrap, useStore };
@@ -0,0 +1,4 @@
1
+ import { snapshot, unwrap } from "./read.js";
2
+ import { produce, reconcile } from "./reconcile.js";
3
+ import { useStore } from "./use-store.js";
4
+ export { produce, reconcile, snapshot, unwrap, useStore };
@@ -0,0 +1,192 @@
1
+ import { track } from "../internal/graph.js";
2
+ import { createSignalNode, isTracking, notify as notify$1 } from "../extend/index.js";
3
+ //#region src/store/nodes.ts
4
+ /** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */
5
+ const RESERVED_KEYS = /* @__PURE__ */ new Set([
6
+ "__proto__",
7
+ "constructor",
8
+ "prototype"
9
+ ]);
10
+ /** Raw object -> its tracking state. Keys are the raw data, so nothing is stamped on user objects. */
11
+ const NODES = /* @__PURE__ */ new WeakMap();
12
+ /** Any store proxy (read-only or draft) -> the raw object it wraps. */
13
+ const RAW = /* @__PURE__ */ new WeakMap();
14
+ /** True for the keys that must never be written as own properties. */
15
+ function isReservedKey(key) {
16
+ return RESERVED_KEYS.has(key);
17
+ }
18
+ /** True for the values the store wraps: plain objects (null or Object.prototype) and arrays. */
19
+ function isWrappable(value) {
20
+ if (typeof value !== "object" || value === null) return false;
21
+ if (Array.isArray(value)) return true;
22
+ if (value === Object.prototype) return false;
23
+ const prototype = Object.getPrototypeOf(value);
24
+ return prototype === Object.prototype || prototype === null;
25
+ }
26
+ /** Replaces a store proxy by the raw object it wraps; any other value is returned as is. */
27
+ function unwrapValue(value) {
28
+ if (typeof value !== "object" || value === null) return value;
29
+ return RAW.get(value) ?? value;
30
+ }
31
+ /** True when a store proxy (draft or read-only view) sits anywhere inside the plain data `root`. */
32
+ function containsProxy(root) {
33
+ const seen = /* @__PURE__ */ new Set([root]);
34
+ const stack = [root];
35
+ while (stack.length > 0) {
36
+ const container = stack.pop();
37
+ for (const key of Object.keys(container)) {
38
+ const member = Reflect.get(container, key);
39
+ if (typeof member !== "object" || member === null) continue;
40
+ if (RAW.has(member)) return true;
41
+ if (isWrappable(member) && !seen.has(member)) {
42
+ seen.add(member);
43
+ stack.push(member);
44
+ }
45
+ }
46
+ }
47
+ return false;
48
+ }
49
+ /**
50
+ * Like {@link unwrapValue}, and also for proxies hidden inside plain data: `draft.todos =
51
+ * draft.todos.filter(...)` assigns an array whose members are drafts, and a draft stored in the
52
+ * data would throw on its next use. Data without proxies is returned as is; otherwise a copy with
53
+ * every proxy replaced by its raw object. Iterative, so nesting depth is not limited by the stack.
54
+ */
55
+ function unwrapDeep(value) {
56
+ const first = unwrapValue(value);
57
+ if (first !== value || !isWrappable(first) || !containsProxy(first)) return first;
58
+ const copies = /* @__PURE__ */ new Map();
59
+ const copyOf = (source) => {
60
+ const existing = copies.get(source);
61
+ if (existing !== void 0) return existing;
62
+ const made = Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));
63
+ copies.set(source, made);
64
+ return made;
65
+ };
66
+ const rootCopy = copyOf(first);
67
+ const queue = [first];
68
+ for (let head = 0; head < queue.length; head += 1) {
69
+ const source = queue[head];
70
+ const target = copies.get(source);
71
+ for (const key of Object.keys(source)) {
72
+ let member = Reflect.get(source, key);
73
+ if (typeof member === "object" && member !== null) {
74
+ const raw = RAW.get(member);
75
+ if (raw !== void 0) member = raw;
76
+ else if (isWrappable(member)) {
77
+ const known = copies.has(member);
78
+ member = copyOf(member);
79
+ if (!known) queue.push(Reflect.get(source, key));
80
+ }
81
+ }
82
+ Object.defineProperty(target, key, {
83
+ value: member,
84
+ enumerable: true,
85
+ writable: true,
86
+ configurable: true
87
+ });
88
+ }
89
+ }
90
+ return rootCopy;
91
+ }
92
+ /** Reads an own or inherited property without tracking and without invoking proxies. */
93
+ function readRaw(target, key) {
94
+ return Reflect.get(target, key);
95
+ }
96
+ /** Returns the tracking state of `raw`, creating an empty one on first use. */
97
+ function nodeOf(raw) {
98
+ let node = NODES.get(raw);
99
+ if (node === void 0) {
100
+ node = {
101
+ signals: null,
102
+ keys: null,
103
+ proxy: null
104
+ };
105
+ NODES.set(raw, node);
106
+ }
107
+ return node;
108
+ }
109
+ function signalFor(node, key) {
110
+ let signals = node.signals;
111
+ if (signals === null) {
112
+ signals = /* @__PURE__ */ new Map();
113
+ node.signals = signals;
114
+ }
115
+ let signal = signals.get(key);
116
+ if (signal === void 0) {
117
+ signal = createSignalNode(0, false);
118
+ signals.set(key, signal);
119
+ }
120
+ return signal;
121
+ }
122
+ /** Subscribes the running computation (if any) to one property of the object. */
123
+ function trackProperty(node, key) {
124
+ if (!isTracking()) return;
125
+ track(signalFor(node, key));
126
+ }
127
+ /** Subscribes the running computation (if any) to the key set of the object. */
128
+ function trackKeys(node) {
129
+ if (!isTracking()) return;
130
+ if (node.keys === null) node.keys = createSignalNode(0, false);
131
+ track(node.keys);
132
+ }
133
+ /**
134
+ * Notifies the observers of one signal. The same engine steps as a signal write: mark the
135
+ * observers dirty, then request a flush (which the surrounding batch defers).
136
+ */
137
+ function notify(signal) {
138
+ if (signal === void 0 || signal === null) return;
139
+ notify$1(signal);
140
+ }
141
+ function isIndexKey(key) {
142
+ const index = Number(key);
143
+ return Number.isInteger(index) && index >= 0 && String(index) === key;
144
+ }
145
+ /** Notifies the index signals of an array at or beyond `from` (used when the array shrinks). */
146
+ function notifyIndicesFrom(node, from) {
147
+ const signals = node.signals;
148
+ if (signals === null) return;
149
+ for (const [key, signal] of signals) if (isIndexKey(key) && Number(key) >= from) notify(signal);
150
+ }
151
+ /**
152
+ * Writes one property of a raw object and notifies exactly what changed: the property's signal,
153
+ * the key set when a property appears, and the length when an array's length moves. An equal
154
+ * value (Object.is) writes nothing. Returns whether anything changed.
155
+ */
156
+ function writeRaw(target, key, value) {
157
+ if (isReservedKey(key)) throw new TypeError(`ShadowStore: "${key}" cannot be written; it is a reserved key`);
158
+ value = unwrapDeep(value);
159
+ const array = Array.isArray(target);
160
+ const had = Object.hasOwn(target, key);
161
+ if (had && Object.is(readRaw(target, key), value)) return false;
162
+ const before = array ? target.length : 0;
163
+ if (!Reflect.set(target, key, value)) throw new TypeError(`ShadowStore: property "${key}" is read-only and cannot be written`);
164
+ const node = NODES.get(target);
165
+ if (node === void 0) return true;
166
+ notify(node.signals?.get(key));
167
+ if (!had) notify(node.keys);
168
+ if (array) {
169
+ const after = target.length;
170
+ if (after !== before) {
171
+ notify(node.signals?.get("length"));
172
+ notify(node.keys);
173
+ if (after < before) notifyIndicesFrom(node, after);
174
+ }
175
+ }
176
+ return true;
177
+ }
178
+ /** Deletes one own property of a raw object and notifies its signal and the key set. */
179
+ function deleteRaw(target, key) {
180
+ if (isReservedKey(key)) throw new TypeError(`ShadowStore: "${key}" cannot be deleted; it is a reserved key`);
181
+ if (!Object.hasOwn(target, key)) return true;
182
+ if (!Reflect.deleteProperty(target, key)) throw new TypeError(`ShadowStore: property "${key}" cannot be deleted`);
183
+ const node = NODES.get(target);
184
+ if (node === void 0) return true;
185
+ notify(node.signals?.get(key));
186
+ notify(node.keys);
187
+ return true;
188
+ }
189
+ //#endregion
190
+ export { NODES, RAW, deleteRaw, isReservedKey, isWrappable, nodeOf, readRaw, trackKeys, trackProperty, unwrapDeep, unwrapValue, writeRaw };
191
+
192
+ //# sourceMappingURL=nodes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nodes.js","names":[],"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":";;;;AASA,MAAM,gCAAqC,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;AAgB5F,MAAa,wBAAoC,IAAI,QAAQ;;AAG7D,MAAa,sBAA+B,IAAI,QAAQ;;AAGxD,SAAgB,cAAc,KAAsB;CAClD,OAAO,cAAc,IAAI,GAAG;AAC9B;;AAGA,SAAgB,YAAY,OAAiC;CAC3D,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,IAAI,UAAU,OAAO,WAAW,OAAO;CACvC,MAAM,YAAqB,OAAO,eAAe,KAAK;CACtD,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;;AAGA,SAAgB,YAAY,OAAyB;CACnD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAO,IAAI,IAAI,KAAK,KAAK;AAC3B;;AAGA,SAAS,cAAc,MAAuB;CAC5C,MAAM,uBAAO,IAAI,IAAY,CAAC,IAAI,CAAC;CACnC,MAAM,QAAkB,CA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AG,GAAG,OAAO;CACxC,IAAI,CAAC,QAAQ,eAAe,QAAQ,GAAG,GACrC,MAAM,IAAI,UACE,0BAA0B,IAAI,oBAC1C;CAEF,MAAM,OAAO,MAAM,IAAI,MAAM;CAC7B,IAAI,SAAS,KAAA,GAAW,OAAO;CAC/B,OAAO,KAAK,SAAS,IAAI,GAAG,CAAC;CAC7B,OAAO,KAAK,IAAI;CAChB,OAAO;AACT"}
@@ -0,0 +1,160 @@
1
+ import { RAW, deleteRaw, isReservedKey, isWrappable, nodeOf, readRaw, trackKeys, trackProperty, unwrapValue, writeRaw } from "./nodes.js";
2
+ //#region src/store/proxies.ts
3
+ /**
4
+ * One `setStore` call. Drafts made for it are cached here, so a draft object keeps its identity
5
+ * inside the update, and they stop accepting writes when the call returns.
6
+ */
7
+ var Transaction = class {
8
+ label;
9
+ open;
10
+ drafts;
11
+ handler;
12
+ constructor(label) {
13
+ this.label = label;
14
+ this.open = true;
15
+ this.drafts = /* @__PURE__ */ new Map();
16
+ this.handler = draftHandler(this);
17
+ }
18
+ };
19
+ function readOnly(key) {
20
+ const name = typeof key === "symbol" ? key.toString() : `"${key}"`;
21
+ return /* @__PURE__ */ new TypeError(`ShadowStore: the store is read-only; ${name} can only be changed inside setStore((draft) => ...)`);
22
+ }
23
+ /**
24
+ * Returns the value to hand out for `key`: a wrapped object when the value is an own, writable
25
+ * wrappable slot, otherwise the raw value. Frozen slots must return the raw value because a proxy
26
+ * may not report a different value for a non-writable, non-configurable property.
27
+ */
28
+ function childOf(target, key, value, wrap) {
29
+ if (!isWrappable(value) || !Object.hasOwn(target, key)) return value;
30
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, key);
31
+ if (descriptor !== void 0 && descriptor.configurable === false && descriptor.writable === false) return value;
32
+ return wrap(value);
33
+ }
34
+ /** Descriptor passthrough that wraps the value the same way `get` does. */
35
+ function describeChild(target, key, wrap) {
36
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, key);
37
+ if (descriptor === void 0 || typeof key === "symbol") return descriptor;
38
+ if (descriptor.configurable === false) return descriptor;
39
+ const value = descriptor.value;
40
+ if (!isWrappable(value)) return descriptor;
41
+ return {
42
+ ...descriptor,
43
+ value: wrap(value)
44
+ };
45
+ }
46
+ /** `__proto__` is only reachable through the prototype chain, so the store never exposes it. */
47
+ function hidesPrototype(target, key) {
48
+ return key === "__proto__" && !Object.hasOwn(target, key);
49
+ }
50
+ /** True when `key` resolves to an accessor property (own or inherited). */
51
+ function hasGetter(target, key) {
52
+ for (let object = target; object !== null; object = Object.getPrototypeOf(object)) {
53
+ const descriptor = Reflect.getOwnPropertyDescriptor(object, key);
54
+ if (descriptor !== void 0) return typeof descriptor.get === "function";
55
+ }
56
+ return false;
57
+ }
58
+ /** Read-only handler: every read subscribes the running computation to the property it touches. */
59
+ const READ_HANDLER = {
60
+ get(target, key, receiver) {
61
+ if (typeof key === "symbol") return Reflect.get(target, key);
62
+ if (hidesPrototype(target, key)) return void 0;
63
+ trackProperty(nodeOf(target), key);
64
+ if (hasGetter(target, key)) return Reflect.get(target, key, receiver);
65
+ return childOf(target, key, readRaw(target, key), readProxyOf);
66
+ },
67
+ has(target, key) {
68
+ if (typeof key !== "symbol") trackProperty(nodeOf(target), key);
69
+ return Reflect.has(target, key);
70
+ },
71
+ ownKeys(target) {
72
+ trackKeys(nodeOf(target));
73
+ return Reflect.ownKeys(target);
74
+ },
75
+ getOwnPropertyDescriptor(target, key) {
76
+ return describeChild(target, key, readProxyOf);
77
+ },
78
+ set(_target, key) {
79
+ throw readOnly(key);
80
+ },
81
+ deleteProperty(_target, key) {
82
+ throw readOnly(key);
83
+ },
84
+ defineProperty(_target, key) {
85
+ throw readOnly(key);
86
+ },
87
+ setPrototypeOf() {
88
+ throw readOnly("[[Prototype]]");
89
+ },
90
+ preventExtensions() {
91
+ throw readOnly("[[Extensible]]");
92
+ }
93
+ };
94
+ /** Draft handler for one transaction: writes go through the notifying helpers. */
95
+ function draftHandler(tx) {
96
+ const wrap = (raw) => draftOf(raw, tx);
97
+ /** Throws unless the draft is still inside its update and `key` is a string key. */
98
+ const writable = (key) => {
99
+ if (!tx.open) throw new TypeError(`ShadowStore (${tx.label}): a draft was used after its setStore() call returned; write only inside the update`);
100
+ if (typeof key === "symbol") throw new TypeError(`ShadowStore (${tx.label}): symbol keys cannot be written`);
101
+ return key;
102
+ };
103
+ return {
104
+ get(target, key) {
105
+ if (typeof key === "symbol") return Reflect.get(target, key);
106
+ if (hidesPrototype(target, key)) return void 0;
107
+ return childOf(target, key, readRaw(target, key), wrap);
108
+ },
109
+ has(target, key) {
110
+ return Reflect.has(target, key);
111
+ },
112
+ ownKeys(target) {
113
+ return Reflect.ownKeys(target);
114
+ },
115
+ getOwnPropertyDescriptor(target, key) {
116
+ return describeChild(target, key, wrap);
117
+ },
118
+ set(target, key, value) {
119
+ const name = writable(key);
120
+ if (isReservedKey(name)) throw new TypeError(`ShadowStore (${tx.label}): "${name}" cannot be written; it is a reserved key`);
121
+ writeRaw(target, name, unwrapValue(value));
122
+ return true;
123
+ },
124
+ deleteProperty(target, key) {
125
+ return deleteRaw(target, writable(key));
126
+ },
127
+ defineProperty(_target, key) {
128
+ throw new TypeError(`ShadowStore (${tx.label}): defineProperty is not supported on drafts; assign the property instead (key "${String(key)}")`);
129
+ },
130
+ setPrototypeOf() {
131
+ throw new TypeError(`ShadowStore (${tx.label}): drafts cannot change their prototype`);
132
+ },
133
+ preventExtensions() {
134
+ throw new TypeError(`ShadowStore (${tx.label}): drafts cannot be made non-extensible`);
135
+ }
136
+ };
137
+ }
138
+ /** Returns the read-only proxy of a raw object. The same raw object always yields the same proxy. */
139
+ function readProxyOf(raw) {
140
+ const node = nodeOf(raw);
141
+ if (node.proxy === null) {
142
+ const proxy = new Proxy(raw, READ_HANDLER);
143
+ RAW.set(proxy, raw);
144
+ node.proxy = proxy;
145
+ }
146
+ return node.proxy;
147
+ }
148
+ /** Returns the draft proxy of a raw object for one transaction. */
149
+ function draftOf(raw, tx) {
150
+ const existing = tx.drafts.get(raw);
151
+ if (existing !== void 0) return existing;
152
+ const proxy = new Proxy(raw, tx.handler);
153
+ RAW.set(proxy, raw);
154
+ tx.drafts.set(raw, proxy);
155
+ return proxy;
156
+ }
157
+ //#endregion
158
+ export { Transaction, draftOf, readProxyOf };
159
+
160
+ //# sourceMappingURL=proxies.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxies.js","names":[],"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":";;;;;;AAiBA,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA;CAEA,YAAY,OAAe;EACzB,KAAK,QAAQ;EACb,KAAK,OAAO;EACZ,KAAK,yBAAS,IAAI,IAAI;EACtB,KAAK,UAAU,aAAa,IAAI;CAClC;AACF;AAEA,SAAS,SAAS,KAAiC;CACjD,MAAM,OAAO,OAAO,QAAQ,WAAW,IAAI,SAAS,IAAI,IAAI,IAAI;CAChE,uBAAO,IAAI,UAEL,wCAAwC,KAAK,qDAEnD;AACF;;;;;;AAOA,SAAS,QACP,QACA,KACA,OACA,MACS;CACT,IAAI,CAAC,YAAY,KAAK,KAAK,CAAC,OAAO,OAAO,QAAQ,GAAG,GAAG,OAAO;CAC/D,MAAM,aAAa,QAAQ,yBAAyB,QAAQ,GAAG;CAC/D,IACE,eAAe,KAAA,KACf,WAAW,iBAAiB,SAC5B,WAAW,aAAa,OAExB,OAAO;CAET,OAAO,KAAK,KAAK;AACnB;;AAGA,SAAS,cACP,QACA,KACA,MACgC;CAChC,MAAM,aAAa,QAAQ,yBAAyB,QAAQ,GAAG;CAC/D,IAAI,eAAe,KAAA,KAAa,OAAO,QAAQ,UAAU,OAAO;CAChE,IAAI,WAAW,iBAAiB,OAAO,OAAO;CAC9C,MAAM,QAAiB,WAAW;CAClC,IAAI,CAAC,YAAY,KAAK,GAAG,OAAO;CAChC,OAAO;EAAE,GAAG;EAAY,OAAO,KAAK,KAAK;CAAE;AAC7C;;AAGA,SAAS,eAAe,QAAgB,KAAsB;CAC5D,OAAO,QAAQ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