deno_webidl 0.179.0

WebIDL implementation for Deno
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

// Adapted from https://github.com/jsdom/webidl-conversions.
// Copyright Domenic Denicola. Licensed under BSD-2-Clause License.
// Original license at https://github.com/jsdom/webidl-conversions/blob/master/LICENSE.md.

/// <reference path="../../core/internal.d.ts" />

import { core, primordials } from "ext:core/mod.js";
const {
  isArrayBuffer,
  isDataView,
  isSharedArrayBuffer,
  isTypedArray,
} = core;
const {
  ArrayBufferIsView,
  ArrayPrototypeForEach,
  ArrayPrototypePush,
  ArrayPrototypeSort,
  ArrayIteratorPrototype,
  BigInt,
  BigIntAsIntN,
  BigIntAsUintN,
  DataViewPrototypeGetBuffer,
  Float32Array,
  Float64Array,
  FunctionPrototypeBind,
  FunctionPrototypeCall,
  Int16Array,
  Int32Array,
  Int8Array,
  MathFloor,
  MathFround,
  MathMax,
  MathMin,
  MathPow,
  MathRound,
  MathTrunc,
  Number,
  NumberIsFinite,
  NumberIsNaN,
  NumberMAX_SAFE_INTEGER,
  NumberMIN_SAFE_INTEGER,
  ObjectAssign,
  ObjectCreate,
  ObjectDefineProperties,
  ObjectDefineProperty,
  ObjectGetOwnPropertyDescriptor,
  ObjectGetOwnPropertyDescriptors,
  ObjectGetPrototypeOf,
  ObjectHasOwn,
  ObjectPrototypeIsPrototypeOf,
  ObjectIs,
  PromisePrototypeThen,
  PromiseReject,
  PromiseResolve,
  ReflectApply,
  ReflectDefineProperty,
  ReflectGetOwnPropertyDescriptor,
  ReflectHas,
  ReflectOwnKeys,
  RegExpPrototypeTest,
  SafeRegExp,
  SafeSet,
  SetPrototypeEntries,
  SetPrototypeForEach,
  SetPrototypeKeys,
  SetPrototypeValues,
  SetPrototypeHas,
  SetPrototypeClear,
  SetPrototypeDelete,
  SetPrototypeAdd,
  // TODO(lucacasonato): add SharedArrayBuffer to primordials
  // SharedArrayBufferPrototype,
  String,
  StringPrototypeCharCodeAt,
  StringPrototypeToWellFormed,
  Symbol,
  SymbolIterator,
  SymbolAsyncIterator,
  SymbolToStringTag,
  TypedArrayPrototypeGetBuffer,
  TypedArrayPrototypeGetSymbolToStringTag,
  TypeError,
  Uint16Array,
  Uint32Array,
  Uint8Array,
  Uint8ClampedArray,
} = primordials;

function makeException(ErrorType, message, prefix, context) {
  return new ErrorType(
    `${prefix ? prefix + ": " : ""}${context ? context : "Value"} ${message}`,
  );
}

function toNumber(value) {
  if (typeof value === "bigint") {
    throw new TypeError("Cannot convert a BigInt value to a number");
  }
  return Number(value);
}

function type(V) {
  if (V === null) {
    return "Null";
  }
  switch (typeof V) {
    case "undefined":
      return "Undefined";
    case "boolean":
      return "Boolean";
    case "number":
      return "Number";
    case "string":
      return "String";
    case "symbol":
      return "Symbol";
    case "bigint":
      return "BigInt";
    case "object":
    // Falls through
    case "function":
    // Falls through
    default:
      // Per ES spec, typeof returns an implementation-defined value that is not any of the existing ones for
      // uncallable non-standard exotic objects. Yet Type() which the Web IDL spec depends on returns Object for
      // such cases. So treat the default case as an object.
      return "Object";
  }
}

// Round x to the nearest integer, choosing the even integer if it lies halfway between two.
function evenRound(x) {
  // There are four cases for numbers with fractional part being .5:
  //
  // case |     x     | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 |   example
  //   1  |  2n + 0.5 |  2n      |  2n + 1  |  2n      |   >    |  0.5  |   0   |  0.5 ->  0
  //   2  |  2n + 1.5 |  2n + 1  |  2n + 2  |  2n + 2  |   >    |  0.5  |   1   |  1.5 ->  2
  //   3  | -2n - 0.5 | -2n - 1  | -2n      | -2n      |   <    | -0.5  |   0   | -0.5 ->  0
  //   4  | -2n - 1.5 | -2n - 2  | -2n - 1  | -2n - 2  |   <    | -0.5  |   1   | -1.5 -> -2
  // (where n is a non-negative integer)
  //
  // Branch here for cases 1 and 4
  if (
    (x > 0 && x % 1 === +0.5 && (x & 1) === 0) ||
    (x < 0 && x % 1 === -0.5 && (x & 1) === 1)
  ) {
    return censorNegativeZero(MathFloor(x));
  }

  return censorNegativeZero(MathRound(x));
}

