@mpgd/i18n 0.1.0

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 (129) hide show
  1. package/LICENSE +21 -0
  2. package/dist/index.d.ts +7 -0
  3. package/dist/index.js +36 -0
  4. package/dist/paraglide/README.md +162 -0
  5. package/dist/paraglide/messages/_index.d.ts +55 -0
  6. package/dist/paraglide/messages/_index.js +56 -0
  7. package/dist/paraglide/messages/action_interstitial_ads.d.ts +16 -0
  8. package/dist/paraglide/messages/action_interstitial_ads.js +29 -0
  9. package/dist/paraglide/messages/action_leaderboard.d.ts +16 -0
  10. package/dist/paraglide/messages/action_leaderboard.js +29 -0
  11. package/dist/paraglide/messages/action_localization.d.ts +16 -0
  12. package/dist/paraglide/messages/action_localization.js +29 -0
  13. package/dist/paraglide/messages/action_purchases.d.ts +16 -0
  14. package/dist/paraglide/messages/action_purchases.js +29 -0
  15. package/dist/paraglide/messages/action_reward_ads.d.ts +16 -0
  16. package/dist/paraglide/messages/action_reward_ads.js +29 -0
  17. package/dist/paraglide/messages/app_title.d.ts +16 -0
  18. package/dist/paraglide/messages/app_title.js +29 -0
  19. package/dist/paraglide/messages/availability_off.d.ts +16 -0
  20. package/dist/paraglide/messages/availability_off.js +29 -0
  21. package/dist/paraglide/messages/availability_on.d.ts +16 -0
  22. package/dist/paraglide/messages/availability_on.js +29 -0
  23. package/dist/paraglide/messages/availability_unsupported.d.ts +16 -0
  24. package/dist/paraglide/messages/availability_unsupported.js +29 -0
  25. package/dist/paraglide/messages/cap_iap.d.ts +16 -0
  26. package/dist/paraglide/messages/cap_iap.js +29 -0
  27. package/dist/paraglide/messages/cap_leaderboard.d.ts +16 -0
  28. package/dist/paraglide/messages/cap_leaderboard.js +29 -0
  29. package/dist/paraglide/messages/cap_localization.d.ts +16 -0
  30. package/dist/paraglide/messages/cap_localization.js +29 -0
  31. package/dist/paraglide/messages/cap_rewarded_ads.d.ts +16 -0
  32. package/dist/paraglide/messages/cap_rewarded_ads.js +29 -0
  33. package/dist/paraglide/messages/cap_save.d.ts +16 -0
  34. package/dist/paraglide/messages/cap_save.js +29 -0
  35. package/dist/paraglide/messages/effective_config_summary.d.ts +20 -0
  36. package/dist/paraglide/messages/effective_config_summary.js +29 -0
  37. package/dist/paraglide/messages/feature_target_disabled.d.ts +18 -0
  38. package/dist/paraglide/messages/feature_target_disabled.js +29 -0
  39. package/dist/paraglide/messages/feature_unavailable.d.ts +18 -0
  40. package/dist/paraglide/messages/feature_unavailable.js +29 -0
  41. package/dist/paraglide/messages/feature_unsupported.d.ts +18 -0
  42. package/dist/paraglide/messages/feature_unsupported.js +29 -0
  43. package/dist/paraglide/messages/leaderboard_action.d.ts +16 -0
  44. package/dist/paraglide/messages/leaderboard_action.js +29 -0
  45. package/dist/paraglide/messages/leaderboard_action_unavailable.d.ts +16 -0
  46. package/dist/paraglide/messages/leaderboard_action_unavailable.js +29 -0
  47. package/dist/paraglide/messages/leaderboard_opened.d.ts +16 -0
  48. package/dist/paraglide/messages/leaderboard_opened.js +29 -0
  49. package/dist/paraglide/messages/leaderboard_unavailable.d.ts +16 -0
  50. package/dist/paraglide/messages/leaderboard_unavailable.js +29 -0
  51. package/dist/paraglide/messages/loading_player.d.ts +16 -0
  52. package/dist/paraglide/messages/loading_player.js +29 -0
  53. package/dist/paraglide/messages/mock_only.d.ts +16 -0
  54. package/dist/paraglide/messages/mock_only.js +29 -0
  55. package/dist/paraglide/messages/opening_purchase.d.ts +16 -0
  56. package/dist/paraglide/messages/opening_purchase.js +29 -0
  57. package/dist/paraglide/messages/package.json +4 -0
  58. package/dist/paraglide/messages/play_again.d.ts +16 -0
  59. package/dist/paraglide/messages/play_again.js +29 -0
  60. package/dist/paraglide/messages/player.d.ts +18 -0
  61. package/dist/paraglide/messages/player.js +29 -0
  62. package/dist/paraglide/messages/preparing_demo.d.ts +16 -0
  63. package/dist/paraglide/messages/preparing_demo.js +29 -0
  64. package/dist/paraglide/messages/purchase_action.d.ts +16 -0
  65. package/dist/paraglide/messages/purchase_action.js +29 -0
  66. package/dist/paraglide/messages/purchase_completed.d.ts +16 -0
  67. package/dist/paraglide/messages/purchase_completed.js +29 -0
  68. package/dist/paraglide/messages/purchase_status.d.ts +18 -0
  69. package/dist/paraglide/messages/purchase_status.js +29 -0
  70. package/dist/paraglide/messages/purchase_unavailable.d.ts +16 -0
  71. package/dist/paraglide/messages/purchase_unavailable.js +29 -0
  72. package/dist/paraglide/messages/reward_ad_action.d.ts +16 -0
  73. package/dist/paraglide/messages/reward_ad_action.js +29 -0
  74. package/dist/paraglide/messages/reward_ad_unavailable.d.ts +16 -0
  75. package/dist/paraglide/messages/reward_ad_unavailable.js +29 -0
  76. package/dist/paraglide/messages/reward_granted.d.ts +16 -0
  77. package/dist/paraglide/messages/reward_granted.js +29 -0
  78. package/dist/paraglide/messages/reward_unavailable.d.ts +18 -0
  79. package/dist/paraglide/messages/reward_unavailable.js +29 -0
  80. package/dist/paraglide/messages/save_summary.d.ts +19 -0
  81. package/dist/paraglide/messages/save_summary.js +29 -0
  82. package/dist/paraglide/messages/saved.d.ts +16 -0
  83. package/dist/paraglide/messages/saved.js +29 -0
  84. package/dist/paraglide/messages/saved_and_submitted.d.ts +16 -0
  85. package/dist/paraglide/messages/saved_and_submitted.js +29 -0
  86. package/dist/paraglide/messages/saving_result.d.ts +16 -0
  87. package/dist/paraglide/messages/saving_result.js +29 -0
  88. package/dist/paraglide/messages/score.d.ts +18 -0
  89. package/dist/paraglide/messages/score.js +29 -0
  90. package/dist/paraglide/messages/sdk_summary.d.ts +18 -0
  91. package/dist/paraglide/messages/sdk_summary.js +29 -0
  92. package/dist/paraglide/messages/showing_rewarded_ad.d.ts +16 -0
  93. package/dist/paraglide/messages/showing_rewarded_ad.js +29 -0
  94. package/dist/paraglide/messages/status_cleared.d.ts +16 -0
  95. package/dist/paraglide/messages/status_cleared.js +29 -0
  96. package/dist/paraglide/messages/status_try_again.d.ts +16 -0
  97. package/dist/paraglide/messages/status_try_again.js +29 -0
  98. package/dist/paraglide/messages/tap_to_start.d.ts +16 -0
  99. package/dist/paraglide/messages/tap_to_start.js +29 -0
  100. package/dist/paraglide/messages/target.d.ts +18 -0
  101. package/dist/paraglide/messages/target.js +29 -0
  102. package/dist/paraglide/messages/target_availability_summary.d.ts +19 -0
  103. package/dist/paraglide/messages/target_availability_summary.js +29 -0
  104. package/dist/paraglide/messages/target_config_unavailable.d.ts +16 -0
  105. package/dist/paraglide/messages/target_config_unavailable.js +29 -0
  106. package/dist/paraglide/messages/target_feature_iap.d.ts +16 -0
  107. package/dist/paraglide/messages/target_feature_iap.js +29 -0
  108. package/dist/paraglide/messages/target_feature_interstitial_ads.d.ts +16 -0
  109. package/dist/paraglide/messages/target_feature_interstitial_ads.js +29 -0
  110. package/dist/paraglide/messages/target_feature_leaderboard.d.ts +16 -0
  111. package/dist/paraglide/messages/target_feature_leaderboard.js +29 -0
  112. package/dist/paraglide/messages/target_feature_localization.d.ts +16 -0
  113. package/dist/paraglide/messages/target_feature_localization.js +29 -0
  114. package/dist/paraglide/messages/target_feature_rewarded_ads.d.ts +16 -0
  115. package/dist/paraglide/messages/target_feature_rewarded_ads.js +29 -0
  116. package/dist/paraglide/messages.d.ts +2 -0
  117. package/dist/paraglide/messages.js +4 -0
  118. package/dist/paraglide/registry.d.ts +34 -0
  119. package/dist/paraglide/registry.js +46 -0
  120. package/dist/paraglide/runtime.d.ts +758 -0
  121. package/dist/paraglide/runtime.js +1852 -0
  122. package/dist/paraglide/server.d.ts +96 -0
  123. package/dist/paraglide/server.js +282 -0
  124. package/dist/paraglideAdapter.d.ts +86 -0
  125. package/dist/paraglideAdapter.js +2 -0
  126. package/messages/en.json +57 -0
  127. package/messages/ko.json +57 -0
  128. package/package.json +69 -0
  129. package/project.inlang/settings.json +10 -0
