@ttt-productions/query-core 0.14.22 → 0.14.24
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.
- package/README.md +6 -6
- package/dist/defaults.d.ts +0 -15
- package/dist/defaults.d.ts.map +1 -1
- package/dist/defaults.js +0 -15
- package/dist/defaults.js.map +1 -1
- package/dist/firestore/types.d.ts +5 -49
- package/dist/firestore/types.d.ts.map +1 -1
- package/dist/firestore/types.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/dist/keys.d.ts +0 -22
- package/dist/keys.d.ts.map +1 -1
- package/dist/keys.js +0 -4
- package/dist/keys.js.map +1 -1
- package/dist/react/cache-helpers.d.ts +0 -32
- package/dist/react/cache-helpers.d.ts.map +1 -1
- package/dist/react/cache-helpers.js +0 -28
- package/dist/react/cache-helpers.js.map +1 -1
- package/dist/react/callables/create-callables.d.ts +40 -0
- package/dist/react/callables/create-callables.d.ts.map +1 -0
- package/dist/react/callables/create-callables.js +101 -0
- package/dist/react/callables/create-callables.js.map +1 -0
- package/dist/react/defaults.d.ts +0 -4
- package/dist/react/defaults.d.ts.map +1 -1
- package/dist/react/defaults.js +2 -6
- package/dist/react/defaults.js.map +1 -1
- package/dist/react/domain-events/cache-invalidation.d.ts +0 -37
- package/dist/react/domain-events/cache-invalidation.d.ts.map +1 -1
- package/dist/react/domain-events/cache-invalidation.js +4 -53
- package/dist/react/domain-events/cache-invalidation.js.map +1 -1
- package/dist/react/domain-events/create-domain-event-invalidator.d.ts +0 -18
- package/dist/react/domain-events/create-domain-event-invalidator.d.ts.map +1 -1
- package/dist/react/domain-events/create-domain-event-invalidator.js +0 -5
- package/dist/react/domain-events/create-domain-event-invalidator.js.map +1 -1
- package/dist/react/firestore/absence-scheduler.d.ts +0 -28
- package/dist/react/firestore/absence-scheduler.d.ts.map +1 -1
- package/dist/react/firestore/absence-scheduler.js +1 -39
- package/dist/react/firestore/absence-scheduler.js.map +1 -1
- package/dist/react/firestore/batch-doc-loader.d.ts +0 -30
- package/dist/react/firestore/batch-doc-loader.d.ts.map +1 -1
- package/dist/react/firestore/batch-doc-loader.js +0 -34
- package/dist/react/firestore/batch-doc-loader.js.map +1 -1
- package/dist/react/firestore/context.d.ts +0 -19
- package/dist/react/firestore/context.d.ts.map +1 -1
- package/dist/react/firestore/context.js +0 -19
- package/dist/react/firestore/context.js.map +1 -1
- package/dist/react/firestore/doc-subscription-registry.d.ts +0 -23
- package/dist/react/firestore/doc-subscription-registry.d.ts.map +1 -1
- package/dist/react/firestore/doc-subscription-registry.js +5 -26
- package/dist/react/firestore/doc-subscription-registry.js.map +1 -1
- package/dist/react/firestore/infinite-helpers.d.ts +0 -12
- package/dist/react/firestore/infinite-helpers.d.ts.map +1 -1
- package/dist/react/firestore/infinite-helpers.js +0 -12
- package/dist/react/firestore/infinite-helpers.js.map +1 -1
- package/dist/react/firestore/resubscribe.d.ts +0 -20
- package/dist/react/firestore/resubscribe.d.ts.map +1 -1
- package/dist/react/firestore/resubscribe.js +0 -20
- package/dist/react/firestore/resubscribe.js.map +1 -1
- package/dist/react/firestore/subscription-status.d.ts +0 -29
- package/dist/react/firestore/subscription-status.d.ts.map +1 -1
- package/dist/react/firestore/subscription-status.js +1 -34
- package/dist/react/firestore/subscription-status.js.map +1 -1
- package/dist/react/firestore/types.d.ts +0 -64
- package/dist/react/firestore/types.d.ts.map +1 -1
- package/dist/react/firestore/types.js +0 -3
- package/dist/react/firestore/types.js.map +1 -1
- package/dist/react/firestore/use-firestore-collection.d.ts +0 -20
- package/dist/react/firestore/use-firestore-collection.d.ts.map +1 -1
- package/dist/react/firestore/use-firestore-collection.js +1 -35
- package/dist/react/firestore/use-firestore-collection.js.map +1 -1
- package/dist/react/firestore/use-firestore-count.d.ts +0 -15
- package/dist/react/firestore/use-firestore-count.d.ts.map +1 -1
- package/dist/react/firestore/use-firestore-count.js +0 -15
- package/dist/react/firestore/use-firestore-count.js.map +1 -1
- package/dist/react/firestore/use-firestore-doc.d.ts +0 -23
- package/dist/react/firestore/use-firestore-doc.d.ts.map +1 -1
- package/dist/react/firestore/use-firestore-doc.js +3 -40
- package/dist/react/firestore/use-firestore-doc.js.map +1 -1
- package/dist/react/firestore/use-firestore-infinite.d.ts +0 -29
- package/dist/react/firestore/use-firestore-infinite.d.ts.map +1 -1
- package/dist/react/firestore/use-firestore-infinite.js +0 -32
- package/dist/react/firestore/use-firestore-infinite.js.map +1 -1
- package/dist/react/firestore/use-firestore-live-infinite.d.ts +0 -34
- package/dist/react/firestore/use-firestore-live-infinite.d.ts.map +1 -1
- package/dist/react/firestore/use-firestore-live-infinite.js +1 -35
- package/dist/react/firestore/use-firestore-live-infinite.js.map +1 -1
- package/dist/react/firestore/use-firestore-mutations.d.ts.map +1 -1
- package/dist/react/firestore/use-firestore-mutations.js +6 -5
- package/dist/react/firestore/use-firestore-mutations.js.map +1 -1
- package/dist/react/firestore/use-firestore-paginated.d.ts +0 -30
- package/dist/react/firestore/use-firestore-paginated.d.ts.map +1 -1
- package/dist/react/firestore/use-firestore-paginated.js +2 -33
- package/dist/react/firestore/use-firestore-paginated.js.map +1 -1
- package/dist/react/firestore/useBatchFirestoreDocs.d.ts +1 -123
- package/dist/react/firestore/useBatchFirestoreDocs.d.ts.map +1 -1
- package/dist/react/firestore/useBatchFirestoreDocs.js +23 -64
- package/dist/react/firestore/useBatchFirestoreDocs.js.map +1 -1
- package/dist/react/index.d.ts +4 -0
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +2 -13
- package/dist/react/index.js.map +1 -1
- package/dist/react/pending-mutations.d.ts +1 -21
- package/dist/react/pending-mutations.d.ts.map +1 -1
- package/dist/react/pending-mutations.js +1 -32
- package/dist/react/pending-mutations.js.map +1 -1
- package/dist/react/provider.d.ts +0 -5
- package/dist/react/provider.d.ts.map +1 -1
- package/dist/react/provider.js +0 -4
- package/dist/react/provider.js.map +1 -1
- package/dist/react/query-client.d.ts +0 -4
- package/dist/react/query-client.d.ts.map +1 -1
- package/dist/react/query-client.js +0 -4
- package/dist/react/query-client.js.map +1 -1
- package/dist/react/search/types.d.ts +0 -12
- package/dist/react/search/types.d.ts.map +1 -1
- package/dist/react/search/types.js.map +1 -1
- package/dist/react/search/use-firestore-search.d.ts +0 -29
- package/dist/react/search/use-firestore-search.d.ts.map +1 -1
- package/dist/react/search/use-firestore-search.js +3 -41
- package/dist/react/search/use-firestore-search.js.map +1 -1
- package/dist/react/session-mutation.d.ts +27 -0
- package/dist/react/session-mutation.d.ts.map +1 -0
- package/dist/react/session-mutation.js +150 -0
- package/dist/react/session-mutation.js.map +1 -0
- package/dist/react/use-read-retry-state.d.ts +1 -21
- package/dist/react/use-read-retry-state.d.ts.map +1 -1
- package/dist/react/use-read-retry-state.js +2 -21
- package/dist/react/use-read-retry-state.js.map +1 -1
- package/dist/search/rule.d.ts +0 -6
- package/dist/search/rule.d.ts.map +1 -1
- package/dist/search/rule.js +0 -6
- package/dist/search/rule.js.map +1 -1
- package/dist/search/types.d.ts +1 -13
- package/dist/search/types.d.ts.map +1 -1
- package/dist/search/types.js.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-callables.js","sourceRoot":"","sources":["../../../src/react/callables/create-callables.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAGrD,OAAO,EACL,YAAY,EACZ,yBAAyB,GAE1B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GAGnB,MAAM,wBAAwB,CAAC;AAoChC,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAiCtC,MAAM,UAAU,eAAe,CAAC,MAAsB;IACpD,SAAS,oBAAoB,CAC3B,YAAoB,EACpB,WAAgC,EAChC,OAAiC;QAEjC,MAAM,UAAU,GAAG,MA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;gBACjE,OAAO,mBAAmB,CAAkB,IAAI,CAAC,CAAC;YACpD,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\nimport { useCallback, useMemo, useRef } from 'react';\nimport type { UseMutationResult } from '@tanstack/react-query';\nimport type { ExpectedCallableAnswerCode } from '@ttt-productions/firebase-helpers';\nimport {\n callCallable,\n isRecoveredFallbackReport,\n type FunctionsProvider,\n} from '@ttt-productions/firebase-helpers/client';\nimport {\n useMutationSessionCapture,\n useSessionMutation,\n type MutationSession,\n type SessionMutationOptions,\n} from '../session-mutation.js';\n\nexport interface CallableErrorRouting {\n showErrorToast: boolean;\n answeredRefusals: readonly ExpectedCallableAnswerCode[];\n isAnswerSurfacedByCaller?: (error: unknown) => boolean;\n}\n\nexport type CallableCaptureContext = Record<string, unknown>;\n\nexport interface CallablePolicy {\n getFunctions: FunctionsProvider;\n timeoutMs: number;\n resolveLimitedUseAppCheck: (requested: boolean) => boolean;\n captureFault: (error: unknown, context: CallableCaptureContext) => void;\n captureRecoveredFallback: (error: unknown, context: CallableCaptureContext) => void;\n onActionError: (error: unknown, routing: CallableErrorRouting) => void;\n}\n\nexport interface CallableDeclaration {\n limitedUseAppCheck?: true;\n}\n\ninterface CallableTransportOptions extends Partial<CallableErrorRouting> {\n captureFaults?: boolean;\n}\n\nexport type CallableMutationOptions<TInput, TResult, TOnMutateResult = unknown> = Omit<\n SessionMutationOptions<TResult, Error, TInput, TOnMutateResult>,\n 'mutationFn' | 'retry'\n> &\n Pick<\n CallableTransportOptions,\n 'showErrorToast' | 'answeredRefusals' | 'isAnswerSurfacedByCaller' | 'captureFaults'\n >;\n\nexport const MAX_RESUMABLE_CALLS = 12;\n\nexport type ResumableOutcome<TResult> = TResult & { interruption: Error | null };\n\nexport interface Callables {\n createCallableHook<TInput, TResult>(\n functionName: string,\n declaration?: CallableDeclaration,\n ): <TOnMutateResult = unknown>(\n options?: CallableMutationOptions<TInput, TResult, TOnMutateResult>,\n ) => UseMutationResult<TResult, Error, TInput, TOnMutateResult>;\n createResumableCallableHook<TInput, TResult extends { complete: boolean }>(\n functionName: string,\n merge: (earlier: TResult, later: TResult) => TResult,\n declaration?: CallableDeclaration,\n ): <TOnMutateResult = unknown>(\n options?: CallableMutationOptions<TInput, ResumableOutcome<TResult>, TOnMutateResult>,\n ) => UseMutationResult<ResumableOutcome<TResult>, Error, TInput, TOnMutateResult>;\n createCallableReader<TInput, TResult>(\n functionName: string,\n declaration?: CallableDeclaration,\n ): () => (input: TInput) => Promise<TResult>;\n createCallableInvoker<TInput, TResult>(\n functionName: string,\n declaration?: CallableDeclaration,\n ): () => (input: TInput) => Promise<TResult>;\n}\n\ntype CallableTransport = <TInput, TResult>(\n input: TInput,\n session: MutationSession,\n) => Promise<TResult>;\n\nexport function createCallables(policy: CallablePolicy): Callables {\n function useCallableTransport(\n functionName: string,\n declaration: CallableDeclaration,\n options: CallableTransportOptions,\n ): CallableTransport {\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const limitedUseAppCheck = policy.resolveLimitedUseAppCheck(\n declaration.limitedUseAppCheck === true,\n );\n\n return useCallback(\n <TInput, TResult>(input: TInput, session: MutationSession) =>\n callCallable<TInput, TResult>(\n policy.getFunctions,\n functionName,\n input,\n {\n captureException: (error, context) => {\n if (optionsRef.current.captureFaults !== false) policy.captureFault(error, context);\n else if (isRecoveredFallbackReport(context))\n policy.captureRecoveredFallback(error, context);\n },\n onError: (error) => {\n if (!session.isCurrent()) return;\n const {\n showErrorToast = true,\n answeredRefusals = [],\n isAnswerSurfacedByCaller,\n } = optionsRef.current;\n policy.onActionError(error, {\n showErrorToast,\n answeredRefusals,\n isAnswerSurfacedByCaller,\n });\n },\n },\n { timeoutMs: policy.timeoutMs, limitedUseAppCheck },\n ),\n [functionName, limitedUseAppCheck],\n );\n }\n\n function useSessionBoundCall<TInput, TResult>(\n call: CallableTransport,\n ): (input: TInput) => Promise<TResult> {\n const captureSession = useMutationSessionCapture();\n return useMemo(\n () => (input: TInput) => call<TInput, TResult>(input, captureSession()),\n [call, captureSession],\n );\n }\n\n return {\n createCallableHook<TInput, TResult>(\n functionName: string,\n declaration: CallableDeclaration = {},\n ) {\n return function useNamedCallable<TOnMutateResult = unknown>(\n options: CallableMutationOptions<TInput, TResult, TOnMutateResult> = {},\n ): UseMutationResult<TResult, Error, TInput, TOnMutateResult> {\n const {\n showErrorToast,\n answeredRefusals,\n isAnswerSurfacedByCaller,\n captureFaults,\n ...mutationOptions\n } = options;\n const call = useCallableTransport(functionName, declaration, {\n showErrorToast,\n answeredRefusals,\n isAnswerSurfacedByCaller,\n captureFaults,\n });\n // `retry: false` comes last so nothing overrides it: a deadline expiry is an unknown outcome,\n // and a retry after a committed first attempt writes twice.\n return useSessionMutation<TResult, Error, TInput, TOnMutateResult>({\n ...mutationOptions,\n retry: false,\n mutationFn: (input, { session }) => call<TInput, TResult>(input, session),\n });\n };\n },\n\n createResumableCallableHook<TInput, TResult extends { complete: boolean }>(\n functionName: string,\n merge: (earlier: TResult, later: TResult) => TResult,\n declaration: CallableDeclaration = {},\n ) {\n return function useNamedResumableCallable<TOnMutateResult = unknown>(\n options: CallableMutationOptions<TInput, ResumableOutcome<TResult>, TOnMutateResult> = {},\n ): UseMutationResult<ResumableOutcome<TResult>, Error, TInput, TOnMutateResult> {\n const {\n showErrorToast,\n answeredRefusals,\n isAnswerSurfacedByCaller,\n captureFaults,\n ...mutationOptions\n } = options;\n const call = useCallableTransport(functionName, declaration, {\n showErrorToast,\n answeredRefusals,\n isAnswerSurfacedByCaller,\n captureFaults,\n });\n return useSessionMutation<ResumableOutcome<TResult>, Error, TInput, TOnMutateResult>({\n ...mutationOptions,\n retry: false,\n mutationFn: async (input, { session }): Promise<ResumableOutcome<TResult>> => {\n let progress = await call<TInput, TResult>(input, session);\n for (let calls = 1; !progress.complete && calls < MAX_RESUMABLE_CALLS; calls += 1) {\n session.assertCurrent();\n let later: TResult;\n try {\n later = await call<TInput, TResult>(input, session);\n } catch (error) {\n const interruption = error instanceof Error ? error : new Error(String(error));\n return { ...progress, complete: false, interruption };\n }\n progress = merge(progress, later);\n }\n return { ...progress, interruption: null };\n },\n });\n };\n },\n\n createCallableReader<TInput, TResult>(\n functionName: string,\n declaration: CallableDeclaration = {},\n ) {\n return function useNamedCallableReader(): (input: TInput) => Promise<TResult> {\n const call = useCallableTransport(functionName, declaration, {\n showErrorToast: false,\n captureFaults: false,\n });\n return useSessionBoundCall<TInput, TResult>(call);\n };\n },\n\n createCallableInvoker<TInput, TResult>(\n functionName: string,\n declaration: CallableDeclaration = {},\n ) {\n return function useNamedCallableInvoker(): (input: TInput) => Promise<TResult> {\n const call = useCallableTransport(functionName, declaration, {});\n return useSessionBoundCall<TInput, TResult>(call);\n };\n },\n };\n}\n"]}
|
package/dist/react/defaults.d.ts
CHANGED
|
@@ -1,8 +1,4 @@
|
|
|
1
1
|
import type { DefaultOptions, QueryClientConfig } from '@tanstack/react-query';
|
|
2
|
-
/**
|
|
3
|
-
* Small, conservative defaults intended to work well across apps.
|
|
4
|
-
* Apps can override via `createQueryClient({ defaultOptions: ... })`.
|
|
5
|
-
*/
|
|
6
2
|
export declare const defaultQueryOptions: DefaultOptions;
|
|
7
3
|
export declare const defaultQueryClientConfig: QueryClientConfig;
|
|
8
4
|
//# sourceMappingURL=defaults.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../../src/react/defaults.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE/E
|
|
1
|
+
{"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../../src/react/defaults.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE/E,eAAO,MAAM,mBAAmB,EAAE,cAcjC,CAAC;AAEF,eAAO,MAAM,wBAAwB,EAAE,iBAEtC,CAAC"}
|
package/dist/react/defaults.js
CHANGED
|
@@ -1,14 +1,10 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Small, conservative defaults intended to work well across apps.
|
|
3
|
-
* Apps can override via `createQueryClient({ defaultOptions: ... })`.
|
|
4
|
-
*/
|
|
5
1
|
export const defaultQueryOptions = {
|
|
6
2
|
queries: {
|
|
7
3
|
refetchOnWindowFocus: false,
|
|
8
4
|
refetchOnReconnect: true,
|
|
9
5
|
refetchOnMount: false,
|
|
10
|
-
staleTime: 30_000,
|
|
11
|
-
gcTime: 5 * 60_000,
|
|
6
|
+
staleTime: 30_000,
|
|
7
|
+
gcTime: 5 * 60_000,
|
|
12
8
|
retry: (failureCount) => failureCount < 2,
|
|
13
9
|
},
|
|
14
10
|
mutations: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../../src/react/defaults.ts"],"names":[],"mappings":"AAEA
|
|
1
|
+
{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../../src/react/defaults.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,mBAAmB,GAAmB;IACjD,OAAO,EAAE;QACP,oBAAoB,EAAE,KAAK;QAC3B,kBAAkB,EAAE,IAAI;QACxB,cAAc,EAAE,KAAK;QAErB,SAAS,EAAE,MAAM;QACjB,MAAM,EAAE,CAAC,GAAG,MAAM;QAElB,KAAK,EAAE,CAAC,YAAY,EAAE,EAAE,CAAC,YAAY,GAAG,CAAC;KAC1C;IACD,SAAS,EAAE;QACT,KAAK,EAAE,CAAC;KACT;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,wBAAwB,GAAsB;IACzD,cAAc,EAAE,mBAAmB;CACpC,CAAC","sourcesContent":["import type { DefaultOptions, QueryClientConfig } from '@tanstack/react-query';\n\nexport const defaultQueryOptions: DefaultOptions = {\n queries: {\n refetchOnWindowFocus: false,\n refetchOnReconnect: true,\n refetchOnMount: false,\n\n staleTime: 30_000,\n gcTime: 5 * 60_000,\n\n retry: (failureCount) => failureCount < 2,\n },\n mutations: {\n retry: 0,\n },\n};\n\nexport const defaultQueryClientConfig: QueryClientConfig = {\n defaultOptions: defaultQueryOptions,\n};\n"]}
|
|
@@ -1,12 +1,5 @@
|
|
|
1
1
|
import type { Query, QueryClient, QueryKey } from '@tanstack/react-query';
|
|
2
2
|
export type RefetchType = 'active' | 'all' | 'none';
|
|
3
|
-
/**
|
|
4
|
-
* What an entry does to the queries it matches:
|
|
5
|
-
* - `"refresh"` (the default) marks them stale and refetches per `refetchType`;
|
|
6
|
-
* - `"remove"` cancels them and drops them from the cache — for data that no longer exists, or a
|
|
7
|
-
* held answer that must not be served again;
|
|
8
|
-
* - `"reset"` returns them to their initial state and refetches the active ones from scratch.
|
|
9
|
-
*/
|
|
10
3
|
export type CacheAction = 'refresh' | 'remove' | 'reset';
|
|
11
4
|
export type CacheInvalidation = {
|
|
12
5
|
kind: 'exact';
|
|
@@ -25,7 +18,6 @@ export type CacheInvalidation = {
|
|
|
25
18
|
refetchType?: RefetchType;
|
|
26
19
|
action?: CacheAction;
|
|
27
20
|
};
|
|
28
|
-
/** `refetchType` belongs to a refresh; a remove or reset takes none. */
|
|
29
21
|
type EntryOptions = {
|
|
30
22
|
refetchType?: RefetchType;
|
|
31
23
|
action?: 'refresh';
|
|
@@ -36,35 +28,6 @@ export declare function exact(queryKey: QueryKey, opts?: EntryOptions): CacheInv
|
|
|
36
28
|
export declare function prefix(queryKey: QueryKey, opts?: EntryOptions): CacheInvalidation;
|
|
37
29
|
export declare function predicate(description: string, match: (query: Query) => boolean, opts?: EntryOptions): CacheInvalidation;
|
|
38
30
|
export declare function serializeInvalidation(inv: CacheInvalidation): string;
|
|
39
|
-
/**
|
|
40
|
-
* Dispatch a deduplicated list of cache invalidations.
|
|
41
|
-
*
|
|
42
|
-
* Returns a promise that resolves once every `invalidateQueries` call it issued
|
|
43
|
-
* has settled — i.e. once the refetches those invalidations triggered have
|
|
44
|
-
* landed. The dispatch itself stays synchronous (every cancellation and
|
|
45
|
-
* invalidation is issued before this function returns), so a fire-and-forget
|
|
46
|
-
* caller can ignore the promise, while a mutation `onSuccess` that
|
|
47
|
-
* RETURNS or awaits the promise stays pending until the refreshed data is in
|
|
48
|
-
* the cache. The promise never rejects: `invalidateQueries` refetches without
|
|
49
|
-
* `throwOnError`, so a failed refetch surfaces on its own query, never as a
|
|
50
|
-
* failure of the committed action that triggered it. The scoped
|
|
51
|
-
* `cancelQueries` calls stay fire-and-forget — cancellation takes effect
|
|
52
|
-
* synchronously and is not part of the refresh being awaited.
|
|
53
|
-
*
|
|
54
|
-
* Before each invalidation, any query it matches that is mid-PENDING-INITIAL-READ
|
|
55
|
-
* is cancelled (see `cancelPendingInitialReads`) so a read that started before
|
|
56
|
-
* the write committed can never land as the query's first — and freshly-marked —
|
|
57
|
-
* value.
|
|
58
|
-
*
|
|
59
|
-
* `refetchType` governs whether that cancellation happens:
|
|
60
|
-
* - `'active'` (the default) and `'all'` cancel-then-invalidate every matched
|
|
61
|
-
* pending initial read — including one TanStack's refetch pass will not
|
|
62
|
-
* restart, since a stale first value would otherwise land and mark the query
|
|
63
|
-
* fresh, while a cancelled one simply refetches for its next observer.
|
|
64
|
-
* - `'none'` invalidates WITHOUT cancelling: the caller has asked for no
|
|
65
|
-
* refetch at all, so cancelling would abandon the only in-flight read the
|
|
66
|
-
* consumer has and leave it with no data and no pending request.
|
|
67
|
-
*/
|
|
68
31
|
export declare function applyInvalidations(queryClient: QueryClient, invalidations: ReadonlyArray<CacheInvalidation>): Promise<void>;
|
|
69
32
|
export {};
|
|
70
33
|
//# sourceMappingURL=cache-invalidation.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-invalidation.d.ts","sourceRoot":"","sources":["../../../src/react/domain-events/cache-invalidation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,WAAW,EAAgB,QAAQ,EAAE,MAAM,uBAAuB,CA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Q,EAAE,IAAI,CAAC,EAAE,YAAY,GAAG,iBAAiB,CAEjF;AAED,wBAAgB,SAAS,CACvB,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,OAAO,EAChC,IAAI,CAAC,EAAE,YAAY,GAClB,iBAAiB,CAEnB;AAED,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,iBAAiB,GAAG,MAAM,CAIpE;AA0BD,wBAAgB,kBAAkB,CAChC,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,aAAa,CAAC,iBAAiB,CAAC,GAC9C,OAAO,CAAC,IAAI,CAAC,CA+Bf"}
|
|
@@ -17,7 +17,6 @@ export function serializeInvalidation(inv) {
|
|
|
17
17
|
return `${action}predicate:${inv.description}`;
|
|
18
18
|
return `${action}${inv.kind}:${JSON.stringify(inv.queryKey)}`;
|
|
19
19
|
}
|
|
20
|
-
/** The cache filter that selects exactly the queries one invalidation targets. */
|
|
21
20
|
function invalidationFilters(inv) {
|
|
22
21
|
if (inv.kind === 'exact')
|
|
23
22
|
return { queryKey: inv.queryKey, exact: true };
|
|
@@ -26,20 +25,8 @@ function invalidationFilters(inv) {
|
|
|
26
25
|
return { predicate: inv.match };
|
|
27
26
|
}
|
|
28
27
|
/**
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
* TanStack's `Query.fetch` only cancels a running request on refetch when the
|
|
33
|
-
* query already holds data; an initial fetch in flight is REUSED instead, so
|
|
34
|
-
* the invalidation's refetch resolves with the value the server returned BEFORE
|
|
35
|
-
* the mutation committed and then marks the query fresh. Cancelling first makes
|
|
36
|
-
* the invalidation's refetch a genuinely new request: the retryer is rejected
|
|
37
|
-
* synchronously (its `onCancel` reverts state to idle in the same tick), so the
|
|
38
|
-
* `invalidateQueries` call that follows starts a fresh fetch, and the abandoned
|
|
39
|
-
* promise's late, stale resolution is discarded.
|
|
40
|
-
*
|
|
41
|
-
* Cancellation is always scoped to one concrete query key — never a bare
|
|
42
|
-
* `cancelQueries()`.
|
|
28
|
+
* TanStack's `Query.fetch` reuses an in-flight initial fetch instead of cancelling it, so without
|
|
29
|
+
* this cancel the invalidation would resolve with the value read before the mutation committed.
|
|
43
30
|
*/
|
|
44
31
|
function cancelPendingInitialReads(queryClient, filters) {
|
|
45
32
|
for (const query of queryClient.getQueryCache().findAll(filters)) {
|
|
@@ -50,45 +37,11 @@ function cancelPendingInitialReads(queryClient, filters) {
|
|
|
50
37
|
void queryClient.cancelQueries({ queryKey: query.queryKey, exact: true });
|
|
51
38
|
}
|
|
52
39
|
}
|
|
53
|
-
/**
|
|
54
|
-
* Exactly the queries `filters` matches now. A remove or reset acts in two steps — cancel then
|
|
55
|
-
* remove, reset then refetch — and the first step changes the state a predicate may read (a reset
|
|
56
|
-
* clears the failure, a cancel idles the fetch), so the second step re-applying the filter would
|
|
57
|
-
* miss the queries the entry matched.
|
|
58
|
-
*/
|
|
40
|
+
/** A cancel or reset changes the state a predicate reads, so the second step must not re-apply the filter. */
|
|
59
41
|
function matchedNow(queryClient, filters) {
|
|
60
42
|
const matched = new Set(queryClient.getQueryCache().findAll(filters));
|
|
61
43
|
return { predicate: (query) => matched.has(query) };
|
|
62
44
|
}
|
|
63
|
-
/**
|
|
64
|
-
* Dispatch a deduplicated list of cache invalidations.
|
|
65
|
-
*
|
|
66
|
-
* Returns a promise that resolves once every `invalidateQueries` call it issued
|
|
67
|
-
* has settled — i.e. once the refetches those invalidations triggered have
|
|
68
|
-
* landed. The dispatch itself stays synchronous (every cancellation and
|
|
69
|
-
* invalidation is issued before this function returns), so a fire-and-forget
|
|
70
|
-
* caller can ignore the promise, while a mutation `onSuccess` that
|
|
71
|
-
* RETURNS or awaits the promise stays pending until the refreshed data is in
|
|
72
|
-
* the cache. The promise never rejects: `invalidateQueries` refetches without
|
|
73
|
-
* `throwOnError`, so a failed refetch surfaces on its own query, never as a
|
|
74
|
-
* failure of the committed action that triggered it. The scoped
|
|
75
|
-
* `cancelQueries` calls stay fire-and-forget — cancellation takes effect
|
|
76
|
-
* synchronously and is not part of the refresh being awaited.
|
|
77
|
-
*
|
|
78
|
-
* Before each invalidation, any query it matches that is mid-PENDING-INITIAL-READ
|
|
79
|
-
* is cancelled (see `cancelPendingInitialReads`) so a read that started before
|
|
80
|
-
* the write committed can never land as the query's first — and freshly-marked —
|
|
81
|
-
* value.
|
|
82
|
-
*
|
|
83
|
-
* `refetchType` governs whether that cancellation happens:
|
|
84
|
-
* - `'active'` (the default) and `'all'` cancel-then-invalidate every matched
|
|
85
|
-
* pending initial read — including one TanStack's refetch pass will not
|
|
86
|
-
* restart, since a stale first value would otherwise land and mark the query
|
|
87
|
-
* fresh, while a cancelled one simply refetches for its next observer.
|
|
88
|
-
* - `'none'` invalidates WITHOUT cancelling: the caller has asked for no
|
|
89
|
-
* refetch at all, so cancelling would abandon the only in-flight read the
|
|
90
|
-
* consumer has and leave it with no data and no pending request.
|
|
91
|
-
*/
|
|
92
45
|
export function applyInvalidations(queryClient, invalidations) {
|
|
93
46
|
const seen = new Set();
|
|
94
47
|
const refreshes = [];
|
|
@@ -101,9 +54,7 @@ export function applyInvalidations(queryClient, invalidations) {
|
|
|
101
54
|
const action = inv.action ?? 'refresh';
|
|
102
55
|
if (action === 'remove') {
|
|
103
56
|
const matched = matchedNow(queryClient, filters);
|
|
104
|
-
// Removing a query abandons its
|
|
105
|
-
// answer back, but a screen still watching it would go on showing it as fetching. Cancelled
|
|
106
|
-
// first, the read ends visibly and the watcher reads idle.
|
|
57
|
+
// Removing a query abandons its in-flight read silently, leaving a watching screen on fetching; cancelling first ends it visibly.
|
|
107
58
|
void queryClient.cancelQueries(matched);
|
|
108
59
|
queryClient.removeQueries(matched);
|
|
109
60
|
continue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-invalidation.js","sourceRoot":"","sources":["../../../src/react/domain-events/cache-invalidation.ts"],"names":[],"mappings":"AA4BA,MAAM,WAAW,GAAG,CAAC,IAAmB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'none';\n\n/**\n * What an entry does to the queries it matches:\n * - `\"refresh\"` (the default) marks them stale and refetches per `refetchType`;\n * - `\"remove\"` cancels them and drops them from the cache — for data that no longer exists, or a\n * held answer that must not be served again;\n * - `\"reset\"` returns them to their initial state and refetches the active ones from scratch.\n */\nexport type CacheAction = 'refresh' | 'remove' | 'reset';\n\nexport type CacheInvalidation =\n | { kind: 'exact'; queryKey: QueryKey; refetchType?: RefetchType; action?: CacheAction }\n | { kind: 'prefix'; queryKey: QueryKey; refetchType?: RefetchType; action?: CacheAction }\n | {\n kind: 'predicate';\n description: string;\n match: (query: Query) => boolean;\n refetchType?: RefetchType;\n action?: CacheAction;\n };\n\n/** `refetchType` belongs to a refresh; a remove or reset takes none. */\ntype EntryOptions =\n { refetchType?: RefetchType; action?: 'refresh' } | { action: 'remove' | 'reset' };\n\nconst entryFields = (opts?: EntryOptions) => ({\n refetchType: opts && 'refetchType' in opts ? opts.refetchType : undefined,\n action: opts?.action,\n});\n\nexport function exact(queryKey: QueryKey, opts?: EntryOptions): CacheInvalidation {\n return { kind: 'exact', queryKey, ...entryFields(opts) };\n}\n\nexport function prefix(queryKey: QueryKey, opts?: EntryOptions): CacheInvalidation {\n return { kind: 'prefix', queryKey, ...entryFields(opts) };\n}\n\nexport function predicate(\n description: string,\n match: (query: Query) => boolean,\n opts?: EntryOptions,\n): CacheInvalidation {\n return { kind: 'predicate', description, match, ...entryFields(opts) };\n}\n\nexport function serializeInvalidation(inv: CacheInvalidation): string {\n const action = inv.action && inv.action !== 'refresh' ? `${inv.action}:` : '';\n if (inv.kind === 'predicate') return `${action}predicate:${inv.description}`;\n return `${action}${inv.kind}:${JSON.stringify(inv.queryKey)}`;\n}\n\n/** The cache filter that selects exactly the queries one invalidation targets. */\nfunction invalidationFilters(inv: CacheInvalidation): QueryFilters {\n if (inv.kind === 'exact') return { queryKey: inv.queryKey, exact: true };\n if (inv.kind === 'prefix') return { queryKey: inv.queryKey, exact: false };\n return { predicate: inv.match };\n}\n\n/**\n * Cancel every query matched by `filters` that is in a PENDING INITIAL READ —\n * currently fetching with no data yet.\n *\n * TanStack's `Query.fetch` only cancels a running request on refetch when the\n * query already holds data; an initial fetch in flight is REUSED instead, so\n * the invalidation's refetch resolves with the value the server returned BEFORE\n * the mutation committed and then marks the query fresh. Cancelling first makes\n * the invalidation's refetch a genuinely new request: the retryer is rejected\n * synchronously (its `onCancel` reverts state to idle in the same tick), so the\n * `invalidateQueries` call that follows starts a fresh fetch, and the abandoned\n * promise's late, stale resolution is discarded.\n *\n * Cancellation is always scoped to one concrete query key — never a bare\n * `cancelQueries()`.\n */\nfunction cancelPendingInitialReads(queryClient: QueryClient, filters: QueryFilters): void {\n for (const query of queryClient.getQueryCache().findAll(filters)) {\n if (query.state.fetchStatus !== 'fetching') continue;\n if (query.state.data !== undefined) continue;\n void queryClient.cancelQueries({ queryKey: query.queryKey, exact: true });\n }\n}\n\n/**\n * Exactly the queries `filters` matches now. A remove or reset acts in two steps — cancel then\n * remove, reset then refetch — and the first step changes the state a predicate may read (a reset\n * clears the failure, a cancel idles the fetch), so the second step re-applying the filter would\n * miss the queries the entry matched.\n */\nfunction matchedNow(queryClient: QueryClient, filters: QueryFilters): QueryFilters {\n const matched = new Set(queryClient.getQueryCache().findAll(filters));\n return { predicate: (query) => matched.has(query) };\n}\n\n/**\n * Dispatch a deduplicated list of cache invalidations.\n *\n * Returns a promise that resolves once every `invalidateQueries` call it issued\n * has settled — i.e. once the refetches those invalidations triggered have\n * landed. The dispatch itself stays synchronous (every cancellation and\n * invalidation is issued before this function returns), so a fire-and-forget\n * caller can ignore the promise, while a mutation `onSuccess` that\n * RETURNS or awaits the promise stays pending until the refreshed data is in\n * the cache. The promise never rejects: `invalidateQueries` refetches without\n * `throwOnError`, so a failed refetch surfaces on its own query, never as a\n * failure of the committed action that triggered it. The scoped\n * `cancelQueries` calls stay fire-and-forget — cancellation takes effect\n * synchronously and is not part of the refresh being awaited.\n *\n * Before each invalidation, any query it matches that is mid-PENDING-INITIAL-READ\n * is cancelled (see `cancelPendingInitialReads`) so a read that started before\n * the write committed can never land as the query's first — and freshly-marked —\n * value.\n *\n * `refetchType` governs whether that cancellation happens:\n * - `'active'` (the default) and `'all'` cancel-then-invalidate every matched\n * pending initial read — including one TanStack's refetch pass will not\n * restart, since a stale first value would otherwise land and mark the query\n * fresh, while a cancelled one simply refetches for its next observer.\n * - `'none'` invalidates WITHOUT cancelling: the caller has asked for no\n * refetch at all, so cancelling would abandon the only in-flight read the\n * consumer has and leave it with no data and no pending request.\n */\nexport function applyInvalidations(\n queryClient: QueryClient,\n invalidations: ReadonlyArray<CacheInvalidation>,\n): Promise<void> {\n const seen = new Set<string>();\n const refreshes: Promise<void>[] = [];\n for (const inv of invalidations) {\n const sig = serializeInvalidation(inv);\n if (seen.has(sig)) continue;\n seen.add(sig);\n\n const filters = invalidationFilters(inv);\n const action: CacheAction = inv.action ?? 'refresh';\n\n if (action === 'remove') {\n const matched = matchedNow(queryClient, filters);\n // Removing a query abandons its read in flight silently, so that read never puts the dropped\n // answer back, but a screen still watching it would go on showing it as fetching. Cancelled\n // first, the read ends visibly and the watcher reads idle.\n void queryClient.cancelQueries(matched);\n queryClient.removeQueries(matched);\n continue;\n }\n if (action === 'reset') {\n refreshes.push(queryClient.resetQueries(matchedNow(queryClient, filters)));\n continue;\n }\n\n const refetchType: RefetchType = inv.refetchType ?? 'active';\n if (refetchType !== 'none') {\n cancelPendingInitialReads(queryClient, filters);\n }\n\n refreshes.push(queryClient.invalidateQueries({ ...filters, refetchType }));\n }\n return Promise.all(refreshes).then(() => undefined);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cache-invalidation.js","sourceRoot":"","sources":["../../../src/react/domain-events/cache-invalidation.ts"],"names":[],"mappings":"AAoBA,MAAM,WAAW,GAAG,CAAC,IAAmB,EAAE,EAAE,CAAC,CAAC;IAC5C,WAAW,EAAE,IAAI,IAAI,aAAa,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,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AAO,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC;QACzC,MAAM,MAAM,GAAgB,GAAG,CAAC,MAAM,IAAI,SAAS,CAAC;QAEpD,IAAI,MAAM,KAAK,QAAQ,EAAE,CAAC;YACxB,MAAM,OAAO,GAAG,UAAU,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;YACjD,kIAAkI;YAClI,KAAK,WAAW,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;YACxC,WAAW,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;YACnC,SAAS;QACX,CAAC;QACD,IAAI,MAAM,KAAK,OAAO,EAAE,CAAC;YACvB,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC,UAAU,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;YAC3E,SAAS;QACX,CAAC;QAED,MAAM,WAAW,GAAgB,GAAG,CAAC,WAAW,IAAI,QAAQ,CAAC;QAC7D,IAAI,WAAW,KAAK,MAAM,EAAE,CAAC;YAC3B,yBAAyB,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;QAClD,CAAC;QAED,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,iBAAiB,CAAC,EAAE,GAAG,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC;IAC7E,CAAC;IACD,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;AACtD,CAAC","sourcesContent":["import type { Query, QueryClient, QueryFilters, QueryKey } from '@tanstack/react-query';\n\nexport type RefetchType = 'active' | 'all' | 'none';\n\nexport type CacheAction = 'refresh' | 'remove' | 'reset';\n\nexport type CacheInvalidation =\n | { kind: 'exact'; queryKey: QueryKey; refetchType?: RefetchType; action?: CacheAction }\n | { kind: 'prefix'; queryKey: QueryKey; refetchType?: RefetchType; action?: CacheAction }\n | {\n kind: 'predicate';\n description: string;\n match: (query: Query) => boolean;\n refetchType?: RefetchType;\n action?: CacheAction;\n };\n\ntype EntryOptions =\n { refetchType?: RefetchType; action?: 'refresh' } | { action: 'remove' | 'reset' };\n\nconst entryFields = (opts?: EntryOptions) => ({\n refetchType: opts && 'refetchType' in opts ? opts.refetchType : undefined,\n action: opts?.action,\n});\n\nexport function exact(queryKey: QueryKey, opts?: EntryOptions): CacheInvalidation {\n return { kind: 'exact', queryKey, ...entryFields(opts) };\n}\n\nexport function prefix(queryKey: QueryKey, opts?: EntryOptions): CacheInvalidation {\n return { kind: 'prefix', queryKey, ...entryFields(opts) };\n}\n\nexport function predicate(\n description: string,\n match: (query: Query) => boolean,\n opts?: EntryOptions,\n): CacheInvalidation {\n return { kind: 'predicate', description, match, ...entryFields(opts) };\n}\n\nexport function serializeInvalidation(inv: CacheInvalidation): string {\n const action = inv.action && inv.action !== 'refresh' ? `${inv.action}:` : '';\n if (inv.kind === 'predicate') return `${action}predicate:${inv.description}`;\n return `${action}${inv.kind}:${JSON.stringify(inv.queryKey)}`;\n}\n\nfunction invalidationFilters(inv: CacheInvalidation): QueryFilters {\n if (inv.kind === 'exact') return { queryKey: inv.queryKey, exact: true };\n if (inv.kind === 'prefix') return { queryKey: inv.queryKey, exact: false };\n return { predicate: inv.match };\n}\n\n/**\n * TanStack's `Query.fetch` reuses an in-flight initial fetch instead of cancelling it, so without\n * this cancel the invalidation would resolve with the value read before the mutation committed.\n */\nfunction cancelPendingInitialReads(queryClient: QueryClient, filters: QueryFilters): void {\n for (const query of queryClient.getQueryCache().findAll(filters)) {\n if (query.state.fetchStatus !== 'fetching') continue;\n if (query.state.data !== undefined) continue;\n void queryClient.cancelQueries({ queryKey: query.queryKey, exact: true });\n }\n}\n\n/** A cancel or reset changes the state a predicate reads, so the second step must not re-apply the filter. */\nfunction matchedNow(queryClient: QueryClient, filters: QueryFilters): QueryFilters {\n const matched = new Set(queryClient.getQueryCache().findAll(filters));\n return { predicate: (query) => matched.has(query) };\n}\n\nexport function applyInvalidations(\n queryClient: QueryClient,\n invalidations: ReadonlyArray<CacheInvalidation>,\n): Promise<void> {\n const seen = new Set<string>();\n const refreshes: Promise<void>[] = [];\n for (const inv of invalidations) {\n const sig = serializeInvalidation(inv);\n if (seen.has(sig)) continue;\n seen.add(sig);\n\n const filters = invalidationFilters(inv);\n const action: CacheAction = inv.action ?? 'refresh';\n\n if (action === 'remove') {\n const matched = matchedNow(queryClient, filters);\n // Removing a query abandons its in-flight read silently, leaving a watching screen on fetching; cancelling first ends it visibly.\n void queryClient.cancelQueries(matched);\n queryClient.removeQueries(matched);\n continue;\n }\n if (action === 'reset') {\n refreshes.push(queryClient.resetQueries(matchedNow(queryClient, filters)));\n continue;\n }\n\n const refetchType: RefetchType = inv.refetchType ?? 'active';\n if (refetchType !== 'none') {\n cancelPendingInitialReads(queryClient, filters);\n }\n\n refreshes.push(queryClient.invalidateQueries({ ...filters, refetchType }));\n }\n return Promise.all(refreshes).then(() => undefined);\n}\n"]}
|
|
@@ -1,9 +1,5 @@
|
|
|
1
1
|
import type { QueryClient } from '@tanstack/react-query';
|
|
2
2
|
import { exact, prefix, predicate, type CacheInvalidation } from './cache-invalidation.js';
|
|
3
|
-
/**
|
|
4
|
-
* Registry shape: each event type maps to a function from the event's `ids`
|
|
5
|
-
* payload to the list of cache invalidations that event should trigger.
|
|
6
|
-
*/
|
|
7
3
|
export type DomainEventInvalidationRegistry<TEvent extends {
|
|
8
4
|
type: string;
|
|
9
5
|
ids: unknown;
|
|
@@ -16,29 +12,15 @@ export interface DomainEventInvalidator<TEvent extends {
|
|
|
16
12
|
type: string;
|
|
17
13
|
ids: unknown;
|
|
18
14
|
}> {
|
|
19
|
-
/**
|
|
20
|
-
* Dispatch the event's invalidations. The returned promise resolves once
|
|
21
|
-
* every refetch they triggered has settled, and never rejects — return or
|
|
22
|
-
* await it from a mutation's `onSuccess` to keep the mutation pending until
|
|
23
|
-
* the refreshed data lands; ignore it for fire-and-forget dispatch.
|
|
24
|
-
*/
|
|
25
15
|
notify(queryClient: QueryClient, event: TEvent): Promise<void>;
|
|
26
|
-
/** `notify` for several events, deduplicating their invalidations as one batch. */
|
|
27
16
|
notifyAll(queryClient: QueryClient, events: ReadonlyArray<TEvent>): Promise<void>;
|
|
28
|
-
/** Test/debug helpers. */
|
|
29
17
|
readonly helpers: {
|
|
30
18
|
exact: typeof exact;
|
|
31
19
|
prefix: typeof prefix;
|
|
32
20
|
predicate: typeof predicate;
|
|
33
21
|
};
|
|
34
|
-
/** Direct access to the registry, mainly for tests. */
|
|
35
22
|
readonly registry: DomainEventInvalidationRegistry<TEvent>;
|
|
36
23
|
}
|
|
37
|
-
/**
|
|
38
|
-
* Build a domain-event → cache-invalidation notifier from a typed registry.
|
|
39
|
-
* The registry's keys are statically tied to `TEvent["type"]`, so missing or
|
|
40
|
-
* extra entries are compile errors.
|
|
41
|
-
*/
|
|
42
24
|
export declare function createDomainEventInvalidator<TEvent extends {
|
|
43
25
|
type: string;
|
|
44
26
|
ids: unknown;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-domain-event-invalidator.d.ts","sourceRoot":"","sources":["../../../src/react/domain-events/create-domain-event-invalidator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAEL,KAAK,EACL,MAAM,EACN,SAAS,EACT,KAAK,iBAAiB,EACvB,MAAM,yBAAyB,CAAC;AAEjC
|
|
1
|
+
{"version":3,"file":"create-domain-event-invalidator.d.ts","sourceRoot":"","sources":["../../../src/react/domain-events/create-domain-event-invalidator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAEL,KAAK,EACL,MAAM,EACN,SAAS,EACT,KAAK,iBAAiB,EACvB,MAAM,yBAAyB,CAAC;AAEjC,MAAM,MAAM,+BAA+B,CAAC,MAAM,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,OAAO,CAAA;CAAE,IAAI;KAC1F,CAAC,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CACrB,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE;QAAE,IAAI,EAAE,CAAC,CAAA;KAAE,CAAC,CAAC,KAAK,CAAC,KACrC,aAAa,CAAC,iBAAiB,CAAC;CACtC,CAAC;AAEF,MAAM,WAAW,sBAAsB,CAAC,MAAM,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,OAAO,CAAA;CAAE;IACnF,MAAM,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/D,SAAS,CAAC,WAAW,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAClF,QAAQ,CAAC,OAAO,EAAE;QAChB,KAAK,EAAE,OAAO,KAAK,CAAC;QACpB,MAAM,EAAE,OAAO,MAAM,CAAC;QACtB,SAAS,EAAE,OAAO,SAAS,CAAC;KAC7B,CAAC;IACF,QAAQ,CAAC,QAAQ,EAAE,+BAA+B,CAAC,MAAM,CAAC,CAAC;CAC5D;AAED,wBAAgB,4BAA4B,CAAC,MAAM,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,OAAO,CAAA;CAAE,EACxF,QAAQ,EAAE,+BAA+B,CAAC,MAAM,CAAC,GAChD,sBAAsB,CAAC,MAAM,CAAC,CA4BhC"}
|
|
@@ -1,9 +1,4 @@
|
|
|
1
1
|
import { applyInvalidations, exact, prefix, predicate, } from './cache-invalidation.js';
|
|
2
|
-
/**
|
|
3
|
-
* Build a domain-event → cache-invalidation notifier from a typed registry.
|
|
4
|
-
* The registry's keys are statically tied to `TEvent["type"]`, so missing or
|
|
5
|
-
* extra entries are compile errors.
|
|
6
|
-
*/
|
|
7
2
|
export function createDomainEventInvalidator(registry) {
|
|
8
3
|
function lookup(type) {
|
|
9
4
|
return registry[type];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-domain-event-invalidator.js","sourceRoot":"","sources":["../../../src/react/domain-events/create-domain-event-invalidator.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kBAAkB,EAClB,KAAK,EACL,MAAM,EACN,SAAS,GAEV,MAAM,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"create-domain-event-invalidator.js","sourceRoot":"","sources":["../../../src/react/domain-events/create-domain-event-invalidator.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kBAAkB,EAClB,KAAK,EACL,MAAM,EACN,SAAS,GAEV,MAAM,yBAAyB,CAAC;AAmBjC,MAAM,UAAU,4BAA4B,CAC1C,QAAiD;IAEjD,SAAS,MAAM,CAA+B,IAAW;QACvD,OAAO,QAAQ,CAAC,IAAI,CAEiB,CAAC;IACxC,CAAC;IAED,SAAS,MAAM,CAAC,WAAwB,EAAE,KAAa;QACrD,MAAM,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,IAAsB,CAAC,CAAC;QAChD,MAAM,aAAa,GAAG,EAAE,CAAC,KAAK,CAAC,GAAuD,CAAC,CAAC;QACxF,OAAO,kBAAkB,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;IACxD,CAAC;IAED,SAAS,SAAS,CAAC,WAAwB,EAAE,MAA6B;QACxE,MAAM,GAAG,GAAwB,EAAE,CAAC;QACpC,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;YAC3B,MAAM,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,IAAsB,CAAC,CAAC;YAChD,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,GAAuD,CAAC,CAAC,CAAC;QACjF,CAAC;QACD,OAAO,kBAAkB,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC;IAC9C,CAAC;IAED,OAAO;QACL,MAAM;QACN,SAAS;QACT,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE;QACrC,QAAQ;KACT,CAAC;AACJ,CAAC","sourcesContent":["import type { QueryClient } from '@tanstack/react-query';\nimport {\n applyInvalidations,\n exact,\n prefix,\n predicate,\n type CacheInvalidation,\n} from './cache-invalidation.js';\n\nexport type DomainEventInvalidationRegistry<TEvent extends { type: string; ids: unknown }> = {\n [K in TEvent['type']]: (\n ids: Extract<TEvent, { type: K }>['ids'],\n ) => ReadonlyArray<CacheInvalidation>;\n};\n\nexport interface DomainEventInvalidator<TEvent extends { type: string; ids: unknown }> {\n notify(queryClient: QueryClient, event: TEvent): Promise<void>;\n notifyAll(queryClient: QueryClient, events: ReadonlyArray<TEvent>): Promise<void>;\n readonly helpers: {\n exact: typeof exact;\n prefix: typeof prefix;\n predicate: typeof predicate;\n };\n readonly registry: DomainEventInvalidationRegistry<TEvent>;\n}\n\nexport function createDomainEventInvalidator<TEvent extends { type: string; ids: unknown }>(\n registry: DomainEventInvalidationRegistry<TEvent>,\n): DomainEventInvalidator<TEvent> {\n function lookup<TType extends TEvent['type']>(type: TType) {\n return registry[type] as (\n ids: Extract<TEvent, { type: TType }>['ids'],\n ) => ReadonlyArray<CacheInvalidation>;\n }\n\n function notify(queryClient: QueryClient, event: TEvent): Promise<void> {\n const fn = lookup(event.type as TEvent['type']);\n const invalidations = fn(event.ids as Extract<TEvent, { type: TEvent['type'] }>['ids']);\n return applyInvalidations(queryClient, invalidations);\n }\n\n function notifyAll(queryClient: QueryClient, events: ReadonlyArray<TEvent>): Promise<void> {\n const all: CacheInvalidation[] = [];\n for (const event of events) {\n const fn = lookup(event.type as TEvent['type']);\n all.push(...fn(event.ids as Extract<TEvent, { type: TEvent['type'] }>['ids']));\n }\n return applyInvalidations(queryClient, all);\n }\n\n return {\n notify,\n notifyAll,\n helpers: { exact, prefix, predicate },\n registry,\n };\n}\n"]}
|
|
@@ -1,39 +1,11 @@
|
|
|
1
1
|
import type { QueryClient, QueryKey } from '@tanstack/react-query';
|
|
2
|
-
/**
|
|
3
|
-
* Bounded re-read ladder for a document that resolved ABSENT.
|
|
4
|
-
*
|
|
5
|
-
* A one-shot lookup that lands `null` has no listener to tell it when the doc appears —
|
|
6
|
-
* the row would stay blank until something invalidates it. That is the real failure the
|
|
7
|
-
* realtime path was introduced to fix (a mirror doc that is missing or lagging at fetch
|
|
8
|
-
* time: just after a create-and-redirect, or in a second tab racing the server mirror).
|
|
9
|
-
* This scheduler restores the recovery without a listener: after an absent result it
|
|
10
|
-
* re-reads a few times on a widening ladder, then gives up.
|
|
11
|
-
*
|
|
12
|
-
* Delays (ms) between re-reads within one absence episode. After the last rung the episode
|
|
13
|
-
* is exhausted and never restarts on its own; only a later PRESENT→absent transition opens
|
|
14
|
-
* a new one.
|
|
15
|
-
*/
|
|
16
2
|
export declare const ABSENT_RETRY_DELAYS_MS: readonly [5000, 15000, 45000, 120000];
|
|
17
3
|
export interface TrackAbsentDocParams {
|
|
18
4
|
queryClient: QueryClient;
|
|
19
|
-
/** Exact key of the per-id lookup query. */
|
|
20
5
|
queryKey: QueryKey;
|
|
21
|
-
/**
|
|
22
|
-
* Ladder this registrant wants; an empty array means it wants no re-reads. Registrants
|
|
23
|
-
* on the same key combine by union — the longest ladder among them governs — so one
|
|
24
|
-
* consumer passing `[]` never disables polling another consumer asked for.
|
|
25
|
-
*/
|
|
26
6
|
delays?: readonly number[];
|
|
27
7
|
}
|
|
28
|
-
/**
|
|
29
|
-
* Register interest in re-reading `queryKey` while it resolves absent. Returns an
|
|
30
|
-
* idempotent release function; releasing the last interested consumer pauses the ladder
|
|
31
|
-
* without spending the episode's remaining budget, and releasing the last registrant that
|
|
32
|
-
* wanted polling shrinks the effective ladder for the episode still in progress.
|
|
33
|
-
*/
|
|
34
8
|
export declare function trackAbsentDoc({ queryClient, queryKey, delays, }: TrackAbsentDocParams): () => void;
|
|
35
|
-
/** Test-only: number of absence episodes currently tracked for a QueryClient. */
|
|
36
9
|
export declare function __absenceEpisodeCount(queryClient: QueryClient): number;
|
|
37
|
-
/** Test-only: rungs already spent on a key's current episode, or `null` if there is none. */
|
|
38
10
|
export declare function __absenceAttempt(queryClient: QueryClient, queryKey: QueryKey): number | null;
|
|
39
11
|
//# sourceMappingURL=absence-scheduler.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"absence-scheduler.d.ts","sourceRoot":"","sources":["../../../src/react/firestore/absence-scheduler.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEnE
|
|
1
|
+
{"version":3,"file":"absence-scheduler.d.ts","sourceRoot":"","sources":["../../../src/react/firestore/absence-scheduler.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEnE,eAAO,MAAM,sBAAsB,uCAA4C,CAAC;AAwIhF,MAAM,WAAW,oBAAoB;IACnC,WAAW,EAAE,WAAW,CAAC;IACzB,QAAQ,EAAE,QAAQ,CAAC;IACnB,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5B;AAED,wBAAgB,cAAc,CAAC,EAC7B,WAAW,EACX,QAAQ,EACR,MAA+B,GAChC,EAAE,oBAAoB,GAAG,MAAM,IAAI,CAiCnC;AAED,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,WAAW,GAAG,MAAM,CAEtE;AAED,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,WAAW,EAAE,QAAQ,EAAE,QAAQ,GAAG,MAAM,GAAG,IAAI,CAE5F"}
|
|
@@ -1,31 +1,11 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
/**
|
|
3
|
-
* Bounded re-read ladder for a document that resolved ABSENT.
|
|
4
|
-
*
|
|
5
|
-
* A one-shot lookup that lands `null` has no listener to tell it when the doc appears —
|
|
6
|
-
* the row would stay blank until something invalidates it. That is the real failure the
|
|
7
|
-
* realtime path was introduced to fix (a mirror doc that is missing or lagging at fetch
|
|
8
|
-
* time: just after a create-and-redirect, or in a second tab racing the server mirror).
|
|
9
|
-
* This scheduler restores the recovery without a listener: after an absent result it
|
|
10
|
-
* re-reads a few times on a widening ladder, then gives up.
|
|
11
|
-
*
|
|
12
|
-
* Delays (ms) between re-reads within one absence episode. After the last rung the episode
|
|
13
|
-
* is exhausted and never restarts on its own; only a later PRESENT→absent transition opens
|
|
14
|
-
* a new one.
|
|
15
|
-
*/
|
|
16
2
|
export const ABSENT_RETRY_DELAYS_MS = [5_000, 15_000, 45_000, 120_000];
|
|
17
3
|
const NO_DELAYS = [];
|
|
18
|
-
// Per-QueryClient, like the doc-subscription registry: a discarded client is GC'd with its
|
|
19
|
-
// bookkeeping, and each browser tab schedules independently.
|
|
20
4
|
const schedulers = new WeakMap();
|
|
21
|
-
/**
|
|
22
|
-
* Hash a key the way THIS client hashes it, so a consumer with a custom
|
|
23
|
-
* `queryKeyHashFn` still lines up with `QueryCache.get()`.
|
|
24
|
-
*/
|
|
5
|
+
/** Hashes with this client's `queryKeyHashFn` so a custom hash still lines up with `QueryCache.get()`. */
|
|
25
6
|
function hashOf(queryClient, queryKey) {
|
|
26
7
|
return queryClient.defaultQueryOptions({ queryKey }).queryHash;
|
|
27
8
|
}
|
|
28
|
-
/** Union of the registrants' ladders: the longest one wins; none means no polling. */
|
|
29
9
|
function effectiveDelays(tracked) {
|
|
30
10
|
if (!tracked)
|
|
31
11
|
return NO_DELAYS;
|
|
@@ -61,8 +41,6 @@ function schedule(queryClient, state, hash) {
|
|
|
61
41
|
if (!current || !isAbsentAndActive(queryClient, hash))
|
|
62
42
|
return;
|
|
63
43
|
void queryClient.refetchQueries({ queryKey: current.queryKey, exact: true, type: 'active' });
|
|
64
|
-
// Lay the next rung; the ladder stops the moment the doc appears, the budget runs
|
|
65
|
-
// out, or the last enabled observer goes away.
|
|
66
44
|
evaluate(queryClient, state, hash);
|
|
67
45
|
}, delays[episode.attempt]);
|
|
68
46
|
}
|
|
@@ -80,13 +58,10 @@ function evaluate(queryClient, state, hash) {
|
|
|
80
58
|
}
|
|
81
59
|
const { status, data } = query.state;
|
|
82
60
|
if (status === 'success' && data !== null) {
|
|
83
|
-
// The doc is present — the episode is over.
|
|
84
61
|
discardEpisode(state, hash);
|
|
85
62
|
return;
|
|
86
63
|
}
|
|
87
64
|
if (status !== 'success') {
|
|
88
|
-
// Pending or errored: never polled, but the budget survives so an error mid-episode
|
|
89
|
-
// cannot hand the id a fresh ladder when it returns to absent.
|
|
90
65
|
clearTimer(state.episodes.get(hash));
|
|
91
66
|
return;
|
|
92
67
|
}
|
|
@@ -97,7 +72,6 @@ function evaluate(queryClient, state, hash) {
|
|
|
97
72
|
}
|
|
98
73
|
let episode = state.episodes.get(hash);
|
|
99
74
|
if (!episode) {
|
|
100
|
-
// No registrant wants polling — do not open an episode that could never spend a rung.
|
|
101
75
|
if (effectiveDelays(tracked).length === 0)
|
|
102
76
|
return;
|
|
103
77
|
episode = { attempt: 0, timer: null };
|
|
@@ -116,8 +90,6 @@ function getState(queryClient) {
|
|
|
116
90
|
state = { episodes: new Map(), tracked: new Map() };
|
|
117
91
|
schedulers.set(queryClient, state);
|
|
118
92
|
const scheduler = state;
|
|
119
|
-
// Exactly ONE cache listener per QueryClient, created with this state and never detached:
|
|
120
|
-
// it is WeakMap-scoped, so it is collected together with the client it belongs to.
|
|
121
93
|
queryClient.getQueryCache().subscribe((event) => {
|
|
122
94
|
const hash = event.query.queryHash;
|
|
123
95
|
if (!scheduler.tracked.has(hash) && !scheduler.episodes.has(hash))
|
|
@@ -130,12 +102,6 @@ function getState(queryClient) {
|
|
|
130
102
|
});
|
|
131
103
|
return state;
|
|
132
104
|
}
|
|
133
|
-
/**
|
|
134
|
-
* Register interest in re-reading `queryKey` while it resolves absent. Returns an
|
|
135
|
-
* idempotent release function; releasing the last interested consumer pauses the ladder
|
|
136
|
-
* without spending the episode's remaining budget, and releasing the last registrant that
|
|
137
|
-
* wanted polling shrinks the effective ladder for the episode still in progress.
|
|
138
|
-
*/
|
|
139
105
|
export function trackAbsentDoc({ queryClient, queryKey, delays = ABSENT_RETRY_DELAYS_MS, }) {
|
|
140
106
|
const state = getState(queryClient);
|
|
141
107
|
const hash = hashOf(queryClient, queryKey);
|
|
@@ -164,18 +130,14 @@ export function trackAbsentDoc({ queryClient, queryKey, delays = ABSENT_RETRY_DE
|
|
|
164
130
|
return;
|
|
165
131
|
}
|
|
166
132
|
if (effectiveDelays(current).length !== before) {
|
|
167
|
-
// The effective ladder changed: re-derive under the new one rather than letting a
|
|
168
|
-
// timer from the departed registrant's ladder fire.
|
|
169
133
|
clearTimer(state.episodes.get(hash));
|
|
170
134
|
evaluate(queryClient, state, hash);
|
|
171
135
|
}
|
|
172
136
|
};
|
|
173
137
|
}
|
|
174
|
-
/** Test-only: number of absence episodes currently tracked for a QueryClient. */
|
|
175
138
|
export function __absenceEpisodeCount(queryClient) {
|
|
176
139
|
return schedulers.get(queryClient)?.episodes.size ?? 0;
|
|
177
140
|
}
|
|
178
|
-
/** Test-only: rungs already spent on a key's current episode, or `null` if there is none. */
|
|
179
141
|
export function __absenceAttempt(queryClient, queryKey) {
|
|
180
142
|
return schedulers.get(queryClient)?.episodes.get(hashOf(queryClient, queryKey))?.attempt ?? null;
|
|
181
143
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"absence-scheduler.js","sourceRoot":"","sources":["../../../src/react/firestore/absence-scheduler.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAIb;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAU,CAAC;AA+ChF,MAAM,SAAS,GAAsB,EAAE,CAAC;AAExC,2FAA2F;AAC3F,6DAA6D;AAC7D,MAAM,UAAU,GAAG,IAAI,OAAO,EAA+B,CAAC;AAE9D;;;GAGG;AACH,SAAS,MAAM,CAAC,WAAwB,EAAE,QA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AACjF,MAAM,UAAU,qBAAqB,CAAC,WAAwB;IAC5D,OAAO,UAAU,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,QAAQ,CAAC,IAAI,IAAI,CAAC,CAAC;AACzD,CAAC;AAED,6FAA6F;AAC7F,MAAM,UAAU,gBAAgB,CAAC,WAAwB,EAAE,QAAkB;IAC3E,OAAO,UAAU,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,EAAE,OAAO,IAAI,IAAI,CAAC;AACnG,CAAC","sourcesContent":["'use client';\n\nimport type { QueryClient, QueryKey } from '@tanstack/react-query';\n\n/**\n * Bounded re-read ladder for a document that resolved ABSENT.\n *\n * A one-shot lookup that lands `null` has no listener to tell it when the doc appears —\n * the row would stay blank until something invalidates it. That is the real failure the\n * realtime path was introduced to fix (a mirror doc that is missing or lagging at fetch\n * time: just after a create-and-redirect, or in a second tab racing the server mirror).\n * This scheduler restores the recovery without a listener: after an absent result it\n * re-reads a few times on a widening ladder, then gives up.\n *\n * Delays (ms) between re-reads within one absence episode. After the last rung the episode\n * is exhausted and never restarts on its own; only a later PRESENT→absent transition opens\n * a new one.\n */\nexport const ABSENT_RETRY_DELAYS_MS = [5_000, 15_000, 45_000, 120_000] as const;\n\n/**\n * The rules the scheduler holds to:\n *\n * - It polls ONLY a query in `status: 'success'` whose data is `null`. An error state is\n * never polled (a denial is not an absence), and an error mid-episode pauses the ladder\n * with its remaining budget intact.\n * - One timer per query key and one budget per absence episode: the first successful\n * `undefined → null` opens the episode, and neither a repeated `null` nor an additional\n * consumer resets it. A `present → null` transition opens a NEW episode.\n * - Several consumers may register the same key with DIFFERENT ladders. The effective\n * ladder is the union: poll if any registrant wants polling, using the LONGEST ladder\n * among them, recomputed on every register and release. Mount order never decides.\n * - Eligibility is TanStack's `query.isActive()` — at least one observer that is not\n * disabled. Subscribe-mode and disabled observers therefore never keep an episode\n * polling, while disabling ONE consumer cannot stop polling another still needs.\n * - Losing the last enabled observer PAUSES the ladder and retains the episode's remaining\n * rungs; a later enabled observer resumes from there. A new observer on an EXHAUSTED\n * episode does not restart it.\n * - Cache removal (gc) discards the episode outright, so a later re-fetch that lands absent\n * starts fresh.\n *\n * Because the timer is per key rather than per observer, N consumers of one absent id cost\n * one re-read per rung, not N.\n */\n\ntype Episode = {\n /** Rungs consumed so far; `>= effectiveDelays().length` means exhausted. */\n attempt: number;\n timer: ReturnType<typeof setTimeout> | null;\n};\n\ntype Registration = {\n delays: readonly number[];\n};\n\ntype Tracked = {\n queryKey: QueryKey;\n registrations: Registration[];\n};\n\ntype SchedulerState = {\n episodes: Map<string, Episode>;\n tracked: Map<string, Tracked>;\n};\n\nconst NO_DELAYS: readonly number[] = [];\n\n// Per-QueryClient, like the doc-subscription registry: a discarded client is GC'd with its\n// bookkeeping, and each browser tab schedules independently.\nconst schedulers = new WeakMap<QueryClient, SchedulerState>();\n\n/**\n * Hash a key the way THIS client hashes it, so a consumer with a custom\n * `queryKeyHashFn` still lines up with `QueryCache.get()`.\n */\nfunction hashOf(queryClient: QueryClient, queryKey: QueryKey): string {\n return queryClient.defaultQueryOptions({ queryKey }).queryHash;\n}\n\n/** Union of the registrants' ladders: the longest one wins; none means no polling. */\nfunction effectiveDelays(tracked: Tracked | undefined): readonly number[] {\n if (!tracked) return NO_DELAYS;\n let longest: readonly number[] = NO_DELAYS;\n for (const registration of tracked.registrations) {\n if (registration.delays.length > longest.length) longest = registration.delays;\n }\n return longest;\n}\n\nfunction clearTimer(episode: Episode | undefined): void {\n if (episode?.timer != null) {\n clearTimeout(episode.timer);\n episode.timer = null;\n }\n}\n\nfunction discardEpisode(state: SchedulerState, hash: string): void {\n clearTimer(state.episodes.get(hash));\n state.episodes.delete(hash);\n}\n\nfunction schedule(queryClient: QueryClient, state: SchedulerState, hash: string): void {\n const tracked = state.tracked.get(hash);\n const episode = state.episodes.get(hash);\n if (!tracked || !episode || episode.timer !== null) return;\n\n const delays = effectiveDelays(tracked);\n if (episode.attempt >= delays.length) return;\n\n episode.timer = setTimeout(() => {\n episode.timer = null;\n episode.attempt += 1;\n const current = state.tracked.get(hash);\n if (!current || !isAbsentAndActive(queryClient, hash)) return;\n void queryClient.refetchQueries({ queryKey: current.queryKey, exact: true, type: 'active' });\n // Lay the next rung; the ladder stops the moment the doc appears, the budget runs\n // out, or the last enabled observer goes away.\n evaluate(queryClient, state, hash);\n }, delays[episode.attempt]);\n}\n\nfunction isAbsentAndActive(queryClient: QueryClient, hash: string): boolean {\n const query = queryClient.getQueryCache().get(hash);\n if (!query) return false;\n return query.state.status === 'success' && query.state.data === null && query.isActive();\n}\n\nfunction evaluate(queryClient: QueryClient, state: SchedulerState, hash: string): void {\n const query = queryClient.getQueryCache().get(hash);\n if (!query) {\n discardEpisode(state, hash);\n return;\n }\n\n const { status, data } = query.state;\n\n if (status === 'success' && data !== null) {\n // The doc is present — the episode is over.\n discardEpisode(state, hash);\n return;\n }\n\n if (status !== 'success') {\n // Pending or errored: never polled, but the budget survives so an error mid-episode\n // cannot hand the id a fresh ladder when it returns to absent.\n clearTimer(state.episodes.get(hash));\n return;\n }\n\n const tracked = state.tracked.get(hash);\n if (!tracked) {\n clearTimer(state.episodes.get(hash));\n return;\n }\n\n let episode = state.episodes.get(hash);\n if (!episode) {\n // No registrant wants polling — do not open an episode that could never spend a rung.\n if (effectiveDelays(tracked).length === 0) return;\n episode = { attempt: 0, timer: null };\n state.episodes.set(hash, episode);\n }\n\n if (!query.isActive()) {\n clearTimer(episode);\n return;\n }\n\n schedule(queryClient, state, hash);\n}\n\nfunction getState(queryClient: QueryClient): SchedulerState {\n let state = schedulers.get(queryClient);\n if (state) return state;\n\n state = { episodes: new Map(), tracked: new Map() };\n schedulers.set(queryClient, state);\n\n const scheduler = state;\n // Exactly ONE cache listener per QueryClient, created with this state and never detached:\n // it is WeakMap-scoped, so it is collected together with the client it belongs to.\n queryClient.getQueryCache().subscribe((event) => {\n const hash = event.query.queryHash;\n if (!scheduler.tracked.has(hash) && !scheduler.episodes.has(hash)) return;\n if (event.type === 'removed') {\n discardEpisode(scheduler, hash);\n return;\n }\n evaluate(queryClient, scheduler, hash);\n });\n\n return state;\n}\n\nexport interface TrackAbsentDocParams {\n queryClient: QueryClient;\n /** Exact key of the per-id lookup query. */\n queryKey: QueryKey;\n /**\n * Ladder this registrant wants; an empty array means it wants no re-reads. Registrants\n * on the same key combine by union — the longest ladder among them governs — so one\n * consumer passing `[]` never disables polling another consumer asked for.\n */\n delays?: readonly number[];\n}\n\n/**\n * Register interest in re-reading `queryKey` while it resolves absent. Returns an\n * idempotent release function; releasing the last interested consumer pauses the ladder\n * without spending the episode's remaining budget, and releasing the last registrant that\n * wanted polling shrinks the effective ladder for the episode still in progress.\n */\nexport function trackAbsentDoc({\n queryClient,\n queryKey,\n delays = ABSENT_RETRY_DELAYS_MS,\n}: TrackAbsentDocParams): () => void {\n const state = getState(queryClient);\n const hash = hashOf(queryClient, queryKey);\n const registration: Registration = { delays };\n\n const existing = state.tracked.get(hash);\n if (existing) existing.registrations.push(registration);\n else state.tracked.set(hash, { queryKey, registrations: [registration] });\n\n evaluate(queryClient, state, hash);\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = state.tracked.get(hash);\n if (!current) return;\n\n const before = effectiveDelays(current).length;\n const index = current.registrations.indexOf(registration);\n if (index >= 0) current.registrations.splice(index, 1);\n\n if (current.registrations.length === 0) {\n state.tracked.delete(hash);\n clearTimer(state.episodes.get(hash));\n return;\n }\n\n if (effectiveDelays(current).length !== before) {\n // The effective ladder changed: re-derive under the new one rather than letting a\n // timer from the departed registrant's ladder fire.\n clearTimer(state.episodes.get(hash));\n evaluate(queryClient, state, hash);\n }\n };\n}\n\n/** Test-only: number of absence episodes currently tracked for a QueryClient. */\nexport function __absenceEpisodeCount(queryClient: QueryClient): number {\n return schedulers.get(queryClient)?.episodes.size ?? 0;\n}\n\n/** Test-only: rungs already spent on a key's current episode, or `null` if there is none. */\nexport function __absenceAttempt(queryClient: QueryClient, queryKey: QueryKey): number | null {\n return schedulers.get(queryClient)?.episodes.get(hashOf(queryClient, queryKey))?.attempt ?? null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"absence-scheduler.js","sourceRoot":"","sources":["../../../src/react/firestore/absence-scheduler.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAIb,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAU,CAAC;AAqBhF,MAAM,SAAS,GAAsB,EAAE,CAAC;AAExC,MAAM,UAAU,GAAG,IAAI,OAAO,EAA+B,CAAC;AAE9D,0GAA0G;AAC1G,SAAS,MAAM,CAAC,WAAwB,EAAE,QAAkB;IAC1D,OAAO,WAAW,CAAC,mBAAmB,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,SAAS,CAAC;AACjE,CAAC;AAED,SAAS,eAAe,CAAC,OAA4B;IACnD,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,IAAI,OAAO,GAAsB,SAAS,CAAC;IAC3C,KAAK,MAAM,YAAY,IAAI,OAAO,CAAC,aAAa,EAAE,CAAC;QACjD,IAAI,YAAY,CAAC,MAAM,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM;YAAE,OAAO,GAAG,YAAY,CAAC,MAAM,CAAC;IACjF,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,SAAS,UAAU,CAAC,OAA4B;IAC9C,IAAI,OAAO,EAAE,KAAK,IAAI,IAAI,EAAE,CAAC;QAC3B,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAC5B,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC;IACvB,CAAC;AACH,CAAC;AAED,SAAS,cAAc,CAAC,KAAqB,EAAE,IAAY;IACzD,UAAU,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;IAC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AAC;YACrC,OAAO;QACT,CAAC;QAED,IAAI,eAAe,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;YAC/C,UAAU,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;YACrC,QAAQ,CAAC,WAAW,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;QACrC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,WAAwB;IAC5D,OAAO,UAAU,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,QAAQ,CAAC,IAAI,IAAI,CAAC,CAAC;AACzD,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,WAAwB,EAAE,QAAkB;IAC3E,OAAO,UAAU,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,EAAE,OAAO,IAAI,IAAI,CAAC;AACnG,CAAC","sourcesContent":["'use client';\n\nimport type { QueryClient, QueryKey } from '@tanstack/react-query';\n\nexport const ABSENT_RETRY_DELAYS_MS = [5_000, 15_000, 45_000, 120_000] as const;\n\ntype Episode = {\n attempt: number;\n timer: ReturnType<typeof setTimeout> | null;\n};\n\ntype Registration = {\n delays: readonly number[];\n};\n\ntype Tracked = {\n queryKey: QueryKey;\n registrations: Registration[];\n};\n\ntype SchedulerState = {\n episodes: Map<string, Episode>;\n tracked: Map<string, Tracked>;\n};\n\nconst NO_DELAYS: readonly number[] = [];\n\nconst schedulers = new WeakMap<QueryClient, SchedulerState>();\n\n/** Hashes with this client's `queryKeyHashFn` so a custom hash still lines up with `QueryCache.get()`. */\nfunction hashOf(queryClient: QueryClient, queryKey: QueryKey): string {\n return queryClient.defaultQueryOptions({ queryKey }).queryHash;\n}\n\nfunction effectiveDelays(tracked: Tracked | undefined): readonly number[] {\n if (!tracked) return NO_DELAYS;\n let longest: readonly number[] = NO_DELAYS;\n for (const registration of tracked.registrations) {\n if (registration.delays.length > longest.length) longest = registration.delays;\n }\n return longest;\n}\n\nfunction clearTimer(episode: Episode | undefined): void {\n if (episode?.timer != null) {\n clearTimeout(episode.timer);\n episode.timer = null;\n }\n}\n\nfunction discardEpisode(state: SchedulerState, hash: string): void {\n clearTimer(state.episodes.get(hash));\n state.episodes.delete(hash);\n}\n\nfunction schedule(queryClient: QueryClient, state: SchedulerState, hash: string): void {\n const tracked = state.tracked.get(hash);\n const episode = state.episodes.get(hash);\n if (!tracked || !episode || episode.timer !== null) return;\n\n const delays = effectiveDelays(tracked);\n if (episode.attempt >= delays.length) return;\n\n episode.timer = setTimeout(() => {\n episode.timer = null;\n episode.attempt += 1;\n const current = state.tracked.get(hash);\n if (!current || !isAbsentAndActive(queryClient, hash)) return;\n void queryClient.refetchQueries({ queryKey: current.queryKey, exact: true, type: 'active' });\n evaluate(queryClient, state, hash);\n }, delays[episode.attempt]);\n}\n\nfunction isAbsentAndActive(queryClient: QueryClient, hash: string): boolean {\n const query = queryClient.getQueryCache().get(hash);\n if (!query) return false;\n return query.state.status === 'success' && query.state.data === null && query.isActive();\n}\n\nfunction evaluate(queryClient: QueryClient, state: SchedulerState, hash: string): void {\n const query = queryClient.getQueryCache().get(hash);\n if (!query) {\n discardEpisode(state, hash);\n return;\n }\n\n const { status, data } = query.state;\n\n if (status === 'success' && data !== null) {\n discardEpisode(state, hash);\n return;\n }\n\n if (status !== 'success') {\n clearTimer(state.episodes.get(hash));\n return;\n }\n\n const tracked = state.tracked.get(hash);\n if (!tracked) {\n clearTimer(state.episodes.get(hash));\n return;\n }\n\n let episode = state.episodes.get(hash);\n if (!episode) {\n if (effectiveDelays(tracked).length === 0) return;\n episode = { attempt: 0, timer: null };\n state.episodes.set(hash, episode);\n }\n\n if (!query.isActive()) {\n clearTimer(episode);\n return;\n }\n\n schedule(queryClient, state, hash);\n}\n\nfunction getState(queryClient: QueryClient): SchedulerState {\n let state = schedulers.get(queryClient);\n if (state) return state;\n\n state = { episodes: new Map(), tracked: new Map() };\n schedulers.set(queryClient, state);\n\n const scheduler = state;\n queryClient.getQueryCache().subscribe((event) => {\n const hash = event.query.queryHash;\n if (!scheduler.tracked.has(hash) && !scheduler.episodes.has(hash)) return;\n if (event.type === 'removed') {\n discardEpisode(scheduler, hash);\n return;\n }\n evaluate(queryClient, scheduler, hash);\n });\n\n return state;\n}\n\nexport interface TrackAbsentDocParams {\n queryClient: QueryClient;\n queryKey: QueryKey;\n delays?: readonly number[];\n}\n\nexport function trackAbsentDoc({\n queryClient,\n queryKey,\n delays = ABSENT_RETRY_DELAYS_MS,\n}: TrackAbsentDocParams): () => void {\n const state = getState(queryClient);\n const hash = hashOf(queryClient, queryKey);\n const registration: Registration = { delays };\n\n const existing = state.tracked.get(hash);\n if (existing) existing.registrations.push(registration);\n else state.tracked.set(hash, { queryKey, registrations: [registration] });\n\n evaluate(queryClient, state, hash);\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = state.tracked.get(hash);\n if (!current) return;\n\n const before = effectiveDelays(current).length;\n const index = current.registrations.indexOf(registration);\n if (index >= 0) current.registrations.splice(index, 1);\n\n if (current.registrations.length === 0) {\n state.tracked.delete(hash);\n clearTimer(state.episodes.get(hash));\n return;\n }\n\n if (effectiveDelays(current).length !== before) {\n clearTimer(state.episodes.get(hash));\n evaluate(queryClient, state, hash);\n }\n };\n}\n\nexport function __absenceEpisodeCount(queryClient: QueryClient): number {\n return schedulers.get(queryClient)?.episodes.size ?? 0;\n}\n\nexport function __absenceAttempt(queryClient: QueryClient, queryKey: QueryKey): number | null {\n return schedulers.get(queryClient)?.episodes.get(hashOf(queryClient, queryKey))?.attempt ?? null;\n}\n"]}
|
|
@@ -1,42 +1,12 @@
|
|
|
1
1
|
import { type Firestore } from 'firebase/firestore';
|
|
2
2
|
import type { QueryClient } from '@tanstack/react-query';
|
|
3
|
-
/**
|
|
4
|
-
* Coalescing document loader behind {@link useBatchFirestoreDocs}'s one-shot mode.
|
|
5
|
-
*
|
|
6
|
-
* Every id is its own observed React Query query, so without coalescing N ids would issue
|
|
7
|
-
* N Firestore round-trips. The loader collects the ids enqueued in a single microtask and
|
|
8
|
-
* dispatches them as `where(documentId(), 'in', chunk)` queries of at most `FIRESTORE_IN_FILTER_LIMIT` ids each
|
|
9
|
-
* (`'batch'` transport), or as concurrent per-document gets (`'get'` transport — required
|
|
10
|
-
* for collections whose rules gate reads on `resource.data`, where an unconstrained list
|
|
11
|
-
* query is denied wholesale but per-document gets are evaluated per doc).
|
|
12
|
-
*
|
|
13
|
-
* Two properties are load-bearing:
|
|
14
|
-
*
|
|
15
|
-
* - **The loader resolves promises only — it NEVER writes the query cache.** TanStack's
|
|
16
|
-
* per-query fetch identity is therefore the sole guard against a late batch response
|
|
17
|
-
* overwriting a newer per-id result.
|
|
18
|
-
* - **A dispatched batch is closed.** A later enqueue of the same id (a refetch after a
|
|
19
|
-
* cancellation, say) always joins a NEW batch, never the in-flight one — so a cancelled
|
|
20
|
-
* read can never be served by the request it was cancelled out of.
|
|
21
|
-
*
|
|
22
|
-
* Cancelling one per-id query detaches only that waiter; the shared request still completes
|
|
23
|
-
* for its batch-mates.
|
|
24
|
-
*
|
|
25
|
-
* Loaders are scoped per `(QueryClient, Firestore instance, collectionPath)`. The Firestore
|
|
26
|
-
* instance is part of the scope on purpose: two `db` instances sharing a collection path
|
|
27
|
-
* must never share a request.
|
|
28
|
-
*/
|
|
29
|
-
/** Maximum `in`-query requests in flight at once, per loader scope. */
|
|
30
3
|
export declare const MAX_CONCURRENT_BATCH_REQUESTS = 4;
|
|
31
|
-
/** Maximum per-document gets in flight at once, per loader scope. */
|
|
32
4
|
export declare const MAX_CONCURRENT_DOC_GETS = 12;
|
|
33
5
|
export type LoadedDoc = Record<string, unknown> & {
|
|
34
6
|
id: string;
|
|
35
7
|
};
|
|
36
8
|
export type DocLoader = {
|
|
37
|
-
/** Resolve one id through the coalescing `in`-query batcher. */
|
|
38
9
|
loadBatched(id: string, signal?: AbortSignal): Promise<LoadedDoc | null>;
|
|
39
|
-
/** Resolve one id through its own `getDoc`, bounded by the get concurrency limit. */
|
|
40
10
|
loadOne(id: string, signal?: AbortSignal): Promise<LoadedDoc | null>;
|
|
41
11
|
};
|
|
42
12
|
export declare function getDocLoader(queryClient: QueryClient, db: Firestore, collectionPath: string): DocLoader;
|