@effect-app/vue 4.0.0-beta.29 → 4.0.0-beta.291

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 (131) hide show
  1. package/CHANGELOG.md +2167 -0
  2. package/dist/atomQuery.d.ts +107 -0
  3. package/dist/atomQuery.d.ts.map +1 -0
  4. package/dist/atomQuery.js +345 -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 +212 -336
  30. package/dist/makeClient.d.ts.map +1 -1
  31. package/dist/makeClient.js +388 -411
  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 +108 -40
  38. package/dist/mutate.d.ts.map +1 -1
  39. package/dist/mutate.js +211 -58
  40. package/dist/query.d.ts +139 -45
  41. package/dist/query.d.ts.map +1 -1
  42. package/dist/query.js +325 -122
  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 +30 -94
  62. package/src/atomQuery.ts +466 -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 +930 -1159
  73. package/src/makeIntl.ts +2 -2
  74. package/src/{experimental/makeUseCommand.ts → makeUseCommand.ts} +9 -6
  75. package/src/mutate.ts +372 -152
  76. package/src/query.ts +683 -260
  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 +352 -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/lib.test.d.ts.map +1 -0
  87. package/test/dist/query-span.test.d.ts.map +1 -0
  88. package/test/dist/streamFinal.test.d.ts.map +1 -0
  89. package/test/dist/streamFn.test.d.ts.map +1 -0
  90. package/test/dist/stubs.d.ts +3756 -122
  91. package/test/dist/stubs.d.ts.map +1 -1
  92. package/test/dist/stubs.js +192 -32
  93. package/test/dist/suspense-regression.test.d.ts.map +1 -0
  94. package/test/dist/suspense.test.d.ts.map +1 -0
  95. package/test/form-validation-errors.test.ts +25 -20
  96. package/test/form.test.ts +22 -3
  97. package/test/lib.test.ts +240 -0
  98. package/test/makeClient.test.ts +437 -38
  99. package/test/query-span.test.ts +92 -0
  100. package/test/streamFinal.test.ts +64 -0
  101. package/test/streamFn.test.ts +457 -0
  102. package/test/stubs.ts +228 -43
  103. package/test/suspense-regression.test.ts +168 -0
  104. package/test/suspense.test.ts +160 -0
  105. package/tsconfig.examples.json +20 -0
  106. package/tsconfig.json +3 -1
  107. package/tsconfig.src.json +34 -34
  108. package/tsconfig.test.json +2 -2
  109. package/vitest.config.ts +5 -5
  110. package/dist/experimental/commander.d.ts +0 -359
  111. package/dist/experimental/commander.d.ts.map +0 -1
  112. package/dist/experimental/commander.js +0 -557
  113. package/dist/experimental/confirm.d.ts.map +0 -1
  114. package/dist/experimental/confirm.js +0 -28
  115. package/dist/experimental/intl.d.ts +0 -16
  116. package/dist/experimental/intl.d.ts.map +0 -1
  117. package/dist/experimental/intl.js +0 -5
  118. package/dist/experimental/makeUseCommand.d.ts.map +0 -1
  119. package/dist/experimental/makeUseCommand.js +0 -13
  120. package/dist/experimental/toast.d.ts +0 -47
  121. package/dist/experimental/toast.d.ts.map +0 -1
  122. package/dist/experimental/toast.js +0 -41
  123. package/dist/experimental/withToast.d.ts +0 -25
  124. package/dist/experimental/withToast.d.ts.map +0 -1
  125. package/dist/experimental/withToast.js +0 -45
  126. package/eslint.config.mjs +0 -24
  127. package/src/experimental/commander.ts +0 -1835
  128. package/src/experimental/intl.ts +0 -9
  129. package/src/experimental/toast.ts +0 -66
  130. package/src/experimental/withToast.ts +0 -99
  131. package/tsconfig.json.bak +0 -12
package/src/query.ts CHANGED
@@ -2,33 +2,200 @@
2
2
  /* eslint-disable @typescript-eslint/no-unsafe-call */
3
3
  /* eslint-disable @typescript-eslint/no-unsafe-return */
4
4
  /* eslint-disable @typescript-eslint/no-unsafe-assignment */
5
- import { type DefaultError, type Enabled, type InitialDataFunction, type NonUndefinedGuard, type PlaceholderDataFunction, type QueryKey, type QueryObserverOptions, type QueryObserverResult, type RefetchOptions, useQuery as useTanstackQuery, useQueryClient, type UseQueryDefinedReturnType, type UseQueryReturnType } from "@tanstack/vue-query"
6
- import { Array, Cause, Effect, Exit, flow, Option, S, type ServiceMap } from "effect-app"
7
- import { type Req } from "effect-app/client"
8
- import type { RequestHandler, RequestHandlerWithInput } from "effect-app/client/clientFor"
9
- import { ServiceUnavailableError } from "effect-app/client/errors"
10
- import { type Span } from "effect/Tracer"
11
- import { isHttpClientError } from "effect/unstable/http/HttpClientError"
5
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
6
+ import { injectRegistry, useAtomValue } from "@effect/atom-vue"
7
+ import * as Array from "effect-app/Array"
8
+ import { makeQueryKey, type Req } from "effect-app/client"
9
+ import type { ClientForOptions, RequestHandlerWithInput, RequestStreamHandlerWithInput } from "effect-app/client/clientFor"
10
+ import { type CauseException } from "effect-app/client/errors"
11
+ import type * as Context from "effect-app/Context"
12
+ import * as Effect from "effect-app/Effect"
13
+ import * as Option from "effect-app/Option"
14
+ import type * as Cause from "effect/Cause"
15
+ import * as Exit from "effect/Exit"
16
+ import * as Stream from "effect/Stream"
12
17
  import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"
13
- import { computed, type ComputedRef, type MaybeRefOrGetter, ref, shallowRef, watch, type WatchSource } from "vue"
14
- import { makeQueryKey, reportRuntimeError } from "./lib.js"
18
+ import * as Atom from "effect/unstable/reactivity/Atom"
19
+ import { computed, type ComputedRef, effectScope, type MaybeRefOrGetter, onBeforeUnmount, onMounted, onScopeDispose, ref, toValue, type WatchSource } from "vue"
20
+ import { type AtomClientRuntime, type AtomQueryOptions, awaitAtomResult, buildQueryFamily, buildStreamQueryFamily, disabledQueryAtom, isStaleResult, refreshAtomWithCurrentSpan, staleTimeMsOf, withQueryOptions } from "./atomQuery.ts"
21
+ import { latestDefined } from "./suspense.ts"
15
22
 
