Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@expo/metro-config

Package Overview
Dependencies
Maintainers
25
Versions
229
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@expo/metro-config - npm Package Compare versions

Comparing version 0.19.0-canary-20240628-1ba8152 to 0.19.0-canary-20240719-83ee47b

build/serializer/findUpPackageJsonPath.d.ts

2

build/babel-transformer.js

@@ -70,3 +70,3 @@ "use strict";

// Set the standard Babel flag to disable ESM transformations.
supportsStaticESM: options.experimentalImportSupport,
supportsStaticESM: isCustomTruthy(options.customTransformOptions?.optimize) || options.experimentalImportSupport,
// Enable React compiler support in Babel.

@@ -73,0 +73,0 @@ // TODO: Remove this in the future when compiler is on by default.

@@ -12,4 +12,6 @@ declare class Env {

get EXPO_NO_CLIENT_ENV_VARS(): boolean;
/** Enable the use of Expo's custom metro require implementation. The custom require supports better debugging, tree shaking, and React Server Components. */
get EXPO_USE_METRO_REQUIRE(): boolean;
}
export declare const env: Env;
export {};

@@ -26,4 +26,8 @@ "use strict";

}
/** Enable the use of Expo's custom metro require implementation. The custom require supports better debugging, tree shaking, and React Server Components. */
get EXPO_USE_METRO_REQUIRE() {
return (0, getenv_1.boolish)('EXPO_USE_METRO_REQUIRE', false);
}
}
exports.env = new Env();
//# sourceMappingURL=env.js.map

@@ -47,2 +47,3 @@ "use strict";

const rewriteRequestUrl_1 = require("./rewriteRequestUrl");
const sideEffects_1 = require("./serializer/sideEffects");
const withExpoSerializers_1 = require("./serializer/withExpoSerializers");

