@formatjs/intl-localematcher 0.8.2 → 0.8.4
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.
- package/index.d.ts +29 -5
- package/index.js +3723 -5
- package/index.js.map +1 -0
- package/package.json +2 -2
- package/abstract/BestAvailableLocale.d.ts +0 -6
- package/abstract/BestAvailableLocale.js +0 -29
- package/abstract/BestFitMatcher.d.ts +0 -8
- package/abstract/BestFitMatcher.js +0 -30
- package/abstract/CanonicalizeLocaleList.d.ts +0 -5
- package/abstract/CanonicalizeLocaleList.js +0 -7
- package/abstract/CanonicalizeUValue.d.ts +0 -1
- package/abstract/CanonicalizeUValue.js +0 -8
- package/abstract/CanonicalizeUnicodeLocaleId.d.ts +0 -1
- package/abstract/CanonicalizeUnicodeLocaleId.js +0 -3
- package/abstract/InsertUnicodeExtensionAndCanonicalize.d.ts +0 -2
- package/abstract/InsertUnicodeExtensionAndCanonicalize.js +0 -29
- package/abstract/LookupMatcher.d.ts +0 -8
- package/abstract/LookupMatcher.js +0 -24
- package/abstract/LookupSupportedLocales.d.ts +0 -6
- package/abstract/LookupSupportedLocales.js +0 -18
- package/abstract/ResolveLocale.d.ts +0 -15
- package/abstract/ResolveLocale.js +0 -95
- package/abstract/UnicodeExtensionComponents.d.ts +0 -5
- package/abstract/UnicodeExtensionComponents.js +0 -44
- package/abstract/UnicodeExtensionValue.d.ts +0 -6
- package/abstract/UnicodeExtensionValue.js +0 -43
- package/abstract/languageMatching.d.ts +0 -2240
- package/abstract/languageMatching.js +0 -1846
- package/abstract/regions.generated.d.ts +0 -1
- package/abstract/regions.generated.js +0 -1334
- package/abstract/types.d.ts +0 -9
- package/abstract/types.js +0 -1
- package/abstract/utils.d.ts +0 -46
- package/abstract/utils.js +0 -349
package/abstract/types.d.ts
DELETED
package/abstract/types.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/abstract/utils.d.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
export declare const UNICODE_EXTENSION_SEQUENCE_REGEX: RegExp;
|
|
2
|
-
/**
|
|
3
|
-
* Asserts that a condition is true, throwing an error if it is not.
|
|
4
|
-
* Used for runtime validation and type narrowing.
|
|
5
|
-
*
|
|
6
|
-
* @param condition - The condition to check
|
|
7
|
-
* @param message - Error message if condition is false
|
|
8
|
-
* @param Err - Error constructor to use (defaults to Error)
|
|
9
|
-
* @throws {Error} When condition is false
|
|
10
|
-
*
|
|
11
|
-
* @example
|
|
12
|
-
* ```ts
|
|
13
|
-
* invariant(locale !== undefined, 'Locale must be defined')
|
|
14
|
-
* // locale is now narrowed to non-undefined type
|
|
15
|
-
* ```
|
|
16
|
-
*/
|
|
17
|
-
export declare function invariant(condition: boolean, message: string, Err?: any): asserts condition;
|
|
18
|
-
/**
|
|
19
|
-
* Calculates the matching distance between two locales using the CLDR Enhanced Language Matching algorithm.
|
|
20
|
-
* This function is memoized for performance, as distance calculations are expensive.
|
|
21
|
-
*
|
|
22
|
-
* The distance represents how "far apart" two locales are, with 0 being identical (after maximization).
|
|
23
|
-
* Distances are calculated based on Language-Script-Region (LSR) differences using CLDR data.
|
|
24
|
-
*
|
|
25
|
-
* @param desired - The desired locale (e.g., "en-US")
|
|
26
|
-
* @param supported - The supported locale to compare against (e.g., "en-GB")
|
|
27
|
-
* @returns The calculated distance between the locales
|
|
28
|
-
*
|
|
29
|
-
* @example
|
|
30
|
-
* ```ts
|
|
31
|
-
* findMatchingDistance('en-US', 'en-US') // 0 - identical
|
|
32
|
-
* findMatchingDistance('en-US', 'en-GB') // 40 - same language/script, different region
|
|
33
|
-
* findMatchingDistance('es-CO', 'es-419') // 39 - regional variant
|
|
34
|
-
* findMatchingDistance('en', 'fr') // 840 - completely different languages
|
|
35
|
-
* ```
|
|
36
|
-
*
|
|
37
|
-
* @see https://unicode.org/reports/tr35/#EnhancedLanguageMatching
|
|
38
|
-
*/
|
|
39
|
-
export declare const findMatchingDistance: (desired: string, supported: string) => number;
|
|
40
|
-
interface LocaleMatchingResult {
|
|
41
|
-
distances: Record<string, Record<string, number>>;
|
|
42
|
-
matchedSupportedLocale?: string;
|
|
43
|
-
matchedDesiredLocale?: string;
|
|
44
|
-
}
|
|
45
|
-
export declare function findBestMatch(requestedLocales: readonly string[], supportedLocales: readonly string[], threshold?: number): LocaleMatchingResult;
|
|
46
|
-
export {};
|
package/abstract/utils.js
DELETED
|
@@ -1,349 +0,0 @@
|
|
|
1
|
-
import { memoize } from "@formatjs/fast-memoize";
|
|
2
|
-
import { data as jsonData } from "./languageMatching.js";
|
|
3
|
-
import { regions } from "./regions.generated.js";
|
|
4
|
-
export const UNICODE_EXTENSION_SEQUENCE_REGEX = /-u(?:-[0-9a-z]{2,8})+/gi;
|
|
5
|
-
/**
|
|
6
|
-
* Asserts that a condition is true, throwing an error if it is not.
|
|
7
|
-
* Used for runtime validation and type narrowing.
|
|
8
|
-
*
|
|
9
|
-
* @param condition - The condition to check
|
|
10
|
-
* @param message - Error message if condition is false
|
|
11
|
-
* @param Err - Error constructor to use (defaults to Error)
|
|
12
|
-
* @throws {Error} When condition is false
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* ```ts
|
|
16
|
-
* invariant(locale !== undefined, 'Locale must be defined')
|
|
17
|
-
* // locale is now narrowed to non-undefined type
|
|
18
|
-
* ```
|
|
19
|
-
*/
|
|
20
|
-
export function invariant(condition, message, Err = Error) {
|
|
21
|
-
if (!condition) {
|
|
22
|
-
throw new Err(message);
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
// This is effectively 2 languages in 2 different regions in the same cluster
|
|
26
|
-
const DEFAULT_MATCHING_THRESHOLD = 838;
|
|
27
|
-
let PROCESSED_DATA;
|
|
28
|
-
function processData() {
|
|
29
|
-
if (!PROCESSED_DATA) {
|
|
30
|
-
const paradigmLocales = jsonData.supplemental.languageMatching["written-new"][0]?.paradigmLocales?._locales.split(" ");
|
|
31
|
-
const matchVariables = jsonData.supplemental.languageMatching["written-new"].slice(1, 5);
|
|
32
|
-
const data = jsonData.supplemental.languageMatching["written-new"].slice(5);
|
|
33
|
-
const matches = data.map((d) => {
|
|
34
|
-
const key = Object.keys(d)[0];
|
|
35
|
-
const value = d[key];
|
|
36
|
-
return {
|
|
37
|
-
supported: key,
|
|
38
|
-
desired: value._desired,
|
|
39
|
-
distance: +value._distance,
|
|
40
|
-
oneway: value.oneway === "true" ? true : false
|
|
41
|
-
};
|
|
42
|
-
}, {});
|
|
43
|
-
PROCESSED_DATA = {
|
|
44
|
-
matches,
|
|
45
|
-
matchVariables: matchVariables.reduce((all, d) => {
|
|
46
|
-
const key = Object.keys(d)[0];
|
|
47
|
-
const value = d[key];
|
|
48
|
-
all[key.slice(1)] = value._value.split("+");
|
|
49
|
-
return all;
|
|
50
|
-
}, {}),
|
|
51
|
-
paradigmLocales: [...paradigmLocales, ...paradigmLocales.map((l) => new Intl.Locale(l.replace(/_/g, "-")).maximize().toString())]
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
return PROCESSED_DATA;
|
|
55
|
-
}
|
|
56
|
-
function isMatched(locale, languageMatchInfoLocale, matchVariables) {
|
|
57
|
-
const [language, script, region] = languageMatchInfoLocale.split("-");
|
|
58
|
-
let matches = true;
|
|
59
|
-
if (region && region[0] === "$") {
|
|
60
|
-
const shouldInclude = region[1] !== "!";
|
|
61
|
-
const matchRegions = shouldInclude ? matchVariables[region.slice(1)] : matchVariables[region.slice(2)];
|
|
62
|
-
const expandedMatchedRegions = matchRegions.map((r) => regions[r] || [r]).reduce((all, list) => [...all, ...list], []);
|
|
63
|
-
matches &&= !(expandedMatchedRegions.indexOf(locale.region || "") > -1 != shouldInclude);
|
|
64
|
-
} else {
|
|
65
|
-
matches &&= locale.region ? region === "*" || region === locale.region : true;
|
|
66
|
-
}
|
|
67
|
-
matches &&= locale.script ? script === "*" || script === locale.script : true;
|
|
68
|
-
matches &&= locale.language ? language === "*" || language === locale.language : true;
|
|
69
|
-
return matches;
|
|
70
|
-
}
|
|
71
|
-
function serializeLSR(lsr) {
|
|
72
|
-
return [
|
|
73
|
-
lsr.language,
|
|
74
|
-
lsr.script,
|
|
75
|
-
lsr.region
|
|
76
|
-
].filter(Boolean).join("-");
|
|
77
|
-
}
|
|
78
|
-
function findMatchingDistanceForLSR(desired, supported, data) {
|
|
79
|
-
for (const d of data.matches) {
|
|
80
|
-
let matches = isMatched(desired, d.desired, data.matchVariables) && isMatched(supported, d.supported, data.matchVariables);
|
|
81
|
-
if (!d.oneway && !matches) {
|
|
82
|
-
matches = isMatched(desired, d.supported, data.matchVariables) && isMatched(supported, d.desired, data.matchVariables);
|
|
83
|
-
}
|
|
84
|
-
if (matches) {
|
|
85
|
-
const distance = d.distance * 10;
|
|
86
|
-
if (data.paradigmLocales.indexOf(serializeLSR(desired)) > -1 != data.paradigmLocales.indexOf(serializeLSR(supported)) > -1) {
|
|
87
|
-
return distance - 1;
|
|
88
|
-
}
|
|
89
|
-
return distance;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
throw new Error("No matching distance found");
|
|
93
|
-
}
|
|
94
|
-
function findMatchingDistanceImpl(desired, supported) {
|
|
95
|
-
const desiredLocale = new Intl.Locale(desired).maximize();
|
|
96
|
-
const supportedLocale = new Intl.Locale(supported).maximize();
|
|
97
|
-
const desiredLSR = {
|
|
98
|
-
language: desiredLocale.language,
|
|
99
|
-
script: desiredLocale.script || "",
|
|
100
|
-
region: desiredLocale.region || ""
|
|
101
|
-
};
|
|
102
|
-
const supportedLSR = {
|
|
103
|
-
language: supportedLocale.language,
|
|
104
|
-
script: supportedLocale.script || "",
|
|
105
|
-
region: supportedLocale.region || ""
|
|
106
|
-
};
|
|
107
|
-
let matchingDistance = 0;
|
|
108
|
-
const data = processData();
|
|
109
|
-
if (desiredLSR.language !== supportedLSR.language) {
|
|
110
|
-
matchingDistance += findMatchingDistanceForLSR({
|
|
111
|
-
language: desiredLocale.language,
|
|
112
|
-
script: "",
|
|
113
|
-
region: ""
|
|
114
|
-
}, {
|
|
115
|
-
language: supportedLocale.language,
|
|
116
|
-
script: "",
|
|
117
|
-
region: ""
|
|
118
|
-
}, data);
|
|
119
|
-
}
|
|
120
|
-
if (desiredLSR.script !== supportedLSR.script) {
|
|
121
|
-
matchingDistance += findMatchingDistanceForLSR({
|
|
122
|
-
language: desiredLocale.language,
|
|
123
|
-
script: desiredLSR.script,
|
|
124
|
-
region: ""
|
|
125
|
-
}, {
|
|
126
|
-
language: supportedLocale.language,
|
|
127
|
-
script: supportedLSR.script,
|
|
128
|
-
region: ""
|
|
129
|
-
}, data);
|
|
130
|
-
}
|
|
131
|
-
if (desiredLSR.region !== supportedLSR.region) {
|
|
132
|
-
matchingDistance += findMatchingDistanceForLSR(desiredLSR, supportedLSR, data);
|
|
133
|
-
}
|
|
134
|
-
return matchingDistance;
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* Calculates the matching distance between two locales using the CLDR Enhanced Language Matching algorithm.
|
|
138
|
-
* This function is memoized for performance, as distance calculations are expensive.
|
|
139
|
-
*
|
|
140
|
-
* The distance represents how "far apart" two locales are, with 0 being identical (after maximization).
|
|
141
|
-
* Distances are calculated based on Language-Script-Region (LSR) differences using CLDR data.
|
|
142
|
-
*
|
|
143
|
-
* @param desired - The desired locale (e.g., "en-US")
|
|
144
|
-
* @param supported - The supported locale to compare against (e.g., "en-GB")
|
|
145
|
-
* @returns The calculated distance between the locales
|
|
146
|
-
*
|
|
147
|
-
* @example
|
|
148
|
-
* ```ts
|
|
149
|
-
* findMatchingDistance('en-US', 'en-US') // 0 - identical
|
|
150
|
-
* findMatchingDistance('en-US', 'en-GB') // 40 - same language/script, different region
|
|
151
|
-
* findMatchingDistance('es-CO', 'es-419') // 39 - regional variant
|
|
152
|
-
* findMatchingDistance('en', 'fr') // 840 - completely different languages
|
|
153
|
-
* ```
|
|
154
|
-
*
|
|
155
|
-
* @see https://unicode.org/reports/tr35/#EnhancedLanguageMatching
|
|
156
|
-
*/
|
|
157
|
-
export const findMatchingDistance = memoize(findMatchingDistanceImpl, { serializer: (args) => `${args[0]}|${args[1]}` });
|
|
158
|
-
/**
|
|
159
|
-
* Generates fallback candidates by progressively removing subtags
|
|
160
|
-
* e.g., "en-US" -> ["en-US", "en"]
|
|
161
|
-
* "zh-Hans-CN" -> ["zh-Hans-CN", "zh-Hans", "zh"]
|
|
162
|
-
*/
|
|
163
|
-
function getFallbackCandidates(locale) {
|
|
164
|
-
const candidates = [];
|
|
165
|
-
let current = locale;
|
|
166
|
-
while (current) {
|
|
167
|
-
candidates.push(current);
|
|
168
|
-
const lastDash = current.lastIndexOf("-");
|
|
169
|
-
if (lastDash === -1) break;
|
|
170
|
-
current = current.substring(0, lastDash);
|
|
171
|
-
}
|
|
172
|
-
return candidates;
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
* Finds the best locale match using a three-tier optimization hierarchy.
|
|
176
|
-
*
|
|
177
|
-
* ## Three-Tier Matching Algorithm:
|
|
178
|
-
*
|
|
179
|
-
* **Tier 1 - Fast Path** (O(n)): Exact string matching via Set lookup
|
|
180
|
-
* - Example: 'en' matches 'en' exactly → distance 0
|
|
181
|
-
* - Solves #4936: 48x faster than baseline (12ms vs 610ms with 700+ locales)
|
|
182
|
-
*
|
|
183
|
-
* **Tier 2 - Fallback Path** (O(k×n)): Maximization + progressive subtag removal
|
|
184
|
-
* - Maximizes requested locale, then removes subtags right-to-left
|
|
185
|
-
* - Example: "zh-TW" → "zh-Hant-TW" → ["zh-Hant-TW", "zh-Hant", "zh"]
|
|
186
|
-
* - Distance: 0 for maximized match, 10 per removed subtag + position penalty
|
|
187
|
-
* - 40-50x faster than full UTS #35, handles 99% of real-world cases correctly
|
|
188
|
-
*
|
|
189
|
-
* **Tier 3 - Slow Path** (O(n×m), memoized): Full UTS #35 CLDR matching
|
|
190
|
-
* - Calculates Language-Script-Region distances using CLDR data
|
|
191
|
-
* - Handles complex cases like cross-script matching (sr-Cyrl ↔ sr-Latn)
|
|
192
|
-
* - Only used when Tiers 1 & 2 find no match
|
|
193
|
-
* - Still 6x faster than baseline due to memoization
|
|
194
|
-
*
|
|
195
|
-
* ## Performance Impact of Maximization:
|
|
196
|
-
*
|
|
197
|
-
* While Tier 2 now calls `Intl.Locale().maximize()` once per requested locale,
|
|
198
|
-
* this is still much faster than Tier 3's full distance calculation:
|
|
199
|
-
* - Tier 1: ~12ms (exact match, no maximization)
|
|
200
|
-
* - Tier 2: ~13-15ms (maximization + fallback)
|
|
201
|
-
* - Tier 3: ~100ms+ (full UTS #35 with all supported locales)
|
|
202
|
-
*
|
|
203
|
-
* @param requestedLocales - Locale identifiers in preference order
|
|
204
|
-
* @param supportedLocales - Available locale identifiers
|
|
205
|
-
* @param threshold - Maximum distance (default: 838, from CLDR)
|
|
206
|
-
* @returns Matching result with distances
|
|
207
|
-
*
|
|
208
|
-
* @example
|
|
209
|
-
* ```ts
|
|
210
|
-
* // Tier 1: Exact match
|
|
211
|
-
* findBestMatch(['en'], ['en', 'fr'])
|
|
212
|
-
* // → { matchedSupportedLocale: 'en', distances: { en: { en: 0 } } }
|
|
213
|
-
*
|
|
214
|
-
* // Tier 2: Fallback with maximization
|
|
215
|
-
* findBestMatch(['zh-TW'], ['zh-Hant'])
|
|
216
|
-
* // → zh-TW maximizes to zh-Hant-TW, falls back to zh-Hant (distance 0)
|
|
217
|
-
*
|
|
218
|
-
* findBestMatch(['en-US'], ['en'])
|
|
219
|
-
* // → en-US maximizes to en-Latn-US, falls back to en (distance 10)
|
|
220
|
-
*
|
|
221
|
-
* // Tier 3: Full calculation
|
|
222
|
-
* findBestMatch(['en-XZ'], ['ja', 'ko'])
|
|
223
|
-
* // → No fallback match, uses UTS #35 to find closest match
|
|
224
|
-
* ```
|
|
225
|
-
*
|
|
226
|
-
* @see https://unicode.org/reports/tr35/#EnhancedLanguageMatching
|
|
227
|
-
* @see https://github.com/formatjs/formatjs/issues/4936
|
|
228
|
-
*/
|
|
229
|
-
// WeakMap to cache canonicalized supported locales arrays
|
|
230
|
-
const canonicalizedSupportedCache = new WeakMap();
|
|
231
|
-
export function findBestMatch(requestedLocales, supportedLocales, threshold = DEFAULT_MATCHING_THRESHOLD) {
|
|
232
|
-
let lowestDistance = Infinity;
|
|
233
|
-
let result = {
|
|
234
|
-
matchedDesiredLocale: "",
|
|
235
|
-
distances: {}
|
|
236
|
-
};
|
|
237
|
-
// Get or compute canonicalized supported locales (one by one to preserve indices)
|
|
238
|
-
let canonicalizedSupportedLocales = canonicalizedSupportedCache.get(supportedLocales);
|
|
239
|
-
if (!canonicalizedSupportedLocales) {
|
|
240
|
-
canonicalizedSupportedLocales = supportedLocales.map((locale) => {
|
|
241
|
-
try {
|
|
242
|
-
const canonical = Intl.getCanonicalLocales([locale]);
|
|
243
|
-
return canonical[0] || locale;
|
|
244
|
-
} catch {
|
|
245
|
-
return locale;
|
|
246
|
-
}
|
|
247
|
-
});
|
|
248
|
-
canonicalizedSupportedCache.set(supportedLocales, canonicalizedSupportedLocales);
|
|
249
|
-
}
|
|
250
|
-
const supportedSet = new Set(canonicalizedSupportedLocales);
|
|
251
|
-
// === TIER 1: FAST PATH - Exact Match ===
|
|
252
|
-
// Check for exact matches in ALL requested locales
|
|
253
|
-
// This is the fastest path and handles the majority of real-world cases
|
|
254
|
-
for (let i = 0; i < requestedLocales.length; i++) {
|
|
255
|
-
const desired = requestedLocales[i];
|
|
256
|
-
if (supportedSet.has(desired)) {
|
|
257
|
-
const distance = 0 + i * 40;
|
|
258
|
-
result.distances[desired] = { [desired]: distance };
|
|
259
|
-
if (distance < lowestDistance) {
|
|
260
|
-
lowestDistance = distance;
|
|
261
|
-
result.matchedDesiredLocale = desired;
|
|
262
|
-
result.matchedSupportedLocale = desired;
|
|
263
|
-
}
|
|
264
|
-
// Only return immediately if this is the first requested locale (distance=0)
|
|
265
|
-
// Otherwise, continue checking for potentially better matches
|
|
266
|
-
if (i === 0) {
|
|
267
|
-
return result;
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
// If we found an exact match in Tier 1 (but not for first locale), check Tier 2
|
|
272
|
-
// to see if there's a better fallback match with lower distance
|
|
273
|
-
// If no exact match found, Tier 2 will find fallback matches
|
|
274
|
-
// === TIER 2: FALLBACK PATH - Maximization + Progressive Subtag Removal ===
|
|
275
|
-
// Try maximization-based matching before resorting to expensive Tier 3
|
|
276
|
-
// This handles cases like zh-TW → zh-Hant efficiently
|
|
277
|
-
for (let i = 0; i < requestedLocales.length; i++) {
|
|
278
|
-
const desired = requestedLocales[i];
|
|
279
|
-
// Maximize then fallback (for linguistic accuracy like zh-TW → zh-Hant)
|
|
280
|
-
try {
|
|
281
|
-
const maximized = new Intl.Locale(desired).maximize().toString();
|
|
282
|
-
if (maximized !== desired) {
|
|
283
|
-
const maximizedCandidates = getFallbackCandidates(maximized);
|
|
284
|
-
for (let j = 0; j < maximizedCandidates.length; j++) {
|
|
285
|
-
const candidate = maximizedCandidates[j];
|
|
286
|
-
if (candidate === desired) continue;
|
|
287
|
-
if (supportedSet.has(candidate)) {
|
|
288
|
-
// Check if candidate also maximizes to the same form
|
|
289
|
-
// e.g., zh-TW → zh-Hant-TW and zh-Hant → zh-Hant-TW (distance 0)
|
|
290
|
-
// but es-co → es-Latn-CO and es → es-Latn-ES (distance 10)
|
|
291
|
-
let distance;
|
|
292
|
-
try {
|
|
293
|
-
const candidateMaximized = new Intl.Locale(candidate).maximize().toString();
|
|
294
|
-
distance = candidateMaximized === maximized ? 0 + i * 40 : j * 10 + i * 40;
|
|
295
|
-
} catch {
|
|
296
|
-
distance = j * 10 + i * 40;
|
|
297
|
-
}
|
|
298
|
-
if (!result.distances[desired]) {
|
|
299
|
-
result.distances[desired] = {};
|
|
300
|
-
}
|
|
301
|
-
result.distances[desired][candidate] = distance;
|
|
302
|
-
if (distance < lowestDistance) {
|
|
303
|
-
lowestDistance = distance;
|
|
304
|
-
result.matchedDesiredLocale = desired;
|
|
305
|
-
result.matchedSupportedLocale = candidate;
|
|
306
|
-
}
|
|
307
|
-
break;
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
} catch {}
|
|
312
|
-
}
|
|
313
|
-
// If Tier 2 found a perfect maximized match (distance 0), return immediately (fast path)
|
|
314
|
-
if (result.matchedSupportedLocale && lowestDistance === 0) {
|
|
315
|
-
return result;
|
|
316
|
-
}
|
|
317
|
-
// === TIER 3: SLOW PATH - Full UTS #35 Distance Calculation ===
|
|
318
|
-
// Always run Tier 3 for full CLDR accuracy
|
|
319
|
-
// Tier 3 may find better matches than Tier 2's fallback approach
|
|
320
|
-
// findMatchingDistance is memoized, so repeated calculations are cached
|
|
321
|
-
requestedLocales.forEach((desired, i) => {
|
|
322
|
-
if (!result.distances[desired]) {
|
|
323
|
-
result.distances[desired] = {};
|
|
324
|
-
}
|
|
325
|
-
canonicalizedSupportedLocales.forEach((canonicalLocale, supportedIndex) => {
|
|
326
|
-
const originalSupported = supportedLocales[supportedIndex];
|
|
327
|
-
// findMatchingDistance is memoized via fast-memoize
|
|
328
|
-
// Use the canonical locale for distance calculation
|
|
329
|
-
const distance = findMatchingDistance(desired, canonicalLocale);
|
|
330
|
-
// Add some weight to the distance based on the order of the supported locales
|
|
331
|
-
// Add penalty for the order of the requested locales, which currently is 0 since ECMA-402
|
|
332
|
-
// doesn't really have room for weighted locales like `en; q=0.1`
|
|
333
|
-
const finalDistance = distance + 0 + i * 40;
|
|
334
|
-
// Store and return the original locale, not the canonical one
|
|
335
|
-
// Tier 3 overwrites Tier 2 distances (Tier 3 is more accurate)
|
|
336
|
-
result.distances[desired][originalSupported] = finalDistance;
|
|
337
|
-
if (finalDistance < lowestDistance) {
|
|
338
|
-
lowestDistance = finalDistance;
|
|
339
|
-
result.matchedDesiredLocale = desired;
|
|
340
|
-
result.matchedSupportedLocale = originalSupported;
|
|
341
|
-
}
|
|
342
|
-
});
|
|
343
|
-
});
|
|
344
|
-
if (lowestDistance >= threshold) {
|
|
345
|
-
result.matchedDesiredLocale = undefined;
|
|
346
|
-
result.matchedSupportedLocale = undefined;
|
|
347
|
-
}
|
|
348
|
-
return result;
|
|
349
|
-
}
|