@bleedingdev/modern-js-plugin-i18n 3.9.0-ultramodern.2 → 3.9.0-ultramodern.20

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 (127) hide show
  1. package/dist/cjs/cli/index.js +10 -21
  2. package/dist/cjs/cli/localisedRoutes.js +47 -0
  3. package/dist/cjs/runtime/Link.js +19 -32
  4. package/dist/cjs/runtime/context.js +30 -73
  5. package/dist/cjs/runtime/contextHelpers.js +5 -5
  6. package/dist/cjs/runtime/contexts.js +49 -0
  7. package/dist/cjs/runtime/core.js +27 -14
  8. package/dist/cjs/runtime/hooks.js +7 -8
  9. package/dist/cjs/runtime/localizedPaths.js +11 -9
  10. package/dist/cjs/runtime/navigation.js +48 -0
  11. package/dist/cjs/runtime/providerComposition.js +37 -13
  12. package/dist/cjs/runtime/routerAdapter.js +33 -140
  13. package/dist/cjs/runtime/sharedContexts.js +43 -0
  14. package/dist/cjs/runtime/utils.js +21 -19
  15. package/dist/cjs/server/defaultUrlStrategy.js +48 -0
  16. package/dist/cjs/server/index.js +11 -7
  17. package/dist/cjs/server/mappedUrlStrategy.js +43 -0
  18. package/dist/cjs/server/redirectPolicy.js +33 -24
  19. package/dist/cjs/shared/mappedUrlStrategy.js +63 -0
  20. package/dist/cjs/shared/urlStrategy.js +48 -0
  21. package/dist/esm/cli/index.mjs +10 -21
  22. package/dist/esm/cli/localisedRoutes.mjs +9 -0
  23. package/dist/esm/runtime/Link.mjs +19 -32
  24. package/dist/esm/runtime/context.mjs +20 -72
  25. package/dist/esm/runtime/contextHelpers.mjs +5 -5
  26. package/dist/esm/runtime/contexts.mjs +5 -0
  27. package/dist/esm/runtime/core.mjs +13 -6
  28. package/dist/esm/runtime/hooks.mjs +7 -8
  29. package/dist/esm/runtime/localizedPaths.mjs +11 -9
  30. package/dist/esm/runtime/navigation.mjs +7 -0
  31. package/dist/esm/runtime/providerComposition.mjs +38 -14
  32. package/dist/esm/runtime/routerAdapter.mjs +28 -141
  33. package/dist/esm/runtime/sharedContexts.mjs +1 -0
  34. package/dist/esm/runtime/utils.mjs +19 -17
  35. package/dist/esm/server/defaultUrlStrategy.mjs +7 -0
  36. package/dist/esm/server/index.mjs +11 -7
  37. package/dist/esm/server/mappedUrlStrategy.mjs +1 -0
  38. package/dist/esm/server/redirectPolicy.mjs +33 -24
  39. package/dist/esm/shared/mappedUrlStrategy.mjs +19 -0
  40. package/dist/esm/shared/urlStrategy.mjs +7 -0
  41. package/dist/esm-node/cli/index.mjs +10 -21
  42. package/dist/esm-node/cli/localisedRoutes.mjs +10 -0
  43. package/dist/esm-node/runtime/Link.mjs +19 -32
  44. package/dist/esm-node/runtime/context.mjs +20 -72
  45. package/dist/esm-node/runtime/contextHelpers.mjs +5 -5
  46. package/dist/esm-node/runtime/contexts.mjs +6 -0
  47. package/dist/esm-node/runtime/core.mjs +13 -6
  48. package/dist/esm-node/runtime/hooks.mjs +7 -8
  49. package/dist/esm-node/runtime/localizedPaths.mjs +11 -9
  50. package/dist/esm-node/runtime/navigation.mjs +8 -0
  51. package/dist/esm-node/runtime/providerComposition.mjs +38 -14
  52. package/dist/esm-node/runtime/routerAdapter.mjs +28 -141
  53. package/dist/esm-node/runtime/sharedContexts.mjs +2 -0
  54. package/dist/esm-node/runtime/utils.mjs +19 -17
  55. package/dist/esm-node/server/defaultUrlStrategy.mjs +8 -0
  56. package/dist/esm-node/server/index.mjs +11 -7
  57. package/dist/esm-node/server/mappedUrlStrategy.mjs +2 -0
  58. package/dist/esm-node/server/redirectPolicy.mjs +33 -24
  59. package/dist/esm-node/shared/mappedUrlStrategy.mjs +20 -0
  60. package/dist/esm-node/shared/urlStrategy.mjs +8 -0
  61. package/dist/types/cli/localisedRoutes.d.ts +19 -0
  62. package/dist/types/runtime/context.d.ts +8 -11
  63. package/dist/types/runtime/contextHelpers.d.ts +2 -2
  64. package/dist/types/runtime/contexts.d.ts +6 -0
  65. package/dist/types/runtime/core.d.ts +12 -2
  66. package/dist/types/runtime/hooks.d.ts +4 -5
  67. package/dist/types/runtime/localizedPaths.d.ts +4 -4
  68. package/dist/types/runtime/navigation.d.ts +10 -0
  69. package/dist/types/runtime/providerComposition.d.ts +13 -1
  70. package/dist/types/runtime/routerAdapter.d.ts +23 -6
  71. package/dist/types/runtime/sharedContexts.d.ts +1 -0
  72. package/dist/types/runtime/utils.d.ts +4 -12
  73. package/dist/types/server/defaultUrlStrategy.d.ts +11 -0
  74. package/dist/types/server/index.d.ts +2 -0
  75. package/dist/types/server/mappedUrlStrategy.d.ts +7 -0
  76. package/dist/types/server/redirectPolicy.d.ts +5 -13
  77. package/dist/types/shared/mappedUrlStrategy.d.ts +27 -0
  78. package/dist/types/shared/type.d.ts +7 -11
  79. package/dist/types/shared/urlStrategy.d.ts +18 -0
  80. package/package.json +42 -19
  81. package/rslib.config.mts +8 -1
  82. package/rstest.config.mts +6 -5
  83. package/src/cli/index.ts +42 -42
  84. package/src/cli/localisedRoutes.ts +53 -0
  85. package/src/runtime/Link.tsx +20 -40
  86. package/src/runtime/context.tsx +33 -157
  87. package/src/runtime/contextHelpers.ts +7 -5
  88. package/src/runtime/contexts.ts +16 -0
  89. package/src/runtime/core.tsx +53 -6
  90. package/src/runtime/hooks.ts +14 -9
  91. package/src/runtime/i18n/instance.ts +1 -2
  92. package/src/runtime/localizedPaths.ts +24 -19
  93. package/src/runtime/navigation.tsx +20 -0
  94. package/src/runtime/providerComposition.tsx +71 -23
  95. package/src/runtime/routerAdapter.tsx +65 -339
  96. package/src/runtime/sharedContexts.ts +8 -0
  97. package/src/runtime/utils.ts +49 -31
  98. package/src/server/defaultUrlStrategy.ts +27 -0
  99. package/src/server/index.ts +39 -9
  100. package/src/server/mappedUrlStrategy.ts +10 -0
  101. package/src/server/redirectPolicy.ts +85 -70
  102. package/src/shared/mappedUrlStrategy.ts +59 -0
  103. package/src/shared/type.ts +7 -11
  104. package/src/shared/urlStrategy.ts +38 -0
  105. package/tests/backendDefaults.test.ts +2 -23
  106. package/tests/defaultUrlStrategy.test.ts +107 -0
  107. package/tests/federatedI18nBoundaryResolver.test.tsx +65 -0
  108. package/tests/i18nUtils.test.ts +31 -65
  109. package/tests/link.test.tsx +13 -511
  110. package/tests/localisedRouteGeneration.test.ts +200 -0
  111. package/tests/localisedUrls.test.ts +16 -208
  112. package/tests/mappedUrlStrategyDerivation.test.ts +62 -0
  113. package/tests/navigation.test.tsx +403 -0
  114. package/tests/reactI18nextRuntimeBoundary.test.ts +8 -83
  115. package/tests/redirectPolicy.test.ts +89 -27
  116. package/tests/routerAdapter.test.tsx +98 -1171
  117. package/tests/urlStrategySerialization.test.ts +122 -0
  118. package/tsconfig.json +4 -2
  119. package/tests/federatedI18nBoundary.client.test.tsx +0 -129
  120. package/tests/federatedI18nBoundary.test.tsx +0 -132
  121. package/tests/linkTypes.test.ts +0 -59
  122. package/tests/localisedUrlRewriteMatrix.fork.test.ts +0 -147
  123. package/tests/peerCohort.test.ts +0 -25
  124. package/tests/type-fixture/fixture-globals.d.ts +0 -11
  125. package/tests/type-fixture/i18nInstanceTypes.fixture.ts +0 -29
  126. package/tests/type-fixture/linkTypes.fixture.tsx +0 -51
  127. package/tests/type-fixture/tsconfig.json +0 -16
