ses 1.3.0 → 1.4.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/index.js CHANGED
@@ -15,3 +15,4 @@
15
15
  import './src/lockdown-shim.js';
16
16
  import './src/compartment-shim.js';
17
17
  import './src/assert-shim.js';
18
+ import './src/console-shim.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ses",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
4
4
  "description": "Hardened JavaScript for Fearless Cooperation",
5
5
  "keywords": [
6
6
  "lockdown",
@@ -66,26 +66,26 @@
66
66
  "test:platform-compatibility": "node test/package/test.cjs"
67
67
  },
68
68
  "dependencies": {
69
- "@endo/env-options": "^1.1.1"
69
+ "@endo/env-options": "^1.1.3"
70
70
  },
71
71
  "devDependencies": {
72
- "@endo/compartment-mapper": "^1.1.2",
73
- "@endo/static-module-record": "^1.0.4",
74
- "@endo/test262-runner": "^0.1.34",
75
- "ava": "^5.3.0",
72
+ "@endo/compartment-mapper": "^1.1.4",
73
+ "@endo/static-module-record": "^1.1.1",
74
+ "@endo/test262-runner": "^0.1.36",
75
+ "ava": "^6.1.2",
76
76
  "babel-eslint": "^10.0.3",
77
77
  "c8": "^7.14.0",
78
78
  "core-js": "^3.31.0",
79
- "eslint": "^8.46.0",
79
+ "eslint": "^8.57.0",
80
80
  "eslint-config-airbnb-base": "^15.0.0",
81
- "eslint-config-prettier": "^8.8.0",
81
+ "eslint-config-prettier": "^9.1.0",
82
82
  "eslint-plugin-eslint-comments": "^3.1.2",
83
83
  "eslint-plugin-import": "^2.29.0",
84
84
  "prettier": "^3.0.0",
85
85
  "sinon": "^15.1.0",
86
86
  "terser": "^5.16.6",
87
- "tsd": "^0.28.1",
88
- "typescript": "~5.3.3"
87
+ "tsd": "^0.30.7",
88
+ "typescript": "~5.5.0-dev.20240327"
89
89
  },
90
90
  "files": [
91
91
  "LICENSE*",
@@ -189,5 +189,5 @@
189
189
  "typeCoverage": {
190
190
  "atLeast": 81.17
191
191
  },
192
- "gitHead": "297fed572fedec0e1ae3ce34cf409f9d45233d43"
192
+ "gitHead": "25229bdcc26babb3afe0c229df4283a0f3c105f3"
193
193
  }
package/src/commons.js CHANGED
@@ -159,6 +159,9 @@ export const arrayIncludes = uncurryThis(arrayPrototype.includes);
159
159
  export const arrayJoin = uncurryThis(arrayPrototype.join);
160
160
  /** @type {<T, U>(thisArg: readonly T[], callbackfn: (value: T, index: number, array: T[]) => U, cbThisArg?: any) => U[]} */
161
161
  export const arrayMap = /** @type {any} */ (uncurryThis(arrayPrototype.map));
162
+ export const arrayFlatMap = /** @type {any} */ (
163
+ uncurryThis(arrayPrototype.flatMap)
164
+ );
162
165
  export const arrayPop = uncurryThis(arrayPrototype.pop);
163
166
  /** @type {<T>(thisArg: T[], ...items: T[]) => number} */
164
167
  export const arrayPush = uncurryThis(arrayPrototype.push);
