@shadow-js/core 1.0.0 → 1.0.2

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 (240) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/dev/action.d.ts +0 -2
  3. package/dist/dev/action.js +1 -2
  4. package/dist/dev/cache.d.ts +2 -3
  5. package/dist/dev/cache.js +6 -5
  6. package/dist/dev/cache.js.map +1 -1
  7. package/dist/dev/context.d.ts +0 -2
  8. package/dist/dev/context.js +1 -2
  9. package/dist/dev/effect.d.ts +0 -2
  10. package/dist/dev/effect.js +18 -35
  11. package/dist/dev/effect.js.map +1 -1
  12. package/dist/dev/env.d.ts +0 -2
  13. package/dist/dev/env.js +1 -2
  14. package/dist/dev/events.d.ts +0 -2
  15. package/dist/dev/events.js +1 -2
  16. package/dist/dev/extend/index.d.ts +7 -8
  17. package/dist/dev/extend/index.js +8 -9
  18. package/dist/dev/extend/index.js.map +1 -1
  19. package/dist/dev/external-store.d.ts +0 -2
  20. package/dist/dev/external-store.js +9 -5
  21. package/dist/dev/external-store.js.map +1 -1
  22. package/dist/dev/internal/concurrency.d.ts +0 -2
  23. package/dist/dev/internal/concurrency.js +43 -22
  24. package/dist/dev/internal/concurrency.js.map +1 -1
  25. package/dist/dev/internal/devtools.d.ts +0 -2
  26. package/dist/dev/internal/devtools.js +1 -2
  27. package/dist/dev/internal/diagnostics.d.ts +0 -2
  28. package/dist/dev/internal/diagnostics.js +1 -4
  29. package/dist/dev/internal/diagnostics.js.map +1 -1
  30. package/dist/dev/internal/dispose.d.ts +0 -2
  31. package/dist/dev/internal/dispose.js +1 -2
  32. package/dist/dev/internal/flags.js +2 -5
  33. package/dist/dev/internal/flags.js.map +1 -1
  34. package/dist/dev/internal/graph.d.ts +0 -3
  35. package/dist/dev/internal/graph.js +21 -39
  36. package/dist/dev/internal/graph.js.map +1 -1
  37. package/dist/dev/internal/hydration-flag.d.ts +0 -2
  38. package/dist/dev/internal/hydration-flag.js +1 -2
  39. package/dist/dev/internal/messages.d.ts +0 -2
  40. package/dist/dev/internal/messages.js +1 -2
  41. package/dist/dev/internal/owner.d.ts +7 -7
  42. package/dist/dev/internal/owner.js +13 -24
  43. package/dist/dev/internal/owner.js.map +1 -1
  44. package/dist/dev/internal/queue.js +1 -2
  45. package/dist/dev/internal/scheduler.d.ts +0 -2
  46. package/dist/dev/internal/scheduler.js +34 -73
  47. package/dist/dev/internal/scheduler.js.map +1 -1
  48. package/dist/dev/internal/state.d.ts +0 -2
  49. package/dist/dev/internal/state.js +1 -2
  50. package/dist/dev/internal/suspension.d.ts +0 -2
  51. package/dist/dev/internal/suspension.js +1 -2
  52. package/dist/dev/internal/types.d.ts +0 -2
  53. package/dist/dev/list.d.ts +0 -2
  54. package/dist/dev/list.js +1 -10
  55. package/dist/dev/list.js.map +1 -1
  56. package/dist/dev/memo.d.ts +2 -3
  57. package/dist/dev/memo.js +5 -6
  58. package/dist/dev/memo.js.map +1 -1
  59. package/dist/dev/optimistic.d.ts +0 -2
  60. package/dist/dev/optimistic.js +1 -2
  61. package/dist/dev/ownership.d.ts +4 -4
  62. package/dist/dev/ownership.js +60 -5
  63. package/dist/dev/ownership.js.map +1 -1
  64. package/dist/dev/props.d.ts +0 -2
  65. package/dist/dev/props.js +19 -13
  66. package/dist/dev/props.js.map +1 -1
  67. package/dist/dev/reaction.d.ts +1 -3
  68. package/dist/dev/reaction.js +6 -3
  69. package/dist/dev/reaction.js.map +1 -1
  70. package/dist/dev/reducer.d.ts +0 -2
  71. package/dist/dev/reducer.js +2 -3
  72. package/dist/dev/reducer.js.map +1 -1
  73. package/dist/dev/refs.d.ts +0 -2
  74. package/dist/dev/refs.js +1 -2
  75. package/dist/dev/resource.d.ts +0 -2
  76. package/dist/dev/resource.js +22 -14
  77. package/dist/dev/resource.js.map +1 -1
  78. package/dist/dev/selector.d.ts +0 -2
  79. package/dist/dev/selector.js +2 -7
  80. package/dist/dev/selector.js.map +1 -1
  81. package/dist/dev/signal.d.ts +3 -4
  82. package/dist/dev/signal.js +1 -2
  83. package/dist/dev/signal.js.map +1 -1
  84. package/dist/dev/store/nodes.js +7 -2
  85. package/dist/dev/store/nodes.js.map +1 -1
  86. package/dist/dev/store/proxies.js +1 -2
  87. package/dist/dev/store/read.d.ts +0 -2
  88. package/dist/dev/store/read.js +1 -2
  89. package/dist/dev/store/reconcile.d.ts +0 -2
  90. package/dist/dev/store/reconcile.js +1 -2
  91. package/dist/dev/store/types.d.ts +0 -2
  92. package/dist/dev/store/use-store.d.ts +5 -2
  93. package/dist/dev/store/use-store.js +1 -2
  94. package/dist/dev/store/use-store.js.map +1 -1
  95. package/dist/dev/suspense.d.ts +0 -2
  96. package/dist/dev/suspense.js +1 -2
  97. package/dist/dev/transitions.d.ts +0 -2
  98. package/dist/dev/transitions.js +2 -3
  99. package/dist/dev/transitions.js.map +1 -1
  100. package/dist/prod/cache.js +1 -1
  101. package/dist/prod/cache.js.map +1 -1
  102. package/dist/prod/effect.js +1 -1
  103. package/dist/prod/effect.js.map +1 -1
  104. package/dist/prod/extend/index.js +1 -1
  105. package/dist/prod/extend/index.js.map +1 -1
  106. package/dist/prod/external-store.js +1 -1
  107. package/dist/prod/external-store.js.map +1 -1
  108. package/dist/prod/internal/concurrency.js +1 -1
  109. package/dist/prod/internal/concurrency.js.map +1 -1
  110. package/dist/prod/internal/diagnostics.js +1 -1
  111. package/dist/prod/internal/diagnostics.js.map +1 -1
  112. package/dist/prod/internal/flags.js +1 -1
  113. package/dist/prod/internal/flags.js.map +1 -1
  114. package/dist/prod/internal/graph.js +1 -1
  115. package/dist/prod/internal/graph.js.map +1 -1
  116. package/dist/prod/internal/owner.js +1 -1
  117. package/dist/prod/internal/owner.js.map +1 -1
  118. package/dist/prod/internal/scheduler.js +1 -1
  119. package/dist/prod/internal/scheduler.js.map +1 -1
  120. package/dist/prod/list.js +1 -1
  121. package/dist/prod/list.js.map +1 -1
  122. package/dist/prod/memo.js +1 -1
  123. package/dist/prod/memo.js.map +1 -1
  124. package/dist/prod/ownership.js +1 -1
  125. package/dist/prod/ownership.js.map +1 -1
  126. package/dist/prod/props.js.map +1 -1
  127. package/dist/prod/reaction.js +1 -1
  128. package/dist/prod/reaction.js.map +1 -1
  129. package/dist/prod/reducer.js +1 -1
  130. package/dist/prod/reducer.js.map +1 -1
  131. package/dist/prod/resource.js +1 -1
  132. package/dist/prod/resource.js.map +1 -1
  133. package/dist/prod/selector.js +1 -1
  134. package/dist/prod/selector.js.map +1 -1
  135. package/dist/prod/signal.js.map +1 -1
  136. package/dist/prod/store/nodes.js +1 -1
  137. package/dist/prod/store/nodes.js.map +1 -1
  138. package/dist/prod/store/use-store.js.map +1 -1
  139. package/dist/prod/transitions.js +1 -1
  140. package/dist/prod/transitions.js.map +1 -1
  141. package/dist/server/cache.js +1 -1
  142. package/dist/server/cache.js.map +1 -1
  143. package/dist/server/effect.js.map +1 -1
  144. package/dist/server/extend/index.js +1 -1
  145. package/dist/server/extend/index.js.map +1 -1
  146. package/dist/server/external-store.js.map +1 -1
  147. package/dist/server/internal/concurrency.js +1 -1
  148. package/dist/server/internal/concurrency.js.map +1 -1
  149. package/dist/server/internal/diagnostics.js +1 -1
  150. package/dist/server/internal/diagnostics.js.map +1 -1
  151. package/dist/server/internal/flags.js +1 -1
  152. package/dist/server/internal/flags.js.map +1 -1
  153. package/dist/server/internal/graph.js +1 -1
  154. package/dist/server/internal/graph.js.map +1 -1
  155. package/dist/server/internal/owner.js +1 -1
  156. package/dist/server/internal/owner.js.map +1 -1
  157. package/dist/server/internal/scheduler.js +1 -1
  158. package/dist/server/internal/scheduler.js.map +1 -1
  159. package/dist/server/list.js +1 -1
  160. package/dist/server/list.js.map +1 -1
  161. package/dist/server/memo.js +1 -1
  162. package/dist/server/memo.js.map +1 -1
  163. package/dist/server/ownership.js +1 -1
  164. package/dist/server/ownership.js.map +1 -1
  165. package/dist/server/props.js.map +1 -1
  166. package/dist/server/reaction.js +1 -1
  167. package/dist/server/reaction.js.map +1 -1
  168. package/dist/server/reducer.js +1 -1
  169. package/dist/server/reducer.js.map +1 -1
  170. package/dist/server/resource.js +1 -1
  171. package/dist/server/resource.js.map +1 -1
  172. package/dist/server/selector.js +1 -1
  173. package/dist/server/selector.js.map +1 -1
  174. package/dist/server/signal.js.map +1 -1
  175. package/dist/server/store/nodes.js +1 -1
  176. package/dist/server/store/nodes.js.map +1 -1
  177. package/dist/server/store/use-store.js.map +1 -1
  178. package/dist/server/transitions.js.map +1 -1
  179. package/dist/server-dev/action.js +1 -2
  180. package/dist/server-dev/cache.js +6 -5
  181. package/dist/server-dev/cache.js.map +1 -1
  182. package/dist/server-dev/context.js +1 -2
  183. package/dist/server-dev/effect.js +1 -2
  184. package/dist/server-dev/effect.js.map +1 -1
  185. package/dist/server-dev/env.js +1 -2
  186. package/dist/server-dev/events.js +1 -2
  187. package/dist/server-dev/extend/index.js +8 -9
  188. package/dist/server-dev/extend/index.js.map +1 -1
  189. package/dist/server-dev/external-store.js +1 -2
  190. package/dist/server-dev/external-store.js.map +1 -1
  191. package/dist/server-dev/internal/concurrency.js +43 -22
  192. package/dist/server-dev/internal/concurrency.js.map +1 -1
  193. package/dist/server-dev/internal/devtools.js +1 -2
  194. package/dist/server-dev/internal/diagnostics.js +1 -4
  195. package/dist/server-dev/internal/diagnostics.js.map +1 -1
  196. package/dist/server-dev/internal/dispose.js +1 -2
  197. package/dist/server-dev/internal/flags.js +2 -5
  198. package/dist/server-dev/internal/flags.js.map +1 -1
  199. package/dist/server-dev/internal/graph.js +21 -39
  200. package/dist/server-dev/internal/graph.js.map +1 -1
  201. package/dist/server-dev/internal/hydration-flag.js +1 -2
  202. package/dist/server-dev/internal/messages.js +1 -2
  203. package/dist/server-dev/internal/owner.js +13 -24
  204. package/dist/server-dev/internal/owner.js.map +1 -1
  205. package/dist/server-dev/internal/queue.js +1 -2
  206. package/dist/server-dev/internal/scheduler.js +34 -73
  207. package/dist/server-dev/internal/scheduler.js.map +1 -1
  208. package/dist/server-dev/internal/state.js +1 -2
  209. package/dist/server-dev/internal/suspension.js +1 -2
  210. package/dist/server-dev/list.js +1 -10
  211. package/dist/server-dev/list.js.map +1 -1
  212. package/dist/server-dev/memo.js +5 -6
  213. package/dist/server-dev/memo.js.map +1 -1
  214. package/dist/server-dev/optimistic.js +1 -2
  215. package/dist/server-dev/ownership.js +60 -5
  216. package/dist/server-dev/ownership.js.map +1 -1
  217. package/dist/server-dev/props.js +19 -13
  218. package/dist/server-dev/props.js.map +1 -1
  219. package/dist/server-dev/reaction.js +6 -3
  220. package/dist/server-dev/reaction.js.map +1 -1
  221. package/dist/server-dev/reducer.js +2 -3
  222. package/dist/server-dev/reducer.js.map +1 -1
  223. package/dist/server-dev/refs.js +1 -2
  224. package/dist/server-dev/resource.js +22 -14
  225. package/dist/server-dev/resource.js.map +1 -1
  226. package/dist/server-dev/selector.js +2 -7
  227. package/dist/server-dev/selector.js.map +1 -1
  228. package/dist/server-dev/signal.js +1 -2
  229. package/dist/server-dev/signal.js.map +1 -1
  230. package/dist/server-dev/store/nodes.js +7 -2
  231. package/dist/server-dev/store/nodes.js.map +1 -1
  232. package/dist/server-dev/store/proxies.js +1 -2
  233. package/dist/server-dev/store/read.js +1 -2
  234. package/dist/server-dev/store/reconcile.js +1 -2
  235. package/dist/server-dev/store/use-store.js +1 -2
  236. package/dist/server-dev/store/use-store.js.map +1 -1
  237. package/dist/server-dev/suspense.js +1 -2
  238. package/dist/server-dev/transitions.js +1 -2
  239. package/dist/server-dev/transitions.js.map +1 -1
  240. package/package.json +2 -1