function integerPart(n) {
  return censorNegativeZero(MathTrunc(n));
}

function sign(x) {
  return x < 0 ? -1 : 1;
}

function modulo(x, y) {
  // https://tc39.github.io/ecma262/#eqn-modulo
  // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos
  const signMightNotMatch = x % y;
  if (sign(y) !== sign(signMightNotMatch)) {
    return signMightNotMatch + y;
  }
  return signMightNotMatch;
}

function censorNegativeZero(x) {
  return x === 0 ? 0 : x;
}

function createIntegerConversion(bitLength, typeOpts) {
  const isSigned = !typeOpts.unsigned;

  let lowerBound;
  let upperBound;
  if (bitLength === 64) {
    upperBound = NumberMAX_SAFE_INTEGER;
    lowerBound = !isSigned ? 0 : NumberMIN_SAFE_INTEGER;
  } else if (!isSigned) {
    lowerBound = 0;
    upperBound = MathPow(2, bitLength) - 1;
  } else {
    lowerBound = -MathPow(2, bitLength - 1);
    upperBound = MathPow(2, bitLength - 1) - 1;
  }

  const twoToTheBitLength = MathPow(2, bitLength);
  const twoToOneLessThanTheBitLength = MathPow(2, bitLength - 1);

  return (
    V,
    prefix = undefined,
    context = undefined,
    opts = { __proto__: null },
  ) => {
    let x = toNumber(V);
    x = censorNegativeZero(x);

    if (opts.enforceRange) {
      if (!NumberIsFinite(x)) {
        throw makeException(
          TypeError,
          "is not a finite number",
          prefix,
          context,
        );
      }

      x = integerPart(x);

      if (x < lowerBound || x > upperBound) {
        throw makeException(
          TypeError,
          `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`,
          prefix,
          context,
        );
      }

      return x;
    }

    if (!NumberIsNaN(x) && opts.clamp) {
      x = MathMin(MathMax(x, lowerBound), upperBound);
      x = evenRound(x);
      return x;
    }

    if (!NumberIsFinite(x) || x === 0) {
      return 0;
    }
    x = integerPart(x);

    // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if
    // possible. Hopefully it's an optimization for the non-64-bitLength cases too.
    if (x >= lowerBound && x <= upperBound) {
      return x;
    }

    // These will not work great for bitLength of 64, but oh well. See the README for more details.
    x = modulo(x, twoToTheBitLength);
    if (isSigned && x >= twoToOneLessThanTheBitLength) {
      return x - twoToTheBitLength;
    }
    return x;
  };
}

function createLongLongConversion(bitLength, { unsigned }) {
  const upperBound = NumberMAX_SAFE_INTEGER;
  const lowerBound = unsigned ? 0 : NumberMIN_SAFE_INTEGER;
  const asBigIntN = unsigned ? BigIntAsUintN : BigIntAsIntN;

  return (
    V,
    prefix = undefined,
    context = undefined,
    opts = { __proto__: null },
  ) => {
    let x = toNumber(V);
    x = censorNegativeZero(x);

    if (opts.enforceRange) {
      if (!NumberIsFinite(x)) {
        throw makeException(
          TypeError,
          "is not a finite number",
          prefix,
          context,
        );
      }

      x = integerPart(x);

      if (x < lowerBound || x > upperBound) {
        throw makeException(
          TypeError,
          `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`,
          prefix,
          context,
        );
      }

      return x;
    }

    if (!NumberIsNaN(x) && opts.clamp) {
      x = MathMin(MathMax(x, lowerBound), upperBound);
      x = evenRound(x);
      return x;
    }

    if (!NumberIsFinite(x) || x === 0) {
      return 0;
    }

    let xBigInt = BigInt(integerPart(x));
    xBigInt = asBigIntN(bitLength, xBigInt);
    return Number(xBigInt);
  };
}

const converters = [];

converters.any = (V) => {
  return V;
};

converters.boolean = function (val) {
  return !!val;
};

