feat(smart-app): implement complete mobile app MVP

- App.tsx: full navigation (Auth stack + Main tabs with 5 screens)
- Auth: LoginScreen, RegisterScreen, ForgotPasswordScreen
- HomeScreen: dashboard with IoT metrics, weather widget, alerts, quick actions, sensors
- MapScreen: interactive map with layer toggles (6 layers)
- MarketplaceScreen: categories (6), products (5), search
- ChatScreen: AI chat with quick prompts (4), bot responses
- ProfileScreen: user info, stats, menu (9 items), logout
- AlertsScreen: alert list with severity, acknowledge
- SensorsScreen: sensor list with type filters (6 types), search
- ZonesScreen: zone cards with stats
- SettingsScreen: language picker (FR/EN/ES/DE), privacy, about
- Stores: iotStore (sensors, zones, alerts), notificationStore, uiStore + i18n
- Hooks: useSensors, useAlerts, useNotifications, useLocation
- Components: Card, Button, LoadingSpinner, ErrorBoundary, Header
- Services: iotService, notificationService (with axios API client)
- Utils: formatters (temp, AQI, noise, dates), validators (email, password, IBAN)
- Theme: colors.ts with full design system (Blue Ocean palette)
- Ditto: fixed MongoDB connection, new JWT secrets, official gateway image
This commit is contained in:
Eric FELIXINE
2026-06-01 18:00:35 -04:00
parent 08ca495bde
commit e30ae8ed09
35578 changed files with 3703534 additions and 43 deletions

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getExpoApiBaseUrl: ()=>getExpoApiBaseUrl,
getExpoWebsiteBaseUrl: ()=>getExpoWebsiteBaseUrl
});
const _env = require("../utils/env");
function getExpoApiBaseUrl() {
if (_env.env.EXPO_STAGING) {
return `https://staging-api.expo.dev`;
} else if (_env.env.EXPO_LOCAL) {
return `http://127.0.0.1:3000`;
} else {
return `https://api.expo.dev`;
}
}
function getExpoWebsiteBaseUrl() {
if (_env.env.EXPO_STAGING) {
return `https://staging.expo.dev`;
} else if (_env.env.EXPO_LOCAL) {
return `http://127.0.0.1:3001`;
} else {
return `https://expo.dev`;
}
}
//# sourceMappingURL=endpoint.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/api/endpoint.ts"],"sourcesContent":["import { env } from '../utils/env';\n\n/** Get the URL for the expo.dev API. */\nexport function getExpoApiBaseUrl(): string {\n if (env.EXPO_STAGING) {\n return `https://staging-api.expo.dev`;\n } else if (env.EXPO_LOCAL) {\n return `http://127.0.0.1:3000`;\n } else {\n return `https://api.expo.dev`;\n }\n}\n\n/** Get the URL for the expo.dev website. */\nexport function getExpoWebsiteBaseUrl(): string {\n if (env.EXPO_STAGING) {\n return `https://staging.expo.dev`;\n } else if (env.EXPO_LOCAL) {\n return `http://127.0.0.1:3001`;\n } else {\n return `https://expo.dev`;\n }\n}\n"],"names":["getExpoApiBaseUrl","getExpoWebsiteBaseUrl","env","EXPO_STAGING","EXPO_LOCAL"],"mappings":"AAAA;;;;;;;;;;;IAGgBA,iBAAiB,MAAjBA,iBAAiB;IAWjBC,qBAAqB,MAArBA,qBAAqB;;qBAdjB,cAAc;AAG3B,SAASD,iBAAiB,GAAW;IAC1C,IAAIE,IAAG,IAAA,CAACC,YAAY,EAAE;QACpB,OAAO,CAAC,4BAA4B,CAAC,CAAC;IACxC,OAAO,IAAID,IAAG,IAAA,CAACE,UAAU,EAAE;QACzB,OAAO,CAAC,qBAAqB,CAAC,CAAC;IACjC,OAAO;QACL,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAChC,CAAC;AACH,CAAC;AAGM,SAASH,qBAAqB,GAAW;IAC9C,IAAIC,IAAG,IAAA,CAACC,YAAY,EAAE;QACpB,OAAO,CAAC,wBAAwB,CAAC,CAAC;IACpC,OAAO,IAAID,IAAG,IAAA,CAACE,UAAU,EAAE;QACzB,OAAO,CAAC,qBAAqB,CAAC,CAAC;IACjC,OAAO;QACL,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAC5B,CAAC;AACH,CAAC"}

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getExpoGoIntermediateCertificateAsync", {
enumerable: true,
get: ()=>getExpoGoIntermediateCertificateAsync
});
const _client = require("./rest/client");
const _errors = require("../utils/errors");
async function getExpoGoIntermediateCertificateAsync(easProjectId) {
const response = await (0, _client.fetchAsync)(`projects/${encodeURIComponent(easProjectId)}/development-certificates/expo-go-intermediate-certificate`, {
method: "GET"
});
if (!response.ok) {
throw new _errors.CommandError("API", `Unexpected error from Expo servers: ${response.statusText}.`);
}
const buffer = await response.buffer();
return buffer.toString("utf8");
}
//# sourceMappingURL=getExpoGoIntermediateCertificate.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/api/getExpoGoIntermediateCertificate.ts"],"sourcesContent":["import { fetchAsync } from './rest/client';\nimport { CommandError } from '../utils/errors';\n\nexport async function getExpoGoIntermediateCertificateAsync(easProjectId: string): Promise<string> {\n const response = await fetchAsync(\n `projects/${encodeURIComponent(\n easProjectId\n )}/development-certificates/expo-go-intermediate-certificate`,\n {\n method: 'GET',\n }\n );\n if (!response.ok) {\n throw new CommandError('API', `Unexpected error from Expo servers: ${response.statusText}.`);\n }\n const buffer = await response.buffer();\n return buffer.toString('utf8');\n}\n"],"names":["getExpoGoIntermediateCertificateAsync","easProjectId","response","fetchAsync","encodeURIComponent","method","ok","CommandError","statusText","buffer","toString"],"mappings":"AAAA;;;;+BAGsBA,uCAAqC;;aAArCA,qCAAqC;;wBAHhC,eAAe;wBACb,iBAAiB;AAEvC,eAAeA,qCAAqC,CAACC,YAAoB,EAAmB;IACjG,MAAMC,QAAQ,GAAG,MAAMC,IAAAA,OAAU,WAAA,EAC/B,CAAC,SAAS,EAAEC,kBAAkB,CAC5BH,YAAY,CACb,CAAC,0DAA0D,CAAC,EAC7D;QACEI,MAAM,EAAE,KAAK;KACd,CACF,AAAC;IACF,IAAI,CAACH,QAAQ,CAACI,EAAE,EAAE;QAChB,MAAM,IAAIC,OAAY,aAAA,CAAC,KAAK,EAAE,CAAC,oCAAoC,EAAEL,QAAQ,CAACM,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/F,CAAC;IACD,MAAMC,MAAM,GAAG,MAAMP,QAAQ,CAACO,MAAM,EAAE,AAAC;IACvC,OAAOA,MAAM,CAACC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACjC,CAAC"}

View File

@@ -0,0 +1,89 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getAssetSchemasAsync", {
enumerable: true,
get: ()=>getAssetSchemasAsync
});
function _fs() {
const data = /*#__PURE__*/ _interopRequireDefault(require("fs"));
_fs = function() {
return data;
};
return data;
}
function _jsonSchemaDerefSync() {
const data = /*#__PURE__*/ _interopRequireDefault(require("json-schema-deref-sync"));
_jsonSchemaDerefSync = function() {
return data;
};
return data;
}
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
const _client = require("./rest/client");
const _env = require("../utils/env");
const _errors = require("../utils/errors");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const schemaJson = {};
// TODO: Maybe move json-schema-deref-sync out of api (1.58MB -- lodash)
// https://packagephobia.com/result?p=json-schema-deref-sync
async function getSchemaAsync(sdkVersion) {
const json = await getSchemaJSONAsync(sdkVersion);
return (0, _jsonSchemaDerefSync().default)(json.schema);
}
async function getAssetSchemasAsync(sdkVersion = "UNVERSIONED") {
// If no SDK version is available then fall back to unversioned
const schema = await getSchemaAsync(sdkVersion);
const assetSchemas = [];
const visit = (node, fieldPath)=>{
if (node.meta && node.meta.asset) {
assetSchemas.push(fieldPath);
}
const properties = node.properties;
if (properties) {
Object.keys(properties).forEach((property)=>visit(properties[property], `${fieldPath}${fieldPath.length > 0 ? "." : ""}${property}`));
}
};
visit(schema, "");
return assetSchemas;
}
async function getSchemaJSONAsync(sdkVersion) {
if (_env.env.EXPO_UNIVERSE_DIR) {
return JSON.parse(_fs().default.readFileSync(_path().default.join(_env.env.EXPO_UNIVERSE_DIR, "server", "www", "xdl-schemas", "UNVERSIONED-schema.json")).toString());
}
if (!schemaJson[sdkVersion]) {
try {
schemaJson[sdkVersion] = await getConfigurationSchemaAsync(sdkVersion);
} catch (e) {
if (e.code === "INVALID_JSON") {
throw new _errors.CommandError("INVALID_JSON", `Couldn't read schema from server`);
}
throw e;
}
}
return schemaJson[sdkVersion];
}
async function getConfigurationSchemaAsync(sdkVersion) {
// Reconstruct the cached fetch since caching could be disabled.
const fetchAsync = (0, _client.createCachedFetch)({
cacheDirectory: "schema-cache",
// We'll use a 1 week cache for versions so older versions get flushed out eventually.
ttl: 1000 * 60 * 60 * 24 * 7
});
const response = await fetchAsync(`project/configuration/schema/${sdkVersion}`);
const { data } = await response.json();
return data;
}
//# sourceMappingURL=getExpoSchema.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getNativeModuleVersionsAsync", {
enumerable: true,
get: ()=>getNativeModuleVersionsAsync
});
const _client = require("./rest/client");
const _errors = require("../utils/errors");
async function getNativeModuleVersionsAsync(sdkVersion) {
const fetchAsync = (0, _client.createCachedFetch)({
cacheDirectory: "native-modules-cache",
// 1 minute cache
ttl: 1000 * 60 * 1
});
const results = await fetchAsync(`sdks/${sdkVersion}/native-modules`);
if (!results.ok) {
throw new _errors.CommandError("API", `Unexpected response when fetching version info from Expo servers: ${results.statusText}.`);
}
const { data } = await results.json();
if (!data.length) {
throw new _errors.CommandError("VERSIONS", "The bundled native module list from the Expo API is empty");
}
return fromBundledNativeModuleList(data);
}
function fromBundledNativeModuleList(list) {
return list.reduce((acc, i)=>{
acc[i.npmPackage] = i.versionRange;
return acc;
}, {});
}
//# sourceMappingURL=getNativeModuleVersions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/api/getNativeModuleVersions.ts"],"sourcesContent":["import { createCachedFetch } from './rest/client';\nimport { CommandError } from '../utils/errors';\n\ninterface NativeModule {\n npmPackage: string;\n versionRange: string;\n}\ntype BundledNativeModuleList = NativeModule[];\n\nexport type BundledNativeModules = Record<string, string>;\n\n/**\n * The endpoint returns the list of bundled native modules for a given SDK version.\n * The data is populated by the `et sync-bundled-native-modules` script from expo/expo repo.\n * See the code for more details:\n * https://github.com/expo/expo/blob/main/tools/src/commands/SyncBundledNativeModules.ts\n *\n * Example result:\n * [\n * {\n * id: \"79285187-e5c4-47f7-b6a9-664f5d16f0db\",\n * sdkVersion: \"41.0.0\",\n * npmPackage: \"expo-camera\",\n * versionRange: \"~10.1.0\",\n * createdAt: \"2021-04-29T09:34:32.825Z\",\n * updatedAt: \"2021-04-29T09:34:32.825Z\"\n * },\n * ...\n * ]\n */\nexport async function getNativeModuleVersionsAsync(\n sdkVersion: string\n): Promise<BundledNativeModules> {\n const fetchAsync = createCachedFetch({\n cacheDirectory: 'native-modules-cache',\n // 1 minute cache\n ttl: 1000 * 60 * 1,\n });\n const results = await fetchAsync(`sdks/${sdkVersion}/native-modules`);\n if (!results.ok) {\n throw new CommandError(\n 'API',\n `Unexpected response when fetching version info from Expo servers: ${results.statusText}.`\n );\n }\n const { data } = await results.json();\n if (!data.length) {\n throw new CommandError('VERSIONS', 'The bundled native module list from the Expo API is empty');\n }\n return fromBundledNativeModuleList(data);\n}\n\nfunction fromBundledNativeModuleList(list: BundledNativeModuleList): BundledNativeModules {\n return list.reduce((acc, i) => {\n acc[i.npmPackage] = i.versionRange;\n return acc;\n }, {} as BundledNativeModules);\n}\n"],"names":["getNativeModuleVersionsAsync","sdkVersion","fetchAsync","createCachedFetch","cacheDirectory","ttl","results","ok","CommandError","statusText","data","json","length","fromBundledNativeModuleList","list","reduce","acc","i","npmPackage","versionRange"],"mappings":"AAAA;;;;+BA8BsBA,8BAA4B;;aAA5BA,4BAA4B;;wBA9BhB,eAAe;wBACpB,iBAAiB;AA6BvC,eAAeA,4BAA4B,CAChDC,UAAkB,EACa;IAC/B,MAAMC,UAAU,GAAGC,IAAAA,OAAiB,kBAAA,EAAC;QACnCC,cAAc,EAAE,sBAAsB;QACtC,iBAAiB;QACjBC,GAAG,EAAE,IAAI,GAAG,EAAE,GAAG,CAAC;KACnB,CAAC,AAAC;IACH,MAAMC,OAAO,GAAG,MAAMJ,UAAU,CAAC,CAAC,KAAK,EAAED,UAAU,CAAC,eAAe,CAAC,CAAC,AAAC;IACtE,IAAI,CAACK,OAAO,CAACC,EAAE,EAAE;QACf,MAAM,IAAIC,OAAY,aAAA,CACpB,KAAK,EACL,CAAC,kEAAkE,EAAEF,OAAO,CAACG,UAAU,CAAC,CAAC,CAAC,CAC3F,CAAC;IACJ,CAAC;IACD,MAAM,EAAEC,IAAI,CAAA,EAAE,GAAG,MAAMJ,OAAO,CAACK,IAAI,EAAE,AAAC;IACtC,IAAI,CAACD,IAAI,CAACE,MAAM,EAAE;QAChB,MAAM,IAAIJ,OAAY,aAAA,CAAC,UAAU,EAAE,2DAA2D,CAAC,CAAC;IAClG,CAAC;IACD,OAAOK,2BAA2B,CAACH,IAAI,CAAC,CAAC;AAC3C,CAAC;AAED,SAASG,2BAA2B,CAACC,IAA6B,EAAwB;IACxF,OAAOA,IAAI,CAACC,MAAM,CAAC,CAACC,GAAG,EAAEC,CAAC,GAAK;QAC7BD,GAAG,CAACC,CAAC,CAACC,UAAU,CAAC,GAAGD,CAAC,CAACE,YAAY,CAAC;QACnC,OAAOH,GAAG,CAAC;IACb,CAAC,EAAE,EAAE,CAAyB,CAAC;AACjC,CAAC"}

View File

@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getProjectDevelopmentCertificateAsync", {
enumerable: true,
get: ()=>getProjectDevelopmentCertificateAsync
});
const _client = require("./rest/client");
const _errors = require("../utils/errors");
async function getProjectDevelopmentCertificateAsync(easProjectId, csrPEM) {
const response = await (0, _client.fetchAsync)(`projects/${encodeURIComponent(easProjectId)}/development-certificates`, {
method: "POST",
body: JSON.stringify({
csrPEM
})
});
if (!response.ok) {
throw new _errors.CommandError("API", `Unexpected error from Expo servers: ${response.statusText}.`);
}
const buffer = await response.buffer();
return buffer.toString("utf8");
}
//# sourceMappingURL=getProjectDevelopmentCertificate.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/api/getProjectDevelopmentCertificate.ts"],"sourcesContent":["import { fetchAsync } from './rest/client';\nimport { CommandError } from '../utils/errors';\n\nexport async function getProjectDevelopmentCertificateAsync(\n easProjectId: string,\n csrPEM: string\n): Promise<string> {\n const response = await fetchAsync(\n `projects/${encodeURIComponent(easProjectId)}/development-certificates`,\n {\n method: 'POST',\n body: JSON.stringify({\n csrPEM,\n }),\n }\n );\n if (!response.ok) {\n throw new CommandError('API', `Unexpected error from Expo servers: ${response.statusText}.`);\n }\n const buffer = await response.buffer();\n return buffer.toString('utf8');\n}\n"],"names":["getProjectDevelopmentCertificateAsync","easProjectId","csrPEM","response","fetchAsync","encodeURIComponent","method","body","JSON","stringify","ok","CommandError","statusText","buffer","toString"],"mappings":"AAAA;;;;+BAGsBA,uCAAqC;;aAArCA,qCAAqC;;wBAHhC,eAAe;wBACb,iBAAiB;AAEvC,eAAeA,qCAAqC,CACzDC,YAAoB,EACpBC,MAAc,EACG;IACjB,MAAMC,QAAQ,GAAG,MAAMC,IAAAA,OAAU,WAAA,EAC/B,CAAC,SAAS,EAAEC,kBAAkB,CAACJ,YAAY,CAAC,CAAC,yBAAyB,CAAC,EACvE;QACEK,MAAM,EAAE,MAAM;QACdC,IAAI,EAAEC,IAAI,CAACC,SAAS,CAAC;YACnBP,MAAM;SACP,CAAC;KACH,CACF,AAAC;IACF,IAAI,CAACC,QAAQ,CAACO,EAAE,EAAE;QAChB,MAAM,IAAIC,OAAY,aAAA,CAAC,KAAK,EAAE,CAAC,oCAAoC,EAAER,QAAQ,CAACS,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/F,CAAC;IACD,MAAMC,MAAM,GAAG,MAAMV,QAAQ,CAACU,MAAM,EAAE,AAAC;IACvC,OAAOA,MAAM,CAACC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACjC,CAAC"}

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getVersionsAsync", {
enumerable: true,
get: ()=>getVersionsAsync
});
const _client = require("./rest/client");
const _errors = require("../utils/errors");
async function getVersionsAsync({ skipCache } = {}) {
// Reconstruct the cached fetch since caching could be disabled.
const fetchAsync = (0, _client.createCachedFetch)({
skipCache,
cacheDirectory: "versions-cache",
// We'll use a 5 minute cache to ensure we stay relatively up to date.
ttl: 1000 * 60 * 5
});
const results = await fetchAsync("versions/latest");
if (!results.ok) {
throw new _errors.CommandError("API", `Unexpected response when fetching version info from Expo servers: ${results.statusText}.`);
}
const json = await results.json();
return json.data;
}
//# sourceMappingURL=getVersions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/api/getVersions.ts"],"sourcesContent":["import { createCachedFetch } from './rest/client';\nimport { CommandError } from '../utils/errors';\n\n/** Represents version info for a particular SDK. */\nexport type SDKVersion = {\n /** @example \"2.16.1\" */\n iosVersion?: string;\n /** @example \"https://dpq5q02fu5f55.cloudfront.net/Exponent-2.17.4.tar.gz\" */\n iosClientUrl?: string;\n /** @example \"https://dev.to/expo/expo-sdk-38-is-now-available-5aa0\" */\n releaseNoteUrl?: string;\n /** @example \"2.17.4\" */\n iosClientVersion?: string;\n /** @example \"https://d1ahtucjixef4r.cloudfront.net/Exponent-2.16.1.apk\" */\n androidClientUrl?: string;\n /** @example \"2.16.1\" */\n androidClientVersion?: string;\n /** @example { \"typescript\": \"~3.9.5\" } */\n relatedPackages?: Record<string, string>;\n\n facebookReactNativeVersion: string;\n\n facebookReactVersion?: string;\n\n expoVersion?: string;\n\n beta?: boolean;\n};\n\nexport type SDKVersions = Record<string, SDKVersion>;\n\nexport type Versions = {\n androidUrl: string;\n androidVersion: string;\n iosUrl: string;\n iosVersion: string;\n sdkVersions: SDKVersions;\n};\n\n/** Get versions from remote endpoint. */\nexport async function getVersionsAsync({\n skipCache,\n}: { skipCache?: boolean } = {}): Promise<Versions> {\n // Reconstruct the cached fetch since caching could be disabled.\n const fetchAsync = createCachedFetch({\n skipCache,\n cacheDirectory: 'versions-cache',\n // We'll use a 5 minute cache to ensure we stay relatively up to date.\n ttl: 1000 * 60 * 5,\n });\n\n const results = await fetchAsync('versions/latest');\n if (!results.ok) {\n throw new CommandError(\n 'API',\n `Unexpected response when fetching version info from Expo servers: ${results.statusText}.`\n );\n }\n const json = await results.json();\n return json.data;\n}\n"],"names":["getVersionsAsync","skipCache","fetchAsync","createCachedFetch","cacheDirectory","ttl","results","ok","CommandError","statusText","json","data"],"mappings":"AAAA;;;;+BAwCsBA,kBAAgB;;aAAhBA,gBAAgB;;wBAxCJ,eAAe;wBACpB,iBAAiB;AAuCvC,eAAeA,gBAAgB,CAAC,EACrCC,SAAS,CAAA,EACe,GAAG,EAAE,EAAqB;IAClD,gEAAgE;IAChE,MAAMC,UAAU,GAAGC,IAAAA,OAAiB,kBAAA,EAAC;QACnCF,SAAS;QACTG,cAAc,EAAE,gBAAgB;QAChC,sEAAsE;QACtEC,GAAG,EAAE,IAAI,GAAG,EAAE,GAAG,CAAC;KACnB,CAAC,AAAC;IAEH,MAAMC,OAAO,GAAG,MAAMJ,UAAU,CAAC,iBAAiB,CAAC,AAAC;IACpD,IAAI,CAACI,OAAO,CAACC,EAAE,EAAE;QACf,MAAM,IAAIC,OAAY,aAAA,CACpB,KAAK,EACL,CAAC,kEAAkE,EAAEF,OAAO,CAACG,UAAU,CAAC,CAAC,CAAC,CAC3F,CAAC;IACJ,CAAC;IACD,MAAMC,IAAI,GAAG,MAAMJ,OAAO,CAACI,IAAI,EAAE,AAAC;IAClC,OAAOA,IAAI,CAACC,IAAI,CAAC;AACnB,CAAC"}

View File

@@ -0,0 +1,144 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
graphqlClient: ()=>graphqlClient,
withErrorHandlingAsync: ()=>withErrorHandlingAsync,
GraphqlError: ()=>_core().CombinedError
});
function _core() {
const data = require("@urql/core");
_core = function() {
return data;
};
return data;
}
function _exchangeRetry() {
const data = require("@urql/exchange-retry");
_exchangeRetry = function() {
return data;
};
return data;
}
function _nodeFetch() {
const data = /*#__PURE__*/ _interopRequireDefault(require("node-fetch"));
_nodeFetch = function() {
return data;
};
return data;
}
const _log = /*#__PURE__*/ _interopRequireWildcard(require("../../log"));
const _endpoint = require("../endpoint");
const _wrapFetchWithOffline = require("../rest/wrapFetchWithOffline");
const _wrapFetchWithProxy = require("../rest/wrapFetchWithProxy");
const _userSettings = /*#__PURE__*/ _interopRequireDefault(require("../user/UserSettings"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const graphqlClient = (0, _core().createClient)({
url: (0, _endpoint.getExpoApiBaseUrl)() + "/graphql",
exchanges: [
_core().dedupExchange,
_core().cacheExchange,
(0, _exchangeRetry().retryExchange)({
maxDelayMs: 4000,
retryIf: (err)=>{
return !!(err && (err.networkError || err.graphQLErrors.some((e)=>{
var ref;
return e == null ? void 0 : (ref = e.extensions) == null ? void 0 : ref.isTransient;
})));
}
}),
_core().fetchExchange,
],
// @ts-ignore Type 'typeof fetch' is not assignable to type '(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>'.
fetch: (0, _wrapFetchWithOffline.wrapFetchWithOffline)((0, _wrapFetchWithProxy.wrapFetchWithProxy)(_nodeFetch().default)),
fetchOptions: ()=>{
var ref;
const token = _userSettings.default.getAccessToken();
if (token) {
return {
headers: {
authorization: `Bearer ${token}`
}
};
}
const sessionSecret = (ref = _userSettings.default.getSession()) == null ? void 0 : ref.sessionSecret;
if (sessionSecret) {
return {
headers: {
"expo-session": sessionSecret
}
};
}
return {};
}
});
async function withErrorHandlingAsync(promise) {
const { data , error } = await promise;
if (error) {
if (error.graphQLErrors.some((e)=>{
var ref;
return e == null ? void 0 : (ref = e.extensions) == null ? void 0 : ref.isTransient;
})) {
_log.error(`We've encountered a transient error, please try again shortly.`);
}
throw error;
}
// Check for a malformed response. This only checks the root query's existence. It doesn't affect
// returning responses with an empty result set.
if (!data) {
throw new Error("Returned query result data is null!");
}
return data;
}
//# sourceMappingURL=client.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "AppQuery", {
enumerable: true,
get: ()=>AppQuery
});
function _graphql() {
const data = require("graphql");
_graphql = function() {
return data;
};
return data;
}
function _graphqlTag() {
const data = /*#__PURE__*/ _interopRequireDefault(require("graphql-tag"));
_graphqlTag = function() {
return data;
};
return data;
}
const _client = require("../client");
const _app = require("../types/App");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const AppQuery = {
async byIdAsync (projectId) {
const data = await (0, _client.withErrorHandlingAsync)(_client.graphqlClient.query((0, _graphqlTag().default)`
query AppByIdQuery($appId: String!) {
app {
byId(appId: $appId) {
id
...AppFragment
}
}
}
${(0, _graphql().print)(_app.AppFragmentNode)}
`, {
appId: projectId
}, {
additionalTypenames: [
"App"
]
}).toPromise());
return data.app.byId;
}
};
//# sourceMappingURL=AppQuery.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/api/graphql/queries/AppQuery.ts"],"sourcesContent":["import { print } from 'graphql';\nimport gql from 'graphql-tag';\n\nimport { AppByIdQuery } from '../../../graphql/generated';\nimport { graphqlClient, withErrorHandlingAsync } from '../client';\nimport { AppFragmentNode } from '../types/App';\n\nexport const AppQuery = {\n async byIdAsync(projectId: string): Promise<AppByIdQuery['app']['byId']> {\n const data = await withErrorHandlingAsync(\n graphqlClient\n .query<AppByIdQuery>(\n gql`\n query AppByIdQuery($appId: String!) {\n app {\n byId(appId: $appId) {\n id\n ...AppFragment\n }\n }\n }\n ${print(AppFragmentNode)}\n `,\n { appId: projectId },\n {\n additionalTypenames: ['App'],\n }\n )\n .toPromise()\n );\n return data.app.byId;\n },\n};\n"],"names":["AppQuery","byIdAsync","projectId","data","withErrorHandlingAsync","graphqlClient","query","gql","print","AppFragmentNode","appId","additionalTypenames","toPromise","app","byId"],"mappings":"AAAA;;;;+BAOaA,UAAQ;;aAARA,QAAQ;;;yBAPC,SAAS;;;;;;;8DACf,aAAa;;;;;;wBAGyB,WAAW;qBACjC,cAAc;;;;;;AAEvC,MAAMA,QAAQ,GAAG;IACtB,MAAMC,SAAS,EAACC,SAAiB,EAAwC;QACvE,MAAMC,IAAI,GAAG,MAAMC,IAAAA,OAAsB,uBAAA,EACvCC,OAAa,cAAA,CACVC,KAAK,CACJC,IAAAA,WAAG,EAAA,QAAA,CAAA,CAAC;;;;;;;;;YASF,EAAEC,IAAAA,QAAK,EAAA,MAAA,EAACC,IAAe,gBAAA,CAAC,CAAC;UAC3B,CAAC,EACD;YAAEC,KAAK,EAAER,SAAS;SAAE,EACpB;YACES,mBAAmB,EAAE;gBAAC,KAAK;aAAC;SAC7B,CACF,CACAC,SAAS,EAAE,CACf,AAAC;QACF,OAAOT,IAAI,CAACU,GAAG,CAACC,IAAI,CAAC;IACvB,CAAC;CACF,AAAC"}

View File

