@expo/cli 55.0.6 → 55.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/bin/cli +1 -1
- package/build/src/api/user/actions.js +5 -2
- package/build/src/api/user/actions.js.map +1 -1
- package/build/src/api/user/expoSsoLauncher.js +22 -49
- package/build/src/api/user/expoSsoLauncher.js.map +1 -1
- package/build/src/api/user/user.js +6 -5
- package/build/src/api/user/user.js.map +1 -1
- package/build/src/login/index.js +6 -2
- package/build/src/login/index.js.map +1 -1
- package/build/src/start/platforms/ios/devicectl.js +4 -1
- package/build/src/start/platforms/ios/devicectl.js.map +1 -1
- package/build/src/start/server/metro/debugging/createDebugMiddleware.js +5 -1
- package/build/src/start/server/metro/debugging/createDebugMiddleware.js.map +1 -1
- package/build/src/start/server/metro/instantiateMetro.js +9 -5
- package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
- package/build/src/utils/downloadExpoGoAsync.js +36 -0
- package/build/src/utils/downloadExpoGoAsync.js.map +1 -1
- package/build/src/utils/env.js +13 -11
- package/build/src/utils/env.js.map +1 -1
- package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
- package/build/src/utils/telemetry/utils/context.js +1 -1
- package/package.json +6 -6
package/build/bin/cli
CHANGED
|
@@ -90,11 +90,14 @@ async function showLoginPromptAsync({ printNewLine = false, otp, ...options } =
|
|
|
90
90
|
}
|
|
91
91
|
const hasCredentials = options.username && options.password;
|
|
92
92
|
const sso = options.sso;
|
|
93
|
+
const browser = options.browser;
|
|
93
94
|
if (printNewLine) {
|
|
94
95
|
_log.log();
|
|
95
96
|
}
|
|
96
|
-
if (sso) {
|
|
97
|
-
await (0, _user.
|
|
97
|
+
if (sso || browser) {
|
|
98
|
+
await (0, _user.browserLoginAsync)({
|
|
99
|
+
sso: !!sso
|
|
100
|
+
});
|
|
98
101
|
return;
|
|
99
102
|
}
|
|
100
103
|
_log.log(hasCredentials ? `Logging in to EAS with email or username (exit and run 'npx expo login --help' for other login options)` : `Log in to EAS with email or username (exit and run 'npx expo login --help' for other login options)`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/api/user/actions.ts"],"sourcesContent":["import assert from 'assert';\nimport chalk from 'chalk';\n\nimport { retryUsernamePasswordAuthWithOTPAsync } from './otp';\nimport { Actor, getUserAsync, loginAsync,
|
|
1
|
+
{"version":3,"sources":["../../../../src/api/user/actions.ts"],"sourcesContent":["import assert from 'assert';\nimport chalk from 'chalk';\n\nimport { retryUsernamePasswordAuthWithOTPAsync } from './otp';\nimport { Actor, getUserAsync, loginAsync, browserLoginAsync } from './user';\nimport * as Log from '../../log';\nimport { env } from '../../utils/env';\nimport { CommandError } from '../../utils/errors';\nimport { learnMore } from '../../utils/link';\nimport promptAsync, { confirmAsync, Question, selectAsync } from '../../utils/prompts';\nimport { ApiV2Error } from '../rest/client';\n\n/** Show login prompt while prompting for missing credentials. */\nexport async function showLoginPromptAsync({\n printNewLine = false,\n otp,\n ...options\n}: {\n printNewLine?: boolean;\n username?: string;\n password?: string;\n otp?: string;\n sso?: boolean | undefined;\n browser?: boolean | undefined;\n} = {}): Promise<void> {\n if (env.EXPO_OFFLINE) {\n throw new CommandError('OFFLINE', 'Cannot authenticate in offline-mode');\n }\n const hasCredentials = options.username && options.password;\n const sso = options.sso;\n const browser = options.browser;\n\n if (printNewLine) {\n Log.log();\n }\n\n if (sso || browser) {\n await browserLoginAsync({ sso: !!sso });\n return;\n }\n\n Log.log(\n hasCredentials\n ? `Logging in to EAS with email or username (exit and run 'npx expo login --help' for other login options)`\n : `Log in to EAS with email or username (exit and run 'npx expo login --help' for other login options)`\n );\n\n let username = options.username;\n let password = options.password;\n\n if (!hasCredentials) {\n const resolved = await promptAsync(\n [\n !options.username && {\n type: 'text',\n name: 'username',\n message: 'Email or username',\n },\n !options.password && {\n type: 'password',\n name: 'password',\n message: 'Password',\n },\n ].filter(Boolean) as Question<string>[],\n {\n nonInteractiveHelp: `Use the EXPO_TOKEN environment variable to authenticate in CI (${learnMore(\n 'https://docs.expo.dev/accounts/programmatic-access/'\n )})`,\n }\n );\n username ??= resolved.username;\n password ??= resolved.password;\n }\n // This is just for the types.\n assert(username && password);\n\n try {\n await loginAsync({\n username,\n password,\n otp,\n });\n } catch (e) {\n if (e instanceof ApiV2Error && e.expoApiV2ErrorCode === 'ONE_TIME_PASSWORD_REQUIRED') {\n await retryUsernamePasswordAuthWithOTPAsync(\n username,\n password,\n e.expoApiV2ErrorMetadata as any\n );\n } else {\n throw e;\n }\n }\n}\n\nexport async function tryGetUserAsync(): Promise<Actor | null> {\n const user = await getUserAsync().catch(() => null);\n\n if (user) {\n return user;\n }\n\n const choices = [\n {\n title: 'Log in',\n value: true,\n },\n {\n title: 'Proceed anonymously',\n value: false,\n },\n ];\n\n const value = await selectAsync(\n chalk`\\n\\nIt is recommended to log in with your Expo account before proceeding. \\n{dim ${learnMore(\n 'https://expo.fyi/unverified-app-expo-go'\n )}}\\n`,\n choices,\n {\n nonInteractiveHelp: `Use the EXPO_TOKEN environment variable to authenticate in CI (${learnMore(\n 'https://docs.expo.dev/accounts/programmatic-access/'\n )})`,\n }\n );\n\n if (value) {\n await showLoginPromptAsync({ printNewLine: true });\n return (await getUserAsync()) ?? null;\n }\n\n return null;\n}\n"],"names":["showLoginPromptAsync","tryGetUserAsync","printNewLine","otp","options","env","EXPO_OFFLINE","CommandError","hasCredentials","username","password","sso","browser","Log","log","browserLoginAsync","resolved","promptAsync","type","name","message","filter","Boolean","nonInteractiveHelp","learnMore","assert","loginAsync","e","ApiV2Error","expoApiV2ErrorCode","retryUsernamePasswordAuthWithOTPAsync","expoApiV2ErrorMetadata","user","getUserAsync","catch","choices","title","value","selectAsync","chalk"],"mappings":";;;;;;;;;;;IAasBA,oBAAoB;eAApBA;;IAkFAC,eAAe;eAAfA;;;;gEA/FH;;;;;;;gEACD;;;;;;qBAEoC;sBACa;6DAC9C;qBACD;wBACS;sBACH;iEACuC;wBACtC;;;;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IAAID,EAAEE,kBAAkB,KAAK,8BAA8B;YACpF,MAAMC,IAAAA,0CAAqC,EACzCrB,UACAC,UACAiB,EAAEI,sBAAsB;QAE5B,OAAO;YACL,MAAMJ;QACR;IACF;AACF;AAEO,eAAe1B;IACpB,MAAM+B,OAAO,MAAMC,IAAAA,kBAAY,IAAGC,KAAK,CAAC,IAAM;IAE9C,IAAIF,MAAM;QACR,OAAOA;IACT;IAEA,MAAMG,UAAU;QACd;YACEC,OAAO;YACPC,OAAO;QACT;QACA;YACED,OAAO;YACPC,OAAO;QACT;KACD;IAED,MAAMA,QAAQ,MAAMC,IAAAA,oBAAW,EAC7BC,IAAAA,gBAAK,CAAA,CAAC,iFAAiF,EAAEf,IAAAA,eAAS,EAChG,2CACA,GAAG,CAAC,EACNW,SACA;QACEZ,oBAAoB,CAAC,+DAA+D,EAAEC,IAAAA,eAAS,EAC7F,uDACA,CAAC,CAAC;IACN;IAGF,IAAIa,OAAO;QACT,MAAMrC,qBAAqB;YAAEE,cAAc;QAAK;QAChD,OAAO,AAAC,MAAM+B,IAAAA,kBAAY,OAAO;IACnC;IAEA,OAAO;AACT"}
|
|
@@ -83,55 +83,37 @@ function _interop_require_wildcard(obj, nodeInterop) {
|
|
|
83
83
|
}
|
|
84
84
|
return newObj;
|
|
85
85
|
}
|
|
86
|
-
|
|
87
|
-
<!DOCTYPE html>
|
|
88
|
-
<html lang="en">
|
|
89
|
-
<head>
|
|
90
|
-
<title>Expo SSO Login</title>
|
|
91
|
-
<meta charset="utf-8">
|
|
92
|
-
<style type="text/css">
|
|
93
|
-
html {
|
|
94
|
-
margin: 0;
|
|
95
|
-
padding: 0
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
body {
|
|
99
|
-
background-color: #fff;
|
|
100
|
-
font-family: Tahoma,Verdana;
|
|
101
|
-
font-size: 16px;
|
|
102
|
-
color: #000;
|
|
103
|
-
max-width: 100%;
|
|
104
|
-
box-sizing: border-box;
|
|
105
|
-
padding: .5rem;
|
|
106
|
-
margin: 1em;
|
|
107
|
-
overflow-wrap: break-word
|
|
108
|
-
}
|
|
109
|
-
</style>
|
|
110
|
-
</head>
|
|
111
|
-
<body>
|
|
112
|
-
SSO login complete. You may now close this tab and return to the command prompt.
|
|
113
|
-
</body>
|
|
114
|
-
</html>`;
|
|
115
|
-
async function getSessionUsingBrowserAuthFlowAsync({ expoWebsiteUrl }) {
|
|
86
|
+
async function getSessionUsingBrowserAuthFlowAsync({ expoWebsiteUrl, sso = false }) {
|
|
116
87
|
const scheme = 'http';
|
|
117
88
|
const hostname = 'localhost';
|
|
118
89
|
const path = '/auth/callback';
|
|
119
|
-
const
|
|
120
|
-
const
|
|
90
|
+
const buildExpoLoginUrl = (port, sso)=>{
|
|
91
|
+
const params = _querystring().default.stringify({
|
|
92
|
+
confirm_account: 'true',
|
|
121
93
|
app_redirect_uri: `${scheme}://${hostname}:${port}${path}`
|
|
122
|
-
};
|
|
123
|
-
|
|
124
|
-
return `${expoWebsiteUrl}/sso-login?${params}`;
|
|
94
|
+
});
|
|
95
|
+
return `${expoWebsiteUrl}${sso ? '/sso-login' : '/login'}?${params}`;
|
|
125
96
|
};
|
|
126
97
|
// Start server and begin auth flow
|
|
127
98
|
const executeAuthFlow = ()=>{
|
|
128
99
|
return new Promise(async (resolve, reject)=>{
|
|
129
100
|
const connections = new Set();
|
|
130
101
|
const server = _http().default.createServer((request, response)=>{
|
|
102
|
+
const redirectAndCleanup = (result)=>{
|
|
103
|
+
const redirectUrl = `${expoWebsiteUrl}/oauth/expo-cli?result=${result}`;
|
|
104
|
+
response.writeHead(302, {
|
|
105
|
+
Location: redirectUrl
|
|
106
|
+
});
|
|
107
|
+
response.end();
|
|
108
|
+
server.close();
|
|
109
|
+
for (const connection of connections){
|
|
110
|
+
connection.destroy();
|
|
111
|
+
}
|
|
112
|
+
};
|
|
131
113
|
try {
|
|
132
114
|
var _request_url;
|
|
133
|
-
if (!(request.method === 'GET' && ((_request_url = request.url) == null ? void 0 : _request_url.includes(
|
|
134
|
-
throw new Error('Unexpected
|
|
115
|
+
if (!(request.method === 'GET' && ((_request_url = request.url) == null ? void 0 : _request_url.includes('/auth/callback')))) {
|
|
116
|
+
throw new Error('Unexpected login response.');
|
|
135
117
|
}
|
|
136
118
|
const url = new URL(request.url, `http:${request.headers.host}`);
|
|
137
119
|
const sessionSecret = url.searchParams.get('session_secret');
|
|
@@ -139,19 +121,10 @@ async function getSessionUsingBrowserAuthFlowAsync({ expoWebsiteUrl }) {
|
|
|
139
121
|
throw new Error('Request missing session_secret search parameter.');
|
|
140
122
|
}
|
|
141
123
|
resolve(sessionSecret);
|
|
142
|
-
|
|
143
|
-
'Content-Type': 'text/html'
|
|
144
|
-
});
|
|
145
|
-
response.write(successBody);
|
|
146
|
-
response.end();
|
|
124
|
+
redirectAndCleanup('success');
|
|
147
125
|
} catch (error) {
|
|
126
|
+
redirectAndCleanup('error');
|
|
148
127
|
reject(error);
|
|
149
|
-
} finally{
|
|
150
|
-
server.close();
|
|
151
|
-
// Ensure that the server shuts down
|
|
152
|
-
for (const connection of connections){
|
|
153
|
-
connection.destroy();
|
|
154
|
-
}
|
|
155
128
|
}
|
|
156
129
|
});
|
|
157
130
|
server.listen(0, hostname, ()=>{
|
|
@@ -159,7 +132,7 @@ async function getSessionUsingBrowserAuthFlowAsync({ expoWebsiteUrl }) {
|
|
|
159
132
|
const address = server.address();
|
|
160
133
|
(0, _assert().default)(address !== null && typeof address === 'object', 'Server address and port should be set after listening has begun');
|
|
161
134
|
const port = address.port;
|
|
162
|
-
const authorizeUrl =
|
|
135
|
+
const authorizeUrl = buildExpoLoginUrl(port, sso);
|
|
163
136
|
(0, _betteropn().default)(authorizeUrl);
|
|
164
137
|
});
|
|
165
138
|
server.on('connection', (connection)=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/api/user/expoSsoLauncher.ts"],"sourcesContent":["import assert from 'assert';\nimport openBrowserAsync from 'better-opn';\nimport http from 'http';\nimport { Socket } from 'node:net';\nimport querystring from 'querystring';\n\nimport * as Log from '../../log';\n\
|
|
1
|
+
{"version":3,"sources":["../../../../src/api/user/expoSsoLauncher.ts"],"sourcesContent":["import assert from 'assert';\nimport openBrowserAsync from 'better-opn';\nimport http from 'http';\nimport { Socket } from 'node:net';\nimport querystring from 'querystring';\n\nimport * as Log from '../../log';\n\nexport async function getSessionUsingBrowserAuthFlowAsync({\n expoWebsiteUrl,\n sso = false,\n}: {\n expoWebsiteUrl: string;\n sso?: boolean;\n}): Promise<string> {\n const scheme = 'http';\n const hostname = 'localhost';\n const path = '/auth/callback';\n\n const buildExpoLoginUrl = (port: number, sso: boolean): string => {\n const params = querystring.stringify({\n confirm_account: 'true',\n app_redirect_uri: `${scheme}://${hostname}:${port}${path}`,\n });\n return `${expoWebsiteUrl}${sso ? '/sso-login' : '/login'}?${params}`;\n };\n\n // Start server and begin auth flow\n const executeAuthFlow = (): Promise<string> => {\n return new Promise<string>(async (resolve, reject) => {\n const connections = new Set<Socket>();\n\n const server = http.createServer(\n (request: http.IncomingMessage, response: http.ServerResponse) => {\n const redirectAndCleanup = (result: 'success' | 'error'): void => {\n const redirectUrl = `${expoWebsiteUrl}/oauth/expo-cli?result=${result}`;\n response.writeHead(302, { Location: redirectUrl });\n response.end();\n server.close();\n for (const connection of connections) {\n connection.destroy();\n }\n };\n\n try {\n if (!(request.method === 'GET' && request.url?.includes('/auth/callback'))) {\n throw new Error('Unexpected login response.');\n }\n const url = new URL(request.url, `http:${request.headers.host}`);\n const sessionSecret = url.searchParams.get('session_secret');\n\n if (!sessionSecret) {\n throw new Error('Request missing session_secret search parameter.');\n }\n resolve(sessionSecret);\n redirectAndCleanup('success');\n } catch (error) {\n redirectAndCleanup('error');\n reject(error);\n }\n }\n );\n\n server.listen(0, hostname, () => {\n Log.log('Waiting for browser login...');\n\n const address = server.address();\n assert(\n address !== null && typeof address === 'object',\n 'Server address and port should be set after listening has begun'\n );\n const port = address.port;\n const authorizeUrl = buildExpoLoginUrl(port, sso);\n openBrowserAsync(authorizeUrl);\n });\n\n server.on('connection', (connection) => {\n connections.add(connection);\n\n connection.on('close', () => {\n connections.delete(connection);\n });\n });\n });\n };\n\n return await executeAuthFlow();\n}\n"],"names":["getSessionUsingBrowserAuthFlowAsync","expoWebsiteUrl","sso","scheme","hostname","path","buildExpoLoginUrl","port","params","querystring","stringify","confirm_account","app_redirect_uri","executeAuthFlow","Promise","resolve","reject","connections","Set","server","http","createServer","request","response","redirectAndCleanup","result","redirectUrl","writeHead","Location","end","close","connection","destroy","method","url","includes","Error","URL","headers","host","sessionSecret","searchParams","get","error","listen","Log","log","address","assert","authorizeUrl","openBrowserAsync","on","add","delete"],"mappings":";;;;+BAQsBA;;;eAAAA;;;;gEARH;;;;;;;gEACU;;;;;;;gEACZ;;;;;;;gEAEO;;;;;;6DAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEd,eAAeA,oCAAoC,EACxDC,cAAc,EACdC,MAAM,KAAK,EAIZ;IACC,MAAMC,SAAS;IACf,MAAMC,WAAW;IACjB,MAAMC,OAAO;IAEb,MAAMC,oBAAoB,CAACC,MAAcL;QACvC,MAAMM,SAASC,sBAAW,CAACC,SAAS,CAAC;YACnCC,iBAAiB;YACjBC,kBAAkB,GAAGT,OAAO,GAAG,EAAEC,SAAS,CAAC,EAAEG,OAAOF,MAAM;QAC5D;QACA,OAAO,GAAGJ,iBAAiBC,MAAM,eAAe,SAAS,CAAC,EAAEM,QAAQ;IACtE;IAEA,mCAAmC;IACnC,MAAMK,kBAAkB;QACtB,OAAO,IAAIC,QAAgB,OAAOC,SAASC;YACzC,MAAMC,cAAc,IAAIC;YAExB,MAAMC,SAASC,eAAI,CAACC,YAAY,CAC9B,CAACC,SAA+BC;gBAC9B,MAAMC,qBAAqB,CAACC;oBAC1B,MAAMC,cAAc,GAAGzB,eAAe,uBAAuB,EAAEwB,QAAQ;oBACvEF,SAASI,SAAS,CAAC,KAAK;wBAAEC,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
browserLoginAsync: function() {
|
|
16
|
+
return browserLoginAsync;
|
|
17
|
+
},
|
|
15
18
|
getActorDisplayName: function() {
|
|
16
19
|
return getActorDisplayName;
|
|
17
20
|
},
|
|
@@ -23,9 +26,6 @@ _export(exports, {
|
|
|
23
26
|
},
|
|
24
27
|
logoutAsync: function() {
|
|
25
28
|
return logoutAsync;
|
|
26
|
-
},
|
|
27
|
-
ssoLoginAsync: function() {
|
|
28
|
-
return ssoLoginAsync;
|
|
29
29
|
}
|
|
30
30
|
});
|
|
31
31
|
function _fs() {
|
|
@@ -124,9 +124,10 @@ async function loginAsync(credentials) {
|
|
|
124
124
|
currentConnection: 'Username-Password-Authentication'
|
|
125
125
|
});
|
|
126
126
|
}
|
|
127
|
-
async function
|
|
127
|
+
async function browserLoginAsync({ sso = false }) {
|
|
128
128
|
const sessionSecret = await (0, _expoSsoLauncher.getSessionUsingBrowserAuthFlowAsync)({
|
|
129
|
-
expoWebsiteUrl: (0, _endpoint.getExpoWebsiteBaseUrl)()
|
|
129
|
+
expoWebsiteUrl: (0, _endpoint.getExpoWebsiteBaseUrl)(),
|
|
130
|
+
sso
|
|
130
131
|
});
|
|
131
132
|
const userData = await _UserQuery.UserQuery.meUserActorAsync({
|
|
132
133
|
'expo-session': sessionSecret
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/api/user/user.ts"],"sourcesContent":["import { promises as fs } from 'fs';\n\nimport { getAccessToken, getSession, setSessionAsync } from './UserSettings';\nimport { getSessionUsingBrowserAuthFlowAsync } from './expoSsoLauncher';\nimport * as Log from '../../log';\nimport { getDevelopmentCodeSigningDirectory } from '../../utils/codesigning';\nimport { env } from '../../utils/env';\nimport { getExpoWebsiteBaseUrl } from '../endpoint';\nimport { UserQuery, type Actor } from '../graphql/queries/UserQuery';\nimport { fetchAsync } from '../rest/client';\n\nlet currentUser: Actor | undefined;\n\nexport const ANONYMOUS_USERNAME = 'anonymous';\n\n/**\n * Resolve the name of the actor, either normal user or robot user.\n * This should be used whenever the \"current user\" needs to be displayed.\n * The display name CANNOT be used as project owner.\n */\nexport function getActorDisplayName(user?: Actor): string {\n switch (user?.__typename) {\n case 'User':\n return user.username;\n case 'SSOUser':\n return user.username;\n case 'Robot':\n return user.firstName ? `${user.firstName} (robot)` : 'robot';\n default:\n return ANONYMOUS_USERNAME;\n }\n}\n\nexport type { Actor };\n\nexport async function getUserAsync(): Promise<Actor | undefined> {\n const hasCredentials = getAccessToken() || getSession()?.sessionSecret;\n if (!env.EXPO_OFFLINE && !currentUser && hasCredentials) {\n const user = await UserQuery.currentUserAsync();\n currentUser = user ?? undefined;\n }\n return currentUser;\n}\n\nexport async function loginAsync(credentials: {\n username: string;\n password: string;\n otp?: string;\n}): Promise<void> {\n const res = await fetchAsync('auth/loginAsync', {\n method: 'POST',\n body: JSON.stringify(credentials),\n });\n const json: any = await res.json();\n const sessionSecret = json.data.sessionSecret;\n\n const userData = await UserQuery.meUserActorAsync({\n 'expo-session': sessionSecret,\n });\n\n await setSessionAsync({\n sessionSecret,\n userId: userData.id,\n username: userData.username,\n currentConnection: 'Username-Password-Authentication',\n });\n}\n\nexport async function
|
|
1
|
+
{"version":3,"sources":["../../../../src/api/user/user.ts"],"sourcesContent":["import { promises as fs } from 'fs';\n\nimport { getAccessToken, getSession, setSessionAsync } from './UserSettings';\nimport { getSessionUsingBrowserAuthFlowAsync } from './expoSsoLauncher';\nimport * as Log from '../../log';\nimport { getDevelopmentCodeSigningDirectory } from '../../utils/codesigning';\nimport { env } from '../../utils/env';\nimport { getExpoWebsiteBaseUrl } from '../endpoint';\nimport { UserQuery, type Actor } from '../graphql/queries/UserQuery';\nimport { fetchAsync } from '../rest/client';\n\nlet currentUser: Actor | undefined;\n\nexport const ANONYMOUS_USERNAME = 'anonymous';\n\n/**\n * Resolve the name of the actor, either normal user or robot user.\n * This should be used whenever the \"current user\" needs to be displayed.\n * The display name CANNOT be used as project owner.\n */\nexport function getActorDisplayName(user?: Actor): string {\n switch (user?.__typename) {\n case 'User':\n return user.username;\n case 'SSOUser':\n return user.username;\n case 'Robot':\n return user.firstName ? `${user.firstName} (robot)` : 'robot';\n default:\n return ANONYMOUS_USERNAME;\n }\n}\n\nexport type { Actor };\n\nexport async function getUserAsync(): Promise<Actor | undefined> {\n const hasCredentials = getAccessToken() || getSession()?.sessionSecret;\n if (!env.EXPO_OFFLINE && !currentUser && hasCredentials) {\n const user = await UserQuery.currentUserAsync();\n currentUser = user ?? undefined;\n }\n return currentUser;\n}\n\nexport async function loginAsync(credentials: {\n username: string;\n password: string;\n otp?: string;\n}): Promise<void> {\n const res = await fetchAsync('auth/loginAsync', {\n method: 'POST',\n body: JSON.stringify(credentials),\n });\n const json: any = await res.json();\n const sessionSecret = json.data.sessionSecret;\n\n const userData = await UserQuery.meUserActorAsync({\n 'expo-session': sessionSecret,\n });\n\n await setSessionAsync({\n sessionSecret,\n userId: userData.id,\n username: userData.username,\n currentConnection: 'Username-Password-Authentication',\n });\n}\n\nexport async function browserLoginAsync({ sso = false }): Promise<void> {\n const sessionSecret = await getSessionUsingBrowserAuthFlowAsync({\n expoWebsiteUrl: getExpoWebsiteBaseUrl(),\n sso,\n });\n const userData = await UserQuery.meUserActorAsync({\n 'expo-session': sessionSecret,\n });\n await setSessionAsync({\n sessionSecret,\n userId: userData.id,\n username: userData.username,\n currentConnection: 'Browser-Flow-Authentication',\n });\n}\n\nexport async function logoutAsync(): Promise<void> {\n currentUser = undefined;\n await Promise.all([\n fs.rm(getDevelopmentCodeSigningDirectory(), { recursive: true, force: true }),\n setSessionAsync(undefined),\n ]);\n Log.log('Logged out');\n}\n"],"names":["ANONYMOUS_USERNAME","browserLoginAsync","getActorDisplayName","getUserAsync","loginAsync","logoutAsync","currentUser","user","__typename","username","firstName","getSession","hasCredentials","getAccessToken","sessionSecret","env","EXPO_OFFLINE","UserQuery","currentUserAsync","undefined","credentials","res","fetchAsync","method","body","JSON","stringify","json","data","userData","meUserActorAsync","setSessionAsync","userId","id","currentConnection","sso","getSessionUsingBrowserAuthFlowAsync","expoWebsiteUrl","getExpoWebsiteBaseUrl","Promise","all","fs","rm","getDevelopmentCodeSigningDirectory","recursive","force","Log","log"],"mappings":";;;;;;;;;;;IAaaA,kBAAkB;eAAlBA;;IAuDSC,iBAAiB;eAAjBA;;IAhDNC,mBAAmB;eAAnBA;;IAeMC,YAAY;eAAZA;;IASAC,UAAU;eAAVA;;IAwCAC,WAAW;eAAXA;;;;yBApFS;;;;;;8BAE6B;iCACR;6DAC/B;6BAC8B;qBAC/B;0BACkB;2BACA;wBACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE3B,IAAIC;AAEG,MAAMN,qBAAqB;AAO3B,SAASE,oBAAoBK,IAAY;IAC9C,OAAQA,wBAAAA,KAAMC,UAAU;QACtB,KAAK;YACH,OAAOD,KAAKE,QAAQ;QACtB,KAAK;YACH,OAAOF,KAAKE,QAAQ;QACtB,KAAK;YACH,OAAOF,KAAKG,SAAS,GAAG,GAAGH,KAAKG,SAAS,CAAC,QAAQ,CAAC,GAAG;QACxD;YACE,OAAOV;IACX;AACF;AAIO,eAAeG;QACuBQ;IAA3C,MAAMC,iBAAiBC,IAAAA,4BAAc,SAAMF,cAAAA,IAAAA,wBAAU,wBAAVA,YAAcG,aAAa;IACtE,IAAI,CAACC,QAAG,CAACC,YAAY,IAAI,CAACV,eAAeM,gBAAgB;QACvD,MAAML,OAAO,MAAMU,oBAAS,CAACC,gBAAgB;QAC7CZ,cAAcC,QAAQY;IACxB;IACA,OAAOb;AACT;AAEO,eAAeF,WAAWgB,WAIhC;IACC,MAAMC,MAAM,MAAMC,IAAAA,kBAAU,EAAC,mBAAmB;QAC9CC,QAAQ;QACRC,MAAMC,KAAKC,SAAS,CAACN;IACvB;IACA,MAAMO,OAAY,MAAMN,IAAIM,IAAI;IAChC,MAAMb,gBAAgBa,KAAKC,IAAI,CAACd,aAAa;IAE7C,MAAMe,WAAW,MAAMZ,oBAAS,CAACa,gBAAgB,CAAC;QAChD,gBAAgBhB;IAClB;IAEA,MAAMiB,IAAAA,6BAAe,EAAC;QACpBjB;QACAkB,QAAQH,SAASI,EAAE;QACnBxB,UAAUoB,SAASpB,QAAQ;QAC3ByB,mBAAmB;IACrB;AACF;AAEO,eAAejC,kBAAkB,EAAEkC,MAAM,KAAK,EAAE;IACrD,MAAMrB,gBAAgB,MAAMsB,IAAAA,oDAAmC,EAAC;QAC9DC,gBAAgBC,IAAAA,+BAAqB;QACrCH;IACF;IACA,MAAMN,WAAW,MAAMZ,oBAAS,CAACa,gBAAgB,CAAC;QAChD,gBAAgBhB;IAClB;IACA,MAAMiB,IAAAA,6BAAe,EAAC;QACpBjB;QACAkB,QAAQH,SAASI,EAAE;QACnBxB,UAAUoB,SAASpB,QAAQ;QAC3ByB,mBAAmB;IACrB;AACF;AAEO,eAAe7B;IACpBC,cAAca;IACd,MAAMoB,QAAQC,GAAG,CAAC;QAChBC,cAAE,CAACC,EAAE,CAACC,IAAAA,+CAAkC,KAAI;YAAEC,WAAW;YAAMC,OAAO;QAAK;QAC3Ed,IAAAA,6BAAe,EAACZ;KACjB;IACD2B,KAAIC,GAAG,CAAC;AACV"}
|
package/build/src/login/index.js
CHANGED
|
@@ -60,11 +60,13 @@ const expoLogin = async (argv)=>{
|
|
|
60
60
|
'--password': String,
|
|
61
61
|
'--otp': String,
|
|
62
62
|
'--sso': Boolean,
|
|
63
|
+
'--browser': Boolean,
|
|
63
64
|
// Aliases
|
|
64
65
|
'-h': '--help',
|
|
65
66
|
'-u': '--username',
|
|
66
67
|
'-p': '--password',
|
|
67
|
-
'-s': '--sso'
|
|
68
|
+
'-s': '--sso',
|
|
69
|
+
'-b': '--browser'
|
|
68
70
|
}, argv);
|
|
69
71
|
if (args['--help']) {
|
|
70
72
|
(0, _args.printHelp)(`Log in to an Expo account`, `npx expo login`, [
|
|
@@ -72,6 +74,7 @@ const expoLogin = async (argv)=>{
|
|
|
72
74
|
`-p, --password <string> Password`,
|
|
73
75
|
`--otp <string> One-time password from your 2FA device`,
|
|
74
76
|
`-s, --sso Log in with SSO`,
|
|
77
|
+
`-b, --browser Log in with a browser`,
|
|
75
78
|
`-h, --help Usage info`
|
|
76
79
|
].join('\n'));
|
|
77
80
|
}
|
|
@@ -81,7 +84,8 @@ const expoLogin = async (argv)=>{
|
|
|
81
84
|
username: args['--username'],
|
|
82
85
|
password: args['--password'],
|
|
83
86
|
otp: args['--otp'],
|
|
84
|
-
sso: !!args['--sso']
|
|
87
|
+
sso: !!args['--sso'],
|
|
88
|
+
browser: !!args['--browser']
|
|
85
89
|
}).catch(_errors.logCmdError);
|
|
86
90
|
};
|
|
87
91
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/login/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from '../../bin/cli';\nimport { assertArgs, printHelp } from '../utils/args';\nimport { logCmdError } from '../utils/errors';\n\nexport const expoLogin: Command = async (argv) => {\n const args = assertArgs(\n {\n // Types\n '--help': Boolean,\n '--username': String,\n '--password': String,\n '--otp': String,\n '--sso': Boolean,\n // Aliases\n '-h': '--help',\n '-u': '--username',\n '-p': '--password',\n '-s': '--sso',\n },\n argv\n );\n\n if (args['--help']) {\n printHelp(\n `Log in to an Expo account`,\n `npx expo login`,\n [\n `-u, --username <string> Username`,\n `-p, --password <string> Password`,\n `--otp <string> One-time password from your 2FA device`,\n `-s, --sso Log in with SSO`,\n `-h, --help Usage info`,\n ].join('\\n')\n );\n }\n\n const { showLoginPromptAsync } = await import('../api/user/actions.js');\n return showLoginPromptAsync({\n // Parsed options\n username: args['--username'],\n password: args['--password'],\n otp: args['--otp'],\n sso: !!args['--sso'],\n }).catch(logCmdError);\n};\n"],"names":["expoLogin","argv","args","assertArgs","Boolean","String","printHelp","join","showLoginPromptAsync","username","password","otp","sso","catch","logCmdError"],"mappings":";;;;;+BAKaA;;;eAAAA;;;sBAHyB;wBACV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErB,MAAMA,YAAqB,OAAOC;IACvC,MAAMC,OAAOC,IAAAA,gBAAU,EACrB;QACE,QAAQ;QACR,UAAUC;QACV,cAAcC;QACd,cAAcA;QACd,SAASA;QACT,SAASD;QACT,UAAU;QACV,MAAM;QACN,MAAM;QACN,MAAM;QACN,MAAM;IACR,GACAH;IAGF,IAAIC,IAAI,CAAC,SAAS,EAAE;QAClBI,IAAAA,eAAS,EACP,CAAC,yBAAyB,CAAC,EAC3B,CAAC,cAAc,CAAC,EAChB;YACE,CAAC,iCAAiC,CAAC;YACnC,CAAC,iCAAiC,CAAC;YACnC,CAAC,+DAA+D,CAAC;YACjE,CAAC,wCAAwC,CAAC;YAC1C,CAAC,mCAAmC,CAAC;SACtC,CAACC,IAAI,CAAC;IAEX;IAEA,MAAM,EAAEC,oBAAoB,EAAE,GAAG,MAAM,mEAAA,QAAO;IAC9C,OAAOA,qBAAqB;QAC1B,iBAAiB;QACjBC,UAAUP,IAAI,CAAC,aAAa;QAC5BQ,UAAUR,IAAI,CAAC,aAAa;QAC5BS,KAAKT,IAAI,CAAC,QAAQ;QAClBU,KAAK,CAAC,CAACV,IAAI,CAAC,QAAQ;
|
|
1
|
+
{"version":3,"sources":["../../../src/login/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from '../../bin/cli';\nimport { assertArgs, printHelp } from '../utils/args';\nimport { logCmdError } from '../utils/errors';\n\nexport const expoLogin: Command = async (argv) => {\n const args = assertArgs(\n {\n // Types\n '--help': Boolean,\n '--username': String,\n '--password': String,\n '--otp': String,\n '--sso': Boolean,\n '--browser': Boolean,\n // Aliases\n '-h': '--help',\n '-u': '--username',\n '-p': '--password',\n '-s': '--sso',\n '-b': '--browser',\n },\n argv\n );\n\n if (args['--help']) {\n printHelp(\n `Log in to an Expo account`,\n `npx expo login`,\n [\n `-u, --username <string> Username`,\n `-p, --password <string> Password`,\n `--otp <string> One-time password from your 2FA device`,\n `-s, --sso Log in with SSO`,\n `-b, --browser Log in with a browser`,\n `-h, --help Usage info`,\n ].join('\\n')\n );\n }\n\n const { showLoginPromptAsync } = await import('../api/user/actions.js');\n return showLoginPromptAsync({\n // Parsed options\n username: args['--username'],\n password: args['--password'],\n otp: args['--otp'],\n sso: !!args['--sso'],\n browser: !!args['--browser'],\n }).catch(logCmdError);\n};\n"],"names":["expoLogin","argv","args","assertArgs","Boolean","String","printHelp","join","showLoginPromptAsync","username","password","otp","sso","browser","catch","logCmdError"],"mappings":";;;;;+BAKaA;;;eAAAA;;;sBAHyB;wBACV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErB,MAAMA,YAAqB,OAAOC;IACvC,MAAMC,OAAOC,IAAAA,gBAAU,EACrB;QACE,QAAQ;QACR,UAAUC;QACV,cAAcC;QACd,cAAcA;QACd,SAASA;QACT,SAASD;QACT,aAAaA;QACb,UAAU;QACV,MAAM;QACN,MAAM;QACN,MAAM;QACN,MAAM;QACN,MAAM;IACR,GACAH;IAGF,IAAIC,IAAI,CAAC,SAAS,EAAE;QAClBI,IAAAA,eAAS,EACP,CAAC,yBAAyB,CAAC,EAC3B,CAAC,cAAc,CAAC,EAChB;YACE,CAAC,iCAAiC,CAAC;YACnC,CAAC,iCAAiC,CAAC;YACnC,CAAC,+DAA+D,CAAC;YACjE,CAAC,wCAAwC,CAAC;YAC1C,CAAC,8CAA8C,CAAC;YAChD,CAAC,mCAAmC,CAAC;SACtC,CAACC,IAAI,CAAC;IAEX;IAEA,MAAM,EAAEC,oBAAoB,EAAE,GAAG,MAAM,mEAAA,QAAO;IAC9C,OAAOA,qBAAqB;QAC1B,iBAAiB;QACjBC,UAAUP,IAAI,CAAC,aAAa;QAC5BQ,UAAUR,IAAI,CAAC,aAAa;QAC5BS,KAAKT,IAAI,CAAC,QAAQ;QAClBU,KAAK,CAAC,CAACV,IAAI,CAAC,QAAQ;QACpBW,SAAS,CAAC,CAACX,IAAI,CAAC,YAAY;IAC9B,GAAGY,KAAK,CAACC,mBAAW;AACtB"}
|
|
@@ -183,7 +183,10 @@ async function getConnectedAppleDevicesAsync() {
|
|
|
183
183
|
]);
|
|
184
184
|
debug(devices.stdout);
|
|
185
185
|
const devicesJson = await _jsonfile().default.readAsync(tmpPath);
|
|
186
|
-
if (
|
|
186
|
+
if (![
|
|
187
|
+
2,
|
|
188
|
+
3
|
|
189
|
+
].includes(devicesJson == null ? void 0 : (_devicesJson_info = devicesJson.info) == null ? void 0 : _devicesJson_info.jsonVersion)) {
|
|
187
190
|
_log.warn('Unexpected devicectl JSON version output from devicectl. Connecting to physical Apple devices may not work as expected.');
|
|
188
191
|
}
|
|
189
192
|
assertDevicesJson(devicesJson);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/platforms/ios/devicectl.ts"],"sourcesContent":["/**\n * Copyright © 2024 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport JsonFile from '@expo/json-file';\nimport spawnAsync, { SpawnOptions, SpawnResult } from '@expo/spawn-async';\nimport chalk from 'chalk';\nimport { spawn, execSync } from 'child_process';\nimport fs from 'fs';\nimport assert from 'node:assert';\nimport { Ora } from 'ora';\nimport { EOL } from 'os';\nimport path from 'path';\n\nimport { xcrunAsync } from './xcrun';\nimport { getExpoHomeDirectory } from '../../../api/user/UserSettings';\nimport * as Log from '../../../log';\nimport { createTempFilePath } from '../../../utils/createTempPath';\nimport { CommandError } from '../../../utils/errors';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { ora } from '../../../utils/ora';\nimport { confirmAsync } from '../../../utils/prompts';\n\nconst DEVICE_CTL_EXISTS_PATH = path.join(getExpoHomeDirectory(), 'devicectl-exists');\n\nconst debug = require('debug')('expo:devicectl') as typeof console.log;\n\ntype AnyEnum<T extends string = string> = T | (string & object);\n\ntype DeviceCtlDevice = {\n capabilities: DeviceCtlDeviceCapability[];\n connectionProperties: DeviceCtlConnectionProperties;\n deviceProperties: DeviceCtlDeviceProperties;\n hardwareProperties: DeviceCtlHardwareProperties;\n /** \"A1A1AAA1-0011-1AA1-11A1-10A1111AA11A\" */\n identifier: string;\n visibilityClass: AnyEnum<'default'>;\n};\n\ntype DeviceCtlHardwareProperties = {\n cpuType: DeviceCtlCpuType;\n deviceType: AnyEnum<'iPhone'>;\n /** 1114404411111111 */\n ecid: number;\n /** \"D74AP\" */\n hardwareModel: string;\n /** 512000000000 */\n internalStorageCapacity: number;\n /** true */\n isProductionFused: boolean;\n /** \"iPhone 14 Pro Max\" */\n marketingName: string;\n /** \"iOS\" */\n platform: AnyEnum<'iOS' | 'xrOS'>;\n /** \"iPhone15,3\" */\n productType: AnyEnum<'iPhone13,4' | 'iPhone15,3'>;\n reality: AnyEnum<'physical'>;\n /** \"X2X1CC1XXX\" */\n serialNumber: string;\n supportedCPUTypes: DeviceCtlCpuType[];\n /** [1] */\n supportedDeviceFamilies: number[];\n thinningProductType: AnyEnum<'iPhone15,3'>;\n /** \"00001110-001111110110101A\" */\n udid: string;\n};\n\ntype DeviceCtlDeviceProperties = {\n /** true */\n bootedFromSnapshot: boolean;\n /** \"com.apple.os.update-AD0CF111ACFF11A11111A76A3D1262AE42A3F56F305AF5AE1135393A7A14A7D1\" */\n bootedSnapshotName: string;\n /** false */\n ddiServicesAvailable: boolean;\n\n developerModeStatus: AnyEnum<'enabled'>;\n /** false */\n hasInternalOSBuild: boolean;\n /** \"Evan's phone\" */\n name: string;\n /** \"21E236\" */\n osBuildUpdate: string;\n /** \"17.4.1\" */\n osVersionNumber: string;\n /** false */\n rootFileSystemIsWritable: boolean;\n};\n\ntype DeviceCtlDeviceCapability =\n | {\n name: AnyEnum;\n featureIdentifier: AnyEnum;\n }\n | {\n featureIdentifier: 'com.apple.coredevice.feature.connectdevice';\n name: 'Connect to Device';\n }\n | {\n featureIdentifier: 'com.apple.coredevice.feature.unpairdevice';\n name: 'Unpair Device';\n }\n | {\n featureIdentifier: 'com.apple.coredevice.feature.acquireusageassertion';\n name: 'Acquire Usage Assertion';\n };\n\ntype DeviceCtlConnectionProperties = {\n authenticationType: AnyEnum<'manualPairing'>;\n isMobileDeviceOnly: boolean;\n /** \"2024-04-20T22:50:04.244Z\" */\n lastConnectionDate: string;\n pairingState: AnyEnum<'paired'>;\n /** [\"00001111-001111110110101A.coredevice.local\", \"A1A1AAA1-0011-1AA1-11A1-10A1111AA11A.coredevice.local\"] */\n potentialHostnames: string[];\n transportType: AnyEnum<'localNetwork' | 'wired'>;\n tunnelState: AnyEnum<'disconnected' | 'unavailable'>;\n tunnelTransportProtocol: AnyEnum<'tcp'>;\n};\n\ntype DeviceCtlCpuType = {\n name: AnyEnum<'arm64e' | 'arm64' | 'arm64_32'>;\n subType: number;\n /** 16777228 */\n type: number;\n};\n\n/** Run a `devicectl` command. */\nexport async function devicectlAsync(\n args: (string | undefined)[],\n options?: SpawnOptions\n): Promise<SpawnResult> {\n try {\n return await xcrunAsync(['devicectl', ...args], options);\n } catch (error: any) {\n if (error instanceof CommandError) {\n throw error;\n }\n if ('stderr' in error) {\n const errorCodes = getDeviceCtlErrorCodes(error.stderr);\n if (errorCodes.includes('Locked')) {\n throw new CommandError('APPLE_DEVICE_LOCKED', 'Device is locked, unlock and try again.');\n }\n }\n throw error;\n }\n}\n\nexport async function getConnectedAppleDevicesAsync() {\n if (!hasDevicectlEverBeenInstalled()) {\n debug('devicectl not found, skipping remote Apple devices.');\n return [];\n }\n\n const tmpPath = createTempFilePath();\n const devices = await devicectlAsync([\n 'list',\n 'devices',\n '--json-output',\n tmpPath,\n // Give two seconds before timing out: between 5 and 9223372036854775807\n '--timeout',\n '5',\n ]);\n debug(devices.stdout);\n const devicesJson = await JsonFile.readAsync(tmpPath);\n\n if ((devicesJson as any)?.info?.jsonVersion !== 2) {\n Log.warn(\n 'Unexpected devicectl JSON version output from devicectl. Connecting to physical Apple devices may not work as expected.'\n );\n }\n\n assertDevicesJson(devicesJson);\n\n return devicesJson.result.devices as DeviceCtlDevice[];\n}\n\nfunction assertDevicesJson(\n results: any\n): asserts results is { result: { devices: DeviceCtlDevice[] } } {\n assert(\n results != null && 'result' in results && Array.isArray(results?.result?.devices),\n 'Malformed JSON output from devicectl: ' + JSON.stringify(results, null, 2)\n );\n}\n\nexport async function launchBinaryOnMacAsync(\n bundleId: string,\n appBinaryPath: string\n): Promise<void> {\n const args = ['-b', bundleId, appBinaryPath];\n try {\n await spawnAsync('open', args);\n } catch (error: any) {\n if ('code' in error) {\n if (error.code === 1) {\n throw new CommandError(\n 'MACOS_LAUNCH',\n 'Failed to launch the compatible binary on macOS: open ' +\n args.join(' ') +\n '\\n\\n' +\n error.message\n );\n }\n }\n throw error;\n }\n}\n\nasync function installAppWithDeviceCtlAsync(\n uuid: string,\n bundleIdOrAppPath: string,\n onProgress: (event: { status: string; isComplete: boolean; progress: number }) => void\n): Promise<void> {\n // 𝝠 xcrun devicectl device install app --device 00001110-001111110110101A /Users/evanbacon/Library/Developer/Xcode/DerivedData/Router-hgbqaxzhrhkiftfweydvhgttadvn/Build/Products/Debug-iphoneos/Router.app --verbose\n return new Promise((resolve, reject) => {\n const args: string[] = [\n 'devicectl',\n 'device',\n 'install',\n 'app',\n '--device',\n uuid,\n bundleIdOrAppPath,\n ];\n const childProcess = spawn('xcrun', args);\n debug('xcrun ' + args.join(' '));\n\n let currentProgress = 0;\n let hasStarted = false;\n\n function updateProgress(progress: number) {\n hasStarted = true;\n if (progress <= currentProgress) {\n return;\n }\n currentProgress = progress;\n onProgress({\n progress,\n isComplete: progress === 100,\n status: 'Installing',\n });\n }\n\n childProcess.stdout.on('data', (data: Buffer) => {\n // Sometimes more than one chunk comes at a time, here we split by system newline,\n // then trim and filter.\n const strings = data\n .toString()\n .split(EOL)\n .map((value) => value.trim());\n\n strings.forEach((str) => {\n // Match the progress percentage:\n // - '34%... 35%...' -> 34\n // - '31%...' -> 31\n // - 'Complete!' -> 100\n\n const match = str.match(/(\\d+)%\\.\\.\\./);\n if (match) {\n updateProgress(parseInt(match[1], 10));\n } else if (hasStarted) {\n updateProgress(100);\n }\n });\n\n debug('[stdout]:', strings);\n });\n\n childProcess.on('close', (code) => {\n debug('[close]: ' + code);\n if (code === 0) {\n resolve();\n } else {\n const stderr = childProcess.stderr.read();\n const err = new Error(stderr);\n (err as any).code = code;\n detach(err);\n }\n });\n\n const detach = async (err?: Error) => {\n off?.();\n if (childProcess) {\n return new Promise<void>((resolve) => {\n childProcess?.on('close', resolve);\n childProcess?.kill();\n // childProcess = null;\n reject(err ?? new CommandError('detached'));\n });\n }\n };\n\n const off = installExitHooks(() => detach());\n });\n}\n\nexport async function launchAppWithDeviceCtl(deviceId: string, bundleId: string) {\n await devicectlAsync(['device', 'process', 'launch', '--device', deviceId, bundleId]);\n}\n\n/** Find all error codes from the output log */\nfunction getDeviceCtlErrorCodes(log: string): string[] {\n return [...log.matchAll(/BSErrorCodeDescription\\s+=\\s+(.*)$/gim)].map(([_line, code]) => code);\n}\n\nlet hasEverBeenInstalled: boolean | undefined;\n\nexport function hasDevicectlEverBeenInstalled() {\n if (hasEverBeenInstalled) return hasEverBeenInstalled;\n // It doesn't appear possible for devicectl to ever be uninstalled. We can just check once and store this result forever\n // to prevent cold boots of devicectl from slowing down all invocations of `expo run ios`\n if (fs.existsSync(DEVICE_CTL_EXISTS_PATH)) {\n hasEverBeenInstalled = true;\n return true;\n }\n\n const isInstalled = isDevicectlInstalled();\n\n if (isInstalled) {\n fs.writeFileSync(DEVICE_CTL_EXISTS_PATH, '1');\n }\n hasEverBeenInstalled = isInstalled;\n return isInstalled;\n}\n\nfunction isDevicectlInstalled() {\n try {\n execSync('xcrun devicectl --version', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Wraps the apple device method for installing and running an app,\n * adds indicator and retry loop for when the device is locked.\n */\nexport async function installAndLaunchAppAsync(props: {\n bundle: string;\n bundleIdentifier: string;\n udid: string;\n deviceName: string;\n}): Promise<void> {\n debug('Running on device:', props);\n const { bundle, bundleIdentifier, udid, deviceName } = props;\n let indicator: Ora | undefined;\n\n try {\n if (!indicator) {\n indicator = ora(`Connecting to: ${props.deviceName}`).start();\n }\n\n await installAppWithDeviceCtlAsync(\n udid,\n bundle,\n ({\n status,\n isComplete,\n progress,\n }: {\n status: string;\n isComplete: boolean;\n progress: number;\n }) => {\n if (!indicator) {\n indicator = ora(status).start();\n }\n indicator.text = `${chalk.bold(status)} ${progress}%`;\n if (isComplete) {\n indicator.succeed();\n }\n }\n );\n } catch (error: any) {\n if (indicator) {\n indicator.fail();\n }\n throw error;\n }\n\n async function launchAppOptionally() {\n try {\n await launchAppWithDeviceCtl(udid, bundleIdentifier);\n } catch (error: any) {\n if (indicator) {\n indicator.fail();\n }\n if (error.code === 'APPLE_DEVICE_LOCKED') {\n // Get the app name from the binary path.\n const appName = path.basename(bundle).split('.')[0] ?? 'app';\n if (\n isInteractive() &&\n (await confirmAsync({\n message: `Cannot launch ${appName} because the device is locked. Unlock ${deviceName} to continue...`,\n initial: true,\n }))\n ) {\n return launchAppOptionally();\n }\n throw new CommandError(\n `Cannot launch ${appName} on ${deviceName} because the device is locked.`\n );\n }\n throw error;\n }\n }\n\n await launchAppOptionally();\n}\n"],"names":["devicectlAsync","getConnectedAppleDevicesAsync","hasDevicectlEverBeenInstalled","installAndLaunchAppAsync","launchAppWithDeviceCtl","launchBinaryOnMacAsync","DEVICE_CTL_EXISTS_PATH","path","join","getExpoHomeDirectory","debug","require","args","options","xcrunAsync","error","CommandError","errorCodes","getDeviceCtlErrorCodes","stderr","includes","tmpPath","createTempFilePath","devices","stdout","devicesJson","JsonFile","readAsync","info","jsonVersion","Log","warn","assertDevicesJson","result","results","assert","Array","isArray","JSON","stringify","bundleId","appBinaryPath","spawnAsync","code","message","installAppWithDeviceCtlAsync","uuid","bundleIdOrAppPath","onProgress","Promise","resolve","reject","childProcess","spawn","currentProgress","hasStarted","updateProgress","progress","isComplete","status","on","data","strings","toString","split","EOL","map","value","trim","forEach","str","match","parseInt","read","err","Error","detach","off","kill","installExitHooks","deviceId","log","matchAll","_line","hasEverBeenInstalled","fs","existsSync","isInstalled","isDevicectlInstalled","writeFileSync","execSync","stdio","props","bundle","bundleIdentifier","udid","deviceName","indicator","ora","start","text","chalk","bold","succeed","fail","launchAppOptionally","appName","basename","isInteractive","confirmAsync","initial"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IA8HqBA,cAAc;eAAdA;;IAoBAC,6BAA6B;eAA7BA;;IAiKNC,6BAA6B;eAA7BA;;IA+BMC,wBAAwB;eAAxBA;;IA1CAC,sBAAsB;eAAtBA;;IA/GAC,sBAAsB;eAAtBA;;;;gEAvLD;;;;;;;gEACiC;;;;;;;gEACpC;;;;;;;yBACc;;;;;;;gEACjB;;;;;;;gEACI;;;;;;;yBAEC;;;;;;;gEACH;;;;;;uBAEU;8BACU;6DAChB;gCACc;wBACN;sBACI;6BACH;qBACV;yBACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE7B,MAAMC,yBAAyBC,eAAI,CAACC,IAAI,CAACC,IAAAA,kCAAoB,KAAI;AAEjE,MAAMC,QAAQC,QAAQ,SAAS;AAsGxB,eAAeX,eACpBY,IAA4B,EAC5BC,OAAsB;IAEtB,IAAI;QACF,OAAO,MAAMC,IAAAA,iBAAU,EAAC;YAAC;eAAgBF;SAAK,EAAEC;IAClD,EAAE,OAAOE,OAAY;QACnB,IAAIA,iBAAiBC,oBAAY,EAAE;YACjC,MAAMD;QACR;QACA,IAAI,YAAYA,OAAO;YACrB,MAAME,aAAaC,uBAAuBH,MAAMI,MAAM;YACtD,IAAIF,WAAWG,QAAQ,CAAC,WAAW;gBACjC,MAAM,IAAIJ,oBAAY,CAAC,uBAAuB;YAChD;QACF;QACA,MAAMD;IACR;AACF;AAEO,eAAed;QAmBhB;IAlBJ,IAAI,CAACC,iCAAiC;QACpCQ,MAAM;QACN,OAAO,EAAE;IACX;IAEA,MAAMW,UAAUC,IAAAA,kCA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UAAUM,OAAO;YACnB;QACF;IAEJ,EAAE,OAAOxF,OAAY;QACnB,IAAIkF,WAAW;YACbA,UAAUO,IAAI;QAChB;QACA,MAAMzF;IACR;IAEA,eAAe0F;QACb,IAAI;YACF,MAAMrG,uBAAuB2F,MAAMD;QACrC,EAAE,OAAO/E,OAAY;YACnB,IAAIkF,WAAW;gBACbA,UAAUO,IAAI;YAChB;YACA,IAAIzF,MAAM4B,IAAI,KAAK,uBAAuB;gBACxC,yCAAyC;gBACzC,MAAM+D,UAAUnG,eAAI,CAACoG,QAAQ,CAACd,QAAQ7B,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI;gBACvD,IACE4C,IAAAA,0BAAa,OACZ,MAAMC,IAAAA,qBAAY,EAAC;oBAClBjE,SAAS,CAAC,cAAc,EAAE8D,QAAQ,sCAAsC,EAAEV,WAAW,eAAe,CAAC;oBACrGc,SAAS;gBACX,IACA;oBACA,OAAOL;gBACT;gBACA,MAAM,IAAIzF,oBAAY,CACpB,CAAC,cAAc,EAAE0F,QAAQ,IAAI,EAAEV,WAAW,8BAA8B,CAAC;YAE7E;YACA,MAAMjF;QACR;IACF;IAEA,MAAM0F;AACR"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/platforms/ios/devicectl.ts"],"sourcesContent":["/**\n * Copyright © 2024 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport JsonFile from '@expo/json-file';\nimport spawnAsync, { SpawnOptions, SpawnResult } from '@expo/spawn-async';\nimport chalk from 'chalk';\nimport { spawn, execSync } from 'child_process';\nimport fs from 'fs';\nimport assert from 'node:assert';\nimport { Ora } from 'ora';\nimport { EOL } from 'os';\nimport path from 'path';\n\nimport { xcrunAsync } from './xcrun';\nimport { getExpoHomeDirectory } from '../../../api/user/UserSettings';\nimport * as Log from '../../../log';\nimport { createTempFilePath } from '../../../utils/createTempPath';\nimport { CommandError } from '../../../utils/errors';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { ora } from '../../../utils/ora';\nimport { confirmAsync } from '../../../utils/prompts';\n\nconst DEVICE_CTL_EXISTS_PATH = path.join(getExpoHomeDirectory(), 'devicectl-exists');\n\nconst debug = require('debug')('expo:devicectl') as typeof console.log;\n\ntype AnyEnum<T extends string = string> = T | (string & object);\n\ntype DeviceCtlDevice = {\n capabilities: DeviceCtlDeviceCapability[];\n connectionProperties: DeviceCtlConnectionProperties;\n deviceProperties: DeviceCtlDeviceProperties;\n hardwareProperties: DeviceCtlHardwareProperties;\n /** \"A1A1AAA1-0011-1AA1-11A1-10A1111AA11A\" */\n identifier: string;\n visibilityClass: AnyEnum<'default'>;\n};\n\ntype DeviceCtlHardwareProperties = {\n cpuType: DeviceCtlCpuType;\n deviceType: AnyEnum<'iPhone'>;\n /** 1114404411111111 */\n ecid: number;\n /** \"D74AP\" */\n hardwareModel: string;\n /** 512000000000 */\n internalStorageCapacity: number;\n /** true */\n isProductionFused: boolean;\n /** \"iPhone 14 Pro Max\" */\n marketingName: string;\n /** \"iOS\" */\n platform: AnyEnum<'iOS' | 'xrOS'>;\n /** \"iPhone15,3\" */\n productType: AnyEnum<'iPhone13,4' | 'iPhone15,3'>;\n reality: AnyEnum<'physical'>;\n /** \"X2X1CC1XXX\" */\n serialNumber: string;\n supportedCPUTypes: DeviceCtlCpuType[];\n /** [1] */\n supportedDeviceFamilies: number[];\n thinningProductType: AnyEnum<'iPhone15,3'>;\n /** \"00001110-001111110110101A\" */\n udid: string;\n};\n\ntype DeviceCtlDeviceProperties = {\n /** true */\n bootedFromSnapshot: boolean;\n /** \"com.apple.os.update-AD0CF111ACFF11A11111A76A3D1262AE42A3F56F305AF5AE1135393A7A14A7D1\" */\n bootedSnapshotName: string;\n /** false */\n ddiServicesAvailable: boolean;\n\n developerModeStatus: AnyEnum<'enabled'>;\n /** false */\n hasInternalOSBuild: boolean;\n /** \"Evan's phone\" */\n name: string;\n /** \"21E236\" */\n osBuildUpdate: string;\n /** \"17.4.1\" */\n osVersionNumber: string;\n /** false */\n rootFileSystemIsWritable: boolean;\n};\n\ntype DeviceCtlDeviceCapability =\n | {\n name: AnyEnum;\n featureIdentifier: AnyEnum;\n }\n | {\n featureIdentifier: 'com.apple.coredevice.feature.connectdevice';\n name: 'Connect to Device';\n }\n | {\n featureIdentifier: 'com.apple.coredevice.feature.unpairdevice';\n name: 'Unpair Device';\n }\n | {\n featureIdentifier: 'com.apple.coredevice.feature.acquireusageassertion';\n name: 'Acquire Usage Assertion';\n };\n\ntype DeviceCtlConnectionProperties = {\n authenticationType: AnyEnum<'manualPairing'>;\n isMobileDeviceOnly: boolean;\n /** \"2024-04-20T22:50:04.244Z\" */\n lastConnectionDate: string;\n pairingState: AnyEnum<'paired'>;\n /** [\"00001111-001111110110101A.coredevice.local\", \"A1A1AAA1-0011-1AA1-11A1-10A1111AA11A.coredevice.local\"] */\n potentialHostnames: string[];\n transportType: AnyEnum<'localNetwork' | 'wired'>;\n tunnelState: AnyEnum<'disconnected' | 'unavailable'>;\n tunnelTransportProtocol: AnyEnum<'tcp'>;\n};\n\ntype DeviceCtlCpuType = {\n name: AnyEnum<'arm64e' | 'arm64' | 'arm64_32'>;\n subType: number;\n /** 16777228 */\n type: number;\n};\n\n/** Run a `devicectl` command. */\nexport async function devicectlAsync(\n args: (string | undefined)[],\n options?: SpawnOptions\n): Promise<SpawnResult> {\n try {\n return await xcrunAsync(['devicectl', ...args], options);\n } catch (error: any) {\n if (error instanceof CommandError) {\n throw error;\n }\n if ('stderr' in error) {\n const errorCodes = getDeviceCtlErrorCodes(error.stderr);\n if (errorCodes.includes('Locked')) {\n throw new CommandError('APPLE_DEVICE_LOCKED', 'Device is locked, unlock and try again.');\n }\n }\n throw error;\n }\n}\n\nexport async function getConnectedAppleDevicesAsync() {\n if (!hasDevicectlEverBeenInstalled()) {\n debug('devicectl not found, skipping remote Apple devices.');\n return [];\n }\n\n const tmpPath = createTempFilePath();\n const devices = await devicectlAsync([\n 'list',\n 'devices',\n '--json-output',\n tmpPath,\n // Give two seconds before timing out: between 5 and 9223372036854775807\n '--timeout',\n '5',\n ]);\n debug(devices.stdout);\n const devicesJson = await JsonFile.readAsync(tmpPath);\n\n if (![2, 3].includes((devicesJson as any)?.info?.jsonVersion)) {\n Log.warn(\n 'Unexpected devicectl JSON version output from devicectl. Connecting to physical Apple devices may not work as expected.'\n );\n }\n\n assertDevicesJson(devicesJson);\n\n return devicesJson.result.devices as DeviceCtlDevice[];\n}\n\nfunction assertDevicesJson(\n results: any\n): asserts results is { result: { devices: DeviceCtlDevice[] } } {\n assert(\n results != null && 'result' in results && Array.isArray(results?.result?.devices),\n 'Malformed JSON output from devicectl: ' + JSON.stringify(results, null, 2)\n );\n}\n\nexport async function launchBinaryOnMacAsync(\n bundleId: string,\n appBinaryPath: string\n): Promise<void> {\n const args = ['-b', bundleId, appBinaryPath];\n try {\n await spawnAsync('open', args);\n } catch (error: any) {\n if ('code' in error) {\n if (error.code === 1) {\n throw new CommandError(\n 'MACOS_LAUNCH',\n 'Failed to launch the compatible binary on macOS: open ' +\n args.join(' ') +\n '\\n\\n' +\n error.message\n );\n }\n }\n throw error;\n }\n}\n\nasync function installAppWithDeviceCtlAsync(\n uuid: string,\n bundleIdOrAppPath: string,\n onProgress: (event: { status: string; isComplete: boolean; progress: number }) => void\n): Promise<void> {\n // 𝝠 xcrun devicectl device install app --device 00001110-001111110110101A /Users/evanbacon/Library/Developer/Xcode/DerivedData/Router-hgbqaxzhrhkiftfweydvhgttadvn/Build/Products/Debug-iphoneos/Router.app --verbose\n return new Promise((resolve, reject) => {\n const args: string[] = [\n 'devicectl',\n 'device',\n 'install',\n 'app',\n '--device',\n uuid,\n bundleIdOrAppPath,\n ];\n const childProcess = spawn('xcrun', args);\n debug('xcrun ' + args.join(' '));\n\n let currentProgress = 0;\n let hasStarted = false;\n\n function updateProgress(progress: number) {\n hasStarted = true;\n if (progress <= currentProgress) {\n return;\n }\n currentProgress = progress;\n onProgress({\n progress,\n isComplete: progress === 100,\n status: 'Installing',\n });\n }\n\n childProcess.stdout.on('data', (data: Buffer) => {\n // Sometimes more than one chunk comes at a time, here we split by system newline,\n // then trim and filter.\n const strings = data\n .toString()\n .split(EOL)\n .map((value) => value.trim());\n\n strings.forEach((str) => {\n // Match the progress percentage:\n // - '34%... 35%...' -> 34\n // - '31%...' -> 31\n // - 'Complete!' -> 100\n\n const match = str.match(/(\\d+)%\\.\\.\\./);\n if (match) {\n updateProgress(parseInt(match[1], 10));\n } else if (hasStarted) {\n updateProgress(100);\n }\n });\n\n debug('[stdout]:', strings);\n });\n\n childProcess.on('close', (code) => {\n debug('[close]: ' + code);\n if (code === 0) {\n resolve();\n } else {\n const stderr = childProcess.stderr.read();\n const err = new Error(stderr);\n (err as any).code = code;\n detach(err);\n }\n });\n\n const detach = async (err?: Error) => {\n off?.();\n if (childProcess) {\n return new Promise<void>((resolve) => {\n childProcess?.on('close', resolve);\n childProcess?.kill();\n // childProcess = null;\n reject(err ?? new CommandError('detached'));\n });\n }\n };\n\n const off = installExitHooks(() => detach());\n });\n}\n\nexport async function launchAppWithDeviceCtl(deviceId: string, bundleId: string) {\n await devicectlAsync(['device', 'process', 'launch', '--device', deviceId, bundleId]);\n}\n\n/** Find all error codes from the output log */\nfunction getDeviceCtlErrorCodes(log: string): string[] {\n return [...log.matchAll(/BSErrorCodeDescription\\s+=\\s+(.*)$/gim)].map(([_line, code]) => code);\n}\n\nlet hasEverBeenInstalled: boolean | undefined;\n\nexport function hasDevicectlEverBeenInstalled() {\n if (hasEverBeenInstalled) return hasEverBeenInstalled;\n // It doesn't appear possible for devicectl to ever be uninstalled. We can just check once and store this result forever\n // to prevent cold boots of devicectl from slowing down all invocations of `expo run ios`\n if (fs.existsSync(DEVICE_CTL_EXISTS_PATH)) {\n hasEverBeenInstalled = true;\n return true;\n }\n\n const isInstalled = isDevicectlInstalled();\n\n if (isInstalled) {\n fs.writeFileSync(DEVICE_CTL_EXISTS_PATH, '1');\n }\n hasEverBeenInstalled = isInstalled;\n return isInstalled;\n}\n\nfunction isDevicectlInstalled() {\n try {\n execSync('xcrun devicectl --version', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Wraps the apple device method for installing and running an app,\n * adds indicator and retry loop for when the device is locked.\n */\nexport async function installAndLaunchAppAsync(props: {\n bundle: string;\n bundleIdentifier: string;\n udid: string;\n deviceName: string;\n}): Promise<void> {\n debug('Running on device:', props);\n const { bundle, bundleIdentifier, udid, deviceName } = props;\n let indicator: Ora | undefined;\n\n try {\n if (!indicator) {\n indicator = ora(`Connecting to: ${props.deviceName}`).start();\n }\n\n await installAppWithDeviceCtlAsync(\n udid,\n bundle,\n ({\n status,\n isComplete,\n progress,\n }: {\n status: string;\n isComplete: boolean;\n progress: number;\n }) => {\n if (!indicator) {\n indicator = ora(status).start();\n }\n indicator.text = `${chalk.bold(status)} ${progress}%`;\n if (isComplete) {\n indicator.succeed();\n }\n }\n );\n } catch (error: any) {\n if (indicator) {\n indicator.fail();\n }\n throw error;\n }\n\n async function launchAppOptionally() {\n try {\n await launchAppWithDeviceCtl(udid, bundleIdentifier);\n } catch (error: any) {\n if (indicator) {\n indicator.fail();\n }\n if (error.code === 'APPLE_DEVICE_LOCKED') {\n // Get the app name from the binary path.\n const appName = path.basename(bundle).split('.')[0] ?? 'app';\n if (\n isInteractive() &&\n (await confirmAsync({\n message: `Cannot launch ${appName} because the device is locked. Unlock ${deviceName} to continue...`,\n initial: true,\n }))\n ) {\n return launchAppOptionally();\n }\n throw new CommandError(\n `Cannot launch ${appName} on ${deviceName} because the device is locked.`\n );\n }\n throw error;\n }\n }\n\n await launchAppOptionally();\n}\n"],"names":["devicectlAsync","getConnectedAppleDevicesAsync","hasDevicectlEverBeenInstalled","installAndLaunchAppAsync","launchAppWithDeviceCtl","launchBinaryOnMacAsync","DEVICE_CTL_EXISTS_PATH","path","join","getExpoHomeDirectory","debug","require","args","options","xcrunAsync","error","CommandError","errorCodes","getDeviceCtlErrorCodes","stderr","includes","tmpPath","createTempFilePath","devices","stdout","devicesJson","JsonFile","readAsync","info","jsonVersion","Log","warn","assertDevicesJson","result","results","assert","Array","isArray","JSON","stringify","bundleId","appBinaryPath","spawnAsync","code","message","installAppWithDeviceCtlAsync","uuid","bundleIdOrAppPath","onProgress","Promise","resolve","reject","childProcess","spawn","currentProgress","hasStarted","updateProgress","progress","isComplete","status","on","data","strings","toString","split","EOL","map","value","trim","forEach","str","match","parseInt","read","err","Error","detach","off","kill","installExitHooks","deviceId","log","matchAll","_line","hasEverBeenInstalled","fs","existsSync","isInstalled","isDevicectlInstalled","writeFileSync","execSync","stdio","props","bundle","bundleIdentifier","udid","deviceName","indicator","ora","start","text","chalk","bold","succeed","fail","launchAppOptionally","appName","basename","isInteractive","confirmAsync","initial"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IA8HqBA,cAAc;eAAdA;;IAoBAC,6BAA6B;eAA7BA;;IAiKNC,6BAA6B;eAA7BA;;IA+BMC,wBAAwB;eAAxBA;;IA1CAC,sBAAsB;eAAtBA;;IA/GAC,sBAAsB;eAAtBA;;;;gEAvLD;;;;;;;gEACiC;;;;;;;gEACpC;;;;;;;yBACc;;;;;;;gEACjB;;;;;;;gEACI;;;;;;;yBAEC;;;;;;;gEACH;;;;;;uBAEU;8BACU;6DAChB;gCACc;wBACN;sBACI;6BACH;qBACV;yBACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE7B,MAAMC,yBAAyBC,eAAI,CAACC,IAAI,CAACC,IAAAA,kCAAoB,KAAI;AAEjE,MAAMC,QAAQC,QAAQ,SAAS;AAsGxB,eAAeX,eACpBY,IAA4B,EAC5BC,OAAsB;IAEtB,IAAI;QACF,OAAO,MAAMC,IAAAA,iBAAU,EAAC;YAAC;eAAgBF;SAAK,EAAEC;IAClD,EAAE,OAAOE,OAAY;QACnB,IAAIA,iBAAiBC,oBAAY,EAAE;YACjC,MAAMD;QACR;QACA,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AAMI,UAAU,EAAE,EAAEG,KAAK;QAC7D;QAEA,MAAMtD,6BACJkD,MACAF,QACA,CAAC,EACClC,MAAM,EACND,UAAU,EACVD,QAAQ,EAKT;YACC,IAAI,CAACwC,WAAW;gBACdA,YAAYC,IAAAA,QAAG,EAACvC,QAAQwC,KAAK;YAC/B;YACAF,UAAUG,IAAI,GAAG,GAAGC,gBAAK,CAACC,IAAI,CAAC3C,QAAQ,CAAC,EAAEF,SAAS,CAAC,CAAC;YACrD,IAAIC,YAAY;gBACduC,UAAUM,OAAO;YACnB;QACF;IAEJ,EAAE,OAAOxF,OAAY;QACnB,IAAIkF,WAAW;YACbA,UAAUO,IAAI;QAChB;QACA,MAAMzF;IACR;IAEA,eAAe0F;QACb,IAAI;YACF,MAAMrG,uBAAuB2F,MAAMD;QACrC,EAAE,OAAO/E,OAAY;YACnB,IAAIkF,WAAW;gBACbA,UAAUO,IAAI;YAChB;YACA,IAAIzF,MAAM4B,IAAI,KAAK,uBAAuB;gBACxC,yCAAyC;gBACzC,MAAM+D,UAAUnG,eAAI,CAACoG,QAAQ,CAACd,QAAQ7B,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI;gBACvD,IACE4C,IAAAA,0BAAa,OACZ,MAAMC,IAAAA,qBAAY,EAAC;oBAClBjE,SAAS,CAAC,cAAc,EAAE8D,QAAQ,sCAAsC,EAAEV,WAAW,eAAe,CAAC;oBACrGc,SAAS;gBACX,IACA;oBACA,OAAOL;gBACT;gBACA,MAAM,IAAIzF,oBAAY,CACpB,CAAC,cAAc,EAAE0F,QAAQ,IAAI,EAAEV,WAAW,8BAA8B,CAAC;YAE7E;YACA,MAAMjF;QACR;IACF;IAEA,MAAM0F;AACR"}
|
|
@@ -42,7 +42,11 @@ function createDebugMiddleware({ serverBaseUrl, reporter }) {
|
|
|
42
42
|
enableNetworkInspector: true,
|
|
43
43
|
// Only enable opening the browser version of React Native DevTools when debugging.
|
|
44
44
|
// This is useful when debugging the React Native DevTools by going to `/open-debugger` in the browser.
|
|
45
|
-
enableOpenDebuggerRedirect: _env.env.EXPO_DEBUG
|
|
45
|
+
enableOpenDebuggerRedirect: _env.env.EXPO_DEBUG,
|
|
46
|
+
// The standalone fusebox shell (@react-native/debugger-shell) starts installing almost
|
|
47
|
+
// immediately in the background when the dev middleware is created, which we don't
|
|
48
|
+
// always want to happen
|
|
49
|
+
enableStandaloneFuseboxShell: !(0, _env.envIsHeadless)()
|
|
46
50
|
}
|
|
47
51
|
});
|
|
48
52
|
const debuggerWebsocketEndpoint = websocketEndpoints['/inspector/debug'];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../src/start/server/metro/debugging/createDebugMiddleware.ts"],"sourcesContent":["import type { NextHandleFunction } from 'connect';\nimport { WebSocketServer } from 'ws';\n\nimport { createHandlersFactory } from './createHandlersFactory';\nimport { env } from '../../../../utils/env';\nimport { isLocalSocket, isMatchingOrigin } from '../../../../utils/net';\nimport { TerminalReporter } from '../TerminalReporter';\nimport { NETWORK_RESPONSE_STORAGE } from './messageHandlers/NetworkResponse';\n\nconst debug = require('debug')('expo:metro:debugging:middleware') as typeof console.log;\n\ninterface DebugMiddleware {\n debugMiddleware: NextHandleFunction;\n debugWebsocketEndpoints: Record<string, WebSocketServer>;\n}\n\ninterface DebugMiddlewareParams {\n serverBaseUrl: string;\n reporter: TerminalReporter;\n}\n\nexport function createDebugMiddleware({\n serverBaseUrl,\n reporter,\n}: DebugMiddlewareParams): DebugMiddleware {\n // Load the React Native debugging tools from project\n // TODO: check if this works with isolated modules\n const { createDevMiddleware } =\n require('@react-native/dev-middleware') as typeof import('@react-native/dev-middleware');\n\n const { middleware, websocketEndpoints } = createDevMiddleware({\n // TODO: Check with cedric why this can be removed\n // https://github.com/facebook/react-native/pull/53921\n // projectRoot: metroBundler.projectRoot,\n serverBaseUrl,\n logger: createLogger(reporter),\n unstable_customInspectorMessageHandler: createHandlersFactory(),\n // TODO: Forward all events to the shared Metro log reporter. Do this when we have opinions on how all logs should be presented.\n // unstable_eventReporter: {\n // logEvent(event) {\n // reporter.update(event);\n // },\n // },\n unstable_experiments: {\n // Enable the Network tab in React Native DevTools\n enableNetworkInspector: true,\n // Only enable opening the browser version of React Native DevTools when debugging.\n // This is useful when debugging the React Native DevTools by going to `/open-debugger` in the browser.\n enableOpenDebuggerRedirect: env.EXPO_DEBUG,\n },\n });\n\n const debuggerWebsocketEndpoint = websocketEndpoints['/inspector/debug'] as WebSocketServer;\n\n // NOTE(cedric): add a temporary websocket to handle Network-related CDP events\n websocketEndpoints['/inspector/network'] = createNetworkWebsocket(debuggerWebsocketEndpoint);\n\n // Explicitly limit debugger websocket to loopback requests\n debuggerWebsocketEndpoint.on('connection', (socket, request) => {\n if (!isLocalSocket(request.socket) || !isMatchingOrigin(request, serverBaseUrl)) {\n // NOTE: `socket.close` nicely closes the websocket, which will still allow incoming messages\n // `socket.terminate` instead forcefully closes down the socket\n socket.terminate();\n }\n });\n\n return {\n debugMiddleware(req, res, next) {\n // The debugger middleware is skipped entirely if the connection isn't a loopback request\n if (isLocalSocket(req.socket)) {\n return middleware(req, res, next);\n } else {\n return next();\n }\n },\n debugWebsocketEndpoints: websocketEndpoints,\n };\n}\n\nfunction createLogger(\n reporter: TerminalReporter\n): Parameters<typeof import('@react-native/dev-middleware').createDevMiddleware>[0]['logger'] {\n return {\n info: makeLogger(reporter, 'info'),\n warn: makeLogger(reporter, 'warn'),\n error: makeLogger(reporter, 'error'),\n };\n}\n\nfunction makeLogger(reporter: TerminalReporter, level: 'info' | 'warn' | 'error') {\n return (...data: any[]) =>\n reporter.update({\n type: 'unstable_server_log',\n level,\n data,\n });\n}\n\n/**\n * This adds a dedicated websocket connection that handles Network-related CDP events.\n * It's a temporary solution until Fusebox either implements the Network CDP domain,\n * or allows external domain agents that can send messages over the CDP socket to the debugger.\n * The Network websocket rebroadcasts events on the debugger CDP connections.\n */\nfunction createNetworkWebsocket(debuggerWebsocket: WebSocketServer) {\n const wss = new WebSocketServer({\n noServer: true,\n perMessageDeflate: true,\n // Don't crash on exceptionally large messages - assume the device is\n // well-behaved and the debugger is prepared to handle large messages.\n maxPayload: 0,\n });\n\n wss.on('connection', (networkSocket) => {\n networkSocket.on('message', (data) => {\n try {\n // Parse the network message, to determine how the message should be handled\n const message = JSON.parse(data.toString());\n\n if (message.method === 'Expo(Network.receivedResponseBody)' && message.params) {\n // If its a response body, write it to the global storage\n const { requestId, ...requestInfo } = message.params;\n NETWORK_RESPONSE_STORAGE.set(requestId, requestInfo);\n } else if (message.method.startsWith('Network.')) {\n // Otherwise, directly re-broadcast the Network events to all connected debuggers\n debuggerWebsocket.clients.forEach((debuggerSocket) => {\n if (debuggerSocket.readyState === debuggerSocket.OPEN) {\n debuggerSocket.send(data.toString());\n }\n });\n }\n } catch (error) {\n debug('Failed to handle Network CDP event', error);\n }\n });\n });\n\n return wss;\n}\n"],"names":["createDebugMiddleware","debug","require","serverBaseUrl","reporter","createDevMiddleware","middleware","websocketEndpoints","logger","createLogger","unstable_customInspectorMessageHandler","createHandlersFactory","unstable_experiments","enableNetworkInspector","enableOpenDebuggerRedirect","env","EXPO_DEBUG","debuggerWebsocketEndpoint","createNetworkWebsocket","on","socket","request","isLocalSocket","isMatchingOrigin","terminate","debugMiddleware","req","res","next","debugWebsocketEndpoints","info","makeLogger","warn","error","level","data","update","type","debuggerWebsocket","wss","WebSocketServer","noServer","perMessageDeflate","maxPayload","networkSocket","message","JSON","parse","toString","method","params","requestId","requestInfo","NETWORK_RESPONSE_STORAGE","set","startsWith","clients","forEach","debuggerSocket","readyState","OPEN","send"],"mappings":";;;;+BAqBgBA;;;eAAAA;;;;yBApBgB;;;;;;uCAEM;
|
|
1
|
+
{"version":3,"sources":["../../../../../../src/start/server/metro/debugging/createDebugMiddleware.ts"],"sourcesContent":["import type { NextHandleFunction } from 'connect';\nimport { WebSocketServer } from 'ws';\n\nimport { createHandlersFactory } from './createHandlersFactory';\nimport { env, envIsHeadless } from '../../../../utils/env';\nimport { isLocalSocket, isMatchingOrigin } from '../../../../utils/net';\nimport { TerminalReporter } from '../TerminalReporter';\nimport { NETWORK_RESPONSE_STORAGE } from './messageHandlers/NetworkResponse';\n\nconst debug = require('debug')('expo:metro:debugging:middleware') as typeof console.log;\n\ninterface DebugMiddleware {\n debugMiddleware: NextHandleFunction;\n debugWebsocketEndpoints: Record<string, WebSocketServer>;\n}\n\ninterface DebugMiddlewareParams {\n serverBaseUrl: string;\n reporter: TerminalReporter;\n}\n\nexport function createDebugMiddleware({\n serverBaseUrl,\n reporter,\n}: DebugMiddlewareParams): DebugMiddleware {\n // Load the React Native debugging tools from project\n // TODO: check if this works with isolated modules\n const { createDevMiddleware } =\n require('@react-native/dev-middleware') as typeof import('@react-native/dev-middleware');\n\n const { middleware, websocketEndpoints } = createDevMiddleware({\n // TODO: Check with cedric why this can be removed\n // https://github.com/facebook/react-native/pull/53921\n // projectRoot: metroBundler.projectRoot,\n serverBaseUrl,\n logger: createLogger(reporter),\n unstable_customInspectorMessageHandler: createHandlersFactory(),\n // TODO: Forward all events to the shared Metro log reporter. Do this when we have opinions on how all logs should be presented.\n // unstable_eventReporter: {\n // logEvent(event) {\n // reporter.update(event);\n // },\n // },\n unstable_experiments: {\n // Enable the Network tab in React Native DevTools\n enableNetworkInspector: true,\n // Only enable opening the browser version of React Native DevTools when debugging.\n // This is useful when debugging the React Native DevTools by going to `/open-debugger` in the browser.\n enableOpenDebuggerRedirect: env.EXPO_DEBUG,\n // The standalone fusebox shell (@react-native/debugger-shell) starts installing almost\n // immediately in the background when the dev middleware is created, which we don't\n // always want to happen\n enableStandaloneFuseboxShell: !envIsHeadless(),\n },\n });\n\n const debuggerWebsocketEndpoint = websocketEndpoints['/inspector/debug'] as WebSocketServer;\n\n // NOTE(cedric): add a temporary websocket to handle Network-related CDP events\n websocketEndpoints['/inspector/network'] = createNetworkWebsocket(debuggerWebsocketEndpoint);\n\n // Explicitly limit debugger websocket to loopback requests\n debuggerWebsocketEndpoint.on('connection', (socket, request) => {\n if (!isLocalSocket(request.socket) || !isMatchingOrigin(request, serverBaseUrl)) {\n // NOTE: `socket.close` nicely closes the websocket, which will still allow incoming messages\n // `socket.terminate` instead forcefully closes down the socket\n socket.terminate();\n }\n });\n\n return {\n debugMiddleware(req, res, next) {\n // The debugger middleware is skipped entirely if the connection isn't a loopback request\n if (isLocalSocket(req.socket)) {\n return middleware(req, res, next);\n } else {\n return next();\n }\n },\n debugWebsocketEndpoints: websocketEndpoints,\n };\n}\n\nfunction createLogger(\n reporter: TerminalReporter\n): Parameters<typeof import('@react-native/dev-middleware').createDevMiddleware>[0]['logger'] {\n return {\n info: makeLogger(reporter, 'info'),\n warn: makeLogger(reporter, 'warn'),\n error: makeLogger(reporter, 'error'),\n };\n}\n\nfunction makeLogger(reporter: TerminalReporter, level: 'info' | 'warn' | 'error') {\n return (...data: any[]) =>\n reporter.update({\n type: 'unstable_server_log',\n level,\n data,\n });\n}\n\n/**\n * This adds a dedicated websocket connection that handles Network-related CDP events.\n * It's a temporary solution until Fusebox either implements the Network CDP domain,\n * or allows external domain agents that can send messages over the CDP socket to the debugger.\n * The Network websocket rebroadcasts events on the debugger CDP connections.\n */\nfunction createNetworkWebsocket(debuggerWebsocket: WebSocketServer) {\n const wss = new WebSocketServer({\n noServer: true,\n perMessageDeflate: true,\n // Don't crash on exceptionally large messages - assume the device is\n // well-behaved and the debugger is prepared to handle large messages.\n maxPayload: 0,\n });\n\n wss.on('connection', (networkSocket) => {\n networkSocket.on('message', (data) => {\n try {\n // Parse the network message, to determine how the message should be handled\n const message = JSON.parse(data.toString());\n\n if (message.method === 'Expo(Network.receivedResponseBody)' && message.params) {\n // If its a response body, write it to the global storage\n const { requestId, ...requestInfo } = message.params;\n NETWORK_RESPONSE_STORAGE.set(requestId, requestInfo);\n } else if (message.method.startsWith('Network.')) {\n // Otherwise, directly re-broadcast the Network events to all connected debuggers\n debuggerWebsocket.clients.forEach((debuggerSocket) => {\n if (debuggerSocket.readyState === debuggerSocket.OPEN) {\n debuggerSocket.send(data.toString());\n }\n });\n }\n } catch (error) {\n debug('Failed to handle Network CDP event', error);\n }\n });\n });\n\n return wss;\n}\n"],"names":["createDebugMiddleware","debug","require","serverBaseUrl","reporter","createDevMiddleware","middleware","websocketEndpoints","logger","createLogger","unstable_customInspectorMessageHandler","createHandlersFactory","unstable_experiments","enableNetworkInspector","enableOpenDebuggerRedirect","env","EXPO_DEBUG","enableStandaloneFuseboxShell","envIsHeadless","debuggerWebsocketEndpoint","createNetworkWebsocket","on","socket","request","isLocalSocket","isMatchingOrigin","terminate","debugMiddleware","req","res","next","debugWebsocketEndpoints","info","makeLogger","warn","error","level","data","update","type","debuggerWebsocket","wss","WebSocketServer","noServer","perMessageDeflate","maxPayload","networkSocket","message","JSON","parse","toString","method","params","requestId","requestInfo","NETWORK_RESPONSE_STORAGE","set","startsWith","clients","forEach","debuggerSocket","readyState","OPEN","send"],"mappings":";;;;+BAqBgBA;;;eAAAA;;;;yBApBgB;;;;;;uCAEM;qBACH;qBACa;iCAEP;AAEzC,MAAMC,QAAQC,QAAQ,SAAS;AAYxB,SAASF,sBAAsB,EACpCG,aAAa,EACbC,QAAQ,EACc;IACtB,qDAAqD;IACrD,kDAAkD;IAClD,MAAM,EAAEC,mBAAmB,EAAE,GAC3BH,QAAQ;IAEV,MAAM,EAAEI,UAAU,EAAEC,kBAAkB,EAAE,GAAGF,oBAAoB;QAC7D,kDAAkD;QAClD,sDAAsD;QACtD,yCAAyC;QACzCF;QACAK,QAAQC,aAAaL;QACrBM,wCAAwCC,IAAAA,4CAAqB;QAC7D,gIAAgI;QAChI,4BAA4B;QAC5B,sBAAsB;QACtB,8BAA8B;QAC9B,OAAO;QACP,KAAK;QACLC,sBAAsB;YACpB,kDAAkD;YAClDC,wBAAwB;YACxB,mFAAmF;YACnF,uGAAuG;YACvGC,4BAA4BC,QAAG,CAACC,UAAU;YAC1C,uFAAuF;YACvF,mFAAmF;YACnF,wBAAwB;YACxBC,8BAA8B,CAACC,IAAAA,kBAA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M,KAAK,wCAAwCJ,QAAQK,MAAM,EAAE;oBAC7E,yDAAyD;oBACzD,MAAM,EAAEC,SAAS,EAAE,GAAGC,aAAa,GAAGP,QAAQK,MAAM;oBACpDG,yCAAwB,CAACC,GAAG,CAACH,WAAWC;gBAC1C,OAAO,IAAIP,QAAQI,MAAM,CAACM,UAAU,CAAC,aAAa;oBAChD,iFAAiF;oBACjFjB,kBAAkBkB,OAAO,CAACC,OAAO,CAAC,CAACC;wBACjC,IAAIA,eAAeC,UAAU,KAAKD,eAAeE,IAAI,EAAE;4BACrDF,eAAeG,IAAI,CAAC1B,KAAKa,QAAQ;wBACnC;oBACF;gBACF;YACF,EAAE,OAAOf,OAAO;gBACdlC,MAAM,sCAAsCkC;YAC9C;QACF;IACF;IAEA,OAAOM;AACT"}
|
|
@@ -129,7 +129,12 @@ const terminal = new LogRespectingTerminal(process.stdout);
|
|
|
129
129
|
async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, getMetroBundler }) {
|
|
130
130
|
var _exp_experiments, _exp_experiments1, _exp_experiments2, _exp_experiments3, _config_resolver, _exp_experiments4, _exp_experiments5, _exp_experiments6;
|
|
131
131
|
let reportEvent;
|
|
132
|
-
|
|
132
|
+
// We're resolving a monorepo root, higher up than the `projectRoot`. If this
|
|
133
|
+
// folder is different (presumably a parent) we're in a monorepo
|
|
134
|
+
const serverRoot = (0, _paths().getMetroServerRoot)(projectRoot);
|
|
135
|
+
const isWorkspace = serverRoot !== projectRoot;
|
|
136
|
+
// Autolinking Module Resolution will be enabled by default when we're in a monorepo
|
|
137
|
+
const autolinkingModuleResolutionEnabled = ((_exp_experiments = exp.experiments) == null ? void 0 : _exp_experiments.autolinkingModuleResolution) ?? isWorkspace;
|
|
133
138
|
const serverActionsEnabled = ((_exp_experiments1 = exp.experiments) == null ? void 0 : _exp_experiments1.reactServerFunctions) ?? _env.env.EXPO_UNSTABLE_SERVER_FUNCTIONS;
|
|
134
139
|
if (serverActionsEnabled) {
|
|
135
140
|
process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';
|
|
@@ -141,7 +146,6 @@ async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, ge
|
|
|
141
146
|
if ((_exp_experiments3 = exp.experiments) == null ? void 0 : _exp_experiments3.reactCanary) {
|
|
142
147
|
_log.Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);
|
|
143
148
|
}
|
|
144
|
-
const serverRoot = (0, _paths().getMetroServerRoot)(projectRoot);
|
|
145
149
|
const terminalReporter = new _MetroTerminalReporter.MetroTerminalReporter(serverRoot, terminal);
|
|
146
150
|
// NOTE: Allow external tools to override the metro config. This is considered internal and unstable
|
|
147
151
|
const configPath = _env.env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined;
|
|
@@ -185,6 +189,9 @@ async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, ge
|
|
|
185
189
|
if ((_exp_experiments4 = exp.experiments) == null ? void 0 : _exp_experiments4.reactCompiler) {
|
|
186
190
|
_log.Log.log(_chalk().default.gray`React Compiler enabled`);
|
|
187
191
|
}
|
|
192
|
+
if (autolinkingModuleResolutionEnabled) {
|
|
193
|
+
_log.Log.log(_chalk().default.gray`Expo Autolinking module resolution enabled`);
|
|
194
|
+
}
|
|
188
195
|
if (_env.env.EXPO_UNSTABLE_TREE_SHAKING && !_env.env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {
|
|
189
196
|
throw new _errors.CommandError('EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.');
|
|
190
197
|
}
|
|
@@ -197,9 +204,6 @@ async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, ge
|
|
|
197
204
|
if (_env.env.EXPO_UNSTABLE_LOG_BOX) {
|
|
198
205
|
_log.Log.warn(`Experimental Expo LogBox is enabled.`);
|
|
199
206
|
}
|
|
200
|
-
if (autolinkingModuleResolutionEnabled) {
|
|
201
|
-
_log.Log.warn(`Experimental Expo Autolinking module resolver is enabled.`);
|
|
202
|
-
}
|
|
203
207
|
if (serverActionsEnabled) {
|
|
204
208
|
var _exp_experiments8;
|
|
205
209
|
_log.Log.warn(`React Server Functions (beta) are enabled. Route rendering mode: ${((_exp_experiments8 = exp.experiments) == null ? void 0 : _exp_experiments8.reactServerComponentRoutes) ? 'server' : 'client'}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { Reporter } from '@expo/metro/metro';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport MetroHmrServer, { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport RevisionNotFoundError from '@expo/metro/metro/IncrementalBundler/RevisionNotFoundError';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport formatBundlingError from '@expo/metro/metro/lib/formatBundlingError';\nimport { mergeConfig, resolveConfig, type ConfigT } from '@expo/metro/metro-config';\nimport { Terminal } from '@expo/metro/metro-core';\nimport { createStableModuleIdFactory, getDefaultConfig } from '@expo/metro-config';\nimport chalk from 'chalk';\nimport http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// NOTE(@kitten): We pass a custom createStableModuleIdFactory function into the Metro module ID factory sometimes\ninterface MetroServerWithModuleIdMod extends MetroServer {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\ninterface MetroHmrServerWithModuleIdMod extends MetroHmrServer<MetroHmrClient> {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// TODO(@kitten): We assign this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this setting is used\ndeclare namespace globalThis {\n let __requireCycleIgnorePatterns: readonly RegExp[] | undefined;\n}\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\n// Wrap terminal and polyfill console.log so we can log during bundling without breaking the indicator.\nclass LogRespectingTerminal extends Terminal {\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream, { ttyPrint: true });\n\n const sendLog = (...msg: any[]) => {\n if (!msg.length) {\n this.log('');\n } else {\n const [format, ...args] = msg;\n this.log(format, ...args);\n }\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n console.log = sendLog;\n console.info = sendLog;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\ninterface LoadMetroConfigOptions {\n maxWorkers?: number;\n port?: number;\n reporter?: Reporter;\n resetCache?: boolean;\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadMetroConfigOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? env.EXPO_USE_STICKY_RESOLVER;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (exp.experiments?.reactServerComponentRoutes || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n }\n\n if (exp.experiments?.reactCanary) {\n Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);\n }\n\n const serverRoot = getMetroServerRoot(projectRoot);\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n // NOTE: Allow external tools to override the metro config. This is considered internal and unstable\n const configPath = env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined;\n const resolvedConfig = await resolveConfig(configPath, projectRoot);\n const defaultConfig = getDefaultConfig(projectRoot);\n\n let config: ConfigT = resolvedConfig.isEmpty\n ? defaultConfig\n : await mergeConfig(defaultConfig, resolvedConfig.config);\n\n // Set the watchfolders to include the projectRoot, as Metro assumes this\n // Force-override the reporter\n config = {\n ...config,\n\n // See: `overrideConfigWithArguments` https://github.com/facebook/metro/blob/5059e26/packages/metro-config/src/loadConfig.js#L274-L339\n // Compare to `LoadOptions` type (disregard `reporter` as we don't expose this)\n resetCache: !!options.resetCache,\n maxWorkers: options.maxWorkers ?? config.maxWorkers,\n server: {\n ...config.server,\n port: options.port ?? config.server.port,\n },\n\n watchFolders: !config.watchFolders.includes(config.projectRoot)\n ? [config.projectRoot, ...config.watchFolders]\n : config.watchFolders,\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n asWritable(config.transformer).publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n if (exp.experiments?.reactCompiler) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n if (autolinkingModuleResolutionEnabled) {\n Log.warn(`Experimental Expo Autolinking module resolver is enabled.`);\n }\n\n if (serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: !!exp.experiments?.reactServerComponentRoutes,\n getMetroBundler,\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\ninterface InstantiateMetroConfigOptions extends LoadMetroConfigOptions {\n host?: string;\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: InstantiateMetroConfigOptions,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: MetroServer;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler() {\n return metro.getBundler().getBundler();\n },\n });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } =\n createMetroMiddleware(metroConfig);\n\n // Get local URL to Metro bundler server (typically configured as 127.0.0.1:8081)\n const serverBaseUrl = metroBundler\n .getUrlCreator()\n .constructUrl({ scheme: 'http', hostType: 'localhost' });\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware({\n serverBaseUrl,\n reporter,\n });\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n\n const devtoolsWebsocketEndpoints = createDevToolsPluginWebsocketEndpoint();\n Object.assign(websocketEndpoints, devtoolsWebsocketEndpoints);\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n const { server, hmrServer, metro } = await runServer(\n metroBundler,\n metroConfig,\n {\n host: options.host,\n websocketEndpoints,\n watch: !isExporting && isWatchEnabled(),\n },\n {\n mockServer: isExporting,\n }\n );\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n projectRoot,\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: MetroServerWithModuleIdMod, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n // TODO(@kitten): Increase type-safety here\n platform: graph.transformOptions.platform!,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle:\n | typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default\n | typeof import('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // TODO: Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (\n this: MetroHmrServerWithModuleIdMod,\n group,\n options,\n changeEvent\n ) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n // TODO(@kitten): Increase type-safety here\n platform: revision.graph.transformOptions.platform!,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const resolvedRouterRoot = path.resolve(projectRoot, routerRoot).split(path.sep).join('/');\n const isRouterRoute = path.isAbsolute(filePath) && filePath.startsWith(resolvedRouterRoot);\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","asWritable","input","LogRespectingTerminal","Terminal","constructor","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","console","info","terminal","process","stdout","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","env","EXPO_USE_STICKY_RESOLVER","serverActionsEnabled","reactServerFunctions","EXPO_UNSTABLE_SERVER_FUNCTIONS","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","warn","serverRoot","getMetroServerRoot","terminalReporter","MetroTerminalReporter","configPath","EXPO_OVERRIDE_METRO_CONFIG","undefined","resolvedConfig","resolveConfig","defaultConfig","getDefaultConfig","isEmpty","mergeConfig","resetCache","maxWorkers","server","port","watchFolders","includes","reporter","update","event","globalThis","__requireCycleIgnorePatterns","resolver","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","serverBaseUrl","getUrlCreator","constructUrl","scheme","hostType","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","devtoolsWebsocketEndpoints","createDevToolsPluginWebsocketEndpoint","attachAtlasAsync","resetAtlasFile","hmrServer","runServer","host","watch","mockServer","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","path","sort","a","b","hmrJSBundle","require","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","push","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","error","formattedError","messageSocket","split","sep","join","dom","match","routerRoot","isRouterEntry","test","isRouterModule","resolvedRouterRoot","resolve","isRouterRoute","isAbsolute","startsWith","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;IA+NsBA,qBAAqB;eAArBA;;IAuSNC,cAAc;eAAdA;;IA9aMC,oBAAoB;eAApBA;;;;yBAxFqB;;;;;;;yBACR;;;;;;;gEAMD;;;;;;;gEAEF;;;;;;;yBACyB;;;;;;;yBAChC;;;;;;;yBACqC;;;;;;;gEAC5C;;;;;;;gEAED;;;;;;iDAEqC;uCAEhB;6BACL;uCACK;uCACA;+BAC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AW,KACpD,+IAA+I;IAC/I,CAAE5E,CAAAA,SAASkE,KAAK,CAAC,0BAA0BlE,SAASkE,KAAK,CAAC,yBAAwB,GAClF;QACA,OAAOjE,iBAAiBG,sBAAsB,CAACwE,WAAW;IAC5D;IAEA,IACE3E,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyC4E,gBAAgB,KACzD,2FAA2F;IAC3F,CAAC7E,SAASkE,KAAK,CAAC,8BAChB;QACA,OAAOjE,iBAAiBG,sBAAsB,CAACyE,gBAAgB;IACjE;IAEA,OAAO5E;AACT;AAMO,SAAShI;IACd,IAAI+B,QAAG,CAAC8K,EAAE,EAAE;QACVtK,QAAG,CAAC3B,GAAG,CACL6D,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAAC1C,QAAG,CAAC8K,EAAE;AAChB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { Reporter } from '@expo/metro/metro';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport MetroHmrServer, { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport RevisionNotFoundError from '@expo/metro/metro/IncrementalBundler/RevisionNotFoundError';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport formatBundlingError from '@expo/metro/metro/lib/formatBundlingError';\nimport { mergeConfig, resolveConfig, type ConfigT } from '@expo/metro/metro-config';\nimport { Terminal } from '@expo/metro/metro-core';\nimport { createStableModuleIdFactory, getDefaultConfig } from '@expo/metro-config';\nimport chalk from 'chalk';\nimport http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// NOTE(@kitten): We pass a custom createStableModuleIdFactory function into the Metro module ID factory sometimes\ninterface MetroServerWithModuleIdMod extends MetroServer {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\ninterface MetroHmrServerWithModuleIdMod extends MetroHmrServer<MetroHmrClient> {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// TODO(@kitten): We assign this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this setting is used\ndeclare namespace globalThis {\n let __requireCycleIgnorePatterns: readonly RegExp[] | undefined;\n}\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\n// Wrap terminal and polyfill console.log so we can log during bundling without breaking the indicator.\nclass LogRespectingTerminal extends Terminal {\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream, { ttyPrint: true });\n\n const sendLog = (...msg: any[]) => {\n if (!msg.length) {\n this.log('');\n } else {\n const [format, ...args] = msg;\n this.log(format, ...args);\n }\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n console.log = sendLog;\n console.info = sendLog;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\ninterface LoadMetroConfigOptions {\n maxWorkers?: number;\n port?: number;\n reporter?: Reporter;\n resetCache?: boolean;\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadMetroConfigOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n // We're resolving a monorepo root, higher up than the `projectRoot`. If this\n // folder is different (presumably a parent) we're in a monorepo\n const serverRoot = getMetroServerRoot(projectRoot);\n const isWorkspace = serverRoot !== projectRoot;\n\n // Autolinking Module Resolution will be enabled by default when we're in a monorepo\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? isWorkspace;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (exp.experiments?.reactServerComponentRoutes || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n }\n\n if (exp.experiments?.reactCanary) {\n Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);\n }\n\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n // NOTE: Allow external tools to override the metro config. This is considered internal and unstable\n const configPath = env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined;\n const resolvedConfig = await resolveConfig(configPath, projectRoot);\n const defaultConfig = getDefaultConfig(projectRoot);\n\n let config: ConfigT = resolvedConfig.isEmpty\n ? defaultConfig\n : await mergeConfig(defaultConfig, resolvedConfig.config);\n\n // Set the watchfolders to include the projectRoot, as Metro assumes this\n // Force-override the reporter\n config = {\n ...config,\n\n // See: `overrideConfigWithArguments` https://github.com/facebook/metro/blob/5059e26/packages/metro-config/src/loadConfig.js#L274-L339\n // Compare to `LoadOptions` type (disregard `reporter` as we don't expose this)\n resetCache: !!options.resetCache,\n maxWorkers: options.maxWorkers ?? config.maxWorkers,\n server: {\n ...config.server,\n port: options.port ?? config.server.port,\n },\n\n watchFolders: !config.watchFolders.includes(config.projectRoot)\n ? [config.projectRoot, ...config.watchFolders]\n : config.watchFolders,\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n asWritable(config.transformer).publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n if (exp.experiments?.reactCompiler) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (autolinkingModuleResolutionEnabled) {\n Log.log(chalk.gray`Expo Autolinking module resolution enabled`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n\n if (serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: !!exp.experiments?.reactServerComponentRoutes,\n getMetroBundler,\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\ninterface InstantiateMetroConfigOptions extends LoadMetroConfigOptions {\n host?: string;\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: InstantiateMetroConfigOptions,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: MetroServer;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler() {\n return metro.getBundler().getBundler();\n },\n });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } =\n createMetroMiddleware(metroConfig);\n\n // Get local URL to Metro bundler server (typically configured as 127.0.0.1:8081)\n const serverBaseUrl = metroBundler\n .getUrlCreator()\n .constructUrl({ scheme: 'http', hostType: 'localhost' });\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware({\n serverBaseUrl,\n reporter,\n });\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n\n const devtoolsWebsocketEndpoints = createDevToolsPluginWebsocketEndpoint();\n Object.assign(websocketEndpoints, devtoolsWebsocketEndpoints);\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n const { server, hmrServer, metro } = await runServer(\n metroBundler,\n metroConfig,\n {\n host: options.host,\n websocketEndpoints,\n watch: !isExporting && isWatchEnabled(),\n },\n {\n mockServer: isExporting,\n }\n );\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n projectRoot,\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: MetroServerWithModuleIdMod, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n // TODO(@kitten): Increase type-safety here\n platform: graph.transformOptions.platform!,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle:\n | typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default\n | typeof import('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // TODO: Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (\n this: MetroHmrServerWithModuleIdMod,\n group,\n options,\n changeEvent\n ) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n // TODO(@kitten): Increase type-safety here\n platform: revision.graph.transformOptions.platform!,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const resolvedRouterRoot = path.resolve(projectRoot, routerRoot).split(path.sep).join('/');\n const isRouterRoute = path.isAbsolute(filePath) && filePath.startsWith(resolvedRouterRoot);\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","asWritable","input","LogRespectingTerminal","Terminal","constructor","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","console","info","terminal","process","stdout","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","serverRoot","getMetroServerRoot","isWorkspace","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","serverActionsEnabled","reactServerFunctions","env","EXPO_UNSTABLE_SERVER_FUNCTIONS","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","warn","terminalReporter","MetroTerminalReporter","configPath","EXPO_OVERRIDE_METRO_CONFIG","undefined","resolvedConfig","resolveConfig","defaultConfig","getDefaultConfig","isEmpty","mergeConfig","resetCache","maxWorkers","server","port","watchFolders","includes","reporter","update","event","globalThis","__requireCycleIgnorePatterns","resolver","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","serverBaseUrl","getUrlCreator","constructUrl","scheme","hostType","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","devtoolsWebsocketEndpoints","createDevToolsPluginWebsocketEndpoint","attachAtlasAsync","resetAtlasFile","hmrServer","runServer","host","watch","mockServer","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","path","sort","a","b","hmrJSBundle","require","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","push","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","error","formattedError","messageSocket","split","sep","join","dom","match","routerRoot","isRouterEntry","test","isRouterModule","resolvedRouterRoot","resolve","isRouterRoute","isAbsolute","startsWith","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;IAqOsBA,qBAAqB;eAArBA;;IAuSNC,cAAc;eAAdA;;IApbMC,oBAAoB;eAApBA;;;;yBAxFqB;;;;;;;yBACR;;;;;;;gEAMD;;;;;;;gEAEF;;;;;;;yBACyB;;;;;;;yBAChC;;;;;;;yBACqC;;;;;;;gEAC5C;;;;;;;gEAED;;;;;;iDAEqC;uCAEhB;6BACL;uCACK;uCACA;+BACZ;wCACkB;qBACxB;qBACA;wBACS;gCACQ;6CACO;2BACV;kCACE;;;;;;AAsBpC,SAASC,WAAcC,KAAQ;IAC7B,OAAOA;AACT;AAEA,uGAAuG;AACvG,MAAMC,8BAA8BC,qBAAQ;IAC1CC,YAAYC,MAAkE,CAAE;QAC9E,KAAK,CAACA,QAAQ;YAAEC,UAAU;QAAK;QAE/B,MAAMC,UAAU,CAAC,GAAGC;YAClB,IAAI,CAACA,IAAIC,MAAM,EAAE;gBACf,IAAI,CAACC,GAAG,CAAC;YACX,OAAO;gBACL,MAAM,CAACC,QAAQ,GAAGC,KAAK,GAAGJ;gBAC1B,IAAI,CAACE,GAAG,CAACC,WAAWC;YACtB;YACA,6FAA6F;YAC7F,IAAI,CAACC,KAAK;QACZ;QAEAC,QAAQJ,GAAG,GAAGH;QACdO,QAAQC,IAAI,GAAGR;IACjB;AACF;AAEA,6DAA6D;AAC7D,MAAMS,WAAW,IAAId,sBAAsBe,QAAQC,MAAM;AASlD,eAAenB,qBACpBoB,WAAmB,EACnBC,OAA+B,EAC/B,EACEC,GAAG,EACHC,WAAW,EACXC,eAAe,EAC2D;QAW1EF,kBAGAA,mBAOEA,mBAIAA,mBA0CsCG,kBAatCH,mBAkCsBA,mBAIUA;IApHpC,IAAII;IAEJ,6EAA6E;IAC7E,gEAAgE;IAChE,MAAMC,aA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,MAAMsE,iBAAiB,yBAAyBD,IAAI,CAACrE;QACrD,mIAAmI;QACnI,MAAMuE,qBAAqBtD,eAAI,CAACuD,OAAO,CAAClL,aAAa6K,YAAYL,KAAK,CAAC7C,eAAI,CAAC8C,GAAG,EAAEC,IAAI,CAAC;QACtF,MAAMS,gBAAgBxD,eAAI,CAACyD,UAAU,CAAC1E,aAAaA,SAAS2E,UAAU,CAACJ;QAEvE,qIAAqI;QACrI,wEAAwE;QACxE,IAAI,CAACH,iBAAiB,CAACE,kBAAkB,CAACG,eAAe;YACvDxE,iBAAiBG,sBAAsB,CAAE+D,UAAU,GAAG;QACxD;IACF;IAEA,IACElE,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyC2E,WAAW,KACpD,+IAA+I;IAC/I,CAAE5E,CAAAA,SAASkE,KAAK,CAAC,0BAA0BlE,SAASkE,KAAK,CAAC,yBAAwB,GAClF;QACA,OAAOjE,iBAAiBG,sBAAsB,CAACwE,WAAW;IAC5D;IAEA,IACE3E,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyC4E,gBAAgB,KACzD,2FAA2F;IAC3F,CAAC7E,SAASkE,KAAK,CAAC,8BAChB;QACA,OAAOjE,iBAAiBG,sBAAsB,CAACyE,gBAAgB;IACjE;IAEA,OAAO5E;AACT;AAMO,SAAShI;IACd,IAAIoC,QAAG,CAACyK,EAAE,EAAE;QACVpK,QAAG,CAAC7B,GAAG,CACL6D,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAACrC,QAAG,CAACyK,EAAE;AAChB"}
|
|
@@ -9,6 +9,9 @@ function _export(target, all) {
|
|
|
9
9
|
});
|
|
10
10
|
}
|
|
11
11
|
_export(exports, {
|
|
12
|
+
cleanupOldExpoGoCacheEntriesAsync: function() {
|
|
13
|
+
return cleanupOldExpoGoCacheEntriesAsync;
|
|
14
|
+
},
|
|
12
15
|
downloadExpoGoAsync: function() {
|
|
13
16
|
return downloadExpoGoAsync;
|
|
14
17
|
},
|
|
@@ -16,6 +19,13 @@ _export(exports, {
|
|
|
16
19
|
return getExpoGoVersionEntryAsync;
|
|
17
20
|
}
|
|
18
21
|
});
|
|
22
|
+
function _promises() {
|
|
23
|
+
const data = /*#__PURE__*/ _interop_require_default(require("fs/promises"));
|
|
24
|
+
_promises = function() {
|
|
25
|
+
return data;
|
|
26
|
+
};
|
|
27
|
+
return data;
|
|
28
|
+
}
|
|
19
29
|
function _path() {
|
|
20
30
|
const data = /*#__PURE__*/ _interop_require_default(require("path"));
|
|
21
31
|
_path = function() {
|
|
@@ -77,6 +87,31 @@ async function getExpoGoVersionEntryAsync(sdkVersion) {
|
|
|
77
87
|
}
|
|
78
88
|
return version;
|
|
79
89
|
}
|
|
90
|
+
const SIX_MONTHS_IN_MS = 6 * 30 * 24 * 60 * 60 * 1000;
|
|
91
|
+
async function cleanupOldExpoGoCacheEntriesAsync(cacheDirectory, maxAgeMs = SIX_MONTHS_IN_MS) {
|
|
92
|
+
let cacheEntries;
|
|
93
|
+
try {
|
|
94
|
+
cacheEntries = await _promises().default.readdir(cacheDirectory);
|
|
95
|
+
} catch {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const now = Date.now();
|
|
99
|
+
for (const entry of cacheEntries){
|
|
100
|
+
const filePath = _path().default.join(cacheDirectory, entry);
|
|
101
|
+
try {
|
|
102
|
+
const stat = await _promises().default.lstat(filePath);
|
|
103
|
+
if (now - stat.mtimeMs > maxAgeMs) {
|
|
104
|
+
debug(`Removing old app cache entry: ${filePath}`);
|
|
105
|
+
await _promises().default.rm(filePath, {
|
|
106
|
+
recursive: true,
|
|
107
|
+
force: true
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
} catch {
|
|
111
|
+
// continue
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
80
115
|
async function downloadExpoGoAsync(platform, { url, sdkVersion }) {
|
|
81
116
|
const { getFilePath, versionsKey, shouldExtractResults } = platformSettings[platform];
|
|
82
117
|
const spinner = (0, _ora.ora)({
|
|
@@ -97,6 +132,7 @@ async function downloadExpoGoAsync(platform, { url, sdkVersion }) {
|
|
|
97
132
|
const filename = _path().default.parse(url).name;
|
|
98
133
|
try {
|
|
99
134
|
const outputPath = getFilePath(filename);
|
|
135
|
+
cleanupOldExpoGoCacheEntriesAsync(_path().default.dirname(outputPath));
|
|
100
136
|
debug(`Downloading Expo Go from "${url}" to "${outputPath}".`);
|
|
101
137
|
debug(`The requested copy of Expo Go might already be cached in: "${(0, _UserSettings.getExpoHomeDirectory)()}". You can disable the cache with EXPO_NO_CACHE=1`);
|
|
102
138
|
await (0, _profile.profile)(_downloadAppAsync.downloadAppAsync)({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/downloadExpoGoAsync.ts"],"sourcesContent":["import path from 'path';\nimport ProgressBar from 'progress';\nimport { gt } from 'semver';\n\nimport { downloadAppAsync } from './downloadAppAsync';\nimport { CommandError } from './errors';\nimport { ora } from './ora';\nimport { profile } from './profile';\nimport { createProgressBar } from './progress';\nimport { getVersionsAsync, SDKVersion } from '../api/getVersions';\nimport { getExpoHomeDirectory } from '../api/user/UserSettings';\nimport { Log } from '../log';\n\nconst debug = require('debug')('expo:utils:downloadExpoGo') as typeof console.log;\n\nconst platformSettings: Record<\n string,\n {\n shouldExtractResults: boolean;\n versionsKey: keyof SDKVersion;\n getFilePath: (filename: string) => string;\n }\n> = {\n ios: {\n versionsKey: 'iosClientUrl',\n getFilePath: (filename) =>\n path.join(getExpoHomeDirectory(), 'ios-simulator-app-cache', `${filename}.app`),\n shouldExtractResults: true,\n },\n android: {\n versionsKey: 'androidClientUrl',\n getFilePath: (filename) =>\n path.join(getExpoHomeDirectory(), 'android-apk-cache', `${filename}.apk`),\n shouldExtractResults: false,\n },\n};\n\n/**\n * @internal exposed for testing.\n * @returns the matching `SDKVersion` object from the Expo API.\n */\nexport async function getExpoGoVersionEntryAsync(sdkVersion: string): Promise<SDKVersion> {\n const { sdkVersions: versions } = await getVersionsAsync();\n let version: SDKVersion;\n\n if (sdkVersion.toUpperCase() === 'UNVERSIONED') {\n // find the latest version\n const latestVersionKey = Object.keys(versions).reduce((a, b) => {\n if (gt(b, a)) {\n return b;\n }\n return a;\n }, '0.0.0');\n\n Log.warn(\n `Downloading the latest Expo Go client (${latestVersionKey}). This will not fully conform to UNVERSIONED.`\n );\n version = versions[latestVersionKey];\n } else {\n version = versions[sdkVersion];\n }\n\n if (!version) {\n throw new CommandError(`Unable to find a version of Expo Go for SDK ${sdkVersion}`);\n }\n return version;\n}\n\n/** Download the Expo Go app from the Expo servers (if only it was this easy for every app). */\nexport async function downloadExpoGoAsync(\n platform: keyof typeof platformSettings,\n {\n url,\n sdkVersion,\n }: {\n url?: string;\n sdkVersion: string;\n }\n): Promise<string> {\n const { getFilePath, versionsKey, shouldExtractResults } = platformSettings[platform];\n\n const spinner = ora({ text: 'Fetching Expo Go', color: 'white' }).start();\n\n let bar: ProgressBar | null = null;\n\n try {\n if (!url) {\n const version = await getExpoGoVersionEntryAsync(sdkVersion);\n\n debug(`Installing Expo Go version for SDK ${sdkVersion} at URL: ${version[versionsKey]}`);\n url = version[versionsKey] as string;\n }\n } catch (error) {\n spinner.fail();\n throw error;\n }\n\n const filename = path.parse(url).name;\n\n try {\n const outputPath = getFilePath(filename);\n debug(`Downloading Expo Go from \"${url}\" to \"${outputPath}\".`);\n debug(\n `The requested copy of Expo Go might already be cached in: \"${getExpoHomeDirectory()}\". You can disable the cache with EXPO_NO_CACHE=1`\n );\n await profile(downloadAppAsync)({\n url,\n // Save all encrypted cache data to `~/.expo/expo-go`\n cacheDirectory: 'expo-go',\n outputPath,\n extract: shouldExtractResults,\n onProgress({ progress, total }) {\n if (progress && total) {\n if (!bar) {\n if (spinner.isSpinning) {\n spinner.stop();\n }\n bar = createProgressBar('Downloading the Expo Go app [:bar] :percent :etas', {\n width: 64,\n total: 100,\n // clear: true,\n complete: '=',\n incomplete: ' ',\n });\n } else {\n bar.update(progress, total);\n }\n }\n },\n });\n return outputPath;\n } finally {\n spinner.stop();\n (bar as ProgressBar | null)?.terminate();\n }\n}\n"],"names":["downloadExpoGoAsync","getExpoGoVersionEntryAsync","debug","require","platformSettings","ios","versionsKey","getFilePath","filename","path","join","getExpoHomeDirectory","shouldExtractResults","android","sdkVersion","sdkVersions","versions","getVersionsAsync","version","toUpperCase","latestVersionKey","Object","keys","reduce","a","b","gt","Log","warn","CommandError","platform","url","spinner","ora","text","color","start","bar","error","fail","parse","name","outputPath","
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/downloadExpoGoAsync.ts"],"sourcesContent":["import fs from 'fs/promises';\nimport path from 'path';\nimport ProgressBar from 'progress';\nimport { gt } from 'semver';\n\nimport { downloadAppAsync } from './downloadAppAsync';\nimport { CommandError } from './errors';\nimport { ora } from './ora';\nimport { profile } from './profile';\nimport { createProgressBar } from './progress';\nimport { getVersionsAsync, SDKVersion } from '../api/getVersions';\nimport { getExpoHomeDirectory } from '../api/user/UserSettings';\nimport { Log } from '../log';\n\nconst debug = require('debug')('expo:utils:downloadExpoGo') as typeof console.log;\n\nconst platformSettings: Record<\n string,\n {\n shouldExtractResults: boolean;\n versionsKey: keyof SDKVersion;\n getFilePath: (filename: string) => string;\n }\n> = {\n ios: {\n versionsKey: 'iosClientUrl',\n getFilePath: (filename) =>\n path.join(getExpoHomeDirectory(), 'ios-simulator-app-cache', `${filename}.app`),\n shouldExtractResults: true,\n },\n android: {\n versionsKey: 'androidClientUrl',\n getFilePath: (filename) =>\n path.join(getExpoHomeDirectory(), 'android-apk-cache', `${filename}.apk`),\n shouldExtractResults: false,\n },\n};\n\n/**\n * @internal exposed for testing.\n * @returns the matching `SDKVersion` object from the Expo API.\n */\nexport async function getExpoGoVersionEntryAsync(sdkVersion: string): Promise<SDKVersion> {\n const { sdkVersions: versions } = await getVersionsAsync();\n let version: SDKVersion;\n\n if (sdkVersion.toUpperCase() === 'UNVERSIONED') {\n // find the latest version\n const latestVersionKey = Object.keys(versions).reduce((a, b) => {\n if (gt(b, a)) {\n return b;\n }\n return a;\n }, '0.0.0');\n\n Log.warn(\n `Downloading the latest Expo Go client (${latestVersionKey}). This will not fully conform to UNVERSIONED.`\n );\n version = versions[latestVersionKey];\n } else {\n version = versions[sdkVersion];\n }\n\n if (!version) {\n throw new CommandError(`Unable to find a version of Expo Go for SDK ${sdkVersion}`);\n }\n return version;\n}\n\nconst SIX_MONTHS_IN_MS = 6 * 30 * 24 * 60 * 60 * 1000;\n\n/** Remove cached Expo Go apps (.apk / .app) that are older than `maxAge` from the given directory. */\nexport async function cleanupOldExpoGoCacheEntriesAsync(\n cacheDirectory: string,\n maxAgeMs: number = SIX_MONTHS_IN_MS\n): Promise<void> {\n let cacheEntries: string[];\n try {\n cacheEntries = await fs.readdir(cacheDirectory);\n } catch {\n return;\n }\n\n const now = Date.now();\n for (const entry of cacheEntries) {\n const filePath = path.join(cacheDirectory, entry);\n try {\n const stat = await fs.lstat(filePath);\n if (now - stat.mtimeMs > maxAgeMs) {\n debug(`Removing old app cache entry: ${filePath}`);\n await fs.rm(filePath, { recursive: true, force: true });\n }\n } catch {\n // continue\n }\n }\n}\n\n/** Download the Expo Go app from the Expo servers (if only it was this easy for every app). */\nexport async function downloadExpoGoAsync(\n platform: keyof typeof platformSettings,\n {\n url,\n sdkVersion,\n }: {\n url?: string;\n sdkVersion: string;\n }\n): Promise<string> {\n const { getFilePath, versionsKey, shouldExtractResults } = platformSettings[platform];\n\n const spinner = ora({ text: 'Fetching Expo Go', color: 'white' }).start();\n\n let bar: ProgressBar | null = null;\n\n try {\n if (!url) {\n const version = await getExpoGoVersionEntryAsync(sdkVersion);\n\n debug(`Installing Expo Go version for SDK ${sdkVersion} at URL: ${version[versionsKey]}`);\n url = version[versionsKey] as string;\n }\n } catch (error) {\n spinner.fail();\n throw error;\n }\n\n const filename = path.parse(url).name;\n\n try {\n const outputPath = getFilePath(filename);\n cleanupOldExpoGoCacheEntriesAsync(path.dirname(outputPath));\n debug(`Downloading Expo Go from \"${url}\" to \"${outputPath}\".`);\n debug(\n `The requested copy of Expo Go might already be cached in: \"${getExpoHomeDirectory()}\". You can disable the cache with EXPO_NO_CACHE=1`\n );\n await profile(downloadAppAsync)({\n url,\n // Save all encrypted cache data to `~/.expo/expo-go`\n cacheDirectory: 'expo-go',\n outputPath,\n extract: shouldExtractResults,\n onProgress({ progress, total }) {\n if (progress && total) {\n if (!bar) {\n if (spinner.isSpinning) {\n spinner.stop();\n }\n bar = createProgressBar('Downloading the Expo Go app [:bar] :percent :etas', {\n width: 64,\n total: 100,\n // clear: true,\n complete: '=',\n incomplete: ' ',\n });\n } else {\n bar.update(progress, total);\n }\n }\n },\n });\n return outputPath;\n } finally {\n spinner.stop();\n (bar as ProgressBar | null)?.terminate();\n }\n}\n"],"names":["cleanupOldExpoGoCacheEntriesAsync","downloadExpoGoAsync","getExpoGoVersionEntryAsync","debug","require","platformSettings","ios","versionsKey","getFilePath","filename","path","join","getExpoHomeDirectory","shouldExtractResults","android","sdkVersion","sdkVersions","versions","getVersionsAsync","version","toUpperCase","latestVersionKey","Object","keys","reduce","a","b","gt","Log","warn","CommandError","SIX_MONTHS_IN_MS","cacheDirectory","maxAgeMs","cacheEntries","fs","readdir","now","Date","entry","filePath","stat","lstat","mtimeMs","rm","recursive","force","platform","url","spinner","ora","text","color","start","bar","error","fail","parse","name","outputPath","dirname","profile","downloadAppAsync","extract","onProgress","progress","total","isSpinning","stop","createProgressBar","width","complete","incomplete","update","terminate"],"mappings":";;;;;;;;;;;IAwEsBA,iCAAiC;eAAjCA;;IA2BAC,mBAAmB;eAAnBA;;IAzDAC,0BAA0B;eAA1BA;;;;gEA1CP;;;;;;;gEACE;;;;;;;yBAEE;;;;;;kCAEc;wBACJ;qBACT;yBACI;0BACU;6BACW;8BACR;qBACjB;;;;;;AAEpB,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MAAMC,mBAOF;IACFC,K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AQ,EAAEC,KAAK,EAAE;gBAC5B,IAAID,YAAYC,OAAO;oBACrB,IAAI,CAACZ,KAAK;wBACR,IAAIL,QAAQkB,UAAU,EAAE;4BACtBlB,QAAQmB,IAAI;wBACd;wBACAd,MAAMe,IAAAA,2BAAiB,EAAC,qDAAqD;4BAC3EC,OAAO;4BACPJ,OAAO;4BACP,eAAe;4BACfK,UAAU;4BACVC,YAAY;wBACd;oBACF,OAAO;wBACLlB,IAAImB,MAAM,CAACR,UAAUC;oBACvB;gBACF;YACF;QACF;QACA,OAAOP;IACT,SAAU;QACRV,QAAQmB,IAAI;QACXd,uBAAD,AAACA,IAA4BoB,SAAS;IACxC;AACF"}
|
package/build/src/utils/env.js
CHANGED
|
@@ -12,6 +12,9 @@ _export(exports, {
|
|
|
12
12
|
env: function() {
|
|
13
13
|
return env;
|
|
14
14
|
},
|
|
15
|
+
envIsHeadless: function() {
|
|
16
|
+
return envIsHeadless;
|
|
17
|
+
},
|
|
15
18
|
envIsWebcontainer: function() {
|
|
16
19
|
return envIsWebcontainer;
|
|
17
20
|
}
|
|
@@ -75,7 +78,7 @@ class Env {
|
|
|
75
78
|
return (0, _getenv().boolish)('EXPO_NO_GIT_STATUS', true);
|
|
76
79
|
}
|
|
77
80
|
/** Disable auto web setup */ get EXPO_NO_WEB_SETUP() {
|
|
78
|
-
return (0, _getenv().boolish)('EXPO_NO_WEB_SETUP',
|
|
81
|
+
return (0, _getenv().boolish)('EXPO_NO_WEB_SETUP', envIsHeadless());
|
|
79
82
|
}
|
|
80
83
|
/** Disable auto TypeScript setup */ get EXPO_NO_TYPESCRIPT_SETUP() {
|
|
81
84
|
return (0, _getenv().boolish)('EXPO_NO_TYPESCRIPT_SETUP', false);
|
|
@@ -164,11 +167,6 @@ class Env {
|
|
|
164
167
|
*/ get EXPO_METRO_UNSTABLE_ERRORS() {
|
|
165
168
|
return (0, _getenv().boolish)('EXPO_METRO_UNSTABLE_ERRORS', true);
|
|
166
169
|
}
|
|
167
|
-
/** Enable the experimental sticky resolver for Metro (Uses Expo Autolinking results and applies them to Metro's resolution)
|
|
168
|
-
* @deprecated Replaced by `exp.experiments.autolinkingModuleResolution`
|
|
169
|
-
*/ get EXPO_USE_STICKY_RESOLVER() {
|
|
170
|
-
return (0, _getenv().boolish)('EXPO_USE_STICKY_RESOLVER', false);
|
|
171
|
-
}
|
|
172
170
|
/** Disable Environment Variable injection in client bundles. */ get EXPO_NO_CLIENT_ENV_VARS() {
|
|
173
171
|
return (0, _getenv().boolish)('EXPO_NO_CLIENT_ENV_VARS', false);
|
|
174
172
|
}
|
|
@@ -218,12 +216,10 @@ class Env {
|
|
|
218
216
|
return (0, _getenv().boolish)('EAS_BUILD', false);
|
|
219
217
|
}
|
|
220
218
|
/** Disable the React Native Directory compatibility check for new architecture when installing packages */ get EXPO_NO_NEW_ARCH_COMPAT_CHECK() {
|
|
221
|
-
return (0, _getenv().boolish)('EXPO_NO_NEW_ARCH_COMPAT_CHECK',
|
|
219
|
+
return (0, _getenv().boolish)('EXPO_NO_NEW_ARCH_COMPAT_CHECK', envIsHeadless());
|
|
222
220
|
}
|
|
223
221
|
/** Disable the dependency validation when installing other dependencies and starting the project */ get EXPO_NO_DEPENDENCY_VALIDATION() {
|
|
224
|
-
|
|
225
|
-
const isWebContainer = _nodeprocess().default.versions.webcontainer != null;
|
|
226
|
-
return (0, _getenv().boolish)('EXPO_NO_DEPENDENCY_VALIDATION', isWebContainer);
|
|
222
|
+
return (0, _getenv().boolish)('EXPO_NO_DEPENDENCY_VALIDATION', envIsHeadless());
|
|
227
223
|
}
|
|
228
224
|
/** Force Expo CLI to run in webcontainer mode, this has impact on which URL Expo is using by default */ get EXPO_FORCE_WEBCONTAINER_ENV() {
|
|
229
225
|
return (0, _getenv().boolish)('EXPO_FORCE_WEBCONTAINER_ENV', false);
|
|
@@ -249,7 +245,10 @@ class Env {
|
|
|
249
245
|
/**
|
|
250
246
|
* Enable Bonjour advertising of the Expo CLI on local networks
|
|
251
247
|
*/ get EXPO_UNSTABLE_BONJOUR() {
|
|
252
|
-
return (0, _getenv().boolish)('EXPO_UNSTABLE_BONJOUR',
|
|
248
|
+
return (0, _getenv().boolish)('EXPO_UNSTABLE_BONJOUR', !envIsHeadless());
|
|
249
|
+
}
|
|
250
|
+
/** @internal Configure other environment variables for headless operations */ get EXPO_UNSTABLE_HEADLESS() {
|
|
251
|
+
return (0, _getenv().boolish)('EXPO_UNSTABLE_HEADLESS', envIsWebcontainer());
|
|
253
252
|
}
|
|
254
253
|
}
|
|
255
254
|
const env = new Env();
|
|
@@ -257,5 +256,8 @@ function envIsWebcontainer() {
|
|
|
257
256
|
// See: https://github.com/unjs/std-env/blob/4b1e03c4efce58249858efc2cc5f5eac727d0adb/src/providers.ts#L134-L143
|
|
258
257
|
return env.EXPO_FORCE_WEBCONTAINER_ENV || _nodeprocess().default.env.SHELL === '/bin/jsh' && !!_nodeprocess().default.versions.webcontainer;
|
|
259
258
|
}
|
|
259
|
+
function envIsHeadless() {
|
|
260
|
+
return env.EXPO_UNSTABLE_HEADLESS;
|
|
261
|
+
}
|
|
260
262
|
|
|
261
263
|
//# sourceMappingURL=env.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/env.ts"],"sourcesContent":["import { boolish, int, string } from 'getenv';\nimport process from 'node:process';\n\n// @expo/webpack-config -> expo-pwa -> @expo/image-utils: EXPO_IMAGE_UTILS_NO_SHARP\n\n// TODO: EXPO_CLI_USERNAME, EXPO_CLI_PASSWORD\n\nclass Env {\n /** Enable profiling metrics */\n get EXPO_PROFILE() {\n return boolish('EXPO_PROFILE', false);\n }\n\n /** Enable debug logging */\n get EXPO_DEBUG() {\n return boolish('EXPO_DEBUG', false);\n }\n\n /** Disable all network requests */\n get EXPO_OFFLINE() {\n return boolish('EXPO_OFFLINE', false);\n }\n\n /** Enable the beta version of Expo (TODO: Should this just be in the beta version of expo releases?) */\n get EXPO_BETA() {\n return boolish('EXPO_BETA', false);\n }\n\n /** Enable staging API environment */\n get EXPO_STAGING() {\n return boolish('EXPO_STAGING', false);\n }\n\n /** Enable local API environment */\n get EXPO_LOCAL() {\n return boolish('EXPO_LOCAL', false);\n }\n\n /** Is running in non-interactive CI mode */\n get CI() {\n return boolish('CI', false);\n }\n\n /** Disable telemetry (analytics) */\n get EXPO_NO_TELEMETRY() {\n return boolish('EXPO_NO_TELEMETRY', false);\n }\n\n /** Disable detaching telemetry to separate process */\n get EXPO_NO_TELEMETRY_DETACH() {\n return boolish('EXPO_NO_TELEMETRY_DETACH', false);\n }\n\n /** local directory to the universe repo for testing locally */\n get EXPO_UNIVERSE_DIR() {\n return string('EXPO_UNIVERSE_DIR', '');\n }\n\n /** @deprecated Default Webpack host string */\n get WEB_HOST() {\n return string('WEB_HOST', '0.0.0.0');\n }\n\n /** Skip warning users about a dirty git status */\n get EXPO_NO_GIT_STATUS() {\n return boolish('EXPO_NO_GIT_STATUS', true);\n }\n /** Disable auto web setup */\n get EXPO_NO_WEB_SETUP() {\n return boolish('EXPO_NO_WEB_SETUP', false);\n }\n /** Disable auto TypeScript setup */\n get EXPO_NO_TYPESCRIPT_SETUP() {\n return boolish('EXPO_NO_TYPESCRIPT_SETUP', false);\n }\n /** Disable all API caches. Does not disable bundler caches. */\n get EXPO_NO_CACHE() {\n return boolish('EXPO_NO_CACHE', false);\n }\n /** Disable the app select redirect page. */\n get EXPO_NO_REDIRECT_PAGE() {\n return boolish('EXPO_NO_REDIRECT_PAGE', false);\n }\n /** The React Metro port that's baked into react-native scripts and tools. */\n get RCT_METRO_PORT() {\n return int('RCT_METRO_PORT', 0);\n }\n /** Skip validating the manifest during `export`. */\n get EXPO_SKIP_MANIFEST_VALIDATION_TOKEN(): boolean {\n return !!string('EXPO_SKIP_MANIFEST_VALIDATION_TOKEN', '');\n }\n\n /** Public folder path relative to the project root. Default to `public` */\n get EXPO_PUBLIC_FOLDER(): string {\n return string('EXPO_PUBLIC_FOLDER', 'public');\n }\n\n /** Higher priority `$EDIOTR` variable for indicating which editor to use when pressing `o` in the Terminal UI. */\n get EXPO_EDITOR(): string {\n return string('EXPO_EDITOR', '');\n }\n\n /**\n * Overwrite the dev server URL, disregarding the `--port`, `--host`, `--tunnel`, `--lan`, `--localhost` arguments.\n * This is useful for browser editors that require custom proxy URLs.\n */\n get EXPO_PACKAGER_PROXY_URL(): string {\n return string('EXPO_PACKAGER_PROXY_URL', '');\n }\n\n /**\n * **Experimental** - Disable using `exp.direct` as the hostname for\n * `--tunnel` connections. This enables **https://** forwarding which\n * can be used to test universal links on iOS.\n *\n * This may cause issues with `expo-linking` and Expo Go.\n *\n * Select the exact subdomain by passing a string value that is not one of: `true`, `false`, `1`, `0`.\n */\n get EXPO_TUNNEL_SUBDOMAIN(): string | boolean {\n const subdomain = string('EXPO_TUNNEL_SUBDOMAIN', '');\n if (['0', 'false', ''].includes(subdomain)) {\n return false;\n } else if (['1', 'true'].includes(subdomain)) {\n return true;\n }\n return subdomain;\n }\n\n /**\n * Force Expo CLI to use the [`resolver.resolverMainFields`](https://facebook.github.io/metro/docs/configuration/#resolvermainfields) from the project `metro.config.js` for all platforms.\n *\n * By default, Expo CLI will use `['browser', 'module', 'main']` (default for Webpack) for web and the user-defined main fields for other platforms.\n */\n get EXPO_METRO_NO_MAIN_FIELD_OVERRIDE(): boolean {\n return boolish('EXPO_METRO_NO_MAIN_FIELD_OVERRIDE', false);\n }\n\n /**\n * HTTP/HTTPS proxy to connect to for network requests. Configures [https-proxy-agent](https://www.npmjs.com/package/https-proxy-agent).\n */\n get HTTP_PROXY(): string {\n return process.env.HTTP_PROXY || process.env.http_proxy || '';\n }\n\n /**\n * Instructs a different Metro config to be loaded.\n * The path, according to metro-config, should be a path relative to the current working directory.\n * This flag is internal and was added for external tools.\n * @internal\n */\n get EXPO_OVERRIDE_METRO_CONFIG(): string | undefined {\n return process.env.EXPO_OVERRIDE_METRO_CONFIG?.trim() || undefined;\n }\n\n /**\n * Use the network inspector by overriding the metro inspector proxy with a custom version.\n * @deprecated This has been replaced by `@react-native/dev-middleware` and is now unused.\n */\n get EXPO_NO_INSPECTOR_PROXY(): boolean {\n return boolish('EXPO_NO_INSPECTOR_PROXY', false);\n }\n\n /** Disable lazy bundling in Metro bundler. */\n get EXPO_NO_METRO_LAZY() {\n return boolish('EXPO_NO_METRO_LAZY', false);\n }\n\n /**\n * Enable the unstable inverse dependency stack trace for Metro bundling errors.\n * @deprecated This will be removed in the future.\n */\n get EXPO_METRO_UNSTABLE_ERRORS() {\n return boolish('EXPO_METRO_UNSTABLE_ERRORS', true);\n }\n\n /** Enable the experimental sticky resolver for Metro (Uses Expo Autolinking results and applies them to Metro's resolution)\n * @deprecated Replaced by `exp.experiments.autolinkingModuleResolution`\n */\n get EXPO_USE_STICKY_RESOLVER() {\n return boolish('EXPO_USE_STICKY_RESOLVER', false);\n }\n\n /** Disable Environment Variable injection in client bundles. */\n get EXPO_NO_CLIENT_ENV_VARS(): boolean {\n return boolish('EXPO_NO_CLIENT_ENV_VARS', false);\n }\n\n /** Set the default `user` that should be passed to `--user` with ADB commands. Used for installing APKs on Android devices with multiple profiles. Defaults to `0`. */\n get EXPO_ADB_USER(): string {\n return string('EXPO_ADB_USER', '0');\n }\n\n /** Used internally to enable E2E utilities. This behavior is not stable to external users. */\n get __EXPO_E2E_TEST(): boolean {\n return boolish('__EXPO_E2E_TEST', false);\n }\n\n /** Unstable: Force single-bundle exports in production. */\n get EXPO_NO_BUNDLE_SPLITTING(): boolean {\n return boolish('EXPO_NO_BUNDLE_SPLITTING', false);\n }\n\n /**\n * Enable Atlas to gather bundle information during development or export.\n * Note, because this used to be an experimental feature, both `EXPO_ATLAS` and `EXPO_UNSTABLE_ATLAS` are supported.\n */\n get EXPO_ATLAS() {\n return boolish('EXPO_ATLAS', boolish('EXPO_UNSTABLE_ATLAS', false));\n }\n\n /** Unstable: Enable tree shaking for Metro. */\n get EXPO_UNSTABLE_TREE_SHAKING() {\n return boolish('EXPO_UNSTABLE_TREE_SHAKING', false);\n }\n\n /** Unstable: Enable eager bundling where transformation runs uncached after the entire bundle has been created. This is required for production tree shaking and less optimized for development bundling. */\n get EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH() {\n return boolish('EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH', false);\n }\n\n /** Enable the use of Expo's custom metro require implementation. The custom require supports better debugging, tree shaking, and React Server Components. */\n get EXPO_USE_METRO_REQUIRE() {\n return boolish('EXPO_USE_METRO_REQUIRE', false);\n }\n\n /** Internal key used to pass eager bundle data from the CLI to the native run scripts during `npx expo run` commands. */\n get __EXPO_EAGER_BUNDLE_OPTIONS() {\n return string('__EXPO_EAGER_BUNDLE_OPTIONS', '');\n }\n\n /** Disable server deployment during production builds (during `expo export:embed`). This is useful for testing API routes and server components against a local server. */\n get EXPO_NO_DEPLOY(): boolean {\n return boolish('EXPO_NO_DEPLOY', false);\n }\n\n /** Enable hydration during development when rendering Expo Web */\n get EXPO_WEB_DEV_HYDRATE(): boolean {\n return boolish('EXPO_WEB_DEV_HYDRATE', false);\n }\n\n /** Enable experimental React Server Functions support. */\n get EXPO_UNSTABLE_SERVER_FUNCTIONS(): boolean {\n return boolish('EXPO_UNSTABLE_SERVER_FUNCTIONS', false);\n }\n\n /** Enable unstable/experimental mode where React Native Web isn't required to run Expo apps on web. */\n get EXPO_NO_REACT_NATIVE_WEB(): boolean {\n return boolish('EXPO_NO_REACT_NATIVE_WEB', false);\n }\n\n /** Enable unstable/experimental support for deploying the native server in `npx expo run` commands. */\n get EXPO_UNSTABLE_DEPLOY_SERVER(): boolean {\n return boolish('EXPO_UNSTABLE_DEPLOY_SERVER', false);\n }\n\n /** Is running in EAS Build. This is set by EAS: https://docs.expo.dev/eas/environment-variables/ */\n get EAS_BUILD(): boolean {\n return boolish('EAS_BUILD', false);\n }\n\n /** Disable the React Native Directory compatibility check for new architecture when installing packages */\n get EXPO_NO_NEW_ARCH_COMPAT_CHECK(): boolean {\n return boolish('EXPO_NO_NEW_ARCH_COMPAT_CHECK', false);\n }\n\n /** Disable the dependency validation when installing other dependencies and starting the project */\n get EXPO_NO_DEPENDENCY_VALIDATION(): boolean {\n // Default to disabling when running in a web container (stackblitz, bolt, etc).\n const isWebContainer = process.versions.webcontainer != null;\n return boolish('EXPO_NO_DEPENDENCY_VALIDATION', isWebContainer);\n }\n\n /** Force Expo CLI to run in webcontainer mode, this has impact on which URL Expo is using by default */\n get EXPO_FORCE_WEBCONTAINER_ENV(): boolean {\n return boolish('EXPO_FORCE_WEBCONTAINER_ENV', false);\n }\n\n /** Force Expo CLI to run in webcontainer mode, this has impact on which URL Expo is using by default */\n get EXPO_UNSTABLE_WEB_MODAL(): boolean {\n return boolish('EXPO_UNSTABLE_WEB_MODAL', false);\n }\n\n /** Disable by falsy value live binding in experimental import export support. Enabled by default. */\n get EXPO_UNSTABLE_LIVE_BINDINGS(): boolean {\n return boolish('EXPO_UNSTABLE_LIVE_BINDINGS', true);\n }\n\n /**\n * Enable the experimental MCP integration or further specify the MCP server URL.\n */\n get EXPO_UNSTABLE_MCP_SERVER(): string {\n const value = string('EXPO_UNSTABLE_MCP_SERVER', '');\n if (value === '1' || value.toLowerCase() === 'true') {\n return this.EXPO_STAGING ? 'staging-mcp.expo.dev' : 'mcp.expo.dev';\n }\n return value;\n }\n\n /** Enable Expo Log Box for iOS and Android (Web is enabled by default) */\n get EXPO_UNSTABLE_LOG_BOX(): boolean {\n return boolish('EXPO_UNSTABLE_LOG_BOX', false);\n }\n\n /**\n * Enable Bonjour advertising of the Expo CLI on local networks\n */\n get EXPO_UNSTABLE_BONJOUR(): boolean {\n return boolish('EXPO_UNSTABLE_BONJOUR', false);\n }\n}\n\nexport const env = new Env();\n\nexport function envIsWebcontainer() {\n // See: https://github.com/unjs/std-env/blob/4b1e03c4efce58249858efc2cc5f5eac727d0adb/src/providers.ts#L134-L143\n return (\n env.EXPO_FORCE_WEBCONTAINER_ENV ||\n (process.env.SHELL === '/bin/jsh' && !!process.versions.webcontainer)\n );\n}\n"],"names":["env","envIsWebcontainer","Env","EXPO_PROFILE","boolish","EXPO_DEBUG","EXPO_OFFLINE","EXPO_BETA","EXPO_STAGING","EXPO_LOCAL","CI","EXPO_NO_TELEMETRY","EXPO_NO_TELEMETRY_DETACH","EXPO_UNIVERSE_DIR","string","WEB_HOST","EXPO_NO_GIT_STATUS","EXPO_NO_WEB_SETUP","EXPO_NO_TYPESCRIPT_SETUP","EXPO_NO_CACHE","EXPO_NO_REDIRECT_PAGE","RCT_METRO_PORT","int","EXPO_SKIP_MANIFEST_VALIDATION_TOKEN","EXPO_PUBLIC_FOLDER","EXPO_EDITOR","EXPO_PACKAGER_PROXY_URL","EXPO_TUNNEL_SUBDOMAIN","subdomain","includes","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","HTTP_PROXY","process","http_proxy","EXPO_OVERRIDE_METRO_CONFIG","trim","undefined","EXPO_NO_INSPECTOR_PROXY","EXPO_NO_METRO_LAZY","EXPO_METRO_UNSTABLE_ERRORS","EXPO_USE_STICKY_RESOLVER","EXPO_NO_CLIENT_ENV_VARS","EXPO_ADB_USER","__EXPO_E2E_TEST","EXPO_NO_BUNDLE_SPLITTING","EXPO_ATLAS","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","EXPO_USE_METRO_REQUIRE","__EXPO_EAGER_BUNDLE_OPTIONS","EXPO_NO_DEPLOY","EXPO_WEB_DEV_HYDRATE","EXPO_UNSTABLE_SERVER_FUNCTIONS","EXPO_NO_REACT_NATIVE_WEB","EXPO_UNSTABLE_DEPLOY_SERVER","EAS_BUILD","EXPO_NO_NEW_ARCH_COMPAT_CHECK","EXPO_NO_DEPENDENCY_VALIDATION","isWebContainer","versions","webcontainer","EXPO_FORCE_WEBCONTAINER_ENV","EXPO_UNSTABLE_WEB_MODAL","EXPO_UNSTABLE_LIVE_BINDINGS","EXPO_UNSTABLE_MCP_SERVER","value","toLowerCase","EXPO_UNSTABLE_LOG_BOX","EXPO_UNSTABLE_BONJOUR","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,GAAG,yBAAyB;QACtD;QACA,OAAOyD;IACT;IAEA,wEAAwE,GACxE,IAAIE,wBAAiC;QACnC,OAAO/D,IAAAA,iBAAO,EAAC,yBAAyB;IAC1C;IAEA;;GAEC,GACD,IAAIgE,wBAAiC;QACnC,OAAOhE,IAAAA,iBAAO,EAAC,yBAAyB;IAC1C;AACF;AAEO,MAAMJ,MAAM,IAAIE;AAEhB,SAASD;IACd,gHAAgH;IAChH,OACED,IAAI6D,2BAA2B,IAC9B7B,sBAAO,CAAChC,GAAG,CAACqE,KAAK,KAAK,cAAc,CAAC,CAACrC,sBAAO,CAAC2B,QAAQ,CAACC,YAAY;AAExE"}
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/env.ts"],"sourcesContent":["import { boolish, int, string } from 'getenv';\nimport process from 'node:process';\n\n// @expo/webpack-config -> expo-pwa -> @expo/image-utils: EXPO_IMAGE_UTILS_NO_SHARP\n\n// TODO: EXPO_CLI_USERNAME, EXPO_CLI_PASSWORD\n\nclass Env {\n /** Enable profiling metrics */\n get EXPO_PROFILE() {\n return boolish('EXPO_PROFILE', false);\n }\n\n /** Enable debug logging */\n get EXPO_DEBUG() {\n return boolish('EXPO_DEBUG', false);\n }\n\n /** Disable all network requests */\n get EXPO_OFFLINE() {\n return boolish('EXPO_OFFLINE', false);\n }\n\n /** Enable the beta version of Expo (TODO: Should this just be in the beta version of expo releases?) */\n get EXPO_BETA() {\n return boolish('EXPO_BETA', false);\n }\n\n /** Enable staging API environment */\n get EXPO_STAGING() {\n return boolish('EXPO_STAGING', false);\n }\n\n /** Enable local API environment */\n get EXPO_LOCAL() {\n return boolish('EXPO_LOCAL', false);\n }\n\n /** Is running in non-interactive CI mode */\n get CI() {\n return boolish('CI', false);\n }\n\n /** Disable telemetry (analytics) */\n get EXPO_NO_TELEMETRY() {\n return boolish('EXPO_NO_TELEMETRY', false);\n }\n\n /** Disable detaching telemetry to separate process */\n get EXPO_NO_TELEMETRY_DETACH() {\n return boolish('EXPO_NO_TELEMETRY_DETACH', false);\n }\n\n /** local directory to the universe repo for testing locally */\n get EXPO_UNIVERSE_DIR() {\n return string('EXPO_UNIVERSE_DIR', '');\n }\n\n /** @deprecated Default Webpack host string */\n get WEB_HOST() {\n return string('WEB_HOST', '0.0.0.0');\n }\n\n /** Skip warning users about a dirty git status */\n get EXPO_NO_GIT_STATUS() {\n return boolish('EXPO_NO_GIT_STATUS', true);\n }\n /** Disable auto web setup */\n get EXPO_NO_WEB_SETUP() {\n return boolish('EXPO_NO_WEB_SETUP', envIsHeadless());\n }\n /** Disable auto TypeScript setup */\n get EXPO_NO_TYPESCRIPT_SETUP() {\n return boolish('EXPO_NO_TYPESCRIPT_SETUP', false);\n }\n /** Disable all API caches. Does not disable bundler caches. */\n get EXPO_NO_CACHE() {\n return boolish('EXPO_NO_CACHE', false);\n }\n /** Disable the app select redirect page. */\n get EXPO_NO_REDIRECT_PAGE() {\n return boolish('EXPO_NO_REDIRECT_PAGE', false);\n }\n /** The React Metro port that's baked into react-native scripts and tools. */\n get RCT_METRO_PORT() {\n return int('RCT_METRO_PORT', 0);\n }\n /** Skip validating the manifest during `export`. */\n get EXPO_SKIP_MANIFEST_VALIDATION_TOKEN(): boolean {\n return !!string('EXPO_SKIP_MANIFEST_VALIDATION_TOKEN', '');\n }\n\n /** Public folder path relative to the project root. Default to `public` */\n get EXPO_PUBLIC_FOLDER(): string {\n return string('EXPO_PUBLIC_FOLDER', 'public');\n }\n\n /** Higher priority `$EDIOTR` variable for indicating which editor to use when pressing `o` in the Terminal UI. */\n get EXPO_EDITOR(): string {\n return string('EXPO_EDITOR', '');\n }\n\n /**\n * Overwrite the dev server URL, disregarding the `--port`, `--host`, `--tunnel`, `--lan`, `--localhost` arguments.\n * This is useful for browser editors that require custom proxy URLs.\n */\n get EXPO_PACKAGER_PROXY_URL(): string {\n return string('EXPO_PACKAGER_PROXY_URL', '');\n }\n\n /**\n * **Experimental** - Disable using `exp.direct` as the hostname for\n * `--tunnel` connections. This enables **https://** forwarding which\n * can be used to test universal links on iOS.\n *\n * This may cause issues with `expo-linking` and Expo Go.\n *\n * Select the exact subdomain by passing a string value that is not one of: `true`, `false`, `1`, `0`.\n */\n get EXPO_TUNNEL_SUBDOMAIN(): string | boolean {\n const subdomain = string('EXPO_TUNNEL_SUBDOMAIN', '');\n if (['0', 'false', ''].includes(subdomain)) {\n return false;\n } else if (['1', 'true'].includes(subdomain)) {\n return true;\n }\n return subdomain;\n }\n\n /**\n * Force Expo CLI to use the [`resolver.resolverMainFields`](https://facebook.github.io/metro/docs/configuration/#resolvermainfields) from the project `metro.config.js` for all platforms.\n *\n * By default, Expo CLI will use `['browser', 'module', 'main']` (default for Webpack) for web and the user-defined main fields for other platforms.\n */\n get EXPO_METRO_NO_MAIN_FIELD_OVERRIDE(): boolean {\n return boolish('EXPO_METRO_NO_MAIN_FIELD_OVERRIDE', false);\n }\n\n /**\n * HTTP/HTTPS proxy to connect to for network requests. Configures [https-proxy-agent](https://www.npmjs.com/package/https-proxy-agent).\n */\n get HTTP_PROXY(): string {\n return process.env.HTTP_PROXY || process.env.http_proxy || '';\n }\n\n /**\n * Instructs a different Metro config to be loaded.\n * The path, according to metro-config, should be a path relative to the current working directory.\n * This flag is internal and was added for external tools.\n * @internal\n */\n get EXPO_OVERRIDE_METRO_CONFIG(): string | undefined {\n return process.env.EXPO_OVERRIDE_METRO_CONFIG?.trim() || undefined;\n }\n\n /**\n * Use the network inspector by overriding the metro inspector proxy with a custom version.\n * @deprecated This has been replaced by `@react-native/dev-middleware` and is now unused.\n */\n get EXPO_NO_INSPECTOR_PROXY(): boolean {\n return boolish('EXPO_NO_INSPECTOR_PROXY', false);\n }\n\n /** Disable lazy bundling in Metro bundler. */\n get EXPO_NO_METRO_LAZY() {\n return boolish('EXPO_NO_METRO_LAZY', false);\n }\n\n /**\n * Enable the unstable inverse dependency stack trace for Metro bundling errors.\n * @deprecated This will be removed in the future.\n */\n get EXPO_METRO_UNSTABLE_ERRORS() {\n return boolish('EXPO_METRO_UNSTABLE_ERRORS', true);\n }\n\n /** Disable Environment Variable injection in client bundles. */\n get EXPO_NO_CLIENT_ENV_VARS(): boolean {\n return boolish('EXPO_NO_CLIENT_ENV_VARS', false);\n }\n\n /** Set the default `user` that should be passed to `--user` with ADB commands. Used for installing APKs on Android devices with multiple profiles. Defaults to `0`. */\n get EXPO_ADB_USER(): string {\n return string('EXPO_ADB_USER', '0');\n }\n\n /** Used internally to enable E2E utilities. This behavior is not stable to external users. */\n get __EXPO_E2E_TEST(): boolean {\n return boolish('__EXPO_E2E_TEST', false);\n }\n\n /** Unstable: Force single-bundle exports in production. */\n get EXPO_NO_BUNDLE_SPLITTING(): boolean {\n return boolish('EXPO_NO_BUNDLE_SPLITTING', false);\n }\n\n /**\n * Enable Atlas to gather bundle information during development or export.\n * Note, because this used to be an experimental feature, both `EXPO_ATLAS` and `EXPO_UNSTABLE_ATLAS` are supported.\n */\n get EXPO_ATLAS() {\n return boolish('EXPO_ATLAS', boolish('EXPO_UNSTABLE_ATLAS', false));\n }\n\n /** Unstable: Enable tree shaking for Metro. */\n get EXPO_UNSTABLE_TREE_SHAKING() {\n return boolish('EXPO_UNSTABLE_TREE_SHAKING', false);\n }\n\n /** Unstable: Enable eager bundling where transformation runs uncached after the entire bundle has been created. This is required for production tree shaking and less optimized for development bundling. */\n get EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH() {\n return boolish('EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH', false);\n }\n\n /** Enable the use of Expo's custom metro require implementation. The custom require supports better debugging, tree shaking, and React Server Components. */\n get EXPO_USE_METRO_REQUIRE() {\n return boolish('EXPO_USE_METRO_REQUIRE', false);\n }\n\n /** Internal key used to pass eager bundle data from the CLI to the native run scripts during `npx expo run` commands. */\n get __EXPO_EAGER_BUNDLE_OPTIONS() {\n return string('__EXPO_EAGER_BUNDLE_OPTIONS', '');\n }\n\n /** Disable server deployment during production builds (during `expo export:embed`). This is useful for testing API routes and server components against a local server. */\n get EXPO_NO_DEPLOY(): boolean {\n return boolish('EXPO_NO_DEPLOY', false);\n }\n\n /** Enable hydration during development when rendering Expo Web */\n get EXPO_WEB_DEV_HYDRATE(): boolean {\n return boolish('EXPO_WEB_DEV_HYDRATE', false);\n }\n\n /** Enable experimental React Server Functions support. */\n get EXPO_UNSTABLE_SERVER_FUNCTIONS(): boolean {\n return boolish('EXPO_UNSTABLE_SERVER_FUNCTIONS', false);\n }\n\n /** Enable unstable/experimental mode where React Native Web isn't required to run Expo apps on web. */\n get EXPO_NO_REACT_NATIVE_WEB(): boolean {\n return boolish('EXPO_NO_REACT_NATIVE_WEB', false);\n }\n\n /** Enable unstable/experimental support for deploying the native server in `npx expo run` commands. */\n get EXPO_UNSTABLE_DEPLOY_SERVER(): boolean {\n return boolish('EXPO_UNSTABLE_DEPLOY_SERVER', false);\n }\n\n /** Is running in EAS Build. This is set by EAS: https://docs.expo.dev/eas/environment-variables/ */\n get EAS_BUILD(): boolean {\n return boolish('EAS_BUILD', false);\n }\n\n /** Disable the React Native Directory compatibility check for new architecture when installing packages */\n get EXPO_NO_NEW_ARCH_COMPAT_CHECK(): boolean {\n return boolish('EXPO_NO_NEW_ARCH_COMPAT_CHECK', envIsHeadless());\n }\n\n /** Disable the dependency validation when installing other dependencies and starting the project */\n get EXPO_NO_DEPENDENCY_VALIDATION(): boolean {\n return boolish('EXPO_NO_DEPENDENCY_VALIDATION', envIsHeadless());\n }\n\n /** Force Expo CLI to run in webcontainer mode, this has impact on which URL Expo is using by default */\n get EXPO_FORCE_WEBCONTAINER_ENV(): boolean {\n return boolish('EXPO_FORCE_WEBCONTAINER_ENV', false);\n }\n\n /** Force Expo CLI to run in webcontainer mode, this has impact on which URL Expo is using by default */\n get EXPO_UNSTABLE_WEB_MODAL(): boolean {\n return boolish('EXPO_UNSTABLE_WEB_MODAL', false);\n }\n\n /** Disable by falsy value live binding in experimental import export support. Enabled by default. */\n get EXPO_UNSTABLE_LIVE_BINDINGS(): boolean {\n return boolish('EXPO_UNSTABLE_LIVE_BINDINGS', true);\n }\n\n /**\n * Enable the experimental MCP integration or further specify the MCP server URL.\n */\n get EXPO_UNSTABLE_MCP_SERVER(): string {\n const value = string('EXPO_UNSTABLE_MCP_SERVER', '');\n if (value === '1' || value.toLowerCase() === 'true') {\n return this.EXPO_STAGING ? 'staging-mcp.expo.dev' : 'mcp.expo.dev';\n }\n return value;\n }\n\n /** Enable Expo Log Box for iOS and Android (Web is enabled by default) */\n get EXPO_UNSTABLE_LOG_BOX(): boolean {\n return boolish('EXPO_UNSTABLE_LOG_BOX', false);\n }\n\n /**\n * Enable Bonjour advertising of the Expo CLI on local networks\n */\n get EXPO_UNSTABLE_BONJOUR(): boolean {\n return boolish('EXPO_UNSTABLE_BONJOUR', !envIsHeadless());\n }\n\n /** @internal Configure other environment variables for headless operations */\n get EXPO_UNSTABLE_HEADLESS() {\n return boolish('EXPO_UNSTABLE_HEADLESS', envIsWebcontainer());\n }\n}\n\nexport const env = new Env();\n\nexport function envIsWebcontainer() {\n // See: https://github.com/unjs/std-env/blob/4b1e03c4efce58249858efc2cc5f5eac727d0adb/src/providers.ts#L134-L143\n return (\n env.EXPO_FORCE_WEBCONTAINER_ENV ||\n (process.env.SHELL === '/bin/jsh' && !!process.versions.webcontainer)\n );\n}\n\nexport function envIsHeadless() {\n return env.EXPO_UNSTABLE_HEADLESS;\n}\n"],"names":["env","envIsHeadless","envIsWebcontainer","Env","EXPO_PROFILE","boolish","EXPO_DEBUG","EXPO_OFFLINE","EXPO_BETA","EXPO_STAGING","EXPO_LOCAL","CI","EXPO_NO_TELEMETRY","EXPO_NO_TELEMETRY_DETACH","EXPO_UNIVERSE_DIR","string","WEB_HOST","EXPO_NO_GIT_STATUS","EXPO_NO_WEB_SETUP","EXPO_NO_TYPESCRIPT_SETUP","EXPO_NO_CACHE","EXPO_NO_REDIRECT_PAGE","RCT_METRO_PORT","int","EXPO_SKIP_MANIFEST_VALIDATION_TOKEN","EXPO_PUBLIC_FOLDER","EXPO_EDITOR","EXPO_PACKAGER_PROXY_URL","EXPO_TUNNEL_SUBDOMAIN","subdomain","includes","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","HTTP_PROXY","process","http_proxy","EXPO_OVERRIDE_METRO_CONFIG","trim","undefined","EXPO_NO_INSPECTOR_PROXY","EXPO_NO_METRO_LAZY","EXPO_METRO_UNSTABLE_ERRORS","EXPO_NO_CLIENT_ENV_VARS","EXPO_ADB_USER","__EXPO_E2E_TEST","EXPO_NO_BUNDLE_SPLITTING","EXPO_ATLAS","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","EXPO_USE_METRO_REQUIRE","__EXPO_EAGER_BUNDLE_OPTIONS","EXPO_NO_DEPLOY","EXPO_WEB_DEV_HYDRATE","EXPO_UNSTABLE_SERVER_FUNCTIONS","EXPO_NO_REACT_NATIVE_WEB","EXPO_UNSTABLE_DEPLOY_SERVER","EAS_BUILD","EXPO_NO_NEW_ARCH_COMPAT_CHECK","EXPO_NO_DEPENDENCY_VALIDATION","EXPO_FORCE_WEBCONTAINER_ENV","EXPO_UNSTABLE_WEB_MODAL","EXPO_UNSTABLE_LIVE_BINDINGS","EXPO_UNSTABLE_MCP_SERVER","value","toLowerCase","EXPO_UNSTABLE_LOG_BOX","EXPO_UNSTABLE_BONJOUR","EXPO_UNSTABLE_HEADLESS","SHELL","versions","webcontainer"],"mappings":";;;;;;;;;;;IAoTaA,GAAG;eAAHA;;IAUGC,aAAa;eAAbA;;IARAC,iBAAiB;eAAjBA;;;;yBAtTqB;;;;;;;gEACjB;;;;;;;;;;;AAEpB,mFAAmF;AAEnF,6CAA6C;AAE7C,MAAMC;IACJ,6BAA6B,GAC7B,IAAIC,eAAe;QACjB,OAAOC,IAAAA,iBAAO,EAAC,gBAAgB;IACjC;IAEA,yBAAyB,GACzB,IAAIC,aAAa;QACf,OAAOD,IAAAA,iBAAO,EAAC,cAAc;IAC/B;IAEA,iCAAiC,GACjC,IAAIE,eA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SAASpE;IACd,OAAOD,IAAIkE,sBAAsB;AACnC"}
|
|
@@ -26,7 +26,7 @@ class FetchClient {
|
|
|
26
26
|
this.headers = {
|
|
27
27
|
accept: 'application/json',
|
|
28
28
|
'content-type': 'application/json',
|
|
29
|
-
'user-agent': `expo-cli/${"55.0.
|
|
29
|
+
'user-agent': `expo-cli/${"55.0.7"}`,
|
|
30
30
|
authorization: 'Basic ' + _nodebuffer().Buffer.from(`${target}:`).toString('base64')
|
|
31
31
|
};
|
|
32
32
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@expo/cli",
|
|
3
|
-
"version": "55.0.
|
|
3
|
+
"version": "55.0.7",
|
|
4
4
|
"description": "The Expo CLI",
|
|
5
5
|
"main": "build/bin/cli",
|
|
6
6
|
"bin": {
|
|
@@ -44,12 +44,12 @@
|
|
|
44
44
|
"@expo/config": "~55.0.4",
|
|
45
45
|
"@expo/config-plugins": "~55.0.4",
|
|
46
46
|
"@expo/devcert": "^1.2.1",
|
|
47
|
-
"@expo/env": "~2.0
|
|
47
|
+
"@expo/env": "~2.1.0",
|
|
48
48
|
"@expo/image-utils": "^0.8.12",
|
|
49
49
|
"@expo/json-file": "^10.0.12",
|
|
50
|
-
"@expo/log-box": "55.0.
|
|
50
|
+
"@expo/log-box": "55.0.6",
|
|
51
51
|
"@expo/metro": "~54.2.0",
|
|
52
|
-
"@expo/metro-config": "~55.0.
|
|
52
|
+
"@expo/metro-config": "~55.0.5",
|
|
53
53
|
"@expo/osascript": "^2.4.2",
|
|
54
54
|
"@expo/package-manager": "^1.10.3",
|
|
55
55
|
"@expo/plist": "^0.5.2",
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
"dnssd-advertise": "^1.1.1",
|
|
74
74
|
"env-editor": "^0.4.1",
|
|
75
75
|
"expo-server": "^55.0.3",
|
|
76
|
-
"fetch-nodeshim": "^0.4.
|
|
76
|
+
"fetch-nodeshim": "^0.4.5",
|
|
77
77
|
"getenv": "^2.0.0",
|
|
78
78
|
"glob": "^13.0.0",
|
|
79
79
|
"lan-network": "^0.1.6",
|
|
@@ -160,5 +160,5 @@
|
|
|
160
160
|
"tree-kill": "^1.2.2",
|
|
161
161
|
"tsd": "^0.28.1"
|
|
162
162
|
},
|
|
163
|
-
"gitHead": "
|
|
163
|
+
"gitHead": "cd3638bb85f9560392acfd5160a266cf97880b3b"
|
|
164
164
|
}
|