Skip to content

Commit 58636f2

Browse files
committed
esm: refactor test-esm-loader-resolve-type
1 parent b9f29d0 commit 58636f2

File tree

3 files changed

+69
-71
lines changed

3 files changed

+69
-71
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,38 @@
1-
// Flags: --loader ./test/fixtures/es-module-loaders/hook-resolve-type.mjs
2-
import { allowGlobals } from '../common/index.mjs';
1+
import { spawnPromisified } from '../common/index.mjs';
32
import * as fixtures from '../common/fixtures.mjs';
4-
import { strict as assert } from 'assert';
5-
import * as fs from 'fs';
6-
7-
allowGlobals(global.getModuleTypeStats);
8-
9-
const { importedESM: importedESMBefore,
10-
importedCJS: importedCJSBefore } = await global.getModuleTypeStats();
11-
12-
const basePath =
13-
new URL('./node_modules/', import.meta.url);
14-
15-
const rel = (file) => new URL(file, basePath);
16-
const createDir = (path) => {
17-
if (!fs.existsSync(path)) {
18-
fs.mkdirSync(path);
19-
}
20-
};
3+
import { match } from 'node:assert';
4+
import { mkdir, rm, cp } from 'node:fs/promises';
5+
import { tmpdir } from 'node:os';
6+
import { execPath } from 'node:process';
7+
import { fileURLToPath, pathToFileURL } from 'node:url';
218

9+
const base = new URL(`test-esm-loader-resolve-type-${(Math.random() * Date.now()).toFixed(0)}`, pathToFileURL(tmpdir()));
2210
const moduleName = 'module-counter-by-type';
23-
const moduleDir = rel(`${moduleName}`);
11+
const moduleURL = new URL(`${base}/node_modules/${moduleName}`);
2412
try {
25-
createDir(basePath);
26-
createDir(moduleDir);
27-
fs.cpSync(
28-
fixtures.path('es-modules', moduleName),
29-
moduleDir,
13+
await mkdir(moduleURL, { recursive: true });
14+
await cp(
15+
fixtures.path('es-modules', 'module-counter-by-type'),
16+
moduleURL,
3017
{ recursive: true }
3118
);
3219

20+
const { stdout } = await spawnPromisified(
21+
execPath,
22+
[
23+
'--input-type=module',
24+
'--eval',
25+
`import { getModuleTypeStats } from ${JSON.stringify(fixtures.fileURL('es-module-loaders', 'hook-resolve-type.mjs'))};
26+
const before = getModuleTypeStats();
27+
await import('${moduleName}');
28+
const after = getModuleTypeStats();
29+
console.log(JSON.stringify({ before, after }));`
30+
],
31+
{ cwd: fileURLToPath(base) },
32+
);
3333

34-
await import(`${moduleName}`);
34+
// Dynamic import in the eval script should increment ESM counter but not CJS counter
35+
match(stdout, /{"before":{"importedESM":0,"importedCJS":0},"after":{"importedESM":1,"importedCJS":0}}/);
3536
} finally {
36-
fs.rmSync(basePath, { recursive: true, force: true });
37+
await rm(base, { recursive: true, force: true });
3738
}
38-
39-
const { importedESM: importedESMAfter,
40-
importedCJS: importedCJSAfter } = await global.getModuleTypeStats();
41-
42-
// Dynamic import above should increment ESM counter but not CJS counter
43-
assert.strictEqual(importedESMBefore + 1, importedESMAfter);
44-
assert.strictEqual(importedCJSBefore, importedCJSAfter);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/** @type {MessagePort} */
2+
let port;
3+
export function initialize(data) {
4+
port = data.port;
5+
}
6+
7+
export async function resolve(specifier, context, next) {
8+
const nextResult = await next(specifier, context);
9+
const { format } = nextResult;
10+
11+
if (format === 'module' || specifier.endsWith('.mjs')) {
12+
port.postMessage({ type: 'module' });
13+
} else if (format == null || format === 'commonjs') {
14+
port.postMessage({ type: 'commonjs' });
15+
}
16+
17+
return nextResult;
18+
}
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,30 @@
1+
import * as fixtures from '../../common/fixtures.mjs';
2+
import { register } from 'node:module';
3+
import { MessageChannel } from 'node:worker_threads';
4+
15
let importedESM = 0;
26
let importedCJS = 0;
7+
export function getModuleTypeStats() {
8+
return { importedESM, importedCJS };
9+
};
310

4-
export function globalPreload({ port }) {
5-
port.on('message', (int32) => {
6-
port.postMessage({ importedESM, importedCJS });
7-
Atomics.store(int32, 0, 1);
8-
Atomics.notify(int32, 0);
9-
});
10-
port.unref();
11-
return `
12-
const { receiveMessageOnPort } = getBuiltin('worker_threads');
13-
global.getModuleTypeStats = async function getModuleTypeStats() {
14-
const sab = new SharedArrayBuffer(4);
15-
const int32 = new Int32Array(sab);
16-
port.postMessage(int32);
17-
// Artificial timeout to keep the event loop alive.
18-
// https://bugs.chromium.org/p/v8/issues/detail?id=13238
19-
// TODO(targos) Remove when V8 issue is resolved.
20-
const timeout = setTimeout(() => { throw new Error('timeout'); }, 1_000);
21-
await Atomics.waitAsync(int32, 0, 0).value;
22-
clearTimeout(timeout);
23-
return receiveMessageOnPort(port).message;
24-
};
25-
`;
26-
}
27-
28-
export async function load(url, context, next) {
29-
return next(url);
30-
}
11+
const { port1, port2 } = new MessageChannel();
3112

32-
export async function resolve(specifier, context, next) {
33-
const nextResult = await next(specifier, context);
34-
const { format } = nextResult;
13+
register(fixtures.fileURL('es-module-loaders/hook-resolve-type-loader.mjs'), {
14+
data: { port: port2 },
15+
transferList: [port2],
16+
});
3517

36-
if (format === 'module' || specifier.endsWith('.mjs')) {
37-
importedESM++;
38-
} else if (format == null || format === 'commonjs') {
39-
importedCJS++;
18+
port1.on('message', ({ type }) => {
19+
switch (type) {
20+
case 'module':
21+
importedESM++;
22+
break;
23+
case 'commonjs':
24+
importedCJS++;
25+
break;
4026
}
27+
});
4128

42-
return nextResult;
43-
}
44-
29+
port1.unref();
30+
port2.unref();

0 commit comments

Comments
 (0)