node.jscommonjs

How is LOAD_PACKAGE_EXPORTS in the Node.js CommonJS spec supposed to work?


I'm trying to implement the require() module ID resolver as described in https://nodejs.org/api/modules.html#all-together, currently getting stumped by the informal phrasing of LOAD_PACKAGE_EXPORTS:

Try to interpret X as a combination of NAME and SUBPATH where the name may have a @scope/ prefix and the subpath begins with a slash ('/').

In case X contains multiple slashes, which one starts the SUBPATH? May the slash ending the @scope/ prefix also be the separator? Is the prefix considered part of the NAME?


Slightly less important: LOAD_PACKAGE_SELF says

let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE), "." + X.slice("name".length), package.json "exports", ["node", "require"]) defined in the ESM resolver.

I'm assuming "name" is referring to the "name" field in package.json here. Why slice up X when the previous step asserted that X starts with the name string?


Solution

  • PACKAGE_RESOLVE in https://nodejs.org/api/esm.html#resolution-algorithm-specification deals with a similar pattern, which I'll assume is meant here too: if X does not begin with an @, then the first slash begins the subpath, otherwise the second slash begins the subpath. The prefix is part of the name.

    It's not quite the same, as the subpath may be empty in PACKAGE_RESOLVE whereas LOAD_PACKAGE_EXPORTS implies that the subpath must contain at least a slash, but I'm willing to deal with that.

    I did not solve the second mystery; it may just be due to another oversight.