16
- // we must use interface extends, or we get the dreaded typescript error of isn't portable blabla @tanstack/vue-query/build/modern/types.js
17
- // but because how they are dealing with some extends clause, we loose all properties except initialData
18
- // so we actually reconstruct the interfaces here from the ground up :/
23
+ // --- minimal local types (replacing the former @tanstack/vue-query type imports) ---
24
+ type DefaultError = Error
25
+ type QueryKey = ReadonlyArray<unknown>
26
+ /** Options accepted by `refetch()` — kept for source compatibility; the atom path ignores them. */
27
+ export interface RefetchOptions {
28
+ readonly cancelRefetch?: boolean
29
+ readonly throwOnError?: boolean
30
+ }
31
+ /** The 4th tuple element: private atom/registry handle for client helpers. */
32
+ export interface QueryHandle<A = unknown, E = unknown> {
33
+ readonly awaitResult: () => Effect.Effect<A, E, never>
34
+ readonly refetch: () => Effect.Effect<A, E, never>
35
+ readonly refresh: () => void
36
+ readonly registry: ReturnType<typeof injectRegistry>
37
+ readonly atom: ComputedRef<Atom.Atom<AsyncResult.AsyncResult<A, E>>>
38
+ }
39
+ export interface QueryView<A, E> extends QueryHandle<A, E> {
40
+ readonly result: ComputedRef<AsyncResult.AsyncResult<A, E>>
41
+ readonly data: ComputedRef<A | undefined>
42
+ }
43
+
44
+ const useScopedSuspenseSetup = <A>(setup: () => A) => {
45
+ const scope = effectScope()
46
+ const controller = new AbortController()
47
+ const value = scope.run(setup)
48
+ if (value === undefined) {
49
+ throw new Error("Internal Error: atom suspense setup scope did not initialize")
50
+ }
51
+
52
+ const isMounted = ref(true)
53
+ let stopped = false
54
+ const stop = () => {
55
+ if (stopped) return
56
+ stopped = true
57
+ isMounted.value = false
58
+ controller.abort()
59
+ scope.stop()
60
+ }
61
+ onBeforeUnmount(stop)
62
+ onScopeDispose(stop)
63
+
64
+ return [value, isMounted, controller.signal] as const
65
+ }
66
+
67
+ export interface QueryCacheUpdater {
68
+ readonly update: <I, A, E, R, Request extends Req, Name extends string>(
69
+ registry: ReturnType<typeof injectRegistry>,
70
+ query: RequestHandlerWithInput<I, A, E, R, Request, Name>,
71
+ input: I,
72
+ updater: (data: NoInfer<A>) => NoInfer<A>
73
+ ) => void
74
+ }
75
+
76
+ // retained generic aliases so the exported option-interface arity is unchanged for consumers
77
+ export type UseQueryReturnType<A = any, E = any> = QueryHandle<A, E>
78
+ export type UseQueryDefinedReturnType<A = any, E = any> = QueryHandle<A, E>
79
+ export type QueryObserverResult<A = any, _E = any> = AsyncResult.AsyncResult<A, any>
80
+ export type SuspenseQueryTuple<A, E> = readonly [
81
+ ComputedRef<AsyncResult.AsyncResult<A, E>>,
82
+ ComputedRef<A>,
83
+ (options?: RefetchOptions) => Effect.Effect<A, E, never>,
84
+ QueryHandle<A, E>
85
+ ]
86
+
87
+ export type SuspenseQueryView<A, E> =
88
+ & Omit<QueryView<A, E>, "data">
89
+ & {
90
+ readonly data: ComputedRef<A>
91
+ }
92
+ & SuspenseQueryTuple<A, E>
93
+
94
+ export type QueryAtomFamily<I, A, E> = (input: I) => Atom.Atom<AsyncResult.AsyncResult<A, E>>
95
+ export type StreamQueryAtomFamily<I, A, E> = (input: I) => Atom.Writable<Atom.PullResult<A, E>, void>
96
+
97
+ interface QueryFamilyDescriptor<I, A, E> {
98
+ readonly id: string
99
+ readonly handler: (i: I) => Effect.Effect<A, E, any>
100
+ readonly options?: ClientForOptions
101
+ readonly queryKeyProjectionHash?: string
102
+ }
103
+
104
+ interface StreamQueryFamilyDescriptor<I, A, E> {
105
+ readonly id: string
106
+ readonly handler: (i: I) => Stream.Stream<A, E, any>
107
+ readonly options?: ClientForOptions
108
+ readonly queryKeyProjectionHash?: string
109
+ }
110
+
111
+ const queryFamilyCacheKey = (
112
+ q: { readonly id: string; readonly options?: ClientForOptions; readonly queryKeyProjectionHash?: string }
113
+ ) => `${makeQueryKey(q).join("/")}:${q.queryKeyProjectionHash ?? ""}`
114
+
115
+ // One atom family per request shape, keyed by the stable query key + projection hash (not the
116
+ // handler object — `clientFor` returns a fresh proxy per call, so the object isn't shareable).
117
+ // Module-level + key-indexed => the family is process-global, so the same request+input read
118
+ // the same atom across components/pages => cross-page caching via the global registry.
119
+ const queryFamilyByKey = new Map<string, any>()
120
+ const getQueryFamily = <I, A, E>(
121
+ rt: AtomClientRuntime,
122
+ q: QueryFamilyDescriptor<I, A, E>
123
+ ): QueryAtomFamily<I, A, E> => {
124
+ const key = queryFamilyCacheKey(q)
125
+ let f = queryFamilyByKey.get(key)
126
+ if (!f) {
127
+ f = buildQueryFamily(rt, q)
128
+ queryFamilyByKey.set(key, f)
129
+ }
130
+ return f
131
+ }
132
+
133
+ const streamQueryFamilyByKey = new Map<string, any>()
134
+ const getStreamQueryFamily = <I, A, E>(
135
+ rt: AtomClientRuntime,
136
+ q: StreamQueryFamilyDescriptor<I, A, E>
137
+ ): StreamQueryAtomFamily<I, A, E> => {
138
+ const key = queryFamilyCacheKey(q)
139
+ let f = streamQueryFamilyByKey.get(key)
140
+ if (!f) {
141
+ f = buildStreamQueryFamily(rt, q)
142
+ streamQueryFamilyByKey.set(key, f)
143
+ }
144
+ return f
145
+ }
146
+
147
+ const makeAtomQueryCacheUpdater = (warnIfMissing: boolean): QueryCacheUpdater => ({
148
+ update: (registry, query, input) => {
149
+ const family = queryFamilyByKey.get(queryFamilyCacheKey(query))
150
+ if (!family) {
151
+ if (warnIfMissing) {
152
+ console.warn(`Query ${query.id} has not been used yet; nothing to update`)
153
+ }
154
+ return
155
+ }
156
+ registry.refresh(family(input))
157
+ }
158
+ })
159
+
160
+ export const atomQueryCacheUpdater = makeAtomQueryCacheUpdater(true)
161
+ export const optionalAtomQueryCacheUpdater = makeAtomQueryCacheUpdater(false)
162
+
163
+ export const combineQueryCacheUpdaters = (first: QueryCacheUpdater, second: QueryCacheUpdater): QueryCacheUpdater => ({
164
+ update: (registry, query, input, updater) => {
165
+ first.update(registry, query, input, updater)
166
+ second.update(registry, query, input, updater)
167
+ }
168
+ })
169
+
170
+ let activeQueryCacheUpdater = atomQueryCacheUpdater
171
+
172
+ export const setQueryCacheUpdater = (updater: QueryCacheUpdater) => {
173
+ activeQueryCacheUpdater = updater
174
+ }
175
+
176
+ // Atom-engine query options (formerly reconstructed from @tanstack/vue-query types).
177
+ // The generic arity is kept so the exported interface signatures are unchanged for consumers.
19
178
  export interface CustomUseQueryOptions<
