-
Notifications
You must be signed in to change notification settings - Fork 86
/
idl.ts
1813 lines (1582 loc) · 46.9 KB
/
idl.ts
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
// tslint:disable:max-classes-per-file
import { Principal as PrincipalId } from '@dfinity/principal';
import { JsonValue } from './types';
import { concat, PipeArrayBuffer as Pipe } from './utils/buffer';
import { idlLabelToId } from './utils/hash';
import {
lebDecode,
lebEncode,
readIntLE,
readUIntLE,
safeRead,
safeReadUint8,
slebDecode,
slebEncode,
writeIntLE,
writeUIntLE,
} from './utils/leb128';
// tslint:disable:max-line-length
/**
* This module provides a combinator library to create serializers/deserializers
* between JavaScript values and IDL used by canisters on the Internet Computer,
* as documented at https://github.com/dfinity/candid/blob/119703ba342d2fef6ab4972d2541b9fe36ae8e36/spec/Candid.md
*/
// tslint:enable:max-line-length
const enum IDLTypeIds {
Null = -1,
Bool = -2,
Nat = -3,
Int = -4,
Float32 = -13,
Float64 = -14,
Text = -15,
Reserved = -16,
Empty = -17,
Opt = -18,
Vector = -19,
Record = -20,
Variant = -21,
Func = -22,
Service = -23,
Principal = -24,
}
const magicNumber = 'DIDL';
function zipWith<TX, TY, TR>(xs: TX[], ys: TY[], f: (a: TX, b: TY) => TR): TR[] {
return xs.map((x, i) => f(x, ys[i]));
}
/**
* An IDL Type Table, which precedes the data in the stream.
*/
class TypeTable {
// List of types. Needs to be an array as the index needs to be stable.
private _typs: ArrayBuffer[] = [];
private _idx = new Map<string, number>();
public has(obj: ConstructType) {
return this._idx.has(obj.name);
}
public add<T>(type: ConstructType<T>, buf: ArrayBuffer) {
const idx = this._typs.length;
this._idx.set(type.name, idx);
this._typs.push(buf);
}
public merge<T>(obj: ConstructType<T>, knot: string) {
const idx = this._idx.get(obj.name);
const knotIdx = this._idx.get(knot);
if (idx === undefined) {
throw new Error('Missing type index for ' + obj);
}
if (knotIdx === undefined) {
throw new Error('Missing type index for ' + knot);
}
this._typs[idx] = this._typs[knotIdx];
// Delete the type.
this._typs.splice(knotIdx, 1);
this._idx.delete(knot);
}
public encode() {
const len = lebEncode(this._typs.length);
const buf = concat(...this._typs);
return concat(len, buf);
}
public indexOf(typeName: string) {
if (!this._idx.has(typeName)) {
throw new Error('Missing type index for ' + typeName);
}
return slebEncode(this._idx.get(typeName) || 0);
}
}
export abstract class Visitor<D, R> {
public visitType<T>(t: Type<T>, data: D): R {
throw new Error('Not implemented');
}
public visitPrimitive<T>(t: PrimitiveType<T>, data: D): R {
return this.visitType(t, data);
}
public visitEmpty(t: EmptyClass, data: D): R {
return this.visitPrimitive(t, data);
}
public visitBool(t: BoolClass, data: D): R {
return this.visitPrimitive(t, data);
}
public visitNull(t: NullClass, data: D): R {
return this.visitPrimitive(t, data);
}
public visitReserved(t: ReservedClass, data: D): R {
return this.visitPrimitive(t, data);
}
public visitText(t: TextClass, data: D): R {
return this.visitPrimitive(t, data);
}
public visitNumber<T>(t: PrimitiveType<T>, data: D): R {
return this.visitPrimitive(t, data);
}
public visitInt(t: IntClass, data: D): R {
return this.visitNumber(t, data);
}
public visitNat(t: NatClass, data: D): R {
return this.visitNumber(t, data);
}
public visitFloat(t: FloatClass, data: D): R {
return this.visitPrimitive(t, data);
}
public visitFixedInt(t: FixedIntClass, data: D): R {
return this.visitNumber(t, data);
}
public visitFixedNat(t: FixedNatClass, data: D): R {
return this.visitNumber(t, data);
}
public visitPrincipal(t: PrincipalClass, data: D): R {
return this.visitPrimitive(t, data);
}
public visitConstruct<T>(t: ConstructType<T>, data: D): R {
return this.visitType(t, data);
}
public visitVec<T>(t: VecClass<T>, ty: Type<T>, data: D): R {
return this.visitConstruct(t, data);
}
public visitOpt<T>(t: OptClass<T>, ty: Type<T>, data: D): R {
return this.visitConstruct(t, data);
}
public visitRecord(t: RecordClass, fields: Array<[string, Type]>, data: D): R {
return this.visitConstruct(t, data);
}
public visitTuple<T extends any[]>(t: TupleClass<T>, components: Type[], data: D): R {
const fields: Array<[string, Type]> = components.map((ty, i) => [`_${i}_`, ty]);
return this.visitRecord(t, fields, data);
}
public visitVariant(t: VariantClass, fields: Array<[string, Type]>, data: D): R {
return this.visitConstruct(t, data);
}
public visitRec<T>(t: RecClass<T>, ty: ConstructType<T>, data: D): R {
return this.visitConstruct(ty, data);
}
public visitFunc(t: FuncClass, data: D): R {
return this.visitConstruct(t, data);
}
public visitService(t: ServiceClass, data: D): R {
return this.visitConstruct(t, data);
}
}
/**
* Represents an IDL type.
*/
export abstract class Type<T = any> {
public abstract readonly name: string;
public abstract accept<D, R>(v: Visitor<D, R>, d: D): R;
/* Display type name */
public display(): string {
return this.name;
}
public valueToString(x: T): string {
return toReadableString(x);
}
/* Implement `T` in the IDL spec, only needed for non-primitive types */
public buildTypeTable(typeTable: TypeTable): void {
if (!typeTable.has(this)) {
this._buildTypeTableImpl(typeTable);
}
}
/**
* Assert that JavaScript's `x` is the proper type represented by this
* Type.
*/
public abstract covariant(x: any): x is T;
/**
* Encode the value. This needs to be public because it is used by
* encodeValue() from different types.
* @internal
*/
public abstract encodeValue(x: T): ArrayBuffer;
/**
* Implement `I` in the IDL spec.
* Encode this type for the type table.
*/
public abstract encodeType(typeTable: TypeTable): ArrayBuffer;
public abstract checkType(t: Type): Type;
public abstract decodeValue(x: Pipe, t: Type): T;
protected abstract _buildTypeTableImpl(typeTable: TypeTable): void;
}
export abstract class PrimitiveType<T = any> extends Type<T> {
public checkType(t: Type): Type {
if (this.name !== t.name) {
throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);
}
return t;
}
public _buildTypeTableImpl(typeTable: TypeTable): void {
// No type table encoding for Primitive types.
return;
}
}
export abstract class ConstructType<T = any> extends Type<T> {
public checkType(t: Type): ConstructType<T> {
if (t instanceof RecClass) {
const ty = t.getType();
if (typeof ty === 'undefined') {
throw new Error('type mismatch with uninitialized type');
}
return ty;
}
throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);
}
public encodeType(typeTable: TypeTable) {
return typeTable.indexOf(this.name);
}
}
/**
* Represents an IDL Empty, a type which has no inhabitants.
* Since no values exist for this type, it cannot be serialised or deserialised.
* Result types like `Result<Text, Empty>` should always succeed.
*/
export class EmptyClass extends PrimitiveType<never> {
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitEmpty(this, d);
}
public covariant(x: any): x is never {
return false;
}
public encodeValue(): never {
throw new Error('Empty cannot appear as a function argument');
}
public valueToString(): never {
throw new Error('Empty cannot appear as a value');
}
public encodeType() {
return slebEncode(IDLTypeIds.Empty);
}
public decodeValue(): never {
throw new Error('Empty cannot appear as an output');
}
get name() {
return 'empty';
}
}
/**
* Represents an IDL Unknown, a placeholder type for deserialization only.
* When decoding a value as Unknown, all fields will be retained but the names are only available in
* hashed form.
* A deserialized unknown will offer it's actual type by calling the `type()` function.
* Unknown cannot be serialized and attempting to do so will throw an error.
*/
export class UnknownClass extends Type {
public checkType(t: Type): Type {
throw new Error('Method not implemented for unknown.');
}
public accept<D, R>(v: Visitor<D, R>, d: D): R {
throw v.visitType(this, d);
}
public covariant(x: any): x is any {
return false;
}
public encodeValue(): never {
throw new Error('Unknown cannot appear as a function argument');
}
public valueToString(): never {
throw new Error('Unknown cannot appear as a value');
}
public encodeType(): never {
throw new Error('Unknown cannot be serialized');
}
public decodeValue(b: Pipe, t: Type): any {
let decodedValue = t.decodeValue(b, t);
if (Object(decodedValue) !== decodedValue) {
// decodedValue is primitive. Box it, otherwise we cannot add the type() function.
// The type() function is important for primitives because otherwise we cannot tell apart the
// different number types.
decodedValue = Object(decodedValue);
}
let typeFunc;
if (t instanceof RecClass) {
typeFunc = () => t.getType();
} else {
typeFunc = () => t;
}
// Do not use 'decodedValue.type = typeFunc' because this would lead to an enumerable property
// 'type' which means it would be serialized if the value would be candid encoded again.
// This in turn leads to problems if the decoded value is a variant because these values are
// only allowed to have a single property.
Object.defineProperty(decodedValue, 'type', {
value: typeFunc,
writable: true,
enumerable: false,
configurable: true,
});
return decodedValue;
}
protected _buildTypeTableImpl(): void {
throw new Error('Unknown cannot be serialized');
}
get name() {
return 'Unknown';
}
}
/**
* Represents an IDL Bool
*/
export class BoolClass extends PrimitiveType<boolean> {
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitBool(this, d);
}
public covariant(x: any): x is boolean {
return typeof x === 'boolean';
}
public encodeValue(x: boolean): ArrayBuffer {
return new Uint8Array([x ? 1 : 0]);
}
public encodeType() {
return slebEncode(IDLTypeIds.Bool);
}
public decodeValue(b: Pipe, t: Type) {
this.checkType(t);
switch (safeReadUint8(b)) {
case 0:
return false;
case 1:
return true;
default:
throw new Error('Boolean value out of range');
}
}
get name() {
return 'bool';
}
}
/**
* Represents an IDL Null
*/
export class NullClass extends PrimitiveType<null> {
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitNull(this, d);
}
public covariant(x: any): x is null {
return x === null;
}
public encodeValue() {
return new ArrayBuffer(0);
}
public encodeType() {
return slebEncode(IDLTypeIds.Null);
}
public decodeValue(b: Pipe, t: Type) {
this.checkType(t);
return null;
}
get name() {
return 'null';
}
}
/**
* Represents an IDL Reserved
*/
export class ReservedClass extends PrimitiveType<any> {
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitReserved(this, d);
}
public covariant(x: any): x is any {
return true;
}
public encodeValue() {
return new ArrayBuffer(0);
}
public encodeType() {
return slebEncode(IDLTypeIds.Reserved);
}
public decodeValue(b: Pipe, t: Type) {
if (t.name !== this.name) {
t.decodeValue(b, t);
}
return null;
}
get name() {
return 'reserved';
}
}
/**
* Represents an IDL Text
*/
export class TextClass extends PrimitiveType<string> {
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitText(this, d);
}
public covariant(x: any): x is string {
return typeof x === 'string';
}
public encodeValue(x: string) {
const buf = new TextEncoder().encode(x);
const len = lebEncode(buf.byteLength);
return concat(len, buf);
}
public encodeType() {
return slebEncode(IDLTypeIds.Text);
}
public decodeValue(b: Pipe, t: Type) {
this.checkType(t);
const len = lebDecode(b);
const buf = safeRead(b, Number(len));
const decoder = new TextDecoder('utf8', { fatal: true });
return decoder.decode(buf);
}
get name() {
return 'text';
}
public valueToString(x: string) {
return '"' + x + '"';
}
}
/**
* Represents an IDL Int
*/
export class IntClass extends PrimitiveType<bigint> {
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitInt(this, d);
}
public covariant(x: any): x is bigint {
// We allow encoding of JavaScript plain numbers.
// But we will always decode to bigint.
return typeof x === 'bigint' || Number.isInteger(x);
}
public encodeValue(x: bigint | number) {
return slebEncode(x);
}
public encodeType() {
return slebEncode(IDLTypeIds.Int);
}
public decodeValue(b: Pipe, t: Type) {
this.checkType(t);
return slebDecode(b);
}
get name() {
return 'int';
}
public valueToString(x: bigint) {
return x.toString();
}
}
/**
* Represents an IDL Nat
*/
export class NatClass extends PrimitiveType<bigint> {
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitNat(this, d);
}
public covariant(x: any): x is bigint {
// We allow encoding of JavaScript plain numbers.
// But we will always decode to bigint.
return (typeof x === 'bigint' && x >= BigInt(0)) || (Number.isInteger(x) && x >= 0);
}
public encodeValue(x: bigint | number) {
return lebEncode(x);
}
public encodeType() {
return slebEncode(IDLTypeIds.Nat);
}
public decodeValue(b: Pipe, t: Type) {
this.checkType(t);
return lebDecode(b);
}
get name() {
return 'nat';
}
public valueToString(x: bigint) {
return x.toString();
}
}
/**
* Represents an IDL Float
*/
export class FloatClass extends PrimitiveType<number> {
constructor(private _bits: number) {
super();
if (_bits !== 32 && _bits !== 64) {
throw new Error('not a valid float type');
}
}
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitFloat(this, d);
}
public covariant(x: any): x is number {
return typeof x === 'number' || x instanceof Number;
}
public encodeValue(x: number) {
const buf = new ArrayBuffer(this._bits / 8);
const view = new DataView(buf);
if (this._bits === 32) {
view.setFloat32(0, x, true);
} else {
view.setFloat64(0, x, true);
}
return buf;
}
public encodeType() {
const opcode = this._bits === 32 ? IDLTypeIds.Float32 : IDLTypeIds.Float64;
return slebEncode(opcode);
}
public decodeValue(b: Pipe, t: Type) {
this.checkType(t);
const bytes = safeRead(b, this._bits / 8);
const view = new DataView(bytes);
if (this._bits === 32) {
return view.getFloat32(0, true);
} else {
return view.getFloat64(0, true);
}
}
get name() {
return 'float' + this._bits;
}
public valueToString(x: number) {
return x.toString();
}
}
/**
* Represents an IDL fixed-width Int(n)
*/
export class FixedIntClass extends PrimitiveType<bigint | number> {
constructor(private _bits: number) {
super();
}
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitFixedInt(this, d);
}
public covariant(x: any): x is bigint {
const min = BigInt(2) ** BigInt(this._bits - 1) * BigInt(-1);
const max = BigInt(2) ** BigInt(this._bits - 1) - BigInt(1);
if (typeof x === 'bigint') {
return x >= min && x <= max;
} else if (Number.isInteger(x)) {
const v = BigInt(x);
return v >= min && v <= max;
} else {
return false;
}
}
public encodeValue(x: bigint | number) {
return writeIntLE(x, this._bits / 8);
}
public encodeType() {
const offset = Math.log2(this._bits) - 3;
return slebEncode(-9 - offset);
}
public decodeValue(b: Pipe, t: Type) {
this.checkType(t);
const num = readIntLE(b, this._bits / 8);
if (this._bits <= 32) {
return Number(num);
} else {
return num;
}
}
get name() {
return `int${this._bits}`;
}
public valueToString(x: bigint | number) {
return x.toString();
}
}
/**
* Represents an IDL fixed-width Nat(n)
*/
export class FixedNatClass extends PrimitiveType<bigint | number> {
constructor(public readonly bits: number) {
super();
}
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitFixedNat(this, d);
}
public covariant(x: any): x is bigint {
const max = BigInt(2) ** BigInt(this.bits);
if (typeof x === 'bigint' && x >= BigInt(0)) {
return x < max;
} else if (Number.isInteger(x) && x >= 0) {
const v = BigInt(x);
return v < max;
} else {
return false;
}
}
public encodeValue(x: bigint | number) {
return writeUIntLE(x, this.bits / 8);
}
public encodeType() {
const offset = Math.log2(this.bits) - 3;
return slebEncode(-5 - offset);
}
public decodeValue(b: Pipe, t: Type) {
this.checkType(t);
const num = readUIntLE(b, this.bits / 8);
if (this.bits <= 32) {
return Number(num);
} else {
return num;
}
}
get name() {
return `nat${this.bits}`;
}
public valueToString(x: bigint | number) {
return x.toString();
}
}
/**
* Represents an IDL Array
* @param {Type} t
*/
export class VecClass<T> extends ConstructType<T[]> {
// If true, this vector is really a blob and we can just use memcpy.
private _blobOptimization = false;
constructor(protected _type: Type<T>) {
super();
if (_type instanceof FixedNatClass && _type.bits === 8) {
this._blobOptimization = true;
}
}
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitVec(this, this._type, d);
}
public covariant(x: any): x is T[] {
return Array.isArray(x) && x.every(v => this._type.covariant(v));
}
public encodeValue(x: T[]) {
const len = lebEncode(x.length);
if (this._blobOptimization) {
return concat(len, new Uint8Array(x as unknown as number[]));
}
const buf = new Pipe(new ArrayBuffer(len.byteLength + x.length), 0);
buf.write(len);
for (const d of x) {
const encoded = this._type.encodeValue(d);
buf.write(new Uint8Array(encoded));
}
return buf.buffer;
}
public _buildTypeTableImpl(typeTable: TypeTable) {
this._type.buildTypeTable(typeTable);
const opCode = slebEncode(IDLTypeIds.Vector);
const buffer = this._type.encodeType(typeTable);
typeTable.add(this, concat(opCode, buffer));
}
public decodeValue(b: Pipe, t: Type): T[] {
const vec = this.checkType(t);
if (!(vec instanceof VecClass)) {
throw new Error('Not a vector type');
}
const len = Number(lebDecode(b));
if (this._blobOptimization) {
return [...new Uint8Array(b.read(len))] as unknown as T[];
}
const rets: T[] = [];
for (let i = 0; i < len; i++) {
rets.push(this._type.decodeValue(b, vec._type));
}
return rets;
}
get name() {
return `vec ${this._type.name}`;
}
public display() {
return `vec ${this._type.display()}`;
}
public valueToString(x: T[]) {
const elements = x.map(e => this._type.valueToString(e));
return 'vec {' + elements.join('; ') + '}';
}
}
/**
* Represents an IDL Option
* @param {Type} t
*/
export class OptClass<T> extends ConstructType<[T] | []> {
constructor(protected _type: Type<T>) {
super();
}
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitOpt(this, this._type, d);
}
public covariant(x: any): x is [T] | [] {
return Array.isArray(x) && (x.length === 0 || (x.length === 1 && this._type.covariant(x[0])));
}
public encodeValue(x: [T] | []) {
if (x.length === 0) {
return new Uint8Array([0]);
} else {
return concat(new Uint8Array([1]), this._type.encodeValue(x[0]));
}
}
public _buildTypeTableImpl(typeTable: TypeTable) {
this._type.buildTypeTable(typeTable);
const opCode = slebEncode(IDLTypeIds.Opt);
const buffer = this._type.encodeType(typeTable);
typeTable.add(this, concat(opCode, buffer));
}
public decodeValue(b: Pipe, t: Type): [T] | [] {
const opt = this.checkType(t);
if (!(opt instanceof OptClass)) {
throw new Error('Not an option type');
}
switch (safeReadUint8(b)) {
case 0:
return [];
case 1:
return [this._type.decodeValue(b, opt._type)];
default:
throw new Error('Not an option value');
}
}
get name() {
return `opt ${this._type.name}`;
}
public display() {
return `opt ${this._type.display()}`;
}
public valueToString(x: [T] | []) {
if (x.length === 0) {
return 'null';
} else {
return `opt ${this._type.valueToString(x[0])}`;
}
}
}
/**
* Represents an IDL Record
* @param {Object} [fields] - mapping of function name to Type
*/
export class RecordClass extends ConstructType<Record<string, any>> {
protected readonly _fields: Array<[string, Type]>;
constructor(fields: Record<string, Type> = {}) {
super();
this._fields = Object.entries(fields).sort((a, b) => idlLabelToId(a[0]) - idlLabelToId(b[0]));
}
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitRecord(this, this._fields, d);
}
public tryAsTuple(): Type[] | null {
const res: Type[] = [];
for (let i = 0; i < this._fields.length; i++) {
const [key, type] = this._fields[i];
if (key !== `_${i}_`) {
return null;
}
res.push(type);
}
return res;
}
public covariant(x: any): x is Record<string, any> {
return (
typeof x === 'object' &&
this._fields.every(([k, t]) => {
// eslint-disable-next-line
if (!x.hasOwnProperty(k)) {
throw new Error(`Record is missing key "${k}".`);
}
return t.covariant(x[k]);
})
);
}
public encodeValue(x: Record<string, any>) {
const values = this._fields.map(([key]) => x[key]);
const bufs = zipWith(this._fields, values, ([, c], d) => c.encodeValue(d));
return concat(...bufs);
}
public _buildTypeTableImpl(T: TypeTable) {
this._fields.forEach(([_, value]) => value.buildTypeTable(T));
const opCode = slebEncode(IDLTypeIds.Record);
const len = lebEncode(this._fields.length);
const fields = this._fields.map(([key, value]) =>
concat(lebEncode(idlLabelToId(key)), value.encodeType(T)),
);
T.add(this, concat(opCode, len, concat(...fields)));
}
public decodeValue(b: Pipe, t: Type) {
const record = this.checkType(t);
if (!(record instanceof RecordClass)) {
throw new Error('Not a record type');
}
const x: Record<string, any> = {};
let idx = 0;
for (const [hash, type] of record._fields) {
if (idx >= this._fields.length || idlLabelToId(this._fields[idx][0]) !== idlLabelToId(hash)) {
// skip field
type.decodeValue(b, type);
continue;
}
const [expectKey, expectType] = this._fields[idx];
x[expectKey] = expectType.decodeValue(b, type);
idx++;
}
for (const [expectKey, expectType] of this._fields.slice(idx)) {
if (expectType instanceof OptClass || expectType instanceof ReservedClass) {
// TODO this assumes null value in opt is represented as []
x[expectKey] = [];
} else {
throw new Error('Cannot find required field ' + expectKey);
}
}
return x;
}
get name() {
const fields = this._fields.map(([key, value]) => key + ':' + value.name);
return `record {${fields.join('; ')}}`;
}
public display() {
const fields = this._fields.map(([key, value]) => key + ':' + value.display());
return `record {${fields.join('; ')}}`;
}
public valueToString(x: Record<string, any>) {
const values = this._fields.map(([key]) => x[key]);
const fields = zipWith(this._fields, values, ([k, c], d) => k + '=' + c.valueToString(d));
return `record {${fields.join('; ')}}`;
}
}
/**
* Represents Tuple, a syntactic sugar for Record.
* @param {Type} components
*/
export class TupleClass<T extends any[]> extends RecordClass {
protected readonly _components: Type[];
constructor(_components: Type[]) {
const x: Record<string, any> = {};
_components.forEach((e, i) => (x['_' + i + '_'] = e));
super(x);
this._components = _components;
}
public accept<D, R>(v: Visitor<D, R>, d: D): R {
return v.visitTuple(this, this._components, d);
}
public covariant(x: any): x is T {
// `>=` because tuples can be covariant when encoded.
return (
Array.isArray(x) &&
x.length >= this._fields.length &&
this._components.every((t, i) => t.covariant(x[i]))
);
}
public encodeValue(x: any[]) {
const bufs = zipWith(this._components, x, (c, d) => c.encodeValue(d));
return concat(...bufs);
}