@analogjs/router 3.0.0-beta.5 → 3.0.0-beta.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/fesm2022/analogjs-router-content.mjs +2 -2
  2. package/fesm2022/analogjs-router-content.mjs.map +1 -1
  3. package/fesm2022/analogjs-router-server-actions.mjs +18 -6
  4. package/fesm2022/analogjs-router-server-actions.mjs.map +1 -1
  5. package/fesm2022/analogjs-router-server.mjs +739 -39
  6. package/fesm2022/analogjs-router-server.mjs.map +1 -1
  7. package/fesm2022/analogjs-router-tanstack-query-server.mjs +24 -31
  8. package/fesm2022/analogjs-router-tanstack-query-server.mjs.map +1 -1
  9. package/fesm2022/analogjs-router-tanstack-query.mjs +14 -40
  10. package/fesm2022/analogjs-router-tanstack-query.mjs.map +1 -1
  11. package/fesm2022/analogjs-router.mjs +75 -21
  12. package/fesm2022/analogjs-router.mjs.map +1 -1
  13. package/fesm2022/debug.page.mjs +3 -3
  14. package/fesm2022/route-files.mjs +44 -16
  15. package/fesm2022/route-files.mjs.map +1 -1
  16. package/package.json +7 -6
  17. package/types/content/src/lib/markdown-helpers.d.ts +2 -1
  18. package/types/content/src/lib/routes.d.ts +2 -1
  19. package/types/server/actions/src/parse-request-data.d.ts +3 -0
  20. package/types/server/src/index.d.ts +2 -0
  21. package/types/server/src/node-handler.d.ts +8 -0
  22. package/types/server/src/request-handler.d.ts +30 -0
  23. package/types/server/src/server-fn/dispatch.d.ts +4 -2
  24. package/types/server/src/server-fn/event-handler.d.ts +3 -1
  25. package/types/server/src/server-fn/node-context.d.ts +14 -4
  26. package/types/server/src/server-fn/server-fn.d.ts +4 -4
  27. package/types/server/src/server-manifest.d.ts +26 -0
  28. package/types/server/src/utils/stream-request.d.ts +2 -0
  29. package/types/src/index.d.ts +1 -1
  30. package/types/src/lib/models.d.ts +14 -9
  31. package/types/src/lib/request-context.d.ts +5 -0
  32. package/types/src/lib/route-config.d.ts +1 -1
  33. package/types/src/lib/server-fn/inject-server-fn.d.ts +4 -4
  34. package/types/src/lib/server-fn/types.d.ts +1 -0
  35. package/types/src/lib/to-route.d.ts +53 -14
  36. package/types/tanstack-query/server/src/define-page-load-queries.d.ts +13 -10
  37. package/types/tanstack-query/server/src/index.d.ts +1 -2
  38. package/types/tanstack-query/src/index.d.ts +1 -1
  39. package/types/tanstack-query/src/provide-analog-query.d.ts +1 -3
  40. package/types/tanstack-query/src/server-query.d.ts +1 -1
  41. package/types/tanstack-query/server/src/provide-server-analog-query.d.ts +0 -2
  42. package/types/tanstack-query/src/provide-server-analog-query.d.ts +0 -2
@@ -1,26 +1,11 @@
1
- import { ApplicationRef, ENVIRONMENT_INITIALIZER, TransferState, inject, makeEnvironmentProviders } from "@angular/core";
2
- import { filter, skipWhile, take } from "rxjs/operators";
3
- import { QueryClient, dehydrate } from "@tanstack/angular-query-experimental";
4
- import { ANALOG_QUERIES_KEY, ANALOG_QUERIES_KEY as ANALOG_QUERIES_KEY$1, ANALOG_QUERY_STATE_KEY } from "@analogjs/router/tanstack-query";
1
+ import { QueryClient, dehydrate } from "@tanstack/angular-query";
5
2
  import { definePageLoad } from "@analogjs/router/server/actions";
6
- //#region packages/router/tanstack-query/server/src/provide-server-analog-query.ts
7
- function provideServerAnalogQuery() {
8
- return makeEnvironmentProviders([{
9
- provide: ENVIRONMENT_INITIALIZER,
10
- multi: true,
11
- useValue() {
12
- const appRef = inject(ApplicationRef);
13
- const queryClient = inject(QueryClient);
14
- const transferState = inject(TransferState);
15
- const subscription = appRef.isStable.pipe(skipWhile((stable) => stable), filter((stable) => stable), take(1)).subscribe(() => {
16
- transferState.set(ANALOG_QUERY_STATE_KEY, dehydrate(queryClient));
17
- });
18
- appRef.onDestroy(() => subscription.unsubscribe());
19
- }
20
- }]);
21
- }
22
- //#endregion
3
+ import { ANALOG_QUERIES_KEY, ANALOG_QUERIES_KEY as ANALOG_QUERIES_KEY$1 } from "@analogjs/router/tanstack-query";
23
4
  //#region packages/router/tanstack-query/server/src/define-page-load-queries.ts