@@ -1,151 +1,38 @@
1
1
  import "node:module";
2
+ import { jsx } from "react/jsx-runtime";
3
+ import { I18nNavigationContext } from "@modern-js/plugin-i18n/runtime/contexts";
2
4
  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 = ()=>{
5
+ import { InternalRuntimeContext } from "@modern-js/runtime/context";
6
+ import { useContext } from "react";
7
+ const I18nNavigationProvider = ({ children, value })=>/*#__PURE__*/ jsx(I18nNavigationContext.Provider, {
8
+ value: value,
9
+ children: children
10
+ });
11
+ const useNativeI18nRouterAdapter = ()=>{
64
12
  const runtimeContext = useContext(RuntimeContext);
65
13
  const internalContext = useContext(InternalRuntimeContext);
66
14
  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;
15
+ const hasRouter = routerApi?.useInRouterContext?.() ?? false;
16
+ const navigate = hasRouter ? routerApi?.useNavigate?.() ?? null : null;
17
+ const routerLocation = hasRouter ? routerApi?.useLocation?.() ?? null : null;
18
+ const params = hasRouter ? routerApi?.useParams?.() ?? {} : {};
19
+ const location = routerLocation ?? (isBrowser() ? {
20
+ pathname: window.location.pathname,
21
+ search: window.location.search,
22
+ hash: window.location.hash
23
+ } : null);
142
24
  return {
143
- framework,
25
+ framework: hasRouter ? 'react-router' : void 0,
144
26
  hasRouter,
27
+ navigate,
145
28
  location,
146
- navigate: hasRouter ? navigate : null,
147
- Link,
148
- params
29
+ params,
30
+ Link: hasRouter ? routerApi?.Link ?? null : null
149
31
  };
150
32
  };
151
- export { useI18nRouterAdapter };
33
+ const useI18nRouterAdapter = ()=>{
34
+ const provided = useContext(I18nNavigationContext);
35
+ const native = useNativeI18nRouterAdapter();
36
+ return provided ?? native;
37
+ };
38
+ export { I18nNavigationProvider, useI18nRouterAdapter, useNativeI18nRouterAdapter };
@@ -0,0 +1,2 @@
1
+ import "node:module";
2
+ export { ModernI18nContext, ReactI18nextProviderContext } from "@modern-js/plugin-i18n/runtime/contexts";
@@ -1,7 +1,9 @@
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
+ import { isDefaultLocaleRedirectSkipPath } from "../shared/mappedUrlStrategy.mjs";
6
+ import { asI18nUrlStrategy } from "../shared/urlStrategy.mjs";
5
7
  const getPathname = (context)=>{
6
8
  if (isBrowser()) return window.location.pathname;
7
9
  return context.ssrContext?.request?.pathname || '/';
@@ -17,22 +19,14 @@ const getLanguageFromPath = (pathname, languages, fallbackLanguage)=>{
17
19
  if (languages.includes(firstSegment)) return firstSegment;
18
20
  return fallbackLanguage;
19
21
  };
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)=>{
22
+ const buildLocalizedUrl = (target, language, languages, urlStrategy)=>{
34
23
  const { pathname, search, hash } = splitUrlTarget(target);
35
- const localizedPathname = localiseTargetPathname(pathname, language, languages, localisedUrls);
24
+ const strategy = asI18nUrlStrategy(urlStrategy);
25
+ if (strategy) return `${strategy.localizePathname(pathname, language, languages)}${search}${hash}`;
26
+ const segments = pathname.split('/').filter(Boolean);
27
+ if (segments[0] && languages.some((item)=>item.toLowerCase() === segments[0].toLowerCase())) segments[0] = language;
28
+ else segments.unshift(language);
29
+ const localizedPathname = `/${segments.join('/')}`;
36
30
  return `${localizedPathname}${search}${hash}`;
37
31
  };
38
32
  const detectLanguageFromPath = (pathname, languages, localePathRedirect)=>{
@@ -52,5 +46,13 @@ const detectLanguageFromPath = (pathname, languages, localePathRedirect)=>{
52
46
  detected: false
53
47
  };
54
48
  };
55
- const shouldIgnoreRedirect = (pathname, languages, ignoreRedirectRoutes)=>shouldSkipLocaleRedirect(pathname, languages, ignoreRedirectRoutes);
49
+ const shouldIgnoreRedirect = (pathname, languages, ignoreRedirectRoutes, urlStrategy)=>{
50
+ if (isDefaultLocaleRedirectSkipPath(pathname, languages)) return true;
51
+ if (asI18nUrlStrategy(urlStrategy)?.shouldSkipRedirect?.(pathname, languages)) return true;
52
+ if (!ignoreRedirectRoutes) return false;
53
+ const segments = pathname.split('/').filter(Boolean);
54
+ if (segments[0] && languages.some((item)=>item.toLowerCase() === segments[0].toLowerCase())) segments.shift();
55
+ const normalizedPath = `/${segments.join('/')}`;
56
+ return 'function' == typeof ignoreRedirectRoutes ? ignoreRedirectRoutes(normalizedPath) : ignoreRedirectRoutes.some((pattern)=>normalizedPath === pattern || normalizedPath.startsWith(`${pattern}/`));
57
+ };
56
58
  export { buildLocalizedUrl, detectLanguageFromPath, getEntryPath, getLanguageFromPath, getPathname, shouldIgnoreRedirect, splitUrlTarget };
@@ -0,0 +1,8 @@
1
+ import "node:module";
2
+ import { createMappedUrlStrategy } from "./mappedUrlStrategy.mjs";
3
+ const createDefaultUrlStrategy = (localisedUrls)=>createMappedUrlStrategy(localisedUrls);
4
+ const resolveDefaultUrlStrategy = (localisedUrls)=>{
5
+ if (!localisedUrls || 'object' != typeof localisedUrls || 0 === Object.keys(localisedUrls).length) return;
6
+ return createDefaultUrlStrategy(localisedUrls);
7
+ };
8
+ export { createDefaultUrlStrategy, resolveDefaultUrlStrategy };
@@ -1,7 +1,8 @@
1
1
  import "node:module";
2
- import { resolveLocalisedUrlsConfig } from "@modern-js/i18n-runtime-extensions";
2
+ import { asI18nUrlStrategy } from "../shared/urlStrategy.mjs";
3
3
  import { getLocaleDetectionOptions } from "../shared/utils.mjs";
4
4
  import { collectApiPrefixes, matchesApiPrefix } from "./apiPrefix.mjs";
5
+ import { resolveDefaultUrlStrategy } from "./defaultUrlStrategy.mjs";
5
6
  import { convertToHonoLanguageDetectorOptions } from "./detectorOptions.mjs";
6
7
  import { buildLocalizedUrl, createLocaleRedirectResponse, getLanguageFromPath, isStaticResourceRequest, shouldIgnoreRedirect } from "./redirectPolicy.mjs";
7
8
  import * as __rspack_external__modern_js_server_core_hono_0af3baa7 from "@modern-js/server-core/hono";
@@ -25,7 +26,10 @@ const i18nServerPlugin = (options)=>({
25
26
  const { entryName } = route;
26
27
  if (!entryName) return;
27
28
  if (!options.localeDetection) return;
28
- const { localePathRedirect, i18nextDetector = true, languages = [], fallbackLanguage = 'en', detection, ignoreRedirectRoutes, localisedUrls } = getLocaleDetectionOptions(entryName, options.localeDetection);
29
+ const entryLocaleDetection = getLocaleDetectionOptions(entryName, options.localeDetection);
30
+ const { localePathRedirect, i18nextDetector = true, languages = [], fallbackLanguage = 'en', detection, ignoreRedirectRoutes } = entryLocaleDetection;
31
+ const legacyLocalisedUrls = Reflect.get(entryLocaleDetection, 'localisedUrls');
32
+ const urlStrategy = asI18nUrlStrategy(options.resolveUrlStrategy?.(entryName)) ?? resolveDefaultUrlStrategy(legacyLocalisedUrls);
29
33
  const staticRoutePrefixes = options.staticRoutePrefixes;
30
34
  const originUrlPath = route.urlPath;
31
35
  const urlPath = originUrlPath.endsWith('/') ? `${originUrlPath}*` : `${originUrlPath}/*`;
@@ -40,6 +44,7 @@ const i18nServerPlugin = (options)=>({
40
44
  const url = new URL(c.req.url);
41
45
  const pathname = url.pathname;
42
46
  if (matchesApiPrefix(pathname, apiPrefixes)) return await next();
47
+ if (shouldIgnoreRedirect(pathname, urlPath, ignoreRedirectRoutes, urlStrategy, languages)) return await next();
43
48
  if (isStaticResourceRequest(pathname, staticRoutePrefixes, languages)) return await next();
44
49
  if ('/' === originUrlPath) {
45
50
  const pathSegments = pathname.split('/').filter(Boolean);
@@ -60,7 +65,7 @@ const i18nServerPlugin = (options)=>({
60
65
  const pathname = url.pathname;
61
66
  if (matchesApiPrefix(pathname, apiPrefixes)) return await next();
62
67
  if (isStaticResourceRequest(pathname, staticRoutePrefixes, languages)) return await next();
63
- if (shouldIgnoreRedirect(pathname, urlPath, ignoreRedirectRoutes)) return await next();
68
+ if (shouldIgnoreRedirect(pathname, urlPath, ignoreRedirectRoutes, urlStrategy, languages)) return await next();
64
69
  if ('/' === originUrlPath) {
65
70
  const pathSegments = pathname.split('/').filter(Boolean);
66
71
  if (pathSegments.length > 0) {
@@ -73,12 +78,11 @@ const i18nServerPlugin = (options)=>({
73
78
  let detectedLanguage = null;
74
79
  if (i18nextDetector) detectedLanguage = c.get('language') || null;
75
80
  const targetLanguage = detectedLanguage || fallbackLanguage;
76
- const localizedUrl = buildLocalizedUrl(c.req, originUrlPath, targetLanguage, languages, localisedUrls);
81
+ const localizedUrl = buildLocalizedUrl(c.req, originUrlPath, targetLanguage, languages, urlStrategy);
77
82
  return createLocaleRedirectResponse(localizedUrl);
78
83
  }
79
- const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
80
- if (localisedUrlsConfig.enabled) {
81
- const expectedUrl = buildLocalizedUrl(c.req, originUrlPath, language, languages, localisedUrls);
84
+ if (urlStrategy) {
85
+ const expectedUrl = buildLocalizedUrl(c.req, originUrlPath, language, languages, urlStrategy);
82
86
  if (expectedUrl !== `${pathname}${url.search}${url.hash}`) return createLocaleRedirectResponse(expectedUrl);
83
87
  }
84
88
  await next();
@@ -0,0 +1,2 @@
1
+ import "node:module";
2
+ export { createMappedUrlStrategy, resolveMappedUrlStrategy } from "../shared/mappedUrlStrategy.mjs";
@@ -1,40 +1,49 @@
1
1
  import "node:module";
2
- import { isDefaultLocaleRedirectSkipPath, localiseTargetPathname, matchesPathPrefix, shouldSkipLocaleRedirect, stripLanguagePrefix } from "@modern-js/i18n-runtime-extensions";
2
+ import { isDefaultLocaleRedirectSkipPath } from "../shared/mappedUrlStrategy.mjs";
3
+ import { asI18nUrlStrategy } from "../shared/urlStrategy.mjs";
3
4
  const stripUrlPathPrefix = (pathname, urlPath)=>{
4
5
  const basePath = urlPath.replace('/*', '');
5
6
  if (!basePath || '/' === basePath) return pathname;
6
- const remainingPath = pathname.startsWith(basePath) ? pathname.slice(basePath.length) : pathname;
7
- return remainingPath || '/';
7
+ return pathname === basePath || pathname.startsWith(`${basePath}/`) ? pathname.slice(basePath.length) || '/' : pathname;
8
8
  };
9
- const shouldIgnoreRedirect = (pathname, urlPath, ignoreRedirectRoutes)=>{
9
+ const shouldIgnoreRedirect = (pathname, urlPath, ignoreRedirectRoutes, urlStrategy, languages = [])=>{
10
10
  const remainingPath = stripUrlPathPrefix(pathname, urlPath);
11
- return shouldSkipLocaleRedirect(remainingPath, [], ignoreRedirectRoutes);
11
+ if (isDefaultLocaleRedirectSkipPath(remainingPath, languages)) return true;
12
+ if (asI18nUrlStrategy(urlStrategy)?.shouldSkipRedirect?.(remainingPath, languages)) return true;
13
+ if (!ignoreRedirectRoutes) return false;
14
+ const segments = remainingPath.split('/').filter(Boolean);
15
+ if (segments[0] && languages.some((language)=>language.toLowerCase() === segments[0].toLowerCase())) segments.shift();
16
+ const normalizedPath = `/${segments.join('/')}`;
17
+ return 'function' == typeof ignoreRedirectRoutes ? ignoreRedirectRoutes(normalizedPath) : ignoreRedirectRoutes.some((pattern)=>normalizedPath === pattern || normalizedPath.startsWith(`${pattern}/`));
12
18
  };
13
19
  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);
20
+ const prefixes = [
21
+ ...staticRoutePrefixes,
22
+ '/static',
23
+ '/upload'
24
+ ];
25
+ const matches = (target)=>prefixes.some((prefix)=>target === prefix || target.startsWith(`${prefix}/`));
26
+ if (matches(pathname)) return true;
27
+ const segments = pathname.split('/').filter(Boolean);
28
+ if (segments[0] && languages.some((language)=>language.toLowerCase() === segments[0].toLowerCase())) return matches(`/${segments.slice(1).join('/')}`);
29
+ return false;
19
30
  };
20
31
  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;
32
+ const host = req.header?.().host;
33
+ const url = new URL(req.url, host ? `http://${host}` : void 0);
34
+ const firstSegment = stripUrlPathPrefix(url.pathname, urlPath).split('/').filter(Boolean)[0];
35
+ return languages.find((language)=>language.toLowerCase() === firstSegment?.toLowerCase()) ?? null;
28
36
  };
29
- const buildLocalizedUrl = (req, urlPath, language, languages, localisedUrls)=>{
37
+ const buildLocalizedUrl = (req, urlPath, language, languages, urlStrategy)=>{
30
38
  const url = new URL(req.url);
31
- const pathname = url.pathname;
32
39
  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;
40
+ const remainingPath = stripUrlPathPrefix(url.pathname, urlPath);
41
+ const segments = remainingPath.split('/').filter(Boolean);
42
+ if (segments[0] && languages.some((item)=>item.toLowerCase() === segments[0].toLowerCase())) segments[0] = language;
43
+ else segments.unshift(language);
44
+ const strategy = asI18nUrlStrategy(urlStrategy);
45
+ const pathname = strategy ? strategy.localizePathname(remainingPath, language, languages) : `/${segments.join('/')}`;
46
+ return `${'/' === basePath ? '' : basePath}${pathname}${url.search}${url.hash}`;
38
47
  };
39
48
  const createLocaleRedirectResponse = (location)=>new Response(null, {
40
49
  status: 302,
@@ -0,0 +1,20 @@
1
+ import "node:module";
2
+ import { canonicalTargetPathname, isDefaultLocaleRedirectSkipPath, localiseTargetPathname } from "@modern-js/i18n-runtime-extensions";
3
+ const createMappedUrlStrategy = (localisedUrls)=>({
4
+ localizePathname: (pathname, language, languages)=>localiseTargetPathname(pathname, language, [
5
+ ...languages
6
+ ], localisedUrls),
7
+ canonicalPathname: (pathname, languages)=>canonicalTargetPathname(pathname, [
8
+ ...languages
9
+ ], localisedUrls),
10
+ shouldSkipRedirect: (pathname, languages)=>isDefaultLocaleRedirectSkipPath(pathname, [
11
+ ...languages
12
+ ])
13
+ });
14
+ const resolveMappedUrlStrategy = (localeDetection)=>{
15
+ if (!localeDetection || 'object' != typeof localeDetection) return;
16
+ const localisedUrls = Reflect.get(localeDetection, 'localisedUrls');
17
+ if (!localisedUrls || 'object' != typeof localisedUrls || 0 === Object.keys(localisedUrls).length) return;
18
+ return createMappedUrlStrategy(localisedUrls);
19
+ };
20
+ export { createMappedUrlStrategy, isDefaultLocaleRedirectSkipPath, resolveMappedUrlStrategy };
@@ -0,0 +1,8 @@
1
+ import "node:module";
2
+ const asI18nUrlStrategy = (candidate)=>{
3
+ if (!candidate || 'object' != typeof candidate) return;
4
+ const strategy = candidate;
5
+ return 'function' == typeof strategy.localizePathname && 'function' == typeof strategy.canonicalPathname ? strategy : void 0;
6
+ };
7
+ const isUnusableI18nUrlStrategy = (candidate)=>Boolean(candidate) && 'object' == typeof candidate && void 0 === asI18nUrlStrategy(candidate);
8
+ export { asI18nUrlStrategy, isUnusableI18nUrlStrategy };
@@ -0,0 +1,19 @@
1
+ import { getEntrypointRoutesOwner } from '@modern-js/runtime/cli';
2
+ import type { Entrypoint, NestedRouteForCli, PageRoute } from '@modern-js/types';
3
+ import type { BaseLocaleDetectionOptions } from '../shared/type.js';
4
+ type FileSystemRoutes = (NestedRouteForCli | PageRoute)[];
5
+ /**
6
+ * Expand file-system routes from `localeDetection.localisedUrls`.
7
+ *
8
+ * Fork-owned: the localised-URL engine lives in
9
+ * `@modern-js/i18n-runtime-extensions`, which upstream-owned files must not
10
+ * import. `cli/index.ts` calls this through a relative import so the seam, not
11
+ * the edge, is what appears in the upstream-shaped file.
12
+ *
13
+ * Returns the routes unchanged unless locale-path redirects are on, languages
14
+ * are declared, and a non-empty map is configured — an upstream-style config
15
+ * with `localePathRedirect` and `languages` but no map keeps plain
16
+ * locale-prefix behaviour.
17
+ */
18
+ export declare const applyLocalisedRoutes: (routes: FileSystemRoutes, localeDetection: BaseLocaleDetectionOptions | undefined, entrypoint?: Entrypoint & Parameters<typeof getEntrypointRoutesOwner>[0]) => FileSystemRoutes;
19
+ export {};
@@ -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
+ import { ModernI18nContext, ReactI18nextProviderContext } from './sharedContexts.js';
6
+ export { getActualI18nextInstance } from './i18n/instance.js';
7
+ export interface ModernI18nContextValue {
6
8
  language: string;
7
9
  i18nInstance: I18nInstance;
8
10
  entryName?: string;
9
11
  languages?: string[];
10
12
  localePathRedirect?: boolean;
11
13
  ignoreRedirectRoutes?: string[] | ((pathname: string) => boolean);
12
- localisedUrls?: LocalisedUrlsOption;
14
+ urlStrategy?: I18nUrlStrategy;
13
15
  updateLanguage?: (newLang: string) => void;
14
16
  synchronizeLanguage?: (newLang: string) => void;
15
17
  }
16
- interface ModernI18nProviderProps {
18
+ export { ModernI18nContext, ReactI18nextProviderContext };
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;
@@ -0,0 +1,6 @@
1
+ import type { ComponentType } from 'react';
2
+ import type { ModernI18nContextValue } from './context.js';
3
+ import type { I18nRouterAdapter } from './routerAdapter.js';
4
+ export declare const ModernI18nContext: import("react").Context<ModernI18nContextValue | null>;
5
+ export declare const ReactI18nextProviderContext: import("react").Context<ComponentType<any> | null>;
6
+ export declare const I18nNavigationContext: import("react").Context<I18nRouterAdapter | null>;
@@ -1,11 +1,18 @@
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';
13
+ export { I18nRouterNavigationProvider, useIntegratedRouterAdapter, } from './navigation.js';
8
14
  export type { LoadReactI18nextIntegration, ReactI18nextIntegration, } from './reactI18next.js';
15
+ export { I18nNavigationProvider, type I18nRouterAdapter, type I18nRouterLinkTarget, useI18nRouterAdapter, useNativeI18nRouterAdapter, } from './routerAdapter.js';
9
16
  export interface I18nPluginOptions {
10
17
  entryName?: string;
11
18
  localeDetection?: BaseLocaleDetectionOptions;
@@ -15,6 +22,9 @@ export interface I18nPluginOptions {
15
22
  initOptions?: I18nInitOptions;
16
23
  htmlLangAttr?: boolean;
17
24
  reactI18next?: boolean;
25
+ urlStrategy?: I18nUrlStrategy;
26
+ NavigationProvider?: React.ComponentType<React.PropsWithChildren>;
27
+ LanguageSynchronization?: React.ComponentType<I18nLanguageSynchronizationProps>;
18
28
  [key: string]: any;
19
29
  }
20
30
  export declare const createI18nPlugin: (loadReactI18nextIntegration?: LoadReactI18nextIntegration) => ((options: I18nPluginOptions) => RuntimePlugin);
@@ -22,5 +32,5 @@ export type { AllowedLinkTarget, CanonicalRoutePath, UltramodernCanonicalRoutes,
22
32
  export { FederatedI18nBoundary, type FederatedI18nBoundaryProps, type UseModernI18nReturn, useModernI18n, } from './context.js';
23
33
  export { I18nLink, type I18nLinkProps } from './I18nLink.js';
24
34
  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';
35
+ export { type LocalizedPathsConfig, type UseLocalizedLocationReturn, type UseLocalizedPathsReturn, useLocalizedLocation, useLocalizedPaths, } from './localizedPaths.js';
36
+ 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;
@@ -0,0 +1,10 @@
1
+ import { type I18nRouterAdapter } from './routerAdapter.js';
2
+ /**
3
+ * The seam, and only the seam. The selected-router navigation adapter is a
4
+ * fork subsystem, so it lives in the fork-owned
5
+ * `@modern-js/i18n-runtime-extensions` and is attached here through the
6
+ * `NavigationProvider` extension point this package already exposes. The
7
+ * factory takes this package's own primitives as arguments, so the fork
8
+ * package never imports back into it and the dependency stays one-way.
9
+ */
10
+ export declare const I18nRouterNavigationProvider: ({ children, }: React.PropsWithChildren) => React.JSX.Element, useIntegratedRouterAdapter: () => I18nRouterAdapter;