mirror of
https://github.com/expo/eas-cli.git
synced 2026-11-15 13:08:11 -10:00
Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e912ca078 | ||
|
|
f366dbec69 | ||
|
|
5ce625e9f2 | ||
|
|
7005300cff | ||
|
|
394576368a | ||
|
|
f80e34cffe | ||
|
|
59ad2c2ca0 | ||
|
|
4e95a29797 | ||
|
|
66d8e3d6b8 | ||
|
|
5e4a88094f | ||
|
|
7a4c81f4e3 | ||
|
|
c9cdfd1eb5 | ||
|
|
8115dc8766 | ||
|
|
113467c91d | ||
|
|
be967f4b9a | ||
|
|
660303b0c3 | ||
|
|
5514289648 | ||
|
|
7924e33e96 | ||
|
|
e699a06c07 | ||
|
|
ce819c1a14 | ||
|
|
92ad6b5ba3 | ||
|
|
d63d51f548 | ||
|
|
bfb12f0317 | ||
|
|
b162162007 | ||
|
|
6ed7e14a69 | ||
|
|
37910b17e1 | ||
|
|
0d3c56f4d6 | ||
|
|
bc8e60d385 | ||
|
|
99b8d67d3f |
No files matched your search
@@ -0,0 +1,11 @@
|
||||
# THIS IS AUTOGENERATED. DO NOT EDIT MANUALLY
|
||||
version = 1
|
||||
name = "eas-cli"
|
||||
|
||||
[setup]
|
||||
script = '''
|
||||
mise trust
|
||||
mise install
|
||||
yarn
|
||||
yarn typecheck
|
||||
'''
|
||||
@@ -16,6 +16,7 @@
|
||||
"packages/eas-cli/README.md",
|
||||
"packages/eas-cli/schema/**",
|
||||
"packages/eas-cli/graphql.schema.json",
|
||||
"packages/eas-cli/src/graphql/generated.ts",
|
||||
"packages/build-tools/schema.graphql"
|
||||
]
|
||||
}
|
||||
@@ -3,3 +3,4 @@
|
||||
When working with this repository follow instructions from CLAUDE.md.
|
||||
|
||||
- [./CLAUDE.md](./CLAUDE.md)
|
||||
- Before committing, run the formatter on modified files.
|
||||
+18
-2
@@ -8,13 +8,27 @@ This is the log of notable changes to EAS CLI and related packages.
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
- Auto-detect non-interactive mode in CI and non-TTY environments. ([#3486](https://github.com/expo/eas-cli/pull/3486) by [@EvanBacon](https://github.com/EvanBacon))
|
||||
- Add `skip-build-if-not-found` flag to `eas build:dev`. ([#3495](https://github.com/expo/eas-cli/pull/3495) by [@mmichels-brex](https://github.com/mmichels-brex))
|
||||
- [eas-cli] Add screenshots and previews support to `metadata:push` and `metadata:pull`. ([#3301](https://github.com/expo/eas-cli/pull/3301) by [@EvanBacon](https://github.com/EvanBacon))
|
||||
- [eas-cli] Add `--non-interactive` flag to `metadata:push` and `metadata:pull` commands with ASC API Key auth support. ([#3548](https://github.com/expo/eas-cli/pull/3548) by [@EvanBacon](https://github.com/EvanBacon))
|
||||
|
||||
### 🐛 Bug fixes
|
||||
|
||||
- [eas-cli] Fix workflow:logs for builds using built-in EAS build steps. ([#3523](https://github.com/expo/eas-cli/pull/3523) by [@douglowder](https://github.com/douglowder))
|
||||
- [build-tools][worker] Read Expo app config with `expo config` CLI invocation before falling back to `@expo/config` ([#3536](https://github.com/expo/eas-cli/pull/3536) by [@kitten](https://github.com/kitten))
|
||||
- Fix workflow detection for tracked `.gitignore`d native projects when `requireCommit` is disabled. ([#3561](https://github.com/expo/eas-cli/pull/3561) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
|
||||
### 🧹 Chores
|
||||
|
||||
- Bump apple-utils. ([#3545](https://github.com/expo/eas-cli/pull/3545) by [@quinlanj](https://github.com/quinlanj))
|
||||
- [eas-cli][build-tools][worker] Bump `@expo/config` and `@expo/config-plugins`. ([#3527](https://github.com/expo/eas-cli/pull/3527) by [@quinlanj](https://github.com/quinlanj))
|
||||
|
||||
## [18.4.0](https://github.com/expo/eas-cli/releases/tag/v18.4.0) - 2026-03-16
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
- Auto-detect non-interactive mode in CI and non-TTY environments. ([#3486](https://github.com/expo/eas-cli/pull/3486) by [@EvanBacon](https://github.com/EvanBacon))
|
||||
- Add `skip-build-if-not-found` flag to `eas build:dev`. ([#3495](https://github.com/expo/eas-cli/pull/3495) by [@mmichels-brex](https://github.com/mmichels-brex))
|
||||
|
||||
## [18.3.0](https://github.com/expo/eas-cli/releases/tag/v18.3.0) - 2026-03-10
|
||||
|
||||
### 🎉 New features
|
||||
@@ -51,6 +65,8 @@ This is the log of notable changes to EAS CLI and related packages.
|
||||
- Remove --environment flag requirement for update:configure. ([#3440](https://github.com/expo/eas-cli/pull/3440) by [@douglowder](https://github.com/douglowder))
|
||||
- Fix login spinner interfering with prompts in `eas go` command when not logged in. ([#3451](https://github.com/expo/eas-cli/pull/3451) by [@byronkarlen](https://github.com/byronkarlen))
|
||||
|
||||
### 🧹 Chores
|
||||
|
||||
## [18.0.6](https://github.com/expo/eas-cli/releases/tag/v18.0.6) - 2026-02-27
|
||||
|
||||
## [18.0.5](https://github.com/expo/eas-cli/releases/tag/v18.0.5) - 2026-02-25
|
||||
|
||||
+2
-1
@@ -17,7 +17,7 @@
|
||||
"lint-changelog": "./scripts/bin/run lint-changelog",
|
||||
"release": "lerna run rebuild --concurrency 1 && ./scripts/bin/run release",
|
||||
"test": "lerna run test",
|
||||
"clean": "lerna run clean && rm -rf node_modules coverage"
|
||||
"clean": "lerna run clean && rimraf node_modules coverage"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "29.5.11",
|
||||
@@ -30,6 +30,7 @@
|
||||
"oxfmt": "0.28.0",
|
||||
"oxlint": "1.43.0",
|
||||
"oxlint-tsgolint": "0.11.1",
|
||||
"rimraf": "3.0.2",
|
||||
"ts-jest": "29.1.1",
|
||||
"typescript": "5.5.4"
|
||||
},
|
||||
|
||||
@@ -24,19 +24,19 @@
|
||||
"prebuild": "yarn gql",
|
||||
"build": "tsc",
|
||||
"typecheck": "tsc",
|
||||
"prepack": "rm -rf dist *.tsbuildinfo && yarn gql && tsc -p tsconfig.build.json",
|
||||
"prepack": "rimraf dist \"*.tsbuildinfo\" && yarn gql && tsc -p tsconfig.build.json",
|
||||
"jest-unit": "jest --config jest/unit-config.ts",
|
||||
"jest-integration": "jest --config jest/integration-config.ts",
|
||||
"jest-unit-watch": "jest --config jest/unit-config.ts --watch",
|
||||
"jest-integration-watch": "jest --config jest/integration-config.ts --watch",
|
||||
"clean": "rm -rf node_modules dist coverage *.tsbuildinfo",
|
||||
"clean": "rimraf node_modules dist coverage \"*.tsbuildinfo\"",
|
||||
"gql": "gql.tada generate-schema ${API_SERVER_URL:-https://api.expo.dev}/graphql --output ./schema.graphql && gql.tada generate-output",
|
||||
"gql:local": "API_SERVER_URL=http://api.expo.test yarn gql",
|
||||
"test": "yarn jest-unit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/config": "10.0.6",
|
||||
"@expo/config-plugins": "9.0.12",
|
||||
"@expo/config": "55.0.10",
|
||||
"@expo/config-plugins": "55.0.7",
|
||||
"@expo/downloader": "18.0.1",
|
||||
"@expo/eas-build-job": "18.4.0",
|
||||
"@expo/env": "^0.4.0",
|
||||
@@ -75,7 +75,7 @@
|
||||
"zod": "^4.3.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/repack-app": "~0.2.5",
|
||||
"@expo/repack-app": "~0.4.1",
|
||||
"@types/fs-extra": "^11.0.4",
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/lodash": "^4.17.4",
|
||||
@@ -91,6 +91,7 @@
|
||||
"jest": "^29.7.0",
|
||||
"memfs": "^4.17.1",
|
||||
"nock": "13.4.0",
|
||||
"rimraf": "3.0.2",
|
||||
"ts-jest": "^29.1.4",
|
||||
"ts-mockito": "^2.6.1",
|
||||
"tslib": "^2.6.3",
|
||||
|
||||
@@ -14,8 +14,12 @@ import { eagerBundleAsync, shouldUseEagerBundle } from '../common/eagerBundle';
|
||||
import { prebuildAsync } from '../common/prebuild';
|
||||
import { setupAsync } from '../common/setup';
|
||||
import { Artifacts, BuildContext, SkipNativeBuildError } from '../context';
|
||||
import { cacheStatsAsync, restoreCcacheAsync } from '../steps/functions/restoreBuildCache';
|
||||
import { saveCcacheAsync } from '../steps/functions/saveBuildCache';
|
||||
import {
|
||||
cacheStatsAsync,
|
||||
restoreCcacheAsync,
|
||||
restoreGradleCacheAsync,
|
||||
} from '../steps/functions/restoreBuildCache';
|
||||
import { saveCcacheAsync, saveGradleCacheAsync } from '../steps/functions/saveBuildCache';
|
||||
import {
|
||||
injectConfigureVersionGradleConfig,
|
||||
injectCredentialsGradleConfig,
|
||||
@@ -81,6 +85,12 @@ async function buildAsync(ctx: BuildContext<Android.Job>): Promise<void> {
|
||||
env: ctx.env,
|
||||
secrets: ctx.job.secrets,
|
||||
});
|
||||
await restoreGradleCacheAsync({
|
||||
logger: ctx.logger,
|
||||
workingDirectory,
|
||||
env: ctx.env,
|
||||
secrets: ctx.job.secrets,
|
||||
});
|
||||
});
|
||||
|
||||
await ctx.runBuildPhase(BuildPhase.POST_INSTALL_HOOK, async () => {
|
||||
@@ -93,7 +103,7 @@ async function buildAsync(ctx: BuildContext<Android.Job>): Promise<void> {
|
||||
return await resolveRuntimeVersionForExpoUpdatesIfConfiguredAsync({
|
||||
cwd: ctx.getReactNativeProjectDirectory(),
|
||||
logger: ctx.logger,
|
||||
appConfig: ctx.appConfig,
|
||||
appConfig: await ctx.appConfig,
|
||||
platform: ctx.job.platform,
|
||||
workflow: ctx.job.type,
|
||||
env: ctx.env,
|
||||
@@ -196,6 +206,12 @@ async function buildAsync(ctx: BuildContext<Android.Job>): Promise<void> {
|
||||
env: ctx.env,
|
||||
secrets: ctx.job.secrets,
|
||||
});
|
||||
await saveGradleCacheAsync({
|
||||
logger: ctx.logger,
|
||||
workingDirectory,
|
||||
env: ctx.env,
|
||||
secrets: ctx.job.secrets,
|
||||
});
|
||||
});
|
||||
|
||||
await ctx.runBuildPhase(BuildPhase.CACHE_STATS, async () => {
|
||||
|
||||
@@ -103,7 +103,7 @@ async function buildAsync(ctx: BuildContext<Ios.Job>): Promise<void> {
|
||||
return await resolveRuntimeVersionForExpoUpdatesIfConfiguredAsync({
|
||||
cwd: ctx.getReactNativeProjectDirectory(),
|
||||
logger: ctx.logger,
|
||||
appConfig: ctx.appConfig,
|
||||
appConfig: await ctx.appConfig,
|
||||
platform: ctx.job.platform,
|
||||
workflow: ctx.job.type,
|
||||
env: ctx.env,
|
||||
|
||||
@@ -113,7 +113,7 @@ export async function setupAsync<TJob extends BuildJob>(ctx: BuildContext<TJob>)
|
||||
});
|
||||
|
||||
await ctx.runBuildPhase(BuildPhase.READ_APP_CONFIG, async () => {
|
||||
const appConfig = ctx.appConfig;
|
||||
const appConfig = await ctx.appConfig;
|
||||
ctx.logger.info('Using app configuration:');
|
||||
ctx.logger.info(JSON.stringify(appConfig, null, 2));
|
||||
await validateAppConfigAsync(ctx, appConfig);
|
||||
@@ -121,12 +121,13 @@ export async function setupAsync<TJob extends BuildJob>(ctx: BuildContext<TJob>)
|
||||
|
||||
if (ctx.job.triggeredBy === BuildTrigger.GIT_BASED_INTEGRATION) {
|
||||
await ctx.runBuildPhase(BuildPhase.EAS_BUILD_INTERNAL, async () => {
|
||||
if (!ctx.appConfig.ios?.bundleIdentifier && ctx.job.platform === Platform.IOS) {
|
||||
const appConfig = await ctx.appConfig;
|
||||
if (!appConfig.ios?.bundleIdentifier && ctx.job.platform === Platform.IOS) {
|
||||
throw new Error(
|
||||
'The "ios.bundleIdentifier" is required to be set in app config for builds triggered by GitHub integration. Learn more: https://docs.expo.dev/versions/latest/config/app/#bundleidentifier.'
|
||||
);
|
||||
}
|
||||
if (!ctx.appConfig.android?.package && ctx.job.platform === Platform.ANDROID) {
|
||||
if (!appConfig.android?.package && ctx.job.platform === Platform.ANDROID) {
|
||||
throw new Error(
|
||||
'The "android.package" is required to be set in app config for builds triggered by GitHub integration. Learn more: https://docs.expo.dev/versions/latest/config/app/#package.'
|
||||
);
|
||||
|
||||
@@ -96,7 +96,7 @@ export class BuildContext<TJob extends Job = Job> {
|
||||
private buildPhase?: BuildPhase;
|
||||
private buildPhaseSkipped = false;
|
||||
private buildPhaseHasWarnings = false;
|
||||
private _appConfig?: ExpoConfig;
|
||||
private _appConfig?: Promise<ExpoConfig>;
|
||||
private readonly reportBuildPhaseStats?: (stats: BuildPhaseStats) => void;
|
||||
public readonly graphqlClient: Client;
|
||||
|
||||
@@ -175,14 +175,14 @@ export class BuildContext<TJob extends Job = Job> {
|
||||
public get packageManager(): PackageManager {
|
||||
return resolvePackageManager(this.getReactNativeProjectDirectory());
|
||||
}
|
||||
public get appConfig(): ExpoConfig {
|
||||
public get appConfig(): Promise<ExpoConfig> {
|
||||
if (!this._appConfig) {
|
||||
this._appConfig = readAppConfig({
|
||||
projectDir: this.getReactNativeProjectDirectory(),
|
||||
env: this.env,
|
||||
logger: this.logger,
|
||||
sdkVersion: this.metadata?.sdkVersion,
|
||||
}).exp;
|
||||
}).then(config => config.exp);
|
||||
}
|
||||
return this._appConfig;
|
||||
}
|
||||
|
||||
@@ -19,5 +19,12 @@ export { PackageManager } from './utils/packageManager';
|
||||
export { findAndUploadXcodeBuildLogsAsync } from './ios/xcodeBuildLogs';
|
||||
|
||||
export { Hook, runHookIfPresent } from './utils/hooks';
|
||||
export {
|
||||
maybeStartPreparingPrecompiledModules,
|
||||
PRECOMPILED_MODULES_PATH,
|
||||
shouldUsePrecompiledDependencies,
|
||||
startPreparingPrecompiledDependencies,
|
||||
waitForPrecompiledModulesPreparationAsync,
|
||||
} from './utils/precompiledModules';
|
||||
|
||||
export * from './generic';
|
||||
@@ -0,0 +1,127 @@
|
||||
import downloadFile from '@expo/downloader';
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import { mkdirp, mkdtemp, move, remove } from 'fs-extra';
|
||||
import StreamZip from 'node-stream-zip';
|
||||
|
||||
import { createTestIosJob } from '../../__tests__/utils/job';
|
||||
import { createMockLogger } from '../../__tests__/utils/logger';
|
||||
import { BuildContext } from '../../context';
|
||||
import {
|
||||
startPreparingPrecompiledDependencies,
|
||||
PRECOMPILED_MODULES_PATH,
|
||||
} from '../../utils/precompiledModules';
|
||||
import { installPods } from '../pod';
|
||||
|
||||
jest.mock('@expo/downloader');
|
||||
jest.mock('fs-extra');
|
||||
jest.mock('@expo/turtle-spawn');
|
||||
jest.mock('node-stream-zip', () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
async: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe(installPods.name, () => {
|
||||
const extract = jest.fn();
|
||||
const close = jest.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
jest.mocked(remove).mockImplementation(async () => undefined as any);
|
||||
jest.mocked(mkdirp).mockImplementation(async () => undefined as any);
|
||||
jest.mocked(move).mockImplementation(async () => undefined as any);
|
||||
let mkdtempCallCount = 0;
|
||||
jest.mocked(mkdtemp).mockImplementation(async () => {
|
||||
mkdtempCallCount += 1;
|
||||
return mkdtempCallCount === 1
|
||||
? ('/tmp/precompiled-modules-archive' as any)
|
||||
: ('/tmp/precompiled-modules-staging' as any);
|
||||
});
|
||||
extract.mockReset().mockResolvedValue(undefined);
|
||||
close.mockReset().mockResolvedValue(undefined);
|
||||
jest.mocked(StreamZip.async).mockImplementation(
|
||||
() =>
|
||||
({
|
||||
extract,
|
||||
close,
|
||||
}) as any
|
||||
);
|
||||
});
|
||||
|
||||
it('waits for precompiled dependencies before running pod install', async () => {
|
||||
let resolvePreparation: (() => void) | undefined;
|
||||
const preparationPromise = new Promise<void>(resolve => {
|
||||
resolvePreparation = resolve;
|
||||
});
|
||||
jest.mocked(downloadFile).mockReturnValue(preparationPromise);
|
||||
const ctx = new BuildContext(
|
||||
createTestIosJob({
|
||||
buildCredentials: undefined,
|
||||
}),
|
||||
{
|
||||
workingdir: '/workingdir',
|
||||
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
|
||||
logger: createMockLogger(),
|
||||
env: {
|
||||
__API_SERVER_URL: 'http://api.expo.test',
|
||||
},
|
||||
uploadArtifact: jest.fn(),
|
||||
}
|
||||
);
|
||||
startPreparingPrecompiledDependencies(ctx, [
|
||||
'https://example.com/precompiled-modules-0.zip',
|
||||
'https://example.com/precompiled-modules-1.zip',
|
||||
]);
|
||||
|
||||
jest.mocked(spawn).mockResolvedValue({} as any);
|
||||
|
||||
const installPodsPromise = installPods(ctx, {});
|
||||
await Promise.resolve();
|
||||
|
||||
expect(spawn).not.toHaveBeenCalled();
|
||||
|
||||
resolvePreparation?.();
|
||||
await installPodsPromise;
|
||||
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'pod',
|
||||
['install'],
|
||||
expect.objectContaining({
|
||||
cwd: '/workingdir/build/ios',
|
||||
})
|
||||
);
|
||||
expect(mkdirp).toHaveBeenCalledWith(PRECOMPILED_MODULES_PATH);
|
||||
});
|
||||
|
||||
it('continues with pod install when precompiled dependencies preparation fails', async () => {
|
||||
jest.mocked(downloadFile).mockRejectedValue(new Error('download failed'));
|
||||
const ctx = new BuildContext(
|
||||
createTestIosJob({
|
||||
buildCredentials: undefined,
|
||||
}),
|
||||
{
|
||||
workingdir: '/workingdir',
|
||||
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
|
||||
logger: createMockLogger(),
|
||||
env: {
|
||||
__API_SERVER_URL: 'http://api.expo.test',
|
||||
},
|
||||
uploadArtifact: jest.fn(),
|
||||
}
|
||||
);
|
||||
startPreparingPrecompiledDependencies(ctx, ['https://example.com/precompiled-modules-0.zip']);
|
||||
|
||||
jest.mocked(spawn).mockResolvedValue({} as any);
|
||||
|
||||
await expect(installPods(ctx, {})).resolves.toEqual({
|
||||
spawnPromise: expect.any(Promise),
|
||||
});
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'pod',
|
||||
['install'],
|
||||
expect.objectContaining({
|
||||
cwd: '/workingdir/build/ios',
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -3,11 +3,21 @@ import spawn, { SpawnOptions, SpawnPromise, SpawnResult } from '@expo/turtle-spa
|
||||
import path from 'path';
|
||||
|
||||
import { BuildContext } from '../context';
|
||||
import { waitForPrecompiledModulesPreparationAsync } from '../utils/precompiledModules';
|
||||
|
||||
export async function installPods<TJob extends Ios.Job>(
|
||||
ctx: BuildContext<TJob>,
|
||||
{ infoCallbackFn }: SpawnOptions
|
||||
): Promise<{ spawnPromise: SpawnPromise<SpawnResult> }> {
|
||||
try {
|
||||
await waitForPrecompiledModulesPreparationAsync();
|
||||
} catch (err) {
|
||||
ctx.logger.warn(
|
||||
{ err },
|
||||
'Precompiled dependencies were not prepared successfully, continuing with pod install'
|
||||
);
|
||||
}
|
||||
|
||||
const iosDir = path.join(ctx.getReactNativeProjectDirectory(), 'ios');
|
||||
|
||||
const verboseFlag = ctx.env['EAS_VERBOSE'] === '1' ? ['--verbose'] : [];
|
||||
|
||||
@@ -51,7 +51,6 @@ export function createEasMaestroTestFunctionGroup(
|
||||
steps.push(
|
||||
new BuildStep(globalCtx, {
|
||||
id: BuildStep.getNewId(),
|
||||
name: 'install_app',
|
||||
displayName: `Install app to Simulator`,
|
||||
command: `
|
||||
# shopt -s nullglob is necessary not to try to install
|
||||
@@ -97,7 +96,6 @@ export function createEasMaestroTestFunctionGroup(
|
||||
steps.push(
|
||||
new BuildStep(globalCtx, {
|
||||
id: BuildStep.getNewId(),
|
||||
name: 'install_app',
|
||||
displayName: `Install app to Emulator`,
|
||||
command: `
|
||||
# shopt -s globstar is necessary to add /**/ support
|
||||
@@ -134,7 +132,6 @@ export function createEasMaestroTestFunctionGroup(
|
||||
steps.push(
|
||||
new BuildStep(globalCtx, {
|
||||
id: BuildStep.getNewId(),
|
||||
name: 'maestro_test',
|
||||
ifCondition: '${ always() }',
|
||||
displayName: `maestro test ${flowPath}`,
|
||||
command: `maestro test ${flowPath}`,
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
|
||||
import { createGlobalContextMock } from '../../../__tests__/utils/context';
|
||||
import { waitForPrecompiledModulesPreparationAsync } from '../../../utils/precompiledModules';
|
||||
import { createInstallPodsBuildFunction } from '../installPods';
|
||||
|
||||
jest.mock('@expo/turtle-spawn');
|
||||
jest.mock('../../../utils/precompiledModules', () => ({
|
||||
...jest.requireActual('../../../utils/precompiledModules'),
|
||||
waitForPrecompiledModulesPreparationAsync: jest.fn(),
|
||||
}));
|
||||
|
||||
describe(createInstallPodsBuildFunction, () => {
|
||||
it('waits for precompiled dependencies before running pod install', async () => {
|
||||
jest.mocked(spawn).mockResolvedValue({} as any);
|
||||
jest.mocked(waitForPrecompiledModulesPreparationAsync).mockResolvedValue(undefined);
|
||||
|
||||
const installPods = createInstallPodsBuildFunction();
|
||||
const globalContext = createGlobalContextMock({});
|
||||
const buildStep = installPods.createBuildStepFromFunctionCall(globalContext, {
|
||||
callInputs: {},
|
||||
});
|
||||
|
||||
await buildStep.executeAsync();
|
||||
|
||||
expect(waitForPrecompiledModulesPreparationAsync).toHaveBeenCalled();
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'pod',
|
||||
['install'],
|
||||
expect.objectContaining({
|
||||
cwd: globalContext.defaultWorkingDirectory,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('continues with pod install when precompiled dependencies preparation fails', async () => {
|
||||
jest.mocked(spawn).mockResolvedValue({} as any);
|
||||
jest
|
||||
.mocked(waitForPrecompiledModulesPreparationAsync)
|
||||
.mockRejectedValue(new Error('precompiled dependencies failed'));
|
||||
|
||||
const installPods = createInstallPodsBuildFunction();
|
||||
const globalContext = createGlobalContextMock({});
|
||||
const buildStep = installPods.createBuildStepFromFunctionCall(globalContext, {
|
||||
callInputs: {},
|
||||
});
|
||||
|
||||
await expect(buildStep.executeAsync()).resolves.toBeUndefined();
|
||||
|
||||
expect(waitForPrecompiledModulesPreparationAsync).toHaveBeenCalled();
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'pod',
|
||||
['install'],
|
||||
expect.objectContaining({
|
||||
cwd: globalContext.defaultWorkingDirectory,
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,7 @@ jest.mock('../../../utils/AndroidEmulatorUtils', () => ({
|
||||
cloneAsync: jest.fn(),
|
||||
startAsync: jest.fn(),
|
||||
waitForReadyAsync: jest.fn(),
|
||||
disableWindowAndTransitionAnimationsAsync: jest.fn(),
|
||||
deleteAsync: jest.fn(),
|
||||
},
|
||||
}));
|
||||
@@ -34,14 +35,15 @@ const mockedSpawn = jest.mocked(spawn);
|
||||
const mockedRetryAsync = jest.mocked(retryAsync);
|
||||
const mockedAndroidUtils = jest.mocked(AndroidEmulatorUtils);
|
||||
|
||||
function createStep(callInputs?: Record<string, unknown>) {
|
||||
function createStep(callInputs?: Record<string, unknown>, envOverrides?: NodeJS.ProcessEnv) {
|
||||
const logger = createMockLogger();
|
||||
const fn = createStartAndroidEmulatorBuildFunction();
|
||||
const globalCtx = createGlobalContextMock({ logger });
|
||||
globalCtx.updateEnv({ HOME: '/home/expo', ANDROID_HOME: '/android/home' });
|
||||
return fn.createBuildStepFromFunctionCall(globalCtx, {
|
||||
globalCtx.updateEnv({ HOME: '/home/expo', ANDROID_HOME: '/android/home', ...envOverrides });
|
||||
const step = fn.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs,
|
||||
});
|
||||
return Object.assign(step, { logger });
|
||||
}
|
||||
|
||||
function createStartResult(serialId: string) {
|
||||
@@ -57,7 +59,9 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
|
||||
mockedAndroidUtils.getAvailableDevicesAsync.mockResolvedValue([]);
|
||||
mockedAndroidUtils.createAsync.mockResolvedValue(undefined);
|
||||
mockedAndroidUtils.cloneAsync.mockResolvedValue(undefined);
|
||||
mockedAndroidUtils.startAsync.mockResolvedValue(createStartResult('emulator-default'));
|
||||
mockedAndroidUtils.waitForReadyAsync.mockResolvedValue(undefined);
|
||||
mockedAndroidUtils.disableWindowAndTransitionAnimationsAsync.mockResolvedValue(undefined);
|
||||
mockedAndroidUtils.deleteAsync.mockResolvedValue(undefined);
|
||||
|
||||
mockedRetryAsync.mockImplementation(async (fn, { retryOptions }) => {
|
||||
@@ -97,6 +101,12 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
|
||||
timeoutMs: 120_000,
|
||||
})
|
||||
);
|
||||
expect(mockedAndroidUtils.disableWindowAndTransitionAnimationsAsync).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
serialId: 'emulator-2222',
|
||||
})
|
||||
);
|
||||
expect(mockedAndroidUtils.deleteAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
serialId: 'emulator-1111',
|
||||
@@ -147,6 +157,24 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
|
||||
timeoutMs: 60_000,
|
||||
})
|
||||
);
|
||||
expect(mockedAndroidUtils.disableWindowAndTransitionAnimationsAsync).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
serialId: 'emulator-base',
|
||||
})
|
||||
);
|
||||
expect(mockedAndroidUtils.disableWindowAndTransitionAnimationsAsync).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
serialId: 'emulator-clone-1-attempt-2',
|
||||
})
|
||||
);
|
||||
expect(mockedAndroidUtils.disableWindowAndTransitionAnimationsAsync).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
expect.objectContaining({
|
||||
serialId: 'emulator-clone-2-attempt-1',
|
||||
})
|
||||
);
|
||||
|
||||
expect(mockedAndroidUtils.deleteAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
@@ -174,4 +202,14 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
|
||||
);
|
||||
expect(mockedAndroidUtils.deleteAsync).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('skips animation scale adjustments when opt out env var is disabled', async () => {
|
||||
const step = createStep(undefined, {
|
||||
ANDROID_EMULATOR_ADJUST_ANIMATION_SCALE: 'false',
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedAndroidUtils.disableWindowAndTransitionAnimationsAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
isClosedVersionTrainError,
|
||||
isInvalidBundleIdentifierError,
|
||||
isMissingPurposeStringError,
|
||||
isSdkVersionIssueError,
|
||||
parseMissingUsageDescriptionKeys,
|
||||
} from '../uploadToAsc';
|
||||
|
||||
@@ -58,6 +59,20 @@ describe(isMissingPurposeStringError, () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe(isSdkVersionIssueError, () => {
|
||||
it('returns true when all errors are SDK-version-issue codes', () => {
|
||||
expect(isSdkVersionIssueError([{ code: '90725' }, { code: '90725' }])).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when any other error code is present', () => {
|
||||
expect(isSdkVersionIssueError([{ code: '90725' }, { code: '90062' }])).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when there are no errors', () => {
|
||||
expect(isSdkVersionIssueError([])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe(parseMissingUsageDescriptionKeys, () => {
|
||||
it('extracts missing UsageDescription keys from ASC messages', () => {
|
||||
expect(
|
||||
|
||||
@@ -34,18 +34,20 @@ export function calculateEASUpdateRuntimeVersionFunction(): BuildFunction {
|
||||
}),
|
||||
],
|
||||
fn: async (stepCtx, { env, inputs, outputs }) => {
|
||||
const appConfig = readAppConfig({
|
||||
projectDir: stepCtx.workingDirectory,
|
||||
env: Object.keys(env).reduce(
|
||||
(acc, key) => {
|
||||
acc[key] = env[key] ?? '';
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, string>
|
||||
),
|
||||
logger: stepCtx.logger,
|
||||
sdkVersion: stepCtx.global.staticContext.metadata?.sdkVersion,
|
||||
}).exp;
|
||||
const appConfig = (
|
||||
await readAppConfig({
|
||||
projectDir: stepCtx.workingDirectory,
|
||||
env: Object.keys(env).reduce(
|
||||
(acc, key) => {
|
||||
acc[key] = env[key] ?? '';
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, string>
|
||||
),
|
||||
logger: stepCtx.logger,
|
||||
sdkVersion: stepCtx.global.staticContext.metadata?.sdkVersion,
|
||||
})
|
||||
).exp;
|
||||
|
||||
const platform =
|
||||
(inputs.platform.value as Platform) ?? stepCtx.global.staticContext.job.platform;
|
||||
|
||||
@@ -42,18 +42,20 @@ export function configureEASUpdateIfInstalledFunction(): BuildFunction {
|
||||
assert(job.platform, 'Configuring EAS Update in generic jobs is not supported.');
|
||||
const metadata = stepCtx.global.staticContext.metadata as Metadata | undefined;
|
||||
|
||||
const appConfig = readAppConfig({
|
||||
projectDir: stepCtx.workingDirectory,
|
||||
env: Object.keys(env).reduce(
|
||||
(acc, key) => {
|
||||
acc[key] = env[key] ?? '';
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, string>
|
||||
),
|
||||
logger: stepCtx.logger,
|
||||
sdkVersion: metadata?.sdkVersion,
|
||||
}).exp;
|
||||
const appConfig = (
|
||||
await readAppConfig({
|
||||
projectDir: stepCtx.workingDirectory,
|
||||
env: Object.keys(env).reduce(
|
||||
(acc, key) => {
|
||||
acc[key] = env[key] ?? '';
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, string>
|
||||
),
|
||||
logger: stepCtx.logger,
|
||||
sdkVersion: metadata?.sdkVersion,
|
||||
})
|
||||
).exp;
|
||||
|
||||
const channelInput = inputs.channel.value as string | undefined;
|
||||
const runtimeVersionInput = inputs.runtime_version.value as string | undefined;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { BuildFunction } from '@expo/steps';
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
|
||||
import { waitForPrecompiledModulesPreparationAsync } from '../../utils/precompiledModules';
|
||||
|
||||
export function createInstallPodsBuildFunction(): BuildFunction {
|
||||
return new BuildFunction({
|
||||
namespace: 'eas',
|
||||
@@ -8,6 +10,14 @@ export function createInstallPodsBuildFunction(): BuildFunction {
|
||||
name: 'Install Pods',
|
||||
__metricsId: 'eas/install_pods',
|
||||
fn: async (stepsCtx, { env }) => {
|
||||
try {
|
||||
await waitForPrecompiledModulesPreparationAsync();
|
||||
} catch (err) {
|
||||
stepsCtx.logger.warn(
|
||||
{ err },
|
||||
'Precompiled dependencies were not prepared successfully, continuing with pod install'
|
||||
);
|
||||
}
|
||||
stepsCtx.logger.info('Installing pods');
|
||||
const verboseFlag = stepsCtx.global.env['EAS_VERBOSE'] === '1' ? ['--verbose'] : [];
|
||||
const cocoapodsDeploymentFlag =
|
||||
|
||||
@@ -23,6 +23,7 @@ import resolveFrom from 'resolve-from';
|
||||
|
||||
import { COMMON_FASTLANE_ENV } from '../../common/fastlane';
|
||||
import IosCredentialsManager from '../utils/ios/credentials/manager';
|
||||
import { resolvePackageVersionAsync } from '../../utils/packageManager';
|
||||
|
||||
export function createRepackBuildFunction(): BuildFunction {
|
||||
return new BuildFunction({
|
||||
@@ -51,6 +52,11 @@ export function createRepackBuildFunction(): BuildFunction {
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.BOOLEAN,
|
||||
required: false,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'js_bundle_only',
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.BOOLEAN,
|
||||
required: false,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'repack_version',
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
@@ -82,7 +88,10 @@ export function createRepackBuildFunction(): BuildFunction {
|
||||
);
|
||||
}
|
||||
|
||||
const repackSpawnAsync = createSpawnAsyncStepAdapter({ verbose, logger: stepsCtx.logger });
|
||||
const repackSpawnAsync = createSpawnAsyncStepAdapter({
|
||||
verbose,
|
||||
logger: stepsCtx.logger,
|
||||
});
|
||||
|
||||
const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), `repack-`));
|
||||
const workingDirectory = path.join(tmpDir, 'working-directory');
|
||||
@@ -98,13 +107,20 @@ export function createRepackBuildFunction(): BuildFunction {
|
||||
sourcemapOutput: undefined,
|
||||
}
|
||||
: undefined;
|
||||
const jsBundleOnly = (inputs.js_bundle_only.value as boolean | undefined) ?? false;
|
||||
|
||||
const resolvedRepackVersion =
|
||||
(await resolvePackageVersionAsync({
|
||||
logger: stepsCtx.logger,
|
||||
packageName: inputs.repack_package.value as string,
|
||||
distTag: inputs.repack_version.value as string,
|
||||
})) ?? (inputs.repack_version.value as string);
|
||||
stepsCtx.logger.info(
|
||||
`Using repack from: ${inputs.repack_package.value}@${inputs.repack_version.value}`
|
||||
`Using repack from: ${inputs.repack_package.value}@${inputs.repack_version.value} (${resolvedRepackVersion})`
|
||||
);
|
||||
const repackApp = await installAndImportRepackAsync({
|
||||
packageName: inputs.repack_package.value as string,
|
||||
version: inputs.repack_version.value as string,
|
||||
version: resolvedRepackVersion,
|
||||
});
|
||||
const { repackAppIosAsync, repackAppAndroidAsync } = repackApp;
|
||||
|
||||
@@ -118,6 +134,7 @@ export function createRepackBuildFunction(): BuildFunction {
|
||||
outputPath,
|
||||
workingDirectory,
|
||||
exportEmbedOptions,
|
||||
jsBundleOnly,
|
||||
iosSigningOptions: await resolveIosSigningOptionsAsync({
|
||||
job: stepsCtx.global.staticContext.job,
|
||||
logger: stepsCtx.logger,
|
||||
@@ -146,6 +163,7 @@ export function createRepackBuildFunction(): BuildFunction {
|
||||
outputPath,
|
||||
workingDirectory,
|
||||
exportEmbedOptions,
|
||||
jsBundleOnly,
|
||||
androidSigningOptions,
|
||||
logger: stepsCtx.logger,
|
||||
spawnAsync: repackSpawnAsync,
|
||||
|
||||
@@ -7,7 +7,10 @@ import {
|
||||
BuildStepInputValueTypeName,
|
||||
spawnAsync,
|
||||
} from '@expo/steps';
|
||||
import fs from 'fs';
|
||||
import nullthrows from 'nullthrows';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import { sendCcacheStatsAsync } from './ccacheStats';
|
||||
import { decompressCacheAsync, downloadCacheAsync, downloadPublicCacheAsync } from './restoreCache';
|
||||
@@ -16,6 +19,7 @@ import {
|
||||
generateDefaultBuildCacheKeyAsync,
|
||||
getCcachePath,
|
||||
} from '../../utils/cacheKey';
|
||||
import { GRADLE_CACHE_KEY_PREFIX, generateGradleCacheKeyAsync } from '../../utils/gradleCacheKey';
|
||||
import { TurtleFetchError } from '../../utils/turtleFetch';
|
||||
|
||||
export function createRestoreBuildCacheFunction(): BuildFunction {
|
||||
@@ -50,6 +54,15 @@ export function createRestoreBuildCacheFunction(): BuildFunction {
|
||||
env,
|
||||
secrets: stepCtx.global.staticContext.job.secrets,
|
||||
});
|
||||
|
||||
if (platform === Platform.ANDROID) {
|
||||
await restoreGradleCacheAsync({
|
||||
logger,
|
||||
workingDirectory,
|
||||
env,
|
||||
secrets: stepCtx.global.staticContext.job.secrets,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -176,6 +189,106 @@ export async function restoreCcacheAsync({
|
||||
}
|
||||
}
|
||||
|
||||
export async function restoreGradleCacheAsync({
|
||||
logger,
|
||||
workingDirectory,
|
||||
env,
|
||||
secrets,
|
||||
}: {
|
||||
logger: bunyan;
|
||||
workingDirectory: string;
|
||||
env: Record<string, string | undefined>;
|
||||
secrets?: { robotAccessToken?: string };
|
||||
}): Promise<void> {
|
||||
if (env.EXPERIMENTAL_EAS_GRADLE_CACHE !== '1') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const gradlePropertiesPath = path.join(workingDirectory, 'android', 'gradle.properties');
|
||||
const gradlePropertiesContent = await fs.promises.readFile(gradlePropertiesPath, 'utf-8');
|
||||
await fs.promises.writeFile(
|
||||
gradlePropertiesPath,
|
||||
`${gradlePropertiesContent}\n\norg.gradle.caching=true\n`
|
||||
);
|
||||
|
||||
// Configure cache cleanup via init script (works with both Gradle 8 and 9,
|
||||
// org.gradle.cache.cleanup property was removed in Gradle 9)
|
||||
const initScriptDir = path.join(os.homedir(), '.gradle', 'init.d');
|
||||
await fs.promises.mkdir(initScriptDir, { recursive: true });
|
||||
await fs.promises.writeFile(
|
||||
path.join(initScriptDir, 'eas-cache-cleanup.gradle'),
|
||||
[
|
||||
'def cacheDir = new File(System.getProperty("user.home"), ".gradle/caches/build-cache-1")',
|
||||
'def countBefore = cacheDir.exists() ? cacheDir.listFiles()?.length ?: 0 : 0',
|
||||
'println "[EAS] Gradle build cache entries before cleanup: ${countBefore}"',
|
||||
'',
|
||||
'beforeSettings { settings ->',
|
||||
' try {',
|
||||
' settings.caches {',
|
||||
' cleanup = Cleanup.ALWAYS',
|
||||
' buildCache {',
|
||||
' setRemoveUnusedEntriesAfterDays(3)',
|
||||
' }',
|
||||
' }',
|
||||
' println "[EAS] Configured Gradle cache cleanup via init script"',
|
||||
' } catch (Exception e) {',
|
||||
' println "[EAS] Failed to configure cache cleanup: ${e.message}"',
|
||||
' }',
|
||||
'}',
|
||||
'',
|
||||
'gradle.buildFinished {',
|
||||
' def countAfter = cacheDir.exists() ? cacheDir.listFiles()?.length ?: 0 : 0',
|
||||
' println "[EAS] Gradle build cache entries after build: ${countAfter} (was ${countBefore})"',
|
||||
'}',
|
||||
'',
|
||||
].join('\n')
|
||||
);
|
||||
|
||||
const robotAccessToken = nullthrows(
|
||||
secrets?.robotAccessToken,
|
||||
'Robot access token is required for cache operations'
|
||||
);
|
||||
const expoApiServerURL = nullthrows(env.__API_SERVER_URL, '__API_SERVER_URL is not set');
|
||||
const jobId = nullthrows(env.EAS_BUILD_ID, 'EAS_BUILD_ID is not set');
|
||||
const cacheKey = await generateGradleCacheKeyAsync(workingDirectory);
|
||||
logger.info(`Restoring Gradle cache key: ${cacheKey}`);
|
||||
|
||||
const gradleCachesPath = path.join(os.homedir(), '.gradle', 'caches');
|
||||
|
||||
const buildCachePath = path.join(gradleCachesPath, 'build-cache-1');
|
||||
|
||||
const { archivePath, matchedKey } = await downloadCacheAsync({
|
||||
logger,
|
||||
jobId,
|
||||
expoApiServerURL,
|
||||
robotAccessToken,
|
||||
paths: [buildCachePath],
|
||||
key: cacheKey,
|
||||
keyPrefixes: [GRADLE_CACHE_KEY_PREFIX],
|
||||
platform: Platform.ANDROID,
|
||||
});
|
||||
|
||||
await fs.promises.mkdir(gradleCachesPath, { recursive: true });
|
||||
await decompressCacheAsync({
|
||||
archivePath,
|
||||
workingDirectory: gradleCachesPath,
|
||||
verbose: env.EXPO_DEBUG === '1',
|
||||
logger,
|
||||
});
|
||||
|
||||
logger.info(
|
||||
`Gradle cache restored to ${gradleCachesPath} ${matchedKey === cacheKey ? '(direct hit)' : '(prefix match)'}`
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof TurtleFetchError && err.response?.status === 404) {
|
||||
logger.info('No Gradle cache found for this key');
|
||||
} else {
|
||||
logger.warn('Failed to restore Gradle cache: ', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function cacheStatsAsync({
|
||||
logger,
|
||||
env,
|
||||
|
||||
@@ -10,8 +10,13 @@ import {
|
||||
import fs from 'fs';
|
||||
import nullthrows from 'nullthrows';
|
||||
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import { compressCacheAsync, uploadCacheAsync } from './saveCache';
|
||||
import { formatBytes } from '../../utils/artifacts';
|
||||
import { generateDefaultBuildCacheKeyAsync, getCcachePath } from '../../utils/cacheKey';
|
||||
import { generateGradleCacheKeyAsync } from '../../utils/gradleCacheKey';
|
||||
|
||||
export function createSaveBuildCacheFunction(evictUsedBefore: Date): BuildFunction {
|
||||
return new BuildFunction({
|
||||
@@ -46,6 +51,15 @@ export function createSaveBuildCacheFunction(evictUsedBefore: Date): BuildFuncti
|
||||
env,
|
||||
secrets: stepCtx.global.staticContext.job.secrets,
|
||||
});
|
||||
|
||||
if (platform === Platform.ANDROID) {
|
||||
await saveGradleCacheAsync({
|
||||
logger,
|
||||
workingDirectory,
|
||||
env,
|
||||
secrets: stepCtx.global.staticContext.job.secrets,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -135,3 +149,66 @@ export async function saveCcacheAsync({
|
||||
logger.error({ err }, 'Failed to save cache');
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveGradleCacheAsync({
|
||||
logger,
|
||||
workingDirectory,
|
||||
env,
|
||||
secrets,
|
||||
}: {
|
||||
logger: bunyan;
|
||||
workingDirectory: string;
|
||||
env: Record<string, string | undefined>;
|
||||
secrets?: { robotAccessToken?: string };
|
||||
}): Promise<void> {
|
||||
if (env.EXPERIMENTAL_EAS_GRADLE_CACHE !== '1') {
|
||||
return;
|
||||
}
|
||||
|
||||
const gradleCachesPath = path.join(os.homedir(), '.gradle', 'caches');
|
||||
const buildCachePath = path.join(gradleCachesPath, 'build-cache-1');
|
||||
|
||||
try {
|
||||
await fs.promises.access(buildCachePath);
|
||||
} catch {
|
||||
logger.warn('No Gradle build cache found, skipping save');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const cacheKey = await generateGradleCacheKeyAsync(workingDirectory);
|
||||
logger.info(`Saving Gradle cache key: ${cacheKey}`);
|
||||
|
||||
const jobId = nullthrows(env.EAS_BUILD_ID, 'EAS_BUILD_ID is not set');
|
||||
const robotAccessToken = nullthrows(
|
||||
secrets?.robotAccessToken,
|
||||
'Robot access token is required for cache operations'
|
||||
);
|
||||
const expoApiServerURL = nullthrows(env.__API_SERVER_URL, '__API_SERVER_URL is not set');
|
||||
|
||||
logger.info('Compressing Gradle build cache...');
|
||||
const { archivePath } = await compressCacheAsync({
|
||||
paths: [buildCachePath],
|
||||
workingDirectory: gradleCachesPath,
|
||||
verbose: env.EXPO_DEBUG === '1',
|
||||
logger,
|
||||
});
|
||||
|
||||
const { size } = await fs.promises.stat(archivePath);
|
||||
logger.info(`Gradle cache archive size: ${formatBytes(size)}`);
|
||||
|
||||
await uploadCacheAsync({
|
||||
logger,
|
||||
jobId,
|
||||
expoApiServerURL,
|
||||
robotAccessToken,
|
||||
archivePath,
|
||||
key: cacheKey,
|
||||
paths: [buildCachePath],
|
||||
size,
|
||||
platform: Platform.ANDROID,
|
||||
});
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'Failed to save Gradle cache');
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,15 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
|
||||
const systemImagePackage = `${inputs.system_image_package.value}`;
|
||||
// We can cast because allowedValueTypeName validated this is a string.
|
||||
const deviceIdentifier = inputs.device_identifier.value as AndroidDeviceName | undefined;
|
||||
const shouldAdjustAnimationScale =
|
||||
env.ANDROID_EMULATOR_ADJUST_ANIMATION_SCALE !== 'false' &&
|
||||
env.ANDROID_EMULATOR_ADJUST_ANIMATION_SCALE !== '0';
|
||||
|
||||
if (!shouldAdjustAnimationScale) {
|
||||
logger.info(
|
||||
'Skipping Android emulator animation scale adjustments because $ANDROID_EMULATOR_ADJUST_ANIMATION_SCALE is disabled.'
|
||||
);
|
||||
}
|
||||
|
||||
logger.info('Making sure system image is installed');
|
||||
await retryAsync(
|
||||
@@ -107,6 +116,13 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
|
||||
timeoutMs,
|
||||
logger,
|
||||
});
|
||||
if (shouldAdjustAnimationScale) {
|
||||
await AndroidEmulatorUtils.disableWindowAndTransitionAnimationsAsync({
|
||||
env,
|
||||
logger,
|
||||
serialId: attemptSerialId,
|
||||
});
|
||||
}
|
||||
logger.info(`${deviceName} is ready.`);
|
||||
|
||||
serialId = attemptSerialId;
|
||||
@@ -191,6 +207,13 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
|
||||
timeoutMs,
|
||||
logger,
|
||||
});
|
||||
if (shouldAdjustAnimationScale) {
|
||||
await AndroidEmulatorUtils.disableWindowAndTransitionAnimationsAsync({
|
||||
env,
|
||||
logger,
|
||||
serialId: cloneSerialId,
|
||||
});
|
||||
}
|
||||
|
||||
logger.info(`${cloneIdentifier} is ready.`);
|
||||
} catch (err) {
|
||||
|
||||
@@ -266,12 +266,31 @@ export function createUploadToAscBuildFunction(): BuildFunction {
|
||||
}
|
||||
|
||||
if (state.state === 'FAILED') {
|
||||
if (isSdkVersionIssueError(errors)) {
|
||||
throw new UserError(
|
||||
'EAS_UPLOAD_TO_ASC_SDK_VERSION_ISSUE',
|
||||
'Build upload was rejected by App Store Connect because the IPA was built with an iOS SDK that is too old for current App Store Connect requirements. ' +
|
||||
'In an Expo project, this usually means the build used an outdated EAS iOS image or the project still depends on an Expo SDK / native setup that does not support the required Xcode toolchain. ' +
|
||||
'Upgrade to a supported Expo SDK if needed and/or select a newer iOS image in `eas.json`, rebuild, and submit again.',
|
||||
{
|
||||
docsUrl: 'https://docs.expo.dev/workflow/upgrading-expo-sdk-walkthrough/',
|
||||
}
|
||||
);
|
||||
}
|
||||
if (isInvalidBundleIdentifierError(errors)) {
|
||||
const ipaInfoResult = await asyncResult(readIpaInfoAsync(ipaPath));
|
||||
const ipaBundleIdentifier = ipaInfoResult.ok
|
||||
? ipaInfoResult.value.bundleIdentifier
|
||||
: null;
|
||||
|
||||
let visibleAppsSummary: string | null = null;
|
||||
try {
|
||||
const apps = await AscApiUtils.getAppsAsync({ client, limit: 5 });
|
||||
visibleAppsSummary = AscApiUtils.formatAppsList(apps);
|
||||
} catch {
|
||||
// Ok to fail, this is just trying to be helpful.
|
||||
}
|
||||
|
||||
throw new UserError(
|
||||
'EAS_UPLOAD_TO_ASC_INVALID_BUNDLE_ID',
|
||||
`Build upload was rejected by App Store Connect because the app bundle identifier in the IPA does not match the selected App Store Connect app.\n\n` +
|
||||
@@ -279,7 +298,12 @@ export function createUploadToAscBuildFunction(): BuildFunction {
|
||||
`App Store Connect app bundle identifier: ${ascAppBundleIdentifier}\n\n` +
|
||||
'Bundle identifier cannot be changed for an existing App Store Connect app. ' +
|
||||
'If you selected the wrong app, change the Apple app identifier in the submit profile. ' +
|
||||
'If you selected the right app, you may want to select a different build to upload (or rebuild with a different profile).'
|
||||
'If you selected the right app, you may want to select a different build to upload (or rebuild with a different profile).' +
|
||||
'\n\nOther App Store Connect apps visible to this API key:\n' +
|
||||
(visibleAppsSummary ?? ' (unable to retrieve)'),
|
||||
{
|
||||
docsUrl: 'https://expo.fyi/asc-app-id',
|
||||
}
|
||||
);
|
||||
}
|
||||
if (isMissingPurposeStringError(errors)) {
|
||||
@@ -331,6 +355,10 @@ export function isClosedVersionTrainError(messages: { code: string }[]): boolean
|
||||
);
|
||||
}
|
||||
|
||||
export function isSdkVersionIssueError(messages: { code: string }[]): boolean {
|
||||
return messages.length > 0 && messages.every(message => message.code === '90725');
|
||||
}
|
||||
|
||||
export function isInvalidBundleIdentifierError(messages: { code: string }[]): boolean {
|
||||
return (
|
||||
messages.length > 0 && messages.every(message => ['90054', '90055'].includes(message.code))
|
||||
|
||||
@@ -34,11 +34,13 @@ export namespace AscApiUtils {
|
||||
|
||||
let visibleAppsSummary: string | null = null;
|
||||
try {
|
||||
visibleAppsSummary = await getVisibleAppsSummaryAsync(client);
|
||||
const apps = await AscApiUtils.getAppsAsync({ client, limit: 10 });
|
||||
visibleAppsSummary = AscApiUtils.formatAppsList(apps);
|
||||
} catch {
|
||||
// Don't hide the original NOT_FOUND error with a secondary lookup failure.
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new UserError(
|
||||
'EAS_UPLOAD_TO_ASC_APP_NOT_FOUND',
|
||||
`App Store Connect app for application identifier ${appleAppIdentifier} was not found. ` +
|
||||
@@ -108,19 +110,26 @@ export namespace AscApiUtils {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function getVisibleAppsSummaryAsync(
|
||||
client: Pick<AscApiClient, 'getAsync'>
|
||||
): Promise<string | null> {
|
||||
const appsResponse = await client.getAsync('/v1/apps', {
|
||||
'fields[apps]': ['bundleId', 'name'],
|
||||
limit: 10,
|
||||
});
|
||||
if (appsResponse.data.length === 0) {
|
||||
return ' (none)';
|
||||
export async function getAppsAsync({
|
||||
client,
|
||||
limit,
|
||||
}: {
|
||||
client: Pick<AscApiClient, 'getAsync'>;
|
||||
limit?: number;
|
||||
}): Promise<AscApiClientGetApi['/v1/apps']['response']['data']> {
|
||||
const appsResponse = await client.getAsync('/v1/apps', {
|
||||
'fields[apps]': ['bundleId', 'name'],
|
||||
limit: limit ?? 10,
|
||||
});
|
||||
return appsResponse.data;
|
||||
}
|
||||
|
||||
export function formatAppsList(apps: AscApiClientGetApi['/v1/apps']['response']['data']): string {
|
||||
return (
|
||||
apps
|
||||
.map(app => `- ${app.attributes.name} (${app.attributes.bundleId}) (ID: ${app.id})`)
|
||||
.join('\n') || ' (none)'
|
||||
);
|
||||
}
|
||||
return appsResponse.data
|
||||
.map(app => `- ${app.attributes.name} (${app.attributes.bundleId}) (ID: ${app.id})`)
|
||||
.join('\n');
|
||||
}
|
||||
@@ -60,8 +60,8 @@ describe('AscApiUtils', () => {
|
||||
expect.objectContaining({
|
||||
errorCode: 'EAS_UPLOAD_TO_ASC_APP_NOT_FOUND',
|
||||
docsUrl: 'https://expo.fyi/asc-app-id',
|
||||
message: expect.stringContaining(
|
||||
'App Store Connect app for application identifier 1234567890 was not found'
|
||||
message: expect.stringMatching(
|
||||
/App Store Connect app for application identifier 1234567890 was not found[\s\S]*- Visible App \(com\.visible\.app\) \(ID: 1111111111\)/
|
||||
),
|
||||
})
|
||||
);
|
||||
@@ -96,6 +96,31 @@ describe('AscApiUtils', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatAppsList', () => {
|
||||
it('formats visible apps', () => {
|
||||
expect(
|
||||
AscApiUtils.formatAppsList([
|
||||
{
|
||||
type: 'apps',
|
||||
id: '1111111111',
|
||||
attributes: { name: 'Visible App', bundleId: 'com.visible.app' },
|
||||
},
|
||||
{
|
||||
type: 'apps',
|
||||
id: '2222222222',
|
||||
attributes: { name: 'Second App', bundleId: 'com.second.app' },
|
||||
},
|
||||
])
|
||||
).toBe(
|
||||
'- Visible App (com.visible.app) (ID: 1111111111)\n- Second App (com.second.app) (ID: 2222222222)'
|
||||
);
|
||||
});
|
||||
|
||||
it('returns a placeholder when no visible apps are found', () => {
|
||||
expect(AscApiUtils.formatAppsList([])).toBe(' (none)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBuildUploadAsync', () => {
|
||||
it('throws UserError when ASC duplicate version error is returned', async () => {
|
||||
const payload = {
|
||||
|
||||
@@ -391,6 +391,38 @@ export namespace AndroidEmulatorUtils {
|
||||
);
|
||||
}
|
||||
|
||||
export async function disableWindowAndTransitionAnimationsAsync({
|
||||
serialId,
|
||||
env,
|
||||
logger,
|
||||
}: {
|
||||
serialId: AndroidDeviceSerialId;
|
||||
env: NodeJS.ProcessEnv;
|
||||
logger: bunyan;
|
||||
}): Promise<void> {
|
||||
logger.info('Disabling Android emulator window animations.');
|
||||
try {
|
||||
await spawn(
|
||||
'adb',
|
||||
['-s', serialId, 'shell', 'settings', 'put', 'global', 'window_animation_scale', '0'],
|
||||
{ env }
|
||||
);
|
||||
} catch (err) {
|
||||
logger.warn({ err }, 'Failed to disable Android emulator window animations.');
|
||||
}
|
||||
|
||||
logger.info('Disabling Android emulator transition animations.');
|
||||
try {
|
||||
await spawn(
|
||||
'adb',
|
||||
['-s', serialId, 'shell', 'settings', 'put', 'global', 'transition_animation_scale', '0'],
|
||||
{ env }
|
||||
);
|
||||
} catch (err) {
|
||||
logger.warn({ err }, 'Failed to disable Android emulator transition animations.');
|
||||
}
|
||||
}
|
||||
|
||||
async function hasNetworkConnectionAsync({
|
||||
serialId,
|
||||
env,
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,120 @@
|
||||
import fs from 'fs-extra';
|
||||
import nock from 'nock';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import { createMockLogger } from '../../__tests__/utils/logger';
|
||||
|
||||
jest.unmock('fs');
|
||||
jest.unmock('node:fs');
|
||||
jest.unmock('fs/promises');
|
||||
jest.unmock('node:fs/promises');
|
||||
|
||||
describe('precompiledModules integration', () => {
|
||||
beforeAll(() => {
|
||||
nock.disableNetConnect();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
nock.enableNetConnect();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
nock.cleanAll();
|
||||
});
|
||||
|
||||
it('merges the extracted debug and release xcframework trees', async () => {
|
||||
const homeDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'precompiled-modules-home-'));
|
||||
const previousHome = process.env.HOME;
|
||||
process.env.HOME = homeDirectory;
|
||||
|
||||
try {
|
||||
const fixturesDirectory = path.join(__dirname, 'fixtures', 'precompiledModules');
|
||||
const debugArchive = await fs.readFile(
|
||||
path.join(fixturesDirectory, 'xcframeworks-Debug.zip')
|
||||
);
|
||||
const releaseArchive = await fs.readFile(
|
||||
path.join(fixturesDirectory, 'xcframeworks-Release.zip')
|
||||
);
|
||||
|
||||
nock('https://fixtures.expo.test')
|
||||
.get('/xcframeworks-Debug.zip')
|
||||
.reply(200, debugArchive, { 'Content-Type': 'application/zip' })
|
||||
.get('/xcframeworks-Release.zip')
|
||||
.reply(200, releaseArchive, { 'Content-Type': 'application/zip' });
|
||||
|
||||
jest.resetModules();
|
||||
jest.doMock('os', () => ({
|
||||
...jest.requireActual('os'),
|
||||
homedir: () => homeDirectory,
|
||||
}));
|
||||
const {
|
||||
PRECOMPILED_MODULES_PATH,
|
||||
startPreparingPrecompiledDependencies,
|
||||
waitForPrecompiledModulesPreparationAsync,
|
||||
} = await import('../precompiledModules');
|
||||
|
||||
startPreparingPrecompiledDependencies(
|
||||
{
|
||||
logger: createMockLogger(),
|
||||
env: {},
|
||||
} as any,
|
||||
[
|
||||
'https://fixtures.expo.test/xcframeworks-Debug.zip',
|
||||
'https://fixtures.expo.test/xcframeworks-Release.zip',
|
||||
]
|
||||
);
|
||||
await waitForPrecompiledModulesPreparationAsync();
|
||||
|
||||
expect(PRECOMPILED_MODULES_PATH).toBe(
|
||||
path.join(homeDirectory, '.expo', 'precompiled-modules')
|
||||
);
|
||||
|
||||
await expect(
|
||||
fs.readFile(
|
||||
path.join(
|
||||
PRECOMPILED_MODULES_PATH,
|
||||
'expo-modules-core/output/debug/xcframeworks/ExpoModulesCore.tar.gz'
|
||||
),
|
||||
'utf8'
|
||||
)
|
||||
).resolves.toBe('debug expo-modules-core fixture\n');
|
||||
await expect(
|
||||
fs.readFile(
|
||||
path.join(
|
||||
PRECOMPILED_MODULES_PATH,
|
||||
'expo-modules-core/output/release/xcframeworks/ExpoModulesCore.tar.gz'
|
||||
),
|
||||
'utf8'
|
||||
)
|
||||
).resolves.toBe('release expo-modules-core fixture\n');
|
||||
await expect(
|
||||
fs.readFile(
|
||||
path.join(
|
||||
PRECOMPILED_MODULES_PATH,
|
||||
'expo-camera/output/debug/xcframeworks/ExpoCamera.tar.gz'
|
||||
),
|
||||
'utf8'
|
||||
)
|
||||
).resolves.toBe('debug expo-camera fixture\n');
|
||||
await expect(
|
||||
fs.readFile(
|
||||
path.join(
|
||||
PRECOMPILED_MODULES_PATH,
|
||||
'expo-application/output/release/xcframeworks/EXApplication.tar.gz'
|
||||
),
|
||||
'utf8'
|
||||
)
|
||||
).resolves.toBe('release expo-application fixture\n');
|
||||
} finally {
|
||||
jest.dontMock('os');
|
||||
jest.resetModules();
|
||||
if (previousHome === undefined) {
|
||||
delete process.env.HOME;
|
||||
} else {
|
||||
process.env.HOME = previousHome;
|
||||
}
|
||||
await fs.remove(homeDirectory);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
|
||||
import { createMockLogger } from '../../__tests__/utils/logger';
|
||||
import { AndroidEmulatorUtils } from '../AndroidEmulatorUtils';
|
||||
import { retryAsync } from '../retry';
|
||||
|
||||
@@ -110,6 +111,87 @@ describe('AndroidEmulatorUtils', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe(AndroidEmulatorUtils.disableWindowAndTransitionAnimationsAsync, () => {
|
||||
it('sets window and transition animation scales to zero', async () => {
|
||||
const logger = createMockLogger();
|
||||
|
||||
await AndroidEmulatorUtils.disableWindowAndTransitionAnimationsAsync({
|
||||
serialId: 'emulator-5554' as any,
|
||||
env: process.env,
|
||||
logger,
|
||||
});
|
||||
|
||||
expect(logger.info).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'Disabling Android emulator window animations.'
|
||||
);
|
||||
expect(mockedSpawn).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'adb',
|
||||
[
|
||||
'-s',
|
||||
'emulator-5554',
|
||||
'shell',
|
||||
'settings',
|
||||
'put',
|
||||
'global',
|
||||
'window_animation_scale',
|
||||
'0',
|
||||
],
|
||||
{ env: process.env }
|
||||
);
|
||||
expect(logger.info).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'Disabling Android emulator transition animations.'
|
||||
);
|
||||
expect(mockedSpawn).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'adb',
|
||||
[
|
||||
'-s',
|
||||
'emulator-5554',
|
||||
'shell',
|
||||
'settings',
|
||||
'put',
|
||||
'global',
|
||||
'transition_animation_scale',
|
||||
'0',
|
||||
],
|
||||
{ env: process.env }
|
||||
);
|
||||
});
|
||||
|
||||
it('logs and swallows failures when disabling animations', async () => {
|
||||
const logger = createMockLogger();
|
||||
mockedSpawn
|
||||
.mockRejectedValueOnce(new Error('window failed'))
|
||||
.mockRejectedValueOnce(new Error('transition failed'));
|
||||
|
||||
await expect(
|
||||
AndroidEmulatorUtils.disableWindowAndTransitionAnimationsAsync({
|
||||
serialId: 'emulator-5554' as any,
|
||||
env: process.env,
|
||||
logger,
|
||||
})
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
expect(logger.warn).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
err: expect.objectContaining({ message: 'window failed' }),
|
||||
}),
|
||||
'Failed to disable Android emulator window animations.'
|
||||
);
|
||||
expect(logger.warn).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
err: expect.objectContaining({ message: 'transition failed' }),
|
||||
}),
|
||||
'Failed to disable Android emulator transition animations.'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe(AndroidEmulatorUtils.stopAsync, () => {
|
||||
it('kills emulator and waits for it to detach', async () => {
|
||||
mockedSpawn.mockImplementation((async (_command: string, args: string[]) => {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { bunyan } from '@expo/logger';
|
||||
|
||||
import { readAppConfig } from '../appConfig';
|
||||
|
||||
jest.mock('@expo/env', () => ({
|
||||
load: jest.fn(() => ({ FROM_DOTENV: 'true' })),
|
||||
}));
|
||||
|
||||
jest.mock('@expo/config', () => ({
|
||||
getConfig: jest.fn(() => ({
|
||||
exp: { name: 'fallback-app', slug: 'fallback-app' },
|
||||
})),
|
||||
}));
|
||||
|
||||
jest.mock('../expoCli');
|
||||
|
||||
const { expoCommandAsync } = jest.requireMock('../expoCli') as {
|
||||
expoCommandAsync: jest.Mock;
|
||||
};
|
||||
|
||||
const { getConfig } = jest.requireMock('@expo/config') as {
|
||||
getConfig: jest.Mock;
|
||||
};
|
||||
|
||||
const { load: loadEnv } = jest.requireMock('@expo/env') as {
|
||||
load: jest.Mock;
|
||||
};
|
||||
|
||||
const logger = { warn: jest.fn(), info: jest.fn(), error: jest.fn() } as unknown as bunyan;
|
||||
|
||||
const baseParams = {
|
||||
projectDir: '/project',
|
||||
env: { NODE_ENV: 'production' },
|
||||
logger,
|
||||
};
|
||||
|
||||
describe(readAppConfig, () => {
|
||||
it('returns config from expo CLI when it succeeds', async () => {
|
||||
const config = { exp: { name: 'test-app', slug: 'test-app' } };
|
||||
expoCommandAsync.mockResolvedValue({ stdout: JSON.stringify(config) });
|
||||
|
||||
const result = await readAppConfig(baseParams);
|
||||
|
||||
expect(result).toEqual(config);
|
||||
expect(expoCommandAsync).toHaveBeenCalledWith(
|
||||
'/project',
|
||||
['config', '--json', '--full', '--type', 'public'],
|
||||
{ env: baseParams.env }
|
||||
);
|
||||
expect(getConfig).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('falls back to @expo/config when expo CLI fails', async () => {
|
||||
expoCommandAsync.mockRejectedValue(new Error('expo not found'));
|
||||
|
||||
const result = await readAppConfig(baseParams);
|
||||
|
||||
expect(result).toEqual({ exp: { name: 'fallback-app', slug: 'fallback-app' } });
|
||||
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('expo not found'));
|
||||
expect(getConfig).toHaveBeenCalledWith('/project', {
|
||||
skipSDKVersionRequirement: true,
|
||||
isPublicConfig: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when expo CLI returns invalid JSON and @expo/config also fails', async () => {
|
||||
expoCommandAsync.mockResolvedValue({ stdout: 'not json' });
|
||||
getConfig.mockImplementation(() => {
|
||||
throw new Error('@expo/config failed');
|
||||
});
|
||||
|
||||
await expect(readAppConfig(baseParams)).rejects.toThrow('@expo/config failed');
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Failed to parse JSON output from 'expo config'")
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when expo CLI output is missing exp field and @expo/config also fails', async () => {
|
||||
expoCommandAsync.mockResolvedValue({ stdout: JSON.stringify({ other: 'data' }) });
|
||||
getConfig.mockImplementation(() => {
|
||||
throw new Error('@expo/config failed');
|
||||
});
|
||||
|
||||
await expect(readAppConfig(baseParams)).rejects.toThrow('@expo/config failed');
|
||||
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining("missing 'exp' field"));
|
||||
});
|
||||
|
||||
it('loads env vars from dotenv for SDK >= 49', async () => {
|
||||
const config = { exp: { name: 'test-app', slug: 'test-app' } };
|
||||
expoCommandAsync.mockResolvedValue({ stdout: JSON.stringify(config) });
|
||||
|
||||
await readAppConfig({ ...baseParams, sdkVersion: '49.0.0' });
|
||||
|
||||
expect(loadEnv).toHaveBeenCalledWith('/project');
|
||||
expect(expoCommandAsync).toHaveBeenCalledWith('/project', expect.any(Array), {
|
||||
env: { NODE_ENV: 'production', FROM_DOTENV: 'true' },
|
||||
});
|
||||
});
|
||||
|
||||
it('does not load env vars from dotenv for SDK < 49', async () => {
|
||||
const config = { exp: { name: 'test-app', slug: 'test-app' } };
|
||||
expoCommandAsync.mockResolvedValue({ stdout: JSON.stringify(config) });
|
||||
|
||||
await readAppConfig({ ...baseParams, sdkVersion: '48.0.0' });
|
||||
|
||||
expect(loadEnv).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import resolveFrom from 'resolve-from';
|
||||
import spawnAsync from '@expo/turtle-spawn';
|
||||
|
||||
import { expoCommandAsync, ExpoCLIModuleNotFoundError } from '../expoCli';
|
||||
|
||||
jest.mock('resolve-from', () => ({
|
||||
__esModule: true,
|
||||
default: Object.assign(jest.fn(), {
|
||||
silent: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('@expo/turtle-spawn', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn().mockResolvedValue({ stdout: '', stderr: '' }),
|
||||
}));
|
||||
|
||||
const mockedResolveFrom = resolveFrom as jest.MockedFunction<typeof resolveFrom> & {
|
||||
silent: jest.MockedFunction<typeof resolveFrom.silent>;
|
||||
};
|
||||
|
||||
describe(expoCommandAsync, () => {
|
||||
it('resolves expo CLI and spawns with correct args', async () => {
|
||||
mockedResolveFrom.silent.mockReturnValue('/project/node_modules/expo/bin/cli');
|
||||
|
||||
await expoCommandAsync('/project', ['config', '--json'], { env: { FOO: 'bar' } });
|
||||
|
||||
expect(spawnAsync).toHaveBeenCalledWith(
|
||||
'/project/node_modules/expo/bin/cli',
|
||||
['config', '--json'],
|
||||
expect.objectContaining({
|
||||
cwd: '/project',
|
||||
stdio: 'pipe',
|
||||
env: { FOO: 'bar', EXPO_DEBUG: '0' },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('falls back to expo/bin/cli.js when silent resolve returns null', async () => {
|
||||
mockedResolveFrom.silent.mockReturnValue(undefined);
|
||||
mockedResolveFrom.mockReturnValue('/project/node_modules/expo/bin/cli.js');
|
||||
|
||||
await expoCommandAsync('/project', ['config'], { env: {} });
|
||||
|
||||
expect(spawnAsync).toHaveBeenCalledWith(
|
||||
'/project/node_modules/expo/bin/cli.js',
|
||||
['config'],
|
||||
expect.any(Object)
|
||||
);
|
||||
});
|
||||
|
||||
it('throws ExpoCLIModuleNotFoundError when expo is not installed', async () => {
|
||||
mockedResolveFrom.silent.mockReturnValue(undefined);
|
||||
const moduleError = new Error('Cannot find module');
|
||||
(moduleError as any).code = 'MODULE_NOT_FOUND';
|
||||
mockedResolveFrom.mockImplementation(() => {
|
||||
throw moduleError;
|
||||
});
|
||||
|
||||
await expect(expoCommandAsync('/project', ['config'], { env: {} })).rejects.toThrow(
|
||||
ExpoCLIModuleNotFoundError
|
||||
);
|
||||
});
|
||||
|
||||
it('overrides EXPO_DEBUG to 0', async () => {
|
||||
mockedResolveFrom.silent.mockReturnValue('/project/node_modules/expo/bin/cli');
|
||||
|
||||
await expoCommandAsync('/project', ['config'], { env: { EXPO_DEBUG: '1' } });
|
||||
|
||||
expect(spawnAsync).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.any(Array),
|
||||
expect.objectContaining({
|
||||
env: expect.objectContaining({ EXPO_DEBUG: '0' }),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,14 @@
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import fs from 'fs-extra';
|
||||
import { vol } from 'memfs';
|
||||
import path from 'path';
|
||||
import semver from 'semver';
|
||||
|
||||
import {
|
||||
findPackagerRootDir,
|
||||
getPackageVersionFromPackageJson,
|
||||
resolvePackageManager,
|
||||
resolvePackageVersionAsync,
|
||||
shouldUseFrozenLockfile,
|
||||
} from '../packageManager';
|
||||
|
||||
@@ -68,6 +71,33 @@ describe(resolvePackageManager, () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe(resolvePackageVersionAsync, () => {
|
||||
const logger = {
|
||||
debug: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
} as unknown as bunyan;
|
||||
|
||||
it('should resolve version from package name and dist tag', async () => {
|
||||
const version = await resolvePackageVersionAsync({
|
||||
logger,
|
||||
packageName: '@expo/repack-app',
|
||||
distTag: 'latest',
|
||||
});
|
||||
expect(semver.valid(version)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should return null if version cannot be resolved', async () => {
|
||||
const version = await resolvePackageVersionAsync({
|
||||
logger,
|
||||
packageName: '@expo/repack-app',
|
||||
distTag: 'nonexistent-dist-tag',
|
||||
});
|
||||
expect(version).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe(findPackagerRootDir, () => {
|
||||
beforeEach(() => {
|
||||
vol.reset();
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import downloadFile from '@expo/downloader';
|
||||
import { mkdirp, mkdtemp, move, remove } from 'fs-extra';
|
||||
import StreamZip from 'node-stream-zip';
|
||||
|
||||
import {
|
||||
PRECOMPILED_MODULES_PATH,
|
||||
startPreparingPrecompiledDependencies,
|
||||
waitForPrecompiledModulesPreparationAsync,
|
||||
} from '../precompiledModules';
|
||||
import { createMockLogger } from '../../__tests__/utils/logger';
|
||||
import { BuildContext } from '../../context';
|
||||
|
||||
jest.mock('@expo/downloader');
|
||||
jest.mock('fs-extra');
|
||||
jest.mock('node-stream-zip', () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
async: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('precompiledModules', () => {
|
||||
const extract = jest.fn();
|
||||
const close = jest.fn();
|
||||
const getMkdtempPath = jest.fn();
|
||||
|
||||
const createCtx = (env: Record<string, string | undefined> = {}): BuildContext =>
|
||||
({
|
||||
logger: createMockLogger(),
|
||||
env,
|
||||
}) as unknown as BuildContext;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.mocked(remove).mockImplementation(async () => undefined as any);
|
||||
jest.mocked(mkdirp).mockImplementation(async () => undefined as any);
|
||||
jest.mocked(move).mockImplementation(async () => undefined as any);
|
||||
getMkdtempPath.mockReset();
|
||||
getMkdtempPath
|
||||
.mockReturnValueOnce('/tmp/precompiled-modules-archive')
|
||||
.mockReturnValueOnce('/tmp/precompiled-modules-staging');
|
||||
jest.mocked(mkdtemp).mockImplementation(async () => getMkdtempPath() as any);
|
||||
jest.mocked(downloadFile).mockReset();
|
||||
extract.mockReset().mockResolvedValue(undefined);
|
||||
close.mockReset().mockResolvedValue(undefined);
|
||||
jest.mocked(StreamZip.async).mockImplementation(
|
||||
() =>
|
||||
({
|
||||
extract,
|
||||
close,
|
||||
}) as any
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('downloads through CocoaPods proxy when enabled', async () => {
|
||||
jest.mocked(downloadFile).mockResolvedValue(undefined);
|
||||
|
||||
startPreparingPrecompiledDependencies(
|
||||
createCtx({ EAS_BUILD_COCOAPODS_CACHE_URL: 'http://localhost:9001' }),
|
||||
[
|
||||
'https://storage.googleapis.com/eas-build-precompiled-modules-production/ios/precompiled-modules-0.zip',
|
||||
]
|
||||
);
|
||||
|
||||
await waitForPrecompiledModulesPreparationAsync();
|
||||
|
||||
expect(downloadFile).toHaveBeenCalledWith(
|
||||
'http://localhost:9001/storage.googleapis.com/eas-build-precompiled-modules-production/ios/precompiled-modules-0.zip',
|
||||
'/tmp/precompiled-modules-archive/precompiled-modules-0.zip',
|
||||
{ retry: 3 }
|
||||
);
|
||||
});
|
||||
|
||||
it('falls back to the direct url when CocoaPods proxy download fails', async () => {
|
||||
jest
|
||||
.mocked(downloadFile)
|
||||
.mockRejectedValueOnce(new Error('proxy failed'))
|
||||
.mockResolvedValueOnce(undefined);
|
||||
|
||||
startPreparingPrecompiledDependencies(
|
||||
createCtx({ EAS_BUILD_COCOAPODS_CACHE_URL: 'http://localhost:9001' }),
|
||||
[
|
||||
'https://storage.googleapis.com/eas-build-precompiled-modules-production/ios/precompiled-modules-0.zip',
|
||||
]
|
||||
);
|
||||
|
||||
await waitForPrecompiledModulesPreparationAsync();
|
||||
|
||||
expect(downloadFile).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'http://localhost:9001/storage.googleapis.com/eas-build-precompiled-modules-production/ios/precompiled-modules-0.zip',
|
||||
'/tmp/precompiled-modules-archive/precompiled-modules-0.zip',
|
||||
{ retry: 3 }
|
||||
);
|
||||
expect(downloadFile).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'https://storage.googleapis.com/eas-build-precompiled-modules-production/ios/precompiled-modules-0.zip',
|
||||
'/tmp/precompiled-modules-archive/precompiled-modules-0.zip',
|
||||
{ retry: 3 }
|
||||
);
|
||||
});
|
||||
|
||||
it('extracts all configured archives into the well-known destination path', async () => {
|
||||
jest.mocked(downloadFile).mockResolvedValue(undefined);
|
||||
|
||||
startPreparingPrecompiledDependencies(createCtx(), [
|
||||
'https://storage.googleapis.com/eas-build-precompiled-modules-production/ios/precompiled-modules-0.zip',
|
||||
'https://storage.googleapis.com/eas-build-precompiled-modules-production/ios/precompiled-modules-1.zip',
|
||||
]);
|
||||
|
||||
await waitForPrecompiledModulesPreparationAsync();
|
||||
|
||||
expect(mkdirp).toHaveBeenCalledWith(PRECOMPILED_MODULES_PATH);
|
||||
expect(downloadFile).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'https://storage.googleapis.com/eas-build-precompiled-modules-production/ios/precompiled-modules-0.zip',
|
||||
'/tmp/precompiled-modules-archive/precompiled-modules-0.zip',
|
||||
{ retry: 3 }
|
||||
);
|
||||
expect(downloadFile).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'https://storage.googleapis.com/eas-build-precompiled-modules-production/ios/precompiled-modules-1.zip',
|
||||
'/tmp/precompiled-modules-archive/precompiled-modules-1.zip',
|
||||
{ retry: 3 }
|
||||
);
|
||||
expect(extract).toHaveBeenNthCalledWith(1, null, '/tmp/precompiled-modules-staging');
|
||||
expect(extract).toHaveBeenNthCalledWith(2, null, '/tmp/precompiled-modules-staging');
|
||||
expect(move).toHaveBeenCalledWith('/tmp/precompiled-modules-staging', PRECOMPILED_MODULES_PATH);
|
||||
});
|
||||
|
||||
it('leaves the destination empty when preparation fails', async () => {
|
||||
jest.mocked(downloadFile).mockResolvedValue(undefined);
|
||||
extract.mockRejectedValueOnce(new Error('extract failed'));
|
||||
|
||||
startPreparingPrecompiledDependencies(createCtx(), [
|
||||
'https://storage.googleapis.com/eas-build-precompiled-modules-production/ios/precompiled-modules-0.zip',
|
||||
]);
|
||||
|
||||
await expect(waitForPrecompiledModulesPreparationAsync()).rejects.toThrow('extract failed');
|
||||
|
||||
expect(move).not.toHaveBeenCalled();
|
||||
expect(remove).toHaveBeenCalledWith('/tmp/precompiled-modules-staging');
|
||||
expect(remove).toHaveBeenCalledWith(PRECOMPILED_MODULES_PATH);
|
||||
expect(mkdirp).toHaveBeenCalledWith(PRECOMPILED_MODULES_PATH);
|
||||
});
|
||||
|
||||
it('throws when precompiled dependencies are still not ready after 30 seconds', async () => {
|
||||
jest.useFakeTimers();
|
||||
jest.mocked(downloadFile).mockImplementation(() => new Promise<void>(() => {}) as any);
|
||||
|
||||
startPreparingPrecompiledDependencies(createCtx(), [
|
||||
'https://example.com/xcframeworks-Debug.zip',
|
||||
]);
|
||||
|
||||
const waitPromise = waitForPrecompiledModulesPreparationAsync();
|
||||
const waitExpectation = expect(waitPromise).rejects.toThrow(
|
||||
'Timed out waiting for precompiled dependencies after 30 seconds'
|
||||
);
|
||||
|
||||
await Promise.resolve();
|
||||
|
||||
await jest.advanceTimersByTimeAsync(30_000);
|
||||
await waitExpectation;
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,7 @@ describe(runExpoCliCommand, () => {
|
||||
|
||||
const mockCtx = mock<BuildContext<Android.Job>>();
|
||||
when(mockCtx.packageManager).thenReturn(PackageManager.NPM);
|
||||
when(mockCtx.appConfig).thenReturn(expoConfig);
|
||||
when(mockCtx.appConfig).thenReturn(Promise.resolve(expoConfig));
|
||||
const ctx = instance(mockCtx);
|
||||
|
||||
void runExpoCliCommand({ args: ['doctor'], options: {}, packageManager: ctx.packageManager });
|
||||
@@ -38,7 +38,7 @@ describe(runExpoCliCommand, () => {
|
||||
|
||||
const mockCtx = mock<BuildContext<Android.Job>>();
|
||||
when(mockCtx.packageManager).thenReturn(PackageManager.NPM);
|
||||
when(mockCtx.appConfig).thenReturn(expoConfig);
|
||||
when(mockCtx.appConfig).thenReturn(Promise.resolve(expoConfig));
|
||||
const ctx = instance(mockCtx);
|
||||
|
||||
void runExpoCliCommand({ args: ['doctor'], options: {}, packageManager: ctx.packageManager });
|
||||
@@ -52,7 +52,7 @@ describe(runExpoCliCommand, () => {
|
||||
|
||||
const mockCtx = mock<BuildContext<Android.Job>>();
|
||||
when(mockCtx.packageManager).thenReturn(PackageManager.PNPM);
|
||||
when(mockCtx.appConfig).thenReturn(expoConfig);
|
||||
when(mockCtx.appConfig).thenReturn(Promise.resolve(expoConfig));
|
||||
const ctx = instance(mockCtx);
|
||||
|
||||
void runExpoCliCommand({ args: ['doctor'], options: {}, packageManager: ctx.packageManager });
|
||||
@@ -66,7 +66,7 @@ describe(runExpoCliCommand, () => {
|
||||
|
||||
const mockCtx = mock<BuildContext<Android.Job>>();
|
||||
when(mockCtx.packageManager).thenReturn(PackageManager.BUN);
|
||||
when(mockCtx.appConfig).thenReturn(expoConfig);
|
||||
when(mockCtx.appConfig).thenReturn(Promise.resolve(expoConfig));
|
||||
const ctx = instance(mockCtx);
|
||||
|
||||
void runExpoCliCommand({ args: ['doctor'], options: {}, packageManager: ctx.packageManager });
|
||||
|
||||
@@ -3,18 +3,70 @@ import { Env } from '@expo/eas-build-job';
|
||||
import { load } from '@expo/env';
|
||||
import { LoggerLevel, bunyan } from '@expo/logger';
|
||||
import semver from 'semver';
|
||||
import { expoCommandAsync } from './expoCli';
|
||||
|
||||
export function readAppConfig({
|
||||
projectDir,
|
||||
env,
|
||||
logger,
|
||||
sdkVersion,
|
||||
}: {
|
||||
interface ReadAppConfigParams {
|
||||
projectDir: string;
|
||||
env: Env;
|
||||
logger: bunyan;
|
||||
sdkVersion?: string;
|
||||
}): ProjectConfig {
|
||||
}
|
||||
|
||||
export async function readAppConfig(params: ReadAppConfigParams): Promise<ProjectConfig> {
|
||||
const shouldLoadEnvVarsFromDotenvFile =
|
||||
params.sdkVersion && semver.satisfies(params.sdkVersion, '>=49');
|
||||
if (shouldLoadEnvVarsFromDotenvFile) {
|
||||
const envVarsFromDotenvFile = load(params.projectDir) as Env;
|
||||
const env = { ...params.env, ...envVarsFromDotenvFile };
|
||||
params = { ...params, env };
|
||||
}
|
||||
|
||||
// Reading the app config is done in two steps/attempts. We first attempt to run `expo config` as a CLI,
|
||||
try {
|
||||
return await getAppConfigFromExpo(params);
|
||||
} catch (error: any) {
|
||||
params.logger.warn(
|
||||
'Failed to read the app config file with `expo config` command:\n' +
|
||||
`${error?.message || error}`
|
||||
);
|
||||
}
|
||||
|
||||
// If this fails, we fall back to directly using `@expo/config`
|
||||
// This can fail, since it's tied to a specific SDK version, so reading for older SDKs isn't guaranteed to work
|
||||
return getAppConfigFromExpoConfig(params);
|
||||
}
|
||||
|
||||
async function getAppConfigFromExpo({
|
||||
projectDir,
|
||||
env,
|
||||
}: ReadAppConfigParams): Promise<ProjectConfig> {
|
||||
const result = await expoCommandAsync(
|
||||
projectDir,
|
||||
['config', '--json', '--full', '--type', 'public'],
|
||||
{ env }
|
||||
);
|
||||
|
||||
let parsed: any;
|
||||
try {
|
||||
parsed = JSON.parse(result.stdout);
|
||||
} catch {
|
||||
throw new Error(
|
||||
`Failed to parse JSON output from 'expo config'.\nOutput: ${result.stdout.slice(0, 500)}`
|
||||
);
|
||||
}
|
||||
|
||||
if (!('exp' in parsed)) {
|
||||
throw new Error(`Unexpected output from 'expo config': missing 'exp' field.`);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function getAppConfigFromExpoConfig({
|
||||
projectDir,
|
||||
env,
|
||||
logger,
|
||||
}: ReadAppConfigParams): ProjectConfig {
|
||||
const originalProcessExit = process.exit;
|
||||
const originalProcessCwd = process.cwd;
|
||||
const originalStdoutWrite = process.stdout.write;
|
||||
@@ -22,11 +74,8 @@ export function readAppConfig({
|
||||
const originalProcessEnv = process.env;
|
||||
|
||||
const stdoutStore: { text: string; level: LoggerLevel }[] = [];
|
||||
const shouldLoadEnvVarsFromDotenvFile = sdkVersion && semver.satisfies(sdkVersion, '>=49');
|
||||
const envVarsFromDotenvFile = shouldLoadEnvVarsFromDotenvFile ? load(projectDir) : {};
|
||||
const newEnvsToUse = { ...env, ...envVarsFromDotenvFile };
|
||||
try {
|
||||
process.env = newEnvsToUse;
|
||||
process.env = env;
|
||||
process.exit = () => {
|
||||
throw new Error('Failed to evaluate app config file');
|
||||
};
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import resolveFrom from 'resolve-from';
|
||||
import spawnAsync, { type SpawnOptions } from '@expo/turtle-spawn';
|
||||
|
||||
export class ExpoCLIModuleNotFoundError extends Error {}
|
||||
|
||||
function resolveExpoCLI(projectRoot: string): string {
|
||||
try {
|
||||
return (
|
||||
resolveFrom.silent(projectRoot, 'expo/bin/cli') ?? resolveFrom(projectRoot, 'expo/bin/cli.js')
|
||||
);
|
||||
} catch (e: any) {
|
||||
if (e.code === 'MODULE_NOT_FOUND') {
|
||||
throw new ExpoCLIModuleNotFoundError(`The \`expo\` package was not found.`);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export async function expoCommandAsync(
|
||||
projectDir: string,
|
||||
args: string[],
|
||||
options: Omit<SpawnOptions, 'cwd'>
|
||||
) {
|
||||
const expoCliPath = resolveExpoCLI(projectDir);
|
||||
return spawnAsync(expoCliPath, args, {
|
||||
cwd: projectDir,
|
||||
stdio: 'pipe',
|
||||
...options,
|
||||
env: {
|
||||
...options.env,
|
||||
// NOTE: If we're reading user configs, if a user has set this, it might cause excessive output
|
||||
// that can stop the command from being readable
|
||||
EXPO_DEBUG: '0',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -120,7 +120,7 @@ This would cause any updates published on the local machine to not be compatible
|
||||
);
|
||||
}
|
||||
|
||||
if (isEASUpdateConfigured(ctx)) {
|
||||
if (await isEASUpdateConfigured(ctx)) {
|
||||
if (ctx.job.updates?.channel !== undefined) {
|
||||
await configureEASExpoUpdatesAsync(ctx);
|
||||
} else {
|
||||
@@ -134,7 +134,7 @@ This would cause any updates published on the local machine to not be compatible
|
||||
} else if (isDevelopmentClient) {
|
||||
// NO-OP: Development clients don't need to have a channel set
|
||||
} else {
|
||||
const easUpdateUrl = ctx.appConfig.updates?.url ?? null;
|
||||
const easUpdateUrl = (await ctx.appConfig).updates?.url ?? null;
|
||||
const jobProfile = ctx.job.buildProfile ?? null;
|
||||
ctx.logger.warn(
|
||||
`This build has an invalid EAS Update configuration: update.url is set to "${easUpdateUrl}" in app config, but a channel is not specified${
|
||||
@@ -220,8 +220,8 @@ export async function getRuntimeVersionAsync(ctx: BuildContext<Job>): Promise<st
|
||||
}
|
||||
}
|
||||
|
||||
export function isEASUpdateConfigured(ctx: BuildContext<Job>): boolean {
|
||||
const rawUrl = ctx.appConfig.updates?.url;
|
||||
export async function isEASUpdateConfigured(ctx: BuildContext<Job>): Promise<boolean> {
|
||||
const rawUrl = (await ctx.appConfig).updates?.url;
|
||||
if (!rawUrl) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import * as PackageManagerUtils from '@expo/package-manager';
|
||||
import { hashFiles } from '@expo/steps';
|
||||
import path from 'path';
|
||||
|
||||
import { findPackagerRootDir } from './packageManager';
|
||||
|
||||
export const GRADLE_CACHE_KEY_PREFIX = 'android-gradle-cache-';
|
||||
|
||||
export async function generateGradleCacheKeyAsync(workingDirectory: string): Promise<string> {
|
||||
const packagerRunDir = findPackagerRootDir(workingDirectory);
|
||||
const manager = PackageManagerUtils.createForProject(packagerRunDir);
|
||||
const lockPath = path.join(packagerRunDir, manager.lockFile);
|
||||
|
||||
try {
|
||||
return `${GRADLE_CACHE_KEY_PREFIX}${hashFiles([lockPath])}`;
|
||||
} catch (err: unknown) {
|
||||
throw new Error(
|
||||
`Failed to read lockfile for Gradle cache key generation: ${err instanceof Error ? err.message : err}`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import * as PackageManagerUtils from '@expo/package-manager';
|
||||
import spawnAsync from '@expo/turtle-spawn';
|
||||
import semver from 'semver';
|
||||
@@ -27,6 +28,34 @@ export function resolvePackageManager(directory: string): PackageManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the version of a package from the dist-tags.
|
||||
* Returns null if the version cannot be resolved.
|
||||
*/
|
||||
export async function resolvePackageVersionAsync({
|
||||
logger,
|
||||
packageName,
|
||||
distTag,
|
||||
}: {
|
||||
logger: bunyan;
|
||||
packageName: string;
|
||||
distTag: string;
|
||||
}): Promise<string | null> {
|
||||
try {
|
||||
const { stdout } = await spawnAsync('npm', ['view', packageName, 'dist-tags', '--json'], {
|
||||
stdio: 'pipe',
|
||||
});
|
||||
const distTags = JSON.parse(stdout);
|
||||
if (distTag in distTags) {
|
||||
return distTags[distTag];
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
logger.warn(`Unable to resolve version for ${packageName}@${distTag}: ${message}`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function findPackagerRootDir(currentDir: string): string {
|
||||
return PackageManagerUtils.resolveWorkspaceRoot(currentDir) ?? currentDir;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import downloadFile from '@expo/downloader';
|
||||
import { bunyan } from '@expo/logger';
|
||||
import fs from 'fs-extra';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import StreamZip from 'node-stream-zip';
|
||||
|
||||
import { BuildContext } from '../context';
|
||||
|
||||
let precompiledModulesPreparationPromise: Promise<void> | null = null;
|
||||
const PRECOMPILED_MODULES_WAIT_TIMEOUT_MS = 30_000;
|
||||
export const PRECOMPILED_MODULES_PATH = path.join(os.homedir(), '.expo', 'precompiled-modules');
|
||||
|
||||
export function shouldUsePrecompiledDependencies(env: Record<string, string | undefined>): boolean {
|
||||
return env.EAS_USE_PRECOMPILED_MODULES === '1';
|
||||
}
|
||||
|
||||
export function maybeStartPreparingPrecompiledModules(
|
||||
ctx: BuildContext,
|
||||
config: { precompiledModulesUrls: string[] }
|
||||
): void {
|
||||
if (!shouldUsePrecompiledDependencies(ctx.env)) {
|
||||
return;
|
||||
}
|
||||
|
||||
startPreparingPrecompiledDependencies(ctx, config.precompiledModulesUrls);
|
||||
}
|
||||
|
||||
export function startPreparingPrecompiledDependencies(ctx: BuildContext, urls: string[]): void {
|
||||
precompiledModulesPreparationPromise = preparePrecompiledDependenciesAsync({
|
||||
logger: ctx.logger,
|
||||
urls,
|
||||
destinationDirectory: PRECOMPILED_MODULES_PATH,
|
||||
cocoapodsProxyUrl: ctx.env.EAS_BUILD_COCOAPODS_CACHE_URL,
|
||||
});
|
||||
}
|
||||
|
||||
export async function waitForPrecompiledModulesPreparationAsync(): Promise<void> {
|
||||
if (!precompiledModulesPreparationPromise) {
|
||||
return;
|
||||
}
|
||||
|
||||
let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
await Promise.race([
|
||||
precompiledModulesPreparationPromise,
|
||||
new Promise<void>((_, reject) => {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
reject(
|
||||
new Error(
|
||||
`Timed out waiting for precompiled dependencies after ${PRECOMPILED_MODULES_WAIT_TIMEOUT_MS / 1000} seconds`
|
||||
)
|
||||
);
|
||||
}, PRECOMPILED_MODULES_WAIT_TIMEOUT_MS);
|
||||
timeoutHandle.unref?.();
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function preparePrecompiledDependenciesAsync({
|
||||
logger,
|
||||
urls,
|
||||
destinationDirectory,
|
||||
cocoapodsProxyUrl,
|
||||
}: {
|
||||
logger: bunyan;
|
||||
urls: string[];
|
||||
destinationDirectory: string;
|
||||
cocoapodsProxyUrl?: string;
|
||||
}): Promise<void> {
|
||||
const archiveDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'precompiled-modules-'));
|
||||
const destinationParentDirectory = path.dirname(destinationDirectory);
|
||||
await fs.mkdirp(destinationParentDirectory);
|
||||
const stagingDirectory = await fs.mkdtemp(
|
||||
path.join(destinationParentDirectory, `${path.basename(destinationDirectory)}-staging-`)
|
||||
);
|
||||
|
||||
logger.info('');
|
||||
logger.info(
|
||||
{
|
||||
destinationDirectory,
|
||||
urls,
|
||||
},
|
||||
'Starting precompiled dependencies download'
|
||||
);
|
||||
|
||||
await fs.remove(destinationDirectory);
|
||||
await fs.mkdirp(destinationDirectory);
|
||||
|
||||
try {
|
||||
const archives = urls.map((url, index) => ({
|
||||
archiveName: path.basename(new URL(url).pathname),
|
||||
url,
|
||||
archivePath: path.join(archiveDirectory, `precompiled-modules-${index}.zip`),
|
||||
}));
|
||||
|
||||
await Promise.all(
|
||||
archives.map(async ({ url, archivePath }) => {
|
||||
await downloadPrecompiledModulesAsync({
|
||||
url,
|
||||
archivePath,
|
||||
cocoapodsProxyUrl,
|
||||
logger,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
for (const { archiveName, url, archivePath } of archives) {
|
||||
logger.info({ archivePath, url }, `Downloaded ${archiveName}, extracting archive`);
|
||||
await extractZipAsync(archivePath, stagingDirectory);
|
||||
logger.info(
|
||||
{ destinationDirectory: stagingDirectory },
|
||||
`Extracted ${archiveName} into staging precompiled dependencies directory`
|
||||
);
|
||||
}
|
||||
|
||||
await fs.remove(destinationDirectory);
|
||||
await fs.move(stagingDirectory, destinationDirectory);
|
||||
logger.info({ destinationDirectory }, `Precompiled modules ready in ${destinationDirectory}`);
|
||||
} catch (error) {
|
||||
await fs.remove(stagingDirectory);
|
||||
await fs.remove(destinationDirectory);
|
||||
await fs.mkdirp(destinationDirectory);
|
||||
throw error;
|
||||
} finally {
|
||||
await fs.remove(archiveDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadPrecompiledModulesAsync({
|
||||
url,
|
||||
archivePath,
|
||||
cocoapodsProxyUrl,
|
||||
logger,
|
||||
}: {
|
||||
url: string;
|
||||
archivePath: string;
|
||||
cocoapodsProxyUrl?: string;
|
||||
logger: bunyan;
|
||||
}): Promise<void> {
|
||||
const proxiedUrl = cocoapodsProxyUrl
|
||||
? (() => {
|
||||
const parsedUrl = new URL(url);
|
||||
return `${cocoapodsProxyUrl}/${parsedUrl.hostname}${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;
|
||||
})()
|
||||
: null;
|
||||
if (proxiedUrl) {
|
||||
try {
|
||||
await downloadFile(proxiedUrl, archivePath, { retry: 3 });
|
||||
return;
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err, proxiedUrl },
|
||||
'Failed to download through CocoaPods proxy, retrying directly'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await downloadFile(url, archivePath, { retry: 3 });
|
||||
}
|
||||
|
||||
async function extractZipAsync(archivePath: string, destinationDirectory: string): Promise<void> {
|
||||
const zip = new StreamZip.async({ file: archivePath });
|
||||
try {
|
||||
await zip.extract(null, destinationDirectory);
|
||||
} finally {
|
||||
await zip.close();
|
||||
}
|
||||
}
|
||||
@@ -19,10 +19,10 @@
|
||||
"watch": "tsc --watch --preserveWatchOutput",
|
||||
"build": "tsc",
|
||||
"typecheck": "tsc",
|
||||
"prepack": "rm -rf dist *.tsbuildinfo && tsc -p tsconfig.build.json",
|
||||
"prepack": "rimraf dist \"*.tsbuildinfo\" && tsc -p tsconfig.build.json",
|
||||
"test": "jest --config jest.config.ts",
|
||||
"test:watch": "jest --config jest.config.ts --watch",
|
||||
"clean": "rm -rf node_modules dist coverage *.tsbuildinfo"
|
||||
"clean": "rimraf node_modules dist coverage \"*.tsbuildinfo\""
|
||||
},
|
||||
"dependencies": {
|
||||
"fs-extra": "^11.2.0",
|
||||
@@ -33,6 +33,7 @@
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/node": "20.14.2",
|
||||
"jest": "^29.7.0",
|
||||
"rimraf": "3.0.2",
|
||||
"ts-jest": "^29.1.4",
|
||||
"typescript": "^5.5.4"
|
||||
}
|
||||
|
||||
@@ -26,9 +26,9 @@
|
||||
"watch-allow-unused": "yarn build-allow-unused --watch --preserveWatchOutput",
|
||||
"typecheck": "tsc",
|
||||
"prepack": "yarn rebuild",
|
||||
"rebuild": "rimraf build *.tsbuildinfo && yarn build",
|
||||
"rebuild": "rimraf build \"*.tsbuildinfo\" && yarn build",
|
||||
"test": "jest --passWithNoTests",
|
||||
"clean": "rimraf build node_modules yarn-error.log *.tsbuildinfo"
|
||||
"clean": "rimraf build node_modules yarn-error.log \"*.tsbuildinfo\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "7.23.5",
|
||||
|
||||
@@ -19,10 +19,10 @@
|
||||
"watch": "tsc --watch --preserveWatchOutput",
|
||||
"build": "tsc",
|
||||
"typecheck": "tsc",
|
||||
"prepack": "rm -rf dist *.tsbuildinfo && tsc -p tsconfig.build.json",
|
||||
"prepack": "rimraf dist \"*.tsbuildinfo\" && tsc -p tsconfig.build.json",
|
||||
"test": "jest --config jest.config.ts",
|
||||
"test:watch": "jest --config jest.config.ts --watch",
|
||||
"clean": "rm -rf node_modules dist coverage *.tsbuildinfo"
|
||||
"clean": "rimraf node_modules dist coverage \"*.tsbuildinfo\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/logger": "18.0.1",
|
||||
@@ -34,6 +34,7 @@
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/node": "20.14.2",
|
||||
"jest": "^29.7.0",
|
||||
"rimraf": "3.0.2",
|
||||
"ts-jest": "^29.1.4",
|
||||
"typescript": "^5.5.4"
|
||||
}
|
||||
|
||||
Generated
+3067
-359
File diff suppressed because it is too large.
Load diff
@@ -28,7 +28,7 @@
|
||||
"scripts": {
|
||||
"postpack": "rimraf oclif.manifest.json",
|
||||
"prepack": "yarn rebuild && node ./scripts/prepack.js",
|
||||
"rebuild": "rimraf build *.tsbuildinfo && yarn build",
|
||||
"rebuild": "rimraf build \"*.tsbuildinfo\" && yarn build",
|
||||
"build": "yarn typecheck-for-build && yarn copy-new-templates",
|
||||
"build-allow-unused": "tsc --project tsconfig.allowUnused.json",
|
||||
"watch": "yarn typecheck-for-build --watch --preserveWatchOutput",
|
||||
@@ -39,14 +39,14 @@
|
||||
"version": "yarn run -T oclif readme && node scripts/patch-readme && git add README.md",
|
||||
"generate-graphql-code": "graphql-codegen --config graphql-codegen.yml",
|
||||
"verify-graphql-code": "./scripts/verify-graphql.sh",
|
||||
"clean": "rimraf dist build tmp node_modules yarn-error.log *.tsbuildinfo",
|
||||
"clean": "rimraf dist build tmp node_modules yarn-error.log \"*.tsbuildinfo\"",
|
||||
"copy-new-templates": "rimraf build/commandUtils/new/templates && mkdir -p build/commandUtils/new && cp -r src/commandUtils/new/templates build/commandUtils/new"
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/apple-utils": "2.1.13",
|
||||
"@expo/apple-utils": "2.1.16",
|
||||
"@expo/code-signing-certificates": "0.0.5",
|
||||
"@expo/config": "10.0.6",
|
||||
"@expo/config-plugins": "9.0.12",
|
||||
"@expo/config": "55.0.10",
|
||||
"@expo/config-plugins": "55.0.7",
|
||||
"@expo/eas-build-job": "18.4.0",
|
||||
"@expo/eas-json": "18.4.0",
|
||||
"@expo/env": "^1.0.0",
|
||||
@@ -68,6 +68,7 @@
|
||||
"@oclif/core": "^4.8.3",
|
||||
"@oclif/plugin-autocomplete": "^3.2.40",
|
||||
"@segment/ajv-human-errors": "^2.1.2",
|
||||
"@sentry/node": "7.77.0",
|
||||
"@urql/core": "4.0.11",
|
||||
"@urql/exchange-retry": "1.2.0",
|
||||
"ajv": "8.11.0",
|
||||
|
||||
@@ -315,6 +315,42 @@
|
||||
"liveEdits": true,
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"screenshots": {
|
||||
"type": "object",
|
||||
"description": "Screenshots for this locale, organized by display type (e.g., APP_IPHONE_67, APP_IPAD_PRO_129)",
|
||||
"additionalProperties": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"previews": {
|
||||
"type": "object",
|
||||
"description": "Video previews for this locale, organized by display type (e.g., IPHONE_67, IPAD_PRO_129)",
|
||||
"additionalProperties": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Video file path (relative to project root)"
|
||||
},
|
||||
"previewFrameTimeCode": {
|
||||
"type": "string",
|
||||
"description": "Optional preview frame time code (e.g., '00:05:00' for 5 seconds)"
|
||||
}
|
||||
},
|
||||
"required": ["path"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
getMockEmptyWorkflowRunsFragment,
|
||||
getMockWorkflowCustomJobFragment,
|
||||
getMockWorkflowRunWithBuildJobsFragment,
|
||||
getMockWorkflowRunWithJobsFragment,
|
||||
getMockWorkflowRunsFragment,
|
||||
mockCommandContext,
|
||||
@@ -124,7 +125,8 @@ describe(WorkflowLogView, () => {
|
||||
.mocked(AppQuery.byIdWorkflowRunsFilteredByStatusAsync)
|
||||
.mockResolvedValue(getMockWorkflowRunsFragment({ withJobs: 1 }));
|
||||
let promptCalls = 0;
|
||||
jest.mocked(promptAsync).mockImplementation(async () => {
|
||||
let stepPrompt: any;
|
||||
jest.mocked(promptAsync).mockImplementation(async prompt => {
|
||||
if (promptCalls === 0) {
|
||||
promptCalls++;
|
||||
return { selectedRun: 'build1' };
|
||||
@@ -132,13 +134,14 @@ describe(WorkflowLogView, () => {
|
||||
promptCalls++;
|
||||
return { selectedJob: 0 };
|
||||
} else {
|
||||
return { selectedStep: 'step1' };
|
||||
stepPrompt = prompt;
|
||||
return { selectedStep: 'step-id-1' };
|
||||
}
|
||||
});
|
||||
jest
|
||||
.mocked(fetchRawLogsForCustomJobAsync)
|
||||
.mockResolvedValue(
|
||||
'{"result":"test","marker":"test","buildStepDisplayName":"step1","buildStepInternalId":"step1","time":"2022-01-01T00:00:00.000Z","msg":"test"}'
|
||||
'{"result":"success","marker":"end-step","buildStepDisplayName":"Install dependencies","buildStepId":"step-id-1","time":"2022-01-01T00:00:00.000Z","msg":"test"}'
|
||||
);
|
||||
await cmd.run();
|
||||
expect(AppQuery.byIdWorkflowRunsFilteredByStatusAsync).toHaveBeenCalledWith(
|
||||
@@ -148,6 +151,14 @@ describe(WorkflowLogView, () => {
|
||||
20
|
||||
);
|
||||
expect(promptAsync).toHaveBeenCalledTimes(3);
|
||||
expect(stepPrompt.choices).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
title: 'Install dependencies - success',
|
||||
value: 'step-id-1',
|
||||
}),
|
||||
])
|
||||
);
|
||||
expect(Log.error).not.toHaveBeenCalled();
|
||||
expect(Log.log).toHaveBeenCalledWith(' 2022-01-01T00:00:00.000Z test');
|
||||
});
|
||||
@@ -159,6 +170,9 @@ describe(WorkflowLogView, () => {
|
||||
jest
|
||||
.mocked(AppQuery.byIdWorkflowRunsFilteredByStatusAsync)
|
||||
.mockResolvedValue(getMockWorkflowRunsFragment({ withBuildJobs: 1 }));
|
||||
jest
|
||||
.mocked(WorkflowRunQuery.withJobsByIdAsync)
|
||||
.mockResolvedValue(getMockWorkflowRunWithBuildJobsFragment());
|
||||
jest.mocked(BuildQuery.byIdAsync).mockResolvedValue({
|
||||
id: 'build1',
|
||||
status: BuildStatus.Finished,
|
||||
@@ -181,7 +195,8 @@ describe(WorkflowLogView, () => {
|
||||
logFiles: ['https://example.com/log1'],
|
||||
});
|
||||
let promptCalls = 0;
|
||||
jest.mocked(promptAsync).mockImplementation(async () => {
|
||||
let stepPrompt: any;
|
||||
jest.mocked(promptAsync).mockImplementation(async prompt => {
|
||||
if (promptCalls === 0) {
|
||||
promptCalls++;
|
||||
return { selectedRun: 'build1' };
|
||||
@@ -189,13 +204,14 @@ describe(WorkflowLogView, () => {
|
||||
promptCalls++;
|
||||
return { selectedJob: 0 };
|
||||
} else {
|
||||
return { selectedStep: 'step1' };
|
||||
stepPrompt = prompt;
|
||||
return { selectedStep: 'step-id-1' };
|
||||
}
|
||||
});
|
||||
jest
|
||||
.mocked(fetchRawLogsForBuildJobAsync)
|
||||
.mockResolvedValue(
|
||||
'{"result":"test","marker":"test","buildStepDisplayName":"step1","buildStepInternalId":"step1","time":"2022-01-01T00:00:00.000Z","msg":"test"}'
|
||||
'{"result":"success","marker":"end-step","buildStepDisplayName":"step1","buildStepId":"step-id-1","time":"2022-01-01T00:00:00.000Z","msg":"test"}'
|
||||
);
|
||||
await cmd.run();
|
||||
expect(AppQuery.byIdWorkflowRunsFilteredByStatusAsync).toHaveBeenCalledWith(
|
||||
@@ -205,9 +221,65 @@ describe(WorkflowLogView, () => {
|
||||
20
|
||||
);
|
||||
expect(promptAsync).toHaveBeenCalledTimes(3);
|
||||
expect(stepPrompt.choices).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
title: 'step1 - success',
|
||||
value: 'step-id-1',
|
||||
}),
|
||||
])
|
||||
);
|
||||
expect(Log.error).not.toHaveBeenCalled();
|
||||
expect(Log.log).toHaveBeenCalledWith(' 2022-01-01T00:00:00.000Z test');
|
||||
});
|
||||
test('view logs keeps duplicate display names separated by step id', async () => {
|
||||
const ctx = mockCommandContext(WorkflowLogView, {
|
||||
projectId: mockProjectId,
|
||||
});
|
||||
const cmd = mockTestCommand(WorkflowLogView, [], ctx);
|
||||
jest
|
||||
.mocked(AppQuery.byIdWorkflowRunsFilteredByStatusAsync)
|
||||
.mockResolvedValue(getMockWorkflowRunsFragment({ withJobs: 1 }));
|
||||
let promptCalls = 0;
|
||||
let stepPrompt: any;
|
||||
jest.mocked(promptAsync).mockImplementation(async prompt => {
|
||||
if (promptCalls === 0) {
|
||||
promptCalls++;
|
||||
return { selectedRun: 'build1' };
|
||||
} else if (promptCalls === 1) {
|
||||
promptCalls++;
|
||||
return { selectedJob: 0 };
|
||||
} else {
|
||||
stepPrompt = prompt;
|
||||
return { selectedStep: 'step-id-2' };
|
||||
}
|
||||
});
|
||||
jest
|
||||
.mocked(fetchRawLogsForCustomJobAsync)
|
||||
.mockResolvedValue(
|
||||
[
|
||||
'{"result":"success","marker":"end-step","buildStepDisplayName":"Install","buildStepId":"step-id-1","time":"2022-01-01T00:00:00.000Z","msg":"first"}',
|
||||
'{"result":"fail","marker":"end-step","buildStepDisplayName":"Install","buildStepId":"step-id-2","time":"2022-01-01T00:00:01.000Z","msg":"second"}',
|
||||
].join('\n')
|
||||
);
|
||||
|
||||
await cmd.run();
|
||||
|
||||
expect(promptAsync).toHaveBeenCalledTimes(3);
|
||||
expect(stepPrompt.choices).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
title: 'Install - success',
|
||||
value: 'step-id-1',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
title: 'Install - fail',
|
||||
value: 'step-id-2',
|
||||
}),
|
||||
])
|
||||
);
|
||||
expect(Log.log).toHaveBeenCalledWith(' 2022-01-01T00:00:01.000Z second');
|
||||
});
|
||||
test('view logs for a workflow job, passing in a job ID, all steps', async () => {
|
||||
const ctx = mockCommandContext(WorkflowLogView, {
|
||||
projectId: mockProjectId,
|
||||
|
||||
@@ -12,8 +12,8 @@ import slash from 'slash';
|
||||
|
||||
import { AndroidCredentials } from '../../credentials/android/AndroidCredentialsProvider';
|
||||
import { getCustomBuildConfigPathForJob } from '../../project/customBuildConfig';
|
||||
import { getUsernameForBuildMetadataAndBuildJob } from '../../project/projectUtils';
|
||||
import { BuildContext } from '../context';
|
||||
import { getActorUsername } from '../../user/User';
|
||||
|
||||
interface JobData {
|
||||
projectArchive: ArchiveSource;
|
||||
@@ -29,7 +29,7 @@ export async function prepareJobAsync(
|
||||
ctx: BuildContext<Platform.ANDROID>,
|
||||
jobData: JobData
|
||||
): Promise<Android.Job> {
|
||||
const username = getUsernameForBuildMetadataAndBuildJob(ctx.user);
|
||||
const username = getActorUsername(ctx.user) ?? undefined;
|
||||
const buildProfile: BuildProfile<Platform.ANDROID> = ctx.buildProfile;
|
||||
const projectRootDirectory =
|
||||
slash(path.relative(await ctx.vcsClient.getRootPathAsync(), ctx.projectDir)) || '.';
|
||||
|
||||
@@ -14,8 +14,8 @@ import slash from 'slash';
|
||||
import { IosCredentials, TargetCredentials } from '../../credentials/ios/types';
|
||||
import { IosJobSecretsInput } from '../../graphql/generated';
|
||||
import { getCustomBuildConfigPathForJob } from '../../project/customBuildConfig';
|
||||
import { getUsernameForBuildMetadataAndBuildJob } from '../../project/projectUtils';
|
||||
import { BuildContext } from '../context';
|
||||
import { getActorUsername } from '../../user/User';
|
||||
|
||||
interface JobData {
|
||||
projectArchive: ArchiveSource;
|
||||
@@ -32,7 +32,7 @@ export async function prepareJobAsync(
|
||||
ctx: BuildContext<Platform.IOS>,
|
||||
jobData: JobData
|
||||
): Promise<Ios.Job> {
|
||||
const username = getUsernameForBuildMetadataAndBuildJob(ctx.user);
|
||||
const username = getActorUsername(ctx.user) ?? undefined;
|
||||
const buildProfile: BuildProfile<Platform.IOS> = ctx.buildProfile;
|
||||
const projectRootDirectory =
|
||||
slash(path.relative(await ctx.vcsClient.getRootPathAsync(), ctx.projectDir)) || '.';
|
||||
|
||||
@@ -10,12 +10,12 @@ import { LocalBuildMode } from './local';
|
||||
import { BuildDistributionType } from './types';
|
||||
import Log from '../log';
|
||||
import {
|
||||
getUsernameForBuildMetadataAndBuildJob,
|
||||
isExpoUpdatesInstalled,
|
||||
} from '../project/projectUtils';
|
||||
import { readChannelSafelyAsync as readAndroidChannelSafelyAsync } from '../update/android/UpdatesModule';
|
||||
import { readChannelSafelyAsync as readIosChannelSafelyAsync } from '../update/ios/UpdatesModule';
|
||||
import { easCliVersion } from '../utils/easCli';
|
||||
import { getActorUsername } from '../user/User';
|
||||
|
||||
export async function collectMetadataAsync<T extends Platform>(
|
||||
ctx: BuildContext<T>,
|
||||
@@ -49,7 +49,7 @@ export async function collectMetadataAsync<T extends Platform>(
|
||||
ctx.localBuildOptions.localBuildMode === LocalBuildMode.INTERNAL
|
||||
? false
|
||||
: await ctx.vcsClient.hasUncommittedChangesAsync(),
|
||||
username: getUsernameForBuildMetadataAndBuildJob(ctx.user),
|
||||
username: getActorUsername(ctx.user) ?? undefined,
|
||||
message: ctx.message,
|
||||
...(ctx.platform === Platform.IOS && {
|
||||
iosEnterpriseProvisioning: resolveIosEnterpriseProvisioning(
|
||||
|
||||
@@ -107,7 +107,7 @@ async function validateAndroidPNGsAsync(ctx: CommonContext<Platform.ANDROID>): P
|
||||
},
|
||||
{
|
||||
configPath: 'exp.notification.icon',
|
||||
pngPath: ctx.exp.notification?.icon,
|
||||
pngPath: (ctx.exp as Record<string, any>).notification?.icon,
|
||||
},
|
||||
];
|
||||
await validatePNGsAsync(pngs);
|
||||
|
||||
@@ -27,7 +27,9 @@ import {
|
||||
createAnalyticsAsync,
|
||||
} from '../analytics/AnalyticsManager';
|
||||
import Log, { link } from '../log';
|
||||
import Sentry from '../sentry';
|
||||
import SessionManager from '../user/SessionManager';
|
||||
import { getActorDisplayName } from '../user/User';
|
||||
import { Client } from '../vcs/vcs';
|
||||
|
||||
export type ContextInput<
|
||||
@@ -169,7 +171,6 @@ export default abstract class EasCommand extends Command {
|
||||
* It is set up here to ensure a consistent setup.
|
||||
*/
|
||||
private analyticsInternal?: AnalyticsWithOrchestration;
|
||||
|
||||
/**
|
||||
* Execute the context in the contextDefinition to satisfy command prerequisites.
|
||||
*/
|
||||
@@ -230,7 +231,13 @@ export default abstract class EasCommand extends Command {
|
||||
|
||||
// this is needed for logEvent call below as it identifies the user in the analytics system
|
||||
// if possible
|
||||
await this.sessionManager.getUserAsync();
|
||||
const actor = await this.sessionManager.getUserAsync();
|
||||
if (actor) {
|
||||
Sentry.setUser({
|
||||
id: actor.id,
|
||||
username: getActorDisplayName(actor),
|
||||
});
|
||||
}
|
||||
|
||||
this.analytics.logEvent(CommandEvent.ACTION, {
|
||||
// id is assigned by oclif in constructor based on the filepath:
|
||||
@@ -244,11 +251,13 @@ export default abstract class EasCommand extends Command {
|
||||
// eslint-disable-next-line async-protect/async-suffix
|
||||
override async finally(err: Error): Promise<any> {
|
||||
await this.analytics.flushAsync();
|
||||
await Sentry.flush(2000);
|
||||
return await super.finally(err);
|
||||
}
|
||||
|
||||
protected override catch(err: Error): Promise<any> {
|
||||
let baseMessage = `${this.id} command failed.`;
|
||||
const commandId = this.id ?? 'unknown';
|
||||
let baseMessage = `${commandId} command failed.`;
|
||||
if (err instanceof EasCommandError) {
|
||||
Log.error(err.message);
|
||||
} else if (err instanceof CombinedError && err?.graphQLErrors) {
|
||||
@@ -293,6 +302,17 @@ export default abstract class EasCommand extends Command {
|
||||
Log.error(err.message);
|
||||
}
|
||||
Log.debug(err);
|
||||
Sentry.withScope(scope => {
|
||||
scope.setTag('command', commandId);
|
||||
scope.setTag('error_name', err.name);
|
||||
scope.setExtra('commandId', commandId);
|
||||
scope.setExtra('commandMessage', baseMessage);
|
||||
scope.setExtra('originalMessage', err.message);
|
||||
if (err instanceof CombinedError) {
|
||||
scope.setExtra('graphQLErrorCount', err.graphQLErrors.length);
|
||||
}
|
||||
Sentry.captureException(err);
|
||||
});
|
||||
const sanitizedError = new Error(baseMessage);
|
||||
sanitizedError.stack = err.stack;
|
||||
throw sanitizedError;
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import { CombinedError } from '@urql/core';
|
||||
import { GraphQLError } from 'graphql/error';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import { AnalyticsWithOrchestration, createAnalyticsAsync } from '../../analytics/AnalyticsManager';
|
||||
import Log from '../../log';
|
||||
import SessionManager from '../../user/SessionManager';
|
||||
import EasCommand from '../EasCommand';
|
||||
import { AnalyticsWithOrchestration } from '../../analytics/AnalyticsManager';
|
||||
|
||||
jest.mock('../../user/User');
|
||||
jest.mock('../../user/SessionManager');
|
||||
jest.mock('../../sentry', () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
init: jest.fn(),
|
||||
setTag: jest.fn(),
|
||||
setUser: jest.fn(),
|
||||
withScope: jest.fn(),
|
||||
captureException: jest.fn(),
|
||||
flush: jest.fn(async (): Promise<void> => {}),
|
||||
},
|
||||
}));
|
||||
jest.mock('../../analytics/AnalyticsManager', () => {
|
||||
const { CommandEvent } = jest.requireActual('../../analytics/AnalyticsManager');
|
||||
return {
|
||||
@@ -38,20 +44,22 @@ const analytics: AnalyticsWithOrchestration = {
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
|
||||
jest.mocked(createAnalyticsAsync).mockResolvedValue(analytics);
|
||||
});
|
||||
|
||||
const createTestEasCommand = (): any => {
|
||||
const { createAnalyticsAsync } = jest.requireMock('../../analytics/AnalyticsManager');
|
||||
createAnalyticsAsync.mockResolvedValue(analytics);
|
||||
const EasCommand = require('../EasCommand').default;
|
||||
|
||||
class TestEasCommand extends EasCommand {
|
||||
override async runAsync(): Promise<void> {}
|
||||
async runAsync(): Promise<void> {}
|
||||
}
|
||||
|
||||
TestEasCommand.id = 'testEasCommand'; // normally oclif will assign ids, but b/c this is located outside the commands folder it will not
|
||||
return TestEasCommand;
|
||||
};
|
||||
|
||||
describe(EasCommand.name, () => {
|
||||
describe('EasCommand', () => {
|
||||
describe('without exceptions', () => {
|
||||
// The first test in this suite should have an increased timeout
|
||||
// because of the implementation of Command from @oclif/command.
|
||||
@@ -64,6 +72,7 @@ describe(EasCommand.name, () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
await TestEasCommand.run();
|
||||
|
||||
const SessionManager = jest.requireMock('../../user/SessionManager').default;
|
||||
const sessionManagerSpy = jest.spyOn(SessionManager.prototype, 'getUserAsync');
|
||||
expect(sessionManagerSpy).toBeCalledTimes(1);
|
||||
}, 60_000);
|
||||
@@ -72,6 +81,7 @@ describe(EasCommand.name, () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
await TestEasCommand.run();
|
||||
|
||||
const { createAnalyticsAsync } = jest.requireMock('../../analytics/AnalyticsManager');
|
||||
expect(createAnalyticsAsync).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -82,6 +92,14 @@ describe(EasCommand.name, () => {
|
||||
expect(analytics.flushAsync).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('flushes Sentry', async () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
await TestEasCommand.run();
|
||||
|
||||
const Sentry = jest.requireMock('../../sentry').default;
|
||||
expect(Sentry.flush).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('logs events', async () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
await TestEasCommand.run();
|
||||
@@ -105,8 +123,59 @@ describe(EasCommand.name, () => {
|
||||
});
|
||||
|
||||
describe('catch', () => {
|
||||
it('captures unexpected errors', async () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
const runAsyncMock = jest.spyOn(TestEasCommand.prototype, 'runAsync');
|
||||
const error = new Error('Unexpected, internal error message');
|
||||
const sentryScope = {
|
||||
setTag: jest.fn(),
|
||||
setExtra: jest.fn(),
|
||||
};
|
||||
const Sentry = jest.requireMock('../../sentry').default;
|
||||
Sentry.withScope.mockImplementation((cb: (scope: typeof sentryScope) => void) => {
|
||||
cb(sentryScope);
|
||||
});
|
||||
runAsyncMock.mockImplementation(() => {
|
||||
throw error;
|
||||
});
|
||||
|
||||
try {
|
||||
await TestEasCommand.run();
|
||||
} catch {}
|
||||
|
||||
expect(sentryScope.setTag).toHaveBeenCalledWith('command', TestEasCommand.id);
|
||||
expect(sentryScope.setTag).toHaveBeenCalledWith('error_name', error.name);
|
||||
expect(sentryScope.setExtra).toHaveBeenCalledWith('commandId', TestEasCommand.id);
|
||||
expect(sentryScope.setExtra).toHaveBeenCalledWith(
|
||||
'commandMessage',
|
||||
`${TestEasCommand.id} command failed.`
|
||||
);
|
||||
expect(sentryScope.setExtra).toHaveBeenCalledWith('originalMessage', error.message);
|
||||
expect(Sentry.captureException).toHaveBeenCalledWith(error);
|
||||
});
|
||||
|
||||
it('captures expected command errors', async () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
const runAsyncMock = jest.spyOn(TestEasCommand.prototype, 'runAsync');
|
||||
const { EasCommandError } = require('../errors');
|
||||
const Sentry = jest.requireMock('../../sentry').default;
|
||||
Sentry.withScope.mockImplementation((cb: (scope: any) => void) => {
|
||||
cb({ setTag: jest.fn(), setExtra: jest.fn() });
|
||||
});
|
||||
runAsyncMock.mockImplementation(() => {
|
||||
throw new EasCommandError('Expected user-facing error');
|
||||
});
|
||||
|
||||
try {
|
||||
await TestEasCommand.run();
|
||||
} catch {}
|
||||
|
||||
expect(Sentry.captureException).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('logs the message', async () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
const Log = jest.requireMock('../../log').default;
|
||||
const logErrorSpy = jest.spyOn(Log, 'error');
|
||||
const logDebugSpy = jest.spyOn(Log, 'debug');
|
||||
const runAsyncMock = jest.spyOn(TestEasCommand.prototype, 'runAsync');
|
||||
@@ -124,9 +193,11 @@ describe(EasCommand.name, () => {
|
||||
|
||||
it('logs the cleaned message if needed', async () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
const Log = jest.requireMock('../../log').default;
|
||||
const logErrorSpy = jest.spyOn(Log, 'error');
|
||||
const logDebugSpy = jest.spyOn(Log, 'debug');
|
||||
const runAsyncMock = jest.spyOn(TestEasCommand.prototype, 'runAsync');
|
||||
const { CombinedError } = require('@urql/core');
|
||||
const graphQLErrors = ['Unexpected GraphQL error message'];
|
||||
const error = new CombinedError({ graphQLErrors });
|
||||
runAsyncMock.mockImplementation(() => {
|
||||
@@ -142,9 +213,12 @@ describe(EasCommand.name, () => {
|
||||
|
||||
it('logs the cleaned message with request ID if present', async () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
const Log = jest.requireMock('../../log').default;
|
||||
const logErrorSpy = jest.spyOn(Log, 'error');
|
||||
const logDebugSpy = jest.spyOn(Log, 'debug');
|
||||
const runAsyncMock = jest.spyOn(TestEasCommand.prototype, 'runAsync');
|
||||
const { CombinedError } = require('@urql/core');
|
||||
const { GraphQLError } = require('graphql/error');
|
||||
const graphQLError = new GraphQLError(
|
||||
'Unexpected GraphQL error message',
|
||||
null,
|
||||
@@ -174,9 +248,12 @@ describe(EasCommand.name, () => {
|
||||
|
||||
it('logs the cleaned messages with request IDs if multiple GraphQL errors present', async () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
const Log = jest.requireMock('../../log').default;
|
||||
const logErrorSpy = jest.spyOn(Log, 'error');
|
||||
const logDebugSpy = jest.spyOn(Log, 'debug');
|
||||
const runAsyncMock = jest.spyOn(TestEasCommand.prototype, 'runAsync');
|
||||
const { CombinedError } = require('@urql/core');
|
||||
const { GraphQLError } = require('graphql/error');
|
||||
const graphQLErrors = [
|
||||
new GraphQLError('Unexpected GraphQL error message', null, null, null, null, null, {
|
||||
errorCode: 'UNKNOWN_GRAPHQL_ERROR',
|
||||
@@ -227,6 +304,7 @@ describe(EasCommand.name, () => {
|
||||
it('re-throws the error with a different default base message in case of CombinedError', async () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
const runAsyncMock = jest.spyOn(TestEasCommand.prototype, 'runAsync');
|
||||
const { CombinedError } = require('@urql/core');
|
||||
runAsyncMock.mockImplementation(() => {
|
||||
const graphQLErrors = ['Unexpected GraphQL error message'];
|
||||
throw new CombinedError({ graphQLErrors });
|
||||
@@ -242,6 +320,8 @@ describe(EasCommand.name, () => {
|
||||
it('re-throws the error with a different default base message in case of CombinedError with multiple GraphQLErrors', async () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
const runAsyncMock = jest.spyOn(TestEasCommand.prototype, 'runAsync');
|
||||
const { CombinedError } = require('@urql/core');
|
||||
const { GraphQLError } = require('graphql/error');
|
||||
runAsyncMock.mockImplementation(() => {
|
||||
const graphQLErrors = [
|
||||
new GraphQLError('Unexpected GraphQL error message', null, null, null, null, null, {
|
||||
|
||||
@@ -189,6 +189,8 @@ export async function validateOrSetProjectIdAsync({
|
||||
return user.username;
|
||||
case 'SSOUser':
|
||||
return user.username;
|
||||
case 'PartnerActor':
|
||||
return user.username;
|
||||
case 'Robot':
|
||||
throw new Error(
|
||||
'Must configure EAS project by running "eas init" before using a robot user to manage the project.'
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { getMockWorkflowRunWithJobsFragment } from '../../../__tests__/commands/utils';
|
||||
import { fetchRawLogsForCustomJobAsync } from '../fetchLogs';
|
||||
import { infoForActiveWorkflowRunAsync } from '../utils';
|
||||
import { WorkflowJobStatus } from '../../../graphql/generated';
|
||||
|
||||
jest.mock('../fetchLogs');
|
||||
|
||||
describe('workflow utils', () => {
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
test('shows the display name for the current step while keying logs by step id', async () => {
|
||||
const workflowRun = getMockWorkflowRunWithJobsFragment();
|
||||
workflowRun.jobs = workflowRun.jobs.map(job => ({
|
||||
...job,
|
||||
status: WorkflowJobStatus.InProgress,
|
||||
}));
|
||||
|
||||
jest
|
||||
.mocked(fetchRawLogsForCustomJobAsync)
|
||||
.mockResolvedValue(
|
||||
[
|
||||
'{"buildStepId":"step-id-1","buildStepDisplayName":"Install dependencies","time":"2022-01-01T00:00:00.000Z","msg":"npm ci"}',
|
||||
'{"buildStepId":"step-id-1","buildStepDisplayName":"Install dependencies","marker":"end-step","result":"success","time":"2022-01-01T00:00:01.000Z","msg":"done"}',
|
||||
].join('\n')
|
||||
);
|
||||
|
||||
const output = await infoForActiveWorkflowRunAsync({} as any, workflowRun);
|
||||
|
||||
expect(output).toContain('Current step');
|
||||
expect(output).toContain('Install dependencies');
|
||||
expect(output).not.toContain('step-id-1');
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,17 @@ export async function fetchRawLogsForBuildJobAsync(
|
||||
state: { graphqlClient: ExpoGraphqlClient },
|
||||
job: WorkflowJobResult
|
||||
): Promise<string | null> {
|
||||
// Prefer turtleJobRun logs, which contain JSONL-formatted step logs
|
||||
// for both built-in and custom build steps
|
||||
const turtleLogFileUrl = job.turtleJobRun?.logFileUrls?.[0];
|
||||
if (turtleLogFileUrl) {
|
||||
const response = await fetch(turtleLogFileUrl, {
|
||||
method: 'GET',
|
||||
});
|
||||
return await response.text();
|
||||
}
|
||||
|
||||
// Fall back to build logFiles
|
||||
const buildId = job.outputs?.build_id;
|
||||
if (!buildId) {
|
||||
return null;
|
||||
@@ -36,6 +47,5 @@ export async function fetchRawLogsForBuildJobAsync(
|
||||
const response = await fetch(firstLogFileUrl, {
|
||||
method: 'GET',
|
||||
});
|
||||
const rawLogs = await response.text();
|
||||
return rawLogs;
|
||||
return await response.text();
|
||||
}
|
||||
@@ -50,4 +50,11 @@ export type WorkflowLogLine = {
|
||||
err?: any;
|
||||
};
|
||||
|
||||
export type WorkflowLogs = Map<string, WorkflowLogLine[]>;
|
||||
export type WorkflowLogs = Map<
|
||||
string,
|
||||
{
|
||||
key: string;
|
||||
label: string;
|
||||
logLines: WorkflowLogLine[];
|
||||
}
|
||||
>;
|
||||
@@ -84,16 +84,17 @@ export function choiceFromWorkflowJob(job: WorkflowJobResult, index: number): Ch
|
||||
export function choicesFromWorkflowLogs(
|
||||
logs: WorkflowLogs
|
||||
): (Choice & { name: string; status: string; logLines: WorkflowLogLine[] | undefined })[] {
|
||||
return Array.from(logs.keys())
|
||||
.map(step => {
|
||||
const logLines = logs.get(step);
|
||||
return Array.from(logs.values())
|
||||
.map(({ key, label, logLines }) => {
|
||||
const stepStatus =
|
||||
logLines?.filter((line: WorkflowLogLine) => line.marker === 'end-step')[0]?.result ?? '';
|
||||
logLines?.filter(
|
||||
(line: WorkflowLogLine) => line.marker === 'end-step' || line.marker === 'END_PHASE'
|
||||
)[0]?.result ?? '';
|
||||
return {
|
||||
title: `${step} - ${stepStatus}`,
|
||||
name: step,
|
||||
title: `${label} - ${stepStatus}`,
|
||||
name: label,
|
||||
status: stepStatus,
|
||||
value: step,
|
||||
value: key,
|
||||
logLines,
|
||||
};
|
||||
})
|
||||
@@ -139,20 +140,27 @@ export async function fetchAndProcessLogsFromJobAsync(
|
||||
}
|
||||
Log.debug(`rawLogs = ${JSON.stringify(rawLogs, null, 2)}`);
|
||||
const logs: WorkflowLogs = new Map();
|
||||
const logKeys = new Set<string>();
|
||||
rawLogs.split('\n').forEach((line, index) => {
|
||||
Log.debug(`line ${index} = ${JSON.stringify(line, null, 2)}`);
|
||||
try {
|
||||
const parsedLine = JSON.parse(line);
|
||||
const { buildStepDisplayName, buildStepInternalId, time, msg, result, marker, err } =
|
||||
const { buildStepDisplayName, buildStepId, phase, time, msg, result, marker, err } =
|
||||
parsedLine;
|
||||
const stepId = buildStepDisplayName ?? buildStepInternalId;
|
||||
if (stepId) {
|
||||
if (!logKeys.has(stepId)) {
|
||||
logKeys.add(stepId);
|
||||
logs.set(stepId, []);
|
||||
const stepKey = buildStepId ?? buildStepDisplayName ?? phase;
|
||||
const stepLabel = buildStepDisplayName ?? buildStepId ?? phase;
|
||||
if (stepKey && stepLabel) {
|
||||
if (!logs.has(stepKey)) {
|
||||
logs.set(stepKey, {
|
||||
key: stepKey,
|
||||
label: stepLabel,
|
||||
logLines: [],
|
||||
});
|
||||
}
|
||||
logs.get(stepId)?.push({ time, msg, result, marker, err });
|
||||
const logGroup = logs.get(stepKey)!;
|
||||
if (buildStepDisplayName) {
|
||||
logGroup.label = buildStepDisplayName;
|
||||
}
|
||||
logGroup.logLines.push({ time, msg, result, marker, err });
|
||||
}
|
||||
} catch {}
|
||||
});
|
||||
@@ -238,7 +246,7 @@ export async function infoForFailedWorkflowRunAsync(
|
||||
statusValues.push({ label: '', value: '' });
|
||||
statusValues.push({ label: ' Failed job', value: job.name });
|
||||
if (steps.length > 0) {
|
||||
const failedStep = steps.find(step => step.status === 'fail');
|
||||
const failedStep = steps.find(step => step.status === 'fail' || step.status === 'failed');
|
||||
if (failedStep) {
|
||||
const logs = failedStep.logLines?.map(line => line.msg).slice(-logLinesToKeep) ?? [];
|
||||
statusValues.push({ label: ' Failed step', value: failedStep.name });
|
||||
|
||||
@@ -21,6 +21,10 @@ export default class MetadataPull extends EasCommand {
|
||||
description:
|
||||
'Name of the submit profile from eas.json. Defaults to "production" if defined in eas.json.',
|
||||
}),
|
||||
'non-interactive': Flags.boolean({
|
||||
default: false,
|
||||
description: 'Run the command in non-interactive mode.',
|
||||
}),
|
||||
};
|
||||
|
||||
static override contextDefinition = {
|
||||
@@ -34,18 +38,18 @@ export default class MetadataPull extends EasCommand {
|
||||
Log.warn('EAS Metadata is in beta and subject to breaking changes.');
|
||||
|
||||
const { flags } = await this.parse(MetadataPull);
|
||||
const nonInteractive = flags['non-interactive'];
|
||||
const {
|
||||
loggedIn: { actor, graphqlClient },
|
||||
privateProjectConfig: { exp, projectId, projectDir },
|
||||
analytics,
|
||||
vcsClient,
|
||||
} = await this.getContextAsync(MetadataPull, {
|
||||
nonInteractive: false,
|
||||
nonInteractive,
|
||||
withServerSideEnvironment: null,
|
||||
});
|
||||
|
||||
// this command is interactive (all nonInteractive flags passed to utility functions are false)
|
||||
await ensureProjectConfiguredAsync({ projectDir, nonInteractive: false, vcsClient });
|
||||
await ensureProjectConfiguredAsync({ projectDir, nonInteractive, vcsClient });
|
||||
|
||||
const submitProfiles = await getProfilesAsync({
|
||||
type: 'submit',
|
||||
@@ -66,7 +70,7 @@ export default class MetadataPull extends EasCommand {
|
||||
user: actor,
|
||||
graphqlClient,
|
||||
analytics,
|
||||
nonInteractive: false,
|
||||
nonInteractive,
|
||||
vcsClient,
|
||||
});
|
||||
|
||||
@@ -77,6 +81,9 @@ export default class MetadataPull extends EasCommand {
|
||||
credentialsCtx,
|
||||
projectDir,
|
||||
profile: submitProfile,
|
||||
nonInteractive,
|
||||
graphqlClient,
|
||||
projectId,
|
||||
});
|
||||
const relativePath = path.relative(process.cwd(), filePath);
|
||||
|
||||
|
||||
@@ -19,6 +19,10 @@ export default class MetadataPush extends EasCommand {
|
||||
description:
|
||||
'Name of the submit profile from eas.json. Defaults to "production" if defined in eas.json.',
|
||||
}),
|
||||
'non-interactive': Flags.boolean({
|
||||
default: false,
|
||||
description: 'Run the command in non-interactive mode.',
|
||||
}),
|
||||
};
|
||||
|
||||
static override contextDefinition = {
|
||||
@@ -32,18 +36,18 @@ export default class MetadataPush extends EasCommand {
|
||||
Log.warn('EAS Metadata is in beta and subject to breaking changes.');
|
||||
|
||||
const { flags } = await this.parse(MetadataPush);
|
||||
const nonInteractive = flags['non-interactive'];
|
||||
const {
|
||||
loggedIn: { actor, graphqlClient },
|
||||
privateProjectConfig: { exp, projectId, projectDir },
|
||||
analytics,
|
||||
vcsClient,
|
||||
} = await this.getContextAsync(MetadataPush, {
|
||||
nonInteractive: false,
|
||||
nonInteractive,
|
||||
withServerSideEnvironment: null,
|
||||
});
|
||||
|
||||
// this command is interactive (all nonInteractive flags passed to utility functions are false)
|
||||
await ensureProjectConfiguredAsync({ projectDir, nonInteractive: false, vcsClient });
|
||||
await ensureProjectConfiguredAsync({ projectDir, nonInteractive, vcsClient });
|
||||
|
||||
const submitProfiles = await getProfilesAsync({
|
||||
type: 'submit',
|
||||
@@ -64,7 +68,7 @@ export default class MetadataPush extends EasCommand {
|
||||
user: actor,
|
||||
graphqlClient,
|
||||
analytics,
|
||||
nonInteractive: false,
|
||||
nonInteractive,
|
||||
vcsClient,
|
||||
});
|
||||
|
||||
@@ -75,6 +79,9 @@ export default class MetadataPush extends EasCommand {
|
||||
credentialsCtx,
|
||||
projectDir,
|
||||
profile: submitProfile,
|
||||
nonInteractive,
|
||||
graphqlClient,
|
||||
projectId,
|
||||
});
|
||||
|
||||
Log.addNewLineIfNone();
|
||||
|
||||
@@ -73,6 +73,12 @@ export default class Onboarding extends EasCommand {
|
||||
);
|
||||
}
|
||||
|
||||
if (actor.__typename === 'PartnerActor') {
|
||||
throw new Error(
|
||||
'This command is not available for partner actors. Make sure you are using a user token and try again.'
|
||||
);
|
||||
}
|
||||
|
||||
if (!actor.preferences.onboarding) {
|
||||
throw new Error(
|
||||
'This command can only be run as part of the onboarding process started on the Expo website. Visit https://expo.new to start a new project.'
|
||||
|
||||
@@ -12,14 +12,14 @@ import Log from '../../log';
|
||||
import { enableJsonOutput, printJsonOnlyOutput } from '../../utils/json';
|
||||
|
||||
function printLogsForAllSteps(logs: WorkflowLogs): void {
|
||||
[...logs.keys()].forEach(step => {
|
||||
const logLines = logs.get(step);
|
||||
if (logLines) {
|
||||
Log.log(`Step: ${step}`);
|
||||
logLines.forEach(line => {
|
||||
Log.log(` ${line.time} ${line.msg}`);
|
||||
});
|
||||
[...logs.values()].forEach(({ label, logLines }) => {
|
||||
if (logLines.length === 0) {
|
||||
return;
|
||||
}
|
||||
Log.log(`Step: ${label}`);
|
||||
logLines.forEach(line => {
|
||||
Log.log(` ${line.time} ${line.msg}`);
|
||||
});
|
||||
Log.addNewLineIfNone();
|
||||
});
|
||||
}
|
||||
@@ -89,21 +89,25 @@ export default class WorkflowLogView extends EasCommand {
|
||||
if (allSteps) {
|
||||
if (logs) {
|
||||
if (flags.json) {
|
||||
printJsonOnlyOutput(Object.fromEntries(logs));
|
||||
printJsonOnlyOutput(
|
||||
Object.fromEntries(
|
||||
Array.from(logs.entries()).map(([key, value]) => [key, value.logLines])
|
||||
)
|
||||
);
|
||||
} else {
|
||||
printLogsForAllSteps(logs);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const selectedStep = finalSelectionState?.step as unknown as string;
|
||||
const logLines = logs?.get(selectedStep);
|
||||
if (logLines) {
|
||||
const logGroup = logs?.get(selectedStep);
|
||||
if (logGroup) {
|
||||
if (flags.json) {
|
||||
const output: { [key: string]: WorkflowLogLine[] | null } = {};
|
||||
output[selectedStep] = logLines ?? null;
|
||||
output[selectedStep] = logGroup.logLines;
|
||||
printJsonOnlyOutput(output);
|
||||
} else {
|
||||
logLines.forEach(line => {
|
||||
logGroup.logLines.forEach(line => {
|
||||
Log.log(` ${line.time} ${line.msg}`);
|
||||
});
|
||||
}
|
||||
|
||||
+1605
-8236
File diff suppressed because it is too large.
Load diff
@@ -43,6 +43,9 @@ export const UserQuery = {
|
||||
id
|
||||
...AccountFragment
|
||||
}
|
||||
... on PartnerActor {
|
||||
username
|
||||
}
|
||||
featureGates
|
||||
isExpoAdmin
|
||||
}
|
||||
|
||||
@@ -23,6 +23,9 @@ export const UpdateFragmentNode = gql`
|
||||
... on Robot {
|
||||
firstName
|
||||
}
|
||||
... on PartnerActor {
|
||||
username
|
||||
}
|
||||
}
|
||||
branch {
|
||||
id
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
import { App } from '@expo/apple-utils';
|
||||
import { SubmitProfile } from '@expo/eas-json';
|
||||
|
||||
import { getAppStoreAuthAsync } from '../auth';
|
||||
import { AuthenticationMode } from '../../credentials/ios/appstore/authenticateTypes';
|
||||
|
||||
// Mock all external dependencies
|
||||
jest.mock('@expo/apple-utils', () => ({
|
||||
App: { findAsync: jest.fn() },
|
||||
}));
|
||||
|
||||
jest.mock('../../credentials/ios/appstore/authenticate', () => ({
|
||||
getRequestContext: jest.fn(() => ({ token: 'mock-token' })),
|
||||
}));
|
||||
|
||||
jest.mock('../../credentials/ios/appstore/resolveCredentials', () => ({
|
||||
hasAscEnvVars: jest.fn(() => false),
|
||||
}));
|
||||
|
||||
jest.mock('../../project/ios/bundleIdentifier', () => ({
|
||||
getBundleIdentifierAsync: jest.fn(() => 'com.example.app'),
|
||||
}));
|
||||
|
||||
jest.mock('../../project/projectUtils', () => ({
|
||||
getOwnerAccountForProjectIdAsync: jest.fn(() => ({
|
||||
id: 'account-id',
|
||||
name: 'testaccount',
|
||||
})),
|
||||
}));
|
||||
|
||||
jest.mock('../../credentials/ios/api/GraphqlClient', () => ({
|
||||
getAscApiKeyForAppSubmissionsAsync: jest.fn(() => null),
|
||||
}));
|
||||
|
||||
jest.mock('../../graphql/queries/AppStoreConnectApiKeyQuery', () => ({
|
||||
AppStoreConnectApiKeyQuery: {
|
||||
getByIdAsync: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('fs', () => ({
|
||||
promises: {
|
||||
readFile: jest.fn(() => 'mock-key-p8-content'),
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('../../log');
|
||||
|
||||
const { hasAscEnvVars } =
|
||||
require('../../credentials/ios/appstore/resolveCredentials') as jest.Mocked<
|
||||
typeof import('../../credentials/ios/appstore/resolveCredentials')
|
||||
>;
|
||||
const { getAscApiKeyForAppSubmissionsAsync } =
|
||||
require('../../credentials/ios/api/GraphqlClient') as jest.Mocked<
|
||||
typeof import('../../credentials/ios/api/GraphqlClient')
|
||||
>;
|
||||
const { AppStoreConnectApiKeyQuery } =
|
||||
require('../../graphql/queries/AppStoreConnectApiKeyQuery') as jest.Mocked<
|
||||
typeof import('../../graphql/queries/AppStoreConnectApiKeyQuery')
|
||||
>;
|
||||
|
||||
const mockApp = { id: '123', bundleId: 'com.example.app' };
|
||||
|
||||
function createMockCredentialsCtx(ensureAuthResult?: any) {
|
||||
return {
|
||||
appStore: {
|
||||
ensureAuthenticatedAsync: jest.fn(() => ({
|
||||
authState: { context: { token: 'mock-token' } },
|
||||
...ensureAuthResult,
|
||||
})),
|
||||
},
|
||||
vcsClient: {},
|
||||
} as any;
|
||||
}
|
||||
|
||||
function createBaseArgs(overrides: Record<string, any> = {}) {
|
||||
return {
|
||||
projectDir: '/app',
|
||||
profile: { bundleIdentifier: 'com.example.app' } as SubmitProfile,
|
||||
exp: { slug: 'my-app', name: 'My App' } as any,
|
||||
credentialsCtx: createMockCredentialsCtx(),
|
||||
nonInteractive: false,
|
||||
graphqlClient: {} as any,
|
||||
projectId: 'test-project-id',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe(getAppStoreAuthAsync, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
(App.findAsync as jest.Mock).mockResolvedValue(mockApp);
|
||||
hasAscEnvVars.mockReturnValue(false);
|
||||
(getAscApiKeyForAppSubmissionsAsync as jest.Mock).mockResolvedValue(null);
|
||||
});
|
||||
|
||||
it('uses API key auth when ASC env vars are set', async () => {
|
||||
hasAscEnvVars.mockReturnValue(true);
|
||||
const args = createBaseArgs();
|
||||
|
||||
const result = await getAppStoreAuthAsync(args);
|
||||
|
||||
expect(args.credentialsCtx.appStore.ensureAuthenticatedAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ mode: AuthenticationMode.API_KEY })
|
||||
);
|
||||
expect(result.app).toBe(mockApp);
|
||||
});
|
||||
|
||||
it('uses API key from submit profile when ascApiKeyPath/Id/IssuerId are set', async () => {
|
||||
const profile = {
|
||||
bundleIdentifier: 'com.example.app',
|
||||
ascApiKeyPath: '/path/to/key.p8',
|
||||
ascApiKeyId: 'KEY123',
|
||||
ascApiKeyIssuerId: 'ISSUER456',
|
||||
} as any;
|
||||
const args = createBaseArgs({ profile });
|
||||
|
||||
const result = await getAppStoreAuthAsync(args);
|
||||
|
||||
expect(args.credentialsCtx.appStore.ensureAuthenticatedAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
mode: AuthenticationMode.API_KEY,
|
||||
ascApiKey: {
|
||||
keyP8: 'mock-key-p8-content',
|
||||
keyId: 'KEY123',
|
||||
issuerId: 'ISSUER456',
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(result.app).toBe(mockApp);
|
||||
});
|
||||
|
||||
it('uses API key from EAS credentials service when available', async () => {
|
||||
(getAscApiKeyForAppSubmissionsAsync as jest.Mock).mockResolvedValue({
|
||||
id: 'asc-key-id',
|
||||
keyIdentifier: 'KEY789',
|
||||
issuerIdentifier: 'ISSUER012',
|
||||
appleTeam: {
|
||||
appleTeamIdentifier: 'TEAM123',
|
||||
appleTeamName: 'Test Team',
|
||||
},
|
||||
});
|
||||
(AppStoreConnectApiKeyQuery.getByIdAsync as jest.Mock).mockResolvedValue({
|
||||
keyP8: 'stored-key-p8',
|
||||
keyIdentifier: 'KEY789',
|
||||
issuerIdentifier: 'ISSUER012',
|
||||
});
|
||||
|
||||
const args = createBaseArgs();
|
||||
const result = await getAppStoreAuthAsync(args);
|
||||
|
||||
expect(AppStoreConnectApiKeyQuery.getByIdAsync).toHaveBeenCalledWith(
|
||||
args.graphqlClient,
|
||||
'asc-key-id'
|
||||
);
|
||||
expect(args.credentialsCtx.appStore.ensureAuthenticatedAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
mode: AuthenticationMode.API_KEY,
|
||||
ascApiKey: {
|
||||
keyP8: 'stored-key-p8',
|
||||
keyId: 'KEY789',
|
||||
issuerId: 'ISSUER012',
|
||||
},
|
||||
teamId: 'TEAM123',
|
||||
teamName: 'Test Team',
|
||||
})
|
||||
);
|
||||
expect(result.app).toBe(mockApp);
|
||||
});
|
||||
|
||||
it('falls back to interactive cookie auth when no API key and interactive mode', async () => {
|
||||
const args = createBaseArgs({ nonInteractive: false });
|
||||
|
||||
const result = await getAppStoreAuthAsync(args);
|
||||
|
||||
// Should call ensureAuthenticatedAsync without API key options
|
||||
expect(args.credentialsCtx.appStore.ensureAuthenticatedAsync).toHaveBeenCalledWith();
|
||||
expect(result.app).toBe(mockApp);
|
||||
});
|
||||
|
||||
it('throws in non-interactive mode when no API key is available', async () => {
|
||||
const args = createBaseArgs({ nonInteractive: true });
|
||||
|
||||
await expect(getAppStoreAuthAsync(args)).rejects.toThrow('No App Store Connect API Key found');
|
||||
});
|
||||
|
||||
it('falls back gracefully when credentials service lookup fails', async () => {
|
||||
(getAscApiKeyForAppSubmissionsAsync as jest.Mock).mockRejectedValue(new Error('Network error'));
|
||||
|
||||
// Interactive mode: should fall back to cookie auth
|
||||
const args = createBaseArgs({ nonInteractive: false });
|
||||
const result = await getAppStoreAuthAsync(args);
|
||||
|
||||
expect(args.credentialsCtx.appStore.ensureAuthenticatedAsync).toHaveBeenCalledWith();
|
||||
expect(result.app).toBe(mockApp);
|
||||
});
|
||||
|
||||
it('falls back gracefully when credentials service fails in non-interactive mode', async () => {
|
||||
(getAscApiKeyForAppSubmissionsAsync as jest.Mock).mockRejectedValue(new Error('Network error'));
|
||||
|
||||
const args = createBaseArgs({ nonInteractive: true });
|
||||
|
||||
await expect(getAppStoreAuthAsync(args)).rejects.toThrow('No App Store Connect API Key found');
|
||||
});
|
||||
|
||||
it('prefers submit profile key over credentials service', async () => {
|
||||
const profile = {
|
||||
bundleIdentifier: 'com.example.app',
|
||||
ascApiKeyPath: '/path/to/key.p8',
|
||||
ascApiKeyId: 'PROFILE_KEY',
|
||||
ascApiKeyIssuerId: 'PROFILE_ISSUER',
|
||||
} as any;
|
||||
// Also set up a stored key that should NOT be used
|
||||
(getAscApiKeyForAppSubmissionsAsync as jest.Mock).mockResolvedValue({
|
||||
id: 'stored-key-id',
|
||||
keyIdentifier: 'STORED_KEY',
|
||||
issuerIdentifier: 'STORED_ISSUER',
|
||||
});
|
||||
|
||||
const args = createBaseArgs({ profile });
|
||||
await getAppStoreAuthAsync(args);
|
||||
|
||||
// Should use profile key, not the stored one
|
||||
expect(args.credentialsCtx.appStore.ensureAuthenticatedAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
ascApiKey: expect.objectContaining({ keyId: 'PROFILE_KEY' }),
|
||||
})
|
||||
);
|
||||
// Should NOT have called getByIdAsync since profile key was found first
|
||||
expect(AppStoreConnectApiKeyQuery.getByIdAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import fs from 'fs-extra';
|
||||
|
||||
import { downloadMetadataAsync } from '../download';
|
||||
import { MetadataValidationError } from '../errors';
|
||||
|
||||
jest.mock('../auth', () => ({
|
||||
getAppStoreAuthAsync: jest.fn(() => ({
|
||||
app: { id: '123' },
|
||||
auth: { context: { token: 'mock' } },
|
||||
})),
|
||||
}));
|
||||
|
||||
jest.mock('../apple/tasks', () => ({
|
||||
createAppleTasks: jest.fn(() => []),
|
||||
}));
|
||||
|
||||
jest.mock('../config/resolve', () => ({
|
||||
createAppleWriter: jest.fn(() => ({
|
||||
toSchema: jest.fn(() => ({ configVersion: 0 })),
|
||||
})),
|
||||
getStaticConfigFilePath: jest.fn(() => '/app/store.config.json'),
|
||||
}));
|
||||
|
||||
jest.mock('../utils/telemetry', () => ({
|
||||
subscribeTelemetryAsync: jest.fn(() => ({
|
||||
unsubscribeTelemetry: jest.fn(),
|
||||
executionId: 'exec-123',
|
||||
})),
|
||||
}));
|
||||
|
||||
jest.mock('fs-extra', () => ({
|
||||
pathExists: jest.fn(() => false),
|
||||
writeJSON: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock('../../log');
|
||||
|
||||
jest.mock('../../prompts', () => ({
|
||||
confirmAsync: jest.fn(),
|
||||
}));
|
||||
|
||||
const { confirmAsync } = require('../../prompts') as jest.Mocked<typeof import('../../prompts')>;
|
||||
|
||||
function createArgs(overrides: Record<string, any> = {}) {
|
||||
return {
|
||||
projectDir: '/app',
|
||||
profile: { bundleIdentifier: 'com.example.app' } as any,
|
||||
exp: { slug: 'my-app', name: 'My App' } as any,
|
||||
analytics: {} as any,
|
||||
credentialsCtx: { appStore: { ensureAuthenticatedAsync: jest.fn() }, vcsClient: {} } as any,
|
||||
nonInteractive: false,
|
||||
graphqlClient: {} as any,
|
||||
projectId: 'test-project-id',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe(downloadMetadataAsync, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
(fs.pathExists as jest.Mock).mockResolvedValue(false);
|
||||
});
|
||||
|
||||
it('skips overwrite prompt and auto-overwrites in non-interactive mode', async () => {
|
||||
(fs.pathExists as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
await downloadMetadataAsync(createArgs({ nonInteractive: true }));
|
||||
|
||||
expect(confirmAsync).not.toHaveBeenCalled();
|
||||
expect(fs.writeJSON).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prompts for overwrite in interactive mode when file exists', async () => {
|
||||
(fs.pathExists as jest.Mock).mockResolvedValue(true);
|
||||
(confirmAsync as jest.Mock).mockResolvedValue(true);
|
||||
|
||||
await downloadMetadataAsync(createArgs({ nonInteractive: false }));
|
||||
|
||||
expect(confirmAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ message: expect.stringContaining('overwrite') })
|
||||
);
|
||||
});
|
||||
|
||||
it('throws MetadataValidationError when user declines overwrite in interactive mode', async () => {
|
||||
(fs.pathExists as jest.Mock).mockResolvedValue(true);
|
||||
(confirmAsync as jest.Mock).mockResolvedValue(false);
|
||||
|
||||
await expect(downloadMetadataAsync(createArgs({ nonInteractive: false }))).rejects.toThrow(
|
||||
MetadataValidationError
|
||||
);
|
||||
});
|
||||
|
||||
it('does not prompt when file does not exist', async () => {
|
||||
(fs.pathExists as jest.Mock).mockResolvedValue(false);
|
||||
|
||||
await downloadMetadataAsync(createArgs({ nonInteractive: false }));
|
||||
|
||||
expect(confirmAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { uploadMetadataAsync } from '../upload';
|
||||
import { MetadataValidationError } from '../errors';
|
||||
|
||||
jest.mock('../auth', () => ({
|
||||
getAppStoreAuthAsync: jest.fn(() => ({
|
||||
app: { id: '123' },
|
||||
auth: { context: { token: 'mock' } },
|
||||
})),
|
||||
}));
|
||||
|
||||
jest.mock('../apple/tasks', () => ({
|
||||
createAppleTasks: jest.fn(() => []),
|
||||
}));
|
||||
|
||||
jest.mock('../config/resolve', () => ({
|
||||
createAppleReader: jest.fn(() => ({
|
||||
getVersion: jest.fn(() => ({ versionString: '1.0.0' })),
|
||||
})),
|
||||
loadConfigAsync: jest.fn(() => ({ configVersion: 0 })),
|
||||
}));
|
||||
|
||||
jest.mock('../utils/telemetry', () => ({
|
||||
subscribeTelemetryAsync: jest.fn(() => ({
|
||||
unsubscribeTelemetry: jest.fn(),
|
||||
executionId: 'exec-123',
|
||||
})),
|
||||
}));
|
||||
|
||||
jest.mock('../../log');
|
||||
|
||||
jest.mock('../../prompts', () => ({
|
||||
confirmAsync: jest.fn(),
|
||||
}));
|
||||
|
||||
const { loadConfigAsync } = require('../config/resolve') as jest.Mocked<
|
||||
typeof import('../config/resolve')
|
||||
>;
|
||||
const { confirmAsync } = require('../../prompts') as jest.Mocked<typeof import('../../prompts')>;
|
||||
|
||||
function createArgs(overrides: Record<string, any> = {}) {
|
||||
return {
|
||||
projectDir: '/app',
|
||||
profile: { metadataPath: 'store.config.json', bundleIdentifier: 'com.example.app' } as any,
|
||||
exp: { slug: 'my-app', name: 'My App' } as any,
|
||||
analytics: {} as any,
|
||||
credentialsCtx: { appStore: { ensureAuthenticatedAsync: jest.fn() }, vcsClient: {} } as any,
|
||||
nonInteractive: false,
|
||||
graphqlClient: {} as any,
|
||||
projectId: 'test-project-id',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe(uploadMetadataAsync, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
(loadConfigAsync as jest.Mock).mockResolvedValue({ configVersion: 0 });
|
||||
});
|
||||
|
||||
it('throws MetadataValidationError directly in non-interactive mode without prompting', async () => {
|
||||
(loadConfigAsync as jest.Mock).mockRejectedValue(
|
||||
new MetadataValidationError('validation errors found')
|
||||
);
|
||||
|
||||
await expect(uploadMetadataAsync(createArgs({ nonInteractive: true }))).rejects.toThrow(
|
||||
MetadataValidationError
|
||||
);
|
||||
expect(confirmAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prompts user about validation errors in interactive mode', async () => {
|
||||
(loadConfigAsync as jest.Mock).mockRejectedValueOnce(
|
||||
new MetadataValidationError('validation errors found')
|
||||
);
|
||||
(confirmAsync as jest.Mock).mockResolvedValue(true);
|
||||
// Second call (with skipValidation) succeeds
|
||||
(loadConfigAsync as jest.Mock).mockResolvedValueOnce({ configVersion: 0 });
|
||||
|
||||
await uploadMetadataAsync(createArgs({ nonInteractive: false }));
|
||||
|
||||
expect(confirmAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ message: expect.stringContaining('still want to push') })
|
||||
);
|
||||
});
|
||||
|
||||
it('re-throws validation error when user declines to continue in interactive mode', async () => {
|
||||
(loadConfigAsync as jest.Mock).mockRejectedValue(
|
||||
new MetadataValidationError('validation errors found')
|
||||
);
|
||||
(confirmAsync as jest.Mock).mockResolvedValue(false);
|
||||
|
||||
await expect(uploadMetadataAsync(createArgs({ nonInteractive: false }))).rejects.toThrow(
|
||||
MetadataValidationError
|
||||
);
|
||||
});
|
||||
|
||||
it('uploads successfully when config is valid', async () => {
|
||||
const result = await uploadMetadataAsync(createArgs());
|
||||
|
||||
expect(result).toHaveProperty('appleLink');
|
||||
expect(result.appleLink).toContain('appstoreconnect.apple.com');
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
import uniq from '../../../utils/expodash/uniq';
|
||||
import { AttributesOf } from '../../utils/asc';
|
||||
import { removeDatePrecision } from '../../utils/date';
|
||||
import { AppleMetadata } from '../types';
|
||||
import { AppleMetadata, ApplePreviews, AppleScreenshots } from '../types';
|
||||
|
||||
type PartialExcept<T, K extends keyof T> = Pick<T, K> & Partial<Omit<T, K>>;
|
||||
|
||||
@@ -211,4 +211,14 @@ export class AppleConfigReader {
|
||||
// TODO: add attachment
|
||||
};
|
||||
}
|
||||
|
||||
/** Get screenshots configuration for a specific locale */
|
||||
public getScreenshots(locale: string): AppleScreenshots | null {
|
||||
return this.schema.info?.[locale]?.screenshots ?? null;
|
||||
}
|
||||
|
||||
/** Get video previews configuration for a specific locale */
|
||||
public getPreviews(locale: string): ApplePreviews | null {
|
||||
return this.schema.info?.[locale]?.previews ?? null;
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from '@expo/apple-utils';
|
||||
|
||||
import { AttributesOf } from '../../utils/asc';
|
||||
import { AppleMetadata } from '../types';
|
||||
import { AppleMetadata, ApplePreviews, AppleScreenshots } from '../types';
|
||||
|
||||
/**
|
||||
* Serializes the Apple ASC entities into the metadata configuration schema.
|
||||
@@ -186,6 +186,21 @@ export class AppleConfigWriter {
|
||||
// TODO: add attachment
|
||||
};
|
||||
}
|
||||
|
||||
/** Set screenshots for a specific locale */
|
||||
public setScreenshots(locale: string, screenshots: AppleScreenshots): void {
|
||||
this.schema.info = this.schema.info ?? {};
|
||||
this.schema.info[locale] = this.schema.info[locale] ?? { title: '' };
|
||||
this.schema.info[locale].screenshots =
|
||||
Object.keys(screenshots).length > 0 ? screenshots : undefined;
|
||||
}
|
||||
|
||||
/** Set video previews for a specific locale */
|
||||
public setPreviews(locale: string, previews: ApplePreviews): void {
|
||||
this.schema.info = this.schema.info ?? {};
|
||||
this.schema.info[locale] = this.schema.info[locale] ?? { title: '' };
|
||||
this.schema.info[locale].previews = Object.keys(previews).length > 0 ? previews : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Helper function to convert `T | null` to `T | undefined`, required for the entity properties */
|
||||
|
||||
@@ -4,16 +4,25 @@ import type { AgeRatingData } from './tasks/age-rating';
|
||||
import type { AppInfoData } from './tasks/app-info';
|
||||
import type { AppReviewData } from './tasks/app-review-detail';
|
||||
import type { AppVersionData } from './tasks/app-version';
|
||||
import type { PreviewsData } from './tasks/previews';
|
||||
import type { ScreenshotsData } from './tasks/screenshots';
|
||||
|
||||
/**
|
||||
* The fully prepared apple data, used within the `downloadAsync` or `uploadAsync` tasks.
|
||||
* It contains references to each individual models, to either upload or download App Store data.
|
||||
*/
|
||||
export type AppleData = { app: App } & AppInfoData & AppVersionData & AgeRatingData & AppReviewData;
|
||||
export type AppleData = { app: App; projectDir: string } & AppInfoData &
|
||||
AppVersionData &
|
||||
AgeRatingData &
|
||||
AppReviewData &
|
||||
ScreenshotsData &
|
||||
PreviewsData;
|
||||
|
||||
/**
|
||||
* The unprepared partial apple data, used within the `prepareAsync` tasks.
|
||||
* It contains a reference to the app, each task should populate the necessary data.
|
||||
* If an entity fails to prepare the data, individual tasks should raise errors about the missing data.
|
||||
*/
|
||||
export type PartialAppleData = { app: App } & Partial<Omit<AppleData, 'app'>>;
|
||||
export type PartialAppleData = { app: App; projectDir: string } & Partial<
|
||||
Omit<AppleData, 'app' | 'projectDir'>
|
||||
>;
|
||||
@@ -1,8 +1,14 @@
|
||||
import { truthy } from '../../../utils/expodash/filter';
|
||||
import { IssueRule } from '../../config/issue';
|
||||
import { AppleInfo } from '../types';
|
||||
|
||||
const RESTRICTED_PROPERTIES: (keyof AppleInfo)[] = ['title', 'subtitle', 'description', 'keywords'];
|
||||
/** Only check text properties that may contain restricted words */
|
||||
type AppleInfoTextProperty = 'title' | 'subtitle' | 'description' | 'keywords';
|
||||
const RESTRICTED_PROPERTIES: AppleInfoTextProperty[] = [
|
||||
'title',
|
||||
'subtitle',
|
||||
'description',
|
||||
'keywords',
|
||||
];
|
||||
const RESTRICTED_WORDS = {
|
||||
beta: 'Apple restricts the word "beta" and synonyms implying incomplete functionality.',
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AgeRatingDeclaration, AppStoreVersion, Rating } from '@expo/apple-utils';
|
||||
import { AgeRatingDeclaration, AppInfo, Rating } from '@expo/apple-utils';
|
||||
import nock from 'nock';
|
||||
|
||||
import { requestContext } from './fixtures/requestContext';
|
||||
@@ -12,13 +12,13 @@ jest.mock('../../config/writer');
|
||||
|
||||
describe(AgeRatingTask, () => {
|
||||
describe('prepareAsync', () => {
|
||||
it('loads age rating from app version', async () => {
|
||||
it('loads age rating from app info', async () => {
|
||||
const scope = nock('https://api.appstoreconnect.apple.com')
|
||||
.get(`/v1/${AppStoreVersion.type}/stub-id/ageRatingDeclaration`)
|
||||
.get(`/v1/${AppInfo.type}/stub-id/ageRatingDeclaration`)
|
||||
.reply(200, require('./fixtures/appStoreVersions/get-ageRatingDeclaration-200.json'));
|
||||
|
||||
const context: any = {
|
||||
version: new AppStoreVersion(requestContext, 'stub-id', {} as any),
|
||||
info: new AppInfo(requestContext, 'stub-id', {} as any),
|
||||
};
|
||||
|
||||
await new AgeRatingTask().prepareAsync({ context });
|
||||
@@ -26,6 +26,16 @@ describe(AgeRatingTask, () => {
|
||||
expect(context.ageRating).toBeInstanceOf(AgeRatingDeclaration);
|
||||
expect(scope.isDone()).toBeTruthy();
|
||||
});
|
||||
|
||||
it('skips when info is not available', async () => {
|
||||
const context: any = {
|
||||
info: undefined,
|
||||
};
|
||||
|
||||
await new AgeRatingTask().prepareAsync({ context });
|
||||
|
||||
expect(context.ageRating).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('downloadAsync', () => {
|
||||
@@ -54,13 +64,13 @@ describe(AgeRatingTask, () => {
|
||||
});
|
||||
|
||||
describe('uploadAsync', () => {
|
||||
it('aborts when age rating is not loaded', async () => {
|
||||
const promise = new AgeRatingTask().uploadAsync({
|
||||
config: new AppleConfigReader({}),
|
||||
context: { ageRating: undefined } as any,
|
||||
});
|
||||
|
||||
await expect(promise).rejects.toThrow('rating not initialized');
|
||||
it('skips when age rating is not loaded', async () => {
|
||||
await expect(
|
||||
new AgeRatingTask().uploadAsync({
|
||||
config: new AppleConfigReader({}),
|
||||
context: { ageRating: undefined } as any,
|
||||
})
|
||||
).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
it('skips updating age rating when not configured', async () => {
|
||||
|
||||
@@ -23,6 +23,7 @@ describe(AppInfoTask, () => {
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: new App(requestContext, 'stub-id', {} as any),
|
||||
projectDir: '/test/project',
|
||||
};
|
||||
|
||||
await new AppInfoTask().prepareAsync({ context });
|
||||
|
||||
@@ -72,20 +72,20 @@ describe(AppReviewDetailTask, () => {
|
||||
nock.cleanAll();
|
||||
});
|
||||
|
||||
it('aborts when version is not loaded', async () => {
|
||||
const promise = new AppReviewDetailTask().uploadAsync({
|
||||
config: new AppleConfigReader({
|
||||
review: {
|
||||
firstName: 'Evan',
|
||||
lastName: 'Bacon',
|
||||
email: 'review@example.com',
|
||||
phone: '+1 555 555 5555',
|
||||
},
|
||||
}),
|
||||
context: {} as any,
|
||||
});
|
||||
|
||||
await expect(promise).rejects.toThrow('version not init');
|
||||
it('skips when version is not loaded', async () => {
|
||||
await expect(
|
||||
new AppReviewDetailTask().uploadAsync({
|
||||
config: new AppleConfigReader({
|
||||
review: {
|
||||
firstName: 'Evan',
|
||||
lastName: 'Bacon',
|
||||
email: '[email protected]',
|
||||
phone: '+1 555 555 5555',
|
||||
},
|
||||
}),
|
||||
context: {} as any,
|
||||
})
|
||||
).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
it('updates review details when loaded', async () => {
|
||||
|
||||
@@ -44,6 +44,7 @@ describe(AppVersionTask, () => {
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: new App(requestContext, 'stub-id', {} as any),
|
||||
projectDir: '/test/project',
|
||||
};
|
||||
|
||||
await new AppVersionTask({ editLive: true }).prepareAsync({ context });
|
||||
@@ -83,6 +84,7 @@ describe(AppVersionTask, () => {
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: new App(requestContext, 'stub-id', {} as any),
|
||||
projectDir: '/test/project',
|
||||
};
|
||||
|
||||
await new AppVersionTask({ editLive: true }).prepareAsync({ context });
|
||||
@@ -118,6 +120,7 @@ describe(AppVersionTask, () => {
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: new App(requestContext, 'stub-id', {} as any),
|
||||
projectDir: '/test/project',
|
||||
};
|
||||
|
||||
await new AppVersionTask().prepareAsync({ context });
|
||||
@@ -153,6 +156,7 @@ describe(AppVersionTask, () => {
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: new App(requestContext, 'stub-id', {} as any),
|
||||
projectDir: '/test/project',
|
||||
};
|
||||
|
||||
await new AppVersionTask().prepareAsync({ context });
|
||||
@@ -194,6 +198,7 @@ describe(AppVersionTask, () => {
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: new App(requestContext, 'stub-id', {} as any),
|
||||
projectDir: '/test/project',
|
||||
};
|
||||
|
||||
await new AppVersionTask({ version: '2.0' }).prepareAsync({ context });
|
||||
@@ -243,6 +248,7 @@ describe(AppVersionTask, () => {
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: new App(requestContext, 'stub-id', {} as any),
|
||||
projectDir: '/test/project',
|
||||
};
|
||||
|
||||
await new AppVersionTask({ version: '3.0' }).prepareAsync({ context });
|
||||
@@ -371,6 +377,7 @@ describe(AppVersionTask, () => {
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: new App(requestContext, 'stub-id', {} as any),
|
||||
projectDir: '/test/project',
|
||||
version: new AppStoreVersion(requestContext, 'APP_STORE_VERSION_1', {} as any),
|
||||
};
|
||||
|
||||
@@ -399,6 +406,7 @@ describe(AppVersionTask, () => {
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: new App(requestContext, 'stub-id', {} as any),
|
||||
projectDir: '/test/project',
|
||||
version: new AppStoreVersion(requestContext, 'APP_STORE_VERSION_1', {} as any),
|
||||
versionPhasedRelease: null, // Not enabled yet
|
||||
};
|
||||
@@ -417,6 +425,7 @@ describe(AppVersionTask, () => {
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: new App(requestContext, 'stub-id', {} as any),
|
||||
projectDir: '/test/project',
|
||||
version: new AppStoreVersion(requestContext, 'APP_STORE_VERSION_1', {} as any),
|
||||
// Enabled, and not completed yet
|
||||
versionPhasedRelease: new AppStoreVersionPhasedRelease(
|
||||
@@ -440,8 +449,9 @@ describe(AppVersionTask, () => {
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: new App(requestContext, 'stub-id', {} as any),
|
||||
projectDir: '/test/project',
|
||||
version: new AppStoreVersion(requestContext, 'APP_STORE_VERSION_1', {} as any),
|
||||
// Enabled, and not completed yet
|
||||
// Enabled, and completed
|
||||
versionPhasedRelease: new AppStoreVersionPhasedRelease(
|
||||
requestContext,
|
||||
'APP_STORE_VERSION_PHASED_RELEASE_1',
|
||||
|
||||
@@ -0,0 +1,405 @@
|
||||
import {
|
||||
AppPreview,
|
||||
AppPreviewSet,
|
||||
AppStoreVersionLocalization,
|
||||
PreviewType,
|
||||
} from '@expo/apple-utils';
|
||||
import nock from 'nock';
|
||||
|
||||
import { requestContext } from './fixtures/requestContext';
|
||||
import { AppleConfigReader } from '../../config/reader';
|
||||
import { AppleConfigWriter } from '../../config/writer';
|
||||
import { PartialAppleData } from '../../data';
|
||||
import { PreviewsTask } from '../previews';
|
||||
|
||||
jest.mock('../../../../ora');
|
||||
jest.mock('../../config/writer');
|
||||
|
||||
const mockFetch = jest.fn();
|
||||
jest.mock('../../../../fetch', () => ({
|
||||
__esModule: true,
|
||||
default: (...args: any[]) => mockFetch(...args),
|
||||
}));
|
||||
|
||||
import fs from 'fs';
|
||||
|
||||
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
|
||||
jest.spyOn(fs, 'statSync').mockReturnValue({ size: 10240 } as any);
|
||||
jest.spyOn(fs.promises, 'mkdir').mockResolvedValue(undefined);
|
||||
jest.spyOn(fs.promises, 'writeFile').mockResolvedValue(undefined);
|
||||
|
||||
describe(PreviewsTask, () => {
|
||||
beforeEach(() => {
|
||||
nock.cleanAll();
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('prepareAsync', () => {
|
||||
it('initializes empty preview sets when no locales are available', async () => {
|
||||
const context: PartialAppleData = {
|
||||
app: {} as any,
|
||||
projectDir: '/test/project',
|
||||
versionLocales: undefined,
|
||||
};
|
||||
|
||||
await new PreviewsTask().prepareAsync({ context });
|
||||
|
||||
expect(context.previewSets).toBeDefined();
|
||||
expect(context.previewSets!.size).toBe(0);
|
||||
});
|
||||
|
||||
it('fetches preview sets for each locale', async () => {
|
||||
const locale = new AppStoreVersionLocalization(requestContext, 'LOC_1', {
|
||||
locale: 'en-US',
|
||||
} as any);
|
||||
|
||||
const scope = nock('https://api.appstoreconnect.apple.com')
|
||||
.get(`/v1/${AppStoreVersionLocalization.type}/LOC_1/${AppPreviewSet.type}`)
|
||||
.query(true)
|
||||
.reply(200, {
|
||||
data: [
|
||||
{
|
||||
id: 'PSET_1',
|
||||
type: AppPreviewSet.type,
|
||||
attributes: {
|
||||
previewType: PreviewType.IPHONE_67,
|
||||
appPreviews: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: {} as any,
|
||||
projectDir: '/test/project',
|
||||
versionLocales: [locale],
|
||||
};
|
||||
|
||||
await new PreviewsTask().prepareAsync({ context });
|
||||
|
||||
expect(context.previewSets).toBeDefined();
|
||||
expect(context.previewSets!.size).toBe(1);
|
||||
expect(context.previewSets!.get('en-US')).toBeDefined();
|
||||
expect(context.previewSets!.get('en-US')!.has(PreviewType.IPHONE_67)).toBeTruthy();
|
||||
expect(scope.isDone()).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('downloadAsync', () => {
|
||||
it('skips when preview sets are not prepared', async () => {
|
||||
const writer = jest.mocked(new AppleConfigWriter());
|
||||
|
||||
await new PreviewsTask().downloadAsync({
|
||||
config: writer,
|
||||
context: { previewSets: undefined, versionLocales: undefined } as any,
|
||||
});
|
||||
|
||||
expect(writer.setPreviews).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('skips locales with no preview sets', async () => {
|
||||
const writer = jest.mocked(new AppleConfigWriter());
|
||||
const previewSets = new Map();
|
||||
previewSets.set('en-US', new Map());
|
||||
|
||||
const locale = new AppStoreVersionLocalization(requestContext, 'LOC_1', {
|
||||
locale: 'en-US',
|
||||
} as any);
|
||||
|
||||
await new PreviewsTask().downloadAsync({
|
||||
config: writer,
|
||||
context: {
|
||||
previewSets,
|
||||
versionLocales: [locale],
|
||||
} as any,
|
||||
});
|
||||
|
||||
expect(writer.setPreviews).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('downloads previews and sets config with simple path', async () => {
|
||||
const writer = jest.mocked(new AppleConfigWriter());
|
||||
|
||||
const preview = new AppPreview(requestContext, 'PV_1', {
|
||||
fileName: 'demo.mp4',
|
||||
fileSize: 10240,
|
||||
previewFrameTimeCode: null,
|
||||
videoUrl: 'https://example.com/demo.mp4',
|
||||
assetDeliveryState: {
|
||||
state: 'COMPLETE',
|
||||
errors: [],
|
||||
warnings: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
jest.spyOn(preview, 'getVideoUrl').mockReturnValue('https://example.com/demo.mp4');
|
||||
|
||||
const previewTypeMap = new Map<PreviewType, AppPreviewSet>();
|
||||
const previewSet = new AppPreviewSet(requestContext, 'PSET_1', {
|
||||
previewType: PreviewType.IPHONE_67,
|
||||
appPreviews: [preview],
|
||||
} as any);
|
||||
previewTypeMap.set(PreviewType.IPHONE_67, previewSet);
|
||||
|
||||
const previewSets = new Map();
|
||||
previewSets.set('en-US', previewTypeMap);
|
||||
|
||||
const locale = new AppStoreVersionLocalization(requestContext, 'LOC_1', {
|
||||
locale: 'en-US',
|
||||
} as any);
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
buffer: () => Promise.resolve(Buffer.from('fake-video-data')),
|
||||
});
|
||||
|
||||
await new PreviewsTask().downloadAsync({
|
||||
config: writer,
|
||||
context: {
|
||||
previewSets,
|
||||
versionLocales: [locale],
|
||||
projectDir: '/test/project',
|
||||
} as any,
|
||||
});
|
||||
|
||||
expect(writer.setPreviews).toBeCalledWith('en-US', {
|
||||
[PreviewType.IPHONE_67]: 'store/apple/preview/en-US/IPHONE_67/demo.mp4',
|
||||
});
|
||||
});
|
||||
|
||||
it('downloads previews with previewFrameTimeCode as object config', async () => {
|
||||
const writer = jest.mocked(new AppleConfigWriter());
|
||||
|
||||
const preview = new AppPreview(requestContext, 'PV_1', {
|
||||
fileName: 'demo.mp4',
|
||||
fileSize: 10240,
|
||||
previewFrameTimeCode: '00:05:00',
|
||||
videoUrl: 'https://example.com/demo.mp4',
|
||||
assetDeliveryState: {
|
||||
state: 'COMPLETE',
|
||||
errors: [],
|
||||
warnings: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
jest.spyOn(preview, 'getVideoUrl').mockReturnValue('https://example.com/demo.mp4');
|
||||
|
||||
const previewTypeMap = new Map<PreviewType, AppPreviewSet>();
|
||||
const previewSet = new AppPreviewSet(requestContext, 'PSET_1', {
|
||||
previewType: PreviewType.IPHONE_67,
|
||||
appPreviews: [preview],
|
||||
} as any);
|
||||
previewTypeMap.set(PreviewType.IPHONE_67, previewSet);
|
||||
|
||||
const previewSets = new Map();
|
||||
previewSets.set('en-US', previewTypeMap);
|
||||
|
||||
const locale = new AppStoreVersionLocalization(requestContext, 'LOC_1', {
|
||||
locale: 'en-US',
|
||||
} as any);
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
buffer: () => Promise.resolve(Buffer.from('fake-video-data')),
|
||||
});
|
||||
|
||||
await new PreviewsTask().downloadAsync({
|
||||
config: writer,
|
||||
context: {
|
||||
previewSets,
|
||||
versionLocales: [locale],
|
||||
projectDir: '/test/project',
|
||||
} as any,
|
||||
});
|
||||
|
||||
expect(writer.setPreviews).toBeCalledWith('en-US', {
|
||||
[PreviewType.IPHONE_67]: {
|
||||
path: 'store/apple/preview/en-US/IPHONE_67/demo.mp4',
|
||||
previewFrameTimeCode: '00:05:00',
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploadAsync', () => {
|
||||
it('skips when preview sets are not prepared', async () => {
|
||||
const config = new AppleConfigReader({});
|
||||
|
||||
await new PreviewsTask().uploadAsync({
|
||||
config,
|
||||
context: { previewSets: undefined, versionLocales: undefined } as any,
|
||||
});
|
||||
|
||||
// Should not throw, just log and return
|
||||
});
|
||||
|
||||
it('skips when no locales are configured', async () => {
|
||||
const config = new AppleConfigReader({});
|
||||
|
||||
await new PreviewsTask().uploadAsync({
|
||||
config,
|
||||
context: {
|
||||
previewSets: new Map(),
|
||||
versionLocales: [],
|
||||
} as any,
|
||||
});
|
||||
|
||||
// Should not throw, just log and return
|
||||
});
|
||||
|
||||
it('skips locales without previews in config', async () => {
|
||||
const config = new AppleConfigReader({
|
||||
info: {
|
||||
'en-US': {
|
||||
title: 'My App',
|
||||
// No previews
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const locale = new AppStoreVersionLocalization(requestContext, 'LOC_1', {
|
||||
locale: 'en-US',
|
||||
} as any);
|
||||
|
||||
await new PreviewsTask().uploadAsync({
|
||||
config,
|
||||
context: {
|
||||
previewSets: new Map(),
|
||||
versionLocales: [locale],
|
||||
} as any,
|
||||
});
|
||||
|
||||
// Should complete without uploading
|
||||
});
|
||||
|
||||
it('uploads new preview for configured locale with string path', async () => {
|
||||
const config = new AppleConfigReader({
|
||||
info: {
|
||||
'en-US': {
|
||||
title: 'My App',
|
||||
previews: {
|
||||
IPHONE_67: './previews/demo.mp4',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const locale = new AppStoreVersionLocalization(requestContext, 'LOC_1', {
|
||||
locale: 'en-US',
|
||||
} as any);
|
||||
|
||||
const newPreview = new AppPreview(requestContext, 'NEW_PV_1', {
|
||||
fileName: 'demo.mp4',
|
||||
fileSize: 10240,
|
||||
previewFrameTimeCode: null,
|
||||
assetDeliveryState: { state: 'COMPLETE', errors: [], warnings: [] },
|
||||
} as any);
|
||||
|
||||
const scope = nock('https://api.appstoreconnect.apple.com')
|
||||
// Create preview set
|
||||
.post(`/v1/${AppPreviewSet.type}`)
|
||||
.reply(201, {
|
||||
data: {
|
||||
id: 'NEW_PSET_1',
|
||||
type: AppPreviewSet.type,
|
||||
attributes: {
|
||||
previewType: PreviewType.IPHONE_67,
|
||||
appPreviews: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Mock AppPreview.uploadAsync to avoid real file access
|
||||
jest.spyOn(AppPreview, 'uploadAsync').mockResolvedValue(newPreview);
|
||||
|
||||
const previewSets = new Map();
|
||||
previewSets.set('en-US', new Map());
|
||||
|
||||
await new PreviewsTask().uploadAsync({
|
||||
config,
|
||||
context: {
|
||||
previewSets,
|
||||
versionLocales: [locale],
|
||||
projectDir: '/test/project',
|
||||
} as any,
|
||||
});
|
||||
|
||||
expect(scope.isDone()).toBeTruthy();
|
||||
expect(AppPreview.uploadAsync).toHaveBeenCalledWith(
|
||||
requestContext,
|
||||
expect.objectContaining({
|
||||
id: 'NEW_PSET_1',
|
||||
filePath: '/test/project/previews/demo.mp4',
|
||||
waitForProcessing: true,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('uploads new preview with object config including previewFrameTimeCode', async () => {
|
||||
const config = new AppleConfigReader({
|
||||
info: {
|
||||
'en-US': {
|
||||
title: 'My App',
|
||||
previews: {
|
||||
IPHONE_67: {
|
||||
path: './previews/demo.mp4',
|
||||
previewFrameTimeCode: '00:05:00',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const locale = new AppStoreVersionLocalization(requestContext, 'LOC_1', {
|
||||
locale: 'en-US',
|
||||
} as any);
|
||||
|
||||
const newPreview = new AppPreview(requestContext, 'NEW_PV_1', {
|
||||
fileName: 'demo.mp4',
|
||||
fileSize: 10240,
|
||||
previewFrameTimeCode: '00:05:00',
|
||||
assetDeliveryState: { state: 'COMPLETE', errors: [], warnings: [] },
|
||||
} as any);
|
||||
|
||||
const scope = nock('https://api.appstoreconnect.apple.com')
|
||||
// Create preview set
|
||||
.post(`/v1/${AppPreviewSet.type}`)
|
||||
.reply(201, {
|
||||
data: {
|
||||
id: 'NEW_PSET_1',
|
||||
type: AppPreviewSet.type,
|
||||
attributes: {
|
||||
previewType: PreviewType.IPHONE_67,
|
||||
appPreviews: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Mock AppPreview.uploadAsync to avoid real file access
|
||||
jest.spyOn(AppPreview, 'uploadAsync').mockResolvedValue(newPreview);
|
||||
|
||||
const previewSets = new Map();
|
||||
previewSets.set('en-US', new Map());
|
||||
|
||||
await new PreviewsTask().uploadAsync({
|
||||
config,
|
||||
context: {
|
||||
previewSets,
|
||||
versionLocales: [locale],
|
||||
projectDir: '/test/project',
|
||||
} as any,
|
||||
});
|
||||
|
||||
expect(scope.isDone()).toBeTruthy();
|
||||
expect(AppPreview.uploadAsync).toHaveBeenCalledWith(
|
||||
requestContext,
|
||||
expect.objectContaining({
|
||||
id: 'NEW_PSET_1',
|
||||
filePath: '/test/project/previews/demo.mp4',
|
||||
waitForProcessing: true,
|
||||
previewFrameTimeCode: '00:05:00',
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,303 @@
|
||||
import {
|
||||
AppScreenshot,
|
||||
AppScreenshotSet,
|
||||
AppStoreVersionLocalization,
|
||||
ScreenshotDisplayType,
|
||||
} from '@expo/apple-utils';
|
||||
import nock from 'nock';
|
||||
|
||||
import { requestContext } from './fixtures/requestContext';
|
||||
import { AppleConfigReader } from '../../config/reader';
|
||||
import { AppleConfigWriter } from '../../config/writer';
|
||||
import { PartialAppleData } from '../../data';
|
||||
import { ScreenshotsTask } from '../screenshots';
|
||||
|
||||
jest.mock('../../../../ora');
|
||||
jest.mock('../../config/writer');
|
||||
|
||||
const mockFetch = jest.fn();
|
||||
jest.mock('../../../../fetch', () => ({
|
||||
__esModule: true,
|
||||
default: (...args: any[]) => mockFetch(...args),
|
||||
}));
|
||||
|
||||
import fs from 'fs';
|
||||
|
||||
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
|
||||
jest.spyOn(fs, 'statSync').mockReturnValue({ size: 1024 } as any);
|
||||
jest.spyOn(fs.promises, 'mkdir').mockResolvedValue(undefined);
|
||||
jest.spyOn(fs.promises, 'writeFile').mockResolvedValue(undefined);
|
||||
|
||||
describe(ScreenshotsTask, () => {
|
||||
beforeEach(() => {
|
||||
nock.cleanAll();
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('prepareAsync', () => {
|
||||
it('initializes empty screenshot sets when no locales are available', async () => {
|
||||
const context: PartialAppleData = {
|
||||
app: {} as any,
|
||||
projectDir: '/test/project',
|
||||
versionLocales: undefined,
|
||||
};
|
||||
|
||||
await new ScreenshotsTask().prepareAsync({ context });
|
||||
|
||||
expect(context.screenshotSets).toBeDefined();
|
||||
expect(context.screenshotSets!.size).toBe(0);
|
||||
});
|
||||
|
||||
it('fetches screenshot sets for each locale', async () => {
|
||||
const locale = new AppStoreVersionLocalization(requestContext, 'LOC_1', {
|
||||
locale: 'en-US',
|
||||
} as any);
|
||||
|
||||
const scope = nock('https://api.appstoreconnect.apple.com')
|
||||
.get(`/v1/${AppStoreVersionLocalization.type}/LOC_1/${AppScreenshotSet.type}`)
|
||||
.query(true)
|
||||
.reply(200, {
|
||||
data: [
|
||||
{
|
||||
id: 'SET_1',
|
||||
type: AppScreenshotSet.type,
|
||||
attributes: {
|
||||
screenshotDisplayType: ScreenshotDisplayType.APP_IPHONE_67,
|
||||
appScreenshots: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const context: PartialAppleData = {
|
||||
app: {} as any,
|
||||
projectDir: '/test/project',
|
||||
versionLocales: [locale],
|
||||
};
|
||||
|
||||
await new ScreenshotsTask().prepareAsync({ context });
|
||||
|
||||
expect(context.screenshotSets).toBeDefined();
|
||||
expect(context.screenshotSets!.size).toBe(1);
|
||||
expect(context.screenshotSets!.get('en-US')).toBeDefined();
|
||||
expect(
|
||||
context.screenshotSets!.get('en-US')!.has(ScreenshotDisplayType.APP_IPHONE_67)
|
||||
).toBeTruthy();
|
||||
expect(scope.isDone()).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('downloadAsync', () => {
|
||||
it('skips when screenshot sets are not prepared', async () => {
|
||||
const writer = jest.mocked(new AppleConfigWriter());
|
||||
|
||||
await new ScreenshotsTask().downloadAsync({
|
||||
config: writer,
|
||||
context: { screenshotSets: undefined, versionLocales: undefined } as any,
|
||||
});
|
||||
|
||||
expect(writer.setScreenshots).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('skips locales with no screenshot sets', async () => {
|
||||
const writer = jest.mocked(new AppleConfigWriter());
|
||||
const screenshotSets = new Map();
|
||||
screenshotSets.set('en-US', new Map());
|
||||
|
||||
const locale = new AppStoreVersionLocalization(requestContext, 'LOC_1', {
|
||||
locale: 'en-US',
|
||||
} as any);
|
||||
|
||||
await new ScreenshotsTask().downloadAsync({
|
||||
config: writer,
|
||||
context: {
|
||||
screenshotSets,
|
||||
versionLocales: [locale],
|
||||
} as any,
|
||||
});
|
||||
|
||||
expect(writer.setScreenshots).not.toBeCalled();
|
||||
});
|
||||
|
||||
it('downloads screenshots and sets config', async () => {
|
||||
const writer = jest.mocked(new AppleConfigWriter());
|
||||
|
||||
const screenshot = new AppScreenshot(requestContext, 'SS_1', {
|
||||
fileName: 'home.png',
|
||||
fileSize: 1024,
|
||||
assetDeliveryState: {
|
||||
state: 'COMPLETE',
|
||||
errors: [],
|
||||
warnings: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
// Mock getImageAssetUrl
|
||||
jest.spyOn(screenshot, 'getImageAssetUrl').mockReturnValue('https://example.com/home.png');
|
||||
|
||||
const displayTypeMap = new Map<ScreenshotDisplayType, AppScreenshotSet>();
|
||||
const screenshotSet = new AppScreenshotSet(requestContext, 'SET_1', {
|
||||
screenshotDisplayType: ScreenshotDisplayType.APP_IPHONE_67,
|
||||
appScreenshots: [screenshot],
|
||||
} as any);
|
||||
displayTypeMap.set(ScreenshotDisplayType.APP_IPHONE_67, screenshotSet);
|
||||
|
||||
const screenshotSets = new Map();
|
||||
screenshotSets.set('en-US', displayTypeMap);
|
||||
|
||||
const locale = new AppStoreVersionLocalization(requestContext, 'LOC_1', {
|
||||
locale: 'en-US',
|
||||
} as any);
|
||||
|
||||
// Mock fetch response
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
buffer: () => Promise.resolve(Buffer.from('fake-image-data')),
|
||||
});
|
||||
|
||||
await new ScreenshotsTask().downloadAsync({
|
||||
config: writer,
|
||||
context: {
|
||||
screenshotSets,
|
||||
versionLocales: [locale],
|
||||
projectDir: '/test/project',
|
||||
} as any,
|
||||
});
|
||||
|
||||
expect(writer.setScreenshots).toBeCalledWith('en-US', {
|
||||
[ScreenshotDisplayType.APP_IPHONE_67]: [
|
||||
'store/apple/screenshot/en-US/APP_IPHONE_67/home.png',
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploadAsync', () => {
|
||||
it('skips when screenshot sets are not prepared', async () => {
|
||||
const config = new AppleConfigReader({});
|
||||
|
||||
await new ScreenshotsTask().uploadAsync({
|
||||
config,
|
||||
context: { screenshotSets: undefined, versionLocales: undefined } as any,
|
||||
});
|
||||
|
||||
// Should not throw, just log and return
|
||||
});
|
||||
|
||||
it('skips when no locales are configured', async () => {
|
||||
const config = new AppleConfigReader({});
|
||||
|
||||
await new ScreenshotsTask().uploadAsync({
|
||||
config,
|
||||
context: {
|
||||
screenshotSets: new Map(),
|
||||
versionLocales: [],
|
||||
} as any,
|
||||
});
|
||||
|
||||
// Should not throw, just log and return
|
||||
});
|
||||
|
||||
it('skips locales without screenshots in config', async () => {
|
||||
const config = new AppleConfigReader({
|
||||
info: {
|
||||
'en-US': {
|
||||
title: 'My App',
|
||||
// No screenshots
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const locale = new AppStoreVersionLocalization(requestContext, 'LOC_1', {
|
||||
locale: 'en-US',
|
||||
} as any);
|
||||
|
||||
await new ScreenshotsTask().uploadAsync({
|
||||
config,
|
||||
context: {
|
||||
screenshotSets: new Map(),
|
||||
versionLocales: [locale],
|
||||
} as any,
|
||||
});
|
||||
|
||||
// Should complete without uploading
|
||||
});
|
||||
|
||||
it('uploads new screenshots for configured locale', async () => {
|
||||
const config = new AppleConfigReader({
|
||||
info: {
|
||||
'en-US': {
|
||||
title: 'My App',
|
||||
screenshots: {
|
||||
APP_IPHONE_67: ['./screenshots/home.png'],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const locale = new AppStoreVersionLocalization(requestContext, 'LOC_1', {
|
||||
locale: 'en-US',
|
||||
} as any);
|
||||
|
||||
const newScreenshot = new AppScreenshot(requestContext, 'NEW_SS_1', {
|
||||
fileName: 'home.png',
|
||||
fileSize: 1024,
|
||||
assetDeliveryState: { state: 'COMPLETE', errors: [], warnings: [] },
|
||||
} as any);
|
||||
|
||||
// Mock createAppScreenshotSetAsync on the locale
|
||||
const scope = nock('https://api.appstoreconnect.apple.com')
|
||||
// Create screenshot set
|
||||
.post(`/v1/${AppScreenshotSet.type}`)
|
||||
.reply(201, {
|
||||
data: {
|
||||
id: 'NEW_SET_1',
|
||||
type: AppScreenshotSet.type,
|
||||
attributes: {
|
||||
screenshotDisplayType: ScreenshotDisplayType.APP_IPHONE_67,
|
||||
appScreenshots: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Mock AppScreenshot.uploadAsync to avoid real file access
|
||||
jest.spyOn(AppScreenshot, 'uploadAsync').mockResolvedValue(newScreenshot);
|
||||
|
||||
// Mock AppScreenshotSet.infoAsync for reorder step
|
||||
jest.spyOn(AppScreenshotSet, 'infoAsync').mockResolvedValue(
|
||||
new AppScreenshotSet(requestContext, 'NEW_SET_1', {
|
||||
screenshotDisplayType: ScreenshotDisplayType.APP_IPHONE_67,
|
||||
appScreenshots: [newScreenshot],
|
||||
} as any)
|
||||
);
|
||||
|
||||
// Mock reorderScreenshotsAsync
|
||||
const reorderMock = jest.fn().mockResolvedValue([]);
|
||||
AppScreenshotSet.prototype.reorderScreenshotsAsync = reorderMock;
|
||||
|
||||
const screenshotSets = new Map();
|
||||
screenshotSets.set('en-US', new Map());
|
||||
|
||||
await new ScreenshotsTask().uploadAsync({
|
||||
config,
|
||||
context: {
|
||||
screenshotSets,
|
||||
versionLocales: [locale],
|
||||
projectDir: '/test/project',
|
||||
} as any,
|
||||
});
|
||||
|
||||
expect(scope.isDone()).toBeTruthy();
|
||||
expect(AppScreenshot.uploadAsync).toHaveBeenCalledWith(
|
||||
requestContext,
|
||||
expect.objectContaining({
|
||||
id: 'NEW_SET_1',
|
||||
filePath: '/test/project/screenshots/home.png',
|
||||
waitForProcessing: true,
|
||||
})
|
||||
);
|
||||
// Reorder is skipped because the current order already matches
|
||||
expect(reorderMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { AgeRatingDeclaration } from '@expo/apple-utils';
|
||||
import assert from 'assert';
|
||||
import chalk from 'chalk';
|
||||
|
||||
import Log from '../../../log';
|
||||
@@ -7,7 +6,7 @@ import { logAsync } from '../../utils/log';
|
||||
import { AppleTask, TaskDownloadOptions, TaskPrepareOptions, TaskUploadOptions } from '../task';
|
||||
|
||||
export type AgeRatingData = {
|
||||
/** The app age rating declaration for the app version */
|
||||
/** The app age rating declaration for the app info */
|
||||
ageRating: AgeRatingDeclaration;
|
||||
};
|
||||
|
||||
@@ -15,7 +14,22 @@ export class AgeRatingTask extends AppleTask {
|
||||
public name = (): string => 'age rating declarations';
|
||||
|
||||
public async prepareAsync({ context }: TaskPrepareOptions): Promise<void> {
|
||||
context.ageRating = (await context.version!.getAgeRatingDeclarationAsync()) ?? undefined;
|
||||
if (!context.info) {
|
||||
return;
|
||||
}
|
||||
// The ageRatingDeclaration relationship is on appInfos (not appStoreVersions).
|
||||
try {
|
||||
context.ageRating = (await context.info.getAgeRatingDeclarationAsync()) ?? undefined;
|
||||
} catch (error: any) {
|
||||
// Gracefully handle cases where the relationship is not available
|
||||
if (error?.message?.includes('ageRatingDeclaration')) {
|
||||
Log.warn(
|
||||
chalk`{yellow Skipped age rating - not available for this app. This may require updating through App Store Connect directly.}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async downloadAsync({ config, context }: TaskDownloadOptions): Promise<void> {
|
||||
@@ -25,7 +39,10 @@ export class AgeRatingTask extends AppleTask {
|
||||
}
|
||||
|
||||
public async uploadAsync({ config, context }: TaskUploadOptions): Promise<void> {
|
||||
assert(context.ageRating, `Age rating not initialized, can't update age rating`);
|
||||
if (!context.ageRating) {
|
||||
Log.log(chalk`{dim - Skipped age rating update, not available}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const ageRating = config.getAgeRating();
|
||||
if (!ageRating) {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { AppStoreReviewDetail } from '@expo/apple-utils';
|
||||
import assert from 'assert';
|
||||
import chalk from 'chalk';
|
||||
|
||||
import Log from '../../../log';
|
||||
@@ -16,7 +15,10 @@ export class AppReviewDetailTask extends AppleTask {
|
||||
public name = (): string => 'app review detail';
|
||||
|
||||
public async prepareAsync({ context }: TaskPrepareOptions): Promise<void> {
|
||||
context.reviewDetail = (await context.version!.getAppStoreReviewDetailAsync()) ?? undefined;
|
||||
if (!context.version) {
|
||||
return;
|
||||
}
|
||||
context.reviewDetail = (await context.version.getAppStoreReviewDetailAsync()) ?? undefined;
|
||||
}
|
||||
|
||||
public async downloadAsync({ config, context }: TaskDownloadOptions): Promise<void> {
|
||||
@@ -32,7 +34,10 @@ export class AppReviewDetailTask extends AppleTask {
|
||||
return;
|
||||
}
|
||||
|
||||
assert(context.version, `App version not initialized, can't upload store review details`);
|
||||
if (!context.version) {
|
||||
Log.log(chalk`{dim - Skipped store review details, no version available}`);
|
||||
return;
|
||||
}
|
||||
const { versionString } = context.version.attributes;
|
||||
|
||||
if (!context.reviewDetail) {
|
||||
|
||||
@@ -2,6 +2,8 @@ import { AgeRatingTask } from './age-rating';
|
||||
import { AppInfoTask } from './app-info';
|
||||
import { AppReviewDetailTask } from './app-review-detail';
|
||||
import { AppVersionOptions, AppVersionTask } from './app-version';
|
||||
import { PreviewsTask } from './previews';
|
||||
import { ScreenshotsTask } from './screenshots';
|
||||
import { AppleTask } from '../task';
|
||||
|
||||
type AppleTaskOptions = {
|
||||
@@ -17,5 +19,7 @@ export function createAppleTasks({ version }: AppleTaskOptions = {}): AppleTask[
|
||||
new AppInfoTask(),
|
||||
new AgeRatingTask(),
|
||||
new AppReviewDetailTask(),
|
||||
new ScreenshotsTask(),
|
||||
new PreviewsTask(),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
import {
|
||||
AppPreview,
|
||||
AppPreviewSet,
|
||||
AppStoreVersionLocalization,
|
||||
PreviewType,
|
||||
} from '@expo/apple-utils';
|
||||
import chalk from 'chalk';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
import fetch from '../../../fetch';
|
||||
import Log from '../../../log';
|
||||
import { logAsync } from '../../utils/log';
|
||||
import { AppleTask, TaskDownloadOptions, TaskPrepareOptions, TaskUploadOptions } from '../task';
|
||||
import { ApplePreviewConfig, ApplePreviews } from '../types';
|
||||
|
||||
/** Locale -> PreviewType -> AppPreviewSet */
|
||||
export type PreviewSetsMap = Map<string, Map<PreviewType, AppPreviewSet>>;
|
||||
|
||||
export type PreviewsData = {
|
||||
/** Map of locales to their preview sets */
|
||||
previewSets: PreviewSetsMap;
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalize preview config to always return an object with path and optional previewFrameTimeCode.
|
||||
*/
|
||||
function normalizePreviewConfig(config: ApplePreviewConfig): {
|
||||
path: string;
|
||||
previewFrameTimeCode?: string;
|
||||
} {
|
||||
if (typeof config === 'string') {
|
||||
return { path: config };
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Task for managing App Store video previews.
|
||||
* Downloads existing previews and uploads new ones based on store configuration.
|
||||
*/
|
||||
export class PreviewsTask extends AppleTask {
|
||||
public name = (): string => 'video previews';
|
||||
|
||||
public async prepareAsync({ context }: TaskPrepareOptions): Promise<void> {
|
||||
// Initialize the preview sets map
|
||||
context.previewSets = new Map();
|
||||
|
||||
if (!context.versionLocales) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch preview sets for all locales in parallel
|
||||
await Promise.all(
|
||||
context.versionLocales.map(async locale => {
|
||||
const sets = await locale.getAppPreviewSetsAsync();
|
||||
const previewTypeMap = new Map<PreviewType, AppPreviewSet>();
|
||||
|
||||
for (const set of sets) {
|
||||
previewTypeMap.set(set.attributes.previewType, set);
|
||||
}
|
||||
|
||||
context.previewSets!.set(locale.attributes.locale, previewTypeMap);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public async downloadAsync({ config, context }: TaskDownloadOptions): Promise<void> {
|
||||
if (!context.previewSets || !context.versionLocales) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const locale of context.versionLocales) {
|
||||
const localeCode = locale.attributes.locale;
|
||||
const previewTypeMap = context.previewSets.get(localeCode);
|
||||
|
||||
if (!previewTypeMap || previewTypeMap.size === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const previews: ApplePreviews = {};
|
||||
|
||||
for (const [previewType, set] of previewTypeMap) {
|
||||
const previewModels = set.attributes.appPreviews;
|
||||
if (!previewModels || previewModels.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// For now, we only handle the first preview per set (App Store allows up to 3)
|
||||
// We can extend this later to support multiple previews
|
||||
const preview = previewModels[0];
|
||||
const relativePath = await downloadPreviewAsync(
|
||||
context.projectDir,
|
||||
localeCode,
|
||||
previewType,
|
||||
preview,
|
||||
0
|
||||
);
|
||||
|
||||
if (relativePath) {
|
||||
// Include preview frame time code if available
|
||||
if (preview.attributes.previewFrameTimeCode) {
|
||||
previews[previewType] = {
|
||||
path: relativePath,
|
||||
previewFrameTimeCode: preview.attributes.previewFrameTimeCode,
|
||||
};
|
||||
} else {
|
||||
previews[previewType] = relativePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(previews).length > 0) {
|
||||
config.setPreviews(localeCode, previews);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async uploadAsync({ config, context }: TaskUploadOptions): Promise<void> {
|
||||
if (!context.previewSets || !context.versionLocales) {
|
||||
Log.log(chalk`{dim - Skipped video previews, no version available}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const locales = config.getLocales();
|
||||
if (locales.length <= 0) {
|
||||
Log.log(chalk`{dim - Skipped video previews, no locales configured}`);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const localeCode of locales) {
|
||||
const previews = config.getPreviews(localeCode);
|
||||
if (!previews || Object.keys(previews).length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const localization = context.versionLocales.find(l => l.attributes.locale === localeCode);
|
||||
if (!localization) {
|
||||
Log.warn(chalk`{yellow Skipping video previews for ${localeCode} - locale not found}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const [previewType, previewConfig] of Object.entries(previews)) {
|
||||
if (!previewConfig) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await syncPreviewSetAsync(
|
||||
context.projectDir,
|
||||
localization,
|
||||
previewType as PreviewType,
|
||||
normalizePreviewConfig(previewConfig),
|
||||
context.previewSets.get(localeCode)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync a preview set - upload new preview, delete old one if changed.
|
||||
*/
|
||||
async function syncPreviewSetAsync(
|
||||
projectDir: string,
|
||||
localization: AppStoreVersionLocalization,
|
||||
previewType: PreviewType,
|
||||
previewConfig: { path: string; previewFrameTimeCode?: string },
|
||||
existingSets: Map<PreviewType, AppPreviewSet> | undefined
|
||||
): Promise<void> {
|
||||
const locale = localization.attributes.locale;
|
||||
const absolutePath = path.resolve(projectDir, previewConfig.path);
|
||||
const fileName = path.basename(absolutePath);
|
||||
|
||||
if (!fs.existsSync(absolutePath)) {
|
||||
Log.warn(chalk`{yellow Video preview not found: ${absolutePath}}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get or create the preview set
|
||||
let previewSet = existingSets?.get(previewType);
|
||||
|
||||
if (!previewSet) {
|
||||
previewSet = await logAsync(
|
||||
() =>
|
||||
localization.createAppPreviewSetAsync({
|
||||
previewType,
|
||||
}),
|
||||
{
|
||||
pending: `Creating preview set for ${chalk.bold(previewType)} (${locale})...`,
|
||||
success: `Created preview set for ${chalk.bold(previewType)} (${locale})`,
|
||||
failure: `Failed creating preview set for ${chalk.bold(previewType)} (${locale})`,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const existingPreviews = previewSet.attributes.appPreviews || [];
|
||||
|
||||
// Check if we need to update (different filename, size, or no existing preview)
|
||||
const existingPreview = existingPreviews.find(p => p.attributes.fileName === fileName);
|
||||
const localSize = fs.statSync(absolutePath).size;
|
||||
|
||||
if (
|
||||
existingPreview &&
|
||||
existingPreview.isComplete() &&
|
||||
existingPreview.attributes.fileSize === localSize
|
||||
) {
|
||||
// Preview with same filename exists, check if we need to update preview frame time code
|
||||
if (
|
||||
previewConfig.previewFrameTimeCode &&
|
||||
existingPreview.attributes.previewFrameTimeCode !== previewConfig.previewFrameTimeCode
|
||||
) {
|
||||
await logAsync(
|
||||
() =>
|
||||
existingPreview.updateAsync({
|
||||
previewFrameTimeCode: previewConfig.previewFrameTimeCode,
|
||||
}),
|
||||
{
|
||||
pending: `Updating preview frame time code for ${chalk.bold(fileName)} (${locale})...`,
|
||||
success: `Updated preview frame time code for ${chalk.bold(fileName)} (${locale})`,
|
||||
failure: `Failed updating preview frame time code for ${chalk.bold(fileName)} (${locale})`,
|
||||
}
|
||||
);
|
||||
}
|
||||
Log.log(chalk`{dim Preview ${fileName} already exists, skipping upload}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Delete existing previews that don't match
|
||||
for (const preview of existingPreviews) {
|
||||
if (preview.attributes.fileName !== fileName) {
|
||||
await logAsync(() => preview.deleteAsync(), {
|
||||
pending: `Deleting old preview ${chalk.bold(preview.attributes.fileName)} (${locale})...`,
|
||||
success: `Deleted old preview ${chalk.bold(preview.attributes.fileName)} (${locale})`,
|
||||
failure: `Failed deleting old preview ${chalk.bold(preview.attributes.fileName)} (${locale})`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Upload new preview
|
||||
await logAsync(
|
||||
() =>
|
||||
AppPreview.uploadAsync(localization.context, {
|
||||
id: previewSet!.id,
|
||||
filePath: absolutePath,
|
||||
waitForProcessing: true,
|
||||
previewFrameTimeCode: previewConfig.previewFrameTimeCode,
|
||||
}),
|
||||
{
|
||||
pending: `Uploading video preview ${chalk.bold(fileName)} (${locale})...`,
|
||||
success: `Uploaded video preview ${chalk.bold(fileName)} (${locale})`,
|
||||
failure: `Failed uploading video preview ${chalk.bold(fileName)} (${locale})`,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a video preview to the local filesystem.
|
||||
* Returns the relative path to the downloaded file.
|
||||
*/
|
||||
async function downloadPreviewAsync(
|
||||
projectDir: string,
|
||||
locale: string,
|
||||
previewType: PreviewType,
|
||||
preview: AppPreview,
|
||||
index: number
|
||||
): Promise<string | null> {
|
||||
const videoUrl = preview.getVideoUrl();
|
||||
if (!videoUrl) {
|
||||
Log.warn(chalk`{yellow Could not get download URL for preview ${preview.attributes.fileName}}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create directory structure: store/apple/preview/{locale}/{previewType}/
|
||||
const previewsDir = path.join(projectDir, 'store', 'apple', 'preview', locale, previewType);
|
||||
await fs.promises.mkdir(previewsDir, { recursive: true });
|
||||
|
||||
// Use original filename for matching during sync
|
||||
const fileName = preview.attributes.fileName || `${String(index + 1).padStart(2, '0')}.mp4`;
|
||||
const outputPath = path.join(previewsDir, fileName);
|
||||
const relativePath = path.relative(projectDir, outputPath);
|
||||
|
||||
try {
|
||||
const response = await fetch(videoUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const buffer = await response.buffer();
|
||||
await fs.promises.writeFile(outputPath, buffer);
|
||||
|
||||
Log.log(chalk`{dim Downloaded video preview: ${relativePath}}`);
|
||||
return relativePath;
|
||||
} catch (error: any) {
|
||||
Log.warn(chalk`{yellow Failed to download video preview ${fileName}: ${error.message}}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
import {
|
||||
AppScreenshot,
|
||||
AppScreenshotSet,
|
||||
AppStoreVersionLocalization,
|
||||
ScreenshotDisplayType,
|
||||
} from '@expo/apple-utils';
|
||||
import chalk from 'chalk';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
import fetch from '../../../fetch';
|
||||
import Log from '../../../log';
|
||||
import { logAsync } from '../../utils/log';
|
||||
import { AppleTask, TaskDownloadOptions, TaskPrepareOptions, TaskUploadOptions } from '../task';
|
||||
import { AppleScreenshots } from '../types';
|
||||
|
||||
/** Locale -> ScreenshotDisplayType -> AppScreenshotSet */
|
||||
export type ScreenshotSetsMap = Map<string, Map<ScreenshotDisplayType, AppScreenshotSet>>;
|
||||
|
||||
export type ScreenshotsData = {
|
||||
/** Map of locales to their screenshot sets */
|
||||
screenshotSets: ScreenshotSetsMap;
|
||||
};
|
||||
|
||||
/**
|
||||
* Task for managing App Store screenshots.
|
||||
* Downloads existing screenshots and uploads new ones based on store configuration.
|
||||
*/
|
||||
export class ScreenshotsTask extends AppleTask {
|
||||
public name = (): string => 'screenshots';
|
||||
|
||||
public async prepareAsync({ context }: TaskPrepareOptions): Promise<void> {
|
||||
// Initialize the screenshot sets map
|
||||
context.screenshotSets = new Map();
|
||||
|
||||
if (!context.versionLocales) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch screenshot sets for all locales in parallel
|
||||
await Promise.all(
|
||||
context.versionLocales.map(async locale => {
|
||||
const sets = await locale.getAppScreenshotSetsAsync();
|
||||
const displayTypeMap = new Map<ScreenshotDisplayType, AppScreenshotSet>();
|
||||
|
||||
for (const set of sets) {
|
||||
displayTypeMap.set(set.attributes.screenshotDisplayType, set);
|
||||
}
|
||||
|
||||
context.screenshotSets!.set(locale.attributes.locale, displayTypeMap);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public async downloadAsync({ config, context }: TaskDownloadOptions): Promise<void> {
|
||||
if (!context.screenshotSets || !context.versionLocales) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const locale of context.versionLocales) {
|
||||
const localeCode = locale.attributes.locale;
|
||||
const displayTypeMap = context.screenshotSets.get(localeCode);
|
||||
|
||||
if (!displayTypeMap || displayTypeMap.size === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const screenshots: AppleScreenshots = {};
|
||||
|
||||
for (const [displayType, set] of displayTypeMap) {
|
||||
const screenshotModels = set.attributes.appScreenshots;
|
||||
if (!screenshotModels || screenshotModels.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Download screenshots and save to local filesystem
|
||||
const paths: string[] = [];
|
||||
for (let i = 0; i < screenshotModels.length; i++) {
|
||||
const screenshot = screenshotModels[i];
|
||||
const relativePath = await downloadScreenshotAsync(
|
||||
context.projectDir,
|
||||
localeCode,
|
||||
displayType,
|
||||
screenshot,
|
||||
i
|
||||
);
|
||||
if (relativePath) {
|
||||
paths.push(relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
if (paths.length > 0) {
|
||||
screenshots[displayType] = paths;
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(screenshots).length > 0) {
|
||||
config.setScreenshots(localeCode, screenshots);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async uploadAsync({ config, context }: TaskUploadOptions): Promise<void> {
|
||||
if (!context.screenshotSets || !context.versionLocales) {
|
||||
Log.log(chalk`{dim - Skipped screenshots, no version available}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const locales = config.getLocales();
|
||||
if (locales.length <= 0) {
|
||||
Log.log(chalk`{dim - Skipped screenshots, no locales configured}`);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const localeCode of locales) {
|
||||
const screenshots = config.getScreenshots(localeCode);
|
||||
if (!screenshots || Object.keys(screenshots).length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const localization = context.versionLocales.find(l => l.attributes.locale === localeCode);
|
||||
if (!localization) {
|
||||
Log.warn(chalk`{yellow Skipping screenshots for ${localeCode} - locale not found}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const [displayType, paths] of Object.entries(screenshots)) {
|
||||
if (!paths || paths.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await syncScreenshotSetAsync(
|
||||
context.projectDir,
|
||||
localization,
|
||||
displayType as ScreenshotDisplayType,
|
||||
paths,
|
||||
context.screenshotSets.get(localeCode)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync a screenshot set - upload new screenshots, delete removed ones, reorder if needed.
|
||||
*/
|
||||
async function syncScreenshotSetAsync(
|
||||
projectDir: string,
|
||||
localization: AppStoreVersionLocalization,
|
||||
displayType: ScreenshotDisplayType,
|
||||
paths: string[],
|
||||
existingSets: Map<ScreenshotDisplayType, AppScreenshotSet> | undefined
|
||||
): Promise<void> {
|
||||
const locale = localization.attributes.locale;
|
||||
|
||||
// Get or create the screenshot set
|
||||
let screenshotSet = existingSets?.get(displayType);
|
||||
|
||||
if (!screenshotSet) {
|
||||
screenshotSet = await logAsync(
|
||||
() =>
|
||||
localization.createAppScreenshotSetAsync({
|
||||
screenshotDisplayType: displayType,
|
||||
}),
|
||||
{
|
||||
pending: `Creating screenshot set for ${chalk.bold(displayType)} (${locale})...`,
|
||||
success: `Created screenshot set for ${chalk.bold(displayType)} (${locale})`,
|
||||
failure: `Failed creating screenshot set for ${chalk.bold(displayType)} (${locale})`,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const existingScreenshots = screenshotSet.attributes.appScreenshots || [];
|
||||
|
||||
// Build a map of existing screenshots by filename for comparison
|
||||
const existingByFilename = new Map<string, AppScreenshot>();
|
||||
for (const screenshot of existingScreenshots) {
|
||||
existingByFilename.set(screenshot.attributes.fileName, screenshot);
|
||||
}
|
||||
|
||||
// Track which screenshots to keep, upload, and delete
|
||||
const screenshotIdsToKeep: string[] = [];
|
||||
const pathsToUpload: string[] = [];
|
||||
|
||||
for (const relativePath of paths) {
|
||||
const absolutePath = path.resolve(projectDir, relativePath);
|
||||
const fileName = path.basename(absolutePath);
|
||||
|
||||
// Check if screenshot already exists with same name and file size
|
||||
const existing = existingByFilename.get(fileName);
|
||||
const localSize = fs.existsSync(absolutePath) ? fs.statSync(absolutePath).size : null;
|
||||
if (
|
||||
existing &&
|
||||
existing.isComplete() &&
|
||||
(localSize === null || existing.attributes.fileSize === localSize)
|
||||
) {
|
||||
screenshotIdsToKeep.push(existing.id);
|
||||
existingByFilename.delete(fileName);
|
||||
} else {
|
||||
pathsToUpload.push(absolutePath);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete screenshots that are no longer in config
|
||||
for (const screenshot of existingByFilename.values()) {
|
||||
await logAsync(() => screenshot.deleteAsync(), {
|
||||
pending: `Deleting screenshot ${chalk.bold(screenshot.attributes.fileName)} (${locale})...`,
|
||||
success: `Deleted screenshot ${chalk.bold(screenshot.attributes.fileName)} (${locale})`,
|
||||
failure: `Failed deleting screenshot ${chalk.bold(screenshot.attributes.fileName)} (${locale})`,
|
||||
});
|
||||
}
|
||||
|
||||
// Upload new screenshots
|
||||
for (const absolutePath of pathsToUpload) {
|
||||
const fileName = path.basename(absolutePath);
|
||||
|
||||
if (!fs.existsSync(absolutePath)) {
|
||||
Log.warn(chalk`{yellow Screenshot not found: ${absolutePath}}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const newScreenshot = await logAsync(
|
||||
() =>
|
||||
AppScreenshot.uploadAsync(localization.context, {
|
||||
id: screenshotSet!.id,
|
||||
filePath: absolutePath,
|
||||
waitForProcessing: true,
|
||||
}),
|
||||
{
|
||||
pending: `Uploading screenshot ${chalk.bold(fileName)} (${locale})...`,
|
||||
success: `Uploaded screenshot ${chalk.bold(fileName)} (${locale})`,
|
||||
failure: `Failed uploading screenshot ${chalk.bold(fileName)} (${locale})`,
|
||||
}
|
||||
);
|
||||
|
||||
screenshotIdsToKeep.push(newScreenshot.id);
|
||||
}
|
||||
|
||||
// Reorder screenshots to match config order
|
||||
if (screenshotIdsToKeep.length > 0) {
|
||||
const refreshedSet = await AppScreenshotSet.infoAsync(localization.context, {
|
||||
id: screenshotSet.id,
|
||||
});
|
||||
const refreshedScreenshots = refreshedSet.attributes.appScreenshots || [];
|
||||
const screenshotsByFilename = new Map<string, AppScreenshot>();
|
||||
for (const s of refreshedScreenshots) {
|
||||
screenshotsByFilename.set(s.attributes.fileName, s);
|
||||
}
|
||||
|
||||
// Build the desired order based on config paths
|
||||
const orderedIds: string[] = [];
|
||||
for (const relativePath of paths) {
|
||||
const fileName = path.basename(relativePath);
|
||||
const screenshot = screenshotsByFilename.get(fileName);
|
||||
if (screenshot) {
|
||||
orderedIds.push(screenshot.id);
|
||||
}
|
||||
}
|
||||
|
||||
// Only call reorder if the order actually differs from current
|
||||
const currentIds = refreshedScreenshots.map(s => s.id);
|
||||
if (
|
||||
orderedIds.length > 0 &&
|
||||
(orderedIds.length !== currentIds.length || orderedIds.some((id, i) => id !== currentIds[i]))
|
||||
) {
|
||||
await screenshotSet.reorderScreenshotsAsync({ appScreenshots: orderedIds });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a screenshot to the local filesystem.
|
||||
* Returns the relative path to the downloaded file.
|
||||
*/
|
||||
async function downloadScreenshotAsync(
|
||||
projectDir: string,
|
||||
locale: string,
|
||||
displayType: ScreenshotDisplayType,
|
||||
screenshot: AppScreenshot,
|
||||
index: number
|
||||
): Promise<string | null> {
|
||||
const imageUrl = screenshot.getImageAssetUrl({ type: 'png' });
|
||||
if (!imageUrl) {
|
||||
Log.warn(
|
||||
chalk`{yellow Could not get download URL for screenshot ${screenshot.attributes.fileName}}`
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create directory structure: store/apple/screenshot/{locale}/{displayType}/
|
||||
const screenshotsDir = path.join(projectDir, 'store', 'apple', 'screenshot', locale, displayType);
|
||||
await fs.promises.mkdir(screenshotsDir, { recursive: true });
|
||||
|
||||
// Use original filename for matching during sync
|
||||
const fileName = screenshot.attributes.fileName || `${String(index + 1).padStart(2, '0')}.png`;
|
||||
const outputPath = path.join(screenshotsDir, fileName);
|
||||
const relativePath = path.relative(projectDir, outputPath);
|
||||
|
||||
try {
|
||||
const response = await fetch(imageUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const buffer = await response.buffer();
|
||||
await fs.promises.writeFile(outputPath, buffer);
|
||||
|
||||
Log.log(chalk`{dim Downloaded screenshot: ${relativePath}}`);
|
||||
return relativePath;
|
||||
} catch (error: any) {
|
||||
Log.warn(chalk`{yellow Failed to download screenshot ${fileName}: ${error.message}}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,46 @@
|
||||
import type { AgeRatingDeclarationProps } from '@expo/apple-utils';
|
||||
import type {
|
||||
AgeRatingDeclarationProps,
|
||||
PreviewType,
|
||||
ScreenshotDisplayType,
|
||||
} from '@expo/apple-utils';
|
||||
|
||||
export type AppleLocale = string;
|
||||
|
||||
/** Screenshot display type enum values from App Store Connect API */
|
||||
export type AppleScreenshotDisplayType = `${ScreenshotDisplayType}`;
|
||||
|
||||
/** Preview display type enum values from App Store Connect API */
|
||||
export type ApplePreviewType = `${PreviewType}`;
|
||||
|
||||
/**
|
||||
* Screenshots organized by display type.
|
||||
* Key is the display type (e.g., 'APP_IPHONE_67'), value is array of file paths.
|
||||
* @example { "APP_IPHONE_67": ["./screenshots/home.png", "./screenshots/profile.png"] }
|
||||
*/
|
||||
export type AppleScreenshots = Partial<Record<AppleScreenshotDisplayType, string[]>>;
|
||||
|
||||
/**
|
||||
* Video preview configuration - either a simple path string or an object with options.
|
||||
* @example "./previews/demo.mp4"
|
||||
* @example { path: "./previews/demo.mp4", previewFrameTimeCode: "00:05:00" }
|
||||
*/
|
||||
export type ApplePreviewConfig =
|
||||
| string
|
||||
| {
|
||||
/** Video file path (relative to project root) */
|
||||
path: string;
|
||||
/** Optional preview frame time code (e.g., '00:05:00' for 5 seconds) */
|
||||
previewFrameTimeCode?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Video previews organized by display type.
|
||||
* Key is the display type (e.g., 'IPHONE_67'), value is the preview config.
|
||||
* @example { "IPHONE_67": "./previews/demo.mp4" }
|
||||
* @example { "IPHONE_67": { path: "./previews/demo.mp4", previewFrameTimeCode: "00:05:00" } }
|
||||
*/
|
||||
export type ApplePreviews = Partial<Record<ApplePreviewType, ApplePreviewConfig>>;
|
||||
|
||||
export interface AppleMetadata {
|
||||
version?: string;
|
||||
copyright?: string;
|
||||
@@ -9,6 +48,7 @@ export interface AppleMetadata {
|
||||
categories?: AppleCategory;
|
||||
release?: AppleRelease;
|
||||
advisory?: AppleAdvisory;
|
||||
/** @deprecated Use screenshots/previews in AppleInfo instead */
|
||||
preview?: Record<string, string[]>;
|
||||
review?: AppleReview;
|
||||
}
|
||||
@@ -40,6 +80,10 @@ export interface AppleInfo {
|
||||
privacyPolicyText?: string;
|
||||
privacyChoicesUrl?: string;
|
||||
supportUrl?: string;
|
||||
/** Screenshots for this locale, organized by display type */
|
||||
screenshots?: AppleScreenshots;
|
||||
/** Video previews for this locale, organized by display type */
|
||||
previews?: ApplePreviews;
|
||||
}
|
||||
|
||||
export interface AppleReview {
|
||||
|
||||
@@ -2,10 +2,22 @@ import { App, Session } from '@expo/apple-utils';
|
||||
import { ExpoConfig } from '@expo/config';
|
||||
import { SubmitProfile } from '@expo/eas-json';
|
||||
import assert from 'assert';
|
||||
import fs from 'fs';
|
||||
|
||||
import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { CredentialsContext } from '../credentials/context';
|
||||
import { getRequestContext } from '../credentials/ios/appstore/authenticate';
|
||||
import { AppLookupParams } from '../credentials/ios/api/graphql/types/AppLookupParams';
|
||||
import {
|
||||
Options as AuthOptions,
|
||||
getRequestContext,
|
||||
} from '../credentials/ios/appstore/authenticate';
|
||||
import { AppleTeamType, AuthenticationMode } from '../credentials/ios/appstore/authenticateTypes';
|
||||
import { hasAscEnvVars } from '../credentials/ios/appstore/resolveCredentials';
|
||||
import { MinimalAscApiKey } from '../credentials/ios/credentials';
|
||||
import { AppStoreConnectApiKeyQuery } from '../graphql/queries/AppStoreConnectApiKeyQuery';
|
||||
import Log from '../log';
|
||||
import { getBundleIdentifierAsync } from '../project/ios/bundleIdentifier';
|
||||
import { getOwnerAccountForProjectIdAsync } from '../project/projectUtils';
|
||||
import { Client } from '../vcs/vcs';
|
||||
|
||||
export type MetadataAppStoreAuthentication = {
|
||||
@@ -32,20 +44,107 @@ async function resolveAppStoreBundleIdentifierAsync(
|
||||
return await getBundleIdentifierAsync(projectDir, exp, vcsClient);
|
||||
}
|
||||
|
||||
type ResolvedAscApiKey = {
|
||||
ascApiKey: MinimalAscApiKey;
|
||||
teamId?: string;
|
||||
teamName?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Try to resolve an ASC API key from the submit profile or EAS credentials service.
|
||||
* Returns null if no key is available from these sources.
|
||||
*/
|
||||
async function tryResolveAscApiKeyAsync({
|
||||
profile,
|
||||
graphqlClient,
|
||||
projectId,
|
||||
exp,
|
||||
bundleId,
|
||||
}: {
|
||||
profile: SubmitProfile;
|
||||
graphqlClient: ExpoGraphqlClient;
|
||||
projectId: string;
|
||||
exp: ExpoConfig;
|
||||
bundleId: string;
|
||||
}): Promise<ResolvedAscApiKey | null> {
|
||||
// 1. Check submit profile for ASC API key fields
|
||||
if ('ascApiKeyPath' in profile && 'ascApiKeyIssuerId' in profile && 'ascApiKeyId' in profile) {
|
||||
const { ascApiKeyPath, ascApiKeyIssuerId, ascApiKeyId } = profile;
|
||||
if (ascApiKeyPath && ascApiKeyIssuerId && ascApiKeyId) {
|
||||
const keyP8 = await fs.promises.readFile(ascApiKeyPath, 'utf-8');
|
||||
// Also try to get teamId from the profile if available
|
||||
const teamId = 'appleTeamId' in profile ? (profile as any).appleTeamId : undefined;
|
||||
return {
|
||||
ascApiKey: { keyP8, keyId: ascApiKeyId, issuerId: ascApiKeyIssuerId },
|
||||
teamId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Look up stored credentials via EAS credentials service
|
||||
try {
|
||||
const account = await getOwnerAccountForProjectIdAsync(graphqlClient, projectId);
|
||||
const appLookupParams: AppLookupParams = {
|
||||
account,
|
||||
projectName: exp.slug,
|
||||
bundleIdentifier: bundleId,
|
||||
};
|
||||
|
||||
// Import dynamically to avoid circular dependency issues
|
||||
const { getAscApiKeyForAppSubmissionsAsync } =
|
||||
await import('../credentials/ios/api/GraphqlClient');
|
||||
const ascKeyFragment = await getAscApiKeyForAppSubmissionsAsync(graphqlClient, appLookupParams);
|
||||
|
||||
if (ascKeyFragment) {
|
||||
Log.log('Using App Store Connect API Key from EAS credentials service.');
|
||||
const fullKey = await AppStoreConnectApiKeyQuery.getByIdAsync(
|
||||
graphqlClient,
|
||||
ascKeyFragment.id
|
||||
);
|
||||
return {
|
||||
ascApiKey: {
|
||||
keyP8: fullKey.keyP8,
|
||||
keyId: fullKey.keyIdentifier,
|
||||
issuerId: fullKey.issuerIdentifier,
|
||||
},
|
||||
teamId: ascKeyFragment.appleTeam?.appleTeamIdentifier,
|
||||
teamName: ascKeyFragment.appleTeam?.appleTeamName ?? undefined,
|
||||
};
|
||||
}
|
||||
} catch (error: any) {
|
||||
// If we can't look up credentials, that's fine — we'll fall back
|
||||
Log.warn(`Could not look up stored ASC API key: ${error.message}`);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* To start syncing ASC entities, we need access to the apple utils App instance.
|
||||
* This resolves both the authentication and that App instance.
|
||||
*
|
||||
* Resolution order for authentication:
|
||||
* 1. ASC API key from environment variables (EXPO_ASC_API_KEY_PATH, etc.)
|
||||
* 2. ASC API key from submit profile (ascApiKeyPath, etc. in eas.json)
|
||||
* 3. ASC API key from EAS credentials service
|
||||
* 4. Interactive cookie auth (only when not in non-interactive mode)
|
||||
*/
|
||||
export async function getAppStoreAuthAsync({
|
||||
projectDir,
|
||||
profile,
|
||||
exp,
|
||||
credentialsCtx,
|
||||
nonInteractive,
|
||||
graphqlClient,
|
||||
projectId,
|
||||
}: {
|
||||
projectDir: string;
|
||||
profile: SubmitProfile;
|
||||
exp: ExpoConfig;
|
||||
credentialsCtx: CredentialsContext;
|
||||
nonInteractive: boolean;
|
||||
graphqlClient: ExpoGraphqlClient;
|
||||
projectId: string;
|
||||
}): Promise<MetadataAppStoreAuthentication> {
|
||||
const bundleId = await resolveAppStoreBundleIdentifierAsync(
|
||||
projectDir,
|
||||
@@ -54,10 +153,49 @@ export async function getAppStoreAuthAsync({
|
||||
credentialsCtx.vcsClient
|
||||
);
|
||||
|
||||
// Try to resolve an ASC API key from profile or credentials service
|
||||
const resolvedKey = await tryResolveAscApiKeyAsync({
|
||||
profile,
|
||||
graphqlClient,
|
||||
projectId,
|
||||
exp,
|
||||
bundleId,
|
||||
});
|
||||
|
||||
if (resolvedKey || hasAscEnvVars()) {
|
||||
const authOptions: AuthOptions = {
|
||||
mode: AuthenticationMode.API_KEY,
|
||||
...(resolvedKey
|
||||
? {
|
||||
ascApiKey: resolvedKey.ascApiKey,
|
||||
teamId: resolvedKey.teamId,
|
||||
teamName: resolvedKey.teamName,
|
||||
// Default to COMPANY_OR_ORGANIZATION to avoid prompting for team type
|
||||
teamType: AppleTeamType.COMPANY_OR_ORGANIZATION,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
const authCtx = await credentialsCtx.appStore.ensureAuthenticatedAsync(authOptions);
|
||||
assert(authCtx.authState, 'Failed to authenticate with App Store Connect');
|
||||
|
||||
const app = await App.findAsync(getRequestContext(authCtx), { bundleId });
|
||||
assert(app, `Failed to load app "${bundleId}" from App Store Connect`);
|
||||
return { app, auth: authCtx.authState };
|
||||
}
|
||||
|
||||
if (nonInteractive) {
|
||||
throw new Error(
|
||||
'No App Store Connect API Key found. In non-interactive mode, provide one via:\n' +
|
||||
' - Environment variables: EXPO_ASC_API_KEY_PATH, EXPO_ASC_KEY_ID, EXPO_ASC_ISSUER_ID\n' +
|
||||
' - eas.json submit profile: ascApiKeyPath, ascApiKeyId, ascApiKeyIssuerId\n' +
|
||||
' - EAS credentials service: run `eas credentials` to set up an API key'
|
||||
);
|
||||
}
|
||||
|
||||
// Fall back to interactive cookie auth
|
||||
const authCtx = await credentialsCtx.appStore.ensureAuthenticatedAsync();
|
||||
assert(authCtx.authState, 'Failed to authenticate with App Store Connect');
|
||||
|
||||
// TODO: improve error handling by mentioning possible configuration errors
|
||||
const app = await App.findAsync(getRequestContext(authCtx), { bundleId });
|
||||
assert(app, `Failed to load app "${bundleId}" from App Store Connect`);
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import { createAppleWriter, getStaticConfigFilePath } from './config/resolve';
|
||||
import { MetadataDownloadError, MetadataValidationError } from './errors';
|
||||
import { subscribeTelemetryAsync } from './utils/telemetry';
|
||||
import { Analytics, MetadataEvent } from '../analytics/AnalyticsManager';
|
||||
import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { CredentialsContext } from '../credentials/context';
|
||||
import Log from '../log';
|
||||
import { confirmAsync } from '../prompts';
|
||||
@@ -24,23 +25,33 @@ export async function downloadMetadataAsync({
|
||||
exp,
|
||||
analytics,
|
||||
credentialsCtx,
|
||||
nonInteractive,
|
||||
graphqlClient,
|
||||
projectId,
|
||||
}: {
|
||||
projectDir: string;
|
||||
profile: SubmitProfile;
|
||||
exp: ExpoConfig;
|
||||
analytics: Analytics;
|
||||
credentialsCtx: CredentialsContext;
|
||||
nonInteractive: boolean;
|
||||
graphqlClient: ExpoGraphqlClient;
|
||||
projectId: string;
|
||||
}): Promise<string> {
|
||||
const filePath = getStaticConfigFilePath({ projectDir, profile });
|
||||
|
||||
const fileExists = await fs.pathExists(filePath);
|
||||
if (fileExists) {
|
||||
const filePathRelative = path.relative(projectDir, filePath);
|
||||
const overwrite = await confirmAsync({
|
||||
message: `Do you want to overwrite the existing "${filePathRelative}"?`,
|
||||
});
|
||||
if (!overwrite) {
|
||||
throw new MetadataValidationError(`Store config already exists at "${filePath}"`);
|
||||
if (nonInteractive) {
|
||||
Log.log(`Overwriting existing store config at "${path.relative(projectDir, filePath)}".`);
|
||||
} else {
|
||||
const filePathRelative = path.relative(projectDir, filePath);
|
||||
const overwrite = await confirmAsync({
|
||||
message: `Do you want to overwrite the existing "${filePathRelative}"?`,
|
||||
});
|
||||
if (!overwrite) {
|
||||
throw new MetadataValidationError(`Store config already exists at "${filePath}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +60,9 @@ export async function downloadMetadataAsync({
|
||||
credentialsCtx,
|
||||
projectDir,
|
||||
profile,
|
||||
nonInteractive,
|
||||
graphqlClient,
|
||||
projectId,
|
||||
});
|
||||
|
||||
const { unsubscribeTelemetry, executionId } = await subscribeTelemetryAsync(
|
||||
@@ -63,7 +77,7 @@ export async function downloadMetadataAsync({
|
||||
const errors: Error[] = [];
|
||||
const config = createAppleWriter();
|
||||
const tasks = createAppleTasks();
|
||||
const taskCtx = { app };
|
||||
const taskCtx = { app, projectDir };
|
||||
|
||||
for (const task of tasks) {
|
||||
try {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { MetadataConfig } from './config/schema';
|
||||
import { MetadataUploadError, MetadataValidationError, logMetadataValidationError } from './errors';
|
||||
import { subscribeTelemetryAsync } from './utils/telemetry';
|
||||
import { Analytics, MetadataEvent } from '../analytics/AnalyticsManager';
|
||||
import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { CredentialsContext } from '../credentials/context';
|
||||
import Log from '../log';
|
||||
import { confirmAsync } from '../prompts';
|
||||
@@ -23,19 +24,32 @@ export async function uploadMetadataAsync({
|
||||
exp,
|
||||
analytics,
|
||||
credentialsCtx,
|
||||
nonInteractive,
|
||||
graphqlClient,
|
||||
projectId,
|
||||
}: {
|
||||
projectDir: string;
|
||||
profile: SubmitProfile;
|
||||
exp: ExpoConfig;
|
||||
analytics: Analytics;
|
||||
credentialsCtx: CredentialsContext;
|
||||
nonInteractive: boolean;
|
||||
graphqlClient: ExpoGraphqlClient;
|
||||
projectId: string;
|
||||
}): Promise<{ appleLink: string }> {
|
||||
const storeConfig = await loadConfigWithValidationPromptAsync(projectDir, profile);
|
||||
const storeConfig = await loadConfigWithValidationPromptAsync(
|
||||
projectDir,
|
||||
profile,
|
||||
nonInteractive
|
||||
);
|
||||
const { app, auth } = await getAppStoreAuthAsync({
|
||||
exp,
|
||||
credentialsCtx,
|
||||
projectDir,
|
||||
profile,
|
||||
nonInteractive,
|
||||
graphqlClient,
|
||||
projectId,
|
||||
});
|
||||
|
||||
const { unsubscribeTelemetry, executionId } = await subscribeTelemetryAsync(
|
||||
@@ -55,7 +69,7 @@ export async function uploadMetadataAsync({
|
||||
version: config.getVersion()?.versionString,
|
||||
});
|
||||
|
||||
const taskCtx = { app };
|
||||
const taskCtx = { app, projectDir };
|
||||
|
||||
for (const task of tasks) {
|
||||
try {
|
||||
@@ -84,12 +98,18 @@ export async function uploadMetadataAsync({
|
||||
|
||||
async function loadConfigWithValidationPromptAsync(
|
||||
projectDir: string,
|
||||
profile: SubmitProfile
|
||||
profile: SubmitProfile,
|
||||
nonInteractive: boolean
|
||||
): Promise<MetadataConfig> {
|
||||
try {
|
||||
return await loadConfigAsync({ projectDir, profile });
|
||||
} catch (error) {
|
||||
if (error instanceof MetadataValidationError) {
|
||||
if (nonInteractive) {
|
||||
logMetadataValidationError(error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
logMetadataValidationError(error);
|
||||
Log.newLine();
|
||||
Log.warn(
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import spawnAsync from '@expo/spawn-async';
|
||||
import { Platform, Workflow } from '@expo/eas-build-job';
|
||||
import fs from 'fs/promises';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import GitClient from '../../vcs/clients/git';
|
||||
import { resolveWorkflowAsync } from '../workflow';
|
||||
|
||||
describe('resolveWorkflowAsync with GitClient', () => {
|
||||
let repoRoot: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
repoRoot = await fs.realpath(
|
||||
await fs.mkdtemp(path.join(os.tmpdir(), 'eas-cli-workflow-test-'))
|
||||
);
|
||||
await spawnAsync('git', ['init'], { cwd: repoRoot });
|
||||
await spawnAsync('git', ['config', 'user.email', '[email protected]'], { cwd: repoRoot });
|
||||
await spawnAsync('git', ['config', 'user.name', 'Test User'], { cwd: repoRoot });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await fs.rm(repoRoot, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('treats tracked gitignored native projects as managed when requireCommit is false', async () => {
|
||||
const vcsClient = new GitClient({
|
||||
requireCommit: false,
|
||||
maybeCwdOverride: repoRoot,
|
||||
});
|
||||
|
||||
await fs.mkdir(path.join(repoRoot, 'ios', 'app.xcodeproj'), { recursive: true });
|
||||
await fs.writeFile(path.join(repoRoot, 'ios', 'app.xcodeproj', 'project.pbxproj'), 'fake');
|
||||
await fs.writeFile(path.join(repoRoot, '.gitignore'), 'ios/\n');
|
||||
|
||||
await spawnAsync('git', ['add', '.gitignore'], { cwd: repoRoot });
|
||||
await spawnAsync('git', ['add', '-f', 'ios/app.xcodeproj/project.pbxproj'], { cwd: repoRoot });
|
||||
await spawnAsync('git', ['commit', '-m', 'test setup'], { cwd: repoRoot });
|
||||
|
||||
await expect(resolveWorkflowAsync(repoRoot, Platform.IOS, vcsClient)).resolves.toBe(
|
||||
Workflow.MANAGED
|
||||
);
|
||||
});
|
||||
|
||||
it('treats tracked gitignored native projects as generic when requireCommit is true', async () => {
|
||||
const vcsClient = new GitClient({
|
||||
requireCommit: true,
|
||||
maybeCwdOverride: repoRoot,
|
||||
});
|
||||
|
||||
await fs.mkdir(path.join(repoRoot, 'ios', 'app.xcodeproj'), { recursive: true });
|
||||
await fs.writeFile(path.join(repoRoot, 'ios', 'app.xcodeproj', 'project.pbxproj'), 'fake');
|
||||
await fs.writeFile(path.join(repoRoot, '.gitignore'), 'ios/\n');
|
||||
|
||||
await spawnAsync('git', ['add', '.gitignore'], { cwd: repoRoot });
|
||||
await spawnAsync('git', ['add', '-f', 'ios/app.xcodeproj/project.pbxproj'], { cwd: repoRoot });
|
||||
await spawnAsync('git', ['commit', '-m', 'test setup'], { cwd: repoRoot });
|
||||
|
||||
await expect(resolveWorkflowAsync(repoRoot, Platform.IOS, vcsClient)).resolves.toBe(
|
||||
Workflow.GENERIC
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,23 @@ import { ensureNonExemptEncryptionIsDefinedForManagedProjectAsync } from '../exe
|
||||
jest.mock('fs');
|
||||
jest.mock('../../../prompts');
|
||||
|
||||
// @expo/require-utils uses require() to load JS configs, which bypasses the
|
||||
// mocked fs. Override loadModuleSync to read from the mocked fs and evaluate.
|
||||
jest.mock('@expo/require-utils', () => {
|
||||
const actual = jest.requireActual('@expo/require-utils');
|
||||
return {
|
||||
...actual,
|
||||
loadModuleSync: (filename: string) => {
|
||||
const fs = require('fs');
|
||||
const content = fs.readFileSync(filename, 'utf-8');
|
||||
const mod = { exports: {} as any };
|
||||
// eslint-disable-next-line no-new-func
|
||||
new Function('module', 'exports', content)(mod, mod.exports);
|
||||
return mod.exports;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.resetAllMocks();
|
||||
vol.reset();
|
||||
|
||||
@@ -10,21 +10,8 @@ import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGr
|
||||
import { AccountFragment } from '../graphql/generated';
|
||||
import { AppQuery } from '../graphql/queries/AppQuery';
|
||||
import Log, { learnMore } from '../log';
|
||||
import { Actor } from '../user/User';
|
||||
import { expoCommandAsync } from '../utils/expoCli';
|
||||
|
||||
export function getUsernameForBuildMetadataAndBuildJob(user: Actor): string | undefined {
|
||||
switch (user.__typename) {
|
||||
case 'User':
|
||||
return user.username;
|
||||
case 'SSOUser':
|
||||
return user.username;
|
||||
case 'Robot':
|
||||
// robot users don't have usernames
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a useful name describing the project config.
|
||||
* - dynamic: app.config.js
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import * as Sentry from '@sentry/node';
|
||||
|
||||
import { easCliVersion } from './utils/easCli';
|
||||
|
||||
Sentry.init({
|
||||
dsn: process.env.EAS_CLI_SENTRY_DSN,
|
||||
enabled: !!process.env.EAS_CLI_SENTRY_DSN,
|
||||
environment: getSentryEnvironment(),
|
||||
release: easCliVersion ? `eas-cli@${easCliVersion}` : undefined,
|
||||
});
|
||||
Sentry.setTag('source', 'eas-cli');
|
||||
|
||||
function getSentryEnvironment(): string {
|
||||
if (process.env.EXPO_LOCAL) {
|
||||
return 'local';
|
||||
} else if (process.env.EXPO_STAGING) {
|
||||
return 'staging';
|
||||
}
|
||||
return 'production';
|
||||
}
|
||||
|
||||
export default Sentry;
|
||||
@@ -7,6 +7,7 @@ import semver from 'semver';
|
||||
import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import {
|
||||
AppPlatform,
|
||||
PartnerActor,
|
||||
Robot,
|
||||
SsoUser,
|
||||
Update,
|
||||
@@ -29,6 +30,7 @@ export type FormatUpdateParameter = Pick<Update, 'id' | 'createdAt' | 'message'>
|
||||
| Pick<Robot, '__typename' | 'firstName'>
|
||||
| Pick<User, '__typename' | 'username'>
|
||||
| Pick<SsoUser, '__typename' | 'username'>
|
||||
| Pick<PartnerActor, '__typename' | 'username'>
|
||||
| null;
|
||||
};
|
||||
|
||||
@@ -194,6 +196,7 @@ export function formatUpdateTitle(update: UpdateFragment): string {
|
||||
let actorName: string;
|
||||
switch (actor?.__typename) {
|
||||
case 'User':
|
||||
case 'PartnerActor':
|
||||
case 'SSOUser': {
|
||||
actorName = actor.username;
|
||||
break;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CurrentUserQuery, Robot, SsoUser, User } from '../graphql/generated';
|
||||
import { CurrentUserQuery, PartnerActor, Robot, SsoUser, User } from '../graphql/generated';
|
||||
|
||||
export type Actor = NonNullable<CurrentUserQuery['meActor']>;
|
||||
|
||||
@@ -12,6 +12,7 @@ export function getActorDisplayName(
|
||||
| Pick<Robot, '__typename' | 'firstName'>
|
||||
| Pick<User, '__typename' | 'username'>
|
||||
| Pick<SsoUser, '__typename' | 'username'>
|
||||
| Pick<PartnerActor, '__typename' | 'username'>
|
||||
| null
|
||||
): string {
|
||||
switch (actor?.__typename) {
|
||||
@@ -21,6 +22,8 @@ export function getActorDisplayName(
|
||||
return actor.firstName ? `${actor.firstName} (robot)` : 'robot';
|
||||
case 'SSOUser':
|
||||
return actor.username;
|
||||
case 'PartnerActor':
|
||||
return actor.username;
|
||||
case undefined:
|
||||
return 'unknown';
|
||||
}
|
||||
@@ -30,6 +33,7 @@ export function getActorUsername(actor?: Actor): string | null {
|
||||
switch (actor?.__typename) {
|
||||
case 'User':
|
||||
case 'SSOUser':
|
||||
case 'PartnerActor':
|
||||
return actor.username;
|
||||
case 'Robot':
|
||||
case undefined:
|
||||
|
||||
@@ -1,24 +1,86 @@
|
||||
import assert from 'assert';
|
||||
import openBrowserAsync from 'better-opn';
|
||||
import crypto from 'crypto';
|
||||
import http from 'http';
|
||||
import { Socket } from 'node:net';
|
||||
import querystring from 'querystring';
|
||||
|
||||
import { getExpoWebsiteBaseUrl } from '../api';
|
||||
import { getExpoApiBaseUrl, getExpoWebsiteBaseUrl } from '../api';
|
||||
import fetch from '../fetch';
|
||||
import Log from '../log';
|
||||
|
||||
const CLIENT_ID = 'eas-cli';
|
||||
|
||||
function generateCodeVerifier(): string {
|
||||
return crypto.randomBytes(32).toString('base64url');
|
||||
}
|
||||
|
||||
function generateCodeChallenge(codeVerifier: string): string {
|
||||
return crypto.createHash('sha256').update(codeVerifier).digest('base64url');
|
||||
}
|
||||
|
||||
function generateState(): string {
|
||||
return crypto.randomBytes(32).toString('base64url');
|
||||
}
|
||||
|
||||
async function exchangeCodeForSessionSecretAsync({
|
||||
code,
|
||||
codeVerifier,
|
||||
redirectUri,
|
||||
}: {
|
||||
code: string;
|
||||
codeVerifier: string;
|
||||
redirectUri: string;
|
||||
}): Promise<string> {
|
||||
const tokenUrl = `${getExpoApiBaseUrl()}/v2/auth/token`;
|
||||
const response = await fetch(tokenUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
redirect_uri: redirectUri,
|
||||
code_verifier: codeVerifier,
|
||||
client_id: CLIENT_ID,
|
||||
}),
|
||||
});
|
||||
|
||||
const result: any = await response.json();
|
||||
const sessionSecret = result?.data?.session_secret;
|
||||
if (!sessionSecret) {
|
||||
throw new Error('Failed to obtain session secret from token exchange.');
|
||||
}
|
||||
return sessionSecret;
|
||||
}
|
||||
|
||||
export async function getSessionUsingBrowserAuthFlowAsync({ sso = false }): Promise<string> {
|
||||
const scheme = 'http';
|
||||
const hostname = 'localhost';
|
||||
const path = '/auth/callback';
|
||||
const callbackPath = '/auth/callback';
|
||||
|
||||
const expoWebsiteUrl = getExpoWebsiteBaseUrl();
|
||||
|
||||
const codeVerifier = generateCodeVerifier();
|
||||
const codeChallenge = generateCodeChallenge(codeVerifier);
|
||||
const state = generateState();
|
||||
|
||||
const buildRedirectUri = (port: number): string =>
|
||||
`${scheme}://${hostname}:${port}${callbackPath}`;
|
||||
|
||||
const buildExpoLoginUrl = (port: number, sso: boolean): string => {
|
||||
const params = querystring.stringify({
|
||||
confirm_account: true,
|
||||
app_redirect_uri: `${scheme}://${hostname}:${port}${path}`,
|
||||
});
|
||||
// Note: we avoid URLSearchParams here because better-opn calls encodeURI()
|
||||
// on the URL before passing it to AppleScript, which would double-encode
|
||||
// the percent-encoded values from URLSearchParams.toString().
|
||||
const params = [
|
||||
`client_id=${CLIENT_ID}`,
|
||||
`redirect_uri=${buildRedirectUri(port)}`,
|
||||
`response_type=code`,
|
||||
`code_challenge=${codeChallenge}`,
|
||||
`code_challenge_method=S256`,
|
||||
`state=${state}`,
|
||||
`confirm_account=true`,
|
||||
].join('&');
|
||||
return `${expoWebsiteUrl}${sso ? '/sso-login' : '/login'}?${params}`;
|
||||
};
|
||||
|
||||
@@ -39,22 +101,39 @@ export async function getSessionUsingBrowserAuthFlowAsync({ sso = false }): Prom
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const handleRequestAsync = async (): Promise<void> => {
|
||||
if (!(request.method === 'GET' && request.url?.includes('/auth/callback'))) {
|
||||
throw new Error('Unexpected login response.');
|
||||
}
|
||||
const url = new URL(request.url, `http:${request.headers.host}`);
|
||||
const sessionSecret = url.searchParams.get('session_secret');
|
||||
const code = url.searchParams.get('code');
|
||||
const returnedState = url.searchParams.get('state');
|
||||
|
||||
if (!sessionSecret) {
|
||||
throw new Error('Request missing session_secret search parameter.');
|
||||
if (!code) {
|
||||
throw new Error('Request missing code search parameter.');
|
||||
}
|
||||
if (returnedState !== state) {
|
||||
throw new Error('State mismatch. Possible CSRF attack.');
|
||||
}
|
||||
|
||||
const address = server.address();
|
||||
assert(address !== null && typeof address === 'object');
|
||||
const redirectUri = buildRedirectUri(address.port);
|
||||
|
||||
const sessionSecret = await exchangeCodeForSessionSecretAsync({
|
||||
code,
|
||||
codeVerifier,
|
||||
redirectUri,
|
||||
});
|
||||
|
||||
resolve(sessionSecret);
|
||||
redirectAndCleanup('success');
|
||||
} catch (error) {
|
||||
};
|
||||
|
||||
handleRequestAsync().catch(error => {
|
||||
redirectAndCleanup('error');
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -91,14 +91,14 @@ describe('git', () => {
|
||||
await fs.rm(`${repoRoot}/.gitignore`);
|
||||
});
|
||||
|
||||
it.each(testFiles.filter(file => file.gitignore && !file.commit))(
|
||||
it.each(testFiles.filter(file => file.gitignore))(
|
||||
'$filename should be ignored',
|
||||
async file => {
|
||||
expect(await vcs.isFileIgnoredAsync(file.filename)).toBe(true);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(testFiles.filter(file => !file.gitignore || file.commit))(
|
||||
it.each(testFiles.filter(file => !file.gitignore))(
|
||||
'$filename should not be ignored',
|
||||
async file => {
|
||||
expect(await vcs.isFileIgnoredAsync(file.filename)).toBe(false);
|
||||
|
||||
@@ -376,12 +376,18 @@ export default class GitClient extends Client {
|
||||
return wouldNotBeCopiedToClone && (!isTracked || wouldBeDeletedFromClone);
|
||||
}
|
||||
|
||||
if (isTracked) {
|
||||
return false; // Tracked files aren't ignored even if they match ignore patterns
|
||||
if (isTracked && this.requireCommit) {
|
||||
// With requireCommit=true we rely on a Git checkout, so tracked files are included
|
||||
// even if they match ignore patterns.
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await spawnAsync('git', ['check-ignore', '-q', filePath], { cwd: rootPath });
|
||||
await spawnAsync(
|
||||
'git',
|
||||
['check-ignore', '-q', ...(this.requireCommit ? [] : ['--no-index']), filePath],
|
||||
{ cwd: rootPath }
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
|
||||
@@ -26,9 +26,9 @@
|
||||
"watch-allow-unused": "yarn build-allow-unused --watch --preserveWatchOutput",
|
||||
"typecheck": "tsc",
|
||||
"prepack": "yarn rebuild",
|
||||
"rebuild": "rimraf build *.tsbuildinfo && yarn build",
|
||||
"rebuild": "rimraf build \"*.tsbuildinfo\" && yarn build",
|
||||
"test": "jest",
|
||||
"clean": "rimraf build node_modules yarn-error.log *.tsbuildinfo"
|
||||
"clean": "rimraf build node_modules yarn-error.log \"*.tsbuildinfo\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "7.23.5",
|
||||
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user