triiiceratops 0.9.5 → 0.9.6
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.
- package/dist/paraglide/messages/_index.d.ts +88 -0
- package/dist/paraglide/messages/_index.js +89 -0
- package/dist/paraglide/messages/annotations_count.d.ts +5 -0
- package/dist/paraglide/messages/annotations_count.js +33 -0
- package/dist/paraglide/messages/attribution.d.ts +3 -0
- package/dist/paraglide/messages/attribution.js +33 -0
- package/dist/paraglide/messages/change_theme_label.d.ts +3 -0
- package/dist/paraglide/messages/change_theme_label.js +33 -0
- package/dist/paraglide/messages/close.d.ts +3 -0
- package/dist/paraglide/messages/close.js +33 -0
- package/dist/paraglide/messages/close_gallery.d.ts +3 -0
- package/dist/paraglide/messages/close_gallery.js +33 -0
- package/dist/paraglide/messages/close_menu.d.ts +3 -0
- package/dist/paraglide/messages/close_menu.js +33 -0
- package/dist/paraglide/messages/close_search.d.ts +3 -0
- package/dist/paraglide/messages/close_search.js +33 -0
- package/dist/paraglide/messages/copied.d.ts +3 -0
- package/dist/paraglide/messages/copied.js +33 -0
- package/dist/paraglide/messages/copy_config.d.ts +3 -0
- package/dist/paraglide/messages/copy_config.js +33 -0
- package/dist/paraglide/messages/demo_header_active_canvas.d.ts +3 -0
- package/dist/paraglide/messages/demo_header_active_canvas.js +33 -0
- package/dist/paraglide/messages/demo_header_external_controls.d.ts +3 -0
- package/dist/paraglide/messages/demo_header_external_controls.js +33 -0
- package/dist/paraglide/messages/docs.d.ts +3 -0
- package/dist/paraglide/messages/docs.js +33 -0
- package/dist/paraglide/messages/enter_full_screen.d.ts +3 -0
- package/dist/paraglide/messages/enter_full_screen.js +33 -0
- package/dist/paraglide/messages/error_prefix.d.ts +3 -0
- package/dist/paraglide/messages/error_prefix.js +33 -0
- package/dist/paraglide/messages/exit_full_screen.d.ts +3 -0
- package/dist/paraglide/messages/exit_full_screen.js +33 -0
- package/dist/paraglide/messages/gallery.d.ts +3 -0
- package/dist/paraglide/messages/gallery.js +33 -0
- package/dist/paraglide/messages/github.d.ts +3 -0
- package/dist/paraglide/messages/github.js +33 -0
- package/dist/paraglide/messages/hello_world.d.ts +3 -0
- package/dist/paraglide/messages/hello_world.js +33 -0
- package/dist/paraglide/messages/hide_all_annotations.d.ts +3 -0
- package/dist/paraglide/messages/hide_all_annotations.js +33 -0
- package/dist/paraglide/messages/hide_annotations.d.ts +3 -0
- package/dist/paraglide/messages/hide_annotations.js +33 -0
- package/dist/paraglide/messages/hide_gallery.d.ts +3 -0
- package/dist/paraglide/messages/hide_gallery.js +33 -0
- package/dist/paraglide/messages/iiif_manifest_label.d.ts +3 -0
- package/dist/paraglide/messages/iiif_manifest_label.js +33 -0
- package/dist/paraglide/messages/image_adjustments.d.ts +3 -0
- package/dist/paraglide/messages/image_adjustments.js +33 -0
- package/dist/paraglide/messages/language_select_label.d.ts +3 -0
- package/dist/paraglide/messages/language_select_label.js +33 -0
- package/dist/paraglide/messages/license.d.ts +3 -0
- package/dist/paraglide/messages/license.js +33 -0
- package/dist/paraglide/messages/load.d.ts +3 -0
- package/dist/paraglide/messages/load.js +33 -0
- package/dist/paraglide/messages/loading.d.ts +3 -0
- package/dist/paraglide/messages/loading.js +33 -0
- package/dist/paraglide/messages/manifest_placeholder.d.ts +3 -0
- package/dist/paraglide/messages/manifest_placeholder.js +33 -0
- package/dist/paraglide/messages/menu.d.ts +3 -0
- package/dist/paraglide/messages/menu.js +33 -0
- package/dist/paraglide/messages/metadata.d.ts +3 -0
- package/dist/paraglide/messages/metadata.js +33 -0
- package/dist/paraglide/messages/metadata_label_fallback.d.ts +3 -0
- package/dist/paraglide/messages/metadata_label_fallback.js +33 -0
- package/dist/paraglide/messages/next_canvas.d.ts +3 -0
- package/dist/paraglide/messages/next_canvas.js +33 -0
- package/dist/paraglide/messages/no_annotations_available.d.ts +3 -0
- package/dist/paraglide/messages/no_annotations_available.js +33 -0
- package/dist/paraglide/messages/no_canvases_loaded.d.ts +3 -0
- package/dist/paraglide/messages/no_canvases_loaded.js +33 -0
- package/dist/paraglide/messages/no_content.d.ts +3 -0
- package/dist/paraglide/messages/no_content.js +33 -0
- package/dist/paraglide/messages/no_image_found.d.ts +3 -0
- package/dist/paraglide/messages/no_image_found.js +33 -0
- package/dist/paraglide/messages/plugins_tooltip.d.ts +3 -0
- package/dist/paraglide/messages/plugins_tooltip.js +33 -0
- package/dist/paraglide/messages/previous_canvas.d.ts +3 -0
- package/dist/paraglide/messages/previous_canvas.js +33 -0
- package/dist/paraglide/messages/search.d.ts +3 -0
- package/dist/paraglide/messages/search.js +33 -0
- package/dist/paraglide/messages/search_panel_close.d.ts +3 -0
- package/dist/paraglide/messages/search_panel_close.js +33 -0
- package/dist/paraglide/messages/search_panel_instruction.d.ts +3 -0
- package/dist/paraglide/messages/search_panel_instruction.js +33 -0
- package/dist/paraglide/messages/search_panel_no_results.d.ts +5 -0
- package/dist/paraglide/messages/search_panel_no_results.js +33 -0
- package/dist/paraglide/messages/search_panel_placeholder.d.ts +3 -0
- package/dist/paraglide/messages/search_panel_placeholder.js +33 -0
- package/dist/paraglide/messages/search_panel_results_count.d.ts +5 -0
- package/dist/paraglide/messages/search_panel_results_count.js +33 -0
- package/dist/paraglide/messages/search_panel_title.d.ts +3 -0
- package/dist/paraglide/messages/search_panel_title.js +33 -0
- package/dist/paraglide/messages/settings_category_configuration.d.ts +3 -0
- package/dist/paraglide/messages/settings_category_configuration.js +33 -0
- package/dist/paraglide/messages/settings_category_general.d.ts +3 -0
- package/dist/paraglide/messages/settings_category_general.js +33 -0
- package/dist/paraglide/messages/settings_label.d.ts +3 -0
- package/dist/paraglide/messages/settings_label.js +33 -0
- package/dist/paraglide/messages/settings_position_bottom.d.ts +3 -0
- package/dist/paraglide/messages/settings_position_bottom.js +33 -0
- package/dist/paraglide/messages/settings_position_floating.d.ts +3 -0
- package/dist/paraglide/messages/settings_position_floating.js +33 -0
- package/dist/paraglide/messages/settings_position_left.d.ts +3 -0
- package/dist/paraglide/messages/settings_position_left.js +33 -0
- package/dist/paraglide/messages/settings_position_right.d.ts +3 -0
- package/dist/paraglide/messages/settings_position_right.js +33 -0
- package/dist/paraglide/messages/settings_position_top.d.ts +3 -0
- package/dist/paraglide/messages/settings_position_top.js +33 -0
- package/dist/paraglide/messages/settings_select_dock_position.d.ts +3 -0
- package/dist/paraglide/messages/settings_select_dock_position.js +33 -0
- package/dist/paraglide/messages/settings_submenu_annotations.d.ts +3 -0
- package/dist/paraglide/messages/settings_submenu_annotations.js +33 -0
- package/dist/paraglide/messages/settings_submenu_gallery.d.ts +3 -0
- package/dist/paraglide/messages/settings_submenu_gallery.js +33 -0
- package/dist/paraglide/messages/settings_submenu_right_menu_items.d.ts +3 -0
- package/dist/paraglide/messages/settings_submenu_right_menu_items.js +33 -0
- package/dist/paraglide/messages/settings_submenu_search.d.ts +3 -0
- package/dist/paraglide/messages/settings_submenu_search.js +33 -0
- package/dist/paraglide/messages/settings_toggle_canvas_nav.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_canvas_nav.js +33 -0
- package/dist/paraglide/messages/settings_toggle_close_button.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_close_button.js +33 -0
- package/dist/paraglide/messages/settings_toggle_draggable.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_draggable.js +33 -0
- package/dist/paraglide/messages/settings_toggle_left_menu.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_left_menu.js +33 -0
- package/dist/paraglide/messages/settings_toggle_open.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_open.js +33 -0
- package/dist/paraglide/messages/settings_toggle_panel_open.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_panel_open.js +33 -0
- package/dist/paraglide/messages/settings_toggle_right_menu.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_right_menu.js +33 -0
- package/dist/paraglide/messages/settings_toggle_show_annotations.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_show_annotations.js +33 -0
- package/dist/paraglide/messages/settings_toggle_show_fullscreen.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_show_fullscreen.js +33 -0
- package/dist/paraglide/messages/settings_toggle_show_gallery.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_show_gallery.js +33 -0
- package/dist/paraglide/messages/settings_toggle_show_info.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_show_info.js +33 -0
- package/dist/paraglide/messages/settings_toggle_show_search.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_show_search.js +33 -0
- package/dist/paraglide/messages/settings_toggle_visible_by_default.d.ts +3 -0
- package/dist/paraglide/messages/settings_toggle_visible_by_default.js +33 -0
- package/dist/paraglide/messages/show_all_annotations.d.ts +3 -0
- package/dist/paraglide/messages/show_all_annotations.js +33 -0
- package/dist/paraglide/messages/show_annotations.d.ts +3 -0
- package/dist/paraglide/messages/show_annotations.js +33 -0
- package/dist/paraglide/messages/show_gallery.d.ts +3 -0
- package/dist/paraglide/messages/show_gallery.js +33 -0
- package/dist/paraglide/messages/theme_menu_title.d.ts +3 -0
- package/dist/paraglide/messages/theme_menu_title.js +33 -0
- package/dist/paraglide/messages/toggle_annotations.d.ts +3 -0
- package/dist/paraglide/messages/toggle_annotations.js +33 -0
- package/dist/paraglide/messages/toggle_metadata.d.ts +3 -0
- package/dist/paraglide/messages/toggle_metadata.js +33 -0
- package/dist/paraglide/messages/toggle_search.d.ts +3 -0
- package/dist/paraglide/messages/toggle_search.js +33 -0
- package/dist/paraglide/messages/try_your_own.d.ts +3 -0
- package/dist/paraglide/messages/try_your_own.js +33 -0
- package/dist/paraglide/messages/viewer_variant_core.d.ts +3 -0
- package/dist/paraglide/messages/viewer_variant_core.js +33 -0
- package/dist/paraglide/messages/viewer_variant_custom_theme.d.ts +3 -0
- package/dist/paraglide/messages/viewer_variant_custom_theme.js +33 -0
- package/dist/paraglide/messages/viewer_variant_full.d.ts +3 -0
- package/dist/paraglide/messages/viewer_variant_full.js +33 -0
- package/dist/paraglide/messages/viewer_variant_svelte.d.ts +3 -0
- package/dist/paraglide/messages/viewer_variant_svelte.js +33 -0
- package/dist/paraglide/messages/viewer_variant_svelte_component_tooltip.d.ts +3 -0
- package/dist/paraglide/messages/viewer_variant_svelte_component_tooltip.js +33 -0
- package/dist/paraglide/messages/viewer_variant_tooltip_core.d.ts +3 -0
- package/dist/paraglide/messages/viewer_variant_tooltip_core.js +33 -0
- package/dist/paraglide/messages/viewer_variant_tooltip_custom_theme.d.ts +3 -0
- package/dist/paraglide/messages/viewer_variant_tooltip_custom_theme.js +33 -0
- package/dist/paraglide/messages/viewer_variant_tooltip_full.d.ts +3 -0
- package/dist/paraglide/messages/viewer_variant_tooltip_full.js +33 -0
- package/dist/paraglide/messages/visible_count.d.ts +5 -0
- package/dist/paraglide/messages/visible_count.js +33 -0
- package/dist/paraglide/messages.d.ts +2 -0
- package/dist/paraglide/messages.js +4 -0
- package/dist/paraglide/registry.d.ts +21 -0
- package/dist/paraglide/registry.js +31 -0
- package/dist/paraglide/runtime.d.ts +583 -0
- package/dist/paraglide/runtime.js +1411 -0
- package/dist/paraglide/server.d.ts +67 -0
- package/dist/paraglide/server.js +175 -0
- package/package.json +2 -2
|
@@ -0,0 +1,1411 @@
|
|
|
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", "de"]);
|
|
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
|
+
* The used URL patterns.
|
|
42
|
+
*
|
|
43
|
+
* @type {Array<{ pattern: string, localized: Array<[Locale, string]> }> }
|
|
44
|
+
*/
|
|
45
|
+
export const urlPatterns = [
|
|
46
|
+
{
|
|
47
|
+
"pattern": ":protocol://:domain(.*)::port?/:path(.*)?",
|
|
48
|
+
"localized": [
|
|
49
|
+
[
|
|
50
|
+
"de",
|
|
51
|
+
":protocol://:domain(.*)::port?/de/:path(.*)?"
|
|
52
|
+
],
|
|
53
|
+
[
|
|
54
|
+
"en",
|
|
55
|
+
":protocol://:domain(.*)::port?/:path(.*)?"
|
|
56
|
+
]
|
|
57
|
+
]
|
|
58
|
+
}
|
|
59
|
+
];
|
|
60
|
+
/**
|
|
61
|
+
* @typedef {{
|
|
62
|
+
* getStore(): {
|
|
63
|
+
* locale?: Locale,
|
|
64
|
+
* origin?: string,
|
|
65
|
+
* messageCalls?: Set<string>
|
|
66
|
+
* } | undefined,
|
|
67
|
+
* run: (store: { locale?: Locale, origin?: string, messageCalls?: Set<string>},
|
|
68
|
+
* cb: any) => any
|
|
69
|
+
* }} ParaglideAsyncLocalStorage
|
|
70
|
+
*/
|
|
71
|
+
/**
|
|
72
|
+
* Server side async local storage that is set by `serverMiddleware()`.
|
|
73
|
+
*
|
|
74
|
+
* The variable is used to retrieve the locale and origin in a server-side
|
|
75
|
+
* rendering context without effecting other requests.
|
|
76
|
+
*
|
|
77
|
+
* @type {ParaglideAsyncLocalStorage | undefined}
|
|
78
|
+
*/
|
|
79
|
+
export let serverAsyncLocalStorage = undefined;
|
|
80
|
+
export const disableAsyncLocalStorage = false;
|
|
81
|
+
export const experimentalMiddlewareLocaleSplitting = false;
|
|
82
|
+
export const isServer = typeof window === 'undefined';
|
|
83
|
+
/**
|
|
84
|
+
* Sets the server side async local storage.
|
|
85
|
+
*
|
|
86
|
+
* The function is needed because the `runtime.js` file
|
|
87
|
+
* must define the `serverAsyncLocalStorage` variable to
|
|
88
|
+
* avoid a circular import between `runtime.js` and
|
|
89
|
+
* `server.js` files.
|
|
90
|
+
*
|
|
91
|
+
* @param {ParaglideAsyncLocalStorage | undefined} value
|
|
92
|
+
*/
|
|
93
|
+
export function overwriteServerAsyncLocalStorage(value) {
|
|
94
|
+
serverAsyncLocalStorage = value;
|
|
95
|
+
}
|
|
96
|
+
const TREE_SHAKE_COOKIE_STRATEGY_USED = true;
|
|
97
|
+
const TREE_SHAKE_URL_STRATEGY_USED = false;
|
|
98
|
+
const TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED = true;
|
|
99
|
+
const TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED = false;
|
|
100
|
+
const TREE_SHAKE_DEFAULT_URL_PATTERN_USED = true;
|
|
101
|
+
const TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED = false;
|
|
102
|
+
|
|
103
|
+
globalThis.__paraglide = {}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* This is a fallback to get started with a custom
|
|
107
|
+
* strategy and avoid type errors.
|
|
108
|
+
*
|
|
109
|
+
* The implementation is overwritten
|
|
110
|
+
* by \`overwriteGetLocale()\` and \`defineSetLocale()\`.
|
|
111
|
+
*
|
|
112
|
+
* @type {Locale|undefined}
|
|
113
|
+
*/
|
|
114
|
+
let _locale;
|
|
115
|
+
let localeInitiallySet = false;
|
|
116
|
+
/**
|
|
117
|
+
* Get the current locale.
|
|
118
|
+
*
|
|
119
|
+
* @example
|
|
120
|
+
* if (getLocale() === 'de') {
|
|
121
|
+
* console.log('Germany 🇩🇪');
|
|
122
|
+
* } else if (getLocale() === 'nl') {
|
|
123
|
+
* console.log('Netherlands 🇳🇱');
|
|
124
|
+
* }
|
|
125
|
+
*
|
|
126
|
+
* @type {() => Locale}
|
|
127
|
+
*/
|
|
128
|
+
export let getLocale = () => {
|
|
129
|
+
/** @type {string | undefined} */
|
|
130
|
+
let locale;
|
|
131
|
+
// if running in a server-side rendering context
|
|
132
|
+
// retrieve the locale from the async local storage
|
|
133
|
+
if (serverAsyncLocalStorage) {
|
|
134
|
+
const locale = serverAsyncLocalStorage?.getStore()?.locale;
|
|
135
|
+
if (locale) {
|
|
136
|
+
return locale;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
for (const strat of strategy) {
|
|
140
|
+
if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
|
|
141
|
+
locale = extractLocaleFromCookie();
|
|
142
|
+
}
|
|
143
|
+
else if (strat === "baseLocale") {
|
|
144
|
+
locale = baseLocale;
|
|
145
|
+
}
|
|
146
|
+
else if (TREE_SHAKE_URL_STRATEGY_USED &&
|
|
147
|
+
strat === "url" &&
|
|
148
|
+
!isServer &&
|
|
149
|
+
typeof window !== "undefined") {
|
|
150
|
+
locale = extractLocaleFromUrl(window.location.href);
|
|
151
|
+
}
|
|
152
|
+
else if (TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED &&
|
|
153
|
+
strat === "globalVariable" &&
|
|
154
|
+
_locale !== undefined) {
|
|
155
|
+
locale = _locale;
|
|
156
|
+
}
|
|
157
|
+
else if (TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED &&
|
|
158
|
+
strat === "preferredLanguage" &&
|
|
159
|
+
!isServer) {
|
|
160
|
+
locale = extractLocaleFromNavigator();
|
|
161
|
+
}
|
|
162
|
+
else if (TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED &&
|
|
163
|
+
strat === "localStorage" &&
|
|
164
|
+
!isServer) {
|
|
165
|
+
locale = localStorage.getItem(localStorageKey) ?? undefined;
|
|
166
|
+
}
|
|
167
|
+
else if (isCustomStrategy(strat) && customClientStrategies.has(strat)) {
|
|
168
|
+
const handler = customClientStrategies.get(strat);
|
|
169
|
+
if (handler) {
|
|
170
|
+
const result = handler.getLocale();
|
|
171
|
+
// Handle both sync and async results - skip async in sync getLocale
|
|
172
|
+
if (result instanceof Promise) {
|
|
173
|
+
// Can't await in sync function, skip async strategies
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
locale = result;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
// check if match, else continue loop
|
|
180
|
+
if (locale !== undefined) {
|
|
181
|
+
const asserted = assertIsLocale(locale);
|
|
182
|
+
if (!localeInitiallySet) {
|
|
183
|
+
_locale = asserted;
|
|
184
|
+
// https://github.com/opral/inlang-paraglide-js/issues/455
|
|
185
|
+
localeInitiallySet = true;
|
|
186
|
+
setLocale(asserted, { reload: false });
|
|
187
|
+
}
|
|
188
|
+
return asserted;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
throw new Error("No locale found. Read the docs https://inlang.com/m/gerre34r/library-inlang-paraglideJs/errors#no-locale-found");
|
|
192
|
+
};
|
|
193
|
+
/**
|
|
194
|
+
* Overwrite the \`getLocale()\` function.
|
|
195
|
+
*
|
|
196
|
+
* Use this function to overwrite how the locale is resolved. For example,
|
|
197
|
+
* you can resolve the locale from the browser's preferred language,
|
|
198
|
+
* a cookie, env variable, or a user's preference.
|
|
199
|
+
*
|
|
200
|
+
* @example
|
|
201
|
+
* overwriteGetLocale(() => {
|
|
202
|
+
* // resolve the locale from a cookie. fallback to the base locale.
|
|
203
|
+
* return Cookies.get('locale') ?? baseLocale
|
|
204
|
+
* }
|
|
205
|
+
*
|
|
206
|
+
* @type {(fn: () => Locale) => void}
|
|
207
|
+
*/
|
|
208
|
+
export const overwriteGetLocale = (fn) => {
|
|
209
|
+
getLocale = fn;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Navigates to the localized URL, or reloads the current page
|
|
214
|
+
*
|
|
215
|
+
* @param {string} [newLocation] The new location
|
|
216
|
+
* @return {undefined}
|
|
217
|
+
*/
|
|
218
|
+
const navigateOrReload = (newLocation) => {
|
|
219
|
+
if (newLocation) {
|
|
220
|
+
// reload the page by navigating to the new url
|
|
221
|
+
window.location.href = newLocation;
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
// reload the page to reflect the new locale
|
|
225
|
+
window.location.reload();
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
/**
|
|
229
|
+
* @typedef {(newLocale: Locale, options?: { reload?: boolean }) => void | Promise<void>} SetLocaleFn
|
|
230
|
+
*/
|
|
231
|
+
/**
|
|
232
|
+
* Set the locale.
|
|
233
|
+
*
|
|
234
|
+
* Set locale reloads the site by default on the client. Reloading
|
|
235
|
+
* can be disabled by passing \`reload: false\` as an option. If
|
|
236
|
+
* reloading is disabled, you need to ensure that the UI is updated
|
|
237
|
+
* to reflect the new locale.
|
|
238
|
+
*
|
|
239
|
+
* If any custom strategy's \`setLocale\` function is async, then this
|
|
240
|
+
* function will become async as well.
|
|
241
|
+
*
|
|
242
|
+
* @example
|
|
243
|
+
* setLocale('en');
|
|
244
|
+
*
|
|
245
|
+
* @example
|
|
246
|
+
* setLocale('en', { reload: false });
|
|
247
|
+
*
|
|
248
|
+
* @type {SetLocaleFn}
|
|
249
|
+
*/
|
|
250
|
+
export let setLocale = (newLocale, options) => {
|
|
251
|
+
const optionsWithDefaults = {
|
|
252
|
+
reload: true,
|
|
253
|
+
...options,
|
|
254
|
+
};
|
|
255
|
+
// locale is already set
|
|
256
|
+
// https://github.com/opral/inlang-paraglide-js/issues/430
|
|
257
|
+
/** @type {Locale | undefined} */
|
|
258
|
+
let currentLocale;
|
|
259
|
+
try {
|
|
260
|
+
currentLocale = getLocale();
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
// do nothing, no locale has been set yet.
|
|
264
|
+
}
|
|
265
|
+
/** @type {Array<Promise<any>>} */
|
|
266
|
+
const customSetLocalePromises = [];
|
|
267
|
+
/** @type {string | undefined} */
|
|
268
|
+
let newLocation = undefined;
|
|
269
|
+
for (const strat of strategy) {
|
|
270
|
+
if (TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED &&
|
|
271
|
+
strat === "globalVariable") {
|
|
272
|
+
// a default for a custom strategy to get started quickly
|
|
273
|
+
// is likely overwritten by `defineSetLocale()`
|
|
274
|
+
_locale = newLocale;
|
|
275
|
+
}
|
|
276
|
+
else if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
|
|
277
|
+
if (isServer ||
|
|
278
|
+
typeof document === "undefined" ||
|
|
279
|
+
typeof window === "undefined") {
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
// set the cookie
|
|
283
|
+
const cookieString = `${cookieName}=${newLocale}; path=/; max-age=${cookieMaxAge}`;
|
|
284
|
+
document.cookie = cookieDomain
|
|
285
|
+
? `${cookieString}; domain=${cookieDomain}`
|
|
286
|
+
: cookieString;
|
|
287
|
+
}
|
|
288
|
+
else if (strat === "baseLocale") {
|
|
289
|
+
// nothing to be set here. baseLocale is only a fallback
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
else if (TREE_SHAKE_URL_STRATEGY_USED &&
|
|
293
|
+
strat === "url" &&
|
|
294
|
+
typeof window !== "undefined") {
|
|
295
|
+
// route to the new url
|
|
296
|
+
//
|
|
297
|
+
// this triggers a page reload but a user rarely
|
|
298
|
+
// switches locales, so this should be fine.
|
|
299
|
+
//
|
|
300
|
+
// if the behavior is not desired, the implementation
|
|
301
|
+
// can be overwritten by `defineSetLocale()` to avoid
|
|
302
|
+
// a full page reload.
|
|
303
|
+
newLocation = localizeUrl(window.location.href, {
|
|
304
|
+
locale: newLocale,
|
|
305
|
+
}).href;
|
|
306
|
+
}
|
|
307
|
+
else if (TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED &&
|
|
308
|
+
strat === "localStorage" &&
|
|
309
|
+
typeof window !== "undefined") {
|
|
310
|
+
// set the localStorage
|
|
311
|
+
localStorage.setItem(localStorageKey, newLocale);
|
|
312
|
+
}
|
|
313
|
+
else if (isCustomStrategy(strat) && customClientStrategies.has(strat)) {
|
|
314
|
+
const handler = customClientStrategies.get(strat);
|
|
315
|
+
if (handler) {
|
|
316
|
+
let result = handler.setLocale(newLocale);
|
|
317
|
+
// Handle async setLocale
|
|
318
|
+
if (result instanceof Promise) {
|
|
319
|
+
result = result.catch((error) => {
|
|
320
|
+
throw new Error(`Custom strategy "${strat}" setLocale failed.`, {
|
|
321
|
+
cause: error,
|
|
322
|
+
});
|
|
323
|
+
});
|
|
324
|
+
customSetLocalePromises.push(result);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
const runReload = () => {
|
|
330
|
+
if (!isServer &&
|
|
331
|
+
optionsWithDefaults.reload &&
|
|
332
|
+
window.location &&
|
|
333
|
+
newLocale !== currentLocale) {
|
|
334
|
+
navigateOrReload(newLocation);
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
if (customSetLocalePromises.length) {
|
|
338
|
+
return Promise.all(customSetLocalePromises).then(() => {
|
|
339
|
+
runReload();
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
runReload();
|
|
343
|
+
return;
|
|
344
|
+
};
|
|
345
|
+
/**
|
|
346
|
+
* Overwrite the \`setLocale()\` function.
|
|
347
|
+
*
|
|
348
|
+
* Use this function to overwrite how the locale is set. For example,
|
|
349
|
+
* modify a cookie, env variable, or a user's preference.
|
|
350
|
+
*
|
|
351
|
+
* @example
|
|
352
|
+
* overwriteSetLocale((newLocale) => {
|
|
353
|
+
* // set the locale in a cookie
|
|
354
|
+
* return Cookies.set('locale', newLocale)
|
|
355
|
+
* });
|
|
356
|
+
*
|
|
357
|
+
* @param {SetLocaleFn} fn
|
|
358
|
+
*/
|
|
359
|
+
export const overwriteSetLocale = (fn) => {
|
|
360
|
+
setLocale = /** @type {SetLocaleFn} */ (fn);
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* The origin of the current URL.
|
|
365
|
+
*
|
|
366
|
+
* Defaults to "http://y.com" in non-browser environments. If this
|
|
367
|
+
* behavior is not desired, the implementation can be overwritten
|
|
368
|
+
* by `overwriteGetUrlOrigin()`.
|
|
369
|
+
*
|
|
370
|
+
* @type {() => string}
|
|
371
|
+
*/
|
|
372
|
+
export let getUrlOrigin = () => {
|
|
373
|
+
if (serverAsyncLocalStorage) {
|
|
374
|
+
return serverAsyncLocalStorage.getStore()?.origin ?? "http://fallback.com";
|
|
375
|
+
}
|
|
376
|
+
else if (typeof window !== "undefined") {
|
|
377
|
+
return window.location.origin;
|
|
378
|
+
}
|
|
379
|
+
return "http://fallback.com";
|
|
380
|
+
};
|
|
381
|
+
/**
|
|
382
|
+
* Overwrite the getUrlOrigin function.
|
|
383
|
+
*
|
|
384
|
+
* Use this function in server environments to
|
|
385
|
+
* define how the URL origin is resolved.
|
|
386
|
+
*
|
|
387
|
+
* @type {(fn: () => string) => void}
|
|
388
|
+
*/
|
|
389
|
+
export let overwriteGetUrlOrigin = (fn) => {
|
|
390
|
+
getUrlOrigin = fn;
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Check if something is an available locale.
|
|
395
|
+
*
|
|
396
|
+
* @example
|
|
397
|
+
* if (isLocale(params.locale)) {
|
|
398
|
+
* setLocale(params.locale);
|
|
399
|
+
* } else {
|
|
400
|
+
* setLocale('en');
|
|
401
|
+
* }
|
|
402
|
+
*
|
|
403
|
+
* @param {any} locale
|
|
404
|
+
* @returns {locale is Locale}
|
|
405
|
+
*/
|
|
406
|
+
export function isLocale(locale) {
|
|
407
|
+
if (typeof locale !== "string")
|
|
408
|
+
return false;
|
|
409
|
+
return !locale
|
|
410
|
+
? false
|
|
411
|
+
: locales.some((item) => item.toLowerCase() === locale.toLowerCase());
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Asserts that the input is a locale.
|
|
416
|
+
*
|
|
417
|
+
* @param {any} input - The input to check.
|
|
418
|
+
* @returns {Locale} The input if it is a locale.
|
|
419
|
+
* @throws {Error} If the input is not a locale.
|
|
420
|
+
*/
|
|
421
|
+
export function assertIsLocale(input) {
|
|
422
|
+
if (typeof input !== "string") {
|
|
423
|
+
throw new Error(`Invalid locale: ${input}. Expected a string.`);
|
|
424
|
+
}
|
|
425
|
+
const lowerInput = input.toLowerCase();
|
|
426
|
+
const matchedLocale = locales.find((item) => item.toLowerCase() === lowerInput);
|
|
427
|
+
if (!matchedLocale) {
|
|
428
|
+
throw new Error(`Invalid locale: ${input}. Expected one of: ${locales.join(", ")}`);
|
|
429
|
+
}
|
|
430
|
+
return matchedLocale;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Extracts a locale from a request.
|
|
435
|
+
*
|
|
436
|
+
* Use the function on the server to extract the locale
|
|
437
|
+
* from a request.
|
|
438
|
+
*
|
|
439
|
+
* The function goes through the strategies in the order
|
|
440
|
+
* they are defined. If a strategy returns an invalid locale,
|
|
441
|
+
* it will fall back to the next strategy.
|
|
442
|
+
*
|
|
443
|
+
* Note: Custom server strategies are not supported in this synchronous version.
|
|
444
|
+
* Use `extractLocaleFromRequestAsync` if you need custom server strategies with async getLocale methods.
|
|
445
|
+
*
|
|
446
|
+
* @example
|
|
447
|
+
* const locale = extractLocaleFromRequest(request);
|
|
448
|
+
*
|
|
449
|
+
* @type {(request: Request) => Locale}
|
|
450
|
+
*/
|
|
451
|
+
export const extractLocaleFromRequest = (request) => {
|
|
452
|
+
/** @type {string|undefined} */
|
|
453
|
+
let locale;
|
|
454
|
+
for (const strat of strategy) {
|
|
455
|
+
if (TREE_SHAKE_COOKIE_STRATEGY_USED && strat === "cookie") {
|
|
456
|
+
locale = request.headers
|
|
457
|
+
.get("cookie")
|
|
458
|
+
?.split("; ")
|
|
459
|
+
.find((c) => c.startsWith(cookieName + "="))
|
|
460
|
+
?.split("=")[1];
|
|
461
|
+
}
|
|
462
|
+
else if (TREE_SHAKE_URL_STRATEGY_USED && strat === "url") {
|
|
463
|
+
locale = extractLocaleFromUrl(request.url);
|
|
464
|
+
}
|
|
465
|
+
else if (TREE_SHAKE_PREFERRED_LANGUAGE_STRATEGY_USED &&
|
|
466
|
+
strat === "preferredLanguage") {
|
|
467
|
+
locale = extractLocaleFromHeader(request);
|
|
468
|
+
}
|
|
469
|
+
else if (strat === "globalVariable") {
|
|
470
|
+
locale = _locale;
|
|
471
|
+
}
|
|
472
|
+
else if (strat === "baseLocale") {
|
|
473
|
+
return baseLocale;
|
|
474
|
+
}
|
|
475
|
+
else if (strat === "localStorage") {
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
else if (isCustomStrategy(strat)) {
|
|
479
|
+
// Custom strategies are not supported in sync version
|
|
480
|
+
// Use extractLocaleFromRequestAsync for custom server strategies
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
if (locale !== undefined) {
|
|
484
|
+
if (!isLocale(locale)) {
|
|
485
|
+
locale = undefined;
|
|
486
|
+
}
|
|
487
|
+
else {
|
|
488
|
+
return assertIsLocale(locale);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
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");
|
|
493
|
+
};
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* Asynchronously extracts a locale from a request.
|
|
497
|
+
*
|
|
498
|
+
* This function supports async custom server strategies, unlike the synchronous
|
|
499
|
+
* `extractLocaleFromRequest`. Use this function when you have custom server strategies
|
|
500
|
+
* that need to perform asynchronous operations (like database calls) in their getLocale method.
|
|
501
|
+
*
|
|
502
|
+
* The function first processes any custom server strategies asynchronously, then falls back
|
|
503
|
+
* to the synchronous `extractLocaleFromRequest` for all other strategies.
|
|
504
|
+
*
|
|
505
|
+
* @see {@link https://github.com/opral/inlang-paraglide-js/issues/527#issuecomment-2978151022}
|
|
506
|
+
*
|
|
507
|
+
* @example
|
|
508
|
+
* // Basic usage
|
|
509
|
+
* const locale = await extractLocaleFromRequestAsync(request);
|
|
510
|
+
*
|
|
511
|
+
* @example
|
|
512
|
+
* // With custom async server strategy
|
|
513
|
+
* defineCustomServerStrategy("custom-database", {
|
|
514
|
+
* getLocale: async (request) => {
|
|
515
|
+
* const userId = extractUserIdFromRequest(request);
|
|
516
|
+
* return await getUserLocaleFromDatabase(userId);
|
|
517
|
+
* }
|
|
518
|
+
* });
|
|
519
|
+
*
|
|
520
|
+
* const locale = await extractLocaleFromRequestAsync(request);
|
|
521
|
+
*
|
|
522
|
+
* @type {(request: Request) => Promise<Locale>}
|
|
523
|
+
*/
|
|
524
|
+
export const extractLocaleFromRequestAsync = async (request) => {
|
|
525
|
+
/** @type {string|undefined} */
|
|
526
|
+
let locale;
|
|
527
|
+
// Process custom strategies first, in order
|
|
528
|
+
for (const strat of strategy) {
|
|
529
|
+
if (isCustomStrategy(strat) && customServerStrategies.has(strat)) {
|
|
530
|
+
const handler = customServerStrategies.get(strat);
|
|
531
|
+
if (handler) {
|
|
532
|
+
/** @type {string|undefined} */
|
|
533
|
+
locale = await handler.getLocale(request);
|
|
534
|
+
}
|
|
535
|
+
// If we got a valid locale from this custom strategy, use it
|
|
536
|
+
if (locale !== undefined && isLocale(locale)) {
|
|
537
|
+
return assertIsLocale(locale);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
// If no custom strategy provided a valid locale, fall back to sync version
|
|
542
|
+
locale = extractLocaleFromRequest(request);
|
|
543
|
+
return assertIsLocale(locale);
|
|
544
|
+
};
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* Extracts a cookie from the document.
|
|
548
|
+
*
|
|
549
|
+
* Will return undefined if the document is not available or if the cookie is not set.
|
|
550
|
+
* The `document` object is not available in server-side rendering, so this function should not be called in that context.
|
|
551
|
+
*
|
|
552
|
+
* @returns {string | undefined}
|
|
553
|
+
*/
|
|
554
|
+
export function extractLocaleFromCookie() {
|
|
555
|
+
if (typeof document === "undefined" || !document.cookie) {
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
const match = document.cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));
|
|
559
|
+
const locale = match?.[2];
|
|
560
|
+
if (isLocale(locale)) {
|
|
561
|
+
return locale;
|
|
562
|
+
}
|
|
563
|
+
return undefined;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Extracts a locale from the accept-language header.
|
|
568
|
+
*
|
|
569
|
+
* Use the function on the server to extract the locale
|
|
570
|
+
* from the accept-language header that is sent by the client.
|
|
571
|
+
*
|
|
572
|
+
* @example
|
|
573
|
+
* const locale = extractLocaleFromHeader(request);
|
|
574
|
+
*
|
|
575
|
+
* @type {(request: Request) => Locale}
|
|
576
|
+
* @param {Request} request - The request object to extract the locale from.
|
|
577
|
+
* @returns {string|undefined} The negotiated preferred language.
|
|
578
|
+
*/
|
|
579
|
+
export function extractLocaleFromHeader(request) {
|
|
580
|
+
const acceptLanguageHeader = request.headers.get("accept-language");
|
|
581
|
+
if (acceptLanguageHeader) {
|
|
582
|
+
// Parse language preferences with their q-values and base language codes
|
|
583
|
+
const languages = acceptLanguageHeader
|
|
584
|
+
.split(",")
|
|
585
|
+
.map((lang) => {
|
|
586
|
+
const [tag, q = "1"] = lang.trim().split(";q=");
|
|
587
|
+
// Get both the full tag and base language code
|
|
588
|
+
const baseTag = tag?.split("-")[0]?.toLowerCase();
|
|
589
|
+
return {
|
|
590
|
+
fullTag: tag?.toLowerCase(),
|
|
591
|
+
baseTag,
|
|
592
|
+
q: Number(q),
|
|
593
|
+
};
|
|
594
|
+
})
|
|
595
|
+
.sort((a, b) => b.q - a.q);
|
|
596
|
+
for (const lang of languages) {
|
|
597
|
+
if (isLocale(lang.fullTag)) {
|
|
598
|
+
return lang.fullTag;
|
|
599
|
+
}
|
|
600
|
+
else if (isLocale(lang.baseTag)) {
|
|
601
|
+
return lang.baseTag;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
return undefined;
|
|
605
|
+
}
|
|
606
|
+
return undefined;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* Negotiates a preferred language from navigator.languages.
|
|
611
|
+
*
|
|
612
|
+
* Use the function on the client to extract the locale
|
|
613
|
+
* from the navigator.languages array.
|
|
614
|
+
*
|
|
615
|
+
* @example
|
|
616
|
+
* const locale = extractLocaleFromNavigator();
|
|
617
|
+
*
|
|
618
|
+
* @type {() => Locale | undefined}
|
|
619
|
+
* @returns {string | undefined}
|
|
620
|
+
*/
|
|
621
|
+
export function extractLocaleFromNavigator() {
|
|
622
|
+
if (!navigator?.languages?.length) {
|
|
623
|
+
return undefined;
|
|
624
|
+
}
|
|
625
|
+
const languages = navigator.languages.map((lang) => ({
|
|
626
|
+
fullTag: lang.toLowerCase(),
|
|
627
|
+
baseTag: lang.split("-")[0]?.toLowerCase(),
|
|
628
|
+
}));
|
|
629
|
+
for (const lang of languages) {
|
|
630
|
+
if (isLocale(lang.fullTag)) {
|
|
631
|
+
return lang.fullTag;
|
|
632
|
+
}
|
|
633
|
+
else if (isLocale(lang.baseTag)) {
|
|
634
|
+
return lang.baseTag;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
return undefined;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* If extractLocaleFromUrl is called many times on the same page and the URL
|
|
642
|
+
* hasn't changed, we don't need to recompute it every time which can get expensive.
|
|
643
|
+
* We might use a LRU cache if needed, but for now storing only the last result is enough.
|
|
644
|
+
* https://github.com/opral/monorepo/pull/3575#discussion_r2066731243
|
|
645
|
+
*/
|
|
646
|
+
/** @type {string|undefined} */
|
|
647
|
+
let cachedUrl;
|
|
648
|
+
/** @type {Locale|undefined} */
|
|
649
|
+
let cachedLocale;
|
|
650
|
+
/**
|
|
651
|
+
* Extracts the locale from a given URL using native URLPattern.
|
|
652
|
+
*
|
|
653
|
+
* @param {URL|string} url - The full URL from which to extract the locale.
|
|
654
|
+
* @returns {Locale|undefined} The extracted locale, or undefined if no locale is found.
|
|
655
|
+
*/
|
|
656
|
+
export function extractLocaleFromUrl(url) {
|
|
657
|
+
const urlString = typeof url === "string" ? url : url.href;
|
|
658
|
+
if (cachedUrl === urlString) {
|
|
659
|
+
return cachedLocale;
|
|
660
|
+
}
|
|
661
|
+
let result;
|
|
662
|
+
if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
|
|
663
|
+
result = defaultUrlPatternExtractLocale(url);
|
|
664
|
+
}
|
|
665
|
+
else {
|
|
666
|
+
const urlObj = typeof url === "string" ? new URL(url) : url;
|
|
667
|
+
// Iterate over URL patterns
|
|
668
|
+
for (const element of urlPatterns) {
|
|
669
|
+
for (const [locale, localizedPattern] of element.localized) {
|
|
670
|
+
const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
|
|
671
|
+
if (!match) {
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
// Check if the locale is valid
|
|
675
|
+
if (assertIsLocale(locale)) {
|
|
676
|
+
result = locale;
|
|
677
|
+
break;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
if (result)
|
|
681
|
+
break;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
cachedUrl = urlString;
|
|
685
|
+
cachedLocale = result;
|
|
686
|
+
return result;
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* https://github.com/opral/inlang-paraglide-js/issues/381
|
|
690
|
+
*
|
|
691
|
+
* @param {URL|string} url - The full URL from which to extract the locale.
|
|
692
|
+
* @returns {Locale|undefined} The extracted locale, or undefined if no locale is found.
|
|
693
|
+
*/
|
|
694
|
+
function defaultUrlPatternExtractLocale(url) {
|
|
695
|
+
const urlObj = new URL(url, "http://dummy.com");
|
|
696
|
+
const pathSegments = urlObj.pathname.split("/").filter(Boolean);
|
|
697
|
+
if (pathSegments.length > 0) {
|
|
698
|
+
const potentialLocale = pathSegments[0];
|
|
699
|
+
if (isLocale(potentialLocale)) {
|
|
700
|
+
return potentialLocale;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
// everything else has to be the base locale
|
|
704
|
+
return baseLocale;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Lower-level URL localization function, primarily used in server contexts.
|
|
709
|
+
*
|
|
710
|
+
* This function is designed for server-side usage where you need precise control
|
|
711
|
+
* over URL localization, such as in middleware or request handlers. It works with
|
|
712
|
+
* URL objects and always returns absolute URLs.
|
|
713
|
+
*
|
|
714
|
+
* For client-side UI components, use `localizeHref()` instead, which provides
|
|
715
|
+
* a more convenient API with relative paths and automatic locale detection.
|
|
716
|
+
*
|
|
717
|
+
* @example
|
|
718
|
+
* ```typescript
|
|
719
|
+
* // Server middleware example
|
|
720
|
+
* app.use((req, res, next) => {
|
|
721
|
+
* const url = new URL(req.url, `${req.protocol}://${req.headers.host}`);
|
|
722
|
+
* const localized = localizeUrl(url, { locale: "de" });
|
|
723
|
+
*
|
|
724
|
+
* if (localized.href !== url.href) {
|
|
725
|
+
* return res.redirect(localized.href);
|
|
726
|
+
* }
|
|
727
|
+
* next();
|
|
728
|
+
* });
|
|
729
|
+
* ```
|
|
730
|
+
*
|
|
731
|
+
* @example
|
|
732
|
+
* ```typescript
|
|
733
|
+
* // Using with URL patterns
|
|
734
|
+
* const url = new URL("https://example.com/about");
|
|
735
|
+
* localizeUrl(url, { locale: "de" });
|
|
736
|
+
* // => URL("https://example.com/de/about")
|
|
737
|
+
*
|
|
738
|
+
* // Using with domain-based localization
|
|
739
|
+
* const url = new URL("https://example.com/store");
|
|
740
|
+
* localizeUrl(url, { locale: "de" });
|
|
741
|
+
* // => URL("https://de.example.com/store")
|
|
742
|
+
* ```
|
|
743
|
+
*
|
|
744
|
+
* @param {string | URL} url - The URL to localize. If string, must be absolute.
|
|
745
|
+
* @param {Object} [options] - Options for localization
|
|
746
|
+
* @param {string} [options.locale] - Target locale. If not provided, uses getLocale()
|
|
747
|
+
* @returns {URL} The localized URL, always absolute
|
|
748
|
+
*/
|
|
749
|
+
export function localizeUrl(url, options) {
|
|
750
|
+
if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
|
|
751
|
+
return localizeUrlDefaultPattern(url, options);
|
|
752
|
+
}
|
|
753
|
+
const targetLocale = options?.locale ?? getLocale();
|
|
754
|
+
const urlObj = typeof url === "string" ? new URL(url) : url;
|
|
755
|
+
// Iterate over URL patterns
|
|
756
|
+
for (const element of urlPatterns) {
|
|
757
|
+
// match localized patterns
|
|
758
|
+
for (const [, localizedPattern] of element.localized) {
|
|
759
|
+
const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
|
|
760
|
+
if (!match) {
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
const targetPattern = element.localized.find(([locale]) => locale === targetLocale)?.[1];
|
|
764
|
+
if (!targetPattern) {
|
|
765
|
+
continue;
|
|
766
|
+
}
|
|
767
|
+
const localizedUrl = fillPattern(targetPattern, aggregateGroups(match), urlObj.origin);
|
|
768
|
+
return fillMissingUrlParts(localizedUrl, match);
|
|
769
|
+
}
|
|
770
|
+
const unlocalizedMatch = new URLPattern(element.pattern, urlObj.href).exec(urlObj.href);
|
|
771
|
+
if (unlocalizedMatch) {
|
|
772
|
+
const targetPattern = element.localized.find(([locale]) => locale === targetLocale)?.[1];
|
|
773
|
+
if (targetPattern) {
|
|
774
|
+
const localizedUrl = fillPattern(targetPattern, aggregateGroups(unlocalizedMatch), urlObj.origin);
|
|
775
|
+
return fillMissingUrlParts(localizedUrl, unlocalizedMatch);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
// If no match found, return the original URL
|
|
780
|
+
return urlObj;
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* https://github.com/opral/inlang-paraglide-js/issues/381
|
|
784
|
+
*
|
|
785
|
+
* @param {string | URL} url
|
|
786
|
+
* @param {Object} [options]
|
|
787
|
+
* @param {string} [options.locale]
|
|
788
|
+
* @returns {URL}
|
|
789
|
+
*/
|
|
790
|
+
function localizeUrlDefaultPattern(url, options) {
|
|
791
|
+
const urlObj = typeof url === "string" ? new URL(url, getUrlOrigin()) : new URL(url);
|
|
792
|
+
const locale = options?.locale ?? getLocale();
|
|
793
|
+
const currentLocale = extractLocaleFromUrl(urlObj);
|
|
794
|
+
// If current locale matches target locale, no change needed
|
|
795
|
+
if (currentLocale === locale) {
|
|
796
|
+
return urlObj;
|
|
797
|
+
}
|
|
798
|
+
const pathSegments = urlObj.pathname.split("/").filter(Boolean);
|
|
799
|
+
// If current path starts with a locale, remove it
|
|
800
|
+
if (pathSegments.length > 0 && isLocale(pathSegments[0])) {
|
|
801
|
+
pathSegments.shift();
|
|
802
|
+
}
|
|
803
|
+
// For base locale, don't add prefix
|
|
804
|
+
if (locale === baseLocale) {
|
|
805
|
+
urlObj.pathname = "/" + pathSegments.join("/");
|
|
806
|
+
}
|
|
807
|
+
else {
|
|
808
|
+
// For other locales, add prefix
|
|
809
|
+
urlObj.pathname = "/" + locale + "/" + pathSegments.join("/");
|
|
810
|
+
}
|
|
811
|
+
return urlObj;
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* Low-level URL de-localization function, primarily used in server contexts.
|
|
815
|
+
*
|
|
816
|
+
* This function is designed for server-side usage where you need precise control
|
|
817
|
+
* over URL de-localization, such as in middleware or request handlers. It works with
|
|
818
|
+
* URL objects and always returns absolute URLs.
|
|
819
|
+
*
|
|
820
|
+
* For client-side UI components, use `deLocalizeHref()` instead, which provides
|
|
821
|
+
* a more convenient API with relative paths.
|
|
822
|
+
*
|
|
823
|
+
* @example
|
|
824
|
+
* ```typescript
|
|
825
|
+
* // Server middleware example
|
|
826
|
+
* app.use((req, res, next) => {
|
|
827
|
+
* const url = new URL(req.url, `${req.protocol}://${req.headers.host}`);
|
|
828
|
+
* const baseUrl = deLocalizeUrl(url);
|
|
829
|
+
*
|
|
830
|
+
* // Store the base URL for later use
|
|
831
|
+
* req.baseUrl = baseUrl;
|
|
832
|
+
* next();
|
|
833
|
+
* });
|
|
834
|
+
* ```
|
|
835
|
+
*
|
|
836
|
+
* @example
|
|
837
|
+
* ```typescript
|
|
838
|
+
* // Using with URL patterns
|
|
839
|
+
* const url = new URL("https://example.com/de/about");
|
|
840
|
+
* deLocalizeUrl(url); // => URL("https://example.com/about")
|
|
841
|
+
*
|
|
842
|
+
* // Using with domain-based localization
|
|
843
|
+
* const url = new URL("https://de.example.com/store");
|
|
844
|
+
* deLocalizeUrl(url); // => URL("https://example.com/store")
|
|
845
|
+
* ```
|
|
846
|
+
*
|
|
847
|
+
* @param {string | URL} url - The URL to de-localize. If string, must be absolute.
|
|
848
|
+
* @returns {URL} The de-localized URL, always absolute
|
|
849
|
+
*/
|
|
850
|
+
export function deLocalizeUrl(url) {
|
|
851
|
+
if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
|
|
852
|
+
return deLocalizeUrlDefaultPattern(url);
|
|
853
|
+
}
|
|
854
|
+
const urlObj = typeof url === "string" ? new URL(url) : url;
|
|
855
|
+
// Iterate over URL patterns
|
|
856
|
+
for (const element of urlPatterns) {
|
|
857
|
+
// Iterate over localized versions
|
|
858
|
+
for (const [, localizedPattern] of element.localized) {
|
|
859
|
+
const match = new URLPattern(localizedPattern, urlObj.href).exec(urlObj.href);
|
|
860
|
+
if (match) {
|
|
861
|
+
// Convert localized URL back to the base pattern
|
|
862
|
+
const groups = aggregateGroups(match);
|
|
863
|
+
const baseUrl = fillPattern(element.pattern, groups, urlObj.origin);
|
|
864
|
+
return fillMissingUrlParts(baseUrl, match);
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
// match unlocalized pattern
|
|
868
|
+
const unlocalizedMatch = new URLPattern(element.pattern, urlObj.href).exec(urlObj.href);
|
|
869
|
+
if (unlocalizedMatch) {
|
|
870
|
+
const baseUrl = fillPattern(element.pattern, aggregateGroups(unlocalizedMatch), urlObj.origin);
|
|
871
|
+
return fillMissingUrlParts(baseUrl, unlocalizedMatch);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
// no match found return the original url
|
|
875
|
+
return urlObj;
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* De-localizes a URL using the default pattern (/:locale/*)
|
|
879
|
+
* @param {string|URL} url
|
|
880
|
+
* @returns {URL}
|
|
881
|
+
*/
|
|
882
|
+
function deLocalizeUrlDefaultPattern(url) {
|
|
883
|
+
const urlObj = typeof url === "string" ? new URL(url, getUrlOrigin()) : new URL(url);
|
|
884
|
+
const pathSegments = urlObj.pathname.split("/").filter(Boolean);
|
|
885
|
+
// If first segment is a locale, remove it
|
|
886
|
+
if (pathSegments.length > 0 && isLocale(pathSegments[0])) {
|
|
887
|
+
urlObj.pathname = "/" + pathSegments.slice(1).join("/");
|
|
888
|
+
}
|
|
889
|
+
return urlObj;
|
|
890
|
+
}
|
|
891
|
+
/**
|
|
892
|
+
* Takes matches of implicit wildcards in the UrlPattern (when a part is missing
|
|
893
|
+
* it is equal to '*') and adds them back to the result of fillPattern.
|
|
894
|
+
*
|
|
895
|
+
* At least protocol and hostname are required to create a valid URL inside fillPattern.
|
|
896
|
+
*
|
|
897
|
+
* @param {URL} url
|
|
898
|
+
* @param {any} match
|
|
899
|
+
* @returns {URL}
|
|
900
|
+
*/
|
|
901
|
+
function fillMissingUrlParts(url, match) {
|
|
902
|
+
if (match.protocol.groups["0"]) {
|
|
903
|
+
url.protocol = match.protocol.groups["0"] ?? "";
|
|
904
|
+
}
|
|
905
|
+
if (match.hostname.groups["0"]) {
|
|
906
|
+
url.hostname = match.hostname.groups["0"] ?? "";
|
|
907
|
+
}
|
|
908
|
+
if (match.username.groups["0"]) {
|
|
909
|
+
url.username = match.username.groups["0"] ?? "";
|
|
910
|
+
}
|
|
911
|
+
if (match.password.groups["0"]) {
|
|
912
|
+
url.password = match.password.groups["0"] ?? "";
|
|
913
|
+
}
|
|
914
|
+
if (match.port.groups["0"]) {
|
|
915
|
+
url.port = match.port.groups["0"] ?? "";
|
|
916
|
+
}
|
|
917
|
+
if (match.pathname.groups["0"]) {
|
|
918
|
+
url.pathname = match.pathname.groups["0"] ?? "";
|
|
919
|
+
}
|
|
920
|
+
if (match.search.groups["0"]) {
|
|
921
|
+
url.search = match.search.groups["0"] ?? "";
|
|
922
|
+
}
|
|
923
|
+
if (match.hash.groups["0"]) {
|
|
924
|
+
url.hash = match.hash.groups["0"] ?? "";
|
|
925
|
+
}
|
|
926
|
+
return url;
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Fills a URL pattern with values for named groups, supporting all URLPattern-style modifiers.
|
|
930
|
+
*
|
|
931
|
+
* This function will eventually be replaced by https://github.com/whatwg/urlpattern/issues/73
|
|
932
|
+
*
|
|
933
|
+
* Matches:
|
|
934
|
+
* - :name -> Simple
|
|
935
|
+
* - :name? -> Optional
|
|
936
|
+
* - :name+ -> One or more
|
|
937
|
+
* - :name* -> Zero or more
|
|
938
|
+
* - :name(...) -> Regex group
|
|
939
|
+
* - {text} -> Group delimiter
|
|
940
|
+
* - {text}? -> Optional group delimiter
|
|
941
|
+
*
|
|
942
|
+
* If the value is `null`, the segment is removed.
|
|
943
|
+
*
|
|
944
|
+
* @param {string} pattern - The URL pattern containing named groups.
|
|
945
|
+
* @param {Record<string, string | null | undefined>} values - Object of values for named groups.
|
|
946
|
+
* @param {string} origin - Base URL to use for URL construction.
|
|
947
|
+
* @returns {URL} - The constructed URL with named groups filled.
|
|
948
|
+
*/
|
|
949
|
+
function fillPattern(pattern, values, origin) {
|
|
950
|
+
// Pre-process the pattern to handle explicit port numbers
|
|
951
|
+
// This detects patterns like "http://localhost:5173" and protects the port number
|
|
952
|
+
// from being interpreted as a parameter
|
|
953
|
+
let processedPattern = pattern.replace(/(https?:\/\/[^:/]+):(\d+)(\/|$)/g, (_, protocol, port, slash) => {
|
|
954
|
+
// Replace ":5173" with "#PORT-5173#" to protect it from parameter replacement
|
|
955
|
+
return `${protocol}#PORT-${port}#${slash}`;
|
|
956
|
+
});
|
|
957
|
+
// First, handle group delimiters with curly braces
|
|
958
|
+
let processedGroupDelimiters = processedPattern.replace(/\{([^{}]*)\}([?+*]?)/g, (_, content, modifier) => {
|
|
959
|
+
// For optional group delimiters
|
|
960
|
+
if (modifier === "?") {
|
|
961
|
+
// For optional groups, we'll include the content
|
|
962
|
+
return content;
|
|
963
|
+
}
|
|
964
|
+
// For non-optional group delimiters, always include the content
|
|
965
|
+
return content;
|
|
966
|
+
});
|
|
967
|
+
// Then handle named groups
|
|
968
|
+
let filled = processedGroupDelimiters.replace(/(\/?):([a-zA-Z0-9_]+)(\([^)]*\))?([?+*]?)/g, (_, slash, name, __, modifier) => {
|
|
969
|
+
const value = values[name];
|
|
970
|
+
if (value === null) {
|
|
971
|
+
// If value is null, remove the entire segment including the preceding slash
|
|
972
|
+
return "";
|
|
973
|
+
}
|
|
974
|
+
if (modifier === "?") {
|
|
975
|
+
// Optional segment
|
|
976
|
+
return value !== undefined ? `${slash}${value}` : "";
|
|
977
|
+
}
|
|
978
|
+
if (modifier === "+" || modifier === "*") {
|
|
979
|
+
// Repeatable segments
|
|
980
|
+
if (value === undefined && modifier === "+") {
|
|
981
|
+
throw new Error(`Missing value for "${name}" (one or more required)`);
|
|
982
|
+
}
|
|
983
|
+
return value ? `${slash}${value}` : "";
|
|
984
|
+
}
|
|
985
|
+
// Simple named group (no modifier)
|
|
986
|
+
if (value === undefined) {
|
|
987
|
+
throw new Error(`Missing value for "${name}"`);
|
|
988
|
+
}
|
|
989
|
+
return `${slash}${value}`;
|
|
990
|
+
});
|
|
991
|
+
// Restore port numbers
|
|
992
|
+
filled = filled.replace(/#PORT-(\d+)#/g, ":$1");
|
|
993
|
+
return new URL(filled, origin);
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Aggregates named groups from various parts of the URLPattern match result.
|
|
997
|
+
*
|
|
998
|
+
*
|
|
999
|
+
* @type {(match: any) => Record<string, string | null | undefined>}
|
|
1000
|
+
*/
|
|
1001
|
+
export function aggregateGroups(match) {
|
|
1002
|
+
return {
|
|
1003
|
+
...match.hash.groups,
|
|
1004
|
+
...match.hostname.groups,
|
|
1005
|
+
...match.password.groups,
|
|
1006
|
+
...match.pathname.groups,
|
|
1007
|
+
...match.port.groups,
|
|
1008
|
+
...match.protocol.groups,
|
|
1009
|
+
...match.search.groups,
|
|
1010
|
+
...match.username.groups,
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
/**
|
|
1015
|
+
* @typedef {object} ShouldRedirectServerInput
|
|
1016
|
+
* @property {Request} request
|
|
1017
|
+
* @property {string | URL} [url]
|
|
1018
|
+
* @property {ReturnType<typeof assertIsLocale>} [locale]
|
|
1019
|
+
*
|
|
1020
|
+
* @typedef {object} ShouldRedirectClientInput
|
|
1021
|
+
* @property {undefined} [request]
|
|
1022
|
+
* @property {string | URL} [url]
|
|
1023
|
+
* @property {ReturnType<typeof assertIsLocale>} [locale]
|
|
1024
|
+
*
|
|
1025
|
+
* @typedef {ShouldRedirectServerInput | ShouldRedirectClientInput} ShouldRedirectInput
|
|
1026
|
+
*
|
|
1027
|
+
* @typedef {object} ShouldRedirectResult
|
|
1028
|
+
* @property {boolean} shouldRedirect - Indicates whether the consumer should perform a redirect.
|
|
1029
|
+
* @property {ReturnType<typeof assertIsLocale>} locale - Locale resolved using the configured strategies.
|
|
1030
|
+
* @property {URL | undefined} redirectUrl - Destination URL when a redirect is required.
|
|
1031
|
+
*/
|
|
1032
|
+
/**
|
|
1033
|
+
* Determines whether a redirect is required to align the current URL with the active locale.
|
|
1034
|
+
*
|
|
1035
|
+
* This helper mirrors the logic that powers `paraglideMiddleware`, but works in both server
|
|
1036
|
+
* and client environments. It evaluates the configured strategies in order, computes the
|
|
1037
|
+
* canonical localized URL, and reports when the current URL does not match.
|
|
1038
|
+
*
|
|
1039
|
+
* When called in the browser without arguments, the current `window.location.href` is used.
|
|
1040
|
+
*
|
|
1041
|
+
* @example
|
|
1042
|
+
* // Client side usage (e.g. TanStack Router beforeLoad hook)
|
|
1043
|
+
* async function beforeLoad({ location }) {
|
|
1044
|
+
* const decision = await shouldRedirect({ url: location.href });
|
|
1045
|
+
*
|
|
1046
|
+
* if (decision.shouldRedirect) {
|
|
1047
|
+
* throw redirect({ to: decision.redirectUrl.href });
|
|
1048
|
+
* }
|
|
1049
|
+
* }
|
|
1050
|
+
*
|
|
1051
|
+
* @example
|
|
1052
|
+
* // Server side usage with a Request
|
|
1053
|
+
* export async function handle(request) {
|
|
1054
|
+
* const decision = await shouldRedirect({ request });
|
|
1055
|
+
*
|
|
1056
|
+
* if (decision.shouldRedirect) {
|
|
1057
|
+
* return Response.redirect(decision.redirectUrl, 307);
|
|
1058
|
+
* }
|
|
1059
|
+
*
|
|
1060
|
+
* return render(request, decision.locale);
|
|
1061
|
+
* }
|
|
1062
|
+
*
|
|
1063
|
+
* @param {ShouldRedirectInput} [input]
|
|
1064
|
+
* @returns {Promise<ShouldRedirectResult>}
|
|
1065
|
+
*/
|
|
1066
|
+
export async function shouldRedirect(input = {}) {
|
|
1067
|
+
const locale = /** @type {ReturnType<typeof assertIsLocale>} */ (await resolveLocale(input));
|
|
1068
|
+
if (!strategy.includes("url")) {
|
|
1069
|
+
return { shouldRedirect: false, locale, redirectUrl: undefined };
|
|
1070
|
+
}
|
|
1071
|
+
const currentUrl = resolveUrl(input);
|
|
1072
|
+
const localizedUrl = localizeUrl(currentUrl.href, { locale });
|
|
1073
|
+
const shouldRedirectToLocalizedUrl = normalizeUrl(localizedUrl.href) !== normalizeUrl(currentUrl.href);
|
|
1074
|
+
return {
|
|
1075
|
+
shouldRedirect: shouldRedirectToLocalizedUrl,
|
|
1076
|
+
locale,
|
|
1077
|
+
redirectUrl: shouldRedirectToLocalizedUrl ? localizedUrl : undefined,
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
/**
|
|
1081
|
+
* Resolves the locale either from the provided input or by using the configured strategies.
|
|
1082
|
+
*
|
|
1083
|
+
* @param {ShouldRedirectInput} input
|
|
1084
|
+
* @returns {Promise<ReturnType<typeof assertIsLocale>>}
|
|
1085
|
+
*/
|
|
1086
|
+
async function resolveLocale(input) {
|
|
1087
|
+
if (input.locale) {
|
|
1088
|
+
return assertIsLocale(input.locale);
|
|
1089
|
+
}
|
|
1090
|
+
if (input.request) {
|
|
1091
|
+
return extractLocaleFromRequestAsync(input.request);
|
|
1092
|
+
}
|
|
1093
|
+
return getLocale();
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Resolves the current URL from the provided input or runtime context.
|
|
1097
|
+
*
|
|
1098
|
+
* @param {ShouldRedirectInput} input
|
|
1099
|
+
* @returns {URL}
|
|
1100
|
+
*/
|
|
1101
|
+
function resolveUrl(input) {
|
|
1102
|
+
if (input.request) {
|
|
1103
|
+
return new URL(input.request.url);
|
|
1104
|
+
}
|
|
1105
|
+
if (input.url instanceof URL) {
|
|
1106
|
+
return new URL(input.url.href);
|
|
1107
|
+
}
|
|
1108
|
+
if (typeof input.url === "string") {
|
|
1109
|
+
return new URL(input.url, getUrlOrigin());
|
|
1110
|
+
}
|
|
1111
|
+
if (typeof window !== "undefined" && window?.location?.href) {
|
|
1112
|
+
return new URL(window.location.href);
|
|
1113
|
+
}
|
|
1114
|
+
throw new Error("shouldRedirect() requires either a request, an absolute URL, or must run in a browser environment.");
|
|
1115
|
+
}
|
|
1116
|
+
/**
|
|
1117
|
+
* Normalize url for comparison by stripping the trailing slash.
|
|
1118
|
+
*
|
|
1119
|
+
* @param {string} url
|
|
1120
|
+
* @returns {string}
|
|
1121
|
+
*/
|
|
1122
|
+
function normalizeUrl(url) {
|
|
1123
|
+
const urlObj = new URL(url);
|
|
1124
|
+
urlObj.pathname = urlObj.pathname.replace(/\/$/, "");
|
|
1125
|
+
return urlObj.href;
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
/**
|
|
1129
|
+
* High-level URL localization function optimized for client-side UI usage.
|
|
1130
|
+
*
|
|
1131
|
+
* This is a convenience wrapper around `localizeUrl()` that provides features
|
|
1132
|
+
* needed in UI:
|
|
1133
|
+
*
|
|
1134
|
+
* - Accepts relative paths (e.g., "/about")
|
|
1135
|
+
* - Returns relative paths when possible
|
|
1136
|
+
* - Automatically detects current locale if not specified
|
|
1137
|
+
* - Handles string input/output instead of URL objects
|
|
1138
|
+
*
|
|
1139
|
+
* @example
|
|
1140
|
+
* ```typescript
|
|
1141
|
+
* // In a React/Vue/Svelte component
|
|
1142
|
+
* const NavLink = ({ href }) => {
|
|
1143
|
+
* // Automatically uses current locale, keeps path relative
|
|
1144
|
+
* return <a href={localizeHref(href)}>...</a>;
|
|
1145
|
+
* };
|
|
1146
|
+
*
|
|
1147
|
+
* // Examples:
|
|
1148
|
+
* localizeHref("/about")
|
|
1149
|
+
* // => "/de/about" (if current locale is "de")
|
|
1150
|
+
* localizeHref("/store", { locale: "fr" })
|
|
1151
|
+
* // => "/fr/store" (explicit locale)
|
|
1152
|
+
*
|
|
1153
|
+
* // Cross-origin links remain absolute
|
|
1154
|
+
* localizeHref("https://other-site.com/about")
|
|
1155
|
+
* // => "https://other-site.com/de/about"
|
|
1156
|
+
* ```
|
|
1157
|
+
*
|
|
1158
|
+
* For server-side URL localization (e.g., in middleware), use `localizeUrl()`
|
|
1159
|
+
* which provides more precise control over URL handling.
|
|
1160
|
+
*
|
|
1161
|
+
* @param {string} href - The href to localize (can be relative or absolute)
|
|
1162
|
+
* @param {Object} [options] - Options for localization
|
|
1163
|
+
* @param {string} [options.locale] - Target locale. If not provided, uses `getLocale()`
|
|
1164
|
+
* @returns {string} The localized href, relative if input was relative
|
|
1165
|
+
*/
|
|
1166
|
+
export function localizeHref(href, options) {
|
|
1167
|
+
const currentLocale = getLocale();
|
|
1168
|
+
const locale = options?.locale ?? currentLocale;
|
|
1169
|
+
const url = new URL(href, getUrlOrigin());
|
|
1170
|
+
const localized = localizeUrl(url, { locale });
|
|
1171
|
+
// if the origin is identical and the href is relative,
|
|
1172
|
+
// return the relative path
|
|
1173
|
+
if (href.startsWith("/") && url.origin === localized.origin) {
|
|
1174
|
+
// check for cross origin localization in which case an absolute URL must be returned.
|
|
1175
|
+
if (locale !== currentLocale) {
|
|
1176
|
+
const localizedCurrentLocale = localizeUrl(url, {
|
|
1177
|
+
locale: currentLocale,
|
|
1178
|
+
});
|
|
1179
|
+
if (localizedCurrentLocale.origin !== localized.origin) {
|
|
1180
|
+
return localized.href;
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
return localized.pathname + localized.search + localized.hash;
|
|
1184
|
+
}
|
|
1185
|
+
return localized.href;
|
|
1186
|
+
}
|
|
1187
|
+
/**
|
|
1188
|
+
* High-level URL de-localization function optimized for client-side UI usage.
|
|
1189
|
+
*
|
|
1190
|
+
* This is a convenience wrapper around `deLocalizeUrl()` that provides features
|
|
1191
|
+
* needed in the UI:
|
|
1192
|
+
*
|
|
1193
|
+
* - Accepts relative paths (e.g., "/de/about")
|
|
1194
|
+
* - Returns relative paths when possible
|
|
1195
|
+
* - Handles string input/output instead of URL objects
|
|
1196
|
+
*
|
|
1197
|
+
* @example
|
|
1198
|
+
* ```typescript
|
|
1199
|
+
* // In a React/Vue/Svelte component
|
|
1200
|
+
* const LocaleSwitcher = ({ href }) => {
|
|
1201
|
+
* // Remove locale prefix before switching
|
|
1202
|
+
* const baseHref = deLocalizeHref(href);
|
|
1203
|
+
* return locales.map(locale =>
|
|
1204
|
+
* <a href={localizeHref(baseHref, { locale })}>
|
|
1205
|
+
* Switch to {locale}
|
|
1206
|
+
* </a>
|
|
1207
|
+
* );
|
|
1208
|
+
* };
|
|
1209
|
+
*
|
|
1210
|
+
* // Examples:
|
|
1211
|
+
* deLocalizeHref("/de/about") // => "/about"
|
|
1212
|
+
* deLocalizeHref("/fr/store") // => "/store"
|
|
1213
|
+
*
|
|
1214
|
+
* // Cross-origin links remain absolute
|
|
1215
|
+
* deLocalizeHref("https://example.com/de/about")
|
|
1216
|
+
* // => "https://example.com/about"
|
|
1217
|
+
* ```
|
|
1218
|
+
*
|
|
1219
|
+
* For server-side URL de-localization (e.g., in middleware), use `deLocalizeUrl()`
|
|
1220
|
+
* which provides more precise control over URL handling.
|
|
1221
|
+
*
|
|
1222
|
+
* @param {string} href - The href to de-localize (can be relative or absolute)
|
|
1223
|
+
* @returns {string} The de-localized href, relative if input was relative
|
|
1224
|
+
* @see deLocalizeUrl - For low-level URL de-localization in server contexts
|
|
1225
|
+
*/
|
|
1226
|
+
export function deLocalizeHref(href) {
|
|
1227
|
+
const url = new URL(href, getUrlOrigin());
|
|
1228
|
+
const deLocalized = deLocalizeUrl(url);
|
|
1229
|
+
// If the origin is identical and the href is relative,
|
|
1230
|
+
// return the relative path instead of the full URL.
|
|
1231
|
+
if (href.startsWith("/") && url.origin === deLocalized.origin) {
|
|
1232
|
+
return deLocalized.pathname + deLocalized.search + deLocalized.hash;
|
|
1233
|
+
}
|
|
1234
|
+
return deLocalized.href;
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
/**
|
|
1238
|
+
* @param {string} safeModuleId
|
|
1239
|
+
* @param {Locale} locale
|
|
1240
|
+
*/
|
|
1241
|
+
export function trackMessageCall(safeModuleId, locale) {
|
|
1242
|
+
if (isServer === false)
|
|
1243
|
+
return;
|
|
1244
|
+
const store = serverAsyncLocalStorage?.getStore();
|
|
1245
|
+
if (store) {
|
|
1246
|
+
store.messageCalls?.add(`${safeModuleId}:${locale}`);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
/**
|
|
1251
|
+
* Generates a list of localized URLs for all provided URLs.
|
|
1252
|
+
*
|
|
1253
|
+
* This is useful for SSG (Static Site Generation) and sitemap generation.
|
|
1254
|
+
* NextJS and other frameworks use this function for SSG.
|
|
1255
|
+
*
|
|
1256
|
+
* @example
|
|
1257
|
+
* ```typescript
|
|
1258
|
+
* const urls = generateStaticLocalizedUrls([
|
|
1259
|
+
* "https://example.com/about",
|
|
1260
|
+
* "https://example.com/blog",
|
|
1261
|
+
* ]);
|
|
1262
|
+
* urls[0].href // => "https://example.com/about"
|
|
1263
|
+
* urls[1].href // => "https://example.com/blog"
|
|
1264
|
+
* urls[2].href // => "https://example.com/de/about"
|
|
1265
|
+
* urls[3].href // => "https://example.com/de/blog"
|
|
1266
|
+
* ...
|
|
1267
|
+
* ```
|
|
1268
|
+
*
|
|
1269
|
+
* @param {(string | URL)[]} urls - List of URLs to generate localized versions for. Can be absolute URLs or paths.
|
|
1270
|
+
* @returns {URL[]} List of localized URLs as URL objects
|
|
1271
|
+
*/
|
|
1272
|
+
export function generateStaticLocalizedUrls(urls) {
|
|
1273
|
+
const localizedUrls = new Set();
|
|
1274
|
+
// For default URL pattern, we can optimize the generation
|
|
1275
|
+
if (TREE_SHAKE_DEFAULT_URL_PATTERN_USED) {
|
|
1276
|
+
for (const urlInput of urls) {
|
|
1277
|
+
const url = urlInput instanceof URL
|
|
1278
|
+
? urlInput
|
|
1279
|
+
: new URL(urlInput, "http://localhost");
|
|
1280
|
+
// Base locale doesn't get a prefix
|
|
1281
|
+
localizedUrls.add(url);
|
|
1282
|
+
// Other locales get their code as prefix
|
|
1283
|
+
for (const locale of locales) {
|
|
1284
|
+
if (locale !== baseLocale) {
|
|
1285
|
+
const localizedPath = `/${locale}${url.pathname}${url.search}${url.hash}`;
|
|
1286
|
+
const localizedUrl = new URL(localizedPath, url.origin);
|
|
1287
|
+
localizedUrls.add(localizedUrl);
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
return Array.from(localizedUrls);
|
|
1292
|
+
}
|
|
1293
|
+
// For custom URL patterns, we need to use localizeUrl for each URL and locale
|
|
1294
|
+
for (const urlInput of urls) {
|
|
1295
|
+
const url = urlInput instanceof URL
|
|
1296
|
+
? urlInput
|
|
1297
|
+
: new URL(urlInput, "http://localhost");
|
|
1298
|
+
// Try each URL pattern to find one that matches
|
|
1299
|
+
let patternFound = false;
|
|
1300
|
+
for (const pattern of urlPatterns) {
|
|
1301
|
+
try {
|
|
1302
|
+
// Try to match the unlocalized pattern
|
|
1303
|
+
const unlocalizedMatch = new URLPattern(pattern.pattern, url.href).exec(url.href);
|
|
1304
|
+
if (!unlocalizedMatch)
|
|
1305
|
+
continue;
|
|
1306
|
+
patternFound = true;
|
|
1307
|
+
// Track unique localized URLs to avoid duplicates when patterns are the same
|
|
1308
|
+
const seenUrls = new Set();
|
|
1309
|
+
// Generate localized URL for each locale
|
|
1310
|
+
for (const [locale] of pattern.localized) {
|
|
1311
|
+
try {
|
|
1312
|
+
const localizedUrl = localizeUrl(url, { locale });
|
|
1313
|
+
const urlString = localizedUrl.href;
|
|
1314
|
+
// Only add if we haven't seen this exact URL before
|
|
1315
|
+
if (!seenUrls.has(urlString)) {
|
|
1316
|
+
seenUrls.add(urlString);
|
|
1317
|
+
localizedUrls.add(localizedUrl);
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
catch {
|
|
1321
|
+
// Skip if localization fails for this locale
|
|
1322
|
+
continue;
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
break;
|
|
1326
|
+
}
|
|
1327
|
+
catch {
|
|
1328
|
+
// Skip if pattern matching fails
|
|
1329
|
+
continue;
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
// If no pattern matched, use the URL as is
|
|
1333
|
+
if (!patternFound) {
|
|
1334
|
+
localizedUrls.add(url);
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
return Array.from(localizedUrls);
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
/**
|
|
1341
|
+
* @typedef {"cookie" | "baseLocale" | "globalVariable" | "url" | "preferredLanguage" | "localStorage"} BuiltInStrategy
|
|
1342
|
+
*/
|
|
1343
|
+
/**
|
|
1344
|
+
* @typedef {`custom_${string}`} CustomStrategy
|
|
1345
|
+
*/
|
|
1346
|
+
/**
|
|
1347
|
+
* @typedef {BuiltInStrategy | CustomStrategy} Strategy
|
|
1348
|
+
*/
|
|
1349
|
+
/**
|
|
1350
|
+
* @typedef {Array<Strategy>} Strategies
|
|
1351
|
+
*/
|
|
1352
|
+
/**
|
|
1353
|
+
* @typedef {{ getLocale: (request?: Request) => Promise<string | undefined> | (string | undefined) }} CustomServerStrategyHandler
|
|
1354
|
+
*/
|
|
1355
|
+
/**
|
|
1356
|
+
* @typedef {{ getLocale: () => Promise<string|undefined> | (string | undefined), setLocale: (locale: string) => Promise<void> | void }} CustomClientStrategyHandler
|
|
1357
|
+
*/
|
|
1358
|
+
/** @type {Map<string, CustomServerStrategyHandler>} */
|
|
1359
|
+
export const customServerStrategies = new Map();
|
|
1360
|
+
/** @type {Map<string, CustomClientStrategyHandler>} */
|
|
1361
|
+
export const customClientStrategies = new Map();
|
|
1362
|
+
/**
|
|
1363
|
+
* Checks if the given strategy is a custom strategy.
|
|
1364
|
+
*
|
|
1365
|
+
* @param {any} strategy The name of the custom strategy to validate.
|
|
1366
|
+
* Must be a string that starts with "custom-" followed by alphanumeric characters, hyphens, or underscores.
|
|
1367
|
+
* @returns {boolean} Returns true if it is a custom strategy, false otherwise.
|
|
1368
|
+
*/
|
|
1369
|
+
export function isCustomStrategy(strategy) {
|
|
1370
|
+
return (typeof strategy === "string" && /^custom-[A-Za-z0-9_-]+$/.test(strategy));
|
|
1371
|
+
}
|
|
1372
|
+
/**
|
|
1373
|
+
* Defines a custom strategy that is executed on the server.
|
|
1374
|
+
*
|
|
1375
|
+
* @param {any} strategy The name of the custom strategy to define. Must follow the pattern custom-name with alphanumeric characters, hyphens, or underscores.
|
|
1376
|
+
* @param {CustomServerStrategyHandler} handler The handler for the custom strategy, which should implement
|
|
1377
|
+
* the method getLocale.
|
|
1378
|
+
* @returns {void}
|
|
1379
|
+
*/
|
|
1380
|
+
export function defineCustomServerStrategy(strategy, handler) {
|
|
1381
|
+
if (!isCustomStrategy(strategy)) {
|
|
1382
|
+
throw new Error(`Invalid custom strategy: "${strategy}". Must be a custom strategy following the pattern custom-name.`);
|
|
1383
|
+
}
|
|
1384
|
+
customServerStrategies.set(strategy, handler);
|
|
1385
|
+
}
|
|
1386
|
+
/**
|
|
1387
|
+
* Defines a custom strategy that is executed on the client.
|
|
1388
|
+
*
|
|
1389
|
+
* @param {any} strategy The name of the custom strategy to define. Must follow the pattern custom-name with alphanumeric characters, hyphens, or underscores.
|
|
1390
|
+
* @param {CustomClientStrategyHandler} handler The handler for the custom strategy, which should implement the
|
|
1391
|
+
* methods getLocale and setLocale.
|
|
1392
|
+
* @returns {void}
|
|
1393
|
+
*/
|
|
1394
|
+
export function defineCustomClientStrategy(strategy, handler) {
|
|
1395
|
+
if (!isCustomStrategy(strategy)) {
|
|
1396
|
+
throw new Error(`Invalid custom strategy: "${strategy}". Must be a custom strategy following the pattern custom-name.`);
|
|
1397
|
+
}
|
|
1398
|
+
customClientStrategies.set(strategy, handler);
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
// ------ TYPES ------
|
|
1402
|
+
|
|
1403
|
+
/**
|
|
1404
|
+
* A locale that is available in the project.
|
|
1405
|
+
*
|
|
1406
|
+
* @example
|
|
1407
|
+
* setLocale(request.locale as Locale)
|
|
1408
|
+
*
|
|
1409
|
+
* @typedef {(typeof locales)[number]} Locale
|
|
1410
|
+
*/
|
|
1411
|
+
|