@@ -1,6 +1,6 @@
1
1
  import { untrack } from "./ownership.js";
2
2
  import { useMemo } from "./memo.js";
3
- //#region src/props.ts
3
+ // src/props.ts
4
4
  /**
5
5
  * Keys that never take part in a merge or a split. Reading them through a props object that came
6
6
  * from JSON or from user input could reach `Object.prototype`, so they are skipped everywhere.
@@ -74,17 +74,19 @@ function mergedKeys(objects) {
74
74
  return keys;
75
75
  }
76
76
  /**
77
- * A Proxy whose key set and values are recomputed on every access: `load` runs once per trap, so
78
- * a function source is called once per access. The target is an ordinary object, so prototype
79
- * lookups keep their usual meaning, and every write is refused because props are read-only.
80
- */
81
- /**
82
- * How deep the live reads are running, and the state each live view computed during the outermost
83
- * read. A view's traps read the views beneath it, and those read the views beneath them: without a
84
- * cache every trap recomputes each level below, and a few nested components (a chain of `{...props}`
85
- * forwards) take exponential time. Within one outermost read a view's state is computed once, so a
86
- * read costs time linear in the number of views. The cache is dropped when that read returns, so each
87
- * read still sees the current values.
77
+ * The cache of the live views: `readDepth` counts how deep the live reads are running and
78
+ * `readStates` holds the state each live view computed during the outermost read. A view's traps
79
+ * read the views beneath them, and those read the views beneath them: without a cache every trap
80
+ * recomputes each level below, and a few nested components (a chain of `{...props}` forwards) take
81
+ * exponential time. Within one outermost read a view's state is computed once, so a read costs time
82
+ * linear in the number of views. The cache is dropped when that read returns, so each read still
83
+ * sees the current values.
84
+ *
85
+ * These two are module-level scratch state (R-CODE-4, the scratch-array class), and not registers
86
+ * of `internal/state.ts`: this file may import only the public extension API (EXT-01), which has no
87
+ * place for them, and a new public export for two private counters is not worth it. They are safe
88
+ * because every write is undone in `finally` (`duringRead`), so a getter that throws leaves depth 0
89
+ * and an empty map, and because the map holds a view only while one outermost read is running.
88
90
  */
89
91
  let readDepth = 0;
90
92
  const readStates = /* @__PURE__ */ new Map();
@@ -104,6 +106,11 @@ function duringRead(run) {
104
106
  if (readDepth === 0) readStates.clear();
105
107
  }
106
108
  }
109
+ /**
110
+ * A Proxy whose key set and values are recomputed on every access: `load` runs once per trap, so
111
+ * a function source is called once per access. The target is an ordinary object, so prototype
112
+ * lookups keep their usual meaning, and every write is refused because props are read-only.
113
+ */
107
114
  function liveView(load) {
108
115
  const target = {};
109
116
  return new Proxy(target, {
@@ -276,7 +283,6 @@ function children(fn) {
276
283
  }
277
284
  });
278
285
  }
279
- //#endregion
280
286
  export { children, mergeProps, splitProps };
281
287
 
