@analogjs/router 2.8.0-beta.10 → 2.8.0-beta.12

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 (28) hide show
  1. package/fesm2022/analogjs-router-debug.page-MFY2u07E.mjs +119 -0
  2. package/fesm2022/analogjs-router-debug.page-MFY2u07E.mjs.map +1 -0
  3. package/fesm2022/analogjs-router-i18n.mjs +82 -219
  4. package/fesm2022/analogjs-router-i18n.mjs.map +1 -1
  5. package/fesm2022/analogjs-router-routes-L2tt-0ms.mjs +263 -0
  6. package/fesm2022/analogjs-router-routes-L2tt-0ms.mjs.map +1 -0
  7. package/fesm2022/analogjs-router-server-actions.mjs +228 -463
  8. package/fesm2022/analogjs-router-server-actions.mjs.map +1 -1
  9. package/fesm2022/analogjs-router-server.mjs +608 -838
  10. package/fesm2022/analogjs-router-server.mjs.map +1 -1
  11. package/fesm2022/analogjs-router-tanstack-query-server.mjs +35 -85
  12. package/fesm2022/analogjs-router-tanstack-query-server.mjs.map +1 -1
  13. package/fesm2022/analogjs-router-tanstack-query.mjs +79 -127
  14. package/fesm2022/analogjs-router-tanstack-query.mjs.map +1 -1
  15. package/fesm2022/analogjs-router-tokens.mjs +14 -19
  16. package/fesm2022/analogjs-router-tokens.mjs.map +1 -1
  17. package/fesm2022/analogjs-router.mjs +772 -1312
  18. package/fesm2022/analogjs-router.mjs.map +1 -1
  19. package/package.json +2 -2
  20. package/types/analogjs-router-i18n.d.ts +55 -24
  21. package/types/analogjs-router-server-actions.d.ts +98 -107
  22. package/types/analogjs-router-server.d.ts +76 -116
  23. package/types/analogjs-router-tanstack-query-server.d.ts +33 -37
  24. package/types/analogjs-router-tanstack-query.d.ts +19 -24
  25. package/types/analogjs-router-tokens.d.ts +26 -22
  26. package/types/analogjs-router.d.ts +268 -265
  27. package/fesm2022/analogjs-router-debug.page-COcFkgRu.mjs +0 -91
  28. package/fesm2022/analogjs-router-debug.page-COcFkgRu.mjs.map +0 -1
