@turnipxenon/pineapple 4.5.0 → 4.5.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.
@@ -0,0 +1,1070 @@
1
+ // eslint-disable
2
+
3
+ /** @type {any} */
4
+ const URLPattern = {}
5
+
6
+ /**
7
+ * The project's base locale.
8
+ *
9
+ * @example
10
+ * if (locale === baseLocale) {
11
+ * // do something
12
+ * }
13
+ */
14
+ export const baseLocale = "en";
15
+ /**
16
+ * The project's locales that have been specified in the settings.
17
+ *
18
+ * @example
19
+ * if (locales.includes(userSelectedLocale) === false) {
20
+ * throw new Error('Locale is not available');
21
+ * }
22
+ */
23
+ export const locales = /** @type {const} */ (["en", "fr", "tl"]);
24
+ /** @type {string} */
25
+ export const cookieName = "PARAGLIDE_LOCALE";
26
+ /** @type {number} */
27
+ export const cookieMaxAge = 34560000;
28
+ /** @type {string} */
29
+ export const localStorageKey = "PARAGLIDE_LOCALE";
30
+ /**
31
+ * @type {Array<"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage">}
32
+ */
33
+ export const strategy = [
34
+ "url",
35
+ "cookie",
36
+ "baseLocale"
37
+ ];
38
+ /**
39
+ * The used URL patterns.
40
+ *
41
+ * @type {Array<{ pattern: string, localized: Array<[Locale, string]> }> }
42
+ */
43
+ export const urlPatterns = [
44
+ {
45
+ "pattern": ":protocol://:domain(.*)::port?/:path(.*)?",
46
+ "localized": [
47
+ [
48
+ "fr",
49
+ ":protocol://:domain(.*)::port?/fr/:path(.*)?"
50
+ ],
51
+ [
52
+ "tl",
53
+ ":protocol://:domain(.*)::port?/tl/:path(.*)?"
54
+ ],
55
+ [
56
+ "en",
57
+ ":protocol://:domain(.*)::port?/:path(.*)?"
58
+ ]
59
+ ]
60
+ }
61
+ ];
62
+ /**
63
+ * @typedef {{
64
+ * getStore(): {
65
+ * locale?: Locale,
66
+ * origin?: string,
67
+ * messageCalls?: Set<string>
68
+ * } | undefined,
69
+ * run: (store: { locale?: Locale, origin?: string, messageCalls?: Set<string>},
70
+ * cb: any) => any
71
+ * }} ParaglideAsyncLocalStorage
72
+ */
73
+ /**
74
+ * Server side async local storage that is set by `serverMiddleware()`.
75
+ *
76
+ * The variable is used to retrieve the locale and origin in a server-side
77
+ * rendering context without effecting other requests.
78
+ *
79
+ * @type {ParaglideAsyncLocalStorage | undefined}
80
+ */
81
+ export let serverAsyncLocalStorage = undefined;
82
+ export const disableAsyncLocalStorage = false;
83
+ export const experimentalMiddlewareLocaleSplitting = false;
84
+ export const isServer = import.meta.env?.SSR ?? typeof window === 'undefined';
85
+ /**
86
+ * Sets the server side async local storage.
87
+ *
88
+ * The function is needed because the `runtime.js` file
89
+ * must define the `serverAsyncLocalStorage` variable to
90
+ * avoid a circular import between `runtime.js` and
91
+ * `server.js` files.
92
+ *
93
+ * @param {ParaglideAsyncLocalStorage | undefined} value
94
+ */
95
+ export function overwriteServerAsyncLocalStorage(value) {
96
+ serverAsyncLocalStorage = value;
97
+ }
98
+ const TREE_SHAKE_COOKIE_STRATEGY_USED = true;
99
+ const TREE_SHAKE_URL_STRATEGY_USED = true;
100
+ const TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED = false;
101
+ const TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED = false;
102
+ const TREE_SHAKE_DEFAULT_URL_PATTERN_USED = true;
103
+ const TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED = false;
104
+
105
+ globalThis.__paraglide = {}
106
+
107
+ /**
108
+ * This is a fallback to get started with a custom
109
+ * strategy and avoid type errors.
110
+ *
111
+ * The implementation is overwritten
112
+ * by \`overwriteGetLocale()\` and \`defineSetLocale()\`.
113
+ *
114
+ * @type {Locale|undefined}
115
+ */
116
+ let _locale;
117
+ let localeInitiallySet = false;
118
+ /**
119
+ * Get the current locale.
120
+ *
121
+ * @example
122
+ * if (getLocale() === 'de') {
123
+ * console.log('Germany 🇩🇪');
124
+ * } else if (getLocale() === 'nl') {
125
+ * console.log('Netherlands 🇳🇱');
126
+ * }
127
+ *
128
+ * @type {() => Locale}
129
+ */
130
+ export let getLocale = () => {
131
+ /** @type {string | undefined} */
132
+ let locale;
133
+ // if running in a server-side rendering context
134
+ // retrieve the locale from the async local storage
135
+ if (serverAsyncLocalStorage) {
136
+ const locale = serverAsyncLocalStorage?.getStore()?.locale;
137
+ if (locale) {
138
+ return locale;
139
+ }
140
+ }
141
+ for (const strat of strategy) {
142
+ if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
143
+ locale = extractLocaleFromCookie();
144
+ }
145
+ else if (strat === "baseLocale") {
146
+ locale = baseLocale;
147
+ }
148
+ else if (TREE_SHAKE_URL_STRATEGY_USED &&
149
+ strat === "url" &&
150
+ !isServer &&
151
+ typeof window !== "undefined") {
152
+ locale = extractLocaleFromUrl(window.location.href);
153
+ }
154
+ else if (TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED &&
155
+ strat === "globalVariable" &&
156
+ _locale !== undefined) {
157
+ locale = _locale;
158
+ }
159
+ else if (TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED &&
160
+ strat === "preferredLanguage" &&
161
+ !isServer) {
162
+ locale = negotiatePreferredLanguageFromNavigator();
163
+ }
164
+ else if (TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED &&
165
+ strat === "localStorage" &&
166
+ !isServer) {
167
+ locale = localStorage.getItem(localStorageKey) ?? undefined;
168
+ }
169
+ // check if match, else continue loop
170
+ if (locale !== undefined) {
171
+ const asserted = assertIsLocale(locale);
172
+ if (!localeInitiallySet) {
173
+ _locale = asserted;
174
+ // https://github.com/opral/inlang-paraglide-js/issues/455
175
+ localeInitiallySet = true;
176
+ setLocale(asserted, { reload: false });
177
+ }
178
+ return asserted;
179
+ }
180
+ }
181
+ throw new Error("No locale found. Read the docs https://inlang.com/m/gerre34r/library-inlang-paraglideJs/errors#no-locale-found");
182
+ };
183
+ /**
184
+ * Negotiates a preferred language from navigator.languages.
185
+ *
186
+ * @returns {string|undefined} The negotiated preferred language.
187
+ */
188
+ function negotiatePreferredLanguageFromNavigator() {
189
+ if (!navigator?.languages?.length) {
190
+ return undefined;
191
+ }
192
+ const languages = navigator.languages.map((lang) => ({
193
+ fullTag: lang.toLowerCase(),
194
+ baseTag: lang.split("-")[0]?.toLowerCase(),
195
+ }));
196
+ for (const lang of languages) {
197
+ if (isLocale(lang.fullTag)) {
198
+ return lang.fullTag;
199
+ }
200
+ else if (isLocale(lang.baseTag)) {
201
+ return lang.baseTag;
202
+ }
203
+ }
204
+ return undefined;
205
+ }
206
+ /**
207
+ * Overwrite the \`getLocale()\` function.
208
+ *
209
+ * Use this function to overwrite how the locale is resolved. For example,
210
+ * you can resolve the locale from the browser's preferred language,
211
+ * a cookie, env variable, or a user's preference.
212
+ *
213
+ * @example
214
+ * overwriteGetLocale(() => {
215
+ * // resolve the locale from a cookie. fallback to the base locale.
216
+ * return Cookies.get('locale') ?? baseLocale
217
+ * }
218
+ *
219
+ * @type {(fn: () => Locale) => void}
220
+ */
221
+ export const overwriteGetLocale = (fn) => {
222
+ getLocale = fn;
223
+ };
224
+
225
+ /**
226
+ * Set the locale.
227
+ *
228
+ * Set locale reloads the site by default on the client. Reloading
229
+ * can be disabled by passing \`reload: false\` as an option. If
230
+ * reloading is disabled, you need to ensure that the UI is updated
231
+ * to reflect the new locale.
232
+ *
233
+ * @example
234
+ * setLocale('en');
235
+ *
236
+ * @example
237
+ * setLocale('en', { reload: false });
238
+ *
239
+ * @type {(newLocale: Locale, options?: { reload?: boolean }) => void}
240
+ */
241
+ export let setLocale = (newLocale, options) => {
242
+ const optionsWithDefaults = {
243
+ reload: true,
244
+ ...options,
245
+ };
246
+ // locale is already set
247
+ // https://github.com/opral/inlang-paraglide-js/issues/430
248
+ let currentLocale;
249
+ try {
250
+ currentLocale = getLocale();
251
+ }
252
+ catch {
253
+ // do nothing, no locale has been set yet.
254
+ }
255
+ /** @type {string | undefined} */
256
+ let newLocation = undefined;
257
+ for (const strat of strategy) {
258
+ if (TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED &&
259
+ strat === "globalVariable") {
260
+ // a default for a custom strategy to get started quickly
261
+ // is likely overwritten by `defineSetLocale()`
262
+ _locale = newLocale;
263
+ }
264
+ else if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
265
+ if (isServer || typeof document === "undefined") {
266
+ continue;
267
+ }
268
+ // set the cookie
269
+ document.cookie = `${cookieName}=${newLocale}; path=/; max-age=${cookieMaxAge}`;
270
+ }
271
+ else if (strat === "baseLocale") {
272
+ // nothing to be set here. baseLocale is only a fallback
273
+ continue;
274
+ }
275
+ else if (TREE_SHAKE_URL_STRATEGY_USED &&
276
+ strat === "url" &&
277
+ typeof window !== "undefined") {
278
+ // route to the new url
279
+ //
280
+ // this triggers a page reload but a user rarely
281
+ // switches locales, so this should be fine.
282
+ //
283
+ // if the behavior is not desired, the implementation
284
+ // can be overwritten by `defineSetLocale()` to avoid
285
+ // a full page reload.
286
+ newLocation = localizeUrl(window.location.href, {
287
+ locale: newLocale,
288
+ }).href;
289
+ }
290
+ else if (TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED &&
291
+ strat === "localStorage" &&
292
+ typeof window !== "undefined") {
293
+ // set the localStorage
294
+ localStorage.setItem(localStorageKey, newLocale);
295
+ }
296
+ }
297
+ if (!isServer &&
298
+ optionsWithDefaults.reload &&
299
+ window.location &&
300
+ newLocale !== currentLocale) {
301
+ if (newLocation) {
302
+ // reload the page by navigating to the new url
303
+ window.location.href = newLocation;
304
+ }
305
+ else {
306
+ // reload the page to reflect the new locale
307
+ window.location.reload();
308
+ }
309
+ }
310
+ return;
311
+ };
312
+ /**
313
+ * Overwrite the \`setLocale()\` function.
314
+ *
315
+ * Use this function to overwrite how the locale is set. For example,
316
+ * modify a cookie, env variable, or a user's preference.
317
+ *
318
+ * @example
319
+ * overwriteSetLocale((newLocale) => {
320
+ * // set the locale in a cookie
321
+ * return Cookies.set('locale', newLocale)
322
+ * });
323
+ *
324
+ * @param {(newLocale: Locale) => void} fn
325
+ */
326
+ export const overwriteSetLocale = (fn) => {
327
+ setLocale = fn;
328
+ };
329
+
330
+ /**
331
+ * The origin of the current URL.
332
+ *
333
+ * Defaults to "http://y.com" in non-browser environments. If this
334
+ * behavior is not desired, the implementation can be overwritten
335
+ * by `overwriteGetUrlOrigin()`.
336
+ *
337
+ * @type {() => string}
338
+ */
339
+ export let getUrlOrigin = () => {
340
+ if (serverAsyncLocalStorage) {
341
+ return serverAsyncLocalStorage.getStore()?.origin ?? "http://fallback.com";
342
+ }
343
+ else if (typeof window !== "undefined") {
344
+ return window.location.origin;
345
+ }
346
+ return "http://fallback.com";
347
+ };
348
+ /**
349
+ * Overwrite the getUrlOrigin function.
350
+ *
351
+ * Use this function in server environments to
352
+ * define how the URL origin is resolved.
353
+ *
354
+ * @type {(fn: () => string) => void}
355
+ */
356
+ export let overwriteGetUrlOrigin = (fn) => {
357
+ getUrlOrigin = fn;
358
+ };
359
+
360
+ /**
361
+ * Check if something is an available locale.
362
+ *
363
+ * @example
364
+ * if (isLocale(params.locale)) {
365
+ * setLocale(params.locale);
366
+ * } else {
367
+ * setLocale('en');
368
+ * }
369
+ *
370
+ * @param {any} locale
371
+ * @returns {locale is Locale}
372
+ */
373
+ export function isLocale(locale) {
374
+ return !locale ? false : locales.includes(locale);
375
+ }
376
+
377
+ /**
378
+ * Asserts that the input is a locale.
379
+ *
380
+ * @param {any} input - The input to check.
381
+ * @returns {Locale} The input if it is a locale.
382
+ * @throws {Error} If the input is not a locale.
383
+ */
384
+ export function assertIsLocale(input) {
385
+ if (isLocale(input) === false) {
386
+ throw new Error(`Invalid locale: ${input}. Expected one of: ${locales.join(", ")}`);
387
+ }
388
+ return input;
389
+ }
390
+
391
+ /**
392
+ * Extracts a locale from a request.
393
+ *
394
+ * Use the function on the server to extract the locale
395
+ * from a request.
396
+ *
397
+ * The function goes through the strategies in the order
398
+ * they are defined. If a strategy returns an invalid locale,
399
+ * it will fall back to the next strategy.
400
+ *
401
+ * @example
402
+ * const locale = extractLocaleFromRequest(request);
403
+ *
404
+ * @type {(request: Request) => Locale}
405
+ */
406
+ export const extractLocaleFromRequest = (request) => {
407
+ /** @type {string|undefined} */
408
+ let locale;
409
+ for (const strat of strategy) {
410
+ if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
411
+ locale = request.headers
412
+ .get("cookie")
413
+ ?.split("; ")
414
+ .find((c) => c.startsWith(cookieName + "="))
415
+ ?.split("=")[1];
416
+ }
417
+ else if (TREE_SHAKE_URL_STRATEGY_USED && strat === "url") {
418
+ locale = extractLocaleFromUrl(request.url);
419
+ }
420
+ else if (TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED &&
421
+ strat === "preferredLanguage") {
422
+ const acceptLanguageHeader = request.headers.get("accept-language");
423
+ if (acceptLanguageHeader) {
424
+ locale = negotiatePreferredLanguageFromHeader(acceptLanguageHeader);
425
+ }
426
+ }
427
+ else if (strat === "globalVariable") {
428
+ locale = _locale;
429
+ }
430
+ else if (strat === "baseLocale") {
431
+ return baseLocale;
432
+ }
433
+ else if (strat === "localStorage") {
434
+ continue;
435
+ }
436
+ if (locale !== undefined) {
437
+ if (!isLocale(locale)) {
438
+ locale = undefined;
439
+ }
440
+ else {
441
+ return assertIsLocale(locale);
442
+ }
443
+ }
444
+ }
445
+ throw new Error("No locale found. There is an error in your strategy. Try adding 'baseLocale' as the very last strategy. Read more here https://inlang.com/m/gerre34r/library-inlang-paraglideJs/errors#no-locale-found");
446
+ };
447
+ /**
448
+ * Negotiates a preferred language from a header.
449
+ *
450
+ * @param {string} header - The header to negotiate from.
451
+ * @returns {string|undefined} The negotiated preferred language.
452
+ */
453
+ function negotiatePreferredLanguageFromHeader(header) {
454
+ // Parse language preferences with their q-values and base language codes
455
+ const languages = header
456
+ .split(",")
457
+ .map((lang) => {
458
+ const [tag, q = "1"] = lang.trim().split(";q=");
459
+ // Get both the full tag and base language code
460
+ const baseTag = tag?.split("-")[0]?.toLowerCase();
461
+ return {
462
+ fullTag: tag?.toLowerCase(),
463
+ baseTag,
464
+ q: Number(q),
465
+ };
466
+ })
467
+ .sort((a, b) => b.q - a.q);
468
+ for (const lang of languages) {
469
+ if (isLocale(lang.fullTag)) {
470
+ return lang.fullTag;
471
+ }
472
+ else if (isLocale(lang.baseTag)) {
473
+ return lang.baseTag;
474
+ }
475
+ }
476
+ return undefined;
477
+ }
478
+
479
+ /**
480
+ * Extracts a cookie from the document.
481
+ *
482
+ * Will return undefined if the docuement is not available or if the cookie is not set.
483
+ * The `document` object is not available in server-side rendering, so this function should not be called in that context.
484
+ *
485
+ * @returns {string | undefined}
486
+ */
487
+ export function extractLocaleFromCookie() {
488
+ if (typeof document === "undefined" || !document.cookie) {
489
+ return;
490
+ }
491
+ const match = document.cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));
492
+ const locale = match?.[2];
493
+ if (isLocale(locale)) {
494
+ return locale;
495
+ }
496
+ return undefined;
497
+ }
498
+
499
+ /**
500
+ * Extracts the locale from a given URL using native URLPattern.
501
+ *
502
+ * @param {URL|string} url - The full URL from which to extract the locale.
503
+ * @returns {Locale|undefined} The extracted locale, or undefined if no locale is found.
504
+ */
505
+ export function extractLocaleFromUrl(url) {
506
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
507
+ return defaultUrlPatternExtractLocale(url);
508
+ }
509
+ const urlObj = typeof url === "string" ? new URL(url) : url;
510
+ // Iterate over URL patterns
511
+ for (const element of urlPatterns) {
512
+ for (const [locale, localizedPattern] of element.localized) {
513
+ const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
514
+ if (!match) {
515
+ continue;
516
+ }
517
+ // Check if the locale is valid
518
+ if (assertIsLocale(locale)) {
519
+ return locale;
520
+ }
521
+ }
522
+ }
523
+ return undefined;
524
+ }
525
+ /**
526
+ * https://github.com/opral/inlang-paraglide-js/issues/381
527
+ *
528
+ * @param {URL|string} url - The full URL from which to extract the locale.
529
+ * @returns {Locale|undefined} The extracted locale, or undefined if no locale is found.
530
+ */
531
+ function defaultUrlPatternExtractLocale(url) {
532
+ const urlObj = new URL(url, "http://dummy.com");
533
+ const pathSegments = urlObj.pathname.split("/").filter(Boolean);
534
+ if (pathSegments.length > 0) {
535
+ const potentialLocale = pathSegments[0];
536
+ if (isLocale(potentialLocale)) {
537
+ return potentialLocale;
538
+ }
539
+ }
540
+ // everything else has to be the base locale
541
+ return baseLocale;
542
+ }
543
+
544
+ /**
545
+ * Lower-level URL localization function, primarily used in server contexts.
546
+ *
547
+ * This function is designed for server-side usage where you need precise control
548
+ * over URL localization, such as in middleware or request handlers. It works with
549
+ * URL objects and always returns absolute URLs.
550
+ *
551
+ * For client-side UI components, use `localizeHref()` instead, which provides
552
+ * a more convenient API with relative paths and automatic locale detection.
553
+ *
554
+ * @example
555
+ * ```typescript
556
+ * // Server middleware example
557
+ * app.use((req, res, next) => {
558
+ * const url = new URL(req.url, `${req.protocol}://${req.headers.host}`);
559
+ * const localized = localizeUrl(url, { locale: "de" });
560
+ *
561
+ * if (localized.href !== url.href) {
562
+ * return res.redirect(localized.href);
563
+ * }
564
+ * next();
565
+ * });
566
+ * ```
567
+ *
568
+ * @example
569
+ * ```typescript
570
+ * // Using with URL patterns
571
+ * const url = new URL("https://example.com/about");
572
+ * localizeUrl(url, { locale: "de" });
573
+ * // => URL("https://example.com/de/about")
574
+ *
575
+ * // Using with domain-based localization
576
+ * const url = new URL("https://example.com/store");
577
+ * localizeUrl(url, { locale: "de" });
578
+ * // => URL("https://de.example.com/store")
579
+ * ```
580
+ *
581
+ * @param {string | URL} url - The URL to localize. If string, must be absolute.
582
+ * @param {Object} [options] - Options for localization
583
+ * @param {string} [options.locale] - Target locale. If not provided, uses getLocale()
584
+ * @returns {URL} The localized URL, always absolute
585
+ */
586
+ export function localizeUrl(url, options) {
587
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
588
+ return localizeUrlDefaultPattern(url, options);
589
+ }
590
+ const targetLocale = options?.locale ?? getLocale();
591
+ const urlObj = typeof url === "string" ? new URL(url) : url;
592
+ // Iterate over URL patterns
593
+ for (const element of urlPatterns) {
594
+ // match localized patterns
595
+ for (const [, localizedPattern] of element.localized) {
596
+ const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
597
+ if (!match) {
598
+ continue;
599
+ }
600
+ const targetPattern = element.localized.find(([locale]) => locale === targetLocale)?.[1];
601
+ if (!targetPattern) {
602
+ continue;
603
+ }
604
+ const localizedUrl = fillPattern(targetPattern, aggregateGroups(match), urlObj.origin);
605
+ return fillMissingUrlParts(localizedUrl, match);
606
+ }
607
+ const unlocalizedMatch = new URLPattern(element.pattern, urlObj.href).exec(urlObj.href);
608
+ if (unlocalizedMatch) {
609
+ const targetPattern = element.localized.find(([locale]) => locale === targetLocale)?.[1];
610
+ if (targetPattern) {
611
+ const localizedUrl = fillPattern(targetPattern, aggregateGroups(unlocalizedMatch), urlObj.origin);
612
+ return fillMissingUrlParts(localizedUrl, unlocalizedMatch);
613
+ }
614
+ }
615
+ }
616
+ // If no match found, return the original URL
617
+ return urlObj;
618
+ }
619
+ /**
620
+ * https://github.com/opral/inlang-paraglide-js/issues/381
621
+ *
622
+ * @param {string | URL} url
623
+ * @param {Object} [options]
624
+ * @param {string} [options.locale]
625
+ * @returns {URL}
626
+ */
627
+ function localizeUrlDefaultPattern(url, options) {
628
+ const urlObj = typeof url === "string" ? new URL(url, getUrlOrigin()) : new URL(url);
629
+ const locale = options?.locale ?? getLocale();
630
+ const currentLocale = extractLocaleFromUrl(urlObj);
631
+ // If current locale matches target locale, no change needed
632
+ if (currentLocale === locale) {
633
+ return urlObj;
634
+ }
635
+ const pathSegments = urlObj.pathname.split("/").filter(Boolean);
636
+ // If current path starts with a locale, remove it
637
+ if (pathSegments.length > 0 && isLocale(pathSegments[0])) {
638
+ pathSegments.shift();
639
+ }
640
+ // For base locale, don't add prefix
641
+ if (locale === baseLocale) {
642
+ urlObj.pathname = "/" + pathSegments.join("/");
643
+ }
644
+ else {
645
+ // For other locales, add prefix
646
+ urlObj.pathname = "/" + locale + "/" + pathSegments.join("/");
647
+ }
648
+ return urlObj;
649
+ }
650
+ /**
651
+ * Low-level URL de-localization function, primarily used in server contexts.
652
+ *
653
+ * This function is designed for server-side usage where you need precise control
654
+ * over URL de-localization, such as in middleware or request handlers. It works with
655
+ * URL objects and always returns absolute URLs.
656
+ *
657
+ * For client-side UI components, use `deLocalizeHref()` instead, which provides
658
+ * a more convenient API with relative paths.
659
+ *
660
+ * @example
661
+ * ```typescript
662
+ * // Server middleware example
663
+ * app.use((req, res, next) => {
664
+ * const url = new URL(req.url, `${req.protocol}://${req.headers.host}`);
665
+ * const baseUrl = deLocalizeUrl(url);
666
+ *
667
+ * // Store the base URL for later use
668
+ * req.baseUrl = baseUrl;
669
+ * next();
670
+ * });
671
+ * ```
672
+ *
673
+ * @example
674
+ * ```typescript
675
+ * // Using with URL patterns
676
+ * const url = new URL("https://example.com/de/about");
677
+ * deLocalizeUrl(url); // => URL("https://example.com/about")
678
+ *
679
+ * // Using with domain-based localization
680
+ * const url = new URL("https://de.example.com/store");
681
+ * deLocalizeUrl(url); // => URL("https://example.com/store")
682
+ * ```
683
+ *
684
+ * @param {string | URL} url - The URL to de-localize. If string, must be absolute.
685
+ * @returns {URL} The de-localized URL, always absolute
686
+ */
687
+ export function deLocalizeUrl(url) {
688
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
689
+ return deLocalizeUrlDefaultPattern(url);
690
+ }
691
+ const urlObj = typeof url === "string" ? new URL(url) : url;
692
+ // Iterate over URL patterns
693
+ for (const element of urlPatterns) {
694
+ // Iterate over localized versions
695
+ for (const [, localizedPattern] of element.localized) {
696
+ const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
697
+ if (match) {
698
+ // Convert localized URL back to the base pattern
699
+ const groups = aggregateGroups(match);
700
+ const baseUrl = fillPattern(element.pattern, groups, urlObj.origin);
701
+ return fillMissingUrlParts(baseUrl, match);
702
+ }
703
+ }
704
+ // match unlocalized pattern
705
+ const unlocalizedMatch = new URLPattern(element.pattern, urlObj.href).exec(urlObj.href);
706
+ if (unlocalizedMatch) {
707
+ const baseUrl = fillPattern(element.pattern, aggregateGroups(unlocalizedMatch), urlObj.origin);
708
+ return fillMissingUrlParts(baseUrl, unlocalizedMatch);
709
+ }
710
+ }
711
+ // no match found return the original url
712
+ return urlObj;
713
+ }
714
+ /**
715
+ * De-localizes a URL using the default pattern (/:locale/*)
716
+ * @param {string|URL} url
717
+ * @returns {URL}
718
+ */
719
+ function deLocalizeUrlDefaultPattern(url) {
720
+ const urlObj = typeof url === "string" ? new URL(url, getUrlOrigin()) : new URL(url);
721
+ const pathSegments = urlObj.pathname.split("/").filter(Boolean);
722
+ // If first segment is a locale, remove it
723
+ if (pathSegments.length > 0 && isLocale(pathSegments[0])) {
724
+ urlObj.pathname = "/" + pathSegments.slice(1).join("/");
725
+ }
726
+ return urlObj;
727
+ }
728
+ /**
729
+ * Takes matches of implicit wildcards in the UrlPattern (when a part is missing
730
+ * it is equal to '*') and adds them back to the result of fillPattern.
731
+ *
732
+ * At least protocol and hostname are required to create a valid URL inside fillPattern.
733
+ *
734
+ * @param {URL} url
735
+ * @param {any} match
736
+ * @returns {URL}
737
+ */
738
+ function fillMissingUrlParts(url, match) {
739
+ if (match.protocol.groups["0"]) {
740
+ url.protocol = match.protocol.groups["0"] ?? "";
741
+ }
742
+ if (match.hostname.groups["0"]) {
743
+ url.hostname = match.hostname.groups["0"] ?? "";
744
+ }
745
+ if (match.username.groups["0"]) {
746
+ url.username = match.username.groups["0"] ?? "";
747
+ }
748
+ if (match.password.groups["0"]) {
749
+ url.password = match.password.groups["0"] ?? "";
750
+ }
751
+ if (match.port.groups["0"]) {
752
+ url.port = match.port.groups["0"] ?? "";
753
+ }
754
+ if (match.pathname.groups["0"]) {
755
+ url.pathname = match.pathname.groups["0"] ?? "";
756
+ }
757
+ if (match.search.groups["0"]) {
758
+ url.search = match.search.groups["0"] ?? "";
759
+ }
760
+ if (match.hash.groups["0"]) {
761
+ url.hash = match.hash.groups["0"] ?? "";
762
+ }
763
+ return url;
764
+ }
765
+ /**
766
+ * Fills a URL pattern with values for named groups, supporting all URLPattern-style modifiers.
767
+ *
768
+ * This function will eventually be replaced by https://github.com/whatwg/urlpattern/issues/73
769
+ *
770
+ * Matches:
771
+ * - :name -> Simple
772
+ * - :name? -> Optional
773
+ * - :name+ -> One or more
774
+ * - :name* -> Zero or more
775
+ * - :name(...) -> Regex group
776
+ * - {text} -> Group delimiter
777
+ * - {text}? -> Optional group delimiter
778
+ *
779
+ * If the value is `null`, the segment is removed.
780
+ *
781
+ * @param {string} pattern - The URL pattern containing named groups.
782
+ * @param {Record<string, string | null | undefined>} values - Object of values for named groups.
783
+ * @param {string} origin - Base URL to use for URL construction.
784
+ * @returns {URL} - The constructed URL with named groups filled.
785
+ */
786
+ function fillPattern(pattern, values, origin) {
787
+ // Pre-process the pattern to handle explicit port numbers
788
+ // This detects patterns like "http://localhost:5173" and protects the port number
789
+ // from being interpreted as a parameter
790
+ let processedPattern = pattern.replace(/(https?:\/\/[^:/]+):(\d+)(\/|$)/g, (_, protocol, port, slash) => {
791
+ // Replace ":5173" with "#PORT-5173#" to protect it from parameter replacement
792
+ return `${protocol}#PORT-${port}#${slash}`;
793
+ });
794
+ // First, handle group delimiters with curly braces
795
+ let processedGroupDelimiters = processedPattern.replace(/\{([^{}]*)\}([?+*]?)/g, (_, content, modifier) => {
796
+ // For optional group delimiters
797
+ if (modifier === "?") {
798
+ // For optional groups, we'll include the content
799
+ return content;
800
+ }
801
+ // For non-optional group delimiters, always include the content
802
+ return content;
803
+ });
804
+ // Then handle named groups
805
+ let filled = processedGroupDelimiters.replace(/(\/?):([a-zA-Z0-9_]+)(\([^)]*\))?([?+*]?)/g, (_, slash, name, __, modifier) => {
806
+ const value = values[name];
807
+ if (value === null) {
808
+ // If value is null, remove the entire segment including the preceding slash
809
+ return "";
810
+ }
811
+ if (modifier === "?") {
812
+ // Optional segment
813
+ return value !== undefined ? `${slash}${value}` : "";
814
+ }
815
+ if (modifier === "+" || modifier === "*") {
816
+ // Repeatable segments
817
+ if (value === undefined && modifier === "+") {
818
+ throw new Error(`Missing value for "${name}" (one or more required)`);
819
+ }
820
+ return value ? `${slash}${value}` : "";
821
+ }
822
+ // Simple named group (no modifier)
823
+ if (value === undefined) {
824
+ throw new Error(`Missing value for "${name}"`);
825
+ }
826
+ return `${slash}${value}`;
827
+ });
828
+ // Restore port numbers
829
+ filled = filled.replace(/#PORT-(\d+)#/g, ":$1");
830
+ return new URL(filled, origin);
831
+ }
832
+ /**
833
+ * Aggregates named groups from various parts of the URLPattern match result.
834
+ *
835
+ *
836
+ * @type {(match: any) => Record<string, string | null | undefined>}
837
+ */
838
+ export function aggregateGroups(match) {
839
+ return {
840
+ ...match.hash.groups,
841
+ ...match.hostname.groups,
842
+ ...match.password.groups,
843
+ ...match.pathname.groups,
844
+ ...match.port.groups,
845
+ ...match.protocol.groups,
846
+ ...match.search.groups,
847
+ ...match.username.groups,
848
+ };
849
+ }
850
+
851
+ /**
852
+ * High-level URL localization function optimized for client-side UI usage.
853
+ *
854
+ * This is a convenience wrapper around `localizeUrl()` that provides features
855
+ * needed in UI:
856
+ *
857
+ * - Accepts relative paths (e.g., "/about")
858
+ * - Returns relative paths when possible
859
+ * - Automatically detects current locale if not specified
860
+ * - Handles string input/output instead of URL objects
861
+ *
862
+ * @example
863
+ * ```typescript
864
+ * // In a React/Vue/Svelte component
865
+ * const NavLink = ({ href }) => {
866
+ * // Automatically uses current locale, keeps path relative
867
+ * return <a href={localizeHref(href)}>...</a>;
868
+ * };
869
+ *
870
+ * // Examples:
871
+ * localizeHref("/about")
872
+ * // => "/de/about" (if current locale is "de")
873
+ * localizeHref("/store", { locale: "fr" })
874
+ * // => "/fr/store" (explicit locale)
875
+ *
876
+ * // Cross-origin links remain absolute
877
+ * localizeHref("https://other-site.com/about")
878
+ * // => "https://other-site.com/de/about"
879
+ * ```
880
+ *
881
+ * For server-side URL localization (e.g., in middleware), use `localizeUrl()`
882
+ * which provides more precise control over URL handling.
883
+ *
884
+ * @param {string} href - The href to localize (can be relative or absolute)
885
+ * @param {Object} [options] - Options for localization
886
+ * @param {string} [options.locale] - Target locale. If not provided, uses `getLocale()`
887
+ * @returns {string} The localized href, relative if input was relative
888
+ */
889
+ export function localizeHref(href, options) {
890
+ const locale = options?.locale ?? getLocale();
891
+ const url = new URL(href, getUrlOrigin());
892
+ const localized = localizeUrl(url, options);
893
+ // if the origin is identical and the href is relative,
894
+ // return the relative path
895
+ if (href.startsWith("/") && url.origin === localized.origin) {
896
+ // check for cross origin localization in which case an absolute URL must be returned.
897
+ if (locale !== getLocale()) {
898
+ const localizedCurrentLocale = localizeUrl(url, { locale: getLocale() });
899
+ if (localizedCurrentLocale.origin !== localized.origin) {
900
+ return localized.href;
901
+ }
902
+ }
903
+ return localized.pathname + localized.search + localized.hash;
904
+ }
905
+ return localized.href;
906
+ }
907
+ /**
908
+ * High-level URL de-localization function optimized for client-side UI usage.
909
+ *
910
+ * This is a convenience wrapper around `deLocalizeUrl()` that provides features
911
+ * needed in the UI:
912
+ *
913
+ * - Accepts relative paths (e.g., "/de/about")
914
+ * - Returns relative paths when possible
915
+ * - Handles string input/output instead of URL objects
916
+ *
917
+ * @example
918
+ * ```typescript
919
+ * // In a React/Vue/Svelte component
920
+ * const LocaleSwitcher = ({ href }) => {
921
+ * // Remove locale prefix before switching
922
+ * const baseHref = deLocalizeHref(href);
923
+ * return locales.map(locale =>
924
+ * <a href={localizeHref(baseHref, { locale })}>
925
+ * Switch to {locale}
926
+ * </a>
927
+ * );
928
+ * };
929
+ *
930
+ * // Examples:
931
+ * deLocalizeHref("/de/about") // => "/about"
932
+ * deLocalizeHref("/fr/store") // => "/store"
933
+ *
934
+ * // Cross-origin links remain absolute
935
+ * deLocalizeHref("https://example.com/de/about")
936
+ * // => "https://example.com/about"
937
+ * ```
938
+ *
939
+ * For server-side URL de-localization (e.g., in middleware), use `deLocalizeUrl()`
940
+ * which provides more precise control over URL handling.
941
+ *
942
+ * @param {string} href - The href to de-localize (can be relative or absolute)
943
+ * @returns {string} The de-localized href, relative if input was relative
944
+ * @see deLocalizeUrl - For low-level URL de-localization in server contexts
945
+ */
946
+ export function deLocalizeHref(href) {
947
+ const url = new URL(href, getUrlOrigin());
948
+ const deLocalized = deLocalizeUrl(url);
949
+ // If the origin is identical and the href is relative,
950
+ // return the relative path instead of the full URL.
951
+ if (href.startsWith("/") && url.origin === deLocalized.origin) {
952
+ return deLocalized.pathname + deLocalized.search + deLocalized.hash;
953
+ }
954
+ return deLocalized.href;
955
+ }
956
+
957
+ /**
958
+ * @param {string} safeModuleId
959
+ * @param {Locale} locale
960
+ */
961
+ export function trackMessageCall(safeModuleId, locale) {
962
+ if (isServer === false)
963
+ return;
964
+ const store = serverAsyncLocalStorage?.getStore();
965
+ if (store) {
966
+ store.messageCalls?.add(`${safeModuleId}:${locale}`);
967
+ }
968
+ }
969
+
970
+ /**
971
+ * Generates a list of localized URLs for all provided URLs.
972
+ *
973
+ * This is useful for SSG (Static Site Generation) and sitemap generation.
974
+ * NextJS and other frameworks use this function for SSG.
975
+ *
976
+ * @example
977
+ * ```typescript
978
+ * const urls = generateStaticLocalizedUrls([
979
+ * "https://example.com/about",
980
+ * "https://example.com/blog",
981
+ * ]);
982
+ * urls[0].href // => "https://example.com/about"
983
+ * urls[1].href // => "https://example.com/blog"
984
+ * urls[2].href // => "https://example.com/de/about"
985
+ * urls[3].href // => "https://example.com/de/blog"
986
+ * ...
987
+ * ```
988
+ *
989
+ * @param {(string | URL)[]} urls - List of URLs to generate localized versions for. Can be absolute URLs or paths.
990
+ * @returns {URL[]} List of localized URLs as URL objects
991
+ */
992
+ export function generateStaticLocalizedUrls(urls) {
993
+ const localizedUrls = new Set();
994
+ // For default URL pattern, we can optimize the generation
995
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
996
+ for (const urlInput of urls) {
997
+ const url = urlInput instanceof URL
998
+ ? urlInput
999
+ : new URL(urlInput, "http://localhost");
1000
+ // Base locale doesn't get a prefix
1001
+ localizedUrls.add(url);
1002
+ // Other locales get their code as prefix
1003
+ for (const locale of locales) {
1004
+ if (locale !== baseLocale) {
1005
+ const localizedPath = `/${locale}${url.pathname}${url.search}${url.hash}`;
1006
+ const localizedUrl = new URL(localizedPath, url.origin);
1007
+ localizedUrls.add(localizedUrl);
1008
+ }
1009
+ }
1010
+ }
1011
+ return Array.from(localizedUrls);
1012
+ }
1013
+ // For custom URL patterns, we need to use localizeUrl for each URL and locale
1014
+ for (const urlInput of urls) {
1015
+ const url = urlInput instanceof URL
1016
+ ? urlInput
1017
+ : new URL(urlInput, "http://localhost");
1018
+ // Try each URL pattern to find one that matches
1019
+ let patternFound = false;
1020
+ for (const pattern of urlPatterns) {
1021
+ try {
1022
+ // Try to match the unlocalized pattern
1023
+ const unlocalizedMatch = new URLPattern(pattern.pattern, url.href).exec(url.href);
1024
+ if (!unlocalizedMatch)
1025
+ continue;
1026
+ patternFound = true;
1027
+ // Track unique localized URLs to avoid duplicates when patterns are the same
1028
+ const seenUrls = new Set();
1029
+ // Generate localized URL for each locale
1030
+ for (const [locale] of pattern.localized) {
1031
+ try {
1032
+ const localizedUrl = localizeUrl(url, { locale });
1033
+ const urlString = localizedUrl.href;
1034
+ // Only add if we haven't seen this exact URL before
1035
+ if (!seenUrls.has(urlString)) {
1036
+ seenUrls.add(urlString);
1037
+ localizedUrls.add(localizedUrl);
1038
+ }
1039
+ }
1040
+ catch {
1041
+ // Skip if localization fails for this locale
1042
+ continue;
1043
+ }
1044
+ }
1045
+ break;
1046
+ }
1047
+ catch {
1048
+ // Skip if pattern matching fails
1049
+ continue;
1050
+ }
1051
+ }
1052
+ // If no pattern matched, use the URL as is
1053
+ if (!patternFound) {
1054
+ localizedUrls.add(url);
1055
+ }
1056
+ }
1057
+ return Array.from(localizedUrls);
1058
+ }
1059
+
1060
+ // ------ TYPES ------
1061
+
1062
+ /**
1063
+ * A locale that is available in the project.
1064
+ *
1065
+ * @example
1066
+ * setLocale(request.locale as Locale)
1067
+ *
1068
+ * @typedef {(typeof locales)[number]} Locale
1069
+ */
1070
+