@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
@@ -18,7 +18,7 @@ function createMinimalI18nInstance(language) {
18
18
  };
19
19
  return minimalInstance;
20
20
  }
21
- function createContextValue(lang, i18nInstance, entryName, languages, localePathRedirect, ignoreRedirectRoutes, localisedUrls, setLang, synchronizeLanguage) {
21
+ function createContextValue(lang, i18nInstance, entryName, languages, localePathRedirect, ignoreRedirectRoutes, setLang, urlStrategy) {
22
22
  const instance = i18nInstance || createMinimalI18nInstance(lang);
23
23
  return {
24
24
  language: lang,
@@ -27,9 +27,8 @@ function createContextValue(lang, i18nInstance, entryName, languages, localePath
27
27
  languages,
28
28
  localePathRedirect,
29
29
  ignoreRedirectRoutes,
30
- localisedUrls,
31
- updateLanguage: setLang,
32
- synchronizeLanguage
30
+ urlStrategy,
31
+ updateLanguage: setLang
33
32
  };
34
33
  }
35
34
  function useSdkResourcesLoader(i18nInstance, setForceUpdate) {
@@ -78,7 +77,7 @@ function useSdkResourcesLoader(i18nInstance, setForceUpdate) {
78
77
  setForceUpdate
79
78
  ]);
80
79
  }
81
- function useClientSideRedirect(i18nInstance, localePathRedirect, languages, fallbackLanguage, ignoreRedirectRoutes, localisedUrls) {
80
+ function useClientSideRedirect(i18nInstance, localePathRedirect, languages, fallbackLanguage, ignoreRedirectRoutes, urlStrategy) {
82
81
  const urlRef = useRef('');
83
82
  const { navigate, location, hasRouter } = useI18nRouterAdapter();
84
83
  useEffect(()=>{
@@ -95,10 +94,10 @@ function useClientSideRedirect(i18nInstance, localePathRedirect, languages, fall
95
94
  const currentHash = hasRouter && location ? location.hash : window.location.hash;
96
95
  const entryPath = getEntryPath();
97
96
  const relativePath = currentPathname.replace(entryPath, '');
98
- if (shouldIgnoreRedirect(relativePath, languages, ignoreRedirectRoutes)) return;
97
+ if (shouldIgnoreRedirect(relativePath, languages, ignoreRedirectRoutes, urlStrategy)) return;
99
98
  const pathDetection = detectLanguageFromPath(currentPathname, languages, localePathRedirect);
100
99
  const targetLanguage = pathDetection.language || i18nInstance.language || fallbackLanguage || languages[0] || 'en';
101
- const newPath = buildLocalizedUrl(relativePath, targetLanguage, languages, localisedUrls);
100
+ const newPath = buildLocalizedUrl(relativePath, targetLanguage, languages, urlStrategy);
102
101
  const newUrl = entryPath + newPath + currentSearch + currentHash;
103
102
  urlRef.current = currentPathname;
104
103
  if (newUrl !== currentPathname + currentSearch + currentHash) if (hasRouter && navigate && location) navigate(newUrl, {
@@ -114,7 +113,7 @@ function useClientSideRedirect(i18nInstance, localePathRedirect, languages, fall
114
113
  languages,
115
114
  fallbackLanguage,
116
115
  ignoreRedirectRoutes,
117
- localisedUrls
116
+ urlStrategy
118
117
  ]);
119
118
  }
120
119
  function useLanguageSync(i18nInstance, localePathRedirect, languages, pathname, prevLangRef, setLang) {
@@ -1,20 +1,22 @@
1
- import { canonicalTargetPathname } from "@modern-js/i18n-runtime-extensions";
2
1
  import { useMemo } from "react";
3
2
  import { useModernI18n } from "./context.mjs";
4
3
  import { useI18nRouterAdapter } from "./routerAdapter.mjs";
5
4
  import { buildLocalizedUrl, splitUrlTarget } from "./utils.mjs";
6
- const localizePath = (pathname, language, config)=>buildLocalizedUrl(pathname, language, config.languages, config.localisedUrls);
5
+ const localizePath = (pathname, language, config)=>buildLocalizedUrl(pathname, language, config.languages, config.urlStrategy);
7
6
  const canonicalPath = (target, config)=>{
8
7
  const { pathname, search, hash } = splitUrlTarget(target);
9
- const resolvedPath = canonicalTargetPathname(pathname, config.languages, config.localisedUrls);
8
+ if (config.urlStrategy) return `${config.urlStrategy.canonicalPathname(pathname, config.languages)}${search}${hash}`;
9
+ const segments = pathname.split('/').filter(Boolean);
10
+ if (segments[0] && config.languages.some((language)=>language.toLowerCase() === segments[0].toLowerCase())) segments.shift();
11
+ const resolvedPath = `/${segments.join('/')}`;
10
12
  return `${resolvedPath}${search}${hash}`;
11
13
  };
12
14
  const useLocalizedPaths = ()=>{
13
- const { supportedLanguages, localisedUrls } = useModernI18n();
15
+ const { supportedLanguages, urlStrategy } = useModernI18n();
14
16
  return useMemo(()=>{
15
17
  const config = {
16
18
  languages: supportedLanguages,
17
- localisedUrls
19
+ urlStrategy
18
20
  };
19
21
  return {
20
22
  localizePath: (pathname, language)=>localizePath(pathname, language, config),
@@ -22,11 +24,11 @@ const useLocalizedPaths = ()=>{
22
24
  };
23
25
  }, [
24
26
  supportedLanguages,
25
- localisedUrls
27
+ urlStrategy
26
28
  ]);
27
29
  };
28
30
  const useLocalizedLocation = ()=>{
29
- const { language, supportedLanguages, localisedUrls } = useModernI18n();
31
+ const { language, supportedLanguages, urlStrategy } = useModernI18n();
30
32
  const { location } = useI18nRouterAdapter();
31
33
  const pathname = location?.pathname ?? '/';
32
34
  const search = location?.search ?? '';
@@ -34,7 +36,7 @@ const useLocalizedLocation = ()=>{
34
36
  return useMemo(()=>{
35
37
  const config = {
36
38
  languages: supportedLanguages,
37
- localisedUrls
39
+ urlStrategy
38
40
  };
39
41
  const alternates = {};
40
42
  for (const supportedLanguage of supportedLanguages)alternates[supportedLanguage] = `${localizePath(pathname, supportedLanguage, config)}${search}${hash}`;
@@ -46,7 +48,7 @@ const useLocalizedLocation = ()=>{
46
48
  }, [
47
49
  language,
48
50
  supportedLanguages,
49
- localisedUrls,
51
+ urlStrategy,
50
52
  pathname,
51
53
  search,
52
54
  hash
@@ -0,0 +1,7 @@
1
+ import { createI18nRouterNavigation } from "@modern-js/i18n-runtime-extensions/router-navigation";
2
+ import { I18nNavigationProvider, useNativeI18nRouterAdapter } from "./routerAdapter.mjs";
3
+ const { I18nRouterNavigationProvider: I18nRouterNavigationProvider, useIntegratedRouterAdapter: useIntegratedRouterAdapter } = createI18nRouterNavigation({
4
+ I18nNavigationProvider: I18nNavigationProvider,
5
+ useNativeI18nRouterAdapter: useNativeI18nRouterAdapter
6
+ });
7
+ export { I18nRouterNavigationProvider, useIntegratedRouterAdapter };
@@ -1,14 +1,19 @@
1
1
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
- import { useLanguageSync } from "@modern-js/i18n-runtime-extensions";
3
2
  import { RuntimeContext } from "@modern-js/runtime";
4
3
  import { Helmet } from "@modern-js/runtime/head";
5
4
  import { useContext, useEffect, useMemo, useRef, useState } from "react";
6
5
  import { ModernI18nProvider } from "./context.mjs";
7
- import { createContextValue, useClientSideRedirect, useSdkResourcesLoader } from "./hooks.mjs";
6
+ import { createContextValue, useClientSideRedirect, useLanguageSync, useSdkResourcesLoader } from "./hooks.mjs";
8
7
  import { getI18nextInstanceForProvider } from "./i18n/instance.mjs";
9
8
  import { useI18nRouterAdapter } from "./routerAdapter.mjs";
10
- const createI18nRootWrapper = (options)=>(App)=>(props)=>{
11
- const { entryName, htmlLangAttr, localePathRedirect, languages, fallbackLanguage, ignoreRedirectRoutes, localisedUrls, getLatestI18nInstance, getI18nextProvider } = options;
9
+ const NativeLanguageSynchronization = ({ i18nInstance, localePathRedirect, languages, pathname, prevLangRef, setLang, children })=>{
10
+ const synchronizeLanguage = useLanguageSync(i18nInstance, localePathRedirect, languages, pathname, prevLangRef, setLang);
11
+ return children(synchronizeLanguage);
12
+ };
13
+ const createI18nRootWrapper = (options)=>(App)=>{
14
+ const LanguageSynchronization = options.LanguageSynchronization ?? NativeLanguageSynchronization;
15
+ const I18nRoot = (props)=>{
16
+ const { entryName, htmlLangAttr, localePathRedirect, languages, fallbackLanguage, ignoreRedirectRoutes, urlStrategy, getLatestI18nInstance, getI18nextProvider } = options;
12
17
  const runtimeContext = useContext(RuntimeContext);
13
18
  const i18nInstance = runtimeContext.i18nInstance || getLatestI18nInstance();
14
19
  const initialLang = useMemo(()=>i18nInstance?.language || fallbackLanguage, [
@@ -33,18 +38,16 @@ const createI18nRootWrapper = (options)=>(App)=>(props)=>{
33
38
  lang
34
39
  ]);
35
40
  useSdkResourcesLoader(i18nInstance, setForceUpdate);
36
- const synchronizeLanguage = useLanguageSync(i18nInstance, localePathRedirect, languages, location?.pathname, prevLangRef, setLang);
37
- useClientSideRedirect(i18nInstance, localePathRedirect, languages, fallbackLanguage, ignoreRedirectRoutes, localisedUrls);
38
- const contextValue = useMemo(()=>createContextValue(lang, i18nInstance, entryName, languages, localePathRedirect, ignoreRedirectRoutes, localisedUrls, setLang, synchronizeLanguage), [
41
+ useClientSideRedirect(i18nInstance, localePathRedirect, languages, fallbackLanguage, ignoreRedirectRoutes, urlStrategy);
42
+ const contextValue = useMemo(()=>createContextValue(lang, i18nInstance, entryName, languages, localePathRedirect, ignoreRedirectRoutes, setLang, urlStrategy), [
39
43
  lang,
40
44
  i18nInstance,
41
45
  entryName,
42
46
  languages,
43
47
  localePathRedirect,
44
48
  ignoreRedirectRoutes,
45
- localisedUrls,
46
- forceUpdate,
47
- synchronizeLanguage
49
+ urlStrategy,
50
+ forceUpdate
48
51
  ]);
49
52
  const I18nextProvider = getI18nextProvider();
50
53
  const i18nextInstanceForProvider = useMemo(()=>i18nInstance ? getI18nextInstanceForProvider(i18nInstance, lang) : void 0, [
@@ -67,12 +70,33 @@ const createI18nRootWrapper = (options)=>(App)=>(props)=>{
67
70
  lang
68
71
  }
69
72
  }),
70
- /*#__PURE__*/ jsx(ModernI18nProvider, {
71
- i18nextProvider: I18nextProvider,
72
- value: contextValue,
73
- children: appContent
73
+ /*#__PURE__*/ jsx(LanguageSynchronization, {
74
+ i18nInstance: i18nInstance,
75
+ localePathRedirect: localePathRedirect,
76
+ languages: languages,
77
+ pathname: location?.pathname,
78
+ prevLangRef: prevLangRef,
79
+ setLang: setLang,
80
+ children: (synchronizeLanguage)=>/*#__PURE__*/ jsx(ModernI18nProvider, {
81
+ i18nextProvider: I18nextProvider,
82
+ value: {
83
+ ...contextValue,
84
+ synchronizeLanguage
85
+ },
86
+ children: appContent
87
+ })
74
88
  })
75
89
  ]
76
90
  });
77
91
  };
92
+ const { NavigationProvider } = options;
93
+ if (!NavigationProvider) return I18nRoot;
94
+ return function(props) {
95
+ return /*#__PURE__*/ jsx(NavigationProvider, {
96
+ children: /*#__PURE__*/ jsx(I18nRoot, {
97
+ ...props
98
+ })
99
+ });
100
+ };
101
+ };
78
102
  export { createI18nRootWrapper };
@@ -1,150 +1,37 @@
1
+ import { jsx } from "react/jsx-runtime";
2
+ import { I18nNavigationContext } from "@modern-js/plugin-i18n/runtime/contexts";
1
3
  import { RuntimeContext, isBrowser } from "@modern-js/runtime";
2
- import { InternalRuntimeContext, getRouterRuntimeState } from "@modern-js/runtime/context";
3
- import { useCallback, useContext, useSyncExternalStore } from "react";
4
- const normalizeUrlPart = (value, prefix)=>{
5
- if ('string' != typeof value || !value) return '';
6
- return value.startsWith(prefix) ? value : `${prefix}${value}`;
7
- };
8
- const normalizeLocation = (location)=>{
9
- if (!location || 'object' != typeof location) return null;
10
- const locationValue = location;
11
- if ('string' != typeof locationValue.pathname) return null;
12
- return {
13
- pathname: locationValue.pathname,
14
- search: normalizeUrlPart('string' == typeof locationValue.search ? locationValue.search : locationValue.searchStr, '?'),
15
- hash: normalizeUrlPart(locationValue.hash, '#')
16
- };
17
- };
18
- const getWindowLocation = ()=>{
19
- if (!isBrowser()) return null;
20
- return {
21
- pathname: window.location.pathname,
22
- search: window.location.search,
23
- hash: window.location.hash
24
- };
25
- };
26
- const getRouterFramework = (runtimeContext, internalContext, inReactRouter)=>{
27
- const framework = getRouterRuntimeState(internalContext)?.framework || getRouterRuntimeState(runtimeContext)?.framework;
28
- if (framework) return framework;
29
- if (internalContext.router?.useRouter || runtimeContext.router?.useRouter) return 'tanstack';
30
- if (internalContext.router?.useLocation || internalContext.router?.useHref || runtimeContext.router?.useLocation || runtimeContext.router?.useHref) return 'react-router';
31
- if (inReactRouter) return 'react-router';
32
- };
33
- const getRouterInstance = (internalContext, contextRouter)=>{
34
- if (contextRouter) return contextRouter;
35
- const router = getRouterRuntimeState(internalContext)?.instance;
36
- if (!router || 'object' != typeof router) return null;
37
- return router;
38
- };
39
- const getRouterStateLocation = (internalContext, contextRouter)=>{
40
- const router = getRouterInstance(internalContext, contextRouter);
41
- return normalizeLocation(router?.stores?.location?.get?.()) || normalizeLocation(router?.state?.location);
42
- };
43
- const getRouterParams = (internalContext, contextRouter)=>{
44
- const router = getRouterInstance(internalContext, contextRouter);
45
- const matches = router?.stores?.matches?.get?.() || router?.state?.matches;
46
- if (!Array.isArray(matches)) return {};
47
- return matches.reduce((params, match)=>{
48
- if (match?.params) Object.assign(params, match.params);
49
- return params;
50
- }, {});
51
- };
52
- const getRouterSnapshot = (internalContext, contextRouter)=>{
53
- const location = getRouterStateLocation(internalContext, contextRouter);
54
- const params = getRouterParams(internalContext, contextRouter);
55
- return JSON.stringify([
56
- location?.pathname ?? '',
57
- location?.search ?? '',
58
- location?.hash ?? '',
59
- Object.entries(params).sort(([left], [right])=>left.localeCompare(right))
60
- ]);
61
- };
62
- const useI18nRouterAdapter = ()=>{
4
+ import { InternalRuntimeContext } from "@modern-js/runtime/context";
5
+ import { useContext } from "react";
6
+ const I18nNavigationProvider = ({ children, value })=>/*#__PURE__*/ jsx(I18nNavigationContext.Provider, {
7
+ value: value,
8
+ children: children
9
+ });
10
+ const useNativeI18nRouterAdapter = ()=>{
63
11
  const runtimeContext = useContext(RuntimeContext);
64
12
  const internalContext = useContext(InternalRuntimeContext);
65
13
  const routerApi = internalContext.router || runtimeContext.router;
66
- const inReactRouter = routerApi?.useInRouterContext?.() ?? false;
67
- const reactRouterNavigate = inReactRouter ? routerApi?.useNavigate?.() ?? null : null;
68
- const reactRouterLocation = inReactRouter ? routerApi?.useLocation?.() ?? null : null;
69
- const reactRouterParams = inReactRouter ? routerApi?.useParams?.() ?? {} : {};
70
- const framework = getRouterFramework(runtimeContext, internalContext, inReactRouter);
71
- const contextUseRouter = inReactRouter || 'tanstack' !== framework ? void 0 : internalContext.router?.useRouter || runtimeContext.router?.useRouter;
72
- const contextRouter = contextUseRouter ? contextUseRouter({
73
- warn: false
74
- }) : null;
75
- const hasRouter = 'tanstack' === framework || 'react-router' === framework || Boolean(reactRouterNavigate);
76
- const subscribeToRouter = useCallback((update)=>{
77
- const router = getRouterInstance(internalContext, contextRouter);
78
- if (!router) return ()=>void 0;
79
- const unsubscribers = [];
80
- if ('react-router' === framework && !inReactRouter && 'function' == typeof router.subscribe) {
81
- const subscribe = router.subscribe;
82
- const unsubscribe = subscribe.call(router, update);
83
- if ('function' == typeof unsubscribe) unsubscribers.push(unsubscribe);
84
- }
85
- if ('tanstack' === framework && 'function' == typeof router.stores?.location?.subscribe) {
86
- const unsubscribe = router.stores.location.subscribe(update);
87
- if ('function' == typeof unsubscribe) unsubscribers.push(unsubscribe);
88
- }
89
- if ('tanstack' === framework && 'function' == typeof router.subscribe) {
90
- const subscribe = router.subscribe;
91
- for (const eventType of [
92
- 'onBeforeNavigate',
93
- 'onBeforeLoad'
94
- ]){
95
- const unsubscribe = subscribe.call(router, eventType, update);
96
- if ('function' == typeof unsubscribe) unsubscribers.push(unsubscribe);
97
- }
98
- }
99
- return ()=>{
100
- for (const unsubscribe of unsubscribers)unsubscribe();
101
- };
102
- }, [
103
- contextRouter,
104
- framework,
105
- inReactRouter,
106
- internalContext
107
- ]);
108
- const getSnapshot = useCallback(()=>getRouterSnapshot(internalContext, contextRouter), [
109
- contextRouter,
110
- internalContext
111
- ]);
112
- useSyncExternalStore(subscribeToRouter, getSnapshot, getSnapshot);
113
- const navigate = useCallback((href, options)=>{
114
- const router = getRouterInstance(internalContext, contextRouter);
115
- const activeFramework = getRouterFramework(runtimeContext, internalContext, inReactRouter);
116
- if ('tanstack' === activeFramework) {
117
- if ('function' == typeof router?.navigate) return router.navigate({
118
- to: href,
119
- replace: options?.replace,
120
- ...options?.state === void 0 ? {} : {
121
- state: options.state
122
- }
123
- });
124
- throw new Error('TanStack router instance is not available.');
125
- }
126
- if (reactRouterNavigate) return reactRouterNavigate(href, options);
127
- if ('react-router' === activeFramework) {
128
- if ('function' == typeof router?.navigate) return router.navigate(href, options);
129
- throw new Error('React Router instance is not available.');
130
- }
131
- }, [
132
- contextRouter,
133
- internalContext,
134
- inReactRouter,
135
- reactRouterNavigate,
136
- runtimeContext
137
- ]);
138
- const location = (reactRouterLocation ? normalizeLocation(reactRouterLocation) : getRouterStateLocation(internalContext, contextRouter)) || getWindowLocation();
139
- const params = inReactRouter ? reactRouterParams : getRouterParams(internalContext, contextRouter);
140
- const Link = 'tanstack' === framework ? internalContext.router?.Link || runtimeContext.router?.Link || null : 'react-router' === framework || inReactRouter ? routerApi?.Link ?? null : null;
14
+ const hasRouter = routerApi?.useInRouterContext?.() ?? false;
15
+ const navigate = hasRouter ? routerApi?.useNavigate?.() ?? null : null;
16
+ const routerLocation = hasRouter ? routerApi?.useLocation?.() ?? null : null;
17
+ const params = hasRouter ? routerApi?.useParams?.() ?? {} : {};
18
+ const location = routerLocation ?? (isBrowser() ? {
19
+ pathname: window.location.pathname,
20
+ search: window.location.search,
21
+ hash: window.location.hash
22
+ } : null);
141
23
  return {
142
- framework,
24
+ framework: hasRouter ? 'react-router' : void 0,
143
25
  hasRouter,
26
+ navigate,
144
27
  location,
145
- navigate: hasRouter ? navigate : null,
146
- Link,
147
- params
28
+ params,
29
+ Link: hasRouter ? routerApi?.Link ?? null : null
148
30
  };
149
31
  };
150
- export { useI18nRouterAdapter };
32
+ const useI18nRouterAdapter = ()=>{
33
+ const provided = useContext(I18nNavigationContext);
34
+ const native = useNativeI18nRouterAdapter();
35
+ return provided ?? native;
36
+ };
37
+ export { I18nNavigationProvider, useI18nRouterAdapter, useNativeI18nRouterAdapter };
@@ -0,0 +1 @@
1
+ export { ModernI18nContext, ReactI18nextProviderContext } from "@modern-js/plugin-i18n/runtime/contexts";
@@ -1,6 +1,8 @@
1
- import { localiseTargetPathname, shouldSkipLocaleRedirect } from "@modern-js/i18n-runtime-extensions";
2
1
  import { isBrowser } from "@modern-js/runtime";
3
2
  import { getGlobalBasename } from "@modern-js/runtime/context";
3
+ import { splitUrlTarget } from "@modern-js/runtime-utils/url";
4
+ import { isDefaultLocaleRedirectSkipPath } from "../shared/mappedUrlStrategy.mjs";
5
+ import { asI18nUrlStrategy } from "../shared/urlStrategy.mjs";
4
6
  const getPathname = (context)=>{
5
7
  if (isBrowser()) return window.location.pathname;
6
8
  return context.ssrContext?.request?.pathname || '/';
@@ -16,22 +18,14 @@ const getLanguageFromPath = (pathname, languages, fallbackLanguage)=>{
16
18
  if (languages.includes(firstSegment)) return firstSegment;
17
19
  return fallbackLanguage;
18
20
  };
19
- const splitUrlTarget = (target)=>{
20
- const hashIndex = target.indexOf('#');
21
- const hash = hashIndex >= 0 ? target.slice(hashIndex) : '';
22
- const beforeHash = hashIndex >= 0 ? target.slice(0, hashIndex) : target;
23
- const searchIndex = beforeHash.indexOf('?');
24
- const search = searchIndex >= 0 ? beforeHash.slice(searchIndex) : '';
25
- const pathname = searchIndex >= 0 ? beforeHash.slice(0, searchIndex) : beforeHash;
26
- return {
27
- pathname,
28
- search,
29
- hash
30
- };
31
- };
32
- const buildLocalizedUrl = (target, language, languages, localisedUrls)=>{
21
+ const buildLocalizedUrl = (target, language, languages, urlStrategy)=>{
33
22
  const { pathname, search, hash } = splitUrlTarget(target);
34
- const localizedPathname = localiseTargetPathname(pathname, language, languages, localisedUrls);
23
+ const strategy = asI18nUrlStrategy(urlStrategy);
24
+ if (strategy) return `${strategy.localizePathname(pathname, language, languages)}${search}${hash}`;
25
+ const segments = pathname.split('/').filter(Boolean);
26
+ if (segments[0] && languages.some((item)=>item.toLowerCase() === segments[0].toLowerCase())) segments[0] = language;
27
+ else segments.unshift(language);
28
+ const localizedPathname = `/${segments.join('/')}`;
35
29
  return `${localizedPathname}${search}${hash}`;
36
30
  };
37
31
  const detectLanguageFromPath = (pathname, languages, localePathRedirect)=>{
@@ -51,5 +45,13 @@ const detectLanguageFromPath = (pathname, languages, localePathRedirect)=>{
51
45
  detected: false
52
46
  };
53
47
  };
54
- const shouldIgnoreRedirect = (pathname, languages, ignoreRedirectRoutes)=>shouldSkipLocaleRedirect(pathname, languages, ignoreRedirectRoutes);
48
+ const shouldIgnoreRedirect = (pathname, languages, ignoreRedirectRoutes, urlStrategy)=>{
49
+ if (isDefaultLocaleRedirectSkipPath(pathname, languages)) return true;
50
+ if (asI18nUrlStrategy(urlStrategy)?.shouldSkipRedirect?.(pathname, languages)) return true;
51
+ if (!ignoreRedirectRoutes) return false;
52
+ const segments = pathname.split('/').filter(Boolean);
53
+ if (segments[0] && languages.some((item)=>item.toLowerCase() === segments[0].toLowerCase())) segments.shift();
54
+ const normalizedPath = `/${segments.join('/')}`;
55
+ return 'function' == typeof ignoreRedirectRoutes ? ignoreRedirectRoutes(normalizedPath) : ignoreRedirectRoutes.some((pattern)=>normalizedPath === pattern || normalizedPath.startsWith(`${pattern}/`));
56
+ };
55
57
  export { buildLocalizedUrl, detectLanguageFromPath, getEntryPath, getLanguageFromPath, getPathname, shouldIgnoreRedirect, splitUrlTarget };
@@ -0,0 +1,7 @@
1
+ import { createMappedUrlStrategy } from "./mappedUrlStrategy.mjs";
2
+ const createDefaultUrlStrategy = (localisedUrls)=>createMappedUrlStrategy(localisedUrls);
3
+ const resolveDefaultUrlStrategy = (localisedUrls)=>{
4
+ if (!localisedUrls || 'object' != typeof localisedUrls || 0 === Object.keys(localisedUrls).length) return;
5
+ return createDefaultUrlStrategy(localisedUrls);
6
+ };
7
+ export { createDefaultUrlStrategy, resolveDefaultUrlStrategy };
@@ -1,6 +1,7 @@
1
- import { resolveLocalisedUrlsConfig } from "@modern-js/i18n-runtime-extensions";
1
+ import { asI18nUrlStrategy } from "../shared/urlStrategy.mjs";
2
2
  import { getLocaleDetectionOptions } from "../shared/utils.mjs";
3
3
  import { collectApiPrefixes, matchesApiPrefix } from "./apiPrefix.mjs";
4
+ import { resolveDefaultUrlStrategy } from "./defaultUrlStrategy.mjs";
4
5
  import { convertToHonoLanguageDetectorOptions } from "./detectorOptions.mjs";
5
6
  import { buildLocalizedUrl, createLocaleRedirectResponse, getLanguageFromPath, isStaticResourceRequest, shouldIgnoreRedirect } from "./redirectPolicy.mjs";
6
7
  import * as __rspack_external__modern_js_server_core_hono_0af3baa7 from "@modern-js/server-core/hono";
@@ -24,7 +25,10 @@ const i18nServerPlugin = (options)=>({
24
25
  const { entryName } = route;
25
26
  if (!entryName) return;
26
27
  if (!options.localeDetection) return;
27
- const { localePathRedirect, i18nextDetector = true, languages = [], fallbackLanguage = 'en', detection, ignoreRedirectRoutes, localisedUrls } = getLocaleDetectionOptions(entryName, options.localeDetection);
28
+ const entryLocaleDetection = getLocaleDetectionOptions(entryName, options.localeDetection);
29
+ const { localePathRedirect, i18nextDetector = true, languages = [], fallbackLanguage = 'en', detection, ignoreRedirectRoutes } = entryLocaleDetection;
30
+ const legacyLocalisedUrls = Reflect.get(entryLocaleDetection, 'localisedUrls');
31
+ const urlStrategy = asI18nUrlStrategy(options.resolveUrlStrategy?.(entryName)) ?? resolveDefaultUrlStrategy(legacyLocalisedUrls);
28
32
  const staticRoutePrefixes = options.staticRoutePrefixes;
29
33
  const originUrlPath = route.urlPath;
30
34
  const urlPath = originUrlPath.endsWith('/') ? `${originUrlPath}*` : `${originUrlPath}/*`;
@@ -39,6 +43,7 @@ const i18nServerPlugin = (options)=>({
39
43
  const url = new URL(c.req.url);
40
44
  const pathname = url.pathname;
41
45
  if (matchesApiPrefix(pathname, apiPrefixes)) return await next();
46
+ if (shouldIgnoreRedirect(pathname, urlPath, ignoreRedirectRoutes, urlStrategy, languages)) return await next();
42
47
  if (isStaticResourceRequest(pathname, staticRoutePrefixes, languages)) return await next();
43
48
  if ('/' === originUrlPath) {
44
49
  const pathSegments = pathname.split('/').filter(Boolean);
@@ -59,7 +64,7 @@ const i18nServerPlugin = (options)=>({
59
64
  const pathname = url.pathname;
60
65
  if (matchesApiPrefix(pathname, apiPrefixes)) return await next();
61
66
  if (isStaticResourceRequest(pathname, staticRoutePrefixes, languages)) return await next();
62
- if (shouldIgnoreRedirect(pathname, urlPath, ignoreRedirectRoutes)) return await next();
67
+ if (shouldIgnoreRedirect(pathname, urlPath, ignoreRedirectRoutes, urlStrategy, languages)) return await next();
63
68
  if ('/' === originUrlPath) {
64
69
  const pathSegments = pathname.split('/').filter(Boolean);
65
70
  if (pathSegments.length > 0) {
@@ -72,12 +77,11 @@ const i18nServerPlugin = (options)=>({
72
77
  let detectedLanguage = null;
73
78
  if (i18nextDetector) detectedLanguage = c.get('language') || null;
74
79
  const targetLanguage = detectedLanguage || fallbackLanguage;
75
- const localizedUrl = buildLocalizedUrl(c.req, originUrlPath, targetLanguage, languages, localisedUrls);
80
+ const localizedUrl = buildLocalizedUrl(c.req, originUrlPath, targetLanguage, languages, urlStrategy);
76
81
  return createLocaleRedirectResponse(localizedUrl);
77
82
  }
78
- const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
79
- if (localisedUrlsConfig.enabled) {
80
- const expectedUrl = buildLocalizedUrl(c.req, originUrlPath, language, languages, localisedUrls);
83
+ if (urlStrategy) {
84
+ const expectedUrl = buildLocalizedUrl(c.req, originUrlPath, language, languages, urlStrategy);
81
85
  if (expectedUrl !== `${pathname}${url.search}${url.hash}`) return createLocaleRedirectResponse(expectedUrl);
82
86
  }
83
87
  await next();
@@ -0,0 +1 @@
1
+ export { createMappedUrlStrategy, resolveMappedUrlStrategy } from "../shared/mappedUrlStrategy.mjs";
@@ -1,39 +1,48 @@
1
- import { isDefaultLocaleRedirectSkipPath, localiseTargetPathname, matchesPathPrefix, shouldSkipLocaleRedirect, stripLanguagePrefix } from "@modern-js/i18n-runtime-extensions";
1
+ import { isDefaultLocaleRedirectSkipPath } from "../shared/mappedUrlStrategy.mjs";
2
+ import { asI18nUrlStrategy } from "../shared/urlStrategy.mjs";
2
3
  const stripUrlPathPrefix = (pathname, urlPath)=>{
3
4
  const basePath = urlPath.replace('/*', '');
4
5
  if (!basePath || '/' === basePath) return pathname;
5
- const remainingPath = pathname.startsWith(basePath) ? pathname.slice(basePath.length) : pathname;
6
- return remainingPath || '/';
6
+ return pathname === basePath || pathname.startsWith(`${basePath}/`) ? pathname.slice(basePath.length) || '/' : pathname;
7
7
  };
8
- const shouldIgnoreRedirect = (pathname, urlPath, ignoreRedirectRoutes)=>{
8
+ const shouldIgnoreRedirect = (pathname, urlPath, ignoreRedirectRoutes, urlStrategy, languages = [])=>{
9
9
  const remainingPath = stripUrlPathPrefix(pathname, urlPath);
10
- return shouldSkipLocaleRedirect(remainingPath, [], ignoreRedirectRoutes);
10
+ if (isDefaultLocaleRedirectSkipPath(remainingPath, languages)) return true;
11
+ if (asI18nUrlStrategy(urlStrategy)?.shouldSkipRedirect?.(remainingPath, languages)) return true;
12
+ if (!ignoreRedirectRoutes) return false;
13
+ const segments = remainingPath.split('/').filter(Boolean);
14
+ if (segments[0] && languages.some((language)=>language.toLowerCase() === segments[0].toLowerCase())) segments.shift();
15
+ const normalizedPath = `/${segments.join('/')}`;
16
+ return 'function' == typeof ignoreRedirectRoutes ? ignoreRedirectRoutes(normalizedPath) : ignoreRedirectRoutes.some((pattern)=>normalizedPath === pattern || normalizedPath.startsWith(`${pattern}/`));
11
17
  };
12
18
  const isStaticResourceRequest = (pathname, staticRoutePrefixes, languages = [])=>{
13
- if (isDefaultLocaleRedirectSkipPath(pathname, languages)) return true;
14
- const matchesStaticRoutePrefix = (targetPathname)=>staticRoutePrefixes.some((prefix)=>matchesPathPrefix(targetPathname, prefix));
15
- if (matchesStaticRoutePrefix(pathname)) return true;
16
- const pathWithoutLanguage = stripLanguagePrefix(pathname, languages);
17
- return pathWithoutLanguage !== pathname && matchesStaticRoutePrefix(pathWithoutLanguage);
19
+ const prefixes = [
20
+ ...staticRoutePrefixes,
21
+ '/static',
22
+ '/upload'
23
+ ];
24
+ const matches = (target)=>prefixes.some((prefix)=>target === prefix || target.startsWith(`${prefix}/`));
25
+ if (matches(pathname)) return true;
26
+ const segments = pathname.split('/').filter(Boolean);
27
+ if (segments[0] && languages.some((language)=>language.toLowerCase() === segments[0].toLowerCase())) return matches(`/${segments.slice(1).join('/')}`);
28
+ return false;
18
29
  };
19
30
  const getLanguageFromPath = (req, urlPath, languages)=>{
20
- const url = new URL(req.url, `http://${req.header().host}`);
21
- const pathname = url.pathname;
22
- const remainingPath = stripUrlPathPrefix(pathname, urlPath);
23
- const segments = remainingPath.split('/').filter(Boolean);
24
- const firstSegment = segments[0];
25
- if (languages.includes(firstSegment)) return firstSegment;
26
- return null;
31
+ const host = req.header?.().host;
32
+ const url = new URL(req.url, host ? `http://${host}` : void 0);
33
+ const firstSegment = stripUrlPathPrefix(url.pathname, urlPath).split('/').filter(Boolean)[0];
34
+ return languages.find((language)=>language.toLowerCase() === firstSegment?.toLowerCase()) ?? null;
27
35
  };
28
- const buildLocalizedUrl = (req, urlPath, language, languages, localisedUrls)=>{
36
+ const buildLocalizedUrl = (req, urlPath, language, languages, urlStrategy)=>{
29
37
  const url = new URL(req.url);
30
- const pathname = url.pathname;
31
38
  const basePath = urlPath.replace('/*', '');
32
- const remainingPath = stripUrlPathPrefix(pathname, urlPath);
33
- const newPathname = localiseTargetPathname(remainingPath, language, languages, localisedUrls);
34
- const suffix = `${url.search}${url.hash}`;
35
- const localizedUrl = '/' === basePath ? newPathname + suffix : basePath + newPathname + suffix;
36
- return localizedUrl;
39
+ const remainingPath = stripUrlPathPrefix(url.pathname, urlPath);
40
+ const segments = remainingPath.split('/').filter(Boolean);
41
+ if (segments[0] && languages.some((item)=>item.toLowerCase() === segments[0].toLowerCase())) segments[0] = language;
42
+ else segments.unshift(language);
43
+ const strategy = asI18nUrlStrategy(urlStrategy);
44
+ const pathname = strategy ? strategy.localizePathname(remainingPath, language, languages) : `/${segments.join('/')}`;
45
+ return `${'/' === basePath ? '' : basePath}${pathname}${url.search}${url.hash}`;
37
46
  };
38
47
  const createLocaleRedirectResponse = (location)=>new Response(null, {
39
48
  status: 302,
@@ -0,0 +1,19 @@
1
+ import { canonicalTargetPathname, isDefaultLocaleRedirectSkipPath, localiseTargetPathname } from "@modern-js/i18n-runtime-extensions";
2
+ const createMappedUrlStrategy = (localisedUrls)=>({
3
+ localizePathname: (pathname, language, languages)=>localiseTargetPathname(pathname, language, [
4
+ ...languages
5
+ ], localisedUrls),
6
+ canonicalPathname: (pathname, languages)=>canonicalTargetPathname(pathname, [
7
+ ...languages
8
+ ], localisedUrls),
9
+ shouldSkipRedirect: (pathname, languages)=>isDefaultLocaleRedirectSkipPath(pathname, [
10
+ ...languages
11
+ ])
12
+ });
13
+ const resolveMappedUrlStrategy = (localeDetection)=>{
14
+ if (!localeDetection || 'object' != typeof localeDetection) return;
15
+ const localisedUrls = Reflect.get(localeDetection, 'localisedUrls');
16
+ if (!localisedUrls || 'object' != typeof localisedUrls || 0 === Object.keys(localisedUrls).length) return;
17
+ return createMappedUrlStrategy(localisedUrls);
18
+ };
19
+ export { createMappedUrlStrategy, isDefaultLocaleRedirectSkipPath, resolveMappedUrlStrategy };
@@ -0,0 +1,7 @@
1
+ const asI18nUrlStrategy = (candidate)=>{
2
+ if (!candidate || 'object' != typeof candidate) return;
3
+ const strategy = candidate;
4
+ return 'function' == typeof strategy.localizePathname && 'function' == typeof strategy.canonicalPathname ? strategy : void 0;
5
+ };
6
+ const isUnusableI18nUrlStrategy = (candidate)=>Boolean(candidate) && 'object' == typeof candidate && void 0 === asI18nUrlStrategy(candidate);
7
+ export { asI18nUrlStrategy, isUnusableI18nUrlStrategy };