@tanstack/angular-query-experimental 5.102.8 → 5.103.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"inject-is-mutating.mjs","sources":["../src/inject-is-mutating.ts"],"sourcesContent":["import {\n DestroyRef,\n Injector,\n NgZone,\n assertInInjectionContext,\n inject,\n signal,\n} from '@angular/core'\nimport { QueryClient, notifyManager } from '@tanstack/query-core'\nimport type { MutationFilters } from '@tanstack/query-core'\nimport type { Signal } from '@angular/core'\n\nexport interface InjectIsMutatingOptions {\n /**\n * The `Injector` in which to create the isMutating signal.\n *\n * If this is not provided, the current injection context will be used instead (via `inject`).\n */\n injector?: Injector\n}\n\n/**\n * Injects a signal that tracks the number of mutations that your application is fetching.\n *\n * Can be used for app-wide loading indicators\n * @param filters - The filters to apply to the query.\n * @param options - Additional configuration\n * @returns A read-only signal with the number of fetching mutations.\n */\nexport function injectIsMutating(\n filters?: MutationFilters,\n options?: InjectIsMutatingOptions,\n): Signal<number> {\n !options?.injector && assertInInjectionContext(injectIsMutating)\n const injector = options?.injector ?? inject(Injector)\n const destroyRef = injector.get(DestroyRef)\n const ngZone = injector.get(NgZone)\n const queryClient = injector.get(QueryClient)\n\n const cache = queryClient.getMutationCache()\n // isMutating is the prev value initialized on mount *\n let isMutating = queryClient.isMutating(filters)\n\n const result = signal(isMutating)\n\n const unsubscribe = ngZone.runOutsideAngular(() =>\n cache.subscribe(\n notifyManager.batchCalls(() => {\n const newIsMutating = queryClient.isMutating(filters)\n if (isMutating !== newIsMutating) {\n // * and update with each change\n isMutating = newIsMutating\n ngZone.run(() => {\n result.set(isMutating)\n })\n }\n }),\n ),\n )\n\n destroyRef.onDestroy(unsubscribe)\n\n return result.asReadonly()\n}\n"],"names":[],"mappings":";;AA6BO,SAAS,iBACd,SACA,SACgB;AAChB,IAAC,mCAAS,aAAY,yBAAyB,gBAAgB;AAC/D,QAAM,YAAW,mCAAS,aAAY,OAAO,QAAQ;AACrD,QAAM,aAAa,SAAS,IAAI,UAAU;AAC1C,QAAM,SAAS,SAAS,IAAI,MAAM;AAClC,QAAM,cAAc,SAAS,IAAI,WAAW;AAE5C,QAAM,QAAQ,YAAY,iBAAA;AAE1B,MAAI,aAAa,YAAY,WAAW,OAAO;AAE/C,QAAM,SAAS,OAAO,UAAU;AAEhC,QAAM,cAAc,OAAO;AAAA,IAAkB,MAC3C,MAAM;AAAA,MACJ,cAAc,WAAW,MAAM;AAC7B,cAAM,gBAAgB,YAAY,WAAW,OAAO;AACpD,YAAI,eAAe,eAAe;AAEhC,uBAAa;AACb,iBAAO,IAAI,MAAM;AACf,mBAAO,IAAI,UAAU;AAAA,UACvB,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,IAAA;AAAA,EACH;AAGF,aAAW,UAAU,WAAW;AAEhC,SAAO,OAAO,WAAA;AAChB;"}
1
+ {"version":3,"file":"inject-is-mutating.mjs","sources":["../src/inject-is-mutating.ts"],"sourcesContent":["import {\n DestroyRef,\n Injector,\n NgZone,\n assertInInjectionContext,\n inject,\n signal,\n} from '@angular/core'\nimport { QueryClient, notifyManager } from '@tanstack/query-core'\nimport type { MutationFilters } from '@tanstack/query-core'\nimport type { Signal } from '@angular/core'\n\nexport interface InjectIsMutatingOptions {\n /**\n * The `Injector` in which to create the isMutating signal.\n *\n * If this is not provided, the current injection context will be used instead (via `inject`).\n */\n injector?: Injector\n}\n\n/**\n * Injects a signal that tracks the number of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n *\n * @param filters - The {@link MutationFilters} to narrow down the matched mutations.\n * @param options - Additional configuration\n * @returns A `Signal` with the number of mutations that your application currently has `pending`.\n *\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts-mutating-indicator',\n * template: `\n * @if (isMutatingPosts()) {\n * <span>Saving posts...</span>\n * }\n * `,\n * })\n * export class PostsMutatingIndicator {\n * // How many mutations matching the posts prefix are in progress?\n * readonly isMutatingPosts = injectIsMutating({ mutationKey: ['posts'] })\n * }\n * ```\n */\nexport function injectIsMutating(\n filters?: MutationFilters,\n options?: InjectIsMutatingOptions,\n): Signal<number> {\n !options?.injector && assertInInjectionContext(injectIsMutating)\n const injector = options?.injector ?? inject(Injector)\n const destroyRef = injector.get(DestroyRef)\n const ngZone = injector.get(NgZone)\n const queryClient = injector.get(QueryClient)\n\n const cache = queryClient.getMutationCache()\n // isMutating is the prev value initialized on mount *\n let isMutating = queryClient.isMutating(filters)\n\n const result = signal(isMutating)\n\n const unsubscribe = ngZone.runOutsideAngular(() =>\n cache.subscribe(\n notifyManager.batchCalls(() => {\n const newIsMutating = queryClient.isMutating(filters)\n if (isMutating !== newIsMutating) {\n // * and update with each change\n isMutating = newIsMutating\n ngZone.run(() => {\n result.set(isMutating)\n })\n }\n }),\n ),\n )\n\n destroyRef.onDestroy(unsubscribe)\n\n return result.asReadonly()\n}\n"],"names":[],"mappings":";;AA6CO,SAAS,iBACd,SACA,SACgB;AAChB,IAAC,mCAAS,aAAY,yBAAyB,gBAAgB;AAC/D,QAAM,YAAW,mCAAS,aAAY,OAAO,QAAQ;AACrD,QAAM,aAAa,SAAS,IAAI,UAAU;AAC1C,QAAM,SAAS,SAAS,IAAI,MAAM;AAClC,QAAM,cAAc,SAAS,IAAI,WAAW;AAE5C,QAAM,QAAQ,YAAY,iBAAA;AAE1B,MAAI,aAAa,YAAY,WAAW,OAAO;AAE/C,QAAM,SAAS,OAAO,UAAU;AAEhC,QAAM,cAAc,OAAO;AAAA,IAAkB,MAC3C,MAAM;AAAA,MACJ,cAAc,WAAW,MAAM;AAC7B,cAAM,gBAAgB,YAAY,WAAW,OAAO;AACpD,YAAI,eAAe,eAAe;AAEhC,uBAAa;AACb,iBAAO,IAAI,MAAM;AACf,mBAAO,IAAI,UAAU;AAAA,UACvB,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,IAAA;AAAA,EACH;AAGF,aAAW,UAAU,WAAW;AAEhC,SAAO,OAAO,WAAA;AAChB;"}
@@ -8,15 +8,20 @@ interface InjectIsRestoringOptions {
8
8
  injector?: Injector;
9
9
  }
10
10
  /**
11
- * Injects a signal that tracks whether a restore is currently in progress. {@link injectQuery} and friends also check this internally to avoid race conditions between the restore and initializing queries.
12
- * @param options - Options for injectIsRestoring.
13
- * @returns readonly signal with boolean that indicates whether a restore is in progress.
11
+ * Injects a signal that tracks whether a restore (e.g. from a persisted client, wired up via
12
+ * `provideIsRestoring`) is currently in progress. `injectQuery` and friends also check this internally to
13
+ * avoid race conditions between the restore and initializing queries.
14
+ * @param options - Additional configuration
15
+ * @returns A readonly `Signal<boolean>` — `true` while a restore is in progress, `false` otherwise (the
16
+ * default when no `provideIsRestoring` provider is registered).
14
17
  */
15
18
  export declare function injectIsRestoring(options?: InjectIsRestoringOptions): Signal<boolean>;
16
19
  /**
17
- * Used by TanStack Query Angular persist client plugin to provide the signal that tracks the restore state
18
- * @param isRestoring - a readonly signal that returns a boolean
19
- * @returns Provider for the `isRestoring` signal
20
+ * Registers a provider for the restore state read by `injectIsRestoring`. Wire this up wherever you drive a
21
+ * restore yourself — e.g. a persist-client integration — so `injectQuery` and friends can defer subscribing
22
+ * to their observer (avoiding a race with the restore) until the restore signal flips back to `false`.
23
+ * @param isRestoring - A readonly `Signal<boolean>` that tracks the restore state.
24
+ * @returns A provider for the `isRestoring` signal.
20
25
  */
21
26
  export declare function provideIsRestoring(isRestoring: Signal<boolean>): Provider;
