@bleedingdev/modern-js-plugin-i18n 3.9.0-ultramodern.4 → 3.9.0-ultramodern.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.
Files changed (79) hide show
  1. package/dist/cjs/cli/index.js +0 -22
  2. package/dist/cjs/runtime/Link.js +19 -32
  3. package/dist/cjs/runtime/context.js +26 -61
  4. package/dist/cjs/runtime/contextHelpers.js +5 -5
  5. package/dist/cjs/runtime/core.js +17 -14
  6. package/dist/cjs/runtime/hooks.js +7 -8
  7. package/dist/cjs/runtime/localizedPaths.js +11 -9
  8. package/dist/cjs/runtime/providerComposition.js +37 -13
  9. package/dist/cjs/runtime/routerAdapter.js +35 -140
  10. package/dist/cjs/runtime/utils.js +17 -19
  11. package/dist/cjs/server/index.js +10 -7
  12. package/dist/cjs/server/redirectPolicy.js +36 -31
  13. package/dist/cjs/shared/urlStrategy.js +18 -0
  14. package/dist/esm/cli/index.mjs +0 -22
  15. package/dist/esm/runtime/Link.mjs +19 -32
  16. package/dist/esm/runtime/context.mjs +18 -62
  17. package/dist/esm/runtime/contextHelpers.mjs +5 -5
  18. package/dist/esm/runtime/core.mjs +8 -5
  19. package/dist/esm/runtime/hooks.mjs +7 -8
  20. package/dist/esm/runtime/localizedPaths.mjs +11 -9
  21. package/dist/esm/runtime/providerComposition.mjs +38 -14
  22. package/dist/esm/runtime/routerAdapter.mjs +30 -141
  23. package/dist/esm/runtime/utils.mjs +15 -17
  24. package/dist/esm/server/index.mjs +10 -7
  25. package/dist/esm/server/redirectPolicy.mjs +29 -24
  26. package/dist/esm/shared/urlStrategy.mjs +0 -0
  27. package/dist/esm-node/cli/index.mjs +0 -22
  28. package/dist/esm-node/runtime/Link.mjs +19 -32
  29. package/dist/esm-node/runtime/context.mjs +18 -62
  30. package/dist/esm-node/runtime/contextHelpers.mjs +5 -5
  31. package/dist/esm-node/runtime/core.mjs +8 -5
  32. package/dist/esm-node/runtime/hooks.mjs +7 -8
  33. package/dist/esm-node/runtime/localizedPaths.mjs +11 -9
  34. package/dist/esm-node/runtime/providerComposition.mjs +38 -14
  35. package/dist/esm-node/runtime/routerAdapter.mjs +30 -141
  36. package/dist/esm-node/runtime/utils.mjs +15 -17
  37. package/dist/esm-node/server/index.mjs +10 -7
  38. package/dist/esm-node/server/redirectPolicy.mjs +29 -24
  39. package/dist/esm-node/shared/urlStrategy.mjs +1 -0
  40. package/dist/types/runtime/context.d.ts +8 -11
  41. package/dist/types/runtime/contextHelpers.d.ts +2 -2
  42. package/dist/types/runtime/core.d.ts +11 -2
  43. package/dist/types/runtime/hooks.d.ts +4 -5
  44. package/dist/types/runtime/localizedPaths.d.ts +4 -4
  45. package/dist/types/runtime/providerComposition.d.ts +13 -1
  46. package/dist/types/runtime/routerAdapter.d.ts +23 -6
  47. package/dist/types/runtime/utils.d.ts +4 -12
  48. package/dist/types/server/index.d.ts +2 -0
  49. package/dist/types/server/redirectPolicy.d.ts +5 -13
  50. package/dist/types/shared/type.d.ts +0 -14
  51. package/dist/types/shared/urlStrategy.d.ts +7 -0
  52. package/package.json +21 -11
  53. package/rstest.config.mts +2 -8
  54. package/src/cli/index.ts +1 -43
  55. package/src/runtime/Link.tsx +20 -40
  56. package/src/runtime/context.tsx +34 -133
  57. package/src/runtime/contextHelpers.ts +7 -5
  58. package/src/runtime/core.tsx +26 -6
  59. package/src/runtime/hooks.ts +14 -9
  60. package/src/runtime/localizedPaths.ts +24 -19
  61. package/src/runtime/providerComposition.tsx +71 -23
  62. package/src/runtime/routerAdapter.tsx +73 -338
  63. package/src/runtime/utils.ts +40 -31
  64. package/src/server/index.ts +44 -9
  65. package/src/server/redirectPolicy.ts +70 -70
  66. package/src/shared/type.ts +0 -14
  67. package/src/shared/urlStrategy.ts +11 -0
  68. package/tests/federatedI18nBoundaryResolver.test.tsx +71 -0
  69. package/tests/i18nUtils.test.ts +31 -65
  70. package/tests/link.test.tsx +13 -511
  71. package/tests/linkTypes.test.ts +12 -3
  72. package/tests/localisedUrlRewriteMatrix.fork.test.ts +4 -96
  73. package/tests/localisedUrls.test.ts +7 -216
  74. package/tests/reactI18nextRuntimeBoundary.test.ts +1 -82
  75. package/tests/redirectPolicy.test.ts +39 -30
  76. package/tests/routerAdapter.test.tsx +95 -1055
  77. package/tests/federatedI18nBoundary.client.test.tsx +0 -129
  78. package/tests/federatedI18nBoundary.test.tsx +0 -132
  79. package/tests/peerCohort.test.ts +0 -25
@@ -1,151 +1,40 @@
1
1
  import "node:module";