@@ -0,0 +1,50 @@
1
+ import { symbolFor, globalThis } from './commons.js';
2
+ import { defineCausalConsoleFromLogger } from './error/console.js';
3
+ import { loggedErrorHandler } from './error/assert.js';
4
+
5
+ // TODO possible additional exports. Some are privileged.
6
+ // export { loggedErrorHandler };
7
+ // export {
8
+ // makeCausalConsole,
9
+ // consoleLevelMethods,
10
+ // consoleOtherMethods,
11
+ // makeLoggingConsoleKit,
12
+ // filterConsole,
13
+ // pumpLogToConsole,
14
+ // } from './src/error/console.js';
15
+ // export { assertLogs, throwsAndLogs } from './src/error/throws-and-logs.js';
16
+
17
+ /**
18
+ * Makes a Console like the
19
+ * [SES causal `console`](https://github.com/endojs/endo/blob/master/packages/ses/src/error/README.md)
20
+ * but whose output is redirected to the supplied `logger` function.
21
+ */
22
+ const makeCausalConsoleFromLoggerForSesAva =
23
+ defineCausalConsoleFromLogger(loggedErrorHandler);
24
+
25
+ /**
26
+ *`makeCausalConsoleFromLoggerForSesAva` is privileged because it exposes
27
+ * unredacted error info onto the `Logger` provided by the caller. It
28
+ * should not be made available to non-privileged code.
29
+ *
30
+ * Further, we consider this particular API choice to be experimental
31
+ * and may change in the future. It is currently only intended for use by
32
+ * `@endo/ses-ava`, with which it will be co-maintained.
33
+ *
34
+ * Thus, this `console-shim.js` makes `makeCausalConsoleFromLoggerForSesAva`
35
+ * available on `globalThis` which it *assumes* is the global of the start
36
+ * compartment and is therefore allowed to hold powers that should not be
37
+ * available in constructed compartments. It makes it available as the value of
38
+ * a global property named by a registered symbol named
39
+ * `MAKE_CAUSAL_CONSOLE_FROM_LOGGER_KEY_FOR_SES_AVA`.
40
+ *
41
+ * Anyone accessing this, including `@endo/ses-ava`, should feature test for
42
+ * this and be tolerant of its absence. It may indeed disappear from later
43
+ * versions of the ses-shim.
44
+ */
45
+ const MAKE_CAUSAL_CONSOLE_FROM_LOGGER_KEY_FOR_SES_AVA = symbolFor(
46
+ 'MAKE_CAUSAL_CONSOLE_FROM_LOGGER_KEY_FOR_SES_AVA',
47
+ );
48
+
49
+ globalThis[MAKE_CAUSAL_CONSOLE_FROM_LOGGER_KEY_FOR_SES_AVA] =
50
+ makeCausalConsoleFromLoggerForSesAva;
@@ -6,7 +6,15 @@ Summary
6
6
  * SES tames the global `console` and grants it the ability to reveal error annotations and stacks to the actual console.
7
7
  * Both `assert` and `console` are powerful globals that SES does not implicitly carry into child compartments. When creating a child compartment, add `assert` to the compartment’s globals. Either add `console` too, or add a wrapper that annotates the console with a topic.
8
8
  * SES hides annotations and stack traces by default. To reveal them, SES uses mechanisms like `process.on("uncaughtException")` in Node.js to catch the error and log it back to the `console` tamed by `lockdown`.
