Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

esm: update example-loader test fixture & API docs #29819

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 38 additions & 16 deletions test/fixtures/es-module-loaders/example-loader.mjs
Original file line number Diff line number Diff line change
@@ -1,44 +1,66 @@
import { URL } from 'url';
import path from 'path';
import process from 'process';
import { builtinModules } from 'module';
import { extname } from 'path';
import { default as Module } from 'module';

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

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

/**
* @param {!(string)} specifier
* @param {{
* parentURL:!(URL|string|undefined),
* }} context
* @param {!(Function)} defaultResolve
* @returns {{
* url:!(string),
* }}
*/
export function resolve(specifier, { parentURL = baseURL }, defaultResolve) {
if (builtinModules.includes(specifier)) {
if (Module.builtinModules.includes(specifier)) {
return {
url: 'nodejs:' + specifier
url: 'nodejs:' + specifier,
};
}
if (/^\.{1,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) {
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`);
"Imports must either be URLs or begin with './' or '../'; " +
`'${specifier}' satisfied neither of these requirements.`
);
}
const resolved = new URL(specifier, parentURL);
return {
url: resolved.href
url: resolved.href,
};
}

export function getFormat(url, context, defaultGetFormat) {
if (url.startsWith('nodejs:') && builtinModules.includes(url.slice(7))) {
/**
* @param {!(string)} url
// * param {!(Object)} context
// * param {!(Function)} defaultGetFormat
* @returns {{
* format:!(string),
* }}
*/
export function getFormat(url /* , context, defaultGetFormat */) {
if (url.startsWith('nodejs:') &&
Module.builtinModules.includes(url.slice(7))) {
return {
format: 'builtin'
format: 'builtin',
};
}
const { pathname } = new URL(url);
const ext = path.extname(pathname);
const ext = extname(pathname);
if (!JS_EXTENSIONS.has(ext)) {
throw new Error(
`Cannot load file with non-JavaScript file extension ${ext}.`);
`Cannot load file with non-JavaScript file extension ${ext}.`
);
}
return {
format: 'module'
format: 'module',
};
}