@shadow-js/core 0.1.0 → 1.0.1

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 +17 -0
  2. package/LICENSE +2 -2
  3. package/README.md +134 -331
  4. package/dist/dev/action.d.ts +34 -0
  5. package/dist/dev/action.js +89 -0
  6. package/dist/dev/action.js.map +1 -0
  7. package/dist/dev/cache.d.ts +33 -0
  8. package/dist/dev/cache.js +61 -0
  9. package/dist/dev/cache.js.map +1 -0
  10. package/dist/dev/context.d.ts +104 -0
  11. package/dist/dev/context.js +110 -0
  12. package/dist/dev/context.js.map +1 -0
  13. package/dist/dev/effect.d.ts +120 -0
  14. package/dist/dev/effect.js +110 -0
  15. package/dist/dev/effect.js.map +1 -0
  16. package/dist/dev/env.d.ts +27 -0
  17. package/dist/dev/env.js +30 -0
  18. package/dist/dev/env.js.map +1 -0
  19. package/dist/dev/events.d.ts +26 -0
  20. package/dist/dev/events.js +32 -0
  21. package/dist/dev/events.js.map +1 -0
  22. package/dist/dev/extend/index.d.ts +329 -0
  23. package/dist/dev/extend/index.js +316 -0
  24. package/dist/dev/extend/index.js.map +1 -0
  25. package/dist/dev/external-store.d.ts +58 -0
  26. package/dist/dev/external-store.js +59 -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 +211 -0
  31. package/dist/dev/internal/concurrency.js +631 -0
  32. package/dist/dev/internal/concurrency.js.map +1 -0
  33. package/dist/dev/internal/devtools.d.ts +69 -0
  34. package/dist/dev/internal/devtools.js +76 -0
  35. package/dist/dev/internal/devtools.js.map +1 -0
  36. package/dist/dev/internal/diagnostics.d.ts +88 -0
  37. package/dist/dev/internal/diagnostics.js +101 -0
  38. package/dist/dev/internal/diagnostics.js.map +1 -0
  39. package/dist/dev/internal/dispose.d.ts +26 -0
  40. package/dist/dev/internal/dispose.js +48 -0
  41. package/dist/dev/internal/dispose.js.map +1 -0
  42. package/dist/dev/internal/flags.js +10 -0
  43. package/dist/dev/internal/flags.js.map +1 -0
  44. package/dist/dev/internal/graph.d.ts +231 -0
  45. package/dist/dev/internal/graph.js +577 -0
  46. package/dist/dev/internal/graph.js.map +1 -0
  47. package/dist/dev/internal/hydration-flag.d.ts +31 -0
  48. package/dist/dev/internal/hydration-flag.js +45 -0
  49. package/dist/dev/internal/hydration-flag.js.map +1 -0
  50. package/dist/dev/internal/messages.d.ts +54 -0
  51. package/dist/dev/internal/messages.js +53 -0
  52. package/dist/dev/internal/messages.js.map +1 -0
  53. package/dist/dev/internal/owner.d.ts +140 -0
  54. package/dist/dev/internal/owner.js +289 -0
  55. package/dist/dev/internal/owner.js.map +1 -0
  56. package/dist/dev/internal/queue.js +45 -0
  57. package/dist/dev/internal/queue.js.map +1 -0
  58. package/dist/dev/internal/scheduler.d.ts +111 -0
  59. package/dist/dev/internal/scheduler.js +286 -0
  60. package/dist/dev/internal/scheduler.js.map +1 -0
  61. package/dist/dev/internal/state.d.ts +139 -0
  62. package/dist/dev/internal/state.js +27 -0
  63. package/dist/dev/internal/state.js.map +1 -0
  64. package/dist/dev/internal/suspension.d.ts +41 -0
  65. package/dist/dev/internal/suspension.js +44 -0
  66. package/dist/dev/internal/suspension.js.map +1 -0
  67. package/dist/dev/internal/types.d.ts +44 -0
  68. package/dist/dev/list.d.ts +91 -0
  69. package/dist/dev/list.js +281 -0
  70. package/dist/dev/list.js.map +1 -0
  71. package/dist/dev/memo.d.ts +58 -0
  72. package/dist/dev/memo.js +40 -0
  73. package/dist/dev/memo.js.map +1 -0
  74. package/dist/dev/optimistic.d.ts +24 -0
  75. package/dist/dev/optimistic.js +44 -0
  76. package/dist/dev/optimistic.js.map +1 -0
  77. package/dist/dev/ownership.d.ts +202 -0
  78. package/dist/dev/ownership.js +260 -0
  79. package/dist/dev/ownership.js.map +1 -0
  80. package/dist/dev/props.d.ts +132 -0
  81. package/dist/dev/props.js +281 -0
  82. package/dist/dev/props.js.map +1 -0
  83. package/dist/dev/reaction.d.ts +27 -0
  84. package/dist/dev/reaction.js +60 -0
  85. package/dist/dev/reaction.js.map +1 -0
  86. package/dist/dev/reducer.d.ts +39 -0
  87. package/dist/dev/reducer.js +38 -0
  88. package/dist/dev/reducer.js.map +1 -0
  89. package/dist/dev/refs.d.ts +50 -0
  90. package/dist/dev/refs.js +57 -0
  91. package/dist/dev/refs.js.map +1 -0
  92. package/dist/dev/resource.d.ts +133 -0
  93. package/dist/dev/resource.js +176 -0
  94. package/dist/dev/resource.js.map +1 -0
  95. package/dist/dev/selector.d.ts +32 -0
  96. package/dist/dev/selector.js +117 -0
  97. package/dist/dev/selector.js.map +1 -0
  98. package/dist/dev/signal.d.ts +40 -0
  99. package/dist/dev/signal.js +38 -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 +191 -0
  104. package/dist/dev/store/nodes.js.map +1 -0
  105. package/dist/dev/store/proxies.js +159 -0
  106. package/dist/dev/store/proxies.js.map +1 -0
  107. package/dist/dev/store/read.d.ts +37 -0
  108. package/dist/dev/store/read.js +71 -0
  109. package/dist/dev/store/read.js.map +1 -0
  110. package/dist/dev/store/reconcile.d.ts +71 -0
  111. package/dist/dev/store/reconcile.js +185 -0
  112. package/dist/dev/store/reconcile.js.map +1 -0
  113. package/dist/dev/store/types.d.ts +104 -0
  114. package/dist/dev/store/use-store.d.ts +58 -0
  115. package/dist/dev/store/use-store.js +167 -0
  116. package/dist/dev/store/use-store.js.map +1 -0
  117. package/dist/dev/suspense.d.ts +99 -0
  118. package/dist/dev/suspense.js +44 -0
  119. package/dist/dev/suspense.js.map +1 -0
  120. package/dist/dev/transitions.d.ts +75 -0
  121. package/dist/dev/transitions.js +100 -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 +89 -0
  284. package/dist/server-dev/action.js.map +1 -0
  285. package/dist/server-dev/cache.js +61 -0
  286. package/dist/server-dev/cache.js.map +1 -0
  287. package/dist/server-dev/context.js +107 -0
  288. package/dist/server-dev/context.js.map +1 -0
  289. package/dist/server-dev/effect.js +55 -0
  290. package/dist/server-dev/effect.js.map +1 -0
  291. package/dist/server-dev/env.js +30 -0
  292. package/dist/server-dev/env.js.map +1 -0
  293. package/dist/server-dev/events.js +32 -0
  294. package/dist/server-dev/events.js.map +1 -0
  295. package/dist/server-dev/extend/index.js +316 -0
  296. package/dist/server-dev/extend/index.js.map +1 -0
  297. package/dist/server-dev/external-store.js +45 -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 +632 -0
  301. package/dist/server-dev/internal/concurrency.js.map +1 -0
  302. package/dist/server-dev/internal/devtools.js +76 -0
  303. package/dist/server-dev/internal/devtools.js.map +1 -0
  304. package/dist/server-dev/internal/diagnostics.js +101 -0
  305. package/dist/server-dev/internal/diagnostics.js.map +1 -0
  306. package/dist/server-dev/internal/dispose.js +48 -0
  307. package/dist/server-dev/internal/dispose.js.map +1 -0
  308. package/dist/server-dev/internal/flags.js +10 -0
  309. package/dist/server-dev/internal/flags.js.map +1 -0
  310. package/dist/server-dev/internal/graph.js +577 -0
  311. package/dist/server-dev/internal/graph.js.map +1 -0
  312. package/dist/server-dev/internal/hydration-flag.js +45 -0
  313. package/dist/server-dev/internal/hydration-flag.js.map +1 -0
  314. package/dist/server-dev/internal/messages.js +53 -0
  315. package/dist/server-dev/internal/messages.js.map +1 -0
  316. package/dist/server-dev/internal/owner.js +289 -0
  317. package/dist/server-dev/internal/owner.js.map +1 -0
  318. package/dist/server-dev/internal/queue.js +45 -0
  319. package/dist/server-dev/internal/queue.js.map +1 -0
  320. package/dist/server-dev/internal/scheduler.js +286 -0
  321. package/dist/server-dev/internal/scheduler.js.map +1 -0
  322. package/dist/server-dev/internal/state.js +27 -0
  323. package/dist/server-dev/internal/state.js.map +1 -0
  324. package/dist/server-dev/internal/suspension.js +44 -0
  325. package/dist/server-dev/internal/suspension.js.map +1 -0
  326. package/dist/server-dev/list.js +281 -0
  327. package/dist/server-dev/list.js.map +1 -0
  328. package/dist/server-dev/memo.js +40 -0
  329. package/dist/server-dev/memo.js.map +1 -0
  330. package/dist/server-dev/optimistic.js +44 -0
  331. package/dist/server-dev/optimistic.js.map +1 -0
  332. package/dist/server-dev/ownership.js +260 -0
  333. package/dist/server-dev/ownership.js.map +1 -0
  334. package/dist/server-dev/props.js +281 -0
  335. package/dist/server-dev/props.js.map +1 -0
  336. package/dist/server-dev/reaction.js +60 -0
  337. package/dist/server-dev/reaction.js.map +1 -0
  338. package/dist/server-dev/reducer.js +38 -0
  339. package/dist/server-dev/reducer.js.map +1 -0
  340. package/dist/server-dev/refs.js +57 -0
  341. package/dist/server-dev/refs.js.map +1 -0
  342. package/dist/server-dev/resource.js +175 -0
  343. package/dist/server-dev/resource.js.map +1 -0
  344. package/dist/server-dev/selector.js +81 -0
  345. package/dist/server-dev/selector.js.map +1 -0
  346. package/dist/server-dev/signal.js +38 -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 +191 -0
  350. package/dist/server-dev/store/nodes.js.map +1 -0
  351. package/dist/server-dev/store/proxies.js +159 -0
  352. package/dist/server-dev/store/proxies.js.map +1 -0
  353. package/dist/server-dev/store/read.js +71 -0
  354. package/dist/server-dev/store/read.js.map +1 -0
  355. package/dist/server-dev/store/reconcile.js +185 -0
  356. package/dist/server-dev/store/reconcile.js.map +1 -0
  357. package/dist/server-dev/store/use-store.js +167 -0
  358. package/dist/server-dev/store/use-store.js.map +1 -0
  359. package/dist/server-dev/suspense.js +44 -0
  360. package/dist/server-dev/suspense.js.map +1 -0
  361. package/dist/server-dev/transitions.js +85 -0
  362. package/dist/server-dev/transitions.js.map +1 -0
  363. package/package.json +111 -50
  364. package/dist/chunk-6Y3CCWOY.js +0 -887
  365. package/dist/chunk-6Y3CCWOY.js.map +0 -1
  366. package/dist/chunk-B5FTYDUG.js +0 -3
  367. package/dist/chunk-B5FTYDUG.js.map +0 -1
  368. package/dist/index.cjs +0 -2000
  369. package/dist/index.cjs.map +0 -1
  370. package/dist/index.d.cts +0 -609
  371. package/dist/index.d.ts +0 -609
  372. package/dist/index.js +0 -1094
  373. package/dist/index.js.map +0 -1
  374. package/dist/jsx-Bugil6CJ.d.cts +0 -151
  375. package/dist/jsx-Bugil6CJ.d.ts +0 -151
  376. package/dist/jsx-dev-runtime.cjs +0 -742
  377. package/dist/jsx-dev-runtime.cjs.map +0 -1
  378. package/dist/jsx-dev-runtime.d.cts +0 -2
  379. package/dist/jsx-dev-runtime.d.ts +0 -2
  380. package/dist/jsx-dev-runtime.js +0 -4
  381. package/dist/jsx-dev-runtime.js.map +0 -1
  382. package/dist/jsx-runtime.cjs +0 -742
  383. package/dist/jsx-runtime.cjs.map +0 -1
  384. package/dist/jsx-runtime.d.cts +0 -36
  385. package/dist/jsx-runtime.d.ts +0 -36
  386. package/dist/jsx-runtime.js +0 -4
  387. package/dist/jsx-runtime.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"effect.js","names":["useEffect","second","third","useRenderEffect","onMount"],"sources":["../../src/effect.ts"],"sourcesContent":["import { type Cleanup, createComputation, currentOwner, warn } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.\n * @since 1.0.0\n */\nexport interface EffectOptions {\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the effect is unnamed)\n */\n name?: string;\n}\n\n/**\n * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.\n * @since 1.0.0\n */\nexport interface DeferredEffectOptions extends EffectOptions {\n /**\n * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only\n * runs for later changes of it.\n * @default false\n */\n defer?: boolean;\n}\n\n/** What a held effect computes while its gate is closed: nothing for `apply` to act on. */\nconst HELD: unique symbol = Symbol(\"held\");\n\n/** The nearest gate above the current owner (see `Owner.gate`), or null. */\nfunction nearestGate(): (() => boolean) | null {\n for (let owner = currentOwner(); owner !== null; owner = owner.parent) {\n if (owner.gate !== null) return owner.gate;\n }\n return null;\n}\n\nfunction createEffect(\n fnIn: (previous: never) => unknown,\n applyIn: ((value: never, previous: never) => unknown) | null,\n render: boolean,\n deferIn: boolean,\n name: string | undefined,\n): void {\n // Effects never run on the server (G-24): no node, no ownership slot, no cost.\n if (__SERVER__) return;\n if (currentOwner() === null) warn(\"NO_OWNER_EFFECT\");\n let fn = fnIn;\n let apply = applyIn;\n let defer = deferIn;\n const gate = render ? null : nearestGate();\n if (gate !== null) {\n // Held until the gate first opens (a Suspense boundary resolving). The gate is only read until\n // then, so later changes of it never re-run the effect.\n let opened = false;\n const held = (): boolean => {\n if (opened) return false;\n if (gate()) return true;\n opened = true;\n return false;\n };\n if (apply === null) {\n const inner = fn;\n fn = (previous) => (held() ? undefined : inner(previous));\n } else {\n const innerFn = fn;\n const innerApply = apply;\n // `defer` skips the first real run, not the held one, so it is handled here.\n let skipFirst = defer;\n defer = false;\n fn = (previous) => (held() ? HELD : innerFn(previous));\n apply = (value, previous) => {\n if ((value as unknown) === HELD) return undefined;\n if (skipFirst) {\n skipFirst = false;\n return undefined;\n }\n return innerApply(value, ((previous as unknown) === HELD ? undefined : previous) as never);\n };\n }\n }\n createComputation({\n kind: \"effect\",\n fn,\n render,\n defer,\n ...(apply === null ? {} : { apply }),\n ...(name === undefined ? {} : { name }),\n });\n}\n\n/**\n * Runs a side effect after rendering and again whenever a tracked signal changes. The first run\n * is deferred to the next flush. Effects never run on the server. Inside a `<Suspense>` boundary\n * that is still showing its fallback, the first run waits until the boundary first shows its content.\n *\n * Two forms: `useEffect(fn)` tracks everything `fn` reads; `useEffect(deps, fn)` tracks only\n * `deps` and runs `fn` untracked. Return a function to clean up before the next run or disposal.\n * An error thrown by the effect goes to the owner's error handler (`onError`, an error boundary).\n * In development, an effect created outside any owner warns `NO_OWNER_EFFECT`: it still runs, but\n * nothing can dispose it.\n *\n * @param fn The effect. Every signal it reads is tracked. It may return a cleanup function.\n * @param options A devtools name. Undefined uses the default.\n * @example\n * import { useEffect, useSignal } from \"@shadow-js/core\";\n *\n * function PageTitle(props: { unread: number }) {\n * const [title] = useSignal(\"Inbox\");\n * useEffect(() => {\n * document.title = `${title()} (${props.unread})`; // re-runs when either changes\n * });\n * return null;\n * }\n * @see useRenderEffect\n * @see onMount\n * @since 1.0.0\n */\nexport function useEffect(fn: () => void | Cleanup, options?: EffectOptions): void;\n/**\n * Explicit-dependency form of {@link useEffect}: tracks only what `deps` reads, and calls `fn`\n * untracked with the new and the previous value of `deps`. Use it when the effect body reads\n * signals that must not re-run it.\n *\n * @param deps Tracked; its result is passed to `fn`.\n * @param fn Untracked; receives the value of `deps` and its previous value (`undefined` when there\n * is none yet). It may return a cleanup function, which runs before the next call or on disposal.\n * @param options `defer` skips the first call; a devtools name. Undefined uses the defaults.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n *\n * function Profile(props: { userId: string }) {\n * useEffect(\n * () => props.userId,\n * (next, previous) => console.log(`switched from ${previous} to ${next}`),\n * { defer: true }, // not called for the first id\n * );\n * return null;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useEffect<T>(\n deps: () => T,\n fn: (value: T, previous: T | undefined) => void | Cleanup,\n options?: DeferredEffectOptions,\n): void;\nexport function useEffect(\n first: () => unknown,\n second?: unknown,\n third?: DeferredEffectOptions,\n): void {\n if (typeof second === \"function\") {\n createEffect(\n first,\n second as (value: never, previous: never) => unknown,\n false,\n third?.defer === true,\n third?.name,\n );\n } else {\n if (Array.isArray(second)) warn(\"EFFECT_DEPS_IGNORED\");\n createEffect(first, null, false, false, (second as EffectOptions | undefined)?.name);\n }\n}\n\n/**\n * Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and\n * before user effects on every flush. Used for DOM bindings; application code rarely needs it.\n * It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In\n * development, one created outside any owner warns `NO_OWNER_EFFECT`.\n *\n * @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself\n * and may return a cleanup function.\n * @param apply Untracked; receives the value and the previous value (`undefined` on the first\n * run), and may return a cleanup function. Undefined: only `compute` runs.\n * @example\n * import { createRoot, useRenderEffect, useSignal } from \"@shadow-js/core\";\n *\n * const button = document.createElement(\"button\");\n * createRoot(() => {\n * const [label] = useSignal(\"Save\");\n * useRenderEffect(label, (text) => {\n * button.textContent = text; // runs now, and again when label changes\n * });\n * });\n * @see useEffect\n * @since 1.0.0\n */\nexport function useRenderEffect<T>(\n compute: () => T,\n apply?: (value: T, previous: T | undefined) => void | Cleanup,\n): void {\n createEffect(\n compute,\n (apply ?? null) as ((value: never, previous: never) => unknown) | null,\n true,\n false,\n undefined,\n );\n}\n\n/**\n * Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never\n * run it again. Its return value, if a function, is the cleanup, which runs when the owner is\n * disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`\n * boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.\n *\n * @param fn Runs once, untracked. It may return a cleanup function.\n * @example\n * import { onMount } from \"@shadow-js/core\";\n *\n * function SearchBox() {\n * let input: HTMLInputElement | undefined;\n * onMount(() => input?.focus());\n * return <input ref={(el: HTMLInputElement) => (input = el)} />;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function onMount(fn: () => void | Cleanup): void {\n createEffect(() => untrack(fn), null, false, false, \"onMount\");\n}\n"],"mappings":"A,kCAqJA,SAAgBA,EACd,EACA,EACA,EACM,CACF,OAAOC,GAAW,YACpBC,GAIS,MACPA,GAAO,MAITD,GAA+E,IAEnF,CAyBA,SAAgBE,EACd,EACA,EACM,CAQR,CAoBA,SAAgBC,EAAQ,EAAgC,CAExD,C"}