converters.byte = createIntegerConversion(8, { unsigned: false });
converters.octet = createIntegerConversion(8, { unsigned: true });

converters.short = createIntegerConversion(16, { unsigned: false });
converters["unsigned short"] = createIntegerConversion(16, {
  unsigned: true,
});

converters.long = createIntegerConversion(32, { unsigned: false });
converters["unsigned long"] = createIntegerConversion(32, { unsigned: true });

converters["long long"] = createLongLongConversion(64, { unsigned: false });
converters["unsigned long long"] = createLongLongConversion(64, {
  unsigned: true,
});

converters.float = (V, prefix, context, _opts) => {
  const x = toNumber(V);

  if (!NumberIsFinite(x)) {
    throw makeException(
      TypeError,
      "is not a finite floating-point value",
      prefix,
      context,
    );
  }

  if (ObjectIs(x, -0)) {
    return x;
  }

  const y = MathFround(x);

  if (!NumberIsFinite(y)) {
    throw makeException(
      TypeError,
      "is outside the range of a single-precision floating-point value",
      prefix,
      context,
    );
  }

  return y;
};

converters["unrestricted float"] = (V, _prefix, _context, _opts) => {
  const x = toNumber(V);

  if (NumberIsNaN(x)) {
    return x;
  }

  if (ObjectIs(x, -0)) {
    return x;
  }

  return MathFround(x);
};

converters.double = (V, prefix, context, _opts) => {
  const x = toNumber(V);

  if (!NumberIsFinite(x)) {
    throw makeException(
      TypeError,
      "is not a finite floating-point value",
      prefix,
      context,
    );
  }

  return x;
};

converters["unrestricted double"] = (V, _prefix, _context, _opts) => {
  const x = toNumber(V);

  return x;
};

converters.DOMString = function (
  V,
  prefix,
  context,
  opts = { __proto__: null },
) {
  if (typeof V === "string") {
    return V;
  } else if (V === null && opts.treatNullAsEmptyString) {
    return "";
  } else if (typeof V === "symbol") {
    throw makeException(
      TypeError,
      "is a symbol, which cannot be converted to a string",
      prefix,
      context,
    );
  }

  return String(V);
};

function isByteString(input) {
  for (let i = 0; i < input.length; i++) {
    if (StringPrototypeCharCodeAt(input, i) > 255) {
      // If a character code is greater than 255, it means the string is not a byte string.
      return false;
    }
  }
  return true;
}

converters.ByteString = (V, prefix, context, opts) => {
  const x = converters.DOMString(V, prefix, context, opts);
  if (!isByteString(x)) {
    throw makeException(
      TypeError,
      "is not a valid ByteString",
      prefix,
      context,
    );
  }
  return x;
};

converters.USVString = (V, prefix, context, opts) => {
  const S = converters.DOMString(V, prefix, context, opts);
  return StringPrototypeToWellFormed(S);
};

converters.object = (V, prefix, context, _opts) => {
  if (type(V) !== "Object") {
    throw makeException(
      TypeError,
      "is not an object",
      prefix,
      context,
    );
  }

  return V;
};

// Not exported, but used in Function and VoidFunction.

// Neither Function nor VoidFunction is defined with [TreatNonObjectAsNull], so
// handling for that is omitted.
function convertCallbackFunction(V, prefix, context, _opts) {
  if (typeof V !== "function") {
    throw makeException(
      TypeError,
      "is not a function",
      prefix,
      context,
    );
  }
  return V;
}

converters.ArrayBuffer = (
  V,
  prefix = undefined,
  context = undefined,
  opts = { __proto__: null },
) => {
  if (!isArrayBuffer(V)) {
    if (opts.allowShared && !isSharedArrayBuffer(V)) {
      throw makeException(
        TypeError,
        "is not an ArrayBuffer or SharedArrayBuffer",
        prefix,
        context,
      );
    }
    throw makeException(
      TypeError,
      "is not an ArrayBuffer",
      prefix,
      context,
    );
  }

  return V;
};

converters.DataView = (
  V,
  prefix = undefined,
  context = undefined,
  opts = { __proto__: null },
) => {
  if (!isDataView(V)) {
    throw makeException(
      TypeError,
      "is not a DataView",
      prefix,
      context,
    );
  }

  if (
    !opts.allowShared &&
    isSharedArrayBuffer(DataViewPrototypeGetBuffer(V))
  ) {
    throw makeException(
      TypeError,
      "is backed by a SharedArrayBuffer, which is not allowed",
      prefix,
      context,
    );
  }

  return V;
};

