@expo/cli 0.17.4 → 0.17.6

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 (36) hide show
  1. package/build/bin/cli +2 -2
  2. package/build/src/export/embed/exportEmbedAsync.js +1 -0
  3. package/build/src/export/embed/exportEmbedAsync.js.map +1 -1
  4. package/build/src/export/exportApp.js +5 -1
  5. package/build/src/export/exportApp.js.map +1 -1
  6. package/build/src/export/fork-bundleAsync.js +3 -1
  7. package/build/src/export/fork-bundleAsync.js.map +1 -1
  8. package/build/src/export/index.js +2 -0
  9. package/build/src/export/index.js.map +1 -1
  10. package/build/src/export/resolveOptions.js +1 -0
  11. package/build/src/export/resolveOptions.js.map +1 -1
  12. package/build/src/export/saveAssets.js +0 -24
  13. package/build/src/export/saveAssets.js.map +1 -1
  14. package/build/src/start/server/AsyncNgrok.js +1 -5
  15. package/build/src/start/server/AsyncNgrok.js.map +1 -1
  16. package/build/src/start/server/UrlCreator.js +2 -2
  17. package/build/src/start/server/UrlCreator.js.map +1 -1
  18. package/build/src/start/server/getStaticRenderFunctions.js +5 -12
  19. package/build/src/start/server/getStaticRenderFunctions.js.map +1 -1
  20. package/build/src/start/server/metro/MetroBundlerDevServer.js +4 -2
  21. package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
  22. package/build/src/start/server/metro/MetroTerminalReporter.js +3 -3
  23. package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
  24. package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js +2 -1
  25. package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js.map +1 -1
  26. package/build/src/start/server/middleware/ManifestMiddleware.js +8 -5
  27. package/build/src/start/server/middleware/ManifestMiddleware.js.map +1 -1
  28. package/build/src/start/server/middleware/metroOptions.js +22 -10
  29. package/build/src/start/server/middleware/metroOptions.js.map +1 -1
  30. package/build/src/start/server/serverLogLikeMetro.js +147 -0
  31. package/build/src/start/server/serverLogLikeMetro.js.map +1 -0
  32. package/build/src/start/server/type-generation/__typetests__/fixtures/basic.js.map +1 -1
  33. package/build/src/utils/analytics/rudderstackClient.js +2 -2
  34. package/build/src/utils/createFileTransform.js +1 -0
  35. package/build/src/utils/createFileTransform.js.map +1 -1
  36. package/package.json +3 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { Terminal } from 'metro-core';\nimport path from 'path';\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 { learnMore } from '../../../utils/link';\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 constructor(\n public projectRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n // Used for testing\n _getElapsedTime(startTime: number): number {\n return Date.now() - 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 = progress.bundleDetails.entryFile.startsWith(path.sep)\n ? path.relative(this.projectRoot, progress.bundleDetails.entryFile)\n : progress.bundleDetails.entryFile;\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundling complete ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n const time = startTime != null ? chalk.dim(this._getElapsedTime(startTime) + 'ms') : '';\n // iOS Bundling complete 150ms\n return color(platform + status) + time + chalk.reset.dim(' (' + localPath + ')');\n }\n\n const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);\n\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\n return (\n platform +\n chalk.reset.dim(`${path.dirname(localPath)}/`) +\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('Starting Metro Bundler');\n }\n\n shouldFilterClientLog(event: {\n type: 'client_log';\n level: 'trace' | 'info' | 'warn' | 'log' | 'group' | 'groupCollapsed' | 'groupEnd' | 'debug';\n data: unknown[];\n }): 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 'Please fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n _logBundlingError(error: SnippetError): void {\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.projectRoot, error);\n const cause = error.cause as undefined | { _expoImportStack?: string };\n if (moduleResolutionError) {\n let message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n if (cause?._expoImportStack) {\n message += `\\n\\n${cause?._expoImportStack}`;\n }\n return this.terminal.log(message);\n }\n if (cause?._expoImportStack) {\n error.message += `\\n\\n${cause._expoImportStack}`;\n }\n return super._logBundlingError(error);\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 projectRoot: 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(projectRoot, 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 = stripMetroInfo(rawMessage);\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\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 | null {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return null;\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 null;\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('Server')} `;\n }\n\n return '';\n}\n"],"names":["formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","MetroTerminalReporter","TerminalReporter","constructor","projectRoot","terminal","_getElapsedTime","startTime","Date","now","_getBundleStatusMessage","progress","phase","env","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","entryFile","startsWith","path","sep","relative","status","color","chalk","green","red","_bundleTimers","get","buildID","time","dim","reset","filledBar","Math","floor","ratio","_progress","bgGreen","repeat","bgWhite","white","bold","toFixed","padStart","transformedFileCount","toString","totalFileCount","length","dirname","basename","_logInitializing","port","hasReducedPerformance","log","shouldFilterClientLog","event","isAppRegistryStartupMessage","data","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundlingError","error","moduleResolutionError","cause","message","maybeAppendCodeFrame","_expoImportStack","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","includes","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","lines","split","index","findIndex","line","slice","body","formatted","ios","android","web","customTransformOptions","environment"],"mappings":"AAAA;;;;QAiJgBA,mCAAmC,GAAnCA,mCAAmC;QAwCnCC,sBAAsB,GAAtBA,sBAAsB;QAkBtBC,cAAc,GAAdA,cAAc;AA3MZ,IAAA,MAAO,kCAAP,OAAO,EAAA;AAER,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEsB,IAAA,iBAAoB,WAApB,oBAAoB,CAAA;AAQ7B,IAAA,UAAa,WAAb,aAAa,CAAA;AACvB,IAAA,KAAqB,WAArB,qBAAqB,CAAA;;;;;;AAE/C,MAAMC,2BAA2B,GAAG,EAAE,AAAC;AACvC,MAAMC,eAAe,GAAG,QAAQ,AAAC;AACjC,MAAMC,gBAAgB,GAAG,QAAQ,AAAC;AAK3B,MAAMC,qBAAqB,SAASC,iBAAgB,iBAAA;IACzDC,YACSC,WAAmB,EAC1BC,QAAkB,CAClB;QACA,KAAK,CAACA,QAAQ,CAAC,CAAC;aAHTD,WAAmB,GAAnBA,WAAmB;KAI3B;IAED,mBAAmB;IACnBE,eAAe,CAACC,SAAiB,EAAU;QACzC,OAAOC,IAAI,CAACC,GAAG,EAAE,GAAGF,SAAS,CAAC;KAC/B;IACD;;;;KAIG,CACHG,uBAAuB,CAACC,QAAwB,EAAEC,KAAiB,EAAU;QAC3E,MAAMC,GAAG,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CAAC,CAAC,CAAC,CAAC;KACnC;IAED,OAAO,EAAE,CAAC;CACX"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { Terminal } from 'metro-core';\nimport path from 'path';\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 { learnMore } from '../../../utils/link';\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 constructor(\n public projectRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n // Used for testing\n _getElapsedTime(startTime: number): number {\n return Date.now() - 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 = progress.bundleDetails.entryFile.startsWith(path.sep)\n ? path.relative(this.projectRoot, progress.bundleDetails.entryFile)\n : 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 const time = startTime != null ? chalk.dim(this._getElapsedTime(startTime) + 'ms') : '';\n // iOS Bundled 150ms\n return color(platform + status) + time + chalk.reset.dim(' (' + localPath + ')');\n }\n\n const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);\n\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\n return (\n platform +\n chalk.reset.dim(`${path.dirname(localPath)}/`) +\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('Starting Metro Bundler');\n }\n\n shouldFilterClientLog(event: {\n type: 'client_log';\n level: 'trace' | 'info' | 'warn' | 'log' | 'group' | 'groupCollapsed' | 'groupEnd' | 'debug';\n data: unknown[];\n }): 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 'Please fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n _logBundlingError(error: SnippetError): void {\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.projectRoot, error);\n const cause = error.cause as undefined | { _expoImportStack?: string };\n if (moduleResolutionError) {\n let message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n if (cause?._expoImportStack) {\n message += `\\n\\n${cause?._expoImportStack}`;\n }\n return this.terminal.log(message);\n }\n if (cause?._expoImportStack) {\n error.message += `\\n\\n${cause._expoImportStack}`;\n }\n return super._logBundlingError(error);\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 projectRoot: 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(projectRoot, 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 = stripMetroInfo(rawMessage);\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\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 | null {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return null;\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 null;\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 }\n\n return '';\n}\n"],"names":["formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","MetroTerminalReporter","TerminalReporter","constructor","projectRoot","terminal","_getElapsedTime","startTime","Date","now","_getBundleStatusMessage","progress","phase","env","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","entryFile","startsWith","path","sep","relative","status","color","chalk","green","red","_bundleTimers","get","buildID","time","dim","reset","filledBar","Math","floor","ratio","_progress","bgGreen","repeat","bgWhite","white","bold","toFixed","padStart","transformedFileCount","toString","totalFileCount","length","dirname","basename","_logInitializing","port","hasReducedPerformance","log","shouldFilterClientLog","event","isAppRegistryStartupMessage","data","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundlingError","error","moduleResolutionError","cause","message","maybeAppendCodeFrame","_expoImportStack","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","includes","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","lines","split","index","findIndex","line","slice","body","formatted","ios","android","web","customTransformOptions","environment"],"mappings":"AAAA;;;;QAiJgBA,mCAAmC,GAAnCA,mCAAmC;QAwCnCC,sBAAsB,GAAtBA,sBAAsB;QAkBtBC,cAAc,GAAdA,cAAc;AA3MZ,IAAA,MAAO,kCAAP,OAAO,EAAA;AAER,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEsB,IAAA,iBAAoB,WAApB,oBAAoB,CAAA;AAQ7B,IAAA,UAAa,WAAb,aAAa,CAAA;AACvB,IAAA,KAAqB,WAArB,qBAAqB,CAAA;;;;;;AAE/C,MAAMC,2BAA2B,GAAG,EAAE,AAAC;AACvC,MAAMC,eAAe,GAAG,QAAQ,AAAC;AACjC,MAAMC,gBAAgB,GAAG,QAAQ,AAAC;AAK3B,MAAMC,qBAAqB,SAASC,iBAAgB,iBAAA;IACzDC,YACSC,WAAmB,EAC1BC,QAAkB,CAClB;QACA,KAAK,CAACA,QAAQ,CAAC,CAAC;aAHTD,WAAmB,GAAnBA,WAAmB;KAI3B;IAED,mBAAmB;IACnBE,eAAe,CAACC,SAAiB,EAAU;QACzC,OAAOC,IAAI,CAACC,GAAG,EAAE,GAAGF,SAAS,CAAC;KAC/B;IACD;;;;KAIG,CACHG,uBAAuB,CAACC,QAAwB,EAAEC,KAAiB,EAAU;QAC3E,MAAMC,GAAG,GAAGC,6BAA6B,CAACH,QAAQ,CAACI,aAAa,CAAC,AAAC;QAClE,MAAMC,QAAQ,GAAGH,GAAG,IAAII,6BAA6B,CAACN,QAAQ,CAACI,aAAa,CAAC,AAAC;QAC9E,M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IAAI,CAACW,IAAI,CAAC,CAAC,CAAC,CAAC,IAC1D,0BAA0BX,IAAI,CAACW,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAC1C;CACH;AAED,kEAAkE,CAClE,SAAS5E,6BAA6B,CAACF,aAAoC,EAAU;QAClEA,GAAuB;IAAxC,MAAMC,QAAQ,GAAGD,CAAAA,GAAuB,GAAvBA,aAAa,QAAU,GAAvBA,KAAAA,CAAuB,GAAvBA,aAAa,CAAEC,QAAQ,YAAvBD,GAAuB,GAAI,IAAI,AAAC;IACjD,IAAIC,QAAQ,EAAE;QACZ,MAAM8E,SAAS,GAAG;YAAEC,GAAG,EAAE,KAAK;YAAEC,OAAO,EAAE,SAAS;YAAEC,GAAG,EAAE,KAAK;SAAE,CAACjF,QAAQ,CAAC,IAAIA,QAAQ,AAAC;QACvF,OAAO,CAAC,EAAEW,MAAK,QAAA,CAACkB,IAAI,CAACiD,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;KACpC;IAED,OAAO,EAAE,CAAC;CACX;AACD,kEAAkE,CAClE,SAAShF,6BAA6B,CAACC,aAAoC,EAAU;QAEvEA,GAAqC;QAArCA,IAAkD;IAD9D,iGAAiG;IACjG,MAAMF,GAAG,GAAGE,CAAAA,IAAkD,GAAlDA,aAAa,QAAwB,GAArCA,KAAAA,CAAqC,GAArCA,CAAAA,GAAqC,GAArCA,aAAa,CAAEmF,sBAAsB,SAAA,GAArCnF,KAAAA,CAAqC,GAArCA,GAAqC,CAAEoF,WAAW,AAAb,YAArCpF,IAAkD,GAAI,IAAI,AAAC;IACvE,IAAIF,GAAG,KAAK,MAAM,EAAE;QAClB,OAAOc,MAAK,QAAA,CAACkB,IAAI,CAAC,QAAG,CAAC,GAAG,GAAG,CAAC;KAC9B;IAED,OAAO,EAAE,CAAC;CACX"}
@@ -70,7 +70,8 @@ class ExpoGoManifestHandlerMiddleware extends _manifestMiddleware.ManifestMiddle
70
70
  responseContentType,
71
71
  platform,
72
72
  expectSignature: expectSignature ? String(expectSignature) : null,
73
- hostname: (0, _url).stripPort(req.headers["host"])
73
+ hostname: (0, _url).stripPort(req.headers["host"]),
74
+ protocol: req.headers["x-forwarded-proto"]
74
75
  };
