@expo/cli 55.0.0-canary-20251127-587bc53 → 55.0.0-canary-20251205-756eb7a

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.
Files changed (62) hide show
  1. package/add-module.js +4 -1
  2. package/build/bin/cli +1 -1
  3. package/build/src/export/embed/exportEmbedAsync.js +17 -13
  4. package/build/src/export/embed/exportEmbedAsync.js.map +1 -1
  5. package/build/src/export/exportApp.js +0 -1
  6. package/build/src/export/exportApp.js.map +1 -1
  7. package/build/src/prebuild/resolveLocalTemplate.js +34 -2
  8. package/build/src/prebuild/resolveLocalTemplate.js.map +1 -1
  9. package/build/src/run/ios/options/promptDevice.js.map +1 -1
  10. package/build/src/run/ios/options/resolveDevice.js +1 -3
  11. package/build/src/run/ios/options/resolveDevice.js.map +1 -1
  12. package/build/src/start/server/MCP.js +13 -1
  13. package/build/src/start/server/MCP.js.map +1 -1
  14. package/build/src/start/server/getStaticRenderFunctions.js +0 -2
  15. package/build/src/start/server/getStaticRenderFunctions.js.map +1 -1
  16. package/build/src/start/server/metro/MetroBundlerDevServer.js +10 -15
  17. package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
  18. package/build/src/start/server/metro/createServerComponentsMiddleware.js.map +1 -1
  19. package/build/src/start/server/metro/createServerRouteMiddleware.js.map +1 -1
  20. package/build/src/start/server/metro/debugging/MessageHandler.js +0 -2
  21. package/build/src/start/server/metro/debugging/MessageHandler.js.map +1 -1
  22. package/build/src/start/server/metro/debugging/pageIsSupported.js +0 -1
  23. package/build/src/start/server/metro/debugging/pageIsSupported.js.map +1 -1
  24. package/build/src/start/server/metro/externals.js +1 -2
  25. package/build/src/start/server/metro/externals.js.map +1 -1
  26. package/build/src/start/server/metro/fetchRouterManifest.js +2 -3
  27. package/build/src/start/server/metro/fetchRouterManifest.js.map +1 -1
  28. package/build/src/start/server/metro/instantiateMetro.js +9 -11
  29. package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
  30. package/build/src/start/server/metro/withMetroErrorReportingResolver.js +0 -1
  31. package/build/src/start/server/metro/withMetroErrorReportingResolver.js.map +1 -1
  32. package/build/src/start/server/metro/withMetroMultiPlatform.js +12 -16
  33. package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
  34. package/build/src/start/server/middleware/DataLoaderModuleMiddleware.js.map +1 -1
  35. package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.js +0 -1
  36. package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.js.map +1 -1
  37. package/build/src/start/server/middleware/metroOptions.js +19 -4
  38. package/build/src/start/server/middleware/metroOptions.js.map +1 -1
  39. package/build/src/start/server/platformBundlers.js +0 -2
  40. package/build/src/start/server/platformBundlers.js.map +1 -1
  41. package/build/src/start/server/serverLogLikeMetro.js +18 -18
  42. package/build/src/start/server/serverLogLikeMetro.js.map +1 -1
  43. package/build/src/start/server/webpack/WebpackBundlerDevServer.js +2 -2
  44. package/build/src/start/server/webpack/WebpackBundlerDevServer.js.map +1 -1
  45. package/build/src/start/startAsync.js +5 -5
  46. package/build/src/start/startAsync.js.map +1 -1
  47. package/build/src/utils/downloadExpoGoAsync.js +0 -1
  48. package/build/src/utils/downloadExpoGoAsync.js.map +1 -1
  49. package/build/src/utils/errors.js.map +1 -1
  50. package/build/src/utils/exit.js +1 -2
  51. package/build/src/utils/exit.js.map +1 -1
  52. package/build/src/utils/nodeEnv.js +0 -1
  53. package/build/src/utils/nodeEnv.js.map +1 -1
  54. package/build/src/utils/npm.js +31 -0
  55. package/build/src/utils/npm.js.map +1 -1
  56. package/build/src/utils/plist.js +0 -1
  57. package/build/src/utils/plist.js.map +1 -1
  58. package/build/src/utils/progress.js +3 -4
  59. package/build/src/utils/progress.js.map +1 -1
  60. package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
  61. package/build/src/utils/telemetry/utils/context.js +1 -1
  62. package/package.json +21 -20
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport MetroHmrServer, { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport RevisionNotFoundError from '@expo/metro/metro/IncrementalBundler/RevisionNotFoundError';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport formatBundlingError from '@expo/metro/metro/lib/formatBundlingError';\nimport { loadConfig, resolveConfig, type ConfigT } from '@expo/metro/metro-config';\nimport { Terminal } from '@expo/metro/metro-core';\nimport { getDefaultConfig, type LoadOptions } from '@expo/metro-config';\nimport chalk from 'chalk';\nimport http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// Wrap terminal and polyfill console.log so we can log during bundling without breaking the indicator.\nclass LogRespectingTerminal extends Terminal {\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream, { ttyPrint: true });\n\n const sendLog = (...msg: any[]) => {\n if (!msg.length) {\n this.log('');\n } else {\n const [format, ...args] = msg;\n this.log(format, ...args);\n }\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n console.log = sendLog;\n console.info = sendLog;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? env.EXPO_USE_STICKY_RESOLVER;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (exp.experiments?.reactServerComponentRoutes || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n }\n\n if (exp.experiments?.reactCanary) {\n Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);\n }\n\n const serverRoot = getMetroServerRoot(projectRoot);\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n const hasConfig = await resolveConfig(options.config, projectRoot);\n let config: ConfigT = {\n ...(await loadConfig(\n { cwd: projectRoot, projectRoot, ...options },\n // If the project does not have a metro.config.js, then we use the default config.\n hasConfig.isEmpty ? getDefaultConfig(projectRoot) : undefined\n )),\n reporter: {\n update(event: any) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n // @ts-expect-error: Set the global require cycle ignore patterns for SSR bundles. This won't work with custom global prefixes, but we don't use those.\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n // @ts-expect-error: typed as readonly.\n config.transformer.publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n // @ts-expect-error: typed as readonly\n config.transformer.publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n if (exp.experiments?.reactCompiler) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n if (autolinkingModuleResolutionEnabled) {\n Log.warn(`Experimental Expo Autolinking module resolver is enabled.`);\n }\n\n if (serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: !!exp.experiments?.reactServerComponentRoutes,\n getMetroBundler,\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: Omit<LoadOptions, 'logger'>,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: MetroServer;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler() {\n return metro.getBundler().getBundler();\n },\n });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } =\n createMetroMiddleware(metroConfig);\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware(\n metroBundler,\n reporter\n );\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n // @ts-expect-error: can't mutate readonly config\n metroConfig.server.enhanceMiddleware = (metroMiddleware: any, server: MetroServer) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n const { server, hmrServer, metro } = await runServer(\n metroBundler,\n metroConfig,\n {\n websocketEndpoints: {\n ...websocketEndpoints,\n ...createDevToolsPluginWebsocketEndpoint(),\n },\n watch: !isExporting && isWatchEnabled(),\n },\n {\n mockServer: isExporting,\n }\n );\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n projectRoot,\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: MetroServer, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n platform: graph.transformOptions.platform,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n // @ts-expect-error\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n // @ts-expect-error\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle:\n | typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default\n | typeof import('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // TODO: Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (\n this: MetroHmrServer<MetroHmrClient>,\n group,\n options,\n changeEvent\n ) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n platform: revision.graph.transformOptions.platform,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n // @ts-expect-error\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const isRouterRoute =\n path.isAbsolute(filePath) && filePath.startsWith(path.resolve(projectRoot, routerRoot));\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","LogRespectingTerminal","Terminal","constructor","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","console","info","terminal","process","stdout","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","env","EXPO_USE_STICKY_RESOLVER","serverActionsEnabled","reactServerFunctions","EXPO_UNSTABLE_SERVER_FUNCTIONS","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","warn","serverRoot","getMetroServerRoot","terminalReporter","MetroTerminalReporter","hasConfig","resolveConfig","loadConfig","cwd","isEmpty","getDefaultConfig","undefined","reporter","update","event","globalThis","__requireCycleIgnorePatterns","resolver","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","server","enhanceMiddleware","metroMiddleware","attachAtlasAsync","resetAtlasFile","hmrServer","runServer","createDevToolsPluginWebsocketEndpoint","watch","mockServer","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","path","sort","a","b","hmrJSBundle","require","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","push","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","error","formattedError","messageSocket","split","sep","join","dom","match","routerRoot","isRouterEntry","test","isRouterModule","isRouterRoute","isAbsolute","startsWith","resolve","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;IAgLsBA,qBAAqB;eAArBA;;IAgSNC,cAAc;eAAdA;;IAnZMC,oBAAoB;eAApBA;;;;yBA7DqB;;;;;;;yBACR;;;;;;;gEAKD;;;;;;;gEAEF;;;;;;;yBACwB;;;;;;;yBAC/B;;;;;;;yBAC0B;;;;;;;gEACjC;;;;;;;gEAED;;;;;;iDAEqC;uCAEhB;6BACL;uCACK;uCACA;+BACZ;wCACkB;qBACxB;qBACA;wBACS;gCACQ;6CACO;2BACV;kCACE;;;;;;AAOpC,uGAAuG;AACvG,MAAMC,8BAA8BC,qBAAQ;IAC1CC,YAAYC,MAAkE,CAAE;QAC9E,KAAK,CAACA,QAAQ;YAAEC,UAAU;QAAK;QAE/B,MAAMC,UAAU,CAAC,GAAGC;YAClB,IAAI,CAACA,IAAIC,MAAM,EAAE;gBACf,IAAI,CAACC,GAAG,CAAC;YACX,OAAO;gBACL,MAAM,CAACC,QAAQ,GAAGC,KAAK,GAAGJ;gBAC1B,IAAI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AACE,kBAAkB,CAACC,eAAe;YACvDtE,iBAAiBG,sBAAsB,CAAE+D,UAAU,GAAG;QACxD;IACF;IAEA,IACElE,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyC0E,WAAW,KACpD,+IAA+I;IAC/I,CAAE3E,CAAAA,SAASkE,KAAK,CAAC,0BAA0BlE,SAASkE,KAAK,CAAC,yBAAwB,GAClF;QACA,OAAOjE,iBAAiBG,sBAAsB,CAACuE,WAAW;IAC5D;IAEA,IACE1E,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyC2E,gBAAgB,KACzD,2FAA2F;IAC3F,CAAC5E,SAASkE,KAAK,CAAC,8BAChB;QACA,OAAOjE,iBAAiBG,sBAAsB,CAACwE,gBAAgB;IACjE;IAEA,OAAO3E;AACT;AAMO,SAAShH;IACd,IAAI6B,QAAG,CAAC+J,EAAE,EAAE;QACVvJ,QAAG,CAAC3B,GAAG,CACLqD,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAAClC,QAAG,CAAC+J,EAAE;AAChB"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport MetroHmrServer, { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport RevisionNotFoundError from '@expo/metro/metro/IncrementalBundler/RevisionNotFoundError';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport formatBundlingError from '@expo/metro/metro/lib/formatBundlingError';\nimport { loadConfig, resolveConfig, type ConfigT } from '@expo/metro/metro-config';\nimport { Terminal } from '@expo/metro/metro-core';\nimport {\n createStableModuleIdFactory,\n getDefaultConfig,\n type LoadOptions,\n} from '@expo/metro-config';\nimport chalk from 'chalk';\nimport http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// NOTE(@kitten): We pass a custom createStableModuleIdFactory function into the Metro module ID factory sometimes\ninterface MetroServerWithModuleIdMod extends MetroServer {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\ninterface MetroHmrServerWithModuleIdMod extends MetroHmrServer<MetroHmrClient> {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// TODO(@kitten): We assign this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this setting is used\ndeclare namespace globalThis {\n let __requireCycleIgnorePatterns: readonly RegExp[] | undefined;\n}\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\n// Wrap terminal and polyfill console.log so we can log during bundling without breaking the indicator.\nclass LogRespectingTerminal extends Terminal {\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream, { ttyPrint: true });\n\n const sendLog = (...msg: any[]) => {\n if (!msg.length) {\n this.log('');\n } else {\n const [format, ...args] = msg;\n this.log(format, ...args);\n }\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n console.log = sendLog;\n console.info = sendLog;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? env.EXPO_USE_STICKY_RESOLVER;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (exp.experiments?.reactServerComponentRoutes || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n }\n\n if (exp.experiments?.reactCanary) {\n Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);\n }\n\n const serverRoot = getMetroServerRoot(projectRoot);\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n const hasConfig = await resolveConfig(options.config, projectRoot);\n let config: ConfigT = {\n ...(await loadConfig(\n { cwd: projectRoot, projectRoot, ...options },\n // If the project does not have a metro.config.js, then we use the default config.\n hasConfig.isEmpty ? getDefaultConfig(projectRoot) : undefined\n )),\n reporter: {\n update(event: any) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n asWritable(config.transformer).publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n if (exp.experiments?.reactCompiler) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n if (autolinkingModuleResolutionEnabled) {\n Log.warn(`Experimental Expo Autolinking module resolver is enabled.`);\n }\n\n if (serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: !!exp.experiments?.reactServerComponentRoutes,\n getMetroBundler,\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: Omit<LoadOptions, 'logger'>,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: MetroServer;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler() {\n return metro.getBundler().getBundler();\n },\n });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } =\n createMetroMiddleware(metroConfig);\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware(\n metroBundler,\n reporter\n );\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n const { server, hmrServer, metro } = await runServer(\n metroBundler,\n metroConfig,\n {\n websocketEndpoints: {\n ...websocketEndpoints,\n ...createDevToolsPluginWebsocketEndpoint(),\n },\n watch: !isExporting && isWatchEnabled(),\n },\n {\n mockServer: isExporting,\n }\n );\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n projectRoot,\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: MetroServerWithModuleIdMod, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n // TODO(@kitten): Increase type-safety here\n platform: graph.transformOptions.platform!,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle:\n | typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default\n | typeof import('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // TODO: Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (\n this: MetroHmrServerWithModuleIdMod,\n group,\n options,\n changeEvent\n ) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n // TODO(@kitten): Increase type-safety here\n platform: revision.graph.transformOptions.platform!,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const isRouterRoute =\n path.isAbsolute(filePath) && filePath.startsWith(path.resolve(projectRoot, routerRoot));\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","asWritable","input","LogRespectingTerminal","Terminal","constructor","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","console","info","terminal","process","stdout","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","env","EXPO_USE_STICKY_RESOLVER","serverActionsEnabled","reactServerFunctions","EXPO_UNSTABLE_SERVER_FUNCTIONS","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","warn","serverRoot","getMetroServerRoot","terminalReporter","MetroTerminalReporter","hasConfig","resolveConfig","loadConfig","cwd","isEmpty","getDefaultConfig","undefined","reporter","update","event","globalThis","__requireCycleIgnorePatterns","resolver","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","server","enhanceMiddleware","metroMiddleware","attachAtlasAsync","resetAtlasFile","hmrServer","runServer","createDevToolsPluginWebsocketEndpoint","watch","mockServer","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","path","sort","a","b","hmrJSBundle","require","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","push","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","error","formattedError","messageSocket","split","sep","join","dom","match","routerRoot","isRouterEntry","test","isRouterModule","isRouterRoute","isAbsolute","startsWith","resolve","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;IAoMsBA,qBAAqB;eAArBA;;IAiSNC,cAAc;eAAdA;;IAjZMC,oBAAoB;eAApBA;;;;yBApFqB;;;;;;;yBACR;;;;;;;gEAKD;;;;;;;gEAEF;;;;;;;yBACwB;;;;;;;yBAC/B;;;;;;;yBAKlB;;;;;;;gEACW;;;;;;;gEAED;;;;;;iDAEqC;uCAEhB;6BACL;uCACK;uCACA;+BACZ;wCACkB;qBACxB;qBACA;wBACS;gCACQ;6CACO;2BACV;kCACE;;;;;;AAsBpC,SAASC,WAAcC,KAAQ;IAC7B,OAAOA;AACT;AAEA,uGAAuG;AACvG,MAAMC,8BAA8BC,qBAAQ;IAC1CC,YAAYC,MAAkE,CAAE;QAC9E,KAAK,CAACA,QAAQ;YAAEC,UAAU;QAAK;QAE/B,MAAMC,UAAU,CAAC,GAAGC;YAClB,IAAI,CAACA,IAAIC,MAAM,EAAE;gBACf,IAAI,CAACC,GAAG,CAAC;YACX,OAAO;gBACL,MAAM,CAACC,QAAQ,GAAGC,KAAK,GAAGJ;gBAC1B,IAAI,CAACE,GAAG,CAACC,WAAWC;YACtB;YACA,6FAA6F;YAC7F,IA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AAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyC0E,WAAW,KACpD,+IAA+I;IAC/I,CAAE3E,CAAAA,SAASkE,KAAK,CAAC,0BAA0BlE,SAASkE,KAAK,CAAC,yBAAwB,GAClF;QACA,OAAOjE,iBAAiBG,sBAAsB,CAACuE,WAAW;IAC5D;IAEA,IACE1E,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyC2E,gBAAgB,KACzD,2FAA2F;IAC3F,CAAC5E,SAASkE,KAAK,CAAC,8BAChB;QACA,OAAOjE,iBAAiBG,sBAAsB,CAACwE,gBAAgB;IACjE;IAEA,OAAO3E;AACT;AAMO,SAASlH;IACd,IAAI+B,QAAG,CAAC+J,EAAE,EAAE;QACVvJ,QAAG,CAAC3B,GAAG,CACLqD,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAAClC,QAAG,CAAC+J,EAAE;AAChB"}
@@ -256,7 +256,6 @@ const createMutateResolutionError = (config, depGraph, stackDepthLimit = STACK_D
256
256
  extraMessage += (0, _chalk().default)`\n\n {bold {yellow Depth limit reached. The actual stack is longer than what you can see above.}}`;
257
257
  }
258
258
  extraMessage += '\n';
259
- // @ts-expect-error
260
259
  error._expoImportStack = extraMessage;
261
260
  } else {
262
261
  debug('Found no inverse tree for:', context.originModulePath);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/withMetroErrorReportingResolver.ts"],"sourcesContent":["import type { ConfigT as MetroConfig } from '@expo/metro/metro-config';\nimport type { ResolutionContext } from '@expo/metro/metro-resolver';\nimport chalk from 'chalk';\nimport path from 'path';\nimport { stripVTControlCharacters } from 'util';\n\nimport type { ExpoCustomMetroResolver } from './withMetroResolvers';\nimport { isPathInside } from '../../../utils/dir';\nimport { env } from '../../../utils/env';\n\nconst debug = require('debug')('expo:metro:withMetroResolvers') as typeof console.log;\n\n// TODO: Do we need to expose this?\nconst STACK_DEPTH_LIMIT = 35;\nconst STACK_COUNT_LIMIT = 2_000;\n\nexport function withMetroErrorReportingResolver(config: MetroConfig): MetroConfig {\n if (!env.EXPO_METRO_UNSTABLE_ERRORS) {\n return config;\n }\n\n const originalResolveRequest = config.resolver?.resolveRequest;\n\n const depGraph: DepGraph = new Map();\n\n const mutateResolutionError = createMutateResolutionError(config, depGraph);\n\n return {\n ...config,\n resolver: {\n ...config.resolver,\n resolveRequest(context, moduleName, platform) {\n const storeResult = (res: NonNullable<ReturnType<ExpoCustomMetroResolver>>) => {\n const inputPlatform = platform ?? 'null';\n\n const key = optionsKeyForContext(context);\n if (!depGraph.has(key)) depGraph.set(key, new Map());\n const mapByTarget = depGraph.get(key);\n if (!mapByTarget!.has(inputPlatform)) mapByTarget!.set(inputPlatform, new Map());\n const mapByPlatform = mapByTarget!.get(inputPlatform);\n if (!mapByPlatform!.has(context.originModulePath))\n mapByPlatform!.set(context.originModulePath, new Set());\n const setForModule = mapByPlatform!.get(context.originModulePath)!;\n\n const qualifiedModuleName = res?.type === 'sourceFile' ? res.filePath : moduleName;\n setForModule.add({ path: qualifiedModuleName, request: moduleName });\n };\n\n // If the user defined a resolver, run it first and depend on the documented\n // chaining logic: https://facebook.github.io/metro/docs/resolution/#resolution-algorithm\n //\n // config.resolver.resolveRequest = (context, moduleName, platform) => {\n //\n // // Do work...\n //\n // return context.resolveRequest(context, moduleName, platform);\n // };\n try {\n const firstResolver = originalResolveRequest ?? context.resolveRequest;\n const res = firstResolver(context, moduleName, platform);\n storeResult(res);\n return res;\n } catch (error: any) {\n throw mutateResolutionError(error, context, moduleName, platform);\n }\n },\n },\n };\n}\n\nexport type DepGraph = Map<\n // custom options\n string,\n Map<\n // platform\n string,\n Map<\n // origin module name\n string,\n Set<{\n // required module name\n path: string;\n // This isn't entirely accurate since a module can be imported multiple times in a file,\n // and use different names. But it's good enough for now.\n request: string;\n }>\n >\n >\n>;\n\nfunction optionsKeyForContext(context: ResolutionContext) {\n const canonicalize: typeof import('@expo/metro/metro-core/canonicalize').default = require('@expo/metro/metro-core/canonicalize');\n // Compound key for the resolver cache\n return JSON.stringify(context.customResolverOptions ?? {}, canonicalize) ?? '';\n}\n\nexport const createMutateResolutionError =\n (\n config: MetroConfig,\n depGraph: DepGraph,\n stackDepthLimit = STACK_DEPTH_LIMIT,\n stackCountLimit = STACK_COUNT_LIMIT\n ) =>\n (error: Error, context: ResolutionContext, moduleName: string, platform: string | null) => {\n const inputPlatform = platform ?? 'null';\n\n const mapByOrigin = depGraph.get(optionsKeyForContext(context));\n const mapByPlatform = mapByOrigin?.get(inputPlatform);\n\n if (!mapByPlatform) {\n return error;\n }\n\n // collect all references inversely using some expensive lookup\n\n const getReferences = (origin: string) => {\n const inverseOrigin: { origin: string; previous: string; request: string }[] = [];\n\n if (!mapByPlatform) {\n return inverseOrigin;\n }\n\n for (const [originKey, mapByTarget] of mapByPlatform) {\n // search comparing origin to path\n\n const found = [...mapByTarget.values()].find((resolution) => resolution.path === origin);\n if (found) {\n inverseOrigin.push({\n origin,\n previous: originKey,\n request: found.request,\n });\n }\n }\n\n return inverseOrigin;\n };\n\n const root = config.server?.unstable_serverRoot ?? config.projectRoot;\n const projectRoot = config.projectRoot;\n\n type Frame = {\n origin: string;\n request: string;\n };\n type Stack = {\n circular?: boolean;\n limited?: boolean;\n serverRoot?: boolean;\n projectRoot?: boolean;\n frames: Frame[];\n };\n\n let stackCounter = 0;\n let inverseStack: Stack | undefined;\n /** @returns boolean - done */\n const saveStack = (stack: Stack): boolean => {\n stackCounter++;\n\n if (!inverseStack) {\n // First stack, save it\n inverseStack = stack;\n return false;\n }\n\n if (stackCounter >= stackCountLimit) {\n // Too many stacks explored, stop searching\n return true;\n }\n\n if (stack.circular || stack.limited) {\n // Not better than the current one, skip\n return false;\n }\n\n if (inverseStack.circular || inverseStack.limited) {\n // Current one is better than the previous one, save it\n inverseStack = stack;\n // No return as we want to continue validation the new stack\n }\n\n if (inverseStack.projectRoot) {\n // The best possible stack already acquired, skip\n return true;\n }\n\n const stackOrigin = stack.frames[stack.frames.length - 1].origin;\n\n if (\n stackOrigin &&\n isPathInside(stackOrigin, projectRoot) &&\n !stackOrigin.includes('node_modules')\n ) {\n // The best stack to show to users is the one leading from the project code.\n stack.serverRoot = true;\n inverseStack = stack;\n return true;\n }\n\n if (\n // Has to be after the project root check\n stackOrigin &&\n isPathInside(stackOrigin, root) &&\n !stackOrigin.includes('node_modules')\n ) {\n // The best stack to show to users is the one leading from the monorepo code.\n stack.serverRoot = true;\n inverseStack = stack;\n return false;\n }\n\n // If new stack is not better do nothing\n return false;\n };\n\n /** @returns boolean - done */\n const recurseBackWithLimit = (\n frame: { origin: string; request: string },\n limit: number,\n stack: Stack = { frames: [] },\n visited: Set<string> = new Set()\n ): boolean => {\n stack.frames.push(frame);\n\n if (visited.has(frame.origin)) {\n stack.circular = true;\n return saveStack(stack);\n }\n\n if (stack.frames.length >= limit) {\n stack.limited = true;\n return saveStack(stack);\n }\n\n visited.add(frame.origin);\n\n const inverse = getReferences(frame.origin);\n if (inverse.length === 0) {\n // No more references, push the stack and return\n return saveStack(stack);\n }\n\n for (const match of inverse) {\n // Use more qualified name if possible\n // results.origin = match.origin;\n // Found entry point\n if (frame.origin === match.previous) {\n continue;\n }\n\n const isDone = recurseBackWithLimit(\n { origin: match.previous, request: match.request },\n limit,\n {\n frames: [...stack.frames],\n },\n new Set(visited)\n );\n\n if (isDone) {\n return true; // Stop search\n }\n }\n\n return false; // Continue search\n };\n\n recurseBackWithLimit(\n { origin: context.originModulePath, request: moduleName },\n stackDepthLimit\n );\n\n debug('Number of explored stacks:', stackCounter);\n\n if (inverseStack && inverseStack.frames.length > 0) {\n const formattedImport = chalk`{gray |} {cyan import} `;\n const importMessagePadding = ' '.repeat(stripVTControlCharacters(formattedImport).length + 1);\n\n debug('Found inverse graph:', JSON.stringify(inverseStack, null, 2));\n\n let extraMessage = chalk.bold(\n `Import stack${stackCounter >= stackCountLimit ? ` (${stackCounter})` : ''}:`\n );\n\n for (const frame of inverseStack.frames) {\n let currentMessage = '';\n let filename = path.relative(root, frame.origin);\n\n if (filename.match(/\\?ctx=[\\w\\d]+$/)) {\n filename = filename.replace(/\\?ctx=[\\w\\d]+$/, chalk.dim(' (require.context)'));\n } else {\n let formattedRequest = chalk.green(`\"${frame.request}\"`);\n\n if (\n // If bundling for web and the import is pulling internals from outside of react-native\n // then mark it as an invalid import.\n inputPlatform === 'web' &&\n !/^(node_modules\\/)?react-native\\//.test(filename) &&\n frame.request.match(/^react-native\\/.*/)\n ) {\n formattedRequest =\n formattedRequest +\n chalk`\\n${importMessagePadding}{yellow ^ Importing react-native internals is not supported on web.}`;\n }\n\n filename = filename + chalk`\\n${formattedImport}${formattedRequest}`;\n }\n\n let line = '\\n' + chalk.gray(' ') + filename;\n if (filename.match(/node_modules/)) {\n line = chalk.gray(\n // Bold the node module name\n line.replace(/node_modules\\/([^/]+)/, (_match, p1) => {\n return 'node_modules/' + chalk.bold(p1);\n })\n );\n }\n currentMessage += `\\n${line}`;\n extraMessage += currentMessage;\n }\n\n if (inverseStack.circular) {\n extraMessage += chalk`\\n${importMessagePadding}{yellow ^ The import above creates circular dependency.}`;\n }\n\n if (inverseStack.limited) {\n extraMessage += chalk`\\n\\n {bold {yellow Depth limit reached. The actual stack is longer than what you can see above.}}`;\n }\n\n extraMessage += '\\n';\n\n // @ts-expect-error\n error._expoImportStack = extraMessage;\n } else {\n debug('Found no inverse tree for:', context.originModulePath);\n }\n\n return error;\n };\n"],"names":["createMutateResolutionError","withMetroErrorReportingResolver","debug","require","STACK_DEPTH_LIMIT","STACK_COUNT_LIMIT","config","env","EXPO_METRO_UNSTABLE_ERRORS","originalResolveRequest","resolver","resolveRequest","depGraph","Map","mutateResolutionError","context","moduleName","platform","storeResult","res","inputPlatform","key","optionsKeyForContext","has","set","mapByTarget","get","mapByPlatform","originModulePath","Set","setForModule","qualifiedModuleName","type","filePath","add","path","request","firstResolver","error","canonicalize","JSON","stringify","customResolverOptions","stackDepthLimit","stackCountLimit","mapByOrigin","getReferences","origin","inverseOrigin","originKey","found","values","find","resolution","push","previous","root","server","unstable_serverRoot","projectRoot","stackCounter","inverseStack","saveStack","stack","circular","limited","stackOrigin","frames","length","isPathInside","includes","serverRoot","recurseBackWithLimit","frame","limit","visited","inverse","match","isDone","formattedImport","chalk","importMessagePadding","repeat","stripVTControlCharacters","extraMessage","bold","currentMessage","filename","relative","replace","dim","formattedRequest","green","test","line","gray","_match","p1","_expoImportStack"],"mappings":";;;;;;;;;;;IAgGaA,2BAA2B;eAA3BA;;IAhFGC,+BAA+B;eAA/BA;;;;gEAdE;;;;;;;gEACD;;;;;;;yBACwB;;;;;;qBAGZ;qBACT;;;;;;AAEpB,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,mCAAmC;AACnC,MAAMC,oBAAoB;AAC1B,MAAMC,oBAAoB;AAEnB,SAASJ,gCAAgCK,MAAmB;QAKlCA;IAJ/B,IAAI,CAACC,QAAG,CAACC,0BAA0B,EAAE;QACnC,OAAOF;IACT;IAEA,MAAMG,0BAAyBH,mBAAAA,OAAOI,QAAQ,qBAAfJ,iBAAiBK,cAAc;IAE9D,MAAMC,WAAqB,IAAIC;IAE/B,MAAMC,wBAAwBd,4BAA4BM,QAAQM;IAElE,OAAO;QACL,GAAGN,MAAM;QACTI,UAAU;YACR,GAAGJ,OAAOI,QAAQ;YAClBC,gBAAeI,OAAO,EAAEC,UAAU,EAAEC,QAAQ;gBAC1C,MAAMC,cAAc,CAACC;oBACnB,MAAMC,gBAAgBH,YAAY;oBAElC,MAAMI,MAAMC,qBAAqBP;oBACjC,IAAI,CAACH,SAASW,GAAG,CAACF,MAAMT,SAASY,GAAG,CAACH,KAAK,IAAIR;oBAC9C,MAAMY,cAAcb,SAASc,GAAG,CAACL;oBACjC,IAAI,CAACI,YAAaF,GAAG,CAACH,gBAAgBK,YAAaD,GAAG,CAACJ,eAAe,IAAIP;oBAC1E,MAAMc,gBAAgBF,YAAaC,GAAG,CAACN;oBACvC,IAAI,CAAC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e,IAAI,CAAC,OAAOR;gBACpC,IAAIA,SAASV,KAAK,CAAC,iBAAiB;oBAClCiB,OAAOd,gBAAK,CAACe,IAAI,CACf,4BAA4B;oBAC5BD,KAAKL,OAAO,CAAC,yBAAyB,CAACO,QAAQC;wBAC7C,OAAO,kBAAkBjB,gBAAK,CAACK,IAAI,CAACY;oBACtC;gBAEJ;gBACAX,kBAAkB,CAAC,EAAE,EAAEQ,MAAM;gBAC7BV,gBAAgBE;YAClB;YAEA,IAAIzB,aAAaG,QAAQ,EAAE;gBACzBoB,gBAAgBJ,IAAAA,gBAAK,CAAA,CAAC,EAAE,EAAEC,qBAAqB,wDAAwD,CAAC;YAC1G;YAEA,IAAIpB,aAAaI,OAAO,EAAE;gBACxBmB,gBAAgBJ,IAAAA,gBAAK,CAAA,CAAC,iGAAiG,CAAC;YAC1H;YAEAI,gBAAgB;YAEhB,mBAAmB;YACnB9C,MAAM4D,gBAAgB,GAAGd;QAC3B,OAAO;YACLlF,MAAM,8BAA8Ba,QAAQa,gBAAgB;QAC9D;QAEA,OAAOU;IACT"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/withMetroErrorReportingResolver.ts"],"sourcesContent":["import type { ConfigT as MetroConfig } from '@expo/metro/metro-config';\nimport type { ResolutionContext } from '@expo/metro/metro-resolver';\nimport chalk from 'chalk';\nimport path from 'path';\nimport { stripVTControlCharacters } from 'util';\n\nimport type { ExpoCustomMetroResolver } from './withMetroResolvers';\nimport { isPathInside } from '../../../utils/dir';\nimport { env } from '../../../utils/env';\n\nconst debug = require('debug')('expo:metro:withMetroResolvers') as typeof console.log;\n\n// TODO: Do we need to expose this?\nconst STACK_DEPTH_LIMIT = 35;\nconst STACK_COUNT_LIMIT = 2_000;\n\nexport function withMetroErrorReportingResolver(config: MetroConfig): MetroConfig {\n if (!env.EXPO_METRO_UNSTABLE_ERRORS) {\n return config;\n }\n\n const originalResolveRequest = config.resolver?.resolveRequest;\n\n const depGraph: DepGraph = new Map();\n\n const mutateResolutionError = createMutateResolutionError(config, depGraph);\n\n return {\n ...config,\n resolver: {\n ...config.resolver,\n resolveRequest(context, moduleName, platform) {\n const storeResult = (res: NonNullable<ReturnType<ExpoCustomMetroResolver>>) => {\n const inputPlatform = platform ?? 'null';\n\n const key = optionsKeyForContext(context);\n if (!depGraph.has(key)) depGraph.set(key, new Map());\n const mapByTarget = depGraph.get(key);\n if (!mapByTarget!.has(inputPlatform)) mapByTarget!.set(inputPlatform, new Map());\n const mapByPlatform = mapByTarget!.get(inputPlatform);\n if (!mapByPlatform!.has(context.originModulePath))\n mapByPlatform!.set(context.originModulePath, new Set());\n const setForModule = mapByPlatform!.get(context.originModulePath)!;\n\n const qualifiedModuleName = res?.type === 'sourceFile' ? res.filePath : moduleName;\n setForModule.add({ path: qualifiedModuleName, request: moduleName });\n };\n\n // If the user defined a resolver, run it first and depend on the documented\n // chaining logic: https://facebook.github.io/metro/docs/resolution/#resolution-algorithm\n //\n // config.resolver.resolveRequest = (context, moduleName, platform) => {\n //\n // // Do work...\n //\n // return context.resolveRequest(context, moduleName, platform);\n // };\n try {\n const firstResolver = originalResolveRequest ?? context.resolveRequest;\n const res = firstResolver(context, moduleName, platform);\n storeResult(res);\n return res;\n } catch (error: any) {\n throw mutateResolutionError(error, context, moduleName, platform);\n }\n },\n },\n };\n}\n\nexport type DepGraph = Map<\n // custom options\n string,\n Map<\n // platform\n string,\n Map<\n // origin module name\n string,\n Set<{\n // required module name\n path: string;\n // This isn't entirely accurate since a module can be imported multiple times in a file,\n // and use different names. But it's good enough for now.\n request: string;\n }>\n >\n >\n>;\n\nfunction optionsKeyForContext(context: ResolutionContext) {\n const canonicalize: typeof import('@expo/metro/metro-core/canonicalize').default = require('@expo/metro/metro-core/canonicalize');\n // Compound key for the resolver cache\n return JSON.stringify(context.customResolverOptions ?? {}, canonicalize) ?? '';\n}\n\ninterface ErrorWithExpoImportStack extends Error {\n _expoImportStack?: string;\n}\n\nexport const createMutateResolutionError =\n (\n config: MetroConfig,\n depGraph: DepGraph,\n stackDepthLimit = STACK_DEPTH_LIMIT,\n stackCountLimit = STACK_COUNT_LIMIT\n ) =>\n (\n error: ErrorWithExpoImportStack,\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) => {\n const inputPlatform = platform ?? 'null';\n\n const mapByOrigin = depGraph.get(optionsKeyForContext(context));\n const mapByPlatform = mapByOrigin?.get(inputPlatform);\n\n if (!mapByPlatform) {\n return error;\n }\n\n // collect all references inversely using some expensive lookup\n\n const getReferences = (origin: string) => {\n const inverseOrigin: { origin: string; previous: string; request: string }[] = [];\n\n if (!mapByPlatform) {\n return inverseOrigin;\n }\n\n for (const [originKey, mapByTarget] of mapByPlatform) {\n // search comparing origin to path\n\n const found = [...mapByTarget.values()].find((resolution) => resolution.path === origin);\n if (found) {\n inverseOrigin.push({\n origin,\n previous: originKey,\n request: found.request,\n });\n }\n }\n\n return inverseOrigin;\n };\n\n const root = config.server?.unstable_serverRoot ?? config.projectRoot;\n const projectRoot = config.projectRoot;\n\n type Frame = {\n origin: string;\n request: string;\n };\n type Stack = {\n circular?: boolean;\n limited?: boolean;\n serverRoot?: boolean;\n projectRoot?: boolean;\n frames: Frame[];\n };\n\n let stackCounter = 0;\n let inverseStack: Stack | undefined;\n /** @returns boolean - done */\n const saveStack = (stack: Stack): boolean => {\n stackCounter++;\n\n if (!inverseStack) {\n // First stack, save it\n inverseStack = stack;\n return false;\n }\n\n if (stackCounter >= stackCountLimit) {\n // Too many stacks explored, stop searching\n return true;\n }\n\n if (stack.circular || stack.limited) {\n // Not better than the current one, skip\n return false;\n }\n\n if (inverseStack.circular || inverseStack.limited) {\n // Current one is better than the previous one, save it\n inverseStack = stack;\n // No return as we want to continue validation the new stack\n }\n\n if (inverseStack.projectRoot) {\n // The best possible stack already acquired, skip\n return true;\n }\n\n const stackOrigin = stack.frames[stack.frames.length - 1].origin;\n\n if (\n stackOrigin &&\n isPathInside(stackOrigin, projectRoot) &&\n !stackOrigin.includes('node_modules')\n ) {\n // The best stack to show to users is the one leading from the project code.\n stack.serverRoot = true;\n inverseStack = stack;\n return true;\n }\n\n if (\n // Has to be after the project root check\n stackOrigin &&\n isPathInside(stackOrigin, root) &&\n !stackOrigin.includes('node_modules')\n ) {\n // The best stack to show to users is the one leading from the monorepo code.\n stack.serverRoot = true;\n inverseStack = stack;\n return false;\n }\n\n // If new stack is not better do nothing\n return false;\n };\n\n /** @returns boolean - done */\n const recurseBackWithLimit = (\n frame: { origin: string; request: string },\n limit: number,\n stack: Stack = { frames: [] },\n visited: Set<string> = new Set()\n ): boolean => {\n stack.frames.push(frame);\n\n if (visited.has(frame.origin)) {\n stack.circular = true;\n return saveStack(stack);\n }\n\n if (stack.frames.length >= limit) {\n stack.limited = true;\n return saveStack(stack);\n }\n\n visited.add(frame.origin);\n\n const inverse = getReferences(frame.origin);\n if (inverse.length === 0) {\n // No more references, push the stack and return\n return saveStack(stack);\n }\n\n for (const match of inverse) {\n // Use more qualified name if possible\n // results.origin = match.origin;\n // Found entry point\n if (frame.origin === match.previous) {\n continue;\n }\n\n const isDone = recurseBackWithLimit(\n { origin: match.previous, request: match.request },\n limit,\n {\n frames: [...stack.frames],\n },\n new Set(visited)\n );\n\n if (isDone) {\n return true; // Stop search\n }\n }\n\n return false; // Continue search\n };\n\n recurseBackWithLimit(\n { origin: context.originModulePath, request: moduleName },\n stackDepthLimit\n );\n\n debug('Number of explored stacks:', stackCounter);\n\n if (inverseStack && inverseStack.frames.length > 0) {\n const formattedImport = chalk`{gray |} {cyan import} `;\n const importMessagePadding = ' '.repeat(stripVTControlCharacters(formattedImport).length + 1);\n\n debug('Found inverse graph:', JSON.stringify(inverseStack, null, 2));\n\n let extraMessage = chalk.bold(\n `Import stack${stackCounter >= stackCountLimit ? ` (${stackCounter})` : ''}:`\n );\n\n for (const frame of inverseStack.frames) {\n let currentMessage = '';\n let filename = path.relative(root, frame.origin);\n\n if (filename.match(/\\?ctx=[\\w\\d]+$/)) {\n filename = filename.replace(/\\?ctx=[\\w\\d]+$/, chalk.dim(' (require.context)'));\n } else {\n let formattedRequest = chalk.green(`\"${frame.request}\"`);\n\n if (\n // If bundling for web and the import is pulling internals from outside of react-native\n // then mark it as an invalid import.\n inputPlatform === 'web' &&\n !/^(node_modules\\/)?react-native\\//.test(filename) &&\n frame.request.match(/^react-native\\/.*/)\n ) {\n formattedRequest =\n formattedRequest +\n chalk`\\n${importMessagePadding}{yellow ^ Importing react-native internals is not supported on web.}`;\n }\n\n filename = filename + chalk`\\n${formattedImport}${formattedRequest}`;\n }\n\n let line = '\\n' + chalk.gray(' ') + filename;\n if (filename.match(/node_modules/)) {\n line = chalk.gray(\n // Bold the node module name\n line.replace(/node_modules\\/([^/]+)/, (_match, p1) => {\n return 'node_modules/' + chalk.bold(p1);\n })\n );\n }\n currentMessage += `\\n${line}`;\n extraMessage += currentMessage;\n }\n\n if (inverseStack.circular) {\n extraMessage += chalk`\\n${importMessagePadding}{yellow ^ The import above creates circular dependency.}`;\n }\n\n if (inverseStack.limited) {\n extraMessage += chalk`\\n\\n {bold {yellow Depth limit reached. The actual stack is longer than what you can see above.}}`;\n }\n\n extraMessage += '\\n';\n\n error._expoImportStack = extraMessage;\n } else {\n debug('Found no inverse tree for:', context.originModulePath);\n }\n\n return error;\n };\n"],"names":["createMutateResolutionError","withMetroErrorReportingResolver","debug","require","STACK_DEPTH_LIMIT","STACK_COUNT_LIMIT","config","env","EXPO_METRO_UNSTABLE_ERRORS","originalResolveRequest","resolver","resolveRequest","depGraph","Map","mutateResolutionError","context","moduleName","platform","storeResult","res","inputPlatform","key","optionsKeyForContext","has","set","mapByTarget","get","mapByPlatform","originModulePath","Set","setForModule","qualifiedModuleName","type","filePath","add","path","request","firstResolver","error","canonicalize","JSON","stringify","customResolverOptions","stackDepthLimit","stackCountLimit","mapByOrigin","getReferences","origin","inverseOrigin","originKey","found","values","find","resolution","push","previous","root","server","unstable_serverRoot","projectRoot","stackCounter","inverseStack","saveStack","stack","circular","limited","stackOrigin","frames","length","isPathInside","includes","serverRoot","recurseBackWithLimit","frame","limit","visited","inverse","match","isDone","formattedImport","chalk","importMessagePadding","repeat","stripVTControlCharacters","extraMessage","bold","currentMessage","filename","relative","replace","dim","formattedRequest","green","test","line","gray","_match","p1","_expoImportStack"],"mappings":";;;;;;;;;;;IAoGaA,2BAA2B;eAA3BA;;IApFGC,+BAA+B;eAA/BA;;;;gEAdE;;;;;;;gEACD;;;;;;;yBACwB;;;;;;qBAGZ;qBACT;;;;;;AAEpB,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,mCAAmC;AACnC,MAAMC,oBAAoB;AAC1B,MAAMC,oBAAoB;AAEnB,SAASJ,gCAAgCK,MAAmB;QAKlCA;IAJ/B,IAAI,CAACC,QAAG,CAACC,0BAA0B,EAAE;QACnC,OAAOF;IACT;IAEA,MAAMG,0BAAyBH,mBAAAA,OAAOI,QAAQ,qBAAfJ,iBAAiBK,cAAc;IAE9D,MAAMC,WAAqB,IAAIC;IAE/B,MAAMC,wBAAwBd,4BAA4BM,QAAQM;IAElE,OAAO;QACL,GAAGN,MAAM;QACTI,UAAU;YACR,GAAGJ,OAAOI,QAAQ;YAClBC,gBAAeI,OAAO,EAAEC,UAAU,EAAEC,QAAQ;gBAC1C,MAAMC,cAAc,CAACC;oBACnB,MAAMC,gBAAgBH,YAAY;oBAElC,MAAMI,MAAMC,qBAAqBP;oBACjC,IAAI,CAACH,SAASW,GAAG,CAACF,MAAMT,SAASY,GAAG,CAACH,KAAK,IAAIR;oBAC9C,MAAMY,cAAcb,SAASc,GAAG,CAACL;oBACjC,IAAI,CAACI,YAAaF,GAAG,CAACH,gBAAgBK,YAAaD,GAAG,CAACJ,eAAe,IAAIP;oBAC1E,MAAMc,gBAAgBF,YAAaC,GAAG,CAACN;oBACvC,IAAI,CAACO,cAAeJ,GAAG,CAACR,QAAQa,gBAAgB,GAC9CD,cAAeH,GAAG,CAACT,QAAQa,gBAAgB,EAAE,IAAIC;oBACnD,MAAMC,eAAeH,cAAeD,GAAG,C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AC,yBAAyB,CAACO,QAAQC;wBAC7C,OAAO,kBAAkBjB,gBAAK,CAACK,IAAI,CAACY;oBACtC;gBAEJ;gBACAX,kBAAkB,CAAC,EAAE,EAAEQ,MAAM;gBAC7BV,gBAAgBE;YAClB;YAEA,IAAIzB,aAAaG,QAAQ,EAAE;gBACzBoB,gBAAgBJ,IAAAA,gBAAK,CAAA,CAAC,EAAE,EAAEC,qBAAqB,wDAAwD,CAAC;YAC1G;YAEA,IAAIpB,aAAaI,OAAO,EAAE;gBACxBmB,gBAAgBJ,IAAAA,gBAAK,CAAA,CAAC,iGAAiG,CAAC;YAC1H;YAEAI,gBAAgB;YAEhB9C,MAAM4D,gBAAgB,GAAGd;QAC3B,OAAO;YACLlF,MAAM,8BAA8Ba,QAAQa,gBAAgB;QAC9D;QAEA,OAAOU;IACT"}
@@ -79,6 +79,9 @@ function _interop_require_default(obj) {
79
79
  }
80
80
  const ASSET_REGISTRY_SRC = `const assets=[];module.exports={registerAsset:s=>assets.push(s),getAssetByID:s=>assets[s-1]};`;
81
81
  const debug = require('debug')('expo:start:server:metro:multi-platform');
82
+ function asWritable(input) {
83
+ return input;
84
+ }
82
85
  function withWebPolyfills(config, { getMetroBundler }) {
83
86
  const originalGetPolyfills = config.serializer.getPolyfills ? config.serializer.getPolyfills.bind(config.serializer) : ()=>[];
84
87
  const getPolyfills = (ctx)=>{
@@ -588,10 +591,10 @@ function withExtendedResolver(config, { tsconfig, autolinkingModuleResolverInput
588
591
  // Ensure we mutate the resolution context to include the custom resolver options for server and web.
589
592
  const metroConfigWithCustomContext = (0, _withMetroResolvers.withMetroMutatedResolverContext)(metroConfigWithCustomResolver, (immutableContext, moduleName, platform)=>{
590
593
  var _context_customResolverOptions;
591
- const context = {
594
+ const context = asWritable({
592
595
  ...immutableContext,
593
596
  preferNativePlatform: platform !== 'web'
594
- };
597
+ });
595
598
  if ((0, _metroOptions.isServerEnvironment)((_context_customResolverOptions = context.customResolverOptions) == null ? void 0 : _context_customResolverOptions.environment)) {
596
599
  var _context_customResolverOptions1, _context_customResolverOptions2;
597
600
  // Adjust nodejs source extensions to sort mjs after js, including platform variants.
@@ -692,24 +695,18 @@ async function withMetroMultiPlatformAsync(projectRoot, { config, exp, platformB
692
695
  // Change the default metro-runtime to a custom one that supports bundle splitting.
693
696
  // NOTE(@kitten): This is now always active and EXPO_USE_METRO_REQUIRE / isNamedRequiresEnabled is disregarded
694
697
  const metroDefaults = require('@expo/metro/metro-config/defaults/defaults');
695
- metroDefaults.moduleSystem = require.resolve('@expo/cli/build/metro-require/require');
698
+ asWritable(metroDefaults).moduleSystem = require.resolve('@expo/cli/build/metro-require/require');
696
699
  if (!config.projectRoot) {
697
- // @ts-expect-error: read-only types
698
- config.projectRoot = projectRoot;
700
+ asWritable(config).projectRoot = projectRoot;
699
701
  }
700
702
  // Required for @expo/metro-runtime to format paths in the web LogBox.
701
703
  process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;
702
704
  // This is used for running Expo CLI in development against projects outside the monorepo.
703
705
  if (!isDirectoryIn(__dirname, projectRoot)) {
704
- // TODO(@kitten): Remove ts-export-errors here and replace with cast for type safety
705
- if (!config.watchFolders) {
706
- // @ts-expect-error: watchFolders is readonly
707
- config.watchFolders = [];
708
- }
709
- // @ts-expect-error: watchFolders is readonly
710
- config.watchFolders.push(_path().default.join(require.resolve('metro-runtime/package.json'), '../..'));
711
- // @ts-expect-error: watchFolders is readonly
712
- config.watchFolders.push(_path().default.join(require.resolve('@expo/metro-config/package.json'), '../..'), // For virtual modules
706
+ const watchFolders = config.watchFolders || [];
707
+ asWritable(config).watchFolders = watchFolders;
708
+ watchFolders.push(_path().default.join(require.resolve('metro-runtime/package.json'), '../..'));
709
+ watchFolders.push(_path().default.join(require.resolve('@expo/metro-config/package.json'), '../..'), // For virtual modules
713
710
  _path().default.join(require.resolve('expo/package.json'), '..'));
714
711
  }
715
712
  let tsconfig = null;
@@ -725,8 +722,7 @@ async function withMetroMultiPlatformAsync(projectRoot, { config, exp, platformB
725
722
  ...new Set(expoConfigPlatforms.concat(config.resolver.platforms))
726
723
  ];
727
724
  }
728
- // @ts-expect-error: typed as `readonly`.
729
- config.resolver.platforms = expoConfigPlatforms;
725
+ asWritable(config.resolver).platforms = expoConfigPlatforms;
730
726
  config = withWebPolyfills(config, {
731
727
  getMetroBundler
732
728
  });