-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathtypes.d.ts
More file actions
585 lines (523 loc) · 19.9 KB
/
types.d.ts
File metadata and controls
585 lines (523 loc) · 19.9 KB
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
/**
* Types of the SES environment
* @module
*/
import '@endo/immutable-arraybuffer/shim.js';
/* eslint-disable no-restricted-globals, vars-on-top, no-var */
// It's academically tempting to define a hardened type, but TypeScript doesn't
// strike a good balance in distinguishing "readonly" in the sense that you
// promise not to change vs "readonly" in the sense that you depend on a thing
// not changing.
// type Hardened<T> =
// T extends number | bigint | string | null | undefined | Function ? T :
// { readonly [P in keyof T]: Hardened<T[P]> };
// So Harden just passes the type through without modification.
// This will occasionally conflict with the type of Object.freeze.
// In those cases, we recommend casting the result of Object.freeze to the
// original thawn type, as if the signature of freeze were identical to this
// version of harden.
export type Harden = <T>(value: T) => T; // not Hardened<T>;
// TODO Somehow remove the redundancy between these type deinitions and the
// inline casts on each call to `getenv` in `lockdown.js`. Hopefully we can
// keep the type info in those casts so it is easily comparable by eye to
// the parameters of that call to `genev`.
export interface RepairOptions {
regExpTaming?: 'safe' | 'unsafe';
localeTaming?: 'safe' | 'unsafe';
consoleTaming?: 'safe' | 'unsafe';
errorTrapping?: 'platform' | 'exit' | 'abort' | 'report' | 'none';
reporting?: 'platform' | 'console' | 'none';
unhandledRejectionTrapping?: 'report' | 'none';
errorTaming?: 'safe' | 'unsafe' | 'unsafe-debug';
/**
* @deprecated Deprecated and does nothing. In the future specifying it will be an error.
*/
dateTaming?: 'safe' | 'unsafe';
/**
* @deprecated Deprecated and does nothing. In the future specifying it will be an error.
*/
mathTaming?: 'safe' | 'unsafe';
evalTaming?:
| 'safe-eval'
| 'unsafe-eval'
| 'no-eval'
// deprecated
| 'safeEval'
| 'unsafeEval'
| 'noEval';
stackFiltering?: 'concise' | 'omit-frames' | 'shorten-paths' | 'verbose';
overrideTaming?: 'moderate' | 'min' | 'severe';
overrideDebug?: Array<string>;
domainTaming?: 'safe' | 'unsafe';
/**
* safe (default): do nothing.
*
* unsafe-ignore: make %IteratorPrototype%[@@iterator] to a funky accessor which ignores all assignments.
*/
legacyRegeneratorRuntimeTaming?: 'safe' | 'unsafe-ignore';
__hardenTaming__?: 'safe' | 'unsafe';
}
// Deprecated in favor of the more specific RepairOptions
export type LockdownOptions = RepairOptions;
export type RepairIntrinsics = (options?: LockdownOptions) => void;
export type HardenIntrinsics = () => void;
export type Lockdown = (options?: LockdownOptions) => void;
export type ModuleExportsNamespace = Record<string, any>;
export type __LiveExportMap__ = Record<string, [string, boolean]>;
export type __FixedExportMap__ = Record<string, [string]>;
export type __ReexportMap__ = Record<string, Array<[string, string]>>;
export interface PrecompiledModuleSource {
imports: Array<string>;
exports: Array<string>;
reexports: Array<string>;
__syncModuleProgram__: string;
__liveExportMap__: __LiveExportMap__;
__fixedExportMap__: __FixedExportMap__;
__reexportMap__: __ReexportMap__;
}
export interface VirtualModuleSource {
imports: Array<string>;
exports: Array<string>;
/**
* Note that this value does _not_ contain any numeric or symbol property keys, which can theoretically be members of `exports` in a CommonJS module.
*/
execute(
exportsTarget: Record<string, any>,
compartment: Compartment,
resolvedImports: Record<string, string>,
): void;
}
export type ModuleSource = PrecompiledModuleSource | VirtualModuleSource;
export interface SourceModuleDescriptor {
source: string | ModuleSource;
specifier?: string;
importMeta?: any;
compartment?: Compartment; // defaults to parent
}
export interface NamespaceModuleDescriptor {
namespace: string | ModuleExportsNamespace;
compartment?: Compartment;
}
// Deprecated in favor of SourceModuleDescriptor,
// but beware the change in default compartment.
export interface RecordModuleDescriptor {
specifier: string;
record?: ModuleSource;
importMeta?: any;
compartment?: Compartment; // defaults to self
}
export type ModuleDescriptor =
| SourceModuleDescriptor
| NamespaceModuleDescriptor
// To be deprecated:
| RecordModuleDescriptor
| ModuleExportsNamespace
| VirtualModuleSource
| PrecompiledModuleSource
| string;
// Deprecated type aliases:
export type PrecompiledStaticModuleInterface = PrecompiledModuleSource;
export type ThirdPartyStaticModuleInterface = VirtualModuleSource;
export type RedirectStaticModuleInterface = RecordModuleDescriptor;
export type FinalStaticModuleType = ModuleSource;
export type StaticModuleType = RedirectStaticModuleInterface | ModuleSource;
export type Transform = (source: string) => string;
export type ResolveHook = (
importSpecifier: string,
referrerSpecifier: string,
) => string;
export type ModuleMap = Record<string, string | ModuleDescriptor>;
export type ModuleMapHook = (
moduleSpecifier: string,
) => ModuleDescriptor | undefined;
export type ImportHook = (moduleSpecifier: string) => Promise<ModuleDescriptor>;
export type ImportNowHook = (
moduleSpecifier: string,
) => ModuleDescriptor | undefined;
export type ImportMetaHook = (
moduleSpecifier: string,
importMeta: ImportMeta,
) => void;
export interface CompartmentOptions {
name?: string;
transforms?: Array<Transform>;
moduleMapHook?: ModuleMapHook;
importHook?: ImportHook;
importNowHook?: ImportNowHook;
importMetaHook?: ImportMetaHook;
resolveHook?: ResolveHook;
globals?: Map<string, any>;
modules?: Map<string, ModuleDescriptor>;
__shimTransforms__?: Array<Transform>;
__noNamespaceBox__?: boolean;
/** @deprecated */
loadHook?: (specifier: string) => Promise<ModuleDescriptor>;
/** @deprecated */
loadNowHook?: (specifier: string) => ModuleDescriptor;
__native__?: boolean;
/**
* If `true`, the first error encountered during module loading will be thrown immediately
*/
noAggregateLoadErrors?: boolean;
}
export interface EvaluateOptions {
transforms?: Array<Transform>;
sloppyGlobalsMode?: boolean;
__moduleShimLexicals__?: Record<string, any>;
__evadeHtmlCommentTest__?: boolean;
__rejectSomeDirectEvalExpressions__?: boolean;
}
interface Stringable {
toString(): string;
}
/** @deprecated */
type StringPayload = Stringable;
/**
* A call to the {@link details} template literal makes and returns a fresh
* DetailsToken, which is a frozen empty object associated with the arguments of
* that expression.
*/
export type DetailsToken = Record<any, never>;
/**
* A plain string, or a {@link DetailsToken} from the {@link details} template
* literal tag.
*/
export type Details = string | DetailsToken;
export interface AssertMakeErrorOptions {
/**
* Does not affect the error.name property. That remains determined by
* the constructor. Rather, the `errorName` determines how this error is
* identified in an associated console's output.
*/
errorName?: string;
/**
* Discloses the error that caused this one, typically from a lower
* layer of abstraction. This is represented by a public `cause` data property
* on the error, not a hidden annotation.
*/
cause?: Error;
/**
* Normally only used when the ErrorConstuctor is `AggregateError`, to
* represent the set of prior errors aggregated together in this error,
* typically by `Promise.any`. But `makeError` allows it on any error.
* This is represented by a public `errors` data property on the error,
* not a hidden annotation.
*/
errors?: Error[];
/**
* Defaults to true. If true, `makeError` will apply `sanitizeError`
* to the error before returning it. See the comments on
* {@link sanitizeError}.
*/
sanitize?: boolean;
/**
* The error code to assign to the error.
*/
code?: string;
}
// TODO inline overloading
type AssertTypeofBigint = (
specimen: any,
typeName: 'bigint',
details?: Details,
) => asserts specimen is bigint;
type AssertTypeofBoolean = (
specimen: any,
typeName: 'boolean',
details?: Details,
) => asserts specimen is boolean;
type AssertTypeofFunction = (
specimen: any,
typeName: 'function',
details?: Details,
) => asserts specimen is Function;
type AssertTypeofNumber = (
specimen: any,
typeName: 'number',
details?: Details,
) => asserts specimen is number;
type AssertTypeofObject = (
specimen: any,
typeName: 'object',
details?: Details,
) => asserts specimen is Record<any, any> | null;
type AssertTypeofString = (
specimen: any,
typeName: 'string',
details?: Details,
) => asserts specimen is string;
type AssertTypeofSymbol = (
specimen: any,
typeName: 'symbol',
details?: Details,
) => asserts specimen is symbol;
type AssertTypeofUndefined = (
specimen: any,
typeName: 'undefined',
details?: Details,
) => asserts specimen is undefined;
export type AssertTypeof = AssertTypeofBigint &
AssertTypeofBoolean &
AssertTypeofFunction &
AssertTypeofNumber &
AssertTypeofObject &
AssertTypeofString &
AssertTypeofSymbol &
AssertTypeofUndefined;
/**
* TypeScript does not treat `AggregateErrorConstructor` as a subtype of
* `ErrorConstructor`, which makes sense because their constructors
* have incompatible signatures. However, we want to parameterize some
* operations by any error constructor, including possible `AggregateError`.
* So we introduce `GenericErrorConstructor` as a common supertype. Any call
* to it to make an instance must therefore first case split on whether the
* constructor is an AggregateErrorConstructor or a normal ErrorConstructor.
*/
export type GenericErrorConstructor =
| ErrorConstructor
| AggregateErrorConstructor;
/**
* An `Error` with a `code` property.
*/
export type CodableError = Error & { code?: string };
/**
* 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.
*/
export type Raise = (reason: CodableError) => void;
/**
* Makes and returns an `assert` function object that shares the
* per-module-instance bookkeeping state defined by this module with other
* `assert` function objects made by `makeAssert`. We refer to `assert` as a
* "function object" because it can be called directly as a function, but also
* has callable methods of its own.
*
* If `raise` is provided, the returned `assert` function object will call
* `raise(reason)` before throwing an assertion-failure error. This enables
* `raise` to engage in even more violent termination behavior, like process
* termination, that prevents execution from reaching the following throw.
* However, if `raise(reason)` returns normally, which would be unusual, that
* throw still happens.
*/
// eslint-disable-next-line no-use-before-define
export type MakeAssert = (raise?: Raise, unredacted?: boolean) => Assert;
export type BaseAssert = (
/** The condition whose truthiness is being asserted */
condition: any,
/** The details associated with assertion failure (falsy condition) */
details?: Details,
/** An optional alternate error constructor to use */
errConstructor?: GenericErrorConstructor,
options?: AssertMakeErrorOptions,
) => asserts condition;
export interface AssertionFunctions extends BaseAssert {
typeof: AssertTypeof;
/**
* Assert that two values are the same as observed by `Object.is`.
*/
equal<T>(
/** What we received */
actual: unknown,
/** What we wanted */
expected: T,
/** The details associated with assertion failure (`Object.is` returning false) */
details?: Details,
/** An optional alternate error constructor to use */
errConstructor?: GenericErrorConstructor,
options?: AssertMakeErrorOptions,
): asserts actual is T;
/**
* Assert that a value is a primitive string.
* `assert.string(v)` is equivalent to `assert.typeof(v, 'string')`. We
* special case this one because it is the most frequently used.
*/
string(
specimen: any,
/** The details of what was asserted */
details?: Details,
): asserts specimen is string;
/**
* Fail an assertion, raising an exception with a `message` in which unquoted
* `details` substitution values may have been redacted into `typeof` types
* but are still available for logging to an associated console.
*/
fail(
/** The details of what was asserted */
details?: Details,
/** An optional alternate error constructor to use */
errConstructor?: GenericErrorConstructor,
options?: AssertMakeErrorOptions,
): never;
}
export interface AssertionUtilities {
/**
* Create an error with a `message` in which unquoted {@link details}
* substitution values may have been redacted into lossy `typeof` output but
* are still available for logging to an associated console.
*/
makeError(
/** The details of what was asserted */
details?: Details,
/** An optional alternate error constructor to use */
errConstructor?: GenericErrorConstructor,
options?: AssertMakeErrorOptions,
): CodableError;
/**
* Associate `details` with `error`, potentially to be logged by an associated
* console for providing extra information about the error.
*/
note(error: CodableError, details: Details): void;
/**
* Use as a template literal tag to create an opaque {@link DetailsToken} for
* use with other assertion functions that might redact unquoted substitution
* values (i.e., those that are not output from the {@link quote} function)
* into lossy `typeof` output but still preserve them for logging to an
* associated console.
*
* The normal convention is to locally rename `details` to `X` like
* `const { details: X, quote: q, Fail } = assert;`.
* However, note that in most cases it is preferable to instead use the `Fail`
* template literal tag (which has the same input signature but automatically
* creates and throws an error):
* ```js
* sky.isBlue() || Fail`${sky.color} should be "blue"`;
* ```
*
* The `raw` property of an input template array is ignored, so a simple
* array of strings may be provided directly.
*/
details(
template: TemplateStringsArray | string[],
...args: any
): DetailsToken;
/**
* Use as a template literal tag to create and throw an error in whose
* `message` unquoted substitution values (i.e., those that are not output
* from the {@link quote} function) may have been redacted into lossy `typeof`
* output but are still available for logging to an associated console.
*
* For example, using the normal convention to locally rename properties like
* `const { quote: q, Fail } = assert;`:
* ```js
* sky.isBlue() || Fail`${sky.color} should be "blue"`;
* ```
*
* This `||` pattern saves the cost of creating {@link DetailsToken} and/or
* error instances when the asserted condition holds, but can weaken
* TypeScript static reasoning due to
* https://github.com/microsoft/TypeScript/issues/51426 . Where this is a
* problem, instead express the assertion as
* ```js
* if (!sky.isBlue()) {
* // This `throw` does not affect runtime behavior since `Fail` throws, but
* // might be needed to improve static analysis.
* throw Fail`${sky.color} should be "blue"`;
* }
* ```
*
* The `raw` property of an input template array is ignored, so a simple
* array of strings may be provided directly.
*/
Fail(template: TemplateStringsArray | string[], ...args: any): never;
/**
* Wrap a value such that its use as a substitution value in a template
* literal tagged with {@link details} or {@link Fail} will result in it
* appearing quoted (in a way similar to but more general than
* `JSON.stringify`) rather than redacted in the `message` of errors based on
* the resulting {@link DetailsToken}.
*
* This does not affect representation in output of an associated console,
* which still logs the value as it would without `quote`, but *does* reveal
* it to functions in the propagation path of such errors.
*
* For example, the following will reveal the expected value in the thrown
* error's `message`, but only the _type_ of the actual incorrect value (using
* the normal convention to locally rename properties like
* `const { quote: q, Fail } = assert;`):
* ```js
* actual === expected || Fail`${actual} should be ${q(expected)}`;
* ```
*
* The optional `space` parameter matches that of `JSON.stringify`, and is
* used to request insertion of non-semantic line feeds, indentation, and
* separating spaces in the output for improving readability of objects and
* arrays.
*/
quote(value: any, space?: string | number): Stringable;
/**
* Wrap a string such that its use as a substitution value in a template
* literal tagged with {@link details} or {@link Fail} will be treated
* literally rather than being quoted or redacted.
*
* To avoid injection attacks that exploit quoting confusion, this must NEVER
* be used with data that is possibly attacker-controlled.
*
* As a further safeguard, we fall back to quoting any input that is not a
* string of sufficiently word-like parts separated by isolated spaces (rather
* than throwing an exception, which could hide the original problem for which
* explanatory details are being constructed---i.e., ``` assert.details`...` ```
* should never be the source of a new exception, nor should an attempt to
* render its output, although we _could_ instead decide to handle the latter
* by inline replacement similar to that of `bestEffortStringify` for producing
* rendered messages like `(an object) was tagged "[Unsafe bare string]"`).
*/
bare(text: string, spaces?: string | number): Stringable;
}
export interface DeprecatedAssertionUtilities {
makeAssert: MakeAssert;
error: AssertionUtilities['makeError'];
}
/**
* Assert that `condition` is truthy, with optional details associated with
* assertion failure (falsy condition).
*
* The literal portions of the template used to make a {@link DetailsToken} are
* assumed non-sensitive, as are the `typeof` output for substitution values.
* These are assembled into the error `message`. The actual contents of the
* substitution values are assumed sensitive and usually redacted, to be
* revealed only to an associated console. 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.
*/
export type Assert = AssertionFunctions &
AssertionUtilities &
DeprecatedAssertionUtilities;
interface CompartmentEvaluateOptions {
sloppyGlobalsMode?: boolean;
__moduleShimLexicals__?: Object;
__evadeHtmlCommentTest__?: boolean;
__evadeImportExpressionTest__?: boolean;
__rejectSomeDirectEvalExpressions__?: boolean;
}
declare global {
var harden: Harden;
var repairIntrinsics: RepairIntrinsics;
var hardenIntrinsics: HardenIntrinsics;
var lockdown: Lockdown;
var assert: Assert;
/**
* Each Compartment constructor is a global. A host that wants to execute
* code in a context bound to a new global creates a new compartment.
*/
export class Compartment {
constructor(options?: CompartmentOptions & { __options__: true });
// Deprecated:
constructor(
globals?: Record<PropertyKey, any> | undefined,
modules?: Record<string, ModuleDescriptor>,
options?: CompartmentOptions,
);
get globalThis(): Record<PropertyKey, any>;
get name(): string;
evaluate(code: string, options?: CompartmentEvaluateOptions): any;
import(
specifier: string | null,
): Promise<{ namespace: ModuleExportsNamespace }>;
load(specifier: string): Promise<void>;
importNow(specifier: string): ModuleExportsNamespace;
module(specifier: string): ModuleExportsNamespace;
}
}