• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import { spawnPromisified } from '../common/index.mjs';
2import fixtures from '../common/fixtures.js';
3import assert from 'node:assert';
4import http from 'node:http';
5import path from 'node:path';
6import { execPath } from 'node:process';
7import { promisify } from 'node:util';
8import { describe, it, after } from 'node:test';
9
10
11const files = {
12  'main.mjs': 'export * from "./lib.mjs";',
13  'lib.mjs': 'export { sum } from "./sum.mjs";',
14  'sum.mjs': 'export function sum(a, b) { return a + b }',
15  'console.mjs': `
16    import { sum } from './sum.mjs';
17    globalThis.sum = sum;
18    console.log("loaded over http");
19  `,
20};
21
22const requestListener = ({ url }, rsp) => {
23  const filename = path.basename(url);
24  const content = files[filename];
25
26  if (content) {
27    return rsp
28      .writeHead(200, { 'Content-Type': 'application/javascript' })
29      .end(content);
30  }
31
32  return rsp
33    .writeHead(404)
34    .end();
35};
36
37const server = http.createServer(requestListener);
38
39await promisify(server.listen.bind(server))({
40  host: '127.0.0.1',
41  port: 0,
42});
43
44const {
45  address: host,
46  port,
47} = server.address();
48
49describe('ESM: http import via loader', { concurrency: true }, () => {
50  it('should load using --import flag', async () => {
51    // ! MUST NOT use spawnSync to avoid blocking the event loop
52    const { code, signal, stderr, stdout } = await spawnPromisified(
53      execPath,
54      [
55        '--no-warnings',
56        '--loader',
57        fixtures.fileURL('es-module-loaders', 'http-loader.mjs'),
58        '--import', `http://${host}:${port}/console.mjs`,
59        '--eval',
60        'console.log(sum(1, 2))',
61      ]
62    );
63    assert.strictEqual(stderr, '');
64    assert.match(stdout, /loaded over http\r?\n3/);
65    assert.strictEqual(code, 0);
66    assert.strictEqual(signal, null);
67  });
68  it('should load using import inside --eval code', async () => {
69    // ! MUST NOT use spawnSync to avoid blocking the event loop
70    const { code, signal, stderr, stdout } = await spawnPromisified(
71      execPath,
72      [
73        '--no-warnings',
74        '--loader',
75        fixtures.fileURL('es-module-loaders', 'http-loader.mjs'),
76        '--input-type=module',
77        '--eval',
78        `import * as main from 'http://${host}:${port}/main.mjs'; console.log(main)`,
79      ]
80    );
81
82    assert.strictEqual(stderr, '');
83    assert.strictEqual(stdout, '[Module: null prototype] { sum: [Function: sum] }\n');
84    assert.strictEqual(code, 0);
85    assert.strictEqual(signal, null);
86  });
87
88  after(() => server.close());
89});
90