@analogjs/router 2.7.3-beta.1 → 2.8.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,14 @@
1
- import { Router, NavigationEnd, UrlSegment, ActivatedRoute, provideRouter, ROUTES } from '@angular/router';
1
+ import * as i1 from '@angular/router';
2
+ import { Router, NavigationEnd, UrlSegment, ActivatedRoute, provideRouter, ROUTES, UrlSegmentGroup, PRIMARY_OUTLET, DefaultUrlSerializer, UrlTree, RouterLink } from '@angular/router';
2
3
  import * as i0 from '@angular/core';
3
4
  import { inject, PLATFORM_ID, makeEnvironmentProviders, ENVIRONMENT_INITIALIZER, Injector, makeStateKey, TransferState, input, output, Directive, InjectionToken, Injectable, assertInInjectionContext, resource } from '@angular/core';
4
5
  import { HttpClient, HttpHeaders, ɵHTTP_ROOT_INTERCEPTOR_FNS as _HTTP_ROOT_INTERCEPTOR_FNS, HttpResponse } from '@angular/common/http';
5
- import { firstValueFrom, map, from, of } from 'rxjs';
6
+ import { firstValueFrom, map, from, of, combineLatest } from 'rxjs';
6
7
  import { Meta } from '@angular/platform-browser';
7
8
  import { filter } from 'rxjs/operators';
8
9
  import { injectAPIPrefix, injectBaseURL, injectRequest, API_PREFIX } from '@analogjs/router/tokens';
9
10
  import { isPlatformServer } from '@angular/common';
11
+ import { toSignal } from '@angular/core/rxjs-interop';
10
12
 
11
13
  const ROUTE_META_TAGS_KEY = Symbol('@analogjs/router Route Meta Tags Key');
12
14
  const CHARSET_KEY = 'charset';
@@ -1015,9 +1017,231 @@ function createServerFnRef(config) {
1015
1017
  });
1016
1018
  }
1017
1019
 