@@ -0,0 +1,2 @@
1
+ const e=!0,t=!1;export{t as isDev,e as isServer};
2
+ //# sourceMappingURL=env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","names":["isServer","isDev"],"sources":["../../src/env.ts"],"sourcesContent":["/**\n * True in the server condition build, where effects never run and rendering produces strings. Use\n * it to skip browser-only work. The value is fixed per build: the package export conditions\n * (`node`, `worker`, `browser`, ...) choose the build, not a runtime check.\n *\n * @example\n * import { isServer } from \"@shadow-js/core\";\n *\n * const width = isServer ? 1024 : window.innerWidth;\n * @see isDev\n * @since 1.0.0\n */\nexport const isServer: boolean = __SERVER__;\n\n/**\n * True in development builds; false in production builds where `__DEV__` is compiled away. The\n * `development` export condition selects the development build. Use it to guard checks and logging\n * meant for development only.\n *\n * @example\n * import { isDev } from \"@shadow-js/core\";\n *\n * if (isDev) console.info(\"debug panel enabled\");\n * @see isServer\n * @since 1.0.0\n */\nexport const isDev: boolean = __DEV__;\n"],"mappings":"AAYA,MAAaA,EAAA,GAcAC,EAAA,G"}
@@ -0,0 +1,2 @@
1
+ import{untrack as e}from"./ownership.js";function t(t){return(...n)=>e(()=>t(...n))}export{t as useEvent};
2
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","names":["useEvent","args","untrack","handler"],"sources":["../../src/events.ts"],"sourcesContent":["import { untrack } from \"./ownership\";\n\n/**\n * A stable callback that always runs its handler untracked. The ShadowJS form of React's\n * `useEffectEvent`: components run once and props are getters, so the handler already sees the\n * latest values. What it adds is the untracked call: an effect that calls the event does not\n * subscribe to the signals the handler reads.\n *\n * @param handler The handler. Its arguments and result are passed through.\n * @returns A new function with the same signature that calls `handler` untracked. Create it once,\n * in the component body, and keep the reference.\n * @example\n * import { useEffect, useEvent, useSignal } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const [count] = useSignal(0);\n * const onTick = useEvent(() => console.log(count())); // count() is not tracked by the effect\n * useEffect(() => {\n * const id = setInterval(() => onTick(), 1000);\n * return () => clearInterval(id);\n * });\n * return null;\n * }\n * @see untrack\n * @since 1.0.0\n */\nexport function useEvent<A extends unknown[], R>(handler: (...args: A) => R): (...args: A) => R {\n return (...args: A): R => untrack(() => handler(...args));\n}\n"],"mappings":"A,yCA0BA,SAAgBA,EAAiC,EAA+C,CAC9F,OAAQ,GAAGC,IAAeC,MAAcC,EAAQ,GAAGF,CAAI,CAAC,CAC1D,C"}
@@ -0,0 +1,2 @@
1
+ import{DEVTOOLS_EVENT as e,report as t}from"../internal/devtools.js";import{MESSAGES as n,formatMessage as r}from"../internal/messages.js";import{ShadowError as i,resetWarningDedupe as a,setWarningListener as o,warn as s}from"../internal/diagnostics.js";import{rt as c}from"../internal/state.js";import{Owner as l,addCleanup as u,handleError as d}from"../internal/owner.js";import{enqueue as f}from"../internal/queue.js";import{Computation as p,Signal as m,hasObservers as h,markObservers as g,observersOf as _,readMemo as v,readSignal as y,recompute as b,sourcesOf as x,track as S,updateIfNecessary as C}from"../internal/graph.js";import{batch as w,flush as T,flushSync as E,group as D,schedule as O}from"../internal/scheduler.js";import{runWithContext as k}from"../context.js";import{disposeTree as A}from"../internal/dispose.js";import{SUSPENSION as j,isSuspension as M}from"../internal/suspension.js";import{beginHold as ee,createTransitionHold as N,endHold as P,holdReader as F,inTransition as I,pauseOwner as L,registerTransitionLane as R,resumeOwner as z,startTransition as B,transitionHooks as V,wakeSuspended as H}from"../internal/concurrency.js";import{isHydrating as U,withHydration as W}from"../internal/hydration-flag.js";function G(){return c.owner}function K(){return c.listener}function q(){return c.listener!==null}function J(){return c.disposing===0&&c.running!==null&&c.running.kind===1&&!(c.running.flags&256)}function Y(e,t){let n=c.owner,r=c.listener;try{let n=e.owner;n!==void 0&&(c.owner=n);let r=e.listener;return r!==void 0&&(c.listener=r),t()}finally{c.owner=n,c.listener=r}}function X(e,t,n){return new m(e,t,n)}function Z(e,t,n){let r=e.equals;return r!==!1&&r(e.value,t)?!1:(e.value=t,Q(e),!0)}function Q(e){h(e)&&(g(e),O())}function $(e){let t=e.owner===void 0?c.owner:e.owner;if(e.kind===`memo`){let n=new p(t,1,32|(e.allowWrites===!0?256:0),e.fn,e.equals??Object.is,e.name);return e.lazy!==!0&&C(n),n}let n=(e.render===!0?16:0)|(e.defer===!0?64:0)|(e.lane===!0?512:0),r=new p(t,2,n,e.fn,!1,e.name);return r.apply=e.apply??null,e.render===!0?b(r):(f(r),O()),r}function te(e){return v(e)}function ne(e){C(e)}function re(e){return new l(e===void 0?c.owner:e)}export{p as ComputationNode,e as DEVTOOLS_EVENT,n as MESSAGES,l as Owner,j as SUSPENSION,i as ShadowError,m as SignalNode,u as addCleanup,w as batch,ee as beginHold,$ as createComputation,re as createOwner,X as createSignalNode,N as createTransitionHold,K as currentListener,G as currentOwner,t as devtoolsReport,A as disposeOwner,P as endHold,T as flush,E as flushSync,r as formatMessage,D as group,d as handleError,F as holdReader,I as inTransition,J as isComputingMemo,U as isHydrating,M as isSuspension,q as isTracking,g as markObservers,Q as notify,_ as observersOf,L as pauseOwner,te as readComputation,y as readSignal,ne as refresh,R as registerTransitionLane,a as resetWarningDedupe,z as resumeOwner,Y as runInScope,k as runWithContext,O as schedule,o as setWarningListener,x as sourcesOf,B as startTransition,S as track,V as transitionHooks,H as wakeSuspended,s as warn,W as withHydration,Z as writeSignal};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["OwnerClass","currentOwner","rt","currentListener","isTracking","isComputingMemo","runInScope","owner","listener","nextOwner","scope","nextListener","fn","createSignalNode","Signal","value","equals","name","writeSignal","signal","next","notify","hasObservers","source","markObservers","schedule","createComputation","options","node","Computation","updateIfNecessary","flags","recompute","enqueue","readComputation","readMemo","refresh","createOwner","Owner","parent","DEVTOOLS_EVENT","MESSAGES","SUSPENSION","ShadowError","addCleanup","batch","beginHold","createTransitionHold","report","disposeTree","endHold","flush","flushSync","formatMessage","group","handleError","holdReader","inTransition","isHydrating","isSuspension","observersOf","pauseOwner","readSignal","registerTransitionLane","resetWarningDedupe","resumeOwner","runWithContext","setWarningListener","sourcesOf","startTransition","track","transitionHooks","wakeSuspended","warn","withHydration"],"sources":["../../../src/extend.ts"],"sourcesContent":["/**\n * The extension API: everything the built-in hooks (`useSignal`, `useMemo`, `useEffect`,\n * `useStore`, `useResource`, `mapArray`, `useSelector`, contexts, ...) are built from. They import\n * ONLY this module, never the engine internals, so a third-party package can create hooks with the\n * same behavior, performance and diagnostics. A test (`public-api.test.ts`) enforces that.\n *\n * Import from `@shadow-js/core/extend`. These functions are stable but low level: prefer the hooks\n * unless you are building a new primitive.\n *\n * @packageDocumentation\n */\n\nimport { DEVTOOLS_EVENT, report } from \"./internal/devtools\";\nimport { ShadowError } from \"./internal/diagnostics\";\nimport {\n FLAG_ALLOW_WRITES,\n FLAG_DEFER,\n FLAG_LANE,\n FLAG_RENDER,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n} from \"./internal/flags\";\nimport {\n Computation,\n hasObservers,\n markObservers,\n observersOf,\n readMemo,\n readSignal,\n recompute,\n Signal,\n type Source,\n sourcesOf,\n track,\n updateIfNecessary,\n} from \"./internal/graph\";\nimport { type Owner, Owner as OwnerClass } from \"./internal/owner\";\nimport { enqueue } from \"./internal/queue\";\nimport { schedule } from \"./internal/scheduler\";\nimport { rt } from \"./internal/state\";\nimport type { Equals } from \"./internal/types\";\n\nexport { runWithContext } from \"./context\";\nexport {\n beginHold,\n createTransitionHold,\n endHold,\n holdReader,\n inTransition,\n pauseOwner,\n registerTransitionLane,\n resumeOwner,\n startTransition,\n transitionHooks,\n wakeSuspended,\n} from \"./internal/concurrency\";\nexport { DEVTOOLS_EVENT, report as devtoolsReport } from \"./internal/devtools\";\nexport type { WarningListener } from \"./internal/diagnostics\";\nexport { resetWarningDedupe, ShadowError, setWarningListener, warn } from \"./internal/diagnostics\";\nexport { disposeTree as disposeOwner } from \"./internal/dispose\";\nexport { isHydrating, withHydration } from \"./internal/hydration-flag\";\nexport type { MessageCode } from \"./internal/messages\";\nexport { formatMessage, MESSAGES } from \"./internal/messages\";\nexport type { ContextMap } from \"./internal/owner\";\nexport { addCleanup, handleError, Owner } from \"./internal/owner\";\nexport { batch, flush, flushSync, group } from \"./internal/scheduler\";\nexport type {\n BoundaryHold,\n SlotBranch,\n SlotChoice,\n SlotOwned,\n SlotState,\n SlotSwap,\n TransitionHold,\n} from \"./internal/state\";\nexport { isSuspension, SUSPENSION } from \"./internal/suspension\";\nexport type {\n Accessor,\n AnyFunction,\n Cleanup,\n Equals,\n ErrorHandler,\n Setter,\n} from \"./internal/types\";\nexport type { Source as SourceNode };\nexport { Computation as ComputationNode, Signal as SignalNode };\n\n// ---------- registers ----------\n\n/**\n * Returns the owner that adopts nodes created right now. The extension-API form of `getOwner`: use\n * it in a primitive that attaches a node or a cleanup to its caller's owner.\n *\n * @returns The current owner, or `null` outside any owner.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * function useInterval(fn: () => void, ms: number): void {\n * const timer = setInterval(fn, ms);\n * const owner = currentOwner();\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see createOwner\n * @since 1.0.0\n */\nexport function currentOwner(): Owner | null {\n return rt.owner;\n}\n\n/**\n * Returns the computation that records reads right now. Use it in a primitive whose read behaves\n * differently for a tracked reader, for example one that holds a boundary only for a listening\n * memo or effect.\n *\n * @returns The listening memo or effect, or `null` when reads are untracked.\n * @example\n * import { currentListener } from \"@shadow-js/core/extend\";\n *\n * function readWithStats<T>(read: () => T, stats: { tracked: number }): T {\n * if (currentListener() !== null) stats.tracked += 1;\n * return read();\n * }\n * @see isTracking\n * @since 1.0.0\n */\nexport function currentListener(): Computation | null {\n return rt.listener;\n}\n\n/**\n * Says whether reads are being recorded as dependencies right now. Use it to skip subscription\n * work, or to warn, when a primitive is read outside an effect or a memo.\n *\n * @returns `true` while an effect or a memo runs tracked, `false` otherwise (module scope,\n * `untrack`, event handlers).\n * @example\n * import { untrack, useMemo } from \"@shadow-js/core\";\n * import { isTracking } from \"@shadow-js/core/extend\";\n *\n * const inMemo = useMemo(() => isTracking());\n * console.log(inMemo(), untrack(() => isTracking())); // true false\n * @see currentListener\n * @since 1.0.0\n */\nexport function isTracking(): boolean {\n return rt.listener !== null;\n}\n\n/**\n * Says whether a memo (not an effect) is computing right now: writing signals is a mistake there.\n * Cleanups that run while a memo tears down rows or children may write, so a disposal in progress\n * is not a violation, and neither is a memo created with `allowWrites`. Use it to guard a custom\n * write path the way {@link writeSignal} does.\n *\n * @returns `true` while a memo without `allowWrites` computes and no disposal is running.\n * @example\n * import { isComputingMemo, ShadowError } from \"@shadow-js/core/extend\";\n *\n * function appendLog(log: string[], entry: string): void {\n * if (isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n * log.push(entry);\n * }\n * @since 1.0.0\n */\nexport function isComputingMemo(): boolean {\n return (\n rt.disposing === 0 &&\n rt.running !== null &&\n rt.running.kind === KIND_MEMO &&\n (rt.running.flags & FLAG_ALLOW_WRITES) === 0\n );\n}\n\n/**\n * Runs `fn` with the given owner and listener in effect, and restores both afterward, even when\n * `fn` throws. The low-level form of `runWithOwner` and `untrack`; unlike `runWithOwner` it does\n * not check whether the owner is disposed.\n *\n * @param scope `owner` and `listener` to install. For each, `undefined` (or absent) keeps the\n * current one and `null` clears it.\n * Getters are evaluated once; a failed getter restores the original scope.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates after the registers are\n * restored.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * runInScope({ owner, listener: null }, () => {\n * onCleanup(() => console.log(\"released\"));\n * });\n * disposeOwner(owner); // logs \"released\"\n * @see createOwner\n * @since 1.0.0\n */\nexport function runInScope<T>(\n scope: { owner?: Owner | null; listener?: Computation | null },\n fn: () => T,\n): T {\n const owner = rt.owner;\n const listener = rt.listener;\n try {\n const nextOwner = scope.owner;\n if (nextOwner !== undefined) rt.owner = nextOwner;\n const nextListener = scope.listener;\n if (nextListener !== undefined) rt.listener = nextListener;\n return fn();\n } finally {\n rt.owner = owner;\n rt.listener = listener;\n }\n}\n\n// ---------- reactive cells ----------\n\n/**\n * Creates the storage of a signal: its value, its equality and the observers that read it. Read it\n * with `readSignal` and write it with {@link writeSignal}; `useSignal` is built this way.\n *\n * @param value Initial value.\n * @param equals Decides whether a write is a change: readers are notified only when it returns\n * `false`. `false` notifies on every write.\n * @param name Label shown by devtools. Undefined leaves the signal unnamed.\n * @returns The signal node. It has no owner: it lives as long as something references it.\n * @example\n * import { createSignalNode, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const temperature = createSignalNode<number>(20, Object.is, \"temperature\");\n * const read = () => readSignal(temperature);\n * writeSignal(temperature, 21);\n * console.log(read()); // 21\n * @see writeSignal\n * @since 1.0.0\n */\nexport function createSignalNode<T>(value: T, equals: Equals<T>, name?: string): Signal<T> {\n return new Signal<T>(value, equals, name);\n}\n\n/**\n * Options of {@link writeSignal}.\n * @since 1.0.0\n */\nexport interface WriteOptions {\n /**\n * Permit the write while a memo computes, for bookkeeping signals owned by a primitive (a\n * Suspense counter, a resource's state). Turns the development `WRITE_IN_MEMO` check off for\n * this write.\n * @default false\n */\n allowInMemo?: boolean;\n}\n\n/**\n * Stores a new value in a signal node and notifies its readers when the value differs by the\n * signal's equality. Effects that read it run on the next flush; memos recompute on their next\n * read.\n *\n * @param signal The node, from {@link createSignalNode}.\n * @param next The new value. A function is stored as is: there is no updater form.\n * @param options `allowInMemo` permits the write while a memo computes. Undefined uses the default.\n * @returns `true` when the value changed and was stored, `false` when the equality kept the old\n * value (nobody is notified then).\n * @throws ShadowError `WRITE_IN_MEMO`, in development builds only, when a memo is computing and\n * `allowInMemo` is not set.\n * @example\n * import { createSignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const status = createSignalNode<string>(\"idle\", Object.is);\n * console.log(writeSignal(status, \"loading\")); // true\n * console.log(writeSignal(status, \"loading\")); // false: an equal value notifies nobody\n * @see notify\n * @since 1.0.0\n */\nexport function writeSignal<T>(signal: Signal<T>, next: T, options?: WriteOptions): boolean {\n if (__DEV__ && options?.allowInMemo !== true && isComputingMemo()) {\n throw new ShadowError(\"WRITE_IN_MEMO\");\n }\n const equals = signal.equals;\n if (equals !== false && equals(signal.value, next)) return false;\n signal.value = next;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.SIGNAL_WRITTEN, signal, next, rt.running, observersOf(signal));\n }\n notify(signal);\n return true;\n}\n\n/**\n * Marks the observers of `source` stale and schedules a flush. Call it after changing a source's\n * value in place (for example after mutating an array a signal node holds), where\n * {@link writeSignal} cannot see the change.\n *\n * @param source A signal or memo node. A source nobody observes is left alone.\n * @example\n * import { createSignalNode, notify } from \"@shadow-js/core/extend\";\n *\n * const list = createSignalNode<string[]>([], false);\n * list.value.push(\"milk\"); // an in-place change: no equality can see it\n * notify(list); // the readers of `list` run again\n * @see writeSignal\n * @since 1.0.0\n */\nexport function notify(source: Source): void {\n if (!hasObservers(source)) return;\n markObservers(source);\n schedule();\n}\n\nexport { markObservers, observersOf, readSignal, schedule, sourcesOf, track };\n\n// ---------- computations (memos and effects) ----------\n\n/**\n * Options of {@link createComputation}.\n * @since 1.0.0\n */\nexport interface ComputationOptions {\n /**\n * `\"memo\"` creates a cached value that readers pull with {@link readComputation}; `\"effect\"`\n * creates a side effect that the scheduler runs.\n */\n kind: \"memo\" | \"effect\";\n /**\n * The computation. It is tracked: every source it reads becomes a dependency. It receives the\n * previous value (a memo's last value, or an effect's last computed value when `apply` is set;\n * `undefined` otherwise). A memo stores its result; an effect without `apply` may return a\n * cleanup function.\n */\n fn: (previous: never) => unknown;\n /**\n * Memos: decides whether a recomputation changed the value; readers are notified only when it\n * returns `false`, and `false` always propagates. Ignored for effects.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the node is unnamed)\n */\n name?: string;\n /**\n * Effects: run in the render phase, synchronously at creation and before user effects in each\n * flush. Ignored for memos.\n * @default false\n */\n render?: boolean;\n /**\n * Effects with `apply`: skip the first call of `apply`; `fn` still runs and tracks.\n * @default false\n */\n defer?: boolean;\n /**\n * Memos: do not compute until the first read.\n * @default false (the memo computes once at creation)\n */\n lazy?: boolean;\n /**\n * Memos that run component setup (such as a hot-reload wrapper): writing signals inside is\n * legitimate there, so the dev-mode write guard stays off.\n * @default false\n */\n allowWrites?: boolean;\n /**\n * Effects: second stage, run untracked with the value `fn` computed and the previous one. It may\n * return a cleanup function.\n * @default undefined (`fn` is the whole effect)\n */\n apply?: (value: never, previous: never) => unknown;\n /**\n * Owner to attach to. `null` creates a node that no owner disposes.\n * @default the current owner\n */\n owner?: Owner | null;\n /**\n * Effects: always run in the transition lane (the watcher behind `useDeferredValue`).\n * @default false\n */\n lane?: boolean;\n}\n\n/**\n * Creates a memo or effect node: the building block of `useMemo`, `useEffect` and the render\n * effects of a renderer. Memos compute immediately unless `lazy`; render effects run immediately;\n * user effects are queued for the next flush. The node is owned and disposed with its owner.\n * Errors of a memo are stored and rethrown to its readers; errors of an effect go to the owner's\n * error handler.\n *\n * @param options What to create, how it runs and where it is owned.\n * @returns The node. Read a memo with {@link readComputation}; an effect needs no handle.\n * @throws The error of a render effect's first run when no error handler takes it and no flush is\n * running.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode<number>(10, Object.is);\n * const withTax = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 1.2 });\n * createComputation({\n * kind: \"effect\",\n * fn: () => console.log(readComputation<number>(withTax)),\n * });\n * writeSignal(price, 20); // the effect logs 24 on the next flush\n * @see readComputation\n * @since 1.0.0\n */\nexport function createComputation(options: ComputationOptions): Computation {\n const owner = options.owner === undefined ? rt.owner : options.owner;\n if (options.kind === \"memo\") {\n const node = new Computation(\n owner,\n KIND_MEMO,\n FLAG_UNINIT | (options.allowWrites === true ? FLAG_ALLOW_WRITES : 0),\n options.fn,\n options.equals ?? Object.is,\n options.name,\n );\n if (options.lazy !== true) updateIfNecessary(node);\n return node;\n }\n const flags =\n (options.render === true ? FLAG_RENDER : 0) |\n (options.defer === true ? FLAG_DEFER : 0) |\n (options.lane === true ? FLAG_LANE : 0);\n const node = new Computation(owner, KIND_EFFECT, flags, options.fn, false, options.name);\n node.apply = options.apply ?? null;\n if (options.render === true) {\n // A suspended render effect keeps its DOM and waits on its own: its creator completes normally\n // (the branch that holds it decides whether to commit; see createBranches).\n recompute(node);\n } else {\n enqueue(node);\n schedule();\n }\n return node;\n}\n\n/**\n * Reads a memo node: brings it up to date if a source changed, subscribes the running computation\n * to it, and rethrows the error its last run stored. The accessor `useMemo` returns is this call.\n *\n * @param node A memo node from {@link createComputation}.\n * @returns The memo's current value.\n * @throws The error the memo's last computation threw, when no error handler took it. ShadowError\n * `CYCLE_DETECTED` when the memo is read while it computes.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const first = createSignalNode<string>(\"Ada\", Object.is);\n * const greeting = createComputation({ kind: \"memo\", fn: () => `Hello, ${readSignal(first)}` });\n * console.log(readComputation<string>(greeting)); // \"Hello, Ada\"\n * @see createComputation\n * @since 1.0.0\n */\nexport function readComputation<T>(node: Computation): T {\n return readMemo<T>(node);\n}\n\n/**\n * Brings a memo or effect node up to date if one of its sources changed, without tracking it. Use\n * it to settle a node before reading its fields directly.\n *\n * @param node A node from {@link createComputation}. A node that is up to date is left as is.\n * @throws ShadowError `CYCLE_DETECTED` when a dependency is still computing (a cycle). An effect\n * that re-runs routes its errors to its owner's error handler.\n * @example\n * import { createComputation, createSignalNode, readSignal, refresh, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is);\n * const doubled = createComputation({ kind: \"memo\", fn: () => readSignal(count) * 2 });\n * writeSignal(count, 2);\n * refresh(doubled);\n * console.log(doubled.value); // 4\n * @see readComputation\n * @since 1.0.0\n */\nexport function refresh(node: Computation): void {\n updateIfNecessary(node);\n}\n\n/**\n * Creates a plain owner: a scope that adopts the nodes and cleanups created under it and disposes\n * them together. The building block of `createRoot` and of control-flow branches.\n *\n * @param parent The owner to attach to and inherit context from. Undefined (or omitted) uses the\n * current owner; `null` creates a root with no context that only an explicit dispose ends.\n * @returns The new owner. Dispose it with `disposeOwner`.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const branch = createOwner();\n * runInScope({ owner: branch, listener: null }, () => {\n * useEffect(() => console.log(\"branch effect\"));\n * });\n * disposeOwner(branch); // the effect and its cleanups are gone\n * @see runInScope\n * @since 1.0.0\n */\nexport function createOwner(parent?: Owner | null): Owner {\n return new OwnerClass(parent === undefined ? rt.owner : parent);\n}\n"],"mappings":"A,mtCA0GA,SAAgBC,GAA6B,CAC3C,OAAOC,EAAG,KACZ,CAkBA,SAAgBC,GAAsC,CACpD,OAAOD,EAAG,QACZ,CAiBA,SAAgBE,GAAsB,CACpC,OAAOF,EAAG,WAAa,IACzB,CAkBA,SAAgBG,GAA2B,CACzC,OACEH,EAAG,YAAc,GACjBA,EAAG,UAAY,MACfA,EAAG,QAAQ,OAAA,GAAA,EACVA,EAAG,QAAQ,MAAA,IAEhB,CAyBA,SAAgBI,EACd,EACA,EACG,CACH,IAAMC,EAAQL,EAAG,MACXM,EAAWN,EAAG,SACpB,GAAI,CACF,IAAMO,EAAYC,EAAM,MACpBD,IAAc,IAAA,KAAW,EAAG,MAAQA,GACxC,IAAME,EAAeD,EAAM,SAE3B,OADIC,IAAiB,IAAA,KAAW,EAAG,SAAWA,GACvCC,EAAG,CACZ,QAAU,CACR,EAAG,MAAQL,EACX,EAAG,SAAWC,CAChB,CACF,CAuBA,SAAgBK,EAAoB,EAAU,EAAmB,EAA0B,CACzF,OAAO,IAAIC,EAAUC,EAAOC,EAAQC,CAAI,CAC1C,CAqCA,SAAgBC,EAAe,EAAmB,EAAS,EAAiC,CAI1F,IAAMF,EAASG,EAAO,OAOtB,OANIH,IAAW,IAASA,EAAOG,EAAO,MAAOC,CAAI,EAAU,IAC3D,EAAO,MAAQA,EAIfC,EAAOF,CAAM,EACN,GACT,CAiBA,SAAgBE,EAAO,EAAsB,CACtCC,EAAaC,CAAM,IACxBC,EAAcD,CAAM,EACpBE,EAAS,EACX,CAkGA,SAAgBC,EAAkB,EAA0C,CAC1E,IAAMnB,EAAQoB,EAAQ,QAAU,IAAA,GAAYzB,EAAG,MAAQyB,EAAQ,MAC/D,GAAIA,EAAQ,OAAS,OAAQ,CAC3B,IAAMC,EAAO,IAAIC,EACftB,EAAA,EAAA,IAEeoB,EAAQ,cAAgB,GAAA,IAA2B,GAClEA,EAAQ,GACRA,EAAQ,QAAU,OAAO,GACzBA,EAAQ,IACV,EAEA,OADIA,EAAQ,OAAS,IAAMG,EAAkBF,CAAI,EAC1CA,CACT,CACA,IAAMG,GACHJ,EAAQ,SAAW,GAAA,GAAqB,IACxCA,EAAQ,QAAU,GAAA,GAAoB,IACtCA,EAAQ,OAAS,GAAA,IAAmB,GACjCC,EAAO,IAAIC,EAAYtB,EAAA,EAAoBwB,EAAOJ,EAAQ,GAAI,GAAOA,EAAQ,IAAI,EAUvF,MATA,GAAK,MAAQA,EAAQ,OAAS,KAC1BA,EAAQ,SAAW,GAGrBK,EAAUJ,CAAI,GAEdK,EAAQL,CAAI,EACZH,EAAS,GAEJG,CACT,CAmBA,SAAgBM,GAAmB,EAAsB,CACvD,OAAOC,EAAYP,CAAI,CACzB,CAoBA,SAAgBQ,GAAQ,EAAyB,CAC/CN,EAAkBF,CAAI,CACxB,CAqBA,SAAgBS,GAAY,EAA8B,CACxD,OAAO,IAAIrC,EAAWuC,IAAW,IAAA,GAAYrC,EAAG,MAAQqC,CAAM,CAChE,C"}
@@ -0,0 +1,2 @@
1
+ import{untrack as e}from"./ownership.js";function t(t,n,r){{let t=e(r?.getServerSnapshot??n);return()=>t}}export{t as useExternalStore};
2
+ //# sourceMappingURL=external-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"external-store.js","names":["useExternalStore","snapshot","untrack","options","getSnapshot"],"sources":["../../src/external-store.ts"],"sourcesContent":["import { useEffect } from \"./effect\";\nimport type { Accessor, Equals } from \"./extend\";\nimport { isHydrating } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useExternalStore}. @since 1.0.0 */\nexport interface ExternalStoreOptions<T> {\n /**\n * The snapshot the server renders (there is no subscription there). Without it the server reads\n * `getSnapshot` once. Keep it equal to what the browser reads on its first render: a difference is\n * corrected only after subscribing, and no hydration test covers that case yet. While hydrating,\n * the browser's first render also uses it.\n * @default undefined (the server, and hydration, read `getSnapshot`)\n */\n getServerSnapshot?: () => T;\n /**\n * Decides whether a new snapshot is a change: the accessor updates only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\n/**\n * Reads a value that lives outside ShadowJS (a store, a browser API, an observable) as a reactive\n * accessor. The one bridge for every external source, and the ShadowJS form of React's\n * `useSyncExternalStore` and Solid's `from`.\n *\n * `subscribe(notify)` is called in an effect after the owner is created and returns the\n * unsubscribe function, which runs when the owner is disposed. `getSnapshot()` is read untracked\n * at creation, on every notification, and once after subscribing (so a change made between the\n * first read and the subscription is not lost). The accessor updates only when the snapshot differs\n * by `equals`. On the server nothing is subscribed: the accessor returns `getServerSnapshot()`.\n *\n * @param subscribe Registers `notify`; returns the unsubscribe function.\n * @param getSnapshot Returns the current value. Reads inside it are not tracked.\n * @param options Server snapshot, equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the current snapshot.\n * @example\n * import { useExternalStore } from \"@shadow-js/core\";\n *\n * function subscribe(notify: () => void): () => void {\n * window.addEventListener(\"online\", notify);\n * window.addEventListener(\"offline\", notify);\n * return () => {\n * window.removeEventListener(\"online\", notify);\n * window.removeEventListener(\"offline\", notify);\n * };\n * }\n *\n * function OnlineBadge() {\n * const online = useExternalStore(subscribe, () => navigator.onLine, { getServerSnapshot: () => true });\n * return <span>{online() ? \"online\" : \"offline\"}</span>;\n * }\n * @see useSignal\n * @since 1.0.0\n */\nexport function useExternalStore<T>(\n subscribe: (notify: () => void) => () => void,\n getSnapshot: () => T,\n options?: ExternalStoreOptions<T>,\n): Accessor<T> {\n if (__SERVER__) {\n const snapshot = untrack(options?.getServerSnapshot ?? getSnapshot);\n return () => snapshot;\n }\n // While hydrating, the first render must equal the server markup: the server snapshot, when given.\n // The browser's snapshot is applied by the subscription below.\n const first =\n isHydrating() && options?.getServerSnapshot !== undefined\n ? options.getServerSnapshot\n : getSnapshot;\n const [value, setValue] = useSignal<T>(untrack(first), {\n equals: options?.equals ?? Object.is,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n const sync = (): void => {\n const next = untrack(getSnapshot);\n setValue(() => next);\n };\n useEffect(() => {\n const unsubscribe = subscribe(sync);\n // Catch up with changes made between the first read and the subscription.\n sync();\n return unsubscribe;\n });\n return value;\n}\n"],"mappings":"A,yCA8DA,SAAgBA,EACd,EACA,EACA,EACa,CACG,CACd,IAAMC,EAAWC,EAAQC,GAAS,mBAAqBC,CAAW,EAClE,UAAaH,CACf,CAsBF,C"}
@@ -0,0 +1 @@
1
+ import{batch as e,flushSync as t}from"./internal/scheduler.js";import{catchError as n,createRoot as r,getOwner as i,onCleanup as a,onError as o,runWithOwner as s,untrack as c,useId as l}from"./ownership.js";import{onMount as u,useEffect as d,useRenderEffect as f}from"./effect.js";import{useSignal as p}from"./signal.js";import{createContext as m,useContext as h}from"./context.js";import{ResourceCacheContext as g,SuspenseContext as _}from"./suspense.js";import{startTransition as v}from"./internal/concurrency.js";import{useAction as y}from"./action.js";import{cache as b}from"./cache.js";import{isDev as x,isServer as S}from"./env.js";import{useEvent as C}from"./events.js";import{useExternalStore as w}from"./external-store.js";import{useMemo as T}from"./memo.js";import{indexArray as E,mapArray as D}from"./list.js";import{useOptimistic as O}from"./optimistic.js";import{children as k,mergeProps as A,splitProps as j}from"./props.js";import{useReaction as M}from"./reaction.js";import{useReducer as N}from"./reducer.js";import{createRef as P,useImperativeHandle as F}from"./refs.js";import{useResource as I}from"./resource.js";import{useSelector as L}from"./selector.js";import{snapshot as R,unwrap as z}from"./store/read.js";import{produce as B,reconcile as V}from"./store/reconcile.js";import{useStore as H}from"./store/use-store.js";import{useDeferredValue as U,useTransition as W}from"./transitions.js";export{g as ResourceCacheContext,_ as SuspenseContext,e as batch,b as cache,n as catchError,k as children,m as createContext,P as createRef,r as createRoot,t as flushSync,i as getOwner,E as indexArray,x as isDev,S as isServer,D as mapArray,A as mergeProps,a as onCleanup,o as onError,u as onMount,B as produce,V as reconcile,s as runWithOwner,R as snapshot,j as splitProps,v as startTransition,c as untrack,z as unwrap,y as useAction,h as useContext,U as useDeferredValue,d as useEffect,C as useEvent,w as useExternalStore,l as useId,F as useImperativeHandle,T as useMemo,O as useOptimistic,M as useReaction,N as useReducer,f as useRenderEffect,I as useResource,L as useSelector,p as useSignal,H as useStore,W as useTransition};
@@ -0,0 +1,2 @@
1
+ import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_SUSPENDED as n,FLAG_TRANSITION as r}from"./flags.js";import{rt as i}from"./state.js";import{Owner as a,addCleanup as o,handleError as s}from"./owner.js";import{clearQueues as c,hasPending as l,place as u,renderQueue as d,userQueue as f}from"./queue.js";import{Computation as p,Signal as m,hasObservers as h,markObservers as g,readSignal as _,recompute as v,updateIfNecessary as y}from"./graph.js";import{byCreation as b,isOrdered as x,reportUncaught as S,schedule as C}from"./scheduler.js";import{runWithContext as w}from"../context.js";import{SuspenseContext as T}from"../suspense.js";import{disposeTree as E}from"./dispose.js";import{SUSPENSION as D,isSuspension as O}from"./suspension.js";function k(e,t){let n=[e];for(;n.length>0;){let e=n.pop();if(e===void 0)break;t(e);for(let t=e.lastChild;t!==null;t=t.prevSibling)n.push(t)}}function A(){let A=[],j=[],M=[],N=[],P=0,F=!1,I=()=>A.length>0||j.length>0,L=()=>I()||P>0,R=(e,n)=>{let i=e.splice(0,n);x(i)||i.sort(b);for(let e of i)if(e.flags&1024&&(e.flags&=~(2|r),!(e.flags&4))){if(e.pauses>0)e.flags|=t|r;else try{e.state===2?v(e):y(e)}catch(t){s(t,e)}}return i.length},z=()=>{if(L()||M.length===0)return;let e=M.splice(0,M.length);for(let t of e)t()},B=()=>{F||(F=!0,setTimeout(V,0))},V=()=>{if(F=!1,i.flushing){B();return}let t=i.inTransition;i.inTransition=!0,i.flushing=!0;let n=64,r=0;try{for(;n>0&&I();){if(r+=1,r>1e3){c(),i.uncaught.push(new e(`INFINITE_LOOP`));break}let t=A.length>0?A:j;n-=R(t,n)}}finally{i.inTransition=t,i.flushing=!1}let a=i.uncaught.splice(0,i.uncaught.length);for(let e of a)S(e);I()?B():z(),l()&&C()},H=e=>{let t=i.inTransition,n=i.listener;i.inTransition=!0,i.listener=null;try{e()}finally{i.inTransition=t,i.listener=n}let r=new Promise(e=>{M.push(e)});return z(),r},U=(e,n)=>{if(e.pauses>0){e.flags=n?e.flags|t|r:(e.flags|t)&~r;return}let i=!!(e.flags&16);e.flags=e.flags&~t|2|r,i?A.push(e):j.push(e),B()},W=e=>{e.flags&512||e.pauses>0||(e.flags&2048?u(e,!1):(e.flags&1026)==1026&&(e.flags&=~r,e.flags&16?d.push(e):f.push(e)))},G=()=>{for(let e of[A,j]){for(let t of e)t.flags&=~(2|r),t.state=0;e.length=0}},K=(e,t)=>t===D&&(e.flags|=n,N.push(e),!0),q=e=>{if(e.hold?.()===!0)throw D},J=()=>{P+=1},Y=()=>{P>0&&--P,I()&&B(),z()},X=()=>{let e=N.splice(0,N.length),t=i.inTransition;i.inTransition=!0;try{for(let t of e)t.flags&4096&&!t.disposed&&(t.flags&=~n,t.state=2,t.kind===2?u(t,!0):g(t))}finally{i.inTransition=t}C()},Z=e=>{k(e,e=>{e.pauses+=1,e instanceof p&&e.kind===2&&!(e.flags&16)&&!e.disposed&&e.runCleanups()})},Q=e=>{let t=0,n=!1,r=!1,i={increment(){t+=1},decrement(){--t,t===0&&(n&&(n=!1,X(),Y()),e())},hold(){return r=!0,n||(n=!0,J()),!0}};return{run:e=>w(T,i,e),count:()=>t,engaged:()=>r,drop:()=>{n&&(n=!1,Y())}}};return{place:U,promote:W,clear:G,suspend:K,holdReader:q,startTransition:H,beginHold:J,endHold:Y,wakeSuspended:X,pause:Z,resume:e=>{k(e,e=>{if(e.pauses>0&&--e.pauses,e instanceof p&&e.pauses===0&&!e.disposed){if(e.kind===2){if(e.flags&16&&!(e.flags&2048))return;e.state=2,u(e,!1)}else e.state!==0&&g(e)}}),C()},createHold:Q,slotSwap:(e,t,n,r)=>{let s,c=new a(r),l=new m(0,!1,void 0),u=()=>{l.value+=1,h(l)&&(g(l),C())},d=e=>{e.owned.disposing=!0;try{e.hold?.drop(),e.dispose?.()}finally{e.owned.disposing=!1}},f=t=>{let n=e.live;e.live=t,n!==void 0&&d(n)},p=e=>{let n={index:e.index,value:e.when,disposing:!1},r=Q(()=>{s!==void 0&&s.hold===r&&u()}),l=new a(c),d=i.owner,f=i.listener;i.owner=l,i.listener=null;let p;try{try{p=r.run(()=>t(e,n,!0))}catch(e){if(!O(e))throw e}let i=new a(l);o(i,()=>{n.disposing=!0})}finally{i.owner=d,i.listener=f}return{choice:e,owned:n,result:p,dispose:()=>E(l),hold:r.engaged()?r:null}};return{step(t){if(_(l),s!==void 0){if(!n(s.choice,t)){let e=s;s=void 0,e.hold?.drop(),e.dispose?.()}else if((s.hold?.count()??0)>0)return!0;else{let e=s;return s=void 0,f(e),!0}}if(e.live!==void 0&&i.inTransition){let e=p(t);return e.hold===null?f(e):s=e,!0}let r=e.live;return e.live=void 0,r!==void 0&&d(r),!1}}},boundaryHold:()=>{let e=!1;return{engage:()=>(e||(e=!0,J()),!0),release:()=>{e&&(e=!1,X(),Y())},holding:()=>e}}}}function j(){let e=i.hooks;if(e!==null)return e;let t=A();return i.hooks=t,t}function M(){j()}function N(e){return e(),Promise.resolve()}function P(){i.hooks?.beginHold()}function F(){i.hooks?.endHold()}function I(){i.hooks?.wakeSuspended()}function L(e){i.hooks?.holdReader(e)}function R(){return i.inTransition}function z(e){let t=i.hooks;return t===null?null:t.createHold(e)}function B(){return i.inTransition?i.hooks:null}function V(e){j().pause(e)}function H(e){i.hooks?.resume(e)}export{P as beginHold,z as createTransitionHold,F as endHold,L as holdReader,R as inTransition,V as pauseOwner,M as registerTransitionLane,H as resumeOwner,N as startTransition,B as transitionHooks,I as wakeSuspended};
2
+ //# sourceMappingURL=concurrency.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"concurrency.js","names":["walk","stack","root","node","visit","child","createHooks","laneRender","laneUser","waiters","suspended","holds","scheduled","hasLanePending","laneBusy","drainLane","batch","queue","limit","isOrdered","byCreation","effect","FLAG_TRANSITION","FLAG_PARKED","recompute","updateIfNecessary","error","handleError","settleLane","resolved","resolve","scheduleLane","flushLane","rt","previous","budget","passes","clearQueues","ShadowError","errors","reportUncaught","hasPending","schedule","startTransition","listener","fn","applied","parkOrLane","inLane","render","promote","place","renderQueue","userQueue","clear","suspend","SUSPENSION","FLAG_SUSPENDED","holdReader","tracker","beginHold","endHold","wakeSuspended","waiting","markObservers","pause","owner","Computation","createHold","count","holding","engagedOnce","onSettled","runWithContext","SuspenseContext","pending","holder","Owner","parent","settled","Signal","settle","hasObservers","retireBranch","branch","commit","state","buildPending","owned","choice","hold","previousOwner","previousListener","result","build","isSuspension","marker","addCleanup","disposeTree","readSignal","same","dropped","ready","built","live","ensureHooks","existing","created","registerTransitionLane","inTransition","createTransitionHold","hooks","transitionHooks","pauseOwner","resumeOwner"],"sources":["../../../src/internal/concurrency.ts"],"sourcesContent":["import { runWithContext } from \"../context\";\nimport { SuspenseContext } from \"../suspense\";\nimport { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport { disposeTree } from \"./dispose\";\nimport {\n CLEAN,\n DIRTY,\n FLAG_DISPOSED,\n FLAG_LANE,\n FLAG_PARKED,\n FLAG_QUEUED,\n FLAG_RENDER,\n FLAG_SUSPENDED,\n FLAG_TRANSITION,\n KIND_EFFECT,\n} from \"./flags\";\nimport {\n Computation,\n hasObservers,\n markObservers,\n readSignal,\n recompute,\n Signal,\n updateIfNecessary,\n} from \"./graph\";\nimport { addCleanup, handleError, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, isOrdered, MAX_FLUSH_PASSES, reportUncaught, schedule } from \"./scheduler\";\nimport {\n type BoundaryHold,\n type Hooks,\n rt,\n type SlotBranch,\n type SlotChoice,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n type TransitionHold,\n} from \"./state\";\nimport { isSuspension, SUSPENSION } from \"./suspension\";\n\n/*\n * Transitions, Activity pauses and Suspense holds. Nothing here runs unless an API that needs it is\n * called (startTransition, useTransition, useDeferredValue, pauseOwner, a Suspense hold inside a\n * transition): the first of those creates the hooks (`ensureHooks`), and the engine reaches them only\n * through `rt.hooks`. Module level holds no state of its own: the queues, waiters and holds are\n * closure variables of `createHooks`.\n */\n\n/** Transition-lane effects run per macrotask; between two chunks urgent work and input can run. */\nconst LANE_CHUNK = 64;\n\n/** Visits `root` and every node below it. Iterative: the depth is user controlled. */\nfunction walk(root: Owner, visit: (node: Owner) => void): void {\n const stack: Owner[] = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n if (node === undefined) break;\n visit(node);\n for (let child = node.lastChild; child !== null; child = child.prevSibling) stack.push(child);\n }\n}\n\n/** Creates the transition machinery. Called once, by the first API that needs it. */\nfunction createHooks(): Hooks {\n const laneRender: Computation[] = [];\n const laneUser: Computation[] = [];\n /** Resolvers of the transitions waiting for the lane to go idle. */\n const waiters: Array<() => void> = [];\n /** Memos and effects that caught a suspension; woken all at once when a boundary releases them. */\n const suspended: Computation[] = [];\n /** Suspense boundaries currently holding a transition (the lane is busy while any holds). */\n let holds = 0;\n let scheduled = false;\n\n const hasLanePending = (): boolean => laneRender.length > 0 || laneUser.length > 0;\n const laneBusy = (): boolean => hasLanePending() || holds > 0;\n\n /**\n * Runs one chunk of a lane queue. An entry without FLAG_TRANSITION was promoted to the urgent queue\n * after it was queued here; it is skipped (the urgent queue owns its FLAG_QUEUED).\n */\n const drainLane = (queue: Computation[], limit: number): number => {\n const batch = queue.splice(0, limit);\n if (!isOrdered(batch)) batch.sort(byCreation);\n for (const effect of batch) {\n if ((effect.flags & FLAG_TRANSITION) === 0) continue;\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n effect.flags |= FLAG_PARKED | FLAG_TRANSITION;\n continue;\n }\n try {\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n };\n\n /** Resolves the transitions that wait for the lane, once the lane is idle. */\n const settleLane = (): void => {\n if (laneBusy() || waiters.length === 0) return;\n const resolved = waiters.splice(0, waiters.length);\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_END, resolved.length);\n for (const resolve of resolved) resolve();\n };\n\n /** Asks for one lane macrotask (the timer lets the browser paint and take input first). */\n const scheduleLane = (): void => {\n if (scheduled) return;\n scheduled = true;\n setTimeout(flushLane, 0);\n };\n\n /**\n * Runs the transition lane: one chunk per macrotask, render effects first. Writes made here belong to\n * the lane, so the effects they wake join it. Errors nobody handled are reported, not thrown, because\n * no caller is waiting for this macrotask.\n */\n const flushLane = (): void => {\n scheduled = false;\n if (rt.flushing) {\n scheduleLane();\n return;\n }\n const previous = rt.inTransition;\n rt.inTransition = true;\n rt.flushing = true;\n let budget = LANE_CHUNK;\n let passes = 0;\n try {\n while (budget > 0 && hasLanePending()) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const queue = laneRender.length > 0 ? laneRender : laneUser;\n budget -= drainLane(queue, budget);\n }\n } finally {\n rt.inTransition = previous;\n rt.flushing = false;\n }\n const errors = rt.uncaught.splice(0, rt.uncaught.length);\n for (const error of errors) reportUncaught(error);\n if (hasLanePending()) scheduleLane();\n else settleLane();\n if (hasPending()) schedule();\n };\n\n const startTransition = (fn: () => void): Promise<void> => {\n // A user callback runs untracked and as a transition: its reads are not subscriptions of the caller.\n const previous = rt.inTransition;\n const listener = rt.listener;\n rt.inTransition = true;\n rt.listener = null;\n try {\n fn();\n } finally {\n rt.inTransition = previous;\n rt.listener = listener;\n }\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_START);\n const applied = new Promise<void>((resolve) => {\n waiters.push(resolve);\n });\n settleLane();\n return applied;\n };\n\n /** The hook's `place`: parks a paused effect or queues a lane effect. */\n const parkOrLane = (effect: Computation, inLane: boolean): void => {\n if (effect.pauses > 0) {\n // Paused: parked (unqueued) until the owner resumes. A lane effect keeps its lane.\n effect.flags = inLane\n ? effect.flags | FLAG_PARKED | FLAG_TRANSITION\n : (effect.flags | FLAG_PARKED) & ~FLAG_TRANSITION;\n return;\n }\n const render = (effect.flags & FLAG_RENDER) !== 0;\n effect.flags = (effect.flags & ~FLAG_PARKED) | FLAG_QUEUED | FLAG_TRANSITION;\n if (render) laneRender.push(effect);\n else laneUser.push(effect);\n scheduleLane();\n };\n\n const promote = (effect: Computation): void => {\n // Lane-only effects (useDeferredValue's watcher) and paused effects stay where they are.\n if ((effect.flags & FLAG_LANE) !== 0 || effect.pauses > 0) return;\n if ((effect.flags & FLAG_PARKED) !== 0) {\n place(effect, false);\n return;\n }\n if ((effect.flags & (FLAG_QUEUED | FLAG_TRANSITION)) !== (FLAG_QUEUED | FLAG_TRANSITION))\n return;\n // Still listed in the lane array; the lane skips entries that no longer carry FLAG_TRANSITION.\n effect.flags &= ~FLAG_TRANSITION;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n };\n\n const clear = (): void => {\n for (const queue of [laneRender, laneUser]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n };\n\n const suspend = (node: Computation, error: unknown): boolean => {\n if (error !== SUSPENSION) return false;\n node.flags |= FLAG_SUSPENDED;\n suspended.push(node);\n return true;\n };\n\n const holdReader = (tracker: { hold?(): boolean }): void => {\n if (tracker.hold?.() === true) throw SUSPENSION;\n };\n\n const beginHold = (): void => {\n holds += 1;\n };\n\n const endHold = (): void => {\n if (holds > 0) holds -= 1;\n if (hasLanePending()) scheduleLane();\n settleLane();\n };\n\n const wakeSuspended = (): void => {\n const waiting = suspended.splice(0, suspended.length);\n // The woken work is still the transition: it runs in the lane, so a resource it reads again is\n // held the same way, not shown as a fallback by an urgent pass.\n const previous = rt.inTransition;\n rt.inTransition = true;\n try {\n for (const node of waiting) {\n if ((node.flags & FLAG_SUSPENDED) === 0 || node.disposed) continue;\n node.flags &= ~FLAG_SUSPENDED;\n node.state = DIRTY;\n if (node.kind === KIND_EFFECT) place(node, true);\n else markObservers(node);\n }\n } finally {\n rt.inTransition = previous;\n }\n schedule();\n };\n\n const pause = (owner: Owner): void => {\n walk(owner, (node) => {\n node.pauses += 1;\n if (\n node instanceof Computation &&\n node.kind === KIND_EFFECT &&\n (node.flags & FLAG_RENDER) === 0 &&\n !node.disposed\n ) {\n node.runCleanups();\n }\n });\n };\n\n const createHold = (onSettled: () => void): TransitionHold => {\n let count = 0;\n let holding = false;\n let engagedOnce = false;\n const tracker = {\n increment(): void {\n count += 1;\n },\n decrement(): void {\n count -= 1;\n if (count !== 0) return;\n if (holding) {\n holding = false;\n // Everything that kept its value for this hold runs again, now that the data arrived.\n wakeSuspended();\n endHold();\n }\n onSettled();\n },\n hold(): boolean {\n engagedOnce = true;\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n };\n return {\n run: (fn) => runWithContext(SuspenseContext, tracker, fn),\n count: () => count,\n engaged: () => engagedOnce,\n drop: () => {\n if (!holding) return;\n holding = false;\n endHold();\n },\n };\n };\n\n const resume = (owner: Owner): void => {\n walk(owner, (node) => {\n if (node.pauses > 0) node.pauses -= 1;\n if (!(node instanceof Computation) || node.pauses !== 0 || node.disposed) return;\n if (node.kind === KIND_EFFECT) {\n // A render effect that was not due while paused keeps its DOM: re-running it would rebuild its\n // subtree (a Provider's children, for one) and lose that state.\n if ((node.flags & FLAG_RENDER) !== 0 && (node.flags & FLAG_PARKED) === 0) return;\n node.state = DIRTY;\n place(node, false);\n } else if (node.state !== CLEAN) {\n // A memo that changed while paused was not recomputed, so its readers outside this owner were\n // not woken either (they read the frozen value). Wake them now that it can be recomputed.\n markObservers(node);\n }\n });\n schedule();\n };\n\n /** A Suspense boundary's hold: engaged by a transition read, released when its data arrived. */\n const boundaryHold = (): BoundaryHold => {\n let holding = false;\n return {\n engage: () => {\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n release: () => {\n if (!holding) return;\n holding = false;\n // Everything that kept its value for this boundary runs again, with the data that arrived.\n wakeSuspended();\n endHold();\n },\n holding: () => holding,\n };\n };\n\n /**\n * The transition layer of one branch slot (Show, Switch). A change made during a transition, while a\n * branch is on screen, builds the new branch under a hold and keeps the shown one until the hold\n * settles; then it commits. The slot's output memo calls `step` first, so the usual path (its own\n * teardown) only runs when no transition is involved. Its state lives in `state`, which the memo\n * reads and writes.\n */\n const slotSwap = <C extends SlotChoice>(\n state: SlotState<C>,\n build: (choice: C, owned: SlotOwned, eager: boolean) => unknown,\n same: (a: C, b: C) => boolean,\n parent: Owner | null,\n ): SlotSwap<C> => {\n /** A transition's branch waiting for its reads; the shown branch stays until it is ready. */\n let pending: SlotBranch<C> | undefined;\n /** Owns the branches built during transitions: they live as long as the slot's owner. */\n const holder = new Owner(parent);\n /** Counts the settled holds; the memo reads it, so it runs again when a pending branch is ready. */\n const settled = new Signal<number>(0, false, undefined);\n\n const settle = (): void => {\n settled.value += 1;\n if (hasObservers(settled)) {\n markObservers(settled);\n schedule();\n }\n };\n\n /** Tears a branch down. Its owner is marked `disposing` first (see the accessors of Show). */\n const retireBranch = (branch: SlotBranch<C>): void => {\n branch.owned.disposing = true;\n try {\n branch.hold?.drop();\n branch.dispose?.();\n } finally {\n branch.owned.disposing = false;\n }\n };\n\n const commit = (branch: SlotBranch<C>): void => {\n const previous = state.live;\n state.live = branch;\n if (previous !== undefined) retireBranch(previous);\n };\n\n /** Builds a transition's branch under the holder. A held read leaves it pending, not shown. */\n const buildPending = (choice: C): SlotBranch<C> => {\n const owned: SlotOwned = { index: choice.index, value: choice.when, disposing: false };\n const hold: TransitionHold = createHold(() => {\n // Only the branch still waiting may commit; a dropped one must not wake the slot.\n if (pending !== undefined && pending.hold === hold) settle();\n });\n const root = new Owner(holder);\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = root;\n rt.listener = null;\n let result: unknown;\n try {\n // The branch's reads report to its own hold (not the boundary), so they do not bring the\n // fallback back. No Provider: its render effect would be re-run by the wake-up, rebuilding\n // the branch and starting its loads again.\n try {\n result = hold.run(() => build(choice, owned, true));\n } catch (error) {\n if (!isSuspension(error)) throw error;\n }\n const marker = new Owner(root);\n addCleanup(marker, () => {\n owned.disposing = true;\n });\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n return {\n choice,\n owned,\n result,\n dispose: () => disposeTree(root),\n hold: hold.engaged() ? hold : null,\n };\n };\n\n return {\n step(choice: C): boolean {\n readSignal(settled);\n if (pending !== undefined) {\n if (!same(pending.choice, choice)) {\n const dropped = pending;\n pending = undefined;\n dropped.hold?.drop();\n dropped.dispose?.();\n } else if ((pending.hold?.count() ?? 0) > 0) {\n // Still waiting for data: the shown branch stays on screen, untouched.\n return true;\n } else {\n const ready = pending;\n pending = undefined;\n commit(ready);\n return true;\n }\n }\n // A transition replacing the shown branch: build it first, keep the shown one until it is ready.\n if (state.live !== undefined && rt.inTransition) {\n const built = buildPending(choice);\n if (built.hold === null) commit(built);\n else pending = built;\n return true;\n }\n // The usual path follows: the branch on screen is retired here (an unmanaged one is torn down).\n const live = state.live;\n state.live = undefined;\n if (live !== undefined) retireBranch(live);\n return false;\n },\n };\n };\n\n return {\n place: parkOrLane,\n promote,\n clear,\n suspend,\n holdReader,\n startTransition,\n beginHold,\n endHold,\n wakeSuspended,\n pause,\n resume,\n createHold,\n slotSwap,\n boundaryHold,\n };\n}\n\n/** Installs the transition machinery on first use; later calls return the same hooks. */\nfunction ensureHooks(): Hooks {\n const existing = rt.hooks;\n if (existing !== null) return existing;\n const created = createHooks();\n rt.hooks = created;\n return created;\n}\n\n/**\n * Installs the transition machinery (the transition lane, Activity pauses and Suspense holds) now\n * instead of at the first `startTransition`. The machinery is created on first use so that an\n * application that never uses transitions does not carry its code; call this from a primitive whose\n * later work needs the lane to exist, as `useDeferredValue` does. Calling it again does nothing.\n *\n * @example\n * import { registerTransitionLane } from \"@shadow-js/core/extend\";\n *\n * export function useBackgroundValue(): void {\n * registerTransitionLane(); // later lane-only effects of this hook find the lane\n * }\n * @see startTransition\n * @since 1.0.0\n */\nexport function registerTransitionLane(): void {\n ensureHooks();\n}\n\n/**\n * Runs `fn` as a transition: the effects its writes wake wait in the transition lane, which runs\n * after urgent work (in a macrotask, one chunk at a time). Reads see the writes at once; the DOM\n * catches up when the lane runs. Use it for an update that may be slow to render or load, so input\n * stays responsive and a Suspense boundary keeps its content instead of showing its fallback. `fn`\n * runs untracked. The returned promise resolves when the lane is idle and no Suspense boundary holds\n * the transition.\n *\n * On the server there are no effects, so `fn` simply runs and the promise is already resolved.\n *\n * @param fn Callback whose writes form the transition.\n * @returns A promise that resolves when the transition has been applied.\n * @throws What `fn` throws, synchronously; no transition is started then.\n * @example\n * import { startTransition, useSignal } from \"@shadow-js/core\";\n *\n * const [page, setPage] = useSignal(\"home\");\n * async function openReports(): Promise<void> {\n * await startTransition(() => setPage(\"reports\"));\n * console.log(`${page()} is on screen`);\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function startTransition(fn: () => void): Promise<void> {\n if (__SERVER__) {\n fn();\n return Promise.resolve();\n }\n return ensureHooks().startTransition(fn);\n}\n\n/**\n * Starts a Suspense hold: the boundary keeps showing its current content while a transition waits\n * for data. Holds are counted, and the running transitions stay pending (`isPending` of\n * `useTransition`, the promise of `startTransition`) until every hold has ended. For renderers that\n * implement Suspense; each call needs one {@link endHold}. Does nothing before the transition\n * machinery exists (no transition has run).\n *\n * @example\n * import { beginHold, endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function holdUntil(data: Promise<unknown>): void {\n * beginHold(); // the boundary keeps its content\n * void data.finally(() => {\n * wakeSuspended();\n * endHold();\n * });\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function beginHold(): void {\n rt.hooks?.beginHold();\n}\n\n/**\n * Ends a Suspense hold started with {@link beginHold}. Call {@link wakeSuspended} first, so the\n * memos and effects that waited are queued; this then schedules the lane for them and, once the lane\n * is idle and no hold remains, resolves the transitions that were waiting. Extra calls never take the\n * count below zero. Does nothing before the transition machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function release(): void {\n * wakeSuspended(); // the held readers run again with the data that arrived\n * endHold();\n * }\n * @see beginHold\n * @since 1.0.0\n */\nexport function endHold(): void {\n rt.hooks?.endHold();\n}\n\n/**\n * Wakes every memo and effect that kept its value for a transition (it caught {@link SUSPENSION}):\n * each runs again in the transition lane, so it reads the data that arrived. A Suspense boundary\n * calls it when it releases its hold, before {@link endHold}. Does nothing before the transition\n * machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function onDataArrived(): void {\n * wakeSuspended();\n * endHold();\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function wakeSuspended(): void {\n rt.hooks?.wakeSuspended();\n}\n\n/**\n * Lets a pending read inside a transition keep the boundary's content: when the tracker's `hold()`\n * returns true (the boundary holds its content for the transition), the reader throws\n * {@link SUSPENSION} and keeps its previous value until the boundary wakes it. Call it from a data\n * primitive's reader when its data is pending, the reader is tracked and {@link inTransition} is\n * true, as `useResource` does. Does nothing before the transition machinery exists, or when the\n * tracker has no `hold`.\n *\n * @param tracker The Suspense tracker of the nearest boundary (`SuspenseContext`).\n * @throws {@link SUSPENSION} (not an error) when the boundary holds its content.\n * @example\n * import { useContext, SuspenseContext } from \"@shadow-js/core\";\n * import { currentListener, holdReader, inTransition } from \"@shadow-js/core/extend\";\n *\n * export function readPending(): void {\n * const tracker = useContext(SuspenseContext);\n * if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n * }\n * @see isSuspension\n * @since 1.0.0\n */\nexport function holdReader(tracker: { hold?(): boolean }): void {\n rt.hooks?.holdReader(tracker);\n}\n\n/**\n * Tells whether a transition callback or a transition-lane run is active, so the writes made now\n * belong to the lane. Use it in a primitive that treats transition reads differently, such as a data\n * reader that holds the boundary only in a transition.\n *\n * @returns True inside `startTransition`'s callback and while the lane runs.\n * @example\n * import { startTransition } from \"@shadow-js/core\";\n * import { inTransition } from \"@shadow-js/core/extend\";\n *\n * void startTransition(() => {\n * console.log(inTransition()); // true in the browser\n * });\n * console.log(inTransition()); // false\n * @see startTransition\n * @since 1.0.0\n */\nexport function inTransition(): boolean {\n return rt.inTransition;\n}\n\n/**\n * Creates the hold of a value a transition builds (see {@link TransitionHold}): the reads that wait\n * for data inside `hold.run(...)` count against this hold instead of the Suspense boundary around the\n * value, so the value on screen stays until the new one is ready. For renderers that build values\n * during a transition.\n *\n * @param onSettled Called each time the number of waiting reads drops back to zero.\n * @returns The hold, or null when the transition machinery does not exist yet (no transition has run,\n * so nothing can be held).\n * @example\n * import { createTransitionHold } from \"@shadow-js/core/extend\";\n *\n * const hold = createTransitionHold(() => console.log(\"ready to commit\"));\n * const built = hold === null ? \"now\" : hold.run(() => \"pending\");\n * @see transitionHooks\n * @since 1.0.0\n */\nexport function createTransitionHold(onSettled: () => void): TransitionHold | null {\n const hooks = rt.hooks;\n return hooks === null ? null : hooks.createHold(onSettled);\n}\n\n/**\n * Returns the transition machinery while a transition is running, otherwise null. Renderers reach\n * the slot and boundary layers (`slotSwap`, `boundaryHold`) only through it: a transition can only be\n * running once the machinery exists, so this never creates it (a static call that did would keep the\n * whole machinery in every bundle that renders a Show).\n *\n * @returns The hooks during a transition callback or lane run, null otherwise.\n * @example\n * import { transitionHooks } from \"@shadow-js/core/extend\";\n *\n * export function boundaryHoldIfTransition() {\n * return transitionHooks()?.boundaryHold() ?? null;\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function transitionHooks(): Hooks | null {\n return rt.inTransition ? rt.hooks : null;\n}\n\n/**\n * Pauses `owner` and everything below it (Activity hidden). User effects run their cleanups and wait.\n * DOM bindings (render effects) wait without a cleanup, so their nodes stay as they are. Memos keep their\n * last value, and effects created below are parked until the owner resumes. Pauses nest: each\n * `pauseOwner` needs one `resumeOwner`. Use it to hide a subtree while keeping its state.\n *\n * @param owner The owner to pause, with its whole subtree.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const hidden = createOwner(null);\n * pauseOwner(hidden); // its effects stop; its memos keep their values\n * resumeOwner(hidden); // its user effects run again with the latest values\n * @see resumeOwner\n * @since 1.0.0\n */\nexport function pauseOwner(owner: Owner): void {\n ensureHooks().pause(owner);\n}\n\n/**\n * Resumes an owner paused with {@link pauseOwner}; the subtree runs again once its last pause ends.\n * User effects below it run once more with the current values (their cleanups ran on pause). DOM\n * bindings run only if something they read changed while paused, so a hidden subtree is not rebuilt\n * on show. Memos that changed while paused wake their readers outside the owner. Call it once per\n * `pauseOwner`, not on an owner that is not paused.\n *\n * @param owner The paused owner.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const panel = createOwner(null);\n * pauseOwner(panel);\n * resumeOwner(panel); // every user effect below runs once with the latest values\n * @see pauseOwner\n * @since 1.0.0\n */\nexport function resumeOwner(owner: Owner): void {\n rt.hooks?.resume(owner);\n}\n"],"mappings":"A,gwBAsDA,SAASA,EAAK,EAAa,EAAoC,CAC7D,IAAMC,EAAiB,CAACC,CAAI,EAC5B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAAOF,EAAM,IAAI,EACvB,GAAIE,IAAS,IAAA,GAAW,MACxBC,EAAMD,CAAI,EACV,IAAK,IAAIE,EAAQF,EAAK,UAAWE,IAAU,KAAM,EAAQA,EAAM,YAAaJ,EAAM,KAAKI,CAAK,CAC9F,CACF,CAGA,SAASC,GAAqB,CAC5B,IAAMC,EAA4B,CAAC,EAC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:11,HYDRATION_MISMATCH:12,FLUSH_START:13,FLUSH_END:14,STORE_CREATED:15,TRANSITION_START:16,TRANSITION_END:17};function t(e,t,n,r,i,a){}export{e as DEVTOOLS_EVENT,t as report};
2
+ //# sourceMappingURL=devtools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devtools.js","names":["DEVTOOLS_EVENT","report"],"sources":["../../../src/internal/devtools.ts"],"sourcesContent":["/**\n * The runtime's side of the devtools protocol (version 1, see `@shadow-js/devtools`). The runtime\n * does not import that package: it looks up a global hook, in development builds only, and every\n * call site is wrapped as `if (__DEV__) report(...)` so production bundles drop it entirely.\n */\n\n/**\n * The event kinds of the devtools protocol (version 1), numbered as `EVENT` in `@shadow-js/devtools`\n * numbers them. Pass one to {@link devtoolsReport} when a custom primitive shows up in devtools; the\n * meaning of the other arguments of each kind is in the protocol table of the devtools README.\n *\n * Kinds 16 and 17 are the transition events, reported by `internal/concurrency.ts`: `TRANSITION_START`\n * (16) after a `transition()` callback has run, with no arguments; `TRANSITION_END` (17) when the\n * transition lane is idle, with the number of transitions it resolved. The devtools agent does not use\n * them yet.\n *\n * @example\n * import { DEVTOOLS_EVENT } from \"@shadow-js/core/extend\";\n *\n * function describe(kind: number): string {\n * if (kind === DEVTOOLS_EVENT.SIGNAL_WRITTEN) return \"signal written\";\n * if (kind === DEVTOOLS_EVENT.ERROR) return \"error\";\n * return `event ${kind}`;\n * }\n * @see devtoolsReport\n * @since 1.0.0\n */\nexport const DEVTOOLS_EVENT = {\n OWNER_CREATED: 1,\n OWNER_DISPOSED: 2,\n SIGNAL_CREATED: 3,\n SIGNAL_WRITTEN: 4,\n COMPUTATION_CREATED: 5,\n COMPUTATION_RUN: 6,\n COMPUTATION_DISPOSED: 7,\n COMPONENT_MOUNTED: 8,\n COMPONENT_UNMOUNTED: 9,\n RESOURCE_STATE: 10,\n ERROR: 11,\n HYDRATION_MISMATCH: 12,\n FLUSH_START: 13,\n FLUSH_END: 14,\n STORE_CREATED: 15,\n TRANSITION_START: 16,\n TRANSITION_END: 17,\n} as const;\n\nconst KEY = \"__SHADOWJS_DEVTOOLS_HOOK__\";\n\ninterface Hook {\n readonly version: number;\n report(kind: number, a?: unknown, b?: unknown, c?: unknown, d?: unknown, e?: unknown): void;\n}\n\n/**\n * Reports one event to the devtools hook (`globalThis.__SHADOWJS_DEVTOOLS_HOOK__`, protocol version\n * 1) when one is installed. Does nothing without a hook, with a hook of another version, and in\n * production builds. Exported from `@shadow-js/core/extend` as `devtoolsReport`. Pass the runtime's\n * own objects, not copies, so a report allocates nothing.\n *\n * @param kind The event kind, one of {@link DEVTOOLS_EVENT}.\n * @param a First argument of the event (see the protocol table of the devtools README).\n * @param b Second argument of the event, or undefined when the kind has none.\n * @param c Third argument of the event, or undefined when the kind has none.\n * @param d Fourth argument of the event, or undefined when the kind has none.\n * @param e Fifth argument of the event, or undefined when the kind has none.\n * @example\n * import { isDev } from \"@shadow-js/core\";\n * import { currentOwner, DEVTOOLS_EVENT, devtoolsReport } from \"@shadow-js/core/extend\";\n *\n * function reportFailure(error: unknown): void {\n * if (isDev) devtoolsReport(DEVTOOLS_EVENT.ERROR, currentOwner(), error, undefined);\n * }\n * @see DEVTOOLS_EVENT\n * @since 1.0.0\n */\nexport function report(\n kind: number,\n a?: unknown,\n b?: unknown,\n c?: unknown,\n d?: unknown,\n e?: unknown,\n): void {\n if (!__DEV__) return;\n const hook = Reflect.get(globalThis, KEY) as Hook | undefined;\n if (hook !== undefined && hook.version === 1) hook.report(kind, a, b, c, d, e);\n}\n"],"mappings":"AA2BA,MAAaA,EAAiB,CAC5B,cAAe,EACf,eAAgB,EAChB,eAAgB,EAChB,eAAgB,EAChB,oBAAqB,EACrB,gBAAiB,EACjB,qBAAsB,EACtB,kBAAmB,EACnB,oBAAqB,EACrB,eAAgB,GAChB,MAAO,GACP,mBAAoB,GACpB,YAAa,GACb,UAAW,GACX,cAAe,GACf,iBAAkB,GAClB,eAAgB,EAClB,EA+BA,SAAgBC,EACd,EACA,EACA,EACA,EACA,EACA,EACM,CAIR,C"}
@@ -0,0 +1,2 @@
1
+ import{formatMessage as e}from"./messages.js";var t=class extends Error{code;constructor(t){super(e(t)),this.name=`ShadowError`,this.code=t}};const n=/* @__PURE__ */ new Set;let r;function i(e){let t=r;return r=e,t}function a(){n.clear()}function o(e){}export{t as ShadowError,a as resetWarningDedupe,i as setWarningListener,o as warn};
2
+ //# sourceMappingURL=diagnostics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics.js","names":["ShadowError","formatMessage","code","seen","listener","setWarningListener","previous","next","resetWarningDedupe","warn"],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["import { formatMessage, type MessageCode } from \"./messages\";\n\n/**\n * The error class of every diagnostic the runtime throws, carrying a stable code next to the\n * message. Match on `code` rather than the message: the message is the full text in development\n * builds and only `SHADOW_<CODE>` in production builds. Throw it from a custom primitive to report a\n * core diagnostic the same way the built-in hooks do.\n *\n * @example\n * import { ShadowError } from \"@shadow-js/core/extend\";\n *\n * function isCycle(error: unknown): boolean {\n * return error instanceof ShadowError && error.code === \"CYCLE_DETECTED\";\n * }\n * @see MESSAGES\n * @since 1.0.0\n */\nexport class ShadowError extends Error {\n /** The diagnostic code, a key of {@link MESSAGES}; the same in development and production builds. */\n readonly code: MessageCode;\n /**\n * Creates the error with the text of {@link formatMessage} for `code` and the name `\"ShadowError\"`.\n * @param code The diagnostic code.\n */\n constructor(code: MessageCode) {\n super(formatMessage(code));\n this.name = \"ShadowError\";\n this.code = code;\n }\n}\n\n/**\n * A function that receives the warnings of {@link warn} instead of `console.warn`. Install one with\n * {@link setWarningListener}.\n * @param code The diagnostic code of the warning.\n * @param message The text of {@link formatMessage} for that code.\n * @since 1.0.0\n */\nexport type WarningListener = (code: MessageCode, message: string) => void;\n\nconst seen = new Set<MessageCode>();\nlet listener: WarningListener | undefined;\n\n/**\n * Sends every later warning to `next` instead of `console.warn`, for devtools and test helpers\n * (`@shadow-js/testing`) that collect warnings. Deduplication still applies: the listener receives\n * the first warning of each code only. Warnings exist in development builds only.\n *\n * @param next The listener to install. Undefined restores the default, `console.warn`.\n * @returns The listener that was installed before, or undefined when it was the default, so the\n * caller can restore it.\n * @example\n * import { type MessageCode, setWarningListener } from \"@shadow-js/core/extend\";\n *\n * const codes: MessageCode[] = [];\n * const previous = setWarningListener((code) => {\n * codes.push(code);\n * });\n * // ... run the code under test, then:\n * setWarningListener(previous);\n * @see warn\n * @see resetWarningDedupe\n * @since 1.0.0\n */\nexport function setWarningListener(next: WarningListener | undefined): WarningListener | undefined {\n const previous = listener;\n listener = next;\n return previous;\n}\n\n/**\n * Forgets which codes {@link warn} has already reported, so the next warning of each code is\n * reported again. Use it between test cases and after a hot reload.\n *\n * @example\n * import { resetWarningDedupe } from \"@shadow-js/core/extend\";\n *\n * function startTestCase(): void {\n * resetWarningDedupe(); // each case sees its own first warnings\n * }\n * @see warn\n * @since 1.0.0\n */\nexport function resetWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Reports a development-only diagnostic. Only the first warning of each code is reported, for the\n * whole program, until {@link resetWarningDedupe}; it goes to the listener of\n * {@link setWarningListener}, or to `console.warn` with the text of {@link formatMessage}. Does\n * nothing in production builds. Use it for a mistake that should not stop the app; throw\n * {@link ShadowError} for one that must.\n *\n * @param code The diagnostic code to report.\n * @example\n * import { currentOwner, warn } from \"@shadow-js/core/extend\";\n *\n * export function useTicker(): void {\n * if (currentOwner() === null) warn(\"NO_OWNER_CLEANUP\");\n * }\n * @see setWarningListener\n * @since 1.0.0\n */\nexport function warn(code: MessageCode): void {\n if (!__DEV__) return;\n if (seen.has(code)) return;\n seen.add(code);\n const message = formatMessage(code);\n if (listener !== undefined) listener(code, message);\n else console.warn(message);\n}\n"],"mappings":"A,8CAiBA,IAAaA,EAAb,cAAiC,KAAM,CAErC,KAKA,YAAY,EAAmB,CAC7B,MAAMC,EAAcC,CAAI,CAAC,EACzB,KAAK,KAAO,cACZ,KAAK,KAAOA,CACd,CACF,EAWA,MAAMC,kBAAO,IAAI,IACjB,IAAIC,EAuBJ,SAAgBC,EAAmB,EAAgE,CACjG,IAAMC,EAAWF,EAEjB,MADA,GAAWG,EACJD,CACT,CAeA,SAAgBE,GAA2B,CACzCL,EAAK,MAAM,CACb,CAmBA,SAAgBM,EAAK,EAAyB,CAO9C,C"}
@@ -0,0 +1,2 @@
1
+ import{rt as e}from"./state.js";import{disposeTree as t}from"./owner.js";import{hasPending as n}from"./queue.js";import{flush as r}from"./scheduler.js";function i(i){let a,o=!1;try{t(i)}catch(e){o=!0,a=e}if(e.running===null&&e.batchDepth===0&&!e.flushing&&n())try{r()}catch(e){throw o?AggregateError([a,e],`SHADOW_DISPOSE_FLUSH_ERRORS`):e}if(o)throw a}export{i as disposeTree};
2
+ //# sourceMappingURL=dispose.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dispose.js","names":["disposeTree$1","disposeTree","failure","failed","root","error","rt","hasPending","flush"],"sources":["../../../src/internal/dispose.ts"],"sourcesContent":["import type { Owner } from \"./owner\";\nimport { disposeTree as disposeSubtree } from \"./owner\";\nimport { hasPending } from \"./queue\";\nimport { flush } from \"./scheduler\";\nimport { rt } from \"./state\";\n\n/**\n * Disposes an owner and everything below it: children first, newest first, then each node's\n * cleanups, newest first. Use it to end an owner made with `createOwner`; disposing an owner that is\n * already disposed does nothing. Exported from `@shadow-js/core/extend` as `disposeOwner`.\n *\n * Cleanups run in an implicit batch (O-3): effects that depend on signals a cleanup wrote are\n * flushed before this returns, unless the disposal happens inside a computation, a batch or a flush,\n * whose own exit flushes.\n *\n * @param root The owner to dispose, with its whole subtree.\n * @throws The error of a cleanup that no error handler caught, once the whole tree is disposed\n * (several such errors are thrown together as an `AggregateError`); during a running flush, that\n * flush throws them instead. An error of the flush that\n * follows is thrown as is, or combined with the cleanup errors in an `AggregateError`.\n * @example\n * import { addCleanup, createOwner, disposeOwner } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * addCleanup(owner, () => console.log(\"released\"));\n * disposeOwner(owner); // logs \"released\"\n * @see addCleanup\n * @since 1.0.0\n */\nexport function disposeTree(root: Owner): void {\n let failure: unknown;\n let failed = false;\n try {\n disposeSubtree(root);\n } catch (error) {\n failed = true;\n failure = error;\n }\n if (rt.running === null && rt.batchDepth === 0 && !rt.flushing && hasPending()) {\n try {\n flush();\n } catch (error) {\n if (!failed) throw error;\n throw new AggregateError(\n [failure, error],\n __DEV__ ? \"Disposal and the following flush both threw.\" : \"SHADOW_DISPOSE_FLUSH_ERRORS\",\n );\n }\n }\n if (failed) throw failure;\n}\n"],"mappings":"A,wJA6BA,SAAgBC,EAAY,EAAmB,CAC7C,IAAIC,EACAC,EAAS,GACb,GAAI,CACFH,EAAeI,CAAI,CACrB,OAASC,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,CACA,GAAIC,EAAG,UAAY,MAAQA,EAAG,aAAe,GAAK,CAACA,EAAG,UAAYC,EAAW,EAC3E,GAAI,CACFC,EAAM,CACR,OAASH,EAAO,CAEd,MADKF,EACK,eACR,CAACD,EAASG,CAAK,EAC4C,6BAC7D,EAJmBA,CAKrB,CAEF,GAAIF,EAAQ,MAAMD,CACpB,C"}
@@ -0,0 +1,2 @@
1
+ const e=1024,t=2048,n=4096;export{t as FLAG_PARKED,n as FLAG_SUSPENDED,e as FLAG_TRANSITION};
2
+ //# sourceMappingURL=flags.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flags.js","names":["FLAG_TRANSITION","FLAG_PARKED","FLAG_SUSPENDED"],"sources":["../../../src/internal/flags.ts"],"sourcesContent":["/** Node states: how stale a node is. Monotonic CLEAN < CHECK < DIRTY between two refreshes. */\nexport const CLEAN = 0;\n/** A transitive source changed; verify sources before recomputing. */\nexport const CHECK = 1;\n/** A direct source changed; recompute. */\nexport const DIRTY = 2;\n\n/** Node kinds. */\nexport const KIND_SIGNAL = 0;\nexport const KIND_MEMO = 1;\nexport const KIND_EFFECT = 2;\n\n/** Bit flags on computations. */\nexport const FLAG_RUNNING = 1;\nexport const FLAG_QUEUED = 2;\nexport const FLAG_DISPOSED = 4;\nexport const FLAG_HAS_ERROR = 8;\n/** Effect belongs to the render phase (runs before user effects, synchronously at creation). */\nexport const FLAG_RENDER = 16;\n/** Memo has not produced its first value yet. */\nexport const FLAG_UNINIT = 32;\n/** Explicit-dependency effect whose first apply is skipped. */\nexport const FLAG_DEFER = 64;\n/** Node is on the pull stack of updateIfNecessary (guards re-entrant ancestor refreshes). */\nexport const FLAG_REFRESHING = 128;\n/** Memo that builds components: its body may write signals (component setup does). */\nexport const FLAG_ALLOW_WRITES = 256;\n/** Effect always runs in the transition lane (the watcher behind useDeferredValue). */\nexport const FLAG_LANE = 512;\n/** Effect is queued in (or parked from) the transition lane, not the urgent queues. */\nexport const FLAG_TRANSITION = 1024;\n/** Effect was due while its owner was paused: it waits, unqueued, until the owner resumes. */\nexport const FLAG_PARKED = 2048;\n/** Computation threw a suspension: it keeps its previous value until its boundary releases it. */\nexport const FLAG_SUSPENDED = 4096;\n"],"mappings":"AA8BA,MAAaA,EAAkB,KAElBC,EAAc,KAEdC,EAAiB,K"}
@@ -0,0 +1,2 @@
1
+ import{ShadowError as e}from"./diagnostics.js";import{nextSequence as t,rt as n}from"./state.js";import{Owner as r,addCleanup as i,disposeChildren as a,handleError as o,hasErrorHandler as s}from"./owner.js";import{enqueue as c}from"./queue.js";const l=Object.freeze([]);var u=class{kind=0;value;equals;observers=null;stamp=0;name;constructor(e,t,n){this.value=e,this.equals=t,this.name=n}},d=class extends r{kind;state;flags;value;error=void 0;equals;fn;apply=null;sources=l;observers=null;stamp=0;trackIndex=0;seq;name;constructor(e,n,r,i,a,o){super(e),this.kind=n,this.flags=r,this.state=2,this.fn=i,this.equals=a,this.name=o,this.value=void 0,this.seq=t()}reportDisposed(){}release(){this.flags|=4,p(this),this.fn=null,this.apply=null}};function f(e,t){let n=e.observers;if(n===null)return;let r=n.length-2;if(t!==r){let e=n[r],i=n[r+1];n[t]=e,n[t+1]=i,e.sources[i+1]=t}n.length=r}function p(e){m(e,0)}function m(e,t){let n=e.sources;if(!(n.length<=t)){for(let e=n.length-2;e>=t;e-=2)f(n[e],n[e+1]);n.length=t}}function h(e,t,n){let r=e.length;if(r>=16)return e.push(t,n),e;let i=Array(r+2);for(let t=0;t<r;t+=1)i[t]=e[t];return i[r]=t,i[r+1]=n,i}function g(e){let t=n.listener;if(t===null||e.stamp===t.stamp)return;e.stamp=t.stamp;let r=t.trackIndex;if(r<t.sources.length){if(t.sources[r]===e){t.trackIndex=r+2;return}m(t,r)}let i=e.observers,a=t.sources,o=i===null?0:i.length,s=a.length;e.observers=i===null?[t,s]:h(i,t,s),t.sources=h(a,e,o),t.trackIndex=s+2}function _(e){return b(e.sources)}function v(e){return e.observers===null?[]:b(e.observers)}function y(e){return e.observers!==null&&e.observers.length>0}function b(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(e[n]);return t}const x=[];function S(e,t){let r=e.state;e.kind===2?(r<t&&(e.state=t),r===0?c(e):n.inTransition||n.hooks?.promote(e)):r>=t||(e.state=t,r===0&&e.observers!==null&&e.observers.length>0&&x.push(e))}function C(e,t){return n.hooks?.suspend(e,t)===!0}function w(e){return e.pauses>0&&!(e.flags&32)}function T(e){for(E(e.observers,2);x.length>0;){let e=x.pop();e!==void 0&&E(e.observers,1)}}function E(e,t){if(e!==null)for(let n=0;n<e.length;n+=2)S(e[n],t)}const D=[],O=[];let k=0;function A(t,n=!1){if(t.state===0)return;let r=k;D[k]=t,O[k]=0,k+=1,t.flags|=128;try{for(;k>r;){let t=k-1,r=D[t];if(r===void 0)break;if(r.state===1||r.state===2&&n){let n=r.sources,i=O[t]??0,a=!1;for(;i<n.length;){let r=n[i];if(i+=2,r.kind===0)continue;let o=r;if(!(o.state===0||o.flags&4)&&!w(o)){if(o.flags&1)throw new e(`CYCLE_DETECTED`);if(j(o),!(o.state===0||o.flags&4)&&!w(o)){O[t]=i,D[k]=o,O[k]=0,k+=1,o.flags|=128,a=!0;break}}}if(a)continue}r.state===2?P(r):r.state=0,r.flags&=-129,--k}}finally{for(let e=r;e<k;e+=1){let t=D[e];t!==void 0&&(t.flags&=-129)}D.length=r,O.length=r,k=r}}function j(e){let t=[];for(let n=e.parent;n!==null;n=n.parent)n instanceof d&&n.state!==0&&!(n.flags&133)&&!w(n)&&t.push(n);for(let e=t.length-1;e>=0;--e){let n=t[e];n!==void 0&&!(n.flags&4)&&A(n)}}function M(e){return n.listener!==null&&g(e),e.value}function N(t){if(t.flags&1)throw new e(`CYCLE_DETECTED`);if(t.state!==0&&!(t.flags&4)&&!w(t)&&(j(t),t.flags&4||A(t,n.recomputeDepth>=128)),n.listener!==null&&g(t),t.flags&8)throw t.error;return t.value}function P(e){let r=e.fn;if(r===null)return;a(e),e.runCleanups(),e.trackIndex=0,e.errorHandlers=null,e.idCount=0,e.childCount=0;let i=n.owner,o=n.listener,s=n.running;n.owner=e,n.listener=e,n.running=e,n.recomputeDepth+=1,e.state=0,e.flags|=1,e.stamp=t();let c,l=!1,u;try{c=r(e.value)}catch(e){l=!0,u=e}finally{n.owner=i,n.listener=o,n.running=s,--n.recomputeDepth,e.flags&=-2,e.trackIndex<e.sources.length&&m(e,e.trackIndex)}e.kind===1&&F(e,c,l,u),e.kind!==1&&L(e,c,l,u)}function F(e,t,n,r){if(n&&C(e,r))return!1;let i=!!(e.flags&32);e.flags&=-33;let a=!!(e.flags&8),o;if(n&&I(e,r))return!1;if(n)e.flags|=8,e.error=r,o=!0;else{e.flags&=-9,e.error=void 0;let n=e.equals;try{o=i||a||n===!1||!n(e.value,t),o&&(e.value=t)}catch(t){e.flags|=8,e.error=t,o=!0}}if(!o||i)return o;let s=e.observers;if(s===null)return o;for(let e=0;e<s.length;e+=2){let t=s[e];t.state===1&&(t.state=2)}return o}function I(e,t){if(!s(e))return!1;e.flags&=-9,e.error=void 0;try{o(t,e)}catch(t){e.flags|=8,e.error=t}return!0}function L(e,t,r,a){if(r){C(e,a)||o(a,e);return}let s=e.apply,c;if(s===null)c=t;else{let r=!!(e.flags&64);e.flags&=-65;let i=e.value;if(e.value=t,r)return;let a=n.owner,l=n.listener,u=n.running;n.owner=e,n.listener=null,n.running=e;try{c=s(t,i)}catch(t){C(e,t)||o(t,e);return}finally{n.owner=a,n.listener=l,n.running=u}}typeof c==`function`&&(i(e,c),e.flags&4&&e.runCleanups())}export{d as Computation,u as Signal,y as hasObservers,w as isFrozen,T as markObservers,v as observersOf,N as readMemo,M as readSignal,P as recompute,_ as sourcesOf,g as track,p as unlinkSources,A as updateIfNecessary};
2
+ //# sourceMappingURL=graph.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","names":["NO_SOURCES","Signal","value","equals","name","Computation","Owner","parent","kind","flags","fn","nextSequence","unlinkSources","removeObserver","observers","source","last","at","moved","movedAt","unlinkFrom","node","sources","from","i","withEdge","length","array","first","second","next","track","listener","rt","position","index","sourcesOf","everyOther","observersOf","hasObservers","out","edges","markStack","stale","previous","observer","enqueue","trySuspend","error","isFrozen","markObservers","staleObservers","frameNodes","frameIndex","frameTop","updateIfNecessary","root","base","eagerSources","cursor","descended","dependency","ShadowError","refreshAncestors","recompute","pending","owner","ancestor","readSignal","signal","readMemo","memo","disposeChildren","previousOwner","previousListener","previousRunning","result","failed","failure","settleMemo","settleEffect","hadError","changed","routeToHandler","comparatorError","hasErrorHandler","handleError","unhandled","apply","cleanup","deferred","previousValue","addCleanup"],"sources":["../../../src/internal/graph.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport {\n CHECK,\n CLEAN,\n DIRTY,\n FLAG_DEFER,\n FLAG_DISPOSED,\n FLAG_HAS_ERROR,\n FLAG_REFRESHING,\n FLAG_RENDER,\n FLAG_RUNNING,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n KIND_SIGNAL,\n} from \"./flags\";\nimport { addCleanup, disposeChildren, handleError, hasErrorHandler, Owner } from \"./owner\";\nimport { enqueue } from \"./queue\";\nimport { nextSequence, rt } from \"./state\";\nimport type { Cleanup, Equals } from \"./types\";\n\n// Shared and frozen until a computation reads its first source: most effects and memos in a large\n// tree own few edges, and an empty array per node dominates creation cost.\nconst NO_SOURCES: Edges<Source> = Object.freeze([]) as unknown as Edges<Source>;\n\n/** Memo nesting depth after which pulls switch from recursion to the iterative walk. */\nconst DEEP_LIMIT = 128;\n\n/**\n * Anything that can be read reactively and notify observers: a signal, a memo, or a custom source\n * of a primitive. Exported from `@shadow-js/core/extend` as `SourceNode`. Read one with\n * {@link track}; after changing it, call {@link markObservers} and `schedule` (or `notify`).\n * @since 1.0.0\n */\nexport interface Source {\n /**\n * The node kind: 0 for a signal and for any custom source, which have no sources of their own; a\n * computation has its own kind. A refresh walks only the sources whose kind is not 0.\n */\n readonly kind: number;\n /** The current value. */\n value: unknown;\n /**\n * The computations that read this source in their last run, as pairs: an observer, then the index of this source in\n * that observer's `sources`. Null or empty when none. Read it with `observersOf`, which returns the observers alone.\n */\n observers: Edges<Computation> | null;\n /** Stamp of the last computation run that tracked this source (dedupes repeated reads). */\n stamp: number;\n}\n\n/**\n * The edges of one node, stored as pairs in one array: the node on the other side of the edge, then the index of this\n * node's entry in that node's own edge array. One array per side costs half the memory of two parallel ones, and\n * removing an edge stays O(1): the last pair moves into the vacated place and tells its owner where it went.\n */\nexport type Edges<T> = Array<T | number>;\n\n/**\n * The storage of a signal: its value, its equality and the computations that read it. Exported from\n * `@shadow-js/core/extend` as `SignalNode`; create one with `createSignalNode`, read it with\n * {@link readSignal} and write it with `writeSignal`, which notifies its readers. Build a custom\n * primitive on it the way `useSignal` does.\n *\n * @example\n * import { createSignalNode, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(0, Object.is, \"count\");\n * writeSignal(count, 1);\n * console.log(readSignal(count), count instanceof SignalNode); // 1 true\n * @see createSignalNode\n * @since 1.0.0\n */\nexport class Signal<T = unknown> implements Source {\n /** Always 0, the kind of a signal. */\n readonly kind: number = KIND_SIGNAL;\n /**\n * The current value. Assigning it directly notifies no one: use `writeSignal`, or call `notify`\n * after the assignment.\n */\n value: T;\n /** Decides whether a write is a change; `false` treats every write as one. */\n equals: Equals<T>;\n /** The computations that read this signal in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the last computation run that tracked this signal (dedupes repeated reads). */\n stamp = 0;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name: string | undefined;\n\n /**\n * Creates a signal. Prefer `createSignalNode`, which takes the same arguments.\n * @param value Initial value.\n * @param equals Equality that decides whether a write is a change.\n * @param name Devtools label, or undefined for an unnamed signal.\n */\n constructor(value: T, equals: Equals<T>, name: string | undefined) {\n this.value = value;\n this.equals = equals;\n this.name = name;\n if (__DEV__) report(DEVTOOLS_EVENT.SIGNAL_CREATED, this, rt.owner, name, value);\n }\n}\n\n/**\n * A memo or an effect: an owner that reads sources and (for memos) is itself a source. Exported from\n * `@shadow-js/core/extend` as `ComputationNode`; create one with `createComputation` and read a memo\n * with `readComputation`. It owns what its function creates: each run first disposes the children\n * and runs the cleanups of the previous run.\n *\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode(10, Object.is);\n * const total = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 2 });\n * console.log(readComputation<number>(total)); // 20\n * @see createComputation\n * @since 1.0.0\n */\nexport class Computation extends Owner implements Source {\n /** 1 for a memo, 2 for an effect. */\n kind: number;\n /** How stale the node is: 0 (clean), 1 (a transitive source changed), 2 (a direct source changed). */\n state: number;\n /** Engine bit flags (queued, running, disposed, render phase, ...). Read-only outside the engine. */\n flags: number;\n /** A memo's last value; an effect's last computed value when it has an `apply` stage. */\n value: unknown;\n /** The error a memo's last run threw, rethrown to its readers; undefined when it succeeded. */\n error: unknown = undefined;\n /** A memo's equality: readers are notified only when it says the new value differs. */\n equals: Equals<unknown>;\n /** The function each run calls with the previous value; null once disposed. */\n fn: ((previous: never) => unknown) | null;\n /**\n * An effect's second stage, run untracked with the computed value and the previous one; null for\n * none and once disposed.\n */\n apply: ((value: never, previous: never) => unknown) | null = null;\n /**\n * The sources the last run read, in reading order, as pairs: a source, then the index of this computation in that\n * source's `observers`. Read it with `sourcesOf`, which returns the sources alone.\n */\n sources: Edges<Source> = NO_SOURCES;\n /** The computations that read this memo in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the current run while it tracks, and of the last run that tracked this memo. */\n stamp = 0;\n /** During a run: how many leading entries of `sources` were confirmed again (they keep their edges). */\n trackIndex = 0;\n /** Creation order; breaks ties between effects at equal depth (G-16). */\n seq: number;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the computation is unnamed)\n */\n name: string | undefined;\n\n /**\n * Creates a computation that has not run yet. Prefer `createComputation`, which also runs or\n * queues it.\n * @param parent The owner to attach to, or null.\n * @param kind 1 for a memo, 2 for an effect.\n * @param flags Initial engine bit flags.\n * @param fn The function each run calls.\n * @param equals A memo's equality; `false` for an effect.\n * @param name Devtools label, or undefined.\n */\n constructor(\n parent: Owner | null,\n kind: number,\n flags: number,\n fn: (previous: never) => unknown,\n equals: Equals<unknown>,\n name: string | undefined,\n ) {\n super(parent);\n this.kind = kind;\n this.flags = flags;\n this.state = DIRTY;\n this.fn = fn;\n this.equals = equals;\n this.name = name;\n this.value = undefined;\n this.seq = nextSequence();\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_CREATED,\n this,\n parent,\n kind === KIND_MEMO ? \"memo\" : \"effect\",\n name,\n (flags & FLAG_RENDER) !== 0,\n );\n }\n }\n\n protected override reportDisposed(): void {\n if (__DEV__) report(DEVTOOLS_EVENT.COMPUTATION_DISPOSED, this);\n }\n\n protected override release(): void {\n this.flags |= FLAG_DISPOSED;\n unlinkSources(this);\n this.fn = null;\n this.apply = null;\n }\n}\n\n/**\n * Removes the pair at `at` from `source.observers` in O(1): the last pair moves into its place, and its observer is told\n * where it went.\n */\nfunction removeObserver(source: Source, at: number): void {\n const observers = source.observers;\n if (observers === null) return;\n const last = observers.length - 2;\n if (at !== last) {\n const moved = observers[last] as Computation;\n const movedAt = observers[last + 1] as number;\n observers[at] = moved;\n observers[at + 1] = movedAt;\n moved.sources[movedAt + 1] = at;\n }\n observers.length = last;\n}\n\n/** Drops every edge from `node` to its sources. */\nexport function unlinkSources(node: Computation): void {\n unlinkFrom(node, 0);\n}\n\n/** Drops the edges from `node` to the sources at index `from` of `node.sources` and later, and truncates the list. */\nfunction unlinkFrom(node: Computation, from: number): void {\n const sources = node.sources;\n if (sources.length <= from) return;\n for (let i = sources.length - 2; i >= from; i -= 2) {\n // The index in the source is read each time: removing an edge may move this node's pair in another source.\n removeObserver(sources[i] as Source, sources[i + 1] as number);\n }\n sources.length = from;\n}\n\n/**\n * The array with the pair `first`, `second` appended: a new array of exactly the right size while short (`new Array(n)`\n * allocates the backing store at that size, where `push` on a short array reserves room for sixteen), the same array\n * grown by `push` from sixteen entries on.\n */\nfunction withEdge<T>(array: Array<T | number>, first: T, second: number): Array<T | number> {\n const length = array.length;\n if (length >= 16) {\n array.push(first, second);\n return array;\n }\n const next = new Array<T | number>(length + 2);\n for (let i = 0; i < length; i += 1) next[i] = array[i] as T | number;\n next[length] = first;\n next[length + 1] = second;\n return next;\n}\n\n/**\n * Records that the running computation read `source`, so a later {@link markObservers} on it marks\n * that computation stale. Call it in the reader of a custom source; {@link readSignal} does it for\n * signals. Does nothing when untracked, and a source read again in the same run is recorded once.\n *\n * @param source The source that was read.\n * @example\n * import { markObservers, schedule, type SourceNode, track } from \"@shadow-js/core/extend\";\n *\n * const clock: SourceNode = { kind: 0, value: Date.now(), observers: null, stamp: 0 };\n * export function now(): number {\n * track(clock);\n * return clock.value as number;\n * }\n * setInterval(() => {\n * clock.value = Date.now();\n * markObservers(clock);\n * schedule();\n * }, 1000);\n * @see readSignal\n * @since 1.0.0\n */\nexport function track(source: Source): void {\n const listener = rt.listener;\n if (listener === null) return;\n if (source.stamp === listener.stamp) return;\n source.stamp = listener.stamp;\n // Same dependency at the same position as last run: keep the edge, touch nothing.\n const position = listener.trackIndex;\n if (position < listener.sources.length) {\n if (listener.sources[position] === source) {\n listener.trackIndex = position + 2;\n return;\n }\n unlinkFrom(listener, position);\n }\n // Edge arrays are small: most nodes have one to three edges. `push` on a short array reserves room for about sixteen\n // entries (200 bytes where an exact array takes 64, measured), and a large list pays it for every row. A short array\n // therefore grows into a new exact one; from sixteen entries on `push` amortizes. Nothing iterates an edge array of\n // a node while it tracks, so replacing the array is safe.\n const observers = source.observers;\n const sources = listener.sources;\n const at = observers === null ? 0 : observers.length;\n const index = sources.length;\n source.observers =\n observers === null\n ? [listener, index]\n : (withEdge(observers, listener, index) as Edges<Computation>);\n listener.sources = withEdge(sources, source, at) as Edges<Source>;\n listener.trackIndex = index + 2;\n}\n\n/**\n * The sources the last run of a computation read, in reading order. Use it to inspect the graph (a debugger, a test);\n * it is a snapshot, so changing the returned array changes no edge.\n *\n * @param node The memo or effect.\n * @returns The signals and memos it reads now.\n * @example\n * import { createComputation, createSignalNode, flushSync, readSignal, sourcesOf } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * const effect = createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(sourcesOf(effect).length); // 1\n * @see observersOf\n * @since 1.0.0\n */\nexport function sourcesOf(node: Computation): Source[] {\n return everyOther(node.sources) as Source[];\n}\n\n/**\n * The computations that read a signal or memo in their last run, in the order their edges were made. It is a snapshot,\n * so changing the returned array changes no edge. The node's own `observers` array stores pairs (the observer and an\n * index for the engine), so read it through this function.\n *\n * @param source A signal, a memo or a custom source.\n * @returns The memos and effects that read it now.\n * @example\n * import { createComputation, createSignalNode, flushSync, observersOf, readSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(observersOf(count).length); // 1\n * @see sourcesOf\n * @since 1.0.0\n */\nexport function observersOf(source: Source): Computation[] {\n return source.observers === null ? [] : (everyOther(source.observers) as Computation[]);\n}\n\n/** True when at least one computation read `source` in its last run. */\nexport function hasObservers(source: Source): boolean {\n return source.observers !== null && source.observers.length > 0;\n}\n\n/** The first element of every pair of an edge array. */\nfunction everyOther<T>(edges: Edges<T>): T[] {\n const out: T[] = [];\n for (let i = 0; i < edges.length; i += 2) out.push(edges[i] as T);\n return out;\n}\n\n// Scratch stack for markObservers; never holds data across calls.\nconst markStack: Computation[] = [];\n\nfunction stale(observer: Computation, next: number): void {\n const previous = observer.state;\n if (observer.kind === KIND_EFFECT) {\n if (previous < next) observer.state = next;\n if (previous === CLEAN) enqueue(observer);\n else if (!rt.inTransition) rt.hooks?.promote(observer);\n return;\n }\n if (previous >= next) return;\n observer.state = next;\n if (previous !== CLEAN) return;\n if (observer.observers !== null && observer.observers.length > 0) markStack.push(observer);\n}\n\n/**\n * A suspension (a transition read pending data inside a held boundary) keeps the node's value until the\n * boundary releases it. True when `error` was one, and the node was recorded for that wake-up.\n */\nfunction trySuspend(node: Computation, error: unknown): boolean {\n return rt.hooks?.suspend(node, error) === true;\n}\n\n/**\n * A memo or effect frozen by a pause keeps its last value and does not refresh until it resumes.\n * A memo that never computed is not frozen (it has no value to keep).\n */\nexport function isFrozen(node: Computation): boolean {\n return node.pauses > 0 && (node.flags & FLAG_UNINIT) === 0;\n}\n\n/**\n * Marks the direct observers of a changed source DIRTY and everything downstream CHECK, and queues\n * the effects it reaches. It does not request a flush: call `schedule` afterward, or use `notify`,\n * which does both. Iterative: the graph can be 100,000 nodes deep (G-10).\n *\n * @param source The source whose value changed.\n * @example\n * import { markObservers, schedule, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function push(list: SignalNode<string[]>, item: string): void {\n * list.value.push(item); // same array: writeSignal would see no change\n * markObservers(list);\n * schedule();\n * }\n * @see track\n * @since 1.0.0\n */\nexport function markObservers(source: Source): void {\n staleObservers(source.observers, DIRTY);\n while (markStack.length > 0) {\n const node = markStack.pop();\n if (node !== undefined) staleObservers(node.observers, CHECK);\n }\n}\n\n/** Marks every observer in a list of edge pairs stale at the given level. */\nfunction staleObservers(observers: Edges<Computation> | null, next: number): void {\n if (observers === null) return;\n for (let i = 0; i < observers.length; i += 2) stale(observers[i] as Computation, next);\n}\n\n// Scratch frames for updateIfNecessary; entries above `frameTop` are dead.\nconst frameNodes: Computation[] = [];\nconst frameIndex: number[] = [];\nlet frameTop = 0;\n\n/**\n * Brings `root` up to date: verifies stale sources oldest-first and recomputes only nodes whose\n * sources really changed (equality cut-off, G-2). Iterative so deep chains cannot overflow (G-10).\n * With `eagerSources`, DIRTY nodes also refresh their previous sources first, which keeps the\n * native stack flat for chains where every node reads both a fresh signal and its predecessor.\n */\nexport function updateIfNecessary(root: Computation, eagerSources = false): void {\n if (root.state === CLEAN) return;\n const base = frameTop;\n frameNodes[frameTop] = root;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n root.flags |= FLAG_REFRESHING;\n try {\n while (frameTop > base) {\n const at = frameTop - 1;\n const node = frameNodes[at];\n if (node === undefined) break;\n if (node.state === CHECK || (node.state === DIRTY && eagerSources)) {\n const sources = node.sources;\n let cursor = frameIndex[at] ?? 0;\n let descended = false;\n while (cursor < sources.length) {\n const source = sources[cursor] as Source;\n cursor += 2;\n if (source.kind === KIND_SIGNAL) continue;\n const dependency = source as Computation;\n if (dependency.state === CLEAN || (dependency.flags & FLAG_DISPOSED) !== 0) continue;\n if (isFrozen(dependency)) continue;\n if ((dependency.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n // An owner that is about to re-run would dispose this dependency: update it first.\n refreshAncestors(dependency);\n if (dependency.state === CLEAN || (dependency.flags & FLAG_DISPOSED) !== 0) continue;\n if (isFrozen(dependency)) continue;\n frameIndex[at] = cursor;\n frameNodes[frameTop] = dependency;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n dependency.flags |= FLAG_REFRESHING;\n descended = true;\n break;\n }\n if (descended) continue;\n }\n if (node.state === DIRTY) recompute(node);\n else node.state = CLEAN;\n node.flags &= ~FLAG_REFRESHING;\n frameTop -= 1;\n }\n } finally {\n // An exception leaves frames on the stack: they must not stay marked as being refreshed.\n for (let i = base; i < frameTop; i += 1) {\n const pending = frameNodes[i];\n if (pending !== undefined) pending.flags &= ~FLAG_REFRESHING;\n }\n frameNodes.length = base;\n frameIndex.length = base;\n frameTop = base;\n }\n}\n\n/**\n * Brings stale owners of `node` up to date, topmost first. An owner that is about to re-run will\n * dispose `node`; computing `node` first would run it with state that is already out of date\n * (a zombie, G-17). Iterative: the owner chain depth is user controlled.\n */\nfunction refreshAncestors(node: Computation): void {\n const stale: Computation[] = [];\n for (let owner = node.parent; owner !== null; owner = owner.parent) {\n if (!(owner instanceof Computation)) continue;\n if (\n owner.state !== CLEAN &&\n (owner.flags & (FLAG_RUNNING | FLAG_DISPOSED | FLAG_REFRESHING)) === 0 &&\n !isFrozen(owner)\n ) {\n stale.push(owner);\n }\n }\n for (let i = stale.length - 1; i >= 0; i -= 1) {\n const ancestor = stale[i];\n if (ancestor !== undefined && (ancestor.flags & FLAG_DISPOSED) === 0) {\n updateIfNecessary(ancestor);\n }\n }\n}\n\n/**\n * Reads a signal's value, subscribing the running computation to it when one is listening. The\n * reader of a custom primitive built on `createSignalNode`.\n *\n * @param signal The signal to read.\n * @returns The current value.\n * @example\n * import { createSignalNode, readSignal } from \"@shadow-js/core/extend\";\n *\n * const name = createSignalNode(\"Ada\", Object.is);\n * export const getName = (): string => readSignal(name);\n * @see track\n * @since 1.0.0\n */\nexport function readSignal<T>(signal: Signal<T>): T {\n if (rt.listener !== null) track(signal);\n return signal.value;\n}\n\n/** Reads a memo: refreshes it if stale, tracks it, rethrows its stored error. */\nexport function readMemo<T>(memo: Computation): T {\n if ((memo.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n if (memo.state !== CLEAN && (memo.flags & FLAG_DISPOSED) === 0 && !isFrozen(memo)) {\n refreshAncestors(memo);\n if ((memo.flags & FLAG_DISPOSED) === 0) {\n updateIfNecessary(memo, rt.recomputeDepth >= DEEP_LIMIT);\n }\n }\n if (rt.listener !== null) track(memo);\n if ((memo.flags & FLAG_HAS_ERROR) !== 0) throw memo.error;\n return memo.value as T;\n}\n\n/** Re-runs a memo or effect: disposes the previous run, re-tracks sources, stores the result. */\nexport function recompute(node: Computation): void {\n const fn = node.fn;\n if (fn === null) return;\n disposeChildren(node);\n node.runCleanups();\n // Edges are kept and re-confirmed in order while the function runs (see track()).\n node.trackIndex = 0;\n // Each run starts from a clean slate: handlers, ids and child indices belong to one run.\n node.errorHandlers = null;\n node.idCount = 0;\n node.childCount = 0;\n\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = node;\n rt.running = node;\n rt.recomputeDepth += 1;\n node.state = CLEAN;\n node.flags |= FLAG_RUNNING;\n node.stamp = nextSequence();\n\n let result: unknown;\n let failed = false;\n let failure: unknown;\n const startedAt = __DEV__ ? performance.now() : 0;\n try {\n result = (fn as (previous: unknown) => unknown)(node.value);\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n rt.recomputeDepth -= 1;\n node.flags &= ~FLAG_RUNNING;\n // Sources this run did not read again are no longer dependencies.\n if (node.trackIndex < node.sources.length) unlinkFrom(node, node.trackIndex);\n }\n\n const changed = node.kind === KIND_MEMO ? settleMemo(node, result, failed, failure) : true;\n if (node.kind !== KIND_MEMO) settleEffect(node, result, failed, failure);\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_RUN,\n node,\n startedAt,\n performance.now() - startedAt,\n changed,\n sourcesOf(node),\n );\n }\n}\n\n/** Stores a memo's result; says whether its value changed (observers were told). */\nfunction settleMemo(\n node: Computation,\n result: unknown,\n failed: boolean,\n failure: unknown,\n): boolean {\n // A suspended memo keeps its previous value: its readers see nothing change until it resumes.\n if (failed && trySuspend(node, failure)) return false;\n const first = (node.flags & FLAG_UNINIT) !== 0;\n node.flags &= ~FLAG_UNINIT;\n const hadError = (node.flags & FLAG_HAS_ERROR) !== 0;\n let changed: boolean;\n if (failed && routeToHandler(node, failure)) {\n return false;\n }\n if (failed) {\n node.flags |= FLAG_HAS_ERROR;\n node.error = failure;\n changed = true;\n } else {\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n const equals = node.equals;\n try {\n changed = first || hadError || equals === false || !equals(node.value, result);\n if (changed) node.value = result;\n } catch (comparatorError) {\n // A throwing comparator is a failing memo, not a wedged graph: readers see the error.\n node.flags |= FLAG_HAS_ERROR;\n node.error = comparatorError;\n changed = true;\n }\n }\n if (!changed || first) return changed;\n const observers = node.observers;\n if (observers === null) return changed;\n for (let i = 0; i < observers.length; i += 2) {\n const observer = observers[i] as Computation;\n if (observer.state === CHECK) observer.state = DIRTY;\n }\n return changed;\n}\n\n/**\n * A memo that fails inside a boundary (an ancestor registered catchError()/onError()) reports to it\n * when it fails, and keeps its previous value. Readers then see that value instead of the error:\n * the reader may live outside the boundary (the DOM region that displays the memo's result), where a\n * rethrown error would escape the very boundary meant to catch it. Without a handler the error is\n * stored and rethrown to readers, so it is never silent.\n *\n * The first computation counts too: its value is `undefined`, and it is typically read by a\n * consumer outside the boundary (a DOM region), not by the code that created it.\n */\nfunction routeToHandler(node: Computation, failure: unknown): boolean {\n if (!hasErrorHandler(node)) return false;\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n try {\n handleError(failure, node);\n } catch (unhandled) {\n // The chain ended in a handler that rethrew: readers see it, as for any unhandled failure.\n node.flags |= FLAG_HAS_ERROR;\n node.error = unhandled;\n }\n return true;\n}\n\nfunction settleEffect(node: Computation, result: unknown, failed: boolean, failure: unknown): void {\n if (failed) {\n if (!trySuspend(node, failure)) handleError(failure, node);\n return;\n }\n const apply = node.apply;\n let cleanup: unknown;\n if (apply === null) {\n cleanup = result;\n } else {\n const deferred = (node.flags & FLAG_DEFER) !== 0;\n node.flags &= ~FLAG_DEFER;\n const previousValue = node.value;\n node.value = result;\n if (deferred) return;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = null;\n // Writes from an effect's apply are legal even when the effect was created inside a memo.\n rt.running = node;\n try {\n cleanup = (apply as (value: unknown, previous: unknown) => unknown)(result, previousValue);\n } catch (error) {\n if (!trySuspend(node, error)) handleError(error, node);\n return;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n }\n }\n if (typeof cleanup === \"function\") {\n addCleanup(node, cleanup as Cleanup);\n // The effect disposed its own owner while running: nothing will dispose it again, so run now.\n if ((node.flags & FLAG_DISPOSED) !== 0) node.runCleanups();\n }\n}\n"],"mappings":"A,oPAwBA,MAAMA,EAA4B,OAAO,OAAO,CAAC,CAAC,EAkDlD,IAAaC,EAAb,KAAmD,CAEjD,KAAS,EAKT,MAEA,OAEA,UAAuC,KAEvC,MAAQ,EAKR,KAQA,YAAY,EAAU,EAAmB,EAA0B,CACjE,KAAK,MAAQC,EACb,KAAK,OAASC,EACd,KAAK,KAAOC,CAEd,CACF,EAiBaC,EAAb,cAAiCC,CAAwB,CAEvD,KAEA,MAEA,MAEA,MAEA,MAAiB,IAAA,GAEjB,OAEA,GAKA,MAA6D,KAK7D,QAAyBN,EAEzB,UAAuC,KAEvC,MAAQ,EAER,WAAa,EAEb,IAKA,KAYA,YACE,EACA,EACA,EACA,EACA,EACA,EACA,CACA,MAAMO,CAAM,EACZ,KAAK,KAAOC,EACZ,KAAK,MAAQC,EACb,KAAK,MAAA,EACL,KAAK,GAAKC,EACV,KAAK,OAASP,EACd,KAAK,KAAOC,EACZ,KAAK,MAAQ,IAAA,GACb,KAAK,IAAMO,EAAa,CAW1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AmBzC,EAAG,SACtB0C,EAAkB1C,EAAG,QAC3B,EAAG,MAAQZ,EACX,EAAG,SAAW,KAEd,EAAG,QAAUA,EACb,GAAI,CACF,EAAWmE,EAAyDZ,EAAQe,CAAa,CAC3F,OAAS3C,EAAO,CACTD,EAAW1B,EAAM2B,CAAK,GAAGsC,EAAYtC,EAAO3B,CAAI,EACrD,MACF,QAAU,CACR,EAAG,MAAQoD,EACX,EAAG,SAAWC,EACd,EAAG,QAAUC,CACf,CACF,CACI,OAAOc,GAAY,aACrBG,EAAWvE,EAAMoE,CAAkB,EAE9BpE,EAAK,MAAA,GAA8BA,EAAK,YAAY,EAE7D,C"}
@@ -0,0 +1,2 @@
1
+ import{rt as e}from"./state.js";function t(){return e.hydrating}function n(t){let n=e.hydrating;e.hydrating=!0;try{return t()}finally{e.hydrating=n}}export{t as isHydrating,n as withHydration};
2
+ //# sourceMappingURL=hydration-flag.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration-flag.js","names":["isHydrating","rt","withHydration","previous","fn"],"sources":["../../../src/internal/hydration-flag.ts"],"sourcesContent":["import { rt } from \"./state\";\n\n/**\n * Tells whether the code runs while `hydrate()` claims server markup. Read it at creation in a hook\n * whose first render must match the server, as `useExternalStore` does to read its server snapshot.\n *\n * @returns True inside {@link withHydration}, false otherwise.\n * @example\n * import { isHydrating } from \"@shadow-js/core/extend\";\n *\n * function initialWidth(serverWidth: number): number {\n * return isHydrating() ? serverWidth : window.innerWidth;\n * }\n * @see withHydration\n * @since 1.0.0\n */\nexport function isHydrating(): boolean {\n return rt.hydrating;\n}\n\n/**\n * Runs `fn` with the hydration flag set, so the hooks created inside see {@link isHydrating} return\n * true, and restores the previous flag in `finally`. Renderers wrap their hydration pass in it (the\n * `hydrate()` of `@shadow-js/web` does); application code does not need it.\n *\n * @param fn The hydration pass. A throw is rethrown after the flag is restored.\n * @returns What `fn` returns.\n * @example\n * import { isHydrating, withHydration } from \"@shadow-js/core/extend\";\n *\n * const during = withHydration(() => isHydrating()); // true\n * const after = isHydrating(); // false again\n * @since 1.0.0\n */\nexport function withHydration<T>(fn: () => T): T {\n const previous = rt.hydrating;\n rt.hydrating = true;\n try {\n return fn();\n } finally {\n rt.hydrating = previous;\n }\n}\n"],"mappings":"A,gCAgBA,SAAgBA,GAAuB,CACrC,OAAOC,EAAG,SACZ,CAgBA,SAAgBC,EAAiB,EAAgB,CAC/C,IAAMC,EAAWF,EAAG,UACpB,EAAG,UAAY,GACf,GAAI,CACF,OAAOG,EAAG,CACZ,QAAU,CACR,EAAG,UAAYD,CACjB,CACF,C"}
@@ -0,0 +1,2 @@
1
+ const e={NO_OWNER_EFFECT:`An effect was created outside any owner, so it can never be disposed. Create it inside a component or createRoot().`,NO_OWNER_CLEANUP:`onCleanup() was called outside any owner, so the cleanup will never run.`,NO_OWNER_ERROR:`onError() was called outside any owner, so the handler can never be reached.`,WRITE_IN_MEMO:`A signal was written inside a useMemo() computation. Derive values from sources instead, or write from an effect.`,CYCLE_DETECTED:`A reactive cycle was detected: a computation read itself while it was running.`,INFINITE_LOOP:`Effects kept re-triggering each other for more than 1000 passes; the flush was aborted.`,FLUSH_IN_EFFECT:`flushSync() was called while a flush was already running; the call was ignored.`,RUN_WITH_DISPOSED_OWNER:`runWithOwner() was called with an owner that is already disposed; the callback ran without an owner.`,DUPLICATE_CORE:`More than one copy of @shadow-js/core is loaded. Signals created by one copy are invisible to the other.`,CONTEXT_MISSING:`useContext() found no provider and the context has no default value.`,NO_OWNER_ID:`useId() was called outside any owner; the id is not stable across server and client.`,EACH_KEY_DUPLICATE:`Duplicate key in a keyed list; later duplicates get fresh rows each update.`,EFFECT_DEPS_IGNORED:`useEffect(fn, [deps]) ignores the array and re-runs on any signal it reads; use useEffect(deps, fn).`};function t(e){return`SHADOW_${e}`}export{e as MESSAGES,t as formatMessage};
2
+ //# sourceMappingURL=messages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messages.js","names":["MESSAGES","formatMessage","code"],"sources":["../../../src/internal/messages.ts"],"sourcesContent":["/**\n * The diagnostic catalog: every code the runtime throws (as {@link ShadowError}) or warns with\n * (through {@link warn}), mapped to its development text. Read it to show or match a diagnostic by\n * code. {@link formatMessage} reads it only in development builds, so production bundles keep the\n * code (`SHADOW_<CODE>`) and drop the text (R-CODE-8) unless your own code imports this object.\n *\n * @example\n * import { MESSAGES, type MessageCode } from \"@shadow-js/core/extend\";\n *\n * function explain(code: MessageCode): string {\n * return `${code}: ${MESSAGES[code]}`;\n * }\n * @see formatMessage\n * @since 1.0.0\n */\nexport const MESSAGES = {\n NO_OWNER_EFFECT:\n \"An effect was created outside any owner, so it can never be disposed. Create it inside a component or createRoot().\",\n NO_OWNER_CLEANUP: \"onCleanup() was called outside any owner, so the cleanup will never run.\",\n NO_OWNER_ERROR: \"onError() was called outside any owner, so the handler can never be reached.\",\n WRITE_IN_MEMO:\n \"A signal was written inside a useMemo() computation. Derive values from sources instead, or write from an effect.\",\n CYCLE_DETECTED: \"A reactive cycle was detected: a computation read itself while it was running.\",\n INFINITE_LOOP:\n \"Effects kept re-triggering each other for more than 1000 passes; the flush was aborted.\",\n FLUSH_IN_EFFECT:\n \"flushSync() was called while a flush was already running; the call was ignored.\",\n RUN_WITH_DISPOSED_OWNER:\n \"runWithOwner() was called with an owner that is already disposed; the callback ran without an owner.\",\n DUPLICATE_CORE:\n \"More than one copy of @shadow-js/core is loaded. Signals created by one copy are invisible to the other.\",\n CONTEXT_MISSING: \"useContext() found no provider and the context has no default value.\",\n NO_OWNER_ID:\n \"useId() was called outside any owner; the id is not stable across server and client.\",\n EACH_KEY_DUPLICATE: \"Duplicate key in a keyed list; later duplicates get fresh rows each update.\",\n EFFECT_DEPS_IGNORED:\n \"useEffect(fn, [deps]) ignores the array and re-runs on any signal it reads; use useEffect(deps, fn).\",\n} as const;\n\n/**\n * A diagnostic code: one key of {@link MESSAGES}, such as `\"WRITE_IN_MEMO\"`. {@link ShadowError}\n * carries one in its `code` field, and {@link warn} takes one.\n * @since 1.0.0\n */\nexport type MessageCode = keyof typeof MESSAGES;\n\n/**\n * Turns a diagnostic code into the text the runtime throws or logs: the full sentence in development\n * builds and only a stable code in production builds, so message strings never reach user bundles.\n * Use it when a custom primitive reports a core diagnostic in its own way.\n *\n * @param code The diagnostic code.\n * @returns `[shadow <CODE>] <text>` in development builds, `SHADOW_<CODE>` in production builds.\n * @example\n * import { formatMessage } from \"@shadow-js/core/extend\";\n *\n * const text = formatMessage(\"CONTEXT_MISSING\");\n * // development: \"[shadow CONTEXT_MISSING] useContext() found no provider ...\"\n * // production: \"SHADOW_CONTEXT_MISSING\"\n * @see MESSAGES\n * @since 1.0.0\n */\nexport function formatMessage(code: MessageCode): string {\n return __DEV__ ? `[shadow ${code}] ${MESSAGES[code]}` : `SHADOW_${code}`;\n}\n"],"mappings":"AAeA,MAAaA,EAAW,CACtB,gBACE,sHACF,iBAAkB,2EAClB,eAAgB,+EAChB,cACE,oHACF,eAAgB,iFAChB,cACE,0FACF,gBACE,kFACF,wBACE,uGACF,eACE,2GACF,gBAAiB,uEACjB,YACE,uFACF,mBAAoB,8EACpB,oBACE,sGACJ,EAyBA,SAAgBC,EAAc,EAA2B,CACvD,MAAwD,UAAUC,GACpE,C"}
@@ -0,0 +1,2 @@
1
+ import{rt as e}from"./state.js";var t=class{parent;lastChild=null;prevSibling=null;nextSibling=null;cleanups=null;context;errorHandlers=null;childCount=0;idCount=0;index;depth;idPrefix;disposed=!1;gate=null;pauses=0;constructor(e){if(this.parent=e,this.context=e===null?null:e.context,this.depth=e===null?0:e.depth+1,this.pauses=e===null?0:e.pauses,e===null)this.index=0;else{this.index=e.childCount,e.childCount+=1;let t=e.lastChild;this.prevSibling=t,t!==null&&(t.nextSibling=this),e.lastChild=this}}reportDisposed(){}release(){}disposeSelf(){if(this.disposed)return;this.disposed=!0;let e=this.parent;if(e!==null){let t=this.prevSibling,n=this.nextSibling;t!==null&&(t.nextSibling=n),n===null?e.lastChild=t:n.prevSibling=t,this.prevSibling=null,this.nextSibling=null}this.release(),this.reportDisposed(),this.runCleanups()}runCleanups(){let t=this.cleanups;if(t===null)return;this.cleanups=null;let r=e.owner,i=e.listener;e.owner=null,e.listener=null;try{if(typeof t==`function`)n(t,this);else for(let e=t.length-1;e>=0;--e){let r=t[e];r!==void 0&&n(r,this)}}finally{e.owner=r,e.listener=i}}};function n(e,t){try{e()}catch(e){s(e,t)}}function r(e,t){let n=e.cleanups;n===null?e.cleanups=t:typeof n==`function`?e.cleanups=[n,t]:n.push(t)}function i(e){for(;;){let t=e.lastChild;if(t===null)return;o(t)}}function a(){if(--e.disposing,e.disposing>0||e.flushing||e.uncaught.length===0)return;let t=e.uncaught;throw e.uncaught=[],t.length===1?t[0]:AggregateError(t,`SHADOW_DISPOSE_ERRORS`)}function o(t){e.disposing+=1;try{let e=t;for(;;){for(;e.lastChild!==null;)e=e.lastChild;let n=e.parent;if(e.disposeSelf(),e===t||n===null)break;e=n}}finally{a()}}function s(t,n){let r=t;for(let t=n;t!==null;t=t.parent){let n=t.errorHandlers;if(n!==null)for(let t=n.length-1;t>=0;--t){let i=n[t];if(i===void 0)continue;let a=e.listener;try{e.listener=null,i(r);return}catch(e){r=e}finally{e.listener=a}}}l(r)}function c(e){for(let t=e;t!==null;t=t.parent){let e=t.errorHandlers;if(e!==null&&e.length>0)return!0}return!1}function l(t){if(e.flushing||e.disposing>0)e.uncaught.push(t);else throw t}export{t as Owner,r as addCleanup,i as disposeChildren,o as disposeTree,s as handleError,c as hasErrorHandler};
2
+ //# sourceMappingURL=owner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"owner.js","names":["Owner","parent","last","prev","next","cleanups","previousOwner","rt","previousListener","runCleanup","i","cleanup","error","handleError","owner","addCleanup","existing","disposeChildren","child","disposeTree","finishDisposal","errors","node","root","current","from","handlers","handler","reportUncaught","hasErrorHandler"],"sources":["../../../src/internal/owner.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { rt } from \"./state\";\nimport type { Cleanup, ErrorHandler } from \"./types\";\n\n/**\n * The context values an owner sees, keyed by the symbol of each context. A provider creates a map\n * whose prototype is its parent's map, so a lookup is one property read and never walks owners.\n * @since 1.0.0\n */\nexport type ContextMap = Record<symbol, unknown>;\n\n/**\n * A node in the ownership tree: it owns the effects, memos and owners created under it, their\n * cleanups and error handlers, and disposes them together. Create one with `createOwner` and end it\n * with `disposeOwner`; the class is exported for `instanceof` checks and for reading its state.\n * Computations (`ComputationNode`) are owners too. Children are a doubly linked list so detaching one\n * is O(1); disposal walks the tree iteratively because its depth is user controlled (R-CODE-11).\n *\n * @example\n * import { createOwner, disposeOwner, Owner } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * console.log(owner instanceof Owner, owner.depth); // true 0\n * disposeOwner(owner);\n * console.log(owner.disposed); // true\n * @see createOwner\n * @see disposeOwner\n * @since 1.0.0\n */\nexport class Owner {\n /** The owner this node was created under, or null for a root. Kept after disposal. */\n parent: Owner | null;\n /** The newest child that is still alive, or null when there is none. */\n lastChild: Owner | null = null;\n /** The next older sibling that is still alive, or null. */\n prevSibling: Owner | null = null;\n /** The next newer sibling that is still alive, or null. */\n nextSibling: Owner | null = null;\n /**\n * The cleanups registered with `addCleanup` or `onCleanup`: null for none, a function for one, an\n * array (oldest first) for several. Emptied when they run.\n */\n cleanups: Cleanup | Cleanup[] | null = null;\n /** The context values this node sees: inherited from the parent at creation, null for a root. */\n context: ContextMap | null;\n /**\n * The handlers registered with `onError` or `catchError`, oldest first (they are tried newest\n * first), or null for none. A computation clears them before each run.\n */\n errorHandlers: ErrorHandler[] | null = null;\n /** Number of children ever created; gives each child a stable index for useId(). */\n childCount = 0;\n /** Number of ids useId() has handed out from this owner. */\n idCount = 0;\n /** Position among the parent's children, assigned at creation. */\n index: number;\n /** Distance from the root: 0 for a root, the parent's depth plus one otherwise. */\n depth: number;\n /**\n * The hydration-scope prefix of a component's owner, set by the renderer. When present, useId()\n * builds the ids below it from this prefix instead of the owner path.\n * @default undefined\n */\n idPrefix: string | undefined;\n /** True once the node has been disposed. */\n disposed = false;\n /**\n * While this returns true, user effects (and `onMount`) created below this owner wait: they do\n * not run until it returns false for the first time. Suspense sets it so the effects of content\n * that is still loading are held back. The read is tracked.\n */\n gate: (() => boolean) | null = null;\n /**\n * Number of pauses (Activity hidden) that cover this node. Inherited at creation, and changed for a\n * whole subtree by `pauseOwner`/`resumeOwner`. Above zero, effects wait and memos keep their value.\n */\n pauses = 0;\n\n /**\n * Creates an owner and links it as the newest child of `parent`. It inherits the parent's context\n * and pauses.\n * @param parent The owner to attach to, or null for a root.\n */\n constructor(parent: Owner | null) {\n this.parent = parent;\n this.context = parent === null ? null : parent.context;\n this.depth = parent === null ? 0 : parent.depth + 1;\n this.pauses = parent === null ? 0 : parent.pauses;\n if (parent === null) {\n this.index = 0;\n } else {\n this.index = parent.childCount;\n parent.childCount += 1;\n const last = parent.lastChild;\n this.prevSibling = last;\n if (last !== null) last.nextSibling = this;\n parent.lastChild = this;\n }\n // Computations report themselves (with their kind); plain owners and subclasses of it here.\n if (__DEV__ && new.target === Owner) {\n report(DEVTOOLS_EVENT.OWNER_CREATED, this, parent, parent === null ? \"root\" : \"owner\");\n }\n }\n\n /** Tells devtools this node is gone. Computations override it with their own event. */\n protected reportDisposed(): void {\n if (__DEV__) report(DEVTOOLS_EVENT.OWNER_DISPOSED, this);\n }\n\n /** Hook for subclasses: release graph edges before the node is marked disposed. */\n protected release(): void {\n // Plain owners hold no graph edges.\n }\n\n /**\n * Disposes this node only (children must already be gone).\n * @internal\n */\n disposeSelf(): void {\n if (this.disposed) return;\n this.disposed = true;\n // Detach first: a cleanup that throws must never leave a dead node in the tree (R-CODE-5).\n const parent = this.parent;\n if (parent !== null) {\n const prev = this.prevSibling;\n const next = this.nextSibling;\n if (prev !== null) prev.nextSibling = next;\n if (next !== null) next.prevSibling = prev;\n else parent.lastChild = prev;\n this.prevSibling = null;\n this.nextSibling = null;\n }\n this.release();\n this.reportDisposed();\n this.runCleanups();\n }\n\n /**\n * Runs own cleanups newest first, untracked, isolating failures.\n * @internal\n */\n runCleanups(): void {\n const cleanups = this.cleanups;\n if (cleanups === null) return;\n this.cleanups = null;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = null;\n rt.listener = null;\n try {\n if (typeof cleanups === \"function\") {\n runCleanup(cleanups, this);\n } else {\n for (let i = cleanups.length - 1; i >= 0; i -= 1) {\n const cleanup = cleanups[i];\n if (cleanup !== undefined) runCleanup(cleanup, this);\n }\n }\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n }\n}\n\nfunction runCleanup(cleanup: Cleanup, owner: Owner): void {\n try {\n cleanup();\n } catch (error) {\n handleError(error, owner);\n }\n}\n\n/**\n * Registers `cleanup` on an explicit owner. It runs when the owner is disposed or, when the owner is a\n * computation, before its next run. Cleanups run newest first, untracked and with no current owner;\n * one that throws goes to {@link handleError} for that owner and does not stop the others. Use it\n * where `onCleanup` cannot be called: the owner is not the current one, or the code must not warn.\n * Unlike `onCleanup`, nothing checks that the owner is still alive: a cleanup added to a disposed\n * owner never runs.\n *\n * @param owner The owner whose disposal runs the cleanup.\n * @param cleanup The function to run.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * export function useInterval(tick: () => void, ms: number): void {\n * const owner = currentOwner();\n * const timer = setInterval(tick, ms);\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see disposeOwner\n * @since 1.0.0\n */\nexport function addCleanup(owner: Owner, cleanup: Cleanup): void {\n const existing = owner.cleanups;\n if (existing === null) owner.cleanups = cleanup;\n else if (typeof existing === \"function\") owner.cleanups = [existing, cleanup];\n else existing.push(cleanup);\n}\n\n/**\n * Disposes every child of `owner` (newest first), keeping `owner` itself alive.\n * @internal\n */\nexport function disposeChildren(owner: Owner): void {\n for (;;) {\n const child = owner.lastChild;\n if (child === null) return;\n disposeTree(child);\n }\n}\n\n/** Rethrows what disposal collected once the outermost disposal is finished. */\nfunction finishDisposal(): void {\n rt.disposing -= 1;\n if (rt.disposing > 0 || rt.flushing || rt.uncaught.length === 0) return;\n const errors = rt.uncaught;\n rt.uncaught = [];\n if (errors.length === 1) throw errors[0];\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while disposing.\" : \"SHADOW_DISPOSE_ERRORS\",\n );\n}\n\n/**\n * Disposes `root` and everything below it: children first, then own cleanups, newest first.\n * Iterative post-order walk: a leaf is disposed, which re-links its parent's `lastChild`\n * to the previous sibling, so the loop naturally visits the remaining subtree. The public\n * `disposeOwner` (dispose.ts) wraps it with the flush that follows.\n * @internal\n */\nexport function disposeTree(root: Owner): void {\n rt.disposing += 1;\n try {\n let node: Owner = root;\n for (;;) {\n while (node.lastChild !== null) node = node.lastChild;\n const parent: Owner | null = node.parent;\n node.disposeSelf();\n if (node === root || parent === null) break;\n node = parent;\n }\n } finally {\n finishDisposal();\n }\n}\n\n/**\n * Routes `error` to the nearest handler registered with `catchError` or `onError`, searching `from`\n * and then its ancestors, newest handler first on each owner. Handlers run untracked and restore\n * the caller's tracking even when they rethrow. Use it for errors that happen outside\n * any computation (a rejected promise, an event callback), so they reach the same boundary as errors\n * thrown during rendering. A handler that throws hands its own error to the next handler up the\n * chain. With no handler left the error is uncaught: collected until the running flush or disposal\n * ends (which then throws it), or thrown at once otherwise.\n *\n * @param error The thrown value.\n * @param from The owner where the error happened. Null searches no handler: the error is uncaught.\n * @throws The error (or the last error a handler threw) when no handler catches it and no flush or\n * disposal is running.\n * @example\n * import { currentOwner, handleError } from \"@shadow-js/core/extend\";\n *\n * export function useSaveOnLoad(save: () => Promise<void>): void {\n * const owner = currentOwner();\n * save().catch((error: unknown) => handleError(error, owner));\n * }\n * @since 1.0.0\n */\nexport function handleError(error: unknown, from: Owner | null): void {\n if (__DEV__) report(DEVTOOLS_EVENT.ERROR, from, error, codeOf(error));\n let current = error;\n for (let owner = from; owner !== null; owner = owner.parent) {\n const handlers = owner.errorHandlers;\n if (handlers === null) continue;\n for (let i = handlers.length - 1; i >= 0; i -= 1) {\n const handler = handlers[i];\n if (handler === undefined) continue;\n const previousListener = rt.listener;\n try {\n rt.listener = null;\n return void handler(current);\n } catch (next) {\n current = next;\n } finally {\n rt.listener = previousListener;\n }\n }\n }\n reportUncaught(current);\n}\n\n/**\n * True when `handleError(_, from)` would reach a handler registered by catchError()/onError().\n * @internal\n */\nexport function hasErrorHandler(from: Owner | null): boolean {\n for (let owner = from; owner !== null; owner = owner.parent) {\n const handlers = owner.errorHandlers;\n if (handlers !== null && handlers.length > 0) return true;\n }\n return false;\n}\n\n/**\n * The diagnostic code of a ShadowJS error, for devtools. Reads an own data property only: a getter on a thrown\n * value would run user code inside the error path, and a throw there would replace the error being handled.\n */\nfunction codeOf(error: unknown): unknown {\n if (typeof error !== \"object\" || error === null) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(error, \"code\");\n return descriptor !== undefined && \"value\" in descriptor ? descriptor.value : undefined;\n}\n\nfunction reportUncaught(error: unknown): void {\n if (rt.flushing || rt.disposing > 0) rt.uncaught.push(error);\n else throw error;\n}\n"],"mappings":"A,gCA6BA,IAAaA,EAAb,KAAmB,CAEjB,OAEA,UAA0B,KAE1B,YAA4B,KAE5B,YAA4B,KAK5B,SAAuC,KAEvC,QAKA,cAAuC,KAEvC,WAAa,EAEb,QAAU,EAEV,MAEA,MAMA,SAEA,SAAW,GAMX,KAA+B,KAK/B,OAAS,EAOT,YAAY,EAAsB,CAKhC,GAJA,KAAK,OAASC,EACd,KAAK,QAAUA,IAAW,KAAO,KAAOA,EAAO,QAC/C,KAAK,MAAQA,IAAW,KAAO,EAAIA,EAAO,MAAQ,EAClD,KAAK,OAASA,IAAW,KAAO,EAAIA,EAAO,OACvCA,IAAW,KACb,KAAK,MAAQ,MACR,CACL,KAAK,MAAQA,EAAO,WACpB,EAAO,YAAc,EACrB,IAAMC,EAAOD,EAAO,UACpB,KAAK,YAAcC,EACfA,IAAS,OAAM,EAAK,YAAc,MACt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EAAsB,CAC5C,GAAIrB,EAAG,UAAYA,EAAG,UAAY,EAAGA,EAAG,SAAS,KAAKK,CAAK,OACtD,MAAMA,CACb,C"}
@@ -0,0 +1,2 @@
1
+ import{FLAG_PARKED as e,FLAG_TRANSITION as t}from"./flags.js";import{rt as n}from"./state.js";const r=[],i=[];function a(a,o){if(a.flags&2)return;let s=o||!!(a.flags&512),c=n.hooks;c!==null&&(s||a.pauses>0)?c.place(a,s):(a.flags=a.flags&~(e|t)|2,a.flags&16?r.push(a):i.push(a))}function o(e){a(e,n.inTransition)}function s(){return r.length>0||i.length>0}function c(){for(let e of[r,i]){for(let n of e)n.flags&=~(2|t),n.state=0;e.length=0}n.hooks?.clear()}export{c as clearQueues,o as enqueue,s as hasPending,a as place,r as renderQueue,i as userQueue};
2
+ //# sourceMappingURL=queue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queue.js","names":["renderQueue","userQueue","place","effect","inLane","lane","hooks","rt","FLAG_PARKED","FLAG_TRANSITION","enqueue","hasPending","clearQueues","queue"],"sources":["../../../src/internal/queue.ts"],"sourcesContent":["import { CLEAN, FLAG_LANE, FLAG_PARKED, FLAG_QUEUED, FLAG_RENDER, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { rt } from \"./state\";\n\n/** Urgent effects waiting for the next flush, split by phase (render effects run first). */\nexport const renderQueue: Computation[] = [];\nexport const userQueue: Computation[] = [];\n\n/**\n * Puts an effect where it belongs. `lane` says the write that marked it was a transition write;\n * effects with FLAG_LANE always go to the lane. Lane and paused effects are handed to the transition\n * hooks (their queues live there); everything else is queued here, with no hook involved.\n */\nexport function place(effect: Computation, lane: boolean): void {\n if ((effect.flags & FLAG_QUEUED) !== 0) return;\n const inLane = lane || (effect.flags & FLAG_LANE) !== 0;\n const hooks = rt.hooks;\n if (hooks !== null && (inLane || effect.pauses > 0)) {\n hooks.place(effect, inLane);\n return;\n }\n effect.flags = (effect.flags & ~(FLAG_PARKED | FLAG_TRANSITION)) | FLAG_QUEUED;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n}\n\n/** Queues an effect for the current write: a transition write joins the lane. */\nexport function enqueue(effect: Computation): void {\n place(effect, rt.inTransition);\n}\n\n/** True when an urgent effect is waiting. */\nexport function hasPending(): boolean {\n return renderQueue.length > 0 || userQueue.length > 0;\n}\n\n/** Drops everything queued (used when a flush is aborted by the loop guard). */\nexport function clearQueues(): void {\n for (const queue of [renderQueue, userQueue]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n // Back to CLEAN so the next write can notify (and re-queue) this effect again.\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n rt.hooks?.clear();\n}\n"],"mappings":"A,8FAKA,MAAaA,EAA6B,CAAC,EAC9BC,EAA2B,CAAC,EAOzC,SAAgBC,EAAM,EAAqB,EAAqB,CAC9D,GAAKC,EAAO,MAAA,EAA4B,OACxC,IAAMC,EAASC,GAAA,GAASF,EAAO,MAAA,KACzBG,EAAQC,EAAG,MACbD,IAAU,OAASF,GAAUD,EAAO,OAAS,GAC/CG,EAAM,MAAMH,EAAQC,CAAM,GAG5B,EAAO,MAASD,EAAO,MAAQ,EAAEK,EAAcC,GAAA,EAC1CN,EAAO,MAAA,GAA4BH,EAAY,KAAKG,CAAM,EAC1DF,EAAU,KAAKE,CAAM,EAC5B,CAGA,SAAgBO,EAAQ,EAA2B,CACjDR,EAAMC,EAAQI,EAAG,YAAY,CAC/B,CAGA,SAAgBI,GAAsB,CACpC,OAAOX,EAAY,OAAS,GAAKC,EAAU,OAAS,CACtD,CAGA,SAAgBW,GAAoB,CAClC,IAAK,IAAMC,IAAS,CAACb,EAAaC,CAAS,EAAG,CAC5C,IAAK,IAAME,KAAUU,EACnB,EAAO,OAAS,EAAA,EAAgBJ,GAEhC,EAAO,MAAA,EAET,EAAM,OAAS,CACjB,CACAF,EAAG,OAAO,MAAM,CAClB,C"}
@@ -0,0 +1,2 @@
1
+ import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_TRANSITION as n}from"./flags.js";import{rt as r}from"./state.js";import{handleError as i}from"./owner.js";import{clearQueues as a,hasPending as o,renderQueue as s,userQueue as c}from"./queue.js";import{recompute as l,updateIfNecessary as u}from"./graph.js";const d=1e3;let f=!1;function p(e,t){return e.depth-t.depth||e.seq-t.seq}function m(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n!==void 0&&r!==void 0&&p(n,r)>0)return!1}return!0}function h(e){let r=e.splice(0,e.length);m(r)||r.sort(p);for(let e of r)if(e.flags&=-3,!(e.flags&4)){if(e.pauses>0)e.flags=e.flags&~n|t;else try{e.state===2?l(e):u(e)}catch(t){i(t,e)}}return r.length}function g(e){let[t]=e;throw e.length===1?t:AggregateError(e,`SHADOW_FLUSH_ERRORS`)}function _(){if(r.flushing)return;r.flushing=!0;let t=0,n=0;try{for(;o();){let i=!1;for(;s.length>0;){if(t+=1,t>1e3){i=!0;break}n+=h(s)}if(!i&&c.length>0&&(t+=1,t>1e3?i=!0:n+=h(c)),i){a(),r.uncaught.push(new e(`INFINITE_LOOP`));break}}}finally{r.flushing=!1}let i=r.uncaught;i.length>0&&(r.uncaught=[],g(i))}function v(e){typeof reportError==`function`?reportError(e):queueMicrotask(()=>Promise.reject(e))}function y(){if(f=!1,o())try{_()}catch(e){v(e)}}function b(){r.inTransition||r.batchDepth>0||r.flushing||f||(f=!0,queueMicrotask(y))}function x(e){r.batchDepth+=1;try{return e()}finally{--r.batchDepth,r.batchDepth===0&&o()&&b()}}function S(e,t){return AggregateError([e,t],`SHADOW_BATCH_ERRORS`)}function C(e){r.batchDepth+=1;let t,n,i=!1;try{t=e()}catch(e){i=!0,n=e}finally{--r.batchDepth}if(r.batchDepth===0&&!r.flushing&&o())try{_()}catch(e){throw i?S(n,e):e}if(i)throw n;return t}function w(e){if(r.flushing)return e===void 0?void 0:e();r.batchDepth+=1;let t,n,i=!1;try{t=e===void 0?void 0:e()}catch(e){i=!0,n=e}finally{--r.batchDepth}try{_()}catch(e){throw i?S(n,e):e}if(i)throw n;return t}export{d as MAX_FLUSH_PASSES,C as batch,p as byCreation,_ as flush,w as flushSync,x as group,m as isOrdered,v as reportUncaught,b as schedule};
2
+ //# sourceMappingURL=scheduler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scheduler.js","names":["MAX_FLUSH_PASSES","microtaskScheduled","byCreation","a","b","isOrdered","i","list","previous","current","drain","batch","queue","effect","FLAG_TRANSITION","FLAG_PARKED","recompute","updateIfNecessary","error","handleError","raise","first","errors","flush","rt","passes","runs","hasPending","aborted","renderQueue","userQueue","clearQueues","ShadowError","reportUncaught","runScheduled","schedule","group","fn","combine","primary","secondary","result","failure","failed","flushSync"],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/**\n * Effects mostly arrive in creation order already; checking is O(n), sorting is not.\n * @internal\n */\nexport function isOrdered(list: readonly Computation[]): boolean {\n for (let i = 1; i < list.length; i += 1) {\n const previous = list[i - 1];\n const current = list[i];\n if (previous !== undefined && current !== undefined && byCreation(previous, current) > 0) {\n return false;\n }\n }\n return true;\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n if (!isOrdered(batch)) batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n try {\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n let aborted = false;\n // Render passes count too: a render effect that keeps writing its own source must abort.\n while (renderQueue.length > 0) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n aborted = true;\n break;\n }\n runs += drain(renderQueue);\n }\n if (!aborted && userQueue.length > 0) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) aborted = true;\n else runs += drain(userQueue);\n }\n if (aborted) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batchDepth > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batchDepth += 1;\n try {\n return fn();\n } finally {\n rt.batchDepth -= 1;\n if (rt.batchDepth === 0 && hasPending()) schedule();\n }\n}\n\nfunction combine(primary: unknown, secondary: unknown): unknown {\n return new AggregateError(\n [primary, secondary],\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n if (rt.batchDepth === 0 && !rt.flushing && hasPending()) {\n try {\n flush();\n } catch (error) {\n if (failed) throw combine(failure, error);\n throw error;\n }\n }\n if (failed) throw failure;\n return result as T;\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n try {\n flush();\n } catch (error) {\n if (failed) throw combine(failure, error);\n throw error;\n }\n if (failed) throw failure;\n return result as T;\n}\n"],"mappings":"A,6UAaA,MAAaA,EAAmB,IAEhC,IAAIC,EAAqB,GAMzB,SAAgBC,EAAW,EAAgB,EAAwB,CACjE,OAAOC,EAAE,MAAQC,EAAE,OAASD,EAAE,IAAMC,EAAE,GACxC,CAMA,SAAgBC,EAAU,EAAuC,CAC/D,IAAK,IAAIC,EAAI,EAAGA,EAAIC,EAAK,OAAQ,GAAK,EAAG,CACvC,IAAMC,EAAWD,EAAKD,EAAI,GACpBG,EAAUF,EAAKD,GACrB,GAAIE,IAAa,I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U,CACR,IAAG,UACL,CACA,GAAI,CACFK,EAAM,CACR,OAASL,EAAO,CAEd,MADIyB,EAAcL,EAAQI,EAASxB,CAAK,EAClCA,CACR,CACA,GAAIyB,EAAQ,MAAMD,EAClB,OAAOD,CACT,C"}
@@ -0,0 +1,2 @@
1
+ const e={owner:null,listener:null,running:null,batchDepth:0,flushing:!1,recomputeDepth:0,disposing:0,uncaught:[],inTransition:!1,hydrating:!1,hooks:null};let t=0;function n(){return t+=1,t}export{n as nextSequence,e as rt};
2
+ //# sourceMappingURL=state.js.map