@expo/cli 0.8.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/bin/cli +8 -3
- package/build/bin/cli.map +1 -1
- package/build/src/export/createBundles.js +1 -0
- package/build/src/export/createBundles.js.map +1 -1
- package/build/src/export/embed/exportEmbedAsync.js +1 -2
- package/build/src/export/embed/exportEmbedAsync.js.map +1 -1
- package/build/src/export/embed/resolveOptions.js +3 -3
- package/build/src/export/embed/resolveOptions.js.map +1 -1
- package/build/src/export/exportApp.js +4 -4
- package/build/src/export/exportApp.js.map +1 -1
- package/build/src/export/exportStaticAsync.js +18 -18
- package/build/src/export/exportStaticAsync.js.map +1 -1
- package/build/src/export/fork-bundleAsync.js +0 -1
- package/build/src/export/fork-bundleAsync.js.map +1 -1
- package/build/src/export/index.js +5 -1
- package/build/src/export/index.js.map +1 -1
- package/build/src/export/resolveOptions.js +1 -0
- package/build/src/export/resolveOptions.js.map +1 -1
- package/build/src/install/checkPackages.js +6 -0
- package/build/src/install/checkPackages.js.map +1 -1
- package/build/src/install/installAsync.js +15 -1
- package/build/src/install/installAsync.js.map +1 -1
- package/build/src/prebuild/copyTemplateFiles.js +3 -33
- package/build/src/prebuild/copyTemplateFiles.js.map +1 -1
- package/build/src/prebuild/ensureConfigAsync.js.map +1 -1
- package/build/src/prebuild/prebuildAsync.js +1 -1
- package/build/src/prebuild/prebuildAsync.js.map +1 -1
- package/build/src/prebuild/updateFromTemplate.js +1 -8
- package/build/src/prebuild/updateFromTemplate.js.map +1 -1
- package/build/src/prebuild/updatePackageJson.js +33 -47
- package/build/src/prebuild/updatePackageJson.js.map +1 -1
- package/build/src/start/doctor/dependencies/getVersionedPackages.js +13 -2
- package/build/src/start/doctor/dependencies/getVersionedPackages.js.map +1 -1
- package/build/src/start/doctor/dependencies/validateDependenciesVersions.js +11 -1
- package/build/src/start/doctor/dependencies/validateDependenciesVersions.js.map +1 -1
- package/build/src/start/doctor/ngrok/ExternalModule.js +2 -2
- package/build/src/start/doctor/ngrok/ExternalModule.js.map +1 -1
- package/build/src/start/index.js +3 -1
- package/build/src/start/index.js.map +1 -1
- package/build/src/start/server/getStaticRenderFunctions.js +2 -1
- package/build/src/start/server/getStaticRenderFunctions.js.map +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +16 -33
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/externals.js +7 -30
- package/build/src/start/server/metro/externals.js.map +1 -1
- package/build/src/start/server/metro/getCssModulesFromBundler.js.map +1 -1
- package/build/src/start/server/metro/instantiateMetro.js +7 -4
- package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
- package/build/src/start/server/metro/metroErrorInterface.js +26 -3
- package/build/src/start/server/metro/metroErrorInterface.js.map +1 -1
- package/build/src/start/server/metro/router.js +14 -5
- package/build/src/start/server/metro/router.js.map +1 -1
- package/build/src/start/server/metro/runServer-fork.js +0 -1
- package/build/src/start/server/metro/runServer-fork.js.map +1 -1
- package/build/src/start/server/metro/withMetroMultiPlatform.js +10 -4
- package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
- package/build/src/start/server/middleware/ClassicManifestMiddleware.js +1 -1
- package/build/src/start/server/middleware/CreateFileMiddleware.js +6 -3
- package/build/src/start/server/middleware/CreateFileMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js +75 -15
- package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/ManifestMiddleware.js +8 -3
- package/build/src/start/server/middleware/ManifestMiddleware.js.map +1 -1
- package/build/src/start/server/type-generation/index.js +9 -1
- package/build/src/start/server/type-generation/index.js.map +1 -1
- package/build/src/start/server/type-generation/routes.js +2 -3
- package/build/src/start/server/type-generation/routes.js.map +1 -1
- package/build/src/utils/analytics/rudderstackClient.js +2 -2
- package/build/src/utils/cocoapods.js +1 -1
- package/build/src/utils/cocoapods.js.map +1 -1
- package/build/src/utils/dir.js +16 -6
- package/build/src/utils/dir.js.map +1 -1
- package/build/src/utils/downloadExpoGoAsync.js +2 -1
- package/build/src/utils/downloadExpoGoAsync.js.map +1 -1
- package/build/src/utils/env.js +3 -0
- package/build/src/utils/env.js.map +1 -1
- package/build/src/utils/strings.js +24 -0
- package/build/src/utils/strings.js.map +1 -0
- package/package.json +6 -8
- package/build/src/prebuild/writeMetroConfig.js +0 -89
- package/build/src/prebuild/writeMetroConfig.js.map +0 -1
|
@@ -4,6 +4,8 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
4
4
|
});
|
|
5
5
|
exports.logMetroErrorWithStack = logMetroErrorWithStack;
|
|
6
6
|
exports.logMetroError = logMetroError;
|
|
7
|
+
exports.logFromError = logFromError;
|
|
8
|
+
exports.logMetroErrorAsync = logMetroErrorAsync;
|
|
7
9
|
exports.getErrorOverlayHtmlAsync = getErrorOverlayHtmlAsync;
|
|
8
10
|
var _chalk = _interopRequireDefault(require("chalk"));
|
|
9
11
|
var _resolveFrom = _interopRequireDefault(require("resolve-from"));
|
|
@@ -69,11 +71,10 @@ async function logMetroError(projectRoot, { error }) {
|
|
|
69
71
|
error
|
|
70
72
|
});
|
|
71
73
|
}
|
|
72
|
-
|
|
73
|
-
var ref, ref3;
|
|
74
|
+
function logFromError({ error , projectRoot }) {
|
|
74
75
|
const { LogBoxLog , parseErrorStack } = require((0, _resolveFrom).default(projectRoot, "@expo/metro-runtime/symbolicate"));
|
|
75
76
|
const stack = parseErrorStack(error.stack);
|
|
76
|
-
|
|
77
|
+
return new LogBoxLog({
|
|
77
78
|
level: "static",
|
|
78
79
|
message: {
|
|
79
80
|
content: error.message,
|
|
@@ -84,6 +85,13 @@ async function getErrorOverlayHtmlAsync({ error , projectRoot }) {
|
|
|
84
85
|
category: "static",
|
|
85
86
|
componentStack: []
|
|
86
87
|
});
|
|
88
|
+
}
|
|
89
|
+
async function logMetroErrorAsync({ error , projectRoot }) {
|
|
90
|
+
var ref, ref3;
|
|
91
|
+
const log = logFromError({
|
|
92
|
+
projectRoot,
|
|
93
|
+
error
|
|
94
|
+
});
|
|
87
95
|
await new Promise((res)=>log.symbolicate("stack", res)
|
|
88
96
|
);
|
|
89
97
|
var ref4;
|
|
@@ -92,6 +100,21 @@ async function getErrorOverlayHtmlAsync({ error , projectRoot }) {
|
|
|
92
100
|
codeFrame: log.codeFrame,
|
|
93
101
|
error
|
|
94
102
|
});
|
|
103
|
+
}
|
|
104
|
+
async function getErrorOverlayHtmlAsync({ error , projectRoot }) {
|
|
105
|
+
var ref, ref5;
|
|
106
|
+
const log = logFromError({
|
|
107
|
+
projectRoot,
|
|
108
|
+
error
|
|
109
|
+
});
|
|
110
|
+
await new Promise((res)=>log.symbolicate("stack", res)
|
|
111
|
+
);
|
|
112
|
+
var ref6;
|
|
113
|
+
logMetroErrorWithStack(projectRoot, {
|
|
114
|
+
stack: (ref6 = (ref = log.symbolicated) == null ? void 0 : (ref5 = ref.stack) == null ? void 0 : ref5.stack) != null ? ref6 : [],
|
|
115
|
+
codeFrame: log.codeFrame,
|
|
116
|
+
error
|
|
117
|
+
});
|
|
95
118
|
const logBoxContext = {
|
|
96
119
|
selectedLogIndex: 0,
|
|
97
120
|
isDisabled: false,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/metroErrorInterface.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 chalk from 'chalk';\nimport resolveFrom from 'resolve-from';\nimport { StackFrame } from 'stacktrace-parser';\nimport terminalLink from 'terminal-link';\n\nimport { Log } from '../../../log';\nimport { createMetroEndpointAsync } from '../getStaticRenderFunctions';\n// import type { CodeFrame, MetroStackFrame } from '@expo/metro-runtime/symbolicate';\n\ntype CodeFrame = {\n content: string;\n location?: {\n row: number;\n column: number;\n [key: string]: any;\n };\n fileName: string;\n};\n\ntype MetroStackFrame = StackFrame & { collapse?: boolean };\n\nexport async function logMetroErrorWithStack(\n projectRoot: string,\n {\n stack,\n codeFrame,\n error,\n }: {\n stack: MetroStackFrame[];\n codeFrame: CodeFrame;\n error: Error;\n }\n) {\n const { getStackFormattedLocation } = require(resolveFrom(\n projectRoot,\n '@expo/metro-runtime/symbolicate'\n ));\n\n Log.log();\n Log.log(chalk.red('Metro error: ') + error.message);\n Log.log();\n\n if (codeFrame) {\n Log.log(codeFrame.content);\n }\n\n if (stack?.length) {\n Log.log();\n Log.log(chalk.bold`Call Stack`);\n\n const stackProps = stack.map((frame) => {\n return {\n title: frame.methodName,\n subtitle: getStackFormattedLocation(projectRoot, frame),\n collapse: frame.collapse,\n };\n });\n\n stackProps.forEach((frame) => {\n const position = terminalLink.isSupported\n ? terminalLink(frame.subtitle, frame.subtitle)\n : frame.subtitle;\n let lineItem = chalk.gray(` ${frame.title} (${position})`);\n if (frame.collapse) {\n lineItem = chalk.dim(lineItem);\n }\n Log.log(lineItem);\n });\n } else {\n Log.log(chalk.gray(` ${error.stack}`));\n }\n}\n\nexport async function logMetroError(projectRoot: string, { error }: { error: Error }) {\n const { LogBoxLog, parseErrorStack } = require(resolveFrom(\n projectRoot,\n '@expo/metro-runtime/symbolicate'\n ));\n\n const stack = parseErrorStack(error.stack);\n\n const log = new LogBoxLog({\n level: 'static',\n message: {\n content: error.message,\n substitutions: [],\n },\n isComponentError: false,\n stack,\n category: 'static',\n componentStack: [],\n });\n\n await new Promise((res) => log.symbolicate('stack', res));\n\n logMetroErrorWithStack(projectRoot, {\n stack: log.symbolicated?.stack?.stack ?? [],\n codeFrame: log.codeFrame,\n error,\n });\n}\n\n/** @returns the html required to render the static metro error as an SPA. */\nexport async function getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n}: {\n error: Error;\n projectRoot: string;\n}) {\n const { LogBoxLog, parseErrorStack } = require(resolveFrom(\n projectRoot,\n '@expo/metro-runtime/symbolicate'\n ));\n\n const stack = parseErrorStack(error.stack);\n\n const log = new LogBoxLog({\n level: 'static',\n message: {\n content: error.message,\n substitutions: [],\n },\n isComponentError: false,\n stack,\n category: 'static',\n componentStack: [],\n });\n\n await new Promise((res) => log.symbolicate('stack', res));\n\n logMetroErrorWithStack(projectRoot, {\n stack: log.symbolicated?.stack?.stack ?? [],\n codeFrame: log.codeFrame,\n error,\n });\n\n const logBoxContext = {\n selectedLogIndex: 0,\n isDisabled: false,\n logs: [log],\n };\n const html = `<html><head><style>#root,body,html{height:100%}body{overflow:hidden}#root{display:flex}</style></head><body><div id=\"root\"></div><script id=\"_expo-static-error\" type=\"application/json\">${JSON.stringify(\n logBoxContext\n )}</script></body></html>`;\n\n const errorOverlayEntry = await createMetroEndpointAsync(\n projectRoot,\n // Keep the URL relative\n '',\n resolveFrom(projectRoot, 'expo-router/_error'),\n {\n dev: true,\n platform: 'web',\n minify: false,\n environment: 'node',\n }\n );\n\n const htmlWithJs = html.replace('</body>', `<script src=${errorOverlayEntry}></script></body>`);\n return htmlWithJs;\n}\n"],"names":["logMetroErrorWithStack","logMetroError","getErrorOverlayHtmlAsync","projectRoot","stack","codeFrame","error","getStackFormattedLocation","require","resolveFrom","Log","log","chalk","red","message","content","length","bold","stackProps","map","frame","title","methodName","subtitle","collapse","forEach","position","terminalLink","isSupported","lineItem","gray","dim","LogBoxLog","parseErrorStack","level","substitutions","isComponentError","category","componentStack","Promise","res","symbolicate","symbolicated","logBoxContext","selectedLogIndex","isDisabled","logs","html","JSON","stringify","errorOverlayEntry","createMetroEndpointAsync","dev","platform","minify","environment","htmlWithJs","replace"],"mappings":"AAMA;;;;QAqBsBA,sBAAsB,GAAtBA,sBAAsB;QAoDtBC,aAAa,GAAbA,aAAa;QA8BbC,wBAAwB,GAAxBA,wBAAwB;AAvG5B,IAAA,MAAO,kCAAP,OAAO,EAAA;AACD,IAAA,YAAc,kCAAd,cAAc,EAAA;AAEb,IAAA,aAAe,kCAAf,eAAe,EAAA;AAEpB,IAAA,IAAc,WAAd,cAA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AAK,EAAEO,CAAAA,IAA8B,GAA9BA,CAAAA,GAAgB,GAAhBA,GAAG,CAAC+B,YAAY,SAAO,GAAvB/B,KAAAA,CAAuB,GAAvBA,QAAAA,GAAgB,CAAEP,KAAK,SAAA,GAAvBO,KAAAA,CAAuB,QAAEP,KAAK,AAAP,YAAvBO,IAA8B,GAAI,EAAE;QAC3CN,SAAS,EAAEM,GAAG,CAACN,SAAS;QACxBC,KAAK;KACN,CAAC,CAAC;IAEH,MAAMqC,aAAa,GAAG;QACpBC,gBAAgB,EAAE,CAAC;QACnBC,UAAU,EAAE,KAAK;QACjBC,IAAI,EAAE;YAACnC,GAAG;SAAC;KACZ,AAAC;IACF,MAAMoC,IAAI,GAAG,CAAC,yLAAyL,EAAEC,IAAI,CAACC,SAAS,CACrNN,aAAa,CACd,CAAC,uBAAuB,CAAC,AAAC;IAE3B,MAAMO,iBAAiB,GAAG,MAAMC,CAAAA,GAAAA,yBAAwB,AAWvD,CAAA,yBAXuD,CACtDhD,WAAW,EACX,wBAAwB;IACxB,EAAE,EACFM,CAAAA,GAAAA,YAAW,AAAmC,CAAA,QAAnC,CAACN,WAAW,EAAE,oBAAoB,CAAC,EAC9C;QACEiD,GAAG,EAAE,IAAI;QACTC,QAAQ,EAAE,KAAK;QACfC,MAAM,EAAE,KAAK;QACbC,WAAW,EAAE,MAAM;KACpB,CACF,AAAC;IAEF,MAAMC,UAAU,GAAGT,IAAI,CAACU,OAAO,CAAC,SAAS,EAAE,CAAC,YAAY,EAAEP,iBAAiB,CAAC,iBAAiB,CAAC,CAAC,AAAC;IAChG,OAAOM,UAAU,CAAC;CACnB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/metroErrorInterface.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 chalk from 'chalk';\nimport resolveFrom from 'resolve-from';\nimport { StackFrame } from 'stacktrace-parser';\nimport terminalLink from 'terminal-link';\n\nimport { Log } from '../../../log';\nimport { createMetroEndpointAsync } from '../getStaticRenderFunctions';\n// import type { CodeFrame, MetroStackFrame } from '@expo/metro-runtime/symbolicate';\n\ntype CodeFrame = {\n content: string;\n location?: {\n row: number;\n column: number;\n [key: string]: any;\n };\n fileName: string;\n};\n\ntype MetroStackFrame = StackFrame & { collapse?: boolean };\n\nexport async function logMetroErrorWithStack(\n projectRoot: string,\n {\n stack,\n codeFrame,\n error,\n }: {\n stack: MetroStackFrame[];\n codeFrame: CodeFrame;\n error: Error;\n }\n) {\n const { getStackFormattedLocation } = require(resolveFrom(\n projectRoot,\n '@expo/metro-runtime/symbolicate'\n ));\n\n Log.log();\n Log.log(chalk.red('Metro error: ') + error.message);\n Log.log();\n\n if (codeFrame) {\n Log.log(codeFrame.content);\n }\n\n if (stack?.length) {\n Log.log();\n Log.log(chalk.bold`Call Stack`);\n\n const stackProps = stack.map((frame) => {\n return {\n title: frame.methodName,\n subtitle: getStackFormattedLocation(projectRoot, frame),\n collapse: frame.collapse,\n };\n });\n\n stackProps.forEach((frame) => {\n const position = terminalLink.isSupported\n ? terminalLink(frame.subtitle, frame.subtitle)\n : frame.subtitle;\n let lineItem = chalk.gray(` ${frame.title} (${position})`);\n if (frame.collapse) {\n lineItem = chalk.dim(lineItem);\n }\n Log.log(lineItem);\n });\n } else {\n Log.log(chalk.gray(` ${error.stack}`));\n }\n}\n\nexport async function logMetroError(projectRoot: string, { error }: { error: Error }) {\n const { LogBoxLog, parseErrorStack } = require(resolveFrom(\n projectRoot,\n '@expo/metro-runtime/symbolicate'\n ));\n\n const stack = parseErrorStack(error.stack);\n\n const log = new LogBoxLog({\n level: 'static',\n message: {\n content: error.message,\n substitutions: [],\n },\n isComponentError: false,\n stack,\n category: 'static',\n componentStack: [],\n });\n\n await new Promise((res) => log.symbolicate('stack', res));\n\n logMetroErrorWithStack(projectRoot, {\n stack: log.symbolicated?.stack?.stack ?? [],\n codeFrame: log.codeFrame,\n error,\n });\n}\n\n/** @returns the html required to render the static metro error as an SPA. */\nexport function logFromError({ error, projectRoot }: { error: Error; projectRoot: string }): {\n symbolicated: any;\n symbolicate: (type: string, callback: () => void) => void;\n codeFrame: CodeFrame;\n} {\n const { LogBoxLog, parseErrorStack } = require(resolveFrom(\n projectRoot,\n '@expo/metro-runtime/symbolicate'\n ));\n\n const stack = parseErrorStack(error.stack);\n\n return new LogBoxLog({\n level: 'static',\n message: {\n content: error.message,\n substitutions: [],\n },\n isComponentError: false,\n stack,\n category: 'static',\n componentStack: [],\n });\n}\n\n/** @returns the html required to render the static metro error as an SPA. */\nexport async function logMetroErrorAsync({\n error,\n projectRoot,\n}: {\n error: Error;\n projectRoot: string;\n}) {\n const log = logFromError({ projectRoot, error });\n\n await new Promise<void>((res) => log.symbolicate('stack', res));\n\n logMetroErrorWithStack(projectRoot, {\n stack: log.symbolicated?.stack?.stack ?? [],\n codeFrame: log.codeFrame,\n error,\n });\n}\n\n/** @returns the html required to render the static metro error as an SPA. */\nexport async function getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n}: {\n error: Error;\n projectRoot: string;\n}) {\n const log = logFromError({ projectRoot, error });\n\n await new Promise<void>((res) => log.symbolicate('stack', res));\n\n logMetroErrorWithStack(projectRoot, {\n stack: log.symbolicated?.stack?.stack ?? [],\n codeFrame: log.codeFrame,\n error,\n });\n\n const logBoxContext = {\n selectedLogIndex: 0,\n isDisabled: false,\n logs: [log],\n };\n const html = `<html><head><style>#root,body,html{height:100%}body{overflow:hidden}#root{display:flex}</style></head><body><div id=\"root\"></div><script id=\"_expo-static-error\" type=\"application/json\">${JSON.stringify(\n logBoxContext\n )}</script></body></html>`;\n\n const errorOverlayEntry = await createMetroEndpointAsync(\n projectRoot,\n // Keep the URL relative\n '',\n resolveFrom(projectRoot, 'expo-router/_error'),\n {\n dev: true,\n platform: 'web',\n minify: false,\n environment: 'node',\n }\n );\n\n const htmlWithJs = html.replace('</body>', `<script src=${errorOverlayEntry}></script></body>`);\n return htmlWithJs;\n}\n"],"names":["logMetroErrorWithStack","logMetroError","logFromError","logMetroErrorAsync","getErrorOverlayHtmlAsync","projectRoot","stack","codeFrame","error","getStackFormattedLocation","require","resolveFrom","Log","log","chalk","red","message","content","length","bold","stackProps","map","frame","title","methodName","subtitle","collapse","forEach","position","terminalLink","isSupported","lineItem","gray","dim","LogBoxLog","parseErrorStack","level","substitutions","isComponentError","category","componentStack","Promise","res","symbolicate","symbolicated","logBoxContext","selectedLogIndex","isDisabled","logs","html","JSON","stringify","errorOverlayEntry","createMetroEndpointAsync","dev","platform","minify","environment","htmlWithJs","replace"],"mappings":"AAMA;;;;QAqBsBA,sBAAsB,GAAtBA,sBAAsB;QAoDtBC,aAAa,GAAbA,aAAa;QA8BnBC,YAAY,GAAZA,YAAY;QA0BNC,kBAAkB,GAAlBA,kBAAkB;QAmBlBC,wBAAwB,GAAxBA,wBAAwB;AApJ5B,IAAA,MAAO,kCAAP,OAAO,EAAA;AACD,IAAA,YAAc,kCAAd,cAAc,EAAA;AAEb,IAAA,aAAe,kCAAf,eAAe,EAAA;AAEpB,IAAA,IAAc,WAAd,cAAc,CAAA;AACO,IAAA,yBAA6B,WAA7B,6BAA6B,CAAA;;;;;;AAe/D,eAAeJ,sBAAsB,CAC1CK,WAAmB,EACnB,EACEC,KAAK,CAAA,EACLC,SAAS,CAAA,EACTC,KAAK,CAAA,EAKN,EACD;IACA,MAAM,EAAEC,yBAAyB,CAAA,EAAE,GAAGC,OAAO,CAACC,CAAAA,GAAAA,YAAW,AAGxD,CAAA,QAHwD,CACvDN,WAAW,EACX,iCAAiC,CAClC,CAAC,AAAC;IAEHO,IAAG,IAAA,CAACC,GAAG,EAAE,CAAC;IACVD,IAAG,IAAA,CAACC,GAAG,CAACC,MAAK,QAAA,CAACC,GAAG,CAAC,eAAe,CAAC,GAAGP,KAAK,CAACQ,OAAO,CAAC,CAAC;IACpDJ,IAAG,IAAA,CAACC,GAAG,EAAE,CAAC;IAEV,IAAIN,SAAS,EA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,CAAC,AAAC;IAChG,OAAOM,UAAU,CAAC;CACnB"}
|
|
@@ -3,16 +3,19 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
3
3
|
value: true
|
|
4
4
|
});
|
|
5
5
|
exports.getAppRouterRelativeEntryPath = getAppRouterRelativeEntryPath;
|
|
6
|
-
exports.
|
|
6
|
+
exports.getRouterDirectory = getRouterDirectory;
|
|
7
|
+
var _chalk = _interopRequireDefault(require("chalk"));
|
|
7
8
|
var _path = _interopRequireDefault(require("path"));
|
|
8
9
|
var _resolveFrom = _interopRequireDefault(require("resolve-from"));
|
|
10
|
+
var _log = require("../../../log");
|
|
11
|
+
var _dir = require("../../../utils/dir");
|
|
9
12
|
function _interopRequireDefault(obj) {
|
|
10
13
|
return obj && obj.__esModule ? obj : {
|
|
11
14
|
default: obj
|
|
12
15
|
};
|
|
13
16
|
}
|
|
14
17
|
const debug = require("debug")("expo:start:server:metro:router");
|
|
15
|
-
function getAppRouterRelativeEntryPath(projectRoot) {
|
|
18
|
+
function getAppRouterRelativeEntryPath(projectRoot, routerDirectory = getRouterDirectory(projectRoot)) {
|
|
16
19
|
var ref;
|
|
17
20
|
// Auto pick App entry
|
|
18
21
|
const routerEntry = (ref = _resolveFrom.default.silent(projectRoot, "expo-router/entry")) != null ? ref : getFallbackEntryRoot(projectRoot);
|
|
@@ -20,7 +23,7 @@ function getAppRouterRelativeEntryPath(projectRoot) {
|
|
|
20
23
|
return undefined;
|
|
21
24
|
}
|
|
22
25
|
// It doesn't matter if the app folder exists.
|
|
23
|
-
const appFolder = _path.default.join(projectRoot,
|
|
26
|
+
const appFolder = _path.default.join(projectRoot, routerDirectory);
|
|
24
27
|
const appRoot = _path.default.relative(_path.default.dirname(routerEntry), appFolder);
|
|
25
28
|
debug("routerEntry", routerEntry, appFolder, appRoot);
|
|
26
29
|
return appRoot;
|
|
@@ -32,8 +35,14 @@ function getAppRouterRelativeEntryPath(projectRoot) {
|
|
|
32
35
|
}
|
|
33
36
|
return _path.default.join(projectRoot, "node_modules/expo-router/entry");
|
|
34
37
|
}
|
|
35
|
-
function
|
|
36
|
-
|
|
38
|
+
function getRouterDirectory(projectRoot) {
|
|
39
|
+
// more specific directories first
|
|
40
|
+
if ((0, _dir).directoryExistsSync(_path.default.join(projectRoot, "src/app"))) {
|
|
41
|
+
_log.Log.log(_chalk.default.gray("Using src/app as the root directory for Expo Router."));
|
|
42
|
+
return "src/app";
|
|
43
|
+
}
|
|
44
|
+
_log.Log.debug("Using app as the root directory for Expo Router.");
|
|
45
|
+
return "app";
|
|
37
46
|
}
|
|
38
47
|
|
|
39
48
|
//# sourceMappingURL=router.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/router.ts"],"sourcesContent":["import path from 'path';\nimport resolveFrom from 'resolve-from';\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(projectRoot: string): 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,
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/router.ts"],"sourcesContent":["import chalk from 'chalk';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { directoryExistsSync } from '../../../utils/dir';\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('routerEntry', 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 getRouterDirectory(projectRoot: string): string {\n // more specific directories first\n if (directoryExistsSync(path.join(projectRoot, 'src/app'))) {\n Log.log(chalk.gray('Using src/app as the root directory for Expo Router.'));\n return 'src/app';\n }\n\n Log.debug('Using app as the root directory for Expo Router.');\n return 'app';\n}\n"],"names":["getAppRouterRelativeEntryPath","getRouterDirectory","debug","require","projectRoot","routerDirectory","resolveFrom","routerEntry","silent","getFallbackEntryRoot","undefined","appFolder","path","join","appRoot","relative","dirname","expoRoot","directoryExistsSync","Log","log","chalk","gray"],"mappings":"AAAA;;;;QAagBA,6BAA6B,GAA7BA,6BAA6B;QA0B7BC,kBAAkB,GAAlBA,kBAAkB;AAvChB,IAAA,MAAO,kCAAP,OAAO,EAAA;AACR,IAAA,KAAM,kCAAN,MAAM,EAAA;AACC,IAAA,YAAc,kCAAd,cAAc,EAAA;AAElB,IAAA,IAAc,WAAd,cAAc,CAAA;AACE,IAAA,IAAoB,WAApB,oBAAoB,CAAA;;;;;;AAExD,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,gCAAgC,CAAC,AAAsB,AAAC;AAMhF,SAASH,6BAA6B,CAC3CI,WAAmB,EACnBC,eAAuB,GAAGJ,kBAAkB,CAACG,WAAW,CAAC,EACrC;QAGlBE,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AAI,CAAC,sDAAsD,CAAC,CAAC,CAAC;QAC5E,OAAO,SAAS,CAAC;KAClB;IAEDH,IAAG,IAAA,CAACjB,KAAK,CAAC,kDAAkD,CAAC,CAAC;IAC9D,OAAO,KAAK,CAAC;CACd"}
|
|
@@ -34,7 +34,6 @@ const runServer = async (metroBundler, config, { hasReducedPerformance =false ,
|
|
|
34
34
|
const connect = require("connect");
|
|
35
35
|
const serverApp = connect();
|
|
36
36
|
const { middleware , end , metroServer } = await Metro.createConnectMiddleware(config, {
|
|
37
|
-
// @ts-expect-error
|
|
38
37
|
hasReducedPerformance,
|
|
39
38
|
waitForBundler,
|
|
40
39
|
watch
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/runServer-fork.ts"],"sourcesContent":["// Copyright © 2023 650 Industries.\n// Copyright (c) Meta Platforms, Inc. and affiliates.\n//\n// Forks https://github.com/facebook/metro/blob/b80d9a0f638ee9fb82ff69cd3c8d9f4309ca1da2/packages/metro/src/index.flow.js#L57\n// and adds the ability to access the bundler instance.\nimport http from 'http';\nimport https from 'https';\nimport { RunServerOptions, Server } from 'metro';\nimport { ConfigT } from 'metro-config';\nimport { InspectorProxy } from 'metro-inspector-proxy';\nimport { parse } from 'url';\n\nimport { env } from '../../../utils/env';\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { createInspectorProxy, ExpoInspectorProxy } from './inspector-proxy';\nimport {\n importMetroCreateWebsocketServerFromProject,\n importMetroFromProject,\n importMetroHmrServerFromProject,\n importMetroInspectorProxyFromProject,\n} from './resolveFromProject';\n\nexport const runServer = async (\n metroBundler: MetroBundlerDevServer,\n config: ConfigT,\n {\n hasReducedPerformance = false,\n host,\n onError,\n onReady,\n secureServerOptions,\n waitForBundler = false,\n websocketEndpoints = {},\n watch,\n }: RunServerOptions\n): Promise<{ server: http.Server | https.Server; metro: Server }> => {\n const projectRoot = metroBundler.projectRoot;\n\n const Metro = importMetroFromProject(projectRoot);\n\n const createWebsocketServer = importMetroCreateWebsocketServerFromProject(projectRoot);\n\n const { InspectorProxy } = importMetroInspectorProxyFromProject(projectRoot);\n\n const MetroHmrServer = importMetroHmrServerFromProject(projectRoot);\n\n // await earlyPortCheck(host, config.server.port);\n\n // if (secure != null || secureCert != null || secureKey != null) {\n // // eslint-disable-next-line no-console\n // console.warn(\n // chalk.inverse.yellow.bold(' DEPRECATED '),\n // 'The `secure`, `secureCert`, and `secureKey` options are now deprecated. ' +\n // 'Please use the `secureServerOptions` object instead to pass options to ' +\n // \"Metro's https development server.\",\n // );\n // }\n // Lazy require\n const connect = require('connect');\n\n const serverApp = connect();\n\n const { middleware, end, metroServer } = await Metro.createConnectMiddleware(config, {\n
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/runServer-fork.ts"],"sourcesContent":["// Copyright © 2023 650 Industries.\n// Copyright (c) Meta Platforms, Inc. and affiliates.\n//\n// Forks https://github.com/facebook/metro/blob/b80d9a0f638ee9fb82ff69cd3c8d9f4309ca1da2/packages/metro/src/index.flow.js#L57\n// and adds the ability to access the bundler instance.\nimport http from 'http';\nimport https from 'https';\nimport { RunServerOptions, Server } from 'metro';\nimport { ConfigT } from 'metro-config';\nimport { InspectorProxy } from 'metro-inspector-proxy';\nimport { parse } from 'url';\n\nimport { env } from '../../../utils/env';\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { createInspectorProxy, ExpoInspectorProxy } from './inspector-proxy';\nimport {\n importMetroCreateWebsocketServerFromProject,\n importMetroFromProject,\n importMetroHmrServerFromProject,\n importMetroInspectorProxyFromProject,\n} from './resolveFromProject';\n\nexport const runServer = async (\n metroBundler: MetroBundlerDevServer,\n config: ConfigT,\n {\n hasReducedPerformance = false,\n host,\n onError,\n onReady,\n secureServerOptions,\n waitForBundler = false,\n websocketEndpoints = {},\n watch,\n }: RunServerOptions\n): Promise<{ server: http.Server | https.Server; metro: Server }> => {\n const projectRoot = metroBundler.projectRoot;\n\n const Metro = importMetroFromProject(projectRoot);\n\n const createWebsocketServer = importMetroCreateWebsocketServerFromProject(projectRoot);\n\n const { InspectorProxy } = importMetroInspectorProxyFromProject(projectRoot);\n\n const MetroHmrServer = importMetroHmrServerFromProject(projectRoot);\n\n // await earlyPortCheck(host, config.server.port);\n\n // if (secure != null || secureCert != null || secureKey != null) {\n // // eslint-disable-next-line no-console\n // console.warn(\n // chalk.inverse.yellow.bold(' DEPRECATED '),\n // 'The `secure`, `secureCert`, and `secureKey` options are now deprecated. ' +\n // 'Please use the `secureServerOptions` object instead to pass options to ' +\n // \"Metro's https development server.\",\n // );\n // }\n // Lazy require\n const connect = require('connect');\n\n const serverApp = connect();\n\n const { middleware, end, metroServer } = await Metro.createConnectMiddleware(config, {\n hasReducedPerformance,\n waitForBundler,\n watch,\n });\n\n serverApp.use(middleware);\n\n let inspectorProxy: InspectorProxy | ExpoInspectorProxy | null = null;\n if (config.server.runInspectorProxy && env.EXPO_USE_CUSTOM_INSPECTOR_PROXY) {\n inspectorProxy = createInspectorProxy(metroBundler, config.projectRoot);\n } else if (config.server.runInspectorProxy) {\n inspectorProxy = new InspectorProxy(config.projectRoot);\n }\n\n let httpServer: http.Server | https.Server;\n\n if (secureServerOptions != null) {\n httpServer = https.createServer(secureServerOptions, serverApp);\n } else {\n httpServer = http.createServer(serverApp);\n }\n return new Promise<{ server: http.Server | https.Server; metro: Server }>((resolve, reject) => {\n httpServer.on('error', (error) => {\n if (onError) {\n onError(error);\n }\n reject(error);\n end();\n });\n\n httpServer.listen(config.server.port, host, () => {\n if (onReady) {\n onReady(httpServer);\n }\n\n Object.assign(websocketEndpoints, {\n ...(inspectorProxy ? { ...inspectorProxy.createWebSocketListeners(httpServer) } : {}),\n '/hot': createWebsocketServer({\n websocketServer: new MetroHmrServer(\n metroServer.getBundler(),\n metroServer.getCreateModuleId(),\n config\n ),\n }),\n });\n\n httpServer.on('upgrade', (request, socket, head) => {\n const { pathname } = parse(request.url!);\n if (pathname != null && websocketEndpoints[pathname]) {\n websocketEndpoints[pathname].handleUpgrade(request, socket, head, (ws) => {\n websocketEndpoints[pathname].emit('connection', ws, request);\n });\n } else {\n socket.destroy();\n }\n });\n\n if (inspectorProxy) {\n // TODO(hypuk): Refactor inspectorProxy.processRequest into separate request handlers\n // so that we could provide routes (/json/list and /json/version) here.\n // Currently this causes Metro to give warning about T31407894.\n // $FlowFixMe[method-unbinding] added when improving typing for this parameters\n serverApp.use(inspectorProxy.processRequest.bind(inspectorProxy));\n }\n\n resolve({ server: httpServer, metro: metroServer });\n });\n\n // Disable any kind of automatic timeout behavior for incoming\n // requests in case it takes the packager more than the default\n // timeout of 120 seconds to respond to a request.\n httpServer.timeout = 0;\n\n httpServer.on('close', () => {\n end();\n });\n });\n};\n"],"names":["runServer","metroBundler","config","hasReducedPerformance","host","onError","onReady","secureServerOptions","waitForBundler","websocketEndpoints","watch","projectRoot","Metro","importMetroFromProject","createWebsocketServer","importMetroCreateWebsocketServerFromProject","InspectorProxy","importMetroInspectorProxyFromProject","MetroHmrServer","importMetroHmrServerFromProject","connect","require","serverApp","middleware","end","metroServer","createConnectMiddleware","use","inspectorProxy","server","runInspectorProxy","env","EXPO_USE_CUSTOM_INSPECTOR_PROXY","createInspectorProxy","httpServer","https","createServer","http","Promise","resolve","reject","on","error","listen","port","Object","assign","createWebSocketListeners","websocketServer","getBundler","getCreateModuleId","request","socket","head","pathname","parse","url","handleUpgrade","ws","emit","destroy","processRequest","bind","metro","timeout"],"mappings":"AAKA;;;;;AAAiB,IAAA,KAAM,kCAAN,MAAM,EAAA;AACL,IAAA,MAAO,kCAAP,OAAO,EAAA;AAIH,IAAA,IAAK,WAAL,KAAK,CAAA;AAEP,IAAA,IAAoB,WAApB,oBAAoB,CAAA;AAEiB,IAAA,eAAmB,WAAnB,mBAAmB,CAAA;AAMrE,IAAA,mBAAsB,WAAtB,sBAAsB,CAAA;;;;;;AAEtB,MAAMA,SAAS,GAAG,OACvBC,YAAmC,EACnCC,MAAe,EACf,EACEC,qBAAqB,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
@@ -181,11 +181,11 @@ function withExtendedResolver(config, { projectRoot , tsconfig , platforms , isT
|
|
|
181
181
|
...context,
|
|
182
182
|
preferNativePlatform: platform !== "web",
|
|
183
183
|
resolveRequest: undefined,
|
|
184
|
-
// @ts-expect-error
|
|
185
184
|
mainFields,
|
|
186
185
|
// Passing `mainFields` directly won't be considered (in certain version of Metro)
|
|
187
186
|
// we need to extend the `getPackageMainPath` directly to
|
|
188
187
|
// use platform specific `mainFields`.
|
|
188
|
+
// @ts-ignore
|
|
189
189
|
getPackageMainPath (packageJsonPath) {
|
|
190
190
|
// @ts-expect-error: mainFields is not on type
|
|
191
191
|
const package_ = context.moduleCache.getPackage(packageJsonPath);
|
|
@@ -229,9 +229,9 @@ function withExtendedResolver(config, { projectRoot , tsconfig , platforms , isT
|
|
|
229
229
|
function shouldAliasAssetRegistryForWeb(platform, result) {
|
|
230
230
|
return platform === "web" && (result == null ? void 0 : result.type) === "sourceFile" && typeof (result == null ? void 0 : result.filePath) === "string" && normalizeSlashes(result.filePath).endsWith("react-native-web/dist/modules/AssetRegistry/index.js");
|
|
231
231
|
}
|
|
232
|
-
async function withMetroMultiPlatformAsync(projectRoot, { config , platformBundlers , isTsconfigPathsEnabled , webOutput }) {
|
|
233
|
-
// Auto pick
|
|
234
|
-
process.env.EXPO_ROUTER_APP_ROOT = (0, _router).getAppRouterRelativeEntryPath(projectRoot);
|
|
232
|
+
async function withMetroMultiPlatformAsync(projectRoot, { config , platformBundlers , isTsconfigPathsEnabled , webOutput , routerDirectory }) {
|
|
233
|
+
// Auto pick app entry for router.
|
|
234
|
+
process.env.EXPO_ROUTER_APP_ROOT = (0, _router).getAppRouterRelativeEntryPath(projectRoot, routerDirectory);
|
|
235
235
|
var _EXPO_PUBLIC_PROJECT_ROOT;
|
|
236
236
|
// Required for @expo/metro-runtime to format paths in the web LogBox.
|
|
237
237
|
process.env.EXPO_PUBLIC_PROJECT_ROOT = (_EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT) != null ? _EXPO_PUBLIC_PROJECT_ROOT : projectRoot;
|
|
@@ -239,6 +239,12 @@ async function withMetroMultiPlatformAsync(projectRoot, { config , platformBundl
|
|
|
239
239
|
// Enable static rendering in runtime space.
|
|
240
240
|
process.env.EXPO_PUBLIC_USE_STATIC = "1";
|
|
241
241
|
}
|
|
242
|
+
// Ensure the cache is invalidated if these values change.
|
|
243
|
+
// @ts-expect-error
|
|
244
|
+
config.transformer._expoRouterRootDirectory = process.env.EXPO_ROUTER_APP_ROOT;
|
|
245
|
+
// @ts-expect-error
|
|
246
|
+
config.transformer._expoRouterWebRendering = webOutput;
|
|
247
|
+
// TODO: import mode
|
|
242
248
|
if (platformBundlers.web === "metro") {
|
|
243
249
|
await new _webSupportProjectPrerequisite.WebSupportProjectPrerequisite(projectRoot).assertAsync();
|
|
244
250
|
} else if (!isTsconfigPathsEnabled) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext } from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { installExitHooks } from '../../../utils/exit';\nimport { learnMore } from '../../../utils/link';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { WebSupportProjectPrerequisite } from '../../doctor/web/WebSupportProjectPrerequisite';\nimport { PlatformBundlers } from '../platformBundlers';\nimport {\n EXTERNAL_REQUIRE_NATIVE_POLYFILL,\n EXTERNAL_REQUIRE_POLYFILL,\n getNodeExternalModuleId,\n isNodeExternal,\n setupNodeExternals,\n} from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { importMetroResolverFromProject } from './resolveFromProject';\nimport { getAppRouterRelativeEntryPath } from './router';\nimport { withMetroResolvers } from './withMetroResolvers';\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(config: ConfigT, projectRoot: string): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform: string | null | undefined }): readonly string[] => {\n if (ctx.platform === 'web') {\n return [\n // NOTE: We might need this for all platforms\n path.join(projectRoot, EXTERNAL_REQUIRE_POLYFILL),\n // TODO: runtime polyfills, i.e. Fast Refresh, error overlay, React Dev Tools...\n ];\n }\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n\n return [...polyfills, EXTERNAL_REQUIRE_NATIVE_POLYFILL];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n projectRoot,\n tsconfig,\n platforms,\n isTsconfigPathsEnabled,\n }: {\n projectRoot: string;\n tsconfig: TsConfigPaths | null;\n platforms: string[];\n isTsconfigPathsEnabled?: boolean;\n }\n) {\n // Get the `transformer.assetRegistryPath`\n // this needs to be unified since you can't dynamically\n // swap out the transformer based on platform.\n const assetRegistryPath = fs.realpathSync(\n // This is the native asset registry alias for native.\n path.resolve(resolveFrom(projectRoot, 'react-native/Libraries/Image/AssetRegistry'))\n // NOTE(EvanBacon): This is the newer import but it doesn't work in the expo/expo monorepo.\n // path.resolve(resolveFrom(projectRoot, '@react-native/assets/registry.js'))\n );\n\n const isWebEnabled = platforms.includes('web');\n\n const { resolve } = importMetroResolverFromProject(projectRoot);\n\n const extraNodeModules: { [key: string]: Record<string, string> } = {};\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n },\n };\n\n if (isWebEnabled) {\n // Allow `react-native-web` to be optional when web is not enabled but path aliases is.\n extraNodeModules['web'] = {\n 'react-native': path.resolve(require.resolve('react-native-web/package.json'), '..'),\n };\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve = tsconfig?.paths\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl,\n })\n : null;\n\n if (isTsconfigPathsEnabled && !env.CI) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(projectRoot, ['./tsconfig.json', './jsconfig.json']);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n\n return withMetroResolvers(config, projectRoot, [\n // Add a resolver to alias the web asset resolver.\n (immutableContext: ResolutionContext, moduleName: string, platform: string | null) => {\n let context = {\n ...immutableContext,\n } as ResolutionContext & {\n mainFields: string[];\n customResolverOptions?: Record<string, string>;\n };\n\n const environment = context.customResolverOptions?.environment;\n const isNode = environment === 'node';\n\n // TODO: We need to prevent the require.context from including API routes as these use externals.\n // Should be fine after async routes lands.\n if (isNode) {\n const moduleId = isNodeExternal(moduleName);\n if (moduleId) {\n moduleName = getNodeExternalModuleId(context.originModulePath, moduleId);\n debug(`Redirecting Node.js external \"${moduleId}\" to \"${moduleName}\"`);\n }\n }\n\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n moduleName = aliases[platform][moduleName];\n }\n\n // TODO: We may be able to remove this in the future, it's doing no harm\n // by staying here.\n // Conditionally remap `react-native` to `react-native-web`\n if (platform && platform in extraNodeModules) {\n context.extraNodeModules = {\n ...extraNodeModules[platform],\n ...context.extraNodeModules,\n };\n }\n\n if (tsconfig?.baseUrl && isTsconfigPathsEnabled) {\n context = {\n ...context,\n nodeModulesPaths: [\n ...immutableContext.nodeModulesPaths,\n // add last to ensure node modules are resolved first\n tsconfig.baseUrl,\n ],\n };\n }\n\n let mainFields: string[] = context.mainFields;\n\n if (isNode) {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n mainFields = ['main'];\n } else if (env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE) {\n mainFields = context.mainFields;\n } else if (platform && platform in preferredMainFields) {\n mainFields = preferredMainFields[platform];\n }\n function doResolve(moduleName: string): Resolution | null {\n return resolve(\n {\n ...context,\n preferNativePlatform: platform !== 'web',\n resolveRequest: undefined,\n\n // @ts-expect-error\n mainFields,\n // Passing `mainFields` directly won't be considered (in certain version of Metro)\n // we need to extend the `getPackageMainPath` directly to\n // use platform specific `mainFields`.\n getPackageMainPath(packageJsonPath) {\n // @ts-expect-error: mainFields is not on type\n const package_ = context.moduleCache.getPackage(packageJsonPath);\n return package_.getMain(mainFields);\n },\n },\n moduleName,\n platform\n );\n }\n\n function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n }\n\n let result: Resolution | null = null;\n\n if (tsConfigResolve) {\n result = tsConfigResolve(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n optionalResolve\n );\n }\n\n result ??= doResolve(moduleName);\n\n if (result) {\n // Replace the web resolver with the original one.\n // This is basically an alias for web-only.\n if (shouldAliasAssetRegistryForWeb(platform, result)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = assetRegistryPath;\n }\n }\n return result;\n },\n ]);\n}\n\n/** @returns `true` if the incoming resolution should be swapped on web. */\nexport function shouldAliasAssetRegistryForWeb(\n platform: string | null,\n result: Resolution\n): boolean {\n return (\n platform === 'web' &&\n result?.type === 'sourceFile' &&\n typeof result?.filePath === 'string' &&\n normalizeSlashes(result.filePath).endsWith(\n 'react-native-web/dist/modules/AssetRegistry/index.js'\n )\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n webOutput,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n webOutput?: 'single' | 'static';\n }\n) {\n // Auto pick App entry: this is injected with a custom serializer.\n process.env.EXPO_ROUTER_APP_ROOT = getAppRouterRelativeEntryPath(projectRoot);\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n if (webOutput === 'static') {\n // Enable static rendering in runtime space.\n process.env.EXPO_PUBLIC_USE_STATIC = '1';\n }\n\n if (platformBundlers.web === 'metro') {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n } else if (!isTsconfigPathsEnabled) {\n // Bail out early for performance enhancements if no special features are enabled.\n return config;\n }\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n Log.warn(\n chalk.yellow`Experimental path aliases feature is enabled. ` +\n learnMore('https://docs.expo.dev/guides/typescript/#path-aliases')\n );\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n await setupNodeExternals(projectRoot);\n\n return withMetroMultiPlatform(projectRoot, {\n config,\n platformBundlers,\n tsconfig,\n isTsconfigPathsEnabled,\n });\n}\n\nfunction withMetroMultiPlatform(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n tsconfig,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n tsconfig: TsConfigPaths | null;\n }\n) {\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(([, bundler]) => bundler === 'metro')\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n if (expoConfigPlatforms.includes('web')) {\n config = withWebPolyfills(config, projectRoot);\n }\n\n return withExtendedResolver(config, {\n projectRoot,\n tsconfig,\n isTsconfigPathsEnabled,\n platforms: expoConfigPlatforms,\n });\n}\n"],"names":["withExtendedResolver","shouldAliasAssetRegistryForWeb","withMetroMultiPlatformAsync","debug","require","withWebPolyfills","config","projectRoot","originalGetPolyfills","serializer","getPolyfills","bind","ctx","platform","path","join","EXTERNAL_REQUIRE_POLYFILL","polyfills","EXTERNAL_REQUIRE_NATIVE_POLYFILL","normalizeSlashes","p","replace","tsconfig","platforms","isTsconfigPathsEnabled","assetRegistryPath","fs","realpathSync","resolve","resolveFrom","isWebEnabled","includes","importMetroResolverFromProject","extraNodeModules","aliases","web","preferredMainFields","tsConfigResolve","paths","resolveWithTsConfigPaths","baseUrl","env","CI","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","withMetroResolvers","immutableContext","moduleName","context","environment","customResolverOptions","isNode","moduleId","isNodeExternal","getNodeExternalModuleId","originModulePath","nodeModulesPaths","mainFields","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","doResolve","preferNativePlatform","resolveRequest","undefined","getPackageMainPath","packageJsonPath","package_","moduleCache","getPackage","getMain","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","result","filePath","type","endsWith","platformBundlers","webOutput","process","EXPO_ROUTER_APP_ROOT","getAppRouterRelativeEntryPath","EXPO_PUBLIC_PROJECT_ROOT","EXPO_PUBLIC_USE_STATIC","WebSupportProjectPrerequisite","assertAsync","Log","warn","chalk","yellow","learnMore","setupNodeExternals","withMetroMultiPlatform","expoConfigPlatforms","entries","filter","bundler","map","Array","isArray","resolver","Set","concat"],"mappings":"AAMA;;;;QAqEgBA,oBAAoB,GAApBA,oBAAoB;QAqNpBC,8BAA8B,GAA9BA,8BAA8B;QAexBC,2BAA2B,GAA3BA,2BAA2B;AAzS/B,IAAA,MAAO,kCAAP,OAAO,EAAA;AACV,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAGF,IAAA,KAAM,kCAAN,MAAM,EAAA;AACC,IAAA,YAAc,kCAAd,cAAc,EAAA;AAElB,IAAA,IAAc,WAAd,cAAc,CAAA;AACL,IAAA,aAA6B,WAA7B,6BAA6B,CAAA;AACtC,IAAA,IAAoB,WAApB,oBAAoB,CAAA;AACP,IAAA,KAAqB,WAArB,qBAAqB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AAsB;QACtBD,SAAS,EAAEgF,mBAAmB;KAC/B,CAAC,CAAC;CACJ"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext } from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { installExitHooks } from '../../../utils/exit';\nimport { learnMore } from '../../../utils/link';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { WebSupportProjectPrerequisite } from '../../doctor/web/WebSupportProjectPrerequisite';\nimport { PlatformBundlers } from '../platformBundlers';\nimport {\n EXTERNAL_REQUIRE_NATIVE_POLYFILL,\n EXTERNAL_REQUIRE_POLYFILL,\n getNodeExternalModuleId,\n isNodeExternal,\n setupNodeExternals,\n} from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { importMetroResolverFromProject } from './resolveFromProject';\nimport { getAppRouterRelativeEntryPath } from './router';\nimport { withMetroResolvers } from './withMetroResolvers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(config: ConfigT, projectRoot: string): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform: string | null }): readonly string[] => {\n if (ctx.platform === 'web') {\n return [\n // NOTE: We might need this for all platforms\n path.join(projectRoot, EXTERNAL_REQUIRE_POLYFILL),\n // TODO: runtime polyfills, i.e. Fast Refresh, error overlay, React Dev Tools...\n ];\n }\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n\n return [...polyfills, EXTERNAL_REQUIRE_NATIVE_POLYFILL];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n projectRoot,\n tsconfig,\n platforms,\n isTsconfigPathsEnabled,\n }: {\n projectRoot: string;\n tsconfig: TsConfigPaths | null;\n platforms: string[];\n isTsconfigPathsEnabled?: boolean;\n }\n) {\n // Get the `transformer.assetRegistryPath`\n // this needs to be unified since you can't dynamically\n // swap out the transformer based on platform.\n const assetRegistryPath = fs.realpathSync(\n // This is the native asset registry alias for native.\n path.resolve(resolveFrom(projectRoot, 'react-native/Libraries/Image/AssetRegistry'))\n // NOTE(EvanBacon): This is the newer import but it doesn't work in the expo/expo monorepo.\n // path.resolve(resolveFrom(projectRoot, '@react-native/assets/registry.js'))\n );\n\n const isWebEnabled = platforms.includes('web');\n\n const { resolve } = importMetroResolverFromProject(projectRoot);\n\n const extraNodeModules: { [key: string]: Record<string, string> } = {};\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n },\n };\n\n if (isWebEnabled) {\n // Allow `react-native-web` to be optional when web is not enabled but path aliases is.\n extraNodeModules['web'] = {\n 'react-native': path.resolve(require.resolve('react-native-web/package.json'), '..'),\n };\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve = tsconfig?.paths\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl,\n })\n : null;\n\n if (isTsconfigPathsEnabled && !env.CI) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(projectRoot, ['./tsconfig.json', './jsconfig.json']);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n\n return withMetroResolvers(config, projectRoot, [\n // Add a resolver to alias the web asset resolver.\n (immutableContext: ResolutionContext, moduleName: string, platform: string | null) => {\n let context = {\n ...immutableContext,\n } as Mutable<ResolutionContext> & {\n mainFields: string[];\n customResolverOptions?: Record<string, string>;\n };\n\n const environment = context.customResolverOptions?.environment;\n const isNode = environment === 'node';\n\n // TODO: We need to prevent the require.context from including API routes as these use externals.\n // Should be fine after async routes lands.\n if (isNode) {\n const moduleId = isNodeExternal(moduleName);\n if (moduleId) {\n moduleName = getNodeExternalModuleId(context.originModulePath, moduleId);\n debug(`Redirecting Node.js external \"${moduleId}\" to \"${moduleName}\"`);\n }\n }\n\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n moduleName = aliases[platform][moduleName];\n }\n\n // TODO: We may be able to remove this in the future, it's doing no harm\n // by staying here.\n // Conditionally remap `react-native` to `react-native-web`\n if (platform && platform in extraNodeModules) {\n context.extraNodeModules = {\n ...extraNodeModules[platform],\n ...context.extraNodeModules,\n };\n }\n\n if (tsconfig?.baseUrl && isTsconfigPathsEnabled) {\n context = {\n ...context,\n nodeModulesPaths: [\n ...immutableContext.nodeModulesPaths,\n // add last to ensure node modules are resolved first\n tsconfig.baseUrl,\n ],\n };\n }\n\n let mainFields: string[] = context.mainFields;\n\n if (isNode) {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n mainFields = ['main'];\n } else if (env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE) {\n mainFields = context.mainFields;\n } else if (platform && platform in preferredMainFields) {\n mainFields = preferredMainFields[platform];\n }\n function doResolve(moduleName: string): Resolution | null {\n return resolve(\n {\n ...context,\n preferNativePlatform: platform !== 'web',\n resolveRequest: undefined,\n\n mainFields,\n\n // Passing `mainFields` directly won't be considered (in certain version of Metro)\n // we need to extend the `getPackageMainPath` directly to\n // use platform specific `mainFields`.\n // @ts-ignore\n getPackageMainPath(packageJsonPath) {\n // @ts-expect-error: mainFields is not on type\n const package_ = context.moduleCache.getPackage(packageJsonPath);\n return package_.getMain(mainFields);\n },\n },\n moduleName,\n platform\n );\n }\n\n function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n }\n\n let result: Resolution | null = null;\n\n if (tsConfigResolve) {\n result = tsConfigResolve(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n optionalResolve\n );\n }\n\n result ??= doResolve(moduleName);\n\n if (result) {\n // Replace the web resolver with the original one.\n // This is basically an alias for web-only.\n if (shouldAliasAssetRegistryForWeb(platform, result)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = assetRegistryPath;\n }\n }\n return result;\n },\n ]);\n}\n\n/** @returns `true` if the incoming resolution should be swapped on web. */\nexport function shouldAliasAssetRegistryForWeb(\n platform: string | null,\n result: Resolution\n): boolean {\n return (\n platform === 'web' &&\n result?.type === 'sourceFile' &&\n typeof result?.filePath === 'string' &&\n normalizeSlashes(result.filePath).endsWith(\n 'react-native-web/dist/modules/AssetRegistry/index.js'\n )\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n webOutput,\n routerDirectory,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n webOutput?: 'single' | 'static';\n routerDirectory: string;\n }\n) {\n // Auto pick app entry for router.\n process.env.EXPO_ROUTER_APP_ROOT = getAppRouterRelativeEntryPath(projectRoot, routerDirectory);\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n if (webOutput === 'static') {\n // Enable static rendering in runtime space.\n process.env.EXPO_PUBLIC_USE_STATIC = '1';\n }\n\n // Ensure the cache is invalidated if these values change.\n // @ts-expect-error\n config.transformer._expoRouterRootDirectory = process.env.EXPO_ROUTER_APP_ROOT;\n // @ts-expect-error\n config.transformer._expoRouterWebRendering = webOutput;\n // TODO: import mode\n\n if (platformBundlers.web === 'metro') {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n } else if (!isTsconfigPathsEnabled) {\n // Bail out early for performance enhancements if no special features are enabled.\n return config;\n }\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n Log.warn(\n chalk.yellow`Experimental path aliases feature is enabled. ` +\n learnMore('https://docs.expo.dev/guides/typescript/#path-aliases')\n );\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n await setupNodeExternals(projectRoot);\n\n return withMetroMultiPlatform(projectRoot, {\n config,\n platformBundlers,\n tsconfig,\n isTsconfigPathsEnabled,\n });\n}\n\nfunction withMetroMultiPlatform(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n tsconfig,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n tsconfig: TsConfigPaths | null;\n }\n) {\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(([, bundler]) => bundler === 'metro')\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n if (expoConfigPlatforms.includes('web')) {\n config = withWebPolyfills(config, projectRoot);\n }\n\n return withExtendedResolver(config, {\n projectRoot,\n tsconfig,\n isTsconfigPathsEnabled,\n platforms: expoConfigPlatforms,\n });\n}\n"],"names":["withExtendedResolver","shouldAliasAssetRegistryForWeb","withMetroMultiPlatformAsync","debug","require","withWebPolyfills","config","projectRoot","originalGetPolyfills","serializer","getPolyfills","bind","ctx","platform","path","join","EXTERNAL_REQUIRE_POLYFILL","polyfills","EXTERNAL_REQUIRE_NATIVE_POLYFILL","normalizeSlashes","p","replace","tsconfig","platforms","isTsconfigPathsEnabled","assetRegistryPath","fs","realpathSync","resolve","resolveFrom","isWebEnabled","includes","importMetroResolverFromProject","extraNodeModules","aliases","web","preferredMainFields","tsConfigResolve","paths","resolveWithTsConfigPaths","baseUrl","env","CI","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","withMetroResolvers","immutableContext","moduleName","context","environment","customResolverOptions","isNode","moduleId","isNodeExternal","getNodeExternalModuleId","originModulePath","nodeModulesPaths","mainFields","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","doResolve","preferNativePlatform","resolveRequest","undefined","getPackageMainPath","packageJsonPath","package_","moduleCache","getPackage","getMain","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","result","filePath","type","endsWith","platformBundlers","webOutput","routerDirectory","process","EXPO_ROUTER_APP_ROOT","getAppRouterRelativeEntryPath","EXPO_PUBLIC_PROJECT_ROOT","EXPO_PUBLIC_USE_STATIC","transformer","_expoRouterRootDirectory","_expoRouterWebRendering","WebSupportProjectPrerequisite","assertAsync","Log","warn","chalk","yellow","learnMore","setupNodeExternals","withMetroMultiPlatform","expoConfigPlatforms","entries","filter","bundler","map","Array","isArray","resolver","Set","concat"],"mappings":"AAMA;;;;QAuEgBA,oBAAoB,GAApBA,oBAAoB;QAsNpBC,8BAA8B,GAA9BA,8BAA8B;QAexBC,2BAA2B,GAA3BA,2BAA2B;AA5S/B,IAAA,MAAO,kCAAP,OAAO,EAAA;AACV,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAGF,IAAA,KAAM,kCAAN,MAAM,EAAA;AACC,IAAA,YAAc,kCAAd,cAAc,EAAA;AAElB,IAAA,IAAc,WAAd,cAAc,CAAA;AACL,IAAA,aAA6B,WAA7B,6BAA6B,CAAA;AACtC,IAAA,IAAoB,WAApB,oBAAoB,CAAA;AACP,IAAA,KAAqB,WAArB,qBAAqB,CAAA;AAC5B,IAAA,KAAqB,WAArB,qBAAqB,CAAA;AACO,IAAA,kBAA2C,WAA3C,2CAA2C,CAAA;AACxD,IAAA,yBAAkD,WAAlD,kDAAkD,CAAA;AAC7C,IAAA,8BAAgD,WAAhD,gDAAgD,CAAA;AAQvF,IAAA,UAAa,WAAb,aAAa,CAAA;AACmD,IAAA,YAAe,WAAf,eAAe,CAAA;AACvC,IAAA,mBAAsB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AAS,EAAEoF,mBAAmB;KAC/B,CAAC,CAAC;CACJ"}
|
|
@@ -137,7 +137,7 @@ async function createHostInfoAsync() {
|
|
|
137
137
|
host: await _userSettings.default.getAnonymousIdentifierAsync(),
|
|
138
138
|
server: "expo",
|
|
139
139
|
// Defined in the build step
|
|
140
|
-
serverVersion: "0.
|
|
140
|
+
serverVersion: "0.9.1",
|
|
141
141
|
serverDriver: _manifestMiddleware.DEVELOPER_TOOL,
|
|
142
142
|
serverOS: _os.default.platform(),
|
|
143
143
|
serverOSVersion: _os.default.release()
|
|
@@ -19,8 +19,11 @@ class CreateFileMiddleware extends _expoMiddleware.ExpoMiddleware {
|
|
|
19
19
|
this.projectRoot = projectRoot;
|
|
20
20
|
}
|
|
21
21
|
resolvePath(inputPath) {
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
return this.resolveExtension(_path.default.join(this.projectRoot, inputPath));
|
|
23
|
+
}
|
|
24
|
+
resolveExtension(inputPath) {
|
|
25
|
+
let resolvedPath = inputPath;
|
|
26
|
+
const extension = _path.default.extname(inputPath);
|
|
24
27
|
if (extension === ".js") {
|
|
25
28
|
// Automatically convert JS files to TS files when added to a project
|
|
26
29
|
// with TypeScript.
|
|
@@ -75,7 +78,7 @@ class CreateFileMiddleware extends _expoMiddleware.ExpoMiddleware {
|
|
|
75
78
|
return;
|
|
76
79
|
}
|
|
77
80
|
debug(`Requested: %O`, properties);
|
|
78
|
-
const resolvedPath = this.resolvePath(properties.path);
|
|
81
|
+
const resolvedPath = properties.absolutePath ? this.resolveExtension(_path.default.resolve(properties.absolutePath)) : this.resolvePath(properties.path);
|
|
79
82
|
if (_fs.default.existsSync(resolvedPath)) {
|
|
80
83
|
res.statusCode = 409;
|
|
81
84
|
res.end("File already exists.");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/CreateFileMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport fs from 'fs';\nimport path from 'path';\n\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport { ServerRequest, ServerResponse } from './server.types';\n\nconst debug = require('debug')('expo:start:server:middleware:createFile') as typeof console.log;\n\nexport type TouchFileBody = { path: string
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/CreateFileMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport fs from 'fs';\nimport path from 'path';\n\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport { ServerRequest, ServerResponse } from './server.types';\n\nconst debug = require('debug')('expo:start:server:middleware:createFile') as typeof console.log;\n\nexport type TouchFileBody = {\n /** @deprecated */\n path: string;\n absolutePath?: string;\n contents: string;\n};\n\n/**\n * Middleware for creating a file given a `POST` request with\n * `{ contents: string, path: string }` in the body.\n */\nexport class CreateFileMiddleware extends ExpoMiddleware {\n constructor(protected projectRoot: string) {\n super(projectRoot, ['/_expo/touch']);\n }\n\n protected resolvePath(inputPath: string): string {\n return this.resolveExtension(path.join(this.projectRoot, inputPath));\n }\n\n protected resolveExtension(inputPath: string): string {\n let resolvedPath = inputPath;\n const extension = path.extname(inputPath);\n if (extension === '.js') {\n // Automatically convert JS files to TS files when added to a project\n // with TypeScript.\n const tsconfigPath = path.join(this.projectRoot, 'tsconfig.json');\n if (fs.existsSync(tsconfigPath)) {\n resolvedPath = resolvedPath.replace(/\\.js$/, '.tsx');\n }\n }\n\n return resolvedPath;\n }\n\n protected async parseRawBody(req: ServerRequest): Promise<TouchFileBody> {\n const rawBody = await new Promise<string>((resolve, reject) => {\n let body = '';\n req.on('data', (chunk) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n resolve(body);\n });\n req.on('error', (err) => {\n reject(err);\n });\n });\n\n const properties = JSON.parse(rawBody);\n this.assertTouchFileBody(properties);\n\n return properties;\n }\n\n private assertTouchFileBody(body: any): asserts body is TouchFileBody {\n if (typeof body !== 'object' || body == null) {\n throw new Error('Expected object');\n }\n if (typeof body.path !== 'string') {\n throw new Error('Expected \"path\" in body to be string');\n }\n if (typeof body.contents !== 'string') {\n throw new Error('Expected \"contents\" in body to be string');\n }\n }\n\n async handleRequestAsync(req: ServerRequest, res: ServerResponse): Promise<void> {\n if (req.method !== 'POST') {\n res.statusCode = 405;\n res.end('Method Not Allowed');\n return;\n }\n\n let properties: TouchFileBody;\n\n try {\n properties = await this.parseRawBody(req);\n } catch (e) {\n debug('Error parsing request body', e);\n res.statusCode = 400;\n res.end('Bad Request');\n return;\n }\n\n debug(`Requested: %O`, properties);\n\n const resolvedPath = properties.absolutePath\n ? this.resolveExtension(path.resolve(properties.absolutePath))\n : this.resolvePath(properties.path);\n\n if (fs.existsSync(resolvedPath)) {\n res.statusCode = 409;\n res.end('File already exists.');\n return;\n }\n\n debug(`Resolved path:`, resolvedPath);\n\n try {\n await fs.promises.mkdir(path.dirname(resolvedPath), { recursive: true });\n await fs.promises.writeFile(resolvedPath, properties.contents, 'utf8');\n } catch (e) {\n debug('Error writing file', e);\n res.statusCode = 500;\n res.end('Error writing file.');\n return;\n }\n\n debug(`File created`);\n res.statusCode = 200;\n res.end('OK');\n }\n}\n"],"names":["debug","require","CreateFileMiddleware","ExpoMiddleware","constructor","projectRoot","resolvePath","inputPath","resolveExtension","path","join","resolvedPath","extension","extname","tsconfigPath","fs","existsSync","replace","parseRawBody","req","rawBody","Promise","resolve","reject","body","on","chunk","toString","err","properties","JSON","parse","assertTouchFileBody","Error","contents","handleRequestAsync","res","method","statusCode","end","e","absolutePath","promises","mkdir","dirname","recursive","writeFile"],"mappings":"AAMA;;;;AAAe,IAAA,GAAI,kCAAJ,IAAI,EAAA;AACF,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEQ,IAAA,eAAkB,WAAlB,kBAAkB,CAAA;;;;;;AAGjD,MAAMA,KAAK,GAAGC,OAAO,CAAC,OAAO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object.defineProperty(exports, "__esModule", {
|
|
3
3
|
value: true
|
|
4
4
|
});
|
|
5
|
+
exports.ResponseContentType = void 0;
|
|
5
6
|
var _configPlugins = require("@expo/config-plugins");
|
|
6
7
|
var _accepts = _interopRequireDefault(require("accepts"));
|
|
7
8
|
var _crypto = _interopRequireDefault(require("crypto"));
|
|
@@ -44,6 +45,14 @@ function _interopRequireWildcard(obj) {
|
|
|
44
45
|
}
|
|
45
46
|
}
|
|
46
47
|
const debug = require("debug")("expo:start:server:middleware:ExpoGoManifestHandlerMiddleware");
|
|
48
|
+
var ResponseContentType;
|
|
49
|
+
exports.ResponseContentType = ResponseContentType;
|
|
50
|
+
(function(ResponseContentType) {
|
|
51
|
+
ResponseContentType[ResponseContentType["TEXT_PLAIN"] = 0] = "TEXT_PLAIN";
|
|
52
|
+
ResponseContentType[ResponseContentType["APPLICATION_JSON"] = 1] = "APPLICATION_JSON";
|
|
53
|
+
ResponseContentType[ResponseContentType["APPLICATION_EXPO_JSON"] = 2] = "APPLICATION_EXPO_JSON";
|
|
54
|
+
ResponseContentType[ResponseContentType["MULTIPART_MIXED"] = 3] = "MULTIPART_MIXED";
|
|
55
|
+
})(ResponseContentType || (exports.ResponseContentType = ResponseContentType = {}));
|
|
47
56
|
class ExpoGoManifestHandlerMiddleware extends _manifestMiddleware.ManifestMiddleware {
|
|
48
57
|
getParsedHeaders(req) {
|
|
49
58
|
let platform = (0, _resolvePlatform).parsePlatformHeader(req);
|
|
@@ -57,13 +66,31 @@ class ExpoGoManifestHandlerMiddleware extends _manifestMiddleware.ManifestMiddle
|
|
|
57
66
|
// URLs in a browser, we denote the response as "text/plain" if the user agent appears not to be
|
|
58
67
|
// an Expo Updates client.
|
|
59
68
|
const accept = (0, _accepts).default(req);
|
|
60
|
-
const
|
|
69
|
+
const acceptedType = accept.types([
|
|
61
70
|
"unknown/unknown",
|
|
62
|
-
"multipart/mixed"
|
|
63
|
-
|
|
71
|
+
"multipart/mixed",
|
|
72
|
+
"application/json",
|
|
73
|
+
"application/expo+json",
|
|
74
|
+
"text/plain",
|
|
75
|
+
]);
|
|
76
|
+
let responseContentType;
|
|
77
|
+
switch(acceptedType){
|
|
78
|
+
case "multipart/mixed":
|
|
79
|
+
responseContentType = 3;
|
|
80
|
+
break;
|
|
81
|
+
case "application/json":
|
|
82
|
+
responseContentType = 1;
|
|
83
|
+
break;
|
|
84
|
+
case "application/expo+json":
|
|
85
|
+
responseContentType = 2;
|
|
86
|
+
break;
|
|
87
|
+
default:
|
|
88
|
+
responseContentType = 0;
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
64
91
|
const expectSignature = req.headers["expo-expect-signature"];
|
|
65
92
|
return {
|
|
66
|
-
|
|
93
|
+
responseContentType,
|
|
67
94
|
platform,
|
|
68
95
|
expectSignature: expectSignature ? String(expectSignature) : null,
|
|
69
96
|
hostname: (0, _url).stripPort(req.headers["host"])
|
|
@@ -133,18 +160,51 @@ class ExpoGoManifestHandlerMiddleware extends _manifestMiddleware.ManifestMiddle
|
|
|
133
160
|
};
|
|
134
161
|
certificateChainBody = codeSigningInfo.certificateChainForResponse.join("\n");
|
|
135
162
|
}
|
|
136
|
-
const form = this.getFormData({
|
|
137
|
-
stringifiedManifest,
|
|
138
|
-
manifestPartHeaders,
|
|
139
|
-
certificateChainBody
|
|
140
|
-
});
|
|
141
163
|
const headers = this.getDefaultResponseHeaders();
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
164
|
+
switch(requestOptions.responseContentType){
|
|
165
|
+
case 3:
|
|
166
|
+
{
|
|
167
|
+
const form = this.getFormData({
|
|
168
|
+
stringifiedManifest,
|
|
169
|
+
manifestPartHeaders,
|
|
170
|
+
certificateChainBody
|
|
171
|
+
});
|
|
172
|
+
headers.set("content-type", `multipart/mixed; boundary=${form.getBoundary()}`);
|
|
173
|
+
return {
|
|
174
|
+
body: form.getBuffer().toString(),
|
|
175
|
+
version: runtimeVersion,
|
|
176
|
+
headers
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
case 2:
|
|
180
|
+
case 1:
|
|
181
|
+
case 0:
|
|
182
|
+
{
|
|
183
|
+
headers.set("content-type", ExpoGoManifestHandlerMiddleware.getContentTypeForResponseContentType(requestOptions.responseContentType));
|
|
184
|
+
if (manifestPartHeaders) {
|
|
185
|
+
Object.entries(manifestPartHeaders).forEach(([key, value])=>{
|
|
186
|
+
headers.set(key, value);
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
return {
|
|
190
|
+
body: stringifiedManifest,
|
|
191
|
+
version: runtimeVersion,
|
|
192
|
+
headers
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
static getContentTypeForResponseContentType(responseContentType) {
|
|
198
|
+
switch(responseContentType){
|
|
199
|
+
case 3:
|
|
200
|
+
return "multipart/mixed";
|
|
201
|
+
case 2:
|
|
202
|
+
return "application/expo+json";
|
|
203
|
+
case 1:
|
|
204
|
+
return "application/json";
|
|
205
|
+
case 0:
|
|
206
|
+
return "text/plain";
|
|
207
|
+
}
|
|
148
208
|
}
|
|
149
209
|
getFormData({ stringifiedManifest , manifestPartHeaders , certificateChainBody }) {
|
|
150
210
|
const form = new _formData.default();
|