@@ -1,1377 +1,837 @@
1
- import * as i1 from '@angular/router';
2
- import { Router, NavigationEnd, UrlSegment, ActivatedRoute, provideRouter, ROUTES, UrlSegmentGroup, PRIMARY_OUTLET, DefaultUrlSerializer, UrlTree, RouterLink } from '@angular/router';
3
- import * as i0 from '@angular/core';
4
- import { inject, PLATFORM_ID, makeEnvironmentProviders, ENVIRONMENT_INITIALIZER, Injector, makeStateKey, TransferState, input, booleanAttribute, output, signal, ElementRef, Renderer2, effect, runInInjectionContext, Directive, InjectionToken, Injectable, assertInInjectionContext, resource } from '@angular/core';
5
- import { HttpClient, HttpHeaders, ɵHTTP_ROOT_INTERCEPTOR_FNS as _HTTP_ROOT_INTERCEPTOR_FNS, HttpResponse } from '@angular/common/http';
6
- import { firstValueFrom, map, from, of, combineLatest } from 'rxjs';
7
- import { Meta } from '@angular/platform-browser';
8
- import { filter } from 'rxjs/operators';
9
- import { injectAPIPrefix, injectBaseURL, injectRequest, API_PREFIX } from '@analogjs/router/tokens';
10
- import { isPlatformServer } from '@angular/common';
11
- import { toSignal } from '@angular/core/rxjs-interop';
12
-
13
- const ROUTE_META_TAGS_KEY = Symbol('@analogjs/router Route Meta Tags Key');
14
- const CHARSET_KEY = 'charset';
15
- const HTTP_EQUIV_KEY = 'httpEquiv';
16
- // httpEquiv selector key needs to be in kebab case format
17
- const HTTP_EQUIV_SELECTOR_KEY = 'http-equiv';
18
- const NAME_KEY = 'name';
19
- const PROPERTY_KEY = 'property';
20
- const CONTENT_KEY = 'content';
21
- const ITEMPROP_KEY = 'itemprop';
22
- function updateMetaTagsOnRouteChange() {
23
- const router = inject(Router);
24
- const metaService = inject(Meta);
25
- router.events
26
- .pipe(filter((event) => event instanceof NavigationEnd))
27
- .subscribe(() => {
28
- const metaTagMap = getMetaTagMap(router.routerState.snapshot.root);
29
- for (const metaTagSelector in metaTagMap) {
30
- const metaTag = metaTagMap[metaTagSelector];
31
- metaService.updateTag(metaTag, metaTagSelector);
32
- }
33
- });
34
- }
35
- function getMetaTagMap(route) {
36
- const metaTagMap = {};
37
- let currentRoute = route;
38
- while (currentRoute) {
39
- const metaTags = currentRoute.data[ROUTE_META_TAGS_KEY] ?? [];
40
- for (const metaTag of metaTags) {
41
- metaTagMap[getMetaTagSelector(metaTag)] = metaTag;
42
- }
43
- currentRoute = currentRoute.firstChild;
44
- }
45
- return metaTagMap;
46
- }
47
- function getMetaTagSelector(metaTag) {
48
- if (metaTag.name) {
49
- return `${NAME_KEY}="${metaTag.name}"`;
50
- }
51
- if (metaTag.property) {
52
- return `${PROPERTY_KEY}="${metaTag.property}"`;
53
- }
54
- if (metaTag.httpEquiv) {
55
- return `${HTTP_EQUIV_SELECTOR_KEY}="${metaTag.httpEquiv}"`;
56
- }
57
- if (metaTag.itemprop) {
58
- return `${ITEMPROP_KEY}="${metaTag.itemprop}"`;
59
- }
60
- return CHARSET_KEY;
61
- }
62
-
63
- const ANALOG_META_KEY = Symbol('@analogjs/router Analog Route Metadata Key');
64
- /**
65
- * This variable reference is replaced with a glob of all route endpoints.
66
- */
67
- let ANALOG_PAGE_ENDPOINTS = {};
68
-
69
- function injectRouteEndpointURL(route) {
70
- const routeConfig = route.routeConfig;
71
- const apiPrefix = injectAPIPrefix();
72
- const baseUrl = injectBaseURL();
73
- const { queryParams, fragment: hash, params, parent } = route;
74
- const segment = parent?.url.map((segment) => segment.path).join('/') || '';
75
- const url = new URL('', import.meta.env['VITE_ANALOG_PUBLIC_BASE_URL'] ||
76
- baseUrl ||
77
- (typeof window !== 'undefined' && window.location.origin
78
- ? window.location.origin
79
- : ''));
80
- url.pathname = `${url.pathname.endsWith('/') ? url.pathname : url.pathname + '/'}${apiPrefix}/_analog${routeConfig[ANALOG_META_KEY].endpoint}`;
81
- url.search = `${new URLSearchParams(queryParams).toString()}`;
82
- url.hash = hash ?? '';
83
- Object.keys(params).forEach((param) => {
84
- url.pathname = url.pathname.replace(`[${param}]`, params[param]);
85
- });
86
- url.pathname = url.pathname.replace('**', segment);
87
- return url;
88
- }
89
-
90
- function toRouteConfig(routeMeta) {
91
- if (routeMeta && isRedirectRouteMeta(routeMeta)) {
92
- return routeMeta;
93
- }
94
- let { meta, ...routeConfig } = routeMeta ?? {};
95
- if (Array.isArray(meta)) {
96
- routeConfig.data = { ...routeConfig.data, [ROUTE_META_TAGS_KEY]: meta };
97
- }
98
- else if (typeof meta === 'function') {
99
- routeConfig.resolve = {
100
- ...routeConfig.resolve,
101
- [ROUTE_META_TAGS_KEY]: meta,
102
- };
103
- }
104
- if (!routeConfig) {
105
- routeConfig = {};
106
- }
107
- routeConfig.runGuardsAndResolvers =
108
- routeConfig.runGuardsAndResolvers ?? 'paramsOrQueryParamsChange';
109
- routeConfig.resolve = {
110
- ...routeConfig.resolve,
111
- load: async (route) => {
112
- const routeConfig = route.routeConfig;
113
- if (ANALOG_PAGE_ENDPOINTS[routeConfig[ANALOG_META_KEY].endpointKey]) {
114
- const http = inject(HttpClient);
115
- const url = injectRouteEndpointURL(route);
116
- if (!!import.meta.env['VITE_ANALOG_PUBLIC_BASE_URL'] &&
117
- globalThis.$fetch) {
118
- return globalThis.$fetch(`${url.pathname}${url.search}`);
119
- }
120
- return firstValueFrom(http.get(`${url.href}`));
121
- }
122
- return {};
123
- },
124
- };
125
- return routeConfig;
126
- }
127
- function isRedirectRouteMeta(routeMeta) {
128
- return !!routeMeta.redirectTo;
129
- }
130
-
131
- // The Zone is currently enabled by default, so we wouldn't need this check.
132
- // However, leaving this open space will be useful if zone.js becomes optional
133
- // in the future. This means we won't have to modify the current code, and it will
134
- // continue to work seamlessly.
135
- const isNgZoneEnabled = typeof Zone !== 'undefined' && !!Zone.root;
136
- function toMarkdownModule(markdownFileFactory) {
137
- return async () => {
138
- const createLoader = () => Promise.all([import('@analogjs/content'), markdownFileFactory()]);
139
- const [{ parseRawContentFile, MarkdownRouteComponent, ContentRenderer }, markdownFile,] = await (isNgZoneEnabled
140
- ? // We are not able to use `runOutsideAngular` because we are not inside
141
- // an injection context to retrieve the `NgZone` instance.
142
- // The `Zone.root.run` is required when the code is running in the
143
- // browser since asynchronous tasks being scheduled in the current context
144
- // are a reason for unnecessary change detection cycles.
145
- Zone.root.run(createLoader)
146
- : createLoader());
147
- const { content, attributes } = parseRawContentFile(markdownFile);
148
- const { title, meta } = attributes;
149
- return {
150
- default: MarkdownRouteComponent,
151
- routeMeta: {
152
- data: { _analogContent: content },
153
- title,
154
- meta,
155
- resolve: {
156
- renderedAnalogContent: async () => {
157
- const contentRenderer = inject(ContentRenderer);
158
- const rendered = await contentRenderer.render(content);
159
- return typeof rendered === 'string'
160
- ? rendered
161
- : rendered.content;
162
- },
163
- },
164
- },
165
- };
166
- };
167
- }
168
-
169
- const ENDPOINT_EXTENSION = '.server.ts';
170
- const APP_DIR = 'src/app';
171
-
172
- /**
173
- * This variable reference is replaced with a glob of all page routes.
174
- */
175
- let ANALOG_ROUTE_FILES = {};
176
- /**
177
- * This variable reference is replaced with a glob of all content routes.
178
- */
179
- let ANALOG_CONTENT_ROUTE_FILES = {};
180
- /**
181
- * A function used to parse list of files and create configuration of routes.
182
- *
183
- * @param files
184
- * @returns Array of routes
185
- */
186
- function createRoutes(files, debug = false) {
187
- const filenames = Object.keys(files);
188
- if (filenames.length === 0) {
189
- return [];
190
- }
191
- // map filenames to raw routes and group them by level
192
- const rawRoutesByLevelMap = filenames.reduce((acc, filename) => {
193
- const rawPath = toRawPath(filename);
194
- const rawSegments = rawPath.split('/');
195
- // nesting level starts at 0
196
- // rawPath: /products => level: 0
197
- // rawPath: /products/:id => level: 1
198
- const level = rawSegments.length - 1;
199
- const rawSegment = rawSegments[level];
200
- const ancestorRawSegments = rawSegments.slice(0, level);
201
- return {
202
- ...acc,
203
- [level]: {
204
- ...acc[level],
205
- [rawPath]: {
206
- filename,
207
- rawSegment,
208
- ancestorRawSegments,
209
- segment: toSegment(rawSegment),
210
- level,
211
- children: [],
212
- },
213
- },
214
- };
215
- }, {});
216
- const allLevels = Object.keys(rawRoutesByLevelMap).map(Number);
217
- const maxLevel = Math.max(...allLevels);
218
- // add each raw route to its parent's children array
219
- for (let level = maxLevel; level > 0; level--) {
220
- const rawRoutesMap = rawRoutesByLevelMap[level];
221
- const rawPaths = Object.keys(rawRoutesMap);
222
- for (const rawPath of rawPaths) {
223
- const rawRoute = rawRoutesMap[rawPath];
224
- const parentRawPath = rawRoute.ancestorRawSegments.join('/');
225
- const parentRawSegmentIndex = rawRoute.ancestorRawSegments.length - 1;
226
- const parentRawSegment = rawRoute.ancestorRawSegments[parentRawSegmentIndex];
227
- // create the parent level and/or raw route if it does not exist
228
- // parent route won't exist for nested routes that don't have a layout route
229
- rawRoutesByLevelMap[level - 1] ||= {};
230
- rawRoutesByLevelMap[level - 1][parentRawPath] ||= {
231
- filename: null,
232
- rawSegment: parentRawSegment,
233
- ancestorRawSegments: rawRoute.ancestorRawSegments.slice(0, parentRawSegmentIndex),
234
- segment: toSegment(parentRawSegment),
235
- level: level - 1,
236
- children: [],
237
- };
238
- rawRoutesByLevelMap[level - 1][parentRawPath].children.push(rawRoute);
239
- }
240
- }
241
- // only take raw routes from the root level
242
- // since they already contain nested routes as their children
243
- const rootRawRoutesMap = rawRoutesByLevelMap[0];
244
- const rawRoutes = Object.keys(rootRawRoutesMap).map((segment) => rootRawRoutesMap[segment]);
245
- sortRawRoutes(rawRoutes);
246
- return toRoutes(rawRoutes, files, debug);
247
- }
248
- function toRawPath(filename) {
249
- return (filename
250
- .replace(
251
- // convert to relative path and remove file extension
252
- /^(?:[a-zA-Z]:[\\/])?(.*?)[\\/](?:routes|pages)[\\/]|(?:[\\/](?:app[\\/](?:routes|pages)|src[\\/]content)[\\/])|(\.page\.(js|ts|analog|ag)$)|(\.(ts|md|analog|ag)$)/g, '')
253
- // [[...slug]] => placeholder (named empty) which is stripped by toSegment
254
- .replace(/\[\[\.\.\.([^\]]+)\]\]/g, '(opt-$1)')
255
- .replace(/\[\.{3}.+\]/, '**') // [...not-found] => **
256
- .replace(/\[([^\]]+)\]/g, ':$1')); // [id] => :id
257
- }
258
- function toSegment(rawSegment) {
259
- return rawSegment
260
- .replace(/index|\(.*?\)/g, '') // replace named empty segments
261
- .replace(/\.|\/+/g, '/') // replace dots with slashes and remove redundant slashes
262
- .replace(/^\/+|\/+$/g, ''); // remove trailing slashes
263
- }
264
- function createOptionalCatchAllMatcher(paramName) {
265
- return (segments) => {
266
- if (segments.length === 0) {
267
- return null;
268
- }
269
- const joined = segments.map((s) => s.path).join('/');
270
- return {
271
- consumed: segments,
272
- posParams: { [paramName]: new UrlSegment(joined, {}) },
273
- };
274
- };
275
- }
276
- function toRoutes(rawRoutes, files, debug = false) {
277
- const routes = [];
278
- for (const rawRoute of rawRoutes) {
279
- const children = rawRoute.children.length > 0
280
- ? toRoutes(rawRoute.children, files, debug)
281
- : undefined;
282
- let module = undefined;
283
- let analogMeta = undefined;
284
- if (rawRoute.filename) {
285
- const isMarkdownFile = rawRoute.filename.endsWith('.md');
286
- if (!debug) {
287
- module = isMarkdownFile
288
- ? toMarkdownModule(files[rawRoute.filename])
289
- : files[rawRoute.filename];
290
- }
291
- const endpointKey = rawRoute.filename.replace(/\.page\.(ts|analog|ag)$/, ENDPOINT_EXTENSION);
292
- // get endpoint path
293
- const rawEndpoint = rawRoute.filename
294
- .replace(/\.page\.(ts|analog|ag)$/, '')
295
- .replace(/\[\[\.\.\..+\]\]/, '**')
296
- .replace(/\[\.{3}.+\]/, '**') // [...not-found] => **
297
- .replace(/^(.*?)\/pages/, '/pages');
298
- // replace periods, remove (index) paths
299
- const endpoint = (rawEndpoint || '')
300
- .replace(/\./g, '/')
301
- .replace(/\/\((.*?)\)$/, '/-$1-');
302
- analogMeta = {
303
- endpoint,
304
- endpointKey,
305
- };
306
- }
307
- // Detect Next.js-style optional catch-all at this node: [[...param]]
308
- const optCatchAllMatch = rawRoute.filename?.match(/\[\[\.\.\.([^\]]+)\]\]/);
309
- const optCatchAllParam = optCatchAllMatch ? optCatchAllMatch[1] : null;
310
- const route = module
311
- ? {
312
- path: rawRoute.segment,
313
- loadChildren: () => module().then((m) => {
314
- if (import.meta.env.DEV) {
315
- const hasModuleDefault = !!m.default;
316
- const hasRedirect = !!m.routeMeta?.redirectTo;
317
- if (!hasModuleDefault && !hasRedirect) {
318
- console.warn(`[Analog] Missing default export at ${rawRoute.filename}`);
319
- }
320
- }
321
- const baseChild = {
322
- path: '',
323
- component: m.default,
324
- ...toRouteConfig(m.routeMeta),
325
- children,
326
- [ANALOG_META_KEY]: analogMeta,
327
- };
328
- // Base route first so static matches win, then optional catch-all matcher
329
- return [
330
- {
331
- ...baseChild,
332
- },
333
- ...(optCatchAllParam
334
- ? [
335
- {
336
- matcher: createOptionalCatchAllMatcher(optCatchAllParam),
337
- component: m.default,
338
- ...toRouteConfig(m.routeMeta),
339
- [ANALOG_META_KEY]: analogMeta,
340
- },
341
- ]
342
- : []),
343
- ];
344
- }),
345
- }
346
- : {
347
- path: rawRoute.segment,
348
- ...(debug
349
- ? {
350
- filename: rawRoute.filename ? rawRoute.filename : undefined,
351
- isLayout: children && children.length > 0 ? true : false,
352
- }
353
- : {}),
354
- children,
355
- };
356
- routes.push(route);
357
- }
358
- return routes;
359
- }
360
- function sortRawRoutes(rawRoutes) {
361
- rawRoutes.sort((a, b) => {
362
- let segmentA = deprioritizeSegment(a.segment);
363
- let segmentB = deprioritizeSegment(b.segment);
364
- // prioritize routes with fewer children
365
- if (a.children.length > b.children.length) {
366
- segmentA = `~${segmentA}`;
367
- }
368
- else if (a.children.length < b.children.length) {
369
- segmentB = `~${segmentB}`;
370
- }
371
- return segmentA > segmentB ? 1 : -1;
372
- });
373
- for (const rawRoute of rawRoutes) {
374
- sortRawRoutes(rawRoute.children);
375
- }
376
- }
377
- function deprioritizeSegment(segment) {
378
- // deprioritize param and wildcard segments
379
- return segment.replace(':', '~~').replace('**', '~~~~');
380
- }
381
- const routes = createRoutes({
382
- ...ANALOG_ROUTE_FILES,
383
- ...ANALOG_CONTENT_ROUTE_FILES,
384
- });
385
-
386
- /**
387
- * @deprecated Use `RouteMeta` type instead.
388
- * For more info see: https://github.com/analogjs/analog/issues/223
389
- *
390
- * Defines additional route config metadata. This
391
- * object is merged into the route config with
392
- * the predefined file-based route.
393
- *
394
- * @usageNotes
395
- *
396
- * ```
397
- * import { Component } from '@angular/core';
398
- * import { defineRouteMeta } from '@analogjs/router';
399
- *
400
- * export const routeMeta = defineRouteMeta({
401
- * title: 'Welcome'
402
- * });
403
- *
404
- * @Component({
405
- * template: `Home`,
406
- * standalone: true,
407
- * })
408
- * export default class HomeComponent {}
409
- * ```
410
- *
411
- * @param route
412
- * @returns
413
- */
1
+ import { a as ANALOG_META_KEY, i as injectRouteEndpointURL, n as createRoutes, o as updateMetaTagsOnRouteChange, r as routes, t as injectDebugRoutes } from "./analogjs-router-routes-L2tt-0ms.mjs";
2
+ import * as i1 from "@angular/router";
3
+ import { ActivatedRoute, DefaultUrlSerializer, PRIMARY_OUTLET, ROUTES, Router, RouterLink, UrlSegment, UrlSegmentGroup, UrlTree, provideRouter } from "@angular/router";
4
+ import * as i0 from "@angular/core";
5
+ import { Directive, ENVIRONMENT_INITIALIZER, ElementRef, Injectable, InjectionToken, Injector, PLATFORM_ID, Renderer2, TransferState, assertInInjectionContext, booleanAttribute, effect, inject, input, makeEnvironmentProviders, makeStateKey, output, resource, runInInjectionContext, signal } from "@angular/core";
6
+ import { HttpClient, HttpHeaders, HttpResponse, ɵHTTP_ROOT_INTERCEPTOR_FNS } from "@angular/common/http";
7
+ import { combineLatest, firstValueFrom, from, map, of } from "rxjs";
8
+ import { API_PREFIX, injectAPIPrefix, injectBaseURL, injectRequest } from "@analogjs/router/tokens";
9
+ import { isPlatformServer } from "@angular/common";
10
+ import { toSignal } from "@angular/core/rxjs-interop";
414
11
  const defineRouteMeta = (route) => {
415
- return route;
12
+ return route;
416
13
  };
417
- /**
418
- * Returns the instance of Angular Router
419
- *
420
- * @returns The router
421
- */
422
14
  const injectRouter = () => {
423
- return inject(Router);
15
+ return inject(Router);
424
16
  };
425
- /**
426
- * Returns the instance of the Activate Route for the component
427
- *
428
- * @returns The activated route
429
- */
430
17
  const injectActivatedRoute = () => {
431
- return inject(ActivatedRoute);
18
+ return inject(ActivatedRoute);
432
19
  };
433
-
434
20
  function cookieInterceptor(req, next, location = inject(PLATFORM_ID), serverRequest = injectRequest()) {
435
- if (isPlatformServer(location) && req.url.includes('/_analog/')) {
436
- let headers = new HttpHeaders();
437
- const cookies = serverRequest?.headers.cookie;
438
- headers = headers.set('cookie', cookies ?? '');
439
- const cookiedRequest = req.clone({
440
- headers,
441
- });
442
- return next(cookiedRequest);
443
- }
444
- else {
445
- return next(req);
446
- }
21
+ if (isPlatformServer(location) && req.url.includes("/_analog/")) {
22
+ let headers = new HttpHeaders();
23
+ const cookies = serverRequest?.headers.cookie;
24
+ headers = headers.set("cookie", cookies ?? "");
25
+ return next(req.clone({ headers }));
26
+ } else return next(req);
447
27
  }