282
288
  //# sourceMappingURL=props.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"props.js","names":[],"sources":["../../src/props.ts"],"sourcesContent":["import { useMemo } from \"./memo\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Keys that never take part in a merge or a split. Reading them through a props object that came\n * from JSON or from user input could reach `Object.prototype`, so they are skipped everywhere.\n */\nconst UNSAFE_KEYS: ReadonlySet<PropertyKey> = new Set<PropertyKey>([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Results of mergeProps (and splitProps over them) that have at least one function source. Their\n * key set can change between reads, so splitProps builds a live rest object for them. A WeakSet is\n * bounded by the garbage collector.\n */\nconst DYNAMIC_PROPS = new WeakSet<object>();\n\n/** Longest chain of nested accessors that children() follows before it gives up. */\nconst MAX_FUNCTION_LAYERS = 1000;\n\n/**\n * A value accepted by {@link mergeProps}: an object, a function that returns one (called at every\n * read, so it can be reactive), or `null`, `undefined` or `false`, which are skipped. Use it to type\n * a helper that collects sources before merging them.\n * @since 1.0.0\n */\nexport type MergeSource = object | null | undefined | false;\n\n/** The props object a source stands for; functions contribute their return type. */\ntype PropsOf<S> = S extends (...args: never[]) => infer R\n ? Exclude<R, null | undefined | false>\n : S extends null | undefined | false\n ? object\n : S;\n\n/** Later keys replace earlier ones; a later key that may be `undefined` keeps the earlier type too. */\ntype Overlay<A, B> = {\n [K in keyof A | keyof B]: K extends keyof B\n ? K extends keyof A\n ? undefined extends B[K]\n ? Exclude<B[K], undefined> | A[K]\n : B[K]\n : B[K]\n : K extends keyof A\n ? A[K]\n : never;\n};\n\n/**\n * The type of `mergeProps(...sources)`, folded left to right: a later source's key replaces an\n * earlier one, and a later key that may be `undefined` keeps the earlier type as well.\n * @since 1.0.0\n */\nexport type MergeProps<T extends readonly unknown[], Acc = object> = T extends readonly [\n infer Head,\n ...infer Rest,\n]\n ? MergeProps<Rest, Overlay<Acc, PropsOf<Head>>>\n : Acc;\n\n/**\n * The type of `splitProps(props, ...keyLists)`: one object per key list, picking those keys, then\n * the rest without any listed key.\n * @since 1.0.0\n */\nexport type SplitProps<T extends object, K extends readonly (readonly (keyof T)[])[]> = [\n ...{ [I in keyof K]: Pick<T, Extract<K[I][number], keyof T>> },\n Omit<T, K[number][number]>,\n];\n\n/**\n * The value returned by {@link children}: calling it yields one leaf, an array of several leaves,\n * or `undefined` for none; `toArray()` always returns an array. The methods mirror React's\n * `Children` helpers.\n * @since 1.0.0\n */\nexport interface ResolvedChildren {\n /**\n * The current children: one leaf, an array of several leaves, or `undefined` when there is none.\n * The read is tracked like a memo read.\n */\n (): unknown;\n /** A fresh array of the leaves, without `null`, `undefined` or booleans. */\n toArray(): unknown[];\n /** Number of leaves, zero or more (the React `Children.count`). */\n count(): number;\n /** Maps each leaf with its index; the callback runs untracked (React `Children.map`). */\n map<U>(fn: (leaf: unknown, index: number) => U): U[];\n /** Visits each leaf with its index; the callback runs untracked (React `Children.forEach`). */\n forEach(fn: (leaf: unknown, index: number) => void): void;\n /**\n * The single leaf (React `Children.only`). Throws a TypeError (production message\n * `SHADOW_CHILDREN_ONLY`) when there is not exactly one leaf.\n */\n only(): unknown;\n}\n\n/** Whether a source stands for nothing and is skipped. */\nfunction isEmptySource(value: unknown): value is null | undefined | false {\n return value === null || value === undefined || value === false;\n}\n\n/** Own enumerable string and symbol keys, minus the unsafe ones. Reads no getter. */\nfunction ownEnumerableKeys(source: object): Key[] {\n return Reflect.ownKeys(source).filter(\n (key) => !UNSAFE_KEYS.has(key) && Object.prototype.propertyIsEnumerable.call(source, key),\n );\n}\n\n/** Defines an enumerable getter; the target is a fresh object, so this never hits a setter. */\nfunction defineGetter(target: object, key: PropertyKey, read: () => unknown): void {\n Object.defineProperty(target, key, { enumerable: true, configurable: true, get: read });\n}\n\n/** The object a source stands for at this moment, or `undefined` when it is skipped. */\nfunction resolveSource(source: object): object | undefined {\n const value: unknown = typeof source === \"function\" ? (source as () => unknown)() : source;\n if (isEmptySource(value)) return undefined;\n if (typeof value === \"object\" && value !== null) return value;\n throw new TypeError(\n __DEV__\n ? \"mergeProps: a source function must return an object, null, undefined or false\"\n : \"SHADOW_MERGE_SOURCE\",\n );\n}\n\n/** The sources that stand for an object right now, in order; skipped ones are dropped. */\nfunction resolveAll(sources: readonly object[]): object[] {\n const resolved: object[] = [];\n for (const source of sources) {\n const object = resolveSource(source);\n if (object !== undefined) resolved.push(object);\n }\n return resolved;\n}\n\n/**\n * Reads one merged key: the right-most object that has the key and a value other than `undefined`\n * wins. Each getter is read at most once.\n */\nfunction readMerged(objects: readonly object[], key: Key): unknown {\n for (let index = objects.length - 1; index >= 0; index -= 1) {\n const source = objects[index];\n if (source === undefined || !(key in source)) continue;\n const value: unknown = Reflect.get(source, key);\n if (value !== undefined) return value;\n }\n return undefined;\n}\n\n/** Every merged key in first-occurrence order. Reads no getter. */\nfunction mergedKeys(objects: readonly object[]): Key[] {\n const seen = new Set<Key>();\n const keys: Key[] = [];\n for (const source of objects) {\n for (const key of ownEnumerableKeys(source)) {\n if (seen.has(key)) continue;\n seen.add(key);\n keys.push(key);\n }\n }\n return keys;\n}\n\n/** A property name as a Proxy trap sees it. */\ntype Key = string | symbol;\n\n/** The key set and the reader that a live view uses for one access. */\ninterface LiveState {\n readonly keys: ReadonlySet<Key>;\n read(key: Key): unknown;\n}\n\n/**\n * A Proxy whose key set and values are recomputed on every access: `load` runs once per trap, so\n * a function source is called once per access. The target is an ordinary object, so prototype\n * lookups keep their usual meaning, and every write is refused because props are read-only.\n */\n/**\n * How deep the live reads are running, and the state each live view computed during the outermost\n * read. A view's traps read the views beneath it, and those read the views beneath them: without a\n * cache every trap recomputes each level below, and a few nested components (a chain of `{...props}`\n * forwards) take exponential time. Within one outermost read a view's state is computed once, so a\n * read costs time linear in the number of views. The cache is dropped when that read returns, so each\n * read still sees the current values.\n */\nlet readDepth = 0;\nconst readStates = new Map<object, LiveState>();\n\nfunction stateOf(view: object, load: () => LiveState): LiveState {\n const known = readStates.get(view);\n if (known !== undefined) return known;\n const state = load();\n readStates.set(view, state);\n return state;\n}\n\nfunction duringRead<T>(run: () => T): T {\n readDepth += 1;\n try {\n return run();\n } finally {\n readDepth -= 1;\n if (readDepth === 0) readStates.clear();\n }\n}\n\nfunction liveView(load: () => LiveState): object {\n const target: object = {};\n return new Proxy(target, {\n get(_target, key) {\n return duringRead(() => {\n const state = stateOf(target, load);\n return state.keys.has(key) ? state.read(key) : (Reflect.get(target, key) as unknown);\n });\n },\n has(_target, key) {\n return duringRead(() => stateOf(target, load).keys.has(key) || Reflect.has(target, key));\n },\n ownKeys() {\n return duringRead(() => [...stateOf(target, load).keys]);\n },\n getOwnPropertyDescriptor(_target, key) {\n return duringRead(() => {\n if (!stateOf(target, load).keys.has(key)) return undefined;\n return {\n enumerable: true,\n configurable: true,\n get: () => duringRead(() => stateOf(target, load).read(key)),\n };\n });\n },\n set: () => false,\n defineProperty: () => false,\n deleteProperty: () => false,\n });\n}\n\n/**\n * Merges props objects into one getter-preserving object. Reading a key returns the value from the\n * right-most source that has it, unless that value is `undefined`, in which case the next source\n * to the left is tried. Nothing is copied at merge time, so reads stay reactive. Use it to give\n * component props defaults without reading them in the component body.\n *\n * Sources may be objects, `null`, `undefined` or `false` (skipped), or functions that return an\n * object. A function is called on every read, which is how spreads such as `{...props()}` stay\n * reactive. Keys named `__proto__`, `constructor` or `prototype` are ignored.\n *\n * @param sources The props objects, from lowest to highest priority.\n * @returns A read-only object whose keys are the union of the sources' own enumerable keys. With a\n * function source, the key set is recomputed on every access.\n * @throws TypeError (production message `SHADOW_MERGE_SOURCES`) when a source is not an object, a\n * function, `null`, `undefined` or `false`. A read of the result throws TypeError (production\n * message `SHADOW_MERGE_SOURCE`) when a function source returns anything else.\n * @example\n * import { mergeProps } from \"@shadow-js/core\";\n *\n * function Button(props: { size?: \"sm\" | \"md\"; label: string }) {\n * const merged = mergeProps({ size: \"md\" as const }, props);\n * return <button class={`btn-${merged.size}`}>{merged.label}</button>;\n * }\n * @see splitProps\n * @since 1.0.0\n */\nexport function mergeProps<T extends readonly MergeSource[]>(...sources: T): MergeProps<T>;\nexport function mergeProps(...sources: readonly MergeSource[]): object {\n const inputs: object[] = [];\n let dynamic = false;\n for (const source of sources) {\n if (isEmptySource(source)) continue;\n if (typeof source === \"function\") {\n dynamic = true;\n } else if (typeof source !== \"object\") {\n throw new TypeError(\n __DEV__\n ? \"mergeProps: sources must be objects, functions, or null, undefined or false\"\n : \"SHADOW_MERGE_SOURCES\",\n );\n }\n inputs.push(source);\n }\n if (!dynamic) {\n const objects = resolveAll(inputs);\n const merged: object = {};\n for (const key of mergedKeys(objects)) {\n defineGetter(merged, key, () => readMerged(objects, key));\n }\n return merged;\n }\n const view = liveView(() => {\n const objects = resolveAll(inputs);\n return { keys: new Set(mergedKeys(objects)), read: (key) => readMerged(objects, key) };\n });\n DYNAMIC_PROPS.add(view);\n return view;\n}\n\n/**\n * Splits props into one getter-preserving object per key list, followed by an object holding every\n * other key. Each group reads its keys from `props` at access time, so reactivity is preserved. A\n * key listed in two groups appears in both and never in the rest. A listed key that `props` does not\n * have is still present in its group, as `undefined`. Use it to separate the props a component\n * consumes from the ones it forwards to an element.\n *\n * @param props The props to split; plain objects, Proxies and {@link mergeProps} results work.\n * @param keys One or more key lists. Keys named `__proto__`, `constructor` or `prototype` are\n * ignored.\n * @returns `[...groups, rest]`, in the order the key lists were given.\n * @example\n * import { splitProps } from \"@shadow-js/core\";\n *\n * function Field(props: { label: string; value: string; placeholder?: string }) {\n * const [own, input] = splitProps(props, [\"label\"]);\n * return (\n * <label>\n * {own.label}\n * <input {...input} />\n * </label>\n * );\n * }\n * @see mergeProps\n * @since 1.0.0\n */\nexport function splitProps<T extends object, const K extends readonly (readonly (keyof T)[])[]>(\n props: T,\n ...keys: K\n): SplitProps<T, K>;\nexport function splitProps(props: object, ...keys: readonly (readonly PropertyKey[])[]): object[] {\n const listed = new Set<PropertyKey>();\n const groups: object[] = [];\n for (const group of keys) {\n const picked: object = {};\n for (const key of group) {\n if (UNSAFE_KEYS.has(key)) continue;\n listed.add(key);\n defineGetter(picked, key, () => Reflect.get(props, key) as unknown);\n }\n groups.push(picked);\n }\n const restKeys = (): Key[] => ownEnumerableKeys(props).filter((key) => !listed.has(key));\n const readRest = (key: Key): unknown => Reflect.get(props, key) as unknown;\n if (DYNAMIC_PROPS.has(props)) {\n const rest = liveView(() => ({ keys: new Set(restKeys()), read: readRest }));\n return [...groups, rest];\n }\n const rest: object = {};\n for (const key of restKeys()) defineGetter(rest, key, () => readRest(key));\n return [...groups, rest];\n}\n\n/** One level of a children walk: an array being read and the function-layer depth it sits at. */\ninterface Frame {\n readonly items: readonly unknown[];\n next: number;\n readonly layer: number;\n}\n\n/**\n * Resolves children without recursion: arrays flatten in order, accessors are called until a plain\n * value appears, and `null`, `undefined` and booleans are dropped. A cyclic array or more than\n * {@link MAX_FUNCTION_LAYERS} nested accessors is a TypeError.\n */\nfunction flattenChildren(fn: () => unknown): unknown[] {\n const leaves: unknown[] = [];\n const frames: Frame[] = [];\n const open = new Set<readonly unknown[]>();\n let value: unknown = fn;\n let layer = 0;\n for (;;) {\n if (typeof value === \"function\") {\n if (layer >= MAX_FUNCTION_LAYERS) {\n throw new TypeError(\n __DEV__\n ? `children(): more than ${MAX_FUNCTION_LAYERS} nested accessors; a function child may return itself`\n : \"SHADOW_CHILDREN_LAYERS\",\n );\n }\n value = (value as () => unknown)();\n layer += 1;\n continue;\n }\n if (Array.isArray(value)) {\n if (open.has(value))\n throw new TypeError(\n __DEV__ ? \"children(): an array contains itself\" : \"SHADOW_CHILDREN_CYCLE\",\n );\n open.add(value);\n frames.push({ items: value, next: 0, layer });\n } else if (value !== null && value !== undefined && typeof value !== \"boolean\") {\n leaves.push(value);\n }\n let advanced = false;\n while (!advanced) {\n const top = frames.at(-1);\n if (top === undefined) return leaves;\n if (top.next < top.items.length) {\n value = top.items[top.next];\n top.next += 1;\n layer = top.layer;\n advanced = true;\n } else {\n frames.pop();\n open.delete(top.items);\n }\n }\n }\n}\n\n/**\n * Memoizes a `props.children` getter so that it is read at most once per change of its\n * dependencies. Arrays are flattened, accessors are called, and `null`, `undefined` and booleans\n * are dropped. The memo is created in the current owner, so nodes created while resolving are\n * disposed with it. Use it when a component inspects or rearranges its children.\n *\n * @param fn The lazy children accessor, usually `() => props.children`.\n * @returns A {@link ResolvedChildren} accessor with `toArray()`, `count()`, `map()`, `forEach()`\n * and `only()`.\n * @throws TypeError from the returned accessor and its methods when the children contain an array\n * that contains itself (production message `SHADOW_CHILDREN_CYCLE`) or more than 1000 nested\n * accessors (`SHADOW_CHILDREN_LAYERS`). `only()` throws TypeError (`SHADOW_CHILDREN_ONLY`) unless\n * there is exactly one leaf.\n * @example\n * import { children } from \"@shadow-js/core\";\n *\n * function Steps(props: { children?: unknown }) {\n * const steps = children(() => props.children);\n * return (\n * <ol aria-label={`${steps.count()} steps`}>\n * {steps.map((step) => <li>{step as Node | string}</li>)}\n * </ol>\n * );\n * }\n * @since 1.0.0\n */\nexport function children(fn: () => unknown): ResolvedChildren {\n const memo = useMemo(() => flattenChildren(fn), { allowWrites: true });\n const accessor = (): unknown => {\n const leaves = memo();\n if (leaves.length === 1) return leaves[0];\n return leaves.length === 0 ? undefined : leaves;\n };\n return Object.assign(accessor, {\n toArray: (): unknown[] => [...memo()],\n count: (): number => memo().length,\n map: <U>(fn: (leaf: unknown, index: number) => U): U[] =>\n memo().map((leaf, index) => untrack(() => fn(leaf, index))),\n forEach: (fn: (leaf: unknown, index: number) => void): void => {\n memo().forEach((leaf, index) => {\n untrack(() => fn(leaf, index));\n });\n },\n only: (): unknown => {\n const leaves = memo();\n if (leaves.length !== 1) {\n throw new TypeError(\n __DEV__\n ? `children().only(): expected one child, received ${leaves.length}`\n : \"SHADOW_CHILDREN_ONLY\",\n );\n }\n return leaves[0];\n },\n });\n}\n"],"mappings":";;;;;;;AAOA,MAAM,8BAAwC,IAAI,IAAiB;CACjE;CACA;CACA;AACF,CAAC;;;;;;AAOD,MAAM,gCAAgB,IAAI,QAAgB;;AAG1C,MAAM,sBAAsB;;AAgF5B,SAAS,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,aAAa,KAAK,CAAC;CACrE,MAAM,iBAA0B;EAC9B,MAAM,SAAS,KAAK;EACpB,IAAI,OAAO,WAAW,GAAG,OAAO,OAAO;EACvC,OAAO,OAAO,WAAW,IAAI,KAAA,IAAY;CAC3C;CACA,OAAO,OAAO,OAAO,UAAU;EAC7B,eAA0B,CAAC,GAAG,KAAK,CAAC;EACpC,aAAqB,KAAK,CAAC,CAAC;EAC5B,MAAS,OACP,KAAK,CAAC,CAAC,KAAK,MAAM,UAAU,cAAc,GAAG,MAAM,KAAK,CAAC,CAAC;EAC5D,UAAU,OAAqD;GAC7D,KAAK,CAAC,CAAC,SAAS,MAAM,UAAU;IAC9B,cAAc,GAAG,MAAM,KAAK,CAAC;GAC/B,CAAC;EACH;EACA,YAAqB;GACnB,MAAM,SAAS,KAAK;GACpB,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,UAEJ,mDAAmD,OAAO,QAEhE;GAEF,OAAO,OAAO;EAChB;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"props.js","names":[],"sources":["../../src/props.ts"],"sourcesContent":["import { useMemo } from \"./memo\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Keys that never take part in a merge or a split. Reading them through a props object that came\n * from JSON or from user input could reach `Object.prototype`, so they are skipped everywhere.\n */\nconst UNSAFE_KEYS: ReadonlySet<PropertyKey> = new Set<PropertyKey>([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Results of mergeProps (and splitProps over them) that have at least one function source. Their\n * key set can change between reads, so splitProps builds a live rest object for them. A WeakSet is\n * bounded by the garbage collector.\n */\nconst DYNAMIC_PROPS = new WeakSet<object>();\n\n/** Longest chain of nested accessors that children() follows before it gives up. */\nconst MAX_FUNCTION_LAYERS = 1000;\n\n/**\n * A value accepted by {@link mergeProps}: an object, a function that returns one (called at every\n * read, so it can be reactive), or `null`, `undefined` or `false`, which are skipped. Use it to type\n * a helper that collects sources before merging them.\n * @since 1.0.0\n */\nexport type MergeSource = object | null | undefined | false;\n\n/** The props object a source stands for; functions contribute their return type. */\ntype PropsOf<S> = S extends (...args: never[]) => infer R\n ? Exclude<R, null | undefined | false>\n : S extends null | undefined | false\n ? object\n : S;\n\n/** Later keys replace earlier ones; a later key that may be `undefined` keeps the earlier type too. */\ntype Overlay<A, B> = {\n [K in keyof A | keyof B]: K extends keyof B\n ? K extends keyof A\n ? undefined extends B[K]\n ? Exclude<B[K], undefined> | A[K]\n : B[K]\n : B[K]\n : K extends keyof A\n ? A[K]\n : never;\n};\n\n/**\n * The type of `mergeProps(...sources)`, folded left to right: a later source's key replaces an\n * earlier one, and a later key that may be `undefined` keeps the earlier type as well.\n * @since 1.0.0\n */\nexport type MergeProps<T extends readonly unknown[], Acc = object> = T extends readonly [\n infer Head,\n ...infer Rest,\n]\n ? MergeProps<Rest, Overlay<Acc, PropsOf<Head>>>\n : Acc;\n\n/**\n * The type of `splitProps(props, ...keyLists)`: one object per key list, picking those keys, then\n * the rest without any listed key.\n * @since 1.0.0\n */\nexport type SplitProps<T extends object, K extends readonly (readonly (keyof T)[])[]> = [\n ...{ [I in keyof K]: Pick<T, Extract<K[I][number], keyof T>> },\n Omit<T, K[number][number]>,\n];\n\n/**\n * The value returned by {@link children}: calling it yields one leaf, an array of several leaves,\n * or `undefined` for none; `toArray()` always returns an array. The methods mirror React's\n * `Children` helpers.\n * @since 1.0.0\n */\nexport interface ResolvedChildren {\n /**\n * The current children: one leaf, an array of several leaves, or `undefined` when there is none.\n * The read is tracked like a memo read.\n */\n (): unknown;\n /** A fresh array of the leaves, without `null`, `undefined` or booleans. */\n toArray(): unknown[];\n /** Number of leaves, zero or more (the React `Children.count`). */\n count(): number;\n /** Maps each leaf with its index; the callback runs untracked (React `Children.map`). */\n map<U>(fn: (leaf: unknown, index: number) => U): U[];\n /** Visits each leaf with its index; the callback runs untracked (React `Children.forEach`). */\n forEach(fn: (leaf: unknown, index: number) => void): void;\n /**\n * The single leaf (React `Children.only`). Throws a TypeError (production message\n * `SHADOW_CHILDREN_ONLY`) when there is not exactly one leaf.\n */\n only(): unknown;\n}\n\n/** Whether a source stands for nothing and is skipped. */\nfunction isEmptySource(value: unknown): value is null | undefined | false {\n return value === null || value === undefined || value === false;\n}\n\n/** Own enumerable string and symbol keys, minus the unsafe ones. Reads no getter. */\nfunction ownEnumerableKeys(source: object): Key[] {\n return Reflect.ownKeys(source).filter(\n (key) => !UNSAFE_KEYS.has(key) && Object.prototype.propertyIsEnumerable.call(source, key),\n );\n}\n\n/** Defines an enumerable getter; the target is a fresh object, so this never hits a setter. */\nfunction defineGetter(target: object, key: PropertyKey, read: () => unknown): void {\n Object.defineProperty(target, key, { enumerable: true, configurable: true, get: read });\n}\n\n/** The object a source stands for at this moment, or `undefined` when it is skipped. */\nfunction resolveSource(source: object): object | undefined {\n const value: unknown = typeof source === \"function\" ? (source as () => unknown)() : source;\n if (isEmptySource(value)) return undefined;\n if (typeof value === \"object\" && value !== null) return value;\n throw new TypeError(\n __DEV__\n ? \"mergeProps: a source function must return an object, null, undefined or false\"\n : \"SHADOW_MERGE_SOURCE\",\n );\n}\n\n/** The sources that stand for an object right now, in order; skipped ones are dropped. */\nfunction resolveAll(sources: readonly object[]): object[] {\n const resolved: object[] = [];\n for (const source of sources) {\n const object = resolveSource(source);\n if (object !== undefined) resolved.push(object);\n }\n return resolved;\n}\n\n/**\n * Reads one merged key: the right-most object that has the key and a value other than `undefined`\n * wins. Each getter is read at most once.\n */\nfunction readMerged(objects: readonly object[], key: Key): unknown {\n for (let index = objects.length - 1; index >= 0; index -= 1) {\n const source = objects[index];\n if (source === undefined || !(key in source)) continue;\n const value: unknown = Reflect.get(source, key);\n if (value !== undefined) return value;\n }\n return undefined;\n}\n\n/** Every merged key in first-occurrence order. Reads no getter. */\nfunction mergedKeys(objects: readonly object[]): Key[] {\n const seen = new Set<Key>();\n const keys: Key[] = [];\n for (const source of objects) {\n for (const key of ownEnumerableKeys(source)) {\n if (seen.has(key)) continue;\n seen.add(key);\n keys.push(key);\n }\n }\n return keys;\n}\n\n/** A property name as a Proxy trap sees it. */\ntype Key = string | symbol;\n\n/** The key set and the reader that a live view uses for one access. */\ninterface LiveState {\n readonly keys: ReadonlySet<Key>;\n read(key: Key): unknown;\n}\n\n/**\n * The cache of the live views: `readDepth` counts how deep the live reads are running and\n * `readStates` holds the state each live view computed during the outermost read. A view's traps\n * read the views beneath them, and those read the views beneath them: without a cache every trap\n * recomputes each level below, and a few nested components (a chain of `{...props}` forwards) take\n * exponential time. Within one outermost read a view's state is computed once, so a read costs time\n * linear in the number of views. The cache is dropped when that read returns, so each read still\n * sees the current values.\n *\n * These two are module-level scratch state (R-CODE-4, the scratch-array class), and not registers\n * of `internal/state.ts`: this file may import only the public extension API (EXT-01), which has no\n * place for them, and a new public export for two private counters is not worth it. They are safe\n * because every write is undone in `finally` (`duringRead`), so a getter that throws leaves depth 0\n * and an empty map, and because the map holds a view only while one outermost read is running.\n */\nlet readDepth = 0;\nconst readStates = new Map<object, LiveState>();\n\nfunction stateOf(view: object, load: () => LiveState): LiveState {\n const known = readStates.get(view);\n if (known !== undefined) return known;\n const state = load();\n readStates.set(view, state);\n return state;\n}\n\nfunction duringRead<T>(run: () => T): T {\n readDepth += 1;\n try {\n return run();\n } finally {\n readDepth -= 1;\n if (readDepth === 0) readStates.clear();\n }\n}\n\n/**\n * A Proxy whose key set and values are recomputed on every access: `load` runs once per trap, so\n * a function source is called once per access. The target is an ordinary object, so prototype\n * lookups keep their usual meaning, and every write is refused because props are read-only.\n */\nfunction liveView(load: () => LiveState): object {\n const target: object = {};\n return new Proxy(target, {\n get(_target, key) {\n return duringRead(() => {\n const state = stateOf(target, load);\n return state.keys.has(key) ? state.read(key) : (Reflect.get(target, key) as unknown);\n });\n },\n has(_target, key) {\n return duringRead(() => stateOf(target, load).keys.has(key) || Reflect.has(target, key));\n },\n ownKeys() {\n return duringRead(() => [...stateOf(target, load).keys]);\n },\n getOwnPropertyDescriptor(_target, key) {\n return duringRead(() => {\n if (!stateOf(target, load).keys.has(key)) return undefined;\n return {\n enumerable: true,\n configurable: true,\n get: () => duringRead(() => stateOf(target, load).read(key)),\n };\n });\n },\n set: () => false,\n defineProperty: () => false,\n deleteProperty: () => false,\n });\n}\n\n/**\n * Merges props objects into one getter-preserving object. Reading a key returns the value from the\n * right-most source that has it, unless that value is `undefined`, in which case the next source\n * to the left is tried. Nothing is copied at merge time, so reads stay reactive. Use it to give\n * component props defaults without reading them in the component body.\n *\n * Sources may be objects, `null`, `undefined` or `false` (skipped), or functions that return an\n * object. A function is called on every read, which is how spreads such as `{...props()}` stay\n * reactive. Keys named `__proto__`, `constructor` or `prototype` are ignored.\n *\n * @param sources The props objects, from lowest to highest priority.\n * @returns A read-only object whose keys are the union of the sources' own enumerable keys. With a\n * function source, the key set is recomputed on every access.\n * @throws TypeError (production message `SHADOW_MERGE_SOURCES`) when a source is not an object, a\n * function, `null`, `undefined` or `false`. A read of the result throws TypeError (production\n * message `SHADOW_MERGE_SOURCE`) when a function source returns anything else.\n * @example\n * import { mergeProps } from \"@shadow-js/core\";\n *\n * function Button(props: { size?: \"sm\" | \"md\"; label: string }) {\n * const merged = mergeProps({ size: \"md\" as const }, props);\n * return <button class={`btn-${merged.size}`}>{merged.label}</button>;\n * }\n * @see splitProps\n * @since 1.0.0\n */\nexport function mergeProps<T extends readonly MergeSource[]>(...sources: T): MergeProps<T>;\nexport function mergeProps(...sources: readonly MergeSource[]): object {\n const inputs: object[] = [];\n let dynamic = false;\n for (const source of sources) {\n if (isEmptySource(source)) continue;\n if (typeof source === \"function\") {\n dynamic = true;\n } else if (typeof source !== \"object\") {\n throw new TypeError(\n __DEV__\n ? \"mergeProps: sources must be objects, functions, or null, undefined or false\"\n : \"SHADOW_MERGE_SOURCES\",\n );\n }\n inputs.push(source);\n }\n if (!dynamic) {\n const objects = resolveAll(inputs);\n const merged: object = {};\n for (const key of mergedKeys(objects)) {\n defineGetter(merged, key, () => readMerged(objects, key));\n }\n return merged;\n }\n const view = liveView(() => {\n const objects = resolveAll(inputs);\n return { keys: new Set(mergedKeys(objects)), read: (key) => readMerged(objects, key) };\n });\n DYNAMIC_PROPS.add(view);\n return view;\n}\n\n/**\n * Splits props into one getter-preserving object per key list, followed by an object holding every\n * other key. Each group reads its keys from `props` at access time, so reactivity is preserved. A\n * key listed in two groups appears in both and never in the rest. A listed key that `props` does not\n * have is still present in its group, as `undefined`. Use it to separate the props a component\n * consumes from the ones it forwards to an element.\n *\n * @param props The props to split; plain objects, Proxies and {@link mergeProps} results work.\n * @param keys One or more key lists. Keys named `__proto__`, `constructor` or `prototype` are\n * ignored.\n * @returns `[...groups, rest]`, in the order the key lists were given.\n * @example\n * import { splitProps } from \"@shadow-js/core\";\n *\n * function Field(props: { label: string; value: string; placeholder?: string }) {\n * const [own, input] = splitProps(props, [\"label\"]);\n * return (\n * <label>\n * {own.label}\n * <input {...input} />\n * </label>\n * );\n * }\n * @see mergeProps\n * @since 1.0.0\n */\nexport function splitProps<T extends object, const K extends readonly (readonly (keyof T)[])[]>(\n props: T,\n ...keys: K\n): SplitProps<T, K>;\nexport function splitProps(props: object, ...keys: readonly (readonly PropertyKey[])[]): object[] {\n const listed = new Set<PropertyKey>();\n const groups: object[] = [];\n for (const group of keys) {\n const picked: object = {};\n for (const key of group) {\n if (UNSAFE_KEYS.has(key)) continue;\n listed.add(key);\n defineGetter(picked, key, () => Reflect.get(props, key) as unknown);\n }\n groups.push(picked);\n }\n const restKeys = (): Key[] => ownEnumerableKeys(props).filter((key) => !listed.has(key));\n const readRest = (key: Key): unknown => Reflect.get(props, key) as unknown;\n if (DYNAMIC_PROPS.has(props)) {\n const rest = liveView(() => ({ keys: new Set(restKeys()), read: readRest }));\n return [...groups, rest];\n }\n const rest: object = {};\n for (const key of restKeys()) defineGetter(rest, key, () => readRest(key));\n return [...groups, rest];\n}\n\n/** One level of a children walk: an array being read and the function-layer depth it sits at. */\ninterface Frame {\n readonly items: readonly unknown[];\n next: number;\n readonly layer: number;\n}\n\n/**\n * Resolves children without recursion: arrays flatten in order, accessors are called until a plain\n * value appears, and `null`, `undefined` and booleans are dropped. A cyclic array or more than\n * {@link MAX_FUNCTION_LAYERS} nested accessors is a TypeError.\n */\nfunction flattenChildren(fn: () => unknown): unknown[] {\n const leaves: unknown[] = [];\n const frames: Frame[] = [];\n const open = new Set<readonly unknown[]>();\n let value: unknown = fn;\n let layer = 0;\n for (;;) {\n if (typeof value === \"function\") {\n if (layer >= MAX_FUNCTION_LAYERS) {\n throw new TypeError(\n __DEV__\n ? `children(): more than ${MAX_FUNCTION_LAYERS} nested accessors; a function child may return itself`\n : \"SHADOW_CHILDREN_LAYERS\",\n );\n }\n value = (value as () => unknown)();\n layer += 1;\n continue;\n }\n if (Array.isArray(value)) {\n if (open.has(value))\n throw new TypeError(\n __DEV__ ? \"children(): an array contains itself\" : \"SHADOW_CHILDREN_CYCLE\",\n );\n open.add(value);\n frames.push({ items: value, next: 0, layer });\n } else if (value !== null && value !== undefined && typeof value !== \"boolean\") {\n leaves.push(value);\n }\n let advanced = false;\n while (!advanced) {\n const top = frames.at(-1);\n if (top === undefined) return leaves;\n if (top.next < top.items.length) {\n value = top.items[top.next];\n top.next += 1;\n layer = top.layer;\n advanced = true;\n } else {\n frames.pop();\n open.delete(top.items);\n }\n }\n }\n}\n\n/**\n * Memoizes a `props.children` getter so that it is read at most once per change of its\n * dependencies. Arrays are flattened, accessors are called, and `null`, `undefined` and booleans\n * are dropped. The memo is created in the current owner, so nodes created while resolving are\n * disposed with it. Use it when a component inspects or rearranges its children.\n *\n * @param fn The lazy children accessor, usually `() => props.children`.\n * @returns A {@link ResolvedChildren} accessor with `toArray()`, `count()`, `map()`, `forEach()`\n * and `only()`.\n * @throws TypeError from the returned accessor and its methods when the children contain an array\n * that contains itself (production message `SHADOW_CHILDREN_CYCLE`) or more than 1000 nested\n * accessors (`SHADOW_CHILDREN_LAYERS`). `only()` throws TypeError (`SHADOW_CHILDREN_ONLY`) unless\n * there is exactly one leaf.\n * @example\n * import { children } from \"@shadow-js/core\";\n *\n * function Steps(props: { children?: unknown }) {\n * const steps = children(() => props.children);\n * return (\n * <ol aria-label={`${steps.count()} steps`}>\n * {steps.map((step) => <li>{step as Node | string}</li>)}\n * </ol>\n * );\n * }\n * @since 1.0.0\n */\nexport function children(fn: () => unknown): ResolvedChildren {\n const memo = useMemo(() => flattenChildren(fn), { allowWrites: true });\n const accessor = (): unknown => {\n const leaves = memo();\n if (leaves.length === 1) return leaves[0];\n return leaves.length === 0 ? undefined : leaves;\n };\n return Object.assign(accessor, {\n toArray: (): unknown[] => [...memo()],\n count: (): number => memo().length,\n map: <U>(fn: (leaf: unknown, index: number) => U): U[] =>\n memo().map((leaf, index) => untrack(() => fn(leaf, index))),\n forEach: (fn: (leaf: unknown, index: number) => void): void => {\n memo().forEach((leaf, index) => {\n untrack(() => fn(leaf, index));\n });\n },\n only: (): unknown => {\n const leaves = memo();\n if (leaves.length !== 1) {\n throw new TypeError(\n __DEV__\n ? `children().only(): expected one child, received ${leaves.length}`\n : \"SHADOW_CHILDREN_ONLY\",\n );\n }\n return leaves[0];\n },\n });\n}\n"],"mappings":";;;;;;;AAOA,MAAM,8BAAwC,IAAI,IAAiB;CACjE;CACA;CACA;AACF,CAAC;;;;;;AAOD,MAAM,gCAAgB,IAAI,QAAgB;;AAG1C,MAAM,sBAAsB;;AAgF5B,SAAS,cAAc,OAAmD;CACxE,OAAO,UAAU,QAAQ,UAAU,KAAA,KAAa,UAAU;AAC5D;;AAGA,SAAS,kBAAkB,QAAuB;CAChD,OAAO,QAAQ,QAAQ,MAAM,CAAC,CAAC,QAC5B,QAAQ,CAAC,YAAY,IAAI,GAAG,KAAK,OAAO,UAAU,qBAAqB,KAAK,QAAQ,GAAG,CAC1F;AACF;;AAGA,SAAS,aAAa,QAAgB,KAAkB,MAA2B;CACjF,OAAO,eAAe,QAAQ,KAAK;EAAE,YAAY;EAAM,cAAc;EAAM,KAAK;CAAK,CAAC;AACxF;;AAGA,SAAS,cAAc,QAAoC;CACzD,M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SAAS,MAAM,UAAU;IAC9B,cAAc,GAAG,MAAM,KAAK,CAAC;GAC/B,CAAC;EACH;EACA,YAAqB;GACnB,MAAM,SAAS,KAAK;GACpB,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,UAEJ,mDAAmD,OAAO,QAEhE;GAEF,OAAO,OAAO;EAChB;CACF,CAAC;AACH"}