ArrayPrototypeForEach(
  [
    Int8Array,
    Int16Array,
    Int32Array,
    Uint8Array,
    Uint16Array,
    Uint32Array,
    Uint8ClampedArray,
    // TODO(petamoriken): add Float16Array converter
    // Float16Array,
    Float32Array,
    Float64Array,
  ],
  (func) => {
    const name = func.name;
    const article = RegExpPrototypeTest(new SafeRegExp(/^[AEIOU]/), name)
      ? "an"
      : "a";
    converters[name] = (
      V,
      prefix = undefined,
      context = undefined,
      opts = { __proto__: null },
    ) => {
      if (TypedArrayPrototypeGetSymbolToStringTag(V) !== name) {
        throw makeException(
          TypeError,
          `is not ${article} ${name} object`,
          prefix,
          context,
        );
      }
      if (
        !opts.allowShared &&
        isSharedArrayBuffer(TypedArrayPrototypeGetBuffer(V))
      ) {
        throw makeException(
          TypeError,
          "is a view on a SharedArrayBuffer, which is not allowed",
          prefix,
          context,
        );
      }

      return V;
    };
  },
);

// Common definitions

converters.ArrayBufferView = (
  V,
  prefix = undefined,
  context = undefined,
  opts = { __proto__: null },
) => {
  if (!ArrayBufferIsView(V)) {
    throw makeException(
      TypeError,
      "is not a view on an ArrayBuffer or SharedArrayBuffer",
      prefix,
      context,
    );
  }
  let buffer;
  if (isTypedArray(V)) {
    buffer = TypedArrayPrototypeGetBuffer(V);
  } else {
    buffer = DataViewPrototypeGetBuffer(V);
  }
  if (!opts.allowShared && isSharedArrayBuffer(buffer)) {
    throw makeException(
      TypeError,
      "is a view on a SharedArrayBuffer, which is not allowed",
      prefix,
      context,
    );
  }

  return V;
};

converters.BufferSource = (
  V,
  prefix = undefined,
  context = undefined,
  opts = { __proto__: null },
) => {
  if (ArrayBufferIsView(V)) {
    let buffer;
    if (isTypedArray(V)) {
      buffer = TypedArrayPrototypeGetBuffer(V);
    } else {
      buffer = DataViewPrototypeGetBuffer(V);
    }
    if (!opts.allowShared && isSharedArrayBuffer(buffer)) {
      throw makeException(
        TypeError,
        "is a view on a SharedArrayBuffer, which is not allowed",
        prefix,
        context,
      );
    }

    return V;
  }

  if (!opts.allowShared && !isArrayBuffer(V)) {
    throw makeException(
      TypeError,
      "is not an ArrayBuffer or a view on one",
      prefix,
      context,
    );
  }
  if (
    opts.allowShared &&
    !isSharedArrayBuffer(V) &&
    !isArrayBuffer(V)
  ) {
    throw makeException(
      TypeError,
      "is not an ArrayBuffer, SharedArrayBuffer, or a view on one",
      prefix,
      context,
    );
  }

  return V;
};

converters.DOMTimeStamp = converters["unsigned long long"];
converters.DOMHighResTimeStamp = converters["double"];

converters.Function = convertCallbackFunction;

converters.VoidFunction = convertCallbackFunction;

converters["UVString?"] = createNullableConverter(
  converters.USVString,
);
converters["sequence<double>"] = createSequenceConverter(
  converters.double,
);
converters["sequence<object>"] = createSequenceConverter(
  converters.object,
);
converters["Promise<undefined>"] = createPromiseConverter(() => undefined);

converters["sequence<ByteString>"] = createSequenceConverter(
  converters.ByteString,
);
converters["sequence<sequence<ByteString>>"] = createSequenceConverter(
  converters["sequence<ByteString>"],
);
converters["record<ByteString, ByteString>"] = createRecordConverter(
  converters.ByteString,
  converters.ByteString,
);

converters["sequence<USVString>"] = createSequenceConverter(
  converters.USVString,
);
converters["sequence<sequence<USVString>>"] = createSequenceConverter(
  converters["sequence<USVString>"],
);
converters["record<USVString, USVString>"] = createRecordConverter(
  converters.USVString,
  converters.USVString,
);

converters["sequence<DOMString>"] = createSequenceConverter(
  converters.DOMString,
);

function requiredArguments(length, required, prefix) {
  if (length < required) {
    const errMsg = `${prefix ? prefix + ": " : ""}${required} argument${
      required === 1 ? "" : "s"
    } required, but only ${length} present`;
    throw new TypeError(errMsg);
  }
}

