@bleedingdev/modern-js-plugin-i18n 3.2.0-ultramodern.2 → 3.2.0-ultramodern.23

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 (85) hide show
  1. package/dist/cjs/cli/index.js +22 -0
  2. package/dist/cjs/runtime/I18nLink.js +4 -12
  3. package/dist/cjs/runtime/context.js +32 -5
  4. package/dist/cjs/runtime/hooks.js +8 -5
  5. package/dist/cjs/runtime/i18n/backend/defaults.js +1 -1
  6. package/dist/cjs/runtime/i18n/backend/middleware.node.js +4 -4
  7. package/dist/cjs/runtime/i18n/instance.js +4 -2
  8. package/dist/cjs/runtime/index.js +7 -6
  9. package/dist/cjs/runtime/routerAdapter.js +163 -0
  10. package/dist/cjs/runtime/utils.js +63 -94
  11. package/dist/cjs/server/index.js +64 -8
  12. package/dist/cjs/shared/localisedUrls.js +237 -0
  13. package/dist/esm/cli/index.mjs +22 -0
  14. package/dist/esm/runtime/I18nLink.mjs +4 -12
  15. package/dist/esm/runtime/context.mjs +34 -7
  16. package/dist/esm/runtime/hooks.mjs +9 -6
  17. package/dist/esm/runtime/i18n/backend/defaults.mjs +1 -1
  18. package/dist/esm/runtime/i18n/backend/middleware.node.mjs +3 -3
  19. package/dist/esm/runtime/i18n/instance.mjs +4 -2
  20. package/dist/esm/runtime/index.mjs +7 -6
  21. package/dist/esm/runtime/routerAdapter.mjs +129 -0
  22. package/dist/esm/runtime/utils.mjs +11 -30
  23. package/dist/esm/server/index.mjs +57 -7
  24. package/dist/esm/shared/localisedUrls.mjs +191 -0
  25. package/dist/esm-node/cli/index.mjs +22 -0
  26. package/dist/esm-node/runtime/I18nLink.mjs +4 -12
  27. package/dist/esm-node/runtime/context.mjs +34 -7
  28. package/dist/esm-node/runtime/hooks.mjs +9 -6
  29. package/dist/esm-node/runtime/i18n/backend/defaults.mjs +1 -1
  30. package/dist/esm-node/runtime/i18n/backend/middleware.node.mjs +3 -3
  31. package/dist/esm-node/runtime/i18n/instance.mjs +4 -2
  32. package/dist/esm-node/runtime/index.mjs +7 -6
  33. package/dist/esm-node/runtime/routerAdapter.mjs +130 -0
  34. package/dist/esm-node/runtime/utils.mjs +11 -30
  35. package/dist/esm-node/server/index.mjs +57 -7
  36. package/dist/esm-node/shared/localisedUrls.mjs +192 -0
  37. package/dist/types/cli/index.d.ts +21 -0
  38. package/dist/types/runtime/I18nLink.d.ts +23 -0
  39. package/dist/types/runtime/context.d.ts +41 -0
  40. package/dist/types/runtime/hooks.d.ts +30 -0
  41. package/dist/types/runtime/i18n/backend/config.d.ts +2 -0
  42. package/dist/types/runtime/i18n/backend/defaults.d.ts +13 -0
  43. package/dist/types/runtime/i18n/backend/defaults.node.d.ts +8 -0
  44. package/dist/types/runtime/i18n/backend/index.d.ts +3 -0
  45. package/dist/types/runtime/i18n/backend/middleware.common.d.ts +14 -0
  46. package/dist/types/runtime/i18n/backend/middleware.d.ts +12 -0
  47. package/dist/types/runtime/i18n/backend/middleware.node.d.ts +13 -0
  48. package/dist/types/runtime/i18n/backend/sdk-backend.d.ts +53 -0
  49. package/dist/types/runtime/i18n/backend/sdk-event.d.ts +9 -0
  50. package/dist/types/runtime/i18n/detection/config.d.ts +11 -0
  51. package/dist/types/runtime/i18n/detection/index.d.ts +50 -0
  52. package/dist/types/runtime/i18n/detection/middleware.d.ts +24 -0
  53. package/dist/types/runtime/i18n/detection/middleware.node.d.ts +17 -0
  54. package/dist/types/runtime/i18n/index.d.ts +3 -0
  55. package/dist/types/runtime/i18n/instance.d.ts +96 -0
  56. package/dist/types/runtime/i18n/utils.d.ts +29 -0
  57. package/dist/types/runtime/index.d.ts +21 -0
  58. package/dist/types/runtime/routerAdapter.d.ts +26 -0
  59. package/dist/types/runtime/types.d.ts +15 -0
  60. package/dist/types/runtime/utils.d.ts +28 -0
  61. package/dist/types/server/index.d.ts +14 -0
  62. package/dist/types/shared/deepMerge.d.ts +1 -0
  63. package/dist/types/shared/detection.d.ts +11 -0
  64. package/dist/types/shared/localisedUrls.d.ts +13 -0
  65. package/dist/types/shared/type.d.ts +168 -0
  66. package/dist/types/shared/utils.d.ts +5 -0
  67. package/package.json +15 -15
  68. package/rstest.config.mts +39 -0
  69. package/src/cli/index.ts +43 -1
  70. package/src/runtime/I18nLink.tsx +10 -16
  71. package/src/runtime/context.tsx +45 -7
  72. package/src/runtime/hooks.ts +13 -4
  73. package/src/runtime/i18n/backend/defaults.ts +3 -1
  74. package/src/runtime/i18n/backend/middleware.node.ts +1 -1
  75. package/src/runtime/i18n/instance.ts +14 -5
  76. package/src/runtime/index.tsx +10 -2
  77. package/src/runtime/routerAdapter.tsx +333 -0
  78. package/src/runtime/utils.ts +22 -34
  79. package/src/server/index.ts +135 -10
  80. package/src/shared/localisedUrls.ts +393 -0
  81. package/src/shared/type.ts +12 -0
  82. package/tests/localisedUrls.test.ts +278 -0
  83. package/tests/routerAdapter.test.tsx +278 -0
  84. package/dist/esm/rslib-runtime.mjs +0 -18
  85. package/dist/esm-node/rslib-runtime.mjs +0 -19