448
-
449
- /**
450
- * Sets up providers for the Angular router, and registers
451
- * file-based routes. Additional features can be provided
452
- * to further configure the behavior of the router.
453
- *
454
- * @param features
455
- * @returns Providers and features to configure the router with routes
456
- */
457
28
  function provideFileRouter(...features) {
458
- const extraRoutesFeature = features.filter((feat) => feat.ɵkind >= 100);
459
- const routerFeatures = features.filter((feat) => feat.ɵkind < 100);
460
- return makeEnvironmentProviders([
461
- extraRoutesFeature.map((erf) => erf.ɵproviders),
462
- provideRouter(routes, ...routerFeatures),
463
- {
464
- provide: ENVIRONMENT_INITIALIZER,
465
- multi: true,
466
- useValue: () => updateMetaTagsOnRouteChange(),
467
- },
468
- {
469
- provide: _HTTP_ROOT_INTERCEPTOR_FNS,
470
- multi: true,
471
- useValue: cookieInterceptor,
472
- },
473
- {
474
- provide: API_PREFIX,
475
- useFactory() {
476
- return typeof ANALOG_API_PREFIX !== 'undefined'
477
- ? ANALOG_API_PREFIX
478
- : 'api';
479
- },
480
- },
481
- ]);
29
+ const extraRoutesFeature = features.filter((feat) => feat.ɵkind >= 100);
30
+ const routerFeatures = features.filter((feat) => feat.ɵkind < 100);
31
+ return makeEnvironmentProviders([
32
+ extraRoutesFeature.map((erf) => erf.ɵproviders),
33
+ provideRouter(routes, ...routerFeatures),
34
+ {
35
+ provide: ENVIRONMENT_INITIALIZER,
36
+ multi: true,
37
+ useValue: () => updateMetaTagsOnRouteChange()
38
+ },
39
+ {
40
+ provide: ɵHTTP_ROOT_INTERCEPTOR_FNS,
41
+ multi: true,
42
+ useValue: cookieInterceptor
43
+ },
44
+ {
45
+ provide: API_PREFIX,
46
+ useFactory() {
47
+ return typeof ANALOG_API_PREFIX !== "undefined" ? ANALOG_API_PREFIX : "api";
48
+ }
49
+ }
50
+ ]);
482
51
  }
483
- /**
484
- * Provides extra custom routes in addition to the routes
485
- * discovered from the filesystem-based routing. These routes are
486
- * inserted before the filesystem-based routes, and take priority in
487
- * route matching.
488
- */
489
52
  function withExtraRoutes(routes) {
490
- return {
491
- ɵkind: 100,
492
- ɵproviders: [{ provide: ROUTES, useValue: routes, multi: true }],
493
- };
53
+ return {
54
+ ɵkind: 100,
55
+ ɵproviders: [{
56
+ provide: ROUTES,
57
+ useValue: routes,
58
+ multi: true
59
+ }]
60
+ };
494
61
  }
495
-
496
62
  function injectLoad(options) {
497
- const injector = options?.injector ?? inject(Injector);
498
- const route = injector.get(ActivatedRoute);
499
- return route.data.pipe(map((data) => data['load']));
63
+ return (options?.injector ?? inject(Injector)).get(ActivatedRoute).data.pipe(map((data) => data["load"]));
500
64
  }
501
-
502
- /**
503
- * Get server load resolver data for the route
504
- *
505
- * @param route Provides the route to get server load resolver
506
- * @returns Returns server load resolver data for the route
507
- */
508
65
  async function getLoadResolver(route) {
509
- return route.routeConfig?.resolve?.['load']?.(route);
66
+ return route.routeConfig?.resolve?.["load"]?.(route);
510
67
  }
511
-
512
- // Length-prefix each atom (netstring style) so no field, parameter key, or
513
- // parameter value can be crafted to shift another's boundary. Without this a
514
- // hash over delimiter-joined fields still collides on ambiguous inputs, e.g.
515
- // `?tag=x&tag=y` and `?tag=x,y` both serialize to `tag=x,y`.
516
68
  function encodeAtom(value) {
517
- return `${value.length}:${value}`;
69
+ return `${value.length}:${value}`;
518
70
  }
519
71
  function sortAndConcatParams(params) {
520
- const keys = [...new Set(params.keys())].sort();
521
- const atoms = [];
522
- for (const key of keys) {
523
- for (const value of params.getAll(key) ?? []) {
524
- atoms.push(encodeAtom(key), encodeAtom(value));
525
- }
526
- }
527
- return atoms.join('');
72
+ const keys = [...new Set(params.keys())].sort();
73
+ const atoms = [];
74
+ for (const key of keys) for (const value of params.getAll(key) ?? []) atoms.push(encodeAtom(key), encodeAtom(value));
75
+ return atoms.join("");
528
76
  }
529
77
  function makeCacheKey(request, mappedRequestUrl) {
530
- const { params, method, responseType } = request;
531
- const encodedParams = sortAndConcatParams(params);
532
- let serializedBody = request.serializeBody();
533
- if (serializedBody instanceof URLSearchParams) {
534
- serializedBody = sortAndConcatParams(serializedBody);
535
- }
536
- else if (typeof serializedBody !== 'string') {
537
- serializedBody = '';
538
- }
539
- const key = [
540
- method,
541
- responseType,
542
- mappedRequestUrl,
543
- serializedBody,
544
- encodedParams,
545
- ]
546
- .map(encodeAtom)
547
- .join('');
548
- const hash = generateHash(key);
549
- return makeStateKey(hash);
78
+ const { params, method, responseType } = request;
79
+ const encodedParams = sortAndConcatParams(params);
80
+ let serializedBody = request.serializeBody();
81
+ if (serializedBody instanceof URLSearchParams) serializedBody = sortAndConcatParams(serializedBody);
82
+ else if (typeof serializedBody !== "string") serializedBody = "";
83
+ return makeStateKey(generateHash([
84
+ method,
85
+ responseType,
86
+ mappedRequestUrl,
87
+ serializedBody,
88
+ encodedParams
89
+ ].map(encodeAtom).join("")));
550
90
  }
551
- /**
552
- * SHA-256 round constants (first 32 bits of the fractional parts of the cube
553
- * roots of the first 64 primes).
554
- */
555
91
  const SHA256_ROUND_CONSTANTS = /* @__PURE__ */ new Uint32Array([
556
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
557
- 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
558
- 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
559
- 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
560
- 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
561
- 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
562
- 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
563
- 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
564
- 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
565
- 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
566
- 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
92
+ 1116352408,
93
+ 1899447441,
94
+ 3049323471,
95
+ 3921009573,
96
+ 961987163,
97
+ 1508970993,
98
+ 2453635748,
99
+ 2870763221,
100
+ 3624381080,
101
+ 310598401,
102
+ 607225278,
103
+ 1426881987,
104
+ 1925078388,
105
+ 2162078206,
106
+ 2614888103,
107
+ 3248222580,
108
+ 3835390401,
109
+ 4022224774,
110
+ 264347078,
111
+ 604807628,
112
+ 770255983,
113
+ 1249150122,
114
+ 1555081692,
115
+ 1996064986,
116
+ 2554220882,
117
+ 2821834349,
118
+ 2952996808,
119
+ 3210313671,
120
+ 3336571891,
121
+ 3584528711,
122
+ 113926993,
123
+ 338241895,
124
+ 666307205,
125
+ 773529912,
126
+ 1294757372,
127
+ 1396182291,
128
+ 1695183700,
129
+ 1986661051,
130
+ 2177026350,
131
+ 2456956037,
132
+ 2730485921,
133
+ 2820302411,
134
+ 3259730800,
135
+ 3345764771,
136
+ 3516065817,
137
+ 3600352804,
138
+ 4094571909,
139
+ 275423344,
140
+ 430227734,
141
+ 506948616,
142
+ 659060556,
143
+ 883997877,
144
+ 958139571,
145
+ 1322822218,
146
+ 1537002063,
147
+ 1747873779,
148
+ 1955562222,
149
+ 2024104815,
150
+ 2227730452,
151
+ 2361852424,
152
+ 2428436474,
153
+ 2756734187,
154
+ 3204031479,
155
+ 3329325298
567
156
  ]);
568
157
  let textEncoder;
