@expo/cli 0.7.3 → 0.9.0
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/README.md +1 -1
- package/build/bin/cli +17 -3
- package/build/bin/cli.map +1 -1
- package/build/src/api/getExpoGoIntermediateCertificate.js +0 -2
- package/build/src/api/getExpoGoIntermediateCertificate.js.map +1 -1
- package/build/src/api/getProjectDevelopmentCertificate.js +0 -2
- package/build/src/api/getProjectDevelopmentCertificate.js.map +1 -1
- package/build/src/api/graphql/queries/AppQuery.js +39 -0
- package/build/src/api/graphql/queries/AppQuery.js.map +1 -0
- package/build/src/api/graphql/queries/UserQuery.js +10 -3
- package/build/src/api/graphql/queries/UserQuery.js.map +1 -1
- package/build/src/api/graphql/types/App.js +23 -0
- package/build/src/api/graphql/types/App.js.map +1 -0
- package/build/src/api/signManifest.js +0 -12
- package/build/src/api/signManifest.js.map +1 -1
- package/build/src/api/user/UserSettings.js.map +1 -1
- package/build/src/api/user/user.js.map +1 -1
- package/build/src/config/configAsync.js +3 -0
- package/build/src/config/configAsync.js.map +1 -1
- package/build/src/customize/customizeAsync.js +3 -0
- package/build/src/customize/customizeAsync.js.map +1 -1
- package/build/src/export/createBundles.js +8 -3
- package/build/src/export/createBundles.js.map +1 -1
- package/build/src/export/embed/exportEmbedAsync.js +23 -0
- package/build/src/export/embed/exportEmbedAsync.js.map +1 -0
- package/build/src/export/embed/index.js +117 -0
- package/build/src/export/embed/index.js.map +1 -0
- package/build/src/export/embed/resolveOptions.js +63 -0
- package/build/src/export/embed/resolveOptions.js.map +1 -0
- package/build/src/export/exportApp.js +58 -31
- package/build/src/export/exportApp.js.map +1 -1
- package/build/src/export/exportAssets.js +17 -0
- package/build/src/export/exportAssets.js.map +1 -1
- package/build/src/export/exportAsync.js +3 -0
- package/build/src/export/exportAsync.js.map +1 -1
- package/build/src/export/exportStaticAsync.js +179 -0
- package/build/src/export/exportStaticAsync.js.map +1 -0
- package/build/src/export/fork-bundleAsync.js +15 -43
- package/build/src/export/fork-bundleAsync.js.map +1 -1
- package/build/src/export/html.js +21 -0
- package/build/src/export/html.js.map +1 -0
- package/build/src/export/index.js +5 -1
- package/build/src/export/index.js.map +1 -1
- package/build/src/export/printBundleSizes.js +2 -2
- package/build/src/export/printBundleSizes.js.map +1 -1
- package/build/src/export/resolveOptions.js +1 -0
- package/build/src/export/resolveOptions.js.map +1 -1
- package/build/src/export/web/exportWebAsync.js +3 -0
- package/build/src/export/web/exportWebAsync.js.map +1 -1
- package/build/src/export/writeContents.js +5 -2
- package/build/src/export/writeContents.js.map +1 -1
- package/build/src/graphql/generated.js +462 -0
- package/build/src/graphql/generated.js.map +1 -0
- package/build/src/install/checkPackages.js +6 -0
- package/build/src/install/checkPackages.js.map +1 -1
- package/build/src/install/installAsync.js +18 -1
- package/build/src/install/installAsync.js.map +1 -1
- package/build/src/prebuild/clearNativeFolder.js +6 -1
- package/build/src/prebuild/clearNativeFolder.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 +1 -12
- package/build/src/prebuild/ensureConfigAsync.js.map +1 -1
- package/build/src/prebuild/prebuildAsync.js +7 -2
- package/build/src/prebuild/prebuildAsync.js.map +1 -1
- package/build/src/prebuild/resolveOptions.js +7 -8
- package/build/src/prebuild/resolveOptions.js.map +1 -1
- package/build/src/prebuild/resolveTemplate.js +5 -0
- package/build/src/prebuild/resolveTemplate.js.map +1 -1
- package/build/src/prebuild/updateFromTemplate.js +6 -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/prebuild/validateTemplatePlatforms.js +48 -0
- package/build/src/prebuild/validateTemplatePlatforms.js.map +1 -0
- package/build/src/run/android/runAndroidAsync.js +4 -0
- package/build/src/run/android/runAndroidAsync.js.map +1 -1
- package/build/src/run/ios/appleDevice/AppleDevice.js +25 -19
- package/build/src/run/ios/appleDevice/AppleDevice.js.map +1 -1
- package/build/src/run/ios/appleDevice/client/InstallationProxyClient.js.map +1 -1
- package/build/src/run/ios/options/resolveNativeScheme.js +13 -4
- package/build/src/run/ios/options/resolveNativeScheme.js.map +1 -1
- package/build/src/run/ios/runIosAsync.js +3 -0
- package/build/src/run/ios/runIosAsync.js.map +1 -1
- package/build/src/run/startBundler.js +4 -0
- package/build/src/run/startBundler.js.map +1 -1
- package/build/src/start/doctor/Prerequisite.js.map +1 -1
- package/build/src/start/doctor/dependencies/ensureDependenciesAsync.js +12 -6
- package/build/src/start/doctor/dependencies/ensureDependenciesAsync.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 +12 -4
- package/build/src/start/doctor/dependencies/validateDependenciesVersions.js.map +1 -1
- package/build/src/start/doctor/typescript/TypeScriptProjectPrerequisite.js +31 -5
- package/build/src/start/doctor/typescript/TypeScriptProjectPrerequisite.js.map +1 -1
- package/build/src/start/doctor/typescript/updateTSConfig.js +6 -0
- package/build/src/start/doctor/typescript/updateTSConfig.js.map +1 -1
- package/build/src/start/doctor/web/WebSupportProjectPrerequisite.js +1 -0
- package/build/src/start/doctor/web/WebSupportProjectPrerequisite.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/platforms/android/adb.js +1 -1
- package/build/src/start/platforms/android/adb.js.map +1 -1
- package/build/src/start/platforms/ios/AppleDeviceManager.js +1 -1
- package/build/src/start/platforms/ios/AppleDeviceManager.js.map +1 -1
- package/build/src/start/server/BundlerDevServer.js +16 -2
- package/build/src/start/server/BundlerDevServer.js.map +1 -1
- package/build/src/start/server/DevServerManager.js +33 -2
- package/build/src/start/server/DevServerManager.js.map +1 -1
- package/build/src/start/server/getStaticRenderFunctions.js +167 -0
- package/build/src/start/server/getStaticRenderFunctions.js.map +1 -0
- package/build/src/start/server/metro/MetroBundlerDevServer.js +262 -3
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/MetroTerminalReporter.js +2 -34
- package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
- package/build/src/start/server/metro/externals.js +72 -0
- package/build/src/start/server/metro/externals.js.map +1 -0
- package/build/src/start/server/metro/getCssModulesFromBundler.js +77 -0
- package/build/src/start/server/metro/getCssModulesFromBundler.js.map +1 -0
- package/build/src/start/server/metro/inspector-proxy/index.js +2 -2
- package/build/src/start/server/metro/inspector-proxy/index.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/proxy.js +1 -3
- package/build/src/start/server/metro/inspector-proxy/proxy.js.map +1 -1
- package/build/src/start/server/metro/instantiateMetro.js +47 -48
- package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
- package/build/src/start/server/metro/metroErrorInterface.js +137 -0
- package/build/src/start/server/metro/metroErrorInterface.js.map +1 -0
- package/build/src/start/server/metro/metroWatchTypeScriptFiles.js +51 -0
- package/build/src/start/server/metro/metroWatchTypeScriptFiles.js.map +1 -0
- package/build/src/start/server/metro/resolveFromProject.js +26 -3
- package/build/src/start/server/metro/resolveFromProject.js.map +1 -1
- package/build/src/start/server/metro/router.js +15 -2
- package/build/src/start/server/metro/router.js.map +1 -1
- package/build/src/start/server/metro/runServer-fork.js +107 -0
- package/build/src/start/server/metro/runServer-fork.js.map +1 -0
- package/build/src/start/server/metro/symbolicate.js +6 -0
- package/build/src/start/server/metro/symbolicate.js.map +1 -0
- package/build/src/start/server/metro/waitForMetroToObserveTypeScriptFile.js +70 -0
- package/build/src/start/server/metro/waitForMetroToObserveTypeScriptFile.js.map +1 -0
- package/build/src/start/server/metro/withMetroMultiPlatform.js +188 -45
- package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
- package/build/src/start/server/middleware/ClassicManifestMiddleware.js +8 -1
- package/build/src/start/server/middleware/ClassicManifestMiddleware.js.map +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 +113 -47
- package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/ManifestMiddleware.js +59 -20
- package/build/src/start/server/middleware/ManifestMiddleware.js.map +1 -1
- package/build/src/start/server/type-generation/expo-env.js +27 -0
- package/build/src/start/server/type-generation/expo-env.js.map +1 -0
- package/build/src/start/server/type-generation/index.js +57 -0
- package/build/src/start/server/type-generation/index.js.map +1 -0
- package/build/src/start/server/type-generation/routes.js +291 -0
- package/build/src/start/server/type-generation/routes.js.map +1 -0
- package/build/src/start/server/type-generation/tsconfig.js +89 -0
- package/build/src/start/server/type-generation/tsconfig.js.map +1 -0
- package/build/src/start/server/webTemplate.js +20 -4
- package/build/src/start/server/webTemplate.js.map +1 -1
- package/build/src/start/server/webpack/WebpackBundlerDevServer.js +4 -6
- package/build/src/start/server/webpack/WebpackBundlerDevServer.js.map +1 -1
- package/build/src/start/startAsync.js +30 -8
- package/build/src/start/startAsync.js.map +1 -1
- package/build/src/utils/FileNotifier.js +11 -4
- package/build/src/utils/FileNotifier.js.map +1 -1
- package/build/src/utils/analytics/getMetroProperties.js +1 -1
- package/build/src/utils/analytics/getMetroProperties.js.map +1 -1
- package/build/src/utils/analytics/rudderstackClient.js +2 -2
- package/build/src/utils/codesigning.js +31 -7
- package/build/src/utils/codesigning.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/env.js +6 -0
- package/build/src/utils/env.js.map +1 -1
- package/build/src/utils/mergeGitIgnorePaths.js +42 -0
- package/build/src/utils/mergeGitIgnorePaths.js.map +1 -1
- package/build/src/utils/nodeEnv.js +11 -0
- package/build/src/utils/nodeEnv.js.map +1 -0
- package/build/src/utils/resolveArgs.js +43 -0
- package/build/src/utils/resolveArgs.js.map +1 -1
- package/build/src/utils/strings.js +24 -0
- package/build/src/utils/strings.js.map +1 -0
- package/build/src/utils/template.js +21 -0
- package/build/src/utils/template.js.map +1 -0
- package/build/src/utils/tsconfig/evaluateTsConfig.js +61 -0
- package/build/src/utils/tsconfig/evaluateTsConfig.js.map +1 -0
- package/build/src/utils/tsconfig/loadTsConfigPaths.js +69 -0
- package/build/src/utils/tsconfig/loadTsConfigPaths.js.map +1 -0
- package/build/src/utils/tsconfig/matchTsConfigPathAlias.js +88 -0
- package/build/src/utils/tsconfig/matchTsConfigPathAlias.js.map +1 -0
- package/build/src/utils/tsconfig/resolveWithTsConfigPaths.js +41 -0
- package/build/src/utils/tsconfig/resolveWithTsConfigPaths.js.map +1 -0
- package/package.json +16 -10
- package/static/template/metro.config.js +4 -1
- package/build/src/api/getProject.js +0 -19
- package/build/src/api/getProject.js.map +0 -1
- package/build/src/api/graphql/generated.js +0 -113
- package/build/src/api/graphql/generated.js.map +0 -1
- package/build/src/prebuild/writeMetroConfig.js +0 -89
- package/build/src/prebuild/writeMetroConfig.js.map +0 -1
|
@@ -2,14 +2,23 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", {
|
|
3
3
|
value: true
|
|
4
4
|
});
|
|
5
|
-
exports.
|
|
5
|
+
exports.withExtendedResolver = withExtendedResolver;
|
|
6
6
|
exports.shouldAliasAssetRegistryForWeb = shouldAliasAssetRegistryForWeb;
|
|
7
7
|
exports.withMetroMultiPlatformAsync = withMetroMultiPlatformAsync;
|
|
8
|
+
var _chalk = _interopRequireDefault(require("chalk"));
|
|
8
9
|
var _fs = _interopRequireDefault(require("fs"));
|
|
9
10
|
var _path = _interopRequireDefault(require("path"));
|
|
10
11
|
var _resolveFrom = _interopRequireDefault(require("resolve-from"));
|
|
12
|
+
var _log = require("../../../log");
|
|
13
|
+
var _fileNotifier = require("../../../utils/FileNotifier");
|
|
11
14
|
var _env = require("../../../utils/env");
|
|
15
|
+
var _exit = require("../../../utils/exit");
|
|
16
|
+
var _link = require("../../../utils/link");
|
|
17
|
+
var _loadTsConfigPaths = require("../../../utils/tsconfig/loadTsConfigPaths");
|
|
18
|
+
var _resolveWithTsConfigPaths = require("../../../utils/tsconfig/resolveWithTsConfigPaths");
|
|
12
19
|
var _webSupportProjectPrerequisite = require("../../doctor/web/WebSupportProjectPrerequisite");
|
|
20
|
+
var _externals = require("./externals");
|
|
21
|
+
var _metroErrors = require("./metroErrors");
|
|
13
22
|
var _resolveFromProject = require("./resolveFromProject");
|
|
14
23
|
var _router = require("./router");
|
|
15
24
|
var _withMetroResolvers = require("./withMetroResolvers");
|
|
@@ -18,15 +27,23 @@ function _interopRequireDefault(obj) {
|
|
|
18
27
|
default: obj
|
|
19
28
|
};
|
|
20
29
|
}
|
|
21
|
-
|
|
30
|
+
const debug = require("debug")("expo:start:server:metro:multi-platform");
|
|
31
|
+
function withWebPolyfills(config, projectRoot) {
|
|
22
32
|
const originalGetPolyfills = config.serializer.getPolyfills ? config.serializer.getPolyfills.bind(config.serializer) : ()=>[]
|
|
23
33
|
;
|
|
24
34
|
const getPolyfills = (ctx)=>{
|
|
25
35
|
if (ctx.platform === "web") {
|
|
26
|
-
return [
|
|
36
|
+
return [
|
|
37
|
+
// NOTE: We might need this for all platforms
|
|
38
|
+
_path.default.join(projectRoot, _externals.EXTERNAL_REQUIRE_POLYFILL)
|
|
39
|
+
];
|
|
27
40
|
}
|
|
28
41
|
// Generally uses `rn-get-polyfills`
|
|
29
|
-
|
|
42
|
+
const polyfills = originalGetPolyfills(ctx);
|
|
43
|
+
return [
|
|
44
|
+
...polyfills,
|
|
45
|
+
_externals.EXTERNAL_REQUIRE_NATIVE_POLYFILL
|
|
46
|
+
];
|
|
30
47
|
};
|
|
31
48
|
return {
|
|
32
49
|
...config,
|
|
@@ -39,25 +56,26 @@ function withWebPolyfills(config) {
|
|
|
39
56
|
function normalizeSlashes(p) {
|
|
40
57
|
return p.replace(/\\/g, "/");
|
|
41
58
|
}
|
|
42
|
-
function
|
|
59
|
+
function withExtendedResolver(config, { projectRoot , tsconfig , platforms , isTsconfigPathsEnabled }) {
|
|
43
60
|
// Get the `transformer.assetRegistryPath`
|
|
44
61
|
// this needs to be unified since you can't dynamically
|
|
45
62
|
// swap out the transformer based on platform.
|
|
46
63
|
const assetRegistryPath = _fs.default.realpathSync(// This is the native asset registry alias for native.
|
|
47
64
|
_path.default.resolve((0, _resolveFrom).default(projectRoot, "react-native/Libraries/Image/AssetRegistry")));
|
|
48
|
-
|
|
49
|
-
// `*.native.*` extensions on web.
|
|
65
|
+
const isWebEnabled = platforms.includes("web");
|
|
50
66
|
const { resolve } = (0, _resolveFromProject).importMetroResolverFromProject(projectRoot);
|
|
51
|
-
const extraNodeModules = {
|
|
52
|
-
web: {
|
|
53
|
-
"react-native": _path.default.resolve(require.resolve("react-native-web/package.json"), "..")
|
|
54
|
-
}
|
|
55
|
-
};
|
|
67
|
+
const extraNodeModules = {};
|
|
56
68
|
const aliases = {
|
|
57
69
|
web: {
|
|
58
70
|
"react-native": "react-native-web"
|
|
59
71
|
}
|
|
60
72
|
};
|
|
73
|
+
if (isWebEnabled) {
|
|
74
|
+
// Allow `react-native-web` to be optional when web is not enabled but path aliases is.
|
|
75
|
+
extraNodeModules["web"] = {
|
|
76
|
+
"react-native": _path.default.resolve(require.resolve("react-native-web/package.json"), "..")
|
|
77
|
+
};
|
|
78
|
+
}
|
|
61
79
|
const preferredMainFields = {
|
|
62
80
|
// Defaults from Expo Webpack. Most packages using `react-native` don't support web
|
|
63
81
|
// in the `react-native` field, so we should prefer the `browser` field.
|
|
@@ -68,16 +86,64 @@ function withWebResolvers(config, projectRoot) {
|
|
|
68
86
|
"main"
|
|
69
87
|
]
|
|
70
88
|
};
|
|
89
|
+
var _paths1;
|
|
90
|
+
let tsConfigResolve = (tsconfig == null ? void 0 : tsconfig.paths) ? _resolveWithTsConfigPaths.resolveWithTsConfigPaths.bind(_resolveWithTsConfigPaths.resolveWithTsConfigPaths, {
|
|
91
|
+
paths: (_paths1 = tsconfig.paths) != null ? _paths1 : {},
|
|
92
|
+
baseUrl: tsconfig.baseUrl
|
|
93
|
+
}) : null;
|
|
94
|
+
if (isTsconfigPathsEnabled && !_env.env.CI) {
|
|
95
|
+
// TODO: We should track all the files that used imports and invalidate them
|
|
96
|
+
// currently the user will need to save all the files that use imports to
|
|
97
|
+
// use the new aliases.
|
|
98
|
+
const configWatcher = new _fileNotifier.FileNotifier(projectRoot, [
|
|
99
|
+
"./tsconfig.json",
|
|
100
|
+
"./jsconfig.json"
|
|
101
|
+
]);
|
|
102
|
+
configWatcher.startObserving(()=>{
|
|
103
|
+
debug("Reloading tsconfig.json");
|
|
104
|
+
(0, _loadTsConfigPaths).loadTsConfigPathsAsync(projectRoot).then((tsConfigPaths)=>{
|
|
105
|
+
if ((tsConfigPaths == null ? void 0 : tsConfigPaths.paths) && !!Object.keys(tsConfigPaths.paths).length) {
|
|
106
|
+
debug("Enabling tsconfig.json paths support");
|
|
107
|
+
var _paths;
|
|
108
|
+
tsConfigResolve = _resolveWithTsConfigPaths.resolveWithTsConfigPaths.bind(_resolveWithTsConfigPaths.resolveWithTsConfigPaths, {
|
|
109
|
+
paths: (_paths = tsConfigPaths.paths) != null ? _paths : {},
|
|
110
|
+
baseUrl: tsConfigPaths.baseUrl
|
|
111
|
+
});
|
|
112
|
+
} else {
|
|
113
|
+
debug("Disabling tsconfig.json paths support");
|
|
114
|
+
tsConfigResolve = null;
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
// TODO: This probably prevents the process from exiting.
|
|
119
|
+
(0, _exit).installExitHooks(()=>{
|
|
120
|
+
configWatcher.stopObserving();
|
|
121
|
+
});
|
|
122
|
+
} else {
|
|
123
|
+
debug("Skipping tsconfig.json paths support");
|
|
124
|
+
}
|
|
71
125
|
return (0, _withMetroResolvers).withMetroResolvers(config, projectRoot, [
|
|
72
126
|
// Add a resolver to alias the web asset resolver.
|
|
73
|
-
(immutableContext,
|
|
74
|
-
|
|
127
|
+
(immutableContext, moduleName1, platform)=>{
|
|
128
|
+
var ref;
|
|
129
|
+
let context = {
|
|
75
130
|
...immutableContext
|
|
76
131
|
};
|
|
132
|
+
const environment = (ref = context.customResolverOptions) == null ? void 0 : ref.environment;
|
|
133
|
+
const isNode = environment === "node";
|
|
134
|
+
// TODO: We need to prevent the require.context from including API routes as these use externals.
|
|
135
|
+
// Should be fine after async routes lands.
|
|
136
|
+
if (isNode) {
|
|
137
|
+
const moduleId = (0, _externals).isNodeExternal(moduleName1);
|
|
138
|
+
if (moduleId) {
|
|
139
|
+
moduleName1 = (0, _externals).getNodeExternalModuleId(context.originModulePath, moduleId);
|
|
140
|
+
debug(`Redirecting Node.js external "${moduleId}" to "${moduleName1}"`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
77
143
|
// Conditionally remap `react-native` to `react-native-web` on web in
|
|
78
144
|
// a way that doesn't require Babel to resolve the alias.
|
|
79
|
-
if (platform && platform in aliases && aliases[platform][
|
|
80
|
-
|
|
145
|
+
if (platform && platform in aliases && aliases[platform][moduleName1]) {
|
|
146
|
+
moduleName1 = aliases[platform][moduleName1];
|
|
81
147
|
}
|
|
82
148
|
// TODO: We may be able to remove this in the future, it's doing no harm
|
|
83
149
|
// by staying here.
|
|
@@ -88,25 +154,73 @@ function withWebResolvers(config, projectRoot) {
|
|
|
88
154
|
...context.extraNodeModules
|
|
89
155
|
};
|
|
90
156
|
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
157
|
+
if ((tsconfig == null ? void 0 : tsconfig.baseUrl) && isTsconfigPathsEnabled) {
|
|
158
|
+
context = {
|
|
159
|
+
...context,
|
|
160
|
+
nodeModulesPaths: [
|
|
161
|
+
...immutableContext.nodeModulesPaths,
|
|
162
|
+
// add last to ensure node modules are resolved first
|
|
163
|
+
tsconfig.baseUrl,
|
|
164
|
+
]
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
let mainFields = context.mainFields;
|
|
168
|
+
if (isNode) {
|
|
169
|
+
// Node.js runtimes should only be importing main at the moment.
|
|
170
|
+
// This is a temporary fix until we can support the package.json exports.
|
|
171
|
+
mainFields = [
|
|
172
|
+
"main"
|
|
173
|
+
];
|
|
174
|
+
} else if (_env.env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE) {
|
|
175
|
+
mainFields = context.mainFields;
|
|
176
|
+
} else if (platform && platform in preferredMainFields) {
|
|
177
|
+
mainFields = preferredMainFields[platform];
|
|
178
|
+
}
|
|
179
|
+
function doResolve(moduleName) {
|
|
180
|
+
return resolve({
|
|
181
|
+
...context,
|
|
182
|
+
preferNativePlatform: platform !== "web",
|
|
183
|
+
resolveRequest: undefined,
|
|
184
|
+
mainFields,
|
|
185
|
+
// Passing `mainFields` directly won't be considered (in certain version of Metro)
|
|
186
|
+
// we need to extend the `getPackageMainPath` directly to
|
|
187
|
+
// use platform specific `mainFields`.
|
|
188
|
+
// @ts-ignore
|
|
189
|
+
getPackageMainPath (packageJsonPath) {
|
|
190
|
+
// @ts-expect-error: mainFields is not on type
|
|
191
|
+
const package_ = context.moduleCache.getPackage(packageJsonPath);
|
|
192
|
+
return package_.getMain(mainFields);
|
|
193
|
+
}
|
|
194
|
+
}, moduleName, platform);
|
|
195
|
+
}
|
|
196
|
+
function optionalResolve(moduleName) {
|
|
197
|
+
try {
|
|
198
|
+
return doResolve(moduleName);
|
|
199
|
+
} catch (error) {
|
|
200
|
+
// If the error is directly related to a resolver not being able to resolve a module, then
|
|
201
|
+
// we can ignore the error and try the next resolver. Otherwise, we should throw the error.
|
|
202
|
+
const isResolutionError = (0, _metroErrors).isFailedToResolveNameError(error) || (0, _metroErrors).isFailedToResolvePathError(error);
|
|
203
|
+
if (!isResolutionError) {
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
let result = null;
|
|
210
|
+
if (tsConfigResolve) {
|
|
211
|
+
result = tsConfigResolve({
|
|
212
|
+
originModulePath: context.originModulePath,
|
|
213
|
+
moduleName: moduleName1
|
|
214
|
+
}, optionalResolve);
|
|
215
|
+
}
|
|
216
|
+
result != null ? result : result = doResolve(moduleName1);
|
|
217
|
+
if (result) {
|
|
218
|
+
// Replace the web resolver with the original one.
|
|
219
|
+
// This is basically an alias for web-only.
|
|
220
|
+
if (shouldAliasAssetRegistryForWeb(platform, result)) {
|
|
221
|
+
// @ts-expect-error: `readonly` for some reason.
|
|
222
|
+
result.filePath = assetRegistryPath;
|
|
103
223
|
}
|
|
104
|
-
}, moduleName, platform);
|
|
105
|
-
// Replace the web resolver with the original one.
|
|
106
|
-
// This is basically an alias for web-only.
|
|
107
|
-
if (shouldAliasAssetRegistryForWeb(platform, result)) {
|
|
108
|
-
// @ts-expect-error: `readonly` for some reason.
|
|
109
|
-
result.filePath = assetRegistryPath;
|
|
110
224
|
}
|
|
111
225
|
return result;
|
|
112
226
|
},
|
|
@@ -115,20 +229,42 @@ function withWebResolvers(config, projectRoot) {
|
|
|
115
229
|
function shouldAliasAssetRegistryForWeb(platform, result) {
|
|
116
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");
|
|
117
231
|
}
|
|
118
|
-
async function withMetroMultiPlatformAsync(projectRoot, config, platformBundlers) {
|
|
119
|
-
// Auto pick
|
|
120
|
-
process.env.EXPO_ROUTER_APP_ROOT = (0, _router).getAppRouterRelativeEntryPath(projectRoot);
|
|
121
|
-
var
|
|
122
|
-
|
|
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
|
+
var _EXPO_PUBLIC_PROJECT_ROOT;
|
|
236
|
+
// Required for @expo/metro-runtime to format paths in the web LogBox.
|
|
237
|
+
process.env.EXPO_PUBLIC_PROJECT_ROOT = (_EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT) != null ? _EXPO_PUBLIC_PROJECT_ROOT : projectRoot;
|
|
238
|
+
if (webOutput === "static") {
|
|
239
|
+
// Enable static rendering in runtime space.
|
|
240
|
+
process.env.EXPO_PUBLIC_USE_STATIC = "1";
|
|
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
|
|
123
248
|
if (platformBundlers.web === "metro") {
|
|
124
249
|
await new _webSupportProjectPrerequisite.WebSupportProjectPrerequisite(projectRoot).assertAsync();
|
|
125
|
-
} else {
|
|
126
|
-
// Bail out early for performance enhancements if
|
|
250
|
+
} else if (!isTsconfigPathsEnabled) {
|
|
251
|
+
// Bail out early for performance enhancements if no special features are enabled.
|
|
127
252
|
return config;
|
|
128
253
|
}
|
|
129
|
-
|
|
254
|
+
let tsconfig = null;
|
|
255
|
+
if (isTsconfigPathsEnabled) {
|
|
256
|
+
_log.Log.warn(_chalk.default.yellow`Experimental path aliases feature is enabled. ` + (0, _link).learnMore("https://docs.expo.dev/guides/typescript/#path-aliases"));
|
|
257
|
+
tsconfig = await (0, _loadTsConfigPaths).loadTsConfigPathsAsync(projectRoot);
|
|
258
|
+
}
|
|
259
|
+
await (0, _externals).setupNodeExternals(projectRoot);
|
|
260
|
+
return withMetroMultiPlatform(projectRoot, {
|
|
261
|
+
config,
|
|
262
|
+
platformBundlers,
|
|
263
|
+
tsconfig,
|
|
264
|
+
isTsconfigPathsEnabled
|
|
265
|
+
});
|
|
130
266
|
}
|
|
131
|
-
function withMetroMultiPlatform(projectRoot, config, platformBundlers) {
|
|
267
|
+
function withMetroMultiPlatform(projectRoot, { config , platformBundlers , isTsconfigPathsEnabled , tsconfig }) {
|
|
132
268
|
let expoConfigPlatforms = Object.entries(platformBundlers).filter(([, bundler])=>bundler === "metro"
|
|
133
269
|
).map(([platform])=>platform
|
|
134
270
|
);
|
|
@@ -139,8 +275,15 @@ function withMetroMultiPlatform(projectRoot, config, platformBundlers) {
|
|
|
139
275
|
}
|
|
140
276
|
// @ts-expect-error: typed as `readonly`.
|
|
141
277
|
config.resolver.platforms = expoConfigPlatforms;
|
|
142
|
-
|
|
143
|
-
|
|
278
|
+
if (expoConfigPlatforms.includes("web")) {
|
|
279
|
+
config = withWebPolyfills(config, projectRoot);
|
|
280
|
+
}
|
|
281
|
+
return withExtendedResolver(config, {
|
|
282
|
+
projectRoot,
|
|
283
|
+
tsconfig,
|
|
284
|
+
isTsconfigPathsEnabled,
|
|
285
|
+
platforms: expoConfigPlatforms
|
|
286
|
+
});
|
|
144
287
|
}
|
|
145
288
|
|
|
146
289
|
//# sourceMappingURL=withMetroMultiPlatform.js.map
|
|
@@ -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 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 { env } from '../../../utils/env';\nimport { WebSupportProjectPrerequisite } from '../../doctor/web/WebSupportProjectPrerequisite';\nimport { PlatformBundlers } from '../platformBundlers';\nimport { importMetroResolverFromProject } from './resolveFromProject';\nimport { getAppRouterRelativeEntryPath } from './router';\nimport { withMetroResolvers } from './withMetroResolvers';\n\nfunction withWebPolyfills(config: ConfigT): 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 // TODO: runtime polyfills, i.e. Fast Refresh, error overlay, React Dev Tools...\n ];\n }\n // Generally uses `rn-get-polyfills`\n return originalGetPolyfills(ctx);\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 */\nexport function withWebResolvers(config: ConfigT, projectRoot: string) {\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 // Create a resolver which dynamically disables support for\n // `*.native.*` extensions on web.\n\n const { resolve } = importMetroResolverFromProject(projectRoot);\n\n const extraNodeModules: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': path.resolve(require.resolve('react-native-web/package.json'), '..'),\n },\n };\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\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 return withMetroResolvers(config, projectRoot, [\n // Add a resolver to alias the web asset resolver.\n (immutableContext: ResolutionContext, moduleName: string, platform: string | null) => {\n const context = { ...immutableContext } as ResolutionContext & { mainFields: string[] };\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 const mainFields = env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE\n ? context.mainFields\n : platform && platform in preferredMainFields\n ? preferredMainFields[platform]\n : context.mainFields;\n\n const result = resolve(\n {\n ...context,\n preferNativePlatform: platform !== 'web',\n resolveRequest: undefined,\n\n // Passing `mainFields` directly won't be considered\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 // 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 config: ConfigT,\n platformBundlers: PlatformBundlers\n) {\n // Auto pick App entry: this is injected with Babel.\n process.env.EXPO_ROUTER_APP_ROOT = getAppRouterRelativeEntryPath(projectRoot);\n process.env.EXPO_PROJECT_ROOT = process.env.EXPO_PROJECT_ROOT ?? projectRoot;\n\n if (platformBundlers.web === 'metro') {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n } else {\n // Bail out early for performance enhancements if web is not enabled.\n return config;\n }\n\n return withMetroMultiPlatform(projectRoot, config, platformBundlers);\n}\n\nfunction withMetroMultiPlatform(\n projectRoot: string,\n config: ConfigT,\n platformBundlers: PlatformBundlers\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 config = withWebPolyfills(config);\n\n return withWebResolvers(config, projectRoot);\n}\n"],"names":["withWebResolvers","shouldAliasAssetRegistryForWeb","withMetroMultiPlatformAsync","withWebPolyfills","config","originalGetPolyfills","serializer","getPolyfills","bind","ctx","platform","normalizeSlashes","p","replace","projectRoot","assetRegistryPath","fs","realpathSync","path","resolve","resolveFrom","importMetroResolverFromProject","extraNodeModules","web","require","aliases","preferredMainFields","withMetroResolvers","immutableContext","moduleName","context","mainFields","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","result","preferNativePlatform","resolveRequest","undefined","getPackageMainPath","packageJsonPath","package_","moduleCache","getPackage","getMain","filePath","type","endsWith","platformBundlers","process","EXPO_ROUTER_APP_ROOT","getAppRouterRelativeEntryPath","EXPO_PROJECT_ROOT","WebSupportProjectPrerequisite","assertAsync","withMetroMultiPlatform","expoConfigPlatforms","Object","entries","filter","bundler","map","Array","isArray","res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AAC2D,QAAQ,CAACC,SAAS,CAAC,CAAC;SAAC,CAAC;KAC3F;IAED,yCAAyC;IACzC5D,MAAM,CAAC2D,QAAQ,CAACC,SAAS,GAAGT,mBAAmB,CAAC;IAEhDnD,MAAM,GAAGD,gBAAgB,CAACC,MAAM,CAAC,CAAC;IAElC,OAAOJ,gBAAgB,CAACI,MAAM,EAAEU,WAAW,CAAC,CAAC;CAC9C"}
|
|
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,WAA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5E,QAAQ,CAAC,KAAK,CAAC,EAAE;QACvCzB,MAAM,GAAGD,gBAAgB,CAACC,MAAM,EAAEC,WAAW,CAAC,CAAC;KAChD;IAED,OAAOP,oBAAoB,CAACM,MAAM,EAAE;QAClCC,WAAW;QACXe,QAAQ;QACRE,sBAAsB;QACtBD,SAAS,EAAEoF,mBAAmB;KAC/B,CAAC,CAAC;CACJ"}
|
|
@@ -52,6 +52,13 @@ class ClassicManifestMiddleware extends _manifestMiddleware.ManifestMiddleware {
|
|
|
52
52
|
hostname: (0, _url).stripPort(req.headers["host"])
|
|
53
53
|
};
|
|
54
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* This header is specified as a string "true" or "false", in one of two headers:
|
|
57
|
+
* - exponent-accept-signature
|
|
58
|
+
* - expo-accept-signature
|
|
59
|
+
*/ getLegacyAcceptSignatureHeader(req) {
|
|
60
|
+
return req.headers["exponent-accept-signature"] === "true" || req.headers["expo-accept-signature"] === "true";
|
|
61
|
+
}
|
|
55
62
|
async _getManifestResponseAsync({ acceptSignature , ...requestOptions }) {
|
|
56
63
|
const { exp , hostUri , expoGoConfig , bundleUrl } = await this._resolveProjectSettingsAsync(requestOptions);
|
|
57
64
|
const manifest = {
|
|
@@ -130,7 +137,7 @@ async function createHostInfoAsync() {
|
|
|
130
137
|
host: await _userSettings.default.getAnonymousIdentifierAsync(),
|
|
131
138
|
server: "expo",
|
|
132
139
|
// Defined in the build step
|
|
133
|
-
serverVersion: "0.
|
|
140
|
+
serverVersion: "0.9.0",
|
|
134
141
|
serverDriver: _manifestMiddleware.DEVELOPER_TOOL,
|
|
135
142
|
serverOS: _os.default.platform(),
|
|
136
143
|
serverOSVersion: _os.default.release()
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/ClassicManifestMiddleware.ts"],"sourcesContent":["import { ExpoAppManifest, ExpoConfig } from '@expo/config';\nimport chalk from 'chalk';\nimport os from 'os';\n\nimport { APISettings } from '../../../api/settings';\nimport { signClassicExpoGoManifestAsync } from '../../../api/signManifest';\nimport UserSettings from '../../../api/user/UserSettings';\nimport { ANONYMOUS_USERNAME, getUserAsync } from '../../../api/user/user';\nimport * as Log from '../../../log';\nimport { logEventAsync } from '../../../utils/analytics/rudderstackClient';\nimport { memoize } from '../../../utils/fn';\nimport { learnMore } from '../../../utils/link';\nimport { stripPort } from '../../../utils/url';\nimport {\n DEVELOPER_TOOL,\n HostInfo,\n ManifestMiddleware,\n ManifestRequestInfo,\n} from './ManifestMiddleware';\nimport { assertRuntimePlatform, parsePlatformHeader } from './resolvePlatform';\nimport { ServerHeaders, ServerRequest } from './server.types';\n\ntype SignManifestProps = {\n manifest: ExpoAppManifest;\n hostId: string;\n acceptSignature: boolean;\n};\n\ninterface ClassicManifestRequestInfo extends ManifestRequestInfo {}\n\nconst debug = require('debug')(\n 'expo:start:server:middleware:ClassicManifestMiddleware'\n) as typeof console.log;\n\nexport class ClassicManifestMiddleware extends ManifestMiddleware<ClassicManifestRequestInfo> {\n public getParsedHeaders(req: ServerRequest): ClassicManifestRequestInfo {\n const platform = parsePlatformHeader(req) || 'ios';\n assertRuntimePlatform(platform);\n return {\n platform,\n acceptSignature: this.getLegacyAcceptSignatureHeader(req),\n hostname: stripPort(req.headers['host']),\n };\n }\n\n public async _getManifestResponseAsync({\n acceptSignature,\n ...requestOptions\n }: ClassicManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }> {\n const { exp, hostUri, expoGoConfig, bundleUrl } = await this._resolveProjectSettingsAsync(\n requestOptions\n );\n\n const manifest: ExpoAppManifest = {\n ...(exp as ExpoAppManifest),\n ...expoGoConfig,\n hostUri,\n bundleUrl,\n };\n\n // Gather packager and host info\n const hostInfo = await createHostInfoAsync();\n\n const headers = new Map<string, any>();\n headers.set('Exponent-Server', JSON.stringify(hostInfo));\n\n // Create the final string\n const body = await this._fetchComputedManifestStringAsync({\n manifest,\n hostId: hostInfo.host,\n acceptSignature,\n });\n\n return {\n body,\n version: manifest.sdkVersion,\n headers,\n };\n }\n\n protected trackManifest(version?: string) {\n // Log analytics\n logEventAsync('Serve Manifest', {\n sdkVersion: version ?? null,\n });\n }\n\n /** Exposed for testing. */\n async _getManifestStringAsync({\n manifest,\n hostId,\n acceptSignature,\n }: SignManifestProps): Promise<string> {\n const currentSession = await getUserAsync();\n if (!currentSession || APISettings.isOffline) {\n manifest.id = `@${ANONYMOUS_USERNAME}/${manifest.slug}-${hostId}`;\n }\n if (!acceptSignature) {\n return JSON.stringify(manifest);\n } else if (!currentSession || APISettings.isOffline) {\n return getUnsignedManifestString(manifest);\n } else {\n return this.getSignedManifestStringAsync(manifest);\n }\n }\n\n private getSignedManifestStringAsync = memoize(signClassicExpoGoManifestAsync);\n\n /** Exposed for testing. */\n async _fetchComputedManifestStringAsync(props: SignManifestProps): Promise<string> {\n try {\n return await this._getManifestStringAsync(props);\n } catch (error: any) {\n debug(`Error getting manifest:`, error);\n if (error.code === 'UNAUTHORIZED' && props.manifest.owner) {\n // Don't have permissions for siging, warn and enable offline mode.\n this.addSigningDisabledWarning(\n `This project belongs to ${chalk.bold(\n `@${props.manifest.owner}`\n )} and you have not been granted the appropriate permissions.\\n` +\n `Please request access from an admin of @${props.manifest.owner} or change the \"owner\" field to an account you belong to.\\n` +\n learnMore('https://docs.expo.dev/versions/latest/config/app/#owner')\n );\n APISettings.isOffline = true;\n return await this._getManifestStringAsync(props);\n } else if (error.code === 'ENOTFOUND') {\n // Got a DNS error, i.e. can't access exp.host, warn and enable offline mode.\n this.addSigningDisabledWarning(\n `Could not reach Expo servers, please check if you can access ${\n error.hostname || 'exp.host'\n }.`\n );\n APISettings.isOffline = true;\n return await this._getManifestStringAsync(props);\n } else {\n throw error;\n }\n }\n }\n\n private addSigningDisabledWarning = memoize((reason: string) => {\n Log.warn(`${reason}\\nFalling back to offline mode.`);\n // For the memo\n return reason;\n });\n}\n\n// Passed to Expo Go and registered as telemetry.\n// TODO: it's unclear why we don't just send it from the CLI.\nasync function createHostInfoAsync(): Promise<HostInfo> {\n return {\n host: await UserSettings.getAnonymousIdentifierAsync(),\n server: 'expo',\n // Defined in the build step\n serverVersion: process.env.__EXPO_VERSION!,\n serverDriver: DEVELOPER_TOOL,\n serverOS: os.platform(),\n serverOSVersion: os.release(),\n };\n}\n\nfunction getUnsignedManifestString(manifest: ExpoConfig) {\n const unsignedManifest = {\n manifestString: JSON.stringify(manifest),\n signature: 'UNSIGNED',\n };\n return JSON.stringify(unsignedManifest);\n}\n"],"names":["Log","debug","require","ClassicManifestMiddleware","ManifestMiddleware","getParsedHeaders","req","platform","parsePlatformHeader","assertRuntimePlatform","acceptSignature","getLegacyAcceptSignatureHeader","hostname","stripPort","headers","_getManifestResponseAsync","requestOptions","exp","hostUri","expoGoConfig","bundleUrl","_resolveProjectSettingsAsync","manifest","hostInfo","createHostInfoAsync","Map","set","JSON","stringify","body","_fetchComputedManifestStringAsync","hostId","host","version","sdkVersion","trackManifest","logEventAsync","_getManifestStringAsync","currentSession","getUserAsync","APISettings","isOffline","id","ANONYMOUS_USERNAME","slug","getUnsignedManifestString","getSignedManifestStringAsync","memoize","signClassicExpoGoManifestAsync","props","error","code","owner","addSigningDisabledWarning","chalk","bold","learnMore","reason","warn","UserSettings","getAnonymousIdentifierAsync","server","serverVersion","process","env","__EXPO_VERSION","serverDriver","DEVELOPER_TOOL","serverOS","os","serverOSVersion","release","unsignedManifest","manifestString","signature"],"mappings":"AAAA;;;;AACkB,IAAA,MAAO,kCAAP,OAAO,EAAA;AACV,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAES,IAAA,SAAuB,WAAvB,uBAAuB,CAAA;AACJ,IAAA,aAA2B,WAA3B,2BAA2B,CAAA;AACjD,IAAA,aAAgC,kCAAhC,gCAAgC,EAAA;AACR,IAAA,KAAwB,WAAxB,wBAAwB,CAAA;AAC7DA,IAAAA,GAAG,mCAAM,cAAc,EAApB;AACe,IAAA,kBAA4C,WAA5C,4CAA4C,CAAA;AAClD,IAAA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KAAK,CAAC,CAAC;aAClD,MAAM;gBACL,MAAMC,KAAK,CAAC;aACb;SACF;KACF;IAED,AAAQG,yBAAyB,GAAGN,CAAAA,GAAAA,GAAO,AAIzC,CAAA,QAJyC,CAAC,CAACU,MAAc,GAAK;QAC9DzD,GAAG,CAAC0D,IAAI,CAAC,CAAC,EAAED,MAAM,CAAC,+BAA+B,CAAC,CAAC,CAAC;QACrD,eAAe;QACf,OAAOA,MAAM,CAAC;KACf,CAAC,CAAC;CACJ;QAnHYtD,yBAAyB,GAAzBA,yBAAyB;AAqHtC,iDAAiD;AACjD,6DAA6D;AAC7D,eAAeqB,mBAAmB,GAAsB;IACtD,OAAO;QACLQ,IAAI,EAAE,MAAM2B,aAAY,QAAA,CAACC,2BAA2B,EAAE;QACtDC,MAAM,EAAE,MAAM;QACd,4BAA4B;QAC5BC,aAAa,EAAEC,OAAO,CAACC,GAAG,CAACC,cAAc;QACzCC,YAAY,EAAEC,mBAAc,eAAA;QAC5BC,QAAQ,EAAEC,GAAE,QAAA,CAAC9D,QAAQ,EAAE;QACvB+D,eAAe,EAAED,GAAE,QAAA,CAACE,OAAO,EAAE;KAC9B,CAAC;CACH;AAED,SAAS1B,yBAAyB,CAACvB,QAAoB,EAAE;IACvD,MAAMkD,gBAAgB,GAAG;QACvBC,cAAc,EAAE9C,IAAI,CAACC,SAAS,CAACN,QAAQ,CAAC;QACxCoD,SAAS,EAAE,UAAU;KACtB,AAAC;IACF,OAAO/C,IAAI,CAACC,SAAS,CAAC4C,gBAAgB,CAAC,CAAC;CACzC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/ClassicManifestMiddleware.ts"],"sourcesContent":["import { ExpoAppManifest, ExpoConfig } from '@expo/config';\nimport chalk from 'chalk';\nimport os from 'os';\n\nimport { APISettings } from '../../../api/settings';\nimport { signClassicExpoGoManifestAsync } from '../../../api/signManifest';\nimport UserSettings from '../../../api/user/UserSettings';\nimport { ANONYMOUS_USERNAME, getUserAsync } from '../../../api/user/user';\nimport * as Log from '../../../log';\nimport { logEventAsync } from '../../../utils/analytics/rudderstackClient';\nimport { memoize } from '../../../utils/fn';\nimport { learnMore } from '../../../utils/link';\nimport { stripPort } from '../../../utils/url';\nimport {\n DEVELOPER_TOOL,\n HostInfo,\n ManifestMiddleware,\n ManifestRequestInfo,\n} from './ManifestMiddleware';\nimport { assertRuntimePlatform, parsePlatformHeader } from './resolvePlatform';\nimport { ServerHeaders, ServerRequest } from './server.types';\n\ntype SignManifestProps = {\n manifest: ExpoAppManifest;\n hostId: string;\n acceptSignature: boolean;\n};\n\ninterface ClassicManifestRequestInfo extends ManifestRequestInfo {\n /** Should return the signed manifest. */\n acceptSignature: boolean;\n}\n\nconst debug = require('debug')(\n 'expo:start:server:middleware:ClassicManifestMiddleware'\n) as typeof console.log;\n\nexport class ClassicManifestMiddleware extends ManifestMiddleware<ClassicManifestRequestInfo> {\n public getParsedHeaders(req: ServerRequest): ClassicManifestRequestInfo {\n const platform = parsePlatformHeader(req) || 'ios';\n assertRuntimePlatform(platform);\n return {\n platform,\n acceptSignature: this.getLegacyAcceptSignatureHeader(req),\n hostname: stripPort(req.headers['host']),\n };\n }\n\n /**\n * This header is specified as a string \"true\" or \"false\", in one of two headers:\n * - exponent-accept-signature\n * - expo-accept-signature\n */\n private getLegacyAcceptSignatureHeader(req: ServerRequest): boolean {\n return (\n req.headers['exponent-accept-signature'] === 'true' ||\n req.headers['expo-accept-signature'] === 'true'\n );\n }\n\n public async _getManifestResponseAsync({\n acceptSignature,\n ...requestOptions\n }: ClassicManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }> {\n const { exp, hostUri, expoGoConfig, bundleUrl } = await this._resolveProjectSettingsAsync(\n requestOptions\n );\n\n const manifest: ExpoAppManifest = {\n ...(exp as ExpoAppManifest),\n ...expoGoConfig,\n hostUri,\n bundleUrl,\n };\n\n // Gather packager and host info\n const hostInfo = await createHostInfoAsync();\n\n const headers = new Map<string, any>();\n headers.set('Exponent-Server', JSON.stringify(hostInfo));\n\n // Create the final string\n const body = await this._fetchComputedManifestStringAsync({\n manifest,\n hostId: hostInfo.host,\n acceptSignature,\n });\n\n return {\n body,\n version: manifest.sdkVersion,\n headers,\n };\n }\n\n protected trackManifest(version?: string) {\n // Log analytics\n logEventAsync('Serve Manifest', {\n sdkVersion: version ?? null,\n });\n }\n\n /** Exposed for testing. */\n async _getManifestStringAsync({\n manifest,\n hostId,\n acceptSignature,\n }: SignManifestProps): Promise<string> {\n const currentSession = await getUserAsync();\n if (!currentSession || APISettings.isOffline) {\n manifest.id = `@${ANONYMOUS_USERNAME}/${manifest.slug}-${hostId}`;\n }\n if (!acceptSignature) {\n return JSON.stringify(manifest);\n } else if (!currentSession || APISettings.isOffline) {\n return getUnsignedManifestString(manifest);\n } else {\n return this.getSignedManifestStringAsync(manifest);\n }\n }\n\n private getSignedManifestStringAsync = memoize(signClassicExpoGoManifestAsync);\n\n /** Exposed for testing. */\n async _fetchComputedManifestStringAsync(props: SignManifestProps): Promise<string> {\n try {\n return await this._getManifestStringAsync(props);\n } catch (error: any) {\n debug(`Error getting manifest:`, error);\n if (error.code === 'UNAUTHORIZED' && props.manifest.owner) {\n // Don't have permissions for siging, warn and enable offline mode.\n this.addSigningDisabledWarning(\n `This project belongs to ${chalk.bold(\n `@${props.manifest.owner}`\n )} and you have not been granted the appropriate permissions.\\n` +\n `Please request access from an admin of @${props.manifest.owner} or change the \"owner\" field to an account you belong to.\\n` +\n learnMore('https://docs.expo.dev/versions/latest/config/app/#owner')\n );\n APISettings.isOffline = true;\n return await this._getManifestStringAsync(props);\n } else if (error.code === 'ENOTFOUND') {\n // Got a DNS error, i.e. can't access exp.host, warn and enable offline mode.\n this.addSigningDisabledWarning(\n `Could not reach Expo servers, please check if you can access ${\n error.hostname || 'exp.host'\n }.`\n );\n APISettings.isOffline = true;\n return await this._getManifestStringAsync(props);\n } else {\n throw error;\n }\n }\n }\n\n private addSigningDisabledWarning = memoize((reason: string) => {\n Log.warn(`${reason}\\nFalling back to offline mode.`);\n // For the memo\n return reason;\n });\n}\n\n// Passed to Expo Go and registered as telemetry.\n// TODO: it's unclear why we don't just send it from the CLI.\nasync function createHostInfoAsync(): Promise<HostInfo> {\n return {\n host: await UserSettings.getAnonymousIdentifierAsync(),\n server: 'expo',\n // Defined in the build step\n serverVersion: process.env.__EXPO_VERSION!,\n serverDriver: DEVELOPER_TOOL,\n serverOS: os.platform(),\n serverOSVersion: os.release(),\n };\n}\n\nfunction getUnsignedManifestString(manifest: ExpoConfig) {\n const unsignedManifest = {\n manifestString: JSON.stringify(manifest),\n signature: 'UNSIGNED',\n };\n return JSON.stringify(unsignedManifest);\n}\n"],"names":["Log","debug","require","ClassicManifestMiddleware","ManifestMiddleware","getParsedHeaders","req","platform","parsePlatformHeader","assertRuntimePlatform","acceptSignature","getLegacyAcceptSignatureHeader","hostname","stripPort","headers","_getManifestResponseAsync","requestOptions","exp","hostUri","expoGoConfig","bundleUrl","_resolveProjectSettingsAsync","manifest","hostInfo","createHostInfoAsync","Map","set","JSON","stringify","body","_fetchComputedManifestStringAsync","hostId","host","version","sdkVersion","trackManifest","logEventAsync","_getManifestStringAsync","currentSession","getUserAsync","APISettings","isOffline","id","ANONYMOUS_USERNAME","slug","getUnsignedManifestString","getSignedManifestStringAsync","memoize","signClassicExpoGoManifestAsync","props","error","code","owner","addSigningDisabledWarning","chalk","bold","learnMore","reason","warn","UserSettings","getAnonymousIdentifierAsync","server","serverVersion","process","env","__EXPO_VERSION","serverDriver","DEVELOPER_TOOL","serverOS","os","serverOSVersion","release","unsignedManifest","manifestString","signature"],"mappings":"AAAA;;;;AACkB,IAAA,MAAO,kCAAP,OAAO,EAAA;AACV,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAES,IAAA,SAAuB,WAAvB,uBAAuB,CAAA;AACJ,IAAA,aAA2B,WAA3B,2BAA2B,CAAA;AACjD,IAAA,aAAgC,kCAAhC,gCAAgC,EAAA;AACR,IAAA,KAAwB,W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4C,gBAAgB,CAAC,CAAC;CACzC"}
|
|
@@ -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":["
|
|
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,CAAC,CAAC,yCAAyC,CAAC,AAAsB,AAAC;AAazF,MAAMC,oBAAoB,SAASC,eAAc,eAAA;IACtDC,YAAsBC,WAAmB,CAAE;QACzC,KAAK,CAACA,WAAW,EAAE;YAAC,cAAc;SAAC,CAAC,CAAC;aADjBA,WAAmB,GAAnBA,WAAmB;KAExC;IAED,AAAUC,WAAW,CAACC,SAAiB,EAAU;QAC/C,OAAO,IAAI,CAACC,gBAAgB,CAACC,KAAI,QAAA,CAACC,IAAI,CAAC,IAAI,CAACL,WAAW,EAAEE,SAAS,CAAC,CAAC,CAAC;KACtE;IAED,AAAUC,gBAAgB,CAACD,SAAiB,EAAU;QACpD,IAAII,YAAY,GAAGJ,SAAS,AAAC;QAC7B,MAAMK,SAAS,GAAGH,KAAI,QAAA,CAACI,OAAO,CAACN,SAAS,CAAC,AAAC;QAC1C,IAAIK,SAAS,KAAK,K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