@bleedingdev/modern-js-plugin-i18n 3.5.0-ultramodern.3 → 3.5.0-ultramodern.31

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 (168) hide show
  1. package/dist/cjs/cli/index.js +2 -1
  2. package/dist/cjs/runtime/Link.js +8 -89
  3. package/dist/cjs/runtime/context.js +18 -82
  4. package/dist/cjs/runtime/contextHelpers.js +137 -0
  5. package/dist/cjs/runtime/core.js +29 -132
  6. package/dist/cjs/runtime/i18n/detection/cache.js +149 -0
  7. package/dist/cjs/runtime/i18n/detection/detector.js +100 -0
  8. package/dist/cjs/runtime/i18n/detection/index.js +8 -263
  9. package/dist/cjs/runtime/i18n/detection/initOptions.js +69 -0
  10. package/dist/cjs/runtime/i18n/detection/language.js +62 -0
  11. package/dist/cjs/runtime/i18n/detection/path.js +49 -0
  12. package/dist/cjs/runtime/i18n/detection/priority.js +66 -0
  13. package/dist/cjs/runtime/i18n/detection/ssr.js +70 -0
  14. package/dist/cjs/runtime/i18n/detection/types.js +18 -0
  15. package/dist/cjs/runtime/linkHelpers.js +148 -0
  16. package/dist/cjs/runtime/pluginSetup.js +102 -0
  17. package/dist/cjs/runtime/providerComposition.js +113 -0
  18. package/dist/cjs/runtime/reactI18next.js +43 -0
  19. package/dist/cjs/server/apiPrefix.js +72 -0
  20. package/dist/cjs/server/detectorOptions.js +97 -0
  21. package/dist/cjs/server/index.js +17 -144
  22. package/dist/cjs/server/redirectPolicy.js +102 -0
  23. package/dist/cjs/shared/localisedUrls/config.js +49 -0
  24. package/dist/cjs/shared/localisedUrls/index.js +75 -0
  25. package/dist/cjs/shared/localisedUrls/normalise.js +87 -0
  26. package/dist/cjs/shared/localisedUrls/pathname.js +65 -0
  27. package/dist/cjs/shared/localisedUrls/patterns.js +130 -0
  28. package/dist/cjs/shared/localisedUrls/resolve.js +91 -0
  29. package/dist/cjs/shared/localisedUrls/routes.js +129 -0
  30. package/dist/cjs/shared/localisedUrls/types.js +18 -0
  31. package/dist/cjs/shared/localisedUrls.js +13 -294
  32. package/dist/esm/cli/index.mjs +2 -1
  33. package/dist/esm/runtime/Link.mjs +1 -82
  34. package/dist/esm/runtime/context.mjs +18 -82
  35. package/dist/esm/runtime/contextHelpers.mjs +84 -0
  36. package/dist/esm/runtime/core.mjs +30 -133
  37. package/dist/esm/runtime/i18n/detection/cache.mjs +102 -0
  38. package/dist/esm/runtime/i18n/detection/detector.mjs +62 -0
  39. package/dist/esm/runtime/i18n/detection/index.mjs +4 -260
  40. package/dist/esm/runtime/i18n/detection/initOptions.mjs +28 -0
  41. package/dist/esm/runtime/i18n/detection/language.mjs +21 -0
  42. package/dist/esm/runtime/i18n/detection/path.mjs +11 -0
  43. package/dist/esm/runtime/i18n/detection/priority.mjs +28 -0
  44. package/dist/esm/runtime/i18n/detection/ssr.mjs +26 -0
  45. package/dist/esm/runtime/i18n/detection/types.mjs +0 -0
  46. package/dist/esm/runtime/linkHelpers.mjs +98 -0
  47. package/dist/esm/runtime/pluginSetup.mjs +64 -0
  48. package/dist/esm/runtime/providerComposition.mjs +75 -0
  49. package/dist/esm/runtime/reactI18next.mjs +5 -0
  50. package/dist/esm/server/apiPrefix.mjs +31 -0
  51. package/dist/esm/server/detectorOptions.mjs +59 -0
  52. package/dist/esm/server/index.mjs +6 -133
  53. package/dist/esm/server/redirectPolicy.mjs +52 -0
  54. package/dist/esm/shared/localisedUrls/config.mjs +11 -0
  55. package/dist/esm/shared/localisedUrls/index.mjs +6 -0
  56. package/dist/esm/shared/localisedUrls/normalise.mjs +37 -0
  57. package/dist/esm/shared/localisedUrls/pathname.mjs +24 -0
  58. package/dist/esm/shared/localisedUrls/patterns.mjs +86 -0
  59. package/dist/esm/shared/localisedUrls/resolve.mjs +50 -0
  60. package/dist/esm/shared/localisedUrls/routes.mjs +88 -0
  61. package/dist/esm/shared/localisedUrls/types.mjs +0 -0
  62. package/dist/esm/shared/localisedUrls.mjs +1 -283
  63. package/dist/esm-node/cli/index.mjs +2 -1
  64. package/dist/esm-node/runtime/Link.mjs +1 -82
  65. package/dist/esm-node/runtime/context.mjs +18 -82
  66. package/dist/esm-node/runtime/contextHelpers.mjs +85 -0
  67. package/dist/esm-node/runtime/core.mjs +30 -133
  68. package/dist/esm-node/runtime/i18n/detection/cache.mjs +103 -0
  69. package/dist/esm-node/runtime/i18n/detection/detector.mjs +63 -0
  70. package/dist/esm-node/runtime/i18n/detection/index.mjs +4 -260
  71. package/dist/esm-node/runtime/i18n/detection/initOptions.mjs +29 -0
  72. package/dist/esm-node/runtime/i18n/detection/language.mjs +22 -0
  73. package/dist/esm-node/runtime/i18n/detection/path.mjs +12 -0
  74. package/dist/esm-node/runtime/i18n/detection/priority.mjs +29 -0
  75. package/dist/esm-node/runtime/i18n/detection/ssr.mjs +27 -0
  76. package/dist/esm-node/runtime/i18n/detection/types.mjs +1 -0
  77. package/dist/esm-node/runtime/linkHelpers.mjs +99 -0
  78. package/dist/esm-node/runtime/pluginSetup.mjs +65 -0
  79. package/dist/esm-node/runtime/providerComposition.mjs +76 -0
  80. package/dist/esm-node/runtime/reactI18next.mjs +6 -0
  81. package/dist/esm-node/server/apiPrefix.mjs +32 -0
  82. package/dist/esm-node/server/detectorOptions.mjs +60 -0
  83. package/dist/esm-node/server/index.mjs +6 -133
  84. package/dist/esm-node/server/redirectPolicy.mjs +53 -0
  85. package/dist/esm-node/shared/localisedUrls/config.mjs +12 -0
  86. package/dist/esm-node/shared/localisedUrls/index.mjs +7 -0
  87. package/dist/esm-node/shared/localisedUrls/normalise.mjs +38 -0
  88. package/dist/esm-node/shared/localisedUrls/pathname.mjs +25 -0
  89. package/dist/esm-node/shared/localisedUrls/patterns.mjs +87 -0
  90. package/dist/esm-node/shared/localisedUrls/resolve.mjs +51 -0
  91. package/dist/esm-node/shared/localisedUrls/routes.mjs +89 -0
  92. package/dist/esm-node/shared/localisedUrls/types.mjs +1 -0
  93. package/dist/esm-node/shared/localisedUrls.mjs +1 -283
  94. package/dist/types/runtime/Link.d.ts +3 -7
  95. package/dist/types/runtime/context.d.ts +2 -2
  96. package/dist/types/runtime/contextHelpers.d.ts +28 -0
  97. package/dist/types/runtime/core.d.ts +3 -7
  98. package/dist/types/runtime/hooks.d.ts +5 -0
  99. package/dist/types/runtime/i18n/detection/cache.d.ts +14 -0
  100. package/dist/types/runtime/i18n/detection/detector.d.ts +8 -0
  101. package/dist/types/runtime/i18n/detection/index.d.ts +5 -50
  102. package/dist/types/runtime/i18n/detection/initOptions.d.ts +10 -0
  103. package/dist/types/runtime/i18n/detection/language.d.ts +11 -0
  104. package/dist/types/runtime/i18n/detection/path.d.ts +5 -0
  105. package/dist/types/runtime/i18n/detection/priority.d.ts +10 -0
  106. package/dist/types/runtime/i18n/detection/ssr.d.ts +9 -0
  107. package/dist/types/runtime/i18n/detection/types.d.ts +29 -0
  108. package/dist/types/runtime/i18n/react-i18next.d.ts +1 -6
  109. package/dist/types/runtime/linkHelpers.d.ts +17 -0
  110. package/dist/types/runtime/pluginSetup.d.ts +32 -0
  111. package/dist/types/runtime/providerComposition.d.ts +15 -0
  112. package/dist/types/runtime/reactI18next.d.ts +7 -0
  113. package/dist/types/runtime/utils.d.ts +7 -2
  114. package/dist/types/server/apiPrefix.d.ts +7 -0
  115. package/dist/types/server/detectorOptions.d.ts +21 -0
  116. package/dist/types/server/index.d.ts +1 -6
  117. package/dist/types/server/redirectPolicy.d.ts +16 -0
  118. package/dist/types/shared/localisedUrls/config.d.ts +9 -0
  119. package/dist/types/shared/localisedUrls/index.d.ts +7 -0
  120. package/dist/types/shared/localisedUrls/normalise.d.ts +10 -0
  121. package/dist/types/shared/localisedUrls/pathname.d.ts +3 -0
  122. package/dist/types/shared/localisedUrls/patterns.d.ts +5 -0
  123. package/dist/types/shared/localisedUrls/resolve.d.ts +8 -0
  124. package/dist/types/shared/localisedUrls/routes.d.ts +3 -0
  125. package/dist/types/shared/localisedUrls/types.d.ts +14 -0
  126. package/dist/types/shared/localisedUrls.d.ts +2 -36
  127. package/package.json +10 -10
  128. package/src/cli/index.ts +3 -2
  129. package/src/runtime/Link.tsx +11 -138
  130. package/src/runtime/context.tsx +42 -196
  131. package/src/runtime/contextHelpers.ts +232 -0
  132. package/src/runtime/core.tsx +43 -274
  133. package/src/runtime/hooks.ts +3 -0
  134. package/src/runtime/i18n/detection/cache.ts +175 -0
  135. package/src/runtime/i18n/detection/detector.ts +157 -0
  136. package/src/runtime/i18n/detection/index.ts +10 -641
  137. package/src/runtime/i18n/detection/initOptions.ts +74 -0
  138. package/src/runtime/i18n/detection/language.ts +64 -0
  139. package/src/runtime/i18n/detection/path.ts +41 -0
  140. package/src/runtime/i18n/detection/priority.ts +82 -0
  141. package/src/runtime/i18n/detection/ssr.ts +47 -0
  142. package/src/runtime/i18n/detection/types.ts +33 -0
  143. package/src/runtime/i18n/react-i18next.ts +1 -6
  144. package/src/runtime/linkHelpers.ts +174 -0
  145. package/src/runtime/pluginSetup.ts +189 -0
  146. package/src/runtime/providerComposition.tsx +142 -0
  147. package/src/runtime/reactI18next.ts +20 -0
  148. package/src/runtime/utils.ts +7 -5
  149. package/src/server/apiPrefix.ts +67 -0
  150. package/src/server/detectorOptions.ts +105 -0
  151. package/src/server/index.ts +14 -319
  152. package/src/server/redirectPolicy.ts +152 -0
  153. package/src/shared/localisedUrls/config.ts +18 -0
  154. package/src/shared/localisedUrls/index.ts +13 -0
  155. package/src/shared/localisedUrls/normalise.ts +67 -0
  156. package/src/shared/localisedUrls/pathname.ts +57 -0
  157. package/src/shared/localisedUrls/patterns.ts +160 -0
  158. package/src/shared/localisedUrls/resolve.ts +118 -0
  159. package/src/shared/localisedUrls/routes.ts +226 -0
  160. package/src/shared/localisedUrls/types.ts +18 -0
  161. package/src/shared/localisedUrls.ts +20 -623
  162. package/tests/link.test.tsx +111 -0
  163. package/tests/linkTypes.test.ts +15 -4
  164. package/tests/localisedUrls.test.ts +54 -2
  165. package/tests/reactI18nextRuntimeBoundary.test.ts +6 -3
  166. package/tests/routerAdapter.test.tsx +56 -0
  167. package/tests/type-fixture/fixture-globals.d.ts +11 -0
  168. package/tests/type-fixture/tsconfig.json +1 -0