569
- /**
570
- * Generates a SHA-256 hash of a string. This mirrors Angular's `HttpTransferCache`
571
- * key derivation: a synchronous SHA-256 is used because the Web Crypto API is
572
- * asynchronous, whereas cache-key derivation in the interceptor must stay
573
- * synchronous. The previous 32-bit DJB2 hash had a keyspace small enough for an
574
- * attacker to craft colliding requests and poison the transfer cache.
575
- */
576
158
  function generateHash(value) {
577
- textEncoder ??= new TextEncoder();
578
- const inputBytes = textEncoder.encode(value);
579
- // Initial hash values (first 32 bits of the fractional parts of the square
580
- // roots of the first 8 primes).
581
- let hashState0 = 0x6a09e667;
582
- let hashState1 = 0xbb67ae85;
583
- let hashState2 = 0x3c6ef372;
584
- let hashState3 = 0xa54ff53a;
585
- let hashState4 = 0x510e527f;
586
- let hashState5 = 0x9b05688c;
587
- let hashState6 = 0x1f83d9ab;
588
- let hashState7 = 0x5be0cd19;
589
- const messageLengthInBits = inputBytes.length * 8;
590
- const paddedLengthInBytes = (((inputBytes.length + 8) >> 6) + 1) << 6;
591
- const paddedBytes = new Uint8Array(paddedLengthInBytes);
592
- paddedBytes.set(inputBytes);
593
- paddedBytes[inputBytes.length] = 0x80;
594
- const paddedBytesView = new DataView(paddedBytes.buffer);
595
- const lowBits = messageLengthInBits >>> 0;
596
- const highBits = (messageLengthInBits / 0x100000000) >>> 0;
597
- paddedBytesView.setUint32(paddedLengthInBytes - 8, highBits, false);
598
- paddedBytesView.setUint32(paddedLengthInBytes - 4, lowBits, false);
599
- const messageSchedule = new Uint32Array(64);
600
- for (let chunkOffset = 0; chunkOffset < paddedLengthInBytes; chunkOffset += 64) {
601
- for (let i = 0; i < 16; i++) {
602
- messageSchedule[i] = paddedBytesView.getUint32(chunkOffset + i * 4, false);
603
- }
604
- for (let i = 16; i < 64; i++) {
605
- const prevWord15 = messageSchedule[i - 15];
606
- const sigma0 = (((prevWord15 >>> 7) | (prevWord15 << 25)) ^
607
- ((prevWord15 >>> 18) | (prevWord15 << 14)) ^
608
- (prevWord15 >>> 3)) >>>
609
- 0;
610
- const prevWord2 = messageSchedule[i - 2];
611
- const sigma1 = (((prevWord2 >>> 17) | (prevWord2 << 15)) ^
612
- ((prevWord2 >>> 19) | (prevWord2 << 13)) ^
613
- (prevWord2 >>> 10)) >>>
614
- 0;
615
- messageSchedule[i] =
616
- (messageSchedule[i - 16] + sigma0 + messageSchedule[i - 7] + sigma1) >>>
617
- 0;
618
- }
619
- let workingStateA = hashState0;
620
- let workingStateB = hashState1;
621
- let workingStateC = hashState2;
622
- let workingStateD = hashState3;
623
- let workingStateE = hashState4;
624
- let workingStateF = hashState5;
625
- let workingStateG = hashState6;
626
- let workingStateH = hashState7;
627
- for (let i = 0; i < 64; i++) {
628
- const capitalSigma1 = (((workingStateE >>> 6) | (workingStateE << 26)) ^
629
- ((workingStateE >>> 11) | (workingStateE << 21)) ^
630
- ((workingStateE >>> 25) | (workingStateE << 7))) >>>
631
- 0;
632
- const chFunction = ((workingStateE & workingStateF) ^ (~workingStateE & workingStateG)) >>>
633
- 0;
634
- const temp1 = (workingStateH +
635
- capitalSigma1 +
636
- chFunction +
637
- SHA256_ROUND_CONSTANTS[i] +
638
- messageSchedule[i]) >>>
639
- 0;
640
- const capitalSigma0 = (((workingStateA >>> 2) | (workingStateA << 30)) ^
641
- ((workingStateA >>> 13) | (workingStateA << 19)) ^
642
- ((workingStateA >>> 22) | (workingStateA << 10))) >>>
643
- 0;
644
- const majFunction = ((workingStateA & workingStateB) ^
645
- (workingStateA & workingStateC) ^
646
- (workingStateB & workingStateC)) >>>
647
- 0;
648
- const temp2 = (capitalSigma0 + majFunction) >>> 0;
649
- workingStateH = workingStateG;
650
- workingStateG = workingStateF;
651
- workingStateF = workingStateE;
652
- workingStateE = (workingStateD + temp1) >>> 0;
653
- workingStateD = workingStateC;
654
- workingStateC = workingStateB;
655
- workingStateB = workingStateA;
656
- workingStateA = (temp1 + temp2) >>> 0;
657
- }
658
- hashState0 = (hashState0 + workingStateA) >>> 0;
659
- hashState1 = (hashState1 + workingStateB) >>> 0;
660
- hashState2 = (hashState2 + workingStateC) >>> 0;
661
- hashState3 = (hashState3 + workingStateD) >>> 0;
662
- hashState4 = (hashState4 + workingStateE) >>> 0;
663
- hashState5 = (hashState5 + workingStateF) >>> 0;
664
- hashState6 = (hashState6 + workingStateG) >>> 0;
665
- hashState7 = (hashState7 + workingStateH) >>> 0;
666
- }
667
- return [
668
- hashState0,
669
- hashState1,
670
- hashState2,
671
- hashState3,
672
- hashState4,
673
- hashState5,
674
- hashState6,
675
- hashState7,
676
- ]
677
- .map((x) => x.toString(16).padStart(8, '0'))
678
- .join('');
159
+ textEncoder ??= new TextEncoder();
160
+ const inputBytes = textEncoder.encode(value);
161
+ let hashState0 = 1779033703;
162
+ let hashState1 = 3144134277;
163
+ let hashState2 = 1013904242;
164
+ let hashState3 = 2773480762;
165
+ let hashState4 = 1359893119;
166
+ let hashState5 = 2600822924;
167
+ let hashState6 = 528734635;
168
+ let hashState7 = 1541459225;
169
+ const messageLengthInBits = inputBytes.length * 8;
170
+ const paddedLengthInBytes = (inputBytes.length + 8 >> 6) + 1 << 6;
171
+ const paddedBytes = new Uint8Array(paddedLengthInBytes);
172
+ paddedBytes.set(inputBytes);
173
+ paddedBytes[inputBytes.length] = 128;
174
+ const paddedBytesView = new DataView(paddedBytes.buffer);
175
+ const lowBits = messageLengthInBits >>> 0;
176
+ const highBits = messageLengthInBits / 4294967296 >>> 0;
177
+ paddedBytesView.setUint32(paddedLengthInBytes - 8, highBits, false);
178
+ paddedBytesView.setUint32(paddedLengthInBytes - 4, lowBits, false);
179
+ const messageSchedule = /* @__PURE__ */ new Uint32Array(64);
180
+ for (let chunkOffset = 0; chunkOffset < paddedLengthInBytes; chunkOffset += 64) {
181
+ for (let i = 0; i < 16; i++) messageSchedule[i] = paddedBytesView.getUint32(chunkOffset + i * 4, false);
182
+ for (let i = 16; i < 64; i++) {
183
+ const prevWord15 = messageSchedule[i - 15];
184
+ const sigma0 = ((prevWord15 >>> 7 | prevWord15 << 25) ^ (prevWord15 >>> 18 | prevWord15 << 14) ^ prevWord15 >>> 3) >>> 0;
185
+ const prevWord2 = messageSchedule[i - 2];
186
+ const sigma1 = ((prevWord2 >>> 17 | prevWord2 << 15) ^ (prevWord2 >>> 19 | prevWord2 << 13) ^ prevWord2 >>> 10) >>> 0;
187
+ messageSchedule[i] = messageSchedule[i - 16] + sigma0 + messageSchedule[i - 7] + sigma1 >>> 0;
188
+ }
189
+ let workingStateA = hashState0;
190
+ let workingStateB = hashState1;
191
+ let workingStateC = hashState2;
192
+ let workingStateD = hashState3;
193
+ let workingStateE = hashState4;
194
+ let workingStateF = hashState5;
195
+ let workingStateG = hashState6;
196
+ let workingStateH = hashState7;
197
+ for (let i = 0; i < 64; i++) {
198
+ const capitalSigma1 = ((workingStateE >>> 6 | workingStateE << 26) ^ (workingStateE >>> 11 | workingStateE << 21) ^ (workingStateE >>> 25 | workingStateE << 7)) >>> 0;
199
+ const chFunction = (workingStateE & workingStateF ^ ~workingStateE & workingStateG) >>> 0;
200
+ const temp1 = workingStateH + capitalSigma1 + chFunction + SHA256_ROUND_CONSTANTS[i] + messageSchedule[i] >>> 0;
201
+ const temp2 = (((workingStateA >>> 2 | workingStateA << 30) ^ (workingStateA >>> 13 | workingStateA << 19) ^ (workingStateA >>> 22 | workingStateA << 10)) >>> 0) + ((workingStateA & workingStateB ^ workingStateA & workingStateC ^ workingStateB & workingStateC) >>> 0) >>> 0;
202
+ workingStateH = workingStateG;
203
+ workingStateG = workingStateF;
204
+ workingStateF = workingStateE;
205
+ workingStateE = workingStateD + temp1 >>> 0;
206
+ workingStateD = workingStateC;
207
+ workingStateC = workingStateB;
208
+ workingStateB = workingStateA;
209
+ workingStateA = temp1 + temp2 >>> 0;
210
+ }
211
+ hashState0 = hashState0 + workingStateA >>> 0;
212
+ hashState1 = hashState1 + workingStateB >>> 0;
213
+ hashState2 = hashState2 + workingStateC >>> 0;
214
+ hashState3 = hashState3 + workingStateD >>> 0;
215
+ hashState4 = hashState4 + workingStateE >>> 0;
216
+ hashState5 = hashState5 + workingStateF >>> 0;
217
+ hashState6 = hashState6 + workingStateG >>> 0;
218
+ hashState7 = hashState7 + workingStateH >>> 0;
219
+ }
220
+ return [
221
+ hashState0,
222
+ hashState1,
223
+ hashState2,
224
+ hashState3,
225
+ hashState4,
226
+ hashState5,
227
+ hashState6,
228
+ hashState7
229
+ ].map((x) => x.toString(16).padStart(8, "0")).join("");
679
230
  }