22
27
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"inject-is-restoring.mjs","sources":["../src/inject-is-restoring.ts"],"sourcesContent":["import {\n InjectionToken,\n Injector,\n assertInInjectionContext,\n inject,\n signal,\n} from '@angular/core'\nimport type { Provider, Signal } from '@angular/core'\n\n/**\n * Internal token used to track isRestoring state, accessible in public API through `injectIsRestoring` and set via `provideIsRestoring`\n */\nconst IS_RESTORING = new InjectionToken('', {\n // Default value when not provided\n factory: () => signal(false).asReadonly(),\n})\n\ninterface InjectIsRestoringOptions {\n /**\n * The `Injector` to use to get the isRestoring signal.\n *\n * If this is not provided, the current injection context will be used instead (via `inject`).\n */\n injector?: Injector\n}\n\n/**\n * Injects a signal that tracks whether a restore is currently in progress. {@link injectQuery} and friends also check this internally to avoid race conditions between the restore and initializing queries.\n * @param options - Options for injectIsRestoring.\n * @returns readonly signal with boolean that indicates whether a restore is in progress.\n */\nexport function injectIsRestoring(options?: InjectIsRestoringOptions) {\n !options?.injector && assertInInjectionContext(injectIsRestoring)\n const injector = options?.injector ?? inject(Injector)\n return injector.get(IS_RESTORING)\n}\n\n/**\n * Used by TanStack Query Angular persist client plugin to provide the signal that tracks the restore state\n * @param isRestoring - a readonly signal that returns a boolean\n * @returns Provider for the `isRestoring` signal\n */\nexport function provideIsRestoring(isRestoring: Signal<boolean>): Provider {\n return {\n provide: IS_RESTORING,\n useValue: isRestoring,\n }\n}\n"],"names":[],"mappings":";AAYA,MAAM,eAAe,IAAI,eAAe,IAAI;AAAA;AAAA,EAE1C,SAAS,MAAM,OAAO,KAAK,EAAE,WAAA;AAC/B,CAAC;AAgBM,SAAS,kBAAkB,SAAoC;AACpE,IAAC,mCAAS,aAAY,yBAAyB,iBAAiB;AAChE,QAAM,YAAW,mCAAS,aAAY,OAAO,QAAQ;AACrD,SAAO,SAAS,IAAI,YAAY;AAClC;AAOO,SAAS,mBAAmB,aAAwC;AACzE,SAAO;AAAA,IACL,SAAS;AAAA,IACT,UAAU;AAAA,EAAA;AAEd;"}
1
+ {"version":3,"file":"inject-is-restoring.mjs","sources":["../src/inject-is-restoring.ts"],"sourcesContent":["import {\n InjectionToken,\n Injector,\n assertInInjectionContext,\n inject,\n signal,\n} from '@angular/core'\nimport type { Provider, Signal } from '@angular/core'\n\n/**\n * Internal token used to track isRestoring state, accessible in public API through `injectIsRestoring` and set via `provideIsRestoring`\n */\nconst IS_RESTORING = new InjectionToken('', {\n // Default value when not provided\n factory: () => signal(false).asReadonly(),\n})\n\ninterface InjectIsRestoringOptions {\n /**\n * The `Injector` to use to get the isRestoring signal.\n *\n * If this is not provided, the current injection context will be used instead (via `inject`).\n */\n injector?: Injector\n}\n\n/**\n * Injects a signal that tracks whether a restore (e.g. from a persisted client, wired up via\n * `provideIsRestoring`) is currently in progress. `injectQuery` and friends also check this internally to\n * avoid race conditions between the restore and initializing queries.\n * @param options - Additional configuration\n * @returns A readonly `Signal<boolean>` — `true` while a restore is in progress, `false` otherwise (the\n * default when no `provideIsRestoring` provider is registered).\n */\nexport function injectIsRestoring(options?: InjectIsRestoringOptions) {\n !options?.injector && assertInInjectionContext(injectIsRestoring)\n const injector = options?.injector ?? inject(Injector)\n return injector.get(IS_RESTORING)\n}\n\n/**\n * Registers a provider for the restore state read by `injectIsRestoring`. Wire this up wherever you drive a\n * restore yourself — e.g. a persist-client integration — so `injectQuery` and friends can defer subscribing\n * to their observer (avoiding a race with the restore) until the restore signal flips back to `false`.\n * @param isRestoring - A readonly `Signal<boolean>` that tracks the restore state.\n * @returns A provider for the `isRestoring` signal.\n */\nexport function provideIsRestoring(isRestoring: Signal<boolean>): Provider {\n return {\n provide: IS_RESTORING,\n useValue: isRestoring,\n }\n}\n"],"names":[],"mappings":";AAYA,MAAM,eAAe,IAAI,eAAe,IAAI;AAAA;AAAA,EAE1C,SAAS,MAAM,OAAO,KAAK,EAAE,WAAA;AAC/B,CAAC;AAmBM,SAAS,kBAAkB,SAAoC;AACpE,IAAC,mCAAS,aAAY,yBAAyB,iBAAiB;AAChE,QAAM,YAAW,mCAAS,aAAY,OAAO,QAAQ;AACrD,SAAO,SAAS,IAAI,YAAY;AAClC;AASO,SAAS,mBAAmB,aAAwC;AACzE,SAAO;AAAA,IACL,SAAS;AAAA,IACT,UAAU;AAAA,EAAA;AAEd;"}
@@ -13,10 +13,61 @@ export interface InjectMutationStateOptions {
13
13
  injector?: Injector;
14
14
  }
15
15
  /**
16
- * Injects a signal that tracks the state of all mutations.
17
- * @param injectMutationStateFn - A function that returns mutation state options.
18
- * @param options - The Angular injector to use.
19
- * @returns The signal that tracks the state of all mutations.
16
+ * Injects a signal that gives you access to all mutations in the `MutationCache`. You can pass `filters`
17
+ * ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation state.
18
+ *
19
+ * @param injectMutationStateFn - A function returning the `filters` to narrow down matched mutations, and an
20
+ * optional `select` to transform the mutation state. Similar to `computed` from Angular, this function runs
21
+ * in the reactive context, so signals read inside it re-narrow the matched mutations.
22
+ * @param options - Additional configuration
23
+ * @returns A `Signal` with an Array of whatever `select` returns for each matching mutation.
24
+ *
25
+ * @example
26
+ * Get all variables of all running mutations:
27
+ * ```angular-ts
28
+ * @Component({
29
+ * selector: 'pending-posts',
30
+ * template: `{{ pendingVariables().length }} posts saving...`,
31
+ * })
32
+ * export class PendingPosts {
33
+ * readonly pendingVariables = injectMutationState(() => ({
34
+ * filters: { status: 'pending' },
35
+ * select: (mutation) => mutation.state.variables,
36
+ * }))
37
+ * }
38
+ * ```
39
+ *
40
+ * @example
41
+ * Get all data for specific mutations via the `mutationKey`:
42
+ * ```angular-ts
43
+ * const mutationKey = ['posts']
44
+ *
45
+ * @Component({
46
+ * selector: 'posts',
47
+ * template: `
48
+ * <button (click)="createPost()">
49
+ * Create post ({{ savedPosts().length }} saved so far)
50
+ * </button>
51
+ * `,
52
+ * })
53
+ * export class Posts {
54
+ * // Some mutation that we want to get the state for
55
+ * readonly createPostMutation = injectMutation(() => ({
56
+ * mutationKey,
57
+ * mutationFn: createPosts,
58
+ * }))
59
+ *
60
+ * readonly savedPosts = injectMutationState(() => ({
61
+ * // this mutation key needs to match the mutation key of the given mutation (see above)
62
+ * filters: { mutationKey, status: 'success' },
63
+ * select: (mutation) => mutation.state.data,
64
+ * }))
65
+ *
66
+ * createPost() {
67
+ * this.createPostMutation.mutate(['New Post'])
68
+ * }
69
+ * }
70
+ * ```
20
71
  */
21
72
  export declare function injectMutationState<TResult = MutationState>(injectMutationStateFn?: () => MutationStateOptions<TResult>, options?: InjectMutationStateOptions): Signal<Array<TResult>>;