@@ -27,301 +27,20 @@ var __webpack_require__ = {};
27
27
  })();
28
28
  var __webpack_exports__ = {};
29
29
  __webpack_require__.r(__webpack_exports__);
30
- const LOCALE_PARAM_NAMES = new Set([
31
- 'lang',
32
- 'locale',
33
- 'language'
34
- ]);
35
- const normaliseSlashes = (path)=>{
36
- const withoutDuplicateSlashes = path.replace(/\/+/g, '/');
37
- const withLeadingSlash = withoutDuplicateSlashes.startsWith('/') ? withoutDuplicateSlashes : `/${withoutDuplicateSlashes}`;
38
- return withLeadingSlash.length > 1 ? withLeadingSlash.replace(/\/+$/, '') : withLeadingSlash;
39
- };
40
- const normalisePathPattern = (path)=>normaliseSlashes(path).replace(/\[(.+?)\]/g, ':$1');
41
- const normalisePathname = (pathname)=>normaliseSlashes(pathname);
42
- const normaliseRoutePath = (path)=>{
43
- const normalized = normalisePathPattern(path);
44
- return '/' === normalized ? '' : normalized.slice(1);
45
- };
46
- const getLocaleParamSegment = (segment)=>{
47
- if (!segment.startsWith(':')) return null;
48
- const paramName = segment.slice(1).replace(/\?$/, '');
49
- return LOCALE_PARAM_NAMES.has(paramName) ? segment : null;
50
- };
51
- const splitPathSegments = (path)=>{
52
- if (!path) return [];
53
- return normalisePathPattern(path).split('/').filter(Boolean);
54
- };
55
- const stripLeadingLocaleParam = (path)=>{
56
- const segments = splitPathSegments(path);
57
- const leadingLocaleParam = getLocaleParamSegment(segments[0] || '');
58
- if (!leadingLocaleParam) return path;
59
- const remainingPath = segments.slice(1).join('/');
60
- return remainingPath ? `/${remainingPath}` : void 0;
61
- };
62
- const getLeadingLocaleParam = (path)=>{
63
- const segments = splitPathSegments(path);
64
- return getLocaleParamSegment(segments[0] || '');
65
- };
66
- const resolveLocalisedUrlsConfig = (option)=>{
67
- if (option && 'object' == typeof option && Object.keys(option).length > 0) return {
68
- enabled: true,
69
- map: option
70
- };
71
- return {
72
- enabled: false,
73
- map: {}
74
- };
75
- };
76
- const isLocalisableRoutePath = (path)=>{
77
- const pathWithoutLocale = stripLeadingLocaleParam(path);
78
- if (!pathWithoutLocale || '/' === pathWithoutLocale || '*' === pathWithoutLocale) return false;
79
- return true;
80
- };
81
- const joinPath = (parentPath, routePath)=>{
82
- if (!isLocalisableRoutePath(routePath)) return parentPath;
83
- const segment = normaliseRoutePath(stripLeadingLocaleParam(routePath) || '');
84
- return normalisePathPattern(`${parentPath}/${segment}`);
85
- };
86
- const ensureLocalisedUrlsForPath = (canonicalPath, languages, localisedUrls)=>{
87
- const entry = localisedUrls[canonicalPath];
88
- if (!entry) throw new Error(`localisedUrls is enabled, but route "${canonicalPath}" does not define localised URLs for languages: ${languages.join(', ')}. Add localisedUrls["${canonicalPath}"] or set localeDetection.localisedUrls to false.`);
89
- const missingLanguages = languages.filter((language)=>!entry[language]);
90
- if (missingLanguages.length > 0) throw new Error(`localisedUrls["${canonicalPath}"] is missing languages: ${missingLanguages.join(', ')}. Every configured language must have a localised URL.`);
91
- return entry;
92
- };
93
- const validateLocalisedUrls = (routes, languages, localisedUrls)=>{
94
- const visit = (route, parentPath)=>{
95
- const canonicalPath = joinPath(parentPath, route.path);
96
- if (isLocalisableRoutePath(route.path)) ensureLocalisedUrlsForPath(canonicalPath, languages, localisedUrls);
97
- if ('children' in route && route.children) route.children.forEach((child)=>visit(child, canonicalPath));
98
- };
99
- routes.forEach((route)=>visit(route, ''));
100
- };
101
- const getLocalisedRoutePaths = (canonicalPath, parentLocalisedPaths, languages, entry)=>{
102
- const paths = languages.map((language)=>{
103
- const fullPath = normalisePathPattern(entry[language]);
104
- const parentPath = normalisePathPattern(parentLocalisedPaths[language] || '/');
105
- if ('/' === parentPath) return normaliseRoutePath(fullPath) || void 0;
106
- const parentPrefix = `${parentPath}/`;
107
- if (!fullPath.startsWith(parentPrefix)) throw new Error(`localisedUrls["${canonicalPath}"].${language} must be nested under "${parentPath}" because its parent route is localised there.`);
108
- return normaliseRoutePath(fullPath.slice(parentPath.length));
109
- });
110
- return Array.from(new Set(paths.filter(Boolean)));
111
- };
112
- const transformLocalisedRoute = (route, parentCanonicalPath, parentLocalisedPaths, languages, localisedUrls)=>{
113
- const canonicalPath = joinPath(parentCanonicalPath, route.path);
114
- const localisedUrlEntry = isLocalisableRoutePath(route.path) ? ensureLocalisedUrlsForPath(canonicalPath, languages, localisedUrls) : void 0;
115
- const routeLocalisedPaths = localisedUrlEntry ? languages.reduce((acc, language)=>{
116
- acc[language] = normalisePathPattern(localisedUrlEntry[language]);
117
- return acc;
118
- }, {}) : parentLocalisedPaths;
119
- const children = 'children' in route && route.children ? route.children.flatMap((child)=>transformLocalisedRoute(child, canonicalPath, routeLocalisedPaths, languages, localisedUrls)) : void 0;
120
- const baseRoute = {
121
- ...route,
122
- ...children ? {
123
- children
124
- } : {}
125
- };
126
- if (!localisedUrlEntry) return [
127
- baseRoute
128
- ];
129
- return getLocalisedRoutePaths(canonicalPath, parentLocalisedPaths, languages, localisedUrlEntry).map((localisedPath, index)=>cloneRouteWithLocalisedPath(baseRoute, localisedPath, index, canonicalPath));
130
- };
131
- const legalRouteIdPart = (value)=>value.replace(/[^a-zA-Z0-9_$-]+/g, '_').replace(/^_+|_+$/g, '') || 'index';
132
- const suffixRouteIds = (route, suffix)=>{
133
- const children = 'children' in route && route.children ? route.children.map((child)=>suffixRouteIds(child, suffix)) : void 0;
134
- return {
135
- ...route,
136
- ...route.id ? {
137
- id: `${route.id}__localised_${suffix}`
138
- } : {},
139
- ...children ? {
140
- children
141
- } : {}
142
- };
143
- };
144
- const cloneRouteWithLocalisedPath = (route, path, index, canonicalPath)=>{
145
- const leadingLocaleParam = getLeadingLocaleParam(route.path);
146
- const localisedPath = leadingLocaleParam ? normaliseRoutePath(`${leadingLocaleParam}/${path}`) : path;
147
- const routeWithPath = {
148
- ...route,
149
- path: localisedPath
150
- };
151
- routeWithPath.modernCanonicalPath = canonicalPath;
152
- return 0 === index ? routeWithPath : suffixRouteIds(routeWithPath, legalRouteIdPart(localisedPath));
153
- };
154
- const applyLocalisedUrlsToRoutes = (routes, languages, localisedUrls)=>{
155
- const rootLocalisedPaths = languages.reduce((acc, language)=>{
156
- acc[language] = '/';
157
- return acc;
158
- }, {});
159
- validateLocalisedUrls(routes, languages, localisedUrls);
160
- return routes.flatMap((route)=>transformLocalisedRoute(route, '', rootLocalisedPaths, languages, localisedUrls));
161
- };
162
- const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
163
- const getParamName = (segment)=>segment.slice(1).replace(/\?$/, '');
164
- const compiledPathPatternCache = new Map();
165
- const compilePathPattern = (pattern)=>{
166
- const normalizedPattern = normalisePathPattern(pattern);
167
- const cached = compiledPathPatternCache.get(normalizedPattern);
168
- if (cached) return cached;
169
- const names = [];
170
- const segments = normalizedPattern.split('/').filter(Boolean);
171
- const source = segments.map((segment)=>{
172
- if (segment.startsWith(':')) {
173
- names.push(getParamName(segment));
174
- const paramPattern = '([^/]+)';
175
- return segment.endsWith('?') ? `(?:/${paramPattern})?` : `/${paramPattern}`;
176
- }
177
- if ('*' === segment) {
178
- names.push('*');
179
- return '/(.*)';
180
- }
181
- return `/${escapeRegExp(segment)}`;
182
- }).join('');
183
- const compiled = {
184
- names,
185
- regexp: new RegExp(`^${source || '/'}$`)
186
- };
187
- compiledPathPatternCache.set(normalizedPattern, compiled);
188
- return compiled;
189
- };
190
- const getPatternSpecificity = (pattern)=>{
191
- const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
192
- let staticSegments = 0;
193
- let dynamicSegments = 0;
194
- let splatSegments = 0;
195
- for (const segment of segments)if ('*' === segment) splatSegments++;
196
- else if (segment.startsWith(':')) dynamicSegments++;
197
- else staticSegments++;
198
- return {
199
- staticSegments,
200
- dynamicSegments,
201
- splatSegments,
202
- totalSegments: segments.length
203
- };
204
- };
205
- const comparePatternSpecificity = (left, right)=>{
206
- const a = getPatternSpecificity(left);
207
- const b = getPatternSpecificity(right);
208
- return b.staticSegments - a.staticSegments || b.totalSegments - a.totalSegments || a.splatSegments - b.splatSegments || a.dynamicSegments - b.dynamicSegments;
209
- };
210
- const sortPatternsBySpecificity = (patterns)=>patterns.map((pattern, index)=>({
211
- pattern,
212
- index
213
- })).sort((left, right)=>comparePatternSpecificity(left.pattern.pattern, right.pattern.pattern) || left.index - right.index).map(({ pattern })=>pattern);
214
- const decodePathParam = (value)=>{
215
- try {
216
- return decodeURIComponent(value);
217
- } catch {
218
- return null;
219
- }
220
- };
221
- const matchPathPattern = (pathname, pattern)=>{
222
- const { names, regexp } = compilePathPattern(pattern);
223
- const match = regexp.exec(normalisePathname(pathname));
224
- if (!match) return null;
225
- const params = {};
226
- for(let index = 0; index < names.length; index++){
227
- const decoded = decodePathParam(match[index + 1] || '');
228
- if (null === decoded) return null;
229
- params[names[index]] = decoded;
230
- }
231
- return params;
232
- };
233
- const buildPathFromPattern = (pattern, params)=>{
234
- const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
235
- const path = segments.map((segment)=>{
236
- if (segment.startsWith(':')) {
237
- const param = params[getParamName(segment)];
238
- return param ? encodeURIComponent(param) : '';
239
- }
240
- if ('*' === segment) return params['*'] || '';
241
- return segment;
242
- }).filter(Boolean).join('/');
243
- return `/${path}`;
244
- };
245
- const resolveLocalisedPath = (pathname, targetLanguage, languages, localisedUrls)=>{
246
- const normalizedPathname = normalisePathname(pathname);
247
- const canonicalCandidates = sortPatternsBySpecificity(Object.entries(localisedUrls).map(([canonicalPattern, localisedUrlEntry])=>({
248
- pattern: canonicalPattern,
249
- canonicalPattern,
250
- localisedUrlEntry
251
- })));
252
- for (const { canonicalPattern, localisedUrlEntry } of canonicalCandidates){
253
- const targetPattern = localisedUrlEntry[targetLanguage];
254
- if (!targetPattern) continue;
255
- const params = matchPathPattern(normalizedPathname, canonicalPattern);
256
- if (params) return buildPathFromPattern(targetPattern, params);
257
- }
258
- const localisedCandidates = sortPatternsBySpecificity(Object.values(localisedUrls).flatMap((localisedUrlEntry)=>{
259
- const targetPattern = localisedUrlEntry[targetLanguage];
260
- if (!targetPattern) return [];
261
- return languages.map((language)=>localisedUrlEntry[language]).filter((sourcePattern)=>Boolean(sourcePattern)).map((sourcePattern)=>({
262
- pattern: sourcePattern,
263
- sourcePattern,
264
- targetPattern
265
- }));
266
- }));
267
- for (const { sourcePattern, targetPattern } of localisedCandidates){
268
- const params = matchPathPattern(normalizedPathname, sourcePattern);
269
- if (params) return buildPathFromPattern(targetPattern, params);
270
- }
271
- return normalizedPathname;
272
- };
273
- const resolveCanonicalLocalisedPath = (pathname, languages, localisedUrls)=>{
274
- const normalizedPathname = normalisePathname(pathname);
275
- const canonicalCandidates = sortPatternsBySpecificity(Object.entries(localisedUrls).map(([canonicalPattern, localisedUrlEntry])=>({
276
- pattern: canonicalPattern,
277
- canonicalPattern,
278
- localisedUrlEntry
279
- })));
280
- for (const { canonicalPattern, localisedUrlEntry } of canonicalCandidates){
281
- const canonicalParams = matchPathPattern(normalizedPathname, canonicalPattern);
282
- if (canonicalParams) return buildPathFromPattern(canonicalPattern, canonicalParams);
283
- for (const language of languages){
284
- const sourcePattern = localisedUrlEntry[language];
285
- if (!sourcePattern) continue;
286
- const params = matchPathPattern(normalizedPathname, sourcePattern);
287
- if (params) return buildPathFromPattern(canonicalPattern, params);
288
- }
289
- }
290
- return normalizedPathname;
291
- };
292
- const stripLanguagePrefix = (pathname, languages)=>{
293
- const segments = pathname.split('/').filter(Boolean);
294
- if (segments.length > 0 && languages.includes(segments[0])) return `/${segments.slice(1).join('/')}`;
295
- return pathname || '/';
296
- };
297
- const localiseTargetPathname = (pathname, language, languages, localisedUrls)=>{
298
- const pathWithoutLanguage = stripLanguagePrefix(pathname, languages);
299
- const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
300
- const resolvedPath = localisedUrlsConfig.enabled ? resolveLocalisedPath(pathWithoutLanguage, language, languages, localisedUrlsConfig.map) : pathWithoutLanguage;
301
- const resolvedSegments = resolvedPath.split('/').filter(Boolean);
302
- return `/${[
303
- language,
304
- ...resolvedSegments
305
- ].join('/')}`;
306
- };
307
- const canonicalTargetPathname = (pathname, languages, localisedUrls)=>{
308
- const pathWithoutLanguage = stripLanguagePrefix(pathname, languages);
309
- const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
310
- return localisedUrlsConfig.enabled ? resolveCanonicalLocalisedPath(pathWithoutLanguage, languages, localisedUrlsConfig.map) : pathWithoutLanguage;
311
- };
312
- __webpack_require__.d(__webpack_exports__, {}, {
313
- applyLocalisedUrlsToRoutes: applyLocalisedUrlsToRoutes,
314
- buildPathFromPattern: buildPathFromPattern,
315
- canonicalTargetPathname: canonicalTargetPathname,
316
- localiseTargetPathname: localiseTargetPathname,
317
- matchPathPattern: matchPathPattern,
318
- normalisePathPattern: normalisePathPattern,
319
- normalisePathname: normalisePathname,
320
- resolveCanonicalLocalisedPath: resolveCanonicalLocalisedPath,
321
- resolveLocalisedPath: resolveLocalisedPath,
322
- resolveLocalisedUrlsConfig: resolveLocalisedUrlsConfig,
323
- validateLocalisedUrls: validateLocalisedUrls
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ applyLocalisedUrlsToRoutes: ()=>index_js_namespaceObject.applyLocalisedUrlsToRoutes,
32
+ buildPathFromPattern: ()=>index_js_namespaceObject.buildPathFromPattern,
33
+ canonicalTargetPathname: ()=>index_js_namespaceObject.canonicalTargetPathname,
34
+ localiseTargetPathname: ()=>index_js_namespaceObject.localiseTargetPathname,
35
+ matchPathPattern: ()=>index_js_namespaceObject.matchPathPattern,
36
+ normalisePathPattern: ()=>index_js_namespaceObject.normalisePathPattern,
37
+ normalisePathname: ()=>index_js_namespaceObject.normalisePathname,
38
+ resolveCanonicalLocalisedPath: ()=>index_js_namespaceObject.resolveCanonicalLocalisedPath,
39
+ resolveLocalisedPath: ()=>index_js_namespaceObject.resolveLocalisedPath,
40
+ resolveLocalisedUrlsConfig: ()=>index_js_namespaceObject.resolveLocalisedUrlsConfig,
41
+ validateLocalisedUrls: ()=>index_js_namespaceObject.validateLocalisedUrls
324
42
  });
