File size: 26,427 Bytes
d0faac4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
You are working in `/workspace/typescript`, a source tree checked out at
the base commit for this task. Implement the requested behavior in the source
tree, then run:

```bash
lolbench-submit
```

Do not stop after editing files, running tests, or describing the solution. The
task is complete only when `lolbench-submit` has created
`/logs/artifacts/solution.patch`. If that file does not exist, continue
working and run `lolbench-submit` again.

That command writes your implementation diff to
`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier
will grade. Before running `lolbench-submit`, clean or revert any test files
you created or modified; test files must not be included in the final
`solution.patch`.

This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources.

Now please implement the following requirements in the source tree:

---

# Deferring Module Evaluation

previously known as "Lazy Module Initialization"

## Background

JS applications can get very large, to the point that not only loading, but even executing their
initialization scripts incurs a significant performance cost. Usually, this happens later in an application's
life span - often requiring invasive changes to make it more performant.

Loading performance is a big and important area for improvement, and involves preloading techniques for
avoiding waterfalls and dynamic `import()` for lazily loading modules.

But even with loading performance solved using these techniques, there is still overhead for execution
performance - CPU bottlenecks during initialization due to the way that the code itself is written.

## Motivation

Avoiding unnecessary execution is a well-known optimization in the Node.js CommonJS module system,
where there is a smaller gap between load contention and execution contention. The common pattern
in Node.js applications is to refactor code to dynamically require as needed:

```js
const operation = require('operation');

exports.doSomething = function (target) {
  return operation(target);
}
```

being rewritten as a performance optimization into:

```js
exports.doSomething = function (target) {
  const operation = require('operation');
  return operation(target);
}
```

The consumer still is provided with the same API, but with a more efficient use of FS & CPU during
initialization time.

For ES modules, we have a solution for the lazy loading component of this problem via dynamic `import()`.

For the same example we can write:

```js
export async function doSomething (target) {
  const { operation } = await import('operations');
  return operation(target);
}
```

This avoids bottlenecking the network and CPU during application initialization, but there are still a
number of problems with this technique:

1. It doesn't actually solve the deferral of execution problem, since sending a network
   request in such a scenario would usually be a performance regression and not an improvement.
   A separate network preloading step would therefore still be desirable to achieve efficient
   deferred execution while avoiding triggering a waterfall of requests.

2. It forces all functions and their callers into an asynchronous programming model,
   without necessarily reflecting the real intention of the program. This leads to all call
   sites having to be updated into a new model, and cannot be made without a breaking API
   change to existing API consumers.

## Problem Statement

Deferring the synchronous evaluation of a module may be desirable new primitive to avoid unnecessary
CPU work during application initialization, without requiring any changes from a module API consumer
perspective.

Dynamic import does not properly solve this problem, since it must often be coupled with a preload step,
and enforces the unnecessary asyncification of all functions, without providing the ability to only defer
the synchronous evaluation work.

## Proposal

The proposal is to have a new syntactical import form which will only ever return a namespace exotic object.
When used, the module and its dependencies would not be executed, but would be fully loaded to the point
of being execution-ready before the module graph is considered loaded.

_Only when accessing a property of this module, would the execution operations be performed (if needed)._

This way, the module namespace exotic object acts like a proxy to the evaluation of the module, effectively
with [[Get]] behavior that triggers synchronous evaluation before returning the defined bindings.

The API will use the below syntax, following the phases model established by the
[source phase imports](https://github.com/tc39/proposal-source-phase-imports) proposal:

```js
// or with a custom keyword:
import defer * as yNamespace from "y";
```

This namespace binding is the only form a deferred import may take. Because `import defer` can only ever produce a namespace exotic object, a default binding (`import defer someDefault from "y"`) or named bindings (`import defer { thing } from "y"`) carry no meaning and are rejected at compile time. A default binding produces error `TS18058`, "Default imports are not allowed in a deferred import." Named bindings produce error `TS18059`, "Named imports are not allowed in a deferred import."

Deferred imports are furthermore supported only under module targets that preserve native ES import syntax. A deferred import is accepted only when the `--module` flag is set to `esnext` or `preserve`; under every other target, including `commonjs`, `es2015`, `es2020`, and `nodenext`, the compiler reports error `TS18060`, "Deferred imports are only supported when the '--module' flag is set to 'esnext' or 'preserve'."

Deferring also has a dynamic counterpart, mirroring the `import.<phase>` call form of the source phase imports proposal described below. Calling `import.defer(specifier)` performs a dynamic deferred import and evaluates to a promise for the deferred namespace, so that `import.defer("./dep.js")` has type `Promise<typeof import("dep")>`. Here `import.defer` is a meta-property (alongside `import.meta`) that must be _immediately_ called: a bare reference such as `const callee = import.defer;`, a parenthesized callee such as `(import.defer)("./dep.js")`, or passing `import.defer` as an argument to another call are all syntax errors, each reported as error `TS1005`, "'(' expected." Any meta-property name on `import` other than `meta` or `defer` is reported with error `TS18061`. The same `esnext`/`preserve` module restriction (error `TS18060`) also applies to the `import.defer(...)` dynamic call form.

## Semantics

The imports would still participate in deep graph loading so that they are fully populated into
the module cache prior to execution, however it the imported module will not be evaluated yet.

When a property of the resulting module namespace object is accessed, if the execution has
not already been performed, a new top-level execution would be initiated for that module.

In this way, a deferred module evaluation import acts as a new top-level execution node
in the execution graph, just like a dynamic import does, except executing synchronously.

There are possible extensions under consideration, such as deferred re-exports, but they are not
included in the current version of the proposal.

### Top-level await

Property access on the namespace object of a deferred module must be synchronous, and it's thus
impossible to defer evaluation of modules that use top-level await. When a module is imported
using the `import defer` syntax, its asynchronous dependencies together with their own transitive
dependencies are eagerly evaluated, and only the synchronous parts of the graph are deferred.

Consider the following example, where `a` is the top-level entry point:
<table><tr><td>

```js
// a
import "b";
import defer * as c from "c"

