forked from MetaMask/metamask-mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ses.cjs
11994 lines (9988 loc) · 403 KB
/
ses.cjs
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
'use strict';
(() => {
const functors = [
// === functors[0] ===
({ imports: $h_imports, liveVar: $h_live, onceVar: $h_once, importMeta: $h____meta, }) => (function () { 'use strict'; $h_imports([]); /* global globalThis */
/* eslint-disable no-restricted-globals */
/**
* commons.js
* Declare shorthand functions. Sharing these declarations across modules
* improves on consistency and minification. Unused declarations are
* dropped by the tree shaking process.
*
* We capture these, not just for brevity, but for security. If any code
* modifies Object to change what 'assign' points to, the Compartment shim
* would be corrupted.
*/
// We cannot use globalThis as the local name since it would capture the
// lexical name.
const universalThis= globalThis;$h_once.universalThis(universalThis);
const {
Array,
Date,
FinalizationRegistry,
Float32Array,
JSON,
Map,
Math,
Number,
Object,
Promise,
Proxy,
Reflect,
RegExp: FERAL_REG_EXP,
Set,
String,
Symbol,
WeakMap,
WeakSet}=
globalThis;$h_once.Array(Array);$h_once.Date(Date);$h_once.FinalizationRegistry(FinalizationRegistry);$h_once.Float32Array(Float32Array);$h_once.JSON(JSON);$h_once.Map(Map);$h_once.Math(Math);$h_once.Number(Number);$h_once.Object(Object);$h_once.Promise(Promise);$h_once.Proxy(Proxy);$h_once.Reflect(Reflect);$h_once.FERAL_REG_EXP(FERAL_REG_EXP);$h_once.Set(Set);$h_once.String(String);$h_once.Symbol(Symbol);$h_once.WeakMap(WeakMap);$h_once.WeakSet(WeakSet);
const {
// The feral Error constructor is safe for internal use, but must not be
// revealed to post-lockdown code in any compartment including the start
// compartment since in V8 at least it bears stack inspection capabilities.
Error: FERAL_ERROR,
RangeError,
ReferenceError,
SyntaxError,
TypeError,
AggregateError}=
globalThis;$h_once.FERAL_ERROR(FERAL_ERROR);$h_once.RangeError(RangeError);$h_once.ReferenceError(ReferenceError);$h_once.SyntaxError(SyntaxError);$h_once.TypeError(TypeError);$h_once.AggregateError(AggregateError);
const {
assign,
create,
defineProperties,
entries,
freeze,
getOwnPropertyDescriptor,
getOwnPropertyDescriptors,
getOwnPropertyNames,
getPrototypeOf,
is,
isFrozen,
isSealed,
isExtensible,
keys,
prototype: objectPrototype,
seal,
preventExtensions,
setPrototypeOf,
values,
fromEntries}=
Object;$h_once.assign(assign);$h_once.create(create);$h_once.defineProperties(defineProperties);$h_once.entries(entries);$h_once.freeze(freeze);$h_once.getOwnPropertyDescriptor(getOwnPropertyDescriptor);$h_once.getOwnPropertyDescriptors(getOwnPropertyDescriptors);$h_once.getOwnPropertyNames(getOwnPropertyNames);$h_once.getPrototypeOf(getPrototypeOf);$h_once.is(is);$h_once.isFrozen(isFrozen);$h_once.isSealed(isSealed);$h_once.isExtensible(isExtensible);$h_once.keys(keys);$h_once.objectPrototype(objectPrototype);$h_once.seal(seal);$h_once.preventExtensions(preventExtensions);$h_once.setPrototypeOf(setPrototypeOf);$h_once.values(values);$h_once.fromEntries(fromEntries);
const {
species: speciesSymbol,
toStringTag: toStringTagSymbol,
iterator: iteratorSymbol,
matchAll: matchAllSymbol,
unscopables: unscopablesSymbol,
keyFor: symbolKeyFor,
for: symbolFor}=
Symbol;$h_once.speciesSymbol(speciesSymbol);$h_once.toStringTagSymbol(toStringTagSymbol);$h_once.iteratorSymbol(iteratorSymbol);$h_once.matchAllSymbol(matchAllSymbol);$h_once.unscopablesSymbol(unscopablesSymbol);$h_once.symbolKeyFor(symbolKeyFor);$h_once.symbolFor(symbolFor);
const { isInteger}= Number;$h_once.isInteger(isInteger);
const { stringify: stringifyJson}= JSON;
// Needed only for the Safari bug workaround below
$h_once.stringifyJson(stringifyJson);const{defineProperty:originalDefineProperty}=Object;
const defineProperty= (object, prop, descriptor)=> {
// We used to do the following, until we had to reopen Safari bug
// https://bugs.webkit.org/show_bug.cgi?id=222538#c17
// Once this is fixed, we may restore it.
// // Object.defineProperty is allowed to fail silently so we use
// // Object.defineProperties instead.
// return defineProperties(object, { [prop]: descriptor });
// Instead, to workaround the Safari bug
const result= originalDefineProperty(object, prop, descriptor);
if( result!== object) {
// See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_DEFINE_PROPERTY_FAILED_SILENTLY.md
throw TypeError(
`Please report that the original defineProperty silently failed to set ${stringifyJson(
String(prop))
}. (SES_DEFINE_PROPERTY_FAILED_SILENTLY)`);
}
return result;
};$h_once.defineProperty(defineProperty);
const {
apply,
construct,
get: reflectGet,
getOwnPropertyDescriptor: reflectGetOwnPropertyDescriptor,
has: reflectHas,
isExtensible: reflectIsExtensible,
ownKeys,
preventExtensions: reflectPreventExtensions,
set: reflectSet}=
Reflect;$h_once.apply(apply);$h_once.construct(construct);$h_once.reflectGet(reflectGet);$h_once.reflectGetOwnPropertyDescriptor(reflectGetOwnPropertyDescriptor);$h_once.reflectHas(reflectHas);$h_once.reflectIsExtensible(reflectIsExtensible);$h_once.ownKeys(ownKeys);$h_once.reflectPreventExtensions(reflectPreventExtensions);$h_once.reflectSet(reflectSet);
const { isArray, prototype: arrayPrototype}= Array;$h_once.isArray(isArray);$h_once.arrayPrototype(arrayPrototype);
const { prototype: mapPrototype}= Map;$h_once.mapPrototype(mapPrototype);
const { revocable: proxyRevocable}= Proxy;$h_once.proxyRevocable(proxyRevocable);
const { prototype: regexpPrototype}= RegExp;$h_once.regexpPrototype(regexpPrototype);
const { prototype: setPrototype}= Set;$h_once.setPrototype(setPrototype);
const { prototype: stringPrototype}= String;$h_once.stringPrototype(stringPrototype);
const { prototype: weakmapPrototype}= WeakMap;$h_once.weakmapPrototype(weakmapPrototype);
const { prototype: weaksetPrototype}= WeakSet;$h_once.weaksetPrototype(weaksetPrototype);
const { prototype: functionPrototype}= Function;$h_once.functionPrototype(functionPrototype);
const { prototype: promisePrototype}= Promise;$h_once.promisePrototype(promisePrototype);
const { prototype: generatorPrototype}= getPrototypeOf(
// eslint-disable-next-line no-empty-function, func-names
function*() { });$h_once.generatorPrototype(generatorPrototype);
const typedArrayPrototype= getPrototypeOf(Uint8Array.prototype);$h_once.typedArrayPrototype(typedArrayPrototype);
const { bind}= functionPrototype;
/**
* uncurryThis()
* Equivalent of: fn => (thisArg, ...args) => apply(fn, thisArg, args)
*
* See those reference for a complete explanation:
* http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming
* which only lives at
* http://web.archive.org/web/20160805225710/http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming
*
* @type {<F extends (this: any, ...args: any[]) => any>(fn: F) => ((thisArg: ThisParameterType<F>, ...args: Parameters<F>) => ReturnType<F>)}
*/
const uncurryThis= bind.bind(bind.call); // eslint-disable-line @endo/no-polymorphic-call
$h_once.uncurryThis(uncurryThis);
const objectHasOwnProperty= uncurryThis(objectPrototype.hasOwnProperty);
//
$h_once.objectHasOwnProperty(objectHasOwnProperty);const arrayFilter=uncurryThis(arrayPrototype.filter);$h_once.arrayFilter(arrayFilter);
const arrayForEach= uncurryThis(arrayPrototype.forEach);$h_once.arrayForEach(arrayForEach);
const arrayIncludes= uncurryThis(arrayPrototype.includes);$h_once.arrayIncludes(arrayIncludes);
const arrayJoin= uncurryThis(arrayPrototype.join);
/** @type {<T, U>(thisArg: readonly T[], callbackfn: (value: T, index: number, array: T[]) => U, cbThisArg?: any) => U[]} */$h_once.arrayJoin(arrayJoin);
const arrayMap= /** @type {any} */ uncurryThis(arrayPrototype.map);$h_once.arrayMap(arrayMap);
const arrayFlatMap= /** @type {any} */
uncurryThis(arrayPrototype.flatMap);$h_once.arrayFlatMap(arrayFlatMap);
const arrayPop= uncurryThis(arrayPrototype.pop);
/** @type {<T>(thisArg: T[], ...items: T[]) => number} */$h_once.arrayPop(arrayPop);
const arrayPush= uncurryThis(arrayPrototype.push);$h_once.arrayPush(arrayPush);
const arraySlice= uncurryThis(arrayPrototype.slice);$h_once.arraySlice(arraySlice);
const arraySome= uncurryThis(arrayPrototype.some);$h_once.arraySome(arraySome);
const arraySort= uncurryThis(arrayPrototype.sort);$h_once.arraySort(arraySort);
const iterateArray= uncurryThis(arrayPrototype[iteratorSymbol]);
//
$h_once.iterateArray(iterateArray);const mapSet=uncurryThis(mapPrototype.set);$h_once.mapSet(mapSet);
const mapGet= uncurryThis(mapPrototype.get);$h_once.mapGet(mapGet);
const mapHas= uncurryThis(mapPrototype.has);$h_once.mapHas(mapHas);
const mapDelete= uncurryThis(mapPrototype.delete);$h_once.mapDelete(mapDelete);
const mapEntries= uncurryThis(mapPrototype.entries);$h_once.mapEntries(mapEntries);
const iterateMap= uncurryThis(mapPrototype[iteratorSymbol]);
//
$h_once.iterateMap(iterateMap);const setAdd=uncurryThis(setPrototype.add);$h_once.setAdd(setAdd);
const setDelete= uncurryThis(setPrototype.delete);$h_once.setDelete(setDelete);
const setForEach= uncurryThis(setPrototype.forEach);$h_once.setForEach(setForEach);
const setHas= uncurryThis(setPrototype.has);$h_once.setHas(setHas);
const iterateSet= uncurryThis(setPrototype[iteratorSymbol]);
//
$h_once.iterateSet(iterateSet);const regexpTest=uncurryThis(regexpPrototype.test);$h_once.regexpTest(regexpTest);
const regexpExec= uncurryThis(regexpPrototype.exec);$h_once.regexpExec(regexpExec);
const matchAllRegExp= uncurryThis(regexpPrototype[matchAllSymbol]);
//
$h_once.matchAllRegExp(matchAllRegExp);const stringEndsWith=uncurryThis(stringPrototype.endsWith);$h_once.stringEndsWith(stringEndsWith);
const stringIncludes= uncurryThis(stringPrototype.includes);$h_once.stringIncludes(stringIncludes);
const stringIndexOf= uncurryThis(stringPrototype.indexOf);$h_once.stringIndexOf(stringIndexOf);
const stringMatch= uncurryThis(stringPrototype.match);$h_once.stringMatch(stringMatch);
const generatorNext= uncurryThis(generatorPrototype.next);$h_once.generatorNext(generatorNext);
const generatorThrow= uncurryThis(generatorPrototype.throw);
/**
* @type { &
* ((thisArg: string, searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string) => string) &
* ((thisArg: string, searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string) => string)
* }
*/$h_once.generatorThrow(generatorThrow);
const stringReplace= /** @type {any} */
uncurryThis(stringPrototype.replace);$h_once.stringReplace(stringReplace);
const stringSearch= uncurryThis(stringPrototype.search);$h_once.stringSearch(stringSearch);
const stringSlice= uncurryThis(stringPrototype.slice);
/** @type {(thisArg: string, splitter: string | RegExp | { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number) => string[]} */$h_once.stringSlice(stringSlice);
const stringSplit= uncurryThis(stringPrototype.split);$h_once.stringSplit(stringSplit);
const stringStartsWith= uncurryThis(stringPrototype.startsWith);$h_once.stringStartsWith(stringStartsWith);
const iterateString= uncurryThis(stringPrototype[iteratorSymbol]);
//
$h_once.iterateString(iterateString);const weakmapDelete=uncurryThis(weakmapPrototype.delete);
/** @type {<K extends {}, V>(thisArg: WeakMap<K, V>, ...args: Parameters<WeakMap<K,V>['get']>) => ReturnType<WeakMap<K,V>['get']>} */$h_once.weakmapDelete(weakmapDelete);
const weakmapGet= uncurryThis(weakmapPrototype.get);$h_once.weakmapGet(weakmapGet);
const weakmapHas= uncurryThis(weakmapPrototype.has);$h_once.weakmapHas(weakmapHas);
const weakmapSet= uncurryThis(weakmapPrototype.set);
//
$h_once.weakmapSet(weakmapSet);const weaksetAdd=uncurryThis(weaksetPrototype.add);$h_once.weaksetAdd(weaksetAdd);
const weaksetHas= uncurryThis(weaksetPrototype.has);
//
$h_once.weaksetHas(weaksetHas);const functionToString=uncurryThis(functionPrototype.toString);$h_once.functionToString(functionToString);
const functionBind= uncurryThis(bind);
//
$h_once.functionBind(functionBind);const{all}=Promise;
const promiseAll= (promises)=>apply(all, Promise, [promises]);$h_once.promiseAll(promiseAll);
const promiseCatch= uncurryThis(promisePrototype.catch);
/** @type {<T, TResult1 = T, TResult2 = never>(thisArg: T, onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null) => Promise<TResult1 | TResult2>} */$h_once.promiseCatch(promiseCatch);
const promiseThen= /** @type {any} */
uncurryThis(promisePrototype.then);
//
$h_once.promiseThen(promiseThen);const finalizationRegistryRegister=
FinalizationRegistry&& uncurryThis(FinalizationRegistry.prototype.register);$h_once.finalizationRegistryRegister(finalizationRegistryRegister);
const finalizationRegistryUnregister=
FinalizationRegistry&&
uncurryThis(FinalizationRegistry.prototype.unregister);
/**
* getConstructorOf()
* Return the constructor from an instance.
*
* @param {Function} fn
*/$h_once.finalizationRegistryUnregister(finalizationRegistryUnregister);
const getConstructorOf= (fn)=>
reflectGet(getPrototypeOf(fn), 'constructor');
/**
* immutableObject
* An immutable (frozen) empty object that is safe to share.
*/$h_once.getConstructorOf(getConstructorOf);
const immutableObject= freeze(create(null));
/**
* isObject tests whether a value is an object.
* Today, this is equivalent to:
*
* const isObject = value => {
* if (value === null) return false;
* const type = typeof value;
* return type === 'object' || type === 'function';
* };
*
* But this is not safe in the face of possible evolution of the language, for
* example new types or semantics of records and tuples.
* We use this implementation despite the unnecessary allocation implied by
* attempting to box a primitive.
*
* @param {any} value
*/$h_once.immutableObject(immutableObject);
const isObject= (value)=>Object(value)=== value;
/**
* isError tests whether an object inherits from the intrinsic
* `Error.prototype`.
* We capture the original error constructor as FERAL_ERROR to provide a clear
* signal for reviewers that we are handling an object with excess authority,
* like stack trace inspection, that we are carefully hiding from client code.
* Checking instanceof happens to be safe, but to avoid uttering FERAL_ERROR
* for such a trivial case outside commons.js, we provide a utility function.
*
* @param {any} value
*/$h_once.isObject(isObject);
const isError= (value)=>value instanceof FERAL_ERROR;
// The original unsafe untamed eval function, which must not escape.
// Sample at module initialization time, which is before lockdown can
// repair it. Use it only to build powerless abstractions.
// eslint-disable-next-line no-eval
$h_once.isError(isError);const FERAL_EVAL=eval;
// The original unsafe untamed Function constructor, which must not escape.
// Sample at module initialization time, which is before lockdown can
// repair it. Use it only to build powerless abstractions.
$h_once.FERAL_EVAL(FERAL_EVAL);const FERAL_FUNCTION=Function;$h_once.FERAL_FUNCTION(FERAL_FUNCTION);
const noEvalEvaluate= ()=> {
// See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_NO_EVAL.md
throw TypeError('Cannot eval with evalTaming set to "noEval" (SES_NO_EVAL)');
};
// ////////////////// FERAL_STACK_GETTER FERAL_STACK_SETTER ////////////////////
$h_once.noEvalEvaluate(noEvalEvaluate);
const er1StackDesc= getOwnPropertyDescriptor(Error('er1'), 'stack');
const er2StackDesc= getOwnPropertyDescriptor(TypeError('er2'), 'stack');
let feralStackGetter;
let feralStackSetter;
if( er1StackDesc&& er2StackDesc&& er1StackDesc.get) {
// We should only encounter this case on v8 because of its problematic
// error own stack accessor behavior.
// Note that FF/SpiderMonkey, Moddable/XS, and the error stack proposal
// all inherit a stack accessor property from Error.prototype, which is
// great. That case needs no heroics to secure.
if(
// In the v8 case as we understand it, all errors have an own stack
// accessor property, but within the same realm, all these accessor
// properties have the same getter and have the same setter.
// This is therefore the case that we repair.
typeof er1StackDesc.get=== 'function'&&
er1StackDesc.get=== er2StackDesc.get&&
typeof er1StackDesc.set=== 'function'&&
er1StackDesc.set=== er2StackDesc.set)
{
// Otherwise, we have own stack accessor properties that are outside
// our expectations, that therefore need to be understood better
// before we know how to repair them.
feralStackGetter= freeze(er1StackDesc.get);
feralStackSetter= freeze(er1StackDesc.set);
}else {
// See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_UNEXPECTED_ERROR_OWN_STACK_ACCESSOR.md
throw TypeError(
'Unexpected Error own stack accessor functions (SES_UNEXPECTED_ERROR_OWN_STACK_ACCESSOR)');
}
}
/**
* If on a v8 with the problematic error own stack accessor behavior,
* `FERAL_STACK_GETTER` will be the shared getter of all those accessors
* and `FERAL_STACK_SETTER` will be the shared setter. On any platform
* without this problem, `FERAL_STACK_GETTER` and `FERAL_STACK_SETTER` are
* both `undefined`.
*
* @type {(() => any) | undefined}
*/
const FERAL_STACK_GETTER= feralStackGetter;
/**
* If on a v8 with the problematic error own stack accessor behavior,
* `FERAL_STACK_GETTER` will be the shared getter of all those accessors
* and `FERAL_STACK_SETTER` will be the shared setter. On any platform
* without this problem, `FERAL_STACK_GETTER` and `FERAL_STACK_SETTER` are
* both `undefined`.
*
* @type {((newValue: any) => void) | undefined}
*/$h_once.FERAL_STACK_GETTER(FERAL_STACK_GETTER);
const FERAL_STACK_SETTER= feralStackSetter;$h_once.FERAL_STACK_SETTER(FERAL_STACK_SETTER);
})()
,
// === functors[1] ===
({ imports: $h_imports, liveVar: $h_live, onceVar: $h_once, importMeta: $h____meta, }) => (function () { 'use strict'; let TypeError;$h_imports([["./commons.js", [["TypeError", [$h_a => (TypeError = $h_a)]]]]]);
/** getThis returns globalThis in sloppy mode or undefined in strict mode. */
function getThis() {
return this;
}
if( getThis()) {
// See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_NO_SLOPPY.md
throw TypeError( `SES failed to initialize, sloppy mode (SES_NO_SLOPPY)`);
}
})()
,
// === functors[2] ===
({ imports: $h_imports, liveVar: $h_live, onceVar: $h_once, importMeta: $h____meta, }) => (function () { 'use strict'; $h_imports([]); /* global globalThis */
// @ts-check
// `@endo/env-options` needs to be imported quite early, and so should
// avoid importing from ses or anything that depends on ses.
// /////////////////////////////////////////////////////////////////////////////
// Prelude of cheap good - enough imitations of things we'd use or
// do differently if we could depend on ses
const { freeze}= Object;
const { apply}= Reflect;
// Should be equivalent to the one in ses' commons.js even though it
// uses the other technique.
const uncurryThis=
(fn)=>
(receiver, ...args)=>
apply(fn, receiver, args);
const arrayPush= uncurryThis(Array.prototype.push);
const arrayIncludes= uncurryThis(Array.prototype.includes);
const stringSplit= uncurryThis(String.prototype.split);
const q= JSON.stringify;
const Fail= (literals, ...args)=> {
let msg= literals[0];
for( let i= 0; i< args.length; i+= 1) {
msg= `${msg}${args[i]}${literals[i+ 1] }`;
}
throw Error(msg);
};
// end prelude
// /////////////////////////////////////////////////////////////////////////////
/**
* `makeEnvironmentCaptor` provides a mechanism for getting environment
* variables, if they are needed, and a way to catalog the names of all
* the environment variables that were captured.
*
* @param {object} aGlobal
* @param {boolean} [dropNames] Defaults to false. If true, don't track
* names used.
*/
const makeEnvironmentCaptor= (aGlobal, dropNames= false)=> {
const capturedEnvironmentOptionNames= [];
/**
* Gets an environment option by name and returns the option value or the
* given default.
*
* @param {string} optionName
* @param {string} defaultSetting
* @param {string[]} [optOtherValues]
* If provided, the option value must be included or match `defaultSetting`.
* @returns {string}
*/
const getEnvironmentOption= (
optionName,
defaultSetting,
optOtherValues= undefined)=>
{
typeof optionName=== 'string'||
Fail `Environment option name ${q(optionName)} must be a string.`;
typeof defaultSetting=== 'string'||
Fail `Environment option default setting ${q(
defaultSetting)
} must be a string.`;
/** @type {string} */
let setting= defaultSetting;
const globalProcess= aGlobal.process|| undefined;
const globalEnv=
typeof globalProcess=== 'object'&& globalProcess.env|| undefined;
if( typeof globalEnv=== 'object') {
if( optionName in globalEnv) {
if( !dropNames) {
arrayPush(capturedEnvironmentOptionNames, optionName);
}
const optionValue= globalEnv[optionName];
// eslint-disable-next-line @endo/no-polymorphic-call
typeof optionValue=== 'string'||
Fail `Environment option named ${q(
optionName)
}, if present, must have a corresponding string value, got ${q(
optionValue)
}`;
setting= optionValue;
}
}
optOtherValues=== undefined||
setting=== defaultSetting||
arrayIncludes(optOtherValues, setting)||
Fail `Unrecognized ${q(optionName)} value ${q(
setting)
}. Expected one of ${q([defaultSetting,...optOtherValues]) }`;
return setting;
};
freeze(getEnvironmentOption);
/**
* @param {string} optionName
* @returns {string[]}
*/
const getEnvironmentOptionsList= (optionName)=>{
const option= getEnvironmentOption(optionName, '');
return freeze(option=== ''? []: stringSplit(option, ','));
};
freeze(getEnvironmentOptionsList);
const environmentOptionsListHas= (optionName, element)=>
arrayIncludes(getEnvironmentOptionsList(optionName), element);
const getCapturedEnvironmentOptionNames= ()=> {
return freeze([...capturedEnvironmentOptionNames]);
};
freeze(getCapturedEnvironmentOptionNames);
return freeze({
getEnvironmentOption,
getEnvironmentOptionsList,
environmentOptionsListHas,
getCapturedEnvironmentOptionNames});
};$h_once.makeEnvironmentCaptor(makeEnvironmentCaptor);
freeze(makeEnvironmentCaptor);
/**
* For the simple case, where the global in question is `globalThis` and no
* reporting of option names is desired.
*/
const {
getEnvironmentOption,
getEnvironmentOptionsList,
environmentOptionsListHas}=
makeEnvironmentCaptor(globalThis, true);$h_once.getEnvironmentOption(getEnvironmentOption);$h_once.getEnvironmentOptionsList(getEnvironmentOptionsList);$h_once.environmentOptionsListHas(environmentOptionsListHas);
})()
,
// === functors[3] ===
({ imports: $h_imports, liveVar: $h_live, onceVar: $h_once, importMeta: $h____meta, }) => (function () { 'use strict'; $h_imports([["./src/env-options.js", []]]);
})()
,
// === functors[4] ===
({ imports: $h_imports, liveVar: $h_live, onceVar: $h_once, importMeta: $h____meta, }) => (function () { 'use strict'; let Set,String,isArray,arrayJoin,arraySlice,arraySort,arrayMap,keys,fromEntries,freeze,is,isError,setAdd,setHas,stringIncludes,stringStartsWith,stringifyJson,toStringTagSymbol;$h_imports([["../commons.js", [["Set", [$h_a => (Set = $h_a)]],["String", [$h_a => (String = $h_a)]],["isArray", [$h_a => (isArray = $h_a)]],["arrayJoin", [$h_a => (arrayJoin = $h_a)]],["arraySlice", [$h_a => (arraySlice = $h_a)]],["arraySort", [$h_a => (arraySort = $h_a)]],["arrayMap", [$h_a => (arrayMap = $h_a)]],["keys", [$h_a => (keys = $h_a)]],["fromEntries", [$h_a => (fromEntries = $h_a)]],["freeze", [$h_a => (freeze = $h_a)]],["is", [$h_a => (is = $h_a)]],["isError", [$h_a => (isError = $h_a)]],["setAdd", [$h_a => (setAdd = $h_a)]],["setHas", [$h_a => (setHas = $h_a)]],["stringIncludes", [$h_a => (stringIncludes = $h_a)]],["stringStartsWith", [$h_a => (stringStartsWith = $h_a)]],["stringifyJson", [$h_a => (stringifyJson = $h_a)]],["toStringTagSymbol", [$h_a => (toStringTagSymbol = $h_a)]]]]]);
/** @import {StringablePayload} from '../../types.js' */
/**
* Joins English terms with commas and an optional conjunction.
*
* @param {(string | StringablePayload)[]} terms
* @param {"and" | "or"} conjunction
*/
const enJoin= (terms, conjunction)=> {
if( terms.length=== 0) {
return '(none)';
}else if( terms.length=== 1) {
return terms[0];
}else if( terms.length=== 2) {
const [first, second]= terms;
return `${first} ${conjunction} ${second}`;
}else {
return `${arrayJoin(arraySlice(terms,0, -1), ', ') }, ${conjunction} ${
terms[terms.length- 1]
}`;
}
};
/**
* Prepend the correct indefinite article onto a noun, typically a typeof
* result, e.g., "an object" vs. "a number"
*
* @param {string} str The noun to prepend
* @returns {string} The noun prepended with a/an
*/$h_once.enJoin(enJoin);
const an= (str)=>{
str= `${str}`;
if( str.length>= 1&& stringIncludes('aeiouAEIOU', str[0])) {
return `an ${str}`;
}
return `a ${str}`;
};$h_once.an(an);
freeze(an);
/**
* Like `JSON.stringify` but does not blow up if given a cycle or a bigint.
* This is not
* intended to be a serialization to support any useful unserialization,
* or any programmatic use of the resulting string. The string is intended
* *only* for showing a human under benign conditions, in order to be
* informative enough for some
* logging purposes. As such, this `bestEffortStringify` has an
* imprecise specification and may change over time.
*
* The current `bestEffortStringify` possibly emits too many "seen"
* markings: Not only for cycles, but also for repeated subtrees by
* object identity.
*
* As a best effort only for diagnostic interpretation by humans,
* `bestEffortStringify` also turns various cases that normal
* `JSON.stringify` skips or errors on, like `undefined` or bigints,
* into strings that convey their meaning. To distinguish this from
* strings in the input, these synthesized strings always begin and
* end with square brackets. To distinguish those strings from an
* input string with square brackets, and input string that starts
* with an open square bracket `[` is itself placed in square brackets.
*
* @param {any} payload
* @param {(string|number)=} spaces
* @returns {string}
*/
const bestEffortStringify= (payload, spaces= undefined)=> {
const seenSet= new Set();
const replacer= (_, val)=> {
switch( typeof val){
case 'object': {
if( val=== null) {
return null;
}
if( setHas(seenSet, val)) {
return '[Seen]';
}
setAdd(seenSet, val);
if( isError(val)) {
return `[${val.name}: ${val.message}]`;
}
if( toStringTagSymbol in val) {
// For the built-ins that have or inherit a `Symbol.toStringTag`-named
// property, most of them inherit the default `toString` method,
// which will print in a similar manner: `"[object Foo]"` vs
// `"[Foo]"`. The exceptions are
// * `Symbol.prototype`, `BigInt.prototype`, `String.prototype`
// which don't matter to us since we handle primitives
// separately and we don't care about primitive wrapper objects.
// * TODO
// `Date.prototype`, `TypedArray.prototype`.
// Hmmm, we probably should make special cases for these. We're
// not using these yet, so it's not urgent. But others will run
// into these.
//
// Once #2018 is closed, the only objects in our code that have or
// inherit a `Symbol.toStringTag`-named property are remotables
// or their remote presences.
// This printing will do a good job for these without
// violating abstraction layering. This behavior makes sense
// purely in terms of JavaScript concepts. That's some of the
// motivation for choosing that representation of remotables
// and their remote presences in the first place.
return `[${val[toStringTagSymbol]}]`;
}
if( isArray(val)) {
return val;
}
const names= keys(val);
if( names.length< 2) {
return val;
}
let sorted= true;
for( let i= 1; i< names.length; i+= 1) {
if( names[i- 1]>= names[i]) {
sorted= false;
break;
}
}
if( sorted) {
return val;
}
arraySort(names);
const entries= arrayMap(names, (name)=>[name, val[name]]);
return fromEntries(entries);
}
case 'function': {
return `[Function ${val.name|| '<anon>' }]`;
}
case 'string': {
if( stringStartsWith(val, '[')) {
return `[${val}]`;
}
return val;
}
case 'undefined':
case 'symbol': {
return `[${String(val)}]`;
}
case 'bigint': {
return `[${val}n]`;
}
case 'number': {
if( is(val, NaN)) {
return '[NaN]';
}else if( val=== Infinity) {
return '[Infinity]';
}else if( val=== -Infinity) {
return '[-Infinity]';
}
return val;
}
default: {
return val;
}}
};
try {
return stringifyJson(payload, replacer, spaces);
}catch( _err) {
// Don't do anything more fancy here if there is any
// chance that might throw, unless you surround that
// with another try-catch-recovery. For example,
// the caught thing might be a proxy or other exotic
// object rather than an error. The proxy might throw
// whenever it is possible for it to.
return '[Something that failed to stringify]';
}
};$h_once.bestEffortStringify(bestEffortStringify);
freeze(bestEffortStringify);
})()
,
// === functors[5] ===
({ imports: $h_imports, liveVar: $h_live, onceVar: $h_once, importMeta: $h____meta, }) => (function () { 'use strict'; $h_imports([]); // @ts-check
/** @import {GenericErrorConstructor, AssertMakeErrorOptions, DetailsToken, StringablePayload} from '../../types.js' */
/**
* @typedef {object} VirtualConsole
* @property {Console['debug']} debug
* @property {Console['log']} log
* @property {Console['info']} info
* @property {Console['warn']} warn
* @property {Console['error']} error
*
* @property {Console['trace']} trace
* @property {Console['dirxml']} dirxml
* @property {Console['group']} group
* @property {Console['groupCollapsed']} groupCollapsed
*
* @property {Console['assert']} assert
* @property {Console['timeLog']} timeLog
*
* @property {Console['clear']} clear
* @property {Console['count']} count
* @property {Console['countReset']} countReset
* @property {Console['dir']} dir
* @property {Console['groupEnd']} groupEnd
*
* @property {Console['table']} table
* @property {Console['time']} time
* @property {Console['timeEnd']} timeEnd
* @property {Console['timeStamp']} timeStamp
*/
/* This is deliberately *not* JSDoc, it is a regular comment.
*
* TODO: We'd like to add the following properties to the above
* VirtualConsole, but they currently cause conflicts where
* some Typescript implementations don't have these properties
* on the Console type.
*
* @property {Console['profile']} profile
* @property {Console['profileEnd']} profileEnd
*/
/**
* @typedef {'debug' | 'log' | 'info' | 'warn' | 'error'} LogSeverity
*/
/**
* @typedef ConsoleFilter
* @property {(severity: LogSeverity) => boolean} canLog
*/
/**
* @callback FilterConsole
* @param {VirtualConsole} baseConsole
* @param {ConsoleFilter} filter
* @param {string} [topic]
* @returns {VirtualConsole}
*/
})()
,
// === functors[6] ===
({ imports: $h_imports, liveVar: $h_live, onceVar: $h_once, importMeta: $h____meta, }) => (function () { 'use strict'; $h_imports([]); // @ts-check
/**
* @typedef {readonly any[]} LogArgs
*
* This is an array suitable to be used as arguments of a console
* level message *after* the format string argument. It is the result of
* a `details` template string and consists of alternating literal strings
* and substitution values, starting with a literal string. At least that
* first literal string is always present.
*/
/**
* @callback NoteCallback
*
* @param {Error} error
* @param {LogArgs} noteLogArgs
* @returns {void}
*/
/**
* @callback GetStackString
* @param {Error} error
* @returns {string=}
*/
/**
* @typedef {object} LoggedErrorHandler
*
* Used to parameterize `makeCausalConsole` to give it access to potentially
* hidden information to augment the logging of errors.
*
* @property {GetStackString} getStackString
* @property {(error: Error) => string} tagError
* @property {() => void} resetErrorTagNum for debugging purposes only
* @property {(error: Error) => (LogArgs | undefined)} getMessageLogArgs
* @property {(error: Error) => (LogArgs | undefined)} takeMessageLogArgs
* @property {(error: Error, callback?: NoteCallback) => LogArgs[] } takeNoteLogArgsArray
*/
// /////////////////////////////////////////////////////////////////////////////
/**
* @typedef {readonly [string, ...any[]]} LogRecord
*/
/**
* @typedef {object} LoggingConsoleKit
* @property {VirtualConsole} loggingConsole
* @property {() => readonly LogRecord[]} takeLog
*/
/**
* @typedef {object} MakeLoggingConsoleKitOptions
* @property {boolean=} shouldResetForDebugging
*/
/**
* @callback MakeLoggingConsoleKit
*
* A logging console just accumulates the contents of all whitelisted calls,
* making them available to callers of `takeLog()`. Calling `takeLog()`
* consumes these, so later calls to `takeLog()` will only provide a log of
* calls that have happened since then.
*
* @param {LoggedErrorHandler} loggedErrorHandler
* @param {MakeLoggingConsoleKitOptions=} options
* @returns {LoggingConsoleKit}
*/
/**
* @typedef {{
* NOTE: 'ERROR_NOTE:',
* MESSAGE: 'ERROR_MESSAGE:',
* CAUSE: 'cause:',
* ERRORS: 'errors:',
* }} ErrorInfo
*/
/**
* @typedef {ErrorInfo[keyof ErrorInfo]} ErrorInfoKind
*/
/**
* @callback MakeCausalConsole
*
* Makes a causal console wrapper of a `baseConsole`, where the causal console
* calls methods of the `loggedErrorHandler` to customize how it handles logged
* errors.
*
* @param {VirtualConsole | undefined} baseConsole
* @param {LoggedErrorHandler} loggedErrorHandler
* @returns {VirtualConsole | undefined}
*/
})()
,
// === functors[7] ===
({ imports: $h_imports, liveVar: $h_live, onceVar: $h_once, importMeta: $h____meta, }) => (function () { 'use strict'; $h_imports([]); // @ts-check
/* eslint-disable @endo/no-polymorphic-call */
// eslint-disable-next-line no-restricted-globals
const { isSafeInteger}= Number;
// eslint-disable-next-line no-restricted-globals
const { freeze}= Object;
// eslint-disable-next-line no-restricted-globals
const { toStringTag: toStringTagSymbol}= Symbol;
/**
* @template Data
* @typedef {object} DoublyLinkedCell
* A cell of a doubly-linked ring, i.e., a doubly-linked circular list.
* DoublyLinkedCells are not frozen, and so should be closely encapsulated by
* any abstraction that uses them.
* @property {DoublyLinkedCell<Data>} next
* @property {DoublyLinkedCell<Data>} prev
* @property {Data} data
*/
/**
* Makes a new self-linked cell. There are two reasons to do so:
* * To make the head sigil of a new initially-empty doubly-linked ring.
* * To make a non-sigil cell to be `spliceAfter`ed.
*
* @template Data
* @param {Data} data
* @returns {DoublyLinkedCell<Data>}
*/
const makeSelfCell= (data)=>{
/** @type {Partial<DoublyLinkedCell<Data>>} */
const incompleteCell= {
next: undefined,
prev: undefined,
data};
const selfCell= /** @type {DoublyLinkedCell<Data>} */ incompleteCell;
selfCell.next= selfCell;
selfCell.prev= selfCell;
// Not frozen!
return selfCell;
};
/**
* Splices a self-linked non-sigil cell into a ring after `prev`.
* `prev` could be the head sigil, or it could be some other non-sigil
* cell within a ring.
*
* @template Data
* @param {DoublyLinkedCell<Data>} prev
* @param {DoublyLinkedCell<Data>} selfCell
*/
const spliceAfter= (prev, selfCell)=> {
if( prev=== selfCell) {
// eslint-disable-next-line no-restricted-globals
throw TypeError('Cannot splice a cell into itself');
}
if( selfCell.next!== selfCell|| selfCell.prev!== selfCell) {
// eslint-disable-next-line no-restricted-globals
throw TypeError('Expected self-linked cell');
}
const cell= selfCell;
// rename variable cause it isn't self-linked after this point.
const next= prev.next;
cell.prev= prev;
cell.next= next;
prev.next= cell;
next.prev= cell;
// Not frozen!
return cell;
};
/**
* @template Data
* @param {DoublyLinkedCell<Data>} cell
* No-op if the cell is self-linked.
*/
const spliceOut= (cell)=>{
const { prev, next}= cell;
prev.next= next;
next.prev= prev;
cell.prev= cell;
cell.next= cell;
};
/**
* The LRUCacheMap is used within the implementation of `assert` and so
* at a layer below SES or harden. Thus, we give it a `WeakMap`-like interface
* rather than a `WeakMapStore`-like interface. To work before `lockdown`,
* the implementation must use `freeze` manually, but still exhaustively.
*
* It implements the WeakMap interface, and holds its keys weakly. Cached
* values are only held while the key is held by the user and the key/value
* bookkeeping cell has not been pushed off the end of the cache by `budget`
* number of more recently referenced cells. If the key is dropped by the user,
* the value will no longer be held by the cache, but the bookkeeping cell
* itself will stay in memory.
*
* @template {{}} K
* @template {unknown} V
* @param {number} keysBudget
* @returns {WeakMap<K,V>}
*/
const makeLRUCacheMap= (keysBudget)=>{
if( !isSafeInteger(keysBudget)|| keysBudget< 0) {
// eslint-disable-next-line no-restricted-globals
throw TypeError('keysBudget must be a safe non-negative integer number');
}
/** @typedef {DoublyLinkedCell<WeakMap<K, V> | undefined>} LRUCacheCell */
/** @type {WeakMap<K, LRUCacheCell>} */
// eslint-disable-next-line no-restricted-globals
const keyToCell= new WeakMap();
let size= 0; // `size` must remain <= `keysBudget`
// As a sigil, `head` uniquely is not in the `keyToCell` map.