43
+ const index_js_namespaceObject = require("./localisedUrls/index.js");
325
44
  exports.applyLocalisedUrlsToRoutes = __webpack_exports__.applyLocalisedUrlsToRoutes;
326
45
  exports.buildPathFromPattern = __webpack_exports__.buildPathFromPattern;
327
46
  exports.canonicalTargetPathname = __webpack_exports__.canonicalTargetPathname;
@@ -31,7 +31,8 @@ const i18nPlugin = (options = {})=>({
31
31
  backend: backendOptions,
32
32
  ...extendedConfig
33
33
  };
34
- const runtimePluginPath = customPlugin?.runtime?.path || (false === config.reactI18next ? `@${metaName}/plugin-i18n/runtime/no-react-i18next` : `@${metaName}/plugin-i18n/runtime`);
34
+ const { reactI18next } = extendedConfig;
35
+ const runtimePluginPath = customPlugin?.runtime?.path || (false === reactI18next ? `@${metaName}/plugin-i18n/runtime/no-react-i18next` : `@${metaName}/plugin-i18n/runtime`);
35
36
  plugins.push({
36
37
  name: customPlugin?.runtime?.name || 'i18n',
37
38
  path: runtimePluginPath,
@@ -1,92 +1,11 @@
1
1
  import { jsx } from "react/jsx-runtime";
2
2
  import { useMemo } from "react";
3
3
  import { useModernI18n } from "./context.mjs";
4
+ import { interpolateRouteParams, mergeClassNames, normalizeSearch, splitActiveProps, warnOnce } from "./linkHelpers.mjs";
4
5
  import { canonicalPath } from "./localizedPaths.mjs";
5
6
  import { useI18nRouterAdapter } from "./routerAdapter.mjs";
6
7
  import { buildLocalizedUrl, splitUrlTarget } from "./utils.mjs";
7
8
  const EXTERNAL_TARGET_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
8
- const warnedTargets = new Set();
9
- const warnOnce = (key, message)=>{
10
- if ('development' !== process.env.NODE_ENV || warnedTargets.has(key)) return;
11
- warnedTargets.add(key);
12
- console.warn(message);
13
- };
14
- const interpolateRouteParams = (pathname, params)=>{
15
- if (!/[$:*{]/.test(pathname)) return pathname;
16
- const resolveParam = (name)=>{
17
- const value = params?.[name];
18
- return void 0 === value ? void 0 : String(value);
19
- };
20
- const segments = pathname.split('/').map((segment)=>{
21
- if (!segment) return segment;
22
- if (segment.startsWith('{-$') && segment.endsWith('}')) {
23
- const value = resolveParam(segment.slice(3, -1));
24
- return void 0 === value ? null : encodeURIComponent(value);
25
- }
26
- if ('$' === segment || '*' === segment) {
27
- const value = resolveParam('_splat') ?? resolveParam('*');
28
- return void 0 === value ? null : value.split('/').map(encodeURIComponent).join('/');
29
- }
30
- if (segment.startsWith('$')) {
31
- const value = resolveParam(segment.slice(1));
32
- if (void 0 === value) {
33
- warnOnce(`missing-param:${pathname}:${segment}`, `[plugin-i18n] <Link to="${pathname}"> is missing required param "${segment.slice(1)}".`);
34
- return segment;
35
- }
36
- return encodeURIComponent(value);
37
- }
38
- if (segment.startsWith(':')) {
39
- const optional = segment.endsWith('?');
40
- const name = segment.slice(1, optional ? -1 : void 0);
41
- const value = resolveParam(name);
42
- if (void 0 === value) {
43
- if (optional) return null;
44
- warnOnce(`missing-param:${pathname}:${segment}`, `[plugin-i18n] <Link to="${pathname}"> is missing required param "${name}".`);
45
- return segment;
46
- }
47
- return encodeURIComponent(value);
48
- }
49
- return segment;
50
- }).filter((segment)=>null !== segment);
51
- return segments.join('/') || '/';
52
- };
53
- const normalizeSearch = (search, searchFromTo)=>{
54
- if (search && 'object' == typeof search) {
55
- const entries = Object.entries(search).filter(([, value])=>null != value);
56
- const searchObject = Object.fromEntries(entries.map(([key, value])=>[
57
- key,
58
- String(value)
59
- ]));
60
- const params = new URLSearchParams(searchObject);
61
- const serialized = params.toString();
62
- return {
63
- searchString: serialized ? `?${serialized}` : '',
64
- searchObject
65
- };
66
- }
67
- const raw = 'string' == typeof search && search ? search : searchFromTo;
68
- if (!raw) return {
69
- searchString: '',
70
- searchObject: void 0
71
- };
72
- const searchString = raw.startsWith('?') ? raw : `?${raw}`;
73
- const searchObject = {};
74
- new URLSearchParams(searchString).forEach((value, key)=>{
75
- searchObject[key] = value;
76
- });
77
- return {
78
- searchString,
79
- searchObject
80
- };
81
- };
82
- const splitActiveProps = (active, activeProps)=>{
83
- if (!active || !activeProps) return {};
84
- return activeProps;
85
- };
86
- const mergeClassNames = (...values)=>{
87
- const classNames = values.filter((value)=>'string' == typeof value && value.length > 0);
88
- return classNames.length > 0 ? classNames.join(' ') : void 0;
89
- };
90
9
  const Link = (props)=>{
91
10
  const { to, params, children, hash: hashProp, search: searchProp, hashScrollIntoView, activeOptions, activeProps, prefetch, preload, ...rest } = props;
92
11
  const adapter = useI18nRouterAdapter();
@@ -1,9 +1,7 @@
1
1
  import { jsx } from "react/jsx-runtime";
2
- import { isBrowser } from "@modern-js/runtime";
3
2
  import { createContext, useCallback, useContext, useEffect, useMemo } from "react";
4
- import { cacheUserLanguage } from "./i18n/detection/index.mjs";
3
+ import { cacheI18nLanguage, changeModernI18nLanguage, getPathLanguage, isI18nLanguageSupported, isI18nResourcesReady, translateI18n } from "./contextHelpers.mjs";
5
4
  import { useI18nRouterAdapter } from "./routerAdapter.mjs";
6
- import { buildLocalizedUrl, detectLanguageFromPath, getEntryPath, shouldIgnoreRedirect } from "./utils.mjs";
7
5
  const modernI18nContextKey = Symbol.for('@modern-js/plugin-i18n/runtime/ModernI18nContext');
8
6
  const getModernI18nContext = ()=>{
9
7
  const globalStore = globalThis;
@@ -17,14 +15,10 @@ const ModernI18nProvider = ({ children, value })=>/*#__PURE__*/ jsx(ModernI18nCo
17
15
  });
18
16
  const useModernI18n = ()=>{
19
17
  const context = useContext(ModernI18nContext);
20
- if (!context) throw new Error('useModernI18n must be used within a ModernI18nProvider');
18
+ if (!context) throw new Error('useModernI18n must be used within ModernI18nProvider');
21
19
  const { language: contextLanguage, i18nInstance, languages, localePathRedirect, ignoreRedirectRoutes, localisedUrls, updateLanguage } = context;
22
20
  const { navigate, location, hasRouter } = useI18nRouterAdapter();
23
- const pathLanguage = useMemo(()=>{
24
- if (!localePathRedirect || !location?.pathname) return;
25
- const detected = detectLanguageFromPath(location.pathname, languages || [], localePathRedirect);
26
- return detected.detected ? detected.language : void 0;
27
- }, [
21
+ const pathLanguage = useMemo(()=>getPathLanguage(location?.pathname, languages, localePathRedirect), [
28
22
  languages,
29
23
  localePathRedirect,
30
24
  location?.pathname
@@ -35,56 +29,24 @@ const useModernI18n = ()=>{
35
29
  updateLanguage?.(pathLanguage);
36
30
  i18nInstance?.setLang?.(pathLanguage);
37
31
  i18nInstance?.changeLanguage?.(pathLanguage);
38
- if (isBrowser()) {
39
- const detectionOptions = i18nInstance.options?.detection;
40
- cacheUserLanguage(i18nInstance, pathLanguage, detectionOptions);
41
- }
32
+ cacheI18nLanguage(i18nInstance, pathLanguage);
42
33
  }, [
43
34
  contextLanguage,
44
35
  i18nInstance,
45
36
  pathLanguage,
46
37
  updateLanguage
47
38
  ]);
48
- const changeLanguage = useCallback(async (newLang)=>{
49
- try {
50
- if (!newLang || 'string' != typeof newLang) throw new Error('Language must be a non-empty string');
51
- await i18nInstance?.setLang?.(newLang);
52
- await i18nInstance?.changeLanguage?.(newLang);
53
- if (isBrowser()) {
54
- const detectionOptions = i18nInstance.options?.detection;
55
- cacheUserLanguage(i18nInstance, newLang, detectionOptions);
56
- }
57
- if (localePathRedirect && isBrowser() && hasRouter && navigate && location) {
58
- const currentPath = location.pathname;
59
- const entryPath = getEntryPath();
60
- const relativePath = currentPath.replace(entryPath, '');
61
- const pathLanguage = detectLanguageFromPath(currentPath, languages || [], localePathRedirect);
62
- if (pathLanguage.detected && pathLanguage.language === newLang) return;
63
- if (!shouldIgnoreRedirect(relativePath, languages || [], ignoreRedirectRoutes)) {
64
- const newPath = buildLocalizedUrl(relativePath, newLang, languages || [], localisedUrls);
65
- const newUrl = entryPath + newPath + location.search + location.hash;
66
- await navigate(newUrl, {
67
- replace: true
68
- });
69
- }
70
- } else if (localePathRedirect && isBrowser() && !hasRouter) {
71
- const currentPath = window.location.pathname;
72
- const entryPath = getEntryPath();
73
- const relativePath = currentPath.replace(entryPath, '');
74
- const pathLanguage = detectLanguageFromPath(currentPath, languages || [], localePathRedirect);
75
- if (pathLanguage.detected && pathLanguage.language === newLang) return;
76
- if (!shouldIgnoreRedirect(relativePath, languages || [], ignoreRedirectRoutes)) {
77
- const newPath = buildLocalizedUrl(relativePath, newLang, languages || [], localisedUrls);
78
- const newUrl = entryPath + newPath + window.location.search + window.location.hash;
79
- window.history.pushState(null, '', newUrl);
80
- }
81
- }
82
- if (updateLanguage) updateLanguage(newLang);
83
- } catch (error) {
84
- console.error('Failed to change language:', error);
85
- throw error;
86
- }
87
- }, [
39
+ const changeLanguage = useCallback((newLang)=>changeModernI18nLanguage(newLang, {
40
+ i18nInstance,
41
+ updateLanguage,
42
+ localePathRedirect,
43
+ ignoreRedirectRoutes,
44
+ localisedUrls,
45
+ languages,
46
+ hasRouter,
47
+ navigate,
48
+ location
49
+ }), [
88
50
  i18nInstance,
89
51
  updateLanguage,
90
52
  localePathRedirect,
@@ -95,40 +57,14 @@ const useModernI18n = ()=>{
95
57
  navigate,
96
58
  location
97
59
  ]);
98
- const t = useCallback((key, ...args)=>{
99
- if ('function' != typeof i18nInstance.t) throw new Error('i18nInstance.t is required');
100
- return i18nInstance.t(key, ...args);
101
- }, [
60
+ const t = useCallback((key, ...args)=>translateI18n(i18nInstance, key, ...args), [
102
61
  currentLanguage,
103
62
  i18nInstance
104
63
  ]);
105
- const isLanguageSupported = useCallback((lang)=>languages?.includes(lang) || false, [
64
+ const isLanguageSupported = useCallback((lang)=>isI18nLanguageSupported(languages, lang), [
106
65
  languages
107
66
  ]);
108
- const isResourcesReady = useMemo(()=>{
109
- if (!i18nInstance?.isInitialized) return false;
110
- const backend = i18nInstance?.services?.backend;
111
- if (backend && 'function' == typeof backend.isLoading) {
112
- const loadingResources = backend.getLoadingResources();
113
- const isCurrentLanguageLoading = loadingResources.some(({ language })=>language === currentLanguage);
114
- if (isCurrentLanguageLoading) return false;
115
- }
116
- const store = i18nInstance.store;
117
- if (!store?.data) return false;
118
- const langData = store.data[currentLanguage];
119
- if (!langData || 'object' != typeof langData) return false;
120
- const options = i18nInstance.options;
121
- const namespaces = options?.ns || options?.defaultNS || [
122
- 'translation'
123
- ];
124
- const requiredNamespaces = Array.isArray(namespaces) ? namespaces : [
125
- namespaces
126
- ];
127
- return requiredNamespaces.every((ns)=>{
128
- const nsData = langData[ns];
129
- return nsData && 'object' == typeof nsData && Object.keys(nsData).length > 0;
130
- });
131
- }, [
67
+ const isResourcesReady = useMemo(()=>isI18nResourcesReady(i18nInstance, currentLanguage), [
132
68
  currentLanguage,
133
69
  i18nInstance
134
70
  ]);
@@ -0,0 +1,84 @@
1
+ import { isBrowser } from "@modern-js/runtime";
2
+ import { cacheUserLanguage } from "./i18n/detection/index.mjs";
3
+ import { buildLocalizedUrl, detectLanguageFromPath, getEntryPath, shouldIgnoreRedirect } from "./utils.mjs";
4
+ function getPathLanguage(pathname, languages, localePathRedirect) {
5
+ if (!localePathRedirect || !pathname) return;
6
+ const detected = detectLanguageFromPath(pathname, languages || [], localePathRedirect);
7
+ return detected.detected ? detected.language : void 0;
8
+ }
9
+ function cacheI18nLanguage(i18nInstance, language) {
10
+ if (isBrowser()) {
11
+ const detectionOptions = i18nInstance.options?.detection;
12
+ cacheUserLanguage(i18nInstance, language, detectionOptions);
13
+ }
14
+ }
15
+ async function changeModernI18nLanguage(newLang, options) {
16
+ const { i18nInstance, updateLanguage, localePathRedirect, ignoreRedirectRoutes, localisedUrls, languages, hasRouter, navigate, location } = options;
17
+ try {
18
+ if (!newLang || 'string' != typeof newLang) throw new Error('Language must be non-empty string');
19
+ await i18nInstance?.setLang?.(newLang);
20
+ await i18nInstance?.changeLanguage?.(newLang);
21
+ cacheI18nLanguage(i18nInstance, newLang);
22
+ if (localePathRedirect && isBrowser() && hasRouter && navigate && location) {
23
+ const currentPath = location.pathname;
24
+ const entryPath = getEntryPath();
25
+ const relativePath = currentPath.replace(entryPath, '');
26
+ const pathLanguage = detectLanguageFromPath(currentPath, languages || [], localePathRedirect);
27
+ if (pathLanguage.detected && pathLanguage.language === newLang) return void updateLanguage?.(newLang);
28
+ if (!shouldIgnoreRedirect(relativePath, languages || [], ignoreRedirectRoutes)) {
29
+ const newPath = buildLocalizedUrl(relativePath, newLang, languages || [], localisedUrls);
30
+ const newUrl = entryPath + newPath + location.search + location.hash;
31
+ await navigate(newUrl, {
32
+ replace: true
33
+ });
34
+ }
35
+ } else if (localePathRedirect && isBrowser() && !hasRouter) {
36
+ const currentPath = window.location.pathname;
37
+ const entryPath = getEntryPath();
38
+ const relativePath = currentPath.replace(entryPath, '');
39
+ const pathLanguage = detectLanguageFromPath(currentPath, languages || [], localePathRedirect);
40
+ if (pathLanguage.detected && pathLanguage.language === newLang) return void updateLanguage?.(newLang);
41
+ if (!shouldIgnoreRedirect(relativePath, languages || [], ignoreRedirectRoutes)) {
42
+ const newPath = buildLocalizedUrl(relativePath, newLang, languages || [], localisedUrls);
43
+ const newUrl = entryPath + newPath + window.location.search + window.location.hash;
44
+ window.history.pushState(null, '', newUrl);
45
+ }
46
+ }
47
+ if (updateLanguage) updateLanguage(newLang);
48
+ } catch (error) {
49
+ console.error('Failed change language:', error);
50
+ throw error;
51
+ }
52
+ }
53
+ function translateI18n(i18nInstance, key, ...args) {
54
+ if ('function' != typeof i18nInstance.t) throw new Error('i18nInstance.t required');
55
+ return i18nInstance.t(key, ...args);
56
+ }
57
+ function isI18nLanguageSupported(languages, lang) {
58
+ return languages?.includes(lang) || false;
59
+ }
60
+ function isI18nResourcesReady(i18nInstance, currentLanguage) {
61
+ if (!i18nInstance?.isInitialized) return false;
62
+ const backend = i18nInstance?.services?.backend;
63
+ if (backend && 'function' == typeof backend.isLoading) {
64
+ const loadingResources = backend.getLoadingResources();
65
+ const isCurrentLanguageLoading = loadingResources.some(({ language })=>language === currentLanguage);
66
+ if (isCurrentLanguageLoading) return false;
67
+ }
68
+ const store = i18nInstance.store;
69
+ if (!store?.data) return false;
70
+ const langData = store.data[currentLanguage];
71
+ if (!langData || 'object' != typeof langData) return false;
72
+ const options = i18nInstance.options;
73
+ const namespaces = options?.ns || options?.defaultNS || [
74
+ 'translation'
75
+ ];
76
+ const requiredNamespaces = Array.isArray(namespaces) ? namespaces : [
77
+ namespaces
78
+ ];
79
+ return requiredNamespaces.every((ns)=>{
80
+ const nsData = langData[ns];
81
+ return nsData && 'object' == typeof nsData && Object.keys(nsData).length > 0;
82
+ });
83
+ }
84
+ export { cacheI18nLanguage, changeModernI18nLanguage, getPathLanguage, isI18nLanguageSupported, isI18nResourcesReady, translateI18n };