@expo/cli 55.0.10 → 55.0.12

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 (29) hide show
  1. package/build/bin/cli +1 -1
  2. package/build/src/events/builder.js.map +1 -1
  3. package/build/src/events/index.js +10 -1
  4. package/build/src/events/index.js.map +1 -1
  5. package/build/src/export/exportAssets.js +10 -9
  6. package/build/src/export/exportAssets.js.map +1 -1
  7. package/build/src/start/platforms/ios/devicectl.js +27 -5
  8. package/build/src/start/platforms/ios/devicectl.js.map +1 -1
  9. package/build/src/start/server/DevToolsPluginManager.js +10 -1
  10. package/build/src/start/server/DevToolsPluginManager.js.map +1 -1
  11. package/build/src/start/server/metro/MetroBundlerDevServer.js +27 -3
  12. package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
  13. package/build/src/start/server/metro/MetroTerminalReporter.js +3 -1
  14. package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
  15. package/build/src/start/server/metro/instantiateMetro.js +45 -14
  16. package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
  17. package/build/src/start/server/metro/runServer-fork.js +4 -1
  18. package/build/src/start/server/metro/runServer-fork.js.map +1 -1
  19. package/build/src/start/server/metro/withMetroMultiPlatform.js +1 -2
  20. package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
  21. package/build/src/start/startAsync.js +4 -2
  22. package/build/src/start/startAsync.js.map +1 -1
  23. package/build/src/utils/interactive.js +2 -1
  24. package/build/src/utils/interactive.js.map +1 -1
  25. package/build/src/utils/nodeEnv.js +29 -2
  26. package/build/src/utils/nodeEnv.js.map +1 -1
  27. package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
  28. package/build/src/utils/telemetry/utils/context.js +1 -1
  29. package/package.json +11 -12
@@ -183,7 +183,9 @@ class MetroTerminalReporter extends _TerminalReporter.TerminalReporter {
183
183
  }
184
184
  _logInitializing(port, hasReducedPerformance) {
185
185
  // Don't print a giant logo...
186
- this.terminal.log(_chalk().default.dim('Starting Metro Bundler') + '\n');
186
+ if (!(0, _events.shouldReduceLogs)()) {
187
+ this.terminal.log(_chalk().default.dim('Starting Metro Bundler') + '\n');
188
+ }
187
189
  }