@@ -88,2 +89,41 @@ const postcss_1 = require("./transform-worker/postcss");

}
function createNumericModuleIdFactory() {
const fileToIdMap = new Map();
let nextId = 0;
return (modulePath) => {
let id = fileToIdMap.get(modulePath);
if (typeof id !== 'number') {
id = nextId++;
fileToIdMap.set(modulePath, id);
}
return id;
};
}
function createStableModuleIdFactory(root) {
const fileToIdMap = new Map();
// This is an absolute file path.
return (modulePath) => {
// TODO: We may want a hashed version for production builds in the future.
let id = fileToIdMap.get(modulePath);
if (id == null) {
// NOTE: Metro allows this but it can lead to confusing errors when dynamic requires cannot be resolved, e.g. `module 456 cannot be found`.
if (modulePath == null) {
id = 'MODULE_NOT_FOUND';
}
else if ((0, sideEffects_1.isVirtualModule)(modulePath)) {
// Virtual modules should be stable.
id = modulePath;
}
else if (path_1.default.isAbsolute(modulePath)) {
id = path_1.default.relative(root, modulePath);
}
else {
id = modulePath;
}
fileToIdMap.set(modulePath, id);
}
// @ts-expect-error: we patch this to support being a string.
return id;
};
}
function getDefaultConfig(projectRoot, { mode, isCSSEnabled = true, unstable_beforeAssetSerializationPlugins } = {}) {

@@ -170,2 +210,16 @@ const { getDefaultConfig: getDefaultMetroConfig, mergeConfig } = (0, metro_config_1.importMetroConfig)(projectRoot);

serializer: {
isThirdPartyModule(module) {
// Block virtual modules from appearing in the source maps.
if ((0, sideEffects_1.isVirtualModule)(module.path))
return true;
// Generally block node modules
if (/(?:^|[/\\])node_modules[/\\]/.test(module.path)) {
// Allow the expo-router/entry and expo/AppEntry modules to be considered first party so the root of the app appears in the trace.
return !module.path.match(/[/\\](expo-router[/\\]entry|expo[/\\]AppEntry)/);
}
return false;
},
createModuleIdFactory: env_1.env.EXPO_USE_METRO_REQUIRE
? createStableModuleIdFactory.bind(null, projectRoot)
: createNumericModuleIdFactory,
getModulesRunBeforeMainModule: () => {

@@ -228,2 +282,3 @@ const preModules = [

_expoRelativeProjectRoot: path_1.default.relative(serverRoot, projectRoot),
unstable_collectDependenciesPath: require.resolve('./transform-worker/collect-dependencies'),
// `require.context` support

@@ -230,0 +285,0 @@ unstable_allowRequireContext: true,

@@ -27,6 +27,3 @@ "use strict";

const { params, paths } = getModuleParams(module, options);
let src = output.data.code;
if (!options.skipWrapping) {
src = (0, metro_transform_plugins_1.addParamsToDefineCall)(output.data.code, ...params);
}
const src = (0, metro_transform_plugins_1.addParamsToDefineCall)(output.data.code, ...params);
return { src, paths };

@@ -40,3 +37,13 @@ }

const dependencyMapArray = Array.from(module.dependencies.values()).map((dependency) => {
const id = options.createModuleId(dependency.absolutePath);
let modulePath = dependency.absolutePath;
if (modulePath == null) {
if (dependency.data.data.isOptional) {
// For optional dependencies, that could not be resolved.
modulePath = dependency.data.name;
}
else {
throw new Error(`Module "${module.path}" has a dependency with missing absolutePath: ${(JSON.stringify(dependency), null, 2)}`);
}
}
const id = options.createModuleId(modulePath);
if (

@@ -43,0 +50,0 @@ // NOTE(EvanBacon): Disabled this to ensure that paths are provided even when the entire bundle

@@ -8,2 +8,4 @@ /**

import { FBSourceFunctionMap, MetroSourceMapSegmentTuple } from 'metro-source-map';
import { JsTransformerConfig } from 'metro-transform-worker';
import { Options as CollectDependenciesOptions } from '../transform-worker/collect-dependencies';
export type JSFileType = 'js/script' | 'js/module' | 'js/module/asset';

@@ -22,2 +24,6 @@ export type JsOutput = {

};
ast?: import('@babel/types').File;
hasCjsExports?: boolean;
readonly reconcile?: ReconcileTransformSettings;
readonly reactClientReference?: string;
};

@@ -42,3 +48,20 @@ type: JSFileType;

};
export type ReconcileTransformSettings = {
inlineRequires: boolean;
importDefault: string;
importAll: string;
globalPrefix: string;
unstable_renameRequire?: boolean;
unstable_compactOutput?: boolean;
minify?: {
minifierPath: string;
minifierConfig: JsTransformerConfig['minifierConfig'];
};
collectDependenciesOptions: CollectDependenciesOptions;
unstable_dependencyMapReservedName?: string;
optimizationSizeLimit?: number;
unstable_disableNormalizePseudoGlobals?: boolean;
normalizePseudoGlobals: boolean;
};
export declare function isExpoJsOutput(output: any): output is ExpoJsOutput;
export declare function isTransformOptionTruthy(option: any): boolean;

@@ -19,2 +19,3 @@ "use strict";

const baseJSBundle_1 = require("./fork/baseJSBundle");
const reconcileTransformSerializerPlugin_1 = require("./reconcileTransformSerializerPlugin");
const serializeChunks_1 = require("./serializeChunks");

@@ -28,2 +29,4 @@ const env_1 = require("../env");

}
// Then finish transforming the modules from AST to JS.
processors.push(reconcileTransformSerializerPlugin_1.reconcileTransformSerializerPlugin);
return withSerializerPlugins(config, processors, options);

@@ -30,0 +33,0 @@ }

/// <reference types="node" />
/// <reference types="metro" />
import type { TransformResultDependency } from 'metro/src/DeltaBundler';
import { JsOutput, JsTransformerConfig, JsTransformOptions } from 'metro-transform-worker';
import * as babylon from '@babel/parser';
import * as t from '@babel/types';
import type { MetroSourceMapSegmentTuple } from 'metro-source-map';
import { JsTransformerConfig, JsTransformOptions } from 'metro-transform-worker';
import { InvalidRequireCallError as InternalInvalidRequireCallError, CollectedDependencies, Options as CollectDependenciesOptions } from './collect-dependencies';
import { ExpoJsOutput } from '../serializer/jsOutput';
export { JsTransformOptions };
interface TransformResponse {
readonly dependencies: readonly TransformResultDependency[];
readonly dependencies: CollectedDependencies['dependencies'];
readonly output: readonly ExpoJsOutput[];
}
export type ExpoJsOutput = Pick<JsOutput, 'type'> & {
readonly data: JsOutput['data'] & {
readonly reactClientReference?: string;
};
};
export declare class InvalidRequireCallError extends Error {
innerError: InternalInvalidRequireCallError;
filename: string;
constructor(innerError: InternalInvalidRequireCallError, filename: string);
}
export declare const minifyCode: (config: Pick<JsTransformerConfig, 'minifierPath' | 'minifierConfig'>, filename: string, code: string, source: string, map: MetroSourceMapSegmentTuple[], reserved?: string[]) => Promise<{
code: string;
map: MetroSourceMapSegmentTuple[];
}>;
export declare function applyImportSupport<TFile extends t.File>(ast: TFile, { filename, options, importDefault, importAll, }: {
filename: string;
options: Pick<JsTransformOptions, 'experimentalImportSupport' | 'inlineRequires' | 'nonInlinedRequires'>;
importDefault: string;
importAll: string;
}): TFile;
export declare function transform(config: JsTransformerConfig, projectRoot: string, filename: string, data: Buffer, options: JsTransformOptions): Promise<TransformResponse>;
export declare function getCacheKey(config: JsTransformerConfig): string;
export declare function collectDependenciesForShaking(ast: babylon.ParseResult<t.File>, options: CollectDependenciesOptions): Readonly<{
ast: babylon.ParseResult<t.File>;
dependencyMapName: string;
dependencies: readonly Readonly<{
data: Readonly<{
key: string;
asyncType: import("./collect-dependencies").AsyncDependencyType | null;
isOptional?: boolean | undefined;
locs: readonly t.SourceLocation[];
contextParams?: Readonly<{
recursive: boolean;
filter: Readonly<Readonly<{
pattern: string;
flags: string;
}>>;
mode: "sync" | "eager" | "lazy" | "lazy-once";
}> | undefined;
exportNames: string[];
}>;
name: string;
}>[];
}>;

@@ -29,3 +29,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.getCacheKey = exports.transform = void 0;
exports.collectDependenciesForShaking = exports.getCacheKey = exports.transform = exports.applyImportSupport = exports.minifyCode = exports.InvalidRequireCallError = void 0;
/**

@@ -44,5 +44,5 @@ * Copyright 2023-present 650 Industries (Expo). All rights reserved.

const babylon = __importStar(require("@babel/parser"));
const types = __importStar(require("@babel/types"));
const template_1 = __importDefault(require("@babel/template"));
const t = __importStar(require("@babel/types"));
const JsFileWrapping_1 = __importDefault(require("metro/src/ModuleGraph/worker/JsFileWrapping"));
const collectDependencies_1 = __importStar(require("metro/src/ModuleGraph/worker/collectDependencies"));
const generateImportNames_1 = __importDefault(require("metro/src/ModuleGraph/worker/generateImportNames"));

@@ -57,3 +57,14 @@ const countLines_1 = __importDefault(require("metro/src/lib/countLines"));

const assetTransformer = __importStar(require("./asset-transformer"));
const collect_dependencies_1 = __importStar(require("./collect-dependencies"));
const resolveOptions_1 = require("./resolveOptions");
class InvalidRequireCallError extends Error {
innerError;
filename;
constructor(innerError, filename) {
super(`${filename}:${innerError.message}`);
this.innerError = innerError;
this.filename = filename;
}
}
exports.InvalidRequireCallError = InvalidRequireCallError;
// asserts non-null

@@ -74,3 +85,3 @@ function nullthrows(x, message) {

}
const minifyCode = async (config, projectRoot, filename, code, source, map, reserved = []) => {
const minifyCode = async (config, filename, code, source, map, reserved = []) => {
const sourceMap = (0, metro_source_map_1.fromRawMappings)([

@@ -109,25 +120,16 @@ {

};
const disabledDependencyTransformer = {
transformSyncRequire: () => { },
transformImportCall: () => { },
transformPrefetch: () => { },
transformIllegalDynamicRequire: () => { },
};
class InvalidRequireCallError extends Error {
innerError;
filename;
constructor(innerError, filename) {
super(`${filename}:${innerError.message}`);
this.innerError = innerError;
this.filename = filename;
}
exports.minifyCode = minifyCode;
function renameTopLevelModuleVariables() {
// A babel plugin which renames variables in the top-level scope that are named "module".
return {
visitor: {
Program(path) {
['global', 'require', 'module', 'exports'].forEach((name) => {
path.scope.rename(name, path.scope.generateUidIdentifier(name).name);
});
},
},
};
}
async function transformJS(file, { config, options, projectRoot }) {
// const targetEnv = options.customTransformOptions?.environment;
// const isServerEnv = targetEnv === 'node' || targetEnv === 'react-server';
// Transformers can output null ASTs (if they ignore the file). In that case
// we need to parse the module source code to get their AST.
let ast = file.ast ?? babylon.parse(file.code, { sourceType: 'unambiguous' });
// NOTE(EvanBacon): This can be really expensive on larger files. We should replace it with a cheaper alternative that just iterates and matches.
const { importDefault, importAll } = (0, generateImportNames_1.default)(ast);
function applyUseStrictDirective(ast) {
// Add "use strict" if the file was parsed as a module, and the directive did

@@ -139,4 +141,6 @@ // not exist yet.

directives.findIndex((d) => d.value.value === 'use strict') === -1) {
directives.push(types.directive(types.directiveLiteral('use strict')));
directives.push(t.directive(t.directiveLiteral('use strict')));
}
}
function applyImportSupport(ast, { filename, options, importDefault, importAll, }) {
// Perform the import-export transform (in case it's still needed), then

@@ -152,5 +156,9 @@ // fold requires and perform constant folding (if in dev).

// NOTE(EvanBacon): This is effectively a replacement for the `@babel/plugin-transform-modules-commonjs`
// plugin that's running in `@@react-native/babel-preset`, but with shared names for inlining requires.
// plugin that's running in `@react-native/babel-preset`, but with shared names for inlining requires.
if (options.experimentalImportSupport === true) {
plugins.push([metro_transform_plugins_1.default.importExportPlugin, babelPluginOpts]);
plugins.push(
// Ensure the iife "globals" don't have conflicting variables in the module.
renameTopLevelModuleVariables,
//
[metro_transform_plugins_1.default.importExportPlugin, babelPluginOpts]);
}

@@ -180,3 +188,3 @@ // NOTE(EvanBacon): This can basically never be safely enabled because it doesn't respect side-effects and

comments: true,
filename: file.filename,
filename,
plugins,

@@ -193,41 +201,73 @@ sourceMaps: false,

cloneInputAst: false,
}).ast);
})?.ast);
}
if (!options.dev) {
// NOTE(kitten): Any Babel helpers that have been added (`path.hub.addHelper(...)`) will usually not have any
// references, and hence the `constantFoldingPlugin` below will remove them.
// To fix the references we add an explicit `programPath.scope.crawl()`. Alternatively, we could also wipe the
// Babel traversal cache (`traverse.cache.clear()`)
const clearProgramScopePlugin = {
visitor: {
Program: {
enter(path) {
path.scope.crawl();
},
return ast;
}
exports.applyImportSupport = applyImportSupport;
function performConstantFolding(ast, { filename }) {
// NOTE(kitten): Any Babel helpers that have been added (`path.hub.addHelper(...)`) will usually not have any
// references, and hence the `constantFoldingPlugin` below will remove them.
// To fix the references we add an explicit `programPath.scope.crawl()`. Alternatively, we could also wipe the
// Babel traversal cache (`traverse.cache.clear()`)
const clearProgramScopePlugin = {
visitor: {
Program: {
enter(path) {
path.scope.crawl();
},
},
};
// Run the constant folding plugin in its own pass, avoiding race conditions
// with other plugins that have exit() visitors on Program (e.g. the ESM
// transform).
ast = nullthrows(
// @ts-expect-error
(0, core_1.transformFromAstSync)(ast, '', {
ast: true,
babelrc: false,
code: false,
configFile: false,
comments: true,
filename: file.filename,
plugins: [
clearProgramScopePlugin,
[metro_transform_plugins_1.default.constantFoldingPlugin, babelPluginOpts],
],
sourceMaps: false,
// NOTE(kitten): In Metro, this is also false, but only works because the prior run of `transformFromAstSync` was always
// running with `cloneInputAst: true`.
// This isn't needed anymore since `clearProgramScopePlugin` re-crawls the AST’s scope instead.
cloneInputAst: false,
}).ast);
},
};
// Run the constant folding plugin in its own pass, avoiding race conditions
// with other plugins that have exit() visitors on Program (e.g. the ESM
// transform).
ast = nullthrows(
// @ts-expect-error
(0, core_1.transformFromAstSync)(ast, '', {
ast: true,
babelrc: false,
code: false,
configFile: false,
comments: true,
filename,
plugins: [clearProgramScopePlugin, metro_transform_plugins_1.default.constantFoldingPlugin],
sourceMaps: false,
// NOTE(kitten): In Metro, this is also false, but only works because the prior run of `transformFromAstSync` was always
// running with `cloneInputAst: true`.
// This isn't needed anymore since `clearProgramScopePlugin` re-crawls the AST’s scope instead.
cloneInputAst: false,
}).ast);
return ast;
}
async function transformJS(file, { config, options }) {
const targetEnv = options.customTransformOptions?.environment;
const isServerEnv = targetEnv === 'node' || targetEnv === 'react-server';
const optimize =
// Ensure we don't enable tree shaking for scripts or assets.
file.type === 'js/module' &&
String(options.customTransformOptions?.optimize) === 'true' &&
// Disable tree shaking on JSON files.
!file.filename.endsWith('.json');
const unstable_disableModuleWrapping = optimize || config.unstable_disableModuleWrapping;
if (optimize && !options.experimentalImportSupport) {
// Add a warning so devs can incrementally migrate since experimentalImportSupport may cause other issues in their app.
throw new Error('Experimental tree shaking support only works with experimentalImportSupport enabled.');
}
// Transformers can output null ASTs (if they ignore the file). In that case
// we need to parse the module source code to get their AST.
let ast = file.ast ?? babylon.parse(file.code, { sourceType: 'unambiguous' });
// NOTE(EvanBacon): This can be really expensive on larger files. We should replace it with a cheaper alternative that just iterates and matches.
const { importDefault, importAll } = (0, generateImportNames_1.default)(ast);
// Add "use strict" if the file was parsed as a module, and the directive did
// not exist yet.
applyUseStrictDirective(ast);
// @ts-expect-error: Not on types yet (Metro 0.80).
const unstable_renameRequire = config.unstable_renameRequire;
// Disable all Metro single-file optimizations when full-graph optimization will be used.
if (!optimize) {
ast = applyImportSupport(ast, { filename: file.filename, options, importDefault, importAll });
}
if (!options.dev) {
ast = performConstantFolding(ast, { filename: file.filename });
}
let dependencyMapName = '';

@@ -240,2 +280,3 @@ let dependencies;

// not have dependencies).
let collectDependenciesOptions;
if (file.type === 'js/script') {

@@ -247,3 +288,3 @@ dependencies = [];

try {
const opts = {
collectDependenciesOptions = {
asyncRequireModulePath: config.asyncRequireModulePath,

@@ -253,3 +294,7 @@ dependencyTransformer: config.unstable_disableModuleWrapping === true

: undefined,
dynamicRequires: getDynamicDepsBehavior(config.dynamicDepsInPackages, file.filename),
dynamicRequires: isServerEnv
? // NOTE(EvanBacon): Allow arbitrary imports in server environments.
// This requires a patch to Metro collectDeps.
'warn'
: getDynamicDepsBehavior(config.dynamicDepsInPackages, file.filename),
inlineableCalls: [importDefault, importAll],

@@ -260,10 +305,19 @@ keepRequireNames: options.dev,

unstable_allowRequireContext: config.unstable_allowRequireContext,
// NOTE(EvanBacon): Allow arbitrary imports in server environments.
// This requires a patch to Metro collectDeps.
// allowArbitraryImport: isServerEnv,
// If tree shaking is enabled, then preserve the original require calls.
// This ensures require.context calls are not broken.
collectOnly: optimize === true,
};
({ ast, dependencies, dependencyMapName } = (0, collectDependencies_1.default)(ast, opts));
({ ast, dependencies, dependencyMapName } = (0, collect_dependencies_1.default)(ast, {
...collectDependenciesOptions,
// This setting shouldn't be shared with the tree shaking transformer.
dependencyTransformer: unstable_disableModuleWrapping === true ? disabledDependencyTransformer : undefined,
}));
// Ensure we use the same name for the second pass of the dependency collection in the serializer.
collectDependenciesOptions = {
...collectDependenciesOptions,
dependencyMapName,
};
}
catch (error) {
if (error instanceof collectDependencies_1.InvalidRequireCallError) {
if (error instanceof collect_dependencies_1.InvalidRequireCallError) {
throw new InvalidRequireCallError(error, file.filename);

@@ -273,3 +327,3 @@ }

}
if (config.unstable_disableModuleWrapping === true) {
if (unstable_disableModuleWrapping === true) {
wrappedAst = ast;

@@ -284,5 +338,9 @@ }

// @ts-expect-error: Not on types yet (Metro 0.80.9).
config.unstable_renameRequire === false));
unstable_renameRequire === false));
}
}
const minify = (0, resolveOptions_1.shouldMinify)(options);
const shouldNormalizePseudoGlobals = minify &&
file.inputFileSize <= config.optimizationSizeLimit &&
!config.unstable_disableNormalizePseudoGlobals;
const reserved = [];

@@ -292,6 +350,5 @@ if (config.unstable_dependencyMapReservedName != null) {

}
const minify = (0, resolveOptions_1.shouldMinify)(options);
if (minify &&
file.inputFileSize <= config.optimizationSizeLimit &&
!config.unstable_disableNormalizePseudoGlobals) {
if (shouldNormalizePseudoGlobals &&
// TODO: If the module wrapping is disabled then the normalize function needs to change to account for not being in a body.
!unstable_disableModuleWrapping) {
// NOTE(EvanBacon): Simply pushing this function will mutate the AST, so it must run before the `generate` step!!

@@ -313,5 +370,27 @@ reserved.push(...metro_transform_plugins_1.default.normalizePseudoGlobals(wrappedAst, {

let code = result.code;
// NOTE: We might want to enable this on native + hermes when tree shaking is enabled.
if (minify) {
({ map, code } = await minifyCode(config, projectRoot, file.filename, result.code, file.code, map, reserved));
({ map, code } = await (0, exports.minifyCode)(config, file.filename, result.code, file.code, map, reserved));
}
const possibleReconcile = optimize && collectDependenciesOptions
? {
inlineRequires: options.inlineRequires,
importDefault,
importAll,
normalizePseudoGlobals: shouldNormalizePseudoGlobals,
globalPrefix: config.globalPrefix,
unstable_compactOutput: config.unstable_compactOutput,
collectDependenciesOptions,
minify: minify
? {
minifierPath: config.minifierPath,
minifierConfig: config.minifierConfig,
}
: undefined,
unstable_dependencyMapReservedName: config.unstable_dependencyMapReservedName,
optimizationSizeLimit: config.optimizationSizeLimit,
unstable_disableNormalizePseudoGlobals: config.unstable_disableNormalizePseudoGlobals,
unstable_renameRequire,
}
: undefined;
const output = [

@@ -324,3 +403,12 @@ {

functionMap: file.functionMap,
hasCjsExports: file.hasCjsExports,
reactClientReference: file.reactClientReference,
...(possibleReconcile
? {
ast: wrappedAst,
// Store settings for the module that will be used to finish transformation after graph-based optimizations
// have finished.
reconcile: possibleReconcile,
}
: {}),
},

@@ -345,2 +433,3 @@ type: file.type,

functionMap: null,
hasCjsExports: true,
reactClientReference: result.reactClientReference,

@@ -367,2 +456,3 @@ };

}
// TODO: Add a babel plugin which returns if the module has commonjs, and if so, disable all tree shaking optimizations early.
const transformResult = await transformer.transform(

@@ -378,2 +468,3 @@ // functionMapBabelPlugin populates metadata.metro.functionMap

null,
hasCjsExports: transformResult.metadata?.hasCjsExports,
reactClientReference: transformResult.metadata?.reactClientReference,

@@ -383,3 +474,3 @@ };

}
async function transformJSON(file, { options, config, projectRoot }) {
async function transformJSON(file, { options, config }) {
let code = config.unstable_disableModuleWrapping === true

@@ -391,3 +482,3 @@ ? JsFileWrapping_1.default.jsonToCommonJS(file.code)

if (minify) {
({ map, code } = await minifyCode(config, projectRoot, file.filename, code, file.code, map));
({ map, code } = await (0, exports.minifyCode)(config, file.filename, code, file.code, map));
}

@@ -484,3 +575,5 @@ let jsType;

require.resolve('metro-transform-worker/src/utils/getMinifier'),
require.resolve('./collect-dependencies'),
require.resolve('./asset-transformer'),
require.resolve('./resolveOptions'),
require.resolve('metro/src/ModuleGraph/worker/generateImportNames'),

@@ -498,2 +591,42 @@ require.resolve('metro/src/ModuleGraph/worker/JsFileWrapping'),

exports.getCacheKey = getCacheKey;
/**
* Produces a Babel template that transforms an "import(...)" call into a
* "require(...)" call to the asyncRequire specified.
*/
const makeShimAsyncRequireTemplate = template_1.default.expression(`require(ASYNC_REQUIRE_MODULE_PATH)`);
const disabledDependencyTransformer = {
transformSyncRequire: (path) => { },
transformImportCall: (path, dependency, state) => {
// HACK: Ensure the async import code is included in the bundle when an import() call is found.
let topParent = path;
while (topParent.parentPath) {
topParent = topParent.parentPath;
}
// @ts-expect-error
if (topParent._handled) {
return;
}
path.insertAfter(makeShimAsyncRequireTemplate({
ASYNC_REQUIRE_MODULE_PATH: nullthrows(state.asyncRequireModulePathStringLiteral),
}));
// @ts-expect-error: Prevent recursive loop
topParent._handled = true;
},
transformPrefetch: () => { },
transformIllegalDynamicRequire: () => { },
};
function collectDependenciesForShaking(ast, options) {
const collectDependenciesOptions = {
...options,
// If tree shaking is enabled, then preserve the original require calls.
// This ensures require.context calls are not broken.
collectOnly: true,
};
return (0, collect_dependencies_1.default)(ast, {
...collectDependenciesOptions,
// This setting shouldn't be shared with the tree shaking transformer.
dependencyTransformer: disabledDependencyTransformer,
});
}
exports.collectDependenciesForShaking = collectDependenciesForShaking;
//# sourceMappingURL=metro-transform-worker.js.map
{
"name": "@expo/metro-config",
"version": "0.19.0-canary-20240628-1ba8152",
"version": "0.19.0-canary-20240719-83ee47b",
"description": "A Metro config for running React Native projects with the Metro bundler",

@@ -40,5 +40,5 @@ "main": "build/ExpoMetroConfig.js",

"@babel/types": "^7.20.0",
"@expo/config": "9.1.0-canary-20240628-1ba8152",
"@expo/env": "0.3.1-canary-20240628-1ba8152",
"@expo/json-file": "8.3.4-canary-20240628-1ba8152",
"@expo/config": "9.1.0-canary-20240719-83ee47b",
"@expo/env": "0.3.1-canary-20240719-83ee47b",
"@expo/json-file": "8.3.4-canary-20240719-83ee47b",
"@expo/spawn-async": "^1.7.2",

@@ -54,8 +54,10 @@ "chalk": "^4.1.0",

"postcss": "~8.4.32",
"resolve-from": "^5.0.0"
"resolve-from": "^5.0.0",
"minimatch": "^3.0.4"
},
"devDependencies": {
"@jridgewell/trace-mapping": "^0.3.20",
"expo-module-scripts": "3.6.0-canary-20240628-1ba8152",
"sass": "^1.60.0"
"expo-module-scripts": "3.6.0-canary-20240719-83ee47b",
"sass": "^1.60.0",
"dedent": "^1.5.3"
},

@@ -65,3 +67,3 @@ "publishConfig": {

},
"gitHead": "1ba815237ed606c5ee8488f68e49773fc9735cc3"
"gitHead": "83ee47b5c89c7f1b1a5101189580eaf3555f5962"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc