ses 1.4.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,36 +1,59 @@
1
- // For brevity, in this file, as in module-link.js, the term "moduleRecord"
2
- // without qualification means "module compartment record".
3
- // This is a super-set of the "static module record", that is reusable between
4
- // compartments with different hooks.
5
- // The "module compartment record" captures the compartment and overlays the
6
- // module's "imports" with the more specific "resolvedImports" as inferred from
7
- // the particular compartment's "resolveHook".
8
-
1
+ import { getEnvironmentOption as getenv } from '@endo/env-options';
9
2
  import {
10
- ReferenceError,
11
- TypeError,
12
3
  Map,
13
4
  Set,
5
+ TypeError,
14
6
  arrayJoin,
15
7
  arrayMap,
16
8
  arrayPush,
17
9
  create,
18
10
  freeze,
11
+ generatorNext,
12
+ generatorThrow,
13
+ getOwnPropertyNames,
14
+ isObject,
19
15
  mapGet,
20
16
  mapHas,
21
17
  mapSet,
22
- setAdd,
23
- promiseCatch,
24
18
  promiseThen,
19
+ setAdd,
25
20
  values,
26
21
  weakmapGet,
22
+ weakmapHas,
27
23
  } from './commons.js';
28
- import { assert } from './error/assert.js';
29
-
30
- const { Fail, details: d, quote: q } = assert;
24
+ import { makeError, annotateError, q, X } from './error/assert.js';
31
25
 
32
26
  const noop = () => {};
33
27
 
28
+ const asyncTrampoline = async (generatorFunc, args, errorWrapper) => {
29
+ await null;
30
+ const iterator = generatorFunc(...args);
31
+ let result = generatorNext(iterator);
32
+ while (!result.done) {
33
+ try {
34
+ // eslint-disable-next-line no-await-in-loop
35
+ const val = await result.value;
36
+ result = generatorNext(iterator, val);
37
+ } catch (error) {
38
+ result = generatorThrow(iterator, errorWrapper(error));
39
+ }
40
+ }
41
+ return result.value;
42
+ };
43
+
44
+ const syncTrampoline = (generatorFunc, args) => {
45
+ const iterator = generatorFunc(...args);
46
+ let result = generatorNext(iterator);
47
+ while (!result.done) {
48
+ try {
49
+ result = generatorNext(iterator, result.value);
50
+ } catch (error) {
51
+ result = generatorThrow(iterator, error);
52
+ }
53
+ }
54
+ return result.value;
55
+ };
56
+
34
57
  // `makeAlias` constructs compartment specifier tuples for the `aliases`
35
58
  // private field of compartments.
36
59
  // These aliases allow a compartment to alias an internal module specifier to a
@@ -38,10 +61,7 @@ const noop = () => {};
38
61
  // aliases.
39
62
  // Both are facilitated by the moduleMap Compartment constructor option.
40
63
  export const makeAlias = (compartment, specifier) =>
41
- freeze({
42
- compartment,
43
- specifier,
44
- });
64
+ freeze({ compartment, specifier });
45
65
 
46
66
  // `resolveAll` pre-computes resolutions of all imports within the compartment
47
67
  // in which a module was loaded.
@@ -54,31 +74,28 @@ const resolveAll = (imports, resolveHook, fullReferrerSpecifier) => {
54
74
  return freeze(resolvedImports);
55
75
  };
56
76
 
