Skip to content

Commit

Permalink
src: support top-level await in --experimental-detect-module
Browse files Browse the repository at this point in the history
  • Loading branch information
targos committed Nov 26, 2023
1 parent f28839b commit 0032e24
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/node_contextify.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1406,7 +1406,9 @@ Local<Object> ContextifyContext::CompileFunctionAndCacheResult(
constexpr std::array<std::string_view, 3> esm_syntax_error_messages = {
"Cannot use import statement outside a module", // `import` statements
"Unexpected token 'export'", // `export` statements
"Cannot use 'import.meta' outside a module"}; // `import.meta` references
"Cannot use 'import.meta' outside a module", // `import.meta` references
"await is only valid in async functions and the top level bodies of "
"modules"}; // top-level `await`

void ContextifyContext::ContainsModuleSyntax(
const FunctionCallbackInfo<Value>& args) {
Expand Down
42 changes: 42 additions & 0 deletions test/es-module/test-esm-detect-ambiguous.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,51 @@ import * as fixtures from '../common/fixtures.mjs';
import { spawn } from 'node:child_process';
import { describe, it } from 'node:test';
import { strictEqual, match } from 'node:assert';
import { join } from 'node:path';

describe('--experimental-detect-module', { concurrency: true }, () => {
describe('string input', { concurrency: true }, () => {
for (const { name, code, output } of [
{
name: '`import` statements',
code: 'import { version } from "node:process"; console.log(version);',
output: `${process.version}\n`,
},
{
name: '`export` statements',
code: 'export const foo = "bar"; console.log foo;',
output: 'bar\n',
},
{
name: '`import.meta` references',
code: 'console.log(import.meta.filename);',
output: `${join(process.cwd(), '[eval1]')}\n`,
},
{
name: 'top-level `await`',
code: 'const foo = await Promise.resolve("bar"); console.log(foo);',
output: 'bar\n',
},
{
name: 'top-level `await` in a function call',
code: 'console.log(await Promise.resolve("bar"));',
output: 'bar\n',
},
]) {
it(`supports all possible ESM-only syntax elements: (${name})`, async () => {
const { stdout, stderr, code: exitCode, signal } = await spawnPromisified(process.execPath, [
'--experimental-detect-module',
'--eval',
code,
]);

strictEqual(stderr, '');
strictEqual(stdout, output);
strictEqual(exitCode, 0);
strictEqual(signal, null);
});
}

it('permits ESM syntax in --eval input without requiring --input-type=module', async () => {
const { stdout, stderr, code, signal } = await spawnPromisified(process.execPath, [
'--experimental-detect-module',
Expand Down

0 comments on commit 0032e24

Please sign in to comment.