Skip to content

esm: The getPackageType utility function is not exposed #30514

@DerekNonGeneric

Description

@DerekNonGeneric

Is your feature request related to a problem? Please describe.
Assist in determining module format by using internal machinery.

Describe the solution you'd like
Expose the getPackageType utility function.

Describe alternatives you've considered
The alternative is what I am currently doing, which is passing the --expose-internals flag (no bueno) and acquiring the utility function via internalBinding('module_wrap'). Exposing it would allow shaving off one dangerous flag and five lines from the following example.

// Flags: --expose-internals --experimental-modules --experimental-loader

import { createRequire /*, getPackageType*/ } from 'module';
import { dirname as pathDirname } from 'path';
import { fileURLToPath as pathFromFileUrl } from 'url';

const __filename = pathFromFileUrl(import.meta.url);
const __dirname = pathDirname(__filename);
const require = createRequire(__dirname);
const { internalBinding } = require('internal/test/binding');
const { getPackageType } = internalBinding('module_wrap');

// const TYPE_NONE = 0;
// const TYPE_COMMONJS = 1;
const TYPE_MODULE = 2;

/**
 * @param {string} specifier
 * @returns {Promise<{url: string, format: string}>}
 */
export async function resolve(specifier) {
  const type = getPackageType(specifier);
  if (type === TYPE_MODULE) {
    return {
      url: specifier,
      format: 'module',
    };
  }
}

As you may have noticed, one use-case is for custom loaders, which necessitate this info. Amongst others, one advantage of using the internal machinery (over writing it in JS) is that it is implemented in C++, which is important because this particular algorithm can be very expensive to perform and ( ! ) resolve hooks are on the hot code path of every module.

Additionally, exposing this function may also improve the viability of using loaders to fill the current gap in format autodetection until the --es-module-resolution flag's proposed auto mode is ready.

cc @nodejs/modules-active-members
bcc @GeoffreyBooth (please cc above)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions