ses 1.4.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/commons.js CHANGED
@@ -133,6 +133,10 @@ export const { prototype: weakmapPrototype } = WeakMap;
133
133
  export const { prototype: weaksetPrototype } = WeakSet;
134
134
  export const { prototype: functionPrototype } = Function;
135
135
  export const { prototype: promisePrototype } = Promise;
136
+ export const { prototype: generatorPrototype } = getPrototypeOf(
137
+ // eslint-disable-next-line no-empty-function, func-names
138
+ function* () {},
139
+ );
136
140
 
137
141
  export const typedArrayPrototype = getPrototypeOf(Uint8Array.prototype);
138
142
 
@@ -191,6 +195,9 @@ export const stringEndsWith = uncurryThis(stringPrototype.endsWith);
191
195
  export const stringIncludes = uncurryThis(stringPrototype.includes);
192
196
  export const stringIndexOf = uncurryThis(stringPrototype.indexOf);
193
197
  export const stringMatch = uncurryThis(stringPrototype.match);
198
+ export const generatorNext = uncurryThis(generatorPrototype.next);
199
+ export const generatorThrow = uncurryThis(generatorPrototype.throw);
200
+
194
201
  /**
195
202
  * @type { &
196
203
  * ((thisArg: string, searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string) => string) &
@@ -217,6 +224,7 @@ export const weaksetAdd = uncurryThis(weaksetPrototype.add);
217
224
  export const weaksetHas = uncurryThis(weaksetPrototype.has);
218
225
  //
219
226
  export const functionToString = uncurryThis(functionPrototype.toString);
227
+ export const functionBind = uncurryThis(bind);
220
228
  //
221
229
  const { all } = Promise;
222
230
  export const promiseAll = promises => apply(all, Promise, [promises]);
@@ -294,3 +302,61 @@ export const noEvalEvaluate = () => {
294
302
  // See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_NO_EVAL.md
295
303
  throw TypeError('Cannot eval with evalTaming set to "noEval" (SES_NO_EVAL)');
296
304
  };
305
+
306
+ // ////////////////// FERAL_STACK_GETTER FERAL_STACK_SETTER ////////////////////
307
+
308
+ const er1StackDesc = getOwnPropertyDescriptor(Error('er1'), 'stack');
309
+ const er2StackDesc = getOwnPropertyDescriptor(TypeError('er2'), 'stack');
310
+
311
+ let feralStackGetter;
312
+ let feralStackSetter;
313
+ if (er1StackDesc && er2StackDesc && er1StackDesc.get) {
314
+ // We should only encounter this case on v8 because of its problematic
315
+ // error own stack accessor behavior.
316
+ // Note that FF/SpiderMonkey, Moddable/XS, and the error stack proposal
317
+ // all inherit a stack accessor property from Error.prototype, which is
318
+ // great. That case needs no heroics to secure.
319
+ if (
320
+ // In the v8 case as we understand it, all errors have an own stack
321
+ // accessor property, but within the same realm, all these accessor
322
+ // properties have the same getter and have the same setter.
323
+ // This is therefore the case that we repair.
324
+ typeof er1StackDesc.get === 'function' &&
325
+ er1StackDesc.get === er2StackDesc.get &&
326
+ typeof er1StackDesc.set === 'function' &&
327
+ er1StackDesc.set === er2StackDesc.set
328
+ ) {
329
+ // Otherwise, we have own stack accessor properties that are outside
330
+ // our expectations, that therefore need to be understood better
331
+ // before we know how to repair them.
332
+ feralStackGetter = freeze(er1StackDesc.get);
333
+ feralStackSetter = freeze(er1StackDesc.set);
334
+ } else {
335
+ // See https://github.com/endojs/endo/blob/master/packages/ses/error-codes/SES_UNEXPECTED_ERROR_OWN_STACK_ACCESSOR.md
336
+ throw TypeError(
337
+ 'Unexpected Error own stack accessor functions (SES_UNEXPECTED_ERROR_OWN_STACK_ACCESSOR)',
338
+ );
339
+ }
340
+ }
341
+
342
+ /**
343
+ * If on a v8 with the problematic error own stack accessor behavior,
344
+ * `FERAL_STACK_GETTER` will be the shared getter of all those accessors
345
+ * and `FERAL_STACK_SETTER` will be the shared setter. On any platform
346
+ * without this problem, `FERAL_STACK_GETTER` and `FERAL_STACK_SETTER` are
347
+ * both `undefined`.
348
+ *
349
+ * @type {(() => any) | undefined}
350
+ */
351
+ export const FERAL_STACK_GETTER = feralStackGetter;
352
+
353
+ /**
354
+ * If on a v8 with the problematic error own stack accessor behavior,
355
+ * `FERAL_STACK_GETTER` will be the shared getter of all those accessors
356
+ * and `FERAL_STACK_SETTER` will be the shared setter. On any platform
357
+ * without this problem, `FERAL_STACK_GETTER` and `FERAL_STACK_SETTER` are
358
+ * both `undefined`.
359
+ *
360
+ * @type {((newValue: any) => void) | undefined}
361
+ */
362
+ export const FERAL_STACK_SETTER = feralStackSetter;
@@ -4,12 +4,10 @@
4
4
 