setTimeout(() => {
  c.value
}, 1000);
```

</td><td>

```js
// b
```

</td><td>

```js
// c
import "d"
import "f"
export let value = 2;
```

</td></tr><tr><td>

```js
// d
import "e"
await 0;
```

</td><td>

```js
// e
```

</td><td>

```js
// f
```

</td></tr></table>

Since `d` uses top-level await, `d` and its dependencies cannot be deferred:
- The initial evaluation will execute `b`, `e`, `d` and `a`.
- Later, the `c.value` access will trigger the execution of `f` and `c`.

### Rough sketch

If we split out the components of Module loading and initialization, we could roughly sketch out the
intended semantics:

> ⚠️ The following example does not take cycles into account

```js
// LazyModuleLoader.js
async function loadModuleAndDependencies(name) {
  const loadedModule = await import.load(`./${name}.js`); // load is async, and needs to be awaited
  const parsedModule = loadedModule.parse();
  await Promise.all(parsedModule.imports.map(loadModuleAndDependencies)); // load all dependencies
  return parsedModule;
}

async function executeAsyncSubgraphs(module) {
  if (module.hasTLA) return module.evaluate();
  return Promise.all(module.importedModules.map(executeAsyncSubgraphs));
}

export default async function lazyModule(object, name) {
  const module = await loadModuleAndDependencies(name);
  await executeAsyncSubgraphs(module);
  Object.defineProperty(object, name, {
    get: function() {
      delete object[name];
      const value = module.evaluateSync();
      Object.defineProperty(object, name, {
        value,
        writable: true,
        configurable: true,
        enumerable: true,
      });
      return value;
    },
    configurable: true,
    enumerable: true,
  });

  return object;
}

// myModule.js
import foo from "./bar";

etc.

// module.js
import LazyModule from "./LazyModuleLoader";
await LazyModule(globalThis, "myModule");

function Foo() {
  myModule.doWork() // first use
}
```

## Implementations

- engine262: https://github.com/nicolo-ribaudo/engine262/tree/defer-eval
- webpack: https://github.com/webpack/webpack/pull/16567
- Babel: https://babeljs.io/docs/babel-plugin-proposal-import-defer

## Q&A

#### What happened to the direct lazy bindings?

The initial version of this proposal included direct binding access for deferred evaluation via
named exports:

```js
import { feature } from './lib' with { lazyInit: true }