@@ -1,7 +1,7 @@
1
1
  import { untrack } from "./ownership.js";
2
2
  import { disposeTree } from "./internal/dispose.js";
3
3
  import { createComputation, createOwner, currentOwner, runInScope } from "./extend/index.js";
4
- //#region src/reaction.ts
4
+ // src/reaction.ts
5
5
  /**
6
6
  * Creates a tracker that reports the first change of what it reads. `useReaction(onInvalidate)`
7
7
  * returns `track(fn)`: `fn` runs at once (synchronously) and the signals it reads are recorded.
@@ -13,7 +13,7 @@ import { createComputation, createOwner, currentOwner, runInScope } from "./exte
13
13
  *
14
14
  * @param onInvalidate Called once, untracked, after a change of a tracked read.
15
15
  * @returns `track(fn)`. Each call replaces the previous tracking. Tracking lives in a child of the
16
- * owner that called `useReaction`, so it stops when that owner is disposed.
16
+ * owner that called `useReaction`, so it stops when that owner is disposed; calling `track` after that does nothing.
17
17
  * @example
18
18
  * import { useReaction, useSignal } from "@shadow-js/core";
19
19
  *
@@ -32,6 +32,10 @@ function useReaction(onInvalidate) {
32
32
  let scope = null;
33
33
  return (track) => {
34
34
  if (scope !== null) disposeTree(scope);
35
+ if (owner?.disposed === true) {
36
+ scope = null;
37
+ return;
38
+ }
35
39
  const next = createOwner(owner);
36
40
  scope = next;
37
41
  let tracking = true;
@@ -55,7 +59,6 @@ function useReaction(onInvalidate) {
55
59
  });
56
60
  };
57
61
  }
58
- //#endregion
59
62
  export { useReaction };
60
63
 
61
64
  //# sourceMappingURL=reaction.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reaction.js","names":[],"sources":["../../src/reaction.ts"],"sourcesContent":["import {\n createComputation,\n createOwner,\n currentOwner,\n disposeOwner,\n type Owner,\n runInScope,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Creates a tracker that reports the first change of what it reads. `useReaction(onInvalidate)`\n * returns `track(fn)`: `fn` runs at once (synchronously) and the signals it reads are recorded.\n * The first change of any of them calls `onInvalidate` once, untracked, and then nothing is\n * observed until `track` is called again. The ShadowJS form of Solid's `createReaction`.\n *\n * Use it when the work that follows a change is not a pure rerun of `fn` (for example, re-fetching\n * after a change and then deciding what to track next). For ordinary effects use `useEffect`.\n *\n * @param onInvalidate Called once, untracked, after a change of a tracked read.\n * @returns `track(fn)`. Each call replaces the previous tracking. Tracking lives in a child of the\n * owner that called `useReaction`, so it stops when that owner is disposed.\n * @example\n * import { useReaction, useSignal } from \"@shadow-js/core\";\n *\n * function Results() {\n * const [filters] = useSignal({ query: \"\" });\n * const [stale, setStale] = useSignal(false);\n * const track = useReaction(() => setStale(true));\n * track(() => filters()); // the first change of filters marks the results stale\n * return <p>{stale() ? \"Refresh to update\" : \"Up to date\"}</p>;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useReaction(onInvalidate: () => void): (track: () => void) => void {\n const owner = currentOwner();\n let scope: Owner | null = null;\n return (track: () => void): void => {\n if (scope !== null) disposeOwner(scope);\n const next = createOwner(owner);\n scope = next;\n let tracking = true;\n runInScope({ owner: next, listener: null }, () => {\n createComputation({\n kind: \"effect\",\n render: true,\n owner: next,\n fn: () => {\n if (tracking) {\n tracking = false;\n track();\n return undefined;\n }\n untrack(onInvalidate);\n return undefined;\n },\n });\n });\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,YAAY,cAAuD;CACjF,MAAM,QAAQ,aAAa;CAC3B,IAAI,QAAsB;CAC1B,QAAQ,UAA4B;EAClC,IAAI,UAAU,MAAM,YAAa,KAAK;EACtC,MAAM,OAAO,YAAY,KAAK;EAC9B,QAAQ;EACR,IAAI,WAAW;EACf,WAAW;GAAE,OAAO;GAAM,UAAU;EAAK,SAAS;GAChD,kBAAkB;IAChB,MAAM;IACN,QAAQ;IACR,OAAO;IACP,UAAU;KACR,IAAI,UAAU;MACZ,WAAW;MACX,MAAM;MACN;KACF;KACA,QAAQ,YAAY;IAEtB;GACF,CAAC;EACH,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"reaction.js","names":[],"sources":["../../src/reaction.ts"],"sourcesContent":["import {\n createComputation,\n createOwner,\n currentOwner,\n disposeOwner,\n type Owner,\n runInScope,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Creates a tracker that reports the first change of what it reads. `useReaction(onInvalidate)`\n * returns `track(fn)`: `fn` runs at once (synchronously) and the signals it reads are recorded.\n * The first change of any of them calls `onInvalidate` once, untracked, and then nothing is\n * observed until `track` is called again. The ShadowJS form of Solid's `createReaction`.\n *\n * Use it when the work that follows a change is not a pure rerun of `fn` (for example, re-fetching\n * after a change and then deciding what to track next). For ordinary effects use `useEffect`.\n *\n * @param onInvalidate Called once, untracked, after a change of a tracked read.\n * @returns `track(fn)`. Each call replaces the previous tracking. Tracking lives in a child of the\n * owner that called `useReaction`, so it stops when that owner is disposed; calling `track` after that does nothing.\n * @example\n * import { useReaction, useSignal } from \"@shadow-js/core\";\n *\n * function Results() {\n * const [filters] = useSignal({ query: \"\" });\n * const [stale, setStale] = useSignal(false);\n * const track = useReaction(() => setStale(true));\n * track(() => filters()); // the first change of filters marks the results stale\n * return <p>{stale() ? \"Refresh to update\" : \"Up to date\"}</p>;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useReaction(onInvalidate: () => void): (track: () => void) => void {\n const owner = currentOwner();\n let scope: Owner | null = null;\n return (track: () => void): void => {\n if (scope !== null) disposeOwner(scope);\n // The owner is gone: a scope made now would hang on it and never be disposed.\n if (owner?.disposed === true) {\n scope = null;\n return;\n }\n const next = createOwner(owner);\n scope = next;\n let tracking = true;\n runInScope({ owner: next, listener: null }, () => {\n createComputation({\n kind: \"effect\",\n render: true,\n owner: next,\n fn: () => {\n if (tracking) {\n tracking = false;\n track();\n return undefined;\n }\n untrack(onInvalidate);\n return undefined;\n },\n });\n });\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,YAAY,cAAuD;CACjF,MAAM,QAAQ,aAAa;CAC3B,IAAI,QAAsB;CAC1B,QAAQ,UAA4B;EAClC,IAAI,UAAU,MAAM,YAAa,KAAK;EAEtC,IAAI,OAAO,aAAa,MAAM;GAC5B,QAAQ;GACR;EACF;EACA,MAAM,OAAO,YAAY,KAAK;EAC9B,QAAQ;EACR,IAAI,WAAW;EACf,WAAW;GAAE,OAAO;GAAM,UAAU;EAAK,SAAS;GAChD,kBAAkB;IAChB,MAAM;IACN,QAAQ;IACR,OAAO;IACP,UAAU;KACR,IAAI,UAAU;MACZ,WAAW;MACX,MAAM;MACN;KACF;KACA,QAAQ,YAAY;IAEtB;GACF,CAAC;EACH,CAAC;CACH;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { useSignal } from "./signal.js";
2
- //#region src/reducer.ts
2
+ // src/reducer.ts
3
3
  /**
4
4
  * A state cell whose writes go through a reducer: `dispatch(action)` stores
5
5
  * `reducer(state, action)`. Equivalent to `useSignal` with the transition written in one place,
@@ -26,14 +26,13 @@ import { useSignal } from "./signal.js";
26
26
  function useReducer(reducer, initialState, options) {
27
27
  const [state, setState] = useSignal(initialState, {
28
28
  equals: options?.equals ?? Object.is,
29
- ...options?.name === void 0 ? {} : { name: options.name }
29
+ name: options?.name
30
30
  });
31
31
  const dispatch = (action) => {
32
32
  setState((previous) => reducer(previous, action));
33
33
  };
34
34
  return [state, dispatch];
35
35
  }
36
- //#endregion
37
36
  export { useReducer };
38
37
 
39
38
  //# sourceMappingURL=reducer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reducer.js","names":[],"sources":["../../src/reducer.ts"],"sourcesContent":["import type { Accessor, Equals } from \"./extend\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useReducer}. @since 1.0.0 */\nexport interface ReducerOptions {\n /**\n * Decides whether a new state is a change: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the state is unnamed)\n */\n name?: string;\n}\n\n/**\n * A state cell whose writes go through a reducer: `dispatch(action)` stores\n * `reducer(state, action)`. Equivalent to `useSignal` with the transition written in one place,\n * which keeps every state change of a complex value (a form, a queue) in one function. Reads are\n * fresh immediately after `dispatch`, like every write.\n *\n * @param reducer Pure function `(state, action) => next`.\n * @param initialState Starting state, stored as is.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns `[state, dispatch]`; `state()` tracks, `dispatch(action)` returns nothing. The reducer\n * runs untracked, once per dispatch.\n * @throws ShadowError `WRITE_IN_MEMO` from `dispatch`, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `dispatch` also rethrows what the reducer throws.\n * @example\n * import { useReducer } from \"@shadow-js/core\";\n *\n * type Action = \"inc\" | \"dec\";\n * const [count, dispatch] = useReducer((n: number, a: Action) => (a === \"inc\" ? n + 1 : n - 1), 0);\n * dispatch(\"inc\");\n * console.log(count()); // 1\n * @see useSignal\n * @since 1.0.0\n */\nexport function useReducer<S, A>(\n reducer: (state: S, action: A) => S,\n initialState: S,\n options?: ReducerOptions,\n): [Accessor<S>, (action: A) => void] {\n const [state, setState] = useSignal<S>(initialState, {\n equals: (options?.equals ?? Object.is) as Equals<S>,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n const dispatch = (action: A): void => {\n setState((previous) => reducer(previous, action));\n };\n return [state, dispatch];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,WACd,SACA,cACA,SACoC;CACpC,MAAM,CAAC,OAAO,YAAY,UAAa,cAAc;EACnD,QAAS,SAAS,UAAU,OAAO;EACnC,GAAI,SAAS,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,KAAK;CAC9D,CAAC;CACD,MAAM,YAAY,WAAoB;EACpC,UAAU,aAAa,QAAQ,UAAU,MAAM,CAAC;CAClD;CACA,OAAO,CAAC,OAAO,QAAQ;AACzB"}
1
+ {"version":3,"file":"reducer.js","names":[],"sources":["../../src/reducer.ts"],"sourcesContent":["import type { Accessor, Equals } from \"./extend\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useReducer}. @since 1.0.0 */\nexport interface ReducerOptions {\n /**\n * Decides whether a new state is a change: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the state is unnamed)\n */\n name?: string;\n}\n\n/**\n * A state cell whose writes go through a reducer: `dispatch(action)` stores\n * `reducer(state, action)`. Equivalent to `useSignal` with the transition written in one place,\n * which keeps every state change of a complex value (a form, a queue) in one function. Reads are\n * fresh immediately after `dispatch`, like every write.\n *\n * @param reducer Pure function `(state, action) => next`.\n * @param initialState Starting state, stored as is.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns `[state, dispatch]`; `state()` tracks, `dispatch(action)` returns nothing. The reducer\n * runs untracked, once per dispatch.\n * @throws ShadowError `WRITE_IN_MEMO` from `dispatch`, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `dispatch` also rethrows what the reducer throws.\n * @example\n * import { useReducer } from \"@shadow-js/core\";\n *\n * type Action = \"inc\" | \"dec\";\n * const [count, dispatch] = useReducer((n: number, a: Action) => (a === \"inc\" ? n + 1 : n - 1), 0);\n * dispatch(\"inc\");\n * console.log(count()); // 1\n * @see useSignal\n * @since 1.0.0\n */\nexport function useReducer<S, A>(\n reducer: (state: S, action: A) => S,\n initialState: S,\n options?: ReducerOptions,\n): [Accessor<S>, (action: A) => void] {\n const [state, setState] = useSignal<S>(initialState, {\n equals: (options?.equals ?? Object.is) as Equals<S>,\n name: options?.name,\n });\n const dispatch = (action: A): void => {\n setState((previous) => reducer(previous, action));\n };\n return [state, dispatch];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,WACd,SACA,cACA,SACoC;CACpC,MAAM,CAAC,OAAO,YAAY,UAAa,cAAc;EACnD,QAAS,SAAS,UAAU,OAAO;EACnC,MAAM,SAAS;CACjB,CAAC;CACD,MAAM,YAAY,WAAoB;EACpC,UAAU,aAAa,QAAQ,UAAU,MAAM,CAAC;CAClD;CACA,OAAO,CAAC,OAAO,QAAQ;AACzB"}
@@ -1,5 +1,5 @@
1
1
  import { onCleanup, untrack } from "./ownership.js";
2
- //#region src/refs.ts
2
+ // src/refs.ts
3
3
  /**
4
4
  * Creates a {@link Ref}. Calling it with a value stores the value; calling it with `undefined`
5
5
  * clears it. The same object works as a plain ref callback, so no `forwardRef` is needed.
@@ -52,7 +52,6 @@ function useImperativeHandle(ref, create) {
52
52
  ref(untrack(create));
53
53
  onCleanup(() => ref(void 0));
54
54
  }
55
- //#endregion
56
55
  export { createRef, useImperativeHandle };
57
56
 
58
57
  //# sourceMappingURL=refs.js.map
@@ -6,7 +6,7 @@ import { useContext } from "./context.js";
6
6
  import { ResourceCacheContext, SuspenseContext } from "./suspense.js";
7
7
  import { holdReader, inTransition } from "./internal/concurrency.js";
8
8
  import { createSignalNode, currentListener, currentOwner, writeSignal } from "./extend/index.js";
9
- //#region src/resource.ts
9
+ // src/resource.ts
10
10
  /**
11
11
  * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`
12
12
  * false notifies on every write, true only when the value changes.
@@ -53,8 +53,11 @@ function useResource(first, second, third) {
53
53
  /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */
54
54
  const settle = (id, apply) => {
55
55
  if (disposed || id !== version) return false;
56
- batch(apply);
57
- release();
56
+ try {
57
+ batch(apply);
58
+ } finally {
59
+ release();
60
+ }
58
61
  return true;
59
62
  };
60
63
  /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */
@@ -142,22 +145,28 @@ function useResource(first, second, third) {
142
145
  error: { get: failure },
143
146
  latest: { get: value },
144
147
  refetch: { value: () => {
148
+ if (disposed) return Promise.resolve(void 0);
145
149
  const input = untrack(source);
146
150
  if (input === false || input === null || input === void 0) return Promise.resolve(void 0);
147
151
  return load(input, hasValue);
148
152
  } },
149
153
  mutate: { value: (next) => {
150
154
  let resolved;
151
- batch(() => {
152
- resolved = typeof next === "function" ? next(untrack(value)) : next;
153
- controller?.abort();
154
- version += 1;
155
- hasValue = true;
156
- setValue(resolved);
157
- setFailure(void 0);
158
- setState("ready");
159
- });
160
- release();
155
+ let changed = false;
156
+ try {
157
+ batch(() => {
158
+ resolved = typeof next === "function" ? untrack(() => next(value())) : next;
159
+ changed = true;
160
+ controller?.abort();
161
+ version += 1;
162
+ hasValue = true;
163
+ setValue(resolved);
164
+ setFailure(void 0);
165
+ setState("ready");
166
+ });
167
+ } finally {
168
+ if (changed) release();
169
+ }
161
170
  return resolved;
162
171
  } }
163
172
  });
@@ -170,7 +179,6 @@ function useResource(first, second, third) {
170
179
  });
171
180
  return read;
172
181
  }
173
- //#endregion
174
182
  export { useResource };
175
183
 
176
184
  //# sourceMappingURL=resource.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"resource.js","names":[],"sources":["../../src/resource.ts"],"sourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n createSignalNode,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = createSignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n batch(apply);\n release();\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? (next as (previous: T | undefined) => T)(untrack(value))\n : next;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n release();\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n release();\n });\n return read;\n}\n"],"mappings":";;;;;;;;;;;;;AAkGA,SAAS,KAAQ,SAAY,UAAqD;CAChF,MAAM,OAAO,iBAAoB,SAAS,WAAW,OAAO,KAAK,KAAK;CACtE,OAAO,OACC,WAAW,IAAI,IACpB,SAAS;EACR,YAAY,MAAM,MAAM,EAAE,aAAa,KAAK,CAAC;CAC/C,CACF;AACF;AAEA,SAAS,cAAiB,OAAyC;CACjE,OACE,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;AAElD;AAiFA,SAAgB,YACd,OACA,QACA,OACa;CACb,MAAM,YAAY,OAAO,WAAW;CAEpC,MAAM,SACJ,YAA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ourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n createSignalNode,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = createSignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n // The flush that ends the batch throws what no handler took (a reader that failed): the boundary\n // must be released regardless, or it would show its fallback forever.\n try {\n batch(apply);\n } finally {\n release();\n }\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n // A disposed resource has aborted its fetch and owns no controller any more: a new fetch would\n // run unabortable and its result would be thrown away.\n if (disposed) return Promise.resolve(undefined);\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n // A throwing updater changes nothing, so the boundaries it holds stay held.\n let changed = false;\n try {\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? untrack(() => (next as (previous: T | undefined) => T)(value()))\n : next;\n changed = true;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n } finally {\n if (changed) release();\n }\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n release();\n });\n return read;\n}\n"],"mappings":";;;;;;;;;;;;;AAkGA,SAAS,KAAQ,SAAY,UAAqD;CAChF,MAAM,OAAO,iBAAoB,SAAS,WAAW,OAAO,KAAK,KAAK;CACtE,OAAO,OACC,WAAW,IAAI,IACpB,SAAS;EACR,YAAY,MAAM,MAAM,EAAE,aAAa,KAAK,CAAC;CAC/C,CACF;AACF;AAEA,SAAS,cAAiB,OAAyC;CACjE,OACE,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;AAElD;AAiFA,SAAgB,YACd,OACA,QACA,OACa;CACb,MAAM,YAAY,OAAO,WAAW;CAEpC,MAAM,SACJ,YAAa,OAAO,UAAU,aAAa,cAAc,cAAe;CAE1E,MAAM,UAAU;CAChB,MAAM,UAAW,YAAY,UAAU,QAAW,SAA0B,QAAQ,IAAI;CAIxF,MAAM,WAAW,YAAY,QAAS,WAA8C,CAAC;CAErF,MAAM,aAAa,kBAAkB;CAGrC,MAAM,CAAC,OAAO,YAAY,KAAoB,QAAQ,cAAc,KAAK;CACzE,MAAM,CAAC,OAAO,cAAc,KAAoB,aAAa,UAAU,cAAc,IAAI;CAEzF,IAAI;CACJ,MAAM,YAAY,SAA8B;EAC9C,WAAW,IAAI;EAEb,OAAe,eAAe,gBAAgB,QAAQ,MAAM,QAAQ,MAAM,aAAa,CAAC;CAE5F;CACA,MAAM,CAAC,SAAS,cAAc,KAAc,KAAA,GAAW,KAAK;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AAO,EAAE,KAAK,MAAM;EACpB,SAAS,EAAE,WAAW,MAAM,MAAM,aAAa,MAAM,MAAM,aAAa;EACxE,OAAO,EAAE,KAAK,QAAQ;EACtB,QAAQ,EAAE,KAAK,MAAM;EACrB,SAAS,EACP,aAAqC;GAGnC,IAAI,UAAU,OAAO,QAAQ,QAAQ,KAAA,CAAS;GAC9C,MAAM,QAAQ,QAAQ,MAAM;GAC5B,IAAI,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAA,GACjD,OAAO,QAAQ,QAAQ,KAAA,CAAS;GAElC,OAAO,KAAK,OAAO,QAAQ;EAC7B,EACF;EACA,QAAQ,EACN,QAAQ,SAAkD;GACxD,IAAI;GAEJ,IAAI,UAAU;GACd,IAAI;IACF,YAAY;KACV,WACE,OAAO,SAAS,aACZ,cAAe,KAAwC,MAAM,CAAC,CAAC,IAC/D;KACN,UAAU;KACV,YAAY,MAAM;KAClB,WAAW;KACX,WAAW;KACX,SAAS,QAAa;KACtB,WAAW,KAAA,CAAS;KACpB,SAAS,OAAO;IAClB,CAAC;GACH,UAAU;IACR,IAAI,SAAS,QAAQ;GACvB;GACA,OAAO;EACT,EACF;CACF,CAAC;CAID,SAAS;CAEO,SAAS,QAAQ,MAAM,CAAC;CAExC,gBAAgB;EACd,WAAW;EACX,YAAY,MAAM;EAClB,QAAQ;CACV,CAAC;CACD,OAAO;AACT"}
@@ -2,7 +2,7 @@ import { track } from "./internal/graph.js";
2
2
  import { onCleanup, untrack } from "./ownership.js";
3
3
  import "./effect.js";
4
4
  import { isTracking } from "./extend/index.js";
5
- //#region src/selector.ts
5
+ // src/selector.ts
6
6
  /**
7
7
  * The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the
8
8
  * shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.
@@ -14,10 +14,6 @@ var Entry = class {
14
14
  stamp = 0;
15
15
  /** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */
16
16
  subscribers = 0;
17
- /** The key this entry answers for. */
18
- key;
19
- /** Whether the key matches the selected value. */
20
- value;
21
17
  constructor(key, value) {
22
18
  this.key = key;
23
19
  this.value = value;
@@ -62,7 +58,7 @@ function useSelector(source, equals) {
62
58
  if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);
63
59
  };
64
60
  const create = (key) => {
65
- const entry = new Entry(key, matches(key, currentValue()));
61
+ const entry = new Entry(key, untrack(() => matches(key, currentValue())));
66
62
  entries.set(key, entry);
67
63
  return entry;
68
64
  };
@@ -76,7 +72,6 @@ function useSelector(source, equals) {
76
72
  };
77
73
  return isSelected;
78
74
  }
