@expo/cli 0.12.0 → 0.13.1

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 (111) hide show
  1. package/build/bin/cli +2 -2
  2. package/build/src/export/createBundles.js +0 -30
  3. package/build/src/export/createBundles.js.map +1 -1
  4. package/build/src/export/createMetadataJson.js +1 -0
  5. package/build/src/export/createMetadataJson.js.map +1 -1
  6. package/build/src/export/embed/exportEmbedAsync.js +2 -0
  7. package/build/src/export/embed/exportEmbedAsync.js.map +1 -1
  8. package/build/src/export/exportApp.js +42 -15
  9. package/build/src/export/exportApp.js.map +1 -1
  10. package/build/src/export/exportAssets.js +2 -2
  11. package/build/src/export/exportAssets.js.map +1 -1
  12. package/build/src/export/exportHermes.js +204 -0
  13. package/build/src/export/exportHermes.js.map +1 -0
  14. package/build/src/export/exportStaticAsync.js +58 -3
  15. package/build/src/export/exportStaticAsync.js.map +1 -1
  16. package/build/src/export/favicon.js +7 -7
  17. package/build/src/export/favicon.js.map +1 -1
  18. package/build/src/export/fork-bundleAsync.js +9 -11
  19. package/build/src/export/fork-bundleAsync.js.map +1 -1
  20. package/build/src/export/persistMetroAssets.js +118 -0
  21. package/build/src/export/persistMetroAssets.js.map +1 -0
  22. package/build/src/export/saveAssets.js.map +1 -1
  23. package/build/src/export/writeContents.js +2 -2
  24. package/build/src/export/writeContents.js.map +1 -1
  25. package/build/src/install/index.js +1 -0
  26. package/build/src/install/index.js.map +1 -1
  27. package/build/src/install/installAsync.js +1 -0
  28. package/build/src/install/installAsync.js.map +1 -1
  29. package/build/src/install/resolveOptions.js +7 -4
  30. package/build/src/install/resolveOptions.js.map +1 -1
  31. package/build/src/prebuild/index.js +2 -0
  32. package/build/src/prebuild/index.js.map +1 -1
  33. package/build/src/prebuild/prebuildAsync.js +2 -1
  34. package/build/src/prebuild/prebuildAsync.js.map +1 -1
  35. package/build/src/prebuild/resolveOptions.js +4 -2
  36. package/build/src/prebuild/resolveOptions.js.map +1 -1
  37. package/build/src/run/android/runAndroidAsync.js +5 -0
  38. package/build/src/run/android/runAndroidAsync.js.map +1 -1
  39. package/build/src/run/ios/runIosAsync.js +5 -0
  40. package/build/src/run/ios/runIosAsync.js.map +1 -1
  41. package/build/src/start/interface/interactiveActions.js +3 -3
  42. package/build/src/start/interface/interactiveActions.js.map +1 -1
  43. package/build/src/start/server/BundlerDevServer.js.map +1 -1
  44. package/build/src/start/server/getStaticRenderFunctions.js +7 -12
  45. package/build/src/start/server/getStaticRenderFunctions.js.map +1 -1
  46. package/build/src/start/server/metro/MetroBundlerDevServer.js +78 -54
  47. package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
  48. package/build/src/start/server/metro/MetroTerminalReporter.js +1 -1
  49. package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
  50. package/build/src/start/server/metro/bundleApiRoutes.js +67 -0
  51. package/build/src/start/server/metro/bundleApiRoutes.js.map +1 -0
  52. package/build/src/start/server/metro/createServerRouteMiddleware.js +112 -0
  53. package/build/src/start/server/metro/createServerRouteMiddleware.js.map +1 -0
  54. package/build/src/start/server/metro/fetchRouterManifest.js +60 -0
  55. package/build/src/start/server/metro/fetchRouterManifest.js.map +1 -0
  56. package/build/src/start/server/metro/instantiateMetro.js +31 -11
  57. package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
  58. package/build/src/start/server/metro/metroErrorInterface.js +70 -10
  59. package/build/src/start/server/metro/metroErrorInterface.js.map +1 -1
  60. package/build/src/start/server/metro/resolveFromProject.js +13 -0
  61. package/build/src/start/server/metro/resolveFromProject.js.map +1 -1
  62. package/build/src/start/server/metro/router.js +32 -0
  63. package/build/src/start/server/metro/router.js.map +1 -1
  64. package/build/src/start/server/metro/waitForMetroToObserveTypeScriptFile.js +22 -0
  65. package/build/src/start/server/metro/waitForMetroToObserveTypeScriptFile.js.map +1 -1
  66. package/build/src/start/server/metro/withMetroMultiPlatform.js +18 -1
  67. package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
  68. package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js +1 -1
  69. package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js.map +1 -1
  70. package/build/src/start/server/middleware/InterstitialPageMiddleware.js +3 -3
  71. package/build/src/start/server/middleware/InterstitialPageMiddleware.js.map +1 -1
  72. package/build/src/start/server/middleware/ManifestMiddleware.js +5 -1
  73. package/build/src/start/server/middleware/ManifestMiddleware.js.map +1 -1
  74. package/build/src/start/server/middleware/inspector/JsInspector.js +69 -0
  75. package/build/src/start/server/middleware/inspector/JsInspector.js.map +1 -0
  76. package/build/src/start/server/middleware/inspector/LaunchBrowser.js +57 -0
  77. package/build/src/start/server/middleware/inspector/LaunchBrowser.js.map +1 -0
  78. package/build/src/start/server/middleware/inspector/LaunchBrowser.types.js +13 -0
  79. package/build/src/start/server/middleware/inspector/LaunchBrowser.types.js.map +1 -0
  80. package/build/src/start/server/middleware/inspector/LaunchBrowserImplLinux.js +79 -0
  81. package/build/src/start/server/middleware/inspector/LaunchBrowserImplLinux.js.map +1 -0
  82. package/build/src/start/server/middleware/inspector/LaunchBrowserImplMacOS.js +78 -0
  83. package/build/src/start/server/middleware/inspector/LaunchBrowserImplMacOS.js.map +1 -0
  84. package/build/src/start/server/middleware/inspector/LaunchBrowserImplWindows.js +123 -0
  85. package/build/src/start/server/middleware/inspector/LaunchBrowserImplWindows.js.map +1 -0
  86. package/build/src/start/server/middleware/inspector/createJsInspectorMiddleware.js +64 -0
  87. package/build/src/start/server/middleware/inspector/createJsInspectorMiddleware.js.map +1 -0
  88. package/build/src/start/server/middleware/inspector/middlwareMutations.js +19 -0
  89. package/build/src/start/server/middleware/inspector/middlwareMutations.js.map +1 -0
  90. package/build/src/start/server/middleware/mutations.js +19 -0
  91. package/build/src/start/server/middleware/mutations.js.map +1 -0
  92. package/build/src/start/server/middleware/remoteDevtoolsCorsMiddleware.js +31 -0
  93. package/build/src/start/server/middleware/remoteDevtoolsCorsMiddleware.js.map +1 -0
  94. package/build/src/start/server/middleware/remoteDevtoolsSecurityHeadersMiddleware.js +17 -0
  95. package/build/src/start/server/middleware/remoteDevtoolsSecurityHeadersMiddleware.js.map +1 -0
  96. package/build/src/start/server/middleware/resolveAssets.js.map +1 -1
  97. package/build/src/start/server/middleware/suppressErrorMiddleware.js +16 -0
  98. package/build/src/start/server/middleware/suppressErrorMiddleware.js.map +1 -0
  99. package/build/src/start/server/type-generation/routes.js +3 -4
  100. package/build/src/start/server/type-generation/routes.js.map +1 -1
  101. package/build/src/start/server/type-generation/startTypescriptTypeGeneration.js +1 -3
  102. package/build/src/start/server/type-generation/startTypescriptTypeGeneration.js.map +1 -1
  103. package/build/src/start/server/webpack/WebpackBundlerDevServer.js +9 -82
  104. package/build/src/start/server/webpack/WebpackBundlerDevServer.js.map +1 -1
  105. package/build/src/utils/analytics/rudderstackClient.js +2 -2
  106. package/build/src/utils/codesigning.js.map +1 -1
  107. package/build/src/utils/port.js +45 -17
  108. package/build/src/utils/port.js.map +1 -1
  109. package/package.json +18 -12
  110. package/build/src/start/server/middleware/createDevServerMiddleware.js +0 -24
  111. package/build/src/start/server/middleware/createDevServerMiddleware.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/start/interface/interactiveActions.ts"],"sourcesContent":["import { openJsInspector, queryAllInspectorAppsAsync } from '@expo/dev-server';\nimport assert from 'assert';\nimport chalk from 'chalk';\n\nimport { BLT, printHelp, printItem, printQRCode, printUsage, StartOptions } from './commandsTable';\nimport * as Log from '../../log';\nimport { delayAsync } from '../../utils/delay';\nimport { learnMore } from '../../utils/link';\nimport { openBrowserAsync } from '../../utils/open';\nimport { selectAsync } from '../../utils/prompts';\nimport { DevServerManager } from '../server/DevServerManager';\nimport {\n addReactDevToolsReloadListener,\n startReactDevToolsProxyAsync,\n} from '../server/ReactDevToolsProxy';\n\nconst debug = require('debug')('expo:start:interface:interactiveActions') as typeof console.log;\n\n/** Wraps the DevServerManager and adds an interface for user actions. */\nexport class DevServerManagerActions {\n constructor(private devServerManager: DevServerManager) {}\n\n printDevServerInfo(\n options: Pick<StartOptions, 'devClient' | 'isWebSocketsEnabled' | 'platforms'>\n ) {\n // If native dev server is running, print its URL.\n if (this.devServerManager.getNativeDevServerPort()) {\n const devServer = this.devServerManager.getDefaultDevServer();\n try {\n const nativeRuntimeUrl = devServer.getNativeRuntimeUrl()!;\n const interstitialPageUrl = devServer.getRedirectUrl();\n\n printQRCode(interstitialPageUrl ?? nativeRuntimeUrl);\n\n if (interstitialPageUrl) {\n Log.log(\n printItem(\n chalk`Choose an app to open your project at {underline ${interstitialPageUrl}}`\n )\n );\n }\n Log.log(printItem(chalk`Metro waiting on {underline ${nativeRuntimeUrl}}`));\n if (options.devClient === false) {\n // TODO: if development build, change this message!\n Log.log(\n printItem('Scan the QR code above with Expo Go (Android) or the Camera app (iOS)')\n );\n } else {\n Log.log(\n printItem(\n 'Scan the QR code above to open the project in a development build. ' +\n learnMore('https://expo.fyi/start')\n )\n );\n }\n } catch (error) {\n console.log('err', error);\n // @ts-ignore: If there is no development build scheme, then skip the QR code.\n if (error.code !== 'NO_DEV_CLIENT_SCHEME') {\n throw error;\n } else {\n const serverUrl = devServer.getDevServerUrl();\n Log.log(printItem(chalk`Metro waiting on {underline ${serverUrl}}`));\n Log.log(printItem(`Linking is disabled because the client scheme cannot be resolved.`));\n }\n }\n }\n\n const webDevServer = this.devServerManager.getWebDevServer();\n const webUrl = webDevServer?.getDevServerUrl({ hostType: 'localhost' });\n if (webUrl) {\n Log.log();\n Log.log(printItem(chalk`Web is waiting on {underline ${webUrl}}`));\n }\n\n printUsage(options, { verbose: false });\n printHelp();\n Log.log();\n }\n\n async openJsInspectorAsync() {\n Log.log('Opening JavaScript inspector in the browser...');\n const metroServerOrigin = this.devServerManager.getDefaultDevServer().getJsInspectorBaseUrl();\n assert(metroServerOrigin, 'Metro dev server is not running');\n const apps = await queryAllInspectorAppsAsync(metroServerOrigin);\n if (!apps.length) {\n Log.warn(\n `No compatible apps connected. JavaScript Debugging can only be used with the Hermes engine. ${learnMore(\n 'https://docs.expo.dev/guides/using-hermes/'\n )}`\n );\n return;\n }\n try {\n for (const app of apps) {\n await openJsInspector(app);\n }\n } catch (error: any) {\n Log.error('Failed to open JavaScript inspector. This is often an issue with Google Chrome.');\n Log.exception(error);\n }\n }\n\n reloadApp() {\n Log.log(`${BLT} Reloading apps`);\n // Send reload requests over the dev servers\n this.devServerManager.broadcastMessage('reload');\n }\n\n async openMoreToolsAsync() {\n try {\n // Options match: Chrome > View > Developer\n const value = await selectAsync(chalk`Dev tools {dim (native only)}`, [\n { title: 'Inspect elements', value: 'toggleElementInspector' },\n { title: 'Toggle performance monitor', value: 'togglePerformanceMonitor' },\n { title: 'Toggle developer menu', value: 'toggleDevMenu' },\n { title: 'Reload app', value: 'reload' },\n { title: 'Start React devtools', value: 'startReactDevTools' },\n // TODO: Maybe a \"View Source\" option to open code.\n // Toggling Remote JS Debugging is pretty rough, so leaving it disabled.\n // { title: 'Toggle Remote Debugging', value: 'toggleRemoteDebugging' },\n ]);\n if (value === 'startReactDevTools') {\n this.startReactDevToolsAsync();\n } else {\n this.devServerManager.broadcastMessage('sendDevCommand', { name: value });\n }\n } catch (error: any) {\n debug(error);\n // do nothing\n } finally {\n printHelp();\n }\n }\n\n async startReactDevToolsAsync() {\n await startReactDevToolsProxyAsync();\n const url = this.devServerManager.getDefaultDevServer().getReactDevToolsUrl();\n await openBrowserAsync(url);\n addReactDevToolsReloadListener(() => {\n this.reconnectReactDevTools();\n });\n this.reconnectReactDevTools();\n }\n\n async reconnectReactDevTools() {\n // Wait a little time for react-devtools to be initialized in browser\n await delayAsync(3000);\n this.devServerManager.broadcastMessage('sendDevCommand', { name: 'reconnectReactDevTools' });\n }\n\n toggleDevMenu() {\n Log.log(`${BLT} Toggling dev menu`);\n this.devServerManager.broadcastMessage('devMenu');\n }\n}\n"],"names":["Log","debug","require","DevServerManagerActions","constructor","devServerManager","printDevServerInfo","options","getNativeDevServerPort","devServer","getDefaultDevServer","nativeRuntimeUrl","getNativeRuntimeUrl","interstitialPageUrl","getRedirectUrl","printQRCode","log","printItem","chalk","devClient","learnMore","error","console","code","serverUrl","getDevServerUrl","webDevServer","getWebDevServer","webUrl","hostType","printUsage","verbose","printHelp","openJsInspectorAsync","metroServerOrigin","getJsInspectorBaseUrl","assert","apps","queryAllInspectorAppsAsync","length","warn","app","openJsInspector","exception","reloadApp","BLT","broadcastMessage","openMoreToolsAsync","value","selectAsync","title","startReactDevToolsAsync","name","startReactDevToolsProxyAsync","url","getReactDevToolsUrl","openBrowserAsync","addReactDevToolsReloadListener","reconnectReactDevTools","delayAsync","toggleDevMenu"],"mappings":"AAAA;;;;AAA4D,IAAA,UAAkB,WAAlB,kBAAkB,CAAA;AAC3D,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACT,IAAA,MAAO,kCAAP,OAAO,EAAA;AAEwD,IAAA,cAAiB,WAAjB,iBAAiB,CAAA;AACtFA,IAAAA,GAAG,mCAAM,WAAW,EAAjB;AACY,IAAA,MAAmB,WAAnB,mBAAmB,CAAA;AACpB,IAAA,KAAkB,WAAlB,kBAAkB,CAAA;AACX,IAAA,KAAkB,WAAlB,kBAAkB,CAAA;AACvB,IAAA,QAAqB,WAArB,qBAAqB,CAAA;AAK1C,IAAA,mBAA8B,WAA9B,8BAA8B,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,yCAAyC,CAAC,AAAsB,AAAC;AAGzF,MAAMC,uBAAuB;IAClCC,YAAoBC,gBAAkC,CAAE;aAApCA,gBAAkC,GAAlCA,gBAAkC;KAAI;IAE1DC,kBAAkB,CAChBC,OAA8E,EAC9E;QACA,kDAAkD;QAClD,IAAI,IAAI,CAACF,gBAAgB,CAACG,sBAAsB,EAAE,EAAE;YAClD,MAAMC,SAAS,GAAG,IAAI,CAACJ,gBAAgB,CAACK,mBAAmB,EAAE,AA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AAkB,CAAC,CAAC,CAAC;QACpC,IAAI,CAACxC,gBAAgB,CAACyC,gBAAgB,CAAC,SAAS,CAAC,CAAC;KACnD;CACF;QAxIY3C,uBAAuB,GAAvBA,uBAAuB"}
1
+ {"version":3,"sources":["../../../../src/start/interface/interactiveActions.ts"],"sourcesContent":["import assert from 'assert';\nimport chalk from 'chalk';\n\nimport { BLT, printHelp, printItem, printQRCode, printUsage, StartOptions } from './commandsTable';\nimport * as Log from '../../log';\nimport { delayAsync } from '../../utils/delay';\nimport { learnMore } from '../../utils/link';\nimport { openBrowserAsync } from '../../utils/open';\nimport { selectAsync } from '../../utils/prompts';\nimport { DevServerManager } from '../server/DevServerManager';\nimport {\n addReactDevToolsReloadListener,\n startReactDevToolsProxyAsync,\n} from '../server/ReactDevToolsProxy';\nimport {\n openJsInspector,\n queryAllInspectorAppsAsync,\n} from '../server/middleware/inspector/JsInspector';\n\nconst debug = require('debug')('expo:start:interface:interactiveActions') as typeof console.log;\n\n/** Wraps the DevServerManager and adds an interface for user actions. */\nexport class DevServerManagerActions {\n constructor(private devServerManager: DevServerManager) {}\n\n printDevServerInfo(\n options: Pick<StartOptions, 'devClient' | 'isWebSocketsEnabled' | 'platforms'>\n ) {\n // If native dev server is running, print its URL.\n if (this.devServerManager.getNativeDevServerPort()) {\n const devServer = this.devServerManager.getDefaultDevServer();\n try {\n const nativeRuntimeUrl = devServer.getNativeRuntimeUrl()!;\n const interstitialPageUrl = devServer.getRedirectUrl();\n\n printQRCode(interstitialPageUrl ?? nativeRuntimeUrl);\n\n if (interstitialPageUrl) {\n Log.log(\n printItem(\n chalk`Choose an app to open your project at {underline ${interstitialPageUrl}}`\n )\n );\n }\n Log.log(printItem(chalk`Metro waiting on {underline ${nativeRuntimeUrl}}`));\n if (options.devClient === false) {\n // TODO: if development build, change this message!\n Log.log(\n printItem('Scan the QR code above with Expo Go (Android) or the Camera app (iOS)')\n );\n } else {\n Log.log(\n printItem(\n 'Scan the QR code above to open the project in a development build. ' +\n learnMore('https://expo.fyi/start')\n )\n );\n }\n } catch (error) {\n console.log('err', error);\n // @ts-ignore: If there is no development build scheme, then skip the QR code.\n if (error.code !== 'NO_DEV_CLIENT_SCHEME') {\n throw error;\n } else {\n const serverUrl = devServer.getDevServerUrl();\n Log.log(printItem(chalk`Metro waiting on {underline ${serverUrl}}`));\n Log.log(printItem(`Linking is disabled because the client scheme cannot be resolved.`));\n }\n }\n }\n\n const webDevServer = this.devServerManager.getWebDevServer();\n const webUrl = webDevServer?.getDevServerUrl({ hostType: 'localhost' });\n if (webUrl) {\n Log.log();\n Log.log(printItem(chalk`Web is waiting on {underline ${webUrl}}`));\n }\n\n printUsage(options, { verbose: false });\n printHelp();\n Log.log();\n }\n\n async openJsInspectorAsync() {\n Log.log('Opening JavaScript inspector in the browser...');\n const metroServerOrigin = this.devServerManager.getDefaultDevServer().getJsInspectorBaseUrl();\n assert(metroServerOrigin, 'Metro dev server is not running');\n const apps = await queryAllInspectorAppsAsync(metroServerOrigin);\n if (!apps.length) {\n Log.warn(\n `No compatible apps connected. JavaScript Debugging can only be used with the Hermes engine. ${learnMore(\n 'https://docs.expo.dev/guides/using-hermes/'\n )}`\n );\n return;\n }\n try {\n for (const app of apps) {\n await openJsInspector(app);\n }\n } catch (error: any) {\n Log.error('Failed to open JavaScript inspector. This is often an issue with Google Chrome.');\n Log.exception(error);\n }\n }\n\n reloadApp() {\n Log.log(`${BLT} Reloading apps`);\n // Send reload requests over the dev servers\n this.devServerManager.broadcastMessage('reload');\n }\n\n async openMoreToolsAsync() {\n try {\n // Options match: Chrome > View > Developer\n const value = await selectAsync(chalk`Dev tools {dim (native only)}`, [\n { title: 'Inspect elements', value: 'toggleElementInspector' },\n { title: 'Toggle performance monitor', value: 'togglePerformanceMonitor' },\n { title: 'Toggle developer menu', value: 'toggleDevMenu' },\n { title: 'Reload app', value: 'reload' },\n { title: 'Start React devtools', value: 'startReactDevTools' },\n // TODO: Maybe a \"View Source\" option to open code.\n // Toggling Remote JS Debugging is pretty rough, so leaving it disabled.\n // { title: 'Toggle Remote Debugging', value: 'toggleRemoteDebugging' },\n ]);\n if (value === 'startReactDevTools') {\n this.startReactDevToolsAsync();\n } else {\n this.devServerManager.broadcastMessage('sendDevCommand', { name: value });\n }\n } catch (error: any) {\n debug(error);\n // do nothing\n } finally {\n printHelp();\n }\n }\n\n async startReactDevToolsAsync() {\n await startReactDevToolsProxyAsync();\n const url = this.devServerManager.getDefaultDevServer().getReactDevToolsUrl();\n await openBrowserAsync(url);\n addReactDevToolsReloadListener(() => {\n this.reconnectReactDevTools();\n });\n this.reconnectReactDevTools();\n }\n\n async reconnectReactDevTools() {\n // Wait a little time for react-devtools to be initialized in browser\n await delayAsync(3000);\n this.devServerManager.broadcastMessage('sendDevCommand', { name: 'reconnectReactDevTools' });\n }\n\n toggleDevMenu() {\n Log.log(`${BLT} Toggling dev menu`);\n this.devServerManager.broadcastMessage('devMenu');\n }\n}\n"],"names":["Log","debug","require","DevServerManagerActions","constructor","devServerManager","printDevServerInfo","options","getNativeDevServerPort","devServer","getDefaultDevServer","nativeRuntimeUrl","getNativeRuntimeUrl","interstitialPageUrl","getRedirectUrl","printQRCode","log","printItem","chalk","devClient","learnMore","error","console","code","serverUrl","getDevServerUrl","webDevServer","getWebDevServer","webUrl","hostType","printUsage","verbose","printHelp","openJsInspectorAsync","metroServerOrigin","getJsInspectorBaseUrl","assert","apps","queryAllInspectorAppsAsync","length","warn","app","openJsInspector","exception","reloadApp","BLT","broadcastMessage","openMoreToolsAsync","value","selectAsync","title","startReactDevToolsAsync","name","startReactDevToolsProxyAsync","url","getReactDevToolsUrl","openBrowserAsync","addReactDevToolsReloadListener","reconnectReactDevTools","delayAsync","toggleDevMenu"],"mappings":"AAAA;;;;AAAmB,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACT,IAAA,MAAO,kCAAP,OAAO,EAAA;AAEwD,IAAA,cAAiB,WAAjB,iBAAiB,CAAA;AACtFA,IAAAA,GAAG,mCAAM,WAAW,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,IAAI,CAACjD,gBAAgB,CAACK,mBAAmB,EAAE,CAAC6C,mBAAmB,EAAE,AAAC;QAC9E,MAAMC,CAAAA,GAAAA,KAAgB,AAAK,CAAA,iBAAL,CAACF,GAAG,CAAC,CAAC;QAC5BG,CAAAA,GAAAA,mBAA8B,AAE5B,CAAA,+BAF4B,CAAC,IAAM;YACnC,IAAI,CAACC,sBAAsB,EAAE,CAAC;SAC/B,CAAC,CAAC;QACH,IAAI,CAACA,sBAAsB,EAAE,CAAC;KAC/B;IAED,MAAMA,sBAAsB,GAAG;QAC7B,qEAAqE;QACrE,MAAMC,CAAAA,GAAAA,MAAU,AAAM,CAAA,WAAN,CAAC,IAAI,CAAC,CAAC;QACvB,IAAI,CAACtD,gBAAgB,CAACyC,gBAAgB,CAAC,gBAAgB,EAAE;YAAEM,IAAI,EAAE,wBAAwB;SAAE,CAAC,CAAC;KAC9F;IAEDQ,aAAa,GAAG;QACd5D,GAAG,CAACgB,GAAG,CAAC,CAAC,EAAE6B,cAAG,IAAA,CAAC,kBAAkB,CAAC,CAAC,CAAC;QACpC,IAAI,CAACxC,gBAAgB,CAACyC,gBAAgB,CAAC,SAAS,CAAC,CAAC;KACnD;CACF;QAxIY3C,uBAAuB,GAAvBA,uBAAuB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/start/server/BundlerDevServer.ts"],"sourcesContent":["import { MessageSocket } from '@expo/dev-server';\nimport assert from 'assert';\nimport resolveFrom from 'resolve-from';\n\nimport { AsyncNgrok } from './AsyncNgrok';\nimport { DevelopmentSession } from './DevelopmentSession';\nimport { CreateURLOptions, UrlCreator } from './UrlCreator';\nimport { PlatformBundlers } from './platformBundlers';\nimport * as Log from '../../log';\nimport { FileNotifier } from '../../utils/FileNotifier';\nimport { resolveWithTimeout } from '../../utils/delay';\nimport { env } from '../../utils/env';\nimport { CommandError } from '../../utils/errors';\nimport { openBrowserAsync } from '../../utils/open';\nimport {\n BaseOpenInCustomProps,\n BaseResolveDeviceProps,\n PlatformManager,\n} from '../platforms/PlatformManager';\n\nconst debug = require('debug')('expo:start:server:devServer') as typeof console.log;\n\nexport type ServerLike = {\n close(callback?: (err?: Error) => void): void;\n addListener?(event: string, listener: (...args: any[]) => void): unknown;\n};\n\nexport type DevServerInstance = {\n /** Bundler dev server instance. */\n server: ServerLike;\n /** Dev server URL location properties. */\n location: {\n url: string;\n port: number;\n protocol: 'http' | 'https';\n host?: string;\n };\n /** Additional middleware that's attached to the `server`. */\n middleware: any;\n /** Message socket for communicating with the runtime. */\n messageSocket: MessageSocket;\n};\n\nexport interface BundlerStartOptions {\n /** Should the dev server use `https` protocol. */\n https?: boolean;\n /** Should start the dev servers in development mode (minify). */\n mode?: 'development' | 'production';\n /** Is dev client enabled. */\n devClient?: boolean;\n /** Should run dev servers with clean caches. */\n resetDevServer?: boolean;\n /** Code signing private key path (defaults to same directory as certificate) */\n privateKeyPath?: string;\n\n /** Max amount of workers (threads) to use with Metro bundler, defaults to undefined for max workers. */\n maxWorkers?: number;\n /** Port to start the dev server on. */\n port?: number;\n\n /** Should start a headless dev server e.g. mock representation to approximate info from a server running in a different process. */\n headless?: boolean;\n /** Should instruct the bundler to create minified bundles. */\n minify?: boolean;\n\n /** Will the bundler be used for exporting. NOTE: This is an odd option to pass to the dev server. */\n isExporting?: boolean;\n\n // Webpack options\n /** Should modify and create PWA icons. */\n isImageEditingEnabled?: boolean;\n\n location: CreateURLOptions;\n}\n\nconst PLATFORM_MANAGERS = {\n simulator: () =>\n require('../platforms/ios/ApplePlatformManager')\n .ApplePlatformManager as typeof import('../platforms/ios/ApplePlatformManager').ApplePlatformManager,\n emulator: () =>\n require('../platforms/android/AndroidPlatformManager')\n .AndroidPlatformManager as typeof import('../platforms/android/AndroidPlatformManager').AndroidPlatformManager,\n};\n\nexport abstract class BundlerDevServer {\n /** Name of the bundler. */\n abstract get name(): string;\n\n /** Ngrok instance for managing tunnel connections. */\n protected ngrok: AsyncNgrok | null = null;\n /** Interfaces with the Expo 'Development Session' API. */\n protected devSession: DevelopmentSession | null = null;\n /** Http server and related info. */\n protected instance: DevServerInstance | null = null;\n /** Native platform interfaces for opening projects. */\n private platformManagers: Record<string, PlatformManager<any>> = {};\n /** Manages the creation of dev server URLs. */\n protected urlCreator?: UrlCreator | null = null;\n\n private notifier: FileNotifier | null = null;\n\n constructor(\n /** Project root folder. */\n public projectRoot: string,\n /** A mapping of bundlers to platforms. */\n public platformBundlers: PlatformBundlers,\n // TODO: Replace with custom scheme maybe...\n public isDevClient?: boolean\n ) {}\n\n protected setInstance(instance: DevServerInstance) {\n this.instance = instance;\n }\n\n /** Get the manifest middleware function. */\n protected async getManifestMiddlewareAsync(\n options: Pick<BundlerStartOptions, 'minify' | 'mode' | 'privateKeyPath'> = {}\n ) {\n const Middleware = require('./middleware/ExpoGoManifestHandlerMiddleware')\n .ExpoGoManifestHandlerMiddleware as typeof import('./middleware/ExpoGoManifestHandlerMiddleware').ExpoGoManifestHandlerMiddleware;\n\n const urlCreator = this.getUrlCreator();\n const middleware = new Middleware(this.projectRoot, {\n constructUrl: urlCreator.constructUrl.bind(urlCreator),\n mode: options.mode,\n minify: options.minify,\n isNativeWebpack: this.name === 'webpack' && this.isTargetingNative(),\n privateKeyPath: options.privateKeyPath,\n });\n return middleware;\n }\n\n /** Start the dev server using settings defined in the start command. */\n public async startAsync(options: BundlerStartOptions): Promise<DevServerInstance> {\n await this.stopAsync();\n\n let instance: DevServerInstance;\n if (options.headless) {\n instance = await this.startHeadlessAsync(options);\n } else {\n instance = await this.startImplementationAsync(options);\n }\n\n this.setInstance(instance);\n await this.postStartAsync(options);\n return instance;\n }\n\n protected abstract startImplementationAsync(\n options: BundlerStartOptions\n ): Promise<DevServerInstance>;\n\n public async waitForTypeScriptAsync(): Promise<boolean> {\n return false;\n }\n\n public abstract startTypeScriptServices(): Promise<void>;\n\n public async watchEnvironmentVariables(): Promise<void> {\n // noop -- We've only implemented this functionality in Metro.\n }\n\n /**\n * Creates a mock server representation that can be used to estimate URLs for a server started in another process.\n * This is used for the run commands where you can reuse the server from a previous run.\n */\n private async startHeadlessAsync(options: BundlerStartOptions): Promise<DevServerInstance> {\n if (!options.port)\n throw new CommandError('HEADLESS_SERVER', 'headless dev server requires a port option');\n this.urlCreator = this.getUrlCreator(options);\n\n return {\n // Create a mock server\n server: {\n close: () => {\n this.instance = null;\n },\n addListener() {},\n },\n location: {\n // The port is the main thing we want to send back.\n port: options.port,\n // localhost isn't always correct.\n host: 'localhost',\n // http is the only supported protocol on native.\n url: `http://localhost:${options.port}`,\n protocol: 'http',\n },\n middleware: {},\n messageSocket: {\n broadcast: () => {\n throw new CommandError('HEADLESS_SERVER', 'Cannot broadcast messages to headless server');\n },\n },\n };\n }\n\n /**\n * Runs after the `startAsync` function, performing any additional common operations.\n * You can assume the dev server is started by the time this function is called.\n */\n protected async postStartAsync(options: BundlerStartOptions) {\n if (\n options.location.hostType === 'tunnel' &&\n !env.EXPO_OFFLINE &&\n // This is a hack to prevent using tunnel on web since we block it upstream for some reason.\n this.isTargetingNative()\n ) {\n await this._startTunnelAsync();\n }\n await this.startDevSessionAsync();\n\n this.watchConfig();\n }\n\n protected abstract getConfigModuleIds(): string[];\n\n protected watchConfig() {\n this.notifier?.stopObserving();\n this.notifier = new FileNotifier(this.projectRoot, this.getConfigModuleIds());\n this.notifier.startObserving();\n }\n\n /** Create ngrok instance and start the tunnel server. Exposed for testing. */\n public async _startTunnelAsync(): Promise<AsyncNgrok | null> {\n const port = this.getInstance()?.location.port;\n if (!port) return null;\n debug('[ngrok] connect to port: ' + port);\n this.ngrok = new AsyncNgrok(this.projectRoot, port);\n await this.ngrok.startAsync();\n return this.ngrok;\n }\n\n protected async startDevSessionAsync() {\n // This is used to make Expo Go open the project in either Expo Go, or the web browser.\n // Must come after ngrok (`startTunnelAsync`) setup.\n this.devSession?.stopNotifying?.();\n this.devSession = new DevelopmentSession(\n this.projectRoot,\n // This URL will be used on external devices so the computer IP won't be relevant.\n this.isTargetingNative()\n ? this.getNativeRuntimeUrl()\n : this.getDevServerUrl({ hostType: 'localhost' }),\n () => {\n // TODO: This appears to be happening consistently after an hour.\n // We should investigate why this is happening and fix it on our servers.\n // Log.error(\n // chalk.red(\n // '\\nAn unexpected error occurred while updating the Dev Session API. This project will not appear in the \"Development servers\" section of the Expo Go app until this process has been restarted.'\n // )\n // );\n // Log.exception(error);\n this.devSession?.closeAsync().catch((error) => {\n debug('[dev-session] error closing: ' + error.message);\n });\n }\n );\n\n await this.devSession.startAsync({\n runtime: this.isTargetingNative() ? 'native' : 'web',\n });\n }\n\n public isTargetingNative() {\n // Temporary hack while we implement multi-bundler dev server proxy.\n return true;\n }\n\n public isTargetingWeb() {\n return this.platformBundlers.web === this.name;\n }\n\n /**\n * Sends a message over web sockets to any connected device,\n * does nothing when the dev server is not running.\n *\n * @param method name of the command. In RN projects `reload`, and `devMenu` are available. In Expo Go, `sendDevCommand` is available.\n * @param params\n */\n public broadcastMessage(\n method: 'reload' | 'devMenu' | 'sendDevCommand',\n params?: Record<string, any>\n ) {\n this.getInstance()?.messageSocket.broadcast(method, params);\n }\n\n /** Get the running dev server instance. */\n public getInstance() {\n return this.instance;\n }\n\n /** Stop the running dev server instance. */\n async stopAsync() {\n // Stop file watching.\n this.notifier?.stopObserving();\n\n // Stop the dev session timer and tell Expo API to remove dev session.\n await this.devSession?.closeAsync();\n\n // Stop ngrok if running.\n await this.ngrok?.stopAsync().catch((e) => {\n Log.error(`Error stopping ngrok:`);\n Log.exception(e);\n });\n\n return resolveWithTimeout(\n () =>\n new Promise<void>((resolve, reject) => {\n // Close the server.\n debug(`Stopping dev server (bundler: ${this.name})`);\n\n if (this.instance?.server) {\n this.instance.server.close((error) => {\n debug(`Stopped dev server (bundler: ${this.name})`);\n this.instance = null;\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n } else {\n debug(`Stopped dev server (bundler: ${this.name})`);\n this.instance = null;\n resolve();\n }\n }),\n {\n // NOTE(Bacon): Metro dev server doesn't seem to be closing in time.\n timeout: 1000,\n errorMessage: `Timeout waiting for '${this.name}' dev server to close`,\n }\n );\n }\n\n public getUrlCreator(options: Partial<Pick<BundlerStartOptions, 'port' | 'location'>> = {}) {\n if (!this.urlCreator) {\n assert(options?.port, 'Dev server instance not found');\n this.urlCreator = new UrlCreator(options.location, {\n port: options.port,\n getTunnelUrl: this.getTunnelUrl.bind(this),\n });\n }\n return this.urlCreator;\n }\n\n public getNativeRuntimeUrl(opts: Partial<CreateURLOptions> = {}) {\n return this.isDevClient\n ? this.getUrlCreator().constructDevClientUrl(opts) ?? this.getDevServerUrl()\n : this.getUrlCreator().constructUrl({ ...opts, scheme: 'exp' });\n }\n\n /** Get the URL for the running instance of the dev server. */\n public getDevServerUrl(options: { hostType?: 'localhost' } = {}): string | null {\n const instance = this.getInstance();\n if (!instance?.location) {\n return null;\n }\n const { location } = instance;\n if (options.hostType === 'localhost') {\n return `${location.protocol}://localhost:${location.port}`;\n }\n return location.url ?? null;\n }\n\n /** Get the base URL for JS inspector */\n public getJsInspectorBaseUrl(): string {\n if (this.name !== 'metro') {\n throw new CommandError(\n 'DEV_SERVER',\n `Cannot get the JS inspector base url - bundler[${this.name}]`\n );\n }\n return this.getUrlCreator().constructUrl({ scheme: 'http' });\n }\n\n /** Get the tunnel URL from ngrok. */\n public getTunnelUrl(): string | null {\n return this.ngrok?.getActiveUrl() ?? null;\n }\n\n /** Open the dev server in a runtime. */\n public async openPlatformAsync(\n launchTarget: keyof typeof PLATFORM_MANAGERS | 'desktop',\n resolver: BaseResolveDeviceProps<any> = {}\n ) {\n if (launchTarget === 'desktop') {\n const serverUrl = this.getDevServerUrl({ hostType: 'localhost' });\n // Allow opening the tunnel URL when using Metro web.\n const url = this.name === 'metro' ? this.getTunnelUrl() ?? serverUrl : serverUrl;\n await openBrowserAsync(url!);\n return { url };\n }\n\n const runtime = this.isTargetingNative() ? (this.isDevClient ? 'custom' : 'expo') : 'web';\n const manager = await this.getPlatformManagerAsync(launchTarget);\n return manager.openAsync({ runtime }, resolver);\n }\n\n /** Open the dev server in a runtime. */\n public async openCustomRuntimeAsync(\n launchTarget: keyof typeof PLATFORM_MANAGERS,\n launchProps: Partial<BaseOpenInCustomProps> = {},\n resolver: BaseResolveDeviceProps<any> = {}\n ) {\n const runtime = this.isTargetingNative() ? (this.isDevClient ? 'custom' : 'expo') : 'web';\n if (runtime !== 'custom') {\n throw new CommandError(\n `dev server cannot open custom runtimes either because it does not target native platforms or because it is not targeting dev clients. (target: ${runtime})`\n );\n }\n\n const manager = await this.getPlatformManagerAsync(launchTarget);\n return manager.openAsync({ runtime: 'custom', props: launchProps }, resolver);\n }\n\n /** Get the URL for opening in Expo Go. */\n protected getExpoGoUrl(): string {\n return this.getUrlCreator().constructUrl({ scheme: 'exp' });\n }\n\n /** Should use the interstitial page for selecting which runtime to use. */\n protected isRedirectPageEnabled(): boolean {\n return (\n !env.EXPO_NO_REDIRECT_PAGE &&\n // if user passed --dev-client flag, skip interstitial page\n !this.isDevClient &&\n // Checks if dev client is installed.\n !!resolveFrom.silent(this.projectRoot, 'expo-dev-client')\n );\n }\n\n /** Get the redirect URL when redirecting is enabled. */\n public getRedirectUrl(platform: keyof typeof PLATFORM_MANAGERS | null = null): string | null {\n if (!this.isRedirectPageEnabled()) {\n debug('Redirect page is disabled');\n return null;\n }\n\n return (\n this.getUrlCreator().constructLoadingUrl(\n {},\n platform === 'emulator' ? 'android' : platform === 'simulator' ? 'ios' : null\n ) ?? null\n );\n }\n\n public getReactDevToolsUrl(): string {\n return new URL(\n '_expo/react-devtools',\n this.getUrlCreator().constructUrl({ scheme: 'http' })\n ).toString();\n }\n\n protected async getPlatformManagerAsync(platform: keyof typeof PLATFORM_MANAGERS) {\n if (!this.platformManagers[platform]) {\n const Manager = PLATFORM_MANAGERS[platform]();\n const port = this.getInstance()?.location.port;\n if (!port || !this.urlCreator) {\n throw new CommandError(\n 'DEV_SERVER',\n 'Cannot interact with native platforms until dev server has started'\n );\n }\n debug(`Creating platform manager (platform: ${platform}, port: ${port})`);\n this.platformManagers[platform] = new Manager(this.projectRoot, port, {\n getCustomRuntimeUrl: this.urlCreator.constructDevClientUrl.bind(this.urlCreator),\n getExpoGoUrl: this.getExpoGoUrl.bind(this),\n getRedirectUrl: this.getRedirectUrl.bind(this, platform),\n getDevServerUrl: this.getDevServerUrl.bind(this, { hostType: 'localhost' }),\n });\n }\n return this.platformManagers[platform];\n }\n}\n"],"names":["Log","debug","require","PLATFORM_MANAGERS","simulator","ApplePlatformManager","emulator","AndroidPlatformManager","BundlerDevServer","constructor","projectRoot","platformBundlers","isDevClient","ngrok","devSession","instance","platformManagers","urlCreator","notifier","setInstance","getManifestMiddlewareAsync","options","Middleware","ExpoGoManifestHandlerMiddleware","getUrlCreator","middleware","constructUrl","bind","mode","minify","isNativeWebpack","name","isTargetingNative","privateKeyPath","startAsync","stopAsync","headless","startHeadlessAsync","startImplementationAsync","postStartAsync","waitForTypeScriptAsync","watchEnvironmentVariables","port","CommandError","server","close","addListener","location","host","url","protocol","messageSocket","broadcast","hostType","env","EXPO_OFFLINE","_startTunnelAsync","startDevSessionAsync","watchConfig","stopObserving","FileNotifier","getConfigModuleIds","startObserving","getInstance","AsyncNgrok","stopNotifying","DevelopmentSession","getNativeRuntimeUrl","getDevServerUrl","closeAsync","catch","error","message","runtime","isTargetingWeb","web","broadcastMessage","method","params","e","exception","resolveWithTimeout","Promise","resolve","reject","timeout","errorMessage","assert","UrlCreator","getTunnelUrl","opts","constructDevClientUrl","scheme","getJsInspectorBaseUrl","getActiveUrl","openPlatformAsync","launchTarget","resolver","serverUrl","openBrowserAsync","manager","getPlatformManagerAsync","openAsync","openCustomRuntimeAsync","launchProps","props","getExpoGoUrl","isRedirectPageEnabled","EXPO_NO_REDIRECT_PAGE","resolveFrom","silent","getRedirectUrl","platform","constructLoadingUrl","getReactDevToolsUrl","URL","toString","Manager","getCustomRuntimeUrl"],"mappings":"AAAA;;;;AACmB,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACH,IAAA,YAAc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AACA,IAAI,IAAI,CAAC,IAAI,CAACzB,UAAU,EAAE;gBAC7B,MAAM,IAAI0B,OAAY,aAAA,CACpB,YAAY,EACZ,oEAAoE,CACrE,CAAC;aACH;YACD1C,KAAK,CAAC,CAAC,qCAAqC,EAAE+G,QAAQ,CAAC,QAAQ,EAAEtE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1E,IAAI,CAAC1B,gBAAgB,CAACgG,QAAQ,CAAC,GAAG,IAAIK,OAAO,CAAC,IAAI,CAAC3G,WAAW,EAAEgC,IAAI,EAAE;gBACpE4E,mBAAmB,EAAE,IAAI,CAACrG,UAAU,CAAC0E,qBAAqB,CAAChE,IAAI,CAAC,IAAI,CAACV,UAAU,CAAC;gBAChFyF,YAAY,EAAE,IAAI,CAACA,YAAY,CAAC/E,IAAI,CAAC,IAAI,CAAC;gBAC1CoF,cAAc,EAAE,IAAI,CAACA,cAAc,CAACpF,IAAI,CAAC,IAAI,EAAEqF,QAAQ,CAAC;gBACxD5C,eAAe,EAAE,IAAI,CAACA,eAAe,CAACzC,IAAI,CAAC,IAAI,EAAE;oBAAE0B,QAAQ,EAAE,WAAW;iBAAE,CAAC;aAC5E,CAAC,CAAC;SACJ;QACD,OAAO,IAAI,CAACrC,gBAAgB,CAACgG,QAAQ,CAAC,CAAC;KACxC;CACF;QAtYqBxG,gBAAgB,GAAhBA,gBAAgB"}
1
+ {"version":3,"sources":["../../../../src/start/server/BundlerDevServer.ts"],"sourcesContent":["import assert from 'assert';\nimport resolveFrom from 'resolve-from';\n\nimport { AsyncNgrok } from './AsyncNgrok';\nimport { DevelopmentSession } from './DevelopmentSession';\nimport { CreateURLOptions, UrlCreator } from './UrlCreator';\nimport { PlatformBundlers } from './platformBundlers';\nimport * as Log from '../../log';\nimport { FileNotifier } from '../../utils/FileNotifier';\nimport { resolveWithTimeout } from '../../utils/delay';\nimport { env } from '../../utils/env';\nimport { CommandError } from '../../utils/errors';\nimport { openBrowserAsync } from '../../utils/open';\nimport {\n BaseOpenInCustomProps,\n BaseResolveDeviceProps,\n PlatformManager,\n} from '../platforms/PlatformManager';\n\nconst debug = require('debug')('expo:start:server:devServer') as typeof console.log;\n\nexport type MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\nexport type ServerLike = {\n close(callback?: (err?: Error) => void): void;\n addListener?(event: string, listener: (...args: any[]) => void): unknown;\n};\n\nexport type DevServerInstance = {\n /** Bundler dev server instance. */\n server: ServerLike;\n /** Dev server URL location properties. */\n location: {\n url: string;\n port: number;\n protocol: 'http' | 'https';\n host?: string;\n };\n /** Additional middleware that's attached to the `server`. */\n middleware: any;\n /** Message socket for communicating with the runtime. */\n messageSocket: MessageSocket;\n};\n\nexport interface BundlerStartOptions {\n /** Should the dev server use `https` protocol. */\n https?: boolean;\n /** Should start the dev servers in development mode (minify). */\n mode?: 'development' | 'production';\n /** Is dev client enabled. */\n devClient?: boolean;\n /** Should run dev servers with clean caches. */\n resetDevServer?: boolean;\n /** Code signing private key path (defaults to same directory as certificate) */\n privateKeyPath?: string;\n\n /** Max amount of workers (threads) to use with Metro bundler, defaults to undefined for max workers. */\n maxWorkers?: number;\n /** Port to start the dev server on. */\n port?: number;\n\n /** Should start a headless dev server e.g. mock representation to approximate info from a server running in a different process. */\n headless?: boolean;\n /** Should instruct the bundler to create minified bundles. */\n minify?: boolean;\n\n /** Will the bundler be used for exporting. NOTE: This is an odd option to pass to the dev server. */\n isExporting?: boolean;\n\n // Webpack options\n /** Should modify and create PWA icons. */\n isImageEditingEnabled?: boolean;\n\n location: CreateURLOptions;\n}\n\nconst PLATFORM_MANAGERS = {\n simulator: () =>\n require('../platforms/ios/ApplePlatformManager')\n .ApplePlatformManager as typeof import('../platforms/ios/ApplePlatformManager').ApplePlatformManager,\n emulator: () =>\n require('../platforms/android/AndroidPlatformManager')\n .AndroidPlatformManager as typeof import('../platforms/android/AndroidPlatformManager').AndroidPlatformManager,\n};\n\nexport abstract class BundlerDevServer {\n /** Name of the bundler. */\n abstract get name(): string;\n\n /** Ngrok instance for managing tunnel connections. */\n protected ngrok: AsyncNgrok | null = null;\n /** Interfaces with the Expo 'Development Session' API. */\n protected devSession: DevelopmentSession | null = null;\n /** Http server and related info. */\n protected instance: DevServerInstance | null = null;\n /** Native platform interfaces for opening projects. */\n private platformManagers: Record<string, PlatformManager<any>> = {};\n /** Manages the creation of dev server URLs. */\n protected urlCreator?: UrlCreator | null = null;\n\n private notifier: FileNotifier | null = null;\n\n constructor(\n /** Project root folder. */\n public projectRoot: string,\n /** A mapping of bundlers to platforms. */\n public platformBundlers: PlatformBundlers,\n // TODO: Replace with custom scheme maybe...\n public isDevClient?: boolean\n ) {}\n\n protected setInstance(instance: DevServerInstance) {\n this.instance = instance;\n }\n\n /** Get the manifest middleware function. */\n protected async getManifestMiddlewareAsync(\n options: Pick<BundlerStartOptions, 'minify' | 'mode' | 'privateKeyPath'> = {}\n ) {\n const Middleware = require('./middleware/ExpoGoManifestHandlerMiddleware')\n .ExpoGoManifestHandlerMiddleware as typeof import('./middleware/ExpoGoManifestHandlerMiddleware').ExpoGoManifestHandlerMiddleware;\n\n const urlCreator = this.getUrlCreator();\n const middleware = new Middleware(this.projectRoot, {\n constructUrl: urlCreator.constructUrl.bind(urlCreator),\n mode: options.mode,\n minify: options.minify,\n isNativeWebpack: this.name === 'webpack' && this.isTargetingNative(),\n privateKeyPath: options.privateKeyPath,\n });\n return middleware;\n }\n\n /** Start the dev server using settings defined in the start command. */\n public async startAsync(options: BundlerStartOptions): Promise<DevServerInstance> {\n await this.stopAsync();\n\n let instance: DevServerInstance;\n if (options.headless) {\n instance = await this.startHeadlessAsync(options);\n } else {\n instance = await this.startImplementationAsync(options);\n }\n\n this.setInstance(instance);\n await this.postStartAsync(options);\n return instance;\n }\n\n protected abstract startImplementationAsync(\n options: BundlerStartOptions\n ): Promise<DevServerInstance>;\n\n public async waitForTypeScriptAsync(): Promise<boolean> {\n return false;\n }\n\n public abstract startTypeScriptServices(): Promise<void>;\n\n public async watchEnvironmentVariables(): Promise<void> {\n // noop -- We've only implemented this functionality in Metro.\n }\n\n /**\n * Creates a mock server representation that can be used to estimate URLs for a server started in another process.\n * This is used for the run commands where you can reuse the server from a previous run.\n */\n private async startHeadlessAsync(options: BundlerStartOptions): Promise<DevServerInstance> {\n if (!options.port)\n throw new CommandError('HEADLESS_SERVER', 'headless dev server requires a port option');\n this.urlCreator = this.getUrlCreator(options);\n\n return {\n // Create a mock server\n server: {\n close: () => {\n this.instance = null;\n },\n addListener() {},\n },\n location: {\n // The port is the main thing we want to send back.\n port: options.port,\n // localhost isn't always correct.\n host: 'localhost',\n // http is the only supported protocol on native.\n url: `http://localhost:${options.port}`,\n protocol: 'http',\n },\n middleware: {},\n messageSocket: {\n broadcast: () => {\n throw new CommandError('HEADLESS_SERVER', 'Cannot broadcast messages to headless server');\n },\n },\n };\n }\n\n /**\n * Runs after the `startAsync` function, performing any additional common operations.\n * You can assume the dev server is started by the time this function is called.\n */\n protected async postStartAsync(options: BundlerStartOptions) {\n if (\n options.location.hostType === 'tunnel' &&\n !env.EXPO_OFFLINE &&\n // This is a hack to prevent using tunnel on web since we block it upstream for some reason.\n this.isTargetingNative()\n ) {\n await this._startTunnelAsync();\n }\n await this.startDevSessionAsync();\n\n this.watchConfig();\n }\n\n protected abstract getConfigModuleIds(): string[];\n\n protected watchConfig() {\n this.notifier?.stopObserving();\n this.notifier = new FileNotifier(this.projectRoot, this.getConfigModuleIds());\n this.notifier.startObserving();\n }\n\n /** Create ngrok instance and start the tunnel server. Exposed for testing. */\n public async _startTunnelAsync(): Promise<AsyncNgrok | null> {\n const port = this.getInstance()?.location.port;\n if (!port) return null;\n debug('[ngrok] connect to port: ' + port);\n this.ngrok = new AsyncNgrok(this.projectRoot, port);\n await this.ngrok.startAsync();\n return this.ngrok;\n }\n\n protected async startDevSessionAsync() {\n // This is used to make Expo Go open the project in either Expo Go, or the web browser.\n // Must come after ngrok (`startTunnelAsync`) setup.\n this.devSession?.stopNotifying?.();\n this.devSession = new DevelopmentSession(\n this.projectRoot,\n // This URL will be used on external devices so the computer IP won't be relevant.\n this.isTargetingNative()\n ? this.getNativeRuntimeUrl()\n : this.getDevServerUrl({ hostType: 'localhost' }),\n () => {\n // TODO: This appears to be happening consistently after an hour.\n // We should investigate why this is happening and fix it on our servers.\n // Log.error(\n // chalk.red(\n // '\\nAn unexpected error occurred while updating the Dev Session API. This project will not appear in the \"Development servers\" section of the Expo Go app until this process has been restarted.'\n // )\n // );\n // Log.exception(error);\n this.devSession?.closeAsync().catch((error) => {\n debug('[dev-session] error closing: ' + error.message);\n });\n }\n );\n\n await this.devSession.startAsync({\n runtime: this.isTargetingNative() ? 'native' : 'web',\n });\n }\n\n public isTargetingNative() {\n // Temporary hack while we implement multi-bundler dev server proxy.\n return true;\n }\n\n public isTargetingWeb() {\n return this.platformBundlers.web === this.name;\n }\n\n /**\n * Sends a message over web sockets to any connected device,\n * does nothing when the dev server is not running.\n *\n * @param method name of the command. In RN projects `reload`, and `devMenu` are available. In Expo Go, `sendDevCommand` is available.\n * @param params\n */\n public broadcastMessage(\n method: 'reload' | 'devMenu' | 'sendDevCommand',\n params?: Record<string, any>\n ) {\n this.getInstance()?.messageSocket.broadcast(method, params);\n }\n\n /** Get the running dev server instance. */\n public getInstance() {\n return this.instance;\n }\n\n /** Stop the running dev server instance. */\n async stopAsync() {\n // Stop file watching.\n this.notifier?.stopObserving();\n\n // Stop the dev session timer and tell Expo API to remove dev session.\n await this.devSession?.closeAsync();\n\n // Stop ngrok if running.\n await this.ngrok?.stopAsync().catch((e) => {\n Log.error(`Error stopping ngrok:`);\n Log.exception(e);\n });\n\n return resolveWithTimeout(\n () =>\n new Promise<void>((resolve, reject) => {\n // Close the server.\n debug(`Stopping dev server (bundler: ${this.name})`);\n\n if (this.instance?.server) {\n this.instance.server.close((error) => {\n debug(`Stopped dev server (bundler: ${this.name})`);\n this.instance = null;\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n } else {\n debug(`Stopped dev server (bundler: ${this.name})`);\n this.instance = null;\n resolve();\n }\n }),\n {\n // NOTE(Bacon): Metro dev server doesn't seem to be closing in time.\n timeout: 1000,\n errorMessage: `Timeout waiting for '${this.name}' dev server to close`,\n }\n );\n }\n\n public getUrlCreator(options: Partial<Pick<BundlerStartOptions, 'port' | 'location'>> = {}) {\n if (!this.urlCreator) {\n assert(options?.port, 'Dev server instance not found');\n this.urlCreator = new UrlCreator(options.location, {\n port: options.port,\n getTunnelUrl: this.getTunnelUrl.bind(this),\n });\n }\n return this.urlCreator;\n }\n\n public getNativeRuntimeUrl(opts: Partial<CreateURLOptions> = {}) {\n return this.isDevClient\n ? this.getUrlCreator().constructDevClientUrl(opts) ?? this.getDevServerUrl()\n : this.getUrlCreator().constructUrl({ ...opts, scheme: 'exp' });\n }\n\n /** Get the URL for the running instance of the dev server. */\n public getDevServerUrl(options: { hostType?: 'localhost' } = {}): string | null {\n const instance = this.getInstance();\n if (!instance?.location) {\n return null;\n }\n const { location } = instance;\n if (options.hostType === 'localhost') {\n return `${location.protocol}://localhost:${location.port}`;\n }\n return location.url ?? null;\n }\n\n /** Get the base URL for JS inspector */\n public getJsInspectorBaseUrl(): string {\n if (this.name !== 'metro') {\n throw new CommandError(\n 'DEV_SERVER',\n `Cannot get the JS inspector base url - bundler[${this.name}]`\n );\n }\n return this.getUrlCreator().constructUrl({ scheme: 'http' });\n }\n\n /** Get the tunnel URL from ngrok. */\n public getTunnelUrl(): string | null {\n return this.ngrok?.getActiveUrl() ?? null;\n }\n\n /** Open the dev server in a runtime. */\n public async openPlatformAsync(\n launchTarget: keyof typeof PLATFORM_MANAGERS | 'desktop',\n resolver: BaseResolveDeviceProps<any> = {}\n ) {\n if (launchTarget === 'desktop') {\n const serverUrl = this.getDevServerUrl({ hostType: 'localhost' });\n // Allow opening the tunnel URL when using Metro web.\n const url = this.name === 'metro' ? this.getTunnelUrl() ?? serverUrl : serverUrl;\n await openBrowserAsync(url!);\n return { url };\n }\n\n const runtime = this.isTargetingNative() ? (this.isDevClient ? 'custom' : 'expo') : 'web';\n const manager = await this.getPlatformManagerAsync(launchTarget);\n return manager.openAsync({ runtime }, resolver);\n }\n\n /** Open the dev server in a runtime. */\n public async openCustomRuntimeAsync(\n launchTarget: keyof typeof PLATFORM_MANAGERS,\n launchProps: Partial<BaseOpenInCustomProps> = {},\n resolver: BaseResolveDeviceProps<any> = {}\n ) {\n const runtime = this.isTargetingNative() ? (this.isDevClient ? 'custom' : 'expo') : 'web';\n if (runtime !== 'custom') {\n throw new CommandError(\n `dev server cannot open custom runtimes either because it does not target native platforms or because it is not targeting dev clients. (target: ${runtime})`\n );\n }\n\n const manager = await this.getPlatformManagerAsync(launchTarget);\n return manager.openAsync({ runtime: 'custom', props: launchProps }, resolver);\n }\n\n /** Get the URL for opening in Expo Go. */\n protected getExpoGoUrl(): string {\n return this.getUrlCreator().constructUrl({ scheme: 'exp' });\n }\n\n /** Should use the interstitial page for selecting which runtime to use. */\n protected isRedirectPageEnabled(): boolean {\n return (\n !env.EXPO_NO_REDIRECT_PAGE &&\n // if user passed --dev-client flag, skip interstitial page\n !this.isDevClient &&\n // Checks if dev client is installed.\n !!resolveFrom.silent(this.projectRoot, 'expo-dev-client')\n );\n }\n\n /** Get the redirect URL when redirecting is enabled. */\n public getRedirectUrl(platform: keyof typeof PLATFORM_MANAGERS | null = null): string | null {\n if (!this.isRedirectPageEnabled()) {\n debug('Redirect page is disabled');\n return null;\n }\n\n return (\n this.getUrlCreator().constructLoadingUrl(\n {},\n platform === 'emulator' ? 'android' : platform === 'simulator' ? 'ios' : null\n ) ?? null\n );\n }\n\n public getReactDevToolsUrl(): string {\n return new URL(\n '_expo/react-devtools',\n this.getUrlCreator().constructUrl({ scheme: 'http' })\n ).toString();\n }\n\n protected async getPlatformManagerAsync(platform: keyof typeof PLATFORM_MANAGERS) {\n if (!this.platformManagers[platform]) {\n const Manager = PLATFORM_MANAGERS[platform]();\n const port = this.getInstance()?.location.port;\n if (!port || !this.urlCreator) {\n throw new CommandError(\n 'DEV_SERVER',\n 'Cannot interact with native platforms until dev server has started'\n );\n }\n debug(`Creating platform manager (platform: ${platform}, port: ${port})`);\n this.platformManagers[platform] = new Manager(this.projectRoot, port, {\n getCustomRuntimeUrl: this.urlCreator.constructDevClientUrl.bind(this.urlCreator),\n getExpoGoUrl: this.getExpoGoUrl.bind(this),\n getRedirectUrl: this.getRedirectUrl.bind(this, platform),\n getDevServerUrl: this.getDevServerUrl.bind(this, { hostType: 'localhost' }),\n });\n }\n return this.platformManagers[platform];\n }\n}\n"],"names":["Log","debug","require","PLATFORM_MANAGERS","simulator","ApplePlatformManager","emulator","AndroidPlatformManager","BundlerDevServer","constructor","projectRoot","platformBundlers","isDevClient","ngrok","devSession","instance","platformManagers","urlCreator","notifier","setInstance","getManifestMiddlewareAsync","options","Middleware","ExpoGoManifestHandlerMiddleware","getUrlCreator","middleware","constructUrl","bind","mode","minify","isNativeWebpack","name","isTargetingNative","privateKeyPath","startAsync","stopAsync","headless","startHeadlessAsync","startImplementationAsync","postStartAsync","waitForTypeScriptAsync","watchEnvironmentVariables","port","CommandError","server","close","addListener","location","host","url","protocol","messageSocket","broadcast","hostType","env","EXPO_OFFLINE","_startTunnelAsync","startDevSessionAsync","watchConfig","stopObserving","FileNotifier","getConfigModuleIds","startObserving","getInstance","AsyncNgrok","stopNotifying","DevelopmentSession","getNativeRuntimeUrl","getDevServerUrl","closeAsync","catch","error","message","runtime","isTargetingWeb","web","broadcastMessage","method","params","e","exception","resolveWithTimeout","Promise","resolve","reject","timeout","errorMessage","assert","UrlCreator","getTunnelUrl","opts","constructDevClientUrl","scheme","getJsInspectorBaseUrl","getActiveUrl","openPlatformAsync","launchTarget","resolver","serverUrl","openBrowserAsync","manager","getPlatformManagerAsync","openAsync","openCustomRuntimeAsync","launchProps","props","getExpoGoUrl","isRedirectPageEnabled","EXPO_NO_REDIRECT_PAGE","resolveFrom","silent","getRedirectUrl","platform","constructLoadingUrl","getReactDevToolsUrl","URL","to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,EAAE,SAAU,GAA5B,KAAA,CAA4B,GAA5B,GAAkB,CAAEhB,QAAQ,CAACL,IAAI,AAAC;YAC/C,IAAI,CAACA,IAAI,IAAI,CAAC,IAAI,CAACzB,UAAU,EAAE;gBAC7B,MAAM,IAAI0B,OAAY,aAAA,CACpB,YAAY,EACZ,oEAAoE,CACrE,CAAC;aACH;YACD1C,KAAK,CAAC,CAAC,qCAAqC,EAAE+G,QAAQ,CAAC,QAAQ,EAAEtE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1E,IAAI,CAAC1B,gBAAgB,CAACgG,QAAQ,CAAC,GAAG,IAAIK,OAAO,CAAC,IAAI,CAAC3G,WAAW,EAAEgC,IAAI,EAAE;gBACpE4E,mBAAmB,EAAE,IAAI,CAACrG,UAAU,CAAC0E,qBAAqB,CAAChE,IAAI,CAAC,IAAI,CAACV,UAAU,CAAC;gBAChFyF,YAAY,EAAE,IAAI,CAACA,YAAY,CAAC/E,IAAI,CAAC,IAAI,CAAC;gBAC1CoF,cAAc,EAAE,IAAI,CAACA,cAAc,CAACpF,IAAI,CAAC,IAAI,EAAEqF,QAAQ,CAAC;gBACxD5C,eAAe,EAAE,IAAI,CAACA,eAAe,CAACzC,IAAI,CAAC,IAAI,EAAE;oBAAE0B,QAAQ,EAAE,WAAW;iBAAE,CAAC;aAC5E,CAAC,CAAC;SACJ;QACD,OAAO,IAAI,CAACrC,gBAAgB,CAACgG,QAAQ,CAAC,CAAC;KACxC;CACF;QAtYqBxG,gBAAgB,GAAhBA,gBAAgB"}
@@ -7,6 +7,7 @@ exports.createMetroEndpointAsync = createMetroEndpointAsync;
7
7
  exports.requireFileContentsWithMetro = requireFileContentsWithMetro;
8
8
  exports.requireWithMetro = requireWithMetro;
9
9
  exports.getStaticRenderFunctions = getStaticRenderFunctions;
10
+ exports.evalMetroAndWrapFunctions = evalMetroAndWrapFunctions;
10
11
  var _fs = _interopRequireDefault(require("fs"));
11
12
  var _nodeFetch = _interopRequireDefault(require("node-fetch"));
12
13
  var _path = _interopRequireDefault(require("path"));
@@ -31,10 +32,6 @@ function wrapBundle(str) {
31
32
  // Use gm to apply to the last require line. This is needed when the bundle has side-effects.
32
33
  return str.replace(/^(__r\(.*\);)$/gm, "module.exports = $1");
33
34
  }
34
- function stripProcess(str) {
35
- // TODO: Remove from the metro prelude
36
- return str.replace(/process=this\.process\|\|{},/m, "");
37
- }
38
35
  // TODO(EvanBacon): Group all the code together and version.
39
36
  const getRenderModuleId = (projectRoot)=>{
40
37
  const moduleId = _resolveFrom.default.silent(projectRoot, "expo-router/node/render.js");
@@ -124,20 +121,18 @@ async function requireFileContentsWithMetro(projectRoot, devServerUrl, absoluteF
124
121
  throw new Error(`Error fetching bundle for static rendering: ${res.status} ${res.statusText}`);
125
122
  }
126
123
  const content = await res.text();
127
- let bun = wrapBundle(content);
128
- // This exposes the entire environment to the bundle.
129
- if (props.environment === "node") {
130
- bun = stripProcess(bun);
131
- }
132
- return bun;
124
+ return wrapBundle(content);
133
125
  }
134
126
  async function requireWithMetro(projectRoot, devServerUrl, absoluteFilePath, options = {}) {
135
127
  const content = await requireFileContentsWithMetro(projectRoot, devServerUrl, absoluteFilePath, options);
136
- return evalMetro(content);
128
+ return evalMetroAndWrapFunctions(projectRoot, content);
137
129
  }
138
130
  async function getStaticRenderFunctions(projectRoot, devServerUrl, options = {}) {
139
131
  const scriptContents = await getStaticRenderFunctionsContentAsync(projectRoot, devServerUrl, options);
140
- const contents = evalMetro(scriptContents);
132
+ return evalMetroAndWrapFunctions(projectRoot, scriptContents);
133
+ }
134
+ function evalMetroAndWrapFunctions(projectRoot, script) {
135
+ const contents = evalMetro(script);
141
136
  // wrap each function with a try/catch that uses Metro's error formatter
142
137
  return Object.keys(contents).reduce((acc, key)=>{
143
138
  const fn = contents[key];
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/start/server/getStaticRenderFunctions.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport fs from 'fs';\nimport fetch from 'node-fetch';\nimport path from 'path';\nimport requireString from 'require-from-string';\nimport resolveFrom from 'resolve-from';\n\nimport { logMetroError } from './metro/metroErrorInterface';\nimport { getMetroServerRoot } from './middleware/ManifestMiddleware';\nimport { stripAnsi } from '../../utils/ansi';\nimport { delayAsync } from '../../utils/delay';\nimport { SilentError } from '../../utils/errors';\nimport { memoize } from '../../utils/fn';\nimport { profile } from '../../utils/profile';\n\nconst debug = require('debug')('expo:start:server:node-renderer') as typeof console.log;\n\nfunction wrapBundle(str: string) {\n // Skip the metro runtime so debugging is a bit easier.\n // Replace the __r() call with an export statement.\n // Use gm to apply to the last require line. This is needed when the bundle has side-effects.\n return str.replace(/^(__r\\(.*\\);)$/gm, 'module.exports = $1');\n}\n\nfunction stripProcess(str: string) {\n // TODO: Remove from the metro prelude\n return str.replace(/process=this\\.process\\|\\|{},/m, '');\n}\n\n// TODO(EvanBacon): Group all the code together and version.\nconst getRenderModuleId = (projectRoot: string): string => {\n const moduleId = resolveFrom.silent(projectRoot, 'expo-router/node/render.js');\n if (!moduleId) {\n throw new Error(\n `A version of expo-router with Node.js support is not installed in the project.`\n );\n }\n\n return moduleId;\n};\n\ntype StaticRenderOptions = {\n // Ensure the style format is `css-xxxx` (prod) instead of `css-view-xxxx` (dev)\n dev?: boolean;\n minify?: boolean;\n platform?: string;\n environment?: 'node';\n};\n\nconst moveStaticRenderFunction = memoize(async (projectRoot: string, requiredModuleId: string) => {\n // Copy the file into the project to ensure it works in monorepos.\n // This means the file cannot have any relative imports.\n const tempDir = path.join(projectRoot, '.expo/static');\n await fs.promises.mkdir(tempDir, { recursive: true });\n const moduleId = path.join(tempDir, 'render.js');\n await fs.promises.writeFile(moduleId, await fs.promises.readFile(requiredModuleId, 'utf8'));\n // Sleep to give watchman time to register the file.\n await delayAsync(50);\n return moduleId;\n});\n\n/** @returns the js file contents required to generate the static generation function. */\nexport async function getStaticRenderFunctionsContentAsync(\n projectRoot: string,\n devServerUrl: string,\n { dev = false, minify = false, environment }: StaticRenderOptions = {}\n): Promise<string> {\n const root = getMetroServerRoot(projectRoot);\n const requiredModuleId = getRenderModuleId(root);\n let moduleId = requiredModuleId;\n\n // Cannot be accessed using Metro's server API, we need to move the file\n // into the project root and try again.\n if (path.relative(root, moduleId).startsWith('..')) {\n moduleId = await moveStaticRenderFunction(projectRoot, requiredModuleId);\n }\n\n return requireFileContentsWithMetro(root, devServerUrl, moduleId, { dev, minify, environment });\n}\n\nasync function ensureFileInRootDirectory(projectRoot: string, otherFile: string) {\n // Cannot be accessed using Metro's server API, we need to move the file\n // into the project root and try again.\n if (!path.relative(projectRoot, otherFile).startsWith('../')) {\n return otherFile;\n }\n\n // Copy the file into the project to ensure it works in monorepos.\n // This means the file cannot have any relative imports.\n const tempDir = path.join(projectRoot, '.expo/static-tmp');\n await fs.promises.mkdir(tempDir, { recursive: true });\n const moduleId = path.join(tempDir, path.basename(otherFile));\n await fs.promises.writeFile(moduleId, await fs.promises.readFile(otherFile, 'utf8'));\n // Sleep to give watchman time to register the file.\n await delayAsync(50);\n return moduleId;\n}\n\nexport async function createMetroEndpointAsync(\n projectRoot: string,\n devServerUrl: string,\n absoluteFilePath: string,\n { dev = false, platform = 'web', minify = false, environment }: StaticRenderOptions = {}\n): Promise<string> {\n const root = getMetroServerRoot(projectRoot);\n const safeOtherFile = await ensureFileInRootDirectory(projectRoot, absoluteFilePath);\n const serverPath = path.relative(root, safeOtherFile).replace(/\\.[jt]sx?$/, '.bundle');\n debug('fetching from Metro:', root, serverPath);\n\n let url = `${devServerUrl}/${serverPath}?platform=${platform}&dev=${dev}&minify=${minify}`;\n\n if (environment) {\n url += `&resolver.environment=${environment}&transform.environment=${environment}`;\n }\n return url;\n}\n\nexport class MetroNodeError extends Error {\n constructor(\n message: string,\n public rawObject: any\n ) {\n super(message);\n }\n}\n\nexport async function requireFileContentsWithMetro(\n projectRoot: string,\n devServerUrl: string,\n absoluteFilePath: string,\n props: StaticRenderOptions = {}\n): Promise<string> {\n const url = await createMetroEndpointAsync(projectRoot, devServerUrl, absoluteFilePath, props);\n\n const res = await fetch(url);\n\n // TODO: Improve error handling\n if (res.status === 500) {\n const text = await res.text();\n if (text.startsWith('{\"originModulePath\"') || text.startsWith('{\"type\":\"TransformError\"')) {\n const errorObject = JSON.parse(text);\n\n throw new MetroNodeError(stripAnsi(errorObject.message) ?? errorObject.message, errorObject);\n }\n throw new Error(`[${res.status}]: ${res.statusText}\\n${text}`);\n }\n\n if (!res.ok) {\n throw new Error(`Error fetching bundle for static rendering: ${res.status} ${res.statusText}`);\n }\n\n const content = await res.text();\n\n let bun = wrapBundle(content);\n\n // This exposes the entire environment to the bundle.\n if (props.environment === 'node') {\n bun = stripProcess(bun);\n }\n\n return bun;\n}\nexport async function requireWithMetro<T>(\n projectRoot: string,\n devServerUrl: string,\n absoluteFilePath: string,\n options: StaticRenderOptions = {}\n): Promise<T> {\n const content = await requireFileContentsWithMetro(\n projectRoot,\n devServerUrl,\n absoluteFilePath,\n options\n );\n return evalMetro(content);\n}\n\nexport async function getStaticRenderFunctions(\n projectRoot: string,\n devServerUrl: string,\n options: StaticRenderOptions = {}\n): Promise<Record<string, (...args: any[]) => Promise<any>>> {\n const scriptContents = await getStaticRenderFunctionsContentAsync(\n projectRoot,\n devServerUrl,\n options\n );\n\n const contents = evalMetro(scriptContents);\n\n // wrap each function with a try/catch that uses Metro's error formatter\n return Object.keys(contents).reduce((acc, key) => {\n const fn = contents[key];\n if (typeof fn !== 'function') {\n return { ...acc, [key]: fn };\n }\n\n acc[key] = async function (...props: any[]) {\n try {\n return await fn.apply(this, props);\n } catch (error: any) {\n await logMetroError(projectRoot, { error });\n throw new SilentError(error);\n }\n };\n return acc;\n }, {} as any);\n}\n\nfunction evalMetro(src: string) {\n return profile(requireString, 'eval-metro-bundle')(src);\n}\n"],"names":["getStaticRenderFunctionsContentAsync","createMetroEndpointAsync","requireFileContentsWithMetro","requireWithMetro","getStaticRenderFunctions","debug","require","wrapBundle","str","replace","stripProcess","getRenderModuleId","projectRoot","moduleId","resolveFrom","silent","Error","moveStaticRenderFunction","memoize","requiredModuleId","tempDir","path","join","fs","promises","mkdir","recursive","writeFile","readFile","delayAsync","devServerUrl","dev","minify","environment","root","getMetroServerRoot","relative","startsWith","ensureFileInRootDirectory","otherFile","basename","absoluteFilePath","platform","safeOtherFile","serverPath","url","MetroNodeError","constructor","message","rawObject","props","res","fetch","status","text","errorObject","JSON","parse","stripAnsi","statusText","ok","content","bun","options","evalMetro","scriptContents","contents","Object","keys","reduce","acc","key","fn","apply","error","logMetroError","SilentError","src","profile","requireString"],"mappings":"AAMA;;;;QA6DsBA,oCAAoC,GAApCA,oCAAoC;QAoCpCC,wBAAwB,GAAxBA,wBAAwB;QA4BxBC,4BAA4B,GAA5BA,4BAA4B;QAoC5BC,gBAAgB,GAAhBA,gBAAgB;QAehBC,wBAAwB,GAAxBA,wBAAwB;AAhL/B,IAAA,GAAI,kCAAJ,IAAI,EAAA;AACD,IAAA,UAAY,kCAAZ,YAAY,EAAA;AACb,IAAA,KAAM,kCAAN,MAAM,EAAA;AACG,IAAA,kBAAqB,kCAArB,qBAAqB,EAAA;AACvB,IAAA,YAAc,kCAAd,cAAc,EAAA;AAER,IAAA,oBAA6B,WAA7B,6BAA6B,CAAA;AACxB,IAAA,mBAAiC,WAAjC,iCAAiC,CAAA;AAC1C,IAAA,KAAkB,WAAlB,kBAAkB,CAAA;AACjB,IAAA,MAAmB,WAAnB,mBAAmB,CAAA;AAClB,IAAA,OAAoB,WAApB,oBAAoB,CAAA;AACxB,IAAA,GAAgB,WAAhB,gBAAgB,CAAA;AAChB,IAAA,QAAqB,WAArB,qBAAqB,CAAA;;;;;;AAE7C,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,iCAAiC,CAAC,AAAsB,AAAC;AAExF,SAASC,UAAU,CAACC,GAAW,EAAE;IAC/B,uDAAuD;IACvD,mDAAmD;I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ACC,GAAG,CAAC,GAAG,eAAgB,GAAGrB,KAAK,AAAO,EAAE;YAC1C,IAAI;gBACF,OAAO,MAAMsB,EAAE,CAACC,KAAK,CAAC,IAAI,EAAEvB,KAAK,CAAC,CAAC;aACpC,CAAC,OAAOwB,KAAK,EAAO;gBACnB,MAAMC,CAAAA,GAAAA,oBAAa,AAAwB,CAAA,cAAxB,CAAC/D,WAAW,EAAE;oBAAE8D,KAAK;iBAAE,CAAC,CAAC;gBAC5C,MAAM,IAAIE,OAAW,YAAA,CAACF,KAAK,CAAC,CAAC;aAC9B;SACF,CAAC;QACF,OAAOJ,GAAG,CAAC;KACZ,EAAE,EAAE,CAAQ,CAAC;CACf;AAED,SAASN,SAAS,CAACa,GAAW,EAAE;IAC9B,OAAOC,CAAAA,GAAAA,QAAO,AAAoC,CAAA,QAApC,CAACC,kBAAa,QAAA,EAAE,mBAAmB,CAAC,CAACF,GAAG,CAAC,CAAC;CACzD"}
1
+ {"version":3,"sources":["../../../../src/start/server/getStaticRenderFunctions.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport fs from 'fs';\nimport fetch from 'node-fetch';\nimport path from 'path';\nimport requireString from 'require-from-string';\nimport resolveFrom from 'resolve-from';\n\nimport { logMetroError } from './metro/metroErrorInterface';\nimport { getMetroServerRoot } from './middleware/ManifestMiddleware';\nimport { stripAnsi } from '../../utils/ansi';\nimport { delayAsync } from '../../utils/delay';\nimport { SilentError } from '../../utils/errors';\nimport { memoize } from '../../utils/fn';\nimport { profile } from '../../utils/profile';\n\nconst debug = require('debug')('expo:start:server:node-renderer') as typeof console.log;\n\nfunction wrapBundle(str: string) {\n // Skip the metro runtime so debugging is a bit easier.\n // Replace the __r() call with an export statement.\n // Use gm to apply to the last require line. This is needed when the bundle has side-effects.\n return str.replace(/^(__r\\(.*\\);)$/gm, 'module.exports = $1');\n}\n\n// TODO(EvanBacon): Group all the code together and version.\nconst getRenderModuleId = (projectRoot: string): string => {\n const moduleId = resolveFrom.silent(projectRoot, 'expo-router/node/render.js');\n if (!moduleId) {\n throw new Error(\n `A version of expo-router with Node.js support is not installed in the project.`\n );\n }\n\n return moduleId;\n};\n\ntype StaticRenderOptions = {\n // Ensure the style format is `css-xxxx` (prod) instead of `css-view-xxxx` (dev)\n dev?: boolean;\n minify?: boolean;\n platform?: string;\n environment?: 'node';\n};\n\nconst moveStaticRenderFunction = memoize(async (projectRoot: string, requiredModuleId: string) => {\n // Copy the file into the project to ensure it works in monorepos.\n // This means the file cannot have any relative imports.\n const tempDir = path.join(projectRoot, '.expo/static');\n await fs.promises.mkdir(tempDir, { recursive: true });\n const moduleId = path.join(tempDir, 'render.js');\n await fs.promises.writeFile(moduleId, await fs.promises.readFile(requiredModuleId, 'utf8'));\n // Sleep to give watchman time to register the file.\n await delayAsync(50);\n return moduleId;\n});\n\n/** @returns the js file contents required to generate the static generation function. */\nexport async function getStaticRenderFunctionsContentAsync(\n projectRoot: string,\n devServerUrl: string,\n { dev = false, minify = false, environment }: StaticRenderOptions = {}\n): Promise<string> {\n const root = getMetroServerRoot(projectRoot);\n const requiredModuleId = getRenderModuleId(root);\n let moduleId = requiredModuleId;\n\n // Cannot be accessed using Metro's server API, we need to move the file\n // into the project root and try again.\n if (path.relative(root, moduleId).startsWith('..')) {\n moduleId = await moveStaticRenderFunction(projectRoot, requiredModuleId);\n }\n\n return requireFileContentsWithMetro(root, devServerUrl, moduleId, { dev, minify, environment });\n}\n\nasync function ensureFileInRootDirectory(projectRoot: string, otherFile: string) {\n // Cannot be accessed using Metro's server API, we need to move the file\n // into the project root and try again.\n if (!path.relative(projectRoot, otherFile).startsWith('../')) {\n return otherFile;\n }\n\n // Copy the file into the project to ensure it works in monorepos.\n // This means the file cannot have any relative imports.\n const tempDir = path.join(projectRoot, '.expo/static-tmp');\n await fs.promises.mkdir(tempDir, { recursive: true });\n const moduleId = path.join(tempDir, path.basename(otherFile));\n await fs.promises.writeFile(moduleId, await fs.promises.readFile(otherFile, 'utf8'));\n // Sleep to give watchman time to register the file.\n await delayAsync(50);\n return moduleId;\n}\n\nexport async function createMetroEndpointAsync(\n projectRoot: string,\n devServerUrl: string,\n absoluteFilePath: string,\n { dev = false, platform = 'web', minify = false, environment }: StaticRenderOptions = {}\n): Promise<string> {\n const root = getMetroServerRoot(projectRoot);\n const safeOtherFile = await ensureFileInRootDirectory(projectRoot, absoluteFilePath);\n const serverPath = path.relative(root, safeOtherFile).replace(/\\.[jt]sx?$/, '.bundle');\n debug('fetching from Metro:', root, serverPath);\n\n let url = `${devServerUrl}/${serverPath}?platform=${platform}&dev=${dev}&minify=${minify}`;\n\n if (environment) {\n url += `&resolver.environment=${environment}&transform.environment=${environment}`;\n }\n return url;\n}\n\nexport class MetroNodeError extends Error {\n constructor(\n message: string,\n public rawObject: any\n ) {\n super(message);\n }\n}\n\nexport async function requireFileContentsWithMetro(\n projectRoot: string,\n devServerUrl: string,\n absoluteFilePath: string,\n props: StaticRenderOptions = {}\n): Promise<string> {\n const url = await createMetroEndpointAsync(projectRoot, devServerUrl, absoluteFilePath, props);\n\n const res = await fetch(url);\n\n // TODO: Improve error handling\n if (res.status === 500) {\n const text = await res.text();\n if (text.startsWith('{\"originModulePath\"') || text.startsWith('{\"type\":\"TransformError\"')) {\n const errorObject = JSON.parse(text);\n\n throw new MetroNodeError(stripAnsi(errorObject.message) ?? errorObject.message, errorObject);\n }\n throw new Error(`[${res.status}]: ${res.statusText}\\n${text}`);\n }\n\n if (!res.ok) {\n throw new Error(`Error fetching bundle for static rendering: ${res.status} ${res.statusText}`);\n }\n\n const content = await res.text();\n\n return wrapBundle(content);\n}\n\nexport async function requireWithMetro<T extends Record<string, (...args: any[]) => Promise<any>>>(\n projectRoot: string,\n devServerUrl: string,\n absoluteFilePath: string,\n options: StaticRenderOptions = {}\n): Promise<T> {\n const content = await requireFileContentsWithMetro(\n projectRoot,\n devServerUrl,\n absoluteFilePath,\n options\n );\n return evalMetroAndWrapFunctions<T>(projectRoot, content);\n}\n\nexport async function getStaticRenderFunctions(\n projectRoot: string,\n devServerUrl: string,\n options: StaticRenderOptions = {}\n): Promise<Record<string, (...args: any[]) => Promise<any>>> {\n const scriptContents = await getStaticRenderFunctionsContentAsync(\n projectRoot,\n devServerUrl,\n options\n );\n\n return evalMetroAndWrapFunctions(projectRoot, scriptContents);\n}\n\nexport function evalMetroAndWrapFunctions<T = Record<string, (...args: any[]) => Promise<any>>>(\n projectRoot: string,\n script: string\n): Promise<T> {\n const contents = evalMetro(script);\n\n // wrap each function with a try/catch that uses Metro's error formatter\n return Object.keys(contents).reduce((acc, key) => {\n const fn = contents[key];\n if (typeof fn !== 'function') {\n return { ...acc, [key]: fn };\n }\n\n acc[key] = async function (...props: any[]) {\n try {\n return await fn.apply(this, props);\n } catch (error: any) {\n await logMetroError(projectRoot, { error });\n throw new SilentError(error);\n }\n };\n return acc;\n }, {} as any);\n}\n\nfunction evalMetro(src: string) {\n return profile(requireString, 'eval-metro-bundle')(src);\n}\n"],"names":["getStaticRenderFunctionsContentAsync","createMetroEndpointAsync","requireFileContentsWithMetro","requireWithMetro","getStaticRenderFunctions","evalMetroAndWrapFunctions","debug","require","wrapBundle","str","replace","getRenderModuleId","projectRoot","moduleId","resolveFrom","silent","Error","moveStaticRenderFunction","memoize","requiredModuleId","tempDir","path","join","fs","promises","mkdir","recursive","writeFile","readFile","delayAsync","devServerUrl","dev","minify","environment","root","getMetroServerRoot","relative","startsWith","ensureFileInRootDirectory","otherFile","basename","absoluteFilePath","platform","safeOtherFile","serverPath","url","MetroNodeError","constructor","message","rawObject","props","res","fetch","status","text","errorObject","JSON","parse","stripAnsi","statusText","ok","content","options","scriptContents","script","contents","evalMetro","Object","keys","reduce","acc","key","fn","apply","error","logMetroError","SilentError","src","profile","requireString"],"mappings":"AAMA;;;;QAwDsBA,oCAAoC,GAApCA,oCAAoC;QAoCpCC,wBAAwB,GAAxBA,wBAAwB;QA4BxBC,4BAA4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16 @@ Object.defineProperty(exports, "__esModule", {
4
4
  });
5
5
  exports.getDeepLinkHandler = getDeepLinkHandler;
6
6
  var _config = require("@expo/config");
7
- var _devServer = require("@expo/dev-server");
8
7
  var runtimeEnv = _interopRequireWildcard(require("@expo/env"));
9
8
  var _chalk = _interopRequireDefault(require("chalk"));
10
9
  var _nodeFetch = _interopRequireDefault(require("node-fetch"));
11
10
  var _path = _interopRequireDefault(require("path"));
11
+ var _bundleApiRoutes = require("./bundleApiRoutes");
12
+ var _createServerRouteMiddleware = require("./createServerRouteMiddleware");
13
+ var _fetchRouterManifest = require("./fetchRouterManifest");
12
14
  var _instantiateMetro = require("./instantiateMetro");
13
- var _metroErrorInterface = require("./metroErrorInterface");
14
15
  var _metroWatchTypeScriptFiles = require("./metroWatchTypeScriptFiles");
16
+ var _router = require("./router");
15
17
  var _waitForMetroToObserveTypeScriptFile = require("./waitForMetroToObserveTypeScriptFile");
16
18
  var _log = require("../../../log");
17
19
  var _getDevClientProperties = _interopRequireDefault(require("../../../utils/analytics/getDevClientProperties"));
@@ -29,6 +31,7 @@ var _manifestMiddleware = require("../middleware/ManifestMiddleware");
29
31
  var _reactDevToolsPageMiddleware = require("../middleware/ReactDevToolsPageMiddleware");
30
32
  var _runtimeRedirectMiddleware = require("../middleware/RuntimeRedirectMiddleware");
31
33
  var _serveStaticMiddleware = require("../middleware/ServeStaticMiddleware");
34
+ var _mutations = require("../middleware/mutations");
32
35
  var _startTypescriptTypeGeneration = require("../type-generation/startTypescriptTypeGeneration");
33
36
  function _interopRequireDefault(obj) {
34
37
  return obj && obj.__esModule ? obj : {
@@ -63,6 +66,7 @@ class ForwardHtmlError extends _errors.CommandError {
63
66
  this.statusCode = statusCode;
64
67
  }
65
68
  }
69
+ exports.ForwardHtmlError = ForwardHtmlError;
66
70
  const debug = require("debug")("expo:start:server:metro");
67
71
  /** Default port to use for apps running in Expo Go. */ const EXPO_GO_METRO_PORT = 8081;
68
72
  /** Default port to use for apps that run in standard React Native projects or Expo Dev Clients. */ const DEV_CLIENT_METRO_PORT = 8081;
@@ -78,7 +82,26 @@ class MetroBundlerDevServer extends _bundlerDevServer.BundlerDevServer {
78
82
  (options.devClient ? Number(process.env.RCT_METRO_PORT) || DEV_CLIENT_METRO_PORT : await (0, _port).getFreePortAsync(EXPO_GO_METRO_PORT));
79
83
  return port;
80
84
  }
81
- async composeResourcesWithHtml({ mode , resources , template , devBundleUrl }) {
85
+ async getExpoRouterRoutesManifestAsync({ appDir }) {
86
+ const manifest = await (0, _fetchRouterManifest).fetchManifest(this.projectRoot, {
87
+ asJson: true,
88
+ appDir
89
+ });
90
+ if (!manifest) {
91
+ throw new _errors.CommandError("EXPO_ROUTER_SERVER_MANIFEST", "Unexpected error: server manifest could not be fetched.");
92
+ }
93
+ return manifest;
94
+ }
95
+ async exportExpoRouterApiRoutesAsync({ mode , appDir }) {
96
+ var ref;
97
+ return (0, _bundleApiRoutes).exportAllApiRoutesAsync(this.projectRoot, {
98
+ mode,
99
+ appDir,
100
+ port: (ref = this.getInstance()) == null ? void 0 : ref.location.port,
101
+ shouldThrow: true
102
+ });
103
+ }
104
+ async composeResourcesWithHtml({ mode , resources , template , devBundleUrl , basePath }) {
82
105
  if (!resources) {
83
106
  return "";
84
107
  }
@@ -86,6 +109,7 @@ class MetroBundlerDevServer extends _bundlerDevServer.BundlerDevServer {
86
109
  return htmlFromSerialAssets(resources, {
87
110
  dev: isDev,
88
111
  template,
112
+ basePath,
89
113
  bundleUrl: isDev ? devBundleUrl : undefined
90
114
  });
91
115
  }
@@ -100,7 +124,8 @@ class MetroBundlerDevServer extends _bundlerDevServer.BundlerDevServer {
100
124
  return {
101
125
  // Get routes from Expo Router.
102
126
  manifest: await getManifest({
103
- fetchData: true
127
+ fetchData: true,
128
+ preserveApiRoutes: false
104
129
  }),
105
130
  // Get route generating function
106
131
  async renderAsync (path) {
@@ -163,13 +188,7 @@ class MetroBundlerDevServer extends _bundlerDevServer.BundlerDevServer {
163
188
  }
164
189
  throw new Error("Invalid resources returned from the Metro serializer. Expected array, found: " + data);
165
190
  }
166
- async renderStaticErrorAsync(error) {
167
- return (0, _metroErrorInterface).getErrorOverlayHtmlAsync({
168
- error,
169
- projectRoot: this.projectRoot
170
- });
171
- }
172
- async getStaticPageAsync(pathname, { mode , minify =mode !== "development" }) {
191
+ async getStaticPageAsync(pathname, { mode , minify =mode !== "development" , basePath }) {
173
192
  const devBundleUrlPathname = (0, _manifestMiddleware).createBundleUrlPath({
174
193
  platform: "web",
175
194
  mode,
@@ -198,7 +217,8 @@ class MetroBundlerDevServer extends _bundlerDevServer.BundlerDevServer {
198
217
  mode,
199
218
  resources,
200
219
  template: staticHtml,
201
- devBundleUrl: devBundleUrlPathname
220
+ devBundleUrl: devBundleUrlPathname,
221
+ basePath
202
222
  });
203
223
  return {
204
224
  content,
@@ -246,14 +266,14 @@ class MetroBundlerDevServer extends _bundlerDevServer.BundlerDevServer {
246
266
  });
247
267
  const manifestMiddleware = await this.getManifestMiddlewareAsync(options);
248
268
  // Important that we noop source maps for context modules as soon as possible.
249
- (0, _devServer).prependMiddleware(middleware, new _contextModuleSourceMapsMiddleware.ContextModuleSourceMapsMiddleware().getHandler());
269
+ (0, _mutations).prependMiddleware(middleware, new _contextModuleSourceMapsMiddleware.ContextModuleSourceMapsMiddleware().getHandler());
250
270
  // We need the manifest handler to be the first middleware to run so our
251
271
  // routes take precedence over static files. For example, the manifest is
252
272
  // served from '/' and if the user has an index.html file in their project
253
273
  // then the manifest handler will never run, the static middleware will run
254
274
  // and serve index.html instead of the manifest.
255
275
  // https://github.com/expo/expo/issues/13114
256
- (0, _devServer).prependMiddleware(middleware, manifestMiddleware.getHandler());
276
+ (0, _mutations).prependMiddleware(middleware, manifestMiddleware.getHandler());
257
277
  var _scheme;
258
278
  middleware.use(new _interstitialPageMiddleware.InterstitialPageMiddleware(this.projectRoot, {
259
279
  // TODO: Prevent this from becoming stale.
@@ -267,8 +287,8 @@ class MetroBundlerDevServer extends _bundlerDevServer.BundlerDevServer {
267
287
  var ref;
268
288
  return (ref = this.urlCreator) == null ? void 0 : ref.constructDevClientUrl();
269
289
  } else {
270
- var ref1;
271
- return (ref1 = this.urlCreator) == null ? void 0 : ref1.constructUrl({
290
+ var ref3;
291
+ return (ref3 = this.urlCreator) == null ? void 0 : ref3.constructUrl({
272
292
  scheme: "exp"
273
293
  });
274
294
  }
@@ -278,53 +298,57 @@ class MetroBundlerDevServer extends _bundlerDevServer.BundlerDevServer {
278
298
  middleware.use(new _createFileMiddleware.CreateFileMiddleware(this.projectRoot).getHandler());
279
299
  // Append support for redirecting unhandled requests to the index.html page on web.
280
300
  if (this.isTargetingWeb()) {
281
- var ref2;
301
+ var ref4, ref1;
282
302
  const { exp } = (0, _config).getConfig(this.projectRoot, {
283
303
  skipSDKVersionRequirement: true
284
304
  });
285
- const useWebSSG = ((ref2 = exp.web) == null ? void 0 : ref2.output) === "static";
305
+ var ref2;
306
+ const useServerRendering = [
307
+ "static",
308
+ "server"
309
+ ].includes((ref2 = (ref4 = exp.web) == null ? void 0 : ref4.output) != null ? ref2 : "");
286
310
  // This MUST be after the manifest middleware so it doesn't have a chance to serve the template `public/index.html`.
287
311
  middleware.use(new _serveStaticMiddleware.ServeStaticMiddleware(this.projectRoot).getHandler());
288
312
  // This should come after the static middleware so it doesn't serve the favicon from `public/favicon.ico`.
289
313
  middleware.use(new _faviconMiddleware.FaviconMiddleware(this.projectRoot).getHandler());
290
- if (useWebSSG) {
291
- middleware.use(async (req, res, next)=>{
292
- if (!(req == null ? void 0 : req.url)) {
293
- return next();
294
- }
295
- // TODO: Formal manifest for allowed paths
296
- if (req.url.endsWith(".ico")) {
297
- return next();
298
- }
299
- if (req.url.includes("serializer.output=static")) {
300
- return next();
301
- }
302
- try {
303
- var _mode;
304
- const { content } = await this.getStaticPageAsync(req.url, {
305
- mode: (_mode = options.mode) != null ? _mode : "development"
306
- });
307
- res.setHeader("Content-Type", "text/html");
308
- res.end(content);
309
- } catch (error) {
310
- res.setHeader("Content-Type", "text/html");
311
- // Forward the Metro server response as-is. It won't be pretty, but at least it will be accurate.
312
- if (error instanceof ForwardHtmlError) {
313
- res.statusCode = error.statusCode;
314
- res.end(error.html);
315
- return;
314
+ const appDir = (0, _router).getRouterDirectoryWithManifest(this.projectRoot, exp);
315
+ middleware.use((0, _createServerRouteMiddleware).createRouteHandlerMiddleware(this.projectRoot, {
316
+ ...options,
317
+ appDir,
318
+ getWebBundleUrl: manifestMiddleware.getWebBundleUrl.bind(manifestMiddleware),
319
+ getStaticPageAsync: (pathname)=>{
320
+ var _mode;
321
+ return this.getStaticPageAsync(pathname, {
322
+ mode: (_mode = options.mode) != null ? _mode : "development",
323
+ minify: options.minify,
324
+ // No base path in development
325
+ basePath: ""
326
+ });
327
+ }
328
+ }));
329
+ // @ts-expect-error: TODO
330
+ if (((ref1 = exp.web) == null ? void 0 : ref1.output) === "server") {
331
+ // Cache observation for API Routes...
332
+ (0, _waitForMetroToObserveTypeScriptFile).observeApiRouteChanges(this.projectRoot, {
333
+ metro,
334
+ server
335
+ }, async (filepath, op)=>{
336
+ if ((0, _router).isApiRouteConvention(filepath)) {
337
+ debug(`[expo-cli] ${op} ${filepath}`);
338
+ if (op === "change" || op === "add") {
339
+ (0, _bundleApiRoutes).rebundleApiRoute(this.projectRoot, filepath, {
340
+ ...options,
341
+ appDir
342
+ });
316
343
  }
317
- try {
318
- res.end(await this.renderStaticErrorAsync(error));
319
- } catch (staticError) {
320
- // Fallback error for when Expo Router is misconfigured in the project.
321
- res.end("<span><h3>Internal Error:</h3><b>Project is not setup correctly for static rendering (check terminal for more info):</b><br/>" + error.message + "<br/><br/>" + staticError.message + "</span>");
344
+ if (op === "delete") {
345
+ // TODO: Cancel the bundling of the deleted route.
322
346
  }
323
347
  }
324
348
  });
325
349
  }
326
350
  // This MUST run last since it's the fallback.
327
- if (!useWebSSG) {
351
+ if (!useServerRendering) {
328
352
  middleware.use(new _historyFallbackMiddleware.HistoryFallbackMiddleware(manifestMiddleware.getHandler().internal).getHandler());
329
353
  }
330
354
  }
@@ -424,7 +448,7 @@ function getDeepLinkHandler(projectRoot) {
424
448
  });
425
449
  };
426
450
  }
427
- function htmlFromSerialAssets(assets, { dev , template , bundleUrl }) {
451
+ function htmlFromSerialAssets(assets, { dev , template , basePath , bundleUrl }) {
428
452
  // Combine the CSS modules into tags that have hot refresh data attributes.
429
453
  const styleString = assets.filter((asset)=>asset.type === "css"
430
454
  ).map(({ metadata , filename , source })=>{
@@ -432,15 +456,15 @@ function htmlFromSerialAssets(assets, { dev , template , bundleUrl }) {
432
456
  return `<style data-expo-css-hmr="${metadata.hmrId}">` + source + "\n</style>";
433
457
  } else {
434
458
  return [
435
- `<link rel="preload" href="/${filename}" as="style">`,
436
- `<link rel="stylesheet" href="/${filename}">`,
459
+ `<link rel="preload" href="${basePath}/${filename}" as="style">`,
460
+ `<link rel="stylesheet" href="${basePath}/${filename}">`,
437
461
  ].join("");
438
462
  }
439
463
  }).join("");
440
464
  const jsAssets = assets.filter((asset)=>asset.type === "js"
441
465
  );
442
466
  const scripts = bundleUrl ? `<script src="${bundleUrl}" defer></script>` : jsAssets.map(({ filename })=>{
443
- return `<script src="/${filename}" defer></script>`;
467
+ return `<script src="${basePath}/${filename}" defer></script>`;
444
468
  }).join("");
445
469
  return template.replace("</head>", `${styleString}</head>`).replace("</body>", `${scripts}\n</body>`);
446
470
  }