680
-
681
- /**
682
- * Interceptor that is server-aware when making HttpClient requests.
683
- * Server-side requests use the full URL
684
- * Prerendering uses the internal Nitro $fetch function, along with state transfer
685
- * Client-side requests use the window.location.origin
686
- *
687
- * @param req HttpRequest<unknown>
688
- * @param next HttpHandlerFn
689
- * @returns
690
- */
691
231
  function requestContextInterceptor(req, next) {
692
- const apiPrefix = injectAPIPrefix();
693
- const baseUrl = injectBaseURL();
694
- const transferState = inject(TransferState);
695
- // during prerendering with Nitro
696
- if (typeof global !== 'undefined' &&
697
- global.$fetch &&
698
- baseUrl &&
699
- (req.url.startsWith('/') ||
700
- req.url.startsWith(baseUrl) ||
701
- req.url.startsWith(`/${apiPrefix}`))) {
702
- const requestUrl = new URL(req.urlWithParams, baseUrl);
703
- const fetchUrl = `${requestUrl.pathname}${requestUrl.search}`;
704
- const cacheKey = makeCacheKey(req, fetchUrl);
705
- const storeKey = makeStateKey(`analog_${cacheKey}`);
706
- const responseType = req.responseType === 'arraybuffer' ? 'arrayBuffer' : req.responseType;
707
- return from(global.$fetch
708
- .raw(fetchUrl, {
709
- method: req.method,
710
- body: req.body ? req.body : undefined,
711
- responseType,
712
- headers: req.headers.keys().reduce((hdrs, current) => {
713
- return {
714
- ...hdrs,
715
- [current]: req.headers.get(current),
716
- };
717
- }, {}),
718
- })
719
- .then((res) => {
720
- const cacheResponse = {
721
- body: res._data,
722
- headers: new HttpHeaders(res.headers),
723
- status: 200,
724
- statusText: 'OK',
725
- url: fetchUrl,
726
- };
727
- const transferResponse = new HttpResponse(cacheResponse);
728
- transferState.set(storeKey, cacheResponse);
729
- return transferResponse;
730
- }));
731
- }
732
- // on the client
733
- if (!import.meta.env.SSR &&
734
- (req.url.startsWith('/') || req.url.includes('/_analog/'))) {
735
- // /_analog/ requests are full URLs
736
- const toAbsoluteUrl = (url) => new URL(url, window.location.origin);
737
- const requestUrl = toAbsoluteUrl(req.url).href;
738
- const { pathname, search } = toAbsoluteUrl(req.urlWithParams);
739
- const cacheKey = makeCacheKey(req, `${pathname}${search}`);
740
- const storeKey = makeStateKey(`analog_${cacheKey}`);
741
- const cacheRestoreResponse = transferState.get(storeKey, null);
742
- if (cacheRestoreResponse) {
743
- transferState.remove(storeKey);
744
- return of(new HttpResponse(cacheRestoreResponse));
745
- }
746
- return next(req.clone({
747
- url: requestUrl,
748
- }));
749
- }
750
- // on the server
751
- if (baseUrl && (req.url.startsWith('/') || req.url.startsWith(baseUrl))) {
752
- const requestUrl = req.url.startsWith(baseUrl) && !req.url.startsWith('/')
753
- ? req.url
754
- : `${baseUrl}${req.url}`;
755
- return next(req.clone({
756
- url: requestUrl,
757
- }));
758
- }
759
- return next(req);
760
- }
761
-
762
- class FormAction {
763
- constructor() {
764
- this.action = input('', /* @ts-ignore */
765
- ...(ngDevMode ? [{ debugName: "action" }] : /* istanbul ignore next */ []));
766
- this.enhanceForm = input(false, { ...(ngDevMode ? { debugName: "enhanceForm" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
767
- // eslint-disable-next-line @angular-eslint/no-output-on-prefix
768
- this.onSuccess = output();
769
- // eslint-disable-next-line @angular-eslint/no-output-on-prefix
770
- this.onError = output();
771
- this.state = output();
772
- this.currentState = signal('idle', /* @ts-ignore */
773
- ...(ngDevMode ? [{ debugName: "currentState" }] : /* istanbul ignore next */ []));
774
- this.injector = inject(Injector);
775
- this.router = inject(Router);
776
- this.route = inject(ActivatedRoute);
777
- this.path = this._getPath();
778
- const form = inject((ElementRef)).nativeElement;
779
- const renderer = inject(Renderer2);
780
- effect((onCleanup) => {
781
- if (!this.enhanceForm()) {
782
- return;
783
- }
784
- const previous = {
785
- 'data-state': form.getAttribute('data-state'),
786
- 'aria-busy': form.getAttribute('aria-busy'),
787
- };
788
- const state = this.currentState();
789
- renderer.setAttribute(form, 'data-state', state);
790
- if (state === 'submitting') {
791
- renderer.setAttribute(form, 'aria-busy', 'true');
792
- }
793
- else {
794
- renderer.removeAttribute(form, 'aria-busy');
795
- }
796
- onCleanup(() => {
797
- for (const [name, value] of Object.entries(previous)) {
798
- if (value === null) {
799
- renderer.removeAttribute(form, name);
800
- }
801
- else {
802
- renderer.setAttribute(form, name, value);
803
- }
804
- }
805
- });
806
- });
807
- }
808
- submitted($event) {
809
- $event.preventDefault();
810
- this._emitState('submitting');
811
- const body = new FormData($event.target);
812
- if (this.enhanceForm()) {
813
- const form = $event.target;
814
- try {
815
- const action = this.action().trim() || form.getAttribute('action')?.trim();
816
- if (form.method.toUpperCase() === 'GET') {
817
- this._handleEnhancedGet(body, action || this.router.url);
818
- }
819
- else {
820
- const path = action
821
- ? new URL(action, window.location.href).toString()
822
- : this._getPath();
823
- void this._handleEnhancedPost(body, path, form.method);
824
- }
825
- }
826
- catch {
827
- this._emitState('error');
828
- }
829
- return;
830
- }
831
- if ($event.target.method.toUpperCase() === 'GET') {
832
- this._handleGet(body, this.router.url);
833
- }
834
- else {
835
- this._handlePost(body, this.path, $event);
836
- }
837
- }
838
- _handleGet(body, path) {
839
- const params = {};
840
- body.forEach((formVal, formKey) => (params[formKey] = formVal));
841
- this._emitState('navigate');
842
- const url = path.split('?')[0];
843
- this.router.navigate([url], {
844
- queryParams: params,
845
- onSameUrlNavigation: 'reload',
846
- });
847
- }
848
- _handlePost(body, path, $event) {
849
- fetch(path, {
850
- method: $event.target.method,
851
- body,
852
- })
853
- .then((res) => {
854
- if (res.ok) {
855
- if (res.redirected) {
856
- const redirectUrl = new URL(res.url).pathname;
857
- this._emitState('redirect');
858
- this.router.navigate([redirectUrl]);
859
- }
860
- else if (this._isJSON(res.headers.get('Content-type'))) {
861
- res.json().then((result) => {
862
- this.onSuccess.emit(result);
863
- this._emitState('success');
864
- });
865
- }
866
- else {
867
- res.text().then((result) => {
868
- this.onSuccess.emit(result);
869
- this._emitState('success');
870
- });
871
- }
872
- }
873
- else {
874
- if (res.headers.get('X-Analog-Errors')) {
875
- res.json().then((errors) => {
876
- this.onError.emit(errors);
877
- this._emitState('error');
878
- });
879
- }
880
- else {
881
- this._emitState('error');
882
- }
883
- }
884
- })
885
- .catch((_) => {
886
- this._emitState('error');
887
- });
888
- }
889
- _getPath() {
890
- const snapshot = this.route.snapshot;
891
- if (snapshot.routeConfig && ANALOG_META_KEY in snapshot.routeConfig) {
892
- return runInInjectionContext(this.injector, () => injectRouteEndpointURL(snapshot)).pathname;
893
- }
894
- return `/api/_analog/pages${window.location.pathname}`;
895
- }
896
- _handleEnhancedGet(body, path) {
897
- const url = new URL(path, window.location.href);
898
- const params = new URLSearchParams(url.search);
899
- body.forEach((_value, key) => params.delete(key));
900
- body.forEach((value, key) => {
901
- params.append(key, value instanceof File ? value.name : value);
902
- });
903
- url.search = params.toString();
904
- this._emitState('navigate');
905
- this._navigateTo(url);
906
- }
907
- async _handleEnhancedPost(body, path, method) {
908
- try {
909
- const response = await fetch(path, { method, body });
910
- if (response.ok) {
911
- if (response.redirected) {
912
- this._emitState('redirect');
913
- this._navigateTo(new URL(response.url, window.location.href));
914
- }
915
- else {
916
- const result = this._isJSON(response.headers.get('Content-type'))
917
- ? await response.json()
918
- : await response.text();
919
- this.onSuccess.emit(result);
920
- this._emitState('success');
921
- }
922
- }
923
- else {
924
- if (response.headers.get('X-Analog-Errors')) {
925
- this.onError.emit(await response.json());
926
- }
927
- this._emitState('error');
928
- }
929
- }
930
- catch {
931
- this._emitState('error');
932
- }
933
- }
934
- _emitState(state) {
935
- this.currentState.set(state);
936
- this.state.emit(state);
937
- }
938
- _navigateTo(url) {
939
- if (url.origin === window.location.origin) {
940
- void this.router.navigateByUrl(`${url.pathname}${url.search}${url.hash}`, {
941
- onSameUrlNavigation: 'reload',
942
- });
943
- return;
944
- }
945
- window.location.assign(url.toString());
946
- }
947
- _isJSON(contentType) {
948
- const mime = contentType ? contentType.split(';') : [];
949
- const essence = mime[0];
950
- return essence === 'application/json';
951
- }
952
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: FormAction, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
953
- static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.1.5", type: FormAction, isStandalone: true, selector: "form[action],form[method],form[enhanceForm]", inputs: { action: { classPropertyName: "action", publicName: "action", isSignal: true, isRequired: false, transformFunction: null }, enhanceForm: { classPropertyName: "enhanceForm", publicName: "enhanceForm", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { onSuccess: "onSuccess", onError: "onError", state: "state" }, host: { listeners: { "submit": "submitted($event)" } }, ngImport: i0 }); }
954
- }
955
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: FormAction, decorators: [{
956
- type: Directive,
957
- args: [{
958
- // eslint-disable-next-line @angular-eslint/directive-selector
959
- selector: 'form[action],form[method],form[enhanceForm]',
960
- host: {
961
- '(submit)': `submitted($event)`,
962
- },
963
- standalone: true,
964
- }]
965
- }], ctorParameters: () => [], propDecorators: { action: [{ type: i0.Input, args: [{ isSignal: true, alias: "action", required: false }] }], enhanceForm: [{ type: i0.Input, args: [{ isSignal: true, alias: "enhanceForm", required: false }] }], onSuccess: [{ type: i0.Output, args: ["onSuccess"] }], onError: [{ type: i0.Output, args: ["onError"] }], state: [{ type: i0.Output, args: ["state"] }] } });
966
-
232
+ const apiPrefix = injectAPIPrefix();
233
+ const baseUrl = injectBaseURL();
234
+ const transferState = inject(TransferState);
235
+ if (typeof global !== "undefined" && global.$fetch && baseUrl && (req.url.startsWith("/") || req.url.startsWith(baseUrl) || req.url.startsWith(`/${apiPrefix}`))) {
236
+ const requestUrl = new URL(req.urlWithParams, baseUrl);
237
+ const fetchUrl = `${requestUrl.pathname}${requestUrl.search}`;
238
+ const storeKey = makeStateKey(`analog_${makeCacheKey(req, fetchUrl)}`);
239
+ const responseType = req.responseType === "arraybuffer" ? "arrayBuffer" : req.responseType;
240
+ return from(global.$fetch.raw(fetchUrl, {
241
+ method: req.method,
242
+ body: req.body ? req.body : void 0,
243
+ responseType,
244
+ headers: req.headers.keys().reduce((hdrs, current) => {
245
+ return {
246
+ ...hdrs,
247
+ [current]: req.headers.get(current)
248
+ };
249
+ }, {})
250
+ }).then((res) => {
251
+ const cacheResponse = {
252
+ body: res._data,
253
+ headers: new HttpHeaders(res.headers),
254
+ status: 200,
255
+ statusText: "OK",
256
+ url: fetchUrl
257
+ };
258
+ const transferResponse = new HttpResponse(cacheResponse);
259
+ transferState.set(storeKey, cacheResponse);
260
+ return transferResponse;
261
+ }));
262
+ }
263
+ if (!import.meta.env.SSR && (req.url.startsWith("/") || req.url.includes("/_analog/"))) {
264
+ const toAbsoluteUrl = (url) => new URL(url, window.location.origin);
265
+ const requestUrl = toAbsoluteUrl(req.url).href;
266
+ const { pathname, search } = toAbsoluteUrl(req.urlWithParams);
267
+ const storeKey = makeStateKey(`analog_${makeCacheKey(req, `${pathname}${search}`)}`);
268
+ const cacheRestoreResponse = transferState.get(storeKey, null);
269
+ if (cacheRestoreResponse) {
270
+ transferState.remove(storeKey);
271
+ return of(new HttpResponse(cacheRestoreResponse));
272
+ }
273
+ return next(req.clone({ url: requestUrl }));
274
+ }
275
+ if (baseUrl && (req.url.startsWith("/") || req.url.startsWith(baseUrl))) {
276
+ const requestUrl = req.url.startsWith(baseUrl) && !req.url.startsWith("/") ? req.url : `${baseUrl}${req.url}`;
277
+ return next(req.clone({ url: requestUrl }));
278
+ }
279
+ return next(req);
280
+ }
281
+ var FormAction = class FormAction {
282
+ constructor() {
283
+ this.action = input("", ...ngDevMode ? [{ debugName: "action" }] : /* istanbul ignore next */ []);
284
+ this.enhanceForm = input(false, {
285
+ ...ngDevMode ? { debugName: "enhanceForm" } : /* istanbul ignore next */ {},
286
+ transform: booleanAttribute
287
+ });
288
+ this.onSuccess = output();
289
+ this.onError = output();
290
+ this.state = output();
291
+ this.currentState = signal("idle", ...ngDevMode ? [{ debugName: "currentState" }] : /* istanbul ignore next */ []);
292
+ this.injector = inject(Injector);
293
+ this.router = inject(Router);
294
+ this.route = inject(ActivatedRoute);
295
+ this.path = this._getPath();
296
+ const form = inject(ElementRef).nativeElement;
297
+ const renderer = inject(Renderer2);
298
+ effect((onCleanup) => {
299
+ if (!this.enhanceForm()) return;
300
+ const previous = {
301
+ "data-state": form.getAttribute("data-state"),
302
+ "aria-busy": form.getAttribute("aria-busy")
303
+ };
304
+ const state = this.currentState();
305
+ renderer.setAttribute(form, "data-state", state);
306
+ if (state === "submitting") renderer.setAttribute(form, "aria-busy", "true");
307
+ else renderer.removeAttribute(form, "aria-busy");
308
+ onCleanup(() => {
309
+ for (const [name, value] of Object.entries(previous)) if (value === null) renderer.removeAttribute(form, name);
310
+ else renderer.setAttribute(form, name, value);
311
+ });
312
+ });
313
+ }
314
+ submitted($event) {
315
+ $event.preventDefault();
316
+ this._emitState("submitting");
317
+ const body = new FormData($event.target);
318
+ if (this.enhanceForm()) {
319
+ const form = $event.target;
320
+ try {
321
+ const action = this.action().trim() || form.getAttribute("action")?.trim();
322
+ if (form.method.toUpperCase() === "GET") this._handleEnhancedGet(body, action || this.router.url);
323
+ else {
324
+ const path = action ? new URL(action, window.location.href).toString() : this._getPath();
325
+ this._handleEnhancedPost(body, path, form.method);
326
+ }
327
+ } catch {
328
+ this._emitState("error");
329
+ }
330
+ return;
331
+ }
332
+ if ($event.target.method.toUpperCase() === "GET") this._handleGet(body, this.router.url);
333
+ else this._handlePost(body, this.path, $event);
334
+ }
335
+ _handleGet(body, path) {
336
+ const params = {};
337
+ body.forEach((formVal, formKey) => params[formKey] = formVal);
338
+ this._emitState("navigate");
339
+ const url = path.split("?")[0];
340
+ this.router.navigate([url], {
341
+ queryParams: params,
342
+ onSameUrlNavigation: "reload"
343
+ });
344
+ }
345
+ _handlePost(body, path, $event) {
346
+ fetch(path, {
347
+ method: $event.target.method,
348
+ body
349
+ }).then((res) => {
350
+ if (res.ok) if (res.redirected) {
351
+ const redirectUrl = new URL(res.url).pathname;
352
+ this._emitState("redirect");
353
+ this.router.navigate([redirectUrl]);
354
+ } else if (this._isJSON(res.headers.get("Content-type"))) res.json().then((result) => {
355
+ this.onSuccess.emit(result);
356
+ this._emitState("success");
357
+ });
358
+ else res.text().then((result) => {
359
+ this.onSuccess.emit(result);
360
+ this._emitState("success");
361
+ });
362
+ else if (res.headers.get("X-Analog-Errors")) res.json().then((errors) => {
363
+ this.onError.emit(errors);
364
+ this._emitState("error");
365
+ });
366
+ else this._emitState("error");
367
+ }).catch((_) => {
368
+ this._emitState("error");
369
+ });
370
+ }
371
+ _getPath() {
372
+ const snapshot = this.route.snapshot;
373
+ if (snapshot.routeConfig && ANALOG_META_KEY in snapshot.routeConfig) return runInInjectionContext(this.injector, () => injectRouteEndpointURL(snapshot)).pathname;
374
+ return `/api/_analog/pages${window.location.pathname}`;
375
+ }
376
+ _handleEnhancedGet(body, path) {
377
+ const url = new URL(path, window.location.href);
378
+ const params = new URLSearchParams(url.search);
379
+ body.forEach((_value, key) => params.delete(key));
380
+ body.forEach((value, key) => {
381
+ params.append(key, value instanceof File ? value.name : value);
382
+ });
383
+ url.search = params.toString();
384
+ this._emitState("navigate");
385
+ this._navigateTo(url);
386
+ }
387
+ async _handleEnhancedPost(body, path, method) {
388
+ try {
389
+ const response = await fetch(path, {
390
+ method,
391
+ body
392
+ });
393
+ if (response.ok) if (response.redirected) {
394
+ this._emitState("redirect");
395
+ this._navigateTo(new URL(response.url, window.location.href));
396
+ } else {
397
+ const result = this._isJSON(response.headers.get("Content-type")) ? await response.json() : await response.text();
398
+ this.onSuccess.emit(result);
399
+ this._emitState("success");
400
+ }
401
+ else {
402
+ if (response.headers.get("X-Analog-Errors")) this.onError.emit(await response.json());
403
+ this._emitState("error");
404
+ }
405
+ } catch {
406
+ this._emitState("error");
407
+ }
408
+ }
409
+ _emitState(state) {
410
+ this.currentState.set(state);
411
+ this.state.emit(state);
412
+ }
413
+ _navigateTo(url) {
414
+ if (url.origin === window.location.origin) {
415
+ this.router.navigateByUrl(`${url.pathname}${url.search}${url.hash}`, { onSameUrlNavigation: "reload" });
416
+ return;
417
+ }
418
+ window.location.assign(url.toString());
419
+ }
420
+ _isJSON(contentType) {
421
+ return (contentType ? contentType.split(";") : [])[0] === "application/json";
422
+ }
423
+ static {
424
+ this.ɵfac = i0.ɵɵngDeclareFactory({
425
+ minVersion: "12.0.0",
426
+ version: "22.2.0",
427
+ ngImport: i0,
428
+ type: FormAction,
429
+ deps: [],
430
+ target: i0.ɵɵFactoryTarget.Directive
431
+ });
432
+ }
433
+ static {
434
+ this.ɵdir = i0.ɵɵngDeclareDirective({
435
+ minVersion: "17.1.0",
436
+ version: "22.2.0",
437
+ type: FormAction,
438
+ isStandalone: true,
439
+ selector: "form[action],form[method],form[enhanceForm]",
440
+ inputs: {
441
+ action: {
442
+ classPropertyName: "action",
443
+ publicName: "action",
444
+ isSignal: true,
445
+ isRequired: false,
446
+ transformFunction: null
447
+ },
448
+ enhanceForm: {
449
+ classPropertyName: "enhanceForm",
450
+ publicName: "enhanceForm",
451
+ isSignal: true,
452
+ isRequired: false,
453
+ transformFunction: null
454
+ }
455
+ },
456
+ outputs: {
457
+ onSuccess: "onSuccess",
458
+ onError: "onError",
459
+ state: "state"
460
+ },
461
+ host: { listeners: { "submit": "submitted($event)" } },
462
+ ngImport: i0
463
+ });
464
+ }
465
+ };
466
+ i0.ɵɵngDeclareClassMetadata({
467
+ minVersion: "12.0.0",
468
+ version: "22.2.0",
469
+ ngImport: i0,
470
+ type: FormAction,
471
+ decorators: [{
472
+ type: Directive,
473
+ args: [{
474
+ selector: "form[action],form[method],form[enhanceForm]",
475
+ host: { "(submit)": `submitted($event)` },
476
+ standalone: true
477
+ }]
478
+ }],
479
+ ctorParameters: () => [],
480
+ propDecorators: {
481
+ action: [{
482
+ type: i0.Input,
483
+ args: [{
484
+ isSignal: true,
485
+ alias: "action",
486
+ required: false
487
+ }]
488
+ }],
489
+ enhanceForm: [{
490
+ type: i0.Input,
491
+ args: [{
492
+ isSignal: true,
493
+ alias: "enhanceForm",
494
+ required: false
495
+ }]
496
+ }],
497
+ onSuccess: [{
498
+ type: i0.Output,
499
+ args: ["onSuccess"]
500
+ }],
501
+ onError: [{
502
+ type: i0.Output,
503
+ args: ["onError"]
504
+ }],
505
+ state: [{
506
+ type: i0.Output,
507
+ args: ["state"]
508
+ }]
509
+ }
510
+ });
967
511
  function getPathSegmentKey(segment) {
968
- return typeof segment === 'object' ? segment.key : segment;
512
+ return typeof segment === "object" ? segment.key : segment;
969
513
  }
970
514
  function issuePathToFieldName(path) {
971
- return path.map((segment) => String(getPathSegmentKey(segment))).join('.');
515
+ return path.map((segment) => String(getPathSegmentKey(segment))).join(".");
972
516
  }
973
517
  function issuesToFieldErrors(issues) {
974
- return issues.reduce((errors, issue) => {
975
- if (!issue.path?.length) {
976
- return errors;
977
- }
978
- const fieldName = issuePathToFieldName(issue.path);
979
- errors[fieldName] ??= [];
980
- errors[fieldName].push(issue.message);
981
- return errors;
982
- }, Object.create(null));
518
+ return issues.reduce((errors, issue) => {
519
+ if (!issue.path?.length) return errors;
520
+ const fieldName = issuePathToFieldName(issue.path);
521
+ errors[fieldName] ??= [];
522
+ errors[fieldName].push(issue.message);
523
+ return errors;
524
+ }, Object.create(null));
983
525
  }
984
526
  function issuesToFormErrors(issues) {
985
- return issues
986
- .filter((issue) => !issue.path?.length)
987
- .map((issue) => issue.message);
988
- }
989
-
990
- const DEBUG_ROUTES = new InjectionToken('@analogjs/router debug routes', {
991
- providedIn: 'root',
992
- factory() {
993
- const debugRoutes = createRoutes({
994
- ...ANALOG_ROUTE_FILES,
995
- ...ANALOG_CONTENT_ROUTE_FILES,
996
- }, true);
997
- return debugRoutes;
998
- },
999
- });
1000
- function injectDebugRoutes() {
1001
- return inject(DEBUG_ROUTES);
527
+ return issues.filter((issue) => !issue.path?.length).map((issue) => issue.message);
1002
528
  }
1003
-
1004
- /**
1005
- * Provides routes that provide additional
1006
- * pages for displaying and debugging
1007
- * routes.
1008
- */
1009
529
  function withDebugRoutes() {
1010
- const routes = [
1011
- {
1012
- path: '__analog/routes',
1013
- loadComponent: () => import('./analogjs-router-debug.page-COcFkgRu.mjs'),
1014
- },
1015
- ];
1016
- return {
1017
- ɵkind: 101,
1018
- ɵproviders: [{ provide: ROUTES, useValue: routes, multi: true }],
1019
- };
1020
- }
1021
-
1022
- const SERVER_FN_DISPATCHER = new InjectionToken('@analogjs/router Server Function Dispatcher');
1023
-
1024
- /**
1025
- * Client transport for server functions. In the browser it goes through Angular
1026
- * `HttpClient`, so client `HttpInterceptorFn`s apply. During SSR the dispatcher
1027
- * token is provided, and the call short-circuits the HTTP round-trip: the
1028
- * handler runs in-process in the current request injector. Lives in the client
1029
- * entry (client-safe).
1030
- */
1031
- class ServerFnClient {
1032
- constructor() {
1033
- this.http = inject(HttpClient);
1034
- this.transferState = inject(TransferState);
1035
- this.injector = inject(Injector);
1036
- this.dispatcher = inject(SERVER_FN_DISPATCHER, {
1037
- optional: true,
1038
- });
1039
- }
1040
- /** True while rendering on the server (the in-process dispatcher is provided). */
1041
- get isServer() {
1042
- return !!this.dispatcher;
1043
- }
1044
- async call(fn, input) {
1045
- if (this.dispatcher) {
1046
- return this.dispatcher(fn, input, this.injector);
1047
- }
1048
- const request$ = fn.method === 'GET'
1049
- ? this.http.get(fn.url)
1050
- : this.http.post(fn.url, input ?? {});
1051
- return firstValueFrom(request$);
1052
- }
1053
- /** Key a read's value for TransferState hydration (fn id + input). */
1054
- stateKey(fn, input) {
1055
- return makeStateKey(`__analog_fn_${fn.id}_${stableInput(input)}`);
1056
- }
1057
- readSeed(fn, input) {
1058
- const key = this.stateKey(fn, input);
1059
- if (this.transferState.hasKey(key)) {
1060
- const value = this.transferState.get(key, undefined);
1061
- this.transferState.remove(key); // single-use
1062
- return value;
1063
- }
1064
- return undefined;
1065
- }
1066
- writeSeed(fn, input, value) {
1067
- this.transferState.set(this.stateKey(fn, input), value);
1068
- }
1069
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: ServerFnClient, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1070
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: ServerFnClient, providedIn: 'root' }); }
1071
- }
1072
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: ServerFnClient, decorators: [{
1073
- type: Injectable,
1074
- args: [{ providedIn: 'root' }]
1075
- }] });
1076
- /** No-op provider hook; ServerFnClient is `providedIn: 'root'`. */
530
+ return {
531
+ ɵkind: 101,
532
+ ɵproviders: [{
533
+ provide: ROUTES,
534
+ useValue: [{
535
+ path: "__analog/routes",
536
+ loadComponent: () => import("./analogjs-router-debug.page-MFY2u07E.mjs")
537
+ }],
538
+ multi: true
539
+ }]
540
+ };
541
+ }
542
+ const SERVER_FN_DISPATCHER = new InjectionToken("@analogjs/router Server Function Dispatcher");
543
+ var ServerFnClient = class ServerFnClient {
544
+ constructor() {
545
+ this.http = inject(HttpClient);
546
+ this.transferState = inject(TransferState);
547
+ this.injector = inject(Injector);
548
+ this.dispatcher = inject(SERVER_FN_DISPATCHER, { optional: true });
549
+ }
550
+ get isServer() {
551
+ return !!this.dispatcher;
552
+ }
553
+ async call(fn, input) {
554
+ if (this.dispatcher) return this.dispatcher(fn, input, this.injector);
555
+ return firstValueFrom(fn.method === "GET" ? this.http.get(fn.url) : this.http.post(fn.url, input ?? {}));
556
+ }
557
+ stateKey(fn, input) {
558
+ return makeStateKey(`__analog_fn_${fn.id}_${stableInput(input)}`);
559
+ }
560
+ readSeed(fn, input) {
561
+ const key = this.stateKey(fn, input);
562
+ if (this.transferState.hasKey(key)) {
563
+ const value = this.transferState.get(key, void 0);
564
+ this.transferState.remove(key);
565
+ return value;
566
+ }
567
+ }
568
+ writeSeed(fn, input, value) {
569
+ this.transferState.set(this.stateKey(fn, input), value);
570
+ }
571
+ static {
572
+ this.ɵfac = i0.ɵɵngDeclareFactory({
573
+ minVersion: "12.0.0",
574
+ version: "22.2.0",
575
+ ngImport: i0,
576
+ type: ServerFnClient,
577
+ deps: [],
578
+ target: i0.ɵɵFactoryTarget.Injectable
579
+ });
580
+ }
581
+ static {
582
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
583
+ minVersion: "12.0.0",
584
+ version: "22.2.0",
585
+ ngImport: i0,
586
+ type: ServerFnClient,
587
+ providedIn: "root"
588
+ });
589
+ }
590
+ };
591
+ i0.ɵɵngDeclareClassMetadata({
592
+ minVersion: "12.0.0",
593
+ version: "22.2.0",
594
+ ngImport: i0,
595
+ type: ServerFnClient,
596
+ decorators: [{
597
+ type: Injectable,
598
+ args: [{ providedIn: "root" }]
599
+ }]
600
+ });
1077
601
  function provideServerFnClient() {
1078
- return [];
602
+ return [];
1079
603
  }