@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "UserQuery", {
enumerable: true,
get: ()=>UserQuery
});
function _graphqlTag() {
const data = /*#__PURE__*/ _interopRequireDefault(require("graphql-tag"));
_graphqlTag = function() {
return data;
};
return data;
}
const _client = require("../client");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const UserQuery = {
async currentUserAsync () {
const data = await (0, _client.withErrorHandlingAsync)(_client.graphqlClient.query((0, _graphqlTag().default)`
query CurrentUser {
meActor {
__typename
id
... on UserActor {
primaryAccount {
id
}
username
}
... on Robot {
firstName
}
accounts {
id
users {
actor {
id
}
permissions
}
}
}
}
`, /* variables */ undefined, {
additionalTypenames: [
"User",
"SSOUser"
]
}).toPromise());
return data.meActor;
}
};
//# sourceMappingURL=UserQuery.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/api/graphql/queries/UserQuery.ts"],"sourcesContent":["import gql from 'graphql-tag';\n\nimport { CurrentUserQuery } from '../../../graphql/generated';\nimport { graphqlClient, withErrorHandlingAsync } from '../client';\n\nexport const UserQuery = {\n async currentUserAsync(): Promise<CurrentUserQuery['meActor']> {\n const data = await withErrorHandlingAsync(\n graphqlClient\n .query<CurrentUserQuery>(\n gql`\n query CurrentUser {\n meActor {\n __typename\n id\n ... on UserActor {\n primaryAccount {\n id\n }\n username\n }\n ... on Robot {\n firstName\n }\n accounts {\n id\n users {\n actor {\n id\n }\n permissions\n }\n }\n }\n }\n `,\n /* variables */ undefined,\n {\n additionalTypenames: ['User', 'SSOUser'],\n }\n )\n .toPromise()\n );\n\n return data.meActor;\n },\n};\n"],"names":["UserQuery","currentUserAsync","data","withErrorHandlingAsync","graphqlClient","query","gql","undefined","additionalTypenames","toPromise","meActor"],"mappings":"AAAA;;;;+BAKaA,WAAS;;aAATA,SAAS;;;8DALN,aAAa;;;;;;wBAGyB,WAAW;;;;;;AAE1D,MAAMA,SAAS,GAAG;IACvB,MAAMC,gBAAgB,IAAyC;QAC7D,MAAMC,IAAI,GAAG,MAAMC,IAAAA,OAAsB,uBAAA,EACvCC,OAAa,cAAA,CACVC,KAAK,CACJC,IAAAA,WAAG,EAAA,QAAA,CAAA,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;UAyBJ,CAAC,EACD,aAAa,GAAGC,SAAS,EACzB;YACEC,mBAAmB,EAAE;gBAAC,MAAM;gBAAE,SAAS;aAAC;SACzC,CACF,CACAC,SAAS,EAAE,CACf,AAAC;QAEF,OAAOP,IAAI,CAACQ,OAAO,CAAC;IACtB,CAAC;CACF,AAAC"}

View File

@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "AppFragmentNode", {
enumerable: true,
get: ()=>AppFragmentNode
});
function _graphqlTag() {
const data = /*#__PURE__*/ _interopRequireDefault(require("graphql-tag"));
_graphqlTag = function() {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const AppFragmentNode = (0, _graphqlTag().default)`
fragment AppFragment on App {
id
scopeKey
ownerAccount {
id
}
}
`;
//# sourceMappingURL=App.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/api/graphql/types/App.ts"],"sourcesContent":["import gql from 'graphql-tag';\n\nexport const AppFragmentNode = gql`\n fragment AppFragment on App {\n id\n scopeKey\n ownerAccount {\n id\n }\n }\n`;\n"],"names":["AppFragmentNode","gql"],"mappings":"AAAA;;;;+BAEaA,iBAAe;;aAAfA,eAAe;;;8DAFZ,aAAa;;;;;;;;;;;AAEtB,MAAMA,eAAe,GAAGC,IAAAA,WAAG,EAAA,QAAA,CAAA,CAAC;;;;;;;;AAQnC,CAAC,AAAC"}

View File

@@ -0,0 +1,93 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "FileSystemCache", {
enumerable: true,
get: ()=>FileSystemCache
});
function _cacache() {
const data = /*#__PURE__*/ _interopRequireDefault(require("cacache"));
_cacache = function() {
return data;
};
return data;
}
function _stream() {
const data = require("stream");
_stream = function() {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function getBodyAndMetaKeys(key) {
return [
`${key}body`,
`${key}meta`
];
}
class FileSystemCache {
constructor(options){
this.options = options;
}
async get(key) {
const [, metaKey] = getBodyAndMetaKeys(key);
const metaInfo = await _cacache().default.get.info(this.options.cacheDirectory, metaKey);
if (!metaInfo) {
return undefined;
}
const metaBuffer = await _cacache().default.get.byDigest(this.options.cacheDirectory, metaInfo.integrity);
const metaData = JSON.parse(metaBuffer);
const { bodyStreamIntegrity , empty , expiration } = metaData;
delete metaData.bodyStreamIntegrity;
delete metaData.empty;
delete metaData.expiration;
if (expiration && expiration < Date.now()) {
return undefined;
}
const bodyStream = empty ? _stream().Readable.from(Buffer.alloc(0)) : _cacache().default.get.stream.byDigest(this.options.cacheDirectory, bodyStreamIntegrity);
return {
bodyStream,
metaData
};
}
remove(key) {
const [bodyKey, metaKey] = getBodyAndMetaKeys(key);
return Promise.all([
_cacache().default.rm.entry(this.options.cacheDirectory, bodyKey),
_cacache().default.rm.entry(this.options.cacheDirectory, metaKey),
]);
}
async set(key, bodyStream, metaData) {
const [bodyKey, metaKey] = getBodyAndMetaKeys(key);
const metaCopy = {
...metaData
};
if (typeof this.options.ttl === "number") {
metaCopy.expiration = Date.now() + this.options.ttl;
}
try {
metaCopy.bodyStreamIntegrity = await new Promise((fulfill, reject)=>{
bodyStream.pipe(_cacache().default.put.stream(this.options.cacheDirectory, bodyKey)).on("integrity", (i)=>fulfill(i)).on("error", (e)=>{
reject(e);
});
});
} catch (err) {
if (err.code !== "ENODATA") {
throw err;
}
metaCopy.empty = true;
}
const metaBuffer = Buffer.from(JSON.stringify(metaCopy));
await _cacache().default.put(this.options.cacheDirectory, metaKey, metaBuffer);
const cachedData = await this.get(key);
return cachedData;
}
}
//# sourceMappingURL=FileSystemCache.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "NFCResponse", {
enumerable: true,
get: ()=>NFCResponse
});
function _nodeFetch() {
const data = require("node-fetch");
_nodeFetch = function() {
return data;
};
return data;
}
const responseInternalSymbol = Object.getOwnPropertySymbols(new (_nodeFetch()).Response())[1];
class NFCResponse extends _nodeFetch().Response {
constructor(bodyStream, metaData, ejectFromCache = function ejectFromCache() {
return this.ejectSelfFromCache();
}, fromCache = false){
super(bodyStream, metaData);
this.ejectFromCache = ejectFromCache;
this.fromCache = fromCache;
}
static serializeMetaFromNodeFetchResponse(res) {
const metaData = {
url: res.url,
status: res.status,
statusText: res.statusText,
headers: res.headers.raw(),
size: res.size,
timeout: res.timeout,
// @ts-ignore
counter: res[responseInternalSymbol].counter
};
return metaData;
}
}
//# sourceMappingURL=response.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/api/rest/cache/response.ts"],"sourcesContent":["import type { CacheObject } from 'cacache';\nimport { BodyInit, Response, ResponseInit } from 'node-fetch';\n\nconst responseInternalSymbol = Object.getOwnPropertySymbols(new Response())[1];\n\nexport class NFCResponse extends Response {\n constructor(\n bodyStream?: BodyInit,\n metaData?: ResponseInit,\n public ejectFromCache: () => Promise<[CacheObject, CacheObject]> = function ejectFromCache(\n this: any\n ) {\n return this.ejectSelfFromCache();\n },\n public fromCache: boolean = false\n ) {\n super(bodyStream, metaData);\n }\n\n static serializeMetaFromNodeFetchResponse(res: Response) {\n const metaData = {\n url: res.url,\n status: res.status,\n statusText: res.statusText,\n headers: res.headers.raw(),\n size: res.size,\n timeout: res.timeout,\n // @ts-ignore\n counter: res[responseInternalSymbol].counter,\n };\n\n return metaData;\n }\n}\n"],"names":["NFCResponse","responseInternalSymbol","Object","getOwnPropertySymbols","Response","constructor","bodyStream","metaData","ejectFromCache","ejectSelfFromCache","fromCache","serializeMetaFromNodeFetchResponse","res","url","status","statusText","headers","raw","size","timeout","counter"],"mappings":"AAAA;;;;+BAKaA,aAAW;;aAAXA,WAAW;;;yBAJyB,YAAY;;;;;;AAE7D,MAAMC,sBAAsB,GAAGC,MAAM,CAACC,qBAAqB,CAAC,IAAIC,CAAAA,UAAQ,EAAA,CAAA,SAAA,EAAE,CAAC,CAAC,CAAC,CAAC,AAAC;AAExE,MAAMJ,WAAW,SAASI,UAAQ,EAAA,SAAA;IACvCC,YACEC,UAAqB,EACrBC,QAAuB,EAChBC,cAAyD,GAAG,SAASA,cAAc,GAExF;QACA,OAAO,IAAI,CAACC,kBAAkB,EAAE,CAAC;IACnC,CAAC,EACMC,SAAkB,GAAG,KAAK,CACjC;QACA,KAAK,CAACJ,UAAU,EAAEC,QAAQ,CAAC,CAAC;QAPrBC,sBAAAA,cAAyD,CAAA;QAKzDE,iBAAAA,SAAkB,CAAA;IAG3B;WAEOC,kCAAkC,CAACC,GAAa,EAAE;QACvD,MAAML,QAAQ,GAAG;YACfM,GAAG,EAAED,GAAG,CAACC,GAAG;YACZC,MAAM,EAAEF,GAAG,CAACE,MAAM;YAClBC,UAAU,EAAEH,GAAG,CAACG,UAAU;YAC1BC,OAAO,EAAEJ,GAAG,CAACI,OAAO,CAACC,GAAG,EAAE;YAC1BC,IAAI,EAAEN,GAAG,CAACM,IAAI;YACdC,OAAO,EAAEP,GAAG,CAACO,OAAO;YACpB,aAAa;YACbC,OAAO,EAAER,GAAG,CAACX,sBAAsB,CAAC,CAACmB,OAAO;SAC7C,AAAC;QAEF,OAAOb,QAAQ,CAAC;IAClB;CACD"}

View File

@@ -0,0 +1,189 @@
/**
* Copyright (c) 2021 Expo, Inc.
* Copyright (c) 2020 mistval.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* Based on https://github.com/mistval/node-fetch-cache/blob/9c40ddf786b0de22ce521d8bdaa6347bc44dd629/src/index.js#L1
* But with TypeScript support to fix Jest tests, and removed unused code.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "wrapFetchWithCache", {
enumerable: true,
get: ()=>wrapFetchWithCache
});
function _crypto() {
const data = /*#__PURE__*/ _interopRequireDefault(require("crypto"));
_crypto = function() {
return data;
};
return data;
}
function _fs() {
const data = /*#__PURE__*/ _interopRequireDefault(require("fs"));
_fs = function() {
return data;
};
return data;
}
function _nodeFetch() {
const data = require("node-fetch");
_nodeFetch = function() {
return data;
};
return data;
}
function _url() {
const data = require("url");
_url = function() {
return data;
};
return data;
}
const _response = require("./response");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const CACHE_VERSION = 3;
const lockPromiseForKey = {};
const unlockFunctionForKey = {};
/**
* Take out a lock. When this function returns (asynchronously),
* you have the lock.
* @param {string} key - The key to lock on. Anyone else who
* tries to lock on the same key will need to wait for it to
* be unlocked.
*/ async function lock(key) {
if (!lockPromiseForKey[key]) {
lockPromiseForKey[key] = Promise.resolve();
}
const takeLockPromise = lockPromiseForKey[key];
lockPromiseForKey[key] = takeLockPromise.then(()=>new Promise((fulfill)=>{
unlockFunctionForKey[key] = fulfill;
}));
return takeLockPromise;
}
/**
* Release a lock.
* @param {string} key - The key to release the lock for.
* The next person in line will now be able to take out
* the lock for that key.
*/ function unlock(key) {
if (unlockFunctionForKey[key]) {
unlockFunctionForKey[key]();
delete unlockFunctionForKey[key];
}
}
function md5(str) {
return _crypto().default.createHash("md5").update(str).digest("hex");
}
// Since the boundary in FormData is random,
// we ignore it for purposes of calculating
// the cache key.
function getFormDataCacheKey(formData) {
const cacheKey = {
...formData
};
const boundary = formData.getBoundary();
// @ts-expect-error
delete cacheKey._boundary;
const boundaryReplaceRegex = new RegExp(boundary, "g");
// @ts-expect-error
cacheKey._streams = cacheKey._streams.map((s)=>{
if (typeof s === "string") {
return s.replace(boundaryReplaceRegex, "");
}
return s;
});
return cacheKey;
}
function getBodyCacheKeyJson(body) {
if (!body) {
return body;
}
if (typeof body === "string") {
return body;
}
if (body instanceof _url().URLSearchParams) {
return body.toString();
}
if (body instanceof _fs().default.ReadStream) {
return body.path;
}
if (body.toString && body.toString() === "[object FormData]") {
return getFormDataCacheKey(body);
}
if (body instanceof Buffer) {
return body.toString();
}
throw new Error("Unsupported body type. Supported body types are: string, number, undefined, null, url.URLSearchParams, fs.ReadStream, FormData");
}
function getRequestCacheKey(req) {
return {
cache: req.cache,
credentials: req.credentials,
destination: req.destination,
headers: req.headers,
integrity: req.integrity,
method: req.method,
redirect: req.redirect,
referrer: req.referrer,
referrerPolicy: req.referrerPolicy,
url: req.url,
body: getBodyCacheKeyJson(req.body)
};
}
function getCacheKey(requestArguments) {
const resource = requestArguments[0];
const init = requestArguments[1] || {};
const resourceCacheKeyJson = resource instanceof _nodeFetch().Request ? getRequestCacheKey(resource) : {
url: resource
};
const initCacheKeyJson = {
...init
};
// @ts-ignore
resourceCacheKeyJson.body = getBodyCacheKeyJson(resourceCacheKeyJson.body);
initCacheKeyJson.body = getBodyCacheKeyJson(initCacheKeyJson.body);
delete initCacheKeyJson.agent;
return md5(JSON.stringify([
resourceCacheKeyJson,
initCacheKeyJson,
CACHE_VERSION
]));
}
function wrapFetchWithCache(fetch, cache) {
async function getResponse(cache, url, init) {
const cacheKey = getCacheKey([
url,
init
]);
let cachedValue = await cache.get(cacheKey);
const ejectSelfFromCache = ()=>cache.remove(cacheKey);
if (cachedValue) {
return new _response.NFCResponse(cachedValue.bodyStream, cachedValue.metaData, ejectSelfFromCache, true);
}
await lock(cacheKey);
try {
cachedValue = await cache.get(cacheKey);
if (cachedValue) {
return new _response.NFCResponse(cachedValue.bodyStream, cachedValue.metaData, ejectSelfFromCache, true);
}
const fetchResponse = await fetch(url, init);
const serializedMeta = _response.NFCResponse.serializeMetaFromNodeFetchResponse(fetchResponse);
const newlyCachedData = await cache.set(cacheKey, // @ts-expect-error
fetchResponse.body, serializedMeta);
return new _response.NFCResponse(newlyCachedData.bodyStream, newlyCachedData.metaData, ejectSelfFromCache, false);
} finally{
unlock(cacheKey);
}
}
return (url, init)=>getResponse(cache, url, init);
}
//# sourceMappingURL=wrapFetchWithCache.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,134 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ApiV2Error: ()=>ApiV2Error,
UnexpectedServerError: ()=>UnexpectedServerError,
wrapFetchWithCredentials: ()=>wrapFetchWithCredentials,
createCachedFetch: ()=>createCachedFetch,
fetchAsync: ()=>fetchAsync
});
function _getUserState() {
const data = require("@expo/config/build/getUserState");
_getUserState = function() {
return data;
};
return data;
}
function _nodeFetch() {
const data = /*#__PURE__*/ _interopRequireDefault(require("node-fetch"));
_nodeFetch = function() {
return data;
};
return data;
}
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
const _wrapFetchWithCache = require("./cache/wrapFetchWithCache");
const _wrapFetchWithBaseUrl = require("./wrapFetchWithBaseUrl");
const _wrapFetchWithOffline = require("./wrapFetchWithOffline");
const _wrapFetchWithProgress = require("./wrapFetchWithProgress");
const _wrapFetchWithProxy = require("./wrapFetchWithProxy");
const _env = require("../../utils/env");
const _errors = require("../../utils/errors");
const _endpoint = require("../endpoint");
const _settings = require("../settings");
const _userSettings = /*#__PURE__*/ _interopRequireDefault(require("../user/UserSettings"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
class ApiV2Error extends Error {
name = "ApiV2Error";
constructor(response){
super(response.message);
this.code = response.code;
this.expoApiV2ErrorCode = response.code;
this.expoApiV2ErrorDetails = response.details;
this.expoApiV2ErrorServerStack = response.stack;
this.expoApiV2ErrorMetadata = response.metadata;
}
}
class UnexpectedServerError extends Error {
name = "UnexpectedServerError";
}
function wrapFetchWithCredentials(fetchFunction) {
return async function fetchWithCredentials(url, options = {}) {
if (Array.isArray(options.headers)) {
throw new Error("request headers must be in object form");
}
var _headers;
const resolvedHeaders = (_headers = options.headers) != null ? _headers : {};
const token = _userSettings.default.getAccessToken();
if (token) {
resolvedHeaders.authorization = `Bearer ${token}`;
} else {
var ref;
const sessionSecret = (ref = _userSettings.default.getSession()) == null ? void 0 : ref.sessionSecret;
if (sessionSecret) {
resolvedHeaders["expo-session"] = sessionSecret;
}
}
try {
const results = await fetchFunction(url, {
...options,
headers: resolvedHeaders
});
if (results.status >= 400 && results.status < 500) {
const body = await results.text();
try {
var ref1;
const data = JSON.parse(body);
if (data == null ? void 0 : (ref1 = data.errors) == null ? void 0 : ref1.length) {
throw new ApiV2Error(data.errors[0]);
}
} catch (error) {
// Server returned non-json response.
if (error.message.includes("in JSON at position")) {
throw new UnexpectedServerError(body);
}
throw error;
}
}
return results;
} catch (error1) {
// Specifically, when running `npx expo start` and the wifi is connected but not really (public wifi, airplanes, etc).
if ("code" in error1 && error1.code === "ENOTFOUND") {
(0, _settings.disableNetwork)();
throw new _errors.CommandError("OFFLINE", "Network connection is unreliable. Try again with the environment variable `EXPO_OFFLINE=1` to skip network requests.");
}
throw error1;
}
};
}
const fetchWithOffline = (0, _wrapFetchWithOffline.wrapFetchWithOffline)(_nodeFetch().default);
const fetchWithBaseUrl = (0, _wrapFetchWithBaseUrl.wrapFetchWithBaseUrl)(fetchWithOffline, (0, _endpoint.getExpoApiBaseUrl)() + "/v2/");
const fetchWithProxy = (0, _wrapFetchWithProxy.wrapFetchWithProxy)(fetchWithBaseUrl);
const fetchWithCredentials = (0, _wrapFetchWithProgress.wrapFetchWithProgress)(wrapFetchWithCredentials(fetchWithProxy));
function createCachedFetch({ fetch =fetchWithCredentials , cacheDirectory , ttl , skipCache }) {
// Disable all caching in EXPO_BETA.
if (skipCache || _env.env.EXPO_BETA || _env.env.EXPO_NO_CACHE) {
return fetch;
}
const { FileSystemCache } = require("./cache/FileSystemCache");
return (0, _wrapFetchWithCache.wrapFetchWithCache)(fetch, new FileSystemCache({
cacheDirectory: _path().default.join((0, _getUserState().getExpoHomeDirectory)(), cacheDirectory),
ttl
}));
}
const fetchAsync = (0, _wrapFetchWithProgress.wrapFetchWithProgress)(wrapFetchWithCredentials(fetchWithProxy));
//# sourceMappingURL=client.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
//# sourceMappingURL=client.types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/api/rest/client.types.ts"],"sourcesContent":["import { RequestInfo, RequestInit, Response } from 'node-fetch';\nimport { URLSearchParams } from 'url';\n\nexport type ProgressCallback = (props: {\n /** Number ranging from 0 to 1 representing the download percentage. */\n progress: number;\n /** Total size of the download, in bytes. */\n total: number;\n /** Current amount of data downloaded, in bytes. */\n loaded: number;\n}) => void;\n\n/**\n * Represents a `fetch`-like function. Used since `typeof fetch` has statics we don't\n * use and aren't interested in hoisting every time we wrap fetch with extra features.\n */\nexport type FetchLike = (\n url: RequestInfo,\n init?: RequestInit & {\n searchParams?: URLSearchParams;\n /** Progress callback, only implemented when `wrapFetchWithProgress` is used. */\n onProgress?: ProgressCallback;\n }\n) => Promise<Response>;\n"],"names":[],"mappings":"AAAA"}

View File

@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "wrapFetchWithBaseUrl", {
enumerable: true,
get: ()=>wrapFetchWithBaseUrl
});
function _url() {
const data = require("url");
_url = function() {
return data;
};
return data;
}
function wrapFetchWithBaseUrl(fetch, baseUrl) {
// NOTE(EvanBacon): DO NOT RETURN AN ASYNC WRAPPER. THIS BREAKS LOADING INDICATORS.
return (url, init)=>{
if (typeof url !== "string") {
throw new TypeError("Custom fetch function only accepts a string URL as the first parameter");
}
const parsed = new (_url()).URL(url, baseUrl);
if (init == null ? void 0 : init.searchParams) {
parsed.search = init.searchParams.toString();
}
// debug('fetch:', parsed.toString().trim());
return fetch(parsed.toString(), init);
};
}
//# sourceMappingURL=wrapFetchWithBaseUrl.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/api/rest/wrapFetchWithBaseUrl.ts"],"sourcesContent":["import { URL } from 'url';\n\nimport { FetchLike } from './client.types';\n\n// const debug = require('debug')('expo:api:fetch:base') as typeof console.log;\n\n/**\n * Wrap a fetch function with support for a predefined base URL.\n * This implementation works like the browser fetch, applying the input to a prefix base URL.\n */\nexport function wrapFetchWithBaseUrl(fetch: FetchLike, baseUrl: string): FetchLike {\n // NOTE(EvanBacon): DO NOT RETURN AN ASYNC WRAPPER. THIS BREAKS LOADING INDICATORS.\n return (url, init) => {\n if (typeof url !== 'string') {\n throw new TypeError('Custom fetch function only accepts a string URL as the first parameter');\n }\n const parsed = new URL(url, baseUrl);\n if (init?.searchParams) {\n parsed.search = init.searchParams.toString();\n }\n // debug('fetch:', parsed.toString().trim());\n return fetch(parsed.toString(), init);\n };\n}\n"],"names":["wrapFetchWithBaseUrl","fetch","baseUrl","url","init","TypeError","parsed","URL","searchParams","search","toString"],"mappings":"AAAA;;;;+BAUgBA,sBAAoB;;aAApBA,oBAAoB;;;yBAVhB,KAAK;;;;;;AAUlB,SAASA,oBAAoB,CAACC,KAAgB,EAAEC,OAAe,EAAa;IACjF,mFAAmF;IACnF,OAAO,CAACC,GAAG,EAAEC,IAAI,GAAK;QACpB,IAAI,OAAOD,GAAG,KAAK,QAAQ,EAAE;YAC3B,MAAM,IAAIE,SAAS,CAAC,wEAAwE,CAAC,CAAC;QAChG,CAAC;QACD,MAAMC,MAAM,GAAG,IAAIC,CAAAA,IAAG,EAAA,CAAA,IAAA,CAACJ,GAAG,EAAED,OAAO,CAAC,AAAC;QACrC,IAAIE,IAAI,QAAc,GAAlBA,KAAAA,CAAkB,GAAlBA,IAAI,CAAEI,YAAY,EAAE;YACtBF,MAAM,CAACG,MAAM,GAAGL,IAAI,CAACI,YAAY,CAACE,QAAQ,EAAE,CAAC;QAC/C,CAAC;QACD,6CAA6C;QAC7C,OAAOT,KAAK,CAACK,MAAM,CAACI,QAAQ,EAAE,EAAEN,IAAI,CAAC,CAAC;IACxC,CAAC,CAAC;AACJ,CAAC"}

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "wrapFetchWithOffline", {
enumerable: true,
get: ()=>wrapFetchWithOffline
});
const _env = require("../../utils/env");
const debug = require("debug")("expo:api:fetch:offline");
function wrapFetchWithOffline(fetchFunction) {
// NOTE(EvanBacon): DO NOT RETURN AN ASYNC WRAPPER. THIS BREAKS LOADING INDICATORS.
return function fetchWithOffline(url, options = {}) {
if (_env.env.EXPO_OFFLINE) {
debug("Skipping network request: " + url);
options.timeout = 1;
}
return fetchFunction(url, options);
};
}
//# sourceMappingURL=wrapFetchWithOffline.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/api/rest/wrapFetchWithOffline.ts"],"sourcesContent":["import { FetchLike } from './client.types';\nimport { env } from '../../utils/env';\n\nconst debug = require('debug')('expo:api:fetch:offline') as typeof console.log;\n\n/** Wrap fetch with support for `EXPO_OFFLINE` to disable network requests. */\nexport function wrapFetchWithOffline(fetchFunction: FetchLike): FetchLike {\n // NOTE(EvanBacon): DO NOT RETURN AN ASYNC WRAPPER. THIS BREAKS LOADING INDICATORS.\n return function fetchWithOffline(url, options = {}) {\n if (env.EXPO_OFFLINE) {\n debug('Skipping network request: ' + url);\n options.timeout = 1;\n }\n return fetchFunction(url, options);\n };\n}\n"],"names":["wrapFetchWithOffline","debug","require","fetchFunction","fetchWithOffline","url","options","env","EXPO_OFFLINE","timeout"],"mappings":"AAAA;;;;+BAMgBA,sBAAoB;;aAApBA,oBAAoB;;qBALhB,iBAAiB;AAErC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,wBAAwB,CAAC,AAAsB,AAAC;AAGxE,SAASF,oBAAoB,CAACG,aAAwB,EAAa;IACxE,mFAAmF;IACnF,OAAO,SAASC,gBAAgB,CAACC,GAAG,EAAEC,OAAO,GAAG,EAAE,EAAE;QAClD,IAAIC,IAAG,IAAA,CAACC,YAAY,EAAE;YACpBP,KAAK,CAAC,4BAA4B,GAAGI,GAAG,CAAC,CAAC;YAC1CC,OAAO,CAACG,OAAO,GAAG,CAAC,CAAC;QACtB,CAAC;QACD,OAAON,aAAa,CAACE,GAAG,EAAEC,OAAO,CAAC,CAAC;IACrC,CAAC,CAAC;AACJ,CAAC"}

View File

