@expo/cli 55.0.0-canary-20251127-587bc53 → 55.0.0-canary-20251205-756eb7a
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/add-module.js +4 -1
- package/build/bin/cli +1 -1
- package/build/src/export/embed/exportEmbedAsync.js +17 -13
- package/build/src/export/embed/exportEmbedAsync.js.map +1 -1
- package/build/src/export/exportApp.js +0 -1
- package/build/src/export/exportApp.js.map +1 -1
- package/build/src/prebuild/resolveLocalTemplate.js +34 -2
- package/build/src/prebuild/resolveLocalTemplate.js.map +1 -1
- package/build/src/run/ios/options/promptDevice.js.map +1 -1
- package/build/src/run/ios/options/resolveDevice.js +1 -3
- package/build/src/run/ios/options/resolveDevice.js.map +1 -1
- package/build/src/start/server/MCP.js +13 -1
- package/build/src/start/server/MCP.js.map +1 -1
- package/build/src/start/server/getStaticRenderFunctions.js +0 -2
- package/build/src/start/server/getStaticRenderFunctions.js.map +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +10 -15
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/createServerComponentsMiddleware.js.map +1 -1
- package/build/src/start/server/metro/createServerRouteMiddleware.js.map +1 -1
- package/build/src/start/server/metro/debugging/MessageHandler.js +0 -2
- package/build/src/start/server/metro/debugging/MessageHandler.js.map +1 -1
- package/build/src/start/server/metro/debugging/pageIsSupported.js +0 -1
- package/build/src/start/server/metro/debugging/pageIsSupported.js.map +1 -1
- package/build/src/start/server/metro/externals.js +1 -2
- package/build/src/start/server/metro/externals.js.map +1 -1
- package/build/src/start/server/metro/fetchRouterManifest.js +2 -3
- package/build/src/start/server/metro/fetchRouterManifest.js.map +1 -1
- package/build/src/start/server/metro/instantiateMetro.js +9 -11
- package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
- package/build/src/start/server/metro/withMetroErrorReportingResolver.js +0 -1
- package/build/src/start/server/metro/withMetroErrorReportingResolver.js.map +1 -1
- package/build/src/start/server/metro/withMetroMultiPlatform.js +12 -16
- package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
- package/build/src/start/server/middleware/DataLoaderModuleMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.js +0 -1
- package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.js.map +1 -1
- package/build/src/start/server/middleware/metroOptions.js +19 -4
- package/build/src/start/server/middleware/metroOptions.js.map +1 -1
- package/build/src/start/server/platformBundlers.js +0 -2
- package/build/src/start/server/platformBundlers.js.map +1 -1
- package/build/src/start/server/serverLogLikeMetro.js +18 -18
- package/build/src/start/server/serverLogLikeMetro.js.map +1 -1
- package/build/src/start/server/webpack/WebpackBundlerDevServer.js +2 -2
- package/build/src/start/server/webpack/WebpackBundlerDevServer.js.map +1 -1
- package/build/src/start/startAsync.js +5 -5
- package/build/src/start/startAsync.js.map +1 -1
- package/build/src/utils/downloadExpoGoAsync.js +0 -1
- package/build/src/utils/downloadExpoGoAsync.js.map +1 -1
- package/build/src/utils/errors.js.map +1 -1
- package/build/src/utils/exit.js +1 -2
- package/build/src/utils/exit.js.map +1 -1
- package/build/src/utils/nodeEnv.js +0 -1
- package/build/src/utils/nodeEnv.js.map +1 -1
- package/build/src/utils/npm.js +31 -0
- package/build/src/utils/npm.js.map +1 -1
- package/build/src/utils/plist.js +0 -1
- package/build/src/utils/plist.js.map +1 -1
- package/build/src/utils/progress.js +3 -4
- package/build/src/utils/progress.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 +21 -20
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/createServerComponentsMiddleware.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 { getMetroServerRoot } from '@expo/config/paths';\nimport type { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport type { EntriesDev } from '@expo/router-server/build/rsc/server';\nimport assert from 'assert';\nimport { getRscMiddleware } from 'expo-server/private';\nimport path from 'node:path';\nimport url from 'node:url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport type { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n type ExpoMetroOptions,\n getMetroOptionsFromUrl,\n} from '../middleware/metroOptions';\n\nconst debug = require('debug')('expo:rsc') as typeof console.log;\n\ntype SSRLoadModuleArtifactsFunc = (\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>\n) => Promise<{ artifacts: SerialAsset[]; src: string }>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\nconst getMetroServerRootMemo = memoize(getMetroServerRoot);\n\nexport function createServerComponentsMiddleware(\n projectRoot: string,\n {\n rscPath,\n instanceMetroOptions,\n ssrLoadModule,\n ssrLoadModuleArtifacts,\n useClientRouter,\n createModuleId,\n routerOptions,\n }: {\n rscPath: string;\n instanceMetroOptions: Partial<ExpoMetroOptions>;\n ssrLoadModule: SSRLoadModuleFunc;\n ssrLoadModuleArtifacts: SSRLoadModuleArtifactsFunc;\n useClientRouter: boolean;\n createModuleId: (\n filePath: string,\n context: { platform: string; environment: string }\n ) => string | number;\n routerOptions: Record<string, any>;\n }\n) {\n const routerModule = useClientRouter\n ? '@expo/router-server/build/rsc/router/noopRouter'\n : '@expo/router-server/build/rsc/router/expo-definedRouter';\n\n const rscMiddleware = getRscMiddleware({\n config: {},\n // Disabled in development\n baseUrl: '',\n rscPath,\n onError: console.error,\n renderRsc: async (args) => {\n // In development we should add simulated versions of common production headers.\n if (args.headers['x-real-ip'] == null) {\n args.headers['x-real-ip'] = getIpAddress();\n }\n if (args.headers['x-forwarded-for'] == null) {\n args.headers['x-forwarded-for'] = args.headers['x-real-ip'];\n }\n if (args.headers['x-forwarded-proto'] == null) {\n args.headers['x-forwarded-proto'] = 'http';\n }\n\n // Dev server-only implementation.\n try {\n return await renderRscToReadableStream({\n ...args,\n headers: new Headers(args.headers),\n body: args.body!,\n routerOptions,\n });\n } catch (error: any) {\n // If you get a codeFrame error during SSR like when using a Class component in React Server Components, then this\n // will throw with:\n // {\n // rawObject: {\n // type: 'TransformError',\n // lineNumber: 0,\n // errors: [ [Object] ],\n // name: 'SyntaxError',\n // message: '...',\n // }\n // }\n\n // TODO: Revisit all error handling now that we do direct metro bundling...\n await logMetroError(projectRoot, { error });\n\n if (error[IS_METRO_BUNDLE_ERROR_SYMBOL]) {\n throw new Response(JSON.stringify(error), {\n status: isPossiblyUnableToResolveError(error) ? 404 : 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n const sanitizedServerMessage = stripAnsi(error.message) ?? error.message;\n throw new Response(sanitizedServerMessage, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n }\n },\n });\n\n let rscPathPrefix = rscPath;\n if (rscPathPrefix !== '/') {\n rscPathPrefix += '/';\n }\n\n async function exportServerActionsAsync(\n {\n platform,\n entryPoints,\n domRoot,\n }: { platform: string; entryPoints: string[]; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n clientBoundaries: string[];\n manifest: Record<string, [string, string]>;\n }> {\n const uniqueEntryPoints = [...new Set(entryPoints)];\n // TODO: Support multiple entry points in a single split server bundle...\n const manifest: Record<string, [string, string]> = {};\n const nestedClientBoundaries: string[] = [];\n const nestedServerBoundaries: string[] = [];\n const processedEntryPoints = new Set<string>();\n async function processEntryPoint(entryPoint: string) {\n processedEntryPoints.add(entryPoint);\n\n const contents = await ssrLoadModuleArtifacts(entryPoint, {\n environment: 'react-server',\n platform,\n // Ignore the metro runtime to avoid overwriting the original in the API route.\n modulesOnly: true,\n // Required\n runModule: true,\n // Required to ensure assets load as client boundaries.\n domRoot,\n });\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactClientReferences) {\n nestedClientBoundaries.push(...reactClientReferences!);\n }\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactServerReferences) {\n nestedServerBoundaries.push(...reactServerReferences!);\n }\n\n // Naive check to ensure the module runtime is not included in the server action bundle.\n if (contents.src.includes('The experimental Metro feature')) {\n throw new Error(\n 'Internal error: module runtime should not be included in server action bundles: ' +\n entryPoint\n );\n }\n\n const relativeName = createModuleId(entryPoint, {\n platform,\n environment: 'react-server',\n });\n const safeName = path.basename(contents.artifacts.find((a) => a.type === 'js')!.filename!);\n\n const outputName = `_expo/rsc/${platform}/${safeName}`;\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(outputName, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n // Match babel plugin.\n const publicModuleId = './' + toPosixPath(path.relative(projectRoot, entryPoint));\n\n // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[publicModuleId] = [String(relativeName), outputName];\n }\n\n async function processEntryPoints(entryPoints: string[], recursions = 0) {\n // Arbitrary recursion limit to prevent infinite loops.\n if (recursions > 10) {\n throw new Error('Recursion limit exceeded while processing server boundaries');\n }\n\n for (const entryPoint of entryPoints) {\n await processEntryPoint(entryPoint);\n }\n\n // When a server action has other server actions inside of it, we need to process those as well to ensure all entry points are in the manifest and accounted for.\n let uniqueNestedServerBoundaries = [...new Set(nestedServerBoundaries)];\n // Filter out values that have already been processed.\n uniqueNestedServerBoundaries = uniqueNestedServerBoundaries.filter(\n (value) => !processedEntryPoints.has(value)\n );\n if (uniqueNestedServerBoundaries.length) {\n debug('bundling nested server action boundaries', uniqueNestedServerBoundaries);\n return processEntryPoints(uniqueNestedServerBoundaries, recursions + 1);\n }\n }\n\n await processEntryPoints(uniqueEntryPoints);\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/${platform}/action-manifest.js`, {\n targetDomain: 'server',\n contents: 'module.exports = ' + JSON.stringify(manifest),\n });\n\n return { manifest, clientBoundaries: nestedClientBoundaries };\n }\n\n async function getExpoRouterClientReferencesAsync(\n { platform, domRoot }: { platform: string; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n reactClientReferences: string[];\n reactServerReferences: string[];\n cssModules: SerialAsset[];\n }> {\n const contents = await ssrLoadModuleArtifacts(routerModule, {\n environment: 'react-server',\n platform,\n modulesOnly: true,\n domRoot,\n });\n\n // Extract the global CSS modules that are imported from the router.\n // These will be injected in the head of the HTML document for the website.\n const cssModules = contents.artifacts.filter((a) => a.type.startsWith('css'));\n\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactServerReferences) {\n throw new Error(\n 'Static server action references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactServerReferences);\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactClientReferences) {\n throw new Error(\n 'Static client references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactClientReferences);\n\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(`_expo/rsc/${platform}/router.js`, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n return { reactClientReferences, reactServerReferences, cssModules };\n }\n\n const routerCache = new Map<string, EntriesDev>();\n\n async function getExpoRouterRscEntriesGetterAsync({\n platform,\n routerOptions,\n }: {\n platform: string;\n routerOptions: Record<string, any>;\n }) {\n await ensureMemo();\n // We can only cache this if we're using the client router since it doesn't change or use HMR\n if (routerCache.has(platform) && useClientRouter) {\n return routerCache.get(platform)!;\n }\n\n const router = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/router/expo-definedRouter')\n >(\n routerModule,\n {\n environment: 'react-server',\n modulesOnly: true,\n platform,\n },\n {\n hot: !useClientRouter,\n }\n );\n\n const entries = router.default({\n redirects: routerOptions?.redirects,\n rewrites: routerOptions?.rewrites,\n });\n\n routerCache.set(platform, entries);\n return entries;\n }\n\n function getResolveClientEntry(context: {\n platform: string;\n engine?: 'hermes' | null;\n ssrManifest?: Map<string, string>;\n }): (\n file: string,\n isServer: boolean\n ) => {\n id: string;\n chunks: string[];\n } {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n const {\n mode,\n minify = false,\n isExporting,\n baseUrl,\n routerRoot,\n asyncRoutes,\n preserveEnvVars,\n reactCompiler,\n lazy,\n } = instanceMetroOptions;\n\n assert(\n isExporting != null &&\n baseUrl != null &&\n mode != null &&\n routerRoot != null &&\n asyncRoutes != null,\n `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`\n );\n\n return (file: string, isServer: boolean) => {\n const filePath = path.join(\n projectRoot,\n file.startsWith('file://') ? fileURLToFilePath(file) : file\n );\n\n if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n\n const relativeFilePath = toPosixPath(path.relative(serverRoot, filePath));\n\n assert(\n context.ssrManifest.has(relativeFilePath),\n `SSR manifest is missing client boundary \"${relativeFilePath}\"`\n );\n\n const chunk = context.ssrManifest.get(relativeFilePath);\n\n return {\n id: String(\n createModuleId(filePath, { platform: context.platform, environment: 'client' })\n ),\n chunks: chunk != null ? [chunk] : [],\n };\n }\n\n const environment = isServer ? 'react-server' : 'client';\n const searchParams = createBundleUrlSearchParams({\n mainModuleName: '',\n platform: context.platform,\n mode,\n minify,\n lazy,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n reactCompiler: !!reactCompiler,\n engine: context.engine ?? undefined,\n bytecode: false,\n clientBoundaries: [],\n inlineSourceMap: false,\n environment,\n modulesOnly: true,\n runModule: false,\n });\n\n searchParams.set('resolver.clientboundary', String(true));\n\n const clientReferenceUrl = new URL('http://a');\n\n // TICKLE: Handshake 1\n searchParams.set('xRSC', '1');\n\n clientReferenceUrl.search = searchParams.toString();\n\n const relativeFilePath = path.relative(serverRoot, filePath);\n\n clientReferenceUrl.pathname = relativeFilePath;\n\n // Ensure url.pathname ends with '.bundle'\n if (!clientReferenceUrl.pathname.endsWith('.bundle')) {\n clientReferenceUrl.pathname += '.bundle';\n }\n\n // Return relative URLs to help Android fetch from wherever it was loaded from since it doesn't support localhost.\n const chunkName = clientReferenceUrl.pathname + clientReferenceUrl.search;\n\n return {\n id: String(createModuleId(filePath, { platform: context.platform, environment })),\n chunks: [chunkName],\n };\n };\n }\n\n const rscRendererCache = new Map<\n string,\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >();\n\n let ensurePromise: Promise<any> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n const runtime = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >('metro-runtime/src/modules/empty-module.js', {\n environment: 'react-server',\n platform: 'web',\n });\n return runtime;\n }\n const ensureMemo = () => {\n ensurePromise ??= ensureSSRReady();\n return ensurePromise;\n };\n\n async function getRscRendererAsync(platform: string) {\n await ensureMemo();\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRendererCache.has(platform)) {\n return rscRendererCache.get(platform)!;\n }\n\n // TODO: Extract CSS Modules / Assets from the bundler process\n const renderer = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >('@expo/router-server/build/rsc/rsc-renderer', {\n environment: 'react-server',\n platform,\n });\n\n rscRendererCache.set(platform, renderer);\n return renderer;\n }\n\n const rscRenderContext = new Map<string, any>();\n\n function getRscRenderContext(platform: string) {\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRenderContext.has(platform)) {\n return rscRenderContext.get(platform)!;\n }\n\n const context = {};\n\n rscRenderContext.set(platform, context);\n return context;\n }\n\n async function renderRscToReadableStream(\n {\n input,\n headers,\n method,\n platform,\n body,\n engine,\n contentType,\n ssrManifest,\n decodedBody,\n routerOptions,\n }: {\n input: string;\n headers: Headers;\n method: 'POST' | 'GET';\n platform: string;\n body?: ReadableStream<Uint8Array>;\n engine?: 'hermes' | null;\n contentType?: string;\n ssrManifest?: Map<string, string>;\n decodedBody?: unknown;\n routerOptions: Record<string, any>;\n },\n isExporting: boolean | undefined = instanceMetroOptions.isExporting\n ) {\n assert(\n isExporting != null,\n 'The server must be started before calling renderRscToReadableStream.'\n );\n\n if (method === 'POST') {\n assert(body, 'Server request must be provided when method is POST (server actions)');\n }\n\n const context = getRscRenderContext(platform);\n\n context['__expo_requestHeaders'] = headers;\n\n const { renderRsc } = await getRscRendererAsync(platform);\n\n return renderRsc(\n {\n body,\n decodedBody,\n context,\n config: {},\n input,\n contentType,\n },\n {\n isExporting,\n entries: await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions }),\n resolveClientEntry: getResolveClientEntry({ platform, engine, ssrManifest }),\n async loadServerModuleRsc(urlFragment) {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n debug('[SSR] loadServerModuleRsc:', urlFragment);\n\n const options = getMetroOptionsFromUrl(urlFragment);\n\n return ssrLoadModule(\n path.join(serverRoot, options.mainModuleName),\n\n options,\n {\n hot: true,\n }\n );\n },\n }\n );\n }\n\n return {\n // Get the static client boundaries (no dead code elimination allowed) for the production export.\n getExpoRouterClientReferencesAsync,\n exportServerActionsAsync,\n\n async exportRoutesAsync(\n {\n platform,\n ssrManifest,\n routerOptions,\n }: {\n platform: string;\n ssrManifest: Map<string, string>;\n routerOptions: Record<string, any>;\n },\n files: ExportAssetMap\n ) {\n // TODO: When we add web SSR support, we need to extract CSS Modules / Assets from the bundler process to prevent FLOUC.\n const { getBuildConfig } = (\n await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions })\n ).default;\n\n // Get all the routes to render.\n const buildConfig = await getBuildConfig!(async () =>\n // TODO: Rework prefetching code to use Metro runtime.\n []\n );\n\n await Promise.all(\n Array.from(buildConfig).map(async ({ entries }) => {\n for (const { input, isStatic } of entries || []) {\n if (!isStatic) {\n debug('Skipping static export for route', { input });\n continue;\n }\n const destRscFile = path.join('_flight', platform, encodeInput(input));\n\n const pipe = await renderRscToReadableStream(\n {\n input,\n method: 'GET',\n platform,\n headers: new Headers(),\n ssrManifest,\n routerOptions,\n },\n true\n );\n\n const rsc = await streamToStringAsync(pipe);\n debug('RSC Payload', { platform, input, rsc });\n\n files.set(destRscFile, {\n contents: rsc,\n targetDomain: 'client',\n rscId: input,\n });\n }\n })\n );\n },\n\n middleware: createBuiltinAPIRequestHandler(\n // Match `/_flight/[platform]/[...path]`\n (req) => {\n return getFullUrl(req.url).pathname.startsWith(rscPathPrefix);\n },\n rscMiddleware\n ),\n onReloadRscEvent: (platform: string) => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n rscRendererCache.delete(platform);\n routerCache.delete(platform);\n },\n };\n}\n\nconst getFullUrl = (url: string) => {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'http://localhost:0');\n }\n};\n\nexport const fileURLToFilePath = (fileURL: string) => {\n try {\n return url.fileURLToPath(fileURL);\n } catch (error) {\n if (error instanceof TypeError) {\n throw Error(`Invalid URL: ${fileURL}`, { cause: error });\n }\n throw error;\n }\n};\n\nconst encodeInput = (input: string) => {\n if (input === '') {\n return 'index.txt';\n }\n if (input === 'index') {\n throw new Error('Input should not be `index`');\n }\n if (input.startsWith('/')) {\n throw new Error('Input should not start with `/`');\n }\n if (input.endsWith('/')) {\n throw new Error('Input should not end with `/`');\n }\n return input + '.txt';\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"],"names":["createServerComponentsMiddleware","fileURLToFilePath","debug","require","getMetroServerRootMemo","memoize","getMetroServerRoot","projectRoot","rscPath","instanceMetroOptions","ssrLoadModule","ssrLoadModuleArtifacts","useClientRouter","createModuleId","routerOptions","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","IS_METRO_BUNDLE_ERROR_SYMBOL","Response","JSON","stringify","status","isPossiblyUnableToResolveError","sanitizedServerMessage","stripAnsi","message","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","nestedServerBoundaries","processedEntryPoints","processEntryPoint","entryPoint","contents","add","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","reactServerReferences","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","publicModuleId","toPosixPath","relative","String","processEntryPoints","recursions","uniqueNestedServerBoundaries","value","has","length","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","routerCache","Map","getExpoRouterRscEntriesGetterAsync","ensureMemo","get","router","hot","entries","default","redirects","rewrites","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","filePath","join","ssrManifest","relativeFilePath","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","runtime","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","TypeError","cause","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAqmBHC,iBAAiB;eAAjBA;;;;yBA3oBsB;;;;;;;gEAGhB;;;;;;;yBACc;;;;;;;gEAChB;;;;;;;gEACD;;;;;;qCAE4C;qCACb;sBAErB;0BACE;oBACJ;oBACK;wBACO;gDACW;8BAKxC;;;;;;AAEP,MAAMC,QAAQC,QAAQ,SAAS;AAa/B,MAAMC,yBAAyBC,IAAAA,WAAO,EAACC,2BAAkB;AAElD,SAASN,iCACdO,WAAmB,EACnB,EACEC,OAAO,EACPC,oBAAoB,EACpBC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,EACfC,cAAc,EACdC,aAAa,EAYd;IAED,MAAMC,eAAeH,kBACjB,oDACA;IAEJ,MAAMI,gBAAgBC,IAAAA,2BAAgB,EAAC;QACrCC,QAAQ,CAAC;QACT,0BAA0B;QAC1BC,SAAS;QACTX;QACAY,SAASC,QAAQC,KAAK;QACtBC,WAAW,OAAOC;YAChB,gFAAgF;YAChF,IAAIA,KAAKC,OAAO,CAAC,YAAY,IAAI,MAAM;gBACrCD,KAAKC,OAAO,CAAC,YAAY,GAAGC,IAAAA,gBAAY;YAC1C;YACA,IAAIF,KAAKC,OAAO,CAAC,kBAAkB,IAAI,MAAM;gBAC3CD,KAAKC,OAAO,CAAC,kBAAkB,GAAGD,KAAKC,OAAO,CAAC,YAAY;YAC7D;YACA,IAAID,KA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A,MAAMsI,aAAa,CAACC;IAClB,IAAI;QACF,OAAO,IAAIzC,IAAIyC;IACjB,EAAE,OAAM;QACN,OAAO,IAAIzC,IAAIyC,KAAK;IACtB;AACF;AAEO,MAAMhL,oBAAoB,CAACmL;IAChC,IAAI;QACF,OAAOH,kBAAG,CAACI,aAAa,CAACD;IAC3B,EAAE,OAAO9J,OAAO;QACd,IAAIA,iBAAiBgK,WAAW;YAC9B,MAAM/G,MAAM,CAAC,aAAa,EAAE6G,SAAS,EAAE;gBAAEG,OAAOjK;YAAM;QACxD;QACA,MAAMA;IACR;AACF;AAEA,MAAMkJ,cAAc,CAAClB;IACnB,IAAIA,UAAU,IAAI;QAChB,OAAO;IACT;IACA,IAAIA,UAAU,SAAS;QACrB,MAAM,IAAI/E,MAAM;IAClB;IACA,IAAI+E,MAAMvD,UAAU,CAAC,MAAM;QACzB,MAAM,IAAIxB,MAAM;IAClB;IACA,IAAI+E,MAAMV,QAAQ,CAAC,MAAM;QACvB,MAAM,IAAIrE,MAAM;IAClB;IACA,OAAO+E,QAAQ;AACjB;AAEA,SAASrE,WAAWuG,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAIC,OAAO,CAAC,oBAAoB;AACzC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/createServerComponentsMiddleware.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 { getMetroServerRoot } from '@expo/config/paths';\nimport type { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport type { EntriesDev } from '@expo/router-server/build/rsc/server';\nimport assert from 'assert';\nimport { getRscMiddleware } from 'expo-server/private';\nimport path from 'node:path';\nimport url from 'node:url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport type { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n type ExpoMetroOptions,\n getMetroOptionsFromUrl,\n} from '../middleware/metroOptions';\n\nconst debug = require('debug')('expo:rsc') as typeof console.log;\n\ntype SSRLoadModuleArtifactsFunc = (\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>\n) => Promise<{ artifacts: SerialAsset[]; src: string }>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\nconst getMetroServerRootMemo = memoize(getMetroServerRoot);\n\nexport function createServerComponentsMiddleware(\n projectRoot: string,\n {\n rscPath,\n instanceMetroOptions,\n ssrLoadModule,\n ssrLoadModuleArtifacts,\n useClientRouter,\n createModuleId,\n routerOptions,\n }: {\n rscPath: string;\n instanceMetroOptions: Partial<ExpoMetroOptions>;\n ssrLoadModule: SSRLoadModuleFunc;\n ssrLoadModuleArtifacts: SSRLoadModuleArtifactsFunc;\n useClientRouter: boolean;\n createModuleId: (\n filePath: string,\n context: { platform: string; environment: string }\n ) => string | number;\n routerOptions: Record<string, any>;\n }\n) {\n const routerModule = useClientRouter\n ? '@expo/router-server/build/rsc/router/noopRouter'\n : '@expo/router-server/build/rsc/router/expo-definedRouter';\n\n const rscMiddleware = getRscMiddleware({\n config: {},\n // Disabled in development\n baseUrl: '',\n rscPath,\n onError: console.error,\n renderRsc: async (args) => {\n // In development we should add simulated versions of common production headers.\n if (args.headers['x-real-ip'] == null) {\n args.headers['x-real-ip'] = getIpAddress();\n }\n if (args.headers['x-forwarded-for'] == null) {\n args.headers['x-forwarded-for'] = args.headers['x-real-ip'];\n }\n if (args.headers['x-forwarded-proto'] == null) {\n args.headers['x-forwarded-proto'] = 'http';\n }\n\n // Dev server-only implementation.\n try {\n return await renderRscToReadableStream({\n ...args,\n headers: new Headers(args.headers),\n body: args.body!,\n routerOptions,\n });\n } catch (error: any) {\n // If you get a codeFrame error during SSR like when using a Class component in React Server Components, then this\n // will throw with:\n // {\n // rawObject: {\n // type: 'TransformError',\n // lineNumber: 0,\n // errors: [ [Object] ],\n // name: 'SyntaxError',\n // message: '...',\n // }\n // }\n\n // TODO: Revisit all error handling now that we do direct metro bundling...\n await logMetroError(projectRoot, { error });\n\n if (error[IS_METRO_BUNDLE_ERROR_SYMBOL]) {\n throw new Response(JSON.stringify(error), {\n status: isPossiblyUnableToResolveError(error) ? 404 : 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n const sanitizedServerMessage = stripAnsi(error.message) ?? error.message;\n throw new Response(sanitizedServerMessage, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n }\n },\n });\n\n let rscPathPrefix = rscPath;\n if (rscPathPrefix !== '/') {\n rscPathPrefix += '/';\n }\n\n async function exportServerActionsAsync(\n {\n platform,\n entryPoints,\n domRoot,\n }: { platform: string; entryPoints: string[]; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n clientBoundaries: string[];\n manifest: Record<string, [string, string]>;\n }> {\n const uniqueEntryPoints = [...new Set(entryPoints)];\n // TODO: Support multiple entry points in a single split server bundle...\n const manifest: Record<string, [string, string]> = {};\n const nestedClientBoundaries: string[] = [];\n const nestedServerBoundaries: string[] = [];\n const processedEntryPoints = new Set<string>();\n async function processEntryPoint(entryPoint: string) {\n processedEntryPoints.add(entryPoint);\n\n const contents = await ssrLoadModuleArtifacts(entryPoint, {\n environment: 'react-server',\n platform,\n // Ignore the metro runtime to avoid overwriting the original in the API route.\n modulesOnly: true,\n // Required\n runModule: true,\n // Required to ensure assets load as client boundaries.\n domRoot,\n });\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactClientReferences) {\n nestedClientBoundaries.push(...reactClientReferences!);\n }\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactServerReferences) {\n nestedServerBoundaries.push(...reactServerReferences!);\n }\n\n // Naive check to ensure the module runtime is not included in the server action bundle.\n if (contents.src.includes('The experimental Metro feature')) {\n throw new Error(\n 'Internal error: module runtime should not be included in server action bundles: ' +\n entryPoint\n );\n }\n\n const relativeName = createModuleId(entryPoint, {\n platform,\n environment: 'react-server',\n });\n const safeName = path.basename(contents.artifacts.find((a) => a.type === 'js')!.filename!);\n\n const outputName = `_expo/rsc/${platform}/${safeName}`;\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(outputName, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n // Match babel plugin.\n const publicModuleId = './' + toPosixPath(path.relative(projectRoot, entryPoint));\n\n // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[publicModuleId] = [String(relativeName), outputName];\n }\n\n async function processEntryPoints(entryPoints: string[], recursions = 0) {\n // Arbitrary recursion limit to prevent infinite loops.\n if (recursions > 10) {\n throw new Error('Recursion limit exceeded while processing server boundaries');\n }\n\n for (const entryPoint of entryPoints) {\n await processEntryPoint(entryPoint);\n }\n\n // When a server action has other server actions inside of it, we need to process those as well to ensure all entry points are in the manifest and accounted for.\n let uniqueNestedServerBoundaries = [...new Set(nestedServerBoundaries)];\n // Filter out values that have already been processed.\n uniqueNestedServerBoundaries = uniqueNestedServerBoundaries.filter(\n (value) => !processedEntryPoints.has(value)\n );\n if (uniqueNestedServerBoundaries.length) {\n debug('bundling nested server action boundaries', uniqueNestedServerBoundaries);\n return processEntryPoints(uniqueNestedServerBoundaries, recursions + 1);\n }\n }\n\n await processEntryPoints(uniqueEntryPoints);\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/${platform}/action-manifest.js`, {\n targetDomain: 'server',\n contents: 'module.exports = ' + JSON.stringify(manifest),\n });\n\n return { manifest, clientBoundaries: nestedClientBoundaries };\n }\n\n async function getExpoRouterClientReferencesAsync(\n { platform, domRoot }: { platform: string; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n reactClientReferences: string[];\n reactServerReferences: string[];\n cssModules: SerialAsset[];\n }> {\n const contents = await ssrLoadModuleArtifacts(routerModule, {\n environment: 'react-server',\n platform,\n modulesOnly: true,\n domRoot,\n });\n\n // Extract the global CSS modules that are imported from the router.\n // These will be injected in the head of the HTML document for the website.\n const cssModules = contents.artifacts.filter((a) => a.type.startsWith('css'));\n\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactServerReferences) {\n throw new Error(\n 'Static server action references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactServerReferences);\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactClientReferences) {\n throw new Error(\n 'Static client references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactClientReferences);\n\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(`_expo/rsc/${platform}/router.js`, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n return { reactClientReferences, reactServerReferences, cssModules };\n }\n\n const routerCache = new Map<string, EntriesDev>();\n\n async function getExpoRouterRscEntriesGetterAsync({\n platform,\n routerOptions,\n }: {\n platform: string;\n routerOptions: Record<string, any>;\n }) {\n await ensureMemo();\n // We can only cache this if we're using the client router since it doesn't change or use HMR\n if (routerCache.has(platform) && useClientRouter) {\n return routerCache.get(platform)!;\n }\n\n const router = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/router/expo-definedRouter')\n >(\n routerModule,\n {\n environment: 'react-server',\n modulesOnly: true,\n platform,\n },\n {\n hot: !useClientRouter,\n }\n );\n\n const entries = router.default({\n redirects: routerOptions?.redirects,\n rewrites: routerOptions?.rewrites,\n });\n\n routerCache.set(platform, entries);\n return entries;\n }\n\n function getResolveClientEntry(context: {\n platform: string;\n engine?: 'hermes' | null;\n ssrManifest?: Map<string, string | null>;\n }): (\n file: string,\n isServer: boolean\n ) => {\n id: string;\n chunks: string[];\n } {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n const {\n mode,\n minify = false,\n isExporting,\n baseUrl,\n routerRoot,\n asyncRoutes,\n preserveEnvVars,\n reactCompiler,\n lazy,\n } = instanceMetroOptions;\n\n assert(\n isExporting != null &&\n baseUrl != null &&\n mode != null &&\n routerRoot != null &&\n asyncRoutes != null,\n `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`\n );\n\n return (file: string, isServer: boolean) => {\n const filePath = path.join(\n projectRoot,\n file.startsWith('file://') ? fileURLToFilePath(file) : file\n );\n\n if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n\n const relativeFilePath = toPosixPath(path.relative(serverRoot, filePath));\n\n assert(\n context.ssrManifest.has(relativeFilePath),\n `SSR manifest is missing client boundary \"${relativeFilePath}\"`\n );\n\n const chunk = context.ssrManifest.get(relativeFilePath);\n\n return {\n id: String(\n createModuleId(filePath, { platform: context.platform, environment: 'client' })\n ),\n chunks: chunk != null ? [chunk] : [],\n };\n }\n\n const environment = isServer ? 'react-server' : 'client';\n const searchParams = createBundleUrlSearchParams({\n mainModuleName: '',\n platform: context.platform,\n mode,\n minify,\n lazy,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n reactCompiler: !!reactCompiler,\n engine: context.engine ?? undefined,\n bytecode: false,\n clientBoundaries: [],\n inlineSourceMap: false,\n environment,\n modulesOnly: true,\n runModule: false,\n });\n\n searchParams.set('resolver.clientboundary', String(true));\n\n const clientReferenceUrl = new URL('http://a');\n\n // TICKLE: Handshake 1\n searchParams.set('xRSC', '1');\n\n clientReferenceUrl.search = searchParams.toString();\n\n const relativeFilePath = path.relative(serverRoot, filePath);\n\n clientReferenceUrl.pathname = relativeFilePath;\n\n // Ensure url.pathname ends with '.bundle'\n if (!clientReferenceUrl.pathname.endsWith('.bundle')) {\n clientReferenceUrl.pathname += '.bundle';\n }\n\n // Return relative URLs to help Android fetch from wherever it was loaded from since it doesn't support localhost.\n const chunkName = clientReferenceUrl.pathname + clientReferenceUrl.search;\n\n return {\n id: String(createModuleId(filePath, { platform: context.platform, environment })),\n chunks: [chunkName],\n };\n };\n }\n\n const rscRendererCache = new Map<\n string,\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >();\n\n let ensurePromise: Promise<any> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n const runtime = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >('metro-runtime/src/modules/empty-module.js', {\n environment: 'react-server',\n platform: 'web',\n });\n return runtime;\n }\n const ensureMemo = () => {\n ensurePromise ??= ensureSSRReady();\n return ensurePromise;\n };\n\n async function getRscRendererAsync(platform: string) {\n await ensureMemo();\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRendererCache.has(platform)) {\n return rscRendererCache.get(platform)!;\n }\n\n // TODO: Extract CSS Modules / Assets from the bundler process\n const renderer = await ssrLoadModule<\n typeof import('@expo/router-server/build/rsc/rsc-renderer')\n >('@expo/router-server/build/rsc/rsc-renderer', {\n environment: 'react-server',\n platform,\n });\n\n rscRendererCache.set(platform, renderer);\n return renderer;\n }\n\n const rscRenderContext = new Map<string, any>();\n\n function getRscRenderContext(platform: string) {\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRenderContext.has(platform)) {\n return rscRenderContext.get(platform)!;\n }\n\n const context = {};\n\n rscRenderContext.set(platform, context);\n return context;\n }\n\n async function renderRscToReadableStream(\n {\n input,\n headers,\n method,\n platform,\n body,\n engine,\n contentType,\n ssrManifest,\n decodedBody,\n routerOptions,\n }: {\n input: string;\n headers: Headers;\n method: 'POST' | 'GET';\n platform: string;\n body?: ReadableStream<Uint8Array>;\n engine?: 'hermes' | null;\n contentType?: string;\n ssrManifest?: Map<string, string | null>;\n decodedBody?: unknown;\n routerOptions: Record<string, any>;\n },\n isExporting: boolean | undefined = instanceMetroOptions.isExporting\n ) {\n assert(\n isExporting != null,\n 'The server must be started before calling renderRscToReadableStream.'\n );\n\n if (method === 'POST') {\n assert(body, 'Server request must be provided when method is POST (server actions)');\n }\n\n const context = getRscRenderContext(platform);\n\n context['__expo_requestHeaders'] = headers;\n\n const { renderRsc } = await getRscRendererAsync(platform);\n\n return renderRsc(\n {\n body,\n decodedBody,\n context,\n config: {},\n input,\n contentType,\n },\n {\n isExporting,\n entries: await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions }),\n resolveClientEntry: getResolveClientEntry({ platform, engine, ssrManifest }),\n async loadServerModuleRsc(urlFragment) {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n debug('[SSR] loadServerModuleRsc:', urlFragment);\n\n const options = getMetroOptionsFromUrl(urlFragment);\n\n return ssrLoadModule(\n path.join(serverRoot, options.mainModuleName),\n\n options,\n {\n hot: true,\n }\n );\n },\n }\n );\n }\n\n return {\n // Get the static client boundaries (no dead code elimination allowed) for the production export.\n getExpoRouterClientReferencesAsync,\n exportServerActionsAsync,\n\n async exportRoutesAsync(\n {\n platform,\n ssrManifest,\n routerOptions,\n }: {\n platform: string;\n ssrManifest: Map<string, string | null>;\n routerOptions: Record<string, any>;\n },\n files: ExportAssetMap\n ) {\n // TODO: When we add web SSR support, we need to extract CSS Modules / Assets from the bundler process to prevent FLOUC.\n const { getBuildConfig } = (\n await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions })\n ).default;\n\n // Get all the routes to render.\n const buildConfig = await getBuildConfig!(async () =>\n // TODO: Rework prefetching code to use Metro runtime.\n []\n );\n\n await Promise.all(\n Array.from(buildConfig).map(async ({ entries }) => {\n for (const { input, isStatic } of entries || []) {\n if (!isStatic) {\n debug('Skipping static export for route', { input });\n continue;\n }\n const destRscFile = path.join('_flight', platform, encodeInput(input));\n\n const pipe = await renderRscToReadableStream(\n {\n input,\n method: 'GET',\n platform,\n headers: new Headers(),\n ssrManifest,\n routerOptions,\n },\n true\n );\n\n const rsc = await streamToStringAsync(pipe);\n debug('RSC Payload', { platform, input, rsc });\n\n files.set(destRscFile, {\n contents: rsc,\n targetDomain: 'client',\n rscId: input,\n });\n }\n })\n );\n },\n\n middleware: createBuiltinAPIRequestHandler(\n // Match `/_flight/[platform]/[...path]`\n (req) => {\n return getFullUrl(req.url).pathname.startsWith(rscPathPrefix);\n },\n rscMiddleware\n ),\n onReloadRscEvent: (platform: string) => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n rscRendererCache.delete(platform);\n routerCache.delete(platform);\n },\n };\n}\n\nconst getFullUrl = (url: string) => {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'http://localhost:0');\n }\n};\n\nexport const fileURLToFilePath = (fileURL: string) => {\n try {\n return url.fileURLToPath(fileURL);\n } catch (error) {\n if (error instanceof TypeError) {\n throw Error(`Invalid URL: ${fileURL}`, { cause: error });\n }\n throw error;\n }\n};\n\nconst encodeInput = (input: string) => {\n if (input === '') {\n return 'index.txt';\n }\n if (input === 'index') {\n throw new Error('Input should not be `index`');\n }\n if (input.startsWith('/')) {\n throw new Error('Input should not start with `/`');\n }\n if (input.endsWith('/')) {\n throw new Error('Input should not end with `/`');\n }\n return input + '.txt';\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"],"names":["createServerComponentsMiddleware","fileURLToFilePath","debug","require","getMetroServerRootMemo","memoize","getMetroServerRoot","projectRoot","rscPath","instanceMetroOptions","ssrLoadModule","ssrLoadModuleArtifacts","useClientRouter","createModuleId","routerOptions","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","IS_METRO_BUNDLE_ERROR_SYMBOL","Response","JSON","stringify","status","isPossiblyUnableToResolveError","sanitizedServerMessage","stripAnsi","message","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","nestedServerBoundaries","processedEntryPoints","processEntryPoint","entryPoint","contents","add","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","reactServerReferences","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","publicModuleId","toPosixPath","relative","String","processEntryPoints","recursions","uniqueNestedServerBoundaries","value","has","length","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","routerCache","Map","getExpoRouterRscEntriesGetterAsync","ensureMemo","get","router","hot","entries","default","redirects","rewrites","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","filePath","join","ssrManifest","relativeFilePath","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","runtime","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","TypeError","cause","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAqmBHC,iBAAiB;eAAjBA;;;;yBA3oBsB;;;;;;;gEAGhB;;;;;;;yBACc;;;;;;;gEAChB;;;;;;;gEACD;;;;;;qCAE4C;qCACb;sBAErB;0BACE;oBACJ;oBACK;wBACO;gDACW;8BAKxC;;;;;;AAEP,MAAMC,QAAQC,QAAQ,SAAS;AAa/B,MAAMC,yBAAyBC,IAAAA,WAAO,EAACC,2BAAkB;AAElD,SAASN,iCACdO,WAAmB,EACnB,EACEC,OAAO,EACPC,oBAAoB,EACpBC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,EACfC,cAAc,EACdC,aAAa,EAYd;IAED,MAAMC,eAAeH,kBACjB,oDACA;IAEJ,MAAMI,gBAAgBC,IAAAA,2BAAgB,EAAC;QACrCC,QAAQ,CAAC;QACT,0BAA0B;QAC1BC,SAAS;QACTX;QACAY,SAASC,QAAQC,KAAK;QACtBC,WAAW,OAAOC;YAChB,gFAAgF;YAChF,IAAIA,KAAKC,OAAO,CAAC,YAAY,IAAI,MAAM;gBACrCD,KAAKC,OAAO,CAAC,YAAY,GAAGC,IAAAA,gBAAY;YAC1C;YACA,IAAIF,KAAKC,OAAO,CAAC,kBAAkB,IAAI,MAAM;gBAC3CD,KAAKC,OAAO,CAAC,kBAAkB,GAAGD,KAAKC,OAAO,CAAC,YAAY;YAC7D;YACA,IAAID,KAAKC,OAAO,CAAC,oBAAoB,IAAI,MAAM;gBAC7CD,KAAKC,OAAO,CAAC,oBAAoB,GAAG;YACtC;YAEA,kCAAkC;YAClC,IAAI;gBACF,OAAO,MAAME,0BAA0B;oBACrC,GAAGH,IAAI;oBACPC,SAAS,IAAIG,QAAQJ,KAAKC,OAAO;oBACjCI,MAAML,KAAKK,IAAI;oBACff;gB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AAIA,iBAAiBgK,WAAW;YAC9B,MAAM/G,MAAM,CAAC,aAAa,EAAE6G,SAAS,EAAE;gBAAEG,OAAOjK;YAAM;QACxD;QACA,MAAMA;IACR;AACF;AAEA,MAAMkJ,cAAc,CAAClB;IACnB,IAAIA,UAAU,IAAI;QAChB,OAAO;IACT;IACA,IAAIA,UAAU,SAAS;QACrB,MAAM,IAAI/E,MAAM;IAClB;IACA,IAAI+E,MAAMvD,UAAU,CAAC,MAAM;QACzB,MAAM,IAAIxB,MAAM;IAClB;IACA,IAAI+E,MAAMV,QAAQ,CAAC,MAAM;QACvB,MAAM,IAAIrE,MAAM;IAClB;IACA,OAAO+E,QAAQ;AACjB;AAEA,SAASrE,WAAWuG,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAIC,OAAO,CAAC,oBAAoB;AACzC"}
|
|
@@ -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<RegExp>(projectRoot, options);\n debug('manifest', manifest);\n // NOTE: no app dir if null\n // TODO: Redirect to 404 page\n return (\n manifest ?? {\n // Support the onboarding screen if there's no manifest\n htmlRoutes: [\n {\n file: 'index.js',\n page: '/index',\n routeKeys: {},\n namedRegex: /^\\/(?:index)?\\/?$/i,\n },\n ],\n apiRoutes: [],\n notFoundRoutes: [],\n 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,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,EAAST,aAAaC;YAC1DH,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;YACd;QAEJ;QACA,MAAMC,SAAQC,OAAO,EAAEC,KAAK;YAC1B,IAAI;gBACF,MAAM,EAAEC,OAAO,EAAE,GAA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O,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#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;;;;yBA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;oBAEJ;gBACF;YACF;YAEA,IAAIkC,EAAAA,WAAAA,IAAIE,GAAG,qBAAPF,SAASG,MAAM,MAAK,UAAU;gBAChCW,IAAAA,mCAA2B;gBAC3B,OAAO;oBACLD,SAAS;wBACPE,QAAQC,IAAI,CACV;oBAEJ;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"}
|
|
@@ -18,12 +18,10 @@ class MessageHandler {
|
|
|
18
18
|
return true;
|
|
19
19
|
}
|
|
20
20
|
/** Send a message directly to the device */ sendToDevice(message) {
|
|
21
|
-
// @ts-expect-error Type `T` is json serializable, just not the same one from `@react-native/dev-middleware`
|
|
22
21
|
this.device.sendMessage(message);
|
|
23
22
|
return true;
|
|
24
23
|
}
|
|
25
24
|
/** Send a message directly to the debugger */ sendToDebugger(message) {
|
|
26
|
-
// @ts-expect-error Type `T` is json serializable, just not the same one from `@react-native/dev-middleware`
|
|
27
25
|
this.debugger.sendMessage(message);
|
|
28
26
|
return true;
|
|
29
27
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../src/start/server/metro/debugging/MessageHandler.ts"],"sourcesContent":["import type {\n Connection,\n DebuggerMetadata,\n DebuggerRequest,\n DebuggerResponse,\n DeviceMetadata,\n DeviceRequest,\n DeviceResponse,\n Page,\n} from './types';\n\nexport abstract class MessageHandler {\n protected page: Page;\n protected device: DeviceMetadata;\n protected debugger: DebuggerMetadata;\n\n constructor(connection: Connection) {\n this.page = connection.page;\n this.device = connection.device;\n this.debugger = connection.debugger;\n }\n\n /** Determine if this middleware should be enabled or disabled, based on the page capabilities */\n isEnabled(): boolean {\n return true;\n }\n\n /** Send a message directly to the device */\n sendToDevice<T = DeviceResponse | DebuggerResponse>(message: T): true {\n
|
|
1
|
+
{"version":3,"sources":["../../../../../../src/start/server/metro/debugging/MessageHandler.ts"],"sourcesContent":["import type {\n Connection,\n DebuggerMetadata,\n DebuggerRequest,\n DebuggerResponse,\n DeviceMetadata,\n DeviceRequest,\n DeviceResponse,\n Page,\n} from './types';\n\ntype BaseMessage = Parameters<DeviceMetadata['sendMessage']>[0];\n\nexport abstract class MessageHandler {\n protected page: Page;\n protected device: DeviceMetadata;\n protected debugger: DebuggerMetadata;\n\n constructor(connection: Connection) {\n this.page = connection.page;\n this.device = connection.device;\n this.debugger = connection.debugger;\n }\n\n /** Determine if this middleware should be enabled or disabled, based on the page capabilities */\n isEnabled(): boolean {\n return true;\n }\n\n /** Send a message directly to the device */\n sendToDevice<T = DeviceResponse | DebuggerResponse>(message: Readonly<T>): true {\n this.device.sendMessage(message as BaseMessage);\n return true;\n }\n\n /** Send a message directly to the debugger */\n sendToDebugger<T = DeviceResponse | DebuggerResponse>(message: Readonly<T>): true {\n this.debugger.sendMessage(message as BaseMessage);\n return true;\n }\n\n /**\n * Intercept a message coming from the device, modify or respond to it through `this._sendMessageToDevice`.\n * Return `true` if the message was handled, this will stop the message propagation.\n */\n handleDeviceMessage?(message: DeviceRequest | DeviceResponse): boolean;\n\n /**\n * Intercept a message coming from the debugger, modify or respond to it through `socket.send`.\n * Return `true` if the message was handled, this will stop the message propagation.\n */\n handleDebuggerMessage?(message: DebuggerRequest | DebuggerResponse): boolean;\n}\n"],"names":["MessageHandler","constructor","connection","page","device","debugger","isEnabled","sendToDevice","message","sendMessage","sendToDebugger"],"mappings":";;;;+BAasBA;;;eAAAA;;;AAAf,MAAeA;IAKpBC,YAAYC,UAAsB,CAAE;QAClC,IAAI,CAACC,IAAI,GAAGD,WAAWC,IAAI;QAC3B,IAAI,CAACC,MAAM,GAAGF,WAAWE,MAAM;QAC/B,IAAI,CAACC,QAAQ,GAAGH,WAAWG,QAAQ;IACrC;IAEA,+FAA+F,GAC/FC,YAAqB;QACnB,OAAO;IACT;IAEA,0CAA0C,GAC1CC,aAAoDC,OAAoB,EAAQ;QAC9E,IAAI,CAACJ,MAAM,CAACK,WAAW,CAACD;QACxB,OAAO;IACT;IAEA,4CAA4C,GAC5CE,eAAsDF,OAAoB,EAAQ;QAChF,IAAI,CAACH,QAAQ,CAACI,WAAW,CAACD;QAC1B,OAAO;IACT;AAaF"}
|
|
@@ -10,7 +10,6 @@ Object.defineProperty(exports, "pageIsSupported", {
|
|
|
10
10
|
});
|
|
11
11
|
function pageIsSupported(page) {
|
|
12
12
|
var _page_reactNative;
|
|
13
|
-
// @ts-expect-error No good way to filter this properly in TypeScript
|
|
14
13
|
const capabilities = page.capabilities ?? ((_page_reactNative = page.reactNative) == null ? void 0 : _page_reactNative.capabilities) ?? {};
|
|
15
14
|
return page.title === 'React Native Experimental (Improved Chrome Reloads)' || capabilities.nativePageReloads === true;
|
|
16
15
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../src/start/server/metro/debugging/pageIsSupported.ts"],"sourcesContent":["import { Page } from './types';\n\ntype DevicePageInternal = Pick<Page, 'title' | 'capabilities'>;\ntype DevicePageResponse = {\n title: string;\n reactNative?: {\n logicalDeviceId: string;\n capabilities: Page['capabilities'];\n };\n};\n\n/**\n * Determine if a page debug target is supported by our debugging extensions.\n * If it's not, the extended CDP handlers will not be enabled.\n */\nexport function pageIsSupported(page: DevicePageInternal | DevicePageResponse): boolean {\n
|
|
1
|
+
{"version":3,"sources":["../../../../../../src/start/server/metro/debugging/pageIsSupported.ts"],"sourcesContent":["import { Page } from './types';\n\ntype DevicePageInternal = Pick<Page, 'title' | 'capabilities'>;\ntype DevicePageResponse = {\n title: string;\n reactNative?: {\n logicalDeviceId: string;\n capabilities: Page['capabilities'];\n };\n};\n\n/**\n * Determine if a page debug target is supported by our debugging extensions.\n * If it's not, the extended CDP handlers will not be enabled.\n */\nexport function pageIsSupported(page: DevicePageInternal | DevicePageResponse): boolean {\n const capabilities =\n (page as DevicePageInternal).capabilities ??\n (page as DevicePageResponse).reactNative?.capabilities ??\n {};\n\n return (\n page.title === 'React Native Experimental (Improved Chrome Reloads)' ||\n capabilities.nativePageReloads === true\n );\n}\n"],"names":["pageIsSupported","page","capabilities","reactNative","title","nativePageReloads"],"mappings":";;;;+BAegBA;;;eAAAA;;;AAAT,SAASA,gBAAgBC,IAA6C;QAGzE;IAFF,MAAMC,eACJ,AAACD,KAA4BC,YAAY,MACzC,oBAAA,AAACD,KAA4BE,WAAW,qBAAxC,kBAA0CD,YAAY,KACtD,CAAC;IAEH,OACED,KAAKG,KAAK,KAAK,yDACfF,aAAaG,iBAAiB,KAAK;AAEvC"}
|
|
@@ -66,8 +66,7 @@ const NODE_STDLIB_MODULES = [
|
|
|
66
66
|
'util/types',
|
|
67
67
|
'sqlite',
|
|
68
68
|
// Collect all builtin modules...
|
|
69
|
-
...(_module().builtinModules ||
|
|
70
|
-
(process.binding ? Object.keys(process.binding('natives')) : []) || []).filter((x)=>!/^(internal|v8|node-inspect)\/|\//.test(x) && ![
|
|
69
|
+
...(_module().builtinModules || (process.binding ? Object.keys(process.binding('natives')) : []) || []).filter((x)=>!/^(internal|v8|node-inspect)\/|\//.test(x) && ![
|
|
71
70
|
'sys'
|
|
72
71
|
].includes(x))
|
|
73
72
|
].sort();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/externals.ts"],"sourcesContent":["/**\n * Copyright © 2023 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport fs from 'fs';\nimport { builtinModules } from 'module';\nimport path from 'path';\n\n// A list of the Node.js standard library modules that are currently\n// available,\nexport const NODE_STDLIB_MODULES: string[] = [\n // Add all nested imports...\n 'assert/strict',\n 'dns/promises',\n 'inspector/promises',\n 'fs/promises',\n 'stream/web',\n 'stream/promises',\n 'path/posix',\n 'path/win32',\n 'readline/promises',\n 'stream/consumers',\n 'timers/promises',\n 'util/types',\n 'sqlite',\n\n // Collect all builtin modules...\n ...(\n builtinModules ||\n
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/externals.ts"],"sourcesContent":["/**\n * Copyright © 2023 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport fs from 'fs';\nimport { builtinModules } from 'module';\nimport path from 'path';\n\n// TODO(@kitten): When `builtinModules` isn't present, we instead use the `process.binding('natives')` internal\n// call which is almost equivalent. It's unclear from the History in Node.js' docs whether this fallback is still necessary\n// https://nodejs.org/api/module.html#modulebuiltinmodules\ndeclare global {\n namespace NodeJS {\n interface Process {\n binding?(key: 'natives'): Record<string, unknown>;\n }\n }\n}\n\n// A list of the Node.js standard library modules that are currently\n// available,\nexport const NODE_STDLIB_MODULES: string[] = [\n // Add all nested imports...\n 'assert/strict',\n 'dns/promises',\n 'inspector/promises',\n 'fs/promises',\n 'stream/web',\n 'stream/promises',\n 'path/posix',\n 'path/win32',\n 'readline/promises',\n 'stream/consumers',\n 'timers/promises',\n 'util/types',\n 'sqlite',\n\n // Collect all builtin modules...\n ...(\n builtinModules ||\n (process.binding ? Object.keys(process.binding('natives')) : []) ||\n []\n ).filter((x) => !/^(internal|v8|node-inspect)\\/|\\//.test(x) && !['sys'].includes(x)),\n].sort();\n\nconst shimsFolder = path.join(require.resolve('@expo/cli/package.json'), '../static/shims');\n\nexport function shouldCreateVirtualShim(normalName: string) {\n const shimPath = path.join(shimsFolder, normalName);\n if (fs.existsSync(shimPath)) {\n return shimPath;\n }\n return null;\n}\n\nexport function isNodeExternal(moduleName: string): string | null {\n const moduleId = moduleName.replace(/^node:/, '');\n if (NODE_STDLIB_MODULES.includes(moduleId)) {\n return moduleId;\n }\n return null;\n}\n"],"names":["NODE_STDLIB_MODULES","isNodeExternal","shouldCreateVirtualShim","builtinModules","process","binding","Object","keys","filter","x","test","includes","sort","shimsFolder","path","join","require","resolve","normalName","shimPath","fs","existsSync","moduleName","moduleId","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAkBYA,mBAAmB;eAAnBA;;IAkCGC,cAAc;eAAdA;;IARAC,uBAAuB;eAAvBA;;;;gEA3CD;;;;;;;yBACgB;;;;;;;gEACd;;;;;;;;;;;AAeV,MAAMF,sBAAgC;IAC3C,4BAA4B;IAC5B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAEA,iCAAiC;OAC9B,AACDG,CAAAA,wBAAc,IACbC,CAAAA,QAAQC,OAAO,GAAGC,OAAOC,IAAI,CAACH,QAAQC,OAAO,CAAC,cAAc,EAAE,AAAD,KAC9D,EAAE,AAAD,EACDG,MAAM,CAAC,CAACC,IAAM,CAAC,mCAAmCC,IAAI,CAACD,MAAM,CAAC;YAAC;SAAM,CAACE,QAAQ,CAACF;CAClF,CAACG,IAAI;AAEN,MAAMC,cAAcC,eAAI,CAACC,IAAI,CAACC,QAAQC,OAAO,CAAC,2BAA2B;AAElE,SAASf,wBAAwBgB,UAAkB;IACxD,MAAMC,WAAWL,eAAI,CAACC,IAAI,CAACF,aAAaK;IACxC,IAAIE,aAAE,CAACC,UAAU,CAACF,WAAW;QAC3B,OAAOA;IACT;IACA,OAAO;AACT;AAEO,SAASlB,eAAeqB,UAAkB;IAC/C,MAAMC,WAAWD,WAAWE,OAAO,CAAC,UAAU;IAC9C,IAAIxB,oBAAoBW,QAAQ,CAACY,WAAW;QAC1C,OAAOA;IACT;IACA,OAAO;AACT"}
|
|
@@ -49,11 +49,10 @@ async function fetchManifest(projectRoot, options) {
|
|
|
49
49
|
throw new Error('Routes manifest is malformed: ' + JSON.stringify(jsonManifest, null, 2));
|
|
50
50
|
}
|
|
51
51
|
if (!options.asJson) {
|
|
52
|
-
// @ts-expect-error
|
|
53
52
|
return inflateManifest(jsonManifest);
|
|
53
|
+
} else {
|
|
54
|
+
return jsonManifest;
|
|
54
55
|
}
|
|
55
|
-
// @ts-expect-error
|
|
56
|
-
return jsonManifest;
|
|
57
56
|
}
|
|
58
57
|
function inflateManifest(json) {
|
|
59
58
|
var _json_htmlRoutes, _json_apiRoutes, _json_notFoundRoutes, _json_redirects, _json_rewrites;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/fetchRouterManifest.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { type MiddlewareInfo, type RouteInfo, type RoutesManifest } from 'expo-server/private';\nimport resolveFrom from 'resolve-from';\n\nimport { getRoutePaths } from './router';\n\nfunction getExpoRouteManifestBuilderAsync(projectRoot: string) {\n return require(resolveFrom(projectRoot, '@expo/router-server/build/routes-manifest'))\n .createRoutesManifest as typeof import('@expo/router-server/build/routes-manifest').createRoutesManifest;\n}\n\n// TODO: Simplify this now that we use Node.js directly, no need for the Metro bundler caching layer.\
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/fetchRouterManifest.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport type { Options as RoutesManifestOptions } from '@expo/router-server/build/routes-manifest';\nimport { type MiddlewareInfo, type RouteInfo, type RoutesManifest } from 'expo-server/private';\nimport resolveFrom from 'resolve-from';\n\nimport { getRoutePaths } from './router';\n\nfunction getExpoRouteManifestBuilderAsync(projectRoot: string) {\n return require(resolveFrom(projectRoot, '@expo/router-server/build/routes-manifest'))\n .createRoutesManifest as typeof import('@expo/router-server/build/routes-manifest').createRoutesManifest;\n}\n\ninterface FetchManifestOptions extends RoutesManifestOptions {\n asJson?: boolean;\n appDir: string;\n}\n\n// TODO: Simplify this now that we use Node.js directly, no need for the Metro bundler caching layer.\nasync function fetchManifest(\n projectRoot: string,\n options: FetchManifestOptions & { asJson: true }\n): Promise<RoutesManifest<string> | null>;\nasync function fetchManifest(\n projectRoot: string,\n options: FetchManifestOptions & { asJson?: false | undefined }\n): Promise<RoutesManifest<RegExp> | null>;\nasync function fetchManifest(\n projectRoot: string,\n options: FetchManifestOptions\n): Promise<RoutesManifest | null> {\n const getManifest = getExpoRouteManifestBuilderAsync(projectRoot);\n const paths = getRoutePaths(options.appDir);\n // Get the serialized manifest\n const jsonManifest = getManifest(paths, options);\n if (!jsonManifest) {\n return null;\n }\n\n if (!jsonManifest.htmlRoutes || !jsonManifest.apiRoutes) {\n throw new Error('Routes manifest is malformed: ' + JSON.stringify(jsonManifest, null, 2));\n }\n\n if (!options.asJson) {\n return inflateManifest(jsonManifest);\n } else {\n return jsonManifest;\n }\n}\n\nexport { fetchManifest };\n\n// Convert the serialized manifest to a usable format\nexport function inflateManifest(json: RoutesManifest<string>): RoutesManifest<RegExp> {\n return {\n ...json,\n middleware: json.middleware,\n htmlRoutes: json.htmlRoutes?.map((value) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n apiRoutes: json.apiRoutes?.map((value) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n notFoundRoutes: json.notFoundRoutes?.map((value) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n redirects: json.redirects?.map((value: any) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n rewrites: json.rewrites?.map((value: any) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n };\n}\n"],"names":["fetchManifest","inflateManifest","getExpoRouteManifestBuilderAsync","projectRoot","require","resolveFrom","createRoutesManifest","options","getManifest","paths","getRoutePaths","appDir","jsonManifest","htmlRoutes","apiRoutes","Error","JSON","stringify","asJson","json","middleware","map","value","namedRegex","RegExp","notFoundRoutes","redirects","rewrites"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAiDQA,aAAa;eAAbA;;IAGOC,eAAe;eAAfA;;;;gEAjDQ;;;;;;wBAEM;;;;;;AAE9B,SAASC,iCAAiCC,WAAmB;IAC3D,OAAOC,QAAQC,IAAAA,sBAAW,EAACF,aAAa,8CACrCG,oBAAoB;AACzB;AAgBA,eAAeN,cACbG,WAAmB,EACnBI,OAA6B;IAE7B,MAAMC,cAAcN,iCAAiCC;IACrD,MAAMM,QAAQC,IAAAA,qBAAa,EAACH,QAAQI,MAAM;IAC1C,8BAA8B;IAC9B,MAAMC,eAAeJ,YAAYC,OAAOF;IACxC,IAAI,CAACK,cAAc;QACjB,OAAO;IACT;IAEA,IAAI,CAACA,aAAaC,UAAU,IAAI,CAACD,aAAaE,SAAS,EAAE;QACvD,MAAM,IAAIC,MAAM,mCAAmCC,KAAKC,SAAS,CAACL,cAAc,MAAM;IACxF;IAEA,IAAI,CAACL,QAAQW,MAAM,EAAE;QACnB,OAAOjB,gBAAgBW;IACzB,OAAO;QACL,OAAOA;IACT;AACF;AAKO,SAASX,gBAAgBkB,IAA4B;QAI5CA,kBAMDA,iBAMKA,sBAMLA,iBAMDA;IA3BZ,OAAO;QACL,GAAGA,IAAI;QACPC,YAAYD,KAAKC,UAAU;QAC3BP,UAAU,GAAEM,mBAAAA,KAAKN,UAAU,qBAAfM,iBAAiBE,GAAG,CAAC,CAACC;YAChC,OAAO;gBACL,GAAGA,KAAK;gBACRC,YAAY,IAAIC,OAAOF,MAAMC,UAAU;YACzC;QACF;QACAT,SAAS,GAAEK,kBAAAA,KAAKL,SAAS,qBAAdK,gBAAgBE,GAAG,CAAC,CAACC;YAC9B,OAAO;gBACL,GAAGA,KAAK;gBACRC,YAAY,IAAIC,OAAOF,MAAMC,UAAU;YACzC;QACF;QACAE,cAAc,GAAEN,uBAAAA,KAAKM,cAAc,qBAAnBN,qBAAqBE,GAAG,CAAC,CAACC;YACxC,OAAO;gBACL,GAAGA,KAAK;gBACRC,YAAY,IAAIC,OAAOF,MAAMC,UAAU;YACzC;QACF;QACAG,SAAS,GAAEP,kBAAAA,KAAKO,SAAS,qBAAdP,gBAAgBE,GAAG,CAAC,CAACC;YAC9B,OAAO;gBACL,GAAGA,KAAK;gBACRC,YAAY,IAAIC,OAAOF,MAAMC,UAAU;YACzC;QACF;QACAI,QAAQ,GAAER,iBAAAA,KAAKQ,QAAQ,qBAAbR,eAAeE,GAAG,CAAC,CAACC;YAC5B,OAAO;gBACL,GAAGA,KAAK;gBACRC,YAAY,IAAIC,OAAOF,MAAMC,UAAU;YACzC;QACF;IACF;AACF"}
|
|
@@ -101,6 +101,9 @@ function _interop_require_default(obj) {
|
|
|
101
101
|
default: obj
|
|
102
102
|
};
|
|
103
103
|
}
|
|
104
|
+
function asWritable(input) {
|
|
105
|
+
return input;
|
|
106
|
+
}
|
|
104
107
|
// Wrap terminal and polyfill console.log so we can log during bundling without breaking the indicator.
|
|
105
108
|
class LogRespectingTerminal extends _metrocore().Terminal {
|
|
106
109
|
constructor(stream){
|
|
@@ -157,16 +160,13 @@ async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, ge
|
|
|
157
160
|
}
|
|
158
161
|
}
|
|
159
162
|
};
|
|
160
|
-
// @ts-expect-error: Set the global require cycle ignore patterns for SSR bundles. This won't work with custom global prefixes, but we don't use those.
|
|
161
163
|
globalThis.__requireCycleIgnorePatterns = (_config_resolver = config.resolver) == null ? void 0 : _config_resolver.requireCycleIgnorePatterns;
|
|
162
164
|
if (isExporting) {
|
|
163
165
|
var _exp_experiments7;
|
|
164
166
|
// This token will be used in the asset plugin to ensure the path is correct for writing locally.
|
|
165
|
-
|
|
166
|
-
config.transformer.publicPath = `/assets?export_path=${(((_exp_experiments7 = exp.experiments) == null ? void 0 : _exp_experiments7.baseUrl) ?? '') + '/assets'}`;
|
|
167
|
+
asWritable(config.transformer).publicPath = `/assets?export_path=${(((_exp_experiments7 = exp.experiments) == null ? void 0 : _exp_experiments7.baseUrl) ?? '') + '/assets'}`;
|
|
167
168
|
} else {
|
|
168
|
-
|
|
169
|
-
config.transformer.publicPath = '/assets/?unstable_path=.';
|
|
169
|
+
asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';
|
|
170
170
|
}
|
|
171
171
|
const platformBundlers = (0, _platformBundlers.getPlatformBundlers)(projectRoot, exp);
|
|
172
172
|
if ((_exp_experiments4 = exp.experiments) == null ? void 0 : _exp_experiments4.reactCompiler) {
|
|
@@ -233,8 +233,7 @@ async function instantiateMetroAsync(metroBundler, options, { isExporting, exp =
|
|
|
233
233
|
// See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9
|
|
234
234
|
// See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52
|
|
235
235
|
const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;
|
|
236
|
-
|
|
237
|
-
metroConfig.server.enhanceMiddleware = (metroMiddleware, server)=>{
|
|
236
|
+
asWritable(metroConfig.server).enhanceMiddleware = (metroMiddleware, server)=>{
|
|
238
237
|
if (customEnhanceMiddleware) {
|
|
239
238
|
metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);
|
|
240
239
|
}
|
|
@@ -281,17 +280,16 @@ async function instantiateMetroAsync(metroBundler, options, { isExporting, exp =
|
|
|
281
280
|
...graph.dependencies.values()
|
|
282
281
|
];
|
|
283
282
|
const ctx = {
|
|
283
|
+
// TODO(@kitten): Increase type-safety here
|
|
284
284
|
platform: graph.transformOptions.platform,
|
|
285
285
|
environment: (_graph_transformOptions_customTransformOptions = graph.transformOptions.customTransformOptions) == null ? void 0 : _graph_transformOptions_customTransformOptions.environment
|
|
286
286
|
};
|
|
287
287
|
// Assign IDs to modules in a consistent order
|
|
288
288
|
for (const module of modules){
|
|
289
|
-
// @ts-expect-error
|
|
290
289
|
this._createModuleId(module.path, ctx);
|
|
291
290
|
}
|
|
292
291
|
// Sort by IDs
|
|
293
|
-
return modules.sort(
|
|
294
|
-
(a, b)=>this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx));
|
|
292
|
+
return modules.sort((a, b)=>this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx));
|
|
295
293
|
};
|
|
296
294
|
if (hmrServer) {
|
|
297
295
|
let hmrJSBundle;
|
|
@@ -329,6 +327,7 @@ async function instantiateMetroAsync(metroBundler, options, { isExporting, exp =
|
|
|
329
327
|
logger == null ? void 0 : logger.point('serialize_start');
|
|
330
328
|
// NOTE(EvanBacon): This is the patch
|
|
331
329
|
const moduleIdContext = {
|
|
330
|
+
// TODO(@kitten): Increase type-safety here
|
|
332
331
|
platform: revision.graph.transformOptions.platform,
|
|
333
332
|
environment: (_revision_graph_transformOptions_customTransformOptions = revision.graph.transformOptions.customTransformOptions) == null ? void 0 : _revision_graph_transformOptions_customTransformOptions.environment
|
|
334
333
|
};
|
|
@@ -336,7 +335,6 @@ async function instantiateMetroAsync(metroBundler, options, { isExporting, exp =
|
|
|
336
335
|
clientUrl: group.clientUrl,
|
|
337
336
|
// NOTE(EvanBacon): This is also the patch
|
|
338
337
|
createModuleId: (moduleId)=>{
|
|
339
|
-
// @ts-expect-error
|
|
340
338
|
return this._createModuleId(moduleId, moduleIdContext);
|
|
341
339
|
},
|
|
342
340
|
includeAsyncPaths: group.graphOptions.lazy,
|