@expo/cli 55.0.0-canary-20251216-3f01dbf → 55.0.0-canary-20251230-fc48ddc
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 +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +8 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/createExpoAutolinkingResolver.js +1 -3
- package/build/src/start/server/metro/createExpoAutolinkingResolver.js.map +1 -1
- package/build/src/start/server/metro/createExpoFallbackResolver.js +1 -3
- package/build/src/start/server/metro/createExpoFallbackResolver.js.map +1 -1
- package/build/src/start/server/metro/createServerComponentsMiddleware.js +1 -2
- package/build/src/start/server/metro/createServerComponentsMiddleware.js.map +1 -1
- package/build/src/start/server/metro/instantiateMetro.js +11 -8
- package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
- package/build/src/start/server/metro/runServer-fork.js +7 -4
- package/build/src/start/server/metro/runServer-fork.js.map +1 -1
- package/build/src/start/server/metro/withMetroMultiPlatform.js +0 -3
- package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
- package/build/src/utils/delay.js +8 -2
- package/build/src/utils/delay.js.map +1 -1
- package/build/src/utils/exit.js +47 -6
- package/build/src/utils/exit.js.map +1 -1
- package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
- package/build/src/utils/telemetry/utils/context.js +1 -1
- package/package.json +20 -20
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/runServer-fork.ts"],"sourcesContent":["// Copyright © 2023 650 Industries.\n// Copyright (c) Meta Platforms, Inc. and affiliates.\n//\n// Forks https://github.com/facebook/metro/blob/b80d9a0f638ee9fb82ff69cd3c8d9f4309ca1da2/packages/metro/src/index.flow.js#L57\n// and adds the ability to access the bundler instance.\nimport { createConnectMiddleware } from '@expo/metro/metro';\nimport type { RunServerOptions } from '@expo/metro/metro';\nimport MetroHmrServer, { type Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport Server from '@expo/metro/metro/Server';\nimport createWebsocketServer from '@expo/metro/metro/lib/createWebsocketServer';\nimport type { ConfigT } from '@expo/metro/metro-config';\nimport assert from 'assert';\nimport http from 'http';\nimport https from 'https';\nimport { parse } from 'url';\nimport type { WebSocketServer } from 'ws';\n\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { Log } from '../../../log';\nimport { getRunningProcess } from '../../../utils/getRunningProcess';\nimport type { ConnectAppType } from '../middleware/server.types';\n\nexport const runServer = async (\n metroBundler: MetroBundlerDevServer,\n config: ConfigT,\n {\n hasReducedPerformance = false,\n host,\n onError,\n onReady,\n secureServerOptions,\n waitForBundler = false,\n websocketEndpoints = {},\n watch,\n }: RunServerOptions,\n {\n mockServer,\n }: {\n // Use a mock server object instead of creating a real server, this is used in export cases where we want to reuse codepaths but not actually start a server.\n mockServer: boolean;\n }\n): Promise<{\n server: http.Server | https.Server;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n metro: Server;\n}> => {\n // await earlyPortCheck(host, config.server.port);\n\n // if (secure != null || secureCert != null || secureKey != null) {\n // // eslint-disable-next-line no-console\n // console.warn(\n // chalk.inverse.yellow.bold(' DEPRECATED '),\n // 'The `secure`, `secureCert`, and `secureKey` options are now deprecated. ' +\n // 'Use the `secureServerOptions` object instead to pass options to ' +\n // \"Metro's https development server.\",\n // );\n // }\n\n const { middleware, end, metroServer } = await createConnectMiddleware(config, {\n hasReducedPerformance,\n waitForBundler,\n watch,\n });\n\n if (!mockServer) {\n assert(typeof (middleware as any).use === 'function');\n }\n const serverApp = middleware as ConnectAppType;\n\n let httpServer: http.Server | https.Server;\n\n if (secureServerOptions != null) {\n httpServer = https.createServer(secureServerOptions, serverApp);\n } else {\n httpServer = http.createServer(serverApp);\n }\n\n httpServer.on('error', (error) => {\n if ('code' in error && error.code === 'EADDRINUSE') {\n // If `Error: listen EADDRINUSE: address already in use :::8081` then print additional info\n // about the process before throwing.\n const info = getRunningProcess(config.server.port);\n if (info) {\n Log.error(\n `Port ${config.server.port} is busy running ${info.command} in: ${info.directory}`\n );\n }\n }\n\n if (onError) {\n onError(error);\n }\n end();\n });\n\n // Disable any kind of automatic timeout behavior for incoming\n // requests in case it takes the packager more than the default\n // timeout of 120 seconds to respond to a request.\n httpServer.timeout = 0;\n\n
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/runServer-fork.ts"],"sourcesContent":["// Copyright © 2023 650 Industries.\n// Copyright (c) Meta Platforms, Inc. and affiliates.\n//\n// Forks https://github.com/facebook/metro/blob/b80d9a0f638ee9fb82ff69cd3c8d9f4309ca1da2/packages/metro/src/index.flow.js#L57\n// and adds the ability to access the bundler instance.\nimport { createConnectMiddleware } from '@expo/metro/metro';\nimport type { RunServerOptions } from '@expo/metro/metro';\nimport MetroHmrServer, { type Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport Server from '@expo/metro/metro/Server';\nimport createWebsocketServer from '@expo/metro/metro/lib/createWebsocketServer';\nimport type { ConfigT } from '@expo/metro/metro-config';\nimport assert from 'assert';\nimport http from 'http';\nimport https from 'https';\nimport { parse } from 'url';\nimport type { WebSocketServer } from 'ws';\n\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { Log } from '../../../log';\nimport { getRunningProcess } from '../../../utils/getRunningProcess';\nimport type { ConnectAppType } from '../middleware/server.types';\n\nexport const runServer = async (\n metroBundler: MetroBundlerDevServer,\n config: ConfigT,\n {\n hasReducedPerformance = false,\n host,\n onError,\n onReady,\n secureServerOptions,\n waitForBundler = false,\n websocketEndpoints = {},\n watch,\n }: RunServerOptions,\n {\n mockServer,\n }: {\n // Use a mock server object instead of creating a real server, this is used in export cases where we want to reuse codepaths but not actually start a server.\n mockServer: boolean;\n }\n): Promise<{\n server: http.Server | https.Server;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n metro: Server;\n}> => {\n // await earlyPortCheck(host, config.server.port);\n\n // if (secure != null || secureCert != null || secureKey != null) {\n // // eslint-disable-next-line no-console\n // console.warn(\n // chalk.inverse.yellow.bold(' DEPRECATED '),\n // 'The `secure`, `secureCert`, and `secureKey` options are now deprecated. ' +\n // 'Use the `secureServerOptions` object instead to pass options to ' +\n // \"Metro's https development server.\",\n // );\n // }\n\n const { middleware, end, metroServer } = await createConnectMiddleware(config, {\n hasReducedPerformance,\n waitForBundler,\n watch,\n });\n\n if (!mockServer) {\n assert(typeof (middleware as any).use === 'function');\n }\n const serverApp = middleware as ConnectAppType;\n\n let httpServer: http.Server | https.Server;\n\n if (secureServerOptions != null) {\n httpServer = https.createServer(secureServerOptions, serverApp);\n } else {\n httpServer = http.createServer(serverApp);\n }\n\n httpServer.on('error', (error) => {\n if ('code' in error && error.code === 'EADDRINUSE') {\n // If `Error: listen EADDRINUSE: address already in use :::8081` then print additional info\n // about the process before throwing.\n const info = getRunningProcess(config.server.port);\n if (info) {\n Log.error(\n `Port ${config.server.port} is busy running ${info.command} in: ${info.directory}`\n );\n }\n }\n\n if (onError) {\n onError(error);\n }\n end();\n });\n\n // Disable any kind of automatic timeout behavior for incoming\n // requests in case it takes the packager more than the default\n // timeout of 120 seconds to respond to a request.\n httpServer.timeout = 0;\n\n // Extend the close method to ensure all websocket servers are closed, and connections are terminated\n const originalClose = httpServer.close.bind(httpServer);\n\n httpServer.close = function closeHttpServer(callback) {\n originalClose((err?: Error) => {\n // Always call end() to clean up Metro workers, even if the server wasn't started.\n // The 'close' event doesn't fire for servers that were never started (mockServer case),\n // so we need to call end() explicitly here.\n end();\n callback?.(err);\n });\n\n // Close all websocket servers, including possible client connections (see: https://github.com/websockets/ws/issues/2137#issuecomment-1507469375)\n for (const endpoint of Object.values(websocketEndpoints) as WebSocketServer[]) {\n endpoint.close();\n endpoint.clients.forEach((client) => client.terminate());\n }\n\n // Forcibly close active connections\n this.closeAllConnections();\n return this;\n };\n\n if (mockServer) {\n return { server: httpServer, hmrServer: null, metro: metroServer };\n }\n\n return new Promise<{\n server: http.Server | https.Server;\n hmrServer: MetroHmrServer<MetroHmrClient>;\n metro: Server;\n }>((resolve, reject) => {\n httpServer.on('error', (error) => {\n reject(error);\n });\n\n httpServer.listen(config.server.port, host, () => {\n if (onReady) {\n onReady(httpServer);\n }\n\n const hmrServer = new MetroHmrServer(\n metroServer.getBundler(),\n metroServer.getCreateModuleId(),\n config\n );\n\n Object.assign(websocketEndpoints, {\n '/hot': createWebsocketServer({\n websocketServer: hmrServer,\n }),\n });\n\n httpServer.on('upgrade', (request, socket, head) => {\n const { pathname } = parse(request.url!);\n if (pathname != null && websocketEndpoints[pathname]) {\n websocketEndpoints[pathname].handleUpgrade(request, socket, head, (ws) => {\n websocketEndpoints[pathname].emit('connection', ws, request);\n });\n } else {\n socket.destroy();\n }\n });\n\n resolve({ server: httpServer, hmrServer, metro: metroServer });\n });\n });\n};\n"],"names":["runServer","metroBundler","config","hasReducedPerformance","host","onError","onReady","secureServerOptions","waitForBundler","websocketEndpoints","watch","mockServer","middleware","end","metroServer","createConnectMiddleware","assert","use","serverApp","httpServer","https","createServer","http","on","error","code","info","getRunningProcess","server","port","Log","command","directory","timeout","originalClose","close","bind","closeHttpServer","callback","err","endpoint","Object","values","clients","forEach","client","terminate","closeAllConnections","hmrServer","metro","Promise","resolve","reject","listen","MetroHmrServer","getBundler","getCreateModuleId","assign","createWebsocketServer","websocketServer","request","socket","head","pathname","parse","url","handleUpgrade","ws","emit","destroy"],"mappings":"AAAA,mCAAmC;AACnC,qDAAqD;AACrD,EAAE;AACF,6HAA6H;AAC7H,uDAAuD;;;;;+BAkB1CA;;;eAAAA;;;;yBAjB2B;;;;;;;gEAEsB;;;;;;;gEAE5B;;;;;;;gEAEf;;;;;;;gEACF;;;;;;;gEACC;;;;;;;yBACI;;;;;;qBAIF;mCACc;;;;;;AAG3B,MAAMA,YAAY,OACvBC,cACAC,QACA,EACEC,wBAAwB,KAAK,EAC7BC,IAAI,EACJC,OAAO,EACPC,OAAO,EACPC,mBAAmB,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BAAEvB,QAAQT;gBAAY6B;gBAAWC,OAAOnC;YAAY;QAC9D;IACF;AACF"}
|
|
@@ -699,9 +699,6 @@ async function withMetroMultiPlatformAsync(projectRoot, { config, exp, platformB
|
|
|
699
699
|
// NOTE(@kitten): This is now always active and EXPO_USE_METRO_REQUIRE / isNamedRequiresEnabled is disregarded
|
|
700
700
|
const metroDefaults = require('@expo/metro/metro-config/defaults/defaults');
|
|
701
701
|
asWritable(metroDefaults).moduleSystem = require.resolve('@expo/cli/build/metro-require/require');
|
|
702
|
-
if (!config.projectRoot) {
|
|
703
|
-
asWritable(config).projectRoot = projectRoot;
|
|
704
|
-
}
|
|
705
702
|
// Required for @expo/metro-runtime to format paths in the web LogBox.
|
|
706
703
|
process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;
|
|
707
704
|
// This is used for running Expo CLI in development against projects outside the monorepo.
|
|
@@ -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 type { ExpoConfig, Platform } from '@expo/config';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ConfigT } from '@expo/metro/metro-config';\nimport type {\n Resolution,\n ResolutionContext,\n CustomResolutionContext,\n} from '@expo/metro/metro-resolver';\nimport { resolve as resolver } from '@expo/metro/metro-resolver';\nimport type { SourceFileResolution } from '@expo/metro/metro-resolver/types';\nimport fs from 'fs';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport {\n createAutolinkingModuleResolverInput,\n createAutolinkingModuleResolver,\n AutolinkingModuleResolverInput,\n} from './createExpoAutolinkingResolver';\nimport { createFallbackModuleResolver } from './createExpoFallbackResolver';\nimport { FailedToResolveNativeOnlyModuleError } from './errors/FailedToResolveNativeOnlyModuleError';\nimport { isNodeExternal, shouldCreateVirtualShim } from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { getMetroBundlerWithVirtualModules } from './metroVirtualModules';\nimport { withMetroErrorReportingResolver } from './withMetroErrorReportingResolver';\nimport { withMetroMutatedResolverContext, withMetroResolvers } from './withMetroResolvers';\nimport { withMetroSupervisingTransformWorker } from './withMetroSupervisingTransformWorker';\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\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\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 asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\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 // NOTE(@hassankhan): We need to wrap require in an arrow function rather than assigning\n // it directly because `workerd` loses its `this` context when `require` is dereferenced\n // and called later.\n return `global.$$require_external = typeof require !== \"undefined\" ? (m) => require(m) : () => 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 const virtualModulesPolyfills = [virtualModuleId, virtualEnvVarId];\n\n if (ctx.platform === 'web') {\n try {\n const rnGetPolyfills: () => string[] = require('react-native/rn-get-polyfills');\n return [\n ...virtualModulesPolyfills,\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 // NOTE(@kitten): This is technically the public API to get polyfills rather than resolving directly into\n // `@react-native/js-polyfills`. We should really just start vendoring these, but for now, this exclusion works\n ...rnGetPolyfills().filter((x: string) => !x.includes('/console')),\n ];\n } catch (error: any) {\n if ('code' in error && error.code === 'MODULE_NOT_FOUND') {\n // If react-native is not installed, because we're targeting web, we still continue\n // This should be rare, but we add it so we don't unnecessarily have a fixed peer dependency on react-native\n debug(\n 'Skipping react-native/rn-get-polyfills from getPolyfills. react-native is not installed.'\n );\n return virtualModulesPolyfills;\n } else {\n throw error;\n }\n }\n }\n\n // Generally uses `@expo/metro-config`'s `getPolyfills` function, unless overridden\n const polyfills = originalGetPolyfills(ctx);\n return [\n ...polyfills,\n ...virtualModulesPolyfills,\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 */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n tsconfig,\n autolinkingModuleResolverInput,\n isTsconfigPathsEnabled,\n isExporting,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n tsconfig: TsConfigPaths | null;\n autolinkingModuleResolverInput?: AutolinkingModuleResolverInput;\n isTsconfigPathsEnabled?: boolean;\n isExporting?: boolean;\n isReactServerComponentsEnabled?: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isReactServerComponentsEnabled) {\n Log.warn(`React Server Components (beta) is enabled.`);\n }\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 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 // used to resolve externals in `requestCustomExternals` from the project root\n const projectRootOriginPath = path.join(config.projectRoot, 'package.json');\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 // We're manually resolving the `asyncRequireModulePath` since it's a module request\n // However, in isolated installations it might not resolve from all paths, so we're resolving\n // it from the project root manually\n let _asyncRequireModuleResolvedPath: string | null | undefined;\n const getAsyncRequireModule = () => {\n if (_asyncRequireModuleResolvedPath === undefined) {\n _asyncRequireModuleResolvedPath =\n resolveFrom.silent(config.projectRoot, config.transformer.asyncRequireModulePath) ?? null;\n }\n return _asyncRequireModuleResolvedPath\n ? ({ type: 'sourceFile', filePath: _asyncRequireModuleResolvedPath } as const)\n : null;\n };\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 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 = getStrictResolver(context, platform)(moduleName);\n const realPath = realModule.type === 'sourceFile' ? realModule.filePath : moduleName;\n const opaqueId = idFactory(realPath, {\n platform: platform!,\n environment: context.customResolverOptions?.environment,\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 // TODO(@kitten): Temporary workaround. Our externals logic here isn't generic and only works\n // for development and not exports. We never intend to use it in exported production bundles,\n // however, this is still a dangerous implementation. To protect us from externalizing modules\n // that aren't available to the app, we force any resolution to happen via the project root\n const projectRootContext: ResolutionContext = {\n ...context,\n nodeModulesPaths: [],\n originModulePath: projectRootOriginPath,\n disableHierarchicalLookup: false,\n };\n const externModule = getStrictResolver(projectRootContext, platform)(moduleName);\n if (externModule.type !== 'sourceFile') {\n return null;\n }\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 external.replace satisfies never;\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 (assetRegistryPath) and async require module (asyncRequireModulePath)\n function requestStableConfigModules(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n if (moduleName === config.transformer.asyncRequireModulePath) {\n return getAsyncRequireModule();\n }\n\n // TODO(@kitten): Compare against `config.transformer.assetRegistryPath`\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 createAutolinkingModuleResolver(autolinkingModuleResolverInput, {\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 const normalizedPath = normalizeSlashes(result.filePath);\n\n const doReplace = (from: string, to: string | undefined, options?: { throws?: boolean }) =>\n doReplaceHelper(from, to, {\n normalizedPath,\n doResolve,\n ...options,\n });\n const doReplaceStrict = (from: string, to: string | undefined) =>\n doReplace(from, to, { throws: true });\n\n if (env.EXPO_UNSTABLE_WEB_MODAL) {\n const webModalModule = doReplace(\n 'expo-router/build/layouts/_web-modal.js',\n 'expo-router/build/layouts/ExperimentalModalStack.js'\n );\n if (webModalModule) {\n debug('Using `_unstable-web-modal` implementation.');\n return webModalModule;\n }\n }\n\n if (platform === 'web') {\n if (result.filePath.includes('node_modules')) {\n // Disallow importing confusing native modules on web\n if (\n [\n 'react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore',\n 'react-native/Libraries/Utilities/codegenNativeCommands',\n 'react-native/Libraries/Utilities/codegenNativeComponent',\n ].some((matcher) =>\n // Support absolute and modules with .js extensions.\n moduleName.includes(matcher)\n )\n ) {\n throw new FailedToResolveNativeOnlyModuleError(\n moduleName,\n path.relative(config.projectRoot, context.originModulePath)\n );\n }\n\n // Replace with static shims\n\n // Drop everything up until the `node_modules` folder.\n const normalName = normalizedPath.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 // Shim out React Native native runtime globals in server mode for native.\n if (isServer) {\n const emptyModule = doReplace('react-native/Libraries/Core/InitializeCore.js', undefined);\n if (emptyModule) {\n debug('Shimming out InitializeCore for React Native in native SSR bundle');\n return emptyModule;\n }\n }\n\n const hmrModule = doReplaceStrict(\n 'react-native/Libraries/Utilities/HMRClient.js',\n 'expo/src/async-require/hmr.ts'\n );\n if (hmrModule) return hmrModule;\n\n if (env.EXPO_UNSTABLE_LOG_BOX) {\n const logBoxModule = doReplace(\n 'react-native/Libraries/LogBox/LogBoxInspectorContainer.js',\n '@expo/log-box/swap-rn-logbox.js'\n );\n if (logBoxModule) return logBoxModule;\n\n const logBoxParserModule = doReplace(\n 'react-native/Libraries/LogBox/Data/parseLogBoxLog.js',\n '@expo/log-box/swap-rn-logbox-parser.js'\n );\n if (logBoxParserModule) return logBoxParserModule;\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 = asWritable({\n ...immutableContext,\n preferNativePlatform: platform !== 'web',\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(\n withMetroSupervisingTransformWorker(metroConfigWithCustomContext)\n );\n}\n\nfunction doReplaceHelper(\n from: string,\n to: string | undefined,\n {\n throws = false,\n normalizedPath,\n doResolve,\n }: {\n throws?: boolean;\n normalizedPath: string;\n doResolve: StrictResolver;\n }\n): SourceFileResolution | { type: 'empty' } | undefined {\n if (!normalizedPath.endsWith(from)) {\n return undefined;\n }\n\n if (to === undefined) {\n return {\n type: 'empty',\n };\n }\n\n try {\n const hmrModule = doResolve(to);\n if (hmrModule.type === 'sourceFile') {\n debug(`Using \\`${to}\\` implementation.`);\n return hmrModule;\n }\n } catch (resolutionError) {\n if (throws) {\n throw new Error(`Failed to replace ${from} with ${to}. Resolution of ${to} failed.`, {\n cause: resolutionError,\n });\n }\n\n debug(`Failed to resolve ${to} when swapping from ${from}: ${resolutionError}`);\n }\n return undefined;\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 isAutolinkingResolverEnabled,\n isExporting,\n\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n isAutolinkingResolverEnabled?: boolean;\n isExporting?: boolean;\n\n isReactServerComponentsEnabled: boolean;\n isNamedRequiresEnabled: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n // Change the default metro-runtime to a custom one that supports bundle splitting.\n // NOTE(@kitten): This is now always active and EXPO_USE_METRO_REQUIRE / isNamedRequiresEnabled is disregarded\n const metroDefaults: typeof import('@expo/metro/metro-config/defaults/defaults') = require('@expo/metro/metro-config/defaults/defaults');\n asWritable(metroDefaults).moduleSystem = require.resolve('@expo/cli/build/metro-require/require');\n\n if (!config.projectRoot) {\n asWritable(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 const watchFolders = (config.watchFolders as string[]) || [];\n asWritable(config).watchFolders = watchFolders;\n\n watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n 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 }\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 asWritable(config.resolver).platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config, { getMetroBundler });\n\n let autolinkingModuleResolverInput: AutolinkingModuleResolverInput | undefined;\n if (isAutolinkingResolverEnabled) {\n autolinkingModuleResolverInput = await createAutolinkingModuleResolverInput({\n platforms: expoConfigPlatforms,\n projectRoot,\n });\n }\n\n return withExtendedResolver(config, {\n autolinkingModuleResolverInput,\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\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","asWritable","input","withWebPolyfills","config","getMetroBundler","originalGetPolyfills","serializer","getPolyfills","bind","ctx","virtualEnvVarId","getMetroBundlerWithVirtualModules","setVirtualModule","virtualModuleId","platform","virtualModulesPolyfills","rnGetPolyfills","filter","x","includes","error","code","polyfills","resolve","normalizeSlashes","p","replace","srcExts","mjsExts","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","autolinkingModuleResolverInput","isTsconfigPathsEnabled","isExporting","isReactServerComponentsEnabled","Log","warn","aliases","web","_universalAliases","getUniversalAliases","resolveFrom","silent","projectRoot","push","projectRootOriginPath","path","join","preferredMainFields","tsConfigResolve","paths","baseUrl","resolveWithTsConfigPaths","hasBaseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","getStrictResolver","resolveRequest","context","doResolve","moduleName","resolver","getOptionalResolver","optionalResolve","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","idFactory","createModuleIdFactory","id","_asyncRequireModuleResolvedPath","getAsyncRequireModule","undefined","transformer","asyncRequireModulePath","type","filePath","getAssetRegistryModule","externals","match","customResolverOptions","exporting","isServerEnvironment","environment","process","clientboundary","endsWith","isExternal","metroConfigWithCustomResolver","withMetroResolvers","requestDevMockProdReact","dev","originModulePath","requestTsconfigPaths","requestNodeExternals","isServer","moduleId","isNodeExternal","result","contents","requestCustomExternals","external","realModule","realPath","opaqueId","JSON","stringify","projectRootContext","nodeModulesPaths","disableHierarchicalLookup","externModule","requestAlias","redirectedModuleName","matcher","alias","aliasedModule","_","parseInt","requestStableConfigModules","createAutolinkingModuleResolver","requestPostRewrites","normalizedPath","doReplace","from","to","options","doReplaceHelper","doReplaceStrict","throws","env","EXPO_UNSTABLE_WEB_MODAL","webModalModule","some","FailedToResolveNativeOnlyModuleError","relative","normalName","shimFile","shouldCreateVirtualShim","virtualId","bundler","hasVirtualModule","fs","readFileSync","emptyModule","hmrModule","EXPO_UNSTABLE_LOG_BOX","logBoxModule","logBoxParserModule","createFallbackModuleResolver","originModuleNames","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","sourceExts","unstable_enablePackageExports","unstable_conditionsByPlatform","isReactServerComponents","mainFields","unstable_conditionNames","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","withMetroSupervisingTransformWorker","resolutionError","Error","cause","output","exp","platformBundlers","isAutolinkingResolverEnabled","metroDefaults","moduleSystem","EXPO_PUBLIC_PROJECT_ROOT","isDirectoryIn","__dirname","watchFolders","expoConfigPlatforms","entries","platforms","map","Array","isArray","Set","concat","createAutolinkingModuleResolverInput","targetPath","rootPath","startsWith"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IA8IeA,mBAAmB;eAAnBA;;IA6tBAC,iBAAiB;eAAjBA;;IAxsBAC,oBAAoB;eAApBA;;IAwtBMC,2BAA2B;eAA3BA;;;;yBAl3Bc;;;;;;;gEAErB;;;;;;;gEACE;;;;;;;gEACO;;;;;;+CAMjB;4CACsC;sDACQ;2BACG;6BACe;qCACrB;iDACF;oCACoB;qDAChB;qBAChC;8BACS;qBACT;sBACa;6BACH;mCACwB;0CACb;8BACL;;;;;;AASpC,MAAMC,qBAAqB,CAAC,6FAA6F,CAAC;AAE1H,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,SAASC,WAAcC,KAAQ;IAC7B,OAAOA;AACT;AAEA,SAASC,iBACPC,MAAe,EACf,EACEC,eAAe,EAGhB;IAED,MAAMC,uBAAuBF,OAAOG,UAAU,CAACC,YAAY,GACvDJ,OAAOG,UAAU,CAACC,YAAY,CAACC,IAAI,CAACL,OAAOG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,iBAAiBC,QAAQ;QAAEC;IAAgB;IAEpD,IAAIkC;IACJ,IAAIoJ,8BAA8B;QAChCpJ,iCAAiC,MAAMmK,IAAAA,mEAAoC,EAAC;YAC1EN,WAAWF;YACX/I;QACF;IACF;IAEA,OAAOvD,qBAAqBQ,QAAQ;QAClCmC;QACAD;QACAG;QACAD;QACAE;QACArC;IACF;AACF;AAEA,SAAS0L,cAAcY,UAAkB,EAAEC,QAAgB;IACzD,OAAOD,WAAWE,UAAU,CAACD,aAAaD,WAAWpI,MAAM,IAAIqI,SAASrI,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 type { ExpoConfig, Platform } from '@expo/config';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ConfigT } from '@expo/metro/metro-config';\nimport type {\n Resolution,\n ResolutionContext,\n CustomResolutionContext,\n} from '@expo/metro/metro-resolver';\nimport { resolve as resolver } from '@expo/metro/metro-resolver';\nimport type { SourceFileResolution } from '@expo/metro/metro-resolver/types';\nimport fs from 'fs';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport {\n createAutolinkingModuleResolverInput,\n createAutolinkingModuleResolver,\n AutolinkingModuleResolverInput,\n} from './createExpoAutolinkingResolver';\nimport { createFallbackModuleResolver } from './createExpoFallbackResolver';\nimport { FailedToResolveNativeOnlyModuleError } from './errors/FailedToResolveNativeOnlyModuleError';\nimport { isNodeExternal, shouldCreateVirtualShim } from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { getMetroBundlerWithVirtualModules } from './metroVirtualModules';\nimport { withMetroErrorReportingResolver } from './withMetroErrorReportingResolver';\nimport { withMetroMutatedResolverContext, withMetroResolvers } from './withMetroResolvers';\nimport { withMetroSupervisingTransformWorker } from './withMetroSupervisingTransformWorker';\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\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\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 asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\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 // NOTE(@hassankhan): We need to wrap require in an arrow function rather than assigning\n // it directly because `workerd` loses its `this` context when `require` is dereferenced\n // and called later.\n return `global.$$require_external = typeof require !== \"undefined\" ? (m) => require(m) : () => 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 const virtualModulesPolyfills = [virtualModuleId, virtualEnvVarId];\n\n if (ctx.platform === 'web') {\n try {\n const rnGetPolyfills: () => string[] = require('react-native/rn-get-polyfills');\n return [\n ...virtualModulesPolyfills,\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 // NOTE(@kitten): This is technically the public API to get polyfills rather than resolving directly into\n // `@react-native/js-polyfills`. We should really just start vendoring these, but for now, this exclusion works\n ...rnGetPolyfills().filter((x: string) => !x.includes('/console')),\n ];\n } catch (error: any) {\n if ('code' in error && error.code === 'MODULE_NOT_FOUND') {\n // If react-native is not installed, because we're targeting web, we still continue\n // This should be rare, but we add it so we don't unnecessarily have a fixed peer dependency on react-native\n debug(\n 'Skipping react-native/rn-get-polyfills from getPolyfills. react-native is not installed.'\n );\n return virtualModulesPolyfills;\n } else {\n throw error;\n }\n }\n }\n\n // Generally uses `@expo/metro-config`'s `getPolyfills` function, unless overridden\n const polyfills = originalGetPolyfills(ctx);\n return [\n ...polyfills,\n ...virtualModulesPolyfills,\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 */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n tsconfig,\n autolinkingModuleResolverInput,\n isTsconfigPathsEnabled,\n isExporting,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n tsconfig: TsConfigPaths | null;\n autolinkingModuleResolverInput?: AutolinkingModuleResolverInput;\n isTsconfigPathsEnabled?: boolean;\n isExporting?: boolean;\n isReactServerComponentsEnabled?: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isReactServerComponentsEnabled) {\n Log.warn(`React Server Components (beta) is enabled.`);\n }\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 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 // used to resolve externals in `requestCustomExternals` from the project root\n const projectRootOriginPath = path.join(config.projectRoot, 'package.json');\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 // We're manually resolving the `asyncRequireModulePath` since it's a module request\n // However, in isolated installations it might not resolve from all paths, so we're resolving\n // it from the project root manually\n let _asyncRequireModuleResolvedPath: string | null | undefined;\n const getAsyncRequireModule = () => {\n if (_asyncRequireModuleResolvedPath === undefined) {\n _asyncRequireModuleResolvedPath =\n resolveFrom.silent(config.projectRoot, config.transformer.asyncRequireModulePath) ?? null;\n }\n return _asyncRequireModuleResolvedPath\n ? ({ type: 'sourceFile', filePath: _asyncRequireModuleResolvedPath } as const)\n : null;\n };\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 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 = getStrictResolver(context, platform)(moduleName);\n const realPath = realModule.type === 'sourceFile' ? realModule.filePath : moduleName;\n const opaqueId = idFactory(realPath, {\n platform: platform!,\n environment: context.customResolverOptions?.environment,\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 // TODO(@kitten): Temporary workaround. Our externals logic here isn't generic and only works\n // for development and not exports. We never intend to use it in exported production bundles,\n // however, this is still a dangerous implementation. To protect us from externalizing modules\n // that aren't available to the app, we force any resolution to happen via the project root\n const projectRootContext: ResolutionContext = {\n ...context,\n nodeModulesPaths: [],\n originModulePath: projectRootOriginPath,\n disableHierarchicalLookup: false,\n };\n const externModule = getStrictResolver(projectRootContext, platform)(moduleName);\n if (externModule.type !== 'sourceFile') {\n return null;\n }\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 external.replace satisfies never;\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 (assetRegistryPath) and async require module (asyncRequireModulePath)\n function requestStableConfigModules(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n if (moduleName === config.transformer.asyncRequireModulePath) {\n return getAsyncRequireModule();\n }\n\n // TODO(@kitten): Compare against `config.transformer.assetRegistryPath`\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 createAutolinkingModuleResolver(autolinkingModuleResolverInput, {\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 const normalizedPath = normalizeSlashes(result.filePath);\n\n const doReplace = (from: string, to: string | undefined, options?: { throws?: boolean }) =>\n doReplaceHelper(from, to, {\n normalizedPath,\n doResolve,\n ...options,\n });\n const doReplaceStrict = (from: string, to: string | undefined) =>\n doReplace(from, to, { throws: true });\n\n if (env.EXPO_UNSTABLE_WEB_MODAL) {\n const webModalModule = doReplace(\n 'expo-router/build/layouts/_web-modal.js',\n 'expo-router/build/layouts/ExperimentalModalStack.js'\n );\n if (webModalModule) {\n debug('Using `_unstable-web-modal` implementation.');\n return webModalModule;\n }\n }\n\n if (platform === 'web') {\n if (result.filePath.includes('node_modules')) {\n // Disallow importing confusing native modules on web\n if (\n [\n 'react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore',\n 'react-native/Libraries/Utilities/codegenNativeCommands',\n 'react-native/Libraries/Utilities/codegenNativeComponent',\n ].some((matcher) =>\n // Support absolute and modules with .js extensions.\n moduleName.includes(matcher)\n )\n ) {\n throw new FailedToResolveNativeOnlyModuleError(\n moduleName,\n path.relative(config.projectRoot, context.originModulePath)\n );\n }\n\n // Replace with static shims\n\n // Drop everything up until the `node_modules` folder.\n const normalName = normalizedPath.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 // Shim out React Native native runtime globals in server mode for native.\n if (isServer) {\n const emptyModule = doReplace('react-native/Libraries/Core/InitializeCore.js', undefined);\n if (emptyModule) {\n debug('Shimming out InitializeCore for React Native in native SSR bundle');\n return emptyModule;\n }\n }\n\n const hmrModule = doReplaceStrict(\n 'react-native/Libraries/Utilities/HMRClient.js',\n 'expo/src/async-require/hmr.ts'\n );\n if (hmrModule) return hmrModule;\n\n if (env.EXPO_UNSTABLE_LOG_BOX) {\n const logBoxModule = doReplace(\n 'react-native/Libraries/LogBox/LogBoxInspectorContainer.js',\n '@expo/log-box/swap-rn-logbox.js'\n );\n if (logBoxModule) return logBoxModule;\n\n const logBoxParserModule = doReplace(\n 'react-native/Libraries/LogBox/Data/parseLogBoxLog.js',\n '@expo/log-box/swap-rn-logbox-parser.js'\n );\n if (logBoxParserModule) return logBoxParserModule;\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 = asWritable({\n ...immutableContext,\n preferNativePlatform: platform !== 'web',\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(\n withMetroSupervisingTransformWorker(metroConfigWithCustomContext)\n );\n}\n\nfunction doReplaceHelper(\n from: string,\n to: string | undefined,\n {\n throws = false,\n normalizedPath,\n doResolve,\n }: {\n throws?: boolean;\n normalizedPath: string;\n doResolve: StrictResolver;\n }\n): SourceFileResolution | { type: 'empty' } | undefined {\n if (!normalizedPath.endsWith(from)) {\n return undefined;\n }\n\n if (to === undefined) {\n return {\n type: 'empty',\n };\n }\n\n try {\n const hmrModule = doResolve(to);\n if (hmrModule.type === 'sourceFile') {\n debug(`Using \\`${to}\\` implementation.`);\n return hmrModule;\n }\n } catch (resolutionError) {\n if (throws) {\n throw new Error(`Failed to replace ${from} with ${to}. Resolution of ${to} failed.`, {\n cause: resolutionError,\n });\n }\n\n debug(`Failed to resolve ${to} when swapping from ${from}: ${resolutionError}`);\n }\n return undefined;\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 isAutolinkingResolverEnabled,\n isExporting,\n\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n isAutolinkingResolverEnabled?: boolean;\n isExporting?: boolean;\n\n isReactServerComponentsEnabled: boolean;\n isNamedRequiresEnabled: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n // Change the default metro-runtime to a custom one that supports bundle splitting.\n // NOTE(@kitten): This is now always active and EXPO_USE_METRO_REQUIRE / isNamedRequiresEnabled is disregarded\n const metroDefaults: typeof import('@expo/metro/metro-config/defaults/defaults') = require('@expo/metro/metro-config/defaults/defaults');\n asWritable(metroDefaults).moduleSystem = require.resolve('@expo/cli/build/metro-require/require');\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 const watchFolders = (config.watchFolders as string[]) || [];\n asWritable(config).watchFolders = watchFolders;\n\n watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n 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 }\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 asWritable(config.resolver).platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config, { getMetroBundler });\n\n let autolinkingModuleResolverInput: AutolinkingModuleResolverInput | undefined;\n if (isAutolinkingResolverEnabled) {\n autolinkingModuleResolverInput = await createAutolinkingModuleResolverInput({\n platforms: expoConfigPlatforms,\n projectRoot,\n });\n }\n\n return withExtendedResolver(config, {\n autolinkingModuleResolverInput,\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\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","asWritable","input","withWebPolyfills","config","getMetroBundler","originalGetPolyfills","serializer","getPolyfills","bind","ctx","virtualEnvVarId","getMetroBundlerWithVirtualModules","setVirtualModule","virtualModuleId","platform","virtualModulesPolyfills","rnGetPolyfills","filter","x","includes","error","code","polyfills","resolve","normalizeSlashes","p","replace","srcExts","mjsExts","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","autolinkingModuleResolverInput","isTsconfigPathsEnabled","isExporting","isReactServerComponentsEnabled","Log","warn","aliases","web","_universalAliases","getUniversalAliases","resolveFrom","silent","projectRoot","push","projectRootOriginPath","path","join","preferredMainFields","tsConfigResolve","paths","baseUrl","resolveWithTsConfigPaths","hasBaseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","getStrictResolver","resolveRequest","context","doResolve","moduleName","resolver","getOptionalResolver","optionalResolve","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","idFactory","createModuleIdFactory","id","_asyncRequireModuleResolvedPath","getAsyncRequireModule","undefined","transformer","asyncRequireModulePath","type","filePath","getAssetRegistryModule","externals","match","customResolverOptions","exporting","isServerEnvironment","environment","process","clientboundary","endsWith","isExternal","metroConfigWithCustomResolver","withMetroResolvers","requestDevMockProdReact","dev","originModulePath","requestTsconfigPaths","requestNodeExternals","isServer","moduleId","isNodeExternal","result","contents","requestCustomExternals","external","realModule","realPath","opaqueId","JSON","stringify","projectRootContext","nodeModulesPaths","disableHierarchicalLookup","externModule","requestAlias","redirectedModuleName","matcher","alias","aliasedModule","_","parseInt","requestStableConfigModules","createAutolinkingModuleResolver","requestPostRewrites","normalizedPath","doReplace","from","to","options","doReplaceHelper","doReplaceStrict","throws","env","EXPO_UNSTABLE_WEB_MODAL","webModalModule","some","FailedToResolveNativeOnlyModuleError","relative","normalName","shimFile","shouldCreateVirtualShim","virtualId","bundler","hasVirtualModule","fs","readFileSync","emptyModule","hmrModule","EXPO_UNSTABLE_LOG_BOX","logBoxModule","logBoxParserModule","createFallbackModuleResolver","originModuleNames","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","sourceExts","unstable_enablePackageExports","unstable_conditionsByPlatform","isReactServerComponents","mainFields","unstable_conditionNames","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","withMetroSupervisingTransformWorker","resolutionError","Error","cause","output","exp","platformBundlers","isAutolinkingResolverEnabled","metroDefaults","moduleSystem","EXPO_PUBLIC_PROJECT_ROOT","isDirectoryIn","__dirname","watchFolders","expoConfigPlatforms","entries","platforms","map","Array","isArray","Set","concat","createAutolinkingModuleResolverInput","targetPath","rootPath","startsWith"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IA8IeA,mBAAmB;eAAnBA;;IA6tBAC,iBAAiB;eAAjBA;;IAxsBAC,oBAAoB;eAApBA;;IAwtBMC,2BAA2B;eAA3BA;;;;yBAl3Bc;;;;;;;gEAErB;;;;;;;gEACE;;;;;;;gEACO;;;;;;+CAMjB;4CACsC;sDACQ;2BACG;6BACe;qCACrB;iDACF;oCACoB;qDAChB;qBAChC;8BACS;qBACT;sBACa;6BACH;mCACwB;0CACb;8BACL;;;;;;AASpC,MAAMC,qBAAqB,CAAC,6FAA6F,CAAC;AAE1H,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,SAASC,WAAcC,KAAQ;IAC7B,OAAOA;AACT;AAEA,SAASC,iBACPC,MAAe,EACf,EACEC,eAAe,EAGhB;IAED,MAAMC,uBAAuBF,OAAOG,UAAU,CAACC,YAAY,GACvDJ,OAAOG,UAAU,CAACC,YAAY,CAACC,IAAI,CAACL,OAAOG,UAAU,IACrD,IAAM,EAAE;IAEZ,MAAMC,eAAe,CAACE;QACpB,MAAMC,kBAAkB,CAAC,gCAAgC,CAAC;QAE1DC,IAAAA,sDAAiC,EAACP,mBAAmBQ,gBAAgB,CACnEF,iBACA,AAAC,CAAA;YACC,OAAO,CAAC,EAAE,CAAC;QACb,CAAA;QAGF,MAAMG,kBAAkB,CAAC,2BAA2B,CAAC;QAErDF,IAAAA,sDAAiC,EAACP,mBAAm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/utils/delay.js
CHANGED
|
@@ -42,10 +42,16 @@ async function waitForActionAsync({ action, interval = 100, maxWaitTime = 20000
|
|
|
42
42
|
}
|
|
43
43
|
function resolveWithTimeout(action, { timeout, errorMessage }) {
|
|
44
44
|
return new Promise((resolve, reject)=>{
|
|
45
|
-
setTimeout(()=>{
|
|
45
|
+
const timeoutId = setTimeout(()=>{
|
|
46
46
|
reject(new _errors.CommandError('TIMEOUT', errorMessage));
|
|
47
47
|
}, timeout);
|
|
48
|
-
action().then(
|
|
48
|
+
action().then((result)=>{
|
|
49
|
+
clearTimeout(timeoutId);
|
|
50
|
+
resolve(result);
|
|
51
|
+
}, (error)=>{
|
|
52
|
+
clearTimeout(timeoutId);
|
|
53
|
+
reject(error);
|
|
54
|
+
});
|
|
49
55
|
});
|
|
50
56
|
}
|
|
51
57
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/delay.ts"],"sourcesContent":["import { CommandError } from './errors';\n\n/** Await for a given duration of milliseconds. */\nexport function delayAsync(timeout: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, timeout));\n}\n\n/** Wait for a given action to return a truthy value. */\nexport async function waitForActionAsync<T>({\n action,\n interval = 100,\n maxWaitTime = 20000,\n}: {\n action: () => T | Promise<T>;\n interval?: number;\n maxWaitTime?: number;\n}): Promise<T> {\n let complete: T;\n const start = Date.now();\n do {\n const actionStartTime = Date.now();\n complete = await action();\n\n const actionTimeElapsed = Date.now() - actionStartTime;\n const remainingDelayInterval = interval - actionTimeElapsed;\n if (remainingDelayInterval > 0) {\n await delayAsync(remainingDelayInterval);\n }\n if (Date.now() - start > maxWaitTime) {\n break;\n }\n } while (!complete);\n\n return complete;\n}\n\n/** Resolves a given function or rejects if the provided timeout is passed. */\nexport function resolveWithTimeout<T>(\n action: () => Promise<T>,\n {\n timeout,\n errorMessage,\n }: {\n /** Duration in milliseconds to wait before asserting a timeout. */\n timeout: number;\n /** Optional error message to use in the assertion. */\n errorMessage?: string;\n }\n): Promise<T> {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n reject(new CommandError('TIMEOUT', errorMessage));\n }, timeout);\n action().then(resolve
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/delay.ts"],"sourcesContent":["import { CommandError } from './errors';\n\n/** Await for a given duration of milliseconds. */\nexport function delayAsync(timeout: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, timeout));\n}\n\n/** Wait for a given action to return a truthy value. */\nexport async function waitForActionAsync<T>({\n action,\n interval = 100,\n maxWaitTime = 20000,\n}: {\n action: () => T | Promise<T>;\n interval?: number;\n maxWaitTime?: number;\n}): Promise<T> {\n let complete: T;\n const start = Date.now();\n do {\n const actionStartTime = Date.now();\n complete = await action();\n\n const actionTimeElapsed = Date.now() - actionStartTime;\n const remainingDelayInterval = interval - actionTimeElapsed;\n if (remainingDelayInterval > 0) {\n await delayAsync(remainingDelayInterval);\n }\n if (Date.now() - start > maxWaitTime) {\n break;\n }\n } while (!complete);\n\n return complete;\n}\n\n/** Resolves a given function or rejects if the provided timeout is passed. */\nexport function resolveWithTimeout<T>(\n action: () => Promise<T>,\n {\n timeout,\n errorMessage,\n }: {\n /** Duration in milliseconds to wait before asserting a timeout. */\n timeout: number;\n /** Optional error message to use in the assertion. */\n errorMessage?: string;\n }\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new CommandError('TIMEOUT', errorMessage));\n }, timeout);\n action().then(\n (result) => {\n clearTimeout(timeoutId);\n resolve(result);\n },\n (error) => {\n clearTimeout(timeoutId);\n reject(error);\n }\n );\n });\n}\n"],"names":["delayAsync","resolveWithTimeout","waitForActionAsync","timeout","Promise","resolve","setTimeout","action","interval","maxWaitTime","complete","start","Date","now","actionStartTime","actionTimeElapsed","remainingDelayInterval","errorMessage","reject","timeoutId","CommandError","then","result","clearTimeout","error"],"mappings":";;;;;;;;;;;IAGgBA,UAAU;eAAVA;;IAkCAC,kBAAkB;eAAlBA;;IA7BMC,kBAAkB;eAAlBA;;;wBARO;AAGtB,SAASF,WAAWG,OAAe;IACxC,OAAO,IAAIC,QAAQ,CAACC,UAAYC,WAAWD,SAASF;AACtD;AAGO,eAAeD,mBAAsB,EAC1CK,MAAM,EACNC,WAAW,GAAG,EACdC,cAAc,KAAK,EAKpB;IACC,IAAIC;IACJ,MAAMC,QAAQC,KAAKC,GAAG;IACtB,GAAG;QACD,MAAMC,kBAAkBF,KAAKC,GAAG;QAChCH,WAAW,MAAMH;QAEjB,MAAMQ,oBAAoBH,KAAKC,GAAG,KAAKC;QACvC,MAAME,yBAAyBR,WAAWO;QAC1C,IAAIC,yBAAyB,GAAG;YAC9B,MAAMhB,WAAWgB;QACnB;QACA,IAAIJ,KAAKC,GAAG,KAAKF,QAAQF,aAAa;YACpC;QACF;IACF,QAAS,CAACC,UAAU;IAEpB,OAAOA;AACT;AAGO,SAAST,mBACdM,MAAwB,EACxB,EACEJ,OAAO,EACPc,YAAY,EAMb;IAED,OAAO,IAAIb,QAAQ,CAACC,SAASa;QAC3B,MAAMC,YAAYb,WAAW;YAC3BY,OAAO,IAAIE,oBAAY,CAAC,WAAWH;QACrC,GAAGd;QACHI,SAASc,IAAI,CACX,CAACC;YACCC,aAAaJ;YACbd,QAAQiB;QACV,GACA,CAACE;YACCD,aAAaJ;YACbD,OAAOM;QACT;IAEJ;AACF"}
|
package/build/src/utils/exit.js
CHANGED
|
@@ -116,9 +116,16 @@ function ensureProcessExitsAfterDelay(waitUntilExitMs = 10000, startedAtMs = Dat
|
|
|
116
116
|
}
|
|
117
117
|
return true;
|
|
118
118
|
});
|
|
119
|
-
|
|
119
|
+
// Check if only Timeouts remain (no blocking resources like ProcessWrap/PipeWrap)
|
|
120
|
+
const hasBlockingResources = unexpectedActiveResources.some((resource)=>resource !== 'Timeout' && resource !== 'CloseReq');
|
|
121
|
+
const canExitProcess = !unexpectedActiveResources.length || !hasBlockingResources;
|
|
120
122
|
if (canExitProcess) {
|
|
121
|
-
|
|
123
|
+
if (unexpectedActiveResources.length && !hasBlockingResources) {
|
|
124
|
+
debug('only non-blocking resources remain (Timeout/CloseReq), process can safely exit');
|
|
125
|
+
} else {
|
|
126
|
+
debug('no active resources detected, process can safely exit');
|
|
127
|
+
}
|
|
128
|
+
return;
|
|
122
129
|
} else {
|
|
123
130
|
debug(`process is trying to exit, but is stuck on unexpected active resources:`, unexpectedActiveResources);
|
|
124
131
|
}
|
|
@@ -134,7 +141,11 @@ function ensureProcessExitsAfterDelay(waitUntilExitMs = 10000, startedAtMs = Dat
|
|
|
134
141
|
clearTimeout(timeoutId);
|
|
135
142
|
// Check if the process can exit
|
|
136
143
|
ensureProcessExitsAfterDelay(waitUntilExitMs, startedAtMs);
|
|
144
|
+
// setTimeout is using the global definitions from React Native which is missing the unref method in Node.js.
|
|
137
145
|
}, 100);
|
|
146
|
+
// Unref the timeout so it doesn't prevent the process from exiting naturally
|
|
147
|
+
// when this timeout is the only remaining active resource
|
|
148
|
+
timeoutId.unref();
|
|
138
149
|
}
|
|
139
150
|
/**
|
|
140
151
|
* Try to warn the user about unexpected active processes running in the background.
|
|
@@ -148,17 +159,47 @@ function ensureProcessExitsAfterDelay(waitUntilExitMs = 10000, startedAtMs = Dat
|
|
|
148
159
|
* - node /Users/cedric/../node_modules/nativewind/dist/metro/tailwind/v3/child.js
|
|
149
160
|
* ```
|
|
150
161
|
*/ function tryWarnActiveProcesses() {
|
|
151
|
-
|
|
162
|
+
const activeProcesses = [];
|
|
163
|
+
const handleSummary = {};
|
|
164
|
+
const timeoutDetails = [];
|
|
152
165
|
try {
|
|
153
|
-
const
|
|
154
|
-
|
|
155
|
-
|
|
166
|
+
const handles = _nodeprocess().default._getActiveHandles();
|
|
167
|
+
// Categorize handles by their constructor name
|
|
168
|
+
for (const handle of handles){
|
|
169
|
+
var _handle_constructor;
|
|
170
|
+
const name = (handle == null ? void 0 : (_handle_constructor = handle.constructor) == null ? void 0 : _handle_constructor.name) ?? 'Unknown';
|
|
171
|
+
handleSummary[name] = (handleSummary[name] ?? 0) + 1;
|
|
172
|
+
// Collect ChildProcess command info
|
|
173
|
+
if (handle instanceof _nodechild_process().ChildProcess) {
|
|
174
|
+
activeProcesses.push(handle.spawnargs.join(' '));
|
|
175
|
+
}
|
|
176
|
+
// Try to get more info about Timeout handles
|
|
177
|
+
if (name === 'Timeout') {
|
|
178
|
+
try {
|
|
179
|
+
// Attempt to get callback name or source info
|
|
180
|
+
const callback = handle._onTimeout ?? handle._repeat;
|
|
181
|
+
const callbackName = (callback == null ? void 0 : callback.name) || '<anonymous>';
|
|
182
|
+
const delay = handle._idleTimeout ?? 'unknown';
|
|
183
|
+
timeoutDetails.push(`Timeout(${delay}ms, fn: ${callbackName})`);
|
|
184
|
+
} catch {
|
|
185
|
+
timeoutDetails.push('Timeout(details unavailable)');
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
// Log detailed handle info when debug is enabled
|
|
190
|
+
debug('active handles by type:', handleSummary);
|
|
191
|
+
if (timeoutDetails.length) {
|
|
192
|
+
debug('timeout details:', timeoutDetails);
|
|
156
193
|
}
|
|
157
194
|
} catch (error) {
|
|
158
195
|
debug('failed to get active process information:', error);
|
|
159
196
|
}
|
|
160
197
|
if (!activeProcesses.length) {
|
|
161
198
|
(0, _log.warn)('Something prevented Expo from exiting, forcefully exiting now.');
|
|
199
|
+
// Log handle summary when no specific processes are identified
|
|
200
|
+
if (Object.keys(handleSummary).length > 0) {
|
|
201
|
+
debug('handle summary (use DEBUG=expo:utils:exit for details):', handleSummary);
|
|
202
|
+
}
|
|
162
203
|
} else {
|
|
163
204
|
const singularOrPlural = activeProcesses.length === 1 ? '1 process' : `${activeProcesses.length} processes`;
|
|
164
205
|
(0, _log.warn)(`Detected ${singularOrPlural} preventing Expo from exiting, forcefully exiting now.`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/exit.ts"],"sourcesContent":["import { ChildProcess } from 'node:child_process';\nimport process from 'node:process';\n\nimport { guardAsync } from './fn';\nimport { warn } from '../log';\n\nconst debug = require('debug')('expo:utils:exit') as typeof console.log;\n\n// NOTE: This is an internal method, not designed to be exposed. It's also our only way to get this info\ndeclare global {\n namespace NodeJS {\n interface Process {\n _getActiveHandles(): readonly any[];\n }\n }\n}\n\ntype AsyncExitHook = (signal: NodeJS.Signals) => void | Promise<void>;\n\nconst PRE_EXIT_SIGNALS: NodeJS.Signals[] = ['SIGHUP', 'SIGINT', 'SIGTERM', 'SIGBREAK'];\n\n// We create a queue since Node.js throws an error if we try to append too many listeners:\n// (node:4405) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 SIGINT listeners added to [process]. Use emitter.setMaxListeners() to increase limit\nconst queue: AsyncExitHook[] = [];\n\nlet unsubscribe: (() => void) | null = null;\n\n/** Add functions that run before the process exits. Returns a function for removing the listeners. */\nexport function installExitHooks(asyncExitHook: AsyncExitHook): () => void {\n // We need to instantiate the master listener the first time the queue is used.\n if (!queue.length) {\n // Track the master listener so we can remove it later.\n unsubscribe = attachMasterListener();\n }\n\n queue.push(asyncExitHook);\n\n return () => {\n const index = queue.indexOf(asyncExitHook);\n if (index >= 0) {\n queue.splice(index, 1);\n }\n // Clean up the master listener if we don't need it anymore.\n if (!queue.length) {\n unsubscribe?.();\n }\n };\n}\n\n// Create a function that runs before the process exits and guards against running multiple times.\nfunction createExitHook(signal: NodeJS.Signals) {\n return guardAsync(async () => {\n debug(`pre-exit (signal: ${signal}, queue length: ${queue.length})`);\n\n for (const [index, hookAsync] of Object.entries(queue)) {\n try {\n await hookAsync(signal);\n } catch (error: any) {\n debug(`Error in exit hook: %O (queue: ${index})`, error);\n }\n }\n\n debug(`post-exit (code: ${process.exitCode ?? 0})`);\n\n process.exit();\n });\n}\n\nfunction attachMasterListener() {\n const hooks: [NodeJS.Signals, () => any][] = [];\n for (const signal of PRE_EXIT_SIGNALS) {\n const hook = createExitHook(signal);\n hooks.push([signal, hook]);\n process.on(signal, hook);\n }\n return () => {\n for (const [signal, hook] of hooks) {\n process.removeListener(signal, hook);\n }\n };\n}\n\n/**\n * Monitor if the current process is exiting before the delay is reached.\n * If there are active resources, the process will be forced to exit after the delay is reached.\n *\n * @see https://nodejs.org/docs/latest-v18.x/api/process.html#processgetactiveresourcesinfo\n */\nexport function ensureProcessExitsAfterDelay(waitUntilExitMs = 10000, startedAtMs = Date.now()) {\n // Create a list of the expected active resources before exiting.\n // Note, the order is undeterministic\n const expectedResources = [\n process.stdout.isTTY ? 'TTYWrap' : 'PipeWrap',\n process.stderr.isTTY ? 'TTYWrap' : 'PipeWrap',\n process.stdin.isTTY ? 'TTYWrap' : 'PipeWrap',\n ];\n // Check active resources, besides the TTYWrap/PipeWrap (process.stdin, process.stdout, process.stderr)\n const activeResources = process.getActiveResourcesInfo() as string[];\n // Filter the active resource list by subtracting the expected resources, in undeterministic order\n const unexpectedActiveResources = activeResources.filter((activeResource) => {\n const index = expectedResources.indexOf(activeResource);\n if (index >= 0) {\n expectedResources.splice(index, 1);\n return false;\n }\n\n return true;\n });\n\n const canExitProcess = !unexpectedActiveResources.length;\n if (canExitProcess) {\n return debug('no active resources detected, process can safely exit');\n } else {\n debug(\n `process is trying to exit, but is stuck on unexpected active resources:`,\n unexpectedActiveResources\n );\n }\n\n // Check if the process needs to be force-closed\n const elapsedTime = Date.now() - startedAtMs;\n if (elapsedTime > waitUntilExitMs) {\n debug('active handles detected past the exit delay, forcefully exiting:', activeResources);\n tryWarnActiveProcesses();\n return process.exit(0);\n }\n\n const timeoutId = setTimeout(() => {\n // Ensure the timeout is cleared before checking the active resources\n clearTimeout(timeoutId);\n // Check if the process can exit\n ensureProcessExitsAfterDelay(waitUntilExitMs, startedAtMs);\n }, 100);\n}\n\n/**\n * Try to warn the user about unexpected active processes running in the background.\n * This uses the internal `process._getActiveHandles` method, within a try-catch block.\n * If active child processes are detected, the commands of these processes are logged.\n *\n * @example ```bash\n * Done writing bundle output\n * Detected 2 processes preventing Expo from exiting, forcefully exiting now.\n * - node /Users/cedric/../node_modules/nativewind/dist/metro/tailwind/v3/child.js\n * - node /Users/cedric/../node_modules/nativewind/dist/metro/tailwind/v3/child.js\n * ```\n */\nfunction tryWarnActiveProcesses() {\n let activeProcesses: string[] = [];\n\n try {\n const children: ChildProcess[] = process\n ._getActiveHandles()\n .filter((handle: any) => handle instanceof ChildProcess);\n\n if (children.length) {\n activeProcesses = children.map((child) => child.spawnargs.join(' '));\n }\n } catch (error) {\n debug('failed to get active process information:', error);\n }\n\n if (!activeProcesses.length) {\n warn('Something prevented Expo from exiting, forcefully exiting now.');\n } else {\n const singularOrPlural =\n activeProcesses.length === 1 ? '1 process' : `${activeProcesses.length} processes`;\n\n warn(`Detected ${singularOrPlural} preventing Expo from exiting, forcefully exiting now.`);\n warn(' - ' + activeProcesses.join('\\n - '));\n }\n}\n"],"names":["ensureProcessExitsAfterDelay","installExitHooks","debug","require","PRE_EXIT_SIGNALS","queue","unsubscribe","asyncExitHook","length","attachMasterListener","push","index","indexOf","splice","createExitHook","signal","guardAsync","hookAsync","Object","entries","error","process","exitCode","exit","hooks","hook","on","removeListener","waitUntilExitMs","startedAtMs","Date","now","expectedResources","stdout","isTTY","stderr","stdin","activeResources","getActiveResourcesInfo","unexpectedActiveResources","filter","activeResource","canExitProcess","elapsedTime","tryWarnActiveProcesses","timeoutId","setTimeout","clearTimeout","activeProcesses","children","_getActiveHandles","handle","ChildProcess","map","child","spawnargs","join","warn","singularOrPlural"],"mappings":";;;;;;;;;;;IAwFgBA,4BAA4B;eAA5BA;;IA5DAC,gBAAgB;eAAhBA;;;;yBA5Ba;;;;;;;gEACT;;;;;;oBAEO;qBACN;;;;;;AAErB,MAAMC,QAAQC,QAAQ,SAAS;AAa/B,MAAMC,mBAAqC;IAAC;IAAU;IAAU;IAAW;CAAW;AAEtF,0FAA0F;AAC1F,+KAA+K;AAC/K,MAAMC,QAAyB,EAAE;AAEjC,IAAIC,cAAmC;AAGhC,SAASL,iBAAiBM,aAA4B;IAC3D,+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AC3BiD,IAAAA,SAAI,EAAC;IACP,OAAO;QACL,MAAMC,mBACJV,gBAAgBxC,MAAM,KAAK,IAAI,cAAc,GAAGwC,gBAAgBxC,MAAM,CAAC,UAAU,CAAC;QAEpFiD,IAAAA,SAAI,EAAC,CAAC,SAAS,EAAEC,iBAAiB,sDAAsD,CAAC;QACzFD,IAAAA,SAAI,EAAC,SAAST,gBAAgBQ,IAAI,CAAC;IACrC;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/exit.ts"],"sourcesContent":["import { ChildProcess } from 'node:child_process';\nimport process from 'node:process';\n\nimport { guardAsync } from './fn';\nimport { warn } from '../log';\n\nconst debug = require('debug')('expo:utils:exit') as typeof console.log;\n\n// NOTE: This is an internal method, not designed to be exposed. It's also our only way to get this info\ndeclare global {\n namespace NodeJS {\n interface Process {\n _getActiveHandles(): readonly any[];\n }\n }\n}\n\ntype AsyncExitHook = (signal: NodeJS.Signals) => void | Promise<void>;\n\nconst PRE_EXIT_SIGNALS: NodeJS.Signals[] = ['SIGHUP', 'SIGINT', 'SIGTERM', 'SIGBREAK'];\n\n// We create a queue since Node.js throws an error if we try to append too many listeners:\n// (node:4405) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 SIGINT listeners added to [process]. Use emitter.setMaxListeners() to increase limit\nconst queue: AsyncExitHook[] = [];\n\nlet unsubscribe: (() => void) | null = null;\n\n/** Add functions that run before the process exits. Returns a function for removing the listeners. */\nexport function installExitHooks(asyncExitHook: AsyncExitHook): () => void {\n // We need to instantiate the master listener the first time the queue is used.\n if (!queue.length) {\n // Track the master listener so we can remove it later.\n unsubscribe = attachMasterListener();\n }\n\n queue.push(asyncExitHook);\n\n return () => {\n const index = queue.indexOf(asyncExitHook);\n if (index >= 0) {\n queue.splice(index, 1);\n }\n // Clean up the master listener if we don't need it anymore.\n if (!queue.length) {\n unsubscribe?.();\n }\n };\n}\n\n// Create a function that runs before the process exits and guards against running multiple times.\nfunction createExitHook(signal: NodeJS.Signals) {\n return guardAsync(async () => {\n debug(`pre-exit (signal: ${signal}, queue length: ${queue.length})`);\n\n for (const [index, hookAsync] of Object.entries(queue)) {\n try {\n await hookAsync(signal);\n } catch (error: any) {\n debug(`Error in exit hook: %O (queue: ${index})`, error);\n }\n }\n\n debug(`post-exit (code: ${process.exitCode ?? 0})`);\n\n process.exit();\n });\n}\n\nfunction attachMasterListener() {\n const hooks: [NodeJS.Signals, () => any][] = [];\n for (const signal of PRE_EXIT_SIGNALS) {\n const hook = createExitHook(signal);\n hooks.push([signal, hook]);\n process.on(signal, hook);\n }\n return () => {\n for (const [signal, hook] of hooks) {\n process.removeListener(signal, hook);\n }\n };\n}\n\n/**\n * Monitor if the current process is exiting before the delay is reached.\n * If there are active resources, the process will be forced to exit after the delay is reached.\n *\n * @see https://nodejs.org/docs/latest-v18.x/api/process.html#processgetactiveresourcesinfo\n */\nexport function ensureProcessExitsAfterDelay(waitUntilExitMs = 10000, startedAtMs = Date.now()) {\n // Create a list of the expected active resources before exiting.\n // Note, the order is undeterministic\n const expectedResources = [\n process.stdout.isTTY ? 'TTYWrap' : 'PipeWrap',\n process.stderr.isTTY ? 'TTYWrap' : 'PipeWrap',\n process.stdin.isTTY ? 'TTYWrap' : 'PipeWrap',\n ];\n // Check active resources, besides the TTYWrap/PipeWrap (process.stdin, process.stdout, process.stderr)\n const activeResources = process.getActiveResourcesInfo() as string[];\n // Filter the active resource list by subtracting the expected resources, in undeterministic order\n const unexpectedActiveResources = activeResources.filter((activeResource) => {\n const index = expectedResources.indexOf(activeResource);\n if (index >= 0) {\n expectedResources.splice(index, 1);\n return false;\n }\n\n return true;\n });\n\n // Check if only Timeouts remain (no blocking resources like ProcessWrap/PipeWrap)\n const hasBlockingResources = unexpectedActiveResources.some(\n (resource) => resource !== 'Timeout' && resource !== 'CloseReq'\n );\n\n const canExitProcess = !unexpectedActiveResources.length || !hasBlockingResources;\n if (canExitProcess) {\n if (unexpectedActiveResources.length && !hasBlockingResources) {\n debug('only non-blocking resources remain (Timeout/CloseReq), process can safely exit');\n } else {\n debug('no active resources detected, process can safely exit');\n }\n return;\n } else {\n debug(\n `process is trying to exit, but is stuck on unexpected active resources:`,\n unexpectedActiveResources\n );\n }\n\n // Check if the process needs to be force-closed\n const elapsedTime = Date.now() - startedAtMs;\n if (elapsedTime > waitUntilExitMs) {\n debug('active handles detected past the exit delay, forcefully exiting:', activeResources);\n tryWarnActiveProcesses();\n return process.exit(0);\n }\n\n const timeoutId = setTimeout(() => {\n // Ensure the timeout is cleared before checking the active resources\n clearTimeout(timeoutId);\n // Check if the process can exit\n ensureProcessExitsAfterDelay(waitUntilExitMs, startedAtMs);\n\n // setTimeout is using the global definitions from React Native which is missing the unref method in Node.js.\n }, 100) as unknown as NodeJS.Timeout;\n\n // Unref the timeout so it doesn't prevent the process from exiting naturally\n // when this timeout is the only remaining active resource\n timeoutId.unref();\n}\n\n/**\n * Try to warn the user about unexpected active processes running in the background.\n * This uses the internal `process._getActiveHandles` method, within a try-catch block.\n * If active child processes are detected, the commands of these processes are logged.\n *\n * @example ```bash\n * Done writing bundle output\n * Detected 2 processes preventing Expo from exiting, forcefully exiting now.\n * - node /Users/cedric/../node_modules/nativewind/dist/metro/tailwind/v3/child.js\n * - node /Users/cedric/../node_modules/nativewind/dist/metro/tailwind/v3/child.js\n * ```\n */\nfunction tryWarnActiveProcesses() {\n const activeProcesses: string[] = [];\n const handleSummary: Record<string, number> = {};\n const timeoutDetails: string[] = [];\n\n try {\n const handles = process._getActiveHandles();\n\n // Categorize handles by their constructor name\n for (const handle of handles) {\n const name = handle?.constructor?.name ?? 'Unknown';\n handleSummary[name] = (handleSummary[name] ?? 0) + 1;\n\n // Collect ChildProcess command info\n if (handle instanceof ChildProcess) {\n activeProcesses.push(handle.spawnargs.join(' '));\n }\n\n // Try to get more info about Timeout handles\n if (name === 'Timeout') {\n try {\n // Attempt to get callback name or source info\n const callback = handle._onTimeout ?? handle._repeat;\n const callbackName = callback?.name || '<anonymous>';\n const delay = handle._idleTimeout ?? 'unknown';\n timeoutDetails.push(`Timeout(${delay}ms, fn: ${callbackName})`);\n } catch {\n timeoutDetails.push('Timeout(details unavailable)');\n }\n }\n }\n\n // Log detailed handle info when debug is enabled\n debug('active handles by type:', handleSummary);\n if (timeoutDetails.length) {\n debug('timeout details:', timeoutDetails);\n }\n } catch (error) {\n debug('failed to get active process information:', error);\n }\n\n if (!activeProcesses.length) {\n warn('Something prevented Expo from exiting, forcefully exiting now.');\n // Log handle summary when no specific processes are identified\n if (Object.keys(handleSummary).length > 0) {\n debug('handle summary (use DEBUG=expo:utils:exit for details):', handleSummary);\n }\n } else {\n const singularOrPlural =\n activeProcesses.length === 1 ? '1 process' : `${activeProcesses.length} processes`;\n\n warn(`Detected ${singularOrPlural} preventing Expo from exiting, forcefully exiting now.`);\n warn(' - ' + activeProcesses.join('\\n - '));\n }\n}\n"],"names":["ensureProcessExitsAfterDelay","installExitHooks","debug","require","PRE_EXIT_SIGNALS","queue","unsubscribe","asyncExitHook","length","attachMasterListener","push","index","indexOf","splice","createExitHook","signal","guardAsync","hookAsync","Object","entries","error","process","exitCode","exit","hooks","hook","on","removeListener","waitUntilExitMs","startedAtMs","Date","now","expectedResources","stdout","isTTY","stderr","stdin","activeResources","getActiveResourcesInfo","unexpectedActiveResources","filter","activeResource","hasBlockingResources","some","resource","canExitProcess","elapsedTime","tryWarnActiveProcesses","timeoutId","setTimeout","clearTimeout","unref","activeProcesses","handleSummary","timeoutDetails","handles","_getActiveHandles","handle","name","constructor","ChildProcess","spawnargs","join","callback","_onTimeout","_repeat","callbackName","delay","_idleTimeout","warn","keys","singularOrPlural"],"mappings":";;;;;;;;;;;IAwFgBA,4BAA4B;eAA5BA;;IA5DAC,gBAAgB;eAAhBA;;;;yBA5Ba;;;;;;;gEACT;;;;;;oBAEO;qBACN;;;;;;AAErB,MAAMC,QAAQC,QAAQ,SAAS;AAa/B,MAAMC,mBAAqC;IAAC;IAAU;IAAU;IAAW;CAAW;AAEtF,0FAA0F;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B,mBACJnB,gBAAgB5C,MAAM,KAAK,IAAI,cAAc,GAAG4C,gBAAgB5C,MAAM,CAAC,UAAU,CAAC;QAEpF6D,IAAAA,SAAI,EAAC,CAAC,SAAS,EAAEE,iBAAiB,sDAAsD,CAAC;QACzFF,IAAAA,SAAI,EAAC,SAASjB,gBAAgBU,IAAI,CAAC;IACrC;AACF"}
|
|
@@ -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/${"55.0.0-canary-
|
|
36
|
+
'user-agent': `expo-cli/${"55.0.0-canary-20251230-fc48ddc"}`,
|
|
37
37
|
authorization: 'Basic ' + _nodebuffer().Buffer.from(`${target}:`).toString('base64')
|
|
38
38
|
};
|
|
39
39
|
}
|