5
+ function getRequestSignal(event) {
6
+ const { web, req } = event;
7
+ return (web?.request ?? (req instanceof Request ? req : void 0))?.signal;
8
+ }
24
9
  /**
25
10
  * Page load helper that prefetches TanStack Query queries inside the
26
11
  * `.server.ts` handler and ships the dehydrated cache alongside any
@@ -33,7 +18,7 @@ function provideServerAnalogQuery() {
33
18
  * ```ts
34
19
  * // src/app/pages/posts.server.ts
35
20
  * import { definePageLoadQueries } from '@analogjs/router/tanstack-query/server';
36
- * import { queryOptions } from '@tanstack/angular-query-experimental';
21
+ * import { queryOptions } from '@tanstack/angular-query';
37
22
  *
38
23
  * export const postsQuery = queryOptions({
39
24
  * queryKey: ['posts'],
@@ -53,19 +38,27 @@ function definePageLoadQueries(options) {
53
38
  params: options.params,
54
39
  query: options.query,
55
40
  handler: async (ctx) => {
41
+ const signal = getRequestSignal(ctx.event);
42
+ signal?.throwIfAborted();
56
43
  const client = options.client?.() ?? new QueryClient();
57
- const data = await options.handler({
58
- ...ctx,
59
- client
60
- });
61
- return {
62
- [ANALOG_QUERIES_KEY$1]: dehydrate(client),
63
- data
64
- };
44
+ const cancel = () => void client.cancelQueries();
45
+ signal?.addEventListener("abort", cancel, { once: true });
46
+ try {
47
+ const data = await options.handler({
48
+ ...ctx,
49
+ client
50
+ });
51
+ return {
52
+ [ANALOG_QUERIES_KEY$1]: dehydrate(client),
53
+ data
54
+ };
55
+ } finally {
56
+ signal?.removeEventListener("abort", cancel);
57
+ }
65
58
  }
66
59
  });
67
60
  }
68
61
  //#endregion
69
- export { ANALOG_QUERIES_KEY, definePageLoadQueries, provideServerAnalogQuery };
62
+ export { ANALOG_QUERIES_KEY, definePageLoadQueries };
70
63
 
71
64
  //# sourceMappingURL=analogjs-router-tanstack-query-server.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"analogjs-router-tanstack-query-server.mjs","names":[],"sources":["../../tanstack-query/server/src/provide-server-analog-query.ts","../../tanstack-query/server/src/define-page-load-queries.ts"],"sourcesContent":["import {\n ApplicationRef,\n ENVIRONMENT_INITIALIZER,\n TransferState,\n inject,\n makeEnvironmentProviders,\n} from '@angular/core';\nimport type { EnvironmentProviders } from '@angular/core';\nimport { filter, skipWhile, take } from 'rxjs/operators';\nimport { QueryClient, dehydrate } from '@tanstack/angular-query-experimental';\n\nimport { ANALOG_QUERY_STATE_KEY } from '@analogjs/router/tanstack-query';\n\nexport function provideServerAnalogQuery(): EnvironmentProviders {\n return makeEnvironmentProviders([\n {\n provide: ENVIRONMENT_INITIALIZER,\n multi: true,\n useValue() {\n // Dehydrate the QueryClient into `TransferState` once the app\n // becomes stable POST-RENDER on the server. `renderApplication`\n // awaits `whenStable()` itself before invoking\n // `BEFORE_APP_SERIALIZED` (which is where Angular's\n // `TRANSFER_STATE_SERIALIZATION_PROVIDERS` reads the store and\n // writes the `ng-state` script). Settling our write at the same\n // point — but ahead of Angular's own subscriber — lets the\n // dehydrated cache land in `TransferState` before the serializer\n // snapshots it, so component-issued queries make it to the client\n // without depending on provider declaration order.\n //\n // `skipWhile(stable => stable)` waits past the initial \"no\n // pending tasks yet\" emission `BehaviorSubject` semantics give\n // us at subscribe time; the next stable transition is the\n // post-render one with all queries settled.\n const appRef = inject(ApplicationRef);\n const queryClient = inject(QueryClient);\n const transferState = inject(TransferState);\n\n const subscription = appRef.isStable\n .pipe(\n skipWhile((stable) => stable),\n filter((stable) => stable),\n take(1),\n )\n .subscribe(() => {\n transferState.set(ANALOG_QUERY_STATE_KEY, dehydrate(queryClient));\n });\n\n appRef.onDestroy(() => subscription.unsubscribe());\n },\n },\n ]);\n}\n","import { QueryClient, dehydrate } from '@tanstack/angular-query-experimental';\nimport type { DehydratedState } from '@tanstack/angular-query-experimental';\nimport type { H3Event, H3EventContext } from 'h3';\nimport type { $Fetch } from 'ofetch';\n\nimport {\n definePageLoad,\n type PageLoadContext,\n type StandardSchemaV1,\n} from '@analogjs/router/server/actions';\nimport { ANALOG_QUERIES_KEY } from '@analogjs/router/tanstack-query';\n\nexport { ANALOG_QUERIES_KEY } from '@analogjs/router/tanstack-query';\n\ntype OptionalSchema = StandardSchemaV1 | undefined;\n\nexport interface PageLoadQueriesResult<TData> {\n __analogQueries: DehydratedState;\n data: TData;\n}\n\nexport interface DefinePageLoadQueriesOptions<\n TParamsSchema extends OptionalSchema,\n TQuerySchema extends OptionalSchema,\n TData,\n> {\n params?: TParamsSchema;\n query?: TQuerySchema;\n /**\n * Optional QueryClient factory. Defaults to `new QueryClient()`.\n * Override to set `defaultOptions` (e.g. `queries: { staleTime: Infinity }`).\n */\n client?: () => QueryClient;\n /**\n * Handler receives the standard PageLoadContext plus a per-request\n * QueryClient. Use `client.prefetchQuery` / `ensureQueryData` /\n * `prefetchInfiniteQuery` to warm the cache; the dehydrated client\n * is returned as `__analogQueries` on the load result. Anything you\n * return from the handler becomes `data` on the same result.\n */\n handler: (\n ctx: PageLoadContext<TParamsSchema, TQuerySchema> & { client: QueryClient },\n ) => Promise<TData> | TData;\n}\n\n/**\n * Page load helper that prefetches TanStack Query queries inside the\n * `.server.ts` handler and ships the dehydrated cache alongside any\n * additional data. The router-side hydrator in `provideAnalogQuery()`\n * merges the dehydrated payload into the active `QueryClient` on\n * `ResolveEnd`, so components reading the same query options see a\n * warm cache on first render.\n *\n * @example\n * ```ts\n * // src/app/pages/posts.server.ts\n * import { definePageLoadQueries } from '@analogjs/router/tanstack-query/server';\n * import { queryOptions } from '@tanstack/angular-query-experimental';\n *\n * export const postsQuery = queryOptions({\n * queryKey: ['posts'],\n * queryFn: async ({ signal }) =>\n * fetch('https://api.example.com/posts', { signal }).then((r) => r.json()),\n * });\n *\n * export const load = definePageLoadQueries({\n * handler: async ({ client }) => {\n * await client.prefetchQuery(postsQuery);\n * },\n * });\n * ```\n */\nexport function definePageLoadQueries<\n TParamsSchema extends OptionalSchema = undefined,\n TQuerySchema extends OptionalSchema = undefined,\n TData = void,\n>(\n options: DefinePageLoadQueriesOptions<TParamsSchema, TQuerySchema, TData>,\n): (ctx: {\n params: H3EventContext['params'];\n req: H3Event['node']['req'];\n res: H3Event['node']['res'];\n fetch: $Fetch;\n event: H3Event;\n}) => Promise<PageLoadQueriesResult<TData> | Response> {\n return definePageLoad({\n params: options.params,\n query: options.query,\n handler: async (ctx): Promise<PageLoadQueriesResult<TData>> => {\n const client = options.client?.() ?? new QueryClient();\n const data = await options.handler({ ...ctx, client });\n return {\n [ANALOG_QUERIES_KEY]: dehydrate(client),\n data,\n };\n },\n });\n}\n"],"mappings":";;;;;;AAaA,SAAgB,2BAAwB;CACtC,OAAO,yBAAyB,CAC9B;EACE,SAAS;EACT,OAAO;EACP,WAAQ;GAgBN,MAAM,SAAS,OAAO,cAAc;GACpC,MAAM,cAAc,OAAO,WAAW;GACtC,MAAM,gBAAgB,OAAO,aAAa;GAE1C,MAAM,eAAe,OAAO,SACzB,KACC,WAAW,WAAW,MAAM,GAC5B,QAAQ,WAAW,MAAM,GACzB,KAAK,CAAC,CAAC,CACR,CACA,gBAAe;IACd,cAAc,IAAI,wBAAwB,UAAU,WAAW,CAAC;GAClE,CAAC;GAEH,OAAO,gBAAgB,aAAa,YAAW,CAAE;EACnD;CACD,CACF,CAAA;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACoBA,SAAgB,sBAKd,SAAyE;CAQzE,OAAO,eAAe;EACpB,QAAQ,QAAQ;EAChB,OAAO,QAAQ;EACf,SAAS,OAAO,QAA8C;GAC5D,MAAM,SAAS,QAAQ,SAAQ,KAAM,IAAI,YAAW;GACpD,MAAM,OAAO,MAAM,QAAQ,QAAQ;IAAE,GAAG;IAAK;GAAM,CAAE;GACrD,OAAO;KACJ,uBAAqB,UAAU,MAAM;IACtC;GACD;EACH;CACD,CAAA;AACH"}