2
+ import { jsx } from "react/jsx-runtime";
2
3
  import { RuntimeContext, isBrowser } from "@modern-js/runtime";
3
- import { InternalRuntimeContext, getRouterRuntimeState } from "@modern-js/runtime/context";
4
- import { useCallback, useContext, useSyncExternalStore } 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 = getRouterRuntimeState(internalContext)?.framework || getRouterRuntimeState(runtimeContext)?.framework;
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 = getRouterRuntimeState(internalContext)?.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 getRouterSnapshot = (internalContext, contextRouter)=>{
54
- const location = getRouterStateLocation(internalContext, contextRouter);
55
- const params = getRouterParams(internalContext, contextRouter);
56
- return JSON.stringify([
57
- location?.pathname ?? '',
58
- location?.search ?? '',
59
- location?.hash ?? '',
60
- Object.entries(params).sort(([left], [right])=>left.localeCompare(right))
61
- ]);
62
- };
63
- const useI18nRouterAdapter = ()=>{
4
+ import { InternalRuntimeContext } from "@modern-js/runtime/context";
5
+ import { createContext, useContext } from "react";
6
+ const navigationContextKey = Symbol.for('@modern-js/plugin-i18n/runtime/I18nNavigationContext');
7
+ const contextStore = globalThis;
8
+ const I18nNavigationContext = contextStore[navigationContextKey] ??= /*#__PURE__*/ createContext(null);
9
+ const I18nNavigationProvider = ({ children, value })=>/*#__PURE__*/ jsx(I18nNavigationContext.Provider, {
10
+ value: value,
11
+ children: children
12
+ });
13
+ const useNativeI18nRouterAdapter = ()=>{
64
14
  const runtimeContext = useContext(RuntimeContext);
65
15
  const internalContext = useContext(InternalRuntimeContext);
66
16
  const routerApi = internalContext.router || runtimeContext.router;
67
- const inReactRouter = routerApi?.useInRouterContext?.() ?? false;
68
- const reactRouterNavigate = inReactRouter ? routerApi?.useNavigate?.() ?? null : null;
69
- const reactRouterLocation = inReactRouter ? routerApi?.useLocation?.() ?? null : null;
70
- const reactRouterParams = inReactRouter ? routerApi?.useParams?.() ?? {} : {};
71
- const framework = getRouterFramework(runtimeContext, internalContext, inReactRouter);
72
- const contextUseRouter = inReactRouter || 'tanstack' !== framework ? void 0 : internalContext.router?.useRouter || runtimeContext.router?.useRouter;
73
- const contextRouter = contextUseRouter ? contextUseRouter({
74
- warn: false
75
- }) : null;
76
- const hasRouter = 'tanstack' === framework || 'react-router' === framework || Boolean(reactRouterNavigate);
77
- const subscribeToRouter = useCallback((update)=>{
78
- const router = getRouterInstance(internalContext, contextRouter);
79
- if (!router) return ()=>void 0;
80
- const unsubscribers = [];
81
- if ('react-router' === framework && !inReactRouter && 'function' == typeof router.subscribe) {
82
- const subscribe = router.subscribe;
83
- const unsubscribe = subscribe.call(router, update);
84
- if ('function' == typeof unsubscribe) unsubscribers.push(unsubscribe);
85
- }
86
- if ('tanstack' === framework && 'function' == typeof router.stores?.location?.subscribe) {
87
- const unsubscribe = router.stores.location.subscribe(update);
88
- if ('function' == typeof unsubscribe) unsubscribers.push(unsubscribe);
89
- }
90
- if ('tanstack' === framework && 'function' == typeof router.subscribe) {
91
- const subscribe = router.subscribe;
92
- for (const eventType of [
93
- 'onBeforeNavigate',
94
- 'onBeforeLoad'
95
- ]){
96
- const unsubscribe = subscribe.call(router, eventType, update);
97
- if ('function' == typeof unsubscribe) unsubscribers.push(unsubscribe);
98
- }
99
- }
100
- return ()=>{
101
- for (const unsubscribe of unsubscribers)unsubscribe();
102
- };
103
- }, [
104
- contextRouter,
105
- framework,
106
- inReactRouter,
107
- internalContext
108
- ]);
109
- const getSnapshot = useCallback(()=>getRouterSnapshot(internalContext, contextRouter), [
110
- contextRouter,
111
- internalContext
112
- ]);
113
- useSyncExternalStore(subscribeToRouter, getSnapshot, getSnapshot);
114
- const navigate = useCallback((href, options)=>{
115
- const router = getRouterInstance(internalContext, contextRouter);
116
- const activeFramework = getRouterFramework(runtimeContext, internalContext, inReactRouter);
117
- if ('tanstack' === activeFramework) {
118
- if ('function' == typeof router?.navigate) return router.navigate({
119
- to: href,
120
- replace: options?.replace,
121
- ...options?.state === void 0 ? {} : {
122
- state: options.state
123
- }
124
- });
125
- throw new Error('TanStack router instance is not available.');
126
- }
127
- if (reactRouterNavigate) return reactRouterNavigate(href, options);
128
- if ('react-router' === activeFramework) {
129
- if ('function' == typeof router?.navigate) return router.navigate(href, options);
130
- throw new Error('React Router instance is not available.');
131
- }
132
- }, [
133
- contextRouter,
134
- internalContext,
135
- inReactRouter,
136
- reactRouterNavigate,
137
- runtimeContext
138
- ]);
139
- const location = (reactRouterLocation ? normalizeLocation(reactRouterLocation) : getRouterStateLocation(internalContext, contextRouter)) || getWindowLocation();
140
- const params = inReactRouter ? reactRouterParams : getRouterParams(internalContext, contextRouter);
141
- const Link = 'tanstack' === framework ? internalContext.router?.Link || runtimeContext.router?.Link || null : 'react-router' === framework || inReactRouter ? routerApi?.Link ?? null : null;
17
+ const hasRouter = routerApi?.useInRouterContext?.() ?? false;
18
+ const navigate = hasRouter ? routerApi?.useNavigate?.() ?? null : null;
19
+ const routerLocation = hasRouter ? routerApi?.useLocation?.() ?? null : null;
20
+ const params = hasRouter ? routerApi?.useParams?.() ?? {} : {};
21
+ const location = routerLocation ?? (isBrowser() ? {
22
+ pathname: window.location.pathname,
23
+ search: window.location.search,
24
+ hash: window.location.hash
25
+ } : null);
142
26
  return {
143
- framework,
27
+ framework: hasRouter ? 'react-router' : void 0,
144
28
  hasRouter,
29
+ navigate,
145
30
  location,
146
- navigate: hasRouter ? navigate : null,
147
- Link,
148
- params
31
+ params,
32
+ Link: hasRouter ? routerApi?.Link ?? null : null
149
33
  };
150
34
  };
151
- export { useI18nRouterAdapter };
35
+ const useI18nRouterAdapter = ()=>{
36
+ const provided = useContext(I18nNavigationContext);
37
+ const native = useNativeI18nRouterAdapter();
38
+ return provided ?? native;
39
+ };
40
+ export { I18nNavigationProvider, useI18nRouterAdapter, useNativeI18nRouterAdapter };
@@ -1,7 +1,7 @@
1
1
  import "node:module";
2
- import { localiseTargetPathname, shouldSkipLocaleRedirect } from "@modern-js/i18n-runtime-extensions";
3
2
  import { isBrowser } from "@modern-js/runtime";
4
3
  import { getGlobalBasename } from "@modern-js/runtime/context";
4
+ import { splitUrlTarget } from "@modern-js/runtime-utils/url";
5
5
  const getPathname = (context)=>{
6
6
  if (isBrowser()) return window.location.pathname;
7
7
  return context.ssrContext?.request?.pathname || '/';
@@ -17,22 +17,13 @@ const getLanguageFromPath = (pathname, languages, fallbackLanguage)=>{
17
17
  if (languages.includes(firstSegment)) return firstSegment;
18
18
  return fallbackLanguage;
19
19
  };
20
- const splitUrlTarget = (target)=>{
21
- const hashIndex = target.indexOf('#');
22
- const hash = hashIndex >= 0 ? target.slice(hashIndex) : '';
23
- const beforeHash = hashIndex >= 0 ? target.slice(0, hashIndex) : target;
24
- const searchIndex = beforeHash.indexOf('?');
25
- const search = searchIndex >= 0 ? beforeHash.slice(searchIndex) : '';
26
- const pathname = searchIndex >= 0 ? beforeHash.slice(0, searchIndex) : beforeHash;
27
- return {
28
- pathname,
29
- search,
30
- hash
31
- };
32
- };
33
- const buildLocalizedUrl = (target, language, languages, localisedUrls)=>{
20
+ const buildLocalizedUrl = (target, language, languages, urlStrategy)=>{
34
21
  const { pathname, search, hash } = splitUrlTarget(target);
35
- const localizedPathname = localiseTargetPathname(pathname, language, languages, localisedUrls);
22
+ if (urlStrategy) return `${urlStrategy.localizePathname(pathname, language, languages)}${search}${hash}`;
23
+ const segments = pathname.split('/').filter(Boolean);
24
+ if (segments[0] && languages.some((item)=>item.toLowerCase() === segments[0].toLowerCase())) segments[0] = language;
25
+ else segments.unshift(language);
26
+ const localizedPathname = `/${segments.join('/')}`;
36
27
  return `${localizedPathname}${search}${hash}`;
37
28
  };
38
29
  const detectLanguageFromPath = (pathname, languages, localePathRedirect)=>{
@@ -52,5 +43,12 @@ const detectLanguageFromPath = (pathname, languages, localePathRedirect)=>{
52
43
  detected: false
53
44
  };
54
45
  };
55
- const shouldIgnoreRedirect = (pathname, languages, ignoreRedirectRoutes)=>shouldSkipLocaleRedirect(pathname, languages, ignoreRedirectRoutes);
46
+ const shouldIgnoreRedirect = (pathname, languages, ignoreRedirectRoutes, urlStrategy)=>{
47
+ if (urlStrategy?.shouldSkipRedirect?.(pathname, languages)) return true;
48
+ if (!ignoreRedirectRoutes) return false;
49
+ const segments = pathname.split('/').filter(Boolean);
50
+ if (segments[0] && languages.some((item)=>item.toLowerCase() === segments[0].toLowerCase())) segments.shift();
51
+ const normalizedPath = `/${segments.join('/')}`;
52
+ return 'function' == typeof ignoreRedirectRoutes ? ignoreRedirectRoutes(normalizedPath) : ignoreRedirectRoutes.some((pattern)=>normalizedPath === pattern || normalizedPath.startsWith(`${pattern}/`));
53
+ };
56
54
  export { buildLocalizedUrl, detectLanguageFromPath, getEntryPath, getLanguageFromPath, getPathname, shouldIgnoreRedirect, splitUrlTarget };
@@ -1,5 +1,4 @@
1
1
  import "node:module";
2
- import { resolveLocalisedUrlsConfig } from "@modern-js/i18n-runtime-extensions";
3
2
  import { getLocaleDetectionOptions } from "../shared/utils.mjs";
4
3
  import { collectApiPrefixes, matchesApiPrefix } from "./apiPrefix.mjs";
5
4
  import { convertToHonoLanguageDetectorOptions } from "./detectorOptions.mjs";
@@ -25,7 +24,11 @@ const i18nServerPlugin = (options)=>({
25
24
  const { entryName } = route;
26
25
  if (!entryName) return;
27
26
  if (!options.localeDetection) return;
28
- const { localePathRedirect, i18nextDetector = true, languages = [], fallbackLanguage = 'en', detection, ignoreRedirectRoutes, localisedUrls } = getLocaleDetectionOptions(entryName, options.localeDetection);
27
+ const entryLocaleDetection = getLocaleDetectionOptions(entryName, options.localeDetection);
28
+ const { localePathRedirect, i18nextDetector = true, languages = [], fallbackLanguage = 'en', detection, ignoreRedirectRoutes } = entryLocaleDetection;
29
+ const legacyLocalisedUrls = Reflect.get(entryLocaleDetection, 'localisedUrls');
30
+ const urlStrategy = options.resolveUrlStrategy?.(entryName);
31
+ if (legacyLocalisedUrls && 'object' == typeof legacyLocalisedUrls && Object.keys(legacyLocalisedUrls).length > 0 && !urlStrategy) throw new Error('Mapped locale URLs require a URL strategy. Use the i18n integration server plugin or supply resolveUrlStrategy.');
29
32
  const staticRoutePrefixes = options.staticRoutePrefixes;
30
33
  const originUrlPath = route.urlPath;
31
34
  const urlPath = originUrlPath.endsWith('/') ? `${originUrlPath}*` : `${originUrlPath}/*`;
@@ -40,6 +43,7 @@ const i18nServerPlugin = (options)=>({
40
43
  const url = new URL(c.req.url);
41
44
  const pathname = url.pathname;
42
45
  if (matchesApiPrefix(pathname, apiPrefixes)) return await next();
46
+ if (shouldIgnoreRedirect(pathname, urlPath, ignoreRedirectRoutes, urlStrategy, languages)) return await next();
43
47
  if (isStaticResourceRequest(pathname, staticRoutePrefixes, languages)) return await next();
44
48
  if ('/' === originUrlPath) {
45
49
  const pathSegments = pathname.split('/').filter(Boolean);
@@ -60,7 +64,7 @@ const i18nServerPlugin = (options)=>({
60
64
  const pathname = url.pathname;
61
65
  if (matchesApiPrefix(pathname, apiPrefixes)) return await next();
62
66
  if (isStaticResourceRequest(pathname, staticRoutePrefixes, languages)) return await next();
63
- if (shouldIgnoreRedirect(pathname, urlPath, ignoreRedirectRoutes)) return await next();
67
+ if (shouldIgnoreRedirect(pathname, urlPath, ignoreRedirectRoutes, urlStrategy, languages)) return await next();
64
68
  if ('/' === originUrlPath) {
65
69
  const pathSegments = pathname.split('/').filter(Boolean);
66
70
  if (pathSegments.length > 0) {
@@ -73,12 +77,11 @@ const i18nServerPlugin = (options)=>({
73
77
  let detectedLanguage = null;
74
78
  if (i18nextDetector) detectedLanguage = c.get('language') || null;
75
79
  const targetLanguage = detectedLanguage || fallbackLanguage;
76
- const localizedUrl = buildLocalizedUrl(c.req, originUrlPath, targetLanguage, languages, localisedUrls);
80
+ const localizedUrl = buildLocalizedUrl(c.req, originUrlPath, targetLanguage, languages, urlStrategy);
77
81
  return createLocaleRedirectResponse(localizedUrl);
78
82
  }
79
- const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
80
- if (localisedUrlsConfig.enabled) {
81
- const expectedUrl = buildLocalizedUrl(c.req, originUrlPath, language, languages, localisedUrls);
83
+ if (urlStrategy) {
84
+ const expectedUrl = buildLocalizedUrl(c.req, originUrlPath, language, languages, urlStrategy);
82
85
  if (expectedUrl !== `${pathname}${url.search}${url.hash}`) return createLocaleRedirectResponse(expectedUrl);
83
86
  }
84
87
  await next();
@@ -1,40 +1,45 @@
1
1
  import "node:module";
2
- import { isDefaultLocaleRedirectSkipPath, localiseTargetPathname, matchesPathPrefix, shouldSkipLocaleRedirect, stripLanguagePrefix } from "@modern-js/i18n-runtime-extensions";
3
2
  const stripUrlPathPrefix = (pathname, urlPath)=>{
4
3
  const basePath = urlPath.replace('/*', '');
5
4
  if (!basePath || '/' === basePath) return pathname;
6
- const remainingPath = pathname.startsWith(basePath) ? pathname.slice(basePath.length) : pathname;
7
- return remainingPath || '/';
5
+ return pathname === basePath || pathname.startsWith(`${basePath}/`) ? pathname.slice(basePath.length) || '/' : pathname;
8
6
  };
9
- const shouldIgnoreRedirect = (pathname, urlPath, ignoreRedirectRoutes)=>{
7
+ const shouldIgnoreRedirect = (pathname, urlPath, ignoreRedirectRoutes, urlStrategy, languages = [])=>{
10
8
  const remainingPath = stripUrlPathPrefix(pathname, urlPath);
11
- return shouldSkipLocaleRedirect(remainingPath, [], ignoreRedirectRoutes);
9
+ if (urlStrategy?.shouldSkipRedirect?.(remainingPath, languages)) return true;
10
+ if (!ignoreRedirectRoutes) return false;
11
+ const segments = remainingPath.split('/').filter(Boolean);
12
+ if (segments[0] && languages.some((language)=>language.toLowerCase() === segments[0].toLowerCase())) segments.shift();
13
+ const normalizedPath = `/${segments.join('/')}`;
14
+ return 'function' == typeof ignoreRedirectRoutes ? ignoreRedirectRoutes(normalizedPath) : ignoreRedirectRoutes.some((pattern)=>normalizedPath === pattern || normalizedPath.startsWith(`${pattern}/`));
12
15
  };
13
16
  const isStaticResourceRequest = (pathname, staticRoutePrefixes, languages = [])=>{
14
- if (isDefaultLocaleRedirectSkipPath(pathname, languages)) return true;
15
- const matchesStaticRoutePrefix = (targetPathname)=>staticRoutePrefixes.some((prefix)=>matchesPathPrefix(targetPathname, prefix));
16
- if (matchesStaticRoutePrefix(pathname)) return true;
17
- const pathWithoutLanguage = stripLanguagePrefix(pathname, languages);
18
- return pathWithoutLanguage !== pathname && matchesStaticRoutePrefix(pathWithoutLanguage);
17
+ const prefixes = [
18
+ ...staticRoutePrefixes,
19
+ '/static',
20
+ '/upload'
21
+ ];
22
+ const matches = (target)=>prefixes.some((prefix)=>target === prefix || target.startsWith(`${prefix}/`));
23
+ if (matches(pathname)) return true;
24
+ const segments = pathname.split('/').filter(Boolean);
25
+ if (segments[0] && languages.some((language)=>language.toLowerCase() === segments[0].toLowerCase())) return matches(`/${segments.slice(1).join('/')}`);
26
+ return false;
19
27
  };
20
28
  const getLanguageFromPath = (req, urlPath, languages)=>{
21
- const url = new URL(req.url, `http://${req.header().host}`);
22
- const pathname = url.pathname;
23
- const remainingPath = stripUrlPathPrefix(pathname, urlPath);
24
- const segments = remainingPath.split('/').filter(Boolean);
25
- const firstSegment = segments[0];
26
- if (languages.includes(firstSegment)) return firstSegment;
27
- return null;
29
+ const host = req.header?.().host;
30
+ const url = new URL(req.url, host ? `http://${host}` : void 0);
31
+ const firstSegment = stripUrlPathPrefix(url.pathname, urlPath).split('/').filter(Boolean)[0];
32
+ return languages.find((language)=>language.toLowerCase() === firstSegment?.toLowerCase()) ?? null;
28
33
  };
29
- const buildLocalizedUrl = (req, urlPath, language, languages, localisedUrls)=>{
34
+ const buildLocalizedUrl = (req, urlPath, language, languages, urlStrategy)=>{
30
35
  const url = new URL(req.url);
31
- const pathname = url.pathname;
32
36
  const basePath = urlPath.replace('/*', '');
33
- const remainingPath = stripUrlPathPrefix(pathname, urlPath);
34
- const newPathname = localiseTargetPathname(remainingPath, language, languages, localisedUrls);
35
- const suffix = `${url.search}${url.hash}`;
36
- const localizedUrl = '/' === basePath ? newPathname + suffix : basePath + newPathname + suffix;
37
- return localizedUrl;
37
+ const remainingPath = stripUrlPathPrefix(url.pathname, urlPath);
38
+ const segments = remainingPath.split('/').filter(Boolean);
39
+ if (segments[0] && languages.some((item)=>item.toLowerCase() === segments[0].toLowerCase())) segments[0] = language;
40
+ else segments.unshift(language);
41
+ const pathname = urlStrategy ? urlStrategy.localizePathname(remainingPath, language, languages) : `/${segments.join('/')}`;
42
+ return `${'/' === basePath ? '' : basePath}${pathname}${url.search}${url.hash}`;
38
43
  };
39
44
  const createLocaleRedirectResponse = (location)=>new Response(null, {
40
45
  status: 302,
@@ -0,0 +1 @@
1
+ import "node:module";
@@ -1,19 +1,22 @@
1
- import type { LocalisedUrlsOption } from '@modern-js/i18n-runtime-extensions';
2
1
  import type { ComponentType, FC, ReactNode } from 'react';
2
+ import type { I18nUrlStrategy } from '../shared/urlStrategy.js';
3
3
  import type { I18nInstance } from './i18n/index.js';
4
4
  import type { Resources } from './i18n/instance.js';
5
- interface ModernI18nContextValue {
5
+ export { getActualI18nextInstance } from './i18n/instance.js';
6
+ export interface ModernI18nContextValue {
6
7
  language: string;
7
8
  i18nInstance: I18nInstance;
8
9
  entryName?: string;
9
10
  languages?: string[];
10
11
  localePathRedirect?: boolean;
11
12
  ignoreRedirectRoutes?: string[] | ((pathname: string) => boolean);
12
- localisedUrls?: LocalisedUrlsOption;
13
+ urlStrategy?: I18nUrlStrategy;
13
14
  updateLanguage?: (newLang: string) => void;
14
15
  synchronizeLanguage?: (newLang: string) => void;
15
16
  }
16
- interface ModernI18nProviderProps {
17
+ export declare const ModernI18nContext: import("react").Context<ModernI18nContextValue | null>;
18
+ export declare const ReactI18nextProviderContext: import("react").Context<ComponentType<any> | null>;
19
+ export interface ModernI18nProviderProps {
17
20
  children: ReactNode;
18
21
  i18nextProvider?: ComponentType<any> | null;
19
22
  value: ModernI18nContextValue;
@@ -26,11 +29,6 @@ export interface FederatedI18nBoundaryProps {
26
29
  resources: Resources;
27
30
  supportedLanguages?: string[];
28
31
  }
29
- /**
30
- * Keeps a federated surface's translation resources inside its delivery unit.
31
- * The host supplies only the active language; the remote owns and versions the
32
- * resources used below this boundary.
33
- */
34
32
  export declare const FederatedI18nBoundary: FC<FederatedI18nBoundaryProps>;
35
33
  export interface UseModernI18nReturn<TInstance extends I18nInstance = I18nInstance> {
36
34
  language: string;
@@ -38,7 +36,7 @@ export interface UseModernI18nReturn<TInstance extends I18nInstance = I18nInstan
38
36
  t: (key: string | string[], ...args: any[]) => string;
39
37
  i18nInstance: TInstance;
40
38
  supportedLanguages: string[];
41
- localisedUrls?: LocalisedUrlsOption;
39
+ urlStrategy?: I18nUrlStrategy;
42
40
  isLanguageSupported: (lang: string) => boolean;
43
41
  isResourcesReady: boolean;
44
42
  }
@@ -62,4 +60,3 @@ export interface UseModernI18nReturn<TInstance extends I18nInstance = I18nInstan
62
60
  * @returns Object containing i18n functionality and utilities
63
61
  */
64
62
  export declare const useModernI18n: <TInstance extends I18nInstance = I18nInstance>() => UseModernI18nReturn<TInstance>;
65
- export {};
@@ -1,4 +1,4 @@
1
- import type { LocalisedUrlsOption } from '@modern-js/i18n-runtime-extensions';
1
+ import type { I18nUrlStrategy } from '../shared/urlStrategy.js';
2
2
  import type { I18nInstance } from './i18n/index.js';
3
3
  type Navigate = (url: string, options?: {
4
4
  replace?: boolean;
@@ -16,7 +16,7 @@ interface ChangeModernI18nLanguageOptions {
16
16
  updateLanguage?: (newLang: string) => void;
17
17
  localePathRedirect?: boolean;
18
18
  ignoreRedirectRoutes?: string[] | ((pathname: string) => boolean);
19
- localisedUrls?: LocalisedUrlsOption;
19
+ urlStrategy?: I18nUrlStrategy;
20
20
  languages?: string[];
21
21
  hasRouter: boolean;
22
22
  navigate?: Navigate | null;
@@ -1,11 +1,17 @@
1
1
  import type { RuntimePlugin } from '@modern-js/runtime';
2
+ import type React from 'react';
2
3
  import type { BaseBackendOptions, BaseLocaleDetectionOptions } from '../shared/type.js';
4
+ import type { I18nUrlStrategy } from '../shared/urlStrategy.js';
3
5
  import type { I18nInitOptions, I18nInstance } from './i18n/index.js';
6
+ import { type I18nLanguageSynchronizationProps } from './providerComposition.js';
7
+ export type { I18nLanguageSynchronizationProps } from './providerComposition.js';
4
8
  import { type LoadReactI18nextIntegration } from './reactI18next.js';
5
9
  import './types.js';
6
10
  export type { I18nSdkLoader, I18nSdkLoadOptions } from '../shared/type.js';
11
+ export type { I18nUrlStrategy } from '../shared/urlStrategy.js';
7
12
  export type { I18nInitOptions, I18nInstance, Resources, TranslateFn, } from './i18n/instance.js';
8
13
  export type { LoadReactI18nextIntegration, ReactI18nextIntegration, } from './reactI18next.js';
14
+ export { I18nNavigationProvider, type I18nRouterAdapter, type I18nRouterLinkTarget, useI18nRouterAdapter, useNativeI18nRouterAdapter, } from './routerAdapter.js';
9
15
  export interface I18nPluginOptions {
10
16
  entryName?: string;
11
17
  localeDetection?: BaseLocaleDetectionOptions;
@@ -15,6 +21,9 @@ export interface I18nPluginOptions {
15
21
  initOptions?: I18nInitOptions;
16
22
  htmlLangAttr?: boolean;
17
23
  reactI18next?: boolean;
24
+ urlStrategy?: I18nUrlStrategy;
25
+ NavigationProvider?: React.ComponentType<React.PropsWithChildren>;
26
+ LanguageSynchronization?: React.ComponentType<I18nLanguageSynchronizationProps>;
18
27
  [key: string]: any;
19
28
  }
20
29
  export declare const createI18nPlugin: (loadReactI18nextIntegration?: LoadReactI18nextIntegration) => ((options: I18nPluginOptions) => RuntimePlugin);
@@ -22,5 +31,5 @@ export type { AllowedLinkTarget, CanonicalRoutePath, UltramodernCanonicalRoutes,
22
31
  export { FederatedI18nBoundary, type FederatedI18nBoundaryProps, type UseModernI18nReturn, useModernI18n, } from './context.js';
23
32
  export { I18nLink, type I18nLinkProps } from './I18nLink.js';
24
33
  export { Link, type LinkActiveOptions, type LinkBaseProps, type LinkParams, type LinkProps, } from './Link.js';
25
- export { canonicalPath, type LocalizedPathsConfig, localizePath, type UseLocalizedLocationReturn, type UseLocalizedPathsReturn, useLocalizedLocation, useLocalizedPaths, } from './localizedPaths.js';
26
- export { buildLocalizedUrl, splitUrlTarget } from './utils.js';
34
+ export { type LocalizedPathsConfig, type UseLocalizedLocationReturn, type UseLocalizedPathsReturn, useLocalizedLocation, useLocalizedPaths, } from './localizedPaths.js';
35
+ export { splitUrlTarget } from './utils.js';
@@ -1,16 +1,15 @@
1
- import type { LocalisedUrlsOption } from '@modern-js/i18n-runtime-extensions';
2
1
  import type React from 'react';
2
+ import type { I18nUrlStrategy } from '../shared/urlStrategy.js';
3
3
  import type { I18nInstance } from './i18n/index.js';
4
- export declare function createContextValue(lang: string, i18nInstance: I18nInstance | undefined, entryName: string | undefined, languages: string[], localePathRedirect: boolean, ignoreRedirectRoutes: string[] | ((pathname: string) => boolean) | undefined, localisedUrls: LocalisedUrlsOption | undefined, setLang: (lang: string) => void, synchronizeLanguage: (lang: string) => void): {
4
+ export declare function createContextValue(lang: string, i18nInstance: I18nInstance | undefined, entryName: string | undefined, languages: string[], localePathRedirect: boolean, ignoreRedirectRoutes: string[] | ((pathname: string) => boolean) | undefined, setLang: (lang: string) => void, urlStrategy?: I18nUrlStrategy): {
5
5
  language: string;
6
6
  i18nInstance: I18nInstance;
7
7
  entryName: string | undefined;
8
8
  languages: string[];
9
9
  localePathRedirect: boolean;
10
10
  ignoreRedirectRoutes: string[] | ((pathname: string) => boolean) | undefined;
11
- localisedUrls: LocalisedUrlsOption | undefined;
11
+ urlStrategy: I18nUrlStrategy | undefined;
12
12
  updateLanguage: (lang: string) => void;
13
- synchronizeLanguage: (lang: string) => void;
14
13
  };
15
14
  export declare function useSdkResourcesLoader(i18nInstance: I18nInstance | undefined, setForceUpdate: React.Dispatch<React.SetStateAction<number>>): void;
16
15
  /**
@@ -22,5 +21,5 @@ export declare function useSdkResourcesLoader(i18nInstance: I18nInstance | undef
22
21
  * In SSR/SSG scenarios, server-side middleware handles redirects, so this hook is skipped.
23
22
  * We use process.env.MODERN_TARGET to ensure this code is only included in browser bundles.
24
23
  */
25
- export declare function useClientSideRedirect(i18nInstance: I18nInstance | undefined, localePathRedirect: boolean, languages: string[], fallbackLanguage: string, ignoreRedirectRoutes?: string[] | ((pathname: string) => boolean), localisedUrls?: LocalisedUrlsOption): void;
24
+ export declare function useClientSideRedirect(i18nInstance: I18nInstance | undefined, localePathRedirect: boolean, languages: string[], fallbackLanguage: string, ignoreRedirectRoutes?: string[] | ((pathname: string) => boolean), urlStrategy?: I18nUrlStrategy): void;
26
25
  export declare function useLanguageSync(i18nInstance: I18nInstance | undefined, localePathRedirect: boolean, languages: string[], pathname: string | undefined, prevLangRef: React.MutableRefObject<string>, setLang: (lang: string) => void): (currentLang: string) => void;
@@ -1,11 +1,11 @@
1
- import { type LocalisedUrlsOption } from '@modern-js/i18n-runtime-extensions';
1
+ import type { I18nUrlStrategy } from '../shared/urlStrategy.js';
2
2
  export interface LocalizedPathsConfig {
3
3
  languages: string[];
4
- localisedUrls?: LocalisedUrlsOption;
4
+ urlStrategy?: I18nUrlStrategy;
5
5
  }
6
6
  /**
7
7
  * Localize a canonical, language-agnostic target for the given language:
8
- * adds the language prefix and applies `localisedUrls` pattern mapping.
8
+ * adds the language prefix and applies the configured URL strategy.
9
9
  * `?search`/`#hash` suffixes are preserved verbatim.
10
10
  */
11
11
  export declare const localizePath: (pathname: string, language: string, config: LocalizedPathsConfig) => string;
@@ -21,7 +21,7 @@ export interface UseLocalizedPathsReturn {
21
21
  }
22
22
  /**
23
23
  * Context-bound versions of {@link localizePath} and {@link canonicalPath} —
24
- * the plugin configuration (languages, localisedUrls) is read from the i18n
24
+ * the languages and URL strategy are read from the i18n
25
25
  * provider, so apps never copy pattern-matching helpers again.
26
26
  */
27
27
  export declare const useLocalizedPaths: () => UseLocalizedPathsReturn;
@@ -1,6 +1,16 @@
1
1
  import type React from 'react';
2
2
  import type { BaseLocaleDetectionOptions } from '../shared/type.js';
3
+ import type { I18nUrlStrategy } from '../shared/urlStrategy.js';
3
4
  import type { I18nInstance } from './i18n/index.js';
5
+ export interface I18nLanguageSynchronizationProps {
6
+ i18nInstance: I18nInstance | undefined;
7
+ localePathRedirect: boolean;
8
+ languages: string[];
9
+ pathname: string | undefined;
10
+ prevLangRef: React.MutableRefObject<string>;
11
+ setLang: (language: string) => void;
12
+ children: (synchronizeLanguage: (language: string) => void) => React.ReactNode;
13
+ }
4
14
  interface I18nRootWrapperOptions {
5
15
  entryName?: string;
6
16
  htmlLangAttr: boolean;
@@ -8,7 +18,9 @@ interface I18nRootWrapperOptions {
8
18
  languages: string[];
9
19
  fallbackLanguage: string;
10
20
  ignoreRedirectRoutes?: BaseLocaleDetectionOptions['ignoreRedirectRoutes'];
11
- localisedUrls?: BaseLocaleDetectionOptions['localisedUrls'];
21
+ urlStrategy?: I18nUrlStrategy;
22
+ NavigationProvider?: React.ComponentType<React.PropsWithChildren>;
23
+ LanguageSynchronization?: React.ComponentType<I18nLanguageSynchronizationProps>;
12
24
  getLatestI18nInstance: () => I18nInstance | undefined;
13
25
  getI18nextProvider: () => React.ComponentType<any> | null | undefined;
14
26
  }
@@ -1,27 +1,44 @@
1
1
  import type React from 'react';
2
- type I18nRouterFramework = 'react-router' | 'tanstack' | string;
3
2
  interface I18nRouterLocation {
4
3
  pathname: string;
5
4
  search: string;
6
5
  hash: string;
7
6
  }
8
- interface I18nRouterNavigateOptions {
7
+ type I18nRouterNavigate = (href: string, options?: {
9
8
  replace?: boolean;
10
9
  state?: unknown;
11
- }
12
- type I18nRouterNavigate = (href: string, options?: I18nRouterNavigateOptions) => void | Promise<void>;
10
+ }) => void | Promise<void>;
13
11
  type I18nRouterLink = React.ComponentType<{
14
12
  to: string;
15
13
  children?: React.ReactNode;
16
14
  [key: string]: unknown;
17
15
  }>;
18
- interface I18nRouterAdapter {
19
- framework?: I18nRouterFramework;
16
+ export interface I18nRouterLinkTarget {
17
+ pathname: string;
18
+ href: string;
19
+ search?: Record<string, unknown>;
20
+ hash?: string;
21
+ hashScrollIntoView?: boolean | ScrollIntoViewOptions;
22
+ prefetch?: 'intent' | 'render' | 'viewport' | 'none';
23
+ preload?: unknown;
24
+ }
25
+ export interface I18nRouterAdapter {
26
+ framework?: string;
20
27
  hasRouter: boolean;
21
28
  location: I18nRouterLocation | null;
22
29
  navigate: I18nRouterNavigate | null;
23
30
  Link: I18nRouterLink | null;
24
31
  params: Record<string, string>;
32
+ /** Convert an already resolved target to the selected router's own props. */
33
+ createLinkProps?: (target: I18nRouterLinkTarget) => {
34
+ to: string;
35
+ [key: string]: unknown;
36
+ };
25
37
  }
38
+ export declare const I18nNavigationProvider: ({ children, value, }: React.PropsWithChildren<{
39
+ value: I18nRouterAdapter;
40
+ }>) => React.JSX.Element;
41
+ /** Read native router hooks only when their own provider is present. */
42
+ export declare const useNativeI18nRouterAdapter: () => I18nRouterAdapter;
26
43
  export declare const useI18nRouterAdapter: () => I18nRouterAdapter;
27
44
  export {};
@@ -1,4 +1,5 @@
1
- import { type LocalisedUrlsOption } from '@modern-js/i18n-runtime-extensions';
1
+ import type { I18nUrlStrategy } from '../shared/urlStrategy.js';
2
+ export { splitUrlTarget } from '@modern-js/runtime-utils/url';
2
3
  export declare const getPathname: (context: {
3
4
  ssrContext?: {
4
5
  request?: {
@@ -15,15 +16,6 @@ export declare const getEntryPath: () => string;
15
16
  * @returns The detected language or fallback language
16
17
  */
17
18
  export declare const getLanguageFromPath: (pathname: string, languages: string[], fallbackLanguage: string) => string;
18
- /**
19
- * Split a link target into its pathname, search and hash parts without
20
- * relying on `new URL` (SSR-hot path; targets are relative).
21
- */
22
- export declare const splitUrlTarget: (target: string) => {
23
- pathname: string;
24
- search: string;
25
- hash: string;
26
- };
27
19
  /**
28
20
  * Helper function to build localized URL
29
21
  * @param target - The language-agnostic target; may include `?search` and `#hash`
@@ -31,7 +23,7 @@ export declare const splitUrlTarget: (target: string) => {
31
23
  * @param languages - Array of supported languages
32
24
  * @returns The localized URL path with search and hash re-appended verbatim
33
25
  */
34
- export declare const buildLocalizedUrl: (target: string, language: string, languages: string[], localisedUrls?: LocalisedUrlsOption) => string;
26
+ export declare const buildLocalizedUrl: (target: string, language: string, languages: string[], urlStrategy?: I18nUrlStrategy) => string;
35
27
  export declare const detectLanguageFromPath: (pathname: string, languages: string[], localePathRedirect: boolean) => {
36
28
  detected: boolean;
37
29
  language?: string;
@@ -39,4 +31,4 @@ export declare const detectLanguageFromPath: (pathname: string, languages: strin
39
31
  /**
40
32
  * Check if the given pathname should ignore automatic locale redirect
41
33
  */
42
- export declare const shouldIgnoreRedirect: (pathname: string, languages: string[], ignoreRedirectRoutes?: string[] | ((pathname: string) => boolean)) => boolean;
34
+ export declare const shouldIgnoreRedirect: (pathname: string, languages: string[], ignoreRedirectRoutes?: string[] | ((pathname: string) => boolean), urlStrategy?: I18nUrlStrategy) => boolean;