Skip to content

Commit

Permalink
module: improve error message for top-level await in CommonJS
Browse files Browse the repository at this point in the history
  • Loading branch information
Mert Can Altin committed Nov 15, 2024
1 parent def4c28 commit 6450b04
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/node_contextify.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1611,7 +1611,8 @@ static std::vector<std::string_view> throws_only_in_cjs_error_messages = {
"Identifier '__filename' has already been declared",
"Identifier '__dirname' has already been declared",
"await is only valid in async functions and "
"the top level bodies of modules"};
"the top level bodies of modules",
"Identifier 'require' has already been declared",};

// If cached_data is provided, it would be used for the compilation and
// the on-disk compilation cache from NODE_COMPILE_CACHE (if configured)
Expand Down Expand Up @@ -1816,6 +1817,17 @@ bool ShouldRetryAsESM(Realm* realm,
Utf8Value message_value(isolate, message);
auto message_view = message_value.ToStringView();

for (const auto& error_message : throws_only_in_cjs_error_messages) {
if (message_view.find(error_message) != std::string_view::npos) {
isolate->ThrowException(v8::Exception::SyntaxError(
String::NewFromUtf8(isolate,
"Top-level await is not supported in CommonJS. "
"Consider using ESM or wrap await in an async function.")
.ToLocalChecked()));
return true;
}
}

// These indicates that the file contains syntaxes that are only valid in
// ESM. So it must be true.
for (const auto& error_message : esm_syntax_error_messages) {
Expand Down
11 changes: 11 additions & 0 deletions test/parallel/test-commonjs-top-level-await.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';
require('../common');

const { spawnSync } = require('node:child_process');
const assert = require('node:assert');

const result = spawnSync(process.execPath, ['-e', `
const port = await getPort();
`]);

assert.strictEqual(result.stderr.includes('Top-level await is not supported in CommonJS'), true);

0 comments on commit 6450b04

Please sign in to comment.