@@ -17,8 +17,8 @@ import "./types.mjs";
17
17
  const i18nPlugin = (options)=>({
18
18
  name: '@modern-js/plugin-i18n',
19
19
  setup: (api)=>{
20
- const { entryName, i18nInstance: userI18nInstance, initOptions, localeDetection, backend, htmlLangAttr = false } = options;
21
- const { localePathRedirect = false, i18nextDetector = true, languages = [], fallbackLanguage = 'en', detection, ignoreRedirectRoutes } = localeDetection || {};
20
+ const { entryName, i18nInstance: userI18nInstance, initOptions, localeDetection, backend, htmlLangAttr = false, reactI18next = true } = options;
21
+ const { localePathRedirect = false, i18nextDetector = true, languages = [], fallbackLanguage = 'en', detection, ignoreRedirectRoutes, localisedUrls } = localeDetection || {};
22
22
  const { enabled: backendEnabled = false } = backend || {};
23
23
  let latestI18nInstance;
24
24
  let I18nextProvider;
@@ -27,8 +27,8 @@ const i18nPlugin = (options)=>({
27
27
  const { i18n: otherConfig } = api.getRuntimeConfig();
28
28
  const { initOptions: otherInitOptions } = otherConfig || {};
29
29
  const userInitOptions = merge(otherInitOptions || {}, initOptions || {});
30
- const initReactI18next = await getInitReactI18next();
31
- I18nextProvider = await getI18nextProvider();
30
+ const initReactI18next = reactI18next ? await getInitReactI18next() : null;
31
+ I18nextProvider = reactI18next ? await getI18nextProvider() : null;
32
32
  if (initReactI18next) i18nInstance.use(initReactI18next);
33
33
  const pathname = getPathname(context);
34
34
  if (i18nextDetector) useI18nextLanguageDetector(i18nInstance);
@@ -89,14 +89,15 @@ const i18nPlugin = (options)=>({
89
89
  ]);
90
90
  useSdkResourcesLoader(i18nInstance, setForceUpdate);
91
91
  useLanguageSync(i18nInstance, localePathRedirect, languages, runtimeContextRef, prevLangRef, setLang);
92
- useClientSideRedirect(i18nInstance, localePathRedirect, languages, fallbackLanguage, ignoreRedirectRoutes);
93
- const contextValue = useMemo(()=>createContextValue(lang, i18nInstance, entryName, languages, localePathRedirect, ignoreRedirectRoutes, setLang), [
92
+ useClientSideRedirect(i18nInstance, localePathRedirect, languages, fallbackLanguage, ignoreRedirectRoutes, localisedUrls);
93
+ const contextValue = useMemo(()=>createContextValue(lang, i18nInstance, entryName, languages, localePathRedirect, ignoreRedirectRoutes, localisedUrls, setLang), [
94
94
  lang,
95
95
  i18nInstance,
96
96
  entryName,
97
97
  languages,
98
98
  localePathRedirect,
99
99
  ignoreRedirectRoutes,
100
+ localisedUrls,
100
101
  forceUpdate
101
102
  ]);
102
103
  const appContent = /*#__PURE__*/ jsxs(Fragment, {
@@ -0,0 +1,129 @@
1
+ import { RuntimeContext, isBrowser } from "@modern-js/runtime";
2
+ import { InternalRuntimeContext } from "@modern-js/runtime/context";
3
+ import { Link as router_Link, useInRouterContext, useLocation, useNavigate, useParams } from "@modern-js/runtime/router";
4
+ import { useCallback, useContext, useEffect, useState } from "react";
5
+ const normalizeUrlPart = (value, prefix)=>{
6
+ if ('string' != typeof value || !value) return '';
7
+ return value.startsWith(prefix) ? value : `${prefix}${value}`;
8
+ };
9
+ const normalizeLocation = (location)=>{
10
+ if (!location || 'object' != typeof location) return null;
11
+ const locationValue = location;
12
+ if ('string' != typeof locationValue.pathname) return null;
13
+ return {
14
+ pathname: locationValue.pathname,
15
+ search: normalizeUrlPart('string' == typeof locationValue.search ? locationValue.search : locationValue.searchStr, '?'),
16
+ hash: normalizeUrlPart(locationValue.hash, '#')
17
+ };
18
+ };
19
+ const getWindowLocation = ()=>{
20
+ if (!isBrowser()) return null;
21
+ return {
22
+ pathname: window.location.pathname,
23
+ search: window.location.search,
24
+ hash: window.location.hash
25
+ };
26
+ };
27
+ const getRouterFramework = (runtimeContext, internalContext, inReactRouter)=>{
28
+ const framework = internalContext.routerFramework || internalContext.routerRuntime?.framework || runtimeContext.routerFramework;
29
+ if (framework) return framework;
30
+ if (internalContext.router?.useRouter || runtimeContext.router?.useRouter) return 'tanstack';
31
+ if (internalContext.router?.useLocation || internalContext.router?.useHref || runtimeContext.router?.useLocation || runtimeContext.router?.useHref) return 'react-router';
32
+ if (inReactRouter) return 'react-router';
33
+ };
34
+ const getRouterInstance = (internalContext, contextRouter)=>{
35
+ if (contextRouter) return contextRouter;
36
+ const router = internalContext.routerInstance || internalContext.routerRuntime?.instance;
37
+ if (!router || 'object' != typeof router) return null;
38
+ return router;
39
+ };
40
+ const getRouterStateLocation = (internalContext, contextRouter)=>{
41
+ const router = getRouterInstance(internalContext, contextRouter);
42
+ return normalizeLocation(router?.stores?.location?.get?.()) || normalizeLocation(router?.state?.location);
43
+ };
44
+ const getRouterParams = (internalContext, contextRouter)=>{
45
+ const router = getRouterInstance(internalContext, contextRouter);
46
+ const matches = router?.stores?.matches?.get?.() || router?.state?.matches;
47
+ if (!Array.isArray(matches)) return {};
48
+ return matches.reduce((params, match)=>{
49
+ if (match?.params) Object.assign(params, match.params);
50
+ return params;
51
+ }, {});
52
+ };
53
+ const useI18nRouterAdapter = ()=>{
54
+ const runtimeContext = useContext(RuntimeContext);
55
+ const internalContext = useContext(InternalRuntimeContext);
56
+ const inReactRouter = useInRouterContext();
57
+ const reactRouterNavigate = inReactRouter ? useNavigate() : null;
58
+ const reactRouterLocation = inReactRouter ? useLocation() : null;
59
+ const reactRouterParams = inReactRouter ? useParams() : {};
60
+ const framework = getRouterFramework(runtimeContext, internalContext, inReactRouter);
61
+ const contextUseRouter = inReactRouter || 'tanstack' !== framework ? void 0 : internalContext.router?.useRouter || runtimeContext.router?.useRouter;
62
+ const contextRouter = contextUseRouter ? contextUseRouter({
63
+ warn: false
64
+ }) : null;
65
+ const [, setRouterVersion] = useState(0);
66
+ const hasRouter = 'tanstack' === framework || 'react-router' === framework || Boolean(reactRouterNavigate);
67
+ useEffect(()=>{
68
+ if ('tanstack' !== framework) return;
69
+ const router = getRouterInstance(internalContext, contextRouter);
70
+ if (!router) return;
71
+ const update = ()=>setRouterVersion((version)=>version + 1);
72
+ const unsubscribers = [];
73
+ if ('function' == typeof router.stores?.location?.subscribe) {
74
+ const unsubscribe = router.stores.location.subscribe(update);
75
+ if ('function' == typeof unsubscribe) unsubscribers.push(unsubscribe);
76
+ }
77
+ if ('function' == typeof router.subscribe) for (const eventType of [
78
+ 'onBeforeNavigate',
79
+ 'onBeforeLoad'
80
+ ]){
81
+ const unsubscribe = router.subscribe(eventType, update);
82
+ if ('function' == typeof unsubscribe) unsubscribers.push(unsubscribe);
83
+ }
84
+ return ()=>{
85
+ for (const unsubscribe of unsubscribers)unsubscribe();
86
+ };
87
+ }, [
88
+ contextRouter,
89
+ framework,
90
+ internalContext
91
+ ]);
92
+ const navigate = useCallback((href, options)=>{
93
+ const router = getRouterInstance(internalContext, contextRouter);
94
+ const activeFramework = getRouterFramework(runtimeContext, internalContext, inReactRouter);
95
+ if ('tanstack' === activeFramework) {
96
+ if ('function' == typeof router?.navigate) return router.navigate({
97
+ to: href,
98
+ replace: options?.replace,
99
+ ...options?.state === void 0 ? {} : {
100
+ state: options.state
101
+ }
102
+ });
103
+ throw new Error('TanStack router instance is not available.');
104
+ }
105
+ if (reactRouterNavigate) return reactRouterNavigate(href, options);
106
+ if ('react-router' === activeFramework) {
107
+ if ('function' == typeof router?.navigate) return router.navigate(href, options);
108
+ throw new Error('React Router instance is not available.');
109
+ }
110
+ }, [
111
+ contextRouter,
112
+ internalContext,
113
+ inReactRouter,
114
+ reactRouterNavigate,
115
+ runtimeContext
116
+ ]);
117
+ const location = (reactRouterLocation ? normalizeLocation(reactRouterLocation) : getRouterStateLocation(internalContext, contextRouter)) || getWindowLocation();
118
+ const params = inReactRouter ? reactRouterParams : getRouterParams(internalContext, contextRouter);
119
+ const Link = 'tanstack' === framework ? internalContext.router?.Link || runtimeContext.router?.Link || null : 'react-router' === framework || inReactRouter ? router_Link : null;
120
+ return {
121
+ framework,
122
+ hasRouter,
123
+ location,
124
+ navigate: hasRouter ? navigate : null,
125
+ Link,
126
+ params
127
+ };
128
+ };
129
+ export { useI18nRouterAdapter };
@@ -1,12 +1,6 @@
1
1
  import { isBrowser } from "@modern-js/runtime";
2
2
  import { getGlobalBasename } from "@modern-js/runtime/context";
3
- import { __webpack_require__ } from "../rslib-runtime.mjs";
4
- import * as __rspack_external__modern_js_runtime_router_2dfd0c78 from "@modern-js/runtime/router";
5
- __webpack_require__.add({
6
- "@modern-js/runtime/router?f1fa" (module) {
7
- module.exports = __rspack_external__modern_js_runtime_router_2dfd0c78;
8
- }
9
- });
3
+ import { resolveLocalisedPath, resolveLocalisedUrlsConfig } from "../shared/localisedUrls.mjs";
10
4
  const getPathname = (context)=>{
11
5
  if (isBrowser()) return window.location.pathname;
12
6
  return context.ssrContext?.request?.pathname || '/';
@@ -22,11 +16,16 @@ const getLanguageFromPath = (pathname, languages, fallbackLanguage)=>{
22
16
  if (languages.includes(firstSegment)) return firstSegment;
23
17
  return fallbackLanguage;
24
18
  };
25
- const buildLocalizedUrl = (pathname, language, languages)=>{
19
+ const buildLocalizedUrl = (pathname, language, languages, localisedUrls)=>{
26
20
  const segments = pathname.split('/').filter(Boolean);
27
- if (segments.length > 0 && languages.includes(segments[0])) segments[0] = language;
28
- else segments.unshift(language);
29
- return `/${segments.join('/')}`;
21
+ const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
22
+ const pathWithoutLanguage = segments.length > 0 && languages.includes(segments[0]) ? `/${segments.slice(1).join('/')}` : pathname;
23
+ const resolvedPath = localisedUrlsConfig.enabled ? resolveLocalisedPath(pathWithoutLanguage, language, languages, localisedUrlsConfig.map) : pathWithoutLanguage;
24
+ const resolvedSegments = resolvedPath.split('/').filter(Boolean);
25
+ return `/${[
26
+ language,
27
+ ...resolvedSegments
28
+ ].join('/')}`;
30
29
  };
31
30
  const detectLanguageFromPath = (pathname, languages, localePathRedirect)=>{
32
31
  if (!localePathRedirect) return {
@@ -54,22 +53,4 @@ const shouldIgnoreRedirect = (pathname, languages, ignoreRedirectRoutes)=>{
54
53
  if ('function' == typeof ignoreRedirectRoutes) return ignoreRedirectRoutes(normalizedPath);
55
54
  return ignoreRedirectRoutes.some((pattern)=>normalizedPath === pattern || normalizedPath.startsWith(`${pattern}/`));
56
55
  };
57
- const useRouterHooks = ()=>{
58
- try {
59
- const { useLocation, useNavigate, useParams } = __webpack_require__("@modern-js/runtime/router?f1fa");
60
- return {
61
- navigate: useNavigate(),
62
- location: useLocation(),
63
- params: useParams(),
64
- hasRouter: true
65
- };
66
- } catch (error) {
67
- return {
68
- navigate: null,
69
- location: null,
70
- params: {},
71
- hasRouter: false
72
- };
73
- }
74
- };
75
- export { buildLocalizedUrl, detectLanguageFromPath, getEntryPath, getLanguageFromPath, getPathname, shouldIgnoreRedirect, useRouterHooks };
56
+ export { buildLocalizedUrl, detectLanguageFromPath, getEntryPath, getLanguageFromPath, getPathname, shouldIgnoreRedirect };
@@ -1,7 +1,38 @@
1
1
  import { DEFAULT_I18NEXT_DETECTION_OPTIONS, mergeDetectionOptions } from "../runtime/i18n/detection/config.mjs";
2
+ import { resolveLocalisedPath, resolveLocalisedUrlsConfig } from "../shared/localisedUrls.mjs";
2
3
  import { getLocaleDetectionOptions } from "../shared/utils.mjs";
3
4
  import * as __rspack_external__modern_js_server_core_hono_a76ca254 from "@modern-js/server-core/hono";
4
5
  const { languageDetector: languageDetector } = __rspack_external__modern_js_server_core_hono_a76ca254;
6
+ const normalizeApiPrefix = (prefix)=>{
7
+ const trimmedPrefix = prefix.trim();
8
+ if (!trimmedPrefix) return null;
9
+ const prefixedPath = trimmedPrefix.startsWith('/') ? trimmedPrefix : `/${trimmedPrefix}`;
10
+ const withoutWildcard = prefixedPath.replace(/\/\*$/, '');
11
+ const normalizedPrefix = withoutWildcard.length > 1 ? withoutWildcard.replace(/\/+$/, '') : withoutWildcard;
12
+ return '/' === normalizedPrefix ? null : normalizedPrefix;
13
+ };
14
+ const collectApiPrefixes = (routes, bffPrefix)=>{
15
+ const prefixes = new Set();
16
+ for (const route of routes){
17
+ if (!route.isApi || !route.urlPath) continue;
18
+ const normalizedPrefix = normalizeApiPrefix(route.urlPath);
19
+ if (normalizedPrefix) prefixes.add(normalizedPrefix);
20
+ }
21
+ const bffPrefixes = Array.isArray(bffPrefix) ? bffPrefix : bffPrefix ? [
22
+ bffPrefix
23
+ ] : [];
24
+ for (const prefix of bffPrefixes){
25
+ const normalizedPrefix = normalizeApiPrefix(prefix);
26
+ if (normalizedPrefix) prefixes.add(normalizedPrefix);
27
+ }
28
+ return [
29
+ ...prefixes
30
+ ];
31
+ };
32
+ const matchesApiPrefix = (pathname, apiPrefixes)=>{
33
+ const normalizedPathname = pathname.startsWith('/') ? pathname : `/${pathname}`;
34
+ return apiPrefixes.some((prefix)=>normalizedPathname === prefix || normalizedPathname.startsWith(`${prefix}/`));
35
+ };
5
36
  const convertToHonoLanguageDetectorOptions = (languages, fallbackLanguage, detectionOptions)=>{
6
37
  const mergedDetection = detectionOptions ? mergeDetectionOptions(detectionOptions) : DEFAULT_I18NEXT_DETECTION_OPTIONS;
7
38
  const order = (mergedDetection.order || []).filter((item)=>![
@@ -91,15 +122,20 @@ const getLanguageFromPath = (req, urlPath, languages)=>{
91
122
  if (languages.includes(firstSegment)) return firstSegment;
92
123
  return null;
93
124
  };
94
- const buildLocalizedUrl = (req, urlPath, language, languages)=>{
125
+ const buildLocalizedUrl = (req, urlPath, language, languages, localisedUrls)=>{
95
126
  const url = new URL(req.url);
96
127
  const pathname = url.pathname;
97
128
  const basePath = urlPath.replace('/*', '');
98
129
  const remainingPath = pathname.startsWith(basePath) ? pathname.slice(basePath.length) : pathname;
99
130
  const segments = remainingPath.split('/').filter(Boolean);
100
- if (segments.length > 0 && languages.includes(segments[0])) segments[0] = language;
101
- else segments.unshift(language);
102
- const newPathname = `/${segments.join('/')}`;
131
+ const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
132
+ const pathWithoutLanguage = segments.length > 0 && languages.includes(segments[0]) ? `/${segments.slice(1).join('/')}` : remainingPath;
133
+ const resolvedPath = localisedUrlsConfig.enabled ? resolveLocalisedPath(pathWithoutLanguage, language, languages, localisedUrlsConfig.map) : pathWithoutLanguage;
134
+ const resolvedSegments = resolvedPath.split('/').filter(Boolean);
135
+ const newPathname = `/${[
136
+ language,
137
+ ...resolvedSegments
138
+ ].join('/')}`;
103
139
  const suffix = `${url.search}${url.hash}`;
104
140
  const localizedUrl = '/' === basePath ? newPathname + suffix : basePath + newPathname + suffix;
105
141
  return localizedUrl;
@@ -109,6 +145,9 @@ const i18nServerPlugin = (options)=>({
109
145
  setup: (api)=>{
110
146
  api.onPrepare(()=>{
111
147
  const { middlewares, routes } = api.getServerContext();
148
+ const serverConfig = api.getServerConfig();
149
+ const bffPrefix = serverConfig?.bff ? serverConfig.bff.prefix ?? '/api' : void 0;
150
+ const apiPrefixes = collectApiPrefixes(routes, bffPrefix);
112
151
  const entryPaths = new Set();
113
152
  routes.forEach((route)=>{
114
153
  if (route.entryName && route.urlPath && '/' !== route.urlPath) {
@@ -120,7 +159,7 @@ const i18nServerPlugin = (options)=>({
120
159
  const { entryName } = route;
121
160
  if (!entryName) return;
122
161
  if (!options.localeDetection) return;
123
- const { localePathRedirect, i18nextDetector = true, languages = [], fallbackLanguage = 'en', detection, ignoreRedirectRoutes } = getLocaleDetectionOptions(entryName, options.localeDetection);
162
+ const { localePathRedirect, i18nextDetector = true, languages = [], fallbackLanguage = 'en', detection, ignoreRedirectRoutes, localisedUrls } = getLocaleDetectionOptions(entryName, options.localeDetection);
124
163
  const staticRoutePrefixes = options.staticRoutePrefixes;
125
164
  const originUrlPath = route.urlPath;
126
165
  const urlPath = originUrlPath.endsWith('/') ? `${originUrlPath}*` : `${originUrlPath}/*`;
@@ -134,6 +173,7 @@ const i18nServerPlugin = (options)=>({
134
173
  handler: async (c, next)=>{
135
174
  const url = new URL(c.req.url);
136
175
  const pathname = url.pathname;
176
+ if (matchesApiPrefix(pathname, apiPrefixes)) return await next();
137
177
  if (isStaticResourceRequest(pathname, staticRoutePrefixes, languages)) return await next();
138
178
  if ('/' === originUrlPath) {
139
179
  const pathSegments = pathname.split('/').filter(Boolean);
@@ -152,6 +192,7 @@ const i18nServerPlugin = (options)=>({
152
192
  handler: async (c, next)=>{
153
193
  const url = new URL(c.req.url);
154
194
  const pathname = url.pathname;
195
+ if (matchesApiPrefix(pathname, apiPrefixes)) return await next();
155
196
  if (isStaticResourceRequest(pathname, staticRoutePrefixes, languages)) return await next();
156
197
  if (shouldIgnoreRedirect(pathname, urlPath, ignoreRedirectRoutes)) return await next();
157
198
  if ('/' === originUrlPath) {
@@ -166,9 +207,18 @@ const i18nServerPlugin = (options)=>({
166
207
  let detectedLanguage = null;
167
208
  if (i18nextDetector) detectedLanguage = c.get('language') || null;
168
209
  const targetLanguage = detectedLanguage || fallbackLanguage;
169
- const localizedUrl = buildLocalizedUrl(c.req, originUrlPath, targetLanguage, languages);
210
+ const localizedUrl = buildLocalizedUrl(c.req, originUrlPath, targetLanguage, languages, localisedUrls);
170
211
  return c.redirect(localizedUrl);
171
212
  }
213
+ const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
214
+ if (localisedUrlsConfig.enabled) {
215
+ const basePath = originUrlPath.replace('/*', '');
216
+ const remainingPath = pathname.startsWith(basePath) ? pathname.slice(basePath.length) : pathname;
217
+ const pathWithoutLanguage = remainingPath.split('/').filter(Boolean).slice(1).join('/');
218
+ const canonicalLocalizedPath = resolveLocalisedPath(`/${pathWithoutLanguage}`, language, languages, localisedUrlsConfig.map);
219
+ const expectedPathname = '/' === basePath ? `/${language}${'/' === canonicalLocalizedPath ? '' : canonicalLocalizedPath}` : `${basePath}/${language}${'/' === canonicalLocalizedPath ? '' : canonicalLocalizedPath}`;
220
+ if (expectedPathname !== pathname) return c.redirect(`${expectedPathname}${url.search}${url.hash}`);
221
+ }
172
222
  await next();
173
223
  }
174
224
  });
@@ -179,4 +229,4 @@ const i18nServerPlugin = (options)=>({
179
229
  });
180
230
  const server = i18nServerPlugin;
181
231
  export default server;
182
- export { i18nServerPlugin };
232
+ export { collectApiPrefixes, i18nServerPlugin, matchesApiPrefix };
@@ -0,0 +1,191 @@
1
+ const LOCALE_PARAM_NAMES = new Set([
2
+ 'lang',
3
+ 'locale',
4
+ 'language'
5
+ ]);
6
+ const normalisePathPattern = (path)=>{
7
+ const withoutDuplicateSlashes = path.replace(/\/+/g, '/');
8
+ const withLeadingSlash = withoutDuplicateSlashes.startsWith('/') ? withoutDuplicateSlashes : `/${withoutDuplicateSlashes}`;
9
+ const withoutTrailingSlash = withLeadingSlash.length > 1 ? withLeadingSlash.replace(/\/+$/, '') : withLeadingSlash;
10
+ return withoutTrailingSlash.replace(/\[(.+?)\]/g, ':$1');
11
+ };
12
+ const normaliseRoutePath = (path)=>{
13
+ const normalized = normalisePathPattern(path);
14
+ return '/' === normalized ? '' : normalized.slice(1);
15
+ };
16
+ const getLocaleParamSegment = (segment)=>{
17
+ if (!segment.startsWith(':')) return null;
18
+ const paramName = segment.slice(1).replace(/\?$/, '');
19
+ return LOCALE_PARAM_NAMES.has(paramName) ? segment : null;
20
+ };
21
+ const splitPathSegments = (path)=>{
22
+ if (!path) return [];
23
+ return normalisePathPattern(path).split('/').filter(Boolean);
24
+ };
25
+ const stripLeadingLocaleParam = (path)=>{
26
+ const segments = splitPathSegments(path);
27
+ const leadingLocaleParam = getLocaleParamSegment(segments[0] || '');
28
+ if (!leadingLocaleParam) return path;
29
+ const remainingPath = segments.slice(1).join('/');
30
+ return remainingPath ? `/${remainingPath}` : void 0;
31
+ };
32
+ const getLeadingLocaleParam = (path)=>{
33
+ const segments = splitPathSegments(path);
34
+ return getLocaleParamSegment(segments[0] || '');
35
+ };
36
+ const resolveLocalisedUrlsConfig = (option)=>{
37
+ if (false === option) return {
38
+ enabled: false,
39
+ map: {}
40
+ };
41
+ if (option && 'object' == typeof option) return {
42
+ enabled: true,
43
+ map: option
44
+ };
45
+ return {
46
+ enabled: true,
47
+ map: {}
48
+ };
49
+ };
50
+ const isLocalisableRoutePath = (path)=>{
51
+ const pathWithoutLocale = stripLeadingLocaleParam(path);
52
+ if (!pathWithoutLocale || '/' === pathWithoutLocale || '*' === pathWithoutLocale) return false;
53
+ return true;
54
+ };
55
+ const joinPath = (parentPath, routePath)=>{
56
+ if (!isLocalisableRoutePath(routePath)) return parentPath;
57
+ const segment = normaliseRoutePath(stripLeadingLocaleParam(routePath) || '');
58
+ return normalisePathPattern(`${parentPath}/${segment}`);
59
+ };
60
+ const ensureLocalisedUrlsForPath = (canonicalPath, languages, localisedUrls)=>{
61
+ const entry = localisedUrls[canonicalPath];
62
+ if (!entry) throw new Error(`localisedUrls is enabled, but route "${canonicalPath}" does not define localised URLs for languages: ${languages.join(', ')}. Add localisedUrls["${canonicalPath}"] or set localeDetection.localisedUrls to false.`);
63
+ const missingLanguages = languages.filter((language)=>!entry[language]);
64
+ if (missingLanguages.length > 0) throw new Error(`localisedUrls["${canonicalPath}"] is missing languages: ${missingLanguages.join(', ')}. Every configured language must have a localised URL.`);
65
+ return entry;
66
+ };
67
+ const validateLocalisedUrls = (routes, languages, localisedUrls)=>{
68
+ const visit = (route, parentPath)=>{
69
+ const canonicalPath = joinPath(parentPath, route.path);
70
+ if (isLocalisableRoutePath(route.path)) ensureLocalisedUrlsForPath(canonicalPath, languages, localisedUrls);
71
+ if ('children' in route && route.children) route.children.forEach((child)=>visit(child, canonicalPath));
72
+ };
73
+ routes.forEach((route)=>visit(route, ''));
74
+ };
75
+ const getLocalisedRoutePaths = (canonicalPath, parentLocalisedPaths, languages, entry)=>{
76
+ const paths = languages.map((language)=>{
77
+ const fullPath = normalisePathPattern(entry[language]);
78
+ const parentPath = normalisePathPattern(parentLocalisedPaths[language] || '/');
79
+ if ('/' === parentPath) return normaliseRoutePath(fullPath) || void 0;
80
+ const parentPrefix = `${parentPath}/`;
81
+ if (!fullPath.startsWith(parentPrefix)) throw new Error(`localisedUrls["${canonicalPath}"].${language} must be nested under "${parentPath}" because its parent route is localised there.`);
82
+ return normaliseRoutePath(fullPath.slice(parentPath.length));
83
+ });
84
+ return Array.from(new Set(paths.filter(Boolean)));
85
+ };
86
+ const transformLocalisedRoute = (route, parentCanonicalPath, parentLocalisedPaths, languages, localisedUrls)=>{
87
+ const canonicalPath = joinPath(parentCanonicalPath, route.path);
88
+ const localisedUrlEntry = isLocalisableRoutePath(route.path) ? ensureLocalisedUrlsForPath(canonicalPath, languages, localisedUrls) : void 0;
89
+ const routeLocalisedPaths = localisedUrlEntry ? languages.reduce((acc, language)=>{
90
+ acc[language] = normalisePathPattern(localisedUrlEntry[language]);
91
+ return acc;
92
+ }, {}) : parentLocalisedPaths;
93
+ const children = 'children' in route && route.children ? route.children.flatMap((child)=>transformLocalisedRoute(child, canonicalPath, routeLocalisedPaths, languages, localisedUrls)) : void 0;
94
+ const baseRoute = {
95
+ ...route,
96
+ ...children ? {
97
+ children
98
+ } : {}
99
+ };
100
+ if (!localisedUrlEntry) return [
101
+ baseRoute
102
+ ];
103
+ return getLocalisedRoutePaths(canonicalPath, parentLocalisedPaths, languages, localisedUrlEntry).map((localisedPath, index)=>cloneRouteWithLocalisedPath(baseRoute, localisedPath, index));
104
+ };
105
+ const legalRouteIdPart = (value)=>value.replace(/[^a-zA-Z0-9_$-]+/g, '_').replace(/^_+|_+$/g, '') || 'index';
106
+ const suffixRouteIds = (route, suffix)=>{
107
+ const children = 'children' in route && route.children ? route.children.map((child)=>suffixRouteIds(child, suffix)) : void 0;
108
+ return {
109
+ ...route,
110
+ ...route.id ? {
111
+ id: `${route.id}__localised_${suffix}`
112
+ } : {},
113
+ ...children ? {
114
+ children
115
+ } : {}
116
+ };
117
+ };
118
+ const cloneRouteWithLocalisedPath = (route, path, index)=>{
119
+ const leadingLocaleParam = getLeadingLocaleParam(route.path);
120
+ const localisedPath = leadingLocaleParam ? normaliseRoutePath(`${leadingLocaleParam}/${path}`) : path;
121
+ const routeWithPath = {
122
+ ...route,
123
+ path: localisedPath
124
+ };
125
+ return 0 === index ? routeWithPath : suffixRouteIds(routeWithPath, legalRouteIdPart(localisedPath));
126
+ };
127
+ const applyLocalisedUrlsToRoutes = (routes, languages, localisedUrls)=>{
128
+ const rootLocalisedPaths = languages.reduce((acc, language)=>{
129
+ acc[language] = '/';
130
+ return acc;
131
+ }, {});
132
+ validateLocalisedUrls(routes, languages, localisedUrls);
133
+ return routes.flatMap((route)=>transformLocalisedRoute(route, '', rootLocalisedPaths, languages, localisedUrls));
134
+ };
135
+ const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
136
+ const getParamName = (segment)=>segment.slice(1).replace(/\?$/, '');
137
+ const compilePathPattern = (pattern)=>{
138
+ const names = [];
139
+ const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
140
+ const source = segments.map((segment)=>{
141
+ if (segment.startsWith(':')) {
142
+ names.push(getParamName(segment));
143
+ const paramPattern = '([^/]+)';
144
+ return segment.endsWith('?') ? `(?:/${paramPattern})?` : `/${paramPattern}`;
145
+ }
146
+ if ('*' === segment) {
147
+ names.push('*');
148
+ return '/(.*)';
149
+ }
150
+ return `/${escapeRegExp(segment)}`;
151
+ }).join('');
152
+ return {
153
+ names,
154
+ regexp: new RegExp(`^${source || '/'}$`)
155
+ };
156
+ };
157
+ const matchPathPattern = (pathname, pattern)=>{
158
+ const { names, regexp } = compilePathPattern(pattern);
159
+ const match = regexp.exec(normalisePathPattern(pathname));
160
+ if (!match) return null;
161
+ return names.reduce((params, name, index)=>{
162
+ params[name] = decodeURIComponent(match[index + 1] || '');
163
+ return params;
164
+ }, {});
165
+ };
166
+ const buildPathFromPattern = (pattern, params)=>{
167
+ const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
168
+ const path = segments.map((segment)=>{
169
+ if (segment.startsWith(':')) {
170
+ const param = params[getParamName(segment)];
171
+ return param ? encodeURIComponent(param) : '';
172
+ }
173
+ if ('*' === segment) return params['*'] || '';
174
+ return segment;
175
+ }).filter(Boolean).join('/');
176
+ return `/${path}`;
177
+ };
178
+ const resolveLocalisedPath = (pathname, targetLanguage, languages, localisedUrls)=>{
179
+ const normalizedPathname = normalisePathPattern(pathname);
180
+ for (const localisedUrlEntry of Object.values(localisedUrls)){
181
+ const targetPattern = localisedUrlEntry[targetLanguage];
182
+ if (targetPattern) for (const language of languages){
183
+ const sourcePattern = localisedUrlEntry[language];
184
+ if (!sourcePattern) continue;
185
+ const params = matchPathPattern(normalizedPathname, sourcePattern);
186
+ if (params) return buildPathFromPattern(targetPattern, params);
187
+ }
188
+ }
189
+ return normalizedPathname;
190
+ };
191
+ export { applyLocalisedUrlsToRoutes, normalisePathPattern, resolveLocalisedPath, resolveLocalisedUrlsConfig, validateLocalisedUrls };
@@ -2,6 +2,7 @@ import "node:module";
2
2
  import { getPublicDirRoutePrefixes } from "@modern-js/server-core";
3
3
  import fs from "fs";
4
4
  import path from "path";
5
+ import { applyLocalisedUrlsToRoutes, resolveLocalisedUrlsConfig } from "../shared/localisedUrls.mjs";
5
6
  import { getBackendOptions, getLocaleDetectionOptions } from "../shared/utils.mjs";
6
7
  function hasJsonFiles(dirPath) {
7
8
  try {
@@ -81,6 +82,27 @@ const i18nPlugin = (options = {})=>({
81
82
  plugins
82
83
  };
83
84
  });
85
+ api.modifyFileSystemRoutes(({ entrypoint, routes })=>{
86
+ if (!localeDetection) return {
87
+ entrypoint,
88
+ routes
89
+ };
90
+ const localeDetectionOptions = getLocaleDetectionOptions(entrypoint.entryName, localeDetection);
91
+ const { localePathRedirect, languages = [], localisedUrls } = localeDetectionOptions;
92
+ if (!localePathRedirect || 0 === languages.length) return {
93
+ entrypoint,
94
+ routes
95
+ };
96
+ const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
97
+ if (!localisedUrlsConfig.enabled) return {
98
+ entrypoint,
99
+ routes
100
+ };
101
+ return {
102
+ entrypoint,
103
+ routes: applyLocalisedUrlsToRoutes(routes, languages, localisedUrlsConfig.map)
104
+ };
105
+ });
84
106
  api._internalServerPlugins(({ plugins })=>{
85
107
  const { serverRoutes, metaName } = api.getAppContext();
86
108
  const normalizedConfig = api.getNormalizedConfig();
@@ -1,21 +1,13 @@
1
1
  import "node:module";
2
2
  import { jsx } from "react/jsx-runtime";
3
- import { Link as router_Link, useInRouterContext, useParams } from "@modern-js/runtime/router";
4
3
  import { useModernI18n } from "./context.mjs";
4
+ import { useI18nRouterAdapter } from "./routerAdapter.mjs";
5
5
  import { buildLocalizedUrl } from "./utils.mjs";
6
- const useRouterHooks = ()=>{
7
- const inRouter = useInRouterContext();
8
- return {
9
- Link: inRouter ? router_Link : null,
10
- params: inRouter ? useParams() : {},
11
- hasRouter: inRouter
12
- };
13
- };
14
6
  const I18nLink = ({ to, children, ...props })=>{
15
- const { Link, params, hasRouter } = useRouterHooks();
16
- const { language, supportedLanguages } = useModernI18n();
7
+ const { Link, params, hasRouter } = useI18nRouterAdapter();
8
+ const { language, supportedLanguages, localisedUrls } = useModernI18n();
17
9
  const currentLang = language;
18
- const localizedTo = buildLocalizedUrl(to, currentLang, supportedLanguages);
10
+ const localizedTo = buildLocalizedUrl(to, currentLang, supportedLanguages, localisedUrls);
19
11
  if ('development' === process.env.NODE_ENV && hasRouter && !params.lang) console.warn("I18nLink is being used outside of a :lang dynamic route context. This may cause unexpected behavior. Please ensure I18nLink is used within a route that has a :lang parameter.");
20
12
  if (!hasRouter || !Link) return /*#__PURE__*/ jsx("a", {
21
13
  href: localizedTo,