• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const { StringPrototypeStartsWith } = primordials;
3const { extname } = require('path');
4const { getOptionValue } = require('internal/options');
5
6const experimentalJsonModules = getOptionValue('--experimental-json-modules');
7const experimentalSpeciferResolution =
8  getOptionValue('--experimental-specifier-resolution');
9const experimentalWasmModules = getOptionValue('--experimental-wasm-modules');
10const { getPackageType } = require('internal/modules/esm/resolve');
11const { URL, fileURLToPath } = require('internal/url');
12const { ERR_UNKNOWN_FILE_EXTENSION } = require('internal/errors').codes;
13
14const extensionFormatMap = {
15  '__proto__': null,
16  '.cjs': 'commonjs',
17  '.js': 'module',
18  '.mjs': 'module'
19};
20
21const legacyExtensionFormatMap = {
22  '__proto__': null,
23  '.cjs': 'commonjs',
24  '.js': 'commonjs',
25  '.json': 'commonjs',
26  '.mjs': 'module',
27  '.node': 'commonjs'
28};
29
30if (experimentalWasmModules)
31  extensionFormatMap['.wasm'] = legacyExtensionFormatMap['.wasm'] = 'wasm';
32
33if (experimentalJsonModules)
34  extensionFormatMap['.json'] = legacyExtensionFormatMap['.json'] = 'json';
35
36function defaultGetFormat(url, context, defaultGetFormatUnused) {
37  if (StringPrototypeStartsWith(url, 'node:')) {
38    return { format: 'builtin' };
39  }
40  const parsed = new URL(url);
41  if (parsed.protocol === 'data:') {
42    const [ , mime ] = /^([^/]+\/[^;,]+)(?:[^,]*?)(;base64)?,/.exec(parsed.pathname) || [ null, null, null ];
43    const format = ({
44      '__proto__': null,
45      'text/javascript': 'module',
46      'application/json': experimentalJsonModules ? 'json' : null,
47      'application/wasm': experimentalWasmModules ? 'wasm' : null
48    })[mime] || null;
49    return { format };
50  } else if (parsed.protocol === 'file:') {
51    const ext = extname(parsed.pathname);
52    let format;
53    if (ext === '.js') {
54      format = getPackageType(parsed.href) === 'module' ? 'module' : 'commonjs';
55    } else {
56      format = extensionFormatMap[ext];
57    }
58    if (!format) {
59      if (experimentalSpeciferResolution === 'node') {
60        process.emitWarning(
61          'The Node.js specifier resolution in ESM is experimental.',
62          'ExperimentalWarning');
63        format = legacyExtensionFormatMap[ext];
64      } else {
65        throw new ERR_UNKNOWN_FILE_EXTENSION(ext, fileURLToPath(url));
66      }
67    }
68    return { format: format || null };
69  }
70  return { format: null };
71}
72exports.defaultGetFormat = defaultGetFormat;
73