@expo/cli 0.21.8 → 0.22.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/bin/cli +1 -1
- package/build/src/export/exportDomComponents.js +11 -3
- package/build/src/export/exportDomComponents.js.map +1 -1
- package/build/src/prebuild/renameTemplateAppName.js +7 -1
- package/build/src/prebuild/renameTemplateAppName.js.map +1 -1
- package/build/src/run/ios/codeSigning/configureCodeSigning.js +1 -1
- package/build/src/run/ios/codeSigning/configureCodeSigning.js.map +1 -1
- package/build/src/run/ios/codeSigning/resolveCertificateSigningIdentity.js +30 -6
- package/build/src/run/ios/codeSigning/resolveCertificateSigningIdentity.js.map +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/MetroTerminalReporter.js +4 -4
- package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
- package/build/src/start/server/metro/createServerComponentsMiddleware.js +8 -4
- package/build/src/start/server/metro/createServerComponentsMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/DomComponentsMiddleware.js +5 -3
- package/build/src/start/server/middleware/DomComponentsMiddleware.js.map +1 -1
- package/build/src/utils/filePath.js +13 -3
- package/build/src/utils/filePath.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 +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { Terminal } from 'metro-core';\nimport path from 'path';\n\nimport { logWarning, TerminalReporter } from './TerminalReporter';\nimport {\n BuildPhase,\n BundleDetails,\n BundleProgress,\n SnippetError,\n TerminalReportableEvent,\n} from './TerminalReporter.types';\nimport { NODE_STDLIB_MODULES } from './externals';\nimport { learnMore } from '../../../utils/link';\n\nconst MAX_PROGRESS_BAR_CHAR_WIDTH = 16;\nconst DARK_BLOCK_CHAR = '\\u2593';\nconst LIGHT_BLOCK_CHAR = '\\u2591';\n/**\n * Extends the default Metro logger and adds some additional features.\n * Also removes the giant Metro logo from the output.\n */\nexport class MetroTerminalReporter extends TerminalReporter {\n constructor(\n public projectRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n // Used for testing\n _getElapsedTime(startTime: 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('/')\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 localPath = inputFile.startsWith(path.sep)\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)}/`) +\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: {\n type: 'client_log';\n level: 'trace' | 'info' | 'warn' | 'log' | 'group' | 'groupCollapsed' | 'groupEnd' | 'debug';\n data: unknown[];\n }): boolean {\n return isAppRegistryStartupMessage(event.data);\n }\n\n shouldFilterBundleEvent(event: TerminalReportableEvent): boolean {\n return 'bundleDetails' in event && event.bundleDetails?.bundleType === 'map';\n }\n\n /** Print the cache clear message. */\n transformCacheReset(): void {\n logWarning(\n this.terminal,\n chalk`Bundler cache is empty, rebuilding {dim (this may take a minute)}`\n );\n }\n\n /** One of the first logs that will be printed */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {\n // this.terminal.log('Dependency graph is loading...');\n if (hasReducedPerformance) {\n // Extends https://github.com/facebook/metro/blob/347b1d7ed87995d7951aaa9fd597c04b06013dac/packages/metro/src/lib/TerminalReporter.js#L283-L290\n this.terminal.log(\n chalk.red(\n [\n 'Metro is operating with reduced performance.',\n 'Please fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n _logBundlingError(error: SnippetError): void {\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.projectRoot, error);\n const cause = error.cause as undefined | { _expoImportStack?: string };\n if (moduleResolutionError) {\n let message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n if (cause?._expoImportStack) {\n message += `\\n\\n${cause?._expoImportStack}`;\n }\n return this.terminal.log(message);\n }\n if (cause?._expoImportStack) {\n error.message += `\\n\\n${cause._expoImportStack}`;\n }\n return super._logBundlingError(error);\n }\n}\n\n/**\n * Formats an error where the user is attempting to import a module from the Node.js standard library.\n * Exposed for testing.\n *\n * @param error\n * @returns error message or null if not a module resolution error\n */\nexport function formatUsingNodeStandardLibraryError(\n projectRoot: string,\n error: SnippetError\n): string | null {\n if (!error.message) {\n return null;\n }\n const { targetModuleName, originModulePath } = error;\n if (!targetModuleName || !originModulePath) {\n return null;\n }\n const relativePath = path.relative(projectRoot, originModulePath);\n\n const DOCS_PAGE_URL =\n 'https://docs.expo.dev/workflow/using-libraries/#using-third-party-libraries';\n\n if (isNodeStdLibraryModule(targetModuleName)) {\n if (originModulePath.includes('node_modules')) {\n return [\n `The package at \"${chalk.bold(\n relativePath\n )}\" attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n } else {\n return [\n `You attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\" from \"${chalk.bold(relativePath)}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n }\n }\n return `Unable to resolve \"${targetModuleName}\" from \"${relativePath}\"`;\n}\n\nexport function isNodeStdLibraryModule(moduleName: string): boolean {\n return /^node:/.test(moduleName) || NODE_STDLIB_MODULES.includes(moduleName);\n}\n\n/** If the code frame can be found then append it to the existing message. */\nfunction maybeAppendCodeFrame(message: string, rawMessage: string): string {\n const codeFrame = stripMetroInfo(rawMessage);\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\n}\n\n/**\n * Remove the Metro cache clearing steps if they exist.\n * In future versions we won't need this.\n * Returns the remaining code frame logs.\n */\nexport function stripMetroInfo(errorMessage: string): string | null {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return null;\n }\n const lines = errorMessage.split('\\n');\n const index = lines.findIndex((line) => line.includes('4. Remove the cache'));\n if (index === -1) {\n return null;\n }\n return lines.slice(index + 1).join('\\n');\n}\n\n/** @returns if the message matches the initial startup log */\nfunction isAppRegistryStartupMessage(body: any[]): boolean {\n return (\n body.length === 1 &&\n (/^Running application \"main\" with appParams:/.test(body[0]) ||\n /^Running \"main\" with \\{/.test(body[0]))\n );\n}\n\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getPlatformTagForBuildDetails(bundleDetails?: BundleDetails | null): string {\n const platform = bundleDetails?.platform ?? null;\n if (platform) {\n const formatted = { ios: 'iOS', android: 'Android', web: 'Web' }[platform] || platform;\n return `${chalk.bold(formatted)} `;\n }\n\n return '';\n}\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getEnvironmentForBuildDetails(bundleDetails?: BundleDetails | null): string {\n // Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.\n const env = bundleDetails?.customTransformOptions?.environment ?? null;\n if (env === 'node') {\n return chalk.bold('λ') + ' ';\n } 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","formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","TerminalReporter","constructor","projectRoot","terminal","_getElapsedTime","startTime","process","hrtime","bigint","_getBundleStatusMessage","progress","phase","env","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","customTransformOptions","dom","includes","replace","inputFile","entryFile","startsWith","path","sep","relative","status","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","log","shouldFilterClientLog","event","isAppRegistryStartupMessage","data","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundlingError","error","moduleResolutionError","cause","message","maybeAppendCodeFrame","_expoImportStack","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","lines","split","index","findIndex","line","slice","body","formatted","ios","android","web","environment","trim"],"mappings":"AAAA;;;;;;;;;;;IAsBaA,qBAAqB,MAArBA,qBAAqB;IA6JlBC,mCAAmC,MAAnCA,mCAAmC;IAwCnCC,sBAAsB,MAAtBA,sBAAsB;IAkBtBC,cAAc,MAAdA,cAAc;;;8DA7OZ,OAAO;;;;;;;8DAER,MAAM;;;;;;kCAEsB,oBAAoB;2BAQ7B,aAAa;sBACvB,qBAAqB;;;;;;AAE/C,MAAMC,2BAA2B,GAAG,EAAE,AAAC;AACvC,MAAMC,eAAe,GAAG,GAAQ,AAAC;AACjC,MAAMC,gBAAgB,GAAG,GAAQ,AAAC;AAK3B,MAAMN,qBAAqB,SAASO,iBAAgB,iBAAA;IACzDC,YACSC,WAAmB,EAC1BC,QAAkB,CA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|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { Terminal } from 'metro-core';\nimport path from 'path';\n\nimport { logWarning, TerminalReporter } from './TerminalReporter';\nimport {\n BuildPhase,\n BundleDetails,\n BundleProgress,\n SnippetError,\n TerminalReportableEvent,\n} from './TerminalReporter.types';\nimport { NODE_STDLIB_MODULES } from './externals';\nimport { learnMore } from '../../../utils/link';\n\nconst MAX_PROGRESS_BAR_CHAR_WIDTH = 16;\nconst DARK_BLOCK_CHAR = '\\u2593';\nconst LIGHT_BLOCK_CHAR = '\\u2591';\n/**\n * Extends the default Metro logger and adds some additional features.\n * Also removes the giant Metro logo from the output.\n */\nexport class MetroTerminalReporter extends TerminalReporter {\n constructor(\n public projectRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n // Used for testing\n _getElapsedTime(startTime: 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: {\n type: 'client_log';\n level: 'trace' | 'info' | 'warn' | 'log' | 'group' | 'groupCollapsed' | 'groupEnd' | 'debug';\n data: unknown[];\n }): boolean {\n return isAppRegistryStartupMessage(event.data);\n }\n\n shouldFilterBundleEvent(event: TerminalReportableEvent): boolean {\n return 'bundleDetails' in event && event.bundleDetails?.bundleType === 'map';\n }\n\n /** Print the cache clear message. */\n transformCacheReset(): void {\n logWarning(\n this.terminal,\n chalk`Bundler cache is empty, rebuilding {dim (this may take a minute)}`\n );\n }\n\n /** One of the first logs that will be printed */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {\n // this.terminal.log('Dependency graph is loading...');\n if (hasReducedPerformance) {\n // Extends https://github.com/facebook/metro/blob/347b1d7ed87995d7951aaa9fd597c04b06013dac/packages/metro/src/lib/TerminalReporter.js#L283-L290\n this.terminal.log(\n chalk.red(\n [\n 'Metro is operating with reduced performance.',\n 'Please fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n _logBundlingError(error: SnippetError): void {\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.projectRoot, error);\n const cause = error.cause as undefined | { _expoImportStack?: string };\n if (moduleResolutionError) {\n let message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n if (cause?._expoImportStack) {\n message += `\\n\\n${cause?._expoImportStack}`;\n }\n return this.terminal.log(message);\n }\n if (cause?._expoImportStack) {\n error.message += `\\n\\n${cause._expoImportStack}`;\n }\n return super._logBundlingError(error);\n }\n}\n\n/**\n * Formats an error where the user is attempting to import a module from the Node.js standard library.\n * Exposed for testing.\n *\n * @param error\n * @returns error message or null if not a module resolution error\n */\nexport function formatUsingNodeStandardLibraryError(\n projectRoot: string,\n error: SnippetError\n): string | null {\n if (!error.message) {\n return null;\n }\n const { targetModuleName, originModulePath } = error;\n if (!targetModuleName || !originModulePath) {\n return null;\n }\n const relativePath = path.relative(projectRoot, originModulePath);\n\n const DOCS_PAGE_URL =\n 'https://docs.expo.dev/workflow/using-libraries/#using-third-party-libraries';\n\n if (isNodeStdLibraryModule(targetModuleName)) {\n if (originModulePath.includes('node_modules')) {\n return [\n `The package at \"${chalk.bold(\n relativePath\n )}\" attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n } else {\n return [\n `You attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\" from \"${chalk.bold(relativePath)}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n }\n }\n return `Unable to resolve \"${targetModuleName}\" from \"${relativePath}\"`;\n}\n\nexport function isNodeStdLibraryModule(moduleName: string): boolean {\n return /^node:/.test(moduleName) || NODE_STDLIB_MODULES.includes(moduleName);\n}\n\n/** If the code frame can be found then append it to the existing message. */\nfunction maybeAppendCodeFrame(message: string, rawMessage: string): string {\n const codeFrame = stripMetroInfo(rawMessage);\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\n}\n\n/**\n * Remove the Metro cache clearing steps if they exist.\n * In future versions we won't need this.\n * Returns the remaining code frame logs.\n */\nexport function stripMetroInfo(errorMessage: string): string | null {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return null;\n }\n const lines = errorMessage.split('\\n');\n const index = lines.findIndex((line) => line.includes('4. Remove the cache'));\n if (index === -1) {\n return null;\n }\n return lines.slice(index + 1).join('\\n');\n}\n\n/** @returns if the message matches the initial startup log */\nfunction isAppRegistryStartupMessage(body: any[]): boolean {\n return (\n body.length === 1 &&\n (/^Running application \"main\" with appParams:/.test(body[0]) ||\n /^Running \"main\" with \\{/.test(body[0]))\n );\n}\n\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getPlatformTagForBuildDetails(bundleDetails?: BundleDetails | null): string {\n const platform = bundleDetails?.platform ?? null;\n if (platform) {\n const formatted = { ios: 'iOS', android: 'Android', web: 'Web' }[platform] || platform;\n return `${chalk.bold(formatted)} `;\n }\n\n return '';\n}\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getEnvironmentForBuildDetails(bundleDetails?: BundleDetails | null): string {\n // Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.\n const env = bundleDetails?.customTransformOptions?.environment ?? null;\n if (env === 'node') {\n return chalk.bold('λ') + ' ';\n } 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","formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","TerminalReporter","constructor","projectRoot","terminal","_getElapsedTime","startTime","process","hrtime","bigint","_getBundleStatusMessage","progress","phase","env","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","customTransformOptions","dom","includes","path","sep","replace","inputFile","entryFile","isAbsolute","relative","status","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","log","shouldFilterClientLog","event","isAppRegistryStartupMessage","data","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundlingError","error","moduleResolutionError","cause","message","maybeAppendCodeFrame","_expoImportStack","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","lines","split","index","findIndex","line","slice","body","formatted","ios","android","web","environment","trim"],"mappings":"AAAA;;;;;;;;;;;IAsBaA,qBAAqB,MAArBA,qBAAqB;IA8JlBC,mCAAmC,MAAnCA,mCAAmC;IAwCnCC,sBAAsB,MAAtBA,sBAAsB;IAkBtBC,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AqC,CAAEM,GAAG,AAAL,CAAA,IACrC,OAAON,CAAAA,aAAa,QAAwB,GAArCA,KAAAA,CAAqC,GAArCA,CAAAA,IAAqC,GAArCA,aAAa,CAAEK,sBAAsB,SAAA,GAArCL,KAAAA,CAAqC,GAArCA,IAAqC,CAAEM,GAAG,AAAL,CAAA,AAAK,KAAK,QAAQ,EAC9D;QACA,OAAOW,MAAK,EAAA,QAAA,CAACc,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;IACjC,CAAC;IAED,OAAO,EAAE,CAAC;AACZ,CAAC"}
|
|
@@ -45,6 +45,13 @@ function _path() {
|
|
|
45
45
|
};
|
|
46
46
|
return data;
|
|
47
47
|
}
|
|
48
|
+
function _url() {
|
|
49
|
+
const data = /*#__PURE__*/ _interopRequireDefault(require("url"));
|
|
50
|
+
_url = function() {
|
|
51
|
+
return data;
|
|
52
|
+
};
|
|
53
|
+
return data;
|
|
54
|
+
}
|
|
48
55
|
const _metroErrorInterface = require("./metroErrorInterface");
|
|
49
56
|
const _ansi = require("../../../utils/ansi");
|
|
50
57
|
const _fn = require("../../../utils/fn");
|
|
@@ -393,10 +400,7 @@ const getFullUrl = (url)=>{
|
|
|
393
400
|
}
|
|
394
401
|
};
|
|
395
402
|
const fileURLToFilePath = (fileURL)=>{
|
|
396
|
-
|
|
397
|
-
throw new Error("Not a file URL");
|
|
398
|
-
}
|
|
399
|
-
return decodeURI(fileURL.slice("file://".length));
|
|
403
|
+
return _url().default.fileURLToPath(fileURL);
|
|
400
404
|
};
|
|
401
405
|
const encodeInput = (input)=>{
|
|
402
406
|
if (input === "") {
|
|
@@ -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 { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport { getRscMiddleware } from '@expo/server/build/middleware/rsc';\nimport assert from 'assert';\nimport path from 'path';\n\nimport { logMetroError } from './metroErrorInterface';\nimport { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n 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 }: {\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 }\n) {\n const routerModule = useClientRouter\n ? 'expo-router/build/rsc/router/noopRouter'\n : 'expo-router/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 });\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 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\n for (const entryPoint of uniqueEntryPoints) {\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\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 // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[entryPoint] = [String(relativeName), outputName];\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/${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 async function getExpoRouterRscEntriesGetterAsync({ platform }: { platform: string }) {\n return ssrLoadModule<typeof import('expo-router/build/rsc/router/expo-definedRouter')>(\n routerModule,\n {\n environment: 'react-server',\n platform,\n },\n {\n hot: true,\n }\n );\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 if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n const relativeFilePath = path.relative(serverRoot, file);\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(createModuleId(file, { platform: context.platform, environment: 'client' })),\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 filePath = file.startsWith('file://') ? fileURLToFilePath(file) : file;\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<string, typeof import('expo-router/build/rsc/rsc-renderer')>();\n\n async function getRscRendererAsync(platform: string) {\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<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'expo-router/build/rsc/rsc-renderer',\n {\n environment: 'react-server',\n platform,\n }\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 }: {\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 },\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 }),\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(path.join(serverRoot, options.mainModuleName), options);\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 }: {\n platform: string;\n ssrManifest: Map<string, string>;\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 } = (await getExpoRouterRscEntriesGetterAsync({ platform })).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 },\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: () => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n // Clear the render context to ensure that the next render is a fresh start.\n rscRenderContext.clear();\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 if (!fileURL.startsWith('file://')) {\n throw new Error('Not a file URL');\n }\n return decodeURI(fileURL.slice('file://'.length));\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","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","sanitizedServerMessage","stripAnsi","message","Response","status","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","entryPoint","contents","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","String","JSON","stringify","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","reactServerReferences","getExpoRouterRscEntriesGetterAsync","hot","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","ssrManifest","relativeFilePath","relative","has","chunk","get","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","filePath","pathname","endsWith","chunkName","rscRendererCache","Map","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","entries","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","join","exportRoutesAsync","getBuildConfig","default","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","clear","fileURL","decodeURI","slice","length","str","replace"],"mappings":"AAAA;;;;;CAKC,GACD;;;;;;;;;;;IAkCgBA,gCAAgC,MAAhCA,gCAAgC;IAofnCC,iBAAiB,MAAjBA,iBAAiB;;;yBAthBK,oBAAoB;;;;;;;yBAEtB,mCAAmC;;;;;;;8DACjD,QAAQ;;;;;;;8DACV,MAAM;;;;;;qCAEO,uBAAuB;sBAE3B,qBAAqB;oBACvB,mBAAmB;oBACd,mBAAmB;wBACZ,uBAAuB;gDACZ,8CAA8C;8BAKtF,4BAA4B;;;;;;AAEnC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,UAAU,CAAC,AAAsB,AAAC;AAajE,MAAMC,sBAAsB,GAAGC,IAAAA,GAAO,QAAA,EAACC,MAAkB,EAAA,mBAAA,CAAC,AAAC;AAE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CAACC,MAAM,CAAC,CAAC,CAAC;AACpD,CAAC,AAAC;AAEF,MAAMf,WAAW,GAAG,CAACrB,KAAa,GAAK;IACrC,IAAIA,KAAK,KAAK,EAAE,EAAE;QAChB,OAAO,WAAW,CAAC;IACrB,CAAC;IACD,IAAIA,KAAK,KAAK,OAAO,EAAE;QACrB,MAAM,IAAIhE,KAAK,CAAC,6BAA6B,CAAC,CAAC;IACjD,CAAC;IACD,IAAIgE,KAAK,CAAC/C,UAAU,CAAC,GAAG,CAAC,EAAE;QACzB,MAAM,IAAIjB,KAAK,CAAC,iCAAiC,CAAC,CAAC;IACrD,CAAC;IACD,IAAIgE,KAAK,CAACR,QAAQ,CAAC,GAAG,CAAC,EAAE;QACvB,MAAM,IAAIxD,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACnD,CAAC;IACD,OAAOgE,KAAK,GAAG,MAAM,CAAC;AACxB,CAAC,AAAC;AAEF,SAAStD,UAAU,CAAC2F,GAAW,EAAE;IAC/B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,GAAG,CAACC,OAAO,qBAAqB,qBAAqB,CAAC,CAAC;AAChE,CAAC"}
|
|
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 { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport { getRscMiddleware } from '@expo/server/build/middleware/rsc';\nimport assert from 'assert';\nimport path from 'path';\nimport url from 'url';\n\nimport { logMetroError } from './metroErrorInterface';\nimport { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n 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 }: {\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 }\n) {\n const routerModule = useClientRouter\n ? 'expo-router/build/rsc/router/noopRouter'\n : 'expo-router/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 });\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 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\n for (const entryPoint of uniqueEntryPoints) {\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\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 // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[entryPoint] = [String(relativeName), outputName];\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/${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 async function getExpoRouterRscEntriesGetterAsync({ platform }: { platform: string }) {\n return ssrLoadModule<typeof import('expo-router/build/rsc/router/expo-definedRouter')>(\n routerModule,\n {\n environment: 'react-server',\n platform,\n },\n {\n hot: true,\n }\n );\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 if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n const relativeFilePath = path.relative(serverRoot, file);\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(createModuleId(file, { platform: context.platform, environment: 'client' })),\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 filePath = file.startsWith('file://') ? fileURLToFilePath(file) : file;\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<string, typeof import('expo-router/build/rsc/rsc-renderer')>();\n\n async function getRscRendererAsync(platform: string) {\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<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'expo-router/build/rsc/rsc-renderer',\n {\n environment: 'react-server',\n platform,\n }\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 }: {\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 },\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 }),\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(path.join(serverRoot, options.mainModuleName), options);\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 }: {\n platform: string;\n ssrManifest: Map<string, string>;\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 } = (await getExpoRouterRscEntriesGetterAsync({ platform })).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 },\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: () => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n // Clear the render context to ensure that the next render is a fresh start.\n rscRenderContext.clear();\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 return url.fileURLToPath(fileURL);\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","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","sanitizedServerMessage","stripAnsi","message","Response","status","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","entryPoint","contents","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","String","JSON","stringify","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","reactServerReferences","getExpoRouterRscEntriesGetterAsync","hot","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","ssrManifest","relativeFilePath","relative","has","chunk","get","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","filePath","pathname","endsWith","chunkName","rscRendererCache","Map","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","entries","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","join","exportRoutesAsync","getBuildConfig","default","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","clear","fileURL","fileURLToPath","str","replace"],"mappings":"AAAA;;;;;CAKC,GACD;;;;;;;;;;;IAmCgBA,gCAAgC,MAAhCA,gCAAgC;IAofnCC,iBAAiB,MAAjBA,iBAAiB;;;yBAvhBK,oBAAoB;;;;;;;yBAEtB,mCAAmC;;;;;;;8DACjD,QAAQ;;;;;;;8DACV,MAAM;;;;;;;8DACP,KAAK;;;;;;qCAES,uBAAuB;sBAE3B,qBAAqB;oBACvB,mBAAmB;oBACd,mBAAmB;wBACZ,uBAAuB;gDACZ,8CAA8C;8BAKtF,4BAA4B;;;;;;AAEnC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,UAAU,CAAC,AAAsB,AAAC;AAajE,MAAMC,sBAAsB,GAAGC,IAAAA,GAAO,QAAA,EAACC,MAAkB,EAAA,mBAAA,CAAC,AAAC;AAEpD,SAASN,gCAAgC,CAC9CO,WAAmB,EACnB,EACEC,OAAO,CAAA,EACPC,oBAAoB,CAAA,EACpBC,aAAa,CAAA,EACbC,sBAAsB,CAAA,EACtBC,eAAe,CAAA,EACfC,cAAc,CAAA,EAWf,EACD;IACA,MAAMC,YAAY,GAAGF,eAAe,GAChC,yCAAyC,GACzC,iDAAiD,AAAC;IAEtD,MAAMG,aAAa,GAAGC,IAAAA,IAAgB,EAAA,iBAAA,EAAC;QACrCC,MAAM,EAAE,EAAE;QACV,0BAA0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CAAC,+BAA+B,CAAC,CAAC;IACnD,CAAC;IACD,OAAOgE,KAAK,GAAG,MAAM,CAAC;AACxB,CAAC,AAAC;AAEF,SAAStD,UAAU,CAACyF,GAAW,EAAE;IAC/B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,GAAG,CAACC,OAAO,qBAAqB,qBAAqB,CAAC,CAAC;AAChE,CAAC"}
|
|
@@ -29,6 +29,7 @@ function _resolveFrom() {
|
|
|
29
29
|
}
|
|
30
30
|
const _metroOptions = require("./metroOptions");
|
|
31
31
|
const _log = require("../../../log");
|
|
32
|
+
const _filePath = require("../../../utils/filePath");
|
|
32
33
|
const _fn = require("../../../utils/fn");
|
|
33
34
|
const _createServerComponentsMiddleware = require("../metro/createServerComponentsMiddleware");
|
|
34
35
|
function _interopRequireDefault(obj) {
|
|
@@ -62,9 +63,10 @@ function createDomComponentsMiddleware({ metroRoot , projectRoot }, instanceMet
|
|
|
62
63
|
checkWebViewInstalled(projectRoot);
|
|
63
64
|
warnUnstable();
|
|
64
65
|
// Generate a unique entry file for the webview.
|
|
65
|
-
const generatedEntry = file.startsWith("file://") ? (0, _createServerComponentsMiddleware.fileURLToFilePath)(file) : file;
|
|
66
|
-
const virtualEntry = (0, _resolveFrom().default)(projectRoot, "expo/dom/entry.js");
|
|
67
|
-
|
|
66
|
+
const generatedEntry = (0, _filePath.toPosixPath)(file.startsWith("file://") ? (0, _createServerComponentsMiddleware.fileURLToFilePath)(file) : file);
|
|
67
|
+
const virtualEntry = (0, _filePath.toPosixPath)((0, _resolveFrom().default)(projectRoot, "expo/dom/entry.js"));
|
|
68
|
+
// The relative import path will be used like URI so it must be POSIX.
|
|
69
|
+
const relativeImport = "./" + _path().default.posix.relative(_path().default.dirname(virtualEntry), generatedEntry);
|
|
68
70
|
// Create the script URL
|
|
69
71
|
const requestUrlBase = `http://${req.headers.host}`;
|
|
70
72
|
const metroUrl = new URL((0, _metroOptions.createBundleUrlPath)({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/DomComponentsMiddleware.ts"],"sourcesContent":["import path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { createBundleUrlPath, ExpoMetroOptions } from './metroOptions';\nimport type { ServerRequest, ServerResponse } from './server.types';\nimport { Log } from '../../../log';\nimport { memoize } from '../../../utils/fn';\nimport { fileURLToFilePath } from '../metro/createServerComponentsMiddleware';\n\nexport type PickPartial<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\n\nexport const DOM_COMPONENTS_BUNDLE_DIR = 'www.bundle';\n\nconst warnUnstable = memoize(() =>\n Log.warn('Using experimental DOM Components API. Production exports may not work as expected.')\n);\n\nconst checkWebViewInstalled = memoize((projectRoot: string) => {\n const webViewInstalled =\n resolveFrom.silent(projectRoot, 'react-native-webview') ||\n resolveFrom.silent(projectRoot, '@expo/dom-webview');\n if (!webViewInstalled) {\n throw new Error(\n `To use DOM Components, you must install the 'react-native-webview' package. Run 'npx expo install react-native-webview' to install it.`\n );\n }\n});\n\ntype CreateDomComponentsMiddlewareOptions = {\n /** The absolute metro or server root, used to calculate the relative dom entry path */\n metroRoot: string;\n /** The absolute project root, used to resolve the `expo/dom/entry.js` path */\n projectRoot: string;\n};\n\nexport function createDomComponentsMiddleware(\n { metroRoot, projectRoot }: CreateDomComponentsMiddlewareOptions,\n instanceMetroOptions: PickPartial<ExpoMetroOptions, 'mainModuleName' | 'platform' | 'bytecode'>\n) {\n return (req: ServerRequest, res: ServerResponse, next: (err?: Error) => void) => {\n if (!req.url) return next();\n\n const url = coerceUrl(req.url);\n\n // Match `/_expo/@dom`.\n // This URL can contain additional paths like `/_expo/@dom/foo.js?file=...` to help the Safari dev tools.\n if (!url.pathname.startsWith('/_expo/@dom')) {\n return next();\n }\n\n const file = url.searchParams.get('file');\n\n if (!file || !file.startsWith('file://')) {\n res.statusCode = 400;\n res.statusMessage = 'Invalid file path: ' + file;\n return res.end();\n }\n\n checkWebViewInstalled(projectRoot);\n warnUnstable();\n\n // Generate a unique entry file for the webview.\n const generatedEntry = file.startsWith('file://') ? fileURLToFilePath(file) : file;\n const virtualEntry = resolveFrom(projectRoot, 'expo/dom/entry.js');\n const relativeImport = './' + path.relative(path.dirname(virtualEntry), generatedEntry);\n // Create the script URL\n const requestUrlBase = `http://${req.headers.host}`;\n const metroUrl = new URL(\n createBundleUrlPath({\n ...instanceMetroOptions,\n domRoot: encodeURI(relativeImport),\n baseUrl: '/',\n mainModuleName: path.relative(metroRoot, virtualEntry),\n bytecode: false,\n platform: 'web',\n isExporting: false,\n engine: 'hermes',\n // Required for ensuring bundler errors are caught in the root entry / async boundary and can be recovered from automatically.\n lazy: true,\n }),\n requestUrlBase\n ).toString();\n\n res.statusCode = 200;\n // Return HTML file\n res.setHeader('Content-Type', 'text/html');\n\n res.end(\n // Create the entry HTML file.\n getDomComponentHtml(metroUrl, { title: path.basename(file) })\n );\n };\n}\n\nfunction coerceUrl(url: string) {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'https://localhost:0');\n }\n}\n\nexport function getDomComponentHtml(src?: string, { title }: { title?: string } = {}) {\n // This HTML is not optimized for `react-native-web` since DOM Components are meant for general React DOM web development.\n return `\n<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta httpEquiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">\n ${title ? `<title>${title}</title>` : ''}\n <style id=\"expo-dom-component-style\">\n /* These styles make the body full-height */\n html,\n body {\n -webkit-overflow-scrolling: touch; /* Enables smooth momentum scrolling */\n }\n /* These styles make the root element full-height */\n #root {\n display: flex;\n flex: 1;\n }\n </style>\n </head>\n <body>\n <noscript>DOM Components require <code>javaScriptEnabled</code></noscript>\n <!-- Root element for the DOM component. -->\n <div id=\"root\"></div>\n ${src ? `<script crossorigin src=\"${src}\"></script>` : ''}\n </body>\n</html>`;\n}\n"],"names":["DOM_COMPONENTS_BUNDLE_DIR","createDomComponentsMiddleware","getDomComponentHtml","warnUnstable","memoize","Log","warn","checkWebViewInstalled","projectRoot","webViewInstalled","resolveFrom","silent","Error","metroRoot","instanceMetroOptions","req","res","next","url","coerceUrl","pathname","startsWith","file","searchParams","get","statusCode","statusMessage","end","generatedEntry","fileURLToFilePath","virtualEntry","relativeImport","path","relative","dirname","requestUrlBase","headers","host","metroUrl","URL","createBundleUrlPath","domRoot","encodeURI","baseUrl","mainModuleName","bytecode","platform","isExporting","engine","lazy","toString","setHeader","title","basename","src"],"mappings":"AAAA;;;;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/DomComponentsMiddleware.ts"],"sourcesContent":["import path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { createBundleUrlPath, ExpoMetroOptions } from './metroOptions';\nimport type { ServerRequest, ServerResponse } from './server.types';\nimport { Log } from '../../../log';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { fileURLToFilePath } from '../metro/createServerComponentsMiddleware';\n\nexport type PickPartial<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\n\nexport const DOM_COMPONENTS_BUNDLE_DIR = 'www.bundle';\n\nconst warnUnstable = memoize(() =>\n Log.warn('Using experimental DOM Components API. Production exports may not work as expected.')\n);\n\nconst checkWebViewInstalled = memoize((projectRoot: string) => {\n const webViewInstalled =\n resolveFrom.silent(projectRoot, 'react-native-webview') ||\n resolveFrom.silent(projectRoot, '@expo/dom-webview');\n if (!webViewInstalled) {\n throw new Error(\n `To use DOM Components, you must install the 'react-native-webview' package. Run 'npx expo install react-native-webview' to install it.`\n );\n }\n});\n\ntype CreateDomComponentsMiddlewareOptions = {\n /** The absolute metro or server root, used to calculate the relative dom entry path */\n metroRoot: string;\n /** The absolute project root, used to resolve the `expo/dom/entry.js` path */\n projectRoot: string;\n};\n\nexport function createDomComponentsMiddleware(\n { metroRoot, projectRoot }: CreateDomComponentsMiddlewareOptions,\n instanceMetroOptions: PickPartial<ExpoMetroOptions, 'mainModuleName' | 'platform' | 'bytecode'>\n) {\n return (req: ServerRequest, res: ServerResponse, next: (err?: Error) => void) => {\n if (!req.url) return next();\n\n const url = coerceUrl(req.url);\n\n // Match `/_expo/@dom`.\n // This URL can contain additional paths like `/_expo/@dom/foo.js?file=...` to help the Safari dev tools.\n if (!url.pathname.startsWith('/_expo/@dom')) {\n return next();\n }\n\n const file = url.searchParams.get('file');\n\n if (!file || !file.startsWith('file://')) {\n res.statusCode = 400;\n res.statusMessage = 'Invalid file path: ' + file;\n return res.end();\n }\n\n checkWebViewInstalled(projectRoot);\n warnUnstable();\n\n // Generate a unique entry file for the webview.\n const generatedEntry = toPosixPath(file.startsWith('file://') ? fileURLToFilePath(file) : file);\n const virtualEntry = toPosixPath(resolveFrom(projectRoot, 'expo/dom/entry.js'));\n // The relative import path will be used like URI so it must be POSIX.\n const relativeImport = './' + path.posix.relative(path.dirname(virtualEntry), generatedEntry);\n // Create the script URL\n const requestUrlBase = `http://${req.headers.host}`;\n const metroUrl = new URL(\n createBundleUrlPath({\n ...instanceMetroOptions,\n domRoot: encodeURI(relativeImport),\n baseUrl: '/',\n mainModuleName: path.relative(metroRoot, virtualEntry),\n bytecode: false,\n platform: 'web',\n isExporting: false,\n engine: 'hermes',\n // Required for ensuring bundler errors are caught in the root entry / async boundary and can be recovered from automatically.\n lazy: true,\n }),\n requestUrlBase\n ).toString();\n\n res.statusCode = 200;\n // Return HTML file\n res.setHeader('Content-Type', 'text/html');\n\n res.end(\n // Create the entry HTML file.\n getDomComponentHtml(metroUrl, { title: path.basename(file) })\n );\n };\n}\n\nfunction coerceUrl(url: string) {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'https://localhost:0');\n }\n}\n\nexport function getDomComponentHtml(src?: string, { title }: { title?: string } = {}) {\n // This HTML is not optimized for `react-native-web` since DOM Components are meant for general React DOM web development.\n return `\n<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta httpEquiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">\n ${title ? `<title>${title}</title>` : ''}\n <style id=\"expo-dom-component-style\">\n /* These styles make the body full-height */\n html,\n body {\n -webkit-overflow-scrolling: touch; /* Enables smooth momentum scrolling */\n }\n /* These styles make the root element full-height */\n #root {\n display: flex;\n flex: 1;\n }\n </style>\n </head>\n <body>\n <noscript>DOM Components require <code>javaScriptEnabled</code></noscript>\n <!-- Root element for the DOM component. -->\n <div id=\"root\"></div>\n ${src ? `<script crossorigin src=\"${src}\"></script>` : ''}\n </body>\n</html>`;\n}\n"],"names":["DOM_COMPONENTS_BUNDLE_DIR","createDomComponentsMiddleware","getDomComponentHtml","warnUnstable","memoize","Log","warn","checkWebViewInstalled","projectRoot","webViewInstalled","resolveFrom","silent","Error","metroRoot","instanceMetroOptions","req","res","next","url","coerceUrl","pathname","startsWith","file","searchParams","get","statusCode","statusMessage","end","generatedEntry","toPosixPath","fileURLToFilePath","virtualEntry","relativeImport","path","posix","relative","dirname","requestUrlBase","headers","host","metroUrl","URL","createBundleUrlPath","domRoot","encodeURI","baseUrl","mainModuleName","bytecode","platform","isExporting","engine","lazy","toString","setHeader","title","basename","src"],"mappings":"AAAA;;;;;;;;;;;IAYaA,yBAAyB,MAAzBA,yBAAyB;IAwBtBC,6BAA6B,MAA7BA,6BAA6B;IAoE7BC,mBAAmB,MAAnBA,mBAAmB;;;8DAxGlB,MAAM;;;;;;;8DACC,cAAc;;;;;;8BAEgB,gBAAgB;qBAElD,cAAc;0BACN,yBAAyB;oBAC7B,mBAAmB;kDACT,2CAA2C;;;;;;AAItE,MAAMF,yBAAyB,GAAG,YAAY,AAAC;AAEtD,MAAMG,YAAY,GAAGC,IAAAA,GAAO,QAAA,EAAC,IAC3BC,IAAG,IAAA,CAACC,IAAI,CAAC,qFAAqF,CAAC,CAChG,AAAC;AAEF,MAAMC,qBAAqB,G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Q,CAACjC,IAAI,CAAC;SAAE,CAAC,CAC9D,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAED,SAASH,SAAS,CAACD,GAAW,EAAE;IAC9B,IAAI;QACF,OAAO,IAAIuB,GAAG,CAACvB,GAAG,CAAC,CAAC;IACtB,EAAE,OAAM;QACN,OAAO,IAAIuB,GAAG,CAACvB,GAAG,EAAE,qBAAqB,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC;AAEM,SAAShB,mBAAmB,CAACsD,GAAY,EAAE,EAAEF,KAAK,CAAA,EAAsB,GAAG,EAAE,EAAE;IACpF,0HAA0H;IAC1H,OAAO,CAAC;;;;;;;QAOF,EAAEA,KAAK,GAAG,CAAC,OAAO,EAAEA,KAAK,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC;;;;;;;;;;;;;;;;;;QAkBzC,EAAEE,GAAG,GAAG,CAAC,yBAAyB,EAAEA,GAAG,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC;;OAE3D,CAAC,CAAC;AACT,CAAC"}
|
|
@@ -2,9 +2,15 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", {
|
|
3
3
|
value: true
|
|
4
4
|
});
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
function _export(target, all) {
|
|
6
|
+
for(var name in all)Object.defineProperty(target, name, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: all[name]
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
_export(exports, {
|
|
12
|
+
resolveRealEntryFilePath: ()=>resolveRealEntryFilePath,
|
|
13
|
+
toPosixPath: ()=>toPosixPath
|
|
8
14
|
});
|
|
9
15
|
function _fs() {
|
|
10
16
|
const data = /*#__PURE__*/ _interopRequireDefault(require("fs"));
|
|
@@ -18,11 +24,15 @@ function _interopRequireDefault(obj) {
|
|
|
18
24
|
default: obj
|
|
19
25
|
};
|
|
20
26
|
}
|
|
27
|
+
const REGEXP_REPLACE_SLASHES = /\\/g;
|
|
21
28
|
function resolveRealEntryFilePath(projectRoot, entryFile) {
|
|
22
29
|
if (projectRoot.startsWith("/private/var") && entryFile.startsWith("/var")) {
|
|
23
30
|
return _fs().default.realpathSync(entryFile);
|
|
24
31
|
}
|
|
25
32
|
return entryFile;
|
|
26
33
|
}
|
|
34
|
+
function toPosixPath(filePath) {
|
|
35
|
+
return filePath.replace(REGEXP_REPLACE_SLASHES, "/");
|
|
36
|
+
}
|
|
27
37
|
|
|
28
38
|
//# sourceMappingURL=filePath.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/filePath.ts"],"sourcesContent":["import fs from 'fs';\n\n/**\n * This is a workaround for Metro not resolving entry file paths to their real location.\n * When running exports through `eas build --local` on macOS, the `/var/folders` path is used instead of `/private/var/folders`.\n *\n * See: https://github.com/expo/expo/issues/28890\n */\nexport function resolveRealEntryFilePath(projectRoot: string, entryFile: string): string {\n if (projectRoot.startsWith('/private/var') && entryFile.startsWith('/var')) {\n return fs.realpathSync(entryFile);\n }\n\n return entryFile;\n}\n"],"names":["resolveRealEntryFilePath","projectRoot","entryFile","startsWith","fs","realpathSync"],"mappings":"AAAA
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/filePath.ts"],"sourcesContent":["import fs from 'fs';\n\nconst REGEXP_REPLACE_SLASHES = /\\\\/g;\n\n/**\n * This is a workaround for Metro not resolving entry file paths to their real location.\n * When running exports through `eas build --local` on macOS, the `/var/folders` path is used instead of `/private/var/folders`.\n *\n * See: https://github.com/expo/expo/issues/28890\n */\nexport function resolveRealEntryFilePath(projectRoot: string, entryFile: string): string {\n if (projectRoot.startsWith('/private/var') && entryFile.startsWith('/var')) {\n return fs.realpathSync(entryFile);\n }\n\n return entryFile;\n}\n\n/**\n * Convert any platform-specific path to a POSIX path.\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replace(REGEXP_REPLACE_SLASHES, '/');\n}\n"],"names":["resolveRealEntryFilePath","toPosixPath","REGEXP_REPLACE_SLASHES","projectRoot","entryFile","startsWith","fs","realpathSync","filePath","replace"],"mappings":"AAAA;;;;;;;;;;;IAUgBA,wBAAwB,MAAxBA,wBAAwB;IAWxBC,WAAW,MAAXA,WAAW;;;8DArBZ,IAAI;;;;;;;;;;;AAEnB,MAAMC,sBAAsB,QAAQ,AAAC;AAQ9B,SAASF,wBAAwB,CAACG,WAAmB,EAAEC,SAAiB,EAAU;IACvF,IAAID,WAAW,CAACE,UAAU,CAAC,cAAc,CAAC,IAAID,SAAS,CAACC,UAAU,CAAC,MAAM,CAAC,EAAE;QAC1E,OAAOC,GAAE,EAAA,QAAA,CAACC,YAAY,CAACH,SAAS,CAAC,CAAC;IACpC,CAAC;IAED,OAAOA,SAAS,CAAC;AACnB,CAAC;AAKM,SAASH,WAAW,CAACO,QAAgB,EAAU;IACpD,OAAOA,QAAQ,CAACC,OAAO,CAACP,sBAAsB,EAAE,GAAG,CAAC,CAAC;AACvD,CAAC"}
|
|
@@ -31,7 +31,7 @@ class FetchClient {
|
|
|
31
31
|
this.headers = {
|
|
32
32
|
accept: "application/json",
|
|
33
33
|
"content-type": "application/json",
|
|
34
|
-
"user-agent": `expo-cli/${"0.
|
|
34
|
+
"user-agent": `expo-cli/${"0.22.1"}`,
|
|
35
35
|
authorization: "Basic " + _nodeBuffer().Buffer.from(`${target}:`).toString("base64")
|
|
36
36
|
};
|
|
37
37
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@expo/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.1",
|
|
4
4
|
"description": "The Expo CLI",
|
|
5
5
|
"main": "build/bin/cli",
|
|
6
6
|
"bin": {
|
|
@@ -167,5 +167,5 @@
|
|
|
167
167
|
"tree-kill": "^1.2.2",
|
|
168
168
|
"tsd": "^0.28.1"
|
|
169
169
|
},
|
|
170
|
-
"gitHead": "
|
|
170
|
+
"gitHead": "a1fac063b47a647f2a9737e201d502066c52d4b0"
|
|
171
171
|
}
|