57
- const loadRecord = (
77
+ const loadModuleSource = (
58
78
  compartmentPrivateFields,
59
79
  moduleAliases,
60
80
  compartment,
61
81
  moduleSpecifier,
62
- staticModuleRecord,
63
- pendingJobs,
82
+ moduleSource,
83
+ enqueueJob,
84
+ selectImplementation,
64
85
  moduleLoads,
65
- errors,
66
86
  importMeta,
67
87
  ) => {
68
- const { resolveHook, moduleRecords } = weakmapGet(
69
- compartmentPrivateFields,
70
- compartment,
71
- );
88
+ const { resolveHook } = weakmapGet(compartmentPrivateFields, compartment);
72
89
 
73
90
  // resolve all imports relative to this referrer module.
74
91
  const resolvedImports = resolveAll(
75
- staticModuleRecord.imports,
92
+ moduleSource.imports,
76
93
  resolveHook,
77
94
  moduleSpecifier,
78
95
  );
79
96
  const moduleRecord = freeze({
80
97
  compartment,
81
- staticModuleRecord,
98
+ moduleSource,
82
99
  moduleSpecifier,
83
100
  resolvedImports,
84
101
  importMeta,
@@ -88,171 +105,352 @@ const loadRecord = (
88
105
  for (const fullSpecifier of values(resolvedImports)) {
89
106
  // Behold: recursion.
90
107
  // eslint-disable-next-line no-use-before-define
91
- const dependencyLoaded = memoizedLoadWithErrorAnnotation(
108
+ enqueueJob(memoizedLoadWithErrorAnnotation, [
92
109
  compartmentPrivateFields,
93
110
  moduleAliases,
94
111
  compartment,
95
112
  fullSpecifier,
96
- pendingJobs,
113
+ enqueueJob,
114
+ selectImplementation,
97
115
  moduleLoads,
98
- errors,
99
- );
100
- setAdd(
101
- pendingJobs,
102
- promiseThen(dependencyLoaded, noop, error => {
103
- arrayPush(errors, error);
104
- }),
105
- );
116
+ ]);
106
117
  }
107
118
 
108
- // Memoize.
109
- mapSet(moduleRecords, moduleSpecifier, moduleRecord);
110
119
  return moduleRecord;
111
120
  };
112
121
 
113
- const loadWithoutErrorAnnotation = async (
122
+ function* loadWithoutErrorAnnotation(
114
123
  compartmentPrivateFields,
115
124
  moduleAliases,
116
125
  compartment,
117
126
  moduleSpecifier,
118
- pendingJobs,
127
+ enqueueJob,
128
+ selectImplementation,
119
129
  moduleLoads,
120
- errors,
121
- ) => {
122
- const { importHook, moduleMap, moduleMapHook, moduleRecords } = weakmapGet(
123
- compartmentPrivateFields,
124
- compartment,
125
- );
130
+ ) {
131
+ const {
132
+ importHook,
133
+ importNowHook,
134
+ moduleMap,
135
+ moduleMapHook,
136
+ moduleRecords,
137
+ parentCompartment,
138
+ } = weakmapGet(compartmentPrivateFields, compartment);
139
+
140
+ if (mapHas(moduleRecords, moduleSpecifier)) {
141
+ return mapGet(moduleRecords, moduleSpecifier);
142
+ }
126
143
 
127
144
  // Follow moduleMap, or moduleMapHook if present.
128
- let aliasNamespace = moduleMap[moduleSpecifier];
129
- if (aliasNamespace === undefined && moduleMapHook !== undefined) {
130
- aliasNamespace = moduleMapHook(moduleSpecifier);
145
+ let moduleDescriptor = moduleMap[moduleSpecifier];
146
+ if (moduleDescriptor === undefined && moduleMapHook !== undefined) {
147
+ moduleDescriptor = moduleMapHook(moduleSpecifier);
131
148
  }
132
- if (typeof aliasNamespace === 'string') {
133
- // eslint-disable-next-line @endo/no-polymorphic-call
134
- assert.fail(
135
- d`Cannot map module ${q(moduleSpecifier)} to ${q(
136
- aliasNamespace,
137
- )} in parent compartment, not yet implemented`,
138
- TypeError,
139
- );
140
- } else if (aliasNamespace !== undefined) {
141
- const alias = weakmapGet(moduleAliases, aliasNamespace);
142
- if (alias === undefined) {
143
- // eslint-disable-next-line @endo/no-polymorphic-call
144
- assert.fail(
145
- d`Cannot map module ${q(
149
+ if (moduleDescriptor === undefined) {
150
+ const moduleHook = selectImplementation(importHook, importNowHook);
151
+ if (moduleHook === undefined) {
152
+ const moduleHookName = selectImplementation(
153
+ 'importHook',
154
+ 'importNowHook',
155
+ );
156
+ throw makeError(
157
+ X`${moduleHookName} needed to load module ${q(
146
158
  moduleSpecifier,
147
- )} because the value is not a module exports namespace, or is from another realm`,
148
- ReferenceError,
159
+ )} in compartment ${q(compartment.name)}`,
149
160
  );
150
161
  }
151
- // Behold: recursion.
152
- // eslint-disable-next-line no-use-before-define
153
- const aliasRecord = await memoizedLoadWithErrorAnnotation(
154
- compartmentPrivateFields,
155
- moduleAliases,
156
- alias.compartment,
157
- alias.specifier,
158
- pendingJobs,
159
- moduleLoads,
160
- errors,
161
- );
162
- mapSet(moduleRecords, moduleSpecifier, aliasRecord);
163
- return aliasRecord;
162
+ moduleDescriptor = moduleHook(moduleSpecifier);
163
+ // Uninitialized module namespaces throw if we attempt to coerce them into
164
+ // promises.
165
+ if (!weakmapHas(moduleAliases, moduleDescriptor)) {
166
+ moduleDescriptor = yield moduleDescriptor;
167
+ }
164
168
  }
165
169
 
166
- if (mapHas(moduleRecords, moduleSpecifier)) {
167
- return mapGet(moduleRecords, moduleSpecifier);
168
- }
170
+ if (typeof moduleDescriptor === 'string') {
171
+ // eslint-disable-next-line @endo/no-polymorphic-call
172
+ throw makeError(
173
+ X`Cannot map module ${q(moduleSpecifier)} to ${q(
174
+ moduleDescriptor,
175
+ )} in parent compartment, use {source} module descriptor`,
176
+ TypeError,
177
+ );
178
+ } else if (isObject(moduleDescriptor)) {
179
+ // In this shim (and not in XS, and not in the standard we imagine), we
180
+ // allow a module namespace object to stand in for a module descriptor that
181
+ // describes its original {compartment, specifier} so that it can be used
182
+ // to create a link.
183
+ let aliasDescriptor = weakmapGet(moduleAliases, moduleDescriptor);
184
+ if (aliasDescriptor !== undefined) {
185
+ moduleDescriptor = aliasDescriptor;
186
+ }
169
187
 
170
- const staticModuleRecord = await importHook(moduleSpecifier);
188
+ if (moduleDescriptor.namespace !== undefined) {
189
+ // { namespace: string, compartment?: Compartment }
190
+ // Namespace module descriptors link to a module instance.
171
191
 
172
- if (staticModuleRecord === null || typeof staticModuleRecord !== 'object') {
173
- Fail`importHook must return a promise for an object, for module ${q(
174
- moduleSpecifier,
175
- )} in compartment ${q(compartment.name)}`;
176
- }
192
+ if (typeof moduleDescriptor.namespace === 'string') {
193
+ // The default compartment is the *parent*, not this child compartment.
194
+ // This is a difference from the legacy {specifier, compartment} module
195
+ // descriptor.
196
+ const {
197
+ compartment: aliasCompartment = parentCompartment,
198
+ namespace: aliasSpecifier,
199
+ } = moduleDescriptor;
200
+ if (
201
+ !isObject(aliasCompartment) ||
202
+ !weakmapHas(compartmentPrivateFields, aliasCompartment)
203
+ ) {
204
+ throw makeError(
205
+ X`Invalid compartment in module descriptor for specifier ${q(moduleSpecifier)} in compartment ${q(compartment.name)}`,
206
+ );
207
+ }
208
+ // Behold: recursion.
209
+ // eslint-disable-next-line no-use-before-define
210
+ const aliasRecord = yield memoizedLoadWithErrorAnnotation(
211
+ compartmentPrivateFields,
212
+ moduleAliases,
213
+ aliasCompartment,
214
+ aliasSpecifier,
215
+ enqueueJob,
216
+ selectImplementation,
217
+ moduleLoads,
218
+ );
219
+ mapSet(moduleRecords, moduleSpecifier, aliasRecord);
220
+ return aliasRecord;
221
+ }
177
222
 
178
- // check if record is a RedirectStaticModuleInterface
179
- if (staticModuleRecord.specifier !== undefined) {
180
- // check if this redirect with an explicit record
181
- if (staticModuleRecord.record !== undefined) {
182
- // ensure expected record shape
183
- if (staticModuleRecord.compartment !== undefined) {
184
- throw TypeError(
185
- 'Cannot redirect to an explicit record with a specified compartment',
223
+ // All remaining objects must either be a module namespace, or be
224
+ // promoted into a module namespace with a virtual module source.
225
+ if (isObject(moduleDescriptor.namespace)) {
226
+ const { namespace } = moduleDescriptor;
227
+ // Brand-check SES shim module exports namespaces:
228
+ aliasDescriptor = weakmapGet(moduleAliases, namespace);
229
+ if (aliasDescriptor !== undefined) {
230
+ moduleDescriptor = aliasDescriptor;
231
+ // Fall through to processing the resulting {compartment, specifier}
232
+ // alias.
233
+ } else {
234
+ // Promote an arbitrary object to a module namespace with a virtual
235
+ // module source.
236
+ // { namespace: Object }
237
+ const exports = getOwnPropertyNames(namespace);
238
+ /** @type {import('../types.js').VirtualModuleSource} */
239
+ const moduleSource = {
240
+ imports: [],
241
+ exports,
242
+ execute(env) {
243
+ for (const name of exports) {
244
+ env[name] = namespace[name];
245
+ }
246
+ },
247
+ };
248
+ const importMeta = undefined;
249
+ const moduleRecord = loadModuleSource(
250
+ compartmentPrivateFields,
251
+ moduleAliases,
252
+ compartment,
253
+ moduleSpecifier,
254
+ moduleSource,
255
+ enqueueJob,
256
+ selectImplementation,
257
+ moduleLoads,
258
+ importMeta,
259
+ );
260
+ mapSet(moduleRecords, moduleSpecifier, moduleRecord);
261
+ return moduleRecord;
262
+ }
263
+ } else {
264
+ throw makeError(
265
+ X`Invalid compartment in module descriptor for specifier ${q(moduleSpecifier)} in compartment ${q(compartment.name)}`,
186
266
  );
187
267
  }
268
+ }
269
+
270
+ if (moduleDescriptor.source !== undefined) {
271
+ // Module source descriptors create an instance from a module source.
272
+ // The descriptor may contain the module source, or refer to a source
273
+ // loaded in a particular compartment.
274
+
275
+ if (typeof moduleDescriptor.source === 'string') {
276
+ // { source: string, importMeta?, specifier?: string, compartment? }
277
+ // A string source is the specifier for a different module source.
278
+ // That source may come from this compartment's parent (default), or
279
+ // from a specified compartment, and the specified compartment may be
280
+ // this compartment to make a duplicate.
281
+
282
+ const {
283
+ source: loaderSpecifier,
284
+ specifier: instanceSpecifier = moduleSpecifier,
285
+ compartment: loaderCompartment = parentCompartment,
286
+ importMeta = undefined,
287
+ } = moduleDescriptor;
288
+
289
+ // Induce the compartment, possibly a different compartment
290
+ // to load a module source.
291
+
292
+ // Behold: recursion.
293
+ // eslint-disable-next-line no-use-before-define
294
+ const loaderRecord = yield memoizedLoadWithErrorAnnotation(
295
+ compartmentPrivateFields,
296
+ moduleAliases,
297
+ loaderCompartment,
298
+ loaderSpecifier,
299
+ enqueueJob,
300
+ selectImplementation,
301
+ moduleLoads,
302
+ );
303
+
304
+ // Extract the source of the module from the loader compartment's
305
+ // record.
306
+ const { moduleSource } = loaderRecord;
307
+
308
+ // Instantiate that source in our own compartment, possibly with a
309
+ // different specifier for resolving its own imports.
310
+ const moduleRecord = loadModuleSource(
311
+ compartmentPrivateFields,
312
+ moduleAliases,
313
+ compartment,
314
+ instanceSpecifier,
315
+ moduleSource,
316
+ enqueueJob,
317
+ selectImplementation,
318
+ moduleLoads,
319
+ importMeta,
320
+ );
321
+ mapSet(moduleRecords, moduleSpecifier, moduleRecord);
322
+ return moduleRecord;
323
+ } else {
324
+ // { source: ModuleSource, importMeta?, specifier?: string }
325
+ // We assume all non-string module sources are any of the supported
326
+ // kinds of module source: PrecompiledModuleSource,
327
+ // VirtualModuleSource, or a native ModuleSource.
328
+
329
+ const {
330
+ source: moduleSource,
331
+ specifier: aliasSpecifier = moduleSpecifier,
332
+ importMeta,
333
+ } = moduleDescriptor;
334
+
335
+ const aliasRecord = loadModuleSource(
336
+ compartmentPrivateFields,
337
+ moduleAliases,
338
+ compartment,
339
+ aliasSpecifier,
340
+ moduleSource,
341
+ enqueueJob,
342
+ selectImplementation,
343
+ moduleLoads,
344
+ importMeta,
345
+ );
346
+ mapSet(moduleRecords, moduleSpecifier, aliasRecord);
347
+ return aliasRecord;
348
+ }
349
+ }
350
+
351
+ if (moduleDescriptor.archive !== undefined) {
352
+ // { archive: Archive, path: string }
353
+ // We do not support this XS-native module descriptor.
354
+ throw makeError(
355
+ X`Unsupported archive module descriptor for specifier ${q(moduleSpecifier)} in compartment ${q(compartment.name)}`,
356
+ );
357
+ }
358
+
359
+ // { record, specifier?, compartment?, importMeta? }
360
+ // A (legacy) module descriptor for when we find the module source (record)
361
+ // but at a different specifier than requested.
362
+ // Providing this {specifier, record} descriptor serves as an ergonomic
363
+ // short-hand for stashing the record, returning a {compartment, specifier}
364
+ // reference, bouncing the module hook, then producing the source (record)
365
+ // when module hook receives the response specifier.
366
+ if (moduleDescriptor.record !== undefined) {
188
367
  const {
189
368
  compartment: aliasCompartment = compartment,
190
369
  specifier: aliasSpecifier = moduleSpecifier,
191
- record: aliasModuleRecord,
370
+ record: moduleSource,
192
371
  importMeta,
193
- } = staticModuleRecord;
372
+ } = moduleDescriptor;
194
373
 
195
- const aliasRecord = loadRecord(
374
+ const aliasRecord = loadModuleSource(
196
375
  compartmentPrivateFields,
197
376
  moduleAliases,
198
377
  aliasCompartment,
199
378
  aliasSpecifier,
200
- aliasModuleRecord,
201
- pendingJobs,
379
+ moduleSource,
380
+ enqueueJob,
381
+ selectImplementation,
202
382
  moduleLoads,
203
- errors,
204
383
  importMeta,
205
384
  );
206
385
  mapSet(moduleRecords, moduleSpecifier, aliasRecord);
386
+ mapSet(moduleRecords, aliasSpecifier, aliasRecord);
207
387
  return aliasRecord;
208
388
  }
209
389
 
210
- // check if this redirect with an explicit compartment
211
- if (staticModuleRecord.compartment !== undefined) {
212
- // ensure expected record shape
213
- if (staticModuleRecord.importMeta !== undefined) {
214
- throw TypeError(
215
- 'Cannot redirect to an implicit record with a specified importMeta',
390
+ // { specifier: string, compartment: Compartment }
391
+ // A (legacy) module descriptor that describes a link to a module instance
392
+ // in a specified compartment.
393
+ if (
394
+ moduleDescriptor.compartment !== undefined &&
395
+ moduleDescriptor.specifier !== undefined
396
+ ) {
397
+ if (
398
+ !isObject(moduleDescriptor.compartment) ||
399
+ !weakmapHas(compartmentPrivateFields, moduleDescriptor.compartment) ||
400
+ typeof moduleDescriptor.specifier !== 'string'
401
+ ) {
402
+ throw makeError(
403
+ X`Invalid compartment in module descriptor for specifier ${q(moduleSpecifier)} in compartment ${q(compartment.name)}`,
216
404
  );
217
405
  }
218
406
  // Behold: recursion.
219
407
  // eslint-disable-next-line no-use-before-define
220
- const aliasRecord = await memoizedLoadWithErrorAnnotation(
408
+ const aliasRecord = yield memoizedLoadWithErrorAnnotation(
221
409
  compartmentPrivateFields,
222
410
  moduleAliases,
223
- staticModuleRecord.compartment,
224
- staticModuleRecord.specifier,
225
- pendingJobs,
411
+ moduleDescriptor.compartment,
412
+ moduleDescriptor.specifier,
413
+ enqueueJob,
414
+ selectImplementation,
226
415
  moduleLoads,
227
- errors,
228
416
  );
229
417
  mapSet(moduleRecords, moduleSpecifier, aliasRecord);
230
418
  return aliasRecord;
231
419
  }
232
420
 
233
- throw TypeError('Unnexpected RedirectStaticModuleInterface record shape');
421
+ // A (legacy) behavior: If we do not recognize the module descriptor as a
422
+ // module descriptor, we assume that it is a module source (record):
423
+ const moduleSource = moduleDescriptor;
424
+ const moduleRecord = loadModuleSource(
425
+ compartmentPrivateFields,
426
+ moduleAliases,
427
+ compartment,
428
+ moduleSpecifier,
429
+ moduleSource,
430
+ enqueueJob,
431
+ selectImplementation,
432
+ moduleLoads,
433
+ );
434
+ // Memoize.
435
+ mapSet(moduleRecords, moduleSpecifier, moduleRecord);
436
+ return moduleRecord;
437
+ } else {
438
+ throw makeError(
439
+ X`module descriptor must be a string or object for specifier ${q(
440
+ moduleSpecifier,
441
+ )} in compartment ${q(compartment.name)}`,
442
+ );
234
443
  }
444
+ }
235
445
 
236
- return loadRecord(
237
- compartmentPrivateFields,
238
- moduleAliases,
239
- compartment,
240
- moduleSpecifier,
241
- staticModuleRecord,
242
- pendingJobs,
243
- moduleLoads,
244
- errors,
245
- );
246
- };
247
-
248
- const memoizedLoadWithErrorAnnotation = async (
446
+ const memoizedLoadWithErrorAnnotation = (
249
447
  compartmentPrivateFields,
250
448
  moduleAliases,
251
449
  compartment,
252
450
  moduleSpecifier,
253
- pendingJobs,
451
+ enqueueJob,
452
+ selectImplementation,
254
453
  moduleLoads,
255
- errors,
256
454
  ) => {
257
455
  const { name: compartmentName } = weakmapGet(
258
456
  compartmentPrivateFields,
@@ -270,21 +468,22 @@ const memoizedLoadWithErrorAnnotation = async (
270
468
  return moduleLoading;
271
469
  }
272
470
 
273
- moduleLoading = promiseCatch(
274
- loadWithoutErrorAnnotation(
471
+ moduleLoading = selectImplementation(asyncTrampoline, syncTrampoline)(
472
+ loadWithoutErrorAnnotation,
473
+ [
275
474
  compartmentPrivateFields,
276
475
  moduleAliases,
277
476
  compartment,
278
477
  moduleSpecifier,
279
- pendingJobs,
478
+ enqueueJob,
479
+ selectImplementation,
280
480
  moduleLoads,
281
- errors,
282
- ),
481
+ ],
283
482
  error => {
284
483
  // eslint-disable-next-line @endo/no-polymorphic-call
285
- assert.note(
484
+ annotateError(
286
485
  error,
287
- d`${error.message}, loading ${q(moduleSpecifier)} in compartment ${q(
486
+ X`${error.message}, loading ${q(moduleSpecifier)} in compartment ${q(
288
487
  compartmentName,
289
488
  )}`,
290
489
  );
@@ -297,8 +496,67 @@ const memoizedLoadWithErrorAnnotation = async (
297
496
  return moduleLoading;
298
497
  };
299
498
 
499
+ const asyncJobQueue = () => {
500
+ /** @type {Set<Promise<undefined>>} */
501
+ const pendingJobs = new Set();
502
+ /** @type {Array<Error>} */
503
+ const errors = [];
504
+
505
+ /**
506
+ * Enqueues a job that starts immediately but won't be awaited until drainQueue is called.
507
+ *
508
+ * @template {any[]} T
509
+ * @param {(...args: T)=>Promise<*>} func
510
+ * @param {T} args
511
+ */
512
+ const enqueueJob = (func, args) => {
513
+ setAdd(
514
+ pendingJobs,
515
+ promiseThen(func(...args), noop, error => {
516
+ arrayPush(errors, error);
517
+ }),
518
+ );
519
+ };
520
+ /**
521
+ * Sequentially awaits pending jobs and returns an array of errors
522
+ *
523
+ * @returns {Promise<Array<Error>>}
524
+ */
525
+ const drainQueue = async () => {
526
+ await null;
527
+ for (const job of pendingJobs) {
528
+ // eslint-disable-next-line no-await-in-loop
529
+ await job;
530
+ }
531
+ return errors;
532
+ };
533
+ return { enqueueJob, drainQueue };
534
+ };
535
+
536
+ /**
537
+ * @param {object} options
538
+ * @param {Array<Error>} options.errors
539
+ * @param {string} options.errorPrefix
540
+ */
541
+ const throwAggregateError = ({ errors, errorPrefix }) => {
542
+ // Throw an aggregate error if there were any errors.
543
+ if (errors.length > 0) {
544
+ const verbose =
545
+ getenv('COMPARTMENT_LOAD_ERRORS', '', ['verbose']) === 'verbose';
546
+ throw TypeError(
547
+ `${errorPrefix} (${errors.length} underlying failures: ${arrayJoin(
548
+ arrayMap(errors, error => error.message + (verbose ? error.stack : '')),
549
+ ', ',
550
+ )}`,
551
+ );
552
+ }
553
+ };
554
+
555
+ const preferSync = (_asyncImpl, syncImpl) => syncImpl;
556
+ const preferAsync = (asyncImpl, _syncImpl) => asyncImpl;
557
+
300
558
  /*
301
- * `load` asynchronously gathers the `StaticModuleRecord`s for a module and its
559
+ * `load` asynchronously gathers the module records for a module and its
302
560
  * transitive dependencies.
303
561
  * The module records refer to each other by a reference to the dependency's
304
562
  * compartment and the specifier of the module within its own compartment.
@@ -315,47 +573,78 @@ export const load = async (
315
573
  compartment,
316
574
  );
317
575
 
318
- /** @type {Set<Promise<undefined>>} */
319
- const pendingJobs = new Set();
320
576
  /** @type {Map<object, Map<string, Promise<Record<any, any>>>>} */
321
577
  const moduleLoads = new Map();
322
- /** @type {Array<Error>} */
323
- const errors = [];
324
578
 
325
- const dependencyLoaded = memoizedLoadWithErrorAnnotation(
579
+ const { enqueueJob, drainQueue } = asyncJobQueue();
580
+
581
+ enqueueJob(memoizedLoadWithErrorAnnotation, [
326
582
  compartmentPrivateFields,
327
583
  moduleAliases,
328
584
  compartment,
329
585
  moduleSpecifier,
330
- pendingJobs,
586
+ enqueueJob,
587
+ preferAsync,
331
588
  moduleLoads,
589
+ ]);
590
+
591
+ // Drain pending jobs queue and throw an aggregate error
592
+ const errors = await drainQueue();
593
+
594
+ throwAggregateError({
332
595
  errors,
596
+ errorPrefix: `Failed to load module ${q(moduleSpecifier)} in package ${q(
597
+ compartmentName,
598
+ )}`,
599
+ });
600
+ };
601
+
602
+ /*
603
+ * `loadNow` synchronously gathers the module records for a specified module
604
+ * and its transitive dependencies.
605
+ * The module records refer to each other by a reference to the dependency's
606
+ * compartment and the specifier of the module within its own compartment.
607
+ * This graph is then ready to be synchronously linked and executed.
608
+ */
609
+ export const loadNow = (
610
+ compartmentPrivateFields,
611
+ moduleAliases,
612
+ compartment,
613
+ moduleSpecifier,
614
+ ) => {
615
+ const { name: compartmentName } = weakmapGet(
616
+ compartmentPrivateFields,
617
+ compartment,
333
618
  );
334
- setAdd(
335
- pendingJobs,
336
- promiseThen(dependencyLoaded, noop, error => {
619
+
620
+ /** @type {Map<object, Map<string, Promise<Record<any, any>>>>} */
621
+ const moduleLoads = new Map();
622
+
623
+ /** @type {Array<Error>} */
624
+ const errors = [];
625
+
626
+ const enqueueJob = (func, args) => {
627
+ try {
628
+ func(...args);
629
+ } catch (error) {
337
630
  arrayPush(errors, error);
338
- }),
339
- );
631
+ }
632
+ };
340
633
 
341
- // Drain pending jobs queue.
342
- // Each job is a promise for undefined, regardless of success or failure.
343
- // Before we add a job to the queue, we catch any error and push it into the
344
- // `errors` accumulator.
345
- for (const job of pendingJobs) {
346
- // eslint-disable-next-line no-await-in-loop
347
- await job;
348
- }
634
+ enqueueJob(memoizedLoadWithErrorAnnotation, [
635
+ compartmentPrivateFields,
636
+ moduleAliases,
637
+ compartment,
638
+ moduleSpecifier,
639
+ enqueueJob,
640
+ preferSync,
641
+ moduleLoads,
642
+ ]);
349
643
 
350
- // Throw an aggregate error if there were any errors.
351
- if (errors.length > 0) {
352
- throw TypeError(
353
- `Failed to load module ${q(moduleSpecifier)} in package ${q(
354
- compartmentName,
355
- )} (${errors.length} underlying failures: ${arrayJoin(
356
- arrayMap(errors, error => error.message),
357
- ', ',
358
- )}`,
359
- );
360
- }
644
+ throwAggregateError({
645
+ errors,
646
+ errorPrefix: `Failed to load module ${q(moduleSpecifier)} in package ${q(
647
+ compartmentName,
648
+ )}`,
649
+ });
361
650
  };