1020
+ /**
1021
+ * Builds a typed route link object from a route path pattern and options.
1022
+ *
1023
+ * The returned object separates path, query params, and fragment for
1024
+ * direct use with Angular's routerLink directive inputs.
1025
+ *
1026
+ * @example
1027
+ * toRoute('/about')
1028
+ * // → { path: ['/', 'about'], queryParams: null, fragment: undefined }
1029
+ *
1030
+ * toRoute('/users/[id]', { params: { id: '42' } })
1031
+ * // → { path: ['/', 'users', '42'], queryParams: null, fragment: undefined }
1032
+ *
1033
+ * toRoute('/users/[id]', { params: { id: '42' }, query: { tab: 'settings' }, hash: 'bio' })
1034
+ * // → { path: ['/', 'users', '42'], queryParams: { tab: 'settings' }, fragment: 'bio' }
1035
+ *
1036
+ * @example Template usage
1037
+ * Compute the link in the component:
1038
+ * ```ts
1039
+ * readonly link = toRoute('/users/[id]', { params: { id: '42' } });
1040
+ * ```
1041
+ *
1042
+ * ```html
1043
+ * <a [routerLink]="link.path" [queryParams]="link.queryParams" [fragment]="link.fragment">
1044
+ * ```
1045
+ */
1046
+ function toRoute(path, ...args) {
1047
+ const options = args[0];
1048
+ return buildRouteLink(path, options);
1049
+ }
1050
+ /**
1051
+ * Internal: builds a `RouteLinkResult` from path and options.
1052
+ * Exported for direct use in tests (avoids generic constraints).
1053
+ */
1054
+ function buildRouteLink(path, options) {
1055
+ const resolvedPath = buildPath(path, options?.params);
1056
+ let queryParams = null;
1057
+ if (options?.query) {
1058
+ const filtered = {};
1059
+ let hasEntries = false;
1060
+ for (const [key, value] of Object.entries(options.query)) {
1061
+ if (value !== undefined) {
1062
+ filtered[key] = value;
1063
+ hasEntries = true;
1064
+ }
1065
+ }
1066
+ if (hasEntries) {
1067
+ queryParams = filtered;
1068
+ }
1069
+ }
1070
+ return {
1071
+ path: resolvedPath,
1072
+ queryParams,
1073
+ fragment: options?.hash,
1074
+ };
1075
+ }
1076
+ function buildPath(path, params = {}) {
1077
+ const segments = path
1078
+ .split('/')
1079
+ .filter(Boolean)
1080
+ .flatMap((segment) => {
1081
+ const optional = segment.match(/^\[\[\.\.\.([^\]]+)\]\]$/);
1082
+ const catchAll = segment.match(/^\[\.\.\.([^\]]+)\]$/);
1083
+ const dynamic = segment.match(/^\[([^\]]+)\]$/);
1084
+ const match = optional ?? catchAll ?? dynamic;
1085
+ if (!match)
1086
+ return [segment];
1087
+ const value = params[match[1]];
1088
+ if (value == null || (Array.isArray(value) && !value.length)) {
1089
+ if (optional)
1090
+ return [];
1091
+ throw new Error(`Missing required ${catchAll ? 'catch-all ' : ''}param "${match[1]}" for path "${path}"`);
1092
+ }
1093
+ return Array.isArray(value) ? value.map(String) : [String(value)];
1094
+ });
1095
+ // A separate root command keeps slashes inside parameter values in one segment.
1096
+ return ['/', ...segments];
1097
+ }
1098
+ /** Internal URL serialization for programmatic navigation. */
1099
+ function buildUrl(path, options) {
1100
+ const link = buildRouteLink(path, options);
1101
+ const segments = link.path.slice(1).map((path) => new UrlSegment(path, {}));
1102
+ const root = new UrlSegmentGroup([], {
1103
+ [PRIMARY_OUTLET]: new UrlSegmentGroup(segments, {}),
1104
+ });
1105
+ return new DefaultUrlSerializer().serialize(new UrlTree(root, link.queryParams ?? {}, link.fragment ?? null));
1106
+ }
1107
+
1108
+ class LinkTo {
1109
+ constructor() {
1110
+ this.linkTo = input.required(/* @ts-ignore */
1111
+ ...(ngDevMode ? [{ debugName: "linkTo" }] : /* istanbul ignore next */ []));
1112
+ this.routerLink = inject(RouterLink);
1113
+ }
1114
+ ngOnChanges() {
1115
+ const destination = this.linkTo();
1116
+ const link = destination
1117
+ ? typeof destination === 'string'
1118
+ ? buildRouteLink(destination)
1119
+ : buildRouteLink(destination.path, destination)
1120
+ : null;
1121
+ this.routerLink.routerLink = link?.path ?? null;
1122
+ this.routerLink.queryParams = link?.queryParams ?? null;
1123
+ this.routerLink.fragment = link?.fragment;
1124
+ // Direct input assignments must also refresh href and RouterLinkActive.
1125
+ this.routerLink.ngOnChanges({});
1126
+ }
1127
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: LinkTo, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
1128
+ 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 }); }
1129
+ }
1130
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: LinkTo, decorators: [{
1131
+ type: Directive,
1132
+ args: [{
1133
+ // eslint-disable-next-line @angular-eslint/directive-selector
1134
+ selector: '[linkTo]',
1135
+ standalone: true,
1136
+ hostDirectives: [
1137
+ {
1138
+ directive: RouterLink,
1139
+ inputs: [
1140
+ 'target',
1141
+ 'queryParamsHandling',
1142
+ 'preserveFragment',
1143
+ 'skipLocationChange',
1144
+ 'replaceUrl',
1145
+ 'state',
1146
+ ],
1147
+ },
1148
+ ],
1149
+ }]
1150
+ }], propDecorators: { linkTo: [{ type: i0.Input, args: [{ isSignal: true, alias: "linkTo", required: true }] }] } });
1151
+
1152
+ function isRoutePathOptionsBase(value) {
1153
+ return (!!value &&
1154
+ typeof value === 'object' &&
1155
+ ('params' in value || 'query' in value || 'hash' in value));
1156
+ }
1157
+ /**
1158
+ * Injects a typed navigate function.
1159
+ *
1160
+ * @example
1161
+ * ```ts
1162
+ * const navigate = injectNavigate();
1163
+ *
1164
+ * navigate('/users/[id]', { params: { id: '42' } }); // ✅
1165
+ * navigate('/users/[id]', { params: { id: 42 } }); // ✅
1166
+ *
1167
+ * // With navigation extras
1168
+ * navigate('/users/[id]', { params: { id: '42' } }, { replaceUrl: true });
1169
+ * ```
1170
+ */
1171
+ function injectNavigate() {
1172
+ const router = inject(Router);
1173
+ const navigate = (path, ...args) => {
1174
+ let options;
1175
+ let extras;
1176
+ if (args.length > 1) {
1177
+ options = args[0];
1178
+ extras = args[1];
1179
+ }
1180
+ else if (args.length === 1) {
1181
+ if (isRoutePathOptionsBase(args[0])) {
1182
+ options = args[0];
1183
+ }
1184
+ else {
1185
+ extras = args[0];
1186
+ }
1187
+ }
1188
+ const url = buildUrl(path, options);
1189
+ return router.navigateByUrl(url, extras);
1190
+ };
1191
+ return navigate;
1192
+ }
1193
+
1194
+ function extractCatchAllParams(routePath) {
1195
+ const params = [];
1196
+ for (const segment of routePath.split('/')) {
1197
+ const optional = segment.match(/^\[\[\.\.\.([^\]]+)\]\]$/);
1198
+ const required = segment.match(/^\[\.\.\.([^\]]+)\]$/);
1199
+ if (optional) {
1200
+ params.push({ name: optional[1], type: 'optionalCatchAll' });
1201
+ }
1202
+ else if (required) {
1203
+ params.push({ name: required[1], type: 'catchAll' });
1204
+ }
1205
+ }
1206
+ return params;
1207
+ }
1208
+ /** Read raw route params; catch-all segments are returned as arrays. */
1209
+ function injectParams(_from, options) {
1210
+ const injector = options?.injector;
1211
+ const route = injector
1212
+ ? injector.get(ActivatedRoute)
1213
+ : inject(ActivatedRoute);
1214
+ const ancestors = route.pathFromRoot ?? [route];
1215
+ const catchAllParams = extractCatchAllParams(_from);
1216
+ return toSignal(combineLatest([
1217
+ combineLatest(ancestors.map((entry) => entry.params)),
1218
+ combineLatest(ancestors.map((entry) => entry.url ?? of([]))),
1219
+ ]).pipe(map(([values, segments]) => {
1220
+ const params = Object.assign({}, ...values);
1221
+ for (const param of catchAllParams) {
1222
+ const source = ancestors.findIndex((entry, index) => param.type === 'catchAll'
1223
+ ? entry.routeConfig?.path === '**'
1224
+ : !!entry.routeConfig?.matcher &&
1225
+ values[index][param.name] != null);
1226
+ if (source !== -1) {
1227
+ params[param.name] = segments[source].map((segment) => segment.path);
1228
+ }
1229
+ }
1230
+ return params;
1231
+ })), { requireSync: true, injector });
1232
+ }
1233
+ /** Read raw query params as a signal. No schema coercion is performed. */
1234
+ function injectQuery(_from, options) {
1235
+ const injector = options?.injector;
1236
+ const route = injector
1237
+ ? injector.get(ActivatedRoute)
1238
+ : inject(ActivatedRoute);
1239
+ return toSignal(route.queryParams.pipe(map((params) => params)), { requireSync: true, injector });
1240
+ }
1241
+
1018
1242
  /**
1019
1243
  * Generated bundle index. Do not edit.
1020
1244
  */
1021
1245
 
1022
- export { FormAction, SERVER_FN_DISPATCHER, ServerFnClient, createRoutes, createServerFnRef, defineRouteMeta, getLoadResolver, injectActivatedRoute, injectDebugRoutes, injectLoad, injectRouteEndpointURL, injectRouter, injectServerFn, injectServerFnMutation, provideFileRouter, provideServerFnClient, requestContextInterceptor, routes, withDebugRoutes, withExtraRoutes };
1246
+ export { FormAction, LinkTo, SERVER_FN_DISPATCHER, ServerFnClient, createRoutes, createServerFnRef, defineRouteMeta, getLoadResolver, injectActivatedRoute, injectDebugRoutes, injectLoad, injectNavigate, injectParams, injectQuery, injectRouteEndpointURL, injectRouter, injectServerFn, injectServerFnMutation, provideFileRouter, provideServerFnClient, requestContextInterceptor, routes, toRoute, withDebugRoutes, withExtraRoutes };
1023
1247
  //# sourceMappingURL=analogjs-router.mjs.map