export function doSomething (param) {
  return feature(param);
}
```

where the deferred evaluation would only happen on _access_ of the `feature` binding.

There are a number of complexities to this approach, as it introduces a novel
type of execution point in the language, which would need to be worked through.

This approach may still be investigated in various ways within this proposal or an extension of it,
but by focusing on the module namespace exotic object approach first, it keeps the semantics
simple and in-line with standard JS techniques.

#### Is there really a benefit to optimizing execution, when surely loading is the bottleneck?

While it is true that loading time is the most dominant factor on the web, it is important to consider that many
large applications can block the CPU for of the range of 100ms while initializing the main application graph.

Loading times of the order of multiple seconds often take the focus for performance optimization work, and this
is certainly an important problem space, but the problem of freeing up the main event loop during initialization
remains a critical one when the network problem is solved, that doesn't currently have any easy solutions today
for large applications.

#### Is there prior art for this in other languages?

The standard libraries of these programming languages includes related functionality:
- Ruby's `autoload`, in contrast with `require` which works in the same way as JS `import`
- Clojure `import`
- Most LISP environments

Our approach is pretty similar to the Emacs Lisp approach, and it's clear from a manual analysis of billions of Stack Overflow posts that this is the most straightforward to ordinary developers.

#### Why not support a synchronous evaluation API on ModuleInstance

A synchronous evaluation API on the module expression and compartments [ModuleInstance](https://github.com/tc39/proposal-compartments/blob/master/0-module-and-module-source.md#module-instances)
object could offer an API for synchronous evaluation of modules, which could be compatible with
this approach of deferred evaluation, but it is only in having a clear syntactical solution for this use case,
that it can be supported across dependency boundaries and in bundlers to bring the full benefits of avoiding unnecessary
initialization work to the wider JS ecosystem.

#### What can we do in current JS to approximate this behavior?

The closest we can get is the following:

```js
// moduleWrapper.js
export default function ModuleWrapper(object, name, lambda) {
  Object.defineProperty(object, name, {
    get: function() {
      // Redefine this accessor property as a data property.
      // Delete it first, to rule out "too much recursion" in case object is
      // a proxy whose defineProperty handler might unwittingly trigger this
      // getter again.
      delete object[name];
      const value = lambda.apply(object);
      Object.defineProperty(object, name, {
        value,
        writable: true,
        configurable: true,
        enumerable: true,
      });
      return value;
    },
    configurable: true,
    enumerable: true,
  });
  return object;
}

// module.js
import ModuleWrapper from "./ModuleWrapper";
// any imports would need to be wrapped as well

function MyModule() {
 // ... all of the work of the module
}

export default ModuleWrapper({}, "MyModule", MyModule);

// parent.js
import wrappedModule from "./module";

function Foo() {
  wrappedModule.MyModule.bar() // first use
}
```

However, this solution doesn't cover deferring the loading of submodules of a lazy graph, and would
not acheive the characteristics we are looking for.

#### Why `import defer *` gives a different namespace object from `import *`?

Module namespace objects of modules that are _already evaluated_ and threw during evaluation do not re-throw an error on
property access:

```js
// module-that-throws1
import * as self from 'module-that-throws1';
globalThis.ns1 = self;
export let a = 1;
throw new Error("oops");
```
```js
// main1.js
import("module-that-throws1").finally(() => {
  console.log(globalThis.ns1.a); // Doesn't throw, logs '1'
});
```

Deferred namespaces are different. If the module throws while being evaluated, `deferredNamespace.foo` will always throw the evaluation error:

```js
// module-that-throws2
export let a = 1;
throw new Error("oops");
```
```js
// main2.js
import defer * as ns2 from 'module-that-throws2';

