nuxtseo-shared 5.3.10 → 5.3.11

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.
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Runtime-safe i18n route resolution.
3
+ *
4
+ * `./i18n` reaches for `@nuxt/kit` to read the installed module's options, so it
5
+ * can only run at build time. This entry carries no build-time dependencies and
6
+ * is importable from a module's runtime (nitro handlers, plugins, composables).
7
+ * Feed it the config `toRuntimeI18nConfig()` produces.
8
+ */
9
+ /**
10
+ * Custom route paths keyed by route name, then locale code — i18n's `pages`
11
+ * option (`globalLocaleRoutes` for nuxt-i18n-micro). `false` means the page is
12
+ * disabled for that locale.
13
+ *
14
+ * ```
15
+ * { about: { en: '/about', fr: '/a-propos' } }
16
+ * ```
17
+ */
18
+ type LocalePages = Record<string, Record<string, string | false> | undefined>;
19
+ interface RuntimeLocale {
20
+ code: string;
21
+ hreflang: string;
22
+ name?: string;
23
+ nativeName?: string;
24
+ language?: string;
25
+ domain?: string;
26
+ domains?: string[];
27
+ defaultForDomains?: string[];
28
+ }
29
+ /** Runtime-safe subset of `AutoI18nConfig` used for route locale resolution. */
30
+ interface RuntimeI18nConfig {
31
+ defaultLocale: string;
32
+ strategy: 'no_prefix' | 'prefix_except_default' | 'prefix' | 'prefix_and_default';
33
+ locales: RuntimeLocale[];
34
+ differentDomains?: boolean;
35
+ multiDomainLocales?: boolean;
36
+ /** Translated route paths, when i18n is configured with custom routes. */
37
+ pages?: LocalePages;
38
+ }
39
+ interface LocaleAlternate {
40
+ code: string;
41
+ hreflang: string;
42
+ path: string;
43
+ domain?: string;
44
+ }
45
+ type LocaleAlternateResolution = {
46
+ _tag: 'pages';
47
+ alternates: LocaleAlternate[];
48
+ } | {
49
+ _tag: 'strategy';
50
+ alternates: LocaleAlternate[];
51
+ };
52
+ interface RouteLocaleInfo {
53
+ /** Resolved locale code for this route */
54
+ locale: string;
55
+ /** Route with locale prefix stripped (e.g. /fr/about → /about). For no_prefix this equals route. */
56
+ basePath: string;
57
+ }
58
+ interface RuntimeRouteContext {
59
+ /** Request host, used to resolve locales under domain-based strategies. */
60
+ host?: string;
61
+ /** Known current locale, required to translate no_prefix routes without a locale domain. */
62
+ locale?: string;
63
+ }
64
+ /**
65
+ * Resolve which locale a route belongs to and the locale-stripped base path.
66
+ */
67
+ declare function resolveLocaleFromRoute(route: string, i18n: RuntimeI18nConfig, context?: RuntimeRouteContext): RouteLocaleInfo;
68
+ /**
69
+ * Build the URL path for a base path under a given locale, honoring the i18n strategy.
70
+ */
71
+ declare function localePath(basePath: string, locale: string, i18n: RuntimeI18nConfig, context?: RuntimeRouteContext): string;
72
+ /**
73
+ * Compute hreflang alternates for a given route.
74
+ * Returns the route itself plus all sibling locale variants.
75
+ *
76
+ * Translated slugs (i18n `pages`) can't be derived by adding or removing a
77
+ * locale prefix — `/about` and `/fr/a-propos` are the same page — so the route
78
+ * table is consulted first and prefix arithmetic is the fallback.
79
+ */
80
+ declare function resolveLocaleAlternates(route: string, i18n: RuntimeI18nConfig, context?: RuntimeRouteContext): LocaleAlternateResolution;
81
+ declare function computeLocaleAlternates(route: string, i18n: RuntimeI18nConfig, context?: RuntimeRouteContext): LocaleAlternate[];
82
+
83
+ export { computeLocaleAlternates, localePath, resolveLocaleAlternates, resolveLocaleFromRoute };
84
+ export type { LocaleAlternate, LocaleAlternateResolution, LocalePages, RouteLocaleInfo, RuntimeI18nConfig, RuntimeLocale, RuntimeRouteContext };
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Runtime-safe i18n route resolution.
3
+ *
4
+ * `./i18n` reaches for `@nuxt/kit` to read the installed module's options, so it
5
+ * can only run at build time. This entry carries no build-time dependencies and
6
+ * is importable from a module's runtime (nitro handlers, plugins, composables).
7
+ * Feed it the config `toRuntimeI18nConfig()` produces.
8
+ */
9
+ /**
10
+ * Custom route paths keyed by route name, then locale code — i18n's `pages`
11
+ * option (`globalLocaleRoutes` for nuxt-i18n-micro). `false` means the page is
12
+ * disabled for that locale.
13
+ *
14
+ * ```
15
+ * { about: { en: '/about', fr: '/a-propos' } }
16
+ * ```
17
+ */
18
+ type LocalePages = Record<string, Record<string, string | false> | undefined>;
19
+ interface RuntimeLocale {
20
+ code: string;
21
+ hreflang: string;
22
+ name?: string;
23
+ nativeName?: string;
24
+ language?: string;
25
+ domain?: string;
26
+ domains?: string[];
27
+ defaultForDomains?: string[];
28
+ }
29
+ /** Runtime-safe subset of `AutoI18nConfig` used for route locale resolution. */
30
+ interface RuntimeI18nConfig {
31
+ defaultLocale: string;
32
+ strategy: 'no_prefix' | 'prefix_except_default' | 'prefix' | 'prefix_and_default';
33
+ locales: RuntimeLocale[];
34
+ differentDomains?: boolean;
35
+ multiDomainLocales?: boolean;
36
+ /** Translated route paths, when i18n is configured with custom routes. */
37
+ pages?: LocalePages;
38
+ }
39
+ interface LocaleAlternate {
40
+ code: string;
41
+ hreflang: string;
42
+ path: string;
43
+ domain?: string;
44
+ }
45
+ type LocaleAlternateResolution = {
46
+ _tag: 'pages';
47
+ alternates: LocaleAlternate[];
48
+ } | {
49
+ _tag: 'strategy';
50
+ alternates: LocaleAlternate[];
51
+ };
52
+ interface RouteLocaleInfo {
53
+ /** Resolved locale code for this route */
54
+ locale: string;
55
+ /** Route with locale prefix stripped (e.g. /fr/about → /about). For no_prefix this equals route. */
56
+ basePath: string;
57
+ }
58
+ interface RuntimeRouteContext {
59
+ /** Request host, used to resolve locales under domain-based strategies. */
60
+ host?: string;
61
+ /** Known current locale, required to translate no_prefix routes without a locale domain. */
62
+ locale?: string;
63
+ }
64
+ /**
65
+ * Resolve which locale a route belongs to and the locale-stripped base path.
66
+ */
67
+ declare function resolveLocaleFromRoute(route: string, i18n: RuntimeI18nConfig, context?: RuntimeRouteContext): RouteLocaleInfo;
68
+ /**
69
+ * Build the URL path for a base path under a given locale, honoring the i18n strategy.
70
+ */
71
+ declare function localePath(basePath: string, locale: string, i18n: RuntimeI18nConfig, context?: RuntimeRouteContext): string;
72
+ /**
73
+ * Compute hreflang alternates for a given route.
74
+ * Returns the route itself plus all sibling locale variants.
75
+ *
76
+ * Translated slugs (i18n `pages`) can't be derived by adding or removing a
77
+ * locale prefix — `/about` and `/fr/a-propos` are the same page — so the route
78
+ * table is consulted first and prefix arithmetic is the fallback.
79
+ */
80
+ declare function resolveLocaleAlternates(route: string, i18n: RuntimeI18nConfig, context?: RuntimeRouteContext): LocaleAlternateResolution;
81
+ declare function computeLocaleAlternates(route: string, i18n: RuntimeI18nConfig, context?: RuntimeRouteContext): LocaleAlternate[];
82
+
83
+ export { computeLocaleAlternates, localePath, resolveLocaleAlternates, resolveLocaleFromRoute };
84
+ export type { LocaleAlternate, LocaleAlternateResolution, LocalePages, RouteLocaleInfo, RuntimeI18nConfig, RuntimeLocale, RuntimeRouteContext };
@@ -0,0 +1,270 @@
1
+ function normalizeHost(value) {
2
+ return value.trim().toLowerCase().replace(/^[a-z][a-z\d+.-]*:\/\//, "").split("/")[0];
3
+ }
4
+ function localeDomains(locale) {
5
+ return locale.domains?.length ? locale.domains : locale.domain ? [locale.domain] : [];
6
+ }
7
+ function resolveLocaleFromHost(host, i18n) {
8
+ if (!host)
9
+ return void 0;
10
+ const normalizedHost = normalizeHost(host);
11
+ const domainDefault = i18n.locales.find(
12
+ (locale) => locale.defaultForDomains?.some((domain) => normalizeHost(domain) === normalizedHost)
13
+ );
14
+ if (domainDefault)
15
+ return domainDefault;
16
+ const matches = i18n.locales.filter(
17
+ (locale) => localeDomains(locale).some((domain) => normalizeHost(domain) === normalizedHost)
18
+ );
19
+ return matches.length === 1 ? matches[0] : matches.find((locale) => locale.code === i18n.defaultLocale);
20
+ }
21
+ function resolveLocaleDomain(locale) {
22
+ return locale.defaultForDomains?.[0] || locale.domain || locale.domains?.[0];
23
+ }
24
+ function splitRouteSuffix(route) {
25
+ const suffixIndex = route.search(/[?#]/);
26
+ const rawPathname = suffixIndex === -1 ? route : route.slice(0, suffixIndex);
27
+ return {
28
+ pathname: rawPathname ? rawPathname.startsWith("/") ? rawPathname : `/${rawPathname}` : "/",
29
+ suffix: suffixIndex === -1 ? "" : route.slice(suffixIndex)
30
+ };
31
+ }
32
+ function resolveLocaleFromRoute(route, i18n, context = {}) {
33
+ const { pathname, suffix } = splitRouteSuffix(route);
34
+ if (i18n.strategy !== "no_prefix") {
35
+ const segments = pathname.split("/").filter(Boolean);
36
+ const first = segments[0];
37
+ const matched = first ? i18n.locales.find((l) => l.code === first) : void 0;
38
+ if (matched) {
39
+ const rest = segments.slice(1).join("/");
40
+ return { locale: matched.code, basePath: `${rest ? `/${rest}` : "/"}${suffix}` };
41
+ }
42
+ }
43
+ const contextLocale = context.locale ? i18n.locales.find((locale) => locale.code === context.locale) : void 0;
44
+ const domainLocale = resolveLocaleFromHost(context.host, i18n);
45
+ return { locale: contextLocale?.code || domainLocale?.code || i18n.defaultLocale, basePath: `${pathname}${suffix}` };
46
+ }
47
+ function localePath(basePath, locale, i18n, context = {}) {
48
+ const { pathname, suffix } = splitRouteSuffix(basePath);
49
+ if (i18n.strategy === "no_prefix")
50
+ return `${pathname}${suffix}`;
51
+ const isDefault = locale === i18n.defaultLocale;
52
+ const localeConfig = i18n.locales.find((item) => item.code === locale);
53
+ const normalizedHost = context.host ? normalizeHost(context.host) : void 0;
54
+ const matchesDomainDefault = !!normalizedHost && !!localeConfig?.defaultForDomains?.some((domain) => normalizeHost(domain) === normalizedHost);
55
+ const isDomainDefault = i18n.differentDomains || matchesDomainDefault;
56
+ if (i18n.strategy === "prefix_except_default" && (isDefault || isDomainDefault))
57
+ return `${pathname}${suffix}`;
58
+ if (i18n.strategy === "prefix_and_default" && isDomainDefault)
59
+ return `${pathname}${suffix}`;
60
+ if (pathname === "/")
61
+ return `/${locale}${suffix}`;
62
+ return `/${locale}${pathname}${suffix}`;
63
+ }
64
+ function toSegments(path) {
65
+ return path.split("/").filter(Boolean);
66
+ }
67
+ const PAGE_PARAM_PATTERN = /\[\[(\.\.\.)?([^[\]]+)\]\]|\[(\.\.\.)?([^[\]]+)\]|:(\w+)(?:\((\.\*)\))?([?*+]?)/g;
68
+ function parsePageSegment(segment) {
69
+ const tokens = [];
70
+ let offset = 0;
71
+ for (const match of segment.matchAll(PAGE_PARAM_PATTERN)) {
72
+ const index = match.index;
73
+ if (index > offset)
74
+ tokens.push({ _tag: "static", value: segment.slice(offset, index) });
75
+ if (match[2]) {
76
+ tokens.push({ _tag: "param", param: { name: match[2], catchAll: !!match[1], optional: true } });
77
+ } else if (match[4]) {
78
+ tokens.push({ _tag: "param", param: { name: match[4], catchAll: !!match[3], optional: false } });
79
+ } else {
80
+ const modifier = match[7];
81
+ tokens.push({
82
+ _tag: "param",
83
+ param: {
84
+ name: match[5],
85
+ catchAll: !!match[6] || modifier === "*" || modifier === "+",
86
+ optional: modifier === "?" || modifier === "*"
87
+ }
88
+ });
89
+ }
90
+ offset = index + match[0].length;
91
+ }
92
+ if (offset < segment.length)
93
+ tokens.push({ _tag: "static", value: segment.slice(offset) });
94
+ return tokens.length ? tokens : [{ _tag: "static", value: segment }];
95
+ }
96
+ function wholeSegmentParam(tokens) {
97
+ return tokens.length === 1 && tokens[0]?._tag === "param" ? tokens[0].param : null;
98
+ }
99
+ function segmentRanks(pattern) {
100
+ return toSegments(pattern).map((segment) => {
101
+ const tokens = parsePageSegment(segment);
102
+ const params = tokens.filter((token) => token._tag === "param");
103
+ if (!params.length)
104
+ return 6;
105
+ const hasStatic = tokens.some((token) => token._tag === "static");
106
+ if (hasStatic)
107
+ return params.some((token) => token.param.optional) ? 3 : 4;
108
+ const param = params[0].param;
109
+ if (param.catchAll)
110
+ return param.optional ? -1 : 0;
111
+ return param.optional ? 1 : 2;
112
+ });
113
+ }
114
+ function compareSpecificity(a, b) {
115
+ const length = Math.min(a.length, b.length);
116
+ for (let i = 0; i < length; i++) {
117
+ const diff = b[i] - a[i];
118
+ if (diff !== 0)
119
+ return diff;
120
+ }
121
+ return a.length - b.length;
122
+ }
123
+ function matchSegmentTokens(tokens, path) {
124
+ function visit(index, offset, params) {
125
+ if (index === tokens.length)
126
+ return offset === path.length ? params : null;
127
+ const token = tokens[index];
128
+ if (token._tag === "static") {
129
+ return path.startsWith(token.value, offset) ? visit(index + 1, offset + token.value.length, params) : null;
130
+ }
131
+ const minimumEnd = token.param.optional ? offset : offset + 1;
132
+ for (let end = minimumEnd; end <= path.length; end++) {
133
+ const value = path.slice(offset, end);
134
+ const nextParams = value ? { ...params, [token.param.name]: value } : params;
135
+ const matched = visit(index + 1, end, nextParams);
136
+ if (matched)
137
+ return matched;
138
+ }
139
+ return null;
140
+ }
141
+ return visit(0, 0, {});
142
+ }
143
+ function matchPagePattern(pattern, path) {
144
+ const patternSegments = toSegments(pattern);
145
+ const pathSegments = toSegments(path);
146
+ function visit(patternIndex, pathIndex, params) {
147
+ if (patternIndex === patternSegments.length)
148
+ return pathIndex === pathSegments.length ? params : null;
149
+ const tokens = parsePageSegment(patternSegments[patternIndex]);
150
+ const param = wholeSegmentParam(tokens);
151
+ if (param?.catchAll) {
152
+ const minimumEnd = param.optional ? pathIndex : pathIndex + 1;
153
+ for (let end = pathSegments.length; end >= minimumEnd; end--) {
154
+ const value = pathSegments.slice(pathIndex, end).join("/");
155
+ const nextParams = value ? { ...params, [param.name]: value } : params;
156
+ const matched = visit(patternIndex + 1, end, nextParams);
157
+ if (matched)
158
+ return matched;
159
+ }
160
+ return null;
161
+ }
162
+ const segment = pathSegments[pathIndex];
163
+ if (segment !== void 0) {
164
+ const segmentParams = matchSegmentTokens(tokens, segment);
165
+ if (segmentParams) {
166
+ const matched = visit(patternIndex + 1, pathIndex + 1, { ...params, ...segmentParams });
167
+ if (matched)
168
+ return matched;
169
+ }
170
+ }
171
+ return param?.optional ? visit(patternIndex + 1, pathIndex, params) : null;
172
+ }
173
+ return visit(0, 0, {});
174
+ }
175
+ function fillPagePattern(pattern, params) {
176
+ const filled = [];
177
+ for (const segment of toSegments(pattern)) {
178
+ const tokens = parsePageSegment(segment);
179
+ let value = "";
180
+ for (const token of tokens) {
181
+ if (token._tag === "static") {
182
+ value += token.value;
183
+ continue;
184
+ }
185
+ const paramValue = params[token.param.name];
186
+ if (paramValue === void 0) {
187
+ if (token.param.optional)
188
+ continue;
189
+ return null;
190
+ }
191
+ value += paramValue;
192
+ }
193
+ if (value)
194
+ filled.push(value);
195
+ }
196
+ return filled.length ? `/${filled.join("/")}` : "/";
197
+ }
198
+ function alternatesForEntry(localePaths, params, i18n, context) {
199
+ const untranslated = localePaths[i18n.defaultLocale];
200
+ const alternates = [];
201
+ for (const l of i18n.locales) {
202
+ const pattern = localePaths[l.code] ?? untranslated;
203
+ if (localePaths[l.code] === false)
204
+ continue;
205
+ if (typeof pattern !== "string")
206
+ continue;
207
+ const path = fillPagePattern(pattern, params);
208
+ if (path === null)
209
+ continue;
210
+ const domain = resolveLocaleDomain(l);
211
+ alternates.push({
212
+ code: l.code,
213
+ hreflang: l.hreflang || l.code,
214
+ path: localePath(path, l.code, i18n, { host: domain || context.host }),
215
+ ...domain ? { domain } : {}
216
+ });
217
+ }
218
+ return alternates.length ? alternates : null;
219
+ }
220
+ function alternatesFromPages(basePath, locale, i18n, context) {
221
+ const pages = i18n.pages;
222
+ const hasDomainLocales = i18n.differentDomains || i18n.multiDomainLocales;
223
+ const hasContextLocale = !!context.locale && i18n.locales.some((locale2) => locale2.code === context.locale);
224
+ if (!pages || i18n.strategy === "no_prefix" && !hasDomainLocales && !hasContextLocale)
225
+ return null;
226
+ const matches = [];
227
+ for (const localePaths of Object.values(pages)) {
228
+ const pattern = localePaths?.[locale];
229
+ if (!pattern)
230
+ continue;
231
+ const params = matchPagePattern(pattern, basePath);
232
+ if (params)
233
+ matches.push({ ranks: segmentRanks(pattern), localePaths, params });
234
+ }
235
+ matches.sort((a, b) => compareSpecificity(a.ranks, b.ranks));
236
+ for (const match of matches) {
237
+ const alternates = alternatesForEntry(match.localePaths, match.params, i18n, context);
238
+ if (alternates)
239
+ return alternates;
240
+ }
241
+ return null;
242
+ }
243
+ function resolveLocaleAlternates(route, i18n, context = {}) {
244
+ const { locale, basePath } = resolveLocaleFromRoute(route, i18n, context);
245
+ const { pathname, suffix } = splitRouteSuffix(basePath);
246
+ const translated = alternatesFromPages(pathname, locale, i18n, context);
247
+ if (translated) {
248
+ return {
249
+ _tag: "pages",
250
+ alternates: translated.map((alternate) => ({ ...alternate, path: `${alternate.path}${suffix}` }))
251
+ };
252
+ }
253
+ return {
254
+ _tag: "strategy",
255
+ alternates: i18n.locales.map((l) => {
256
+ const domain = resolveLocaleDomain(l);
257
+ return {
258
+ code: l.code,
259
+ hreflang: l.hreflang || l.code,
260
+ path: localePath(basePath, l.code, i18n, { host: domain || context.host }),
261
+ ...domain ? { domain } : {}
262
+ };
263
+ })
264
+ };
265
+ }
266
+ function computeLocaleAlternates(route, i18n, context = {}) {
267
+ return resolveLocaleAlternates(route, i18n, context).alternates;
268
+ }
269
+
270
+ export { computeLocaleAlternates, localePath, resolveLocaleAlternates, resolveLocaleFromRoute };
package/dist/i18n.d.mts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { LocaleObject, NuxtI18nOptions } from '@nuxtjs/i18n';
2
+ import { RuntimeI18nConfig } from './i18n-runtime.mjs';
3
+ export { LocaleAlternate, LocaleAlternateResolution, LocalePages, RouteLocaleInfo, RuntimeLocale, RuntimeRouteContext } from './i18n-runtime.mjs';
2
4
 
3
5
  declare const I18N_MODULES: readonly ["@nuxtjs/i18n", "nuxt-i18n-micro"];
4
6
  type I18nModuleName = typeof I18N_MODULES[number];
@@ -12,6 +14,7 @@ interface AutoI18nConfig {
12
14
  defaultLocale: string;
13
15
  strategy: Strategies;
14
16
  differentDomains?: boolean;
17
+ multiDomainLocales?: boolean;
15
18
  pages?: Record<string, Record<string, string | false>>;
16
19
  }
17
20
  interface StrategyProps {
@@ -61,7 +64,13 @@ declare function resolveI18nModule(): false | I18nModuleResolution;
61
64
  declare function resolveI18nConfig(logger?: {
62
65
  warn: (msg: string) => void;
63
66
  }): Promise<false | AutoI18nConfig>;
67
+ /**
68
+ * Strip a build-time i18n config down to what `./i18n-runtime` needs, dropping
69
+ * the non-serializable `LocaleObject` extras so it can be handed to the runtime
70
+ * through `runtimeConfig`.
71
+ */
72
+ declare function toRuntimeI18nConfig(auto: AutoI18nConfig): RuntimeI18nConfig;
64
73
  declare function mergeOnKey<T extends Record<string, any>>(arr: T[], key: keyof T): T[];
65
74
 
66
- export { expandCompactLocaleRoute, generatePathForI18nPages, isCompactLocaleRoute, mapPathForI18nPages, mergeOnKey, normalizeLocales, resolveI18nConfig, resolveI18nModule, splitPathForI18nLocales };
75
+ export { RuntimeI18nConfig, expandCompactLocaleRoute, generatePathForI18nPages, isCompactLocaleRoute, mapPathForI18nPages, mergeOnKey, normalizeLocales, resolveI18nConfig, resolveI18nModule, splitPathForI18nLocales, toRuntimeI18nConfig };
67
76
  export type { AutoI18nConfig, ExpandedLocaleRoute, I18nModuleResolution, NormalisedLocale, Strategies, StrategyProps };
package/dist/i18n.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { LocaleObject, NuxtI18nOptions } from '@nuxtjs/i18n';
2
+ import { RuntimeI18nConfig } from './i18n-runtime.js';
3
+ export { LocaleAlternate, LocaleAlternateResolution, LocalePages, RouteLocaleInfo, RuntimeLocale, RuntimeRouteContext } from './i18n-runtime.js';
2
4
 
3
5
  declare const I18N_MODULES: readonly ["@nuxtjs/i18n", "nuxt-i18n-micro"];
4
6
  type I18nModuleName = typeof I18N_MODULES[number];
@@ -12,6 +14,7 @@ interface AutoI18nConfig {
12
14
  defaultLocale: string;
13
15
  strategy: Strategies;
14
16
  differentDomains?: boolean;
17
+ multiDomainLocales?: boolean;
15
18
  pages?: Record<string, Record<string, string | false>>;
16
19
  }
17
20
  interface StrategyProps {
@@ -61,7 +64,13 @@ declare function resolveI18nModule(): false | I18nModuleResolution;
61
64
  declare function resolveI18nConfig(logger?: {
62
65
  warn: (msg: string) => void;
63
66
  }): Promise<false | AutoI18nConfig>;
67
+ /**
68
+ * Strip a build-time i18n config down to what `./i18n-runtime` needs, dropping
69
+ * the non-serializable `LocaleObject` extras so it can be handed to the runtime
70
+ * through `runtimeConfig`.
71
+ */
72
+ declare function toRuntimeI18nConfig(auto: AutoI18nConfig): RuntimeI18nConfig;
64
73
  declare function mergeOnKey<T extends Record<string, any>>(arr: T[], key: keyof T): T[];
65
74
 
66
- export { expandCompactLocaleRoute, generatePathForI18nPages, isCompactLocaleRoute, mapPathForI18nPages, mergeOnKey, normalizeLocales, resolveI18nConfig, resolveI18nModule, splitPathForI18nLocales };
75
+ export { RuntimeI18nConfig, expandCompactLocaleRoute, generatePathForI18nPages, isCompactLocaleRoute, mapPathForI18nPages, mergeOnKey, normalizeLocales, resolveI18nConfig, resolveI18nModule, splitPathForI18nLocales, toRuntimeI18nConfig };
67
76
  export type { AutoI18nConfig, ExpandedLocaleRoute, I18nModuleResolution, NormalisedLocale, Strategies, StrategyProps };
package/dist/i18n.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { getNuxtModuleVersion, hasNuxtModuleCompatibility, hasNuxtModule } from '@nuxt/kit';
2
- import { joinURL, withHttps, withBase, withLeadingSlash } from 'ufo';
2
+ import { withHttps, withBase } from 'ufo';
3
+ import { localePath, resolveLocaleAlternates, resolveLocaleFromRoute } from './i18n-runtime.mjs';
3
4
  import { getNuxtModuleOptions } from './kit.mjs';
4
5
  import 'node:url';
5
6
  import 'pathe';
@@ -7,32 +8,41 @@ import 'pkg-types';
7
8
  import 'std-env';
8
9
 
9
10
  const I18N_MODULES = ["@nuxtjs/i18n", "nuxt-i18n-micro"];
10
- const SLASH_PATTERN = /^\/|\/$/g;
11
11
  function generatePathForI18nPages(ctx) {
12
12
  const { localeCode, pageLocales, nuxtI18nConfig, forcedStrategy, normalisedLocales } = ctx;
13
13
  const locale = normalisedLocales.find((l) => l.code === localeCode);
14
- let path = pageLocales;
15
- switch (forcedStrategy ?? nuxtI18nConfig.strategy) {
16
- case "prefix_except_default":
17
- case "prefix_and_default":
18
- path = localeCode === nuxtI18nConfig.defaultLocale ? pageLocales : joinURL(localeCode, pageLocales);
19
- break;
20
- case "prefix":
21
- path = joinURL(localeCode, pageLocales);
22
- break;
23
- }
14
+ const strategy = forcedStrategy ?? nuxtI18nConfig.strategy;
15
+ const i18n = toRuntimeI18nConfig({
16
+ defaultLocale: nuxtI18nConfig.defaultLocale,
17
+ locales: normalisedLocales,
18
+ strategy: strategy === "prefix_and_default" ? "prefix_except_default" : strategy
19
+ });
20
+ const generated = localePath(pageLocales, localeCode, i18n);
21
+ const prefixed = generated === localePath(pageLocales, localeCode, { ...i18n, strategy: "prefix" });
22
+ const path = prefixed ? generated.slice(1) : pageLocales;
24
23
  return locale?.domain ? withHttps(withBase(path, locale.domain)) : path;
25
24
  }
26
25
  function splitPathForI18nLocales(path, autoI18n) {
27
- const locales = autoI18n.strategy === "prefix_except_default" ? autoI18n.locales.filter((l) => l.code !== autoI18n.defaultLocale) : autoI18n.locales;
26
+ const selectedLocales = autoI18n.strategy === "prefix_except_default" ? autoI18n.locales.filter((l) => l.code !== autoI18n.defaultLocale) : autoI18n.locales;
28
27
  if (!path || path.startsWith("/_"))
29
28
  return path;
30
- const hasLocalePrefix = locales.some((l) => path.startsWith(`/${l.code}/`) || path === `/${l.code}`);
29
+ const localeCodes = new Set(selectedLocales.map((locale) => locale.code));
30
+ const runtimeI18n = toRuntimeI18nConfig(autoI18n);
31
+ const i18n = {
32
+ ...runtimeI18n,
33
+ strategy: "prefix",
34
+ locales: runtimeI18n.locales.filter((locale) => localeCodes.has(locale.code))
35
+ };
36
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
37
+ const resolved = resolveLocaleFromRoute(normalizedPath, i18n);
38
+ const hasLocalePrefix = i18n.locales.some(
39
+ (l) => l.code === resolved.locale && localePath(resolved.basePath, l.code, i18n) === normalizedPath
40
+ );
31
41
  if (hasLocalePrefix)
32
42
  return path;
33
43
  return [
34
44
  path,
35
- ...locales.map((l) => `/${l.code}${path}`)
45
+ ...i18n.locales.map((l) => localePath(path, l.code, i18n))
36
46
  ];
37
47
  }
38
48
  const COMPACT_LOCALE_PATTERN = /^\/:locale\(([^)]+)\)/;
@@ -72,36 +82,24 @@ function mapPathForI18nPages(path, autoI18n) {
72
82
  const pages = autoI18n.pages;
73
83
  if (!pages || !Object.keys(pages).length)
74
84
  return false;
75
- const withoutSlashes = path.replace(SLASH_PATTERN, "").replace("/index", "");
76
- function resolveForAllLocales(pageName, pageLocales) {
77
- return autoI18n.locales.filter((l) => {
78
- if (l.code in pageLocales && pageLocales[l.code] === false)
79
- return false;
80
- if (autoI18n.strategy === "prefix_except_default" && l.code === autoI18n.defaultLocale)
81
- return false;
82
- return true;
83
- }).map((l) => {
84
- const localePath = l.code in pageLocales && pageLocales[l.code] !== false ? pageLocales[l.code] : `/${pageName}`;
85
- return withLeadingSlash(generatePathForI18nPages({
86
- localeCode: l.code,
87
- pageLocales: localePath,
88
- nuxtI18nConfig: { strategy: autoI18n.strategy, defaultLocale: autoI18n.defaultLocale },
89
- normalisedLocales: autoI18n.locales
90
- }));
91
- });
92
- }
93
- if (withoutSlashes in pages) {
94
- const pageLocales = pages[withoutSlashes];
95
- if (pageLocales)
96
- return resolveForAllLocales(withoutSlashes, pageLocales);
97
- }
98
- for (const [pageName, pageLocales] of Object.entries(pages)) {
99
- if (!pageLocales)
100
- continue;
101
- if (autoI18n.defaultLocale in pageLocales && pageLocales[autoI18n.defaultLocale] === path)
102
- return resolveForAllLocales(pageName, pageLocales);
103
- }
104
- return false;
85
+ const materializedPages = Object.fromEntries(
86
+ Object.entries(pages).map(([pageName, pageLocales]) => [
87
+ pageName,
88
+ Object.fromEntries(autoI18n.locales.map((locale) => {
89
+ const configuredPath = pageLocales[locale.code];
90
+ return [locale.code, configuredPath === void 0 ? `/${pageName}` : configuredPath];
91
+ }))
92
+ ])
93
+ );
94
+ const i18n = toRuntimeI18nConfig({
95
+ ...autoI18n,
96
+ strategy: autoI18n.strategy === "prefix_and_default" ? "prefix_except_default" : autoI18n.strategy,
97
+ pages: materializedPages
98
+ });
99
+ const resolved = resolveLocaleAlternates(path, i18n, autoI18n.strategy === "no_prefix" ? { locale: autoI18n.defaultLocale } : {});
100
+ if (resolved._tag === "strategy")
101
+ return false;
102
+ return resolved.alternates.filter((alternate) => autoI18n.strategy !== "prefix_except_default" || alternate.code !== autoI18n.defaultLocale).map((alternate) => alternate.domain ? withHttps(withBase(alternate.path, alternate.domain)) : alternate.path);
105
103
  }
106
104
  function resolveI18nModule() {
107
105
  const found = I18N_MODULES.find((m) => hasNuxtModule(m));
@@ -134,17 +132,43 @@ async function resolveI18nConfig(logger) {
134
132
  const normalisedLocales = normalizeLocales(nuxtI18nConfig);
135
133
  const pages = resolveI18nPages(nuxtI18nConfig, i18n.isMicro);
136
134
  const usingI18nPages = Object.keys(pages || {}).length;
137
- const hasI18nConfigForAlternatives = nuxtI18nConfig.differentDomains || usingI18nPages || nuxtI18nConfig.strategy !== "no_prefix" && nuxtI18nConfig.locales;
135
+ const hasI18nConfigForAlternatives = nuxtI18nConfig.differentDomains || nuxtI18nConfig.multiDomainLocales || usingI18nPages || nuxtI18nConfig.strategy !== "no_prefix" && nuxtI18nConfig.locales;
138
136
  if (!hasI18nConfigForAlternatives)
139
137
  return false;
140
138
  return {
141
139
  differentDomains: nuxtI18nConfig.differentDomains,
140
+ multiDomainLocales: nuxtI18nConfig.multiDomainLocales,
142
141
  defaultLocale: nuxtI18nConfig.defaultLocale,
143
142
  locales: normalisedLocales,
144
143
  strategy: nuxtI18nConfig.strategy,
145
144
  pages
146
145
  };
147
146
  }
147
+ function toRuntimeI18nConfig(auto) {
148
+ return {
149
+ defaultLocale: auto.defaultLocale,
150
+ strategy: auto.strategy,
151
+ ...auto.differentDomains ? { differentDomains: true } : {},
152
+ ...auto.multiDomainLocales ? { multiDomainLocales: true } : {},
153
+ // Translated route paths. Without these the runtime can only guess
154
+ // alternates by adding/removing a locale prefix, which is wrong for every
155
+ // page whose slug differs per locale.
156
+ ...auto.pages && Object.keys(auto.pages).length ? { pages: auto.pages } : {},
157
+ locales: auto.locales.map((l) => {
158
+ const raw = l;
159
+ return {
160
+ code: l.code,
161
+ hreflang: l._hreflang || raw.language || l.code,
162
+ name: raw.name,
163
+ nativeName: raw.nativeName ?? raw.name,
164
+ ...raw.language ? { language: raw.language } : {},
165
+ ...raw.domain ? { domain: raw.domain } : {},
166
+ ...raw.domains?.length ? { domains: [...raw.domains] } : {},
167
+ ...raw.defaultForDomains?.length ? { defaultForDomains: [...raw.defaultForDomains] } : {}
168
+ };
169
+ })
170
+ };
171
+ }
148
172
  function mergeOnKey(arr, key) {
149
173
  const map = /* @__PURE__ */ new Map();
150
174
  for (const item of arr) {
@@ -158,4 +182,4 @@ function mergeOnKey(arr, key) {
158
182
  return [...map.values()];
159
183
  }
160
184
 
161
- export { expandCompactLocaleRoute, generatePathForI18nPages, isCompactLocaleRoute, mapPathForI18nPages, mergeOnKey, normalizeLocales, resolveI18nConfig, resolveI18nModule, splitPathForI18nLocales };
185
+ export { expandCompactLocaleRoute, generatePathForI18nPages, isCompactLocaleRoute, mapPathForI18nPages, mergeOnKey, normalizeLocales, resolveI18nConfig, resolveI18nModule, splitPathForI18nLocales, toRuntimeI18nConfig };
package/dist/kit.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { pathToFileURL } from 'node:url';
2
- import { getNuxtVersion, addTypeTemplate, useNuxt, resolveModule, createResolver, addTemplate, loadNuxtModuleInstance, tryUseNuxt, hasNuxtModule, hasNuxtModuleCompatibility, useLogger } from '@nuxt/kit';
2
+ import { getNuxtVersion, addTypeTemplate, useNuxt, useLogger, resolveModule, directoryToURL, createResolver, addTemplate, loadNuxtModuleInstance, tryUseNuxt, hasNuxtModule, hasNuxtModuleCompatibility } from '@nuxt/kit';
3
3
  import { relative, dirname } from 'pathe';
4
4
  import { resolvePackageJSON, readPackageJSON } from 'pkg-types';
5
5
  import { provider, env } from 'std-env';
@@ -125,12 +125,38 @@ ${indent(h3Runtime.trim(), 2)}
125
125
  }
126
126
  `;
127
127
  }
128
- function applyNitroRuntimeCompatibility(nuxt, compatibility) {
128
+ function resolveRuntimeModule(nuxt, id) {
129
+ try {
130
+ return {
131
+ _tag: "resolved",
132
+ path: resolveModule(id, {
133
+ url: [...nuxt.options.modulesDir.map(directoryToURL), new URL(import.meta.url)]
134
+ })
135
+ };
136
+ } catch (cause) {
137
+ return { _tag: "unresolved", cause };
138
+ }
139
+ }
140
+ function applyNitroRuntimeCompatibility(nuxt, compatibility, reportResolutionFailure = false) {
129
141
  const nuxtOptions = nuxt.options;
130
142
  const nitroOptions = nuxtOptions.nitro ||= {};
131
143
  nitroOptions.alias ||= {};
132
144
  nitroOptions.virtual ||= {};
133
- nitroOptions.alias[H3_RUNTIME_MODULE] = compatibility._tag === "nitro-v3" ? "nitro/h3" : "h3";
145
+ const h3RuntimeModule = compatibility._tag === "nitro-v3" ? "nitro/h3" : "h3";
146
+ nitroOptions.alias[H3_RUNTIME_MODULE] = h3RuntimeModule;
147
+ const h3Resolution = resolveRuntimeModule(nuxt, h3RuntimeModule);
148
+ if (h3Resolution._tag === "resolved") {
149
+ nitroOptions.typescript ||= {};
150
+ nitroOptions.typescript.tsConfig ||= {};
151
+ nitroOptions.typescript.tsConfig.compilerOptions ||= {};
152
+ nitroOptions.typescript.tsConfig.compilerOptions.paths ||= {};
153
+ nitroOptions.typescript.tsConfig.compilerOptions.paths[H3_RUNTIME_MODULE] = [h3Resolution.path];
154
+ } else if (reportResolutionFailure) {
155
+ useLogger("nuxtseo-shared").warn(
156
+ `Could not resolve Nitro runtime module '${h3RuntimeModule}'. Generated server types may be incomplete.`,
157
+ h3Resolution.cause
158
+ );
159
+ }
134
160
  if (compatibility._tag === "nitro-v3")
135
161
  nitroOptions.alias[OFETCH_RUNTIME_MODULE] = resolveModule("ofetch", { url: new URL(import.meta.url) });
136
162
  nitroOptions.virtual[NITRO_RUNTIME_MODULE] = compatibility._tag === "nitro-v3" ? nitroV3Runtime : nitroV2Runtime;
@@ -165,7 +191,7 @@ function setupNitroRuntimeCompatibility(nuxt = useNuxt()) {
165
191
  const nuxtWithRuntimeMarker = nuxt;
166
192
  if (!nuxtWithRuntimeMarker[runtimeSetupMarker]) {
167
193
  nuxtWithRuntimeMarker[runtimeSetupMarker] = true;
168
- nuxt.hooks.hookOnce("modules:done", () => applyNitroRuntimeCompatibility(nuxt, compatibility));
194
+ nuxt.hooks.hookOnce("modules:done", () => applyNitroRuntimeCompatibility(nuxt, compatibility, true));
169
195
  }
170
196
  const nuxtWithTypeMarker = nuxt;
171
197
  if (!nuxtWithTypeMarker[typeSetupMarker]) {
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=3.16.0"
6
6
  },
7
- "version": "5.3.10",
7
+ "version": "5.3.11",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxtseo-shared",
3
3
  "type": "module",
4
- "version": "5.3.10",
4
+ "version": "5.3.11",
5
5
  "description": "Shared utilities for Nuxt SEO modules.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -40,6 +40,10 @@
40
40
  "types": "./dist/i18n.d.mts",
41
41
  "default": "./dist/i18n.mjs"
42
42
  },
43
+ "./i18n-runtime": {
44
+ "types": "./dist/i18n-runtime.d.mts",
45
+ "default": "./dist/i18n-runtime.mjs"
46
+ },
43
47
  "./pro": {
44
48
  "types": "./dist/pro.d.mts",
45
49
  "default": "./dist/pro.mjs"
@@ -81,7 +85,7 @@
81
85
  "dependencies": {
82
86
  "@clack/prompts": "^1.7.0",
83
87
  "@nuxt/devtools-kit": "4.0.0-alpha.7",
84
- "@nuxt/kit": "^4.5.1",
88
+ "@nuxt/kit": "^4.5.2",
85
89
  "birpc": "^4.0.0",
86
90
  "consola": "^3.4.2",
87
91
  "defu": "^6.1.7",
@@ -97,16 +101,16 @@
97
101
  "devDependencies": {
98
102
  "@arethetypeswrong/cli": "^0.18.5",
99
103
  "@nuxt/module-builder": "^1.0.3",
100
- "@nuxt/schema": "^4.5.1",
104
+ "@nuxt/schema": "^4.5.2",
101
105
  "@nuxt/test-utils": "^4.1.0",
102
106
  "@nuxtjs/i18n": "^10.6.0",
103
107
  "h3": "^1.15.11",
104
108
  "nitropack": "^2.13.4",
105
- "nuxt": "^4.5.1",
106
- "nuxt-site-config": "^4.1.2",
109
+ "nuxt": "^4.5.2",
110
+ "nuxt-site-config": "^4.1.5",
107
111
  "typescript": "6.0.3",
108
112
  "vitest": "^4.1.10",
109
- "vue": "^3.5.40",
113
+ "vue": "^3.5.41",
110
114
  "vue-tsc": "^3.3.9"
111
115
  },
112
116
  "scripts": {