@expo/cli 55.0.3 → 55.0.5
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/graphql/client.js +133 -68
- package/build/src/api/graphql/client.js.map +1 -1
- package/build/src/api/graphql/queries/AppQuery.js +21 -25
- package/build/src/api/graphql/queries/AppQuery.js.map +1 -1
- package/build/src/api/graphql/queries/UserQuery.js +45 -38
- package/build/src/api/graphql/queries/UserQuery.js.map +1 -1
- package/build/src/api/rest/cache/FileSystemResponseCache.js.map +1 -1
- package/build/src/api/rest/cache/ResponseCache.js.map +1 -1
- package/build/src/api/rest/cache/wrapFetchWithCache.js +7 -7
- package/build/src/api/rest/cache/wrapFetchWithCache.js.map +1 -1
- package/build/src/api/rest/client.js +3 -7
- package/build/src/api/rest/client.js.map +1 -1
- package/build/src/api/rest/wrapFetchWithProgress.js +1 -8
- package/build/src/api/rest/wrapFetchWithProgress.js.map +1 -1
- package/build/src/api/user/user.js +6 -36
- package/build/src/api/user/user.js.map +1 -1
- package/build/src/prebuild/renameTemplateAppName.js +2 -6
- package/build/src/prebuild/renameTemplateAppName.js.map +1 -1
- package/build/src/prebuild/resolveLocalTemplate.js +2 -4
- package/build/src/prebuild/resolveLocalTemplate.js.map +1 -1
- package/build/src/prebuild/resolveTemplate.js +13 -17
- package/build/src/prebuild/resolveTemplate.js.map +1 -1
- package/build/src/prebuild/updateFromTemplate.js +4 -6
- package/build/src/prebuild/updateFromTemplate.js.map +1 -1
- package/build/src/start/doctor/ngrok/ExternalModule.js +2 -8
- package/build/src/start/doctor/ngrok/ExternalModule.js.map +1 -1
- package/build/src/start/server/metro/DevToolsPluginWebsocketEndpoint.js +1 -9
- package/build/src/start/server/metro/DevToolsPluginWebsocketEndpoint.js.map +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +13 -8
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/createServerComponentsMiddleware.js +4 -14
- package/build/src/start/server/metro/createServerComponentsMiddleware.js.map +1 -1
- package/build/src/start/server/metro/createServerRouteMiddleware.js +17 -0
- package/build/src/start/server/metro/createServerRouteMiddleware.js.map +1 -1
- package/build/src/start/server/metro/fetchRouterManifest.js +1 -13
- package/build/src/start/server/metro/fetchRouterManifest.js.map +1 -1
- package/build/src/start/server/metro/instantiateMetro.js +1 -3
- package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
- package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js +47 -34
- package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/ManifestMiddleware.js +27 -4
- package/build/src/start/server/middleware/ManifestMiddleware.js.map +1 -1
- package/build/src/start/server/type-generation/routes.js +2 -62
- package/build/src/start/server/type-generation/routes.js.map +1 -1
- package/build/src/utils/build-cache-providers/index.js +1 -1
- package/build/src/utils/build-cache-providers/index.js.map +1 -1
- package/build/src/utils/codesigning.js +3 -17
- package/build/src/utils/codesigning.js.map +1 -1
- package/build/src/utils/createFileTransform.js +3 -38
- package/build/src/utils/createFileTransform.js.map +1 -1
- package/build/src/utils/downloadAppAsync.js +1 -12
- package/build/src/utils/downloadAppAsync.js.map +1 -1
- package/build/src/utils/fetch.js +23 -4
- package/build/src/utils/fetch.js.map +1 -1
- package/build/src/utils/freeport.js +21 -5
- package/build/src/utils/freeport.js.map +1 -1
- package/build/src/utils/getOrPromptApplicationId.js +2 -15
- package/build/src/utils/getOrPromptApplicationId.js.map +1 -1
- package/build/src/utils/npm.js +60 -65
- package/build/src/utils/npm.js.map +1 -1
- package/build/src/utils/port.js +4 -4
- package/build/src/utils/port.js.map +1 -1
- package/build/src/utils/resolveGlobal.js +195 -0
- package/build/src/utils/resolveGlobal.js.map +1 -0
- package/build/src/utils/tar.js +138 -69
- package/build/src/utils/tar.js.map +1 -1
- package/build/src/utils/telemetry/clients/FetchClient.js +12 -24
- package/build/src/utils/telemetry/clients/FetchClient.js.map +1 -1
- package/build/src/utils/telemetry/utils/context.js +1 -1
- package/package.json +18 -28
- package/build/src/api/graphql/types/App.js +0 -29
- package/build/src/api/graphql/types/App.js.map +0 -1
- package/build/src/api/rest/wrapFetchWithProxy.js +0 -31
- package/build/src/api/rest/wrapFetchWithProxy.js.map +0 -1
- package/build/src/graphql/generated.js +0 -1196
- package/build/src/graphql/generated.js.map +0 -1
- package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.js +0 -85
- package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.js.map +0 -1
- package/build/src/utils/multipartMixed.js +0 -56
- package/build/src/utils/multipartMixed.js.map +0 -1
|
@@ -42,7 +42,6 @@ const _wrapFetchWithCache = require("./cache/wrapFetchWithCache");
|
|
|
42
42
|
const _wrapFetchWithBaseUrl = require("./wrapFetchWithBaseUrl");
|
|
43
43
|
const _wrapFetchWithOffline = require("./wrapFetchWithOffline");
|
|
44
44
|
const _wrapFetchWithProgress = require("./wrapFetchWithProgress");
|
|
45
|
-
const _wrapFetchWithProxy = require("./wrapFetchWithProxy");
|
|
46
45
|
const _wrapFetchWithUserAgent = require("./wrapFetchWithUserAgent");
|
|
47
46
|
const _env = require("../../utils/env");
|
|
48
47
|
const _errors = require("../../utils/errors");
|
|
@@ -126,9 +125,7 @@ function wrapFetchWithCredentials(fetchFunction) {
|
|
|
126
125
|
return response;
|
|
127
126
|
} catch (error) {
|
|
128
127
|
// When running `expo start`, but wifi or internet has issues
|
|
129
|
-
if (isNetworkError(error) ||
|
|
130
|
-
'cause' in error && isNetworkError(error.cause) // undici error handling
|
|
131
|
-
) {
|
|
128
|
+
if (isNetworkError(error) || 'cause' in error && isNetworkError(error.cause)) {
|
|
132
129
|
(0, _settings.disableNetwork)();
|
|
133
130
|
throw new _errors.CommandError('OFFLINE', 'Network connection is unreliable. Try again with the environment variable `EXPO_OFFLINE=1` to skip network requests.');
|
|
134
131
|
}
|
|
@@ -154,8 +151,7 @@ function wrapFetchWithCredentials(fetchFunction) {
|
|
|
154
151
|
}
|
|
155
152
|
const fetchWithOffline = (0, _wrapFetchWithOffline.wrapFetchWithOffline)((0, _wrapFetchWithUserAgent.wrapFetchWithUserAgent)(_fetch.fetch));
|
|
156
153
|
const fetchWithBaseUrl = (0, _wrapFetchWithBaseUrl.wrapFetchWithBaseUrl)(fetchWithOffline, (0, _endpoint.getExpoApiBaseUrl)() + '/v2/');
|
|
157
|
-
const
|
|
158
|
-
const fetchWithCredentials = (0, _wrapFetchWithProgress.wrapFetchWithProgress)(wrapFetchWithCredentials(fetchWithProxy));
|
|
154
|
+
const fetchWithCredentials = (0, _wrapFetchWithProgress.wrapFetchWithProgress)(wrapFetchWithCredentials(fetchWithBaseUrl));
|
|
159
155
|
function createCachedFetch({ fetch = fetchWithCredentials, cacheDirectory, ttl, skipCache }) {
|
|
160
156
|
// Disable all caching in EXPO_BETA.
|
|
161
157
|
if (skipCache || _env.env.EXPO_BETA || _env.env.EXPO_NO_CACHE) {
|
|
@@ -167,6 +163,6 @@ function createCachedFetch({ fetch = fetchWithCredentials, cacheDirectory, ttl,
|
|
|
167
163
|
ttl
|
|
168
164
|
}));
|
|
169
165
|
}
|
|
170
|
-
const fetchAsync = (0, _wrapFetchWithProgress.wrapFetchWithProgress)(wrapFetchWithCredentials(
|
|
166
|
+
const fetchAsync = (0, _wrapFetchWithProgress.wrapFetchWithProgress)(wrapFetchWithCredentials(fetchWithBaseUrl));
|
|
171
167
|
|
|
172
168
|
//# sourceMappingURL=client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/api/rest/client.ts"],"sourcesContent":["import type { JSONValue } from '@expo/json-file';\nimport path from 'path';\n\nimport { wrapFetchWithCache } from './cache/wrapFetchWithCache';\nimport type { FetchLike } from './client.types';\nimport { wrapFetchWithBaseUrl } from './wrapFetchWithBaseUrl';\nimport { wrapFetchWithOffline } from './wrapFetchWithOffline';\nimport { wrapFetchWithProgress } from './wrapFetchWithProgress';\nimport { wrapFetchWithProxy } from './wrapFetchWithProxy';\nimport { wrapFetchWithUserAgent } from './wrapFetchWithUserAgent';\nimport { env } from '../../utils/env';\nimport { CommandError } from '../../utils/errors';\nimport { fetch } from '../../utils/fetch';\nimport { getExpoApiBaseUrl } from '../endpoint';\nimport { disableNetwork } from '../settings';\nimport { getAccessToken, getExpoHomeDirectory, getSession } from '../user/UserSettings';\n\nexport class ApiV2Error extends Error {\n readonly name = 'ApiV2Error';\n readonly code: string;\n readonly expoApiV2ErrorCode: string;\n readonly expoApiV2ErrorDetails?: JSONValue;\n readonly expoApiV2ErrorServerStack?: string;\n readonly expoApiV2ErrorMetadata?: object;\n readonly expoApiV2RequestId?: string;\n\n constructor(response: {\n message: string;\n code: string;\n stack?: string;\n details?: JSONValue;\n metadata?: object;\n requestId: string;\n }) {\n super(response.message);\n this.code = response.code;\n this.expoApiV2ErrorCode = response.code;\n this.expoApiV2ErrorDetails = response.details;\n this.expoApiV2ErrorServerStack = response.stack;\n this.expoApiV2ErrorMetadata = response.metadata;\n this.expoApiV2RequestId = response.requestId;\n }\n\n toString() {\n return `${super.toString()}${env.EXPO_DEBUG && this.expoApiV2RequestId ? ` (Request Id: ${this.expoApiV2RequestId})` : ''}`;\n }\n}\n\n/**\n * An Expo server error that didn't return the expected error JSON information.\n * The only 'expected' place for this is in testing, all other cases are bugs with the server.\n */\nexport class UnexpectedServerError extends Error {\n readonly name = 'UnexpectedServerError';\n}\n\n/**\n * An error defining that the server didn't return the expected error JSON information.\n * The only 'expected' place for this is in testing, all other cases are bugs with the client.\n */\nexport class UnexpectedServerData extends Error {\n readonly name = 'UnexpectedServerData';\n}\n\n/** Validate the response json contains `.data` property, or throw an unexpected server data error */\nexport function getResponseDataOrThrow<T = any>(json: unknown): T {\n if (!!json && typeof json === 'object' && 'data' in json) {\n return json.data as T;\n }\n\n throw new UnexpectedServerData(\n !!json && typeof json === 'object' ? JSON.stringify(json) : 'Unknown data received from server.'\n );\n}\n\n/**\n * @returns a `fetch` function that will inject user authentication information and handle errors from the Expo API.\n */\nexport function wrapFetchWithCredentials(fetchFunction: FetchLike): FetchLike {\n return async function fetchWithCredentials(url, options = {}) {\n if (Array.isArray(options.headers)) {\n throw new Error('request headers must be in object form');\n }\n\n const resolvedHeaders = options.headers ?? ({} as any);\n\n const token = getAccessToken();\n if (token) {\n resolvedHeaders.authorization = `Bearer ${token}`;\n } else {\n const sessionSecret = getSession()?.sessionSecret;\n if (sessionSecret) {\n resolvedHeaders['expo-session'] = sessionSecret;\n }\n }\n\n try {\n const response = await fetchFunction(url, {\n ...options,\n headers: resolvedHeaders,\n });\n\n // Handle expected API errors (4xx)\n if (response.status >= 400 && response.status < 500) {\n const body = await response.text();\n try {\n const data = JSON.parse(body);\n if (data?.errors?.length) {\n throw new ApiV2Error(data.errors[0]);\n }\n } catch (error: any) {\n // Server returned non-json response.\n if (error.message.includes('in JSON at position')) {\n throw new UnexpectedServerError(body);\n }\n throw error;\n }\n }\n\n return response;\n } catch (error: any) {\n // When running `expo start`, but wifi or internet has issues\n if (\n isNetworkError(error) || // node-fetch error handling\n ('cause' in error && isNetworkError(error.cause)) // undici error handling\n ) {\n disableNetwork();\n\n throw new CommandError(\n 'OFFLINE',\n 'Network connection is unreliable. Try again with the environment variable `EXPO_OFFLINE=1` to skip network requests.'\n );\n }\n\n throw error;\n }\n };\n}\n\n/**\n * Determine if the provided error is related to a network issue.\n * When this returns true, offline mode should be enabled.\n * - `ENOTFOUND` is thrown when the DNS lookup failed\n * - `EAI_AGAIN` is thrown when DNS lookup failed due to a server-side error\n * - `UND_ERR_CONNECT_TIMEOUT` is thrown after DNS is resolved, but server can't be reached\n *\n * @see https://nodejs.org/api/errors.html\n * @see https://github.com/nodejs/undici#network-address-family-autoselection\n */\nfunction isNetworkError(error: Error & { code?: string }) {\n return (\n 'code' in error &&\n error.code &&\n ['ENOTFOUND', 'EAI_AGAIN', 'UND_ERR_CONNECT_TIMEOUT'].includes(error.code)\n );\n}\n\nconst fetchWithOffline = wrapFetchWithOffline(wrapFetchWithUserAgent(fetch));\n\nconst fetchWithBaseUrl = wrapFetchWithBaseUrl(fetchWithOffline, getExpoApiBaseUrl() + '/v2/');\n\nconst fetchWithProxy = wrapFetchWithProxy(fetchWithBaseUrl);\n\nconst fetchWithCredentials = wrapFetchWithProgress(wrapFetchWithCredentials(fetchWithProxy));\n\n/**\n * Create an instance of the fully qualified fetch command (auto authentication and api) but with caching in the '~/.expo' directory.\n * Caching is disabled automatically if the EXPO_NO_CACHE or EXPO_BETA environment variables are enabled.\n */\nexport function createCachedFetch({\n fetch = fetchWithCredentials,\n cacheDirectory,\n ttl,\n skipCache,\n}: {\n fetch?: FetchLike;\n cacheDirectory: string;\n ttl?: number;\n skipCache?: boolean;\n}): FetchLike {\n // Disable all caching in EXPO_BETA.\n if (skipCache || env.EXPO_BETA || env.EXPO_NO_CACHE) {\n return fetch;\n }\n\n const { FileSystemResponseCache } =\n require('./cache/FileSystemResponseCache') as typeof import('./cache/FileSystemResponseCache');\n\n return wrapFetchWithCache(\n fetch,\n new FileSystemResponseCache({\n cacheDirectory: path.join(getExpoHomeDirectory(), cacheDirectory),\n ttl,\n })\n );\n}\n\n/** Instance of fetch with automatic base URL pointing to the Expo API, user credential injection, and API error handling. Caching not included. */\nexport const fetchAsync = wrapFetchWithProgress(wrapFetchWithCredentials(fetchWithProxy));\n"],"names":["ApiV2Error","UnexpectedServerData","UnexpectedServerError","createCachedFetch","fetchAsync","getResponseDataOrThrow","wrapFetchWithCredentials","Error","constructor","response","message","name","code","expoApiV2ErrorCode","expoApiV2ErrorDetails","details","expoApiV2ErrorServerStack","stack","expoApiV2ErrorMetadata","metadata","expoApiV2RequestId","requestId","toString","env","EXPO_DEBUG","json","data","JSON","stringify","fetchFunction","fetchWithCredentials","url","options","Array","isArray","headers","resolvedHeaders","token","getAccessToken","authorization","getSession","sessionSecret","status","body","text","parse","errors","length","error","includes","isNetworkError","cause","disableNetwork","CommandError","fetchWithOffline","wrapFetchWithOffline","wrapFetchWithUserAgent","fetch","fetchWithBaseUrl","wrapFetchWithBaseUrl","getExpoApiBaseUrl","fetchWithProxy","wrapFetchWithProxy","wrapFetchWithProgress","cacheDirectory","ttl","skipCache","EXPO_BETA","EXPO_NO_CACHE","FileSystemResponseCache","require","wrapFetchWithCache","path","join","getExpoHomeDirectory"],"mappings":";;;;;;;;;;;IAiBaA,UAAU;eAAVA;;IA2CAC,oBAAoB;eAApBA;;IARAC,qBAAqB;eAArBA;;IAqHGC,iBAAiB;eAAjBA;;IA6BHC,UAAU;eAAVA;;IArIGC,sBAAsB;eAAtBA;;IAaAC,wBAAwB;eAAxBA;;;;gEA7EC;;;;;;oCAEkB;sCAEE;sCACA;uCACC;oCACH;wCACI;qBACnB;wBACS;uBACP;0BACY;0BACH;8BACkC;;;;;;AAE1D,MAAMN,mBAAmBO;IAS9BC,YAAYC,QAOX,CAAE;QACD,KAAK,CAACA,SAASC,OAAO,QAhBfC,OAAO;QAiBd,IAAI,CAACC,IAAI,GAAGH,SAASG,IAAI;QACzB,IAAI,CAACC,kBAAkB,GAAGJ,SAASG,IAAI;QACvC,IAAI,CAACE,qBAAqB,GAAGL,SAASM,OAAO;QAC7C,IAAI,CAACC,yBAAyB,GAAGP,SAASQ,KAAK;QAC/C,IAAI,CAACC,sBAAsB,GAAGT,SAASU,QAAQ;QAC/C,IAAI,CAACC,kBAAkB,GAAGX,SAASY,SAAS;IAC9C;IAEAC,WAAW;QACT,OAAO,GAAG,KAAK,CAACA,aAAaC,QAAG,CAACC,UAAU,IAAI,IAAI,CAACJ,kBAAkB,GAAG,CAAC,cAAc,EAAE,IAAI,CAACA,kBAAkB,CAAC,CAAC,CAAC,GAAG,IAAI;IAC7H;AACF;AAMO,MAAMlB,8BAA8BK;;QAApC,qBACII,OAAO;;AAClB;AAMO,MAAMV,6BAA6BM;;QAAnC,qBACII,OAAO;;AAClB;AAGO,SAASN,uBAAgCoB,IAAa;IAC3D,IAAI,CAAC,CAACA,QAAQ,OAAOA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,OAAOvC;QACT,EAAE,OAAOuC,OAAY;YACnB,6DAA6D;YAC7D,IACEE,eAAeF,UAAU,4BAA4B;YACpD,WAAWA,SAASE,eAAeF,MAAMG,KAAK,EAAG,wBAAwB;cAC1E;gBACAC,IAAAA,wBAAc;gBAEd,MAAM,IAAIC,oBAAY,CACpB,WACA;YAEJ;YAEA,MAAML;QACR;IACF;AACF;AAEA;;;;;;;;;CASC,GACD,SAASE,eAAeF,KAAgC;IACtD,OACE,UAAUA,SACVA,MAAMpC,IAAI,IACV;QAAC;QAAa;QAAa;KAA0B,CAACqC,QAAQ,CAACD,MAAMpC,IAAI;AAE7E;AAEA,MAAM0C,mBAAmBC,IAAAA,0CAAoB,EAACC,IAAAA,8CAAsB,EAACC,YAAK;AAE1E,MAAMC,mBAAmBC,IAAAA,0CAAoB,EAACL,kBAAkBM,IAAAA,2BAAiB,MAAK;AAEtF,MAAMC,iBAAiBC,IAAAA,sCAAkB,EAACJ;AAE1C,MAAM5B,uBAAuBiC,IAAAA,4CAAqB,EAACzD,yBAAyBuD;AAMrE,SAAS1D,kBAAkB,EAChCsD,QAAQ3B,oBAAoB,EAC5BkC,cAAc,EACdC,GAAG,EACHC,SAAS,EAMV;IACC,oCAAoC;IACpC,IAAIA,aAAa3C,QAAG,CAAC4C,SAAS,IAAI5C,QAAG,CAAC6C,aAAa,EAAE;QACnD,OAAOX;IACT;IAEA,MAAM,EAAEY,uBAAuB,EAAE,GAC/BC,QAAQ;IAEV,OAAOC,IAAAA,sCAAkB,EACvBd,OACA,IAAIY,wBAAwB;QAC1BL,gBAAgBQ,eAAI,CAACC,IAAI,CAACC,IAAAA,kCAAoB,KAAIV;QAClDC;IACF;AAEJ;AAGO,MAAM7D,aAAa2D,IAAAA,4CAAqB,EAACzD,yBAAyBuD"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/api/rest/client.ts"],"sourcesContent":["import type { JSONValue } from '@expo/json-file';\nimport path from 'path';\n\nimport { wrapFetchWithCache } from './cache/wrapFetchWithCache';\nimport type { FetchLike } from './client.types';\nimport { wrapFetchWithBaseUrl } from './wrapFetchWithBaseUrl';\nimport { wrapFetchWithOffline } from './wrapFetchWithOffline';\nimport { wrapFetchWithProgress } from './wrapFetchWithProgress';\nimport { wrapFetchWithUserAgent } from './wrapFetchWithUserAgent';\nimport { env } from '../../utils/env';\nimport { CommandError } from '../../utils/errors';\nimport { fetch } from '../../utils/fetch';\nimport { getExpoApiBaseUrl } from '../endpoint';\nimport { disableNetwork } from '../settings';\nimport { getAccessToken, getExpoHomeDirectory, getSession } from '../user/UserSettings';\n\nexport class ApiV2Error extends Error {\n readonly name = 'ApiV2Error';\n readonly code: string;\n readonly expoApiV2ErrorCode: string;\n readonly expoApiV2ErrorDetails?: JSONValue;\n readonly expoApiV2ErrorServerStack?: string;\n readonly expoApiV2ErrorMetadata?: object;\n readonly expoApiV2RequestId?: string;\n\n constructor(response: {\n message: string;\n code: string;\n stack?: string;\n details?: JSONValue;\n metadata?: object;\n requestId: string;\n }) {\n super(response.message);\n this.code = response.code;\n this.expoApiV2ErrorCode = response.code;\n this.expoApiV2ErrorDetails = response.details;\n this.expoApiV2ErrorServerStack = response.stack;\n this.expoApiV2ErrorMetadata = response.metadata;\n this.expoApiV2RequestId = response.requestId;\n }\n\n toString() {\n return `${super.toString()}${env.EXPO_DEBUG && this.expoApiV2RequestId ? ` (Request Id: ${this.expoApiV2RequestId})` : ''}`;\n }\n}\n\n/**\n * An Expo server error that didn't return the expected error JSON information.\n * The only 'expected' place for this is in testing, all other cases are bugs with the server.\n */\nexport class UnexpectedServerError extends Error {\n readonly name = 'UnexpectedServerError';\n}\n\n/**\n * An error defining that the server didn't return the expected error JSON information.\n * The only 'expected' place for this is in testing, all other cases are bugs with the client.\n */\nexport class UnexpectedServerData extends Error {\n readonly name = 'UnexpectedServerData';\n}\n\n/** Validate the response json contains `.data` property, or throw an unexpected server data error */\nexport function getResponseDataOrThrow<T = any>(json: unknown): T {\n if (!!json && typeof json === 'object' && 'data' in json) {\n return json.data as T;\n }\n\n throw new UnexpectedServerData(\n !!json && typeof json === 'object' ? JSON.stringify(json) : 'Unknown data received from server.'\n );\n}\n\n/**\n * @returns a `fetch` function that will inject user authentication information and handle errors from the Expo API.\n */\nexport function wrapFetchWithCredentials(fetchFunction: FetchLike): FetchLike {\n return async function fetchWithCredentials(url, options = {}) {\n if (Array.isArray(options.headers)) {\n throw new Error('request headers must be in object form');\n }\n\n const resolvedHeaders = options.headers ?? ({} as any);\n\n const token = getAccessToken();\n if (token) {\n resolvedHeaders.authorization = `Bearer ${token}`;\n } else {\n const sessionSecret = getSession()?.sessionSecret;\n if (sessionSecret) {\n resolvedHeaders['expo-session'] = sessionSecret;\n }\n }\n\n try {\n const response = await fetchFunction(url, {\n ...options,\n headers: resolvedHeaders,\n });\n\n // Handle expected API errors (4xx)\n if (response.status >= 400 && response.status < 500) {\n const body = await response.text();\n try {\n const data = JSON.parse(body);\n if (data?.errors?.length) {\n throw new ApiV2Error(data.errors[0]);\n }\n } catch (error: any) {\n // Server returned non-json response.\n if (error.message.includes('in JSON at position')) {\n throw new UnexpectedServerError(body);\n }\n throw error;\n }\n }\n\n return response;\n } catch (error: any) {\n // When running `expo start`, but wifi or internet has issues\n if (isNetworkError(error) || ('cause' in error && isNetworkError(error.cause))) {\n disableNetwork();\n\n throw new CommandError(\n 'OFFLINE',\n 'Network connection is unreliable. Try again with the environment variable `EXPO_OFFLINE=1` to skip network requests.'\n );\n }\n\n throw error;\n }\n };\n}\n\n/**\n * Determine if the provided error is related to a network issue.\n * When this returns true, offline mode should be enabled.\n * - `ENOTFOUND` is thrown when the DNS lookup failed\n * - `EAI_AGAIN` is thrown when DNS lookup failed due to a server-side error\n * - `UND_ERR_CONNECT_TIMEOUT` is thrown after DNS is resolved, but server can't be reached\n *\n * @see https://nodejs.org/api/errors.html\n * @see https://github.com/nodejs/undici#network-address-family-autoselection\n */\nfunction isNetworkError(error: Error & { code?: string }) {\n return (\n 'code' in error &&\n error.code &&\n ['ENOTFOUND', 'EAI_AGAIN', 'UND_ERR_CONNECT_TIMEOUT'].includes(error.code)\n );\n}\n\nconst fetchWithOffline = wrapFetchWithOffline(wrapFetchWithUserAgent(fetch));\n\nconst fetchWithBaseUrl = wrapFetchWithBaseUrl(fetchWithOffline, getExpoApiBaseUrl() + '/v2/');\n\nconst fetchWithCredentials = wrapFetchWithProgress(wrapFetchWithCredentials(fetchWithBaseUrl));\n\n/**\n * Create an instance of the fully qualified fetch command (auto authentication and api) but with caching in the '~/.expo' directory.\n * Caching is disabled automatically if the EXPO_NO_CACHE or EXPO_BETA environment variables are enabled.\n */\nexport function createCachedFetch({\n fetch = fetchWithCredentials,\n cacheDirectory,\n ttl,\n skipCache,\n}: {\n fetch?: FetchLike;\n cacheDirectory: string;\n ttl?: number;\n skipCache?: boolean;\n}): FetchLike {\n // Disable all caching in EXPO_BETA.\n if (skipCache || env.EXPO_BETA || env.EXPO_NO_CACHE) {\n return fetch;\n }\n\n const { FileSystemResponseCache } =\n require('./cache/FileSystemResponseCache') as typeof import('./cache/FileSystemResponseCache');\n\n return wrapFetchWithCache(\n fetch,\n new FileSystemResponseCache({\n cacheDirectory: path.join(getExpoHomeDirectory(), cacheDirectory),\n ttl,\n })\n );\n}\n\n/** Instance of fetch with automatic base URL pointing to the Expo API, user credential injection, and API error handling. Caching not included. */\nexport const fetchAsync = wrapFetchWithProgress(wrapFetchWithCredentials(fetchWithBaseUrl));\n"],"names":["ApiV2Error","UnexpectedServerData","UnexpectedServerError","createCachedFetch","fetchAsync","getResponseDataOrThrow","wrapFetchWithCredentials","Error","constructor","response","message","name","code","expoApiV2ErrorCode","expoApiV2ErrorDetails","details","expoApiV2ErrorServerStack","stack","expoApiV2ErrorMetadata","metadata","expoApiV2RequestId","requestId","toString","env","EXPO_DEBUG","json","data","JSON","stringify","fetchFunction","fetchWithCredentials","url","options","Array","isArray","headers","resolvedHeaders","token","getAccessToken","authorization","getSession","sessionSecret","status","body","text","parse","errors","length","error","includes","isNetworkError","cause","disableNetwork","CommandError","fetchWithOffline","wrapFetchWithOffline","wrapFetchWithUserAgent","fetch","fetchWithBaseUrl","wrapFetchWithBaseUrl","getExpoApiBaseUrl","wrapFetchWithProgress","cacheDirectory","ttl","skipCache","EXPO_BETA","EXPO_NO_CACHE","FileSystemResponseCache","require","wrapFetchWithCache","path","join","getExpoHomeDirectory"],"mappings":";;;;;;;;;;;IAgBaA,UAAU;eAAVA;;IA2CAC,oBAAoB;eAApBA;;IARAC,qBAAqB;eAArBA;;IAgHGC,iBAAiB;eAAjBA;;IA6BHC,UAAU;eAAVA;;IAhIGC,sBAAsB;eAAtBA;;IAaAC,wBAAwB;eAAxBA;;;;gEA5EC;;;;;;oCAEkB;sCAEE;sCACA;uCACC;wCACC;qBACnB;wBACS;uBACP;0BACY;0BACH;8BACkC;;;;;;AAE1D,MAAMN,mBAAmBO;IAS9BC,YAAYC,QAOX,CAAE;QACD,KAAK,CAACA,SAASC,OAAO,QAhBfC,OAAO;QAiBd,IAAI,CAACC,IAAI,GAAGH,SAASG,IAAI;QACzB,IAAI,CAACC,kBAAkB,GAAGJ,SAASG,IAAI;QACvC,IAAI,CAACE,qBAAqB,GAAGL,SAASM,OAAO;QAC7C,IAAI,CAACC,yBAAyB,GAAGP,SAASQ,KAAK;QAC/C,IAAI,CAACC,sBAAsB,GAAGT,SAASU,QAAQ;QAC/C,IAAI,CAACC,kBAAkB,GAAGX,SAASY,SAAS;IAC9C;IAEAC,WAAW;QACT,OAAO,GAAG,KAAK,CAACA,aAAaC,QAAG,CAACC,UAAU,IAAI,IAAI,CAACJ,kBAAkB,GAAG,CAAC,cAAc,EAAE,IAAI,CAACA,kBAAkB,CAAC,CAAC,CAAC,GAAG,IAAI;IAC7H;AACF;AAMO,MAAMlB,8BAA8BK;;QAApC,qBACII,OAAO;;AAClB;AAMO,MAAMV,6BAA6BM;;QAAnC,qBACII,OAAO;;AAClB;AAGO,SAASN,uBAAgCoB,IAAa;IAC3D,IAAI,CAAC,CAACA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BACR;YACF;YAEA,OAAOvC;QACT,EAAE,OAAOuC,OAAY;YACnB,6DAA6D;YAC7D,IAAIE,eAAeF,UAAW,WAAWA,SAASE,eAAeF,MAAMG,KAAK,GAAI;gBAC9EC,IAAAA,wBAAc;gBAEd,MAAM,IAAIC,oBAAY,CACpB,WACA;YAEJ;YAEA,MAAML;QACR;IACF;AACF;AAEA;;;;;;;;;CASC,GACD,SAASE,eAAeF,KAAgC;IACtD,OACE,UAAUA,SACVA,MAAMpC,IAAI,IACV;QAAC;QAAa;QAAa;KAA0B,CAACqC,QAAQ,CAACD,MAAMpC,IAAI;AAE7E;AAEA,MAAM0C,mBAAmBC,IAAAA,0CAAoB,EAACC,IAAAA,8CAAsB,EAACC,YAAK;AAE1E,MAAMC,mBAAmBC,IAAAA,0CAAoB,EAACL,kBAAkBM,IAAAA,2BAAiB,MAAK;AAEtF,MAAM9B,uBAAuB+B,IAAAA,4CAAqB,EAACvD,yBAAyBoD;AAMrE,SAASvD,kBAAkB,EAChCsD,QAAQ3B,oBAAoB,EAC5BgC,cAAc,EACdC,GAAG,EACHC,SAAS,EAMV;IACC,oCAAoC;IACpC,IAAIA,aAAazC,QAAG,CAAC0C,SAAS,IAAI1C,QAAG,CAAC2C,aAAa,EAAE;QACnD,OAAOT;IACT;IAEA,MAAM,EAAEU,uBAAuB,EAAE,GAC/BC,QAAQ;IAEV,OAAOC,IAAAA,sCAAkB,EACvBZ,OACA,IAAIU,wBAAwB;QAC1BL,gBAAgBQ,eAAI,CAACC,IAAI,CAACC,IAAAA,kCAAoB,KAAIV;QAClDC;IACF;AAEJ;AAGO,MAAM3D,aAAayD,IAAAA,4CAAqB,EAACvD,yBAAyBoD"}
|
|
@@ -8,13 +8,6 @@ Object.defineProperty(exports, "wrapFetchWithProgress", {
|
|
|
8
8
|
return wrapFetchWithProgress;
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
|
-
function _undici() {
|
|
12
|
-
const data = require("undici");
|
|
13
|
-
_undici = function() {
|
|
14
|
-
return data;
|
|
15
|
-
};
|
|
16
|
-
return data;
|
|
17
|
-
}
|
|
18
11
|
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../log"));
|
|
19
12
|
function _getRequireWildcardCache(nodeInterop) {
|
|
20
13
|
if (typeof WeakMap !== "function") return null;
|
|
@@ -107,7 +100,7 @@ function wrapFetchWithProgress(fetch) {
|
|
|
107
100
|
}
|
|
108
101
|
});
|
|
109
102
|
// Return the new response with the wrapped body stream
|
|
110
|
-
return new
|
|
103
|
+
return new Response(bodyWithProgress, response);
|
|
111
104
|
});
|
|
112
105
|
};
|
|
113
106
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/api/rest/wrapFetchWithProgress.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../../src/api/rest/wrapFetchWithProgress.ts"],"sourcesContent":["import { FetchLike } from './client.types';\nimport * as Log from '../../log';\n\nconst debug = require('debug')('expo:api:fetch:progress') as typeof console.log;\n\nexport function wrapFetchWithProgress(fetch: FetchLike): FetchLike {\n return function fetchWithProgress(url, init) {\n return fetch(url, init).then((response) => {\n const onProgress = init?.onProgress;\n\n // Abort if no `onProgress` is provided, the request failed, or there is no response body\n if (!onProgress || !response.ok || !response.body) {\n return response;\n }\n\n // Calculate total progress size\n const contentLength = response.headers.get('Content-Length');\n const progressTotal = Number(contentLength);\n\n debug(`Download size: %d`, progressTotal);\n\n // Abort if the `Content-Length` header is missing or invalid\n if (!progressTotal || isNaN(progressTotal) || progressTotal < 0) {\n Log.warn(\n 'Progress callback not supported for network request because \"Content-Length\" header missing or invalid in response from URL:',\n url.toString()\n );\n return response;\n }\n\n debug(`Starting progress animation for: %s`, url);\n\n // Initialize the progression variables\n let progressCurrent = 0;\n const progressUpdate = () => {\n const progress = progressCurrent / progressTotal || 0;\n onProgress({\n progress,\n total: progressTotal,\n loaded: progressCurrent,\n });\n };\n\n // Create a new body-wrapping stream that handles the progression methods\n const bodyReader = response.body.getReader();\n const bodyWithProgress = new ReadableStream({\n start(controller) {\n function next() {\n bodyReader.read().then(({ done, value }) => {\n // Close the controller once stream is done\n if (done) return controller.close();\n\n // Update the progression\n progressCurrent += Buffer.byteLength(value);\n progressUpdate();\n\n // Continue the stream, and read the next chunk\n controller.enqueue(value);\n next();\n });\n }\n\n progressUpdate();\n next();\n },\n });\n\n // Return the new response with the wrapped body stream\n return new Response(bodyWithProgress as any, response);\n });\n };\n}\n"],"names":["wrapFetchWithProgress","debug","require","fetch","fetchWithProgress","url","init","then","response","onProgress","ok","body","contentLength","headers","get","progressTotal","Number","isNaN","Log","warn","toString","progressCurrent","progressUpdate","progress","total","loaded","bodyReader","getReader","bodyWithProgress","ReadableStream","start","controller","next","read","done","value","close","Buffer","byteLength","enqueue","Response"],"mappings":";;;;+BAKgBA;;;eAAAA;;;6DAJK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErB,MAAMC,QAAQC,QAAQ,SAAS;AAExB,SAASF,sBAAsBG,KAAgB;IACpD,OAAO,SAASC,kBAAkBC,GAAG,EAAEC,IAAI;QACzC,OAAOH,MAAME,KAAKC,MAAMC,IAAI,CAAC,CAACC;YAC5B,MAAMC,aAAaH,wBAAAA,KAAMG,UAAU;YAEnC,yFAAyF;YACzF,IAAI,CAACA,cAAc,CAACD,SAASE,EAAE,IAAI,CAACF,SAASG,IAAI,EAAE;gBACjD,OAAOH;YACT;YAEA,gCAAgC;YAChC,MAAMI,gBAAgBJ,SAASK,OAAO,CAACC,GAAG,CAAC;YAC3C,MAAMC,gBAAgBC,OAAOJ;YAE7BX,MAAM,CAAC,iBAAiB,CAAC,EAAEc;YAE3B,6DAA6D;YAC7D,IAAI,CAACA,iBAAiBE,MAAMF,kBAAkBA,gBAAgB,GAAG;gBAC/DG,KAAIC,IAAI,CACN,gIACAd,IAAIe,QAAQ;gBAEd,OAAOZ;YACT;YAEAP,MAAM,CAAC,mCAAmC,CAAC,EAAEI;YAE7C,uCAAuC;YACvC,IAAIgB,kBAAkB;YACtB,MAAMC,iBAAiB;gBACrB,MAAMC,WAAWF,kBAAkBN,iBAAiB;gBACpDN,WAAW;oBACTc;oBACAC,OAAOT;oBACPU,QAAQJ;gBACV;YACF;YAEA,yEAAyE;YACzE,MAAMK,aAAalB,SAASG,IAAI,CAACgB,SAAS;YAC1C,MAAMC,mBAAmB,IAAIC,eAAe;gBAC1CC,OAAMC,UAAU;oBACd,SAASC;wBACPN,WAAWO,IAAI,GAAG1B,IAAI,CAAC,CAAC,EAAE2B,IAAI,EAAEC,KAAK,EAAE;4BACrC,2CAA2C;4BAC3C,IAAID,MAAM,OAAOH,WAAWK,KAAK;4BAEjC,yBAAyB;4BACzBf,mBAAmBgB,OAAOC,UAAU,CAACH;4BACrCb;4BAEA,+CAA+C;4BAC/CS,WAAWQ,OAAO,CAACJ;4BACnBH;wBACF;oBACF;oBAEAV;oBACAU;gBACF;YACF;YAEA,uDAAuD;YACvD,OAAO,IAAIQ,SAASZ,kBAAyBpB;QAC/C;IACF;AACF"}
|
|
@@ -28,13 +28,6 @@ _export(exports, {
|
|
|
28
28
|
return ssoLoginAsync;
|
|
29
29
|
}
|
|
30
30
|
});
|
|
31
|
-
function _core() {
|
|
32
|
-
const data = require("@urql/core");
|
|
33
|
-
_core = function() {
|
|
34
|
-
return data;
|
|
35
|
-
};
|
|
36
|
-
return data;
|
|
37
|
-
}
|
|
38
31
|
function _fs() {
|
|
39
32
|
const data = require("fs");
|
|
40
33
|
_fs = function() {
|
|
@@ -48,9 +41,8 @@ const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../log"));
|
|
|
48
41
|
const _codesigning = require("../../utils/codesigning");
|
|
49
42
|
const _env = require("../../utils/env");
|
|
50
43
|
const _endpoint = require("../endpoint");
|
|
51
|
-
const _client = require("../graphql/client");
|
|
52
44
|
const _UserQuery = require("../graphql/queries/UserQuery");
|
|
53
|
-
const
|
|
45
|
+
const _client = require("../rest/client");
|
|
54
46
|
function _getRequireWildcardCache(nodeInterop) {
|
|
55
47
|
if (typeof WeakMap !== "function") return null;
|
|
56
48
|
var cacheBabelInterop = new WeakMap();
|
|
@@ -116,14 +108,14 @@ async function getUserAsync() {
|
|
|
116
108
|
return currentUser;
|
|
117
109
|
}
|
|
118
110
|
async function loginAsync(credentials) {
|
|
119
|
-
const res = await (0,
|
|
111
|
+
const res = await (0, _client.fetchAsync)('auth/loginAsync', {
|
|
120
112
|
method: 'POST',
|
|
121
113
|
body: JSON.stringify(credentials)
|
|
122
114
|
});
|
|
123
115
|
const json = await res.json();
|
|
124
116
|
const sessionSecret = json.data.sessionSecret;
|
|
125
|
-
const userData = await
|
|
126
|
-
sessionSecret
|
|
117
|
+
const userData = await _UserQuery.UserQuery.meUserActorAsync({
|
|
118
|
+
'expo-session': sessionSecret
|
|
127
119
|
});
|
|
128
120
|
await (0, _UserSettings.setSessionAsync)({
|
|
129
121
|
sessionSecret,
|
|
@@ -136,8 +128,8 @@ async function ssoLoginAsync() {
|
|
|
136
128
|
const sessionSecret = await (0, _expoSsoLauncher.getSessionUsingBrowserAuthFlowAsync)({
|
|
137
129
|
expoWebsiteUrl: (0, _endpoint.getExpoWebsiteBaseUrl)()
|
|
138
130
|
});
|
|
139
|
-
const userData = await
|
|
140
|
-
sessionSecret
|
|
131
|
+
const userData = await _UserQuery.UserQuery.meUserActorAsync({
|
|
132
|
+
'expo-session': sessionSecret
|
|
141
133
|
});
|
|
142
134
|
await (0, _UserSettings.setSessionAsync)({
|
|
143
135
|
sessionSecret,
|
|
@@ -157,27 +149,5 @@ async function logoutAsync() {
|
|
|
157
149
|
]);
|
|
158
150
|
_log.log('Logged out');
|
|
159
151
|
}
|
|
160
|
-
async function fetchUserAsync({ sessionSecret }) {
|
|
161
|
-
const result = await _client.graphqlClient.query((0, _core().gql)`
|
|
162
|
-
query UserQuery {
|
|
163
|
-
meUserActor {
|
|
164
|
-
id
|
|
165
|
-
username
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
`, {}, {
|
|
169
|
-
fetchOptions: {
|
|
170
|
-
headers: {
|
|
171
|
-
'expo-session': sessionSecret
|
|
172
|
-
}
|
|
173
|
-
},
|
|
174
|
-
additionalTypenames: []
|
|
175
|
-
}).toPromise();
|
|
176
|
-
const { data } = result;
|
|
177
|
-
return {
|
|
178
|
-
id: data.meUserActor.id,
|
|
179
|
-
username: data.meUserActor.username
|
|
180
|
-
};
|
|
181
|
-
}
|
|
182
152
|
|
|
183
153
|
//# sourceMappingURL=user.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/api/user/user.ts"],"sourcesContent":["import {
|
|
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 ssoLoginAsync(): Promise<void> {\n const sessionSecret = await getSessionUsingBrowserAuthFlowAsync({\n expoWebsiteUrl: getExpoWebsiteBaseUrl(),\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","getActorDisplayName","getUserAsync","loginAsync","logoutAsync","ssoLoginAsync","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","getSessionUsingBrowserAuthFlowAsync","expoWebsiteUrl","getExpoWebsiteBaseUrl","Promise","all","fs","rm","getDevelopmentCodeSigningDirectory","recursive","force","Log","log"],"mappings":";;;;;;;;;;;IAaaA,kBAAkB;eAAlBA;;IAOGC,mBAAmB;eAAnBA;;IAeMC,YAAY;eAAZA;;IASAC,UAAU;eAAVA;;IAuCAC,WAAW;eAAXA;;IAfAC,aAAa;eAAbA;;;;yBApES;;;;;;8BAE6B;iCACR;6DAC/B;6BAC8B;qBAC/B;0BACkB;2BAC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ClB;IACA,MAAMiB,IAAAA,6BAAe,EAAC;QACpBjB;QACAkB,QAAQH,SAASI,EAAE;QACnBxB,UAAUoB,SAASpB,QAAQ;QAC3ByB,mBAAmB;IACrB;AACF;AAEO,eAAe9B;IACpBE,cAAca;IACd,MAAMmB,QAAQC,GAAG,CAAC;QAChBC,cAAE,CAACC,EAAE,CAACC,IAAAA,+CAAkC,KAAI;YAAEC,WAAW;YAAMC,OAAO;QAAK;QAC3Eb,IAAAA,6BAAe,EAACZ;KACjB;IACD0B,KAAIC,GAAG,CAAC;AACV"}
|
|
@@ -81,11 +81,7 @@ const defaultRenameConfig = [
|
|
|
81
81
|
'macos/**/*.xcodeproj/xcshareddata/xcschemes/*.xcscheme',
|
|
82
82
|
'macos/**/*.xcworkspace/contents.xcworkspacedata'
|
|
83
83
|
];
|
|
84
|
-
async function getTemplateFilesToRenameAsync(
|
|
85
|
-
* An array of patterns following the rename config format. If omitted, then
|
|
86
|
-
* we fall back to defaultRenameConfig.
|
|
87
|
-
* @see defaultRenameConfig
|
|
88
|
-
*/ renameConfig: userConfig }) {
|
|
84
|
+
async function getTemplateFilesToRenameAsync(cwd, { renameConfig: userConfig } = {}) {
|
|
89
85
|
let config = userConfig ?? defaultRenameConfig;
|
|
90
86
|
// Strip comments, trim whitespace, and remove empty lines.
|
|
91
87
|
config = config.map((line)=>line.split(/(?<!\\)#/, 2)[0].trim()).filter((line)=>line !== '');
|
|
@@ -103,7 +99,7 @@ async function getTemplateFilesToRenameAsync({ cwd, /**
|
|
|
103
99
|
nodir: true
|
|
104
100
|
});
|
|
105
101
|
}
|
|
106
|
-
async function renameTemplateAppNameAsync(
|
|
102
|
+
async function renameTemplateAppNameAsync(cwd, { expName: name, files }) {
|
|
107
103
|
debug(`Got files to transform: ${JSON.stringify(files)}`);
|
|
108
104
|
await Promise.all(files.map(async (file)=>{
|
|
109
105
|
const absoluteFilePath = _path().default.resolve(cwd, file);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/prebuild/renameTemplateAppName.ts"],"sourcesContent":["import { IOSConfig } from '@expo/config-plugins';\nimport fs from 'fs';\nimport { glob } from 'glob';\nimport path from 'path';\n\nimport { ExtractProps } from '../utils/npm';\n\nconst debug = require('debug')('expo:prebuild:copyTemplateFiles') as typeof console.log;\n\nfunction escapeXMLCharacters(original: string): string {\n const noAmps = original.replace('&', '&');\n const noLt = noAmps.replace('<', '<');\n const noGt = noLt.replace('>', '>');\n const noApos = noGt.replace('\"', '\\\\\"');\n return noApos.replace(\"'\", \"\\\\'\");\n}\n\n/**\n * # Background\n *\n * `@expo/cli` and `create-expo` extract a template from a tarball (whether from\n * a local npm project or a GitHub repository), but these templates have a\n * static name that needs to be updated to match whatever app name the user\n * specified.\n *\n * By convention, the app name of all templates is \"HelloWorld\". During\n * extraction, filepaths are transformed via `createEntryResolver()` in\n * `createFileTransform.ts`, but the contents of files are left untouched.\n * Technically, the contents used to be transformed during extraction as well,\n * but due to poor configurability, we've moved to a post-extraction approach.\n *\n * # The new approach: Renaming the app post-extraction\n *\n * In this new approach, we take a list of file patterns, otherwise known as the\n * \"rename config\" to determine explicitly which files – relative to the root of\n * the template – to perform find-and-replace on, to update the app name.\n *\n * ## The rename config\n *\n * The rename config can be passed directly as a string array to\n * `getTemplateFilesToRenameAsync()`.\n *\n * The file patterns are formatted as glob expressions to be interpreted by\n * [glob](https://github.com/isaacs/node-glob). Comments are supported with\n * the `#` symbol, both in the plain-text file and string array formats.\n * Whitespace is trimmed and whitespace-only lines are ignored.\n *\n * If no rename config has been passed directly to\n * `getTemplateFilesToRenameAsync()` then this default rename config will be\n * used instead.\n */\nexport const defaultRenameConfig = [\n // Common\n '!**/node_modules',\n 'app.json',\n\n // Android\n 'android/**/*.gradle',\n 'android/app/BUCK',\n 'android/app/src/**/*.java',\n 'android/app/src/**/*.kt',\n 'android/app/src/**/*.xml',\n\n // iOS\n 'ios/Podfile',\n 'ios/**/*.xcodeproj/project.pbxproj',\n 'ios/**/*.xcodeproj/xcshareddata/xcschemes/*.xcscheme',\n 'ios/**/*.xcworkspace/contents.xcworkspacedata',\n\n // macOS\n 'macos/Podfile',\n 'macos/**/*.xcodeproj/project.pbxproj',\n 'macos/**/*.xcodeproj/xcshareddata/xcschemes/*.xcscheme',\n 'macos/**/*.xcworkspace/contents.xcworkspacedata',\n] as const;\n\n/**\n * Returns a list of files within a template matched by the resolved rename\n * config.\n *\n * The rename config is resolved in the order of preference:\n * Config provided as function param > defaultRenameConfig\n */\nexport async function getTemplateFilesToRenameAsync(
|
|
1
|
+
{"version":3,"sources":["../../../src/prebuild/renameTemplateAppName.ts"],"sourcesContent":["import { IOSConfig } from '@expo/config-plugins';\nimport fs from 'fs';\nimport { glob } from 'glob';\nimport path from 'path';\n\nimport { ExtractProps } from '../utils/npm';\n\nconst debug = require('debug')('expo:prebuild:copyTemplateFiles') as typeof console.log;\n\nfunction escapeXMLCharacters(original: string): string {\n const noAmps = original.replace('&', '&');\n const noLt = noAmps.replace('<', '<');\n const noGt = noLt.replace('>', '>');\n const noApos = noGt.replace('\"', '\\\\\"');\n return noApos.replace(\"'\", \"\\\\'\");\n}\n\n/**\n * # Background\n *\n * `@expo/cli` and `create-expo` extract a template from a tarball (whether from\n * a local npm project or a GitHub repository), but these templates have a\n * static name that needs to be updated to match whatever app name the user\n * specified.\n *\n * By convention, the app name of all templates is \"HelloWorld\". During\n * extraction, filepaths are transformed via `createEntryResolver()` in\n * `createFileTransform.ts`, but the contents of files are left untouched.\n * Technically, the contents used to be transformed during extraction as well,\n * but due to poor configurability, we've moved to a post-extraction approach.\n *\n * # The new approach: Renaming the app post-extraction\n *\n * In this new approach, we take a list of file patterns, otherwise known as the\n * \"rename config\" to determine explicitly which files – relative to the root of\n * the template – to perform find-and-replace on, to update the app name.\n *\n * ## The rename config\n *\n * The rename config can be passed directly as a string array to\n * `getTemplateFilesToRenameAsync()`.\n *\n * The file patterns are formatted as glob expressions to be interpreted by\n * [glob](https://github.com/isaacs/node-glob). Comments are supported with\n * the `#` symbol, both in the plain-text file and string array formats.\n * Whitespace is trimmed and whitespace-only lines are ignored.\n *\n * If no rename config has been passed directly to\n * `getTemplateFilesToRenameAsync()` then this default rename config will be\n * used instead.\n */\nexport const defaultRenameConfig = [\n // Common\n '!**/node_modules',\n 'app.json',\n\n // Android\n 'android/**/*.gradle',\n 'android/app/BUCK',\n 'android/app/src/**/*.java',\n 'android/app/src/**/*.kt',\n 'android/app/src/**/*.xml',\n\n // iOS\n 'ios/Podfile',\n 'ios/**/*.xcodeproj/project.pbxproj',\n 'ios/**/*.xcodeproj/xcshareddata/xcschemes/*.xcscheme',\n 'ios/**/*.xcworkspace/contents.xcworkspacedata',\n\n // macOS\n 'macos/Podfile',\n 'macos/**/*.xcodeproj/project.pbxproj',\n 'macos/**/*.xcodeproj/xcshareddata/xcschemes/*.xcscheme',\n 'macos/**/*.xcworkspace/contents.xcworkspacedata',\n] as const;\n\n/**\n * Returns a list of files within a template matched by the resolved rename\n * config.\n *\n * The rename config is resolved in the order of preference:\n * Config provided as function param > defaultRenameConfig\n */\nexport async function getTemplateFilesToRenameAsync(\n cwd: string,\n {\n renameConfig: userConfig,\n }: {\n /**\n * An array of patterns following the rename config format. If omitted, then\n * we fall back to defaultRenameConfig.\n * @see defaultRenameConfig\n */\n renameConfig?: string[];\n } = {}\n) {\n let config = userConfig ?? defaultRenameConfig;\n\n // Strip comments, trim whitespace, and remove empty lines.\n config = config.map((line) => line.split(/(?<!\\\\)#/, 2)[0].trim()).filter((line) => line !== '');\n\n return await glob(config, {\n cwd,\n // `true` is consistent with .gitignore. Allows `*.xml` to match .xml files\n // in all subdirs.\n matchBase: true,\n dot: true,\n // Prevent climbing out of the template directory in case a template\n // includes a symlink to an external directory.\n follow: false,\n // Do not match on directories, only files\n // Without this patterns like `android/**/*.gradle` actually match the folder `android/.gradle`\n nodir: true,\n });\n}\n\nexport async function renameTemplateAppNameAsync(\n cwd: string,\n {\n expName: name,\n files,\n }: {\n expName: string;\n /**\n * An array of files to transform. Usually provided by calling\n * getTemplateFilesToRenameAsync().\n * @see getTemplateFilesToRenameAsync\n */\n files: string[];\n }\n) {\n debug(`Got files to transform: ${JSON.stringify(files)}`);\n\n await Promise.all(\n files.map(async (file) => {\n const absoluteFilePath = path.resolve(cwd, file);\n\n let contents: string;\n try {\n contents = await fs.promises.readFile(absoluteFilePath, { encoding: 'utf-8' });\n } catch (error) {\n throw new Error(\n `Failed to read template file: \"${absoluteFilePath}\". Was it removed mid-operation?`,\n { cause: error }\n );\n }\n\n debug(`Renaming app name in file: ${absoluteFilePath}`);\n\n const safeName = ['.xml', '.plist'].includes(path.extname(file))\n ? escapeXMLCharacters(name)\n : name;\n\n try {\n const replacement = contents\n .replace(/Hello App Display Name/g, safeName)\n .replace(/HelloWorld/g, IOSConfig.XcodeUtils.sanitizedName(safeName))\n .replace(/helloworld/g, IOSConfig.XcodeUtils.sanitizedName(safeName.toLowerCase()));\n\n if (replacement === contents) {\n return;\n }\n\n await fs.promises.writeFile(absoluteFilePath, replacement);\n } catch (error) {\n throw new Error(\n `Failed to overwrite template file: \"${absoluteFilePath}\". Was it removed mid-operation?`,\n { cause: error }\n );\n }\n })\n );\n}\n"],"names":["defaultRenameConfig","getTemplateFilesToRenameAsync","renameTemplateAppNameAsync","debug","require","escapeXMLCharacters","original","noAmps","replace","noLt","noGt","noApos","cwd","renameConfig","userConfig","config","map","line","split","trim","filter","glob","matchBase","dot","follow","nodir","expName","name","files","JSON","stringify","Promise","all","file","absoluteFilePath","path","resolve","contents","fs","promises","readFile","encoding","error","Error","cause","safeName","includes","extname","replacement","IOSConfig","XcodeUtils","sanitizedName","toLowerCase","writeFile"],"mappings":";;;;;;;;;;;IAmDaA,mBAAmB;eAAnBA;;IAgCSC,6BAA6B;eAA7BA;;IAiCAC,0BAA0B;eAA1BA;;;;yBApHI;;;;;;;gEACX;;;;;;;yBACM;;;;;;;gEACJ;;;;;;;;;;;AAIjB,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,S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OAAOC,OAAO;YACd,MAAM,IAAIC,MACR,CAAC,+BAA+B,EAAET,iBAAiB,gCAAgC,CAAC,EACpF;gBAAEU,OAAOF;YAAM;QAEnB;QAEAvC,MAAM,CAAC,2BAA2B,EAAE+B,kBAAkB;QAEtD,MAAMW,WAAW;YAAC;YAAQ;SAAS,CAACC,QAAQ,CAACX,eAAI,CAACY,OAAO,CAACd,SACtD5B,oBAAoBsB,QACpBA;QAEJ,IAAI;YACF,MAAMqB,cAAcX,SACjB7B,OAAO,CAAC,2BAA2BqC,UACnCrC,OAAO,CAAC,eAAeyC,0BAAS,CAACC,UAAU,CAACC,aAAa,CAACN,WAC1DrC,OAAO,CAAC,eAAeyC,0BAAS,CAACC,UAAU,CAACC,aAAa,CAACN,SAASO,WAAW;YAEjF,IAAIJ,gBAAgBX,UAAU;gBAC5B;YACF;YAEA,MAAMC,aAAE,CAACC,QAAQ,CAACc,SAAS,CAACnB,kBAAkBc;QAChD,EAAE,OAAON,OAAO;YACd,MAAM,IAAIC,MACR,CAAC,oCAAoC,EAAET,iBAAiB,gCAAgC,CAAC,EACzF;gBAAEU,OAAOF;YAAM;QAEnB;IACF;AAEJ"}
|
|
@@ -64,10 +64,8 @@ async function resolveLocalTemplateAsync({ templateDirectory, projectRoot, exp }
|
|
|
64
64
|
templatePath = (0, _resolvefrom().default)(projectRoot, 'expo/template.tgz');
|
|
65
65
|
debug('Using local template from Expo package:', templatePath);
|
|
66
66
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
cwd: templateDirectory,
|
|
70
|
-
name: exp.name
|
|
67
|
+
return await (0, _npm.extractLocalNpmTarballAsync)(templatePath, templateDirectory, {
|
|
68
|
+
expName: exp.name
|
|
71
69
|
});
|
|
72
70
|
}
|
|
73
71
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/prebuild/resolveLocalTemplate.ts"],"sourcesContent":["import type { ExpoConfig } from '@expo/config';\nimport fs from 'fs';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { packNpmTarballAsync,
|
|
1
|
+
{"version":3,"sources":["../../../src/prebuild/resolveLocalTemplate.ts"],"sourcesContent":["import type { ExpoConfig } from '@expo/config';\nimport fs from 'fs';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { packNpmTarballAsync, extractLocalNpmTarballAsync } from '../utils/npm';\n\nconst debug = require('debug')('expo:prebuild:resolveLocalTemplate') as typeof console.log;\n\n/** Returns the `local-template` target path, only for the `expo/expo` monorepo */\nconst getMonorepoTemplatePath = async () => {\n const cliPath = path.dirname(require.resolve('@expo/cli/package.json'));\n const localTemplateOriginPath = path.join(cliPath, 'local-template');\n try {\n return await fs.promises.realpath(localTemplateOriginPath);\n } catch {\n return null;\n }\n};\n\nexport async function resolveLocalTemplateAsync({\n templateDirectory,\n projectRoot,\n exp,\n}: {\n templateDirectory: string;\n projectRoot: string;\n exp: Pick<ExpoConfig, 'name'>;\n}): Promise<string> {\n let templatePath: string;\n\n // In the expo/expo monorepo only, we use `templates/expo-template-bare-minimum` directly\n const monorepoTemplatePath = await getMonorepoTemplatePath();\n if (monorepoTemplatePath) {\n debug('Packing local template from expo-template-bare-minimum path:', monorepoTemplatePath);\n try {\n templatePath = await packNpmTarballAsync(monorepoTemplatePath);\n debug('Using packed local template at:', templatePath);\n } catch (error) {\n // We're vocal here about an error, since we don't expect this to fail, and it's only for our monorepo\n console.error(\n `Failed to pack local expo-template-bare-minimum to be used as a prebuild template:\\n`,\n error\n );\n throw error;\n }\n } else {\n // The default is to use `expo/template.tgz` which exists in all published versions of it\n templatePath = resolveFrom(projectRoot, 'expo/template.tgz');\n debug('Using local template from Expo package:', templatePath);\n }\n\n return await extractLocalNpmTarballAsync(templatePath, templateDirectory, {\n expName: exp.name,\n });\n}\n"],"names":["resolveLocalTemplateAsync","debug","require","getMonorepoTemplatePath","cliPath","path","dirname","resolve","localTemplateOriginPath","join","fs","promises","realpath","templateDirectory","projectRoot","exp","templatePath","monorepoTemplatePath","packNpmTarballAsync","error","console","resolveFrom","extractLocalNpmTarballAsync","expName","name"],"mappings":";;;;+BAoBsBA;;;eAAAA;;;;gEAnBP;;;;;;;gEACE;;;;;;;gEACO;;;;;;qBAEyC;;;;;;AAEjE,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,gFAAgF,GAChF,MAAMC,0BAA0B;IAC9B,MAAMC,UAAUC,eAAI,CAACC,OAAO,CAACJ,QAAQK,OAAO,CAAC;IAC7C,MAAMC,0BAA0BH,eAAI,CAACI,IAAI,CAACL,SAAS;IACnD,IAAI;QACF,OAAO,MAAMM,aAAE,CAACC,QAAQ,CAACC,QAAQ,CAACJ;IACpC,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEO,eAAeR,0BAA0B,EAC9Ca,iBAAiB,EACjBC,WAAW,EACXC,GAAG,EAKJ;IACC,IAAIC;IAEJ,yFAAyF;IACzF,MAAMC,uBAAuB,MAAMd;IACnC,IAAIc,sBAAsB;QACxBhB,MAAM,gEAAgEgB;QACtE,IAAI;YACFD,eAAe,MAAME,IAAAA,wBAAmB,EAACD;YACzChB,MAAM,mCAAmCe;QAC3C,EAAE,OAAOG,OAAO;YACd,sGAAsG;YACtGC,QAAQD,KAAK,CACX,CAAC,oFAAoF,CAAC,EACtFA;YAEF,MAAMA;QACR;IACF,OAAO;QACL,yFAAyF;QACzFH,eAAeK,IAAAA,sBAAW,EAACP,aAAa;QACxCb,MAAM,2CAA2Ce;IACnD;IAEA,OAAO,MAAMM,IAAAA,gCAA2B,EAACN,cAAcH,mBAAmB;QACxEU,SAASR,IAAIS,IAAI;IACnB;AACF"}
|
|
@@ -78,20 +78,18 @@ function _interop_require_wildcard(obj, nodeInterop) {
|
|
|
78
78
|
const debug = require('debug')('expo:prebuild:resolveTemplate');
|
|
79
79
|
async function cloneTemplateAsync({ templateDirectory, projectRoot, template, exp, ora }) {
|
|
80
80
|
if (template) {
|
|
81
|
-
const
|
|
81
|
+
const expName = exp.name;
|
|
82
82
|
const { type, uri } = template;
|
|
83
83
|
if (type === 'file') {
|
|
84
|
-
return await (0, _npm.extractLocalNpmTarballAsync)(uri, {
|
|
85
|
-
|
|
86
|
-
name: appName
|
|
84
|
+
return await (0, _npm.extractLocalNpmTarballAsync)(uri, templateDirectory, {
|
|
85
|
+
expName
|
|
87
86
|
});
|
|
88
87
|
} else if (type === 'npm') {
|
|
89
|
-
return await (0, _npm.downloadAndExtractNpmModuleAsync)(uri, {
|
|
90
|
-
|
|
91
|
-
name: appName
|
|
88
|
+
return await (0, _npm.downloadAndExtractNpmModuleAsync)(uri, templateDirectory, {
|
|
89
|
+
expName
|
|
92
90
|
});
|
|
93
91
|
} else if (type === 'repository') {
|
|
94
|
-
return await resolveAndDownloadRepoTemplateAsync(templateDirectory, ora,
|
|
92
|
+
return await resolveAndDownloadRepoTemplateAsync(templateDirectory, ora, expName, uri);
|
|
95
93
|
} else {
|
|
96
94
|
throw new Error(`Unknown template type: ${type}`);
|
|
97
95
|
}
|
|
@@ -105,9 +103,8 @@ async function cloneTemplateAsync({ templateDirectory, projectRoot, template, ex
|
|
|
105
103
|
} catch (error) {
|
|
106
104
|
const templatePackageName = getTemplateNpmPackageNameFromSdkVersion(exp.sdkVersion);
|
|
107
105
|
debug('Fallback to SDK template:', templatePackageName);
|
|
108
|
-
return await (0, _npm.downloadAndExtractNpmModuleAsync)(templatePackageName, {
|
|
109
|
-
|
|
110
|
-
name: exp.name
|
|
106
|
+
return await (0, _npm.downloadAndExtractNpmModuleAsync)(templatePackageName, templateDirectory, {
|
|
107
|
+
expName: exp.name
|
|
111
108
|
});
|
|
112
109
|
}
|
|
113
110
|
}
|
|
@@ -155,7 +152,7 @@ function hasRepo({ username, name, branch, filePath }) {
|
|
|
155
152
|
const packagePath = `${filePath ? `/${filePath}` : ''}/package.json`;
|
|
156
153
|
return (0, _url.isUrlOk)(contentsUrl + packagePath + `?ref=${branch}`);
|
|
157
154
|
}
|
|
158
|
-
async function downloadAndExtractRepoAsync({ username, name, branch, filePath }, props) {
|
|
155
|
+
async function downloadAndExtractRepoAsync({ username, name, branch, filePath }, output, props) {
|
|
159
156
|
const url = `https://codeload.github.com/${username}/${name}/tar.gz/${branch}`;
|
|
160
157
|
debug('Downloading tarball from:', url);
|
|
161
158
|
// Extract the (sub)directory into non-empty path segments
|
|
@@ -176,13 +173,13 @@ async function downloadAndExtractRepoAsync({ username, name, branch, filePath },
|
|
|
176
173
|
'**/ios/*.xcworkspace/**'
|
|
177
174
|
]
|
|
178
175
|
});
|
|
179
|
-
return await (0, _npm.extractNpmTarballFromUrlAsync)(url, {
|
|
176
|
+
return await (0, _npm.extractNpmTarballFromUrlAsync)(url, output, {
|
|
180
177
|
...props,
|
|
181
178
|
strip,
|
|
182
179
|
filter
|
|
183
180
|
});
|
|
184
181
|
}
|
|
185
|
-
async function resolveAndDownloadRepoTemplateAsync(templateDirectory, oraInstance,
|
|
182
|
+
async function resolveAndDownloadRepoTemplateAsync(templateDirectory, oraInstance, expName, template, templatePath) {
|
|
186
183
|
let repoUrl;
|
|
187
184
|
try {
|
|
188
185
|
repoUrl = new URL(template);
|
|
@@ -211,9 +208,8 @@ async function resolveAndDownloadRepoTemplateAsync(templateDirectory, oraInstanc
|
|
|
211
208
|
throw new _errors.AbortCommandError();
|
|
212
209
|
}
|
|
213
210
|
oraInstance.text = _chalk().default.bold(`Downloading files from repo ${_chalk().default.cyan(template)}. This might take a moment.`);
|
|
214
|
-
return await downloadAndExtractRepoAsync(repoInfo, {
|
|
215
|
-
|
|
216
|
-
name: appName
|
|
211
|
+
return await downloadAndExtractRepoAsync(repoInfo, templateDirectory, {
|
|
212
|
+
expName
|
|
217
213
|
});
|
|
218
214
|
}
|
|
219
215
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/prebuild/resolveTemplate.ts"],"sourcesContent":["import { ExpoConfig } from '@expo/config';\nimport chalk from 'chalk';\nimport { Ora } from 'ora';\nimport semver from 'semver';\n\nimport { type ResolvedTemplateOption } from './resolveOptions';\nimport { fetchAsync } from '../api/rest/client';\nimport * as Log from '../log';\nimport { resolveLocalTemplateAsync } from './resolveLocalTemplate';\nimport { createGlobFilter } from '../utils/createFileTransform';\nimport { AbortCommandError } from '../utils/errors';\nimport {\n ExtractProps,\n downloadAndExtractNpmModuleAsync,\n extractLocalNpmTarballAsync,\n extractNpmTarballFromUrlAsync,\n} from '../utils/npm';\nimport { isUrlOk } from '../utils/url';\n\nconst debug = require('debug')('expo:prebuild:resolveTemplate') as typeof console.log;\n\ntype RepoInfo = {\n username: string;\n name: string;\n branch: string;\n filePath: string;\n};\n\nexport async function cloneTemplateAsync({\n templateDirectory,\n projectRoot,\n template,\n exp,\n ora,\n}: {\n templateDirectory: string;\n projectRoot: string;\n template?: ResolvedTemplateOption;\n exp: Pick<ExpoConfig, 'name' | 'sdkVersion'>;\n ora: Ora;\n}): Promise<string> {\n if (template) {\n const appName = exp.name;\n const { type, uri } = template;\n if (type === 'file') {\n return await extractLocalNpmTarballAsync(uri, {\n cwd: templateDirectory,\n name: appName,\n });\n } else if (type === 'npm') {\n return await downloadAndExtractNpmModuleAsync(uri, {\n cwd: templateDirectory,\n name: appName,\n });\n } else if (type === 'repository') {\n return await resolveAndDownloadRepoTemplateAsync(templateDirectory, ora, appName, uri);\n } else {\n throw new Error(`Unknown template type: ${type}`);\n }\n } else {\n try {\n return await resolveLocalTemplateAsync({ templateDirectory, projectRoot, exp });\n } catch (error: any) {\n const templatePackageName = getTemplateNpmPackageNameFromSdkVersion(exp.sdkVersion);\n debug('Fallback to SDK template:', templatePackageName);\n return await downloadAndExtractNpmModuleAsync(templatePackageName, {\n cwd: templateDirectory,\n name: exp.name,\n });\n }\n }\n}\n\n/** Given an `sdkVersion` like `44.0.0` return a fully qualified NPM package name like: `expo-template-bare-minimum@sdk-44` */\nfunction getTemplateNpmPackageNameFromSdkVersion(sdkVersion?: string): string {\n // When undefined or UNVERSIONED, we use the latest version.\n if (!sdkVersion || sdkVersion === 'UNVERSIONED') {\n Log.log('Using an unspecified Expo SDK version. The latest template will be used.');\n return `expo-template-bare-minimum@latest`;\n }\n return `expo-template-bare-minimum@sdk-${semver.major(sdkVersion)}`;\n}\n\nasync function getRepoInfo(url: any, examplePath?: string): Promise<RepoInfo | undefined> {\n const [, username, name, t, _branch, ...file] = url.pathname.split('/');\n const filePath = examplePath ? examplePath.replace(/^\\//, '') : file.join('/');\n\n // Support repos whose entire purpose is to be an example, e.g.\n // https://github.com/:username/:my-cool-example-repo-name.\n if (t === undefined) {\n const infoResponse = await fetchAsync(`https://api.github.com/repos/${username}/${name}`);\n if (infoResponse.status !== 200) {\n return;\n }\n const info: any = await infoResponse.json();\n return { username, name, branch: info['default_branch'], filePath };\n }\n\n // If examplePath is available, the branch name takes the entire path\n const branch = examplePath\n ? `${_branch}/${file.join('/')}`.replace(new RegExp(`/${filePath}|/$`), '')\n : _branch;\n\n if (username && name && branch && t === 'tree') {\n return { username, name, branch, filePath };\n }\n return undefined;\n}\n\nfunction hasRepo({ username, name, branch, filePath }: RepoInfo) {\n const contentsUrl = `https://api.github.com/repos/${username}/${name}/contents`;\n const packagePath = `${filePath ? `/${filePath}` : ''}/package.json`;\n\n return isUrlOk(contentsUrl + packagePath + `?ref=${branch}`);\n}\n\nasync function downloadAndExtractRepoAsync(\n { username, name, branch, filePath }: RepoInfo,\n props: ExtractProps\n): Promise<string> {\n const url = `https://codeload.github.com/${username}/${name}/tar.gz/${branch}`;\n\n debug('Downloading tarball from:', url);\n\n // Extract the (sub)directory into non-empty path segments\n const directory = filePath.replace(/^\\//, '').split('/').filter(Boolean);\n // Remove the (sub)directory paths, and the root folder added by GitHub\n const strip = directory.length + 1;\n // Only extract the relevant (sub)directories, ignoring irrelevant files\n // The filder auto-ignores dotfiles, unless explicitly included\n const filter = createGlobFilter(\n !directory.length\n ? ['*/**', '*/ios/.xcode.env']\n : [`*/${directory.join('/')}/**`, `*/${directory.join('/')}/ios/.xcode.env`],\n {\n // Always ignore the `.xcworkspace` folder\n ignore: ['**/ios/*.xcworkspace/**'],\n }\n );\n\n return await extractNpmTarballFromUrlAsync(url, { ...props, strip, filter });\n}\n\nasync function resolveAndDownloadRepoTemplateAsync(\n templateDirectory: string,\n oraInstance: Ora,\n appName: string,\n template: string,\n templatePath?: string\n) {\n let repoUrl: URL | undefined;\n\n try {\n repoUrl = new URL(template);\n } catch (error: any) {\n if (error.code !== 'ERR_INVALID_URL') {\n oraInstance.fail(error);\n throw error;\n }\n }\n if (!repoUrl) {\n oraInstance.fail(`Invalid URL: ${chalk.red(`\"${template}\"`)}. Try again with a valid URL.`);\n throw new AbortCommandError();\n }\n\n if (repoUrl.origin !== 'https://github.com') {\n oraInstance.fail(\n `Invalid URL: ${chalk.red(\n `\"${template}\"`\n )}. Only GitHub repositories are supported. Try again with a valid GitHub URL.`\n );\n throw new AbortCommandError();\n }\n\n const repoInfo = await getRepoInfo(repoUrl, templatePath);\n\n if (!repoInfo) {\n oraInstance.fail(\n `Found invalid GitHub URL: ${chalk.red(`\"${template}\"`)}. Fix the URL and try again.`\n );\n throw new AbortCommandError();\n }\n\n const found = await hasRepo(repoInfo);\n\n if (!found) {\n oraInstance.fail(\n `Could not locate the repository for ${chalk.red(\n `\"${template}\"`\n )}. Check that the repository exists and try again.`\n );\n throw new AbortCommandError();\n }\n\n oraInstance.text = chalk.bold(\n `Downloading files from repo ${chalk.cyan(template)}. This might take a moment.`\n );\n\n return await downloadAndExtractRepoAsync(repoInfo, {\n cwd: templateDirectory,\n name: appName,\n });\n}\n"],"names":["cloneTemplateAsync","debug","require","templateDirectory","projectRoot","template","exp","ora","appName","name","type","uri","extractLocalNpmTarballAsync","cwd","downloadAndExtractNpmModuleAsync","resolveAndDownloadRepoTemplateAsync","Error","resolveLocalTemplateAsync","error","templatePackageName","getTemplateNpmPackageNameFromSdkVersion","sdkVersion","Log","log","semver","major","getRepoInfo","url","examplePath","username","t","_branch","file","pathname","split","filePath","replace","join","undefined","infoResponse","fetchAsync","status","info","json","branch","RegExp","hasRepo","contentsUrl","packagePath","isUrlOk","downloadAndExtractRepoAsync","props","directory","filter","Boolean","strip","length","createGlobFilter","ignore","extractNpmTarballFromUrlAsync","oraInstance","templatePath","repoUrl","URL","code","fail","chalk","red","AbortCommandError","origin","repoInfo","found","text","bold","cyan"],"mappings":";;;;+BA4BsBA;;;eAAAA;;;;gEA3BJ;;;;;;;gEAEC;;;;;;wBAGQ;6DACN;sCACqB;qCACT;wBACC;qBAM3B;qBACiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAExB,MAAMC,QAAQC,QAAQ,SAAS;AASxB,eAAeF,mBAAmB,EACvCG,iBAAiB,EACjBC,WAAW,EACXC,QAAQ,EACRC,GAAG,EACHC,GAAG,EAOJ;IACC,IAAIF,UAAU;QACZ,MAAMG,UAAUF,IAAIG,IAAI;QACxB,MAAM,EAAEC,IAAI,EAAEC,GAAG,EAAE,GAAGN;QACtB,IAAIK,SAAS,QAAQ;YACnB,OAAO,MAAME,IAAAA,gCAA2B,EAACD,KAAK;gBAC5CE,KAAKV;gBACLM,MAAMD;YACR;QACF,OAAO,IAAIE,SAAS,OAAO;YACzB,OAAO,MAAMI,IAAAA,qCAAgC,EAACH,KAAK;gBACjDE,KAAKV;gBACLM,MAAMD;YACR;QACF,OAAO,IAAIE,SAAS,cAAc;YAChC,OAAO,MAAMK,oCAAoCZ,mBAAmBI,KAAKC,SAASG;QACpF,OAAO;YACL,MAAM,IAAIK,MAAM,CAAC,uBAAuB,EAAEN,MAAM;QAClD;IACF,OAAO;QACL,IAAI;YACF,OAAO,MAAMO,IAAAA,+CAAyB,EAAC;gBAAEd;gBAAmBC;gBAAaE;YAAI;QAC/E,EAAE,OAAOY,OAAY;YACnB,MAAMC,sBAAsBC,wCAAwCd,IAAIe,UAAU;YAClFpB,MAAM,6BAA6BkB;YACnC,OAAO,MAAML,IAAAA,qCAAgC,EAACK,qBAAqB;gBACjEN,KAAKV;gBACLM,MAAMH,IAAIG,IAAI;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;YACjB,MAAMA;QACR;IACF;IACA,IAAI,CAAC4C,SAAS;QACZF,YAAYK,IAAI,CAAC,CAAC,aAAa,EAAEC,gBAAK,CAACC,GAAG,CAAC,CAAC,CAAC,EAAE9D,SAAS,CAAC,CAAC,EAAE,6BAA6B,CAAC;QAC1F,MAAM,IAAI+D,yBAAiB;IAC7B;IAEA,IAAIN,QAAQO,MAAM,KAAK,sBAAsB;QAC3CT,YAAYK,IAAI,CACd,CAAC,aAAa,EAAEC,gBAAK,CAACC,GAAG,CACvB,CAAC,CAAC,EAAE9D,SAAS,CAAC,CAAC,EACf,4EAA4E,CAAC;QAEjF,MAAM,IAAI+D,yBAAiB;IAC7B;IAEA,MAAME,WAAW,MAAM5C,YAAYoC,SAASD;IAE5C,IAAI,CAACS,UAAU;QACbV,YAAYK,IAAI,CACd,CAAC,0BAA0B,EAAEC,gBAAK,CAACC,GAAG,CAAC,CAAC,CAAC,EAAE9D,SAAS,CAAC,CAAC,EAAE,4BAA4B,CAAC;QAEvF,MAAM,IAAI+D,yBAAiB;IAC7B;IAEA,MAAMG,QAAQ,MAAMzB,QAAQwB;IAE5B,IAAI,CAACC,OAAO;QACVX,YAAYK,IAAI,CACd,CAAC,oCAAoC,EAAEC,gBAAK,CAACC,GAAG,CAC9C,CAAC,CAAC,EAAE9D,SAAS,CAAC,CAAC,EACf,iDAAiD,CAAC;QAEtD,MAAM,IAAI+D,yBAAiB;IAC7B;IAEAR,YAAYY,IAAI,GAAGN,gBAAK,CAACO,IAAI,CAC3B,CAAC,4BAA4B,EAAEP,gBAAK,CAACQ,IAAI,CAACrE,UAAU,2BAA2B,CAAC;IAGlF,OAAO,MAAM6C,4BAA4BoB,UAAU;QACjDzD,KAAKV;QACLM,MAAMD;IACR;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/prebuild/resolveTemplate.ts"],"sourcesContent":["import { ExpoConfig } from '@expo/config';\nimport chalk from 'chalk';\nimport { Ora } from 'ora';\nimport semver from 'semver';\n\nimport { type ResolvedTemplateOption } from './resolveOptions';\nimport { fetchAsync } from '../api/rest/client';\nimport * as Log from '../log';\nimport { resolveLocalTemplateAsync } from './resolveLocalTemplate';\nimport { createGlobFilter } from '../utils/createFileTransform';\nimport { AbortCommandError } from '../utils/errors';\nimport {\n downloadAndExtractNpmModuleAsync,\n extractLocalNpmTarballAsync,\n extractNpmTarballFromUrlAsync,\n} from '../utils/npm';\nimport { isUrlOk } from '../utils/url';\n\nconst debug = require('debug')('expo:prebuild:resolveTemplate') as typeof console.log;\n\ntype RepoInfo = {\n username: string;\n name: string;\n branch: string;\n filePath: string;\n};\n\nexport async function cloneTemplateAsync({\n templateDirectory,\n projectRoot,\n template,\n exp,\n ora,\n}: {\n templateDirectory: string;\n projectRoot: string;\n template?: ResolvedTemplateOption;\n exp: Pick<ExpoConfig, 'name' | 'sdkVersion'>;\n ora: Ora;\n}): Promise<string> {\n if (template) {\n const expName = exp.name;\n const { type, uri } = template;\n if (type === 'file') {\n return await extractLocalNpmTarballAsync(uri, templateDirectory, {\n expName,\n });\n } else if (type === 'npm') {\n return await downloadAndExtractNpmModuleAsync(uri, templateDirectory, {\n expName,\n });\n } else if (type === 'repository') {\n return await resolveAndDownloadRepoTemplateAsync(templateDirectory, ora, expName, uri);\n } else {\n throw new Error(`Unknown template type: ${type}`);\n }\n } else {\n try {\n return await resolveLocalTemplateAsync({ templateDirectory, projectRoot, exp });\n } catch (error: any) {\n const templatePackageName = getTemplateNpmPackageNameFromSdkVersion(exp.sdkVersion);\n debug('Fallback to SDK template:', templatePackageName);\n return await downloadAndExtractNpmModuleAsync(templatePackageName, templateDirectory, {\n expName: exp.name,\n });\n }\n }\n}\n\n/** Given an `sdkVersion` like `44.0.0` return a fully qualified NPM package name like: `expo-template-bare-minimum@sdk-44` */\nfunction getTemplateNpmPackageNameFromSdkVersion(sdkVersion?: string): string {\n // When undefined or UNVERSIONED, we use the latest version.\n if (!sdkVersion || sdkVersion === 'UNVERSIONED') {\n Log.log('Using an unspecified Expo SDK version. The latest template will be used.');\n return `expo-template-bare-minimum@latest`;\n }\n return `expo-template-bare-minimum@sdk-${semver.major(sdkVersion)}`;\n}\n\nasync function getRepoInfo(url: any, examplePath?: string): Promise<RepoInfo | undefined> {\n const [, username, name, t, _branch, ...file] = url.pathname.split('/');\n const filePath = examplePath ? examplePath.replace(/^\\//, '') : file.join('/');\n\n // Support repos whose entire purpose is to be an example, e.g.\n // https://github.com/:username/:my-cool-example-repo-name.\n if (t === undefined) {\n const infoResponse = await fetchAsync(`https://api.github.com/repos/${username}/${name}`);\n if (infoResponse.status !== 200) {\n return;\n }\n const info: any = await infoResponse.json();\n return { username, name, branch: info['default_branch'], filePath };\n }\n\n // If examplePath is available, the branch name takes the entire path\n const branch = examplePath\n ? `${_branch}/${file.join('/')}`.replace(new RegExp(`/${filePath}|/$`), '')\n : _branch;\n\n if (username && name && branch && t === 'tree') {\n return { username, name, branch, filePath };\n }\n return undefined;\n}\n\nfunction hasRepo({ username, name, branch, filePath }: RepoInfo) {\n const contentsUrl = `https://api.github.com/repos/${username}/${name}/contents`;\n const packagePath = `${filePath ? `/${filePath}` : ''}/package.json`;\n\n return isUrlOk(contentsUrl + packagePath + `?ref=${branch}`);\n}\n\nasync function downloadAndExtractRepoAsync(\n { username, name, branch, filePath }: RepoInfo,\n output: string,\n props: { expName?: string }\n): Promise<string> {\n const url = `https://codeload.github.com/${username}/${name}/tar.gz/${branch}`;\n\n debug('Downloading tarball from:', url);\n\n // Extract the (sub)directory into non-empty path segments\n const directory = filePath.replace(/^\\//, '').split('/').filter(Boolean);\n // Remove the (sub)directory paths, and the root folder added by GitHub\n const strip = directory.length + 1;\n // Only extract the relevant (sub)directories, ignoring irrelevant files\n // The filder auto-ignores dotfiles, unless explicitly included\n const filter = createGlobFilter(\n !directory.length\n ? ['*/**', '*/ios/.xcode.env']\n : [`*/${directory.join('/')}/**`, `*/${directory.join('/')}/ios/.xcode.env`],\n {\n // Always ignore the `.xcworkspace` folder\n ignore: ['**/ios/*.xcworkspace/**'],\n }\n );\n\n return await extractNpmTarballFromUrlAsync(url, output, {\n ...props,\n strip,\n filter,\n });\n}\n\nasync function resolveAndDownloadRepoTemplateAsync(\n templateDirectory: string,\n oraInstance: Ora,\n expName: string,\n template: string,\n templatePath?: string\n) {\n let repoUrl: URL | undefined;\n\n try {\n repoUrl = new URL(template);\n } catch (error: any) {\n if (error.code !== 'ERR_INVALID_URL') {\n oraInstance.fail(error);\n throw error;\n }\n }\n if (!repoUrl) {\n oraInstance.fail(`Invalid URL: ${chalk.red(`\"${template}\"`)}. Try again with a valid URL.`);\n throw new AbortCommandError();\n }\n\n if (repoUrl.origin !== 'https://github.com') {\n oraInstance.fail(\n `Invalid URL: ${chalk.red(\n `\"${template}\"`\n )}. Only GitHub repositories are supported. Try again with a valid GitHub URL.`\n );\n throw new AbortCommandError();\n }\n\n const repoInfo = await getRepoInfo(repoUrl, templatePath);\n\n if (!repoInfo) {\n oraInstance.fail(\n `Found invalid GitHub URL: ${chalk.red(`\"${template}\"`)}. Fix the URL and try again.`\n );\n throw new AbortCommandError();\n }\n\n const found = await hasRepo(repoInfo);\n\n if (!found) {\n oraInstance.fail(\n `Could not locate the repository for ${chalk.red(\n `\"${template}\"`\n )}. Check that the repository exists and try again.`\n );\n throw new AbortCommandError();\n }\n\n oraInstance.text = chalk.bold(\n `Downloading files from repo ${chalk.cyan(template)}. This might take a moment.`\n );\n\n return await downloadAndExtractRepoAsync(repoInfo, templateDirectory, { expName });\n}\n"],"names":["cloneTemplateAsync","debug","require","templateDirectory","projectRoot","template","exp","ora","expName","name","type","uri","extractLocalNpmTarballAsync","downloadAndExtractNpmModuleAsync","resolveAndDownloadRepoTemplateAsync","Error","resolveLocalTemplateAsync","error","templatePackageName","getTemplateNpmPackageNameFromSdkVersion","sdkVersion","Log","log","semver","major","getRepoInfo","url","examplePath","username","t","_branch","file","pathname","split","filePath","replace","join","undefined","infoResponse","fetchAsync","status","info","json","branch","RegExp","hasRepo","contentsUrl","packagePath","isUrlOk","downloadAndExtractRepoAsync","output","props","directory","filter","Boolean","strip","length","createGlobFilter","ignore","extractNpmTarballFromUrlAsync","oraInstance","templatePath","repoUrl","URL","code","fail","chalk","red","AbortCommandError","origin","repoInfo","found","text","bold","cyan"],"mappings":";;;;+BA2BsBA;;;eAAAA;;;;gEA1BJ;;;;;;;gEAEC;;;;;;wBAGQ;6DACN;sCACqB;qCACT;wBACC;qBAK3B;qBACiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAExB,MAAMC,QAAQC,QAAQ,SAAS;AASxB,eAAeF,mBAAmB,EACvCG,iBAAiB,EACjBC,WAAW,EACXC,QAAQ,EACRC,GAAG,EACHC,GAAG,EAOJ;IACC,IAAIF,UAAU;QACZ,MAAMG,UAAUF,IAAIG,IAAI;QACxB,MAAM,EAAEC,IAAI,EAAEC,GAAG,EAAE,GAAGN;QACtB,IAAIK,SAAS,QAAQ;YACnB,OAAO,MAAME,IAAAA,gCAA2B,EAACD,KAAKR,mBAAmB;gBAC/DK;YACF;QACF,OAAO,IAAIE,SAAS,OAAO;YACzB,OAAO,MAAMG,IAAAA,qCAAgC,EAACF,KAAKR,mBAAmB;gBACpEK;YACF;QACF,OAAO,IAAIE,SAAS,cAAc;YAChC,OAAO,MAAMI,oCAAoCX,mBAAmBI,KAAKC,SAASG;QACpF,OAAO;YACL,MAAM,IAAII,MAAM,CAAC,uBAAuB,EAAEL,MAAM;QAClD;IACF,OAAO;QACL,IAAI;YACF,OAAO,MAAMM,IAAAA,+CAAyB,EAAC;gBAAEb;gBAAmBC;gBAAaE;YAAI;QAC/E,EAAE,OAAOW,OAAY;YACnB,MAAMC,sBAAsBC,wCAAwCb,IAAIc,UAAU;YAClFnB,MAAM,6BAA6BiB;YACnC,OAAO,MAAML,IAAAA,qCAAgC,EAACK,qBAAqBf,mBAAmB;gBACpFK,SAASF,IAAIG,IAAI;YACnB;QACF;IACF;AACF;AAEA,4HAA4H,GAC5H,SAASU,w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,CAAC6C,SAAS;QACZF,YAAYK,IAAI,CAAC,CAAC,aAAa,EAAEC,gBAAK,CAACC,GAAG,CAAC,CAAC,CAAC,EAAE9D,SAAS,CAAC,CAAC,EAAE,6BAA6B,CAAC;QAC1F,MAAM,IAAI+D,yBAAiB;IAC7B;IAEA,IAAIN,QAAQO,MAAM,KAAK,sBAAsB;QAC3CT,YAAYK,IAAI,CACd,CAAC,aAAa,EAAEC,gBAAK,CAACC,GAAG,CACvB,CAAC,CAAC,EAAE9D,SAAS,CAAC,CAAC,EACf,4EAA4E,CAAC;QAEjF,MAAM,IAAI+D,yBAAiB;IAC7B;IAEA,MAAME,WAAW,MAAM7C,YAAYqC,SAASD;IAE5C,IAAI,CAACS,UAAU;QACbV,YAAYK,IAAI,CACd,CAAC,0BAA0B,EAAEC,gBAAK,CAACC,GAAG,CAAC,CAAC,CAAC,EAAE9D,SAAS,CAAC,CAAC,EAAE,4BAA4B,CAAC;QAEvF,MAAM,IAAI+D,yBAAiB;IAC7B;IAEA,MAAMG,QAAQ,MAAM1B,QAAQyB;IAE5B,IAAI,CAACC,OAAO;QACVX,YAAYK,IAAI,CACd,CAAC,oCAAoC,EAAEC,gBAAK,CAACC,GAAG,CAC9C,CAAC,CAAC,EAAE9D,SAAS,CAAC,CAAC,EACf,iDAAiD,CAAC;QAEtD,MAAM,IAAI+D,yBAAiB;IAC7B;IAEAR,YAAYY,IAAI,GAAGN,gBAAK,CAACO,IAAI,CAC3B,CAAC,4BAA4B,EAAEP,gBAAK,CAACQ,IAAI,CAACrE,UAAU,2BAA2B,CAAC;IAGlF,OAAO,MAAM4C,4BAA4BqB,UAAUnE,mBAAmB;QAAEK;IAAQ;AAClF"}
|
|
@@ -123,13 +123,11 @@ async function cloneTemplateAndCopyToProjectAsync({ projectRoot, templateDirecto
|
|
|
123
123
|
templateDirectory,
|
|
124
124
|
platforms
|
|
125
125
|
});
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
await (0, _renameTemplateAppName.renameTemplateAppNameAsync)({
|
|
130
|
-
cwd: projectRoot,
|
|
126
|
+
// TODO(@kitten): This duplicates functionality that `cloneTemplateAsync` can already do
|
|
127
|
+
const files = await (0, _renameTemplateAppName.getTemplateFilesToRenameAsync)(projectRoot);
|
|
128
|
+
await (0, _renameTemplateAppName.renameTemplateAppNameAsync)(projectRoot, {
|
|
131
129
|
files,
|
|
132
|
-
|
|
130
|
+
expName: exp.name
|
|
133
131
|
});
|
|
134
132
|
// Says: "Created native directories"
|
|
135
133
|
ora.succeed((0, _copyTemplateFiles.createCopyFilesSuccessMessage)(platforms, results));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/prebuild/updateFromTemplate.ts"],"sourcesContent":["import { ExpoConfig, PackageJSONConfig } from '@expo/config';\nimport { ModPlatform } from '@expo/config-plugins';\nimport chalk from 'chalk';\n\nimport { copyTemplateFiles, createCopyFilesSuccessMessage } from './copyTemplateFiles';\nimport { getTemplateFilesToRenameAsync, renameTemplateAppNameAsync } from './renameTemplateAppName';\nimport { type ResolvedTemplateOption } from './resolveOptions';\nimport { cloneTemplateAsync } from './resolveTemplate';\nimport { DependenciesModificationResults, updatePackageJSONAsync } from './updatePackageJson';\nimport { validateTemplatePlatforms } from './validateTemplatePlatforms';\nimport * as Log from '../log';\nimport { createTempDirectoryPath } from '../utils/createTempPath';\nimport { AbortCommandError, SilentError } from '../utils/errors';\nimport { logNewSection } from '../utils/ora';\nimport { profile } from '../utils/profile';\n\n/**\n * Creates local native files from an input template file path.\n *\n * @return `true` if the project is prebuilding, and `false` if it's syncing.\n */\nexport async function updateFromTemplateAsync(\n projectRoot: string,\n {\n exp,\n pkg,\n template,\n templateDirectory,\n platforms,\n skipDependencyUpdate,\n }: {\n /** Expo Config */\n exp: ExpoConfig;\n /** package.json as JSON */\n pkg: PackageJSONConfig;\n /** Template to clone from. */\n template?: ResolvedTemplateOption;\n /** Directory to write the template to before copying into the project. */\n templateDirectory?: string;\n /** List of platforms to clone. */\n platforms: ModPlatform[];\n /** List of dependencies to skip updating. */\n skipDependencyUpdate?: string[];\n }\n): Promise<\n {\n /** Indicates if new files were created in the project. */\n hasNewProjectFiles: boolean;\n /** Indicates that the project needs to run `pod install` */\n needsPodInstall: boolean;\n /** The template checksum used to create the native project. */\n templateChecksum: string;\n } & DependenciesModificationResults\n> {\n if (!templateDirectory) {\n templateDirectory = createTempDirectoryPath();\n }\n\n const { copiedPaths, templateChecksum } = await profile(cloneTemplateAndCopyToProjectAsync)({\n projectRoot,\n template,\n templateDirectory,\n exp,\n platforms,\n });\n\n const depsResults = await profile(updatePackageJSONAsync)(projectRoot, {\n templateDirectory,\n pkg,\n skipDependencyUpdate,\n });\n\n return {\n hasNewProjectFiles: !!copiedPaths.length,\n // If the iOS folder changes or new packages are added, we should rerun pod install.\n needsPodInstall: copiedPaths.includes('ios') || !!depsResults.changedDependencies.length,\n templateChecksum,\n ...depsResults,\n };\n}\n\n/**\n * Extract the template and copy the ios and android directories over to the project directory.\n *\n * @return `true` if any project files were created.\n */\nexport async function cloneTemplateAndCopyToProjectAsync({\n projectRoot,\n templateDirectory,\n template,\n exp,\n platforms: unknownPlatforms,\n}: {\n projectRoot: string;\n templateDirectory: string;\n template?: ResolvedTemplateOption;\n exp: Pick<ExpoConfig, 'name' | 'sdkVersion'>;\n platforms: ModPlatform[];\n}): Promise<{ copiedPaths: string[]; templateChecksum: string }> {\n const platformDirectories = unknownPlatforms\n .map((platform) => `./${platform}`)\n .reverse()\n .join(' and ');\n\n const pluralized = unknownPlatforms.length > 1 ? 'directories' : 'directory';\n const ora = logNewSection(`Creating native ${pluralized} (${platformDirectories})`);\n\n try {\n const templateChecksum = await cloneTemplateAsync({\n templateDirectory,\n projectRoot,\n template,\n exp,\n ora,\n });\n\n const platforms = validateTemplatePlatforms({\n templateDirectory,\n platforms: unknownPlatforms,\n });\n\n const results = copyTemplateFiles(projectRoot, {\n templateDirectory,\n platforms,\n });\n\n const files = await getTemplateFilesToRenameAsync(
|
|
1
|
+
{"version":3,"sources":["../../../src/prebuild/updateFromTemplate.ts"],"sourcesContent":["import { ExpoConfig, PackageJSONConfig } from '@expo/config';\nimport { ModPlatform } from '@expo/config-plugins';\nimport chalk from 'chalk';\n\nimport { copyTemplateFiles, createCopyFilesSuccessMessage } from './copyTemplateFiles';\nimport { getTemplateFilesToRenameAsync, renameTemplateAppNameAsync } from './renameTemplateAppName';\nimport { type ResolvedTemplateOption } from './resolveOptions';\nimport { cloneTemplateAsync } from './resolveTemplate';\nimport { DependenciesModificationResults, updatePackageJSONAsync } from './updatePackageJson';\nimport { validateTemplatePlatforms } from './validateTemplatePlatforms';\nimport * as Log from '../log';\nimport { createTempDirectoryPath } from '../utils/createTempPath';\nimport { AbortCommandError, SilentError } from '../utils/errors';\nimport { logNewSection } from '../utils/ora';\nimport { profile } from '../utils/profile';\n\n/**\n * Creates local native files from an input template file path.\n *\n * @return `true` if the project is prebuilding, and `false` if it's syncing.\n */\nexport async function updateFromTemplateAsync(\n projectRoot: string,\n {\n exp,\n pkg,\n template,\n templateDirectory,\n platforms,\n skipDependencyUpdate,\n }: {\n /** Expo Config */\n exp: ExpoConfig;\n /** package.json as JSON */\n pkg: PackageJSONConfig;\n /** Template to clone from. */\n template?: ResolvedTemplateOption;\n /** Directory to write the template to before copying into the project. */\n templateDirectory?: string;\n /** List of platforms to clone. */\n platforms: ModPlatform[];\n /** List of dependencies to skip updating. */\n skipDependencyUpdate?: string[];\n }\n): Promise<\n {\n /** Indicates if new files were created in the project. */\n hasNewProjectFiles: boolean;\n /** Indicates that the project needs to run `pod install` */\n needsPodInstall: boolean;\n /** The template checksum used to create the native project. */\n templateChecksum: string;\n } & DependenciesModificationResults\n> {\n if (!templateDirectory) {\n templateDirectory = createTempDirectoryPath();\n }\n\n const { copiedPaths, templateChecksum } = await profile(cloneTemplateAndCopyToProjectAsync)({\n projectRoot,\n template,\n templateDirectory,\n exp,\n platforms,\n });\n\n const depsResults = await profile(updatePackageJSONAsync)(projectRoot, {\n templateDirectory,\n pkg,\n skipDependencyUpdate,\n });\n\n return {\n hasNewProjectFiles: !!copiedPaths.length,\n // If the iOS folder changes or new packages are added, we should rerun pod install.\n needsPodInstall: copiedPaths.includes('ios') || !!depsResults.changedDependencies.length,\n templateChecksum,\n ...depsResults,\n };\n}\n\n/**\n * Extract the template and copy the ios and android directories over to the project directory.\n *\n * @return `true` if any project files were created.\n */\nexport async function cloneTemplateAndCopyToProjectAsync({\n projectRoot,\n templateDirectory,\n template,\n exp,\n platforms: unknownPlatforms,\n}: {\n projectRoot: string;\n templateDirectory: string;\n template?: ResolvedTemplateOption;\n exp: Pick<ExpoConfig, 'name' | 'sdkVersion'>;\n platforms: ModPlatform[];\n}): Promise<{ copiedPaths: string[]; templateChecksum: string }> {\n const platformDirectories = unknownPlatforms\n .map((platform) => `./${platform}`)\n .reverse()\n .join(' and ');\n\n const pluralized = unknownPlatforms.length > 1 ? 'directories' : 'directory';\n const ora = logNewSection(`Creating native ${pluralized} (${platformDirectories})`);\n\n try {\n const templateChecksum = await cloneTemplateAsync({\n templateDirectory,\n projectRoot,\n template,\n exp,\n ora,\n });\n\n const platforms = validateTemplatePlatforms({\n templateDirectory,\n platforms: unknownPlatforms,\n });\n\n const results = copyTemplateFiles(projectRoot, {\n templateDirectory,\n platforms,\n });\n\n // TODO(@kitten): This duplicates functionality that `cloneTemplateAsync` can already do\n const files = await getTemplateFilesToRenameAsync(projectRoot);\n await renameTemplateAppNameAsync(projectRoot, {\n files,\n expName: exp.name,\n });\n\n // Says: \"Created native directories\"\n ora.succeed(createCopyFilesSuccessMessage(platforms, results));\n\n return {\n copiedPaths: results.copiedPaths,\n templateChecksum,\n };\n } catch (e: any) {\n if (!(e instanceof AbortCommandError)) {\n Log.error(e.message);\n }\n ora.fail(`Failed to create the native ${pluralized}`);\n Log.log(\n chalk.yellow(\n chalk`You may want to delete the {bold ./ios} and/or {bold ./android} directories before trying again.`\n )\n );\n throw new SilentError(e);\n }\n}\n"],"names":["cloneTemplateAndCopyToProjectAsync","updateFromTemplateAsync","projectRoot","exp","pkg","template","templateDirectory","platforms","skipDependencyUpdate","createTempDirectoryPath","copiedPaths","templateChecksum","profile","depsResults","updatePackageJSONAsync","hasNewProjectFiles","length","needsPodInstall","includes","changedDependencies","unknownPlatforms","platformDirectories","map","platform","reverse","join","pluralized","ora","logNewSection","cloneTemplateAsync","validateTemplatePlatforms","results","copyTemplateFiles","files","getTemplateFilesToRenameAsync","renameTemplateAppNameAsync","expName","name","succeed","createCopyFilesSuccessMessage","e","AbortCommandError","Log","error","message","fail","log","chalk","yellow","SilentError"],"mappings":";;;;;;;;;;;IAsFsBA,kCAAkC;eAAlCA;;IAjEAC,uBAAuB;eAAvBA;;;;gEAnBJ;;;;;;mCAE+C;uCACS;iCAEvC;mCACqC;2CAC9B;6DACrB;gCACmB;wBACO;qBACjB;yBACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOjB,eAAeA,wBACpBC,WAAmB,EACnB,EACEC,GAAG,EACHC,GAAG,EACHC,QAAQ,EACRC,iBAAiB,EACjBC,SAAS,EACTC,oBAAoB,EAcrB;IAWD,IAAI,CAACF,mBAAmB;QACtBA,oBAAoBG,IAAAA,uCAAuB;IAC7C;IAEA,MAAM,EAAEC,WAAW,EAAEC,gBAAgB,EAAE,GAAG,MAAMC,IAAAA,gBAAO,EAACZ,oCAAoC;QAC1FE;QACAG;QACAC;QACAH;QACAI;IACF;IAEA,MAAMM,cAAc,MAAMD,IAAAA,gBAAO,EAACE,yCAAsB,EAAEZ,aAAa;QACrEI;QACAF;QACAI;IACF;IAEA,OAAO;QACLO,oBAAoB,CAAC,CAACL,YAAYM,MAAM;QACxC,oFAAoF;QACpFC,iBAAiBP,YAAYQ,QAAQ,CAAC,UAAU,CAAC,CAACL,YAAYM,mBAAmB,CAACH,MAAM;QACxFL;QACA,GAAGE,WAAW;IAChB;AACF;AAOO,eAAeb,mCAAmC,EACvDE,WAAW,EAC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};
|
|
24
24
|
return data;
|
|
25
25
|
}
|
|
26
|
-
function _requireg() {
|
|
27
|
-
const data = /*#__PURE__*/ _interop_require_default(require("requireg"));
|
|
28
|
-
_requireg = function() {
|
|
29
|
-
return data;
|
|
30
|
-
};
|
|
31
|
-
return data;
|
|
32
|
-
}
|
|
33
26
|
function _resolvefrom() {
|
|
34
27
|
const data = /*#__PURE__*/ _interop_require_default(require("resolve-from"));
|
|
35
28
|
_resolvefrom = function() {
|
|
@@ -49,6 +42,7 @@ const _delay = require("../../../utils/delay");
|
|
|
49
42
|
const _env = require("../../../utils/env");
|
|
50
43
|
const _errors = require("../../../utils/errors");
|
|
51
44
|
const _prompts = require("../../../utils/prompts");
|
|
45
|
+
const _resolveGlobal = require("../../../utils/resolveGlobal");
|
|
52
46
|
function _interop_require_default(obj) {
|
|
53
47
|
return obj && obj.__esModule ? obj : {
|
|
54
48
|
default: obj
|
|
@@ -188,7 +182,7 @@ class ExternalModule {
|
|
|
188
182
|
return (0, _resolvefrom().default)(this.projectRoot, moduleId);
|
|
189
183
|
}
|
|
190
184
|
/** Resolve a copy that's installed globally. Exposed for testing. */ _resolveGlobal(moduleId) {
|
|
191
|
-
return
|
|
185
|
+
return (0, _resolveGlobal.resolveGlobal)(moduleId);
|
|
192
186
|
}
|
|
193
187
|
/** Resolve the module and verify the version. Exposed for testing. */ _resolveModule(isLocal) {
|
|
194
188
|
const resolver = isLocal ? this._resolveLocal.bind(this) : this._resolveGlobal.bind(this);
|