@expo/cli 0.16.8 → 0.17.0

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 (52) hide show
  1. package/build/bin/cli +4 -3
  2. package/build/bin/cli.map +1 -1
  3. package/build/src/customize/customizeAsync.js +2 -1
  4. package/build/src/customize/customizeAsync.js.map +1 -1
  5. package/build/src/customize/typescript.js +1 -1
  6. package/build/src/customize/typescript.js.map +1 -1
  7. package/build/src/export/resolveOptions.js +7 -5
  8. package/build/src/export/resolveOptions.js.map +1 -1
  9. package/build/src/export/web/exportWebAsync.js +1 -1
  10. package/build/src/export/web/exportWebAsync.js.map +1 -1
  11. package/build/src/export/web/index.js +1 -1
  12. package/build/src/export/web/index.js.map +1 -1
  13. package/build/src/install/installAsync.js +1 -5
  14. package/build/src/install/installAsync.js.map +1 -1
  15. package/build/src/prebuild/configureProjectAsync.js +7 -1
  16. package/build/src/prebuild/configureProjectAsync.js.map +1 -1
  17. package/build/src/prebuild/prebuildAsync.js +3 -2
  18. package/build/src/prebuild/prebuildAsync.js.map +1 -1
  19. package/build/src/prebuild/resolveTemplate.js +41 -48
  20. package/build/src/prebuild/resolveTemplate.js.map +1 -1
  21. package/build/src/prebuild/updateFromTemplate.js +9 -8
  22. package/build/src/prebuild/updateFromTemplate.js.map +1 -1
  23. package/build/src/start/doctor/dependencies/ensureDependenciesAsync.js +4 -12
  24. package/build/src/start/doctor/dependencies/ensureDependenciesAsync.js.map +1 -1
  25. package/build/src/start/doctor/web/WebSupportProjectPrerequisite.js +6 -1
  26. package/build/src/start/doctor/web/WebSupportProjectPrerequisite.js.map +1 -1
  27. package/build/src/start/server/DevServerManager.js +2 -2
  28. package/build/src/start/server/DevServerManager.js.map +1 -1
  29. package/build/src/start/server/metro/createServerRouteMiddleware.js +12 -7
  30. package/build/src/start/server/metro/createServerRouteMiddleware.js.map +1 -1
  31. package/build/src/start/server/metro/instantiateMetro.js +5 -7
  32. package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
  33. package/build/src/start/server/metro/withMetroMultiPlatform.js +7 -4
  34. package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
  35. package/build/src/start/server/middleware/CorsMiddleware.js +55 -0
  36. package/build/src/start/server/middleware/CorsMiddleware.js.map +1 -0
  37. package/build/src/start/server/middleware/ManifestMiddleware.js +5 -5
  38. package/build/src/start/server/middleware/ManifestMiddleware.js.map +1 -1
  39. package/build/src/start/server/platformBundlers.js +18 -5
  40. package/build/src/start/server/platformBundlers.js.map +1 -1
  41. package/build/src/start/startAsync.js +1 -1
  42. package/build/src/start/startAsync.js.map +1 -1
  43. package/build/src/utils/analytics/rudderstackClient.js +2 -2
  44. package/build/src/utils/npm.js +12 -4
  45. package/build/src/utils/npm.js.map +1 -1
  46. package/build/src/utils/resolveArgs.js +8 -2
  47. package/build/src/utils/resolveArgs.js.map +1 -1
  48. package/package.json +3 -3
  49. package/build/src/start/server/middleware/remoteDevtoolsCorsMiddleware.js +0 -31
  50. package/build/src/start/server/middleware/remoteDevtoolsCorsMiddleware.js.map +0 -1
  51. package/build/src/start/server/middleware/remoteDevtoolsSecurityHeadersMiddleware.js +0 -17
  52. package/build/src/start/server/middleware/remoteDevtoolsSecurityHeadersMiddleware.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/createServerRouteMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport type { ProjectConfig } from '@expo/config';\nimport { ExpoResponse } from '@expo/server';\nimport { createRequestHandler } from '@expo/server/build/vendor/http';\nimport requireString from 'require-from-string';\nimport resolve from 'resolve';\nimport { promisify } from 'util';\n\nimport { ForwardHtmlError } from './MetroBundlerDevServer';\nimport { bundleApiRoute } from './bundleApiRoutes';\nimport { fetchManifest } from './fetchRouterManifest';\nimport { getErrorOverlayHtmlAsync, logMetroError, logMetroErrorAsync } from './metroErrorInterface';\nimport { warnInvalidWebOutput } from './router';\nimport { Log } from '../../../log';\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\nconst resolveAsync = promisify(resolve) as any as (\n id: string,\n opts: resolve.AsyncOpts\n) => Promise<string | null>;\n\nexport function createRouteHandlerMiddleware(\n projectRoot: string,\n options: {\n mode?: string;\n appDir: string;\n routerRoot: string;\n port?: number;\n baseUrl: string;\n getWebBundleUrl: () => string;\n getStaticPageAsync: (pathname: string) => Promise<{ content: string }>;\n config: ProjectConfig;\n }\n) {\n return createRequestHandler(\n { build: '' },\n {\n async getRoutesManifest() {\n const manifest = await fetchManifest<RegExp>(projectRoot, options);\n debug('manifest', manifest);\n // NOTE: no app dir if null\n // TODO: Redirect to 404 page\n return (\n manifest ?? {\n // Support the onboarding screen if there's no manifest\n htmlRoutes: [\n {\n file: 'index.js',\n page: '/index',\n routeKeys: {},\n namedRegex: /^\\/(?:index)?\\/?$/i,\n },\n ],\n apiRoutes: [],\n notFoundRoutes: [],\n }\n );\n },\n async getHtml(request) {\n try {\n const { content } = await options.getStaticPageAsync(request.url);\n return content;\n } catch (error: any) {\n // Forward the Metro server response as-is. It won't be pretty, but at least it will be accurate.\n if (error instanceof ForwardHtmlError) {\n return new ExpoResponse(error.html, {\n status: error.statusCode,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n }\n\n try {\n return new ExpoResponse(\n await getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot: options.routerRoot,\n }),\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n } catch (staticError: any) {\n // Fallback error for when Expo Router is misconfigured in the project.\n return new ExpoResponse(\n '<span><h3>Internal Error:</h3><b>Project is not setup correctly for static rendering (check terminal for more info):</b><br/>' +\n error.message +\n '<br/><br/>' +\n staticError.message +\n '</span>',\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n }\n },\n logApiRouteExecutionError(error) {\n logMetroError(projectRoot, { error });\n },\n async getApiRoute(route) {\n const { exp } = options.config;\n if (exp.web?.output !== 'server') {\n warnInvalidWebOutput();\n }\n\n const resolvedFunctionPath = await resolveAsync(route.page, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n });\n\n const middlewareContents = await bundleApiRoute(\n projectRoot,\n resolvedFunctionPath!,\n options\n );\n if (!middlewareContents) {\n // TODO: Error handling\n return null;\n }\n\n try {\n debug(`Bundling middleware at: ${resolvedFunctionPath}`);\n return requireString(middlewareContents);\n } catch (error: any) {\n if (error instanceof Error) {\n await logMetroErrorAsync({ projectRoot, error });\n } else {\n Log.error('Failed to load middleware: ' + error);\n }\n return new ExpoResponse(\n 'Failed to load middleware: ' + resolvedFunctionPath + '\\n\\n' + error.message,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n },\n }\n );\n}\n"],"names":["createRouteHandlerMiddleware","debug","require","resolveAsync","promisify","resolve","projectRoot","options","createRequestHandler","build","getRoutesManifest","manifest","fetchManifest","htmlRoutes","file","page","routeKeys","namedRegex","apiRoutes","notFoundRoutes","getHtml","request","content","getStaticPageAsync","url","error","ForwardHtmlError","ExpoResponse","html","status","statusCode","headers","getErrorOverlayHtmlAsync","routerRoot","staticError","message","logApiRouteExecutionError","logMetroError","getApiRoute","route","exp","config","web","output","warnInvalidWebOutput","resolvedFunctionPath","extensions","basedir","appDir","middlewareContents","bundleApiRoute","requireString","Error","logMetroErrorAsync","Log"],"mappings":"AAMA;;;;QAqBgBA,4BAA4B,GAA5BA,4BAA4B;AApBf,IAAA,OAAc,WAAd,cAAc,CAAA;AACN,IAAA,KAAgC,WAAhC,gCAAgC,CAAA;AAC3C,IAAA,kBAAqB,kCAArB,qBAAqB,EAAA;AAC3B,IAAA,QAAS,kCAAT,SAAS,EAAA;AACH,IAAA,KAAM,WAAN,MAAM,CAAA;AAEC,IAAA,sBAAyB,WAAzB,yBAAyB,CAAA;AAC3B,IAAA,gBAAmB,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cesContent":["/**\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 */\n\nimport type { ProjectConfig } from '@expo/config';\nimport requireString from 'require-from-string';\nimport resolve from 'resolve';\nimport resolveFrom from 'resolve-from';\nimport { promisify } from 'util';\n\nimport { ForwardHtmlError } from './MetroBundlerDevServer';\nimport { bundleApiRoute } from './bundleApiRoutes';\nimport { fetchManifest } from './fetchRouterManifest';\nimport { getErrorOverlayHtmlAsync, logMetroError, logMetroErrorAsync } from './metroErrorInterface';\nimport { warnInvalidWebOutput } from './router';\nimport { Log } from '../../../log';\nimport { CommandError } from '../../../utils/errors';\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\nconst resolveAsync = promisify(resolve) as any as (\n id: string,\n opts: resolve.AsyncOpts\n) => Promise<string | null>;\n\nexport function createRouteHandlerMiddleware(\n projectRoot: string,\n options: {\n mode?: string;\n appDir: string;\n routerRoot: string;\n port?: number;\n baseUrl: string;\n getWebBundleUrl: () => string;\n getStaticPageAsync: (pathname: string) => Promise<{ content: string }>;\n config: ProjectConfig;\n }\n) {\n if (!resolveFrom.silent(projectRoot, 'expo-router')) {\n throw new CommandError(\n 'static and server rendering requires the expo-router package to be installed in your project.'\n );\n }\n\n const { ExpoResponse } = require('expo-router/server') as typeof import('expo-router/server');\n const { createRequestHandler } =\n require('@expo/server/build/vendor/http') as typeof import('@expo/server/build/vendor/http');\n\n return createRequestHandler(\n { build: '' },\n {\n async getRoutesManifest() {\n const manifest = await fetchManifest<RegExp>(projectRoot, options);\n debug('manifest', manifest);\n // NOTE: no app dir if null\n // TODO: Redirect to 404 page\n return (\n manifest ?? {\n // Support the onboarding screen if there's no manifest\n htmlRoutes: [\n {\n file: 'index.js',\n page: '/index',\n routeKeys: {},\n namedRegex: /^\\/(?:index)?\\/?$/i,\n },\n ],\n apiRoutes: [],\n notFoundRoutes: [],\n }\n );\n },\n async getHtml(request) {\n try {\n const { content } = await options.getStaticPageAsync(request.url);\n return content;\n } catch (error: any) {\n // Forward the Metro server response as-is. It won't be pretty, but at least it will be accurate.\n if (error instanceof ForwardHtmlError) {\n return new ExpoResponse(error.html, {\n status: error.statusCode,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n }\n\n try {\n return new ExpoResponse(\n await getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot: options.routerRoot,\n }),\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n } catch (staticError: any) {\n // Fallback error for when Expo Router is misconfigured in the project.\n return new ExpoResponse(\n '<span><h3>Internal Error:</h3><b>Project is not setup correctly for static rendering (check terminal for more info):</b><br/>' +\n error.message +\n '<br/><br/>' +\n staticError.message +\n '</span>',\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n }\n },\n logApiRouteExecutionError(error) {\n logMetroError(projectRoot, { error });\n },\n async getApiRoute(route) {\n const { exp } = options.config;\n if (exp.web?.output !== 'server') {\n warnInvalidWebOutput();\n }\n\n const resolvedFunctionPath = await resolveAsync(route.page, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n });\n\n const middlewareContents = await bundleApiRoute(\n projectRoot,\n resolvedFunctionPath!,\n options\n );\n if (!middlewareContents) {\n // TODO: Error handling\n return null;\n }\n\n try {\n debug(`Bundling middleware at: ${resolvedFunctionPath}`);\n return requireString(middlewareContents);\n } catch (error: any) {\n if (error instanceof Error) {\n await logMetroErrorAsync({ projectRoot, error });\n } else {\n Log.error('Failed to load middleware: ' + error);\n }\n return new ExpoResponse(\n 'Failed to load middleware: ' + resolvedFunctionPath + '\\n\\n' + error.message,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n },\n }\n );\n}\n"],"names":["createRouteHandlerMiddleware","debug","require","resolveAsync","promisify","resolve","projectRoot","options","resolveFrom","silent","CommandError","ExpoResponse","createRequestHandler","build","getRoutesManifest","manifest","fetchManifest","htmlRoutes","file","page","routeKeys","namedRegex","apiRoutes","notFoundRoutes","getHtml","request","content","getStaticPageAsync","url","error","ForwardHtmlError","html","status","statusCode","headers","getErrorOverlayHtmlAsync","routerRoot","staticError","message","logApiRouteExecutionError","logMetroError","getApiRoute","route","exp","config","web","output","warnInvalidWebOutput","resolvedFunctionPath","extensions","basedir","appDir","middlewareContents","bundleApiRoute","requireString","Error","logMetroErrorAsync","Log"],"mappings":"AAOA;;;;QAqBgBA,4BAA4B,GAA5BA,4BAA4B;AApBlB,IAAA,kBAAqB,kCAArB,qBAAqB,EAAA;AAC3B,IAAA,QAAS,kCAAT,SAAS,EAAA;AACL,IAAA,YAAc,kCAAd,cAAc,EAAA;AACZ,IAAA,KAAM,WAAN,MAAM,CAAA;AAEC,IAAA,sBAAyB,WAAzB,yBAAyB,CAAA;AAC3B,IAAA,gBAAmB,WAAnB,mBAAmB,CAAA;AACpB,IAAA,oBAAuB,WAAvB,uBAAuB,CAAA;AACuB,IAAA,oBAAuB,WAAvB,uBAAuB,CAAA;AAC9D,IAAA,OAAU,WAAV,UAAU,CAAA;AAC3B,IAAA,IAAc,WAAd,cAAc,CAAA;AACL,IAAA,OAAuB,WAAvB,uBAAuB,CAAA;;;;;;AAEpD,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,yBAAyB,CAAC,AAAsB,AAAC;AAEhF,MAAMC,YAAY,GAAGC,CAAAA,GAAAA,KAAS,AAAS,CAAA,UAAT,CAACC,QAAO,QAAA,CAAC,AAGZ,AAAC;AAErB,SAASL,4BAA4B,CAC1CM,WAAmB,EACnBC,OASC,EACD;IACA,IAAI,CAACC,YAAW,QAAA,CAACC,MAAM,CAACH,WAAW,EAAE,aAAa,CAAC,EAAE;QACnD,MAAM,IAAII,OAAY,aAAA,CACpB,+FAA+F,CAChG,CAAC;KACH;IAED,MAAM,EAAEC,YAAY,CAAA,EAAE,GAAGT,OAAO,CAAC,oBAAoB,CAAC,AAAuC,AAAC;IAC9F,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AO,CACR,AAAC;YACF,IAAI,CAAC6C,kBAAkB,EAAE;gBACvB,uBAAuB;gBACvB,OAAO,IAAI,CAAC;aACb;YAED,IAAI;gBACFnD,KAAK,CAAC,CAAC,wBAAwB,EAAE+C,oBAAoB,CAAC,CAAC,CAAC,CAAC;gBACzD,OAAOM,CAAAA,GAAAA,kBAAa,AAAoB,CAAA,QAApB,CAACF,kBAAkB,CAAC,CAAC;aAC1C,CAAC,OAAOvB,KAAK,EAAO;gBACnB,IAAIA,KAAK,YAAY0B,KAAK,EAAE;oBAC1B,MAAMC,CAAAA,GAAAA,oBAAkB,AAAwB,CAAA,mBAAxB,CAAC;wBAAElD,WAAW;wBAAEuB,KAAK;qBAAE,CAAC,CAAC;iBAClD,MAAM;oBACL4B,IAAG,IAAA,CAAC5B,KAAK,CAAC,6BAA6B,GAAGA,KAAK,CAAC,CAAC;iBAClD;gBACD,OAAO,IAAIlB,YAAY,CACrB,6BAA6B,GAAGqC,oBAAoB,GAAG,MAAM,GAAGnB,KAAK,CAACS,OAAO,EAC7E;oBACEN,MAAM,EAAE,GAAG;oBACXE,OAAO,EAAE;wBACP,cAAc,EAAE,WAAW;qBAC5B;iBACF,CACF,CAAC;aACH;SACF;KACF,CACF,CAAC;CACH"}
@@ -21,11 +21,10 @@ var _getMetroProperties = require("../../../utils/analytics/getMetroProperties")
21
21
  var _metroDebuggerMiddleware = require("../../../utils/analytics/metroDebuggerMiddleware");
22
22
  var _rudderstackClient = require("../../../utils/analytics/rudderstackClient");
23
23
  var _env = require("../../../utils/env");
24
+ var _corsMiddleware = require("../middleware/CorsMiddleware");
24
25
  var _manifestMiddleware = require("../middleware/ManifestMiddleware");
25
26
  var _createJsInspectorMiddleware = require("../middleware/inspector/createJsInspectorMiddleware");
26
27
  var _mutations = require("../middleware/mutations");
27
- var _remoteDevtoolsCorsMiddleware = require("../middleware/remoteDevtoolsCorsMiddleware");
28
- var _remoteDevtoolsSecurityHeadersMiddleware = require("../middleware/remoteDevtoolsSecurityHeadersMiddleware");
29
28
  var _suppressErrorMiddleware = require("../middleware/suppressErrorMiddleware");
30
29
  var _platformBundlers = require("../platformBundlers");
31
30
  function _interopRequireDefault(obj) {
@@ -92,10 +91,11 @@ async function loadMetroConfigAsync(projectRoot, options, { exp =(0, _config).ge
92
91
  config.transformer.publicPath = (ref5 = exp.experiments) == null ? void 0 : ref5.baseUrl;
93
92
  }
94
93
  }
95
- const platformBundlers = (0, _platformBundlers).getPlatformBundlers(exp);
94
+ const platformBundlers = (0, _platformBundlers).getPlatformBundlers(projectRoot, exp);
96
95
  var ref6, ref7;
97
96
  config = await (0, _withMetroMultiPlatform).withMetroMultiPlatformAsync(projectRoot, {
98
97
  config,
98
+ exp,
99
99
  platformBundlers,
100
100
  isTsconfigPathsEnabled: (ref6 = (ref = exp.experiments) == null ? void 0 : ref.tsconfigPaths) != null ? ref6 : true,
101
101
  webOutput: (ref7 = (ref1 = exp.web) == null ? void 0 : ref1.output) != null ? ref7 : "single",
@@ -127,10 +127,8 @@ async function instantiateMetroAsync(metroBundler, options, { isExporting }) {
127
127
  port: metroConfig.server.port,
128
128
  watchFolders: metroConfig.watchFolders
129
129
  });
130
- // securityHeadersMiddleware does not support cross-origin requests for remote devtools to get the sourcemap.
131
- // We replace with the enhanced version.
132
- (0, _mutations).replaceMiddlewareWith(middleware, securityHeadersMiddleware, _remoteDevtoolsSecurityHeadersMiddleware.remoteDevtoolsSecurityHeadersMiddleware);
133
- middleware.use(_remoteDevtoolsCorsMiddleware.remoteDevtoolsCorsMiddleware);
130
+ // The `securityHeadersMiddleware` does not support cross-origin requests, we replace with the enhanced version.
131
+ (0, _mutations).replaceMiddlewareWith(middleware, securityHeadersMiddleware, (0, _corsMiddleware).createCorsMiddleware(exp));
134
132
  (0, _mutations).prependMiddleware(middleware, _suppressErrorMiddleware.suppressRemoteDebuggingErrorMiddleware);
135
133
  // TODO: We can probably drop this now.
136
134
  const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { ExpoConfig, getConfig } from '@expo/config';\nimport { getDefaultConfig, LoadOptions } from '@expo/metro-config';\nimport chalk from 'chalk';\nimport { Server as ConnectServer } from 'connect';\nimport http from 'http';\nimport type Metro from 'metro';\nimport { loadConfig, resolveConfig, ConfigT } from 'metro-config';\nimport { Terminal } from 'metro-core';\nimport semver from 'semver';\nimport { URL } from 'url';\n\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { runServer } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { MetroDevServerOptions } from '../../../export/fork-bundleAsync';\nimport { Log } from '../../../log';\nimport { getMetroProperties } from '../../../utils/analytics/getMetroProperties';\nimport { createDebuggerTelemetryMiddleware } from '../../../utils/analytics/metroDebuggerMiddleware';\nimport { logEventAsync } from '../../../utils/analytics/rudderstackClient';\nimport { env } from '../../../utils/env';\nimport { getMetroServerRoot } from '../middleware/ManifestMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware, replaceMiddlewareWith } from '../middleware/mutations';\nimport { remoteDevtoolsCorsMiddleware } from '../middleware/remoteDevtoolsCorsMiddleware';\nimport { remoteDevtoolsSecurityHeadersMiddleware } from '../middleware/remoteDevtoolsSecurityHeadersMiddleware';\nimport { ServerNext, ServerRequest, ServerResponse } from '../middleware/server.types';\nimport { suppressRemoteDebuggingErrorMiddleware } from '../middleware/suppressErrorMiddleware';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\nfunction gteSdkVersion(exp: Pick<ExpoConfig, 'sdkVersion'>, sdkVersion: string): boolean {\n if (!exp.sdkVersion) {\n return false;\n }\n\n if (exp.sdkVersion === 'UNVERSIONED') {\n return true;\n }\n\n try {\n return semver.gte(exp.sdkVersion, sdkVersion);\n } catch {\n throw new Error(`${exp.sdkVersion} is not a valid version. Must be in the form of x.y.z`);\n }\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadOptions,\n {\n exp = getConfig(projectRoot, { skipSDKVersionRequirement: true }).exp,\n isExporting,\n }: { exp?: ExpoConfig; isExporting: boolean }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n const serverRoot = getMetroServerRoot(projectRoot);\n\n const terminal = new Terminal(process.stdout);\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n const hasConfig = await resolveConfig(options.config, projectRoot);\n let config: ConfigT = {\n ...(await loadConfig(\n { cwd: projectRoot, projectRoot, ...options },\n // If the project does not have a metro.config.js, then we use the default config.\n hasConfig.isEmpty ? getDefaultConfig(projectRoot) : undefined\n )),\n reporter: {\n update(event: any) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n if (\n // Requires SDK 50 for expo-assets hashAssetPlugin change.\n !exp.sdkVersion ||\n gteSdkVersion(exp, '50.0.0')\n ) {\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n // @ts-expect-error: typed as readonly.\n config.transformer.publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n // @ts-expect-error: typed as readonly\n config.transformer.publicPath = '/assets/?unstable_path=.';\n }\n } else {\n if (isExporting && exp.experiments?.baseUrl) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n // @ts-expect-error: typed as readonly.\n config.transformer.publicPath = exp.experiments?.baseUrl;\n }\n }\n\n const platformBundlers = getPlatformBundlers(exp);\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n platformBundlers,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n webOutput: exp.web?.output ?? 'single',\n isFastResolverEnabled: env.EXPO_USE_FAST_RESOLVER,\n isExporting,\n });\n\n if (process.env.NODE_ENV !== 'test') {\n logEventAsync('metro config', getMetroProperties(projectRoot, exp, config));\n }\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: Omit<MetroDevServerOptions, 'logger'>,\n { isExporting }: { isExporting: boolean }\n): Promise<{\n metro: Metro.Server;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n\n // TODO: When we bring expo/metro-config into the expo/expo repo, then we can upstream this.\n const { exp } = getConfig(projectRoot, {\n skipSDKVersionRequirement: true,\n });\n\n const { config: metroConfig, setEventReporter } = await loadMetroConfigAsync(\n projectRoot,\n options,\n { exp, isExporting }\n );\n\n const { createDevServerMiddleware, securityHeadersMiddleware } =\n require('@react-native-community/cli-server-api') as typeof import('@react-native-community/cli-server-api');\n\n const { middleware, messageSocketEndpoint, eventsSocketEndpoint, websocketEndpoints } =\n createDevServerMiddleware({\n port: metroConfig.server.port,\n watchFolders: metroConfig.watchFolders,\n });\n\n // securityHeadersMiddleware does not support cross-origin requests for remote devtools to get the sourcemap.\n // We replace with the enhanced version.\n replaceMiddlewareWith(\n middleware as ConnectServer,\n securityHeadersMiddleware,\n remoteDevtoolsSecurityHeadersMiddleware\n );\n\n middleware.use(remoteDevtoolsCorsMiddleware);\n\n prependMiddleware(middleware, suppressRemoteDebuggingErrorMiddleware);\n\n // TODO: We can probably drop this now.\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n // @ts-expect-error: can't mutate readonly config\n metroConfig.server.enhanceMiddleware = (metroMiddleware: any, server: Metro.Server) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n\n middleware.use(createDebuggerTelemetryMiddleware(projectRoot, exp));\n\n // Initialize all React Native debug features\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware(metroBundler);\n prependMiddleware(middleware, debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n const { server, metro } = await runServer(metroBundler, metroConfig, {\n // @ts-expect-error: Inconsistent `websocketEndpoints` type between metro and @react-native-community/cli-server-api\n websocketEndpoints: {\n ...websocketEndpoints,\n ...debugWebsocketEndpoints,\n },\n watch: !isExporting && isWatchEnabled(),\n });\n\n prependMiddleware(middleware, (req: ServerRequest, res: ServerResponse, next: ServerNext) => {\n // If the URL is a Metro asset request, then we need to skip all other middleware to prevent\n // the community CLI's serve-static from hosting `/assets/index.html` in place of all assets if it exists.\n // /assets/?unstable_path=.\n if (req.url) {\n const url = new URL(req.url!, 'http://localhost:8000');\n if (url.pathname.match(/^\\/assets\\/?/) && url.searchParams.get('unstable_path') != null) {\n return metro.processRequest(req, res, next);\n }\n }\n return next();\n });\n\n setEventReporter(eventsSocketEndpoint.reportEvent);\n\n return {\n metro,\n server,\n middleware,\n messageSocket: messageSocketEndpoint,\n };\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["loadMetroConfigAsync","instantiateMetroAsync","isWatchEnabled","gteSdkVersion","exp","sdkVersion","semver","gte","Error","projectRoot","options","getConfig","skipSDKVersionRequirement","isExporting","reportEvent","serverRoot","getMetroServerRoot","terminal","Terminal","process","stdout","terminalReporter","MetroTerminalReporter","hasConfig","resolveConfig","config","loadConfig","cwd","isEmpty","getDefaultConfig","undefined","reporter","update","event","transformer","publicPath","experiments","baseUrl","platformBundlers","getPlatformBundlers","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","webOutput","web","output","isFastResolverEnabled","env","EXPO_USE_FAST_RESOLVER","NODE_ENV","logEventAsync","getMetroProperties","setEventReporter","logger","metroBundler","metroConfig","createDevServerMiddleware","securityHeadersMiddleware","require","middleware","messageSocketEndpoint","eventsSocketEndpoint","websocketEndpoints","port","server","watchFolders","replaceMiddlewareWith","remoteDevtoolsSecurityHeadersMiddleware","use","remoteDevtoolsCorsMiddleware","prependMiddleware","suppressRemoteDebuggingErrorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","createDebuggerTelemetryMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","createJsInspectorMiddleware","metro","runServer","watch","req","res","next","url","URL","pathname","match","searchParams","get","processRequest","messageSocket","CI","Log","log","chalk"],"mappings":"AAAA;;;;QAoDsBA,oBAAoB,GAApBA,oBAAoB;QA6EpBC,qBAAqB,GAArBA,qBAAqB;QAiG3BC,cAAc,GAAdA,cAAc;AAlOQ,IAAA,OAAc,WAAd,cAAc,CAAA;AACN,IAAA,YAAoB,WAApB,oBAAoB,CAAA;AAChD,IAAA,MAAO,kCAAP,OAAO,EAAA;AAI0B,IAAA,aAAc,WAAd,cAAc,CAAA;AACxC,IAAA,UAAY,WAAZ,YAAY,CAAA;AAClB,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACP,IAAA,IAAK,WAAL,KAAK,CAAA;AAGa,IAAA,sBAAyB,WAAzB,yBAAyB,CAAA;AACzB,IAAA,sBAAmC,WAAnC,mCAAmC,CAAA;AAC/C,IAAA,cAAkB,WAAlB,kBAAkB,CAAA;AACA,IAAA,uBAA0B,WAA1B,0BAA0B,CAAA;AAElD,IAAA,IAAc,WAAd,cAAc,CAAA;AACC,IAAA,mBAA6C,WAA7C,6CAA6C,CAAA;AAC9B,IAAA,wBAAkD,WAAlD,kDAAkD,CAAA;AACtE,IAAA,kBAA4C,WAA5C,4CAA4C,CAAA;AACtD,IAAA,IAAoB,WAApB,oBAAoB,CAAA;AACL,IAAA,mBAA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CAACX,UAAU,EAAE,CAACwB,GAAkB,EAAEC,GAAmB,EAAEC,IAAgB,GAAK;QAC3F,4FAA4F;QAC5F,0GAA0G;QAC1G,2BAA2B;QAC3B,IAAIF,GAAG,CAACG,GAAG,EAAE;YACX,MAAMA,GAAG,GAAG,IAAIC,IAAG,IAAA,CAACJ,GAAG,CAACG,GAAG,EAAG,uBAAuB,CAAC,AAAC;YACvD,IAAIA,GAAG,CAACE,QAAQ,CAACC,KAAK,gBAAgB,IAAIH,GAAG,CAACI,YAAY,CAACC,GAAG,CAAC,eAAe,CAAC,IAAI,IAAI,EAAE;gBACvF,OAAOX,KAAK,CAACY,cAAc,CAACT,GAAG,EAAEC,GAAG,EAAEC,IAAI,CAAC,CAAC;aAC7C;SACF;QACD,OAAOA,IAAI,EAAE,CAAC;KACf,CAAC,CAAC;IAEHjC,gBAAgB,CAACS,oBAAoB,CAAC/C,WAAW,CAAC,CAAC;IAEnD,OAAO;QACLkE,KAAK;QACLhB,MAAM,EAANA,OAAM;QACNL,UAAU;QACVkC,aAAa,EAAEjC,qBAAqB;KACrC,CAAC;CACH;AAMM,SAAS1D,cAAc,GAAG;IAC/B,IAAI6C,IAAG,IAAA,CAAC+C,EAAE,EAAE;QACVC,IAAG,IAAA,CAACC,GAAG,CACLC,MAAK,QAAA,CAAC,8FAA8F,CAAC,CACtG,CAAC;KACH;IAED,OAAO,CAAClD,IAAG,IAAA,CAAC+C,EAAE,CAAC;CAChB"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { ExpoConfig, getConfig } from '@expo/config';\nimport { getDefaultConfig, LoadOptions } from '@expo/metro-config';\nimport chalk from 'chalk';\nimport { Server as ConnectServer } from 'connect';\nimport http from 'http';\nimport type Metro from 'metro';\nimport { loadConfig, resolveConfig, ConfigT } from 'metro-config';\nimport { Terminal } from 'metro-core';\nimport semver from 'semver';\nimport { URL } from 'url';\n\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { runServer } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { MetroDevServerOptions } from '../../../export/fork-bundleAsync';\nimport { Log } from '../../../log';\nimport { getMetroProperties } from '../../../utils/analytics/getMetroProperties';\nimport { createDebuggerTelemetryMiddleware } from '../../../utils/analytics/metroDebuggerMiddleware';\nimport { logEventAsync } from '../../../utils/analytics/rudderstackClient';\nimport { env } from '../../../utils/env';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { getMetroServerRoot } from '../middleware/ManifestMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware, replaceMiddlewareWith } from '../middleware/mutations';\nimport { ServerNext, ServerRequest, ServerResponse } from '../middleware/server.types';\nimport { suppressRemoteDebuggingErrorMiddleware } from '../middleware/suppressErrorMiddleware';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\nfunction gteSdkVersion(exp: Pick<ExpoConfig, 'sdkVersion'>, sdkVersion: string): boolean {\n if (!exp.sdkVersion) {\n return false;\n }\n\n if (exp.sdkVersion === 'UNVERSIONED') {\n return true;\n }\n\n try {\n return semver.gte(exp.sdkVersion, sdkVersion);\n } catch {\n throw new Error(`${exp.sdkVersion} is not a valid version. Must be in the form of x.y.z`);\n }\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadOptions,\n {\n exp = getConfig(projectRoot, { skipSDKVersionRequirement: true }).exp,\n isExporting,\n }: { exp?: ExpoConfig; isExporting: boolean }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n const serverRoot = getMetroServerRoot(projectRoot);\n\n const terminal = new Terminal(process.stdout);\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n const hasConfig = await resolveConfig(options.config, projectRoot);\n let config: ConfigT = {\n ...(await loadConfig(\n { cwd: projectRoot, projectRoot, ...options },\n // If the project does not have a metro.config.js, then we use the default config.\n hasConfig.isEmpty ? getDefaultConfig(projectRoot) : undefined\n )),\n reporter: {\n update(event: any) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n if (\n // Requires SDK 50 for expo-assets hashAssetPlugin change.\n !exp.sdkVersion ||\n gteSdkVersion(exp, '50.0.0')\n ) {\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n // @ts-expect-error: typed as readonly.\n config.transformer.publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n // @ts-expect-error: typed as readonly\n config.transformer.publicPath = '/assets/?unstable_path=.';\n }\n } else {\n if (isExporting && exp.experiments?.baseUrl) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n // @ts-expect-error: typed as readonly.\n config.transformer.publicPath = exp.experiments?.baseUrl;\n }\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n webOutput: exp.web?.output ?? 'single',\n isFastResolverEnabled: env.EXPO_USE_FAST_RESOLVER,\n isExporting,\n });\n\n if (process.env.NODE_ENV !== 'test') {\n logEventAsync('metro config', getMetroProperties(projectRoot, exp, config));\n }\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: Omit<MetroDevServerOptions, 'logger'>,\n { isExporting }: { isExporting: boolean }\n): Promise<{\n metro: Metro.Server;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n\n // TODO: When we bring expo/metro-config into the expo/expo repo, then we can upstream this.\n const { exp } = getConfig(projectRoot, {\n skipSDKVersionRequirement: true,\n });\n\n const { config: metroConfig, setEventReporter } = await loadMetroConfigAsync(\n projectRoot,\n options,\n { exp, isExporting }\n );\n\n const { createDevServerMiddleware, securityHeadersMiddleware } =\n require('@react-native-community/cli-server-api') as typeof import('@react-native-community/cli-server-api');\n\n const { middleware, messageSocketEndpoint, eventsSocketEndpoint, websocketEndpoints } =\n createDevServerMiddleware({\n port: metroConfig.server.port,\n watchFolders: metroConfig.watchFolders,\n });\n\n // The `securityHeadersMiddleware` does not support cross-origin requests, we replace with the enhanced version.\n replaceMiddlewareWith(\n middleware as ConnectServer,\n securityHeadersMiddleware,\n createCorsMiddleware(exp)\n );\n\n prependMiddleware(middleware, suppressRemoteDebuggingErrorMiddleware);\n\n // TODO: We can probably drop this now.\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n // @ts-expect-error: can't mutate readonly config\n metroConfig.server.enhanceMiddleware = (metroMiddleware: any, server: Metro.Server) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n\n middleware.use(createDebuggerTelemetryMiddleware(projectRoot, exp));\n\n // Initialize all React Native debug features\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware(metroBundler);\n prependMiddleware(middleware, debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n const { server, metro } = await runServer(metroBundler, metroConfig, {\n // @ts-expect-error: Inconsistent `websocketEndpoints` type between metro and @react-native-community/cli-server-api\n websocketEndpoints: {\n ...websocketEndpoints,\n ...debugWebsocketEndpoints,\n },\n watch: !isExporting && isWatchEnabled(),\n });\n\n prependMiddleware(middleware, (req: ServerRequest, res: ServerResponse, next: ServerNext) => {\n // If the URL is a Metro asset request, then we need to skip all other middleware to prevent\n // the community CLI's serve-static from hosting `/assets/index.html` in place of all assets if it exists.\n // /assets/?unstable_path=.\n if (req.url) {\n const url = new URL(req.url!, 'http://localhost:8000');\n if (url.pathname.match(/^\\/assets\\/?/) && url.searchParams.get('unstable_path') != null) {\n return metro.processRequest(req, res, next);\n }\n }\n return next();\n });\n\n setEventReporter(eventsSocketEndpoint.reportEvent);\n\n return {\n metro,\n server,\n middleware,\n messageSocket: messageSocketEndpoint,\n };\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["loadMetroConfigAsync","instantiateMetroAsync","isWatchEnabled","gteSdkVersion","exp","sdkVersion","semver","gte","Error","projectRoot","options","getConfig","skipSDKVersionRequirement","isExporting","reportEvent","serverRoot","getMetroServerRoot","terminal","Terminal","process","stdout","terminalReporter","MetroTerminalReporter","hasConfig","resolveConfig","config","loadConfig","cwd","isEmpty","getDefaultConfig","undefined","reporter","update","event","transformer","publicPath","experiments","baseUrl","platformBundlers","getPlatformBundlers","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","webOutput","web","output","isFastResolverEnabled","env","EXPO_USE_FAST_RESOLVER","NODE_ENV","logEventAsync","getMetroProperties","setEventReporter","logger","metroBundler","metroConfig","createDevServerMiddleware","securityHeadersMiddleware","require","middleware","messageSocketEndpoint","eventsSocketEndpoint","websocketEndpoints","port","server","watchFolders","replaceMiddlewareWith","createCorsMiddleware","prependMiddleware","suppressRemoteDebuggingErrorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","use","createDebuggerTelemetryMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","createJsInspectorMiddleware","metro","runServer","watch","req","res","next","url","URL","pathname","match","searchParams","get","processRequest","messageSocket","CI","Log","log","chalk"],"mappings":"AAAA;;;;QAmDsBA,oBAAoB,G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,WAAW,CAAC,CAAC;IAEnD,OAAO;QACLiE,KAAK;QACLf,MAAM,EAANA,OAAM;QACNL,UAAU;QACViC,aAAa,EAAEhC,qBAAqB;KACrC,CAAC;CACH;AAMM,SAAS1D,cAAc,GAAG;IAC/B,IAAI6C,IAAG,IAAA,CAAC8C,EAAE,EAAE;QACVC,IAAG,IAAA,CAACC,GAAG,CACLC,MAAK,QAAA,CAAC,8FAA8F,CAAC,CACtG,CAAC;KACH;IAED,OAAO,CAACjD,IAAG,IAAA,CAAC8C,EAAE,CAAC;CAChB"}
@@ -335,7 +335,8 @@ function shouldAliasModule(input, alias) {
335
335
  var ref, ref6;
336
336
  return input.platform === alias.platform && ((ref = input.result) == null ? void 0 : ref.type) === "sourceFile" && typeof ((ref6 = input.result) == null ? void 0 : ref6.filePath) === "string" && normalizeSlashes(input.result.filePath).endsWith(alias.output);
337
337
  }
338
- async function withMetroMultiPlatformAsync(projectRoot, { config , platformBundlers , isTsconfigPathsEnabled , webOutput , isFastResolverEnabled , isExporting }) {
338
+ async function withMetroMultiPlatformAsync(projectRoot, { config , exp , platformBundlers , isTsconfigPathsEnabled , webOutput , isFastResolverEnabled , isExporting }) {
339
+ var ref7;
339
340
  if (!config.projectRoot) {
340
341
  // @ts-expect-error: read-only types
341
342
  config.projectRoot = projectRoot;
@@ -363,7 +364,7 @@ async function withMetroMultiPlatformAsync(projectRoot, { config , platformBundl
363
364
  config.transformer._expoRouterWebRendering = webOutput;
364
365
  // @ts-expect-error: Invalidate the cache when the location of expo-router changes on-disk.
365
366
  config.transformer._expoRouterPath = _resolveFrom.default.silent(projectRoot, "expo-router");
366
- if (platformBundlers.web === "metro") {
367
+ if (((ref7 = exp.platforms) == null ? void 0 : ref7.includes("web")) && platformBundlers.web === "metro") {
367
368
  await new _webSupportProjectPrerequisite.WebSupportProjectPrerequisite(projectRoot).assertAsync();
368
369
  }
369
370
  let tsconfig = null;
@@ -372,8 +373,10 @@ async function withMetroMultiPlatformAsync(projectRoot, { config , platformBundl
372
373
  }
373
374
  await (0, _externals).setupShimFiles(projectRoot);
374
375
  await (0, _externals).setupNodeExternals(projectRoot);
375
- let expoConfigPlatforms = Object.entries(platformBundlers).filter(([, bundler])=>bundler === "metro"
376
- ).map(([platform])=>platform
376
+ let expoConfigPlatforms = Object.entries(platformBundlers).filter(([platform, bundler])=>{
377
+ var ref;
378
+ return bundler === "metro" && ((ref = exp.platforms) == null ? void 0 : ref.includes(platform));
379
+ }).map(([platform])=>platform
377
380
  );
378
381
  if (Array.isArray(config.resolver.platforms)) {
379
382
  expoConfigPlatforms = [
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport fs from 'fs';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext, CustomResolutionContext } from 'metro-resolver';\nimport * as metroResolver from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { createFastResolver } from './createExpoMetroResolver';\nimport {\n EXTERNAL_REQUIRE_NATIVE_POLYFILL,\n EXTERNAL_REQUIRE_POLYFILL,\n METRO_SHIMS_FOLDER,\n getNodeExternalModuleId,\n isNodeExternal,\n setupNodeExternals,\n setupShimFiles,\n} from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport {\n withMetroErrorReportingResolver,\n withMetroMutatedResolverContext,\n withMetroResolvers,\n} from './withMetroResolvers';\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { WebSupportProjectPrerequisite } from '../../doctor/web/WebSupportProjectPrerequisite';\nimport { PlatformBundlers } from '../platformBundlers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(config: ConfigT): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform: string | null }): readonly string[] => {\n if (ctx.platform === 'web') {\n return [\n // NOTE: We might need this for all platforms\n path.join(config.projectRoot, EXTERNAL_REQUIRE_POLYFILL),\n // TODO: runtime polyfills, i.e. Fast Refresh, error overlay, React Dev Tools...\n ];\n }\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n\n return [...polyfills, path.join(config.projectRoot, EXTERNAL_REQUIRE_NATIVE_POLYFILL)];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function getNodejsExtensions(srcExts: readonly string[]): string[] {\n const mjsExts = srcExts.filter((ext) => /mjs$/.test(ext));\n const nodejsSourceExtensions = srcExts.filter((ext) => !/mjs$/.test(ext));\n // find index of last `*.js` extension\n const jsIndex = nodejsSourceExtensions.reduce((index, ext, i) => {\n return /jsx?$/.test(ext) ? i : index;\n }, -1);\n\n // insert `*.mjs` extensions after `*.js` extensions\n nodejsSourceExtensions.splice(jsIndex + 1, 0, ...mjsExts);\n\n return nodejsSourceExtensions;\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n tsconfig,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n }: {\n tsconfig: TsConfigPaths | null;\n isTsconfigPathsEnabled?: boolean;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n }\n) {\n if (isFastResolverEnabled) {\n Log.warn(`Experimental bundling features are enabled.`);\n }\n\n // Get the `transformer.assetRegistryPath`\n // this needs to be unified since you can't dynamically\n // swap out the transformer based on platform.\n const assetRegistryPath = fs.realpathSync(\n path.resolve(resolveFrom(config.projectRoot, '@react-native/assets-registry/registry.js'))\n );\n\n const defaultResolver = metroResolver.resolve;\n const resolver = isFastResolverEnabled\n ? createFastResolver({\n preserveSymlinks: config.resolver?.unstable_enableSymlinks ?? true,\n blockList: Array.isArray(config.resolver?.blockList)\n ? config.resolver?.blockList\n : [config.resolver?.blockList],\n })\n : defaultResolver;\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n 'react-native/index': 'react-native-web',\n },\n };\n\n const universalAliases: [RegExp, string][] = [];\n\n // This package is currently always installed as it is included in the `expo` package.\n if (resolveFrom.silent(config.projectRoot, '@expo/vector-icons')) {\n debug('Enabling alias: react-native-vector-icons -> @expo/vector-icons');\n universalAliases.push([/^react-native-vector-icons(\\/.*)?/, '@expo/vector-icons$1']);\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve = tsconfig?.paths\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsconfig.baseUrl,\n })\n : null;\n\n // TODO: Move this to be a transform key for invalidation.\n if (!isExporting && isInteractive()) {\n if (isTsconfigPathsEnabled) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(config.projectRoot, [\n './tsconfig.json',\n './jsconfig.json',\n ]);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(config.projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n }\n\n let nodejsSourceExtensions: string[] | null = null;\n\n const shimsFolder = path.join(config.projectRoot, METRO_SHIMS_FOLDER);\n\n function getStrictResolver(\n { resolveRequest, ...context }: ResolutionContext,\n platform: string | null\n ) {\n return function doResolve(moduleName: string): Resolution {\n return resolver(context, moduleName, platform);\n };\n }\n\n function getOptionalResolver(context: ResolutionContext, platform: string | null) {\n const doResolve = getStrictResolver(context, platform);\n return function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n };\n }\n\n const metroConfigWithCustomResolver = withMetroResolvers(config, [\n // tsconfig paths\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n return (\n tsConfigResolve?.(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n getOptionalResolver(context, platform)\n ) ?? null\n );\n },\n\n // Node.js externals support\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n // This is a web-only feature, we may extend the shimming to native platforms in the future.\n if (platform !== 'web') {\n return null;\n }\n\n const moduleId = isNodeExternal(moduleName);\n if (!moduleId) {\n return null;\n }\n\n if (\n // In browser runtimes, we want to either resolve a local node module by the same name, or shim the module to\n // prevent crashing when Node.js built-ins are imported.\n context.customResolverOptions?.environment !== 'node'\n ) {\n // Perform optional resolve first. If the module doesn't exist (no module in the node_modules)\n // then we can mock the file to use an empty module.\n const result = getOptionalResolver(context, platform)(moduleName);\n return (\n result ?? {\n // In this case, mock the file to use an empty module.\n type: 'empty',\n }\n );\n }\n\n const redirectedModuleName = getNodeExternalModuleId(context.originModulePath, moduleId);\n debug(`Redirecting Node.js external \"${moduleId}\" to \"${redirectedModuleName}\"`);\n return getStrictResolver(context, platform)(redirectedModuleName);\n },\n\n // Basic moduleId aliases\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n const redirectedModuleName = aliases[platform][moduleName];\n return getStrictResolver(context, platform)(redirectedModuleName);\n }\n\n for (const [matcher, alias] of universalAliases) {\n const match = moduleName.match(matcher);\n if (match) {\n const aliasedModule = alias.replace(\n /\\$(\\d+)/g,\n (_, index) => match[parseInt(index, 10)] ?? ''\n );\n const doResolve = getStrictResolver(context, platform);\n debug(`Alias \"${moduleName}\" to \"${aliasedModule}\"`);\n return doResolve(aliasedModule);\n }\n }\n\n return null;\n },\n\n // HACK(EvanBacon):\n // React Native uses `event-target-shim` incorrectly and this causes the native runtime\n // to fail to load. This is a temporary workaround until we can fix this upstream.\n // https://github.com/facebook/react-native/pull/38628\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (platform !== 'web' && moduleName === 'event-target-shim') {\n debug('For event-target-shim to use js:', context.originModulePath);\n const doResolve = getStrictResolver(context, platform);\n return doResolve('event-target-shim/dist/event-target-shim.js');\n }\n\n return null;\n },\n\n // TODO: Reduce these as much as possible in the future.\n // Complex post-resolution rewrites.\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n const doResolve = getStrictResolver(context, platform);\n\n const result = doResolve(moduleName);\n\n if (result.type !== 'sourceFile') {\n return result;\n }\n\n // Replace the web resolver with the original one.\n // This is basically an alias for web-only.\n // TODO: Drop this in favor of the standalone asset registry module.\n if (shouldAliasAssetRegistryForWeb(platform, result)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = assetRegistryPath;\n }\n\n if (platform === 'web' && result.filePath.includes('node_modules')) {\n // Replace with static shims\n\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const shimPath = path.join(shimsFolder, normalName);\n if (fs.existsSync(shimPath)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = shimPath;\n }\n }\n\n return result;\n },\n ]);\n\n // Ensure we mutate the resolution context to include the custom resolver options for server and web.\n const metroConfigWithCustomContext = withMetroMutatedResolverContext(\n metroConfigWithCustomResolver,\n (\n immutableContext: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ): CustomResolutionContext => {\n const context: Mutable<CustomResolutionContext> = {\n ...immutableContext,\n preferNativePlatform: platform !== 'web',\n };\n\n if (context.customResolverOptions?.environment === 'node') {\n // Adjust nodejs source extensions to sort mjs after js, including platform variants.\n if (nodejsSourceExtensions === null) {\n nodejsSourceExtensions = getNodejsExtensions(context.sourceExts);\n }\n context.sourceExts = nodejsSourceExtensions;\n\n context.unstable_enablePackageExports = true;\n context.unstable_conditionNames = ['node', 'require'];\n context.unstable_conditionsByPlatform = {};\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['main', 'module'];\n } else {\n // Non-server changes\n\n if (!env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE && platform && platform in preferredMainFields) {\n context.mainFields = preferredMainFields[platform];\n }\n }\n\n return context;\n }\n );\n\n return withMetroErrorReportingResolver(metroConfigWithCustomContext);\n}\n\n/** @returns `true` if the incoming resolution should be swapped on web. */\nexport function shouldAliasAssetRegistryForWeb(\n platform: string | null,\n result: Resolution\n): boolean {\n return (\n platform === 'web' &&\n result?.type === 'sourceFile' &&\n typeof result?.filePath === 'string' &&\n normalizeSlashes(result.filePath).endsWith(\n 'react-native-web/dist/modules/AssetRegistry/index.js'\n )\n );\n}\n/** @returns `true` if the incoming resolution should be swapped. */\nexport function shouldAliasModule(\n input: {\n platform: string | null;\n result: Resolution;\n },\n alias: { platform: string; output: string }\n): boolean {\n return (\n input.platform === alias.platform &&\n input.result?.type === 'sourceFile' &&\n typeof input.result?.filePath === 'string' &&\n normalizeSlashes(input.result.filePath).endsWith(alias.output)\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n webOutput,\n isFastResolverEnabled,\n isExporting,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n webOutput?: 'single' | 'static' | 'server';\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n }\n) {\n if (!config.projectRoot) {\n // @ts-expect-error: read-only types\n config.projectRoot = projectRoot;\n }\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n if (['static', 'server'].includes(webOutput ?? '')) {\n // Enable static rendering in runtime space.\n process.env.EXPO_PUBLIC_USE_STATIC = '1';\n }\n\n // This is used for running Expo CLI in development against projects outside the monorepo.\n if (!isDirectoryIn(__dirname, projectRoot)) {\n if (!config.watchFolders) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders = [];\n }\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n }\n\n // @ts-expect-error\n config.transformer._expoRouterWebRendering = webOutput;\n // @ts-expect-error: Invalidate the cache when the location of expo-router changes on-disk.\n config.transformer._expoRouterPath = resolveFrom.silent(projectRoot, 'expo-router');\n\n if (platformBundlers.web === 'metro') {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n }\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n await setupShimFiles(projectRoot);\n await setupNodeExternals(projectRoot);\n\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(([, bundler]) => bundler === 'metro')\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config);\n\n return withExtendedResolver(config, {\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n });\n}\n\nfunction isDirectoryIn(a: string, b: string) {\n return b.startsWith(a) && b.length > a.length;\n}\n"],"names":["getNodejsExtensions","withExtendedResolver","shouldAliasAssetRegistryForWeb","shouldAliasModule","withMetroMultiPlatformAsync","metroResolver","debug","require","withWebPolyfills","config","originalGetPolyfills","serializer","getPolyfills","bind","ctx","platform","path","join","projectRoot","EXTERNAL_REQUIRE_POLYFILL","polyfills","EXTERNAL_REQUIRE_NATIVE_POLYFILL","normalizeSlashes","p","replace","srcExts","mjsExts","filter","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","isTsconfigPathsEnabled","isFastResolverEnabled","isExporting","Log","warn","assetRegistryPath","fs","realpathSync","resolve","resolveFrom","defaultResolver","resolver","createFastResolver","preserveSymlinks","unstable_enableSymlinks","blockList","Array","isArray","aliases","web","universalAliases","silent","push","preferredMainFields","tsConfigResolve","paths","resolveWithTsConfigPaths","baseUrl","hasBaseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","shimsFolder","METRO_SHIMS_FOLDER","getStrictResolver","resolveRequest","context","doResolve","moduleName","getOptionalResolver","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","metroConfigWithCustomResolver","withMetroResolvers","originModulePath","moduleId","isNodeExternal","customResolverOptions","environment","result","type","redirectedModuleName","getNodeExternalModuleId","matcher","alias","match","aliasedModule","_","parseInt","filePath","includes","normalName","shimPath","existsSync","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","sourceExts","unstable_enablePackageExports","unstable_conditionNames","unstable_conditionsByPlatform","mainFields","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","endsWith","input","output","platformBundlers","webOutput","process","EXPO_PUBLIC_PROJECT_ROOT","EXPO_PUBLIC_USE_STATIC","isDirectoryIn","__dirname","watchFolders","transformer","_expoRouterWebRendering","_expoRouterPath","WebSupportProjectPrerequisite","assertAsync","setupShimFiles","setupNodeExternals","expoConfigPlatforms","entries","bundler","map","platforms","Set","concat","a","b","startsWith"],"mappings":"AAMA;;;;QAqEgBA,mBAAmB,GAAnBA,mBAAmB;QAqBnBC,oBAAoB,GAApBA,oBAAoB;QAySpBC,8BAA8B,GAA9BA,8BAA8B;QAc9BC,iBAAiB,GAAjBA,iBAAiB;QAgBXC,2BAA2B,GAA3BA,2BAA2B;AAjalC,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAGPC,IAAAA,aAAa,mCAAM,gBAAgB,EAAtB;AACR,IAAA,KAAM,kCAAN,MAAM,EAAA;AACC,IAAA,YAAc,kCAAd,cAAc,EAAA;AAEH,IAAA,wBAA2B,WAA3B,2BAA2B,CAAA;AASvD,IAAA,UAAa,WAAb,aAAa,CAAA;AACmD,IAAA,YAAe,WAAf,eAAe,CAAA;AAK/E,IAAA,mBAAsB,WAAtB,sBAAsB,CAAA;AACT,I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,CAACL,mBAAmB,CAACM,MAAM,CAAC5I,MAAM,CAACuC,QAAQ,CAACmG,SAAS,CAAC,CAAC;SAAC,CAAC;KAC3F;IAED,yCAAyC;IACzC1I,MAAM,CAACuC,QAAQ,CAACmG,SAAS,GAAGJ,mBAAmB,CAAC;IAEhDtI,MAAM,GAAGD,gBAAgB,CAACC,MAAM,CAAC,CAAC;IAElC,OAAOR,oBAAoB,CAACQ,MAAM,EAAE;QAClC2B,QAAQ;QACRG,WAAW;QACXF,sBAAsB;QACtBC,qBAAqB;KACtB,CAAC,CAAC;CACJ;AAED,SAAS+F,aAAa,CAACiB,CAAS,EAAEC,CAAS,EAAE;IAC3C,OAAOA,CAAC,CAACC,UAAU,CAACF,CAAC,CAAC,IAAIC,CAAC,CAAC5E,MAAM,GAAG2E,CAAC,CAAC3E,MAAM,CAAC;CAC/C"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { ExpoConfig, Platform } from '@expo/config';\nimport fs from 'fs';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext, CustomResolutionContext } from 'metro-resolver';\nimport * as metroResolver from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { createFastResolver } from './createExpoMetroResolver';\nimport {\n EXTERNAL_REQUIRE_NATIVE_POLYFILL,\n EXTERNAL_REQUIRE_POLYFILL,\n METRO_SHIMS_FOLDER,\n getNodeExternalModuleId,\n isNodeExternal,\n setupNodeExternals,\n setupShimFiles,\n} from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport {\n withMetroErrorReportingResolver,\n withMetroMutatedResolverContext,\n withMetroResolvers,\n} from './withMetroResolvers';\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { WebSupportProjectPrerequisite } from '../../doctor/web/WebSupportProjectPrerequisite';\nimport { PlatformBundlers } from '../platformBundlers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(config: ConfigT): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform: string | null }): readonly string[] => {\n if (ctx.platform === 'web') {\n return [\n // NOTE: We might need this for all platforms\n path.join(config.projectRoot, EXTERNAL_REQUIRE_POLYFILL),\n // TODO: runtime polyfills, i.e. Fast Refresh, error overlay, React Dev Tools...\n ];\n }\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n\n return [...polyfills, path.join(config.projectRoot, EXTERNAL_REQUIRE_NATIVE_POLYFILL)];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function getNodejsExtensions(srcExts: readonly string[]): string[] {\n const mjsExts = srcExts.filter((ext) => /mjs$/.test(ext));\n const nodejsSourceExtensions = srcExts.filter((ext) => !/mjs$/.test(ext));\n // find index of last `*.js` extension\n const jsIndex = nodejsSourceExtensions.reduce((index, ext, i) => {\n return /jsx?$/.test(ext) ? i : index;\n }, -1);\n\n // insert `*.mjs` extensions after `*.js` extensions\n nodejsSourceExtensions.splice(jsIndex + 1, 0, ...mjsExts);\n\n return nodejsSourceExtensions;\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n tsconfig,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n }: {\n tsconfig: TsConfigPaths | null;\n isTsconfigPathsEnabled?: boolean;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n }\n) {\n if (isFastResolverEnabled) {\n Log.warn(`Experimental bundling features are enabled.`);\n }\n\n // Get the `transformer.assetRegistryPath`\n // this needs to be unified since you can't dynamically\n // swap out the transformer based on platform.\n const assetRegistryPath = fs.realpathSync(\n path.resolve(resolveFrom(config.projectRoot, '@react-native/assets-registry/registry.js'))\n );\n\n const defaultResolver = metroResolver.resolve;\n const resolver = isFastResolverEnabled\n ? createFastResolver({\n preserveSymlinks: config.resolver?.unstable_enableSymlinks ?? true,\n blockList: Array.isArray(config.resolver?.blockList)\n ? config.resolver?.blockList\n : [config.resolver?.blockList],\n })\n : defaultResolver;\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n 'react-native/index': 'react-native-web',\n },\n };\n\n const universalAliases: [RegExp, string][] = [];\n\n // This package is currently always installed as it is included in the `expo` package.\n if (resolveFrom.silent(config.projectRoot, '@expo/vector-icons')) {\n debug('Enabling alias: react-native-vector-icons -> @expo/vector-icons');\n universalAliases.push([/^react-native-vector-icons(\\/.*)?/, '@expo/vector-icons$1']);\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve = tsconfig?.paths\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsconfig.baseUrl,\n })\n : null;\n\n // TODO: Move this to be a transform key for invalidation.\n if (!isExporting && isInteractive()) {\n if (isTsconfigPathsEnabled) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(config.projectRoot, [\n './tsconfig.json',\n './jsconfig.json',\n ]);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(config.projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n }\n\n let nodejsSourceExtensions: string[] | null = null;\n\n const shimsFolder = path.join(config.projectRoot, METRO_SHIMS_FOLDER);\n\n function getStrictResolver(\n { resolveRequest, ...context }: ResolutionContext,\n platform: string | null\n ) {\n return function doResolve(moduleName: string): Resolution {\n return resolver(context, moduleName, platform);\n };\n }\n\n function getOptionalResolver(context: ResolutionContext, platform: string | null) {\n const doResolve = getStrictResolver(context, platform);\n return function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n };\n }\n\n const metroConfigWithCustomResolver = withMetroResolvers(config, [\n // tsconfig paths\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n return (\n tsConfigResolve?.(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n getOptionalResolver(context, platform)\n ) ?? null\n );\n },\n\n // Node.js externals support\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n // This is a web-only feature, we may extend the shimming to native platforms in the future.\n if (platform !== 'web') {\n return null;\n }\n\n const moduleId = isNodeExternal(moduleName);\n if (!moduleId) {\n return null;\n }\n\n if (\n // In browser runtimes, we want to either resolve a local node module by the same name, or shim the module to\n // prevent crashing when Node.js built-ins are imported.\n context.customResolverOptions?.environment !== 'node'\n ) {\n // Perform optional resolve first. If the module doesn't exist (no module in the node_modules)\n // then we can mock the file to use an empty module.\n const result = getOptionalResolver(context, platform)(moduleName);\n return (\n result ?? {\n // In this case, mock the file to use an empty module.\n type: 'empty',\n }\n );\n }\n\n const redirectedModuleName = getNodeExternalModuleId(context.originModulePath, moduleId);\n debug(`Redirecting Node.js external \"${moduleId}\" to \"${redirectedModuleName}\"`);\n return getStrictResolver(context, platform)(redirectedModuleName);\n },\n\n // Basic moduleId aliases\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n const redirectedModuleName = aliases[platform][moduleName];\n return getStrictResolver(context, platform)(redirectedModuleName);\n }\n\n for (const [matcher, alias] of universalAliases) {\n const match = moduleName.match(matcher);\n if (match) {\n const aliasedModule = alias.replace(\n /\\$(\\d+)/g,\n (_, index) => match[parseInt(index, 10)] ?? ''\n );\n const doResolve = getStrictResolver(context, platform);\n debug(`Alias \"${moduleName}\" to \"${aliasedModule}\"`);\n return doResolve(aliasedModule);\n }\n }\n\n return null;\n },\n\n // HACK(EvanBacon):\n // React Native uses `event-target-shim` incorrectly and this causes the native runtime\n // to fail to load. This is a temporary workaround until we can fix this upstream.\n // https://github.com/facebook/react-native/pull/38628\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (platform !== 'web' && moduleName === 'event-target-shim') {\n debug('For event-target-shim to use js:', context.originModulePath);\n const doResolve = getStrictResolver(context, platform);\n return doResolve('event-target-shim/dist/event-target-shim.js');\n }\n\n return null;\n },\n\n // TODO: Reduce these as much as possible in the future.\n // Complex post-resolution rewrites.\n (context: ResolutionContext, moduleName: string, platform: string | null) => {\n const doResolve = getStrictResolver(context, platform);\n\n const result = doResolve(moduleName);\n\n if (result.type !== 'sourceFile') {\n return result;\n }\n\n // Replace the web resolver with the original one.\n // This is basically an alias for web-only.\n // TODO: Drop this in favor of the standalone asset registry module.\n if (shouldAliasAssetRegistryForWeb(platform, result)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = assetRegistryPath;\n }\n\n if (platform === 'web' && result.filePath.includes('node_modules')) {\n // Replace with static shims\n\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const shimPath = path.join(shimsFolder, normalName);\n if (fs.existsSync(shimPath)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = shimPath;\n }\n }\n\n return result;\n },\n ]);\n\n // Ensure we mutate the resolution context to include the custom resolver options for server and web.\n const metroConfigWithCustomContext = withMetroMutatedResolverContext(\n metroConfigWithCustomResolver,\n (\n immutableContext: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ): CustomResolutionContext => {\n const context: Mutable<CustomResolutionContext> = {\n ...immutableContext,\n preferNativePlatform: platform !== 'web',\n };\n\n if (context.customResolverOptions?.environment === 'node') {\n // Adjust nodejs source extensions to sort mjs after js, including platform variants.\n if (nodejsSourceExtensions === null) {\n nodejsSourceExtensions = getNodejsExtensions(context.sourceExts);\n }\n context.sourceExts = nodejsSourceExtensions;\n\n context.unstable_enablePackageExports = true;\n context.unstable_conditionNames = ['node', 'require'];\n context.unstable_conditionsByPlatform = {};\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['main', 'module'];\n } else {\n // Non-server changes\n\n if (!env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE && platform && platform in preferredMainFields) {\n context.mainFields = preferredMainFields[platform];\n }\n }\n\n return context;\n }\n );\n\n return withMetroErrorReportingResolver(metroConfigWithCustomContext);\n}\n\n/** @returns `true` if the incoming resolution should be swapped on web. */\nexport function shouldAliasAssetRegistryForWeb(\n platform: string | null,\n result: Resolution\n): boolean {\n return (\n platform === 'web' &&\n result?.type === 'sourceFile' &&\n typeof result?.filePath === 'string' &&\n normalizeSlashes(result.filePath).endsWith(\n 'react-native-web/dist/modules/AssetRegistry/index.js'\n )\n );\n}\n/** @returns `true` if the incoming resolution should be swapped. */\nexport function shouldAliasModule(\n input: {\n platform: string | null;\n result: Resolution;\n },\n alias: { platform: string; output: string }\n): boolean {\n return (\n input.platform === alias.platform &&\n input.result?.type === 'sourceFile' &&\n typeof input.result?.filePath === 'string' &&\n normalizeSlashes(input.result.filePath).endsWith(alias.output)\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled,\n webOutput,\n isFastResolverEnabled,\n isExporting,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n webOutput?: 'single' | 'static' | 'server';\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n }\n) {\n if (!config.projectRoot) {\n // @ts-expect-error: read-only types\n config.projectRoot = projectRoot;\n }\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n if (['static', 'server'].includes(webOutput ?? '')) {\n // Enable static rendering in runtime space.\n process.env.EXPO_PUBLIC_USE_STATIC = '1';\n }\n\n // This is used for running Expo CLI in development against projects outside the monorepo.\n if (!isDirectoryIn(__dirname, projectRoot)) {\n if (!config.watchFolders) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders = [];\n }\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n }\n\n // @ts-expect-error\n config.transformer._expoRouterWebRendering = webOutput;\n // @ts-expect-error: Invalidate the cache when the location of expo-router changes on-disk.\n config.transformer._expoRouterPath = resolveFrom.silent(projectRoot, 'expo-router');\n\n if (exp.platforms?.includes('web') && platformBundlers.web === 'metro') {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n }\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n await setupShimFiles(projectRoot);\n await setupNodeExternals(projectRoot);\n\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(\n ([platform, bundler]) => bundler === 'metro' && exp.platforms?.includes(platform as Platform)\n )\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config);\n\n return withExtendedResolver(config, {\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n });\n}\n\nfunction isDirectoryIn(a: string, b: string) {\n return b.startsWith(a) && b.length > a.length;\n}\n"],"names":["getNodejsExtensions","withExtendedResolver","shouldAliasAssetRegistryForWeb","shouldAliasModule","withMetroMultiPlatformAsync","metroResolver","debug","require","withWebPolyfills","config","originalGetPolyfills","serializer","getPolyfills","bind","ctx","platform","path","join","projectRoot","EXTERNAL_REQUIRE_POLYFILL","polyfills","EXTERNAL_REQUIRE_NATIVE_POLYFILL","normalizeSlashes","p","replace","srcExts","mjsExts","filter","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","isTsconfigPathsEnabled","isFastResolverEnabled","isExporting","Log","warn","assetRegistryPath","fs","realpathSync","resolve","resolveFrom","defaultResolver","resolver","createFastResolver","preserveSymlinks","unstable_enableSymlinks","blockList","Array","isArray","aliases","web","universalAliases","silent","push","preferredMainFields","tsConfigResolve","paths","resolveWithTsConfigPaths","baseUrl","hasBaseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","shimsFolder","METRO_SHIMS_FOLDER","getStrictResolver","resolveRequest","context","doResolve","moduleName","getOptionalResolver","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","metroConfigWithCustomResolver","withMetroResolvers","originModulePath","moduleId","isNodeExternal","customResolverOptions","environment","result","type","redirectedModuleName","getNodeExternalModuleId","matcher","alias","match","aliasedModule","_","parseInt","filePath","includes","normalName","shimPath","existsSync","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","sourceExts","unstable_enablePackageExports","unstable_conditionNames","unstable_conditionsByPlatform","mainFields","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","endsWith","input","output","exp","platformBundlers","webOutput","process","EXPO_PUBLIC_PROJECT_ROOT","EXPO_PUBLIC_USE_STATIC","isDirectoryIn","__dirname","watchFolders","transformer","_expoRouterWebRendering","_expoRouterPath","platforms","WebSupportProjectPrerequisite","assertAsync","setupShimFiles","setupNodeExternals","expoConfigPlatforms","entries","bundler","map","Set","concat","a","b","startsWith"],"mappings":"AAMA;;;;QAsEgBA,mBAAmB,GAAnBA,mBAAmB;QAqBnBC,oBAAoB,GAApBA,oBAAoB;QAySpBC,8BAA8B,GAA9BA,8BAA8B;QAc9BC,iBAAiB,GAAjBA,iBAAiB;QAgBXC,2BAA2B,GAA3BA,2BAA2B;AAjalC,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAGPC,IAAAA,aA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ware = createCorsMiddleware;
6
+ const DEFAULT_ALLOWED_CORS_HOSTNAMES = [
7
+ "localhost",
8
+ "chrome-devtools-frontend.appspot.com",
9
+ "devtools"
10
+ ];
11
+ function createCorsMiddleware(exp) {
12
+ var ref, ref1, ref2, ref3;
13
+ const allowedHostnames = [
14
+ ...DEFAULT_ALLOWED_CORS_HOSTNAMES
15
+ ];
16
+ // Support for expo-router API routes
17
+ if ((ref = exp.extra) == null ? void 0 : (ref1 = ref.router) == null ? void 0 : ref1.headOrigin) {
18
+ allowedHostnames.push(new URL(exp.extra.router.headOrigin).hostname);
19
+ }
20
+ if ((ref2 = exp.extra) == null ? void 0 : (ref3 = ref2.router) == null ? void 0 : ref3.origin) {
21
+ allowedHostnames.push(new URL(exp.extra.router.origin).hostname);
22
+ }
23
+ return (req, res, next)=>{
24
+ if (typeof req.headers.origin === "string") {
25
+ const { hostname } = new URL(req.headers.origin);
26
+ if (!allowedHostnames.includes(hostname)) {
27
+ next(new Error(`Unauthorized request from ${req.headers.origin}. ` + "This may happen because of a conflicting browser extension to intercept HTTP requests. " + "Please try again without browser extensions or using incognito mode."));
28
+ return;
29
+ }
30
+ res.setHeader("Access-Control-Allow-Origin", req.headers.origin);
31
+ maybePreventMetroResetCorsHeader(req, res);
32
+ }
33
+ // Block MIME-type sniffing.
34
+ res.setHeader("X-Content-Type-Options", "nosniff");
35
+ next();
36
+ };
37
+ }
38
+ // When accessing source maps,
39
+ // metro will overwrite the `Access-Control-Allow-Origin` header with hardcoded `devtools://devtools` value.
40
+ // https://github.com/facebook/metro/blob/a7f8955e6d2424b0d5f73d4bcdaf22560e1d5f27/packages/metro/src/Server.js#L540
41
+ // This is a workaround to prevent this behavior.
42
+ function maybePreventMetroResetCorsHeader(req, res) {
43
+ const pathname = req.url ? new URL(req.url, `http://${req.headers.host}`).pathname : "";
44
+ if (pathname.endsWith(".map")) {
45
+ const setHeader = res.setHeader.bind(res);
46
+ res.setHeader = (key, ...args)=>{
47
+ if (key !== "Access-Control-Allow-Origin") {
48
+ setHeader(key, ...args);
49
+ }
50
+ return res;
51
+ };
52
+ }
53
+ }
54
+
55
+ //# sourceMappingURL=CorsMiddleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/start/server/middleware/CorsMiddleware.ts"],"sourcesContent":["import type { ExpoConfig } from '@expo/config';\n\nimport type { ServerRequest, ServerResponse } from './server.types';\n\nconst DEFAULT_ALLOWED_CORS_HOSTNAMES = [\n 'localhost',\n 'chrome-devtools-frontend.appspot.com', // Support remote Chrome DevTools frontend\n 'devtools', // Support local Chrome DevTools `devtools://devtools`\n];\n\nexport function createCorsMiddleware(exp: ExpoConfig) {\n const allowedHostnames = [...DEFAULT_ALLOWED_CORS_HOSTNAMES];\n // Support for expo-router API routes\n if (exp.extra?.router?.headOrigin) {\n allowedHostnames.push(new URL(exp.extra.router.headOrigin).hostname);\n }\n if (exp.extra?.router?.origin) {\n allowedHostnames.push(new URL(exp.extra.router.origin).hostname);\n }\n\n return (req: ServerRequest, res: ServerResponse, next: (err?: Error) => void) => {\n if (typeof req.headers.origin === 'string') {\n const { hostname } = new URL(req.headers.origin);\n if (!allowedHostnames.includes(hostname)) {\n next(\n new Error(\n `Unauthorized request from ${req.headers.origin}. ` +\n 'This may happen because of a conflicting browser extension to intercept HTTP requests. ' +\n 'Please try again without browser extensions or using incognito mode.'\n )\n );\n return;\n }\n\n res.setHeader('Access-Control-Allow-Origin', req.headers.origin);\n maybePreventMetroResetCorsHeader(req, res);\n }\n\n // Block MIME-type sniffing.\n res.setHeader('X-Content-Type-Options', 'nosniff');\n\n next();\n };\n}\n\n// When accessing source maps,\n// metro will overwrite the `Access-Control-Allow-Origin` header with hardcoded `devtools://devtools` value.\n// https://github.com/facebook/metro/blob/a7f8955e6d2424b0d5f73d4bcdaf22560e1d5f27/packages/metro/src/Server.js#L540\n// This is a workaround to prevent this behavior.\nfunction maybePreventMetroResetCorsHeader(req: ServerRequest, res: ServerResponse) {\n const pathname = req.url ? new URL(req.url, `http://${req.headers.host}`).pathname : '';\n if (pathname.endsWith('.map')) {\n const setHeader = res.setHeader.bind(res);\n res.setHeader = (key, ...args) => {\n if (key !== 'Access-Control-Allow-Origin') {\n setHeader(key, ...args);\n }\n return res;\n };\n }\n}\n"],"names":["createCorsMiddleware","DEFAULT_ALLOWED_CORS_HOSTNAMES","exp","allowedHostnames","extra","router","headOrigin","push","URL","hostname","origin","req","res","next","headers","includes","Error","setHeader","maybePreventMetroResetCorsHeader","pathname","url","host","endsWith","bind","key","args"],"mappings":"AAAA;;;;QAUgBA,oBAAoB,GAApBA,oBAAoB;AANpC,MAAMC,8BAA8B,GAAG;IACrC,WAAW;IACX,sCAAsC;IACtC,UAAU;CACX,AAAC;AAEK,SAASD,oBAAoB,CAACE,GAAe,EAAE;QAGhDA,GAAS,QAGTA,IAAS;IALb,MAAMC,gBAAgB,GAAG;WAAIF,8BAA8B;KAAC,AAAC;IAC7D,qCAAqC;IACrC,IAAIC,CAAAA,GAAS,GAATA,GAAG,CAACE,KAAK,SAAQ,GAAjBF,KAAAA,CAAiB,GAAjBA,QAAAA,GAAS,CAAEG,MAAM,SAAA,GAAjBH,KAAAA,CAAiB,QAAEI,UAAU,AAAZ,EAAc;QACjCH,gBAAgB,CAACI,IAAI,CAAC,IAAIC,GAAG,CAACN,GAAG,CAACE,KAAK,CAACC,MAAM,CAACC,UAAU,CAAC,CAACG,QAAQ,CAAC,CAAC;KACtE;IACD,IAAIP,CAAAA,IAAS,GAATA,GAAG,CAACE,KAAK,SAAQ,GAAjBF,KAAAA,CAAiB,GAAjBA,QAAAA,IAAS,CAAEG,MAAM,SAAA,GAAjBH,KAAAA,CAAiB,QAAEQ,MAAM,AAAR,EAAU;QAC7BP,gBAAgB,CAACI,IAAI,CAAC,IAAIC,GAAG,CAACN,GAAG,CAACE,KAAK,CAACC,MAAM,CAACK,MAAM,CAAC,CAACD,QAAQ,CAAC,CAAC;KAClE;IAED,OAAO,CAACE,GAAkB,EAAEC,GAAmB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AID,GAAG,KAAK,6BAA6B,EAAE;gBACzCP,SAAS,CAACO,GAAG,KAAKC,IAAI,CAAC,CAAC;aACzB;YACD,OAAOb,GAAG,CAAC;SACZ,CAAC;KACH;CACF"}
@@ -100,6 +100,7 @@ class ManifestMiddleware extends _expoMiddleware.ExpoMiddleware {
100
100
  this.projectRoot = projectRoot;
101
101
  this.options = options;
102
102
  this.initialProjectConfig = (0, _config).getConfig(projectRoot);
103
+ this.platformBundlers = (0, _platformBundlers).getPlatformBundlers(projectRoot, this.initialProjectConfig.exp);
103
104
  }
104
105
  /** Exposed for testing. */ async _resolveProjectSettingsAsync({ platform , hostname }) {
105
106
  // Read the config
@@ -256,21 +257,20 @@ class ManifestMiddleware extends _expoMiddleware.ExpoMiddleware {
256
257
  }));
257
258
  }
258
259
  /** Exposed for testing. */ async checkBrowserRequestAsync(req, res, next) {
259
- // Read the config
260
- const bundlers = (0, _platformBundlers).getPlatformBundlers(this.initialProjectConfig.exp);
261
- if (bundlers.web === "metro") {
260
+ var ref;
261
+ if (this.platformBundlers.web === "metro" && ((ref = this.initialProjectConfig.exp.platforms) == null ? void 0 : ref.includes("web"))) {
262
262
  // NOTE(EvanBacon): This effectively disables the safety check we do on custom runtimes to ensure
263
263
  // the `expo-platform` header is included. When `web.bundler=web`, if the user has non-standard Expo
264
264
  // code loading then they'll get a web bundle without a clear assertion of platform support.
265
265
  const platform = (0, _resolvePlatform).parsePlatformHeader(req);
266
266
  // On web, serve the public folder
267
267
  if (!platform || platform === "web") {
268
- var ref;
269
268
  var ref1;
269
+ var ref2;
270
270
  if ([
271
271
  "static",
272
272
  "server"
273
- ].includes((ref1 = (ref = this.initialProjectConfig.exp.web) == null ? void 0 : ref.output) != null ? ref1 : "")) {
273
+ ].includes((ref2 = (ref1 = this.initialProjectConfig.exp.web) == null ? void 0 : ref1.output) != null ? ref2 : "")) {
274
274
  // Skip the spa-styled index.html when static generation is enabled.
275
275
  next();
276
276
  return true;