function createDictionaryConverter(name, ...dictionaries) {
  let hasRequiredKey = false;
  const allMembers = [];
  for (let i = 0; i < dictionaries.length; ++i) {
    const members = dictionaries[i];
    for (let j = 0; j < members.length; ++j) {
      const member = members[j];
      if (member.required) {
        hasRequiredKey = true;
      }
      ArrayPrototypePush(allMembers, member);
    }
  }
  ArrayPrototypeSort(allMembers, (a, b) => {
    if (a.key == b.key) {
      return 0;
    }
    return a.key < b.key ? -1 : 1;
  });

  const defaultValues = { __proto__: null };
  for (let i = 0; i < allMembers.length; ++i) {
    const member = allMembers[i];
    if (ReflectHas(member, "defaultValue")) {
      const idlMemberValue = member.defaultValue;
      const imvType = typeof idlMemberValue;
      // Copy by value types can be directly assigned, copy by reference types
      // need to be re-created for each allocation.
      if (
        imvType === "number" || imvType === "boolean" ||
        imvType === "string" || imvType === "bigint" ||
        imvType === "undefined"
      ) {
        defaultValues[member.key] = member.converter(idlMemberValue, {});
      } else {
        ObjectDefineProperty(defaultValues, member.key, {
          __proto__: null,
          get() {
            return member.converter(idlMemberValue, member.defaultValue);
          },
          enumerable: true,
        });
      }
    }
  }

  return function (
    V,
    prefix = undefined,
    context = undefined,
    opts = { __proto__: null },
  ) {
    const typeV = type(V);
    switch (typeV) {
      case "Undefined":
      case "Null":
      case "Object":
        break;
      default:
        throw makeException(
          TypeError,
          "can not be converted to a dictionary",
          prefix,
          context,
        );
    }
    const esDict = V;

    const idlDict = ObjectAssign({}, defaultValues);

    // NOTE: fast path Null and Undefined.
    if ((V === undefined || V === null) && !hasRequiredKey) {
      return idlDict;
    }

    for (let i = 0; i < allMembers.length; ++i) {
      const member = allMembers[i];
      const key = member.key;

      let esMemberValue;
      if (typeV === "Undefined" || typeV === "Null") {
        esMemberValue = undefined;
      } else {
        esMemberValue = esDict[key];
      }

      if (esMemberValue !== undefined) {
        const memberContext = `'${key}' of '${name}'${
          context ? ` (${context})` : ""
        }`;
        const converter = member.converter;
        const idlMemberValue = converter(
          esMemberValue,
          prefix,
          memberContext,
          opts,
        );
        idlDict[key] = idlMemberValue;
      } else if (member.required) {
        throw makeException(
          TypeError,
          `can not be converted to '${name}' because '${key}' is required in '${name}'`,
          prefix,
          context,
        );
      }
    }

    return idlDict;
  };
}

// https://heycam.github.io/webidl/#es-enumeration
function createEnumConverter(name, values) {
  const E = new SafeSet(values);

  return function (
    V,
    prefix = undefined,
    _context = undefined,
    _opts = { __proto__: null },
  ) {
    const S = String(V);

    if (!E.has(S)) {
      throw new TypeError(
        `${
          prefix ? prefix + ": " : ""
        }The provided value '${S}' is not a valid enum value of type ${name}`,
      );
    }

    return S;
  };
}

function createNullableConverter(converter) {
  return (
    V,
    prefix = undefined,
    context = undefined,
    opts = { __proto__: null },
  ) => {
    // FIXME: If Type(V) is not Object, and the conversion to an IDL value is
    // being performed due to V being assigned to an attribute whose type is a
    // nullable callback function that is annotated with
    // [LegacyTreatNonObjectAsNull], then return the IDL nullable type T?
    // value null.

    if (V === null || V === undefined) return null;
    return converter(V, prefix, context, opts);
  };
}

// https://heycam.github.io/webidl/#es-sequence
function createSequenceConverter(converter) {
  return function (
    V,
    prefix = undefined,
    context = undefined,
    opts = { __proto__: null },
  ) {
    if (type(V) !== "Object") {
      throw makeException(
        TypeError,
        "can not be converted to sequence.",
        prefix,
        context,
      );
    }
    const iter = V?.[SymbolIterator]?.();
    if (iter === undefined) {
      throw makeException(
        TypeError,
        "can not be converted to sequence.",
        prefix,
        context,
      );
    }
    const array = [];
    while (true) {
      const res = iter?.next?.();
      if (res === undefined) {
        throw makeException(
          TypeError,
          "can not be converted to sequence.",
          prefix,
          context,
        );
      }
      if (res.done === true) break;
      const val = converter(
        res.value,
        prefix,
        `${context}, index ${array.length}`,
        opts,
      );
      ArrayPrototypePush(array, val);
    }
    return array;
  };
}