5
5
  import {
6
6
  Map,
7
- ReferenceError,
8
7
  TypeError,
9
8
  WeakMap,
10
9
  assign,
11
10
  defineProperties,
12
- entries,
13
11
  promiseThen,
14
12
  toStringTagSymbol,
15
13
  weakmapGet,
@@ -21,15 +19,15 @@ import {
21
19
  setGlobalObjectMutableProperties,
22
20
  setGlobalObjectEvaluators,
23
21
  } from './global-object.js';
22
+ import { assertEqual } from './error/assert.js';
24
23
  import { sharedGlobalPropertyNames } from './permits.js';
25
- import { load } from './module-load.js';
24
+ import { load, loadNow } from './module-load.js';
26
25
  import { link } from './module-link.js';
27
26
  import { getDeferredExports } from './module-proxy.js';
28
- import { assert } from './error/assert.js';
29
27
  import { compartmentEvaluate } from './compartment-evaluate.js';
30
28
  import { makeSafeEvaluator } from './make-safe-evaluator.js';
31
29
 
32
- const { quote: q } = assert;
30
+ /** @import {ModuleDescriptor} from '../types.js' */
33
31
 
34
32
  // moduleAliases associates every public module exports namespace with its
35
33
  // corresponding compartment and specifier so they can be used to link modules
@@ -42,19 +40,6 @@ const moduleAliases = new WeakMap();
42
40
  // privateFields captures the private state for each compartment.
43
41
  const privateFields = new WeakMap();
44
42
 
45
- // Compartments do not need an importHook or resolveHook to be useful
46
- // as a vessel for evaluating programs.
47
- // However, any method that operates the module system will throw an exception
48
- // if these hooks are not available.
49
- const assertModuleHooks = compartment => {
50
- const { importHook, resolveHook } = weakmapGet(privateFields, compartment);
51
- if (typeof importHook !== 'function' || typeof resolveHook !== 'function') {
52
- throw TypeError(
53
- 'Compartment must be constructed with an importHook and a resolveHook for it to be able to load modules',
54
- );
55
- }
56
- };
57
-
58
43
  export const InertCompartment = function Compartment(
59
44
  _endowments = {},
60
45
  _modules = {},
@@ -111,8 +96,6 @@ export const CompartmentPrototype = {
111
96
  throw TypeError('first argument of module() must be a string');
112
97
  }
113
98
 
114
- assertModuleHooks(this);
115
-
116
99
  const { exportsProxy } = getDeferredExports(
117
100
  this,
118
101
  weakmapGet(privateFields, this),
@@ -124,12 +107,12 @@ export const CompartmentPrototype = {
124
107
  },
125
108
 
126
109
  async import(specifier) {
110
+ const { noNamespaceBox } = weakmapGet(privateFields, this);
111
+
127
112
  if (typeof specifier !== 'string') {
128
113
  throw TypeError('first argument of import() must be a string');
129
114
  }
130
115
 
131
- assertModuleHooks(this);
132
-
133
116
  return promiseThen(
134
117
  load(privateFields, moduleAliases, this, specifier),
135
118
  () => {
@@ -139,6 +122,11 @@ export const CompartmentPrototype = {
139
122
  /** @type {Compartment} */ (this),
140
123
  specifier,
141
124
  );
125
+ if (noNamespaceBox) {
126
+ return namespace;
127
+ }
128
+ // Legacy behavior: box the namespace object so that thenable modules
129
+ // do not get coerced into a promise accidentally.
142
130
  return { namespace };
143
131
  },
144
132
  );
@@ -149,8 +137,6 @@ export const CompartmentPrototype = {
149
137
  throw TypeError('first argument of load() must be a string');
150
138
  }
151
139
 
152
- assertModuleHooks(this);
153
-
154
140
  return load(privateFields, moduleAliases, this, specifier);
155
141
  },
156
142
 
@@ -159,8 +145,7 @@ export const CompartmentPrototype = {
159
145
  throw TypeError('first argument of importNow() must be a string');
160
146
  }
161
147
 
162
- assertModuleHooks(this);
163
-
148
+ loadNow(privateFields, moduleAliases, this, specifier);
164
149
  return compartmentImportNow(/** @type {Compartment} */ (this), specifier);
165
150
  },
166
151
  };
@@ -186,16 +171,67 @@ defineProperties(InertCompartment, {
186
171
  * @param {MakeCompartmentConstructor} targetMakeCompartmentConstructor
187
172
  * @param {Record<string, any>} intrinsics
188
173
  * @param {(object: object) => void} markVirtualizedNativeFunction
174
+ * @param {Compartment} [parentCompartment]
189
175
  * @returns {Compartment['constructor']}
190
176
  */
191
177
 
178
+ // In order to facilitate migration from the deprecated signature
179
+ // of the compartment constructor,
180
+ // new Compartent(globals?, modules?, options?)
181
+ // to the new signature:
182
+ // new Compartment(options?)
183
+ // where globals and modules are expressed in the options bag instead of
184
+ // positional arguments, this function detects the temporary sigil __options__
185
+ // on the first argument and coerces compartments arguments into a single
186
+ // compartments object.
187
+ const compartmentOptions = (...args) => {
188
+ if (args.length === 0) {
189
+ return {};
190
+ }
191
+ if (
192
+ args.length === 1 &&
193
+ typeof args[0] === 'object' &&
194
+ args[0] !== null &&
195
+ '__options__' in args[0]
196
+ ) {
197
+ const { __options__, ...options } = args[0];
198
+ assert(
199
+ __options__ === true,
200
+ `Compartment constructor only supports true __options__ sigil, got ${__options__}`,
201
+ );
202
+ return options;
203
+ } else {
204
+ const [
205
+ globals = /** @type {Map<string, any>} */ ({}),
206
+ modules = /** @type {Map<string, ModuleDescriptor>} */ ({}),
207
+ options = {},
208
+ ] = args;
209
+ assertEqual(
210
+ options.modules,
211
+ undefined,
212
+ `Compartment constructor must receive either a module map argument or modules option, not both`,
213
+ );
214
+ assertEqual(
215
+ options.globals,
216
+ undefined,
217
+ `Compartment constructor must receive either globals argument or option, not both`,
218
+ );
219
+ return {
220
+ ...options,
221
+ globals,
222
+ modules,
223
+ };
224
+ }
225
+ };
226
+
192
227
  /** @type {MakeCompartmentConstructor} */
193
228
  export const makeCompartmentConstructor = (
194
229
  targetMakeCompartmentConstructor,
195
230
  intrinsics,
196
231
  markVirtualizedNativeFunction,
232
+ parentCompartment = undefined,
197
233
  ) => {
198
- function Compartment(endowments = {}, moduleMap = {}, options = {}) {
234
+ function Compartment(...args) {
199
235
  if (new.target === undefined) {
200
236
  throw TypeError(
201
237
  "Class constructor Compartment cannot be invoked without 'new'",
@@ -207,12 +243,18 @@ export const makeCompartmentConstructor = (
207
243
  name = '<unknown>',
208
244
  transforms = [],
209
245
  __shimTransforms__ = [],
246
+ globals: endowmentsOption = {},
247
+ modules: moduleMapOption = {},
210
248
  resolveHook,
211
249
  importHook,
250
+ importNowHook,
212
251
  moduleMapHook,
213
252
  importMetaHook,
214
- } = options;
253
+ __noNamespaceBox__: noNamespaceBox = false,
254
+ } = compartmentOptions(...args);
215
255
  const globalTransforms = [...transforms, ...__shimTransforms__];
256
+ const endowments = { __proto__: null, ...endowmentsOption };
257
+ const moduleMap = { __proto__: null, ...moduleMapOption };
216
258
 
217
259
  // Map<FullSpecifier, ModuleCompartmentRecord>
218
260
  const moduleRecords = new Map();
@@ -221,30 +263,6 @@ export const makeCompartmentConstructor = (
221
263
  // Map<FullSpecifier, {ExportsProxy, ProxiedExports, activate()}>
222
264
  const deferredExports = new Map();
223
265
 
224
- // Validate given moduleMap.
225
- // The module map gets translated on-demand in module-load.js and the
226
- // moduleMap can be invalid in ways that cannot be detected in the
227
- // constructor, but these checks allow us to throw early for a better
228
- // developer experience.
229
- for (const [specifier, aliasNamespace] of entries(moduleMap || {})) {
230
- if (typeof aliasNamespace === 'string') {
231
- // TODO implement parent module record retrieval.
232
- throw TypeError(
233
- `Cannot map module ${q(specifier)} to ${q(
234
- aliasNamespace,
235
- )} in parent compartment`,
236
- );
237
- } else if (weakmapGet(moduleAliases, aliasNamespace) === undefined) {
238
- // TODO create and link a synthetic module instance from the given
239
- // namespace object.
240
- throw ReferenceError(
241
- `Cannot map module ${q(
242
- specifier,
243
- )} because it has no known compartment in this realm`,
244
- );
245
- }
246
- }
247
-
248
266
  const globalObject = {};
249
267
 
250
268
  setGlobalObjectSymbolUnscopables(globalObject);
@@ -266,6 +284,7 @@ export const makeCompartmentConstructor = (
266
284
  intrinsics,
267
285
  newGlobalPropertyNames: sharedGlobalPropertyNames,
268
286
  makeCompartmentConstructor: targetMakeCompartmentConstructor,
287
+ parentCompartment: this,
269
288
  markVirtualizedNativeFunction,
270
289
  });
271
290
 
@@ -285,6 +304,7 @@ export const makeCompartmentConstructor = (
285
304
  safeEvaluate,
286
305
  resolveHook,
287
306
  importHook,
307
+ importNowHook,
288
308
  moduleMap,
289
309
  moduleMapHook,
290
310
  importMetaHook,
@@ -292,6 +312,8 @@ export const makeCompartmentConstructor = (
292
312
  __shimTransforms__,
293
313
  deferredExports,
294
314
  instances,
315
+ parentCompartment,
316
+ noNamespaceBox,
295
317
  });
296
318
  }
297
319
 
@@ -58,7 +58,7 @@ All the above forms of diagnostic information&mdash;error stacks, detailed error
58
58
 
59
59
  To minimize visual noise, none of the following directly produces any logging output: throwing errors, assertion failure, or error annotation. They record information silently, only to be displayed if reached from an explicit `console` logging action. These logging actions are the root of a graph of this additional accumulated information. The logging action arguments include errors. These errors have both a detailed message that include errors, and detailed message annotations that include errors. Those errors likewise... The console logs this extra information once, with a unique tag per error. Any further occurrences of that error output that unique tag, from which to look up such previous log output.
60
60
 
61
- Before repair or `lockdown`, we assume there is some prior "system" console bound to the global `console` in the start compartment. `{ consoleTaming: 'unsafe' }` leaves this unsafe system console in place. This system console is completely ignorant of the extra information in these side tables, which is therefore never seen. This includes the hidden data in the detailed messages. Instead, the system console shows the abbreviated `message` text produced by the `details` template literal that omits censored data. When combined with the default `{ errorTaming: 'safe' }`, the system console may not see error stack information. The `{ errorTaming: 'unsafe' }` setting does not remove error stacks from error objects, in which case the system console will find it as usual.
61
+ Before repair or `lockdown`, we assume there is some prior "system" console bound to the global `console` in the start compartment. `{ consoleTaming: 'unsafe' }` leaves this unsafe system console in place. This system console is completely ignorant of the extra information in these side tables, which is therefore never seen. This includes the hidden data in the detailed messages. Instead, the system console shows the abbreviated `message` text produced by the `details` template literal that omits censored data. When combined with the default `{ errorTaming: 'safe' }`, the system console may not see error stack information. The `{ errorTaming: 'unsafe' }` or `{ errorTaming: 'unsafe-details' }` setting does not remove error stacks from error objects, in which case the system console will find it as usual.
62
62
 
63
63
  The default `{ consoleTaming: 'safe' }` setting replaces the system console with a root console that does use all these side tables to generate a more informative log. This root console wraps the prior system console. This root console outputs its log information only by invoking this wrapped system console, which therefore determines how this log information is made available to the external world. To support determinism, we will also need to support a no-op console setting, as explained at [deterministic handling of adversarial code calling console.log with a Proxy #1852](https://github.com/Agoric/agoric-sdk/issues/1852) and [Need no-op console setting for determinism #487](https://github.com/Agoric/SES-shim/issues/487).
64
64
 
@@ -35,12 +35,21 @@ import {
35
35
  weakmapHas,
36
36
  weakmapSet,
37
37
  AggregateError,
38
+ getOwnPropertyDescriptors,
39
+ ownKeys,
40
+ create,
41
+ objectPrototype,
42
+ objectHasOwnProperty,
38
43
  } from '../commons.js';
39
44
  import { an, bestEffortStringify } from './stringify-utils.js';
40
45
  import './types.js';
41
46
  import './internal-types.js';
42
47
  import { makeNoteLogArgsArrayKit } from './note-log-args.js';
43
48
 
49
+ /**
50
+ * @import {BaseAssert, Assert, AssertionFunctions, AssertionUtilities, StringablePayload, DetailsToken, MakeAssert} from '../../types.js'
51
+ */
52
+
44
53
  // For our internal debugging purposes, uncomment
45
54
  // const internalDebugConsole = console;
46
55
 
@@ -49,7 +58,7 @@ import { makeNoteLogArgsArrayKit } from './note-log-args.js';
49
58
  /** @type {WeakMap<StringablePayload, any>} */
50
59
  const declassifiers = new WeakMap();
51
60
 
52
- /** @type {AssertQuote} */
61
+ /** @type {AssertionUtilities['quote']} */
53
62
  const quote = (payload, spaces = undefined) => {
54
63
  const result = freeze({
55
64
  toString: freeze(() => bestEffortStringify(payload, spaces)),
@@ -62,19 +71,7 @@ freeze(quote);
62
71
  const canBeBare = freeze(/^[\w:-]( ?[\w:-])*$/);
63
72
 
64
73
  /**
65
- * Embed a string directly into error details without wrapping punctuation.
66
- * To avoid injection attacks that exploit quoting confusion, this must NEVER
67
- * be used with data that is possibly attacker-controlled.
68
- * As a further safeguard, we fall back to quoting any input that is not a
69
- * string of sufficiently word-like parts separated by isolated spaces (rather
70
- * than throwing an exception, which could hide the original problem for which
71
- * explanatory details are being constructed---i.e., ``` assert.details`...` ```
72
- * should never be the source of a new exception, nor should an attempt to
73
- * render its output, although we _could_ instead decide to handle the latter
74
- * by inline replacement similar to that of `bestEffortStringify` for producing
75
- * rendered messages like `(an object) was tagged "[Unsafe bare string]"`).
76
- *
77
- * @type {AssertQuote}
74
+ * @type {AssertionUtilities['bare']}
78
75
  */
79
76
  const bare = (payload, spaces = undefined) => {
80
77
  if (typeof payload !== 'string' || !regexpTest(canBeBare, payload)) {
@@ -153,14 +150,15 @@ freeze(DetailsTokenProto.toString);
153
150
 
154
151
  /**
155
152
  * Normally this is the function exported as `assert.details` and often
156
- * spelled `d`. However, if the `{errorTaming: 'unsafe'}` option is given to
157
- * `lockdown`, then `unredactedDetails` is used instead.
153
+ * spelled `X`. However, if the `{errorTaming: 'unsafe'}` or
154
+ * `{errorTaming: 'unsafe-debug'}` option is
155
+ * given to `lockdown`, then `unredactedDetails` is used instead.
158
156
  *
159
157
  * There are some unconditional uses of `redactedDetails` in this module. All
160
158
  * of them should be uses where the template literal has no redacted
161
159
  * substitution values. In those cases, the two are equivalent.
162
160
  *
163
- * @type {DetailsTag}
161
+ * @type {AssertionUtilities['details']}
164
162
  */
165
163
  const redactedDetails = (template, ...args) => {
166
164
  // Keep in mind that the vast majority of calls to `details` creates
@@ -169,7 +167,7 @@ const redactedDetails = (template, ...args) => {
169
167
  // all the work to happen only if needed, for example, if an assertion fails.
170
168
  const detailsToken = freeze({ __proto__: DetailsTokenProto });
171
169
  weakmapSet(hiddenDetailsMap, detailsToken, { template, args });
172
- return detailsToken;
170
+ return /** @type {DetailsToken} */ (/** @type {unknown} */ (detailsToken));
173
171
  };
174
172
  freeze(redactedDetails);
175
173
 
@@ -177,14 +175,15 @@ freeze(redactedDetails);
177
175
  * `unredactedDetails` is like `details` except that it does not redact
178
176
  * anything. It acts like `details` would act if all substitution values
179
177
  * were wrapped with the `quote` function above (the function normally
180
- * spelled `q`). If the `{errorTaming: 'unsafe'}` option is given to
178
+ * spelled `q`). If the `{errorTaming: 'unsafe'}`
179
+ * or `{errorTaming: 'unsafe-debug'}` option is given to
181
180
  * `lockdown`, then the lockdown-shim arranges for the global `assert` to be
182
181
  * one whose `details` property is `unredactedDetails`.
183
182
  * This setting optimizes the debugging and testing experience at the price
184
183
  * of safety. `unredactedDetails` also sacrifices the speed of `details`,
185
184
  * which is usually fine in debugging and testing.
186
185
  *
187
- * @type {DetailsTag}
186
+ * @type {AssertionUtilities['details']}
188
187
  */
189
188
  const unredactedDetails = (template, ...args) => {
190
189
  args = arrayMap(args, arg =>
@@ -255,12 +254,79 @@ const tagError = (err, optErrorName = err.name) => {
255
254
  };
256
255
 
257
256
  /**
258
- * @type {AssertMakeError}
257
+ * Make reasonable best efforts to make a `Passable` error.
258
+ * - `sanitizeError` will remove any "extraneous" own properties already added
259
+ * by the host,
260
+ * such as `fileName`,`lineNumber` on FireFox or `line` on Safari.
261
+ * - If any such "extraneous" properties were removed, `sanitizeError` will
262
+ * annotate
263
+ * the error with them, so they still appear on the causal console
264
+ * log output for diagnostic purposes, but not be otherwise visible.
265
+ * - `sanitizeError` will ensure that any expected properties already
266
+ * added by the host are data
267
+ * properties, converting accessor properties to data properties as needed,
268
+ * such as `stack` on v8 (Chrome, Brave, Edge?)
269
+ * - `sanitizeError` will freeze the error, preventing any correct engine from
270
+ * adding or
271
+ * altering any of the error's own properties `sanitizeError` is done.
272
+ *
273
+ * However, `sanitizeError` will not, for example, `harden`
274
+ * (i.e., deeply freeze)
275
+ * or ensure that the `cause` or `errors` property satisfy the `Passable`
276
+ * constraints. The purpose of `sanitizeError` is only to protect against
277
+ * mischief the host may have already added to the error as created,
278
+ * not to ensure that the error is actually Passable. For that,
279
+ * see `toPassableError` in `@endo/pass-style`.
280
+ *
281
+ * @param {Error} error
282
+ */
283
+ export const sanitizeError = error => {
284
+ const descs = getOwnPropertyDescriptors(error);
285
+ const {
286
+ name: _nameDesc,
287
+ message: _messageDesc,
288
+ errors: _errorsDesc = undefined,
289
+ cause: _causeDesc = undefined,
290
+ stack: _stackDesc = undefined,
291
+ ...restDescs
292
+ } = descs;
293
+
294
+ const restNames = ownKeys(restDescs);
295
+ if (restNames.length >= 1) {
296
+ for (const name of restNames) {
297
+ delete error[name];
298
+ }
299
+ const droppedNote = create(objectPrototype, restDescs);
300
+ // eslint-disable-next-line no-use-before-define
301
+ note(
302
+ error,
303
+ redactedDetails`originally with properties ${quote(droppedNote)}`,
304
+ );
305
+ }
306
+ for (const name of ownKeys(error)) {
307
+ // @ts-expect-error TS still confused by symbols as property names
308
+ const desc = descs[name];
309
+ if (desc && objectHasOwnProperty(desc, 'get')) {
310
+ defineProperty(error, name, {
311
+ value: error[name], // invoke the getter to convert to data property
312
+ });
313
+ }
314
+ }
315
+ freeze(error);
316
+ };
317
+
318
+ /**
319
+ * @type {AssertionUtilities['error']}
259
320
  */
260
321
  const makeError = (
261
322
  optDetails = redactedDetails`Assert failed`,
262
323
  errConstructor = globalThis.Error,
263
- { errorName = undefined, cause = undefined, errors = undefined } = {},
324
+ {
325
+ errorName = undefined,
326
+ cause = undefined,
327
+ errors = undefined,
328
+ sanitize = true,
329
+ } = {},
264
330
  ) => {
265
331
  if (typeof optDetails === 'string') {
266
332
  // If it is a string, use it as the literal part of the template so
@@ -299,6 +365,9 @@ const makeError = (
299
365
  if (errorName !== undefined) {
300
366
  tagError(error, errorName);
301
367
  }
368
+ if (sanitize) {
369
+ sanitizeError(error);
370
+ }
302
371
  // The next line is a particularly fruitful place to put a breakpoint.
303
372
  return error;
304
373
  };
@@ -322,7 +391,7 @@ const { addLogArgs, takeLogArgsArray } = makeNoteLogArgsArrayKit();
322
391
  */
323
392
  const hiddenNoteCallbackArrays = new WeakMap();
324
393
 
325
- /** @type {AssertNote} */
394
+ /** @type {AssertionUtilities['note']} */
326
395
  const note = (error, detailsNote) => {
327
396
  if (typeof detailsNote === 'string') {
328
397
  // If it is a string, use it as the literal part of the template so
@@ -403,7 +472,7 @@ const makeAssert = (optRaise = undefined, unredacted = false) => {
403
472
  const details = unredacted ? unredactedDetails : redactedDetails;
404
473
  const assertFailedDetails = details`Check failed`;
405
474
 
406
- /** @type {AssertFail} */
475
+ /** @type {AssertionFunctions['fail']} */
407
476
  const fail = (
408
477
  optDetails = assertFailedDetails,
409
478
  errConstructor = undefined,
@@ -411,13 +480,14 @@ const makeAssert = (optRaise = undefined, unredacted = false) => {
411
480
  ) => {
412
481
  const reason = makeError(optDetails, errConstructor, options);
413
482
  if (optRaise !== undefined) {
483
+ // @ts-ignore returns `never` doesn't mean it isn't callable
414
484
  optRaise(reason);
415
485
  }
416
486
  throw reason;
417
487
  };
418
488
  freeze(fail);
419
489
 
420
- /** @type {FailTag} */
490
+ /** @type {AssertionUtilities['Fail']} */
421
491
  const Fail = (template, ...args) => fail(details(template, ...args));
422
492
 
423
493
  // Don't freeze or export `baseAssert` until we add methods.
@@ -433,7 +503,7 @@ const makeAssert = (optRaise = undefined, unredacted = false) => {
433
503
  flag || fail(optDetails, errConstructor, options);
434
504
  }
435
505
 
436
- /** @type {AssertEqual} */
506
+ /** @type {AssertionFunctions['equal']} */
437
507
  const equal = (
438
508
  actual,
439
509
  expected,
@@ -450,7 +520,7 @@ const makeAssert = (optRaise = undefined, unredacted = false) => {
450
520
  };
451
521
  freeze(equal);
452
522
 
453
- /** @type {AssertTypeof} */
523
+ /** @type {AssertionFunctions['typeof']} */
454
524
  const assertTypeof = (specimen, typename, optDetails) => {
455
525
  // This will safely fall through if typename is not a string,
456
526
  // which is what we want.
@@ -469,7 +539,7 @@ const makeAssert = (optRaise = undefined, unredacted = false) => {
469
539
  };
470
540
  freeze(assertTypeof);
471
541
 
472
- /** @type {AssertString} */
542
+ /** @type {AssertionFunctions['string']} */
473
543
  const assertString = (specimen, optDetails = undefined) =>
474
544
  assertTypeof(specimen, 'string', optDetails);
475
545
 
@@ -496,3 +566,17 @@ export { makeAssert };
496
566
  /** @type {Assert} */
497
567
  const assert = makeAssert();
498
568
  export { assert };
569
+
570
+ // Internal, to obviate polymorphic dispatch, but may become rigorously
571
+ // consistent with @endo/error:
572
+
573
+ /** @type {AssertionFunctions['equal']} */
574
+ const assertEqual = assert.equal;
575
+
576
+ export {
577
+ assertEqual,
578
+ makeError,
579
+ note as annotateError,
580
+ redactedDetails as X,
581
+ quote as q,
582
+ };
@@ -5,6 +5,8 @@ import { freeze } from '../commons.js';
5
5
  import { makeAssert } from './assert.js';
6
6
  import './types.js';
7
7
 
8
+ /** @import {Assert} from '../../types.js' */
9
+
8
10
  let abandon;
9
11
  // Sniff for host-provided functions for terminating the enclosing UOPT (see
10
12
  // below). Currently it only checks for the `process.abort` or `process.exit`
@@ -21,6 +21,8 @@ import {
21
21
  toStringTagSymbol,
22
22
  } from '../commons.js';
23
23
 
24
+ /** @import {StringablePayload} from '../../types.js' */
25
+
24
26
  /**
25
27
  * Joins English terms with commas and an optional conjunction.
26
28
  *
@@ -58,14 +58,14 @@ export const tameConsole = (
58
58
  typeof globalThis.console !== 'undefined'
59
59
  ? globalThis.console
60
60
  : typeof globalThis.print === 'function'
61
- ? // Make a good-enough console for eshost (including only functions that
62
- // log at a specific level with no special argument interpretation).
63
- // https://console.spec.whatwg.org/#logging
64
- (p => freeze({ debug: p, log: p, info: p, warn: p, error: p }))(
65
- // eslint-disable-next-line no-undef
66
- wrapLogger(globalThis.print),
67
- )
68
- : undefined
61
+ ? // Make a good-enough console for eshost (including only functions that
62
+ // log at a specific level with no special argument interpretation).
63
+ // https://console.spec.whatwg.org/#logging
64
+ (p => freeze({ debug: p, log: p, info: p, warn: p, error: p }))(
65
+ // eslint-disable-next-line no-undef
66
+ wrapLogger(globalThis.print),
67
+ )
68
+ : undefined
69
69
  );
70
70
 
71
71
  // Upgrade a log-only console (as in `eshost -h SpiderMonkey`).