@@ -0,0 +1,85 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "wrapFetchWithProgress", {
enumerable: true,
get: ()=>wrapFetchWithProgress
});
const _log = /*#__PURE__*/ _interopRequireWildcard(require("../../log"));
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const debug = require("debug")("expo:api:fetch:progress");
function wrapFetchWithProgress(fetch) {
return (url, init)=>{
return fetch(url, init).then((res)=>{
if (res.ok && (init == null ? void 0 : init.onProgress)) {
const totalDownloadSize = res.headers.get("Content-Length");
const total = Number(totalDownloadSize);
debug(`Download size: ${totalDownloadSize}`);
if (!totalDownloadSize || isNaN(total) || total < 0) {
_log.warn('Progress callback not supported for network request because "Content-Length" header missing or invalid in response from URL:', url.toString());
return res;
}
let length = 0;
debug(`Starting progress animation for ${url}`);
res.body.on("data", (chunk)=>{
length += Buffer.byteLength(chunk);
onProgress();
});
res.body.on("end", ()=>{
debug(`Finished progress animation for ${url}`);
onProgress();
});
const onProgress = ()=>{
const progress = length / total || 0;
init.onProgress == null ? void 0 : init.onProgress({
progress,
total,
loaded: length
});
};
}
return res;
});
};
}
//# sourceMappingURL=wrapFetchWithProgress.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/api/rest/wrapFetchWithProgress.ts"],"sourcesContent":["import { FetchLike } from './client.types';\nimport * as Log from '../../log';\nconst debug = require('debug')('expo:api:fetch:progress') as typeof console.log;\n\nexport function wrapFetchWithProgress(fetch: FetchLike): FetchLike {\n return (url, init) => {\n return fetch(url, init).then((res) => {\n if (res.ok && init?.onProgress) {\n const totalDownloadSize = res.headers.get('Content-Length');\n const total = Number(totalDownloadSize);\n\n debug(`Download size: ${totalDownloadSize}`);\n if (!totalDownloadSize || isNaN(total) || total < 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 res;\n }\n\n let length = 0;\n\n debug(`Starting progress animation for ${url}`);\n res.body.on('data', (chunk) => {\n length += Buffer.byteLength(chunk);\n onProgress();\n });\n\n res.body.on('end', () => {\n debug(`Finished progress animation for ${url}`);\n onProgress();\n });\n\n const onProgress = () => {\n const progress = length / total || 0;\n init.onProgress?.({\n progress,\n total,\n loaded: length,\n });\n };\n }\n return res;\n });\n };\n}\n"],"names":["wrapFetchWithProgress","debug","require","fetch","url","init","then","res","ok","onProgress","totalDownloadSize","headers","get","total","Number","isNaN","Log","warn","toString","length","body","on","chunk","Buffer","byteLength","progress","loaded"],"mappings":"AAAA;;;;+BAIgBA,uBAAqB;;aAArBA,qBAAqB;;2DAHhB,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAChC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,yBAAyB,CAAC,AAAsB,AAAC;AAEzE,SAASF,qBAAqB,CAACG,KAAgB,EAAa;IACjE,OAAO,CAACC,GAAG,EAAEC,IAAI,GAAK;QACpB,OAAOF,KAAK,CAACC,GAAG,EAAEC,IAAI,CAAC,CAACC,IAAI,CAAC,CAACC,GAAG,GAAK;YACpC,IAAIA,GAAG,CAACC,EAAE,IAAIH,CAAAA,IAAI,QAAY,GAAhBA,KAAAA,CAAgB,GAAhBA,IAAI,CAAEI,UAAU,CAAA,EAAE;gBAC9B,MAAMC,iBAAiB,GAAGH,GAAG,CAACI,OAAO,CAACC,GAAG,CAAC,gBAAgB,CAAC,AAAC;gBAC5D,MAAMC,KAAK,GAAGC,MAAM,CAACJ,iBAAiB,CAAC,AAAC;gBAExCT,KAAK,CAAC,CAAC,eAAe,EAAES,iBAAiB,CAAC,CAAC,CAAC,CAAC;gBAC7C,IAAI,CAACA,iBAAiB,IAAIK,KAAK,CAACF,KAAK,CAAC,IAAIA,KAAK,GAAG,CAAC,EAAE;oBACnDG,IAAG,CAACC,IAAI,CACN,8HAA8H,EAC9Hb,GAAG,CAACc,QAAQ,EAAE,CACf,CAAC;oBACF,OAAOX,GAAG,CAAC;gBACb,CAAC;gBAED,IAAIY,MAAM,GAAG,CAAC,AAAC;gBAEflB,KAAK,CAAC,CAAC,gCAAgC,EAAEG,GAAG,CAAC,CAAC,CAAC,CAAC;gBAChDG,GAAG,CAACa,IAAI,CAACC,EAAE,CAAC,MAAM,EAAE,CAACC,KAAK,GAAK;oBAC7BH,MAAM,IAAII,MAAM,CAACC,UAAU,CAACF,KAAK,CAAC,CAAC;oBACnCb,UAAU,EAAE,CAAC;gBACf,CAAC,CAAC,CAAC;gBAEHF,GAAG,CAACa,IAAI,CAACC,EAAE,CAAC,KAAK,EAAE,IAAM;oBACvBpB,KAAK,CAAC,CAAC,gCAAgC,EAAEG,GAAG,CAAC,CAAC,CAAC,CAAC;oBAChDK,UAAU,EAAE,CAAC;gBACf,CAAC,CAAC,CAAC;gBAEH,MAAMA,UAAU,GAAG,IAAM;oBACvB,MAAMgB,QAAQ,GAAGN,MAAM,GAAGN,KAAK,IAAI,CAAC,AAAC;oBACrCR,IAAI,CAACI,UAAU,QAIb,GAJFJ,KAAAA,CAIE,GAJFA,IAAI,CAACI,UAAU,CAAG;wBAChBgB,QAAQ;wBACRZ,KAAK;wBACLa,MAAM,EAAEP,MAAM;qBACf,CAAC,CAAC;gBACL,CAAC,AAAC;YACJ,CAAC;YACD,OAAOZ,GAAG,CAAC;QACb,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC"}

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "wrapFetchWithProxy", {
enumerable: true,
get: ()=>wrapFetchWithProxy
});
function _httpsProxyAgent() {
const data = /*#__PURE__*/ _interopRequireDefault(require("https-proxy-agent"));
_httpsProxyAgent = function() {
return data;
};
return data;
}
const _env = require("../../utils/env");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const debug = require("debug")("expo:api:fetch:proxy");
function wrapFetchWithProxy(fetchFunction) {
// NOTE(EvanBacon): DO NOT RETURN AN ASYNC WRAPPER. THIS BREAKS LOADING INDICATORS.
return function fetchWithProxy(url, options = {}) {
const proxy = _env.env.HTTP_PROXY;
if (!options.agent && proxy) {
debug("Using proxy:", proxy);
options.agent = (0, _httpsProxyAgent().default)(proxy);
}
return fetchFunction(url, options);
};
}
//# sourceMappingURL=wrapFetchWithProxy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/api/rest/wrapFetchWithProxy.ts"],"sourcesContent":["import createHttpsProxyAgent from 'https-proxy-agent';\n\nimport { FetchLike } from './client.types';\nimport { env } from '../../utils/env';\n\nconst debug = require('debug')('expo:api:fetch:proxy') as typeof console.log;\n\n/** Wrap fetch with support for proxies. */\nexport function wrapFetchWithProxy(fetchFunction: FetchLike): FetchLike {\n // NOTE(EvanBacon): DO NOT RETURN AN ASYNC WRAPPER. THIS BREAKS LOADING INDICATORS.\n return function fetchWithProxy(url, options = {}) {\n const proxy = env.HTTP_PROXY;\n if (!options.agent && proxy) {\n debug('Using proxy:', proxy);\n options.agent = createHttpsProxyAgent(proxy);\n }\n return fetchFunction(url, options);\n };\n}\n"],"names":["wrapFetchWithProxy","debug","require","fetchFunction","fetchWithProxy","url","options","proxy","env","HTTP_PROXY","agent","createHttpsProxyAgent"],"mappings":"AAAA;;;;+BAQgBA,oBAAkB;;aAAlBA,kBAAkB;;;8DARA,mBAAmB;;;;;;qBAGjC,iBAAiB;;;;;;AAErC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,sBAAsB,CAAC,AAAsB,AAAC;AAGtE,SAASF,kBAAkB,CAACG,aAAwB,EAAa;IACtE,mFAAmF;IACnF,OAAO,SAASC,cAAc,CAACC,GAAG,EAAEC,OAAO,GAAG,EAAE,EAAE;QAChD,MAAMC,KAAK,GAAGC,IAAG,IAAA,CAACC,UAAU,AAAC;QAC7B,IAAI,CAACH,OAAO,CAACI,KAAK,IAAIH,KAAK,EAAE;YAC3BN,KAAK,CAAC,cAAc,EAAEM,KAAK,CAAC,CAAC;YAC7BD,OAAO,CAACI,KAAK,GAAGC,IAAAA,gBAAqB,EAAA,QAAA,EAACJ,KAAK,CAAC,CAAC;QAC/C,CAAC;QACD,OAAOJ,aAAa,CAACE,GAAG,EAAEC,OAAO,CAAC,CAAC;IACrC,CAAC,CAAC;AACJ,CAAC"}

View File

@@ -0,0 +1,31 @@
// This file represents temporary globals for the CLI when using the API.
// Settings should be as minimal as possible since they are globals.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "disableNetwork", {
enumerable: true,
get: ()=>disableNetwork
});
function _chalk() {
const data = /*#__PURE__*/ _interopRequireDefault(require("chalk"));
_chalk = function() {
return data;
};
return data;
}
const _log = require("../log");
const _env = require("../utils/env");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function disableNetwork() {
if (_env.env.EXPO_OFFLINE) return;
process.env.EXPO_OFFLINE = "1";
_log.Log.log(_chalk().default.gray("Networking has been disabled"));
}
//# sourceMappingURL=settings.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/api/settings.ts"],"sourcesContent":["// This file represents temporary globals for the CLI when using the API.\n// Settings should be as minimal as possible since they are globals.\nimport chalk from 'chalk';\n\nimport { Log } from '../log';\nimport { env } from '../utils/env';\n\nexport function disableNetwork() {\n if (env.EXPO_OFFLINE) return;\n process.env.EXPO_OFFLINE = '1';\n Log.log(chalk.gray('Networking has been disabled'));\n}\n"],"names":["disableNetwork","env","EXPO_OFFLINE","process","Log","log","chalk","gray"],"mappings":"AAAA,yEAAyE;AACzE,oEAAoE;AACpE;;;;+BAKgBA,gBAAc;;aAAdA,cAAc;;;8DALZ,OAAO;;;;;;qBAEL,QAAQ;qBACR,cAAc;;;;;;AAE3B,SAASA,cAAc,GAAG;IAC/B,IAAIC,IAAG,IAAA,CAACC,YAAY,EAAE,OAAO;IAC7BC,OAAO,CAACF,GAAG,CAACC,YAAY,GAAG,GAAG,CAAC;IAC/BE,IAAG,IAAA,CAACC,GAAG,CAACC,MAAK,EAAA,QAAA,CAACC,IAAI,CAAC,8BAA8B,CAAC,CAAC,CAAC;AACtD,CAAC"}

View File

@@ -0,0 +1,94 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createSessionInfo: ()=>createSessionInfo,
updateDevelopmentSessionAsync: ()=>updateDevelopmentSessionAsync,
closeDevelopmentSessionAsync: ()=>closeDevelopmentSessionAsync
});
function _os() {
const data = /*#__PURE__*/ _interopRequireDefault(require("os"));
_os = function() {
return data;
};
return data;
}
function _url() {
const data = require("url");
_url = function() {
return data;
};
return data;
}
const _client = require("./rest/client");
const _errors = require("../utils/errors");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function createSessionInfo({ exp , runtime , url }) {
return {
session: {
description: `${exp.name} on ${_os().default.hostname()}`,
hostname: _os().default.hostname(),
platform: runtime,
config: {
// TODO: if icons are specified, upload a url for them too so people can distinguish
description: exp.description,
name: exp.name,
slug: exp.slug,
primaryColor: exp.primaryColor
},
url,
source: "desktop"
}
};
}
async function updateDevelopmentSessionAsync({ deviceIds , exp , runtime , url }) {
const searchParams = new (_url()).URLSearchParams();
deviceIds.forEach((id)=>{
searchParams.append("deviceId", id);
});
const results = await (0, _client.fetchAsync)("development-sessions/notify-alive", {
searchParams,
method: "POST",
body: JSON.stringify({
data: createSessionInfo({
exp,
runtime,
url
})
})
});
if (!results.ok) {
throw new _errors.CommandError("API", `Unexpected response when updating the development session on Expo servers: ${results.statusText}.`);
}
}
async function closeDevelopmentSessionAsync({ deviceIds , url }) {
const searchParams = new (_url()).URLSearchParams();
deviceIds.forEach((id)=>{
searchParams.append("deviceId", id);
});
const results = await (0, _client.fetchAsync)("development-sessions/notify-close", {
searchParams,
method: "POST",
body: JSON.stringify({
session: {
url
}
})
});
if (!results.ok) {
throw new _errors.CommandError("API", `Unexpected response when closing the development session on Expo servers: ${results.statusText}.`);
}
}
//# sourceMappingURL=updateDevelopmentSession.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/api/updateDevelopmentSession.ts"],"sourcesContent":["import { ExpoConfig } from '@expo/config';\nimport os from 'os';\nimport { URLSearchParams } from 'url';\n\nimport { fetchAsync } from './rest/client';\nimport { CommandError } from '../utils/errors';\n\n/** Create the expected session info. */\nexport function createSessionInfo({\n exp,\n runtime,\n url,\n}: {\n exp: Pick<ExpoConfig, 'name' | 'description' | 'slug' | 'primaryColor'>;\n runtime: 'native' | 'web';\n url: string;\n}) {\n return {\n session: {\n description: `${exp.name} on ${os.hostname()}`,\n hostname: os.hostname(),\n platform: runtime,\n config: {\n // TODO: if icons are specified, upload a url for them too so people can distinguish\n description: exp.description,\n name: exp.name,\n slug: exp.slug,\n primaryColor: exp.primaryColor,\n },\n url,\n source: 'desktop',\n },\n };\n}\n\n/** Send a request to Expo API to keep the 'development session' alive for the provided devices. */\nexport async function updateDevelopmentSessionAsync({\n deviceIds,\n exp,\n runtime,\n url,\n}: {\n deviceIds: string[];\n exp: Pick<ExpoConfig, 'name' | 'description' | 'slug' | 'primaryColor'>;\n runtime: 'native' | 'web';\n url: string;\n}) {\n const searchParams = new URLSearchParams();\n deviceIds.forEach((id) => {\n searchParams.append('deviceId', id);\n });\n\n const results = await fetchAsync('development-sessions/notify-alive', {\n searchParams,\n method: 'POST',\n body: JSON.stringify({\n data: createSessionInfo({ exp, runtime, url }),\n }),\n });\n\n if (!results.ok) {\n throw new CommandError(\n 'API',\n `Unexpected response when updating the development session on Expo servers: ${results.statusText}.`\n );\n }\n}\n\n/** Send a request to Expo API to close the 'development session' for the provided devices. */\nexport async function closeDevelopmentSessionAsync({\n deviceIds,\n url,\n}: {\n deviceIds: string[];\n url: string;\n}) {\n const searchParams = new URLSearchParams();\n deviceIds.forEach((id) => {\n searchParams.append('deviceId', id);\n });\n\n const results = await fetchAsync('development-sessions/notify-close', {\n searchParams,\n method: 'POST',\n body: JSON.stringify({\n session: { url },\n }),\n });\n\n if (!results.ok) {\n throw new CommandError(\n 'API',\n `Unexpected response when closing the development session on Expo servers: ${results.statusText}.`\n );\n }\n}\n"],"names":["createSessionInfo","updateDevelopmentSessionAsync","closeDevelopmentSessionAsync","exp","runtime","url","session","description","name","os","hostname","platform","config","slug","primaryColor","source","deviceIds","searchParams","URLSearchParams","forEach","id","append","results","fetchAsync","method","body","JSON","stringify","data","ok","CommandError","statusText"],"mappings":"AAAA;;;;;;;;;;;IAQgBA,iBAAiB,MAAjBA,iBAAiB;IA4BXC,6BAA6B,MAA7BA,6BAA6B;IAiC7BC,4BAA4B,MAA5BA,4BAA4B;;;8DApEnC,IAAI;;;;;;;yBACa,KAAK;;;;;;wBAEV,eAAe;wBACb,iBAAiB;;;;;;AAGvC,SAASF,iBAAiB,CAAC,EAChCG,GAAG,CAAA,EACHC,OAAO,CAAA,EACPC,GAAG,CAAA,EAKJ,EAAE;IACD,OAAO;QACLC,OAAO,EAAE;YACPC,WAAW,EAAE,CAAC,EAAEJ,GAAG,CAACK,IAAI,CAAC,IAAI,EAAEC,GAAE,EAAA,QAAA,CAACC,QAAQ,EAAE,CAAC,CAAC;YAC9CA,QAAQ,EAAED,GAAE,EAAA,QAAA,CAACC,QAAQ,EAAE;YACvBC,QAAQ,EAAEP,OAAO;YACjBQ,MAAM,EAAE;gBACN,oFAAoF;gBACpFL,WAAW,EAAEJ,GAAG,CAACI,WAAW;gBAC5BC,IAAI,EAAEL,GAAG,CAACK,IAAI;gBACdK,IAAI,EAAEV,GAAG,CAACU,IAAI;gBACdC,YAAY,EAAEX,GAAG,CAACW,YAAY;aAC/B;YACDT,GAAG;YACHU,MAAM,EAAE,SAAS;SAClB;KACF,CAAC;AACJ,CAAC;AAGM,eAAed,6BAA6B,CAAC,EAClDe,SAAS,CAAA,EACTb,GAAG,CAAA,EACHC,OAAO,CAAA,EACPC,GAAG,CAAA,EAMJ,EAAE;IACD,MAAMY,YAAY,GAAG,IAAIC,CAAAA,IAAe,EAAA,CAAA,gBAAA,EAAE,AAAC;IAC3CF,SAAS,CAACG,OAAO,CAAC,CAACC,EAAE,GAAK;QACxBH,YAAY,CAACI,MAAM,CAAC,UAAU,EAAED,EAAE,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;IAEH,MAAME,OAAO,GAAG,MAAMC,IAAAA,OAAU,WAAA,EAAC,mCAAmC,EAAE;QACpEN,YAAY;QACZO,MAAM,EAAE,MAAM;QACdC,IAAI,EAAEC,IAAI,CAACC,SAAS,CAAC;YACnBC,IAAI,EAAE5B,iBAAiB,CAAC;gBAAEG,GAAG;gBAAEC,OAAO;gBAAEC,GAAG;aAAE,CAAC;SAC/C,CAAC;KACH,CAAC,AAAC;IAEH,IAAI,CAACiB,OAAO,CAACO,EAAE,EAAE;QACf,MAAM,IAAIC,OAAY,aAAA,CACpB,KAAK,EACL,CAAC,2EAA2E,EAAER,OAAO,CAACS,UAAU,CAAC,CAAC,CAAC,CACpG,CAAC;IACJ,CAAC;AACH,CAAC;AAGM,eAAe7B,4BAA4B,CAAC,EACjDc,SAAS,CAAA,EACTX,GAAG,CAAA,EAIJ,EAAE;IACD,MAAMY,YAAY,GAAG,IAAIC,CAAAA,IAAe,EAAA,CAAA,gBAAA,EAAE,AAAC;IAC3CF,SAAS,CAACG,OAAO,CAAC,CAACC,EAAE,GAAK;QACxBH,YAAY,CAACI,MAAM,CAAC,UAAU,EAAED,EAAE,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;IAEH,MAAME,OAAO,GAAG,MAAMC,IAAAA,OAAU,WAAA,EAAC,mCAAmC,EAAE;QACpEN,YAAY;QACZO,MAAM,EAAE,MAAM;QACdC,IAAI,EAAEC,IAAI,CAACC,SAAS,CAAC;YACnBrB,OAAO,EAAE;gBAAED,GAAG;aAAE;SACjB,CAAC;KACH,CAAC,AAAC;IAEH,IAAI,CAACiB,OAAO,CAACO,EAAE,EAAE;QACf,MAAM,IAAIC,OAAY,aAAA,CACpB,KAAK,EACL,CAAC,0EAA0E,EAAER,OAAO,CAACS,UAAU,CAAC,CAAC,CAAC,CACnG,CAAC;IACJ,CAAC;AACH,CAAC"}

View File