function isAsyncIterable(obj) {
  if (obj[SymbolAsyncIterator] === undefined) {
    if (obj[SymbolIterator] === undefined) {
      return false;
    }
  }

  return true;
}

const AsyncIterable = Symbol("[[asyncIterable]]");

function createAsyncIterableConverter(converter) {
  return function (
    V,
    prefix = undefined,
    context = undefined,
    opts = { __proto__: null },
  ) {
    if (type(V) !== "Object") {
      throw makeException(
        TypeError,
        "can not be converted to async iterable.",
        prefix,
        context,
      );
    }

    let isAsync = true;
    let method = V[SymbolAsyncIterator];
    if (method === undefined) {
      method = V[SymbolIterator];

      if (method === undefined) {
        throw makeException(
          TypeError,
          "is not iterable.",
          prefix,
          context,
        );
      }

      isAsync = false;
    }

    return {
      value: V,
      [AsyncIterable]: AsyncIterable,
      open(context) {
        const iter = FunctionPrototypeCall(method, V);
        if (type(iter) !== "Object") {
          throw new TypeError(
            `${context} could not be iterated because iterator method did not return object, but ${
              type(iter)
            }.`,
          );
        }

        let asyncIterator = iter;

        if (!isAsync) {
          asyncIterator = {
            // deno-lint-ignore require-await
            async next() {
              // deno-lint-ignore prefer-primordials
              return iter.next();
            },
          };
        }

        return {
          async next() {
            // deno-lint-ignore prefer-primordials
            const iterResult = await asyncIterator.next();
            if (type(iterResult) !== "Object") {
              throw TypeError(
                `${context} failed to iterate next value because the next() method did not return an object, but ${
                  type(iterResult)
                }.`,
              );
            }

            if (iterResult.done) {
              return { done: true };
            }

            const iterValue = converter(
              iterResult.value,
              `${context} failed to iterate next value`,
              `The value returned from the next() method`,
              opts,
            );

            return { done: false, value: iterValue };
          },
          async return(reason) {
            if (asyncIterator.return === undefined) {
              return undefined;
            }

            // deno-lint-ignore prefer-primordials
            const returnPromiseResult = await asyncIterator.return(reason);
            if (type(returnPromiseResult) !== "Object") {
              throw TypeError(
                `${context} failed to close iterator because the return() method did not return an object, but ${
                  type(returnPromiseResult)
                }.`,
              );
            }

            return undefined;
          },
          [SymbolAsyncIterator]() {
            return this;
          },
        };
      },
    };
  };
}

function createRecordConverter(keyConverter, valueConverter) {
  return (V, prefix, context, opts) => {
    if (type(V) !== "Object") {
      throw makeException(
        TypeError,
        "can not be converted to dictionary",
        prefix,
        context,
      );
    }
    const result = { __proto__: null };
    // Fast path for common case (not a Proxy)
    if (!core.isProxy(V)) {
      for (const key in V) {
        if (!ObjectHasOwn(V, key)) {
          continue;
        }
        const typedKey = keyConverter(key, prefix, context, opts);
        const value = V[key];
        const typedValue = valueConverter(value, prefix, context, opts);
        result[typedKey] = typedValue;
      }
      return result;
    }
    // Slow path if Proxy (e.g: in WPT tests)
    const keys = ReflectOwnKeys(V);
    for (let i = 0; i < keys.length; ++i) {
      const key = keys[i];
      const desc = ObjectGetOwnPropertyDescriptor(V, key);
      if (desc !== undefined && desc.enumerable === true) {
        const typedKey = keyConverter(key, prefix, context, opts);
        const value = V[key];
        const typedValue = valueConverter(value, prefix, context, opts);
        result[typedKey] = typedValue;
      }
    }
    return result;
  };
}

function createPromiseConverter(converter) {
  return (V, prefix, context, opts) =>
    // should be able to handle thenables
    // see: https://github.com/web-platform-tests/wpt/blob/a31d3ba53a79412793642366f3816c9a63f0cf57/streams/writable-streams/close.any.js#L207
    typeof V?.then === "function"
      ? PromisePrototypeThen(PromiseResolve(V), (V) =>
        converter(V, prefix, context, opts))
      : PromiseResolve(converter(V, prefix, context, opts));
}