@@ -0,0 +1,1852 @@
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","ko"]);
24
+ /** @type {string} */
25
+ export const cookieName = "PARAGLIDE_LOCALE";
26
+ /** @type {number} */
27
+ export const cookieMaxAge = 34560000;
28
+ /** @type {string} */
29
+ export const cookieDomain = "";
30
+ /** @type {string} */
31
+ export const localStorageKey = "PARAGLIDE_LOCALE";
32
+ /**
33
+ * @type {Array<"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage" | `custom-${string}`>}
34
+ */
35
+ export const strategy = [
36
+ "cookie",
37
+ "globalVariable",
38
+ "baseLocale"
39
+ ];
40
+ /**
41
+ * Route-level strategy overrides.
42
+ *
43
+ * `match` uses URLPattern syntax.
44
+ *
45
+ * @type {Array<{
46
+ * match: string;
47
+ * strategy?: Array<"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage" | `custom-${string}`>;
48
+ * exclude?: boolean;
49
+ * }>}
50
+ */
51
+ export const routeStrategies = [];
52
+ /**
53
+ * The used URL patterns.
54
+ *
55
+ * @type {Array<{ pattern: string, localized: Array<[Locale, string]> }>}
56
+ */
57
+ export const urlPatterns = [
58
+ {
59
+ "pattern": ":protocol://:domain(.*)::port?/:path(.*)?",
60
+ "localized": [
61
+ [
62
+ "ko",
63
+ ":protocol://:domain(.*)::port?/ko/:path(.*)?"
64
+ ],
65
+ [
66
+ "en",
67
+ ":protocol://:domain(.*)::port?/:path(.*)?"
68
+ ]
69
+ ]
70
+ }
71
+ ];
72
+ /** @type {string | undefined} */
73
+ let cachedRouteStrategyUrl;
74
+ /** @type {{ match: string; strategy?: typeof strategy; exclude?: boolean } | undefined} */
75
+ let cachedRouteStrategy;
76
+ /**
77
+ * @param {string | URL} url
78
+ * @returns {{ match: string; strategy?: typeof strategy; exclude?: boolean } | undefined}
79
+ */
80
+ function findMatchingRouteStrategy(url) {
81
+ if (routeStrategies.length === 0) {
82
+ return undefined;
83
+ }
84
+ const urlString = typeof url === "string" ? url : url.href;
85
+ if (cachedRouteStrategyUrl === urlString) {
86
+ return cachedRouteStrategy;
87
+ }
88
+ const urlObject = new URL(urlString, "http://dummy.com");
89
+ let match;
90
+ for (const routeStrategy of routeStrategies) {
91
+ const pattern = new URLPattern(routeStrategy.match, urlObject.href);
92
+ if (pattern.exec(urlObject.href)) {
93
+ match = routeStrategy;
94
+ break;
95
+ }
96
+ }
97
+ cachedRouteStrategyUrl = urlString;
98
+ cachedRouteStrategy = match;
99
+ return match;
100
+ }
101
+ /**
102
+ * Returns the strategy to use for a specific URL.
103
+ *
104
+ * If no route strategy matches (or the matching rule is `exclude: true`),
105
+ * the global strategy is returned.
106
+ *
107
+ * @param {string | URL} url
108
+ * @returns {typeof strategy}
109
+ */
110
+ export function getStrategyForUrl(url) {
111
+ const routeStrategy = findMatchingRouteStrategy(url);
112
+ if (routeStrategy &&
113
+ routeStrategy.exclude !== true &&
114
+ Array.isArray(routeStrategy.strategy)) {
115
+ return routeStrategy.strategy;
116
+ }
117
+ return strategy;
118
+ }
119
+ /**
120
+ * Returns whether the given URL is excluded from middleware i18n processing.
121
+ *
122
+ * @param {string | URL} url
123
+ * @returns {boolean}
124
+ */
125
+ export function isExcludedByRouteStrategy(url) {
126
+ return findMatchingRouteStrategy(url)?.exclude === true;
127
+ }
128
+ /**
129
+ * @typedef {{
130
+ * getStore(): {
131
+ * locale?: Locale,
132
+ * origin?: string,
133
+ * messageCalls?: Set<string>
134
+ * } | undefined,
135
+ * run: (store: { locale?: Locale, origin?: string, messageCalls?: Set<string>},
136
+ * cb: any) => any
137
+ * }} ParaglideAsyncLocalStorage
138
+ */
139
+ /**
140
+ * Server side async local storage that is set by `serverMiddleware()`.
141
+ *
142
+ * The variable is used to retrieve the locale and origin in a server-side
143
+ * rendering context without effecting other requests.
144
+ *
145
+ * @type {ParaglideAsyncLocalStorage | undefined}
146
+ */
147
+ export let serverAsyncLocalStorage = undefined;
148
+ export const disableAsyncLocalStorage = false;
149
+ export const experimentalMiddlewareLocaleSplitting = false;
150
+ export const isServer = typeof window === 'undefined';
151
+ /** @type {Locale | undefined} */
152
+ export const experimentalStaticLocale = undefined;
153
+ /**
154
+ * Sets the server side async local storage.
155
+ *
156
+ * The function is needed because the `runtime.js` file
157
+ * must define the `serverAsyncLocalStorage` variable to
158
+ * avoid a circular import between `runtime.js` and
159
+ * `server.js` files.
160
+ *
161
+ * @param {ParaglideAsyncLocalStorage | undefined} value
162
+ */
163
+ export function overwriteServerAsyncLocalStorage(value) {
164
+ serverAsyncLocalStorage = value;
165
+ }
166
+ const TREE_SHAKE_COOKIE_STRATEGY_USED = true;
167
+ const TREE_SHAKE_URL_STRATEGY_USED = false;
168
+ const TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED = true;
169
+ const TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED = false;
170
+ const TREE_SHAKE_DEFAULT_URL_PATTERN_USED = true;
171
+ const TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED = false;
172
+
173
+ /** @type {any} */ (globalThis).__paraglide =
174
+ /** @type {any} */ (globalThis).__paraglide ?? {};
175
+ /** @type {any} */ (globalThis).__paraglide.ssr =
176
+ /** @type {any} */ (globalThis).__paraglide.ssr ?? {};
177
+
178
+ /**
179
+ * This is a fallback to get started with a custom
180
+ * strategy and avoid type errors.
181
+ *
182
+ * The implementation is overwritten
183
+ * by `overwriteGetLocale()` and `defineSetLocale()`.
184
+ *
185
+ * @type {Locale | undefined}
186
+ */
187
+ let _locale;
188
+ let localeInitiallySet = false;
189
+ /**
190
+ * Get the current locale.
191
+ *
192
+ * The locale is resolved using your configured strategies (URL, cookie, localStorage, etc.)
193
+ * in the order they are defined. In SSR contexts, the locale is retrieved from AsyncLocalStorage
194
+ * which is set by the `paraglideMiddleware()`.
195
+ *
196
+ * @see https://paraglidejs.com/strategy - Configure locale detection strategies
197
+ *
198
+ * @example
199
+ * if (getLocale() === 'de') {
200
+ * console.log('Germany 🇩🇪');
201
+ * } else if (getLocale() === 'nl') {
202
+ * console.log('Netherlands 🇳🇱');
203
+ * }
204
+ *
205
+ * @returns {Locale} The current locale.
206
+ */
207
+ export let getLocale = () => {
208
+ if (experimentalStaticLocale !== undefined) {
209
+ return experimentalStaticLocale;
210
+ }
211
+ // if running in a server-side rendering context
212
+ // retrieve the locale from the async local storage
213
+ if (serverAsyncLocalStorage) {
214
+ const locale = serverAsyncLocalStorage?.getStore()?.locale;
215
+ if (locale) {
216
+ return locale;
217
+ }
218
+ }
219
+ let strategyToUse = strategy;
220
+ if (!isServer && typeof window !== "undefined" && window.location?.href) {
221
+ strategyToUse = getStrategyForUrl(window.location.href);
222
+ }
223
+ const resolved = resolveLocaleWithStrategies(strategyToUse, typeof window !== "undefined" ? window.location?.href : undefined);
224
+ if (resolved) {
225
+ if (!localeInitiallySet) {
226
+ _locale = resolved;
227
+ // https://github.com/opral/inlang-paraglide-js/issues/455
228
+ localeInitiallySet = true;
229
+ setLocale(resolved, { reload: false });
230
+ }
231
+ return resolved;
232
+ }
233
+ throw new Error("No locale found. Read the docs https://paraglidejs.com/errors#no-locale-found");
234
+ };
235
+ /**
236
+ * Resolve locale for a given URL using route-aware strategies.
237
+ *
238
+ * @param {string | URL} url
239
+ * @returns {Locale}
240
+ */
241
+ export function getLocaleForUrl(url) {
242
+ if (experimentalStaticLocale !== undefined) {
243
+ return experimentalStaticLocale;
244
+ }
245
+ const strategyToUse = getStrategyForUrl(url);
246
+ const resolved = resolveLocaleWithStrategies(strategyToUse, typeof url === "string" ? url : url.href);
247
+ if (resolved) {
248
+ return resolved;
249
+ }
250
+ throw new Error("No locale found. Read the docs https://paraglidejs.com/errors#no-locale-found");
251
+ }
252
+ /**
253
+ * @param {typeof strategy} strategyToUse
254
+ * @param {string | undefined} urlForUrlStrategy
255
+ * @returns {Locale | undefined}
256
+ */
257
+ function resolveLocaleWithStrategies(strategyToUse, urlForUrlStrategy) {
258
+ /** @type {string | undefined} */
259
+ let locale;
260
+ for (const strat of strategyToUse) {
261
+ if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
262
+ locale = extractLocaleFromCookie();
263
+ }
264
+ else if (strat === "baseLocale") {
265
+ locale = baseLocale;
266
+ }
267
+ else if (TREE_SHAKE_URL_STRATEGY_USED &&
268
+ strat === "url" &&
269
+ !isServer &&
270
+ typeof urlForUrlStrategy === "string") {
271
+ locale = extractLocaleFromUrl(urlForUrlStrategy);
272
+ }
273
+ else if (TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED &&
274
+ strat === "globalVariable" &&
275
+ _locale !== undefined) {
276
+ locale = _locale;
277
+ }
278
+ else if (TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED &&
279
+ strat === "preferredLanguage" &&
280
+ !isServer) {
281
+ locale = extractLocaleFromNavigator();
282
+ }
283
+ else if (TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED &&
284
+ strat === "localStorage" &&
285
+ !isServer) {
286
+ locale = localStorage.getItem(localStorageKey) ?? undefined;
287
+ }
288
+ else if (isCustomStrategy(strat) && customClientStrategies.has(strat)) {
289
+ const handler = customClientStrategies.get(strat);
290
+ if (handler) {
291
+ const result = handler.getLocale();
292
+ // Handle both sync and async results - skip async in sync getLocale
293
+ if (result instanceof Promise) {
294
+ // Can't await in sync function, skip async strategies
295
+ continue;
296
+ }
297
+ if (result !== undefined) {
298
+ return assertIsLocale(result);
299
+ }
300
+ }
301
+ }
302
+ const matchedLocale = toLocale(locale);
303
+ if (matchedLocale) {
304
+ return matchedLocale;
305
+ }
306
+ }
307
+ return undefined;
308
+ }
309
+ /**
310
+ * Overwrite the `getLocale()` function.
311
+ *
312
+ * Use this function to overwrite how the locale is resolved. This is useful
313
+ * for custom locale resolution or advanced use cases like SSG with concurrent rendering.
314
+ *
315
+ * @see https://paraglidejs.com/strategy
316
+ *
317
+ * @example
318
+ * overwriteGetLocale(() => {
319
+ * return Cookies.get('locale') ?? baseLocale
320
+ * });
321
+ *
322
+ * @param {() => Locale} fn - The new implementation for `getLocale()`.
323
+ */
324
+ export const overwriteGetLocale = (fn) => {
325
+ getLocale = fn;
326
+ };
327
+
328
+ const rtlLanguages = new Set([
329
+ "ar",
330
+ "dv",
331
+ "fa",
332
+ "he",
333
+ "ks",
334
+ "ku",
335
+ "ps",
336
+ "sd",
337
+ "ug",
338
+ "ur",
339
+ "yi",
340
+ ]);
341
+ /**
342
+ * Get writing direction for a locale.
343
+ *
344
+ * Uses `Intl.Locale` text info when available and falls back to a
345
+ * language-based RTL check for runtimes without `getTextInfo()`.
346
+ *
347
+ * @example
348
+ * getTextDirection(); // "ltr" or "rtl" for current locale
349
+ * getTextDirection("ar"); // "rtl"
350
+ * getTextDirection("en"); // "ltr"
351
+ *
352
+ * @param {string} [locale] - Target locale. If not provided, uses `getLocale()`
353
+ * @returns {"ltr" | "rtl"}
354
+ */
355
+ export function getTextDirection(locale = getLocale()) {
356
+ try {
357
+ const intlLocale = /** @type {Intl.Locale & {
358
+ getTextInfo?: () => { direction?: string };
359
+ textInfo?: { direction?: string };
360
+ }} */ (new Intl.Locale(locale));
361
+ const direction = intlLocale.getTextInfo?.().direction ?? intlLocale.textInfo?.direction;
362
+ if (direction === "ltr" || direction === "rtl") {
363
+ return direction;
364
+ }
365
+ }
366
+ catch {
367
+ // Ignore Intl.Locale parsing/runtime errors and use fallback below.
368
+ }
369
+ const language = locale.split("-")[0]?.toLowerCase();
370
+ return rtlLanguages.has(language ?? "") ? "rtl" : "ltr";
371
+ }
372
+
373
+ /**
374
+ * Navigates to the localized URL, or reloads the current page
375
+ *
376
+ * @param {string} [newLocation] The new location
377
+ */
378
+ const navigateOrReload = (newLocation) => {
379
+ if (newLocation) {
380
+ // reload the page by navigating to the new url
381
+ window.location.href = newLocation;
382
+ }
383
+ else {
384
+ // reload the page to reflect the new locale
385
+ window.location.reload();
386
+ }
387
+ };
388
+ /**
389
+ * @typedef {(newLocale: Locale, options?: { reload?: boolean }) => void | Promise<void>} SetLocaleFn
390
+ */
391
+ /**
392
+ * Set the locale.
393
+ *
394
+ * Updates the locale using your configured strategies (cookie, localStorage, URL, etc.).
395
+ * By default, this reloads the page on the client to reflect the new locale. Reloading
396
+ * can be disabled by passing `reload: false` as an option, but you'll need to ensure
397
+ * the UI updates to reflect the new locale.
398
+ *
399
+ * If any custom strategy's `setLocale` function is async, then this function
400
+ * will become async as well.
401
+ *
402
+ * @see https://paraglidejs.com/strategy
403
+ *
404
+ * @example
405
+ * setLocale('en');
406
+ *
407
+ * @example
408
+ * setLocale('en', { reload: false });
409
+ *
410
+ * @type {SetLocaleFn}
411
+ */
412
+ export let setLocale = (newLocale, options) => {
413
+ const optionsWithDefaults = {
414
+ reload: true,
415
+ ...options,
416
+ };
417
+ // locale is already set
418
+ // https://github.com/opral/inlang-paraglide-js/issues/430
419
+ /** @type {Locale | undefined} */
420
+ let currentLocale;
421
+ try {
422
+ currentLocale = getLocale();
423
+ }
424
+ catch {
425
+ // do nothing, no locale has been set yet.
426
+ }
427
+ /** @type {Array<Promise<void>>} */
428
+ const customSetLocalePromises = [];
429
+ /** @type {string | undefined} */
430
+ let newLocation = undefined;
431
+ let strategyToUse = strategy;
432
+ if (!isServer && typeof window !== "undefined" && window.location?.href) {
433
+ strategyToUse = getStrategyForUrl(window.location.href);
434
+ }
435
+ for (const strat of strategyToUse) {
436
+ if (TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED &&
437
+ strat === "globalVariable") {
438
+ // a default for a custom strategy to get started quickly
439
+ // is likely overwritten by `defineSetLocale()`
440
+ _locale = newLocale;
441
+ }
442
+ else if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
443
+ if (isServer ||
444
+ typeof document === "undefined" ||
445
+ typeof window === "undefined") {
446
+ continue;
447
+ }
448
+ // set the cookie
449
+ const cookieString = `${cookieName}=${newLocale}; path=/; max-age=${cookieMaxAge}`;
450
+ document.cookie = cookieDomain
451
+ ? `${cookieString}; domain=${cookieDomain}`
452
+ : cookieString;
453
+ clearLocaleCookieCache();
454
+ }
455
+ else if (strat === "baseLocale") {
456
+ // nothing to be set here. baseLocale is only a fallback
457
+ continue;
458
+ }
459
+ else if (TREE_SHAKE_URL_STRATEGY_USED &&
460
+ strat === "url" &&
461
+ typeof window !== "undefined") {
462
+ // route to the new url
463
+ //
464
+ // this triggers a page reload but a user rarely
465
+ // switches locales, so this should be fine.
466
+ //
467
+ // if the behavior is not desired, the implementation
468
+ // can be overwritten by `defineSetLocale()` to avoid
469
+ // a full page reload.
470
+ newLocation = localizeUrl(window.location.href, {
471
+ locale: newLocale,
472
+ }).href;
473
+ }
474
+ else if (TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED &&
475
+ strat === "localStorage" &&
476
+ typeof window !== "undefined") {
477
+ // set the localStorage
478
+ localStorage.setItem(localStorageKey, newLocale);
479
+ }
480
+ else if (isCustomStrategy(strat) && customClientStrategies.has(strat)) {
481
+ const handler = customClientStrategies.get(strat);
482
+ if (handler) {
483
+ let result = handler.setLocale(newLocale);
484
+ // Handle async setLocale
485
+ if (result instanceof Promise) {
486
+ result = result.catch((error) => {
487
+ throw new Error(`Custom strategy "${strat}" setLocale failed.`, {
488
+ cause: error,
489
+ });
490
+ });
491
+ customSetLocalePromises.push(result);
492
+ }
493
+ }
494
+ }
495
+ }
496
+ const runReload = () => {
497
+ if (!isServer &&
498
+ optionsWithDefaults.reload &&
499
+ window.location &&
500
+ newLocale !== currentLocale) {
501
+ navigateOrReload(newLocation);
502
+ }
503
+ };
504
+ if (customSetLocalePromises.length) {
505
+ return Promise.all(customSetLocalePromises).then(() => {
506
+ runReload();
507
+ });
508
+ }
509
+ runReload();
510
+ return;
511
+ };
512
+ /**
513
+ * Overwrite the `setLocale()` function.
514
+ *
515
+ * Use this function to overwrite how the locale is set. For example,
516
+ * modify a cookie, env variable, or a user's preference.
517
+ *
518
+ * @example
519
+ * overwriteSetLocale((newLocale) => {
520
+ * // set the locale in a cookie
521
+ * return Cookies.set('locale', newLocale)
522
+ * });
523
+ *
524
+ * @param {SetLocaleFn} fn
525
+ */
526
+ export const overwriteSetLocale = (fn) => {
527
+ setLocale = fn;
528
+ };
529
+
530
+ /**
531
+ * The origin of the current URL.
532
+ *
533
+ * Defaults to "http://y.com" in non-browser environments. If this
534
+ * behavior is not desired, the implementation can be overwritten
535
+ * by `overwriteGetUrlOrigin()`.
536
+ *
537
+ * @type {() => string}
538
+ */
539
+ export let getUrlOrigin = () => {
540
+ if (serverAsyncLocalStorage) {
541
+ return serverAsyncLocalStorage.getStore()?.origin ?? "http://fallback.com";
542
+ }
543
+ else if (typeof window !== "undefined") {
544
+ return window.location.origin;
545
+ }
546
+ return "http://fallback.com";
547
+ };
548
+ /**
549
+ * Overwrite the getUrlOrigin function.
550
+ *
551
+ * Use this function in server environments to
552
+ * define how the URL origin is resolved.
553
+ *
554
+ * @param {() => string} fn - The new implementation for `getUrlOrigin()`.
555
+ */
556
+ export let overwriteGetUrlOrigin = (fn) => {
557
+ getUrlOrigin = fn;
558
+ };
559
+
560
+ /**
561
+ * Coerces a locale-like string to the canonical locale value used by the runtime.
562
+ *
563
+ * @param {unknown} value
564
+ * @returns {Locale | undefined}
565
+ */
566
+ export function toLocale(value) {
567
+ if (typeof value !== "string") {
568
+ return undefined;
569
+ }
570
+ const lowerValue = value.toLowerCase();
571
+ for (const locale of locales) {
572
+ if (locale.toLowerCase() === lowerValue) {
573
+ return locale;
574
+ }
575
+ }
576
+ return undefined;
577
+ }
578
+ /**
579
+ * Check if something is an available locale with the canonical project casing.
580
+ *
581
+ * @example
582
+ * if (isLocale(params.locale)) {
583
+ * setLocale(params.locale);
584
+ * } else {
585
+ * setLocale('en');
586
+ * }
587
+ *
588
+ * Use `toLocale()` when you want case-insensitive matching and canonicalization.
589
+ *
590
+ * @param {unknown} locale
591
+ * @returns {locale is Locale}
592
+ */
593
+ export function isLocale(locale) {
594
+ return !!locale && locales.some((item) => item === locale);
595
+ }
596
+ /**
597
+ * Asserts that the input can be normalized to a locale.
598
+ *
599
+ * @param {unknown} input - The input to check.
600
+ * @returns {Locale} The input normalized to a Locale.
601
+ * @throws {Error} If the input is not a locale.
602
+ */
603
+ export function assertIsLocale(input) {
604
+ const locale = toLocale(input);
605
+ if (locale)
606
+ return locale;
607
+ throw new Error(`Invalid locale: ${input}. Expected one of: ${locales.join(", ")}`);
608
+ }
609
+
610
+ /**
611
+ * @typedef {object} ExtractLocaleFromRequestOptions
612
+ * @property {string | URL} [effectiveRequestUrl] - Effective request URL to use for route matching and locale detection with the URL strategy.
613
+ */
614
+ /**
615
+ * Extracts a locale from a request.
616
+ *
617
+ * Use the function on the server to extract the locale
618
+ * from a request.
619
+ *
620
+ * The function goes through the strategies in the order
621
+ * they are defined. If a strategy returns an invalid locale,
622
+ * it will fall back to the next strategy.
623
+ *
624
+ * Note: Custom server strategies are not supported in this synchronous version.
625
+ * Use `extractLocaleFromRequestAsync` if you need custom server strategies with async getLocale methods.
626
+ *
627
+ * @example
628
+ * const locale = extractLocaleFromRequest(request);
629
+ *
630
+ * @param {Request} request
631
+ * @param {ExtractLocaleFromRequestOptions} [options]
632
+ * @returns {Locale}
633
+ */
634
+ export const extractLocaleFromRequest = (request, options = {}) => {
635
+ const effectiveRequestUrl = resolveEffectiveRequestUrl(request, options.effectiveRequestUrl);
636
+ return extractLocaleFromRequestWithStrategies(request, getStrategyForUrl(effectiveRequestUrl), effectiveRequestUrl);
637
+ };
638
+ /**
639
+ * Extracts a locale from a request using the provided strategy order.
640
+ *
641
+ * @param {Request} request
642
+ * @param {typeof strategy} strategies
643
+ * @param {string | URL} [url]
644
+ * @returns {Locale}
645
+ */
646
+ export const extractLocaleFromRequestWithStrategies = (request, strategies, url = request.url) => {
647
+ const effectiveRequestUrl = resolveEffectiveRequestUrl(request, url);
648
+ /** @type {string|undefined} */
649
+ let locale;
650
+ for (const strat of strategies) {
651
+ if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
652
+ const cookiePrefix = cookieName + "=";
653
+ locale = request.headers
654
+ .get("cookie")
655
+ ?.split(";")
656
+ .map((c) => c.trim())
657
+ .find((c) => c.startsWith(cookiePrefix))
658
+ ?.slice(cookiePrefix.length);
659
+ }
660
+ else if (TREE_SHAKE_URL_STRATEGY_USED && strat === "url") {
661
+ locale = extractLocaleFromUrl(effectiveRequestUrl);
662
+ }
663
+ else if (TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED &&
664
+ strat === "preferredLanguage") {
665
+ locale = extractLocaleFromHeader(request);
666
+ }
667
+ else if (strat === "globalVariable") {
668
+ locale = _locale;
669
+ }
670
+ else if (strat === "baseLocale") {
671
+ return baseLocale;
672
+ }
673
+ else if (strat === "localStorage") {
674
+ continue;
675
+ }
676
+ else if (isCustomStrategy(strat)) {
677
+ // Custom strategies are not supported in sync version
678
+ // Use extractLocaleFromRequestAsync for custom server strategies
679
+ continue;
680
+ }
681
+ const matchedLocale = toLocale(locale);
682
+ if (matchedLocale) {
683
+ return matchedLocale;
684
+ }
685
+ }
686
+ 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://paraglidejs.com/errors#no-locale-found");
687
+ };
688
+ /**
689
+ * @param {Request} request
690
+ * @param {string | URL | undefined} effectiveRequestUrl
691
+ * @returns {URL}
692
+ */
693
+ function resolveEffectiveRequestUrl(request, effectiveRequestUrl = request.url) {
694
+ if (effectiveRequestUrl instanceof URL) {
695
+ return new URL(effectiveRequestUrl.href);
696
+ }
697
+ return new URL(effectiveRequestUrl, request.url);
698
+ }
699
+
700
+ /**
701
+ * Asynchronously extracts a locale from a request.
702
+ *
703
+ * This function supports async custom server strategies, unlike the synchronous
704
+ * `extractLocaleFromRequest`. Use this function when you have custom server strategies
705
+ * that need to perform asynchronous operations (like database calls) in their getLocale method.
706
+ *
707
+ * The function first processes any custom server strategies asynchronously, then falls back
708
+ * to the synchronous `extractLocaleFromRequest` for all other strategies.
709
+ *
710
+ * @see {@link https://github.com/opral/inlang-paraglide-js/issues/527#issuecomment-2978151022}
711
+ *
712
+ * @example
713
+ * // Basic usage
714
+ * const locale = await extractLocaleFromRequestAsync(request);
715
+ *
716
+ * @example
717
+ * // With custom async server strategy
718
+ * defineCustomServerStrategy("custom-database", {
719
+ * getLocale: async (request) => {
720
+ * const userId = extractUserIdFromRequest(request);
721
+ * return await getUserLocaleFromDatabase(userId);
722
+ * }
723
+ * });
724
+ *
725
+ * const locale = await extractLocaleFromRequestAsync(request);
726
+ *
727
+ * @param {Request} request - The request object to extract the locale from.
728
+ * @param {{ effectiveRequestUrl?: string | URL }} [options] - Effective request URL to use for route matching and locale detection with the URL strategy.
729
+ * @returns {Promise<Locale>} The extracted locale.
730
+ */
731
+ export const extractLocaleFromRequestAsync = async (request, options = {}) => {
732
+ /** @type {string|undefined} */
733
+ let locale;
734
+ const effectiveRequestUrl = resolveEffectiveRequestUrlFromRequestAsync(request, options.effectiveRequestUrl);
735
+ const strategy = getStrategyForUrl(effectiveRequestUrl);
736
+ // Process custom strategies first, in order
737
+ for (const strat of strategy) {
738
+ if (isCustomStrategy(strat) && customServerStrategies.has(strat)) {
739
+ const handler = customServerStrategies.get(strat);
740
+ if (handler) {
741
+ /** @type {string|undefined} */
742
+ locale = await handler.getLocale(request);
743
+ }
744
+ // If we got a valid locale from this custom strategy, use it
745
+ const matchedLocale = toLocale(locale);
746
+ if (matchedLocale) {
747
+ return matchedLocale;
748
+ }
749
+ }
750
+ }
751
+ // If no custom strategy provided a valid locale, fall back to sync version
752
+ return extractLocaleFromRequestWithStrategies(request, strategy, effectiveRequestUrl);
753
+ };
754
+ /**
755
+ * @param {Request} request
756
+ * @param {string | URL | undefined} effectiveRequestUrl
757
+ * @returns {URL}
758
+ */
759
+ function resolveEffectiveRequestUrlFromRequestAsync(request, effectiveRequestUrl = request.url) {
760
+ if (effectiveRequestUrl instanceof URL) {
761
+ return new URL(effectiveRequestUrl.href);
762
+ }
763
+ return new URL(effectiveRequestUrl, request.url);
764
+ }
765
+
766
+ const cookieNamePattern = cookieName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
767
+ const localeCookiePattern = new RegExp(`(?:^|;\\s*)${cookieNamePattern}=([^;]*)`);
768
+ const noCachedLocale = Symbol();
769
+ /** @type {Locale | undefined | typeof noCachedLocale} */
770
+ let cachedLocaleFromCookie = noCachedLocale;
771
+ /**
772
+ * Clears the cached locale from `document.cookie`.
773
+ */
774
+ function clearLocaleCookieCache() {
775
+ cachedLocaleFromCookie = noCachedLocale;
776
+ }
777
+ function scheduleLocaleCookieCacheClear() {
778
+ if (typeof queueMicrotask === "function") {
779
+ queueMicrotask(clearLocaleCookieCache);
780
+ }
781
+ else {
782
+ Promise.resolve().then(clearLocaleCookieCache);
783
+ }
784
+ }
785
+ /**
786
+ * Extracts a cookie from the document.
787
+ *
788
+ * Will return undefined if the document is not available or if the cookie is not set.
789
+ * The `document` object is not available in server-side rendering, so this function should not be called in that context.
790
+ *
791
+ * @returns {Locale | undefined}
792
+ */
793
+ export function extractLocaleFromCookie() {
794
+ if (typeof document === "undefined") {
795
+ return;
796
+ }
797
+ if (cachedLocaleFromCookie !== noCachedLocale) {
798
+ return cachedLocaleFromCookie;
799
+ }
800
+ const match = document.cookie.match(localeCookiePattern);
801
+ const locale = match?.[1];
802
+ cachedLocaleFromCookie = toLocale(locale);
803
+ scheduleLocaleCookieCacheClear();
804
+ return cachedLocaleFromCookie;
805
+ }
806
+
807
+ /**
808
+ * Extracts a locale from the accept-language header.
809
+ *
810
+ * Use the function on the server to extract the locale
811
+ * from the accept-language header that is sent by the client.
812
+ *
813
+ * @example
814
+ * const locale = extractLocaleFromHeader(request);
815
+ *
816
+ * @param {Request} request - The request object to extract the locale from.
817
+ * @returns {Locale | undefined} The negotiated preferred language.
818
+ */
819
+ export function extractLocaleFromHeader(request) {
820
+ const acceptLanguageHeader = request.headers.get("accept-language");
821
+ if (acceptLanguageHeader) {
822
+ // Parse language preferences with their q-values and base language codes
823
+ const languages = acceptLanguageHeader
824
+ .split(",")
825
+ .map((lang) => {
826
+ const [tag, q = "1"] = lang.trim().split(";q=");
827
+ // Get both the full tag and base language code
828
+ const baseTag = tag?.split("-")[0];
829
+ return {
830
+ fullTag: tag,
831
+ baseTag,
832
+ q: Number(q),
833
+ };
834
+ })
835
+ .sort((a, b) => b.q - a.q);
836
+ for (const lang of languages) {
837
+ const fullLocale = toLocale(lang.fullTag);
838
+ if (fullLocale) {
839
+ return fullLocale;
840
+ }
841
+ const baseLocale = toLocale(lang.baseTag);
842
+ if (baseLocale) {
843
+ return baseLocale;
844
+ }
845
+ }
846
+ return undefined;
847
+ }
848
+ return undefined;
849
+ }
850
+
851
+ /**
852
+ * Negotiates a preferred language from navigator.languages.
853
+ *
854
+ * Use the function on the client to extract the locale
855
+ * from the navigator.languages array.
856
+ *
857
+ * @example
858
+ * const locale = extractLocaleFromNavigator();
859
+ *
860
+ * @returns {Locale | undefined}
861
+ */
862
+ export function extractLocaleFromNavigator() {
863
+ if (!navigator?.languages?.length) {
864
+ return undefined;
865
+ }
866
+ const languages = navigator.languages.map((lang) => ({
867
+ fullTag: lang,
868
+ baseTag: lang.split("-")[0],
869
+ }));
870
+ for (const lang of languages) {
871
+ const fullLocale = toLocale(lang.fullTag);
872
+ if (fullLocale) {
873
+ return fullLocale;
874
+ }
875
+ const baseLocale = toLocale(lang.baseTag);
876
+ if (baseLocale) {
877
+ return baseLocale;
878
+ }
879
+ }
880
+ return undefined;
881
+ }
882
+
883
+ /**
884
+ * If extractLocaleFromUrl is called many times on the same page and the URL
885
+ * hasn't changed, we don't need to recompute it every time which can get expensive.
886
+ * We might use a LRU cache if needed, but for now storing only the last result is enough.
887
+ * https://github.com/opral/monorepo/pull/3575#discussion_r2066731243
888
+ */
889
+ /** @type {string|undefined} */
890
+ let cachedUrl;
891
+ /** @type {Locale|undefined} */
892
+ let cachedLocale;
893
+ /**
894
+ * Extracts the locale from a given URL using native URLPattern.
895
+ *
896
+ * The built-in default `/:locale/...` routing is case-insensitive because it
897
+ * canonicalizes the first path segment with `toLocale()`. Custom `urlPatterns`
898
+ * keep URLPattern's normal exact matching semantics for path segments.
899
+ *
900
+ * @param {URL|string} url - The full URL from which to extract the locale.
901
+ * @returns {Locale|undefined} The extracted locale, or undefined if no locale is found.
902
+ */
903
+ export function extractLocaleFromUrl(url) {
904
+ const urlString = typeof url === "string" ? url : url.href;
905
+ if (cachedUrl === urlString) {
906
+ return cachedLocale;
907
+ }
908
+ /** @type {Locale | undefined} */
909
+ let result;
910
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
911
+ result = defaultUrlPatternExtractLocale(url);
912
+ }
913
+ else {
914
+ const urlObj = typeof url === "string" ? new URL(url) : url;
915
+ // Iterate over URL patterns
916
+ for (const element of urlPatterns) {
917
+ for (const [locale, localizedPattern] of element.localized) {
918
+ const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
919
+ if (match) {
920
+ result = locale;
921
+ break;
922
+ }
923
+ }
924
+ if (result)
925
+ break;
926
+ }
927
+ }
928
+ cachedUrl = urlString;
929
+ cachedLocale = result;
930
+ return result;
931
+ }
932
+ /**
933
+ * https://github.com/opral/inlang-paraglide-js/issues/381
934
+ *
935
+ * @param {URL | string} url - The full URL from which to extract the locale.
936
+ * @returns {Locale | undefined} The extracted locale, or undefined if no locale is found.
937
+ */
938
+ function defaultUrlPatternExtractLocale(url) {
939
+ const urlObj = new URL(url, "http://dummy.com");
940
+ const pathSegments = urlObj.pathname.split("/").filter(Boolean);
941
+ return toLocale(pathSegments[0]) || baseLocale;
942
+ }
943
+
944
+ /**
945
+ * Lower-level URL localization function, primarily used in server contexts.
946
+ *
947
+ * This function is designed for server-side usage where you need precise control
948
+ * over URL localization, such as in middleware or request handlers. It works with
949
+ * URL objects and always returns absolute URLs.
950
+ *
951
+ * For client-side UI components, use `localizeHref()` instead, which provides
952
+ * a more convenient API with relative paths and automatic locale detection.
953
+ *
954
+ * @see https://paraglidejs.com/i18n-routing
955
+ *
956
+ * @example
957
+ * ```typescript
958
+ * // Server middleware example
959
+ * app.use((req, res, next) => {
960
+ * const url = new URL(req.url, `${req.protocol}://${req.headers.host}`);
961
+ * const localized = localizeUrl(url, { locale: "de" });
962
+ *
963
+ * if (localized.href !== url.href) {
964
+ * return res.redirect(localized.href);
965
+ * }
966
+ * next();
967
+ * });
968
+ * ```
969
+ *
970
+ * @example
971
+ * ```typescript
972
+ * // Using with URL patterns
973
+ * const url = new URL("https://example.com/about");
974
+ * localizeUrl(url, { locale: "de" });
975
+ * // => URL("https://example.com/de/about")
976
+ *
977
+ * // Using with domain-based localization
978
+ * const url = new URL("https://example.com/store");
979
+ * localizeUrl(url, { locale: "de" });
980
+ * // => URL("https://de.example.com/store")
981
+ * ```
982
+ *
983
+ * @param {string | URL} url - The URL to localize. If string, must be absolute.
984
+ * @param {object} [options] - Options for localization
985
+ * @param {Locale} [options.locale] - Target locale. If not provided, uses getLocale()
986
+ * @returns {URL} The localized URL, always absolute
987
+ */
988
+ export function localizeUrl(url, options) {
989
+ const targetLocale = options?.locale
990
+ ? assertIsLocale(options?.locale)
991
+ : getLocale();
992
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
993
+ return localizeUrlDefaultPattern(url, targetLocale);
994
+ }
995
+ const urlObj = typeof url === "string" ? new URL(url) : url;
996
+ // Iterate over URL patterns
997
+ for (const element of urlPatterns) {
998
+ // match localized patterns
999
+ for (const [, localizedPattern] of element.localized) {
1000
+ const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
1001
+ if (!match) {
1002
+ continue;
1003
+ }
1004
+ const targetPattern = element.localized.find(([locale]) => locale === targetLocale)?.[1];
1005
+ if (!targetPattern) {
1006
+ continue;
1007
+ }
1008
+ const localizedUrl = fillPattern(targetPattern, aggregateGroups(match), urlObj.origin);
1009
+ return fillMissingUrlParts(localizedUrl, match);
1010
+ }
1011
+ const unlocalizedMatch = new URLPattern(element.pattern, urlObj.href).exec(urlObj.href);
1012
+ if (unlocalizedMatch) {
1013
+ const targetPattern = element.localized.find(([locale]) => locale === targetLocale)?.[1];
1014
+ if (targetPattern) {
1015
+ const localizedUrl = fillPattern(targetPattern, aggregateGroups(unlocalizedMatch), urlObj.origin);
1016
+ return fillMissingUrlParts(localizedUrl, unlocalizedMatch);
1017
+ }
1018
+ }
1019
+ }
1020
+ // If no match found, return the original URL
1021
+ return urlObj;
1022
+ }
1023
+ /**
1024
+ * https://github.com/opral/inlang-paraglide-js/issues/381
1025
+ *
1026
+ * @param {string | URL} url
1027
+ * @param {Locale} locale
1028
+ * @returns {URL}
1029
+ */
1030
+ function localizeUrlDefaultPattern(url, locale) {
1031
+ const urlObj = typeof url === "string" ? new URL(url, getUrlOrigin()) : new URL(url);
1032
+ const currentLocale = extractLocaleFromUrl(urlObj);
1033
+ // If current locale matches target locale, no change needed
1034
+ if (currentLocale === locale) {
1035
+ return urlObj;
1036
+ }
1037
+ const pathSegments = urlObj.pathname.split("/").filter(Boolean);
1038
+ // If current path starts with a locale, remove it
1039
+ if (pathSegments.length > 0 && toLocale(pathSegments[0])) {
1040
+ pathSegments.shift();
1041
+ }
1042
+ // For base locale, don't add prefix
1043
+ if (locale === baseLocale) {
1044
+ urlObj.pathname = "/" + pathSegments.join("/");
1045
+ }
1046
+ else {
1047
+ // For other locales, add prefix
1048
+ urlObj.pathname = "/" + locale + "/" + pathSegments.join("/");
1049
+ }
1050
+ return urlObj;
1051
+ }
1052
+ /**
1053
+ * Low-level URL de-localization function, primarily used in server contexts.
1054
+ *
1055
+ * This function is designed for server-side usage where you need precise control
1056
+ * over URL de-localization, such as in middleware or request handlers. It works with
1057
+ * URL objects and always returns absolute URLs.
1058
+ *
1059
+ * For client-side UI components, use `deLocalizeHref()` instead, which provides
1060
+ * a more convenient API with relative paths.
1061
+ *
1062
+ * @see https://paraglidejs.com/i18n-routing
1063
+ *
1064
+ * @example
1065
+ * ```typescript
1066
+ * // Server middleware example
1067
+ * app.use((req, res, next) => {
1068
+ * const url = new URL(req.url, `${req.protocol}://${req.headers.host}`);
1069
+ * const baseUrl = deLocalizeUrl(url);
1070
+ *
1071
+ * // Store the base URL for later use
1072
+ * req.baseUrl = baseUrl;
1073
+ * next();
1074
+ * });
1075
+ * ```
1076
+ *
1077
+ * @example
1078
+ * ```typescript
1079
+ * // Using with URL patterns
1080
+ * const url = new URL("https://example.com/de/about");
1081
+ * deLocalizeUrl(url); // => URL("https://example.com/about")
1082
+ *
1083
+ * // Using with domain-based localization
1084
+ * const url = new URL("https://de.example.com/store");
1085
+ * deLocalizeUrl(url); // => URL("https://example.com/store")
1086
+ * ```
1087
+ *
1088
+ * @param {string | URL} url - The URL to de-localize. If string, must be absolute.
1089
+ * @returns {URL} The de-localized URL, always absolute
1090
+ */
1091
+ export function deLocalizeUrl(url) {
1092
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
1093
+ return deLocalizeUrlDefaultPattern(url);
1094
+ }
1095
+ const urlObj = typeof url === "string" ? new URL(url) : url;
1096
+ // Iterate over URL patterns
1097
+ for (const element of urlPatterns) {
1098
+ // Iterate over localized versions
1099
+ for (const [, localizedPattern] of element.localized) {
1100
+ const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
1101
+ if (match) {
1102
+ // Convert localized URL back to the base pattern
1103
+ const groups = aggregateGroups(match);
1104
+ const baseUrl = fillPattern(element.pattern, groups, urlObj.origin);
1105
+ return fillMissingUrlParts(baseUrl, match);
1106
+ }
1107
+ }
1108
+ // match unlocalized pattern
1109
+ const unlocalizedMatch = new URLPattern(element.pattern, urlObj.href).exec(urlObj.href);
1110
+ if (unlocalizedMatch) {
1111
+ const baseUrl = fillPattern(element.pattern, aggregateGroups(unlocalizedMatch), urlObj.origin);
1112
+ return fillMissingUrlParts(baseUrl, unlocalizedMatch);
1113
+ }
1114
+ }
1115
+ // no match found return the original url
1116
+ return urlObj;
1117
+ }
1118
+ /**
1119
+ * De-localizes a URL using the default pattern (/:locale/*)
1120
+ * @param {string|URL} url
1121
+ * @returns {URL}
1122
+ */
1123
+ function deLocalizeUrlDefaultPattern(url) {
1124
+ const urlObj = typeof url === "string" ? new URL(url, getUrlOrigin()) : new URL(url);
1125
+ const pathSegments = urlObj.pathname.split("/").filter(Boolean);
1126
+ // If first segment is a locale, remove it
1127
+ if (pathSegments.length > 0 && toLocale(pathSegments[0])) {
1128
+ urlObj.pathname = "/" + pathSegments.slice(1).join("/");
1129
+ }
1130
+ return urlObj;
1131
+ }
1132
+ /**
1133
+ * Takes matches of implicit wildcards in the UrlPattern (when a part is missing
1134
+ * it is equal to '*') and adds them back to the result of fillPattern.
1135
+ *
1136
+ * At least protocol and hostname are required to create a valid URL inside fillPattern.
1137
+ *
1138
+ * @param {URL} url
1139
+ * @param {any} match
1140
+ * @returns {URL}
1141
+ */
1142
+ function fillMissingUrlParts(url, match) {
1143
+ if (match.protocol.groups["0"]) {
1144
+ url.protocol = match.protocol.groups["0"] ?? "";
1145
+ }
1146
+ if (match.hostname.groups["0"]) {
1147
+ url.hostname = match.hostname.groups["0"] ?? "";
1148
+ }
1149
+ if (match.username.groups["0"]) {
1150
+ url.username = match.username.groups["0"] ?? "";
1151
+ }
1152
+ if (match.password.groups["0"]) {
1153
+ url.password = match.password.groups["0"] ?? "";
1154
+ }
1155
+ if (match.port.groups["0"]) {
1156
+ url.port = match.port.groups["0"] ?? "";
1157
+ }
1158
+ if (match.pathname.groups["0"]) {
1159
+ url.pathname = match.pathname.groups["0"] ?? "";
1160
+ }
1161
+ if (match.search.groups["0"]) {
1162
+ url.search = match.search.groups["0"] ?? "";
1163
+ }
1164
+ if (match.hash.groups["0"]) {
1165
+ url.hash = match.hash.groups["0"] ?? "";
1166
+ }
1167
+ return url;
1168
+ }
1169
+ /**
1170
+ * Fills a URL pattern with values for named groups, supporting all URLPattern-style modifiers.
1171
+ *
1172
+ * This function will eventually be replaced by https://github.com/whatwg/urlpattern/issues/73
1173
+ *
1174
+ * Matches:
1175
+ * - :name -> Simple
1176
+ * - :name? -> Optional
1177
+ * - :name+ -> One or more
1178
+ * - :name* -> Zero or more
1179
+ * - :name(...) -> Regex group
1180
+ * - {text} -> Group delimiter
1181
+ * - {text}? -> Optional group delimiter
1182
+ *
1183
+ * If the value is `null`, the segment is removed.
1184
+ *
1185
+ * @param {string} pattern - The URL pattern containing named groups.
1186
+ * @param {Record<string, string | null | undefined>} values - Object of values for named groups.
1187
+ * @param {string} origin - Base URL to use for URL construction.
1188
+ * @returns {URL} - The constructed URL with named groups filled.
1189
+ */
1190
+ function fillPattern(pattern, values, origin) {
1191
+ // Pre-process the pattern to handle explicit port numbers
1192
+ // This detects patterns like "http://localhost:5173" and protects the port number
1193
+ // from being interpreted as a parameter
1194
+ let processedPattern = pattern.replace(/(https?:\/\/[^:/]+):(\d+)(\/|$)/g, (_, protocol, port, slash) => {
1195
+ // Replace ":5173" with "#PORT-5173#" to protect it from parameter replacement
1196
+ return `${protocol}#PORT-${port}#${slash}`;
1197
+ });
1198
+ // First, handle group delimiters with curly braces
1199
+ let processedGroupDelimiters = processedPattern.replace(/\{([^{}]*)\}([?+*]?)/g, (_, content, modifier) => {
1200
+ // For optional group delimiters
1201
+ if (modifier === "?") {
1202
+ // For optional groups, we'll include the content
1203
+ return content;
1204
+ }
1205
+ // For non-optional group delimiters, always include the content
1206
+ return content;
1207
+ });
1208
+ // Then handle named groups
1209
+ let filled = processedGroupDelimiters.replace(/(\/?):([a-zA-Z0-9_]+)(\([^)]*\))?([?+*]?)/g, (_, slash, name, __, modifier) => {
1210
+ const value = values[name];
1211
+ if (value === null) {
1212
+ // If value is null, remove the entire segment including the preceding slash
1213
+ return "";
1214
+ }
1215
+ if (modifier === "?") {
1216
+ // Optional segment
1217
+ return value !== undefined ? `${slash}${value}` : "";
1218
+ }
1219
+ if (modifier === "+" || modifier === "*") {
1220
+ // Repeatable segments
1221
+ if (value === undefined && modifier === "+") {
1222
+ throw new Error(`Missing value for "${name}" (one or more required)`);
1223
+ }
1224
+ return value ? `${slash}${value}` : "";
1225
+ }
1226
+ // Simple named group (no modifier)
1227
+ if (value === undefined) {
1228
+ throw new Error(`Missing value for "${name}"`);
1229
+ }
1230
+ return `${slash}${value}`;
1231
+ });
1232
+ // Restore port numbers
1233
+ filled = filled.replace(/#PORT-(\d+)#/g, ":$1");
1234
+ return new URL(filled, origin);
1235
+ }
1236
+ /**
1237
+ * Aggregates named groups from various parts of the URLPattern match result.
1238
+ *
1239
+ *
1240
+ * @param {any} match - The URLPattern match result object.
1241
+ * @returns {Record<string, string | null | undefined>} An object containing all named groups from the match.
1242
+ */
1243
+ export function aggregateGroups(match) {
1244
+ return {
1245
+ ...match.hash.groups,
1246
+ ...match.hostname.groups,
1247
+ ...match.password.groups,
1248
+ ...match.pathname.groups,
1249
+ ...match.port.groups,
1250
+ ...match.protocol.groups,
1251
+ ...match.search.groups,
1252
+ ...match.username.groups,
1253
+ };
1254
+ }
1255
+
1256
+ /**
1257
+ * @typedef {object} ShouldRedirectServerInput
1258
+ * @property {Request} request
1259
+ * @property {string | URL} [effectiveRequestUrl] - Effective request URL to use for route matching, locale detection with the URL strategy, and redirect targets.
1260
+ * @property {Locale} [locale]
1261
+ *
1262
+ * @typedef {object} ShouldRedirectClientInput
1263
+ * @property {undefined} [request]
1264
+ * @property {string | URL} [url]
1265
+ * @property {Locale} [locale]
1266
+ *
1267
+ * @typedef {ShouldRedirectServerInput | ShouldRedirectClientInput} ShouldRedirectInput
1268
+ *
1269
+ * @typedef {object} ShouldRedirectResult
1270
+ * @property {boolean} shouldRedirect - Indicates whether the consumer should perform a redirect.
1271
+ * @property {Locale} locale - Locale resolved using the configured strategies.
1272
+ * @property {URL | undefined} redirectUrl - Destination URL when a redirect is required.
1273
+ */
1274
+ /**
1275
+ * Determines whether a redirect is required to align the current URL with the active locale.
1276
+ *
1277
+ * This helper mirrors the logic that powers `paraglideMiddleware`, but works in both server
1278
+ * and client environments. It evaluates the configured strategies in order, computes the
1279
+ * canonical localized URL, and reports when the current URL does not match.
1280
+ *
1281
+ * When called in the browser without arguments, the current `window.location.href` is used.
1282
+ *
1283
+ * @see https://paraglidejs.com/i18n-routing#redirects
1284
+ *
1285
+ * @example
1286
+ * // Client side usage (e.g. TanStack Router beforeLoad hook)
1287
+ * async function beforeLoad({ location }) {
1288
+ * const decision = await shouldRedirect({ url: location.href });
1289
+ *
1290
+ * if (decision.shouldRedirect) {
1291
+ * throw redirect({ to: decision.redirectUrl.href });
1292
+ * }
1293
+ * }
1294
+ *
1295
+ * @example
1296
+ * // Server side usage with a Request
1297
+ * export async function handle(request) {
1298
+ * const decision = await shouldRedirect({ request });
1299
+ *
1300
+ * if (decision.shouldRedirect) {
1301
+ * return Response.redirect(decision.redirectUrl, 307);
1302
+ * }
1303
+ *
1304
+ * return render(request, decision.locale);
1305
+ * }
1306
+ *
1307
+ * @example
1308
+ * // Server side usage behind a proxy where request.url is not public-facing
1309
+ * export async function handle(request) {
1310
+ * const effectiveRequestUrl = new URL(request.url);
1311
+ * effectiveRequestUrl.protocol = "https:";
1312
+ * effectiveRequestUrl.host = "example.com";
1313
+ *
1314
+ * const decision = await shouldRedirect({
1315
+ * request,
1316
+ * effectiveRequestUrl,
1317
+ * });
1318
+ *
1319
+ * if (decision.shouldRedirect) {
1320
+ * return Response.redirect(decision.redirectUrl, 307);
1321
+ * }
1322
+ * }
1323
+ *
1324
+ * @param {ShouldRedirectInput} [input]
1325
+ * @returns {Promise<ShouldRedirectResult>}
1326
+ */
1327
+ export async function shouldRedirect(input = {}) {
1328
+ const currentUrl = resolveUrl(input);
1329
+ const locale = await resolveLocale(input, currentUrl);
1330
+ const strategy = getStrategyForUrl(currentUrl.href);
1331
+ if (isExcludedByRouteStrategy(currentUrl.href) || !strategy.includes("url")) {
1332
+ return { shouldRedirect: false, locale, redirectUrl: undefined };
1333
+ }
1334
+ const localizedUrl = localizeUrl(currentUrl.href, { locale });
1335
+ const shouldRedirectToLocalizedUrl = normalizeUrl(localizedUrl.href) !== normalizeUrl(currentUrl.href);
1336
+ return {
1337
+ shouldRedirect: shouldRedirectToLocalizedUrl,
1338
+ locale,
1339
+ redirectUrl: shouldRedirectToLocalizedUrl ? localizedUrl : undefined,
1340
+ };
1341
+ }
1342
+ /**
1343
+ * Resolves the locale either from the provided input or by using the configured strategies.
1344
+ *
1345
+ * @param {ShouldRedirectInput} input
1346
+ * @param {URL} currentUrl
1347
+ * @returns {Promise<Locale>}
1348
+ */
1349
+ async function resolveLocale(input, currentUrl) {
1350
+ const locale = toLocale(input.locale);
1351
+ if (locale) {
1352
+ return locale;
1353
+ }
1354
+ if (input.request) {
1355
+ return extractLocaleFromRequestAsync(input.request, {
1356
+ effectiveRequestUrl: currentUrl,
1357
+ });
1358
+ }
1359
+ if ("url" in input && typeof input.url !== "undefined") {
1360
+ return getLocaleForUrl(currentUrl.href);
1361
+ }
1362
+ return getLocale();
1363
+ }
1364
+ /**
1365
+ * Resolves the current URL from the provided input or runtime context.
1366
+ *
1367
+ * @param {ShouldRedirectInput} input
1368
+ * @returns {URL}
1369
+ */
1370
+ function resolveUrl(input) {
1371
+ if ("effectiveRequestUrl" in input && input.effectiveRequestUrl instanceof URL) {
1372
+ return new URL(input.effectiveRequestUrl.href);
1373
+ }
1374
+ if ("effectiveRequestUrl" in input && typeof input.effectiveRequestUrl === "string") {
1375
+ return new URL(input.effectiveRequestUrl, input.request ? input.request.url : getUrlOrigin());
1376
+ }
1377
+ if (input.request) {
1378
+ return new URL(input.request.url);
1379
+ }
1380
+ if ("url" in input && input.url instanceof URL) {
1381
+ return new URL(input.url.href);
1382
+ }
1383
+ if ("url" in input && typeof input.url === "string") {
1384
+ return new URL(input.url, getUrlOrigin());
1385
+ }
1386
+ if (typeof window !== "undefined" && window?.location?.href) {
1387
+ return new URL(window.location.href);
1388
+ }
1389
+ throw new Error("shouldRedirect() requires either a request, an absolute URL, or must run in a browser environment.");
1390
+ }
1391
+ /**
1392
+ * Normalize url for comparison by stripping the trailing slash.
1393
+ *
1394
+ * @param {string} url
1395
+ * @returns {string}
1396
+ */
1397
+ function normalizeUrl(url) {
1398
+ const urlObj = new URL(url);
1399
+ urlObj.pathname = urlObj.pathname.replace(/\/$/, "");
1400
+ return urlObj.href;
1401
+ }
1402
+
1403
+ /**
1404
+ * High-level URL localization function optimized for client-side UI usage.
1405
+ *
1406
+ * This is a convenience wrapper around `localizeUrl()` that provides features
1407
+ * needed in UI:
1408
+ *
1409
+ * - Accepts relative paths (e.g., "/about")
1410
+ * - Returns relative paths when possible
1411
+ * - Automatically detects current locale if not specified
1412
+ * - Handles string input/output instead of URL objects
1413
+ *
1414
+ * @see https://paraglidejs.com/i18n-routing
1415
+ *
1416
+ * @example
1417
+ * ```typescript
1418
+ * // In a React/Vue/Svelte component
1419
+ * const NavLink = ({ href }) => {
1420
+ * // Automatically uses current locale, keeps path relative
1421
+ * return <a href={localizeHref(href)}>...</a>;
1422
+ * };
1423
+ *
1424
+ * // Examples:
1425
+ * localizeHref("/about")
1426
+ * // => "/de/about" (if current locale is "de")
1427
+ * localizeHref("/store", { locale: "fr" })
1428
+ * // => "/fr/store" (explicit locale)
1429
+ *
1430
+ * // Cross-origin links remain absolute
1431
+ * localizeHref("https://other-site.com/about")
1432
+ * // => "https://other-site.com/de/about"
1433
+ * ```
1434
+ *
1435
+ * For server-side URL localization (e.g., in middleware), use `localizeUrl()`
1436
+ * which provides more precise control over URL handling.
1437
+ *
1438
+ * @param {string} href - The href to localize (can be relative or absolute)
1439
+ * @param {object} [options] - Options for localization
1440
+ * @param {Locale} [options.locale] - Target locale. If not provided, uses `getLocale()`
1441
+ * @returns {string} The localized href, relative if input was relative
1442
+ */
1443
+ export function localizeHref(href, options) {
1444
+ const currentLocale = getLocale();
1445
+ const locale = options?.locale ?? currentLocale;
1446
+ const url = new URL(href, getUrlOrigin());
1447
+ const localized = localizeUrl(url, { locale });
1448
+ // if the origin is identical and the href is relative,
1449
+ // return the relative path
1450
+ if (href.startsWith("/") && url.origin === localized.origin) {
1451
+ // check for cross origin localization in which case an absolute URL must be returned.
1452
+ if (locale !== currentLocale) {
1453
+ const localizedCurrentLocale = localizeUrl(url, {
1454
+ locale: currentLocale,
1455
+ });
1456
+ if (localizedCurrentLocale.origin !== localized.origin) {
1457
+ return localized.href;
1458
+ }
1459
+ }
1460
+ return localized.pathname + localized.search + localized.hash;
1461
+ }
1462
+ return localized.href;
1463
+ }
1464
+ /**
1465
+ * High-level URL de-localization function optimized for client-side UI usage.
1466
+ *
1467
+ * This is a convenience wrapper around `deLocalizeUrl()` that provides features
1468
+ * needed in the UI:
1469
+ *
1470
+ * - Accepts relative paths (e.g., "/de/about")
1471
+ * - Returns relative paths when possible
1472
+ * - Handles string input/output instead of URL objects
1473
+ *
1474
+ * @see https://paraglidejs.com/i18n-routing
1475
+ *
1476
+ * @example
1477
+ * ```typescript
1478
+ * // In a React/Vue/Svelte component
1479
+ * const LocaleSwitcher = ({ href }) => {
1480
+ * // Remove locale prefix before switching
1481
+ * const baseHref = deLocalizeHref(href);
1482
+ * return locales.map(locale =>
1483
+ * <a href={localizeHref(baseHref, { locale })}>
1484
+ * Switch to {locale}
1485
+ * </a>
1486
+ * );
1487
+ * };
1488
+ *
1489
+ * // Examples:
1490
+ * deLocalizeHref("/de/about") // => "/about"
1491
+ * deLocalizeHref("/fr/store") // => "/store"
1492
+ *
1493
+ * // Cross-origin links remain absolute
1494
+ * deLocalizeHref("https://example.com/de/about")
1495
+ * // => "https://example.com/about"
1496
+ * ```
1497
+ *
1498
+ * For server-side URL de-localization (e.g., in middleware), use `deLocalizeUrl()`
1499
+ * which provides more precise control over URL handling.
1500
+ *
1501
+ * @param {string} href - The href to de-localize (can be relative or absolute)
1502
+ * @returns {string} The de-localized href, relative if input was relative
1503
+ */
1504
+ export function deLocalizeHref(href) {
1505
+ const url = new URL(href, getUrlOrigin());
1506
+ const deLocalized = deLocalizeUrl(url);
1507
+ // If the origin is identical and the href is relative,
1508
+ // return the relative path instead of the full URL.
1509
+ if (href.startsWith("/") && url.origin === deLocalized.origin) {
1510
+ return deLocalized.pathname + deLocalized.search + deLocalized.hash;
1511
+ }
1512
+ return deLocalized.href;
1513
+ }
1514
+
1515
+ /**
1516
+ * @param {string} safeModuleId
1517
+ * @param {Locale} locale
1518
+ */
1519
+ export function trackMessageCall(safeModuleId, locale) {
1520
+ if (isServer === false)
1521
+ return;
1522
+ const store = serverAsyncLocalStorage?.getStore();
1523
+ if (store) {
1524
+ store.messageCalls?.add(`${safeModuleId}:${locale}`);
1525
+ }
1526
+ }
1527
+
1528
+ /**
1529
+ * Generates localized URL variants for all provided URLs based on your configured locales and URL patterns.
1530
+ *
1531
+ * This function is essential for Static Site Generation (SSG) where you need to tell your framework
1532
+ * which pages to pre-render at build time. It's also useful for generating sitemaps and
1533
+ * `<link rel="alternate" hreflang>` tags for SEO.
1534
+ *
1535
+ * The function respects your `urlPatterns` configuration - if you have translated pathnames
1536
+ * (e.g., `/about` → `/ueber-uns` for German), it will generate the correct localized paths.
1537
+ *
1538
+ * @see https://paraglidejs.com/static-site-generation
1539
+ *
1540
+ * @example
1541
+ * // Basic usage - generate all locale variants for a list of paths
1542
+ * const localizedUrls = generateStaticLocalizedUrls([
1543
+ * "/",
1544
+ * "/about",
1545
+ * "/blog/post-1",
1546
+ * ]);
1547
+ * // Returns URL objects for each locale:
1548
+ * // ["/en/", "/de/", "/en/about", "/de/about", "/en/blog/post-1", "/de/blog/post-1"]
1549
+ *
1550
+ * @example
1551
+ * // Use with framework SSG APIs
1552
+ * // SvelteKit
1553
+ * export function entries() {
1554
+ * const paths = ["/", "/about", "/contact"];
1555
+ * return generateStaticLocalizedUrls(paths).map(url => ({
1556
+ * locale: extractLocaleFromUrl(url)
1557
+ * }));
1558
+ * }
1559
+ *
1560
+ * @example
1561
+ * // Sitemap generation
1562
+ * const allPages = ["/", "/about", "/blog"];
1563
+ * const sitemapUrls = generateStaticLocalizedUrls(allPages);
1564
+ *
1565
+ * @param {(string | URL)[]} urls - List of canonical URLs or paths to generate localized versions for.
1566
+ * Can be absolute URLs (`https://example.com/about`) or paths (`/about`).
1567
+ * Paths are resolved against `http://localhost` internally.
1568
+ * @returns {URL[]} Array of URL objects representing all localized variants.
1569
+ * The order follows each input URL with all its locale variants before moving to the next URL.
1570
+ */
1571
+ export function generateStaticLocalizedUrls(urls) {
1572
+ /** @type {Set<URL>} */
1573
+ const localizedUrls = new Set();
1574
+ // For default URL pattern, we can optimize the generation
1575
+ if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
1576
+ for (const urlInput of urls) {
1577
+ const url = urlInput instanceof URL
1578
+ ? urlInput
1579
+ : new URL(urlInput, "http://localhost");
1580
+ // Base locale doesn't get a prefix
1581
+ localizedUrls.add(url);
1582
+ // Other locales get their code as prefix
1583
+ for (const locale of locales) {
1584
+ if (locale !== baseLocale) {
1585
+ const localizedPath = `/${locale}${url.pathname}${url.search}${url.hash}`;
1586
+ const localizedUrl = new URL(localizedPath, url.origin);
1587
+ localizedUrls.add(localizedUrl);
1588
+ }
1589
+ }
1590
+ }
1591
+ return Array.from(localizedUrls);
1592
+ }
1593
+ // For custom URL patterns, we need to use localizeUrl for each URL and locale
1594
+ for (const urlInput of urls) {
1595
+ const url = urlInput instanceof URL
1596
+ ? urlInput
1597
+ : new URL(urlInput, "http://localhost");
1598
+ // Try each URL pattern to find one that matches
1599
+ let patternFound = false;
1600
+ for (const pattern of urlPatterns) {
1601
+ try {
1602
+ // Try to match the unlocalized pattern
1603
+ const unlocalizedMatch = new URLPattern(pattern.pattern, url.href).exec(url.href);
1604
+ if (!unlocalizedMatch)
1605
+ continue;
1606
+ patternFound = true;
1607
+ // Track unique localized URLs to avoid duplicates when patterns are the same
1608
+ const seenUrls = new Set();
1609
+ // Generate localized URL for each locale
1610
+ for (const [locale] of pattern.localized) {
1611
+ try {
1612
+ const localizedUrl = localizeUrl(url, { locale });
1613
+ const urlString = localizedUrl.href;
1614
+ // Only add if we haven't seen this exact URL before
1615
+ if (!seenUrls.has(urlString)) {
1616
+ seenUrls.add(urlString);
1617
+ localizedUrls.add(localizedUrl);
1618
+ }
1619
+ }
1620
+ catch {
1621
+ // Skip if localization fails for this locale
1622
+ continue;
1623
+ }
1624
+ }
1625
+ break;
1626
+ }
1627
+ catch {
1628
+ // Skip if pattern matching fails
1629
+ continue;
1630
+ }
1631
+ }
1632
+ // If no pattern matched, use the URL as is
1633
+ if (!patternFound) {
1634
+ localizedUrls.add(url);
1635
+ }
1636
+ }
1637
+ return Array.from(localizedUrls);
1638
+ }
1639
+
1640
+ /**
1641
+ * @typedef {"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage"} BuiltInStrategy
1642
+ */
1643
+ /**
1644
+ * @typedef {`custom_${string}`} CustomStrategy
1645
+ */
1646
+ /**
1647
+ * @typedef {BuiltInStrategy | CustomStrategy} Strategy
1648
+ */
1649
+ /**
1650
+ * @typedef {Array<Strategy>} Strategies
1651
+ */
1652
+ /**
1653
+ * @typedef {{ getLocale: (request?: Request) => Promise<string | undefined> | (string | undefined) }} CustomServerStrategyHandler
1654
+ */
1655
+ /**
1656
+ * @typedef {{ getLocale: () => Promise<string|undefined> | (string | undefined), setLocale: (locale: string) => Promise<void> | void }} CustomClientStrategyHandler
1657
+ */
1658
+ /** @type {Map<string, CustomServerStrategyHandler>} */
1659
+ export const customServerStrategies = new Map();
1660
+ /** @type {Map<string, CustomClientStrategyHandler>} */
1661
+ export const customClientStrategies = new Map();
1662
+ /**
1663
+ * Checks if the given strategy is a custom strategy.
1664
+ *
1665
+ * @param {unknown} strategy The name of the custom strategy to validate.
1666
+ * Must be a string that starts with "custom-" followed by alphanumeric characters, hyphens, or underscores.
1667
+ * @returns {boolean} Returns true if it is a custom strategy, false otherwise.
1668
+ */
1669
+ export function isCustomStrategy(strategy) {
1670
+ return (typeof strategy === "string" && /^custom-[A-Za-z0-9_-]+$/.test(strategy));
1671
+ }
1672
+ /**
1673
+ * Defines a custom strategy that is executed on the server.
1674
+ *
1675
+ * @see https://paraglidejs.com/strategy#write-your-own-strategy
1676
+ *
1677
+ * @param {string} strategy The name of the custom strategy to define. Must follow the pattern custom-name with alphanumeric characters, hyphens, or underscores.
1678
+ * @param {CustomServerStrategyHandler} handler The handler for the custom strategy, which should implement
1679
+ * the method getLocale.
1680
+ * @returns {void}
1681
+ */
1682
+ export function defineCustomServerStrategy(strategy, handler) {
1683
+ if (!isCustomStrategy(strategy)) {
1684
+ throw new Error(`Invalid custom strategy: "${strategy}". Must be a custom strategy following the pattern custom-name.`);
1685
+ }
1686
+ customServerStrategies.set(strategy, handler);
1687
+ }
1688
+ /**
1689
+ * Defines a custom strategy that is executed on the client.
1690
+ *
1691
+ * @see https://paraglidejs.com/strategy#write-your-own-strategy
1692
+ *
1693
+ * @param {string} strategy The name of the custom strategy to define. Must follow the pattern custom-name with alphanumeric characters, hyphens, or underscores.
1694
+ * @param {CustomClientStrategyHandler} handler The handler for the custom strategy, which should implement the
1695
+ * methods getLocale and setLocale.
1696
+ * @returns {void}
1697
+ */
1698
+ export function defineCustomClientStrategy(strategy, handler) {
1699
+ if (!isCustomStrategy(strategy)) {
1700
+ throw new Error(`Invalid custom strategy: "${strategy}". Must be a custom strategy following the pattern custom-name.`);
1701
+ }
1702
+ customClientStrategies.set(strategy, handler);
1703
+ }
1704
+
1705
+ // ------ TYPES ------
1706
+ export {};
1707
+ /**
1708
+ * A locale that is available in the project.
1709
+ *
1710
+ * @example
1711
+ * setLocale(request.locale as Locale)
1712
+ *
1713
+ * @typedef {typeof locales[number]} Locale
1714
+ */
1715
+ /**
1716
+ * A branded type representing a localized string.
1717
+ *
1718
+ * Message functions return this type instead of \`string\`, enabling TypeScript
1719
+ * to distinguish translated strings from regular strings at compile time.
1720
+ * This allows you to enforce that only properly localized content is used
1721
+ * in your UI components.
1722
+ *
1723
+ * Since \`LocalizedString\` is a branded subtype of \`string\`, it remains fully
1724
+ * backward compatible—you can pass it anywhere a \`string\` is expected.
1725
+ *
1726
+ * @example
1727
+ * // Enforce localized strings in your components
1728
+ * function PageTitle(props: { title: LocalizedString }) {
1729
+ * return <h1>{props.title}</h1>
1730
+ * }
1731
+ *
1732
+ * // ✅ Correct: using a message function
1733
+ * <PageTitle title={m.welcome_title()} />
1734
+ *
1735
+ * // ❌ Type error: raw strings are not LocalizedString
1736
+ * <PageTitle title="Welcome" />
1737
+ *
1738
+ * @example
1739
+ * // LocalizedString is assignable to string (backward compatible)
1740
+ * const localized: LocalizedString = m.greeting()
1741
+ * const str: string = localized // ✅ works fine
1742
+ *
1743
+ * // But string is not assignable to LocalizedString
1744
+ * const raw: LocalizedString = "Hello" // ❌ Type error
1745
+ *
1746
+ * @example
1747
+ * // Catches accidental string concatenation
1748
+ * function showMessage(msg: LocalizedString) { ... }
1749
+ *
1750
+ * showMessage(m.hello()) // ✅
1751
+ * showMessage("Hello " + userName) // ❌ Type error
1752
+ * showMessage(m.hello_user({ name: userName })) // ✅ use params instead
1753
+ *
1754
+ * @typedef {string & { readonly __brand: 'LocalizedString' }} LocalizedString
1755
+ */
1756
+ /**
1757
+ * A single markup option passed to a tag instance.
1758
+ *
1759
+ * @typedef {{
1760
+ * name: string;
1761
+ * value: unknown;
1762
+ * }} MessageMarkupOption
1763
+ */
1764
+ /**
1765
+ * A single static markup attribute attached to a tag instance.
1766
+ *
1767
+ * @typedef {{
1768
+ * name: string;
1769
+ * value: string | true;
1770
+ * }} MessageMarkupAttribute
1771
+ */
1772
+ /**
1773
+ * Record of markup options for a tag instance.
1774
+ *
1775
+ * @typedef {Record<string, unknown>} MessageMarkupOptions
1776
+ */
1777
+ /**
1778
+ * Record of markup attributes for a tag instance.
1779
+ *
1780
+ * @typedef {Record<string, string | true>} MessageMarkupAttributes
1781
+ */
1782
+ /**
1783
+ * Type-level schema for a single markup tag.
1784
+ *
1785
+ * @typedef {{
1786
+ * options: MessageMarkupOptions;
1787
+ * attributes: MessageMarkupAttributes;
1788
+ * children: boolean;
1789
+ * }} MessageMarkupTag
1790
+ */
1791
+ /**
1792
+ * Type-level schema for all markup tags in a message.
1793
+ *
1794
+ * @typedef {Record<string, MessageMarkupTag>} MessageMarkupSchema
1795
+ */
1796
+ /**
1797
+ * Type-only metadata attached to compiled message functions.
1798
+ *
1799
+ * @template Inputs
1800
+ * @template Options
1801
+ * @template {MessageMarkupSchema} [Markup = MessageMarkupSchema]
1802
+ * @typedef {{
1803
+ * readonly __paraglide?: {
1804
+ * inputs: Inputs;
1805
+ * options: Options;
1806
+ * markup: Markup;
1807
+ * };
1808
+ * }} MessageMetadata
1809
+ */
1810
+ /**
1811
+ * A compiled, framework-neutral message part.
1812
+ *
1813
+ * @typedef {{
1814
+ * type: "text";
1815
+ * value: string;
1816
+ * } | {
1817
+ * type: "markup-start";
1818
+ * name: string;
1819
+ * options: MessageMarkupOptions;
1820
+ * attributes: MessageMarkupAttributes;
1821
+ * } | {
1822
+ * type: "markup-end";
1823
+ * name: string;
1824
+ * options: MessageMarkupOptions;
1825
+ * attributes: MessageMarkupAttributes;
1826
+ * } | {
1827
+ * type: "markup-standalone";
1828
+ * name: string;
1829
+ * options: MessageMarkupOptions;
1830
+ * attributes: MessageMarkupAttributes;
1831
+ * }} MessagePart
1832
+ */
1833
+ /**
1834
+ * A message function is a message for a specific locale.
1835
+ *
1836
+ * @example
1837
+ * m.hello({ name: 'world' })
1838
+ *
1839
+ * @typedef {(inputs?: Record<string, never>) => LocalizedString} MessageFunction
1840
+ */
1841
+ /**
1842
+ * A message bundle function that selects the message to be returned.
1843
+ *
1844
+ * Uses `getLocale()` under the hood to determine the locale with an option.
1845
+ *
1846
+ * @template {string} T
1847
+ *
1848
+ * @example
1849
+ * * m.hello({ name: 'world' }, { locale: "en" })
1850
+ *
1851
+ * @typedef {(params: Record<string, never>, options: { locale: T }) => LocalizedString} MessageBundleFunction
1852
+ */