@effect-app/vue 4.0.0-beta.98 → 4.0.0

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