function invokeCallbackFunction(
  callable,
  args,
  thisArg,
  returnValueConverter,
  prefix,
  returnsPromise,
) {
  try {
    const rv = ReflectApply(callable, thisArg, args);
    return returnValueConverter(rv, prefix, "return value");
  } catch (err) {
    if (returnsPromise === true) {
      return PromiseReject(err);
    }
    throw err;
  }
}

const brand = Symbol("[[webidl.brand]]");

function createInterfaceConverter(name, prototype) {
  return (V, prefix, context, _opts) => {
    if (!ObjectPrototypeIsPrototypeOf(prototype, V) || V[brand] !== brand) {
      throw makeException(
        TypeError,
        `is not of type ${name}`,
        prefix,
        context,
      );
    }
    return V;
  };
}

// TODO(lucacasonato): have the user pass in the prototype, and not the type.
function createBranded(Type) {
  const t = ObjectCreate(Type.prototype);
  t[brand] = brand;
  return t;
}

function assertBranded(self, prototype) {
  if (
    !ObjectPrototypeIsPrototypeOf(prototype, self) || self[brand] !== brand
  ) {
    throw new TypeError("Illegal invocation");
  }
}

function illegalConstructor() {
  throw new TypeError("Illegal constructor");
}

function define(target, source) {
  const keys = ReflectOwnKeys(source);
  for (let i = 0; i < keys.length; ++i) {
    const key = keys[i];
    const descriptor = ReflectGetOwnPropertyDescriptor(source, key);
    if (descriptor && !ReflectDefineProperty(target, key, descriptor)) {
      throw new TypeError(`Cannot redefine property: ${String(key)}`);
    }
  }
}

const _iteratorInternal = Symbol("iterator internal");

const globalIteratorPrototype = ObjectGetPrototypeOf(ArrayIteratorPrototype);

function mixinPairIterable(name, prototype, dataSymbol, keyKey, valueKey) {
  const iteratorPrototype = ObjectCreate(globalIteratorPrototype, {
    [SymbolToStringTag]: { configurable: true, value: `${name} Iterator` },
  });
  define(iteratorPrototype, {
    next() {
      const internal = this && this[_iteratorInternal];
      if (!internal) {
        throw new TypeError(
          `next() called on a value that is not a ${name} iterator object`,
        );
      }
      const { target, kind, index } = internal;
      const values = target[dataSymbol];
      const len = values.length;
      if (index >= len) {
        return { value: undefined, done: true };
      }
      const pair = values[index];
      internal.index = index + 1;
      let result;
      switch (kind) {
        case "key":
          result = pair[keyKey];
          break;
        case "value":
          result = pair[valueKey];
          break;
        case "key+value":
          result = [pair[keyKey], pair[valueKey]];
          break;
      }
      return { value: result, done: false };
    },
  });
  function createDefaultIterator(target, kind) {
    const iterator = ObjectCreate(iteratorPrototype);
    ObjectDefineProperty(iterator, _iteratorInternal, {
      __proto__: null,
      value: { target, kind, index: 0 },
      configurable: true,
    });
    return iterator;
  }

  function entries() {
    assertBranded(this, prototype.prototype);
    return createDefaultIterator(this, "key+value");
  }

  const properties = {
    entries: {
      value: entries,
      writable: true,
      enumerable: true,
      configurable: true,
    },
    [SymbolIterator]: {
      value: entries,
      writable: true,
      enumerable: false,
      configurable: true,
    },
    keys: {
      value: function keys() {
        assertBranded(this, prototype.prototype);
        return createDefaultIterator(this, "key");
      },
      writable: true,
      enumerable: true,
      configurable: true,
    },
    values: {
      value: function values() {
        assertBranded(this, prototype.prototype);
        return createDefaultIterator(this, "value");
      },
      writable: true,
      enumerable: true,
      configurable: true,
    },
    forEach: {
      value: function forEach(idlCallback, thisArg = undefined) {
        assertBranded(this, prototype.prototype);
        const prefix = `Failed to execute 'forEach' on '${name}'`;
        requiredArguments(arguments.length, 1, { prefix });
        idlCallback = converters["Function"](idlCallback, {
          prefix,
          context: "Argument 1",
        });
        idlCallback = FunctionPrototypeBind(
          idlCallback,
          thisArg ?? globalThis,
        );
        const pairs = this[dataSymbol];
        for (let i = 0; i < pairs.length; i++) {
          const entry = pairs[i];
          idlCallback(entry[valueKey], entry[keyKey], this);
        }
      },
      writable: true,
      enumerable: true,
      configurable: true,
    },
  };
  return ObjectDefineProperties(prototype.prototype, properties);
}