20
179
  TQueryFnData = unknown,
21
180
  TError = DefaultError,
22
181
  TData = TQueryFnData,
23
182
  TQueryData = TQueryFnData,
24
183
  TQueryKey extends QueryKey = QueryKey
25
- > extends
26
- Omit<
27
- QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>,
28
- "queryKey" | "queryFn" | "initialData" | "enabled" | "placeholderData"
29
- >
30
- {
31
- enabled?: MaybeRefOrGetter<boolean | undefined> | (() => Enabled<TQueryFnData, TError, TQueryData, TQueryKey>)
184
+ > {
185
+ readonly enabled?: MaybeRefOrGetter<boolean | undefined>
186
+ /** stale threshold in ms (or a Duration input) */
187
+ readonly staleTime?: number
188
+ /** garbage-collect after idle, ms (or "infinity") */
189
+ readonly gcTime?: number | "infinity"
190
+ readonly refetchOnWindowFocus?: boolean
191
+ readonly structuralSharing?: boolean
192
+ /** poll: re-fetch every N ms (tanstack refetchInterval) */
193
+ readonly refetchInterval?: number
194
+ readonly select?: (data: TQueryFnData) => TData
195
+ /** accepted for source compatibility; not used by the atom engine */
196
+ readonly retry?: boolean | number
197
+ readonly meta?: Record<string, unknown>
198
+ readonly _phantom?: [TQueryData, TQueryKey, TError]
32
199
  }
33
200
 
34
201
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
@@ -41,11 +208,8 @@ export interface CustomUndefinedInitialQueryOptions<
41
208
  TQueryData = TQueryFnData,
42
209
  TQueryKey extends QueryKey = QueryKey
43
210
  > extends CustomUseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey> {
44
- initialData?: undefined | InitialDataFunction<NonUndefinedGuard<TQueryFnData>> | NonUndefinedGuard<TQueryFnData>
45
- placeholderData?:
46
- | undefined
47
- | NonFunctionGuard<TQueryData>
48
- | PlaceholderDataFunction<NonFunctionGuard<TQueryData>, TError, NonFunctionGuard<TQueryData>, TQueryKey>
211
+ readonly initialData?: TQueryFnData | (() => TQueryFnData) | undefined
212
+ readonly placeholderData?: NonFunctionGuard<TQueryData> | ((prev: TQueryData | undefined) => TQueryData) | undefined
49
213
  }
50
214
  export interface CustomDefinedInitialQueryOptions<
51
215
  TQueryFnData = unknown,
@@ -54,11 +218,8 @@ export interface CustomDefinedInitialQueryOptions<
54
218
  TQueryData = TQueryFnData,
55
219
  TQueryKey extends QueryKey = QueryKey
56
220
  > extends CustomUseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey> {
57
- initialData: NonUndefinedGuard<TQueryFnData> | (() => NonUndefinedGuard<TQueryFnData>)
58
- placeholderData?:
59
- | undefined
60
- | NonFunctionGuard<TQueryData>
61
- | PlaceholderDataFunction<NonFunctionGuard<TQueryData>, TError, NonFunctionGuard<TQueryData>, TQueryKey>
221
+ readonly initialData: TQueryFnData | (() => TQueryFnData)
222
+ readonly placeholderData?: NonFunctionGuard<TQueryData> | ((prev: TQueryData | undefined) => TQueryData) | undefined
62
223
  }
63
224
 
64
225
  export interface CustomDefinedPlaceholderQueryOptions<
@@ -68,35 +229,387 @@ export interface CustomDefinedPlaceholderQueryOptions<
68
229
  TQueryData = TQueryFnData,
69
230
  TQueryKey extends QueryKey = QueryKey
70
231
  > extends CustomUseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey> {
71
- initialData?: NonUndefinedGuard<TQueryFnData> | (() => NonUndefinedGuard<TQueryFnData>) | undefined
72
- placeholderData:
73
- | NonFunctionGuard<TQueryData>
74
- | PlaceholderDataFunction<NonFunctionGuard<TQueryData>, TError, NonFunctionGuard<TQueryData>, TQueryKey>
232
+ readonly initialData?: TQueryFnData | (() => TQueryFnData) | undefined
233
+ readonly placeholderData: NonFunctionGuard<TQueryData> | ((prev: TQueryData | undefined) => TQueryData)
234
+ }
235
+
236
+ export interface AtomQueryNewOptions<TQueryFnData = unknown, TData = TQueryFnData> {
237
+ readonly enabled?: MaybeRefOrGetter<boolean | undefined>
238
+ readonly staleTime?: number
239
+ readonly idleTTL?: number | "infinity"
240
+ readonly gcTime?: number | "infinity"
241
+ readonly revalidateOnFocus?: boolean
242
+ readonly refetchOnWindowFocus?: boolean
243
+ readonly structuralSharing?: boolean
244
+ readonly refreshEvery?: number
245
+ readonly refetchInterval?: number
246
+ readonly select?: (data: TQueryFnData) => TData
247
+ }
248
+
249
+ export interface AtomStreamQueryOptions {
250
+ readonly staleTime?: number
251
+ readonly idleTTL?: number | "infinity"
252
+ readonly gcTime?: number | "infinity"
253
+ readonly revalidateOnFocus?: boolean
254
+ readonly refetchOnWindowFocus?: boolean
255
+ readonly refreshEvery?: number
256
+ readonly refetchInterval?: number
257
+ }
258
+
259
+ const normalizeQueryOptions = (options?: {
260
+ readonly staleTime?: number
261
+ readonly gcTime?: number | "infinity"
262
+ readonly idleTTL?: number | "infinity"
263
+ readonly refetchOnWindowFocus?: boolean
264
+ readonly revalidateOnFocus?: boolean
265
+ readonly structuralSharing?: boolean
266
+ readonly refetchInterval?: number
267
+ readonly refreshEvery?: number
268
+ }): AtomQueryOptions => {
269
+ const out: {
270
+ staleTime?: number
271
+ gcTime?: number | "infinity"
272
+ revalidateOnFocus?: boolean
273
+ structuralSharing?: boolean
274
+ refetchInterval?: number
275
+ } = {}
276
+ if (options?.staleTime !== undefined) out.staleTime = options.staleTime
277
+ const gcTime = options?.idleTTL ?? options?.gcTime
278
+ if (gcTime !== undefined) out.gcTime = gcTime
279
+ const revalidateOnFocus = options?.revalidateOnFocus ?? options?.refetchOnWindowFocus
280
+ if (revalidateOnFocus !== undefined) out.revalidateOnFocus = revalidateOnFocus
281
+ if (options?.structuralSharing !== undefined) out.structuralSharing = options.structuralSharing
282
+ const refetchInterval = options?.refreshEvery ?? options?.refetchInterval
283
+ if (refetchInterval !== undefined) out.refetchInterval = refetchInterval
284
+ return out
285
+ }
286
+
287
+ export const useAtomQuery = <A, E>(
288
+ atom: () => Atom.Atom<AsyncResult.AsyncResult<A, E>>
289
+ ): QueryView<A, E> => {
290
+ const registry = injectRegistry()
291
+ const atomRef = computed(atom)
292
+ const atomResult = useAtomValue(() => atomRef.value)
293
+ const result = computed(() => atomResult.value)
294
+ const refresh = () => registry.refresh(atomRef.value)
295
+ const awaitResult = () => awaitAtomResult(registry, atomRef.value)
296
+ const refetch = () =>
297
+ Effect.gen(function*() {
298
+ yield* refreshAtomWithCurrentSpan(registry, atomRef.value)
299
+ return yield* awaitResult()
300
+ })
301
+ const data = computed(() => Option.getOrUndefined(AsyncResult.value(result.value)))
302
+
303
+ return {
304
+ result,
305
+ data,
306
+ awaitResult,
307
+ refetch,
308
+ refresh,
309
+ registry,
310
+ atom: atomRef
311
+ }
312
+ }
313
+
314
+ export const useAtomSuspense = <A, E>(
315
+ atom: () => Atom.Atom<AsyncResult.AsyncResult<A, E>>
316
+ ): Promise<SuspenseQueryView<A, E>> => {
317
+ const [{ view, data }, isMounted, signal] = useScopedSuspenseSetup(() => {
318
+ const view = useAtomQuery(atom)
319
+ const data = latestDefined(() => view.data.value, "atom suspense")
320
+ return { view, data }
321
+ })
322
+
323
+ const eff = Effect.gen(function*() {
324
+ const exit = yield* view.awaitResult().pipe(Effect.exit)
325
+ if (!isMounted.value) {
326
+ return yield* Effect.interrupt
327
+ }
328
+ if (Exit.isFailure(exit)) {
329
+ return yield* Exit.failCause(exit.cause)
330
+ }
331
+
332
+ const fetch = (_options?: RefetchOptions) => view.refetch()
333
+ const handle = {
334
+ awaitResult: view.awaitResult,
335
+ refetch: view.refetch,
336
+ refresh: view.refresh,
337
+ registry: view.registry,
338
+ atom: view.atom
339
+ }
340
+ return Object.assign(
341
+ [
342
+ view.result,
343
+ data,
344
+ fetch,
345
+ handle
346
+ ] as const,
347
+ {
348
+ ...view,
349
+ data
350
+ }
351
+ )
352
+ })
353
+
354
+ return Effect.runPromise(eff, { signal })
355
+ }
356
+
357
+ export type StreamQueryPullValue<A> = {
358
+ readonly done: boolean
359
+ readonly items: ReadonlyArray<A>
360
+ }
361
+
362
+ export interface StreamQueryView<A, E> {
363
+ readonly result: ComputedRef<Atom.PullResult<A, E>>
364
+ readonly items: ComputedRef<ReadonlyArray<A>>
365
+ readonly latest: ComputedRef<A | undefined>
366
+ readonly done: ComputedRef<boolean>
367
+ readonly awaitResult: () => Effect.Effect<StreamQueryPullValue<A>, E | Cause.NoSuchElementError, never>
368
+ readonly pull: () => void
369
+ readonly pullAndAwait: () => Effect.Effect<StreamQueryPullValue<A>, E | Cause.NoSuchElementError, never>
370
+ readonly refresh: () => void
371
+ readonly registry: ReturnType<typeof injectRegistry>
372
+ readonly atom: ComputedRef<Atom.Writable<Atom.PullResult<A, E>, void>>
373
+ }
374
+
375
+ export const useAtomStreamQuery = <A, E>(
376
+ atom: () => Atom.Writable<Atom.PullResult<A, E>, void>
377
+ ): StreamQueryView<A, E> => {
378
+ const registry = injectRegistry()
379
+ const atomRef = computed(atom)
380
+ const atomResult = useAtomValue(() => atomRef.value)
381
+ const result = computed(() => atomResult.value)
382
+ const pull = () => registry.set(atomRef.value, void 0)
383
+ const refresh = () => registry.refresh(atomRef.value)
384
+ const awaitResult = () => awaitAtomResult(registry, atomRef.value)
385
+ const pullAndAwait = () =>
386
+ Effect.gen(function*() {
387
+ pull()
388
+ return yield* awaitResult()
389
+ })
390
+ const items = computed(() =>
391
+ Option.getOrElse(
392
+ Option.map(AsyncResult.value(result.value), (_) => _.items),
393
+ () => []
394
+ )
395
+ )
396
+ const latest = computed(() => items.value.at(-1))
397
+ const done = computed(() =>
398
+ Option.getOrElse(
399
+ Option.map(AsyncResult.value(result.value), (_) => _.done),
400
+ () => false
401
+ )
402
+ )
403
+
404
+ return {
405
+ result,
406
+ items,
407
+ latest,
408
+ done,
409
+ awaitResult,
410
+ pull,
411
+ pullAndAwait,
412
+ refresh,
413
+ registry,
414
+ atom: atomRef
415
+ }
75
416
  }
76
417
 
77
- export class KnownFiberFailure<E> extends Error {
78
- readonly error: unknown
79
- constructor(public effectCause: Cause.Cause<E>) {
80
- super("Query failed with cause: " + Cause.squash(effectCause))
81
- this.error = Cause.squash(effectCause)
418
+ const optionValue = <I>(
419
+ arr: I | WatchSource<I> | undefined | WatchSource<Option.Option<I>>,
420
+ options?: { readonly mode?: "optional"; readonly enabled?: MaybeRefOrGetter<boolean | undefined> }
421
+ ): readonly [{ readonly value: I }, ComputedRef<boolean>] => {
422
+ if (options?.mode === "optional") {
423
+ const getOption: () => Option.Option<I> = typeof arr === "function"
424
+ ? arr as () => Option.Option<I>
425
+ : () => (arr as { value: Option.Option<I> }).value
426
+ return [
427
+ {
428
+ get value() {
429
+ return Option.getOrUndefined(getOption()) as I
430
+ }
431
+ },
432
+ computed(() => Option.isSome(getOption()))
433
+ ] as const
82
434
  }
435
+ const req = !arr
436
+ ? ({ value: undefined as I })
437
+ : typeof arr === "function"
438
+ ? ({
439
+ get value() {
440
+ return (arr as any)()
441
+ }
442
+ })
443
+ : (ref(arr) as any)
444
+ const enabled = options?.enabled
445
+ return [req, computed(() => enabled === undefined ? true : !!toValue(enabled))] as const
83
446
  }
84
447
 
85
- export const makeQuery = <R>(getRuntime: () => ServiceMap.ServiceMap<R>) => {
448
+ const observedAtom = <A, E>(
449
+ atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
450
+ options?: {
451
+ readonly staleTime?: number
452
+ readonly gcTime?: number | "infinity"
453
+ readonly idleTTL?: number | "infinity"
454
+ readonly refetchOnWindowFocus?: boolean
455
+ readonly revalidateOnFocus?: boolean
456
+ readonly structuralSharing?: boolean
457
+ readonly refetchInterval?: number
458
+ readonly refreshEvery?: number
459
+ }
460
+ ): Atom.Atom<AsyncResult.AsyncResult<A, E>> => withQueryOptions(atom, normalizeQueryOptions(options))
461
+
462
+ const observedStreamAtom = <A, E>(
463
+ atom: Atom.Writable<Atom.PullResult<A, E>, void>,
464
+ options?: AtomStreamQueryOptions
465
+ ): Atom.Writable<Atom.PullResult<A, E>, void> => {
466
+ let next = atom
467
+ const refetchInterval = options?.refreshEvery ?? options?.refetchInterval
468
+ if (refetchInterval !== undefined) next = Atom.withRefresh(refetchInterval)(next)
469
+ const gcTime = options?.idleTTL ?? options?.gcTime
470
+ if (gcTime === "infinity") return Atom.keepAlive(next)
471
+ if (gcTime !== undefined) return Atom.setIdleTTL(next, gcTime)
472
+ return next
473
+ }
474
+
475
+ const queryAtomFor = <I, A, E, TData>(
476
+ rt: AtomClientRuntime,
477
+ q: QueryFamilyDescriptor<I, A, E>,
478
+ arg: I,
479
+ options?: Omit<AtomQueryNewOptions<A, TData>, "select"> | Omit<CustomUseQueryOptions<A, E, TData>, "select">
480
+ ): Atom.Atom<AsyncResult.AsyncResult<A, E>> => {
481
+ const family = getQueryFamily(rt, q)
482
+ return observedAtom(family(arg), options)
483
+ }
484
+
485
+ const makeQueryView = <I, A, E, TData>(
486
+ getAtomRt: () => AtomClientRuntime,
487
+ q: QueryFamilyDescriptor<I, A, E>,
488
+ arg: I | WatchSource<I> | undefined | WatchSource<Option.Option<I>>,
489
+ options?: (AtomQueryNewOptions<A, TData> | CustomUseQueryOptions<A, E, TData>) & {
490
+ readonly mode?: "optional"
491
+ }
492
+ ): QueryView<TData, E> => {
493
+ const atomRt = getAtomRt()
494
+ const registry = injectRegistry()
495
+ const [req, enabledRef] = optionValue<I>(arg, options)
496
+ const family = getQueryFamily(atomRt, q)
497
+ const atomRef = computed(() => enabledRef.value ? observedAtom(family(req.value), options) : disabledQueryAtom)
498
+ const rawResult = useAtomValue(() => atomRef.value) as ComputedRef<AsyncResult.AsyncResult<A, E>>
499
+ const select = options?.select
500
+ const result = (select
501
+ ? computed(() => AsyncResult.map(rawResult.value, select))
502
+ : rawResult) as ComputedRef<AsyncResult.AsyncResult<TData, E>>
503
+ const refresh = () => registry.refresh(atomRef.value)
504
+ const awaitResult = () =>
505
+ select
506
+ ? awaitAtomResult(registry, atomRef.value).pipe(Effect.map(select))
507
+ : awaitAtomResult(registry, atomRef.value)
508
+ const refetch = () =>
509
+ Effect.gen(function*() {
510
+ yield* refreshAtomWithCurrentSpan(registry, atomRef.value)
511
+ return yield* awaitResult()
512
+ })
513
+ const staleMs = staleTimeMsOf(normalizeQueryOptions(options))
514
+ onMounted(() => {
515
+ if (!enabledRef.value) return
516
+ if (isStaleResult(registry.get(atomRef.value), staleMs)) refresh()
517
+ })
518
+ const data = computed(() => Option.getOrUndefined(AsyncResult.value(result.value)))
519
+
520
+ return {
521
+ result,
522
+ data,
523
+ awaitResult,
524
+ refetch,
525
+ refresh,
526
+ registry,
527
+ atom: atomRef
528
+ }
529
+ }
530
+
531
+ export const makeQueryFamily = <R>(_getRuntime: () => Context.Context<R>, getAtomRt: () => AtomClientRuntime) => {
532
+ const useQueryFamily: {
533
+ <I, E, A, Request extends Req, Name extends string>(
534
+ q: RequestHandlerWithInput<I, A, E, R, Request, Name>
535
+ ): QueryAtomFamily<I, A, E>
536
+ } = <I, E, A, Request extends Req, Name extends string>(
537
+ q: RequestHandlerWithInput<I, A, E, R, Request, Name>
538
+ ) => getQueryFamily(getAtomRt(), q)
539
+
540
+ return useQueryFamily
541
+ }
542
+
543
+ export const makeQueryAtom = <R>(_getRuntime: () => Context.Context<R>, getAtomRt: () => AtomClientRuntime) => {
544
+ const useQueryAtom: {
545
+ <I, E, A, Request extends Req, Name extends string>(
546
+ q: RequestHandlerWithInput<I, A, E, R, Request, Name>
547
+ ): {
548
+ <TData = A>(
549
+ arg: I,
550
+ options?: Omit<AtomQueryNewOptions<A, TData>, "select">
551
+ ): Atom.Atom<AsyncResult.AsyncResult<A, E>>
552
+ }
553
+ } = <I, E, A, Request extends Req, Name extends string>(
554
+ q: RequestHandlerWithInput<I, A, E, R, Request, Name>
555
+ ) =>
556
+ <TData = A>(
557
+ arg: I,
558
+ options?: Omit<AtomQueryNewOptions<A, TData>, "select">
559
+ ) => queryAtomFor(getAtomRt(), q, arg, options)
560
+
561
+ return useQueryAtom
562
+ }
563
+
564
+ export const makeQueryNew = <R>(_getRuntime: () => Context.Context<R>, getAtomRt: () => AtomClientRuntime) => {
565
+ const useQueryNew: {
566
+ <I, E, A, Request extends Req, Name extends string>(
567
+ q: RequestHandlerWithInput<I, A, E, R, Request, Name>
568
+ ): {
569
+ <TData = A>(
570
+ arg: WatchSource<Option.Option<I>>,
571
+ options: Omit<AtomQueryNewOptions<A, TData>, "enabled"> & { mode: "optional" }
572
+ ): QueryView<TData, E>
573
+
574
+ <TData = A>(
575
+ arg: I | WatchSource<I> | undefined,
576
+ options?: AtomQueryNewOptions<A, TData>
577
+ ): QueryView<TData, E>
578
+ }
579
+ } = <I, E, A, Request extends Req, Name extends string>(
580
+ q: RequestHandlerWithInput<I, A, E, R, Request, Name>
581
+ ) =>
582
+ <TData = A>(
583
+ arg: I | WatchSource<I> | undefined | WatchSource<Option.Option<I>>,
584
+ options?: AtomQueryNewOptions<A, TData> & { readonly mode?: "optional" }
585
+ ) => makeQueryView<I, A, E, TData>(getAtomRt, q, arg, options)
586
+
587
+ return useQueryNew
588
+ }
589
+
590
+ export const makeQuery = <R>(_getRuntime: () => Context.Context<R>, getAtomRt: () => AtomClientRuntime) => {
86
591
  const useQuery_: {
87
592
  <I, A, E, Request extends Req, Name extends string>(
88
- q:
89
- | RequestHandlerWithInput<I, A, E, R, Request, Name>
90
- | RequestHandler<A, E, R, Request, Name>
593
+ q: RequestHandlerWithInput<I, A, E, R, Request, Name>
91
594
  ): {
595
+ <TData = A>(
596
+ arg: WatchSource<Option.Option<I>>,
597
+ options: Omit<CustomUndefinedInitialQueryOptions<A, E, TData>, "enabled"> & { mode: "optional" }
598
+ ): readonly [
599
+ ComputedRef<AsyncResult.AsyncResult<TData, E>>,
600
+ ComputedRef<TData | undefined>,
601
+ (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, CauseException<E>>>,
602
+ UseQueryDefinedReturnType<TData, CauseException<E>>
603
+ ]
604
+
92
605
  <TData = A>(
93
606
  arg: I | WatchSource<I> | undefined,
94
607
  options?: CustomUndefinedInitialQueryOptions<A, E, TData>
95
608
  ): readonly [
96
609
  ComputedRef<AsyncResult.AsyncResult<TData, E>>,
97
610
  ComputedRef<TData | undefined>,
98
- (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, KnownFiberFailure<E>>, never, never>,
99
- UseQueryDefinedReturnType<TData, KnownFiberFailure<E>>
611
+ (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, CauseException<E>>>,
612
+ UseQueryDefinedReturnType<TData, CauseException<E>>
100
613
  ]
101
614
 
102
615
  <TData = A>(
@@ -105,8 +618,8 @@ export const makeQuery = <R>(getRuntime: () => ServiceMap.ServiceMap<R>) => {
105
618
  ): readonly [
106
619
  ComputedRef<AsyncResult.AsyncResult<TData, E>>,
107
620
  ComputedRef<TData>,
108
- (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, KnownFiberFailure<E>>, never, never>,
109
- UseQueryDefinedReturnType<TData, KnownFiberFailure<E>>
621
+ (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, CauseException<E>>>,
622
+ UseQueryDefinedReturnType<TData, CauseException<E>>
110
623
  ]
111
624
 
112
625
  <TData = A>(
@@ -115,253 +628,178 @@ export const makeQuery = <R>(getRuntime: () => ServiceMap.ServiceMap<R>) => {
115
628
  ): readonly [
116
629
  ComputedRef<AsyncResult.AsyncResult<TData, E>>,
117
630
  ComputedRef<TData>,
118
- (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, KnownFiberFailure<E>>, never, never>,
119
- UseQueryDefinedReturnType<TData, KnownFiberFailure<E>>
631
+ (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, CauseException<E>>>,
632
+ UseQueryDefinedReturnType<TData, CauseException<E>>
120
633
  ]
121
634
  }
122
635
  } = <I, A, E, Request extends Req, Name extends string>(
123
- q:
124
- | RequestHandlerWithInput<I, A, E, R, Request, Name>
125
- | RequestHandler<A, E, R, Request, Name>
636
+ q: RequestHandlerWithInput<I, A, E, R, Request, Name>
126
637
  ) =>
127
638
  <TData = A>(
128
- arg: I | WatchSource<I> | undefined,
129
- // todo QueryKey type would be [string, ...string[]], but with I it would be [string, ...string[], I]
639
+ arg: I | WatchSource<I> | undefined | WatchSource<Option.Option<I>>,
130
640
  options?: any
131
- // TODO
132
641
  ) => {
133
- // we wrap into KnownFiberFailure because we want to keep the full cause of the failure.
134
- const runPromise = flow(Effect.runPromiseExitWith(getRuntime()), (_) =>
135
- _.then(
136
- Exit.match({
137
- onFailure: (cause) => Promise.reject(new KnownFiberFailure(cause)),
138
- onSuccess: (value) => Promise.resolve(value)
139
- })
140
- ))
141
- const arr = arg
142
- const req: { value: I } = !arg
143
- ? undefined
144
- : typeof arr === "function"
145
- ? ({
146
- get value() {
147
- return (arr as any)()
148
- }
149
- } as any)
150
- : ref(arg)
151
- const queryKey = makeQueryKey(q)
152
- const handler = q.handler
153
-
154
- const defaultOptions = {
155
- // we do not want to throw errors, because we turn the success and error responses into a Result type
156
- // why don't we turn the error/success response into a Result type before returning to tanstack query? because we want to leverage tanstack query's retry and caching mechanism, which relies on throwing errors to trigger retries, and we don't want to interfere with that by catching the errors too early.
157
- // but if we allow tanstack query to throw, it will trigger the error boundary in Vue - via a "watcher callback" error - which we currently report and log, which is not what we want.
158
- // TODO: we might want to rethink the strategy of how to handle errors that happen after the initial load.
159
- // For suspense, the initial load is captured by the suspense boundary.
160
- // For subsequent loads (or non suspense use) we currently are required to use the QueryResult component to conditionally render error/loading/etc.
161
- throwOnError: false
162
- }
642
+ const view = makeQueryView<I, A, E, TData>(getAtomRt, q, arg, options)
163
643
 
164
- const r = useTanstackQuery<A, KnownFiberFailure<E>, TData>(
165
- Effect.isEffect(handler)
166
- ? {
167
- ...defaultOptions,
168
- ...options,
169
- retry: (retryCount, error) => {
170
- if (error instanceof KnownFiberFailure) {
171
- if (!isHttpClientError(error.error) && !S.is(ServiceUnavailableError)(error.error)) {
172
- return false
173
- }
174
- }
175
-
176
- return retryCount < 5
177
- },
178
- queryKey,
179
- queryFn: ({ meta, signal }) =>
180
- runPromise(
181
- handler
182
- .pipe(
183
- Effect.tapCauseIf(Cause.hasDies, (cause) => reportRuntimeError(cause)),
184
- Effect.withSpan(`query ${q.id}`, {}, { captureStackTrace: false }),
185
- meta?.["span"] ? Effect.withParentSpan(meta["span"] as Span) : (_) => _
186
- ),
187
- { signal }
188
- )
189
- }
190
- : {
191
- ...defaultOptions,
192
- ...options,
193
- retry: (retryCount, error) => {
194
- if (error instanceof KnownFiberFailure) {
195
- if (!isHttpClientError(error.error) && !S.is(ServiceUnavailableError)(error.error)) {
196
- return false
197
- }
198
- }
199
-
200
- return retryCount < 5
201
- },
202
- queryKey: [...queryKey, req],
203
- queryFn: ({ meta, signal }) =>
204
- runPromise(
205
- handler(req.value)
206
- .pipe(
207
- Effect.tapCauseIf(Cause.hasDies, (cause) => reportRuntimeError(cause)),
208
- Effect.withSpan(`query ${q.id}`, {}, { captureStackTrace: false }),
209
- meta?.["span"] ? Effect.withParentSpan(meta["span"] as Span) : (_) => _
210
- ),
211
- { signal }
212
- )
213
- }
214
- )
215
-
216
- const latestSuccess = shallowRef<TData>()
217
- const result = computed((): AsyncResult.AsyncResult<TData, E> =>
218
- swrToQuery({
219
- error: r.error.value ?? undefined,
220
- data: r.data.value === undefined ? latestSuccess.value : r.data.value, // we fall back to existing data, as tanstack query might loose it when the key changes
221
- isValidating: r.isFetching.value
222
- })
223
- )
224
- // not using `computed` here as we have a circular dependency
225
- watch(result, (value) => latestSuccess.value = Option.getOrUndefined(AsyncResult.value(value)), { immediate: true })
644
+ // 4th element is internal-only; the public `.suspense()` Promise boundary lives in makeClient.
645
+ const handle = {
646
+ awaitResult: view.awaitResult,
647
+ refetch: view.refetch,
648
+ refresh: view.refresh,
649
+ registry: view.registry,
650
+ atom: view.atom
651
+ }
226
652
 
227
653
  return [
228
- result,
229
- computed(() => latestSuccess.value),
230
- // one thing to keep in mind is that span will be disconnected as Context does not pass from outside.
231
- // TODO: consider how we should handle the Result here which is `QueryObserverResult<A, E>`
232
- // and always ends up in the success channel, even when error..
233
- (options?: RefetchOptions) =>
234
- Effect.currentSpan.pipe(
235
- Effect.orElseSucceed(() => null),
236
- Effect.flatMap((span) => Effect.promise(() => r.refetch({ ...options, updateMeta: { span } })))
237
- ),
238
- r
654
+ view.result,
655
+ view.data,
656
+ (_options?: RefetchOptions) => view.refetch(),
657
+ handle
239
658
  ] as any
240
659
  }
241
660
 
242
- function swrToQuery<E, A>(r: {
243
- error: KnownFiberFailure<E> | undefined
244
- data: A | undefined
245
- isValidating: boolean
246
- }): AsyncResult.AsyncResult<A, E> {
247
- if (r.error !== undefined) {
248
- return AsyncResult.failureWithPrevious(
249
- r.error.effectCause,
250
- {
251
- previous: r.data === undefined ? Option.none() : Option.some(AsyncResult.success(r.data)),
252
- waiting: r.isValidating
253
- }
254
- )
255
- }
256
- if (r.data !== undefined) {
257
- return AsyncResult.success<A, E>(r.data, { waiting: r.isValidating })
258
- }
259
-
260
- return AsyncResult.initial(r.isValidating)
261
- }
262
-
263
661
  const useQuery: {
264
662
  /**
265
663
  * Effect results are passed to the caller, including errors.
664
+ * When `I = void` the input argument may be omitted.
266
665
  * @deprecated use client helpers instead (.query())
267
666
  */
268
- <E, A, Request extends Req, Name extends string>(
269
- self: RequestHandler<A, E, R, Request, Name>
667
+ <I, E, A, Request extends Req, Name extends string>(
668
+ self: RequestHandlerWithInput<I, A, E, R, Request, Name>
270
669
  ): {
271
- // required options, with initialData
272
- /**
273
- * Effect results are passed to the caller, including errors.
274
- */
275
670
  <TData = A>(
276
- options: CustomDefinedInitialQueryOptions<A, KnownFiberFailure<E>, TData>
671
+ arg: WatchSource<Option.Option<I>>,
672
+ options: Omit<CustomUndefinedInitialQueryOptions<A, CauseException<E>, TData>, "enabled"> & { mode: "optional" }
277
673
  ): readonly [
278
674
  ComputedRef<AsyncResult.AsyncResult<TData, E>>,
279
- ComputedRef<TData>,
280
- (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, KnownFiberFailure<E>>>,
675
+ ComputedRef<TData | undefined>,
676
+ (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, CauseException<E>>>,
281
677
  UseQueryReturnType<any, any>
282
678
  ]
283
679
  <TData = A>(
284
- options: CustomDefinedPlaceholderQueryOptions<A, E, TData>
680
+ arg: I | WatchSource<I>,
681
+ options: CustomDefinedInitialQueryOptions<A, CauseException<E>, TData>
285
682
  ): readonly [
286
683
  ComputedRef<AsyncResult.AsyncResult<TData, E>>,
287
684
  ComputedRef<TData>,
288
- (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, KnownFiberFailure<E>>, never, never>,
289
- UseQueryDefinedReturnType<TData, KnownFiberFailure<E>>
290
- ]
291
- // optional options, optional A
292
- /**
293
- * Effect results are passed to the caller, including errors.
294
- */
295
- <TData = A>(options?: CustomUndefinedInitialQueryOptions<A, KnownFiberFailure<E>, TData>): readonly [
296
- ComputedRef<AsyncResult.AsyncResult<A, E>>,
297
- ComputedRef<A | undefined>,
298
- (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, KnownFiberFailure<E>>>,
685
+ (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, CauseException<E>>>,
299
686
  UseQueryReturnType<any, any>
300
687
  ]
301
- }
302
- /**
303
- * Effect results are passed to the caller, including errors.
304
- * @deprecated use client helpers instead (.query())
305
- */
306
- <Arg, E, A, Request extends Req, Name extends string>(
307
- self: RequestHandlerWithInput<Arg, A, E, R, Request, Name>
308
- ): {
309
- // required options, with initialData
310
- /**
311
- * Effect results are passed to the caller, including errors.
312
- */
313
688
  <TData = A>(
314
- arg: Arg | WatchSource<Arg>,
315
- options: CustomDefinedInitialQueryOptions<A, KnownFiberFailure<E>, TData>
689
+ arg: I | WatchSource<I>,
690
+ options: CustomDefinedPlaceholderQueryOptions<A, CauseException<E>, TData>
316
691
  ): readonly [
317
692
  ComputedRef<AsyncResult.AsyncResult<TData, E>>,
318
693
  ComputedRef<TData>,
319
- (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, KnownFiberFailure<E>>>,
694
+ (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, CauseException<E>>>,
320
695
  UseQueryReturnType<any, any>
321
696
  ]
322
- // required options, with placeholderData
323
- /**
324
- * Effect results are passed to the caller, including errors.
325
- */
326
697
  <TData = A>(
327
- arg: Arg | WatchSource<Arg>,
328
- options: CustomDefinedPlaceholderQueryOptions<A, KnownFiberFailure<E>, TData>
329
- ): readonly [
330
- ComputedRef<AsyncResult.AsyncResult<TData, E>>,
331
- ComputedRef<TData>,
332
- (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, KnownFiberFailure<E>>>,
333
- UseQueryReturnType<any, any>
334
- ]
335
- // optional options, optional A
336
- /**
337
- * Effect results are passed to the caller, including errors.
338
- */
339
- <TData = A>(
340
- arg: Arg | WatchSource<Arg>,
341
- options?: CustomUndefinedInitialQueryOptions<A, KnownFiberFailure<E>, TData>
698
+ arg: I | WatchSource<I>,
699
+ options?: CustomUndefinedInitialQueryOptions<A, CauseException<E>, TData>
342
700
  ): readonly [
343
701
  ComputedRef<AsyncResult.AsyncResult<TData, E>>,
344
702
  ComputedRef<TData | undefined>,
345
- (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, KnownFiberFailure<E>>>,
703
+ (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<TData, CauseException<E>>>,
346
704
  UseQueryReturnType<any, any>
347
705
  ]
348
706
  }
349
- } = (
707
+ } = ((
350
708
  self: any
351
709
  ) => {
352
710
  const q = useQuery_(self)
353
-
354
- return (argOrOptions?: any, options?: any) =>
355
- Effect.isEffect(self.handler)
356
- ? q(undefined, argOrOptions)
357
- : q(argOrOptions, options)
358
- }
711
+ return (arg?: any, options?: any) => q(arg, options)
712
+ }) as any
359
713
  return useQuery
360
714
  }
361
715
 
362
716
  // eslint-disable-next-line @typescript-eslint/no-empty-object-type
363
717
  export interface MakeQuery2<R> extends ReturnType<typeof makeQuery<R>> {}
364
718
 
719
+ const streamQueryAtomFor = <I, A, E>(
720
+ rt: AtomClientRuntime,
721
+ q: StreamQueryFamilyDescriptor<I, A, E>,
722
+ arg: I,
723
+ options?: AtomStreamQueryOptions
724
+ ): Atom.Writable<Atom.PullResult<A, E>, void> => {
725
+ const family = getStreamQueryFamily(rt, q)
726
+ return observedStreamAtom(family(arg), options)
727
+ }
728
+
729
+ export const makeStreamQueryFamily = <R>(_getRuntime: () => Context.Context<R>, getAtomRt: () => AtomClientRuntime) => {
730
+ const useStreamQueryFamily: {
731
+ <I, E, A, Request extends Req, Name extends string>(
732
+ q: RequestStreamHandlerWithInput<I, A, E, R, Request, Name>
733
+ ): StreamQueryAtomFamily<I, A, E>
734
+ } = <I, E, A, Request extends Req, Name extends string>(
735
+ q: RequestStreamHandlerWithInput<I, A, E, R, Request, Name>
736
+ ) => getStreamQueryFamily(getAtomRt(), q)
737
+
738
+ return useStreamQueryFamily
739
+ }
740
+
741
+ export const makeStreamQueryAtom = <R>(_getRuntime: () => Context.Context<R>, getAtomRt: () => AtomClientRuntime) => {
742
+ const useStreamQueryAtom: {
743
+ <I, E, A, Request extends Req, Name extends string>(
744
+ q: RequestStreamHandlerWithInput<I, A, E, R, Request, Name>
745
+ ): (arg: I, options?: AtomStreamQueryOptions) => Atom.Writable<Atom.PullResult<A, E>, void>
746
+ } = <I, E, A, Request extends Req, Name extends string>(
747
+ q: RequestStreamHandlerWithInput<I, A, E, R, Request, Name>
748
+ ) =>
749
+ (arg: I, options?: AtomStreamQueryOptions) => streamQueryAtomFor(getAtomRt(), q, arg, options)
750
+
751
+ return useStreamQueryAtom
752
+ }
753
+
754
+ export const makeStreamQueryNew = <R>(_getRuntime: () => Context.Context<R>, getAtomRt: () => AtomClientRuntime) => {
755
+ const useStreamQueryNew: {
756
+ <I, E, A, Request extends Req, Name extends string>(
757
+ q: RequestStreamHandlerWithInput<I, A, E, R, Request, Name>
758
+ ): (arg: MaybeRefOrGetter<I>, options?: AtomStreamQueryOptions) => StreamQueryView<A, E>
759
+ } = <I, E, A, Request extends Req, Name extends string>(
760
+ q: RequestStreamHandlerWithInput<I, A, E, R, Request, Name>
761
+ ) =>
762
+ (arg: MaybeRefOrGetter<I>, options?: AtomStreamQueryOptions) =>
763
+ useAtomStreamQuery(() => streamQueryAtomFor(getAtomRt(), q, toValue(arg), options))
764
+
765
+ return useStreamQueryNew
766
+ }
767
+
768
+ type StreamQueryResult<A, E> = readonly [
769
+ ComputedRef<AsyncResult.AsyncResult<A[], E>>,
770
+ ComputedRef<A[] | undefined>,
771
+ (options?: RefetchOptions) => Effect.Effect<QueryObserverResult<A[], CauseException<E>>>,
772
+ UseQueryReturnType<any, any>
773
+ ]
774
+
775
+ export const makeStreamQuery = <R>(
776
+ getRuntime: () => Context.Context<R>,
777
+ getAtomRt: () => AtomClientRuntime
778
+ ) => {
779
+ const query = makeQuery(getRuntime, getAtomRt)
780
+ // A stream query is an ordinary atom query over an effect that collects the whole stream
781
+ // into an array (`Stream.runCollect`). It reuses all the atom machinery (family cache, swr,
782
+ // invalidation, structural sharing). Note: unlike the old tanstack `streamedQuery`, the result
783
+ // appears once the stream completes, not incrementally (stream queries are not used today).
784
+ const streamQuery_: {
785
+ <I, E, A, Request extends Req, Name extends string>(
786
+ q: RequestStreamHandlerWithInput<I, A, E, R, Request, Name>
787
+ ): (arg: I | WatchSource<I>) => StreamQueryResult<A, E>
788
+ } = (q: any) => {
789
+ const hook = query({
790
+ id: q.id,
791
+ options: q.options,
792
+ handler: (i: any) => Stream.runCollect(q.handler(i)).pipe(Effect.map((chunk) => [...chunk]))
793
+ } as any)
794
+ return (arg?: any) => hook(arg) as any
795
+ }
796
+
797
+ return streamQuery_
798
+ }
799
+
800
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
801
+ export interface MakeStreamQuery2<R> extends ReturnType<typeof makeStreamQuery<R>> {}
802
+
365
803
  function orPrevious<E, A>(result: AsyncResult.AsyncResult<A, E>) {
366
804
  return AsyncResult.isFailure(result) && Option.isSome(result.previousSuccess)
367
805
  ? AsyncResult.success(result.previousSuccess.value, { waiting: result.waiting })
@@ -409,29 +847,14 @@ export function composeQueries<
409
847
  }
410
848
 
411
849
  export const useUpdateQuery = () => {
412
- const queryClient = useQueryClient()
850
+ const registry = injectRegistry()
413
851
 
414
852
  const f: {
415
- <A>(
416
- query: RequestHandler<A, any, any, any, any>,
417
- updater: (data: NoInfer<A>) => NoInfer<A>
418
- ): void
419
- <I, A>(
420
- query: RequestHandlerWithInput<I, A, any, any, any, any>,
853
+ <I, A, E, R, Request extends Req, Name extends string>(
854
+ query: RequestHandlerWithInput<I, A, E, R, Request, Name>,
421
855
  input: I,
422
856
  updater: (data: NoInfer<A>) => NoInfer<A>
423
857
  ): void
424
- } = (query: any, updateOrInput: any, updaterMaybe?: any) => {
425
- const updater = updaterMaybe !== undefined ? updaterMaybe : updateOrInput
426
- const key = updaterMaybe !== undefined
427
- ? [...makeQueryKey(query), updateOrInput]
428
- : makeQueryKey(query)
429
- const data = queryClient.getQueryData(key)
430
- if (data) {
431
- queryClient.setQueryData(key, updater)
432
- } else {
433
- console.warn(`Query data for key ${key} not found`, key)
434
- }
435
- }
858
+ } = (query, input, updater) => activeQueryCacheUpdater.update(registry, query, input, updater)
436
859
  return f
437
860
  }