forked from MetaMask/metamask-mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ses.cjs
11657 lines (9697 loc) · 388 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
// ses@1.1.0
'use strict';
(() => {
const functors = [
// === functors[0] ===
({ imports: $h_imports, liveVar: $h_live, onceVar: $h_once, importMeta: $h____meta, }) => (function () { $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}=
globalThis;$h_once.FERAL_ERROR(FERAL_ERROR);$h_once.RangeError(RangeError);$h_once.ReferenceError(ReferenceError);$h_once.SyntaxError(SyntaxError);$h_once.TypeError(TypeError);
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 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 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);
/**
* @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.stringMatch(stringMatch);
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{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)');
};$h_once.noEvalEvaluate(noEvalEvaluate);
})()
,
// === functors[1] ===
({ imports: $h_imports, liveVar: $h_live, onceVar: $h_once, importMeta: $h____meta, }) => (function () { 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 () { $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 () { $h_imports([["./src/env-options.js", []]]);
})()
,
// === functors[4] ===
({ imports: $h_imports, liveVar: $h_live, onceVar: $h_once, importMeta: $h____meta, }) => (function () { 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)]]]]]);
/**
* 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 () { $h_imports([]); // @ts-check
/**
* @callback BaseAssert
* The `assert` function itself.
*
* @param {any} flag The truthy/falsy value
* @param {Details=} optDetails The details to throw
* @param {ErrorConstructor=} ErrorConstructor An optional alternate error
* constructor to use.
* @returns {asserts flag}
*/
/**
* @typedef {object} AssertMakeErrorOptions
* @property {string=} errorName
*/
/**
* @callback AssertMakeError
*
* The `assert.error` method, recording details for the console.
*
* The optional `optDetails` can be a string.
* @param {Details=} optDetails The details of what was asserted
* @param {ErrorConstructor=} ErrorConstructor An optional alternate error
* constructor to use.
* @param {AssertMakeErrorOptions=} options
* @returns {Error}
*/
/**
* @callback AssertFail
*
* The `assert.fail` method.
*
* Fail an assertion, recording full details to the console and
* raising an exception with a message in which `details` substitution values
* have been redacted.
*
* The optional `optDetails` can be a string for backwards compatibility
* with the nodejs assertion library.
* @param {Details=} optDetails The details of what was asserted
* @param {ErrorConstructor=} ErrorConstructor An optional alternate error
* constructor to use.
* @returns {never}
*/
/**
* @callback AssertEqual
* The `assert.equal` method
*
* Assert that two values must be `Object.is`.
* @param {any} actual The value we received
* @param {any} expected What we wanted
* @param {Details=} optDetails The details to throw
* @param {ErrorConstructor=} ErrorConstructor An optional alternate error
* constructor to use.
* @returns {void}
*/
// Type all the overloads of the assertTypeof function.
// There may eventually be a better way to do this, but
// thems the breaks with Typescript 4.0.
/**
* @callback AssertTypeofBigint
* @param {any} specimen
* @param {'bigint'} typename
* @param {Details=} optDetails
* @returns {asserts specimen is bigint}
*/
/**
* @callback AssertTypeofBoolean
* @param {any} specimen
* @param {'boolean'} typename
* @param {Details=} optDetails
* @returns {asserts specimen is boolean}
*/
/**
* @callback AssertTypeofFunction
* @param {any} specimen
* @param {'function'} typename
* @param {Details=} optDetails
* @returns {asserts specimen is Function}
*/
/**
* @callback AssertTypeofNumber
* @param {any} specimen
* @param {'number'} typename
* @param {Details=} optDetails
* @returns {asserts specimen is number}
*/
/**
* @callback AssertTypeofObject
* @param {any} specimen
* @param {'object'} typename
* @param {Details=} optDetails
* @returns {asserts specimen is Record<any, any> | null}
*/
/**
* @callback AssertTypeofString
* @param {any} specimen
* @param {'string'} typename
* @param {Details=} optDetails
* @returns {asserts specimen is string}
*/
/**
* @callback AssertTypeofSymbol
* @param {any} specimen
* @param {'symbol'} typename
* @param {Details=} optDetails
* @returns {asserts specimen is symbol}
*/
/**
* @callback AssertTypeofUndefined
* @param {any} specimen
* @param {'undefined'} typename
* @param {Details=} optDetails
* @returns {asserts specimen is undefined}
*/
/**
* The `assert.typeof` method
*
* @typedef {AssertTypeofBigint & AssertTypeofBoolean & AssertTypeofFunction & AssertTypeofNumber & AssertTypeofObject & AssertTypeofString & AssertTypeofSymbol & AssertTypeofUndefined} AssertTypeof
*/
/**
* @callback AssertString
* The `assert.string` method.
*
* `assert.string(v)` is equivalent to `assert.typeof(v, 'string')`. We
* special case this one because it is the most frequently used.
*
* Assert an expected typeof result.
* @param {any} specimen The value to get the typeof
* @param {Details=} optDetails The details to throw
* @returns {asserts specimen is string}
*/
/**
* @callback AssertNote
* The `assert.note` method.
*
* Annotate an error with details, potentially to be used by an
* augmented console such as the causal console of `console.js`, to
* provide extra information associated with logged errors.
*
* @param {Error} error
* @param {Details} detailsNote
* @returns {void}
*/
// /////////////////////////////////////////////////////////////////////////////
/**
* @typedef {{}} DetailsToken
* A call to the `details` template literal makes and returns a fresh details
* token, which is a frozen empty object associated with the arguments of that
* `details` template literal expression.
*/
/**
* @typedef {string | DetailsToken} Details
* Either a plain string, or made by the `details` template literal tag.
*/
/**
* @typedef {object} StringablePayload
* Holds the payload passed to quote so that its printed form is visible.
* @property {() => string} toString How to print the payload
*/
/**
* To "declassify" and quote a substitution value used in a
* ``` details`...` ``` template literal, enclose that substitution expression
* in a call to `quote`. This makes the value appear quoted
* (as if with `JSON.stringify`) in the message of the thrown error. The
* payload itself is still passed unquoted to the console as it would be
* without `quote`.
*
* For example, the following will reveal the expected sky color, but not the
* actual incorrect sky color, in the thrown error's message:
* ```js
* sky.color === expectedColor || Fail`${sky.color} should be ${quote(expectedColor)}`;
* ```
*
* // TODO Update SES-shim to new convention, where `details` is
* // renamed to `X` rather than `d`.
* The normal convention is to locally rename `details` to `d` and `quote` to `q`
* like `const { details: d, quote: q } = assert;`, so the above example would then be
* ```js
* sky.color === expectedColor || Fail`${sky.color} should be ${q(expectedColor)}`;
* ```
*
* @callback AssertQuote
* @param {any} payload What to declassify
* @param {(string|number)=} spaces
* @returns {StringablePayload} The declassified payload
*/
/**
* @callback Raise
*
* To make an `assert` which terminates some larger unit of computation
* like a transaction, vat, or process, call `makeAssert` with a `Raise`
* callback, where that callback actually performs that larger termination.
* If possible, the callback should also report its `reason` parameter as
* the alleged reason for the termination.
*
* @param {Error} reason
*/
/**
* @callback MakeAssert
*
* Makes and returns an `assert` function object that shares the bookkeeping
* state defined by this module with other `assert` function objects made by
* `makeAssert`. This state is per-module-instance and is exposed by the
* `loggedErrorHandler` above. We refer to `assert` as a "function object"
* because it can be called directly as a function, but also has methods that
* can be called.
*
* If `optRaise` is provided, the returned `assert` function object will call
* `optRaise(reason)` before throwing the error. This enables `optRaise` to
* engage in even more violent termination behavior, like terminating the vat,
* that prevents execution from reaching the following throw. However, if
* `optRaise` returns normally, which would be unusual, the throw following
* `optRaise(reason)` would still happen.
*
* @param {Raise=} optRaise
* @param {boolean=} unredacted
* @returns {Assert}
*/
/**
* @typedef {(template: TemplateStringsArray | string[], ...args: any) => DetailsToken} DetailsTag
*
* Use the `details` function as a template literal tag to create
* informative error messages. The assertion functions take such messages
* as optional arguments:
* ```js
* assert(sky.isBlue(), details`${sky.color} should be "blue"`);
* ```
* // TODO Update SES-shim to new convention, where `details` is
* // renamed to `X` rather than `d`.
* or following the normal convention to locally rename `details` to `d`
* and `quote` to `q` like `const { details: d, quote: q } = assert;`:
* ```js
* assert(sky.isBlue(), d`${sky.color} should be "blue"`);
* ```
* However, note that in most cases it is preferable to instead use the `Fail`
* template literal tag (which has the same input signature as `details`
* but automatically creates and throws an error):
* ```js
* sky.isBlue() || Fail`${sky.color} should be "blue"`;
* ```
*
* The details template tag returns a `DetailsToken` object that can print
* itself with the formatted message in two ways.
* It will report full details to the console, but
* mask embedded substitution values with their typeof information in the thrown error
* to prevent revealing secrets up the exceptional path. In the example
* above, the thrown error may reveal only that `sky.color` is a string,
* whereas the same diagnostic printed to the console reveals that the
* sky was green. This masking can be disabled for an individual substitution value
* using `quote`.
*
* The `raw` property of an input template array is ignored, so a simple
* array of strings may be provided directly.
*/
/**
* @typedef {(template: TemplateStringsArray | string[], ...args: any) => never} FailTag
*
* Use the `Fail` function as a template literal tag to efficiently
* create and throw a `details`-style error only when a condition is not satisfied.
* ```js
* condition || Fail`...complaint...`;
* ```
* This avoids the overhead of creating usually-unnecessary errors like
* ```js
* assert(condition, details`...complaint...`);
* ```
* while improving readability over alternatives like
* ```js
* condition || assert.fail(details`...complaint...`);
* ```
*
* However, due to current weakness in TypeScript, static reasoning
* is less powerful with the `||` patterns than with an `assert` call.
* Until/unless https://github.com/microsoft/TypeScript/issues/51426 is fixed,
* for `||`-style assertions where this loss of static reasoning is a problem,
* instead express the assertion as
* ```js
* if (!condition) {
* Fail`...complaint...`;
* }
* ```
* or, if needed,
* ```js
* if (!condition) {
* // `throw` is noop since `Fail` throws, but it improves static analysis
* throw Fail`...complaint...`;
* }
* ```
*/
/**
* assert that expr is truthy, with an optional details to describe
* the assertion. It is a tagged template literal like
* ```js
* assert(expr, details`....`);`
* ```
*
* The literal portions of the template are assumed non-sensitive, as
* are the `typeof` types of the substitution values. These are
* assembled into the thrown error message. The actual contents of the
* substitution values are assumed sensitive, to be revealed to
* the console only. We assume only the virtual platform's owner can read
* what is written to the console, where the owner is in a privileged
* position over computation running on that platform.
*
* The optional `optDetails` can be a string for backwards compatibility
* with the nodejs assertion library.
*
* @typedef { BaseAssert & {
* typeof: AssertTypeof,
* error: AssertMakeError,
* fail: AssertFail,
* equal: AssertEqual,
* string: AssertString,
* note: AssertNote,
* details: DetailsTag,
* Fail: FailTag,
* quote: AssertQuote,
* bare: AssertQuote,
* makeAssert: MakeAssert,
* } } Assert
*/