summaryrefslogtreecommitdiff
path: root/test/fixtures/es-module-loaders/example-loader.mjs
blob: 70f9f28f08e7421cd7f6b0a8256250a89b9f8a86 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { URL } from 'url';
import path from 'path';
import process from 'process';
import { builtinModules } from 'module';

const JS_EXTENSIONS = new Set(['.js', '.mjs']);

const baseURL = new URL('file://');
baseURL.pathname = process.cwd() + '/';

export function resolve(specifier, { parentURL = baseURL }, defaultResolve) {
  if (builtinModules.includes(specifier)) {
    return {
      url: specifier
    };
  }
  if (/^\.{1,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) {
    // For node_modules support:
    // return defaultResolve(specifier, {parentURL}, defaultResolve);
    throw new Error(
      `imports must be URLs or begin with './', or '../'; '${specifier}' does not`);
  }
  const resolved = new URL(specifier, parentURL);
  return {
    url: resolved.href
  };
}

export function getFormat(url, context, defaultGetFormat) {
  if (builtinModules.includes(url)) {
    return {
      format: 'builtin'
    };
  }
  const { pathname } = new URL(url);
  const ext = path.extname(pathname);
  if (!JS_EXTENSIONS.has(ext)) {
    throw new Error(
      `Cannot load file with non-JavaScript file extension ${ext}.`);
  }
  return {
    format: 'module'
  };
}