1
+ {"version":3,"file":"analogjs-router-tanstack-query-server.mjs","names":[],"sources":["../../tanstack-query/server/src/define-page-load-queries.ts"],"sourcesContent":["import { QueryClient, dehydrate } from '@tanstack/angular-query';\nimport type { DehydratedState } from '@tanstack/angular-query';\nimport type { H3Event, H3EventContext } from 'h3';\nimport type { $Fetch } from 'ofetch';\n\nimport {\n definePageLoad,\n type PageLoadContext,\n type StandardSchemaV1,\n} from '@analogjs/router/server/actions';\nimport { ANALOG_QUERIES_KEY } from '@analogjs/router/tanstack-query';\n\nexport { ANALOG_QUERIES_KEY } from '@analogjs/router/tanstack-query';\n\ntype OptionalSchema = StandardSchemaV1 | undefined;\n\n// h3 v2 exposes the web Request as `event.req`; h3 v1 as `event.web.request`.\nfunction getRequestSignal(event: H3Event): AbortSignal | undefined {\n const { web, req } = event as unknown as {\n web?: { request?: Request };\n req?: unknown;\n };\n return (web?.request ?? (req instanceof Request ? req : undefined))?.signal;\n}\n\nexport interface PageLoadQueriesResult<TData> {\n __analogQueries: DehydratedState;\n data: TData;\n}\n\nexport interface PageLoadQueries<TData> {\n (ctx: {\n params: H3EventContext['params'];\n req: H3Event['node']['req'];\n res: H3Event['node']['res'];\n fetch: $Fetch;\n event: H3Event;\n }): Promise<PageLoadQueriesResult<TData> | Response>;\n}\n\nexport interface DefinePageLoadQueriesOptions<\n TParamsSchema extends OptionalSchema,\n TQuerySchema extends OptionalSchema,\n TData,\n> {\n params?: TParamsSchema;\n query?: TQuerySchema;\n /**\n * Optional QueryClient factory. Defaults to `new QueryClient()`.\n * Override to set `defaultOptions` (e.g. `queries: { staleTime: Infinity }`).\n */\n client?: () => QueryClient;\n /**\n * Handler receives the standard PageLoadContext plus a per-request\n * QueryClient. Use `client.prefetchQuery` / `ensureQueryData` /\n * `prefetchInfiniteQuery` to warm the cache; the dehydrated client\n * is returned as `__analogQueries` on the load result. Anything you\n * return from the handler becomes `data` on the same result.\n */\n handler: (\n ctx: PageLoadContext<TParamsSchema, TQuerySchema> & { client: QueryClient },\n ) => Promise<TData> | TData;\n}\n\n/**\n * Page load helper that prefetches TanStack Query queries inside the\n * `.server.ts` handler and ships the dehydrated cache alongside any\n * additional data. The router-side hydrator in `provideAnalogQuery()`\n * merges the dehydrated payload into the active `QueryClient` on\n * `ResolveEnd`, so components reading the same query options see a\n * warm cache on first render.\n *\n * @example\n * ```ts\n * // src/app/pages/posts.server.ts\n * import { definePageLoadQueries } from '@analogjs/router/tanstack-query/server';\n * import { queryOptions } from '@tanstack/angular-query';\n *\n * export const postsQuery = queryOptions({\n * queryKey: ['posts'],\n * queryFn: async ({ signal }) =>\n * fetch('https://api.example.com/posts', { signal }).then((r) => r.json()),\n * });\n *\n * export const load = definePageLoadQueries({\n * handler: async ({ client }) => {\n * await client.prefetchQuery(postsQuery);\n * },\n * });\n * ```\n */\nexport function definePageLoadQueries<\n TParamsSchema extends OptionalSchema = undefined,\n TQuerySchema extends OptionalSchema = undefined,\n TData = void,\n>(\n options: DefinePageLoadQueriesOptions<TParamsSchema, TQuerySchema, TData>,\n): PageLoadQueries<TData> {\n return definePageLoad({\n params: options.params,\n query: options.query,\n handler: async (ctx): Promise<PageLoadQueriesResult<TData>> => {\n const signal = getRequestSignal(ctx.event);\n signal?.throwIfAborted();\n const client = options.client?.() ?? new QueryClient();\n const cancel = () => void client.cancelQueries();\n signal?.addEventListener('abort', cancel, { once: true });\n try {\n const data = await options.handler({ ...ctx, client });\n return {\n [ANALOG_QUERIES_KEY]: dehydrate(client),\n data,\n };\n } finally {\n signal?.removeEventListener('abort', cancel);\n }\n },\n });\n}\n"],"mappings":";;;;AAiBA,SAAS,iBAAiB,OAAc;CACtC,MAAM,EAAE,KAAK,QAAQ;CAIrB,QAAQ,KAAK,YAAY,eAAe,UAAU,MAAM,KAAA,GAAA,EAAa;AACvE;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,sBAKd,SAAyE;CAEzE,OAAO,eAAe;EACpB,QAAQ,QAAQ;EAChB,OAAO,QAAQ;EACf,SAAS,OAAO,QAA8C;GAC5D,MAAM,SAAS,iBAAiB,IAAI,KAAK;GACzC,QAAQ,eAAc;GACtB,MAAM,SAAS,QAAQ,SAAQ,KAAM,IAAI,YAAW;GACpD,MAAM,eAAe,KAAK,OAAO,cAAa;GAC9C,QAAQ,iBAAiB,SAAS,QAAQ,EAAE,MAAM,KAAI,CAAE;GACxD,IAAI;IACF,MAAM,OAAO,MAAM,QAAQ,QAAQ;KAAE,GAAG;KAAK;IAAM,CAAE;IACrD,OAAO;MACJ,uBAAqB,UAAU,MAAM;KACtC;IACD;GACH,UAAU;IACR,QAAQ,oBAAoB,SAAS,MAAM;GAC7C;EACF;CACD,CAAA;AACH"}
@@ -1,8 +1,7 @@
1
1
  import { ResolveEnd, Router } from "@angular/router";
2
- import { DestroyRef, ENVIRONMENT_INITIALIZER, PLATFORM_ID, TransferState, inject, makeEnvironmentProviders, makeStateKey } from "@angular/core";
3
- import { lastValueFrom } from "rxjs";
4
- import { isPlatformServer } from "@angular/common";
5
- import { QueryClient, hydrate } from "@tanstack/angular-query-experimental";
2
+ import { DestroyRef, ENVIRONMENT_INITIALIZER, inject, makeEnvironmentProviders } from "@angular/core";
3
+ import { fromEvent, lastValueFrom, takeUntil } from "rxjs";
4
+ import { QueryClient, hydrate } from "@tanstack/angular-query";
6
5
  //#region packages/router/tanstack-query/src/constants.ts