@@ -0,0 +1,91 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: ()=>_default
});
function _getUserState() {
const data = require("@expo/config/build/getUserState");
_getUserState = function() {
return data;
};
return data;
}
function _jsonFile() {
const data = /*#__PURE__*/ _interopRequireDefault(require("@expo/json-file"));
_jsonFile = function() {
return data;
};
return data;
}
function _crypto() {
const data = /*#__PURE__*/ _interopRequireDefault(require("crypto"));
_crypto = function() {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
/** Return the user cache directory. */ function getDirectory() {
return (0, _getUserState().getExpoHomeDirectory)();
}
function getFilePath() {
return (0, _getUserState().getUserStatePath)();
}
function userSettingsJsonFile() {
return new (_jsonFile()).default(getFilePath(), {
ensureDir: true,
jsonParseErrorDefault: {},
cantReadFileDefault: {}
});
}
async function setSessionAsync(sessionData) {
await UserSettings.setAsync("auth", sessionData, {
default: {},
ensureDir: true
});
}
function getSession() {
try {
var ref;
var ref1;
return (ref1 = (ref = _jsonFile().default.read((0, _getUserState().getUserStatePath)())) == null ? void 0 : ref.auth) != null ? ref1 : null;
} catch (error) {
if (error.code === "ENOENT") {
return null;
}
throw error;
}
}
function getAccessToken() {
var _EXPO_TOKEN;
return (_EXPO_TOKEN = process.env.EXPO_TOKEN) != null ? _EXPO_TOKEN : null;
}
// returns an anonymous, unique identifier for a user on the current computer
async function getAnonymousIdentifierAsync() {
const settings = await userSettingsJsonFile();
let id = await settings.getAsync("uuid", null);
if (!id) {
id = _crypto().default.randomUUID();
await settings.setAsync("uuid", id);
}
return id;
}
const UserSettings = Object.assign(userSettingsJsonFile(), {
getSession,
setSessionAsync,
getAccessToken,
getDirectory,
getFilePath,
userSettingsJsonFile,
getAnonymousIdentifierAsync
});
const _default = UserSettings;
//# sourceMappingURL=UserSettings.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/api/user/UserSettings.ts"],"sourcesContent":["import { getExpoHomeDirectory, getUserStatePath } from '@expo/config/build/getUserState';\nimport JsonFile from '@expo/json-file';\nimport crypto from 'crypto';\n\ntype SessionData = {\n sessionSecret: string;\n // These fields are potentially used by Expo CLI.\n userId: string;\n username: string;\n currentConnection: 'Username-Password-Authentication' | 'Browser-Flow-Authentication';\n};\n\nexport type UserSettingsData = {\n auth?: SessionData | null;\n ignoreBundledBinaries?: string[];\n PATH?: string;\n /** Last development code signing ID used for `npx expo run:ios`. */\n developmentCodeSigningId?: string;\n /** Unique user ID which is generated anonymously and can be cleared locally. */\n uuid?: string;\n};\n\n/** Return the user cache directory. */\nfunction getDirectory() {\n return getExpoHomeDirectory();\n}\n\nfunction getFilePath(): string {\n return getUserStatePath();\n}\n\nfunction userSettingsJsonFile(): JsonFile<UserSettingsData> {\n return new JsonFile<UserSettingsData>(getFilePath(), {\n ensureDir: true,\n jsonParseErrorDefault: {},\n cantReadFileDefault: {},\n });\n}\n\nasync function setSessionAsync(sessionData?: SessionData): Promise<void> {\n await UserSettings.setAsync('auth', sessionData, {\n default: {},\n ensureDir: true,\n });\n}\n\nfunction getSession(): SessionData | null {\n try {\n return JsonFile.read<UserSettingsData>(getUserStatePath())?.auth ?? null;\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n}\n\nfunction getAccessToken(): string | null {\n return process.env.EXPO_TOKEN ?? null;\n}\n\n// returns an anonymous, unique identifier for a user on the current computer\nasync function getAnonymousIdentifierAsync(): Promise<string> {\n const settings = await userSettingsJsonFile();\n let id = await settings.getAsync('uuid', null);\n\n if (!id) {\n id = crypto.randomUUID();\n await settings.setAsync('uuid', id);\n }\n\n return id;\n}\n\nconst UserSettings = Object.assign(userSettingsJsonFile(), {\n getSession,\n setSessionAsync,\n getAccessToken,\n getDirectory,\n getFilePath,\n userSettingsJsonFile,\n getAnonymousIdentifierAsync,\n});\n\nexport default UserSettings;\n"],"names":["getDirectory","getExpoHomeDirectory","getFilePath","getUserStatePath","userSettingsJsonFile","JsonFile","ensureDir","jsonParseErrorDefault","cantReadFileDefault","setSessionAsync","sessionData","UserSettings","setAsync","default","getSession","read","auth","error","code","getAccessToken","process","env","EXPO_TOKEN","getAnonymousIdentifierAsync","settings","id","getAsync","crypto","randomUUID","Object","assign"],"mappings":"AAAA;;;;+BAoFA,SAA4B;;aAA5B,QAA4B;;;yBApF2B,iCAAiC;;;;;;;8DACnE,iBAAiB;;;;;;;8DACnB,QAAQ;;;;;;;;;;;AAoB3B,qCAAqC,GACrC,SAASA,YAAY,GAAG;IACtB,OAAOC,IAAAA,aAAoB,EAAA,qBAAA,GAAE,CAAC;AAChC,CAAC;AAED,SAASC,WAAW,GAAW;IAC7B,OAAOC,IAAAA,aAAgB,EAAA,iBAAA,GAAE,CAAC;AAC5B,CAAC;AAED,SAASC,oBAAoB,GAA+B;IAC1D,OAAO,IAAIC,CAAAA,SAAQ,EAAA,CAAA,QAAA,CAAmBH,WAAW,EAAE,EAAE;QACnDI,SAAS,EAAE,IAAI;QACfC,qBAAqB,EAAE,EAAE;QACzBC,mBAAmB,EAAE,EAAE;KACxB,CAAC,CAAC;AACL,CAAC;AAED,eAAeC,eAAe,CAACC,WAAyB,EAAiB;IACvE,MAAMC,YAAY,CAACC,QAAQ,CAAC,MAAM,EAAEF,WAAW,EAAE;QAC/CG,OAAO,EAAE,EAAE;QACXP,SAAS,EAAE,IAAI;KAChB,CAAC,CAAC;AACL,CAAC;AAED,SAASQ,UAAU,GAAuB;IACxC,IAAI;YACKT,GAAmD;YAAnDA,IAAyD;QAAhE,OAAOA,CAAAA,IAAyD,GAAzDA,CAAAA,GAAmD,GAAnDA,SAAQ,EAAA,QAAA,CAACU,IAAI,CAAmBZ,IAAAA,aAAgB,EAAA,iBAAA,GAAE,CAAC,SAAM,GAAzDE,KAAAA,CAAyD,GAAzDA,GAAmD,CAAEW,IAAI,YAAzDX,IAAyD,GAAI,IAAI,CAAC;IAC3E,EAAE,OAAOY,KAAK,EAAO;QACnB,IAAIA,KAAK,CAACC,IAAI,KAAK,QAAQ,EAAE;YAC3B,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAMD,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAASE,cAAc,GAAkB;QAChCC,WAAsB;IAA7B,OAAOA,CAAAA,WAAsB,GAAtBA,OAAO,CAACC,GAAG,CAACC,UAAU,YAAtBF,WAAsB,GAAI,IAAI,CAAC;AACxC,CAAC;AAED,6EAA6E;AAC7E,eAAeG,2BAA2B,GAAoB;IAC5D,MAAMC,QAAQ,GAAG,MAAMpB,oBAAoB,EAAE,AAAC;IAC9C,IAAIqB,EAAE,GAAG,MAAMD,QAAQ,CAACE,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,AAAC;IAE/C,IAAI,CAACD,EAAE,EAAE;QACPA,EAAE,GAAGE,OAAM,EAAA,QAAA,CAACC,UAAU,EAAE,CAAC;QACzB,MAAMJ,QAAQ,CAACZ,QAAQ,CAAC,MAAM,EAAEa,EAAE,CAAC,CAAC;IACtC,CAAC;IAED,OAAOA,EAAE,CAAC;AACZ,CAAC;AAED,MAAMd,YAAY,GAAGkB,MAAM,CAACC,MAAM,CAAC1B,oBAAoB,EAAE,EAAE;IACzDU,UAAU;IACVL,eAAe;IACfU,cAAc;IACdnB,YAAY;IACZE,WAAW;IACXE,oBAAoB;IACpBmB,2BAA2B;CAC5B,CAAC,AAAC;MAEH,QAA4B,GAAbZ,YAAY"}

View File

@@ -0,0 +1,144 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
showLoginPromptAsync: ()=>showLoginPromptAsync,
ensureLoggedInAsync: ()=>ensureLoggedInAsync
});
function _assert() {
const data = /*#__PURE__*/ _interopRequireDefault(require("assert"));
_assert = function() {
return data;
};
return data;
}
function _chalk() {
const data = /*#__PURE__*/ _interopRequireDefault(require("chalk"));
_chalk = function() {
return data;
};
return data;
}
const _otp = require("./otp");
const _user = require("./user");
const _log = /*#__PURE__*/ _interopRequireWildcard(require("../../log"));
const _env = require("../../utils/env");
const _errors = require("../../utils/errors");
const _link = require("../../utils/link");
const _prompts = /*#__PURE__*/ _interopRequireDefault(require("../../utils/prompts"));
const _client = require("../rest/client");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
async function showLoginPromptAsync({ printNewLine =false , otp , ...options } = {}) {
if (_env.env.EXPO_OFFLINE) {
throw new _errors.CommandError("OFFLINE", "Cannot authenticate in offline-mode");
}
const hasCredentials = options.username && options.password;
const sso = options.sso;
if (printNewLine) {
_log.log();
}
if (sso) {
await (0, _user.ssoLoginAsync)();
return;
}
_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)`);
let username = options.username;
let password = options.password;
if (!hasCredentials) {
const resolved = await (0, _prompts.default)([
!options.username && {
type: "text",
name: "username",
message: "Email or username"
},
!options.password && {
type: "password",
name: "password",
message: "Password"
},
].filter(Boolean), {
nonInteractiveHelp: `Use the EXPO_TOKEN environment variable to authenticate in CI (${(0, _link.learnMore)("https://docs.expo.dev/accounts/programmatic-access/")})`
});
username != null ? username : username = resolved.username;
password != null ? password : password = resolved.password;
}
// This is just for the types.
(0, _assert().default)(username && password);
try {
await (0, _user.loginAsync)({
username,
password,
otp
});
} catch (e) {
if (e instanceof _client.ApiV2Error && e.expoApiV2ErrorCode === "ONE_TIME_PASSWORD_REQUIRED") {
await (0, _otp.retryUsernamePasswordAuthWithOTPAsync)(username, password, e.expoApiV2ErrorMetadata);
} else {
throw e;
}
}
}
async function ensureLoggedInAsync() {
let user = await (0, _user.getUserAsync)().catch(()=>null);
if (!user) {
_log.warn(_chalk().default.yellow`An Expo user account is required to proceed.`);
await showLoginPromptAsync({
printNewLine: true
});
user = await (0, _user.getUserAsync)();
}
(0, _assert().default)(user, "User should be logged in");
return user;
}
//# sourceMappingURL=actions.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,172 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getSessionUsingBrowserAuthFlowAsync", {
enumerable: true,
get: ()=>getSessionUsingBrowserAuthFlowAsync
});
function _assert() {
const data = /*#__PURE__*/ _interopRequireDefault(require("assert"));
_assert = function() {
return data;
};
return data;
}
function _betterOpn() {
const data = /*#__PURE__*/ _interopRequireDefault(require("better-opn"));
_betterOpn = function() {
return data;
};
return data;
}
function _http() {
const data = /*#__PURE__*/ _interopRequireDefault(require("http"));
_http = function() {
return data;
};
return data;
}
function _querystring() {
const data = /*#__PURE__*/ _interopRequireDefault(require("querystring"));
_querystring = function() {
return data;
};
return data;
}
const _log = /*#__PURE__*/ _interopRequireWildcard(require("../../log"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const successBody = `
<!DOCTYPE html>
<html lang="en">
<head>
<title>Expo SSO Login</title>
<meta charset="utf-8">
<style type="text/css">
html {
margin: 0;
padding: 0
}
body {
background-color: #fff;
font-family: Tahoma,Verdana;
font-size: 16px;
color: #000;
max-width: 100%;
box-sizing: border-box;
padding: .5rem;
margin: 1em;
overflow-wrap: break-word
}
</style>
</head>
<body>
SSO login complete. You may now close this tab and return to the command prompt.
</body>
</html>`;
async function getSessionUsingBrowserAuthFlowAsync({ expoWebsiteUrl }) {
const scheme = "http";
const hostname = "localhost";
const path = "/auth/callback";
const buildExpoSsoLoginUrl = (port)=>{
const data = {
app_redirect_uri: `${scheme}://${hostname}:${port}${path}`
};
const params = _querystring().default.stringify(data);
return `${expoWebsiteUrl}/sso-login?${params}`;
};
// Start server and begin auth flow
const executeAuthFlow = ()=>{
return new Promise(async (resolve, reject)=>{
const connections = new Set();
const server = _http().default.createServer((request, response)=>{
try {
var ref;
if (!(request.method === "GET" && ((ref = request.url) == null ? void 0 : ref.includes(path)))) {
throw new Error("Unexpected SSO login response.");
}
const url = new URL(request.url, `http:${request.headers.host}`);
const sessionSecret = url.searchParams.get("session_secret");
if (!sessionSecret) {
throw new Error("Request missing session_secret search parameter.");
}
resolve(sessionSecret);
response.writeHead(200, {
"Content-Type": "text/html"
});
response.write(successBody);
response.end();
} catch (error) {
reject(error);
} finally{
server.close();
// Ensure that the server shuts down
for (const connection of connections){
connection.destroy();
}
}
});
server.listen(0, hostname, ()=>{
_log.log("Waiting for browser login...");
const address = server.address();
(0, _assert().default)(address !== null && typeof address === "object", "Server address and port should be set after listening has begun");
const port = address.port;
const authorizeUrl = buildExpoSsoLoginUrl(port);
(0, _betterOpn().default)(authorizeUrl);
});
server.on("connection", (connection)=>{
connections.add(connection);
connection.on("close", ()=>{
connections.delete(connection);
});
});
});
};
return await executeAuthFlow();
}
//# sourceMappingURL=expoSsoLauncher.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,171 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
UserSecondFactorDeviceMethod: ()=>UserSecondFactorDeviceMethod,
retryUsernamePasswordAuthWithOTPAsync: ()=>retryUsernamePasswordAuthWithOTPAsync
});
function _assert() {
const data = /*#__PURE__*/ _interopRequireDefault(require("assert"));
_assert = function() {
return data;
};
return data;
}
function _chalk() {
const data = /*#__PURE__*/ _interopRequireDefault(require("chalk"));
_chalk = function() {
return data;
};
return data;
}
const _user = require("./user");
const _log = /*#__PURE__*/ _interopRequireWildcard(require("../../log"));
const _errors = require("../../utils/errors");
const _link = require("../../utils/link");
const _prompts = require("../../utils/prompts");
const _client = require("../rest/client");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
var UserSecondFactorDeviceMethod;
(function(UserSecondFactorDeviceMethod) {
UserSecondFactorDeviceMethod["AUTHENTICATOR"] = "authenticator";
UserSecondFactorDeviceMethod["SMS"] = "sms";
})(UserSecondFactorDeviceMethod || (UserSecondFactorDeviceMethod = {}));
const nonInteractiveHelp = `Use the EXPO_TOKEN environment variable to authenticate in CI (${(0, _link.learnMore)("https://docs.expo.dev/accounts/programmatic-access/")})`;
/**
* Prompt for an OTP with the option to cancel the question by answering empty (pressing return key).
*/ async function promptForOTPAsync(cancelBehavior) {
const enterMessage = cancelBehavior === "cancel" ? (0, _chalk().default)`press {bold Enter} to cancel` : (0, _chalk().default)`press {bold Enter} for more options`;
const { otp } = await (0, _prompts.promptAsync)({
type: "text",
name: "otp",
message: `One-time password or backup code (${enterMessage}):`
}, {
nonInteractiveHelp
});
return otp || null;
}
/**
* Prompt for user to choose a backup OTP method. If selected method is SMS, a request
* for a new OTP will be sent to that method. Then, prompt for the OTP, and retry the user login.
*/ async function promptForBackupOTPAsync(username, password, secondFactorDevices) {
const nonPrimarySecondFactorDevices = secondFactorDevices.filter((device)=>!device.is_primary);
if (nonPrimarySecondFactorDevices.length === 0) {
throw new _errors.CommandError("No other second-factor devices set up. Ensure you have set up and certified a backup device.");
}
const hasAuthenticatorSecondFactorDevice = nonPrimarySecondFactorDevices.find((device)=>device.method === "authenticator");
const smsNonPrimarySecondFactorDevices = nonPrimarySecondFactorDevices.filter((device)=>device.method === "sms");
const authenticatorChoiceSentinel = -1;
const cancelChoiceSentinel = -2;
const deviceChoices = smsNonPrimarySecondFactorDevices.map((device, idx)=>({
title: device.sms_phone_number,
value: idx
}));
if (hasAuthenticatorSecondFactorDevice) {
deviceChoices.push({
title: "Authenticator",
value: authenticatorChoiceSentinel
});
}
deviceChoices.push({
title: "Cancel",
value: cancelChoiceSentinel
});
const selectedValue = await (0, _prompts.selectAsync)("Select a second-factor device:", deviceChoices, {
nonInteractiveHelp
});
if (selectedValue === cancelChoiceSentinel) {
return null;
} else if (selectedValue === authenticatorChoiceSentinel) {
return await promptForOTPAsync("cancel");
}
const device = smsNonPrimarySecondFactorDevices[selectedValue];
await (0, _client.fetchAsync)("auth/send-sms-otp", {
method: "POST",
body: JSON.stringify({
username,
password,
secondFactorDeviceID: device.id
})
});
return await promptForOTPAsync("cancel");
}
async function retryUsernamePasswordAuthWithOTPAsync(username, password, metadata) {
const { secondFactorDevices , smsAutomaticallySent } = metadata;
(0, _assert().default)(secondFactorDevices !== undefined && smsAutomaticallySent !== undefined, `Malformed OTP error metadata: ${metadata}`);
const primaryDevice = secondFactorDevices.find((device)=>device.is_primary);
let otp = null;
if (smsAutomaticallySent) {
(0, _assert().default)(primaryDevice, "OTP should only automatically be sent when there is a primary device");
_log.log(`One-time password was sent to the phone number ending in ${primaryDevice.sms_phone_number}.`);
otp = await promptForOTPAsync("menu");
}
if ((primaryDevice == null ? void 0 : primaryDevice.method) === "authenticator") {
_log.log("One-time password from authenticator required.");
otp = await promptForOTPAsync("menu");
}
// user bailed on case 1 or 2, wants to move to case 3
if (!otp) {
otp = await promptForBackupOTPAsync(username, password, secondFactorDevices);
}
if (!otp) {
throw new _errors.AbortCommandError();
}
await (0, _user.loginAsync)({
username,
password,
otp
});
}
//# sourceMappingURL=otp.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,176 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ANONYMOUS_USERNAME: ()=>ANONYMOUS_USERNAME,
getActorDisplayName: ()=>getActorDisplayName,
getUserAsync: ()=>getUserAsync,
loginAsync: ()=>loginAsync,
ssoLoginAsync: ()=>ssoLoginAsync,
logoutAsync: ()=>logoutAsync
});
function _fs() {
const data = require("fs");
_fs = function() {
return data;
};
return data;
}
function _graphqlTag() {
const data = /*#__PURE__*/ _interopRequireDefault(require("graphql-tag"));
_graphqlTag = function() {
return data;
};
return data;
}
const _userSettings = /*#__PURE__*/ _interopRequireDefault(require("./UserSettings"));
const _expoSsoLauncher = require("./expoSsoLauncher");
const _log = /*#__PURE__*/ _interopRequireWildcard(require("../../log"));
const _codesigning = require("../../utils/codesigning");
const _env = require("../../utils/env");
const _telemetry = require("../../utils/telemetry");
const _endpoint = require("../endpoint");
const _client = require("../graphql/client");
const _userQuery = require("../graphql/queries/UserQuery");
const _client1 = require("../rest/client");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
let currentUser;
const ANONYMOUS_USERNAME = "anonymous";
function getActorDisplayName(user) {
switch(user == null ? void 0 : user.__typename){
case "User":
return user.username;
case "SSOUser":
return user.username;
case "Robot":
return user.firstName ? `${user.firstName} (robot)` : "robot";
default:
return ANONYMOUS_USERNAME;
}
}
async function getUserAsync() {
var ref;
const hasCredentials = _userSettings.default.getAccessToken() || ((ref = _userSettings.default.getSession()) == null ? void 0 : ref.sessionSecret);
if (!_env.env.EXPO_OFFLINE && !currentUser && hasCredentials) {
var ref1;
const user = await _userQuery.UserQuery.currentUserAsync();
currentUser = user != null ? user : undefined;
(ref1 = (0, _telemetry.getTelemetry)()) == null ? void 0 : ref1.identify(currentUser);
}
return currentUser;
}
async function loginAsync(json) {
const res = await (0, _client1.fetchAsync)("auth/loginAsync", {
method: "POST",
body: JSON.stringify(json)
});
const { data: { sessionSecret } , } = await res.json();
const userData = await fetchUserAsync({
sessionSecret
});
await _userSettings.default.setSessionAsync({
sessionSecret,
userId: userData.id,
username: userData.username,
currentConnection: "Username-Password-Authentication"
});
}
async function ssoLoginAsync() {
const sessionSecret = await (0, _expoSsoLauncher.getSessionUsingBrowserAuthFlowAsync)({
expoWebsiteUrl: (0, _endpoint.getExpoWebsiteBaseUrl)()
});
const userData = await fetchUserAsync({
sessionSecret
});
await _userSettings.default.setSessionAsync({
sessionSecret,
userId: userData.id,
username: userData.username,
currentConnection: "Browser-Flow-Authentication"
});
}
async function logoutAsync() {
currentUser = undefined;
await Promise.all([
_fs().promises.rm((0, _codesigning.getDevelopmentCodeSigningDirectory)(), {
recursive: true,
force: true
}),
_userSettings.default.setSessionAsync(undefined),
]);
_log.log("Logged out");
}
async function fetchUserAsync({ sessionSecret }) {
const result = await _client.graphqlClient.query((0, _graphqlTag().default)`
query UserQuery {
meUserActor {
id
username
}
}
`, {}, {
fetchOptions: {
headers: {
"expo-session": sessionSecret
}
},
additionalTypenames: []
}).toPromise();
const { data } = result;
return {
id: data.meUserActor.id,
username: data.meUserActor.username
};
}
//# sourceMappingURL=user.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,174 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
logConfig: ()=>logConfig,
configAsync: ()=>configAsync
});
function _config() {
const data = require("@expo/config");
_config = function() {
return data;
};
return data;
}
function _assert() {
const data = /*#__PURE__*/ _interopRequireDefault(require("assert"));
_assert = function() {
return data;
};
return data;
}
function _util() {
const data = /*#__PURE__*/ _interopRequireDefault(require("util"));
_util = function() {
return data;
};
return data;
}
const _log = /*#__PURE__*/ _interopRequireWildcard(require("../log"));
const _errors = require("../utils/errors");
const _nodeEnv = require("../utils/nodeEnv");
const _profile = require("../utils/profile");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
function logConfig(config) {
const isObjStr = (str)=>/^\w+: {/g.test(str);
_log.log(_util().default.inspect(config, {
colors: true,
compact: false,
// Sort objects to the end so that smaller values aren't hidden between large objects.
sorted (a, b) {
if (isObjStr(a)) return 1;
if (isObjStr(b)) return -1;
return 0;
},
showHidden: false,
depth: null
}));
}
async function configAsync(projectRoot, options) {
const loggingFunctions = {
log: console.log,
warn: console.warn,
error: console.error
};
// Disable logging for this command if the user wants to get JSON output.
// This will ensure that only the JSON is printed to stdout.
if (options.json) {
console.log = function() {};
console.warn = function() {};
console.error = function() {};
}
(0, _nodeEnv.setNodeEnv)("development");
require("@expo/env").load(projectRoot);
if (options.type) {
_assert().default.match(options.type, /^(public|prebuild|introspect)$/);
}
let config;
if (options.type === "prebuild") {
const { getPrebuildConfigAsync } = await Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("@expo/prebuild-config")));
config = await (0, _profile.profile)(getPrebuildConfigAsync)(projectRoot, {
platforms: [
"ios",
"android"
]
});
} else if (options.type === "introspect") {
const { getPrebuildConfigAsync: getPrebuildConfigAsync1 } = await Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("@expo/prebuild-config")));
const { compileModsAsync } = await Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("@expo/config-plugins/build/plugins/mod-compiler.js")));
config = await (0, _profile.profile)(getPrebuildConfigAsync1)(projectRoot, {
platforms: [
"ios",
"android"
]
});
await compileModsAsync(config.exp, {
projectRoot,
introspect: true,
platforms: [
"ios",
"android"
],
assertMissingModProviders: false
});
// @ts-ignore
delete config.modRequest;
// @ts-ignore
delete config.modResults;
} else if (options.type === "public") {
config = (0, _profile.profile)(_config().getConfig)(projectRoot, {
skipSDKVersionRequirement: true,
isPublicConfig: true
});
} else if (options.type) {
throw new _errors.CommandError(`Invalid option: --type ${options.type}. Valid options are: public, prebuild`);
} else {
config = (0, _profile.profile)(_config().getConfig)(projectRoot, {
skipSDKVersionRequirement: true
});
}
const configOutput = options.full ? config : config.exp;
if (!options.json) {
_log.log();
logConfig(configOutput);
_log.log();
} else {
process.stdout.write(JSON.stringify(configOutput));
// Re-enable logging functions for testing.
console.log = loggingFunctions.log;
console.warn = loggingFunctions.warn;
console.error = loggingFunctions.error;
}
}
//# sourceMappingURL=configAsync.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,97 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "expoConfig", {
enumerable: true,
get: ()=>expoConfig
});
function _chalk() {
const data = /*#__PURE__*/ _interopRequireDefault(require("chalk"));
_chalk = function() {
return data;
};
return data;
}
const _args = require("../utils/args");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const expoConfig = async (argv)=>{
const args = (0, _args.assertArgs)({
// Types
"--help": Boolean,
"--full": Boolean,
"--json": Boolean,
"--type": String,
// Aliases
"-h": "--help",
"-t": "--type"
}, argv);
if (args["--help"]) {
(0, _args.printHelp)(`Show the project config`, (0, _chalk().default)`npx expo config {dim <dir>}`, [
(0, _chalk().default)`<dir> Directory of the Expo project. {dim Default: Current working directory}`,
`--full Include all project config data`,
`--json Output in JSON format`,
`-t, --type <public|prebuild|introspect> Type of config to show`,
`-h, --help Usage info`,
].join("\n"));
}
// Load modules after the help prompt so `npx expo config -h` shows as fast as possible.
const [// ./configAsync
{ configAsync }, // ../utils/errors
{ logCmdError }, ] = await Promise.all([
Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("./configAsync.js"))),
Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("../utils/errors.js")))
]);
return configAsync((0, _args.getProjectRoot)(args), {
// Parsed options
full: args["--full"],
json: args["--json"],
type: args["--type"]
}).catch(logCmdError);
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/config/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport chalk from 'chalk';\n\nimport { Command } from '../../bin/cli';\nimport { assertArgs, getProjectRoot, printHelp } from '../utils/args';\n\nexport const expoConfig: Command = async (argv) => {\n const args = assertArgs(\n {\n // Types\n '--help': Boolean,\n '--full': Boolean,\n '--json': Boolean,\n '--type': String,\n // Aliases\n '-h': '--help',\n '-t': '--type',\n },\n argv\n );\n\n if (args['--help']) {\n printHelp(\n `Show the project config`,\n chalk`npx expo config {dim <dir>}`,\n [\n chalk`<dir> Directory of the Expo project. {dim Default: Current working directory}`,\n `--full Include all project config data`,\n `--json Output in JSON format`,\n `-t, --type <public|prebuild|introspect> Type of config to show`,\n `-h, --help Usage info`,\n ].join('\\n')\n );\n }\n\n // Load modules after the help prompt so `npx expo config -h` shows as fast as possible.\n const [\n // ./configAsync\n { configAsync },\n // ../utils/errors\n { logCmdError },\n ] = await Promise.all([import('./configAsync.js'), import('../utils/errors.js')]);\n\n return configAsync(getProjectRoot(args), {\n // Parsed options\n full: args['--full'],\n json: args['--json'],\n type: args['--type'],\n }).catch(logCmdError);\n};\n"],"names":["expoConfig","argv","args","assertArgs","Boolean","String","printHelp","chalk","join","configAsync","logCmdError","Promise","all","getProjectRoot","full","json","type","catch"],"mappings":"AAAA;;;;;+BAMaA,YAAU;;aAAVA,UAAU;;;8DALL,OAAO;;;;;;sBAG6B,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE9D,MAAMA,UAAU,GAAY,OAAOC,IAAI,GAAK;IACjD,MAAMC,IAAI,GAAGC,IAAAA,KAAU,WAAA,EACrB;QACE,QAAQ;QACR,QAAQ,EAAEC,OAAO;QACjB,QAAQ,EAAEA,OAAO;QACjB,QAAQ,EAAEA,OAAO;QACjB,QAAQ,EAAEC,MAAM;QAChB,UAAU;QACV,IAAI,EAAE,QAAQ;QACd,IAAI,EAAE,QAAQ;KACf,EACDJ,IAAI,CACL,AAAC;IAEF,IAAIC,IAAI,CAAC,QAAQ,CAAC,EAAE;QAClBI,IAAAA,KAAS,UAAA,EACP,CAAC,uBAAuB,CAAC,EACzBC,IAAAA,MAAK,EAAA,QAAA,CAAA,CAAC,2BAA2B,CAAC,EAClC;YACEA,IAAAA,MAAK,EAAA,QAAA,CAAA,CAAC,gHAAgH,CAAC;YACvH,CAAC,wEAAwE,CAAC;YAC1E,CAAC,8DAA8D,CAAC;YAChE,CAAC,+DAA+D,CAAC;YACjE,CAAC,mDAAmD,CAAC;SACtD,CAACC,IAAI,CAAC,IAAI,CAAC,CACb,CAAC;IACJ,CAAC;IAED,wFAAwF;IACxF,MAAM,CACJ,gBAAgB;IAChB,EAAEC,WAAW,CAAA,EAAE,EACf,kBAAkB;IAClB,EAAEC,WAAW,CAAA,EAAE,GAChB,GAAG,MAAMC,OAAO,CAACC,GAAG,CAAC;QAAC,iEAAA,OAAM,CAAC,kBAAkB,GAAC;QAAE,iEAAA,OAAM,CAAC,oBAAoB,GAAC;KAAC,CAAC,AAAC;IAElF,OAAOH,WAAW,CAACI,IAAAA,KAAc,eAAA,EAACX,IAAI,CAAC,EAAE;QACvC,iBAAiB;QACjBY,IAAI,EAAEZ,IAAI,CAAC,QAAQ,CAAC;QACpBa,IAAI,EAAEb,IAAI,CAAC,QAAQ,CAAC;QACpBc,IAAI,EAAEd,IAAI,CAAC,QAAQ,CAAC;KACrB,CAAC,CAACe,KAAK,CAACP,WAAW,CAAC,CAAC;AACxB,CAAC,AAAC"}

View File

@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "customizeAsync", {
enumerable: true,
get: ()=>customizeAsync
});
function _config() {
const data = require("@expo/config");
_config = function() {
return data;
};
return data;
}
const _generate = require("./generate");
const _platformBundlers = require("../start/server/platformBundlers");
const _findUp = require("../utils/findUp");
const _nodeEnv = require("../utils/nodeEnv");
async function customizeAsync(files, options, extras) {
var ref;
(0, _nodeEnv.setNodeEnv)("development");
// Locate the project root based on the process current working directory.
// This enables users to run `npx expo customize` from a subdirectory of the project.
const projectRoot = (0, _findUp.findUpProjectRootOrAssert)(process.cwd());
require("@expo/env").load(projectRoot);
// Get the static path (defaults to 'web/')
// Doesn't matter if expo is installed or which mode is used.
const { exp } = (0, _config().getConfig)(projectRoot, {
skipSDKVersionRequirement: true
});
var ref1;
// Create the destination resolution props which are used in both
// the query and select functions.
const props = {
webStaticPath: ((ref1 = (ref = exp.web) == null ? void 0 : ref.staticPath) != null ? ref1 : (0, _platformBundlers.getPlatformBundlers)(projectRoot, exp).web === "webpack") ? "web" : "public"
};
// If the user provided files, we'll generate them without prompting.
if (files.length) {
return (0, _generate.queryAndGenerateAsync)(projectRoot, {
files,
props,
extras
});
}
// Otherwise, we'll prompt the user to select which files to generate.
await (0, _generate.selectAndGenerateAsync)(projectRoot, {
props,
extras
});
}
//# sourceMappingURL=customizeAsync.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/customize/customizeAsync.ts"],"sourcesContent":["import { getConfig } from '@expo/config';\n\nimport { queryAndGenerateAsync, selectAndGenerateAsync } from './generate';\nimport { Options } from './resolveOptions';\nimport { DestinationResolutionProps } from './templates';\nimport { getPlatformBundlers } from '../start/server/platformBundlers';\nimport { findUpProjectRootOrAssert } from '../utils/findUp';\nimport { setNodeEnv } from '../utils/nodeEnv';\n\nexport async function customizeAsync(files: string[], options: Options, extras: any[]) {\n setNodeEnv('development');\n // Locate the project root based on the process current working directory.\n // This enables users to run `npx expo customize` from a subdirectory of the project.\n const projectRoot = findUpProjectRootOrAssert(process.cwd());\n\n require('@expo/env').load(projectRoot);\n\n // Get the static path (defaults to 'web/')\n // Doesn't matter if expo is installed or which mode is used.\n const { exp } = getConfig(projectRoot, {\n skipSDKVersionRequirement: true,\n });\n\n // Create the destination resolution props which are used in both\n // the query and select functions.\n const props: DestinationResolutionProps = {\n webStaticPath:\n exp.web?.staticPath ?? getPlatformBundlers(projectRoot, exp).web === 'webpack'\n ? 'web'\n : 'public',\n };\n\n // If the user provided files, we'll generate them without prompting.\n if (files.length) {\n return queryAndGenerateAsync(projectRoot, {\n files,\n props,\n extras,\n });\n }\n\n // Otherwise, we'll prompt the user to select which files to generate.\n await selectAndGenerateAsync(projectRoot, {\n props,\n extras,\n });\n}\n"],"names":["customizeAsync","files","options","extras","exp","setNodeEnv","projectRoot","findUpProjectRootOrAssert","process","cwd","require","load","getConfig","skipSDKVersionRequirement","props","webStaticPath","web","staticPath","getPlatformBundlers","length","queryAndGenerateAsync","selectAndGenerateAsync"],"mappings":"AAAA;;;;+BASsBA,gBAAc;;aAAdA,cAAc;;;yBATV,cAAc;;;;;;0BAEsB,YAAY;kCAGtC,kCAAkC;wBAC5B,iBAAiB;yBAChC,kBAAkB;AAEtC,eAAeA,cAAc,CAACC,KAAe,EAAEC,OAAgB,EAAEC,MAAa,EAAE;QAkBjFC,GAAO;IAjBXC,IAAAA,QAAU,WAAA,EAAC,aAAa,CAAC,CAAC;IAC1B,0EAA0E;IAC1E,qFAAqF;IACrF,MAAMC,WAAW,GAAGC,IAAAA,OAAyB,0BAAA,EAACC,OAAO,CAACC,GAAG,EAAE,CAAC,AAAC;IAE7DC,OAAO,CAAC,WAAW,CAAC,CAACC,IAAI,CAACL,WAAW,CAAC,CAAC;IAEvC,2CAA2C;IAC3C,6DAA6D;IAC7D,MAAM,EAAEF,GAAG,CAAA,EAAE,GAAGQ,IAAAA,OAAS,EAAA,UAAA,EAACN,WAAW,EAAE;QACrCO,yBAAyB,EAAE,IAAI;KAChC,CAAC,AAAC;QAMCT,IAAmB;IAJvB,iEAAiE;IACjE,kCAAkC;IAClC,MAAMU,KAAK,GAA+B;QACxCC,aAAa,EACXX,CAAAA,CAAAA,IAAmB,GAAnBA,CAAAA,GAAO,GAAPA,GAAG,CAACY,GAAG,SAAY,GAAnBZ,KAAAA,CAAmB,GAAnBA,GAAO,CAAEa,UAAU,YAAnBb,IAAmB,GAAIc,IAAAA,iBAAmB,oBAAA,EAACZ,WAAW,EAAEF,GAAG,CAAC,CAACY,GAAG,KAAK,SAAS,CAAA,GAC1E,KAAK,GACL,QAAQ;KACf,AAAC;IAEF,qEAAqE;IACrE,IAAIf,KAAK,CAACkB,MAAM,EAAE;QAChB,OAAOC,IAAAA,SAAqB,sBAAA,EAACd,WAAW,EAAE;YACxCL,KAAK;YACLa,KAAK;YACLX,MAAM;SACP,CAAC,CAAC;IACL,CAAC;IAED,sEAAsE;IACtE,MAAMkB,IAAAA,SAAsB,uBAAA,EAACf,WAAW,EAAE;QACxCQ,KAAK;QACLX,MAAM;KACP,CAAC,CAAC;AACL,CAAC"}

View File

@@ -0,0 +1,93 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
queryAndGenerateAsync: ()=>queryAndGenerateAsync,
selectAndGenerateAsync: ()=>selectAndGenerateAsync
});
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
function _resolveFrom() {
const data = /*#__PURE__*/ _interopRequireDefault(require("resolve-from"));
_resolveFrom = function() {
return data;
};
return data;
}
const _templates = require("./templates");
const _installAsync = require("../install/installAsync");
const _log = require("../log");
const _dir = require("../utils/dir");
const _errors = require("../utils/errors");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
async function queryAndGenerateAsync(projectRoot, { files , props , extras }) {
const valid = files.filter((file)=>!!_templates.TEMPLATES.find((template)=>template.destination(props) === file));
if (valid.length !== files.length) {
const diff = files.filter((file)=>!_templates.TEMPLATES.find((template)=>template.destination(props) === file));
throw new _errors.CommandError(`Invalid files: ${diff.join(", ")}. Allowed: ${_templates.TEMPLATES.map((template)=>template.destination(props)).join(", ")}`);
}
if (!valid.length) {
return;
}
_log.Log.log(`Generating: ${valid.join(", ")}`);
return generateAsync(projectRoot, {
answer: files.map((file)=>_templates.TEMPLATES.findIndex((template)=>template.destination(props) === file)),
props,
extras
});
}
async function selectAndGenerateAsync(projectRoot, { props , extras }) {
const answer = await (0, _templates.selectTemplatesAsync)(projectRoot, props);
if (!(answer == null ? void 0 : answer.length)) {
_log.Log.exit("\n Exiting with no change...", 0);
}
await generateAsync(projectRoot, {
answer,
props,
extras
});
}
async function generateAsync(projectRoot, { answer , props , extras }) {
// Copy files
await Promise.all(answer.map(async (file)=>{
const template = _templates.TEMPLATES[file];
if (template.configureAsync) {
if (await template.configureAsync(projectRoot)) {
return;
}
}
const projectFilePath = _path().default.resolve(projectRoot, template.destination(props));
// copy the file from template
return (0, _dir.copyAsync)(template.file(projectRoot), projectFilePath, {
overwrite: true,
recursive: true
});
}));
// Install dependencies
const packages = answer.map((file)=>_templates.TEMPLATES[file].dependencies).flat().filter((pkg)=>!_resolveFrom().default.silent(projectRoot, pkg));
if (packages.length) {
_log.Log.debug("Installing " + packages.join(", "));
await (0, _installAsync.installAsync)(packages, {}, [
"--dev",
...extras
]);
}
}
//# sourceMappingURL=generate.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,49 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "expoCustomize", {
enumerable: true,
get: ()=>expoCustomize
});
function _chalk() {
const data = /*#__PURE__*/ _interopRequireDefault(require("chalk"));
_chalk = function() {
return data;
};
return data;
}
const _args = require("../utils/args");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const expoCustomize = async (argv)=>{
const args = (0, _args.assertWithOptionsArgs)({
// Other options are parsed manually.
"--help": Boolean,
// Aliases
"-h": "--help"
}, {
argv,
// Allow other options, we'll throw an error if unexpected values are passed.
permissive: true
});
if (args["--help"]) {
(0, _args.printHelp)(`Generate static project files`, (0, _chalk().default)`npx expo customize {dim [files...] -- [options]}`, [
(0, _chalk().default)`[files...] List of files to generate`,
(0, _chalk().default)`[options] Options to pass to the install command`,
`-h, --help Usage info`,
].join("\n"));
}
// Load modules after the help prompt so `npx expo install -h` shows as fast as possible.
const { customizeAsync } = require("./customizeAsync");
const { logCmdError } = require("../utils/errors");
const { resolveArgsAsync } = require("./resolveOptions");
const { variadic , options , extras } = await resolveArgsAsync(process.argv.slice(3)).catch(logCmdError);
return customizeAsync(variadic, options, extras).catch(logCmdError);
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/customize/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport chalk from 'chalk';\n\nimport { Command } from '../../bin/cli';\nimport { assertWithOptionsArgs, printHelp } from '../utils/args';\n\nexport const expoCustomize: Command = async (argv) => {\n const args = assertWithOptionsArgs(\n {\n // Other options are parsed manually.\n '--help': Boolean,\n // Aliases\n '-h': '--help',\n },\n {\n argv,\n // Allow other options, we'll throw an error if unexpected values are passed.\n permissive: true,\n }\n );\n\n if (args['--help']) {\n printHelp(\n `Generate static project files`,\n chalk`npx expo customize {dim [files...] -- [options]}`,\n [\n chalk`[files...] List of files to generate`,\n chalk`[options] Options to pass to the install command`,\n `-h, --help Usage info`,\n ].join('\\n')\n );\n }\n\n // Load modules after the help prompt so `npx expo install -h` shows as fast as possible.\n const { customizeAsync } = require('./customizeAsync') as typeof import('./customizeAsync');\n const { logCmdError } = require('../utils/errors') as typeof import('../utils/errors');\n const { resolveArgsAsync } = require('./resolveOptions') as typeof import('./resolveOptions');\n\n const { variadic, options, extras } = await resolveArgsAsync(process.argv.slice(3)).catch(\n logCmdError\n );\n return customizeAsync(variadic, options, extras).catch(logCmdError);\n};\n"],"names":["expoCustomize","argv","args","assertWithOptionsArgs","Boolean","permissive","printHelp","chalk","join","customizeAsync","require","logCmdError","resolveArgsAsync","variadic","options","extras","process","slice","catch"],"mappings":"AAAA;;;;;+BAMaA,eAAa;;aAAbA,aAAa;;;8DALR,OAAO;;;;;;sBAGwB,eAAe;;;;;;AAEzD,MAAMA,aAAa,GAAY,OAAOC,IAAI,GAAK;IACpD,MAAMC,IAAI,GAAGC,IAAAA,KAAqB,sBAAA,EAChC;QACE,qCAAqC;QACrC,QAAQ,EAAEC,OAAO;QACjB,UAAU;QACV,IAAI,EAAE,QAAQ;KACf,EACD;QACEH,IAAI;QACJ,6EAA6E;QAC7EI,UAAU,EAAE,IAAI;KACjB,CACF,AAAC;IAEF,IAAIH,IAAI,CAAC,QAAQ,CAAC,EAAE;QAClBI,IAAAA,KAAS,UAAA,EACP,CAAC,6BAA6B,CAAC,EAC/BC,IAAAA,MAAK,EAAA,QAAA,CAAA,CAAC,gDAAgD,CAAC,EACvD;YACEA,IAAAA,MAAK,EAAA,QAAA,CAAA,CAAC,qCAAqC,CAAC;YAC5CA,IAAAA,MAAK,EAAA,QAAA,CAAA,CAAC,kDAAkD,CAAC;YACzD,CAAC,sBAAsB,CAAC;SACzB,CAACC,IAAI,CAAC,IAAI,CAAC,CACb,CAAC;IACJ,CAAC;IAED,yFAAyF;IACzF,MAAM,EAAEC,cAAc,CAAA,EAAE,GAAGC,OAAO,CAAC,kBAAkB,CAAC,AAAqC,AAAC;IAC5F,MAAM,EAAEC,WAAW,CAAA,EAAE,GAAGD,OAAO,CAAC,iBAAiB,CAAC,AAAoC,AAAC;IACvF,MAAM,EAAEE,gBAAgB,CAAA,EAAE,GAAGF,OAAO,CAAC,kBAAkB,CAAC,AAAqC,AAAC;IAE9F,MAAM,EAAEG,QAAQ,CAAA,EAAEC,OAAO,CAAA,EAAEC,MAAM,CAAA,EAAE,GAAG,MAAMH,gBAAgB,CAACI,OAAO,CAACf,IAAI,CAACgB,KAAK,CAAC,CAAC,CAAC,CAAC,CAACC,KAAK,CACvFP,WAAW,CACZ,AAAC;IACF,OAAOF,cAAc,CAACI,QAAQ,EAAEC,OAAO,EAAEC,MAAM,CAAC,CAACG,KAAK,CAACP,WAAW,CAAC,CAAC;AACtE,CAAC,AAAC"}

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "resolveArgsAsync", {
enumerable: true,
get: ()=>resolveArgsAsync
});
const _variadic = require("../utils/variadic");
async function resolveArgsAsync(argv) {
const { variadic , extras , flags } = (0, _variadic.parseVariadicArguments)(argv);
(0, _variadic.assertUnexpectedObjectKeys)([], flags);
return {
// Variadic arguments like `npx expo install react react-dom` -> ['react', 'react-dom']
variadic,
options: {},
extras
};
}
//# sourceMappingURL=resolveOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/customize/resolveOptions.ts"],"sourcesContent":["import { assertUnexpectedObjectKeys, parseVariadicArguments } from '../utils/variadic';\n\nexport type Options = object;\n\nexport async function resolveArgsAsync(\n argv: string[]\n): Promise<{ variadic: string[]; options: Options; extras: string[] }> {\n const { variadic, extras, flags } = parseVariadicArguments(argv);\n\n assertUnexpectedObjectKeys([], flags);\n\n return {\n // Variadic arguments like `npx expo install react react-dom` -> ['react', 'react-dom']\n variadic,\n options: {},\n extras,\n };\n}\n"],"names":["resolveArgsAsync","argv","variadic","extras","flags","parseVariadicArguments","assertUnexpectedObjectKeys","options"],"mappings":"AAAA;;;;+BAIsBA,kBAAgB;;aAAhBA,gBAAgB;;0BAJ6B,mBAAmB;AAI/E,eAAeA,gBAAgB,CACpCC,IAAc,EACuD;IACrE,MAAM,EAAEC,QAAQ,CAAA,EAAEC,MAAM,CAAA,EAAEC,KAAK,CAAA,EAAE,GAAGC,IAAAA,SAAsB,uBAAA,EAACJ,IAAI,CAAC,AAAC;IAEjEK,IAAAA,SAA0B,2BAAA,EAAC,EAAE,EAAEF,KAAK,CAAC,CAAC;IAEtC,OAAO;QACL,uFAAuF;QACvFF,QAAQ;QACRK,OAAO,EAAE,EAAE;QACXJ,MAAM;KACP,CAAC;AACJ,CAAC"}

View File

@@ -0,0 +1,166 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
TEMPLATES: ()=>TEMPLATES,
selectTemplatesAsync: ()=>selectTemplatesAsync
});
function _chalk() {
const data = /*#__PURE__*/ _interopRequireDefault(require("chalk"));
_chalk = function() {
return data;
};
return data;
}
function _fs() {
const data = /*#__PURE__*/ _interopRequireDefault(require("fs"));
_fs = function() {
return data;
};
return data;
}
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
function _resolveFrom() {
const data = /*#__PURE__*/ _interopRequireDefault(require("resolve-from"));
_resolveFrom = function() {
return data;
};
return data;
}
const _prompts = /*#__PURE__*/ _interopRequireDefault(require("../utils/prompts"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const debug = require("debug")("expo:customize:templates");
function importFromExpoWebpackConfig(projectRoot, folder, moduleId) {
try {
const filePath = (0, _resolveFrom().default)(projectRoot, `@expo/webpack-config/${folder}/${moduleId}`);
debug(`Using @expo/webpack-config template for "${moduleId}": ${filePath}`);
return filePath;
} catch {
debug(`@expo/webpack-config template for "${moduleId}" not found, falling back on @expo/cli`);
}
return importFromVendor(projectRoot, moduleId);
}
function importFromVendor(projectRoot, moduleId) {
try {
const filePath = (0, _resolveFrom().default)(projectRoot, "@expo/cli/static/template/" + moduleId);
debug(`Using @expo/cli template for "${moduleId}": ${filePath}`);
return filePath;
} catch {
// For dev mode, testing and other cases where @expo/cli is not installed
const filePath1 = require.resolve(`@expo/cli/static/template/${moduleId}`);
debug(`Local @expo/cli template for "${moduleId}" not found, falling back on template relative to @expo/cli: ${filePath1}`);
return filePath1;
}
}
const TEMPLATES = [
{
id: "babel.config.js",
file: (projectRoot)=>importFromVendor(projectRoot, "babel.config.js"),
destination: ()=>"babel.config.js",
dependencies: [
// Even though this is installed in `expo`, we should add it for now.
"babel-preset-expo",
]
},
{
id: "metro.config.js",
dependencies: [
"@expo/metro-config"
],
destination: ()=>"metro.config.js",
file: (projectRoot)=>importFromVendor(projectRoot, "metro.config.js")
},
{
// `tsconfig.json` is special-cased and doesn't follow the template.
id: "tsconfig.json",
dependencies: [],
destination: ()=>"tsconfig.json",
file: ()=>"",
configureAsync: async (projectRoot)=>{
const { typescript } = require("./typescript");
await typescript(projectRoot);
return true;
}
},
{
id: ".eslintrc.js",
dependencies: [],
destination: ()=>".eslintrc.js",
file: (projectRoot)=>importFromVendor(projectRoot, ".eslintrc.js"),
configureAsync: async (projectRoot)=>{
const { ESLintProjectPrerequisite } = require("../lint/ESlintPrerequisite");
const prerequisite = new ESLintProjectPrerequisite(projectRoot);
if (!await prerequisite.assertAsync()) {
await prerequisite.bootstrapAsync();
}
return false;
}
},
{
id: "serve.json",
file: (projectRoot)=>importFromExpoWebpackConfig(projectRoot, "web-default", "serve.json"),
// web/serve.json
destination: ({ webStaticPath })=>webStaticPath + "/serve.json",
dependencies: []
},
{
id: "index.html",
file: (projectRoot)=>importFromExpoWebpackConfig(projectRoot, "web-default", "index.html"),
// web/index.html
destination: ({ webStaticPath })=>webStaticPath + "/index.html",
dependencies: []
},
{
id: "webpack.config.js",
file: (projectRoot)=>importFromExpoWebpackConfig(projectRoot, "template", "webpack.config.js"),
destination: ()=>"webpack.config.js",
dependencies: [
"@expo/webpack-config"
]
},
];
/** Generate the prompt choices. */ function createChoices(projectRoot, props) {
return TEMPLATES.map((template, index)=>{
const destination = template.destination(props);
const localProjectFile = _path().default.resolve(projectRoot, destination);
const exists = _fs().default.existsSync(localProjectFile);
return {
title: destination,
value: index,
description: exists ? _chalk().default.red("This will overwrite the existing file") : undefined
};
});
}
async function selectTemplatesAsync(projectRoot, props) {
const options = createChoices(projectRoot, props);
const { answer } = await (0, _prompts.default)({
type: "multiselect",
name: "answer",
message: "Which files would you like to generate?",
hint: "- Space to select. Return to submit",
warn: "File already exists.",
limit: options.length,
instructions: "",
choices: options
});
return answer;
}
//# sourceMappingURL=templates.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,77 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "typescript", {
enumerable: true,
get: ()=>typescript
});
function _config() {
const data = require("@expo/config");
_config = function() {
return data;
};
return data;
}
const _log = require("../log");
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
async function typescript(projectRoot) {
const { TypeScriptProjectPrerequisite } = await Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("../start/doctor/typescript/TypeScriptProjectPrerequisite.js")));
const { MetroBundlerDevServer } = await Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("../start/server/metro/MetroBundlerDevServer.js")));
const { getPlatformBundlers } = await Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("../start/server/platformBundlers.js")));
try {
await new TypeScriptProjectPrerequisite(projectRoot).bootstrapAsync();
} catch (error) {
// Ensure the process doesn't fail if the TypeScript check fails.
// This could happen during the install.
_log.Log.log();
_log.Log.exception(error);
return;
}
const { exp } = (0, _config().getConfig)(projectRoot, {
skipSDKVersionRequirement: true
});
await new MetroBundlerDevServer(projectRoot, getPlatformBundlers(projectRoot, exp), {
isDevClient: true
}).startTypeScriptServices();
}
//# sourceMappingURL=typescript.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/customize/typescript.ts"],"sourcesContent":["import { getConfig } from '@expo/config';\n\nimport { Log } from '../log';\n\nexport async function typescript(projectRoot: string) {\n const { TypeScriptProjectPrerequisite } = await import(\n '../start/doctor/typescript/TypeScriptProjectPrerequisite.js'\n );\n const { MetroBundlerDevServer } = await import('../start/server/metro/MetroBundlerDevServer.js');\n const { getPlatformBundlers } = await import('../start/server/platformBundlers.js');\n\n try {\n await new TypeScriptProjectPrerequisite(projectRoot).bootstrapAsync();\n } catch (error: any) {\n // Ensure the process doesn't fail if the TypeScript check fails.\n // This could happen during the install.\n Log.log();\n Log.exception(error);\n return;\n }\n\n const { exp } = getConfig(projectRoot, { skipSDKVersionRequirement: true });\n await new MetroBundlerDevServer(projectRoot, getPlatformBundlers(projectRoot, exp), {\n isDevClient: true,\n }).startTypeScriptServices();\n}\n"],"names":["typescript","projectRoot","TypeScriptProjectPrerequisite","MetroBundlerDevServer","getPlatformBundlers","bootstrapAsync","error","Log","log","exception","exp","getConfig","skipSDKVersionRequirement","isDevClient","startTypeScriptServices"],"mappings":"AAAA;;;;+BAIsBA,YAAU;;aAAVA,UAAU;;;yBAJN,cAAc;;;;;;qBAEpB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErB,eAAeA,UAAU,CAACC,WAAmB,EAAE;IACpD,MAAM,EAAEC,6BAA6B,CAAA,EAAE,GAAG,MAAM,iEAAA,OAAM,CACpD,6DAA6D,GAC9D,AAAC;IACF,MAAM,EAAEC,qBAAqB,CAAA,EAAE,GAAG,MAAM,iEAAA,OAAM,CAAC,gDAAgD,GAAC,AAAC;IACjG,MAAM,EAAEC,mBAAmB,CAAA,EAAE,GAAG,MAAM,iEAAA,OAAM,CAAC,qCAAqC,GAAC,AAAC;IAEpF,IAAI;QACF,MAAM,IAAIF,6BAA6B,CAACD,WAAW,CAAC,CAACI,cAAc,EAAE,CAAC;IACxE,EAAE,OAAOC,KAAK,EAAO;QACnB,iEAAiE;QACjE,wCAAwC;QACxCC,IAAG,IAAA,CAACC,GAAG,EAAE,CAAC;QACVD,IAAG,IAAA,CAACE,SAAS,CAACH,KAAK,CAAC,CAAC;QACrB,OAAO;IACT,CAAC;IAED,MAAM,EAAEI,GAAG,CAAA,EAAE,GAAGC,IAAAA,OAAS,EAAA,UAAA,EAACV,WAAW,EAAE;QAAEW,yBAAyB,EAAE,IAAI;KAAE,CAAC,AAAC;IAC5E,MAAM,IAAIT,qBAAqB,CAACF,WAAW,EAAEG,mBAAmB,CAACH,WAAW,EAAES,GAAG,CAAC,EAAE;QAClFG,WAAW,EAAE,IAAI;KAClB,CAAC,CAACC,uBAAuB,EAAE,CAAC;AAC/B,CAAC"}