9
- * In the scope of the Agoric software ecosystem, this architecture will allow us to eventually introduce a more powerful distributed `console` that can meaningfully capture stack traces for a distributed debugger, based on the design of [Causeway](https://github.com/Agoric/agoric-sdk/issues/1318#issuecomment-662127549).
9
+
10
+ We refer to the enhanced `console`, installed by default by the ses shim, as the *causal console*, because the annotations it reveals are often used to show causality information. For example, with the [`TRACK_TURNS=enabled`](https://github.com/Agoric/agoric-sdk/blob/master/docs/env.md#track_turns) and [`DEBUG=track-turns`](https://github.com/Agoric/agoric-sdk/blob/master/docs/env.md#debug) environment options set
11
+ ```sh
12
+ # in bash syntax
13
+ export DEBUG=track-turns
14
+ export TRACK_TURNS=enabled
15
+ ```
16
+ the @endo/eventual-send package will use annotations to show where previous `E` operations (either eventual sends or `E.when`) in previous turns *locally in the same vat* caused the turn with the current error. This is sometimes called "deep asynchronous stacks".
17
+ * In the scope of the Agoric software ecosystem, this architecture will allow us to eventually introduce a more powerful distributed causal `console` that can meaningfully capture stack traces for a distributed debugger, based on the design of [Causeway](https://github.com/Agoric/agoric-sdk/issues/1318#issuecomment-662127549).
10
18
 
11
19
 
12
20
  ## Goals, non-goals, and partial goals
@@ -8,13 +8,17 @@
8
8
  import {
9
9
  WeakSet,
10
10
  arrayFilter,
11
+ arrayFlatMap,
11
12
  arrayMap,
13
+ arrayPop,
12
14
  arrayPush,
13
15
  defineProperty,
14
16
  freeze,
15
17
  fromEntries,
16
18
  isError,
17
19
  stringEndsWith,
20
+ stringIncludes,
21
+ stringSplit,
18
22
  weaksetAdd,
19
23
  weaksetHas,
20
24
  } from '../commons.js';
@@ -46,8 +50,17 @@ import './internal-types.js';
46
50
 
47
51
  /** @typedef {keyof VirtualConsole | 'profile' | 'profileEnd'} ConsoleProps */
48
52
 
49
- /** @type {readonly [ConsoleProps, LogSeverity | undefined][]} */
50
- const consoleLevelMethods = freeze([
53
+ /**
54
+ * Those console methods whose actual parameters are `(fmt?, ...args)`
55
+ * even if their TypeScript types claim otherwise.
56
+ *
57
+ * Each is paired with what we consider to be their log severity level.
58
+ * This is the same as the log severity of these on other
59
+ * platform console implementations when they all agree.
60
+ *
61
+ * @type {readonly [ConsoleProps, LogSeverity | undefined][]}
62
+ */
63
+ export const consoleLevelMethods = freeze([
51
64
  ['debug', 'debug'], // (fmt?, ...args) verbose level on Chrome
52
65
  ['log', 'log'], // (fmt?, ...args) info level on Chrome
53
66
  ['info', 'info'], // (fmt?, ...args)
@@ -55,13 +68,22 @@ const consoleLevelMethods = freeze([
55
68
  ['error', 'error'], // (fmt?, ...args)
56
69
 
57
70
  ['trace', 'log'], // (fmt?, ...args)
58
- ['dirxml', 'log'], // (fmt?, ...args)
59
- ['group', 'log'], // (fmt?, ...args)
60
- ['groupCollapsed', 'log'], // (fmt?, ...args)
71
+ ['dirxml', 'log'], // (fmt?, ...args) but TS typed (...data)
72
+ ['group', 'log'], // (fmt?, ...args) but TS typed (...label)
73
+ ['groupCollapsed', 'log'], // (fmt?, ...args) but TS typed (...label)
61
74
  ]);
62
75
 
63
- /** @type {readonly [ConsoleProps, LogSeverity | undefined][]} */
64
- const consoleOtherMethods = freeze([
76
+ /**
77
+ * Those console methods other than those already enumerated by
78
+ * `consoleLevelMethods`.
79
+ *
80
+ * Each is paired with what we consider to be their log severity level.
81
+ * This is the same as the log severity of these on other
82
+ * platform console implementations when they all agree.
83
+ *
84
+ * @type {readonly [ConsoleProps, LogSeverity | undefined][]}
85
+ */
86
+ export const consoleOtherMethods = freeze([
65
87
  ['assert', 'error'], // (value, fmt?, ...args)
66
88
  ['timeLog', 'log'], // (label?, ...args) no fmt string
67
89
 
@@ -85,7 +107,7 @@ const consoleOtherMethods = freeze([
85
107
  ]);
86
108
 
87
109
  /** @type {readonly [ConsoleProps, LogSeverity | undefined][]} */
88
- export const consoleWhitelist = freeze([
110
+ const consoleWhitelist = freeze([
89
111
  ...consoleLevelMethods,
90
112
  ...consoleOtherMethods,
91
113
  ]);
@@ -117,10 +139,10 @@ export const consoleWhitelist = freeze([
117
139
  * ]);
118
140
  */
119
141
 
120
- // /////////////////////////////////////////////////////////////////////////////
142
+ // //////////////////////////// Logging Console ////////////////////////////////
121
143
 
122
144
  /** @type {MakeLoggingConsoleKit} */
123
- const makeLoggingConsoleKit = (
145
+ export const makeLoggingConsoleKit = (
124
146
  loggedErrorHandler,
125
147
  { shouldResetForDebugging = false } = {},
126
148
  ) => {
@@ -161,9 +183,23 @@ const makeLoggingConsoleKit = (
161
183
  return freeze({ loggingConsole: typedLoggingConsole, takeLog });
162
184
  };
163
185
  freeze(makeLoggingConsoleKit);
164
- export { makeLoggingConsoleKit };
165
186
 
166
- // /////////////////////////////////////////////////////////////////////////////
187
+ /**
188
+ * Makes the same calls on a `baseConsole` that were made on a
189
+ * `loggingConsole` to produce this `log`. In this way, a logging console
190
+ * can be used as a buffer to delay the application of these calls to a
191
+ * `baseConsole`.
192
+ *
193
+ * @param {LogRecord[]} log
194
+ * @param {VirtualConsole} baseConsole
195
+ */
196
+ export const pumpLogToConsole = (log, baseConsole) => {
197
+ for (const [name, ...args] of log) {
198
+ // eslint-disable-next-line @endo/no-polymorphic-call
199
+ baseConsole[name](...args);
200
+ }
201
+ };
202
+ // //////////////////////////// Causal Console /////////////////////////////////
167
203
 
168
204
  /** @type {ErrorInfo} */
169
205
  const ErrorInfo = {
@@ -175,7 +211,7 @@ const ErrorInfo = {
175
211
  freeze(ErrorInfo);
176
212
 
177
213
  /** @type {MakeCausalConsole} */
178
- const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
214
+ export const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
179
215
  if (!baseConsole) {
180
216
  return undefined;
181
217
  }
@@ -362,12 +398,106 @@ const makeCausalConsole = (baseConsole, loggedErrorHandler) => {
362
398
  return /** @type {VirtualConsole} */ (freeze(causalConsole));
363
399
  };
364
400
  freeze(makeCausalConsole);
365
- export { makeCausalConsole };
366
401
 
367
- // /////////////////////////////////////////////////////////////////////////////
402
+ /**
403
+ * @typedef {(...args: unknown[]) => void} Logger
404
+ */
405
+
406
+ /**
407
+ * This is a rather horrible kludge to indent the output to a logger in
408
+ * the case where some arguments are strings containing newlines. Part of
409
+ * the problem is that console-like loggers, including the one in ava,
410
+ * join the string arguments of the log message with a space.
411
+ * Because of this, there's an extra space at the beginning of each of
412
+ * the split lines. So this kludge compensated by putting an extra empty
413
+ * string at the beginning, so that the logger will add the same extra
414
+ * joiner.
415
+ * TODO: Fix this horrible kludge, and indent in a sane manner.
416
+ *
417
+ * @param {string} str
418
+ * @param {string} sep
419
+ * @param {string[]} indents
420
+ * @returns {string[]}
421
+ */
422
+ const indentAfterAllSeps = (str, sep, indents) => {
423
+ const [firstLine, ...restLines] = stringSplit(str, sep);
424
+ const indentedRest = arrayFlatMap(restLines, line => [sep, ...indents, line]);
425
+ return ['', firstLine, ...indentedRest];
426
+ };
427
+
428
+ /**
429
+ * @param {LoggedErrorHandler} loggedErrorHandler
430
+ */
431
+ export const defineCausalConsoleFromLogger = loggedErrorHandler => {
432
+ /**
433
+ * Implement the `VirtualConsole` API badly by turning all calls into
434
+ * calls on `tlogger`. We need to do this to have `console` logging
435
+ * turn into calls to Ava's `t.log`, so these console log messages
436
+ * are output in the right place.
437
+ *
438
+ * @param {Logger} tlogger
439
+ * @returns {VirtualConsole}
440
+ */
441
+ const makeCausalConsoleFromLogger = tlogger => {
442
+ const indents = [];
443
+ const logWithIndent = (...args) => {
444
+ if (indents.length > 0) {
445
+ args = arrayFlatMap(args, arg =>
446
+ typeof arg === 'string' && stringIncludes(arg, '\n')
447
+ ? indentAfterAllSeps(arg, '\n', indents)
448
+ : [arg],
449
+ );
450
+ args = [...indents, ...args];
451
+ }
452
+ return tlogger(...args);
453
+ };
454
+ const makeNamed = (name, fn) =>
455
+ ({ [name]: (...args) => fn(...args) })[name];
456
+
457
+ const baseConsole = fromEntries([
458
+ ...arrayMap(consoleLevelMethods, ([name]) => [
459
+ name,
460
+ makeNamed(name, logWithIndent),
461
+ ]),
462
+ ...arrayMap(consoleOtherMethods, ([name]) => [
463
+ name,
464
+ makeNamed(name, (...args) => logWithIndent(name, ...args)),
465
+ ]),
466
+ ]);
467
+ // https://console.spec.whatwg.org/#grouping
468
+ for (const name of ['group', 'groupCollapsed']) {
469
+ if (baseConsole[name]) {
470
+ baseConsole[name] = makeNamed(name, (...args) => {
471
+ if (args.length >= 1) {
472
+ // Prefix the logged data with "group" or "groupCollapsed".
473
+ logWithIndent(...args);
474
+ }
475
+ // A single space is enough;
476
+ // the host console will separate them with additional spaces.
477
+ arrayPush(indents, ' ');
478
+ });
479
+ }
480
+ }
481
+ if (baseConsole.groupEnd) {
482
+ baseConsole.groupEnd = makeNamed('groupEnd', (...args) => {
483
+ arrayPop(indents);
484
+ });
485
+ }
486
+ harden(baseConsole);
487
+ const causalConsole = makeCausalConsole(
488
+ /** @type {VirtualConsole} */ (baseConsole),
489
+ loggedErrorHandler,
490
+ );
491
+ return /** @type {VirtualConsole} */ (causalConsole);
492
+ };
493
+ return freeze(makeCausalConsoleFromLogger);
494
+ };
495
+ freeze(defineCausalConsoleFromLogger);
496
+
497
+ // ///////////////////////// Filter Console ////////////////////////////////////
368
498
 
369
499
  /** @type {FilterConsole} */
370
- const filterConsole = (baseConsole, filter, _topic = undefined) => {
500
+ export const filterConsole = (baseConsole, filter, _topic = undefined) => {
371
501
  // TODO do something with optional topic string
372
502
  const whitelist = arrayFilter(
373
503
  consoleWhitelist,
@@ -391,4 +521,3 @@ const filterConsole = (baseConsole, filter, _topic = undefined) => {
391
521
  return /** @type {VirtualConsole} */ (freeze(filteringConsole));
392
522
  };
393
523
  freeze(filterConsole);
394
- export { filterConsole };
@@ -7,8 +7,10 @@ import './assert-sloppy-mode.js';
7
7
  import { globalThis } from './commons.js';
8
8
  import { repairIntrinsics } from './lockdown.js';
9
9
 
10
+ /** @import {LockdownOptions} from '../types.js' */
11
+
10
12
  /**
11
- * @param {import('./lockdown.js').LockdownOptions} options
13
+ * @param {LockdownOptions} options
12
14
  */
13
15
  globalThis.lockdown = options => {
14
16
  const hardenIntrinsics = repairIntrinsics(options);
@@ -16,7 +18,7 @@ globalThis.lockdown = options => {
16
18
  };
17
19
 
18
20
  /**
19
- * @param {import('./lockdown.js').LockdownOptions} options
21
+ * @param {LockdownOptions} options
20
22
  */
21
23
  globalThis.repairIntrinsics = options => {
22
24
  const hardenIntrinsics = repairIntrinsics(options);
package/src/lockdown.js CHANGED
@@ -56,7 +56,7 @@ import { tameHarden } from './tame-harden.js';
56
56
  import { tameSymbolConstructor } from './tame-symbol-constructor.js';
57
57
  import { tameFauxDataProperties } from './tame-faux-data-properties.js';
58
58
 
59
- /** @typedef {import('../types.js').LockdownOptions} LockdownOptions */
59
+ /** @import {LockdownOptions} from '../types.js' */
60
60
 
61
61
  const { Fail, details: d, quote: q } = assert;
62
62
 
@@ -6,7 +6,7 @@
6
6
  * @param {Function} safeEvaluate
7
7
  */
8
8
  export const makeEvalFunction = safeEvaluate => {
9
- // We use the the concise method syntax to create an eval without a
9
+ // We use the concise method syntax to create an eval without a
10
10
  // [[Construct]] behavior (such that the invocation "new eval()" throws
11
11
  // TypeError: eval is not a constructor"), but which still accepts a
12
12
  // 'this' binding.
@@ -53,7 +53,7 @@ import {
53
53
  import { assert } from './error/assert.js';
54
54
 
55
55
  /**
56
- * @typedef {import('../types.js').Harden} Harden
56
+ * @import {Harden} from '../types.js'
57
57
  */
58
58
 
59
59
  // Obtain the string tag accessor of of TypedArray so we can indirectly use the
@@ -25,11 +25,6 @@ export default function tameRegExpConstructor(regExpTaming = 'safe') {
25
25
  return construct(FERAL_REG_EXP, rest, new.target);
26
26
  };
27
27
 
28
- const speciesDesc = getOwnPropertyDescriptor(FERAL_REG_EXP, speciesSymbol);
29
- if (!speciesDesc) {
30
- throw TypeError('no RegExp[Symbol.species] descriptor');
31
- }
32
-
33
28
  defineProperties(ResultRegExp, {
34
29
  length: { value: 2 },
35
30
  prototype: {
@@ -38,8 +33,20 @@ export default function tameRegExpConstructor(regExpTaming = 'safe') {
38
33
  enumerable: false,
39
34
  configurable: false,
40
35
  },
41
- [speciesSymbol]: speciesDesc,
42
36
  });
37
+ // Hermes does not have `Symbol.species`. We should support such platforms.
38
+ if (speciesSymbol) {
39
+ const speciesDesc = getOwnPropertyDescriptor(
40
+ FERAL_REG_EXP,
41
+ speciesSymbol,
42
+ );
43
+ if (!speciesDesc) {
44
+ throw TypeError('no RegExp[Symbol.species] descriptor');
45
+ }
46
+ defineProperties(ResultRegExp, {
47
+ [speciesSymbol]: speciesDesc,
48
+ });
49
+ }
43
50
  return ResultRegExp;
44
51
  };
45
52