79
- //#endregion
80
75
  export { useSelector };
81
76
 
82
77
  //# sourceMappingURL=selector.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"selector.js","names":[],"sources":["../../src/selector.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { isTracking, notify, type SourceNode, track } from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\n\n/**\n * The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the\n * shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.\n */\nclass Entry implements SourceNode {\n /** A source with no sources of its own, like a signal. */\n readonly kind = 0;\n observers: SourceNode[\"observers\"] = null;\n stamp = 0;\n /** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */\n subscribers = 0;\n\n /** The key this entry answers for. */\n readonly key: unknown;\n /** Whether the key matches the selected value. */\n value: boolean;\n\n constructor(key: unknown, value: boolean) {\n this.key = key;\n this.value = value;\n }\n}\n\n/** Writes a key's boolean and notifies its readers only when it actually changed. */\nfunction setEntry(entry: Entry, selected: boolean): void {\n if (entry.value === selected) return;\n entry.value = selected;\n notify(entry);\n}\n\n/**\n * Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the\n * current source value. Reading it inside an effect or memo subscribes only to that key's boolean,\n * so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the\n * default equality. A custom `equals` costs one call per registered key per change.\n *\n * The source is tracked by a render-phase effect in the current owner. Create the selector before\n * its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked\n * context reads the source directly and creates no subscription. The default equality is `===`,\n * so `NaN` never matches.\n *\n * @param source The value that selects keys. Tracked.\n * @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.\n * @returns `isSelected(key)`.\n * @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still\n * updated and the error goes to the owner's error handler. In development, a selector created\n * outside any owner warns `NO_OWNER_EFFECT`.\n * @example\n * import { mapArray, useSelector, useSignal } from \"@shadow-js/core\";\n *\n * function Rows(props: { ids: number[] }) {\n * const [selectedId, setSelectedId] = useSignal(1);\n * const isSelected = useSelector(selectedId);\n * return mapArray(() => props.ids, (id) => (\n * <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>\n * ));\n * }\n * @see mapArray\n * @since 1.0.0\n */\nexport function useSelector<T, K = T>(\n source: () => T,\n equals?: (key: K, value: T) => boolean,\n): (key: K) => boolean {\n const entries = new Map<unknown, Entry>();\n /** The value the entries were last reconciled against; `null` until the first successful apply. */\n let last: { readonly value: T } | null = null;\n\n const matches = (key: K, value: T): boolean =>\n equals === undefined ? (key as unknown) === value : equals(key, value);\n\n const currentValue = (): T => (last === null ? untrack(source) : last.value);\n\n const release = (entry: Entry): void => {\n entry.subscribers -= 1;\n if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);\n };\n\n const create = (key: K): Entry => {\n const entry = new Entry(key, matches(key, currentValue()));\n entries.set(key, entry);\n return entry;\n };\n\n const isSelected = (key: K): boolean => {\n if (!isTracking()) return matches(key, source());\n const entry = entries.get(key) ?? create(key);\n entry.subscribers += 1;\n onCleanup(() => release(entry));\n track(entry);\n return entry.value;\n };\n\n useRenderEffect(\n () => source(),\n (next) => {\n const previous = last;\n last = { value: next };\n if (previous !== null && equals === undefined) {\n // Default equality: only the entries for the previous and the next key can change.\n if (previous.value === next) return;\n const before = entries.get(previous.value);\n if (before !== undefined) setEntry(before, before.key === next);\n const after = entries.get(next);\n if (after !== undefined) setEntry(after, after.key === next);\n return;\n }\n // Custom equality, or the first successful value: every registered key is checked. A\n // failing equals does not stop the others; its error is rethrown once they are all updated.\n let failed = false;\n let failure: unknown;\n for (const entry of entries.values()) {\n let selected: boolean;\n try {\n selected = matches(entry.key as K, next);\n } catch (error) {\n if (!failed) {\n failed = true;\n failure = error;\n }\n continue;\n }\n setEntry(entry, selected);\n }\n if (failed) throw failure;\n },\n );\n\n return isSelected;\n}\n"],"mappings":";;;;;;;;;AAQA,IAAM,QAAN,MAAkC;;CAEhC,OAAgB;CAChB,YAAqC;CACrC,QAAQ;;CAER,cAAc;;CAGd;;CAEA;CAEA,YAAY,KAAc,OAAgB;EACxC,KAAK,MAAM;EACX,KAAK,QAAQ;CACf;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,YACd,QACA,QACqB;CACrB,MAAM,0BAAU,IAAI,IAAoB;CAIxC,MAAM,WAAW,KAAQ,UACvB,WAAW,KAAA,IAAa,QAAoB,QAAQ,OAAO,KAAK,KAAK;CAEvE,MAAM,qBAAyC,QAAQ,MAAM;CAE7D,MAAM,WAAW,UAAuB;EACtC,MAAM,eAAe;EACrB,IAAI,MAAM,gBAAgB,KAAK,QAAQ,IAAI,MAAM,GAAG,MAAM,OAAO,QAAQ,OAAO,MAAM,GAAG;CAC3F;CAEA,MAAM,UAAU,QAAkB;EAChC,MAAM,QAAQ,IAAI,MAAM,KAAK,QAAQ,KAAK,aAAa,CAAC,CAAC;EACzD,QAAQ,IAAI,KAAK,KAAK;EACtB,OAAO;CACT;CAEA,MAAM,cAAc,QAAoB;EACtC,IAAI,CAAC,WAAW,GAAG,OAAO,QAAQ,KAAK,OAAO,CAAC;EAC/C,MAAM,QAAQ,QAAQ,IAAI,GAAG,KAAK,OAAO,GAAG;EAC5C,MAAM,eAAe;EACrB,gBAAgB,QAAQ,KAAK,CAAC;EAC9B,MAAM,KAAK;EACX,OAAO,MAAM;CACf;CAqCA,OAAO;AACT"}