188
190
  shouldFilterClientLog(event) {
189
191
  return isAppRegistryStartupMessage(event.data);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import type { Terminal } from '@expo/metro/metro-core';\nimport chalk from 'chalk';\nimport path from 'path';\nimport { stripVTControlCharacters } from 'util';\n\nimport { logWarning, TerminalReporter } from './TerminalReporter';\nimport {\n BuildPhase,\n BundleDetails,\n BundleProgress,\n SnippetError,\n TerminalReportableEvent,\n} from './TerminalReporter.types';\nimport { NODE_STDLIB_MODULES } from './externals';\nimport { env } from '../../../utils/env';\nimport { learnMore } from '../../../utils/link';\nimport {\n logLikeMetro,\n maybeSymbolicateAndFormatJSErrorStackLogAsync,\n parseErrorStringToObject,\n} from '../serverLogLikeMetro';\nimport { attachImportStackToRootMessage, nearestImportStack } from './metroErrorInterface';\nimport { events, shouldReduceLogs } from '../../../events';\nimport { stripAnsi } from '../../../utils/ansi';\n\ntype ClientLogLevel =\n | 'trace'\n | 'info'\n | 'error'\n | 'warn'\n | 'log'\n | 'group'\n | 'groupCollapsed'\n | 'groupEnd'\n | 'debug';\n\nconst debug = require('debug')('expo:metro:logger') as typeof console.log;\n\n// prettier-ignore\nexport const event = events('metro', (t) => [\n t.event<'bundling:started', {\n id: string;\n platform: null | string;\n environment: null | string;\n entry: string;\n }>(),\n t.event<'bundling:done', {\n id: string | null;\n ms: number | null;\n total: number;\n }>(),\n t.event<'bundling:failed', {\n id: string | null;\n filename: string | null;\n message: string | null;\n importStack: string | null;\n targetModuleName: string | null;\n originModulePath: string | null;\n }>(),\n t.event<'bundling:progress', {\n id: string | null;\n progress: number;\n current: number;\n total: number;\n }>(),\n t.event<'server_log', {\n level: 'info' | 'warn' | 'error' | null;\n data: string | unknown[] | null;\n }>(),\n t.event<'client_log', {\n level: ClientLogLevel | null;\n data: unknown[] | null;\n }>(),\n t.event<'hmr_client_error', {\n message: string;\n }>(),\n t.event<'cache_write_error', {\n message: string;\n }>(),\n t.event<'cache_read_error', {\n message: string;\n }>(),\n]);\n\nconst MAX_PROGRESS_BAR_CHAR_WIDTH = 16;\nconst DARK_BLOCK_CHAR = '\\u2593';\nconst LIGHT_BLOCK_CHAR = '\\u2591';\n/**\n * Extends the default Metro logger and adds some additional features.\n * Also removes the giant Metro logo from the output.\n */\nexport class MetroTerminalReporter extends TerminalReporter {\n #lastFailedBuildID: string | undefined;\n\n constructor(\n public serverRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n _log(event: TerminalReportableEvent): void {\n this.#captureLog(event);\n switch (event.type) {\n case 'unstable_server_log':\n if (typeof event.data?.[0] === 'string') {\n const message = event.data[0];\n if (message.match(/JavaScript logs have moved/)) {\n // Hide this very loud message from upstream React Native in favor of the note in the terminal UI:\n // The \"› Press j │ open debugger\"\n\n // logger?.info(\n // '\\u001B[1m\\u001B[7m💡 JavaScript logs have moved!\\u001B[22m They can now be ' +\n // 'viewed in React Native DevTools. Tip: Type \\u001B[1mj\\u001B[22m in ' +\n // 'the terminal to open (requires Google Chrome or Microsoft Edge).' +\n // '\\u001B[27m',\n // );\n return;\n }\n\n if (!env.EXPO_DEBUG) {\n // In the context of developing an iOS app or website, the MetroInspectorProxy \"connection\" logs are very confusing.\n // Here we'll hide them behind EXPO_DEBUG or DEBUG=expo:*. In the future we can reformat them to clearly indicate that the \"Connection\" is regarding the debugger.\n // These logs are also confusing because they can say \"connection established\" even when the debugger is not in a usable state. Really they belong in a UI or behind some sort of debug logging.\n if (message.match(/Connection (closed|established|failed|terminated)/i)) {\n // Skip logging.\n return;\n }\n }\n }\n break;\n case 'client_log': {\n if (this.shouldFilterClientLog(event)) {\n return;\n } else if (event.level != null) {\n return this.#onClientLog(event);\n } else {\n break;\n }\n }\n }\n return super._log(event);\n }\n\n // Used for testing\n _getElapsedTime(startTime: bigint): bigint {\n return process.hrtime.bigint() - startTime;\n }\n /**\n * Extends the bundle progress to include the current platform that we're bundling.\n *\n * @returns `iOS path/to/bundle.js ▓▓▓▓▓░░░░░░░░░░░ 36.6% (4790/7922)`\n */\n _getBundleStatusMessage(progress: BundleProgress, phase: BuildPhase): string {\n const env = getEnvironmentForBuildDetails(progress.bundleDetails);\n const platform = env || getPlatformTagForBuildDetails(progress.bundleDetails);\n const inProgress = phase === 'in_progress';\n\n const localPath =\n typeof progress.bundleDetails?.customTransformOptions?.dom === 'string' &&\n progress.bundleDetails.customTransformOptions.dom.includes(path.sep)\n ? progress.bundleDetails.customTransformOptions.dom.replace(/^(\\.?\\.[\\\\/])+/, '')\n : this.#normalizePath(progress.bundleDetails.entryFile);\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundled ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n\n let time: string = '';\n let ms: number | null = null;\n\n if (startTime != null) {\n const elapsed: bigint = this._getElapsedTime(startTime);\n const micro = Number(elapsed) / 1000;\n ms = Number(elapsed) / 1e6;\n // If the milliseconds are < 0.5 then it will display as 0, so we display in microseconds.\n if (ms <= 0.5) {\n const tenthFractionOfMicro = ((micro * 10) / 1000).toFixed(0);\n // Format as microseconds to nearest tenth\n time = chalk.cyan.bold(`0.${tenthFractionOfMicro}ms`);\n } else {\n time = chalk.dim(ms.toFixed(0) + 'ms');\n }\n }\n\n if (phase === 'done') {\n event('bundling:done', {\n id: progress.bundleDetails.buildID ?? null,\n total: progress.totalFileCount,\n ms,\n });\n }\n\n // iOS Bundled 150ms\n const plural = progress.totalFileCount === 1 ? '' : 's';\n return (\n color(platform + status) +\n time +\n chalk.reset.dim(` ${localPath} (${progress.totalFileCount} module${plural})`)\n );\n }\n\n event('bundling:progress', {\n id: progress.bundleDetails.buildID ?? null,\n progress: progress.ratio,\n total: progress.totalFileCount,\n current: progress.transformedFileCount,\n });\n if (shouldReduceLogs()) {\n return '';\n }\n\n const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);\n const _progress = inProgress\n ? chalk.green.bgGreen(DARK_BLOCK_CHAR.repeat(filledBar)) +\n chalk.bgWhite.white(LIGHT_BLOCK_CHAR.repeat(MAX_PROGRESS_BAR_CHAR_WIDTH - filledBar)) +\n chalk.bold(` ${(100 * progress.ratio).toFixed(1).padStart(4)}% `) +\n chalk.dim(\n `(${progress.transformedFileCount\n .toString()\n .padStart(progress.totalFileCount.toString().length)}/${progress.totalFileCount})`\n )\n : '';\n return (\n platform +\n chalk.reset.dim(`${path.dirname(localPath)}${path.sep}`) +\n chalk.bold(path.basename(localPath)) +\n ' ' +\n _progress\n );\n }\n\n _logInitializing(port: number, hasReducedPerformance: boolean): void {\n // Don't print a giant logo...\n this.terminal.log(chalk.dim('Starting Metro Bundler') + '\\n');\n }\n\n shouldFilterClientLog(event: { type: 'client_log'; data: unknown[] }): boolean {\n return isAppRegistryStartupMessage(event.data);\n }\n\n shouldFilterBundleEvent(event: TerminalReportableEvent): boolean {\n return 'bundleDetails' in event && event.bundleDetails?.bundleType === 'map';\n }\n\n /** Print the cache clear message. */\n transformCacheReset(): void {\n logWarning(\n this.terminal,\n chalk`Bundler cache is empty, rebuilding {dim (this may take a minute)}`\n );\n }\n\n /** One of the first logs that will be printed */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {\n // this.terminal.log('Dependency graph is loading...');\n if (hasReducedPerformance) {\n // Extends https://github.com/facebook/metro/blob/347b1d7ed87995d7951aaa9fd597c04b06013dac/packages/metro/src/lib/TerminalReporter.js#L283-L290\n this.terminal.log(\n chalk.red(\n [\n 'Metro is operating with reduced performance.',\n 'Fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n /**\n * Workaround to link build ids to bundling errors.\n * This works because `_logBundleBuildFailed` is called before `_logBundlingError` in synchronous manner.\n * https://github.com/facebook/metro/blob/main/packages/metro/src/Server.js#L939-L945\n */\n _logBundleBuildFailed(buildID: string): void {\n this.#lastFailedBuildID = buildID;\n super._logBundleBuildFailed(buildID);\n }\n\n _logBundlingError(error: SnippetError): void {\n const importStack = nearestImportStack(error);\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.serverRoot, error);\n\n if (moduleResolutionError) {\n const message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n event('bundling:failed', {\n id: this.#lastFailedBuildID ?? null,\n message: stripAnsi(message) ?? null,\n importStack: importStack ?? null,\n filename: error.filename ?? null,\n targetModuleName: this.#normalizePath(error.targetModuleName),\n originModulePath: this.#normalizePath(error.originModulePath),\n });\n\n return this.terminal.log(importStack ? `${message}\\n\\n${importStack}` : message);\n } else {\n event('bundling:failed', {\n id: this.#lastFailedBuildID ?? null,\n message: stripAnsi(error.message) ?? null,\n importStack: importStack ?? null,\n filename: error.filename ?? null,\n targetModuleName: error.targetModuleName ?? null,\n originModulePath: error.originModulePath ?? null,\n });\n\n attachImportStackToRootMessage(error, importStack);\n\n // NOTE(@kitten): Metro drops the stack forcefully when it finds a `SyntaxError`. However,\n // this is really unhelpful, since it prevents debugging Babel plugins or reporting bugs\n // in Babel plugins or a transformer entirely\n if (error.snippet == null && error.stack != null && error instanceof SyntaxError) {\n error.message = error.stack;\n delete error.stack;\n }\n\n return super._logBundlingError(error);\n }\n }\n\n #onClientLog(evt: { type: 'client_log'; level?: ClientLogLevel; data: unknown[] }) {\n const { level = 'log', data } = evt;\n if (level === 'warn' || (level as string) === 'error') {\n let hasStack = false;\n const parsed = data.map((msg) => {\n // Quick check to see if an unsymbolicated stack is being logged.\n if (typeof msg === 'string' && msg.includes('.bundle//&platform=')) {\n const stack = parseErrorStringToObject(msg);\n if (stack) {\n hasStack = true;\n }\n return stack;\n }\n return msg;\n });\n\n if (hasStack) {\n (async () => {\n const symbolicating = parsed.map((p) => {\n if (typeof p === 'string') {\n return p;\n } else if (\n p &&\n typeof p === 'object' &&\n 'message' in p &&\n typeof p.message === 'string'\n ) {\n return maybeSymbolicateAndFormatJSErrorStackLogAsync(\n this.serverRoot,\n level,\n p as any\n );\n } else {\n return null;\n }\n });\n\n let usefulStackCount = 0;\n const fallbackIndices: number[] = [];\n const symbolicated = (await Promise.allSettled(symbolicating)).map((s, index) => {\n if (s.status === 'rejected') {\n debug('Error formatting stack', parsed[index], s.reason);\n return parsed[index];\n } else if (!s.value) {\n return parsed[index];\n } else if (typeof s.value === 'string') {\n return s.value;\n } else {\n if (!s.value.isFallback) {\n usefulStackCount++;\n } else {\n fallbackIndices.push(index);\n }\n return s.value.stack;\n }\n });\n\n // Using EXPO_DEBUG we can print all stack\n const filtered =\n usefulStackCount && !env.EXPO_DEBUG\n ? symbolicated.filter((_, index) => !fallbackIndices.includes(index))\n : symbolicated;\n\n event('client_log', { level, data: symbolicated });\n logLikeMetro(this.terminal.log.bind(this.terminal), level, null, ...filtered);\n })();\n return;\n }\n }\n\n event('client_log', { level, data });\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, null, ...data);\n }\n\n #captureLog(evt: TerminalReportableEvent) {\n switch (evt.type) {\n case 'bundle_build_started': {\n const entry =\n typeof evt.bundleDetails?.customTransformOptions?.dom === 'string' &&\n evt.bundleDetails.customTransformOptions.dom.includes(path.sep)\n ? evt.bundleDetails.customTransformOptions.dom.replace(/^(\\.?\\.[\\\\/])+/, '')\n : this.#normalizePath(evt.bundleDetails.entryFile);\n return event('bundling:started', {\n id: evt.buildID,\n platform: evt.bundleDetails.platform ?? null,\n environment: evt.bundleDetails.customTransformOptions?.environment ?? null,\n entry,\n });\n }\n case 'unstable_server_log':\n return event('server_log', {\n level: evt.level ?? null,\n data: evt.data ?? null,\n });\n case 'client_log':\n // Handled separately: see this.#onClientLog\n return;\n case 'hmr_client_error':\n case 'cache_write_error':\n case 'cache_read_error':\n return event(evt.type, {\n message: evt.error.message,\n });\n }\n }\n\n #normalizePath<T extends string | null>(dest: T | undefined): T | string {\n return dest != null && path.isAbsolute(dest)\n ? path.relative(this.serverRoot, dest)\n : ((dest || null) as T);\n }\n}\n\n/**\n * Formats an error where the user is attempting to import a module from the Node.js standard library.\n * Exposed for testing.\n *\n * @param error\n * @returns error message or null if not a module resolution error\n */\nexport function formatUsingNodeStandardLibraryError(\n serverRoot: string,\n error: SnippetError\n): string | null {\n if (!error.message) {\n return null;\n }\n const { targetModuleName, originModulePath } = error;\n if (!targetModuleName || !originModulePath) {\n return null;\n }\n const relativePath = path.relative(serverRoot, originModulePath);\n\n const DOCS_PAGE_URL =\n 'https://docs.expo.dev/workflow/using-libraries/#using-third-party-libraries';\n\n if (isNodeStdLibraryModule(targetModuleName)) {\n if (originModulePath.includes('node_modules')) {\n return [\n `The package at \"${chalk.bold(\n relativePath\n )}\" attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n } else {\n return [\n `You attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\" from \"${chalk.bold(relativePath)}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n }\n }\n return `Unable to resolve \"${targetModuleName}\" from \"${relativePath}\"`;\n}\n\nexport function isNodeStdLibraryModule(moduleName: string): boolean {\n return /^node:/.test(moduleName) || NODE_STDLIB_MODULES.includes(moduleName);\n}\n\n/** If the code frame can be found then append it to the existing message. */\nfunction maybeAppendCodeFrame(message: string, rawMessage: string): string {\n const codeFrame = extractCodeFrame(stripMetroInfo(rawMessage));\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\n}\n\n/** Extract fist code frame presented in the error message */\nexport function extractCodeFrame(errorMessage: string): string {\n const codeFrameLine = /^(?:\\s*(?:>?\\s*\\d+\\s*\\||\\s*\\|).*\\n?)+/;\n let wasPreviousLineCodeFrame: boolean | null = null;\n return errorMessage\n .split('\\n')\n .filter((line) => {\n if (wasPreviousLineCodeFrame === false) return false;\n const keep = codeFrameLine.test(stripVTControlCharacters(line));\n if (keep && wasPreviousLineCodeFrame === null) wasPreviousLineCodeFrame = true;\n else if (!keep && wasPreviousLineCodeFrame) wasPreviousLineCodeFrame = false;\n return keep;\n })\n .join('\\n');\n}\n\n/**\n * Remove the Metro cache clearing steps if they exist.\n * In future versions we won't need this.\n * Returns the remaining code frame logs.\n */\nexport function stripMetroInfo(errorMessage: string): string {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return errorMessage;\n }\n const lines = errorMessage.split('\\n');\n const index = lines.findIndex((line) => line.includes('4. Remove the cache'));\n if (index === -1) {\n return errorMessage;\n }\n return lines.slice(index + 1).join('\\n');\n}\n\n/** @returns if the message matches the initial startup log */\nfunction isAppRegistryStartupMessage(body: any[]): boolean {\n return (\n body.length === 1 &&\n (/^Running application \"main\" with appParams:/.test(body[0]) ||\n /^Running \"main\" with \\{/.test(body[0]))\n );\n}\n\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getPlatformTagForBuildDetails(bundleDetails?: BundleDetails | null): string {\n const platform = bundleDetails?.platform ?? null;\n if (platform) {\n const formatted = { ios: 'iOS', android: 'Android', web: 'Web' }[platform] || platform;\n return `${chalk.bold(formatted)} `;\n }\n\n return '';\n}\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getEnvironmentForBuildDetails(bundleDetails?: BundleDetails | null): string {\n // Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.\n const env = bundleDetails?.customTransformOptions?.environment ?? null;\n if (env === 'node') {\n return chalk.bold('λ') + ' ';\n } else if (env === 'react-server') {\n return chalk.bold(`RSC(${getPlatformTagForBuildDetails(bundleDetails).trim()})`) + ' ';\n }\n\n if (\n bundleDetails?.customTransformOptions?.dom &&\n typeof bundleDetails?.customTransformOptions?.dom === 'string'\n ) {\n return chalk.bold(`DOM`) + ' ';\n }\n\n return '';\n}\n"],"names":["MetroTerminalReporter","event","extractCodeFrame","formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","debug","require","events","t","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","TerminalReporter","constructor","serverRoot","terminal","_log","type","data","message","match","env","EXPO_DEBUG","shouldFilterClientLog","level","_getElapsedTime","startTime","process","hrtime","bigint","_getBundleStatusMessage","progress","phase","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","customTransformOptions","dom","includes","path","sep","replace","entryFile","status","color","chalk","green","red","_bundleTimers","get","buildID","time","ms","elapsed","micro","Number","tenthFractionOfMicro","toFixed","cyan","bold","dim","id","total","totalFileCount","plural","reset","ratio","current","transformedFileCount","shouldReduceLogs","filledBar","Math","floor","_progress","bgGreen","repeat","bgWhite","white","padStart","toString","length","dirname","basename","_logInitializing","port","hasReducedPerformance","log","isAppRegistryStartupMessage","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundleBuildFailed","_logBundlingError","error","importStack","nearestImportStack","moduleResolutionError","maybeAppendCodeFrame","stripAnsi","filename","targetModuleName","originModulePath","attachImportStackToRootMessage","snippet","stack","SyntaxError","evt","hasStack","parsed","map","msg","parseErrorStringToObject","symbolicating","p","maybeSymbolicateAndFormatJSErrorStackLogAsync","usefulStackCount","fallbackIndices","symbolicated","Promise","allSettled","s","index","reason","value","isFallback","push","filtered","filter","_","logLikeMetro","bind","entry","environment","dest","isAbsolute","relative","relativePath","DOCS_PAGE_URL","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","codeFrameLine","wasPreviousLineCodeFrame","split","line","keep","stripVTControlCharacters","lines","findIndex","slice","body","formatted","ios","android","web","trim"],"mappings":";;;;;;;;;;;IA2FaA,qBAAqB;eAArBA;;IApDAC,KAAK;eAALA;;IAycGC,g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AsB,qBAArCL,uCAAuCM,GAAG,KAC1C,QAAON,kCAAAA,yCAAAA,cAAeK,sBAAsB,qBAArCL,uCAAuCM,GAAG,MAAK,UACtD;QACA,OAAOQ,gBAAK,CAACc,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI;IAC7B;IAEA,OAAO;AACT"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import type { Terminal } from '@expo/metro/metro-core';\nimport chalk from 'chalk';\nimport path from 'path';\nimport { stripVTControlCharacters } from 'util';\n\nimport { logWarning, TerminalReporter } from './TerminalReporter';\nimport {\n BuildPhase,\n BundleDetails,\n BundleProgress,\n SnippetError,\n TerminalReportableEvent,\n} from './TerminalReporter.types';\nimport { NODE_STDLIB_MODULES } from './externals';\nimport { env } from '../../../utils/env';\nimport { learnMore } from '../../../utils/link';\nimport {\n logLikeMetro,\n maybeSymbolicateAndFormatJSErrorStackLogAsync,\n parseErrorStringToObject,\n} from '../serverLogLikeMetro';\nimport { attachImportStackToRootMessage, nearestImportStack } from './metroErrorInterface';\nimport { events, shouldReduceLogs } from '../../../events';\nimport { stripAnsi } from '../../../utils/ansi';\n\ntype ClientLogLevel =\n | 'trace'\n | 'info'\n | 'error'\n | 'warn'\n | 'log'\n | 'group'\n | 'groupCollapsed'\n | 'groupEnd'\n | 'debug';\n\nconst debug = require('debug')('expo:metro:logger') as typeof console.log;\n\n// prettier-ignore\nexport const event = events('metro', (t) => [\n t.event<'bundling:started', {\n id: string;\n platform: null | string;\n environment: null | string;\n entry: string;\n }>(),\n t.event<'bundling:done', {\n id: string | null;\n ms: number | null;\n total: number;\n }>(),\n t.event<'bundling:failed', {\n id: string | null;\n filename: string | null;\n message: string | null;\n importStack: string | null;\n targetModuleName: string | null;\n originModulePath: string | null;\n }>(),\n t.event<'bundling:progress', {\n id: string | null;\n progress: number;\n current: number;\n total: number;\n }>(),\n t.event<'server_log', {\n level: 'info' | 'warn' | 'error' | null;\n data: string | unknown[] | null;\n }>(),\n t.event<'client_log', {\n level: ClientLogLevel | null;\n data: unknown[] | null;\n }>(),\n t.event<'hmr_client_error', {\n message: string;\n }>(),\n t.event<'cache_write_error', {\n message: string;\n }>(),\n t.event<'cache_read_error', {\n message: string;\n }>(),\n]);\n\nconst MAX_PROGRESS_BAR_CHAR_WIDTH = 16;\nconst DARK_BLOCK_CHAR = '\\u2593';\nconst LIGHT_BLOCK_CHAR = '\\u2591';\n/**\n * Extends the default Metro logger and adds some additional features.\n * Also removes the giant Metro logo from the output.\n */\nexport class MetroTerminalReporter extends TerminalReporter {\n #lastFailedBuildID: string | undefined;\n\n constructor(\n public serverRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n _log(event: TerminalReportableEvent): void {\n this.#captureLog(event);\n switch (event.type) {\n case 'unstable_server_log':\n if (typeof event.data?.[0] === 'string') {\n const message = event.data[0];\n if (message.match(/JavaScript logs have moved/)) {\n // Hide this very loud message from upstream React Native in favor of the note in the terminal UI:\n // The \"› Press j │ open debugger\"\n\n // logger?.info(\n // '\\u001B[1m\\u001B[7m💡 JavaScript logs have moved!\\u001B[22m They can now be ' +\n // 'viewed in React Native DevTools. Tip: Type \\u001B[1mj\\u001B[22m in ' +\n // 'the terminal to open (requires Google Chrome or Microsoft Edge).' +\n // '\\u001B[27m',\n // );\n return;\n }\n\n if (!env.EXPO_DEBUG) {\n // In the context of developing an iOS app or website, the MetroInspectorProxy \"connection\" logs are very confusing.\n // Here we'll hide them behind EXPO_DEBUG or DEBUG=expo:*. In the future we can reformat them to clearly indicate that the \"Connection\" is regarding the debugger.\n // These logs are also confusing because they can say \"connection established\" even when the debugger is not in a usable state. Really they belong in a UI or behind some sort of debug logging.\n if (message.match(/Connection (closed|established|failed|terminated)/i)) {\n // Skip logging.\n return;\n }\n }\n }\n break;\n case 'client_log': {\n if (this.shouldFilterClientLog(event)) {\n return;\n } else if (event.level != null) {\n return this.#onClientLog(event);\n } else {\n break;\n }\n }\n }\n return super._log(event);\n }\n\n // Used for testing\n _getElapsedTime(startTime: bigint): bigint {\n return process.hrtime.bigint() - startTime;\n }\n /**\n * Extends the bundle progress to include the current platform that we're bundling.\n *\n * @returns `iOS path/to/bundle.js ▓▓▓▓▓░░░░░░░░░░░ 36.6% (4790/7922)`\n */\n _getBundleStatusMessage(progress: BundleProgress, phase: BuildPhase): string {\n const env = getEnvironmentForBuildDetails(progress.bundleDetails);\n const platform = env || getPlatformTagForBuildDetails(progress.bundleDetails);\n const inProgress = phase === 'in_progress';\n\n const localPath =\n typeof progress.bundleDetails?.customTransformOptions?.dom === 'string' &&\n progress.bundleDetails.customTransformOptions.dom.includes(path.sep)\n ? progress.bundleDetails.customTransformOptions.dom.replace(/^(\\.?\\.[\\\\/])+/, '')\n : this.#normalizePath(progress.bundleDetails.entryFile);\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundled ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n\n let time: string = '';\n let ms: number | null = null;\n\n if (startTime != null) {\n const elapsed: bigint = this._getElapsedTime(startTime);\n const micro = Number(elapsed) / 1000;\n ms = Number(elapsed) / 1e6;\n // If the milliseconds are < 0.5 then it will display as 0, so we display in microseconds.\n if (ms <= 0.5) {\n const tenthFractionOfMicro = ((micro * 10) / 1000).toFixed(0);\n // Format as microseconds to nearest tenth\n time = chalk.cyan.bold(`0.${tenthFractionOfMicro}ms`);\n } else {\n time = chalk.dim(ms.toFixed(0) + 'ms');\n }\n }\n\n if (phase === 'done') {\n event('bundling:done', {\n id: progress.bundleDetails.buildID ?? null,\n total: progress.totalFileCount,\n ms,\n });\n }\n\n // iOS Bundled 150ms\n const plural = progress.totalFileCount === 1 ? '' : 's';\n return (\n color(platform + status) +\n time +\n chalk.reset.dim(` ${localPath} (${progress.totalFileCount} module${plural})`)\n );\n }\n\n event('bundling:progress', {\n id: progress.bundleDetails.buildID ?? null,\n progress: progress.ratio,\n total: progress.totalFileCount,\n current: progress.transformedFileCount,\n });\n if (shouldReduceLogs()) {\n return '';\n }\n\n const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);\n const _progress = inProgress\n ? chalk.green.bgGreen(DARK_BLOCK_CHAR.repeat(filledBar)) +\n chalk.bgWhite.white(LIGHT_BLOCK_CHAR.repeat(MAX_PROGRESS_BAR_CHAR_WIDTH - filledBar)) +\n chalk.bold(` ${(100 * progress.ratio).toFixed(1).padStart(4)}% `) +\n chalk.dim(\n `(${progress.transformedFileCount\n .toString()\n .padStart(progress.totalFileCount.toString().length)}/${progress.totalFileCount})`\n )\n : '';\n return (\n platform +\n chalk.reset.dim(`${path.dirname(localPath)}${path.sep}`) +\n chalk.bold(path.basename(localPath)) +\n ' ' +\n _progress\n );\n }\n\n _logInitializing(port: number, hasReducedPerformance: boolean): void {\n // Don't print a giant logo...\n if (!shouldReduceLogs()) {\n this.terminal.log(chalk.dim('Starting Metro Bundler') + '\\n');\n }\n }\n\n shouldFilterClientLog(event: { type: 'client_log'; data: unknown[] }): boolean {\n return isAppRegistryStartupMessage(event.data);\n }\n\n shouldFilterBundleEvent(event: TerminalReportableEvent): boolean {\n return 'bundleDetails' in event && event.bundleDetails?.bundleType === 'map';\n }\n\n /** Print the cache clear message. */\n transformCacheReset(): void {\n logWarning(\n this.terminal,\n chalk`Bundler cache is empty, rebuilding {dim (this may take a minute)}`\n );\n }\n\n /** One of the first logs that will be printed */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {\n // this.terminal.log('Dependency graph is loading...');\n if (hasReducedPerformance) {\n // Extends https://github.com/facebook/metro/blob/347b1d7ed87995d7951aaa9fd597c04b06013dac/packages/metro/src/lib/TerminalReporter.js#L283-L290\n this.terminal.log(\n chalk.red(\n [\n 'Metro is operating with reduced performance.',\n 'Fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n /**\n * Workaround to link build ids to bundling errors.\n * This works because `_logBundleBuildFailed` is called before `_logBundlingError` in synchronous manner.\n * https://github.com/facebook/metro/blob/main/packages/metro/src/Server.js#L939-L945\n */\n _logBundleBuildFailed(buildID: string): void {\n this.#lastFailedBuildID = buildID;\n super._logBundleBuildFailed(buildID);\n }\n\n _logBundlingError(error: SnippetError): void {\n const importStack = nearestImportStack(error);\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.serverRoot, error);\n\n if (moduleResolutionError) {\n const message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n event('bundling:failed', {\n id: this.#lastFailedBuildID ?? null,\n message: stripAnsi(message) ?? null,\n importStack: importStack ?? null,\n filename: error.filename ?? null,\n targetModuleName: this.#normalizePath(error.targetModuleName),\n originModulePath: this.#normalizePath(error.originModulePath),\n });\n\n return this.terminal.log(importStack ? `${message}\\n\\n${importStack}` : message);\n } else {\n event('bundling:failed', {\n id: this.#lastFailedBuildID ?? null,\n message: stripAnsi(error.message) ?? null,\n importStack: importStack ?? null,\n filename: error.filename ?? null,\n targetModuleName: error.targetModuleName ?? null,\n originModulePath: error.originModulePath ?? null,\n });\n\n attachImportStackToRootMessage(error, importStack);\n\n // NOTE(@kitten): Metro drops the stack forcefully when it finds a `SyntaxError`. However,\n // this is really unhelpful, since it prevents debugging Babel plugins or reporting bugs\n // in Babel plugins or a transformer entirely\n if (error.snippet == null && error.stack != null && error instanceof SyntaxError) {\n error.message = error.stack;\n delete error.stack;\n }\n\n return super._logBundlingError(error);\n }\n }\n\n #onClientLog(evt: { type: 'client_log'; level?: ClientLogLevel; data: unknown[] }) {\n const { level = 'log', data } = evt;\n if (level === 'warn' || (level as string) === 'error') {\n let hasStack = false;\n const parsed = data.map((msg) => {\n // Quick check to see if an unsymbolicated stack is being logged.\n if (typeof msg === 'string' && msg.includes('.bundle//&platform=')) {\n const stack = parseErrorStringToObject(msg);\n if (stack) {\n hasStack = true;\n }\n return stack;\n }\n return msg;\n });\n\n if (hasStack) {\n (async () => {\n const symbolicating = parsed.map((p) => {\n if (typeof p === 'string') {\n return p;\n } else if (\n p &&\n typeof p === 'object' &&\n 'message' in p &&\n typeof p.message === 'string'\n ) {\n return maybeSymbolicateAndFormatJSErrorStackLogAsync(\n this.serverRoot,\n level,\n p as any\n );\n } else {\n return null;\n }\n });\n\n let usefulStackCount = 0;\n const fallbackIndices: number[] = [];\n const symbolicated = (await Promise.allSettled(symbolicating)).map((s, index) => {\n if (s.status === 'rejected') {\n debug('Error formatting stack', parsed[index], s.reason);\n return parsed[index];\n } else if (!s.value) {\n return parsed[index];\n } else if (typeof s.value === 'string') {\n return s.value;\n } else {\n if (!s.value.isFallback) {\n usefulStackCount++;\n } else {\n fallbackIndices.push(index);\n }\n return s.value.stack;\n }\n });\n\n // Using EXPO_DEBUG we can print all stack\n const filtered =\n usefulStackCount && !env.EXPO_DEBUG\n ? symbolicated.filter((_, index) => !fallbackIndices.includes(index))\n : symbolicated;\n\n event('client_log', { level, data: symbolicated });\n logLikeMetro(this.terminal.log.bind(this.terminal), level, null, ...filtered);\n })();\n return;\n }\n }\n\n event('client_log', { level, data });\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, null, ...data);\n }\n\n #captureLog(evt: TerminalReportableEvent) {\n switch (evt.type) {\n case 'bundle_build_started': {\n const entry =\n typeof evt.bundleDetails?.customTransformOptions?.dom === 'string' &&\n evt.bundleDetails.customTransformOptions.dom.includes(path.sep)\n ? evt.bundleDetails.customTransformOptions.dom.replace(/^(\\.?\\.[\\\\/])+/, '')\n : this.#normalizePath(evt.bundleDetails.entryFile);\n return event('bundling:started', {\n id: evt.buildID,\n platform: evt.bundleDetails.platform ?? null,\n environment: evt.bundleDetails.customTransformOptions?.environment ?? null,\n entry,\n });\n }\n case 'unstable_server_log':\n return event('server_log', {\n level: evt.level ?? null,\n data: evt.data ?? null,\n });\n case 'client_log':\n // Handled separately: see this.#onClientLog\n return;\n case 'hmr_client_error':\n case 'cache_write_error':\n case 'cache_read_error':\n return event(evt.type, {\n message: evt.error.message,\n });\n }\n }\n\n #normalizePath<T extends string | null>(dest: T | undefined): T | string {\n return dest != null && path.isAbsolute(dest)\n ? path.relative(this.serverRoot, dest)\n : ((dest || null) as T);\n }\n}\n\n/**\n * Formats an error where the user is attempting to import a module from the Node.js standard library.\n * Exposed for testing.\n *\n * @param error\n * @returns error message or null if not a module resolution error\n */\nexport function formatUsingNodeStandardLibraryError(\n serverRoot: string,\n error: SnippetError\n): string | null {\n if (!error.message) {\n return null;\n }\n const { targetModuleName, originModulePath } = error;\n if (!targetModuleName || !originModulePath) {\n return null;\n }\n const relativePath = path.relative(serverRoot, originModulePath);\n\n const DOCS_PAGE_URL =\n 'https://docs.expo.dev/workflow/using-libraries/#using-third-party-libraries';\n\n if (isNodeStdLibraryModule(targetModuleName)) {\n if (originModulePath.includes('node_modules')) {\n return [\n `The package at \"${chalk.bold(\n relativePath\n )}\" attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n } else {\n return [\n `You attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\" from \"${chalk.bold(relativePath)}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n }\n }\n return `Unable to resolve \"${targetModuleName}\" from \"${relativePath}\"`;\n}\n\nexport function isNodeStdLibraryModule(moduleName: string): boolean {\n return /^node:/.test(moduleName) || NODE_STDLIB_MODULES.includes(moduleName);\n}\n\n/** If the code frame can be found then append it to the existing message. */\nfunction maybeAppendCodeFrame(message: string, rawMessage: string): string {\n const codeFrame = extractCodeFrame(stripMetroInfo(rawMessage));\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\n}\n\n/** Extract fist code frame presented in the error message */\nexport function extractCodeFrame(errorMessage: string): string {\n const codeFrameLine = /^(?:\\s*(?:>?\\s*\\d+\\s*\\||\\s*\\|).*\\n?)+/;\n let wasPreviousLineCodeFrame: boolean | null = null;\n return errorMessage\n .split('\\n')\n .filter((line) => {\n if (wasPreviousLineCodeFrame === false) return false;\n const keep = codeFrameLine.test(stripVTControlCharacters(line));\n if (keep && wasPreviousLineCodeFrame === null) wasPreviousLineCodeFrame = true;\n else if (!keep && wasPreviousLineCodeFrame) wasPreviousLineCodeFrame = false;\n return keep;\n })\n .join('\\n');\n}\n\n/**\n * Remove the Metro cache clearing steps if they exist.\n * In future versions we won't need this.\n * Returns the remaining code frame logs.\n */\nexport function stripMetroInfo(errorMessage: string): string {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return errorMessage;\n }\n const lines = errorMessage.split('\\n');\n const index = lines.findIndex((line) => line.includes('4. Remove the cache'));\n if (index === -1) {\n return errorMessage;\n }\n return lines.slice(index + 1).join('\\n');\n}\n\n/** @returns if the message matches the initial startup log */\nfunction isAppRegistryStartupMessage(body: any[]): boolean {\n return (\n body.length === 1 &&\n (/^Running application \"main\" with appParams:/.test(body[0]) ||\n /^Running \"main\" with \\{/.test(body[0]))\n );\n}\n\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getPlatformTagForBuildDetails(bundleDetails?: BundleDetails | null): string {\n const platform = bundleDetails?.platform ?? null;\n if (platform) {\n const formatted = { ios: 'iOS', android: 'Android', web: 'Web' }[platform] || platform;\n return `${chalk.bold(formatted)} `;\n }\n\n return '';\n}\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getEnvironmentForBuildDetails(bundleDetails?: BundleDetails | null): string {\n // Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.\n const env = bundleDetails?.customTransformOptions?.environment ?? null;\n if (env === 'node') {\n return chalk.bold('λ') + ' ';\n } else if (env === 'react-server') {\n return chalk.bold(`RSC(${getPlatformTagForBuildDetails(bundleDetails).trim()})`) + ' ';\n }\n\n if (\n bundleDetails?.customTransformOptions?.dom &&\n typeof bundleDetails?.customTransformOptions?.dom === 'string'\n ) {\n return chalk.bold(`DOM`) + ' ';\n }\n\n return '';\n}\n"],"names":["MetroTerminalReporter","event","extractCodeFrame","formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","debug","require","events","t","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","TerminalReporter","constructor","serverRoot","terminal","_log","type","data","message","match","env","EXPO_DEBUG","shouldFilterClientLog","level","_getElapsedTime","startTime","process","hrtime","bigint","_getBundleStatusMessage","progress","phase","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","customTransformOptions","dom","includes","path","sep","replace","entryFile","status","color","chalk","green","red","_bundleTimers","get","buildID","time","ms","elapsed","micro","Number","tenthFractionOfMicro","toFixed","cyan","bold","dim","id","total","totalFileCount","plural","reset","ratio","current","transformedFileCount","shouldReduceLogs","filledBar","Math","floor","_progress","bgGreen","repeat","bgWhite","white","padStart","toString","length","dirname","basename","_logInitializing","port","hasReducedPerformance","log","isAppRegistryStartupMessage","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundleBuildFailed","_logBundlingError","error","importStack","nearestImportStack","moduleResolutionError","maybeAppendCodeFrame","stripAnsi","filename","targetModuleName","originModulePath","attachImportStackToRootMessage","snippet","stack","SyntaxError","evt","hasStack","parsed","map","msg","parseErrorStringToObject","symbolicating","p","maybeSymbolicateAndFormatJSErrorStackLogAsync","usefulStackCount","fallbackIndices","symbolicated","Promise","allSettled","s","index","reason","value","isFallback","push","filtered","filter","_","logLikeMetro","bind","entry","environment","dest","isAbsolute","relative","relativePath","DOCS_PAGE_URL","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","codeFrameLine","wasPreviousLineCodeFrame","split","line","keep","stripVTControlCharacters","lines","findIndex","slice","body","formatted","ios","android","web","trim"],"mappings":";;;;;;;;;;;IA2FaA,qBAAqB;eAArBA;;IApDAC,KAAK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AC,IAAI;IACrF;IAEA,IACEnI,CAAAA,kCAAAA,yCAAAA,cAAeK,sBAAsB,qBAArCL,uCAAuCM,GAAG,KAC1C,QAAON,kCAAAA,yCAAAA,cAAeK,sBAAsB,qBAArCL,uCAAuCM,GAAG,MAAK,UACtD;QACA,OAAOQ,gBAAK,CAACc,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI;IAC7B;IAEA,OAAO;AACT"}
@@ -9,6 +9,9 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
+ event: function() {
13
+ return event;
14
+ },
12
15
  instantiateMetroAsync: function() {
13
16
  return instantiateMetroAsync;
14
17
  },
@@ -89,6 +92,7 @@ const _createDebugMiddleware = require("./debugging/createDebugMiddleware");
89
92
  const _createMetroMiddleware = require("./dev-server/createMetroMiddleware");
90
93
  const _runServerfork = require("./runServer-fork");
91
94
  const _withMetroMultiPlatform = require("./withMetroMultiPlatform");
95
+ const _events = require("../../../events");
92
96
  const _log = require("../../../log");
93
97
  const _env = require("../../../utils/env");
94
98
  const _errors = require("../../../utils/errors");
@@ -101,6 +105,10 @@ function _interop_require_default(obj) {
101
105
  default: obj
102
106
  };
103
107
  }