22
73
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"inject-mutation-state.mjs","sources":["../src/inject-mutation-state.ts"],"sourcesContent":["import {\n DestroyRef,\n Injector,\n NgZone,\n assertInInjectionContext,\n computed,\n inject,\n signal,\n} from '@angular/core'\nimport {\n QueryClient,\n notifyManager,\n replaceEqualDeep,\n} from '@tanstack/query-core'\nimport type { Signal } from '@angular/core'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n} from '@tanstack/query-core'\n\ntype MutationStateOptions<TResult = MutationState> = {\n filters?: MutationFilters\n select?: (mutation: Mutation) => TResult\n}\n\n/**\n *\n * @param mutationCache\n * @param options\n */\nfunction getResult<TResult = MutationState>(\n mutationCache: MutationCache,\n options: MutationStateOptions<TResult>,\n): Array<TResult> {\n return mutationCache\n .findAll(options.filters)\n .map(\n (mutation): TResult =>\n (options.select ? options.select(mutation) : mutation.state) as TResult,\n )\n}\n\nexport interface InjectMutationStateOptions {\n /**\n * The `Injector` in which to create the mutation state signal.\n *\n * If this is not provided, the current injection context will be used instead (via `inject`).\n */\n injector?: Injector\n}\n\n/**\n * Injects a signal that tracks the state of all mutations.\n * @param injectMutationStateFn - A function that returns mutation state options.\n * @param options - The Angular injector to use.\n * @returns The signal that tracks the state of all mutations.\n */\nexport function injectMutationState<TResult = MutationState>(\n injectMutationStateFn: () => MutationStateOptions<TResult> = () => ({}),\n options?: InjectMutationStateOptions,\n): Signal<Array<TResult>> {\n !options?.injector && assertInInjectionContext(injectMutationState)\n const injector = options?.injector ?? inject(Injector)\n const destroyRef = injector.get(DestroyRef)\n const ngZone = injector.get(NgZone)\n const queryClient = injector.get(QueryClient)\n const mutationCache = queryClient.getMutationCache()\n\n /**\n * Computed signal that gets result from mutation cache based on passed options\n * First element is the result, second element is the time when the result was set\n */\n const resultFromOptionsSignal = computed(() => {\n return [\n getResult(mutationCache, injectMutationStateFn()),\n performance.now(),\n ] as const\n })\n\n /**\n * Signal that contains result set by subscriber\n * First element is the result, second element is the time when the result was set\n */\n const resultFromSubscriberSignal = signal<[Array<TResult>, number] | null>(\n null,\n )\n\n /**\n * Returns the last result by either subscriber or options\n */\n const effectiveResultSignal = computed(() => {\n const optionsResult = resultFromOptionsSignal()\n const subscriberResult = resultFromSubscriberSignal()\n return subscriberResult && subscriberResult[1] > optionsResult[1]\n ? subscriberResult[0]\n : optionsResult[0]\n })\n\n const unsubscribe = ngZone.runOutsideAngular(() =>\n mutationCache.subscribe(\n notifyManager.batchCalls(() => {\n const [lastResult] = effectiveResultSignal()\n const nextResult = replaceEqualDeep(\n lastResult,\n getResult(mutationCache, injectMutationStateFn()),\n )\n if (lastResult !== nextResult) {\n ngZone.run(() => {\n resultFromSubscriberSignal.set([nextResult, performance.now()])\n })\n }\n }),\n ),\n )\n\n destroyRef.onDestroy(unsubscribe)\n\n return effectiveResultSignal\n}\n"],"names":[],"mappings":";;AAgCA,SAAS,UACP,eACA,SACgB;AAChB,SAAO,cACJ,QAAQ,QAAQ,OAAO,EACvB;AAAA,IACC,CAAC,aACE,QAAQ,SAAS,QAAQ,OAAO,QAAQ,IAAI,SAAS;AAAA,EAAA;AAE9D;AAiBO,SAAS,oBACd,wBAA6D,OAAO,CAAA,IACpE,SACwB;AACxB,IAAC,mCAAS,aAAY,yBAAyB,mBAAmB;AAClE,QAAM,YAAW,mCAAS,aAAY,OAAO,QAAQ;AACrD,QAAM,aAAa,SAAS,IAAI,UAAU;AAC1C,QAAM,SAAS,SAAS,IAAI,MAAM;AAClC,QAAM,cAAc,SAAS,IAAI,WAAW;AAC5C,QAAM,gBAAgB,YAAY,iBAAA;AAMlC,QAAM,0BAA0B,SAAS,MAAM;AAC7C,WAAO;AAAA,MACL,UAAU,eAAe,uBAAuB;AAAA,MAChD,YAAY,IAAA;AAAA,IAAI;AAAA,EAEpB,CAAC;AAMD,QAAM,6BAA6B;AAAA,IACjC;AAAA,EAAA;AAMF,QAAM,wBAAwB,SAAS,MAAM;AAC3C,UAAM,gBAAgB,wBAAA;AACtB,UAAM,mBAAmB,2BAAA;AACzB,WAAO,oBAAoB,iBAAiB,CAAC,IAAI,cAAc,CAAC,IAC5D,iBAAiB,CAAC,IAClB,cAAc,CAAC;AAAA,EACrB,CAAC;AAED,QAAM,cAAc,OAAO;AAAA,IAAkB,MAC3C,cAAc;AAAA,MACZ,cAAc,WAAW,MAAM;AAC7B,cAAM,CAAC,UAAU,IAAI,sBAAA;AACrB,cAAM,aAAa;AAAA,UACjB;AAAA,UACA,UAAU,eAAe,sBAAA,CAAuB;AAAA,QAAA;AAElD,YAAI,eAAe,YAAY;AAC7B,iBAAO,IAAI,MAAM;AACf,uCAA2B,IAAI,CAAC,YAAY,YAAY,IAAA,CAAK,CAAC;AAAA,UAChE,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,IAAA;AAAA,EACH;AAGF,aAAW,UAAU,WAAW;AAEhC,SAAO;AACT;"}
1
+ {"version":3,"file":"inject-mutation-state.mjs","sources":["../src/inject-mutation-state.ts"],"sourcesContent":["import {\n DestroyRef,\n Injector,\n NgZone,\n assertInInjectionContext,\n computed,\n inject,\n signal,\n} from '@angular/core'\nimport {\n QueryClient,\n notifyManager,\n replaceEqualDeep,\n} from '@tanstack/query-core'\nimport type { Signal } from '@angular/core'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n} from '@tanstack/query-core'\n\ntype MutationStateOptions<TResult = MutationState> = {\n filters?: MutationFilters\n select?: (mutation: Mutation) => TResult\n}\n\nfunction getResult<TResult = MutationState>(\n mutationCache: MutationCache,\n options: MutationStateOptions<TResult>,\n): Array<TResult> {\n return mutationCache\n .findAll(options.filters)\n .map(\n (mutation): TResult =>\n (options.select ? options.select(mutation) : mutation.state) as TResult,\n )\n}\n\nexport interface InjectMutationStateOptions {\n /**\n * The `Injector` in which to create the mutation state signal.\n *\n * If this is not provided, the current injection context will be used instead (via `inject`).\n */\n injector?: Injector\n}\n\n/**\n * Injects a signal that gives you access to all mutations in the `MutationCache`. You can pass `filters`\n * ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation state.\n *\n * @param injectMutationStateFn - A function returning the `filters` to narrow down matched mutations, and an\n * optional `select` to transform the mutation state. Similar to `computed` from Angular, this function runs\n * in the reactive context, so signals read inside it re-narrow the matched mutations.\n * @param options - Additional configuration\n * @returns A `Signal` with an Array of whatever `select` returns for each matching mutation.\n *\n * @example\n * Get all variables of all running mutations:\n * ```angular-ts\n * @Component({\n * selector: 'pending-posts',\n * template: `{{ pendingVariables().length }} posts saving...`,\n * })\n * export class PendingPosts {\n * readonly pendingVariables = injectMutationState(() => ({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * }))\n * }\n * ```\n *\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```angular-ts\n * const mutationKey = ['posts']\n *\n * @Component({\n * selector: 'posts',\n * template: `\n * <button (click)=\"createPost()\">\n * Create post ({{ savedPosts().length }} saved so far)\n * </button>\n * `,\n * })\n * export class Posts {\n * // Some mutation that we want to get the state for\n * readonly createPostMutation = injectMutation(() => ({\n * mutationKey,\n * mutationFn: createPosts,\n * }))\n *\n * readonly savedPosts = injectMutationState(() => ({\n * // this mutation key needs to match the mutation key of the given mutation (see above)\n * filters: { mutationKey, status: 'success' },\n * select: (mutation) => mutation.state.data,\n * }))\n *\n * createPost() {\n * this.createPostMutation.mutate(['New Post'])\n * }\n * }\n * ```\n */\nexport function injectMutationState<TResult = MutationState>(\n injectMutationStateFn: () => MutationStateOptions<TResult> = () => ({}),\n options?: InjectMutationStateOptions,\n): Signal<Array<TResult>> {\n !options?.injector && assertInInjectionContext(injectMutationState)\n const injector = options?.injector ?? inject(Injector)\n const destroyRef = injector.get(DestroyRef)\n const ngZone = injector.get(NgZone)\n const queryClient = injector.get(QueryClient)\n const mutationCache = queryClient.getMutationCache()\n\n /**\n * Computed signal that gets result from mutation cache based on passed options\n * First element is the result, second element is the time when the result was set\n */\n const resultFromOptionsSignal = computed(() => {\n return [\n getResult(mutationCache, injectMutationStateFn()),\n performance.now(),\n ] as const\n })\n\n /**\n * Signal that contains result set by subscriber\n * First element is the result, second element is the time when the result was set\n */\n const resultFromSubscriberSignal = signal<[Array<TResult>, number] | null>(\n null,\n )\n\n /**\n * Returns the last result by either subscriber or options\n */\n const effectiveResultSignal = computed(() => {\n const optionsResult = resultFromOptionsSignal()\n const subscriberResult = resultFromSubscriberSignal()\n return subscriberResult && subscriberResult[1] > optionsResult[1]\n ? subscriberResult[0]\n : optionsResult[0]\n })\n\n const unsubscribe = ngZone.runOutsideAngular(() =>\n mutationCache.subscribe(\n notifyManager.batchCalls(() => {\n const [lastResult] = effectiveResultSignal()\n const nextResult = replaceEqualDeep(\n lastResult,\n getResult(mutationCache, injectMutationStateFn()),\n )\n if (lastResult !== nextResult) {\n ngZone.run(() => {\n resultFromSubscriberSignal.set([nextResult, performance.now()])\n })\n }\n }),\n ),\n )\n\n destroyRef.onDestroy(unsubscribe)\n\n return effectiveResultSignal\n}\n"],"names":[],"mappings":";;AA2BA,SAAS,UACP,eACA,SACgB;AAChB,SAAO,cACJ,QAAQ,QAAQ,OAAO,EACvB;AAAA,IACC,CAAC,aACE,QAAQ,SAAS,QAAQ,OAAO,QAAQ,IAAI,SAAS;AAAA,EAAA;AAE9D;AAoEO,SAAS,oBACd,wBAA6D,OAAO,CAAA,IACpE,SACwB;AACxB,IAAC,mCAAS,aAAY,yBAAyB,mBAAmB;AAClE,QAAM,YAAW,mCAAS,aAAY,OAAO,QAAQ;AACrD,QAAM,aAAa,SAAS,IAAI,UAAU;AAC1C,QAAM,SAAS,SAAS,IAAI,MAAM;AAClC,QAAM,cAAc,SAAS,IAAI,WAAW;AAC5C,QAAM,gBAAgB,YAAY,iBAAA;AAMlC,QAAM,0BAA0B,SAAS,MAAM;AAC7C,WAAO;AAAA,MACL,UAAU,eAAe,uBAAuB;AAAA,MAChD,YAAY,IAAA;AAAA,IAAI;AAAA,EAEpB,CAAC;AAMD,QAAM,6BAA6B;AAAA,IACjC;AAAA,EAAA;AAMF,QAAM,wBAAwB,SAAS,MAAM;AAC3C,UAAM,gBAAgB,wBAAA;AACtB,UAAM,mBAAmB,2BAAA;AACzB,WAAO,oBAAoB,iBAAiB,CAAC,IAAI,cAAc,CAAC,IAC5D,iBAAiB,CAAC,IAClB,cAAc,CAAC;AAAA,EACrB,CAAC;AAED,QAAM,cAAc,OAAO;AAAA,IAAkB,MAC3C,cAAc;AAAA,MACZ,cAAc,WAAW,MAAM;AAC7B,cAAM,CAAC,UAAU,IAAI,sBAAA;AACrB,cAAM,aAAa;AAAA,UACjB;AAAA,UACA,UAAU,eAAe,sBAAA,CAAuB;AAAA,QAAA;AAElD,YAAI,eAAe,YAAY;AAC7B,iBAAO,IAAI,MAAM;AACf,uCAA2B,IAAI,CAAC,YAAY,YAAY,IAAA,CAAK,CAAC;AAAA,UAChE,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,IAAA;AAAA,EACH;AAGF,aAAW,UAAU,WAAW;AAEhC,SAAO;AACT;"}
@@ -10,11 +10,140 @@ export interface InjectMutationOptions {
10
10
  injector?: Injector;
11
11
  }
12
12
  /**
13
- * Injects a mutation: an imperative function that can be invoked which typically performs server side effects.
13
+ * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
14
+ * `injectMutation` is the function for that. Unlike queries, mutations are not run automatically.
14
15
  *
15
- * Unlike queries, mutations are not run automatically.
16
- * @param injectMutationFn - A function that returns mutation options.
16
+ * @remarks `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a
17
+ * second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to
18
+ * the shared mutation definition. Callbacks defined in `injectMutationFn` fire for every mutation; per-call
19
+ * callbacks fire only for the latest call you've made — `mutateAsync` gives you a promise per call instead,
20
+ * so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.
21
+ * @see {@link mutationOptions} to share these options across multiple `injectMutation` call sites, or to look
22
+ * the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).
23
+ * @param injectMutationFn - A function that returns mutation options. Similar to `computed` from Angular,
24
+ * this function runs in the reactive context, so signals read inside it drive the mutation's options.
17
25
  * @param options - Additional configuration
18
- * @returns The mutation.
26
+ * @returns The mutation result. Value fields are exposed as a `Signal` — read `data`/`error` by calling them
27
+ * (e.g. `mutation.data()`) — while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,
28
+ * unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether
29
+ * `data` is defined.
30
+ *
31
+ * @example
32
+ * ```angular-ts
33
+ * @Component({
34
+ * selector: 'todos',
35
+ * template: `
36
+ * @if (addMutation.isPending()) {
37
+ * <span>Adding todo...</span>
38
+ * } @else if (addMutation.isError()) {
39
+ * <div>An error occurred: {{ addMutation.error()?.message }}</div>
40
+ * }
41
+ * <button (click)="addMutation.mutate('Item')">Add</button>
42
+ * `,
43
+ * })
44
+ * export class Todos {
45
+ * readonly #queryClient = inject(QueryClient)
46
+ *
47
+ * readonly addMutation = injectMutation(() => ({
48
+ * mutationFn: addTodo,
49
+ * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
50
+ * }))
51
+ * }
52
+ * ```
53
+ *
54
+ * @example
55
+ * Optimistic update via `onMutate`, rolling back on `onError`:
56
+ * ```angular-ts
57
+ * @Component({
58
+ * selector: 'todos',
59
+ * template: `<button (click)="addMutation.mutate('Item')">Add</button>`,
60
+ * })
61
+ * export class Todos {
62
+ * readonly #queryClient = inject(QueryClient)
63
+ *
64
+ * readonly addMutation = injectMutation(() => ({
65
+ * mutationFn: addTodo,
66
+ * onMutate: async (newTodo) => {
67
+ * await this.#queryClient.cancelQueries({ queryKey: ['todos'] })
68
+ * const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])
69
+ *
70
+ * this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [
71
+ * ...(old ?? []),
72
+ * newTodo,
73
+ * ])
74
+ *
75
+ * // Passed to `onError` as `onMutateResult` if the mutation fails.
76
+ * return { previousTodos }
77
+ * },
78
+ * onError: (_err, _newTodo, onMutateResult) => {
79
+ * this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
80
+ * },
81
+ * onSettled: () => {
82
+ * this.#queryClient.invalidateQueries({ queryKey: ['todos'] })
83
+ * },
84
+ * }))
85
+ * }
86
+ * ```
87
+ *
88
+ * @example
89
+ * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a promise per
90
+ * call instead, so you can wait for all of them when they succeed:
91
+ * ```angular-ts
92
+ * @Component({
93
+ * selector: 'todos',
94
+ * template: `
95
+ * <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
96
+ * `,
97
+ * })
98
+ * export class Todos {
99
+ * readonly #queryClient = inject(QueryClient)
100
+ *
101
+ * readonly addMutation = injectMutation(() => ({
102
+ * mutationFn: addTodo,
103
+ * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
104
+ * }))
105
+ *
106
+ * async handleAddAll(todos: Array<string>) {
107
+ * try {
108
+ * await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))
109
+ * } catch (error) {
110
+ * console.error('Failed to add todos:', error)
111
+ * }
112
+ * }
113
+ * }
114
+ * ```
115
+ *
116
+ * @example
117
+ * If some of the mutations above can fail independently of the others, and you want to know which ones did —
118
+ * rather than losing that information the moment the first one rejects — swap `Promise.all` for
119
+ * `Promise.allSettled`:
120
+ * ```angular-ts
121
+ * @Component({
122
+ * selector: 'todos',
123
+ * template: `
124
+ * <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
125
+ * `,
126
+ * })
127
+ * export class Todos {
128
+ * readonly #queryClient = inject(QueryClient)
129
+ *
130
+ * readonly addMutation = injectMutation(() => ({
131
+ * mutationFn: addTodo,
132
+ * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
133
+ * }))
134
+ *
135
+ * async handleAddAll(todos: Array<string>) {
136
+ * const addResults = await Promise.allSettled(
137
+ * todos.map((todo) => this.addMutation.mutateAsync(todo)),
138
+ * )
139
+ *
140
+ * addResults.forEach((addResult, index) => {
141
+ * if (addResult.status === 'rejected') {
142
+ * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
143
+ * }
144
+ * })
145
+ * }
146
+ * }
147
+ * ```
19
148
  */
