-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathIntl.js
4402 lines (3732 loc) · 203 KB
/
Intl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
"use strict";
// Core intl lib
(function (EngineInterface, InitType) {
var platform = EngineInterface.Intl;
// allow unit tests to disable caching behavior for testing convenience but have this always `true` in real scenarios
platform.useCaches = true;
// determine what backing library we are using
// making these vars in JS allows us to more change how we
// determine the backing library
const isPlatformUsingICU = !platform.winglob;
const isPlatformUsingWinGlob = platform.winglob;
// constants
const NOT_FOUND = "NOT_FOUND";
// Built-Ins
var setPrototype = platform.builtInSetPrototype;
var getArrayLength = platform.builtInGetArrayLength;
var callInstanceFunc = platform.builtInCallInstanceFunction;
// Helper for our extensive usage of null-prototyped objects
const bare = (obj = {}) => setPrototype(obj, null);
// REVIEW(jahorto): IntlCache replaces past use of raw objects and JS Maps to cache arbitrary data for a given locale
// We use a raw object rather than a Map because we don't need any features specific to Maps
// If the cache gets too big (arbitrarily, > 25 keys is "too big" by default), we delete the entire internal object and start from scratch
// TODO(jahorto): Experiment with the performance benefit of using an LRU or random-delete cache here.
class IntlCache {
constructor(n = 25) {
this.n = n;
this._cache = _.create();
}
get(key) {
return platform.useCaches ? this._cache[key] : undefined;
}
set(key, value) {
if (!platform.useCaches) {
return;
}
if (_.keys(this._cache).length > this.n && this._cache[key] === undefined) {
this._cache = _.create();
}
this._cache[key] = value;
}
}
var Boolean = platform.Boolean;
var Object = platform.Object;
var RegExp = platform.RegExp;
var Number = platform.Number;
var String = platform.String;
var Date = platform.Date;
var Error = platform.Error;
var Map = platform.Map;
var RaiseAssert = platform.raiseAssert;
var Math = setPrototype({
abs: platform.builtInMathAbs,
floor: platform.builtInMathFloor,
max: platform.builtInMathMax,
pow: platform.builtInMathPow
}, null);
var ObjectGetPrototypeOf = platform.builtInJavascriptObjectEntryGetPrototypeOf;
var ObjectIsExtensible = platform.builtInJavascriptObjectEntryIsExtensible;
var ObjectGetOwnPropertyNames = platform.builtInJavascriptObjectEntryGetOwnPropertyNames;
var ObjectInstanceHasOwnProperty = platform.builtInJavascriptObjectEntryHasOwnProperty;
// Because we don't keep track of the attributes object, and neither does the internals of Object.defineProperty;
// We don't need to restore it's prototype.
var _objectDefineProperty = platform.builtInJavascriptObjectEntryDefineProperty;
var ObjectDefineProperty = function (obj, prop, attributes) {
_objectDefineProperty(obj, prop, setPrototype(attributes, null));
};
var ArrayInstanceForEach = platform.builtInJavascriptArrayEntryForEach;
var ArrayInstanceIndexOf = platform.builtInJavascriptArrayEntryIndexOf;
var ArrayInstancePush = platform.builtInJavascriptArrayEntryPush;
var ArrayInstanceJoin = platform.builtInJavascriptArrayEntryJoin;
var FunctionInstanceBind = platform.builtInJavascriptFunctionEntryBind;
var DateInstanceGetDate = platform.builtInJavascriptDateEntryGetDate;
var DateNow = platform.builtInJavascriptDateEntryNow;
var StringInstanceReplace = platform.builtInJavascriptStringEntryReplace;
var StringInstanceToLowerCase = platform.builtInJavascriptStringEntryToLowerCase;
var StringInstanceToUpperCase = platform.builtInJavascriptStringEntryToUpperCase;
var ObjectPrototype = platform.Object_prototype;
var isFinite = platform.builtInGlobalObjectEntryIsFinite;
var isNaN = platform.builtInGlobalObjectEntryIsNaN;
const _ = {
toUpperCase(str) { return callInstanceFunc(StringInstanceToUpperCase, str); },
toLowerCase(str) { return callInstanceFunc(StringInstanceToLowerCase, str); },
replace(str, pattern, replacement) { return callInstanceFunc(StringInstanceReplace, str, pattern, replacement); },
split(str, pattern) { return callInstanceFunc(platform.builtInJavascriptStringEntrySplit, str, pattern); },
substring(str, start, end) { return callInstanceFunc(platform.builtInJavascriptStringEntrySubstring, str, start, end); },
stringIndexOf(str, el, from) { return callInstanceFunc(platform.builtInJavascriptStringEntryIndexOf, str, el, from); },
match(str, re) { return platform.builtInRegexMatch(str, re); },
repeat(str, count) { return callInstanceFunc(platform.builtInJavascriptStringEntryRepeat, str, count); },
forEach(array, func) { return callInstanceFunc(ArrayInstanceForEach, array, func); },
push(array, ...els) { return callInstanceFunc(ArrayInstancePush, array, ...els); },
join(array, sep) { return callInstanceFunc(ArrayInstanceJoin, array, sep); },
arrayIndexOf(array, el, from) { return callInstanceFunc(ArrayInstanceIndexOf, array, el, from); },
map(array, func) { return callInstanceFunc(platform.builtInJavascriptArrayEntryMap, array, func); },
reduce(array, func, init) { return callInstanceFunc(platform.builtInJavascriptArrayEntryReduce, array, func, init); },
slice(array, start, end) { return callInstanceFunc(platform.builtInJavascriptArrayEntrySlice, array, start, end); },
concat(array, ...els) { return callInstanceFunc(platform.builtInJavascriptArrayEntryConcat, array, ...els); },
filter(array, func) { return callInstanceFunc(platform.builtInJavascriptArrayEntryFilter, array, func); },
unique(array) { return _.filter(array, (v, i) => _.arrayIndexOf(array, v) === i); },
any(array, func) {
for (let i = 0; i < array.length; i++) {
if (func(array[i], i)) {
return true;
}
}
return false;
},
sort(array, sortCallback) { return callInstanceFunc(platform.builtInJavascriptArrayEntrySort, array, sortCallback); },
keys: platform.builtInJavascriptObjectEntryKeys,
hasOwnProperty(o, prop) { return callInstanceFunc(platform.builtInJavascriptObjectEntryHasOwnProperty, o, prop); },
// If we don't set the descriptor's prototype to null, defining properties with `value`s can fail of Object.prototype.get is defined
defineProperty(o, prop, desc) {
_.setPrototypeOf(desc, null);
platform.builtInJavascriptObjectEntryDefineProperty(o, prop, desc);
},
isExtensible: platform.builtInJavascriptObjectEntryIsExtensible,
create(proto = null) { return platform.builtInJavascriptObjectCreate(proto); },
setPrototypeOf(target, proto = null) { return platform.builtInSetPrototype(target, proto); },
abs: platform.builtInMathAbs,
// Make _.floor more like ECMA262 #sec-mathematical-operations' floor by normalizing -0
floor(x) { return x === 0 ? 0 : platform.builtInMathFloor(x) },
max: platform.builtInMathMax,
pow: platform.builtInMathPow,
isFinite: platform.builtInGlobalObjectEntryIsFinite,
isNaN: platform.builtInGlobalObjectEntryIsNaN,
getDate(date) { return callInstanceFunc(platform.builtInJavascriptDateEntryGetDate, date); },
bind(func, that) { return callInstanceFunc(platform.builtInJavascriptFunctionEntryBind, func, that); },
apply(func, that, args) { return callInstanceFunc(platform.builtInJavascriptFunctionEntryApply, func, that, args); },
};
const raise = {
rangeError() { return arguments.length === 3 ? platform.raiseOptionValueOutOfRange_3(...arguments) : platform.raiseOptionValueOutOfRange(); },
assert(test, err) { return test ? undefined : platform.raiseAssert(err || new Error("Assert failed")); }
};
// When this file was originally written, it assumed Windows Globalization semantics.
// Throughout the transition to ICU, we tried to share as much code as possible between WinGlob and ICU.
// However, because ICU has different semantics and our ICU-based implementation tries to match a newer
// version of the Intl spec, we have decided that the code sharing was causing more harm than good.
// Thus, while we support both ICU and WinGlob, we have decided to duplicate a substantial amount of code.
// The indentation of the below if block is intentionally incorrect so as to minimize diff.
if (isPlatformUsingICU) {
let __defaultLocale = undefined;
const GetDefaultLocale = function () {
if (__defaultLocale && platform.useCaches) {
return __defaultLocale;
}
const locale = platform.getDefaultLocale();
if (!locale) {
// if the system locale is undefined/null/empty string, we have to
// do something or else we will crash
__defaultLocale = "en";
} else {
__defaultLocale = locale;
}
return __defaultLocale;
};
// A helper function that is meant to rethrow SOE and OOM exceptions allowing them to propagate.
var throwExIfOOMOrSOE = function (ex) {
if (ex.number === -2146828260 || ex.number === -2146828281) {
throw ex;
}
};
var tagPublicFunction = function (name, f) {
return platform.tagPublicLibraryCode(f, name);
};
const createPublicMethod = function (name, f) {
return platform.tagPublicLibraryCode(f, name, false);
}
const OrdinaryCreateFromConstructor = function (constructor, intrinsicDefaultProto) {
let proto = constructor.prototype;
if (typeof proto !== "object") {
proto = intrinsicDefaultProto;
}
return _.create(proto);
};
/**
* Determines the best possible locale available in the system
*
* ECMA-402: #sec-bestavailablelocale
*
* @param {Function} isAvailableLocale A function that takes a locale and returns if the locale is supported
* @param {String} locale the locale (including its fallbacks) that will be searched for
* @returns {String} the given locale or one of its fallbacks, or undefined
*/
const BestAvailableLocale = function (isAvailableLocale, locale) {
if (locale === undefined) {
return undefined;
}
let candidate = locale;
const hyphen = "-";
while (true) {
if (isAvailableLocale(candidate)) {
return candidate;
}
let pos = -1;
for (let i = candidate.length - 1; i >= 0; i--) {
if (candidate[i] === hyphen) {
pos = i;
break;
}
}
if (pos === -1) {
return undefined;
} else if (pos >= 2 && candidate[pos - 2] === hyphen) {
// This is spec code likely intended to skip over singletons,
// such that if we just searched for "en-a-value",
// pos would initially truncate the candidate to "en-a", which
// is not a valid language tag.
// See https://tools.ietf.org/html/rfc5646#section-4.4.2
pos -= 2;
}
candidate = _.substring(candidate, 0, pos);
}
};
/**
* Determines which locale (or fallback) to use of an array of locales.
*
* ECMA-402: #sec-lookupmatcher
*
* @param {Function} isAvailableLocale A function that takes a locale and returns if the locale is supported
* @param {String[]} requestedLocales An array of requested locales
*/
const LookupMatcher = function (isAvailableLocale, requestedLocales) {
const result = _.create();
for (let i = 0; i < requestedLocales.length; ++i) {
const parsedLangtag = langtagToParts(requestedLocales[i]);
if (parsedLangtag === null) {
continue;
}
const availableLocale = BestAvailableLocale(isAvailableLocale, parsedLangtag.base);
if (availableLocale !== undefined) {
result.locale = availableLocale;
if (requestedLocales[i] !== parsedLangtag.base) {
result.extension = parsedLangtag.unicodeExtension;
}
return result;
}
}
result.locale = GetDefaultLocale();
return result;
};
const BestFitMatcher = LookupMatcher;
/**
* Determine a value for a given key in the given extension string
*
* ECMA-402: #sec-unicodeextensionvalue
*
* @param {String} extension the full unicode extension, such as "-u-co-phonebk-kf-true"
* @param {String} key the specific key we are looking for in the extension, such as "co"
*/
const UnicodeExtensionValue = function (extension, key) {
raise.assert(key.length === 2);
const size = extension.length;
// search for the key-value pair
let pos = _.stringIndexOf(extension, `-${key}-`);
if (pos !== -1) {
const start = pos + 4;
let end = start;
let k = start;
let done = false;
while (!done) {
const e = _.stringIndexOf(extension, "-", k);
const len = e === -1 ? size - k : e - k;
if (len === 2) {
done = true;
} else if (e === -1) {
end = size;
done = true;
} else {
end = e;
k = e + 1;
}
}
return _.substring(extension, start, end);
}
// search for the key with no associated value
pos = _.stringIndexOf(extension, `-${key}`);
if (pos !== -1 && pos + 3 === size) {
return "";
} else {
return undefined;
}
};
/**
* Resolves a locale by finding which base locale or fallback is available on the system,
* then determines which provided unicode options are available for that locale.
*
* ECMA-402: #sec-resolvelocale
*
* @param {Function} isAvailableLocale A function that takes a locale and returns if the locale is supported
* @param {String[]} requestedLocales The result of calling CanonicalizeLocaleList on the user-requested locale array
* @param {Object} options An object containing a lookupMatcher value and any value given by the user's option object,
* mapped to the correct unicode extension key
* @param {String[]} relevantExtensionKeys An array of unicode extension keys that we care about for the current lookup
*/
const ResolveLocale = function (isAvailableLocale, requestedLocales, options, relevantExtensionKeys) {
const matcher = options.lookupMatcher;
let r;
if (matcher === "lookup") {
r = LookupMatcher(isAvailableLocale, requestedLocales);
} else {
r = BestFitMatcher(isAvailableLocale, requestedLocales);
}
let foundLocale = r.locale;
const result = bare({ dataLocale: foundLocale });
let supportedExtension = "-u";
_.forEach(relevantExtensionKeys, function (key) {
const keyLocaleData = platform.getLocaleData(platform.LocaleDataKind[key], foundLocale);
let value = keyLocaleData[0];
let supportedExtensionAddition = "";
if (r.extension) {
const requestedValue = UnicodeExtensionValue(r.extension, key);
if (requestedValue !== undefined) {
if (requestedValue !== "") {
if (_.arrayIndexOf(keyLocaleData, requestedValue) !== -1) {
value = requestedValue;
supportedExtensionAddition = `-${key}-${value}`;
}
} else if (_.arrayIndexOf(keyLocaleData, "true") !== -1) {
value = "true";
}
}
}
if (_.hasOwnProperty(options, key)) {
const optionsValue = options[key];
if (_.arrayIndexOf(keyLocaleData, optionsValue) !== -1) {
if (optionsValue !== value) {
value = optionsValue;
supportedExtensionAddition = "";
}
}
}
result[key] = value;
supportedExtension += supportedExtensionAddition;
});
if (supportedExtension.length > 2) {
const privateIndex = _.stringIndexOf(foundLocale, "-x-");
if (privateIndex === -1) {
foundLocale += supportedExtension;
} else {
const preExtension = _.substring(foundLocale, 0, privateIndex);
const postExtension = _.substring(foundLocale, privateIndex);
foundLocale = preExtension + supportedExtension + postExtension;
}
foundLocale = platform.normalizeLanguageTag(foundLocale);
}
result.locale = foundLocale;
return result;
};
var Internal = bare({
ToObject(o) {
if (o === null) {
platform.raiseNeedObject();
}
return o !== undefined ? Object(o) : undefined;
},
ToString(s) {
return s !== undefined ? String(s) : undefined;
},
ToNumber(n) {
return n !== undefined ? Number(n) : NaN;
},
ToLogicalBoolean(v) {
return v !== undefined ? Boolean(v) : undefined;
},
ToInteger(n) {
const number = Number(n);
if (isNaN(number)) {
return 0;
} else if (number === 0 || !isFinite(number)) {
return number;
}
const ret = _.floor(_.abs(number));
if (number < 0) {
return -ret
} else {
return ret;
}
},
ToLength(n) {
const len = Internal.ToInteger(n);
if (len <= 0) {
return 0;
}
const max = _.pow(2, 53) - 1;
return max < len ? max : len;
}
});
// Internal ops implemented in JS:
function GetOption(options, property, type, values, fallback) {
let value = options[property];
if (value !== undefined) {
if (type == "boolean") {
value = Internal.ToLogicalBoolean(value);
}
if (type == "string") {
value = Internal.ToString(value);
}
if (type == "number") {
value = Internal.ToNumber(value);
}
if (values !== undefined && _.arrayIndexOf(values, value) == -1) {
platform.raiseOptionValueOutOfRange_3(String(value), String(property), `['${_.join(values, "', '")}']`);
}
return value;
}
return fallback;
}
/**
* Extracts the value of the property named property from the provided options object,
* converts it to a Number value, checks whether it is in the allowed range,
* and fills in a fallback value if necessary.
*
* NOTE: this has known differences compared to the spec GetNumberOption in order to
* support more verbose errors. It is more similar to DefaultNumberOption
*
* ECMA402: #sec-defaultnumberoption
*
* @param {Object} options user-provided options object
* @param {String} property the property we are trying to get off of `options`
* @param {Number} minimum minimum allowable value for options[property]
* @param {Number} maximum maximum allowable value for options[property]
* @param {Number} fallback return value if options[property] is undefined or invalid
* @returns {Number}
*/
const GetNumberOption = function (options, property, minimum, maximum, fallback) {
let value = options[property];
if (value !== undefined) {
value = Internal.ToNumber(value);
if (_.isNaN(value) || value < minimum || value > maximum) {
platform.raiseOptionValueOutOfRange_3(String(value), property, `[${minimum} - ${maximum}]`);
}
return _.floor(value);
}
return fallback;
};
let CURRENCY_CODE_RE;
function InitializeCurrencyRegExp() {
CURRENCY_CODE_RE = /^[A-Z]{3}$/i;
}
// Language Tag Syntax as described in RFC 5646 #section-2.1
// Note: All language tags are comprised only of ASCII characters (makes our job easy here)
// Note: Language tags in canonical form have case conventions, but language tags are case-insensitive for our purposes
// Note: The ABNF syntax used in RFC 5646 #section-2.1 uses the following numeric quantifier conventions:
// - (Parentheses) are used for grouping
// - PRODUCTION => exactly 1 of PRODUCTION /PRODUCTION/
// - [PRODUCTION] => 0 or 1 of PRODUCTION /(PRODUCTION)?/
// - #PRODUCTION => exactly # of PRODUCTION /(PRODUCTION){#}/
// - a*bPRODUCTION (where a and b are optional)
// - *PRODUCTION => any number of PRODUCTION /(PRODUCTION)*/
// - 1*PRODUCTION => 1 or more of PRODUCTION /(PRODUCTION)+/
// - #*PRODUCTION => # or more of PRODUCTION /(PRODUCTION){#,}/
// - *#PRODUCTION => 0 to # (inclusive) of PRODUCTION /(PRODUCTION){,#}/ or /(PRODUCTION){0,#}/
// - a*bPRODUCTION => a to b (inclusive) of PRODUCTION /(PRODUCTION){a,b}/
const ALPHA = "[A-Z]";
const DIGIT = "[0-9]";
const alphanum = `(?:${ALPHA}|${DIGIT})`;
const regularREString = "\\b(?:art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|zh-min|zh-min-nan|zh-xiang)\\b";
const irregularREString = "\\b(?:en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|i-klingon|i-lux|i-mingo" +
"|i-navajo|i-pwn|i-tao|i-tay|i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE)\\b";
const grandfatheredREString = `\\b(?:${regularREString}|${irregularREString})\\b`;
const privateuseREString = `\\b(?:x(?:-${alphanum}{1,8}\\b)+)\\b`; // privateuse = "x" 1*("-" (1*8alphanum))
const singletonREString = `\\b(?:${DIGIT}|[A-WY-Z])\\b`; // singleton ~= alphanum except for 'x' ; (paraphrased)
const extensionREString = `\\b(?:${singletonREString}(?:-${alphanum}{2,8})+)\\b`; // extension = singleton 1*("-" (2*8alphanum))
const variantREString = `\\b(?:${alphanum}{5,8}|${DIGIT}${alphanum}{3})\\b`; // variant = 5*8alphanum / (DIGIT 3alphanum)
const regionREString = `\\b(?:${ALPHA}{2}|${DIGIT}{3})\\b`; // region = 2ALPHA / 3DIGIT
const scriptREString = `\\b(?:${ALPHA}{4})\\b`; // script = 4ALPHA
const extlangREString = `\\b(?:${ALPHA}{3}\\b(?:-${ALPHA}{3}){0,2})\\b`; // extlang = 3ALPHA *2("-" 3ALPHA)
const languageREString = '\\b(?:' + // language =
`${ALPHA}{2,3}` + // 2*3ALPHA ; shortest ISO 639 code
`\\b(?:-${extlangREString})?` + // ["-" extlang] ; sometimes followed by extended language subtags
// `|${ALPHA}{4}` + // / 4ALPHA ; or reserved for future use
// `|${ALPHA}{5,8}` + // / 5*8ALPHA ; or registered language subtag
`|${ALPHA}{4,8}` + // ~/ 4*8ALPHA ; (paraphrased: combined previous two lines)
')\\b';
// Use matching groups only at the langtag level. This makes it clear what $1, $2, etc are when calling _.match
// NOTE: the leading "-" is matched for variant and extension, but not for any of the other groups.
const langtagREString = `\\b(${languageREString})\\b` + // langtag = language
`\\b(?:-(${scriptREString}))?\\b` + // ["-" script]
`\\b(?:-(${regionREString}))?\\b` + // ["-" region]
`\\b((?:-${variantREString})*)\\b` + // *("-" variant)
`\\b((?:-${extensionREString})*)\\b` + // *("-" extension)
`\\b(?:-(${privateuseREString}))?\\b` ; // ["-" privateuse]
// Use ^ and $ to enforce that the entire input string is a langtag
const langtagRE = new platform.RegExp(`^${langtagREString}$`, "i");
const grandfatheredRE = new platform.RegExp(`^${grandfatheredREString}$`, "i");
const privateuseRE = new platform.RegExp(`^${privateuseREString}$`, "i");
const grandfatheredOrPrivateuseRE = new platform.RegExp(`^(?:${grandfatheredREString}|${privateuseREString})$`, "i");
const languageOptionRE = new platform.RegExp(`^${languageREString}$`, "i");
const scriptOptionRE = new platform.RegExp(`^${scriptREString}$`, "i");
const regionOptionRE = new platform.RegExp(`^${regionREString}$`, "i");
const langtagToPartsCache = new IntlCache();
/**
* Returns an object `{ language, script, region, variants, extensions, unicodeExtension, privateuse }`
* of valid, regular language tags. If the language tag is grandfathered or privateuse, the returned
* object will instead have a `grandfatheredTag` or `privateuseTag` property containing the entire matched
* tag and a `isGrandfatheredOrPrivateuseTag` property set to true.
*
* NOTE: Do NOT modify the returned object unless you also restore the original state. The object is cached
* and modifications to the object do not invalidate the cache.
*
* @param {String} langtag a candidate BCP47 langtag
*/
const langtagToParts = function (langtag) {
const cached = langtagToPartsCache.get(langtag);
if (cached) {
return cached;
}
const ret = _.create();
let parts = _.match(langtag, langtagRE);
if (!parts) {
parts = _.match(langtag, grandfatheredRE);
if (!parts) {
parts = _.match(langtag, privateuseRE);
if (!parts) {
return null;
} else {
ret.privateuseTag = langtag;
}
} else {
ret.grandfatheredTag = langtag;
}
}
langtagToPartsCache.set(langtag, ret);
if (ret.privateuseTag || ret.grandfatheredTag) {
ret.isGrandfatheredOrPrivateuseTag = true;
return ret;
}
ret.language = parts[1];
ret.base = parts[1];
if (parts[2]) {
ret.script = parts[2];
ret.base += "-" + parts[2];
}
if (parts[3]) {
ret.region = parts[3];
ret.base += "-" + parts[3];
}
if (parts[4]) {
ret.variants = parts[4];
// leading "-" is already in parts[4]
ret.base += parts[4];
}
if (parts[5]) {
ret.extensions = parts[5];
// parse the extension to find the unicode (-u) extension
const extensionParts = _.split(parts[5], "-");
for (let unicodeExtensionStart = 0; unicodeExtensionStart < extensionParts.length; ++unicodeExtensionStart) {
if (extensionParts[unicodeExtensionStart] !== "u") {
continue;
}
let unicodeExtensionsEnd;
for (unicodeExtensionsEnd = unicodeExtensionStart + 1; unicodeExtensionsEnd < extensionParts.length && extensionParts[unicodeExtensionsEnd].length > 1; unicodeExtensionsEnd++) {
// do nothing, we just want k to equal the index of the next element whose length is 1
// or to equal the length of extensionParts
// We could have done this with Array.prototype.findIndex too
}
if (unicodeExtensionsEnd > unicodeExtensionStart + 1) {
// this creates u-(keys and values)*, which is good enough for the UnicodeExtensionValue. UnicodeExtensionComponents, on the other hand,
// requires -u-keys-and-values with the leading -. UnicodeExtensionComponents knows to add "-" to the start if its missing.
ret.unicodeExtension = _.join(_.slice(extensionParts, unicodeExtensionStart, unicodeExtensionsEnd), "-");
}
// if we have gotten this far, we have found -u-{values}, so we can break
break;
}
}
if (parts[6]) {
ret.privateuse = parts[6];
}
return ret;
};
// no cache because IntlCache requires keys to be === rather than structurally equal
const partsToLangtag = function (parts) {
if (parts.isGrandfatheredOrPrivateuseTag) {
return parts.privateuseTag || parts.grandfatheredTag;
}
let langtag = parts.language;
if (parts.script) {
langtag += `-${parts.script}`;
}
if (parts.region) {
langtag += `-${parts.region}`;
}
if (parts.variants) {
langtag += parts.variants;
}
if (parts.extensions) {
langtag += parts.extensions;
}
if (parts.privateuse) {
langtag += `-${parts.privateuse}`;
}
return langtag;
};
const IsWellFormedCurrencyCode = function (code) {
code = Internal.ToString(code);
if (!CURRENCY_CODE_RE) {
InitializeCurrencyRegExp();
}
return platform.builtInRegexMatch(code, CURRENCY_CODE_RE) !== null;
}
/**
* Returns true if locale can be generated by RFC5646 section 2.1 and does not contain
* duplicate variant or singleton subtags.
*
* Note that ICU does not implement this correctly for our usage because it is
* extremely permissive about what it will allow -- completely invalid language tags can
* pass through a round of uloc_forLanguageTag/uloc_toLanguageTag or uloc_canonicalize unharmed
*
* ECMA402: #sec-isstructurallyvalidlanguagetag
*
* @param {String} locale The locale to check
* @returns {Boolean}
*/
const IsStructurallyValidLanguageTag = function (locale) {
const parsed = langtagToParts(locale);
if (parsed === null) {
return false;
}
// check duplicate variants
if (parsed.variants) {
const variants = _.split(parsed.variants, "-");
const uniqueVariants = _.unique(variants);
if (variants.length !== uniqueVariants.length) {
return false;
}
}
if (parsed.extensions) {
const extensionParts = _.split(parsed.extensions, "-");
const singletons = _.map(_.filter(extensionParts, (element) => element.length === 1), (element) => _.toLowerCase(element));
const uniqueSingletons = _.unique(singletons);
return singletons.length === uniqueSingletons.length;
}
return true;
};
/**
* Given a locale or list of locales, returns a corresponding list where each locale
* is guaranteed to be "canonical" (proper capitalization, order, etc.).
*
* ECMA402: #sec-canonicalizelocalelist
*
* @param {String|String[]} locales the user-provided locales to be canonicalized
*/
const CanonicalizeLocaleList = function (locales) {
if (typeof locales === "undefined") {
return [];
}
const seen = [];
const O = typeof locales === "string" ? [locales] : Internal.ToObject(locales);
const len = Internal.ToLength(O.length);
let k = 0;
while (k < len) {
const Pk = Internal.ToString(k);
if (Pk in O) {
const kValue = O[Pk];
if ((typeof kValue !== "string" && typeof kValue !== "object") || kValue === null) {
platform.raiseNeedObjectOrString("locale");
}
let tag;
if (typeof kValue === "object") {
const possibleLocaleInternals = platform.getHiddenObject(kValue);
if (possibleLocaleInternals && possibleLocaleInternals.initializedLocale) {
tag = possibleLocaleInternals.locale;
}
}
if (tag === undefined) {
tag = Internal.ToString(kValue);
}
if (!IsStructurallyValidLanguageTag(tag)) {
platform.raiseLocaleNotWellFormed(tag);
}
const canonicalizedTag = platform.normalizeLanguageTag(tag);
if (_.arrayIndexOf(seen, canonicalizedTag) === -1) {
_.push(seen, canonicalizedTag);
}
}
k += 1;
}
return seen;
};
/**
* Returns the subset of requestedLocales that has a matching locale according to BestAvailableLocale.
*
* ECMA402: #sec-lookupsupportedlocales
*
* @param {Function} isAvailableLocale A function that takes a locale and returns if the locale is supported
* @param {String|String[]} requestedLocales
*/
const LookupSupportedLocales = function (isAvailableLocale, requestedLocales) {
const subset = [];
_.forEach(requestedLocales, function (locale) {
const noExtensionsLocale = langtagToParts(locale).base;
if (BestAvailableLocale(isAvailableLocale, noExtensionsLocale) !== undefined) {
_.push(subset, locale);
}
});
return subset;
};
const BestFitSupportedLocales = LookupSupportedLocales;
/**
* Applies digit options used for number formatting onto the given intlObj
*
* This function is used by both NumberFormat and PluralRules, despite being defined
* as a NumberFormat abstract operation
*
* ECMA 402: #sec-setnfdigitoptions
*
* @param {Object} intlObj The state object of either a NumberFormat or PluralRules on which to set the resolved number options
* @param {Object} options The option object to pull min/max sigfigs, fraction digits, and integer digits
* @param {Number} mnfdDefault The default minimumFractionDigits
* @param {Number} mxfdDefault The default maximumFractionDigits
*/
const SetNumberFormatDigitOptions = function (intlObj, options, mnfdDefault, mxfdDefault) {
const mnid = GetNumberOption(options, "minimumIntegerDigits", 1, 21, 1);
const mnfd = GetNumberOption(options, "minimumFractionDigits", 0, 20, mnfdDefault);
const mxfdActualDefault = _.max(mnfd, mxfdDefault);
const mxfd = GetNumberOption(options, "maximumFractionDigits", mnfd, 20, mxfdActualDefault);
intlObj.minimumIntegerDigits = mnid;
intlObj.minimumFractionDigits = mnfd;
intlObj.maximumFractionDigits = mxfd;
let mnsd = options.minimumSignificantDigits;
let mxsd = options.maximumSignificantDigits;
if (mnsd !== undefined || mxsd !== undefined) {
// don't read options.minimumSignificantDigits below in order to pass
// test262/test/intl402/NumberFormat/significant-digits-options-get-sequence.js
mnsd = GetNumberOption({ minimumSignificantDigits: mnsd }, "minimumSignificantDigits", 1, 21, 1);
mxsd = GetNumberOption({ maximumSignificantDigits: mxsd }, "maximumSignificantDigits", mnsd, 21, 21);
intlObj.minimumSignificantDigits = mnsd;
intlObj.maximumSignificantDigits = mxsd;
}
};
/**
* Returns the subset of requestedLocales that has a matching locale, according to
* options.localeMatcher and isAvailableLocale.
*
* ECMA402: #sec-supportedlocales
*
* @param {Function} isAvailableLocale A function that takes a locale and returns if the locale is supported
* @param {String|String[]} requestedLocales
* @param {Object} options
*/
const SupportedLocales = function (isAvailableLocale, requestedLocales, options) {
const matcher = options === undefined
? "best fit"
: GetOption(Internal.ToObject(options), "localeMatcher", "string", ["best fit", "lookup"], "best fit");
const supportedLocales = matcher === "best fit"
? BestFitSupportedLocales(isAvailableLocale, requestedLocales)
: LookupSupportedLocales(isAvailableLocale, requestedLocales);
for (let i = 0; i < supportedLocales.length; i++) {
_.defineProperty(supportedLocales, Internal.ToString(i), { configurable: false, writable: false });
}
// test262 supportedLocalesOf-returned-array-elements-are-frozen.js:
// Property length of object returned by SupportedLocales should not be writable
_.defineProperty(supportedLocales, "length", {
writable: false,
configurable: false,
enumerable: false,
});
return supportedLocales;
};
if (InitType === "Intl") {
const getCanonicalLocales = createPublicMethod("Intl.getCanonicalLocales", function getCanonicalLocales(locales) {
return CanonicalizeLocaleList(locales);
});
_.defineProperty(Intl, "getCanonicalLocales", {
value: getCanonicalLocales,
writable: true,
enumerable: false,
configurable: true
});
}
/**
* Creates an object to be returned out of resolvedOptions() methods that avoids being tainted by Object.prototype
*
* @param {String[]} props The list of properties to extract from hiddenObject and add to the final resolved options
* @param {Object} hiddenObject The hiddenObject of the calling constructor that contains values for each prop in props
* @param {Function} func An optional custom function(prop, resolved) run for each prop; it should return true when
* it handles a property itself. If it does not return true, the default logic will be used.
*/
const createResolvedOptions = function (props, hiddenObject, func = null) {
const resolved = _.create();
_.forEach(props, function (prop) {
if (func !== null && func(prop, resolved) === true) {
// the callback returned true, which means this property was handled and we can go to the next one
return;
}
if (typeof hiddenObject[prop] !== "undefined") {
resolved[prop] = hiddenObject[prop];
}
});
return _.setPrototypeOf(resolved, platform.Object_prototype);
};
// Intl.Collator, String.prototype.localeCompare
const Collator = (function () {
if (InitType !== "Intl" && InitType !== "String") {
return;
}
const InitializeCollator = function (collator, locales, options) {
const requestedLocales = CanonicalizeLocaleList(locales);
options = options === undefined ? _.create() : Internal.ToObject(options);
// The spec says that usage dictates whether to use "[[SearchLocaleData]]" or "[[SortLocaleData]]"
// ICU has no concept of a difference between the two, and instead sort/search corresponds to
// collation = "standard" or collation = "search", respectively. Standard/sort is the default.
// Thus, when the usage is sort, we can accept and honor -u-co in the locale, while if usage is search,
// we are going to overwrite any -u-co value provided before giving the locale to ICU anyways.
// To make the logic simpler, we can simply pretend like we don't accept a -u-co value if the usage is search.
// See the lazy UCollator initialization in EntryIntl_LocaleCompare for where the collation value
// gets overwritten by "search".
collator.usage = GetOption(options, "usage", "string", ["sort", "search"], "sort");
const relevantExtensionKeys = collator.usage === "sort" ? ["co", "kn", "kf"] : ["kn", "kf"];
const opt = _.create();
opt.matcher = GetOption(options, "localeMatcher", "string", ["lookup", "best fit"], "best fit");
let kn = GetOption(options, "numeric", "boolean", undefined, undefined);
opt.kn = kn === undefined ? kn : Internal.ToString(kn);
opt.kf = GetOption(options, "caseFirst", "string", ["upper", "lower", "false"], undefined);
const r = ResolveLocale(platform.isCollatorLocaleAvailable, requestedLocales, opt, relevantExtensionKeys);
collator.locale = r.locale;
// r.co is null when usage === "sort" and no -u-co is provided
// r.co is undefined when usage === "search", since relevantExtensionKeys doesn't even look for -co
collator.collation = r.co === null || r.co === undefined ? "default" : r.co;
collator.numeric = r.kn === "true";
collator.caseFirst = r.kf;
collator.caseFirstEnum = platform.CollatorCaseFirst[collator.caseFirst];
collator.sensitivity = GetOption(options, "sensitivity", "string", ["base", "accent", "case", "variant"], "variant");
collator.sensitivityEnum = platform.CollatorSensitivity[collator.sensitivity];
collator.ignorePunctuation = GetOption(options, "ignorePunctuation", "boolean", undefined, false);
collator.initializedCollator = true;
return collator;
};
let localeCompareStateCache;
// Make arguments undefined to ensure that localeCompare.length === 1
platform.registerBuiltInFunction(createPublicMethod("String.prototype.localeCompare", function localeCompare(that, locales = undefined, options = undefined) {
if (this === undefined || this === null) {
platform.raiseThis_NullOrUndefined("String.prototype.localeCompare");
}
const thisStr = String(this);
const thatStr = String(that);
// Performance optimization to cache the state object and UCollator when the default arguments are provided
// TODO(jahorto): investigate caching when locales and/or options are provided
let stateObject;
if (locales === undefined && options === undefined) {
if (localeCompareStateCache === undefined) {
localeCompareStateCache = _.create();
InitializeCollator(localeCompareStateCache, undefined, undefined);
}