@expo/cli 1.0.0-canary-20250709-136b77f → 1.0.0-canary-20250713-8f814f8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/bin/cli CHANGED
@@ -123,7 +123,7 @@ const args = (0, _arg().default)({
123
123
  });
124
124
  if (args['--version']) {
125
125
  // Version is added in the build script.
126
- console.log("1.0.0-canary-20250709-136b77f");
126
+ console.log("1.0.0-canary-20250713-8f814f8");
127
127
  process.exit(0);
128
128
  }
129
129
  if (args['--non-interactive']) {
@@ -208,7 +208,7 @@ class AsyncNgrok {
208
208
  configPath,
209
209
  onStatusChange (status) {
210
210
  if (status === 'closed') {
211
- _log.error(_chalk().default.red('Tunnel connection has been closed. This is often related to intermittent connection problems with the Ngrok servers. Restart the dev server to try connecting to Ngrok again.') + _chalk().default.gray('\nCheck the Ngrok status page for outages: https://status.ngrok.com/'));
211
+ _log.error(_chalk().default.red('Tunnel connection has been closed. This is often related to intermittent connection issues between the dev server and ngrok. Restart the dev server to try connecting to ngrok again.') + _chalk().default.gray('\nCheck the Ngrok status page for outages: https://status.ngrok.com/'));
212
212
  } else if (status === 'connected') {
213
213
  _log.log('Tunnel connected.');
214
214
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/start/server/AsyncNgrok.ts"],"sourcesContent":["import chalk from 'chalk';\nimport crypto from 'crypto';\nimport * as path from 'path';\nimport slugify from 'slugify';\n\nimport { getSettingsDirectory } from '../../api/user/UserSettings';\nimport { getActorDisplayName, getUserAsync } from '../../api/user/user';\nimport * as Log from '../../log';\nimport { delayAsync, resolveWithTimeout } from '../../utils/delay';\nimport { env } from '../../utils/env';\nimport { CommandError } from '../../utils/errors';\nimport { isNgrokClientError, NgrokInstance, NgrokResolver } from '../doctor/ngrok/NgrokResolver';\nimport { hasAdbReverseAsync, startAdbReverseAsync } from '../platforms/android/adbReverse';\nimport { ProjectSettings } from '../project/settings';\n\nconst debug = require('debug')('expo:start:server:ngrok') as typeof console.log;\n\nconst NGROK_CONFIG = {\n authToken: '5W1bR67GNbWcXqmxZzBG1_56GezNeaX6sSRvn8npeQ8',\n domain: 'exp.direct',\n};\n\nconst TUNNEL_TIMEOUT = 10 * 1000;\n\nexport class AsyncNgrok {\n /** Resolves the best instance of ngrok, exposed for testing. */\n resolver: NgrokResolver;\n\n /** Info about the currently running instance of ngrok. */\n private serverUrl: string | null = null;\n\n constructor(\n private projectRoot: string,\n private port: number\n ) {\n this.resolver = new NgrokResolver(projectRoot);\n }\n\n public getActiveUrl(): string | null {\n return this.serverUrl;\n }\n\n /** Exposed for testing. */\n async _getIdentifyingUrlSegmentsAsync(): Promise<string[]> {\n const user = await getUserAsync();\n if (user?.__typename === 'Robot') {\n throw new CommandError('NGROK_ROBOT', 'Cannot use ngrok with a robot user.');\n }\n const username = getActorDisplayName(user);\n\n return [\n // NOTE: https://github.com/expo/expo/pull/16556#discussion_r822944286\n await this.getProjectRandomnessAsync(),\n // Strip out periods from the username to avoid subdomain issues with SSL certificates.\n slugify(username, { remove: /\\./ }),\n // Use the port to distinguish between multiple tunnels (webpack, metro).\n String(this.port),\n ];\n }\n\n /** Exposed for testing. */\n async _getProjectHostnameAsync(): Promise<string> {\n return `${(await this._getIdentifyingUrlSegmentsAsync()).join('-')}.${NGROK_CONFIG.domain}`;\n }\n\n /** Exposed for testing. */\n async _getProjectSubdomainAsync(): Promise<string> {\n return (await this._getIdentifyingUrlSegmentsAsync()).join('-');\n }\n\n /** Start ngrok on the given port for the project. */\n async startAsync({ timeout }: { timeout?: number } = {}): Promise<void> {\n // Ensure the instance is loaded first, this can linger so we should run it before the timeout.\n await this.resolver.resolveAsync({\n // For now, prefer global install since the package has native code (harder to install) and doesn't change very often.\n prefersGlobalInstall: true,\n });\n\n // NOTE(EvanBacon): If the user doesn't have ADB installed,\n // then skip attempting to reverse the port.\n if (hasAdbReverseAsync()) {\n // Ensure ADB reverse is running.\n if (!(await startAdbReverseAsync([this.port]))) {\n // TODO: Better error message.\n throw new CommandError(\n 'NGROK_ADB',\n `Cannot start tunnel URL because \\`adb reverse\\` failed for the connected Android device(s).`\n );\n }\n }\n\n this.serverUrl = await this._connectToNgrokAsync({ timeout });\n\n debug('Tunnel URL:', this.serverUrl);\n Log.log('Tunnel ready.');\n }\n\n /** Stop the ngrok process if it's running. */\n public async stopAsync(): Promise<void> {\n debug('Stopping Tunnel');\n\n await this.resolver.get()?.kill?.();\n this.serverUrl = null;\n }\n\n /** Exposed for testing. */\n async _connectToNgrokAsync(\n options: { timeout?: number } = {},\n attempts: number = 0\n ): Promise<string> {\n // Attempt to stop any hanging processes, this increases the chances of a successful connection.\n await this.stopAsync();\n\n // Get the instance quietly or assert otherwise.\n const instance = await this.resolver.resolveAsync({\n shouldPrompt: false,\n autoInstall: false,\n });\n\n // TODO(Bacon): Consider dropping the timeout functionality:\n // https://github.com/expo/expo/pull/16556#discussion_r822307373\n const results = await resolveWithTimeout(\n () => this.connectToNgrokInternalAsync(instance, attempts),\n {\n timeout: options.timeout ?? TUNNEL_TIMEOUT,\n errorMessage: 'ngrok tunnel took too long to connect.',\n }\n );\n if (typeof results === 'string') {\n return results;\n }\n\n // Wait 100ms and then try again\n await delayAsync(100);\n\n return this._connectToNgrokAsync(options, attempts + 1);\n }\n\n private async _getConnectionPropsAsync(): Promise<{ hostname?: string; subdomain?: string }> {\n const userDefinedSubdomain = env.EXPO_TUNNEL_SUBDOMAIN;\n if (userDefinedSubdomain) {\n const subdomain =\n typeof userDefinedSubdomain === 'string'\n ? userDefinedSubdomain\n : await this._getProjectSubdomainAsync();\n debug('Subdomain:', subdomain);\n return { subdomain };\n } else {\n const hostname = await this._getProjectHostnameAsync();\n debug('Hostname:', hostname);\n return { hostname };\n }\n }\n\n private async connectToNgrokInternalAsync(\n instance: NgrokInstance,\n attempts: number = 0\n ): Promise<string | false> {\n try {\n // Global config path.\n const configPath = path.join(getSettingsDirectory(), 'ngrok.yml');\n debug('Global config path:', configPath);\n const urlProps = await this._getConnectionPropsAsync();\n\n const url = await instance.connect({\n ...urlProps,\n authtoken: NGROK_CONFIG.authToken,\n configPath,\n onStatusChange(status) {\n if (status === 'closed') {\n Log.error(\n chalk.red(\n 'Tunnel connection has been closed. This is often related to intermittent connection problems with the Ngrok servers. Restart the dev server to try connecting to Ngrok again.'\n ) + chalk.gray('\\nCheck the Ngrok status page for outages: https://status.ngrok.com/')\n );\n } else if (status === 'connected') {\n Log.log('Tunnel connected.');\n }\n },\n port: this.port,\n });\n return url;\n } catch (error: any) {\n const assertNgrok = () => {\n if (isNgrokClientError(error)) {\n throw new CommandError(\n 'NGROK_CONNECT',\n [\n error.body.msg,\n error.body.details?.err,\n chalk.gray('Check the Ngrok status page for outages: https://status.ngrok.com/'),\n ]\n .filter(Boolean)\n .join('\\n\\n')\n );\n }\n throw new CommandError(\n 'NGROK_CONNECT',\n error.toString() +\n chalk.gray('\\nCheck the Ngrok status page for outages: https://status.ngrok.com/')\n );\n };\n\n // Attempt to connect 3 times\n if (attempts >= 2) {\n assertNgrok();\n }\n\n // Attempt to fix the issue\n if (isNgrokClientError(error) && error.body.error_code === 103) {\n // Assert early if a custom subdomain is used since it cannot\n // be changed and retried. If the tunnel subdomain is a boolean\n // then we can reset the randomness and try again.\n if (typeof env.EXPO_TUNNEL_SUBDOMAIN === 'string') {\n assertNgrok();\n }\n // Change randomness to avoid conflict if killing ngrok doesn't help\n await this._resetProjectRandomnessAsync();\n }\n\n return false;\n }\n }\n\n private async getProjectRandomnessAsync() {\n const { urlRandomness: randomness } = await ProjectSettings.readAsync(this.projectRoot);\n if (randomness && /^[A-Za-z0-9]/.test(randomness)) {\n return randomness;\n }\n return await this._resetProjectRandomnessAsync();\n }\n\n async _resetProjectRandomnessAsync() {\n let randomness: string;\n do {\n randomness = crypto.randomBytes(5).toString('base64url');\n } while (randomness.startsWith('_')); // _ is an invalid character for a hostname\n\n await ProjectSettings.setAsync(this.projectRoot, { urlRandomness: randomness });\n debug('Resetting project randomness:', randomness);\n return randomness;\n }\n}\n"],"names":["AsyncNgrok","debug","require","NGROK_CONFIG","authToken","domain","TUNNEL_TIMEOUT","constructor","projectRoot","port","serverUrl","resolver","NgrokResolver","getActiveUrl","_getIdentifyingUrlSegmentsAsync","user","getUserAsync","__typename","CommandError","username","getActorDisplayName","getProjectRandomnessAsync","slugify","remove","String","_getProjectHostnameAsync","join","_getProjectSubdomainAsync","startAsync","timeout","resolveAsync","prefersGlobalInstall","hasAdbReverseAsync","startAdbReverseAsync","_connectToNgrokAsync","Log","log","stopAsync","get","kill","options","attempts","instance","shouldPrompt","autoInstall","results","resolveWithTimeout","connectToNgrokInternalAsync","errorMessage","delayAsync","_getConnectionPropsAsync","userDefinedSubdomain","env","EXPO_TUNNEL_SUBDOMAIN","subdomain","hostname","configPath","path","getSettingsDirectory","urlProps","url","connect","authtoken","onStatusChange","status","error","chalk","red","gray","assertNgrok","isNgrokClientError","body","msg","details","err","filter","Boolean","toString","error_code","_resetProjectRandomnessAsync","urlRandomness","randomness","ProjectSettings","readAsync","test","crypto","randomBytes","startsWith","setAsync"],"mappings":";;;;+BAwBaA;;;eAAAA;;;;gEAxBK;;;;;;;gEACC;;;;;;;iEACG;;;;;;;gEACF;;;;;;8BAEiB;sBACa;6DAC7B;uBAC0B;qBAC3B;wBACS;+BACoC;4BACR;0BACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEhC,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MAAMC,eAAe;IACnBC,WAAW;IACXC,QAAQ;AACV;AAEA,MAAMC,iBAAiB,KAAK;AAErB,MAAMN;IAOXO,YACE,AAAQC,WAAmB,EAC3B,AAAQC,IAAY,CACpB;aAFQD,cAAAA;aACAC,OAAAA;aAJFC,YAA2B;QAMjC,IAAI,CAACC,QAAQ,GAAG,IAAIC,4BAAa,CAACJ;IACpC;IAEOK,eAA8B;QACnC,OAAO,IAAI,CAACH,SAAS;IACvB;IAEA,yBAAyB,GACzB,MAAMI,k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QACT;IACF;IAEA,MAAc1D,4BAA4B;QACxC,MAAM,EAAE2D,eAAeC,UAAU,EAAE,GAAG,MAAMC,yBAAe,CAACC,SAAS,CAAC,IAAI,CAAC3E,WAAW;QACtF,IAAIyE,cAAc,eAAeG,IAAI,CAACH,aAAa;YACjD,OAAOA;QACT;QACA,OAAO,MAAM,IAAI,CAACF,4BAA4B;IAChD;IAEA,MAAMA,+BAA+B;QACnC,IAAIE;QACJ,GAAG;YACDA,aAAaI,iBAAM,CAACC,WAAW,CAAC,GAAGT,QAAQ,CAAC;QAC9C,QAASI,WAAWM,UAAU,CAAC,MAAM,CAAC,2CAA2C;QAEjF,MAAML,yBAAe,CAACM,QAAQ,CAAC,IAAI,CAAChF,WAAW,EAAE;YAAEwE,eAAeC;QAAW;QAC7EhF,MAAM,iCAAiCgF;QACvC,OAAOA;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../src/start/server/AsyncNgrok.ts"],"sourcesContent":["import chalk from 'chalk';\nimport crypto from 'crypto';\nimport * as path from 'path';\nimport slugify from 'slugify';\n\nimport { getSettingsDirectory } from '../../api/user/UserSettings';\nimport { getActorDisplayName, getUserAsync } from '../../api/user/user';\nimport * as Log from '../../log';\nimport { delayAsync, resolveWithTimeout } from '../../utils/delay';\nimport { env } from '../../utils/env';\nimport { CommandError } from '../../utils/errors';\nimport { isNgrokClientError, NgrokInstance, NgrokResolver } from '../doctor/ngrok/NgrokResolver';\nimport { hasAdbReverseAsync, startAdbReverseAsync } from '../platforms/android/adbReverse';\nimport { ProjectSettings } from '../project/settings';\n\nconst debug = require('debug')('expo:start:server:ngrok') as typeof console.log;\n\nconst NGROK_CONFIG = {\n authToken: '5W1bR67GNbWcXqmxZzBG1_56GezNeaX6sSRvn8npeQ8',\n domain: 'exp.direct',\n};\n\nconst TUNNEL_TIMEOUT = 10 * 1000;\n\nexport class AsyncNgrok {\n /** Resolves the best instance of ngrok, exposed for testing. */\n resolver: NgrokResolver;\n\n /** Info about the currently running instance of ngrok. */\n private serverUrl: string | null = null;\n\n constructor(\n private projectRoot: string,\n private port: number\n ) {\n this.resolver = new NgrokResolver(projectRoot);\n }\n\n public getActiveUrl(): string | null {\n return this.serverUrl;\n }\n\n /** Exposed for testing. */\n async _getIdentifyingUrlSegmentsAsync(): Promise<string[]> {\n const user = await getUserAsync();\n if (user?.__typename === 'Robot') {\n throw new CommandError('NGROK_ROBOT', 'Cannot use ngrok with a robot user.');\n }\n const username = getActorDisplayName(user);\n\n return [\n // NOTE: https://github.com/expo/expo/pull/16556#discussion_r822944286\n await this.getProjectRandomnessAsync(),\n // Strip out periods from the username to avoid subdomain issues with SSL certificates.\n slugify(username, { remove: /\\./ }),\n // Use the port to distinguish between multiple tunnels (webpack, metro).\n String(this.port),\n ];\n }\n\n /** Exposed for testing. */\n async _getProjectHostnameAsync(): Promise<string> {\n return `${(await this._getIdentifyingUrlSegmentsAsync()).join('-')}.${NGROK_CONFIG.domain}`;\n }\n\n /** Exposed for testing. */\n async _getProjectSubdomainAsync(): Promise<string> {\n return (await this._getIdentifyingUrlSegmentsAsync()).join('-');\n }\n\n /** Start ngrok on the given port for the project. */\n async startAsync({ timeout }: { timeout?: number } = {}): Promise<void> {\n // Ensure the instance is loaded first, this can linger so we should run it before the timeout.\n await this.resolver.resolveAsync({\n // For now, prefer global install since the package has native code (harder to install) and doesn't change very often.\n prefersGlobalInstall: true,\n });\n\n // NOTE(EvanBacon): If the user doesn't have ADB installed,\n // then skip attempting to reverse the port.\n if (hasAdbReverseAsync()) {\n // Ensure ADB reverse is running.\n if (!(await startAdbReverseAsync([this.port]))) {\n // TODO: Better error message.\n throw new CommandError(\n 'NGROK_ADB',\n `Cannot start tunnel URL because \\`adb reverse\\` failed for the connected Android device(s).`\n );\n }\n }\n\n this.serverUrl = await this._connectToNgrokAsync({ timeout });\n\n debug('Tunnel URL:', this.serverUrl);\n Log.log('Tunnel ready.');\n }\n\n /** Stop the ngrok process if it's running. */\n public async stopAsync(): Promise<void> {\n debug('Stopping Tunnel');\n\n await this.resolver.get()?.kill?.();\n this.serverUrl = null;\n }\n\n /** Exposed for testing. */\n async _connectToNgrokAsync(\n options: { timeout?: number } = {},\n attempts: number = 0\n ): Promise<string> {\n // Attempt to stop any hanging processes, this increases the chances of a successful connection.\n await this.stopAsync();\n\n // Get the instance quietly or assert otherwise.\n const instance = await this.resolver.resolveAsync({\n shouldPrompt: false,\n autoInstall: false,\n });\n\n // TODO(Bacon): Consider dropping the timeout functionality:\n // https://github.com/expo/expo/pull/16556#discussion_r822307373\n const results = await resolveWithTimeout(\n () => this.connectToNgrokInternalAsync(instance, attempts),\n {\n timeout: options.timeout ?? TUNNEL_TIMEOUT,\n errorMessage: 'ngrok tunnel took too long to connect.',\n }\n );\n if (typeof results === 'string') {\n return results;\n }\n\n // Wait 100ms and then try again\n await delayAsync(100);\n\n return this._connectToNgrokAsync(options, attempts + 1);\n }\n\n private async _getConnectionPropsAsync(): Promise<{ hostname?: string; subdomain?: string }> {\n const userDefinedSubdomain = env.EXPO_TUNNEL_SUBDOMAIN;\n if (userDefinedSubdomain) {\n const subdomain =\n typeof userDefinedSubdomain === 'string'\n ? userDefinedSubdomain\n : await this._getProjectSubdomainAsync();\n debug('Subdomain:', subdomain);\n return { subdomain };\n } else {\n const hostname = await this._getProjectHostnameAsync();\n debug('Hostname:', hostname);\n return { hostname };\n }\n }\n\n private async connectToNgrokInternalAsync(\n instance: NgrokInstance,\n attempts: number = 0\n ): Promise<string | false> {\n try {\n // Global config path.\n const configPath = path.join(getSettingsDirectory(), 'ngrok.yml');\n debug('Global config path:', configPath);\n const urlProps = await this._getConnectionPropsAsync();\n\n const url = await instance.connect({\n ...urlProps,\n authtoken: NGROK_CONFIG.authToken,\n configPath,\n onStatusChange(status) {\n if (status === 'closed') {\n Log.error(\n chalk.red(\n 'Tunnel connection has been closed. This is often related to intermittent connection issues between the dev server and ngrok. Restart the dev server to try connecting to ngrok again.'\n ) + chalk.gray('\\nCheck the Ngrok status page for outages: https://status.ngrok.com/')\n );\n } else if (status === 'connected') {\n Log.log('Tunnel connected.');\n }\n },\n port: this.port,\n });\n return url;\n } catch (error: any) {\n const assertNgrok = () => {\n if (isNgrokClientError(error)) {\n throw new CommandError(\n 'NGROK_CONNECT',\n [\n error.body.msg,\n error.body.details?.err,\n chalk.gray('Check the Ngrok status page for outages: https://status.ngrok.com/'),\n ]\n .filter(Boolean)\n .join('\\n\\n')\n );\n }\n throw new CommandError(\n 'NGROK_CONNECT',\n error.toString() +\n chalk.gray('\\nCheck the Ngrok status page for outages: https://status.ngrok.com/')\n );\n };\n\n // Attempt to connect 3 times\n if (attempts >= 2) {\n assertNgrok();\n }\n\n // Attempt to fix the issue\n if (isNgrokClientError(error) && error.body.error_code === 103) {\n // Assert early if a custom subdomain is used since it cannot\n // be changed and retried. If the tunnel subdomain is a boolean\n // then we can reset the randomness and try again.\n if (typeof env.EXPO_TUNNEL_SUBDOMAIN === 'string') {\n assertNgrok();\n }\n // Change randomness to avoid conflict if killing ngrok doesn't help\n await this._resetProjectRandomnessAsync();\n }\n\n return false;\n }\n }\n\n private async getProjectRandomnessAsync() {\n const { urlRandomness: randomness } = await ProjectSettings.readAsync(this.projectRoot);\n if (randomness && /^[A-Za-z0-9]/.test(randomness)) {\n return randomness;\n }\n return await this._resetProjectRandomnessAsync();\n }\n\n async _resetProjectRandomnessAsync() {\n let randomness: string;\n do {\n randomness = crypto.randomBytes(5).toString('base64url');\n } while (randomness.startsWith('_')); // _ is an invalid character for a hostname\n\n await ProjectSettings.setAsync(this.projectRoot, { urlRandomness: randomness });\n debug('Resetting project randomness:', randomness);\n return randomness;\n }\n}\n"],"names":["AsyncNgrok","debug","require","NGROK_CONFIG","authToken","domain","TUNNEL_TIMEOUT","constructor","projectRoot","port","serverUrl","resolver","NgrokResolver","getActiveUrl","_getIdentifyingUrlSegmentsAsync","user","getUserAsync","__typename","CommandError","username","getActorDisplayName","getProjectRandomnessAsync","slugify","remove","String","_getProjectHostnameAsync","join","_getProjectSubdomainAsync","startAsync","timeout","resolveAsync","prefersGlobalInstall","hasAdbReverseAsync","startAdbReverseAsync","_connectToNgrokAsync","Log","log","stopAsync","get","kill","options","attempts","instance","shouldPrompt","autoInstall","results","resolveWithTimeout","connectToNgrokInternalAsync","errorMessage","delayAsync","_getConnectionPropsAsync","userDefinedSubdomain","env","EXPO_TUNNEL_SUBDOMAIN","subdomain","hostname","configPath","path","getSettingsDirectory","urlProps","url","connect","authtoken","onStatusChange","status","error","chalk","red","gray","assertNgrok","isNgrokClientError","body","msg","details","err","filter","Boolean","toString","error_code","_resetProjectRandomnessAsync","urlRandomness","randomness","ProjectSettings","readAsync","test","crypto","randomBytes","startsWith","setAsync"],"mappings":";;;;+BAwBaA;;;eAAAA;;;;gEAxBK;;;;;;;gEACC;;;;;;;iEACG;;;;;;;gEACF;;;;;;8BAEiB;sBACa;6DAC7B;uBAC0B;qBAC3B;wBACS;+BACoC;4BACR;0BACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEhC,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MAAMC,eAAe;IACnBC,WAAW;IACXC,QAAQ;AACV;AAEA,MAAMC,iBAAiB,KAAK;AAErB,MAAMN;IAOXO,YACE,AAAQC,WAAmB,EAC3B,AAAQC,IAAY,CACpB;aAFQD,cAAAA;aACAC,OAAAA;aAJFC,YAA2B;QAMjC,IAAI,CAACC,QAAQ,GAAG,IAAIC,4BAAa,CAACJ;IACpC;IAEOK,eAA8B;QACnC,OAAO,IAAI,CAACH,SAAS;IACvB;IAEA,yBAAyB,GACzB,MAAMI,kCAAqD;QACzD,MAAMC,OAAO,MAAMC,IAAAA,kBAAY;QAC/B,IAAID,CAAAA,wBAAAA,KAAME,UAAU,MAAK,SAAS;YAChC,MAAM,IAAIC,oBAAY,CAAC,eAAe;QACxC;QACA,MAAMC,WAAWC,IAAAA,yBAAmB,EAACL;QAErC,OAAO;YACL,sEAAsE;YACtE,MAAM,IAAI,CAACM,yBAAy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A,MAAMA,+BAA+B;QACnC,IAAIE;QACJ,GAAG;YACDA,aAAaI,iBAAM,CAACC,WAAW,CAAC,GAAGT,QAAQ,CAAC;QAC9C,QAASI,WAAWM,UAAU,CAAC,MAAM,CAAC,2CAA2C;QAEjF,MAAML,yBAAe,CAACM,QAAQ,CAAC,IAAI,CAAChF,WAAW,EAAE;YAAEwE,eAAeC;QAAW;QAC7EhF,MAAM,iCAAiCgF;QACvC,OAAOA;IACT;AACF"}
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ _dependenciesToRegex: function() {
13
+ return _dependenciesToRegex;
14
+ },
15
+ createStickyModuleResolver: function() {
16
+ return createStickyModuleResolver;
17
+ },
18
+ createStickyModuleResolverInput: function() {
19
+ return createStickyModuleResolverInput;
20
+ }
21
+ });
22
+ const debug = require('debug')('expo:start:server:metro:sticky-resolver');
23
+ const AUTOLINKING_PLATFORMS = [
24
+ 'android',
25
+ 'ios',
26
+ 'web'
27
+ ];
28
+ const escapeDependencyName = (dependency)=>dependency.replace(/[*.?()[\]]/g, (x)=>`\\${x}`);
29
+ const _dependenciesToRegex = (dependencies)=>new RegExp(`^(${dependencies.map(escapeDependencyName).join('|')})($|/.*)`);
30
+ /** Creates a function to load a dependency of the `expo` package */ const createExpoDependencyLoader = (request)=>{
31
+ let mod;
32
+ return ()=>{
33
+ if (!mod) {
34
+ const expoPath = require.resolve('expo/package.json');
35
+ const autolinkingPath = require.resolve(request, {
36
+ paths: [
37
+ expoPath
38
+ ]
39
+ });
40
+ return mod = require(autolinkingPath);
41
+ }
42
+ return mod;
43
+ };
44
+ };
45
+ const getAutolinkingModule = createExpoDependencyLoader('expo-modules-autolinking/exports');
46
+ const getReactNativeConfigModule = createExpoDependencyLoader('expo-modules-autolinking/build/reactNativeConfig');
47
+ const getAutolinkingOptions = async (projectRoot, platform)=>{
48
+ const autolinking = getAutolinkingModule();
49
+ return await autolinking.mergeLinkingOptionsAsync({
50
+ searchPaths: [],
51
+ projectRoot,
52
+ platform: platform === 'ios' ? 'apple' : platform,
53
+ onlyProjectDeps: true,
54
+ silent: true
55
+ });
56
+ };
57
+ const getAutolinkingResolutions = async (opts)=>{
58
+ const autolinking = getAutolinkingModule();
59
+ const resolvedModules = await autolinking.findModulesAsync(opts);
60
+ return Object.fromEntries(Object.entries(resolvedModules).map(([key, entry])=>[
61
+ key,
62
+ entry.path
63
+ ]));
64
+ };
65
+ const getReactNativeConfigResolutions = async (opts)=>{
66
+ const reactNativeConfigModule = getReactNativeConfigModule();
67
+ const configResult = await reactNativeConfigModule.createReactNativeConfigAsync({
68
+ ...opts,
69
+ // NOTE(@kitten): web will use ios here. This is desired since this function only accepts android|ios.
70
+ // However, we'd still like to sticky resolve dependencies for web
71
+ platform: opts.platform === 'android' ? 'android' : 'ios',
72
+ // TODO(@kitten): Unclear if this should be populated or directly relates to sticky resolution
73
+ transitiveLinkingDependencies: []
74
+ });
75
+ return Object.fromEntries(Object.entries(configResult.dependencies).map(([key, entry])=>[
76
+ key,
77
+ entry.root
78
+ ]));
79
+ };
80
+ const getPlatformModuleDescription = async (projectRoot, platform)=>{
81
+ const searchOptions = await getAutolinkingOptions(projectRoot, platform);
82
+ const autolinkingResolutions$ = getAutolinkingResolutions(searchOptions);
83
+ const reactNativeConfigResolutions$ = getReactNativeConfigResolutions(searchOptions);
84
+ const resolvedModulePaths = {
85
+ ...await reactNativeConfigResolutions$,
86
+ ...await autolinkingResolutions$
87
+ };
88
+ const resolvedModuleNames = Object.keys(resolvedModulePaths);
89
+ debug(`Sticky resolution for ${platform} registered ${resolvedModuleNames.length} resolutions:`, resolvedModuleNames);
90
+ return {
91
+ platform,
92
+ moduleTestRe: _dependenciesToRegex(resolvedModuleNames),
93
+ resolvedModulePaths
94
+ };
95
+ };
96
+ async function createStickyModuleResolverInput({ platforms, projectRoot }) {
97
+ return Object.fromEntries(await Promise.all(platforms.filter((platform)=>AUTOLINKING_PLATFORMS.includes(platform)).map(async (platform)=>{
98
+ const platformModuleDescription = await getPlatformModuleDescription(projectRoot, platform);
99
+ return [
100
+ platformModuleDescription.platform,
101
+ platformModuleDescription
102
+ ];
103
+ })));
104
+ }
105
+ function createStickyModuleResolver(input, { getStrictResolver }) {
106
+ if (!input) {
107
+ return undefined;
108
+ }
109
+ const fileSpecifierRe = /^[\\/]|^\.\.?(?:$|[\\/])/i;
110
+ const isAutolinkingPlatform = (platform)=>!!platform && input[platform] != null;
111
+ return function requestStickyModule(immutableContext, moduleName, platform) {
112
+ if (!isAutolinkingPlatform(platform)) {
113
+ return null;
114
+ } else if (fileSpecifierRe.test(moduleName)) {
115
+ return null;
116
+ }
117
+ const moduleDescription = input[platform];
118
+ const moduleMatch = moduleDescription.moduleTestRe.exec(moduleName);
119
+ if (moduleMatch) {
120
+ const resolvedModulePath = moduleDescription.resolvedModulePaths[moduleMatch[1]] || moduleName;
121
+ // We instead resolve as if it was a dependency from within the module (self-require/import)
122
+ const context = {
123
+ ...immutableContext,
124
+ nodeModulesPaths: [
125
+ resolvedModulePath
126
+ ],
127
+ originModulePath: resolvedModulePath
128
+ };
129
+ const res = getStrictResolver(context, platform)(moduleName);
130
+ debug(`Sticky resolution for ${platform}: ${moduleName} -> ${resolvedModulePath}`);
131
+ return res;
132
+ }
133
+ return null;
134
+ };
135
+ }
136
+
137
+ //# sourceMappingURL=createExpoStickyResolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/createExpoStickyResolver.ts"],"sourcesContent":["import type { SearchOptions as AutolinkingSearchOptions } from 'expo-modules-autolinking/exports';\nimport type { ResolutionContext } from 'metro-resolver';\n\nimport type { StrictResolverFactory } from './withMetroMultiPlatform';\nimport type { ExpoCustomMetroResolver } from './withMetroResolvers';\n\nconst debug = require('debug')('expo:start:server:metro:sticky-resolver') as typeof console.log;\n\nconst AUTOLINKING_PLATFORMS = ['android', 'ios', 'web'] as const;\ntype AutolinkingPlatform = (typeof AUTOLINKING_PLATFORMS)[number];\n\nconst escapeDependencyName = (dependency: string) =>\n dependency.replace(/[*.?()[\\]]/g, (x) => `\\\\${x}`);\n\n/** Converts a list of module names to a regex that may either match bare module names or sub-modules of modules */\nexport const _dependenciesToRegex = (dependencies: string[]) =>\n new RegExp(`^(${dependencies.map(escapeDependencyName).join('|')})($|/.*)`);\n\n/** Creates a function to load a dependency of the `expo` package */\nconst createExpoDependencyLoader = <T>(request: string) => {\n let mod: T | undefined;\n return (): T => {\n if (!mod) {\n const expoPath = require.resolve('expo/package.json');\n const autolinkingPath = require.resolve(request, {\n paths: [expoPath],\n });\n return (mod = require(autolinkingPath));\n }\n return mod;\n };\n};\n\nconst getAutolinkingModule = createExpoDependencyLoader<\n typeof import('expo-modules-autolinking/exports')\n>('expo-modules-autolinking/exports');\n\nconst getReactNativeConfigModule = createExpoDependencyLoader<\n typeof import('expo-modules-autolinking/build/reactNativeConfig')\n>('expo-modules-autolinking/build/reactNativeConfig');\n\nconst getAutolinkingOptions = async (\n projectRoot: string,\n platform: AutolinkingPlatform\n): Promise<AutolinkingSearchOptions> => {\n const autolinking = getAutolinkingModule();\n return await autolinking.mergeLinkingOptionsAsync({\n searchPaths: [],\n projectRoot,\n platform: platform === 'ios' ? 'apple' : platform,\n onlyProjectDeps: true,\n silent: true,\n });\n};\n\nconst getAutolinkingResolutions = async (\n opts: AutolinkingSearchOptions\n): Promise<Record<string, string>> => {\n const autolinking = getAutolinkingModule();\n const resolvedModules = await autolinking.findModulesAsync(opts);\n return Object.fromEntries(\n Object.entries(resolvedModules).map(([key, entry]) => [key, entry.path])\n );\n};\n\nconst getReactNativeConfigResolutions = async (\n opts: AutolinkingSearchOptions\n): Promise<Record<string, string>> => {\n const reactNativeConfigModule = getReactNativeConfigModule();\n const configResult = await reactNativeConfigModule.createReactNativeConfigAsync({\n ...opts,\n // NOTE(@kitten): web will use ios here. This is desired since this function only accepts android|ios.\n // However, we'd still like to sticky resolve dependencies for web\n platform: opts.platform === 'android' ? 'android' : 'ios',\n // TODO(@kitten): Unclear if this should be populated or directly relates to sticky resolution\n transitiveLinkingDependencies: [],\n });\n return Object.fromEntries(\n Object.entries(configResult.dependencies).map(([key, entry]) => [key, entry.root])\n );\n};\n\ninterface PlatformModuleDescription {\n platform: AutolinkingPlatform;\n moduleTestRe: RegExp;\n resolvedModulePaths: Record<string, string>;\n}\n\nconst getPlatformModuleDescription = async (\n projectRoot: string,\n platform: AutolinkingPlatform\n): Promise<PlatformModuleDescription> => {\n const searchOptions = await getAutolinkingOptions(projectRoot, platform);\n const autolinkingResolutions$ = getAutolinkingResolutions(searchOptions);\n const reactNativeConfigResolutions$ = getReactNativeConfigResolutions(searchOptions);\n const resolvedModulePaths = {\n ...(await reactNativeConfigResolutions$),\n ...(await autolinkingResolutions$),\n };\n const resolvedModuleNames = Object.keys(resolvedModulePaths);\n debug(\n `Sticky resolution for ${platform} registered ${resolvedModuleNames.length} resolutions:`,\n resolvedModuleNames\n );\n return {\n platform,\n moduleTestRe: _dependenciesToRegex(resolvedModuleNames),\n resolvedModulePaths,\n };\n};\n\nexport type StickyModuleResolverInput = {\n [platform in AutolinkingPlatform]?: PlatformModuleDescription;\n};\n\nexport async function createStickyModuleResolverInput({\n platforms,\n projectRoot,\n}: {\n projectRoot: string;\n platforms: string[];\n}): Promise<StickyModuleResolverInput> {\n return Object.fromEntries(\n await Promise.all(\n platforms\n .filter((platform): platform is AutolinkingPlatform =>\n AUTOLINKING_PLATFORMS.includes(platform as any)\n )\n .map(async (platform) => {\n const platformModuleDescription = await getPlatformModuleDescription(\n projectRoot,\n platform\n );\n return [platformModuleDescription.platform, platformModuleDescription] as const;\n })\n )\n ) as StickyModuleResolverInput;\n}\n\nexport function createStickyModuleResolver(\n input: StickyModuleResolverInput | undefined,\n { getStrictResolver }: { getStrictResolver: StrictResolverFactory }\n): ExpoCustomMetroResolver | undefined {\n if (!input) {\n return undefined;\n }\n\n const fileSpecifierRe = /^[\\\\/]|^\\.\\.?(?:$|[\\\\/])/i;\n const isAutolinkingPlatform = (platform: string | null): platform is AutolinkingPlatform =>\n !!platform && (input as any)[platform] != null;\n\n return function requestStickyModule(immutableContext, moduleName, platform) {\n if (!isAutolinkingPlatform(platform)) {\n return null;\n } else if (fileSpecifierRe.test(moduleName)) {\n return null;\n }\n\n const moduleDescription = input[platform]!;\n const moduleMatch = moduleDescription.moduleTestRe.exec(moduleName);\n if (moduleMatch) {\n const resolvedModulePath =\n moduleDescription.resolvedModulePaths[moduleMatch[1]] || moduleName;\n // We instead resolve as if it was a dependency from within the module (self-require/import)\n const context: ResolutionContext = {\n ...immutableContext,\n nodeModulesPaths: [resolvedModulePath],\n originModulePath: resolvedModulePath,\n };\n const res = getStrictResolver(context, platform)(moduleName);\n debug(`Sticky resolution for ${platform}: ${moduleName} -> ${resolvedModulePath}`);\n return res;\n }\n\n return null;\n };\n}\n"],"names":["_dependenciesToRegex","createStickyModuleResolver","createStickyModuleResolverInput","debug","require","AUTOLINKING_PLATFORMS","escapeDependencyName","dependency","replace","x","dependencies","RegExp","map","join","createExpoDependencyLoader","request","mod","expoPath","resolve","autolinkingPath","paths","getAutolinkingModule","getReactNativeConfigModule","getAutolinkingOptions","projectRoot","platform","autolinking","mergeLinkingOptionsAsync","searchPaths","onlyProjectDeps","silent","getAutolinkingResolutions","opts","resolvedModules","findModulesAsync","Object","fromEntries","entries","key","entry","path","getReactNativeConfigResolutions","reactNativeConfigModule","configResult","createReactNativeConfigAsync","transitiveLinkingDependencies","root","getPlatformModuleDescription","searchOptions","autolinkingResolutions$","reactNativeConfigResolutions$","resolvedModulePaths","resolvedModuleNames","keys","length","moduleTestRe","platforms","Promise","all","filter","includes","platformModuleDescription","input","getStrictResolver","undefined","fileSpecifierRe","isAutolinkingPlatform","requestStickyModule","immutableContext","moduleName","test","moduleDescription","moduleMatch","exec","res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ACV,OAAOE;IACT;IAEA,MAAMC,kBAAkB;IACxB,MAAMC,wBAAwB,CAACzC,WAC7B,CAAC,CAACA,YAAY,AAACqC,KAAa,CAACrC,SAAS,IAAI;IAE5C,OAAO,SAAS0C,oBAAoBC,gBAAgB,EAAEC,UAAU,EAAE5C,QAAQ;QACxE,IAAI,CAACyC,sBAAsBzC,WAAW;YACpC,OAAO;QACT,OAAO,IAAIwC,gBAAgBK,IAAI,CAACD,aAAa;YAC3C,OAAO;QACT;QAEA,MAAME,oBAAoBT,KAAK,CAACrC,SAAS;QACzC,MAAM+C,cAAcD,kBAAkBhB,YAAY,CAACkB,IAAI,CAACJ;QACxD,IAAIG,aAAa;YACf,MAAME,qBACJH,kBAAkBpB,mBAAmB,CAACqB,WAAW,CAAC,EAAE,CAAC,IAAIH;YAC3D,4FAA4F;YAC5F,MAAMM,UAA6B;gBACjC,GAAGP,gBAAgB;gBACnBQ,kBAAkB;oBAACF;iBAAmB;gBACtCG,kBAAkBH;YACpB;YACA,MAAMI,MAAMf,kBAAkBY,SAASlD,UAAU4C;YACjDlE,MAAM,CAAC,sBAAsB,EAAEsB,SAAS,EAAE,EAAE4C,WAAW,IAAI,EAAEK,oBAAoB;YACjF,OAAOI;QACT;QAEA,OAAO;IACT;AACF"}
@@ -194,6 +194,7 @@ async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, ge
194
194
  exp,
195
195
  platformBundlers,
196
196
  isTsconfigPathsEnabled: ((_exp_experiments5 = exp.experiments) == null ? void 0 : _exp_experiments5.tsconfigPaths) ?? true,
197
+ isStickyResolverEnabled: _env.env.EXPO_USE_STICKY_RESOLVER,
197
198
  isFastResolverEnabled: _env.env.EXPO_USE_FAST_RESOLVER,
198
199
  isExporting,
199
200
  isReactCanaryEnabled,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport { getDefaultConfig, LoadOptions } from '@expo/metro-config';\nimport chalk from 'chalk';\nimport http from 'http';\nimport type Metro from 'metro';\nimport { ReadOnlyGraph } from 'metro';\nimport Bundler from 'metro/src/Bundler';\nimport type { TransformOptions } from 'metro/src/DeltaBundler/Worker';\nimport MetroHmrServer from 'metro/src/HmrServer';\nimport RevisionNotFoundError from 'metro/src/IncrementalBundler/RevisionNotFoundError';\nimport formatBundlingError from 'metro/src/lib/formatBundlingError';\nimport { loadConfig, resolveConfig, ConfigT } from 'metro-config';\nimport { Terminal } from 'metro-core';\nimport util from 'node:util';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// Wrap terminal and polyfill console.log so we can log during bundling without breaking the indicator.\nclass LogRespectingTerminal extends Terminal {\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream);\n\n const sendLog = (...args: any[]) => {\n this._logLines.push(\n // format args like console.log\n util.format(...args)\n );\n this._scheduleUpdate();\n\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n console.log = sendLog;\n console.info = sendLog;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (exp.experiments?.reactServerComponentRoutes || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n process.env.EXPO_USE_FAST_RESOLVER = '1';\n }\n\n const isReactCanaryEnabled =\n (exp.experiments?.reactServerComponentRoutes ||\n serverActionsEnabled ||\n exp.experiments?.reactCanary) ??\n false;\n\n if (isReactCanaryEnabled) {\n // The fast resolver is required for React canary to work as it can switch the node_modules location for react imports.\n process.env.EXPO_USE_FAST_RESOLVER = '1';\n }\n\n const serverRoot = getMetroServerRoot(projectRoot);\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n const hasConfig = await resolveConfig(options.config, projectRoot);\n let config: ConfigT = {\n ...(await loadConfig(\n { cwd: projectRoot, projectRoot, ...options },\n // If the project does not have a metro.config.js, then we use the default config.\n hasConfig.isEmpty ? getDefaultConfig(projectRoot) : undefined\n )),\n reporter: {\n update(event: any) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n // @ts-expect-error: Set the global require cycle ignore patterns for SSR bundles. This won't work with custom global prefixes, but we don't use those.\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n // @ts-expect-error: typed as readonly.\n config.transformer.publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n // @ts-expect-error: typed as readonly\n config.transformer.publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n if (exp.experiments?.reactCompiler) {\n Log.warn(`Experimental React Compiler is enabled.`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n\n if (serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isFastResolverEnabled: env.EXPO_USE_FAST_RESOLVER,\n isExporting,\n isReactCanaryEnabled,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: !!exp.experiments?.reactServerComponentRoutes,\n getMetroBundler,\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: Omit<LoadOptions, 'logger'>,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: Metro.Server;\n hmrServer: MetroHmrServer | null;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler() {\n return metro.getBundler().getBundler();\n },\n });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } =\n createMetroMiddleware(metroConfig);\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware(\n metroBundler,\n reporter\n );\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n // @ts-expect-error: can't mutate readonly config\n metroConfig.server.enhanceMiddleware = (metroMiddleware: any, server: Metro.Server) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n const { server, hmrServer, metro } = await runServer(\n metroBundler,\n metroConfig,\n {\n websocketEndpoints: {\n ...websocketEndpoints,\n ...createDevToolsPluginWebsocketEndpoint(),\n },\n watch: !isExporting && isWatchEnabled(),\n },\n {\n mockServer: isExporting,\n }\n );\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: Metro.Server, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n platform: graph.transformOptions.platform,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n // @ts-expect-error\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n // @ts-expect-error\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle: typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('metro/src/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (this: MetroHmrServer, group, options, changeEvent) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n platform: revision.graph.transformOptions.platform,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n // @ts-expect-error\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n if (\n transformOptions.customTransformOptions?.routerRoot &&\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n // Set to the default value.\n transformOptions.customTransformOptions.routerRoot = 'app';\n }\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","LogRespectingTerminal","Terminal","constructor","stream","sendLog","args","_logLines","push","util","format","_scheduleUpdate","flush","console","log","info","terminal","process","stdout","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","serverActionsEnabled","experiments","reactServerFunctions","env","EXPO_UNSTABLE_SERVER_FUNCTIONS","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","EXPO_USE_FAST_RESOLVER","isReactCanaryEnabled","reactCanary","serverRoot","getMetroServerRoot","terminalReporter","MetroTerminalReporter","hasConfig","resolveConfig","loadConfig","cwd","isEmpty","getDefaultConfig","undefined","reporter","update","event","globalThis","__requireCycleIgnorePatterns","resolver","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reactCompiler","Log","warn","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isFastResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","server","enhanceMiddleware","metroMiddleware","attachAtlasAsync","resetAtlasFile","hmrServer","runServer","createDevToolsPluginWebsocketEndpoint","watch","mockServer","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","path","sort","a","b","hmrJSBundle","require","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","error","formattedError","messageSocket","split","sep","join","dom","match","routerRoot","asyncRoutes","clientBoundaries","CI","chalk"],"mappings":";;;;;;;;;;;IAiLsBA,qBAAqB;eAArBA;;IA+QNC,cAAc;eAAdA;;IAlYMC,oBAAoB;eAApBA;;;;yBA9Dg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,CAAElE,CAAAA,SAASiE,KAAK,CAAC,0BAA0BjE,SAASiE,KAAK,CAAC,yBAAwB,GAClF;QACA,4BAA4B;QAC5BhE,iBAAiBG,sBAAsB,CAAC8D,UAAU,GAAG;IACvD;IACA,IACEjE,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyCkE,WAAW,KACpD,+IAA+I;IAC/I,CAAEnE,CAAAA,SAASiE,KAAK,CAAC,0BAA0BjE,SAASiE,KAAK,CAAC,yBAAwB,GAClF;QACA,OAAOhE,iBAAiBG,sBAAsB,CAAC+D,WAAW;IAC5D;IAEA,IACElE,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyCmE,gBAAgB,KACzD,2FAA2F;IAC3F,CAACpE,SAASiE,KAAK,CAAC,8BAChB;QACA,OAAOhE,iBAAiBG,sBAAsB,CAACgE,gBAAgB;IACjE;IAEA,OAAOnE;AACT;AAMO,SAAS7G;IACd,IAAI8B,QAAG,CAACmJ,EAAE,EAAE;QACVpH,QAAG,CAAC9C,GAAG,CACLmK,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAACpJ,QAAG,CAACmJ,EAAE;AAChB"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport { getDefaultConfig, LoadOptions } from '@expo/metro-config';\nimport chalk from 'chalk';\nimport http from 'http';\nimport type Metro from 'metro';\nimport { ReadOnlyGraph } from 'metro';\nimport Bundler from 'metro/src/Bundler';\nimport type { TransformOptions } from 'metro/src/DeltaBundler/Worker';\nimport MetroHmrServer from 'metro/src/HmrServer';\nimport RevisionNotFoundError from 'metro/src/IncrementalBundler/RevisionNotFoundError';\nimport formatBundlingError from 'metro/src/lib/formatBundlingError';\nimport { loadConfig, resolveConfig, ConfigT } from 'metro-config';\nimport { Terminal } from 'metro-core';\nimport util from 'node:util';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// Wrap terminal and polyfill console.log so we can log during bundling without breaking the indicator.\nclass LogRespectingTerminal extends Terminal {\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream);\n\n const sendLog = (...args: any[]) => {\n this._logLines.push(\n // format args like console.log\n util.format(...args)\n );\n this._scheduleUpdate();\n\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n console.log = sendLog;\n console.info = sendLog;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (exp.experiments?.reactServerComponentRoutes || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n process.env.EXPO_USE_FAST_RESOLVER = '1';\n }\n\n const isReactCanaryEnabled =\n (exp.experiments?.reactServerComponentRoutes ||\n serverActionsEnabled ||\n exp.experiments?.reactCanary) ??\n false;\n\n if (isReactCanaryEnabled) {\n // The fast resolver is required for React canary to work as it can switch the node_modules location for react imports.\n process.env.EXPO_USE_FAST_RESOLVER = '1';\n }\n\n const serverRoot = getMetroServerRoot(projectRoot);\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n const hasConfig = await resolveConfig(options.config, projectRoot);\n let config: ConfigT = {\n ...(await loadConfig(\n { cwd: projectRoot, projectRoot, ...options },\n // If the project does not have a metro.config.js, then we use the default config.\n hasConfig.isEmpty ? getDefaultConfig(projectRoot) : undefined\n )),\n reporter: {\n update(event: any) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n // @ts-expect-error: Set the global require cycle ignore patterns for SSR bundles. This won't work with custom global prefixes, but we don't use those.\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n // @ts-expect-error: typed as readonly.\n config.transformer.publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n // @ts-expect-error: typed as readonly\n config.transformer.publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n if (exp.experiments?.reactCompiler) {\n Log.warn(`Experimental React Compiler is enabled.`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n\n if (serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isStickyResolverEnabled: env.EXPO_USE_STICKY_RESOLVER,\n isFastResolverEnabled: env.EXPO_USE_FAST_RESOLVER,\n isExporting,\n isReactCanaryEnabled,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: !!exp.experiments?.reactServerComponentRoutes,\n getMetroBundler,\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: Omit<LoadOptions, 'logger'>,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: Metro.Server;\n hmrServer: MetroHmrServer | null;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler() {\n return metro.getBundler().getBundler();\n },\n });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } =\n createMetroMiddleware(metroConfig);\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware(\n metroBundler,\n reporter\n );\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n // @ts-expect-error: can't mutate readonly config\n metroConfig.server.enhanceMiddleware = (metroMiddleware: any, server: Metro.Server) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n const { server, hmrServer, metro } = await runServer(\n metroBundler,\n metroConfig,\n {\n websocketEndpoints: {\n ...websocketEndpoints,\n ...createDevToolsPluginWebsocketEndpoint(),\n },\n watch: !isExporting && isWatchEnabled(),\n },\n {\n mockServer: isExporting,\n }\n );\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: Metro.Server, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n platform: graph.transformOptions.platform,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n // @ts-expect-error\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n // @ts-expect-error\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle: typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('metro/src/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (this: MetroHmrServer, group, options, changeEvent) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n platform: revision.graph.transformOptions.platform,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n // @ts-expect-error\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n if (\n transformOptions.customTransformOptions?.routerRoot &&\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n // Set to the default value.\n transformOptions.customTransformOptions.routerRoot = 'app';\n }\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","LogRespectingTerminal","Terminal","constructor","stream","sendLog","args","_logLines","push","util","format","_scheduleUpdate","flush","console","log","info","terminal","process","stdout","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","serverActionsEnabled","experiments","reactServerFunctions","env","EXPO_UNSTABLE_SERVER_FUNCTIONS","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","EXPO_USE_FAST_RESOLVER","isReactCanaryEnabled","reactCanary","serverRoot","getMetroServerRoot","terminalReporter","MetroTerminalReporter","hasConfig","resolveConfig","loadConfig","cwd","isEmpty","getDefaultConfig","undefined","reporter","update","event","globalThis","__requireCycleIgnorePatterns","resolver","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reactCompiler","Log","warn","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isStickyResolverEnabled","EXPO_USE_STICKY_RESOLVER","isFastResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","server","enhanceMiddleware","metroMiddleware","attachAtlasAsync","resetAtlasFile","hmrServer","runServer","createDevToolsPluginWebsocketEndpoint","watch","mockServer","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","path","sort","a","b","hmrJSBundle","require","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","error","formattedError","messageSocket","split","sep","join","dom","match","routerRoot","asyncRoutes","clientBoundaries","CI","chalk"],"mappings":";;;;;;;;;;;IAkLsBA,qBAAqB;eAArBA;;IA+QNC,cAAc;eAAdA;;IAnYMC,oBAAoB;eAApBA;;;;yBA9DgB;;;;;;;yBACH;;;;;;;yBACW;;;;;;;gEAC5B;;;;;;;gEAOgB;;;;;;;gEACF;;;;;;;yBACmB;;;;;;;yBAC1B;;;;;;;gEACR;;;;;;;gEACA;;;;;;iDAEqC;uCAEhB;6BACL;uCACK;uCACA;+BACZ;wCACkB;qBACxB;qBACA;wBACS;gCACQ;6CACO;2BACV;kCACE;;;;;;AAOpC,uGAAuG;AACvG,MAAMC,8B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A+I;IAC/I,CAAEnE,CAAAA,SAASiE,KAAK,CAAC,0BAA0BjE,SAASiE,KAAK,CAAC,yBAAwB,GAClF;QACA,OAAOhE,iBAAiBG,sBAAsB,CAAC+D,WAAW;IAC5D;IAEA,IACElE,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyCmE,gBAAgB,KACzD,2FAA2F;IAC3F,CAACpE,SAASiE,KAAK,CAAC,8BAChB;QACA,OAAOhE,iBAAiBG,sBAAsB,CAACgE,gBAAgB;IACjE;IAEA,OAAOnE;AACT;AAMO,SAAS/G;IACd,IAAI8B,QAAG,CAACqJ,EAAE,EAAE;QACVtH,QAAG,CAAC9C,GAAG,CACLqK,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAACtJ,QAAG,CAACqJ,EAAE;AAChB"}
@@ -64,6 +64,7 @@ function _resolvefrom() {
64
64
  }
65
65
  const _createExpoFallbackResolver = require("./createExpoFallbackResolver");
66
66
  const _createExpoMetroResolver = require("./createExpoMetroResolver");
67
+ const _createExpoStickyResolver = require("./createExpoStickyResolver");
67
68
  const _externals = require("./externals");
68
69
  const _metroErrors = require("./metroErrors");
69
70
  const _metroVirtualModules = require("./metroVirtualModules");
@@ -183,7 +184,7 @@ function getNodejsExtensions(srcExts) {
183
184
  nodejsSourceExtensions.splice(jsIndex + 1, 0, ...mjsExts);
184
185
  return nodejsSourceExtensions;
185
186
  }
186
- function withExtendedResolver(config, { tsconfig, isTsconfigPathsEnabled, isFastResolverEnabled, isExporting, isReactCanaryEnabled, isReactServerComponentsEnabled, getMetroBundler }) {
187
+ function withExtendedResolver(config, { tsconfig, stickyModuleResolverInput, isTsconfigPathsEnabled, isFastResolverEnabled, isExporting, isReactCanaryEnabled, isReactServerComponentsEnabled, getMetroBundler }) {
187
188
  var _config_resolver, _config_resolver1, _config_resolver2, _config_resolver3, _config_serializer_createModuleIdFactory, _config_serializer;
188
189
  if (isReactServerComponentsEnabled) {
189
190
  _log.Log.warn(`React Server Components (beta) is enabled.`);
@@ -194,6 +195,9 @@ function withExtendedResolver(config, { tsconfig, isTsconfigPathsEnabled, isFast
194
195
  if (isFastResolverEnabled) {
195
196
  _log.Log.log(_chalk().default.dim`Fast resolver is enabled.`);
196
197
  }
198
+ if (stickyModuleResolverInput) {
199
+ _log.Log.log(_chalk().default.dim`Sticky resolver is enabled.`);
200
+ }
197
201
  const defaultResolver = _metroresolver().resolve;
198
202
  const resolver = isFastResolverEnabled ? (0, _createExpoMetroResolver.createFastResolver)({
199
203
  preserveSymlinks: true,
@@ -513,6 +517,9 @@ function withExtendedResolver(config, { tsconfig, isTsconfigPathsEnabled, isFast
513
517
  }
514
518
  return null;
515
519
  },
520
+ (0, _createExpoStickyResolver.createStickyModuleResolver)(stickyModuleResolverInput, {
521
+ getStrictResolver
522
+ }),
516
523
  // TODO: Reduce these as much as possible in the future.
517
524
  // Complex post-resolution rewrites.
518
525
  function requestPostRewrites(context, moduleName, platform) {
@@ -672,7 +679,7 @@ function shouldAliasModule(input, alias) {
672
679
  var _input_result, _input_result1;
673
680
  return input.platform === alias.platform && ((_input_result = input.result) == null ? void 0 : _input_result.type) === 'sourceFile' && typeof ((_input_result1 = input.result) == null ? void 0 : _input_result1.filePath) === 'string' && normalizeSlashes(input.result.filePath).endsWith(alias.output);
674
681
  }
675
- async function withMetroMultiPlatformAsync(projectRoot, { config, exp, platformBundlers, isTsconfigPathsEnabled, isFastResolverEnabled, isExporting, isReactCanaryEnabled, isNamedRequiresEnabled, isReactServerComponentsEnabled, getMetroBundler }) {
682
+ async function withMetroMultiPlatformAsync(projectRoot, { config, exp, platformBundlers, isTsconfigPathsEnabled, isStickyResolverEnabled, isFastResolverEnabled, isExporting, isReactCanaryEnabled, isNamedRequiresEnabled, isReactServerComponentsEnabled, getMetroBundler }) {
676
683
  if (isNamedRequiresEnabled) {
677
684
  debug('Using Expo metro require runtime.');
678
685
  // Change the default metro-runtime to a custom one that supports bundle splitting.
@@ -721,7 +728,15 @@ async function withMetroMultiPlatformAsync(projectRoot, { config, exp, platformB
721
728
  config = withWebPolyfills(config, {
722
729
  getMetroBundler
723
730
  });
731
+ let stickyModuleResolverInput;
732
+ if (isStickyResolverEnabled) {
733
+ stickyModuleResolverInput = await (0, _createExpoStickyResolver.createStickyModuleResolverInput)({
734
+ platforms: expoConfigPlatforms,
735
+ projectRoot
736
+ });
737
+ }
724
738
  return withExtendedResolver(config, {
739
+ stickyModuleResolverInput,
725
740
  tsconfig,
726
741
  isExporting,
727
742
  isTsconfigPathsEnabled,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { ExpoConfig, Platform } from '@expo/config';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport Bundler from 'metro/src/Bundler';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext, CustomResolutionContext } from 'metro-resolver';\nimport * as metroResolver from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { createFallbackModuleResolver } from './createExpoFallbackResolver';\nimport { createFastResolver, FailedToResolvePathError } from './createExpoMetroResolver';\nimport { isNodeExternal, shouldCreateVirtualCanary, shouldCreateVirtualShim } from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { getMetroBundlerWithVirtualModules } from './metroVirtualModules';\nimport {\n withMetroErrorReportingResolver,\n withMetroMutatedResolverContext,\n withMetroResolvers,\n} from './withMetroResolvers';\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { isServerEnvironment } from '../middleware/metroOptions';\nimport { PlatformBundlers } from '../platformBundlers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nexport type StrictResolver = (moduleName: string) => Resolution;\nexport type StrictResolverFactory = (\n context: ResolutionContext,\n platform: string | null\n) => StrictResolver;\n\nconst ASSET_REGISTRY_SRC = `const assets=[];module.exports={registerAsset:s=>assets.push(s),getAssetByID:s=>assets[s-1]};`;\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(\n config: ConfigT,\n {\n getMetroBundler,\n }: {\n getMetroBundler: () => Bundler;\n }\n): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform?: string | null }): readonly string[] => {\n const virtualEnvVarId = `\\0polyfill:environment-variables`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualEnvVarId,\n (() => {\n return `//`;\n })()\n );\n\n const virtualModuleId = `\\0polyfill:external-require`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n (() => {\n if (ctx.platform === 'web') {\n return `global.$$require_external = typeof require !== \"undefined\" ? require : () => null;`;\n } else {\n // Wrap in try/catch to support Android.\n return 'try { global.$$require_external = typeof expo === \"undefined\" ? require : (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} } catch { global.$$require_external = (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} }';\n }\n })()\n );\n\n if (ctx.platform === 'web') {\n return [\n virtualModuleId,\n virtualEnvVarId,\n // Ensure that the error-guard polyfill is included in the web polyfills to\n // make metro-runtime work correctly.\n // TODO: This module is pretty big for a function that simply re-throws an error that doesn't need to be caught.\n require.resolve('@react-native/js-polyfills/error-guard'),\n ];\n }\n\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n return [\n ...polyfills,\n virtualModuleId,\n virtualEnvVarId,\n // Removed on server platforms during the transform.\n require.resolve('expo/virtual/streams.js'),\n ];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function getNodejsExtensions(srcExts: readonly string[]): string[] {\n const mjsExts = srcExts.filter((ext) => /mjs$/.test(ext));\n const nodejsSourceExtensions = srcExts.filter((ext) => !/mjs$/.test(ext));\n // find index of last `*.js` extension\n const jsIndex = nodejsSourceExtensions.reduce((index, ext, i) => {\n return /jsx?$/.test(ext) ? i : index;\n }, -1);\n\n // insert `*.mjs` extensions after `*.js` extensions\n nodejsSourceExtensions.splice(jsIndex + 1, 0, ...mjsExts);\n\n return nodejsSourceExtensions;\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n * - Alias react-native renderer code to a vendored React canary build on native.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n tsconfig,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n tsconfig: TsConfigPaths | null;\n isTsconfigPathsEnabled?: boolean;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled?: boolean;\n isReactServerComponentsEnabled?: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isReactServerComponentsEnabled) {\n Log.warn(`React Server Components (beta) is enabled.`);\n }\n if (isReactCanaryEnabled) {\n Log.warn(`Experimental React 19 canary is enabled.`);\n }\n if (isFastResolverEnabled) {\n Log.log(chalk.dim`Fast resolver is enabled.`);\n }\n\n const defaultResolver = metroResolver.resolve;\n const resolver = isFastResolverEnabled\n ? createFastResolver({\n preserveSymlinks: true,\n blockList: !config.resolver?.blockList\n ? []\n : Array.isArray(config.resolver?.blockList)\n ? config.resolver?.blockList\n : [config.resolver?.blockList],\n })\n : defaultResolver;\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n 'react-native/index': 'react-native-web',\n 'react-native/Libraries/Image/resolveAssetSource': 'expo-asset/build/resolveAssetSource',\n },\n };\n\n // The vendored canary modules live inside /static/canary-full/node_modules\n // Adding the `index.js` allows us to add this path as `originModulePath` to\n // resolve the nested `node_modules` folder properly.\n const canaryModulesPath = path.join(\n require.resolve('@expo/cli/package.json'),\n '../static/canary-full/index.js'\n );\n\n let _universalAliases: [RegExp, string][] | null;\n\n function getUniversalAliases() {\n if (_universalAliases) {\n return _universalAliases;\n }\n\n _universalAliases = [];\n\n // This package is currently always installed as it is included in the `expo` package.\n if (resolveFrom.silent(config.projectRoot, '@expo/vector-icons')) {\n debug('Enabling alias: react-native-vector-icons -> @expo/vector-icons');\n _universalAliases.push([/^react-native-vector-icons(\\/.*)?/, '@expo/vector-icons$1']);\n }\n if (isReactServerComponentsEnabled) {\n if (resolveFrom.silent(config.projectRoot, 'expo-router/rsc')) {\n debug('Enabling bridge alias: expo-router -> expo-router/rsc');\n _universalAliases.push([/^expo-router$/, 'expo-router/rsc']);\n // Bridge the internal entry point which is a standalone import to ensure package.json resolution works as expected.\n _universalAliases.push([/^expo-router\\/entry-classic$/, 'expo-router/rsc/entry']);\n }\n }\n return _universalAliases;\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve =\n isTsconfigPathsEnabled && (tsconfig?.paths || tsconfig?.baseUrl != null)\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsconfig.baseUrl,\n })\n : null;\n\n // TODO: Move this to be a transform key for invalidation.\n if (!isExporting && isInteractive()) {\n if (isTsconfigPathsEnabled) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(config.projectRoot, [\n './tsconfig.json',\n './jsconfig.json',\n ]);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(config.projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n }\n\n let nodejsSourceExtensions: string[] | null = null;\n\n const getStrictResolver: StrictResolverFactory = (\n { resolveRequest, ...context },\n platform\n ): StrictResolver => {\n return function doResolve(moduleName: string): Resolution {\n return resolver(context, moduleName, platform);\n };\n };\n\n function getOptionalResolver(context: ResolutionContext, platform: string | null) {\n const doResolve = getStrictResolver(context, platform);\n return function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n };\n }\n\n // TODO: This is a hack to get resolveWeak working.\n const idFactory = (config.serializer?.createModuleIdFactory?.() ??\n ((id: number | string, context: { platform: string; environment?: string }): number | string =>\n id)) as (\n id: number | string,\n context: { platform: string; environment?: string }\n ) => number | string;\n\n const getAssetRegistryModule = () => {\n const virtualModuleId = `\\0polyfill:assets-registry`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n ASSET_REGISTRY_SRC\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n } as const;\n };\n\n // If Node.js pass-through, then remap to a module like `module.exports = $$require_external(<module>)`.\n // If module should be shimmed, remap to an empty module.\n const externals: {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => boolean;\n replace: 'empty' | 'node' | 'weak';\n }[] = [\n {\n match: (context: ResolutionContext, moduleName: string) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for Node.js environments.\n !isServerEnvironment(context.customResolverOptions?.environment)\n ) {\n return false;\n }\n\n if (context.customResolverOptions?.environment === 'react-server') {\n // Ensure these non-react-server modules are excluded when bundling for React Server Components in development.\n return /^(source-map-support(\\/.*)?|@babel\\/runtime\\/.+|debug|metro-runtime\\/src\\/modules\\/HMRClient|metro|acorn-loose|acorn|chalk|ws|ansi-styles|supports-color|color-convert|has-flag|utf-8-validate|color-name|react-refresh\\/runtime|@remix-run\\/node\\/.+)$/.test(\n moduleName\n );\n }\n\n // TODO: Windows doesn't support externals somehow.\n if (process.platform === 'win32') {\n return /^(source-map-support(\\/.*)?)$/.test(moduleName);\n }\n\n // Extern these modules in standard Node.js environments in development to prevent API routes side-effects\n // from leaking into the dev server process.\n return /^(source-map-support(\\/.*)?|react|@radix-ui\\/.+|@babel\\/runtime\\/.+|react-dom(\\/.+)?|debug|acorn-loose|acorn|css-in-js-utils\\/lib\\/.+|hyphenate-style-name|color|color-string|color-convert|color-name|fontfaceobserver|fast-deep-equal|query-string|escape-string-regexp|invariant|postcss-value-parser|memoize-one|nullthrows|strict-uri-encode|decode-uri-component|split-on-first|filter-obj|warn-once|simple-swizzle|is-arrayish|inline-style-prefixer\\/.+)$/.test(\n moduleName\n );\n },\n replace: 'node',\n },\n // Externals to speed up async split chunks by extern-ing common packages that appear in the root client chunk.\n {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for client environments.\n isServerEnvironment(context.customResolverOptions?.environment) ||\n // Only enable for client boundaries\n !context.customResolverOptions.clientboundary\n ) {\n return false;\n }\n\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return false;\n }\n\n const isExternal = // Extern these modules in standard Node.js environments.\n /^(deprecated-react-native-prop-types|react|react\\/jsx-dev-runtime|scheduler|react-native|react-dom(\\/.+)?|metro-runtime(\\/.+)?)$/.test(\n moduleName\n ) ||\n // TODO: Add more\n /^@babel\\/runtime\\/helpers\\/(wrapNativeSuper)$/.test(moduleName);\n\n return isExternal;\n },\n replace: 'weak',\n },\n ];\n\n const metroConfigWithCustomResolver = withMetroResolvers(config, [\n // Mock out production react imports in development.\n function requestDevMockProdReact(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // This resolution is dev-only to prevent bundling the production React packages in development.\n if (!context.dev) return null;\n\n if (\n // Match react-native renderers.\n (platform !== 'web' &&\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/]react-native[\\\\/]/) &&\n moduleName.match(/([\\\\/]ReactFabric|ReactNativeRenderer)-prod/)) ||\n // Match react production imports.\n (moduleName.match(/\\.production(\\.min)?\\.js$/) &&\n // Match if the import originated from a react package.\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/](react[-\\\\/]|scheduler[\\\\/])/))\n ) {\n debug(`Skipping production module: ${moduleName}`);\n // /Users/path/to/expo/node_modules/react/index.js ./cjs/react.production.min.js\n // /Users/path/to/expo/node_modules/react/jsx-dev-runtime.js ./cjs/react-jsx-dev-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n // /Users/path/to/expo/node_modules/react-refresh/runtime.js ./cjs/react-refresh-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/scheduler/index.native.js ./cjs/scheduler.native.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n return {\n type: 'empty',\n };\n }\n return null;\n },\n // tsconfig paths\n function requestTsconfigPaths(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n return (\n tsConfigResolve?.(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n getOptionalResolver(context, platform)\n ) ?? null\n );\n },\n\n // Node.js externals support\n function requestNodeExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n const moduleId = isNodeExternal(moduleName);\n if (!moduleId) {\n return null;\n }\n\n if (\n // In browser runtimes, we want to either resolve a local node module by the same name, or shim the module to\n // prevent crashing when Node.js built-ins are imported.\n !isServer\n ) {\n // Perform optional resolve first. If the module doesn't exist (no module in the node_modules)\n // then we can mock the file to use an empty module.\n const result = getOptionalResolver(context, platform)(moduleName);\n\n if (!result && platform !== 'web') {\n // Preserve previous behavior where native throws an error on node.js internals.\n return null;\n }\n\n return (\n result ?? {\n // In this case, mock the file to use an empty module.\n type: 'empty',\n }\n );\n }\n const contents = `module.exports=$$require_external('node:${moduleId}');`;\n debug(`Virtualizing Node.js \"${moduleId}\"`);\n const virtualModuleId = `\\0node:${moduleId}`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n },\n\n // Custom externals support\n function requestCustomExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return null;\n }\n // Skip applying JS externals for CSS files.\n if (/\\.(s?css|sass)$/.test(context.originModulePath)) {\n return null;\n }\n\n const environment = context.customResolverOptions?.environment;\n\n const strictResolve = getStrictResolver(context, platform);\n\n for (const external of externals) {\n if (external.match(context, moduleName, platform)) {\n if (external.replace === 'empty') {\n debug(`Redirecting external \"${moduleName}\" to \"${external.replace}\"`);\n return {\n type: external.replace,\n };\n } else if (external.replace === 'weak') {\n // TODO: Make this use require.resolveWeak again. Previously this was just resolving to the same path.\n const realModule = strictResolve(moduleName);\n const realPath = realModule.type === 'sourceFile' ? realModule.filePath : moduleName;\n const opaqueId = idFactory(realPath, {\n platform: platform!,\n environment,\n });\n\n const contents =\n typeof opaqueId === 'number'\n ? `module.exports=/*${moduleName}*/__r(${opaqueId})`\n : `module.exports=/*${moduleName}*/__r(${JSON.stringify(opaqueId)})`;\n // const contents = `module.exports=/*${moduleName}*/__r(require.resolveWeak('${moduleName}'))`;\n // const generatedModuleId = fastHashMemoized(contents);\n const virtualModuleId = `\\0weak:${opaqueId}`;\n debug('Virtualizing module:', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else if (external.replace === 'node') {\n const contents = `module.exports=$$require_external('${moduleName}')`;\n const virtualModuleId = `\\0node:${moduleName}`;\n debug('Virtualizing Node.js (custom):', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else {\n throw new CommandError(\n `Invalid external alias type: \"${external.replace}\" for module \"${moduleName}\" (platform: ${platform}, originModulePath: ${context.originModulePath})`\n );\n }\n }\n }\n return null;\n },\n\n // Basic moduleId aliases\n function requestAlias(context: ResolutionContext, moduleName: string, platform: string | null) {\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n const redirectedModuleName = aliases[platform][moduleName];\n return getStrictResolver(context, platform)(redirectedModuleName);\n }\n\n for (const [matcher, alias] of getUniversalAliases()) {\n const match = moduleName.match(matcher);\n if (match) {\n const aliasedModule = alias.replace(\n /\\$(\\d+)/g,\n (_, index) => match[parseInt(index, 10)] ?? ''\n );\n const doResolve = getStrictResolver(context, platform);\n debug(`Alias \"${moduleName}\" to \"${aliasedModule}\"`);\n return doResolve(aliasedModule);\n }\n }\n\n return null;\n },\n\n // Polyfill for asset registry\n function requestStableAssetRegistry(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n if (/^@react-native\\/assets-registry\\/registry(\\.js)?$/.test(moduleName)) {\n return getAssetRegistryModule();\n }\n\n if (\n platform === 'web' &&\n context.originModulePath.match(/node_modules[\\\\/]react-native-web[\\\\/]/) &&\n moduleName.includes('/modules/AssetRegistry')\n ) {\n return getAssetRegistryModule();\n }\n\n return null;\n },\n\n // TODO: Reduce these as much as possible in the future.\n // Complex post-resolution rewrites.\n function requestPostRewrites(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const doResolve = getStrictResolver(context, platform);\n\n const result = doResolve(moduleName);\n\n if (result.type !== 'sourceFile') {\n return result;\n }\n\n if (platform === 'web') {\n if (result.filePath.includes('node_modules')) {\n // // Disallow importing confusing native modules on web\n if (moduleName.includes('react-native/Libraries/Utilities/codegenNativeCommands')) {\n throw new FailedToResolvePathError(\n `Importing native-only module \"${moduleName}\" on web from: ${context.originModulePath}`\n );\n }\n\n // Replace with static shims\n\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const shimFile = shouldCreateVirtualShim(normalName);\n if (shimFile) {\n const virtualId = `\\0shim:${normalName}`;\n const bundler = getMetroBundlerWithVirtualModules(getMetroBundler());\n if (!bundler.hasVirtualModule(virtualId)) {\n bundler.setVirtualModule(virtualId, fs.readFileSync(shimFile, 'utf8'));\n }\n debug(`Redirecting module \"${result.filePath}\" to shim`);\n\n return {\n ...result,\n filePath: virtualId,\n };\n }\n }\n } else {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n // react-native/Libraries/Core/InitializeCore\n const normal = normalizeSlashes(result.filePath);\n\n // Shim out React Native native runtime globals in server mode for native.\n if (isServer) {\n if (normal.endsWith('react-native/Libraries/Core/InitializeCore.js')) {\n debug('Shimming out InitializeCore for React Native in native SSR bundle');\n return {\n type: 'empty',\n };\n }\n }\n\n // When server components are enabled, redirect React Native's renderer to the canary build\n // this will enable the use hook and other requisite features from React 19.\n if (isReactCanaryEnabled && result.filePath.includes('node_modules')) {\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const canaryFile = shouldCreateVirtualCanary(normalName);\n if (canaryFile) {\n debug(`Redirecting React Native module \"${result.filePath}\" to canary build`);\n return {\n ...result,\n filePath: canaryFile,\n };\n }\n }\n }\n\n return result;\n },\n\n // If at this point, we haven't resolved a module yet, if it's a module specifier for a known dependency\n // of either `expo` or `expo-router`, attempt to resolve it from these origin modules instead\n createFallbackModuleResolver({\n projectRoot: config.projectRoot,\n originModuleNames: ['expo', 'expo-router'],\n getStrictResolver,\n }),\n ]);\n\n // Ensure we mutate the resolution context to include the custom resolver options for server and web.\n const metroConfigWithCustomContext = withMetroMutatedResolverContext(\n metroConfigWithCustomResolver,\n (\n immutableContext: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ): CustomResolutionContext => {\n const context: Mutable<CustomResolutionContext> = {\n ...immutableContext,\n preferNativePlatform: platform !== 'web',\n };\n\n // TODO: Remove this when we have React 19 in the expo/expo monorepo.\n if (\n isReactCanaryEnabled &&\n // Change the node modules path for react and react-dom to use the vendor in Expo CLI.\n /^(react|react\\/.*|react-dom|react-dom\\/.*)$/.test(moduleName)\n ) {\n // Modifying the origin module path changes the starting Node module resolution path to this folder\n context.originModulePath = canaryModulesPath;\n // Hierarchical lookup has to be enabled for this to work\n context.disableHierarchicalLookup = false;\n }\n\n if (isServerEnvironment(context.customResolverOptions?.environment)) {\n // Adjust nodejs source extensions to sort mjs after js, including platform variants.\n if (nodejsSourceExtensions === null) {\n nodejsSourceExtensions = getNodejsExtensions(context.sourceExts);\n }\n context.sourceExts = nodejsSourceExtensions;\n\n context.unstable_enablePackageExports = true;\n context.unstable_conditionsByPlatform = {};\n\n const isReactServerComponents =\n context.customResolverOptions?.environment === 'react-server';\n\n if (isReactServerComponents) {\n // NOTE: Align the behavior across server and client. This is a breaking change so we'll just roll it out with React Server Components.\n // This ensures that react-server and client code both resolve `module` and `main` in the same order.\n if (platform === 'web') {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['module', 'main'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'module', 'main'];\n }\n } else {\n if (platform === 'web') {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['main', 'module'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'main', 'module'];\n }\n }\n\n // Enable react-server import conditions.\n if (context.customResolverOptions?.environment === 'react-server') {\n context.unstable_conditionNames = ['node', 'react-server', 'workerd'];\n } else {\n context.unstable_conditionNames = ['node'];\n }\n } else {\n // Non-server changes\n\n if (!env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE && platform && platform in preferredMainFields) {\n context.mainFields = preferredMainFields[platform];\n }\n }\n\n return context;\n }\n );\n\n return withMetroErrorReportingResolver(metroConfigWithCustomContext);\n}\n\n/** @returns `true` if the incoming resolution should be swapped. */\nexport function shouldAliasModule(\n input: {\n platform: string | null;\n result: Resolution;\n },\n alias: { platform: string; output: string }\n): boolean {\n return (\n input.platform === alias.platform &&\n input.result?.type === 'sourceFile' &&\n typeof input.result?.filePath === 'string' &&\n normalizeSlashes(input.result.filePath).endsWith(alias.output)\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isNamedRequiresEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled: boolean;\n isReactServerComponentsEnabled: boolean;\n isNamedRequiresEnabled: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isNamedRequiresEnabled) {\n debug('Using Expo metro require runtime.');\n // Change the default metro-runtime to a custom one that supports bundle splitting.\n require('metro-config/src/defaults/defaults').moduleSystem = require.resolve(\n '@expo/cli/build/metro-require/require'\n );\n }\n\n if (!config.projectRoot) {\n // @ts-expect-error: read-only types\n config.projectRoot = projectRoot;\n }\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n // This is used for running Expo CLI in development against projects outside the monorepo.\n if (!isDirectoryIn(__dirname, projectRoot)) {\n if (!config.watchFolders) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders = [];\n }\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(\n path.join(require.resolve('@expo/metro-config/package.json'), '../..'),\n // For virtual modules\n path.join(require.resolve('expo/package.json'), '..')\n );\n if (isReactCanaryEnabled) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('@expo/cli/package.json'), '..'));\n }\n }\n\n // TODO: Remove this\n // @ts-expect-error: Invalidate the cache when the location of expo-router changes on-disk.\n config.transformer._expoRouterPath = resolveFrom.silent(projectRoot, 'expo-router');\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(\n ([platform, bundler]) => bundler === 'metro' && exp.platforms?.includes(platform as Platform)\n )\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config, { getMetroBundler });\n\n return withExtendedResolver(config, {\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n });\n}\n\nfunction isDirectoryIn(targetPath: string, rootPath: string) {\n return targetPath.startsWith(rootPath) && targetPath.length >= rootPath.length;\n}\n"],"names":["getNodejsExtensions","shouldAliasModule","withExtendedResolver","withMetroMultiPlatformAsync","ASSET_REGISTRY_SRC","debug","require","withWebPolyfills","config","getMetroBundler","originalGetPolyfills","serializer","getPolyfills","bind","ctx","virtualEnvVarId","getMetroBundlerWithVirtualModules","setVirtualModule","virtualModuleId","platform","resolve","polyfills","normalizeSlashes","p","replace","srcExts","mjsExts","filter","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","isTsconfigPathsEnabled","isFastResolverEnabled","isExporting","isReactCanaryEnabled","isReactServerComponentsEnabled","Log","warn","log","chalk","dim","defaultResolver","metroResolver","resolver","createFastResolver","preserveSymlinks","blockList","Array","isArray","aliases","web","canaryModulesPath","path","join","_universalAliases","getUniversalAliases","resolveFrom","silent","projectRoot","push","preferredMainFields","tsConfigResolve","paths","baseUrl","resolveWithTsConfigPaths","hasBaseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","getStrictResolver","resolveRequest","context","doResolve","moduleName","getOptionalResolver","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","idFactory","createModuleIdFactory","id","getAssetRegistryModule","type","filePath","externals","match","customResolverOptions","exporting","isServerEnvironment","environment","process","clientboundary","endsWith","isExternal","metroConfigWithCustomResolver","withMetroResolvers","requestDevMockProdReact","dev","originModulePath","requestTsconfigPaths","requestNodeExternals","isServer","moduleId","isNodeExternal","result","contents","requestCustomExternals","strictResolve","external","realModule","realPath","opaqueId","JSON","stringify","CommandError","requestAlias","redirectedModuleName","matcher","alias","aliasedModule","_","parseInt","requestStableAssetRegistry","includes","requestPostRewrites","FailedToResolvePathError","normalName","shimFile","shouldCreateVirtualShim","virtualId","bundler","hasVirtualModule","fs","readFileSync","normal","canaryFile","shouldCreateVirtualCanary","createFallbackModuleResolver","originModuleNames","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","disableHierarchicalLookup","sourceExts","unstable_enablePackageExports","unstable_conditionsByPlatform","isReactServerComponents","mainFields","unstable_conditionNames","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","input","output","exp","platformBundlers","isNamedRequiresEnabled","moduleSystem","EXPO_PUBLIC_PROJECT_ROOT","isDirectoryIn","__dirname","watchFolders","transformer","_expoRouterPath","expoConfigPlatforms","entries","platforms","map","Set","concat","targetPath","rootPath","startsWith"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAmHeA,mBAAmB;eAAnBA;;IA4pBAC,iBAAiB;eAAjBA;;IAtoBAC,oBAAoB;eAApBA;;IAspBMC,2BAA2B;eAA3BA;;;;gEA7xBJ;;;;;;;gEACH;;;;;;;iEAIgB;;;;;;;gEACd;;;;;;;gEACO;;;;;;4CAEqB;yCACg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AsB;QACtBsC,eAAI,CAACC,IAAI,CAACrD,QAAQc,OAAO,CAAC,sBAAsB;QAElD,IAAIoB,sBAAsB;YACxB,6CAA6C;YAC7ChC,OAAO2K,YAAY,CAAClH,IAAI,CAACP,eAAI,CAACC,IAAI,CAACrD,QAAQc,OAAO,CAAC,2BAA2B;QAChF;IACF;IAEA,oBAAoB;IACpB,2FAA2F;IAC3FZ,OAAO4K,WAAW,CAACC,eAAe,GAAGvH,sBAAW,CAACC,MAAM,CAACC,aAAa;IAErE,IAAI5B,WAAiC;IAErC,IAAIC,wBAAwB;QAC1BD,WAAW,MAAMwC,IAAAA,yCAAsB,EAACZ;IAC1C;IAEA,IAAIsH,sBAAsBvG,OAAOwG,OAAO,CAACV,kBACtClJ,MAAM,CACL,CAAC,CAACR,UAAUgI,QAAQ;YAA4ByB;eAAvBzB,YAAY,aAAWyB,iBAAAA,IAAIY,SAAS,qBAAbZ,eAAehC,QAAQ,CAACzH;OAEzEsK,GAAG,CAAC,CAAC,CAACtK,SAAS,GAAKA;IAEvB,IAAIkC,MAAMC,OAAO,CAAC9C,OAAOyC,QAAQ,CAACuI,SAAS,GAAG;QAC5CF,sBAAsB;eAAI,IAAII,IAAIJ,oBAAoBK,MAAM,CAACnL,OAAOyC,QAAQ,CAACuI,SAAS;SAAG;IAC3F;IAEA,yCAAyC;IACzChL,OAAOyC,QAAQ,CAACuI,SAAS,GAAGF;IAE5B9K,SAASD,iBAAiBC,QAAQ;QAAEC;IAAgB;IAEpD,OAAOP,qBAAqBM,QAAQ;QAClC4B;QACAG;QACAF;QACAC;QACAE;QACAC;QACAhC;IACF;AACF;AAEA,SAASwK,cAAcW,UAAkB,EAAEC,QAAgB;IACzD,OAAOD,WAAWE,UAAU,CAACD,aAAaD,WAAW3G,MAAM,IAAI4G,SAAS5G,MAAM;AAChF"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { ExpoConfig, Platform } from '@expo/config';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport Bundler from 'metro/src/Bundler';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext, CustomResolutionContext } from 'metro-resolver';\nimport * as metroResolver from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { createFallbackModuleResolver } from './createExpoFallbackResolver';\nimport { createFastResolver, FailedToResolvePathError } from './createExpoMetroResolver';\nimport {\n createStickyModuleResolverInput,\n createStickyModuleResolver,\n StickyModuleResolverInput,\n} from './createExpoStickyResolver';\nimport { isNodeExternal, shouldCreateVirtualCanary, shouldCreateVirtualShim } from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { getMetroBundlerWithVirtualModules } from './metroVirtualModules';\nimport {\n withMetroErrorReportingResolver,\n withMetroMutatedResolverContext,\n withMetroResolvers,\n} from './withMetroResolvers';\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { isServerEnvironment } from '../middleware/metroOptions';\nimport { PlatformBundlers } from '../platformBundlers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nexport type StrictResolver = (moduleName: string) => Resolution;\nexport type StrictResolverFactory = (\n context: ResolutionContext,\n platform: string | null\n) => StrictResolver;\n\nconst ASSET_REGISTRY_SRC = `const assets=[];module.exports={registerAsset:s=>assets.push(s),getAssetByID:s=>assets[s-1]};`;\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(\n config: ConfigT,\n {\n getMetroBundler,\n }: {\n getMetroBundler: () => Bundler;\n }\n): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform?: string | null }): readonly string[] => {\n const virtualEnvVarId = `\\0polyfill:environment-variables`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualEnvVarId,\n (() => {\n return `//`;\n })()\n );\n\n const virtualModuleId = `\\0polyfill:external-require`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n (() => {\n if (ctx.platform === 'web') {\n return `global.$$require_external = typeof require !== \"undefined\" ? require : () => null;`;\n } else {\n // Wrap in try/catch to support Android.\n return 'try { global.$$require_external = typeof expo === \"undefined\" ? require : (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} } catch { global.$$require_external = (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} }';\n }\n })()\n );\n\n if (ctx.platform === 'web') {\n return [\n virtualModuleId,\n virtualEnvVarId,\n // Ensure that the error-guard polyfill is included in the web polyfills to\n // make metro-runtime work correctly.\n // TODO: This module is pretty big for a function that simply re-throws an error that doesn't need to be caught.\n require.resolve('@react-native/js-polyfills/error-guard'),\n ];\n }\n\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n return [\n ...polyfills,\n virtualModuleId,\n virtualEnvVarId,\n // Removed on server platforms during the transform.\n require.resolve('expo/virtual/streams.js'),\n ];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function getNodejsExtensions(srcExts: readonly string[]): string[] {\n const mjsExts = srcExts.filter((ext) => /mjs$/.test(ext));\n const nodejsSourceExtensions = srcExts.filter((ext) => !/mjs$/.test(ext));\n // find index of last `*.js` extension\n const jsIndex = nodejsSourceExtensions.reduce((index, ext, i) => {\n return /jsx?$/.test(ext) ? i : index;\n }, -1);\n\n // insert `*.mjs` extensions after `*.js` extensions\n nodejsSourceExtensions.splice(jsIndex + 1, 0, ...mjsExts);\n\n return nodejsSourceExtensions;\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n * - Alias react-native renderer code to a vendored React canary build on native.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n tsconfig,\n stickyModuleResolverInput,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n tsconfig: TsConfigPaths | null;\n stickyModuleResolverInput?: StickyModuleResolverInput;\n isTsconfigPathsEnabled?: boolean;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled?: boolean;\n isReactServerComponentsEnabled?: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isReactServerComponentsEnabled) {\n Log.warn(`React Server Components (beta) is enabled.`);\n }\n if (isReactCanaryEnabled) {\n Log.warn(`Experimental React 19 canary is enabled.`);\n }\n if (isFastResolverEnabled) {\n Log.log(chalk.dim`Fast resolver is enabled.`);\n }\n if (stickyModuleResolverInput) {\n Log.log(chalk.dim`Sticky resolver is enabled.`);\n }\n\n const defaultResolver = metroResolver.resolve;\n const resolver = isFastResolverEnabled\n ? createFastResolver({\n preserveSymlinks: true,\n blockList: !config.resolver?.blockList\n ? []\n : Array.isArray(config.resolver?.blockList)\n ? config.resolver?.blockList\n : [config.resolver?.blockList],\n })\n : defaultResolver;\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n 'react-native/index': 'react-native-web',\n 'react-native/Libraries/Image/resolveAssetSource': 'expo-asset/build/resolveAssetSource',\n },\n };\n\n // The vendored canary modules live inside /static/canary-full/node_modules\n // Adding the `index.js` allows us to add this path as `originModulePath` to\n // resolve the nested `node_modules` folder properly.\n const canaryModulesPath = path.join(\n require.resolve('@expo/cli/package.json'),\n '../static/canary-full/index.js'\n );\n\n let _universalAliases: [RegExp, string][] | null;\n\n function getUniversalAliases() {\n if (_universalAliases) {\n return _universalAliases;\n }\n\n _universalAliases = [];\n\n // This package is currently always installed as it is included in the `expo` package.\n if (resolveFrom.silent(config.projectRoot, '@expo/vector-icons')) {\n debug('Enabling alias: react-native-vector-icons -> @expo/vector-icons');\n _universalAliases.push([/^react-native-vector-icons(\\/.*)?/, '@expo/vector-icons$1']);\n }\n if (isReactServerComponentsEnabled) {\n if (resolveFrom.silent(config.projectRoot, 'expo-router/rsc')) {\n debug('Enabling bridge alias: expo-router -> expo-router/rsc');\n _universalAliases.push([/^expo-router$/, 'expo-router/rsc']);\n // Bridge the internal entry point which is a standalone import to ensure package.json resolution works as expected.\n _universalAliases.push([/^expo-router\\/entry-classic$/, 'expo-router/rsc/entry']);\n }\n }\n return _universalAliases;\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve =\n isTsconfigPathsEnabled && (tsconfig?.paths || tsconfig?.baseUrl != null)\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsconfig.baseUrl,\n })\n : null;\n\n // TODO: Move this to be a transform key for invalidation.\n if (!isExporting && isInteractive()) {\n if (isTsconfigPathsEnabled) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(config.projectRoot, [\n './tsconfig.json',\n './jsconfig.json',\n ]);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(config.projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n }\n\n let nodejsSourceExtensions: string[] | null = null;\n\n const getStrictResolver: StrictResolverFactory = (\n { resolveRequest, ...context },\n platform\n ): StrictResolver => {\n return function doResolve(moduleName: string): Resolution {\n return resolver(context, moduleName, platform);\n };\n };\n\n function getOptionalResolver(context: ResolutionContext, platform: string | null) {\n const doResolve = getStrictResolver(context, platform);\n return function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n };\n }\n\n // TODO: This is a hack to get resolveWeak working.\n const idFactory = (config.serializer?.createModuleIdFactory?.() ??\n ((id: number | string, context: { platform: string; environment?: string }): number | string =>\n id)) as (\n id: number | string,\n context: { platform: string; environment?: string }\n ) => number | string;\n\n const getAssetRegistryModule = () => {\n const virtualModuleId = `\\0polyfill:assets-registry`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n ASSET_REGISTRY_SRC\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n } as const;\n };\n\n // If Node.js pass-through, then remap to a module like `module.exports = $$require_external(<module>)`.\n // If module should be shimmed, remap to an empty module.\n const externals: {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => boolean;\n replace: 'empty' | 'node' | 'weak';\n }[] = [\n {\n match: (context: ResolutionContext, moduleName: string) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for Node.js environments.\n !isServerEnvironment(context.customResolverOptions?.environment)\n ) {\n return false;\n }\n\n if (context.customResolverOptions?.environment === 'react-server') {\n // Ensure these non-react-server modules are excluded when bundling for React Server Components in development.\n return /^(source-map-support(\\/.*)?|@babel\\/runtime\\/.+|debug|metro-runtime\\/src\\/modules\\/HMRClient|metro|acorn-loose|acorn|chalk|ws|ansi-styles|supports-color|color-convert|has-flag|utf-8-validate|color-name|react-refresh\\/runtime|@remix-run\\/node\\/.+)$/.test(\n moduleName\n );\n }\n\n // TODO: Windows doesn't support externals somehow.\n if (process.platform === 'win32') {\n return /^(source-map-support(\\/.*)?)$/.test(moduleName);\n }\n\n // Extern these modules in standard Node.js environments in development to prevent API routes side-effects\n // from leaking into the dev server process.\n return /^(source-map-support(\\/.*)?|react|@radix-ui\\/.+|@babel\\/runtime\\/.+|react-dom(\\/.+)?|debug|acorn-loose|acorn|css-in-js-utils\\/lib\\/.+|hyphenate-style-name|color|color-string|color-convert|color-name|fontfaceobserver|fast-deep-equal|query-string|escape-string-regexp|invariant|postcss-value-parser|memoize-one|nullthrows|strict-uri-encode|decode-uri-component|split-on-first|filter-obj|warn-once|simple-swizzle|is-arrayish|inline-style-prefixer\\/.+)$/.test(\n moduleName\n );\n },\n replace: 'node',\n },\n // Externals to speed up async split chunks by extern-ing common packages that appear in the root client chunk.\n {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for client environments.\n isServerEnvironment(context.customResolverOptions?.environment) ||\n // Only enable for client boundaries\n !context.customResolverOptions.clientboundary\n ) {\n return false;\n }\n\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return false;\n }\n\n const isExternal = // Extern these modules in standard Node.js environments.\n /^(deprecated-react-native-prop-types|react|react\\/jsx-dev-runtime|scheduler|react-native|react-dom(\\/.+)?|metro-runtime(\\/.+)?)$/.test(\n moduleName\n ) ||\n // TODO: Add more\n /^@babel\\/runtime\\/helpers\\/(wrapNativeSuper)$/.test(moduleName);\n\n return isExternal;\n },\n replace: 'weak',\n },\n ];\n\n const metroConfigWithCustomResolver = withMetroResolvers(config, [\n // Mock out production react imports in development.\n function requestDevMockProdReact(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // This resolution is dev-only to prevent bundling the production React packages in development.\n if (!context.dev) return null;\n\n if (\n // Match react-native renderers.\n (platform !== 'web' &&\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/]react-native[\\\\/]/) &&\n moduleName.match(/([\\\\/]ReactFabric|ReactNativeRenderer)-prod/)) ||\n // Match react production imports.\n (moduleName.match(/\\.production(\\.min)?\\.js$/) &&\n // Match if the import originated from a react package.\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/](react[-\\\\/]|scheduler[\\\\/])/))\n ) {\n debug(`Skipping production module: ${moduleName}`);\n // /Users/path/to/expo/node_modules/react/index.js ./cjs/react.production.min.js\n // /Users/path/to/expo/node_modules/react/jsx-dev-runtime.js ./cjs/react-jsx-dev-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n // /Users/path/to/expo/node_modules/react-refresh/runtime.js ./cjs/react-refresh-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/scheduler/index.native.js ./cjs/scheduler.native.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n return {\n type: 'empty',\n };\n }\n return null;\n },\n // tsconfig paths\n function requestTsconfigPaths(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n return (\n tsConfigResolve?.(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n getOptionalResolver(context, platform)\n ) ?? null\n );\n },\n\n // Node.js externals support\n function requestNodeExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n const moduleId = isNodeExternal(moduleName);\n if (!moduleId) {\n return null;\n }\n\n if (\n // In browser runtimes, we want to either resolve a local node module by the same name, or shim the module to\n // prevent crashing when Node.js built-ins are imported.\n !isServer\n ) {\n // Perform optional resolve first. If the module doesn't exist (no module in the node_modules)\n // then we can mock the file to use an empty module.\n const result = getOptionalResolver(context, platform)(moduleName);\n\n if (!result && platform !== 'web') {\n // Preserve previous behavior where native throws an error on node.js internals.\n return null;\n }\n\n return (\n result ?? {\n // In this case, mock the file to use an empty module.\n type: 'empty',\n }\n );\n }\n const contents = `module.exports=$$require_external('node:${moduleId}');`;\n debug(`Virtualizing Node.js \"${moduleId}\"`);\n const virtualModuleId = `\\0node:${moduleId}`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n },\n\n // Custom externals support\n function requestCustomExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return null;\n }\n // Skip applying JS externals for CSS files.\n if (/\\.(s?css|sass)$/.test(context.originModulePath)) {\n return null;\n }\n\n const environment = context.customResolverOptions?.environment;\n\n const strictResolve = getStrictResolver(context, platform);\n\n for (const external of externals) {\n if (external.match(context, moduleName, platform)) {\n if (external.replace === 'empty') {\n debug(`Redirecting external \"${moduleName}\" to \"${external.replace}\"`);\n return {\n type: external.replace,\n };\n } else if (external.replace === 'weak') {\n // TODO: Make this use require.resolveWeak again. Previously this was just resolving to the same path.\n const realModule = strictResolve(moduleName);\n const realPath = realModule.type === 'sourceFile' ? realModule.filePath : moduleName;\n const opaqueId = idFactory(realPath, {\n platform: platform!,\n environment,\n });\n\n const contents =\n typeof opaqueId === 'number'\n ? `module.exports=/*${moduleName}*/__r(${opaqueId})`\n : `module.exports=/*${moduleName}*/__r(${JSON.stringify(opaqueId)})`;\n // const contents = `module.exports=/*${moduleName}*/__r(require.resolveWeak('${moduleName}'))`;\n // const generatedModuleId = fastHashMemoized(contents);\n const virtualModuleId = `\\0weak:${opaqueId}`;\n debug('Virtualizing module:', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else if (external.replace === 'node') {\n const contents = `module.exports=$$require_external('${moduleName}')`;\n const virtualModuleId = `\\0node:${moduleName}`;\n debug('Virtualizing Node.js (custom):', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else {\n throw new CommandError(\n `Invalid external alias type: \"${external.replace}\" for module \"${moduleName}\" (platform: ${platform}, originModulePath: ${context.originModulePath})`\n );\n }\n }\n }\n return null;\n },\n\n // Basic moduleId aliases\n function requestAlias(context: ResolutionContext, moduleName: string, platform: string | null) {\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n const redirectedModuleName = aliases[platform][moduleName];\n return getStrictResolver(context, platform)(redirectedModuleName);\n }\n\n for (const [matcher, alias] of getUniversalAliases()) {\n const match = moduleName.match(matcher);\n if (match) {\n const aliasedModule = alias.replace(\n /\\$(\\d+)/g,\n (_, index) => match[parseInt(index, 10)] ?? ''\n );\n const doResolve = getStrictResolver(context, platform);\n debug(`Alias \"${moduleName}\" to \"${aliasedModule}\"`);\n return doResolve(aliasedModule);\n }\n }\n\n return null;\n },\n\n // Polyfill for asset registry\n function requestStableAssetRegistry(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n if (/^@react-native\\/assets-registry\\/registry(\\.js)?$/.test(moduleName)) {\n return getAssetRegistryModule();\n }\n\n if (\n platform === 'web' &&\n context.originModulePath.match(/node_modules[\\\\/]react-native-web[\\\\/]/) &&\n moduleName.includes('/modules/AssetRegistry')\n ) {\n return getAssetRegistryModule();\n }\n\n return null;\n },\n\n createStickyModuleResolver(stickyModuleResolverInput, {\n getStrictResolver,\n }),\n\n // TODO: Reduce these as much as possible in the future.\n // Complex post-resolution rewrites.\n function requestPostRewrites(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const doResolve = getStrictResolver(context, platform);\n\n const result = doResolve(moduleName);\n\n if (result.type !== 'sourceFile') {\n return result;\n }\n\n if (platform === 'web') {\n if (result.filePath.includes('node_modules')) {\n // // Disallow importing confusing native modules on web\n if (moduleName.includes('react-native/Libraries/Utilities/codegenNativeCommands')) {\n throw new FailedToResolvePathError(\n `Importing native-only module \"${moduleName}\" on web from: ${context.originModulePath}`\n );\n }\n\n // Replace with static shims\n\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const shimFile = shouldCreateVirtualShim(normalName);\n if (shimFile) {\n const virtualId = `\\0shim:${normalName}`;\n const bundler = getMetroBundlerWithVirtualModules(getMetroBundler());\n if (!bundler.hasVirtualModule(virtualId)) {\n bundler.setVirtualModule(virtualId, fs.readFileSync(shimFile, 'utf8'));\n }\n debug(`Redirecting module \"${result.filePath}\" to shim`);\n\n return {\n ...result,\n filePath: virtualId,\n };\n }\n }\n } else {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n // react-native/Libraries/Core/InitializeCore\n const normal = normalizeSlashes(result.filePath);\n\n // Shim out React Native native runtime globals in server mode for native.\n if (isServer) {\n if (normal.endsWith('react-native/Libraries/Core/InitializeCore.js')) {\n debug('Shimming out InitializeCore for React Native in native SSR bundle');\n return {\n type: 'empty',\n };\n }\n }\n\n // When server components are enabled, redirect React Native's renderer to the canary build\n // this will enable the use hook and other requisite features from React 19.\n if (isReactCanaryEnabled && result.filePath.includes('node_modules')) {\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const canaryFile = shouldCreateVirtualCanary(normalName);\n if (canaryFile) {\n debug(`Redirecting React Native module \"${result.filePath}\" to canary build`);\n return {\n ...result,\n filePath: canaryFile,\n };\n }\n }\n }\n\n return result;\n },\n\n // If at this point, we haven't resolved a module yet, if it's a module specifier for a known dependency\n // of either `expo` or `expo-router`, attempt to resolve it from these origin modules instead\n createFallbackModuleResolver({\n projectRoot: config.projectRoot,\n originModuleNames: ['expo', 'expo-router'],\n getStrictResolver,\n }),\n ]);\n\n // Ensure we mutate the resolution context to include the custom resolver options for server and web.\n const metroConfigWithCustomContext = withMetroMutatedResolverContext(\n metroConfigWithCustomResolver,\n (\n immutableContext: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ): CustomResolutionContext => {\n const context: Mutable<CustomResolutionContext> = {\n ...immutableContext,\n preferNativePlatform: platform !== 'web',\n };\n\n // TODO: Remove this when we have React 19 in the expo/expo monorepo.\n if (\n isReactCanaryEnabled &&\n // Change the node modules path for react and react-dom to use the vendor in Expo CLI.\n /^(react|react\\/.*|react-dom|react-dom\\/.*)$/.test(moduleName)\n ) {\n // Modifying the origin module path changes the starting Node module resolution path to this folder\n context.originModulePath = canaryModulesPath;\n // Hierarchical lookup has to be enabled for this to work\n context.disableHierarchicalLookup = false;\n }\n\n if (isServerEnvironment(context.customResolverOptions?.environment)) {\n // Adjust nodejs source extensions to sort mjs after js, including platform variants.\n if (nodejsSourceExtensions === null) {\n nodejsSourceExtensions = getNodejsExtensions(context.sourceExts);\n }\n context.sourceExts = nodejsSourceExtensions;\n\n context.unstable_enablePackageExports = true;\n context.unstable_conditionsByPlatform = {};\n\n const isReactServerComponents =\n context.customResolverOptions?.environment === 'react-server';\n\n if (isReactServerComponents) {\n // NOTE: Align the behavior across server and client. This is a breaking change so we'll just roll it out with React Server Components.\n // This ensures that react-server and client code both resolve `module` and `main` in the same order.\n if (platform === 'web') {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['module', 'main'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'module', 'main'];\n }\n } else {\n if (platform === 'web') {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['main', 'module'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'main', 'module'];\n }\n }\n\n // Enable react-server import conditions.\n if (context.customResolverOptions?.environment === 'react-server') {\n context.unstable_conditionNames = ['node', 'react-server', 'workerd'];\n } else {\n context.unstable_conditionNames = ['node'];\n }\n } else {\n // Non-server changes\n\n if (!env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE && platform && platform in preferredMainFields) {\n context.mainFields = preferredMainFields[platform];\n }\n }\n\n return context;\n }\n );\n\n return withMetroErrorReportingResolver(metroConfigWithCustomContext);\n}\n\n/** @returns `true` if the incoming resolution should be swapped. */\nexport function shouldAliasModule(\n input: {\n platform: string | null;\n result: Resolution;\n },\n alias: { platform: string; output: string }\n): boolean {\n return (\n input.platform === alias.platform &&\n input.result?.type === 'sourceFile' &&\n typeof input.result?.filePath === 'string' &&\n normalizeSlashes(input.result.filePath).endsWith(alias.output)\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled,\n isStickyResolverEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isNamedRequiresEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n isStickyResolverEnabled?: boolean;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled: boolean;\n isReactServerComponentsEnabled: boolean;\n isNamedRequiresEnabled: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isNamedRequiresEnabled) {\n debug('Using Expo metro require runtime.');\n // Change the default metro-runtime to a custom one that supports bundle splitting.\n require('metro-config/src/defaults/defaults').moduleSystem = require.resolve(\n '@expo/cli/build/metro-require/require'\n );\n }\n\n if (!config.projectRoot) {\n // @ts-expect-error: read-only types\n config.projectRoot = projectRoot;\n }\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n // This is used for running Expo CLI in development against projects outside the monorepo.\n if (!isDirectoryIn(__dirname, projectRoot)) {\n if (!config.watchFolders) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders = [];\n }\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(\n path.join(require.resolve('@expo/metro-config/package.json'), '../..'),\n // For virtual modules\n path.join(require.resolve('expo/package.json'), '..')\n );\n if (isReactCanaryEnabled) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('@expo/cli/package.json'), '..'));\n }\n }\n\n // TODO: Remove this\n // @ts-expect-error: Invalidate the cache when the location of expo-router changes on-disk.\n config.transformer._expoRouterPath = resolveFrom.silent(projectRoot, 'expo-router');\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(\n ([platform, bundler]) => bundler === 'metro' && exp.platforms?.includes(platform as Platform)\n )\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config, { getMetroBundler });\n\n let stickyModuleResolverInput: StickyModuleResolverInput | undefined;\n if (isStickyResolverEnabled) {\n stickyModuleResolverInput = await createStickyModuleResolverInput({\n platforms: expoConfigPlatforms,\n projectRoot,\n });\n }\n\n return withExtendedResolver(config, {\n stickyModuleResolverInput,\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n });\n}\n\nfunction isDirectoryIn(targetPath: string, rootPath: string) {\n return targetPath.startsWith(rootPath) && targetPath.length >= rootPath.length;\n}\n"],"names":["getNodejsExtensions","shouldAliasModule","withExtendedResolver","withMetroMultiPlatformAsync","ASSET_REGISTRY_SRC","debug","require","withWebPolyfills","config","getMetroBundler","originalGetPolyfills","serializer","getPolyfills","bind","ctx","virtualEnvVarId","getMetroBundlerWithVirtualModules","setVirtualModule","virtualModuleId","platform","resolve","polyfills","normalizeSlashes","p","replace","srcExts","mjsExts","filter","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","stickyModuleResolverInput","isTsconfigPathsEnabled","isFastResolverEnabled","isExporting","isReactCanaryEnabled","isReactServerComponentsEnabled","Log","warn","log","chalk","dim","defaultResolver","metroResolver","resolver","createFastResolver","preserveSymlinks","blockList","Array","isArray","aliases","web","canaryModulesPath","path","join","_universalAliases","getUniversalAliases","resolveFrom","silent","projectRoot","push","preferredMainFields","tsConfigResolve","paths","baseUrl","resolveWithTsConfigPaths","hasBaseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","getStrictResolver","resolveRequest","context","doResolve","moduleName","getOptionalResolver","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","idFactory","createModuleIdFactory","id","getAssetRegistryModule","type","filePath","externals","match","customResolverOptions","exporting","isServerEnvironment","environment","process","clientboundary","endsWith","isExternal","metroConfigWithCustomResolver","withMetroResolvers","requestDevMockProdReact","dev","originModulePath","requestTsconfigPaths","requestNodeExternals","isServer","moduleId","isNodeExternal","result","contents","requestCustomExternals","strictResolve","external","realModule","realPath","opaqueId","JSON","stringify","CommandError","requestAlias","redirectedModuleName","matcher","alias","aliasedModule","_","parseInt","requestStableAssetRegistry","includes","createStickyModuleResolver","requestPostRewrites","FailedToResolvePathError","normalName","shimFile","shouldCreateVirtualShim","virtualId","bundler","hasVirtualModule","fs","readFileSync","normal","canaryFile","shouldCreateVirtualCanary","createFallbackModuleResolver","originModuleNames","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","disableHierarchicalLookup","sourceExts","unstable_enablePackageExports","unstable_conditionsByPlatform","isReactServerComponents","mainFields","unstable_conditionNames","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","input","output","exp","platformBundlers","isStickyResolverEnabled","isNamedRequiresEnabled","moduleSystem","EXPO_PUBLIC_PROJECT_ROOT","isDirectoryIn","__dirname","watchFolders","transformer","_expoRouterPath","expoConfigPlatforms","entries","platforms","map","Set","concat","createStickyModuleResolverInput","targetPath","rootPath","startsWith"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAwHeA,mBAAmB;eAAnBA;;IAqqBAC,iBAAiB;eAAjBA;;IA/oBAC,oBAAoB;eAApBA;;IA+pBMC,2BAA2B;eAA3BA;;;;gEA3yBJ;;;;;;;gEACH;;;;;;;iEAIgB;;;;;;;gEACd;;;;;;;gEACO;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C;YAChEJ,WAAWF;YACXxH;QACF;IACF;IAEA,OAAO/D,qBAAqBM,QAAQ;QAClC6B;QACAD;QACAI;QACAF;QACAC;QACAE;QACAC;QACAjC;IACF;AACF;AAEA,SAAS2K,cAAcY,UAAkB,EAAEC,QAAgB;IACzD,OAAOD,WAAWE,UAAU,CAACD,aAAaD,WAAW9G,MAAM,IAAI+G,SAAS/G,MAAM;AAChF"}
@@ -107,8 +107,9 @@ function optionsKeyForContext(context) {
107
107
  // Compound key for the resolver cache
108
108
  return JSON.stringify(context.customResolverOptions ?? {}, canonicalize) ?? '';
109
109
  }
110
- function withMetroResolvers(config, resolvers) {
110
+ function withMetroResolvers(config, inputResolvers) {
111
111
  var _config_resolver, _config_resolver1;
112
+ const resolvers = inputResolvers.filter((x)=>x != null);
112
113
  debug(`Appending ${resolvers.length} custom resolvers to Metro config. (has custom resolver: ${!!((_config_resolver = config.resolver) == null ? void 0 : _config_resolver.resolveRequest)})`);
113
114
  // const hasUserDefinedResolver = !!config.resolver?.resolveRequest;
114
115
  // const defaultResolveRequest = getDefaultMetroResolver(projectRoot);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/withMetroResolvers.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport chalk from 'chalk';\nimport { ConfigT as MetroConfig } from 'metro-config';\nimport type { ResolutionContext, CustomResolutionContext } from 'metro-resolver';\nimport * as metroResolver from 'metro-resolver';\nimport path from 'path';\n\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { env } from '../../../utils/env';\n\nconst debug = require('debug')('expo:metro:withMetroResolvers') as typeof console.log;\n\nexport type MetroResolver = NonNullable<MetroConfig['resolver']['resolveRequest']>;\n\n/** Expo Metro Resolvers can return `null` to skip without throwing an error. Metro Resolvers will throw either a `FailedToResolveNameError` or `FailedToResolvePathError`. */\nexport type ExpoCustomMetroResolver = (\n ...args: Parameters<MetroResolver>\n) => ReturnType<MetroResolver> | null;\n\n/** @returns `MetroResolver` utilizing the upstream `resolve` method. */\nexport function getDefaultMetroResolver(projectRoot: string): MetroResolver {\n return (context: ResolutionContext, moduleName: string, platform: string | null) => {\n return metroResolver.resolve(context, moduleName, platform);\n };\n}\n\nfunction optionsKeyForContext(context: ResolutionContext) {\n const canonicalize = require('metro-core/src/canonicalize');\n\n // Compound key for the resolver cache\n return JSON.stringify(context.customResolverOptions ?? {}, canonicalize) ?? '';\n}\n\n/**\n * Extend the Metro config `resolver.resolveRequest` method with additional resolvers that can\n * exit early by returning a `Resolution` or skip to the next resolver by returning `null`.\n *\n * @param config Metro config.\n * @param resolvers custom MetroResolver to chain.\n * @returns a new `MetroConfig` with the `resolver.resolveRequest` method chained.\n */\nexport function withMetroResolvers(\n config: MetroConfig,\n resolvers: ExpoCustomMetroResolver[]\n): MetroConfig {\n debug(\n `Appending ${\n resolvers.length\n } custom resolvers to Metro config. (has custom resolver: ${!!config.resolver?.resolveRequest})`\n );\n // const hasUserDefinedResolver = !!config.resolver?.resolveRequest;\n // const defaultResolveRequest = getDefaultMetroResolver(projectRoot);\n const originalResolveRequest = config.resolver?.resolveRequest;\n\n return {\n ...config,\n resolver: {\n ...config.resolver,\n resolveRequest(context, moduleName, platform) {\n const upstreamResolveRequest = context.resolveRequest;\n\n const universalContext = {\n ...context,\n resolveRequest(\n ctx: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n for (const resolver of resolvers) {\n try {\n const res = resolver(ctx, moduleName, platform);\n if (res) {\n return res;\n }\n } catch (error: any) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n debug(\n `Custom resolver (${resolver.name || '<anonymous>'}) threw: ${error.constructor.name}. (module: ${moduleName}, platform: ${platform}, env: ${ctx.customResolverOptions?.environment}, origin: ${ctx.originModulePath})`\n );\n }\n }\n // If we haven't returned by now, use the original resolver or upstream resolver.\n return upstreamResolveRequest(ctx, moduleName, platform);\n },\n };\n\n // If the user defined a resolver, run it first and depend on the documented\n // chaining logic: https://facebook.github.io/metro/docs/resolution/#resolution-algorithm\n //\n // config.resolver.resolveRequest = (context, moduleName, platform) => {\n //\n // // Do work...\n //\n // return context.resolveRequest(context, moduleName, platform);\n // };\n const firstResolver = originalResolveRequest ?? universalContext.resolveRequest;\n return firstResolver(universalContext, moduleName, platform);\n },\n },\n };\n}\n\n/**\n * Hook into the Metro resolver chain and mutate the context so users can resolve against our custom assumptions.\n * For example, this will set `preferNativePlatform` to false when bundling for web.\n * */\nexport function withMetroMutatedResolverContext(\n config: MetroConfig,\n getContext: (\n ctx: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ) => CustomResolutionContext\n): MetroConfig {\n const defaultResolveRequest = getDefaultMetroResolver(config.projectRoot);\n const originalResolveRequest = config.resolver?.resolveRequest;\n\n return {\n ...config,\n resolver: {\n ...config.resolver,\n resolveRequest(context, moduleName, platform) {\n const universalContext = getContext(context, moduleName, platform);\n const firstResolver =\n originalResolveRequest ?? universalContext.resolveRequest ?? defaultResolveRequest;\n return firstResolver(universalContext, moduleName, platform);\n },\n },\n };\n}\n\nexport function withMetroErrorReportingResolver(config: MetroConfig): MetroConfig {\n if (!env.EXPO_METRO_UNSTABLE_ERRORS) {\n return config;\n }\n\n const originalResolveRequest = config.resolver?.resolveRequest;\n\n function mutateResolutionError(\n error: Error,\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const inputPlatform = platform ?? 'null';\n\n const mapByOrigin = depGraph.get(optionsKeyForContext(context));\n const mapByPlatform = mapByOrigin?.get(inputPlatform);\n\n if (!mapByPlatform) {\n return error;\n }\n\n // collect all references inversely using some expensive lookup\n\n const getReferences = (origin: string) => {\n const inverseOrigin: { origin: string; previous: string; request: string }[] = [];\n\n if (!mapByPlatform) {\n return inverseOrigin;\n }\n\n for (const [originKey, mapByTarget] of mapByPlatform) {\n // search comparing origin to path\n\n const found = [...mapByTarget.values()].find((resolution) => resolution.path === origin);\n if (found) {\n inverseOrigin.push({\n origin,\n previous: originKey,\n request: found.request,\n });\n }\n }\n\n return inverseOrigin;\n };\n\n const pad = (num: number) => {\n return new Array(num).fill(' ').join('');\n };\n\n const root = config.server?.unstable_serverRoot ?? config.projectRoot;\n\n type InverseDepResult = {\n origin: string;\n request: string;\n previous: InverseDepResult[];\n };\n const recurseBackWithLimit = (\n req: { origin: string; request: string },\n limit: number,\n count: number = 0\n ) => {\n const results: InverseDepResult = {\n origin: req.origin,\n request: req.request,\n previous: [],\n };\n\n if (count >= limit) {\n return results;\n }\n\n const inverse = getReferences(req.origin);\n for (const match of inverse) {\n // Use more qualified name if possible\n // results.origin = match.origin;\n // Found entry point\n if (req.origin === match.previous) {\n continue;\n }\n results.previous.push(\n recurseBackWithLimit({ origin: match.previous, request: match.request }, limit, count + 1)\n );\n }\n return results;\n };\n\n const inverseTree = recurseBackWithLimit(\n { origin: context.originModulePath, request: moduleName },\n // TODO: Do we need to expose this?\n 35\n );\n\n if (inverseTree.previous.length > 0) {\n debug('Found inverse graph:', JSON.stringify(inverseTree, null, 2));\n let extraMessage = chalk.bold('Import stack:');\n const printRecursive = (tree: InverseDepResult, depth: number = 0) => {\n let filename = path.relative(root, tree.origin);\n if (filename.match(/\\?ctx=[\\w\\d]+$/)) {\n filename = filename.replace(/\\?ctx=[\\w\\d]+$/, chalk.dim(' (require.context)'));\n } else {\n let formattedRequest = chalk.green(`\"${tree.request}\"`);\n\n if (\n // If bundling for web and the import is pulling internals from outside of react-native\n // then mark it as an invalid import.\n inputPlatform === 'web' &&\n !/^(node_modules\\/)?react-native\\//.test(filename) &&\n tree.request.match(/^react-native\\/.*/)\n ) {\n formattedRequest =\n formattedRequest +\n chalk`\\n {yellow Importing react-native internals is not supported on web.}`;\n }\n\n filename = filename + chalk`\\n{gray |} {cyan import} ${formattedRequest}\\n`;\n }\n let line = '\\n' + pad(depth) + chalk.gray(' ') + filename;\n if (filename.match(/node_modules/)) {\n line = chalk.gray(\n // Bold the node module name\n line.replace(/node_modules\\/([^/]+)/, (_match, p1) => {\n return 'node_modules/' + chalk.bold(p1);\n })\n );\n }\n extraMessage += line;\n for (const child of tree.previous) {\n printRecursive(\n child,\n // Only add depth if there are multiple children\n tree.previous.length > 1 ? depth + 1 : depth\n );\n }\n };\n printRecursive(inverseTree);\n\n debug('inverse graph message:', extraMessage);\n\n // @ts-expect-error\n error._expoImportStack = extraMessage;\n } else {\n debug('Found no inverse tree for:', context.originModulePath);\n }\n\n return error;\n }\n\n const depGraph: Map<\n // custom options\n string,\n Map<\n // platform\n string,\n Map<\n // origin module name\n string,\n Set<{\n // required module name\n path: string;\n // This isn't entirely accurate since a module can be imported multiple times in a file,\n // and use different names. But it's good enough for now.\n request: string;\n }>\n >\n >\n > = new Map();\n\n return {\n ...config,\n resolver: {\n ...config.resolver,\n resolveRequest(context, moduleName, platform) {\n const storeResult = (res: NonNullable<ReturnType<ExpoCustomMetroResolver>>) => {\n const inputPlatform = platform ?? 'null';\n\n const key = optionsKeyForContext(context);\n if (!depGraph.has(key)) depGraph.set(key, new Map());\n const mapByTarget = depGraph.get(key);\n if (!mapByTarget!.has(inputPlatform)) mapByTarget!.set(inputPlatform, new Map());\n const mapByPlatform = mapByTarget!.get(inputPlatform);\n if (!mapByPlatform!.has(context.originModulePath))\n mapByPlatform!.set(context.originModulePath, new Set());\n const setForModule = mapByPlatform!.get(context.originModulePath)!;\n\n const qualifiedModuleName = res?.type === 'sourceFile' ? res.filePath : moduleName;\n setForModule.add({ path: qualifiedModuleName, request: moduleName });\n };\n\n // If the user defined a resolver, run it first and depend on the documented\n // chaining logic: https://facebook.github.io/metro/docs/resolution/#resolution-algorithm\n //\n // config.resolver.resolveRequest = (context, moduleName, platform) => {\n //\n // // Do work...\n //\n // return context.resolveRequest(context, moduleName, platform);\n // };\n try {\n const firstResolver = originalResolveRequest ?? context.resolveRequest;\n const res = firstResolver(context, moduleName, platform);\n storeResult(res);\n return res;\n } catch (error: any) {\n throw mutateResolutionError(error, context, moduleName, platform);\n }\n },\n },\n };\n}\n"],"names":["getDefaultMetroResolver","withMetroErrorReportingResolver","withMetroMutatedResolverContext","withMetroResolvers","debug","require","projectRoot","context","moduleName","platform","metroResolver","resolve","optionsKeyForContext","canonicalize","JSON","stringify","customResolverOptions","config","resolvers","length","resolver","resolveRequest","originalResolveRequest","upstreamResolveRequest","universalContext","ctx","res","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","name","constructor","environment","originModulePath","firstResolver","getContext","defaultResolveRequest","env","EXPO_METRO_UNSTABLE_ERRORS","mutateResolutionError","inputPlatform","mapByOrigin","depGraph","get","mapByPlatform","getReferences","origin","inverseOrigin","originKey","mapByTarget","found","values","find","resolution","path","push","previous","request","pad","num","Array","fill","join","root","server","unstable_serverRoot","recurseBackWithLimit","req","limit","count","results","inverse","match","inverseTree","extraMessage","chalk","bold","printRecursive","tree","depth","filename","relative","replace","dim","formattedRequest","green","test","line","gray","_match","p1","child","_expoImportStack","Map","storeResult","key","has","set","Set","setForModule","qualifiedModuleName","type","filePath","add"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAoBeA,uBAAuB;eAAvBA;;IAqHAC,+BAA+B;eAA/BA;;IAzBAC,+BAA+B;eAA/BA;;IAvEAC,kBAAkB;eAAlBA;;;;gEAxCE;;;;;;;iEAGa;;;;;;;gEACd;;;;;;6BAEsD;qBACnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpB,MAAMC,QAAQC,QAAQ,SAAS;AAUxB,SAASL,wBAAwBM,WAAmB;IACzD,OAAO,CAACC,SAA4BC,YAAoBC;QACtD,OAAOC,iBAAcC,OAAO,CAACJ,SAASC,YAAYC;IACpD;AACF;AAEA,SAASG,qBAAqBL,OAA0B;IACtD,MAAMM,eAAeR,QAAQ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AK;gBACL,IAAI;oBACF,MAAM2B,gBAAgBb,0BAA0Bf,QAAQc,cAAc;oBACtE,MAAMK,MAAMS,cAAc5B,SAASC,YAAYC;oBAC/CsF,YAAYrE;oBACZ,OAAOA;gBACT,EAAE,OAAOC,OAAY;oBACnB,MAAMa,sBAAsBb,OAAOpB,SAASC,YAAYC;gBAC1D;YACF;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/withMetroResolvers.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport chalk from 'chalk';\nimport { ConfigT as MetroConfig } from 'metro-config';\nimport type { ResolutionContext, CustomResolutionContext } from 'metro-resolver';\nimport * as metroResolver from 'metro-resolver';\nimport path from 'path';\n\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { env } from '../../../utils/env';\n\nconst debug = require('debug')('expo:metro:withMetroResolvers') as typeof console.log;\n\nexport type MetroResolver = NonNullable<MetroConfig['resolver']['resolveRequest']>;\n\n/** Expo Metro Resolvers can return `null` to skip without throwing an error. Metro Resolvers will throw either a `FailedToResolveNameError` or `FailedToResolvePathError`. */\nexport type ExpoCustomMetroResolver = (\n ...args: Parameters<MetroResolver>\n) => ReturnType<MetroResolver> | null;\n\n/** @returns `MetroResolver` utilizing the upstream `resolve` method. */\nexport function getDefaultMetroResolver(projectRoot: string): MetroResolver {\n return (context: ResolutionContext, moduleName: string, platform: string | null) => {\n return metroResolver.resolve(context, moduleName, platform);\n };\n}\n\nfunction optionsKeyForContext(context: ResolutionContext) {\n const canonicalize = require('metro-core/src/canonicalize');\n\n // Compound key for the resolver cache\n return JSON.stringify(context.customResolverOptions ?? {}, canonicalize) ?? '';\n}\n\n/**\n * Extend the Metro config `resolver.resolveRequest` method with additional resolvers that can\n * exit early by returning a `Resolution` or skip to the next resolver by returning `null`.\n *\n * @param config Metro config.\n * @param resolvers custom MetroResolver to chain.\n * @returns a new `MetroConfig` with the `resolver.resolveRequest` method chained.\n */\nexport function withMetroResolvers(\n config: MetroConfig,\n inputResolvers: (ExpoCustomMetroResolver | undefined)[]\n): MetroConfig {\n const resolvers = inputResolvers.filter((x) => x != null);\n debug(\n `Appending ${\n resolvers.length\n } custom resolvers to Metro config. (has custom resolver: ${!!config.resolver?.resolveRequest})`\n );\n // const hasUserDefinedResolver = !!config.resolver?.resolveRequest;\n // const defaultResolveRequest = getDefaultMetroResolver(projectRoot);\n const originalResolveRequest = config.resolver?.resolveRequest;\n\n return {\n ...config,\n resolver: {\n ...config.resolver,\n resolveRequest(context, moduleName, platform) {\n const upstreamResolveRequest = context.resolveRequest;\n\n const universalContext = {\n ...context,\n resolveRequest(\n ctx: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n for (const resolver of resolvers) {\n try {\n const res = resolver(ctx, moduleName, platform);\n if (res) {\n return res;\n }\n } catch (error: any) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n debug(\n `Custom resolver (${resolver.name || '<anonymous>'}) threw: ${error.constructor.name}. (module: ${moduleName}, platform: ${platform}, env: ${ctx.customResolverOptions?.environment}, origin: ${ctx.originModulePath})`\n );\n }\n }\n // If we haven't returned by now, use the original resolver or upstream resolver.\n return upstreamResolveRequest(ctx, moduleName, platform);\n },\n };\n\n // If the user defined a resolver, run it first and depend on the documented\n // chaining logic: https://facebook.github.io/metro/docs/resolution/#resolution-algorithm\n //\n // config.resolver.resolveRequest = (context, moduleName, platform) => {\n //\n // // Do work...\n //\n // return context.resolveRequest(context, moduleName, platform);\n // };\n const firstResolver = originalResolveRequest ?? universalContext.resolveRequest;\n return firstResolver(universalContext, moduleName, platform);\n },\n },\n };\n}\n\n/**\n * Hook into the Metro resolver chain and mutate the context so users can resolve against our custom assumptions.\n * For example, this will set `preferNativePlatform` to false when bundling for web.\n * */\nexport function withMetroMutatedResolverContext(\n config: MetroConfig,\n getContext: (\n ctx: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ) => CustomResolutionContext\n): MetroConfig {\n const defaultResolveRequest = getDefaultMetroResolver(config.projectRoot);\n const originalResolveRequest = config.resolver?.resolveRequest;\n\n return {\n ...config,\n resolver: {\n ...config.resolver,\n resolveRequest(context, moduleName, platform) {\n const universalContext = getContext(context, moduleName, platform);\n const firstResolver =\n originalResolveRequest ?? universalContext.resolveRequest ?? defaultResolveRequest;\n return firstResolver(universalContext, moduleName, platform);\n },\n },\n };\n}\n\nexport function withMetroErrorReportingResolver(config: MetroConfig): MetroConfig {\n if (!env.EXPO_METRO_UNSTABLE_ERRORS) {\n return config;\n }\n\n const originalResolveRequest = config.resolver?.resolveRequest;\n\n function mutateResolutionError(\n error: Error,\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const inputPlatform = platform ?? 'null';\n\n const mapByOrigin = depGraph.get(optionsKeyForContext(context));\n const mapByPlatform = mapByOrigin?.get(inputPlatform);\n\n if (!mapByPlatform) {\n return error;\n }\n\n // collect all references inversely using some expensive lookup\n\n const getReferences = (origin: string) => {\n const inverseOrigin: { origin: string; previous: string; request: string }[] = [];\n\n if (!mapByPlatform) {\n return inverseOrigin;\n }\n\n for (const [originKey, mapByTarget] of mapByPlatform) {\n // search comparing origin to path\n\n const found = [...mapByTarget.values()].find((resolution) => resolution.path === origin);\n if (found) {\n inverseOrigin.push({\n origin,\n previous: originKey,\n request: found.request,\n });\n }\n }\n\n return inverseOrigin;\n };\n\n const pad = (num: number) => {\n return new Array(num).fill(' ').join('');\n };\n\n const root = config.server?.unstable_serverRoot ?? config.projectRoot;\n\n type InverseDepResult = {\n origin: string;\n request: string;\n previous: InverseDepResult[];\n };\n const recurseBackWithLimit = (\n req: { origin: string; request: string },\n limit: number,\n count: number = 0\n ) => {\n const results: InverseDepResult = {\n origin: req.origin,\n request: req.request,\n previous: [],\n };\n\n if (count >= limit) {\n return results;\n }\n\n const inverse = getReferences(req.origin);\n for (const match of inverse) {\n // Use more qualified name if possible\n // results.origin = match.origin;\n // Found entry point\n if (req.origin === match.previous) {\n continue;\n }\n results.previous.push(\n recurseBackWithLimit({ origin: match.previous, request: match.request }, limit, count + 1)\n );\n }\n return results;\n };\n\n const inverseTree = recurseBackWithLimit(\n { origin: context.originModulePath, request: moduleName },\n // TODO: Do we need to expose this?\n 35\n );\n\n if (inverseTree.previous.length > 0) {\n debug('Found inverse graph:', JSON.stringify(inverseTree, null, 2));\n let extraMessage = chalk.bold('Import stack:');\n const printRecursive = (tree: InverseDepResult, depth: number = 0) => {\n let filename = path.relative(root, tree.origin);\n if (filename.match(/\\?ctx=[\\w\\d]+$/)) {\n filename = filename.replace(/\\?ctx=[\\w\\d]+$/, chalk.dim(' (require.context)'));\n } else {\n let formattedRequest = chalk.green(`\"${tree.request}\"`);\n\n if (\n // If bundling for web and the import is pulling internals from outside of react-native\n // then mark it as an invalid import.\n inputPlatform === 'web' &&\n !/^(node_modules\\/)?react-native\\//.test(filename) &&\n tree.request.match(/^react-native\\/.*/)\n ) {\n formattedRequest =\n formattedRequest +\n chalk`\\n {yellow Importing react-native internals is not supported on web.}`;\n }\n\n filename = filename + chalk`\\n{gray |} {cyan import} ${formattedRequest}\\n`;\n }\n let line = '\\n' + pad(depth) + chalk.gray(' ') + filename;\n if (filename.match(/node_modules/)) {\n line = chalk.gray(\n // Bold the node module name\n line.replace(/node_modules\\/([^/]+)/, (_match, p1) => {\n return 'node_modules/' + chalk.bold(p1);\n })\n );\n }\n extraMessage += line;\n for (const child of tree.previous) {\n printRecursive(\n child,\n // Only add depth if there are multiple children\n tree.previous.length > 1 ? depth + 1 : depth\n );\n }\n };\n printRecursive(inverseTree);\n\n debug('inverse graph message:', extraMessage);\n\n // @ts-expect-error\n error._expoImportStack = extraMessage;\n } else {\n debug('Found no inverse tree for:', context.originModulePath);\n }\n\n return error;\n }\n\n const depGraph: Map<\n // custom options\n string,\n Map<\n // platform\n string,\n Map<\n // origin module name\n string,\n Set<{\n // required module name\n path: string;\n // This isn't entirely accurate since a module can be imported multiple times in a file,\n // and use different names. But it's good enough for now.\n request: string;\n }>\n >\n >\n > = new Map();\n\n return {\n ...config,\n resolver: {\n ...config.resolver,\n resolveRequest(context, moduleName, platform) {\n const storeResult = (res: NonNullable<ReturnType<ExpoCustomMetroResolver>>) => {\n const inputPlatform = platform ?? 'null';\n\n const key = optionsKeyForContext(context);\n if (!depGraph.has(key)) depGraph.set(key, new Map());\n const mapByTarget = depGraph.get(key);\n if (!mapByTarget!.has(inputPlatform)) mapByTarget!.set(inputPlatform, new Map());\n const mapByPlatform = mapByTarget!.get(inputPlatform);\n if (!mapByPlatform!.has(context.originModulePath))\n mapByPlatform!.set(context.originModulePath, new Set());\n const setForModule = mapByPlatform!.get(context.originModulePath)!;\n\n const qualifiedModuleName = res?.type === 'sourceFile' ? res.filePath : moduleName;\n setForModule.add({ path: qualifiedModuleName, request: moduleName });\n };\n\n // If the user defined a resolver, run it first and depend on the documented\n // chaining logic: https://facebook.github.io/metro/docs/resolution/#resolution-algorithm\n //\n // config.resolver.resolveRequest = (context, moduleName, platform) => {\n //\n // // Do work...\n //\n // return context.resolveRequest(context, moduleName, platform);\n // };\n try {\n const firstResolver = originalResolveRequest ?? context.resolveRequest;\n const res = firstResolver(context, moduleName, platform);\n storeResult(res);\n return res;\n } catch (error: any) {\n throw mutateResolutionError(error, context, moduleName, platform);\n }\n },\n },\n };\n}\n"],"names":["getDefaultMetroResolver","withMetroErrorReportingResolver","withMetroMutatedResolverContext","withMetroResolvers","debug","require","projectRoot","context","moduleName","platform","metroResolver","resolve","optionsKeyForContext","canonicalize","JSON","stringify","customResolverOptions","config","inputResolvers","resolvers","filter","x","length","resolver","resolveRequest","originalResolveRequest","upstreamResolveRequest","universalContext","ctx","res","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","name","constructor","environment","originModulePath","firstResolver","getContext","defaultResolveRequest","env","EXPO_METRO_UNSTABLE_ERRORS","mutateResolutionError","inputPlatform","mapByOrigin","depGraph","get","mapByPlatform","getReferences","origin","inverseOrigin","originKey","mapByTarget","found","values","find","resolution","path","push","previous","request","pad","num","Array","fill","join","root","server","unstable_serverRoot","recurseBackWithLimit","req","limit","count","results","inverse","match","inverseTree","extraMessage","chalk","bold","printRecursive","tree","depth","filename","relative","replace","dim","formattedRequest","green","test","line","gray","_match","p1","child","_expoImportStack","Map","storeResult","key","has","set","Set","setForModule","qualifiedModuleName","type","filePath","add"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAoBeA,uBAAuB;eAAvBA;;IAsHAC,+BAA+B;eAA/BA;;IAzBAC,+BAA+B;eAA/BA;;IAxEAC,kBAAkB;eAAlBA;;;;gEAxCE;;;;;;;iEAGa;;;;;;;gEACd;;;;;;6BAEsD;qBACnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpB,MAAMC,QAAQC,QAAQ,SAAS;AAUxB,SAASL,wBAAwBM,WAAmB;IACzD,OAAO,CAACC,SAA4BC,YAAoBC;QACtD,OAAOC,iBAAcC,OAAO,CAACJ,SAASC,YAAYC;IACpD;AACF;AAEA,SAASG,qBAAqBL,OAA0B;IACtD,MAAMM,eAAeR,QAAQ;IAE7B,sCAAsC;IACtC,OAAOS,KAAKC,SAAS,CAACR,QAAQS,qBAAqB,IAAI,CAAC,GAAGH,iBAAiB;AAC9E;AAUO,SAASV,mBACdc,MAAmB,EACnBC,cAAuD;QAMSD,kBAIjCA;IAR/B,MAAME,YAAYD,eAAeE,MAAM,CAAC,CAACC,IAAMA,KAAK;IACpDjB,MACE,CAAC,UAAU,EACTe,UAAUG,MAAM,CACjB,yDAAyD,EAAE,CAAC,GAACL,mBAAAA,OAAOM,QAAQ,qBAAfN,iBAAiBO,cAAc,EAAC,CAAC,CAAC;IAElG,oEAAoE;IACpE,sEAAsE;IACtE,MAAM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AAOM,QAAQ;YAClBC,gBAAejB,OAAO,EAAEC,UAAU,EAAEC,QAAQ;gBAC1C,MAAMyF,cAAc,CAACrE;oBACnB,MAAMe,gBAAgBnC,YAAY;oBAElC,MAAM0F,MAAMvF,qBAAqBL;oBACjC,IAAI,CAACuC,SAASsD,GAAG,CAACD,MAAMrD,SAASuD,GAAG,CAACF,KAAK,IAAIF;oBAC9C,MAAM5C,cAAcP,SAASC,GAAG,CAACoD;oBACjC,IAAI,CAAC9C,YAAa+C,GAAG,CAACxD,gBAAgBS,YAAagD,GAAG,CAACzD,eAAe,IAAIqD;oBAC1E,MAAMjD,gBAAgBK,YAAaN,GAAG,CAACH;oBACvC,IAAI,CAACI,cAAeoD,GAAG,CAAC7F,QAAQ8B,gBAAgB,GAC9CW,cAAeqD,GAAG,CAAC9F,QAAQ8B,gBAAgB,EAAE,IAAIiE;oBACnD,MAAMC,eAAevD,cAAeD,GAAG,CAACxC,QAAQ8B,gBAAgB;oBAEhE,MAAMmE,sBAAsB3E,CAAAA,uBAAAA,IAAK4E,IAAI,MAAK,eAAe5E,IAAI6E,QAAQ,GAAGlG;oBACxE+F,aAAaI,GAAG,CAAC;wBAAEjD,MAAM8C;wBAAqB3C,SAASrD;oBAAW;gBACpE;gBAEA,4EAA4E;gBAC5E,yFAAyF;gBACzF,EAAE;gBACF,wEAAwE;gBACxE,EAAE;gBACF,iBAAiB;gBACjB,EAAE;gBACF,iEAAiE;gBACjE,KAAK;gBACL,IAAI;oBACF,MAAM8B,gBAAgBb,0BAA0BlB,QAAQiB,cAAc;oBACtE,MAAMK,MAAMS,cAAc/B,SAASC,YAAYC;oBAC/CyF,YAAYrE;oBACZ,OAAOA;gBACT,EAAE,OAAOC,OAAY;oBACnB,MAAMa,sBAAsBb,OAAOvB,SAASC,YAAYC;gBAC1D;YACF;QACF;IACF;AACF"}
@@ -152,6 +152,9 @@ class Env {
152
152
  /** Enable the unstable inverse dependency stack trace for Metro bundling errors. */ get EXPO_METRO_UNSTABLE_ERRORS() {
153
153
  return (0, _getenv().boolish)('EXPO_METRO_UNSTABLE_ERRORS', false);
154
154
  }
155
+ /** Enable the experimental sticky resolver for Metro. */ get EXPO_USE_STICKY_RESOLVER() {
156
+ return (0, _getenv().boolish)('EXPO_USE_STICKY_RESOLVER', false);
157
+ }
155
158
  /** Enable the unstable fast resolver for Metro. */ get EXPO_USE_FAST_RESOLVER() {
156
159
  return (0, _getenv().boolish)('EXPO_USE_FAST_RESOLVER', false);
157
160
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/env.ts"],"sourcesContent":["import { boolish, int, string } from 'getenv';\nimport process from 'node:process';\n\n// @expo/webpack-config -> expo-pwa -> @expo/image-utils: EXPO_IMAGE_UTILS_NO_SHARP\n\n// TODO: EXPO_CLI_USERNAME, EXPO_CLI_PASSWORD\n\nclass Env {\n /** Enable profiling metrics */\n get EXPO_PROFILE() {\n return boolish('EXPO_PROFILE', false);\n }\n\n /** Enable debug logging */\n get EXPO_DEBUG() {\n return boolish('EXPO_DEBUG', false);\n }\n\n /** Disable all network requests */\n get EXPO_OFFLINE() {\n return boolish('EXPO_OFFLINE', false);\n }\n\n /** Enable the beta version of Expo (TODO: Should this just be in the beta version of expo releases?) */\n get EXPO_BETA() {\n return boolish('EXPO_BETA', false);\n }\n\n /** Enable staging API environment */\n get EXPO_STAGING() {\n return boolish('EXPO_STAGING', false);\n }\n\n /** Enable local API environment */\n get EXPO_LOCAL() {\n return boolish('EXPO_LOCAL', false);\n }\n\n /** Is running in non-interactive CI mode */\n get CI() {\n return boolish('CI', false);\n }\n\n /** Disable telemetry (analytics) */\n get EXPO_NO_TELEMETRY() {\n return boolish('EXPO_NO_TELEMETRY', false);\n }\n\n /** Disable detaching telemetry to separate process */\n get EXPO_NO_TELEMETRY_DETACH() {\n return boolish('EXPO_NO_TELEMETRY_DETACH', false);\n }\n\n /** local directory to the universe repo for testing locally */\n get EXPO_UNIVERSE_DIR() {\n return string('EXPO_UNIVERSE_DIR', '');\n }\n\n /** @deprecated Default Webpack host string */\n get WEB_HOST() {\n return string('WEB_HOST', '0.0.0.0');\n }\n\n /** Skip warning users about a dirty git status */\n get EXPO_NO_GIT_STATUS() {\n return boolish('EXPO_NO_GIT_STATUS', false);\n }\n /** Disable auto web setup */\n get EXPO_NO_WEB_SETUP() {\n return boolish('EXPO_NO_WEB_SETUP', false);\n }\n /** Disable auto TypeScript setup */\n get EXPO_NO_TYPESCRIPT_SETUP() {\n return boolish('EXPO_NO_TYPESCRIPT_SETUP', false);\n }\n /** Disable all API caches. Does not disable bundler caches. */\n get EXPO_NO_CACHE() {\n return boolish('EXPO_NO_CACHE', false);\n }\n /** Disable the app select redirect page. */\n get EXPO_NO_REDIRECT_PAGE() {\n return boolish('EXPO_NO_REDIRECT_PAGE', false);\n }\n /** The React Metro port that's baked into react-native scripts and tools. */\n get RCT_METRO_PORT() {\n return int('RCT_METRO_PORT', 0);\n }\n /** Skip validating the manifest during `export`. */\n get EXPO_SKIP_MANIFEST_VALIDATION_TOKEN(): boolean {\n return !!string('EXPO_SKIP_MANIFEST_VALIDATION_TOKEN', '');\n }\n\n /** Public folder path relative to the project root. Default to `public` */\n get EXPO_PUBLIC_FOLDER(): string {\n return string('EXPO_PUBLIC_FOLDER', 'public');\n }\n\n /** Higher priority `$EDIOTR` variable for indicating which editor to use when pressing `o` in the Terminal UI. */\n get EXPO_EDITOR(): string {\n return string('EXPO_EDITOR', '');\n }\n\n /**\n * Overwrite the dev server URL, disregarding the `--port`, `--host`, `--tunnel`, `--lan`, `--localhost` arguments.\n * This is useful for browser editors that require custom proxy URLs.\n */\n get EXPO_PACKAGER_PROXY_URL(): string {\n return string('EXPO_PACKAGER_PROXY_URL', '');\n }\n\n /**\n * **Experimental** - Disable using `exp.direct` as the hostname for\n * `--tunnel` connections. This enables **https://** forwarding which\n * can be used to test universal links on iOS.\n *\n * This may cause issues with `expo-linking` and Expo Go.\n *\n * Select the exact subdomain by passing a string value that is not one of: `true`, `false`, `1`, `0`.\n */\n get EXPO_TUNNEL_SUBDOMAIN(): string | boolean {\n const subdomain = string('EXPO_TUNNEL_SUBDOMAIN', '');\n if (['0', 'false', ''].includes(subdomain)) {\n return false;\n } else if (['1', 'true'].includes(subdomain)) {\n return true;\n }\n return subdomain;\n }\n\n /**\n * Force Expo CLI to use the [`resolver.resolverMainFields`](https://facebook.github.io/metro/docs/configuration/#resolvermainfields) from the project `metro.config.js` for all platforms.\n *\n * By default, Expo CLI will use `['browser', 'module', 'main']` (default for Webpack) for web and the user-defined main fields for other platforms.\n */\n get EXPO_METRO_NO_MAIN_FIELD_OVERRIDE(): boolean {\n return boolish('EXPO_METRO_NO_MAIN_FIELD_OVERRIDE', false);\n }\n\n /**\n * HTTP/HTTPS proxy to connect to for network requests. Configures [https-proxy-agent](https://www.npmjs.com/package/https-proxy-agent).\n */\n get HTTP_PROXY(): string {\n return process.env.HTTP_PROXY || process.env.http_proxy || '';\n }\n\n /**\n * Use the network inspector by overriding the metro inspector proxy with a custom version.\n * @deprecated This has been replaced by `@react-native/dev-middleware` and is now unused.\n */\n get EXPO_NO_INSPECTOR_PROXY(): boolean {\n return boolish('EXPO_NO_INSPECTOR_PROXY', false);\n }\n\n /** Disable lazy bundling in Metro bundler. */\n get EXPO_NO_METRO_LAZY() {\n return boolish('EXPO_NO_METRO_LAZY', false);\n }\n\n /** Enable the unstable inverse dependency stack trace for Metro bundling errors. */\n get EXPO_METRO_UNSTABLE_ERRORS() {\n return boolish('EXPO_METRO_UNSTABLE_ERRORS', false);\n }\n\n /** Enable the unstable fast resolver for Metro. */\n get EXPO_USE_FAST_RESOLVER() {\n return boolish('EXPO_USE_FAST_RESOLVER', false);\n }\n\n /** Disable Environment Variable injection in client bundles. */\n get EXPO_NO_CLIENT_ENV_VARS(): boolean {\n return boolish('EXPO_NO_CLIENT_ENV_VARS', false);\n }\n\n /** Set the default `user` that should be passed to `--user` with ADB commands. Used for installing APKs on Android devices with multiple profiles. Defaults to `0`. */\n get EXPO_ADB_USER(): string {\n return string('EXPO_ADB_USER', '0');\n }\n\n /** Used internally to enable E2E utilities. This behavior is not stable to external users. */\n get __EXPO_E2E_TEST(): boolean {\n return boolish('__EXPO_E2E_TEST', false);\n }\n\n /** Unstable: Force single-bundle exports in production. */\n get EXPO_NO_BUNDLE_SPLITTING(): boolean {\n return boolish('EXPO_NO_BUNDLE_SPLITTING', false);\n }\n\n /**\n * Enable Atlas to gather bundle information during development or export.\n * Note, because this used to be an experimental feature, both `EXPO_ATLAS` and `EXPO_UNSTABLE_ATLAS` are supported.\n */\n get EXPO_ATLAS() {\n return boolish('EXPO_ATLAS', boolish('EXPO_UNSTABLE_ATLAS', false));\n }\n\n /** Unstable: Enable tree shaking for Metro. */\n get EXPO_UNSTABLE_TREE_SHAKING() {\n return boolish('EXPO_UNSTABLE_TREE_SHAKING', false);\n }\n\n /** Unstable: Enable eager bundling where transformation runs uncached after the entire bundle has been created. This is required for production tree shaking and less optimized for development bundling. */\n get EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH() {\n return boolish('EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH', false);\n }\n\n /** Enable the use of Expo's custom metro require implementation. The custom require supports better debugging, tree shaking, and React Server Components. */\n get EXPO_USE_METRO_REQUIRE() {\n return boolish('EXPO_USE_METRO_REQUIRE', false);\n }\n\n /** Internal key used to pass eager bundle data from the CLI to the native run scripts during `npx expo run` commands. */\n get __EXPO_EAGER_BUNDLE_OPTIONS() {\n return string('__EXPO_EAGER_BUNDLE_OPTIONS', '');\n }\n\n /** Disable server deployment during production builds (during `expo export:embed`). This is useful for testing API routes and server components against a local server. */\n get EXPO_NO_DEPLOY(): boolean {\n return boolish('EXPO_NO_DEPLOY', false);\n }\n\n /** Enable hydration during development when rendering Expo Web */\n get EXPO_WEB_DEV_HYDRATE(): boolean {\n return boolish('EXPO_WEB_DEV_HYDRATE', false);\n }\n\n /** Enable experimental React Server Functions support. */\n get EXPO_UNSTABLE_SERVER_FUNCTIONS(): boolean {\n return boolish('EXPO_UNSTABLE_SERVER_FUNCTIONS', false);\n }\n\n /** Enable unstable/experimental mode where React Native Web isn't required to run Expo apps on web. */\n get EXPO_NO_REACT_NATIVE_WEB(): boolean {\n return boolish('EXPO_NO_REACT_NATIVE_WEB', false);\n }\n\n /** Enable unstable/experimental support for deploying the native server in `npx expo run` commands. */\n get EXPO_UNSTABLE_DEPLOY_SERVER(): boolean {\n return boolish('EXPO_UNSTABLE_DEPLOY_SERVER', false);\n }\n\n /** Is running in EAS Build. This is set by EAS: https://docs.expo.dev/eas/environment-variables/ */\n get EAS_BUILD(): boolean {\n return boolish('EAS_BUILD', false);\n }\n\n /** Disable the React Native Directory compatibility check for new architecture when installing packages */\n get EXPO_NO_NEW_ARCH_COMPAT_CHECK(): boolean {\n return boolish('EXPO_NO_NEW_ARCH_COMPAT_CHECK', false);\n }\n\n /** Disable the dependency validation when installing other dependencies and starting the project */\n get EXPO_NO_DEPENDENCY_VALIDATION(): boolean {\n // Default to disabling when running in a web container (stackblitz, bolt, etc).\n const isWebContainer = process.versions.webcontainer != null;\n return boolish('EXPO_NO_DEPENDENCY_VALIDATION', isWebContainer);\n }\n\n /** Force Expo CLI to run in webcontainer mode, this has impact on which URL Expo is using by default */\n get EXPO_FORCE_WEBCONTAINER_ENV(): boolean {\n return boolish('EXPO_FORCE_WEBCONTAINER_ENV', false);\n }\n}\n\nexport const env = new Env();\n\nexport function envIsWebcontainer() {\n // See: https://github.com/unjs/std-env/blob/4b1e03c4efce58249858efc2cc5f5eac727d0adb/src/providers.ts#L134-L143\n return (\n env.EXPO_FORCE_WEBCONTAINER_ENV ||\n (process.env.SHELL === '/bin/jsh' && !!process.versions.webcontainer)\n );\n}\n"],"names":["env","envIsWebcontainer","Env","EXPO_PROFILE","boolish","EXPO_DEBUG","EXPO_OFFLINE","EXPO_BETA","EXPO_STAGING","EXPO_LOCAL","CI","EXPO_NO_TELEMETRY","EXPO_NO_TELEMETRY_DETACH","EXPO_UNIVERSE_DIR","string","WEB_HOST","EXPO_NO_GIT_STATUS","EXPO_NO_WEB_SETUP","EXPO_NO_TYPESCRIPT_SETUP","EXPO_NO_CACHE","EXPO_NO_REDIRECT_PAGE","RCT_METRO_PORT","int","EXPO_SKIP_MANIFEST_VALIDATION_TOKEN","EXPO_PUBLIC_FOLDER","EXPO_EDITOR","EXPO_PACKAGER_PROXY_URL","EXPO_TUNNEL_SUBDOMAIN","subdomain","includes","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","HTTP_PROXY","process","http_proxy","EXPO_NO_INSPECTOR_PROXY","EXPO_NO_METRO_LAZY","EXPO_METRO_UNSTABLE_ERRORS","EXPO_USE_FAST_RESOLVER","EXPO_NO_CLIENT_ENV_VARS","EXPO_ADB_USER","__EXPO_E2E_TEST","EXPO_NO_BUNDLE_SPLITTING","EXPO_ATLAS","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","EXPO_USE_METRO_REQUIRE","__EXPO_EAGER_BUNDLE_OPTIONS","EXPO_NO_DEPLOY","EXPO_WEB_DEV_HYDRATE","EXPO_UNSTABLE_SERVER_FUNCTIONS","EXPO_NO_REACT_NATIVE_WEB","EXPO_UNSTABLE_DEPLOY_SERVER","EAS_BUILD","EXPO_NO_NEW_ARCH_COMPAT_CHECK","EXPO_NO_DEPENDENCY_VALIDATION","isWebContainer","versions","webcontainer","EXPO_FORCE_WEBCONTAINER_ENV","SHELL"],"mappings":";;;;;;;;;;;IAwQaA,GAAG;eAAHA;;IAEGC,iBAAiB;eAAjBA;;;;yBA1QqB;;;;;;;gEACjB;;;;;;;;;;;AAEpB,mFAAmF;AAEnF,6CAA6C;AAE7C,MAAMC;IACJ,6BAA6B,GAC7B,IAAIC,eAAe;QACjB,OAAOC,IAAAA,iBAAO,EAAC,gBAAgB;IACjC;IAEA,yBAAyB,GACzB,IAAIC,aAAa;QACf,OAAOD,IAAAA,iBAAO,EAAC,cAAc;IAC/B;IAEA,iCAAiC,GACjC,IAAI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AqB;QACvB,OAAOhD,IAAAA,iBAAO,EAAC,aAAa;IAC9B;IAEA,yGAAyG,GACzG,IAAIiD,gCAAyC;QAC3C,OAAOjD,IAAAA,iBAAO,EAAC,iCAAiC;IAClD;IAEA,kGAAkG,GAClG,IAAIkD,gCAAyC;QAC3C,gFAAgF;QAChF,MAAMC,iBAAiBvB,sBAAO,CAACwB,QAAQ,CAACC,YAAY,IAAI;QACxD,OAAOrD,IAAAA,iBAAO,EAAC,iCAAiCmD;IAClD;IAEA,sGAAsG,GACtG,IAAIG,8BAAuC;QACzC,OAAOtD,IAAAA,iBAAO,EAAC,+BAA+B;IAChD;AACF;AAEO,MAAMJ,MAAM,IAAIE;AAEhB,SAASD;IACd,gHAAgH;IAChH,OACED,IAAI0D,2BAA2B,IAC9B1B,sBAAO,CAAChC,GAAG,CAAC2D,KAAK,KAAK,cAAc,CAAC,CAAC3B,sBAAO,CAACwB,QAAQ,CAACC,YAAY;AAExE"}
1
+ {"version":3,"sources":["../../../src/utils/env.ts"],"sourcesContent":["import { boolish, int, string } from 'getenv';\nimport process from 'node:process';\n\n// @expo/webpack-config -> expo-pwa -> @expo/image-utils: EXPO_IMAGE_UTILS_NO_SHARP\n\n// TODO: EXPO_CLI_USERNAME, EXPO_CLI_PASSWORD\n\nclass Env {\n /** Enable profiling metrics */\n get EXPO_PROFILE() {\n return boolish('EXPO_PROFILE', false);\n }\n\n /** Enable debug logging */\n get EXPO_DEBUG() {\n return boolish('EXPO_DEBUG', false);\n }\n\n /** Disable all network requests */\n get EXPO_OFFLINE() {\n return boolish('EXPO_OFFLINE', false);\n }\n\n /** Enable the beta version of Expo (TODO: Should this just be in the beta version of expo releases?) */\n get EXPO_BETA() {\n return boolish('EXPO_BETA', false);\n }\n\n /** Enable staging API environment */\n get EXPO_STAGING() {\n return boolish('EXPO_STAGING', false);\n }\n\n /** Enable local API environment */\n get EXPO_LOCAL() {\n return boolish('EXPO_LOCAL', false);\n }\n\n /** Is running in non-interactive CI mode */\n get CI() {\n return boolish('CI', false);\n }\n\n /** Disable telemetry (analytics) */\n get EXPO_NO_TELEMETRY() {\n return boolish('EXPO_NO_TELEMETRY', false);\n }\n\n /** Disable detaching telemetry to separate process */\n get EXPO_NO_TELEMETRY_DETACH() {\n return boolish('EXPO_NO_TELEMETRY_DETACH', false);\n }\n\n /** local directory to the universe repo for testing locally */\n get EXPO_UNIVERSE_DIR() {\n return string('EXPO_UNIVERSE_DIR', '');\n }\n\n /** @deprecated Default Webpack host string */\n get WEB_HOST() {\n return string('WEB_HOST', '0.0.0.0');\n }\n\n /** Skip warning users about a dirty git status */\n get EXPO_NO_GIT_STATUS() {\n return boolish('EXPO_NO_GIT_STATUS', false);\n }\n /** Disable auto web setup */\n get EXPO_NO_WEB_SETUP() {\n return boolish('EXPO_NO_WEB_SETUP', false);\n }\n /** Disable auto TypeScript setup */\n get EXPO_NO_TYPESCRIPT_SETUP() {\n return boolish('EXPO_NO_TYPESCRIPT_SETUP', false);\n }\n /** Disable all API caches. Does not disable bundler caches. */\n get EXPO_NO_CACHE() {\n return boolish('EXPO_NO_CACHE', false);\n }\n /** Disable the app select redirect page. */\n get EXPO_NO_REDIRECT_PAGE() {\n return boolish('EXPO_NO_REDIRECT_PAGE', false);\n }\n /** The React Metro port that's baked into react-native scripts and tools. */\n get RCT_METRO_PORT() {\n return int('RCT_METRO_PORT', 0);\n }\n /** Skip validating the manifest during `export`. */\n get EXPO_SKIP_MANIFEST_VALIDATION_TOKEN(): boolean {\n return !!string('EXPO_SKIP_MANIFEST_VALIDATION_TOKEN', '');\n }\n\n /** Public folder path relative to the project root. Default to `public` */\n get EXPO_PUBLIC_FOLDER(): string {\n return string('EXPO_PUBLIC_FOLDER', 'public');\n }\n\n /** Higher priority `$EDIOTR` variable for indicating which editor to use when pressing `o` in the Terminal UI. */\n get EXPO_EDITOR(): string {\n return string('EXPO_EDITOR', '');\n }\n\n /**\n * Overwrite the dev server URL, disregarding the `--port`, `--host`, `--tunnel`, `--lan`, `--localhost` arguments.\n * This is useful for browser editors that require custom proxy URLs.\n */\n get EXPO_PACKAGER_PROXY_URL(): string {\n return string('EXPO_PACKAGER_PROXY_URL', '');\n }\n\n /**\n * **Experimental** - Disable using `exp.direct` as the hostname for\n * `--tunnel` connections. This enables **https://** forwarding which\n * can be used to test universal links on iOS.\n *\n * This may cause issues with `expo-linking` and Expo Go.\n *\n * Select the exact subdomain by passing a string value that is not one of: `true`, `false`, `1`, `0`.\n */\n get EXPO_TUNNEL_SUBDOMAIN(): string | boolean {\n const subdomain = string('EXPO_TUNNEL_SUBDOMAIN', '');\n if (['0', 'false', ''].includes(subdomain)) {\n return false;\n } else if (['1', 'true'].includes(subdomain)) {\n return true;\n }\n return subdomain;\n }\n\n /**\n * Force Expo CLI to use the [`resolver.resolverMainFields`](https://facebook.github.io/metro/docs/configuration/#resolvermainfields) from the project `metro.config.js` for all platforms.\n *\n * By default, Expo CLI will use `['browser', 'module', 'main']` (default for Webpack) for web and the user-defined main fields for other platforms.\n */\n get EXPO_METRO_NO_MAIN_FIELD_OVERRIDE(): boolean {\n return boolish('EXPO_METRO_NO_MAIN_FIELD_OVERRIDE', false);\n }\n\n /**\n * HTTP/HTTPS proxy to connect to for network requests. Configures [https-proxy-agent](https://www.npmjs.com/package/https-proxy-agent).\n */\n get HTTP_PROXY(): string {\n return process.env.HTTP_PROXY || process.env.http_proxy || '';\n }\n\n /**\n * Use the network inspector by overriding the metro inspector proxy with a custom version.\n * @deprecated This has been replaced by `@react-native/dev-middleware` and is now unused.\n */\n get EXPO_NO_INSPECTOR_PROXY(): boolean {\n return boolish('EXPO_NO_INSPECTOR_PROXY', false);\n }\n\n /** Disable lazy bundling in Metro bundler. */\n get EXPO_NO_METRO_LAZY() {\n return boolish('EXPO_NO_METRO_LAZY', false);\n }\n\n /** Enable the unstable inverse dependency stack trace for Metro bundling errors. */\n get EXPO_METRO_UNSTABLE_ERRORS() {\n return boolish('EXPO_METRO_UNSTABLE_ERRORS', false);\n }\n\n /** Enable the experimental sticky resolver for Metro. */\n get EXPO_USE_STICKY_RESOLVER() {\n return boolish('EXPO_USE_STICKY_RESOLVER', false);\n }\n\n /** Enable the unstable fast resolver for Metro. */\n get EXPO_USE_FAST_RESOLVER() {\n return boolish('EXPO_USE_FAST_RESOLVER', false);\n }\n\n /** Disable Environment Variable injection in client bundles. */\n get EXPO_NO_CLIENT_ENV_VARS(): boolean {\n return boolish('EXPO_NO_CLIENT_ENV_VARS', false);\n }\n\n /** Set the default `user` that should be passed to `--user` with ADB commands. Used for installing APKs on Android devices with multiple profiles. Defaults to `0`. */\n get EXPO_ADB_USER(): string {\n return string('EXPO_ADB_USER', '0');\n }\n\n /** Used internally to enable E2E utilities. This behavior is not stable to external users. */\n get __EXPO_E2E_TEST(): boolean {\n return boolish('__EXPO_E2E_TEST', false);\n }\n\n /** Unstable: Force single-bundle exports in production. */\n get EXPO_NO_BUNDLE_SPLITTING(): boolean {\n return boolish('EXPO_NO_BUNDLE_SPLITTING', false);\n }\n\n /**\n * Enable Atlas to gather bundle information during development or export.\n * Note, because this used to be an experimental feature, both `EXPO_ATLAS` and `EXPO_UNSTABLE_ATLAS` are supported.\n */\n get EXPO_ATLAS() {\n return boolish('EXPO_ATLAS', boolish('EXPO_UNSTABLE_ATLAS', false));\n }\n\n /** Unstable: Enable tree shaking for Metro. */\n get EXPO_UNSTABLE_TREE_SHAKING() {\n return boolish('EXPO_UNSTABLE_TREE_SHAKING', false);\n }\n\n /** Unstable: Enable eager bundling where transformation runs uncached after the entire bundle has been created. This is required for production tree shaking and less optimized for development bundling. */\n get EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH() {\n return boolish('EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH', false);\n }\n\n /** Enable the use of Expo's custom metro require implementation. The custom require supports better debugging, tree shaking, and React Server Components. */\n get EXPO_USE_METRO_REQUIRE() {\n return boolish('EXPO_USE_METRO_REQUIRE', false);\n }\n\n /** Internal key used to pass eager bundle data from the CLI to the native run scripts during `npx expo run` commands. */\n get __EXPO_EAGER_BUNDLE_OPTIONS() {\n return string('__EXPO_EAGER_BUNDLE_OPTIONS', '');\n }\n\n /** Disable server deployment during production builds (during `expo export:embed`). This is useful for testing API routes and server components against a local server. */\n get EXPO_NO_DEPLOY(): boolean {\n return boolish('EXPO_NO_DEPLOY', false);\n }\n\n /** Enable hydration during development when rendering Expo Web */\n get EXPO_WEB_DEV_HYDRATE(): boolean {\n return boolish('EXPO_WEB_DEV_HYDRATE', false);\n }\n\n /** Enable experimental React Server Functions support. */\n get EXPO_UNSTABLE_SERVER_FUNCTIONS(): boolean {\n return boolish('EXPO_UNSTABLE_SERVER_FUNCTIONS', false);\n }\n\n /** Enable unstable/experimental mode where React Native Web isn't required to run Expo apps on web. */\n get EXPO_NO_REACT_NATIVE_WEB(): boolean {\n return boolish('EXPO_NO_REACT_NATIVE_WEB', false);\n }\n\n /** Enable unstable/experimental support for deploying the native server in `npx expo run` commands. */\n get EXPO_UNSTABLE_DEPLOY_SERVER(): boolean {\n return boolish('EXPO_UNSTABLE_DEPLOY_SERVER', false);\n }\n\n /** Is running in EAS Build. This is set by EAS: https://docs.expo.dev/eas/environment-variables/ */\n get EAS_BUILD(): boolean {\n return boolish('EAS_BUILD', false);\n }\n\n /** Disable the React Native Directory compatibility check for new architecture when installing packages */\n get EXPO_NO_NEW_ARCH_COMPAT_CHECK(): boolean {\n return boolish('EXPO_NO_NEW_ARCH_COMPAT_CHECK', false);\n }\n\n /** Disable the dependency validation when installing other dependencies and starting the project */\n get EXPO_NO_DEPENDENCY_VALIDATION(): boolean {\n // Default to disabling when running in a web container (stackblitz, bolt, etc).\n const isWebContainer = process.versions.webcontainer != null;\n return boolish('EXPO_NO_DEPENDENCY_VALIDATION', isWebContainer);\n }\n\n /** Force Expo CLI to run in webcontainer mode, this has impact on which URL Expo is using by default */\n get EXPO_FORCE_WEBCONTAINER_ENV(): boolean {\n return boolish('EXPO_FORCE_WEBCONTAINER_ENV', false);\n }\n}\n\nexport const env = new Env();\n\nexport function envIsWebcontainer() {\n // See: https://github.com/unjs/std-env/blob/4b1e03c4efce58249858efc2cc5f5eac727d0adb/src/providers.ts#L134-L143\n return (\n env.EXPO_FORCE_WEBCONTAINER_ENV ||\n (process.env.SHELL === '/bin/jsh' && !!process.versions.webcontainer)\n );\n}\n"],"names":["env","envIsWebcontainer","Env","EXPO_PROFILE","boolish","EXPO_DEBUG","EXPO_OFFLINE","EXPO_BETA","EXPO_STAGING","EXPO_LOCAL","CI","EXPO_NO_TELEMETRY","EXPO_NO_TELEMETRY_DETACH","EXPO_UNIVERSE_DIR","string","WEB_HOST","EXPO_NO_GIT_STATUS","EXPO_NO_WEB_SETUP","EXPO_NO_TYPESCRIPT_SETUP","EXPO_NO_CACHE","EXPO_NO_REDIRECT_PAGE","RCT_METRO_PORT","int","EXPO_SKIP_MANIFEST_VALIDATION_TOKEN","EXPO_PUBLIC_FOLDER","EXPO_EDITOR","EXPO_PACKAGER_PROXY_URL","EXPO_TUNNEL_SUBDOMAIN","subdomain","includes","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","HTTP_PROXY","process","http_proxy","EXPO_NO_INSPECTOR_PROXY","EXPO_NO_METRO_LAZY","EXPO_METRO_UNSTABLE_ERRORS","EXPO_USE_STICKY_RESOLVER","EXPO_USE_FAST_RESOLVER","EXPO_NO_CLIENT_ENV_VARS","EXPO_ADB_USER","__EXPO_E2E_TEST","EXPO_NO_BUNDLE_SPLITTING","EXPO_ATLAS","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","EXPO_USE_METRO_REQUIRE","__EXPO_EAGER_BUNDLE_OPTIONS","EXPO_NO_DEPLOY","EXPO_WEB_DEV_HYDRATE","EXPO_UNSTABLE_SERVER_FUNCTIONS","EXPO_NO_REACT_NATIVE_WEB","EXPO_UNSTABLE_DEPLOY_SERVER","EAS_BUILD","EXPO_NO_NEW_ARCH_COMPAT_CHECK","EXPO_NO_DEPENDENCY_VALID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AC,+BAA+B;IAC/C;IAEA,yKAAyK,GACzK,IAAIkC,iBAA0B;QAC5B,OAAO5C,IAAAA,iBAAO,EAAC,kBAAkB;IACnC;IAEA,gEAAgE,GAChE,IAAI6C,uBAAgC;QAClC,OAAO7C,IAAAA,iBAAO,EAAC,wBAAwB;IACzC;IAEA,wDAAwD,GACxD,IAAI8C,iCAA0C;QAC5C,OAAO9C,IAAAA,iBAAO,EAAC,kCAAkC;IACnD;IAEA,qGAAqG,GACrG,IAAI+C,2BAAoC;QACtC,OAAO/C,IAAAA,iBAAO,EAAC,4BAA4B;IAC7C;IAEA,qGAAqG,GACrG,IAAIgD,8BAAuC;QACzC,OAAOhD,IAAAA,iBAAO,EAAC,+BAA+B;IAChD;IAEA,kGAAkG,GAClG,IAAIiD,YAAqB;QACvB,OAAOjD,IAAAA,iBAAO,EAAC,aAAa;IAC9B;IAEA,yGAAyG,GACzG,IAAIkD,gCAAyC;QAC3C,OAAOlD,IAAAA,iBAAO,EAAC,iCAAiC;IAClD;IAEA,kGAAkG,GAClG,IAAImD,gCAAyC;QAC3C,gFAAgF;QAChF,MAAMC,iBAAiBxB,sBAAO,CAACyB,QAAQ,CAACC,YAAY,IAAI;QACxD,OAAOtD,IAAAA,iBAAO,EAAC,iCAAiCoD;IAClD;IAEA,sGAAsG,GACtG,IAAIG,8BAAuC;QACzC,OAAOvD,IAAAA,iBAAO,EAAC,+BAA+B;IAChD;AACF;AAEO,MAAMJ,MAAM,IAAIE;AAEhB,SAASD;IACd,gHAAgH;IAChH,OACED,IAAI2D,2BAA2B,IAC9B3B,sBAAO,CAAChC,GAAG,CAAC4D,KAAK,KAAK,cAAc,CAAC,CAAC5B,sBAAO,CAACyB,QAAQ,CAACC,YAAY;AAExE"}
@@ -33,7 +33,7 @@ class FetchClient {
33
33
  this.headers = {
34
34
  accept: 'application/json',
35
35
  'content-type': 'application/json',
36
- 'user-agent': `expo-cli/${"1.0.0-canary-20250709-136b77f"}`,
36
+ 'user-agent': `expo-cli/${"1.0.0-canary-20250713-8f814f8"}`,
37
37
  authorization: 'Basic ' + _nodebuffer().Buffer.from(`${target}:`).toString('base64')
38
38
  };
39
39
  }
@@ -83,7 +83,7 @@ function createContext() {
83
83
  cpu: summarizeCpuInfo(),
84
84
  app: {
85
85
  name: 'expo/cli',
86
- version: "1.0.0-canary-20250709-136b77f"
86
+ version: "1.0.0-canary-20250713-8f814f8"
87
87
  },
88
88
  ci: _ciinfo().isCI ? {
89
89
  name: _ciinfo().name,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expo/cli",
3
- "version": "1.0.0-canary-20250709-136b77f",
3
+ "version": "1.0.0-canary-20250713-8f814f8",
4
4
  "description": "The Expo CLI",
5
5
  "main": "build/bin/cli",
6
6
  "bin": {
@@ -42,17 +42,17 @@
42
42
  "@0no-co/graphql.web": "^1.0.8",
43
43
  "@babel/runtime": "^7.20.0",
44
44
  "@expo/code-signing-certificates": "^0.0.5",
45
- "@expo/config": "11.0.14-canary-20250709-136b77f",
46
- "@expo/config-plugins": "10.0.4-canary-20250709-136b77f",
45
+ "@expo/config": "11.0.14-canary-20250713-8f814f8",
46
+ "@expo/config-plugins": "10.0.4-canary-20250713-8f814f8",
47
47
  "@expo/devcert": "^1.1.2",
48
- "@expo/env": "1.0.8-canary-20250709-136b77f",
49
- "@expo/image-utils": "0.7.7-canary-20250709-136b77f",
50
- "@expo/json-file": "9.1.6-canary-20250709-136b77f",
51
- "@expo/metro-config": "0.21.0-canary-20250709-136b77f",
52
- "@expo/osascript": "2.2.6-canary-20250709-136b77f",
53
- "@expo/package-manager": "1.8.7-canary-20250709-136b77f",
54
- "@expo/plist": "0.3.6-canary-20250709-136b77f",
55
- "@expo/prebuild-config": "9.1.0-canary-20250709-136b77f",
48
+ "@expo/env": "1.0.8-canary-20250713-8f814f8",
49
+ "@expo/image-utils": "0.7.7-canary-20250713-8f814f8",
50
+ "@expo/json-file": "9.1.6-canary-20250713-8f814f8",
51
+ "@expo/metro-config": "0.21.0-canary-20250713-8f814f8",
52
+ "@expo/osascript": "2.2.6-canary-20250713-8f814f8",
53
+ "@expo/package-manager": "1.8.7-canary-20250713-8f814f8",
54
+ "@expo/plist": "0.3.6-canary-20250713-8f814f8",
55
+ "@expo/prebuild-config": "9.1.0-canary-20250713-8f814f8",
56
56
  "@expo/spawn-async": "^1.7.2",
57
57
  "@expo/ws-tunnel": "^1.0.1",
58
58
  "@expo/xcpretty": "^4.3.0",
@@ -109,7 +109,7 @@
109
109
  "devDependencies": {
110
110
  "@expo/multipart-body-parser": "^1.0.0",
111
111
  "@expo/ngrok": "4.1.3",
112
- "@expo/server": "0.6.4-canary-20250709-136b77f",
112
+ "@expo/server": "0.6.4-canary-20250713-8f814f8",
113
113
  "@graphql-codegen/cli": "^2.16.3",
114
114
  "@graphql-codegen/typescript": "^2.8.7",
115
115
  "@graphql-codegen/typescript-operations": "^2.5.12",
@@ -139,7 +139,7 @@
139
139
  "@types/ws": "^8.5.4",
140
140
  "devtools-protocol": "^0.0.1113120",
141
141
  "expo-atlas": "^0.4.1",
142
- "expo-module-scripts": "4.1.10-canary-20250709-136b77f",
142
+ "expo-module-scripts": "4.1.10-canary-20250713-8f814f8",
143
143
  "find-process": "^1.4.7",
144
144
  "jest-runner-tsd": "^6.0.0",
145
145
  "klaw-sync": "^6.0.0",