108
+ const event = (0, _events.events)('metro', (t)=>[
109
+ t.event(),
110
+ t.event()
111
+ ]);
104
112
  function asWritable(input) {
105
113
  return input;
106
114
  }
@@ -127,7 +135,7 @@ class LogRespectingTerminal extends _metrocore().Terminal {
127
135
  // Share one instance of Terminal for all instances of Metro.
128
136
  const terminal = new LogRespectingTerminal(process.stdout);
129
137
  async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, getMetroBundler }) {
130
- var _exp_experiments, _exp_experiments1, _exp_experiments2, _exp_experiments3, _config_resolver, _exp_experiments4, _exp_experiments5, _exp_experiments6;
138
+ var _exp_experiments, _exp_experiments1, _exp_experiments2, _exp_experiments3, _config_resolver, _exp_experiments4, _exp_experiments5;
131
139
  let reportEvent;
132
140
  // We're resolving a monorepo root, higher up than the `projectRoot`. If this
133
141
  // folder is different (presumably a parent) we're in a monorepo
@@ -136,11 +144,12 @@ async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, ge
136
144
  // Autolinking Module Resolution will be enabled by default when we're in a monorepo
137
145
  const autolinkingModuleResolutionEnabled = ((_exp_experiments = exp.experiments) == null ? void 0 : _exp_experiments.autolinkingModuleResolution) ?? isWorkspace;
138
146
  const serverActionsEnabled = ((_exp_experiments1 = exp.experiments) == null ? void 0 : _exp_experiments1.reactServerFunctions) ?? _env.env.EXPO_UNSTABLE_SERVER_FUNCTIONS;
147
+ const serverComponentsEnabled = !!((_exp_experiments2 = exp.experiments) == null ? void 0 : _exp_experiments2.reactServerComponentRoutes);
139
148
  if (serverActionsEnabled) {
140
149
  process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';
141
150
  }
142
151
  // NOTE: Enable all the experimental Metro flags when RSC is enabled.
143
- if (((_exp_experiments2 = exp.experiments) == null ? void 0 : _exp_experiments2.reactServerComponentRoutes) || serverActionsEnabled) {
152
+ if (serverComponentsEnabled || serverActionsEnabled) {
144
153
  process.env.EXPO_USE_METRO_REQUIRE = '1';
145
154
  }
146
155
  if ((_exp_experiments3 = exp.experiments) == null ? void 0 : _exp_experiments3.reactCanary) {
@@ -187,34 +196,36 @@ async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, ge
187
196
  }
188
197
  globalThis.__requireCycleIgnorePatterns = (_config_resolver = config.resolver) == null ? void 0 : _config_resolver.requireCycleIgnorePatterns;
189
198
  if (isExporting) {
190
- var _exp_experiments7;
199
+ var _exp_experiments6;
191
200
  // This token will be used in the asset plugin to ensure the path is correct for writing locally.
192
- asWritable(config.transformer).publicPath = `/assets?export_path=${(((_exp_experiments7 = exp.experiments) == null ? void 0 : _exp_experiments7.baseUrl) ?? '') + '/assets'}`;
201
+ asWritable(config.transformer).publicPath = `/assets?export_path=${(((_exp_experiments6 = exp.experiments) == null ? void 0 : _exp_experiments6.baseUrl) ?? '') + '/assets'}`;
193
202
  } else {
194
203
  asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';
195
204
  }
196
205
  const platformBundlers = (0, _platformBundlers.getPlatformBundlers)(projectRoot, exp);
197
- if ((_exp_experiments4 = exp.experiments) == null ? void 0 : _exp_experiments4.reactCompiler) {
206
+ const reduceLogs = (0, _events.shouldReduceLogs)();
207
+ const reactCompilerEnabled = !!((_exp_experiments4 = exp.experiments) == null ? void 0 : _exp_experiments4.reactCompiler);
208
+ if (!reduceLogs && reactCompilerEnabled) {
198
209
  _log.Log.log(_chalk().default.gray`React Compiler enabled`);
199
210
  }
200
- if (autolinkingModuleResolutionEnabled) {
211
+ if (!reduceLogs && autolinkingModuleResolutionEnabled) {
201
212
  _log.Log.log(_chalk().default.gray`Expo Autolinking module resolution enabled`);
202
213
  }
203
214
  if (_env.env.EXPO_UNSTABLE_TREE_SHAKING && !_env.env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {
204
215
  throw new _errors.CommandError('EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.');
205
216
  }
206
- if (_env.env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {
217
+ if (!reduceLogs && _env.env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {
207
218
  _log.Log.warn(`Experimental bundle optimization is enabled.`);
208
219
  }
209
- if (_env.env.EXPO_UNSTABLE_TREE_SHAKING) {
220
+ if (!reduceLogs && _env.env.EXPO_UNSTABLE_TREE_SHAKING) {
210
221
  _log.Log.warn(`Experimental tree shaking is enabled.`);
211
222
  }
212
- if (_env.env.EXPO_UNSTABLE_LOG_BOX) {
223
+ if (!reduceLogs && _env.env.EXPO_UNSTABLE_LOG_BOX) {
213
224
  _log.Log.warn(`Experimental Expo LogBox is enabled.`);
214
225
  }
215
- if (serverActionsEnabled) {
216
- var _exp_experiments8;
217
- _log.Log.warn(`React Server Functions (beta) are enabled. Route rendering mode: ${((_exp_experiments8 = exp.experiments) == null ? void 0 : _exp_experiments8.reactServerComponentRoutes) ? 'server' : 'client'}`);
226
+ if (!reduceLogs && serverActionsEnabled) {
227
+ var _exp_experiments7;
228
+ _log.Log.warn(`React Server Functions (beta) are enabled. Route rendering mode: ${((_exp_experiments7 = exp.experiments) == null ? void 0 : _exp_experiments7.reactServerComponentRoutes) ? 'server' : 'client'}`);
218
229
  }
219
230
  config = await (0, _withMetroMultiPlatform.withMetroMultiPlatformAsync)(projectRoot, {
220
231
  config,
@@ -224,9 +235,23 @@ async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, ge
224
235
  isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,
225
236
  isExporting,
226
237
  isNamedRequiresEnabled: _env.env.EXPO_USE_METRO_REQUIRE,
227
- isReactServerComponentsEnabled: !!((_exp_experiments6 = exp.experiments) == null ? void 0 : _exp_experiments6.reactServerComponentRoutes),
238
+ isReactServerComponentsEnabled: serverComponentsEnabled,
228
239
  getMetroBundler
229
240
  });
241
+ event('config', {
242
+ serverRoot: event.path(serverRoot),
243
+ projectRoot: event.path(projectRoot),
244
+ exporting: isExporting,
245
+ flags: {
246
+ autolinkingModuleResolution: autolinkingModuleResolutionEnabled,
247
+ serverActions: serverActionsEnabled,
248
+ serverComponents: serverComponentsEnabled,
249
+ reactCompiler: reactCompilerEnabled,
250
+ optimizeGraph: _env.env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH,
251
+ treeshaking: _env.env.EXPO_UNSTABLE_TREE_SHAKING,
252
+ logbox: _env.env.EXPO_UNSTABLE_LOG_BOX
253
+ }
254
+ });
230
255
  return {
231
256
  config,
232
257
  setEventReporter: (logger)=>reportEvent = logger,
@@ -285,13 +310,19 @@ async function instantiateMetroAsync(metroBundler, options, { isExporting, exp =
285
310
  // NOTE(cedric): reset the Atlas file once, and reuse it for static exports
286
311
  resetAtlasFile: isExporting
287
312
  });
288
- const { server, hmrServer, metro } = await (0, _runServerfork.runServer)(metroBundler, metroConfig, {
313
+ const { address, server, hmrServer, metro } = await (0, _runServerfork.runServer)(metroBundler, metroConfig, {
289
314
  host: options.host,
290
315
  websocketEndpoints,
291
316
  watch: !isExporting && isWatchEnabled()
292
317
  }, {
293
318
  mockServer: isExporting
294
319
  });
320
+ event('instantiate', {
321
+ atlas: _env.env.EXPO_ATLAS,
322
+ workers: metroConfig.maxWorkers ?? null,
323
+ host: (address == null ? void 0 : address.address) ?? null,
324
+ port: (address == null ? void 0 : address.port) ?? null
325
+ });
295
326
  // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.
296
327
  const originalTransformFile = metro.getBundler().getBundler().transformFile.bind(metro.getBundler().getBundler());
297
328
  metro.getBundler().getBundler().transformFile = async function(filePath, transformOptions, fileBuffer) {
@@ -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 { Reporter } from '@expo/metro/metro';\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 { InputConfigT, mergeConfig, resolveConfig, type ConfigT } from '@expo/metro/metro-config';\nimport { Terminal } from '@expo/metro/metro-core';\nimport { createStableModuleIdFactory, getDefaultConfig } 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\ninterface LoadMetroConfigOptions {\n maxWorkers?: number;\n port?: number;\n reporter?: Reporter;\n resetCache?: boolean;\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadMetroConfigOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n // We're resolving a monorepo root, higher up than the `projectRoot`. If this\n // folder is different (presumably a parent) we're in a monorepo\n const serverRoot = getMetroServerRoot(projectRoot);\n const isWorkspace = serverRoot !== projectRoot;\n\n // Autolinking Module Resolution will be enabled by default when we're in a monorepo\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? isWorkspace;\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 terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n // NOTE: Allow external tools to override the metro config. This is considered internal and unstable\n const configPath = env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined;\n const resolvedConfig = await resolveConfig(configPath, projectRoot);\n const defaultConfig = getDefaultConfig(projectRoot);\n\n let config: ConfigT = resolvedConfig.isEmpty\n ? defaultConfig\n : await mergeConfig(defaultConfig, resolvedConfig.config);\n\n // Set the watchfolders to include the projectRoot, as Metro assumes this\n // Force-override the reporter\n config = {\n ...config,\n\n // See: `overrideConfigWithArguments` https://github.com/facebook/metro/blob/5059e26/packages/metro-config/src/loadConfig.js#L274-L339\n // Compare to `LoadOptions` type (disregard `reporter` as we don't expose this)\n resetCache: !!options.resetCache,\n maxWorkers: options.maxWorkers ?? config.maxWorkers,\n server: {\n ...config.server,\n port: options.port ?? config.server.port,\n },\n\n watchFolders: !config.watchFolders.includes(config.projectRoot)\n ? [config.projectRoot, ...config.watchFolders]\n : config.watchFolders,\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n // NOTE(@kitten): `useWatchman` is currently enabled by default, but it also disables `forceNodeFilesystemAPI`.\n // If we instead set it to the special value `null`, it gets enables but also bypasses the \"native find\" codepath,\n // which is slower than just using the Node filesystem API\n // See: https://github.com/facebook/metro/blob/b9c243f/packages/metro-file-map/src/index.js#L326\n // See: https://github.com/facebook/metro/blob/b9c243f/packages/metro/src/node-haste/DependencyGraph/createFileMap.js#L109\n if (config.resolver.useWatchman === true) {\n asWritable(config.resolver).useWatchman = null as any;\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 (autolinkingModuleResolutionEnabled) {\n Log.log(chalk.gray`Expo Autolinking module resolution 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\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\ninterface InstantiateMetroConfigOptions extends LoadMetroConfigOptions {\n host?: string;\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: InstantiateMetroConfigOptions,\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 // Get local URL to Metro bundler server (typically configured as 127.0.0.1:8081)\n const serverBaseUrl = metroBundler\n .getUrlCreator()\n .constructUrl({ scheme: 'http', hostType: 'localhost' });\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 serverBaseUrl,\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 const devtoolsWebsocketEndpoints = createDevToolsPluginWebsocketEndpoint();\n Object.assign(websocketEndpoints, devtoolsWebsocketEndpoints);\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 host: options.host,\n websocketEndpoints,\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 resolvedRouterRoot = path.resolve(projectRoot, routerRoot).split(path.sep).join('/');\n const isRouterRoute = path.isAbsolute(filePath) && filePath.startsWith(resolvedRouterRoot);\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","serverRoot","getMetroServerRoot","isWorkspace","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","serverActionsEnabled","reactServerFunctions","env","EXPO_UNSTABLE_SERVER_FUNCTIONS","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","warn","terminalReporter","MetroTerminalReporter","configPath","EXPO_OVERRIDE_METRO_CONFIG","undefined","resolvedConfig","resolveConfig","defaultConfig","getDefaultConfig","isEmpty","mergeConfig","resetCache","maxWorkers","server","port","watchFolders","includes","reporter","update","event","resolver","useWatchman","globalThis","__requireCycleIgnorePatterns","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","serverBaseUrl","getUrlCreator","constructUrl","scheme","hostType","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","devtoolsWebsocketEndpoints","createDevToolsPluginWebsocketEndpoint","attachAtlasAsync","resetAtlasFile","hmrServer","runServer","host","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","resolvedRouterRoot","resolve","isRouterRoute","isAbsolute","startsWith","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;IA8OsBA,qBAAqB;eAArBA;;IAuSNC,cAAc;eAAdA;;IA7bMC,oBAAoB;eAApBA;;;;yBAxFqB;;;;;;;yBACR;;;;;;;gEAMD;;;;;;;gEAEF;;;;;;;yBACuC;;;;;;;yBAC9C;;;;;;;yBACqC;;;;;;;gEAC5C;;;;;;;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,IAAI,CAACC,KAAK;QACZ;QAEAC,QAAQJ,GAAG,GAAGH;QACdO,QAAQC,IAAI,GAAGR;IACjB;AACF;AAEA,6DAA6D;AAC7D,MAAMS,WAAW,IAA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ACyE,gBAAgB;IACjE;IAEA,OAAO5E;AACT;AAMO,SAASjI;IACd,IAAIoC,QAAG,CAAC0K,EAAE,EAAE;QACVrK,QAAG,CAAC7B,GAAG,CACL8D,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAACtC,QAAG,CAAC0K,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 { Reporter } from '@expo/metro/metro';\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 { InputConfigT, mergeConfig, resolveConfig, type ConfigT } from '@expo/metro/metro-config';\nimport { Terminal } from '@expo/metro/metro-core';\nimport { createStableModuleIdFactory, getDefaultConfig } 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 { events, shouldReduceLogs } from '../../../events';\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// prettier-ignore\nexport const event = events('metro', (t) => [\n t.event<'config', {\n serverRoot: string;\n projectRoot: string;\n exporting: boolean;\n flags: {\n autolinkingModuleResolution: boolean;\n serverActions: boolean;\n serverComponents: boolean;\n reactCompiler: boolean;\n optimizeGraph?: boolean;\n treeshaking?: boolean;\n logbox?: boolean;\n };\n }>(),\n t.event<'instantiate', {\n atlas: boolean;\n workers: number | null;\n host: string | null;\n port: number | null;\n }>(),\n]);\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\ninterface LoadMetroConfigOptions {\n maxWorkers?: number;\n port?: number;\n reporter?: Reporter;\n resetCache?: boolean;\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadMetroConfigOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n // We're resolving a monorepo root, higher up than the `projectRoot`. If this\n // folder is different (presumably a parent) we're in a monorepo\n const serverRoot = getMetroServerRoot(projectRoot);\n const isWorkspace = serverRoot !== projectRoot;\n\n // Autolinking Module Resolution will be enabled by default when we're in a monorepo\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? isWorkspace;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n const serverComponentsEnabled = !!exp.experiments?.reactServerComponentRoutes;\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 (serverComponentsEnabled || 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 terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n // NOTE: Allow external tools to override the metro config. This is considered internal and unstable\n const configPath = env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined;\n const resolvedConfig = await resolveConfig(configPath, projectRoot);\n const defaultConfig = getDefaultConfig(projectRoot);\n\n let config: ConfigT = resolvedConfig.isEmpty\n ? defaultConfig\n : await mergeConfig(defaultConfig, resolvedConfig.config);\n\n // Set the watchfolders to include the projectRoot, as Metro assumes this\n // Force-override the reporter\n config = {\n ...config,\n\n // See: `overrideConfigWithArguments` https://github.com/facebook/metro/blob/5059e26/packages/metro-config/src/loadConfig.js#L274-L339\n // Compare to `LoadOptions` type (disregard `reporter` as we don't expose this)\n resetCache: !!options.resetCache,\n maxWorkers: options.maxWorkers ?? config.maxWorkers,\n server: {\n ...config.server,\n port: options.port ?? config.server.port,\n },\n\n watchFolders: !config.watchFolders.includes(config.projectRoot)\n ? [config.projectRoot, ...config.watchFolders]\n : config.watchFolders,\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n // NOTE(@kitten): `useWatchman` is currently enabled by default, but it also disables `forceNodeFilesystemAPI`.\n // If we instead set it to the special value `null`, it gets enables but also bypasses the \"native find\" codepath,\n // which is slower than just using the Node filesystem API\n // See: https://github.com/facebook/metro/blob/b9c243f/packages/metro-file-map/src/index.js#L326\n // See: https://github.com/facebook/metro/blob/b9c243f/packages/metro/src/node-haste/DependencyGraph/createFileMap.js#L109\n if (config.resolver.useWatchman === true) {\n asWritable(config.resolver).useWatchman = null as any;\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 const reduceLogs = shouldReduceLogs();\n\n const reactCompilerEnabled = !!exp.experiments?.reactCompiler;\n if (!reduceLogs && reactCompilerEnabled) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (!reduceLogs && autolinkingModuleResolutionEnabled) {\n Log.log(chalk.gray`Expo Autolinking module resolution 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 (!reduceLogs && env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n\n if (!reduceLogs && 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: serverComponentsEnabled,\n getMetroBundler,\n });\n\n event('config', {\n serverRoot: event.path(serverRoot),\n projectRoot: event.path(projectRoot),\n exporting: isExporting,\n flags: {\n autolinkingModuleResolution: autolinkingModuleResolutionEnabled,\n serverActions: serverActionsEnabled,\n serverComponents: serverComponentsEnabled,\n reactCompiler: reactCompilerEnabled,\n optimizeGraph: env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH,\n treeshaking: env.EXPO_UNSTABLE_TREE_SHAKING,\n logbox: env.EXPO_UNSTABLE_LOG_BOX,\n },\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\ninterface InstantiateMetroConfigOptions extends LoadMetroConfigOptions {\n host?: string;\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: InstantiateMetroConfigOptions,\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 // Get local URL to Metro bundler server (typically configured as 127.0.0.1:8081)\n const serverBaseUrl = metroBundler\n .getUrlCreator()\n .constructUrl({ scheme: 'http', hostType: 'localhost' });\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 serverBaseUrl,\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 const devtoolsWebsocketEndpoints = createDevToolsPluginWebsocketEndpoint();\n Object.assign(websocketEndpoints, devtoolsWebsocketEndpoints);\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 { address, server, hmrServer, metro } = await runServer(\n metroBundler,\n metroConfig,\n {\n host: options.host,\n websocketEndpoints,\n watch: !isExporting && isWatchEnabled(),\n },\n {\n mockServer: isExporting,\n }\n );\n\n event('instantiate', {\n atlas: env.EXPO_ATLAS,\n workers: metroConfig.maxWorkers ?? null,\n host: address?.address ?? null,\n port: address?.port ?? null,\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 resolvedRouterRoot = path.resolve(projectRoot, routerRoot).split(path.sep).join('/');\n const isRouterRoute = path.isAbsolute(filePath) && filePath.startsWith(resolvedRouterRoot);\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":["event","instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","events","t","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","serverRoot","getMetroServerRoot","isWorkspace","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","serverActionsEnabled","reactServerFunctions","env","EXPO_UNSTABLE_SERVER_FUNCTIONS","serverComponentsEnabled","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","warn","terminalReporter","MetroTerminalReporter","configPath","EXPO_OVERRIDE_METRO_CONFIG","undefined","resolvedConfig","resolveConfig","defaultConfig","getDefaultConfig","isEmpty","mergeConfig","resetCache","maxWorkers","server","port","watchFolders","includes","reporter","update","resolver","useWatchman","globalThis","__requireCycleIgnorePatterns","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reduceLogs","shouldReduceLogs","reactCompilerEnabled","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","path","exporting","flags","serverActions","serverComponents","optimizeGraph","treeshaking","logbox","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","serverBaseUrl","getUrlCreator","constructUrl","scheme","hostType","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","devtoolsWebsocketEndpoints","createDevToolsPluginWebsocketEndpoint","attachAtlasAsync","resetAtlasFile","address","hmrServer","runServer","host","watch","mockServer","atlas","EXPO_ATLAS","workers","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","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","resolvedRouterRoot","resolve","isRouterRoute","isAbsolute","startsWith","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;IAmCaA,KAAK;eAALA;;IAqPSC,qBAAqB;eAArBA;;IA8SNC,cAAc;eAAdA;;IArdMC,oBAAoB;eAApBA;;;;yBAjHqB;;;;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C/I,CAAE3E,CAAAA,SAASiE,KAAK,CAAC,0BAA0BjE,SAASiE,KAAK,CAAC,yBAAwB,GAClF;QACA,OAAOhE,iBAAiBG,sBAAsB,CAACuE,WAAW;IAC5D;IAEA,IACE1E,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyC2E,gBAAgB,KACzD,2FAA2F;IAC3F,CAAC5E,SAASiE,KAAK,CAAC,8BAChB;QACA,OAAOhE,iBAAiBG,sBAAsB,CAACwE,gBAAgB;IACjE;IAEA,OAAO3E;AACT;AAMO,SAASlJ;IACd,IAAIsC,QAAG,CAACwL,EAAE,EAAE;QACVlL,QAAG,CAAC9B,GAAG,CACLiE,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAACzC,QAAG,CAACwL,EAAE;AAChB"}
@@ -68,7 +68,7 @@ function _interop_require_default(obj) {
68
68
  default: obj
69
69
  };
70
70
  }
71
- const runServer = async (metroBundler, config, { hasReducedPerformance = false, host, onError, onReady, secureServerOptions, waitForBundler = false, websocketEndpoints = {}, watch }, { mockServer })=>{
71
+ const runServer = async (_metroBundler, config, { hasReducedPerformance = false, host, onError, onReady, secureServerOptions, waitForBundler = false, websocketEndpoints = {}, watch }, { mockServer })=>{
72
72
  // await earlyPortCheck(host, config.server.port);
73
73
  // if (secure != null || secureCert != null || secureKey != null) {
74
74
  // // eslint-disable-next-line no-console
@@ -135,6 +135,7 @@ const runServer = async (metroBundler, config, { hasReducedPerformance = false,
135
135
  };
136
136
  if (mockServer) {
137
137
  return {
138
+ address: null,
138
139
  server: httpServer,
139
140
  hmrServer: null,
140
141
  metro: metroServer
@@ -164,7 +165,9 @@ const runServer = async (metroBundler, config, { hasReducedPerformance = false,
164
165
  socket.destroy();
165
166
  }
166
167
  });
168
+ const address = httpServer.address();
167
169
  resolve({
170
+ address: address && typeof address === 'object' ? address : null,
168
171
  server: httpServer,
169
172
  hmrServer,
170
173
  metro: metroServer
@@ -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 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 { getRunningProcess } =\n require('../../../utils/getRunningProcess') as typeof import('../../../utils/getRunningProcess');\n getRunningProcess(config.server.port).then((info) => {\n if (info) {\n Log.error(\n `Port ${config.server.port} is busy running ${info.command} in: ${info.directory}`\n );\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","getRunningProcess","require","server","port","then","info","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;;;;;+BAiB1CA;;;eAAAA;;;;yBAhB2B;;;;;;;gEAEsB;;;;;;;gEAE5B;;;;;;;gEAEf;;;;;;;gEACF;;;;;;;gEACC;;;;;;;yBACI;;;;;;qBAIF;;;;;;AAGb,MAAMA,YAAY,OACvBC,cACAC,QACA,EACEC,wBAAwB,KAAK,EAC7BC,IAAI,EACJC,OAAO,EACPC,OAAO,EACPC,mBAAmB,EACnBC,iBAAiB,KAAK,EACtBC,qBAAqB,CAAC,CAAC,EACvBC,KAAK,EACY,EACnB,EACEC,UAAU,EAIX;IAMD,kDAAkD;IAElD,mEAAmE;IACnE,2CAA2C;IAC3C,kBAAkB;IAClB,iDAAiD;IACjD,mFAAmF;IACnF,6EAA6E;IAC7E,6C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,OAAOC,MAAM,CAACnC,oBAA0C;YAC7EiC,SAASL,KAAK;YACdK,SAASG,OAAO,CAACC,OAAO,CAAC,CAACC,SAAWA,OAAOC,SAAS;QACvD;QAEA,oCAAoC;QACpC,IAAI,CAACC,mBAAmB;QACxB,OAAO,IAAI;IACb;IAEA,IAAItC,YAAY;QACd,OAAO;YAAEiB,QAAQT;YAAY+B,WAAW;YAAMC,OAAOrC;QAAY;IACnE;IAEA,OAAO,IAAIsC,QAIR,CAACC,SAASC;QACXnC,WAAWI,EAAE,CAAC,SAAS,CAACC;YACtB8B,OAAO9B;QACT;QAEAL,WAAWoC,MAAM,CAACrD,OAAO0B,MAAM,CAACC,IAAI,EAAEzB,MAAM;YAC1C,IAAIE,SAAS;gBACXA,QAAQa;YACV;YAEA,MAAM+B,YAAY,IAAIM,CAAAA,YAAa,SAAC,CAClC1C,YAAY2C,UAAU,IACtB3C,YAAY4C,iBAAiB,IAC7BxD;YAGFyC,OAAOgB,MAAM,CAAClD,oBAAoB;gBAChC,QAAQmD,IAAAA,gCAAqB,EAAC;oBAC5BC,iBAAiBX;gBACnB;YACF;YAEA/B,WAAWI,EAAE,CAAC,WAAW,CAACuC,SAASC,QAAQC;gBACzC,MAAM,EAAEC,QAAQ,EAAE,GAAGC,IAAAA,YAAK,EAACJ,QAAQK,GAAG;gBACtC,IAAIF,YAAY,QAAQxD,kBAAkB,CAACwD,SAAS,EAAE;oBACpDxD,kBAAkB,CAACwD,SAAS,CAACG,aAAa,CAACN,SAASC,QAAQC,MAAM,CAACK;wBACjE5D,kBAAkB,CAACwD,SAAS,CAACK,IAAI,CAAC,cAAcD,IAAIP;oBACtD;gBACF,OAAO;oBACLC,OAAOQ,OAAO;gBAChB;YACF;YAEAlB,QAAQ;gBAAEzB,QAAQT;gBAAY+B;gBAAWC,OAAOrC;YAAY;QAC9D;IACF;AACF"}
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 type { AddressInfo } from 'net';\nimport { parse } from 'url';\nimport type { WebSocketServer } from 'ws';\n\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { Log } from '../../../log';\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 address: AddressInfo | null;\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 { getRunningProcess } =\n require('../../../utils/getRunningProcess') as typeof import('../../../utils/getRunningProcess');\n getRunningProcess(config.server.port).then((info) => {\n if (info) {\n Log.error(\n `Port ${config.server.port} is busy running ${info.command} in: ${info.directory}`\n );\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 { address: null, server: httpServer, hmrServer: null, metro: metroServer };\n }\n\n return new Promise((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 const address = httpServer.address();\n\n resolve({\n address: address && typeof address === 'object' ? address : null,\n server: httpServer,\n hmrServer,\n metro: metroServer,\n });\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","getRunningProcess","require","server","port","then","info","Log","command","directory","timeout","originalClose","close","bind","closeHttpServer","callback","err","endpoint","Object","values","clients","forEach","client","terminate","closeAllConnections","address","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;;;;;;;yBAEI;;;;;;qBAIF;;;;;;AAGb,MAAMA,YAAY,OACvBC,eACAC,QACA,EACEC,wBAAwB,KAAK,EAC7BC,IAAI,EACJC,OAAO,EACPC,OAAO,EACPC,mBAAmB,EACnBC,iBAAiB,KAAK,EACtBC,qBAAqB,CAAC,CAAC,EACvBC,KAAK,EACY,EACnB,EACEC,UAAU,EAIX;IAOD,kDAAkD;IAElD,mEAAmE;IACnE,2CAA2C;IAC3C,kBAAkB;IAClB,iDAAiD;IACjD,mFAAmF;IACnF,6EAA6E;IAC7E,6CAA6C;IAC7C,OAAO;IACP,IAAI;IAEJ,MAAM,EAA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