1
+ {"version":3,"file":"selector.js","names":[],"sources":["../../src/selector.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { isTracking, notify, type SourceNode, track } from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\n\n/**\n * The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the\n * shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.\n */\nclass Entry implements SourceNode {\n /** A source with no sources of its own, like a signal. */\n readonly kind = 0;\n observers: SourceNode[\"observers\"] = null;\n stamp = 0;\n /** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */\n subscribers = 0;\n\n /** The key this entry answers for. */\n declare readonly key: unknown;\n /** Whether the key matches the selected value. */\n declare value: boolean;\n\n constructor(key: unknown, value: boolean) {\n this.key = key;\n this.value = value;\n }\n}\n\n/** Writes a key's boolean and notifies its readers only when it actually changed. */\nfunction setEntry(entry: Entry, selected: boolean): void {\n if (entry.value === selected) return;\n entry.value = selected;\n notify(entry);\n}\n\n/**\n * Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the\n * current source value. Reading it inside an effect or memo subscribes only to that key's boolean,\n * so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the\n * default equality. A custom `equals` costs one call per registered key per change.\n *\n * The source is tracked by a render-phase effect in the current owner. Create the selector before\n * its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked\n * context reads the source directly and creates no subscription. The default equality is `===`,\n * so `NaN` never matches.\n *\n * @param source The value that selects keys. Tracked.\n * @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.\n * @returns `isSelected(key)`.\n * @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still\n * updated and the error goes to the owner's error handler. In development, a selector created\n * outside any owner warns `NO_OWNER_EFFECT`.\n * @example\n * import { mapArray, useSelector, useSignal } from \"@shadow-js/core\";\n *\n * function Rows(props: { ids: number[] }) {\n * const [selectedId, setSelectedId] = useSignal(1);\n * const isSelected = useSelector(selectedId);\n * return mapArray(() => props.ids, (id) => (\n * <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>\n * ));\n * }\n * @see mapArray\n * @since 1.0.0\n */\nexport function useSelector<T, K = T>(\n source: () => T,\n equals?: (key: K, value: T) => boolean,\n): (key: K) => boolean {\n const entries = new Map<unknown, Entry>();\n /** The value the entries were last reconciled against; `null` until the first successful apply. */\n let last: { readonly value: T } | null = null;\n\n const matches = (key: K, value: T): boolean =>\n equals === undefined ? (key as unknown) === value : equals(key, value);\n\n const currentValue = (): T => (last === null ? untrack(source) : last.value);\n\n const release = (entry: Entry): void => {\n entry.subscribers -= 1;\n if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);\n };\n\n const create = (key: K): Entry => {\n // `equals` is a user callback: it must not subscribe the reader that happens to register the key.\n const entry = new Entry(\n key,\n untrack(() => matches(key, currentValue())),\n );\n entries.set(key, entry);\n return entry;\n };\n\n const isSelected = (key: K): boolean => {\n if (!isTracking()) return matches(key, source());\n const entry = entries.get(key) ?? create(key);\n entry.subscribers += 1;\n onCleanup(() => release(entry));\n track(entry);\n return entry.value;\n };\n\n useRenderEffect(\n () => source(),\n (next) => {\n const previous = last;\n last = { value: next };\n if (previous !== null && equals === undefined) {\n // Default equality: only the entries for the previous and the next key can change.\n if (previous.value === next) return;\n const before = entries.get(previous.value);\n if (before !== undefined) setEntry(before, before.key === next);\n const after = entries.get(next);\n if (after !== undefined) setEntry(after, after.key === next);\n return;\n }\n // Custom equality, or the first successful value: every registered key is checked. A\n // failing equals does not stop the others; its error is rethrown once they are all updated.\n let failed = false;\n let failure: unknown;\n for (const entry of entries.values()) {\n let selected: boolean;\n try {\n selected = matches(entry.key as K, next);\n } catch (error) {\n if (!failed) {\n failed = true;\n failure = error;\n }\n continue;\n }\n setEntry(entry, selected);\n }\n if (failed) throw failure;\n },\n );\n\n return isSelected;\n}\n"],"mappings":";;;;;;;;;AAQA,IAAM,QAAN,MAAkC;;CAEhC,OAAgB;CAChB,YAAqC;CACrC,QAAQ;;CAER,cAAc;CAOd,YAAY,KAAc,OAAgB;EACxC,KAAK,MAAM;EACX,KAAK,QAAQ;CACf;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,YACd,QACA,QACqB;CACrB,MAAM,0BAAU,IAAI,IAAoB;CAIxC,MAAM,WAAW,KAAQ,UACvB,WAAW,KAAA,IAAa,QAAoB,QAAQ,OAAO,KAAK,KAAK;CAEvE,MAAM,qBAAyC,QAAQ,MAAM;CAE7D,MAAM,WAAW,UAAuB;EACtC,MAAM,eAAe;EACrB,IAAI,MAAM,gBAAgB,KAAK,QAAQ,IAAI,MAAM,GAAG,MAAM,OAAO,QAAQ,OAAO,MAAM,GAAG;CAC3F;CAEA,MAAM,UAAU,QAAkB;EAEhC,MAAM,QAAQ,IAAI,MAChB,KACA,cAAc,QAAQ,KAAK,aAAa,CAAC,CAAC,CAC5C;EACA,QAAQ,IAAI,KAAK,KAAK;EACtB,OAAO;CACT;CAEA,MAAM,cAAc,QAAoB;EACtC,IAAI,CAAC,WAAW,GAAG,OAAO,QAAQ,KAAK,OAAO,CAAC;EAC/C,MAAM,QAAQ,QAAQ,IAAI,GAAG,KAAK,OAAO,GAAG;EAC5C,MAAM,eAAe;EACrB,gBAAgB,QAAQ,KAAK,CAAC;EAC9B,MAAM,KAAK;EACX,OAAO,MAAM;CACf;CAqCA,OAAO;AACT"}
@@ -1,7 +1,7 @@
1
1
  import { readSignal } from "./internal/graph.js";
