From 128f56b5b18e434916b55145658bacef5eefe100 Mon Sep 17 00:00:00 2001 From: evanbacon Date: Mon, 23 May 2022 19:56:33 -0500 Subject: [PATCH 01/28] feat: add support for capturing require.context in dependency collector --- .../__tests__/collectDependencies-test.js | 16 ++ .../ModuleGraph/worker/collectDependencies.js | 142 +++++++++++++++++- 2 files changed, 154 insertions(+), 4 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index 41416c9969..c1195f07ba 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -42,6 +42,22 @@ const opts = { dependencyMapName: null, }; +it(`collects require context arguments`, () => { + const ast = astFromCode(` + const a = require.context('./', true, /foobar/); +`); + const {dependencies, dependencyMapName} = collectDependencies(ast, opts); + + expect(dependencies).toEqual([ + {name: './', data: objectContaining({asyncType: null})}, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require.context(${dependencyMapName}[0], { recursive: true, filter: /foobar/ }, "./"); + `), + ); +}); + it('collects unique dependency identifiers and transforms the AST', () => { const ast = astFromCode(` const a = require('b/lib/a'); diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index f0b9897815..2cae22120c 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -45,6 +45,11 @@ type DependencyData = $ReadOnly<{ // If left unspecified, then the dependency is unconditionally split. splitCondition?: TSplitCondition, locs: Array, + + /** Should search recursively through folders. */ + recursive?: boolean, + /** A filter to run against files that match the directory */ + filter?: string, }>; export type MutableInternalDependency = { @@ -59,6 +64,8 @@ export type InternalDependency = $ReadOnly< export type State = { asyncRequireModulePathStringLiteral: ?StringLiteral, + /** Path to file for handling `require.context` statements */ + requireContextModulePathStringLiteral: ?StringLiteral, dependencyCalls: Set, dependencyRegistry: ModuleDependencyRegistry, dependencyTransformer: DependencyTransformer, @@ -70,6 +77,8 @@ export type State = { export type Options = $ReadOnly<{ asyncRequireModulePath: string, + /** Path to file for handling `require.context` statements */ + requireContextModulePath: string, dependencyMapName: ?string, dynamicRequires: DynamicRequiresBehavior, inlineableCalls: $ReadOnlyArray, @@ -142,6 +151,7 @@ function collectDependencies( const state: State = { asyncRequireModulePathStringLiteral: null, + requireContextModulePathStringLiteral: null, dependencyCalls: new Set(), dependencyRegistry: options.dependencyRegistry ?? new DefaultModuleDependencyRegistry(), @@ -199,6 +209,16 @@ function collectDependencies( return; } + if ( + callee.type === 'MemberExpression' && + (callee.object || {}).name === 'require' && + (callee.property || {}).name === 'context' + ) { + processRequireContextCall(path, state); + visited.add(path.node); + return; + } + if ( name != null && state.dependencyCalls.has(name) && @@ -251,6 +271,70 @@ function collectDependencies( }; } +/** Extract args passed to `require.context` method. Exposed for testing. */ +function getRequireContextArgs(path: NodePath): { + directory: string, + /* optional, default true */ + recursive: boolean, + /* optional, default /^\.\/.*$/, any file */ + filter: string, +} { + const args = path.get('arguments'); + + if ( + !Array.isArray(args) || + args.length < 1 || + args[0].node.type !== 'StringLiteral' + ) { + throw new InvalidRequireCallError(path); + } + + let recursive: boolean = true; + if (args.length > 1) { + if (args[1].node.type !== 'BooleanLiteral') { + throw new InvalidRequireCallError(path); + } + recursive = args[1].node.value; + } + let filter = '^\\.\\/.*$'; + if (args.length > 2) { + if (args[2].node.type !== 'RegExpLiteral') { + throw new InvalidRequireCallError(path); + } + filter = args[2].node.pattern; + } + + return { + directory: args[0].node.value, + recursive, + filter, + }; +} +collectDependencies.getRequireContextArgs = getRequireContextArgs; + +function processRequireContextCall( + path: NodePath, + state: State, +): void { + const {directory, filter, recursive} = getRequireContextArgs(path); + const transformer = state.dependencyTransformer; + const dep = registerDependency( + state, + { + // We basically want to "import" every file in a folder and then filter them out with the given `filter` RegExp. + name: directory, + // Capture the matching context + filter, + recursive, + asyncType: null, + optional: isOptionalDependency(directory, path, state), + }, + path, + ); + + transformer.transformSyncRequire(path, dep, state); +} + function collectImports( path: NodePath<>, state: State, @@ -344,6 +428,10 @@ export type ImportQualifier = $ReadOnly<{ asyncType: AsyncDependencyType | null, splitCondition?: NodePath<>, optional: boolean, + /* Should search for files recursively. Optional, default `true` when `require.context` is used */ + recursive?: boolean, + /* Filename filter pattern for use in `require.context`. Optional, default `/^\.\/.*$/` (any file) when `require.context` is used */ + filter?: string, }>; function registerDependency( @@ -352,7 +440,6 @@ function registerDependency( path: NodePath<>, ): InternalDependency { const dependency = state.dependencyRegistry.registerDependency(qualifier); - const loc = getNearestLocFromPath(path); if (loc != null) { dependency.locs.push(loc); @@ -462,6 +549,10 @@ const makeJSResourceTemplate = template.statement(` require(ASYNC_REQUIRE_MODULE_PATH).resource(MODULE_ID, MODULE_NAME) `); +const makeRequireContextTemplate = template.statement(` + require(REQUIRE_CONTEXT_MODULE_PATH).context(MODULE_ID_ARRAY, MODULE_NAME) +`); + const DefaultDependencyTransformer: DependencyTransformer = { transformSyncRequire( path: NodePath, @@ -469,9 +560,30 @@ const DefaultDependencyTransformer: DependencyTransformer = { state: State, ): void { const moduleIDExpression = createModuleIDExpression(dependency, state); - path.node.arguments = state.keepRequireNames - ? [moduleIDExpression, types.stringLiteral(dependency.name)] - : [moduleIDExpression]; + path.node.arguments = [moduleIDExpression]; + // `require.context` adds the filter parameter so we can push it on the arguments with recursive. + if (dependency.filter) { + // Push object props for context, ex: { recursive: true, filter: /foobar/ } + path.node.arguments.push( + // { } + types.objectExpression([ + // { recursive: true } + types.objectProperty( + types.identifier('recursive'), + types.booleanLiteral(dependency.recursive), + ), + // { filter: /foobar/ } + types.objectProperty( + types.identifier('filter'), + types.regExpLiteral(dependency.filter), + ), + ]), + ); + } + // Always add the debug name argument last + if (state.keepRequireNames) { + path.node.arguments.push(types.stringLiteral(dependency.name)); + } }, transformImportCall( @@ -490,6 +602,22 @@ const DefaultDependencyTransformer: DependencyTransformer = { ); }, + transformRequireContext( + path: NodePath<>, + dependency: InternalDependency, + state: State, + ): void { + path.replaceWith( + makeRequireContextTemplate({ + REQUIRE_CONTEXT_MODULE_PATH: nullthrows( + state.requireContextModulePathStringLiteral, + ), + MODULE_ID_ARRAY: createModuleIDExpression(dependency, state), + MODULE_NAME: createModuleNameLiteral(dependency), + }), + ); + }, + transformJSResource( path: NodePath<>, dependency: InternalDependency, @@ -568,6 +696,12 @@ class DefaultModuleDependencyRegistry if (qualifier.optional) { newDependency.isOptional = true; } + if (qualifier.filter) { + newDependency.filter = qualifier.filter; + } + if (qualifier.recursive) { + newDependency.recursive = qualifier.recursive; + } dependency = newDependency; this._dependencies.set(qualifier.name, dependency); From 3c1ea0d13f9a5602474989b09bce061706b377f4 Mon Sep 17 00:00:00 2001 From: evanbacon Date: Tue, 24 May 2022 16:55:05 -0500 Subject: [PATCH 02/28] chore: match require.context better --- .../ModuleGraph/worker/collectDependencies.js | 36 +++++-------------- 1 file changed, 9 insertions(+), 27 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 2cae22120c..17c10c626f 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -64,8 +64,6 @@ export type InternalDependency = $ReadOnly< export type State = { asyncRequireModulePathStringLiteral: ?StringLiteral, - /** Path to file for handling `require.context` statements */ - requireContextModulePathStringLiteral: ?StringLiteral, dependencyCalls: Set, dependencyRegistry: ModuleDependencyRegistry, dependencyTransformer: DependencyTransformer, @@ -77,8 +75,6 @@ export type State = { export type Options = $ReadOnly<{ asyncRequireModulePath: string, - /** Path to file for handling `require.context` statements */ - requireContextModulePath: string, dependencyMapName: ?string, dynamicRequires: DynamicRequiresBehavior, inlineableCalls: $ReadOnlyArray, @@ -151,7 +147,6 @@ function collectDependencies( const state: State = { asyncRequireModulePathStringLiteral: null, - requireContextModulePathStringLiteral: null, dependencyCalls: new Set(), dependencyRegistry: options.dependencyRegistry ?? new DefaultModuleDependencyRegistry(), @@ -209,10 +204,17 @@ function collectDependencies( return; } + // Match `require.context` if ( callee.type === 'MemberExpression' && - (callee.object || {}).name === 'require' && - (callee.property || {}).name === 'context' + callee.object && + // `require` + callee.object.type === 'Identifier' && + callee.object.name === 'require' && + // `context` + callee.property && + callee.property.type === 'Identifier' && + callee.property.name === 'context' ) { processRequireContextCall(path, state); visited.add(path.node); @@ -549,10 +551,6 @@ const makeJSResourceTemplate = template.statement(` require(ASYNC_REQUIRE_MODULE_PATH).resource(MODULE_ID, MODULE_NAME) `); -const makeRequireContextTemplate = template.statement(` - require(REQUIRE_CONTEXT_MODULE_PATH).context(MODULE_ID_ARRAY, MODULE_NAME) -`); - const DefaultDependencyTransformer: DependencyTransformer = { transformSyncRequire( path: NodePath, @@ -602,22 +600,6 @@ const DefaultDependencyTransformer: DependencyTransformer = { ); }, - transformRequireContext( - path: NodePath<>, - dependency: InternalDependency, - state: State, - ): void { - path.replaceWith( - makeRequireContextTemplate({ - REQUIRE_CONTEXT_MODULE_PATH: nullthrows( - state.requireContextModulePathStringLiteral, - ), - MODULE_ID_ARRAY: createModuleIDExpression(dependency, state), - MODULE_NAME: createModuleNameLiteral(dependency), - }), - ); - }, - transformJSResource( path: NodePath<>, dependency: InternalDependency, From a121d3e27dc72c146b2bb50f89a08c066077bbd9 Mon Sep 17 00:00:00 2001 From: evanbacon Date: Tue, 24 May 2022 17:01:45 -0500 Subject: [PATCH 03/28] chore: add guard against feature with `unstable_allowRequireContext` --- packages/metro-config/src/defaults/index.js | 1 + packages/metro-transform-worker/src/index.js | 2 ++ .../worker/__tests__/collectDependencies-test.js | 5 ++++- .../metro/src/ModuleGraph/worker/collectDependencies.js | 6 ++++++ 4 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/metro-config/src/defaults/index.js b/packages/metro-config/src/defaults/index.js index d5ef1b2405..109857b6f7 100644 --- a/packages/metro-config/src/defaults/index.js +++ b/packages/metro-config/src/defaults/index.js @@ -120,6 +120,7 @@ const getDefaultValues = (projectRoot: ?string): ConfigT => ({ workerPath: 'metro/src/DeltaBundler/Worker', publicPath: '/assets', allowOptionalDependencies: false, + unstable_allowRequireContext: false, unstable_collectDependenciesPath: 'metro/src/ModuleGraph/worker/collectDependencies.js', unstable_dependencyMapReservedName: null, diff --git a/packages/metro-transform-worker/src/index.js b/packages/metro-transform-worker/src/index.js index d0bb078961..f7865c90c7 100644 --- a/packages/metro-transform-worker/src/index.js +++ b/packages/metro-transform-worker/src/index.js @@ -99,6 +99,8 @@ export type JsTransformerConfig = $ReadOnly<{ unstable_disableModuleWrapping: boolean, unstable_disableNormalizePseudoGlobals: boolean, unstable_compactOutput: boolean, + /** Enable `require.context` statements which can be used to import multiple files in a directory. */ + unstable_allowRequireContext?: boolean, }>; export type {CustomTransformOptions} from 'metro-babel-transformer'; diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index c1195f07ba..dadf671825 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -46,7 +46,10 @@ it(`collects require context arguments`, () => { const ast = astFromCode(` const a = require.context('./', true, /foobar/); `); - const {dependencies, dependencyMapName} = collectDependencies(ast, opts); + const {dependencies, dependencyMapName} = collectDependencies(ast, { + ...opts, + unstable_allowRequireContext: true, + }); expect(dependencies).toEqual([ {name: './', data: objectContaining({asyncType: null})}, diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 17c10c626f..4fdcca4cb3 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -71,6 +71,8 @@ export type State = { dependencyMapIdentifier: ?Identifier, keepRequireNames: boolean, allowOptionalDependencies: AllowOptionalDependencies, + /** Enable `require.context` statements which can be used to import multiple files in a directory. */ + unstable_allowRequireContext?: boolean, }; export type Options = $ReadOnly<{ @@ -82,6 +84,8 @@ export type Options = $ReadOnly<{ allowOptionalDependencies: AllowOptionalDependencies, dependencyRegistry?: ModuleDependencyRegistry, dependencyTransformer?: DependencyTransformer, + /** Enable `require.context` statements which can be used to import multiple files in a directory. */ + unstable_allowRequireContext?: boolean, }>; export type CollectedDependencies<+TSplitCondition> = $ReadOnly<{ @@ -156,6 +160,7 @@ function collectDependencies( dynamicRequires: options.dynamicRequires, keepRequireNames: options.keepRequireNames, allowOptionalDependencies: options.allowOptionalDependencies, + unstable_allowRequireContext: options.unstable_allowRequireContext, }; const visitor = { @@ -206,6 +211,7 @@ function collectDependencies( // Match `require.context` if ( + state.unstable_allowRequireContext && callee.type === 'MemberExpression' && callee.object && // `require` From 039ca748dc42bf0a8b41bdda1639922a4af3ec1c Mon Sep 17 00:00:00 2001 From: evanbacon Date: Tue, 24 May 2022 17:21:29 -0500 Subject: [PATCH 04/28] fix: don't pass values to runtime --- .../__tests__/collectDependencies-test.js | 22 ++++++++++-- .../ModuleGraph/worker/collectDependencies.js | 34 +++++-------------- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index dadf671825..7ad4500fb4 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -44,19 +44,35 @@ const opts = { it(`collects require context arguments`, () => { const ast = astFromCode(` - const a = require.context('./', true, /foobar/); + const a = require.context('./', false, /foobar/m); + const b = require.context('./baz'); `); const {dependencies, dependencyMapName} = collectDependencies(ast, { ...opts, unstable_allowRequireContext: true, }); + expect(dependencies[0].data.recursive).not.toBeDefined(); expect(dependencies).toEqual([ - {name: './', data: objectContaining({asyncType: null})}, + { + name: './', + data: objectContaining({ + filter: /foobar/m, + }), + }, + { + name: './baz', + data: objectContaining({ + filter: /^\.\/.*$/, + recursive: true, + }), + }, ]); + expect(codeFromAst(ast)).toEqual( comparableCode(` - const a = require.context(${dependencyMapName}[0], { recursive: true, filter: /foobar/ }, "./"); + const a = require.context(${dependencyMapName}[0], "./"); + const b = require.context(${dependencyMapName}[1], "./baz"); `), ); }); diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 4fdcca4cb3..c3e6790f8b 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -279,13 +279,13 @@ function collectDependencies( }; } -/** Extract args passed to `require.context` method. Exposed for testing. */ +/** Extract args passed to the `require.context` method. */ function getRequireContextArgs(path: NodePath): { directory: string, /* optional, default true */ recursive: boolean, /* optional, default /^\.\/.*$/, any file */ - filter: string, + filter: RegExp, } { const args = path.get('arguments'); @@ -304,12 +304,15 @@ function getRequireContextArgs(path: NodePath): { } recursive = args[1].node.value; } - let filter = '^\\.\\/.*$'; + let filter = /^\.\/.*$/; if (args.length > 2) { - if (args[2].node.type !== 'RegExpLiteral') { + const argNode = args[2].node; + if (argNode.type === 'RegExpLiteral') { + filter = new RegExp(argNode.pattern, argNode.flags); + } else { + // TODO: Handle `new RegExp(...)` -- `argNode.type === 'NewExpression'` throw new InvalidRequireCallError(path); } - filter = args[2].node.pattern; } return { @@ -439,7 +442,7 @@ export type ImportQualifier = $ReadOnly<{ /* Should search for files recursively. Optional, default `true` when `require.context` is used */ recursive?: boolean, /* Filename filter pattern for use in `require.context`. Optional, default `/^\.\/.*$/` (any file) when `require.context` is used */ - filter?: string, + filter?: RegExp, }>; function registerDependency( @@ -565,25 +568,6 @@ const DefaultDependencyTransformer: DependencyTransformer = { ): void { const moduleIDExpression = createModuleIDExpression(dependency, state); path.node.arguments = [moduleIDExpression]; - // `require.context` adds the filter parameter so we can push it on the arguments with recursive. - if (dependency.filter) { - // Push object props for context, ex: { recursive: true, filter: /foobar/ } - path.node.arguments.push( - // { } - types.objectExpression([ - // { recursive: true } - types.objectProperty( - types.identifier('recursive'), - types.booleanLiteral(dependency.recursive), - ), - // { filter: /foobar/ } - types.objectProperty( - types.identifier('filter'), - types.regExpLiteral(dependency.filter), - ), - ]), - ); - } // Always add the debug name argument last if (state.keepRequireNames) { path.node.arguments.push(types.stringLiteral(dependency.name)); From f34eab2caf4e72050bf76f237aa2640e97a5d6ee Mon Sep 17 00:00:00 2001 From: evanbacon Date: Wed, 25 May 2022 12:17:54 -0500 Subject: [PATCH 05/28] Added modes --- .../__tests__/collectDependencies-test.js | 16 ++++-- .../ModuleGraph/worker/collectDependencies.js | 53 ++++++++++++------- 2 files changed, 46 insertions(+), 23 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index 7ad4500fb4..b1c23f9d50 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -52,19 +52,27 @@ it(`collects require context arguments`, () => { unstable_allowRequireContext: true, }); - expect(dependencies[0].data.recursive).not.toBeDefined(); expect(dependencies).toEqual([ { name: './', data: objectContaining({ - filter: /foobar/m, + contextParams: { + directory: './', + filter: /foobar/m, + mode: 'sync', + recursive: false, + }, }), }, { name: './baz', data: objectContaining({ - filter: /^\.\/.*$/, - recursive: true, + contextParams: { + directory: './baz', + filter: /^\.\/.*$/, + mode: 'sync', + recursive: true, + }, }), }, ]); diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index c3e6790f8b..b4293d929b 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -37,6 +37,15 @@ export type Dependency = $ReadOnly<{ name: string, }>; +type RequireContextParams = $ReadOnly<{ + /* Should search for files recursively. Optional, default `true` when `require.context` is used */ + recursive?: boolean, + /* Filename filter pattern for use in `require.context`. Optional, default `/^\.\/.*$/` (any file) when `require.context` is used */ + filter?: RegExp, + /** Mode for resolving dynamic dependencies. Defaults to `sync` */ + mode: 'sync' | 'eager' | 'lazy' | 'lazy-once', +}>; + type DependencyData = $ReadOnly<{ // If null, then the dependency is synchronous. // (ex. `require('foo')`) @@ -45,11 +54,7 @@ type DependencyData = $ReadOnly<{ // If left unspecified, then the dependency is unconditionally split. splitCondition?: TSplitCondition, locs: Array, - - /** Should search recursively through folders. */ - recursive?: boolean, - /** A filter to run against files that match the directory */ - filter?: string, + contextParams?: RequireContextParams, }>; export type MutableInternalDependency = { @@ -286,6 +291,8 @@ function getRequireContextArgs(path: NodePath): { recursive: boolean, /* optional, default /^\.\/.*$/, any file */ filter: RegExp, + /** Mode for resolving dynamic dependencies. Defaults to `sync` */ + mode: 'sync' | 'eager' | 'lazy' | 'lazy-once', } { const args = path.get('arguments'); @@ -314,11 +321,26 @@ function getRequireContextArgs(path: NodePath): { throw new InvalidRequireCallError(path); } } + let mode = 'sync'; + if (args.length > 3) { + const argNode = args[3].node; + if (argNode.type === 'StringLiteral') { + mode = argNode.value; + + if (mode === 'weak') { + throw new Error('require.context "weak" mode is not supported.'); + } + } else { + // TODO: Handle `new RegExp(...)` -- `argNode.type === 'NewExpression'` + throw new InvalidRequireCallError(path); + } + } return { directory: args[0].node.value, recursive, filter, + mode, }; } collectDependencies.getRequireContextArgs = getRequireContextArgs; @@ -327,18 +349,17 @@ function processRequireContextCall( path: NodePath, state: State, ): void { - const {directory, filter, recursive} = getRequireContextArgs(path); + const contextParams = getRequireContextArgs(path); const transformer = state.dependencyTransformer; const dep = registerDependency( state, { // We basically want to "import" every file in a folder and then filter them out with the given `filter` RegExp. - name: directory, + name: contextParams.directory, // Capture the matching context - filter, - recursive, + contextParams, asyncType: null, - optional: isOptionalDependency(directory, path, state), + optional: isOptionalDependency(contextParams.directory, path, state), }, path, ); @@ -439,10 +460,7 @@ export type ImportQualifier = $ReadOnly<{ asyncType: AsyncDependencyType | null, splitCondition?: NodePath<>, optional: boolean, - /* Should search for files recursively. Optional, default `true` when `require.context` is used */ - recursive?: boolean, - /* Filename filter pattern for use in `require.context`. Optional, default `/^\.\/.*$/` (any file) when `require.context` is used */ - filter?: RegExp, + contextParams?: RequireContextParams, }>; function registerDependency( @@ -668,11 +686,8 @@ class DefaultModuleDependencyRegistry if (qualifier.optional) { newDependency.isOptional = true; } - if (qualifier.filter) { - newDependency.filter = qualifier.filter; - } - if (qualifier.recursive) { - newDependency.recursive = qualifier.recursive; + if (qualifier.contextParams) { + newDependency.contextParams = qualifier.contextParams; } dependency = newDependency; From 24fb99de3ecf3a03d8e506ad9c122f0e6b4c6237 Mon Sep 17 00:00:00 2001 From: evanbacon Date: Wed, 25 May 2022 12:25:36 -0500 Subject: [PATCH 06/28] Update collectDependencies.js --- .../metro/src/ModuleGraph/worker/collectDependencies.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index b4293d929b..d308ce9530 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -216,6 +216,7 @@ function collectDependencies( // Match `require.context` if ( + // Feature gate, defaults to `false`. state.unstable_allowRequireContext && callee.type === 'MemberExpression' && callee.object && @@ -225,7 +226,9 @@ function collectDependencies( // `context` callee.property && callee.property.type === 'Identifier' && - callee.property.name === 'context' + callee.property.name === 'context' && + // Ensure `require` refers to the global and not something else. + !path.scope.getBinding('require') ) { processRequireContextCall(path, state); visited.add(path.node); @@ -304,6 +307,7 @@ function getRequireContextArgs(path: NodePath): { throw new InvalidRequireCallError(path); } + // Default to requiring through all directories. let recursive: boolean = true; if (args.length > 1) { if (args[1].node.type !== 'BooleanLiteral') { @@ -311,6 +315,7 @@ function getRequireContextArgs(path: NodePath): { } recursive = args[1].node.value; } + // Default to all files. let filter = /^\.\/.*$/; if (args.length > 2) { const argNode = args[2].node; @@ -321,6 +326,7 @@ function getRequireContextArgs(path: NodePath): { throw new InvalidRequireCallError(path); } } + // Default to `sync`. let mode = 'sync'; if (args.length > 3) { const argNode = args[3].node; From 137d6c009588277a9ecdce19dace7e5c9e331315 Mon Sep 17 00:00:00 2001 From: evanbacon Date: Wed, 25 May 2022 12:27:01 -0500 Subject: [PATCH 07/28] Update collectDependencies-test.js --- .../ModuleGraph/worker/__tests__/collectDependencies-test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index b1c23f9d50..913a2b5344 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -44,7 +44,7 @@ const opts = { it(`collects require context arguments`, () => { const ast = astFromCode(` - const a = require.context('./', false, /foobar/m); + const a = require.context('./', false, /foobar/m, 'eager'); const b = require.context('./baz'); `); const {dependencies, dependencyMapName} = collectDependencies(ast, { @@ -59,7 +59,7 @@ it(`collects require context arguments`, () => { contextParams: { directory: './', filter: /foobar/m, - mode: 'sync', + mode: 'eager', recursive: false, }, }), From 9ed9dd42fd07955b4d69bd644ae07aa97d287377 Mon Sep 17 00:00:00 2001 From: evanbacon Date: Wed, 25 May 2022 12:37:56 -0500 Subject: [PATCH 08/28] fix types --- .../ModuleGraph/worker/collectDependencies.js | 62 +++++++++++-------- 1 file changed, 35 insertions(+), 27 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index d308ce9530..53954ca71d 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -37,13 +37,15 @@ export type Dependency = $ReadOnly<{ name: string, }>; +type ContextMode = 'sync' | 'eager' | 'lazy' | 'lazy-once'; + type RequireContextParams = $ReadOnly<{ /* Should search for files recursively. Optional, default `true` when `require.context` is used */ - recursive?: boolean, + recursive: boolean, /* Filename filter pattern for use in `require.context`. Optional, default `/^\.\/.*$/` (any file) when `require.context` is used */ - filter?: RegExp, + filter: RegExp, /** Mode for resolving dynamic dependencies. Defaults to `sync` */ - mode: 'sync' | 'eager' | 'lazy' | 'lazy-once', + mode: ContextMode, }>; type DependencyData = $ReadOnly<{ @@ -288,23 +290,20 @@ function collectDependencies( } /** Extract args passed to the `require.context` method. */ -function getRequireContextArgs(path: NodePath): { - directory: string, - /* optional, default true */ - recursive: boolean, - /* optional, default /^\.\/.*$/, any file */ - filter: RegExp, - /** Mode for resolving dynamic dependencies. Defaults to `sync` */ - mode: 'sync' | 'eager' | 'lazy' | 'lazy-once', -} { +function getRequireContextArgs( + path: NodePath, +): [string, RequireContextParams] { const args = path.get('arguments'); + let directory: string; if ( !Array.isArray(args) || args.length < 1 || args[0].node.type !== 'StringLiteral' ) { throw new InvalidRequireCallError(path); + } else { + directory = args[0].node.value; } // Default to requiring through all directories. @@ -327,45 +326,54 @@ function getRequireContextArgs(path: NodePath): { } } // Default to `sync`. - let mode = 'sync'; + let mode: ContextMode = 'sync'; if (args.length > 3) { const argNode = args[3].node; if (argNode.type === 'StringLiteral') { - mode = argNode.value; - - if (mode === 'weak') { - throw new Error('require.context "weak" mode is not supported.'); - } + mode = getContextMode(argNode.value); } else { // TODO: Handle `new RegExp(...)` -- `argNode.type === 'NewExpression'` throw new InvalidRequireCallError(path); } } - return { - directory: args[0].node.value, - recursive, - filter, - mode, - }; + return [ + directory, + { + recursive, + filter, + mode, + }, + ]; +} + +function getContextMode(mode: any): ContextMode { + if ( + typeof mode === 'string' && + ['sync', 'eager', 'lazy', 'lazy-once'].includes(mode) + ) { + return ((mode: any): ContextMode); + } + throw new Error(`require.context "${mode}" mode is not supported.`); } + collectDependencies.getRequireContextArgs = getRequireContextArgs; function processRequireContextCall( path: NodePath, state: State, ): void { - const contextParams = getRequireContextArgs(path); + const [directory, contextParams] = getRequireContextArgs(path); const transformer = state.dependencyTransformer; const dep = registerDependency( state, { // We basically want to "import" every file in a folder and then filter them out with the given `filter` RegExp. - name: contextParams.directory, + name: directory, // Capture the matching context contextParams, asyncType: null, - optional: isOptionalDependency(contextParams.directory, path, state), + optional: isOptionalDependency(directory, path, state), }, path, ); From f26088df99ce3cb0a45c111cee9c86ed3e1532df Mon Sep 17 00:00:00 2001 From: evanbacon Date: Wed, 25 May 2022 12:39:16 -0500 Subject: [PATCH 09/28] Update collectDependencies-test.js --- .../ModuleGraph/worker/__tests__/collectDependencies-test.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index 913a2b5344..e317a3f50b 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -57,7 +57,6 @@ it(`collects require context arguments`, () => { name: './', data: objectContaining({ contextParams: { - directory: './', filter: /foobar/m, mode: 'eager', recursive: false, @@ -68,7 +67,6 @@ it(`collects require context arguments`, () => { name: './baz', data: objectContaining({ contextParams: { - directory: './baz', filter: /^\.\/.*$/, mode: 'sync', recursive: true, From 518a48e219ec000cfb34f888a67b73d643c3ed6f Mon Sep 17 00:00:00 2001 From: evanbacon Date: Thu, 26 May 2022 10:51:53 -0500 Subject: [PATCH 10/28] strict types --- packages/metro-transform-worker/src/index.js | 2 +- .../metro/src/ModuleGraph/worker/collectDependencies.js | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/packages/metro-transform-worker/src/index.js b/packages/metro-transform-worker/src/index.js index f7865c90c7..d6d4e57262 100644 --- a/packages/metro-transform-worker/src/index.js +++ b/packages/metro-transform-worker/src/index.js @@ -100,7 +100,7 @@ export type JsTransformerConfig = $ReadOnly<{ unstable_disableNormalizePseudoGlobals: boolean, unstable_compactOutput: boolean, /** Enable `require.context` statements which can be used to import multiple files in a directory. */ - unstable_allowRequireContext?: boolean, + unstable_allowRequireContext: boolean, }>; export type {CustomTransformOptions} from 'metro-babel-transformer'; diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 53954ca71d..e2c37ca3b8 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -79,7 +79,7 @@ export type State = { keepRequireNames: boolean, allowOptionalDependencies: AllowOptionalDependencies, /** Enable `require.context` statements which can be used to import multiple files in a directory. */ - unstable_allowRequireContext?: boolean, + unstable_allowRequireContext: boolean, }; export type Options = $ReadOnly<{ @@ -92,7 +92,7 @@ export type Options = $ReadOnly<{ dependencyRegistry?: ModuleDependencyRegistry, dependencyTransformer?: DependencyTransformer, /** Enable `require.context` statements which can be used to import multiple files in a directory. */ - unstable_allowRequireContext?: boolean, + unstable_allowRequireContext: boolean, }>; export type CollectedDependencies<+TSplitCondition> = $ReadOnly<{ @@ -221,12 +221,10 @@ function collectDependencies( // Feature gate, defaults to `false`. state.unstable_allowRequireContext && callee.type === 'MemberExpression' && - callee.object && // `require` callee.object.type === 'Identifier' && callee.object.name === 'require' && // `context` - callee.property && callee.property.type === 'Identifier' && callee.property.name === 'context' && // Ensure `require` refers to the global and not something else. From 85db737bed9f54b2ed05413a1d85adfaccef25c5 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Thu, 26 May 2022 10:52:05 -0500 Subject: [PATCH 11/28] Update packages/metro/src/ModuleGraph/worker/collectDependencies.js Co-authored-by: Moti Zilberman --- packages/metro/src/ModuleGraph/worker/collectDependencies.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index e2c37ca3b8..c2cdbd8f86 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -335,6 +335,10 @@ function getRequireContextArgs( } } + if (args.length > 4) { + throw new InvalidRequireCallError(path); + } + return [ directory, { From 4d0ee6b1f7cedfc7127044b5c9f6bf8eb7ef97e5 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Thu, 26 May 2022 10:53:02 -0500 Subject: [PATCH 12/28] Update packages/metro/src/ModuleGraph/worker/collectDependencies.js Co-authored-by: Moti Zilberman --- packages/metro/src/ModuleGraph/worker/collectDependencies.js | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index c2cdbd8f86..884a184a5a 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -227,6 +227,7 @@ function collectDependencies( // `context` callee.property.type === 'Identifier' && callee.property.name === 'context' && + !callee.computed && // Ensure `require` refers to the global and not something else. !path.scope.getBinding('require') ) { From 1c39e9c3ae91eaec9c682016949eb29438c0d58b Mon Sep 17 00:00:00 2001 From: evanbacon Date: Thu, 26 May 2022 11:07:16 -0500 Subject: [PATCH 13/28] Update collectDependencies.js --- .../ModuleGraph/worker/collectDependencies.js | 68 +++++++++++++------ 1 file changed, 46 insertions(+), 22 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 884a184a5a..082e618b47 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -295,49 +295,64 @@ function getRequireContextArgs( const args = path.get('arguments'); let directory: string; - if ( - !Array.isArray(args) || - args.length < 1 || - args[0].node.type !== 'StringLiteral' - ) { + if (!Array.isArray(args) || args.length < 1) { throw new InvalidRequireCallError(path); } else { - directory = args[0].node.value; + const argNode = args[0].node; + if (argNode.type !== 'StringLiteral') { + throw new InvalidRequireCallError( + argNode, + `First argument of \`require.context\` should be a string denoting the directory to require, instead found node of type: ${argNode.type}.`, + ); + } + directory = argNode.value; } // Default to requiring through all directories. let recursive: boolean = true; if (args.length > 1) { - if (args[1].node.type !== 'BooleanLiteral') { - throw new InvalidRequireCallError(path); + const argNode = args[1].node; + if (argNode.type !== 'BooleanLiteral') { + throw new InvalidRequireCallError( + argNode, + `Second argument of \`require.context\` should be an optional boolean indicating if files should be imported recursively or not, instead found node of type: ${argNode.type}.`, + ); } recursive = args[1].node.value; } + // Default to all files. let filter = /^\.\/.*$/; if (args.length > 2) { const argNode = args[2].node; - if (argNode.type === 'RegExpLiteral') { - filter = new RegExp(argNode.pattern, argNode.flags); - } else { + if (argNode.type !== 'RegExpLiteral') { // TODO: Handle `new RegExp(...)` -- `argNode.type === 'NewExpression'` - throw new InvalidRequireCallError(path); + throw new InvalidRequireCallError( + argNode, + `Third argument of \`require.context\` should be an optional RegExp pattern matching all of the files to import, instead found node of type: ${argNode.type}.`, + ); } + filter = new RegExp(argNode.pattern, argNode.flags); } + // Default to `sync`. let mode: ContextMode = 'sync'; if (args.length > 3) { const argNode = args[3].node; - if (argNode.type === 'StringLiteral') { - mode = getContextMode(argNode.value); - } else { - // TODO: Handle `new RegExp(...)` -- `argNode.type === 'NewExpression'` - throw new InvalidRequireCallError(path); + if (argNode.type !== 'StringLiteral') { + throw new InvalidRequireCallError( + path, + `Fourth argument of \`require.context\` should be an optional string "mode" denoting how the modules will be resolved, instead found node of type: ${argNode.type}.`, + ); } + mode = getContextMode(argNode, argNode.value); } if (args.length > 4) { - throw new InvalidRequireCallError(path); + throw new InvalidRequireCallError( + path, + `Too many arguments provided to \`require.context\` call. Expected 4, got: ${args.length}`, + ); } return [ @@ -350,14 +365,23 @@ function getRequireContextArgs( ]; } -function getContextMode(mode: any): ContextMode { +function getContextMode( + path: NodePath, + mode: string, +): ContextMode { if ( typeof mode === 'string' && - ['sync', 'eager', 'lazy', 'lazy-once'].includes(mode) + (mode === 'sync' || + mode === 'eager' || + mode === 'lazy' || + mode === 'lazy-once') ) { - return ((mode: any): ContextMode); + return mode; } - throw new Error(`require.context "${mode}" mode is not supported.`); + throw new InvalidRequireCallError( + path, + `require.context "${mode}" mode is not supported.`, + ); } collectDependencies.getRequireContextArgs = getRequireContextArgs; From 57108f84338017b0c7a2d4bc38a3a3cc814df807 Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Thu, 26 May 2022 11:07:34 -0500 Subject: [PATCH 14/28] Update packages/metro/src/ModuleGraph/worker/collectDependencies.js Co-authored-by: Moti Zilberman --- packages/metro/src/ModuleGraph/worker/collectDependencies.js | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 082e618b47..3e86b8aa35 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -405,6 +405,7 @@ function processRequireContextCall( path, ); + // require() the generated module representing this context transformer.transformSyncRequire(path, dep, state); } From 33ce4e3739c9669e75e098f61f86500c443778f1 Mon Sep 17 00:00:00 2001 From: evanbacon Date: Thu, 26 May 2022 11:40:32 -0500 Subject: [PATCH 15/28] Add getKeyForDependency Implement a key resolver to prevent dependency collision --- .../__tests__/collectDependencies-test.js | 64 ++++++++++++++++++- .../ModuleGraph/worker/collectDependencies.js | 53 +++++++++++++-- 2 files changed, 111 insertions(+), 6 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index e317a3f50b..03de381693 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -32,7 +32,8 @@ const nullthrows = require('nullthrows'); const {any, objectContaining} = expect; -const {InvalidRequireCallError} = collectDependencies; +const {InvalidRequireCallError, DefaultModuleDependencyRegistry} = + collectDependencies; const opts = { asyncRequireModulePath: 'asyncRequire', dynamicRequires: 'reject', @@ -42,6 +43,67 @@ const opts = { dependencyMapName: null, }; +describe(DefaultModuleDependencyRegistry, () => { + describe('getKeyForDependency', () => { + it(`generates basic key`, () => { + expect( + DefaultModuleDependencyRegistry.getKeyForDependency({ + name: './file.js', + }), + ).toBe('./file.js'); + }); + it(`generates require.context key`, () => { + expect( + DefaultModuleDependencyRegistry.getKeyForDependency({ + name: './dir', + contextParams: { + recursive: true, + filter: /foobar/, + mode: 'lazy', + }, + }), + ).toBe('./dir__true__/foobar/__lazy'); + }); + }); + + it(`registers dependencies without collision`, () => { + const registry = new DefaultModuleDependencyRegistry(); + + registry.registerDependency({ + name: './dir', + }); + + registry.registerDependency({ + name: './dir', + contextParams: { + recursive: true, + filter: /foobar/, + mode: 'lazy', + }, + }); + + expect(registry.getDependencies()).toEqual([ + { + asyncType: undefined, + index: 0, + locs: [], + name: './dir', + }, + { + asyncType: undefined, + contextParams: { + filter: /foobar/, + mode: 'lazy', + recursive: true, + }, + index: 1, + locs: [], + name: './dir', + }, + ]); + }); +}); + it(`collects require context arguments`, () => { const ast = astFromCode(` const a = require.context('./', false, /foobar/m, 'eager'); diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 3e86b8aa35..3d5cd8a928 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -103,9 +103,26 @@ export type CollectedDependencies<+TSplitCondition> = $ReadOnly<{ // Registry for the dependency of a module. // Defines when dependencies should be collapsed. -// E.g. should a module that's once required optinally and once not -// be tretaed as the smae or different dependencies. +// E.g. should a module that's once required optionally and once not +// be treated as the same or different dependencies. export interface ModuleDependencyRegistry<+TSplitCondition> { + /** + * Given an import qualifier, return a key used to register the dependency. + * Generally this return the `ImportQualifier.name` property, but in the case + * of `require.context` more attributes can be appended to distinguish various combinations that would otherwise conflict. + * + * For example, the following case would have collision issues if they all utilized the `name` property: + * ``` + * require('./foo'); + * require.context('./foo'); + * require.context('./foo', true, /something/); + * require.context('./foo', false, /something/); + * require.context('./foo', false, /something/, 'lazy'); + * ``` + * + * This method should be utilized by `registerDependency`. + */ + getKeyForDependency(qualifier: ImportQualifier): string; registerDependency( qualifier: ImportQualifier, ): InternalDependency; @@ -709,13 +726,36 @@ function createModuleNameLiteral(dependency: InternalDependency) { class DefaultModuleDependencyRegistry implements ModuleDependencyRegistry { + /** Default key resolver. */ + static getKeyForDependency(qualifier: ImportQualifier): string { + let key = qualifier.name; + + // Add extra qualifiers when using `require.context` to prevent collisions. + if (qualifier.contextParams) { + // NOTE(EvanBacon): Keep this synchronized with `RequireContextParams`, if any other properties are added + // then this key algorithm should be updated to account for those properties. + // Example: `./directory__true__/foobar/m__lazy` + key += [ + '', + String(qualifier.contextParams.recursive), + String(qualifier.contextParams.filter), + qualifier.contextParams.mode, + // Join together and append to the name: + ].join('__'); + } + return key; + } + _dependencies: Map> = new Map(); + getKeyForDependency = DefaultModuleDependencyRegistry.getKeyForDependency; + registerDependency( qualifier: ImportQualifier, ): InternalDependency { + const key = this.getKeyForDependency(qualifier); let dependency: ?InternalDependency = - this._dependencies.get(qualifier.name); + this._dependencies.get(key); if (dependency == null) { const newDependency: MutableInternalDependency = { @@ -733,12 +773,12 @@ class DefaultModuleDependencyRegistry } dependency = newDependency; - this._dependencies.set(qualifier.name, dependency); + this._dependencies.set(key, dependency); } else { const original = dependency; dependency = collapseDependencies(original, qualifier); if (original !== dependency) { - this._dependencies.set(qualifier.name, dependency); + this._dependencies.set(key, dependency); } } @@ -750,6 +790,9 @@ class DefaultModuleDependencyRegistry } } +collectDependencies.DefaultModuleDependencyRegistry = + DefaultModuleDependencyRegistry; + function collapseDependencies( dependency: InternalDependency, qualifier: ImportQualifier, From 40e1ac76db8d53730f12dc9b3bc148146ad7c8a4 Mon Sep 17 00:00:00 2001 From: evanbacon Date: Thu, 26 May 2022 11:55:46 -0500 Subject: [PATCH 16/28] Added more tests --- .../__tests__/collectDependencies-test.js | 162 ++++++++++++++---- .../ModuleGraph/worker/collectDependencies.js | 22 ++- 2 files changed, 145 insertions(+), 39 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index 03de381693..dbe14ee324 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -104,45 +104,145 @@ describe(DefaultModuleDependencyRegistry, () => { }); }); -it(`collects require context arguments`, () => { - const ast = astFromCode(` +describe(`require.context`, () => { + it(`collects require context arguments`, () => { + const ast = astFromCode(` const a = require.context('./', false, /foobar/m, 'eager'); const b = require.context('./baz'); `); - const {dependencies, dependencyMapName} = collectDependencies(ast, { - ...opts, - unstable_allowRequireContext: true, - }); + const {dependencies, dependencyMapName} = collectDependencies(ast, { + ...opts, + unstable_allowRequireContext: true, + }); - expect(dependencies).toEqual([ - { - name: './', - data: objectContaining({ - contextParams: { - filter: /foobar/m, - mode: 'eager', - recursive: false, - }, - }), - }, - { - name: './baz', - data: objectContaining({ - contextParams: { - filter: /^\.\/.*$/, - mode: 'sync', - recursive: true, - }, - }), - }, - ]); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: /foobar/m, + mode: 'eager', + recursive: false, + }, + }), + }, + { + name: './baz', + data: objectContaining({ + contextParams: { + filter: /^\.\/.*$/, + mode: 'sync', + recursive: true, + }, + }), + }, + ]); - expect(codeFromAst(ast)).toEqual( - comparableCode(` + expect(codeFromAst(ast)).toEqual( + comparableCode(` const a = require.context(${dependencyMapName}[0], "./"); const b = require.context(${dependencyMapName}[1], "./baz"); `), - ); + ); + }); + + it(`asserts invalid first argument`, () => { + const ast = astFromCode(` + const a = require.context(42); +`); + expect(() => + collectDependencies(ast, { + ...opts, + unstable_allowRequireContext: true, + }), + ).toThrowErrorMatchingInlineSnapshot(` + "Invalid call at line 2: 42 + First argument of \`require.context\` should be a string denoting the directory to require, instead found node of type: NumericLiteral." + `); + }); + it(`asserts invalid second argument`, () => { + const ast = astFromCode(` + const a = require.context('./dir', 'hey'); +`); + expect(() => + collectDependencies(ast, { + ...opts, + unstable_allowRequireContext: true, + }), + ).toThrowErrorMatchingInlineSnapshot(` + "Invalid call at line 2: 'hey' + Second argument of \`require.context\` should be an optional boolean indicating if files should be imported recursively or not, instead found node of type: StringLiteral." + `); + }); + it(`asserts invalid third argument`, () => { + const ast = astFromCode(` + const a = require.context('./dir', false, new RegExp('foobar')); +`); + expect(() => + collectDependencies(ast, { + ...opts, + unstable_allowRequireContext: true, + }), + ).toThrowErrorMatchingInlineSnapshot(` + "Invalid call at line 2: new RegExp('foobar') + Third argument of \`require.context\` should be an optional RegExp pattern matching all of the files to import, instead found node of type: NewExpression." + `); + }); + it(`asserts invalid fourth argument`, () => { + const ast = astFromCode(` + const a = require.context('./dir', false, /foobar/, 34); +`); + expect(() => + collectDependencies(ast, { + ...opts, + unstable_allowRequireContext: true, + }), + ).toThrowErrorMatchingInlineSnapshot(` + "Invalid call at line 2: 34 + Fourth argument of \`require.context\` should be an optional string \\"mode\\" denoting how the modules will be resolved, instead found node of type: NumericLiteral." + `); + }); + it(`asserts invalid fourth argument enum value`, () => { + const ast = astFromCode(` + const a = require.context('./dir', false, /foobar/, 'hello'); +`); + expect(() => + collectDependencies(ast, { + ...opts, + unstable_allowRequireContext: true, + }), + ).toThrowErrorMatchingInlineSnapshot(` + "Invalid call at line 2: 'hello' + require.context \\"hello\\" mode is not supported. Expected one of: sync, eager, lazy, lazy-once" + `); + }); + it(`asserts too many arguments`, () => { + const ast = astFromCode(` + const a = require.context('./dir', false, /foobar/, 'sync', 'hey'); +`); + expect(() => + collectDependencies(ast, { + ...opts, + unstable_allowRequireContext: true, + }), + ).toThrowErrorMatchingInlineSnapshot(` + "Invalid call at line 2: require.context('./dir', false, /foobar/, 'sync', 'hey') + Too many arguments provided to \`require.context\` call. Expected 4, got: 5" + `); + }); + it(`asserts no arguments`, () => { + const ast = astFromCode(` + const a = require.context(); +`); + expect(() => + collectDependencies(ast, { + ...opts, + unstable_allowRequireContext: true, + }), + ).toThrowErrorMatchingInlineSnapshot( + `"Invalid call at line 2: require.context()"`, + ); + }); }); it('collects unique dependency identifiers and transforms the AST', () => { diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 3d5cd8a928..1f359629c6 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -318,7 +318,7 @@ function getRequireContextArgs( const argNode = args[0].node; if (argNode.type !== 'StringLiteral') { throw new InvalidRequireCallError( - argNode, + args[0], `First argument of \`require.context\` should be a string denoting the directory to require, instead found node of type: ${argNode.type}.`, ); } @@ -331,7 +331,7 @@ function getRequireContextArgs( const argNode = args[1].node; if (argNode.type !== 'BooleanLiteral') { throw new InvalidRequireCallError( - argNode, + args[1], `Second argument of \`require.context\` should be an optional boolean indicating if files should be imported recursively or not, instead found node of type: ${argNode.type}.`, ); } @@ -345,7 +345,7 @@ function getRequireContextArgs( if (argNode.type !== 'RegExpLiteral') { // TODO: Handle `new RegExp(...)` -- `argNode.type === 'NewExpression'` throw new InvalidRequireCallError( - argNode, + args[2], `Third argument of \`require.context\` should be an optional RegExp pattern matching all of the files to import, instead found node of type: ${argNode.type}.`, ); } @@ -358,11 +358,11 @@ function getRequireContextArgs( const argNode = args[3].node; if (argNode.type !== 'StringLiteral') { throw new InvalidRequireCallError( - path, + args[3], `Fourth argument of \`require.context\` should be an optional string "mode" denoting how the modules will be resolved, instead found node of type: ${argNode.type}.`, ); } - mode = getContextMode(argNode, argNode.value); + mode = getContextMode(args[3], argNode.value); } if (args.length > 4) { @@ -397,7 +397,7 @@ function getContextMode( } throw new InvalidRequireCallError( path, - `require.context "${mode}" mode is not supported.`, + `require.context "${mode}" mode is not supported. Expected one of: sync, eager, lazy, lazy-once`, ); } @@ -594,14 +594,20 @@ function getModuleNameFromCallArgs(path: NodePath): ?string { return null; } + collectDependencies.getModuleNameFromCallArgs = getModuleNameFromCallArgs; class InvalidRequireCallError extends Error { - constructor({node}: any) { + constructor({node}: any, message?: string) { const line = node.loc && node.loc.start && node.loc.start.line; super( - `Invalid call at line ${line || ''}: ${generate(node).code}`, + [ + `Invalid call at line ${line || ''}: ${generate(node).code}`, + message, + ] + .filter(Boolean) + .join('\n'), ); } } From e1cbcc39c61704c1232a89c3de8a8c54e9f781ce Mon Sep 17 00:00:00 2001 From: Evan Bacon Date: Thu, 26 May 2022 11:56:12 -0500 Subject: [PATCH 17/28] Update packages/metro/src/ModuleGraph/worker/collectDependencies.js Co-authored-by: Moti Zilberman --- packages/metro/src/ModuleGraph/worker/collectDependencies.js | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 1f359629c6..e0b45091ca 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -37,6 +37,7 @@ export type Dependency = $ReadOnly<{ name: string, }>; +// TODO: Convert to a Flow enum type ContextMode = 'sync' | 'eager' | 'lazy' | 'lazy-once'; type RequireContextParams = $ReadOnly<{ From cc37131f61dcd0879aec6f2ab9af1483f7209206 Mon Sep 17 00:00:00 2001 From: evanbacon Date: Thu, 26 May 2022 11:56:30 -0500 Subject: [PATCH 18/28] Update collectDependencies.js --- .../metro/src/ModuleGraph/worker/collectDependencies.js | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index e0b45091ca..5e2426f7d5 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -388,11 +388,10 @@ function getContextMode( mode: string, ): ContextMode { if ( - typeof mode === 'string' && - (mode === 'sync' || - mode === 'eager' || - mode === 'lazy' || - mode === 'lazy-once') + mode === 'sync' || + mode === 'eager' || + mode === 'lazy' || + mode === 'lazy-once' ) { return mode; } From c5a39607e83efdea4b1557494a6a958d4c2b038e Mon Sep 17 00:00:00 2001 From: evanbacon Date: Thu, 26 May 2022 12:04:41 -0500 Subject: [PATCH 19/28] Update collectDependencies.js --- packages/metro/src/ModuleGraph/worker/collectDependencies.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 5e2426f7d5..7508e6bb01 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -336,7 +336,7 @@ function getRequireContextArgs( `Second argument of \`require.context\` should be an optional boolean indicating if files should be imported recursively or not, instead found node of type: ${argNode.type}.`, ); } - recursive = args[1].node.value; + recursive = argNode.value; } // Default to all files. From c49f6877ddac3063d497b862bdb420b008356b6b Mon Sep 17 00:00:00 2001 From: evanbacon Date: Fri, 27 May 2022 19:20:58 -0500 Subject: [PATCH 20/28] PR feedback --- .../__tests__/collectDependencies-test.js | 17 +++++++++++--- .../ModuleGraph/worker/collectDependencies.js | 23 ++++++++----------- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index dbe14ee324..a262b37d04 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -46,23 +46,30 @@ const opts = { describe(DefaultModuleDependencyRegistry, () => { describe('getKeyForDependency', () => { it(`generates basic key`, () => { + const registry = new DefaultModuleDependencyRegistry(); expect( - DefaultModuleDependencyRegistry.getKeyForDependency({ + registry.getKeyForDependency({ name: './file.js', + optional: false, + asyncType: null, }), ).toBe('./file.js'); }); it(`generates require.context key`, () => { + const registry = new DefaultModuleDependencyRegistry(); + expect( - DefaultModuleDependencyRegistry.getKeyForDependency({ + registry.getKeyForDependency({ name: './dir', + optional: false, + asyncType: null, contextParams: { recursive: true, filter: /foobar/, mode: 'lazy', }, }), - ).toBe('./dir__true__/foobar/__lazy'); + ).toBe('./dir__context__true__/foobar/__lazy'); }); }); @@ -71,10 +78,14 @@ describe(DefaultModuleDependencyRegistry, () => { registry.registerDependency({ name: './dir', + optional: false, + asyncType: null, }); registry.registerDependency({ name: './dir', + optional: false, + asyncType: null, contextParams: { recursive: true, filter: /foobar/, diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 7508e6bb01..053b258378 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -383,10 +383,7 @@ function getRequireContextArgs( ]; } -function getContextMode( - path: NodePath, - mode: string, -): ContextMode { +function getContextMode(path: NodePath, mode: string): ContextMode { if ( mode === 'sync' || mode === 'eager' || @@ -732,30 +729,30 @@ function createModuleNameLiteral(dependency: InternalDependency) { class DefaultModuleDependencyRegistry implements ModuleDependencyRegistry { + _dependencies: Map> = new Map(); + /** Default key resolver. */ - static getKeyForDependency(qualifier: ImportQualifier): string { + getKeyForDependency(qualifier: ImportQualifier): string { let key = qualifier.name; + const {contextParams} = qualifier; // Add extra qualifiers when using `require.context` to prevent collisions. - if (qualifier.contextParams) { + if (contextParams) { // NOTE(EvanBacon): Keep this synchronized with `RequireContextParams`, if any other properties are added // then this key algorithm should be updated to account for those properties. // Example: `./directory__true__/foobar/m__lazy` key += [ '', - String(qualifier.contextParams.recursive), - String(qualifier.contextParams.filter), - qualifier.contextParams.mode, + 'context', + String(contextParams.recursive), + String(contextParams.filter), + contextParams.mode, // Join together and append to the name: ].join('__'); } return key; } - _dependencies: Map> = new Map(); - - getKeyForDependency = DefaultModuleDependencyRegistry.getKeyForDependency; - registerDependency( qualifier: ImportQualifier, ): InternalDependency { From 039ae9f2e62ec26d88cc2601416d7ad6ab0149a2 Mon Sep 17 00:00:00 2001 From: evanbacon Date: Fri, 27 May 2022 19:21:23 -0500 Subject: [PATCH 21/28] Update collectDependencies-test.js --- .../ModuleGraph/worker/__tests__/collectDependencies-test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index a262b37d04..da0cb648bf 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -43,7 +43,7 @@ const opts = { dependencyMapName: null, }; -describe(DefaultModuleDependencyRegistry, () => { +describe('DefaultModuleDependencyRegistry', () => { describe('getKeyForDependency', () => { it(`generates basic key`, () => { const registry = new DefaultModuleDependencyRegistry(); From 7c19f6e244611b114b6aa72e1ef996ac4e9f5acd Mon Sep 17 00:00:00 2001 From: evanbacon Date: Tue, 14 Jun 2022 10:23:38 +0200 Subject: [PATCH 22/28] drop tests - use serialized regex object - fix types --- .../src/__tests__/index-test.js | 1 + packages/metro-transform-worker/src/index.js | 1 + packages/metro/src/DeltaBundler/types.flow.js | 16 +++ .../__tests__/collectDependencies-test.js | 103 +++++------------- .../ModuleGraph/worker/collectDependencies.js | 93 ++++++++-------- 5 files changed, 89 insertions(+), 125 deletions(-) diff --git a/packages/metro-transform-worker/src/__tests__/index-test.js b/packages/metro-transform-worker/src/__tests__/index-test.js index 0c2f357968..dc1997bb79 100644 --- a/packages/metro-transform-worker/src/__tests__/index-test.js +++ b/packages/metro-transform-worker/src/__tests__/index-test.js @@ -65,6 +65,7 @@ const baseConfig: JsTransformerConfig = { unstable_compactOutput: false, unstable_disableModuleWrapping: false, unstable_disableNormalizePseudoGlobals: false, + unstable_allowRequireContext: false, }; beforeEach(() => { diff --git a/packages/metro-transform-worker/src/index.js b/packages/metro-transform-worker/src/index.js index e65dd4167e..0aa5a3034f 100644 --- a/packages/metro-transform-worker/src/index.js +++ b/packages/metro-transform-worker/src/index.js @@ -398,6 +398,7 @@ async function transformJS( keepRequireNames: options.dev, allowOptionalDependencies: config.allowOptionalDependencies, dependencyMapName: config.unstable_dependencyMapReservedName, + unstable_allowRequireContext: config.unstable_allowRequireContext, }; // $FlowFixMe[unsupported-syntax] dynamic require const collectDependencies: CollectDependenciesFn = require(config.unstable_collectDependenciesPath); diff --git a/packages/metro/src/DeltaBundler/types.flow.js b/packages/metro/src/DeltaBundler/types.flow.js index ac7dbf4b43..be67eba2c2 100644 --- a/packages/metro/src/DeltaBundler/types.flow.js +++ b/packages/metro/src/DeltaBundler/types.flow.js @@ -18,6 +18,19 @@ export type MixedOutput = { +type: string, }; +// TODO: Convert to a Flow enum +export type ContextMode = 'sync' | 'eager' | 'lazy' | 'lazy-once'; + +/** Context for requiring a collection of modules. */ +export type RequireContextParams = $ReadOnly<{ + /* Should search for files recursively. Optional, default `true` when `require.context` is used */ + recursive: boolean, + /* Filename filter pattern for use in `require.context`. Optional, default `/^\.\/.*$/` (any file) when `require.context` is used */ + filter: {pattern: string, flags?: string}, + /** Mode for resolving dynamic dependencies. Defaults to `sync` */ + mode: ContextMode, +}>; + export type AsyncDependencyType = 'async' | 'prefetch'; export type TransformResultDependency = { @@ -48,6 +61,9 @@ export type TransformResultDependency = { +isOptional?: boolean, +locs: $ReadOnlyArray, + + /** Context for requiring a collection of modules. */ + +contextParams?: RequireContextParams, }, }; diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index da0cb648bf..fcb9ee6a9f 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -32,8 +32,7 @@ const nullthrows = require('nullthrows'); const {any, objectContaining} = expect; -const {InvalidRequireCallError, DefaultModuleDependencyRegistry} = - collectDependencies; +const {InvalidRequireCallError} = collectDependencies; const opts = { asyncRequireModulePath: 'asyncRequire', dynamicRequires: 'reject', @@ -41,85 +40,16 @@ const opts = { keepRequireNames: true, allowOptionalDependencies: false, dependencyMapName: null, + unstable_allowRequireContext: true, }; -describe('DefaultModuleDependencyRegistry', () => { - describe('getKeyForDependency', () => { - it(`generates basic key`, () => { - const registry = new DefaultModuleDependencyRegistry(); - expect( - registry.getKeyForDependency({ - name: './file.js', - optional: false, - asyncType: null, - }), - ).toBe('./file.js'); - }); - it(`generates require.context key`, () => { - const registry = new DefaultModuleDependencyRegistry(); - - expect( - registry.getKeyForDependency({ - name: './dir', - optional: false, - asyncType: null, - contextParams: { - recursive: true, - filter: /foobar/, - mode: 'lazy', - }, - }), - ).toBe('./dir__context__true__/foobar/__lazy'); - }); - }); - - it(`registers dependencies without collision`, () => { - const registry = new DefaultModuleDependencyRegistry(); - - registry.registerDependency({ - name: './dir', - optional: false, - asyncType: null, - }); - - registry.registerDependency({ - name: './dir', - optional: false, - asyncType: null, - contextParams: { - recursive: true, - filter: /foobar/, - mode: 'lazy', - }, - }); - - expect(registry.getDependencies()).toEqual([ - { - asyncType: undefined, - index: 0, - locs: [], - name: './dir', - }, - { - asyncType: undefined, - contextParams: { - filter: /foobar/, - mode: 'lazy', - recursive: true, - }, - index: 1, - locs: [], - name: './dir', - }, - ]); - }); -}); - describe(`require.context`, () => { it(`collects require context arguments`, () => { const ast = astFromCode(` const a = require.context('./', false, /foobar/m, 'eager'); const b = require.context('./baz'); + const c = require.context('./dir', true); + const d = require.context('./dir'); `); const {dependencies, dependencyMapName} = collectDependencies(ast, { ...opts, @@ -131,7 +61,10 @@ describe(`require.context`, () => { name: './', data: objectContaining({ contextParams: { - filter: /foobar/m, + filter: { + pattern: 'foobar', + flags: 'm', + }, mode: 'eager', recursive: false, }, @@ -141,7 +74,21 @@ describe(`require.context`, () => { name: './baz', data: objectContaining({ contextParams: { - filter: /^\.\/.*$/, + filter: { + pattern: '.*', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './dir', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + }, mode: 'sync', recursive: true, }, @@ -153,6 +100,8 @@ describe(`require.context`, () => { comparableCode(` const a = require.context(${dependencyMapName}[0], "./"); const b = require.context(${dependencyMapName}[1], "./baz"); + const c = require.context(${dependencyMapName}[2], "./dir"); + const d = require.context(${dependencyMapName}[2], "./dir"); `), ); }); @@ -533,6 +482,7 @@ describe('Evaluating static arguments', () => { keepRequireNames: true, allowOptionalDependencies: false, dependencyMapName: null, + unstable_allowRequireContext: false, }; const {dependencies} = collectDependencies(ast, opts); expect(dependencies).toEqual([]); @@ -694,6 +644,7 @@ describe('optional dependencies', () => { keepRequireNames: true, allowOptionalDependencies: true, dependencyMapName: null, + unstable_allowRequireContext: false, }; const validateDependencies = (dependencies, expectedCount) => { let hasAsync = false; diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 053b258378..878ee48d2b 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -43,8 +43,8 @@ type ContextMode = 'sync' | 'eager' | 'lazy' | 'lazy-once'; type RequireContextParams = $ReadOnly<{ /* Should search for files recursively. Optional, default `true` when `require.context` is used */ recursive: boolean, - /* Filename filter pattern for use in `require.context`. Optional, default `/^\.\/.*$/` (any file) when `require.context` is used */ - filter: RegExp, + /* Filename filter pattern for use in `require.context`. Optional, default `.*` (any file) when `require.context` is used */ + filter: {pattern: string, flags?: string}, /** Mode for resolving dynamic dependencies. Defaults to `sync` */ mode: ContextMode, }>; @@ -57,6 +57,7 @@ type DependencyData = $ReadOnly<{ // If left unspecified, then the dependency is unconditionally split. splitCondition?: TSplitCondition, locs: Array, + /** Context for requiring a collection of modules. */ contextParams?: RequireContextParams, }>; @@ -107,23 +108,6 @@ export type CollectedDependencies<+TSplitCondition> = $ReadOnly<{ // E.g. should a module that's once required optionally and once not // be treated as the same or different dependencies. export interface ModuleDependencyRegistry<+TSplitCondition> { - /** - * Given an import qualifier, return a key used to register the dependency. - * Generally this return the `ImportQualifier.name` property, but in the case - * of `require.context` more attributes can be appended to distinguish various combinations that would otherwise conflict. - * - * For example, the following case would have collision issues if they all utilized the `name` property: - * ``` - * require('./foo'); - * require.context('./foo'); - * require.context('./foo', true, /something/); - * require.context('./foo', false, /something/); - * require.context('./foo', false, /something/, 'lazy'); - * ``` - * - * This method should be utilized by `registerDependency`. - */ - getKeyForDependency(qualifier: ImportQualifier): string; registerDependency( qualifier: ImportQualifier, ): InternalDependency; @@ -340,7 +324,7 @@ function getRequireContextArgs( } // Default to all files. - let filter = /^\.\/.*$/; + let filter = {pattern: '.*'}; if (args.length > 2) { const argNode = args[2].node; if (argNode.type !== 'RegExpLiteral') { @@ -350,7 +334,7 @@ function getRequireContextArgs( `Third argument of \`require.context\` should be an optional RegExp pattern matching all of the files to import, instead found node of type: ${argNode.type}.`, ); } - filter = new RegExp(argNode.pattern, argNode.flags); + filter = {pattern: argNode.pattern, flags: argNode.flags}; } // Default to `sync`. @@ -398,8 +382,6 @@ function getContextMode(path: NodePath, mode: string): ContextMode { ); } -collectDependencies.getRequireContextArgs = getRequireContextArgs; - function processRequireContextCall( path: NodePath, state: State, @@ -726,37 +708,53 @@ function createModuleNameLiteral(dependency: InternalDependency) { return types.stringLiteral(dependency.name); } +/** + * Given an import qualifier, return a key used to register the dependency. + * Generally this return the `ImportQualifier.name` property, but in the case + * of `require.context` more attributes can be appended to distinguish various combinations that would otherwise conflict. + * + * For example, the following case would have collision issues if they all utilized the `name` property: + * ``` + * require('./foo'); + * require.context('./foo'); + * require.context('./foo', true, /something/); + * require.context('./foo', false, /something/); + * require.context('./foo', false, /something/, 'lazy'); + * ``` + * + * This method should be utilized by `registerDependency`. + */ +function getKeyForDependency(qualifier: ImportQualifier): string { + let key = qualifier.name; + + const {contextParams} = qualifier; + // Add extra qualifiers when using `require.context` to prevent collisions. + if (contextParams) { + // NOTE(EvanBacon): Keep this synchronized with `RequireContextParams`, if any other properties are added + // then this key algorithm should be updated to account for those properties. + // Example: `./directory__true__/foobar/m__lazy` + key += [ + '', + 'context', + String(contextParams.recursive), + String(contextParams.filter.pattern), + String(contextParams.filter.flags), + contextParams.mode, + // Join together and append to the name: + ].join('__'); + } + return key; +} + class DefaultModuleDependencyRegistry implements ModuleDependencyRegistry { _dependencies: Map> = new Map(); - /** Default key resolver. */ - getKeyForDependency(qualifier: ImportQualifier): string { - let key = qualifier.name; - - const {contextParams} = qualifier; - // Add extra qualifiers when using `require.context` to prevent collisions. - if (contextParams) { - // NOTE(EvanBacon): Keep this synchronized with `RequireContextParams`, if any other properties are added - // then this key algorithm should be updated to account for those properties. - // Example: `./directory__true__/foobar/m__lazy` - key += [ - '', - 'context', - String(contextParams.recursive), - String(contextParams.filter), - contextParams.mode, - // Join together and append to the name: - ].join('__'); - } - return key; - } - registerDependency( qualifier: ImportQualifier, ): InternalDependency { - const key = this.getKeyForDependency(qualifier); + const key = getKeyForDependency(qualifier); let dependency: ?InternalDependency = this._dependencies.get(key); @@ -793,9 +791,6 @@ class DefaultModuleDependencyRegistry } } -collectDependencies.DefaultModuleDependencyRegistry = - DefaultModuleDependencyRegistry; - function collapseDependencies( dependency: InternalDependency, qualifier: ImportQualifier, From 08a2b888c9c0273703362264ddd22acd07873701 Mon Sep 17 00:00:00 2001 From: evanbacon Date: Tue, 14 Jun 2022 11:00:33 +0200 Subject: [PATCH 23/28] update snapshots --- .../src/__tests__/__snapshots__/loadConfig-test.js.snap | 4 ++++ packages/metro-transform-worker/src/__tests__/index-test.js | 1 + 2 files changed, 5 insertions(+) diff --git a/packages/metro-config/src/__tests__/__snapshots__/loadConfig-test.js.snap b/packages/metro-config/src/__tests__/__snapshots__/loadConfig-test.js.snap index a5773cfe52..f43f282a5e 100644 --- a/packages/metro-config/src/__tests__/__snapshots__/loadConfig-test.js.snap +++ b/packages/metro-config/src/__tests__/__snapshots__/loadConfig-test.js.snap @@ -131,6 +131,7 @@ Object { "transformVariants": Object { "default": Object {}, }, + "unstable_allowRequireContext": false, "unstable_collectDependenciesPath": "metro/src/ModuleGraph/worker/collectDependencies.js", "unstable_compactOutput": false, "unstable_dependencyMapReservedName": null, @@ -276,6 +277,7 @@ Object { "transformVariants": Object { "default": Object {}, }, + "unstable_allowRequireContext": false, "unstable_collectDependenciesPath": "metro/src/ModuleGraph/worker/collectDependencies.js", "unstable_compactOutput": false, "unstable_dependencyMapReservedName": null, @@ -421,6 +423,7 @@ Object { "transformVariants": Object { "default": Object {}, }, + "unstable_allowRequireContext": false, "unstable_collectDependenciesPath": "metro/src/ModuleGraph/worker/collectDependencies.js", "unstable_compactOutput": false, "unstable_dependencyMapReservedName": null, @@ -566,6 +569,7 @@ Object { "transformVariants": Object { "default": Object {}, }, + "unstable_allowRequireContext": false, "unstable_collectDependenciesPath": "metro/src/ModuleGraph/worker/collectDependencies.js", "unstable_compactOutput": false, "unstable_dependencyMapReservedName": null, diff --git a/packages/metro-transform-worker/src/__tests__/index-test.js b/packages/metro-transform-worker/src/__tests__/index-test.js index dc1997bb79..ab6e3e22a4 100644 --- a/packages/metro-transform-worker/src/__tests__/index-test.js +++ b/packages/metro-transform-worker/src/__tests__/index-test.js @@ -538,6 +538,7 @@ it('allows replacing the collectDependencies implementation', async () => { dynamicRequires: 'reject', inlineableCalls: ['_$$_IMPORT_DEFAULT', '_$$_IMPORT_ALL'], keepRequireNames: options.dev, + unstable_allowRequireContext: false, dependencyMapName: null, }, ); From eb2ebe18794467384fb6ce162cfdb7148d3f628c Mon Sep 17 00:00:00 2001 From: evanbacon Date: Tue, 14 Jun 2022 18:19:41 +0200 Subject: [PATCH 24/28] update types --- packages/metro/src/DeltaBundler/types.flow.js | 14 +------------- .../worker/__tests__/collectDependencies-test.js | 2 ++ .../src/ModuleGraph/worker/collectDependencies.js | 10 ++++++---- 3 files changed, 9 insertions(+), 17 deletions(-) diff --git a/packages/metro/src/DeltaBundler/types.flow.js b/packages/metro/src/DeltaBundler/types.flow.js index be67eba2c2..30b467ab65 100644 --- a/packages/metro/src/DeltaBundler/types.flow.js +++ b/packages/metro/src/DeltaBundler/types.flow.js @@ -11,6 +11,7 @@ 'use strict'; import type {PrivateState} from './graphOperations'; +import type {RequireContextParams} from '../ModuleGraph/worker/collectDependencies'; import type {JsTransformOptions} from 'metro-transform-worker'; export type MixedOutput = { @@ -18,19 +19,6 @@ export type MixedOutput = { +type: string, }; -// TODO: Convert to a Flow enum -export type ContextMode = 'sync' | 'eager' | 'lazy' | 'lazy-once'; - -/** Context for requiring a collection of modules. */ -export type RequireContextParams = $ReadOnly<{ - /* Should search for files recursively. Optional, default `true` when `require.context` is used */ - recursive: boolean, - /* Filename filter pattern for use in `require.context`. Optional, default `/^\.\/.*$/` (any file) when `require.context` is used */ - filter: {pattern: string, flags?: string}, - /** Mode for resolving dynamic dependencies. Defaults to `sync` */ - mode: ContextMode, -}>; - export type AsyncDependencyType = 'async' | 'prefetch'; export type TransformResultDependency = { diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index fcb9ee6a9f..8276bab978 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -76,6 +76,7 @@ describe(`require.context`, () => { contextParams: { filter: { pattern: '.*', + flags: '', }, mode: 'sync', recursive: true, @@ -88,6 +89,7 @@ describe(`require.context`, () => { contextParams: { filter: { pattern: '.*', + flags: '', }, mode: 'sync', recursive: true, diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 878ee48d2b..15bd7df06d 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -40,11 +40,13 @@ export type Dependency = $ReadOnly<{ // TODO: Convert to a Flow enum type ContextMode = 'sync' | 'eager' | 'lazy' | 'lazy-once'; -type RequireContextParams = $ReadOnly<{ +type ContextFilter = {pattern: string, flags: string}; + +export type RequireContextParams = $ReadOnly<{ /* Should search for files recursively. Optional, default `true` when `require.context` is used */ recursive: boolean, /* Filename filter pattern for use in `require.context`. Optional, default `.*` (any file) when `require.context` is used */ - filter: {pattern: string, flags?: string}, + filter: $ReadOnly, /** Mode for resolving dynamic dependencies. Defaults to `sync` */ mode: ContextMode, }>; @@ -324,7 +326,7 @@ function getRequireContextArgs( } // Default to all files. - let filter = {pattern: '.*'}; + let filter: ContextFilter = {pattern: '.*', flags: ''}; if (args.length > 2) { const argNode = args[2].node; if (argNode.type !== 'RegExpLiteral') { @@ -334,7 +336,7 @@ function getRequireContextArgs( `Third argument of \`require.context\` should be an optional RegExp pattern matching all of the files to import, instead found node of type: ${argNode.type}.`, ); } - filter = {pattern: argNode.pattern, flags: argNode.flags}; + filter = {pattern: argNode.pattern, flags: argNode.flags || ''}; } // Default to `sync`. From fc9f8112ddee68bf1d1491c8cc2235710dcd6d80 Mon Sep 17 00:00:00 2001 From: Moti Zilberman Date: Wed, 15 Jun 2022 01:03:19 +0100 Subject: [PATCH 25/28] fix: emit require calls --- packages/metro/src/ModuleGraph/worker/collectDependencies.js | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 15bd7df06d..96fa2b0eea 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -404,6 +404,7 @@ function processRequireContextCall( ); // require() the generated module representing this context + path.get('callee').replaceWith(types.identifier('require')); transformer.transformSyncRequire(path, dep, state); } From a6bfc827c0c1d61c877ffc16340e38f25e888ac2 Mon Sep 17 00:00:00 2001 From: Moti Zilberman Date: Wed, 15 Jun 2022 01:04:23 +0100 Subject: [PATCH 26/28] test: improve test coverage --- .../__tests__/collectDependencies-test.js | 584 ++++++++++++++++-- 1 file changed, 524 insertions(+), 60 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index 8276bab978..324c459c2b 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -40,38 +40,334 @@ const opts = { keepRequireNames: true, allowOptionalDependencies: false, dependencyMapName: null, - unstable_allowRequireContext: true, + unstable_allowRequireContext: false, }; describe(`require.context`, () => { - it(`collects require context arguments`, () => { + const optsWithoutContext = {...opts, unstable_allowRequireContext: false}; + const optsWithContext = {...opts, unstable_allowRequireContext: true}; + + it('does not extract/transform if feature is disabled', () => { + // TODO: Should this error/warn? const ast = astFromCode(` - const a = require.context('./', false, /foobar/m, 'eager'); - const b = require.context('./baz'); - const c = require.context('./dir', true); - const d = require.context('./dir'); -`); - const {dependencies, dependencyMapName} = collectDependencies(ast, { - ...opts, - unstable_allowRequireContext: true, - }); + require.context('./', false, /foobar/m, 'eager'); + `); + const {dependencies} = collectDependencies(ast, optsWithoutContext); + expect(dependencies).toEqual([]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + require.context('./', false, /foobar/m, 'eager'); + `), + ); + }); + it('can omit 2nd-4th arguments', () => { + const ast = astFromCode(` + const a = require.context('./'); + const b = require.context('./', false); + const c = require.context('./', true, /custom/i); + const d = require.context('./', true, /.*/, 'eager') + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); expect(dependencies).toEqual([ { name: './', data: objectContaining({ contextParams: { filter: { - pattern: 'foobar', - flags: 'm', + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: false, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'custom', + flags: 'i', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', }, mode: 'eager', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const c = require(${dependencyMapName}[2], "./"); + const d = require(${dependencyMapName}[3], "./"); + `), + ); + }); + + it.skip('can pass undefined for 2nd-4th arguments', () => { + // TODO(moti): fix meta-evaluation of undefined + const ast = astFromCode(` + const a = require.context('./', undefined, undefined, undefined); + const b = require.context('./', false, undefined, undefined); + const c = require.context('./', undefined, /custom/i, undefined); + const d = require.context('./', undefined, undefined, 'eager'); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', recursive: false, }, }), }, { - name: './baz', + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'custom', + flags: 'i', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'eager', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const c = require(${dependencyMapName}[2], "./"); + const d = require(${dependencyMapName}[3], "./"); + `), + ); + }); + + it('distinguishes require from require.context', () => { + const ast = astFromCode(` + const a = require.context('./'); + const anotherA = require.context('./'); + const b = require('./'); + const anotherB = require('./'); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: expect.not.objectContaining({ + contextParams: expect.anything(), + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const anotherA = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + + it('distinguishes require.context based on path', () => { + const ast = astFromCode(` + const a = require.context('./a/'); + const anotherA = require.context('./a/'); + const b = require.context('./b/'); + const anotherB = require.context('./b/'); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './a/', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './b/', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./a/"); + const anotherA = require(${dependencyMapName}[0], "./a/"); + const b = require(${dependencyMapName}[1], "./b/"); + const anotherB = require(${dependencyMapName}[1], "./b/"); + `), + ); + }); + + it('distinguishes require.context based on trailing slash in path', () => { + // TODO: Can/should we merge these two? + const ast = astFromCode(` + const a = require.context('.'); + const anotherA = require.context('.'); + const b = require.context('./'); + const anotherB = require.context('./'); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: '.', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "."); + const anotherA = require(${dependencyMapName}[0], "."); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + + it('distinguishes between backslash and slash in path', () => { + // TODO: Can/should we merge these two? + const ast = astFromCode(` + const a = require.context('.\\\\'); + const anotherA = require.context('.\\\\'); + const b = require.context('./'); + const anotherB = require.context('./'); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: '.\\', data: objectContaining({ contextParams: { filter: { @@ -84,7 +380,7 @@ describe(`require.context`, () => { }), }, { - name: './dir', + name: './', data: objectContaining({ contextParams: { filter: { @@ -97,14 +393,209 @@ describe(`require.context`, () => { }), }, ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], ".\\\\"); + const anotherA = require(${dependencyMapName}[0], ".\\\\"); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + it('distinguishes require.context based on `recursive`', () => { + const ast = astFromCode(` + const a = require.context('./', true); + const anotherA = require.context('./'); + const b = require.context('./', false); + const anotherB = require.context('./', false); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: false, + }, + }), + }, + ]); expect(codeFromAst(ast)).toEqual( comparableCode(` - const a = require.context(${dependencyMapName}[0], "./"); - const b = require.context(${dependencyMapName}[1], "./baz"); - const c = require.context(${dependencyMapName}[2], "./dir"); - const d = require.context(${dependencyMapName}[2], "./dir"); - `), + const a = require(${dependencyMapName}[0], "./"); + const anotherA = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + + it('distinguishes require.context based on filter pattern', () => { + const ast = astFromCode(` + const a = require.context('./', true, /foo/); + const anotherA = require.context('./', true, /foo/); + const b = require.context('./', true, /.*/); + const anotherB = require.context('./', true); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'foo', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const anotherA = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + + it('distinguishes require.context based on filter flags', () => { + const ast = astFromCode(` + const a = require.context('./', true, /foo/m); + const anotherA = require.context('./', true, /foo/m); + const b = require.context('./', true, /foo/); + const anotherB = require.context('./', true, /foo/); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'foo', + flags: 'm', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'foo', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const anotherA = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), + ); + }); + + it('distinguishes require.context based on mode', () => { + const ast = astFromCode(` + const a = require.context('./', true, /.*/, 'sync'); + const anotherA = require.context('./', true, /.*/); + const b = require.context('./', true, /.*/, 'eager'); + const anotherB = require.context('./', true, /.*/, 'eager'); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'sync', + recursive: true, + }, + }), + }, + { + name: './', + data: objectContaining({ + contextParams: { + filter: { + pattern: '.*', + flags: '', + }, + mode: 'eager', + recursive: true, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const a = require(${dependencyMapName}[0], "./"); + const anotherA = require(${dependencyMapName}[0], "./"); + const b = require(${dependencyMapName}[1], "./"); + const anotherB = require(${dependencyMapName}[1], "./"); + `), ); }); @@ -112,12 +603,8 @@ describe(`require.context`, () => { const ast = astFromCode(` const a = require.context(42); `); - expect(() => - collectDependencies(ast, { - ...opts, - unstable_allowRequireContext: true, - }), - ).toThrowErrorMatchingInlineSnapshot(` + expect(() => collectDependencies(ast, optsWithContext)) + .toThrowErrorMatchingInlineSnapshot(` "Invalid call at line 2: 42 First argument of \`require.context\` should be a string denoting the directory to require, instead found node of type: NumericLiteral." `); @@ -126,12 +613,8 @@ describe(`require.context`, () => { const ast = astFromCode(` const a = require.context('./dir', 'hey'); `); - expect(() => - collectDependencies(ast, { - ...opts, - unstable_allowRequireContext: true, - }), - ).toThrowErrorMatchingInlineSnapshot(` + expect(() => collectDependencies(ast, optsWithContext)) + .toThrowErrorMatchingInlineSnapshot(` "Invalid call at line 2: 'hey' Second argument of \`require.context\` should be an optional boolean indicating if files should be imported recursively or not, instead found node of type: StringLiteral." `); @@ -140,12 +623,8 @@ describe(`require.context`, () => { const ast = astFromCode(` const a = require.context('./dir', false, new RegExp('foobar')); `); - expect(() => - collectDependencies(ast, { - ...opts, - unstable_allowRequireContext: true, - }), - ).toThrowErrorMatchingInlineSnapshot(` + expect(() => collectDependencies(ast, optsWithContext)) + .toThrowErrorMatchingInlineSnapshot(` "Invalid call at line 2: new RegExp('foobar') Third argument of \`require.context\` should be an optional RegExp pattern matching all of the files to import, instead found node of type: NewExpression." `); @@ -154,12 +633,8 @@ describe(`require.context`, () => { const ast = astFromCode(` const a = require.context('./dir', false, /foobar/, 34); `); - expect(() => - collectDependencies(ast, { - ...opts, - unstable_allowRequireContext: true, - }), - ).toThrowErrorMatchingInlineSnapshot(` + expect(() => collectDependencies(ast, optsWithContext)) + .toThrowErrorMatchingInlineSnapshot(` "Invalid call at line 2: 34 Fourth argument of \`require.context\` should be an optional string \\"mode\\" denoting how the modules will be resolved, instead found node of type: NumericLiteral." `); @@ -168,12 +643,8 @@ describe(`require.context`, () => { const ast = astFromCode(` const a = require.context('./dir', false, /foobar/, 'hello'); `); - expect(() => - collectDependencies(ast, { - ...opts, - unstable_allowRequireContext: true, - }), - ).toThrowErrorMatchingInlineSnapshot(` + expect(() => collectDependencies(ast, optsWithContext)) + .toThrowErrorMatchingInlineSnapshot(` "Invalid call at line 2: 'hello' require.context \\"hello\\" mode is not supported. Expected one of: sync, eager, lazy, lazy-once" `); @@ -182,12 +653,8 @@ describe(`require.context`, () => { const ast = astFromCode(` const a = require.context('./dir', false, /foobar/, 'sync', 'hey'); `); - expect(() => - collectDependencies(ast, { - ...opts, - unstable_allowRequireContext: true, - }), - ).toThrowErrorMatchingInlineSnapshot(` + expect(() => collectDependencies(ast, optsWithContext)) + .toThrowErrorMatchingInlineSnapshot(` "Invalid call at line 2: require.context('./dir', false, /foobar/, 'sync', 'hey') Too many arguments provided to \`require.context\` call. Expected 4, got: 5" `); @@ -197,10 +664,7 @@ describe(`require.context`, () => { const a = require.context(); `); expect(() => - collectDependencies(ast, { - ...opts, - unstable_allowRequireContext: true, - }), + collectDependencies(ast, optsWithContext), ).toThrowErrorMatchingInlineSnapshot( `"Invalid call at line 2: require.context()"`, ); From 0f90088836098caca9724b9499a774bfedc4c968 Mon Sep 17 00:00:00 2001 From: Moti Zilberman Date: Wed, 15 Jun 2022 01:30:02 +0100 Subject: [PATCH 27/28] fix: support undefined args and some more exprs --- .../__tests__/collectDependencies-test.js | 84 +++++++++++++++++-- .../ModuleGraph/worker/collectDependencies.js | 44 ++++++---- 2 files changed, 106 insertions(+), 22 deletions(-) diff --git a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js index 324c459c2b..4c72df8315 100644 --- a/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js +++ b/packages/metro/src/ModuleGraph/worker/__tests__/collectDependencies-test.js @@ -136,8 +136,7 @@ describe(`require.context`, () => { ); }); - it.skip('can pass undefined for 2nd-4th arguments', () => { - // TODO(moti): fix meta-evaluation of undefined + it('can pass undefined for 2nd-4th arguments', () => { const ast = astFromCode(` const a = require.context('./', undefined, undefined, undefined); const b = require.context('./', false, undefined, undefined); @@ -212,6 +211,81 @@ describe(`require.context`, () => { ); }); + it('can understand constant assignments', () => { + const ast = astFromCode(` + const DOT_SLASH_FOO = './foo'; + const FALSE = false; + const EAGER = 'eager'; + const a = require.context(DOT_SLASH_FOO, FALSE, /pattern/, EAGER); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './foo', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'pattern', + flags: '', + }, + mode: 'eager', + recursive: false, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const DOT_SLASH_FOO = './foo'; + const FALSE = false; + const EAGER = 'eager'; + const a = require(${dependencyMapName}[0], "./foo"); + `), + ); + }); + + it.skip('can understand regex constant assignments', () => { + // TODO: augment Babel's path.evaluate() with regex support + const ast = astFromCode(` + const DOT_SLASH_FOO = './foo'; + const FALSE = false; + const EAGER = 'eager'; + const PATTERN = /pattern/; + const a = require.context(DOT_SLASH_FOO, FALSE, PATTERN, EAGER); + `); + const {dependencies, dependencyMapName} = collectDependencies( + ast, + optsWithContext, + ); + expect(dependencies).toEqual([ + { + name: './foo', + data: objectContaining({ + contextParams: { + filter: { + pattern: 'pattern', + flags: '', + }, + mode: 'eager', + recursive: false, + }, + }), + }, + ]); + expect(codeFromAst(ast)).toEqual( + comparableCode(` + const DOT_SLASH_FOO = "./foo"; + const FALSE = false; + const EAGER = "eager"; + const PATTERN = /pattern/; + const a = require(${dependencyMapName}[0], "./foo"); + `), + ); + }); + it('distinguishes require from require.context', () => { const ast = astFromCode(` const a = require.context('./'); @@ -606,7 +680,7 @@ describe(`require.context`, () => { expect(() => collectDependencies(ast, optsWithContext)) .toThrowErrorMatchingInlineSnapshot(` "Invalid call at line 2: 42 - First argument of \`require.context\` should be a string denoting the directory to require, instead found node of type: NumericLiteral." + First argument of \`require.context\` should be a string denoting the directory to require." `); }); it(`asserts invalid second argument`, () => { @@ -616,7 +690,7 @@ describe(`require.context`, () => { expect(() => collectDependencies(ast, optsWithContext)) .toThrowErrorMatchingInlineSnapshot(` "Invalid call at line 2: 'hey' - Second argument of \`require.context\` should be an optional boolean indicating if files should be imported recursively or not, instead found node of type: StringLiteral." + Second argument of \`require.context\` should be an optional boolean indicating if files should be imported recursively or not." `); }); it(`asserts invalid third argument`, () => { @@ -636,7 +710,7 @@ describe(`require.context`, () => { expect(() => collectDependencies(ast, optsWithContext)) .toThrowErrorMatchingInlineSnapshot(` "Invalid call at line 2: 34 - Fourth argument of \`require.context\` should be an optional string \\"mode\\" denoting how the modules will be resolved, instead found node of type: NumericLiteral." + Fourth argument of \`require.context\` should be an optional string \\"mode\\" denoting how the modules will be resolved." `); }); it(`asserts invalid fourth argument enum value`, () => { diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 96fa2b0eea..424d988d96 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -302,54 +302,64 @@ function getRequireContextArgs( if (!Array.isArray(args) || args.length < 1) { throw new InvalidRequireCallError(path); } else { - const argNode = args[0].node; - if (argNode.type !== 'StringLiteral') { + const result = args[0].evaluate(); + if (result.confident && typeof result.value === 'string') { + directory = result.value; + } else if (!(result.confident && typeof result.value === 'undefined')) { throw new InvalidRequireCallError( - args[0], - `First argument of \`require.context\` should be a string denoting the directory to require, instead found node of type: ${argNode.type}.`, + result.deopt ?? args[0], + 'First argument of `require.context` should be a string denoting the directory to require.', ); } - directory = argNode.value; } // Default to requiring through all directories. let recursive: boolean = true; if (args.length > 1) { - const argNode = args[1].node; - if (argNode.type !== 'BooleanLiteral') { + const result = args[1].evaluate(); + if (result.confident && typeof result.value === 'boolean') { + recursive = result.value; + } else if (!(result.confident && typeof result.value === 'undefined')) { throw new InvalidRequireCallError( - args[1], - `Second argument of \`require.context\` should be an optional boolean indicating if files should be imported recursively or not, instead found node of type: ${argNode.type}.`, + result.deopt ?? args[1], + 'Second argument of `require.context` should be an optional boolean indicating if files should be imported recursively or not.', ); } - recursive = argNode.value; } // Default to all files. let filter: ContextFilter = {pattern: '.*', flags: ''}; if (args.length > 2) { + // evaluate() to check for undefined (because it's technically a scope lookup) + // but check the AST for the regex literal, since evaluate() doesn't do regex. + const result = args[2].evaluate(); const argNode = args[2].node; - if (argNode.type !== 'RegExpLiteral') { + if (argNode.type === 'RegExpLiteral') { // TODO: Handle `new RegExp(...)` -- `argNode.type === 'NewExpression'` + filter = { + pattern: argNode.pattern, + flags: argNode.flags || '', + }; + } else if (!(result.confident && typeof result.value === 'undefined')) { throw new InvalidRequireCallError( args[2], `Third argument of \`require.context\` should be an optional RegExp pattern matching all of the files to import, instead found node of type: ${argNode.type}.`, ); } - filter = {pattern: argNode.pattern, flags: argNode.flags || ''}; } // Default to `sync`. let mode: ContextMode = 'sync'; if (args.length > 3) { - const argNode = args[3].node; - if (argNode.type !== 'StringLiteral') { + const result = args[3].evaluate(); + if (result.confident && typeof result.value === 'string') { + mode = getContextMode(args[3], result.value); + } else if (!(result.confident && typeof result.value === 'undefined')) { throw new InvalidRequireCallError( - args[3], - `Fourth argument of \`require.context\` should be an optional string "mode" denoting how the modules will be resolved, instead found node of type: ${argNode.type}.`, + result.deopt ?? args[3], + 'Fourth argument of `require.context` should be an optional string "mode" denoting how the modules will be resolved.', ); } - mode = getContextMode(args[3], argNode.value); } if (args.length > 4) { From 5a62786e60963e8828d6a70c7b06257f9b23f178 Mon Sep 17 00:00:00 2001 From: Moti Zilberman Date: Wed, 15 Jun 2022 01:33:38 +0100 Subject: [PATCH 28/28] fix: make directory arg required --- packages/metro/src/ModuleGraph/worker/collectDependencies.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/metro/src/ModuleGraph/worker/collectDependencies.js b/packages/metro/src/ModuleGraph/worker/collectDependencies.js index 424d988d96..d302a25cbf 100644 --- a/packages/metro/src/ModuleGraph/worker/collectDependencies.js +++ b/packages/metro/src/ModuleGraph/worker/collectDependencies.js @@ -305,7 +305,7 @@ function getRequireContextArgs( const result = args[0].evaluate(); if (result.confident && typeof result.value === 'string') { directory = result.value; - } else if (!(result.confident && typeof result.value === 'undefined')) { + } else { throw new InvalidRequireCallError( result.deopt ?? args[0], 'First argument of `require.context` should be a string denoting the directory to require.',