1080
- // Stable sentinel for the input-less read: `resource()` treats an `undefined`
1081
- // params value as "idle, don't load", so an input-less read must yield a
1082
- // defined-but-ignored params. It is never sent — the call uses `undefined`.
1083
- const NO_INPUT = Symbol('analog.serverFn.noInput');
604
+ const NO_INPUT = Symbol("analog.serverFn.noInput");
1084
605
  function injectServerFn(fn, args) {
1085
- assertInInjectionContext(injectServerFn);
1086
- const client = inject(ServerFnClient);
1087
- return resource({
1088
- params: () => (args ? args() : NO_INPUT),
1089
- loader: async ({ params }) => {
1090
- const input = (params === NO_INPUT ? undefined : params);
1091
- // Hydrate from the SSR seed on first client render; else fetch and (on
1092
- // the server) seed for the client.
1093
- const seeded = client.readSeed(fn, input);
1094
- if (seeded !== undefined)
1095
- return seeded;
1096
- const value = await client.call(fn, input);
1097
- if (client.isServer) {
1098
- client.writeSeed(fn, input, value);
1099
- }
1100
- return value;
1101
- },
1102
- });
606
+ assertInInjectionContext(injectServerFn);
607
+ const client = inject(ServerFnClient);
608
+ return resource({
609
+ params: () => args ? args() : NO_INPUT,
610
+ loader: async ({ params }) => {
611
+ const input = params === NO_INPUT ? void 0 : params;
612
+ const seeded = client.readSeed(fn, input);
613
+ if (seeded !== void 0) return seeded;
614
+ const value = await client.call(fn, input);
615
+ if (client.isServer) client.writeSeed(fn, input, value);
616
+ return value;
617
+ }
618
+ });
1103
619
  }
