-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathecmascript.mjs
4314 lines (3889 loc) · 157 KB
/
ecmascript.mjs
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
/* global __debug__ */
import {
// constructors and similar
BigInt as BigIntCtor,
Date as DateCtor,
Map as MapCtor,
Number as NumberCtor,
RegExp as RegExpCtor,
Set as SetCtor,
String as StringCtor,
Symbol as SymbolCtor,
// error constructors
Error as ErrorCtor,
RangeError as RangeErrorCtor,
SyntaxError as SyntaxErrorCtor,
TypeError as TypeErrorCtor,
// class static functions and methods
ArrayPrototypeConcat,
ArrayPrototypeEvery,
ArrayPrototypeFilter,
ArrayPrototypeFlatMap,
ArrayPrototypeIncludes,
ArrayPrototypeIndexOf,
ArrayPrototypeJoin,
ArrayPrototypeMap,
ArrayPrototypePush,
ArrayPrototypeReduce,
ArrayPrototypeSort,
DateNow,
DatePrototypeGetTime,
DatePrototypeGetUTCFullYear,
DatePrototypeGetUTCMonth,
DatePrototypeGetUTCDate,
DatePrototypeGetUTCHours,
DatePrototypeGetUTCMinutes,
DatePrototypeGetUTCSeconds,
DatePrototypeGetUTCMilliseconds,
DatePrototypeSetUTCFullYear,
DatePrototypeSetUTCHours,
DateUTC,
IntlDateTimeFormat,
IntlDateTimeFormatPrototypeGetFormat,
IntlDateTimeFormatPrototypeResolvedOptions,
IntlSupportedValuesOf,
MapPrototypeGet,
MapPrototypeHas,
MapPrototypeSet,
MathAbs,
MathFloor,
MathMax,
MathMin,
MathSign,
MathTrunc,
NumberIsFinite,
NumberIsNaN,
NumberIsSafeInteger,
NumberMaxSafeInteger,
NumberPrototypeToString,
ObjectAssign,
ObjectCreate,
ObjectDefineProperty,
RegExpPrototypeExec,
RegExpPrototypeTest,
SetPrototypeHas,
StringFromCharCode,
StringPrototypeCharCodeAt,
StringPrototypeIndexOf,
StringPrototypeMatch,
StringPrototypePadStart,
StringPrototypeReplace,
StringPrototypeSlice,
StringPrototypeSplit,
StringPrototypeStartsWith,
StringPrototypeToUpperCase
} from './primordials.mjs';
import Call from 'es-abstract/2024/Call.js';
import CopyDataProperties from 'es-abstract/2024/CopyDataProperties.js';
import GetMethod from 'es-abstract/2024/GetMethod.js';
import HasOwnProperty from 'es-abstract/2024/HasOwnProperty.js';
import IsIntegralNumber from 'es-abstract/2024/IsIntegralNumber.js';
import ToNumber from 'es-abstract/2024/ToNumber.js';
import ToObject from 'es-abstract/2024/ToObject.js';
import ToPrimitive from 'es-abstract/2024/ToPrimitive.js';
import ToString from 'es-abstract/2024/ToString.js';
import Type from 'es-abstract/2024/Type.js';
import { assert, assertNotReached } from './assert.mjs';
import { GetIntrinsic } from './intrinsicclass.mjs';
import {
ApplyUnsignedRoundingMode,
FMAPowerOf10,
GetUnsignedRoundingMode,
TruncatingDivModByPowerOf10
} from './math.mjs';
import { TimeDuration } from './timeduration.mjs';
import {
CreateSlots,
GetSlot,
HasSlot,
SetSlot,
EPOCHNANOSECONDS,
ISO_DATE,
ISO_DATE_TIME,
TIME,
DATE_BRAND,
YEAR_MONTH_BRAND,
MONTH_DAY_BRAND,
TIME_ZONE,
CALENDAR,
YEARS,
MONTHS,
WEEKS,
DAYS,
HOURS,
MINUTES,
SECONDS,
MILLISECONDS,
MICROSECONDS,
NANOSECONDS
} from './slots.mjs';
import bigInt from 'big-integer';
const DAY_MS = 86400_000;
const DAY_NANOS = DAY_MS * 1e6;
// Instant range is 100 million days (inclusive) before or after epoch.
const MS_MAX = DAY_MS * 1e8;
const NS_MIN = bigInt(DAY_NANOS).multiply(-1e8);
const NS_MAX = bigInt(DAY_NANOS).multiply(1e8);
// PlainDateTime range is 24 hours wider (exclusive) than the Instant range on
// both ends, to allow for valid Instant=>PlainDateTime conversion for all
// built-in time zones (whose offsets must have a magnitude less than 24 hours).
const DATETIME_NS_MIN = NS_MIN.subtract(DAY_NANOS).add(bigInt.one);
const DATETIME_NS_MAX = NS_MAX.add(DAY_NANOS).subtract(bigInt.one);
// The pattern of leap years in the ISO 8601 calendar repeats every 400 years.
// The constant below is the number of nanoseconds in 400 years. It is used to
// avoid overflows when dealing with values at the edge legacy Date's range.
const MS_IN_400_YEAR_CYCLE = (400 * 365 + 97) * DAY_MS;
const YEAR_MIN = -271821;
const YEAR_MAX = 275760;
const BEFORE_FIRST_DST = DateUTC(1847, 0, 1); // 1847-01-01T00:00:00Z
const BUILTIN_CALENDAR_IDS = [
'iso8601',
'hebrew',
'islamic',
'islamic-umalqura',
'islamic-tbla',
'islamic-civil',
'islamic-rgsa',
'islamicc',
'persian',
'ethiopic',
'ethioaa',
'ethiopic-amete-alem',
'coptic',
'chinese',
'dangi',
'roc',
'indian',
'buddhist',
'japanese',
'gregory'
];
const ICU_LEGACY_TIME_ZONE_IDS = new SetCtor([
'ACT',
'AET',
'AGT',
'ART',
'AST',
'BET',
'BST',
'CAT',
'CNT',
'CST',
'CTT',
'EAT',
'ECT',
'IET',
'IST',
'JST',
'MIT',
'NET',
'NST',
'PLT',
'PNT',
'PRT',
'PST',
'SST',
'VST'
]);
export function ToIntegerWithTruncation(value) {
const number = ToNumber(value);
if (number === 0) return 0;
if (NumberIsNaN(number) || !NumberIsFinite(number)) {
throw new RangeErrorCtor('invalid number value');
}
const integer = MathTrunc(number);
if (integer === 0) return 0; // ℝ(value) in spec text; converts -0 to 0
return integer;
}
export function ToPositiveIntegerWithTruncation(value, property) {
const integer = ToIntegerWithTruncation(value);
if (integer <= 0) {
if (property !== undefined) {
throw new RangeErrorCtor(`property '${property}' cannot be a a number less than one`);
}
throw new RangeErrorCtor('Cannot convert a number less than one to a positive integer');
}
return integer;
}
export function ToIntegerIfIntegral(value) {
const number = ToNumber(value);
if (!NumberIsFinite(number)) throw new RangeErrorCtor('infinity is out of range');
if (!IsIntegralNumber(number)) throw new RangeErrorCtor(`unsupported fractional value ${value}`);
if (number === 0) return 0; // ℝ(value) in spec text; converts -0 to 0
return number;
}
// This convenience function isn't in the spec, but is useful in the polyfill
// for DRY and better error messages.
export function RequireString(value) {
if (Type(value) !== 'String') {
// Use String() to ensure that Symbols won't throw
throw new TypeErrorCtor(`expected a string, not ${StringCtor(value)}`);
}
return value;
}
function ToSyntacticallyValidMonthCode(value) {
value = ToPrimitive(value, StringCtor);
RequireString(value);
if (
value.length < 3 ||
value.length > 4 ||
value[0] !== 'M' ||
Call(StringPrototypeIndexOf, '0123456789', [value[1]]) === -1 ||
Call(StringPrototypeIndexOf, '0123456789', [value[2]]) === -1 ||
(value[1] + value[2] === '00' && value[3] !== 'L') ||
(value[3] !== 'L' && value[3] !== undefined)
) {
throw new RangeError(`bad month code ${value}; must match M01-M99 or M00L-M99L`);
}
return value;
}
function ToOffsetString(value) {
value = ToPrimitive(value, StringCtor);
RequireString(value);
ParseDateTimeUTCOffset(value);
return value;
}
const CALENDAR_FIELD_KEYS = [
'era',
'eraYear',
'year',
'month',
'monthCode',
'day',
'hour',
'minute',
'second',
'millisecond',
'microsecond',
'nanosecond',
'offset',
'timeZone'
];
const BUILTIN_CASTS = new MapCtor([
['era', ToString],
['eraYear', ToIntegerWithTruncation],
['year', ToIntegerWithTruncation],
['month', ToPositiveIntegerWithTruncation],
['monthCode', ToSyntacticallyValidMonthCode],
['day', ToPositiveIntegerWithTruncation],
['hour', ToIntegerWithTruncation],
['minute', ToIntegerWithTruncation],
['second', ToIntegerWithTruncation],
['millisecond', ToIntegerWithTruncation],
['microsecond', ToIntegerWithTruncation],
['nanosecond', ToIntegerWithTruncation],
['offset', ToOffsetString],
['timeZone', ToTemporalTimeZoneIdentifier]
]);
const BUILTIN_DEFAULTS = new MapCtor([
['hour', 0],
['minute', 0],
['second', 0],
['millisecond', 0],
['microsecond', 0],
['nanosecond', 0]
]);
// each item is [plural, singular, category, (length in ns)]
const TEMPORAL_UNITS = [
['years', 'year', 'date'],
['months', 'month', 'date'],
['weeks', 'week', 'date'],
['days', 'day', 'date', DAY_NANOS],
['hours', 'hour', 'time', 3600e9],
['minutes', 'minute', 'time', 60e9],
['seconds', 'second', 'time', 1e9],
['milliseconds', 'millisecond', 'time', 1e6],
['microseconds', 'microsecond', 'time', 1e3],
['nanoseconds', 'nanosecond', 'time', 1]
];
const SINGULAR_FOR = new MapCtor(TEMPORAL_UNITS);
// Iterable destructuring is acceptable in this first-run code.
const PLURAL_FOR = new MapCtor(Call(ArrayPrototypeMap, TEMPORAL_UNITS, [([p, s]) => [s, p]]));
const UNITS_DESCENDING = Call(ArrayPrototypeMap, TEMPORAL_UNITS, [([, s]) => s]);
const NS_PER_TIME_UNIT = new MapCtor(
Call(ArrayPrototypeFlatMap, TEMPORAL_UNITS, [([, s, , l]) => (l ? [[s, l]] : [])])
);
const DURATION_FIELDS = [
'days',
'hours',
'microseconds',
'milliseconds',
'minutes',
'months',
'nanoseconds',
'seconds',
'weeks',
'years'
];
import * as PARSE from './regex.mjs';
export { Call, CopyDataProperties, GetMethod, HasOwnProperty, ToNumber, ToObject, ToString, Type };
const IntlDateTimeFormatEnUsCache = new MapCtor();
function getIntlDateTimeFormatEnUsForTimeZone(timeZoneIdentifier) {
const lowercaseIdentifier = ASCIILowercase(timeZoneIdentifier);
let instance = Call(MapPrototypeGet, IntlDateTimeFormatEnUsCache, [lowercaseIdentifier]);
if (instance === undefined) {
instance = new IntlDateTimeFormat('en-us', {
timeZone: lowercaseIdentifier,
hour12: false,
era: 'short',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
Call(MapPrototypeSet, IntlDateTimeFormatEnUsCache, [lowercaseIdentifier, instance]);
}
return instance;
}
export function IsTemporalInstant(item) {
return HasSlot(item, EPOCHNANOSECONDS) && !HasSlot(item, TIME_ZONE, CALENDAR);
}
export function IsTemporalDuration(item) {
return HasSlot(item, YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS);
}
export function IsTemporalDate(item) {
return HasSlot(item, DATE_BRAND);
}
export function IsTemporalTime(item) {
return HasSlot(item, TIME);
}
export function IsTemporalDateTime(item) {
return HasSlot(item, ISO_DATE_TIME);
}
export function IsTemporalYearMonth(item) {
return HasSlot(item, YEAR_MONTH_BRAND);
}
export function IsTemporalMonthDay(item) {
return HasSlot(item, MONTH_DAY_BRAND);
}
export function IsTemporalZonedDateTime(item) {
return HasSlot(item, EPOCHNANOSECONDS, TIME_ZONE, CALENDAR);
}
export function RejectTemporalLikeObject(item) {
if (HasSlot(item, CALENDAR) || HasSlot(item, TIME_ZONE)) {
throw new TypeErrorCtor('with() does not support a calendar or timeZone property');
}
if (IsTemporalTime(item)) {
throw new TypeErrorCtor('with() does not accept Temporal.PlainTime, use withPlainTime() instead');
}
if (item.calendar !== undefined) {
throw new TypeErrorCtor('with() does not support a calendar property');
}
if (item.timeZone !== undefined) {
throw new TypeErrorCtor('with() does not support a timeZone property');
}
}
export function FormatCalendarAnnotation(id, showCalendar) {
if (showCalendar === 'never') return '';
if (showCalendar === 'auto' && id === 'iso8601') return '';
const flag = showCalendar === 'critical' ? '!' : '';
return `[${flag}u-ca=${id}]`;
}
// Not a separate abstract operation in the spec, because it only occurs in one
// place: ParseISODateTime. In the code it's more convenient to split up
// ParseISODateTime for the YYYY-MM, MM-DD, and THH:MM:SS parse goals, so it's
// repeated four times.
function processAnnotations(annotations) {
let calendar;
let calendarWasCritical = false;
// Avoid the user code minefield of matchAll.
let match;
PARSE.annotation.lastIndex = 0;
while ((match = Call(RegExpPrototypeExec, PARSE.annotation, [annotations]))) {
const { 1: critical, 2: key, 3: value } = match;
if (key === 'u-ca') {
if (calendar === undefined) {
calendar = value;
calendarWasCritical = critical === '!';
} else if (critical === '!' || calendarWasCritical) {
throw new RangeErrorCtor(
`Invalid annotations in ${annotations}: more than one u-ca present with critical flag`
);
}
} else if (critical === '!') {
throw new RangeErrorCtor(`Unrecognized annotation: !${key}=${value}`);
}
}
return calendar;
}
export function ParseISODateTime(isoString) {
// ZDT is the superset of fields for every other Temporal type
const match = Call(RegExpPrototypeExec, PARSE.zoneddatetime, [isoString]);
if (!match) throw new RangeErrorCtor(`invalid RFC 9557 string: ${isoString}`);
const calendar = processAnnotations(match[16]);
let yearString = match[1];
if (yearString === '-000000') throw new RangeErrorCtor(`invalid RFC 9557 string: ${isoString}`);
const year = +yearString;
const month = +(match[2] ?? match[4] ?? 1);
const day = +(match[3] ?? match[5] ?? 1);
const hasTime = match[6] !== undefined;
const hour = +(match[6] ?? 0);
const minute = +(match[7] ?? match[10] ?? 0);
let second = +(match[8] ?? match[11] ?? 0);
if (second === 60) second = 59;
const fraction = (match[9] ?? match[12] ?? '') + '000000000';
const millisecond = +Call(StringPrototypeSlice, fraction, [0, 3]);
const microsecond = +Call(StringPrototypeSlice, fraction, [3, 6]);
const nanosecond = +Call(StringPrototypeSlice, fraction, [6, 9]);
let offset;
let z = false;
if (match[13]) {
offset = undefined;
z = true;
} else if (match[14]) {
offset = match[14];
}
const tzAnnotation = match[15];
RejectDateTime(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
return {
year,
month,
day,
time: hasTime ? { hour, minute, second, millisecond, microsecond, nanosecond } : 'start-of-day',
tzAnnotation,
offset,
z,
calendar
};
}
export function ParseTemporalInstantString(isoString) {
const result = ParseISODateTime(isoString);
if (!result.z && !result.offset) throw new RangeErrorCtor('Temporal.Instant requires a time zone offset');
return result;
}
export function ParseTemporalZonedDateTimeString(isoString) {
const result = ParseISODateTime(isoString);
if (!result.tzAnnotation) throw new RangeErrorCtor('Temporal.ZonedDateTime requires a time zone ID in brackets');
return result;
}
export function ParseTemporalDateTimeString(isoString) {
return ParseISODateTime(isoString);
}
export function ParseTemporalDateString(isoString) {
return ParseISODateTime(isoString);
}
export function ParseTemporalTimeString(isoString) {
const match = Call(RegExpPrototypeExec, PARSE.time, [isoString]);
let hour, minute, second, millisecond, microsecond, nanosecond;
if (match) {
processAnnotations(match[10]); // ignore found calendar
hour = +(match[1] ?? 0);
minute = +(match[2] ?? match[5] ?? 0);
second = +(match[3] ?? match[6] ?? 0);
if (second === 60) second = 59;
const fraction = (match[4] ?? match[7] ?? '') + '000000000';
millisecond = +Call(StringPrototypeSlice, fraction, [0, 3]);
microsecond = +Call(StringPrototypeSlice, fraction, [3, 6]);
nanosecond = +Call(StringPrototypeSlice, fraction, [6, 9]);
if (match[8]) throw new RangeErrorCtor('Z designator not supported for PlainTime');
} else {
const { time, z } = ParseISODateTime(isoString);
if (time === 'start-of-day') throw new RangeErrorCtor(`time is missing in string: ${isoString}`);
if (z) throw new RangeErrorCtor('Z designator not supported for PlainTime');
({ hour, minute, second, millisecond, microsecond, nanosecond } = time);
}
RejectTime(hour, minute, second, millisecond, microsecond, nanosecond);
// if it's a date-time string, OK
if (Call(RegExpPrototypeTest, /[tT ][0-9][0-9]/, [isoString])) {
return { hour, minute, second, millisecond, microsecond, nanosecond };
}
// Reject strings that are ambiguous with PlainMonthDay or PlainYearMonth.
try {
const { month, day } = ParseTemporalMonthDayString(isoString);
RejectISODate(1972, month, day);
} catch {
try {
const { year, month } = ParseTemporalYearMonthString(isoString);
RejectISODate(year, month, 1);
} catch {
return { hour, minute, second, millisecond, microsecond, nanosecond };
}
}
throw new RangeErrorCtor(`invalid RFC 9557 time-only string ${isoString}; may need a T prefix`);
}
export function ParseTemporalYearMonthString(isoString) {
const match = Call(RegExpPrototypeExec, PARSE.yearmonth, [isoString]);
let year, month, calendar, referenceISODay;
if (match) {
calendar = processAnnotations(match[3]);
let yearString = match[1];
if (yearString === '-000000') throw new RangeErrorCtor(`invalid RFC 9557 string: ${isoString}`);
year = +yearString;
month = +match[2];
referenceISODay = 1;
if (calendar !== undefined && calendar !== 'iso8601') {
throw new RangeErrorCtor('YYYY-MM format is only valid with iso8601 calendar');
}
} else {
let z;
({ year, month, calendar, day: referenceISODay, z } = ParseISODateTime(isoString));
if (z) throw new RangeErrorCtor('Z designator not supported for PlainYearMonth');
}
return { year, month, calendar, referenceISODay };
}
export function ParseTemporalMonthDayString(isoString) {
const match = Call(RegExpPrototypeExec, PARSE.monthday, [isoString]);
let month, day, calendar, referenceISOYear;
if (match) {
calendar = processAnnotations(match[3]);
month = +match[1];
day = +match[2];
if (calendar !== undefined && calendar !== 'iso8601') {
throw new RangeErrorCtor('MM-DD format is only valid with iso8601 calendar');
}
} else {
let z;
({ month, day, calendar, year: referenceISOYear, z } = ParseISODateTime(isoString));
if (z) throw new RangeErrorCtor('Z designator not supported for PlainMonthDay');
}
return { month, day, calendar, referenceISOYear };
}
const TIMEZONE_IDENTIFIER = new RegExpCtor(`^${PARSE.timeZoneID.source}$`, 'i');
const OFFSET_IDENTIFIER = new RegExpCtor(`^${PARSE.offsetIdentifier.source}$`);
function throwBadTimeZoneStringError(timeZoneString) {
// Offset identifiers only support minute precision, but offsets in ISO
// strings support nanosecond precision. If the identifier is invalid but
// it's a valid ISO offset, then it has sub-minute precision. Show a clearer
// error message in that case.
const msg = Call(RegExpPrototypeTest, OFFSET, [timeZoneString])
? 'Seconds not allowed in offset time zone'
: 'Invalid time zone';
throw new RangeErrorCtor(`${msg}: ${timeZoneString}`);
}
export function ParseTimeZoneIdentifier(identifier) {
if (!Call(RegExpPrototypeTest, TIMEZONE_IDENTIFIER, [identifier])) {
throwBadTimeZoneStringError(identifier);
}
if (Call(RegExpPrototypeTest, OFFSET_IDENTIFIER, [identifier])) {
const offsetNanoseconds = ParseDateTimeUTCOffset(identifier);
// The regex limits the input to minutes precision, so we know that the
// division below will result in an integer.
return { offsetMinutes: offsetNanoseconds / 60e9 };
}
return { tzName: identifier };
}
// This operation doesn't exist in the spec, but in the polyfill it's split from
// ParseTemporalTimeZoneString so that parsing can be tested separately from the
// logic of converting parsed values into a named or offset identifier.
export function ParseTemporalTimeZoneStringRaw(timeZoneString) {
if (Call(RegExpPrototypeTest, TIMEZONE_IDENTIFIER, [timeZoneString])) {
return { tzAnnotation: timeZoneString, offset: undefined, z: false };
}
try {
// Try parsing ISO string instead
const { tzAnnotation, offset, z } = ParseISODateTime(timeZoneString);
if (z || tzAnnotation || offset) {
return { tzAnnotation, offset, z };
}
} catch {
// fall through
}
throwBadTimeZoneStringError(timeZoneString);
}
export function ParseTemporalTimeZoneString(stringIdent) {
const { tzAnnotation, offset, z } = ParseTemporalTimeZoneStringRaw(stringIdent);
if (tzAnnotation) return ParseTimeZoneIdentifier(tzAnnotation);
if (z) return ParseTimeZoneIdentifier('UTC');
if (offset) return ParseTimeZoneIdentifier(offset);
/* c8 ignore next */ assertNotReached();
}
export function ParseTemporalDurationStringRaw(isoString) {
const match = Call(RegExpPrototypeExec, PARSE.duration, [isoString]);
if (!match) throw new RangeErrorCtor(`invalid duration: ${isoString}`);
if (Call(ArrayPrototypeEvery, match, [(part, i) => i < 2 || part === undefined])) {
throw new RangeErrorCtor(`invalid duration: ${isoString}`);
}
const sign = match[1] === '-' ? -1 : 1;
const years = match[2] === undefined ? 0 : ToIntegerWithTruncation(match[2]) * sign;
const months = match[3] === undefined ? 0 : ToIntegerWithTruncation(match[3]) * sign;
const weeks = match[4] === undefined ? 0 : ToIntegerWithTruncation(match[4]) * sign;
const days = match[5] === undefined ? 0 : ToIntegerWithTruncation(match[5]) * sign;
const hours = match[6] === undefined ? 0 : ToIntegerWithTruncation(match[6]) * sign;
let fHours = match[7];
let minutesStr = match[8];
let fMinutes = match[9];
let secondsStr = match[10];
let fSeconds = match[11];
let minutes = 0;
let seconds = 0;
// fractional hours, minutes, or seconds, expressed in whole nanoseconds:
let excessNanoseconds = 0;
if (fHours !== undefined) {
if (minutesStr ?? fMinutes ?? secondsStr ?? fSeconds ?? false) {
throw new RangeErrorCtor('only the smallest unit can be fractional');
}
excessNanoseconds = ToIntegerWithTruncation(Call(StringPrototypeSlice, fHours + '000000000', [0, 9])) * 3600 * sign;
} else {
minutes = minutesStr === undefined ? 0 : ToIntegerWithTruncation(minutesStr) * sign;
if (fMinutes !== undefined) {
if (secondsStr ?? fSeconds ?? false) {
throw new RangeErrorCtor('only the smallest unit can be fractional');
}
excessNanoseconds =
ToIntegerWithTruncation(Call(StringPrototypeSlice, fMinutes + '000000000', [0, 9])) * 60 * sign;
} else {
seconds = secondsStr === undefined ? 0 : ToIntegerWithTruncation(secondsStr) * sign;
if (fSeconds !== undefined) {
excessNanoseconds = ToIntegerWithTruncation(Call(StringPrototypeSlice, fSeconds + '000000000', [0, 9])) * sign;
}
}
}
const nanoseconds = excessNanoseconds % 1000;
const microseconds = MathTrunc(excessNanoseconds / 1000) % 1000;
const milliseconds = MathTrunc(excessNanoseconds / 1e6) % 1000;
seconds += MathTrunc(excessNanoseconds / 1e9) % 60;
minutes += MathTrunc(excessNanoseconds / 60e9);
RejectDuration(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds);
return { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds };
}
function ParseTemporalDurationString(isoString) {
const { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds } =
ParseTemporalDurationStringRaw(isoString);
const TemporalDuration = GetIntrinsic('%Temporal.Duration%');
return new TemporalDuration(
years,
months,
weeks,
days,
hours,
minutes,
seconds,
milliseconds,
microseconds,
nanoseconds
);
}
export function RegulateISODate(year, month, day, overflow) {
switch (overflow) {
case 'reject':
RejectISODate(year, month, day);
break;
case 'constrain':
({ year, month, day } = ConstrainISODate(year, month, day));
break;
}
return { year, month, day };
}
export function RegulateTime(hour, minute, second, millisecond, microsecond, nanosecond, overflow) {
switch (overflow) {
case 'reject':
RejectTime(hour, minute, second, millisecond, microsecond, nanosecond);
break;
case 'constrain':
hour = ConstrainToRange(hour, 0, 23);
minute = ConstrainToRange(minute, 0, 59);
second = ConstrainToRange(second, 0, 59);
millisecond = ConstrainToRange(millisecond, 0, 999);
microsecond = ConstrainToRange(microsecond, 0, 999);
nanosecond = ConstrainToRange(nanosecond, 0, 999);
break;
}
return { hour, minute, second, millisecond, microsecond, nanosecond };
}
export function ToTemporalPartialDurationRecord(temporalDurationLike) {
if (Type(temporalDurationLike) !== 'Object') {
throw new TypeErrorCtor('invalid duration-like');
}
const result = {
years: undefined,
months: undefined,
weeks: undefined,
days: undefined,
hours: undefined,
minutes: undefined,
seconds: undefined,
milliseconds: undefined,
microseconds: undefined,
nanoseconds: undefined
};
let any = false;
for (let index = 0; index < DURATION_FIELDS.length; index++) {
const property = DURATION_FIELDS[index];
const value = temporalDurationLike[property];
if (value !== undefined) {
any = true;
result[property] = ToIntegerIfIntegral(value);
}
}
if (!any) {
throw new TypeErrorCtor('invalid duration-like');
}
return result;
}
export function AdjustDateDurationRecord({ years, months, weeks, days }, newDays, newWeeks, newMonths) {
return {
years,
months: newMonths ?? months,
weeks: newWeeks ?? weeks,
days: newDays ?? days
};
}
export function ZeroDateDuration() {
return { years: 0, months: 0, weeks: 0, days: 0 };
}
export function CombineISODateAndTimeRecord(isoDate, time) {
return { isoDate, time };
}
export function MidnightTimeRecord() {
return { deltaDays: 0, hour: 0, minute: 0, second: 0, millisecond: 0, microsecond: 0, nanosecond: 0 };
}
export function NoonTimeRecord() {
return { deltaDays: 0, hour: 12, minute: 0, second: 0, millisecond: 0, microsecond: 0, nanosecond: 0 };
}
export function GetTemporalOverflowOption(options) {
return GetOption(options, 'overflow', ['constrain', 'reject'], 'constrain');
}
export function GetTemporalDisambiguationOption(options) {
return GetOption(options, 'disambiguation', ['compatible', 'earlier', 'later', 'reject'], 'compatible');
}
export function GetRoundingModeOption(options, fallback) {
return GetOption(
options,
'roundingMode',
['ceil', 'floor', 'expand', 'trunc', 'halfCeil', 'halfFloor', 'halfExpand', 'halfTrunc', 'halfEven'],
fallback
);
}
export function NegateRoundingMode(roundingMode) {
switch (roundingMode) {
case 'ceil':
return 'floor';
case 'floor':
return 'ceil';
case 'halfCeil':
return 'halfFloor';
case 'halfFloor':
return 'halfCeil';
default:
return roundingMode;
}
}
export function GetTemporalOffsetOption(options, fallback) {
return GetOption(options, 'offset', ['prefer', 'use', 'ignore', 'reject'], fallback);
}
export function GetTemporalShowCalendarNameOption(options) {
return GetOption(options, 'calendarName', ['auto', 'always', 'never', 'critical'], 'auto');
}
export function GetTemporalShowTimeZoneNameOption(options) {
return GetOption(options, 'timeZoneName', ['auto', 'never', 'critical'], 'auto');
}
export function GetTemporalShowOffsetOption(options) {
return GetOption(options, 'offset', ['auto', 'never'], 'auto');
}
export function GetDirectionOption(options) {
return GetOption(options, 'direction', ['next', 'previous'], REQUIRED);
}
export function GetRoundingIncrementOption(options) {
let increment = options.roundingIncrement;
if (increment === undefined) return 1;
const integerIncrement = ToIntegerWithTruncation(increment);
if (integerIncrement < 1 || integerIncrement > 1e9) {
throw new RangeErrorCtor(`roundingIncrement must be at least 1 and at most 1e9, not ${increment}`);
}
return integerIncrement;
}
export function ValidateTemporalRoundingIncrement(increment, dividend, inclusive) {
const maximum = inclusive ? dividend : dividend - 1;
if (increment > maximum) {
throw new RangeErrorCtor(`roundingIncrement must be at least 1 and less than ${maximum}, not ${increment}`);
}
if (dividend % increment !== 0) {
throw new RangeErrorCtor(`Rounding increment must divide evenly into ${dividend}`);
}
}
export function GetTemporalFractionalSecondDigitsOption(options) {
let digitsValue = options.fractionalSecondDigits;
if (digitsValue === undefined) return 'auto';
if (Type(digitsValue) !== 'Number') {
if (ToString(digitsValue) !== 'auto') {
throw new RangeErrorCtor(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${digitsValue}`);
}
return 'auto';
}
const digitCount = MathFloor(digitsValue);
if (!NumberIsFinite(digitCount) || digitCount < 0 || digitCount > 9) {
throw new RangeErrorCtor(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${digitsValue}`);
}
return digitCount;
}
export function ToSecondsStringPrecisionRecord(smallestUnit, precision) {
switch (smallestUnit) {
case 'minute':
return { precision: 'minute', unit: 'minute', increment: 1 };
case 'second':
return { precision: 0, unit: 'second', increment: 1 };
case 'millisecond':
return { precision: 3, unit: 'millisecond', increment: 1 };
case 'microsecond':
return { precision: 6, unit: 'microsecond', increment: 1 };
case 'nanosecond':
return { precision: 9, unit: 'nanosecond', increment: 1 };
default: // fall through if option not given
}
switch (precision) {
case 'auto':
return { precision, unit: 'nanosecond', increment: 1 };
case 0:
return { precision, unit: 'second', increment: 1 };
case 1:
case 2:
case 3:
return { precision, unit: 'millisecond', increment: 10 ** (3 - precision) };
case 4:
case 5:
case 6:
return { precision, unit: 'microsecond', increment: 10 ** (6 - precision) };
case 7:
case 8:
case 9:
return { precision, unit: 'nanosecond', increment: 10 ** (9 - precision) };
}
}
export const REQUIRED = SymbolCtor('~required~');
export function GetTemporalUnitValuedOption(options, key, unitGroup, requiredOrDefault, extraValues = []) {
const allowedSingular = [];
for (let index = 0; index < TEMPORAL_UNITS.length; index++) {
const unitInfo = TEMPORAL_UNITS[index];
const singular = unitInfo[1];
const category = unitInfo[2];
if (unitGroup === 'datetime' || unitGroup === category) {
Call(ArrayPrototypePush, allowedSingular, [singular]);
}
}
Call(ArrayPrototypePush, allowedSingular, extraValues);
let defaultVal = requiredOrDefault;
if (defaultVal === REQUIRED) {
defaultVal = undefined;
} else if (defaultVal !== undefined) {
Call(ArrayPrototypePush, allowedSingular, [defaultVal]);
}
const allowedValues = [];
Call(ArrayPrototypePush, allowedValues, allowedSingular);
for (let index = 0; index < allowedSingular.length; index++) {
const singular = allowedSingular[index];
const plural = Call(MapPrototypeGet, PLURAL_FOR, [singular]);
if (plural !== undefined) Call(ArrayPrototypePush, allowedValues, [plural]);
}
let retval = GetOption(options, key, allowedValues, defaultVal);
if (retval === undefined && requiredOrDefault === REQUIRED) {
throw new RangeErrorCtor(`${key} is required`);
}
if (Call(MapPrototypeHas, SINGULAR_FOR, [retval])) retval = Call(MapPrototypeGet, SINGULAR_FOR, [retval]);
return retval;
}
export function GetTemporalRelativeToOption(options) {
// returns: {
// plainRelativeTo: Temporal.PlainDate | undefined
// zonedRelativeTo: Temporal.ZonedDateTime | undefined
// }
// plainRelativeTo and zonedRelativeTo are mutually exclusive.
const relativeTo = options.relativeTo;
if (relativeTo === undefined) return {};
let offsetBehaviour = 'option';
let matchMinutes = false;
let isoDate, time, calendar, timeZone, offset;
if (Type(relativeTo) === 'Object') {
if (IsTemporalZonedDateTime(relativeTo)) {
return { zonedRelativeTo: relativeTo };
}
if (IsTemporalDate(relativeTo)) return { plainRelativeTo: relativeTo };
if (IsTemporalDateTime(relativeTo)) {
return {
plainRelativeTo: CreateTemporalDate(GetSlot(relativeTo, ISO_DATE_TIME).isoDate, GetSlot(relativeTo, CALENDAR))
};
}
calendar = GetTemporalCalendarIdentifierWithISODefault(relativeTo);
const fields = PrepareCalendarFields(
calendar,
relativeTo,
['year', 'month', 'monthCode', 'day'],
['hour', 'minute', 'second', 'millisecond', 'microsecond', 'nanosecond', 'offset', 'timeZone'],
[]
);
({ isoDate, time } = InterpretTemporalDateTimeFields(calendar, fields, 'constrain'));
({ offset, timeZone } = fields);
if (offset === undefined) offsetBehaviour = 'wall';
} else {
let tzAnnotation, z, year, month, day;
({ year, month, day, time, calendar, tzAnnotation, offset, z } = ParseISODateTime(RequireString(relativeTo)));
if (tzAnnotation) {
timeZone = ToTemporalTimeZoneIdentifier(tzAnnotation);
if (z) {
offsetBehaviour = 'exact';
} else if (!offset) {
offsetBehaviour = 'wall';
}
matchMinutes = true;
} else if (z) {
throw new RangeErrorCtor(
'Z designator not supported for PlainDate relativeTo; either remove the Z or add a bracketed time zone'
);