function configureInterface(interface_) {
  configureProperties(interface_);
  configureProperties(interface_.prototype);
  ObjectDefineProperty(interface_.prototype, SymbolToStringTag, {
    __proto__: null,
    value: interface_.name,
    enumerable: false,
    configurable: true,
    writable: false,
  });
}

function configureProperties(obj) {
  const descriptors = ObjectGetOwnPropertyDescriptors(obj);
  for (const key in descriptors) {
    if (!ObjectHasOwn(descriptors, key)) {
      continue;
    }
    if (key === "constructor") continue;
    if (key === "prototype") continue;
    const descriptor = descriptors[key];
    if (
      ReflectHas(descriptor, "value") &&
      typeof descriptor.value === "function"
    ) {
      ObjectDefineProperty(obj, key, {
        __proto__: null,
        enumerable: true,
        writable: true,
        configurable: true,
      });
    } else if (ReflectHas(descriptor, "get")) {
      ObjectDefineProperty(obj, key, {
        __proto__: null,
        enumerable: true,
        configurable: true,
      });
    }
  }
}

const setlikeInner = Symbol("[[set]]");

// Ref: https://webidl.spec.whatwg.org/#es-setlike
function setlike(obj, objPrototype, readonly) {
  ObjectDefineProperties(obj, {
    size: {
      __proto__: null,
      configurable: true,
      enumerable: true,
      get() {
        assertBranded(this, objPrototype);
        return obj[setlikeInner].size;
      },
    },
    [SymbolIterator]: {
      __proto__: null,
      configurable: true,
      enumerable: false,
      writable: true,
      value() {
        assertBranded(this, objPrototype);
        return obj[setlikeInner][SymbolIterator]();
      },
    },
    entries: {
      __proto__: null,
      configurable: true,
      enumerable: true,
      writable: true,
      value() {
        assertBranded(this, objPrototype);
        return SetPrototypeEntries(obj[setlikeInner]);
      },
    },
    keys: {
      __proto__: null,
      configurable: true,
      enumerable: true,
      writable: true,
      value() {
        assertBranded(this, objPrototype);
        return SetPrototypeKeys(obj[setlikeInner]);
      },
    },
    values: {
      __proto__: null,
      configurable: true,
      enumerable: true,
      writable: true,
      value() {
        assertBranded(this, objPrototype);
        return SetPrototypeValues(obj[setlikeInner]);
      },
    },
    forEach: {
      __proto__: null,
      configurable: true,
      enumerable: true,
      writable: true,
      value(callbackfn, thisArg) {
        assertBranded(this, objPrototype);
        return SetPrototypeForEach(obj[setlikeInner], callbackfn, thisArg);
      },
    },
    has: {
      __proto__: null,
      configurable: true,
      enumerable: true,
      writable: true,
      value(value) {
        assertBranded(this, objPrototype);
        return SetPrototypeHas(obj[setlikeInner], value);
      },
    },
  });

  if (!readonly) {
    ObjectDefineProperties(obj, {
      add: {
        __proto__: null,
        configurable: true,
        enumerable: true,
        writable: true,
        value(value) {
          assertBranded(this, objPrototype);
          return SetPrototypeAdd(obj[setlikeInner], value);
        },
      },
      delete: {
        __proto__: null,
        configurable: true,
        enumerable: true,
        writable: true,
        value(value) {
          assertBranded(this, objPrototype);
          return SetPrototypeDelete(obj[setlikeInner], value);
        },
      },
      clear: {
        __proto__: null,
        configurable: true,
        enumerable: true,
        writable: true,
        value() {
          assertBranded(this, objPrototype);
          return SetPrototypeClear(obj[setlikeInner]);
        },
      },
    });
  }
}

export {
  assertBranded,
  AsyncIterable,
  brand,
  configureInterface,
  converters,
  createAsyncIterableConverter,
  createBranded,
  createDictionaryConverter,
  createEnumConverter,
  createInterfaceConverter,
  createNullableConverter,
  createPromiseConverter,
  createRecordConverter,
  createSequenceConverter,
  illegalConstructor,
  invokeCallbackFunction,
  isAsyncIterable,
  makeException,
  mixinPairIterable,
  requiredArguments,
  setlike,
  setlikeInner,
  type,
};