75
76
  }
76
77
  getDefaultResponseHeaders() {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/middleware/ExpoGoManifestHandlerMiddleware.ts"],"sourcesContent":["import { ExpoUpdatesManifest } from '@expo/config';\nimport { Updates } from '@expo/config-plugins';\nimport accepts from 'accepts';\nimport crypto from 'crypto';\nimport FormData from 'form-data';\nimport { serializeDictionary, Dictionary } from 'structured-headers';\n\nimport { ManifestMiddleware, ManifestRequestInfo } from './ManifestMiddleware';\nimport { assertRuntimePlatform, parsePlatformHeader } from './resolvePlatform';\nimport { ServerHeaders, ServerRequest } from './server.types';\nimport UserSettings from '../../../api/user/UserSettings';\nimport { ANONYMOUS_USERNAME } from '../../../api/user/user';\nimport { logEventAsync } from '../../../utils/analytics/rudderstackClient';\nimport {\n CodeSigningInfo,\n getCodeSigningInfoAsync,\n signManifestString,\n} from '../../../utils/codesigning';\nimport { CommandError } from '../../../utils/errors';\nimport { stripPort } from '../../../utils/url';\n\nconst debug = require('debug')('expo:start:server:middleware:ExpoGoManifestHandlerMiddleware');\n\nexport enum ResponseContentType {\n TEXT_PLAIN,\n APPLICATION_JSON,\n APPLICATION_EXPO_JSON,\n MULTIPART_MIXED,\n}\n\ninterface ExpoGoManifestRequestInfo extends ManifestRequestInfo {\n responseContentType: ResponseContentType;\n expectSignature: string | null;\n}\n\nexport class ExpoGoManifestHandlerMiddleware extends ManifestMiddleware<ExpoGoManifestRequestInfo> {\n public getParsedHeaders(req: ServerRequest): ExpoGoManifestRequestInfo {\n let platform = parsePlatformHeader(req);\n\n if (!platform) {\n debug(\n `No \"expo-platform\" header or \"platform\" query parameter specified. Falling back to \"ios\".`\n );\n platform = 'ios';\n }\n\n assertRuntimePlatform(platform);\n\n // Expo Updates clients explicitly accept \"multipart/mixed\" responses while browsers implicitly\n // accept them with \"accept: */*\". To make it easier to debug manifest responses by visiting their\n // URLs in a browser, we denote the response as \"text/plain\" if the user agent appears not to be\n // an Expo Updates client.\n const accept = accepts(req);\n const acceptedType = accept.types([\n 'unknown/unknown',\n 'multipart/mixed',\n 'application/json',\n 'application/expo+json',\n 'text/plain',\n ]);\n\n let responseContentType;\n switch (acceptedType) {\n case 'multipart/mixed':\n responseContentType = ResponseContentType.MULTIPART_MIXED;\n break;\n case 'application/json':\n responseContentType = ResponseContentType.APPLICATION_JSON;\n break;\n case 'application/expo+json':\n responseContentType = ResponseContentType.APPLICATION_EXPO_JSON;\n break;\n default:\n responseContentType = ResponseContentType.TEXT_PLAIN;\n break;\n }\n\n const expectSignature = req.headers['expo-expect-signature'];\n\n return {\n responseContentType,\n platform,\n expectSignature: expectSignature ? String(expectSignature) : null,\n hostname: stripPort(req.headers['host']),\n };\n }\n\n private getDefaultResponseHeaders(): ServerHeaders {\n const headers = new Map<string, number | string | readonly string[]>();\n // set required headers for Expo Updates manifest specification\n headers.set('expo-protocol-version', 0);\n headers.set('expo-sfv-version', 0);\n headers.set('cache-control', 'private, max-age=0');\n return headers;\n }\n\n public async _getManifestResponseAsync(requestOptions: ExpoGoManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }> {\n const { exp, hostUri, expoGoConfig, bundleUrl } =\n await this._resolveProjectSettingsAsync(requestOptions);\n\n const runtimeVersion = await Updates.getRuntimeVersionAsync(\n this.projectRoot,\n { ...exp, runtimeVersion: exp.runtimeVersion ?? { policy: 'sdkVersion' } },\n requestOptions.platform\n );\n if (!runtimeVersion) {\n throw new CommandError(\n 'MANIFEST_MIDDLEWARE',\n `Unable to determine runtime version for platform '${requestOptions.platform}'`\n );\n }\n\n const codeSigningInfo = await getCodeSigningInfoAsync(\n exp,\n requestOptions.expectSignature,\n this.options.privateKeyPath\n );\n\n const easProjectId = exp.extra?.eas?.projectId as string | undefined | null;\n const scopeKey = await ExpoGoManifestHandlerMiddleware.getScopeKeyAsync({\n slug: exp.slug,\n codeSigningInfo,\n });\n\n const expoUpdatesManifest: ExpoUpdatesManifest = {\n id: crypto.randomUUID(),\n createdAt: new Date().toISOString(),\n runtimeVersion,\n launchAsset: {\n key: 'bundle',\n contentType: 'application/javascript',\n url: bundleUrl,\n },\n assets: [], // assets are not used in development\n metadata: {}, // required for the client to detect that this is an expo-updates manifest\n extra: {\n eas: {\n projectId: easProjectId ?? undefined,\n },\n expoClient: {\n ...exp,\n hostUri,\n },\n expoGo: expoGoConfig,\n scopeKey,\n },\n };\n\n const stringifiedManifest = JSON.stringify(expoUpdatesManifest);\n\n let manifestPartHeaders: { 'expo-signature': string } | null = null;\n let certificateChainBody: string | null = null;\n if (codeSigningInfo) {\n const signature = signManifestString(stringifiedManifest, codeSigningInfo);\n manifestPartHeaders = {\n 'expo-signature': serializeDictionary(\n convertToDictionaryItemsRepresentation({\n keyid: codeSigningInfo.keyId,\n sig: signature,\n alg: 'rsa-v1_5-sha256',\n })\n ),\n };\n certificateChainBody = codeSigningInfo.certificateChainForResponse.join('\\n');\n }\n\n const headers = this.getDefaultResponseHeaders();\n\n switch (requestOptions.responseContentType) {\n case ResponseContentType.MULTIPART_MIXED: {\n const form = this.getFormData({\n stringifiedManifest,\n manifestPartHeaders,\n certificateChainBody,\n });\n headers.set('content-type', `multipart/mixed; boundary=${form.getBoundary()}`);\n return {\n body: form.getBuffer().toString(),\n version: runtimeVersion,\n headers,\n };\n }\n case ResponseContentType.APPLICATION_EXPO_JSON:\n case ResponseContentType.APPLICATION_JSON:\n case ResponseContentType.TEXT_PLAIN: {\n headers.set(\n 'content-type',\n ExpoGoManifestHandlerMiddleware.getContentTypeForResponseContentType(\n requestOptions.responseContentType\n )\n );\n if (manifestPartHeaders) {\n Object.entries(manifestPartHeaders).forEach(([key, value]) => {\n headers.set(key, value);\n });\n }\n\n return {\n body: stringifiedManifest,\n version: runtimeVersion,\n headers,\n };\n }\n }\n }\n\n private static getContentTypeForResponseContentType(\n responseContentType: ResponseContentType\n ): string {\n switch (responseContentType) {\n case ResponseContentType.MULTIPART_MIXED:\n return 'multipart/mixed';\n case ResponseContentType.APPLICATION_EXPO_JSON:\n return 'application/expo+json';\n case ResponseContentType.APPLICATION_JSON:\n return 'application/json';\n case ResponseContentType.TEXT_PLAIN:\n return 'text/plain';\n }\n }\n\n private getFormData({\n stringifiedManifest,\n manifestPartHeaders,\n certificateChainBody,\n }: {\n stringifiedManifest: string;\n manifestPartHeaders: { 'expo-signature': string } | null;\n certificateChainBody: string | null;\n }): FormData {\n const form = new FormData();\n form.append('manifest', stringifiedManifest, {\n contentType: 'application/json',\n header: {\n ...manifestPartHeaders,\n },\n });\n if (certificateChainBody && certificateChainBody.length > 0) {\n form.append('certificate_chain', certificateChainBody, {\n contentType: 'application/x-pem-file',\n });\n }\n return form;\n }\n\n protected trackManifest(version?: string) {\n logEventAsync('Serve Expo Updates Manifest', {\n runtimeVersion: version,\n });\n }\n\n private static async getScopeKeyAsync({\n slug,\n codeSigningInfo,\n }: {\n slug: string;\n codeSigningInfo: CodeSigningInfo | null;\n }): Promise<string> {\n const scopeKeyFromCodeSigningInfo = codeSigningInfo?.scopeKey;\n if (scopeKeyFromCodeSigningInfo) {\n return scopeKeyFromCodeSigningInfo;\n }\n\n // Log.warn(\n // env.EXPO_OFFLINE\n // ? 'Using anonymous scope key in manifest for offline mode.'\n // : 'Using anonymous scope key in manifest.'\n // );\n return await getAnonymousScopeKeyAsync(slug);\n }\n}\n\nasync function getAnonymousScopeKeyAsync(slug: string): Promise<string> {\n const userAnonymousIdentifier = await UserSettings.getAnonymousIdentifierAsync();\n return `@${ANONYMOUS_USERNAME}/${slug}-${userAnonymousIdentifier}`;\n}\n\nfunction convertToDictionaryItemsRepresentation(obj: { [key: string]: string }): Dictionary {\n return new Map(\n Object.entries(obj).map(([k, v]) => {\n return [k, [v, new Map()]];\n })\n );\n}\n"],"names":["debug","require","ResponseContentType","TEXT_PLAIN","APPLICATION_JSON","APPLICATION_EXPO_JSON","MULTIPART_MIXED","ExpoGoManifestHandlerMiddleware","ManifestMiddleware","getParsedHeaders","req","platform","parsePlatformHeader","assertRuntimePlatform","accept","accepts","acceptedType","types","responseContentType","expectSignature","headers","String","hostname","stripPort","getDefaultResponseHeaders","Map","set","_getManifestResponseAsync","requestOptions","exp","hostUri","expoGoConfig","bundleUrl","_resolveProjectSettingsAsync","runtimeVersion","Updates","getRuntimeVersionAsync","projectRoot","policy","CommandError","codeSigningInfo","getCodeSigningInfoAsync","options","privateKeyPath","easProjectId","extra","eas","projectId","scopeKey","getScopeKeyAsync","slug","expoUpdatesManifest","id","crypto","randomUUID","createdAt","Date","toISOString","launchAsset","key","contentType","url","assets","metadata","undefined","expoClient","expoGo","stringifiedManifest","JSON","stringify","manifestPartHeaders","certificateChainBody","signature","signManifestString","serializeDictionary","convertToDictionaryItemsRepresentation","keyid","keyId","sig","alg","certificateChainForResponse","join","form","getFormData","getBoundary","body","getBuffer","toString","version","getContentTypeForResponseContentType","Object","entries","forEach","value","FormData","append","header","length","trackManifest","logEventAsync","scopeKeyFromCodeSigningInfo","getAnonymousScopeKeyAsync","userAnonymousIdentifier","UserSettings","getAnonymousIdentifierAsync","ANONYMOUS_USERNAME","obj","map","k","v"],"mappings":"AAAA;;;;;AACwB,IAAA,cAAsB,WAAtB,sBAAsB,CAAA;AAC1B,IAAA,QAAS,kCAAT,SAAS,EAAA;AACV,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACN,IAAA,SAAW,kCAAX,WAAW,EAAA;AACgB,IAAA,kBAAoB,WAApB,oBAAoB,CAAA;AAEZ,IAAA,mBAAsB,WAAtB,sBAAsB,CAAA;AACnB,IAAA,gBAAmB,WAAnB,mBAAmB,CAAA;AAErD,IAAA,aAAgC,kCAAhC,gCAAgC,EAAA;AACtB,IAAA,KAAwB,WAAxB,wBAAwB,CAAA;AAC7B,IAAA,kBAA4C,WAA5C,4CAA4C,CAAA;AAKnE,IAAA,YAA4B,WAA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AACD,CAAC;YAAE;gBAACC,CAAC;gBAAE,IAAIpF,GAAG,EAAE;aAAC;SAAC,CAAC;KAC5B,CAAC,CACH,CAAC;CACH"}
1
+ {"version":3,"sources":["../../../../../src/start/server/middleware/ExpoGoManifestHandlerMiddleware.ts"],"sourcesContent":["import { ExpoUpdatesManifest } from '@expo/config';\nimport { Updates } from '@expo/config-plugins';\nimport accepts from 'accepts';\nimport crypto from 'crypto';\nimport FormData from 'form-data';\nimport { serializeDictionary, Dictionary } from 'structured-headers';\n\nimport { ManifestMiddleware, ManifestRequestInfo } from './ManifestMiddleware';\nimport { assertRuntimePlatform, parsePlatformHeader } from './resolvePlatform';\nimport { ServerHeaders, ServerRequest } from './server.types';\nimport UserSettings from '../../../api/user/UserSettings';\nimport { ANONYMOUS_USERNAME } from '../../../api/user/user';\nimport { logEventAsync } from '../../../utils/analytics/rudderstackClient';\nimport {\n CodeSigningInfo,\n getCodeSigningInfoAsync,\n signManifestString,\n} from '../../../utils/codesigning';\nimport { CommandError } from '../../../utils/errors';\nimport { stripPort } from '../../../utils/url';\n\nconst debug = require('debug')('expo:start:server:middleware:ExpoGoManifestHandlerMiddleware');\n\nexport enum ResponseContentType {\n TEXT_PLAIN,\n APPLICATION_JSON,\n APPLICATION_EXPO_JSON,\n MULTIPART_MIXED,\n}\n\ninterface ExpoGoManifestRequestInfo extends ManifestRequestInfo {\n responseContentType: ResponseContentType;\n expectSignature: string | null;\n}\n\nexport class ExpoGoManifestHandlerMiddleware extends ManifestMiddleware<ExpoGoManifestRequestInfo> {\n public getParsedHeaders(req: ServerRequest): ExpoGoManifestRequestInfo {\n let platform = parsePlatformHeader(req);\n\n if (!platform) {\n debug(\n `No \"expo-platform\" header or \"platform\" query parameter specified. Falling back to \"ios\".`\n );\n platform = 'ios';\n }\n\n assertRuntimePlatform(platform);\n\n // Expo Updates clients explicitly accept \"multipart/mixed\" responses while browsers implicitly\n // accept them with \"accept: */*\". To make it easier to debug manifest responses by visiting their\n // URLs in a browser, we denote the response as \"text/plain\" if the user agent appears not to be\n // an Expo Updates client.\n const accept = accepts(req);\n const acceptedType = accept.types([\n 'unknown/unknown',\n 'multipart/mixed',\n 'application/json',\n 'application/expo+json',\n 'text/plain',\n ]);\n\n let responseContentType;\n switch (acceptedType) {\n case 'multipart/mixed':\n responseContentType = ResponseContentType.MULTIPART_MIXED;\n break;\n case 'application/json':\n responseContentType = ResponseContentType.APPLICATION_JSON;\n break;\n case 'application/expo+json':\n responseContentType = ResponseContentType.APPLICATION_EXPO_JSON;\n break;\n default:\n responseContentType = ResponseContentType.TEXT_PLAIN;\n break;\n }\n\n const expectSignature = req.headers['expo-expect-signature'];\n\n return {\n responseContentType,\n platform,\n expectSignature: expectSignature ? String(expectSignature) : null,\n hostname: stripPort(req.headers['host']),\n protocol: req.headers['x-forwarded-proto'] as 'http' | 'https' | undefined,\n };\n }\n\n private getDefaultResponseHeaders(): ServerHeaders {\n const headers = new Map<string, number | string | readonly string[]>();\n // set required headers for Expo Updates manifest specification\n headers.set('expo-protocol-version', 0);\n headers.set('expo-sfv-version', 0);\n headers.set('cache-control', 'private, max-age=0');\n return headers;\n }\n\n public async _getManifestResponseAsync(requestOptions: ExpoGoManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }> {\n const { exp, hostUri, expoGoConfig, bundleUrl } =\n await this._resolveProjectSettingsAsync(requestOptions);\n\n const runtimeVersion = await Updates.getRuntimeVersionAsync(\n this.projectRoot,\n { ...exp, runtimeVersion: exp.runtimeVersion ?? { policy: 'sdkVersion' } },\n requestOptions.platform\n );\n if (!runtimeVersion) {\n throw new CommandError(\n 'MANIFEST_MIDDLEWARE',\n `Unable to determine runtime version for platform '${requestOptions.platform}'`\n );\n }\n\n const codeSigningInfo = await getCodeSigningInfoAsync(\n exp,\n requestOptions.expectSignature,\n this.options.privateKeyPath\n );\n\n const easProjectId = exp.extra?.eas?.projectId as string | undefined | null;\n const scopeKey = await ExpoGoManifestHandlerMiddleware.getScopeKeyAsync({\n slug: exp.slug,\n codeSigningInfo,\n });\n\n const expoUpdatesManifest: ExpoUpdatesManifest = {\n id: crypto.randomUUID(),\n createdAt: new Date().toISOString(),\n runtimeVersion,\n launchAsset: {\n key: 'bundle',\n contentType: 'application/javascript',\n url: bundleUrl,\n },\n assets: [], // assets are not used in development\n metadata: {}, // required for the client to detect that this is an expo-updates manifest\n extra: {\n eas: {\n projectId: easProjectId ?? undefined,\n },\n expoClient: {\n ...exp,\n hostUri,\n },\n expoGo: expoGoConfig,\n scopeKey,\n },\n };\n\n const stringifiedManifest = JSON.stringify(expoUpdatesManifest);\n\n let manifestPartHeaders: { 'expo-signature': string } | null = null;\n let certificateChainBody: string | null = null;\n if (codeSigningInfo) {\n const signature = signManifestString(stringifiedManifest, codeSigningInfo);\n manifestPartHeaders = {\n 'expo-signature': serializeDictionary(\n convertToDictionaryItemsRepresentation({\n keyid: codeSigningInfo.keyId,\n sig: signature,\n alg: 'rsa-v1_5-sha256',\n })\n ),\n };\n certificateChainBody = codeSigningInfo.certificateChainForResponse.join('\\n');\n }\n\n const headers = this.getDefaultResponseHeaders();\n\n switch (requestOptions.responseContentType) {\n case ResponseContentType.MULTIPART_MIXED: {\n const form = this.getFormData({\n stringifiedManifest,\n manifestPartHeaders,\n certificateChainBody,\n });\n headers.set('content-type', `multipart/mixed; boundary=${form.getBoundary()}`);\n return {\n body: form.getBuffer().toString(),\n version: runtimeVersion,\n headers,\n };\n }\n case ResponseContentType.APPLICATION_EXPO_JSON:\n case ResponseContentType.APPLICATION_JSON:\n case ResponseContentType.TEXT_PLAIN: {\n headers.set(\n 'content-type',\n ExpoGoManifestHandlerMiddleware.getContentTypeForResponseContentType(\n requestOptions.responseContentType\n )\n );\n if (manifestPartHeaders) {\n Object.entries(manifestPartHeaders).forEach(([key, value]) => {\n headers.set(key, value);\n });\n }\n\n return {\n body: stringifiedManifest,\n version: runtimeVersion,\n headers,\n };\n }\n }\n }\n\n private static getContentTypeForResponseContentType(\n responseContentType: ResponseContentType\n ): string {\n switch (responseContentType) {\n case ResponseContentType.MULTIPART_MIXED:\n return 'multipart/mixed';\n case ResponseContentType.APPLICATION_EXPO_JSON:\n return 'application/expo+json';\n case ResponseContentType.APPLICATION_JSON:\n return 'application/json';\n case ResponseContentType.TEXT_PLAIN:\n return 'text/plain';\n }\n }\n\n private getFormData({\n stringifiedManifest,\n manifestPartHeaders,\n certificateChainBody,\n }: {\n stringifiedManifest: string;\n manifestPartHeaders: { 'expo-signature': string } | null;\n certificateChainBody: string | null;\n }): FormData {\n const form = new FormData();\n form.append('manifest', stringifiedManifest, {\n contentType: 'application/json',\n header: {\n ...manifestPartHeaders,\n },\n });\n if (certificateChainBody && certificateChainBody.length > 0) {\n form.append('certificate_chain', certificateChainBody, {\n contentType: 'application/x-pem-file',\n });\n }\n return form;\n }\n\n protected trackManifest(version?: string) {\n logEventAsync('Serve Expo Updates Manifest', {\n runtimeVersion: version,\n });\n }\n\n private static async getScopeKeyAsync({\n slug,\n codeSigningInfo,\n }: {\n slug: string;\n codeSigningInfo: CodeSigningInfo | null;\n }): Promise<string> {\n const scopeKeyFromCodeSigningInfo = codeSigningInfo?.scopeKey;\n if (scopeKeyFromCodeSigningInfo) {\n return scopeKeyFromCodeSigningInfo;\n }\n\n // Log.warn(\n // env.EXPO_OFFLINE\n // ? 'Using anonymous scope key in manifest for offline mode.'\n // : 'Using anonymous scope key in manifest.'\n // );\n return await getAnonymousScopeKeyAsync(slug);\n }\n}\n\nasync function getAnonymousScopeKeyAsync(slug: string): Promise<string> {\n const userAnonymousIdentifier = await UserSettings.getAnonymousIdentifierAsync();\n return `@${ANONYMOUS_USERNAME}/${slug}-${userAnonymousIdentifier}`;\n}\n\nfunction convertToDictionaryItemsRepresentation(obj: { [key: string]: string }): Dictionary {\n return new Map(\n Object.entries(obj).map(([k, v]) => {\n return [k, [v, new Map()]];\n })\n );\n}\n"],"names":["debug","require","ResponseContentType","TEXT_PLAIN","APPLICATION_JSON","APPLICATION_EXPO_JSON","MULTIPART_MIXED","ExpoGoManifestHandlerMiddleware","ManifestMiddleware","getParsedHeaders","req","platform","parsePlatformHeader","assertRuntimePlatform","accept","accepts","acceptedType","types","responseContentType","expectSignature","headers","String","hostname","stripPort","protocol","getDefaultResponseHeaders","Map","set","_getManifestResponseAsync","requestOptions","exp","hostUri","expoGoConfig","bundleUrl","_resolveProjectSettingsAsync","runtimeVersion","Updates","getRuntimeVersionAsync","projectRoot","policy","CommandError","codeSigningInfo","getCodeSigningInfoAsync","options","privateKeyPath","easProjectId","extra","eas","projectId","scopeKey","getScopeKeyAsync","slug","expoUpdatesManifest","id","crypto","randomUUID","createdAt","Date","toISOString","launchAsset","key","contentType","url","assets","metadata","undefined","expoClient","expoGo","stringifiedManifest","JSON","stringify","manifestPartHeaders","certificateChainBody","signature","signManifestString","serializeDictionary","convertToDictionaryItemsRepresentation","keyid","keyId","sig","alg","certificateChainForResponse","join","form","getFormData","getBoundary","body","getBuffer","toString","version","getContentTypeForResponseContentType","Object","entries","forEach","value","FormData","append","header","length","trackManifest","logEventAsync","scopeKeyFromCodeSigningInfo","getAnonymousScopeKeyAsync","userAnonymousIdentifier","UserSettings","getAnonymousIdentifierAsync","ANONYMOUS_USERNAME","obj","map","k","v"],"mappings":"AAAA;;;;;AACwB,IAAA,cAAsB,WAAtB,sBAAsB,CAAA;AAC1B,IAAA,QAAS,kCAAT,SAAS,EAAA;AACV,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACN,IAAA,SAAW,kCAAX,WAAW,EAAA;AACgB,IAAA,kBAAoB,WAApB,oBAAoB,CAAA;AAEZ,IAAA,mBAAsB,WAAtB,sBAAsB,CAAA;AACnB,IAAA,gBAAmB,WAAnB,mBAAmB,CAAA;AAErD,IAAA,aAAgC,kCAAhC,gCAAgC,EAAA;AACtB,IAAA,KAAwB,WAAxB,wBAAwB,CAAA;AAC7B,IAAA,kBAA4C,WAA5C,4CAA4C,CAAA;AAKnE,IAAA,YAA4B,WAA5B,4BAA4B,CAA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AAC,EAAEC,CAAC,CAAC,GAAK;QAClC,OAAO;YAACD,CAAC;YAAE;gBAACC,CAAC;gBAAE,IAAIpF,GAAG,EAAE;aAAC;SAAC,CAAC;KAC5B,CAAC,CACH,CAAC;CACH"}
@@ -102,7 +102,7 @@ class ManifestMiddleware extends _expoMiddleware.ExpoMiddleware {
102
102
  this.initialProjectConfig = (0, _config).getConfig(projectRoot);
103
103
  this.platformBundlers = (0, _platformBundlers).getPlatformBundlers(projectRoot, this.initialProjectConfig.exp);
104
104
  }
105
- /** Exposed for testing. */ async _resolveProjectSettingsAsync({ platform , hostname }) {
105
+ /** Exposed for testing. */ async _resolveProjectSettingsAsync({ platform , hostname , protocol }) {
106
106
  // Read the config
107
107
  const projectConfig = (0, _config).getConfig(this.projectRoot);
108
108
  // Read from headers
@@ -128,7 +128,8 @@ class ManifestMiddleware extends _expoMiddleware.ExpoMiddleware {
128
128
  engine: isHermesEnabled ? "hermes" : undefined,
129
129
  baseUrl: (0, _metroOptions).getBaseUrlFromExpoConfig(projectConfig.exp),
130
130
  asyncRoutes: (0, _metroOptions).getAsyncRoutesFromExpoConfig(projectConfig.exp, (_mode = this.options.mode) != null ? _mode : "development", platform),
131
- routerRoot: (0, _router).getRouterDirectoryModuleIdWithManifest(this.projectRoot, projectConfig.exp)
131
+ routerRoot: (0, _router).getRouterDirectoryModuleIdWithManifest(this.projectRoot, projectConfig.exp),
132
+ protocol
132
133
  });
133
134
  // Resolve all assets and set them on the manifest as URLs
134
135
  await this.mutateManifestWithAssetsAsync(projectConfig.exp, bundleUrl);
@@ -161,7 +162,7 @@ class ManifestMiddleware extends _expoMiddleware.ExpoMiddleware {
161
162
  );
162
163
  }
163
164
  }
164
- /** Create the bundle URL (points to the single JS entry file). Exposed for testing. */ _getBundleUrl({ platform , mainModuleName , hostname , engine , baseUrl , isExporting , asyncRoutes , routerRoot }) {
165
+ /** Create the bundle URL (points to the single JS entry file). Exposed for testing. */ _getBundleUrl({ platform , mainModuleName , hostname , engine , baseUrl , isExporting , asyncRoutes , routerRoot , protocol }) {
165
166
  var _mode;
166
167
  const path = (0, _metroOptions).createBundleUrlPath({
167
168
  mode: (_mode = this.options.mode) != null ? _mode : "development",
@@ -170,13 +171,14 @@ class ManifestMiddleware extends _expoMiddleware.ExpoMiddleware {
170
171
  mainModuleName,
171
172
  lazy: (0, _metroOptions).shouldEnableAsyncImports(this.projectRoot),
172
173
  engine,
174
+ bytecode: engine === "hermes",
173
175
  baseUrl,
174
176
  isExporting: !!isExporting,
175
177
  asyncRoutes,
176
178
  routerRoot
177
179
  });
178
180
  return this.options.constructUrl({
179
- scheme: "http",
181
+ scheme: protocol != null ? protocol : "http",
180
182
  // hostType: this.options.location.hostType,
181
183
  hostname
182
184
  }) + path;
@@ -237,7 +239,8 @@ class ManifestMiddleware extends _expoMiddleware.ExpoMiddleware {
237
239
  mode: (_mode = this.options.mode) != null ? _mode : "development",
238
240
  // Hermes doesn't support more modern JS features than most, if not all, modern browser.
239
241
  engine: "hermes",
240
- isExporting: false
242
+ isExporting: false,
243
+ bytecode: false
241
244
  });
242
245
  }
243
246
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/middleware/ManifestMiddleware.ts"],"sourcesContent":["import {\n ExpoConfig,\n ExpoGoConfig,\n getConfig,\n PackageJSONConfig,\n ProjectConfig,\n} from '@expo/config';\nimport { resolveEntryPoint } from '@expo/config/paths';\nimport findWorkspaceRoot from 'find-yarn-workspace-root';\nimport path from 'path';\nimport { resolve } from 'url';\n\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport {\n shouldEnableAsyncImports,\n createBundleUrlPath,\n getBaseUrlFromExpoConfig,\n getAsyncRoutesFromExpoConfig,\n createBundleUrlPathFromExpoConfig,\n} from './metroOptions';\nimport { resolveGoogleServicesFile, resolveManifestAssets } from './resolveAssets';\nimport { parsePlatformHeader, RuntimePlatform } from './resolvePlatform';\nimport { ServerHeaders, ServerNext, ServerRequest, ServerResponse } from './server.types';\nimport { isEnableHermesManaged } from '../../../export/exportHermes';\nimport * as Log from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { stripExtension } from '../../../utils/url';\nimport * as ProjectDevices from '../../project/devices';\nimport { UrlCreator } from '../UrlCreator';\nimport { getRouterDirectoryModuleIdWithManifest } from '../metro/router';\nimport { getPlatformBundlers, PlatformBundlers } from '../platformBundlers';\nimport { createTemplateHtmlFromExpoConfigAsync } from '../webTemplate';\n\nconst debug = require('debug')('expo:start:server:middleware:manifest') as typeof console.log;\n\n/** Wraps `findWorkspaceRoot` and guards against having an empty `package.json` file in an upper directory. */\nexport function getWorkspaceRoot(projectRoot: string): string | null {\n try {\n return findWorkspaceRoot(projectRoot);\n } catch (error: any) {\n if (error.message.includes('Unexpected end of JSON input')) {\n return null;\n }\n throw error;\n }\n}\n\nconst supportedPlatforms = ['ios', 'android', 'web', 'none'];\n\nexport function getEntryWithServerRoot(\n projectRoot: string,\n props: { platform: string; pkg?: PackageJSONConfig }\n) {\n if (!supportedPlatforms.includes(props.platform)) {\n throw new CommandError(\n `Failed to resolve the project's entry file: The platform \"${props.platform}\" is not supported.`\n );\n }\n return path.relative(getMetroServerRoot(projectRoot), resolveEntryPoint(projectRoot, props));\n}\n\nexport function getMetroServerRoot(projectRoot: string) {\n if (env.EXPO_USE_METRO_WORKSPACE_ROOT) {\n return getWorkspaceRoot(projectRoot) ?? projectRoot;\n }\n\n return projectRoot;\n}\n\n/** Get the main entry module ID (file) relative to the project root. */\nexport function resolveMainModuleName(\n projectRoot: string,\n props: { platform: string; pkg?: PackageJSONConfig }\n): string {\n const entryPoint = getEntryWithServerRoot(projectRoot, props);\n\n debug(`Resolved entry point: ${entryPoint} (project root: ${projectRoot})`);\n\n return stripExtension(entryPoint, 'js');\n}\n\n/** Info about the computer hosting the dev server. */\nexport interface HostInfo {\n host: string;\n server: 'expo';\n serverVersion: string;\n serverDriver: string | null;\n serverOS: NodeJS.Platform;\n serverOSVersion: string;\n}\n\n/** Parsed values from the supported request headers. */\nexport interface ManifestRequestInfo {\n /** Platform to serve. */\n platform: RuntimePlatform;\n /** Requested host name. */\n hostname?: string | null;\n}\n\n/** Project related info. */\nexport type ResponseProjectSettings = {\n expoGoConfig: ExpoGoConfig;\n hostUri: string;\n bundleUrl: string;\n exp: ExpoConfig;\n};\n\nexport const DEVELOPER_TOOL = 'expo-cli';\n\nexport type ManifestMiddlewareOptions = {\n /** Should start the dev servers in development mode (minify). */\n mode?: 'development' | 'production';\n /** Should instruct the bundler to create minified bundles. */\n minify?: boolean;\n constructUrl: UrlCreator['constructUrl'];\n isNativeWebpack?: boolean;\n privateKeyPath?: string;\n};\n\n/** Base middleware creator for serving the Expo manifest (like the index.html but for native runtimes). */\nexport abstract class ManifestMiddleware<\n TManifestRequestInfo extends ManifestRequestInfo,\n> extends ExpoMiddleware {\n private initialProjectConfig: ProjectConfig;\n private platformBundlers: PlatformBundlers;\n\n constructor(\n protected projectRoot: string,\n protected options: ManifestMiddlewareOptions\n ) {\n super(\n projectRoot,\n /**\n * Only support `/`, `/manifest`, `/index.exp` for the manifest middleware.\n */\n ['/', '/manifest', '/index.exp']\n );\n this.initialProjectConfig = getConfig(projectRoot);\n this.platformBundlers = getPlatformBundlers(projectRoot, this.initialProjectConfig.exp);\n }\n\n /** Exposed for testing. */\n public async _resolveProjectSettingsAsync({\n platform,\n hostname,\n }: Pick<TManifestRequestInfo, 'hostname' | 'platform'>): Promise<ResponseProjectSettings> {\n // Read the config\n const projectConfig = getConfig(this.projectRoot);\n\n // Read from headers\n const mainModuleName = this.resolveMainModuleName({\n pkg: projectConfig.pkg,\n platform,\n });\n\n const isHermesEnabled = isEnableHermesManaged(projectConfig.exp, platform);\n\n // Create the manifest and set fields within it\n const expoGoConfig = this.getExpoGoConfig({\n mainModuleName,\n hostname,\n });\n\n const hostUri = this.options.constructUrl({ scheme: '', hostname });\n\n const bundleUrl = this._getBundleUrl({\n platform,\n mainModuleName,\n hostname,\n engine: isHermesEnabled ? 'hermes' : undefined,\n baseUrl: getBaseUrlFromExpoConfig(projectConfig.exp),\n asyncRoutes: getAsyncRoutesFromExpoConfig(\n projectConfig.exp,\n this.options.mode ?? 'development',\n platform\n ),\n routerRoot: getRouterDirectoryModuleIdWithManifest(this.projectRoot, projectConfig.exp),\n });\n\n // Resolve all assets and set them on the manifest as URLs\n await this.mutateManifestWithAssetsAsync(projectConfig.exp, bundleUrl);\n\n return {\n expoGoConfig,\n hostUri,\n bundleUrl,\n exp: projectConfig.exp,\n };\n }\n\n /** Get the main entry module ID (file) relative to the project root. */\n private resolveMainModuleName(props: { pkg: PackageJSONConfig; platform: string }): string {\n let entryPoint = getEntryWithServerRoot(this.projectRoot, props);\n\n debug(`Resolved entry point: ${entryPoint} (project root: ${this.projectRoot})`);\n\n // NOTE(Bacon): Webpack is currently hardcoded to index.bundle on native\n // in the future (TODO) we should move this logic into a Webpack plugin and use\n // a generated file name like we do on web.\n // const server = getDefaultDevServer();\n // // TODO: Move this into BundlerDevServer and read this info from self.\n // const isNativeWebpack = server instanceof WebpackBundlerDevServer && server.isTargetingNative();\n if (this.options.isNativeWebpack) {\n entryPoint = 'index.js';\n }\n\n return stripExtension(entryPoint, 'js');\n }\n\n /** Parse request headers into options. */\n public abstract getParsedHeaders(req: ServerRequest): TManifestRequestInfo;\n\n /** Store device IDs that were sent in the request headers. */\n private async saveDevicesAsync(req: ServerRequest) {\n const deviceIds = req.headers?.['expo-dev-client-id'];\n if (deviceIds) {\n await ProjectDevices.saveDevicesAsync(this.projectRoot, deviceIds).catch((e) =>\n Log.exception(e)\n );\n }\n }\n\n /** Create the bundle URL (points to the single JS entry file). Exposed for testing. */\n public _getBundleUrl({\n platform,\n mainModuleName,\n hostname,\n engine,\n baseUrl,\n isExporting,\n asyncRoutes,\n routerRoot,\n }: {\n platform: string;\n hostname?: string | null;\n mainModuleName: string;\n engine?: 'hermes';\n baseUrl?: string;\n asyncRoutes: boolean;\n isExporting?: boolean;\n routerRoot: string;\n }): string {\n const path = createBundleUrlPath({\n mode: this.options.mode ?? 'development',\n minify: this.options.minify,\n platform,\n mainModuleName,\n lazy: shouldEnableAsyncImports(this.projectRoot),\n engine,\n baseUrl,\n isExporting: !!isExporting,\n asyncRoutes,\n routerRoot,\n });\n\n return (\n this.options.constructUrl({\n scheme: 'http',\n // hostType: this.options.location.hostType,\n hostname,\n }) + path\n );\n }\n\n /** Log telemetry. */\n protected abstract trackManifest(version?: string): void;\n\n /** Get the manifest response to return to the runtime. This file contains info regarding where the assets can be loaded from. Exposed for testing. */\n public abstract _getManifestResponseAsync(options: TManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }>;\n\n private getExpoGoConfig({\n mainModuleName,\n hostname,\n }: {\n mainModuleName: string;\n hostname?: string | null;\n }): ExpoGoConfig {\n return {\n // localhost:8081\n debuggerHost: this.options.constructUrl({ scheme: '', hostname }),\n // Required for Expo Go to function.\n developer: {\n tool: DEVELOPER_TOOL,\n projectRoot: this.projectRoot,\n },\n packagerOpts: {\n // Required for dev client.\n dev: this.options.mode !== 'production',\n },\n // Indicates the name of the main bundle.\n mainModuleName,\n // Add this string to make Flipper register React Native / Metro as \"running\".\n // Can be tested by running:\n // `METRO_SERVER_PORT=8081 open -a flipper.app`\n // Where 8081 is the port where the Expo project is being hosted.\n __flipperHack: 'React Native packager is running',\n };\n }\n\n /** Resolve all assets and set them on the manifest as URLs */\n private async mutateManifestWithAssetsAsync(manifest: ExpoConfig, bundleUrl: string) {\n await resolveManifestAssets(this.projectRoot, {\n manifest,\n resolver: async (path) => {\n if (this.options.isNativeWebpack) {\n // When using our custom dev server, just do assets normally\n // without the `assets/` subpath redirect.\n return resolve(bundleUrl!.match(/^https?:\\/\\/.*?\\//)![0], path);\n }\n return bundleUrl!.match(/^https?:\\/\\/.*?\\//)![0] + 'assets/' + path;\n },\n });\n // The server normally inserts this but if we're offline we'll do it here\n await resolveGoogleServicesFile(this.projectRoot, manifest);\n }\n\n public getWebBundleUrl() {\n const platform = 'web';\n // Read from headers\n const mainModuleName = this.resolveMainModuleName({\n pkg: this.initialProjectConfig.pkg,\n platform,\n });\n\n return createBundleUrlPathFromExpoConfig(this.projectRoot, this.initialProjectConfig.exp, {\n platform,\n mainModuleName,\n minify: this.options.minify,\n lazy: shouldEnableAsyncImports(this.projectRoot),\n mode: this.options.mode ?? 'development',\n // Hermes doesn't support more modern JS features than most, if not all, modern browser.\n engine: 'hermes',\n isExporting: false,\n });\n }\n\n /**\n * Web platforms should create an index.html response using the same script resolution as native.\n *\n * Instead of adding a `bundleUrl` to a `manifest.json` (native) we'll add a `<script src=\"\">`\n * to an `index.html`, this enables the web platform to load JavaScript from the server.\n */\n private async handleWebRequestAsync(req: ServerRequest, res: ServerResponse) {\n // Read from headers\n const bundleUrl = this.getWebBundleUrl();\n\n res.setHeader('Content-Type', 'text/html');\n\n res.end(\n await createTemplateHtmlFromExpoConfigAsync(this.projectRoot, {\n exp: this.initialProjectConfig.exp,\n scripts: [bundleUrl],\n })\n );\n }\n\n /** Exposed for testing. */\n async checkBrowserRequestAsync(req: ServerRequest, res: ServerResponse, next: ServerNext) {\n if (\n this.platformBundlers.web === 'metro' &&\n this.initialProjectConfig.exp.platforms?.includes('web')\n ) {\n // NOTE(EvanBacon): This effectively disables the safety check we do on custom runtimes to ensure\n // the `expo-platform` header is included. When `web.bundler=web`, if the user has non-standard Expo\n // code loading then they'll get a web bundle without a clear assertion of platform support.\n const platform = parsePlatformHeader(req);\n // On web, serve the public folder\n if (!platform || platform === 'web') {\n if (['static', 'server'].includes(this.initialProjectConfig.exp.web?.output ?? '')) {\n // Skip the spa-styled index.html when static generation is enabled.\n next();\n return true;\n } else {\n await this.handleWebRequestAsync(req, res);\n return true;\n }\n }\n }\n return false;\n }\n\n async handleRequestAsync(\n req: ServerRequest,\n res: ServerResponse,\n next: ServerNext\n ): Promise<void> {\n // First check for standard JavaScript runtimes (aka legacy browsers like Chrome).\n if (await this.checkBrowserRequestAsync(req, res, next)) {\n return;\n }\n\n // Save device IDs for dev client.\n await this.saveDevicesAsync(req);\n\n // Read from headers\n const options = this.getParsedHeaders(req);\n const { body, version, headers } = await this._getManifestResponseAsync(options);\n for (const [headerName, headerValue] of headers) {\n res.setHeader(headerName, headerValue);\n }\n res.end(body);\n\n // Log analytics\n this.trackManifest(version ?? null);\n }\n}\n"],"names":["getWorkspaceRoot","getEntryWithServerRoot","getMetroServerRoot","resolveMainModuleName","Log","ProjectDevices","debug","require","projectRoot","findWorkspaceRoot","error","message","includes","supportedPlatforms","props","platform","CommandError","path","relative","resolveEntryPoint","env","EXPO_USE_METRO_WORKSPACE_ROOT","entryPoint","stripExtension","DEVELOPER_TOOL","ManifestMiddleware","ExpoMiddleware","constructor","options","initialProjectConfig","getConfig","platformBundlers","getPlatformBundlers","exp","_resolveProjectSettingsAsync","hostname","projectConfig","mainModuleName","pkg","isHermesEnabled","isEnableHermesManaged","expoGoConfig","getExpoGoConfig","hostUri","constructUrl","scheme","bundleUrl","_getBundleUrl","engine","undefined","baseUrl","getBaseUrlFromExpoConfig","asyncRoutes","getAsyncRoutesFromExpoConfig","mode","routerRoot","getRouterDirectoryModuleIdWithManifest","mutateManifestWithAssetsAsync","isNativeWebpack","saveDevicesAsync","req","deviceIds","headers","catch","e","exception","isExporting","createBundleUrlPath","minify","lazy","shouldEnableAsyncImports","debuggerHost","developer","tool","packagerOpts","dev","__flipperHack","manifest","resolveManifestAssets","resolver","resolve","match","resolveGoogleServicesFile","getWebBundleUrl","createBundleUrlPathFromExpoConfig","handleWebRequestAsync","res","setHeader","end","createTemplateHtmlFromExpoConfigAsync","scripts","checkBrowserRequestAsync","next","web","platforms","parsePlatformHeader","output","handleRequestAsync","getParsedHeaders","body","version","_getManifestResponseAsync","headerName","headerValue","trackManifest"],"mappings":"AAAA;;;;QAqCgBA,gBAAgB,GAAhBA,gBAAgB;QAahBC,sBAAsB,GAAtBA,sBAAsB;QAYtBC,kBAAkB,GAAlBA,kBAAkB;QASlBC,qBAAqB,GA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oB;QACpB,MAAMhC,OAAO,GAAG,IAAI,CAACsE,gBAAgB,CAACtC,GAAG,CAAC,AAAC;QAC3C,MAAM,EAAEuC,IAAI,CAAA,EAAEC,OAAO,CAAA,EAAEtC,OAAO,CAAA,EAAE,GAAG,MAAM,IAAI,CAACuC,yBAAyB,CAACzE,OAAO,CAAC,AAAC;QACjF,KAAK,MAAM,CAAC0E,UAAU,EAAEC,WAAW,CAAC,IAAIzC,OAAO,CAAE;YAC/CwB,GAAG,CAACC,SAAS,CAACe,UAAU,EAAEC,WAAW,CAAC,CAAC;SACxC;QACDjB,GAAG,CAACE,GAAG,CAACW,IAAI,CAAC,CAAC;QAEd,gBAAgB;QAChB,IAAI,CAACK,aAAa,CAACJ,OAAO,WAAPA,OAAO,GAAI,IAAI,CAAC,CAAC;KACrC;CACF;QAjSqB3E,kBAAkB,GAAlBA,kBAAkB"}
1
+ {"version":3,"sources":["../../../../../src/start/server/middleware/ManifestMiddleware.ts"],"sourcesContent":["import {\n ExpoConfig,\n ExpoGoConfig,\n getConfig,\n PackageJSONConfig,\n ProjectConfig,\n} from '@expo/config';\nimport { resolveEntryPoint } from '@expo/config/paths';\nimport findWorkspaceRoot from 'find-yarn-workspace-root';\nimport path from 'path';\nimport { resolve } from 'url';\n\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport {\n shouldEnableAsyncImports,\n createBundleUrlPath,\n getBaseUrlFromExpoConfig,\n getAsyncRoutesFromExpoConfig,\n createBundleUrlPathFromExpoConfig,\n} from './metroOptions';\nimport { resolveGoogleServicesFile, resolveManifestAssets } from './resolveAssets';\nimport { parsePlatformHeader, RuntimePlatform } from './resolvePlatform';\nimport { ServerHeaders, ServerNext, ServerRequest, ServerResponse } from './server.types';\nimport { isEnableHermesManaged } from '../../../export/exportHermes';\nimport * as Log from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { stripExtension } from '../../../utils/url';\nimport * as ProjectDevices from '../../project/devices';\nimport { UrlCreator } from '../UrlCreator';\nimport { getRouterDirectoryModuleIdWithManifest } from '../metro/router';\nimport { getPlatformBundlers, PlatformBundlers } from '../platformBundlers';\nimport { createTemplateHtmlFromExpoConfigAsync } from '../webTemplate';\n\nconst debug = require('debug')('expo:start:server:middleware:manifest') as typeof console.log;\n\n/** Wraps `findWorkspaceRoot` and guards against having an empty `package.json` file in an upper directory. */\nexport function getWorkspaceRoot(projectRoot: string): string | null {\n try {\n return findWorkspaceRoot(projectRoot);\n } catch (error: any) {\n if (error.message.includes('Unexpected end of JSON input')) {\n return null;\n }\n throw error;\n }\n}\n\nconst supportedPlatforms = ['ios', 'android', 'web', 'none'];\n\nexport function getEntryWithServerRoot(\n projectRoot: string,\n props: { platform: string; pkg?: PackageJSONConfig }\n) {\n if (!supportedPlatforms.includes(props.platform)) {\n throw new CommandError(\n `Failed to resolve the project's entry file: The platform \"${props.platform}\" is not supported.`\n );\n }\n return path.relative(getMetroServerRoot(projectRoot), resolveEntryPoint(projectRoot, props));\n}\n\nexport function getMetroServerRoot(projectRoot: string) {\n if (env.EXPO_USE_METRO_WORKSPACE_ROOT) {\n return getWorkspaceRoot(projectRoot) ?? projectRoot;\n }\n\n return projectRoot;\n}\n\n/** Get the main entry module ID (file) relative to the project root. */\nexport function resolveMainModuleName(\n projectRoot: string,\n props: { platform: string; pkg?: PackageJSONConfig }\n): string {\n const entryPoint = getEntryWithServerRoot(projectRoot, props);\n\n debug(`Resolved entry point: ${entryPoint} (project root: ${projectRoot})`);\n\n return stripExtension(entryPoint, 'js');\n}\n\n/** Info about the computer hosting the dev server. */\nexport interface HostInfo {\n host: string;\n server: 'expo';\n serverVersion: string;\n serverDriver: string | null;\n serverOS: NodeJS.Platform;\n serverOSVersion: string;\n}\n\n/** Parsed values from the supported request headers. */\nexport interface ManifestRequestInfo {\n /** Platform to serve. */\n platform: RuntimePlatform;\n /** Requested host name. */\n hostname?: string | null;\n /** The protocol used to request the manifest */\n protocol?: 'http' | 'https';\n}\n\n/** Project related info. */\nexport type ResponseProjectSettings = {\n expoGoConfig: ExpoGoConfig;\n hostUri: string;\n bundleUrl: string;\n exp: ExpoConfig;\n};\n\nexport const DEVELOPER_TOOL = 'expo-cli';\n\nexport type ManifestMiddlewareOptions = {\n /** Should start the dev servers in development mode (minify). */\n mode?: 'development' | 'production';\n /** Should instruct the bundler to create minified bundles. */\n minify?: boolean;\n constructUrl: UrlCreator['constructUrl'];\n isNativeWebpack?: boolean;\n privateKeyPath?: string;\n};\n\n/** Base middleware creator for serving the Expo manifest (like the index.html but for native runtimes). */\nexport abstract class ManifestMiddleware<\n TManifestRequestInfo extends ManifestRequestInfo,\n> extends ExpoMiddleware {\n private initialProjectConfig: ProjectConfig;\n private platformBundlers: PlatformBundlers;\n\n constructor(\n protected projectRoot: string,\n protected options: ManifestMiddlewareOptions\n ) {\n super(\n projectRoot,\n /**\n * Only support `/`, `/manifest`, `/index.exp` for the manifest middleware.\n */\n ['/', '/manifest', '/index.exp']\n );\n this.initialProjectConfig = getConfig(projectRoot);\n this.platformBundlers = getPlatformBundlers(projectRoot, this.initialProjectConfig.exp);\n }\n\n /** Exposed for testing. */\n public async _resolveProjectSettingsAsync({\n platform,\n hostname,\n protocol,\n }: Pick<\n TManifestRequestInfo,\n 'hostname' | 'platform' | 'protocol'\n >): Promise<ResponseProjectSettings> {\n // Read the config\n const projectConfig = getConfig(this.projectRoot);\n\n // Read from headers\n const mainModuleName = this.resolveMainModuleName({\n pkg: projectConfig.pkg,\n platform,\n });\n\n const isHermesEnabled = isEnableHermesManaged(projectConfig.exp, platform);\n\n // Create the manifest and set fields within it\n const expoGoConfig = this.getExpoGoConfig({\n mainModuleName,\n hostname,\n });\n\n const hostUri = this.options.constructUrl({ scheme: '', hostname });\n\n const bundleUrl = this._getBundleUrl({\n platform,\n mainModuleName,\n hostname,\n engine: isHermesEnabled ? 'hermes' : undefined,\n baseUrl: getBaseUrlFromExpoConfig(projectConfig.exp),\n asyncRoutes: getAsyncRoutesFromExpoConfig(\n projectConfig.exp,\n this.options.mode ?? 'development',\n platform\n ),\n routerRoot: getRouterDirectoryModuleIdWithManifest(this.projectRoot, projectConfig.exp),\n protocol,\n });\n\n // Resolve all assets and set them on the manifest as URLs\n await this.mutateManifestWithAssetsAsync(projectConfig.exp, bundleUrl);\n\n return {\n expoGoConfig,\n hostUri,\n bundleUrl,\n exp: projectConfig.exp,\n };\n }\n\n /** Get the main entry module ID (file) relative to the project root. */\n private resolveMainModuleName(props: { pkg: PackageJSONConfig; platform: string }): string {\n let entryPoint = getEntryWithServerRoot(this.projectRoot, props);\n\n debug(`Resolved entry point: ${entryPoint} (project root: ${this.projectRoot})`);\n\n // NOTE(Bacon): Webpack is currently hardcoded to index.bundle on native\n // in the future (TODO) we should move this logic into a Webpack plugin and use\n // a generated file name like we do on web.\n // const server = getDefaultDevServer();\n // // TODO: Move this into BundlerDevServer and read this info from self.\n // const isNativeWebpack = server instanceof WebpackBundlerDevServer && server.isTargetingNative();\n if (this.options.isNativeWebpack) {\n entryPoint = 'index.js';\n }\n\n return stripExtension(entryPoint, 'js');\n }\n\n /** Parse request headers into options. */\n public abstract getParsedHeaders(req: ServerRequest): TManifestRequestInfo;\n\n /** Store device IDs that were sent in the request headers. */\n private async saveDevicesAsync(req: ServerRequest) {\n const deviceIds = req.headers?.['expo-dev-client-id'];\n if (deviceIds) {\n await ProjectDevices.saveDevicesAsync(this.projectRoot, deviceIds).catch((e) =>\n Log.exception(e)\n );\n }\n }\n\n /** Create the bundle URL (points to the single JS entry file). Exposed for testing. */\n public _getBundleUrl({\n platform,\n mainModuleName,\n hostname,\n engine,\n baseUrl,\n isExporting,\n asyncRoutes,\n routerRoot,\n protocol,\n }: {\n platform: string;\n hostname?: string | null;\n mainModuleName: string;\n engine?: 'hermes';\n baseUrl?: string;\n asyncRoutes: boolean;\n isExporting?: boolean;\n routerRoot: string;\n protocol?: 'http' | 'https';\n }): string {\n const path = createBundleUrlPath({\n mode: this.options.mode ?? 'development',\n minify: this.options.minify,\n platform,\n mainModuleName,\n lazy: shouldEnableAsyncImports(this.projectRoot),\n engine,\n bytecode: engine === 'hermes',\n baseUrl,\n isExporting: !!isExporting,\n asyncRoutes,\n routerRoot,\n });\n\n return (\n this.options.constructUrl({\n scheme: protocol ?? 'http',\n // hostType: this.options.location.hostType,\n hostname,\n }) + path\n );\n }\n\n /** Log telemetry. */\n protected abstract trackManifest(version?: string): void;\n\n /** Get the manifest response to return to the runtime. This file contains info regarding where the assets can be loaded from. Exposed for testing. */\n public abstract _getManifestResponseAsync(options: TManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }>;\n\n private getExpoGoConfig({\n mainModuleName,\n hostname,\n }: {\n mainModuleName: string;\n hostname?: string | null;\n }): ExpoGoConfig {\n return {\n // localhost:8081\n debuggerHost: this.options.constructUrl({ scheme: '', hostname }),\n // Required for Expo Go to function.\n developer: {\n tool: DEVELOPER_TOOL,\n projectRoot: this.projectRoot,\n },\n packagerOpts: {\n // Required for dev client.\n dev: this.options.mode !== 'production',\n },\n // Indicates the name of the main bundle.\n mainModuleName,\n // Add this string to make Flipper register React Native / Metro as \"running\".\n // Can be tested by running:\n // `METRO_SERVER_PORT=8081 open -a flipper.app`\n // Where 8081 is the port where the Expo project is being hosted.\n __flipperHack: 'React Native packager is running',\n };\n }\n\n /** Resolve all assets and set them on the manifest as URLs */\n private async mutateManifestWithAssetsAsync(manifest: ExpoConfig, bundleUrl: string) {\n await resolveManifestAssets(this.projectRoot, {\n manifest,\n resolver: async (path) => {\n if (this.options.isNativeWebpack) {\n // When using our custom dev server, just do assets normally\n // without the `assets/` subpath redirect.\n return resolve(bundleUrl!.match(/^https?:\\/\\/.*?\\//)![0], path);\n }\n return bundleUrl!.match(/^https?:\\/\\/.*?\\//)![0] + 'assets/' + path;\n },\n });\n // The server normally inserts this but if we're offline we'll do it here\n await resolveGoogleServicesFile(this.projectRoot, manifest);\n }\n\n public getWebBundleUrl() {\n const platform = 'web';\n // Read from headers\n const mainModuleName = this.resolveMainModuleName({\n pkg: this.initialProjectConfig.pkg,\n platform,\n });\n\n return createBundleUrlPathFromExpoConfig(this.projectRoot, this.initialProjectConfig.exp, {\n platform,\n mainModuleName,\n minify: this.options.minify,\n lazy: shouldEnableAsyncImports(this.projectRoot),\n mode: this.options.mode ?? 'development',\n // Hermes doesn't support more modern JS features than most, if not all, modern browser.\n engine: 'hermes',\n isExporting: false,\n bytecode: false,\n });\n }\n\n /**\n * Web platforms should create an index.html response using the same script resolution as native.\n *\n * Instead of adding a `bundleUrl` to a `manifest.json` (native) we'll add a `<script src=\"\">`\n * to an `index.html`, this enables the web platform to load JavaScript from the server.\n */\n private async handleWebRequestAsync(req: ServerRequest, res: ServerResponse) {\n // Read from headers\n const bundleUrl = this.getWebBundleUrl();\n\n res.setHeader('Content-Type', 'text/html');\n\n res.end(\n await createTemplateHtmlFromExpoConfigAsync(this.projectRoot, {\n exp: this.initialProjectConfig.exp,\n scripts: [bundleUrl],\n })\n );\n }\n\n /** Exposed for testing. */\n async checkBrowserRequestAsync(req: ServerRequest, res: ServerResponse, next: ServerNext) {\n if (\n this.platformBundlers.web === 'metro' &&\n this.initialProjectConfig.exp.platforms?.includes('web')\n ) {\n // NOTE(EvanBacon): This effectively disables the safety check we do on custom runtimes to ensure\n // the `expo-platform` header is included. When `web.bundler=web`, if the user has non-standard Expo\n // code loading then they'll get a web bundle without a clear assertion of platform support.\n const platform = parsePlatformHeader(req);\n // On web, serve the public folder\n if (!platform || platform === 'web') {\n if (['static', 'server'].includes(this.initialProjectConfig.exp.web?.output ?? '')) {\n // Skip the spa-styled index.html when static generation is enabled.\n next();\n return true;\n } else {\n await this.handleWebRequestAsync(req, res);\n return true;\n }\n }\n }\n return false;\n }\n\n async handleRequestAsync(\n req: ServerRequest,\n res: ServerResponse,\n next: ServerNext\n ): Promise<void> {\n // First check for standard JavaScript runtimes (aka legacy browsers like Chrome).\n if (await this.checkBrowserRequestAsync(req, res, next)) {\n return;\n }\n\n // Save device IDs for dev client.\n await this.saveDevicesAsync(req);\n\n // Read from headers\n const options = this.getParsedHeaders(req);\n const { body, version, headers } = await this._getManifestResponseAsync(options);\n for (const [headerName, headerValue] of headers) {\n res.setHeader(headerName, headerValue);\n }\n res.end(body);\n\n // Log analytics\n this.trackManifest(version ?? null);\n }\n}\n"],"names":["getWorkspaceRoot","getEntryWithServerRoot","getMetroServerRoot","resolveMainModuleName","Log","ProjectDevices","debug","require","projectRoot","findWorkspaceRoot","error","message","includes","supportedPlatforms","props","platform","CommandError","path","relative","resolveEntryPoint","env","EXPO_USE_METRO_WORKSPACE_ROOT","entryPoint","stripExtension","DEVELOPER_TOOL","ManifestMiddleware","ExpoMiddleware","constructor","options","initialProjectConfig","getConfig","platformBundlers","getPlatformBundlers","exp","_resolveProjectSettingsAsync","hostname","protocol","projectConfig","mainModuleName","pkg","isHermesEnabled","isEnableHermesManaged","expoGoConfig","getExpoGoConfig","hostUri","constructUrl","scheme","bundleUrl","_getBundleUrl","engine","undefined","baseUrl","getBaseUrlFromExpoConfig","asyncRoutes","getAsyncRoutesFromExpoConfig","mode","routerRoot","getRouterDirectoryModuleIdWithManifest","mutateManifestWithAssetsAsync","isNativeWebpack","saveDevicesAsync","req","deviceIds","headers","catch","e","exception","isExporting","createBundleUrlPath","minify","lazy","shouldEnableAsyncImports","bytecode","debuggerHost","developer","tool","packagerOpts","dev","__flipperHack","manifest","resolveManifestAssets","resolver","resolve","match","resolveGoogleServicesFile","getWebBundleUrl","createBundleUrlPathFromExpoConfig","handleWebRequestAsync","res","setHeader","end","createTemplateHtmlFromExpoConfigAsync","scripts","checkBrowserRequestAsync","next","web","platforms","parsePlatformHeader","output","handleRequestAsync","getParsedHeaders","body","version","_getManifestResponseAsync","headerName","headerValue","trackManifest"],"mappings":"AAAA;;;;QAqCgBA,gBAAgB,GAAhBA,gBAAgB;QAahBC,sBAAsB,GAAtBA,sBAAsB;QAYtBC,kBAAkB,GAAlBA,kBAAkB;QASlBC,qBAAqB,GAArBA,qBAA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AAChC,GAAG,EAAE2B,GAAG,EAAEM,IAAI,CAAC,EAAE;YACvD,OAAO;SACR;QAED,kCAAkC;QAClC,MAAM,IAAI,CAAClC,gBAAgB,CAACC,GAAG,CAAC,CAAC;QAEjC,oBAAoB;QACpB,MAAMjC,OAAO,GAAG,IAAI,CAACwE,gBAAgB,CAACvC,GAAG,CAAC,AAAC;QAC3C,MAAM,EAAEwC,IAAI,CAAA,EAAEC,OAAO,CAAA,EAAEvC,OAAO,CAAA,EAAE,GAAG,MAAM,IAAI,CAACwC,yBAAyB,CAAC3E,OAAO,CAAC,AAAC;QACjF,KAAK,MAAM,CAAC4E,UAAU,EAAEC,WAAW,CAAC,IAAI1C,OAAO,CAAE;YAC/CyB,GAAG,CAACC,SAAS,CAACe,UAAU,EAAEC,WAAW,CAAC,CAAC;SACxC;QACDjB,GAAG,CAACE,GAAG,CAACW,IAAI,CAAC,CAAC;QAEd,gBAAgB;QAChB,IAAI,CAACK,aAAa,CAACJ,OAAO,WAAPA,OAAO,GAAI,IAAI,CAAC,CAAC;KACrC;CACF;QA1SqB7E,kBAAkB,GAAlBA,kBAAkB"}
@@ -11,6 +11,7 @@ exports.createBundleUrlPathFromExpoConfig = createBundleUrlPathFromExpoConfig;
11
11
  exports.createBundleUrlPath = createBundleUrlPath;
12
12
  var _resolveFrom = _interopRequireDefault(require("resolve-from"));
13
13
  var _env = require("../../../utils/env");
14
+ var _errors = require("../../../utils/errors");
14
15
  var _router = require("../metro/router");
15
16
  function _interopRequireDefault(obj) {
16
17
  return obj && obj.__esModule ? obj : {
@@ -29,6 +30,14 @@ function shouldEnableAsyncImports(projectRoot) {
29
30
  return _resolveFrom.default.silent(projectRoot, "@expo/metro-runtime") != null;
30
31
  }
31
32
  function withDefaults({ mode ="development" , minify =mode === "production" , preserveEnvVars =_env.env.EXPO_NO_CLIENT_ENV_VARS , lazy , ...props }) {
33
+ if (props.bytecode) {
34
+ if (props.platform === "web") {
35
+ throw new _errors.CommandError("Cannot use bytecode with the web platform");
36
+ }
37
+ if (props.engine !== "hermes") {
38
+ throw new _errors.CommandError("Bytecode is only supported with the Hermes engine");
39
+ }
40
+ }
32
41
  return {
33
42
  mode,
34
43
  minify,
@@ -72,7 +81,7 @@ function getMetroDirectBundleOptionsForExpoConfig(projectRoot, exp, options) {
72
81
  });
73
82
  }
74
83
  function getMetroDirectBundleOptions(options) {
75
- const { mainModuleName , platform , mode , minify , environment , serializerOutput , serializerIncludeMaps , serializerIncludeBytecode , lazy , engine , preserveEnvVars , asyncRoutes , baseUrl , routerRoot , isExporting , inlineSourceMap , } = withDefaults(options);
84
+ const { mainModuleName , platform , mode , minify , environment , serializerOutput , serializerIncludeMaps , bytecode , lazy , engine , preserveEnvVars , asyncRoutes , baseUrl , routerRoot , isExporting , inlineSourceMap , } = withDefaults(options);
76
85
  const dev = mode !== "production";
77
86
  const isHermes = engine === "hermes";
78
87
  if (isExporting) {
@@ -82,7 +91,7 @@ function getMetroDirectBundleOptions(options) {
82
91
  let fakeSourceUrl;
83
92
  let fakeSourceMapUrl;
84
93
  // TODO: Upstream support to Metro for passing custom serializer options.
85
- if (serializerIncludeMaps != null || serializerOutput != null || serializerIncludeBytecode != null) {
94
+ if (serializerIncludeMaps != null || serializerOutput != null) {
86
95
  fakeSourceUrl = new URL(createBundleUrlPath(options).replace(/^\//, ""), "http://localhost:8081").toString();
87
96
  if (serializerIncludeMaps) {
88
97
  fakeSourceMapUrl = fakeSourceUrl.replace(".bundle?", ".map?");
@@ -92,7 +101,7 @@ function getMetroDirectBundleOptions(options) {
92
101
  platform,
93
102
  entryFile: mainModuleName,
94
103
  dev,
95
- minify: !isHermes && (minify != null ? minify : !dev),
104
+ minify: minify != null ? minify : !dev,
96
105
  inlineSourceMap: inlineSourceMap != null ? inlineSourceMap : false,
97
106
  lazy,
98
107
  unstable_transformProfile: isHermes ? "hermes-stable" : "default",
@@ -103,7 +112,8 @@ function getMetroDirectBundleOptions(options) {
103
112
  asyncRoutes,
104
113
  environment,
105
114
  baseUrl,
106
- routerRoot
115
+ routerRoot,
116
+ bytecode
107
117
  },
108
118
  customResolverOptions: {
109
119
  __proto__: null,
@@ -113,8 +123,7 @@ function getMetroDirectBundleOptions(options) {
113
123
  sourceUrl: fakeSourceUrl,
114
124
  serializerOptions: {
115
125
  output: serializerOutput,
116
- includeSourceMaps: serializerIncludeMaps,
117
- includeBytecode: serializerIncludeBytecode
126
+ includeSourceMaps: serializerIncludeMaps
118
127
  }
119
128
  };
120
129
  return bundleOptions;
@@ -127,7 +136,7 @@ function createBundleUrlPathFromExpoConfig(projectRoot, exp, options) {
127
136
  });
128
137
  }
129
138
  function createBundleUrlPath(options) {
130
- const { platform , mainModuleName , mode , minify , environment , serializerOutput , serializerIncludeMaps , serializerIncludeBytecode , lazy , engine , preserveEnvVars , asyncRoutes , baseUrl , routerRoot , inlineSourceMap , isExporting , } = withDefaults(options);
139
+ const { platform , mainModuleName , mode , minify , environment , serializerOutput , serializerIncludeMaps , lazy , bytecode , engine , preserveEnvVars , asyncRoutes , baseUrl , routerRoot , inlineSourceMap , isExporting , } = withDefaults(options);
131
140
  const dev = String(mode !== "production");
132
141
  const queryParams = new URLSearchParams({
133
142
  platform: encodeURIComponent(platform),
@@ -145,9 +154,15 @@ function createBundleUrlPath(options) {
145
154
  if (minify) {
146
155
  queryParams.append("minify", String(minify));
147
156
  }
157
+ // We split bytecode from the engine since you could technically use Hermes without bytecode.
158
+ // Hermes indicates the type of language features you want to transform out of the JS, whereas bytecode
159
+ // indicates whether you want to use the Hermes bytecode format.
148
160
  if (engine) {
149
161
  queryParams.append("transform.engine", engine);
150
162
  }
163
+ if (bytecode) {
164
+ queryParams.append("transform.bytecode", String(bytecode));
165
+ }
151
166
  if (asyncRoutes) {
152
167
  queryParams.append("transform.asyncRoutes", String(asyncRoutes));
153
168
  }
@@ -170,9 +185,6 @@ function createBundleUrlPath(options) {
170
185
  if (serializerIncludeMaps) {
171
186
  queryParams.append("serializer.map", String(serializerIncludeMaps));
172
187
  }
173
- if (serializerIncludeBytecode) {
174
- queryParams.append("serializer.bytecode", String(serializerIncludeBytecode));
175
- }
176
188
  return `/${encodeURI(mainModuleName)}.bundle?${queryParams.toString()}`;
177
189
  }
178
190
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/middleware/metroOptions.ts"],"sourcesContent":["import { ExpoConfig } from '@expo/config';\nimport type { BundleOptions as MetroBundleOptions } from 'metro/src/shared/types';\nimport resolveFrom from 'resolve-from';\n\nimport { env } from '../../../utils/env';\nimport { getRouterDirectoryModuleIdWithManifest } from '../metro/router';\n\nconst debug = require('debug')('expo:metro:options') as typeof console.log;\n\nexport type ExpoMetroOptions = {\n platform: string;\n mainModuleName: string;\n mode: string;\n minify?: boolean;\n environment?: string;\n serializerOutput?: 'static';\n serializerIncludeMaps?: boolean;\n serializerIncludeBytecode?: boolean;\n lazy?: boolean;\n engine?: 'hermes';\n preserveEnvVars?: boolean;\n asyncRoutes?: boolean;\n\n baseUrl?: string;\n isExporting: boolean;\n /** Module ID relative to the projectRoot for the Expo Router app directory. */\n routerRoot: string;\n inlineSourceMap?: boolean;\n};\n\nexport type SerializerOptions = {\n includeSourceMaps?: boolean;\n includeBytecode?: boolean;\n output?: 'static';\n};\n\nexport type ExpoMetroBundleOptions = MetroBundleOptions & {\n serializerOptions?: SerializerOptions;\n};\n\nexport function shouldEnableAsyncImports(projectRoot: string): boolean {\n if (env.EXPO_NO_METRO_LAZY) {\n return false;\n }\n\n // `@expo/metro-runtime` includes support for the fetch + eval runtime code required\n // to support async imports. If it's not installed, we can't support async imports.\n // If it is installed, the user MUST import it somewhere in their project.\n // Expo Router automatically pulls this in, so we can check for it.\n return resolveFrom.silent(projectRoot, '@expo/metro-runtime') != null;\n}\n\nfunction withDefaults({\n mode = 'development',\n minify = mode === 'production',\n preserveEnvVars = env.EXPO_NO_CLIENT_ENV_VARS,\n lazy,\n ...props\n}: ExpoMetroOptions): ExpoMetroOptions {\n return {\n mode,\n minify,\n preserveEnvVars,\n lazy: !props.isExporting && lazy,\n ...props,\n };\n}\n\nexport function getBaseUrlFromExpoConfig(exp: ExpoConfig) {\n return exp.experiments?.baseUrl?.trim().replace(/\\/+$/, '') ?? '';\n}\nexport function getAsyncRoutesFromExpoConfig(exp: ExpoConfig, mode: string, platform: string) {\n let asyncRoutesSetting;\n\n if (exp.extra?.router?.asyncRoutes) {\n const asyncRoutes = exp.extra?.router?.asyncRoutes;\n if (['boolean', 'string'].includes(typeof asyncRoutes)) {\n asyncRoutesSetting = asyncRoutes;\n } else if (typeof asyncRoutes === 'object') {\n asyncRoutesSetting = asyncRoutes[platform] ?? asyncRoutes.default;\n }\n }\n\n return [mode, true].includes(asyncRoutesSetting);\n}\n\nexport function getMetroDirectBundleOptionsForExpoConfig(\n projectRoot: string,\n exp: ExpoConfig,\n options: Omit<ExpoMetroOptions, 'baseUrl' | 'routerRoot' | 'asyncRoutes'>\n): Partial<ExpoMetroBundleOptions> {\n return getMetroDirectBundleOptions({\n ...options,\n baseUrl: getBaseUrlFromExpoConfig(exp),\n routerRoot: getRouterDirectoryModuleIdWithManifest(projectRoot, exp),\n asyncRoutes: getAsyncRoutesFromExpoConfig(exp, options.mode, options.platform),\n });\n}\n\nexport function getMetroDirectBundleOptions(\n options: ExpoMetroOptions\n): Partial<ExpoMetroBundleOptions> {\n const {\n mainModuleName,\n platform,\n mode,\n minify,\n environment,\n serializerOutput,\n serializerIncludeMaps,\n serializerIncludeBytecode,\n lazy,\n engine,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n inlineSourceMap,\n } = withDefaults(options);\n\n const dev = mode !== 'production';\n const isHermes = engine === 'hermes';\n\n if (isExporting) {\n debug('Disabling lazy bundling for export build');\n options.lazy = false;\n }\n\n let fakeSourceUrl: string | undefined;\n let fakeSourceMapUrl: string | undefined;\n\n // TODO: Upstream support to Metro for passing custom serializer options.\n if (\n serializerIncludeMaps != null ||\n serializerOutput != null ||\n serializerIncludeBytecode != null\n ) {\n fakeSourceUrl = new URL(\n createBundleUrlPath(options).replace(/^\\//, ''),\n 'http://localhost:8081'\n ).toString();\n if (serializerIncludeMaps) {\n fakeSourceMapUrl = fakeSourceUrl.replace('.bundle?', '.map?');\n }\n }\n\n const bundleOptions: Partial<ExpoMetroBundleOptions> = {\n platform,\n entryFile: mainModuleName,\n dev,\n minify: !isHermes && (minify ?? !dev),\n inlineSourceMap: inlineSourceMap ?? false,\n lazy,\n unstable_transformProfile: isHermes ? 'hermes-stable' : 'default',\n customTransformOptions: {\n __proto__: null,\n engine,\n preserveEnvVars,\n asyncRoutes,\n environment,\n baseUrl,\n routerRoot,\n },\n customResolverOptions: {\n __proto__: null,\n environment,\n },\n sourceMapUrl: fakeSourceMapUrl,\n sourceUrl: fakeSourceUrl,\n serializerOptions: {\n output: serializerOutput,\n includeSourceMaps: serializerIncludeMaps,\n includeBytecode: serializerIncludeBytecode,\n },\n };\n\n return bundleOptions;\n}\n\nexport function createBundleUrlPathFromExpoConfig(\n projectRoot: string,\n exp: ExpoConfig,\n options: Omit<ExpoMetroOptions, 'baseUrl' | 'routerRoot'>\n): string {\n return createBundleUrlPath({\n ...options,\n baseUrl: getBaseUrlFromExpoConfig(exp),\n routerRoot: getRouterDirectoryModuleIdWithManifest(projectRoot, exp),\n });\n}\n\nexport function createBundleUrlPath(options: ExpoMetroOptions): string {\n const {\n platform,\n mainModuleName,\n mode,\n minify,\n environment,\n serializerOutput,\n serializerIncludeMaps,\n serializerIncludeBytecode,\n lazy,\n engine,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n inlineSourceMap,\n isExporting,\n } = withDefaults(options);\n\n const dev = String(mode !== 'production');\n const queryParams = new URLSearchParams({\n platform: encodeURIComponent(platform),\n dev,\n // TODO: Is this still needed?\n hot: String(false),\n });\n\n // Lazy bundling must be disabled for bundle splitting to work.\n if (!isExporting && lazy) {\n queryParams.append('lazy', String(lazy));\n }\n\n if (inlineSourceMap) {\n queryParams.append('inlineSourceMap', String(inlineSourceMap));\n }\n\n if (minify) {\n queryParams.append('minify', String(minify));\n }\n\n if (engine) {\n queryParams.append('transform.engine', engine);\n }\n\n if (asyncRoutes) {\n queryParams.append('transform.asyncRoutes', String(asyncRoutes));\n }\n if (preserveEnvVars) {\n queryParams.append('transform.preserveEnvVars', String(preserveEnvVars));\n }\n if (baseUrl) {\n queryParams.append('transform.baseUrl', baseUrl);\n }\n if (routerRoot != null) {\n queryParams.append('transform.routerRoot', routerRoot);\n }\n\n if (environment) {\n queryParams.append('resolver.environment', environment);\n queryParams.append('transform.environment', environment);\n }\n\n if (serializerOutput) {\n queryParams.append('serializer.output', serializerOutput);\n }\n if (serializerIncludeMaps) {\n queryParams.append('serializer.map', String(serializerIncludeMaps));\n }\n if (serializerIncludeBytecode) {\n queryParams.append('serializer.bytecode', String(serializerIncludeBytecode));\n }\n\n return `/${encodeURI(mainModuleName)}.bundle?${queryParams.toString()}`;\n}\n"],"names":["shouldEnableAsyncImports","getBaseUrlFromExpoConfig","getAsyncRoutesFromExpoConfig","getMetroDirectBundleOptionsForExpoConfig","getMetroDirectBundleOptions","createBundleUrlPathFromExpoConfig","createBundleUrlPath","debug","require","projectRoot","env","EXPO_NO_METRO_LAZY","resolveFrom","silent","withDefaults","mode","minify","preserveEnvVars","EXPO_NO_CLIENT_ENV_VARS","lazy","props","isExporting","exp","experiments","baseUrl","trim","replace","platform","asyncRoutesSetting","extra","router","asyncRoutes","includes","default","options","routerRoot","getRouterDirectoryModuleIdWithManifest","mainModuleName","environment","serializerOutput","serializerIncludeMaps","serializerIncludeBytecode","engine","inlineSourceMap","dev","isHermes","fakeSourceUrl","fakeSourceMapUrl","URL","toString","bundleOptions","entryFile","unstable_transformProfile","customTransformOptions","__proto__","customResolverOptions","sourceMapUrl","sourceUrl","serializerOptions","output","includeSourceMaps","includeBytecode","String","queryParams","URLSearchParams","encodeURIComponent","hot","append","encodeURI"],"mappings":"AAAA;;;;QAwCgBA,wBAAwB,GAAxBA,wBAAwB;Q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mB,EAAE3C,OAAO,CAAC,CAAC;KAClD;IACD,IAAIW,UAAU,IAAI,IAAI,EAAE;QACtB4B,WAAW,CAACI,MAAM,CAAC,sBAAsB,EAAEhC,UAAU,CAAC,CAAC;KACxD;IAED,IAAIG,WAAW,EAAE;QACfyB,WAAW,CAACI,MAAM,CAAC,sBAAsB,EAAE7B,WAAW,CAAC,CAAC;QACxDyB,WAAW,CAACI,MAAM,CAAC,uBAAuB,EAAE7B,WAAW,CAAC,CAAC;KAC1D;IAED,IAAIC,gBAAgB,EAAE;QACpBwB,WAAW,CAACI,MAAM,CAAC,mBAAmB,EAAE5B,gBAAgB,CAAC,CAAC;KAC3D;IACD,IAAIC,qBAAqB,EAAE;QACzBuB,WAAW,CAACI,MAAM,CAAC,gBAAgB,EAAEL,MAAM,CAACtB,qBAAqB,CAAC,CAAC,CAAC;KACrE;IACD,IAAIC,yBAAyB,EAAE;QAC7BsB,WAAW,CAACI,MAAM,CAAC,qBAAqB,EAAEL,MAAM,CAACrB,yBAAyB,CAAC,CAAC,CAAC;KAC9E;IAED,OAAO,CAAC,CAAC,EAAE2B,SAAS,CAAC/B,cAAc,CAAC,CAAC,QAAQ,EAAE0B,WAAW,CAACd,QAAQ,EAAE,CAAC,CAAC,CAAC;CACzE"}
1
+ {"version":3,"sources":["../../../../../src/start/server/middleware/metroOptions.ts"],"sourcesContent":["import { ExpoConfig } from '@expo/config';\nimport type { BundleOptions as MetroBundleOptions } from 'metro/src/shared/types';\nimport resolveFrom from 'resolve-from';\n\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { getRouterDirectoryModuleIdWithManifest } from '../metro/router';\n\nconst debug = require('debug')('expo:metro:options') as typeof console.log;\n\nexport type ExpoMetroOptions = {\n platform: string;\n mainModuleName: string;\n mode: string;\n minify?: boolean;\n environment?: string;\n serializerOutput?: 'static';\n serializerIncludeMaps?: boolean;\n lazy?: boolean;\n engine?: 'hermes';\n preserveEnvVars?: boolean;\n bytecode: boolean;\n asyncRoutes?: boolean;\n\n baseUrl?: string;\n isExporting: boolean;\n /** Module ID relative to the projectRoot for the Expo Router app directory. */\n routerRoot: string;\n inlineSourceMap?: boolean;\n};\n\nexport type SerializerOptions = {\n includeSourceMaps?: boolean;\n output?: 'static';\n};\n\nexport type ExpoMetroBundleOptions = MetroBundleOptions & {\n serializerOptions?: SerializerOptions;\n};\n\nexport function shouldEnableAsyncImports(projectRoot: string): boolean {\n if (env.EXPO_NO_METRO_LAZY) {\n return false;\n }\n\n // `@expo/metro-runtime` includes support for the fetch + eval runtime code required\n // to support async imports. If it's not installed, we can't support async imports.\n // If it is installed, the user MUST import it somewhere in their project.\n // Expo Router automatically pulls this in, so we can check for it.\n return resolveFrom.silent(projectRoot, '@expo/metro-runtime') != null;\n}\n\nfunction withDefaults({\n mode = 'development',\n minify = mode === 'production',\n preserveEnvVars = env.EXPO_NO_CLIENT_ENV_VARS,\n lazy,\n ...props\n}: ExpoMetroOptions): ExpoMetroOptions {\n if (props.bytecode) {\n if (props.platform === 'web') {\n throw new CommandError('Cannot use bytecode with the web platform');\n }\n if (props.engine !== 'hermes') {\n throw new CommandError('Bytecode is only supported with the Hermes engine');\n }\n }\n\n return {\n mode,\n minify,\n preserveEnvVars,\n lazy: !props.isExporting && lazy,\n ...props,\n };\n}\n\nexport function getBaseUrlFromExpoConfig(exp: ExpoConfig) {\n return exp.experiments?.baseUrl?.trim().replace(/\\/+$/, '') ?? '';\n}\nexport function getAsyncRoutesFromExpoConfig(exp: ExpoConfig, mode: string, platform: string) {\n let asyncRoutesSetting;\n\n if (exp.extra?.router?.asyncRoutes) {\n const asyncRoutes = exp.extra?.router?.asyncRoutes;\n if (['boolean', 'string'].includes(typeof asyncRoutes)) {\n asyncRoutesSetting = asyncRoutes;\n } else if (typeof asyncRoutes === 'object') {\n asyncRoutesSetting = asyncRoutes[platform] ?? asyncRoutes.default;\n }\n }\n\n return [mode, true].includes(asyncRoutesSetting);\n}\n\nexport function getMetroDirectBundleOptionsForExpoConfig(\n projectRoot: string,\n exp: ExpoConfig,\n options: Omit<ExpoMetroOptions, 'baseUrl' | 'routerRoot' | 'asyncRoutes'>\n): Partial<ExpoMetroBundleOptions> {\n return getMetroDirectBundleOptions({\n ...options,\n baseUrl: getBaseUrlFromExpoConfig(exp),\n routerRoot: getRouterDirectoryModuleIdWithManifest(projectRoot, exp),\n asyncRoutes: getAsyncRoutesFromExpoConfig(exp, options.mode, options.platform),\n });\n}\n\nexport function getMetroDirectBundleOptions(\n options: ExpoMetroOptions\n): Partial<ExpoMetroBundleOptions> {\n const {\n mainModuleName,\n platform,\n mode,\n minify,\n environment,\n serializerOutput,\n serializerIncludeMaps,\n bytecode,\n lazy,\n engine,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n inlineSourceMap,\n } = withDefaults(options);\n\n const dev = mode !== 'production';\n const isHermes = engine === 'hermes';\n\n if (isExporting) {\n debug('Disabling lazy bundling for export build');\n options.lazy = false;\n }\n\n let fakeSourceUrl: string | undefined;\n let fakeSourceMapUrl: string | undefined;\n\n // TODO: Upstream support to Metro for passing custom serializer options.\n if (serializerIncludeMaps != null || serializerOutput != null) {\n fakeSourceUrl = new URL(\n createBundleUrlPath(options).replace(/^\\//, ''),\n 'http://localhost:8081'\n ).toString();\n if (serializerIncludeMaps) {\n fakeSourceMapUrl = fakeSourceUrl.replace('.bundle?', '.map?');\n }\n }\n\n const bundleOptions: Partial<ExpoMetroBundleOptions> = {\n platform,\n entryFile: mainModuleName,\n dev,\n minify: minify ?? !dev,\n inlineSourceMap: inlineSourceMap ?? false,\n lazy,\n unstable_transformProfile: isHermes ? 'hermes-stable' : 'default',\n customTransformOptions: {\n __proto__: null,\n engine,\n preserveEnvVars,\n asyncRoutes,\n environment,\n baseUrl,\n routerRoot,\n bytecode,\n },\n customResolverOptions: {\n __proto__: null,\n environment,\n },\n sourceMapUrl: fakeSourceMapUrl,\n sourceUrl: fakeSourceUrl,\n serializerOptions: {\n output: serializerOutput,\n includeSourceMaps: serializerIncludeMaps,\n },\n };\n\n return bundleOptions;\n}\n\nexport function createBundleUrlPathFromExpoConfig(\n projectRoot: string,\n exp: ExpoConfig,\n options: Omit<ExpoMetroOptions, 'baseUrl' | 'routerRoot'>\n): string {\n return createBundleUrlPath({\n ...options,\n baseUrl: getBaseUrlFromExpoConfig(exp),\n routerRoot: getRouterDirectoryModuleIdWithManifest(projectRoot, exp),\n });\n}\n\nexport function createBundleUrlPath(options: ExpoMetroOptions): string {\n const {\n platform,\n mainModuleName,\n mode,\n minify,\n environment,\n serializerOutput,\n serializerIncludeMaps,\n lazy,\n bytecode,\n engine,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n inlineSourceMap,\n isExporting,\n } = withDefaults(options);\n\n const dev = String(mode !== 'production');\n const queryParams = new URLSearchParams({\n platform: encodeURIComponent(platform),\n dev,\n // TODO: Is this still needed?\n hot: String(false),\n });\n\n // Lazy bundling must be disabled for bundle splitting to work.\n if (!isExporting && lazy) {\n queryParams.append('lazy', String(lazy));\n }\n\n if (inlineSourceMap) {\n queryParams.append('inlineSourceMap', String(inlineSourceMap));\n }\n\n if (minify) {\n queryParams.append('minify', String(minify));\n }\n\n // We split bytecode from the engine since you could technically use Hermes without bytecode.\n // Hermes indicates the type of language features you want to transform out of the JS, whereas bytecode\n // indicates whether you want to use the Hermes bytecode format.\n if (engine) {\n queryParams.append('transform.engine', engine);\n }\n if (bytecode) {\n queryParams.append('transform.bytecode', String(bytecode));\n }\n\n if (asyncRoutes) {\n queryParams.append('transform.asyncRoutes', String(asyncRoutes));\n }\n if (preserveEnvVars) {\n queryParams.append('transform.preserveEnvVars', String(preserveEnvVars));\n }\n if (baseUrl) {\n queryParams.append('transform.baseUrl', baseUrl);\n }\n if (routerRoot != null) {\n queryParams.append('transform.routerRoot', routerRoot);\n }\n\n if (environment) {\n queryParams.append('resolver.environment', environment);\n queryParams.append('transform.environment', environment);\n }\n\n if (serializerOutput) {\n queryParams.append('serializer.output', serializerOutput);\n }\n if (serializerIncludeMaps) {\n queryParams.append('serializer.map', String(serializerIncludeMaps));\n }\n\n return `/${encodeURI(mainModuleName)}.bundle?${queryParams.toString()}`;\n}\n"],"names":["shouldEnableAsyncImports","getBaseUrlFromExpoConfig","getAsyncRoutesFromExpoConfig","getMetroDirectBundleOptionsForExpoConfig","getMetroDirectBundleOptions","createBundleUrlPathFromExpoConfig","createBundleUrlPath","debug","require","projectRoot","env","EXPO_NO_METRO_LAZY","resolveFrom","silent","withDefaults","mode","minify","preserveEnvVars","EXPO_NO_CLIENT_ENV_VARS","lazy","props","bytecode","platform","CommandError","engine","isExporting","exp","experiments","baseUrl","trim","replace","asyncRoutesSetting","extra","router","asyncRoutes","includes","default","options","routerRoot","getRouterDirectoryModuleIdWithManifest","mainModuleName","environment","serializerOutput","serializerIncludeMaps","inlineSourceMap","dev","isHermes","fakeSourceUrl","fakeSourceMapUrl","URL","toString","bundleOptions","entryFile","unstable_transformProfile","customTransformOptions","__proto__","customResolverOptions","sourceMapUrl","sourceUrl","serializerOptions","output","includeSourceMaps","String","queryParams","URLSearchParams","encodeURIComponent","hot","append","encodeURI"],"mappings":"AAAA;;;;QAwCgBA,wBAAwB,GAAxBA,wBAAwB;QAqCxBC,wBAAwB,GAAxBA,wBAAwB;QAGxBC,4BAA4B,GAA5BA,4BAA4B;QAe5BC,wCAAwC,GAAxCA,wCAAwC;QAaxCC,2BAA2B,GAA3BA,2BAA2B;QA6E3BC,iCAAiC,GAAjCA,iCAAiC;QAYjCC,mBAAmB,GAAnBA,mBAAmB;AAnMX,IAAA,YAAc,kCAAd,cAAc,EAAA;AAElB,IAAA,IAAoB,WAApB,oBAAoB,CAAA;AACX,IAAA,OAAuB,WAAvB,uBAAuB,CAAA;AACG,IAAA,OAAiB,WAAjB,iBAAiB,CAAA;;;;;;AAExE,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,oBAAoB,CAAC,AAAsB,AAAC;AAgCpE,SA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