@effect-app/vue 4.0.0-beta.3 → 4.0.0-beta.300

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 (133) hide show
  1. package/CHANGELOG.md +2424 -0
  2. package/dist/atomQuery.d.ts +111 -0
  3. package/dist/atomQuery.d.ts.map +1 -0
  4. package/dist/atomQuery.js +386 -0
  5. package/dist/commander.d.ts +634 -0
  6. package/dist/commander.d.ts.map +1 -0
  7. package/dist/commander.js +1070 -0
  8. package/dist/{experimental/confirm.d.ts → confirm.d.ts} +6 -4
  9. package/dist/confirm.d.ts.map +1 -0
  10. package/dist/confirm.js +26 -0
  11. package/dist/dependencyMetadata.d.ts +10 -0
  12. package/dist/dependencyMetadata.d.ts.map +1 -0
  13. package/dist/dependencyMetadata.js +29 -0
  14. package/dist/errorReporter.d.ts +6 -4
  15. package/dist/errorReporter.d.ts.map +1 -1
  16. package/dist/errorReporter.js +14 -19
  17. package/dist/form.d.ts +14 -5
  18. package/dist/form.d.ts.map +1 -1
  19. package/dist/form.js +46 -13
  20. package/dist/internal/tanstackQuery.d.ts +9 -0
  21. package/dist/internal/tanstackQuery.d.ts.map +1 -0
  22. package/dist/internal/tanstackQuery.js +194 -0
  23. package/dist/intl.d.ts +15 -0
  24. package/dist/intl.d.ts.map +1 -0
  25. package/dist/intl.js +9 -0
  26. package/dist/lib.d.ts +7 -9
  27. package/dist/lib.d.ts.map +1 -1
  28. package/dist/lib.js +35 -10
  29. package/dist/makeClient.d.ts +236 -336
  30. package/dist/makeClient.d.ts.map +1 -1
  31. package/dist/makeClient.js +416 -408
  32. package/dist/makeContext.d.ts.map +1 -1
  33. package/dist/makeIntl.d.ts.map +1 -1
  34. package/dist/{experimental/makeUseCommand.d.ts → makeUseCommand.d.ts} +4 -3
  35. package/dist/makeUseCommand.d.ts.map +1 -0
  36. package/dist/makeUseCommand.js +13 -0
  37. package/dist/mutate.d.ts +109 -41
  38. package/dist/mutate.d.ts.map +1 -1
  39. package/dist/mutate.js +212 -59
  40. package/dist/query.d.ts +140 -46
  41. package/dist/query.d.ts.map +1 -1
  42. package/dist/query.js +328 -111
  43. package/dist/routeParams.d.ts +4 -4
  44. package/dist/routeParams.d.ts.map +1 -1
  45. package/dist/routeParams.js +4 -3
  46. package/dist/runtime.d.ts +1 -14
  47. package/dist/runtime.d.ts.map +1 -1
  48. package/dist/runtime.js +2 -26
  49. package/dist/suspense.d.ts +19 -0
  50. package/dist/suspense.d.ts.map +1 -0
  51. package/dist/suspense.js +38 -0
  52. package/dist/toast.d.ts +2 -0
  53. package/dist/toast.d.ts.map +1 -0
  54. package/dist/toast.js +2 -0
  55. package/dist/withToast.d.ts +2 -0
  56. package/dist/withToast.d.ts.map +1 -0
  57. package/dist/withToast.js +2 -0
  58. package/docs/atom-query-api-redesign.md +207 -0
  59. package/docs/query-key-invalidation.md +106 -0
  60. package/examples/streamMutation.ts +72 -0
  61. package/package.json +36 -95
  62. package/src/atomQuery.ts +540 -0
  63. package/src/commander.ts +3413 -0
  64. package/src/{experimental/confirm.ts → confirm.ts} +13 -15
  65. package/src/dependencyMetadata.ts +38 -0
  66. package/src/errorReporter.ts +65 -75
  67. package/src/form.ts +61 -18
  68. package/src/index.ts +7 -7
  69. package/src/internal/tanstackQuery.ts +289 -0
  70. package/src/intl.ts +12 -0
  71. package/src/lib.ts +49 -21
  72. package/src/makeClient.ts +967 -1159
  73. package/src/makeIntl.ts +2 -2
  74. package/src/{experimental/makeUseCommand.ts → makeUseCommand.ts} +9 -6
  75. package/src/mutate.ts +371 -153
  76. package/src/query.ts +694 -249
  77. package/src/routeParams.ts +7 -7
  78. package/src/runtime.ts +1 -31
  79. package/src/suspense.ts +43 -0
  80. package/src/toast.ts +1 -0
  81. package/src/withToast.ts +1 -0
  82. package/test/Mutation.test.ts +181 -24
  83. package/test/dependencyInvalidation.test.ts +373 -0
  84. package/test/dist/dependencyInvalidation.test.d.ts.map +1 -0
  85. package/test/dist/form.test.d.ts.map +1 -1
  86. package/test/dist/interrupt-refetch-repro.test.d.ts.map +1 -0
  87. package/test/dist/lib.test.d.ts.map +1 -0
  88. package/test/dist/query-span.test.d.ts.map +1 -0
  89. package/test/dist/streamFinal.test.d.ts.map +1 -0
  90. package/test/dist/streamFn.test.d.ts.map +1 -0
  91. package/test/dist/stubs.d.ts +3756 -122
  92. package/test/dist/stubs.d.ts.map +1 -1
  93. package/test/dist/stubs.js +192 -32
  94. package/test/dist/suspense-regression.test.d.ts.map +1 -0
  95. package/test/dist/suspense.test.d.ts.map +1 -0
  96. package/test/form-validation-errors.test.ts +25 -20
  97. package/test/form.test.ts +22 -3
  98. package/test/interrupt-refetch-repro.test.ts +623 -0
  99. package/test/lib.test.ts +240 -0
  100. package/test/makeClient.test.ts +437 -38
  101. package/test/query-span.test.ts +92 -0
  102. package/test/streamFinal.test.ts +64 -0
  103. package/test/streamFn.test.ts +457 -0
  104. package/test/stubs.ts +228 -43
  105. package/test/suspense-regression.test.ts +168 -0
  106. package/test/suspense.test.ts +160 -0
  107. package/tsconfig.examples.json +20 -0
  108. package/tsconfig.json +3 -1
  109. package/tsconfig.src.json +34 -34
  110. package/tsconfig.test.json +2 -2
  111. package/vitest.config.ts +5 -5
  112. package/dist/experimental/commander.d.ts +0 -359
  113. package/dist/experimental/commander.d.ts.map +0 -1
  114. package/dist/experimental/commander.js +0 -558
  115. package/dist/experimental/confirm.d.ts.map +0 -1
  116. package/dist/experimental/confirm.js +0 -28
  117. package/dist/experimental/intl.d.ts +0 -16
  118. package/dist/experimental/intl.d.ts.map +0 -1
  119. package/dist/experimental/intl.js +0 -5
  120. package/dist/experimental/makeUseCommand.d.ts.map +0 -1
  121. package/dist/experimental/makeUseCommand.js +0 -13
  122. package/dist/experimental/toast.d.ts +0 -47
  123. package/dist/experimental/toast.d.ts.map +0 -1
  124. package/dist/experimental/toast.js +0 -41
  125. package/dist/experimental/withToast.d.ts +0 -25
  126. package/dist/experimental/withToast.d.ts.map +0 -1
  127. package/dist/experimental/withToast.js +0 -45
  128. package/eslint.config.mjs +0 -24
  129. package/src/experimental/commander.ts +0 -1836
  130. package/src/experimental/intl.ts +0 -9
  131. package/src/experimental/toast.ts +0 -66
  132. package/src/experimental/withToast.ts +0 -99
  133. package/tsconfig.json.bak +0 -12