View File

@@ -0,0 +1,49 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createMetadataJson", {
enumerable: true,
get: ()=>createMetadataJson
});
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function createMetadataJson({ bundles , fileNames , embeddedHashSet }) {
// Build metadata.json
return {
version: 0,
bundler: "metro",
fileMetadata: Object.entries(bundles).reduce((metadata, [platform, bundle])=>{
if (platform === "web") return metadata;
return {
...metadata,
[platform]: {
// Get the filename for each platform's bundle.
// TODO: Add multi-bundle support to EAS Update!!
bundle: fileNames[platform][0],
// Collect all of the assets and convert them to the serial format.
assets: bundle.assets.filter((asset)=>!embeddedHashSet || !embeddedHashSet.has(asset.hash)).map((asset)=>{
var // Each asset has multiple hashes which we convert and then flatten.
ref;
return (ref = asset.fileHashes) == null ? void 0 : ref.map((hash)=>({
path: _path().default.join("assets", hash),
ext: asset.type
}));
}).filter(Boolean).flat()
}
};
}, {})
};
}
//# sourceMappingURL=createMetadataJson.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/createMetadataJson.ts"],"sourcesContent":["import path from 'path';\n\nimport type { BundleOutput } from './saveAssets';\n\nexport type BundlePlatform = 'android' | 'ios';\n\ntype PlatformMetadataAsset = { path: string; ext: string };\n\ntype PlatformMetadata = { bundle: string; assets: PlatformMetadataAsset[] };\n\ntype FileMetadata = {\n [key in BundlePlatform]: PlatformMetadata;\n};\n\nexport function createMetadataJson({\n bundles,\n fileNames,\n embeddedHashSet,\n}: {\n bundles: Partial<Record<BundlePlatform, Pick<BundleOutput, 'assets'>>>;\n fileNames: Record<string, string[]>;\n embeddedHashSet?: Set<string>;\n}): {\n version: 0;\n bundler: 'metro';\n fileMetadata: FileMetadata;\n} {\n // Build metadata.json\n return {\n version: 0,\n bundler: 'metro',\n fileMetadata: Object.entries(bundles).reduce<Record<string, Partial<PlatformMetadata>>>(\n (metadata, [platform, bundle]) => {\n if (platform === 'web') return metadata;\n\n return {\n ...metadata,\n [platform]: {\n // Get the filename for each platform's bundle.\n // TODO: Add multi-bundle support to EAS Update!!\n bundle: fileNames[platform][0],\n // Collect all of the assets and convert them to the serial format.\n assets: bundle.assets\n .filter((asset) => !embeddedHashSet || !embeddedHashSet.has(asset.hash))\n .map((asset) =>\n // Each asset has multiple hashes which we convert and then flatten.\n asset.fileHashes?.map((hash) => ({\n path: path.join('assets', hash),\n ext: asset.type,\n }))\n )\n .filter(Boolean)\n .flat(),\n },\n };\n },\n {}\n ) as FileMetadata,\n };\n}\n"],"names":["createMetadataJson","bundles","fileNames","embeddedHashSet","version","bundler","fileMetadata","Object","entries","reduce","metadata","platform","bundle","assets","filter","asset","has","hash","map","fileHashes","path","join","ext","type","Boolean","flat"],"mappings":"AAAA;;;;+BAcgBA,oBAAkB;;aAAlBA,kBAAkB;;;8DAdjB,MAAM;;;;;;;;;;;AAchB,SAASA,kBAAkB,CAAC,EACjCC,OAAO,CAAA,EACPC,SAAS,CAAA,EACTC,eAAe,CAAA,EAKhB,EAIC;IACA,sBAAsB;IACtB,OAAO;QACLC,OAAO,EAAE,CAAC;QACVC,OAAO,EAAE,OAAO;QAChBC,YAAY,EAAEC,MAAM,CAACC,OAAO,CAACP,OAAO,CAAC,CAACQ,MAAM,CAC1C,CAACC,QAAQ,EAAE,CAACC,QAAQ,EAAEC,MAAM,CAAC,GAAK;YAChC,IAAID,QAAQ,KAAK,KAAK,EAAE,OAAOD,QAAQ,CAAC;YAExC,OAAO;gBACL,GAAGA,QAAQ;gBACX,CAACC,QAAQ,CAAC,EAAE;oBACV,+CAA+C;oBAC/C,iDAAiD;oBACjDC,MAAM,EAAEV,SAAS,CAACS,QAAQ,CAAC,CAAC,CAAC,CAAC;oBAC9B,mEAAmE;oBACnEE,MAAM,EAAED,MAAM,CAACC,MAAM,CAClBC,MAAM,CAAC,CAACC,KAAK,GAAK,CAACZ,eAAe,IAAI,CAACA,eAAe,CAACa,GAAG,CAACD,KAAK,CAACE,IAAI,CAAC,CAAC,CACvEC,GAAG,CAAC,CAACH,KAAK;4BACT,oEAAoE;wBACpEA,GAAgB;wBAAhBA,OAAAA,CAAAA,GAAgB,GAAhBA,KAAK,CAACI,UAAU,SAAK,GAArBJ,KAAAA,CAAqB,GAArBA,GAAgB,CAAEG,GAAG,CAAC,CAACD,IAAI,GAAK,CAAC;gCAC/BG,IAAI,EAAEA,KAAI,EAAA,QAAA,CAACC,IAAI,CAAC,QAAQ,EAAEJ,IAAI,CAAC;gCAC/BK,GAAG,EAAEP,KAAK,CAACQ,IAAI;6BAChB,CAAC,CAAC,CAAA;qBAAA,CACJ,CACAT,MAAM,CAACU,OAAO,CAAC,CACfC,IAAI,EAAE;iBACV;aACF,CAAC;QACJ,CAAC,EACD,EAAE,CACH;KACF,CAAC;AACJ,CAAC"}

View File