7
6
  /**
8
7
  * Route-data key under `ActivatedRoute.data['load']` that holds the
@@ -15,21 +14,8 @@ import { QueryClient, hydrate } from "@tanstack/angular-query-experimental";
15
14
  var ANALOG_QUERIES_KEY = "__analogQueries";
16
15
  //#endregion
17
16
  //#region packages/router/tanstack-query/src/provide-analog-query.ts
18
- var ANALOG_QUERY_STATE_KEY = makeStateKey("analog_query_state");
19
17
  function provideAnalogQuery() {
20
18
  return makeEnvironmentProviders([{
21
- provide: ENVIRONMENT_INITIALIZER,
22
- multi: true,
23
- useValue() {
24
- const transferState = inject(TransferState);
25
- const client = inject(QueryClient);
26
- const dehydratedState = transferState.get(ANALOG_QUERY_STATE_KEY, null);
27
- if (dehydratedState) {
28
- hydrate(client, dehydratedState);
29
- transferState.remove(ANALOG_QUERY_STATE_KEY);
30
- }
31
- }
32
- }, {
33
19
  provide: ENVIRONMENT_INITIALIZER,
34
20
  multi: true,
35
21
  useValue() {
@@ -37,35 +23,20 @@ function provideAnalogQuery() {
37
23
  if (!router) return;
38
24
  const client = inject(QueryClient);
39
25
  const destroyRef = inject(DestroyRef);
40
- const transferState = isPlatformServer(inject(PLATFORM_ID)) ? inject(TransferState) : null;
41
26
  const subscription = router.events.subscribe((event) => {
42
- if (event instanceof ResolveEnd) mergeRouteSnapshot(event.state.root, client, transferState);
27
+ if (event instanceof ResolveEnd) mergeRouteSnapshot(event.state.root, client);
43
28
  });
44
29
  destroyRef.onDestroy(() => subscription.unsubscribe());
45
30
  }
46
31
  }]);
47
32
  }
48
- function mergeRouteSnapshot(snapshot, client, transferState) {
33
+ function mergeRouteSnapshot(snapshot, client) {
49
34
  const load = snapshot.data?.["load"];
50
35
  if (load && typeof load === "object" && "__analogQueries" in load) {
51
36
  const dehydrated = load[ANALOG_QUERIES_KEY];
52
- if (dehydrated) {
53
- hydrate(client, dehydrated);
54
- if (transferState) {
55
- const existing = transferState.get(ANALOG_QUERY_STATE_KEY, null);
56
- transferState.set(ANALOG_QUERY_STATE_KEY, existing ? mergeDehydrated(existing, dehydrated) : dehydrated);
57
- }
58
- }
37
+ if (dehydrated) hydrate(client, dehydrated);
59
38
  }
60
- for (const child of snapshot.children) mergeRouteSnapshot(child, client, transferState);
61
- }
62
- function mergeDehydrated(base, next) {
63
- const queriesByHash = new Map(base.queries.map((query) => [query.queryHash, query]));
64
- for (const query of next.queries) queriesByHash.set(query.queryHash, query);
65
- return {
66
- mutations: [...base.mutations, ...next.mutations],
67
- queries: [...queriesByHash.values()]
68
- };
39
+ for (const child of snapshot.children) mergeRouteSnapshot(child, client);
69
40
  }
70
41
  //#endregion
71
42
  //#region packages/router/tanstack-query/src/server-query.ts
@@ -81,16 +52,19 @@ function buildUrl(base, params) {
81
52
  if (parts.length === 0) return base;
82
53
  return `${base}${base.includes("?") ? "&" : "?"}${parts.join("&")}`;
83
54
  }
55
+ function fetchUntilAborted(request, signal) {
56
+ return lastValueFrom(request.pipe(takeUntil(fromEvent(signal, "abort"))));
57
+ }
84
58
  function serverQueryOptions(http, url, options) {
85
59
  const { query, ...rest } = options;
86
60
  return {
87
61
  ...rest,
88
- queryFn: () => lastValueFrom(http.get(buildUrl(url, query)))
62
+ queryFn: ({ signal }) => fetchUntilAborted(http.get(buildUrl(url, query), { transferCache: false }), signal)
89
63
  };
90
64
  }
91
65
  function serverMutationOptions(http, url, options) {
92
66
  return {
93
- mutationFn: (body) => lastValueFrom(http.post(url, body)),
67
+ mutationFn: (body) => lastValueFrom(http.post(url, body === void 0 ? null : JSON.stringify(body), { headers: { "content-type": "application/json" } })),
94
68
  ...options
95
69
  };
96
70
  }
@@ -98,10 +72,10 @@ function serverInfiniteQueryOptions(http, url, options) {
98
72
  const { query: buildQuery, ...rest } = options;
99
73
  return {
100
74
  ...rest,
101
- queryFn: (context) => lastValueFrom(http.get(buildUrl(url, buildQuery(context))))
75
+ queryFn: (context) => fetchUntilAborted(http.get(buildUrl(url, buildQuery(context)), { transferCache: false }), context.signal)
102
76
  };
103
77
  }
104
78
  //#endregion
105
- export { ANALOG_QUERIES_KEY, ANALOG_QUERY_STATE_KEY, provideAnalogQuery, serverInfiniteQueryOptions, serverMutationOptions, serverQueryOptions };
79
+ export { ANALOG_QUERIES_KEY, provideAnalogQuery, serverInfiniteQueryOptions, serverMutationOptions, serverQueryOptions };
106
80
 
107
81
  //# sourceMappingURL=analogjs-router-tanstack-query.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"analogjs-router-tanstack-query.mjs","names":[],"sources":["../../tanstack-query/src/constants.ts","../../tanstack-query/src/provide-analog-query.ts","../../tanstack-query/src/server-query.ts"],"sourcesContent":["/**\n * Route-data key under `ActivatedRoute.data['load']` that holds the\n * `DehydratedState` produced by `definePageLoadQueries`. The Router-\n * events hydrator in `provideAnalogQuery()` looks for this key on\n * `ResolveEnd` and merges the dehydrated payload into the active\n * `QueryClient`, so component-issued queries hit a warm cache on\n * first render.\n */\nexport const ANALOG_QUERIES_KEY: '__analogQueries' = '__analogQueries';\n","import {\n DestroyRef,\n ENVIRONMENT_INITIALIZER,\n PLATFORM_ID,\n TransferState,\n inject,\n makeEnvironmentProviders,\n makeStateKey,\n} from '@angular/core';\nimport type { EnvironmentProviders, StateKey } from '@angular/core';\nimport { isPlatformServer } from '@angular/common';\nimport { ResolveEnd, Router } from '@angular/router';\nimport type { ActivatedRouteSnapshot } from '@angular/router';\nimport { QueryClient, hydrate } from '@tanstack/angular-query-experimental';\nimport type { DehydratedState } from '@tanstack/angular-query-experimental';\n\nimport { ANALOG_QUERIES_KEY } from './constants';\n\nexport const ANALOG_QUERY_STATE_KEY: StateKey<DehydratedState> =\n makeStateKey<DehydratedState>('analog_query_state');\n\nexport function provideAnalogQuery(): EnvironmentProviders {\n return makeEnvironmentProviders([\n {\n provide: ENVIRONMENT_INITIALIZER,\n multi: true,\n useValue() {\n if (import.meta.env.SSR) {\n return;\n }\n\n const transferState = inject(TransferState);\n const client = inject(QueryClient);\n const dehydratedState = transferState.get<DehydratedState | null>(\n ANALOG_QUERY_STATE_KEY,\n null,\n );\n\n if (dehydratedState) {\n hydrate(client, dehydratedState);\n transferState.remove(ANALOG_QUERY_STATE_KEY);\n }\n },\n },\n {\n provide: ENVIRONMENT_INITIALIZER,\n multi: true,\n useValue() {\n const router = inject(Router, { optional: true });\n if (!router) {\n return;\n }\n\n const client = inject(QueryClient);\n const destroyRef = inject(DestroyRef);\n // On the server, also mirror any dehydrated load payloads into\n // `TransferState` so Angular's own serializer can include them in\n // the `ng-state` script — we can't rely on\n // `provideServerAnalogQuery()`'s `BEFORE_APP_SERIALIZED` running\n // before Angular's `TRANSFER_STATE_SERIALIZATION_PROVIDERS`.\n const transferState = isPlatformServer(inject(PLATFORM_ID))\n ? inject(TransferState)\n : null;\n\n const subscription = router.events.subscribe((event) => {\n if (event instanceof ResolveEnd) {\n mergeRouteSnapshot(event.state.root, client, transferState);\n }\n });\n\n destroyRef.onDestroy(() => subscription.unsubscribe());\n },\n },\n ]);\n}\n\nfunction mergeRouteSnapshot(\n snapshot: ActivatedRouteSnapshot,\n client: QueryClient,\n transferState: TransferState | null,\n): void {\n const load = snapshot.data?.['load'];\n if (load && typeof load === 'object' && ANALOG_QUERIES_KEY in load) {\n const dehydrated = (load as Record<string, unknown>)[ANALOG_QUERIES_KEY] as\n | DehydratedState\n | undefined;\n if (dehydrated) {\n hydrate(client, dehydrated);\n if (transferState) {\n const existing = transferState.get<DehydratedState | null>(\n ANALOG_QUERY_STATE_KEY,\n null,\n );\n transferState.set(\n ANALOG_QUERY_STATE_KEY,\n existing ? mergeDehydrated(existing, dehydrated) : dehydrated,\n );\n }\n }\n }\n for (const child of snapshot.children) {\n mergeRouteSnapshot(child, client, transferState);\n }\n}\n\nfunction mergeDehydrated(\n base: DehydratedState,\n next: DehydratedState,\n): DehydratedState {\n // Last-writer-wins on duplicate `queryHash`: child route resolves run\n // after parent resolves, so the later entry is the fresher one and\n // matches `hydrate()`'s own newer-wins semantics for the QueryClient.\n const queriesByHash = new Map(\n base.queries.map((query) => [query.queryHash, query]),\n );\n for (const query of next.queries) {\n queriesByHash.set(query.queryHash, query);\n }\n return {\n mutations: [...base.mutations, ...next.mutations],\n queries: [...queriesByHash.values()],\n };\n}\n","import type { HttpClient } from '@angular/common/http';\nimport { lastValueFrom } from 'rxjs';\nimport type {\n CreateQueryOptions,\n CreateMutationOptions,\n CreateInfiniteQueryOptions,\n DefaultError,\n InfiniteData,\n QueryKey,\n} from '@tanstack/angular-query-experimental';\nimport type {\n ApiRouteHandler,\n InferRouteQuery,\n InferRouteBody,\n InferRouteResult,\n} from '@analogjs/router/server/actions';\n\nfunction buildUrl(base: string, params?: Record<string, unknown>): string {\n if (!params) return base;\n const parts: string[] = [];\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n const k = encodeURIComponent(key);\n if (Array.isArray(value)) {\n for (const item of value) {\n parts.push(`${k}=${encodeURIComponent(String(item))}`);\n }\n } else {\n parts.push(`${k}=${encodeURIComponent(String(value))}`);\n }\n }\n if (parts.length === 0) return base;\n const separator = base.includes('?') ? '&' : '?';\n return `${base}${separator}${parts.join('&')}`;\n}\n\nexport function serverQueryOptions<\n TRoute extends ApiRouteHandler<any, any, any>,\n TError = DefaultError,\n TData = InferRouteResult<TRoute>,\n TQueryKey extends QueryKey = QueryKey,\n>(\n http: HttpClient,\n url: string,\n options: { queryKey: TQueryKey; query?: InferRouteQuery<TRoute> } & Omit<\n CreateQueryOptions<InferRouteResult<TRoute>, TError, TData, TQueryKey>,\n 'queryKey' | 'queryFn'\n >,\n): CreateQueryOptions<InferRouteResult<TRoute>, TError, TData, TQueryKey> {\n const { query, ...rest } = options;\n return {\n ...rest,\n queryFn: () =>\n lastValueFrom(\n http.get<InferRouteResult<TRoute>>(\n buildUrl(url, query as Record<string, any>),\n ),\n ),\n } as CreateQueryOptions<InferRouteResult<TRoute>, TError, TData, TQueryKey>;\n}\n\nexport function serverMutationOptions<\n TRoute extends ApiRouteHandler<any, any, any>,\n TError = DefaultError,\n TOnMutateResult = unknown,\n>(\n http: HttpClient,\n url: string,\n options?: Omit<\n CreateMutationOptions<\n InferRouteResult<TRoute>,\n TError,\n InferRouteBody<TRoute>,\n TOnMutateResult\n >,\n 'mutationFn'\n >,\n): CreateMutationOptions<\n InferRouteResult<TRoute>,\n TError,\n InferRouteBody<TRoute>,\n TOnMutateResult\n> {\n return {\n mutationFn: (body: InferRouteBody<TRoute>) =>\n lastValueFrom(http.post<InferRouteResult<TRoute>>(url, body)),\n ...options,\n } as CreateMutationOptions<\n InferRouteResult<TRoute>,\n TError,\n InferRouteBody<TRoute>,\n TOnMutateResult\n >;\n}\n\nexport function serverInfiniteQueryOptions<\n TRoute extends ApiRouteHandler<any, any, any>,\n TError = DefaultError,\n TData = InfiniteData<InferRouteResult<TRoute>>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n http: HttpClient,\n url: string,\n options: {\n queryKey: TQueryKey;\n query: (context: { pageParam: TPageParam }) => InferRouteQuery<TRoute>;\n initialPageParam: TPageParam;\n getNextPageParam: (\n lastPage: InferRouteResult<TRoute>,\n allPages: InferRouteResult<TRoute>[],\n ) => TPageParam | undefined | null;\n } & Omit<\n CreateInfiniteQueryOptions<\n InferRouteResult<TRoute>,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n 'queryKey' | 'queryFn' | 'initialPageParam' | 'getNextPageParam'\n >,\n): CreateInfiniteQueryOptions<\n InferRouteResult<TRoute>,\n TError,\n TData,\n TQueryKey,\n TPageParam\n> {\n const { query: buildQuery, ...rest } = options;\n return {\n ...rest,\n queryFn: (context: { pageParam: TPageParam }) =>\n lastValueFrom(\n http.get<InferRouteResult<TRoute>>(\n buildUrl(url, buildQuery(context) as Record<string, any>),\n ),\n ),\n } as CreateInfiniteQueryOptions<\n InferRouteResult<TRoute>,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >;\n}\n"],"mappings":";;;;;;;;;;;;;;AAQA,IAAa,qBAAwC;;;ACUrD,IAAa,yBACX,aAA8B,oBAAoB;AAEpD,SAAgB,qBAAkB;CAChC,OAAO,yBAAyB,CAC9B;EACE,SAAS;EACT,OAAO;EACP,WAAQ;GAKN,MAAM,gBAAgB,OAAO,aAAa;GAC1C,MAAM,SAAS,OAAO,WAAW;GACjC,MAAM,kBAAkB,cAAc,IACpC,wBACA,IAAI;GAGN,IAAI,iBAAiB;IACnB,QAAQ,QAAQ,eAAe;IAC/B,cAAc,OAAO,sBAAsB;GAC7C;EACF;CACD,GACD;EACE,SAAS;EACT,OAAO;EACP,WAAQ;GACN,MAAM,SAAS,OAAO,QAAQ,EAAE,UAAU,KAAI,CAAE;GAChD,IAAI,CAAC,QACH;GAGF,MAAM,SAAS,OAAO,WAAW;GACjC,MAAM,aAAa,OAAO,UAAU;GAMpC,MAAM,gBAAgB,iBAAiB,OAAO,WAAW,CAAC,IACtD,OAAO,aAAa,IACpB;GAEJ,MAAM,eAAe,OAAO,OAAO,WAAW,UAAS;IACrD,IAAI,iBAAiB,YACnB,mBAAmB,MAAM,MAAM,MAAM,QAAQ,aAAa;GAE9D,CAAC;GAED,WAAW,gBAAgB,aAAa,YAAW,CAAE;EACvD;CACD,CACF,CAAA;AACH;AAEA,SAAS,mBACP,UACA,QACA,eAAmC;CAEnC,MAAM,OAAO,SAAS,OAAO;CAC7B,IAAI,QAAQ,OAAO,SAAS,YAAA,qBAAkC,MAAM;EAClE,MAAM,aAAc,KAAiC;EAGrD,IAAI,YAAY;GACd,QAAQ,QAAQ,UAAU;GAC1B,IAAI,eAAe;IACjB,MAAM,WAAW,cAAc,IAC7B,wBACA,IAAI;IAEN,cAAc,IACZ,wBACA,WAAW,gBAAgB,UAAU,UAAU,IAAI,UAAU;GAEjE;EACF;CACF;CACA,KAAK,MAAM,SAAS,SAAS,UAC3B,mBAAmB,OAAO,QAAQ,aAAa;AAEnD;AAEA,SAAS,gBACP,MACA,MAAqB;CAKrB,MAAM,gBAAgB,IAAI,IACxB,KAAK,QAAQ,KAAK,UAAU,CAAC,MAAM,WAAW,KAAK,CAAC,CAAC;CAEvD,KAAK,MAAM,SAAS,KAAK,SACvB,cAAc,IAAI,MAAM,WAAW,KAAK;CAE1C,OAAO;EACL,WAAW,CAAC,GAAG,KAAK,WAAW,GAAG,KAAK,SAAS;EAChD,SAAS,CAAC,GAAG,cAAc,OAAM,CAAE;CACpC;AACH;;;ACzGA,SAAS,SAAS,MAAc,QAAgC;CAC9D,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,QAAkB,CAAA;CACxB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;EACjD,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM;EAC3C,MAAM,IAAI,mBAAmB,GAAG;EAChC,IAAI,MAAM,QAAQ,KAAK,GACrB,KAAK,MAAM,QAAQ,OACjB,MAAM,KAAK,GAAG,EAAC,GAAI,mBAAmB,OAAO,IAAI,CAAC,GAAG;OAGvD,MAAM,KAAK,GAAG,EAAC,GAAI,mBAAmB,OAAO,KAAK,CAAC,GAAG;CAE1D;CACA,IAAI,MAAM,WAAW,GAAG,OAAO;CAE/B,OAAO,GAAG,OADQ,KAAK,SAAS,GAAG,IAAI,MAAM,MAChB,MAAM,KAAK,GAAG;AAC7C;AAEA,SAAgB,mBAMd,MACA,KACA,SAGC;CAED,MAAM,EAAE,OAAO,GAAG,SAAS;CAC3B,OAAO;EACL,GAAG;EACH,eACE,cACE,KAAK,IACH,SAAS,KAAK,KAA4B,CAAC,CAC5C;CAEoE;AAC7E;AAEA,SAAgB,sBAKd,MACA,KACA,SAQC;CAOD,OAAO;EACL,aAAa,SACX,cAAc,KAAK,KAA+B,KAAK,IAAI,CAAC;EAC9D,GAAG;CAMJ;AACH;AAEA,SAAgB,2BAOd,MACA,KACA,SAiBC;CAQD,MAAM,EAAE,OAAO,YAAY,GAAG,SAAS;CACvC,OAAO;EACL,GAAG;EACH,UAAU,YACR,cACE,KAAK,IACH,SAAS,KAAK,WAAW,OAAO,CAAwB,CAAC,CAC1D;CAQN;AACH"}
1
+ {"version":3,"file":"analogjs-router-tanstack-query.mjs","names":[],"sources":["../../tanstack-query/src/constants.ts","../../tanstack-query/src/provide-analog-query.ts","../../tanstack-query/src/server-query.ts"],"sourcesContent":["/**\n * Route-data key under `ActivatedRoute.data['load']` that holds the\n * `DehydratedState` produced by `definePageLoadQueries`. The Router-\n * events hydrator in `provideAnalogQuery()` looks for this key on\n * `ResolveEnd` and merges the dehydrated payload into the active\n * `QueryClient`, so component-issued queries hit a warm cache on\n * first render.\n */\nexport const ANALOG_QUERIES_KEY: '__analogQueries' = '__analogQueries';\n","import {\n DestroyRef,\n ENVIRONMENT_INITIALIZER,\n inject,\n makeEnvironmentProviders,\n} from '@angular/core';\nimport type { EnvironmentProviders } from '@angular/core';\nimport { ResolveEnd, Router } from '@angular/router';\nimport type { ActivatedRouteSnapshot } from '@angular/router';\nimport { QueryClient, hydrate } from '@tanstack/angular-query';\nimport type { DehydratedState } from '@tanstack/angular-query';\n\nimport { ANALOG_QUERIES_KEY } from './constants';\n\nexport function provideAnalogQuery(): EnvironmentProviders {\n return makeEnvironmentProviders([\n {\n provide: ENVIRONMENT_INITIALIZER,\n multi: true,\n useValue() {\n const router = inject(Router, { optional: true });\n if (!router) {\n return;\n }\n\n const client = inject(QueryClient);\n const destroyRef = inject(DestroyRef);\n const subscription = router.events.subscribe((event) => {\n if (event instanceof ResolveEnd) {\n mergeRouteSnapshot(event.state.root, client);\n }\n });\n\n destroyRef.onDestroy(() => subscription.unsubscribe());\n },\n },\n ]);\n}\n\nfunction mergeRouteSnapshot(\n snapshot: ActivatedRouteSnapshot,\n client: QueryClient,\n): void {\n const load = snapshot.data?.['load'];\n if (load && typeof load === 'object' && ANALOG_QUERIES_KEY in load) {\n const dehydrated = (load as Record<string, unknown>)[ANALOG_QUERIES_KEY] as\n | DehydratedState\n | undefined;\n if (dehydrated) {\n hydrate(client, dehydrated);\n }\n }\n for (const child of snapshot.children) {\n mergeRouteSnapshot(child, client);\n }\n}\n","import type { HttpClient } from '@angular/common/http';\nimport { fromEvent, lastValueFrom, takeUntil, type Observable } from 'rxjs';\nimport type {\n CreateQueryOptions,\n CreateMutationOptions,\n CreateInfiniteQueryOptions,\n DefaultError,\n InfiniteData,\n QueryKey,\n} from '@tanstack/angular-query';\nimport type {\n ApiRouteHandler,\n InferRouteQuery,\n InferRouteBody,\n InferRouteResult,\n} from '@analogjs/router/server/actions';\n\nfunction buildUrl(base: string, params?: Record<string, unknown>): string {\n if (!params) return base;\n const parts: string[] = [];\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n const k = encodeURIComponent(key);\n if (Array.isArray(value)) {\n for (const item of value) {\n parts.push(`${k}=${encodeURIComponent(String(item))}`);\n }\n } else {\n parts.push(`${k}=${encodeURIComponent(String(value))}`);\n }\n }\n if (parts.length === 0) return base;\n const separator = base.includes('?') ? '&' : '?';\n return `${base}${separator}${parts.join('&')}`;\n}\n\nfunction fetchUntilAborted<T>(\n request: Observable<T>,\n signal: AbortSignal,\n): Promise<T> {\n return lastValueFrom(request.pipe(takeUntil(fromEvent(signal, 'abort'))));\n}\n\nexport function serverQueryOptions<\n TRoute extends ApiRouteHandler<any, any, any>,\n TError = DefaultError,\n TData = InferRouteResult<TRoute>,\n TQueryKey extends QueryKey = QueryKey,\n>(\n http: HttpClient,\n url: string,\n options: { queryKey: TQueryKey; query?: InferRouteQuery<TRoute> } & Omit<\n CreateQueryOptions<InferRouteResult<TRoute>, TError, TData, TQueryKey>,\n 'queryKey' | 'queryFn'\n >,\n): CreateQueryOptions<InferRouteResult<TRoute>, TError, TData, TQueryKey> {\n const { query, ...rest } = options;\n return {\n ...rest,\n queryFn: ({ signal }: { signal: AbortSignal }) =>\n fetchUntilAborted(\n http.get<InferRouteResult<TRoute>>(\n buildUrl(url, query as Record<string, any>),\n { transferCache: false },\n ),\n signal,\n ),\n } as CreateQueryOptions<InferRouteResult<TRoute>, TError, TData, TQueryKey>;\n}\n\nexport function serverMutationOptions<\n TRoute extends ApiRouteHandler<any, any, any>,\n TError = DefaultError,\n TOnMutateResult = unknown,\n>(\n http: HttpClient,\n url: string,\n options?: Omit<\n CreateMutationOptions<\n InferRouteResult<TRoute>,\n TError,\n InferRouteBody<TRoute>,\n TOnMutateResult\n >,\n 'mutationFn'\n >,\n): CreateMutationOptions<\n InferRouteResult<TRoute>,\n TError,\n InferRouteBody<TRoute>,\n TOnMutateResult\n> {\n return {\n mutationFn: (body: InferRouteBody<TRoute>) =>\n lastValueFrom(\n http.post<InferRouteResult<TRoute>>(\n url,\n body === undefined ? null : JSON.stringify(body),\n { headers: { 'content-type': 'application/json' } },\n ),\n ),\n ...options,\n } as CreateMutationOptions<\n InferRouteResult<TRoute>,\n TError,\n InferRouteBody<TRoute>,\n TOnMutateResult\n >;\n}\n\nexport function serverInfiniteQueryOptions<\n TRoute extends ApiRouteHandler<any, any, any>,\n TError = DefaultError,\n TData = InfiniteData<InferRouteResult<TRoute>>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n http: HttpClient,\n url: string,\n options: {\n queryKey: TQueryKey;\n query: (context: { pageParam: TPageParam }) => InferRouteQuery<TRoute>;\n initialPageParam: TPageParam;\n getNextPageParam: (\n lastPage: InferRouteResult<TRoute>,\n allPages: InferRouteResult<TRoute>[],\n ) => TPageParam | undefined | null;\n } & Omit<\n CreateInfiniteQueryOptions<\n InferRouteResult<TRoute>,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n 'queryKey' | 'queryFn' | 'initialPageParam' | 'getNextPageParam'\n >,\n): CreateInfiniteQueryOptions<\n InferRouteResult<TRoute>,\n TError,\n TData,\n TQueryKey,\n TPageParam\n> {\n const { query: buildQuery, ...rest } = options;\n return {\n ...rest,\n queryFn: (context: { pageParam: TPageParam; signal: AbortSignal }) =>\n fetchUntilAborted(\n http.get<InferRouteResult<TRoute>>(\n buildUrl(url, buildQuery(context) as Record<string, any>),\n { transferCache: false },\n ),\n context.signal,\n ),\n } as CreateInfiniteQueryOptions<\n InferRouteResult<TRoute>,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >;\n}\n"],"mappings":";;;;;;;;;;;;;AAQA,IAAa,qBAAwC;;;ACMrD,SAAgB,qBAAkB;CAChC,OAAO,yBAAyB,CAC9B;EACE,SAAS;EACT,OAAO;EACP,WAAQ;GACN,MAAM,SAAS,OAAO,QAAQ,EAAE,UAAU,KAAI,CAAE;GAChD,IAAI,CAAC,QACH;GAGF,MAAM,SAAS,OAAO,WAAW;GACjC,MAAM,aAAa,OAAO,UAAU;GACpC,MAAM,eAAe,OAAO,OAAO,WAAW,UAAS;IACrD,IAAI,iBAAiB,YACnB,mBAAmB,MAAM,MAAM,MAAM,MAAM;GAE/C,CAAC;GAED,WAAW,gBAAgB,aAAa,YAAW,CAAE;EACvD;CACD,CACF,CAAA;AACH;AAEA,SAAS,mBACP,UACA,QAAmB;CAEnB,MAAM,OAAO,SAAS,OAAO;CAC7B,IAAI,QAAQ,OAAO,SAAS,YAAA,qBAAkC,MAAM;EAClE,MAAM,aAAc,KAAiC;EAGrD,IAAI,YACF,QAAQ,QAAQ,UAAU;CAE9B;CACA,KAAK,MAAM,SAAS,SAAS,UAC3B,mBAAmB,OAAO,MAAM;AAEpC;;;ACtCA,SAAS,SAAS,MAAc,QAAgC;CAC9D,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,QAAkB,CAAA;CACxB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;EACjD,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM;EAC3C,MAAM,IAAI,mBAAmB,GAAG;EAChC,IAAI,MAAM,QAAQ,KAAK,GACrB,KAAK,MAAM,QAAQ,OACjB,MAAM,KAAK,GAAG,EAAC,GAAI,mBAAmB,OAAO,IAAI,CAAC,GAAG;OAGvD,MAAM,KAAK,GAAG,EAAC,GAAI,mBAAmB,OAAO,KAAK,CAAC,GAAG;CAE1D;CACA,IAAI,MAAM,WAAW,GAAG,OAAO;CAE/B,OAAO,GAAG,OADQ,KAAK,SAAS,GAAG,IAAI,MAAM,MAChB,MAAM,KAAK,GAAG;AAC7C;AAEA,SAAS,kBACP,SACA,QAAmB;CAEnB,OAAO,cAAc,QAAQ,KAAK,UAAU,UAAU,QAAQ,OAAO,CAAC,CAAC,CAAC;AAC1E;AAEA,SAAgB,mBAMd,MACA,KACA,SAGC;CAED,MAAM,EAAE,OAAO,GAAG,SAAS;CAC3B,OAAO;EACL,GAAG;EACH,UAAU,EAAE,aACV,kBACE,KAAK,IACH,SAAS,KAAK,KAA4B,GAC1C,EAAE,eAAe,MAAK,CAAE,GAE1B,MAAM;CAE+D;AAC7E;AAEA,SAAgB,sBAKd,MACA,KACA,SAQC;CAOD,OAAO;EACL,aAAa,SACX,cACE,KAAK,KACH,KACA,SAAS,KAAA,IAAY,OAAO,KAAK,UAAU,IAAI,GAC/C,EAAE,SAAS,EAAE,gBAAgB,mBAAkB,EAAE,CAAE,CACpD;EAEL,GAAG;CAMJ;AACH;AAEA,SAAgB,2BAOd,MACA,KACA,SAiBC;CAQD,MAAM,EAAE,OAAO,YAAY,GAAG,SAAS;CACvC,OAAO;EACL,GAAG;EACH,UAAU,YACR,kBACE,KAAK,IACH,SAAS,KAAK,WAAW,OAAO,CAAwB,GACxD,EAAE,eAAe,MAAK,CAAE,GAE1B,QAAQ,MAAM;CAQnB;AACH"}
@@ -1,12 +1,12 @@
1
- import { API_PREFIX, injectAPIPrefix, injectBaseURL, injectInternalServerFetch, injectRequest } from "./analogjs-router-tokens.mjs";
2
1
  import { a as ANALOG_META_KEY, i as injectRouteEndpointURL, n as ANALOG_ROUTE_FILES, o as updateMetaTagsOnRouteChange, r as createRoutes$1, s as updateJsonLdOnRouteChange, t as ANALOG_EXTRA_ROUTE_FILE_SOURCES } from "./route-files.mjs";
2
+ import { API_PREFIX, injectAPIPrefix, injectBaseURL, injectInternalServerFetch, injectRequest } from "./analogjs-router-tokens.mjs";
3
3
  import { n as createRoutes, t as injectDebugRoutes } from "./routes.mjs";
4
4
  import * as i1 from "@angular/router";
5
5
  import { ActivatedRoute, ROUTES, Router, RouterLink, provideRouter } from "@angular/router";
6
6
  import * as i0 from "@angular/core";
7
- import { DOCUMENT, Directive, ElementRef, Injectable, InjectionToken, Injector, PLATFORM_ID, Renderer2, TransferState, assertInInjectionContext, booleanAttribute, effect, inject, input, makeEnvironmentProviders, makeStateKey, output, provideAppInitializer, resource, runInInjectionContext, signal } from "@angular/core";
8
- import { HttpClient, HttpHeaders, HttpResponse, ɵHTTP_ROOT_INTERCEPTOR_FNS } from "@angular/common/http";
9
- import { combineLatest, firstValueFrom, from, map, of } from "rxjs";
7
+ import { APP_BOOTSTRAP_LISTENER, ApplicationRef, DOCUMENT, Directive, ElementRef, Injectable, InjectionToken, Injector, PLATFORM_ID, Renderer2, TransferState, assertInInjectionContext, booleanAttribute, effect, inject, input, makeEnvironmentProviders, makeStateKey, output, provideAppInitializer, resource, runInInjectionContext, signal } from "@angular/core";
8
+ import { HttpClient, HttpErrorResponse, HttpHeaders, HttpResponse, ɵHTTP_ROOT_INTERCEPTOR_FNS } from "@angular/common/http";
9
+ import { Observable, combineLatest, firstValueFrom, from, map, of, takeUntil } from "rxjs";
10
10
  import { Meta } from "@angular/platform-browser";
11
11
  import { isPlatformBrowser, isPlatformServer } from "@angular/common";
12
12
  import { toSignal } from "@angular/core/rxjs-interop";
@@ -214,6 +214,23 @@ function mergeFetchParams(requestUrl, request) {
214
214
  return params;
215
215
  }, {});
216
216
  }
217
+ var TRANSFER_CACHE_STATE = new InjectionToken("ANALOG_TRANSFER_CACHE_STATE", {
218
+ providedIn: "root",
219
+ factory: () => ({ isActive: true })
220
+ });
221
+ /**
222
+ * Stops restoring transferred responses once the app is first stable,
223
+ * matching Angular's HTTP transfer cache.
224
+ */
225
+ function deactivateTransferCacheWhenStable() {
226
+ const appRef = inject(ApplicationRef);
227
+ const cacheState = inject(TRANSFER_CACHE_STATE);
228
+ return () => {
229
+ appRef.whenStable().then(() => {
230
+ cacheState.isActive = false;
231
+ });
232
+ };
233
+ }
217
234
  /**
218
235
  * Interceptor that is server-aware when making HttpClient requests.
219
236
  * Server-side requests use the full URL
@@ -228,6 +245,7 @@ function requestContextInterceptor(req, next) {
228
245
  const apiPrefix = injectAPIPrefix();
229
246
  const baseUrl = injectBaseURL();
230
247
  const transferState = inject(TransferState);
248
+ const cacheState = inject(TRANSFER_CACHE_STATE);
231
249
  const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
232
250
  const nitroGlobal = globalThis;
233
251
  const serverFetch = injectInternalServerFetch() ?? nitroGlobal.$fetch;
@@ -243,6 +261,8 @@ function requestContextInterceptor(req, next) {
243
261
  body: req.body ? req.body : void 0,
244
262
  params: fetchParams,
245
263
  responseType,
264
+ parseResponse: responseType === "json" ? (text) => text : void 0,
265
+ ignoreResponseError: true,
246
266
  headers: req.headers.keys().reduce((hdrs, current) => {
247
267
  const value = req.headers.get(current);
248
268
  return value != null ? {
@@ -258,8 +278,23 @@ function requestContextInterceptor(req, next) {
258
278
  statusText: res.statusText ?? "OK",
259
279
  url: fetchUrl
260
280
  };
281
+ if (responseType === "json" && typeof res._data === "string") try {
282
+ cacheResponse.body = res._data === "" ? null : JSON.parse(res._data);
283
+ } catch (error) {
284
+ if (cacheResponse.status < 400) throw new HttpErrorResponse({
285
+ ...cacheResponse,
286
+ error: {
287
+ error,
288
+ text: res._data
289
+ }
290
+ });
291
+ }
292
+ if (cacheResponse.status >= 400) throw new HttpErrorResponse({
293
+ ...cacheResponse,
294
+ error: cacheResponse.body
295
+ });
261
296
  const transferResponse = new HttpResponse(cacheResponse);
262
- transferState.set(storeKey, cacheResponse);
297
+ if (req.transferCache !== false) transferState.set(storeKey, cacheResponse);
263
298
  return transferResponse;
264
299
  }));
265
300
  }
@@ -269,7 +304,7 @@ function requestContextInterceptor(req, next) {
269
304
  const { pathname, search } = toAbsoluteUrl(req.urlWithParams);
270
305
  const cacheKey = makeCacheKey(req, `${pathname}${search}`);
271
306
  const storeKey = makeStateKey(`analog_${cacheKey}`);
272
- const cacheRestoreResponse = transferState.get(storeKey, null);
307
+ const cacheRestoreResponse = req.transferCache !== false && cacheState.isActive ? transferState.get(storeKey, null) : null;
273
308
  if (cacheRestoreResponse) {
274
309
  transferState.remove(storeKey);
275
310
  return of(new HttpResponse(cacheRestoreResponse));
@@ -320,6 +355,11 @@ function provideFileRouterWithRoutes(...features) {
320
355
  multi: true,
321
356
  useValue: requestContextInterceptor
322
357
  },
358
+ {
359
+ provide: APP_BOOTSTRAP_LISTENER,
360
+ multi: true,
361
+ useFactory: deactivateTransferCacheWhenStable
362
+ },
323
363
  {
324
364
  provide: ɵHTTP_ROOT_INTERCEPTOR_FNS,
325
365
  multi: true,
@@ -528,7 +568,7 @@ var FormAction = class FormAction {
528
568
  static {
529
569
  this.ɵfac = i0.ɵɵngDeclareFactory({
530
570
  minVersion: "12.0.0",
531
- version: "22.2.0",
571
+ version: "22.3.0",
532
572
  ngImport: i0,
533
573
  type: FormAction,
534
574
  deps: [],
@@ -538,7 +578,7 @@ var FormAction = class FormAction {
538
578
  static {
539
579
  this.ɵdir = i0.ɵɵngDeclareDirective({
540
580
  minVersion: "17.1.0",
541
- version: "22.2.0",
581
+ version: "22.3.0",
542
582
  type: FormAction,
543
583
  isStandalone: true,
544
584
  selector: "form[action],form[method],form[enhanceForm]",
@@ -570,7 +610,7 @@ var FormAction = class FormAction {
570
610
  };
571
611
  i0.ɵɵngDeclareClassMetadata({
572
612
  minVersion: "12.0.0",
573
- version: "22.2.0",
613
+ version: "22.3.0",
574
614
  ngImport: i0,
575
615
  type: FormAction,
576
616
  decorators: [{
@@ -676,10 +716,10 @@ var ServerFnClient = class ServerFnClient {
676
716
  get isServer() {
677
717
  return !!this.dispatcher;
678
718
  }
679
- async call(fn, input) {
719
+ async call(fn, input, signal) {
680
720
  if (this.dispatcher) return this.dispatcher(fn, input, this.injector);
681
- const request$ = fn.method === "GET" ? this.http.get(fn.url) : this.http.post(fn.url, input ?? {});
682
- return firstValueFrom(request$);
721
+ const request$ = fn.method === "GET" ? this.http.get(fn.url) : this.http.post(fn.url, requestBody(input), { headers: { "Content-Type": "application/json" } });
722
+ return firstValueFrom(untilAborted(request$, signal));
683
723
  }
684
724
  /** Key a read's value for TransferState hydration (fn id + input). */
685
725
  stateKey(fn, input) {
@@ -699,7 +739,7 @@ var ServerFnClient = class ServerFnClient {
699
739
  static {
700
740
  this.ɵfac = i0.ɵɵngDeclareFactory({
701
741
  minVersion: "12.0.0",
702
- version: "22.2.0",
742
+ version: "22.3.0",
703
743
  ngImport: i0,
704
744
  type: ServerFnClient,
705
745
  deps: [],
@@ -709,7 +749,7 @@ var ServerFnClient = class ServerFnClient {
709
749
  static {
710
750
  this.ɵprov = i0.ɵɵngDeclareInjectable({
711
751
  minVersion: "12.0.0",
712
- version: "22.2.0",
752
+ version: "22.3.0",
713
753
  ngImport: i0,
714
754
  type: ServerFnClient,
715
755
  providedIn: "root"
@@ -718,7 +758,7 @@ var ServerFnClient = class ServerFnClient {
718
758
  };
719
759
  i0.ɵɵngDeclareClassMetadata({
720
760
  minVersion: "12.0.0",
721
- version: "22.2.0",
761
+ version: "22.3.0",
722
762
  ngImport: i0,
723
763
  type: ServerFnClient,
724
764
  decorators: [{
@@ -736,11 +776,11 @@ function injectServerFn(fn, args) {
736
776
  const client = inject(ServerFnClient);
737
777
  return resource({
738
778
  params: () => args ? args() : NO_INPUT,
739
- loader: async ({ params }) => {
779
+ loader: async ({ params, abortSignal }) => {
740
780
  const input = params === NO_INPUT ? void 0 : params;
741
781
  const seeded = client.readSeed(fn, input);
742
782
  if (seeded !== void 0) return seeded;
743
- const value = await client.call(fn, input);
783
+ const value = await client.call(fn, input, abortSignal);
744
784
  if (client.isServer) client.writeSeed(fn, input, value);
745
785
  return value;
746
786
  }
@@ -758,9 +798,23 @@ function injectServerFnMutation(fn) {
758
798
  return (input) => client.call(fn, input);
759
799
  }
760
800
  function stableInput(input) {
761
- if (input === void 0 || input === null) return "_";
801
+ if (input === void 0) return "_";
762
802
  return JSON.stringify(input);
763
803
  }
804
+ function requestBody(input) {
805
+ if (input === void 0) return {};
806
+ return typeof input === "string" || input === null ? JSON.stringify(input) : input;
807
+ }
808
+ function untilAborted(source, signal) {
809
+ if (!signal) return source;
810
+ const aborted = new Observable((subscriber) => {
811
+ const abort = () => subscriber.error(signal.reason);
812
+ if (signal.aborted) abort();
813
+ else signal.addEventListener("abort", abort, { once: true });
814
+ return () => signal.removeEventListener("abort", abort);
815
+ });
816
+ return source.pipe(takeUntil(aborted));
817
+ }
764
818
  //#endregion
765
819
  //#region packages/router/src/lib/server-fn/server-fn-ref.ts
766
820
  /**
@@ -992,7 +1046,7 @@ var LinkTo = class LinkTo {
992
1046
  static {
993
1047
  this.ɵfac = i0.ɵɵngDeclareFactory({
994
1048
  minVersion: "12.0.0",
995
- version: "22.2.0",
1049
+ version: "22.3.0",
996
1050
  ngImport: i0,
997
1051
  type: LinkTo,
998
1052
  deps: [],
@@ -1002,7 +1056,7 @@ var LinkTo = class LinkTo {
1002
1056
  static {
1003
1057
  this.ɵdir = i0.ɵɵngDeclareDirective({
1004
1058
  minVersion: "17.1.0",
1005
- version: "22.2.0",
1059
+ version: "22.3.0",
1006
1060
  type: LinkTo,
1007
1061
  isStandalone: true,
1008
1062
  selector: "[linkTo]",
@@ -1046,7 +1100,7 @@ var LinkTo = class LinkTo {
1046
1100
  };
1047
1101
  i0.ɵɵngDeclareClassMetadata({
1048
1102
  minVersion: "12.0.0",
1049
- version: "22.2.0",
1103
+ version: "22.3.0",
1050
1104
  ngImport: i0,
1051
1105
  type: LinkTo,
1052
1106
  decorators: [{