@crossbind/extension-app-store 2.0.0-beta.76 → 2.0.0-beta.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,25 +1,39 @@
1
1
  # @crossbind/extension-app-store
2
2
 
3
- Uploads an iOS app to App Store Connect, for TestFlight and App Review.
3
+ Uploads an iOS or a macOS app to App Store Connect, for TestFlight and App Review.
4
4
 
5
- An app has it by having `@crossbind/core-app-host`, which lists it as a dependency: there is nothing to install or list.
5
+ It comes with `@crossbind/core-app-host`: there is nothing to install or list.
6
6
 
7
7
  ## Use
8
8
 
9
9
  ```sh
10
- npx crossbind app publish app-store --submit
10
+ npx crossbind app store app-store
11
+ npx crossbind app store app-store --send
12
+ npx crossbind app upload app-store
13
+ npx crossbind app release app-store -p macos --rollout 10
11
14
  ```
12
15
 
13
- It builds the iOS app with the next build number, archives it and uploads it to App Store Connect, whose TestFlight
14
- hands it to testers. `--submit` hands the version to App Review too, with the listing in `store/app-store`, and
15
- `--phased` releases what App Review approves in phases over 7 days. An iOS publish that names no store comes here.
16
+ An upload sends the iOS app, then the macOS one; `-p` sends one alone, and `crossbind app upload -p ios` with no
17
+ store name comes here. `crossbind app store` lists what only Apple's sites take, and `crossbind app store app-store
18
+ --send` sends the listing in `store/app-store` alone, with no build, into the version of `package.json`'s number,
19
+ through the App Store Connect API key.
20
+
21
+ - **iOS:** the upload builds the app with the next build number, archives it and uploads it to App Store Connect,
22
+ whose TestFlight hands it to testers.
23
+ - **macOS:** the upload builds the app in the App Sandbox, without its updater and for macOS 13 or later, and Xcode
24
+ exports it into the iOS app's record, as a universal purchase. Xcode's account or an Admin key signs the app and its
25
+ installer package in the cloud, so you make no certificate by hand.
26
+
27
+ A release hands the version to App Review, with no build, with the newest build of it TestFlight's testers have and the
28
+ listing in `store/app-store`: its `APP_DESKTOP` screenshots go with the macOS version, the others with the iOS one.
29
+ `--rollout` releases what App Review approves in phases over 7 days.
16
30
 
17
31
  ## Platforms
18
32
 
19
- An iOS app, built on a Mac with Xcode.
33
+ An iOS app, built on a Mac with Xcode, and a macOS app, built and uploaded on macOS.
20
34
 
21
35
  ## Replace or leave out
22
36
 
23
37
  An extension named `app-store` with a publisher takes its place, and `app: { without: ['app-store'] }` in `crossbind.config.js` leaves it out. [extensions.md](https://github.com/crossbind/crossbind/blob/main/docs/api/extensions.md#publishers) says what one gives.
24
38
 
25
- [app.md](https://github.com/crossbind/crossbind/blob/main/docs/api/app.md#app-store-connect) has what it needs before the build, and how it asks for what is missing.
39
+ [app.md](https://github.com/crossbind/crossbind/blob/main/docs/api/app.md#app-store-connect) has what it needs before the build and how it asks for what is missing, and its [Mac App Store](https://github.com/crossbind/crossbind/blob/main/docs/api/app.md#mac-app-store) section what the App Sandbox changes.
@@ -1,21 +1,34 @@
1
- import { appStoreCaller } from './src/appStoreApi.js';
1
+ import {
2
+ APP_STORE_LISTING, appStoreApp, appStoreCaller, appStoreListingProblems, appStoreState, askAppId, listingOf,
3
+ readAppStoreListing, readAppStoreSettings, releaseVersion, sendListing, untilDone, uploadArchive,
4
+ } from '@crossbind/core-store-kit';
2
5
  import {
3
6
  addDsyms, archiveIosApp, archivedBinary, archivedPrivacy, archivedTargets, uploadIosArchive,
4
7
  } from './src/appStoreConnect.js';
5
- import { APP_STORE_LISTING, readAppStoreListing } from './src/appStoreListing.js';
6
- import {
7
- appStoreApp, assertReviewable, newestBuild, submitRelease,
8
- } from './src/appStoreRelease.js';
9
- import { askAppId } from '@crossbind/core-store-kit';
10
8
  import { askEncryption, askIcon, askPrivacy } from './src/appSetup.js';
9
+ import { appStoreGuide } from './src/appStoreGuide.js';
10
+ import { writeArchive } from './src/macArchive.js';
11
+
12
+ // The platforms App Store Connect takes of crossbind's apps, as its API names them.
13
+ const PLATFORMS = {
14
+ ios: { api: 'IOS', name: 'iOS' },
15
+ macos: { api: 'MAC_OS', name: 'macOS' },
16
+ };
17
+ // The Mac App Store takes an Apple silicon app of macOS 13 or later.
18
+ const MINIMUM_MACOS = '13.0';
11
19
 
12
- const NO_APP_ID = 'crossbind: App Store Connect knows an app by its bundle id, app.id, which crossbind.config.js does not set: set it, as com.example.myapp, before the first publish, as Apple keeps it for good.';
20
+ const NO_APP_ID = 'crossbind: App Store Connect knows an app by its bundle id, app.id, which crossbind.config.js does not set: set it, as com.example.myapp, before the first upload, as Apple keeps it for good.';
13
21
  const NO_TEAM = "crossbind: App Store Connect takes uploads from an Apple Developer Program team, which neither app.team in crossbind.config.js nor this machine's XCODE_DEVELOPMENT_TEAM names: set either to its id, which developer.apple.com/account shows under Membership details.";
14
- const NO_ICON = 'crossbind: App Store Connect takes no iOS app without an icon: set app.icon in crossbind.config.js to a square PNG, at best 1024 × 1024.';
22
+ const NO_CATEGORY = 'crossbind: the Mac App Store takes no app without its category: set app.category in crossbind.config.js.';
15
23
  const NO_ENCRYPTION = 'crossbind: app.encryption is not set, so App Store Connect asks whether this build uses encryption before TestFlight hands it out; set it in crossbind.config.js to answer for every build.';
16
- const NO_ENCRYPTION_TO_SUBMIT = 'crossbind: App Review takes no build without its answer to whether it uses encryption: set app.encryption in crossbind.config.js.';
17
- const NO_KEY_TO_SUBMIT = "crossbind: --submit hands the version to App Review through App Store Connect's API, which takes an API key: set CROSSBIND_APPLE_API_KEY, CROSSBIND_APPLE_API_KEY_ID and CROSSBIND_APPLE_API_ISSUER, as app.md's Publishing says.";
24
+ const NO_KEY_TO_RELEASE = "crossbind: crossbind app release hands the version to App Review through App Store Connect's API, which takes an API key: set CROSSBIND_APPLE_API_KEY, CROSSBIND_APPLE_API_KEY_ID and CROSSBIND_APPLE_API_ISSUER, as app.md's Publishing says.";
25
+ const NO_KEY_TO_SEND = "crossbind: crossbind app store --send sends the page through App Store Connect's API, which takes an API key: set CROSSBIND_APPLE_API_KEY, CROSSBIND_APPLE_API_KEY_ID and CROSSBIND_APPLE_API_ISSUER, as app.md's Publishing says.";
26
+ const NO_KEY_TO_SEE = "Set CROSSBIND_APPLE_API_KEY, CROSSBIND_APPLE_API_KEY_ID and CROSSBIND_APPLE_API_ISSUER, an App Store Connect API key's, to see what App Store Connect has.";
18
27
  const TEAM_ID = /^[A-Z0-9]{10}$/;
28
+ const noIcon = (platform) => `crossbind: App Store Connect takes no ${platform} app without an icon: set app.icon in crossbind.config.js to a square PNG, at best 1024 × 1024.`;
29
+ const notOnMac = (id, then = 'upload again, or upload the iOS app alone with -p ios') => `crossbind: App Store Connect's app ${id} is not on macOS yet: add the platform there, with the + beside its platform in the sidebar, which makes it a universal purchase, then ${then}.`;
30
+ const SEND_AGAIN = "send again, or send the iOS app's page alone with -p ios";
31
+ const RELEASE_AGAIN = 'release again, or release the iOS app alone with -p ios';
19
32
 