@@ -0,0 +1,312 @@
/**
* Copyright © 2023 650 Industries.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
exportEmbedAsync: ()=>exportEmbedAsync,
exportEmbedBundleAndAssetsAsync: ()=>exportEmbedBundleAndAssetsAsync,
createMetroServerAndBundleRequestAsync: ()=>createMetroServerAndBundleRequestAsync,
exportEmbedAssetsAsync: ()=>exportEmbedAssetsAsync
});
function _config() {
const data = require("@expo/config");
_config = function() {
return data;
};
return data;
}
function _getAssets() {
const data = /*#__PURE__*/ _interopRequireDefault(require("@expo/metro-config/build/transform-worker/getAssets"));
_getAssets = function() {
return data;
};
return data;
}
function _assert() {
const data = /*#__PURE__*/ _interopRequireDefault(require("assert"));
_assert = function() {
return data;
};
return data;
}
function _fs() {
const data = /*#__PURE__*/ _interopRequireDefault(require("fs"));
_fs = function() {
return data;
};
return data;
}
function _glob() {
const data = require("glob");
_glob = function() {
return data;
};
return data;
}
function _server() {
const data = /*#__PURE__*/ _interopRequireDefault(require("metro/src/Server"));
_server = function() {
return data;
};
return data;
}
function _splitBundleOptions() {
const data = /*#__PURE__*/ _interopRequireDefault(require("metro/src/lib/splitBundleOptions"));
_splitBundleOptions = function() {
return data;
};
return data;
}
function _bundle() {
const data = /*#__PURE__*/ _interopRequireDefault(require("metro/src/shared/output/bundle"));
_bundle = function() {
return data;
};
return data;
}
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
const _xcodeCompilerLogger = require("./xcodeCompilerLogger");
const _log = require("../../log");
const _devServerManager = require("../../start/server/DevServerManager");
const _metroBundlerDevServer = require("../../start/server/metro/MetroBundlerDevServer");
const _instantiateMetro = require("../../start/server/metro/instantiateMetro");
const _metroPrivateServer = require("../../start/server/metro/metroPrivateServer");
const _metroOptions = require("../../start/server/middleware/metroOptions");
const _ansi = require("../../utils/ansi");
const _dir = require("../../utils/dir");
const _nodeEnv = require("../../utils/nodeEnv");
const _exportHermes = require("../exportHermes");
const _persistMetroAssets = require("../persistMetroAssets");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const debug = require("debug")("expo:export:embed");
function guessCopiedAppleBundlePath(bundleOutput) {
// Ensure the path is familiar before guessing.
if (!bundleOutput.match(/\/Xcode\/DerivedData\/.*\/Build\/Products\//)) {
debug("Bundling to non-standard location:", bundleOutput);
return false;
}
const bundleName = _path().default.basename(bundleOutput);
const bundleParent = _path().default.dirname(bundleOutput);
const possiblePath = (0, _glob().sync)(_path().default.join(bundleParent, `*.app/${bundleName}`), {
// bundle identifiers can start with dots.
dot: true
})[0];
debug("Possible path for previous bundle:", possiblePath);
return possiblePath;
}
async function exportEmbedAsync(projectRoot, options) {
(0, _nodeEnv.setNodeEnv)(options.dev ? "development" : "production");
require("@expo/env").load(projectRoot);
// Ensure we delete the old bundle to trigger a failure if the bundle cannot be created.
await (0, _dir.removeAsync)(options.bundleOutput);
// The iOS bundle is copied in to the Xcode project, so we need to remove the old one
// to prevent Xcode from loading the old one after a build failure.
if (options.platform === "ios") {
const previousPath = guessCopiedAppleBundlePath(options.bundleOutput);
if (previousPath && _fs().default.existsSync(previousPath)) {
debug("Removing previous iOS bundle:", previousPath);
await (0, _dir.removeAsync)(previousPath);
}
}
const { bundle , assets } = await exportEmbedBundleAndAssetsAsync(projectRoot, options);
_fs().default.mkdirSync(_path().default.dirname(options.bundleOutput), {
recursive: true,
mode: 493
});
// Persist bundle and source maps.
await Promise.all([
_bundle().default.save(bundle, options, _log.Log.log),
// NOTE(EvanBacon): This may need to be adjusted in the future if want to support baseUrl on native
// platforms when doing production embeds (unlikely).
options.assetsDest ? (0, _persistMetroAssets.persistMetroAssetsAsync)(assets, {
platform: options.platform,
outputDirectory: options.assetsDest,
iosAssetCatalogDirectory: options.assetCatalogDest
}) : null,
]);
}
async function exportEmbedBundleAndAssetsAsync(projectRoot, options) {
const devServerManager = await _devServerManager.DevServerManager.startMetroAsync(projectRoot, {
minify: options.minify,
mode: options.dev ? "development" : "production",
port: 8081,
isExporting: true,
location: {},
resetDevServer: options.resetCache,
maxWorkers: options.maxWorkers
});
const devServer = devServerManager.getDefaultDevServer();
(0, _assert().default)(devServer instanceof _metroBundlerDevServer.MetroBundlerDevServer);
const exp = (0, _config().getConfig)(projectRoot, {
skipSDKVersionRequirement: true
}).exp;
const isHermes = (0, _exportHermes.isEnableHermesManaged)(exp, options.platform);
let sourceMapUrl = options.sourcemapOutput;
if (sourceMapUrl && !options.sourcemapUseAbsolutePath) {
sourceMapUrl = _path().default.basename(sourceMapUrl);
}
try {
var ref, ref1;
const bundles = await devServer.legacySinglePageExportBundleAsync({
splitChunks: false,
mainModuleName: resolveRealEntryFilePath(projectRoot, options.entryFile),
platform: options.platform,
minify: options.minify,
mode: options.dev ? "development" : "production",
engine: isHermes ? "hermes" : undefined,
serializerIncludeMaps: !!sourceMapUrl,
// Never output bytecode in the exported bundle since that is hardcoded in the native run script.
bytecode: false,
// source map inline
reactCompiler: !!((ref = exp.experiments) == null ? void 0 : ref.reactCompiler)
}, {
sourceMapUrl,
unstable_transformProfile: options.unstableTransformProfile || (isHermes ? "hermes-stable" : "default")
});
return {
bundle: {
code: bundles.artifacts.filter((a)=>a.type === "js")[0].source.toString(),
// Can be optional when source maps aren't enabled.
map: (ref1 = bundles.artifacts.filter((a)=>a.type === "map")[0]) == null ? void 0 : ref1.source.toString()
},
assets: bundles.assets
};
} catch (error) {
if (isError(error)) {
// Log using Xcode error format so the errors are picked up by xcodebuild.
// https://developer.apple.com/documentation/xcode/running-custom-scripts-during-a-build#Log-errors-and-warnings-from-your-script
if (options.platform === "ios") {
// If the error is about to be presented in Xcode, strip the ansi characters from the message.
if ("message" in error && (0, _xcodeCompilerLogger.isExecutingFromXcodebuild)()) {
error.message = (0, _ansi.stripAnsi)(error.message);
}
(0, _xcodeCompilerLogger.logMetroErrorInXcode)(projectRoot, error);
}
}
throw error;
} finally{
devServerManager.stopAsync();
}
}
async function createMetroServerAndBundleRequestAsync(projectRoot, options) {
const exp = (0, _config().getConfig)(projectRoot, {
skipSDKVersionRequirement: true
}).exp;
// TODO: This is slow ~40ms
const { config } = await (0, _instantiateMetro.loadMetroConfigAsync)(projectRoot, {
// TODO: This is always enabled in the native script and there's no way to disable it.
resetCache: options.resetCache,
maxWorkers: options.maxWorkers,
config: options.config
}, {
exp,
isExporting: true,
getMetroBundler () {
return server.getBundler().getBundler();
}
});
const isHermes = (0, _exportHermes.isEnableHermesManaged)(exp, options.platform);
let sourceMapUrl = options.sourcemapOutput;
if (sourceMapUrl && !options.sourcemapUseAbsolutePath) {
sourceMapUrl = _path().default.basename(sourceMapUrl);
}
const bundleRequest = {
..._server().default.DEFAULT_BUNDLE_OPTIONS,
...(0, _metroOptions.getMetroDirectBundleOptionsForExpoConfig)(projectRoot, exp, {
splitChunks: false,
mainModuleName: resolveRealEntryFilePath(projectRoot, options.entryFile),
platform: options.platform,
minify: options.minify,
mode: options.dev ? "development" : "production",
engine: isHermes ? "hermes" : undefined,
isExporting: true,
// Never output bytecode in the exported bundle since that is hardcoded in the native run script.
bytecode: false
}),
sourceMapUrl,
unstable_transformProfile: options.unstableTransformProfile || (isHermes ? "hermes-stable" : "default")
};
const server = new (_server()).default(config, {
watch: false
});
return {
server,
bundleRequest
};
}
async function exportEmbedAssetsAsync(server, bundleRequest, projectRoot, options) {
try {
const { entryFile , onProgress , resolverOptions , transformOptions } = (0, _splitBundleOptions().default)({
...bundleRequest,
bundleType: "todo"
});
(0, _metroPrivateServer.assertMetroPrivateServer)(server);
const dependencies = await server._bundler.getDependencies([
entryFile
], transformOptions, resolverOptions, {
onProgress,
shallow: false,
lazy: false
});
const config = server._config;
return (0, _getAssets().default)(dependencies, {
processModuleFilter: config.serializer.processModuleFilter,
assetPlugins: config.transformer.assetPlugins,
platform: transformOptions.platform,
// Forked out of Metro because the `this._getServerRootDir()` doesn't match the development
// behavior.
projectRoot: config.projectRoot,
publicPath: config.transformer.publicPath
});
} catch (error) {
if (isError(error)) {
// Log using Xcode error format so the errors are picked up by xcodebuild.
// https://developer.apple.com/documentation/xcode/running-custom-scripts-during-a-build#Log-errors-and-warnings-from-your-script
if (options.platform === "ios") {
// If the error is about to be presented in Xcode, strip the ansi characters from the message.
if ("message" in error && (0, _xcodeCompilerLogger.isExecutingFromXcodebuild)()) {
error.message = (0, _ansi.stripAnsi)(error.message);
}
(0, _xcodeCompilerLogger.logMetroErrorInXcode)(projectRoot, error);
}
}
throw error;
}
}
function isError(error) {
return error instanceof Error;
}
/**
* This is a workaround for Metro not resolving entry file paths to their real location.
* When running exports through `eas build --local` on macOS, the `/var/folders` path is used instead of `/private/var/folders`.
*
* See: https://github.com/expo/expo/issues/28890
*/ function resolveRealEntryFilePath(projectRoot, entryFile) {
if (projectRoot.startsWith("/private/var") && entryFile.startsWith("/var")) {
return _fs().default.realpathSync(entryFile);
}
return entryFile;
}
//# sourceMappingURL=exportEmbedAsync.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,143 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "expoExportEmbed", {
enumerable: true,
get: ()=>expoExportEmbed
});
function _chalk() {
const data = /*#__PURE__*/ _interopRequireDefault(require("chalk"));
_chalk = function() {
return data;
};
return data;
}
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
const _args = require("../../utils/args");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const expoExportEmbed = async (argv)=>{
const rawArgsMap = {
// Types
"--entry-file": String,
"--platform": String,
"--transformer": String,
"--bundle-output": String,
"--bundle-encoding": String,
"--max-workers": Number,
"--sourcemap-output": String,
"--sourcemap-sources-root": String,
"--assets-dest": String,
"--asset-catalog-dest": String,
"--unstable-transform-profile": String,
"--config": String,
// Hack: This is added because react-native-xcode.sh script always includes this value.
// If supplied, we'll do nothing with the value, but at least the process won't crash.
// Note that we also don't show this value in the `--help` prompt since we don't want people to use it.
"--config-cmd": String,
// This is here for compatibility with the `npx react-native bundle` command.
// devs should use `DEBUG=expo:*` instead.
"--verbose": Boolean,
"--help": Boolean,
// Aliases
"-h": "--help",
"-v": "--verbose"
};
const args = (0, _args.assertWithOptionsArgs)(rawArgsMap, {
argv,
permissive: true
});
if (args["--help"]) {
(0, _args.printHelp)(`(Internal) Export the JavaScript bundle during a native build script for embedding in a native binary`, (0, _chalk().default)`npx expo export:embed {dim <dir>}`, [
(0, _chalk().default)`<dir> Directory of the Expo project. {dim Default: Current working directory}`,
`--entry-file <path> Path to the root JS file, either absolute or relative to JS root`,
`--platform <string> Either "ios" or "android" (default: "ios")`,
`--transformer <string> Specify a custom transformer to be used`,
`--dev [boolean] If false, warnings are disabled and the bundle is minified (default: true)`,
`--minify [boolean] Allows overriding whether bundle is minified. This defaults to false if dev is true, and true if dev is false. Disabling minification can be useful for speeding up production builds for testing purposes.`,
`--bundle-output <string> File name where to store the resulting bundle, ex. /tmp/groups.bundle`,
`--bundle-encoding <string> Encoding the bundle should be written in (https://nodejs.org/api/buffer.html#buffer_buffer). (default: "utf8")`,
`--max-workers <number> Specifies the maximum number of workers the worker-pool will spawn for transforming files. This defaults to the number of the cores available on your machine.`,
`--sourcemap-output <string> File name where to store the sourcemap file for resulting bundle, ex. /tmp/groups.map`,
`--sourcemap-sources-root <string> Path to make sourcemap's sources entries relative to, ex. /root/dir`,
`--sourcemap-use-absolute-path Report SourceMapURL using its full path`,
`--assets-dest <string> Directory name where to store assets referenced in the bundle`,
`--asset-catalog-dest <string> Directory to create an iOS Asset Catalog for images`,
`--unstable-transform-profile <string> Experimental, transform JS for a specific JS engine. Currently supported: hermes, hermes-canary, default`,
`--reset-cache Removes cached files`,
`-v, --verbose Enables debug logging`,
`--config <string> Path to the CLI configuration file`,
// This is seemingly unused.
`--read-global-cache Try to fetch transformed JS code from the global cache, if configured.`,
`-h, --help Usage info`,
].join("\n"));
}
const [{ exportEmbedAsync }, { resolveOptions }, { logCmdError }, { resolveCustomBooleanArgsAsync }, ] = await Promise.all([
Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("./exportEmbedAsync.js"))),
Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("./resolveOptions.js"))),
Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("../../utils/errors.js"))),
Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("../../utils/resolveArgs.js"))),
]);
return (async ()=>{
const parsed = await resolveCustomBooleanArgsAsync(argv != null ? argv : [], rawArgsMap, {
"--dev": Boolean,
"--minify": Boolean,
"--sourcemap-use-absolute-path": Boolean,
"--reset-cache": Boolean,
"--read-global-cache": Boolean
});
return exportEmbedAsync(_path().default.resolve(parsed.projectRoot), resolveOptions(args, parsed));
})().catch(logCmdError);
};
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,67 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "resolveOptions", {
enumerable: true,
get: ()=>resolveOptions
});
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
const _env = require("../../utils/env");
const _errors = require("../../utils/errors");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function assertIsBoolean(val) {
if (typeof val !== "boolean") {
throw new _errors.CommandError(`Expected boolean, got ${typeof val}`);
}
}
function resolveOptions(args, parsed) {
var ref;
const dev = (ref = parsed.args["--dev"]) != null ? ref : true;
assertIsBoolean(dev);
var ref1;
const minify = (ref1 = parsed.args["--minify"]) != null ? ref1 : !dev;
assertIsBoolean(minify);
const entryFile = args["--entry-file"];
if (!entryFile) {
throw new _errors.CommandError(`Missing required argument: --entry-file`);
}
const bundleOutput = args["--bundle-output"];
if (!bundleOutput) {
throw new _errors.CommandError(`Missing required argument: --bundle-output`);
}
var ref2, ref3, ref4;
return {
entryFile,
assetCatalogDest: args["--asset-catalog-dest"],
platform: (ref2 = args["--platform"]) != null ? ref2 : "ios",
transformer: args["--transformer"],
// TODO: Support `--dev false`
// dev: false,
bundleOutput,
bundleEncoding: (ref3 = args["--bundle-encoding"]) != null ? ref3 : "utf8",
maxWorkers: args["--max-workers"],
sourcemapOutput: args["--sourcemap-output"],
sourcemapSourcesRoot: args["--sourcemap-sources-root"],
sourcemapUseAbsolutePath: !!parsed.args["--sourcemap-use-absolute-path"],
assetsDest: args["--assets-dest"],
unstableTransformProfile: args["--unstable-transform-profile"],
resetCache: !!parsed.args["--reset-cache"],
verbose: (ref4 = args["--verbose"]) != null ? ref4 : _env.env.EXPO_DEBUG,
config: args["--config"] ? _path().default.resolve(args["--config"]) : undefined,
dev,
minify
};
}
//# sourceMappingURL=resolveOptions.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/export/embed/resolveOptions.ts"],"sourcesContent":["import arg from 'arg';\nimport path from 'path';\n\nimport { env } from '../../utils/env';\nimport { CommandError } from '../../utils/errors';\nimport { resolveCustomBooleanArgsAsync } from '../../utils/resolveArgs';\n\nexport interface Options {\n assetsDest?: string;\n assetCatalogDest?: string;\n entryFile: string;\n resetCache: boolean;\n transformer?: string;\n minify?: boolean;\n config?: string;\n platform: string;\n dev: boolean;\n bundleOutput: string;\n bundleEncoding?: string;\n maxWorkers?: number;\n sourcemapOutput?: string;\n sourcemapSourcesRoot?: string;\n sourcemapUseAbsolutePath: boolean;\n verbose: boolean;\n unstableTransformProfile?: string;\n}\n\nfunction assertIsBoolean(val: any): asserts val is boolean {\n if (typeof val !== 'boolean') {\n throw new CommandError(`Expected boolean, got ${typeof val}`);\n }\n}\n\nexport function resolveOptions(\n args: arg.Result<arg.Spec>,\n parsed: Awaited<ReturnType<typeof resolveCustomBooleanArgsAsync>>\n): Options {\n const dev = parsed.args['--dev'] ?? true;\n assertIsBoolean(dev);\n\n const minify = parsed.args['--minify'] ?? !dev;\n assertIsBoolean(minify);\n\n const entryFile = args['--entry-file'];\n if (!entryFile) {\n throw new CommandError(`Missing required argument: --entry-file`);\n }\n const bundleOutput = args['--bundle-output'];\n if (!bundleOutput) {\n throw new CommandError(`Missing required argument: --bundle-output`);\n }\n return {\n entryFile,\n assetCatalogDest: args['--asset-catalog-dest'],\n platform: args['--platform'] ?? 'ios',\n transformer: args['--transformer'],\n // TODO: Support `--dev false`\n // dev: false,\n bundleOutput,\n bundleEncoding: args['--bundle-encoding'] ?? 'utf8',\n maxWorkers: args['--max-workers'],\n sourcemapOutput: args['--sourcemap-output'],\n sourcemapSourcesRoot: args['--sourcemap-sources-root'],\n sourcemapUseAbsolutePath: !!parsed.args['--sourcemap-use-absolute-path'],\n assetsDest: args['--assets-dest'],\n unstableTransformProfile: args['--unstable-transform-profile'],\n resetCache: !!parsed.args['--reset-cache'],\n verbose: args['--verbose'] ?? env.EXPO_DEBUG,\n config: args['--config'] ? path.resolve(args['--config']) : undefined,\n dev,\n minify,\n };\n}\n"],"names":["resolveOptions","assertIsBoolean","val","CommandError","args","parsed","dev","minify","entryFile","bundleOutput","assetCatalogDest","platform","transformer","bundleEncoding","maxWorkers","sourcemapOutput","sourcemapSourcesRoot","sourcemapUseAbsolutePath","assetsDest","unstableTransformProfile","resetCache","verbose","env","EXPO_DEBUG","config","path","resolve","undefined"],"mappings":"AAAA;;;;+BAiCgBA,gBAAc;;aAAdA,cAAc;;;8DAhCb,MAAM;;;;;;qBAEH,iBAAiB;wBACR,oBAAoB;;;;;;AAuBjD,SAASC,eAAe,CAACC,GAAQ,EAA0B;IACzD,IAAI,OAAOA,GAAG,KAAK,SAAS,EAAE;QAC5B,MAAM,IAAIC,OAAY,aAAA,CAAC,CAAC,sBAAsB,EAAE,OAAOD,GAAG,CAAC,CAAC,CAAC,CAAC;IAChE,CAAC;AACH,CAAC;AAEM,SAASF,cAAc,CAC5BI,IAA0B,EAC1BC,MAAiE,EACxD;QACGA,GAAoB;IAAhC,MAAMC,GAAG,GAAGD,CAAAA,GAAoB,GAApBA,MAAM,CAACD,IAAI,CAAC,OAAO,CAAC,YAApBC,GAAoB,GAAI,IAAI,AAAC;IACzCJ,eAAe,CAACK,GAAG,CAAC,CAAC;QAEND,IAAuB;IAAtC,MAAME,MAAM,GAAGF,CAAAA,IAAuB,GAAvBA,MAAM,CAACD,IAAI,CAAC,UAAU,CAAC,YAAvBC,IAAuB,GAAI,CAACC,GAAG,AAAC;IAC/CL,eAAe,CAACM,MAAM,CAAC,CAAC;IAExB,MAAMC,SAAS,GAAGJ,IAAI,CAAC,cAAc,CAAC,AAAC;IACvC,IAAI,CAACI,SAAS,EAAE;QACd,MAAM,IAAIL,OAAY,aAAA,CAAC,CAAC,uCAAuC,CAAC,CAAC,CAAC;IACpE,CAAC;IACD,MAAMM,YAAY,GAAGL,IAAI,CAAC,iBAAiB,CAAC,AAAC;IAC7C,IAAI,CAACK,YAAY,EAAE;QACjB,MAAM,IAAIN,OAAY,aAAA,CAAC,CAAC,0CAA0C,CAAC,CAAC,CAAC;IACvE,CAAC;QAIWC,IAAkB,EAKZA,IAAyB,EAQhCA,IAAiB;IAhB5B,OAAO;QACLI,SAAS;QACTE,gBAAgB,EAAEN,IAAI,CAAC,sBAAsB,CAAC;QAC9CO,QAAQ,EAAEP,CAAAA,IAAkB,GAAlBA,IAAI,CAAC,YAAY,CAAC,YAAlBA,IAAkB,GAAI,KAAK;QACrCQ,WAAW,EAAER,IAAI,CAAC,eAAe,CAAC;QAClC,8BAA8B;QAC9B,gBAAgB;QAChBK,YAAY;QACZI,cAAc,EAAET,CAAAA,IAAyB,GAAzBA,IAAI,CAAC,mBAAmB,CAAC,YAAzBA,IAAyB,GAAI,MAAM;QACnDU,UAAU,EAAEV,IAAI,CAAC,eAAe,CAAC;QACjCW,eAAe,EAAEX,IAAI,CAAC,oBAAoB,CAAC;QAC3CY,oBAAoB,EAAEZ,IAAI,CAAC,0BAA0B,CAAC;QACtDa,wBAAwB,EAAE,CAAC,CAACZ,MAAM,CAACD,IAAI,CAAC,+BAA+B,CAAC;QACxEc,UAAU,EAAEd,IAAI,CAAC,eAAe,CAAC;QACjCe,wBAAwB,EAAEf,IAAI,CAAC,8BAA8B,CAAC;QAC9DgB,UAAU,EAAE,CAAC,CAACf,MAAM,CAACD,IAAI,CAAC,eAAe,CAAC;QAC1CiB,OAAO,EAAEjB,CAAAA,IAAiB,GAAjBA,IAAI,CAAC,WAAW,CAAC,YAAjBA,IAAiB,GAAIkB,IAAG,IAAA,CAACC,UAAU;QAC5CC,MAAM,EAAEpB,IAAI,CAAC,UAAU,CAAC,GAAGqB,KAAI,EAAA,QAAA,CAACC,OAAO,CAACtB,IAAI,CAAC,UAAU,CAAC,CAAC,GAAGuB,SAAS;QACrErB,GAAG;QACHC,MAAM;KACP,CAAC;AACJ,CAAC"}

View File

