@expo/cli 54.1.0-canary-20250930-9dc59d3 → 54.1.0-canary-20251003-7b9d7ff
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/run/ios/runIosAsync.js +0 -8
- package/build/src/run/ios/runIosAsync.js.map +1 -1
- package/build/src/serve/serveAsync.js +7 -7
- package/build/src/serve/serveAsync.js.map +1 -1
- package/build/src/start/server/metro/createServerComponentsMiddleware.js +6 -6
- package/build/src/start/server/metro/createServerComponentsMiddleware.js.map +1 -1
- package/build/src/start/server/metro/createServerRouteMiddleware.js +9 -4
- package/build/src/start/server/metro/createServerRouteMiddleware.js.map +1 -1
- package/build/src/start/server/metro/router.js.map +1 -1
- package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.js +1 -1
- package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.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 +17 -17
- package/static/template/[...rsc]+api.ts +1 -1
package/build/bin/cli
CHANGED
|
@@ -123,7 +123,7 @@ const args = (0, _arg().default)({
|
|
|
123
123
|
});
|
|
124
124
|
if (args['--version']) {
|
|
125
125
|
// Version is added in the build script.
|
|
126
|
-
console.log("54.1.0-canary-
|
|
126
|
+
console.log("54.1.0-canary-20251003-7b9d7ff");
|
|
127
127
|
process.exit(0);
|
|
128
128
|
}
|
|
129
129
|
if (args['--non-interactive']) {
|
|
@@ -8,13 +8,6 @@ Object.defineProperty(exports, "runIosAsync", {
|
|
|
8
8
|
return runIosAsync;
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
|
-
function _config() {
|
|
12
|
-
const data = require("@expo/config");
|
|
13
|
-
_config = function() {
|
|
14
|
-
return data;
|
|
15
|
-
};
|
|
16
|
-
return data;
|
|
17
|
-
}
|
|
18
11
|
function _spawnasync() {
|
|
19
12
|
const data = /*#__PURE__*/ _interop_require_default(require("@expo/spawn-async"));
|
|
20
13
|
_spawnasync = function() {
|
|
@@ -122,7 +115,6 @@ async function runIosAsync(projectRoot, options) {
|
|
|
122
115
|
}
|
|
123
116
|
// Resolve the CLI arguments into useable options.
|
|
124
117
|
const props = await (0, _profile.profile)(_resolveOptions.resolveOptionsAsync)(projectRoot, options);
|
|
125
|
-
const projectConfig = (0, _config().getConfig)(projectRoot);
|
|
126
118
|
// We only support build cache for simulator builds for now.
|
|
127
119
|
if (!options.binary && props.buildCacheProvider && props.isSimulator) {
|
|
128
120
|
const localPath = await (0, _buildcacheproviders.resolveBuildCache)({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/run/ios/runIosAsync.ts"],"sourcesContent":["import { getConfig } from '@expo/config';\nimport spawnAsync from '@expo/spawn-async';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport path from 'path';\n\nimport * as XcodeBuild from './XcodeBuild';\nimport { Options } from './XcodeBuild.types';\nimport { getLaunchInfoForBinaryAsync, launchAppAsync } from './launchApp';\nimport { resolveOptionsAsync } from './options/resolveOptions';\nimport { getValidBinaryPathAsync } from './validateExternalBinary';\nimport { exportEagerAsync } from '../../export/embed/exportEager';\nimport * as Log from '../../log';\nimport { AppleAppIdResolver } from '../../start/platforms/ios/AppleAppIdResolver';\nimport { getContainerPathAsync, simctlAsync } from '../../start/platforms/ios/simctl';\nimport { resolveBuildCache, uploadBuildCache } from '../../utils/build-cache-providers';\nimport { maybePromptToSyncPodsAsync } from '../../utils/cocoapods';\nimport { CommandError } from '../../utils/errors';\nimport { setNodeEnv } from '../../utils/nodeEnv';\nimport { ensurePortAvailabilityAsync } from '../../utils/port';\nimport { profile } from '../../utils/profile';\nimport { getSchemesForIosAsync } from '../../utils/scheme';\nimport { ensureNativeProjectAsync } from '../ensureNativeProject';\nimport { logProjectLogsLocation } from '../hints';\nimport { startBundlerAsync } from '../startBundler';\n\nconst debug = require('debug')('expo:run:ios');\n\nexport async function runIosAsync(projectRoot: string, options: Options) {\n setNodeEnv(options.configuration === 'Release' ? 'production' : 'development');\n require('@expo/env').load(projectRoot);\n\n assertPlatform();\n\n const install = !!options.install;\n\n if ((await ensureNativeProjectAsync(projectRoot, { platform: 'ios', install })) && install) {\n await maybePromptToSyncPodsAsync(projectRoot);\n }\n\n // Resolve the CLI arguments into useable options.\n const props = await profile(resolveOptionsAsync)(projectRoot, options);\n\n const projectConfig = getConfig(projectRoot);\n // We only support build cache for simulator builds for now.\n if (!options.binary && props.buildCacheProvider && props.isSimulator) {\n const localPath = await resolveBuildCache({\n projectRoot,\n platform: 'ios',\n runOptions: options,\n provider: props.buildCacheProvider,\n });\n if (localPath) {\n options.binary = localPath;\n }\n }\n\n if (options.rebundle) {\n Log.warn(`The --unstable-rebundle flag is experimental and may not work as expected.`);\n // Get the existing binary path to re-bundle the app.\n\n let binaryPath: string;\n if (!options.binary) {\n if (!props.isSimulator) {\n throw new Error('Re-bundling on physical devices requires the --binary flag.');\n }\n const appId = await new AppleAppIdResolver(projectRoot).getAppIdAsync();\n const possibleBinaryPath = await getContainerPathAsync(props.device, {\n appId,\n });\n if (!possibleBinaryPath) {\n throw new CommandError(\n `Cannot rebundle because no --binary was provided and no existing binary was found on the device for ID: ${appId}.`\n );\n }\n binaryPath = possibleBinaryPath;\n Log.log('Re-using existing binary path:', binaryPath);\n // Set the binary path to the existing binary path.\n options.binary = binaryPath;\n }\n\n Log.log('Rebundling the Expo config file');\n // Re-bundle the config file the same way the app was originally bundled.\n await spawnAsync('node', [\n // TODO(@kitten): This isn't correct. The template installs expo-constants, but expo also depends on it\n // This however means that the top-level module doesn't have to exist. With isolated dependencies this will then fail\n // But we can't resolve via `expo` because that then may do something differently than autolinking if the root has a different version\n path.join(require.resolve('expo-constants/package.json'), '../scripts/getAppConfig.js'),\n projectRoot,\n path.join(options.binary, 'EXConstants.bundle'),\n ]);\n // Re-bundle the app.\n\n const possibleBundleOutput = path.join(options.binary, 'main.jsbundle');\n\n if (fs.existsSync(possibleBundleOutput)) {\n Log.log('Rebundling the app...');\n await exportEagerAsync(projectRoot, {\n resetCache: false,\n dev: false,\n platform: 'ios',\n assetsDest: path.join(options.binary, 'assets'),\n bundleOutput: possibleBundleOutput,\n });\n } else {\n Log.warn('Bundle output not found at expected location:', possibleBundleOutput);\n }\n }\n\n let binaryPath: string;\n let shouldUpdateBuildCache = false;\n if (options.binary) {\n binaryPath = await getValidBinaryPathAsync(options.binary, props);\n Log.log('Using custom binary path:', binaryPath);\n } else {\n let eagerBundleOptions: string | undefined;\n\n if (options.configuration === 'Release') {\n eagerBundleOptions = JSON.stringify(\n await exportEagerAsync(projectRoot, {\n dev: false,\n platform: 'ios',\n })\n );\n }\n\n // Spawn the `xcodebuild` process to create the app binary.\n const buildOutput = await XcodeBuild.buildAsync({\n ...props,\n eagerBundleOptions,\n });\n\n // Find the path to the built app binary, this will be used to install the binary\n // on a device.\n binaryPath = await profile(XcodeBuild.getAppBinaryPath)(buildOutput);\n // We only support build cache for simulator builds for now.\n shouldUpdateBuildCache = props.isSimulator;\n }\n debug('Binary path:', binaryPath);\n\n // Ensure the port hasn't become busy during the build.\n if (props.shouldStartBundler && !(await ensurePortAvailabilityAsync(projectRoot, props))) {\n props.shouldStartBundler = false;\n }\n\n const launchInfo = await getLaunchInfoForBinaryAsync(binaryPath);\n const isCustomBinary = !!options.binary;\n\n // Always close the app before launching on a simulator. Otherwise certain cached resources like the splashscreen will not be available.\n if (props.isSimulator) {\n try {\n await simctlAsync(['terminate', props.device.udid, launchInfo.bundleId]);\n } catch (error) {\n // If we failed it's likely that the app was not running to begin with and we will get an `invalid device` error\n debug('Failed to terminate app (possibly because it was not running):', error);\n }\n }\n\n // Start the dev server which creates all of the required info for\n // launching the app on a simulator.\n const manager = await startBundlerAsync(projectRoot, {\n port: props.port,\n headless: !props.shouldStartBundler,\n // If a scheme is specified then use that instead of the package name.\n\n scheme: isCustomBinary\n ? // If launching a custom binary, use the schemes in the Info.plist.\n launchInfo.schemes[0]\n : // If a scheme is specified then use that instead of the package name.\n (await getSchemesForIosAsync(projectRoot))?.[0],\n });\n\n // Install and launch the app binary on a device.\n await launchAppAsync(\n binaryPath,\n manager,\n {\n isSimulator: props.isSimulator,\n device: props.device,\n shouldStartBundler: props.shouldStartBundler,\n },\n launchInfo.bundleId\n );\n\n // Log the location of the JS logs for the device.\n if (props.shouldStartBundler) {\n logProjectLogsLocation();\n } else {\n await manager.stopAsync();\n }\n\n if (shouldUpdateBuildCache && props.buildCacheProvider) {\n await uploadBuildCache({\n projectRoot,\n platform: 'ios',\n provider: props.buildCacheProvider,\n buildPath: binaryPath,\n runOptions: options,\n });\n }\n}\n\nfunction assertPlatform() {\n if (process.platform !== 'darwin') {\n Log.exit(\n chalk`iOS apps can only be built on macOS devices. Use {cyan eas build -p ios} to build in the cloud.`\n );\n }\n}\n"],"names":["runIosAsync","debug","require","projectRoot","options","setNodeEnv","configuration","load","assertPlatform","install","ensureNativeProjectAsync","platform","maybePromptToSyncPodsAsync","props","profile","resolveOptionsAsync","projectConfig","getConfig","binary","buildCacheProvider","isSimulator","localPath","resolveBuildCache","runOptions","provider","rebundle","Log","warn","binaryPath","Error","appId","AppleAppIdResolver","getAppIdAsync","possibleBinaryPath","getContainerPathAsync","device","CommandError","log","spawnAsync","path","join","resolve","possibleBundleOutput","fs","existsSync","exportEagerAsync","resetCache","dev","assetsDest","bundleOutput","shouldUpdateBuildCache","getValidBinaryPathAsync","eagerBundleOptions","JSON","stringify","buildOutput","XcodeBuild","buildAsync","getAppBinaryPath","shouldStartBundler","ensurePortAvailabilityAsync","launchInfo","getLaunchInfoForBinaryAsync","isCustomBinary","simctlAsync","udid","bundleId","error","manager","startBundlerAsync","port","headless","scheme","schemes","getSchemesForIosAsync","launchAppAsync","logProjectLogsLocation","stopAsync","uploadBuildCache","buildPath","process","exit","chalk"],"mappings":";;;;+BA4BsBA;;;eAAAA;;;;yBA5BI;;;;;;;gEACH;;;;;;;gEACL;;;;;;;gEACH;;;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MsB,MAAM;QACpBwB,oBAAoB9C,MAAM8C,kBAAkB;IAC9C,GACAE,WAAWK,QAAQ;IAGrB,kDAAkD;IAClD,IAAIrD,MAAM8C,kBAAkB,EAAE;QAC5BiB,IAAAA,6BAAsB;IACxB,OAAO;QACL,MAAMR,QAAQS,SAAS;IACzB;IAEA,IAAI3B,0BAA0BrC,MAAMM,kBAAkB,EAAE;QACtD,MAAM2D,IAAAA,qCAAgB,EAAC;YACrB3E;YACAQ,UAAU;YACVa,UAAUX,MAAMM,kBAAkB;YAClC4D,WAAWnD;YACXL,YAAYnB;QACd;IACF;AACF;AAEA,SAASI;IACP,IAAIwE,QAAQrE,QAAQ,KAAK,UAAU;QACjCe,KAAIuD,IAAI,CACNC,IAAAA,gBAAK,CAAA,CAAC,+FAA+F,CAAC;IAE1G;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/run/ios/runIosAsync.ts"],"sourcesContent":["import spawnAsync from '@expo/spawn-async';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport path from 'path';\n\nimport * as XcodeBuild from './XcodeBuild';\nimport { Options } from './XcodeBuild.types';\nimport { getLaunchInfoForBinaryAsync, launchAppAsync } from './launchApp';\nimport { resolveOptionsAsync } from './options/resolveOptions';\nimport { getValidBinaryPathAsync } from './validateExternalBinary';\nimport { exportEagerAsync } from '../../export/embed/exportEager';\nimport * as Log from '../../log';\nimport { AppleAppIdResolver } from '../../start/platforms/ios/AppleAppIdResolver';\nimport { getContainerPathAsync, simctlAsync } from '../../start/platforms/ios/simctl';\nimport { resolveBuildCache, uploadBuildCache } from '../../utils/build-cache-providers';\nimport { maybePromptToSyncPodsAsync } from '../../utils/cocoapods';\nimport { CommandError } from '../../utils/errors';\nimport { setNodeEnv } from '../../utils/nodeEnv';\nimport { ensurePortAvailabilityAsync } from '../../utils/port';\nimport { profile } from '../../utils/profile';\nimport { getSchemesForIosAsync } from '../../utils/scheme';\nimport { ensureNativeProjectAsync } from '../ensureNativeProject';\nimport { logProjectLogsLocation } from '../hints';\nimport { startBundlerAsync } from '../startBundler';\n\nconst debug = require('debug')('expo:run:ios');\n\nexport async function runIosAsync(projectRoot: string, options: Options) {\n setNodeEnv(options.configuration === 'Release' ? 'production' : 'development');\n require('@expo/env').load(projectRoot);\n\n assertPlatform();\n\n const install = !!options.install;\n\n if ((await ensureNativeProjectAsync(projectRoot, { platform: 'ios', install })) && install) {\n await maybePromptToSyncPodsAsync(projectRoot);\n }\n\n // Resolve the CLI arguments into useable options.\n const props = await profile(resolveOptionsAsync)(projectRoot, options);\n\n // We only support build cache for simulator builds for now.\n if (!options.binary && props.buildCacheProvider && props.isSimulator) {\n const localPath = await resolveBuildCache({\n projectRoot,\n platform: 'ios',\n runOptions: options,\n provider: props.buildCacheProvider,\n });\n if (localPath) {\n options.binary = localPath;\n }\n }\n\n if (options.rebundle) {\n Log.warn(`The --unstable-rebundle flag is experimental and may not work as expected.`);\n // Get the existing binary path to re-bundle the app.\n\n let binaryPath: string;\n if (!options.binary) {\n if (!props.isSimulator) {\n throw new Error('Re-bundling on physical devices requires the --binary flag.');\n }\n const appId = await new AppleAppIdResolver(projectRoot).getAppIdAsync();\n const possibleBinaryPath = await getContainerPathAsync(props.device, {\n appId,\n });\n if (!possibleBinaryPath) {\n throw new CommandError(\n `Cannot rebundle because no --binary was provided and no existing binary was found on the device for ID: ${appId}.`\n );\n }\n binaryPath = possibleBinaryPath;\n Log.log('Re-using existing binary path:', binaryPath);\n // Set the binary path to the existing binary path.\n options.binary = binaryPath;\n }\n\n Log.log('Rebundling the Expo config file');\n // Re-bundle the config file the same way the app was originally bundled.\n await spawnAsync('node', [\n // TODO(@kitten): This isn't correct. The template installs expo-constants, but expo also depends on it\n // This however means that the top-level module doesn't have to exist. With isolated dependencies this will then fail\n // But we can't resolve via `expo` because that then may do something differently than autolinking if the root has a different version\n path.join(require.resolve('expo-constants/package.json'), '../scripts/getAppConfig.js'),\n projectRoot,\n path.join(options.binary, 'EXConstants.bundle'),\n ]);\n // Re-bundle the app.\n\n const possibleBundleOutput = path.join(options.binary, 'main.jsbundle');\n\n if (fs.existsSync(possibleBundleOutput)) {\n Log.log('Rebundling the app...');\n await exportEagerAsync(projectRoot, {\n resetCache: false,\n dev: false,\n platform: 'ios',\n assetsDest: path.join(options.binary, 'assets'),\n bundleOutput: possibleBundleOutput,\n });\n } else {\n Log.warn('Bundle output not found at expected location:', possibleBundleOutput);\n }\n }\n\n let binaryPath: string;\n let shouldUpdateBuildCache = false;\n if (options.binary) {\n binaryPath = await getValidBinaryPathAsync(options.binary, props);\n Log.log('Using custom binary path:', binaryPath);\n } else {\n let eagerBundleOptions: string | undefined;\n\n if (options.configuration === 'Release') {\n eagerBundleOptions = JSON.stringify(\n await exportEagerAsync(projectRoot, {\n dev: false,\n platform: 'ios',\n })\n );\n }\n\n // Spawn the `xcodebuild` process to create the app binary.\n const buildOutput = await XcodeBuild.buildAsync({\n ...props,\n eagerBundleOptions,\n });\n\n // Find the path to the built app binary, this will be used to install the binary\n // on a device.\n binaryPath = await profile(XcodeBuild.getAppBinaryPath)(buildOutput);\n // We only support build cache for simulator builds for now.\n shouldUpdateBuildCache = props.isSimulator;\n }\n debug('Binary path:', binaryPath);\n\n // Ensure the port hasn't become busy during the build.\n if (props.shouldStartBundler && !(await ensurePortAvailabilityAsync(projectRoot, props))) {\n props.shouldStartBundler = false;\n }\n\n const launchInfo = await getLaunchInfoForBinaryAsync(binaryPath);\n const isCustomBinary = !!options.binary;\n\n // Always close the app before launching on a simulator. Otherwise certain cached resources like the splashscreen will not be available.\n if (props.isSimulator) {\n try {\n await simctlAsync(['terminate', props.device.udid, launchInfo.bundleId]);\n } catch (error) {\n // If we failed it's likely that the app was not running to begin with and we will get an `invalid device` error\n debug('Failed to terminate app (possibly because it was not running):', error);\n }\n }\n\n // Start the dev server which creates all of the required info for\n // launching the app on a simulator.\n const manager = await startBundlerAsync(projectRoot, {\n port: props.port,\n headless: !props.shouldStartBundler,\n // If a scheme is specified then use that instead of the package name.\n\n scheme: isCustomBinary\n ? // If launching a custom binary, use the schemes in the Info.plist.\n launchInfo.schemes[0]\n : // If a scheme is specified then use that instead of the package name.\n (await getSchemesForIosAsync(projectRoot))?.[0],\n });\n\n // Install and launch the app binary on a device.\n await launchAppAsync(\n binaryPath,\n manager,\n {\n isSimulator: props.isSimulator,\n device: props.device,\n shouldStartBundler: props.shouldStartBundler,\n },\n launchInfo.bundleId\n );\n\n // Log the location of the JS logs for the device.\n if (props.shouldStartBundler) {\n logProjectLogsLocation();\n } else {\n await manager.stopAsync();\n }\n\n if (shouldUpdateBuildCache && props.buildCacheProvider) {\n await uploadBuildCache({\n projectRoot,\n platform: 'ios',\n provider: props.buildCacheProvider,\n buildPath: binaryPath,\n runOptions: options,\n });\n }\n}\n\nfunction assertPlatform() {\n if (process.platform !== 'darwin') {\n Log.exit(\n chalk`iOS apps can only be built on macOS devices. Use {cyan eas build -p ios} to build in the cloud.`\n );\n }\n}\n"],"names":["runIosAsync","debug","require","projectRoot","options","setNodeEnv","configuration","load","assertPlatform","install","ensureNativeProjectAsync","platform","maybePromptToSyncPodsAsync","props","profile","resolveOptionsAsync","binary","buildCacheProvider","isSimulator","localPath","resolveBuildCache","runOptions","provider","rebundle","Log","warn","binaryPath","Error","appId","AppleAppIdResolver","getAppIdAsync","possibleBinaryPath","getContainerPathAsync","device","CommandError","log","spawnAsync","path","join","resolve","possibleBundleOutput","fs","existsSync","exportEagerAsync","resetCache","dev","assetsDest","bundleOutput","shouldUpdateBuildCache","getValidBinaryPathAsync","eagerBundleOptions","JSON","stringify","buildOutput","XcodeBuild","buildAsync","getAppBinaryPath","shouldStartBundler","ensurePortAvailabilityAsync","launchInfo","getLaunchInfoForBinaryAsync","isCustomBinary","simctlAsync","udid","bundleId","error","manager","startBundlerAsync","port","headless","scheme","schemes","getSchemesForIosAsync","launchAppAsync","logProjectLogsLocation","stopAsync","uploadBuildCache","buildPath","process","exit","chalk"],"mappings":";;;;+BA2BsBA;;;eAAAA;;;;gEA3BC;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AAoB5C,MAAM4C,kBAAkB;IAC9C,GACAE,WAAWK,QAAQ;IAGrB,kDAAkD;IAClD,IAAInD,MAAM4C,kBAAkB,EAAE;QAC5BiB,IAAAA,6BAAsB;IACxB,OAAO;QACL,MAAMR,QAAQS,SAAS;IACzB;IAEA,IAAI3B,0BAA0BnC,MAAMI,kBAAkB,EAAE;QACtD,MAAM2D,IAAAA,qCAAgB,EAAC;YACrBzE;YACAQ,UAAU;YACVW,UAAUT,MAAMI,kBAAkB;YAClC4D,WAAWnD;YACXL,YAAYjB;QACd;IACF;AACF;AAEA,SAASI;IACP,IAAIsE,QAAQnE,QAAQ,KAAK,UAAU;QACjCa,KAAIuD,IAAI,CACNC,IAAAA,gBAAK,CAAA,CAAC,+FAA+F,CAAC;IAE1G;AACF"}
|
|
@@ -8,13 +8,6 @@ Object.defineProperty(exports, "serveAsync", {
|
|
|
8
8
|
return serveAsync;
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
|
-
function _http() {
|
|
12
|
-
const data = require("@expo/server/adapter/http");
|
|
13
|
-
_http = function() {
|
|
14
|
-
return data;
|
|
15
|
-
};
|
|
16
|
-
return data;
|
|
17
|
-
}
|
|
18
11
|
function _chalk() {
|
|
19
12
|
const data = /*#__PURE__*/ _interop_require_default(require("chalk"));
|
|
20
13
|
_chalk = function() {
|
|
@@ -29,6 +22,13 @@ function _connect() {
|
|
|
29
22
|
};
|
|
30
23
|
return data;
|
|
31
24
|
}
|
|
25
|
+
function _http() {
|
|
26
|
+
const data = require("expo-server/adapter/http");
|
|
27
|
+
_http = function() {
|
|
28
|
+
return data;
|
|
29
|
+
};
|
|
30
|
+
return data;
|
|
31
|
+
}
|
|
32
32
|
function _http1() {
|
|
33
33
|
const data = /*#__PURE__*/ _interop_require_default(require("http"));
|
|
34
34
|
_http1 = function() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/serve/serveAsync.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"sources":["../../../src/serve/serveAsync.ts"],"sourcesContent":["import chalk from 'chalk';\nimport connect from 'connect';\nimport { createRequestHandler } from 'expo-server/adapter/http';\nimport http from 'http';\nimport path from 'path';\nimport send from 'send';\n\nimport * as Log from '../log';\nimport { directoryExistsAsync, fileExistsAsync } from '../utils/dir';\nimport { CommandError } from '../utils/errors';\nimport { findUpProjectRootOrAssert } from '../utils/findUp';\nimport { setNodeEnv } from '../utils/nodeEnv';\nimport { resolvePortAsync } from '../utils/port';\n\ntype Options = {\n port?: number;\n isDefaultDirectory: boolean;\n};\n\nconst debug = require('debug')('expo:serve') as typeof console.log;\n\n// Start a basic http server\nexport async function serveAsync(inputDir: string, options: Options) {\n const projectRoot = findUpProjectRootOrAssert(inputDir);\n\n setNodeEnv('production');\n require('@expo/env').load(projectRoot);\n\n const port = await resolvePortAsync(projectRoot, {\n defaultPort: options.port,\n fallbackPort: 8081,\n });\n\n if (port == null) {\n throw new CommandError('Could not start server. Port is not available.');\n }\n options.port = port;\n\n const serverDist = options.isDefaultDirectory ? path.join(inputDir, 'dist') : inputDir;\n // TODO: `.expo/server/ios`, `.expo/server/android`, etc.\n\n if (!(await directoryExistsAsync(serverDist))) {\n throw new CommandError(\n `The server directory ${serverDist} does not exist. Run \\`npx expo export\\` first.`\n );\n }\n\n const isStatic = await isStaticExportAsync(serverDist);\n\n Log.log(chalk.dim(`Starting ${isStatic ? 'static ' : ''}server in ${serverDist}`));\n\n if (isStatic) {\n await startStaticServerAsync(serverDist, options);\n } else {\n await startDynamicServerAsync(serverDist, options);\n }\n Log.log(`Server running at http://localhost:${options.port}`);\n // Detect the type of server we need to setup:\n}\n\nasync function startStaticServerAsync(dist: string, options: Options) {\n const server = http.createServer((req, res) => {\n // Remove query strings and decode URI\n const filePath = decodeURI(req.url?.split('?')[0] ?? '');\n\n send(req, filePath, {\n root: dist,\n index: 'index.html',\n extensions: ['html'],\n })\n .on('error', (err: any) => {\n if (err.status === 404) {\n res.statusCode = 404;\n res.end('Not Found');\n return;\n }\n res.statusCode = err.status || 500;\n res.end('Internal Server Error');\n })\n .pipe(res);\n });\n\n server.listen(options.port!);\n}\n\nasync function startDynamicServerAsync(dist: string, options: Options) {\n const middleware = connect();\n\n const staticDirectory = path.join(dist, 'client');\n const serverDirectory = path.join(dist, 'server');\n\n const serverHandler = createRequestHandler({ build: serverDirectory });\n\n // DOM component CORS support\n middleware.use((req, res, next) => {\n // TODO: Only when origin is `file://` (iOS), and Android equivalent.\n\n // Required for DOM components security in release builds.\n\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.setHeader(\n 'Access-Control-Allow-Headers',\n 'Origin, X-Requested-With, Content-Type, Accept, expo-platform'\n );\n\n // Handle OPTIONS preflight requests\n if (req.method === 'OPTIONS') {\n res.statusCode = 200;\n res.end();\n return;\n }\n next();\n });\n\n middleware.use((req, res, next) => {\n if (!req?.url || (req.method !== 'GET' && req.method !== 'HEAD')) {\n return next();\n }\n\n const pathname = canParseURL(req.url) ? new URL(req.url).pathname : req.url;\n if (!pathname) {\n return next();\n }\n\n debug(`Maybe serve static:`, pathname);\n\n const stream = send(req, pathname, {\n root: staticDirectory,\n extensions: ['html'],\n });\n\n // add file listener for fallthrough\n let forwardError = false;\n stream.on('file', function onFile() {\n // once file is determined, always forward error\n forwardError = true;\n });\n\n // forward errors\n stream.on('error', function error(err: any) {\n if (forwardError || !(err.statusCode < 500)) {\n next(err);\n return;\n }\n\n next();\n });\n\n // pipe\n stream.pipe(res);\n });\n\n middleware.use(serverHandler);\n\n middleware.listen(options.port!);\n}\n\nfunction canParseURL(url: string): boolean {\n try {\n // eslint-disable-next-line no-new\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function isStaticExportAsync(dist: string): Promise<boolean> {\n const routesFile = path.join(dist, `server/_expo/routes.json`);\n return !(await fileExistsAsync(routesFile));\n}\n"],"names":["serveAsync","debug","require","inputDir","options","projectRoot","findUpProjectRootOrAssert","setNodeEnv","load","port","resolvePortAsync","defaultPort","fallbackPort","CommandError","serverDist","isDefaultDirectory","path","join","directoryExistsAsync","isStatic","isStaticExportAsync","Log","log","chalk","dim","startStaticServerAsync","startDynamicServerAsync","dist","server","http","createServer","req","res","filePath","decodeURI","url","split","send","root","index","extensions","on","err","status","statusCode","end","pipe","listen","middleware","connect","staticDirectory","serverDirectory","serverHandler","createRequestHandler","build","use","next","setHeader","method","pathname","canParseURL","URL","stream","forwardError","onFile","error","routesFile","fileExistsAsync"],"mappings":";;;;+BAsBsBA;;;eAAAA;;;;gEAtBJ;;;;;;;gEACE;;;;;;;yBACiB;;;;;;;gEACpB;;;;;;;gEACA;;;;;;;gEACA;;;;;;6DAEI;qBACiC;wBACzB;wBACa;yBACf;sBACM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOjC,MAAMC,QAAQC,QAAQ,SAAS;AAGxB,eAAeF,WAAWG,QAAgB,EAAEC,OAAgB;IACjE,MAAMC,cAAcC,IAAAA,iCAAyB,EAACH;IAE9CI,IAAAA,mBAAU,EAAC;IACXL,QAAQ,aAAaM,IAAI,CAACH;IAE1B,MAAMI,OAAO,MAAMC,IAAAA,sBAAgB,EAACL,aAAa;QAC/CM,aAAaP,QAAQK,IAAI;QACzBG,cAAc;IAChB;IAEA,IAAIH,QAAQ,MAAM;QAChB,MAAM,IAAII,oBAAY,CAAC;IACzB;IACAT,QAAQK,IAAI,GAAGA;IAEf,MAAMK,aAAaV,QAAQW,kBAAkB,GAAGC,eAAI,CAACC,IAAI,CAACd,UAAU,UAAUA;IAC9E,0DAA0D;IAE1D,IAAI,CAAE,MAAMe,IAAAA,yBAAoB,EAACJ,aAAc;QAC7C,MAAM,IAAID,oBAAY,CACpB,CAAC,qBAAqB,EAAEC,WAAW,+CAA+C,CAAC;IAEvF;IAEA,MAAMK,WAAW,MAAMC,oBAAoBN;IAE3CO,KAAIC,GAAG,CAACC,gBAAK,CAACC,GAAG,CAAC,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F;AAEA,eAAef,oBAAoBO,IAAY;IAC7C,MAAMuC,aAAalD,eAAI,CAACC,IAAI,CAACU,MAAM,CAAC,wBAAwB,CAAC;IAC7D,OAAO,CAAE,MAAMwC,IAAAA,oBAAe,EAACD;AACjC"}
|
|
@@ -28,16 +28,16 @@ function _paths() {
|
|
|
28
28
|
};
|
|
29
29
|
return data;
|
|
30
30
|
}
|
|
31
|
-
function
|
|
32
|
-
const data = require("
|
|
33
|
-
|
|
31
|
+
function _assert() {
|
|
32
|
+
const data = /*#__PURE__*/ _interop_require_default(require("assert"));
|
|
33
|
+
_assert = function() {
|
|
34
34
|
return data;
|
|
35
35
|
};
|
|
36
36
|
return data;
|
|
37
37
|
}
|
|
38
|
-
function
|
|
39
|
-
const data =
|
|
40
|
-
|
|
38
|
+
function _private() {
|
|
39
|
+
const data = require("expo-server/private");
|
|
40
|
+
_private = function() {
|
|
41
41
|
return data;
|
|
42
42
|
};
|
|
43
43
|
return data;
|
|
@@ -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 { getRscMiddleware } from '@expo/server/private';\nimport assert from 'assert';\nimport type { EntriesDev } from 'expo-router/build/rsc/server';\nimport path from 'path';\nimport url from '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/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 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/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<string, typeof import('expo-router/build/rsc/rsc-renderer')>();\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<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'metro-runtime/src/modules/empty-module.js',\n {\n environment: 'react-server',\n platform: 'web',\n }\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<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 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;;IAomBHC,iBAAiB;eAAjBA;;;;yBA1oBsB;;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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 assert from 'assert';\nimport type { EntriesDev } from 'expo-router/build/rsc/server';\nimport { getRscMiddleware } from 'expo-server/private';\nimport path from 'path';\nimport url from '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/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 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/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<string, typeof import('expo-router/build/rsc/rsc-renderer')>();\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<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'metro-runtime/src/modules/empty-module.js',\n {\n environment: 'react-server',\n platform: 'web',\n }\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<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 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;;IAomBHC,iBAAiB;eAAjBA;;;;yBA1oBsB;;;;;;;gEAEhB;;;;;;;yBAEc;;;;;;;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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IAAIC,OAAO,CAAC,oBAAoB;AACzC"}
|
|
@@ -13,6 +13,13 @@ Object.defineProperty(exports, "createRouteHandlerMiddleware", {
|
|
|
13
13
|
return createRouteHandlerMiddleware;
|
|
14
14
|
}
|
|
15
15
|
});
|
|
16
|
+
function _http() {
|
|
17
|
+
const data = require("expo-server/adapter/http");
|
|
18
|
+
_http = function() {
|
|
19
|
+
return data;
|
|
20
|
+
};
|
|
21
|
+
return data;
|
|
22
|
+
}
|
|
16
23
|
function _resolve() {
|
|
17
24
|
const data = /*#__PURE__*/ _interop_require_default(require("resolve"));
|
|
18
25
|
_resolve = function() {
|
|
@@ -49,8 +56,7 @@ function createRouteHandlerMiddleware(projectRoot, options) {
|
|
|
49
56
|
if (!_resolvefrom().default.silent(projectRoot, 'expo-router')) {
|
|
50
57
|
throw new _errors.CommandError(`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.`);
|
|
51
58
|
}
|
|
52
|
-
|
|
53
|
-
return createRequestHandler({
|
|
59
|
+
return (0, _http().createRequestHandler)({
|
|
54
60
|
build: ''
|
|
55
61
|
}, {
|
|
56
62
|
async getRoutesManifest () {
|
|
@@ -104,8 +110,7 @@ function createRouteHandlerMiddleware(projectRoot, options) {
|
|
|
104
110
|
}
|
|
105
111
|
},
|
|
106
112
|
async handleRouteError (error) {
|
|
107
|
-
// NOTE(@kitten):
|
|
108
|
-
// we rename `@expo/server` if we ever hot-swap the implementation
|
|
113
|
+
// NOTE(@kitten): ExpoError is currently not exposed by expo-server just yet
|
|
109
114
|
if (error && typeof error === 'object' && error.name === 'ExpoError') {
|
|
110
115
|
// TODO(@krystofwoldrich): Can we show code snippet of the handler?
|
|
111
116
|
// NOTE(@krystofwoldrich): Removing stack since to avoid confusion. The error is not in the server code.
|
|
@@ -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 resolve from 'resolve';\nimport resolveFrom from 'resolve-from';\nimport { promisify } from 'util';\n\nimport { fetchManifest, type ExpoRouterServerManifestV1Route } 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\nconst resolveAsync = promisify(resolve) as any as (\n id: string,\n opts: resolve.AsyncOpts\n) => Promise<string | null>;\n\nexport function createRouteHandlerMiddleware(\n projectRoot: string,\n options: {\n appDir: string;\n routerRoot: string;\n getStaticPageAsync: (\n pathname: string,\n route: ExpoRouterServerManifestV1Route<RegExp>\n ) => Promise<{ content: string }>;\n bundleApiRoute: (\n functionFilePath: string\n ) => Promise<null | Record<string, Function> | Response>;\n config: ProjectConfig;\n } & import('expo-router/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 const { createRequestHandler } =\n require('@expo/server/adapter/http') as typeof import('@expo/server/adapter/http');\n\n return createRequestHandler(\n { build: '' },\n {\n async getRoutesManifest() {\n const manifest = await fetchManifest<RegExp>(projectRoot, options);\n debug('manifest', manifest);\n // NOTE: no app dir if null\n // TODO: Redirect to 404 page\n return (\n manifest ?? {\n // Support the onboarding screen if there's no manifest\n htmlRoutes: [\n {\n file: 'index.js',\n page: '/index',\n routeKeys: {},\n namedRegex: /^\\/(?:index)?\\/?$/i,\n },\n ],\n apiRoutes: [],\n notFoundRoutes: [],\n 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): temporarily vendored check instead of `ExpoError.isExpoError` to avoid API incompatibility for when\n // we rename `@expo/server` if we ever hot-swap the implementation\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 const resolvedFunctionPath = await resolveAsync(route.file, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n })!;\n\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 const resolvedFunctionPath = await resolveAsync(route.file, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n })!;\n\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","resolveAsync","promisify","resolve","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","extensions","basedir","appDir","bundleApiRoute","getMiddleware","unstable_useServerMiddleware","default","warnInvalidMiddlewareOutput","console","warn","middlewareModule","unstable_settings","matcher","warnInvalidMiddlewareMatcherSettings"],"mappings":"AAAA;;;;;CAKC;;;;+BAwBeA;;;eAAAA;;;;gEApBI;;;;;;;gEACI;;;;;;;yBACE;;;;;;qCAE0C;qCAC3B;wBAKlC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AM,IAAI9C,oBAAY,CACpB;oBAEJ;gBACF;YACF;YAEA,IAAIkC,EAAAA,WAAAA,IAAIE,GAAG,qBAAPF,SAASG,MAAM,MAAK,UAAU;gBAChCU,IAAAA,mCAA2B;gBAC3B,OAAO;oBACLD,SAAS;wBACPE,QAAQC,IAAI,CACV;oBAEJ;gBACF;YACF;YAEA,MAAMV,uBAAuB,MAAM9C,aAAawB,MAAMV,IAAI,EAAE;gBAC1DiC,YAAY;oBAAC;oBAAO;oBAAQ;oBAAO;iBAAO;gBAC1CC,SAAS5C,QAAQ6C,MAAM;YACzB;YAEA,IAAI;oBAIGQ;gBAHL3D,MAAM,CAAC,wBAAwB,EAAEgD,sBAAsB;gBACvD,MAAMW,mBAAoB,MAAMrD,QAAQ8C,cAAc,CAACJ;gBAEvD,KAAKW,sCAAAA,iBAAiBC,iBAAiB,qBAAnC,AAACD,oCAA2DE,OAAO,EAAE;wBAClCF;oBAArCG,IAAAA,4CAAoC,GAACH,uCAAAA,iBAAiBC,iBAAiB,qBAAlCD,qCAAoCE,OAAO;gBAClF;gBAEA,OAAOF;YACT,EAAE,OAAO7B,OAAY;gBACnB,OAAO,IAAIC,SACT,gCAAgCiB,uBAAuB,SAASlB,MAAMO,OAAO,EAC7E;oBACEH,QAAQ;oBACRC,SAAS;wBACP,gBAAgB;oBAClB;gBACF;YAEJ;QACF;IACF;AAEJ"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/createServerRouteMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport type { ProjectConfig } from '@expo/config';\nimport type { MiddlewareSettings } from 'expo-server';\nimport { createRequestHandler } from 'expo-server/adapter/http';\nimport resolve from 'resolve';\nimport resolveFrom from 'resolve-from';\nimport { promisify } from 'util';\n\nimport { fetchManifest, type ExpoRouterServerManifestV1Route } 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\nconst resolveAsync = promisify(resolve) as any as (\n id: string,\n opts: resolve.AsyncOpts\n) => Promise<string | null>;\n\nexport function createRouteHandlerMiddleware(\n projectRoot: string,\n options: {\n appDir: string;\n routerRoot: string;\n getStaticPageAsync: (\n pathname: string,\n route: ExpoRouterServerManifestV1Route<RegExp>\n ) => Promise<{ content: string }>;\n bundleApiRoute: (\n functionFilePath: string\n ) => Promise<null | Record<string, Function> | Response>;\n config: ProjectConfig;\n } & import('expo-router/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 const resolvedFunctionPath = await resolveAsync(route.file, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n })!;\n\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 const resolvedFunctionPath = await resolveAsync(route.file, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n })!;\n\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","resolveAsync","promisify","resolve","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","extensions","basedir","appDir","bundleApiRoute","getMiddleware","unstable_useServerMiddleware","default","warnInvalidMiddlewareOutput","console","warn","middlewareModule","unstable_settings","matcher","warnInvalidMiddlewareMatcherSettings"],"mappings":"AAAA;;;;;CAKC;;;;+BAyBeA;;;eAAAA;;;;yBArBqB;;;;;;;gEACjB;;;;;;;gEACI;;;;;;;yBACE;;;;;;qCAE0C;qCAC3B;wBAKlC;wBACsB;;;;;;AAE7B,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MAAMC,eAAeC,IAAAA,iBAAS,EAACC,kBAAO;AAK/B,SAASL,6BACdM,WAAmB,EACnBC,OAWuD;IAEvD,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,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Q;gBAHL3D,MAAM,CAAC,wBAAwB,EAAEgD,sBAAsB;gBACvD,MAAMW,mBAAoB,MAAMrD,QAAQ8C,cAAc,CAACJ;gBAEvD,KAAKW,sCAAAA,iBAAiBC,iBAAiB,qBAAnC,AAACD,oCAA2DE,OAAO,EAAE;wBAClCF;oBAArCG,IAAAA,4CAAoC,GAACH,uCAAAA,iBAAiBC,iBAAiB,qBAAlCD,qCAAoCE,OAAO;gBAClF;gBAEA,OAAOF;YACT,EAAE,OAAO7B,OAAY;gBACnB,OAAO,IAAIC,SACT,gCAAgCiB,uBAAuB,SAASlB,MAAMO,OAAO,EAC7E;oBACEH,QAAQ;oBACRC,SAAS;wBACP,gBAAgB;oBAClB;gBACF;YAEJ;QACF;IACF;AAEJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/router.ts"],"sourcesContent":["import { ExpoConfig } from '@expo/config';\nimport type { MiddlewareMatcher } from '@expo/server';\nimport chalk from 'chalk';\nimport { sync as globSync } from 'glob';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { directoryExistsSync } from '../../../utils/dir';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { learnMore } from '../../../utils/link';\n\nconst debug = require('debug')('expo:start:server:metro:router') as typeof console.log;\n\n/**\n * Get the relative path for requiring the `/app` folder relative to the `expo-router/entry` file.\n * This mechanism does require the server to restart after the `expo-router` package is installed.\n */\nexport function getAppRouterRelativeEntryPath(\n projectRoot: string,\n routerDirectory: string = getRouterDirectory(projectRoot)\n): string | undefined {\n // Auto pick App entry\n const routerEntry =\n resolveFrom.silent(projectRoot, 'expo-router/entry') ?? getFallbackEntryRoot(projectRoot);\n if (!routerEntry) {\n return undefined;\n }\n // It doesn't matter if the app folder exists.\n const appFolder = path.join(projectRoot, routerDirectory);\n const appRoot = path.relative(path.dirname(routerEntry), appFolder);\n debug('expo-router entry', routerEntry, appFolder, appRoot);\n return appRoot;\n}\n\n/** If the `expo-router` package is not installed, then use the `expo` package to determine where the node modules are relative to the project. */\nfunction getFallbackEntryRoot(projectRoot: string): string {\n const expoRoot = resolveFrom.silent(projectRoot, 'expo/package.json');\n if (expoRoot) {\n return path.join(path.dirname(path.dirname(expoRoot)), 'expo-router/entry');\n }\n return path.join(projectRoot, 'node_modules/expo-router/entry');\n}\n\nexport function getRouterDirectoryModuleIdWithManifest(\n projectRoot: string,\n exp: ExpoConfig\n): string {\n return toPosixPath(exp.extra?.router?.root ?? getRouterDirectory(projectRoot));\n}\n\nlet hasWarnedAboutSrcDir = false;\nconst logSrcDir = () => {\n if (hasWarnedAboutSrcDir) return;\n hasWarnedAboutSrcDir = true;\n Log.log(chalk.gray('Using src/app as the root directory for Expo Router.'));\n};\n\nexport function getRouterDirectory(projectRoot: string): string {\n // more specific directories first\n if (directoryExistsSync(path.join(projectRoot, 'src', 'app'))) {\n logSrcDir();\n return path.join('src', 'app');\n }\n\n debug('Using app as the root directory for Expo Router.');\n return 'app';\n}\n\nexport function isApiRouteConvention(name: string): boolean {\n return /\\+api\\.[tj]sx?$/.test(name);\n}\n\nexport function getApiRoutesForDirectory(cwd: string) {\n return globSync('**/*+api.@(ts|tsx|js|jsx)', {\n cwd,\n absolute: true,\n dot: true,\n });\n}\n\n/**\n * Gets the +middleware file for a given directory. In\n * @param cwd\n */\nexport function getMiddlewareForDirectory(cwd: string): string | null {\n const files = globSync('+middleware.@(ts|tsx|js|jsx)', {\n cwd,\n absolute: true,\n dot: true,\n });\n\n if (files.length === 0) return null;\n\n if (files.length > 1) {\n // In development, throw an error if there are multiple root-level middleware files\n if (process.env.NODE_ENV !== 'production') {\n const relativePaths = files.map((f) => './' + path.relative(cwd, f)).sort();\n throw new Error(\n `Only one middleware file is allowed. Keep one of the conflicting files: ${relativePaths.map((p) => `\"${p}\"`).join(' or ')}`\n );\n }\n }\n\n return files[0];\n}\n\n// Used to emulate a context module, but way faster. TODO: May need to adjust the extensions to stay in sync with Metro.\nexport function getRoutePaths(cwd: string) {\n return globSync('**/*.@(ts|tsx|js|jsx)', {\n cwd,\n dot: true,\n }).map((p) => './' + normalizePaths(p));\n}\n\nfunction normalizePaths(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nlet hasWarnedAboutApiRouteOutput = false;\nlet hasWarnedAboutMiddlewareOutput = false;\n\nexport function hasWarnedAboutApiRoutes() {\n return hasWarnedAboutApiRouteOutput;\n}\n\nexport function hasWarnedAboutMiddleware() {\n return hasWarnedAboutMiddlewareOutput;\n}\n\nexport function warnInvalidWebOutput() {\n if (!hasWarnedAboutApiRouteOutput) {\n Log.warn(\n chalk.yellow`Using API routes requires the {bold web.output} to be set to {bold \"server\"} in the project {bold app.json}. ${learnMore(\n 'https://docs.expo.dev/router/reference/api-routes/'\n )}`\n );\n }\n\n hasWarnedAboutApiRouteOutput = true;\n}\n\nexport function warnInvalidMiddlewareOutput() {\n if (!hasWarnedAboutMiddlewareOutput) {\n Log.warn(\n chalk.yellow`Using middleware requires the {bold web.output} to be set to {bold \"server\"} in the project {bold app.json}. ${learnMore(\n 'https://docs.expo.dev/router/reference/api-routes/'\n )}`\n );\n }\n\n hasWarnedAboutMiddlewareOutput = true;\n}\n\nexport function warnInvalidMiddlewareMatcherSettings(matcher: MiddlewareMatcher) {\n const validMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'];\n\n // Ensure methods are valid HTTP methods\n if (matcher.methods) {\n if (!Array.isArray(matcher.methods)) {\n Log.error(\n chalk.red`Middleware matcher methods must be an array of valid HTTP methods. Supported methods are: ${validMethods.join(', ')}`\n );\n } else {\n for (const method of matcher.methods) {\n if (!validMethods.includes(method)) {\n Log.error(\n chalk.red`Invalid middleware HTTP method: ${method}. Supported methods are: ${validMethods.join(', ')}`\n );\n }\n }\n }\n }\n\n // Ensure patterns are either a string or RegExp\n if (matcher.patterns) {\n const patterns = Array.isArray(matcher.patterns) ? matcher.patterns : [matcher.patterns];\n for (const pattern of patterns) {\n if (typeof pattern !== 'string' && !(pattern instanceof RegExp)) {\n Log.error(\n chalk.red`Middleware matcher patterns must be strings or regular expressions. Received: ${String(\n pattern\n )}`\n );\n }\n\n if (typeof pattern === 'string' && !pattern.startsWith('/')) {\n Log.error(\n chalk.red`String patterns in middleware matcher must start with '/'. Received: ${pattern}`\n );\n }\n }\n }\n}\n"],"names":["getApiRoutesForDirectory","getAppRouterRelativeEntryPath","getMiddlewareForDirectory","getRoutePaths","getRouterDirectory","getRouterDirectoryModuleIdWithManifest","hasWarnedAboutApiRoutes","hasWarnedAboutMiddleware","isApiRouteConvention","warnInvalidMiddlewareMatcherSettings","warnInvalidMiddlewareOutput","warnInvalidWebOutput","debug","require","projectRoot","routerDirectory","routerEntry","resolveFrom","silent","getFallbackEntryRoot","undefined","appFolder","path","join","appRoot","relative","dirname","expoRoot","exp","toPosixPath","extra","router","root","hasWarnedAboutSrcDir","logSrcDir","Log","log","chalk","gray","directoryExistsSync","name","test","cwd","globSync","absolute","dot","files","length","process","env","NODE_ENV","relativePaths","map","f","sort","Error","p","normalizePaths","replace","hasWarnedAboutApiRouteOutput","hasWarnedAboutMiddlewareOutput","warn","yellow","learnMore","matcher","validMethods","methods","Array","isArray","error","red","method","includes","patterns","pattern","RegExp","String","startsWith"],"mappings":";;;;;;;;;;;IAyEgBA,wBAAwB;eAAxBA;;IAvDAC,6BAA6B;eAA7BA;;IAmEAC,yBAAyB;eAAzBA;;IAuBAC,aAAa;eAAbA;;IAlDAC,kBAAkB;eAAlBA;;IAdAC,sCAAsC;eAAtCA;;IA8EAC,uBAAuB;eAAvBA;;IAIAC,wBAAwB;eAAxBA;;IAzDAC,oBAAoB;eAApBA;;IAqFAC,oCAAoC;eAApCA;;IAZAC,2BAA2B;eAA3BA;;IAZAC,oBAAoB;eAApBA;;;;gEAhIE;;;;;;;yBACe;;;;;;;gEAChB;;;;;;;gEACO;;;;;;qBAEJ;qBACgB;0BACR;sBACF;;;;;;AAE1B,MAAMC,QAA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AAK,CAACiC,GAAG,CAAC,qEAAqE,EAAEI,QAAQ,CAAC;YAE9F;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/router.ts"],"sourcesContent":["import { ExpoConfig } from '@expo/config';\nimport chalk from 'chalk';\nimport type { MiddlewareMatcher } from 'expo-server';\nimport { sync as globSync } from 'glob';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { directoryExistsSync } from '../../../utils/dir';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { learnMore } from '../../../utils/link';\n\nconst debug = require('debug')('expo:start:server:metro:router') as typeof console.log;\n\n/**\n * Get the relative path for requiring the `/app` folder relative to the `expo-router/entry` file.\n * This mechanism does require the server to restart after the `expo-router` package is installed.\n */\nexport function getAppRouterRelativeEntryPath(\n projectRoot: string,\n routerDirectory: string = getRouterDirectory(projectRoot)\n): string | undefined {\n // Auto pick App entry\n const routerEntry =\n resolveFrom.silent(projectRoot, 'expo-router/entry') ?? getFallbackEntryRoot(projectRoot);\n if (!routerEntry) {\n return undefined;\n }\n // It doesn't matter if the app folder exists.\n const appFolder = path.join(projectRoot, routerDirectory);\n const appRoot = path.relative(path.dirname(routerEntry), appFolder);\n debug('expo-router entry', routerEntry, appFolder, appRoot);\n return appRoot;\n}\n\n/** If the `expo-router` package is not installed, then use the `expo` package to determine where the node modules are relative to the project. */\nfunction getFallbackEntryRoot(projectRoot: string): string {\n const expoRoot = resolveFrom.silent(projectRoot, 'expo/package.json');\n if (expoRoot) {\n return path.join(path.dirname(path.dirname(expoRoot)), 'expo-router/entry');\n }\n return path.join(projectRoot, 'node_modules/expo-router/entry');\n}\n\nexport function getRouterDirectoryModuleIdWithManifest(\n projectRoot: string,\n exp: ExpoConfig\n): string {\n return toPosixPath(exp.extra?.router?.root ?? getRouterDirectory(projectRoot));\n}\n\nlet hasWarnedAboutSrcDir = false;\nconst logSrcDir = () => {\n if (hasWarnedAboutSrcDir) return;\n hasWarnedAboutSrcDir = true;\n Log.log(chalk.gray('Using src/app as the root directory for Expo Router.'));\n};\n\nexport function getRouterDirectory(projectRoot: string): string {\n // more specific directories first\n if (directoryExistsSync(path.join(projectRoot, 'src', 'app'))) {\n logSrcDir();\n return path.join('src', 'app');\n }\n\n debug('Using app as the root directory for Expo Router.');\n return 'app';\n}\n\nexport function isApiRouteConvention(name: string): boolean {\n return /\\+api\\.[tj]sx?$/.test(name);\n}\n\nexport function getApiRoutesForDirectory(cwd: string) {\n return globSync('**/*+api.@(ts|tsx|js|jsx)', {\n cwd,\n absolute: true,\n dot: true,\n });\n}\n\n/**\n * Gets the +middleware file for a given directory. In\n * @param cwd\n */\nexport function getMiddlewareForDirectory(cwd: string): string | null {\n const files = globSync('+middleware.@(ts|tsx|js|jsx)', {\n cwd,\n absolute: true,\n dot: true,\n });\n\n if (files.length === 0) return null;\n\n if (files.length > 1) {\n // In development, throw an error if there are multiple root-level middleware files\n if (process.env.NODE_ENV !== 'production') {\n const relativePaths = files.map((f) => './' + path.relative(cwd, f)).sort();\n throw new Error(\n `Only one middleware file is allowed. Keep one of the conflicting files: ${relativePaths.map((p) => `\"${p}\"`).join(' or ')}`\n );\n }\n }\n\n return files[0];\n}\n\n// Used to emulate a context module, but way faster. TODO: May need to adjust the extensions to stay in sync with Metro.\nexport function getRoutePaths(cwd: string) {\n return globSync('**/*.@(ts|tsx|js|jsx)', {\n cwd,\n dot: true,\n }).map((p) => './' + normalizePaths(p));\n}\n\nfunction normalizePaths(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nlet hasWarnedAboutApiRouteOutput = false;\nlet hasWarnedAboutMiddlewareOutput = false;\n\nexport function hasWarnedAboutApiRoutes() {\n return hasWarnedAboutApiRouteOutput;\n}\n\nexport function hasWarnedAboutMiddleware() {\n return hasWarnedAboutMiddlewareOutput;\n}\n\nexport function warnInvalidWebOutput() {\n if (!hasWarnedAboutApiRouteOutput) {\n Log.warn(\n chalk.yellow`Using API routes requires the {bold web.output} to be set to {bold \"server\"} in the project {bold app.json}. ${learnMore(\n 'https://docs.expo.dev/router/reference/api-routes/'\n )}`\n );\n }\n\n hasWarnedAboutApiRouteOutput = true;\n}\n\nexport function warnInvalidMiddlewareOutput() {\n if (!hasWarnedAboutMiddlewareOutput) {\n Log.warn(\n chalk.yellow`Using middleware requires the {bold web.output} to be set to {bold \"server\"} in the project {bold app.json}. ${learnMore(\n 'https://docs.expo.dev/router/reference/api-routes/'\n )}`\n );\n }\n\n hasWarnedAboutMiddlewareOutput = true;\n}\n\nexport function warnInvalidMiddlewareMatcherSettings(matcher: MiddlewareMatcher) {\n const validMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'];\n\n // Ensure methods are valid HTTP methods\n if (matcher.methods) {\n if (!Array.isArray(matcher.methods)) {\n Log.error(\n chalk.red`Middleware matcher methods must be an array of valid HTTP methods. Supported methods are: ${validMethods.join(', ')}`\n );\n } else {\n for (const method of matcher.methods) {\n if (!validMethods.includes(method)) {\n Log.error(\n chalk.red`Invalid middleware HTTP method: ${method}. Supported methods are: ${validMethods.join(', ')}`\n );\n }\n }\n }\n }\n\n // Ensure patterns are either a string or RegExp\n if (matcher.patterns) {\n const patterns = Array.isArray(matcher.patterns) ? matcher.patterns : [matcher.patterns];\n for (const pattern of patterns) {\n if (typeof pattern !== 'string' && !(pattern instanceof RegExp)) {\n Log.error(\n chalk.red`Middleware matcher patterns must be strings or regular expressions. Received: ${String(\n pattern\n )}`\n );\n }\n\n if (typeof pattern === 'string' && !pattern.startsWith('/')) {\n Log.error(\n chalk.red`String patterns in middleware matcher must start with '/'. Received: ${pattern}`\n );\n }\n }\n }\n}\n"],"names":["getApiRoutesForDirectory","getAppRouterRelativeEntryPath","getMiddlewareForDirectory","getRoutePaths","getRouterDirectory","getRouterDirectoryModuleIdWithManifest","hasWarnedAboutApiRoutes","hasWarnedAboutMiddleware","isApiRouteConvention","warnInvalidMiddlewareMatcherSettings","warnInvalidMiddlewareOutput","warnInvalidWebOutput","debug","require","projectRoot","routerDirectory","routerEntry","resolveFrom","silent","getFallbackEntryRoot","undefined","appFolder","path","join","appRoot","relative","dirname","expoRoot","exp","toPosixPath","extra","router","root","hasWarnedAboutSrcDir","logSrcDir","Log","log","chalk","gray","directoryExistsSync","name","test","cwd","globSync","absolute","dot","files","length","process","env","NODE_ENV","relativePaths","map","f","sort","Error","p","normalizePaths","replace","hasWarnedAboutApiRouteOutput","hasWarnedAboutMiddlewareOutput","warn","yellow","learnMore","matcher","validMethods","methods","Array","isArray","error","red","method","includes","patterns","pattern","RegExp","String","startsWith"],"mappings":";;;;;;;;;;;IAyEgBA,wBAAwB;eAAxBA;;IAvDAC,6BAA6B;eAA7BA;;IAmEAC,yBAAyB;eAAzBA;;IAuBAC,aAAa;eAAbA;;IAlDAC,kBAAkB;eAAlBA;;IAdAC,sCAAsC;eAAtCA;;IA8EAC,uBAAuB;eAAvBA;;IAIAC,wBAAwB;eAAxBA;;IAzDAC,oBAAoB;eAApBA;;IAqFAC,oCAAoC;eAApCA;;IAZAC,2BAA2B;eAA3BA;;IAZAC,oBAAoB;eAApBA;;;;gEAjIE;;;;;;;yBAEe;;;;;;;gEAChB;;;;;;;gEACO;;;;;;qBAEJ;qBACgB;0BACR;sBACF;;;;;;AAE1B,MAAMC,QAAQC,QAAQ,SAAS;AAMxB,SAASZ,8BACda,WAAmB,EACnBC,kBAA0BX,mBAAmBU,YAAY;IAEzD,sBAAsB;IACtB,MAAME,cACJC,sBAAW,CAACC,MAAM,CAACJ,aAAa,wBAAwBK,qBAAqBL;IAC/E,IAAI,CAACE,aAAa;QAChB,OAAOI;IACT;IACA,8CAA8C;IAC9C,MAAMC,YAAYC,eAAI,CAACC,IAAI,CAACT,aAAaC;IACzC,MAAMS,UAAUF,eAAI,CAACG,QAAQ,CAACH,eAAI,CAACI,OAAO,CAACV,cAAcK;IACzDT,MAAM,qBAAqBI,aAAaK,WAAWG;IACnD,OAAOA;AACT;AAEA,gJAAgJ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,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,0FAA0F,EAAEL,aAAa1C,IAAI,CAAC,MAAM,CAAC;QAEnI,OAAO;YACL,KAAK,MAAMgD,UAAUP,QAAQE,OAAO,CAAE;gBACpC,IAAI,CAACD,aAAaO,QAAQ,CAACD,SAAS;oBAClCpC,QAAG,CAACkC,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,gCAAgC,EAAEC,OAAO,yBAAyB,EAAEN,aAAa1C,IAAI,CAAC,MAAM,CAAC;gBAE3G;YACF;QACF;IACF;IAEA,gDAAgD;IAChD,IAAIyC,QAAQS,QAAQ,EAAE;QACpB,MAAMA,WAAWN,MAAMC,OAAO,CAACJ,QAAQS,QAAQ,IAAIT,QAAQS,QAAQ,GAAG;YAACT,QAAQS,QAAQ;SAAC;QACxF,KAAK,MAAMC,WAAWD,SAAU;YAC9B,IAAI,OAAOC,YAAY,YAAY,CAAEA,CAAAA,mBAAmBC,MAAK,GAAI;gBAC/DxC,QAAG,CAACkC,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,8EAA8E,EAAEM,OACxFF,SACA,CAAC;YAEP;YAEA,IAAI,OAAOA,YAAY,YAAY,CAACA,QAAQG,UAAU,CAAC,MAAM;gBAC3D1C,QAAG,CAACkC,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,qEAAqE,EAAEI,QAAQ,CAAC;YAE9F;QACF;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/createBuiltinAPIRequestHandler.ts"],"sourcesContent":["import { convertRequest, RequestHandler, respond } from '
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/createBuiltinAPIRequestHandler.ts"],"sourcesContent":["import { convertRequest, RequestHandler, respond } from 'expo-server/adapter/http';\n\nimport type { ServerNext, ServerRequest, ServerResponse } from './server.types';\n\nexport function createBuiltinAPIRequestHandler(\n matchRequest: (request: Request) => boolean,\n handlers: Record<string, (req: Request) => Promise<Response>>\n): RequestHandler {\n return createRequestHandler((req) => {\n if (!matchRequest(req)) {\n winterNext();\n }\n const handler = handlers[req.method];\n if (!handler) {\n notAllowed();\n }\n return handler(req);\n });\n}\n\n/**\n * Returns a request handler for http that serves the response using Remix.\n */\nexport function createRequestHandler(\n handleRequest: (request: Request) => Promise<Response>\n): RequestHandler {\n return async (req: ServerRequest, res: ServerResponse, next: ServerNext) => {\n if (!req?.url || !req.method) {\n return next();\n }\n // These headers (added by other middleware) break the browser preview of RSC.\n res.removeHeader('X-Content-Type-Options');\n res.removeHeader('Cache-Control');\n res.removeHeader('Expires');\n res.removeHeader('Surrogate-Control');\n\n try {\n const request = convertRequest(req, res);\n const response = await handleRequest(request);\n return await respond(res, response);\n } catch (error: unknown) {\n if (error instanceof Error) {\n return await respond(\n res,\n new Response('Internal Server Error: ' + error.message, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n })\n );\n } else if (error instanceof Response) {\n return await respond(res, error);\n }\n // http doesn't support async functions, so we have to pass along the\n // error manually using next().\n // @ts-expect-error\n next(error);\n }\n };\n}\n\nfunction notAllowed(): never {\n throw new Response('Method Not Allowed', {\n status: 405,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n}\n\nexport function winterNext(): never {\n // eslint-disable-next-line no-throw-literal\n throw undefined;\n}\n"],"names":["createBuiltinAPIRequestHandler","createRequestHandler","winterNext","matchRequest","handlers","req","handler","method","notAllowed","handleRequest","res","next","url","removeHeader","request","convertRequest","response","respond","error","Error","Response","message","status","headers","undefined"],"mappings":";;;;;;;;;;;IAIgBA,8BAA8B;eAA9BA;;IAmBAC,oBAAoB;eAApBA;;IAgDAC,UAAU;eAAVA;;;;yBAvEwC;;;;;;AAIjD,SAASF,+BACdG,YAA2C,EAC3CC,QAA6D;IAE7D,OAAOH,qBAAqB,CAACI;QAC3B,IAAI,CAACF,aAAaE,MAAM;YACtBH;QACF;QACA,MAAMI,UAAUF,QAAQ,CAACC,IAAIE,MAAM,CAAC;QACpC,IAAI,CAACD,SAAS;YACZE;QACF;QACA,OAAOF,QAAQD;IACjB;AACF;AAKO,SAASJ,qBACdQ,aAAsD;IAEtD,OAAO,OAAOJ,KAAoBK,KAAqBC;QACrD,IAAI,EAACN,uBAAAA,IAAKO,GAAG,KAAI,CAACP,IAAIE,MAAM,EAAE;YAC5B,OAAOI;QACT;QACA,8EAA8E;QAC9ED,IAAIG,YAAY,CAAC;QACjBH,IAAIG,YAAY,CAAC;QACjBH,IAAIG,YAAY,CAAC;QACjBH,IAAIG,YAAY,CAAC;QAEjB,IAAI;YACF,MAAMC,UAAUC,IAAAA,sBAAc,EAACV,KAAKK;YACpC,MAAMM,WAAW,MAAMP,cAAcK;YACrC,OAAO,MAAMG,IAAAA,eAAO,EAACP,KAAKM;QAC5B,EAAE,OAAOE,OAAgB;YACvB,IAAIA,iBAAiBC,OAAO;gBAC1B,OAAO,MAAMF,IAAAA,eAAO,EAClBP,KACA,IAAIU,SAAS,4BAA4BF,MAAMG,OAAO,EAAE;oBACtDC,QAAQ;oBACRC,SAAS;wBACP,gBAAgB;oBAClB;gBACF;YAEJ,OAAO,IAAIL,iBAAiBE,UAAU;gBACpC,OAAO,MAAMH,IAAAA,eAAO,EAACP,KAAKQ;YAC5B;YACA,qEAAqE;YACrE,+BAA+B;YAC/B,mBAAmB;YACnBP,KAAKO;QACP;IACF;AACF;AAEA,SAASV;IACP,MAAM,IAAIY,SAAS,sBAAsB;QACvCE,QAAQ;QACRC,SAAS;YACP,gBAAgB;QAClB;IACF;AACF;AAEO,SAASrB;IACd,4CAA4C;IAC5C,MAAMsB;AACR"}
|
|
@@ -33,7 +33,7 @@ class FetchClient {
|
|
|
33
33
|
this.headers = {
|
|
34
34
|
accept: 'application/json',
|
|
35
35
|
'content-type': 'application/json',
|
|
36
|
-
'user-agent': `expo-cli/${"54.1.0-canary-
|
|
36
|
+
'user-agent': `expo-cli/${"54.1.0-canary-20251003-7b9d7ff"}`,
|
|
37
37
|
authorization: 'Basic ' + _nodebuffer().Buffer.from(`${target}:`).toString('base64')
|
|
38
38
|
};
|
|
39
39
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@expo/cli",
|
|
3
|
-
"version": "54.1.0-canary-
|
|
3
|
+
"version": "54.1.0-canary-20251003-7b9d7ff",
|
|
4
4
|
"description": "The Expo CLI",
|
|
5
5
|
"main": "build/bin/cli",
|
|
6
6
|
"bin": {
|
|
@@ -43,25 +43,24 @@
|
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@0no-co/graphql.web": "^1.0.8",
|
|
45
45
|
"@expo/code-signing-certificates": "^0.0.5",
|
|
46
|
-
"@expo/config": "12.0.
|
|
47
|
-
"@expo/config-plugins": "54.
|
|
46
|
+
"@expo/config": "12.0.11-canary-20251003-7b9d7ff",
|
|
47
|
+
"@expo/config-plugins": "54.0.3-canary-20251003-7b9d7ff",
|
|
48
48
|
"@expo/devcert": "^1.1.2",
|
|
49
|
-
"@expo/env": "2.0.8-canary-
|
|
50
|
-
"@expo/image-utils": "0.8.8-canary-
|
|
51
|
-
"@expo/json-file": "10.0.8-canary-
|
|
49
|
+
"@expo/env": "2.0.8-canary-20251003-7b9d7ff",
|
|
50
|
+
"@expo/image-utils": "0.8.8-canary-20251003-7b9d7ff",
|
|
51
|
+
"@expo/json-file": "10.0.8-canary-20251003-7b9d7ff",
|
|
52
52
|
"@expo/mcp-tunnel": "~0.0.7",
|
|
53
53
|
"@expo/metro": "~54.0.0",
|
|
54
|
-
"@expo/metro-config": "54.0.
|
|
55
|
-
"@expo/osascript": "2.3.8-canary-
|
|
56
|
-
"@expo/package-manager": "1.9.9-canary-
|
|
57
|
-
"@expo/plist": "0.4.8-canary-
|
|
58
|
-
"@expo/prebuild-config": "54.0.
|
|
59
|
-
"@expo/schema-utils": "0.1.8-canary-
|
|
60
|
-
"@expo/server": "1.0.0-canary-20250930-9dc59d3",
|
|
54
|
+
"@expo/metro-config": "54.0.7-canary-20251003-7b9d7ff",
|
|
55
|
+
"@expo/osascript": "2.3.8-canary-20251003-7b9d7ff",
|
|
56
|
+
"@expo/package-manager": "1.9.9-canary-20251003-7b9d7ff",
|
|
57
|
+
"@expo/plist": "0.4.8-canary-20251003-7b9d7ff",
|
|
58
|
+
"@expo/prebuild-config": "54.0.5-canary-20251003-7b9d7ff",
|
|
59
|
+
"@expo/schema-utils": "0.1.8-canary-20251003-7b9d7ff",
|
|
61
60
|
"@expo/spawn-async": "^1.7.2",
|
|
62
61
|
"@expo/ws-tunnel": "^1.0.1",
|
|
63
62
|
"@expo/xcpretty": "^4.3.0",
|
|
64
|
-
"@react-native/dev-middleware": "0.82.0-rc.
|
|
63
|
+
"@react-native/dev-middleware": "0.82.0-rc.5",
|
|
65
64
|
"@urql/core": "^5.0.6",
|
|
66
65
|
"@urql/exchange-retry": "^1.3.0",
|
|
67
66
|
"accepts": "^1.3.8",
|
|
@@ -75,6 +74,7 @@
|
|
|
75
74
|
"connect": "^3.7.0",
|
|
76
75
|
"debug": "^4.3.4",
|
|
77
76
|
"env-editor": "^0.4.1",
|
|
77
|
+
"expo-server": "1.0.1-canary-20251003-7b9d7ff",
|
|
78
78
|
"freeport-async": "^2.0.0",
|
|
79
79
|
"getenv": "^2.0.0",
|
|
80
80
|
"glob": "^10.4.2",
|
|
@@ -113,8 +113,8 @@
|
|
|
113
113
|
]
|
|
114
114
|
},
|
|
115
115
|
"peerDependencies": {
|
|
116
|
-
"expo": "55.0.0-canary-
|
|
117
|
-
"expo-router": "6.1.0-canary-
|
|
116
|
+
"expo": "55.0.0-canary-20251003-7b9d7ff",
|
|
117
|
+
"expo-router": "6.1.0-canary-20251003-7b9d7ff",
|
|
118
118
|
"react-native": "*"
|
|
119
119
|
},
|
|
120
120
|
"peerDependenciesMeta": {
|
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"@types/ws": "^8.5.4",
|
|
158
158
|
"devtools-protocol": "^0.0.1113120",
|
|
159
159
|
"expo-atlas": "^0.4.1",
|
|
160
|
-
"expo-module-scripts": "5.0.8-canary-
|
|
160
|
+
"expo-module-scripts": "5.0.8-canary-20251003-7b9d7ff",
|
|
161
161
|
"find-process": "^1.4.7",
|
|
162
162
|
"jest-runner-tsd": "^6.0.0",
|
|
163
163
|
"klaw-sync": "^6.0.0",
|