try { ns2.a } catch (e) { console.log(e.message) } // logs "oops"
```

Before this proposal having access to a namespace object of a module that threw during evaluation is incredibly rare. However, it becomes more common with `import defer` declarations. The `import defer` in `main2.js` would have a race condition if it errored only when `module-that-throws2` has already been loaded by something else, instead the error will always be deffered until the namespace is accessed. As `ns2.a` must throw even if `module-that-throws2` is already evaluated, and thus it cannot be the same namespace object as `import *`.

Another approach we considered (and discarded) was to always suppress evaluation errors on namespace property access, so that in the example above `ns2.a` would be guaranteed to _never_ throw and thus not be affected by unrelated modules that might have already triggered evaluation of `module-that-throws`.

#### Why not re-use import attributes (`import * as ns from "mod" with { defer: true }`)?

There are two reasons why we chose to use an "import modifier" rather than an attribute:
1. Import attributes affect what a module _is_, but cannot change basic semantics of how ECMAScript modules behave: they are similar to adding query parameters to the imported URL, except that attributes are handled by the running environment rather than by the server. For example, `with { type: "json" }` behaves as if the imported module was a JavaScript file wrapped in ``export default JSON.parse(` ... the file contents ... `);``. `import defer` changes how namespace objects behave (by making them side-effectul, while before this proposal property access on namespace objects couldn't trigger any side effect): it cannot be expressed as a wrapped/modified "classic" ECMAScript module.
2. Together with the [source phase imports proposal](https://github.com/tc39/proposal-source-phase-imports), we are exposing multiple "phases" of module loading. The phases we've identified are: resolving a module given a specifier, fetching the module (these two both happens in hosts and not in ECMA-262), attaching modules to their execution and resolution context, linking modules together, and finally executing them. We are using `import` modifiers to represent modules processed up to one of those phases, without going all the way to finishing execution. These modifiers give more guarantees than import attributes: while `import "x" with { attr1: "val" }` and `import "x" with { attr2: "val2" }` might be two completely different modules, `import source s from "x"`, `import defer * as ns from "x"`, and `import "x"` all are guaranteed to load the same module, and that module will be executed at most once regardless of which "phase" it gets temporarely paused at (and then continued from).

## Linked Proposal — Source Phase Imports

## Motivation

For both JavaScript and WebAssembly, there is a need to be able to more closely
customize the loading, linking, and execution of modules beyond the standard
host execution model.

For JavaScript, creating userland loaders would require a module source type
in order to share the host parsing, execution, security, and caching semantics.

For WebAssembly, imports and exports for WebAssembly modules often require custom
inspection and wrapping in order to be set up correctly, which typically requires
manual fetch and instantiation work that is not provided for in the current host
[ESM integration][wasm-esm] proposal.

Supporting syntactical module source imports as a new import phase creates a
primitive that can extend the static, security and tooling benefits of modules
from the ESM integration to these dynamic instantiation use cases.

## Proposal

This proposal allows ES modules to import a reified representation of the
compiled source of a module when the host provides such a representation:

```js
import source x from "<specifier>";
```

The `source` module source loading phase name is added to the beginning of the
ImportStatement.

Only the above form is supported - named exports and unbound declarations are
not supported.

### Dynamic form

Just as with static and dynamic imports, there is a need for static and dynamic access
to sources, to be able to support both those sources that are required to be instantiated
from source text during initialization of an application, and those that are optionally or
lazily created at runtime.

The dynamic form uses a `import.<phase>` import call:

```js
const x = await import.source("<specifier>");
```

By making the phase part of the explicit syntax, it is possible to statically distinguish between
a full dynamic import and one that is only for a source (where dependencies don't need to be
processed).

Optional [import attributes][] may still be specified with the second argument in a `with` key,
just like for dynamic import, and without conflict due to the design of phased evaluation.

### Loading Phase

Module source imports can be seen to be one type of evaluation phase.

If the [asset references proposal][] advances in future this could be seen
as another type of phase representing an earlier phase of the loading process.

```js
import asset x from "<specifier>";
await import.asset("<specifier>");
```

Only the `source` import source phase is specified by this proposal.

### Defining Module Source

The object provided by the module source phase must be an object with
`AbstractModuleSource.prototype` in its prototype chain, defined by this specification
to be a minimal shared base prototype for a compiled modular resource.

In addition it defines the `@@toStringTag` getter returning the constructor name string
corresponding to the name of the specific module source subclass, with a strong
internal slot check.

### JS Module Source

For JavaScript modules, the module source phase is then specified to return
a `ModuleSource` object, representing an ECMAScript Module Source, where
`ModuleSource.prototype.[[Proto]]` is `%AbstractModuleSource%.prototype`.

Future proposals may then add support for [bindings lookup methods][],
the [ModuleSource constructor][module soruce] and [instantiation][] support.

New properties may be added to the base `%AbstractModuleSource%.prototype`, or shared
with ECMAScript module sources via `ModuleSource.prototype` additions.

### Wasm Module Source

For WebAssembly modules, the existing `WebAssembly.Module.prototype` object is to be
updated to have a `[[Proto]]` of `%AbstractModuleSource%.prototype` in the
[WebAssembly JS integration API][wasm-js-api].

This allows workflows, as explained in the motivation, like the following:

```js
import source FooModule from "./foo.wasm";
FooModule instanceof WebAssembly.Module; // true

