@tanstack/angular-query-experimental 5.103.1 → 5.103.3
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/dist/create-base-query.d.mts +169 -0
- package/dist/create-base-query.d.mts.map +1 -0
- package/dist/create-base-query.mjs +91 -0
- package/dist/create-base-query.mjs.map +1 -0
- package/dist/devtools/index.d.mts +3 -0
- package/dist/devtools/index.mjs +2 -0
- package/dist/devtools/production/index.d.mts +4 -0
- package/dist/devtools/production/index.mjs +2 -0
- package/dist/devtools/stub.d.mts +6 -0
- package/dist/devtools/stub.d.mts.map +1 -0
- package/dist/devtools/stub.mjs +9 -0
- package/dist/devtools/stub.mjs.map +1 -0
- package/dist/devtools/types.d.mts +107 -0
- package/dist/devtools/types.d.mts.map +1 -0
- package/dist/devtools/types.mjs +1 -0
- package/{devtools/with-devtools.d.ts → dist/devtools/with-devtools.d.mts} +6 -2
- package/dist/devtools/with-devtools.d.mts.map +1 -0
- package/dist/devtools/with-devtools.mjs +110 -0
- package/dist/devtools/with-devtools.mjs.map +1 -0
- package/dist/devtools-panel/index.d.mts +3 -0
- package/dist/devtools-panel/index.mjs +2 -0
- package/{devtools-panel/inject-devtools-panel.d.ts → dist/devtools-panel/inject-devtools-panel.d.mts} +6 -2
- package/dist/devtools-panel/inject-devtools-panel.d.mts.map +1 -0
- package/dist/devtools-panel/inject-devtools-panel.mjs +67 -0
- package/dist/devtools-panel/inject-devtools-panel.mjs.map +1 -0
- package/dist/devtools-panel/production/index.d.mts +4 -0
- package/dist/devtools-panel/production/index.mjs +2 -0
- package/dist/devtools-panel/stub.d.mts +6 -0
- package/dist/devtools-panel/stub.d.mts.map +1 -0
- package/dist/devtools-panel/stub.mjs +7 -0
- package/dist/devtools-panel/stub.mjs.map +1 -0
- package/dist/devtools-panel/types.d.mts +52 -0
- package/dist/devtools-panel/types.d.mts.map +1 -0
- package/dist/devtools-panel/types.mjs +1 -0
- package/dist/index.d.mts +16 -0
- package/{index.mjs → dist/index.mjs} +8 -21
- package/dist/index.mjs.map +1 -0
- package/{infinite-query-options.d.ts → dist/infinite-query-options.d.mts} +35 -31
- package/dist/infinite-query-options.d.mts.map +1 -0
- package/dist/infinite-query-options.mjs +8 -0
- package/dist/infinite-query-options.mjs.map +1 -0
- package/{inject-infinite-query.d.ts → dist/inject-infinite-query.d.mts} +18 -14
- package/dist/inject-infinite-query.d.mts.map +1 -0
- package/dist/inject-infinite-query.mjs +13 -0
- package/dist/inject-infinite-query.mjs.map +1 -0
- package/{inject-is-fetching.d.ts → dist/inject-is-fetching.d.mts} +14 -10
- package/dist/inject-is-fetching.d.mts.map +1 -0
- package/dist/inject-is-fetching.mjs +69 -0
- package/dist/inject-is-fetching.mjs.map +1 -0
- package/{inject-is-mutating.d.ts → dist/inject-is-mutating.d.mts} +14 -10
- package/dist/inject-is-mutating.d.mts.map +1 -0
- package/dist/inject-is-mutating.mjs +52 -0
- package/dist/inject-is-mutating.mjs.map +1 -0
- package/{inject-is-restoring.d.ts → dist/inject-is-restoring.d.mts} +13 -10
- package/dist/inject-is-restoring.d.mts.map +1 -0
- package/dist/inject-is-restoring.mjs +35 -0
- package/dist/inject-is-restoring.mjs.map +1 -0
- package/{inject-mutation-state.d.ts → dist/inject-mutation-state.d.mts} +16 -13
- package/dist/inject-mutation-state.d.mts.map +1 -0
- package/dist/inject-mutation-state.mjs +103 -0
- package/dist/inject-mutation-state.mjs.map +1 -0
- package/{inject-mutation.d.ts → dist/inject-mutation.d.mts} +15 -11
- package/dist/inject-mutation.d.mts.map +1 -0
- package/dist/inject-mutation.mjs +226 -0
- package/dist/inject-mutation.mjs.map +1 -0
- package/dist/inject-queries-experimental/index.d.mts +2 -0
- package/dist/inject-queries-experimental/index.mjs +2 -0
- package/{inject-queries.d.ts → dist/inject-queries.d.mts} +36 -55
- package/dist/inject-queries.d.mts.map +1 -0
- package/dist/inject-queries.mjs +203 -0
- package/dist/inject-queries.mjs.map +1 -0
- package/{inject-query-client.d.ts → dist/inject-query-client.d.mts} +8 -4
- package/dist/inject-query-client.d.mts.map +1 -0
- package/dist/inject-query-client.mjs +23 -0
- package/dist/inject-query-client.mjs.map +1 -0
- package/{inject-query.d.ts → dist/inject-query.d.mts} +18 -14
- package/dist/inject-query.d.mts.map +1 -0
- package/dist/inject-query.mjs +12 -0
- package/dist/inject-query.mjs.map +1 -0
- package/{mutation-options.d.ts → dist/mutation-options.d.mts} +8 -4
- package/dist/mutation-options.d.mts.map +1 -0
- package/dist/mutation-options.mjs +8 -0
- package/dist/mutation-options.mjs.map +1 -0
- package/dist/pending-tasks-compat.d.mts +10 -0
- package/dist/pending-tasks-compat.d.mts.map +1 -0
- package/dist/pending-tasks-compat.mjs +13 -0
- package/dist/pending-tasks-compat.mjs.map +1 -0
- package/{providers.d.ts → dist/providers.d.mts} +16 -13
- package/dist/providers.d.mts.map +1 -0
- package/dist/providers.mjs +124 -0
- package/dist/providers.mjs.map +1 -0
- package/{query-options.d.ts → dist/query-options.d.mts} +41 -37
- package/dist/query-options.d.mts.map +1 -0
- package/dist/query-options.mjs +8 -0
- package/dist/query-options.mjs.map +1 -0
- package/dist/signal-proxy.d.mts +13 -0
- package/dist/signal-proxy.d.mts.map +1 -0
- package/dist/signal-proxy.mjs +35 -0
- package/dist/signal-proxy.mjs.map +1 -0
- package/{types.d.ts → dist/types.d.mts} +36 -37
- package/dist/types.d.mts.map +1 -0
- package/dist/types.mjs +6 -0
- package/dist/types.mjs.map +1 -0
- package/package.json +48 -20
- package/src/__tests__/infinite-query-options.test-d.ts +314 -0
- package/src/__tests__/infinite-query-options.test.ts +19 -0
- package/src/__tests__/inject-devtools-panel.test.ts +196 -0
- package/src/__tests__/inject-infinite-query.test-d.ts +66 -0
- package/src/__tests__/inject-infinite-query.test.ts +227 -0
- package/src/__tests__/inject-is-fetching.test.ts +108 -0
- package/src/__tests__/inject-is-mutating.test.ts +113 -0
- package/src/__tests__/inject-is-restoring.test.ts +93 -0
- package/src/__tests__/inject-mutation-state.test-d.ts +22 -0
- package/src/__tests__/inject-mutation-state.test.ts +198 -0
- package/src/__tests__/inject-mutation.test-d.ts +158 -0
- package/src/__tests__/inject-mutation.test.ts +1161 -0
- package/src/__tests__/inject-queries.test-d.ts +196 -0
- package/src/__tests__/inject-queries.test.ts +240 -0
- package/src/__tests__/inject-query.test-d.ts +357 -0
- package/src/__tests__/inject-query.test.ts +700 -0
- package/src/__tests__/mutation-options.test-d.ts +234 -0
- package/src/__tests__/mutation-options.test.ts +344 -0
- package/src/__tests__/pending-tasks.test.ts +644 -0
- package/src/__tests__/provide-query-client.test.ts +38 -0
- package/src/__tests__/provide-tanstack-query.test.ts +38 -0
- package/src/__tests__/query-options.test-d.ts +262 -0
- package/src/__tests__/query-options.test.ts +14 -0
- package/src/__tests__/signal-proxy.test.ts +27 -0
- package/src/__tests__/test-utils.ts +77 -0
- package/src/__tests__/with-devtools.test.ts +674 -0
- package/src/create-base-query.ts +175 -0
- package/src/devtools/index.ts +8 -0
- package/src/devtools/production/index.ts +1 -0
- package/src/devtools/stub.ts +7 -0
- package/src/devtools/types.ts +116 -0
- package/src/devtools/with-devtools.ts +182 -0
- package/src/devtools-panel/index.ts +8 -0
- package/src/devtools-panel/inject-devtools-panel.ts +110 -0
- package/src/devtools-panel/production/index.ts +1 -0
- package/src/devtools-panel/stub.ts +7 -0
- package/src/devtools-panel/types.ts +57 -0
- package/src/index.ts +60 -0
- package/src/infinite-query-options.ts +354 -0
- package/src/inject-infinite-query.ts +296 -0
- package/src/inject-is-fetching.ts +97 -0
- package/src/inject-is-mutating.ts +80 -0
- package/src/inject-is-restoring.ts +53 -0
- package/src/inject-mutation-state.ts +167 -0
- package/src/inject-mutation.ts +328 -0
- package/src/inject-queries-experimental/index.ts +1 -0
- package/src/inject-queries.ts +479 -0
- package/src/inject-query-client.ts +22 -0
- package/src/inject-query.ts +208 -0
- package/src/mutation-options.ts +121 -0
- package/src/pending-tasks-compat.ts +27 -0
- package/src/providers.ts +170 -0
- package/src/query-options.ts +292 -0
- package/src/signal-proxy.ts +46 -0
- package/src/types.ts +429 -0
- package/create-base-query.d.ts +0 -164
- package/create-base-query.mjs +0 -99
- package/create-base-query.mjs.map +0 -1
- package/devtools/index.d.ts +0 -2
- package/devtools/index.mjs +0 -5
- package/devtools/index.mjs.map +0 -1
- package/devtools/production/index.d.ts +0 -1
- package/devtools/stub.d.ts +0 -2
- package/devtools/stub.mjs +0 -8
- package/devtools/stub.mjs.map +0 -1
- package/devtools/types.d.ts +0 -100
- package/devtools/with-devtools.mjs +0 -106
- package/devtools/with-devtools.mjs.map +0 -1
- package/devtools-panel/index.d.ts +0 -2
- package/devtools-panel/index.mjs +0 -5
- package/devtools-panel/index.mjs.map +0 -1
- package/devtools-panel/inject-devtools-panel.mjs +0 -72
- package/devtools-panel/inject-devtools-panel.mjs.map +0 -1
- package/devtools-panel/production/index.d.ts +0 -1
- package/devtools-panel/stub.d.ts +0 -2
- package/devtools-panel/stub.mjs +0 -8
- package/devtools-panel/stub.mjs.map +0 -1
- package/devtools-panel/types.d.ts +0 -48
- package/index.d.ts +0 -25
- package/index.mjs.map +0 -1
- package/infinite-query-options.mjs +0 -7
- package/infinite-query-options.mjs.map +0 -1
- package/inject-infinite-query.mjs +0 -18
- package/inject-infinite-query.mjs.map +0 -1
- package/inject-is-fetching.mjs +0 -31
- package/inject-is-fetching.mjs.map +0 -1
- package/inject-is-mutating.mjs +0 -31
- package/inject-is-mutating.mjs.map +0 -1
- package/inject-is-restoring.mjs +0 -21
- package/inject-is-restoring.mjs.map +0 -1
- package/inject-mutation-state.mjs +0 -51
- package/inject-mutation-state.mjs.map +0 -1
- package/inject-mutation.mjs +0 -94
- package/inject-mutation.mjs.map +0 -1
- package/inject-queries-experimental/index.d.ts +0 -1
- package/inject-queries-experimental/index.mjs +0 -5
- package/inject-queries-experimental/index.mjs.map +0 -1
- package/inject-queries.mjs +0 -82
- package/inject-queries.mjs.map +0 -1
- package/inject-query-client.mjs +0 -9
- package/inject-query-client.mjs.map +0 -1
- package/inject-query.mjs +0 -14
- package/inject-query.mjs.map +0 -1
- package/mutation-options.mjs +0 -7
- package/mutation-options.mjs.map +0 -1
- package/pending-tasks-compat.d.ts +0 -7
- package/pending-tasks-compat.mjs +0 -19
- package/pending-tasks-compat.mjs.map +0 -1
- package/providers.mjs +0 -32
- package/providers.mjs.map +0 -1
- package/query-options.mjs +0 -7
- package/query-options.mjs.map +0 -1
- package/signal-proxy.d.ts +0 -11
- package/signal-proxy.mjs +0 -29
- package/signal-proxy.mjs.map +0 -1
package/inject-is-mutating.mjs
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { assertInInjectionContext, inject, Injector, DestroyRef, NgZone, signal } from "@angular/core";
|
|
2
|
-
import { QueryClient, notifyManager } from "@tanstack/query-core";
|
|
3
|
-
function injectIsMutating(filters, options) {
|
|
4
|
-
!(options == null ? void 0 : options.injector) && assertInInjectionContext(injectIsMutating);
|
|
5
|
-
const injector = (options == null ? void 0 : options.injector) ?? inject(Injector);
|
|
6
|
-
const destroyRef = injector.get(DestroyRef);
|
|
7
|
-
const ngZone = injector.get(NgZone);
|
|
8
|
-
const queryClient = injector.get(QueryClient);
|
|
9
|
-
const cache = queryClient.getMutationCache();
|
|
10
|
-
let isMutating = queryClient.isMutating(filters);
|
|
11
|
-
const result = signal(isMutating);
|
|
12
|
-
const unsubscribe = ngZone.runOutsideAngular(
|
|
13
|
-
() => cache.subscribe(
|
|
14
|
-
notifyManager.batchCalls(() => {
|
|
15
|
-
const newIsMutating = queryClient.isMutating(filters);
|
|
16
|
-
if (isMutating !== newIsMutating) {
|
|
17
|
-
isMutating = newIsMutating;
|
|
18
|
-
ngZone.run(() => {
|
|
19
|
-
result.set(isMutating);
|
|
20
|
-
});
|
|
21
|
-
}
|
|
22
|
-
})
|
|
23
|
-
)
|
|
24
|
-
);
|
|
25
|
-
destroyRef.onDestroy(unsubscribe);
|
|
26
|
-
return result.asReadonly();
|
|
27
|
-
}
|
|
28
|
-
export {
|
|
29
|
-
injectIsMutating
|
|
30
|
-
};
|
|
31
|
-
//# sourceMappingURL=inject-is-mutating.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
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;"}
|
package/inject-is-restoring.mjs
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { assertInInjectionContext, inject, Injector, InjectionToken, signal } from "@angular/core";
|
|
2
|
-
const IS_RESTORING = new InjectionToken("", {
|
|
3
|
-
// Default value when not provided
|
|
4
|
-
factory: () => signal(false).asReadonly()
|
|
5
|
-
});
|
|
6
|
-
function injectIsRestoring(options) {
|
|
7
|
-
!(options == null ? void 0 : options.injector) && assertInInjectionContext(injectIsRestoring);
|
|
8
|
-
const injector = (options == null ? void 0 : options.injector) ?? inject(Injector);
|
|
9
|
-
return injector.get(IS_RESTORING);
|
|
10
|
-
}
|
|
11
|
-
function provideIsRestoring(isRestoring) {
|
|
12
|
-
return {
|
|
13
|
-
provide: IS_RESTORING,
|
|
14
|
-
useValue: isRestoring
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
export {
|
|
18
|
-
injectIsRestoring,
|
|
19
|
-
provideIsRestoring
|
|
20
|
-
};
|
|
21
|
-
//# sourceMappingURL=inject-is-restoring.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
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;"}
|
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
import { assertInInjectionContext, inject, Injector, DestroyRef, NgZone, computed, signal } from "@angular/core";
|
|
2
|
-
import { QueryClient, notifyManager, replaceEqualDeep } from "@tanstack/query-core";
|
|
3
|
-
function getResult(mutationCache, options) {
|
|
4
|
-
return mutationCache.findAll(options.filters).map(
|
|
5
|
-
(mutation) => options.select ? options.select(mutation) : mutation.state
|
|
6
|
-
);
|
|
7
|
-
}
|
|
8
|
-
function injectMutationState(injectMutationStateFn = () => ({}), options) {
|
|
9
|
-
!(options == null ? void 0 : options.injector) && assertInInjectionContext(injectMutationState);
|
|
10
|
-
const injector = (options == null ? void 0 : options.injector) ?? inject(Injector);
|
|
11
|
-
const destroyRef = injector.get(DestroyRef);
|
|
12
|
-
const ngZone = injector.get(NgZone);
|
|
13
|
-
const queryClient = injector.get(QueryClient);
|
|
14
|
-
const mutationCache = queryClient.getMutationCache();
|
|
15
|
-
const resultFromOptionsSignal = computed(() => {
|
|
16
|
-
return [
|
|
17
|
-
getResult(mutationCache, injectMutationStateFn()),
|
|
18
|
-
performance.now()
|
|
19
|
-
];
|
|
20
|
-
});
|
|
21
|
-
const resultFromSubscriberSignal = signal(
|
|
22
|
-
null
|
|
23
|
-
);
|
|
24
|
-
const effectiveResultSignal = computed(() => {
|
|
25
|
-
const optionsResult = resultFromOptionsSignal();
|
|
26
|
-
const subscriberResult = resultFromSubscriberSignal();
|
|
27
|
-
return subscriberResult && subscriberResult[1] > optionsResult[1] ? subscriberResult[0] : optionsResult[0];
|
|
28
|
-
});
|
|
29
|
-
const unsubscribe = ngZone.runOutsideAngular(
|
|
30
|
-
() => mutationCache.subscribe(
|
|
31
|
-
notifyManager.batchCalls(() => {
|
|
32
|
-
const [lastResult] = effectiveResultSignal();
|
|
33
|
-
const nextResult = replaceEqualDeep(
|
|
34
|
-
lastResult,
|
|
35
|
-
getResult(mutationCache, injectMutationStateFn())
|
|
36
|
-
);
|
|
37
|
-
if (lastResult !== nextResult) {
|
|
38
|
-
ngZone.run(() => {
|
|
39
|
-
resultFromSubscriberSignal.set([nextResult, performance.now()]);
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
})
|
|
43
|
-
)
|
|
44
|
-
);
|
|
45
|
-
destroyRef.onDestroy(unsubscribe);
|
|
46
|
-
return effectiveResultSignal;
|
|
47
|
-
}
|
|
48
|
-
export {
|
|
49
|
-
injectMutationState
|
|
50
|
-
};
|
|
51
|
-
//# sourceMappingURL=inject-mutation-state.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
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;"}
|
package/inject-mutation.mjs
DELETED
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
import { assertInInjectionContext, inject, Injector, NgZone, computed, signal, effect, untracked } from "@angular/core";
|
|
2
|
-
import { QueryClient, MutationObserver, noop, notifyManager, shouldThrowError } from "@tanstack/query-core";
|
|
3
|
-
import { signalProxy } from "./signal-proxy.mjs";
|
|
4
|
-
import { PENDING_TASKS } from "./pending-tasks-compat.mjs";
|
|
5
|
-
function injectMutation(injectMutationFn, options) {
|
|
6
|
-
!(options == null ? void 0 : options.injector) && assertInInjectionContext(injectMutation);
|
|
7
|
-
const injector = (options == null ? void 0 : options.injector) ?? inject(Injector);
|
|
8
|
-
const ngZone = injector.get(NgZone);
|
|
9
|
-
const pendingTasks = injector.get(PENDING_TASKS);
|
|
10
|
-
const queryClient = injector.get(QueryClient);
|
|
11
|
-
const optionsSignal = computed(injectMutationFn);
|
|
12
|
-
const observerSignal = (() => {
|
|
13
|
-
let instance = null;
|
|
14
|
-
return computed(() => {
|
|
15
|
-
return instance || (instance = new MutationObserver(queryClient, optionsSignal()));
|
|
16
|
-
});
|
|
17
|
-
})();
|
|
18
|
-
const mutateFnSignal = computed(() => {
|
|
19
|
-
const observer = observerSignal();
|
|
20
|
-
return (...args) => {
|
|
21
|
-
observer.mutate(args[0], args[1]).catch(noop);
|
|
22
|
-
};
|
|
23
|
-
});
|
|
24
|
-
const resultFromInitialOptionsSignal = computed(() => {
|
|
25
|
-
const observer = observerSignal();
|
|
26
|
-
return observer.getCurrentResult();
|
|
27
|
-
});
|
|
28
|
-
const resultFromSubscriberSignal = signal(null);
|
|
29
|
-
effect(
|
|
30
|
-
() => {
|
|
31
|
-
const observer = observerSignal();
|
|
32
|
-
const observerOptions = optionsSignal();
|
|
33
|
-
untracked(() => {
|
|
34
|
-
observer.setOptions(observerOptions);
|
|
35
|
-
});
|
|
36
|
-
},
|
|
37
|
-
{
|
|
38
|
-
injector
|
|
39
|
-
}
|
|
40
|
-
);
|
|
41
|
-
effect(
|
|
42
|
-
(onCleanup) => {
|
|
43
|
-
const observer = observerSignal();
|
|
44
|
-
let pendingTaskRef = null;
|
|
45
|
-
untracked(() => {
|
|
46
|
-
const unsubscribe = ngZone.runOutsideAngular(
|
|
47
|
-
() => observer.subscribe(
|
|
48
|
-
notifyManager.batchCalls((state) => {
|
|
49
|
-
ngZone.run(() => {
|
|
50
|
-
if (state.isPending && !pendingTaskRef) {
|
|
51
|
-
pendingTaskRef = pendingTasks.add();
|
|
52
|
-
}
|
|
53
|
-
if (!state.isPending && pendingTaskRef) {
|
|
54
|
-
pendingTaskRef();
|
|
55
|
-
pendingTaskRef = null;
|
|
56
|
-
}
|
|
57
|
-
if (state.isError && shouldThrowError(observer.options.throwOnError, [state.error])) {
|
|
58
|
-
ngZone.onError.emit(state.error);
|
|
59
|
-
throw state.error;
|
|
60
|
-
}
|
|
61
|
-
resultFromSubscriberSignal.set(state);
|
|
62
|
-
});
|
|
63
|
-
})
|
|
64
|
-
)
|
|
65
|
-
);
|
|
66
|
-
onCleanup(() => {
|
|
67
|
-
if (pendingTaskRef) {
|
|
68
|
-
pendingTaskRef();
|
|
69
|
-
pendingTaskRef = null;
|
|
70
|
-
}
|
|
71
|
-
unsubscribe();
|
|
72
|
-
});
|
|
73
|
-
});
|
|
74
|
-
},
|
|
75
|
-
{
|
|
76
|
-
injector
|
|
77
|
-
}
|
|
78
|
-
);
|
|
79
|
-
const resultSignal = computed(() => {
|
|
80
|
-
const resultFromSubscriber = resultFromSubscriberSignal();
|
|
81
|
-
const resultFromInitialOptions = resultFromInitialOptionsSignal();
|
|
82
|
-
const result = resultFromSubscriber ?? resultFromInitialOptions;
|
|
83
|
-
return {
|
|
84
|
-
...result,
|
|
85
|
-
mutate: mutateFnSignal(),
|
|
86
|
-
mutateAsync: result.mutate
|
|
87
|
-
};
|
|
88
|
-
});
|
|
89
|
-
return signalProxy(resultSignal);
|
|
90
|
-
}
|
|
91
|
-
export {
|
|
92
|
-
injectMutation
|
|
93
|
-
};
|
|
94
|
-
//# sourceMappingURL=inject-mutation.mjs.map
|
package/inject-mutation.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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;"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from '../inject-queries.js';
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";"}
|
package/inject-queries.mjs
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import { QueryClient, QueriesObserver, notifyManager } from "@tanstack/query-core";
|
|
2
|
-
import { assertInInjectionContext, runInInjectionContext, inject, Injector, DestroyRef, NgZone, computed, effect, signal, untracked } from "@angular/core";
|
|
3
|
-
import { signalProxy } from "./signal-proxy.mjs";
|
|
4
|
-
import { injectIsRestoring } from "./inject-is-restoring.mjs";
|
|
5
|
-
function injectQueries(optionsFn, injector) {
|
|
6
|
-
!injector && assertInInjectionContext(injectQueries);
|
|
7
|
-
return runInInjectionContext(injector ?? inject(Injector), () => {
|
|
8
|
-
const destroyRef = inject(DestroyRef);
|
|
9
|
-
const ngZone = inject(NgZone);
|
|
10
|
-
const queryClient = inject(QueryClient);
|
|
11
|
-
const isRestoring = injectIsRestoring();
|
|
12
|
-
const optionsSignal = computed(() => {
|
|
13
|
-
return optionsFn();
|
|
14
|
-
});
|
|
15
|
-
const defaultedQueries = computed(() => {
|
|
16
|
-
return optionsSignal().queries.map((opts) => {
|
|
17
|
-
const defaultedOptions = queryClient.defaultQueryOptions(
|
|
18
|
-
opts
|
|
19
|
-
);
|
|
20
|
-
defaultedOptions._optimisticResults = isRestoring() ? "isRestoring" : "optimistic";
|
|
21
|
-
return defaultedOptions;
|
|
22
|
-
});
|
|
23
|
-
});
|
|
24
|
-
const observerSignal = (() => {
|
|
25
|
-
let instance = null;
|
|
26
|
-
return computed(() => {
|
|
27
|
-
return instance || (instance = new QueriesObserver(
|
|
28
|
-
queryClient,
|
|
29
|
-
defaultedQueries(),
|
|
30
|
-
optionsSignal()
|
|
31
|
-
));
|
|
32
|
-
});
|
|
33
|
-
})();
|
|
34
|
-
const optimisticResultSignal = computed(
|
|
35
|
-
() => observerSignal().getOptimisticResult(
|
|
36
|
-
defaultedQueries(),
|
|
37
|
-
optionsSignal().combine
|
|
38
|
-
)
|
|
39
|
-
);
|
|
40
|
-
effect(() => {
|
|
41
|
-
observerSignal().setQueries(
|
|
42
|
-
defaultedQueries(),
|
|
43
|
-
optionsSignal()
|
|
44
|
-
);
|
|
45
|
-
});
|
|
46
|
-
const optimisticCombinedResultSignal = computed(() => {
|
|
47
|
-
const [_optimisticResult, getCombinedResult, trackResult] = optimisticResultSignal();
|
|
48
|
-
return getCombinedResult(trackResult());
|
|
49
|
-
});
|
|
50
|
-
const resultFromSubscriberSignal = signal(null);
|
|
51
|
-
effect(() => {
|
|
52
|
-
const observer = observerSignal();
|
|
53
|
-
const [_optimisticResult, getCombinedResult] = optimisticResultSignal();
|
|
54
|
-
untracked(() => {
|
|
55
|
-
const unsubscribe = isRestoring() ? () => void 0 : ngZone.runOutsideAngular(
|
|
56
|
-
() => observer.subscribe(
|
|
57
|
-
notifyManager.batchCalls((state) => {
|
|
58
|
-
resultFromSubscriberSignal.set(getCombinedResult(state));
|
|
59
|
-
})
|
|
60
|
-
)
|
|
61
|
-
);
|
|
62
|
-
destroyRef.onDestroy(unsubscribe);
|
|
63
|
-
});
|
|
64
|
-
});
|
|
65
|
-
const resultSignal = computed(() => {
|
|
66
|
-
const subscriberResult = resultFromSubscriberSignal();
|
|
67
|
-
const optimisticResult = optimisticCombinedResultSignal();
|
|
68
|
-
return subscriberResult ?? optimisticResult;
|
|
69
|
-
});
|
|
70
|
-
return computed(() => {
|
|
71
|
-
const result = resultSignal();
|
|
72
|
-
const { combine } = optionsSignal();
|
|
73
|
-
return combine ? result : result.map(
|
|
74
|
-
(query) => signalProxy(signal(query))
|
|
75
|
-
);
|
|
76
|
-
});
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
export {
|
|
80
|
-
injectQueries
|
|
81
|
-
};
|
|
82
|
-
//# sourceMappingURL=inject-queries.mjs.map
|
package/inject-queries.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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;"}
|
package/inject-query-client.mjs
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { inject, Injector } from "@angular/core";
|
|
2
|
-
import { QueryClient } from "@tanstack/query-core";
|
|
3
|
-
function injectQueryClient(injectOptions = {}) {
|
|
4
|
-
return (injectOptions.injector ?? inject(Injector)).get(QueryClient);
|
|
5
|
-
}
|
|
6
|
-
export {
|
|
7
|
-
injectQueryClient
|
|
8
|
-
};
|
|
9
|
-
//# sourceMappingURL=inject-query-client.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"inject-query-client.mjs","sources":["../src/inject-query-client.ts"],"sourcesContent":["import { Injector, inject } from '@angular/core'\nimport { QueryClient } from '@tanstack/query-core'\nimport type { InjectOptions } from '@angular/core'\n\n/**\n * Injects a `QueryClient` instance and allows passing a custom injector.\n * @param injectOptions - Type of the options argument to inject and optionally a custom injector.\n * @returns The `QueryClient` instance.\n * @deprecated Use `inject(QueryClient)` instead.\n * If you need to get a `QueryClient` from a custom injector, use `injector.get(QueryClient)`.\n *\n *\n * **Example**\n * ```ts\n * const queryClient = injectQueryClient();\n * ```\n */\nexport function injectQueryClient(\n injectOptions: InjectOptions & { injector?: Injector } = {},\n) {\n return (injectOptions.injector ?? inject(Injector)).get(QueryClient)\n}\n"],"names":[],"mappings":";;AAiBO,SAAS,kBACd,gBAAyD,IACzD;AACA,UAAQ,cAAc,YAAY,OAAO,QAAQ,GAAG,IAAI,WAAW;AACrE;"}
|
package/inject-query.mjs
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import { QueryObserver } from "@tanstack/query-core";
|
|
2
|
-
import { assertInInjectionContext, runInInjectionContext, inject, Injector } from "@angular/core";
|
|
3
|
-
import { createBaseQuery } from "./create-base-query.mjs";
|
|
4
|
-
function injectQuery(injectQueryFn, options) {
|
|
5
|
-
!(options == null ? void 0 : options.injector) && assertInInjectionContext(injectQuery);
|
|
6
|
-
return runInInjectionContext(
|
|
7
|
-
(options == null ? void 0 : options.injector) ?? inject(Injector),
|
|
8
|
-
() => createBaseQuery(injectQueryFn, QueryObserver)
|
|
9
|
-
);
|
|
10
|
-
}
|
|
11
|
-
export {
|
|
12
|
-
injectQuery
|
|
13
|
-
};
|
|
14
|
-
//# sourceMappingURL=inject-query.mjs.map
|
package/inject-query.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"inject-query.mjs","sources":["../src/inject-query.ts"],"sourcesContent":["import { QueryObserver } from '@tanstack/query-core'\nimport {\n Injector,\n assertInInjectionContext,\n inject,\n runInInjectionContext,\n} from '@angular/core'\nimport { createBaseQuery } from './create-base-query'\nimport type { DefaultError, QueryKey } from '@tanstack/query-core'\nimport type {\n CreateQueryOptions,\n CreateQueryResult,\n DefinedCreateQueryResult,\n} from './types'\nimport type {\n DefinedInitialDataOptions,\n UndefinedInitialDataOptions,\n} from './query-options'\n\nexport interface InjectQueryOptions {\n /**\n * The `Injector` in which to create the query.\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 * This overload is selected when `initialData` is set on the options returned by `injectQueryFn`, so the\n * resulting `data` signal is never `undefined` (unless a `select` changes `TData` to include `undefined`).\n *\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like\n * `queryClient.fetchQuery`.\n * @param injectQueryFn - A function returning the {@link DefinedInitialDataOptions} to use — everything you\n * can pass to `injectQuery`, with `initialData` set. Similar to `computed` from Angular, this function runs\n * in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.\n * @param options - Additional configuration\n * @returns The query result, typed so that `data` is never `undefined` (unless a `select` changes `TData` to\n * include `undefined`).\n *\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <!-- `postsQuery.data()` is `Post[]`, never `undefined`, thanks to `initialData` — even if a\n * refetch fails, so the list stays visible alongside the error. -->\n * @if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * }\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * `,\n * })\n * export class Posts {\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * initialData: [],\n * }))\n * }\n * ```\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n injectQueryFn: () => DefinedInitialDataOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >,\n options?: InjectQueryOptions,\n): DefinedCreateQueryResult<TData, TError>\n\n/**\n * Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.\n *\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like\n * `queryClient.fetchQuery`.\n * @param injectQueryFn - A function returning the {@link UndefinedInitialDataOptions} to use — everything\n * you can pass to `injectQuery`. Similar to `computed` from Angular, this function runs in the reactive\n * context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.\n * @param options - Additional configuration\n * @returns The query result. `status()` is `'pending'` if there is no cached data to display, `'error'` if\n * the last fetch attempt failed, or `'success'` if the query has data to display. `isPending`/`isSuccess`/\n * `isError` are type-guard methods for convenience.\n *\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * @if (postsQuery.isPending()) {\n * Loading...\n * } @else if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * } @else {\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * }))\n * }\n * ```\n *\n * @example\n * Similar to `computed` from Angular, the function passed to `injectQuery` runs in the reactive context. In\n * the example below, the query is automatically enabled and executed when the filter signal changes to a\n * truthy value. When the filter signal changes back to a falsy value, the query is disabled.\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <input [ngModel]=\"filter()\" (ngModelChange)=\"filter.set($event)\" />\n * @if (postsQuery.isPending()) {\n * Loading...\n * } @else if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * } @else {\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly filter = signal('')\n *\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts', this.filter()],\n * queryFn: () => fetchPosts(this.filter()),\n * // Signals can be combined with expressions\n * enabled: !!this.filter(),\n * }))\n * }\n * ```\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n injectQueryFn: () => UndefinedInitialDataOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >,\n options?: InjectQueryOptions,\n): CreateQueryResult<TData, TError>\n\n/**\n * This overload accepts the general {@link CreateQueryOptions} shape rather than the `initialData`-aware\n * overloads above, so whether `data` is defined can't be inferred from the call site — useful when wrapping\n * `injectQuery` in your own helper function that forwards caller-provided options.\n *\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @param injectQueryFn - A function that returns query options. Similar to `computed` from Angular, this\n * function runs in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive\n * the query.\n * @param options - Additional configuration\n * @returns The query result.\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n injectQueryFn: () => CreateQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >,\n options?: InjectQueryOptions,\n): CreateQueryResult<TData, TError>\n\nexport function injectQuery(\n injectQueryFn: () => CreateQueryOptions,\n options?: InjectQueryOptions,\n) {\n !options?.injector && assertInInjectionContext(injectQuery)\n return runInInjectionContext(options?.injector ?? inject(Injector), () =>\n createBaseQuery(injectQueryFn, QueryObserver),\n ) as unknown as CreateQueryResult\n}\n"],"names":[],"mappings":";;;AAuMO,SAAS,YACd,eACA,SACA;AACA,IAAC,mCAAS,aAAY,yBAAyB,WAAW;AAC1D,SAAO;AAAA,KAAsB,mCAAS,aAAY,OAAO,QAAQ;AAAA,IAAG,MAClE,gBAAgB,eAAe,aAAa;AAAA,EAAA;AAEhD;"}
|
package/mutation-options.mjs
DELETED
package/mutation-options.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mutation-options.mjs","sources":["../src/mutation-options.ts"],"sourcesContent":["import type { DefaultError, WithRequired } from '@tanstack/query-core'\nimport type { CreateMutationOptions } from './types'\n\n/**\n * You can generally pass everything to `mutationOptions` that you can also pass to `injectMutation`. A\n * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with\n * `injectMutationState`.\n *\n * @see {@link injectMutation} to run the mutation these options describe.\n * @param options - The mutation options to use, identical to what you'd pass to `injectMutation`, with a\n * required `mutationKey`.\n * @returns The same options object, unchanged.\n *\n * @example\n * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global \"saving…\" indicator:\n * ```angular-ts\n * import { mutationOptions, injectMutationState } from '@tanstack/angular-query-experimental'\n *\n * const createPostOptions = mutationOptions({\n * mutationKey: ['posts', 'create'],\n * mutationFn: createPost,\n * })\n *\n * @Component({\n * selector: 'saving-indicator',\n * template: `\n * @if (isCreatingPost()) {\n * <span>Saving…</span>\n * }\n * `,\n * })\n * export class SavingIndicator {\n * readonly #pendingCreates = injectMutationState(() => ({\n * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },\n * }))\n * readonly isCreatingPost = computed(() => this.#pendingCreates().length > 0)\n * }\n * ```\n */\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: WithRequired<\n CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n >,\n): WithRequired<\n CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n>\n/**\n * You can generally pass everything to `mutationOptions` that you can also pass to `injectMutation`. No\n * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a\n * `mutationKey` filter later (e.g. with `injectMutationState`); it can still be observed through other\n * filters, such as `status`.\n *\n * @see {@link injectMutation} to run the mutation these options describe.\n * @param options - The mutation options to use, identical to what you'd pass to `injectMutation`, without a\n * `mutationKey`.\n * @returns The same options object, unchanged.\n * @remarks See the other overload's example for looking a mutation up via `injectMutationState`.\n *\n * @example\n * Sharing options across services, so `QueriesService` stays the single place a mutation is defined:\n * ```angular-ts\n * import { mutationOptions, injectMutation } from '@tanstack/angular-query-experimental'\n *\n * @Injectable({ providedIn: 'root' })\n * export class QueriesService {\n * readonly #queryClient = inject(QueryClient)\n *\n * updatePost(id: number) {\n * return mutationOptions({\n * mutationFn: (post: Partial<Post>) => putPost(id, post),\n * onSuccess: (newPost) => this.#queryClient.setQueryData(['posts', id], newPost),\n * })\n * }\n * }\n *\n * @Component({\n * selector: 'post',\n * template: `<button (click)=\"save()\">Save</button>`,\n * })\n * export class Post {\n * readonly queries = inject(QueriesService)\n * readonly id = signal(0)\n * readonly updatePostMutation = injectMutation(() => this.queries.updatePost(this.id()))\n *\n * save() {\n * this.updatePostMutation.mutate({ title: 'New Title' })\n * }\n * }\n * ```\n */\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: Omit<\n CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n >,\n): Omit<\n CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n>\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n): CreateMutationOptions<TData, TError, TVariables, TOnMutateResult> {\n return options\n}\n"],"names":[],"mappings":"AA+GO,SAAS,gBAMd,SACmE;AACnE,SAAO;AACT;"}
|
package/pending-tasks-compat.mjs
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import * as ng from "@angular/core";
|
|
2
|
-
import { InjectionToken, inject } from "@angular/core";
|
|
3
|
-
import { noop } from "@tanstack/query-core";
|
|
4
|
-
const PENDING_TASKS = new InjectionToken(
|
|
5
|
-
"PENDING_TASKS",
|
|
6
|
-
{
|
|
7
|
-
factory: () => {
|
|
8
|
-
const token = Reflect.get(ng, "PendingTasks");
|
|
9
|
-
const svc = token ? inject(token, { optional: true }) : null;
|
|
10
|
-
return {
|
|
11
|
-
add: svc ? () => svc.add() : () => noop
|
|
12
|
-
};
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
);
|
|
16
|
-
export {
|
|
17
|
-
PENDING_TASKS
|
|
18
|
-
};
|
|
19
|
-
//# sourceMappingURL=pending-tasks-compat.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pending-tasks-compat.mjs","sources":["../src/pending-tasks-compat.ts"],"sourcesContent":["import { InjectionToken, inject } from '@angular/core'\nimport * as ng from '@angular/core'\nimport { noop } from '@tanstack/query-core'\n\ntype PendingTasksCompat = { add: () => PendingTaskRef }\n\nexport type PendingTaskRef = () => void\n\nexport const PENDING_TASKS = new InjectionToken<PendingTasksCompat>(\n 'PENDING_TASKS',\n {\n factory: (): PendingTasksCompat => {\n // Access via Reflect so bundlers stay quiet when the token is absent (Angular < 19).\n const token = Reflect.get(ng, 'PendingTasks') as unknown as\n | Parameters<typeof inject>[0]\n | undefined\n\n const svc: PendingTasksCompat | null = token\n ? (inject(token, { optional: true }) as PendingTasksCompat | null)\n : null\n\n // Without PendingTasks we fall back to a stable no-op shim.\n return {\n add: svc ? () => svc.add() : () => noop,\n }\n },\n },\n)\n"],"names":[],"mappings":";;;AAQO,MAAM,gBAAgB,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,IACE,SAAS,MAA0B;AAEjC,YAAM,QAAQ,QAAQ,IAAI,IAAI,cAAc;AAI5C,YAAM,MAAiC,QAClC,OAAO,OAAO,EAAE,UAAU,KAAA,CAAM,IACjC;AAGJ,aAAO;AAAA,QACL,KAAK,MAAM,MAAM,IAAI,IAAA,IAAQ,MAAM;AAAA,MAAA;AAAA,IAEvC;AAAA,EAAA;AAEJ;"}
|
package/providers.mjs
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import { InjectionToken, inject, DestroyRef } from "@angular/core";
|
|
2
|
-
import { QueryClient } from "@tanstack/query-core";
|
|
3
|
-
function provideQueryClient(queryClient) {
|
|
4
|
-
return {
|
|
5
|
-
provide: QueryClient,
|
|
6
|
-
useFactory: () => {
|
|
7
|
-
const client = queryClient instanceof InjectionToken ? inject(queryClient) : queryClient;
|
|
8
|
-
inject(DestroyRef).onDestroy(() => client.unmount());
|
|
9
|
-
client.mount();
|
|
10
|
-
return client;
|
|
11
|
-
}
|
|
12
|
-
};
|
|
13
|
-
}
|
|
14
|
-
function provideTanStackQuery(queryClient, ...features) {
|
|
15
|
-
return [
|
|
16
|
-
provideQueryClient(queryClient),
|
|
17
|
-
features.map((feature) => feature.ɵproviders)
|
|
18
|
-
];
|
|
19
|
-
}
|
|
20
|
-
function provideAngularQuery(queryClient) {
|
|
21
|
-
return provideTanStackQuery(queryClient);
|
|
22
|
-
}
|
|
23
|
-
function queryFeature(kind, providers) {
|
|
24
|
-
return { ɵkind: kind, ɵproviders: providers };
|
|
25
|
-
}
|
|
26
|
-
export {
|
|
27
|
-
provideAngularQuery,
|
|
28
|
-
provideQueryClient,
|
|
29
|
-
provideTanStackQuery,
|
|
30
|
-
queryFeature
|
|
31
|
-
};
|
|
32
|
-
//# sourceMappingURL=providers.mjs.map
|
package/providers.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"providers.mjs","sources":["../src/providers.ts"],"sourcesContent":["import { DestroyRef, InjectionToken, inject } from '@angular/core'\nimport { QueryClient } from '@tanstack/query-core'\nimport type { Provider } from '@angular/core'\n\n/**\n * Usually {@link provideTanStackQuery} is used once to set up TanStack Query and the\n * [`QueryClient`](https://tanstack.com/query/latest/docs/reference/QueryClient) for the entire application —\n * it calls `provideQueryClient` internally. Use `provideQueryClient` directly to provide a different\n * `QueryClient` instance for part of the application, or for unit testing.\n * @param queryClient - A `QueryClient` instance, or an `InjectionToken` which provides a `QueryClient`.\n * @returns A provider object that can be used to provide the `QueryClient` instance.\n *\n * @example\n * Providing a test-only `QueryClient` in a component test, without wiring up `provideTanStackQuery`'s other\n * defaults:\n * ```ts\n * TestBed.configureTestingModule({\n * providers: [provideQueryClient(new QueryClient())],\n * })\n * ```\n */\nexport function provideQueryClient(\n queryClient: QueryClient | InjectionToken<QueryClient>,\n): Provider {\n return {\n provide: QueryClient,\n useFactory: () => {\n const client =\n queryClient instanceof InjectionToken\n ? inject(queryClient)\n : queryClient\n // Unmount the query client on injector destroy\n inject(DestroyRef).onDestroy(() => client.unmount())\n client.mount()\n return client\n },\n }\n}\n\n/**\n * Sets up providers necessary to enable TanStack Query functionality for Angular applications. Allows\n * configuring a `QueryClient` and optional features such as developer tools.\n *\n * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start\n * @see {@link withDevtools}\n * @param queryClient - A `QueryClient` instance, or an `InjectionToken` which provides a `QueryClient`.\n * @param features - Optional features to configure additional Query functionality.\n * @returns A set of providers to set up TanStack Query.\n *\n * @example\n * ```ts\n * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query-experimental'\n *\n * bootstrapApplication(AppComponent, {\n * providers: [provideTanStackQuery(new QueryClient())],\n * })\n * ```\n *\n * @example\n * The same, in an `NgModule`-based application:\n * ```ts\n * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query-experimental'\n *\n * @NgModule({\n * declarations: [AppComponent],\n * imports: [BrowserModule],\n * providers: [provideTanStackQuery(new QueryClient())],\n * bootstrap: [AppComponent],\n * })\n * export class AppModule {}\n * ```\n *\n * @example\n * Enabling optional developer tools by adding `withDevtools` — by default, the tools are then loaded when\n * your app is in development mode:\n * ```ts\n * import {\n * provideTanStackQuery,\n * withDevtools,\n * QueryClient,\n * } from '@tanstack/angular-query-experimental'\n *\n * bootstrapApplication(AppComponent, {\n * providers: [provideTanStackQuery(new QueryClient(), withDevtools())],\n * })\n * ```\n *\n * @example\n * Using an `InjectionToken` for the `QueryClient` — an advanced optimization that lets TanStack Query be\n * absent from the main application bundle, useful for including it on lazy-loaded routes only while still\n * sharing a `QueryClient`. This is a small optimization; for most applications it's preferable to provide\n * the `QueryClient` in the main application config, as in the examples above:\n * ```ts\n * export const MY_QUERY_CLIENT = new InjectionToken('', {\n * factory: () => new QueryClient(),\n * })\n *\n * // In a lazy loaded route or lazy loaded component's providers array:\n * providers: [provideTanStackQuery(MY_QUERY_CLIENT)]\n * ```\n */\nexport function provideTanStackQuery(\n queryClient: QueryClient | InjectionToken<QueryClient>,\n ...features: Array<QueryFeatures>\n): Array<Provider> {\n return [\n provideQueryClient(queryClient),\n features.map((feature) => feature.ɵproviders),\n ]\n}\n\n/**\n * Sets up providers necessary to enable TanStack Query functionality for Angular applications.\n *\n * Allows configuring a `QueryClient`.\n * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start\n * @param queryClient - A `QueryClient` instance.\n * @returns A set of providers to set up TanStack Query.\n * @deprecated Use `provideTanStackQuery` instead.\n */\nexport function provideAngularQuery(queryClient: QueryClient): Array<Provider> {\n return provideTanStackQuery(queryClient)\n}\n\nconst queryFeatures = ['Devtools', 'PersistQueryClient'] as const\n\ntype QueryFeatureKind = (typeof queryFeatures)[number]\n\n/**\n * Helper type to represent a Query feature.\n */\nexport interface QueryFeature<TFeatureKind extends QueryFeatureKind> {\n ɵkind: TFeatureKind\n ɵproviders: Array<Provider>\n}\n\n/**\n * Helper function to create an object that represents a Query feature.\n * @param kind - The kind of feature, e.g. `'Devtools'`.\n * @param providers - The Angular providers this feature contributes to `provideTanStackQuery`.\n * @returns A Query feature.\n */\nexport function queryFeature<TFeatureKind extends QueryFeatureKind>(\n kind: TFeatureKind,\n providers: Array<Provider>,\n): QueryFeature<TFeatureKind> {\n return { ɵkind: kind, ɵproviders: providers }\n}\n\n/**\n * A type alias that represents a feature which enables developer tools.\n * The type is used to describe the return value of the `withDevtools` function.\n * @see {@link withDevtools}\n */\nexport type DevtoolsFeature = QueryFeature<'Devtools'>\n\n/**\n * A type alias that represents a feature which enables persistence.\n * The type is used to describe the return value of the `withPersistQueryClient` function.\n */\nexport type PersistQueryClientFeature = QueryFeature<'PersistQueryClient'>\n\n/**\n * A type alias that represents all Query features available for use with `provideTanStackQuery`.\n * Features can be enabled by adding special functions to the `provideTanStackQuery` call.\n * See documentation for each symbol to find corresponding function name. See also `provideTanStackQuery`\n * documentation on how to use those functions.\n * @see {@link provideTanStackQuery}\n */\nexport type QueryFeatures = DevtoolsFeature | PersistQueryClientFeature\n"],"names":[],"mappings":";;AAqBO,SAAS,mBACd,aACU;AACV,SAAO;AAAA,IACL,SAAS;AAAA,IACT,YAAY,MAAM;AAChB,YAAM,SACJ,uBAAuB,iBACnB,OAAO,WAAW,IAClB;AAEN,aAAO,UAAU,EAAE,UAAU,MAAM,OAAO,SAAS;AACnD,aAAO,MAAA;AACP,aAAO;AAAA,IACT;AAAA,EAAA;AAEJ;AAgEO,SAAS,qBACd,gBACG,UACc;AACjB,SAAO;AAAA,IACL,mBAAmB,WAAW;AAAA,IAC9B,SAAS,IAAI,CAAC,YAAY,QAAQ,UAAU;AAAA,EAAA;AAEhD;AAWO,SAAS,oBAAoB,aAA2C;AAC7E,SAAO,qBAAqB,WAAW;AACzC;AAoBO,SAAS,aACd,MACA,WAC4B;AAC5B,SAAO,EAAE,OAAO,MAAM,YAAY,UAAA;AACpC;"}
|
package/query-options.mjs
DELETED
package/query-options.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"query-options.mjs","sources":["../src/query-options.ts"],"sourcesContent":["import type {\n DefaultError,\n InitialDataFunction,\n NonUndefinedGuard,\n OmitKeyof,\n QueryFunction,\n QueryKey,\n QueryKeyWithDataTag,\n SkipToken,\n} from '@tanstack/query-core'\nimport type { CreateQueryOptions } from './types'\n\n/**\n * The options accepted by the `queryOptions` overload selected when no `initialData` is set — `data` may be\n * `undefined` while the query is `pending`.\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type UndefinedInitialDataOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {\n /**\n * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been\n * created or cached yet). If set to a function, the function will be called **once** during the shared/root\n * query initialization, and be expected to synchronously return the initial data. Initial data is\n * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the\n * cache.\n */\n initialData?:\n | undefined\n | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>\n | NonUndefinedGuard<TQueryFnData>\n}\n\n/**\n * The options accepted by the `queryOptions` overload selected when no `initialData` is set and `queryFn` is\n * not `skipToken` — same as {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type UnusedSkipTokenOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'queryFn'\n> & {\n /**\n * `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If\n * you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a\n * fetch that fails with \"Missing queryFn\" unless `enabled` is `false` or a default query function has been\n * defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.\n */\n queryFn?: Exclude<\n CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],\n SkipToken | undefined\n >\n}\n\n/**\n * The options accepted by the `queryOptions` overload selected when `initialData` is set — `data` is never\n * `undefined` (unless a `select` changes `TData` to include `undefined`).\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type DefinedInitialDataOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = Omit<\n CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'queryFn'\n> & {\n /**\n * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been\n * created or cached yet). If set to a function, the function will be called **once** during the shared/root\n * query initialization, and be expected to synchronously return the initial data. Initial data is\n * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the\n * cache.\n */\n initialData:\n | NonUndefinedGuard<TQueryFnData>\n | (() => NonUndefinedGuard<TQueryFnData>)\n /**\n * Optional here, but omitting it is only safe when no fetch will be attempted — for example with\n * `enabled: false`, or when a default query function has been defined. Otherwise, an enabled query with no\n * `queryFn` still tries to fetch and fails with a \"Missing queryFn\" error; `initialData` does not prevent this.\n */\n queryFn?: QueryFunction<TQueryFnData, TQueryKey>\n}\n\n/**\n * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options\n * can be shared across functions and imperative APIs such as `queryClient.fetchQuery`. `options.queryKey` is\n * required and is the query key to generate options for.\n *\n * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless\n * a `select` changes `TData` to include `undefined`).\n *\n * @see {@link injectQuery} to run a query with these options.\n * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.\n * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `injectQuery`,\n * with `initialData` set.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n *\n * @example\n * ```angular-ts\n * import { queryOptions, injectQuery } from '@tanstack/angular-query-experimental'\n *\n * export const postsOptions = queryOptions({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * initialData: [],\n * })\n *\n * @Component({\n * selector: 'posts',\n * template: `\n * <!-- `postsQuery.data()` is never `undefined`, thanks to `initialData` — even if a refetch\n * fails, so the list stays visible alongside the error. -->\n * @if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * }\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * `,\n * })\n * export class Posts {\n * readonly postsQuery = injectQuery(() => postsOptions)\n * }\n * ```\n */\nexport function queryOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,\n): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &\n QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>\n\n/**\n * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options\n * can be shared across functions and imperative APIs such as `queryClient.fetchQuery`. `options.queryKey` is\n * required and is the query key to generate options for.\n *\n * @see {@link injectQuery} to run a query with these options.\n * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.\n * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `injectQuery`.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n *\n * @example\n * A parameterized factory, so the same options object can be reused per `id`:\n * ```angular-ts\n * import { queryOptions, injectQuery } from '@tanstack/angular-query-experimental'\n *\n * export const postOptions = (id: string) =>\n * queryOptions({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })\n *\n * @Component({\n * selector: 'post',\n * template: `\n * @if (postQuery.isPending()) {\n * Loading...\n * } @else if (postQuery.isError()) {\n * <span>Error: {{ postQuery.error()?.message }}</span>\n * } @else {\n * <h1>{{ postQuery.data().title }}</h1>\n * }\n * `,\n * })\n * export class Post {\n * readonly id = signal('1')\n * readonly postQuery = injectQuery(() => postOptions(this.id()))\n * }\n * ```\n */\nexport function queryOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>,\n): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> &\n QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>\n\n/**\n * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options\n * can be shared across functions and imperative APIs such as `queryClient.fetchQuery`. `options.queryKey` is\n * required and is the query key to generate options for.\n *\n * @see {@link injectQuery} to run a query with these options.\n * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.\n * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `injectQuery`.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.\n *\n * @example\n * A parameterized factory, so the same options object can be reused per `id`:\n * ```angular-ts\n * import { queryOptions, injectQuery } from '@tanstack/angular-query-experimental'\n *\n * export const postOptions = (id: string) =>\n * queryOptions({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })\n *\n * @Component({\n * selector: 'post',\n * template: `\n * @if (postQuery.isPending()) {\n * Loading...\n * } @else if (postQuery.isError()) {\n * <span>Error: {{ postQuery.error()?.message }}</span>\n * } @else {\n * <h1>{{ postQuery.data().title }}</h1>\n * }\n * `,\n * })\n * export class Post {\n * readonly id = signal('1')\n * readonly postQuery = injectQuery(() => postOptions(this.id()))\n * }\n * ```\n *\n * @example\n * A factory that disables the query, type safe, until `postId` is set:\n * ```angular-ts\n * import { queryOptions, skipToken, injectQuery } from '@tanstack/angular-query-experimental'\n *\n * export const postOptions = (postId: number | undefined) =>\n * queryOptions({\n * queryKey: ['post', postId],\n * queryFn: postId != null ? () => fetchPost(postId) : skipToken,\n * })\n *\n * @Component({\n * selector: 'post',\n * template: `\n * @if (postId() == null) {\n * Select a post\n * } @else if (postQuery.isPending()) {\n * Loading...\n * } @else if (postQuery.isError()) {\n * <span>Error: {{ postQuery.error()?.message }}</span>\n * } @else {\n * <h1>{{ postQuery.data().title }}</h1>\n * }\n * `,\n * })\n * export class Post {\n * readonly postId = signal<number | undefined>(undefined)\n * readonly postQuery = injectQuery(() => postOptions(this.postId()))\n * }\n * ```\n */\nexport function queryOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,\n): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &\n QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>\n\nexport function queryOptions(options: unknown) {\n return options\n}\n"],"names":[],"mappings":"AAkSO,SAAS,aAAa,SAAkB;AAC7C,SAAO;AACT;"}
|
package/signal-proxy.d.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { Signal } from '@angular/core';
|
|
2
|
-
export type MapToSignals<T> = {
|
|
3
|
-
[K in keyof T]: T[K] extends Function ? T[K] : Signal<T[K]>;
|
|
4
|
-
};
|
|
5
|
-
/**
|
|
6
|
-
* Exposes fields of an object passed via an Angular `Signal` as `Computed` signals.
|
|
7
|
-
* Functions on the object are passed through as-is.
|
|
8
|
-
* @param inputSignal - `Signal` that must return an object.
|
|
9
|
-
* @returns A proxy object with the same fields as the input object, but with each field wrapped in a `Computed` signal.
|
|
10
|
-
*/
|
|
11
|
-
export declare function signalProxy<TInput extends Record<string | symbol, any>>(inputSignal: Signal<TInput>): MapToSignals<TInput>;
|