ses 2.1.0 → 2.3.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.
@@ -15,12 +15,15 @@ import {
15
15
  defineProperty,
16
16
  freeze,
17
17
  fromEntries,
18
+ globalThis,
18
19
  isError,
19
20
  stringEndsWith,
20
21
  stringIncludes,
21
22
  stringSplit,
22
23
  weaksetAdd,
23
24
  weaksetHas,
25
+ stringIndexOf,
26
+ stringSlice,
24
27
  } from '../commons.js';
25
28
 
26
29
  /**
@@ -75,7 +78,7 @@ const defineName = (name, fn) => defineProperty(fn, 'name', { value: name });
75
78
  * This is the same as the log severity of these on other
76
79
  * platform console implementations when they all agree.
77
80
  *
78
- * @type {readonly [ConsoleProps, LogSeverity | undefined][]}
81
+ * @type {readonly [ConsoleProps, LogSeverity][]}
79
82
  */
80
83
  export const consoleLevelMethods = freeze([
81
84
  ['debug', 'debug'], // (fmt?, ...args) verbose level on Chrome
@@ -90,25 +93,35 @@ export const consoleLevelMethods = freeze([
90
93
  ['groupCollapsed', 'log'], // (fmt?, ...args) but TS typed (...label)
91
94
  ]);
92
95
 
96
+ /**
97
+ * We special case `console.assert` because it contains `fmt?, ...args` just
98
+ * like the `consoleLevelMethods`, but not in the same place.
99
+ * We special case `console.timeLog` because it contains the same kind of
100
+ * `...args`, but with no format string.
101
+ *
102
+ * @type {readonly [ConsoleProps, LogSeverity][]}
103
+ */
104
+ export const consoleSpecialMethods = freeze([
105
+ ['assert', 'error'], // (value, fmt?, ...args)
106
+ ['timeLog', 'log'], // (label?, ...args) no fmt string
107
+ ]);
108
+
93
109
  /**
94
110
  * Those console methods other than those already enumerated by
95
- * `consoleLevelMethods`.
111
+ * `consoleLevelMethods` and `consoleSpecialMethods`.
96
112
  *
97
113
  * Each is paired with what we consider to be their log severity level.
98
114
  * This is the same as the log severity of these on other
99
115
  * platform console implementations when they all agree.
100
116
  *
101
- * @type {readonly [ConsoleProps, LogSeverity | undefined][]}
117
+ * @type {readonly [ConsoleProps, LogSeverity][]}
102
118
  */
103
119
  export const consoleOtherMethods = freeze([
104
- ['assert', 'error'], // (value, fmt?, ...args)
105
- ['timeLog', 'log'], // (label?, ...args) no fmt string
106
-
107
120
  // Insensitive to whether any argument is an error. All arguments can pass
108
121
  // thru to baseConsole as is.
109
- ['clear', undefined], // ()
122
+ ['clear', 'info'], // (), level is not well defined
110
123
  ['count', 'info'], // (label?)
111
- ['countReset', undefined], // (label?)
124
+ ['countReset', 'info'], // (label?), level is not well defined
112
125
  ['dir', 'log'], // (item, options?)
113
126
  ['groupEnd', 'log'], // ()
114
127
  // In theory tabular data may be or contain an error. However, we currently
@@ -118,14 +131,15 @@ export const consoleOtherMethods = freeze([
118
131
  ['timeEnd', 'info'], // (label?)
119
132
 
120
133
  // Node Inspector only, MDN, and TypeScript, but not whatwg
121
- ['profile', undefined], // (label?)
122
- ['profileEnd', undefined], // (label?)
123
- ['timeStamp', undefined], // (label?)
134
+ ['profile', 'info'], // (label?)
135
+ ['profileEnd', 'info'], // (label?)
136
+ ['timeStamp', 'info'], // (label?)
124
137
  ]);
125
138
 
126
- /** @type {readonly [ConsoleProps, LogSeverity | undefined][]} */
139
+ /** @type {readonly [ConsoleProps, LogSeverity][]} */
127
140
  const consoleMethodPermits = freeze([
128
141
  ...consoleLevelMethods,
142
+ ...consoleSpecialMethods,
129
143
  ...consoleOtherMethods,
130
144
  ]);
131
145
 
@@ -156,6 +170,111 @@ const consoleMethodPermits = freeze([
156
170
  * ]);
157
171
  */
158
172
 
173
+ /**
174
+ * If `formatData` consists of `[fmt, ...args]` and `fmt` is a string
175
+ * containing a `%c` specifier that acts as an `%c` specifier
176
+ * according to https://console.spec.whatwg.org/#formatting-specifiers
177
+ * then omit it and its corresponding argument. For the rest of the `fmt`
178
+ * string and its corresponding arguments, return them as a replacement
179
+ * `formatData` to be fed to the underlying console log functions.
180
+ *
181
+ * The test takes into account the number of remaining `args`.
182
+ * A `%c` beyond `args` does not act as a specifier.
183
+ * The additional issue not mentioned at
184
+ * https://console.spec.whatwg.org/#formatting-specifiers
185
+ * is that `%%` is an escaped `%`, so the `%c` found within,
186
+ * for example, `%%c` does not act as a specifier.
187
+ * Instead, it gets rendered as `%c` without consuming an argument.
188
+ *
189
+ * Note terminology differences from the spec-internal `Logger` function
190
+ * at https://console.spec.whatwg.org/#formatting-specifiers .
191
+ *
192
+ * | `Logger` terminology | `sanitizeFormatData` terminology |
193
+ * | ---------------------|----------------------------------|
194
+ * | `args` | `formatData` |
195
+ * | `first` | `fmt` |
196
+ * | `rest` | `args` |
197
+ *
198
+ * Exported only for testing.
199
+ *
200
+ * @param {any[]} formatData
201
+ * @returns {any[]}
202
+ */
203
+ export const sanitizeFormatData = ([...formatData]) => {
204
+ freeze(formatData);
205
+ if (formatData.length <= 1) {
206
+ return formatData;
207
+ }
208
+ const [fmt, ...args] = formatData;
209
+ if (typeof fmt !== 'string' || !stringIncludes(fmt, '%')) {
210
+ return formatData;
211
+ }
212
+
213
+ let startPos = 0;
214
+ let argI = 0;
215
+ let newFmt = '';
216
+ const newArgs = [];
217
+ for (
218
+ let percentPos = stringIndexOf(fmt, '%');
219
+ // Notice the `- 1` below, which leaves room for one more character after
220
+ // the `'%'`.
221
+ percentPos >= startPos && percentPos < fmt.length - 1 && argI < args.length;
222
+ percentPos = stringIndexOf(fmt, '%', startPos)
223
+ ) {
224
+ // The four cases in the following switch are purposely partially
225
+ // redundant. But the total code is small and our attempts at more
226
+ // reuse made the code less clear. Clarity sometimes wins over DRY.
227
+ const char = fmt[percentPos + 1];
228
+ switch (char) {
229
+ case 's':
230
+ case 'd':
231
+ case 'i':
232
+ case 'f':
233
+ case 'o':
234
+ case 'O': {
235
+ // transfer segment + % + char
236
+ newFmt += stringSlice(fmt, startPos, percentPos + 2);
237
+ startPos = percentPos + 2;
238
+ // transfer 1 arg
239
+ arrayPush(newArgs, args[argI]);
240
+ argI += 1;
241
+ break;
242
+ }
243
+ case 'c': {
244
+ // transfer segment. Consume %c
245
+ newFmt += stringSlice(fmt, startPos, percentPos);
246
+ startPos = percentPos + 2;
247
+ // consume 1 arg
248
+ argI += 1;
249
+ break;
250
+ }
251
+ case '%': {
252
+ // transfer segment + % + char. Ignore args
253
+ newFmt += stringSlice(fmt, startPos, percentPos + 2);
254
+ startPos = percentPos + 2;
255
+ break;
256
+ }
257
+ default: {
258
+ // transfer segment + %% + char. Ignore args
259
+ // So that %<unspecified> is treated as unknown even if
260
+ // implemented by the local platform, such as %j on Node.
261
+ newFmt += stringSlice(fmt, startPos, percentPos);
262
+ newFmt += `%%${char}`;
263
+ startPos = percentPos + 2;
264
+ break;
265
+ }
266
+ }
267
+ }
268
+ if (startPos < fmt.length) {
269
+ newFmt += stringSlice(fmt, startPos, fmt.length);
270
+ }
271
+ for (; argI < args.length; argI += 1) {
272
+ arrayPush(newArgs, args[argI]);
273
+ }
274
+ return /** @type {any[]} */ (freeze([newFmt, ...newArgs]));
275
+ };
276
+ freeze(sanitizeFormatData);
277
+
159
278
  // //////////////////////////// Logging Console ////////////////////////////////
160
279
 
161
280
  /** @type {MakeLoggingConsoleKit} */
@@ -224,11 +343,32 @@ const ErrorInfo = {
224
343
  freeze(ErrorInfo);
225
344
 
226
345
  /** @type {MakeCausalConsole} */
227
- export const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
228
- if (!baseConsole) {
346
+ export const makeCausalConsole = (feralConsole, loggedErrorHandler) => {
347
+ if (!feralConsole) {
229
348
  return undefined;
230
349
  }
231
350
 
351
+ // In Node.js, the global console does a deep scan of its inputs for methods
352
+ // keyed by Symbol.for('nodejs.util.inspect.custom'), and invokes any that are
353
+ // found with unhardened arguments as described at
354
+ // https://nodejs.org/docs/latest/api/util.html#custom-inspection-functions-on-objects
355
+ // To circumvent that problematic behavior, we use its
356
+ // https://nodejs.org/docs/latest/api/console.html#class-console Console
357
+ // constructor to build a replacement that explicitly opts out by setting the
358
+ // `customInspect` option to false.
359
+ // https://nodejs.org/docs/latest/api/util.html#utilinspectobject-options
360
+ /** @type {new (options: any) => typeof console} */
361
+ const Console = /** @type {any} */ (feralConsole).Console;
362
+ const { stdout, stderr } = globalThis.process || { __proto__: null };
363
+ const baseConsole =
364
+ typeof Console === 'function' && (stdout || stderr)
365
+ ? new Console({
366
+ stdout,
367
+ stderr,
368
+ inspectOptions: { colors: undefined, customInspect: false },
369
+ })
370
+ : feralConsole;
371
+
232
372
  const { getStackString, tagError, takeMessageLogArgs, takeNoteLogArgsArray } =
233
373
  loggedErrorHandler;
234
374
 
@@ -376,32 +516,53 @@ export const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
376
516
  logSubErrors(severity, subErrors, errorTag);
377
517
  };
378
518
 
379
- const levelMethods = arrayMap(consoleLevelMethods, ([level, _]) => {
519
+ const levelMethods = arrayMap(consoleLevelMethods, ([name, level]) => {
380
520
  /**
381
521
  * @param {...any} logArgs
382
522
  */
383
- const levelMethod = defineName(level, (...logArgs) => {
523
+ const levelMethod = defineName(name, (...logArgs) => {
384
524
  const subErrors = [];
385
- const argTags = extractErrorArgs(logArgs, subErrors);
386
- if (baseConsole[level]) {
387
- // eslint-disable-next-line @endo/no-polymorphic-call
388
- baseConsole[level](...argTags);
389
- }
390
- // @ts-expect-error ConsoleProp vs LogSeverity mismatch
525
+ const argTags = extractErrorArgs(sanitizeFormatData(logArgs), subErrors);
526
+ // eslint-disable-next-line @endo/no-polymorphic-call
527
+ baseConsole[name](...argTags);
391
528
  logSubErrors(level, subErrors);
392
529
  });
393
- return [level, freeze(levelMethod)];
530
+ return [name, freeze(levelMethod)];
394
531
  });
395
- const otherMethodNames = arrayFilter(
396
- consoleOtherMethods,
397
- ([name, _]) => name in baseConsole,
398
- );
399
- const otherMethods = arrayMap(otherMethodNames, ([name, _]) => {
532
+
533
+ const assertMethod = defineName('assert', (...assertArgs) => {
534
+ if (assertArgs.length <= 1) {
535
+ // eslint-disable-next-line @endo/no-polymorphic-call
536
+ baseConsole.assert(...assertArgs);
537
+ } else {
538
+ const [cond, ...logArgs] = assertArgs;
539
+ const subErrors = [];
540
+ const argTags = extractErrorArgs(sanitizeFormatData(logArgs), subErrors);
541
+ // eslint-disable-next-line @endo/no-polymorphic-call
542
+ baseConsole.assert(cond, ...argTags);
543
+ logSubErrors('error', subErrors);
544
+ }
545
+ });
546
+
547
+ const timeLogMethod = defineName('timeLog', (...timeLogArgs) => {
548
+ if (timeLogArgs.length <= 1) {
549
+ // eslint-disable-next-line @endo/no-polymorphic-call
550
+ baseConsole.timeLog(...timeLogArgs);
551
+ } else {
552
+ const [label, ...logArgs] = timeLogArgs;
553
+ const subErrors = [];
554
+ const argTags = extractErrorArgs(sanitizeFormatData(logArgs), subErrors);
555
+ // eslint-disable-next-line @endo/no-polymorphic-call
556
+ baseConsole.timeLog(label, ...argTags);
557
+ logSubErrors('log', subErrors);
558
+ }
559
+ });
560
+
561
+ const otherMethods = arrayMap(consoleOtherMethods, ([name, _level]) => {
400
562
  /**
401
563
  * @param {...any} args
402
564
  */
403
565
  const otherMethod = defineName(name, (...args) => {
404
- // @ts-ignore
405
566
  // eslint-disable-next-line @endo/no-polymorphic-call
406
567
  baseConsole[name](...args);
407
568
  return undefined;
@@ -409,7 +570,17 @@ export const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
409
570
  return [name, freeze(otherMethod)];
410
571
  });
411
572
 
412
- const causalConsole = fromEntries([...levelMethods, ...otherMethods]);
573
+ const methodEntries = arrayFilter(
574
+ [
575
+ ...levelMethods,
576
+ ['assert', assertMethod],
577
+ ['timeLog', timeLogMethod],
578
+ ...otherMethods,
579
+ ],
580
+ ([name, _]) => name in baseConsole,
581
+ );
582
+
583
+ const causalConsole = fromEntries(methodEntries);
413
584
  return /** @type {VirtualConsole} */ (freeze(causalConsole));
414
585
  };
415
586
  freeze(makeCausalConsole);
@@ -20,9 +20,9 @@ if (typeof abandon === 'function') {
20
20
  /** @param {Error} reason */
21
21
  raise = reason => {
22
22
  // Check `console` each time `raise` is called.
23
- // eslint-disable-next-line no-restricted-globals
23
+
24
24
  if (typeof console === 'object' && typeof console.error === 'function') {
25
- // eslint-disable-next-line @endo/no-polymorphic-call, no-restricted-globals
25
+ // eslint-disable-next-line @endo/no-polymorphic-call
26
26
  console.error('Failed because:', reason);
27
27
  }
28
28
  abandon(1);
@@ -51,7 +51,7 @@ export const enJoin = (terms, conjunction) => {
51
51
  * @param {string} str The noun to prepend
52
52
  * @returns {string} The noun prepended with a/an
53
53
  */
54
- const an = str => {
54
+ export const an = str => {
55
55
  str = `${str}`;
56
56
  if (str.length >= 1 && stringIncludes('aeiouAEIOU', str[0])) {
57
57
  return `an ${str}`;
@@ -59,7 +59,6 @@ const an = str => {
59
59
  return `a ${str}`;
60
60
  };
61
61
  freeze(an);
62
- export { an };
63
62
 
64
63
  /**
65
64
  * Like `JSON.stringify` but does not blow up if given a cycle or a bigint.
@@ -88,7 +87,7 @@ export { an };
88
87
  * @param {(string|number)=} spaces
89
88
  * @returns {string}
90
89
  */
91
- const bestEffortStringify = (payload, spaces = undefined) => {
90
+ export const bestEffortStringify = (payload, spaces = undefined) => {
92
91
  const seenSet = new Set();
93
92
  const replacer = (_, val) => {
94
93
  switch (typeof val) {
@@ -192,4 +191,3 @@ const bestEffortStringify = (payload, spaces = undefined) => {
192
191
  }
193
192
  };
194
193
  freeze(bestEffortStringify);
195
- export { bestEffortStringify };
@@ -51,7 +51,6 @@ export const tameConsole = (
51
51
  };
52
52
  }
53
53
 
54
- // eslint-disable-next-line no-restricted-globals
55
54
  const originalConsole = /** @type {VirtualConsole} */ (
56
55
  // eslint-disable-next-line no-nested-ternary
57
56
  typeof globalThis.console !== 'undefined'
@@ -61,7 +60,6 @@ export const tameConsole = (
61
60
  // log at a specific level with no special argument interpretation).
62
61
  // https://console.spec.whatwg.org/#logging
63
62
  (p => freeze({ debug: p, log: p, info: p, warn: p, error: p }))(
64
- // eslint-disable-next-line no-undef
65
63
  wrapLogger(globalThis.print),
66
64
  )
67
65
  : undefined
@@ -46,7 +46,7 @@ export default function tameErrorConstructor(
46
46
  * @this {ErrorConstructor}
47
47
  * @param {...any} rest
48
48
  */
49
- // eslint-disable-next-line no-shadow
49
+
50
50
  const ResultError = function Error(...rest) {
51
51
  let error;
52
52
  if (new.target === undefined) {
@@ -16,7 +16,6 @@ import {
16
16
  globalThis,
17
17
  assign,
18
18
  AsyncGeneratorFunctionInstance,
19
- ArrayBuffer,
20
19
  } from './commons.js';
21
20
  import { InertCompartment } from './compartment.js';
22
21
 
@@ -54,7 +53,6 @@ export const getAnonymousIntrinsics = () => {
54
53
 
55
54
  // 21.1.5.2 The %StringIteratorPrototype% Object
56
55
 
57
- // eslint-disable-next-line no-new-wrappers
58
56
  const StringIteratorObject = iterateString(new String());
59
57
  const StringIteratorPrototype = getPrototypeOf(StringIteratorObject);
60
58
 
@@ -66,7 +64,6 @@ export const getAnonymousIntrinsics = () => {
66
64
 
67
65
  // 22.1.5.2 The %ArrayIteratorPrototype% Object
68
66
 
69
- // eslint-disable-next-line no-array-constructor
70
67
  const ArrayIteratorObject = iterateArray([]);
71
68
  const ArrayIteratorPrototype = getPrototypeOf(ArrayIteratorObject);
72
69
 
@@ -167,14 +164,5 @@ export const getAnonymousIntrinsics = () => {
167
164
  );
168
165
  }
169
166
 
170
- const ab = new ArrayBuffer(0);
171
- // eslint-disable-next-line @endo/no-polymorphic-call
172
- const iab = ab.sliceToImmutable();
173
- const iabProto = getPrototypeOf(iab);
174
- if (iabProto !== ArrayBuffer.prototype) {
175
- // In a native implementation, these will be the same prototype
176
- intrinsics['%ImmutableArrayBufferPrototype%'] = iabProto;
177
- }
178
-
179
167
  return intrinsics;
180
168
  };
package/src/lockdown.js CHANGED
@@ -36,6 +36,7 @@ import removeUnpermittedIntrinsics from './permits-intrinsics.js';
36
36
  import tameFunctionConstructors from './tame-function-constructors.js';
37
37
  import tameDateConstructor from './tame-date-constructor.js';
38
38
  import tameMathObject from './tame-math-object.js';
39
+ import tameTemporalObject from './tame-temporal-object.js';
39
40
  import { tameNaNSideChannel } from './tame-nan-sidechannel.js';
40
41
  import tameRegExpConstructor from './tame-regexp-constructor.js';
41
42
  import enablePropertyOverrides from './enable-property-overrides.js';
@@ -354,6 +355,7 @@ export const repairIntrinsics = (options = {}) => {
354
355
  addIntrinsics(tameDateConstructor());
355
356
  addIntrinsics(tameErrorConstructor(errorTaming, stackFiltering));
356
357
  addIntrinsics(tameMathObject());
358
+ addIntrinsics(tameTemporalObject());
357
359
  tameNaNSideChannel();
358
360
  addIntrinsics(tameRegExpConstructor(regExpTaming));
359
361
  addIntrinsics(tameSymbolConstructor());
@@ -179,7 +179,6 @@ function* loadWithoutErrorAnnotation(
179
179
  }
180
180
 
181
181
  if (typeof moduleDescriptor === 'string') {
182
- // eslint-disable-next-line @endo/no-polymorphic-call
183
182
  throw makeError(
184
183
  X`Cannot map module ${q(moduleSpecifier)} to ${q(
185
184
  moduleDescriptor,
@@ -491,7 +490,6 @@ const memoizedLoadWithErrorAnnotation = (
491
490
  moduleLoads,
492
491
  ],
493
492
  error => {
494
- // eslint-disable-next-line @endo/no-polymorphic-call
495
493
  annotateError(
496
494
  error,
497
495
  X`${error.message}, loading ${q(moduleSpecifier)} in compartment ${q(
@@ -178,34 +178,26 @@ export default function removeUnpermittedIntrinsics(
178
178
  if (typeof permit === 'string') {
179
179
  // A string permit can have one of two meanings:
180
180
 
181
- if (prop === 'prototype' || prop === 'constructor') {
182
- // For prototype and constructor value properties, the permit
183
- // is the name of an intrinsic.
184
- // Assumption: prototype and constructor cannot be primitives.
185
- // Assert: the permit is the name of an intrinsic.
186
- // Assert: the property value is equal to that intrinsic.
187
-
188
- if (hasOwn(intrinsics, permit)) {
189
- if (value !== intrinsics[permit]) {
190
- throw TypeError(`Does not match permit for ${path}`);
191
- }
192
- return true;
181
+ if (arrayIncludes(primitives, permit)) {
182
+ // The permit is the name of a primitive.
183
+
184
+ if (prop === 'prototype' || prop === 'constructor') {
185
+ throw new TypeError(`At ${path} expected intrinsic, not ${permit}`);
193
186
  }
194
- } else {
195
- // For all other properties, the permit is the name of a primitive.
196
- // Assert: the permit is the name of a primitive.
197
- // Assert: the property value type is equal to that primitive.
198
-
199
- // eslint-disable-next-line no-lonely-if
200
- if (arrayIncludes(primitives, permit)) {
201
- // eslint-disable-next-line valid-typeof
202
- if (typeof value !== permit) {
203
- throw TypeError(
204
- `At ${path} expected ${permit} not ${typeof value}`,
205
- );
206
- }
207
- return true;
187
+ // eslint wants to compare typeof only to string literals
188
+ // eslint-disable-next-line valid-typeof
189
+ if (typeof value !== permit) {
190
+ throw TypeError(`At ${path} expected ${permit} not ${typeof value}`);
191
+ }
192
+ return true;
193
+ }
194
+
195
+ if (hasOwn(intrinsics, permit)) {
196
+ // the permit is the name of an intrinsic.
197
+ if (value !== intrinsics[permit]) {
198
+ throw TypeError(`Does not match permit for ${path}`);
208
199
  }
200
+ return true;
209
201
  }
210
202
  }
211
203