// For example, to run a WASI execution with an API like Node.js WASI:
import { WASI } from 'wasi';
const wasi = new WASI({ args, env, preopens });

const fooInstance = await WebAssembly.instantiate(FooModule, {
  wasi_snapshot_preview1: wasi.wasiImport
});

wasi.start(fooInstance);
```

The static analysis benefits of not needing a custom `fetch` and
`WebAssembly.compileStreaming` apply not only to code analysis and security
but also for bundlers.

In turn this enables [Wasm components to be able to import][]
`WebAssembly.Module` objects themselves in future.

### Other Module Types

Any other host-defined module types may define their own host module sources. If a given module does not define a source representation for it's source, importing it with a "source" phase target fails with a `ReferenceError` at link time.

Host-defined module sources must include `%AbstractModuleSource%.prototype` in their prototype chain and support the `[[ModuleSourceRecord]]` internal slot containing the `@@toStringTag` brand check and underlying source host data.

## Security Benefits

The native ES module loader is able to implement security policies, including
support for [Content Security Policies][CSP] in browsers. This property does not just impact platforms using CSP, but also other platforms with systems to restrict permissions, such as Deno. These policies are based on protecting which URLs are supported for the compilation and execution of scripts or modules.

Extending the static security benefits of the host module system to custom loaders is a security benefit of this proposal. For Wasm, it would enable source-specific CSP policies for dynamic Wasm instantiation.

## Cache Key Semantics

Because `[[ModuleSourceObject]]` is keyed on the base module record, it will always
be unique to the module being imported from.

## Q&A

**Q**: How does this relate to import attributes?

**A**: Import attributes are properties of the module request, while source imports
represent phases of that specific request / key in the module map, without affecting
the idempotency of the module load. Both can be used together for a resource to indicate alternative phasing for the given module resource and attributes.

**Q**: How does this relate to module expressions and compartments?

**A**: The module object that is provided has been carefully specified here to be
compatible with the linking model of module expressions and compartments.

**Q**: Why not just use `const module = await
WebAssembly.compileStreaming(fetch(new URL("./module.wasm",
import.meta.url)));`?

**A**: There are multiple benefits: firstly if the module is statically
referenced in the module graph, it is easier to statically analyze (by bundlers
for example). Secondly when using CSP, `script-src: unsafe-eval` would not be
needed. See the security improvements section for more details.

*Source: https://github.com/tc39/proposal-source-phase-imports*

## Linked Proposal — First-class Module and ModuleSource (Module instances)

```ts
type ImportSpecifier = string;

type ImportHook = (this: ModuleHandler, specifier: ImportSpecifier) =>
  Promise<Module>;

type ImportMeta = {
  __proto__: null,
  // ...
  [name: string | symbol | number]: unknown,
};

type ImportMetaHook = (this: ModuleHandler, importMeta: ImportMeta) => any;

type ModuleHandler = {
  importHook?: ImportHook,
  importMetaHook?: ImportMetaHook,
  // ...
  [name: string | symbol | number]: unknown,
};

interface Module {
  constructor(
    source: ModuleSource,
    handler: ModuleHandler,
  );

  readonly source?: ModuleSource,
}
```

Semantics: A `Module` instance has an internal ***Module Record***.
Importing the module will consistently produce the same ***Module Namespace
Exotic Object***.

The module has a lifecycle and fresh instances have not been linked,
initialized, or executed.

Invoking dynamic import on a `Module` instance attempts to advance it and its
transitive dependencies to their end state.
Consistent with dynamic import for a stringly-named module,
dynamic import on a `Module` instance produces a promise for the corresponding
***Module Namespace Exotic Object***

Dynamic import induces calls to `importHook` for each unsatisfied dependency of
each module instance in separate events, before any dependency advances to the
link phase of its lifecycle.

Dynamic import within the evaluation of a `Module` also invokes the
`importHook`.

`Module` instances memoize the result of their `importHook` keyed on the given
Import Specifier.

`Module` constructors, like `Function` constructors, are bound to a realm
and evaluate modules in their particular realm.

*Source: https://github.com/tc39/proposal-compartments/blob/master/0-module-and-module-source.md#module-instances*