2
2
  import { untrack } from "./ownership.js";
3
3
  import { createSignalNode, writeSignal } from "./extend/index.js";
4
- //#region src/signal.ts
4
+ // src/signal.ts
5
5
  /**
6
6
  * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads
7
7
  * inside effects and memos subscribe them; writes notify them. Works at module scope.
@@ -33,7 +33,6 @@ function useSignal(value, options) {
33
33
  });
34
34
  return [read, write];
35
35
  }
36
- //#endregion
37
36
  export { useSignal };
38
37
 
39
38
  //# sourceMappingURL=signal.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"signal.js","names":[],"sources":["../../src/signal.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n type Equals,\n readSignal,\n type Setter,\n writeSignal,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useSignal}.\n * @since 1.0.0\n */\nexport interface SignalOptions<T> {\n /**\n * Decides whether a write is a change: readers are notified only when it returns `false`.\n * `false` notifies on every write, even of the same value.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name?: string;\n}\n\n/**\n * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads\n * inside effects and memos subscribe them; writes notify them. Works at module scope.\n *\n * @param value Initial value.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs\n * untracked, and returns the value it stored.\n * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is\n * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * setCount((n) => n + 1);\n * console.log(count()); // 1\n * @see useStore\n * @see useMemo\n * @since 1.0.0\n */\nexport function useSignal<T>(value: T, options?: SignalOptions<T>): [Accessor<T>, Setter<T>] {\n const equals: Equals<T> = options?.equals === undefined ? Object.is : options.equals;\n const signal = createSignalNode<T>(value, equals, options?.name);\n const read: Accessor<T> = () => readSignal(signal);\n const write = ((next: unknown) => {\n const resolved = (\n typeof next === \"function\" ? untrack(() => (next as (prev: T) => T)(signal.value)) : next\n ) as T;\n writeSignal(signal, resolved);\n return resolved;\n }) as Setter<T>;\n return [read, write];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,UAAa,OAAU,SAAsD;CAC3F,MAAM,SAAoB,SAAS,WAAW,KAAA,IAAY,OAAO,KAAK,QAAQ;CAC9E,MAAM,SAAS,iBAAoB,OAAO,QAAQ,SAAS,IAAI;CAC/D,MAAM,aAA0B,WAAW,MAAM;CACjD,MAAM,UAAU,SAAkB;EAChC,MAAM,WACJ,OAAO,SAAS,aAAa,cAAe,KAAwB,OAAO,KAAK,CAAC,IAAI;EAEvF,YAAY,QAAQ,QAAQ;EAC5B,OAAO;CACT;CACA,OAAO,CAAC,MAAM,KAAK;AACrB"}
1
+ {"version":3,"file":"signal.js","names":[],"sources":["../../src/signal.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n type Equals,\n readSignal,\n type Setter,\n writeSignal,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useSignal}.\n * @since 1.0.0\n */\nexport interface SignalOptions<T> {\n /**\n * Decides whether a write is a change: readers are notified only when it returns `false`.\n * `false` notifies on every write, even of the same value. It runs untracked: a signal it reads\n * is not a dependency of the computation that writes.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name?: string | undefined;\n}\n\n/**\n * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads\n * inside effects and memos subscribe them; writes notify them. Works at module scope.\n *\n * @param value Initial value.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs\n * untracked, and returns the value it stored.\n * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is\n * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * setCount((n) => n + 1);\n * console.log(count()); // 1\n * @see useStore\n * @see useMemo\n * @since 1.0.0\n */\nexport function useSignal<T>(value: T, options?: SignalOptions<T>): [Accessor<T>, Setter<T>] {\n const equals: Equals<T> = options?.equals === undefined ? Object.is : options.equals;\n const signal = createSignalNode<T>(value, equals, options?.name);\n const read: Accessor<T> = () => readSignal(signal);\n const write = ((next: unknown) => {\n const resolved = (\n typeof next === \"function\" ? untrack(() => (next as (prev: T) => T)(signal.value)) : next\n ) as T;\n writeSignal(signal, resolved);\n return resolved;\n }) as Setter<T>;\n return [read, write];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,UAAa,OAAU,SAAsD;CAC3F,MAAM,SAAoB,SAAS,WAAW,KAAA,IAAY,OAAO,KAAK,QAAQ;CAC9E,MAAM,SAAS,iBAAoB,OAAO,QAAQ,SAAS,IAAI;CAC/D,MAAM,aAA0B,WAAW,MAAM;CACjD,MAAM,UAAU,SAAkB;EAChC,MAAM,WACJ,OAAO,SAAS,aAAa,cAAe,KAAwB,OAAO,KAAK,CAAC,IAAI;EAEvF,YAAY,QAAQ,QAAQ;EAC5B,OAAO;CACT;CACA,OAAO,CAAC,MAAM,KAAK;AACrB"}
@@ -1,6 +1,6 @@
1
1
  import { track } from "../internal/graph.js";
2
2
  import { createSignalNode, isTracking, notify as notify$1 } from "../extend/index.js";
3
- //#region src/store/nodes.ts
3
+ // src/store/nodes.ts
4
4
  /** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */
5
5
  const RESERVED_KEYS = /* @__PURE__ */ new Set([
6
6
  "__proto__",
@@ -106,6 +106,8 @@ function nodeOf(raw) {
106
106
  }
107
107
  return node;
108
108
  }
109
+ /** The map size at which the first sweep of unobserved key signals runs. */
110
+ const SWEEP_AT = 256;
109
111
  function signalFor(node, key) {
110
112
  let signals = node.signals;
111
113
  if (signals === null) {
@@ -114,6 +116,10 @@ function signalFor(node, key) {
114
116
  }
115
117
  let signal = signals.get(key);
116
118
  if (signal === void 0) {
119
+ const size = signals.size;
120
+ if (size >= SWEEP_AT && (size & size - 1) === 0) {
121
+ for (const [other, node] of signals) if ((node.observers?.length ?? 0) === 0) signals.delete(other);
122
+ }
117
123
  signal = createSignalNode(0, false);
118
124
  signals.set(key, signal);
119
125
  }
@@ -186,7 +192,6 @@ function deleteRaw(target, key) {
186
192
  notify(node.keys);
187
193
  return true;
188
194
  }
189
- //#endregion
190
195
  export { NODES, RAW, deleteRaw, isReservedKey, isWrappable, nodeOf, readRaw, trackKeys, trackProperty, unwrapDeep, unwrapValue, writeRaw };
191
196
 
192
197
  //# sourceMappingURL=nodes.js.map