ses 2.2.0 → 2.3.1

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/dist/ses.umd.js CHANGED
@@ -1,4 +1,4 @@
1
- // ses@2.2.0
1
+ // ses@2.3.1
2
2
  (functors => options => {
3
3
  'use strict';
4
4
 
@@ -218,6 +218,8 @@
218
218
  {
219
219
  },
220
220
  {
221
+ _amplifyArrayBufferForTests: cell("_amplifyArrayBufferForTests"),
222
+ immutableArrayBufferLibProperties: cell("immutableArrayBufferLibProperties"),
221
223
  isBufferImmutable: cell("isBufferImmutable"),
222
224
  sliceBufferToImmutable: cell("sliceBufferToImmutable"),
223
225
  optTransferBufferToImmutable: cell("optTransferBufferToImmutable"),
@@ -227,9 +229,9 @@
227
229
  {
228
230
  },
229
231
  {
232
+ enJoin: cell("enJoin"),
230
233
  an: cell("an"),
231
234
  bestEffortStringify: cell("bestEffortStringify"),
232
- enJoin: cell("enJoin"),
233
235
  },
234
236
  {
235
237
  },
@@ -369,7 +371,9 @@
369
371
  },
370
372
  {
371
373
  consoleLevelMethods: cell("consoleLevelMethods"),
374
+ consoleSpecialMethods: cell("consoleSpecialMethods"),
372
375
  consoleOtherMethods: cell("consoleOtherMethods"),
376
+ sanitizeFormatData: cell("sanitizeFormatData"),
373
377
  makeLoggingConsoleKit: cell("makeLoggingConsoleKit"),
374
378
  pumpLogToConsole: cell("pumpLogToConsole"),
375
379
  makeCausalConsole: cell("makeCausalConsole"),
@@ -697,6 +701,8 @@ function observeImports(map, importName, importIndex) {
697
701
  liveVar: {
698
702
  },
699
703
  onceVar: {
704
+ amplifyArrayBuffer: cells[4]._amplifyArrayBufferForTests.set,
705
+ immutableArrayBufferLibProperties: cells[4].immutableArrayBufferLibProperties.set,
700
706
  isBufferImmutable: cells[4].isBufferImmutable.set,
701
707
  sliceBufferToImmutable: cells[4].sliceBufferToImmutable.set,
702
708
  optTransferBufferToImmutable: cells[4].optTransferBufferToImmutable.set,
@@ -706,7 +712,7 @@ function observeImports(map, importName, importIndex) {
706
712
  functors[5]({
707
713
  imports(entries) {
708
714
  const map = new Map(entries);
709
- observeImports(map, "./immutable-arraybuffer-pony.js", 4);
715
+ observeImports(map, "./lib.js", 4);
710
716
  },
711
717
  liveVar: {
712
718
  },
@@ -717,7 +723,7 @@ function observeImports(map, importName, importIndex) {
717
723
  functors[6]({
718
724
  imports(entries) {
719
725
  const map = new Map(entries);
720
- observeImports(map, "./src/immutable-arraybuffer-shim.js", 5);
726
+ observeImports(map, "./src/shim.js", 5);
721
727
  },
722
728
  liveVar: {
723
729
  },
@@ -733,9 +739,9 @@ function observeImports(map, importName, importIndex) {
733
739
  liveVar: {
734
740
  },
735
741
  onceVar: {
742
+ enJoin: cells[7].enJoin.set,
736
743
  an: cells[7].an.set,
737
744
  bestEffortStringify: cells[7].bestEffortStringify.set,
738
- enJoin: cells[7].enJoin.set,
739
745
  },
740
746
  importMeta: {},
741
747
  });
@@ -1212,7 +1218,9 @@ function observeImports(map, importName, importIndex) {
1212
1218
  },
1213
1219
  onceVar: {
1214
1220
  consoleLevelMethods: cells[42].consoleLevelMethods.set,
1221
+ consoleSpecialMethods: cells[42].consoleSpecialMethods.set,
1215
1222
  consoleOtherMethods: cells[42].consoleOtherMethods.set,
1223
+ sanitizeFormatData: cells[42].sanitizeFormatData.set,
1216
1224
  makeLoggingConsoleKit: cells[42].makeLoggingConsoleKit.set,
1217
1225
  pumpLogToConsole: cells[42].pumpLogToConsole.set,
1218
1226
  makeCausalConsole: cells[42].makeCausalConsole.set,
@@ -1592,7 +1600,6 @@ function observeImports(map, importName, importIndex) {
1592
1600
  * @module
1593
1601
  */
1594
1602
 
1595
- /* global globalThis */
1596
1603
  /* eslint-disable no-restricted-globals */
1597
1604
 
1598
1605
  // We cannot use globalThis as the local name since it would capture the
@@ -2136,8 +2143,7 @@ if (getThis()) {
2136
2143
  })()
2137
2144
  ,
2138
2145
  // === 2. env-options ./src/env-options.js ===
2139
- ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';$h͏_imports([]);/* global globalThis */
2140
- // @ts-check
2146
+ ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';$h͏_imports([]);// @ts-check
2141
2147
 
2142
2148
  // `@endo/env-options` needs to be imported quite early, and so should
2143
2149
  // avoid importing from ses or anything that depends on ses.
@@ -2222,7 +2228,7 @@ const Fail = (literals, ...args) => {
2222
2228
  arrayPush(capturedEnvironmentOptionNames, optionName);
2223
2229
  }
2224
2230
  const optionValue = globalEnv[optionName];
2225
- // eslint-disable-next-line @endo/no-polymorphic-call
2231
+
2226
2232
  typeof optionValue === 'string' ||
2227
2233
  Fail`Environment option named ${q(
2228
2234
  optionName,
@@ -2291,10 +2297,8 @@ freeze(makeEnvironmentCaptor);
2291
2297
  ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';$h͏_imports([["./src/env-options.js", []]]);
2292
2298
  })()
2293
2299
  ,
2294
- // === 4. immutable-arraybuffer ./src/immutable-arraybuffer-pony.js ===
2295
- ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';$h͏_imports([]);/* global globalThis */
2296
-
2297
- const {
2300
+ // === 4. immutable-arraybuffer ./src/lib.js ===
2301
+ ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';$h͏_imports([]);const {
2298
2302
  ArrayBuffer,
2299
2303
  Object,
2300
2304
  Reflect,
@@ -2307,19 +2311,47 @@ const {
2307
2311
  // eslint-disable-next-line no-restricted-globals
2308
2312
  } = globalThis;
2309
2313
 
2310
- const { freeze, defineProperty, getPrototypeOf, getOwnPropertyDescriptor } =
2314
+ const { freeze, defineProperty, getOwnPropertyDescriptor, getPrototypeOf } =
2311
2315
  Object;
2312
2316
  const { apply, ownKeys } = Reflect;
2313
- const { toStringTag } = Symbol;
2317
+
2318
+ // Capture the WeakMap prototype methods up front so we can use them with
2319
+ // `apply` below, without exposing the `buffers` WeakMap to post-hoc
2320
+ // prototype lookups or polymorphic dispatch.
2321
+ const { get: weakmapGet, set: weakmapSet, has: weakmapHas } = WeakMap.prototype;
2314
2322
 
2315
2323
  const { prototype: arrayBufferPrototype } = ArrayBuffer;
2316
- const { slice, transfer: optTransfer } = arrayBufferPrototype;
2324
+ const {
2325
+ slice,
2326
+ transfer: optTransfer,
2327
+ resize: optResize,
2328
+ transferToFixedLength: optTransferToFixedLength,
2329
+ } = arrayBufferPrototype;
2317
2330
  // @ts-expect-error TS doesn't know it'll be there
2318
2331
  const { get: arrayBufferByteLength } = getOwnPropertyDescriptor(
2319
2332
  arrayBufferPrototype,
2320
2333
  'byteLength',
2321
2334
  );
2322
2335
 
2336
+ // Capture the resizable-ArrayBuffer proposal's accessors when present. On
2337
+ // platforms without that proposal (Node <= 18, Hermes), these are absent;
2338
+ // the fallthrough branches in the lib property record short-circuit on
2339
+ // brand membership and never reach the captured accessor in that case
2340
+ // (an emulated immutable always has `detached === false`, `resizable ===
2341
+ // false`, and `maxByteLength === byteLength`).
2342
+ const optArrayBufferDetached = getOwnPropertyDescriptor(
2343
+ arrayBufferPrototype,
2344
+ 'detached',
2345
+ )?.get;
2346
+ const optArrayBufferResizable = getOwnPropertyDescriptor(
2347
+ arrayBufferPrototype,
2348
+ 'resizable',
2349
+ )?.get;
2350
+ const optArrayBufferMaxByteLength = getOwnPropertyDescriptor(
2351
+ arrayBufferPrototype,
2352
+ 'maxByteLength',
2353
+ )?.get;
2354
+
2323
2355
  const typedArrayPrototype = getPrototypeOf(Uint8Array.prototype);
2324
2356
  const { set: uint8ArraySet } = typedArrayPrototype;
2325
2357
  // @ts-expect-error TS doesn't know it'll be there
@@ -2348,10 +2380,8 @@ const arrayBufferSlice = (realBuffer, start = undefined, end = undefined) =>
2348
2380
  * On other platforms, we can still emulate
2349
2381
  * `ArrayBuffer.prototoype.sliceToImmutable`, but not
2350
2382
  * `ArrayBuffer.prototype.transferToImmutable`.
2351
- * Currently, these known-deficient platforms are
2352
- * - Hermes
2353
- * - Node.js <= 16
2354
- * - Apparently some versions of JavaScriptCore that are still of concern.
2383
+ * See the package README section "Platform support for `transferToImmutable`"
2384
+ * for the per-engine version thresholds and feature-testing guidance.
2355
2385
  *
2356
2386
  * @param {ArrayBuffer} arrayBuffer
2357
2387
  * @returns {ArrayBuffer}
@@ -2381,80 +2411,198 @@ if (optTransfer) {
2381
2411
  * emulate the `this.#buffer` private field, including its use as a brand check.
2382
2412
  * Maps from all and only emulated Immutable ArrayBuffers to real ArrayBuffers.
2383
2413
  *
2384
- * @type {Pick<WeakMap<ArrayBuffer, ArrayBuffer>, 'get' | 'has' | 'set'>}
2414
+ * @type {WeakMap<ArrayBuffer, ArrayBuffer>}
2385
2415
  */
2386
2416
  const buffers = new WeakMap();
2387
- // Avoid post-hoc prototype lookups.
2388
- for (const methodName of ['get', 'has', 'set']) {
2389
- defineProperty(buffers, methodName, { value: buffers[methodName] });
2390
- }
2391
- const getBuffer = immuAB => {
2392
- // Safe because this WeakMap owns its get method.
2393
- // eslint-disable-next-line @endo/no-polymorphic-call
2394
- const result = buffers.get(immuAB);
2395
- if (result) {
2417
+ const isEmulatedImmutable = buf => apply(weakmapHas, buffers, [buf]);
2418
+
2419
+ /**
2420
+ * Amplifier-with-this-fallthrough: returns the underlying genuine
2421
+ * `ArrayBuffer` when `arrayBuffer` is an emulated immutable buffer (in the
2422
+ * brand WeakMap), and returns `arrayBuffer` itself otherwise. This lets the
2423
+ * methods on the shared `ArrayBuffer.prototype` (after the shim install)
2424
+ * work as drop-in replacements for the genuine methods when invoked on a
2425
+ * genuine `ArrayBuffer`, while transparently reaching the underlying buffer
2426
+ * for the emulated-immutable case. The name aligns with the analogous
2427
+ * `amplifyTypedArray` on the freezable-TypedArray experiment branch.
2428
+ *
2429
+ * @param {ArrayBuffer} arrayBuffer
2430
+ * @returns {ArrayBuffer}
2431
+ */
2432
+ const amplifyArrayBuffer = arrayBuffer => {
2433
+ const result = apply(weakmapGet, buffers, [arrayBuffer]);
2434
+ if (result !== undefined) {
2396
2435
  return result;
2397
2436
  }
2398
- throw TypeError('Not an emulated Immutable ArrayBuffer');
2437
+ return arrayBuffer;
2399
2438
  };
2400
2439
 
2401
- // Omits `constructor` so `Array.prototype.constructor` is inherited.
2402
- const ImmutableArrayBufferInternalPrototype = {
2403
- __proto__: arrayBufferPrototype,
2440
+ /**
2441
+ * A plain record of the properties the shim copies onto
2442
+ * `ArrayBuffer.prototype` to install immutable-ArrayBuffer support. This is
2443
+ * not a prototype of any object: emulated immutable buffers directly inherit
2444
+ * from `ArrayBuffer.prototype`, and the methods here become the ones the
2445
+ * (now shared) prototype dispatches to. Each method either calls
2446
+ * `amplifyArrayBuffer(this)` to reach the underlying buffer (read accessors,
2447
+ * `slice`, `sliceToImmutable`) or discriminates on brand WeakMap membership
2448
+ * and delegates to the captured genuine method on fallthrough (the mutators
2449
+ * `resize`, `transfer`, `transferToFixedLength`, `transferToImmutable`).
2450
+ *
2451
+ * Omits `constructor` so the original `ArrayBuffer.prototype.constructor` is unchanged.
2452
+ */$h͏_once.amplifyArrayBuffer(amplifyArrayBuffer);
2453
+ const immutableArrayBufferLibProperties = {
2454
+ __proto__: null,
2455
+ /**
2456
+ * @this {ArrayBuffer}
2457
+ */
2404
2458
  get byteLength() {
2405
- return apply(arrayBufferByteLength, getBuffer(this), []);
2459
+ return apply(arrayBufferByteLength, amplifyArrayBuffer(this), []);
2406
2460
  },
2461
+ /**
2462
+ * @this {ArrayBuffer}
2463
+ */
2407
2464
  get detached() {
2408
- getBuffer(this); // shim brand check
2409
- return false;
2465
+ if (isEmulatedImmutable(this)) {
2466
+ return false;
2467
+ }
2468
+ // Genuine `ArrayBuffer.prototype.detached` is a stage-finished accessor
2469
+ // on platforms with the resizable-ArrayBuffer proposal. On older
2470
+ // platforms (Node <= 18, Hermes) it does not exist; the conservative
2471
+ // answer for a non-detached genuine buffer in that case is false.
2472
+ if (optArrayBufferDetached === undefined) {
2473
+ return false;
2474
+ }
2475
+ return apply(optArrayBufferDetached, this, []);
2410
2476
  },
2477
+ /**
2478
+ * @this {ArrayBuffer}
2479
+ */
2411
2480
  get maxByteLength() {
2412
- // Not underlying maxByteLength, which is irrelevant
2413
- return apply(arrayBufferByteLength, getBuffer(this), []);
2481
+ if (isEmulatedImmutable(this)) {
2482
+ // For an emulated immutable buffer, maxByteLength is byteLength: it
2483
+ // cannot grow.
2484
+ return apply(arrayBufferByteLength, amplifyArrayBuffer(this), []);
2485
+ }
2486
+ if (optArrayBufferMaxByteLength === undefined) {
2487
+ return apply(arrayBufferByteLength, this, []);
2488
+ }
2489
+ return apply(optArrayBufferMaxByteLength, this, []);
2414
2490
  },
2491
+ /**
2492
+ * @this {ArrayBuffer}
2493
+ */
2415
2494
  get resizable() {
2416
- getBuffer(this); // shim brand check
2417
- return false;
2495
+ if (isEmulatedImmutable(this)) {
2496
+ return false;
2497
+ }
2498
+ if (optArrayBufferResizable === undefined) {
2499
+ return false;
2500
+ }
2501
+ return apply(optArrayBufferResizable, this, []);
2418
2502
  },
2503
+ /**
2504
+ * @this {ArrayBuffer}
2505
+ */
2419
2506
  get immutable() {
2420
- getBuffer(this); // shim brand check
2421
- return true;
2507
+ return isEmulatedImmutable(this);
2422
2508
  },
2509
+ /**
2510
+ * @this {ArrayBuffer}
2511
+ * @param {number} [start]
2512
+ * @param {number} [end]
2513
+ */
2423
2514
  slice(start = undefined, end = undefined) {
2424
- return arrayBufferSlice(getBuffer(this), start, end);
2515
+ return arrayBufferSlice(amplifyArrayBuffer(this), start, end);
2425
2516
  },
2517
+ /**
2518
+ * @this {ArrayBuffer}
2519
+ * @param {number} [start]
2520
+ * @param {number} [end]
2521
+ */
2426
2522
  sliceToImmutable(start = undefined, end = undefined) {
2427
2523
  // eslint-disable-next-line no-use-before-define
2428
- return sliceBufferToImmutable(getBuffer(this), start, end);
2429
- },
2430
- resize(_newByteLength = undefined) {
2431
- getBuffer(this); // shim brand check
2432
- throw TypeError('Cannot resize an immutable ArrayBuffer');
2524
+ return sliceBufferToImmutable(amplifyArrayBuffer(this), start, end);
2433
2525
  },
2434
- transfer(_newLength = undefined) {
2435
- getBuffer(this); // shim brand check
2436
- throw TypeError('Cannot detach an immutable ArrayBuffer');
2526
+ /**
2527
+ * @this {ArrayBuffer}
2528
+ * @param {number} [newByteLength]
2529
+ */
2530
+ resize(newByteLength = undefined) {
2531
+ if (isEmulatedImmutable(this)) {
2532
+ throw TypeError('Cannot resize an immutable ArrayBuffer');
2533
+ }
2534
+ if (optResize === undefined) {
2535
+ throw TypeError(
2536
+ 'Cannot resize ArrayBuffer: underlying platform lacks ArrayBuffer.prototype.resize',
2537
+ );
2538
+ }
2539
+ return apply(optResize, this, [newByteLength]);
2437
2540
  },
2438
- transferToFixedLength(_newLength = undefined) {
2439
- getBuffer(this); // shim brand check
2440
- throw TypeError('Cannot detach an immutable ArrayBuffer');
2541
+ /**
2542
+ * @this {ArrayBuffer}
2543
+ * @param {number} [newLength]
2544
+ */
2545
+ transfer(newLength = undefined) {
2546
+ if (isEmulatedImmutable(this)) {
2547
+ throw TypeError('Cannot detach an immutable ArrayBuffer');
2548
+ }
2549
+ if (optTransfer === undefined) {
2550
+ throw TypeError(
2551
+ 'Cannot transfer ArrayBuffer: underlying platform lacks ArrayBuffer.prototype.transfer',
2552
+ );
2553
+ }
2554
+ return apply(optTransfer, this, [newLength]);
2441
2555
  },
2442
- transferToImmutable(_newLength = undefined) {
2443
- getBuffer(this); // shim brand check
2444
- throw TypeError('Cannot detach an immutable ArrayBuffer');
2556
+ /**
2557
+ * @this {ArrayBuffer}
2558
+ * @param {number} [newLength]
2559
+ */
2560
+ transferToFixedLength(newLength = undefined) {
2561
+ if (isEmulatedImmutable(this)) {
2562
+ throw TypeError('Cannot detach an immutable ArrayBuffer');
2563
+ }
2564
+ if (optTransferToFixedLength === undefined) {
2565
+ throw TypeError(
2566
+ 'Cannot transferToFixedLength ArrayBuffer: underlying platform lacks ArrayBuffer.prototype.transferToFixedLength',
2567
+ );
2568
+ }
2569
+ return apply(optTransferToFixedLength, this, [newLength]);
2445
2570
  },
2446
2571
  /**
2447
- * See https://github.com/endojs/endo/tree/master/packages/immutable-arraybuffer#purposeful-violation
2572
+ * @this {ArrayBuffer}
2573
+ * @param {number} [newLength]
2448
2574
  */
2449
- [toStringTag]: 'ImmutableArrayBuffer',
2575
+ transferToImmutable(newLength = undefined) {
2576
+ if (isEmulatedImmutable(this)) {
2577
+ throw TypeError('Cannot detach an immutable ArrayBuffer');
2578
+ }
2579
+ // eslint-disable-next-line no-use-before-define
2580
+ if (optTransferBufferToImmutable === undefined) {
2581
+ throw TypeError(
2582
+ 'Cannot transfer to immutable: underlying platform lacks transfer or structuredClone',
2583
+ );
2584
+ }
2585
+ // eslint-disable-next-line no-use-before-define
2586
+ return optTransferBufferToImmutable(this, newLength);
2587
+ },
2450
2588
  };
2451
2589
 
2452
- // Better fidelity emulation of a class prototype
2453
- for (const key of ownKeys(ImmutableArrayBufferInternalPrototype)) {
2454
- defineProperty(ImmutableArrayBufferInternalPrototype, key, {
2590
+ // Better fidelity emulation of a class prototype: each property is
2591
+ // non-enumerable, matching the shape `ArrayBuffer.prototype` itself uses.
2592
+ $h͏_once.immutableArrayBufferLibProperties(immutableArrayBufferLibProperties);for(const key of ownKeys(immutableArrayBufferLibProperties)){
2593
+ defineProperty(immutableArrayBufferLibProperties, key, {
2455
2594
  enumerable: false,
2456
2595
  });
2457
2596
  }
2597
+ freeze(immutableArrayBufferLibProperties);
2598
+
2599
+ // Internal-test export. The helper itself is load-bearing for every
2600
+ // method on `immutableArrayBufferLibProperties`, but the package's
2601
+ // public export surface intentionally keeps it private (callers either
2602
+ // touch the helper indirectly through `ArrayBuffer.prototype` methods
2603
+ // or rely on `isBufferImmutable`). The export exists so the
2604
+ // adversarial-tests skill can exercise the helper in isolation.
2605
+
2458
2606
 
2459
2607
  /**
2460
2608
  * Emulates what would have been the encapsulated `ImmutableArrayBufferInternal`
@@ -2462,18 +2610,39 @@ for (const key of ownKeys(ImmutableArrayBufferInternalPrototype)) {
2462
2610
  * result encapsulates. Security demands that this result has exclusive access
2463
2611
  * to the `realBuffer` it is given, which its callers must ensure.
2464
2612
  *
2613
+ * The emulated immutable buffer directly inherits from `ArrayBuffer.prototype`.
2614
+ * The brand WeakMap is the sole discriminator: `ArrayBuffer.prototype`'s
2615
+ * methods (after the shim installs the lib properties) check brand membership
2616
+ * to decide whether to treat the receiver as immutable.
2617
+ *
2465
2618
  * @param {ArrayBuffer} realBuffer
2466
2619
  * @returns {ArrayBuffer}
2467
2620
  */
2468
2621
  const makeImmutableArrayBufferInternal = realBuffer => {
2469
2622
  const result = /** @type {ArrayBuffer} */ (
2470
2623
  /** @type {unknown} */ ({
2471
- __proto__: ImmutableArrayBufferInternalPrototype,
2624
+ __proto__: arrayBufferPrototype,
2472
2625
  })
2473
2626
  );
2474
- // Safe because this WeakMap owns its set method.
2475
- // eslint-disable-next-line @endo/no-polymorphic-call
2476
- buffers.set(result, realBuffer);
2627
+ // Install `[Symbol.toStringTag] = 'ImmutableArrayBuffer'` as an own
2628
+ // property of each emulated immutable buffer (not on the shared prototype,
2629
+ // which must retain the genuine `'ArrayBuffer'` tag so genuine instances
2630
+ // continue to read as `[object ArrayBuffer]`). This is the minimum
2631
+ // departure from DESIGN.md Move 2 paragraph 7 needed to keep
2632
+ // `concordance` (and any downstream consumer that sniffs the toStringTag)
2633
+ // from misrouting an emulated immutable through `Buffer.from`, which
2634
+ // throws because the emulated immutable is not a genuine exotic. With the
2635
+ // own-property slot in place, `Object.prototype.toString.call(immuAB)`
2636
+ // returns `'[object ImmutableArrayBuffer]'` and concordance routes the
2637
+ // value through its unrenderable-value path. Genuine ArrayBuffers
2638
+ // continue to inherit `'ArrayBuffer'` from the prototype.
2639
+ defineProperty(result, Symbol.toStringTag, {
2640
+ value: 'ImmutableArrayBuffer',
2641
+ writable: false,
2642
+ enumerable: false,
2643
+ configurable: false,
2644
+ });
2645
+ apply(weakmapSet, buffers, [result, realBuffer]);
2477
2646
  return result;
2478
2647
  };
2479
2648
  // Since `makeImmutableArrayBufferInternal` MUST not escape,
@@ -2481,14 +2650,27 @@ const makeImmutableArrayBufferInternal = realBuffer => {
2481
2650
  freeze(makeImmutableArrayBufferInternal);
2482
2651
 
2483
2652
  /**
2653
+ * Internal brand check. Returns `true` when `buffer` is an emulated
2654
+ * immutable buffer (in the lib's brand WeakMap), `false` otherwise. After
2655
+ * the premise-2 fold-in the package no longer exports this from a public
2656
+ * entry point; callers use `buffer.immutable` (the accessor installed by
2657
+ * the shim on `ArrayBuffer.prototype`) or `Object.prototype.toString
2658
+ * .call(buffer) === '[object ImmutableArrayBuffer]'`. The internal export
2659
+ * lets the in-package tests (`test/lib-*.test.js`) reach the helper
2660
+ * directly without round-tripping through the prototype.
2661
+ *
2484
2662
  * @param {ArrayBuffer} buffer
2485
2663
  * @returns {boolean}
2486
2664
  */
2487
- // eslint-disable-next-line @endo/no-polymorphic-call
2488
- const isBufferImmutable = buffer => buffers.has(buffer);
2665
+ const isBufferImmutable = buffer => isEmulatedImmutable(buffer);
2489
2666
 
2490
2667
  /**
2491
- * Creates an immutable slice of the given buffer.
2668
+ * Creates an immutable slice of the given buffer. Internal helper used by
2669
+ * `immutableArrayBufferLibProperties.sliceToImmutable` and by the shim's
2670
+ * own install. After the premise-2 fold-in the package no longer exports
2671
+ * this from a public entry point; the internal export lets the in-package
2672
+ * tests reach it directly.
2673
+ *
2492
2674
  * @param {ArrayBuffer} buffer The original buffer.
2493
2675
  * @param {number} [start] The start index.
2494
2676
  * @param {number} [end] The end index.
@@ -2499,9 +2681,7 @@ freeze(makeImmutableArrayBufferInternal);
2499
2681
  start = undefined,
2500
2682
  end = undefined,
2501
2683
  ) => {
2502
- // Safe because this WeakMap owns its get method.
2503
- // eslint-disable-next-line @endo/no-polymorphic-call
2504
- let realBuffer = buffers.get(buffer);
2684
+ let realBuffer = apply(weakmapGet, buffers, [buffer]);
2505
2685
  if (realBuffer === undefined) {
2506
2686
  realBuffer = buffer;
2507
2687
  }
@@ -2513,7 +2693,9 @@ freeze(makeImmutableArrayBufferInternal);
2513
2693
  let transferBufferToImmutable;
2514
2694
  if (optArrayBufferTransfer) {
2515
2695
  /**
2516
- * Transfer the contents to a new Immutable ArrayBuffer
2696
+ * Transfer the contents to a new Immutable ArrayBuffer. Internal helper
2697
+ * used by `immutableArrayBufferLibProperties.transferToImmutable` and by
2698
+ * the shim's own install. Not part of the package's public export surface.
2517
2699
  *
2518
2700
  * @param {ArrayBuffer} buffer The original buffer.
2519
2701
  * @param {number} [newLength] The start index.
@@ -2527,7 +2709,7 @@ if (optArrayBufferTransfer) {
2527
2709
  } else {
2528
2710
  buffer = optArrayBufferTransfer(buffer);
2529
2711
  const oldLength = buffer.byteLength;
2530
- // eslint-disable-next-line @endo/restrict-comparison-operands
2712
+
2531
2713
  if (newLength <= oldLength) {
2532
2714
  buffer = arrayBufferSlice(buffer, 0, newLength);
2533
2715
  } else {
@@ -2547,108 +2729,45 @@ if (optArrayBufferTransfer) {
2547
2729
  const optTransferBufferToImmutable = transferBufferToImmutable;$h͏_once.optTransferBufferToImmutable(optTransferBufferToImmutable);
2548
2730
  })()
2549
2731
  ,
2550
- // === 5. immutable-arraybuffer ./src/immutable-arraybuffer-shim.js ===
2551
- ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';let isBufferImmutable,sliceBufferToImmutable,optXferBuf2Immu;$h͏_imports([["./immutable-arraybuffer-pony.js", [["isBufferImmutable",[$h͏_a => (isBufferImmutable = $h͏_a)]],["sliceBufferToImmutable",[$h͏_a => (sliceBufferToImmutable = $h͏_a)]],["optTransferBufferToImmutable",[$h͏_a => (optXferBuf2Immu = $h͏_a)]]]]]);
2552
-
2553
-
2554
-
2555
-
2556
-
2557
-
2558
-
2559
- const {
2560
- ArrayBuffer,
2561
- JSON,
2562
- Object,
2563
- Reflect
2564
- // eslint-disable-next-line no-restricted-globals
2565
- } = globalThis;
2732
+ // === 5. immutable-arraybuffer ./src/shim.js ===
2733
+ ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';let immutableArrayBufferLibProperties;$h͏_imports([["./lib.js", [["immutableArrayBufferLibProperties",[$h͏_a => (immutableArrayBufferLibProperties = $h͏_a)]]]]]);
2566
2734
 
2567
- // Even though the imported one is not exported by the pony as a live binding,
2568
- // TS doesn't know that,
2569
- // so it cannot do its normal flow-based inference. By making and using a local
2570
- // copy, no problem.
2571
- const optTransferBufferToImmutable = optXferBuf2Immu;
2735
+ // eslint-disable-next-line no-restricted-globals
2736
+ const { ArrayBuffer, Object } = globalThis;
2572
2737
 
2573
- const { getOwnPropertyDescriptors, defineProperties, defineProperty } = Object;
2574
- const { ownKeys } = Reflect;
2738
+ const { getOwnPropertyDescriptors, defineProperties } = Object;
2575
2739
  const { prototype: arrayBufferPrototype } = ArrayBuffer;
2576
- const { stringify } = JSON;
2577
-
2578
- const arrayBufferMethods = {
2579
- /**
2580
- * Creates an immutable slice of the given buffer.
2581
- *
2582
- * @this {ArrayBuffer} buffer The original buffer.
2583
- * @param {number} [start] The start index.
2584
- * @param {number} [end] The end index.
2585
- * @returns {ArrayBuffer} The sliced immutable ArrayBuffer.
2586
- */
2587
- sliceToImmutable(start = undefined, end = undefined) {
2588
- return sliceBufferToImmutable(this, start, end);
2589
- },
2590
-
2591
- /**
2592
- * @this {ArrayBuffer}
2593
- */
2594
- get immutable() {
2595
- return isBufferImmutable(this);
2596
- },
2597
-
2598
- ...(optTransferBufferToImmutable
2599
- ? {
2600
- /**
2601
- * Transfer the contents to a new immutable ArrayBuffer
2602
- *
2603
- * @this {ArrayBuffer} buffer The original buffer.
2604
- * @param {number} [newLength] The start index.
2605
- * @returns {ArrayBuffer} The new immutable ArrayBuffer.
2606
- */
2607
- transferToImmutable(newLength = undefined) {
2608
- return optTransferBufferToImmutable(this, newLength);
2609
- },
2610
- }
2611
- : {}),
2612
- };
2613
-
2614
- // Better fidelity emulation of a class prototype
2615
- for (const key of ownKeys(arrayBufferMethods)) {
2616
- defineProperty(arrayBufferMethods, key, {
2617
- enumerable: false,
2618
- });
2619
- }
2620
2740
 
2621
- // Modern shim practice frowns on conditional installation, at least for
2622
- // proposals prior to stage 3. This is so changes to the proposal since
2623
- // an old shim was distributed don't need to worry about the proposal
2624
- // breaking old code depending on the old shim. Thus, if we detect that
2625
- // we're about to overwrite a prior installation, we simply issue this
2626
- // warning and continue.
2741
+ // Stage-3 install policy: detect-then-skip.
2627
2742
  //
2628
- // TODO, if the primordials are frozen after the prior implementation, such as
2629
- // by `lockdown`, then this precludes overwriting as expected. However, for
2630
- // this case, the following warning text will be confusing.
2743
+ // Both the Immutable ArrayBuffer proposal and the parallel Freezable
2744
+ // TypedArray proposal are part of the same TC39 proposal, which has
2745
+ // reached stage 3. At stage 3 or above our policy is detect-then-skip:
2746
+ // if a prior installation (a native implementation, or a previously
2747
+ // loaded shim) has already provided `sliceToImmutable` on
2748
+ // `ArrayBuffer.prototype`, we defer to that installation rather than
2749
+ // overwriting it. The native implementation always wins.
2631
2750
  //
2632
- // Allowing polymorphic calls because these occur during initialization.
2633
- // eslint-disable-next-line @endo/no-polymorphic-call
2634
- const overwrites = ownKeys(arrayBufferMethods).filter(
2635
- key => key in arrayBufferPrototype,
2636
- );
2637
- if (overwrites.length > 0) {
2638
- // eslint-disable-next-line @endo/no-polymorphic-call
2639
- console.warn(
2640
- `About to overwrite ArrayBuffer.prototype properties ${stringify(overwrites)}`,
2751
+ // `sliceToImmutable` is the load-bearing presence check: the proposal
2752
+ // adds `sliceToImmutable`, `transferToImmutable`, and the `immutable`
2753
+ // accessor as a unit, and any installer (native or shim) that provides
2754
+ // one provides all three. Checking only one keeps the detect-then-skip
2755
+ // branch deterministic.
2756
+ //
2757
+ // For proposals prior to stage 3 a warn-and-overwrite policy would be
2758
+ // appropriate so the shim stays authoritative across partial or
2759
+ // divergent platform implementations. The Immutable ArrayBuffer proposal
2760
+ // is past that threshold.
2761
+ if (!('sliceToImmutable' in arrayBufferPrototype)) {
2762
+ defineProperties(
2763
+ arrayBufferPrototype,
2764
+ getOwnPropertyDescriptors(immutableArrayBufferLibProperties),
2641
2765
  );
2642
2766
  }
2643
-
2644
- defineProperties(
2645
- arrayBufferPrototype,
2646
- getOwnPropertyDescriptors(arrayBufferMethods),
2647
- );
2648
2767
  })()
2649
2768
  ,
2650
2769
  // === 6. immutable-arraybuffer ./shim.js ===
2651
- ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';$h͏_imports([["./src/immutable-arraybuffer-shim.js", []]]);
2770
+ ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';$h͏_imports([["./src/shim.js", []]]);
2652
2771
  })()
2653
2772
  ,
2654
2773
  // === 7. ses ./src/error/stringify-utils.js ===
@@ -2705,7 +2824,7 @@ defineProperties(
2705
2824
  * @param {string} str The noun to prepend
2706
2825
  * @returns {string} The noun prepended with a/an
2707
2826
  */$h͏_once.enJoin(enJoin);
2708
- const an = str => {
2827
+ const an = str => {
2709
2828
  str = `${str}`;
2710
2829
  if (str.length >= 1 && stringIncludes('aeiouAEIOU', str[0])) {
2711
2830
  return `an ${str}`;
@@ -2714,7 +2833,6 @@ const an = str => {
2714
2833
  };$h͏_once.an(an);
2715
2834
  freeze(an);
2716
2835
 
2717
-
2718
2836
  /**
2719
2837
  * Like `JSON.stringify` but does not blow up if given a cycle or a bigint.
2720
2838
  * This is not
@@ -2742,7 +2860,7 @@ freeze(an);
2742
2860
  * @param {(string|number)=} spaces
2743
2861
  * @returns {string}
2744
2862
  */
2745
- const bestEffortStringify = (payload, spaces = undefined) => {
2863
+ const bestEffortStringify = (payload, spaces = undefined) => {
2746
2864
  const seenSet = new Set();
2747
2865
  const replacer = (_, val) => {
2748
2866
  switch (typeof val) {
@@ -3013,21 +3131,17 @@ freeze(bestEffortStringify);
3013
3131
  ,
3014
3132
  // === 10. cache-map ./src/cachemap.js ===
3015
3133
  ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';$h͏_imports([]);// @ts-check
3016
- /* global globalThis */
3017
- /* eslint-disable @endo/no-polymorphic-call */
3018
3134
 
3019
- // eslint-disable-next-line no-restricted-globals
3020
3135
  const { Error, TypeError, WeakMap } = globalThis;
3021
- // eslint-disable-next-line no-restricted-globals
3136
+
3022
3137
  const { parse, stringify } = JSON;
3023
- // eslint-disable-next-line no-restricted-globals
3138
+
3024
3139
  const { isSafeInteger } = Number;
3025
- // eslint-disable-next-line no-restricted-globals
3140
+
3026
3141
  const { freeze } = Object;
3027
- // eslint-disable-next-line no-restricted-globals
3142
+
3028
3143
  const { toStringTag: toStringTagSymbol } = Symbol;
3029
3144
 
3030
- // eslint-disable-next-line no-restricted-globals
3031
3145
  const UNKNOWN_KEY = Symbol('UNKNOWN_KEY');
3032
3146
 
3033
3147
  /**
@@ -3206,7 +3320,7 @@ const zeroMetrics = freeze({
3206
3320
  // @ts-expect-error
3207
3321
  MaybeCtor();
3208
3322
  return /** @type {any} */ (MaybeCtor);
3209
- } catch (err) {
3323
+ } catch (_err) {
3210
3324
  // @ts-expect-error
3211
3325
  const constructNewMap = () => new MaybeCtor();
3212
3326
  return constructNewMap;
@@ -3466,7 +3580,17 @@ freeze(makeNoteLogArgsArrayKit);
3466
3580
 
3467
3581
 
3468
3582
  /**
3469
- * @import {BaseAssert, Assert, AssertionFunctions, AssertionUtilities, DeprecatedAssertionUtilities, Stringable, DetailsToken, MakeAssert} from '../../types.js';
3583
+ * @import {BaseAssert,
3584
+ * Assert,
3585
+ * AssertionFunctions,
3586
+ * AssertionUtilities,
3587
+ * DeprecatedAssertionUtilities,
3588
+ * Stringable,
3589
+ * DetailsToken,
3590
+ * MakeAssert,
3591
+ * Details,
3592
+ * GenericErrorConstructor,
3593
+ * AssertMakeErrorOptions} from '../../types.js';
3470
3594
  * @import {LogArgs, NoteCallback, LoggedErrorHandler} from './internal-types.js';
3471
3595
  */
3472
3596
 
@@ -3703,7 +3827,7 @@ const tagError = (err, optErrorName = err.name) => {
3703
3827
  * such as `stack` on v8 (Chrome, Brave, Edge?)
3704
3828
  * - `sanitizeError` will freeze the error, preventing any correct engine from
3705
3829
  * adding or
3706
- * altering any of the error's own properties `sanitizeError` is done.
3830
+ * altering any of the error's own properties once `sanitizeError` is done.
3707
3831
  *
3708
3832
  * However, `sanitizeError` will not, for example, `harden`
3709
3833
  * (i.e., deeply freeze)
@@ -3723,10 +3847,16 @@ const tagError = (err, optErrorName = err.name) => {
3723
3847
  errors: _errorsDesc = undefined,
3724
3848
  cause: _causeDesc = undefined,
3725
3849
  stack: _stackDesc = undefined,
3850
+ code: codeDesc = undefined,
3726
3851
  ...restDescs
3727
3852
  } = descs;
3728
3853
 
3729
3854
  const restNames = ownKeys(restDescs);
3855
+
3856
+ // the spec allows any value, but we drop 'code' if it's not a string
3857
+ if (codeDesc?.value !== undefined && typeof codeDesc.value !== 'string') {
3858
+ arrayPush(restNames, 'code');
3859
+ }
3730
3860
  if (restNames.length >= 1) {
3731
3861
  for (const name of restNames) {
3732
3862
  delete error[name];
@@ -3751,34 +3881,51 @@ const tagError = (err, optErrorName = err.name) => {
3751
3881
  * @type {AssertionUtilities['makeError']}
3752
3882
  */$h͏_once.sanitizeError(sanitizeError);
3753
3883
  const makeError = (
3754
- optDetails = redactedDetails`Assert failed`,
3755
- errConstructor = globalThis.Error,
3884
+ optDetails,
3885
+ errConstructor,
3756
3886
  {
3757
3887
  errorName = undefined,
3758
3888
  cause = undefined,
3759
3889
  errors = undefined,
3760
3890
  sanitize = true,
3891
+ code = undefined,
3761
3892
  } = {},
3762
3893
  ) => {
3894
+ // The first two parameters above cannot be inferred unless this is rewritten
3895
+ // as a function declaration using an @overload tag. This is a workaround so
3896
+ // that we at least have type-safety within the function body.
3897
+ //
3898
+ // Note that due to the overload of AssertionUtilities['makeError'], strict
3899
+ // Note that due to the overload of AssertionUtilities['makeError'], Typescript's so-called "strict
3900
+ // mode" will complain if default parameters are provided in the method
3901
+ // signature. The below workaround (optDetails -> details; errConstructor ->
3902
+ // errCtor) is functionally equivalent but allows us to use type assertions to
3903
+ // workaround the issue with TypeScript's so-called "strict mode".
3904
+ let details = /** @type {Details} */ (
3905
+ optDetails ?? redactedDetails`Assert failed`
3906
+ );
3907
+
3908
+ // Internally, this is a GenericErrorConstructor, but externally it can be
3909
+ // some T which extends GenericErrorConstructor.
3910
+ const errCtor = /** @type {GenericErrorConstructor} */ (
3911
+ errConstructor ?? globalThis.Error
3912
+ );
3763
3913
  // Promote string-valued `optDetails` into a minimal DetailsParts
3764
3914
  // consisting of that string as the sole literal part with no substitutions.
3765
- if (typeof optDetails === 'string') {
3766
- optDetails = redactedDetails([optDetails]);
3915
+ if (typeof details === 'string') {
3916
+ details = redactedDetails([details]);
3767
3917
  }
3768
- const hiddenDetails = weakmapGet(hiddenDetailsMap, optDetails);
3918
+ const hiddenDetails = weakmapGet(hiddenDetailsMap, details);
3769
3919
  if (hiddenDetails === undefined) {
3770
- throw TypeError(`unrecognized details ${quote(optDetails)}`);
3920
+ throw TypeError(`unrecognized details ${quote(details)}`);
3771
3921
  }
3772
3922
  const messageString = getMessageString(hiddenDetails);
3773
3923
  const opts = cause && { cause };
3774
3924
  let error;
3775
- if (
3776
- typeof AggregateError !== 'undefined' &&
3777
- errConstructor === AggregateError
3778
- ) {
3925
+ if (typeof AggregateError !== 'undefined' && errCtor === AggregateError) {
3779
3926
  error = AggregateError(errors || [], messageString, opts);
3780
3927
  } else {
3781
- const ErrorCtor = /** @type {ErrorConstructor} */ (errConstructor);
3928
+ const ErrorCtor = /** @type {ErrorConstructor} */ (errCtor);
3782
3929
  error = ErrorCtor(messageString, opts);
3783
3930
  // Since we need to tolerate `errors` on an AggregateError, we may as well
3784
3931
  // tolerate it on all errors.
@@ -3791,6 +3938,14 @@ const makeError = (
3791
3938
  });
3792
3939
  }
3793
3940
  }
3941
+ if (code !== undefined) {
3942
+ defineProperty(error, 'code', {
3943
+ value: code,
3944
+ writable: true,
3945
+ enumerable: false,
3946
+ configurable: true,
3947
+ });
3948
+ }
3794
3949
  weakmapSet(hiddenMessageLogArgs, error, getLogArgs(hiddenDetails));
3795
3950
  if (errorName !== undefined) {
3796
3951
  tagError(error, errorName);
@@ -3798,7 +3953,11 @@ const makeError = (
3798
3953
  if (sanitize) {
3799
3954
  sanitizeError(error);
3800
3955
  }
3801
- // The next line is a particularly fruitful place to put a breakpoint.
3956
+ // Externally, the return type below is InstanceType<T> where T extends
3957
+ // GenericErrorConstructor. Internally, it's
3958
+ // InstanceType<GenericErrorConstructor> for simplicity of implementation.
3959
+
3960
+ // The next line is a particularly fruitful place to put a breakpoint.
3802
3961
  return error;
3803
3962
  };$h͏_once.makeError(makeError);
3804
3963
  freeze(makeError);
@@ -4373,7 +4532,7 @@ const freezeTypedArray = array => {
4373
4532
  /** @import {GenericErrorConstructor} from '../types.js' */
4374
4533
 
4375
4534
  /**
4376
- * Exports {@code permits}, a recursively defined
4535
+ * Exports `permits`, a recursively defined
4377
4536
  * JSON record enumerating all intrinsics and their properties
4378
4537
  * according to ECMA specs.
4379
4538
  *
@@ -4469,6 +4628,15 @@ const freezeTypedArray = array => {
4469
4628
  JSON: 'JSON',
4470
4629
  Reflect: 'Reflect',
4471
4630
 
4631
+ // WHATWG Encoding Standard
4632
+ // https://encoding.spec.whatwg.org/
4633
+ // TextEncoder and TextDecoder are pure transformations between string and
4634
+ // Uint8Array with no static side channels and no exposed iterator
4635
+ // prototype. They are permitted universally; on hosts that do not provide
4636
+ // them (XS), the sampling pass tolerates the absence.
4637
+ TextEncoder: 'TextEncoder',
4638
+ TextDecoder: 'TextDecoder',
4639
+
4472
4640
  // *** Annex B
4473
4641
 
4474
4642
  escape: 'escape',
@@ -4626,20 +4794,20 @@ if (typeof AggregateError !== 'undefined') {
4626
4794
  * are also considered blacklisted and are removed.
4627
4795
  * <li>A string value equal to a primitive ("number", "string", etc),
4628
4796
  * in which case the property is permitted if its value property
4629
- * is typeof the given type. For example, {@code "Infinity"} leads to
4630
- * "number" and property values that fail {@code typeof "number"}.
4797
+ * is typeof the given type. For example, `Infinity` leads to
4798
+ * "number" and property values that fail `typeof "number`.
4631
4799
  * are removed.
4632
4800
  * <li>A string value equal to an intinsic name ("ObjectPrototype",
4633
4801
  * "Array", etc), in which case the property permitted if its
4634
4802
  * value property is equal to the value of the corresponfing
4635
- * intrinsics. For example, {@code Map.prototype} leads to
4803
+ * intrinsics. For example, `Map.prototype` leads to
4636
4804
  * "MapPrototype" and the property is removed if its value is
4637
4805
  * not equal to %MapPrototype%
4638
4806
  * <li>Another record, in which case this property is simply
4639
4807
  * permitted and that next record represents the disposition of
4640
- * the object which is its value. For example, {@code "Object"}
4641
- * leads to another record explaining what properties {@code
4642
- * "Object"} may have and how each such property should be treated.
4808
+ * the object which is its value. For example, `Object`
4809
+ * leads to another record explaining what properties
4810
+ * `Object` may have and how each such property should be treated.
4643
4811
  *
4644
4812
  * <p>Notes:
4645
4813
  * <li>"[[Proto]]" is used to refer to the "[[Prototype]]" internal
@@ -5754,30 +5922,6 @@ const CommonMath = {
5754
5922
  immutable: getter,
5755
5923
  },
5756
5924
 
5757
- // If this exists, it is purely an artifact of how we currently shim
5758
- // `transferToImmutable`. As natively implemented, there would be no
5759
- // such extra prototype.
5760
- '%ImmutableArrayBufferPrototype%': {
5761
- '[[Proto]]': '%ArrayBufferPrototype%',
5762
- byteLength: getter,
5763
- slice: fn,
5764
- // See https://github.com/endojs/endo/tree/master/packages/immutable-arraybuffer#purposeful-violation
5765
- '@@toStringTag': 'string',
5766
- // See https://github.com/tc39/proposal-resizablearraybuffer
5767
- transfer: fn,
5768
- resize: fn,
5769
- resizable: getter,
5770
- maxByteLength: getter,
5771
- // https://github.com/tc39/proposal-arraybuffer-transfer
5772
- transferToFixedLength: fn,
5773
- detached: getter,
5774
- // https://github.com/endojs/endo/pull/2309#issuecomment-2155513240
5775
- // to be proposed
5776
- transferToImmutable: fn,
5777
- sliceToImmutable: fn,
5778
- immutable: getter,
5779
- },
5780
-
5781
5925
  // SharedArrayBuffer Objects
5782
5926
  SharedArrayBuffer: false, // UNSAFE and purposely suppressed.
5783
5927
  '%SharedArrayBufferPrototype%': false, // UNSAFE and purposely suppressed.
@@ -6450,6 +6594,44 @@ const CommonMath = {
6450
6594
  '@@toStringTag': 'string',
6451
6595
  },
6452
6596
 
6597
+ // WHATWG Encoding Standard
6598
+ // https://encoding.spec.whatwg.org/
6599
+
6600
+ TextEncoder: {
6601
+ // Properties of the TextEncoder Constructor
6602
+ '[[Proto]]': '%FunctionPrototype%',
6603
+ prototype: '%TextEncoderPrototype%',
6604
+ },
6605
+
6606
+ '%TextEncoderPrototype%': {
6607
+ constructor: 'TextEncoder',
6608
+ encode: fn,
6609
+ encodeInto: fn,
6610
+ encoding: getter,
6611
+ '@@toStringTag': 'string',
6612
+
6613
+ // Non-standard property used by Node.js
6614
+ 'RegisteredSymbol(nodejs.util.inspect.custom)': false,
6615
+ },
6616
+
6617
+ TextDecoder: {
6618
+ // Properties of the TextDecoder Constructor
6619
+ '[[Proto]]': '%FunctionPrototype%',
6620
+ prototype: '%TextDecoderPrototype%',
6621
+ },
6622
+
6623
+ '%TextDecoderPrototype%': {
6624
+ constructor: 'TextDecoder',
6625
+ decode: fn,
6626
+ encoding: getter,
6627
+ fatal: getter,
6628
+ ignoreBOM: getter,
6629
+ '@@toStringTag': 'string',
6630
+
6631
+ // Non-standard property used by Node.js
6632
+ 'RegisteredSymbol(nodejs.util.inspect.custom)': false,
6633
+ },
6634
+
6453
6635
  // Appendix B
6454
6636
 
6455
6637
  // Annex B: Additional Properties of the Global Object
@@ -6480,6 +6662,7 @@ const CommonMath = {
6480
6662
  load: asyncFn,
6481
6663
  importNow: fn,
6482
6664
  module: fn,
6665
+ __noNamespaceBox__: getter,
6483
6666
  '@@toStringTag': 'string',
6484
6667
  },
6485
6668
 
@@ -7023,7 +7206,7 @@ function sampleGlobals(globalObject, newPropertyNames) {
7023
7206
  // Verify that the method is not callable.
7024
7207
  // eslint-disable-next-line @endo/no-polymorphic-call
7025
7208
  FERAL_FUNCTION.prototype.constructor('return 1');
7026
- } catch (ignore) {
7209
+ } catch (_err) {
7027
7210
  // Throws, no need to patch.
7028
7211
  return freeze({});
7029
7212
  }
@@ -7693,71 +7876,62 @@ const methods = {
7693
7876
  // === 25. ses ./src/enablements.js ===
7694
7877
  ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';let toStringTagSymbol,iteratorSymbol;$h͏_imports([["./commons.js", [["toStringTagSymbol",[$h͏_a => (toStringTagSymbol = $h͏_a)]],["iteratorSymbol",[$h͏_a => (iteratorSymbol = $h͏_a)]]]]]);
7695
7878
 
7696
- /**
7697
- * Exports {@code enablements}, a recursively defined
7698
- * JSON record defining the optimum set of intrinsics properties
7699
- * that need to be "repaired" before hardening is applied on
7700
- * enviromments subject to the override mistake.
7701
- *
7702
- * @author JF Paradis
7703
- * @author Mark S. Miller
7704
- *
7705
- * @module
7706
- */
7879
+
7880
+
7881
+
7882
+
7883
+
7884
+
7885
+
7886
+
7887
+
7888
+
7889
+
7890
+
7891
+
7892
+
7893
+
7894
+
7895
+
7896
+
7897
+
7898
+
7899
+
7900
+
7901
+
7902
+
7903
+
7904
+
7905
+
7906
+
7907
+
7908
+
7909
+
7910
+
7911
+
7912
+
7913
+
7914
+
7915
+
7916
+
7917
+
7918
+
7919
+
7920
+
7921
+
7922
+
7923
+
7924
+
7925
+
7926
+
7927
+
7928
+
7929
+
7930
+
7707
7931
 
7708
7932
  /**
7709
- * <p>Because "repairing" replaces data properties with accessors, every
7710
- * time a repaired property is accessed, the associated getter is invoked,
7711
- * which degrades the runtime performance of all code executing in the
7712
- * repaired enviromment, compared to the non-repaired case. In order
7713
- * to maintain performance, we only repair the properties of objects
7714
- * for which hardening causes a breakage of their normal intended usage.
7715
- *
7716
- * There are three unwanted cases:
7717
- * <ul>
7718
- * <li>Overriding properties on objects typically used as records,
7719
- * namely {@code "Object"} and {@code "Array"}. In the case of arrays,
7720
- * the situation is unintentional, a given program might not be aware
7721
- * that non-numerical properties are stored on the underlying object
7722
- * instance, not on the array. When an object is typically used as a
7723
- * map, we repair all of its prototype properties.
7724
- * <li>Overriding properties on objects that provide defaults on their
7725
- * prototype and that programs typically set using an assignment, such as
7726
- * {@code "Error.prototype.message"} and {@code "Function.prototype.name"}
7727
- * (both default to "").
7728
- * <li>Setting-up a prototype chain, where a constructor is set to extend
7729
- * another one. This is typically set by assignment, for example
7730
- * {@code "Child.prototype.constructor = Child"}, instead of invoking
7731
- * Object.defineProperty();
7732
- *
7733
- * <p>Each JSON record enumerates the disposition of the properties on
7734
- * some corresponding intrinsic object.
7735
- *
7736
- * <p>For each such record, the values associated with its property
7737
- * names can be:
7738
- * <ul>
7739
- * <li>true, in which case this property is simply repaired. The
7740
- * value associated with that property is not traversed. For
7741
- * example, {@code "Function.prototype.name"} leads to true,
7742
- * meaning that the {@code "name"} property of {@code
7743
- * "Function.prototype"} should be repaired (which is needed
7744
- * when inheriting from @code{Function} and setting the subclass's
7745
- * {@code "prototype.name"} property). If the property is
7746
- * already an accessor property, it is not repaired (because
7747
- * accessors are not subject to the override mistake).
7748
- * <li>"*", in which case this property is not repaired but the
7749
- * value associated with that property are traversed and repaired.
7750
- * <li>Another record, in which case this property is not repaired
7751
- * and that next record represents the disposition of the object
7752
- * which is its value. For example,{@code "FunctionPrototype"}
7753
- * leads to another record explaining which properties {@code
7754
- * Function.prototype} need to be repaired.
7755
- */
7756
-
7757
- /**
7758
- * Minimal enablements when all the code is modern and known not to
7759
- * step into the override mistake, except for the following pervasive
7760
- * cases.
7933
+ * Minimal enablements when all the code is modern and known not to step into
7934
+ * the override mistake, except for the following pervasive cases.
7761
7935
  */
7762
7936
  const minEnablements = {
7763
7937
  '%ObjectPrototype%': {
@@ -8843,7 +9017,8 @@ const sourceMetaEntriesRegExp = freezeRegexp(
8843
9017
  })()
8844
9018
  ,
8845
9019
  // === 35. ses ./src/transforms.js ===
8846
- ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';let FERAL_REG_EXP,SyntaxError,freezeRegexp,regexpReplace,regexpSearch,sealRegexp,stringSlice,stringSplit,freeze,getSourceURL;$h͏_imports([["./commons.js", [["FERAL_REG_EXP",[$h͏_a => (FERAL_REG_EXP = $h͏_a)]],["SyntaxError",[$h͏_a => (SyntaxError = $h͏_a)]],["freezeRegexp",[$h͏_a => (freezeRegexp = $h͏_a)]],["regexpReplace",[$h͏_a => (regexpReplace = $h͏_a)]],["regexpSearch",[$h͏_a => (regexpSearch = $h͏_a)]],["sealRegexp",[$h͏_a => (sealRegexp = $h͏_a)]],["stringSlice",[$h͏_a => (stringSlice = $h͏_a)]],["stringSplit",[$h͏_a => (stringSplit = $h͏_a)]],["freeze",[$h͏_a => (freeze = $h͏_a)]]]],["./get-source-url.js", [["getSourceURL",[$h͏_a => (getSourceURL = $h͏_a)]]]]]);
9020
+ ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';let FERAL_REG_EXP,SyntaxError,freezeRegexp,regexpExec,regexpReplace,regexpSearch,sealRegexp,stringSlice,stringSplit,freeze,getSourceURL;$h͏_imports([["./commons.js", [["FERAL_REG_EXP",[$h͏_a => (FERAL_REG_EXP = $h͏_a)]],["SyntaxError",[$h͏_a => (SyntaxError = $h͏_a)]],["freezeRegexp",[$h͏_a => (freezeRegexp = $h͏_a)]],["regexpExec",[$h͏_a => (regexpExec = $h͏_a)]],["regexpReplace",[$h͏_a => (regexpReplace = $h͏_a)]],["regexpSearch",[$h͏_a => (regexpSearch = $h͏_a)]],["sealRegexp",[$h͏_a => (sealRegexp = $h͏_a)]],["stringSlice",[$h͏_a => (stringSlice = $h͏_a)]],["stringSplit",[$h͏_a => (stringSplit = $h͏_a)]],["freeze",[$h͏_a => (freeze = $h͏_a)]]]],["./get-source-url.js", [["getSourceURL",[$h͏_a => (getSourceURL = $h͏_a)]]]]]);
9021
+
8847
9022
 
8848
9023
 
8849
9024
 
@@ -8955,9 +9130,79 @@ const htmlCommentPattern = sealRegexp(
8955
9130
  // /////////////////////////////////////////////////////////////////////////////
8956
9131
  $h͏_once.evadeHtmlCommentTest(evadeHtmlCommentTest);
8957
9132
  const importPattern = sealRegexp(
8958
- new FERAL_REG_EXP('(^|[^.]|\\.\\.\\.)\\bimport(\\s*(?:\\(|/[/*]))', 'g'),
9133
+ new FERAL_REG_EXP('(^|[^.]|\\.\\.\\.)\\bimport(\\s*(?:\\(|\\.|/[/*]))', 'g'),
9134
+ );
9135
+
9136
+ /**
9137
+ * Matches one line of a run of `//# sourceURL=` and `//# sourceMappingURL=`
9138
+ * comments at the very end of the source (`sourceMetaTrailerStart` finds
9139
+ * the run), as module-source, compartment-mapper and
9140
+ * bundlers append to evaluated code (a module's location may well contain
9141
+ * `import.`, as in `conditional-import.js`).
9142
+ *
9143
+ * Each line must begin at a line start and its value must hold no whitespace
9144
+ * and none of `*`, backtick, `$`, quotes or backslash. Such a line is inert
9145
+ * wherever it stands: outside any literal it is a line comment; a regular
9146
+ * expression literal cannot span lines; and inside a block comment, a string
9147
+ * continued from the line before or a template literal, the line can neither
9148
+ * close that context (no `*`, quote or backtick) nor open a substitution (no
9149
+ * `$`). Since nothing but whitespace follows the run, an unclosed context
9150
+ * there is a SyntaxError. So `rejectImportExpressions` need not scan it.
9151
+ *
9152
+ * A `/*# sourceMappingURL=` block comment is not skipped but scanned like
9153
+ * any other code, which can only make the check stricter.
9154
+ */
9155
+ const sourceMetaLinePattern = freezeRegexp(
9156
+ new FERAL_REG_EXP('^//# source(?:Mapping)?URL=[^\\s*`$\'"\\\\]*$'),
9157
+ );
9158
+
9159
+ const whitespacePattern = freezeRegexp(new FERAL_REG_EXP('^\\s$'));
9160
+
9161
+ const lineTerminatorPattern = freezeRegexp(
9162
+ new FERAL_REG_EXP('^[\\n\\r\\u2028\\u2029]$'),
8959
9163
  );
8960
9164
 
9165
+ /**
9166
+ * Returns the index at which the trailing run of source meta comments
9167
+ * begins, at its leading line terminator if it has one, or the length of
9168
+ * the source if there is no such run. It reads the source backward, one
9169
+ * line at a time, and tests each line with `sourceMetaLinePattern` alone,
9170
+ * so it takes time linear in the length of the source. A single regular
9171
+ * expression for the whole run, `(?:(?:^|[\n\r\u2028\u2029])<line>)+\s*$`,
9172
+ * finds the same run, but a search retries it at every line terminator,
9173
+ * which takes time quadratic in the number of lines of the run.
9174
+ *
9175
+ * @param {string} src
9176
+ * @returns {number}
9177
+ */
9178
+ const sourceMetaTrailerStart = src => {
9179
+ let end = src.length;
9180
+ while (end > 0 && regexpExec(whitespacePattern, src[end - 1]) !== null) {
9181
+ end -= 1;
9182
+ }
9183
+ let start = src.length;
9184
+ for (;;) {
9185
+ let lineStart = end;
9186
+ while (
9187
+ lineStart > 0 &&
9188
+ regexpExec(lineTerminatorPattern, src[lineStart - 1]) === null
9189
+ ) {
9190
+ lineStart -= 1;
9191
+ }
9192
+ if (
9193
+ regexpExec(sourceMetaLinePattern, stringSlice(src, lineStart, end)) ===
9194
+ null
9195
+ ) {
9196
+ return start;
9197
+ }
9198
+ if (lineStart === 0) {
9199
+ return 0;
9200
+ }
9201
+ start = lineStart - 1;
9202
+ end = lineStart - 1;
9203
+ }
9204
+ };
9205
+
8961
9206
  /**
8962
9207
  * Conservatively reject the source text if it may contain a dynamic
8963
9208
  * import expression. To reject without parsing, `rejectImportExpressions` will
@@ -8973,10 +9218,23 @@ const importPattern = sealRegexp(
8973
9218
  * apparent import expressions in literal strings or comments.
8974
9219
  *
8975
9220
  * The current conservative rule looks for the identifier "import"
8976
- * followed by either an open paren or something that looks like the
8977
- * beginning of a comment. We assume that we do not need to worry
8978
- * about html comment syntax because that was already rejected by
8979
- * rejectHtmlComments.
9221
+ * followed by either an open paren, a dot, or something that looks like
9222
+ * the beginning of a comment. The dot case rejects not just a
9223
+ * phase-qualified call such as `import.source(...)` or `import.defer(...)`,
9224
+ * but any property access under `import` at all, including `import.meta`,
9225
+ * regardless of whether the property is then called. This is broader than
9226
+ * strictly necessary: the substring "import." can occur incidentally, for
9227
+ * example in a module path or a comment, and such source text is rejected
9228
+ * too. That tradeoff is intentional: covering every `import.<name>` form,
9229
+ * called or not, without naming specific property names, is judged simpler
9230
+ * and safer than narrowing the match to the shape of a call. We assume that
9231
+ * we do not need to worry about html comment syntax because that was
9232
+ * already rejected by rejectHtmlComments.
9233
+ *
9234
+ * The scan stops short of a trailing run of `//# sourceURL=` or
9235
+ * `//# sourceMappingURL=` comments whose values could not end a comment,
9236
+ * string or template (see `sourceMetaTrailerStart`), so that a module
9237
+ * whose location contains `import.` still loads.
8980
9238
  *
8981
9239
  * this \s *must* match all kinds of syntax-defined whitespace. If e.g.
8982
9240
  * U+2028 (LINE SEPARATOR) or U+2029 (PARAGRAPH SEPARATOR) is treated as
@@ -8989,7 +9247,8 @@ const importPattern = sealRegexp(
8989
9247
  * @returns {string}
8990
9248
  */
8991
9249
  const rejectImportExpressions = src => {
8992
- const lineNumber = getLineNumber(src, importPattern);
9250
+ const scanned = stringSlice(src, 0, sourceMetaTrailerStart(src));
9251
+ const lineNumber = getLineNumber(scanned, importPattern);
8993
9252
  if (lineNumber < 0) {
8994
9253
  return src;
8995
9254
  }
@@ -9672,7 +9931,10 @@ let markVirtualizedNativeFunction;
9672
9931
  })()
9673
9932
  ,
9674
9933
  // === 42. ses ./src/error/console.js ===
9675
- ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';let WeakSet,arrayFilter,arrayFlatMap,arrayMap,arrayPop,arrayPush,defineProperty,freeze,fromEntries,isError,stringEndsWith,stringIncludes,stringSplit,weaksetAdd,weaksetHas;$h͏_imports([["../commons.js", [["WeakSet",[$h͏_a => (WeakSet = $h͏_a)]],["arrayFilter",[$h͏_a => (arrayFilter = $h͏_a)]],["arrayFlatMap",[$h͏_a => (arrayFlatMap = $h͏_a)]],["arrayMap",[$h͏_a => (arrayMap = $h͏_a)]],["arrayPop",[$h͏_a => (arrayPop = $h͏_a)]],["arrayPush",[$h͏_a => (arrayPush = $h͏_a)]],["defineProperty",[$h͏_a => (defineProperty = $h͏_a)]],["freeze",[$h͏_a => (freeze = $h͏_a)]],["fromEntries",[$h͏_a => (fromEntries = $h͏_a)]],["isError",[$h͏_a => (isError = $h͏_a)]],["stringEndsWith",[$h͏_a => (stringEndsWith = $h͏_a)]],["stringIncludes",[$h͏_a => (stringIncludes = $h͏_a)]],["stringSplit",[$h͏_a => (stringSplit = $h͏_a)]],["weaksetAdd",[$h͏_a => (weaksetAdd = $h͏_a)]],["weaksetHas",[$h͏_a => (weaksetHas = $h͏_a)]]]]]);
9934
+ ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';let WeakSet,arrayFilter,arrayFlatMap,arrayMap,arrayPop,arrayPush,defineProperty,freeze,fromEntries,globalThis,isError,stringEndsWith,stringIncludes,stringSplit,weaksetAdd,weaksetHas,stringIndexOf,stringSlice;$h͏_imports([["../commons.js", [["WeakSet",[$h͏_a => (WeakSet = $h͏_a)]],["arrayFilter",[$h͏_a => (arrayFilter = $h͏_a)]],["arrayFlatMap",[$h͏_a => (arrayFlatMap = $h͏_a)]],["arrayMap",[$h͏_a => (arrayMap = $h͏_a)]],["arrayPop",[$h͏_a => (arrayPop = $h͏_a)]],["arrayPush",[$h͏_a => (arrayPush = $h͏_a)]],["defineProperty",[$h͏_a => (defineProperty = $h͏_a)]],["freeze",[$h͏_a => (freeze = $h͏_a)]],["fromEntries",[$h͏_a => (fromEntries = $h͏_a)]],["globalThis",[$h͏_a => (globalThis = $h͏_a)]],["isError",[$h͏_a => (isError = $h͏_a)]],["stringEndsWith",[$h͏_a => (stringEndsWith = $h͏_a)]],["stringIncludes",[$h͏_a => (stringIncludes = $h͏_a)]],["stringSplit",[$h͏_a => (stringSplit = $h͏_a)]],["weaksetAdd",[$h͏_a => (weaksetAdd = $h͏_a)]],["weaksetHas",[$h͏_a => (weaksetHas = $h͏_a)]],["stringIndexOf",[$h͏_a => (stringIndexOf = $h͏_a)]],["stringSlice",[$h͏_a => (stringSlice = $h͏_a)]]]]]);
9935
+
9936
+
9937
+
9676
9938
 
9677
9939
 
9678
9940
 
@@ -9749,7 +10011,7 @@ const defineName = (name, fn) => defineProperty(fn, 'name', { value: name });
9749
10011
  * This is the same as the log severity of these on other
9750
10012
  * platform console implementations when they all agree.
9751
10013
  *
9752
- * @type {readonly [ConsoleProps, LogSeverity | undefined][]}
10014
+ * @type {readonly [ConsoleProps, LogSeverity][]}
9753
10015
  */
9754
10016
  const consoleLevelMethods = freeze([
9755
10017
  ['debug', 'debug'], // (fmt?, ...args) verbose level on Chrome
@@ -9764,25 +10026,35 @@ const defineName = (name, fn) => defineProperty(fn, 'name', { value: name });
9764
10026
  ['groupCollapsed', 'log'] // (fmt?, ...args) but TS typed (...label)
9765
10027
  ]);
9766
10028
 
10029
+ /**
10030
+ * We special case `console.assert` because it contains `fmt?, ...args` just
10031
+ * like the `consoleLevelMethods`, but not in the same place.
10032
+ * We special case `console.timeLog` because it contains the same kind of
10033
+ * `...args`, but with no format string.
10034
+ *
10035
+ * @type {readonly [ConsoleProps, LogSeverity][]}
10036
+ */$h͏_once.consoleLevelMethods(consoleLevelMethods);
10037
+ const consoleSpecialMethods = freeze([
10038
+ ['assert', 'error'], // (value, fmt?, ...args)
10039
+ ['timeLog', 'log'] // (label?, ...args) no fmt string
10040
+ ]);
10041
+
9767
10042
  /**
9768
10043
  * Those console methods other than those already enumerated by
9769
- * `consoleLevelMethods`.
10044
+ * `consoleLevelMethods` and `consoleSpecialMethods`.
9770
10045
  *
9771
10046
  * Each is paired with what we consider to be their log severity level.
9772
10047
  * This is the same as the log severity of these on other
9773
10048
  * platform console implementations when they all agree.
9774
10049
  *
9775
- * @type {readonly [ConsoleProps, LogSeverity | undefined][]}
9776
- */$h͏_once.consoleLevelMethods(consoleLevelMethods);
10050
+ * @type {readonly [ConsoleProps, LogSeverity][]}
10051
+ */$h͏_once.consoleSpecialMethods(consoleSpecialMethods);
9777
10052
  const consoleOtherMethods = freeze([
9778
- ['assert', 'error'], // (value, fmt?, ...args)
9779
- ['timeLog', 'log'], // (label?, ...args) no fmt string
9780
-
9781
10053
  // Insensitive to whether any argument is an error. All arguments can pass
9782
10054
  // thru to baseConsole as is.
9783
- ['clear', undefined], // ()
10055
+ ['clear', 'info'], // (), level is not well defined
9784
10056
  ['count', 'info'], // (label?)
9785
- ['countReset', undefined], // (label?)
10057
+ ['countReset', 'info'], // (label?), level is not well defined
9786
10058
  ['dir', 'log'], // (item, options?)
9787
10059
  ['groupEnd', 'log'], // ()
9788
10060
  // In theory tabular data may be or contain an error. However, we currently
@@ -9792,14 +10064,15 @@ const defineName = (name, fn) => defineProperty(fn, 'name', { value: name });
9792
10064
  ['timeEnd', 'info'], // (label?)
9793
10065
 
9794
10066
  // Node Inspector only, MDN, and TypeScript, but not whatwg
9795
- ['profile', undefined], // (label?)
9796
- ['profileEnd', undefined], // (label?)
9797
- ['timeStamp', undefined] // (label?)
10067
+ ['profile', 'info'], // (label?)
10068
+ ['profileEnd', 'info'], // (label?)
10069
+ ['timeStamp', 'info'] // (label?)
9798
10070
  ]);
9799
10071
 
9800
- /** @type {readonly [ConsoleProps, LogSeverity | undefined][]} */$h͏_once.consoleOtherMethods(consoleOtherMethods);
10072
+ /** @type {readonly [ConsoleProps, LogSeverity][]} */$h͏_once.consoleOtherMethods(consoleOtherMethods);
9801
10073
  const consoleMethodPermits = freeze([
9802
10074
  ...consoleLevelMethods,
10075
+ ...consoleSpecialMethods,
9803
10076
  ...consoleOtherMethods,
9804
10077
  ]);
9805
10078
 
@@ -9830,6 +10103,111 @@ const consoleMethodPermits = freeze([
9830
10103
  * ]);
9831
10104
  */
9832
10105
 
10106
+ /**
10107
+ * If `formatData` consists of `[fmt, ...args]` and `fmt` is a string
10108
+ * containing a `%c` specifier that acts as an `%c` specifier
10109
+ * according to https://console.spec.whatwg.org/#formatting-specifiers
10110
+ * then omit it and its corresponding argument. For the rest of the `fmt`
10111
+ * string and its corresponding arguments, return them as a replacement
10112
+ * `formatData` to be fed to the underlying console log functions.
10113
+ *
10114
+ * The test takes into account the number of remaining `args`.
10115
+ * A `%c` beyond `args` does not act as a specifier.
10116
+ * The additional issue not mentioned at
10117
+ * https://console.spec.whatwg.org/#formatting-specifiers
10118
+ * is that `%%` is an escaped `%`, so the `%c` found within,
10119
+ * for example, `%%c` does not act as a specifier.
10120
+ * Instead, it gets rendered as `%c` without consuming an argument.
10121
+ *
10122
+ * Note terminology differences from the spec-internal `Logger` function
10123
+ * at https://console.spec.whatwg.org/#formatting-specifiers .
10124
+ *
10125
+ * | `Logger` terminology | `sanitizeFormatData` terminology |
10126
+ * | ---------------------|----------------------------------|
10127
+ * | `args` | `formatData` |
10128
+ * | `first` | `fmt` |
10129
+ * | `rest` | `args` |
10130
+ *
10131
+ * Exported only for testing.
10132
+ *
10133
+ * @param {any[]} formatData
10134
+ * @returns {any[]}
10135
+ */
10136
+ const sanitizeFormatData = ([...formatData]) => {
10137
+ freeze(formatData);
10138
+ if (formatData.length <= 1) {
10139
+ return formatData;
10140
+ }
10141
+ const [fmt, ...args] = formatData;
10142
+ if (typeof fmt !== 'string' || !stringIncludes(fmt, '%')) {
10143
+ return formatData;
10144
+ }
10145
+
10146
+ let startPos = 0;
10147
+ let argI = 0;
10148
+ let newFmt = '';
10149
+ const newArgs = [];
10150
+ for (
10151
+ let percentPos = stringIndexOf(fmt, '%');
10152
+ // Notice the `- 1` below, which leaves room for one more character after
10153
+ // the `'%'`.
10154
+ percentPos >= startPos && percentPos < fmt.length - 1 && argI < args.length;
10155
+ percentPos = stringIndexOf(fmt, '%', startPos)
10156
+ ) {
10157
+ // The four cases in the following switch are purposely partially
10158
+ // redundant. But the total code is small and our attempts at more
10159
+ // reuse made the code less clear. Clarity sometimes wins over DRY.
10160
+ const char = fmt[percentPos + 1];
10161
+ switch (char) {
10162
+ case 's':
10163
+ case 'd':
10164
+ case 'i':
10165
+ case 'f':
10166
+ case 'o':
10167
+ case 'O': {
10168
+ // transfer segment + % + char
10169
+ newFmt += stringSlice(fmt, startPos, percentPos + 2);
10170
+ startPos = percentPos + 2;
10171
+ // transfer 1 arg
10172
+ arrayPush(newArgs, args[argI]);
10173
+ argI += 1;
10174
+ break;
10175
+ }
10176
+ case 'c': {
10177
+ // transfer segment. Consume %c
10178
+ newFmt += stringSlice(fmt, startPos, percentPos);
10179
+ startPos = percentPos + 2;
10180
+ // consume 1 arg
10181
+ argI += 1;
10182
+ break;
10183
+ }
10184
+ case '%': {
10185
+ // transfer segment + % + char. Ignore args
10186
+ newFmt += stringSlice(fmt, startPos, percentPos + 2);
10187
+ startPos = percentPos + 2;
10188
+ break;
10189
+ }
10190
+ default: {
10191
+ // transfer segment + %% + char. Ignore args
10192
+ // So that %<unspecified> is treated as unknown even if
10193
+ // implemented by the local platform, such as %j on Node.
10194
+ newFmt += stringSlice(fmt, startPos, percentPos);
10195
+ newFmt += `%%${char}`;
10196
+ startPos = percentPos + 2;
10197
+ break;
10198
+ }
10199
+ }
10200
+ }
10201
+ if (startPos < fmt.length) {
10202
+ newFmt += stringSlice(fmt, startPos, fmt.length);
10203
+ }
10204
+ for (; argI < args.length; argI += 1) {
10205
+ arrayPush(newArgs, args[argI]);
10206
+ }
10207
+ return /** @type {any[]} */ (freeze([newFmt, ...newArgs]));
10208
+ };$h͏_once.sanitizeFormatData(sanitizeFormatData);
10209
+ freeze(sanitizeFormatData);
10210
+
9833
10211
  // //////////////////////////// Logging Console ////////////////////////////////
9834
10212
 
9835
10213
  /** @type {MakeLoggingConsoleKit} */
@@ -9898,11 +10276,32 @@ const ErrorInfo = {
9898
10276
  freeze(ErrorInfo);
9899
10277
 
9900
10278
  /** @type {MakeCausalConsole} */
9901
- const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
9902
- if (!baseConsole) {
10279
+ const makeCausalConsole = (feralConsole, loggedErrorHandler) => {
10280
+ if (!feralConsole) {
9903
10281
  return undefined;
9904
10282
  }
9905
10283
 
10284
+ // In Node.js, the global console does a deep scan of its inputs for methods
10285
+ // keyed by Symbol.for('nodejs.util.inspect.custom'), and invokes any that are
10286
+ // found with unhardened arguments as described at
10287
+ // https://nodejs.org/docs/latest/api/util.html#custom-inspection-functions-on-objects
10288
+ // To circumvent that problematic behavior, we use its
10289
+ // https://nodejs.org/docs/latest/api/console.html#class-console Console
10290
+ // constructor to build a replacement that explicitly opts out by setting the
10291
+ // `customInspect` option to false.
10292
+ // https://nodejs.org/docs/latest/api/util.html#utilinspectobject-options
10293
+ /** @type {new (options: any) => typeof console} */
10294
+ const Console = /** @type {any} */ (feralConsole).Console;
10295
+ const { stdout, stderr } = globalThis.process || { __proto__: null };
10296
+ const baseConsole =
10297
+ typeof Console === 'function' && (stdout || stderr)
10298
+ ? new Console({
10299
+ stdout,
10300
+ stderr,
10301
+ inspectOptions: { colors: undefined, customInspect: false },
10302
+ })
10303
+ : feralConsole;
10304
+
9906
10305
  const { getStackString, tagError, takeMessageLogArgs, takeNoteLogArgsArray } =
9907
10306
  loggedErrorHandler;
9908
10307
 
@@ -10050,32 +10449,53 @@ freeze(ErrorInfo);
10050
10449
  logSubErrors(severity, subErrors, errorTag);
10051
10450
  };
10052
10451
 
10053
- const levelMethods = arrayMap(consoleLevelMethods, ([level, _]) => {
10452
+ const levelMethods = arrayMap(consoleLevelMethods, ([name, level]) => {
10054
10453
  /**
10055
10454
  * @param {...any} logArgs
10056
10455
  */
10057
- const levelMethod = defineName(level, (...logArgs) => {
10456
+ const levelMethod = defineName(name, (...logArgs) => {
10058
10457
  const subErrors = [];
10059
- const argTags = extractErrorArgs(logArgs, subErrors);
10060
- if (baseConsole[level]) {
10061
- // eslint-disable-next-line @endo/no-polymorphic-call
10062
- baseConsole[level](...argTags);
10063
- }
10064
- // @ts-expect-error ConsoleProp vs LogSeverity mismatch
10458
+ const argTags = extractErrorArgs(sanitizeFormatData(logArgs), subErrors);
10459
+ // eslint-disable-next-line @endo/no-polymorphic-call
10460
+ baseConsole[name](...argTags);
10065
10461
  logSubErrors(level, subErrors);
10066
10462
  });
10067
- return [level, freeze(levelMethod)];
10463
+ return [name, freeze(levelMethod)];
10068
10464
  });
10069
- const otherMethodNames = arrayFilter(
10070
- consoleOtherMethods,
10071
- ([name, _]) => name in baseConsole,
10072
- );
10073
- const otherMethods = arrayMap(otherMethodNames, ([name, _]) => {
10465
+
10466
+ const assertMethod = defineName('assert', (...assertArgs) => {
10467
+ if (assertArgs.length <= 1) {
10468
+ // eslint-disable-next-line @endo/no-polymorphic-call
10469
+ baseConsole.assert(...assertArgs);
10470
+ } else {
10471
+ const [cond, ...logArgs] = assertArgs;
10472
+ const subErrors = [];
10473
+ const argTags = extractErrorArgs(sanitizeFormatData(logArgs), subErrors);
10474
+ // eslint-disable-next-line @endo/no-polymorphic-call
10475
+ baseConsole.assert(cond, ...argTags);
10476
+ logSubErrors('error', subErrors);
10477
+ }
10478
+ });
10479
+
10480
+ const timeLogMethod = defineName('timeLog', (...timeLogArgs) => {
10481
+ if (timeLogArgs.length <= 1) {
10482
+ // eslint-disable-next-line @endo/no-polymorphic-call
10483
+ baseConsole.timeLog(...timeLogArgs);
10484
+ } else {
10485
+ const [label, ...logArgs] = timeLogArgs;
10486
+ const subErrors = [];
10487
+ const argTags = extractErrorArgs(sanitizeFormatData(logArgs), subErrors);
10488
+ // eslint-disable-next-line @endo/no-polymorphic-call
10489
+ baseConsole.timeLog(label, ...argTags);
10490
+ logSubErrors('log', subErrors);
10491
+ }
10492
+ });
10493
+
10494
+ const otherMethods = arrayMap(consoleOtherMethods, ([name, _level]) => {
10074
10495
  /**
10075
10496
  * @param {...any} args
10076
10497
  */
10077
10498
  const otherMethod = defineName(name, (...args) => {
10078
- // @ts-ignore
10079
10499
  // eslint-disable-next-line @endo/no-polymorphic-call
10080
10500
  baseConsole[name](...args);
10081
10501
  return undefined;
@@ -10083,7 +10503,17 @@ freeze(ErrorInfo);
10083
10503
  return [name, freeze(otherMethod)];
10084
10504
  });
10085
10505
 
10086
- const causalConsole = fromEntries([...levelMethods, ...otherMethods]);
10506
+ const methodEntries = arrayFilter(
10507
+ [
10508
+ ...levelMethods,
10509
+ ['assert', assertMethod],
10510
+ ['timeLog', timeLogMethod],
10511
+ ...otherMethods,
10512
+ ],
10513
+ ([name, _]) => name in baseConsole,
10514
+ );
10515
+
10516
+ const causalConsole = fromEntries(methodEntries);
10087
10517
  return /** @type {VirtualConsole} */ (freeze(causalConsole));
10088
10518
  };$h͏_once.makeCausalConsole(makeCausalConsole);
10089
10519
  freeze(makeCausalConsole);
@@ -10394,7 +10824,6 @@ const wrapLogger = (logger, thisArg) =>
10394
10824
  };
10395
10825
  }
10396
10826
 
10397
- // eslint-disable-next-line no-restricted-globals
10398
10827
  const originalConsole = /** @type {VirtualConsole} */ (
10399
10828
  // eslint-disable-next-line no-nested-ternary
10400
10829
  typeof globalThis.console !== 'undefined'
@@ -10404,7 +10833,6 @@ const wrapLogger = (logger, thisArg) =>
10404
10833
  // log at a specific level with no special argument interpretation).
10405
10834
  // https://console.spec.whatwg.org/#logging
10406
10835
  (p => freeze({ debug: p, log: p, info: p, warn: p, error: p }))(
10407
- // eslint-disable-next-line no-undef
10408
10836
  wrapLogger(globalThis.print),
10409
10837
  )
10410
10838
  : undefined
@@ -10995,7 +11423,7 @@ let initialGetStackString = tamedMethods.getStackString;
10995
11423
  * @this {ErrorConstructor}
10996
11424
  * @param {...any} rest
10997
11425
  */
10998
- // eslint-disable-next-line no-shadow
11426
+
10999
11427
  const ResultError = function Error(...rest) {
11000
11428
  let error;
11001
11429
  if (new.target === undefined) {
@@ -11421,7 +11849,6 @@ function* loadWithoutErrorAnnotation(
11421
11849
  }
11422
11850
 
11423
11851
  if (typeof moduleDescriptor === 'string') {
11424
- // eslint-disable-next-line @endo/no-polymorphic-call
11425
11852
  throw makeError(
11426
11853
  X`Cannot map module ${q(moduleSpecifier)} to ${q(
11427
11854
  moduleDescriptor,
@@ -11733,7 +12160,6 @@ const memoizedLoadWithErrorAnnotation = (
11733
12160
  moduleLoads,
11734
12161
  ],
11735
12162
  error => {
11736
- // eslint-disable-next-line @endo/no-polymorphic-call
11737
12163
  annotateError(
11738
12164
  error,
11739
12165
  X`${error.message}, loading ${q(moduleSpecifier)} in compartment ${q(
@@ -12993,7 +13419,6 @@ function validateModuleSource(moduleSource, moduleSpecifier) {
12993
13419
 
12994
13420
 
12995
13421
 
12996
-
12997
13422
 
12998
13423
 
12999
13424
  /**
@@ -13082,6 +13507,11 @@ const compartmentImportNow = (compartment, specifier) => {
13082
13507
  .name;
13083
13508
  },
13084
13509
 
13510
+ get __noNamespaceBox__() {
13511
+ return /** @type {CompartmentFields} */ (weakmapGet(privateFields, this))
13512
+ .noNamespaceBox;
13513
+ },
13514
+
13085
13515
  evaluate(source, options = {}) {
13086
13516
  const compartmentFields = weakmapGet(privateFields, this);
13087
13517
  return compartmentEvaluate(compartmentFields, source, options);
@@ -13409,8 +13839,7 @@ defineProperties(InertCompartment, {
13409
13839
  })()
13410
13840
  ,
13411
13841
  // === 53. ses ./src/get-anonymous-intrinsics.js ===
13412
- ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';let FERAL_FUNCTION,FERAL_FLOAT64_ARRAY,Map,Set,String,getOwnPropertyDescriptor,getPrototypeOf,iterateArray,iterateMap,iterateSet,iterateString,matchAllRegExp,matchAllSymbol,regexpPrototype,globalThis,assign,AsyncGeneratorFunctionInstance,ArrayBuffer,InertCompartment;$h͏_imports([["./commons.js", [["FERAL_FUNCTION",[$h͏_a => (FERAL_FUNCTION = $h͏_a)]],["FERAL_FLOAT64_ARRAY",[$h͏_a => (FERAL_FLOAT64_ARRAY = $h͏_a)]],["Map",[$h͏_a => (Map = $h͏_a)]],["Set",[$h͏_a => (Set = $h͏_a)]],["String",[$h͏_a => (String = $h͏_a)]],["getOwnPropertyDescriptor",[$h͏_a => (getOwnPropertyDescriptor = $h͏_a)]],["getPrototypeOf",[$h͏_a => (getPrototypeOf = $h͏_a)]],["iterateArray",[$h͏_a => (iterateArray = $h͏_a)]],["iterateMap",[$h͏_a => (iterateMap = $h͏_a)]],["iterateSet",[$h͏_a => (iterateSet = $h͏_a)]],["iterateString",[$h͏_a => (iterateString = $h͏_a)]],["matchAllRegExp",[$h͏_a => (matchAllRegExp = $h͏_a)]],["matchAllSymbol",[$h͏_a => (matchAllSymbol = $h͏_a)]],["regexpPrototype",[$h͏_a => (regexpPrototype = $h͏_a)]],["globalThis",[$h͏_a => (globalThis = $h͏_a)]],["assign",[$h͏_a => (assign = $h͏_a)]],["AsyncGeneratorFunctionInstance",[$h͏_a => (AsyncGeneratorFunctionInstance = $h͏_a)]],["ArrayBuffer",[$h͏_a => (ArrayBuffer = $h͏_a)]]]],["./compartment.js", [["InertCompartment",[$h͏_a => (InertCompartment = $h͏_a)]]]]]);
13413
-
13842
+ ({imports:$h͏_imports,liveVar:$h͏_live,onceVar:$h͏_once,import:$h͏_import,importMeta:$h͏____meta})=>(function(){'use strict';let FERAL_FUNCTION,FERAL_FLOAT64_ARRAY,Map,Set,String,getOwnPropertyDescriptor,getPrototypeOf,iterateArray,iterateMap,iterateSet,iterateString,matchAllRegExp,matchAllSymbol,regexpPrototype,globalThis,assign,AsyncGeneratorFunctionInstance,InertCompartment;$h͏_imports([["./commons.js", [["FERAL_FUNCTION",[$h͏_a => (FERAL_FUNCTION = $h͏_a)]],["FERAL_FLOAT64_ARRAY",[$h͏_a => (FERAL_FLOAT64_ARRAY = $h͏_a)]],["Map",[$h͏_a => (Map = $h͏_a)]],["Set",[$h͏_a => (Set = $h͏_a)]],["String",[$h͏_a => (String = $h͏_a)]],["getOwnPropertyDescriptor",[$h͏_a => (getOwnPropertyDescriptor = $h͏_a)]],["getPrototypeOf",[$h͏_a => (getPrototypeOf = $h͏_a)]],["iterateArray",[$h͏_a => (iterateArray = $h͏_a)]],["iterateMap",[$h͏_a => (iterateMap = $h͏_a)]],["iterateSet",[$h͏_a => (iterateSet = $h͏_a)]],["iterateString",[$h͏_a => (iterateString = $h͏_a)]],["matchAllRegExp",[$h͏_a => (matchAllRegExp = $h͏_a)]],["matchAllSymbol",[$h͏_a => (matchAllSymbol = $h͏_a)]],["regexpPrototype",[$h͏_a => (regexpPrototype = $h͏_a)]],["globalThis",[$h͏_a => (globalThis = $h͏_a)]],["assign",[$h͏_a => (assign = $h͏_a)]],["AsyncGeneratorFunctionInstance",[$h͏_a => (AsyncGeneratorFunctionInstance = $h͏_a)]]]],["./compartment.js", [["InertCompartment",[$h͏_a => (InertCompartment = $h͏_a)]]]]]);
13414
13843
 
13415
13844
 
13416
13845
 
@@ -13465,7 +13894,6 @@ function makeArguments() {
13465
13894
 
13466
13895
  // 21.1.5.2 The %StringIteratorPrototype% Object
13467
13896
 
13468
- // eslint-disable-next-line no-new-wrappers
13469
13897
  const StringIteratorObject = iterateString(new String());
13470
13898
  const StringIteratorPrototype = getPrototypeOf(StringIteratorObject);
13471
13899
 
@@ -13477,7 +13905,6 @@ function makeArguments() {
13477
13905
 
13478
13906
  // 22.1.5.2 The %ArrayIteratorPrototype% Object
13479
13907
 
13480
- // eslint-disable-next-line no-array-constructor
13481
13908
  const ArrayIteratorObject = iterateArray([]);
13482
13909
  const ArrayIteratorPrototype = getPrototypeOf(ArrayIteratorObject);
13483
13910
 
@@ -13578,15 +14005,6 @@ function makeArguments() {
13578
14005
  );
13579
14006
  }
13580
14007
 
13581
- const ab = new ArrayBuffer(0);
13582
- // eslint-disable-next-line @endo/no-polymorphic-call
13583
- const iab = ab.sliceToImmutable();
13584
- const iabProto = getPrototypeOf(iab);
13585
- if (iabProto !== ArrayBuffer.prototype) {
13586
- // In a native implementation, these will be the same prototype
13587
- intrinsics['%ImmutableArrayBufferPrototype%'] = iabProto;
13588
- }
13589
-
13590
14008
  return intrinsics;
13591
14009
  };$h͏_once.getAnonymousIntrinsics(getAnonymousIntrinsics);
13592
14010
  })()
@@ -13702,7 +14120,7 @@ const throws = thunk => {
13702
14120
  try {
13703
14121
  thunk();
13704
14122
  return false;
13705
- } catch (er) {
14123
+ } catch (_err) {
13706
14124
  return true;
13707
14125
  }
13708
14126
  };