@@ -0,0 +1,121 @@
/**
* Copyright © 2023 650 Industries.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getXcodeCompilerErrorMessage: ()=>getXcodeCompilerErrorMessage,
logMetroErrorInXcode: ()=>logMetroErrorInXcode,
isExecutingFromXcodebuild: ()=>isExecutingFromXcodebuild
});
function _fs() {
const data = /*#__PURE__*/ _interopRequireDefault(require("fs"));
_fs = function() {
return data;
};
return data;
}
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function isPossiblyUnableToResolveError(error) {
return "message" in error && typeof error.message === "string" && "originModulePath" in error && typeof error.originModulePath === "string" && "targetModuleName" in error && typeof error.targetModuleName === "string";
}
function isPossiblyTransformError(error) {
return "message" in error && typeof error.message === "string" && "filename" in error && typeof error.filename === "string" && "lineNumber" in error && typeof error.lineNumber === "number";
}
function getXcodeCompilerErrorMessage(projectRoot, error) {
const makeFilepathAbsolute = (filepath)=>filepath.startsWith("/") ? filepath : _path().default.join(projectRoot, filepath);
if ("message" in error) {
// Metro's `UnableToResolveError`
if (isPossiblyUnableToResolveError(error)) {
const loc = getLineNumberForStringInFile(error.originModulePath, error.targetModuleName);
return makeXcodeCompilerLog("error", error.message, {
fileName: error.originModulePath,
lineNumber: loc == null ? void 0 : loc.lineNumber,
column: loc == null ? void 0 : loc.column
});
} else if (isPossiblyTransformError(error)) {
return makeXcodeCompilerLog("error", error.message, {
// Metro generally returns the filename as relative from the project root.
fileName: makeFilepathAbsolute(error.filename),
lineNumber: error.lineNumber,
column: error.column
});
// TODO: ResourceNotFoundError, GraphNotFoundError, RevisionNotFoundError, AmbiguousModuleResolutionError
} else {
// Unknown error
return makeXcodeCompilerLog("error", error.message);
}
}
return null;
}
function logMetroErrorInXcode(projectRoot, error) {
const message = getXcodeCompilerErrorMessage(projectRoot, error);
if (message != null) {
console.error(message);
}
}
function isExecutingFromXcodebuild() {
return !!process.env.BUILT_PRODUCTS_DIR;
}
function makeXcodeCompilerLog(type, message, { fileName , lineNumber , column } = {}) {
// TODO: Figure out how to support multi-line logs.
const firstLine = message.split("\n")[0];
if (fileName && !(fileName == null ? void 0 : fileName.includes(":"))) {
return `${fileName}:${lineNumber || 0}:${column != null ? column + ":" : ""} ${type}: ${firstLine}`;
}
return `${type}: ${firstLine}`;
}
// TODO: Metro doesn't expose this info even though it knows it.
function getLineNumberForStringInFile(originModulePath, targetModuleName) {
let file;
try {
file = _fs().default.readFileSync(originModulePath, "utf8");
} catch (error) {
if (error.code === "ENOENT" || error.code === "EISDIR") {
// We're probably dealing with a virtualised file system where
// `this.originModulePath` doesn't actually exist on disk.
// We can't show a code frame, but there's no need to let this I/O
// error shadow the original module resolution error.
return null;
}
throw error;
}
const lines = file.split("\n");
let lineNumber = 0;
let column = -1;
for(let line = 0; line < lines.length; line++){
const columnLocation = lines[line].lastIndexOf(targetModuleName);
if (columnLocation >= 0) {
lineNumber = line;
column = columnLocation;
break;
}
}
return {
lineNumber,
column
};
}
//# sourceMappingURL=xcodeCompilerLogger.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,285 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "exportAppAsync", {
enumerable: true,
get: ()=>exportAppAsync
});
function _config() {
const data = require("@expo/config");
_config = function() {
return data;
};
return data;
}
function _assert() {
const data = /*#__PURE__*/ _interopRequireDefault(require("assert"));
_assert = function() {
return data;
};
return data;
}
function _chalk() {
const data = /*#__PURE__*/ _interopRequireDefault(require("chalk"));
_chalk = function() {
return data;
};
return data;
}
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
const _createMetadataJson = require("./createMetadataJson");
const _exportAssets = require("./exportAssets");
const _exportHermes = require("./exportHermes");
const _exportStaticAsync = require("./exportStaticAsync");
const _favicon = require("./favicon");
const _getPublicExpoManifest = require("./getPublicExpoManifest");
const _publicFolder = require("./publicFolder");
const _saveAssets = require("./saveAssets");
const _writeContents = require("./writeContents");
const _log = /*#__PURE__*/ _interopRequireWildcard(require("../log"));
const _webSupportProjectPrerequisite = require("../start/doctor/web/WebSupportProjectPrerequisite");
const _devServerManager = require("../start/server/DevServerManager");
const _metroBundlerDevServer = require("../start/server/metro/MetroBundlerDevServer");
const _router = require("../start/server/metro/router");
const _serializeHtml = require("../start/server/metro/serializeHtml");
const _manifestMiddleware = require("../start/server/middleware/ManifestMiddleware");
const _metroOptions = require("../start/server/middleware/metroOptions");
const _webTemplate = require("../start/server/webTemplate");
const _env = require("../utils/env");
const _nodeEnv = require("../utils/nodeEnv");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
async function exportAppAsync(projectRoot, { platforms , outputDir , clear , dev , dumpAssetmap , sourceMaps , minify , bytecode , maxWorkers }) {
var ref;
(0, _nodeEnv.setNodeEnv)(dev ? "development" : "production");
require("@expo/env").load(projectRoot);
const projectConfig = (0, _config().getConfig)(projectRoot);
const exp = await (0, _getPublicExpoManifest.getPublicExpoManifestAsync)(projectRoot, {
// Web doesn't require validation.
skipValidation: platforms.length === 1 && platforms[0] === "web"
});
if (platforms.includes("web")) {
await new _webSupportProjectPrerequisite.WebSupportProjectPrerequisite(projectRoot).assertAsync();
}
var ref1;
const useServerRendering = [
"static",
"server"
].includes((ref1 = (ref = exp.web) == null ? void 0 : ref.output) != null ? ref1 : "");
const baseUrl = (0, _metroOptions.getBaseUrlFromExpoConfig)(exp);
if (!bytecode && (platforms.includes("ios") || platforms.includes("android"))) {
_log.warn(`Bytecode makes the app startup faster, disabling bytecode is highly discouraged and should only be used for debugging purposes.`);
}
// Print out logs
if (baseUrl) {
_log.log();
_log.log(_chalk().default.gray`Using (experimental) base path: ${baseUrl}`);
// Warn if not using an absolute path.
if (!baseUrl.startsWith("/")) {
_log.log(_chalk().default.yellow` Base path does not start with a slash. Requests will not be absolute.`);
}
}
const mode = dev ? "development" : "production";
const publicPath = _path().default.resolve(projectRoot, _env.env.EXPO_PUBLIC_FOLDER);
const outputPath = _path().default.resolve(projectRoot, outputDir);
// Write the JS bundles to disk, and get the bundle file names (this could change with async chunk loading support).
const files = new Map();
const devServerManager = await _devServerManager.DevServerManager.startMetroAsync(projectRoot, {
minify,
mode,
port: 8081,
isExporting: true,
location: {},
resetDevServer: clear,
maxWorkers
});
const devServer = devServerManager.getDefaultDevServer();
(0, _assert().default)(devServer instanceof _metroBundlerDevServer.MetroBundlerDevServer);
const bundles = {};
const spaPlatforms = useServerRendering ? platforms.filter((platform)=>platform !== "web") : platforms;
try {
// NOTE(kitten): The public folder is currently always copied, regardless of targetDomain
// split. Hence, there's another separate `copyPublicFolderAsync` call below for `web`
await (0, _publicFolder.copyPublicFolderAsync)(publicPath, outputPath);
// Can be empty during web-only SSG.
if (spaPlatforms.length) {
await Promise.all(spaPlatforms.map(async (platform)=>{
var ref;
// Assert early so the user doesn't have to wait until bundling is complete to find out that
// Hermes won't be available.
const isHermes = (0, _exportHermes.isEnableHermesManaged)(exp, platform);
if (isHermes) {
await (0, _exportHermes.assertEngineMismatchAsync)(projectRoot, exp, platform);
}
// Run metro bundler and create the JS bundles/source maps.
const bundle = await devServer.legacySinglePageExportBundleAsync({
platform,
splitChunks: !_env.env.EXPO_NO_BUNDLE_SPLITTING && platform === "web",
mainModuleName: (0, _manifestMiddleware.getEntryWithServerRoot)(projectRoot, {
platform,
pkg: projectConfig.pkg
}),
mode: dev ? "development" : "production",
engine: isHermes ? "hermes" : undefined,
serializerIncludeMaps: sourceMaps,
bytecode: bytecode && isHermes,
reactCompiler: !!((ref = exp.experiments) == null ? void 0 : ref.reactCompiler)
});
bundles[platform] = bundle;
(0, _saveAssets.getFilesFromSerialAssets)(bundle.artifacts, {
includeSourceMaps: sourceMaps,
files
});
if (platform === "web") {
// TODO: Unify with exportStaticAsync
// TODO: Maybe move to the serializer.
let html = await (0, _serializeHtml.serializeHtmlWithAssets)({
isExporting: true,
resources: bundle.artifacts,
template: await (0, _webTemplate.createTemplateHtmlFromExpoConfigAsync)(projectRoot, {
scripts: [],
cssLinks: [],
exp: projectConfig.exp
}),
baseUrl
});
// Add the favicon assets to the HTML.
const modifyHtml = await (0, _favicon.getVirtualFaviconAssetsAsync)(projectRoot, {
outputDir,
baseUrl,
files,
exp: projectConfig.exp
});
if (modifyHtml) {
html = modifyHtml(html);
}
// Generate SPA-styled HTML file.
// If web exists, then write the template HTML file.
files.set("index.html", {
contents: html,
targetDomain: "client"
});
}
}));
// TODO: Use same asset system across platforms again.
const { assets , embeddedHashSet } = await (0, _exportAssets.exportAssetsAsync)(projectRoot, {
files,
exp,
outputDir: outputPath,
bundles,
baseUrl
});
if (dumpAssetmap) {
_log.log("Creating asset map");
files.set("assetmap.json", {
contents: JSON.stringify((0, _writeContents.createAssetMap)({
assets
}))
});
}
const fileNames = Object.fromEntries(Object.entries(bundles).map(([platform, bundle])=>[
platform,
bundle.artifacts.filter((asset)=>asset.type === "js").map((asset)=>asset.filename),
]));
// build source maps
if (sourceMaps) {
_log.log("Preparing additional debugging files");
// If we output source maps, then add a debug HTML file which the user can open in
// the web browser to inspect the output like web.
files.set("debug.html", {
contents: (0, _writeContents.createSourceMapDebugHtml)({
fileNames: Object.values(fileNames).flat()
})
});
}
// Generate a `metadata.json` for EAS Update.
const contents = (0, _createMetadataJson.createMetadataJson)({
bundles,
fileNames,
embeddedHashSet
});
files.set("metadata.json", {
contents: JSON.stringify(contents)
});
}
// Additional web-only steps...
if (platforms.includes("web") && useServerRendering) {
var ref2, ref3;
const exportServer = ((ref2 = exp.web) == null ? void 0 : ref2.output) === "server";
if (exportServer) {
// TODO: Remove when this is abstracted into the files map
await (0, _publicFolder.copyPublicFolderAsync)(publicPath, _path().default.resolve(outputPath, "client"));
}
await (0, _exportStaticAsync.exportFromServerAsync)(projectRoot, devServer, {
mode,
files,
clear: !!clear,
outputDir: outputPath,
minify,
baseUrl,
includeSourceMaps: sourceMaps,
routerRoot: (0, _router.getRouterDirectoryModuleIdWithManifest)(projectRoot, exp),
reactCompiler: !!((ref3 = exp.experiments) == null ? void 0 : ref3.reactCompiler),
exportServer,
maxWorkers,
isExporting: true,
exp: projectConfig.exp
});
}
} finally{
await devServerManager.stopAsync();
}
// Write all files at the end for unified logging.
await (0, _saveAssets.persistMetroFilesAsync)(files, outputPath);
}
//# sourceMappingURL=exportApp.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,214 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
assetPatternsToBeBundled: ()=>assetPatternsToBeBundled,
resolveAssetPatternsToBeBundled: ()=>resolveAssetPatternsToBeBundled,
exportAssetsAsync: ()=>exportAssetsAsync
});
function _fs() {
const data = /*#__PURE__*/ _interopRequireDefault(require("fs"));
_fs = function() {
return data;
};
return data;
}
function _minimatch() {
const data = /*#__PURE__*/ _interopRequireDefault(require("minimatch"));
_minimatch = function() {
return data;
};
return data;
}
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
const _persistMetroAssets = require("./persistMetroAssets");
const _log = /*#__PURE__*/ _interopRequireWildcard(require("../log"));
const _resolveAssets = require("../start/server/middleware/resolveAssets");
const _array = require("../utils/array");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const debug = require("debug")("expo:export:exportAssets");
function mapAssetHashToAssetString(asset, hash) {
return "asset_" + hash + ("type" in asset && asset.type ? "." + asset.type : "");
}
function assetPatternsToBeBundled(exp) {
var ref, ref1, ref2, ref3, ref4;
return (exp == null ? void 0 : (ref = exp.extra) == null ? void 0 : (ref1 = ref.updates) == null ? void 0 : (ref2 = ref1.assetPatternsToBeBundled) == null ? void 0 : ref2.length) ? exp == null ? void 0 : (ref3 = exp.extra) == null ? void 0 : (ref4 = ref3.updates) == null ? void 0 : ref4.assetPatternsToBeBundled : undefined;
}
/**
* Given an asset and a set of strings representing the assets to be bundled, returns true if
* the asset is part of the set to be bundled.
* @param asset Asset object
* @param bundledAssetsSet Set of strings
* @returns true if the asset should be bundled
*/ function assetShouldBeIncludedInExport(asset, bundledAssetsSet) {
if (!bundledAssetsSet) {
return true;
}
return asset.fileHashes.filter((hash)=>bundledAssetsSet.has(mapAssetHashToAssetString(asset, hash))).length > 0;
}
/**
* Computes a set of strings representing the assets to be bundled with an export, given an array of assets,
* and a set of patterns to match
* @param assets The asset array
* @param assetPatternsToBeBundled An array of strings with glob patterns to match
* @param projectRoot The project root
* @returns A set of asset strings
*/ function setOfAssetsToBeBundled(assets, assetPatternsToBeBundled, projectRoot) {
// Convert asset patterns to a list of asset strings that match them.
// Assets strings are formatted as `asset_<hash>.<type>` and represent
// the name that the file will have in the app bundle. The `asset_` prefix is
// needed because android doesn't support assets that start with numbers.
const fullPatterns = assetPatternsToBeBundled.map((p)=>_path().default.join(projectRoot, p));
logPatterns(fullPatterns);
const allBundledAssets = assets.map((asset)=>{
const shouldBundle = shouldBundleAsset(asset, fullPatterns);
if (shouldBundle) {
var ref;
debug(`${shouldBundle ? "Include" : "Exclude"} asset ${(ref = asset.files) == null ? void 0 : ref[0]}`);
return asset.fileHashes.map((hash)=>mapAssetHashToAssetString(asset, hash));
}
return [];
}).flat();
// The assets returned by the RN packager has duplicates so make sure we
// only bundle each once.
return new Set(allBundledAssets);
}
function resolveAssetPatternsToBeBundled(projectRoot, exp, assets) {
if (!assetPatternsToBeBundled(exp)) {
return undefined;
}
var ref;
const bundledAssets = setOfAssetsToBeBundled(assets, (ref = assetPatternsToBeBundled(exp)) != null ? ref : [
"**/*"
], projectRoot);
return bundledAssets;
}
function logPatterns(patterns) {
// Only log the patterns in debug mode, if they aren't already defined in the app.json, then all files will be targeted.
_log.log("\nProcessing asset bundle patterns:");
patterns.forEach((p)=>_log.log("- " + p));
}
function shouldBundleAsset(asset, patterns) {
var ref;
const file = (ref = asset.files) == null ? void 0 : ref[0];
return !!("__packager_asset" in asset && asset.__packager_asset && file && patterns.some((pattern)=>(0, _minimatch().default)(file, pattern)));
}
async function exportAssetsAsync(projectRoot, { exp , outputDir , bundles: { web , ...bundles } , baseUrl , files =new Map() }) {
var ref;
// NOTE: We use a different system for static web
if (web) {
// Save assets like a typical bundler, preserving the file paths on web.
// TODO: Update React Native Web to support loading files from asset hashes.
await (0, _persistMetroAssets.persistMetroAssetsAsync)(web.assets, {
files,
platform: "web",
outputDirectory: outputDir,
baseUrl
});
}
const assets = (0, _array.uniqBy)(Object.values(bundles).flatMap((bundle)=>bundle.assets), (asset)=>asset.hash);
let bundledAssetsSet = undefined;
let filteredAssets = assets;
const embeddedHashSet = new Set();
if ((ref = assets[0]) == null ? void 0 : ref.fileHashes) {
debug(`Assets = ${JSON.stringify(assets, null, 2)}`);
// Updates the manifest to reflect additional asset bundling + configs
// Get only asset strings for assets we will save
bundledAssetsSet = resolveAssetPatternsToBeBundled(projectRoot, exp, assets);
if (bundledAssetsSet) {
debug(`Bundled assets = ${JSON.stringify([
...bundledAssetsSet
], null, 2)}`);
// Filter asset objects to only ones that include assetPatternsToBeBundled matches
filteredAssets = assets.filter((asset)=>{
const shouldInclude = assetShouldBeIncludedInExport(asset, bundledAssetsSet);
if (!shouldInclude) {
embeddedHashSet.add(asset.hash);
}
return shouldInclude;
});
debug(`Filtered assets count = ${filteredAssets.length}`);
}
const hashes = new Set();
// Add assets to copy.
filteredAssets.forEach((asset)=>{
const assetId = "fileSystemLocation" in asset ? _path().default.relative(projectRoot, _path().default.join(asset.fileSystemLocation, asset.name)) + (asset.type ? "." + asset.type : "") : undefined;
asset.files.forEach((fp, index)=>{
const hash = asset.fileHashes[index];
if (hashes.has(hash)) return;
hashes.add(hash);
files.set(_path().default.join("assets", hash), {
originFilename: _path().default.relative(projectRoot, fp),
contents: _fs().default.readFileSync(fp),
assetId
});
});
});
}
// Add google services file if it exists
await (0, _resolveAssets.resolveGoogleServicesFile)(projectRoot, exp);
return {
exp,
assets,
embeddedHashSet,
files
};
}
//# sourceMappingURL=exportAssets.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,85 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "exportAsync", {
enumerable: true,
get: ()=>exportAsync
});
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
const _exportApp = require("./exportApp");
const _log = /*#__PURE__*/ _interopRequireWildcard(require("../log"));
const _attachAtlas = require("../start/server/metro/debugging/attachAtlas");
const _fileNotifier = require("../utils/FileNotifier");
const _dir = require("../utils/dir");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
async function exportAsync(projectRoot, options) {
// Ensure the output directory is created
const outputPath = _path().default.resolve(projectRoot, options.outputDir);
// Delete the output directory if it exists
await (0, _dir.removeAsync)(outputPath);
// Create the output directory
await (0, _dir.ensureDirectoryAsync)(outputPath);
// Export the app
await (0, _exportApp.exportAppAsync)(projectRoot, options);
// Stop any file watchers to prevent the CLI from hanging.
_fileNotifier.FileNotifier.stopAll();
// Wait until Atlas is ready, when enabled
// NOTE(cedric): this is a workaround, remove when `process.exit` is removed
await (0, _attachAtlas.waitUntilAtlasExportIsReadyAsync)(projectRoot);
// Final notes
_log.log(`App exported to: ${options.outputDir}`);
// Exit the process to stop any hanging processes from reading the app.config.js or server rendering.
process.exit(0);
}
//# sourceMappingURL=exportAsync.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/exportAsync.ts"],"sourcesContent":["import path from 'path';\n\nimport { exportAppAsync } from './exportApp';\nimport { Options } from './resolveOptions';\nimport * as Log from '../log';\nimport { waitUntilAtlasExportIsReadyAsync } from '../start/server/metro/debugging/attachAtlas';\nimport { FileNotifier } from '../utils/FileNotifier';\nimport { ensureDirectoryAsync, removeAsync } from '../utils/dir';\n\nexport async function exportAsync(projectRoot: string, options: Options) {\n // Ensure the output directory is created\n const outputPath = path.resolve(projectRoot, options.outputDir);\n // Delete the output directory if it exists\n await removeAsync(outputPath);\n // Create the output directory\n await ensureDirectoryAsync(outputPath);\n\n // Export the app\n await exportAppAsync(projectRoot, options);\n\n // Stop any file watchers to prevent the CLI from hanging.\n FileNotifier.stopAll();\n // Wait until Atlas is ready, when enabled\n // NOTE(cedric): this is a workaround, remove when `process.exit` is removed\n await waitUntilAtlasExportIsReadyAsync(projectRoot);\n\n // Final notes\n Log.log(`App exported to: ${options.outputDir}`);\n\n // Exit the process to stop any hanging processes from reading the app.config.js or server rendering.\n process.exit(0);\n}\n"],"names":["exportAsync","projectRoot","options","outputPath","path","resolve","outputDir","removeAsync","ensureDirectoryAsync","exportAppAsync","FileNotifier","stopAll","waitUntilAtlasExportIsReadyAsync","Log","log","process","exit"],"mappings":"AAAA;;;;+BASsBA,aAAW;;aAAXA,WAAW;;;8DAThB,MAAM;;;;;;2BAEQ,aAAa;2DAEvB,QAAQ;6BACoB,6CAA6C;8BACjE,uBAAuB;qBACF,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEzD,eAAeA,WAAW,CAACC,WAAmB,EAAEC,OAAgB,EAAE;IACvE,yCAAyC;IACzC,MAAMC,UAAU,GAAGC,KAAI,EAAA,QAAA,CAACC,OAAO,CAACJ,WAAW,EAAEC,OAAO,CAACI,SAAS,CAAC,AAAC;IAChE,2CAA2C;IAC3C,MAAMC,IAAAA,IAAW,YAAA,EAACJ,UAAU,CAAC,CAAC;IAC9B,8BAA8B;IAC9B,MAAMK,IAAAA,IAAoB,qBAAA,EAACL,UAAU,CAAC,CAAC;IAEvC,iBAAiB;IACjB,MAAMM,IAAAA,UAAc,eAAA,EAACR,WAAW,EAAEC,OAAO,CAAC,CAAC;IAE3C,0DAA0D;IAC1DQ,aAAY,aAAA,CAACC,OAAO,EAAE,CAAC;IACvB,0CAA0C;IAC1C,4EAA4E;IAC5E,MAAMC,IAAAA,YAAgC,iCAAA,EAACX,WAAW,CAAC,CAAC;IAEpD,cAAc;IACdY,IAAG,CAACC,GAAG,CAAC,CAAC,iBAAiB,EAAEZ,OAAO,CAACI,SAAS,CAAC,CAAC,CAAC,CAAC;IAEjD,qGAAqG;IACrGS,OAAO,CAACC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC"}

View File

@@ -0,0 +1,159 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
assertEngineMismatchAsync: ()=>assertEngineMismatchAsync,
isEnableHermesManaged: ()=>isEnableHermesManaged,
parseGradleProperties: ()=>parseGradleProperties,
maybeThrowFromInconsistentEngineAsync: ()=>maybeThrowFromInconsistentEngineAsync,
maybeInconsistentEngineAndroidAsync: ()=>maybeInconsistentEngineAndroidAsync,
maybeInconsistentEngineIosAsync: ()=>maybeInconsistentEngineIosAsync,
isHermesBytecodeBundleAsync: ()=>isHermesBytecodeBundleAsync,
getHermesBytecodeBundleVersionAsync: ()=>getHermesBytecodeBundleVersionAsync
});
function _config() {
const data = require("@expo/config");
_config = function() {
return data;
};
return data;
}
function _fsExtra() {
const data = /*#__PURE__*/ _interopRequireDefault(require("fs-extra"));
_fsExtra = function() {
return data;
};
return data;
}
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
async function assertEngineMismatchAsync(projectRoot, exp, platform) {
const isHermesManaged = isEnableHermesManaged(exp, platform);
const paths = (0, _config().getConfigFilePaths)(projectRoot);
var _dynamicConfigPath, ref;
const configFilePath = (ref = (_dynamicConfigPath = paths.dynamicConfigPath) != null ? _dynamicConfigPath : paths.staticConfigPath) != null ? ref : "app.json";
await maybeThrowFromInconsistentEngineAsync(projectRoot, configFilePath, platform, isHermesManaged);
}
function isEnableHermesManaged(expoConfig, platform) {
switch(platform){
case "android":
{
var ref;
var ref1;
return ((ref1 = (ref = expoConfig.android) == null ? void 0 : ref.jsEngine) != null ? ref1 : expoConfig.jsEngine) !== "jsc";
}
case "ios":
{
var ref2;
var ref3;
return ((ref3 = (ref2 = expoConfig.ios) == null ? void 0 : ref2.jsEngine) != null ? ref3 : expoConfig.jsEngine) !== "jsc";
}
default:
return false;
}
}
function parseGradleProperties(content) {
const result = {};
for (let line of content.split("\n")){
line = line.trim();
if (!line || line.startsWith("#")) {
continue;
}
const sepIndex = line.indexOf("=");
const key = line.substr(0, sepIndex);
const value = line.substr(sepIndex + 1);
result[key] = value;
}
return result;
}
async function maybeThrowFromInconsistentEngineAsync(projectRoot, configFilePath, platform, isHermesManaged) {
const configFileName = _path().default.basename(configFilePath);
if (platform === "android" && await maybeInconsistentEngineAndroidAsync(projectRoot, isHermesManaged)) {
throw new Error(`JavaScript engine configuration is inconsistent between ${configFileName} and Android native project.\n` + `In ${configFileName}: Hermes is ${isHermesManaged ? "enabled" : "not enabled"}\n` + `In Android native project: Hermes is ${isHermesManaged ? "not enabled" : "enabled"}\n` + `Please check the following files for inconsistencies:\n` + ` - ${configFilePath}\n` + ` - ${_path().default.join(projectRoot, "android", "gradle.properties")}\n` + ` - ${_path().default.join(projectRoot, "android", "app", "build.gradle")}\n` + "Learn more: https://expo.fyi/hermes-android-config");
}
if (platform === "ios" && await maybeInconsistentEngineIosAsync(projectRoot, isHermesManaged)) {
throw new Error(`JavaScript engine configuration is inconsistent between ${configFileName} and iOS native project.\n` + `In ${configFileName}: Hermes is ${isHermesManaged ? "enabled" : "not enabled"}\n` + `In iOS native project: Hermes is ${isHermesManaged ? "not enabled" : "enabled"}\n` + `Please check the following files for inconsistencies:\n` + ` - ${configFilePath}\n` + ` - ${_path().default.join(projectRoot, "ios", "Podfile")}\n` + ` - ${_path().default.join(projectRoot, "ios", "Podfile.properties.json")}\n` + "Learn more: https://expo.fyi/hermes-ios-config");
}
}
async function maybeInconsistentEngineAndroidAsync(projectRoot, isHermesManaged) {
// Trying best to check android native project if by chance to be consistent between app config
// Check gradle.properties from prebuild template
const gradlePropertiesPath = _path().default.join(projectRoot, "android", "gradle.properties");
if (_fsExtra().default.existsSync(gradlePropertiesPath)) {
const props = parseGradleProperties(await _fsExtra().default.readFile(gradlePropertiesPath, "utf8"));
const isHermesBare = props["hermesEnabled"] === "true";
if (isHermesManaged !== isHermesBare) {
return true;
}
}
return false;
}
async function maybeInconsistentEngineIosAsync(projectRoot, isHermesManaged) {
// Trying best to check ios native project if by chance to be consistent between app config
// Check ios/Podfile for ":hermes_enabled => true"
const podfilePath = _path().default.join(projectRoot, "ios", "Podfile");
if (_fsExtra().default.existsSync(podfilePath)) {
const content = await _fsExtra().default.readFile(podfilePath, "utf8");
const isPropsReference = content.search(/^\s*:hermes_enabled\s*=>\s*podfile_properties\['expo.jsEngine'\]\s*==\s*nil\s*\|\|\s*podfile_properties\['expo.jsEngine'\]\s*==\s*'hermes',?/m) >= 0;
const isHermesBare = content.search(/^\s*:hermes_enabled\s*=>\s*true,?\s+/m) >= 0;
if (!isPropsReference && isHermesManaged !== isHermesBare) {
return true;
}
}
// Check Podfile.properties.json from prebuild template
const podfilePropertiesPath = _path().default.join(projectRoot, "ios", "Podfile.properties.json");
if (_fsExtra().default.existsSync(podfilePropertiesPath)) {
const props = await parsePodfilePropertiesAsync(podfilePropertiesPath);
const isHermesBare1 = props["expo.jsEngine"] === "hermes";
if (isHermesManaged !== isHermesBare1) {
return true;
}
}
return false;
}
// https://github.com/facebook/hermes/blob/release-v0.5/include/hermes/BCGen/HBC/BytecodeFileFormat.h#L24-L25
const HERMES_MAGIC_HEADER = "c61fbc03c103191f";
async function isHermesBytecodeBundleAsync(file) {
const header = await readHermesHeaderAsync(file);
return header.slice(0, 8).toString("hex") === HERMES_MAGIC_HEADER;
}
async function getHermesBytecodeBundleVersionAsync(file) {
const header = await readHermesHeaderAsync(file);
if (header.slice(0, 8).toString("hex") !== HERMES_MAGIC_HEADER) {
throw new Error("Invalid hermes bundle file");
}
return header.readUInt32LE(8);
}
async function readHermesHeaderAsync(file) {
const fd = await _fsExtra().default.open(file, "r");
const buffer = Buffer.alloc(12);
await _fsExtra().default.read(fd, buffer, 0, 12, null);
await _fsExtra().default.close(fd);
return buffer;
}
async function parsePodfilePropertiesAsync(podfilePropertiesPath) {
try {
return JSON.parse(await _fsExtra().default.readFile(podfilePropertiesPath, "utf8"));
} catch {
return {};
}
}
//# sourceMappingURL=exportHermes.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,349 @@
/**
* Copyright © 2022 650 Industries.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getFilesToExportFromServerAsync: ()=>getFilesToExportFromServerAsync,
exportFromServerAsync: ()=>exportFromServerAsync,
getHtmlFiles: ()=>getHtmlFiles,
getPathVariations: ()=>getPathVariations
});
function _chalk() {
const data = /*#__PURE__*/ _interopRequireDefault(require("chalk"));
_chalk = function() {
return data;
};
return data;
}
function _matchers() {
const data = require("expo-router/build/matchers");
_matchers = function() {
return data;
};
return data;
}
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
function _resolveFrom() {
const data = /*#__PURE__*/ _interopRequireDefault(require("resolve-from"));
_resolveFrom = function() {
return data;
};
return data;
}
function _util() {
const data = require("util");
_util = function() {
return data;
};
return data;
}
const _favicon = require("./favicon");
const _persistMetroAssets = require("./persistMetroAssets");
const _saveAssets = require("./saveAssets");
const _log = require("../log");
const _metroErrorInterface = require("../start/server/metro/metroErrorInterface");
const _router = require("../start/server/metro/router");
const _serializeHtml = require("../start/server/metro/serializeHtml");
const _link = require("../utils/link");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const debug = require("debug")("expo:export:generateStaticRoutes");
/** Match `(page)` -> `page` */ function matchGroupName(name) {
var ref;
return (ref = name.match(/^\(([^/]+?)\)$/)) == null ? void 0 : ref[1];
}
async function getFilesToExportFromServerAsync(projectRoot, { manifest , renderAsync , // Servers can handle group routes automatically and therefore
// don't require the build-time generation of every possible group
// variation.
exportServer , // name : contents
files =new Map() }) {
await Promise.all(getHtmlFiles({
manifest,
includeGroupVariations: !exportServer
}).map(async ({ route , filePath , pathname })=>{
try {
const targetDomain = exportServer ? "server" : "client";
files.set(filePath, {
contents: "",
targetDomain
});
const data = await renderAsync({
route,
filePath,
pathname
});
files.set(filePath, {
contents: data,
routeId: pathname,
targetDomain
});
} catch (e) {
await (0, _metroErrorInterface.logMetroErrorAsync)({
error: e,
projectRoot
});
throw new Error("Failed to statically export route: " + pathname);
}
}));
return files;
}
function modifyRouteNodeInRuntimeManifest(manifest, callback) {
const iterateScreens = (screens)=>{
Object.values(screens).map((value)=>{
if (typeof value !== "string") {
if (value._route) callback(value._route);
iterateScreens(value.screens);
}
});
};
iterateScreens(manifest.screens);
}
// TODO: Do this earlier in the process.
function makeRuntimeEntryPointsAbsolute(manifest, appDir) {
modifyRouteNodeInRuntimeManifest(manifest, (route)=>{
if (Array.isArray(route.entryPoints)) {
route.entryPoints = route.entryPoints.map((entryPoint)=>{
if (entryPoint.startsWith(".")) {
return _path().default.resolve(appDir, entryPoint);
} else if (!_path().default.isAbsolute(entryPoint)) {
return (0, _resolveFrom().default)(appDir, entryPoint);
}
return entryPoint;
});
}
});
}
async function exportFromServerAsync(projectRoot, devServer, { outputDir , baseUrl , exportServer , includeSourceMaps , routerRoot , files =new Map() , exp }) {
_log.Log.log(`Static rendering is enabled. ` + (0, _link.learnMore)("https://docs.expo.dev/router/reference/static-rendering/"));
const platform = "web";
const isExporting = true;
const appDir = _path().default.join(projectRoot, routerRoot);
const injectFaviconTag = await (0, _favicon.getVirtualFaviconAssetsAsync)(projectRoot, {
outputDir,
baseUrl,
files,
exp
});
const [resources, { manifest , serverManifest , renderAsync }] = await Promise.all([
devServer.getStaticResourcesAsync({
includeSourceMaps
}),
devServer.getStaticRenderFunctionAsync(),
]);
makeRuntimeEntryPointsAbsolute(manifest, appDir);
debug("Routes:\n", (0, _util().inspect)(manifest, {
colors: true,
depth: null
}));
await getFilesToExportFromServerAsync(projectRoot, {
files,
manifest,
exportServer,
async renderAsync ({ pathname , route }) {
const template = await renderAsync(pathname);
let html = await (0, _serializeHtml.serializeHtmlWithAssets)({
isExporting,
resources: resources.artifacts,
template,
baseUrl,
route
});
if (injectFaviconTag) {
html = injectFaviconTag(html);
}
return html;
}
});
(0, _saveAssets.getFilesFromSerialAssets)(resources.artifacts, {
platform,
includeSourceMaps,
files
});
if (resources.assets) {
// TODO: Collect files without writing to disk.
// NOTE(kitten): Re. above, this is now using `files` except for iOS catalog output, which isn't used here
await (0, _persistMetroAssets.persistMetroAssetsAsync)(resources.assets, {
files,
platform,
outputDirectory: outputDir,
baseUrl
});
}
if (exportServer) {
const apiRoutes = await exportApiRoutesAsync({
outputDir,
server: devServer,
manifest: serverManifest,
// NOTE(kitten): For now, we always output source maps for API route exports
includeSourceMaps: true
});
// Add the api routes to the files to export.
for (const [route, contents] of apiRoutes){
files.set(route, contents);
}
} else {
warnPossibleInvalidExportType(appDir);
}
return files;
}
function getHtmlFiles({ manifest , includeGroupVariations }) {
const htmlFiles = new Set();
function traverseScreens(screens, route, baseUrl = "") {
for (const value of Object.values(screens)){
let leaf = null;
if (typeof value === "string") {
leaf = value;
} else if (Object.keys(value.screens).length === 0) {
leaf = value.path;
var __route;
route = (__route = value._route) != null ? __route : null;
}
if (leaf != null) {
let filePath = baseUrl + leaf;
if (leaf === "") {
filePath = baseUrl === "" ? "index" : baseUrl.endsWith("/") ? baseUrl + "index" : baseUrl.slice(0, -1);
} else if (// If the path is a collection of group segments leading to an index route, append `/index`.
(0, _matchers().stripGroupSegmentsFromPath)(filePath) === "") {
filePath += "/index";
}
// This should never happen, the type of `string | object` originally comes from React Navigation.
if (!route) {
throw new Error(`Internal error: Route not found for "${filePath}" while collecting static export paths.`);
}
if (includeGroupVariations) {
// TODO: Dedupe requests for alias routes.
addOptionalGroups(filePath, route);
} else {
htmlFiles.add({
filePath,
route
});
}
} else if (typeof value === "object" && (value == null ? void 0 : value.screens)) {
const newPath = baseUrl + value.path + "/";
var __route1;
traverseScreens(value.screens, (__route1 = value._route) != null ? __route1 : null, newPath);
}
}
}
function addOptionalGroups(path, route) {
const variations = getPathVariations(path);
for (const variation of variations){
htmlFiles.add({
filePath: variation,
route
});
}
}
traverseScreens(manifest.screens, null);
return uniqueBy(Array.from(htmlFiles), (value)=>value.filePath).map((value)=>{
const parts = value.filePath.split("/");
// Replace `:foo` with `[foo]` and `*foo` with `[...foo]`
const partsWithGroups = parts.map((part)=>{
if (part === "*not-found") {
return `+not-found`;
} else if (part.startsWith(":")) {
return `[${part.slice(1)}]`;
} else if (part.startsWith("*")) {
return `[...${part.slice(1)}]`;
}
return part;
});
const filePathLocation = partsWithGroups.join("/");
const filePath = filePathLocation + ".html";
return {
...value,
filePath,
pathname: filePathLocation.replace(/(\/?index)?$/, "")
};
});
}
function uniqueBy(array, key) {
const seen = new Set();
const result = [];
for (const value of array){
const id = key(value);
if (!seen.has(id)) {
seen.add(id);
result.push(value);
}
}
return result;
}
function getPathVariations(routePath) {
const variations = new Set();
const segments = routePath.split("/");
function generateVariations(segments, current = "") {
if (segments.length === 0) {
if (current) variations.add(current);
return;
}
const [head, ...rest] = segments;
if (matchGroupName(head)) {
const groups = head.slice(1, -1).split(",");
if (groups.length > 1) {
for (const group of groups){
// If there are multiple groups, recurse on each group.
generateVariations([
`(${group.trim()})`,
...rest
], current);
}
return;
} else {
// Start a fork where this group is included
generateVariations(rest, current ? `${current}/(${groups[0]})` : `(${groups[0]})`);
// This code will continue and add paths without this group included`
}
} else if (current) {
current = `${current}/${head}`;
} else {
current = head;
}
generateVariations(rest, current);
}
generateVariations(segments);
return Array.from(variations);
}
async function exportApiRoutesAsync({ includeSourceMaps , outputDir , server , ...props }) {
const { manifest , files } = await server.exportExpoRouterApiRoutesAsync({
outputDir: "_expo/functions",
prerenderManifest: props.manifest,
includeSourceMaps
});
_log.Log.log(_chalk().default.bold`Exporting ${files.size} API Routes.`);
files.set("_expo/routes.json", {
contents: JSON.stringify(manifest, null, 2),
targetDomain: "server"
});
return files;
}
function warnPossibleInvalidExportType(appDir) {
const apiRoutes = (0, _router.getApiRoutesForDirectory)(appDir);
if (apiRoutes.length) {
// TODO: Allow API Routes for native-only.
_log.Log.warn(_chalk().default.yellow`Skipping export for API routes because \`web.output\` is not "server". You may want to remove the routes: ${apiRoutes.map((v)=>_path().default.relative(appDir, v)).join(", ")}`);
}
}
//# sourceMappingURL=exportStaticAsync.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,133 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getUserDefinedFaviconFile: ()=>getUserDefinedFaviconFile,
getVirtualFaviconAssetsAsync: ()=>getVirtualFaviconAssetsAsync,
getFaviconFromExpoConfigAsync: ()=>getFaviconFromExpoConfigAsync
});
function _config() {
const data = require("@expo/config");
_config = function() {
return data;
};
return data;
}
function _imageUtils() {
const data = require("@expo/image-utils");
_imageUtils = function() {
return data;
};
return data;
}
function _fs() {
const data = /*#__PURE__*/ _interopRequireDefault(require("fs"));
_fs = function() {
return data;
};
return data;
}
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
const _publicFolder = require("./publicFolder");
const _log = require("../log");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const debug = require("debug")("expo:favicon");
function getUserDefinedFaviconFile(projectRoot) {
return (0, _publicFolder.getUserDefinedFile)(projectRoot, [
"./favicon.ico"
]);
}
async function getVirtualFaviconAssetsAsync(projectRoot, { baseUrl , outputDir , files , exp }) {
const existing = getUserDefinedFaviconFile(projectRoot);
if (existing) {
debug("Using user-defined favicon.ico file.");
return null;
}
const data = await getFaviconFromExpoConfigAsync(projectRoot, {
exp
});
if (!data) {
return null;
}
await Promise.all([
data
].map(async (asset)=>{
const assetPath = _path().default.join(outputDir, asset.path);
if (files) {
debug("Storing asset for persisting: " + assetPath);
files == null ? void 0 : files.set(asset.path, {
contents: asset.source,
targetDomain: "client"
});
} else {
debug("Writing asset to disk: " + assetPath);
await _fs().default.promises.writeFile(assetPath, asset.source);
}
}));
function injectFaviconTag(html) {
if (!html.includes("</head>")) {
return html;
}
return html.replace("</head>", `<link rel="shortcut icon" href="${baseUrl}/favicon.ico" /></head>`);
}
return injectFaviconTag;
}
async function getFaviconFromExpoConfigAsync(projectRoot, { force =false , exp =(0, _config().getConfig)(projectRoot).exp } = {}) {
var ref;
var ref1;
const src = (ref1 = (ref = exp.web) == null ? void 0 : ref.favicon) != null ? ref1 : null;
if (!src) {
return null;
}
const dims = [
16,
32,
48
];
const cacheType = "favicon";
const size = dims[dims.length - 1];
try {
const { source } = await (0, _imageUtils().generateImageAsync)({
projectRoot,
cacheType
}, {
resizeMode: "contain",
src,
backgroundColor: "transparent",
width: size,
height: size,
name: `favicon-${size}.png`
});
const faviconBuffer = await (0, _imageUtils().generateFaviconAsync)(source, dims);
return {
source: faviconBuffer,
path: "favicon.ico"
};
} catch (error) {
// Check for ENOENT
if (!force && error.code === "ENOENT") {
_log.Log.warn(`Favicon source file in Expo config (web.favicon) does not exist: ${src}`);
return null;
}
throw error;
}
}
//# sourceMappingURL=favicon.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getPublicExpoManifestAsync", {
enumerable: true,
get: ()=>getPublicExpoManifestAsync
});
function _config() {
const data = require("@expo/config");
_config = function() {
return data;
};
return data;
}
const _getResolvedLocales = require("./getResolvedLocales");
const _env = require("../utils/env");
const _errors = require("../utils/errors");
async function getPublicExpoManifestAsync(projectRoot, { skipValidation } = {}) {
// Read the config in public mode which strips the `hooks`.
const { exp } = (0, _config().getConfig)(projectRoot, {
isPublicConfig: true,
// This shouldn't be needed since the CLI is vendored in `expo`.
skipSDKVersionRequirement: true
});
// Only allow projects to be published with UNVERSIONED if a correct token is set in env
if (!skipValidation && exp.sdkVersion === "UNVERSIONED" && !_env.env.EXPO_SKIP_MANIFEST_VALIDATION_TOKEN) {
throw new _errors.CommandError("INVALID_OPTIONS", "Cannot publish with sdkVersion UNVERSIONED.");
}
return {
...exp,
locales: await (0, _getResolvedLocales.getResolvedLocalesAsync)(projectRoot, exp),
sdkVersion: exp.sdkVersion
};
}
//# sourceMappingURL=getPublicExpoManifest.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/getPublicExpoManifest.ts"],"sourcesContent":["import { ExpoConfig, getConfig } from '@expo/config';\n\nimport { LocaleMap, getResolvedLocalesAsync } from './getResolvedLocales';\nimport { env } from '../utils/env';\nimport { CommandError } from '../utils/errors';\n\n/** Get the public Expo manifest from the local project config. */\nexport async function getPublicExpoManifestAsync(\n projectRoot: string,\n { skipValidation }: { skipValidation?: boolean } = {}\n): Promise<ExpoConfig & { locales: LocaleMap; sdkVersion: string }> {\n // Read the config in public mode which strips the `hooks`.\n const { exp } = getConfig(projectRoot, {\n isPublicConfig: true,\n // This shouldn't be needed since the CLI is vendored in `expo`.\n skipSDKVersionRequirement: true,\n });\n\n // Only allow projects to be published with UNVERSIONED if a correct token is set in env\n if (\n !skipValidation &&\n exp.sdkVersion === 'UNVERSIONED' &&\n !env.EXPO_SKIP_MANIFEST_VALIDATION_TOKEN\n ) {\n throw new CommandError('INVALID_OPTIONS', 'Cannot publish with sdkVersion UNVERSIONED.');\n }\n\n return {\n ...exp,\n locales: await getResolvedLocalesAsync(projectRoot, exp),\n sdkVersion: exp.sdkVersion!,\n };\n}\n"],"names":["getPublicExpoManifestAsync","projectRoot","skipValidation","exp","getConfig","isPublicConfig","skipSDKVersionRequirement","sdkVersion","env","EXPO_SKIP_MANIFEST_VALIDATION_TOKEN","CommandError","locales","getResolvedLocalesAsync"],"mappings":"AAAA;;;;+BAOsBA,4BAA0B;;aAA1BA,0BAA0B;;;yBAPV,cAAc;;;;;;oCAED,sBAAsB;qBACrD,cAAc;wBACL,iBAAiB;AAGvC,eAAeA,0BAA0B,CAC9CC,WAAmB,EACnB,EAAEC,cAAc,CAAA,EAAgC,GAAG,EAAE,EACa;IAClE,2DAA2D;IAC3D,MAAM,EAAEC,GAAG,CAAA,EAAE,GAAGC,IAAAA,OAAS,EAAA,UAAA,EAACH,WAAW,EAAE;QACrCI,cAAc,EAAE,IAAI;QACpB,gEAAgE;QAChEC,yBAAyB,EAAE,IAAI;KAChC,CAAC,AAAC;IAEH,wFAAwF;IACxF,IACE,CAACJ,cAAc,IACfC,GAAG,CAACI,UAAU,KAAK,aAAa,IAChC,CAACC,IAAG,IAAA,CAACC,mCAAmC,EACxC;QACA,MAAM,IAAIC,OAAY,aAAA,CAAC,iBAAiB,EAAE,6CAA6C,CAAC,CAAC;IAC3F,CAAC;IAED,OAAO;QACL,GAAGP,GAAG;QACNQ,OAAO,EAAE,MAAMC,IAAAA,mBAAuB,wBAAA,EAACX,WAAW,EAAEE,GAAG,CAAC;QACxDI,UAAU,EAAEJ,GAAG,CAACI,UAAU;KAC3B,CAAC;AACJ,CAAC"}

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getResolvedLocalesAsync", {
enumerable: true,
get: ()=>getResolvedLocalesAsync
});
function _jsonFile() {
const data = /*#__PURE__*/ _interopRequireDefault(require("@expo/json-file"));
_jsonFile = function() {
return data;
};
return data;
}
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
const _errors = require("../utils/errors");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
async function getResolvedLocalesAsync(projectRoot, exp) {
if (!exp.locales) {
return {};
}
const locales = {};
for (const [lang, localeJsonPath] of Object.entries(exp.locales)){
if (typeof localeJsonPath === "string") {
try {
locales[lang] = await _jsonFile().default.readAsync(_path().default.join(projectRoot, localeJsonPath));
} catch (error) {
throw new _errors.CommandError("EXPO_CONFIG", JSON.stringify(error));
}
} else {
// In the off chance that someone defined the locales json in the config, pass it directly to the object.
// We do this to make the types more elegant.
locales[lang] = localeJsonPath;
}
}
return locales;
}
//# sourceMappingURL=getResolvedLocales.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/getResolvedLocales.ts"],"sourcesContent":["import { ExpoConfig } from '@expo/config';\nimport JsonFile, { JSONObject } from '@expo/json-file';\nimport path from 'path';\n\nimport { CommandError } from '../utils/errors';\n\nexport type LocaleMap = Record<string, JSONObject>;\n\n// Similar to how we resolve locales in `@expo/config-plugins`\nexport async function getResolvedLocalesAsync(\n projectRoot: string,\n exp: Pick<ExpoConfig, 'locales'>\n): Promise<LocaleMap> {\n if (!exp.locales) {\n return {};\n }\n\n const locales: LocaleMap = {};\n for (const [lang, localeJsonPath] of Object.entries(exp.locales)) {\n if (typeof localeJsonPath === 'string') {\n try {\n locales[lang] = await JsonFile.readAsync(path.join(projectRoot, localeJsonPath));\n } catch (error: any) {\n throw new CommandError('EXPO_CONFIG', JSON.stringify(error));\n }\n } else {\n // In the off chance that someone defined the locales json in the config, pass it directly to the object.\n // We do this to make the types more elegant.\n locales[lang] = localeJsonPath;\n }\n }\n return locales;\n}\n"],"names":["getResolvedLocalesAsync","projectRoot","exp","locales","lang","localeJsonPath","Object","entries","JsonFile","readAsync","path","join","error","CommandError","JSON","stringify"],"mappings":"AAAA;;;;+BASsBA,yBAAuB;;aAAvBA,uBAAuB;;;8DARR,iBAAiB;;;;;;;8DACrC,MAAM;;;;;;wBAEM,iBAAiB;;;;;;AAKvC,eAAeA,uBAAuB,CAC3CC,WAAmB,EACnBC,GAAgC,EACZ;IACpB,IAAI,CAACA,GAAG,CAACC,OAAO,EAAE;QAChB,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAMA,OAAO,GAAc,EAAE,AAAC;IAC9B,KAAK,MAAM,CAACC,IAAI,EAAEC,cAAc,CAAC,IAAIC,MAAM,CAACC,OAAO,CAACL,GAAG,CAACC,OAAO,CAAC,CAAE;QAChE,IAAI,OAAOE,cAAc,KAAK,QAAQ,EAAE;YACtC,IAAI;gBACFF,OAAO,CAACC,IAAI,CAAC,GAAG,MAAMI,SAAQ,EAAA,QAAA,CAACC,SAAS,CAACC,KAAI,EAAA,QAAA,CAACC,IAAI,CAACV,WAAW,EAAEI,cAAc,CAAC,CAAC,CAAC;YACnF,EAAE,OAAOO,KAAK,EAAO;gBACnB,MAAM,IAAIC,OAAY,aAAA,CAAC,aAAa,EAAEC,IAAI,CAACC,SAAS,CAACH,KAAK,CAAC,CAAC,CAAC;YAC/D,CAAC;QACH,OAAO;YACL,yGAAyG;YACzG,6CAA6C;YAC7CT,OAAO,CAACC,IAAI,CAAC,GAAGC,cAAc,CAAC;QACjC,CAAC;IACH,CAAC;IACD,OAAOF,OAAO,CAAC;AACjB,CAAC"}