1104
- /**
1105
- * Imperative binding of a server function: returns a callable that dispatches
1106
- * the call through `HttpClient` (so client interceptors apply) and resolves the
1107
- * result. Use for mutations and event-driven calls; use `injectServerFn` for
1108
- * reactive reads.
1109
- */
1110
620
  function injectServerFnMutation(fn) {
1111
- assertInInjectionContext(injectServerFnMutation);
1112
- const client = inject(ServerFnClient);
1113
- return (input) => client.call(fn, input);
621
+ assertInInjectionContext(injectServerFnMutation);
622
+ const client = inject(ServerFnClient);
623
+ return (input) => client.call(fn, input);
1114
624
  }
1115
625
  function stableInput(input) {
1116
- if (input === undefined || input === null)
1117
- return '_';
1118
- return JSON.stringify(input);
626
+ if (input === void 0 || input === null) return "_";
627
+ return JSON.stringify(input);
1119
628
  }
1120
-
1121
- /**
1122
- * Builds a server-function reference: the client-safe `{ __serverFn, id, url,
1123
- * method }` metadata that `injectServerFn`/`ServerFnClient` dispatch through.
1124
- *
1125
- * Shared by both sides so they produce identical refs: the server `serverFn`
1126
- * wraps this with registration + the handler, and the client build's scrub
1127
- * transform emits a call to this factory in place of the server module so the
1128
- * browser bundle carries only the ref, never the handler or its server imports.
1129
- *
1130
- * The returned value is callable-typed but throws if invoked directly — it is
1131
- * always dispatched via `injectServerFn`/`ServerFnClient`, never called.
1132
- */
1133
629
  function createServerFnRef(config) {
1134
- if (!config.id) {
1135
- throw new Error('[analog] serverFn is missing its build-derived id. Server functions require the Analog build transform (@analogjs/platform / @analogjs/vite-plugin-nitro); a raw import without it is not supported.');
1136
- }
1137
- const method = config.method ?? (config.input ? 'POST' : 'GET');
1138
- const url = `/_analog/fn/${config.id}`;
1139
- const ref = (() => {
1140
- throw new Error(`serverFn "${config.id}" must be called via injectServerFn/ServerFnClient`);
1141
- });
1142
- return Object.assign(ref, {
1143
- __serverFn: true,
1144
- id: config.id,
1145
- url,
1146
- method,
1147
- });
630
+ if (!config.id) throw new Error("[analog] serverFn is missing its build-derived id. Server functions require the Analog build transform (@analogjs/platform / @analogjs/vite-plugin-nitro); a raw import without it is not supported.");
631
+ const method = config.method ?? (config.input ? "POST" : "GET");
632
+ const url = `/_analog/fn/${config.id}`;
633
+ const ref = (() => {
634
+ throw new Error(`serverFn "${config.id}" must be called via injectServerFn/ServerFnClient`);
635
+ });
636
+ return Object.assign(ref, {
637
+ __serverFn: true,
638
+ id: config.id,
639
+ url,
640
+ method
641
+ });
1148
642
  }
1149
-
1150
- /**
1151
- * Builds a typed route link object from a route path pattern and options.
1152
- *
1153
- * The returned object separates path, query params, and fragment for
1154
- * direct use with Angular's routerLink directive inputs.
1155
- *
1156
- * @example
1157
- * toRoute('/about')
1158
- * // → { path: ['/', 'about'], queryParams: null, fragment: undefined }
1159
- *
1160
- * toRoute('/users/[id]', { params: { id: '42' } })
1161
- * // → { path: ['/', 'users', '42'], queryParams: null, fragment: undefined }
1162
- *
1163
- * toRoute('/users/[id]', { params: { id: '42' }, query: { tab: 'settings' }, hash: 'bio' })
1164
- * // → { path: ['/', 'users', '42'], queryParams: { tab: 'settings' }, fragment: 'bio' }
1165
- *
1166
- * @example Template usage
1167
- * Compute the link in the component:
1168
- * ```ts
1169
- * readonly link = toRoute('/users/[id]', { params: { id: '42' } });
1170
- * ```
1171
- *
1172
- * ```html
1173
- * <a [routerLink]="link.path" [queryParams]="link.queryParams" [fragment]="link.fragment">
1174
- * ```
1175
- */
1176
643
  function toRoute(path, ...args) {
1177
- const options = args[0];
1178
- return buildRouteLink(path, options);
644
+ const options = args[0];
645
+ return buildRouteLink(path, options);
1179
646
  }
1180
- /**
1181
- * Internal: builds a `RouteLinkResult` from path and options.
1182
- * Exported for direct use in tests (avoids generic constraints).
1183
- */
1184
647
  function buildRouteLink(path, options) {
1185
- const resolvedPath = buildPath(path, options?.params);
1186
- let queryParams = null;
1187
- if (options?.query) {
1188
- const filtered = {};
1189
- let hasEntries = false;
1190
- for (const [key, value] of Object.entries(options.query)) {
1191
- if (value !== undefined) {
1192
- filtered[key] = value;
1193
- hasEntries = true;
1194
- }
1195
- }
1196
- if (hasEntries) {
1197
- queryParams = filtered;
1198
- }
1199
- }
1200
- return {
1201
- path: resolvedPath,
1202
- queryParams,
1203
- fragment: options?.hash,
1204
- };
648
+ const resolvedPath = buildPath(path, options?.params);
649
+ let queryParams = null;
650
+ if (options?.query) {
651
+ const filtered = {};
652
+ let hasEntries = false;
653
+ for (const [key, value] of Object.entries(options.query)) if (value !== void 0) {
654
+ filtered[key] = value;
655
+ hasEntries = true;
656
+ }
657
+ if (hasEntries) queryParams = filtered;
658
+ }
659
+ return {
660
+ path: resolvedPath,
661
+ queryParams,
662
+ fragment: options?.hash
663
+ };
1205
664
  }
1206
665
  function buildPath(path, params = {}) {
1207
- const segments = path
1208
- .split('/')
1209
- .filter(Boolean)
1210
- .flatMap((segment) => {
1211
- const optional = segment.match(/^\[\[\.\.\.([^\]]+)\]\]$/);
1212
- const catchAll = segment.match(/^\[\.\.\.([^\]]+)\]$/);
1213
- const dynamic = segment.match(/^\[([^\]]+)\]$/);
1214
- const match = optional ?? catchAll ?? dynamic;
1215
- if (!match)
1216
- return [segment];
1217
- const value = params[match[1]];
1218
- if (value == null || (Array.isArray(value) && !value.length)) {
1219
- if (optional)
1220
- return [];
1221
- throw new Error(`Missing required ${catchAll ? 'catch-all ' : ''}param "${match[1]}" for path "${path}"`);
1222
- }
1223
- return Array.isArray(value) ? value.map(String) : [String(value)];
1224
- });
1225
- // A separate root command keeps slashes inside parameter values in one segment.
1226
- return ['/', ...segments];
666
+ return ["/", ...path.split("/").filter(Boolean).flatMap((segment) => {
667
+ const optional = segment.match(/^\[\[\.\.\.([^\]]+)\]\]$/);
668
+ const catchAll = segment.match(/^\[\.\.\.([^\]]+)\]$/);
669
+ const dynamic = segment.match(/^\[([^\]]+)\]$/);
670
+ const match = optional ?? catchAll ?? dynamic;
671
+ if (!match) return [segment];
672
+ const value = params[match[1]];
673
+ if (value == null || Array.isArray(value) && !value.length) {
674
+ if (optional) return [];
675
+ throw new Error(`Missing required ${catchAll ? "catch-all " : ""}param "${match[1]}" for path "${path}"`);
676
+ }
677
+ return Array.isArray(value) ? value.map(String) : [String(value)];
678
+ })];
1227
679
  }
