GeezerVison is showing github.com — module: implement "exports" proposal for CommonJS · lerouxb/node@dcb6929
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: doc/api/errors.md +7Lines changed: 7 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -1585,6 +1585,13 @@ compiled with ICU support. | 1585 | 1585 |
| 1586 | 1586 | A given value is out of the accepted range. | 1587 | 1587 |
| | 1588 | +<a id="ERR_PATH_NOT_EXPORTED"></a> | | 1589 | +### ERR_PATH_NOT_EXPORTED | | 1590 | + | | 1591 | +> Stability: 1 - Experimental | | 1592 | +
| | 1593 | +An attempt was made to load a protected path from a package using `exports`. | | 1594 | + | 1588 | 1595 | <a id="ERR_REQUIRE_ESM"></a> | 1589 | 1596 | ### ERR_REQUIRE_ESM | 1590 | 1597 |
| |
Collapse file Copy file name to clipboardExpand all lines: doc/api/modules.md +33Lines changed: 33 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -202,6 +202,39 @@ NODE_MODULES_PATHS(START) | 202 | 202 | 5. return DIRS | 203 | 203 | ``` | 204 | 204 |
| | 205 | +If `--experimental-exports` is enabled, | | 206 | +node allows packages loaded via `LOAD_NODE_MODULES` to explicitly declare | | 207 | +which filepaths to expose and how they should be interpreted. | | 208 | +This expands on the control packages already had using the `main` field. | | 209 | +With this feature enabled, the `LOAD_NODE_MODULES` changes as follows: | | 210 | + | | 211 | +```txt | | 212 | +LOAD_NODE_MODULES(X, START) | | 213 | +1. let DIRS = NODE_MODULES_PATHS(START) | | 214 | +2. for each DIR in DIRS: | | 215 | + a. let FILE_PATH = RESOLVE_BARE_SPECIFIER(DIR, X) | | 216 | + a. LOAD_AS_FILE(FILE_PATH) | | 217 | + b. LOAD_AS_DIRECTORY(FILE_PATH) | | 218 | +
| | 219 | +RESOLVE_BARE_SPECIFIER(DIR, X) | | 220 | +1. Try to interpret X as a combination of name and subpath where the name | | 221 | + may have a @scope/ prefix and the subpath begins with a slash (`/`). | | 222 | +2. If X matches this pattern and DIR/name/package.json is a file: | | 223 | + a. Parse DIR/name/package.json, and look for "exports" field. | | 224 | + b. If "exports" is null or undefined, GOTO 3. | | 225 | + c. Find the longest key in "exports" that the subpath starts with. | | 226 | + d. If no such key can be found, throw "not exported". | | 227 | + e. If the key matches the subpath entirely, return DIR/name/${exports[key]}. | | 228 | + f. If either the key or exports[key] do not end with a slash (`/`), | | 229 | + throw "not exported". | | 230 | + g. Return DIR/name/${exports[key]}${subpath.slice(key.length)}. | | 231 | +3. return DIR/X | | 232 | +``` | | 233 | + | | 234 | +`"exports"` is only honored when loading a package "name" as defined above. Any | | 235 | +`"exports"` values within nested directories and packages must be declared by | | 236 | +the `package.json` responsible for the "name". | | 237 | + | 205 | 238 | ## Caching | 206 | 239 |
| 207 | 240 | <!--type=misc--> | |
Collapse file Copy file name to clipboardExpand all lines: lib/internal/errors.js +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -1098,6 +1098,8 @@ E('ERR_OUT_OF_RANGE', | 1098 | 1098 | msg += ` It must be ${range}. Received ${received}`; | 1099 | 1099 | return msg; | 1100 | 1100 | }, RangeError); | | 1101 | +E('ERR_PATH_NOT_EXPORTED', | | 1102 | + 'Package exports for \'%s\' do not define a \'%s\' subpath', Error); | 1101 | 1103 | E('ERR_REQUIRE_ESM', 'Must use import to load ES Module: %s', Error); | 1102 | 1104 | E('ERR_SCRIPT_EXECUTION_INTERRUPTED', | 1103 | 1105 | 'Script execution was interrupted by `SIGINT`', Error); | |
Collapse file Copy file name to clipboardExpand all lines: lib/internal/modules/cjs/loader.js +96-9Lines changed: 96 additions & 9 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 21 | 21 |
| 22 | 22 | 'use strict'; | 23 | 23 |
| 24 | | -const { JSON, Object, Reflect } = primordials; | | 24 | +const { | | 25 | + JSON, | | 26 | + Object, | | 27 | + Reflect, | | 28 | + SafeMap, | | 29 | + StringPrototype, | | 30 | +} = primordials; | 25 | 31 |
| 26 | 32 | const { NativeModule } = require('internal/bootstrap/loaders'); | 27 | 33 | const { pathToFileURL, fileURLToPath, URL } = require('internal/url'); | @@ -53,10 +59,12 @@ const { compileFunction } = internalBinding('contextify'); | 53 | 59 | const { | 54 | 60 | ERR_INVALID_ARG_VALUE, | 55 | 61 | ERR_INVALID_OPT_VALUE, | | 62 | + ERR_PATH_NOT_EXPORTED, | 56 | 63 | ERR_REQUIRE_ESM | 57 | 64 | } = require('internal/errors').codes; | 58 | 65 | const { validateString } = require('internal/validators'); | 59 | 66 | const pendingDeprecation = getOptionValue('--pending-deprecation'); | | 67 | +const experimentalExports = getOptionValue('--experimental-exports'); | 60 | 68 |
| 61 | 69 | module.exports = { wrapSafe, Module }; | 62 | 70 |
| @@ -182,12 +190,10 @@ Module._debug = deprecate(debug, 'Module._debug is deprecated.', 'DEP0077'); | 182 | 190 |
| 183 | 191 | // Check if the directory is a package.json dir. | 184 | 192 | const packageMainCache = Object.create(null); | | 193 | +// Explicit exports from package.json files | | 194 | +const packageExportsCache = new SafeMap(); | 185 | 195 |
| 186 | | -function readPackage(requestPath) { | 187 | | - const entry = packageMainCache[requestPath]; | 188 | | - if (entry) | 189 | | - return entry; | 190 | | - | | 196 | +function readPackageRaw(requestPath) { | 191 | 197 | const jsonPath = path.resolve(requestPath, 'package.json'); | 192 | 198 | const json = internalModuleReadJSON(path.toNamespacedPath(jsonPath)); | 193 | 199 |
| @@ -201,14 +207,44 @@ function readPackage(requestPath) { | 201 | 207 | } | 202 | 208 |
| 203 | 209 | try { | 204 | | - return packageMainCache[requestPath] = JSON.parse(json).main; | | 210 | + const parsed = JSON.parse(json); | | 211 | + packageMainCache[requestPath] = parsed.main; | | 212 | + if (experimentalExports) { | | 213 | + packageExportsCache.set(requestPath, parsed.exports); | | 214 | + } | | 215 | + return parsed; | 205 | 216 | } catch (e) { | 206 | 217 | e.path = jsonPath; | 207 | 218 | e.message = 'Error parsing ' + jsonPath + ': ' + e.message; | 208 | 219 | throw e; | 209 | 220 | } | 210 | 221 | } | 211 | 222 |
| | 223 | +function readPackage(requestPath) { | | 224 | + const entry = packageMainCache[requestPath]; | | 225 | + if (entry) | | 226 | + return entry; | | 227 | + | | 228 | + const pkg = readPackageRaw(requestPath); | | 229 | + if (pkg === false) return false; | | 230 | + | | 231 | + return pkg.main; | | 232 | +} | | 233 | + | | 234 | +function readExports(requestPath) { | | 235 | + if (packageExportsCache.has(requestPath)) { | | 236 | + return packageExportsCache.get(requestPath); | | 237 | + } | | 238 | + | | 239 | + const pkg = readPackageRaw(requestPath); | | 240 | + if (!pkg) { | | 241 | + packageExportsCache.set(requestPath, null); | | 242 | + return null; | | 243 | + } | | 244 | + | | 245 | + return pkg.exports; | | 246 | +} | | 247 | + | 212 | 248 | function tryPackage(requestPath, exts, isMain, originalPath) { | 213 | 249 | const pkg = readPackage(requestPath); | 214 | 250 |
| @@ -297,8 +333,59 @@ function findLongestRegisteredExtension(filename) { | 297 | 333 | return '.js'; | 298 | 334 | } | 299 | 335 |
| | 336 | +// This only applies to requests of a specific form: | | 337 | +// 1. name/.* | | 338 | +// 2. @scope/name/.* | | 339 | +const EXPORTS_PATTERN = /^((?:@[^./@\\][^/@\\]*\/)?[^@./\\][^/\\]*)(\/.*)$/; | | 340 | +function resolveExports(nmPath, request, absoluteRequest) { | | 341 | + // The implementation's behavior is meant to mirror resolution in ESM. | | 342 | + if (experimentalExports && !absoluteRequest) { | | 343 | + const [, name, expansion] = | | 344 | + StringPrototype.match(request, EXPORTS_PATTERN) || []; | | 345 | + if (!name) { | | 346 | + return path.resolve(nmPath, request); | | 347 | + } | | 348 | + | | 349 | + const basePath = path.resolve(nmPath, name); | | 350 | + const pkgExports = readExports(basePath); | | 351 | + | | 352 | + if (pkgExports != null) { | | 353 | + const mappingKey = `.${expansion}`; | | 354 | + const mapping = pkgExports[mappingKey]; | | 355 | + if (typeof mapping === 'string') { | | 356 | + return fileURLToPath(new URL(mapping, `${pathToFileURL(basePath)}/`)); | | 357 | + } | | 358 | + | | 359 | + let dirMatch = ''; | | 360 | + for (const [candidateKey, candidateValue] of Object.entries(pkgExports)) { | | 361 | + if (candidateKey[candidateKey.length - 1] !== '/') continue; | | 362 | + if (candidateValue[candidateValue.length - 1] !== '/') continue; | | 363 | + if (candidateKey.length > dirMatch.length && | | 364 | + StringPrototype.startsWith(mappingKey, candidateKey)) { | | 365 | + dirMatch = candidateKey; | | 366 | + } | | 367 | + } | | 368 | + | | 369 | + if (dirMatch !== '') { | | 370 | + const dirMapping = pkgExports[dirMatch]; | | 371 | + const remainder = StringPrototype.slice(mappingKey, dirMatch.length); | | 372 | + const expectedPrefix = | | 373 | + new URL(dirMapping, `${pathToFileURL(basePath)}/`); | | 374 | + const resolved = new URL(remainder, expectedPrefix).href; | | 375 | + if (StringPrototype.startsWith(resolved, expectedPrefix.href)) { | | 376 | + return fileURLToPath(resolved); | | 377 | + } | | 378 | + } | | 379 | + throw new ERR_PATH_NOT_EXPORTED(basePath, mappingKey); | | 380 | + } | | 381 | + } | | 382 | + | | 383 | + return path.resolve(nmPath, request); | | 384 | +} | | 385 | + | 300 | 386 | Module._findPath = function(request, paths, isMain) { | 301 | | - if (path.isAbsolute(request)) { | | 387 | + const absoluteRequest = path.isAbsolute(request); | | 388 | + if (absoluteRequest) { | 302 | 389 | paths = ['']; | 303 | 390 | } else if (!paths || paths.length === 0) { | 304 | 391 | return false; | @@ -322,7 +409,7 @@ Module._findPath = function(request, paths, isMain) { | 322 | 409 | // Don't search further if path doesn't exist | 323 | 410 | const curPath = paths[i]; | 324 | 411 | if (curPath && stat(curPath) < 1) continue; | 325 | | - var basePath = path.resolve(curPath, request); | | 412 | + var basePath = resolveExports(curPath, request, absoluteRequest); | 326 | 413 | var filename; | 327 | 414 |
| 328 | 415 | var rc = stat(basePath); | |
Collapse file Copy file name to clipboardExpand all lines: src/module_wrap.cc +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -856,7 +856,7 @@ Maybe<URL> PackageExportsResolve(Environment* env, | 856 | 856 | std::string msg = "Package exports for '" + | 857 | 857 | URL(".", pjson_url).ToFilePath() + "' do not define a '" + pkg_subpath + | 858 | 858 | "' subpath, imported from " + base.ToFilePath(); | 859 | | - node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str()); | | 859 | + node::THROW_ERR_PATH_NOT_EXPORTED(env, msg.c_str()); | 860 | 860 | return Nothing<URL>(); | 861 | 861 | } | 862 | 862 |
| |
Collapse file Copy file name to clipboardExpand all lines: src/node_errors.h +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -53,6 +53,7 @@ void PrintErrorString(const char* format, ...); | 53 | 53 | V(ERR_MISSING_PLATFORM_FOR_WORKER, Error) \ | 54 | 54 | V(ERR_MODULE_NOT_FOUND, Error) \ | 55 | 55 | V(ERR_OUT_OF_RANGE, RangeError) \ | | 56 | + V(ERR_PATH_NOT_EXPORTED, Error) \ | 56 | 57 | V(ERR_SCRIPT_EXECUTION_INTERRUPTED, Error) \ | 57 | 58 | V(ERR_SCRIPT_EXECUTION_TIMEOUT, Error) \ | 58 | 59 | V(ERR_STRING_TOO_LONG, Error) \ | |
Collapse file Copy file name to clipboardExpand all lines: src/node_file.cc +3-1Lines changed: 3 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -872,7 +872,9 @@ static void InternalModuleReadJSON(const FunctionCallbackInfo<Value>& args) { | 872 | 872 | } | 873 | 873 |
| 874 | 874 | const size_t size = offset - start; | 875 | | - if (size == 0 || size == SearchString(&chars[start], size, "\"main\"")) { | | 875 | + if (size == 0 || ( | | 876 | + size == SearchString(&chars[start], size, "\"main\"") && | | 877 | + size == SearchString(&chars[start], size, "\"exports\""))) { | 876 | 878 | return; | 877 | 879 | } else { | 878 | 880 | Local<String> chars_string = | |
Collapse file Copy file name to clipboardExpand all lines: src/node_options.cc +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -319,6 +319,7 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { | 319 | 319 | "experimental ES Module support and caching modules", | 320 | 320 | &EnvironmentOptions::experimental_modules, | 321 | 321 | kAllowedInEnvironment); | | 322 | + Implies("--experimental-modules", "--experimental-exports"); | 322 | 323 | AddOption("--experimental-wasm-modules", | 323 | 324 | "experimental ES Module support for webassembly modules", | 324 | 325 | &EnvironmentOptions::experimental_wasm_modules, | |
Collapse file Copy file name to clipboardExpand all lines: test/es-module/test-esm-exports.mjs +3-2Lines changed: 3 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | | -// Flags: --experimental-modules --experimental-exports | | 1 | +// Flags: --experimental-modules | 2 | 2 |
| 3 | 3 | import { mustCall } from '../common/index.mjs'; | 4 | 4 | import { ok, strictEqual } from 'assert'; | 5 | 5 |
| 6 | | -import { asdf, asdf2 } from '../fixtures/pkgexports.mjs'; | | 6 | +import { asdf, asdf2, space } from '../fixtures/pkgexports.mjs'; | 7 | 7 | import { | 8 | 8 | loadMissing, | 9 | 9 | loadFromNumber, | @@ -12,6 +12,7 @@ import { | 12 | 12 |
| 13 | 13 | strictEqual(asdf, 'asdf'); | 14 | 14 | strictEqual(asdf2, 'asdf'); | | 15 | +strictEqual(space, 'encoded path'); | 15 | 16 |
| 16 | 17 | loadMissing().catch(mustCall((err) => { | 17 | 18 | ok(err.message.toString().startsWith('Package exports')); | |
Collapse file Copy file name to clipboardExpand all lines: test/fixtures/node_modules/pkgexports/package.json +2Lines changed: 2 additions & 0 deletions
|