• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common');
3const assert = require('assert');
4const { URL } = require('url');
5
6const relativePath = '../fixtures/es-modules/test-esm-ok.mjs';
7const absolutePath = require.resolve('../fixtures/es-modules/test-esm-ok.mjs');
8const targetURL = new URL('file:///');
9targetURL.pathname = absolutePath;
10
11function expectModuleError(result, code, message) {
12  Promise.resolve(result).catch(common.mustCall((error) => {
13    assert.strictEqual(error.code, code);
14    if (message) assert.strictEqual(error.message, message);
15  }));
16}
17
18function expectOkNamespace(result) {
19  Promise.resolve(result)
20    .then(common.mustCall((ns) => {
21      const expected = { default: true };
22      Object.defineProperty(expected, Symbol.toStringTag, {
23        value: 'Module'
24      });
25      Object.setPrototypeOf(expected, Object.getPrototypeOf(ns));
26      assert.deepStrictEqual(ns, expected);
27    }));
28}
29
30function expectFsNamespace(result) {
31  Promise.resolve(result)
32    .then(common.mustCall((ns) => {
33      assert.strictEqual(typeof ns.default.writeFile, 'function');
34      assert.strictEqual(typeof ns.writeFile, 'function');
35    }));
36}
37
38// For direct use of import expressions inside of CJS or ES modules, including
39// via eval, all kinds of specifiers should work without issue.
40(function testScriptOrModuleImport() {
41  // Importing another file, both direct & via eval
42  // expectOkNamespace(import(relativePath));
43  expectOkNamespace(eval(`import("${relativePath}")`));
44  expectOkNamespace(eval(`import("${relativePath}")`));
45  expectOkNamespace(eval(`import("${targetURL}")`));
46
47  // Importing a built-in, both direct & via eval
48  expectFsNamespace(import('fs'));
49  expectFsNamespace(eval('import("fs")'));
50  expectFsNamespace(eval('import("fs")'));
51  expectFsNamespace(import('node:fs'));
52
53  expectModuleError(import('node:unknown'),
54                    'ERR_UNKNOWN_BUILTIN_MODULE');
55  expectModuleError(import('./not-an-existing-module.mjs'),
56                    'ERR_MODULE_NOT_FOUND');
57  expectModuleError(import('http://example.com/foo.js'),
58                    'ERR_UNSUPPORTED_ESM_URL_SCHEME');
59  if (common.isWindows) {
60    const msg =
61      'Only file and data URLs are supported by the default ESM loader. ' +
62      'On Windows, absolute paths must be valid file:// URLs. ' +
63      "Received protocol 'c:'";
64    expectModuleError(import('C:\\example\\foo.mjs'),
65                      'ERR_UNSUPPORTED_ESM_URL_SCHEME',
66                      msg);
67  }
68})();
69