1228
- /** Internal URL serialization for programmatic navigation. */
1229
680
  function buildUrl(path, options) {
1230
- const link = buildRouteLink(path, options);
1231
- const segments = link.path.slice(1).map((path) => new UrlSegment(path, {}));
1232
- const root = new UrlSegmentGroup([], {
1233
- [PRIMARY_OUTLET]: new UrlSegmentGroup(segments, {}),
1234
- });
1235
- return new DefaultUrlSerializer().serialize(new UrlTree(root, link.queryParams ?? {}, link.fragment ?? null));
1236
- }
1237
-
1238
- class LinkTo {
1239
- constructor() {
1240
- this.linkTo = input.required(/* @ts-ignore */
1241
- ...(ngDevMode ? [{ debugName: "linkTo" }] : /* istanbul ignore next */ []));
1242
- this.routerLink = inject(RouterLink);
1243
- }
1244
- ngOnChanges() {
1245
- const destination = this.linkTo();
1246
- const link = destination
1247
- ? typeof destination === 'string'
1248
- ? buildRouteLink(destination)
1249
- : buildRouteLink(destination.path, destination)
1250
- : null;
1251
- this.routerLink.routerLink = link?.path ?? null;
1252
- this.routerLink.queryParams = link?.queryParams ?? null;
1253
- this.routerLink.fragment = link?.fragment;
1254
- // Direct input assignments must also refresh href and RouterLinkActive.
1255
- this.routerLink.ngOnChanges({});
1256
- }
1257
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: LinkTo, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
1258
- static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.1.5", type: LinkTo, isStandalone: true, selector: "[linkTo]", inputs: { linkTo: { classPropertyName: "linkTo", publicName: "linkTo", isSignal: true, isRequired: true, transformFunction: null } }, usesOnChanges: true, hostDirectives: [{ directive: i1.RouterLink, inputs: ["target", "target", "queryParamsHandling", "queryParamsHandling", "preserveFragment", "preserveFragment", "skipLocationChange", "skipLocationChange", "replaceUrl", "replaceUrl", "state", "state"] }], ngImport: i0 }); }
1259
- }
1260
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: LinkTo, decorators: [{
1261
- type: Directive,
1262
- args: [{
1263
- // eslint-disable-next-line @angular-eslint/directive-selector
1264
- selector: '[linkTo]',
1265
- standalone: true,
1266
- hostDirectives: [
1267
- {
1268
- directive: RouterLink,
1269
- inputs: [
1270
- 'target',
1271
- 'queryParamsHandling',
1272
- 'preserveFragment',
1273
- 'skipLocationChange',
1274
- 'replaceUrl',
1275
- 'state',
1276
- ],
1277
- },
1278
- ],
1279
- }]
1280
- }], propDecorators: { linkTo: [{ type: i0.Input, args: [{ isSignal: true, alias: "linkTo", required: true }] }] } });
1281
-
681
+ const link = buildRouteLink(path, options);
682
+ const segments = link.path.slice(1).map((path) => new UrlSegment(path, {}));
683
+ const root = new UrlSegmentGroup([], { [PRIMARY_OUTLET]: new UrlSegmentGroup(segments, {}) });
684
+ return new DefaultUrlSerializer().serialize(new UrlTree(root, link.queryParams ?? {}, link.fragment ?? null));
685
+ }
686
+ var LinkTo = class LinkTo {
687
+ constructor() {
688
+ this.linkTo = input.required(...ngDevMode ? [{ debugName: "linkTo" }] : /* istanbul ignore next */ []);
689
+ this.routerLink = inject(RouterLink);
690
+ }
691
+ ngOnChanges() {
692
+ const destination = this.linkTo();
693
+ const link = destination ? typeof destination === "string" ? buildRouteLink(destination) : buildRouteLink(destination.path, destination) : null;
694
+ this.routerLink.routerLink = link?.path ?? null;
695
+ this.routerLink.queryParams = link?.queryParams ?? null;
696
+ this.routerLink.fragment = link?.fragment;
697
+ this.routerLink.ngOnChanges({});
698
+ }
699
+ static {
700
+ this.ɵfac = i0.ɵɵngDeclareFactory({
701
+ minVersion: "12.0.0",
702
+ version: "22.2.0",
703
+ ngImport: i0,
704
+ type: LinkTo,
705
+ deps: [],
706
+ target: i0.ɵɵFactoryTarget.Directive
707
+ });
708
+ }
709
+ static {
710
+ this.ɵdir = i0.ɵɵngDeclareDirective({
711
+ minVersion: "17.1.0",
712
+ version: "22.2.0",
713
+ type: LinkTo,
714
+ isStandalone: true,
715
+ selector: "[linkTo]",
716
+ inputs: { linkTo: {
717
+ classPropertyName: "linkTo",
718
+ publicName: "linkTo",
719
+ isSignal: true,
720
+ isRequired: true,
721
+ transformFunction: null
722
+ } },
723
+ usesOnChanges: true,
724
+ hostDirectives: [{
725
+ directive: i1.RouterLink,
726
+ inputs: [
727
+ "target",
728
+ "target",
729
+ "queryParamsHandling",
730
+ "queryParamsHandling",
731
+ "preserveFragment",
732
+ "preserveFragment",
733
+ "skipLocationChange",
734
+ "skipLocationChange",
735
+ "replaceUrl",
736
+ "replaceUrl",
737
+ "state",
738
+ "state"
739
+ ]
740
+ }],
741
+ ngImport: i0
742
+ });
743
+ }
744
+ };
745
+ i0.ɵɵngDeclareClassMetadata({
746
+ minVersion: "12.0.0",
747
+ version: "22.2.0",
748
+ ngImport: i0,
749
+ type: LinkTo,
750
+ decorators: [{
751
+ type: Directive,
752
+ args: [{
753
+ selector: "[linkTo]",
754
+ standalone: true,
755
+ hostDirectives: [{
756
+ directive: RouterLink,
757
+ inputs: [
758
+ "target",
759
+ "queryParamsHandling",
760
+ "preserveFragment",
761
+ "skipLocationChange",
762
+ "replaceUrl",
763
+ "state"
764
+ ]
765
+ }]
766
+ }]
767
+ }],
768
+ propDecorators: { linkTo: [{
769
+ type: i0.Input,
770
+ args: [{
771
+ isSignal: true,
772
+ alias: "linkTo",
773
+ required: true
774
+ }]
775
+ }] }
776
+ });
1282
777
  function isRoutePathOptionsBase(value) {
1283
- return (!!value &&
1284
- typeof value === 'object' &&
1285
- ('params' in value || 'query' in value || 'hash' in value));
778
+ return !!value && typeof value === "object" && ("params" in value || "query" in value || "hash" in value);
1286
779
  }
1287
- /**
1288
- * Injects a typed navigate function.
1289
- *
1290
- * @example
1291
- * ```ts
1292
- * const navigate = injectNavigate();
1293
- *
1294
- * navigate('/users/[id]', { params: { id: '42' } }); // ✅
1295
- * navigate('/users/[id]', { params: { id: 42 } }); // ✅
1296
- *
1297
- * // With navigation extras
1298
- * navigate('/users/[id]', { params: { id: '42' } }, { replaceUrl: true });
1299
- * ```
1300
- */
1301
780
  function injectNavigate() {
1302
- const router = inject(Router);
1303
- const navigate = (path, ...args) => {
1304
- let options;
1305
- let extras;
1306
- if (args.length > 1) {
1307
- options = args[0];
1308
- extras = args[1];
1309
- }
1310
- else if (args.length === 1) {
1311
- if (isRoutePathOptionsBase(args[0])) {
1312
- options = args[0];
1313
- }
1314
- else {
1315
- extras = args[0];
1316
- }
1317
- }
1318
- const url = buildUrl(path, options);
1319
- return router.navigateByUrl(url, extras);
1320
- };
1321
- return navigate;
781
+ const router = inject(Router);
782
+ const navigate = (path, ...args) => {
783
+ let options;
784
+ let extras;
785
+ if (args.length > 1) {
786
+ options = args[0];
787
+ extras = args[1];
788
+ } else if (args.length === 1) if (isRoutePathOptionsBase(args[0])) options = args[0];
789
+ else extras = args[0];
790
+ const url = buildUrl(path, options);
791
+ return router.navigateByUrl(url, extras);
792
+ };
793
+ return navigate;
1322
794
  }
1323
-
1324
795
  function extractCatchAllParams(routePath) {
1325
- const params = [];
1326
- for (const segment of routePath.split('/')) {
1327
- const optional = segment.match(/^\[\[\.\.\.([^\]]+)\]\]$/);
1328
- const required = segment.match(/^\[\.\.\.([^\]]+)\]$/);
1329
- if (optional) {
1330
- params.push({ name: optional[1], type: 'optionalCatchAll' });
1331
- }
1332
- else if (required) {
1333
- params.push({ name: required[1], type: 'catchAll' });
1334
- }
1335
- }
1336
- return params;
796
+ const params = [];
797
+ for (const segment of routePath.split("/")) {
798
+ const optional = segment.match(/^\[\[\.\.\.([^\]]+)\]\]$/);
799
+ const required = segment.match(/^\[\.\.\.([^\]]+)\]$/);
800
+ if (optional) params.push({
801
+ name: optional[1],
802
+ type: "optionalCatchAll"
803
+ });
804
+ else if (required) params.push({
805
+ name: required[1],
806
+ type: "catchAll"
807
+ });
808
+ }
809
+ return params;
1337
810
  }
1338
- /** Read raw route params; catch-all segments are returned as arrays. */
1339
811
  function injectParams(_from, options) {
1340
- const injector = options?.injector;
1341
- const route = injector
1342
- ? injector.get(ActivatedRoute)
1343
- : inject(ActivatedRoute);
1344
- const ancestors = route.pathFromRoot ?? [route];
1345
- const catchAllParams = extractCatchAllParams(_from);
1346
- return toSignal(combineLatest([
1347
- combineLatest(ancestors.map((entry) => entry.params)),
1348
- combineLatest(ancestors.map((entry) => entry.url ?? of([]))),
1349
- ]).pipe(map(([values, segments]) => {
1350
- const params = Object.assign({}, ...values);
1351
- for (const param of catchAllParams) {
1352
- const source = ancestors.findIndex((entry, index) => param.type === 'catchAll'
1353
- ? entry.routeConfig?.path === '**'
1354
- : !!entry.routeConfig?.matcher &&
1355
- values[index][param.name] != null);
1356
- if (source !== -1) {
1357
- params[param.name] = segments[source].map((segment) => segment.path);
1358
- }
1359
- }
1360
- return params;
1361
- })), { requireSync: true, injector });
812
+ const injector = options?.injector;
813
+ const route = injector ? injector.get(ActivatedRoute) : inject(ActivatedRoute);
814
+ const ancestors = route.pathFromRoot ?? [route];
815
+ const catchAllParams = extractCatchAllParams(_from);
816
+ return toSignal(combineLatest([combineLatest(ancestors.map((entry) => entry.params)), combineLatest(ancestors.map((entry) => entry.url ?? of([])))]).pipe(map(([values, segments]) => {
817
+ const params = Object.assign({}, ...values);
818
+ for (const param of catchAllParams) {
819
+ const source = ancestors.findIndex((entry, index) => param.type === "catchAll" ? entry.routeConfig?.path === "**" : !!entry.routeConfig?.matcher && values[index][param.name] != null);
820
+ if (source !== -1) params[param.name] = segments[source].map((segment) => segment.path);
821
+ }
822
+ return params;
823
+ })), {
824
+ requireSync: true,
825
+ injector
826
+ });
1362
827
  }
1363
- /** Read raw query params as a signal. No schema coercion is performed. */
1364
828
  function injectQuery(_from, options) {
1365
- const injector = options?.injector;
1366
- const route = injector
1367
- ? injector.get(ActivatedRoute)
1368
- : inject(ActivatedRoute);
1369
- return toSignal(route.queryParams.pipe(map((params) => params)), { requireSync: true, injector });
829
+ const injector = options?.injector;
830
+ return toSignal((injector ? injector.get(ActivatedRoute) : inject(ActivatedRoute)).queryParams.pipe(map((params) => params)), {
831
+ requireSync: true,
832
+ injector
833
+ });
1370
834
  }
1371
-
1372
- /**
1373
- * Generated bundle index. Do not edit.
1374
- */
1375
-
1376
835
  export { FormAction, LinkTo, SERVER_FN_DISPATCHER, ServerFnClient, createRoutes, createServerFnRef, defineRouteMeta, getLoadResolver, injectActivatedRoute, injectDebugRoutes, injectLoad, injectNavigate, injectParams, injectQuery, injectRouteEndpointURL, injectRouter, injectServerFn, injectServerFnMutation, issuePathToFieldName, issuesToFieldErrors, issuesToFormErrors, provideFileRouter, provideServerFnClient, requestContextInterceptor, routes, toRoute, withDebugRoutes, withExtraRoutes };
1377
- //# sourceMappingURL=analogjs-router.mjs.map
836
+
837
+ //# sourceMappingURL=analogjs-router.mjs.map