20
149
  export declare function injectMutation<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown>(injectMutationFn: () => CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, options?: InjectMutationOptions): CreateMutationResult<TData, TError, TVariables, TOnMutateResult>;
@@ -1 +1 @@
1
- {"version":3,"file":"inject-mutation.mjs","sources":["../src/inject-mutation.ts"],"sourcesContent":["import {\n Injector,\n NgZone,\n assertInInjectionContext,\n computed,\n effect,\n inject,\n signal,\n untracked,\n} from '@angular/core'\nimport {\n MutationObserver,\n QueryClient,\n noop,\n notifyManager,\n shouldThrowError,\n} from '@tanstack/query-core'\nimport { signalProxy } from './signal-proxy'\nimport { PENDING_TASKS } from './pending-tasks-compat'\nimport type { PendingTaskRef } from './pending-tasks-compat'\nimport type { DefaultError, MutationObserverResult } from '@tanstack/query-core'\nimport type {\n CreateMutateFunction,\n CreateMutationOptions,\n CreateMutationResult,\n} from './types'\n\nexport interface InjectMutationOptions {\n /**\n * The `Injector` in which to create the mutation.\n *\n * If this is not provided, the current injection context will be used instead (via `inject`).\n */\n injector?: Injector\n}\n\n/**\n * Injects a mutation: an imperative function that can be invoked which typically performs server side effects.\n *\n * Unlike queries, mutations are not run automatically.\n * @param injectMutationFn - A function that returns mutation options.\n * @param options - Additional configuration\n * @returns The mutation.\n */\nexport function injectMutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n injectMutationFn: () => CreateMutationOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n options?: InjectMutationOptions,\n): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {\n !options?.injector && assertInInjectionContext(injectMutation)\n const injector = options?.injector ?? inject(Injector)\n const ngZone = injector.get(NgZone)\n const pendingTasks = injector.get(PENDING_TASKS)\n const queryClient = injector.get(QueryClient)\n\n /**\n * computed() is used so signals can be inserted into the options\n * making it reactive. Wrapping options in a function ensures embedded expressions\n * are preserved and can keep being applied after signal changes\n */\n const optionsSignal = computed(injectMutationFn)\n\n const observerSignal = (() => {\n let instance: MutationObserver<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > | null = null\n\n return computed(() => {\n return (instance ||= new MutationObserver(queryClient, optionsSignal()))\n })\n })()\n\n const mutateFnSignal = computed<\n CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>\n >(() => {\n const observer = observerSignal()\n return (\n ...args: Parameters<\n CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>\n >\n ) => {\n observer.mutate(args[0] as TVariables, args[1]).catch(noop)\n }\n })\n\n /**\n * Computed signal that gets result from mutation cache based on passed options\n */\n const resultFromInitialOptionsSignal = computed(() => {\n const observer = observerSignal()\n return observer.getCurrentResult()\n })\n\n /**\n * Signal that contains result set by subscriber\n */\n const resultFromSubscriberSignal = signal<MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > | null>(null)\n\n effect(\n () => {\n const observer = observerSignal()\n const observerOptions = optionsSignal()\n\n untracked(() => {\n observer.setOptions(observerOptions)\n })\n },\n {\n injector,\n },\n )\n\n effect(\n (onCleanup) => {\n // observer.trackResult is not used as this optimization is not needed for Angular\n const observer = observerSignal()\n let pendingTaskRef: PendingTaskRef | null = null\n\n untracked(() => {\n const unsubscribe = ngZone.runOutsideAngular(() =>\n observer.subscribe(\n notifyManager.batchCalls((state) => {\n ngZone.run(() => {\n // Track pending task when mutation is pending\n if (state.isPending && !pendingTaskRef) {\n pendingTaskRef = pendingTasks.add()\n }\n\n // Clear pending task when mutation is no longer pending\n if (!state.isPending && pendingTaskRef) {\n pendingTaskRef()\n pendingTaskRef = null\n }\n\n if (\n state.isError &&\n shouldThrowError(observer.options.throwOnError, [state.error])\n ) {\n ngZone.onError.emit(state.error)\n throw state.error\n }\n\n resultFromSubscriberSignal.set(state)\n })\n }),\n ),\n )\n onCleanup(() => {\n // Clean up any pending task on destroy\n if (pendingTaskRef) {\n pendingTaskRef()\n pendingTaskRef = null\n }\n unsubscribe()\n })\n })\n },\n {\n injector,\n },\n )\n\n const resultSignal = computed(() => {\n const resultFromSubscriber = resultFromSubscriberSignal()\n const resultFromInitialOptions = resultFromInitialOptionsSignal()\n\n const result = resultFromSubscriber ?? resultFromInitialOptions\n\n return {\n ...result,\n mutate: mutateFnSignal(),\n mutateAsync: result.mutate,\n }\n })\n\n return signalProxy(resultSignal) as CreateMutationResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >\n}\n"],"names":[],"mappings":";;;;AA4CO,SAAS,eAMd,kBAMA,SACkE;AAClE,IAAC,mCAAS,aAAY,yBAAyB,cAAc;AAC7D,QAAM,YAAW,mCAAS,aAAY,OAAO,QAAQ;AACrD,QAAM,SAAS,SAAS,IAAI,MAAM;AAClC,QAAM,eAAe,SAAS,IAAI,aAAa;AAC/C,QAAM,cAAc,SAAS,IAAI,WAAW;AAO5C,QAAM,gBAAgB,SAAS,gBAAgB;AAE/C,QAAM,kBAAkB,MAAM;AAC5B,QAAI,WAKO;AAEX,WAAO,SAAS,MAAM;AACpB,aAAQ,wBAAa,IAAI,iBAAiB,aAAa,eAAe;AAAA,IACxE,CAAC;AAAA,EACH,GAAA;AAEA,QAAM,iBAAiB,SAErB,MAAM;AACN,UAAM,WAAW,eAAA;AACjB,WAAO,IACF,SAGA;AACH,eAAS,OAAO,KAAK,CAAC,GAAiB,KAAK,CAAC,CAAC,EAAE,MAAM,IAAI;AAAA,IAC5D;AAAA,EACF,CAAC;AAKD,QAAM,iCAAiC,SAAS,MAAM;AACpD,UAAM,WAAW,eAAA;AACjB,WAAO,SAAS,iBAAA;AAAA,EAClB,CAAC;AAKD,QAAM,6BAA6B,OAKzB,IAAI;AAEd;AAAA,IACE,MAAM;AACJ,YAAM,WAAW,eAAA;AACjB,YAAM,kBAAkB,cAAA;AAExB,gBAAU,MAAM;AACd,iBAAS,WAAW,eAAe;AAAA,MACrC,CAAC;AAAA,IACH;AAAA,IACA;AAAA,MACE;AAAA,IAAA;AAAA,EACF;AAGF;AAAA,IACE,CAAC,cAAc;AAEb,YAAM,WAAW,eAAA;AACjB,UAAI,iBAAwC;AAE5C,gBAAU,MAAM;AACd,cAAM,cAAc,OAAO;AAAA,UAAkB,MAC3C,SAAS;AAAA,YACP,cAAc,WAAW,CAAC,UAAU;AAClC,qBAAO,IAAI,MAAM;AAEf,oBAAI,MAAM,aAAa,CAAC,gBAAgB;AACtC,mCAAiB,aAAa,IAAA;AAAA,gBAChC;AAGA,oBAAI,CAAC,MAAM,aAAa,gBAAgB;AACtC,iCAAA;AACA,mCAAiB;AAAA,gBACnB;AAEA,oBACE,MAAM,WACN,iBAAiB,SAAS,QAAQ,cAAc,CAAC,MAAM,KAAK,CAAC,GAC7D;AACA,yBAAO,QAAQ,KAAK,MAAM,KAAK;AAC/B,wBAAM,MAAM;AAAA,gBACd;AAEA,2CAA2B,IAAI,KAAK;AAAA,cACtC,CAAC;AAAA,YACH,CAAC;AAAA,UAAA;AAAA,QACH;AAEF,kBAAU,MAAM;AAEd,cAAI,gBAAgB;AAClB,2BAAA;AACA,6BAAiB;AAAA,UACnB;AACA,sBAAA;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,IACA;AAAA,MACE;AAAA,IAAA;AAAA,EACF;AAGF,QAAM,eAAe,SAAS,MAAM;AAClC,UAAM,uBAAuB,2BAAA;AAC7B,UAAM,2BAA2B,+BAAA;AAEjC,UAAM,SAAS,wBAAwB;AAEvC,WAAO;AAAA,MACL,GAAG;AAAA,MACH,QAAQ,eAAA;AAAA,MACR,aAAa,OAAO;AAAA,IAAA;AAAA,EAExB,CAAC;AAED,SAAO,YAAY,YAAY;AAMjC;"}
1
+ {"version":3,"file":"inject-mutation.mjs","sources":["../src/inject-mutation.ts"],"sourcesContent":["import {\n Injector,\n NgZone,\n assertInInjectionContext,\n computed,\n effect,\n inject,\n signal,\n untracked,\n} from '@angular/core'\nimport {\n MutationObserver,\n QueryClient,\n noop,\n notifyManager,\n shouldThrowError,\n} from '@tanstack/query-core'\nimport { signalProxy } from './signal-proxy'\nimport { PENDING_TASKS } from './pending-tasks-compat'\nimport type { PendingTaskRef } from './pending-tasks-compat'\nimport type { DefaultError, MutationObserverResult } from '@tanstack/query-core'\nimport type {\n CreateMutateFunction,\n CreateMutationOptions,\n CreateMutationResult,\n} from './types'\n\nexport interface InjectMutationOptions {\n /**\n * The `Injector` in which to create the mutation.\n *\n * If this is not provided, the current injection context will be used instead (via `inject`).\n */\n injector?: Injector\n}\n\n/**\n * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.\n * `injectMutation` is the function for that. Unlike queries, mutations are not run automatically.\n *\n * @remarks `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a\n * second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to\n * the shared mutation definition. Callbacks defined in `injectMutationFn` fire for every mutation; per-call\n * callbacks fire only for the latest call you've made — `mutateAsync` gives you a promise per call instead,\n * so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.\n * @see {@link mutationOptions} to share these options across multiple `injectMutation` call sites, or to look\n * the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).\n * @param injectMutationFn - A function that returns mutation options. Similar to `computed` from Angular,\n * this function runs in the reactive context, so signals read inside it drive the mutation's options.\n * @param options - Additional configuration\n * @returns The mutation result. Value fields are exposed as a `Signal` — read `data`/`error` by calling them\n * (e.g. `mutation.data()`) — while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,\n * unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether\n * `data` is defined.\n *\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'todos',\n * template: `\n * @if (addMutation.isPending()) {\n * <span>Adding todo...</span>\n * } @else if (addMutation.isError()) {\n * <div>An error occurred: {{ addMutation.error()?.message }}</div>\n * }\n * <button (click)=\"addMutation.mutate('Item')\">Add</button>\n * `,\n * })\n * export class Todos {\n * readonly #queryClient = inject(QueryClient)\n *\n * readonly addMutation = injectMutation(() => ({\n * mutationFn: addTodo,\n * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * }))\n * }\n * ```\n *\n * @example\n * Optimistic update via `onMutate`, rolling back on `onError`:\n * ```angular-ts\n * @Component({\n * selector: 'todos',\n * template: `<button (click)=\"addMutation.mutate('Item')\">Add</button>`,\n * })\n * export class Todos {\n * readonly #queryClient = inject(QueryClient)\n *\n * readonly addMutation = injectMutation(() => ({\n * mutationFn: addTodo,\n * onMutate: async (newTodo) => {\n * await this.#queryClient.cancelQueries({ queryKey: ['todos'] })\n * const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])\n *\n * this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [\n * ...(old ?? []),\n * newTodo,\n * ])\n *\n * // Passed to `onError` as `onMutateResult` if the mutation fails.\n * return { previousTodos }\n * },\n * onError: (_err, _newTodo, onMutateResult) => {\n * this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)\n * },\n * onSettled: () => {\n * this.#queryClient.invalidateQueries({ queryKey: ['todos'] })\n * },\n * }))\n * }\n * ```\n *\n * @example\n * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a promise per\n * call instead, so you can wait for all of them when they succeed:\n * ```angular-ts\n * @Component({\n * selector: 'todos',\n * template: `\n * <button (click)=\"handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])\">Add all</button>\n * `,\n * })\n * export class Todos {\n * readonly #queryClient = inject(QueryClient)\n *\n * readonly addMutation = injectMutation(() => ({\n * mutationFn: addTodo,\n * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * }))\n *\n * async handleAddAll(todos: Array<string>) {\n * try {\n * await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))\n * } catch (error) {\n * console.error('Failed to add todos:', error)\n * }\n * }\n * }\n * ```\n *\n * @example\n * If some of the mutations above can fail independently of the others, and you want to know which ones did —\n * rather than losing that information the moment the first one rejects — swap `Promise.all` for\n * `Promise.allSettled`:\n * ```angular-ts\n * @Component({\n * selector: 'todos',\n * template: `\n * <button (click)=\"handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])\">Add all</button>\n * `,\n * })\n * export class Todos {\n * readonly #queryClient = inject(QueryClient)\n *\n * readonly addMutation = injectMutation(() => ({\n * mutationFn: addTodo,\n * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * }))\n *\n * async handleAddAll(todos: Array<string>) {\n * const addResults = await Promise.allSettled(\n * todos.map((todo) => this.addMutation.mutateAsync(todo)),\n * )\n *\n * addResults.forEach((addResult, index) => {\n * if (addResult.status === 'rejected') {\n * console.error(`Failed to add \"${todos[index]}\":`, addResult.reason)\n * }\n * })\n * }\n * }\n * ```\n */\nexport function injectMutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n injectMutationFn: () => CreateMutationOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n options?: InjectMutationOptions,\n): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {\n !options?.injector && assertInInjectionContext(injectMutation)\n const injector = options?.injector ?? inject(Injector)\n const ngZone = injector.get(NgZone)\n const pendingTasks = injector.get(PENDING_TASKS)\n const queryClient = injector.get(QueryClient)\n\n /**\n * computed() is used so signals can be inserted into the options\n * making it reactive. Wrapping options in a function ensures embedded expressions\n * are preserved and can keep being applied after signal changes\n */\n const optionsSignal = computed(injectMutationFn)\n\n const observerSignal = (() => {\n let instance: MutationObserver<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > | null = null\n\n return computed(() => {\n return (instance ||= new MutationObserver(queryClient, optionsSignal()))\n })\n })()\n\n const mutateFnSignal = computed<\n CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>\n >(() => {\n const observer = observerSignal()\n return (\n ...args: Parameters<\n CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>\n >\n ) => {\n observer.mutate(args[0] as TVariables, args[1]).catch(noop)\n }\n })\n\n /**\n * Computed signal that gets result from mutation cache based on passed options\n */\n const resultFromInitialOptionsSignal = computed(() => {\n const observer = observerSignal()\n return observer.getCurrentResult()\n })\n\n /**\n * Signal that contains result set by subscriber\n */\n const resultFromSubscriberSignal = signal<MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > | null>(null)\n\n effect(\n () => {\n const observer = observerSignal()\n const observerOptions = optionsSignal()\n\n untracked(() => {\n observer.setOptions(observerOptions)\n })\n },\n {\n injector,\n },\n )\n\n effect(\n (onCleanup) => {\n // observer.trackResult is not used as this optimization is not needed for Angular\n const observer = observerSignal()\n let pendingTaskRef: PendingTaskRef | null = null\n\n untracked(() => {\n const unsubscribe = ngZone.runOutsideAngular(() =>\n observer.subscribe(\n notifyManager.batchCalls((state) => {\n ngZone.run(() => {\n // Track pending task when mutation is pending\n if (state.isPending && !pendingTaskRef) {\n pendingTaskRef = pendingTasks.add()\n }\n\n // Clear pending task when mutation is no longer pending\n if (!state.isPending && pendingTaskRef) {\n pendingTaskRef()\n pendingTaskRef = null\n }\n\n if (\n state.isError &&\n shouldThrowError(observer.options.throwOnError, [state.error])\n ) {\n ngZone.onError.emit(state.error)\n throw state.error\n }\n\n resultFromSubscriberSignal.set(state)\n })\n }),\n ),\n )\n onCleanup(() => {\n // Clean up any pending task on destroy\n if (pendingTaskRef) {\n pendingTaskRef()\n pendingTaskRef = null\n }\n unsubscribe()\n })\n })\n },\n {\n injector,\n },\n )\n\n const resultSignal = computed(() => {\n const resultFromSubscriber = resultFromSubscriberSignal()\n const resultFromInitialOptions = resultFromInitialOptionsSignal()\n\n const result = resultFromSubscriber ?? resultFromInitialOptions\n\n return {\n ...result,\n mutate: mutateFnSignal(),\n mutateAsync: result.mutate,\n }\n })\n\n return signalProxy(resultSignal) as CreateMutationResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >\n}\n"],"names":[],"mappings":";;;;AA6KO,SAAS,eAMd,kBAMA,SACkE;AAClE,IAAC,mCAAS,aAAY,yBAAyB,cAAc;AAC7D,QAAM,YAAW,mCAAS,aAAY,OAAO,QAAQ;AACrD,QAAM,SAAS,SAAS,IAAI,MAAM;AAClC,QAAM,eAAe,SAAS,IAAI,aAAa;AAC/C,QAAM,cAAc,SAAS,IAAI,WAAW;AAO5C,QAAM,gBAAgB,SAAS,gBAAgB;AAE/C,QAAM,kBAAkB,MAAM;AAC5B,QAAI,WAKO;AAEX,WAAO,SAAS,MAAM;AACpB,aAAQ,wBAAa,IAAI,iBAAiB,aAAa,eAAe;AAAA,IACxE,CAAC;AAAA,EACH,GAAA;AAEA,QAAM,iBAAiB,SAErB,MAAM;AACN,UAAM,WAAW,eAAA;AACjB,WAAO,IACF,SAGA;AACH,eAAS,OAAO,KAAK,CAAC,GAAiB,KAAK,CAAC,CAAC,EAAE,MAAM,IAAI;AAAA,IAC5D;AAAA,EACF,CAAC;AAKD,QAAM,iCAAiC,SAAS,MAAM;AACpD,UAAM,WAAW,eAAA;AACjB,WAAO,SAAS,iBAAA;AAAA,EAClB,CAAC;AAKD,QAAM,6BAA6B,OAKzB,IAAI;AAEd;AAAA,IACE,MAAM;AACJ,YAAM,WAAW,eAAA;AACjB,YAAM,kBAAkB,cAAA;AAExB,gBAAU,MAAM;AACd,iBAAS,WAAW,eAAe;AAAA,MACrC,CAAC;AAAA,IACH;AAAA,IACA;AAAA,MACE;AAAA,IAAA;AAAA,EACF;AAGF;AAAA,IACE,CAAC,cAAc;AAEb,YAAM,WAAW,eAAA;AACjB,UAAI,iBAAwC;AAE5C,gBAAU,MAAM;AACd,cAAM,cAAc,OAAO;AAAA,UAAkB,MAC3C,SAAS;AAAA,YACP,cAAc,WAAW,CAAC,UAAU;AAClC,qBAAO,IAAI,MAAM;AAEf,oBAAI,MAAM,aAAa,CAAC,gBAAgB;AACtC,mCAAiB,aAAa,IAAA;AAAA,gBAChC;AAGA,oBAAI,CAAC,MAAM,aAAa,gBAAgB;AACtC,iCAAA;AACA,mCAAiB;AAAA,gBACnB;AAEA,oBACE,MAAM,WACN,iBAAiB,SAAS,QAAQ,cAAc,CAAC,MAAM,KAAK,CAAC,GAC7D;AACA,yBAAO,QAAQ,KAAK,MAAM,KAAK;AAC/B,wBAAM,MAAM;AAAA,gBACd;AAEA,2CAA2B,IAAI,KAAK;AAAA,cACtC,CAAC;AAAA,YACH,CAAC;AAAA,UAAA;AAAA,QACH;AAEF,kBAAU,MAAM;AAEd,cAAI,gBAAgB;AAClB,2BAAA;AACA,6BAAiB;AAAA,UACnB;AACA,sBAAA;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,IACA;AAAA,MACE;AAAA,IAAA;AAAA,EACF;AAGF,QAAM,eAAe,SAAS,MAAM;AAClC,UAAM,uBAAuB,2BAAA;AAC7B,UAAM,2BAA2B,+BAAA;AAEjC,UAAM,SAAS,wBAAwB;AAEvC,WAAO;AAAA,MACL,GAAG;AAAA,MACH,QAAQ,eAAA;AAAA,MACR,aAAa,OAAO;AAAA,IAAA;AAAA,EAExB,CAAC;AAED,SAAO,YAAY,YAAY;AAMjC;"}
@@ -40,7 +40,17 @@ type GetCreateQueryResult<T> = T extends {
40
40
  throwOnError?: ThrowOnError<any, infer TError, any, any>;
41
41
  } ? GetDefinedOrUndefinedQueryResult<T, unknown extends TData ? TQueryFnData : TData, unknown extends TError ? DefaultError : TError> : CreateQueryResult;