@@ -0,0 +1,540 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ /**
3
+ * Shared atom core for the query/mutation engine (used by query.ts + mutate.ts).
4
+ *
5
+ * Replaces the @tanstack/vue-query engine with Effect `Atom`, keeping the public
6
+ * `.query()/.suspense()/.mutate()` contract unchanged:
7
+ * - cache identity = the atom reference (one per [handler, input], via Atom.family)
8
+ * - invalidation key = reactivity keys (= the app's existing namespace query keys)
9
+ * - SWR + focus = Atom.swr (+ windowFocusSignal)
10
+ * - gcTime = Atom.setIdleTTL / Atom.keepAlive
11
+ * - retry = Effect.retry inside the atom effect
12
+ *
13
+ * Built over the app's RPC client through the existing `RequestHandlerWithInput`
14
+ * abstraction (mirrors AtomRpc's recipe; see docs/atom-query-plan.md).
15
+ */
16
+ import { defaultRegistry } from "@effect/atom-vue"
17
+ import { DataDependencies, makeQueryKey } from "effect-app/client"
18
+ import type { ClientForOptions } from "effect-app/client/clientFor"
19
+ import { ServiceUnavailableError } from "effect-app/client/errors"
20
+ import * as Effect from "effect-app/Effect"
21
+ import * as Option from "effect-app/Option"
22
+ import * as S from "effect-app/Schema"
23
+ import * as Cause from "effect/Cause"
24
+ import * as Duration from "effect/Duration"
25
+ import * as Equal from "effect/Equal"
26
+ import * as Hash from "effect/Hash"
27
+ import type * as Layer from "effect/Layer"
28
+ import * as Ref from "effect/Ref"
29
+ import * as Stream from "effect/Stream"
30
+ import type * as Tracer from "effect/Tracer"
31
+ import { isHttpClientError } from "effect/unstable/http/HttpClientError"
32
+ import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"
33
+ import * as Atom from "effect/unstable/reactivity/Atom"
34
+ import * as AtomRegistry from "effect/unstable/reactivity/AtomRegistry"
35
+ import { clearQueryReadDependencies, setQueryReadDependencies } from "./dependencyMetadata.ts"
36
+ import { reportRuntimeError } from "./lib.ts"
37
+
38
+ /** All non-empty prefixes of a key, longest last. `[a,b,c]` -> `[[a],[a,b],[a,b,c]]`. */
39
+ const prefixesOf = (key: ReadonlyArray<unknown>): ReadonlyArray<ReadonlyArray<unknown>> =>
40
+ key.map((_, i) => key.slice(0, i + 1))
41
+
42
+ const uniqueKeys = (keys: ReadonlyArray<ReadonlyArray<unknown>>): ReadonlyArray<ReadonlyArray<unknown>> => {
43
+ const out: Array<ReadonlyArray<unknown>> = []
44
+ const seen = new Set<number>()
45
+ for (const key of keys) {
46
+ const hash = Hash.hash(key)
47
+ if (seen.has(hash)) continue
48
+ seen.add(hash)
49
+ out.push(key)
50
+ }
51
+ return out
52
+ }
53
+
54
+ // --- awaitable invalidation -------------------------------------------------------------------
55
+ // keyHash -> live query atoms registered under that key. A query atom is tracked while it is alive
56
+ // in the registry (mounted OR cached within idle-ttl) and removed on GC, so invalidation reaches
57
+ // cached-but-unmounted queries too (e.g. a list you navigated away from).
58
+ const keyAtoms = new Map<number, Set<Atom.Atom<AsyncResult.AsyncResult<any, any>>>>()
59
+
60
+ const trackByKeys =
61
+ (keys: ReadonlyArray<ReadonlyArray<unknown>>) =>
62
+ <A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>): Atom.Atom<AsyncResult.AsyncResult<A, E>> =>
63
+ Atom.transform(atom, (get) => {
64
+ for (const key of keys) {
65
+ const h = Hash.hash(key)
66
+ let set = keyAtoms.get(h)
67
+ if (!set) keyAtoms.set(h, set = new Set())
68
+ set.add(atom)
69
+ get.addFinalizer(() => {
70
+ set.delete(atom)
71
+ if (set.size === 0) keyAtoms.delete(h)
72
+ })
73
+ }
74
+ return get(atom)
75
+ }, { initialValueTarget: atom })
76
+
77
+ const trackWritableByKeys =
78
+ (keys: ReadonlyArray<ReadonlyArray<unknown>>) =>
79
+ <A, E, W>(atom: Atom.Writable<AsyncResult.AsyncResult<A, E>, W>): Atom.Writable<AsyncResult.AsyncResult<A, E>, W> => {
80
+ const tracked = trackByKeys(keys)(atom)
81
+ return Atom.writable(
82
+ (get) => get(tracked),
83
+ (ctx, value) => ctx.set(atom, value),
84
+ (refresh) => refresh(tracked)
85
+ )
86
+ }
87
+
88
+ /**
89
+ * Keep a query's recorded read-dependencies registered for as long as it is alive, and drop them when
90
+ * its atom is GC'd (mirrors `trackByKeys`).
91
+ *
92
+ * `recordReads` only stores the deps on an actual fetch. A query that unmounts and later remounts from
93
+ * cache (within idle-ttl) does NOT re-run the handler, so its registry entry — cleared by the previous
94
+ * teardown's finalizer — would never be restored, and a subsequent mutation could not derive it as an
95
+ * invalidation target. Re-asserting the last-known reads on every (re)subscribe closes that gap, so the
96
+ * registry mirrors the live query even across cache-hit remounts.
97
+ */
98
+ const trackReadDependencies =
99
+ (key: ReadonlyArray<unknown>, getReads: () => DataDependencies.DataDependencies) =>
100
+ <A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>): Atom.Atom<AsyncResult.AsyncResult<A, E>> =>
101
+ Atom.transform(atom, (get) => {
102
+ const reads = getReads()
103
+ if (DataDependencies.isNonEmpty(reads)) setQueryReadDependencies(key, reads)
104
+ get.addFinalizer(() => clearQueryReadDependencies(key))
105
+ return get(atom)
106
+ }, { initialValueTarget: atom })
107
+
108
+ const atomsForKeys = (keys: ReadonlyArray<unknown>): ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<any, any>>> => {
109
+ const atoms = new Set<Atom.Atom<AsyncResult.AsyncResult<any, any>>>()
110
+ for (const key of keys) {
111
+ const set = keyAtoms.get(Hash.hash(key))
112
+ if (set) { for (const a of set) atoms.add(a) }
113
+ }
114
+ return [...atoms]
115
+ }
116
+
117
+ /**
118
+ * Invalidate the given keys and AWAIT the result. `keyAtoms` resolves all matching hierarchical
119
+ * keys to a deduplicated set of query atoms. Refresh that set directly: sending the whole key set
120
+ * through `Reactivity.invalidate` invokes one atom's registered callback once per matching key,
121
+ * repeatedly superseding the same fetch when a mutation carries many row/prefix keys.
122
+ *
123
+ * Resolves once the affected queries have settled, so a mutation can `yield*` this and know the
124
+ * affected queries are fresh. (The await reads via the module-global default registry — the one the
125
+ * vue composables resolve via `injectRegistry`'s fallback.)
126
+ */
127
+ export const invalidateAndAwait = (keys: ReadonlyArray<unknown>): Effect.Effect<void> =>
128
+ Effect.gen(function*() {
129
+ const atoms = atomsForKeys(keys)
130
+ yield* Effect.forEach(atoms, captureAtomQueryParentSpan, { discard: true, concurrency: "inherit" })
131
+ if (atoms.length === 0) return
132
+ yield* Effect.forEach(atoms, (atom) => Effect.sync(() => defaultRegistry.refresh(atom)), {
133
+ discard: true
134
+ })
135
+ yield* Effect.forEach(atoms, (a) => awaitAtomResult(defaultRegistry, a).pipe(Effect.exit))
136
+ })
137
+
138
+ const isPlainObject = (o: unknown): o is Record<string, unknown> => {
139
+ if (typeof o !== "object" || o === null) return false
140
+ const proto = Object.getPrototypeOf(o)
141
+ return proto === Object.prototype || proto === null
142
+ }
143
+
144
+ /**
145
+ * Structural sharing (tanstack `replaceEqualDeep`): walk `next` against `prev` and reuse `prev`'s
146
+ * reference for any unchanged array/object sub-tree, so unchanged data keeps referential identity
147
+ * (Vue skips re-rendering it). Leaves — including decoded Schema CLASS INSTANCES — are compared with
148
+ * Effect `Equal.equals` (structural), which reuses equal instances that tanstack's `===` could not.
149
+ */
150
+ export const replaceEqualDeep = (prev: any, next: any): any => {
151
+ if (prev === next) return prev
152
+ const bothArrays = Array.isArray(prev) && Array.isArray(next)
153
+ if (bothArrays || (isPlainObject(prev) && isPlainObject(next))) {
154
+ const a: Record<PropertyKey, any> = prev
155
+ const b: Record<PropertyKey, any> = next
156
+ const copy: Record<PropertyKey, any> = bothArrays ? [] : {}
157
+ const nextKeys: Array<PropertyKey> = bothArrays ? (b as Array<any>).map((_, i) => i) : Object.keys(b)
158
+ const nextSize = nextKeys.length
159
+ const prevSize = bothArrays ? (a as Array<any>).length : Object.keys(a).length
160
+ let equalItems = 0
161
+ for (let i = 0; i < nextSize; i++) {
162
+ const key = nextKeys[i]!
163
+ copy[key] = replaceEqualDeep(a[key], b[key])
164
+ if (copy[key] === a[key] && a[key] !== undefined) equalItems++
165
+ }
166
+ return prevSize === nextSize && equalItems === prevSize ? prev : copy
167
+ }
168
+ return Equal.equals(prev, next) ? prev : next
169
+ }
170
+
171
+ /** Atom combinator: share each new `Success` value structurally against the previous one. */
172
+ const structuralShare = <A, E>(
173
+ self: Atom.Atom<AsyncResult.AsyncResult<A, E>>
174
+ ): Atom.Atom<AsyncResult.AsyncResult<A, E>> =>
175
+ Atom.transform(self, (get) => {
176
+ const next = get(self)
177
+ if (next._tag !== "Success") return next
178
+ const prev = Option.flatMap(get.self<AsyncResult.AsyncResult<A, E>>(), AsyncResult.value)
179
+ if (Option.isNone(prev)) return next
180
+ const shared = replaceEqualDeep(prev.value, next.value)
181
+ return shared === next.value
182
+ ? next
183
+ : AsyncResult.success(shared, { waiting: next.waiting, timestamp: next.timestamp })
184
+ }, { initialValueTarget: self })
185
+
186
+ export interface AtomClientRuntime {
187
+ readonly runtime: Atom.AtomRuntime<any, never>
188
+ readonly factory: Atom.RuntimeFactory
189
+ }
190
+
191
+ /**
192
+ * Build one AtomRuntime (and its factory) from an already-built app context.
193
+ * Shares the ManagedRuntime's `memoMap` so layers are not built twice, and so
194
+ * query-registration and mutation-invalidation resolve the SAME `Reactivity`.
195
+ */
196
+ export const makeAtomClientRuntime = <R>(
197
+ getContext: () => Layer.Layer<R, never, never>,
198
+ memoMap: Layer.MemoMap
199
+ ): AtomClientRuntime => {
200
+ const factory = Atom.context({ memoMap })
201
+ const runtime = factory((_get) => getContext())
202
+ return { runtime, factory }
203
+ }
204
+
205
+ const isRetryable = (e: unknown): boolean =>
206
+ isHttpClientError(e)
207
+ || S.is(ServiceUnavailableError)(e)
208
+ || (typeof e === "object" && e !== null && (e as any)._tag === "RpcClientError")
209
+
210
+ export interface AtomQueryOptions {
211
+ /** background-refresh threshold (TanStack staleTime; default 5s) */
212
+ readonly staleTime?: Duration.Input
213
+ /** dispose-when-idle (TanStack gcTime; default 5min). "infinity" => keepAlive */
214
+ readonly gcTime?: Duration.Input | "infinity"
215
+ /**
216
+ * Revalidate a stale query on window focus AND on network reconnect (default on, matching
217
+ * tanstack refetchOnWindowFocus + refetchOnReconnect).
218
+ */
219
+ readonly revalidateOnFocus?: boolean
220
+ /**
221
+ * Reuse references of unchanged sub-trees across refetches (default on, matching tanstack
222
+ * structuralSharing). Uses Effect `Equal` so decoded Schema instances share too — more effective
223
+ * than tanstack's `===`, but a deep compare per refetch (O(rows·fields)). Set `false` for very
224
+ * large or mostly-changing result sets where the compare costs more than the saved re-renders.
225
+ */
226
+ readonly structuralSharing?: boolean
227
+ /** poll: re-fetch every N ms (tanstack refetchInterval). */
228
+ readonly refetchInterval?: number
229
+ }
230
+
231
+ const defaults = { staleTime: Duration.seconds(5), gcTime: Duration.minutes(5) }
232
+
233
+ export interface AtomQueryMetadata {
234
+ readonly staleTimeMs: number
235
+ }
236
+
237
+ const atomQueryMetadata = new WeakMap<Atom.Atom<AsyncResult.AsyncResult<any, any>>, AtomQueryMetadata>()
238
+ const atomQueryParentSpans = new WeakMap<Atom.Atom<AsyncResult.AsyncResult<any, any>>, Tracer.AnySpan>()
239
+
240
+ const atomSpanTarget = <A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) => {
241
+ let target = atom
242
+ while (target.initialValueTarget !== undefined) {
243
+ target = target.initialValueTarget
244
+ }
245
+ return target
246
+ }
247
+
248
+ const takeAtomQueryParentSpan = <A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) => {
249
+ const target = atomSpanTarget(atom)
250
+ const span = atomQueryParentSpans.get(target)
251
+ if (span !== undefined) atomQueryParentSpans.delete(target)
252
+ return span
253
+ }
254
+
255
+ const setAtomQueryParentSpan = <A, E>(
256
+ atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
257
+ span: Tracer.AnySpan
258
+ ) => {
259
+ atomQueryParentSpans.set(atomSpanTarget(atom), span)
260
+ }
261
+
262
+ export const captureAtomQueryParentSpan = <A, E>(
263
+ atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>
264
+ ): Effect.Effect<void> =>
265
+ Effect.currentParentSpan.pipe(
266
+ Effect.tap((span) => Effect.sync(() => setAtomQueryParentSpan(atom, span))),
267
+ Effect.ignore
268
+ )
269
+
270
+ export const refreshAtomWithCurrentSpan = <A, E>(
271
+ registry: AtomRegistry.AtomRegistry,
272
+ atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>
273
+ ): Effect.Effect<void> =>
274
+ captureAtomQueryParentSpan(atom).pipe(
275
+ Effect.andThen(Effect.sync(() => registry.refresh(atom)))
276
+ )
277
+
278
+ const setAtomQueryMetadata = <A, E>(
279
+ atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
280
+ opts: AtomQueryOptions = {}
281
+ ) => {
282
+ const staleTimeMs = staleTimeMsOf(opts)
283
+ const previous = atomQueryMetadata.get(atom)
284
+ atomQueryMetadata.set(atom, {
285
+ staleTimeMs: previous === undefined ? staleTimeMs : Math.min(previous.staleTimeMs, staleTimeMs)
286
+ })
287
+ return atom
288
+ }
289
+
290
+ export const getAtomQueryMetadata = <A, E>(
291
+ atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>
292
+ ): AtomQueryMetadata | undefined => atomQueryMetadata.get(atom)
293
+
294
+ /** Exported so the vue hook can do refetch-on-mount-per-observer with the same rule as swr. */
295
+ export const isStaleResult = (r: AsyncResult.AsyncResult<any, any>, staleTimeMs: number): boolean => {
296
+ if (r.waiting) return false
297
+ const ts = r._tag === "Success"
298
+ ? r.timestamp
299
+ : r._tag === "Failure"
300
+ ? Option.getOrUndefined(Option.map(r.previousSuccess, (s) => s.timestamp))
301
+ : undefined
302
+ if (ts === undefined) return r._tag !== "Initial"
303
+ return Date.now() - ts >= staleTimeMs
304
+ }
305
+
306
+ export const staleTimeMsOf = (opts: AtomQueryOptions): number =>
307
+ Duration.toMillis(Duration.fromInputUnsafe(opts.staleTime ?? defaults.staleTime))
308
+
309
+ // A query fetch that is interrupted (a subscriber lost interest / a refresh superseded it / the
310
+ // component navigated) leaves the family atom `waiting=true` with NO fiber running — effect-core
311
+ // `makeEffect` removes its result-observer before interrupting, so the interrupt is never written
312
+ // back; it stays `waitingFrom(previous)`. `swr`/`isStaleResult` both short-circuit
313
+ // `if (waiting) return false`, so that stuck `waiting` is neither completing nor considered stale —
314
+ // mount/focus/staleness all skip it. Left alone the interrupt is TERMINAL: any current or future
315
+ // subscriber inherits the `waiting` forever (cold → `latestDefined` throws → white screen; warm →
316
+ // the Mako Bauhaus PickList stale wedge).
317
+ //
318
+ // The invariant we restore in this layer (no effect-core change): an interrupt must never be a
319
+ // terminal state. We do NOT auto-retry the interrupted fetch — an interrupt is intentional (that
320
+ // caller lost interest), and the first observer recovers through its normal refresh/staleness rules.
321
+ // We only guarantee that a *genuine* new/parallel/future observer is never stuck on a departed
322
+ // observer's interrupt: per family atom we count live computes (`inFlight`), so "stuck" = a `waiting`
323
+ // result with `inFlight === 0` (nothing is actually fetching). On mount a stuck atom triggers one
324
+ // fresh fetch instead of adopting the dangling `waiting`; a genuinely in-flight fetch (`inFlight > 0`)
325
+ // is joined, not superseded (dedup / re-entrancy preserved). `recovering` dedupes concurrent mounts
326
+ // so exactly one recovery fetch is issued until a fetch is running again.
327
+ export interface QueryFetchState {
328
+ inFlight: number
329
+ recovering: boolean
330
+ }
331
+ export const queryFetchStates = new WeakMap<Atom.Atom<any>, QueryFetchState>()
332
+
333
+ const recoverStuckWaitingOnMount =
334
+ <A, E>(familyAtom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) =>
335
+ (wrapped: Atom.Atom<AsyncResult.AsyncResult<A, E>>): Atom.Atom<AsyncResult.AsyncResult<A, E>> =>
336
+ Atom.transform(wrapped, (get) => {
337
+ const current = get.once(wrapped)
338
+ get.subscribe(wrapped, (value) => get.setSelf(value))
339
+ const state = queryFetchStates.get(familyAtom)
340
+ const waiting = current?.waiting === true
341
+ // Stuck: the result says `waiting` yet nothing is in-flight — an interrupt was hidden and left
342
+ // `waiting` dangling. Treat it as not-yet-fetched and refetch; a live fetch (`inFlight > 0`) is
343
+ // joined, not superseded. `recovering` prevents concurrent mounts from issuing more than one
344
+ // recovery fetch (cleared once a fetch is actually running again).
345
+ if (state && waiting && state.inFlight === 0 && !state.recovering) {
346
+ state.recovering = true
347
+ get.refresh(familyAtom)
348
+ }
349
+ return current
350
+ }, { initialValueTarget: wrapped })
351
+
352
+ export const withQueryOptions = <A, E>(
353
+ self: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
354
+ opts: AtomQueryOptions = {}
355
+ ): Atom.Atom<AsyncResult.AsyncResult<A, E>> => {
356
+ setAtomQueryMetadata(self, opts)
357
+ const staleTime: Duration.Input = opts.staleTime ?? defaults.staleTime
358
+ let atom = self
359
+ const revalidateOnFocus = opts.revalidateOnFocus ?? true
360
+ atom = Atom.swr({
361
+ staleTime,
362
+ revalidateOnFocus,
363
+ focusSignal: revalidateOnFocus ? focusOrReconnectSignal : undefined
364
+ })(atom)
365
+ atom = recoverStuckWaitingOnMount(self)(atom)
366
+ if (opts.refetchInterval) atom = Atom.withRefresh(Duration.millis(opts.refetchInterval))(atom)
367
+ if (opts.structuralSharing ?? true) atom = structuralShare(atom)
368
+ return atom
369
+ }
370
+
371
+ /** Constant atom for disabled / `mode:"optional"`-None queries: stays Initial, never fetches. */
372
+ export const disabledQueryAtom: Atom.Atom<AsyncResult.AsyncResult<any, any>> = Atom.readable(() =>
373
+ AsyncResult.initial(false)
374
+ )
375
+
376
+ /**
377
+ * Bumps when the browser regains connectivity (the `online` event) — the tanstack
378
+ * `refetchOnReconnect` trigger. One shared listener (module-level). SSR-guarded.
379
+ */
380
+ const onlineSignal: Atom.Atom<number> = Atom.readable((get) => {
381
+ let count = 0
382
+ if (typeof window === "undefined") return count
383
+ const update = () => {
384
+ if (navigator.onLine) get.setSelf(++count)
385
+ }
386
+ window.addEventListener("online", update)
387
+ get.addFinalizer(() => window.removeEventListener("online", update))
388
+ return count
389
+ })
390
+
391
+ /**
392
+ * Focus OR reconnect, as a single signal for `swr` — both should stale-revalidate a query.
393
+ * swr takes one `focusSignal`, so we fold window-focus + reconnect into one derived atom;
394
+ * a bump from either triggers swr's stale check.
395
+ */
396
+ const focusOrReconnectSignal: Atom.Atom<number> = Atom.make((get) => get(Atom.windowFocusSignal) + get(onlineSignal))
397
+
398
+ /**
399
+ * Build the per-input atom family for a request handler — the query CACHE IDENTITY.
400
+ *
401
+ * This is the TanStack `queryKey = [handler, input]` equivalent and the piece that makes
402
+ * caching cross-component: `Atom.family` memoizes one atom per structurally-distinct input
403
+ * (v4 hashes the input via Hash/Equal), so every component querying the same handler+input
404
+ * reads the SAME atom instance => one fetch, one shared result in the global registry,
405
+ * ref-counted and GC'd on idle ttl. (The registry + ttl give lifetime; reactivity keys give
406
+ * invalidation; the family gives identity/sharing — all three are needed.)
407
+ *
408
+ * The family is created once per handler (see query.ts's per-handler cache), so it is shared
409
+ * process-wide via the registry.
410
+ *
411
+ * Invalidation is hierarchical: each atom registers under EVERY prefix of its full key
412
+ * `[...makeQueryKey(self), input]`. Since reactivity matches keys by exact hash, registering
413
+ * all prefixes means `invalidate(P)` refreshes every atom whose key starts with `P` — e.g.
414
+ * `["$X"]` refreshes all inputs, `["$X","$List",input]` only that input. (`makeQueryKey`'s
415
+ * collapsed form `getQueryKey` — what mutations invalidate by default — is one of the prefixes.)
416
+ */
417
+ export const buildQueryFamily = <I, A, E>(
418
+ rt: AtomClientRuntime,
419
+ self: {
420
+ readonly id: string
421
+ readonly handler: (i: I) => Effect.Effect<A, E, any>
422
+ readonly options?: ClientForOptions
423
+ readonly queryKeyProjectionHash?: string
424
+ }
425
+ ) => {
426
+ const baseKey = makeQueryKey(self) // hierarchical, input-independent
427
+
428
+ return Atom.family((input: I) => {
429
+ const fullKey = [...baseKey, input]
430
+ // Record the repository/server read-dependencies seen while fetching, keyed by `fullKey`, so a
431
+ // later mutation whose writes intersect them can derive this query as an invalidation target.
432
+ // The last recorded reads are retained on the (memoized) family atom so `trackReadDependencies`
433
+ // can re-assert them on a cache-hit remount that never re-runs the handler.
434
+ let lastReads: DataDependencies.DataDependencies = DataDependencies.empty()
435
+ // Fetch bookkeeping read by `recoverStuckWaitingOnMount`. `inFlight` counts live computes, so a
436
+ // `waiting` result with `inFlight === 0` is a stuck/hidden interrupt. `recovering` guards the
437
+ // recovery refresh against concurrent mounts; a running fetch clears it.
438
+ const fetchState: QueryFetchState = { inFlight: 0, recovering: false }
439
+ let atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>
440
+ atom = rt.runtime.atom(
441
+ Effect.suspend(() => {
442
+ // A fetch is now running: the atom is not stuck, and any pending recovery is fulfilled.
443
+ fetchState.recovering = false
444
+ fetchState.inFlight++
445
+ const recordReads = Effect.gen(function*() {
446
+ const readsRef = yield* Ref.make(DataDependencies.empty())
447
+ const writesRef = yield* Ref.make(DataDependencies.empty())
448
+ const recorder = DataDependencies.makeDataDependencyRecorder(readsRef, writesRef)
449
+ const result = yield* self
450
+ .handler(input)
451
+ .pipe(Effect.provideService(DataDependencies.DataDependencyRecorder, recorder))
452
+ lastReads = yield* Ref.get(readsRef)
453
+ setQueryReadDependencies(fullKey, lastReads)
454
+ return result
455
+ })
456
+ const effect = recordReads.pipe(
457
+ Effect.retry({ times: 5, while: isRetryable }),
458
+ Effect.tapCauseIf(Cause.hasDies, (cause) => reportRuntimeError(cause)),
459
+ // On exit, the compute is no longer in-flight. An interrupt (subscriber lost interest / a
460
+ // superseding refresh) may leave the result at `waiting`; with `inFlight` back at 0 that
461
+ // reads as "stuck", so the next mount recovers it (`recoverStuckWaitingOnMount`). We do not
462
+ // re-fire here — the interrupt was intentional; recovery is driven by a genuine (re)mount.
463
+ Effect.onExit(() =>
464
+ Effect.sync(() => {
465
+ fetchState.inFlight = Math.max(0, fetchState.inFlight - 1)
466
+ })
467
+ ),
468
+ Effect.withSpan(`query ${self.id}`, {}, { captureStackTrace: false })
469
+ )
470
+ const parentSpan = takeAtomQueryParentSpan(atom)
471
+ return parentSpan === undefined
472
+ ? effect
473
+ : effect.pipe(Effect.withParentSpan(parentSpan, { captureStackTrace: false }))
474
+ })
475
+ )
476
+ // Register under every prefix of the full key => hierarchical (prefix) invalidation. Two roles:
477
+ // - withReactivity: `Reactivity.invalidate(key)` refreshes this atom (the actual refetch).
478
+ // - trackByKeys: records the atom in `keyAtoms` so the mutation can AWAIT its settle.
479
+ const projectedFullKey = self.queryKeyProjectionHash === undefined
480
+ ? fullKey
481
+ : [...baseKey, self.queryKeyProjectionHash, input]
482
+ const reactivityKeys = uniqueKeys([...prefixesOf(fullKey), ...prefixesOf(projectedFullKey)])
483
+ atom = rt.factory.withReactivity(reactivityKeys)(atom)
484
+ atom = trackByKeys(reactivityKeys)(atom)
485
+ atom = trackReadDependencies(fullKey, () => lastReads)(atom)
486
+ // gcTime LAST so the whole chain (incl. the registration + tracking) stays alive through the
487
+ // idle window, letting invalidation reach a cached-but-unmounted query.
488
+ atom = Atom.setIdleTTL(atom, defaults.gcTime)
489
+ const registered = setAtomQueryMetadata(Atom.withLabel(`query:${self.id}`)(atom))
490
+ const writable = Atom.writable(
491
+ (get) => {
492
+ const current = get.once(registered)
493
+ get.subscribe(registered, (value) => get.setSelf(value))
494
+ return current
495
+ },
496
+ (ctx, value: AsyncResult.AsyncResult<A, E>) => ctx.setSelf(value),
497
+ (refresh) => refresh(registered)
498
+ )
499
+ const writableWithTarget = Object.assign(writable, { initialValueTarget: registered })
500
+ const result = setAtomQueryMetadata(Atom.withLabel(`query-cache:${self.id}`)(writableWithTarget))
501
+ // Key the fetch state by the atom `withQueryOptions` receives, so its mount hook can find it.
502
+ queryFetchStates.set(result, fetchState)
503
+ return result
504
+ })
505
+ }
506
+
507
+ export const buildStreamQueryFamily = <I, A, E>(
508
+ rt: AtomClientRuntime,
509
+ self: {
510
+ readonly id: string
511
+ readonly handler: (i: I) => Stream.Stream<A, E, any>
512
+ readonly options?: ClientForOptions
513
+ readonly queryKeyProjectionHash?: string
514
+ }
515
+ ) => {
516
+ const baseKey = makeQueryKey(self)
517
+
518
+ return Atom.family((input: I) => {
519
+ let atom = rt.runtime.pull(
520
+ self.handler(input).pipe(
521
+ Stream.tapCause((cause) => Cause.hasDies(cause) ? reportRuntimeError(cause) : Effect.void)
522
+ )
523
+ )
524
+ const fullKey = [...baseKey, input]
525
+ const projectedFullKey = self.queryKeyProjectionHash === undefined
526
+ ? fullKey
527
+ : [...baseKey, self.queryKeyProjectionHash, input]
528
+ const reactivityKeys = uniqueKeys([...prefixesOf(fullKey), ...prefixesOf(projectedFullKey)])
529
+ atom = rt.factory.withReactivity(reactivityKeys)(atom)
530
+ atom = trackWritableByKeys(reactivityKeys)(atom)
531
+ atom = Atom.setIdleTTL(atom, defaults.gcTime)
532
+ return setAtomQueryMetadata(Atom.withLabel(`stream-query:${self.id}`)(atom))
533
+ })
534
+ }
535
+
536
+ /** Await the first resolved (non-Waiting) result of an atom. Failing query results fail the Effect. */
537
+ export const awaitAtomResult = <A, E>(
538
+ registry: AtomRegistry.AtomRegistry,
539
+ atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>
540
+ ) => AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true })