20
33
  async function pickTeam(api, teams) {
21
34
  if (teams.length === 1) {
@@ -60,58 +73,73 @@ async function askTeam(api) {
60
73
  api.log(`crossbind: ~/.crossbind.json keeps ${id} as XCODE_DEVELOPMENT_TEAM.`);
61
74
  }
62
75
 
63
- // A step that failed for what only the user can mend, in Xcode or on Apple's sites, runs again once they press Enter,
64
- // after crossbind opened the page that mends it where it knows one. Any other failure, or one without a terminal, stops
65
- // the publish.
66
- async function untilDone(api, step) {
67
- for (;;) {
68
- try {
69
- return step();
70
- } catch (error) {
71
- if (!api.isGuided || !error.isMendable) throw error;
72
- api.log(error.message);
73
- if (error.page) {
74
- api.log(`crossbind: opening ${error.page}.`);
75
- api.openUrl(error.page);
76
- }
77
- await api.ask('Press Enter once that is done to try again, or Ctrl-C to stop. ');
78
- api.log('crossbind: trying again, which can take a few minutes.');
79
- }
80
- }
76
+ // The minimum macOS release of the store's build: the app's own where it is later.
77
+ function minimumMacos(api) {
78
+ const own = api.config.app.macos?.minimumVersion;
79
+ return typeof own === 'string' && own.localeCompare(MINIMUM_MACOS, undefined, { numeric: true }) > 0 ? own : MINIMUM_MACOS;
81
80
  }
82
81
 
83
- // What a publish with --submit hands to App Review through: the API, the app App Store Connect has, and the listing,
84
- // once App Store Connect would take the version to review.
85
- async function reviewableRelease(api, key, bundleId, listings) {
82
+ // Whether the app's record is on macOS too: once its user adds the platform, App Store Connect prepares a macOS version.
83
+ async function isOnMac(call, appId) {
84
+ const { data } = await call('GET', `/apps/${appId}/appStoreVersions?${new URLSearchParams({ 'filter[platform]': PLATFORMS.macos.api, limit: '1' })}`);
85
+ return data.length > 0;
86
+ }
87
+
88
+ // What a macOS app's record lacks, which a key reads before the build: the macOS platform, which App Store Connect takes
89
+ // no macOS build of the app without.
90
+ async function macRecordMissing(api, key) {
91
+ if (!key || api.platform !== 'macos') return [];
86
92
  const call = appStoreCaller(key);
87
- const appStoreId = await appStoreApp(call, bundleId);
88
- await assertReviewable(call, appStoreId, api.app.appleVersion);
89
- return { call, appStoreId, listings };
93
+ return await isOnMac(call, await appStoreApp(call, api.app.id)) ? [] : [notOnMac(api.app.id)];
90
94
  }
91
95
 
92
- // Hands the uploaded build to App Review, with the listing, and says how it went.
93
- async function submitToReview(api, { call, appStoreId, listings }, { before, facts }) {
94
- const isPhased = api.options.phased;
95
- const { build, listed } = await submitRelease(call, {
96
- appId: appStoreId, versionString: api.app.appleVersion, before, buildNumber: api.app.buildNumber, listings, isPhased,
97
- });
96
+ // Says what of the page changed on App Store Connect, as the project has it.
97
+ function saySent(api, platform, listings, { listed, settled }) {
98
98
  if (listings.length > 0) {
99
99
  api.log(listed.length > 0
100
- ? `crossbind: App Store Connect's listing changed in ${listed.join(', ')}, as ${APP_STORE_LISTING} has it.`
101
- : `crossbind: App Store Connect's listing is the one ${APP_STORE_LISTING} has already.`);
100
+ ? `crossbind: App Store Connect's ${platform.name} listing changed in ${listed.join(', ')}, as ${APP_STORE_LISTING} has it.`
101
+ : `crossbind: App Store Connect's ${platform.name} listing is the one ${APP_STORE_LISTING} has already.`);
102
+ }
103
+ if (settled.length > 0) api.log(`crossbind: App Store Connect's ${settled.join(', ')} changed, as ${APP_STORE_LISTING} has them.`);
104
+ }
105
+
106
+ // Hands App Review the version of package.json's number on the platform, with the newest build of it App Store Connect
107
+ // has processed, which TestFlight's testers have, and the page store/app-store holds, with no build, to go out in phases
108
+ // over 7 days once approved where --rollout says so; says how it went.
109
+ async function releaseToReview(api) {
110
+ const platform = PLATFORMS[api.platform];
111
+ const root = api.project.root;
112
+ const listings = listingOf(readAppStoreListing(root), platform.api);
113
+ const settings = readAppStoreSettings(root);
114
+ const missing = appStoreListingProblems(root, listings);
115
+ const key = api.apple.key();
116
+ if (!key) missing.push(NO_KEY_TO_RELEASE);
117
+ if (api.config.app.id === undefined) {
118
+ if (api.isGuided) await askAppId(api, 'App Store Connect', 'bundle id');
119
+ else missing.push(NO_APP_ID);
102
120
  }
103
- const phases = isPhased ? ', to go out in phases over 7 days once released' : '';
104
- api.log(`crossbind: ${facts.id} ${api.app.appleVersion} (build ${build}) went to App Review${phases}; Apple mails as the review goes.`);
121
+ if (missing.length > 0) return { missing };
122
+ const call = appStoreCaller(key);
123
+ const appStoreId = await appStoreApp(call, api.app.id);
124
+ if (api.platform === 'macos' && !await isOnMac(call, appStoreId)) return { missing: [notOnMac(api.app.id, RELEASE_AGAIN)] };
125
+ const isPhased = api.options.rollout !== null;
126
+ api.log(`crossbind: handing ${api.app.id} ${api.app.appleVersion} for ${platform.name} to App Review, with the newest build of it App Store Connect has processed.`);
127
+ const { build, listed, settled } = await releaseVersion(call, {
128
+ appId: appStoreId, versionString: api.app.appleVersion, listings, settings, isPhased, usesEncryption: api.app.encryption, platform: platform.api,
129
+ });
130
+ saySent(api, platform, listings, { listed, settled });
131
+ const phases = isPhased ? ', to go out in phases over 7 days once approved' : '';
132
+ api.log(`crossbind: ${api.app.id} ${api.app.appleVersion} (build ${build}) for ${platform.name} went to App Review${phases}; Apple mails as the review goes.`);
133
+ return {};
105
134
  }
106
135
 
107
- // An app extension's reasons are its target's, which its extension gives, so the publish names them and asks for none.
136
+ // An app extension's reasons are its target's, which its extension gives, so the upload names them and asks for none.
108
137
  const unreasonedTargetError = ({ name, unreasoned }) => new Error(`crossbind: App Store Connect refuses an iOS app that calls required reason API without Apple's reasons for it (ITMS-91053), and the app's target ${name} calls ${unreasoned.map(({ category, symbols }) => `${category} (${symbols.join(', ')})`).join(' and ')} with no reason in its privacy manifest. Its extension gives the target Apple's reasons in its privacy, as { fileTimestamp: ['C617.1'] }. Nothing went to App Store Connect.`);
109
138
  const unreasonedError = (unreasoned) => new Error(`crossbind: App Store Connect refuses an iOS app that calls required reason API without Apple's reasons for it (ITMS-91053), and this app calls ${unreasoned.map(({ category, symbols }) => `${category} (${symbols.join(', ')})`).join(' and ')} with no reason in its privacy manifest. Give app.privacy Apple's reasons, as { fileTimestamp: ['C617.1'] }; Apple's "Describing use of required reason API" says what each covers. Nothing went to App Store Connect.`);
110
139
 
111
140
  // What the app lacks that App Store Connect asks for, asked for on a terminal and named at once without one.
112
- async function missingOf(api, { key, shouldSubmit }) {
141
+ async function missingOf(api) {
113
142
  const missing = [];
114
- if (shouldSubmit && !key) missing.push(NO_KEY_TO_SUBMIT);
115
143
  if (api.config.app.id === undefined) {
116
144
  if (api.isGuided) await askAppId(api, 'App Store Connect', 'bundle id');
117
145
  else missing.push(NO_APP_ID);
@@ -122,77 +150,155 @@ async function missingOf(api, { key, shouldSubmit }) {
122
150
  }
123
151
  if (api.config.app.icon === undefined) {
124
152
  if (api.isGuided) await askIcon(api);
125
- else missing.push(NO_ICON);
153
+ else missing.push(noIcon(PLATFORMS[api.platform].name));
126
154
  }
127
- if (shouldSubmit && !api.isGuided && api.app.encryption === null) missing.push(NO_ENCRYPTION_TO_SUBMIT);
155
+ if (api.platform === 'macos' && !api.app.category?.macos) missing.push(NO_CATEGORY);
128
156
  return missing;
129
157
  }
130
158
 
131
- // The publisher of an iOS app to App Store Connect, whose TestFlight hands it out: crossbind builds the app, which the
132
- // upload archives, and the archived app shows what required reason API it calls before it goes.
159
+ // Archives the iOS app crossbind built, which shows what required reason API it calls before it goes, and uploads it.
160
+ async function uploadIos(api, { key, dsyms, facts }, { project }) {
161
+ api.log('crossbind: archiving the app, which takes a few minutes.');
162
+ const archive = await untilDone(api, () => archiveIosApp(api, project, { facts }));
163
+ const target = archivedTargets(api, archive).map(({ name, binary, privacy }) => ({ name, unreasoned: api.apple.unreasonedApis(binary, privacy) }))
164
+ .find(({ unreasoned }) => unreasoned.length > 0);
165
+ if (target) throw unreasonedTargetError(target);
166
+ const unreasoned = api.apple.unreasonedApis(archivedBinary(api, archive), archivedPrivacy(api, archive));
167
+ if (unreasoned.length > 0) {
168
+ if (!api.isGuided) throw unreasonedError(unreasoned);
169
+ await askPrivacy(api, unreasoned);
170
+ api.log('crossbind: building the app again, with those reasons in its privacy manifest.');
171
+ return { isRebuildAsked: true };
172
+ }
173
+ addDsyms(archive, dsyms);
174
+ api.log(`crossbind: uploading the app to App Store Connect for team ${facts.team} with ${key ? `the API key ${key.keyId}` : "Xcode's account"}, which signs it.`);
175
+ const build = api.app.buildNumber;
176
+ await untilDone(api, () => uploadIosArchive(api, archive, {
177
+ team: facts.team, key, isBuildManaged: build === null, facts,
178
+ }));
179
+ const app = build === null ? `${facts.id} ${api.app.appleVersion}, numbered by Xcode after the builds App Store Connect has of it,` : `${facts.id} ${api.app.appleVersion} (build ${build})`;
180
+ api.log(`crossbind: ${app} is on App Store Connect. TestFlight hands it out once Apple has processed it, usually within 5 to 30 minutes, and Apple mails when it has; crossbind app release app-store then hands it to App Review.`);
181
+ return { published: { appId: facts.id, version: api.app.appleVersion, build } };
182
+ }
183
+
184
+ // Puts the macOS app crossbind built in an archive Xcode exports to App Store Connect, which signs it and its installer
185
+ // package in the cloud.
186
+ async function uploadMac(api, { key, facts }, { apps }) {
187
+ const [built] = apps;
188
+ if (!built) throw new Error('crossbind: the build made no macOS app, so nothing went to App Store Connect.');
189
+ const archive = writeArchive(api, built, { team: facts.team });
190
+ const build = api.app.buildNumber;
191
+ api.log(`crossbind: uploading the app to App Store Connect for team ${facts.team} with ${key ? `the API key ${key.keyId}` : "Xcode's account"}, which signs it and its installer package.`);
192
+ await untilDone(api, () => uploadArchive(api, archive, {
193
+ team: facts.team, key, isBuildManaged: build === null, facts, platform: 'macOS',
194
+ }));
195
+ const app = build === null
196
+ ? `${facts.id} ${api.app.appleVersion} for macOS, numbered by Xcode after the builds App Store Connect has of it,`
197
+ : `${facts.id} ${api.app.appleVersion} (build ${build}) for macOS`;
198
+ api.log(`crossbind: ${app} is on App Store Connect. TestFlight hands it to Mac testers once Apple has processed it, usually within 5 to 30 minutes, and Apple mails when it has; crossbind app release app-store then hands it to App Review.`);
199
+ return { published: { appId: facts.id, version: api.app.appleVersion, build } };
200
+ }
201
+
202
+ // Whether the project's settings give App Store Connect anything.
203
+ const hasSettings = ({
204
+ copyright, categories, ageRating, review,
205
+ }) => copyright !== undefined || Object.keys(categories).length > 0 || Boolean(ageRating) || Object.keys(review).length > 0;
206
+
207
+ // Sends the page store/app-store holds of the app on its platform, with no build: its listing, screenshots and settings,
208
+ // through App Store Connect's API, into the version of package.json's number, which shows them once out.
209
+ async function sendPage(api) {
210
+ const platform = PLATFORMS[api.platform];
211
+ const root = api.project.root;
212
+ const listings = listingOf(readAppStoreListing(root), platform.api);
213
+ const settings = readAppStoreSettings(root);
214
+ if (listings.length === 0 && !hasSettings(settings)) {
215
+ api.log(`crossbind: ${APP_STORE_LISTING} holds no page of the app, so nothing went to App Store Connect for ${platform.name}.`);
216
+ return {};
217
+ }
218
+ const problems = appStoreListingProblems(root, listings);
219
+ if (problems.length > 0) return { missing: problems };
220
+ const key = api.apple.key();
221
+ const missing = key ? [] : [NO_KEY_TO_SEND];
222
+ if (api.config.app.id === undefined) {
223
+ if (api.isGuided) await askAppId(api, 'App Store Connect', 'bundle id');
224
+ else missing.push(NO_APP_ID);
225
+ }
226
+ if (missing.length > 0) return { missing };
227
+ const call = appStoreCaller(key);
228
+ const appStoreId = await appStoreApp(call, api.app.id);
229
+ if (api.platform === 'macos' && !await isOnMac(call, appStoreId)) return { missing: [notOnMac(api.app.id, SEND_AGAIN)] };
230
+ api.log(`crossbind: sending the ${platform.name} page ${APP_STORE_LISTING} holds of ${api.app.id} ${api.app.appleVersion} to App Store Connect.`);
231
+ const sent = await sendListing(call, {
232
+ appId: appStoreId, versionString: api.app.appleVersion, listings, settings, platform: platform.api,
233
+ });
234
+ saySent(api, platform, listings, sent);
235
+ return {};
236
+ }
237
+
238
+ // What App Store Connect has of the app on each platform, asking for nothing.
239
+ async function pageState(api) {
240
+ const key = api.apple.key();
241
+ if (!key) return [NO_KEY_TO_SEE];
242
+ if (api.config.app.id === undefined) return ['Set app.id in crossbind.config.js, and App Store Connect tells what it has of the app.'];
243
+ const call = appStoreCaller(key);
244
+ const lines = await appStoreState(call, await appStoreApp(call, api.app.id));
245
+ return lines.length > 0 ? lines : [`no version or build of ${api.app.id} yet`];
246
+ }
247
+
248
+ // The publisher of an app's iOS and macOS builds to App Store Connect, whose TestFlight hands them out, both one after
249
+ // the other or the one -p names: crossbind builds the app, a macOS one sandboxed, the upload archives it, an iOS one
250
+ // after showing what required reason API it calls, and Xcode exports the archive to App Store Connect, which signs it in
251
+ // the cloud. The release hands the build TestFlight's testers have to App Review with the app's page in store/app-store,
252
+ // which also goes alone.
133
253
  export default function appStore() {
134
254
  return {
135
255
  name: 'app-store',
136
256
  contract: 1,
137
257
  root: import.meta.dirname,
138
258
  publisher: {
139
- platform: 'ios',
140
- isDefault: true,
259
+ platform: ['ios', 'macos'],
260
+ isDefault: ['ios'],
141
261
  store: 'App Store Connect',
142
- options: {
143
- submit: { help: "hand the iOS app's version to App Review too, with the build and the listing in store/app-store, through App Store Connect's API" },
144
- phased: { help: 'release the version App Review approves in phases over 7 days, with --submit' },
145
- },
262
+ canStage: true,
263
+
264
+ // The store updates the macOS app it installs from the installer package the upload makes, and takes it
265
+ // sandboxed.
266
+ build: (api) => (api.platform === 'macos' ? { app: { updater: null, installers: [], macos: { sandbox: true, minimumVersion: minimumMacos(api) } } } : null),
146
267
 
147
268
  async check(api) {
148
- const { submit: shouldSubmit, phased } = api.options;
149
- if (phased && !shouldSubmit) throw new Error('crossbind: --phased releases the version App Review approves, so it takes --submit.');
150
- if (process.platform !== 'darwin') throw new Error('crossbind: iOS apps build and go to App Store Connect on macOS, with Xcode.');
269
+ const platform = PLATFORMS[api.platform];
270
+ if (process.platform !== 'darwin') throw new Error(`crossbind: ${platform.name} apps build and go to App Store Connect on macOS, with Xcode.`);
151
271
  const key = api.apple.key();
152
- const listings = shouldSubmit ? readAppStoreListing(api.project.root) : [];
153
- const missing = await missingOf(api, { key, shouldSubmit });
272
+ const missing = await missingOf(api);
154
273
  if (missing.length > 0) return { missing };
155
274
  if (api.app.encryption === null) {
156
275
  if (api.isGuided) await askEncryption(api);
157
276
  else api.warn(NO_ENCRYPTION);
158
277
  }
278
+ const unready = await macRecordMissing(api, key);
279
+ if (unready.length > 0) return { missing: unready };
159
280
  const facts = { id: api.app.id, team: api.app.team };
160
- const release = shouldSubmit ? await reviewableRelease(api, key, facts.id, listings) : null;
161
- const dsyms = await api.apple.dsyms();
162
- api.log(`crossbind: publishing ${facts.id} ${api.app.appleVersion} to App Store Connect for team ${facts.team}${release ? ' and App Review' : ''}; building the app first.`);
163
- return { session: { key, dsyms, facts, release } };
281
+ const dsyms = api.platform === 'ios' ? { dsyms: await api.apple.dsyms() } : {};
282
+ api.log(`crossbind: publishing ${facts.id} ${api.app.appleVersion} for ${platform.name} to App Store Connect for team ${facts.team}; building the app first.`);
283
+ return { session: { key, ...dsyms, facts } };
164
284
  },
165
285
 
166
286
  // Xcode numbers a build without CROSSBIND_APP_BUILD_NUMBER after those App Store Connect has.
167
287
  buildNumber: (api) => api.app.buildNumber,
168
288
 
169
- async upload(api, {
170
- key, dsyms, facts, release,
171
- }, { project }) {
172
- api.log('crossbind: archiving the app, which takes a few minutes.');
173
- const archive = await untilDone(api, () => archiveIosApp(api, project, { facts }));
174
- const target = archivedTargets(api, archive).map(({ name, binary, privacy }) => ({ name, unreasoned: api.apple.unreasonedApis(binary, privacy) }))
175
- .find(({ unreasoned }) => unreasoned.length > 0);
176
- if (target) throw unreasonedTargetError(target);
177
- const unreasoned = api.apple.unreasonedApis(archivedBinary(api, archive), archivedPrivacy(api, archive));
178
- if (unreasoned.length > 0) {
179
- if (!api.isGuided) throw unreasonedError(unreasoned);
180
- await askPrivacy(api, unreasoned);
181
- api.log('crossbind: building the app again, with those reasons in its privacy manifest.');
182
- return { isRebuildAsked: true };
183
- }
184
- addDsyms(archive, dsyms);
185
- api.log(`crossbind: uploading the app to App Store Connect for team ${facts.team} with ${key ? `the API key ${key.keyId}` : "Xcode's account"}, which signs it.`);
186
- const build = api.app.buildNumber;
187
- const before = release ? await newestBuild(release.call, release.appStoreId, api.app.appleVersion) : null;
188
- await untilDone(api, () => uploadIosArchive(api, archive, {
189
- team: facts.team, key, isBuildManaged: build === null, facts,
190
- }));
191
- const app = build === null ? `${facts.id} ${api.app.appleVersion}, numbered by Xcode after the builds App Store Connect has of it,` : `${facts.id} ${api.app.appleVersion} (build ${build})`;
192
- api.log(`crossbind: ${app} is on App Store Connect. TestFlight hands it out once Apple has processed it, usually within 5 to 30 minutes, and Apple mails when it has.`);
193
- if (release) await submitToReview(api, release, { before, facts });
194
- return { published: { appId: facts.id, version: api.app.appleVersion, build } };
195
- },
289
+ // The build signs a macOS app ad hoc, whatever Developer ID this machine names, as the upload signs it for the
290
+ // store.
291
+ buildEnv: (api) => (api.platform === 'macos' ? { CROSSBIND_APPLE_SIGNING_IDENTITY: undefined } : {}),
292
+
293
+ upload: (api, session, output) => (api.platform === 'macos' ? uploadMac(api, session, output) : uploadIos(api, session, output)),
294
+
295
+ release: (api) => releaseToReview(api),
296
+
297
+ send: (api) => sendPage(api),
298
+
299
+ state: (api) => pageState(api),
300
+
301
+ guide: (api) => appStoreGuide(api),
196
302
  },
197
303
  };
198
304
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@crossbind/extension-app-store",
3
- "version": "2.0.0-beta.76",
4
- "description": "crossbind app extension: uploads an iOS app to App Store Connect, for TestFlight and App Review.",
3
+ "version": "2.0.0-beta.79",
4
+ "description": "crossbind app extension: uploads an iOS or a macOS app to App Store Connect, for TestFlight and App Review.",
5
5
  "homepage": "https://github.com/crossbind/crossbind/tree/main/extensions/app-store#readme",
6
6
  "repository": {
7
7
  "type": "git",
@@ -20,7 +20,7 @@
20
20
  "extension": "./crossbind.extension.js"
21
21
  },
22
22
  "dependencies": {
23
- "@crossbind/core-store-kit": "^2.0.0-beta.76"
23
+ "@crossbind/core-store-kit": "^2.0.0-beta.79"
24
24
  },
25
25
  "keywords": [
26
26
  "crossbind-extension",
package/src/appSetup.js CHANGED
@@ -1,4 +1,4 @@
1
- // What only the project can answer, which a publish asks on a terminal and writes into crossbind.config.js once the
1
+ // What only the project can answer, which an upload asks on a terminal and writes into crossbind.config.js once the
2
2
  // user says yes, through the api.
3
3
 
4
4
  const REASONS_PAGE = 'https://developer.apple.com/documentation/bundleresources/describing-use-of-required-reason-api';
@@ -1,22 +1,10 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { spawnSync } from 'node:child_process';
4
+ import { uploadArchive } from '@crossbind/core-store-kit';
4
5
 
5
- export const APP_STORE_CONNECT = 'https://appstoreconnect.apple.com/apps';
6
-
7
- // An upload to an app App Store Connect does not have yet, which only its site makes.
8
- const MISSING_APP = {
9
- pattern: /No suitable application records were found|App record with bundle identifier .* not found/i,
10
- hint: ({ id }) => `App Store Connect has no app ${id}: create it at ${APP_STORE_CONNECT}, a new iOS app with ${id} as its bundle ID, which this publish registered with Apple.`,
11
- page: APP_STORE_CONNECT,
12
- };
13
-
14
- // What a failed upload means beside what crossbind knows of any xcodebuild's failure.
15
- const CAUSES = [MISSING_APP];
16
-
17
- const keyArgs = (key) => (key ? ['-authenticationKeyPath', key.key, '-authenticationKeyID', key.keyId, '-authenticationKeyIssuerID', key.issuer] : []);
18
6
  const archivedApp = (api, archive) => `${archive}/Products/Applications/${api.project.name}.app`;
19
- const xcodebuild = (api, what, args, log, facts) => api.apple.xcodebuild(what, args, { log: `${api.workDir}/${log}`, facts, causes: CAUSES });
7
+ const xcodebuild = (api, what, args, log, facts) => api.apple.xcodebuild(what, args, { log: `${api.workDir}/${log}`, facts, causes: [] });
20
8
 
21
9
  // The entitlements files the Xcode project names: the app's, or null without one, and those of the targets of Apple's
22
10
  // app extensions of its, which crossbind writes in targets/<name>/, by their names.
@@ -98,63 +86,5 @@ export function addDsyms(archive, dsyms) {
98
86
  dsyms.forEach((dsym) => fs.cpSync(dsym, `${archive}/dSYMs/${path.basename(dsym)}`, { recursive: true }));
99
87
  }
100
88
 
101
- const escaped = (text) => text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
102
-
103
- // The options of an export for App Store Connect, an XML plist: an upload with the app's dSYMs, or an .ipa alone.
104
- function writeExportOptions(file, { destination, team, isBuildManaged }) {
105
- const options = {
106
- destination,
107
- manageAppVersionAndBuildNumber: isBuildManaged,
108
- method: 'app-store-connect',
109
- signingStyle: 'automatic',
110
- teamID: team,
111
- uploadSymbols: destination === 'upload',
112
- };
113
- fs.writeFileSync(file, [
114
- '<?xml version="1.0" encoding="UTF-8"?>',
115
- '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
116
- '<plist version="1.0">',
117
- '<dict>',
118
- ...Object.entries(options).flatMap(([key, value]) => [` <key>${key}</key>`, typeof value === 'boolean' ? ` <${value}/>` : ` <string>${escaped(value)}</string>`]),
119
- '</dict>',
120
- '</plist>',
121
- '',
122
- ].join('\n'));
123
- return file;
124
- }
125
-
126
- // Registers the app's bundle id with Apple, as App Store Connect's form for a new app lists registered ids alone. An
127
- // upload asks for the app record before it signs, so it registers nothing; an export to an .ipa, with no build number
128
- // to look up, signs at once, which registers the id.
129
- function registerBundleId(api, archive, { team, key, facts }) {
130
- const options = writeExportOptions(`${api.workDir}/RegisterOptions.plist`, { destination: 'export', team, isBuildManaged: false });
131
- xcodebuild(api, 'the registration of the bundle id', [
132
- '-exportArchive', '-archivePath', archive, '-exportOptionsPlist', options, '-exportPath', `${api.workDir}/register`, '-allowProvisioningUpdates',
133
- ...keyArgs(key),
134
- ], 'register.log', facts);
135
- }
136
-
137
- // Exports the archive for App Store Connect and uploads it with its dSYMs, signed for distribution in the cloud by Xcode's
138
- // account or an Admin key, else with an Apple Distribution certificate in the keychain, with the entitlements of its ad
139
- // hoc signature, which the App ID gets the capabilities of. Xcode numbers the build unless CROSSBIND_APP_BUILD_NUMBER
140
- // did, and writes nothing to -exportPath, which xcodebuild asks for all the same.
141
- export function uploadIosArchive(api, archive, {
142
- team, key, isBuildManaged, facts,
143
- }) {
144
- const options = writeExportOptions(`${api.workDir}/ExportOptions.plist`, { destination: 'upload', team, isBuildManaged });
145
- let output;
146
- try {
147
- output = xcodebuild(api, 'the upload', [
148
- '-exportArchive', '-archivePath', archive, '-exportOptionsPlist', options, '-exportPath', `${api.workDir}/export`, '-allowProvisioningUpdates',
149
- ...keyArgs(key),
150
- ], 'upload.log', facts);
151
- } catch (error) {
152
- if (error.reason === MISSING_APP) {
153
- api.log(`crossbind: App Store Connect has no app ${facts.id} yet, so this publish registers its bundle id with Apple first.`);
154
- registerBundleId(api, archive, { team, key, facts });
155
- }
156
- throw error;
157
- }
158
- // What App Store Connect warns of, as a dSYM it could not take, goes up with the app all the same.
159
- output.split('\n').filter((line) => line.startsWith('warning: exportArchive')).forEach((line) => api.warn(`crossbind: ${line}`));
160
- }
89
+ // Exports the iOS app's archive for App Store Connect and uploads it, as a macOS app's goes too.
90
+ export const uploadIosArchive = (api, archive, options) => uploadArchive(api, archive, { ...options, platform: 'iOS' });
@@ -0,0 +1,110 @@
1
+ import path from 'node:path';
2
+ import {
3
+ APP_STORE_CONNECT, APP_STORE_LISTING, appStoreListingProblems, readAppStoreListing, readAppStoreSettings,
4
+ } from '@crossbind/core-store-kit';
5
+
6
+ const API_KEYS = 'https://appstoreconnect.apple.com/access/integrations/api';
7
+ const TEXTS = {
8
+ name: 'name',
9
+ subtitle: 'subtitle',
10
+ privacyPolicyUrl: 'privacy policy URL',
11
+ description: 'description',
12
+ keywords: 'keywords',
13
+ whatsNew: 'release notes',
14
+ promotionalText: 'promotional text',
15
+ supportUrl: 'support URL',
16
+ marketingUrl: 'marketing URL',
17
+ };
18
+ const file = (name) => path.join(APP_STORE_LISTING, name);
19
+
20
+ // What crossbind app store --send sends of a locale, as a release does: its texts and its screenshots of
21
+ // each display type.
22
+ function localeLine({
23
+ locale, info, version, screenshots,
24
+ }) {
25
+ const parts = [
26
+ Object.keys({ ...info, ...version }).map((field) => TEXTS[field]).join(', '),
27
+ Object.entries(screenshots).map(([type, files]) => `${files.length} ${type} screenshots`).join(', '),
28
+ ].filter(Boolean);
29
+ return `${path.join(APP_STORE_LISTING, locale)}: ${parts.join('; ')}`;
30
+ }
31
+
32
+ // The project's listing and settings, with what stops reading them as a problem of its own.
33
+ function readAll(root) {
34
+ const problems = [];
35
+ let listings = [];
36
+ let settings = { categories: {}, review: {} };
37
+ try {
38
+ listings = readAppStoreListing(root);
39
+ problems.push(...appStoreListingProblems(root, listings));
40
+ } catch (error) {
41
+ problems.push(error.message);
42
+ }
43
+ try {
44
+ settings = readAppStoreSettings(root);
45
+ } catch (error) {
46
+ problems.push(error.message);
47
+ }
48
+ return { listings, settings, problems };
49
+ }
50
+
51
+ // What crossbind app store --send sends of the app's settings, as a release does.
52
+ function settingsLines({
53
+ copyright, categories, ageRating, review,
54
+ }) {
55
+ return [
56
+ copyright === undefined ? null : `copyright: ${copyright}`,
57
+ Object.keys(categories).length === 0 ? null : `categories: ${Object.values(categories).join(', ')}`,
58
+ ageRating ? `the age rating's answers in ${file('age_rating.json')}` : null,
59
+ Object.keys(review).length === 0 ? null : `App Review's contact in ${file('review_information')}`,
60
+ ].filter(Boolean);
61
+ }
62
+
63
+ // The steps App Store Connect alone takes of what the project's files leave out.
64
+ function lackedSteps(listings, settings) {
65
+ const has = (pattern) => listings.some(({ screenshots }) => Object.keys(screenshots).some((type) => pattern.test(type)));
66
+ return [
67
+ listings.some(({ info }) => info.privacyPolicyUrl !== undefined) ? null
68
+ : `App Information › Privacy Policy URL, which privacy_url.txt in a locale's folder of ${APP_STORE_LISTING} would send.`,
69
+ settings.categories.primaryCategory ? null : `App Information › Category, which ${file('primary_category.txt')} would send, as UTILITIES.`,
70
+ settings.ageRating ? null : `App Information › Age Rating: answer Apple's questions, which ${file('age_rating.json')} would send.`,
71
+ settings.copyright === undefined ? `The version's Copyright, which ${file('copyright.txt')} would send.` : null,
72
+ Object.keys(settings.review).length > 0 ? null : `The version's App Review Information: a contact's name, phone and e-mail, which ${file('review_information')} would send.`,
73
+ has(/^APP_IPHONE_/) ? null : "The version's iPhone screenshots, 6.9-inch ones at least, which a locale's screenshots/APP_IPHONE_67 would send.",
74
+ has(/^APP_IPAD_PRO_3GEN_129$/) ? null : "The version's 13-inch iPad screenshots, which App Store Connect takes of an app that runs on iPads, as crossbind's iOS apps do; a locale's screenshots/APP_IPAD_PRO_3GEN_129 would send them.",
75
+ has(/^APP_DESKTOP$/) ? null : "The macOS version's screenshots, 16:10 ones of 1280 × 800 to 2880 × 1800, which a locale's screenshots/APP_DESKTOP would send.",
76
+ ].filter(Boolean).map((text) => ({ text }));
77
+ }
78
+
79
+ // What crossbind app store says of App Store Connect, of the iOS app and the macOS one alike: what an upload sends, what
80
+ // a release puts out, what --send sends, which a release sends too, what App Store Connect would refuse of them, and the
81
+ // steps it alone takes.
82
+ export function appStoreGuide(api) {
83
+ const { listings, settings, problems: read } = readAll(api.project.root);
84
+ const problems = [...read, ...(api.app.category?.macos ? [] : ['crossbind: app.category is not set, and the Mac App Store takes no app without its category.'])];
85
+ const uploads = [
86
+ 'the iOS app, archived and uploaded, which TestFlight hands to testers once Apple has processed it; -p ios sends it alone',
87
+ 'then the macOS app, sandboxed, in an archive Xcode exports to App Store Connect, which signs it and its installer package in the cloud, and whose TestFlight hands it to Mac testers once Apple has processed it; -p macos sends it alone',
88
+ ];
89
+ const sends = [...listings.map(localeLine), ...settingsLines(settings)];
90
+ const releases = [
91
+ "the newest build of the version TestFlight's testers have, to App Review, which puts it out once approved, in phases over 7 days with --rollout",
92
+ 'with it, the page --send sends',
93
+ ];
94
+ const id = api.config.app.id;
95
+ const steps = [
96
+ id === undefined
97
+ ? { text: 'Set app.id in crossbind.config.js, as com.example.myapp, which App Store Connect keeps for good as the bundle ID; then create the app with it, under Apps, as a new app on iOS and macOS, as an upload without -p sends both.', url: APP_STORE_CONNECT }
98
+ : { text: `Apps › New App: an app with ${id} as its bundle ID, on iOS and macOS, as an upload without -p sends both, with its name, primary language and SKU, as Apple's API makes none; an upload registers the bundle ID first, so the form lists it. An app on iOS alone takes macOS later with the + beside its platform in the sidebar, as a universal purchase, which stays one once both platforms are approved, and uploads with -p ios until then.`, url: APP_STORE_CONNECT },
99
+ { text: "App Privacy: answer what data the app and the code it carries collect, as Data Not Collected where it collects none; Apple's API takes no answer." },
100
+ { text: "Pricing and Availability: the price, free or one of Apple's, and the countries and regions the app goes to." },
101
+ { text: "App Information › Content Rights: whether the app shows, holds or reaches others' content." },
102
+ ...lackedSteps(listings, settings),
103
+ ...(api.app.encryption === null ? [{ text: 'Set app.encryption in crossbind.config.js, whose answer App Store Connect takes of every build and App Review of every submission.' }] : []),
104
+ ...(api.app.encryption === true ? [{ text: 'App Information › App Encryption Documentation: what export compliance takes of an app that uses encryption.' }] : []),
105
+ { text: "For --send, releases and CI: Users and Access › Integrations › App Store Connect API: a key of the App Manager or Admin role, as CROSSBIND_APPLE_API_KEY, CROSSBIND_APPLE_API_KEY_ID and CROSSBIND_APPLE_API_ISSUER; Apple signs the uploads of an Admin key in the cloud, as it does those of Xcode's account on your Mac.", url: API_KEYS },
106
+ ];
107
+ return {
108
+ uploads, sends, releases, problems, where: 'App Store Connect', steps,
109
+ };
110
+ }
@@ -0,0 +1,60 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawnSync } from 'node:child_process';
4
+
5
+ // Apple's names of crossbind's architectures.
6
+ const ARCHES = { arm64: 'arm64', x64: 'x86_64' };
7
+
8
+ const escaped = (text) => text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
9
+
10
+ // A value as an XML plist writes it, indented.
11
+ function plistValue(value, indent) {
12
+ if (value instanceof Date) return `${indent}<date>${value.toISOString().replace(/\.\d{3}Z$/, 'Z')}</date>`;
13
+ if (typeof value === 'number') return `${indent}<integer>${value}</integer>`;
14
+ if (Array.isArray(value)) return [`${indent}<array>`, ...value.map((item) => plistValue(item, `${indent} `)), `${indent}</array>`].join('\n');
15
+ if (typeof value === 'object') {
16
+ return [`${indent}<dict>`, ...Object.entries(value).flatMap(([key, item]) => [`${indent} <key>${escaped(key)}</key>`, plistValue(item, `${indent} `)]), `${indent}</dict>`].join('\n');
17
+ }
18
+ return `${indent}<string>${escaped(String(value))}</string>`;
19
+ }
20
+
21
+ const plist = (root) => [
22
+ '<?xml version="1.0" encoding="UTF-8"?>',
23
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
24
+ '<plist version="1.0">',
25
+ plistValue(root, ''),
26
+ '</plist>',
27
+ '',
28
+ ].join('\n');
29
+
30
+ // The archive Xcode exports for App Store Connect, of the app crossbind built and signed ad hoc, as an archive of Xcode's
31
+ // own holds one: the app under Products/Applications, and an Info.plist that names it, its version and its team. Xcode
32
+ // takes the app's entitlements from its signature.
33
+ export function writeArchive(api, { app, arch }, { team }) {
34
+ const name = path.basename(app, '.app');
35
+ const archive = path.join(api.workDir, `${name}.xcarchive`);
36
+ const applications = path.join(archive, 'Products', 'Applications');
37
+ fs.rmSync(archive, { recursive: true, force: true });
38
+ fs.mkdirSync(applications, { recursive: true });
39
+ // ditto keeps the signed bundle as it is: its links, modes and attributes.
40
+ const copied = spawnSync('ditto', [app, path.join(applications, path.basename(app))], { encoding: 'utf8' });
41
+ if (copied.error || copied.status !== 0) {
42
+ throw new Error(`crossbind: ditto could not copy ${app} into the archive: ${(copied.stderr || copied.error?.message || '').trim()}`);
43
+ }
44
+ fs.writeFileSync(path.join(archive, 'Info.plist'), plist({
45
+ ApplicationProperties: {
46
+ ApplicationPath: `Applications/${path.basename(app)}`,
47
+ Architectures: [ARCHES[arch] ?? arch],
48
+ CFBundleIdentifier: api.app.id,
49
+ CFBundleShortVersionString: api.app.appleVersion,
50
+ CFBundleVersion: String(api.app.buildNumber ?? api.app.appleVersion),
51
+ SigningIdentity: '-',
52
+ Team: team,
53
+ },
54
+ ArchiveVersion: 2,
55
+ CreationDate: new Date(),
56
+ Name: name,
57
+ SchemeName: name,
58
+ }));
59
+ return archive;
60
+ }
@@ -1,94 +0,0 @@
1
- import fs from 'node:fs';
2
- import { createSign } from 'node:crypto';
3
-
4
- const API = 'https://api.appstoreconnect.apple.com/v1';
5
- // A token's life, well under the 20 minutes App Store Connect takes at most, so a clock somewhat ahead of Apple's passes.
6
- const TOKEN_SECONDS = 600;
7
- // How often a call that does the same when made twice, as a GET or PATCH does, tries again on an answer App Store
8
- // Connect gives when busy or down, and how long it waits first where Apple's answer names no time.
9
- const RETRIES = 3;
10
- const RETRY_SECONDS = 10;
11
- const isTransient = (status) => status === 429 || status >= 500;
12
-
13
- const encode = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
14
- const sleep = (seconds) => new Promise((resolve) => { setTimeout(resolve, seconds * 1000); });
15
-
16
- // A token of an App Store Connect API key: a JWT signed ES256, with the signature's two numbers side by side, as JWTs
17
- // take them.
18
- export function appStoreToken({ key, keyId, issuer }, now = Date.now()) {
19
- const iat = Math.floor(now / 1000);
20
- const unsigned = `${encode({ alg: 'ES256', kid: keyId, typ: 'JWT' })}.${encode({ iss: issuer, iat, exp: iat + TOKEN_SECONDS, aud: 'appstoreconnect-v1' })}`;
21
- const signature = createSign('SHA256').update(unsigned).sign({ key: fs.readFileSync(key, 'utf8'), dsaEncoding: 'ieee-p1363' });
22
- return `${unsigned}.${signature.toString('base64url')}`;
23
- }
24
-
25
- // What Apple said of a refused call, with the reasons it gives field by field.
26
- const saidIn = (errors) => errors.flatMap(({ detail, title, meta }) => [
27
- detail ?? title, ...Object.values(meta?.associatedErrors ?? {}).flat().map((associated) => associated.detail ?? associated.title),
28
- ]).filter(Boolean).join(' ');
29
-
30
- function apiError(status, method, route, body, { keyId }) {
31
- const errors = body?.errors ?? [];
32
- const said = saidIn(errors);
33
- let text = `crossbind: App Store Connect answered ${method} ${route} with ${status}${said ? `: ${said}` : '.'}`;
34
- if (status === 401) {
35
- text = `crossbind: App Store Connect refused the API key ${keyId}${said ? ` (${said})` : ''}: CROSSBIND_APPLE_API_KEY is not that key's .p8, CROSSBIND_APPLE_API_KEY_ID or CROSSBIND_APPLE_API_ISSUER is not its own, it was revoked, or this machine's clock is off.`;
36
- } else if (status === 403 && errors.some(({ code }) => /AGREEMENT/i.test(code ?? ''))) {
37
- text += "\ncrossbind: the team's Account Holder accepts Apple's latest agreements in App Store Connect, under Business.";
38
- } else if (status === 403) {
39
- text += `\ncrossbind: the API key ${keyId} takes the App Manager or Admin role for that, which App Store Connect gives under Users and Access › Integrations.`;
40
- }
41
- return Object.assign(new Error(text), { status, errors });
42
- }
43
-
44
- // The answer to a request, which `init` makes anew at each try. One that leaves the same when made twice, as a GET does,
45
- // tries again when App Store Connect is busy or out of reach for a moment; one that would not, as a POST, tries again
46
- // only where App Store Connect said it was too busy to take it. `what` names the request, and `where` its host, where it
47
- // never reached that.
48
- async function answerTo(url, init, isRepeatable, { what, where = 'App Store Connect' }) {
49
- for (let attempt = 0; ; attempt += 1) {
50
- let response;
51
- try {
52
- response = await fetch(url, init());
53
- } catch (error) {
54
- if (!isRepeatable || attempt >= RETRIES) throw new Error(`crossbind: ${where} was out of reach for ${what}: ${error.cause?.message ?? error.message}`, { cause: error });
55
- await sleep(RETRY_SECONDS);
56
- continue;
57
- }
58
- const isRetried = isRepeatable ? isTransient(response.status) : response.status === 429;
59
- if (attempt >= RETRIES || !isRetried) return response;
60
- await sleep(Number(response.headers.get('retry-after')) || RETRY_SECONDS);
61
- }
62
- }
63
-
64
- // A caller of App Store Connect's API with an API key, which signs a token for each try, as a publish outlasts one.
65
- export function appStoreCaller(key) {
66
- return async (method, route, body) => {
67
- const path = route.split('?')[0];
68
- const response = await answerTo(`${API}${route}`, () => ({
69
- method,
70
- headers: { authorization: `Bearer ${appStoreToken(key)}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
71
- body: body === undefined ? undefined : JSON.stringify(body),
72
- }), method !== 'POST', { what: `${method} ${path}` });
73
- const text = await response.text();
74
- let json = null;
75
- try {
76
- json = text ? JSON.parse(text) : {};
77
- } catch {
78
- if (response.ok) throw new Error(`crossbind: App Store Connect answered ${method} ${path} with no JSON, as a proxy between might: ${text.slice(0, 200)}`);
79
- }
80
- if (response.ok) return json;
81
- throw apiError(response.status, method, path, json, key);
82
- };
83
- }
84
-
85
- // Uploads a file's bytes where App Store Connect reserved them, part by part as its upload operations say.
86
- export async function uploadParts(operations, bytes, file) {
87
- for (const {
88
- method, url, offset, length, requestHeaders = [],
89
- } of operations) {
90
- const headers = Object.fromEntries(requestHeaders.map(({ name, value }) => [name, value]));
91
- const response = await answerTo(url, () => ({ method, headers, body: bytes.subarray(offset, offset + length) }), true, { what: `the upload of ${file}`, where: "App Store Connect's storage" });
92
- if (!response.ok) throw new Error(`crossbind: App Store Connect's storage answered the upload of ${file} with ${response.status}.`);
93
- }
94
- }
@@ -1,62 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import {
4
- assertImage, languageFolders, readText, takenNames,
5
- } from '@crossbind/core-store-kit';
6
-
7
- // A project's App Store listing: a folder per locale, named as App Store Connect names its localizations (en-US, tr,
8
- // zh-Hans), with the texts' files fastlane's deliver names and a folder of screenshots per display type.
9
- const STORE = {
10
- name: 'App Store Connect', listing: 'an App Store listing', folder: path.join('store', 'app-store'), language: /^[a-z]{2,3}(-([A-Z]{2}|[A-Z][a-z]{3}))?$/, example: 'en-US',
11
- };
12
- export const APP_STORE_LISTING = STORE.folder;
13
- // A listing's texts by their files: those of the app's information, which change with its next version, and those of
14
- // the version itself, with the most characters App Store Connect takes of each; an optional one's empty file clears it.
15
- const TEXTS = {
16
- 'name.txt': { part: 'info', field: 'name', most: 30 },
17
- 'subtitle.txt': { part: 'info', field: 'subtitle', most: 30, canBeEmpty: true },
18
- 'privacy_url.txt': { part: 'info', field: 'privacyPolicyUrl', most: Infinity },
19
- 'description.txt': { part: 'version', field: 'description', most: 4000 },
20
- 'keywords.txt': { part: 'version', field: 'keywords', most: 100 },
21
- 'release_notes.txt': { part: 'version', field: 'whatsNew', most: 4000 },
22
- 'promotional_text.txt': { part: 'version', field: 'promotionalText', most: 170, canBeEmpty: true },
23
- 'support_url.txt': { part: 'version', field: 'supportUrl', most: Infinity },
24
- 'marketing_url.txt': { part: 'version', field: 'marketingUrl', most: Infinity, canBeEmpty: true },
25
- };
26
- // The display types of an iOS app's screenshots, as App Store Connect names them, a folder each, and the most it takes
27
- // of one type.
28
- const DISPLAY_TYPES = [
29
- 'APP_IPHONE_67', 'APP_IPHONE_65', 'APP_IPHONE_61', 'APP_IPHONE_58', 'APP_IPHONE_55', 'APP_IPHONE_47', 'APP_IPHONE_40', 'APP_IPHONE_35',
30
- 'APP_IPAD_PRO_3GEN_129', 'APP_IPAD_PRO_3GEN_11', 'APP_IPAD_PRO_129', 'APP_IPAD_105', 'APP_IPAD_97',
31
- ];
32
- const SCREENSHOTS_MOST = 10;
33
- const IMAGE_FILE = /\.(png|jpe?g)$/i;
34
-
35
- // The screenshots of each display type, in the order App Store Connect shows them.
36
- function readScreenshots(project, folder) {
37
- if (!fs.existsSync(folder)) return {};
38
- const types = takenNames(STORE, project, folder, (name, isDir) => isDir && DISPLAY_TYPES.includes(name));
39
- return Object.fromEntries(types.map((type) => {
40
- const files = takenNames(STORE, project, path.join(folder, type), (name, isDir) => !isDir && IMAGE_FILE.test(name));
41
- if (files.length > SCREENSHOTS_MOST) {
42
- throw new Error(`crossbind: ${path.relative(project, path.join(folder, type))} has ${files.length} screenshots, and App Store Connect takes ${SCREENSHOTS_MOST} at most.`);
43
- }
44
- const paths = files.map((file) => path.join(folder, type, file));
45
- paths.forEach((file) => assertImage(project, file));
46
- return [type, paths];
47
- }).filter(([, files]) => files.length > 0));
48
- }
49
-
50
- function readLocale(project, { language: locale, folder }) {
51
- const names = takenNames(STORE, project, folder, (name, isDir) => (isDir ? name === 'screenshots' : Object.hasOwn(TEXTS, name)));
52
- const texts = names.filter((name) => Object.hasOwn(TEXTS, name)).map((name) => ({ ...TEXTS[name], text: readText(STORE, project, path.join(folder, name), TEXTS[name]) }));
53
- const partOf = (which) => Object.fromEntries(texts.filter(({ part }) => part === which).map(({ field, text }) => [field, text]));
54
- return {
55
- locale, info: partOf('info'), version: partOf('version'), screenshots: readScreenshots(project, path.join(folder, 'screenshots')),
56
- };
57
- }
58
-
59
- // The project's App Store listing, a locale's texts of the app's information and of its version, and the version's
60
- // screenshots, each as its files hold them; none without the folder, and no locale whose folder holds none.
61
- export const readAppStoreListing = (project) => languageFolders(STORE, project).map((folder) => readLocale(project, folder))
62
- .filter(({ info, version, screenshots }) => [info, version, screenshots].some((part) => Object.keys(part).length > 0));
@@ -1,288 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { createHash } from 'node:crypto';
4
- import { uploadParts } from './appStoreApi.js';
5
- import { APP_STORE_CONNECT } from './appStoreConnect.js';
6
- import { APP_STORE_LISTING } from './appStoreListing.js';
7
-
8
- // How often a publish asks App Store Connect about a build it processes, and how long it waits for it at most; then
9
- // how often it asks whether a version is ready for review, and how many times.
10
- const BUILD_POLL_SECONDS = 30;
11
- const PROCESSING_MINUTES = 60;
12
- const SAY_EVERY_MINUTES = 5;
13
- const READY_POLL_SECONDS = 15;
14
- const READY_LOOKS = 10;
15
- const SCREENSHOT_POLL_SECONDS = 5;
16
- const SCREENSHOT_MINUTES = 10;
17
- // The states of a version App Store Connect takes another build and listing in.
18
- const EDITABLE = ['PREPARE_FOR_SUBMISSION', 'DEVELOPER_REJECTED', 'REJECTED', 'METADATA_REJECTED', 'INVALID_BINARY'];
19
- // The states of the app's information that changes with the version App Store Connect prepares.
20
- const EDITABLE_INFO = ['PREPARE_FOR_SUBMISSION', 'DEVELOPER_REJECTED', 'REJECTED'];
21
- // The states of a review submission App Review has, one at a time, or answered with issues to resolve.
22
- const IN_REVIEW = ['WAITING_FOR_REVIEW', 'IN_REVIEW', 'UNRESOLVED_ISSUES'];
23
- const PREPARED_SUBMISSION = 'crossbind: App Store Connect prepares a review submission of the app with items in it already, as one a publish stopped in leaves: submit or remove them there, then publish again.';
24
-
25
- const sleep = (seconds) => new Promise((resolve) => { setTimeout(resolve, seconds * 1000); });
26
- const query = (route, filters) => `${route}?${new URLSearchParams(filters)}`;
27
- const to = (type, id) => ({ data: { type, id } });
28
-
29
- // The id App Store Connect knows an app by.
30
- export async function appStoreApp(call, bundleId) {
31
- const { data } = await call('GET', query('/apps', { 'filter[bundleId]': bundleId }));
32
- const app = data.find(({ attributes }) => attributes.bundleId === bundleId);
33
- if (!app) {
34
- throw new Error(`crossbind: App Store Connect has no app ${bundleId}: create it at ${APP_STORE_CONNECT}, a new iOS app with ${bundleId} as its bundle ID. A form that lists no such bundle ID lists it once a publish without --submit has registered it with Apple.`);
35
- }
36
- return app.id;
37
- }
38
-
39
- // The app's version of a number on App Store Connect, or null without one; one App Store Connect takes no other build
40
- // in, as in review or out, stops the publish.
41
- async function versionOf(call, appId, versionString) {
42
- const { data: [version = null] } = await call('GET', query(`/apps/${appId}/appStoreVersions`, { 'filter[platform]': 'IOS', 'filter[versionString]': versionString }));
43
- const state = version?.attributes.appVersionState;
44
- if (state === 'READY_FOR_REVIEW') throw new Error(PREPARED_SUBMISSION);
45
- if (version && !EDITABLE.includes(state)) {
46
- throw new Error(`crossbind: App Store Connect has ${versionString} as ${state} already, which takes no other build: raise the version in package.json, or, while App Review has it, cancel its review in App Store Connect.`);
47
- }
48
- return version;
49
- }
50
-
51
- // The review submission App Store Connect prepares for the app, with the items in it it has not removed, or null.
52
- async function preparedSubmission(call, appId) {
53
- const { data: [submission = null], included = [] } = await call('GET', query(`/apps/${appId}/reviewSubmissions`, { 'filter[platform]': 'IOS', 'filter[state]': 'READY_FOR_REVIEW', include: 'items' }));
54
- if (!submission) return null;
55
- const items = (submission.relationships?.items?.data ?? [])
56
- .map(({ id }) => included.find((item) => item.type === 'reviewSubmissionItems' && item.id === id))
57
- .filter((item) => item?.attributes?.state !== 'REMOVED');
58
- return { submission, items };
59
- }
60
-
61
- // Stops a publish, before its build, that App Store Connect would not review: one of a version it takes no other build
62
- // in, while App Review has another submission of the app, or where it prepares one with items in it.
63
- export async function assertReviewable(call, appId, versionString) {
64
- await versionOf(call, appId, versionString);
65
- const { data: [submission] } = await call('GET', query(`/apps/${appId}/reviewSubmissions`, { 'filter[platform]': 'IOS', 'filter[state]': IN_REVIEW.join(',') }));
66
- if (submission?.attributes.state === 'UNRESOLVED_ISSUES') {
67
- throw new Error('crossbind: App Review answered the app\'s last submission with issues, which App Store Connect resolves: publish without --submit, pick the new build there and resubmit, or cancel that submission first.');
68
- }
69
- if (submission) {
70
- throw new Error(`crossbind: App Review has the app's submission as ${submission.attributes.state}, and takes one at a time: let it finish, or cancel it in App Store Connect.`);
71
- }
72
- if ((await preparedSubmission(call, appId))?.items.length > 0) throw new Error(PREPARED_SUBMISSION);
73
- }
74
-
75
- // The newest build App Store Connect has of the version, or of its number where the build has one already.
76
- const newestQuery = (appId, versionString, buildNumber) => query('/builds', {
77
- 'filter[app]': appId,
78
- 'filter[preReleaseVersion.version]': versionString,
79
- 'filter[preReleaseVersion.platform]': 'IOS',
80
- ...(buildNumber === null ? {} : { 'filter[version]': String(buildNumber) }),
81
- sort: '-uploadedDate',
82
- limit: '1',
83
- });
84
-
85
- // The newest build App Store Connect has of the version, which tells the upload's own from those before it.
86
- export async function newestBuild(call, appId, versionString) {
87
- const { data: [build] } = await call('GET', newestQuery(appId, versionString, null));
88
- return build?.id ?? null;
89
- }
90
-
91
- // The upload's build once App Store Connect has processed it: the newest of the version, after the one it had before.
92
- async function processedBuild(call, { appId, versionString, before, buildNumber }) {
93
- console.log('crossbind: waiting for App Store Connect to process the build, usually 5 to 30 minutes.');
94
- for (let waited = 0; ; waited += BUILD_POLL_SECONDS) {
95
- const { data: [build] } = await call('GET', newestQuery(appId, versionString, buildNumber));
96
- const state = build && build.id !== before ? build.attributes.processingState : null;
97
- if (state === 'VALID') return build;
98
- if (state === 'FAILED' || state === 'INVALID') {
99
- throw new Error(`crossbind: App Store Connect could not process build ${build.attributes.version} of ${versionString}, which it marked ${state}; Apple mails why.`);
100
- }
101
- if (waited >= PROCESSING_MINUTES * 60) {
102
- throw new Error(`crossbind: App Store Connect has not processed the build in ${PROCESSING_MINUTES} minutes, so it went to no review: once it has, pick it for ${versionString} in App Store Connect and submit it there.`);
103
- }
104
- if (waited > 0 && waited % (SAY_EVERY_MINUTES * 60) === 0) console.log(`crossbind: App Store Connect is still processing the build, ${waited / 60} minutes on.`);
105
- await sleep(BUILD_POLL_SECONDS);
106
- }
107
- }
108
-
109
- // The app's version to submit: its own, the one App Store Connect prepares under another number, renamed, or a new one.
110
- async function openVersion(call, appId, versionString) {
111
- const own = await versionOf(call, appId, versionString);
112
- if (own) return own;
113
- const { data: [prepared] } = await call('GET', query(`/apps/${appId}/appStoreVersions`, { 'filter[platform]': 'IOS', 'filter[appVersionState]': EDITABLE.join(',') }));
114
- if (prepared) {
115
- console.log(`crossbind: App Store Connect prepares ${prepared.attributes.versionString}, which becomes ${versionString}.`);
116
- return (await call('PATCH', `/appStoreVersions/${prepared.id}`, { data: { type: 'appStoreVersions', id: prepared.id, attributes: { versionString } } })).data;
117
- }
118
- const version = { type: 'appStoreVersions', attributes: { platform: 'IOS', versionString }, relationships: { app: to('apps', appId) } };
119
- return (await call('POST', '/appStoreVersions', { data: version })).data;
120
- }
121
-
122
- // The app's information that changes with the version App Store Connect prepares.
123
- async function openInfo(call, appId) {
124
- const { data } = await call('GET', `/apps/${appId}/appInfos`);
125
- const info = data.find(({ attributes }) => EDITABLE_INFO.includes(attributes.state));
126
- if (!info) throw new Error(`crossbind: App Store Connect takes the app's name, subtitle and privacy policy URL in none of its versions now: remove name.txt, subtitle.txt and privacy_url.txt from ${APP_STORE_LISTING} for this one.`);
127
- return info;
128
- }
129
-
130
- // Gives App Store Connect a locale's texts of one kind where they differ from its own, in a new localization where it
131
- // has none of the locale and one is wanted, and gives the localization's id and whether it changed it. An empty text
132
- // clears Apple's, which takes none for it.
133
- async function localize(call, { type, shown, owner }, locale, texts, isWanted = Object.keys(texts).length > 0) {
134
- const current = shown.find(({ attributes }) => attributes.locale === locale);
135
- if (!current) {
136
- if (!isWanted) return { id: null, isChanged: false };
137
- const given = Object.fromEntries(Object.entries(texts).filter(([, text]) => text !== ''));
138
- const { data } = await call('POST', `/${type}`, { data: { type, attributes: { locale, ...given }, relationships: owner } });
139
- return { id: data.id, isChanged: true };
140
- }
141
- const changed = Object.entries(texts).filter(([field, text]) => (current.attributes[field] ?? '') !== text);
142
- if (changed.length > 0) {
143
- const attributes = Object.fromEntries(changed.map(([field, text]) => [field, text === '' ? null : text]));
144
- await call('PATCH', `/${type}/${current.id}`, { data: { type, id: current.id, attributes } });
145
- }
146
- return { id: current.id, isChanged: changed.length > 0 };
147
- }
148
-
149
- const md5 = (bytes) => createHash('md5').update(bytes).digest('hex');
150
-
151
- // Uploads a screenshot into its set as App Store Connect takes a file: reserved, its bytes uploaded where the reservation
152
- // says, then committed with its checksum, naming the file where App Store Connect refuses it. Gives its id.
153
- async function uploadScreenshot(call, setId, file, bytes) {
154
- try {
155
- const screenshot = { type: 'appScreenshots', attributes: { fileName: path.basename(file), fileSize: bytes.length }, relationships: { appScreenshotSet: to('appScreenshotSets', setId) } };
156
- const { data: reserved } = await call('POST', '/appScreenshots', { data: screenshot });
157
- await uploadParts(reserved.attributes.uploadOperations, bytes, file);
158
- await call('PATCH', `/appScreenshots/${reserved.id}`, { data: { type: 'appScreenshots', id: reserved.id, attributes: { uploaded: true, sourceFileChecksum: md5(bytes) } } });
159
- return reserved.id;
160
- } catch (error) {
161
- if (error.message.includes(file)) throw error;
162
- throw Object.assign(new Error(`${error.message}\ncrossbind: it answered so for ${file}.`), { status: error.status, errors: error.errors });
163
- }
164
- }
165
-
166
- // Whether App Store Connect shows a set's screenshots as the files are, processed and in their order.
167
- const isShownAsFiles = (shown, bytes) => shown.length === bytes.length && shown.every(({ attributes }, index) => attributes.assetDeliveryState?.state === 'COMPLETE'
168
- && attributes.sourceFileChecksum?.toLowerCase() === md5(bytes[index]));
169
-
170
- // Puts a locale's screenshots of each display type into its localization where App Store Connect shows others, in
171
- // another order, or unprocessed, and gives the sets it changed with their new screenshots in order. A screenshot gone
172
- // already, as one a retried call removed, is gone.
173
- async function updateScreenshots(call, localizationId, screenshots) {
174
- if (Object.keys(screenshots).length === 0) return [];
175
- const { data: sets, included = [] } = await call('GET', query(`/appStoreVersionLocalizations/${localizationId}/appScreenshotSets`, { include: 'appScreenshots', 'limit[appScreenshots]': '50' }));
176
- const changed = [];
177
- for (const [displayType, files] of Object.entries(screenshots)) {
178
- const bytes = files.map((file) => fs.readFileSync(file));
179
- const set = sets.find(({ attributes }) => attributes.screenshotDisplayType === displayType) ?? (await call('POST', '/appScreenshotSets', {
180
- data: { type: 'appScreenshotSets', attributes: { screenshotDisplayType: displayType }, relationships: { appStoreVersionLocalization: to('appStoreVersionLocalizations', localizationId) } },
181
- })).data;
182
- const shown = (set.relationships?.appScreenshots?.data ?? []).map(({ id }) => included.find((one) => one.type === 'appScreenshots' && one.id === id)).filter(Boolean);
183
- if (isShownAsFiles(shown, bytes)) continue;
184
- for (const old of shown) {
185
- await call('DELETE', `/appScreenshots/${old.id}`).catch((error) => {
186
- if (error.status !== 404) throw error;
187
- });
188
- }
189
- const uploaded = [];
190
- for (const [index, file] of files.entries()) uploaded.push({ id: await uploadScreenshot(call, set.id, file, bytes[index]), file });
191
- changed.push({ setId: set.id, uploaded });
192
- }
193
- return changed;
194
- }
195
-
196
- // Waits for App Store Connect to process the screenshots uploaded, a set at a time, naming one it refuses.
197
- async function processedScreenshots(call, sets, versionString) {
198
- for (let waited = 0; ; waited += SCREENSHOT_POLL_SECONDS) {
199
- let isProcessed = true;
200
- for (const { setId, uploaded } of sets) {
201
- const { data: shown } = await call('GET', query(`/appScreenshotSets/${setId}/appScreenshots`, { limit: '200' }));
202
- for (const { id, file } of uploaded) {
203
- const delivery = shown.find((one) => one.id === id)?.attributes.assetDeliveryState;
204
- if (delivery?.state === 'FAILED') {
205
- const said = (delivery.errors ?? []).map(({ description, code }) => description ?? code).join(' ');
206
- throw new Error(`crossbind: App Store Connect refused ${file}${said ? `: ${said}` : '.'}`);
207
- }
208
- if (delivery?.state !== 'COMPLETE') isProcessed = false;
209
- }
210
- }
211
- if (isProcessed) return;
212
- if (waited >= SCREENSHOT_MINUTES * 60) {
213
- throw new Error(`crossbind: App Store Connect has not processed the screenshots in ${SCREENSHOT_MINUTES} minutes, so the version went to no review: once it has, pick the build for ${versionString} in App Store Connect and submit it there.`);
214
- }
215
- await sleep(SCREENSHOT_POLL_SECONDS);
216
- }
217
- }
218
-
219
- // Puts the project's listing into the version and the app's information that changes with it, and gives the locales it
220
- // changed. App Store Connect makes a locale's information of its name.
221
- async function updateListing(call, appId, version, listings) {
222
- if (listings.length === 0) return [];
223
- const { data: versionTexts } = await call('GET', query(`/appStoreVersions/${version.id}/appStoreVersionLocalizations`, { limit: '200' }));
224
- const info = listings.some((listing) => Object.keys(listing.info).length > 0) ? await openInfo(call, appId) : null;
225
- const infoTexts = info ? (await call('GET', query(`/appInfos/${info.id}/appInfoLocalizations`, { limit: '200' }))).data : [];
226
- const lacking = listings.find((listing) => Object.keys(listing.info).length > 0 && listing.info.name === undefined
227
- && !infoTexts.some(({ attributes }) => attributes.locale === listing.locale));
228
- if (lacking) throw new Error(`crossbind: App Store Connect has no ${lacking.locale} information of the app yet, which it makes of its name: add name.txt to ${path.join(APP_STORE_LISTING, lacking.locale)}.`);
229
- const changed = [];
230
- const sets = [];
231
- for (const listing of listings) {
232
- const isWanted = Object.keys(listing.version).length > 0 || Object.keys(listing.screenshots).length > 0;
233
- const versionText = await localize(call, { type: 'appStoreVersionLocalizations', shown: versionTexts, owner: { appStoreVersion: to('appStoreVersions', version.id) } }, listing.locale, listing.version, isWanted);
234
- const infoText = info ? await localize(call, { type: 'appInfoLocalizations', shown: infoTexts, owner: { appInfo: to('appInfos', info.id) } }, listing.locale, listing.info) : { isChanged: false };
235
- const shotSets = await updateScreenshots(call, versionText.id, listing.screenshots);
236
- sets.push(...shotSets);
237
- if (versionText.isChanged || infoText.isChanged || shotSets.length > 0) changed.push(listing.locale);
238
- }
239
- await processedScreenshots(call, sets, version.attributes.versionString);
240
- for (const { setId, uploaded } of sets) {
241
- await call('PATCH', `/appScreenshotSets/${setId}/relationships/appScreenshots`, { data: uploaded.map(({ id }) => ({ type: 'appScreenshots', id })) });
242
- }
243
- return changed;
244
- }
245
-
246
- // Releases the version in phases over 7 days once App Review approves it, unless it does already.
247
- async function phaseRelease(call, versionId) {
248
- const { data } = await call('GET', `/appStoreVersions/${versionId}/appStoreVersionPhasedRelease`).catch((error) => {
249
- if (error.status === 404) return { data: null };
250
- throw error;
251
- });
252
- if (data) return;
253
- const phased = { type: 'appStoreVersionPhasedReleases', attributes: { phasedReleaseState: 'INACTIVE' }, relationships: { appStoreVersion: to('appStoreVersions', versionId) } };
254
- await call('POST', '/appStoreVersionPhasedReleases', { data: phased });
255
- }
256
-
257
- // Hands the version to App Review in the app's submission App Store Connect prepares, or a new one, once the version
258
- // is ready for review; one prepared with items in it stops the publish, which knows none of them.
259
- async function submitForReview(call, appId, versionId) {
260
- const prepared = await preparedSubmission(call, appId);
261
- if (prepared?.items.length > 0) throw new Error(PREPARED_SUBMISSION);
262
- const submission = prepared?.submission ?? (await call('POST', '/reviewSubmissions', { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: to('apps', appId) } } })).data;
263
- const item = { type: 'reviewSubmissionItems', relationships: { reviewSubmission: to('reviewSubmissions', submission.id), appStoreVersion: to('appStoreVersions', versionId) } };
264
- await call('POST', '/reviewSubmissionItems', { data: item });
265
- for (let look = 1; ; look += 1) {
266
- const { data: version } = await call('GET', `/appStoreVersions/${versionId}`);
267
- if (version.attributes.appVersionState === 'READY_FOR_REVIEW' || look === READY_LOOKS) break;
268
- await sleep(READY_POLL_SECONDS);
269
- }
270
- await call('PATCH', `/reviewSubmissions/${submission.id}`, { data: { type: 'reviewSubmissions', id: submission.id, attributes: { submitted: true } } });
271
- }
272
-
273
- // Hands the upload's build to App Review as the app's version, with the project's listing, once App Store Connect has
274
- // processed it, to go out in phases over 7 days once released where isPhased says so. Gives the build's number and the
275
- // locales whose listing changed.
276
- export async function submitRelease(call, {
277
- appId, versionString, before, buildNumber = null, listings, isPhased,
278
- }) {
279
- const version = await openVersion(call, appId, versionString);
280
- const listed = await updateListing(call, appId, version, listings);
281
- if (isPhased) await phaseRelease(call, version.id);
282
- const build = await processedBuild(call, {
283
- appId, versionString, before, buildNumber,
284
- });
285
- await call('PATCH', `/appStoreVersions/${version.id}/relationships/build`, to('builds', build.id));
286
- await submitForReview(call, appId, version.id);
287
- return { build: build.attributes.version, listed };
288
- }