42
42
  /**
43
- * QueriesOptions reducer recursively unwraps function arguments to infer/enforce type param
43
+ * The `queries` array accepted by `injectQueries`. Recursively unwraps each tuple element so every entry's
44
+ * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements — past that, tuple
45
+ * recursion falls back to a single homogeneous options type. An opaque array (e.g. `unknown[]`) is returned
46
+ * as-is; a non-tuple array of a known element type is mapped to that element type instead, with no such
47
+ * limit.
48
+ *
49
+ * @template T - The type of the `queries` array as written at the call site.
50
+ * @template TResults - The internal accumulator that this type builds during recursion. It is not meant to
51
+ * be set explicitly.
52
+ * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
53
+ * meant to be set explicitly.
44
54
  */
45
55
  export type QueriesOptions<T extends Array<any>, TResults extends Array<any> = [], TDepth extends ReadonlyArray<number> = []> = TDepth['length'] extends MAXIMUM_DEPTH ? Array<QueryObserverOptionsForCreateQueries> : T extends [] ? [] : T extends [infer Head] ? [...TResults, GetCreateQueryOptionsForCreateQueries<Head>] : T extends [infer Head, ...infer Tails] ? QueriesOptions<[
46
56
  ...Tails
@@ -52,7 +62,16 @@ export type QueriesOptions<T extends Array<any>, TResults extends Array<any> = [
52
62
  1
53
63
  ]> : ReadonlyArray<unknown> extends T ? T : T extends Array<QueryObserverOptionsForCreateQueries<infer TQueryFnData, infer TError, infer TData, infer TQueryKey>> ? Array<QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData, TQueryKey>> : Array<QueryObserverOptionsForCreateQueries>;
54
64
  /**
55
- * QueriesResults reducer recursively maps type param to results
65
+ * The result type returned by `injectQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}:
66
+ * each tuple element's result type is inferred individually, up to 20 elements — past that, tuple recursion
67
+ * falls back to a single homogeneous {@link CreateQueryResult} type. A non-tuple array is mapped per-element
68
+ * instead, with no such limit — every entry keeps its individually inferred type regardless of array length.
69
+ *
70
+ * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.
71
+ * @template TResults - The internal accumulator that this type builds during recursion. It is not meant to
72
+ * be set explicitly.
73
+ * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
74
+ * meant to be set explicitly.
56
75
  */
57
76
  export type QueriesResults<T extends Array<any>, TResults extends Array<any> = [], TDepth extends ReadonlyArray<number> = []> = TDepth['length'] extends MAXIMUM_DEPTH ? Array<CreateQueryResult> : T extends [] ? [] : T extends [infer Head] ? [...TResults, GetCreateQueryResult<Head>] : T extends [infer Head, ...infer Tails] ? QueriesResults<[
58
77
  ...Tails
@@ -74,8 +93,138 @@ export interface InjectQueriesOptions<T extends Array<any>, TCombinedResult = Qu
74
93
  combine?: (result: QueriesResults<T>) => TCombinedResult;
75
94
  }
76
95
  /**
77
- * @param optionsFn - A function that returns queries' options.
78
- * @param injector - The Angular injector to use.
96
+ * Injects a signal to fetch a variable number of queries.
97
+ *
98
+ * The `queries` key accepts an array with query option objects mostly identical to `injectQuery`'s. Having
99
+ * the same query key more than once in the array of query objects may cause some data to be shared between
100
+ * queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
101
+ * structure.
102
+ *
103
+ * The `combine` option can be used to combine the results of the queries into a single value. The result
104
+ * will be structurally shared to be as referentially stable as possible.
105
+ *
106
+ * @remarks Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of an _inline_ `select`
107
+ * from its sibling `queryFn`. Because `injectQueries` infers the type of the whole `queries` array at once,
108
+ * the `select` parameter of a query object written inline cannot be contextually typed from that same
109
+ * object's `queryFn`, so it falls back to `unknown` — a
110
+ * [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate the `select`
111
+ * parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in a single
112
+ * object _before_ it reaches `injectQueries`, to work around this — see the example below.
113
+ * @param optionsFn - A function returning the queries' options — an array of query option objects under
114
+ * `queries`, and an optional `combine`. Similar to `computed` from Angular, this function runs in the
115
+ * reactive context, so signals read inside it (e.g. to build the `queries` array) drive the queries.
116
+ * @param injector - The `Injector` in which to create the queries. If this is not provided, the current
117
+ * injection context will be used instead (via `inject`).
118
+ * @returns A `Signal` with the combined result. Without `combine`, this is an array with all the query
119
+ * results, in the same order as the input. When `combine` is provided, this is the value returned by
120
+ * `combine` instead.
121
+ *
122
+ * @example
123
+ * ```angular-ts
124
+ * @Component({
125
+ * selector: 'posts',
126
+ * template: `
127
+ * <ul>
128
+ * @for (query of postQueries(); track $index) {
129
+ * @if (query.isPending()) {
130
+ * <li>Loading...</li>
131
+ * } @else if (query.isError()) {
132
+ * <li>Error: {{ query.error()?.message }}</li>
133
+ * } @else {
134
+ * <li>{{ query.data().title }}</li>
135
+ * }
136
+ * }
137
+ * </ul>
138
+ * `,
139
+ * })
140
+ * export class Posts {
141
+ * readonly ids = signal([1, 2, 3])
142
+ *
143
+ * readonly postQueries = injectQueries(() => ({
144
+ * queries: this.ids().map((id) => ({
145
+ * queryKey: ['post', id],
146
+ * queryFn: () => fetchPost(id),
147
+ * staleTime: Infinity,
148
+ * })),
149
+ * }))
150
+ * }
151
+ * ```
152
+ *
153
+ * @example
154
+ * Combining results into a single value:
155
+ * ```angular-ts
156
+ * @Component({
157
+ * selector: 'posts',
158
+ * template: `
159
+ * @if (combined().isPending) {
160
+ * Loading...
161
+ * } @else if (combined().isError) {
162
+ * Error loading posts
163
+ * } @else {
164
+ * <ul>
165
+ * @for (post of combined().data; track post?.id) {
166
+ * <li>{{ post?.title }}</li>
167
+ * }
168
+ * </ul>
169
+ * }
170
+ * `,
171
+ * })
172
+ * export class Posts {
173
+ * readonly ids = signal([1, 2, 3])
174
+ *
175
+ * readonly combined = injectQueries(() => ({
176
+ * queries: this.ids().map((id) => ({
177
+ * queryKey: ['post', id],
178
+ * queryFn: () => fetchPost(id),
179
+ * })),
180
+ * combine: (postQueries) => ({
181
+ * data: postQueries.map((query) => query.data),
182
+ * isPending: postQueries.some((query) => query.isPending),
183
+ * isError: postQueries.some((query) => query.isError),
184
+ * }),
185
+ * }))
186
+ * }
187
+ * ```
188
+ *
189
+ * @example
190
+ * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
191
+ * `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is
192
+ * resolved before it reaches `injectQueries`:
193
+ * ```angular-ts
194
+ * const postOptions = (id: number) =>
195
+ * queryOptions({
196
+ * queryKey: ['post', id],
197
+ * queryFn: () => fetchPost(id),
198
+ * })
199
+ *
200
+ * @Component({
201
+ * selector: 'post-title',
202
+ * template: `<h1>{{ fixed()[0].data() }}</h1>`,
203
+ * })
204
+ * export class PostTitle {
205
+ * readonly id = signal(1)
206
+ *
207
+ * readonly broken = injectQueries(() => ({
208
+ * queries: [
209
+ * {
210
+ * ...postOptions(this.id()),
211
+ * // ❌ `data` is `unknown` here
212
+ * select: (data) => data.title,
213
+ * },
214
+ * ],
215
+ * }))
216
+ *
217
+ * readonly fixed = injectQueries(() => ({
218
+ * queries: [
219
+ * queryOptions({
220
+ * ...postOptions(this.id()),
221
+ * // ✅ `data` is `Post`
222
+ * select: (data) => data.title,
223
+ * }),
224
+ * ],
225
+ * }))
226
+ * }
227
+ * ```
79
228
  */
80
229
  export declare function injectQueries<T extends Array<any>, TCombinedResult = QueriesResults<T>>(optionsFn: () => InjectQueriesOptions<T, TCombinedResult>, injector?: Injector): Signal<TCombinedResult>;
81
230
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"inject-queries.mjs","sources":["../src/inject-queries.ts"],"sourcesContent":["import {\n QueriesObserver,\n QueryClient,\n notifyManager,\n} from '@tanstack/query-core'\nimport {\n DestroyRef,\n Injector,\n NgZone,\n assertInInjectionContext,\n computed,\n effect,\n inject,\n runInInjectionContext,\n signal,\n untracked,\n} from '@angular/core'\nimport { signalProxy } from './signal-proxy'\nimport { injectIsRestoring } from './inject-is-restoring'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesObserverOptions,\n QueriesPlaceholderDataFunction,\n QueryFunction,\n QueryKey,\n QueryObserverOptions,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type {\n CreateQueryOptions,\n CreateQueryResult,\n DefinedCreateQueryResult,\n} from './types'\nimport type { Signal } from '@angular/core'\n\n// This defines the `CreateQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function always gets undefined passed\ntype QueryObserverOptionsForCreateQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'placeholderData'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForCreateQueries = symbol\n\ntype GetCreateQueryOptionsForCreateQueries<T> =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? QueryObserverOptionsForCreateQueries<unknown, TError, TData>\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData>\n : T extends [infer TQueryFnData, infer TError]\n ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? QueryObserverOptionsForCreateQueries<TQueryFnData>\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, infer TQueryKey>\n | SkipTokenForCreateQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? QueryObserverOptionsForCreateQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n QueryObserverOptionsForCreateQueries\n\n// A defined initialData setting should return a DefinedCreateQueryResult rather than CreateQueryResult\ntype GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {\n initialData?: infer TInitialData\n}\n ? unknown extends TInitialData\n ? CreateQueryResult<TData, TError>\n : TInitialData extends TData\n ? DefinedCreateQueryResult<TData, TError>\n : TInitialData extends () => infer TInitialDataResult\n ? unknown extends TInitialDataResult\n ? CreateQueryResult<TData, TError>\n : TInitialDataResult extends TData\n ? DefinedCreateQueryResult<TData, TError>\n : CreateQueryResult<TData, TError>\n : CreateQueryResult<TData, TError>\n : CreateQueryResult<TData, TError>\n\ntype GetCreateQueryResult<T> =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends [infer TQueryFnData, infer TError]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, any>\n | SkipTokenForCreateQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? GetDefinedOrUndefinedQueryResult<\n T,\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n CreateQueryResult\n\n/**\n * QueriesOptions reducer recursively unwraps function arguments to infer/enforce type param\n */\nexport type QueriesOptions<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<QueryObserverOptionsForCreateQueries>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetCreateQueryOptionsForCreateQueries<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesOptions<\n [...Tails],\n [...TResults, GetCreateQueryOptionsForCreateQueries<Head>],\n [...TDepth, 1]\n >\n : ReadonlyArray<unknown> extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n QueryObserverOptionsForCreateQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n QueryObserverOptionsForCreateQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array<QueryObserverOptionsForCreateQueries>\n\n/**\n * QueriesResults reducer recursively maps type param to results\n */\nexport type QueriesResults<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<CreateQueryResult>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetCreateQueryResult<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesResults<\n [...Tails],\n [...TResults, GetCreateQueryResult<Head>],\n [...TDepth, 1]\n >\n : { [K in keyof T]: GetCreateQueryResult<T[K]> }\n\nexport interface InjectQueriesOptions<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n> {\n queries:\n | readonly [...QueriesOptions<T>]\n | readonly [\n ...{ [K in keyof T]: GetCreateQueryOptionsForCreateQueries<T[K]> },\n ]\n combine?: (result: QueriesResults<T>) => TCombinedResult\n}\n\n/**\n * @param optionsFn - A function that returns queries' options.\n * @param injector - The Angular injector to use.\n */\nexport function injectQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n optionsFn: () => InjectQueriesOptions<T, TCombinedResult>,\n injector?: Injector,\n): Signal<TCombinedResult> {\n !injector && assertInInjectionContext(injectQueries)\n return runInInjectionContext(injector ?? inject(Injector), () => {\n const destroyRef = inject(DestroyRef)\n const ngZone = inject(NgZone)\n const queryClient = inject(QueryClient)\n const isRestoring = injectIsRestoring()\n\n /**\n * Signal that has the default options from query client applied\n * computed() is used so signals can be inserted into the options\n * making it reactive. Wrapping options in a function ensures embedded expressions\n * are preserved and can keep being applied after signal changes\n */\n const optionsSignal = computed(() => {\n return optionsFn()\n })\n\n const defaultedQueries = computed(() => {\n return optionsSignal().queries.map((opts) => {\n const defaultedOptions = queryClient.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n // Make sure the results are already in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = isRestoring()\n ? 'isRestoring'\n : 'optimistic'\n\n return defaultedOptions as QueryObserverOptions\n })\n })\n\n const observerSignal = (() => {\n let instance: QueriesObserver<TCombinedResult> | null = null\n\n return computed(() => {\n return (instance ||= new QueriesObserver<TCombinedResult>(\n queryClient,\n defaultedQueries(),\n optionsSignal() as QueriesObserverOptions<TCombinedResult>,\n ))\n })\n })()\n\n const optimisticResultSignal = computed(() =>\n observerSignal().getOptimisticResult(\n defaultedQueries(),\n (optionsSignal() as QueriesObserverOptions<TCombinedResult>).combine,\n ),\n )\n\n // Do not notify on updates because of changes in the options because\n // these changes should already be reflected in the optimistic result.\n effect(() => {\n observerSignal().setQueries(\n defaultedQueries(),\n optionsSignal() as QueriesObserverOptions<TCombinedResult>,\n )\n })\n\n const optimisticCombinedResultSignal = computed(() => {\n const [_optimisticResult, getCombinedResult, trackResult] =\n optimisticResultSignal()\n return getCombinedResult(trackResult())\n })\n\n const resultFromSubscriberSignal = signal<TCombinedResult | null>(null)\n\n effect(() => {\n const observer = observerSignal()\n const [_optimisticResult, getCombinedResult] = optimisticResultSignal()\n\n untracked(() => {\n const unsubscribe = isRestoring()\n ? () => undefined\n : ngZone.runOutsideAngular(() =>\n observer.subscribe(\n notifyManager.batchCalls((state) => {\n resultFromSubscriberSignal.set(getCombinedResult(state))\n }),\n ),\n )\n\n destroyRef.onDestroy(unsubscribe)\n })\n })\n\n const resultSignal = computed(() => {\n const subscriberResult = resultFromSubscriberSignal()\n const optimisticResult = optimisticCombinedResultSignal()\n return subscriberResult ?? optimisticResult\n })\n\n return computed(() => {\n const result = resultSignal()\n const { combine } = optionsSignal()\n\n return combine\n ? result\n : (result as QueriesResults<T>).map((query) =>\n signalProxy(signal(query)),\n )\n })\n }) as unknown as Signal<TCombinedResult>\n}\n"],"names":[],"mappings":";;;;AA2NO,SAAS,cAId,WACA,UACyB;AACzB,GAAC,YAAY,yBAAyB,aAAa;AACnD,SAAO,sBAAsB,YAAY,OAAO,QAAQ,GAAG,MAAM;AAC/D,UAAM,aAAa,OAAO,UAAU;AACpC,UAAM,SAAS,OAAO,MAAM;AAC5B,UAAM,cAAc,OAAO,WAAW;AACtC,UAAM,cAAc,kBAAA;AAQpB,UAAM,gBAAgB,SAAS,MAAM;AACnC,aAAO,UAAA;AAAA,IACT,CAAC;AAED,UAAM,mBAAmB,SAAS,MAAM;AACtC,aAAO,cAAA,EAAgB,QAAQ,IAAI,CAAC,SAAS;AAC3C,cAAM,mBAAmB,YAAY;AAAA,UACnC;AAAA,QAAA;AAGF,yBAAiB,qBAAqB,YAAA,IAClC,gBACA;AAEJ,eAAO;AAAA,MACT,CAAC;AAAA,IACH,CAAC;AAED,UAAM,kBAAkB,MAAM;AAC5B,UAAI,WAAoD;AAExD,aAAO,SAAS,MAAM;AACpB,eAAQ,wBAAa,IAAI;AAAA,UACvB;AAAA,UACA,iBAAA;AAAA,UACA,cAAA;AAAA,QAAc;AAAA,MAElB,CAAC;AAAA,IACH,GAAA;AAEA,UAAM,yBAAyB;AAAA,MAAS,MACtC,iBAAiB;AAAA,QACf,iBAAA;AAAA,QACC,gBAA4D;AAAA,MAAA;AAAA,IAC/D;AAKF,WAAO,MAAM;AACX,qBAAA,EAAiB;AAAA,QACf,iBAAA;AAAA,QACA,cAAA;AAAA,MAAc;AAAA,IAElB,CAAC;AAED,UAAM,iCAAiC,SAAS,MAAM;AACpD,YAAM,CAAC,mBAAmB,mBAAmB,WAAW,IACtD,uBAAA;AACF,aAAO,kBAAkB,aAAa;AAAA,IACxC,CAAC;AAED,UAAM,6BAA6B,OAA+B,IAAI;AAEtE,WAAO,MAAM;AACX,YAAM,WAAW,eAAA;AACjB,YAAM,CAAC,mBAAmB,iBAAiB,IAAI,uBAAA;AAE/C,gBAAU,MAAM;AACd,cAAM,cAAc,YAAA,IAChB,MAAM,SACN,OAAO;AAAA,UAAkB,MACvB,SAAS;AAAA,YACP,cAAc,WAAW,CAAC,UAAU;AAClC,yCAA2B,IAAI,kBAAkB,KAAK,CAAC;AAAA,YACzD,CAAC;AAAA,UAAA;AAAA,QACH;AAGN,mBAAW,UAAU,WAAW;AAAA,MAClC,CAAC;AAAA,IACH,CAAC;AAED,UAAM,eAAe,SAAS,MAAM;AAClC,YAAM,mBAAmB,2BAAA;AACzB,YAAM,mBAAmB,+BAAA;AACzB,aAAO,oBAAoB;AAAA,IAC7B,CAAC;AAED,WAAO,SAAS,MAAM;AACpB,YAAM,SAAS,aAAA;AACf,YAAM,EAAE,QAAA,IAAY,cAAA;AAEpB,aAAO,UACH,SACC,OAA6B;AAAA,QAAI,CAAC,UACjC,YAAY,OAAO,KAAK,CAAC;AAAA,MAAA;AAAA,IAEjC,CAAC;AAAA,EACH,CAAC;AACH;"}
1
+ {"version":3,"file":"inject-queries.mjs","sources":["../src/inject-queries.ts"],"sourcesContent":["import {\n QueriesObserver,\n QueryClient,\n notifyManager,\n} from '@tanstack/query-core'\nimport {\n DestroyRef,\n Injector,\n NgZone,\n assertInInjectionContext,\n computed,\n effect,\n inject,\n runInInjectionContext,\n signal,\n untracked,\n} from '@angular/core'\nimport { signalProxy } from './signal-proxy'\nimport { injectIsRestoring } from './inject-is-restoring'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesObserverOptions,\n QueriesPlaceholderDataFunction,\n QueryFunction,\n QueryKey,\n QueryObserverOptions,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type {\n CreateQueryOptions,\n CreateQueryResult,\n DefinedCreateQueryResult,\n} from './types'\nimport type { Signal } from '@angular/core'\n\n// This defines the `CreateQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function always gets undefined passed\ntype QueryObserverOptionsForCreateQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'placeholderData'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForCreateQueries = symbol\n\ntype GetCreateQueryOptionsForCreateQueries<T> =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? QueryObserverOptionsForCreateQueries<unknown, TError, TData>\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData>\n : T extends [infer TQueryFnData, infer TError]\n ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? QueryObserverOptionsForCreateQueries<TQueryFnData>\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, infer TQueryKey>\n | SkipTokenForCreateQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? QueryObserverOptionsForCreateQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n QueryObserverOptionsForCreateQueries\n\n// A defined initialData setting should return a DefinedCreateQueryResult rather than CreateQueryResult\ntype GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {\n initialData?: infer TInitialData\n}\n ? unknown extends TInitialData\n ? CreateQueryResult<TData, TError>\n : TInitialData extends TData\n ? DefinedCreateQueryResult<TData, TError>\n : TInitialData extends () => infer TInitialDataResult\n ? unknown extends TInitialDataResult\n ? CreateQueryResult<TData, TError>\n : TInitialDataResult extends TData\n ? DefinedCreateQueryResult<TData, TError>\n : CreateQueryResult<TData, TError>\n : CreateQueryResult<TData, TError>\n : CreateQueryResult<TData, TError>\n\ntype GetCreateQueryResult<T> =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends [infer TQueryFnData, infer TError]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, any>\n | SkipTokenForCreateQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? GetDefinedOrUndefinedQueryResult<\n T,\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n CreateQueryResult\n\n/**\n * The `queries` array accepted by `injectQueries`. Recursively unwraps each tuple element so every entry's\n * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements — past that, tuple\n * recursion falls back to a single homogeneous options type. An opaque array (e.g. `unknown[]`) is returned\n * as-is; a non-tuple array of a known element type is mapped to that element type instead, with no such\n * limit.\n *\n * @template T - The type of the `queries` array as written at the call site.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant to\n * be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesOptions<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<QueryObserverOptionsForCreateQueries>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetCreateQueryOptionsForCreateQueries<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesOptions<\n [...Tails],\n [...TResults, GetCreateQueryOptionsForCreateQueries<Head>],\n [...TDepth, 1]\n >\n : ReadonlyArray<unknown> extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n QueryObserverOptionsForCreateQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n QueryObserverOptionsForCreateQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array<QueryObserverOptionsForCreateQueries>\n\n/**\n * The result type returned by `injectQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}:\n * each tuple element's result type is inferred individually, up to 20 elements — past that, tuple recursion\n * falls back to a single homogeneous {@link CreateQueryResult} type. A non-tuple array is mapped per-element\n * instead, with no such limit — every entry keeps its individually inferred type regardless of array length.\n *\n * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant to\n * be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesResults<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<CreateQueryResult>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetCreateQueryResult<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesResults<\n [...Tails],\n [...TResults, GetCreateQueryResult<Head>],\n [...TDepth, 1]\n >\n : { [K in keyof T]: GetCreateQueryResult<T[K]> }\n\nexport interface InjectQueriesOptions<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n> {\n queries:\n | readonly [...QueriesOptions<T>]\n | readonly [\n ...{ [K in keyof T]: GetCreateQueryOptionsForCreateQueries<T[K]> },\n ]\n combine?: (result: QueriesResults<T>) => TCombinedResult\n}\n\n/**\n * Injects a signal to fetch a variable number of queries.\n *\n * The `queries` key accepts an array with query option objects mostly identical to `injectQuery`'s. Having\n * the same query key more than once in the array of query objects may cause some data to be shared between\n * queries. To avoid this, consider de-duplicating the queries and map the results back to the desired\n * structure.\n *\n * The `combine` option can be used to combine the results of the queries into a single value. The result\n * will be structurally shared to be as referentially stable as possible.\n *\n * @remarks Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of an _inline_ `select`\n * from its sibling `queryFn`. Because `injectQueries` infers the type of the whole `queries` array at once,\n * the `select` parameter of a query object written inline cannot be contextually typed from that same\n * object's `queryFn`, so it falls back to `unknown` — a\n * [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate the `select`\n * parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in a single\n * object _before_ it reaches `injectQueries`, to work around this — see the example below.\n * @param optionsFn - A function returning the queries' options — an array of query option objects under\n * `queries`, and an optional `combine`. Similar to `computed` from Angular, this function runs in the\n * reactive context, so signals read inside it (e.g. to build the `queries` array) drive the queries.\n * @param injector - The `Injector` in which to create the queries. If this is not provided, the current\n * injection context will be used instead (via `inject`).\n * @returns A `Signal` with the combined result. Without `combine`, this is an array with all the query\n * results, in the same order as the input. When `combine` is provided, this is the value returned by\n * `combine` instead.\n *\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <ul>\n * @for (query of postQueries(); track $index) {\n * @if (query.isPending()) {\n * <li>Loading...</li>\n * } @else if (query.isError()) {\n * <li>Error: {{ query.error()?.message }}</li>\n * } @else {\n * <li>{{ query.data().title }}</li>\n * }\n * }\n * </ul>\n * `,\n * })\n * export class Posts {\n * readonly ids = signal([1, 2, 3])\n *\n * readonly postQueries = injectQueries(() => ({\n * queries: this.ids().map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * staleTime: Infinity,\n * })),\n * }))\n * }\n * ```\n *\n * @example\n * Combining results into a single value:\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * @if (combined().isPending) {\n * Loading...\n * } @else if (combined().isError) {\n * Error loading posts\n * } @else {\n * <ul>\n * @for (post of combined().data; track post?.id) {\n * <li>{{ post?.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly ids = signal([1, 2, 3])\n *\n * readonly combined = injectQueries(() => ({\n * queries: this.ids().map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })),\n * combine: (postQueries) => ({\n * data: postQueries.map((query) => query.data),\n * isPending: postQueries.some((query) => query.isPending),\n * isError: postQueries.some((query) => query.isError),\n * }),\n * }))\n * }\n * ```\n *\n * @example\n * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding\n * `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is\n * resolved before it reaches `injectQueries`:\n * ```angular-ts\n * const postOptions = (id: number) =>\n * queryOptions({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })\n *\n * @Component({\n * selector: 'post-title',\n * template: `<h1>{{ fixed()[0].data() }}</h1>`,\n * })\n * export class PostTitle {\n * readonly id = signal(1)\n *\n * readonly broken = injectQueries(() => ({\n * queries: [\n * {\n * ...postOptions(this.id()),\n * // ❌ `data` is `unknown` here\n * select: (data) => data.title,\n * },\n * ],\n * }))\n *\n * readonly fixed = injectQueries(() => ({\n * queries: [\n * queryOptions({\n * ...postOptions(this.id()),\n * // ✅ `data` is `Post`\n * select: (data) => data.title,\n * }),\n * ],\n * }))\n * }\n * ```\n */\nexport function injectQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n optionsFn: () => InjectQueriesOptions<T, TCombinedResult>,\n injector?: Injector,\n): Signal<TCombinedResult> {\n !injector && assertInInjectionContext(injectQueries)\n return runInInjectionContext(injector ?? inject(Injector), () => {\n const destroyRef = inject(DestroyRef)\n const ngZone = inject(NgZone)\n const queryClient = inject(QueryClient)\n const isRestoring = injectIsRestoring()\n\n /**\n * Signal that has the default options from query client applied\n * computed() is used so signals can be inserted into the options\n * making it reactive. Wrapping options in a function ensures embedded expressions\n * are preserved and can keep being applied after signal changes\n */\n const optionsSignal = computed(() => {\n return optionsFn()\n })\n\n const defaultedQueries = computed(() => {\n return optionsSignal().queries.map((opts) => {\n const defaultedOptions = queryClient.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n // Make sure the results are already in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = isRestoring()\n ? 'isRestoring'\n : 'optimistic'\n\n return defaultedOptions as QueryObserverOptions\n })\n })\n\n const observerSignal = (() => {\n let instance: QueriesObserver<TCombinedResult> | null = null\n\n return computed(() => {\n return (instance ||= new QueriesObserver<TCombinedResult>(\n queryClient,\n defaultedQueries(),\n optionsSignal() as QueriesObserverOptions<TCombinedResult>,\n ))\n })\n })()\n\n const optimisticResultSignal = computed(() =>\n observerSignal().getOptimisticResult(\n defaultedQueries(),\n (optionsSignal() as QueriesObserverOptions<TCombinedResult>).combine,\n ),\n )\n\n // Do not notify on updates because of changes in the options because\n // these changes should already be reflected in the optimistic result.\n effect(() => {\n observerSignal().setQueries(\n defaultedQueries(),\n optionsSignal() as QueriesObserverOptions<TCombinedResult>,\n )\n })\n\n const optimisticCombinedResultSignal = computed(() => {\n const [_optimisticResult, getCombinedResult, trackResult] =\n optimisticResultSignal()\n return getCombinedResult(trackResult())\n })\n\n const resultFromSubscriberSignal = signal<TCombinedResult | null>(null)\n\n effect(() => {\n const observer = observerSignal()\n const [_optimisticResult, getCombinedResult] = optimisticResultSignal()\n\n untracked(() => {\n const unsubscribe = isRestoring()\n ? () => undefined\n : ngZone.runOutsideAngular(() =>\n observer.subscribe(\n notifyManager.batchCalls((state) => {\n resultFromSubscriberSignal.set(getCombinedResult(state))\n }),\n ),\n )\n\n destroyRef.onDestroy(unsubscribe)\n })\n })\n\n const resultSignal = computed(() => {\n const subscriberResult = resultFromSubscriberSignal()\n const optimisticResult = optimisticCombinedResultSignal()\n return subscriberResult ?? optimisticResult\n })\n\n return computed(() => {\n const result = resultSignal()\n const { combine } = optionsSignal()\n\n return combine\n ? result\n : (result as QueriesResults<T>).map((query) =>\n signalProxy(signal(query)),\n )\n })\n }) as unknown as Signal<TCombinedResult>\n}\n"],"names":[],"mappings":";;;;AAgXO,SAAS,cAId,WACA,UACyB;AACzB,GAAC,YAAY,yBAAyB,aAAa;AACnD,SAAO,sBAAsB,YAAY,OAAO,QAAQ,GAAG,MAAM;AAC/D,UAAM,aAAa,OAAO,UAAU;AACpC,UAAM,SAAS,OAAO,MAAM;AAC5B,UAAM,cAAc,OAAO,WAAW;AACtC,UAAM,cAAc,kBAAA;AAQpB,UAAM,gBAAgB,SAAS,MAAM;AACnC,aAAO,UAAA;AAAA,IACT,CAAC;AAED,UAAM,mBAAmB,SAAS,MAAM;AACtC,aAAO,cAAA,EAAgB,QAAQ,IAAI,CAAC,SAAS;AAC3C,cAAM,mBAAmB,YAAY;AAAA,UACnC;AAAA,QAAA;AAGF,yBAAiB,qBAAqB,YAAA,IAClC,gBACA;AAEJ,eAAO;AAAA,MACT,CAAC;AAAA,IACH,CAAC;AAED,UAAM,kBAAkB,MAAM;AAC5B,UAAI,WAAoD;AAExD,aAAO,SAAS,MAAM;AACpB,eAAQ,wBAAa,IAAI;AAAA,UACvB;AAAA,UACA,iBAAA;AAAA,UACA,cAAA;AAAA,QAAc;AAAA,MAElB,CAAC;AAAA,IACH,GAAA;AAEA,UAAM,yBAAyB;AAAA,MAAS,MACtC,iBAAiB;AAAA,QACf,iBAAA;AAAA,QACC,gBAA4D;AAAA,MAAA;AAAA,IAC/D;AAKF,WAAO,MAAM;AACX,qBAAA,EAAiB;AAAA,QACf,iBAAA;AAAA,QACA,cAAA;AAAA,MAAc;AAAA,IAElB,CAAC;AAED,UAAM,iCAAiC,SAAS,MAAM;AACpD,YAAM,CAAC,mBAAmB,mBAAmB,WAAW,IACtD,uBAAA;AACF,aAAO,kBAAkB,aAAa;AAAA,IACxC,CAAC;AAED,UAAM,6BAA6B,OAA+B,IAAI;AAEtE,WAAO,MAAM;AACX,YAAM,WAAW,eAAA;AACjB,YAAM,CAAC,mBAAmB,iBAAiB,IAAI,uBAAA;AAE/C,gBAAU,MAAM;AACd,cAAM,cAAc,YAAA,IAChB,MAAM,SACN,OAAO;AAAA,UAAkB,MACvB,SAAS;AAAA,YACP,cAAc,WAAW,CAAC,UAAU;AAClC,yCAA2B,IAAI,kBAAkB,KAAK,CAAC;AAAA,YACzD,CAAC;AAAA,UAAA;AAAA,QACH;AAGN,mBAAW,UAAU,WAAW;AAAA,MAClC,CAAC;AAAA,IACH,CAAC;AAED,UAAM,eAAe,SAAS,MAAM;AAClC,YAAM,mBAAmB,2BAAA;AACzB,YAAM,mBAAmB,+BAAA;AACzB,aAAO,oBAAoB;AAAA,IAC7B,CAAC;AAED,WAAO,SAAS,MAAM;AACpB,YAAM,SAAS,aAAA;AACf,YAAM,EAAE,QAAA,IAAY,cAAA;AAEpB,aAAO,UACH,SACC,OAA6B;AAAA,QAAI,CAAC,UACjC,YAAY,OAAO,KAAK,CAAC;AAAA,MAAA;AAAA,IAEjC,CAAC;AAAA,EACH,CAAC;AACH;"}