View File

@@ -0,0 +1,29 @@
// <link rel="preload" href="/_expo/static/css/xxxxxx.css" as="style">
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
appendLinkToHtml: ()=>appendLinkToHtml,
appendScriptsToHtml: ()=>appendScriptsToHtml
});
function appendLinkToHtml(html, links) {
return html.replace("</head>", links.map((link)=>{
let linkTag = `<link rel="${link.rel}"`;
if (link.href) linkTag += ` href="${link.href}"`;
if (link.as) linkTag += ` as="${link.as}"`;
linkTag += ">";
return linkTag;
}).join("") + "</head>");
}
function appendScriptsToHtml(html, scripts) {
return html.replace("</body>", scripts.map((script)=>`<script src="${script}" defer></script>`).join("") + "</body>");
}
//# sourceMappingURL=html.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/html.ts"],"sourcesContent":["// <link rel=\"preload\" href=\"/_expo/static/css/xxxxxx.css\" as=\"style\">\nexport function appendLinkToHtml(\n html: string,\n links: { rel: string; href: string; as?: string }[]\n) {\n return html.replace(\n '</head>',\n links\n .map((link) => {\n let linkTag = `<link rel=\"${link.rel}\"`;\n\n if (link.href) linkTag += ` href=\"${link.href}\"`;\n if (link.as) linkTag += ` as=\"${link.as}\"`;\n\n linkTag += '>';\n\n return linkTag;\n })\n .join('') + '</head>'\n );\n}\n\nexport function appendScriptsToHtml(html: string, scripts: string[]) {\n return html.replace(\n '</body>',\n scripts.map((script) => `<script src=\"${script}\" defer></script>`).join('') + '</body>'\n );\n}\n"],"names":["appendLinkToHtml","appendScriptsToHtml","html","links","replace","map","link","linkTag","rel","href","as","join","scripts","script"],"mappings":"AAAA,sEAAsE;AACtE;;;;;;;;;;;IAAgBA,gBAAgB,MAAhBA,gBAAgB;IAqBhBC,mBAAmB,MAAnBA,mBAAmB;;AArB5B,SAASD,gBAAgB,CAC9BE,IAAY,EACZC,KAAmD,EACnD;IACA,OAAOD,IAAI,CAACE,OAAO,CACjB,SAAS,EACTD,KAAK,CACFE,GAAG,CAAC,CAACC,IAAI,GAAK;QACb,IAAIC,OAAO,GAAG,CAAC,WAAW,EAAED,IAAI,CAACE,GAAG,CAAC,CAAC,CAAC,AAAC;QAExC,IAAIF,IAAI,CAACG,IAAI,EAAEF,OAAO,IAAI,CAAC,OAAO,EAAED,IAAI,CAACG,IAAI,CAAC,CAAC,CAAC,CAAC;QACjD,IAAIH,IAAI,CAACI,EAAE,EAAEH,OAAO,IAAI,CAAC,KAAK,EAAED,IAAI,CAACI,EAAE,CAAC,CAAC,CAAC,CAAC;QAE3CH,OAAO,IAAI,GAAG,CAAC;QAEf,OAAOA,OAAO,CAAC;IACjB,CAAC,CAAC,CACDI,IAAI,CAAC,EAAE,CAAC,GAAG,SAAS,CACxB,CAAC;AACJ,CAAC;AAEM,SAASV,mBAAmB,CAACC,IAAY,EAAEU,OAAiB,EAAE;IACnE,OAAOV,IAAI,CAACE,OAAO,CACjB,SAAS,EACTQ,OAAO,CAACP,GAAG,CAAC,CAACQ,MAAM,GAAK,CAAC,aAAa,EAAEA,MAAM,CAAC,iBAAiB,CAAC,CAAC,CAACF,IAAI,CAAC,EAAE,CAAC,GAAG,SAAS,CACxF,CAAC;AACJ,CAAC"}

View File

@@ -0,0 +1,115 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "expoExport", {
enumerable: true,
get: ()=>expoExport
});
function _chalk() {
const data = /*#__PURE__*/ _interopRequireDefault(require("chalk"));
_chalk = function() {
return data;
};
return data;
}
const _args = require("../utils/args");
const _errors = require("../utils/errors");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const expoExport = async (argv)=>{
const args = (0, _args.assertArgs)({
// Types
"--help": Boolean,
"--clear": Boolean,
"--dump-assetmap": Boolean,
"--dev": Boolean,
"--source-maps": Boolean,
"--max-workers": Number,
"--output-dir": String,
"--platform": [
String
],
"--no-minify": Boolean,
"--no-bytecode": Boolean,
// Hack: This is added because EAS CLI always includes the flag.
// If supplied, we'll do nothing with the value, but at least the process won't crash.
// Note that we also don't show this value in the `--help` prompt since we don't want people to use it.
"--experimental-bundle": Boolean,
// Aliases
"-h": "--help",
"-s": "--source-maps",
// '-d': '--dump-assetmap',
"-c": "--clear",
"-p": "--platform",
// Interop with Metro docs and RedBox errors.
"--reset-cache": "--clear",
// Deprecated
"--dump-sourcemap": "--source-maps"
}, argv);
if (args["--help"]) {
(0, _args.printHelp)(`Export the static files of the app for hosting it on a web server`, (0, _chalk().default)`npx expo export {dim <dir>}`, [
(0, _chalk().default)`<dir> Directory of the Expo project. {dim Default: Current working directory}`,
(0, _chalk().default)`--output-dir <dir> The directory to export the static files to. {dim Default: dist}`,
`--dev Configure static files for developing locally using a non-https server`,
`--no-minify Prevent minifying source`,
`--no-bytecode Prevent generating Hermes bytecode`,
`--max-workers <number> Maximum number of tasks to allow the bundler to spawn`,
`--dump-assetmap Emit an asset map for further processing`,
(0, _chalk().default)`-p, --platform <platform> Options: android, ios, web, all. {dim Default: all}`,
`-s, --source-maps Emit JavaScript source maps`,
`-c, --clear Clear the bundler cache`,
`-h, --help Usage info`,
].join("\n"));
}
const projectRoot = (0, _args.getProjectRoot)(args);
const { resolveOptionsAsync } = await Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("./resolveOptions.js")));
const options = await resolveOptionsAsync(projectRoot, args).catch(_errors.logCmdError);
const { exportAsync } = await Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(require("./exportAsync.js")));
return exportAsync(projectRoot, options).catch(_errors.logCmdError);
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/export/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport chalk from 'chalk';\n\nimport { Command } from '../../bin/cli';\nimport { assertArgs, getProjectRoot, printHelp } from '../utils/args';\nimport { logCmdError } from '../utils/errors';\n\nexport const expoExport: Command = async (argv) => {\n const args = assertArgs(\n {\n // Types\n '--help': Boolean,\n '--clear': Boolean,\n '--dump-assetmap': Boolean,\n '--dev': Boolean,\n '--source-maps': Boolean,\n '--max-workers': Number,\n '--output-dir': String,\n '--platform': [String],\n '--no-minify': Boolean,\n '--no-bytecode': Boolean,\n\n // Hack: This is added because EAS CLI always includes the flag.\n // If supplied, we'll do nothing with the value, but at least the process won't crash.\n // Note that we also don't show this value in the `--help` prompt since we don't want people to use it.\n '--experimental-bundle': Boolean,\n\n // Aliases\n '-h': '--help',\n '-s': '--source-maps',\n // '-d': '--dump-assetmap',\n '-c': '--clear',\n '-p': '--platform',\n // Interop with Metro docs and RedBox errors.\n '--reset-cache': '--clear',\n\n // Deprecated\n '--dump-sourcemap': '--source-maps',\n },\n argv\n );\n\n if (args['--help']) {\n printHelp(\n `Export the static files of the app for hosting it on a web server`,\n chalk`npx expo export {dim <dir>}`,\n [\n chalk`<dir> Directory of the Expo project. {dim Default: Current working directory}`,\n chalk`--output-dir <dir> The directory to export the static files to. {dim Default: dist}`,\n `--dev Configure static files for developing locally using a non-https server`,\n `--no-minify Prevent minifying source`,\n `--no-bytecode Prevent generating Hermes bytecode`,\n `--max-workers <number> Maximum number of tasks to allow the bundler to spawn`,\n `--dump-assetmap Emit an asset map for further processing`,\n chalk`-p, --platform <platform> Options: android, ios, web, all. {dim Default: all}`,\n `-s, --source-maps Emit JavaScript source maps`,\n `-c, --clear Clear the bundler cache`,\n `-h, --help Usage info`,\n ].join('\\n')\n );\n }\n\n const projectRoot = getProjectRoot(args);\n const { resolveOptionsAsync } = await import('./resolveOptions.js');\n const options = await resolveOptionsAsync(projectRoot, args).catch(logCmdError);\n\n const { exportAsync } = await import('./exportAsync.js');\n return exportAsync(projectRoot, options).catch(logCmdError);\n};\n"],"names":["expoExport","argv","args","assertArgs","Boolean","Number","String","printHelp","chalk","join","projectRoot","getProjectRoot","resolveOptionsAsync","options","catch","logCmdError","exportAsync"],"mappings":"AAAA;;;;;+BAOaA,YAAU;;aAAVA,UAAU;;;8DANL,OAAO;;;;;;sBAG6B,eAAe;wBACzC,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEtC,MAAMA,UAAU,GAAY,OAAOC,IAAI,GAAK;IACjD,MAAMC,IAAI,GAAGC,IAAAA,KAAU,WAAA,EACrB;QACE,QAAQ;QACR,QAAQ,EAAEC,OAAO;QACjB,SAAS,EAAEA,OAAO;QAClB,iBAAiB,EAAEA,OAAO;QAC1B,OAAO,EAAEA,OAAO;QAChB,eAAe,EAAEA,OAAO;QACxB,eAAe,EAAEC,MAAM;QACvB,cAAc,EAAEC,MAAM;QACtB,YAAY,EAAE;YAACA,MAAM;SAAC;QACtB,aAAa,EAAEF,OAAO;QACtB,eAAe,EAAEA,OAAO;QAExB,gEAAgE;QAChE,sFAAsF;QACtF,uGAAuG;QACvG,uBAAuB,EAAEA,OAAO;QAEhC,UAAU;QACV,IAAI,EAAE,QAAQ;QACd,IAAI,EAAE,eAAe;QACrB,2BAA2B;QAC3B,IAAI,EAAE,SAAS;QACf,IAAI,EAAE,YAAY;QAClB,6CAA6C;QAC7C,eAAe,EAAE,SAAS;QAE1B,aAAa;QACb,kBAAkB,EAAE,eAAe;KACpC,EACDH,IAAI,CACL,AAAC;IAEF,IAAIC,IAAI,CAAC,QAAQ,CAAC,EAAE;QAClBK,IAAAA,KAAS,UAAA,EACP,CAAC,iEAAiE,CAAC,EACnEC,IAAAA,MAAK,EAAA,QAAA,CAAA,CAAC,2BAA2B,CAAC,EAClC;YACEA,IAAAA,MAAK,EAAA,QAAA,CAAA,CAAC,kGAAkG,CAAC;YACzGA,IAAAA,MAAK,EAAA,QAAA,CAAA,CAAC,2FAA2F,CAAC;YAClG,CAAC,iGAAiG,CAAC;YACnG,CAAC,mDAAmD,CAAC;YACrD,CAAC,6DAA6D,CAAC;YAC/D,CAAC,gFAAgF,CAAC;YAClF,CAAC,mEAAmE,CAAC;YACrEA,IAAAA,MAAK,EAAA,QAAA,CAAA,CAAC,8EAA8E,CAAC;YACrF,CAAC,sDAAsD,CAAC;YACxD,CAAC,kDAAkD,CAAC;YACpD,CAAC,qCAAqC,CAAC;SACxC,CAACC,IAAI,CAAC,IAAI,CAAC,CACb,CAAC;IACJ,CAAC;IAED,MAAMC,WAAW,GAAGC,IAAAA,KAAc,eAAA,EAACT,IAAI,CAAC,AAAC;IACzC,MAAM,EAAEU,mBAAmB,CAAA,EAAE,GAAG,MAAM,iEAAA,OAAM,CAAC,qBAAqB,GAAC,AAAC;IACpE,MAAMC,OAAO,GAAG,MAAMD,mBAAmB,CAACF,WAAW,EAAER,IAAI,CAAC,CAACY,KAAK,CAACC,OAAW,YAAA,CAAC,AAAC;IAEhF,MAAM,EAAEC,WAAW,CAAA,EAAE,GAAG,MAAM,iEAAA,OAAM,CAAC,kBAAkB,GAAC,AAAC;IACzD,OAAOA,WAAW,CAACN,WAAW,EAAEG,OAAO,CAAC,CAACC,KAAK,CAACC,OAAW,YAAA,CAAC,CAAC;AAC9D,CAAC,AAAC"}

View File

@@ -0,0 +1,124 @@
/**
* Copyright © 2023 650 Industries.
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* Based on the community asset persisting for Metro but with base path and web support:
* https://github.com/facebook/react-native/blob/d6e0bc714ad4d215ede4949d3c4f44af6dea5dd3/packages/community-cli-plugin/src/commands/bundle/saveAssets.js#L1
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getAssetLocalPath: ()=>getAssetLocalPath,
stripAssetPrefix: ()=>stripAssetPrefix,
drawableFileTypes: ()=>drawableFileTypes
});
function _path() {
const data = /*#__PURE__*/ _interopRequireDefault(require("path"));
_path = function() {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function getAssetLocalPath(asset, { baseUrl , scale , platform }) {
if (platform === "android") {
return getAssetLocalPathAndroid(asset, {
baseUrl,
scale
});
}
return getAssetLocalPathDefault(asset, {
baseUrl,
scale
});
}
function getAssetLocalPathAndroid(asset, { baseUrl , scale }) {
const androidFolder = getAndroidResourceFolderName(asset, scale);
const fileName = getResourceIdentifier(asset);
return _path().default.join(androidFolder, `${fileName}.${asset.type}`);
}
function getAssetLocalPathDefault(asset, { baseUrl , scale }) {
const suffix = scale === 1 ? "" : `@${scale}x`;
const fileName = `${asset.name}${suffix}.${asset.type}`;
const adjustedHttpServerLocation = stripAssetPrefix(asset.httpServerLocation, baseUrl);
return _path().default.join(// Assets can have relative paths outside of the project root.
// Replace `../` with `_` to make sure they don't end up outside of
// the expected assets directory.
adjustedHttpServerLocation.replace(/^\/+/g, "").replace(/\.\.\//g, "_"), fileName);
}
function stripAssetPrefix(path, baseUrl) {
path = path.replace(/\/assets\?export_path=(.*)/, "$1");
// TODO: Windows?
if (baseUrl) {
return path.replace(/^\/+/g, "").replace(new RegExp(`^${baseUrl.replace(/^\/+/g, "").replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d")}`, "g"), "");
}
return path;
}
/**
* FIXME: using number to represent discrete scale numbers is fragile in essence because of
* floating point numbers imprecision.
*/ function getAndroidAssetSuffix(scale) {
switch(scale){
case 0.75:
return "ldpi";
case 1:
return "mdpi";
case 1.5:
return "hdpi";
case 2:
return "xhdpi";
case 3:
return "xxhdpi";
case 4:
return "xxxhdpi";
default:
return null;
}
}
const drawableFileTypes = new Set([
"gif",
"jpeg",
"jpg",
"png",
"webp",
"xml"
]);
function getAndroidResourceFolderName(asset, scale) {
if (!drawableFileTypes.has(asset.type)) {
return "raw";
}
const suffix = getAndroidAssetSuffix(scale);
if (!suffix) {
throw new Error(`Asset "${JSON.stringify(asset)}" does not use a supported Android resolution suffix`);
}
return `drawable-${suffix}`;
}
function getResourceIdentifier(asset) {
const folderPath = getBaseUrl(asset);
return `${folderPath}/${asset.name}`.toLowerCase().replace(/\//g, "_") // Encode folder structure in file name
.replace(/([^a-z0-9_])/g, "") // Remove illegal chars
.replace(/^assets_/, ""); // Remove "assets_" prefix
}
function getBaseUrl(asset) {
let baseUrl = asset.httpServerLocation;
if (baseUrl[0] === "/") {
baseUrl = baseUrl.substring(1);
}
return baseUrl;
}
//# sourceMappingURL=metroAssetLocalPath.js.map

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More