@expo/cli 55.0.0-canary-20251205-a1dedc6 → 55.0.0-canary-20251210-1f163e3
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.
- package/build/bin/cli +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +5 -5
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/MetroTerminalReporter.js +7 -0
- package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
- package/build/src/start/server/metro/createServerRouteMiddleware.js +1 -1
- package/build/src/start/server/metro/createServerRouteMiddleware.js.map +1 -1
- package/build/src/start/server/platformBundlers.js.map +1 -1
- package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
- package/build/src/utils/telemetry/utils/context.js +1 -1
- package/package.json +19 -19
package/build/bin/cli
CHANGED
|
@@ -123,7 +123,7 @@ const args = (0, _arg().default)({
|
|
|
123
123
|
});
|
|
124
124
|
if (args['--version']) {
|
|
125
125
|
// Version is added in the build script.
|
|
126
|
-
console.log("55.0.0-canary-
|
|
126
|
+
console.log("55.0.0-canary-20251210-1f163e3");
|
|
127
127
|
process.exit(0);
|
|
128
128
|
}
|
|
129
129
|
if (args['--non-interactive']) {
|
|
@@ -173,7 +173,7 @@ class MetroBundlerDevServer extends _BundlerDevServer.BundlerDevServer {
|
|
|
173
173
|
(options.devClient ? Number(process.env.RCT_METRO_PORT) || DEV_CLIENT_METRO_PORT : await (0, _port.getFreePortAsync)(EXPO_GO_METRO_PORT));
|
|
174
174
|
return port;
|
|
175
175
|
}
|
|
176
|
-
async
|
|
176
|
+
async exportServerRouteAsync({ contents, artifactFilename, files, includeSourceMaps, descriptor }) {
|
|
177
177
|
if (!contents) return;
|
|
178
178
|
let src = contents.src;
|
|
179
179
|
if (includeSourceMaps && contents.map) {
|
|
@@ -206,14 +206,14 @@ class MetroBundlerDevServer extends _BundlerDevServer.BundlerDevServer {
|
|
|
206
206
|
};
|
|
207
207
|
files.set(artifactFilename, fileData);
|
|
208
208
|
}
|
|
209
|
-
async
|
|
209
|
+
async exportMiddlewareAsync({ manifest, appDir, outputDir, files, platform, includeSourceMaps }) {
|
|
210
210
|
if (!manifest.middleware) return;
|
|
211
211
|
const middlewareFilePath = _path().default.isAbsolute(manifest.middleware.file) ? manifest.middleware.file : _path().default.join(appDir, manifest.middleware.file);
|
|
212
212
|
const contents = await this.bundleApiRoute(middlewareFilePath, {
|
|
213
213
|
platform
|
|
214
214
|
});
|
|
215
215
|
const artifactFilename = (0, _metroOptions.convertPathToModuleSpecifier)(_path().default.join(outputDir, _path().default.relative(appDir, middlewareFilePath.replace(/\.[tj]sx?$/, '.js'))));
|
|
216
|
-
await this.
|
|
216
|
+
await this.exportServerRouteAsync({
|
|
217
217
|
contents,
|
|
218
218
|
artifactFilename,
|
|
219
219
|
files,
|
|
@@ -251,7 +251,7 @@ class MetroBundlerDevServer extends _BundlerDevServer.BundlerDevServer {
|
|
|
251
251
|
}
|
|
252
252
|
});
|
|
253
253
|
}
|
|
254
|
-
await this.
|
|
254
|
+
await this.exportMiddlewareAsync({
|
|
255
255
|
manifest,
|
|
256
256
|
appDir,
|
|
257
257
|
outputDir,
|
|
@@ -265,7 +265,7 @@ class MetroBundlerDevServer extends _BundlerDevServer.BundlerDevServer {
|
|
|
265
265
|
platform
|
|
266
266
|
});
|
|
267
267
|
const artifactFilename = route.page === rscPath ? (0, _metroOptions.convertPathToModuleSpecifier)(_path().default.join(outputDir, '.' + rscPath + '.js')) : (0, _metroOptions.convertPathToModuleSpecifier)(_path().default.join(outputDir, _path().default.relative(appDir, filepath.replace(/\.[tj]sx?$/, '.js'))));
|
|
268
|
-
await this.
|
|
268
|
+
await this.exportServerRouteAsync({
|
|
269
269
|
contents,
|
|
270
270
|
artifactFilename,
|
|
271
271
|
files,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/MetroBundlerDevServer.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, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport * as runtimeEnv from '@expo/env';\nimport baseJSBundle from '@expo/metro/metro/DeltaBundler/Serializers/baseJSBundle';\nimport {\n sourceMapGeneratorNonBlocking,\n type SourceMapGeneratorOptions,\n} from '@expo/metro/metro/DeltaBundler/Serializers/sourceMapGenerator';\nimport type {\n Module,\n DeltaResult,\n TransformInputOptions,\n} from '@expo/metro/metro/DeltaBundler/types';\nimport type {\n default as MetroHmrServer,\n Client as MetroHmrClient,\n} from '@expo/metro/metro/HmrServer';\nimport type { GraphRevision } from '@expo/metro/metro/IncrementalBundler';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport bundleToString from '@expo/metro/metro/lib/bundleToString';\nimport getGraphId from '@expo/metro/metro/lib/getGraphId';\nimport type { TransformProfile } from '@expo/metro/metro-babel-transformer';\nimport type { CustomResolverOptions } from '@expo/metro/metro-resolver';\nimport { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport type { GetStaticContentOptions } from '@expo/router-server/build/static/renderStaticContent';\nimport assert from 'assert';\nimport chalk from 'chalk';\nimport type { RouteNode } from 'expo-router/build/Route';\nimport { type RouteInfo, type RoutesManifest } from 'expo-server/private';\nimport path from 'path';\n\nimport {\n createServerComponentsMiddleware,\n fileURLToFilePath,\n} from './createServerComponentsMiddleware';\nimport { createRouteHandlerMiddleware } from './createServerRouteMiddleware';\nimport { fetchManifest, inflateManifest } from './fetchRouterManifest';\nimport { instantiateMetroAsync } from './instantiateMetro';\nimport {\n attachImportStackToRootMessage,\n dropStackIfContainsCodeFrame,\n getErrorOverlayHtmlAsync,\n IS_METRO_BUNDLE_ERROR_SYMBOL,\n} from './metroErrorInterface';\nimport { metroWatchTypeScriptFiles } from './metroWatchTypeScriptFiles';\nimport {\n getRouterDirectoryModuleIdWithManifest,\n hasWarnedAboutApiRoutes,\n isApiRouteConvention,\n warnInvalidWebOutput,\n} from './router';\nimport { serializeHtmlWithAssets } from './serializeHtml';\nimport { observeAnyFileChanges, observeFileChanges } from './waitForMetroToObserveTypeScriptFile';\nimport type {\n BundleAssetWithFileHashes,\n ExportAssetDescriptor,\n ExportAssetMap,\n} from '../../../export/saveAssets';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { getFreePortAsync } from '../../../utils/port';\nimport { BundlerDevServer, BundlerStartOptions, DevServerInstance } from '../BundlerDevServer';\nimport {\n cachedSourceMaps,\n evalMetroAndWrapFunctions,\n evalMetroNoHandling,\n} from '../getStaticRenderFunctions';\nimport {\n fromRuntimeManifestRoute,\n fromServerManifestRoute,\n type ResolvedLoaderRoute,\n} from './resolveLoader';\nimport { ContextModuleSourceMapsMiddleware } from '../middleware/ContextModuleSourceMapsMiddleware';\nimport { CreateFileMiddleware } from '../middleware/CreateFileMiddleware';\nimport { DataLoaderModuleMiddleware } from '../middleware/DataLoaderModuleMiddleware';\nimport { DevToolsPluginMiddleware } from '../middleware/DevToolsPluginMiddleware';\nimport { createDomComponentsMiddleware } from '../middleware/DomComponentsMiddleware';\nimport { FaviconMiddleware } from '../middleware/FaviconMiddleware';\nimport { HistoryFallbackMiddleware } from '../middleware/HistoryFallbackMiddleware';\nimport { InterstitialPageMiddleware } from '../middleware/InterstitialPageMiddleware';\nimport { resolveMainModuleName } from '../middleware/ManifestMiddleware';\nimport { RuntimeRedirectMiddleware } from '../middleware/RuntimeRedirectMiddleware';\nimport { ServeStaticMiddleware } from '../middleware/ServeStaticMiddleware';\nimport {\n convertPathToModuleSpecifier,\n createBundleUrlPath,\n ExpoMetroOptions,\n createBundleOsPath,\n getAsyncRoutesFromExpoConfig,\n getBaseUrlFromExpoConfig,\n getMetroDirectBundleOptions,\n} from '../middleware/metroOptions';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { ServerNext, ServerRequest, ServerResponse } from '../middleware/server.types';\nimport { startTypescriptTypeGenerationAsync } from '../type-generation/startTypescriptTypeGeneration';\n\nexport type ExpoRouterRuntimeManifest = Awaited<\n ReturnType<typeof import('@expo/router-server/build/static/renderStaticContent').getManifest>\n>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\ninterface BundleDirectResult {\n numModifiedFiles: number;\n lastModifiedDate: Date;\n nextRevId: string;\n bundle: string;\n map: string;\n /** Defined if the output is multi-bundle. */\n artifacts?: SerialAsset[];\n assets?: readonly BundleAssetWithFileHashes[];\n}\n\ninterface MetroModuleContentsResult extends BundleDirectResult {\n filename: string;\n}\n\ninterface SSRModuleContentsResult extends Omit<BundleDirectResult, 'bundle'> {\n filename: string;\n src: string;\n map: string;\n}\n\n// TODO(@kitten): We access this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this function is defined\ndeclare namespace globalThis {\n const __c: (() => void) | undefined;\n let __expo_rsc_inject_module: (params: { code: string; id: string }) => void | undefined;\n}\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\n/** Default port to use for apps running in Expo Go. */\nconst EXPO_GO_METRO_PORT = 8081;\n\n/** Default port to use for apps that run in standard React Native projects or Expo Dev Clients. */\nconst DEV_CLIENT_METRO_PORT = 8081;\n\nexport class MetroBundlerDevServer extends BundlerDevServer {\n private metro: MetroServer | null = null;\n private hmrServer: MetroHmrServer<MetroHmrClient> | null = null;\n private ssrHmrClients: Map<string, MetroHmrClient> = new Map();\n isReactServerComponentsEnabled?: boolean;\n isReactServerRoutesEnabled?: boolean;\n\n get name(): string {\n return 'metro';\n }\n\n async resolvePortAsync(options: Partial<BundlerStartOptions> = {}): Promise<number> {\n const port =\n // If the manually defined port is busy then an error should be thrown...\n options.port ??\n // Otherwise use the default port based on the runtime target.\n (options.devClient\n ? // Don't check if the port is busy if we're using the dev client since most clients are hardcoded to 8081.\n Number(process.env.RCT_METRO_PORT) || DEV_CLIENT_METRO_PORT\n : // Otherwise (running in Expo Go) use a free port that falls back on the classic 8081 port.\n await getFreePortAsync(EXPO_GO_METRO_PORT));\n\n return port;\n }\n\n private async exportServerRoute({\n contents,\n artifactFilename,\n files,\n includeSourceMaps,\n descriptor,\n }: {\n contents: { src: string; map?: any } | null | undefined;\n artifactFilename: string;\n files: ExportAssetMap;\n includeSourceMaps?: boolean;\n routeId?: string;\n descriptor: Partial<ExportAssetDescriptor>;\n }) {\n if (!contents) return;\n\n let src = contents.src;\n if (includeSourceMaps && contents.map) {\n // TODO(kitten): Merge the source map transformer in the future\n // https://github.com/expo/expo/blob/0dffdb15/packages/%40expo/metro-config/src/serializer/serializeChunks.ts#L422-L439\n // Alternatively, check whether `sourcesRoot` helps here\n const artifactBasename = encodeURIComponent(path.basename(artifactFilename) + '.map');\n src = src.replace(/\\/\\/# sourceMappingURL=.*/g, `//# sourceMappingURL=${artifactBasename}`);\n const parsedMap = typeof contents.map === 'string' ? JSON.parse(contents.map) : contents.map;\n const mapData: any = {\n ...descriptor,\n contents: JSON.stringify({\n version: parsedMap.version,\n sources: parsedMap.sources.map((source: string) => {\n source =\n typeof source === 'string' && source.startsWith(this.projectRoot)\n ? path.relative(this.projectRoot, source)\n : source;\n return convertPathToModuleSpecifier(source);\n }),\n sourcesContent: new Array(parsedMap.sources.length).fill(null),\n names: parsedMap.names,\n mappings: parsedMap.mappings,\n }),\n targetDomain: 'server',\n };\n files.set(artifactFilename + '.map', mapData);\n }\n const fileData: ExportAssetDescriptor = {\n ...descriptor,\n contents: src,\n targetDomain: 'server',\n };\n files.set(artifactFilename, fileData);\n }\n\n private async exportMiddleware({\n manifest,\n appDir,\n outputDir,\n files,\n platform,\n includeSourceMaps,\n }: {\n manifest: RoutesManifest;\n appDir: string;\n outputDir: string;\n files: ExportAssetMap;\n platform: string;\n includeSourceMaps?: boolean;\n }) {\n if (!manifest.middleware) return;\n\n const middlewareFilePath = path.isAbsolute(manifest.middleware.file)\n ? manifest.middleware.file\n : path.join(appDir, manifest.middleware.file);\n const contents = await this.bundleApiRoute(middlewareFilePath, { platform });\n const artifactFilename = convertPathToModuleSpecifier(\n path.join(outputDir, path.relative(appDir, middlewareFilePath.replace(/\\.[tj]sx?$/, '.js')))\n );\n\n await this.exportServerRoute({\n contents,\n artifactFilename,\n files,\n includeSourceMaps,\n descriptor: {\n middlewareId: '/middleware',\n },\n });\n\n // Remap the middleware file to represent the output file.\n manifest.middleware.file = artifactFilename;\n }\n\n async exportExpoRouterApiRoutesAsync({\n includeSourceMaps,\n outputDir,\n prerenderManifest,\n platform,\n }: {\n includeSourceMaps?: boolean;\n outputDir: string;\n // This does not contain the API routes info.\n prerenderManifest: RoutesManifest<string>;\n platform: string;\n }): Promise<{ files: ExportAssetMap; manifest: RoutesManifest<string> }> {\n const { routerRoot } = this.instanceMetroOptions;\n assert(\n routerRoot != null,\n 'The server must be started before calling exportExpoRouterApiRoutesAsync.'\n );\n\n const appDir = path.join(this.projectRoot, routerRoot);\n const manifest = await this.getExpoRouterRoutesManifestAsync({ appDir });\n\n const files: ExportAssetMap = new Map();\n\n // Inject RSC middleware.\n const rscPath = '/_flight/[...rsc]';\n\n if (\n this.isReactServerComponentsEnabled &&\n // If the RSC route is not already in the manifest, add it.\n !manifest.apiRoutes.find((route) => route.page.startsWith('/_flight/'))\n ) {\n debug('Adding RSC route to the manifest:', rscPath);\n // NOTE: This might need to be sorted to the correct spot in the future.\n manifest.apiRoutes.push({\n // TODO(@kitten): This isn't great, we shouldn't be needing to rely on files like this\n // It might even be better to make templating strings since that'd be type-checked, but currently,\n // we rely on this being an entrypoint for Metro\n file: require.resolve('@expo/cli/static/template/[...rsc]+api.ts'),\n page: rscPath,\n namedRegex: '^/_flight(?:/(?<rsc>.+?))?(?:/)?$',\n routeKeys: { rsc: 'rsc' },\n });\n }\n\n await this.exportMiddleware({\n manifest,\n appDir,\n outputDir,\n files,\n platform,\n includeSourceMaps,\n });\n\n for (const route of manifest.apiRoutes) {\n const filepath = path.isAbsolute(route.file) ? route.file : path.join(appDir, route.file);\n const contents = await this.bundleApiRoute(filepath, { platform });\n\n const artifactFilename =\n route.page === rscPath\n ? // HACK: Add RSC renderer to the output...\n convertPathToModuleSpecifier(path.join(outputDir, '.' + rscPath + '.js'))\n : convertPathToModuleSpecifier(\n path.join(outputDir, path.relative(appDir, filepath.replace(/\\.[tj]sx?$/, '.js')))\n );\n\n await this.exportServerRoute({\n contents,\n artifactFilename,\n files,\n includeSourceMaps,\n descriptor: {\n apiRouteId: route.page,\n },\n });\n // Remap the manifest files to represent the output files.\n route.file = artifactFilename;\n }\n\n return {\n manifest: {\n ...manifest,\n htmlRoutes: prerenderManifest.htmlRoutes,\n },\n files,\n };\n }\n\n async getExpoRouterRoutesManifestAsync({ appDir }: { appDir: string }) {\n // getBuiltTimeServerManifest\n const { exp } = getConfig(this.projectRoot);\n const manifest = await fetchManifest(this.projectRoot, {\n ...exp.extra?.router,\n preserveRedirectAndRewrites: true,\n asJson: true,\n appDir,\n });\n\n if (!manifest) {\n throw new CommandError(\n 'EXPO_ROUTER_SERVER_MANIFEST',\n 'Unexpected error: server manifest could not be fetched.'\n );\n }\n\n return manifest;\n }\n\n async getServerManifestAsync(): Promise<{\n serverManifest: RoutesManifest<string>;\n htmlManifest: ExpoRouterRuntimeManifest;\n }> {\n const { exp } = getConfig(this.projectRoot);\n // NOTE: This could probably be folded back into `renderStaticContent` when expo-asset and font support RSC.\n const { getBuildTimeServerManifestAsync, getManifest } = await this.ssrLoadModule<\n typeof import('@expo/router-server/build/static/getServerManifest')\n >('@expo/router-server/build/static/getServerManifest.js', {\n // Only use react-server environment when the routes are using react-server rendering by default.\n environment: this.isReactServerRoutesEnabled ? 'react-server' : 'node',\n });\n\n return {\n serverManifest: await getBuildTimeServerManifestAsync({ ...exp.extra?.router }),\n htmlManifest: await getManifest({ ...exp.extra?.router }),\n };\n }\n\n /**\n * This function is invoked when exporting via `expo export`\n */\n async getStaticRenderFunctionAsync(): Promise<{\n serverManifest: RoutesManifest<string>;\n manifest: ExpoRouterRuntimeManifest;\n renderAsync: (\n path: string,\n route: RouteNode,\n opts?: GetStaticContentOptions\n ) => Promise<string>;\n executeLoaderAsync: (path: string, route: RouteNode) => Promise<any>;\n }> {\n const { routerRoot } = this.instanceMetroOptions;\n assert(\n routerRoot != null,\n 'The server must be started before calling getStaticRenderFunctionAsync.'\n );\n\n const appDir = path.join(this.projectRoot, routerRoot);\n const url = this.getDevServerUrlOrAssert();\n\n const { getStaticContent, getManifest, getBuildTimeServerManifestAsync } =\n await this.ssrLoadModule<\n typeof import('@expo/router-server/build/static/renderStaticContent')\n >('@expo/router-server/node/render.js', {\n // This must always use the legacy rendering resolution (no `react-server`) because it leverages\n // the previous React SSG utilities which aren't available in React 19.\n environment: 'node',\n });\n\n const { exp } = getConfig(this.projectRoot);\n\n const serverManifest = await getBuildTimeServerManifestAsync({\n ...exp.extra?.router,\n });\n\n return {\n serverManifest,\n // Get routes from Expo Router.\n manifest: await getManifest({ preserveApiRoutes: false, ...exp.extra?.router }),\n // Get route generating function\n renderAsync: async (path, route, opts?) => {\n const location = new URL(path, url);\n return await getStaticContent(location, opts);\n },\n executeLoaderAsync: async (path, route) => {\n const location = new URL(path, url);\n\n const resolvedLoaderRoute = fromRuntimeManifestRoute(location.pathname, route, {\n serverManifest: inflateManifest(serverManifest),\n appDir,\n });\n\n if (!resolvedLoaderRoute) {\n return undefined;\n }\n\n return await this.executeServerDataLoaderAsync(location, resolvedLoaderRoute);\n },\n };\n }\n\n async getStaticResourcesAsync({\n includeSourceMaps,\n mainModuleName,\n clientBoundaries = this.instanceMetroOptions.clientBoundaries ?? [],\n platform = 'web',\n }: {\n includeSourceMaps?: boolean;\n mainModuleName?: string;\n clientBoundaries?: string[];\n platform?: string;\n } = {}) {\n const { mode, minify, isExporting, baseUrl, reactCompiler, routerRoot, asyncRoutes } =\n this.instanceMetroOptions;\n assert(\n mode != null &&\n isExporting != null &&\n baseUrl != null &&\n routerRoot != null &&\n reactCompiler != null &&\n asyncRoutes != null,\n 'The server must be started before calling getStaticResourcesAsync.'\n );\n\n const resolvedMainModuleName =\n mainModuleName ?? './' + resolveMainModuleName(this.projectRoot, { platform });\n return await this.metroImportAsArtifactsAsync(resolvedMainModuleName, {\n splitChunks: isExporting && !env.EXPO_NO_BUNDLE_SPLITTING,\n platform,\n mode,\n minify,\n environment: 'client',\n serializerIncludeMaps: includeSourceMaps,\n mainModuleName: resolvedMainModuleName,\n lazy: !env.EXPO_NO_METRO_LAZY,\n asyncRoutes,\n baseUrl,\n isExporting,\n routerRoot,\n clientBoundaries,\n reactCompiler,\n bytecode: false,\n });\n }\n\n /**\n * This function is invoked when running in development via `expo start`\n */\n private async getStaticPageAsync(pathname: string, route: RouteInfo<RegExp>) {\n const { exp } = getConfig(this.projectRoot);\n const { mode, isExporting, clientBoundaries, baseUrl, reactCompiler, routerRoot, asyncRoutes } =\n this.instanceMetroOptions;\n assert(\n mode != null &&\n isExporting != null &&\n baseUrl != null &&\n reactCompiler != null &&\n routerRoot != null &&\n asyncRoutes != null,\n 'The server must be started before calling getStaticPageAsync.'\n );\n const platform = 'web';\n\n const devBundleUrlPathname = createBundleUrlPath({\n splitChunks: isExporting && !env.EXPO_NO_BUNDLE_SPLITTING,\n platform,\n mode,\n environment: 'client',\n reactCompiler,\n mainModuleName: resolveMainModuleName(this.projectRoot, { platform }),\n lazy: !env.EXPO_NO_METRO_LAZY,\n baseUrl,\n isExporting,\n asyncRoutes,\n routerRoot,\n clientBoundaries,\n bytecode: false,\n });\n\n const bundleStaticHtml = async (): Promise<string> => {\n const { getStaticContent } = await this.ssrLoadModule<\n typeof import('@expo/router-server/build/static/renderStaticContent')\n >('@expo/router-server/node/render.js', {\n // This must always use the legacy rendering resolution (no `react-server`) because it leverages\n // the previous React SSG utilities which aren't available in React 19.\n environment: 'node',\n minify: false,\n isExporting,\n platform,\n });\n\n const location = new URL(pathname, this.getDevServerUrlOrAssert());\n\n const useServerDataLoaders = exp.extra?.router?.unstable_useServerDataLoaders;\n if (!useServerDataLoaders) {\n return await getStaticContent(location);\n }\n\n const resolvedLoaderRoute = fromServerManifestRoute(location.pathname, route);\n if (!resolvedLoaderRoute) {\n return await getStaticContent(location);\n }\n\n const data = await this.executeServerDataLoaderAsync(location, resolvedLoaderRoute);\n return await getStaticContent(location, { loader: { data } });\n };\n\n const [{ artifacts: resources }, staticHtml] = await Promise.all([\n this.getStaticResourcesAsync({\n clientBoundaries: [],\n }),\n bundleStaticHtml(),\n ]);\n const content = serializeHtmlWithAssets({\n isExporting,\n resources,\n template: staticHtml,\n devBundleUrl: devBundleUrlPathname,\n baseUrl,\n hydrate: env.EXPO_WEB_DEV_HYDRATE,\n });\n return {\n content,\n resources,\n };\n }\n\n // Set when the server is started.\n private instanceMetroOptions: Partial<ExpoMetroOptions> = {};\n\n private ssrLoadModule: SSRLoadModuleFunc = async (\n filePath,\n specificOptions = {},\n extras = {}\n ) => {\n const res = await this.ssrLoadModuleContents(filePath, specificOptions);\n\n if (\n // TODO: hot should be a callback function for invalidating the related SSR module.\n extras.hot &&\n this.instanceMetroOptions.isExporting !== true\n ) {\n // Register SSR HMR\n const serverRoot = getMetroServerRoot(this.projectRoot);\n const relativePath = path.relative(serverRoot, res.filename);\n const url = new URL(relativePath, this.getDevServerUrlOrAssert());\n this.setupHmr(url);\n }\n\n return evalMetroAndWrapFunctions(\n this.projectRoot,\n res.src,\n res.filename,\n specificOptions.isExporting ?? this.instanceMetroOptions.isExporting!\n );\n };\n\n private async metroImportAsArtifactsAsync(\n filePath: string,\n specificOptions: Partial<Omit<ExpoMetroOptions, 'serializerOutput'>> = {}\n ) {\n const results = await this.ssrLoadModuleContents(filePath, {\n serializerOutput: 'static',\n ...specificOptions,\n });\n\n // NOTE: This could potentially need more validation in the future.\n if (results.artifacts && results.assets) {\n return {\n artifacts: results.artifacts,\n assets: results.assets,\n src: results.src,\n filename: results.filename,\n map: results.map,\n };\n }\n throw new CommandError('Invalid bundler results: ' + results);\n }\n\n private async metroLoadModuleContents(\n filePath: string,\n specificOptions: ExpoMetroOptions,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<MetroModuleContentsResult> {\n const { baseUrl } = this.instanceMetroOptions;\n assert(baseUrl != null, 'The server must be started before calling metroLoadModuleContents.');\n\n const opts: ExpoMetroOptions = {\n // TODO: Possibly issues with using an absolute path here...\n // mainModuleName: filePath,\n lazy: false,\n asyncRoutes: false,\n inlineSourceMap: false,\n engine: 'hermes',\n minify: false,\n // bytecode: false,\n // Bundle in Node.js mode for SSR.\n environment: 'node',\n // platform: 'web',\n // mode: 'development',\n //\n ...this.instanceMetroOptions,\n baseUrl,\n // routerRoot,\n // isExporting,\n ...specificOptions,\n };\n\n const expoBundleOptions = getMetroDirectBundleOptions(opts);\n\n const resolverOptions = {\n customResolverOptions: expoBundleOptions.customResolverOptions ?? {},\n dev: expoBundleOptions.dev ?? true,\n };\n\n const transformOptions: TransformInputOptions = {\n dev: expoBundleOptions.dev ?? true,\n minify: expoBundleOptions.minify ?? false,\n type: 'module',\n unstable_transformProfile:\n extraOptions.unstable_transformProfile ??\n expoBundleOptions.unstable_transformProfile ??\n 'default',\n customTransformOptions: expoBundleOptions.customTransformOptions ?? Object.create(null),\n platform: expoBundleOptions.platform ?? 'web',\n };\n\n const resolvedEntryFilePath = await this.resolveRelativePathAsync(filePath, {\n resolverOptions,\n transformOptions,\n });\n\n const filename = createBundleOsPath({\n ...opts,\n mainModuleName: resolvedEntryFilePath,\n });\n\n // https://github.com/facebook/metro/blob/2405f2f6c37a1b641cc379b9c733b1eff0c1c2a1/packages/metro/src/lib/parseOptionsFromUrl.js#L55-L87\n // TODO(@kitten): We've flagged this way of \"direct transpilation\" for replacement, since it's hard to maintain\n // It's possible that the intention here was to do something like what `exportEmbedAsync` is doing (using Server.DEFAULT_BUNDLE_OPTIONS)\n // That's why the defaults were added to match types. It's unclear though if that was correct\n // Maybe the `Server.DEFAULT_BUNDLE_OPTIONS` logic should be hoisted into `getMetroDirectBundleOptions`?\n const results = await this._bundleDirectAsync(resolvedEntryFilePath, {\n graphOptions: {\n lazy: expoBundleOptions.lazy ?? false,\n shallow: expoBundleOptions.shallow ?? false,\n },\n resolverOptions,\n serializerOptions: {\n ...expoBundleOptions.serializerOptions,\n inlineSourceMap: expoBundleOptions.inlineSourceMap ?? false,\n modulesOnly: expoBundleOptions.modulesOnly ?? false,\n runModule: expoBundleOptions.runModule ?? true,\n sourceUrl: expoBundleOptions.sourceUrl!,\n sourceMapUrl: extraOptions.sourceMapUrl ?? expoBundleOptions.sourceMapUrl!,\n },\n transformOptions,\n });\n\n return {\n ...results,\n filename,\n };\n }\n\n private async ssrLoadModuleContents(\n filePath: string,\n specificOptions: Partial<ExpoMetroOptions> = {}\n ): Promise<SSRModuleContentsResult> {\n const { baseUrl, routerRoot, isExporting } = this.instanceMetroOptions;\n assert(\n baseUrl != null && routerRoot != null && isExporting != null,\n 'The server must be started before calling ssrLoadModuleContents.'\n );\n\n const opts: ExpoMetroOptions = {\n // TODO: Possibly issues with using an absolute path here...\n mainModuleName: convertPathToModuleSpecifier(filePath),\n lazy: false,\n asyncRoutes: false,\n inlineSourceMap: false,\n engine: 'hermes',\n minify: false,\n bytecode: false,\n // Bundle in Node.js mode for SSR unless RSC is enabled.\n environment: this.isReactServerComponentsEnabled ? 'react-server' : 'node',\n platform: 'web',\n mode: 'development',\n //\n ...this.instanceMetroOptions,\n\n // Mostly disable compiler in SSR bundles.\n reactCompiler: false,\n baseUrl,\n routerRoot,\n isExporting,\n\n ...specificOptions,\n };\n\n // https://github.com/facebook/metro/blob/2405f2f6c37a1b641cc379b9c733b1eff0c1c2a1/packages/metro/src/lib/parseOptionsFromUrl.js#L55-L87\n const { filename, bundle, map, ...rest } = await this.metroLoadModuleContents(filePath, opts);\n const scriptContents = wrapBundle(bundle);\n\n if (map) {\n debug('Registering SSR source map for:', filename);\n cachedSourceMaps.set(filename, { url: this.projectRoot, map });\n } else {\n debug('No SSR source map found for:', filename);\n }\n\n return {\n ...rest,\n src: scriptContents,\n filename,\n map,\n };\n }\n\n async nativeExportBundleAsync(\n exp: ExpoConfig,\n options: Omit<\n ExpoMetroOptions,\n 'routerRoot' | 'asyncRoutes' | 'isExporting' | 'serializerOutput' | 'environment'\n >,\n files: ExportAssetMap,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<{\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n files?: ExportAssetMap;\n }> {\n if (this.isReactServerComponentsEnabled) {\n return this.singlePageReactServerComponentExportAsync(exp, options, files, extraOptions);\n }\n\n return this.legacySinglePageExportBundleAsync(options, extraOptions);\n }\n\n private async singlePageReactServerComponentExportAsync(\n exp: ExpoConfig,\n options: Omit<\n ExpoMetroOptions,\n 'baseUrl' | 'routerRoot' | 'asyncRoutes' | 'isExporting' | 'serializerOutput' | 'environment'\n >,\n files: ExportAssetMap,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<{\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n files: ExportAssetMap;\n }> {\n const getReactServerReferences = (artifacts: SerialAsset[]): string[] => {\n // Get the React server action boundaries from the client bundle.\n return unique(\n artifacts\n .filter((a) => a.type === 'js')\n .map((artifact) =>\n artifact.metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref))\n )\n // TODO: Segment by module for splitting.\n .flat()\n .filter(Boolean) as string[]\n );\n };\n\n // NOTE(EvanBacon): This will not support any code elimination since it's a static pass.\n let {\n reactClientReferences: clientBoundaries,\n reactServerReferences: serverActionReferencesInServer,\n cssModules,\n } = await this.rscRenderer!.getExpoRouterClientReferencesAsync(\n {\n platform: options.platform,\n domRoot: options.domRoot,\n },\n files\n );\n\n // TODO: The output keys should be in production format or use a lookup manifest.\n\n const processClientBoundaries = async (\n reactServerReferences: string[]\n ): Promise<{\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n }> => {\n debug('Evaluated client boundaries:', clientBoundaries);\n\n // Run metro bundler and create the JS bundles/source maps.\n const bundle = await this.legacySinglePageExportBundleAsync(\n {\n ...options,\n clientBoundaries,\n },\n extraOptions\n );\n\n // Get the React server action boundaries from the client bundle.\n const newReactServerReferences = getReactServerReferences(bundle.artifacts);\n\n if (!newReactServerReferences) {\n // Possible issue with babel plugin / metro-config.\n throw new Error(\n 'Static server action references were not returned from the Metro client bundle'\n );\n }\n debug('React server action boundaries from client:', newReactServerReferences);\n\n const allKnownReactServerReferences = unique([\n ...reactServerReferences,\n ...newReactServerReferences,\n ]);\n\n // When we export the server actions that were imported from the client, we may need to re-bundle the client with the new client boundaries.\n const { clientBoundaries: nestedClientBoundaries } =\n await this.rscRenderer!.exportServerActionsAsync(\n {\n platform: options.platform,\n domRoot: options.domRoot,\n entryPoints: allKnownReactServerReferences,\n },\n files\n );\n\n // TODO: Check against all modules in the initial client bundles.\n const hasUniqueClientBoundaries = nestedClientBoundaries.some(\n (boundary) => !clientBoundaries.includes(boundary)\n );\n\n if (!hasUniqueClientBoundaries) {\n return bundle;\n }\n\n debug('Re-bundling client with nested client boundaries:', nestedClientBoundaries);\n\n clientBoundaries = unique(clientBoundaries.concat(nestedClientBoundaries));\n\n // Re-bundle the client with the new client boundaries that only exist in server actions that were imported from the client.\n // Run metro bundler and create the JS bundles/source maps.\n return processClientBoundaries(allKnownReactServerReferences);\n };\n\n const bundle = await processClientBoundaries(serverActionReferencesInServer);\n\n // Inject the global CSS that was imported during the server render.\n bundle.artifacts.push(...cssModules);\n\n const serverRoot = getMetroServerRoot(this.projectRoot);\n\n // HACK: Maybe this should be done in the serializer.\n const clientBoundariesAsOpaqueIds = clientBoundaries.map((boundary) =>\n // NOTE(cedric): relative module specifiers / IDs should always be POSIX formatted\n toPosixPath(path.relative(serverRoot, boundary))\n );\n const moduleIdToSplitBundle = (\n bundle.artifacts\n .map((artifact) => artifact?.metadata?.paths && Object.values(artifact.metadata.paths))\n .filter(Boolean)\n .flat() as Record<string, string>[]\n ).reduce((acc, paths) => ({ ...acc, ...paths }), {});\n\n debug('SSR Manifest:', moduleIdToSplitBundle, clientBoundariesAsOpaqueIds);\n\n const ssrManifest = new Map<string, string | null>();\n\n if (Object.keys(moduleIdToSplitBundle).length) {\n clientBoundariesAsOpaqueIds.forEach((boundary) => {\n if (boundary in moduleIdToSplitBundle) {\n ssrManifest.set(boundary, moduleIdToSplitBundle[boundary]);\n } else {\n throw new Error(\n `Could not find boundary \"${boundary}\" in the SSR manifest. Available: ${Object.keys(moduleIdToSplitBundle).join(', ')}`\n );\n }\n });\n } else {\n // Native apps with bundle splitting disabled.\n debug('No split bundles');\n clientBoundariesAsOpaqueIds.forEach((boundary) => {\n ssrManifest.set(boundary, null);\n });\n }\n\n const routerOptions = exp.extra?.router;\n\n // Export the static RSC files\n await this.rscRenderer!.exportRoutesAsync(\n {\n platform: options.platform,\n ssrManifest,\n routerOptions,\n },\n files\n );\n\n // Save the SSR manifest so we can perform more replacements in the server renderer and with server actions.\n files.set(`_expo/rsc/${options.platform}/ssr-manifest.js`, {\n targetDomain: 'server',\n contents:\n 'module.exports = ' +\n JSON.stringify(\n // TODO: Add a less leaky version of this across the framework with just [key, value] (module ID, chunk).\n Object.fromEntries(\n Array.from(ssrManifest.entries()).map(([key, value]) => [\n // Must match babel plugin.\n './' + toPosixPath(path.relative(this.projectRoot, path.join(serverRoot, key))),\n [key, value],\n ])\n )\n ),\n });\n\n return { ...bundle, files };\n }\n\n async legacySinglePageExportBundleAsync(\n options: Omit<\n ExpoMetroOptions,\n 'routerRoot' | 'asyncRoutes' | 'isExporting' | 'serializerOutput' | 'environment' | 'hosted'\n >,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<{ artifacts: SerialAsset[]; assets: readonly BundleAssetWithFileHashes[] }> {\n const { baseUrl, routerRoot, isExporting } = this.instanceMetroOptions;\n assert(options.mainModuleName != null, 'mainModuleName must be provided in options.');\n assert(\n baseUrl != null && routerRoot != null && isExporting != null,\n 'The server must be started before calling legacySinglePageExportBundleAsync.'\n );\n\n const opts: ExpoMetroOptions = {\n ...this.instanceMetroOptions,\n baseUrl,\n routerRoot,\n isExporting,\n ...options,\n environment: 'client',\n serializerOutput: 'static',\n };\n\n // https://github.com/facebook/metro/blob/2405f2f6c37a1b641cc379b9c733b1eff0c1c2a1/packages/metro/src/lib/parseOptionsFromUrl.js#L55-L87\n if (!opts.mainModuleName.startsWith('/') && !path.isAbsolute(opts.mainModuleName)) {\n opts.mainModuleName = './' + opts.mainModuleName;\n }\n\n const output = await this.metroLoadModuleContents(opts.mainModuleName, opts, extraOptions);\n\n return {\n artifacts: output.artifacts!,\n assets: output.assets!,\n };\n }\n\n async watchEnvironmentVariables() {\n if (!this.instance) {\n throw new Error(\n 'Cannot observe environment variable changes without a running Metro instance.'\n );\n }\n if (!this.metro) {\n // This can happen when the run command is used and the server is already running in another\n // process.\n debug('Skipping Environment Variable observation because Metro is not running (headless).');\n return;\n }\n\n const envFiles = runtimeEnv\n .getFiles(process.env.NODE_ENV)\n .map((fileName) => path.join(this.projectRoot, fileName));\n\n observeFileChanges(\n {\n metro: this.metro,\n server: this.instance.server,\n },\n envFiles,\n () => {\n debug('Reloading environment variables...');\n // Force reload the environment variables.\n runtimeEnv.load(this.projectRoot, { force: true });\n }\n );\n }\n\n rscRenderer: Awaited<ReturnType<typeof createServerComponentsMiddleware>> | null = null;\n\n protected async startImplementationAsync(\n options: BundlerStartOptions\n ): Promise<DevServerInstance> {\n options.port = await this.resolvePortAsync(options);\n this.urlCreator = this.getUrlCreator(options);\n\n const config = getConfig(this.projectRoot, { skipSDKVersionRequirement: true });\n const { exp } = config;\n // NOTE: This will change in the future when it's less experimental, we enable React 19, and turn on more RSC flags by default.\n const isReactServerComponentsEnabled =\n !!exp.experiments?.reactServerComponentRoutes || !!exp.experiments?.reactServerFunctions;\n const isReactServerActionsOnlyEnabled =\n !exp.experiments?.reactServerComponentRoutes && !!exp.experiments?.reactServerFunctions;\n this.isReactServerComponentsEnabled = isReactServerComponentsEnabled;\n this.isReactServerRoutesEnabled = !!exp.experiments?.reactServerComponentRoutes;\n\n const useServerRendering = ['static', 'server'].includes(exp.web?.output ?? '');\n const hasApiRoutes = isReactServerComponentsEnabled || exp.web?.output === 'server';\n const baseUrl = getBaseUrlFromExpoConfig(exp);\n const asyncRoutes = getAsyncRoutesFromExpoConfig(exp, options.mode ?? 'development', 'web');\n const routerRoot = getRouterDirectoryModuleIdWithManifest(this.projectRoot, exp);\n const reactCompiler = !!exp.experiments?.reactCompiler;\n const appDir = path.join(this.projectRoot, routerRoot);\n const mode = options.mode ?? 'development';\n\n const routerOptions = exp.extra?.router;\n\n if (isReactServerComponentsEnabled && exp.web?.output === 'static') {\n throw new CommandError(\n `Experimental server component support does not support 'web.output: ${exp.web!.output}' yet. Use 'web.output: \"server\"' during the experimental phase.`\n );\n }\n\n // Error early about the window.location polyfill when React Server Components are enabled.\n if (isReactServerComponentsEnabled && exp?.extra?.router?.origin === false) {\n const configPath = config.dynamicConfigPath ?? config.staticConfigPath ?? '/app.json';\n const configFileName = path.basename(configPath);\n throw new CommandError(\n `The Expo Router \"origin\" property in the Expo config (${configFileName}) cannot be \"false\" when React Server Components is enabled. Remove it from the ${configFileName} file and try again.`\n );\n }\n\n const instanceMetroOptions = {\n isExporting: !!options.isExporting,\n baseUrl,\n mode,\n routerRoot,\n reactCompiler,\n minify: options.minify,\n asyncRoutes,\n // Options that are changing between platforms like engine, platform, and environment aren't set here.\n };\n this.instanceMetroOptions = instanceMetroOptions;\n\n const parsedOptions = {\n port: options.port,\n maxWorkers: options.maxWorkers,\n resetCache: options.resetDevServer,\n };\n\n // Required for symbolication:\n process.env.EXPO_DEV_SERVER_ORIGIN = `http://localhost:${options.port}`;\n\n const { metro, hmrServer, server, middleware, messageSocket } = await instantiateMetroAsync(\n this,\n parsedOptions,\n {\n isExporting: !!options.isExporting,\n exp,\n }\n );\n\n if (!options.isExporting) {\n const manifestMiddleware = await this.getManifestMiddlewareAsync(options);\n\n // Important that we noop source maps for context modules as soon as possible.\n prependMiddleware(middleware, new ContextModuleSourceMapsMiddleware().getHandler());\n\n // We need the manifest handler to be the first middleware to run so our\n // routes take precedence over static files. For example, the manifest is\n // served from '/' and if the user has an index.html file in their project\n // then the manifest handler will never run, the static middleware will run\n // and serve index.html instead of the manifest.\n // https://github.com/expo/expo/issues/13114\n prependMiddleware(middleware, manifestMiddleware.getHandler());\n\n middleware.use(\n new InterstitialPageMiddleware(this.projectRoot, {\n // TODO: Prevent this from becoming stale.\n scheme: options.location.scheme ?? null,\n }).getHandler()\n );\n middleware.use(\n new DevToolsPluginMiddleware(this.projectRoot, this.devToolsPluginManager).getHandler()\n );\n\n const deepLinkMiddleware = new RuntimeRedirectMiddleware(this.projectRoot, {\n getLocation: ({ runtime }) => {\n if (runtime === 'custom') {\n return this.urlCreator?.constructDevClientUrl();\n } else {\n return this.urlCreator?.constructUrl({\n scheme: 'exp',\n });\n }\n },\n });\n middleware.use(deepLinkMiddleware.getHandler());\n\n const serverRoot = getMetroServerRoot(this.projectRoot);\n\n const domComponentRenderer = createDomComponentsMiddleware(\n {\n metroRoot: serverRoot,\n projectRoot: this.projectRoot,\n },\n instanceMetroOptions\n );\n // Add support for DOM components.\n // TODO: Maybe put behind a flag for now?\n middleware.use(domComponentRenderer);\n\n // TODO: Disable both of these when tunneling to prevent security issues\n middleware.use(new CreateFileMiddleware(this.projectRoot).getHandler());\n\n // For providing info to the error overlay.\n middleware.use((req: ServerRequest, res: ServerResponse, next: ServerNext) => {\n // Use by `@expo/log-box` https://github.com/expo/expo/blob/f29b9f3715e42dca87bf3eebf11f7e7dd1ff73c1/packages/%40expo/log-box/src/utils/devServerEndpoints.ts#L82\n if (req.url?.startsWith('/_expo/error-overlay-meta')) {\n res.statusCode = 200;\n res.setHeader('Content-Type', 'application/json');\n res.end(\n JSON.stringify({\n projectRoot: this.projectRoot,\n serverRoot,\n sdkVersion: exp.sdkVersion,\n })\n );\n return;\n }\n return next();\n });\n\n // Append support for redirecting unhandled requests to the index.html page on web.\n if (this.isTargetingWeb()) {\n if (exp.extra?.router?.unstable_useServerDataLoaders) {\n const loaderModuleMiddleware = new DataLoaderModuleMiddleware(\n this.projectRoot,\n appDir,\n async (location: URL, route: RouteInfo<RegExp>) => {\n const resolvedLoaderRoute = fromServerManifestRoute(location.pathname, route);\n if (!resolvedLoaderRoute) {\n return;\n }\n return this.executeServerDataLoaderAsync(location, resolvedLoaderRoute);\n },\n () => this.getDevServerUrlOrAssert()\n );\n // This MUST be before ServeStaticMiddleware so it doesn't treat the loader files as static assets\n middleware.use(loaderModuleMiddleware.getHandler());\n }\n\n // This MUST be after the manifest middleware so it doesn't have a chance to serve the template `public/index.html`.\n middleware.use(new ServeStaticMiddleware(this.projectRoot).getHandler());\n\n // This should come after the static middleware so it doesn't serve the favicon from `public/favicon.ico`.\n middleware.use(new FaviconMiddleware(this.projectRoot).getHandler());\n }\n\n if (useServerRendering || isReactServerComponentsEnabled) {\n observeAnyFileChanges(\n {\n metro,\n server,\n },\n (events) => {\n if (hasApiRoutes) {\n // NOTE(EvanBacon): We aren't sure what files the API routes are using so we'll just invalidate\n // aggressively to ensure we always have the latest. The only caching we really get here is for\n // cases where the user is making subsequent requests to the same API route without changing anything.\n // This is useful for testing but pretty suboptimal. Luckily our caching is pretty aggressive so it makes\n // up for a lot of the overhead.\n this.invalidateApiRouteCache();\n } else if (!hasWarnedAboutApiRoutes()) {\n for (const event of events) {\n if (\n // If the user did not delete a file that matches the Expo Router API Route convention, then we should warn that\n // API Routes are not enabled in the project.\n event.metadata?.type !== 'd' &&\n // Ensure the file is in the project's routes directory to prevent false positives in monorepos.\n event.filePath.startsWith(appDir) &&\n isApiRouteConvention(event.filePath)\n ) {\n warnInvalidWebOutput();\n }\n }\n }\n\n // Handle loader file changes for HMR\n if (exp.extra?.router?.unstable_useServerDataLoaders) {\n for (const event of events) {\n if (event.metadata?.type !== 'd') {\n this.handleLoaderFileChange(event.filePath);\n }\n }\n }\n }\n );\n }\n\n // If React 19 is enabled, then add RSC middleware to the dev server.\n if (isReactServerComponentsEnabled) {\n this.bindRSCDevModuleInjectionHandler();\n const rscMiddleware = createServerComponentsMiddleware(this.projectRoot, {\n instanceMetroOptions: this.instanceMetroOptions,\n rscPath: '/_flight',\n ssrLoadModule: this.ssrLoadModule.bind(this),\n ssrLoadModuleArtifacts: this.metroImportAsArtifactsAsync.bind(this),\n useClientRouter: isReactServerActionsOnlyEnabled,\n createModuleId: metro._createModuleId.bind(metro),\n routerOptions,\n });\n this.rscRenderer = rscMiddleware;\n middleware.use(rscMiddleware.middleware);\n this.onReloadRscEvent = rscMiddleware.onReloadRscEvent;\n }\n\n // Append support for redirecting unhandled requests to the index.html page on web.\n if (this.isTargetingWeb()) {\n if (!useServerRendering) {\n // This MUST run last since it's the fallback.\n middleware.use(\n new HistoryFallbackMiddleware(manifestMiddleware.getHandler().internal).getHandler()\n );\n } else {\n middleware.use(\n createRouteHandlerMiddleware(this.projectRoot, {\n appDir,\n routerRoot,\n config,\n ...config.exp.extra?.router,\n bundleApiRoute: (functionFilePath) =>\n this.ssrImportApiRoute(functionFilePath, { platform: 'web' }),\n getStaticPageAsync: async (pathname, route) => {\n // TODO: Add server rendering when RSC is enabled.\n if (isReactServerComponentsEnabled) {\n // NOTE: This is a temporary hack to return the SPA/template index.html in development when RSC is enabled.\n // While this technically works, it doesn't provide the correct experience of server rendering the React code to HTML first.\n const html = await manifestMiddleware.getSingleHtmlTemplateAsync();\n return { content: html };\n }\n\n // Non-RSC apps will bundle the static HTML for a given pathname and respond with it.\n return this.getStaticPageAsync(pathname, route);\n },\n })\n );\n }\n }\n } else {\n // If React 19 is enabled, then add RSC middleware to the dev server.\n if (isReactServerComponentsEnabled) {\n this.bindRSCDevModuleInjectionHandler();\n const rscMiddleware = createServerComponentsMiddleware(this.projectRoot, {\n instanceMetroOptions: this.instanceMetroOptions,\n rscPath: '/_flight',\n ssrLoadModule: this.ssrLoadModule.bind(this),\n ssrLoadModuleArtifacts: this.metroImportAsArtifactsAsync.bind(this),\n useClientRouter: isReactServerActionsOnlyEnabled,\n createModuleId: metro._createModuleId.bind(metro),\n routerOptions,\n });\n this.rscRenderer = rscMiddleware;\n }\n }\n // Extend the close method to ensure that we clean up the local info.\n const originalClose = server.close.bind(server);\n\n server.close = (callback?: (err?: Error) => void) => {\n return originalClose((err?: Error) => {\n this.instance = null;\n this.metro = null;\n this.hmrServer = null;\n this.ssrHmrClients = new Map();\n callback?.(err);\n });\n };\n\n this.metro = metro;\n this.hmrServer = hmrServer;\n return {\n server,\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 };\n }\n\n private onReloadRscEvent: ((platform: string) => void) | null = null;\n\n private async registerSsrHmrAsync(url: string, onReload: (platform: string[]) => void) {\n if (!this.hmrServer || this.ssrHmrClients.has(url)) {\n return;\n }\n\n debug('[SSR] Register HMR:', url);\n\n const sendFn = (message: string) => {\n const data = JSON.parse(String(message)) as { type: string; body: any };\n\n switch (data.type) {\n case 'bundle-registered':\n case 'update-done':\n case 'update-start':\n break;\n case 'update':\n {\n const update = data.body;\n const {\n isInitialUpdate,\n added,\n modified,\n deleted,\n }: {\n isInitialUpdate?: boolean;\n added: {\n module: [number | string, string];\n sourceURL: string;\n sourceMappingURL: string;\n }[];\n modified: {\n module: [number | string, string];\n sourceURL: string;\n sourceMappingURL: string;\n }[];\n deleted: (number | string)[];\n } = update;\n\n const hasUpdate = added.length || modified.length || deleted.length;\n\n // NOTE: We throw away the updates and instead simply send a trigger to the client to re-fetch the server route.\n if (!isInitialUpdate && hasUpdate) {\n // Clear all SSR modules before sending the reload event. This ensures that the next event will rebuild the in-memory state from scratch.\n if (typeof globalThis.__c === 'function') globalThis.__c();\n\n const allModuleIds = new Set(\n [...added, ...modified].map((m) => m.module[0]).concat(deleted)\n );\n\n const platforms = unique(\n Array.from(allModuleIds)\n .map((moduleId) => {\n if (typeof moduleId !== 'string') {\n return null;\n }\n // Extract platforms from the module IDs.\n return moduleId.match(/[?&]platform=([\\w]+)/)?.[1] ?? null;\n })\n .filter(Boolean)\n ) as string[];\n\n onReload(platforms);\n }\n }\n break;\n case 'error':\n // GraphNotFound can mean that we have an issue in metroOptions where the URL doesn't match the object props.\n Log.error('[SSR] HMR Error: ' + JSON.stringify(data, null, 2));\n\n if (data.body?.type === 'GraphNotFoundError') {\n Log.error(\n 'Available SSR HMR keys:',\n `${this.metro?._bundler._revisionsByGraphId.keys()}`\n );\n }\n break;\n default:\n debug('Unknown HMR message:', data);\n break;\n }\n };\n\n const client = await this.hmrServer!.onClientConnect(url, sendFn);\n this.ssrHmrClients.set(url, client);\n // Opt in...\n client.optedIntoHMR = true;\n await this.hmrServer!._registerEntryPoint(client, url, sendFn);\n }\n\n public async waitForTypeScriptAsync(): Promise<boolean> {\n if (!this.instance) {\n throw new Error('Cannot wait for TypeScript without a running server.');\n }\n\n return new Promise<boolean>((resolve) => {\n if (!this.metro) {\n // This can happen when the run command is used and the server is already running in another\n // process. In this case we can't wait for the TypeScript check to complete because we don't\n // have access to the Metro server.\n debug('Skipping TypeScript check because Metro is not running (headless).');\n return resolve(false);\n }\n\n const off = metroWatchTypeScriptFiles({\n projectRoot: this.projectRoot,\n server: this.instance!.server,\n metro: this.metro,\n tsconfig: true,\n throttle: true,\n eventTypes: ['change', 'add'],\n callback: async () => {\n // Run once, this prevents the TypeScript project prerequisite from running on every file change.\n off();\n const { TypeScriptProjectPrerequisite } = await import(\n '../../doctor/typescript/TypeScriptProjectPrerequisite.js'\n );\n\n try {\n const req = new TypeScriptProjectPrerequisite(this.projectRoot);\n await req.bootstrapAsync();\n resolve(true);\n } catch (error: any) {\n // Ensure the process doesn't fail if the TypeScript check fails.\n // This could happen during the install.\n Log.log();\n Log.error(\n chalk.red`Failed to automatically setup TypeScript for your project. Try restarting the dev server to fix.`\n );\n Log.exception(error);\n resolve(false);\n }\n },\n });\n });\n }\n\n public async startTypeScriptServices() {\n return startTypescriptTypeGenerationAsync({\n server: this.instance?.server,\n metro: this.metro,\n projectRoot: this.projectRoot,\n });\n }\n\n protected getConfigModuleIds(): string[] {\n return ['./metro.config.js', './metro.config.json', './rn-cli.config.js'];\n }\n\n // API Routes\n\n private pendingRouteOperations = new Map<string, Promise<SSRModuleContentsResult | null>>();\n\n // Bundle the API Route with Metro and return the string contents to be evaluated in the server.\n private async bundleApiRoute(\n filePath: string,\n { platform }: { platform: string }\n ): Promise<SSRModuleContentsResult | null | undefined> {\n if (this.pendingRouteOperations.has(filePath)) {\n return this.pendingRouteOperations.get(filePath);\n }\n const bundleAsync = async (): Promise<SSRModuleContentsResult> => {\n try {\n debug('Bundle API route:', this.instanceMetroOptions.routerRoot, filePath);\n return await this.ssrLoadModuleContents(filePath, {\n isExporting: this.instanceMetroOptions.isExporting,\n platform,\n });\n } catch (error: any) {\n const appDir = this.instanceMetroOptions?.routerRoot\n ? path.join(this.projectRoot, this.instanceMetroOptions!.routerRoot!)\n : undefined;\n const relativePath = appDir ? path.relative(appDir, filePath) : filePath;\n\n // Expected errors: invalid syntax, missing resolutions.\n // Wrap with command error for better error messages.\n const err = new CommandError(\n 'API_ROUTE',\n chalk`Failed to bundle API Route: {bold ${relativePath}}\\n\\n` + error.message\n );\n\n for (const key in error) {\n err[key] = error[key];\n }\n\n throw err;\n } finally {\n // pendingRouteOperations.delete(filepath);\n }\n };\n const route = bundleAsync();\n\n this.pendingRouteOperations.set(filePath, route);\n return route;\n }\n\n private async ssrImportApiRoute(\n filePath: string,\n { platform }: { platform: string }\n ): Promise<null | Record<string, Function> | Response> {\n // TODO: Cache the evaluated function.\n try {\n const apiRoute = await this.bundleApiRoute(filePath, { platform });\n\n if (!apiRoute?.src) {\n return null;\n }\n return evalMetroNoHandling(this.projectRoot, apiRoute.src, apiRoute.filename);\n } catch (error) {\n // Format any errors that were thrown in the global scope of the evaluation.\n if (error instanceof Error) {\n try {\n const htmlServerError = await getErrorOverlayHtmlAsync({\n error,\n projectRoot: this.projectRoot,\n routerRoot: this.instanceMetroOptions.routerRoot!,\n });\n\n return new Response(htmlServerError, {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n } catch (internalError) {\n debug('Failed to generate Metro server error UI for API Route error:', internalError);\n throw error;\n }\n } else {\n throw error;\n }\n }\n }\n\n private invalidateApiRouteCache() {\n this.pendingRouteOperations.clear();\n }\n\n /**\n * Execute a route's loader function. Used during SSR/SSG to fetch data required by routes.\n *\n * This function is used during development and production builds, and **must** receive a valid\n * matched route.\n *\n * @experimental\n */\n async executeServerDataLoaderAsync(\n location: URL,\n route: ResolvedLoaderRoute\n ): Promise<Record<string, any> | undefined> {\n const { exp } = getConfig(this.projectRoot);\n const { unstable_useServerDataLoaders } = exp.extra?.router;\n\n if (!unstable_useServerDataLoaders) {\n throw new CommandError(\n 'LOADERS_NOT_ENABLED',\n 'Server data loaders are not enabled. Add `unstable_useServerDataLoaders` to your `expo-router` plugin config.'\n );\n }\n\n const { routerRoot } = this.instanceMetroOptions;\n assert(\n routerRoot != null,\n 'The server must be started before calling executeRouteLoaderAsync.'\n );\n let loaderData: Record<string, any> | undefined;\n\n try {\n debug(`Matched ${location.pathname} to file: ${route.file}`);\n\n const appDir = path.join(this.projectRoot, routerRoot);\n let modulePath = route.file;\n modulePath = path.isAbsolute(modulePath) ? modulePath : path.join(appDir, modulePath);\n modulePath = modulePath.replace(/\\.(js|ts)x?$/, '');\n\n debug('Using loader module path: ', modulePath);\n\n const routeModule = await this.ssrLoadModule<any>(modulePath, {\n environment: 'node',\n });\n\n if (routeModule.loader) {\n // Register this module for loader HMR\n this.setupLoaderHmr(modulePath);\n\n loaderData = await routeModule.loader({\n params: route.params,\n // NOTE(@hassankhan): The `request` object should only be available when using SSR\n request: null,\n });\n }\n } catch (error: any) {\n throw new CommandError(\n 'LOADER_EXECUTION_FAILED',\n `Failed to execute loader for route \"${location.pathname}\": ${error.message}`\n );\n }\n\n debug('Loader data:', loaderData, ' for location:', location.pathname);\n return loaderData;\n }\n\n // Ensure the global is available for SSR CSS modules to inject client updates.\n private bindRSCDevModuleInjectionHandler() {\n // Used by SSR CSS modules to broadcast client updates.\n globalThis.__expo_rsc_inject_module = this.sendClientModule.bind(this);\n }\n\n // NOTE: This can only target a single platform at a time (web).\n // used for sending RSC CSS to the root client in development.\n private sendClientModule({ code, id }: { code: string; id: string }) {\n this.broadcastMessage('sendDevCommand', {\n name: 'module-import',\n data: {\n code,\n id,\n },\n });\n }\n\n // Metro HMR\n\n private setupHmr(url: URL) {\n const onReload = (platforms: string[] = []) => {\n // Send reload command to client from Fast Refresh code.\n\n if (!platforms.length) {\n // TODO: When is this called?\n this.broadcastMessage('sendDevCommand', {\n name: 'rsc-reload',\n });\n } else {\n for (const platform of platforms) {\n this.onReloadRscEvent?.(platform);\n this.broadcastMessage('sendDevCommand', {\n name: 'rsc-reload',\n platform,\n });\n }\n }\n };\n\n this.registerSsrHmrAsync(url.toString(), onReload);\n }\n\n private watchedLoaderFiles: Set<string> = new Set();\n\n private setupLoaderHmr(modulePath: string) {\n if (this.watchedLoaderFiles.has(modulePath)) {\n return;\n }\n this.watchedLoaderFiles.add(modulePath);\n\n debug('[Loader HMR] Registering loader file for HMR:', modulePath);\n }\n\n private handleLoaderFileChange(changedFilePath: string) {\n for (const loaderPath of this.watchedLoaderFiles) {\n const possibleExtensions = ['.tsx', '.ts', '.jsx', '.js'];\n const isLoaderFile = possibleExtensions.some(\n (ext) => changedFilePath === loaderPath + ext || changedFilePath === loaderPath\n );\n\n if (isLoaderFile) {\n debug('[Loader HMR] Loader file changed, triggering reload:', changedFilePath);\n this.broadcastMessage('sendDevCommand', {\n name: 'reload',\n });\n }\n }\n }\n\n // Direct Metro access\n\n // Emulates the Metro dev server .bundle endpoint without having to go through a server.\n private async _bundleDirectAsync(\n resolvedEntryFilePath: string,\n {\n transformOptions,\n resolverOptions,\n graphOptions,\n serializerOptions,\n }: {\n transformOptions: TransformInputOptions;\n resolverOptions: {\n customResolverOptions: CustomResolverOptions;\n dev: boolean;\n };\n serializerOptions: {\n output?: 'string' | ({} & string);\n modulesOnly: boolean;\n runModule: boolean;\n sourceMapUrl: string;\n sourceUrl: string;\n inlineSourceMap: boolean;\n excludeSource: boolean;\n };\n graphOptions: {\n shallow: boolean;\n lazy: boolean;\n };\n }\n ): Promise<BundleDirectResult> {\n assert(this.metro, 'Metro server must be running to bundle directly.');\n const config = this.metro._config;\n const buildNumber = this.metro.getNewBuildNumber();\n const bundlePerfLogger = config.unstable_perfLoggerFactory?.('BUNDLING_REQUEST', {\n key: buildNumber,\n });\n\n const onProgress = (transformedFileCount: number, totalFileCount: number) => {\n this.metro?._reporter?.update?.({\n buildID: getBuildID(buildNumber),\n type: 'bundle_transform_progressed',\n transformedFileCount,\n totalFileCount,\n });\n };\n\n const revPromise = this.getMetroRevision(resolvedEntryFilePath, {\n graphOptions,\n transformOptions,\n resolverOptions,\n });\n\n bundlePerfLogger?.point('resolvingAndTransformingDependencies_start');\n bundlePerfLogger?.annotate({\n bool: {\n initial_build: revPromise == null,\n },\n });\n this.metro?._reporter.update({\n buildID: getBuildID(buildNumber),\n bundleDetails: {\n bundleType: transformOptions.type,\n dev: transformOptions.dev,\n entryFile: resolvedEntryFilePath,\n minify: transformOptions.minify,\n platform: transformOptions.platform,\n customResolverOptions: resolverOptions.customResolverOptions,\n customTransformOptions: transformOptions.customTransformOptions ?? {},\n },\n isPrefetch: false,\n type: 'bundle_build_started',\n });\n\n try {\n let delta: DeltaResult;\n let revision: GraphRevision;\n\n try {\n // TODO: Some bug in Metro/RSC causes this to break when changing imports in server components.\n // We should resolve the bug because it results in ~6x faster bundling to reuse the graph revision.\n if (transformOptions.customTransformOptions?.environment === 'react-server') {\n const props = await this.metro.getBundler().initializeGraph(\n // NOTE: Using absolute path instead of relative input path is a breaking change.\n // entryFile,\n resolvedEntryFilePath,\n\n transformOptions,\n resolverOptions,\n {\n onProgress,\n shallow: graphOptions.shallow,\n lazy: graphOptions.lazy,\n }\n );\n delta = props.delta;\n revision = props.revision;\n } else {\n const props = await (revPromise != null\n ? this.metro.getBundler().updateGraph(await revPromise, false)\n : this.metro.getBundler().initializeGraph(\n // NOTE: Using absolute path instead of relative input path is a breaking change.\n // entryFile,\n resolvedEntryFilePath,\n\n transformOptions,\n resolverOptions,\n {\n onProgress,\n shallow: graphOptions.shallow,\n lazy: graphOptions.lazy,\n }\n ));\n delta = props.delta;\n revision = props.revision;\n }\n } catch (error) {\n attachImportStackToRootMessage(error);\n dropStackIfContainsCodeFrame(error);\n throw error;\n }\n\n bundlePerfLogger?.annotate({\n int: {\n graph_node_count: revision.graph.dependencies.size,\n },\n });\n bundlePerfLogger?.point('resolvingAndTransformingDependencies_end');\n bundlePerfLogger?.point('serializingBundle_start');\n\n const shouldAddToIgnoreList = this.metro._shouldAddModuleToIgnoreList.bind(this.metro);\n\n const serializer = this.getMetroSerializer();\n\n const options = {\n asyncRequireModulePath: await this.metro._resolveRelativePath(\n config.transformer.asyncRequireModulePath,\n {\n relativeTo: 'project',\n resolverOptions,\n transformOptions,\n }\n ),\n // ...serializerOptions,\n processModuleFilter: config.serializer.processModuleFilter,\n createModuleId: this.metro._createModuleId,\n getRunModuleStatement: config.serializer.getRunModuleStatement,\n globalPrefix: config.transformer.globalPrefix,\n includeAsyncPaths: graphOptions.lazy,\n dev: transformOptions.dev,\n projectRoot: config.projectRoot,\n modulesOnly: serializerOptions.modulesOnly,\n runBeforeMainModule: config.serializer.getModulesRunBeforeMainModule(\n resolvedEntryFilePath\n // path.relative(config.projectRoot, entryFile)\n ),\n runModule: serializerOptions.runModule,\n sourceMapUrl: serializerOptions.sourceMapUrl,\n sourceUrl: serializerOptions.sourceUrl,\n inlineSourceMap: serializerOptions.inlineSourceMap,\n serverRoot: config.server.unstable_serverRoot ?? config.projectRoot,\n shouldAddToIgnoreList,\n\n // TODO(@kitten): This is incoherently typed. The target should be typed to accept this coherently\n // but we have no type overrides or a proper type chain for this\n serializerOptions,\n };\n\n // TODO(@kitten): Yearns for a refactor. The typings here were and are questionable\n const bundle = await serializer(\n // NOTE: Using absolute path instead of relative input path is a breaking change.\n // entryFile,\n resolvedEntryFilePath,\n revision.prepend,\n revision.graph,\n options\n );\n\n this.metro._reporter.update({\n buildID: getBuildID(buildNumber),\n type: 'bundle_build_done',\n });\n\n bundlePerfLogger?.point('serializingBundle_end');\n\n let bundleCode: string | null = null;\n let bundleMap: string | null = null;\n\n if (serializerOptions.output === 'static') {\n try {\n const parsed = typeof bundle === 'string' ? JSON.parse(bundle) : bundle;\n\n assert(\n 'artifacts' in parsed && Array.isArray(parsed.artifacts),\n 'Expected serializer to return an object with key artifacts to contain an array of serial assets.'\n );\n\n const artifacts = parsed.artifacts as SerialAsset[];\n const assets = parsed.assets;\n\n const bundleCode = artifacts.filter((asset) => asset.type === 'js')[0];\n const bundleMap = artifacts.filter((asset) => asset.type === 'map')?.[0]?.source ?? '';\n\n return {\n numModifiedFiles: delta.reset\n ? delta.added.size + revision.prepend.length\n : delta.added.size + delta.modified.size + delta.deleted.size,\n lastModifiedDate: revision.date,\n nextRevId: revision.id,\n bundle: bundleCode.source,\n map: bundleMap,\n artifacts,\n assets,\n };\n } catch (error: any) {\n throw new Error(\n 'Serializer did not return expected format. The project copy of `expo/metro-config` may be out of date. Error: ' +\n error.message\n );\n }\n }\n\n if (typeof bundle === 'string') {\n bundleCode = bundle;\n\n // Create the source map in a second pass...\n let { prepend, graph } = revision;\n if (serializerOptions.modulesOnly) {\n prepend = [];\n }\n\n bundleMap = await sourceMapStringAsync(\n [\n //\n ...prepend,\n ...this.metro._getSortedModules(graph),\n ],\n {\n excludeSource: serializerOptions.excludeSource,\n processModuleFilter: config.serializer.processModuleFilter,\n shouldAddToIgnoreList,\n }\n );\n } else {\n bundleCode = bundle.code;\n bundleMap = bundle.map;\n }\n\n return {\n numModifiedFiles: delta.reset\n ? delta.added.size + revision.prepend.length\n : delta.added.size + delta.modified.size + delta.deleted.size,\n lastModifiedDate: revision.date,\n nextRevId: revision.id,\n bundle: bundleCode,\n map: bundleMap,\n };\n } catch (error: any) {\n // Mark the error so we know how to format and return it later.\n if (error) {\n error[IS_METRO_BUNDLE_ERROR_SYMBOL] = true;\n }\n\n this.metro._reporter.update({\n buildID: getBuildID(buildNumber),\n type: 'bundle_build_failed',\n });\n\n throw error;\n }\n }\n\n private getMetroSerializer() {\n return (\n this.metro?._config?.serializer.customSerializer ||\n ((entryPoint, preModules, graph, options) =>\n bundleToString(baseJSBundle(entryPoint, preModules, graph, options)).code)\n );\n }\n\n private getMetroRevision(\n resolvedEntryFilePath: string,\n {\n graphOptions,\n transformOptions,\n resolverOptions,\n }: {\n transformOptions: TransformInputOptions;\n resolverOptions: {\n customResolverOptions: CustomResolverOptions;\n dev: boolean;\n };\n graphOptions: {\n shallow: boolean;\n lazy: boolean;\n };\n }\n ) {\n assert(this.metro, 'Metro server must be running to bundle directly.');\n const config = this.metro._config;\n\n const graphId = getGraphId(resolvedEntryFilePath, transformOptions, {\n unstable_allowRequireContext: config.transformer.unstable_allowRequireContext,\n resolverOptions,\n shallow: graphOptions.shallow,\n lazy: graphOptions.lazy,\n });\n return this.metro.getBundler().getRevisionByGraphId(graphId);\n }\n\n private async resolveRelativePathAsync(\n moduleId: string,\n {\n resolverOptions,\n transformOptions,\n }: {\n transformOptions: TransformInputOptions;\n resolverOptions: {\n customResolverOptions: CustomResolverOptions;\n dev: boolean;\n };\n }\n ) {\n assert(this.metro, 'cannot invoke resolveRelativePathAsync without metro instance');\n return await this.metro._resolveRelativePath(convertPathToModuleSpecifier(moduleId), {\n relativeTo: 'server',\n resolverOptions,\n transformOptions,\n });\n }\n}\n\nfunction getBuildID(buildNumber: number): string {\n return buildNumber.toString(36);\n}\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\nasync function sourceMapStringAsync(\n modules: readonly Module[],\n options: SourceMapGeneratorOptions\n): Promise<string> {\n return (await sourceMapGeneratorNonBlocking(modules, options)).toString(undefined, {\n excludeSource: options.excludeSource,\n });\n}\n\nfunction unique<T>(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n"],"names":["MetroBundlerDevServer","debug","require","EXPO_GO_METRO_PORT","DEV_CLIENT_METRO_PORT","BundlerDevServer","name","resolvePortAsync","options","port","devClient","Number","process","env","RCT_METRO_PORT","getFreePortAsync","exportServerRoute","contents","artifactFilename","files","includeSourceMaps","descriptor","src","map","artifactBasename","encodeURIComponent","path","basename","replace","parsedMap","JSON","parse","mapData","stringify","version","sources","source","startsWith","projectRoot","relative","convertPathToModuleSpecifier","sourcesContent","Array","length","fill","names","mappings","targetDomain","set","fileData","exportMiddleware","manifest","appDir","outputDir","platform","middleware","middlewareFilePath","isAbsolute","file","join","bundleApiRoute","middlewareId","exportExpoRouterApiRoutesAsync","prerenderManifest","routerRoot","instanceMetroOptions","assert","getExpoRouterRoutesManifestAsync","Map","rscPath","isReactServerComponentsEnabled","apiRoutes","find","route","page","push","resolve","namedRegex","routeKeys","rsc","filepath","apiRouteId","htmlRoutes","exp","getConfig","fetchManifest","extra","router","preserveRedirectAndRewrites","asJson","CommandError","getServerManifestAsync","getBuildTimeServerManifestAsync","getManifest","ssrLoadModule","environment","isReactServerRoutesEnabled","serverManifest","htmlManifest","getStaticRenderFunctionAsync","url","getDevServerUrlOrAssert","getStaticContent","preserveApiRoutes","renderAsync","opts","location","URL","executeLoaderAsync","resolvedLoaderRoute","fromRuntimeManifestRoute","pathname","inflateManifest","undefined","executeServerDataLoaderAsync","getStaticResourcesAsync","mainModuleName","clientBoundaries","mode","minify","isExporting","baseUrl","reactCompiler","asyncRoutes","resolvedMainModuleName","resolveMainModuleName","metroImportAsArtifactsAsync","splitChunks","EXPO_NO_BUNDLE_SPLITTING","serializerIncludeMaps","lazy","EXPO_NO_METRO_LAZY","bytecode","getStaticPageAsync","devBundleUrlPathname","createBundleUrlPath","bundleStaticHtml","useServerDataLoaders","unstable_useServerDataLoaders","fromServerManifestRoute","data","loader","artifacts","resources","staticHtml","Promise","all","content","serializeHtmlWithAssets","template","devBundleUrl","hydrate","EXPO_WEB_DEV_HYDRATE","filePath","specificOptions","results","ssrLoadModuleContents","serializerOutput","assets","filename","metroLoadModuleContents","extraOptions","inlineSourceMap","engine","expoBundleOptions","getMetroDirectBundleOptions","resolverOptions","customResolverOptions","dev","transformOptions","type","unstable_transformProfile","customTransformOptions","Object","create","resolvedEntryFilePath","resolveRelativePathAsync","createBundleOsPath","_bundleDirectAsync","graphOptions","shallow","serializerOptions","modulesOnly","runModule","sourceUrl","sourceMapUrl","bundle","rest","scriptContents","wrapBundle","cachedSourceMaps","nativeExportBundleAsync","singlePageReactServerComponentExportAsync","legacySinglePageExportBundleAsync","getReactServerReferences","unique","filter","a","artifact","metadata","reactServerReferences","ref","fileURLToFilePath","flat","Boolean","reactClientReferences","serverActionReferencesInServer","cssModules","rscRenderer","getExpoRouterClientReferencesAsync","domRoot","processClientBoundaries","newReactServerReferences","Error","allKnownReactServerReferences","nestedClientBoundaries","exportServerActionsAsync","entryPoints","hasUniqueClientBoundaries","some","boundary","includes","concat","serverRoot","getMetroServerRoot","clientBoundariesAsOpaqueIds","toPosixPath","moduleIdToSplitBundle","paths","values","reduce","acc","ssrManifest","keys","forEach","routerOptions","exportRoutesAsync","fromEntries","from","entries","key","value","output","watchEnvironmentVariables","instance","metro","envFiles","runtimeEnv","getFiles","NODE_ENV","fileName","observeFileChanges","server","load","force","startImplementationAsync","urlCreator","getUrlCreator","config","skipSDKVersionRequirement","experiments","reactServerComponentRoutes","reactServerFunctions","isReactServerActionsOnlyEnabled","useServerRendering","web","hasApiRoutes","getBaseUrlFromExpoConfig","getAsyncRoutesFromExpoConfig","getRouterDirectoryModuleIdWithManifest","origin","configPath","dynamicConfigPath","staticConfigPath","configFileName","parsedOptions","maxWorkers","resetCache","resetDevServer","EXPO_DEV_SERVER_ORIGIN","hmrServer","messageSocket","instantiateMetroAsync","manifestMiddleware","getManifestMiddlewareAsync","prependMiddleware","ContextModuleSourceMapsMiddleware","getHandler","use","InterstitialPageMiddleware","scheme","DevToolsPluginMiddleware","devToolsPluginManager","deepLinkMiddleware","RuntimeRedirectMiddleware","getLocation","runtime","constructDevClientUrl","constructUrl","domComponentRenderer","createDomComponentsMiddleware","metroRoot","CreateFileMiddleware","req","res","next","statusCode","setHeader","end","sdkVersion","isTargetingWeb","loaderModuleMiddleware","DataLoaderModuleMiddleware","ServeStaticMiddleware","FaviconMiddleware","observeAnyFileChanges","events","invalidateApiRouteCache","hasWarnedAboutApiRoutes","event","isApiRouteConvention","warnInvalidWebOutput","handleLoaderFileChange","bindRSCDevModuleInjectionHandler","rscMiddleware","createServerComponentsMiddleware","bind","ssrLoadModuleArtifacts","useClientRouter","createModuleId","_createModuleId","onReloadRscEvent","HistoryFallbackMiddleware","internal","createRouteHandlerMiddleware","functionFilePath","ssrImportApiRoute","html","getSingleHtmlTemplateAsync","originalClose","close","callback","err","ssrHmrClients","host","protocol","registerSsrHmrAsync","onReload","has","sendFn","message","String","update","body","isInitialUpdate","added","modified","deleted","hasUpdate","globalThis","__c","allModuleIds","Set","m","module","platforms","moduleId","match","Log","error","_bundler","_revisionsByGraphId","client","onClientConnect","optedIntoHMR","_registerEntryPoint","waitForTypeScriptAsync","off","metroWatchTypeScriptFiles","tsconfig","throttle","eventTypes","TypeScriptProjectPrerequisite","bootstrapAsync","log","chalk","red","exception","startTypeScriptServices","startTypescriptTypeGenerationAsync","getConfigModuleIds","pendingRouteOperations","get","bundleAsync","relativePath","apiRoute","evalMetroNoHandling","htmlServerError","getErrorOverlayHtmlAsync","Response","status","headers","internalError","clear","loaderData","modulePath","routeModule","setupLoaderHmr","params","request","__expo_rsc_inject_module","sendClientModule","code","id","broadcastMessage","setupHmr","toString","watchedLoaderFiles","add","changedFilePath","loaderPath","possibleExtensions","isLoaderFile","ext","_config","buildNumber","getNewBuildNumber","bundlePerfLogger","unstable_perfLoggerFactory","onProgress","transformedFileCount","totalFileCount","_reporter","buildID","getBuildID","revPromise","getMetroRevision","point","annotate","bool","initial_build","bundleDetails","bundleType","entryFile","isPrefetch","delta","revision","props","getBundler","initializeGraph","updateGraph","attachImportStackToRootMessage","dropStackIfContainsCodeFrame","int","graph_node_count","graph","dependencies","size","shouldAddToIgnoreList","_shouldAddModuleToIgnoreList","serializer","getMetroSerializer","asyncRequireModulePath","_resolveRelativePath","transformer","relativeTo","processModuleFilter","getRunModuleStatement","globalPrefix","includeAsyncPaths","runBeforeMainModule","getModulesRunBeforeMainModule","unstable_serverRoot","prepend","bundleCode","bundleMap","parsed","isArray","asset","numModifiedFiles","reset","lastModifiedDate","date","nextRevId","sourceMapStringAsync","_getSortedModules","excludeSource","IS_METRO_BUNDLE_ERROR_SYMBOL","customSerializer","entryPoint","preModules","bundleToString","baseJSBundle","graphId","getGraphId","unstable_allowRequireContext","getRevisionByGraphId","extras","hot","evalMetroAndWrapFunctions","str","modules","sourceMapGeneratorNonBlocking","array"],"mappings":"AAAA;;;;;CAKC;;;;+BAkJYA;;;eAAAA;;;;yBAjJyB;;;;;;;yBACH;;;;;;;iEACP;;;;;;;gEACH;;;;;;;yBAIlB;;;;;;;gEAYoB;;;;;;;gEACJ;;;;;;;gEAKJ;;;;;;;gEACD;;;;;;;gEAGD;;;;;;kDAKV;6CACsC;qCACE;kCACT;qCAM/B;2CACmC;wBAMnC;+BACiC;qDACkB;qBAMtC;sBACA;wBACS;0BACD;sBACK;kCACwC;0CAKlE;+BAKA;mDAC2C;sCACb;4CACM;0CACF;yCACK;mCACZ;2CACQ;4C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AAI,IAAI,CAACvD,oBAAoB,CAACuD,WAAW;QAExE,QAybAwF,cAAmF,WAoT3E2H,mBAAwD,MAsJhE,aAAa;aAEL4D,yBAAyB,IAAInU,YAkM7B6V,qBAAkC,IAAIvD;;AAqWhD;AAEA,SAASwE,WAAWT,WAAmB;IACrC,OAAOA,YAAYT,QAAQ,CAAC;AAC9B;AAEA,SAASnO,WAAWuT,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAIxd,OAAO,CAAC,oBAAoB;AACzC;AAEA,eAAewc,qBACbiB,OAA0B,EAC1B7e,OAAkC;IAElC,OAAO,AAAC,CAAA,MAAM8e,IAAAA,mDAA6B,EAACD,SAAS7e,QAAO,EAAGwZ,QAAQ,CAAC/S,WAAW;QACjFqX,eAAe9d,QAAQ8d,aAAa;IACtC;AACF;AAEA,SAASnS,OAAUoT,KAAU;IAC3B,OAAO7c,MAAMoM,IAAI,CAAC,IAAI4H,IAAI6I;AAC5B"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/MetroBundlerDevServer.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, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport * as runtimeEnv from '@expo/env';\nimport baseJSBundle from '@expo/metro/metro/DeltaBundler/Serializers/baseJSBundle';\nimport {\n sourceMapGeneratorNonBlocking,\n type SourceMapGeneratorOptions,\n} from '@expo/metro/metro/DeltaBundler/Serializers/sourceMapGenerator';\nimport type {\n Module,\n DeltaResult,\n TransformInputOptions,\n} from '@expo/metro/metro/DeltaBundler/types';\nimport type {\n default as MetroHmrServer,\n Client as MetroHmrClient,\n} from '@expo/metro/metro/HmrServer';\nimport type { GraphRevision } from '@expo/metro/metro/IncrementalBundler';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport bundleToString from '@expo/metro/metro/lib/bundleToString';\nimport getGraphId from '@expo/metro/metro/lib/getGraphId';\nimport type { TransformProfile } from '@expo/metro/metro-babel-transformer';\nimport type { CustomResolverOptions } from '@expo/metro/metro-resolver';\nimport { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport type { GetStaticContentOptions } from '@expo/router-server/build/static/renderStaticContent';\nimport assert from 'assert';\nimport chalk from 'chalk';\nimport type { RouteNode } from 'expo-router/build/Route';\nimport { type RouteInfo, type RoutesManifest } from 'expo-server/private';\nimport path from 'path';\n\nimport {\n createServerComponentsMiddleware,\n fileURLToFilePath,\n} from './createServerComponentsMiddleware';\nimport { createRouteHandlerMiddleware } from './createServerRouteMiddleware';\nimport { fetchManifest, inflateManifest } from './fetchRouterManifest';\nimport { instantiateMetroAsync } from './instantiateMetro';\nimport {\n attachImportStackToRootMessage,\n dropStackIfContainsCodeFrame,\n getErrorOverlayHtmlAsync,\n IS_METRO_BUNDLE_ERROR_SYMBOL,\n} from './metroErrorInterface';\nimport { metroWatchTypeScriptFiles } from './metroWatchTypeScriptFiles';\nimport {\n getRouterDirectoryModuleIdWithManifest,\n hasWarnedAboutApiRoutes,\n isApiRouteConvention,\n warnInvalidWebOutput,\n} from './router';\nimport { serializeHtmlWithAssets } from './serializeHtml';\nimport { observeAnyFileChanges, observeFileChanges } from './waitForMetroToObserveTypeScriptFile';\nimport type {\n BundleAssetWithFileHashes,\n ExportAssetDescriptor,\n ExportAssetMap,\n} from '../../../export/saveAssets';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { getFreePortAsync } from '../../../utils/port';\nimport { BundlerDevServer, BundlerStartOptions, DevServerInstance } from '../BundlerDevServer';\nimport {\n cachedSourceMaps,\n evalMetroAndWrapFunctions,\n evalMetroNoHandling,\n} from '../getStaticRenderFunctions';\nimport {\n fromRuntimeManifestRoute,\n fromServerManifestRoute,\n type ResolvedLoaderRoute,\n} from './resolveLoader';\nimport { ContextModuleSourceMapsMiddleware } from '../middleware/ContextModuleSourceMapsMiddleware';\nimport { CreateFileMiddleware } from '../middleware/CreateFileMiddleware';\nimport { DataLoaderModuleMiddleware } from '../middleware/DataLoaderModuleMiddleware';\nimport { DevToolsPluginMiddleware } from '../middleware/DevToolsPluginMiddleware';\nimport { createDomComponentsMiddleware } from '../middleware/DomComponentsMiddleware';\nimport { FaviconMiddleware } from '../middleware/FaviconMiddleware';\nimport { HistoryFallbackMiddleware } from '../middleware/HistoryFallbackMiddleware';\nimport { InterstitialPageMiddleware } from '../middleware/InterstitialPageMiddleware';\nimport { resolveMainModuleName } from '../middleware/ManifestMiddleware';\nimport { RuntimeRedirectMiddleware } from '../middleware/RuntimeRedirectMiddleware';\nimport { ServeStaticMiddleware } from '../middleware/ServeStaticMiddleware';\nimport {\n convertPathToModuleSpecifier,\n createBundleUrlPath,\n ExpoMetroOptions,\n createBundleOsPath,\n getAsyncRoutesFromExpoConfig,\n getBaseUrlFromExpoConfig,\n getMetroDirectBundleOptions,\n} from '../middleware/metroOptions';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { ServerNext, ServerRequest, ServerResponse } from '../middleware/server.types';\nimport { startTypescriptTypeGenerationAsync } from '../type-generation/startTypescriptTypeGeneration';\n\nexport type ExpoRouterRuntimeManifest = Awaited<\n ReturnType<typeof import('@expo/router-server/build/static/renderStaticContent').getManifest>\n>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\ninterface BundleDirectResult {\n numModifiedFiles: number;\n lastModifiedDate: Date;\n nextRevId: string;\n bundle: string;\n map: string;\n /** Defined if the output is multi-bundle. */\n artifacts?: SerialAsset[];\n assets?: readonly BundleAssetWithFileHashes[];\n}\n\ninterface MetroModuleContentsResult extends BundleDirectResult {\n filename: string;\n}\n\ninterface SSRModuleContentsResult extends Omit<BundleDirectResult, 'bundle'> {\n filename: string;\n src: string;\n map: string;\n}\n\n// TODO(@kitten): We access this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this function is defined\ndeclare namespace globalThis {\n const __c: (() => void) | undefined;\n let __expo_rsc_inject_module: (params: { code: string; id: string }) => void | undefined;\n}\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\n/** Default port to use for apps running in Expo Go. */\nconst EXPO_GO_METRO_PORT = 8081;\n\n/** Default port to use for apps that run in standard React Native projects or Expo Dev Clients. */\nconst DEV_CLIENT_METRO_PORT = 8081;\n\nexport class MetroBundlerDevServer extends BundlerDevServer {\n private metro: MetroServer | null = null;\n private hmrServer: MetroHmrServer<MetroHmrClient> | null = null;\n private ssrHmrClients: Map<string, MetroHmrClient> = new Map();\n isReactServerComponentsEnabled?: boolean;\n isReactServerRoutesEnabled?: boolean;\n\n get name(): string {\n return 'metro';\n }\n\n async resolvePortAsync(options: Partial<BundlerStartOptions> = {}): Promise<number> {\n const port =\n // If the manually defined port is busy then an error should be thrown...\n options.port ??\n // Otherwise use the default port based on the runtime target.\n (options.devClient\n ? // Don't check if the port is busy if we're using the dev client since most clients are hardcoded to 8081.\n Number(process.env.RCT_METRO_PORT) || DEV_CLIENT_METRO_PORT\n : // Otherwise (running in Expo Go) use a free port that falls back on the classic 8081 port.\n await getFreePortAsync(EXPO_GO_METRO_PORT));\n\n return port;\n }\n\n private async exportServerRouteAsync({\n contents,\n artifactFilename,\n files,\n includeSourceMaps,\n descriptor,\n }: {\n contents: { src: string; map?: any } | null | undefined;\n artifactFilename: string;\n files: ExportAssetMap;\n includeSourceMaps?: boolean;\n routeId?: string;\n descriptor: Partial<ExportAssetDescriptor>;\n }) {\n if (!contents) return;\n\n let src = contents.src;\n if (includeSourceMaps && contents.map) {\n // TODO(kitten): Merge the source map transformer in the future\n // https://github.com/expo/expo/blob/0dffdb15/packages/%40expo/metro-config/src/serializer/serializeChunks.ts#L422-L439\n // Alternatively, check whether `sourcesRoot` helps here\n const artifactBasename = encodeURIComponent(path.basename(artifactFilename) + '.map');\n src = src.replace(/\\/\\/# sourceMappingURL=.*/g, `//# sourceMappingURL=${artifactBasename}`);\n const parsedMap = typeof contents.map === 'string' ? JSON.parse(contents.map) : contents.map;\n const mapData: any = {\n ...descriptor,\n contents: JSON.stringify({\n version: parsedMap.version,\n sources: parsedMap.sources.map((source: string) => {\n source =\n typeof source === 'string' && source.startsWith(this.projectRoot)\n ? path.relative(this.projectRoot, source)\n : source;\n return convertPathToModuleSpecifier(source);\n }),\n sourcesContent: new Array(parsedMap.sources.length).fill(null),\n names: parsedMap.names,\n mappings: parsedMap.mappings,\n }),\n targetDomain: 'server',\n };\n files.set(artifactFilename + '.map', mapData);\n }\n const fileData: ExportAssetDescriptor = {\n ...descriptor,\n contents: src,\n targetDomain: 'server',\n };\n files.set(artifactFilename, fileData);\n }\n\n private async exportMiddlewareAsync({\n manifest,\n appDir,\n outputDir,\n files,\n platform,\n includeSourceMaps,\n }: {\n manifest: RoutesManifest;\n appDir: string;\n outputDir: string;\n files: ExportAssetMap;\n platform: string;\n includeSourceMaps?: boolean;\n }) {\n if (!manifest.middleware) return;\n\n const middlewareFilePath = path.isAbsolute(manifest.middleware.file)\n ? manifest.middleware.file\n : path.join(appDir, manifest.middleware.file);\n const contents = await this.bundleApiRoute(middlewareFilePath, { platform });\n const artifactFilename = convertPathToModuleSpecifier(\n path.join(outputDir, path.relative(appDir, middlewareFilePath.replace(/\\.[tj]sx?$/, '.js')))\n );\n\n await this.exportServerRouteAsync({\n contents,\n artifactFilename,\n files,\n includeSourceMaps,\n descriptor: {\n middlewareId: '/middleware',\n },\n });\n\n // Remap the middleware file to represent the output file.\n manifest.middleware.file = artifactFilename;\n }\n\n async exportExpoRouterApiRoutesAsync({\n includeSourceMaps,\n outputDir,\n prerenderManifest,\n platform,\n }: {\n includeSourceMaps?: boolean;\n outputDir: string;\n // This does not contain the API routes info.\n prerenderManifest: RoutesManifest<string>;\n platform: string;\n }): Promise<{ files: ExportAssetMap; manifest: RoutesManifest<string> }> {\n const { routerRoot } = this.instanceMetroOptions;\n assert(\n routerRoot != null,\n 'The server must be started before calling exportExpoRouterApiRoutesAsync.'\n );\n\n const appDir = path.join(this.projectRoot, routerRoot);\n const manifest = await this.getExpoRouterRoutesManifestAsync({ appDir });\n\n const files: ExportAssetMap = new Map();\n\n // Inject RSC middleware.\n const rscPath = '/_flight/[...rsc]';\n\n if (\n this.isReactServerComponentsEnabled &&\n // If the RSC route is not already in the manifest, add it.\n !manifest.apiRoutes.find((route) => route.page.startsWith('/_flight/'))\n ) {\n debug('Adding RSC route to the manifest:', rscPath);\n // NOTE: This might need to be sorted to the correct spot in the future.\n manifest.apiRoutes.push({\n // TODO(@kitten): This isn't great, we shouldn't be needing to rely on files like this\n // It might even be better to make templating strings since that'd be type-checked, but currently,\n // we rely on this being an entrypoint for Metro\n file: require.resolve('@expo/cli/static/template/[...rsc]+api.ts'),\n page: rscPath,\n namedRegex: '^/_flight(?:/(?<rsc>.+?))?(?:/)?$',\n routeKeys: { rsc: 'rsc' },\n });\n }\n\n await this.exportMiddlewareAsync({\n manifest,\n appDir,\n outputDir,\n files,\n platform,\n includeSourceMaps,\n });\n\n for (const route of manifest.apiRoutes) {\n const filepath = path.isAbsolute(route.file) ? route.file : path.join(appDir, route.file);\n const contents = await this.bundleApiRoute(filepath, { platform });\n\n const artifactFilename =\n route.page === rscPath\n ? // HACK: Add RSC renderer to the output...\n convertPathToModuleSpecifier(path.join(outputDir, '.' + rscPath + '.js'))\n : convertPathToModuleSpecifier(\n path.join(outputDir, path.relative(appDir, filepath.replace(/\\.[tj]sx?$/, '.js')))\n );\n\n await this.exportServerRouteAsync({\n contents,\n artifactFilename,\n files,\n includeSourceMaps,\n descriptor: {\n apiRouteId: route.page,\n },\n });\n // Remap the manifest files to represent the output files.\n route.file = artifactFilename;\n }\n\n return {\n manifest: {\n ...manifest,\n htmlRoutes: prerenderManifest.htmlRoutes,\n },\n files,\n };\n }\n\n async getExpoRouterRoutesManifestAsync({ appDir }: { appDir: string }) {\n // getBuiltTimeServerManifest\n const { exp } = getConfig(this.projectRoot);\n const manifest = await fetchManifest(this.projectRoot, {\n ...exp.extra?.router,\n preserveRedirectAndRewrites: true,\n asJson: true,\n appDir,\n });\n\n if (!manifest) {\n throw new CommandError(\n 'EXPO_ROUTER_SERVER_MANIFEST',\n 'Unexpected error: server manifest could not be fetched.'\n );\n }\n\n return manifest;\n }\n\n async getServerManifestAsync(): Promise<{\n serverManifest: RoutesManifest<string>;\n htmlManifest: ExpoRouterRuntimeManifest;\n }> {\n const { exp } = getConfig(this.projectRoot);\n // NOTE: This could probably be folded back into `renderStaticContent` when expo-asset and font support RSC.\n const { getBuildTimeServerManifestAsync, getManifest } = await this.ssrLoadModule<\n typeof import('@expo/router-server/build/static/getServerManifest')\n >('@expo/router-server/build/static/getServerManifest.js', {\n // Only use react-server environment when the routes are using react-server rendering by default.\n environment: this.isReactServerRoutesEnabled ? 'react-server' : 'node',\n });\n\n return {\n serverManifest: await getBuildTimeServerManifestAsync({ ...exp.extra?.router }),\n htmlManifest: await getManifest({ ...exp.extra?.router }),\n };\n }\n\n /**\n * This function is invoked when exporting via `expo export`\n */\n async getStaticRenderFunctionAsync(): Promise<{\n serverManifest: RoutesManifest<string>;\n manifest: ExpoRouterRuntimeManifest;\n renderAsync: (\n path: string,\n route: RouteNode,\n opts?: GetStaticContentOptions\n ) => Promise<string>;\n executeLoaderAsync: (path: string, route: RouteNode) => Promise<any>;\n }> {\n const { routerRoot } = this.instanceMetroOptions;\n assert(\n routerRoot != null,\n 'The server must be started before calling getStaticRenderFunctionAsync.'\n );\n\n const appDir = path.join(this.projectRoot, routerRoot);\n const url = this.getDevServerUrlOrAssert();\n\n const { getStaticContent, getManifest, getBuildTimeServerManifestAsync } =\n await this.ssrLoadModule<\n typeof import('@expo/router-server/build/static/renderStaticContent')\n >('@expo/router-server/node/render.js', {\n // This must always use the legacy rendering resolution (no `react-server`) because it leverages\n // the previous React SSG utilities which aren't available in React 19.\n environment: 'node',\n });\n\n const { exp } = getConfig(this.projectRoot);\n\n const serverManifest = await getBuildTimeServerManifestAsync({\n ...exp.extra?.router,\n });\n\n return {\n serverManifest,\n // Get routes from Expo Router.\n manifest: await getManifest({ preserveApiRoutes: false, ...exp.extra?.router }),\n // Get route generating function\n renderAsync: async (path, route, opts?) => {\n const location = new URL(path, url);\n return await getStaticContent(location, opts);\n },\n executeLoaderAsync: async (path, route) => {\n const location = new URL(path, url);\n\n const resolvedLoaderRoute = fromRuntimeManifestRoute(location.pathname, route, {\n serverManifest: inflateManifest(serverManifest),\n appDir,\n });\n\n if (!resolvedLoaderRoute) {\n return undefined;\n }\n\n return await this.executeServerDataLoaderAsync(location, resolvedLoaderRoute);\n },\n };\n }\n\n async getStaticResourcesAsync({\n includeSourceMaps,\n mainModuleName,\n clientBoundaries = this.instanceMetroOptions.clientBoundaries ?? [],\n platform = 'web',\n }: {\n includeSourceMaps?: boolean;\n mainModuleName?: string;\n clientBoundaries?: string[];\n platform?: string;\n } = {}) {\n const { mode, minify, isExporting, baseUrl, reactCompiler, routerRoot, asyncRoutes } =\n this.instanceMetroOptions;\n assert(\n mode != null &&\n isExporting != null &&\n baseUrl != null &&\n routerRoot != null &&\n reactCompiler != null &&\n asyncRoutes != null,\n 'The server must be started before calling getStaticResourcesAsync.'\n );\n\n const resolvedMainModuleName =\n mainModuleName ?? './' + resolveMainModuleName(this.projectRoot, { platform });\n return await this.metroImportAsArtifactsAsync(resolvedMainModuleName, {\n splitChunks: isExporting && !env.EXPO_NO_BUNDLE_SPLITTING,\n platform,\n mode,\n minify,\n environment: 'client',\n serializerIncludeMaps: includeSourceMaps,\n mainModuleName: resolvedMainModuleName,\n lazy: !env.EXPO_NO_METRO_LAZY,\n asyncRoutes,\n baseUrl,\n isExporting,\n routerRoot,\n clientBoundaries,\n reactCompiler,\n bytecode: false,\n });\n }\n\n /**\n * This function is invoked when running in development via `expo start`\n */\n private async getStaticPageAsync(pathname: string, route: RouteInfo<RegExp>) {\n const { exp } = getConfig(this.projectRoot);\n const { mode, isExporting, clientBoundaries, baseUrl, reactCompiler, routerRoot, asyncRoutes } =\n this.instanceMetroOptions;\n assert(\n mode != null &&\n isExporting != null &&\n baseUrl != null &&\n reactCompiler != null &&\n routerRoot != null &&\n asyncRoutes != null,\n 'The server must be started before calling getStaticPageAsync.'\n );\n const platform = 'web';\n\n const devBundleUrlPathname = createBundleUrlPath({\n splitChunks: isExporting && !env.EXPO_NO_BUNDLE_SPLITTING,\n platform,\n mode,\n environment: 'client',\n reactCompiler,\n mainModuleName: resolveMainModuleName(this.projectRoot, { platform }),\n lazy: !env.EXPO_NO_METRO_LAZY,\n baseUrl,\n isExporting,\n asyncRoutes,\n routerRoot,\n clientBoundaries,\n bytecode: false,\n });\n\n const bundleStaticHtml = async (): Promise<string> => {\n const { getStaticContent } = await this.ssrLoadModule<\n typeof import('@expo/router-server/build/static/renderStaticContent')\n >('@expo/router-server/node/render.js', {\n // This must always use the legacy rendering resolution (no `react-server`) because it leverages\n // the previous React SSG utilities which aren't available in React 19.\n environment: 'node',\n minify: false,\n isExporting,\n platform,\n });\n\n const location = new URL(pathname, this.getDevServerUrlOrAssert());\n\n const useServerDataLoaders = exp.extra?.router?.unstable_useServerDataLoaders;\n if (!useServerDataLoaders) {\n return await getStaticContent(location);\n }\n\n const resolvedLoaderRoute = fromServerManifestRoute(location.pathname, route);\n if (!resolvedLoaderRoute) {\n return await getStaticContent(location);\n }\n\n const data = await this.executeServerDataLoaderAsync(location, resolvedLoaderRoute);\n return await getStaticContent(location, { loader: { data } });\n };\n\n const [{ artifacts: resources }, staticHtml] = await Promise.all([\n this.getStaticResourcesAsync({\n clientBoundaries: [],\n }),\n bundleStaticHtml(),\n ]);\n const content = serializeHtmlWithAssets({\n isExporting,\n resources,\n template: staticHtml,\n devBundleUrl: devBundleUrlPathname,\n baseUrl,\n hydrate: env.EXPO_WEB_DEV_HYDRATE,\n });\n return {\n content,\n resources,\n };\n }\n\n // Set when the server is started.\n private instanceMetroOptions: Partial<ExpoMetroOptions> = {};\n\n private ssrLoadModule: SSRLoadModuleFunc = async (\n filePath,\n specificOptions = {},\n extras = {}\n ) => {\n const res = await this.ssrLoadModuleContents(filePath, specificOptions);\n\n if (\n // TODO: hot should be a callback function for invalidating the related SSR module.\n extras.hot &&\n this.instanceMetroOptions.isExporting !== true\n ) {\n // Register SSR HMR\n const serverRoot = getMetroServerRoot(this.projectRoot);\n const relativePath = path.relative(serverRoot, res.filename);\n const url = new URL(relativePath, this.getDevServerUrlOrAssert());\n this.setupHmr(url);\n }\n\n return evalMetroAndWrapFunctions(\n this.projectRoot,\n res.src,\n res.filename,\n specificOptions.isExporting ?? this.instanceMetroOptions.isExporting!\n );\n };\n\n private async metroImportAsArtifactsAsync(\n filePath: string,\n specificOptions: Partial<Omit<ExpoMetroOptions, 'serializerOutput'>> = {}\n ) {\n const results = await this.ssrLoadModuleContents(filePath, {\n serializerOutput: 'static',\n ...specificOptions,\n });\n\n // NOTE: This could potentially need more validation in the future.\n if (results.artifacts && results.assets) {\n return {\n artifacts: results.artifacts,\n assets: results.assets,\n src: results.src,\n filename: results.filename,\n map: results.map,\n };\n }\n throw new CommandError('Invalid bundler results: ' + results);\n }\n\n private async metroLoadModuleContents(\n filePath: string,\n specificOptions: ExpoMetroOptions,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<MetroModuleContentsResult> {\n const { baseUrl } = this.instanceMetroOptions;\n assert(baseUrl != null, 'The server must be started before calling metroLoadModuleContents.');\n\n const opts: ExpoMetroOptions = {\n // TODO: Possibly issues with using an absolute path here...\n // mainModuleName: filePath,\n lazy: false,\n asyncRoutes: false,\n inlineSourceMap: false,\n engine: 'hermes',\n minify: false,\n // bytecode: false,\n // Bundle in Node.js mode for SSR.\n environment: 'node',\n // platform: 'web',\n // mode: 'development',\n //\n ...this.instanceMetroOptions,\n baseUrl,\n // routerRoot,\n // isExporting,\n ...specificOptions,\n };\n\n const expoBundleOptions = getMetroDirectBundleOptions(opts);\n\n const resolverOptions = {\n customResolverOptions: expoBundleOptions.customResolverOptions ?? {},\n dev: expoBundleOptions.dev ?? true,\n };\n\n const transformOptions: TransformInputOptions = {\n dev: expoBundleOptions.dev ?? true,\n minify: expoBundleOptions.minify ?? false,\n type: 'module',\n unstable_transformProfile:\n extraOptions.unstable_transformProfile ??\n expoBundleOptions.unstable_transformProfile ??\n 'default',\n customTransformOptions: expoBundleOptions.customTransformOptions ?? Object.create(null),\n platform: expoBundleOptions.platform ?? 'web',\n };\n\n const resolvedEntryFilePath = await this.resolveRelativePathAsync(filePath, {\n resolverOptions,\n transformOptions,\n });\n\n const filename = createBundleOsPath({\n ...opts,\n mainModuleName: resolvedEntryFilePath,\n });\n\n // https://github.com/facebook/metro/blob/2405f2f6c37a1b641cc379b9c733b1eff0c1c2a1/packages/metro/src/lib/parseOptionsFromUrl.js#L55-L87\n // TODO(@kitten): We've flagged this way of \"direct transpilation\" for replacement, since it's hard to maintain\n // It's possible that the intention here was to do something like what `exportEmbedAsync` is doing (using Server.DEFAULT_BUNDLE_OPTIONS)\n // That's why the defaults were added to match types. It's unclear though if that was correct\n // Maybe the `Server.DEFAULT_BUNDLE_OPTIONS` logic should be hoisted into `getMetroDirectBundleOptions`?\n const results = await this._bundleDirectAsync(resolvedEntryFilePath, {\n graphOptions: {\n lazy: expoBundleOptions.lazy ?? false,\n shallow: expoBundleOptions.shallow ?? false,\n },\n resolverOptions,\n serializerOptions: {\n ...expoBundleOptions.serializerOptions,\n inlineSourceMap: expoBundleOptions.inlineSourceMap ?? false,\n modulesOnly: expoBundleOptions.modulesOnly ?? false,\n runModule: expoBundleOptions.runModule ?? true,\n sourceUrl: expoBundleOptions.sourceUrl!,\n sourceMapUrl: extraOptions.sourceMapUrl ?? expoBundleOptions.sourceMapUrl!,\n },\n transformOptions,\n });\n\n return {\n ...results,\n filename,\n };\n }\n\n private async ssrLoadModuleContents(\n filePath: string,\n specificOptions: Partial<ExpoMetroOptions> = {}\n ): Promise<SSRModuleContentsResult> {\n const { baseUrl, routerRoot, isExporting } = this.instanceMetroOptions;\n assert(\n baseUrl != null && routerRoot != null && isExporting != null,\n 'The server must be started before calling ssrLoadModuleContents.'\n );\n\n const opts: ExpoMetroOptions = {\n // TODO: Possibly issues with using an absolute path here...\n mainModuleName: convertPathToModuleSpecifier(filePath),\n lazy: false,\n asyncRoutes: false,\n inlineSourceMap: false,\n engine: 'hermes',\n minify: false,\n bytecode: false,\n // Bundle in Node.js mode for SSR unless RSC is enabled.\n environment: this.isReactServerComponentsEnabled ? 'react-server' : 'node',\n platform: 'web',\n mode: 'development',\n //\n ...this.instanceMetroOptions,\n\n // Mostly disable compiler in SSR bundles.\n reactCompiler: false,\n baseUrl,\n routerRoot,\n isExporting,\n\n ...specificOptions,\n };\n\n // https://github.com/facebook/metro/blob/2405f2f6c37a1b641cc379b9c733b1eff0c1c2a1/packages/metro/src/lib/parseOptionsFromUrl.js#L55-L87\n const { filename, bundle, map, ...rest } = await this.metroLoadModuleContents(filePath, opts);\n const scriptContents = wrapBundle(bundle);\n\n if (map) {\n debug('Registering SSR source map for:', filename);\n cachedSourceMaps.set(filename, { url: this.projectRoot, map });\n } else {\n debug('No SSR source map found for:', filename);\n }\n\n return {\n ...rest,\n src: scriptContents,\n filename,\n map,\n };\n }\n\n async nativeExportBundleAsync(\n exp: ExpoConfig,\n options: Omit<\n ExpoMetroOptions,\n 'routerRoot' | 'asyncRoutes' | 'isExporting' | 'serializerOutput' | 'environment'\n >,\n files: ExportAssetMap,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<{\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n files?: ExportAssetMap;\n }> {\n if (this.isReactServerComponentsEnabled) {\n return this.singlePageReactServerComponentExportAsync(exp, options, files, extraOptions);\n }\n\n return this.legacySinglePageExportBundleAsync(options, extraOptions);\n }\n\n private async singlePageReactServerComponentExportAsync(\n exp: ExpoConfig,\n options: Omit<\n ExpoMetroOptions,\n 'baseUrl' | 'routerRoot' | 'asyncRoutes' | 'isExporting' | 'serializerOutput' | 'environment'\n >,\n files: ExportAssetMap,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<{\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n files: ExportAssetMap;\n }> {\n const getReactServerReferences = (artifacts: SerialAsset[]): string[] => {\n // Get the React server action boundaries from the client bundle.\n return unique(\n artifacts\n .filter((a) => a.type === 'js')\n .map((artifact) =>\n artifact.metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref))\n )\n // TODO: Segment by module for splitting.\n .flat()\n .filter(Boolean) as string[]\n );\n };\n\n // NOTE(EvanBacon): This will not support any code elimination since it's a static pass.\n let {\n reactClientReferences: clientBoundaries,\n reactServerReferences: serverActionReferencesInServer,\n cssModules,\n } = await this.rscRenderer!.getExpoRouterClientReferencesAsync(\n {\n platform: options.platform,\n domRoot: options.domRoot,\n },\n files\n );\n\n // TODO: The output keys should be in production format or use a lookup manifest.\n\n const processClientBoundaries = async (\n reactServerReferences: string[]\n ): Promise<{\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n }> => {\n debug('Evaluated client boundaries:', clientBoundaries);\n\n // Run metro bundler and create the JS bundles/source maps.\n const bundle = await this.legacySinglePageExportBundleAsync(\n {\n ...options,\n clientBoundaries,\n },\n extraOptions\n );\n\n // Get the React server action boundaries from the client bundle.\n const newReactServerReferences = getReactServerReferences(bundle.artifacts);\n\n if (!newReactServerReferences) {\n // Possible issue with babel plugin / metro-config.\n throw new Error(\n 'Static server action references were not returned from the Metro client bundle'\n );\n }\n debug('React server action boundaries from client:', newReactServerReferences);\n\n const allKnownReactServerReferences = unique([\n ...reactServerReferences,\n ...newReactServerReferences,\n ]);\n\n // When we export the server actions that were imported from the client, we may need to re-bundle the client with the new client boundaries.\n const { clientBoundaries: nestedClientBoundaries } =\n await this.rscRenderer!.exportServerActionsAsync(\n {\n platform: options.platform,\n domRoot: options.domRoot,\n entryPoints: allKnownReactServerReferences,\n },\n files\n );\n\n // TODO: Check against all modules in the initial client bundles.\n const hasUniqueClientBoundaries = nestedClientBoundaries.some(\n (boundary) => !clientBoundaries.includes(boundary)\n );\n\n if (!hasUniqueClientBoundaries) {\n return bundle;\n }\n\n debug('Re-bundling client with nested client boundaries:', nestedClientBoundaries);\n\n clientBoundaries = unique(clientBoundaries.concat(nestedClientBoundaries));\n\n // Re-bundle the client with the new client boundaries that only exist in server actions that were imported from the client.\n // Run metro bundler and create the JS bundles/source maps.\n return processClientBoundaries(allKnownReactServerReferences);\n };\n\n const bundle = await processClientBoundaries(serverActionReferencesInServer);\n\n // Inject the global CSS that was imported during the server render.\n bundle.artifacts.push(...cssModules);\n\n const serverRoot = getMetroServerRoot(this.projectRoot);\n\n // HACK: Maybe this should be done in the serializer.\n const clientBoundariesAsOpaqueIds = clientBoundaries.map((boundary) =>\n // NOTE(cedric): relative module specifiers / IDs should always be POSIX formatted\n toPosixPath(path.relative(serverRoot, boundary))\n );\n const moduleIdToSplitBundle = (\n bundle.artifacts\n .map((artifact) => artifact?.metadata?.paths && Object.values(artifact.metadata.paths))\n .filter(Boolean)\n .flat() as Record<string, string>[]\n ).reduce((acc, paths) => ({ ...acc, ...paths }), {});\n\n debug('SSR Manifest:', moduleIdToSplitBundle, clientBoundariesAsOpaqueIds);\n\n const ssrManifest = new Map<string, string | null>();\n\n if (Object.keys(moduleIdToSplitBundle).length) {\n clientBoundariesAsOpaqueIds.forEach((boundary) => {\n if (boundary in moduleIdToSplitBundle) {\n ssrManifest.set(boundary, moduleIdToSplitBundle[boundary]);\n } else {\n throw new Error(\n `Could not find boundary \"${boundary}\" in the SSR manifest. Available: ${Object.keys(moduleIdToSplitBundle).join(', ')}`\n );\n }\n });\n } else {\n // Native apps with bundle splitting disabled.\n debug('No split bundles');\n clientBoundariesAsOpaqueIds.forEach((boundary) => {\n ssrManifest.set(boundary, null);\n });\n }\n\n const routerOptions = exp.extra?.router;\n\n // Export the static RSC files\n await this.rscRenderer!.exportRoutesAsync(\n {\n platform: options.platform,\n ssrManifest,\n routerOptions,\n },\n files\n );\n\n // Save the SSR manifest so we can perform more replacements in the server renderer and with server actions.\n files.set(`_expo/rsc/${options.platform}/ssr-manifest.js`, {\n targetDomain: 'server',\n contents:\n 'module.exports = ' +\n JSON.stringify(\n // TODO: Add a less leaky version of this across the framework with just [key, value] (module ID, chunk).\n Object.fromEntries(\n Array.from(ssrManifest.entries()).map(([key, value]) => [\n // Must match babel plugin.\n './' + toPosixPath(path.relative(this.projectRoot, path.join(serverRoot, key))),\n [key, value],\n ])\n )\n ),\n });\n\n return { ...bundle, files };\n }\n\n async legacySinglePageExportBundleAsync(\n options: Omit<\n ExpoMetroOptions,\n 'routerRoot' | 'asyncRoutes' | 'isExporting' | 'serializerOutput' | 'environment' | 'hosted'\n >,\n extraOptions: {\n sourceMapUrl?: string;\n unstable_transformProfile?: TransformProfile;\n } = {}\n ): Promise<{ artifacts: SerialAsset[]; assets: readonly BundleAssetWithFileHashes[] }> {\n const { baseUrl, routerRoot, isExporting } = this.instanceMetroOptions;\n assert(options.mainModuleName != null, 'mainModuleName must be provided in options.');\n assert(\n baseUrl != null && routerRoot != null && isExporting != null,\n 'The server must be started before calling legacySinglePageExportBundleAsync.'\n );\n\n const opts: ExpoMetroOptions = {\n ...this.instanceMetroOptions,\n baseUrl,\n routerRoot,\n isExporting,\n ...options,\n environment: 'client',\n serializerOutput: 'static',\n };\n\n // https://github.com/facebook/metro/blob/2405f2f6c37a1b641cc379b9c733b1eff0c1c2a1/packages/metro/src/lib/parseOptionsFromUrl.js#L55-L87\n if (!opts.mainModuleName.startsWith('/') && !path.isAbsolute(opts.mainModuleName)) {\n opts.mainModuleName = './' + opts.mainModuleName;\n }\n\n const output = await this.metroLoadModuleContents(opts.mainModuleName, opts, extraOptions);\n\n return {\n artifacts: output.artifacts!,\n assets: output.assets!,\n };\n }\n\n async watchEnvironmentVariables() {\n if (!this.instance) {\n throw new Error(\n 'Cannot observe environment variable changes without a running Metro instance.'\n );\n }\n if (!this.metro) {\n // This can happen when the run command is used and the server is already running in another\n // process.\n debug('Skipping Environment Variable observation because Metro is not running (headless).');\n return;\n }\n\n const envFiles = runtimeEnv\n .getFiles(process.env.NODE_ENV)\n .map((fileName) => path.join(this.projectRoot, fileName));\n\n observeFileChanges(\n {\n metro: this.metro,\n server: this.instance.server,\n },\n envFiles,\n () => {\n debug('Reloading environment variables...');\n // Force reload the environment variables.\n runtimeEnv.load(this.projectRoot, { force: true });\n }\n );\n }\n\n rscRenderer: Awaited<ReturnType<typeof createServerComponentsMiddleware>> | null = null;\n\n protected async startImplementationAsync(\n options: BundlerStartOptions\n ): Promise<DevServerInstance> {\n options.port = await this.resolvePortAsync(options);\n this.urlCreator = this.getUrlCreator(options);\n\n const config = getConfig(this.projectRoot, { skipSDKVersionRequirement: true });\n const { exp } = config;\n // NOTE: This will change in the future when it's less experimental, we enable React 19, and turn on more RSC flags by default.\n const isReactServerComponentsEnabled =\n !!exp.experiments?.reactServerComponentRoutes || !!exp.experiments?.reactServerFunctions;\n const isReactServerActionsOnlyEnabled =\n !exp.experiments?.reactServerComponentRoutes && !!exp.experiments?.reactServerFunctions;\n this.isReactServerComponentsEnabled = isReactServerComponentsEnabled;\n this.isReactServerRoutesEnabled = !!exp.experiments?.reactServerComponentRoutes;\n\n const useServerRendering = ['static', 'server'].includes(exp.web?.output ?? '');\n const hasApiRoutes = isReactServerComponentsEnabled || exp.web?.output === 'server';\n const baseUrl = getBaseUrlFromExpoConfig(exp);\n const asyncRoutes = getAsyncRoutesFromExpoConfig(exp, options.mode ?? 'development', 'web');\n const routerRoot = getRouterDirectoryModuleIdWithManifest(this.projectRoot, exp);\n const reactCompiler = !!exp.experiments?.reactCompiler;\n const appDir = path.join(this.projectRoot, routerRoot);\n const mode = options.mode ?? 'development';\n\n const routerOptions = exp.extra?.router;\n\n if (isReactServerComponentsEnabled && exp.web?.output === 'static') {\n throw new CommandError(\n `Experimental server component support does not support 'web.output: ${exp.web!.output}' yet. Use 'web.output: \"server\"' during the experimental phase.`\n );\n }\n\n // Error early about the window.location polyfill when React Server Components are enabled.\n if (isReactServerComponentsEnabled && exp?.extra?.router?.origin === false) {\n const configPath = config.dynamicConfigPath ?? config.staticConfigPath ?? '/app.json';\n const configFileName = path.basename(configPath);\n throw new CommandError(\n `The Expo Router \"origin\" property in the Expo config (${configFileName}) cannot be \"false\" when React Server Components is enabled. Remove it from the ${configFileName} file and try again.`\n );\n }\n\n const instanceMetroOptions = {\n isExporting: !!options.isExporting,\n baseUrl,\n mode,\n routerRoot,\n reactCompiler,\n minify: options.minify,\n asyncRoutes,\n // Options that are changing between platforms like engine, platform, and environment aren't set here.\n };\n this.instanceMetroOptions = instanceMetroOptions;\n\n const parsedOptions = {\n port: options.port,\n maxWorkers: options.maxWorkers,\n resetCache: options.resetDevServer,\n };\n\n // Required for symbolication:\n process.env.EXPO_DEV_SERVER_ORIGIN = `http://localhost:${options.port}`;\n\n const { metro, hmrServer, server, middleware, messageSocket } = await instantiateMetroAsync(\n this,\n parsedOptions,\n {\n isExporting: !!options.isExporting,\n exp,\n }\n );\n\n if (!options.isExporting) {\n const manifestMiddleware = await this.getManifestMiddlewareAsync(options);\n\n // Important that we noop source maps for context modules as soon as possible.\n prependMiddleware(middleware, new ContextModuleSourceMapsMiddleware().getHandler());\n\n // We need the manifest handler to be the first middleware to run so our\n // routes take precedence over static files. For example, the manifest is\n // served from '/' and if the user has an index.html file in their project\n // then the manifest handler will never run, the static middleware will run\n // and serve index.html instead of the manifest.\n // https://github.com/expo/expo/issues/13114\n prependMiddleware(middleware, manifestMiddleware.getHandler());\n\n middleware.use(\n new InterstitialPageMiddleware(this.projectRoot, {\n // TODO: Prevent this from becoming stale.\n scheme: options.location.scheme ?? null,\n }).getHandler()\n );\n middleware.use(\n new DevToolsPluginMiddleware(this.projectRoot, this.devToolsPluginManager).getHandler()\n );\n\n const deepLinkMiddleware = new RuntimeRedirectMiddleware(this.projectRoot, {\n getLocation: ({ runtime }) => {\n if (runtime === 'custom') {\n return this.urlCreator?.constructDevClientUrl();\n } else {\n return this.urlCreator?.constructUrl({\n scheme: 'exp',\n });\n }\n },\n });\n middleware.use(deepLinkMiddleware.getHandler());\n\n const serverRoot = getMetroServerRoot(this.projectRoot);\n\n const domComponentRenderer = createDomComponentsMiddleware(\n {\n metroRoot: serverRoot,\n projectRoot: this.projectRoot,\n },\n instanceMetroOptions\n );\n // Add support for DOM components.\n // TODO: Maybe put behind a flag for now?\n middleware.use(domComponentRenderer);\n\n // TODO: Disable both of these when tunneling to prevent security issues\n middleware.use(new CreateFileMiddleware(this.projectRoot).getHandler());\n\n // For providing info to the error overlay.\n middleware.use((req: ServerRequest, res: ServerResponse, next: ServerNext) => {\n // Use by `@expo/log-box` https://github.com/expo/expo/blob/f29b9f3715e42dca87bf3eebf11f7e7dd1ff73c1/packages/%40expo/log-box/src/utils/devServerEndpoints.ts#L82\n if (req.url?.startsWith('/_expo/error-overlay-meta')) {\n res.statusCode = 200;\n res.setHeader('Content-Type', 'application/json');\n res.end(\n JSON.stringify({\n projectRoot: this.projectRoot,\n serverRoot,\n sdkVersion: exp.sdkVersion,\n })\n );\n return;\n }\n return next();\n });\n\n // Append support for redirecting unhandled requests to the index.html page on web.\n if (this.isTargetingWeb()) {\n if (exp.extra?.router?.unstable_useServerDataLoaders) {\n const loaderModuleMiddleware = new DataLoaderModuleMiddleware(\n this.projectRoot,\n appDir,\n async (location: URL, route: RouteInfo<RegExp>) => {\n const resolvedLoaderRoute = fromServerManifestRoute(location.pathname, route);\n if (!resolvedLoaderRoute) {\n return;\n }\n return this.executeServerDataLoaderAsync(location, resolvedLoaderRoute);\n },\n () => this.getDevServerUrlOrAssert()\n );\n // This MUST be before ServeStaticMiddleware so it doesn't treat the loader files as static assets\n middleware.use(loaderModuleMiddleware.getHandler());\n }\n\n // This MUST be after the manifest middleware so it doesn't have a chance to serve the template `public/index.html`.\n middleware.use(new ServeStaticMiddleware(this.projectRoot).getHandler());\n\n // This should come after the static middleware so it doesn't serve the favicon from `public/favicon.ico`.\n middleware.use(new FaviconMiddleware(this.projectRoot).getHandler());\n }\n\n if (useServerRendering || isReactServerComponentsEnabled) {\n observeAnyFileChanges(\n {\n metro,\n server,\n },\n (events) => {\n if (hasApiRoutes) {\n // NOTE(EvanBacon): We aren't sure what files the API routes are using so we'll just invalidate\n // aggressively to ensure we always have the latest. The only caching we really get here is for\n // cases where the user is making subsequent requests to the same API route without changing anything.\n // This is useful for testing but pretty suboptimal. Luckily our caching is pretty aggressive so it makes\n // up for a lot of the overhead.\n this.invalidateApiRouteCache();\n } else if (!hasWarnedAboutApiRoutes()) {\n for (const event of events) {\n if (\n // If the user did not delete a file that matches the Expo Router API Route convention, then we should warn that\n // API Routes are not enabled in the project.\n event.metadata?.type !== 'd' &&\n // Ensure the file is in the project's routes directory to prevent false positives in monorepos.\n event.filePath.startsWith(appDir) &&\n isApiRouteConvention(event.filePath)\n ) {\n warnInvalidWebOutput();\n }\n }\n }\n\n // Handle loader file changes for HMR\n if (exp.extra?.router?.unstable_useServerDataLoaders) {\n for (const event of events) {\n if (event.metadata?.type !== 'd') {\n this.handleLoaderFileChange(event.filePath);\n }\n }\n }\n }\n );\n }\n\n // If React 19 is enabled, then add RSC middleware to the dev server.\n if (isReactServerComponentsEnabled) {\n this.bindRSCDevModuleInjectionHandler();\n const rscMiddleware = createServerComponentsMiddleware(this.projectRoot, {\n instanceMetroOptions: this.instanceMetroOptions,\n rscPath: '/_flight',\n ssrLoadModule: this.ssrLoadModule.bind(this),\n ssrLoadModuleArtifacts: this.metroImportAsArtifactsAsync.bind(this),\n useClientRouter: isReactServerActionsOnlyEnabled,\n createModuleId: metro._createModuleId.bind(metro),\n routerOptions,\n });\n this.rscRenderer = rscMiddleware;\n middleware.use(rscMiddleware.middleware);\n this.onReloadRscEvent = rscMiddleware.onReloadRscEvent;\n }\n\n // Append support for redirecting unhandled requests to the index.html page on web.\n if (this.isTargetingWeb()) {\n if (!useServerRendering) {\n // This MUST run last since it's the fallback.\n middleware.use(\n new HistoryFallbackMiddleware(manifestMiddleware.getHandler().internal).getHandler()\n );\n } else {\n middleware.use(\n createRouteHandlerMiddleware(this.projectRoot, {\n appDir,\n routerRoot,\n config,\n ...config.exp.extra?.router,\n bundleApiRoute: (functionFilePath) =>\n this.ssrImportApiRoute(functionFilePath, { platform: 'web' }),\n getStaticPageAsync: async (pathname, route) => {\n // TODO: Add server rendering when RSC is enabled.\n if (isReactServerComponentsEnabled) {\n // NOTE: This is a temporary hack to return the SPA/template index.html in development when RSC is enabled.\n // While this technically works, it doesn't provide the correct experience of server rendering the React code to HTML first.\n const html = await manifestMiddleware.getSingleHtmlTemplateAsync();\n return { content: html };\n }\n\n // Non-RSC apps will bundle the static HTML for a given pathname and respond with it.\n return this.getStaticPageAsync(pathname, route);\n },\n })\n );\n }\n }\n } else {\n // If React 19 is enabled, then add RSC middleware to the dev server.\n if (isReactServerComponentsEnabled) {\n this.bindRSCDevModuleInjectionHandler();\n const rscMiddleware = createServerComponentsMiddleware(this.projectRoot, {\n instanceMetroOptions: this.instanceMetroOptions,\n rscPath: '/_flight',\n ssrLoadModule: this.ssrLoadModule.bind(this),\n ssrLoadModuleArtifacts: this.metroImportAsArtifactsAsync.bind(this),\n useClientRouter: isReactServerActionsOnlyEnabled,\n createModuleId: metro._createModuleId.bind(metro),\n routerOptions,\n });\n this.rscRenderer = rscMiddleware;\n }\n }\n // Extend the close method to ensure that we clean up the local info.\n const originalClose = server.close.bind(server);\n\n server.close = (callback?: (err?: Error) => void) => {\n return originalClose((err?: Error) => {\n this.instance = null;\n this.metro = null;\n this.hmrServer = null;\n this.ssrHmrClients = new Map();\n callback?.(err);\n });\n };\n\n this.metro = metro;\n this.hmrServer = hmrServer;\n return {\n server,\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 };\n }\n\n private onReloadRscEvent: ((platform: string) => void) | null = null;\n\n private async registerSsrHmrAsync(url: string, onReload: (platform: string[]) => void) {\n if (!this.hmrServer || this.ssrHmrClients.has(url)) {\n return;\n }\n\n debug('[SSR] Register HMR:', url);\n\n const sendFn = (message: string) => {\n const data = JSON.parse(String(message)) as { type: string; body: any };\n\n switch (data.type) {\n case 'bundle-registered':\n case 'update-done':\n case 'update-start':\n break;\n case 'update':\n {\n const update = data.body;\n const {\n isInitialUpdate,\n added,\n modified,\n deleted,\n }: {\n isInitialUpdate?: boolean;\n added: {\n module: [number | string, string];\n sourceURL: string;\n sourceMappingURL: string;\n }[];\n modified: {\n module: [number | string, string];\n sourceURL: string;\n sourceMappingURL: string;\n }[];\n deleted: (number | string)[];\n } = update;\n\n const hasUpdate = added.length || modified.length || deleted.length;\n\n // NOTE: We throw away the updates and instead simply send a trigger to the client to re-fetch the server route.\n if (!isInitialUpdate && hasUpdate) {\n // Clear all SSR modules before sending the reload event. This ensures that the next event will rebuild the in-memory state from scratch.\n if (typeof globalThis.__c === 'function') globalThis.__c();\n\n const allModuleIds = new Set(\n [...added, ...modified].map((m) => m.module[0]).concat(deleted)\n );\n\n const platforms = unique(\n Array.from(allModuleIds)\n .map((moduleId) => {\n if (typeof moduleId !== 'string') {\n return null;\n }\n // Extract platforms from the module IDs.\n return moduleId.match(/[?&]platform=([\\w]+)/)?.[1] ?? null;\n })\n .filter(Boolean)\n ) as string[];\n\n onReload(platforms);\n }\n }\n break;\n case 'error':\n // GraphNotFound can mean that we have an issue in metroOptions where the URL doesn't match the object props.\n Log.error('[SSR] HMR Error: ' + JSON.stringify(data, null, 2));\n\n if (data.body?.type === 'GraphNotFoundError') {\n Log.error(\n 'Available SSR HMR keys:',\n `${this.metro?._bundler._revisionsByGraphId.keys()}`\n );\n }\n break;\n default:\n debug('Unknown HMR message:', data);\n break;\n }\n };\n\n const client = await this.hmrServer!.onClientConnect(url, sendFn);\n this.ssrHmrClients.set(url, client);\n // Opt in...\n client.optedIntoHMR = true;\n await this.hmrServer!._registerEntryPoint(client, url, sendFn);\n }\n\n public async waitForTypeScriptAsync(): Promise<boolean> {\n if (!this.instance) {\n throw new Error('Cannot wait for TypeScript without a running server.');\n }\n\n return new Promise<boolean>((resolve) => {\n if (!this.metro) {\n // This can happen when the run command is used and the server is already running in another\n // process. In this case we can't wait for the TypeScript check to complete because we don't\n // have access to the Metro server.\n debug('Skipping TypeScript check because Metro is not running (headless).');\n return resolve(false);\n }\n\n const off = metroWatchTypeScriptFiles({\n projectRoot: this.projectRoot,\n server: this.instance!.server,\n metro: this.metro,\n tsconfig: true,\n throttle: true,\n eventTypes: ['change', 'add'],\n callback: async () => {\n // Run once, this prevents the TypeScript project prerequisite from running on every file change.\n off();\n const { TypeScriptProjectPrerequisite } = await import(\n '../../doctor/typescript/TypeScriptProjectPrerequisite.js'\n );\n\n try {\n const req = new TypeScriptProjectPrerequisite(this.projectRoot);\n await req.bootstrapAsync();\n resolve(true);\n } catch (error: any) {\n // Ensure the process doesn't fail if the TypeScript check fails.\n // This could happen during the install.\n Log.log();\n Log.error(\n chalk.red`Failed to automatically setup TypeScript for your project. Try restarting the dev server to fix.`\n );\n Log.exception(error);\n resolve(false);\n }\n },\n });\n });\n }\n\n public async startTypeScriptServices() {\n return startTypescriptTypeGenerationAsync({\n server: this.instance?.server,\n metro: this.metro,\n projectRoot: this.projectRoot,\n });\n }\n\n protected getConfigModuleIds(): string[] {\n return ['./metro.config.js', './metro.config.json', './rn-cli.config.js'];\n }\n\n // API Routes\n\n private pendingRouteOperations = new Map<string, Promise<SSRModuleContentsResult | null>>();\n\n // Bundle the API Route with Metro and return the string contents to be evaluated in the server.\n private async bundleApiRoute(\n filePath: string,\n { platform }: { platform: string }\n ): Promise<SSRModuleContentsResult | null | undefined> {\n if (this.pendingRouteOperations.has(filePath)) {\n return this.pendingRouteOperations.get(filePath);\n }\n const bundleAsync = async (): Promise<SSRModuleContentsResult> => {\n try {\n debug('Bundle API route:', this.instanceMetroOptions.routerRoot, filePath);\n return await this.ssrLoadModuleContents(filePath, {\n isExporting: this.instanceMetroOptions.isExporting,\n platform,\n });\n } catch (error: any) {\n const appDir = this.instanceMetroOptions?.routerRoot\n ? path.join(this.projectRoot, this.instanceMetroOptions!.routerRoot!)\n : undefined;\n const relativePath = appDir ? path.relative(appDir, filePath) : filePath;\n\n // Expected errors: invalid syntax, missing resolutions.\n // Wrap with command error for better error messages.\n const err = new CommandError(\n 'API_ROUTE',\n chalk`Failed to bundle API Route: {bold ${relativePath}}\\n\\n` + error.message\n );\n\n for (const key in error) {\n err[key] = error[key];\n }\n\n throw err;\n } finally {\n // pendingRouteOperations.delete(filepath);\n }\n };\n const route = bundleAsync();\n\n this.pendingRouteOperations.set(filePath, route);\n return route;\n }\n\n private async ssrImportApiRoute(\n filePath: string,\n { platform }: { platform: string }\n ): Promise<null | Record<string, Function> | Response> {\n // TODO: Cache the evaluated function.\n try {\n const apiRoute = await this.bundleApiRoute(filePath, { platform });\n\n if (!apiRoute?.src) {\n return null;\n }\n return evalMetroNoHandling(this.projectRoot, apiRoute.src, apiRoute.filename);\n } catch (error) {\n // Format any errors that were thrown in the global scope of the evaluation.\n if (error instanceof Error) {\n try {\n const htmlServerError = await getErrorOverlayHtmlAsync({\n error,\n projectRoot: this.projectRoot,\n routerRoot: this.instanceMetroOptions.routerRoot!,\n });\n\n return new Response(htmlServerError, {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n } catch (internalError) {\n debug('Failed to generate Metro server error UI for API Route error:', internalError);\n throw error;\n }\n } else {\n throw error;\n }\n }\n }\n\n private invalidateApiRouteCache() {\n this.pendingRouteOperations.clear();\n }\n\n /**\n * Execute a route's loader function. Used during SSR/SSG to fetch data required by routes.\n *\n * This function is used during development and production builds, and **must** receive a valid\n * matched route.\n *\n * @experimental\n */\n async executeServerDataLoaderAsync(\n location: URL,\n route: ResolvedLoaderRoute\n ): Promise<Record<string, any> | undefined> {\n const { exp } = getConfig(this.projectRoot);\n const { unstable_useServerDataLoaders } = exp.extra?.router;\n\n if (!unstable_useServerDataLoaders) {\n throw new CommandError(\n 'LOADERS_NOT_ENABLED',\n 'Server data loaders are not enabled. Add `unstable_useServerDataLoaders` to your `expo-router` plugin config.'\n );\n }\n\n const { routerRoot } = this.instanceMetroOptions;\n assert(\n routerRoot != null,\n 'The server must be started before calling executeRouteLoaderAsync.'\n );\n let loaderData: Record<string, any> | undefined;\n\n try {\n debug(`Matched ${location.pathname} to file: ${route.file}`);\n\n const appDir = path.join(this.projectRoot, routerRoot);\n let modulePath = route.file;\n modulePath = path.isAbsolute(modulePath) ? modulePath : path.join(appDir, modulePath);\n modulePath = modulePath.replace(/\\.(js|ts)x?$/, '');\n\n debug('Using loader module path: ', modulePath);\n\n const routeModule = await this.ssrLoadModule<any>(modulePath, {\n environment: 'node',\n });\n\n if (routeModule.loader) {\n // Register this module for loader HMR\n this.setupLoaderHmr(modulePath);\n\n loaderData = await routeModule.loader({\n params: route.params,\n // NOTE(@hassankhan): The `request` object should only be available when using SSR\n request: null,\n });\n }\n } catch (error: any) {\n throw new CommandError(\n 'LOADER_EXECUTION_FAILED',\n `Failed to execute loader for route \"${location.pathname}\": ${error.message}`\n );\n }\n\n debug('Loader data:', loaderData, ' for location:', location.pathname);\n return loaderData;\n }\n\n // Ensure the global is available for SSR CSS modules to inject client updates.\n private bindRSCDevModuleInjectionHandler() {\n // Used by SSR CSS modules to broadcast client updates.\n globalThis.__expo_rsc_inject_module = this.sendClientModule.bind(this);\n }\n\n // NOTE: This can only target a single platform at a time (web).\n // used for sending RSC CSS to the root client in development.\n private sendClientModule({ code, id }: { code: string; id: string }) {\n this.broadcastMessage('sendDevCommand', {\n name: 'module-import',\n data: {\n code,\n id,\n },\n });\n }\n\n // Metro HMR\n\n private setupHmr(url: URL) {\n const onReload = (platforms: string[] = []) => {\n // Send reload command to client from Fast Refresh code.\n\n if (!platforms.length) {\n // TODO: When is this called?\n this.broadcastMessage('sendDevCommand', {\n name: 'rsc-reload',\n });\n } else {\n for (const platform of platforms) {\n this.onReloadRscEvent?.(platform);\n this.broadcastMessage('sendDevCommand', {\n name: 'rsc-reload',\n platform,\n });\n }\n }\n };\n\n this.registerSsrHmrAsync(url.toString(), onReload);\n }\n\n private watchedLoaderFiles: Set<string> = new Set();\n\n private setupLoaderHmr(modulePath: string) {\n if (this.watchedLoaderFiles.has(modulePath)) {\n return;\n }\n this.watchedLoaderFiles.add(modulePath);\n\n debug('[Loader HMR] Registering loader file for HMR:', modulePath);\n }\n\n private handleLoaderFileChange(changedFilePath: string) {\n for (const loaderPath of this.watchedLoaderFiles) {\n const possibleExtensions = ['.tsx', '.ts', '.jsx', '.js'];\n const isLoaderFile = possibleExtensions.some(\n (ext) => changedFilePath === loaderPath + ext || changedFilePath === loaderPath\n );\n\n if (isLoaderFile) {\n debug('[Loader HMR] Loader file changed, triggering reload:', changedFilePath);\n this.broadcastMessage('sendDevCommand', {\n name: 'reload',\n });\n }\n }\n }\n\n // Direct Metro access\n\n // Emulates the Metro dev server .bundle endpoint without having to go through a server.\n private async _bundleDirectAsync(\n resolvedEntryFilePath: string,\n {\n transformOptions,\n resolverOptions,\n graphOptions,\n serializerOptions,\n }: {\n transformOptions: TransformInputOptions;\n resolverOptions: {\n customResolverOptions: CustomResolverOptions;\n dev: boolean;\n };\n serializerOptions: {\n output?: 'string' | ({} & string);\n modulesOnly: boolean;\n runModule: boolean;\n sourceMapUrl: string;\n sourceUrl: string;\n inlineSourceMap: boolean;\n excludeSource: boolean;\n };\n graphOptions: {\n shallow: boolean;\n lazy: boolean;\n };\n }\n ): Promise<BundleDirectResult> {\n assert(this.metro, 'Metro server must be running to bundle directly.');\n const config = this.metro._config;\n const buildNumber = this.metro.getNewBuildNumber();\n const bundlePerfLogger = config.unstable_perfLoggerFactory?.('BUNDLING_REQUEST', {\n key: buildNumber,\n });\n\n const onProgress = (transformedFileCount: number, totalFileCount: number) => {\n this.metro?._reporter?.update?.({\n buildID: getBuildID(buildNumber),\n type: 'bundle_transform_progressed',\n transformedFileCount,\n totalFileCount,\n });\n };\n\n const revPromise = this.getMetroRevision(resolvedEntryFilePath, {\n graphOptions,\n transformOptions,\n resolverOptions,\n });\n\n bundlePerfLogger?.point('resolvingAndTransformingDependencies_start');\n bundlePerfLogger?.annotate({\n bool: {\n initial_build: revPromise == null,\n },\n });\n this.metro?._reporter.update({\n buildID: getBuildID(buildNumber),\n bundleDetails: {\n bundleType: transformOptions.type,\n dev: transformOptions.dev,\n entryFile: resolvedEntryFilePath,\n minify: transformOptions.minify,\n platform: transformOptions.platform,\n customResolverOptions: resolverOptions.customResolverOptions,\n customTransformOptions: transformOptions.customTransformOptions ?? {},\n },\n isPrefetch: false,\n type: 'bundle_build_started',\n });\n\n try {\n let delta: DeltaResult;\n let revision: GraphRevision;\n\n try {\n // TODO: Some bug in Metro/RSC causes this to break when changing imports in server components.\n // We should resolve the bug because it results in ~6x faster bundling to reuse the graph revision.\n if (transformOptions.customTransformOptions?.environment === 'react-server') {\n const props = await this.metro.getBundler().initializeGraph(\n // NOTE: Using absolute path instead of relative input path is a breaking change.\n // entryFile,\n resolvedEntryFilePath,\n\n transformOptions,\n resolverOptions,\n {\n onProgress,\n shallow: graphOptions.shallow,\n lazy: graphOptions.lazy,\n }\n );\n delta = props.delta;\n revision = props.revision;\n } else {\n const props = await (revPromise != null\n ? this.metro.getBundler().updateGraph(await revPromise, false)\n : this.metro.getBundler().initializeGraph(\n // NOTE: Using absolute path instead of relative input path is a breaking change.\n // entryFile,\n resolvedEntryFilePath,\n\n transformOptions,\n resolverOptions,\n {\n onProgress,\n shallow: graphOptions.shallow,\n lazy: graphOptions.lazy,\n }\n ));\n delta = props.delta;\n revision = props.revision;\n }\n } catch (error) {\n attachImportStackToRootMessage(error);\n dropStackIfContainsCodeFrame(error);\n throw error;\n }\n\n bundlePerfLogger?.annotate({\n int: {\n graph_node_count: revision.graph.dependencies.size,\n },\n });\n bundlePerfLogger?.point('resolvingAndTransformingDependencies_end');\n bundlePerfLogger?.point('serializingBundle_start');\n\n const shouldAddToIgnoreList = this.metro._shouldAddModuleToIgnoreList.bind(this.metro);\n\n const serializer = this.getMetroSerializer();\n\n const options = {\n asyncRequireModulePath: await this.metro._resolveRelativePath(\n config.transformer.asyncRequireModulePath,\n {\n relativeTo: 'project',\n resolverOptions,\n transformOptions,\n }\n ),\n // ...serializerOptions,\n processModuleFilter: config.serializer.processModuleFilter,\n createModuleId: this.metro._createModuleId,\n getRunModuleStatement: config.serializer.getRunModuleStatement,\n globalPrefix: config.transformer.globalPrefix,\n includeAsyncPaths: graphOptions.lazy,\n dev: transformOptions.dev,\n projectRoot: config.projectRoot,\n modulesOnly: serializerOptions.modulesOnly,\n runBeforeMainModule: config.serializer.getModulesRunBeforeMainModule(\n resolvedEntryFilePath\n // path.relative(config.projectRoot, entryFile)\n ),\n runModule: serializerOptions.runModule,\n sourceMapUrl: serializerOptions.sourceMapUrl,\n sourceUrl: serializerOptions.sourceUrl,\n inlineSourceMap: serializerOptions.inlineSourceMap,\n serverRoot: config.server.unstable_serverRoot ?? config.projectRoot,\n shouldAddToIgnoreList,\n\n // TODO(@kitten): This is incoherently typed. The target should be typed to accept this coherently\n // but we have no type overrides or a proper type chain for this\n serializerOptions,\n };\n\n // TODO(@kitten): Yearns for a refactor. The typings here were and are questionable\n const bundle = await serializer(\n // NOTE: Using absolute path instead of relative input path is a breaking change.\n // entryFile,\n resolvedEntryFilePath,\n revision.prepend,\n revision.graph,\n options\n );\n\n this.metro._reporter.update({\n buildID: getBuildID(buildNumber),\n type: 'bundle_build_done',\n });\n\n bundlePerfLogger?.point('serializingBundle_end');\n\n let bundleCode: string | null = null;\n let bundleMap: string | null = null;\n\n if (serializerOptions.output === 'static') {\n try {\n const parsed = typeof bundle === 'string' ? JSON.parse(bundle) : bundle;\n\n assert(\n 'artifacts' in parsed && Array.isArray(parsed.artifacts),\n 'Expected serializer to return an object with key artifacts to contain an array of serial assets.'\n );\n\n const artifacts = parsed.artifacts as SerialAsset[];\n const assets = parsed.assets;\n\n const bundleCode = artifacts.filter((asset) => asset.type === 'js')[0];\n const bundleMap = artifacts.filter((asset) => asset.type === 'map')?.[0]?.source ?? '';\n\n return {\n numModifiedFiles: delta.reset\n ? delta.added.size + revision.prepend.length\n : delta.added.size + delta.modified.size + delta.deleted.size,\n lastModifiedDate: revision.date,\n nextRevId: revision.id,\n bundle: bundleCode.source,\n map: bundleMap,\n artifacts,\n assets,\n };\n } catch (error: any) {\n throw new Error(\n 'Serializer did not return expected format. The project copy of `expo/metro-config` may be out of date. Error: ' +\n error.message\n );\n }\n }\n\n if (typeof bundle === 'string') {\n bundleCode = bundle;\n\n // Create the source map in a second pass...\n let { prepend, graph } = revision;\n if (serializerOptions.modulesOnly) {\n prepend = [];\n }\n\n bundleMap = await sourceMapStringAsync(\n [\n //\n ...prepend,\n ...this.metro._getSortedModules(graph),\n ],\n {\n excludeSource: serializerOptions.excludeSource,\n processModuleFilter: config.serializer.processModuleFilter,\n shouldAddToIgnoreList,\n }\n );\n } else {\n bundleCode = bundle.code;\n bundleMap = bundle.map;\n }\n\n return {\n numModifiedFiles: delta.reset\n ? delta.added.size + revision.prepend.length\n : delta.added.size + delta.modified.size + delta.deleted.size,\n lastModifiedDate: revision.date,\n nextRevId: revision.id,\n bundle: bundleCode,\n map: bundleMap,\n };\n } catch (error: any) {\n // Mark the error so we know how to format and return it later.\n if (error) {\n error[IS_METRO_BUNDLE_ERROR_SYMBOL] = true;\n }\n\n this.metro._reporter.update({\n buildID: getBuildID(buildNumber),\n type: 'bundle_build_failed',\n });\n\n throw error;\n }\n }\n\n private getMetroSerializer() {\n return (\n this.metro?._config?.serializer.customSerializer ||\n ((entryPoint, preModules, graph, options) =>\n bundleToString(baseJSBundle(entryPoint, preModules, graph, options)).code)\n );\n }\n\n private getMetroRevision(\n resolvedEntryFilePath: string,\n {\n graphOptions,\n transformOptions,\n resolverOptions,\n }: {\n transformOptions: TransformInputOptions;\n resolverOptions: {\n customResolverOptions: CustomResolverOptions;\n dev: boolean;\n };\n graphOptions: {\n shallow: boolean;\n lazy: boolean;\n };\n }\n ) {\n assert(this.metro, 'Metro server must be running to bundle directly.');\n const config = this.metro._config;\n\n const graphId = getGraphId(resolvedEntryFilePath, transformOptions, {\n unstable_allowRequireContext: config.transformer.unstable_allowRequireContext,\n resolverOptions,\n shallow: graphOptions.shallow,\n lazy: graphOptions.lazy,\n });\n return this.metro.getBundler().getRevisionByGraphId(graphId);\n }\n\n private async resolveRelativePathAsync(\n moduleId: string,\n {\n resolverOptions,\n transformOptions,\n }: {\n transformOptions: TransformInputOptions;\n resolverOptions: {\n customResolverOptions: CustomResolverOptions;\n dev: boolean;\n };\n }\n ) {\n assert(this.metro, 'cannot invoke resolveRelativePathAsync without metro instance');\n return await this.metro._resolveRelativePath(convertPathToModuleSpecifier(moduleId), {\n relativeTo: 'server',\n resolverOptions,\n transformOptions,\n });\n }\n}\n\nfunction getBuildID(buildNumber: number): string {\n return buildNumber.toString(36);\n}\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\nasync function sourceMapStringAsync(\n modules: readonly Module[],\n options: SourceMapGeneratorOptions\n): Promise<string> {\n return (await sourceMapGeneratorNonBlocking(modules, options)).toString(undefined, {\n excludeSource: options.excludeSource,\n });\n}\n\nfunction unique<T>(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n"],"names":["MetroBundlerDevServer","debug","require","EXPO_GO_METRO_PORT","DEV_CLIENT_METRO_PORT","BundlerDevServer","name","resolvePortAsync","options","port","devClient","Number","process","env","RCT_METRO_PORT","getFreePortAsync","exportServerRouteAsync","contents","artifactFilename","files","includeSourceMaps","descriptor","src","map","artifactBasename","encodeURIComponent","path","basename","replace","parsedMap","JSON","parse","mapData","stringify","version","sources","source","startsWith","projectRoot","relative","convertPathToModuleSpecifier","sourcesContent","Array","length","fill","names","mappings","targetDomain","set","fileData","exportMiddlewareAsync","manifest","appDir","outputDir","platform","middleware","middlewareFilePath","isAbsolute","file","join","bundleApiRoute","middlewareId","exportExpoRouterApiRoutesAsync","prerenderManifest","routerRoot","instanceMetroOptions","assert","getExpoRouterRoutesManifestAsync","Map","rscPath","isReactServerComponentsEnabled","apiRoutes","find","route","page","push","resolve","namedRegex","routeKeys","rsc","filepath","apiRouteId","htmlRoutes","exp","getConfig","fetchManifest","extra","router","preserveRedirectAndRewrites","asJson","CommandError","getServerManifestAsync","getBuildTimeServerManifestAsync","getManifest","ssrLoadModule","environment","isReactServerRoutesEnabled","serverManifest","htmlManifest","getStaticRenderFunctionAsync","url","getDevServerUrlOrAssert","getStaticContent","preserveApiRoutes","renderAsync","opts","location","URL","executeLoaderAsync","resolvedLoaderRoute","fromRuntimeManifestRoute","pathname","inflateManifest","undefined","executeServerDataLoaderAsync","getStaticResourcesAsync","mainModuleName","clientBoundaries","mode","minify","isExporting","baseUrl","reactCompiler","asyncRoutes","resolvedMainModuleName","resolveMainModuleName","metroImportAsArtifactsAsync","splitChunks","EXPO_NO_BUNDLE_SPLITTING","serializerIncludeMaps","lazy","EXPO_NO_METRO_LAZY","bytecode","getStaticPageAsync","devBundleUrlPathname","createBundleUrlPath","bundleStaticHtml","useServerDataLoaders","unstable_useServerDataLoaders","fromServerManifestRoute","data","loader","artifacts","resources","staticHtml","Promise","all","content","serializeHtmlWithAssets","template","devBundleUrl","hydrate","EXPO_WEB_DEV_HYDRATE","filePath","specificOptions","results","ssrLoadModuleContents","serializerOutput","assets","filename","metroLoadModuleContents","extraOptions","inlineSourceMap","engine","expoBundleOptions","getMetroDirectBundleOptions","resolverOptions","customResolverOptions","dev","transformOptions","type","unstable_transformProfile","customTransformOptions","Object","create","resolvedEntryFilePath","resolveRelativePathAsync","createBundleOsPath","_bundleDirectAsync","graphOptions","shallow","serializerOptions","modulesOnly","runModule","sourceUrl","sourceMapUrl","bundle","rest","scriptContents","wrapBundle","cachedSourceMaps","nativeExportBundleAsync","singlePageReactServerComponentExportAsync","legacySinglePageExportBundleAsync","getReactServerReferences","unique","filter","a","artifact","metadata","reactServerReferences","ref","fileURLToFilePath","flat","Boolean","reactClientReferences","serverActionReferencesInServer","cssModules","rscRenderer","getExpoRouterClientReferencesAsync","domRoot","processClientBoundaries","newReactServerReferences","Error","allKnownReactServerReferences","nestedClientBoundaries","exportServerActionsAsync","entryPoints","hasUniqueClientBoundaries","some","boundary","includes","concat","serverRoot","getMetroServerRoot","clientBoundariesAsOpaqueIds","toPosixPath","moduleIdToSplitBundle","paths","values","reduce","acc","ssrManifest","keys","forEach","routerOptions","exportRoutesAsync","fromEntries","from","entries","key","value","output","watchEnvironmentVariables","instance","metro","envFiles","runtimeEnv","getFiles","NODE_ENV","fileName","observeFileChanges","server","load","force","startImplementationAsync","urlCreator","getUrlCreator","config","skipSDKVersionRequirement","experiments","reactServerComponentRoutes","reactServerFunctions","isReactServerActionsOnlyEnabled","useServerRendering","web","hasApiRoutes","getBaseUrlFromExpoConfig","getAsyncRoutesFromExpoConfig","getRouterDirectoryModuleIdWithManifest","origin","configPath","dynamicConfigPath","staticConfigPath","configFileName","parsedOptions","maxWorkers","resetCache","resetDevServer","EXPO_DEV_SERVER_ORIGIN","hmrServer","messageSocket","instantiateMetroAsync","manifestMiddleware","getManifestMiddlewareAsync","prependMiddleware","ContextModuleSourceMapsMiddleware","getHandler","use","InterstitialPageMiddleware","scheme","DevToolsPluginMiddleware","devToolsPluginManager","deepLinkMiddleware","RuntimeRedirectMiddleware","getLocation","runtime","constructDevClientUrl","constructUrl","domComponentRenderer","createDomComponentsMiddleware","metroRoot","CreateFileMiddleware","req","res","next","statusCode","setHeader","end","sdkVersion","isTargetingWeb","loaderModuleMiddleware","DataLoaderModuleMiddleware","ServeStaticMiddleware","FaviconMiddleware","observeAnyFileChanges","events","invalidateApiRouteCache","hasWarnedAboutApiRoutes","event","isApiRouteConvention","warnInvalidWebOutput","handleLoaderFileChange","bindRSCDevModuleInjectionHandler","rscMiddleware","createServerComponentsMiddleware","bind","ssrLoadModuleArtifacts","useClientRouter","createModuleId","_createModuleId","onReloadRscEvent","HistoryFallbackMiddleware","internal","createRouteHandlerMiddleware","functionFilePath","ssrImportApiRoute","html","getSingleHtmlTemplateAsync","originalClose","close","callback","err","ssrHmrClients","host","protocol","registerSsrHmrAsync","onReload","has","sendFn","message","String","update","body","isInitialUpdate","added","modified","deleted","hasUpdate","globalThis","__c","allModuleIds","Set","m","module","platforms","moduleId","match","Log","error","_bundler","_revisionsByGraphId","client","onClientConnect","optedIntoHMR","_registerEntryPoint","waitForTypeScriptAsync","off","metroWatchTypeScriptFiles","tsconfig","throttle","eventTypes","TypeScriptProjectPrerequisite","bootstrapAsync","log","chalk","red","exception","startTypeScriptServices","startTypescriptTypeGenerationAsync","getConfigModuleIds","pendingRouteOperations","get","bundleAsync","relativePath","apiRoute","evalMetroNoHandling","htmlServerError","getErrorOverlayHtmlAsync","Response","status","headers","internalError","clear","loaderData","modulePath","routeModule","setupLoaderHmr","params","request","__expo_rsc_inject_module","sendClientModule","code","id","broadcastMessage","setupHmr","toString","watchedLoaderFiles","add","changedFilePath","loaderPath","possibleExtensions","isLoaderFile","ext","_config","buildNumber","getNewBuildNumber","bundlePerfLogger","unstable_perfLoggerFactory","onProgress","transformedFileCount","totalFileCount","_reporter","buildID","getBuildID","revPromise","getMetroRevision","point","annotate","bool","initial_build","bundleDetails","bundleType","entryFile","isPrefetch","delta","revision","props","getBundler","initializeGraph","updateGraph","attachImportStackToRootMessage","dropStackIfContainsCodeFrame","int","graph_node_count","graph","dependencies","size","shouldAddToIgnoreList","_shouldAddModuleToIgnoreList","serializer","getMetroSerializer","asyncRequireModulePath","_resolveRelativePath","transformer","relativeTo","processModuleFilter","getRunModuleStatement","globalPrefix","includeAsyncPaths","runBeforeMainModule","getModulesRunBeforeMainModule","unstable_serverRoot","prepend","bundleCode","bundleMap","parsed","isArray","asset","numModifiedFiles","reset","lastModifiedDate","date","nextRevId","sourceMapStringAsync","_getSortedModules","excludeSource","IS_METRO_BUNDLE_ERROR_SYMBOL","customSerializer","entryPoint","preModules","bundleToString","baseJSBundle","graphId","getGraphId","unstable_allowRequireContext","getRevisionByGraphId","extras","hot","evalMetroAndWrapFunctions","str","modules","sourceMapGeneratorNonBlocking","array"],"mappings":"AAAA;;;;;CAKC;;;;+BAkJYA;;;eAAAA;;;;yBAjJyB;;;;;;;yBACH;;;;;;;iEACP;;;;;;;gEACH;;;;;;;yBAIlB;;;;;;;gEAYoB;;;;;;;gEACJ;;;;;;;gEAKJ;;;;;;;gEACD;;;;;;;gEAGD;;;;;;kDAKV;6CACsC;qCACE;kCACT;qCAM/B;2CACmC;wBAMnC;+BACiC;qDACkB;qBAMtC;sBACA;wBACS;0BACD;sBACK;kCACwC;0CAKlE;+BAKA;mDAC2C;sCACb;4CACM;0CACF;yCACK;mCACZ;2CACQ;4CACC;oCACL;2CACI;uCACJ;8BAS/B;2BAC2B;+CAEiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCnD,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,qDAAqD,GACrD,MAAMC,qBAAqB;AAE3B,iGAAiG,GACjG,MAAMC,wBAAwB;AAEvB,MAAMJ,8BAA8BK,kCAAgB;IAOzD,IAAIC,OAAe;QACjB,OAAO;IACT;IAEA,MAAMC,iBAAiBC,UAAwC,CAAC,CAAC,EAAmB;QAClF,MAAMC,OACJ,yEAAyE;QACzED,QAAQC,IAAI,IACZ,8DAA8D;QAC7DD,CAAAA,QAAQE,SAAS,GAEdC,OAAOC,QAAQC,GAAG,CAACC,cAAc,KAAKV,wBAEtC,MAAMW,IAAAA,sBAA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e9d,QAAQ8d,aAAa;IACtC;AACF;AAEA,SAASnS,OAAUoT,KAAU;IAC3B,OAAO7c,MAAMoM,IAAI,CAAC,IAAI4H,IAAI6I;AAC5B"}
|
|
@@ -233,6 +233,13 @@ class MetroTerminalReporter extends _TerminalReporter.TerminalReporter {
|
|
|
233
233
|
return this.terminal.log(message);
|
|
234
234
|
}
|
|
235
235
|
(0, _metroErrorInterface.attachImportStackToRootMessage)(error);
|
|
236
|
+
// NOTE(@kitten): Metro drops the stack forcefully when it finds a `SyntaxError`. However,
|
|
237
|
+
// this is really unhelpful, since it prevents debugging Babel plugins or reporting bugs
|
|
238
|
+
// in Babel plugins or a transformer entirely
|
|
239
|
+
if (error.snippet == null && error.stack != null && error instanceof SyntaxError) {
|
|
240
|
+
error.message = error.stack;
|
|
241
|
+
delete error.stack;
|
|
242
|
+
}
|
|
236
243
|
return super._logBundlingError(error);
|
|
237
244
|
}
|
|
238
245
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import type { Terminal } from '@expo/metro/metro-core';\nimport chalk from 'chalk';\nimport path from 'path';\nimport { stripVTControlCharacters } from 'util';\n\nimport { logWarning, TerminalReporter } from './TerminalReporter';\nimport {\n BuildPhase,\n BundleDetails,\n BundleProgress,\n SnippetError,\n TerminalReportableEvent,\n} from './TerminalReporter.types';\nimport { NODE_STDLIB_MODULES } from './externals';\nimport { env } from '../../../utils/env';\nimport { learnMore } from '../../../utils/link';\nimport {\n logLikeMetro,\n maybeSymbolicateAndFormatJSErrorStackLogAsync,\n parseErrorStringToObject,\n} from '../serverLogLikeMetro';\nimport { attachImportStackToRootMessage, nearestImportStack } from './metroErrorInterface';\n\nconst debug = require('debug')('expo:metro:logger') as typeof console.log;\n\nconst MAX_PROGRESS_BAR_CHAR_WIDTH = 16;\nconst DARK_BLOCK_CHAR = '\\u2593';\nconst LIGHT_BLOCK_CHAR = '\\u2591';\n/**\n * Extends the default Metro logger and adds some additional features.\n * Also removes the giant Metro logo from the output.\n */\nexport class MetroTerminalReporter extends TerminalReporter {\n constructor(\n public projectRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n _log(event: TerminalReportableEvent): void {\n switch (event.type) {\n case 'unstable_server_log':\n if (typeof event.data?.[0] === 'string') {\n const message = event.data[0];\n if (message.match(/JavaScript logs have moved/)) {\n // Hide this very loud message from upstream React Native in favor of the note in the terminal UI:\n // The \"› Press j │ open debugger\"\n\n // logger?.info(\n // '\\u001B[1m\\u001B[7m💡 JavaScript logs have moved!\\u001B[22m They can now be ' +\n // 'viewed in React Native DevTools. Tip: Type \\u001B[1mj\\u001B[22m in ' +\n // 'the terminal to open (requires Google Chrome or Microsoft Edge).' +\n // '\\u001B[27m',\n // );\n return;\n }\n\n if (!env.EXPO_DEBUG) {\n // In the context of developing an iOS app or website, the MetroInspectorProxy \"connection\" logs are very confusing.\n // Here we'll hide them behind EXPO_DEBUG or DEBUG=expo:*. In the future we can reformat them to clearly indicate that the \"Connection\" is regarding the debugger.\n // These logs are also confusing because they can say \"connection established\" even when the debugger is not in a usable state. Really they belong in a UI or behind some sort of debug logging.\n if (message.match(/Connection (closed|established|failed|terminated)/i)) {\n // Skip logging.\n return;\n }\n }\n }\n break;\n case 'client_log': {\n if (this.shouldFilterClientLog(event)) {\n return;\n }\n const { level } = event;\n\n if (!level) {\n break;\n }\n\n if (level === 'warn' || (level as string) === 'error') {\n let hasStack = false;\n const parsed = event.data.map((msg) => {\n // Quick check to see if an unsymbolicated stack is being logged.\n if (msg.includes('.bundle//&platform=')) {\n const stack = parseErrorStringToObject(msg);\n if (stack) {\n hasStack = true;\n }\n return stack;\n }\n return msg;\n });\n\n if (hasStack) {\n (async () => {\n const symbolicating = parsed.map((p) => {\n if (typeof p === 'string') return p;\n return maybeSymbolicateAndFormatJSErrorStackLogAsync(this.projectRoot, level, p);\n });\n\n let usefulStackCount = 0;\n const fallbackIndices: number[] = [];\n const symbolicated = (await Promise.allSettled(symbolicating)).map((s, index) => {\n if (s.status === 'rejected') {\n debug('Error formatting stack', parsed[index], s.reason);\n return parsed[index];\n } else if (typeof s.value === 'string') {\n return s.value;\n } else {\n if (!s.value.isFallback) {\n usefulStackCount++;\n } else {\n fallbackIndices.push(index);\n }\n return s.value.stack;\n }\n });\n\n // Using EXPO_DEBUG we can print all stack\n const filtered =\n usefulStackCount && !env.EXPO_DEBUG\n ? symbolicated.filter((_, index) => !fallbackIndices.includes(index))\n : symbolicated;\n\n logLikeMetro(this.terminal.log.bind(this.terminal), level, null, ...filtered);\n })();\n return;\n }\n }\n\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, null, ...event.data);\n return;\n }\n }\n return super._log(event);\n }\n\n // Used for testing\n _getElapsedTime(startTime: bigint): bigint {\n return process.hrtime.bigint() - startTime;\n }\n /**\n * Extends the bundle progress to include the current platform that we're bundling.\n *\n * @returns `iOS path/to/bundle.js ▓▓▓▓▓░░░░░░░░░░░ 36.6% (4790/7922)`\n */\n _getBundleStatusMessage(progress: BundleProgress, phase: BuildPhase): string {\n const env = getEnvironmentForBuildDetails(progress.bundleDetails);\n const platform = env || getPlatformTagForBuildDetails(progress.bundleDetails);\n const inProgress = phase === 'in_progress';\n\n let localPath: string;\n\n if (\n typeof progress.bundleDetails?.customTransformOptions?.dom === 'string' &&\n progress.bundleDetails.customTransformOptions.dom.includes(path.sep)\n ) {\n // Because we use a generated entry file for DOM components, we need to adjust the logging path so it\n // shows a unique path for each component.\n // Here, we take the relative import path and remove all the starting slashes.\n localPath = progress.bundleDetails.customTransformOptions.dom.replace(/^(\\.?\\.[\\\\/])+/, '');\n } else {\n const inputFile = progress.bundleDetails.entryFile;\n\n localPath = path.isAbsolute(inputFile)\n ? path.relative(this.projectRoot, inputFile)\n : inputFile;\n }\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundled ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n\n let time: string = '';\n\n if (startTime != null) {\n const elapsed: bigint = this._getElapsedTime(startTime);\n const micro = Number(elapsed) / 1000;\n const converted = Number(elapsed) / 1e6;\n // If the milliseconds are < 0.5 then it will display as 0, so we display in microseconds.\n if (converted <= 0.5) {\n const tenthFractionOfMicro = ((micro * 10) / 1000).toFixed(0);\n // Format as microseconds to nearest tenth\n time = chalk.cyan.bold(`0.${tenthFractionOfMicro}ms`);\n } else {\n time = chalk.dim(converted.toFixed(0) + 'ms');\n }\n }\n\n // iOS Bundled 150ms\n const plural = progress.totalFileCount === 1 ? '' : 's';\n return (\n color(platform + status) +\n time +\n chalk.reset.dim(` ${localPath} (${progress.totalFileCount} module${plural})`)\n );\n }\n\n const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);\n\n const _progress = inProgress\n ? chalk.green.bgGreen(DARK_BLOCK_CHAR.repeat(filledBar)) +\n chalk.bgWhite.white(LIGHT_BLOCK_CHAR.repeat(MAX_PROGRESS_BAR_CHAR_WIDTH - filledBar)) +\n chalk.bold(` ${(100 * progress.ratio).toFixed(1).padStart(4)}% `) +\n chalk.dim(\n `(${progress.transformedFileCount\n .toString()\n .padStart(progress.totalFileCount.toString().length)}/${progress.totalFileCount})`\n )\n : '';\n\n return (\n platform +\n chalk.reset.dim(`${path.dirname(localPath)}${path.sep}`) +\n chalk.bold(path.basename(localPath)) +\n ' ' +\n _progress\n );\n }\n\n _logInitializing(port: number, hasReducedPerformance: boolean): void {\n // Don't print a giant logo...\n this.terminal.log(chalk.dim('Starting Metro Bundler'));\n }\n\n shouldFilterClientLog(event: { type: 'client_log'; data: unknown[] }): boolean {\n return isAppRegistryStartupMessage(event.data);\n }\n\n shouldFilterBundleEvent(event: TerminalReportableEvent): boolean {\n return 'bundleDetails' in event && event.bundleDetails?.bundleType === 'map';\n }\n\n /** Print the cache clear message. */\n transformCacheReset(): void {\n logWarning(\n this.terminal,\n chalk`Bundler cache is empty, rebuilding {dim (this may take a minute)}`\n );\n }\n\n /** One of the first logs that will be printed */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {\n // this.terminal.log('Dependency graph is loading...');\n if (hasReducedPerformance) {\n // Extends https://github.com/facebook/metro/blob/347b1d7ed87995d7951aaa9fd597c04b06013dac/packages/metro/src/lib/TerminalReporter.js#L283-L290\n this.terminal.log(\n chalk.red(\n [\n 'Metro is operating with reduced performance.',\n 'Fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n _logBundlingError(error: SnippetError): void {\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.projectRoot, error);\n if (moduleResolutionError) {\n let message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n message += '\\n\\n' + nearestImportStack(error);\n return this.terminal.log(message);\n }\n\n attachImportStackToRootMessage(error);\n return super._logBundlingError(error);\n }\n}\n\n/**\n * Formats an error where the user is attempting to import a module from the Node.js standard library.\n * Exposed for testing.\n *\n * @param error\n * @returns error message or null if not a module resolution error\n */\nexport function formatUsingNodeStandardLibraryError(\n projectRoot: string,\n error: SnippetError\n): string | null {\n if (!error.message) {\n return null;\n }\n const { targetModuleName, originModulePath } = error;\n if (!targetModuleName || !originModulePath) {\n return null;\n }\n const relativePath = path.relative(projectRoot, originModulePath);\n\n const DOCS_PAGE_URL =\n 'https://docs.expo.dev/workflow/using-libraries/#using-third-party-libraries';\n\n if (isNodeStdLibraryModule(targetModuleName)) {\n if (originModulePath.includes('node_modules')) {\n return [\n `The package at \"${chalk.bold(\n relativePath\n )}\" attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n } else {\n return [\n `You attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\" from \"${chalk.bold(relativePath)}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n }\n }\n return `Unable to resolve \"${targetModuleName}\" from \"${relativePath}\"`;\n}\n\nexport function isNodeStdLibraryModule(moduleName: string): boolean {\n return /^node:/.test(moduleName) || NODE_STDLIB_MODULES.includes(moduleName);\n}\n\n/** If the code frame can be found then append it to the existing message. */\nfunction maybeAppendCodeFrame(message: string, rawMessage: string): string {\n const codeFrame = extractCodeFrame(stripMetroInfo(rawMessage));\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\n}\n\n/** Extract fist code frame presented in the error message */\nexport function extractCodeFrame(errorMessage: string): string {\n const codeFrameLine = /^(?:\\s*(?:>?\\s*\\d+\\s*\\||\\s*\\|).*\\n?)+/;\n let wasPreviousLineCodeFrame: boolean | null = null;\n return errorMessage\n .split('\\n')\n .filter((line) => {\n if (wasPreviousLineCodeFrame === false) return false;\n const keep = codeFrameLine.test(stripVTControlCharacters(line));\n if (keep && wasPreviousLineCodeFrame === null) wasPreviousLineCodeFrame = true;\n else if (!keep && wasPreviousLineCodeFrame) wasPreviousLineCodeFrame = false;\n return keep;\n })\n .join('\\n');\n}\n\n/**\n * Remove the Metro cache clearing steps if they exist.\n * In future versions we won't need this.\n * Returns the remaining code frame logs.\n */\nexport function stripMetroInfo(errorMessage: string): string {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return errorMessage;\n }\n const lines = errorMessage.split('\\n');\n const index = lines.findIndex((line) => line.includes('4. Remove the cache'));\n if (index === -1) {\n return errorMessage;\n }\n return lines.slice(index + 1).join('\\n');\n}\n\n/** @returns if the message matches the initial startup log */\nfunction isAppRegistryStartupMessage(body: any[]): boolean {\n return (\n body.length === 1 &&\n (/^Running application \"main\" with appParams:/.test(body[0]) ||\n /^Running \"main\" with \\{/.test(body[0]))\n );\n}\n\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getPlatformTagForBuildDetails(bundleDetails?: BundleDetails | null): string {\n const platform = bundleDetails?.platform ?? null;\n if (platform) {\n const formatted = { ios: 'iOS', android: 'Android', web: 'Web' }[platform] || platform;\n return `${chalk.bold(formatted)} `;\n }\n\n return '';\n}\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getEnvironmentForBuildDetails(bundleDetails?: BundleDetails | null): string {\n // Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.\n const env = bundleDetails?.customTransformOptions?.environment ?? null;\n if (env === 'node') {\n return chalk.bold('λ') + ' ';\n } else if (env === 'react-server') {\n return chalk.bold(`RSC(${getPlatformTagForBuildDetails(bundleDetails).trim()})`) + ' ';\n }\n\n if (\n bundleDetails?.customTransformOptions?.dom &&\n typeof bundleDetails?.customTransformOptions?.dom === 'string'\n ) {\n return chalk.bold(`DOM`) + ' ';\n }\n\n return '';\n}\n"],"names":["MetroTerminalReporter","extractCodeFrame","formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","debug","require","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","TerminalReporter","constructor","projectRoot","terminal","_log","event","type","data","message","match","env","EXPO_DEBUG","shouldFilterClientLog","level","hasStack","parsed","map","msg","includes","stack","parseErrorStringToObject","symbolicating","p","maybeSymbolicateAndFormatJSErrorStackLogAsync","usefulStackCount","fallbackIndices","symbolicated","Promise","allSettled","s","index","status","reason","value","isFallback","push","filtered","filter","_","logLikeMetro","log","bind","_getElapsedTime","startTime","process","hrtime","bigint","_getBundleStatusMessage","progress","phase","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","customTransformOptions","dom","path","sep","replace","inputFile","entryFile","isAbsolute","relative","color","chalk","green","red","_bundleTimers","get","buildID","time","elapsed","micro","Number","converted","tenthFractionOfMicro","toFixed","cyan","bold","dim","plural","totalFileCount","reset","filledBar","Math","floor","ratio","_progress","bgGreen","repeat","bgWhite","white","padStart","transformedFileCount","toString","length","dirname","basename","_logInitializing","port","hasReducedPerformance","isAppRegistryStartupMessage","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundlingError","error","moduleResolutionError","maybeAppendCodeFrame","nearestImportStack","attachImportStackToRootMessage","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","codeFrameLine","wasPreviousLineCodeFrame","split","line","keep","stripVTControlCharacters","lines","findIndex","slice","body","formatted","ios","android","web","environment","trim"],"mappings":";;;;;;;;;;;IAgCaA,qBAAqB;eAArBA;;IA8SGC,gBAAgB;eAAhBA;;IAtDAC,mCAAmC;eAAnCA;;IAwCAC,sBAAsB;eAAtBA;;IAkCAC,cAAc;eAAdA;;;;gEAjWE;;;;;;;gEACD;;;;;;;yBACwB;;;;;;kCAEI;2BAQT;qBAChB;sBACM;oCAKnB;qCAC4D;;;;;;AAEnE,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MAAMC,8BAA8B;AACpC,MAAMC,kBAAkB;AACxB,MAAMC,mBAAmB;AAKlB,MAAMT,8BAA8BU,kCAAgB;IACzDC,YACE,AAAOC,WAAmB,EAC1BC,QAAkB,CAClB;QACA,KAAK,CAACA,gBAHCD,cAAAA;IAIT;IAEAE,KAAKC,KAA8B,EAAQ;QACzC,OAAQA,MAAMC,IAAI;YAChB,KAAK;oBACQD;gBAAX,IAAI,SAAOA,cAAAA,MAAME,IAAI,qBAAVF,WAAY,CAAC,EAAE,MAAK,UAAU;oBACvC,MAAMG,UAAUH,MAAME,IAAI,CAAC,EAAE;oBAC7B,IAAIC,QAAQC,KAAK,CAAC,+BAA+B;wBAC/C,kGAAkG;wBAClG,kCAAkC;wBAElC,gBAAgB;wBAChB,oFAAoF;wBACpF,8EAA8E;wBAC9E,2EAA2E;wBAC3E,oBAAoB;wBACpB,KAAK;wBACL;oBACF;oBAEA,IAAI,CAACC,QAAG,CAACC,UAAU,EAAE;wBACnB,oHAAoH;wBACpH,kKAA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ASN,4BAA4BiC,IAAW;IAC9C,OACEA,KAAKvC,MAAM,KAAK,KACf,CAAA,8CAA8CyB,IAAI,CAACc,IAAI,CAAC,EAAE,KACzD,0BAA0Bd,IAAI,CAACc,IAAI,CAAC,EAAE,CAAA;AAE5C;AAEA,gEAAgE,GAChE,SAASnF,8BAA8BF,aAAoC;IACzE,MAAMC,WAAWD,CAAAA,iCAAAA,cAAeC,QAAQ,KAAI;IAC5C,IAAIA,UAAU;QACZ,MAAMqF,YAAY;YAAEC,KAAK;YAAOC,SAAS;YAAWC,KAAK;QAAM,CAAC,CAACxF,SAAS,IAAIA;QAC9E,OAAO,GAAGc,gBAAK,CAACc,IAAI,CAACyD,WAAW,CAAC,CAAC;IACpC;IAEA,OAAO;AACT;AACA,gEAAgE,GAChE,SAASvF,8BAA8BC,aAAoC;QAE7DA,uCAQVA,wCACOA;IAVT,iGAAiG;IACjG,MAAMzC,MAAMyC,CAAAA,kCAAAA,wCAAAA,cAAeK,sBAAsB,qBAArCL,sCAAuC0F,WAAW,KAAI;IAClE,IAAInI,QAAQ,QAAQ;QAClB,OAAOwD,gBAAK,CAACc,IAAI,CAAC,OAAO;IAC3B,OAAO,IAAItE,QAAQ,gBAAgB;QACjC,OAAOwD,gBAAK,CAACc,IAAI,CAAC,CAAC,IAAI,EAAE3B,8BAA8BF,eAAe2F,IAAI,GAAG,CAAC,CAAC,IAAI;IACrF;IAEA,IACE3F,CAAAA,kCAAAA,yCAAAA,cAAeK,sBAAsB,qBAArCL,uCAAuCM,GAAG,KAC1C,QAAON,kCAAAA,yCAAAA,cAAeK,sBAAsB,qBAArCL,uCAAuCM,GAAG,MAAK,UACtD;QACA,OAAOS,gBAAK,CAACc,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI;IAC7B;IAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import type { Terminal } from '@expo/metro/metro-core';\nimport chalk from 'chalk';\nimport path from 'path';\nimport { stripVTControlCharacters } from 'util';\n\nimport { logWarning, TerminalReporter } from './TerminalReporter';\nimport {\n BuildPhase,\n BundleDetails,\n BundleProgress,\n SnippetError,\n TerminalReportableEvent,\n} from './TerminalReporter.types';\nimport { NODE_STDLIB_MODULES } from './externals';\nimport { env } from '../../../utils/env';\nimport { learnMore } from '../../../utils/link';\nimport {\n logLikeMetro,\n maybeSymbolicateAndFormatJSErrorStackLogAsync,\n parseErrorStringToObject,\n} from '../serverLogLikeMetro';\nimport { attachImportStackToRootMessage, nearestImportStack } from './metroErrorInterface';\n\nconst debug = require('debug')('expo:metro:logger') as typeof console.log;\n\nconst MAX_PROGRESS_BAR_CHAR_WIDTH = 16;\nconst DARK_BLOCK_CHAR = '\\u2593';\nconst LIGHT_BLOCK_CHAR = '\\u2591';\n/**\n * Extends the default Metro logger and adds some additional features.\n * Also removes the giant Metro logo from the output.\n */\nexport class MetroTerminalReporter extends TerminalReporter {\n constructor(\n public projectRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n _log(event: TerminalReportableEvent): void {\n switch (event.type) {\n case 'unstable_server_log':\n if (typeof event.data?.[0] === 'string') {\n const message = event.data[0];\n if (message.match(/JavaScript logs have moved/)) {\n // Hide this very loud message from upstream React Native in favor of the note in the terminal UI:\n // The \"› Press j │ open debugger\"\n\n // logger?.info(\n // '\\u001B[1m\\u001B[7m💡 JavaScript logs have moved!\\u001B[22m They can now be ' +\n // 'viewed in React Native DevTools. Tip: Type \\u001B[1mj\\u001B[22m in ' +\n // 'the terminal to open (requires Google Chrome or Microsoft Edge).' +\n // '\\u001B[27m',\n // );\n return;\n }\n\n if (!env.EXPO_DEBUG) {\n // In the context of developing an iOS app or website, the MetroInspectorProxy \"connection\" logs are very confusing.\n // Here we'll hide them behind EXPO_DEBUG or DEBUG=expo:*. In the future we can reformat them to clearly indicate that the \"Connection\" is regarding the debugger.\n // These logs are also confusing because they can say \"connection established\" even when the debugger is not in a usable state. Really they belong in a UI or behind some sort of debug logging.\n if (message.match(/Connection (closed|established|failed|terminated)/i)) {\n // Skip logging.\n return;\n }\n }\n }\n break;\n case 'client_log': {\n if (this.shouldFilterClientLog(event)) {\n return;\n }\n const { level } = event;\n\n if (!level) {\n break;\n }\n\n if (level === 'warn' || (level as string) === 'error') {\n let hasStack = false;\n const parsed = event.data.map((msg) => {\n // Quick check to see if an unsymbolicated stack is being logged.\n if (msg.includes('.bundle//&platform=')) {\n const stack = parseErrorStringToObject(msg);\n if (stack) {\n hasStack = true;\n }\n return stack;\n }\n return msg;\n });\n\n if (hasStack) {\n (async () => {\n const symbolicating = parsed.map((p) => {\n if (typeof p === 'string') return p;\n return maybeSymbolicateAndFormatJSErrorStackLogAsync(this.projectRoot, level, p);\n });\n\n let usefulStackCount = 0;\n const fallbackIndices: number[] = [];\n const symbolicated = (await Promise.allSettled(symbolicating)).map((s, index) => {\n if (s.status === 'rejected') {\n debug('Error formatting stack', parsed[index], s.reason);\n return parsed[index];\n } else if (typeof s.value === 'string') {\n return s.value;\n } else {\n if (!s.value.isFallback) {\n usefulStackCount++;\n } else {\n fallbackIndices.push(index);\n }\n return s.value.stack;\n }\n });\n\n // Using EXPO_DEBUG we can print all stack\n const filtered =\n usefulStackCount && !env.EXPO_DEBUG\n ? symbolicated.filter((_, index) => !fallbackIndices.includes(index))\n : symbolicated;\n\n logLikeMetro(this.terminal.log.bind(this.terminal), level, null, ...filtered);\n })();\n return;\n }\n }\n\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, null, ...event.data);\n return;\n }\n }\n return super._log(event);\n }\n\n // Used for testing\n _getElapsedTime(startTime: bigint): bigint {\n return process.hrtime.bigint() - startTime;\n }\n /**\n * Extends the bundle progress to include the current platform that we're bundling.\n *\n * @returns `iOS path/to/bundle.js ▓▓▓▓▓░░░░░░░░░░░ 36.6% (4790/7922)`\n */\n _getBundleStatusMessage(progress: BundleProgress, phase: BuildPhase): string {\n const env = getEnvironmentForBuildDetails(progress.bundleDetails);\n const platform = env || getPlatformTagForBuildDetails(progress.bundleDetails);\n const inProgress = phase === 'in_progress';\n\n let localPath: string;\n\n if (\n typeof progress.bundleDetails?.customTransformOptions?.dom === 'string' &&\n progress.bundleDetails.customTransformOptions.dom.includes(path.sep)\n ) {\n // Because we use a generated entry file for DOM components, we need to adjust the logging path so it\n // shows a unique path for each component.\n // Here, we take the relative import path and remove all the starting slashes.\n localPath = progress.bundleDetails.customTransformOptions.dom.replace(/^(\\.?\\.[\\\\/])+/, '');\n } else {\n const inputFile = progress.bundleDetails.entryFile;\n\n localPath = path.isAbsolute(inputFile)\n ? path.relative(this.projectRoot, inputFile)\n : inputFile;\n }\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundled ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n\n let time: string = '';\n\n if (startTime != null) {\n const elapsed: bigint = this._getElapsedTime(startTime);\n const micro = Number(elapsed) / 1000;\n const converted = Number(elapsed) / 1e6;\n // If the milliseconds are < 0.5 then it will display as 0, so we display in microseconds.\n if (converted <= 0.5) {\n const tenthFractionOfMicro = ((micro * 10) / 1000).toFixed(0);\n // Format as microseconds to nearest tenth\n time = chalk.cyan.bold(`0.${tenthFractionOfMicro}ms`);\n } else {\n time = chalk.dim(converted.toFixed(0) + 'ms');\n }\n }\n\n // iOS Bundled 150ms\n const plural = progress.totalFileCount === 1 ? '' : 's';\n return (\n color(platform + status) +\n time +\n chalk.reset.dim(` ${localPath} (${progress.totalFileCount} module${plural})`)\n );\n }\n\n const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);\n\n const _progress = inProgress\n ? chalk.green.bgGreen(DARK_BLOCK_CHAR.repeat(filledBar)) +\n chalk.bgWhite.white(LIGHT_BLOCK_CHAR.repeat(MAX_PROGRESS_BAR_CHAR_WIDTH - filledBar)) +\n chalk.bold(` ${(100 * progress.ratio).toFixed(1).padStart(4)}% `) +\n chalk.dim(\n `(${progress.transformedFileCount\n .toString()\n .padStart(progress.totalFileCount.toString().length)}/${progress.totalFileCount})`\n )\n : '';\n\n return (\n platform +\n chalk.reset.dim(`${path.dirname(localPath)}${path.sep}`) +\n chalk.bold(path.basename(localPath)) +\n ' ' +\n _progress\n );\n }\n\n _logInitializing(port: number, hasReducedPerformance: boolean): void {\n // Don't print a giant logo...\n this.terminal.log(chalk.dim('Starting Metro Bundler'));\n }\n\n shouldFilterClientLog(event: { type: 'client_log'; data: unknown[] }): boolean {\n return isAppRegistryStartupMessage(event.data);\n }\n\n shouldFilterBundleEvent(event: TerminalReportableEvent): boolean {\n return 'bundleDetails' in event && event.bundleDetails?.bundleType === 'map';\n }\n\n /** Print the cache clear message. */\n transformCacheReset(): void {\n logWarning(\n this.terminal,\n chalk`Bundler cache is empty, rebuilding {dim (this may take a minute)}`\n );\n }\n\n /** One of the first logs that will be printed */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {\n // this.terminal.log('Dependency graph is loading...');\n if (hasReducedPerformance) {\n // Extends https://github.com/facebook/metro/blob/347b1d7ed87995d7951aaa9fd597c04b06013dac/packages/metro/src/lib/TerminalReporter.js#L283-L290\n this.terminal.log(\n chalk.red(\n [\n 'Metro is operating with reduced performance.',\n 'Fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n _logBundlingError(error: SnippetError): void {\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.projectRoot, error);\n if (moduleResolutionError) {\n let message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n message += '\\n\\n' + nearestImportStack(error);\n return this.terminal.log(message);\n }\n\n attachImportStackToRootMessage(error);\n\n // NOTE(@kitten): Metro drops the stack forcefully when it finds a `SyntaxError`. However,\n // this is really unhelpful, since it prevents debugging Babel plugins or reporting bugs\n // in Babel plugins or a transformer entirely\n if (error.snippet == null && error.stack != null && error instanceof SyntaxError) {\n error.message = error.stack;\n delete error.stack;\n }\n\n return super._logBundlingError(error);\n }\n}\n\n/**\n * Formats an error where the user is attempting to import a module from the Node.js standard library.\n * Exposed for testing.\n *\n * @param error\n * @returns error message or null if not a module resolution error\n */\nexport function formatUsingNodeStandardLibraryError(\n projectRoot: string,\n error: SnippetError\n): string | null {\n if (!error.message) {\n return null;\n }\n const { targetModuleName, originModulePath } = error;\n if (!targetModuleName || !originModulePath) {\n return null;\n }\n const relativePath = path.relative(projectRoot, originModulePath);\n\n const DOCS_PAGE_URL =\n 'https://docs.expo.dev/workflow/using-libraries/#using-third-party-libraries';\n\n if (isNodeStdLibraryModule(targetModuleName)) {\n if (originModulePath.includes('node_modules')) {\n return [\n `The package at \"${chalk.bold(\n relativePath\n )}\" attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n } else {\n return [\n `You attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\" from \"${chalk.bold(relativePath)}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n }\n }\n return `Unable to resolve \"${targetModuleName}\" from \"${relativePath}\"`;\n}\n\nexport function isNodeStdLibraryModule(moduleName: string): boolean {\n return /^node:/.test(moduleName) || NODE_STDLIB_MODULES.includes(moduleName);\n}\n\n/** If the code frame can be found then append it to the existing message. */\nfunction maybeAppendCodeFrame(message: string, rawMessage: string): string {\n const codeFrame = extractCodeFrame(stripMetroInfo(rawMessage));\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\n}\n\n/** Extract fist code frame presented in the error message */\nexport function extractCodeFrame(errorMessage: string): string {\n const codeFrameLine = /^(?:\\s*(?:>?\\s*\\d+\\s*\\||\\s*\\|).*\\n?)+/;\n let wasPreviousLineCodeFrame: boolean | null = null;\n return errorMessage\n .split('\\n')\n .filter((line) => {\n if (wasPreviousLineCodeFrame === false) return false;\n const keep = codeFrameLine.test(stripVTControlCharacters(line));\n if (keep && wasPreviousLineCodeFrame === null) wasPreviousLineCodeFrame = true;\n else if (!keep && wasPreviousLineCodeFrame) wasPreviousLineCodeFrame = false;\n return keep;\n })\n .join('\\n');\n}\n\n/**\n * Remove the Metro cache clearing steps if they exist.\n * In future versions we won't need this.\n * Returns the remaining code frame logs.\n */\nexport function stripMetroInfo(errorMessage: string): string {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return errorMessage;\n }\n const lines = errorMessage.split('\\n');\n const index = lines.findIndex((line) => line.includes('4. Remove the cache'));\n if (index === -1) {\n return errorMessage;\n }\n return lines.slice(index + 1).join('\\n');\n}\n\n/** @returns if the message matches the initial startup log */\nfunction isAppRegistryStartupMessage(body: any[]): boolean {\n return (\n body.length === 1 &&\n (/^Running application \"main\" with appParams:/.test(body[0]) ||\n /^Running \"main\" with \\{/.test(body[0]))\n );\n}\n\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getPlatformTagForBuildDetails(bundleDetails?: BundleDetails | null): string {\n const platform = bundleDetails?.platform ?? null;\n if (platform) {\n const formatted = { ios: 'iOS', android: 'Android', web: 'Web' }[platform] || platform;\n return `${chalk.bold(formatted)} `;\n }\n\n return '';\n}\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getEnvironmentForBuildDetails(bundleDetails?: BundleDetails | null): string {\n // Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.\n const env = bundleDetails?.customTransformOptions?.environment ?? null;\n if (env === 'node') {\n return chalk.bold('λ') + ' ';\n } else if (env === 'react-server') {\n return chalk.bold(`RSC(${getPlatformTagForBuildDetails(bundleDetails).trim()})`) + ' ';\n }\n\n if (\n bundleDetails?.customTransformOptions?.dom &&\n typeof bundleDetails?.customTransformOptions?.dom === 'string'\n ) {\n return chalk.bold(`DOM`) + ' ';\n }\n\n return '';\n}\n"],"names":["MetroTerminalReporter","extractCodeFrame","formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","debug","require","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","TerminalReporter","constructor","projectRoot","terminal","_log","event","type","data","message","match","env","EXPO_DEBUG","shouldFilterClientLog","level","hasStack","parsed","map","msg","includes","stack","parseErrorStringToObject","symbolicating","p","maybeSymbolicateAndFormatJSErrorStackLogAsync","usefulStackCount","fallbackIndices","symbolicated","Promise","allSettled","s","index","status","reason","value","isFallback","push","filtered","filter","_","logLikeMetro","log","bind","_getElapsedTime","startTime","process","hrtime","bigint","_getBundleStatusMessage","progress","phase","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","customTransformOptions","dom","path","sep","replace","inputFile","entryFile","isAbsolute","relative","color","chalk","green","red","_bundleTimers","get","buildID","time","elapsed","micro","Number","converted","tenthFractionOfMicro","toFixed","cyan","bold","dim","plural","totalFileCount","reset","filledBar","Math","floor","ratio","_progress","bgGreen","repeat","bgWhite","white","padStart","transformedFileCount","toString","length","dirname","basename","_logInitializing","port","hasReducedPerformance","isAppRegistryStartupMessage","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundlingError","error","moduleResolutionError","maybeAppendCodeFrame","nearestImportStack","attachImportStackToRootMessage","snippet","SyntaxError","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","codeFrameLine","wasPreviousLineCodeFrame","split","line","keep","stripVTControlCharacters","lines","findIndex","slice","body","formatted","ios","android","web","environment","trim"],"mappings":";;;;;;;;;;;IAgCaA,qBAAqB;eAArBA;;IAuTGC,gBAAgB;eAAhBA;;IAtDAC,mCAAmC;eAAnCA;;IAwCAC,sBAAsB;eAAtBA;;IAkCAC,cAAc;eAAdA;;;;gEA1WE;;;;;;;gEACD;;;;;;;yBACwB;;;;;;kCAEI;2BAQT;qBA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AAEC,KAAK;YAAOC,SAAS;YAAWC,KAAK;QAAM,CAAC,CAAC1F,SAAS,IAAIA;QAC9E,OAAO,GAAGc,gBAAK,CAACc,IAAI,CAAC2D,WAAW,CAAC,CAAC;IACpC;IAEA,OAAO;AACT;AACA,gEAAgE,GAChE,SAASzF,8BAA8BC,aAAoC;QAE7DA,uCAQVA,wCACOA;IAVT,iGAAiG;IACjG,MAAMzC,MAAMyC,CAAAA,kCAAAA,wCAAAA,cAAeK,sBAAsB,qBAArCL,sCAAuC4F,WAAW,KAAI;IAClE,IAAIrI,QAAQ,QAAQ;QAClB,OAAOwD,gBAAK,CAACc,IAAI,CAAC,OAAO;IAC3B,OAAO,IAAItE,QAAQ,gBAAgB;QACjC,OAAOwD,gBAAK,CAACc,IAAI,CAAC,CAAC,IAAI,EAAE3B,8BAA8BF,eAAe6F,IAAI,GAAG,CAAC,CAAC,IAAI;IACrF;IAEA,IACE7F,CAAAA,kCAAAA,yCAAAA,cAAeK,sBAAsB,qBAArCL,uCAAuCM,GAAG,KAC1C,QAAON,kCAAAA,yCAAAA,cAAeK,sBAAsB,qBAArCL,uCAAuCM,GAAG,MAAK,UACtD;QACA,OAAOS,gBAAK,CAACc,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI;IAC7B;IAEA,OAAO;AACT"}
|
|
@@ -158,7 +158,7 @@ function createRouteHandlerMiddleware(projectRoot, options) {
|
|
|
158
158
|
}
|
|
159
159
|
};
|
|
160
160
|
}
|
|
161
|
-
// TODO(@kitten): Unify with MetroBundlerDevServer#
|
|
161
|
+
// TODO(@kitten): Unify with MetroBundlerDevServer#exportMiddlewareAsync
|
|
162
162
|
const resolvedFunctionPath = _path().default.isAbsolute(route.file) ? route.file : _path().default.join(options.appDir, route.file);
|
|
163
163
|
try {
|
|
164
164
|
var _middlewareModule_unstable_settings;
|
|
@@ -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 */\n\nimport type { ProjectConfig } from '@expo/config';\nimport type { MiddlewareSettings } from 'expo-server';\nimport { createRequestHandler } from 'expo-server/adapter/http';\nimport { type RouteInfo } from 'expo-server/private';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { fetchManifest } from './fetchRouterManifest';\nimport { getErrorOverlayHtmlAsync } from './metroErrorInterface';\nimport {\n warnInvalidWebOutput,\n warnInvalidMiddlewareOutput,\n warnInvalidMiddlewareMatcherSettings,\n} from './router';\nimport { CommandError } from '../../../utils/errors';\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\nexport function createRouteHandlerMiddleware(\n projectRoot: string,\n options: {\n appDir: string;\n routerRoot: string;\n getStaticPageAsync: (\n pathname: string,\n route: RouteInfo<RegExp>\n ) => Promise<{ content: string }>;\n bundleApiRoute: (\n functionFilePath: string\n ) => Promise<null | Record<string, Function> | Response>;\n config: ProjectConfig;\n headers: Record<string, string | string[]>;\n } & import('@expo/router-server/build/routes-manifest').Options\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. Either install the expo-router package or change 'web.output' to 'single' in your app.json.`\n );\n }\n\n return createRequestHandler(\n { build: '' },\n {\n async getRoutesManifest() {\n const manifest = await fetchManifest(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 redirects: [],\n rewrites: [],\n }\n );\n },\n async getHtml(request, route) {\n try {\n const { content } = await options.getStaticPageAsync(request.url, route);\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\n try {\n return new Response(\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 debug('Failed to render static error overlay:', staticError);\n // Fallback error for when Expo Router is misconfigured in the project.\n return new Response(\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 async handleRouteError(error) {\n // NOTE(@kitten): ExpoError is currently not exposed by expo-server just yet\n if (error && typeof error === 'object' && error.name === 'ExpoError') {\n // TODO(@krystofwoldrich): Can we show code snippet of the handler?\n // NOTE(@krystofwoldrich): Removing stack since to avoid confusion. The error is not in the server code.\n delete error.stack;\n }\n\n const htmlServerError = await getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot: options.routerRoot!,\n });\n\n return new Response(htmlServerError, {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n },\n async getApiRoute(route) {\n const { exp } = options.config;\n if (exp.web?.output !== 'server') {\n warnInvalidWebOutput();\n }\n\n // TODO(@kitten): Unify with MetroBundlerDevServer#exportExpoRouterApiRoutesAsync\n const resolvedFunctionPath = path.isAbsolute(route.file)\n ? route.file\n : path.join(options.appDir, route.file);\n try {\n debug(`Bundling API route at: ${resolvedFunctionPath}`);\n return await options.bundleApiRoute(resolvedFunctionPath!);\n } catch (error: any) {\n return new Response(\n 'Failed to load API Route: ' + resolvedFunctionPath + '\\n\\n' + error.message,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n },\n async getMiddleware(route) {\n const { exp } = options.config;\n\n if (!options.unstable_useServerMiddleware) {\n return {\n default: () => {\n throw new CommandError(\n 'Server middleware is not enabled. Add unstable_useServerMiddleware: true to your `expo-router` plugin config.'\n );\n },\n };\n }\n\n if (exp.web?.output !== 'server') {\n warnInvalidMiddlewareOutput();\n return {\n default: () => {\n console.warn(\n 'Server middleware is only supported when web.output is set to \"server\" in your app config'\n );\n },\n };\n }\n\n // TODO(@kitten): Unify with MetroBundlerDevServer#exportMiddleware\n const resolvedFunctionPath = path.isAbsolute(route.file)\n ? route.file\n : path.join(options.appDir, route.file);\n try {\n debug(`Bundling middleware at: ${resolvedFunctionPath}`);\n const middlewareModule = (await options.bundleApiRoute(resolvedFunctionPath!)) as any;\n\n if ((middlewareModule.unstable_settings as MiddlewareSettings)?.matcher) {\n warnInvalidMiddlewareMatcherSettings(middlewareModule.unstable_settings?.matcher);\n }\n\n return middlewareModule;\n } catch (error: any) {\n return new Response(\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","projectRoot","options","resolveFrom","silent","CommandError","createRequestHandler","build","getRoutesManifest","manifest","fetchManifest","htmlRoutes","file","page","routeKeys","namedRegex","apiRoutes","notFoundRoutes","redirects","rewrites","getHtml","request","route","content","getStaticPageAsync","url","error","Response","getErrorOverlayHtmlAsync","routerRoot","status","headers","staticError","message","handleRouteError","name","stack","htmlServerError","getApiRoute","exp","config","web","output","warnInvalidWebOutput","resolvedFunctionPath","path","isAbsolute","join","appDir","bundleApiRoute","getMiddleware","unstable_useServerMiddleware","default","warnInvalidMiddlewareOutput","console","warn","middlewareModule","unstable_settings","matcher","warnInvalidMiddlewareMatcherSettings"],"mappings":"AAAA;;;;;CAKC;;;;+BAoBeA;;;eAAAA;;;;yBAhBqB;;;;;;;gEAEpB;;;;;;;gEACO;;;;;;qCAEM;qCACW;wBAKlC;wBACsB;;;;;;AAE7B,MAAMC,QAAQC,QAAQ,SAAS;AAExB,SAASF,6BACdG,WAAmB,EACnBC,OAY+D;IAE/D,IAAI,CAACC,sBA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AEJ;gBACF;YACF;YAEA,mEAAmE;YACnE,MAAMX,uBAAuBC,eAAI,CAACC,UAAU,CAACxB,MAAMV,IAAI,IACnDU,MAAMV,IAAI,GACViC,eAAI,CAACE,IAAI,CAAC7C,QAAQ8C,MAAM,EAAE1B,MAAMV,IAAI;YACxC,IAAI;oBAIG4C;gBAHLzD,MAAM,CAAC,wBAAwB,EAAE6C,sBAAsB;gBACvD,MAAMY,mBAAoB,MAAMtD,QAAQ+C,cAAc,CAACL;gBAEvD,KAAKY,sCAAAA,iBAAiBC,iBAAiB,qBAAnC,AAACD,oCAA2DE,OAAO,EAAE;wBAClCF;oBAArCG,IAAAA,4CAAoC,GAACH,uCAAAA,iBAAiBC,iBAAiB,qBAAlCD,qCAAoCE,OAAO;gBAClF;gBAEA,OAAOF;YACT,EAAE,OAAO9B,OAAY;gBACnB,OAAO,IAAIC,SACT,gCAAgCiB,uBAAuB,SAASlB,MAAMO,OAAO,EAC7E;oBACEH,QAAQ;oBACRC,SAAS;wBACP,gBAAgB;oBAClB;gBACF;YAEJ;QACF;IACF;AAEJ"}
|
|
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 */\n\nimport type { ProjectConfig } from '@expo/config';\nimport type { MiddlewareSettings } from 'expo-server';\nimport { createRequestHandler } from 'expo-server/adapter/http';\nimport { type RouteInfo } from 'expo-server/private';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { fetchManifest } from './fetchRouterManifest';\nimport { getErrorOverlayHtmlAsync } from './metroErrorInterface';\nimport {\n warnInvalidWebOutput,\n warnInvalidMiddlewareOutput,\n warnInvalidMiddlewareMatcherSettings,\n} from './router';\nimport { CommandError } from '../../../utils/errors';\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\nexport function createRouteHandlerMiddleware(\n projectRoot: string,\n options: {\n appDir: string;\n routerRoot: string;\n getStaticPageAsync: (\n pathname: string,\n route: RouteInfo<RegExp>\n ) => Promise<{ content: string }>;\n bundleApiRoute: (\n functionFilePath: string\n ) => Promise<null | Record<string, Function> | Response>;\n config: ProjectConfig;\n headers: Record<string, string | string[]>;\n } & import('@expo/router-server/build/routes-manifest').Options\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. Either install the expo-router package or change 'web.output' to 'single' in your app.json.`\n );\n }\n\n return createRequestHandler(\n { build: '' },\n {\n async getRoutesManifest() {\n const manifest = await fetchManifest(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 redirects: [],\n rewrites: [],\n }\n );\n },\n async getHtml(request, route) {\n try {\n const { content } = await options.getStaticPageAsync(request.url, route);\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\n try {\n return new Response(\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 debug('Failed to render static error overlay:', staticError);\n // Fallback error for when Expo Router is misconfigured in the project.\n return new Response(\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 async handleRouteError(error) {\n // NOTE(@kitten): ExpoError is currently not exposed by expo-server just yet\n if (error && typeof error === 'object' && error.name === 'ExpoError') {\n // TODO(@krystofwoldrich): Can we show code snippet of the handler?\n // NOTE(@krystofwoldrich): Removing stack since to avoid confusion. The error is not in the server code.\n delete error.stack;\n }\n\n const htmlServerError = await getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot: options.routerRoot!,\n });\n\n return new Response(htmlServerError, {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n },\n async getApiRoute(route) {\n const { exp } = options.config;\n if (exp.web?.output !== 'server') {\n warnInvalidWebOutput();\n }\n\n // TODO(@kitten): Unify with MetroBundlerDevServer#exportExpoRouterApiRoutesAsync\n const resolvedFunctionPath = path.isAbsolute(route.file)\n ? route.file\n : path.join(options.appDir, route.file);\n try {\n debug(`Bundling API route at: ${resolvedFunctionPath}`);\n return await options.bundleApiRoute(resolvedFunctionPath!);\n } catch (error: any) {\n return new Response(\n 'Failed to load API Route: ' + resolvedFunctionPath + '\\n\\n' + error.message,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n },\n async getMiddleware(route) {\n const { exp } = options.config;\n\n if (!options.unstable_useServerMiddleware) {\n return {\n default: () => {\n throw new CommandError(\n 'Server middleware is not enabled. Add unstable_useServerMiddleware: true to your `expo-router` plugin config.'\n );\n },\n };\n }\n\n if (exp.web?.output !== 'server') {\n warnInvalidMiddlewareOutput();\n return {\n default: () => {\n console.warn(\n 'Server middleware is only supported when web.output is set to \"server\" in your app config'\n );\n },\n };\n }\n\n // TODO(@kitten): Unify with MetroBundlerDevServer#exportMiddlewareAsync\n const resolvedFunctionPath = path.isAbsolute(route.file)\n ? route.file\n : path.join(options.appDir, route.file);\n try {\n debug(`Bundling middleware at: ${resolvedFunctionPath}`);\n const middlewareModule = (await options.bundleApiRoute(resolvedFunctionPath!)) as any;\n\n if ((middlewareModule.unstable_settings as MiddlewareSettings)?.matcher) {\n warnInvalidMiddlewareMatcherSettings(middlewareModule.unstable_settings?.matcher);\n }\n\n return middlewareModule;\n } catch (error: any) {\n return new Response(\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","projectRoot","options","resolveFrom","silent","CommandError","createRequestHandler","build","getRoutesManifest","manifest","fetchManifest","htmlRoutes","file","page","routeKeys","namedRegex","apiRoutes","notFoundRoutes","redirects","rewrites","getHtml","request","route","content","getStaticPageAsync","url","error","Response","getErrorOverlayHtmlAsync","routerRoot","status","headers","staticError","message","handleRouteError","name","stack","htmlServerError","getApiRoute","exp","config","web","output","warnInvalidWebOutput","resolvedFunctionPath","path","isAbsolute","join","appDir","bundleApiRoute","getMiddleware","unstable_useServerMiddleware","default","warnInvalidMiddlewareOutput","console","warn","middlewareModule","unstable_settings","matcher","warnInvalidMiddlewareMatcherSettings"],"mappings":"AAAA;;;;;CAKC;;;;+BAoBeA;;;eAAAA;;;;yBAhBqB;;;;;;;gEAEpB;;;;;;;gEACO;;;;;;qCAEM;qCACW;wBAKlC;wBACsB;;;;;;AAE7B,MAAMC,QAAQC,QAAQ,SAAS;AAExB,SAASF,6BACdG,WAAmB,EACnBC,OAY+D;IAE/D,IAAI,CAACC,sBAAW,CAACC,MAAM,CAACH,aAAa,gBAAgB;QACnD,MAAM,IAAII,oBAAY,CACpB,CAAC,yLAAyL,CAAC;IAE/L;IAEA,OAAOC,IAAAA,4BAAoB,EACzB;QAAEC,OAAO;IAAG,GACZ;QACE,MAAMC;YACJ,MAAMC,WAAW,MAAMC,IAAAA,kCAAa,EAACT,aAAaC;YAClDH,MAAM,YAAYU;YAClB,2BAA2B;YAC3B,6BAA6B;YAC7B,OACEA,YAAY;gBACV,uDAAuD;gBACvDE,YAAY;oBACV;wBACEC,MAAM;wBACNC,MAAM;wBACNC,WAAW,CAAC;wBACZC,YAAY;oBACd;iBACD;gBACDC,WAAW,EAAE;gBACbC,gBAAgB,EAAE;gBAClBC,WAAW,EAAE;gBACbC,UAAU,EAAE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ClF;gBAEA,OAAOF;YACT,EAAE,OAAO9B,OAAY;gBACnB,OAAO,IAAIC,SACT,gCAAgCiB,uBAAuB,SAASlB,MAAMO,OAAO,EAC7E;oBACEH,QAAQ;oBACRC,SAAS;wBACP,gBAAgB;oBAClB;gBACF;YAEJ;QACF;IACF;AAEJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/start/server/platformBundlers.ts"],"sourcesContent":["import type { ExpoConfig, Platform } from '@expo/config';\nimport resolveFrom from 'resolve-from';\n\n/** Which bundler each platform should use. */\nexport type PlatformBundlers = Record<Platform, 'metro' | 'webpack'>;\n\n
|
|
1
|
+
{"version":3,"sources":["../../../../src/start/server/platformBundlers.ts"],"sourcesContent":["import type { ExpoConfig, ExpoConfigWeb, Platform } from '@expo/config';\nimport resolveFrom from 'resolve-from';\n\n/** Which bundler each platform should use. */\nexport type PlatformBundlers = Record<Platform, 'metro' | 'webpack'>;\n\n/** XDL-schema doesn't have `ios.bundler` and `android.bundler`, since this is technically deprecated */\ntype WithBundlerConfig = Pick<ExpoConfigWeb, 'bundler'> | undefined | null;\n\n/** Get the platform bundlers mapping. */\nexport function getPlatformBundlers(\n projectRoot: string,\n exp: Partial<ExpoConfig>\n): PlatformBundlers {\n /**\n * SDK 50+: The web bundler is dynamic based upon the presence of the `@expo/webpack-config` package.\n */\n let web = exp.web?.bundler;\n if (!web) {\n const resolved = resolveFrom.silent(projectRoot, '@expo/webpack-config/package.json');\n web = resolved ? 'webpack' : 'metro';\n }\n\n return {\n ios: (exp.ios as WithBundlerConfig)?.bundler ?? 'metro',\n android: (exp.android as WithBundlerConfig)?.bundler ?? 'metro',\n web,\n };\n}\n"],"names":["getPlatformBundlers","projectRoot","exp","web","bundler","resolved","resolveFrom","silent","ios","android"],"mappings":";;;;+BAUgBA;;;eAAAA;;;;gEATQ;;;;;;;;;;;AASjB,SAASA,oBACdC,WAAmB,EACnBC,GAAwB;QAKdA,UAOFA,UACIA;IAXZ;;GAEC,GACD,IAAIC,OAAMD,WAAAA,IAAIC,GAAG,qBAAPD,SAASE,OAAO;IAC1B,IAAI,CAACD,KAAK;QACR,MAAME,WAAWC,sBAAW,CAACC,MAAM,CAACN,aAAa;QACjDE,MAAME,WAAW,YAAY;IAC/B;IAEA,OAAO;QACLG,KAAK,EAACN,WAAAA,IAAIM,GAAG,qBAAR,AAACN,SAA+BE,OAAO,KAAI;QAChDK,SAAS,EAACP,eAAAA,IAAIO,OAAO,qBAAZ,AAACP,aAAmCE,OAAO,KAAI;QACxDD;IACF;AACF"}
|
|
@@ -33,7 +33,7 @@ class FetchClient {
|
|
|
33
33
|
this.headers = {
|
|
34
34
|
accept: 'application/json',
|
|
35
35
|
'content-type': 'application/json',
|
|
36
|
-
'user-agent': `expo-cli/${"55.0.0-canary-
|
|
36
|
+
'user-agent': `expo-cli/${"55.0.0-canary-20251210-1f163e3"}`,
|
|
37
37
|
authorization: 'Basic ' + _nodebuffer().Buffer.from(`${target}:`).toString('base64')
|
|
38
38
|
};
|
|
39
39
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@expo/cli",
|
|
3
|
-
"version": "55.0.0-canary-
|
|
3
|
+
"version": "55.0.0-canary-20251210-1f163e3",
|
|
4
4
|
"description": "The Expo CLI",
|
|
5
5
|
"main": "build/bin/cli",
|
|
6
6
|
"bin": {
|
|
@@ -43,25 +43,25 @@
|
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@0no-co/graphql.web": "^1.0.8",
|
|
45
45
|
"@expo/code-signing-certificates": "^0.0.5",
|
|
46
|
-
"@expo/config": "12.0.12-canary-
|
|
47
|
-
"@expo/config-plugins": "54.0.4-canary-
|
|
46
|
+
"@expo/config": "12.0.12-canary-20251210-1f163e3",
|
|
47
|
+
"@expo/config-plugins": "54.0.4-canary-20251210-1f163e3",
|
|
48
48
|
"@expo/devcert": "^1.2.1",
|
|
49
|
-
"@expo/env": "2.0.9-canary-
|
|
50
|
-
"@expo/image-utils": "0.8.9-canary-
|
|
51
|
-
"@expo/json-file": "10.0.9-canary-
|
|
49
|
+
"@expo/env": "2.0.9-canary-20251210-1f163e3",
|
|
50
|
+
"@expo/image-utils": "0.8.9-canary-20251210-1f163e3",
|
|
51
|
+
"@expo/json-file": "10.0.9-canary-20251210-1f163e3",
|
|
52
52
|
"@expo/metro": "~54.1.0",
|
|
53
|
-
"@expo/metro-config": "54.1.0-canary-
|
|
54
|
-
"@expo/osascript": "2.3.9-canary-
|
|
55
|
-
"@expo/package-manager": "1.9.10-canary-
|
|
56
|
-
"@expo/plist": "0.4.9-canary-
|
|
57
|
-
"@expo/prebuild-config": "54.0.8-canary-
|
|
58
|
-
"@expo/router-server": "0.2.0-canary-
|
|
59
|
-
"@expo/log-box": "0.0.13-canary-
|
|
60
|
-
"@expo/schema-utils": "0.1.9-canary-
|
|
53
|
+
"@expo/metro-config": "54.1.0-canary-20251210-1f163e3",
|
|
54
|
+
"@expo/osascript": "2.3.9-canary-20251210-1f163e3",
|
|
55
|
+
"@expo/package-manager": "1.9.10-canary-20251210-1f163e3",
|
|
56
|
+
"@expo/plist": "0.4.9-canary-20251210-1f163e3",
|
|
57
|
+
"@expo/prebuild-config": "54.0.8-canary-20251210-1f163e3",
|
|
58
|
+
"@expo/router-server": "0.2.0-canary-20251210-1f163e3",
|
|
59
|
+
"@expo/log-box": "0.0.13-canary-20251210-1f163e3",
|
|
60
|
+
"@expo/schema-utils": "0.1.9-canary-20251210-1f163e3",
|
|
61
61
|
"@expo/spawn-async": "^1.7.2",
|
|
62
62
|
"@expo/ws-tunnel": "^1.0.1",
|
|
63
63
|
"@expo/xcpretty": "^4.3.0",
|
|
64
|
-
"@react-native/dev-middleware": "0.83.0-rc.
|
|
64
|
+
"@react-native/dev-middleware": "0.83.0-rc.5",
|
|
65
65
|
"@urql/core": "^5.0.6",
|
|
66
66
|
"@urql/exchange-retry": "^1.3.0",
|
|
67
67
|
"accepts": "^1.3.8",
|
|
@@ -75,7 +75,7 @@
|
|
|
75
75
|
"connect": "^3.7.0",
|
|
76
76
|
"debug": "^4.3.4",
|
|
77
77
|
"env-editor": "^0.4.1",
|
|
78
|
-
"expo-server": "1.0.6-canary-
|
|
78
|
+
"expo-server": "1.0.6-canary-20251210-1f163e3",
|
|
79
79
|
"freeport-async": "^2.0.0",
|
|
80
80
|
"getenv": "^2.0.0",
|
|
81
81
|
"glob": "^13.0.0",
|
|
@@ -112,8 +112,8 @@
|
|
|
112
112
|
]
|
|
113
113
|
},
|
|
114
114
|
"peerDependencies": {
|
|
115
|
-
"expo": "55.0.0-canary-
|
|
116
|
-
"expo-router": "7.0.0-canary-
|
|
115
|
+
"expo": "55.0.0-canary-20251210-1f163e3",
|
|
116
|
+
"expo-router": "7.0.0-canary-20251210-1f163e3",
|
|
117
117
|
"react-native": "*"
|
|
118
118
|
},
|
|
119
119
|
"peerDependenciesMeta": {
|
|
@@ -158,7 +158,7 @@
|
|
|
158
158
|
"@types/ws": "^8.5.4",
|
|
159
159
|
"devtools-protocol": "^0.0.1113120",
|
|
160
160
|
"expo-atlas": "^0.4.1",
|
|
161
|
-
"expo-module-scripts": "5.1.0-canary-
|
|
161
|
+
"expo-module-scripts": "5.1.0-canary-20251210-1f163e3",
|
|
162
162
|
"find-process": "^1.4.7",
|
|
163
163
|
"jest-runner-tsd": "^6.0.0",
|
|
164
164
|
"klaw-sync": "^6.0.0",
|