@yoonion/mimi-seed-mcp 0.23.1 → 0.23.2

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.
@@ -0,0 +1,20 @@
1
+ import { z } from 'zod';
2
+ import { apiGet } from './client.js';
3
+ export const appStorePagination = z.object({
4
+ links: z.object({ next: z.string().nullish() }).nullish(),
5
+ meta: z.object({ paging: z.object({
6
+ total: z.number().int().nonnegative().optional(),
7
+ nextCursor: z.string().nullish(),
8
+ }).optional() }).optional(),
9
+ });
10
+ export function pageIsIncomplete(page, count) {
11
+ return Boolean(page.links?.next || page.meta?.paging?.nextCursor) || (page.meta?.paging?.total ?? 0) > count;
12
+ }
13
+ export async function getAppStoreResponse(schema, path, params) {
14
+ const response = schema.safeParse(await apiGet(path, params));
15
+ if (!response.success) {
16
+ const field = response.error.issues[0]?.path.join('.') || '응답 본문';
17
+ throw new Error(`App Store Connect 응답 형식 오류 (${field}).`);
18
+ }
19
+ return response.data;
20
+ }
@@ -0,0 +1,49 @@
1
+ import { z } from 'zod';
2
+ declare const platformSchema: z.ZodEnum<{
3
+ IOS: "IOS";
4
+ MAC_OS: "MAC_OS";
5
+ TV_OS: "TV_OS";
6
+ VISION_OS: "VISION_OS";
7
+ }>;
8
+ export type AppStorePlatform = z.infer<typeof platformSchema>;
9
+ declare const processingState: z.ZodEnum<{
10
+ PROCESSING: "PROCESSING";
11
+ FAILED: "FAILED";
12
+ INVALID: "INVALID";
13
+ VALID: "VALID";
14
+ }>;
15
+ export type AppStoreBuildReadiness = {
16
+ status: 'missing';
17
+ } | {
18
+ status: 'unknown';
19
+ detail: string;
20
+ } | {
21
+ status: 'ready' | 'not-ready';
22
+ id: string;
23
+ processingState: z.infer<typeof processingState>;
24
+ };
25
+ export interface AppStoreVersionCandidate {
26
+ id: string;
27
+ versionString?: string;
28
+ state: string;
29
+ platform: AppStorePlatform;
30
+ linkedBuildId?: string;
31
+ build?: AppStoreBuildReadiness;
32
+ }
33
+ type VersionSelection = {
34
+ status: 'selected';
35
+ version: AppStoreVersionCandidate;
36
+ } | {
37
+ status: 'missing';
38
+ } | {
39
+ status: 'ambiguous';
40
+ } | {
41
+ status: 'incomplete';
42
+ };
43
+ export declare function selectEditableAppStoreVersion(appId: string, filters?: {
44
+ versionId?: string;
45
+ versionString?: string;
46
+ }): Promise<VersionSelection>;
47
+ /** Resolve the selected version's build without an API request when included data is complete. */
48
+ export declare function resolveAppStoreVersionBuild(version: AppStoreVersionCandidate): Promise<AppStoreBuildReadiness>;
49
+ export {};
@@ -0,0 +1,107 @@
1
+ import { z } from 'zod';
2
+ import { encodePathSegment } from '../lib/url-path.js';
3
+ import { isNotFound } from './http.js';
4
+ import { appStorePagination, getAppStoreResponse, pageIsIncomplete } from './read-response.js';
5
+ const editableStates = ['PREPARE_FOR_SUBMISSION', 'DEVELOPER_REJECTED', 'METADATA_REJECTED', 'REJECTED'];
6
+ const versionPage = appStorePagination.extend({
7
+ data: z.array(z.object({
8
+ id: z.string().min(1),
9
+ type: z.literal('appStoreVersions').optional(),
10
+ attributes: z.object({
11
+ versionString: z.string().nullish(),
12
+ appVersionState: z.string().nullish(),
13
+ appStoreState: z.string().nullish(),
14
+ platform: z.string().nullish(),
15
+ }).nullish(),
16
+ relationships: z.object({ build: z.unknown().optional() }).nullish(),
17
+ })),
18
+ included: z.array(z.unknown()).nullish(),
19
+ });
20
+ const platformSchema = z.enum(['IOS', 'MAC_OS', 'TV_OS', 'VISION_OS']);
21
+ const buildReference = z.object({ id: z.string().min(1), type: z.literal('builds') });
22
+ const buildRelationship = z.object({ data: buildReference.nullable() });
23
+ const processingState = z.enum(['PROCESSING', 'FAILED', 'INVALID', 'VALID']);
24
+ const buildResource = buildReference.extend({
25
+ attributes: z.object({ processingState }).nullish(),
26
+ });
27
+ const buildResponse = z.object({ data: buildResource.nullable() });
28
+ function buildReadiness(build) {
29
+ const state = build.attributes?.processingState;
30
+ if (!state)
31
+ return undefined;
32
+ return { status: state === 'VALID' ? 'ready' : 'not-ready', id: build.id, processingState: state };
33
+ }
34
+ export async function selectEditableAppStoreVersion(appId, filters = {}) {
35
+ const { versionId, versionString } = filters;
36
+ const page = await getAppStoreResponse(versionPage, `/apps/${encodePathSegment(appId)}/appStoreVersions`, {
37
+ 'filter[appVersionState]': editableStates.join(','),
38
+ ...(versionId ? { 'filter[id]': versionId } : {}),
39
+ ...(versionString ? { 'filter[versionString]': versionString } : {}),
40
+ 'fields[appStoreVersions]': 'versionString,platform,appVersionState,build',
41
+ 'fields[builds]': 'processingState',
42
+ include: 'build',
43
+ limit: versionId ? '1' : '5',
44
+ });
45
+ const candidates = [];
46
+ let incomplete = pageIsIncomplete(page, page.data.length);
47
+ for (const row of page.data) {
48
+ const version = row.attributes?.versionString ?? undefined;
49
+ const state = row.attributes?.appVersionState ?? row.attributes?.appStoreState ?? undefined;
50
+ if ((versionId && versionId !== row.id) || (versionString && version && versionString !== version)
51
+ || (state && !editableStates.includes(state)))
52
+ continue;
53
+ const platform = platformSchema.safeParse(row.attributes?.platform);
54
+ if (!state || !platform.success || (versionString && !version)) {
55
+ incomplete = true;
56
+ continue;
57
+ }
58
+ const linkage = buildRelationship.safeParse(row.relationships?.build);
59
+ const linkedBuildId = linkage.success ? linkage.data.data?.id : undefined;
60
+ const included = linkedBuildId ? (page.included ?? []).filter((item) => {
61
+ const ref = buildReference.safeParse(item);
62
+ return ref.success && ref.data.id === linkedBuildId;
63
+ }) : [];
64
+ const embedded = included.length === 1 ? buildResource.safeParse(included[0]) : undefined;
65
+ candidates.push({
66
+ id: row.id,
67
+ versionString: version,
68
+ state,
69
+ platform: platform.data,
70
+ linkedBuildId,
71
+ build: linkage.success && linkage.data.data === null
72
+ ? { status: 'missing' }
73
+ : embedded?.success ? buildReadiness(embedded.data) : undefined,
74
+ });
75
+ }
76
+ if (candidates.length > 1)
77
+ return { status: 'ambiguous' };
78
+ if (incomplete)
79
+ return { status: 'incomplete' };
80
+ const version = candidates[0];
81
+ return version ? { status: 'selected', version } : { status: 'missing' };
82
+ }
83
+ /** Resolve the selected version's build without an API request when included data is complete. */
84
+ export async function resolveAppStoreVersionBuild(version) {
85
+ if (version.build)
86
+ return version.build;
87
+ const missing = version.linkedBuildId
88
+ ? { status: 'unknown', detail: '버전 목록의 빌드 연결과 상세 조회 결과가 일치하지 않습니다.' }
89
+ : { status: 'missing' };
90
+ try {
91
+ const { data } = await getAppStoreResponse(buildResponse, `/appStoreVersions/${encodePathSegment(version.id)}/build`, {
92
+ 'fields[builds]': 'processingState',
93
+ });
94
+ if (!data)
95
+ return missing;
96
+ if (version.linkedBuildId && data.id !== version.linkedBuildId) {
97
+ return { status: 'unknown', detail: '버전 목록과 상세 조회에서 서로 다른 빌드 ID가 반환되었습니다.' };
98
+ }
99
+ return buildReadiness(data)
100
+ ?? { status: 'unknown', detail: '연결된 빌드의 처리 상태가 응답에 없습니다.' };
101
+ }
102
+ catch (error) {
103
+ if (isNotFound(error))
104
+ return missing;
105
+ return { status: 'unknown', detail: error instanceof Error ? error.message : String(error) };
106
+ }
107
+ }
@@ -34,7 +34,7 @@ export declare function submitVersionForReview(versionId: string): Promise<{
34
34
  reusedSubmission: boolean;
35
35
  itemAttached: boolean;
36
36
  recoveredFromStaleSubmission: boolean;
37
- state: any;
37
+ state: string;
38
38
  }>;
39
39
  export declare function addProductToReviewSubmission(args: {
40
40
  internalId: string;
@@ -3,10 +3,6 @@
3
3
  import { apiGet, apiPatch, apiPost } from './client.js';
4
4
  import { getVersionAppAndPlatform, getVersionLocalizations } from './versions.js';
5
5
  import { encodePathSegment } from '../lib/url-path.js';
6
- // ─── 심사 제출 (Submit for Review) ───
7
- // 2024년 1월부터 옛 /appStoreVersionSubmissions가 deprecated 됐고,
8
- // 새 모델은 /reviewSubmissions + /reviewSubmissionItems 2단계 + PATCH submitted=true.
9
- // 참고: https://developer.apple.com/documentation/appstoreconnectapi/submit-an-app-for-review
10
6
  async function findOpenReviewSubmission(appId, platform, versionId) {
11
7
  // ASC API는 filter[state]=CREATED를 더 이상 허용하지 않음 (READY_FOR_REVIEW, WAITING_FOR_REVIEW 등만 허용).
12
8
  // CREATED 상태 submission은 별도로 조회 불가 → 이미 진행 중인 submission만 재사용.
@@ -20,7 +16,10 @@ async function findOpenReviewSubmission(appId, platform, versionId) {
20
16
  if (data?.links?.next) {
21
17
  throw new Error('reviewSubmission 목록이 여러 페이지야. 기존 버전 묶음을 모두 확인할 수 없어 제출을 중단했어.');
22
18
  }
23
- const submissions = (data?.data ?? []);
19
+ if (!Array.isArray(data?.data)) {
20
+ throw new Error('reviewSubmission 목록 응답에 data 배열이 없어. 제출을 중단했어.');
21
+ }
22
+ const submissions = data.data;
24
23
  let reusable = null;
25
24
  let staleSubmission = null;
26
25
  let hasUnrelatedItems = false;
@@ -64,7 +63,7 @@ async function getReviewSubmissionItems(submissionId) {
64
63
  if (data?.links?.next) {
65
64
  throw new Error(`reviewSubmission ${submissionId} 항목이 여러 페이지야. 전체 항목을 확인할 수 없어 제출을 중단했어.`);
66
65
  }
67
- return { items: (data?.data ?? []), included: data?.included ?? [] };
66
+ return { items: data.data, included: data.included ?? [] };
68
67
  }
69
68
  /**
70
69
  * submit_for_review dry-run 프리뷰 — 비가역 제출 직전 사용자 확인용.
@@ -307,7 +306,10 @@ async function findDraftReviewSubmission(appId, platform) {
307
306
  if (data?.links?.next) {
308
307
  throw new Error('심사 초안 목록이 여러 페이지야. 안전한 빈 초안을 확인할 수 없어 제출을 중단했어.');
309
308
  }
310
- const drafts = (data?.data ?? []);
309
+ if (!Array.isArray(data?.data)) {
310
+ throw new Error('심사 초안 목록 응답에 data 배열이 없어. 제출을 중단했어.');
311
+ }
312
+ const drafts = data.data;
311
313
  for (const draft of drafts) {
312
314
  const { items } = await getReviewSubmissionItems(draft.id);
313
315
  if (items.length === 0 && !draft.relationships?.appStoreVersionForReview?.data?.id)
@@ -323,7 +325,7 @@ export async function listReviewSubmissions(args) {
323
325
  'filter[platform]': platform,
324
326
  'limit': String(limit),
325
327
  });
326
- const submissions = (data?.data ?? []);
328
+ const submissions = data?.data ?? [];
327
329
  const result = [];
328
330
  for (const sub of submissions) {
329
331
  // 버전만 include 하면 IAP·구독·구독그룹 항목이 전부 "?" 로 남아, 정작 중요한
@@ -412,11 +414,11 @@ async function releaseVersionFromStaleSubmissions(appId, platform, versionId) {
412
414
  'filter[state]': 'UNRESOLVED_ISSUES',
413
415
  'limit': '5',
414
416
  }).catch(() => null);
415
- const stale = (data?.data ?? []);
417
+ const stale = data?.data ?? [];
416
418
  let released = 0;
417
419
  for (const sub of stale) {
418
420
  const items = await apiGet(`/reviewSubmissions/${encodePathSegment(sub.id)}/items`, { limit: '50' }).catch(() => null);
419
- const rows = (items?.data ?? []);
421
+ const rows = items?.data ?? [];
420
422
  for (const row of rows) {
421
423
  if (row?.relationships?.appStoreVersion?.data?.id !== versionId)
422
424
  continue;
@@ -9,6 +9,7 @@ export declare function listScreenshotSets(localizationId: string): Promise<{
9
9
  imageAsset: unknown;
10
10
  }[];
11
11
  }[]>;
12
+ export declare function checkLegacyScreenshotReadiness(localizationId: string): Promise<'ready' | 'missing' | 'not-ready' | 'unknown'>;
12
13
  export declare function uploadScreenshot(localizationId: string, displayType: string, filePath: string): Promise<{
13
14
  id: string;
14
15
  fileName: string;
@@ -1,4 +1,6 @@
1
1
  import { getAuthHeaders } from './auth.js';
2
+ import { apiGet } from './client.js';
3
+ import { z } from 'zod';
2
4
  import fs from 'node:fs';
3
5
  import path from 'node:path';
4
6
  import crypto from 'node:crypto';
@@ -42,11 +44,15 @@ async function req(pathOrUrl, init = {}) {
42
44
  const text = await res.text();
43
45
  return (text ? JSON.parse(text) : null);
44
46
  }
47
+ function fetchScreenshotSets(localizationId, includeImageMetadata) {
48
+ return apiGet(`/appStoreVersionLocalizations/${encodePathSegment(localizationId)}/appScreenshotSets`, {
49
+ include: 'appScreenshots',
50
+ 'fields[appScreenshotSets]': 'screenshotDisplayType,appScreenshots',
51
+ 'fields[appScreenshots]': includeImageMetadata ? 'fileName,fileSize,assetDeliveryState,imageAsset' : 'assetDeliveryState',
52
+ });
53
+ }
45
54
  export async function listScreenshotSets(localizationId) {
46
- const data = await req(`/appStoreVersionLocalizations/${encodePathSegment(localizationId)}/appScreenshotSets` +
47
- `?include=appScreenshots` +
48
- `&fields[appScreenshotSets]=screenshotDisplayType,appScreenshots` +
49
- `&fields[appScreenshots]=fileName,fileSize,assetDeliveryState,imageAsset`);
55
+ const data = await fetchScreenshotSets(localizationId, true);
50
56
  const included = data?.included ?? [];
51
57
  return (data?.data ?? []).map((s) => ({
52
58
  id: s.id,
@@ -63,6 +69,56 @@ export async function listScreenshotSets(localizationId) {
63
69
  }),
64
70
  }));
65
71
  }
72
+ const pagingFields = {
73
+ links: z.object({ next: z.string().nullish() }).nullish(),
74
+ meta: z.object({ paging: z.object({
75
+ total: z.number().int().nonnegative().optional(),
76
+ nextCursor: z.string().nullish(),
77
+ }).optional() }).nullish(),
78
+ };
79
+ const legacyScreenshotRef = z.object({ type: z.literal('appScreenshots'), id: z.string().min(1) });
80
+ const legacyScreenshotSets = z.object({
81
+ ...pagingFields,
82
+ data: z.array(z.object({
83
+ relationships: z.object({
84
+ appScreenshots: z.object({ ...pagingFields, data: z.array(legacyScreenshotRef) }).nullish(),
85
+ }).nullish(),
86
+ })),
87
+ included: z.array(legacyScreenshotRef.extend({
88
+ attributes: z.object({
89
+ assetDeliveryState: z.object({ state: z.string().nullish() }).nullish(),
90
+ }).nullish(),
91
+ })).nullish(),
92
+ });
93
+ function hasMoreScreenshots(page, count) {
94
+ return Boolean(page.links?.next || page.meta?.paging?.nextCursor) || (page.meta?.paging?.total ?? 0) > count;
95
+ }
96
+ export async function checkLegacyScreenshotReadiness(localizationId) {
97
+ const result = legacyScreenshotSets.safeParse(await fetchScreenshotSets(localizationId, false));
98
+ if (!result.success)
99
+ return 'unknown';
100
+ const { data, included } = result.data;
101
+ const states = new Map((included ?? []).map((asset) => [asset.id, asset.attributes?.assetDeliveryState?.state]));
102
+ let hasScreenshot = false;
103
+ let incomplete = hasMoreScreenshots(result.data, data.length);
104
+ for (const set of data) {
105
+ const relationship = set.relationships?.appScreenshots;
106
+ if (!relationship) {
107
+ incomplete = true;
108
+ continue;
109
+ }
110
+ incomplete ||= hasMoreScreenshots(relationship, relationship.data.length);
111
+ for (const screenshot of relationship.data) {
112
+ const state = states.get(screenshot.id);
113
+ if (state === 'COMPLETE')
114
+ return 'ready';
115
+ hasScreenshot = true;
116
+ if (state !== 'AWAITING_UPLOAD' && state !== 'UPLOAD_COMPLETE' && state !== 'FAILED')
117
+ incomplete = true;
118
+ }
119
+ }
120
+ return incomplete ? 'unknown' : hasScreenshot ? 'not-ready' : 'missing';
121
+ }
66
122
  // ─── 셋 확보 (존재하면 재사용, 없으면 생성) ───
67
123
  async function ensureScreenshotSet(localizationId, displayType) {
68
124
  const existing = await listScreenshotSets(localizationId);
@@ -0,0 +1,11 @@
1
+ export interface UploadOperation {
2
+ method: string;
3
+ url: string;
4
+ length: number;
5
+ offset: number;
6
+ requestHeaders: Array<{
7
+ name: string;
8
+ value: string;
9
+ }>;
10
+ }
11
+ export declare function uploadFileParts(absPath: string, ops: readonly UploadOperation[], redirect?: RequestRedirect): Promise<void>;
@@ -0,0 +1,29 @@
1
+ import fs from 'node:fs';
2
+ import { fetchWithTimeout, HTTP_TRANSFER_TIMEOUT_MS } from '../lib/http.js';
3
+ export async function uploadFileParts(absPath, ops, redirect) {
4
+ const fd = fs.openSync(absPath, 'r');
5
+ try {
6
+ for (const op of ops) {
7
+ // 파일 전체를 메모리에 올리지 않는다 — 동영상은 수백 MB 가 될 수 있다.
8
+ const chunk = Buffer.alloc(op.length);
9
+ const bytesRead = fs.readSync(fd, chunk, 0, op.length, op.offset);
10
+ // Buffer.alloc 은 0 으로 채운다 — 짧게 읽힌 걸 모르고 보내면 **0 패딩이 영상 데이터로**
11
+ // 올라가고, PUT 은 성공한 뒤 체크섬 불일치가 한참 뒤 인코딩 실패로 나타난다.
12
+ // 여기서 즉시 멈추는 게 그 추적 불가능한 실패보다 낫다.
13
+ if (bytesRead !== op.length) {
14
+ throw new Error(`파일을 읽는 중 크기가 어긋났다 (offset ${op.offset}: ${op.length} 바이트 요청, ${bytesRead} 읽음). ` +
15
+ '업로드 도중 파일이 바뀌었을 수 있다 — 파일을 확인하고 다시 시도할 것.');
16
+ }
17
+ const headers = {};
18
+ for (const h of op.requestHeaders ?? [])
19
+ headers[h.name] = h.value;
20
+ const res = await fetchWithTimeout(op.url, { method: op.method ?? 'PUT', headers, body: chunk, redirect }, HTTP_TRANSFER_TIMEOUT_MS);
21
+ if (!res.ok) {
22
+ throw new Error(`미디어 업로드 실패 (offset ${op.offset}): ${res.status} ${await res.text()}`);
23
+ }
24
+ }
25
+ }
26
+ finally {
27
+ fs.closeSync(fd);
28
+ }
29
+ }
@@ -4,12 +4,12 @@ import { apiGet, apiPatch, apiPost } from './client.js';
4
4
  import { encodePathSegment } from '../lib/url-path.js';
5
5
  // ─── 버전 ───
6
6
  export async function listVersions(appId, filters = {}) {
7
- const data = (await apiGet(`/apps/${encodePathSegment(appId)}/appStoreVersions`, {
7
+ const data = await apiGet(`/apps/${encodePathSegment(appId)}/appStoreVersions`, {
8
8
  'fields[appStoreVersions]': 'versionString,platform,appStoreState,releaseType,createdDate',
9
9
  'limit': '10',
10
10
  ...(filters.versionString ? { 'filter[versionString]': filters.versionString } : {}),
11
11
  ...(filters.platform ? { 'filter[platform]': filters.platform } : {}),
12
- }));
12
+ });
13
13
  return (data.data ?? []).map((v) => ({
14
14
  id: v.id,
15
15
  version: v.attributes?.versionString,
@@ -133,9 +133,9 @@ export async function attachLatestValidBuild(versionId, opts) {
133
133
  }
134
134
  // ─── 로컬라이제이션 (메타데이터) ───
135
135
  export async function getVersionLocalizations(versionId) {
136
- const data = (await apiGet(`/appStoreVersions/${encodePathSegment(versionId)}/appStoreVersionLocalizations`, {
136
+ const data = await apiGet(`/appStoreVersions/${encodePathSegment(versionId)}/appStoreVersionLocalizations`, {
137
137
  'fields[appStoreVersionLocalizations]': 'locale,description,keywords,promotionalText,whatsNew',
138
- }));
138
+ });
139
139
  return (data.data ?? []).map((l) => ({
140
140
  id: l.id,
141
141
  locale: l.attributes?.locale,
@@ -238,12 +238,12 @@ export async function getReviewNotes(versionId) {
238
238
  }
239
239
  // ─── 빌드 ───
240
240
  export async function listBuilds(appId) {
241
- const data = (await apiGet(`/builds`, {
241
+ const data = await apiGet('/builds', {
242
242
  'filter[app]': appId,
243
243
  'fields[builds]': 'version,uploadedDate,processingState,buildAudienceType',
244
244
  'sort': '-uploadedDate',
245
245
  'limit': '10',
246
- }));
246
+ });
247
247
  return (data.data ?? []).map((b) => ({
248
248
  id: b.id,
249
249
  version: b.attributes?.version,
@@ -253,14 +253,13 @@ export async function listBuilds(appId) {
253
253
  }
254
254
  // ─── 버전 → 앱/플랫폼 역조회 (빌드 연결·심사 제출이 공유) ───
255
255
  export async function getVersionAppAndPlatform(versionId) {
256
- const data = (await apiGet(`/appStoreVersions/${encodePathSegment(versionId)}`, {
257
- 'fields[appStoreVersions]': 'platform,app',
258
- 'include': 'app',
259
- }));
260
- const platform = data?.data?.attributes?.platform;
261
- const appId = data?.data?.relationships?.app?.data?.id;
262
- if (!platform || !appId) {
256
+ const data = await apiGet(`/appStoreVersions/${encodePathSegment(versionId)}`, { 'fields[appStoreVersions]': 'platform,app', include: 'app' });
257
+ const version = data?.data;
258
+ const platform = version?.attributes?.platform;
259
+ const app = version?.relationships?.app?.data;
260
+ if (version?.id !== versionId || version.type !== 'appStoreVersions' || app?.type !== 'apps'
261
+ || typeof app.id !== 'string' || !app.id || typeof platform !== 'string' || !platform) {
263
262
  throw new Error(`appStoreVersion ${versionId}에서 app 또는 platform을 찾지 못했어. 버전 ID 확인 필요.`);
264
263
  }
265
- return { appId, platform };
264
+ return { appId: app.id, platform };
266
265
  }
@@ -6,10 +6,8 @@
6
6
  // AI 에이전트가 응답을 받아 TodoWrite로 사용자에게 제시한 뒤,
7
7
  // 단계별로 기존 *_update_*, *_submit_*, *_check_* 도구를 호출하도록 유도한다.
8
8
  import { publisher, withEdit } from '../playstore/tools.js';
9
- import { apiGet } from '../appstore/tools.js';
10
- import { isNotFound } from '../appstore/http.js';
11
- import { encodePathSegment } from '../lib/url-path.js';
12
- import { APPSTORE_EDITABLE_STATES, checkPlayStoreRisks, checkAppStoreRisks, isRiskCheckIncomplete } from './risks.js';
9
+ import { selectEditableAppStoreVersion, resolveAppStoreVersionBuild } from '../appstore/release-target.js';
10
+ import { appStoreBuildRisk, checkPlayStoreRisksInEdit, checkAppStoreVersionRisks, isRiskCheckIncomplete } from './risks.js';
13
11
  const TODO_DIRECTIVE = [
14
12
  '📋 [AI 지시 — 호출자 에이전트 전용]',
15
13
  '',
@@ -75,27 +73,25 @@ function renderPlan(ctx, steps) {
75
73
  export async function buildPlayStoreReleasePlan(opts) {
76
74
  const { auth, packageName, versionCode, track, language } = opts;
77
75
  const steps = [];
78
- // 1) 인증 + 트랙 / 빌드 상태 조회 (단일 edit session)
79
- let trackInfo = {
80
- hasTargetVersion: false,
81
- };
76
+ // 트랙과 제출 위험을 같은 edit에서 조회해 대상 빌드 선택에 사용한 응답을 재사용한다.
77
+ let checks;
82
78
  try {
83
- await withEdit(auth, packageName, async (editId) => {
84
- // 리스팅 존재 여부는 checkPlayStoreRisks 가 따로 본다. 예전엔 여기서도 한 번 더
85
- // 받아 listingPresent 에 담았지만 그 값을 읽는 곳이 없어 edit 세션마다 낭비였다.
86
- const tracks = await publisher()
87
- .edits.tracks.list({ auth, packageName, editId });
88
- const targetTrack = tracks.data.tracks?.find((t) => t.track === track);
79
+ checks = await withEdit(auth, packageName, async (editId) => {
80
+ const { data } = await publisher().edits.tracks.list({ auth, packageName, editId });
81
+ const tracks = data.tracks ?? [];
82
+ const targetTrack = tracks.find((t) => t.track === track);
89
83
  const releases = targetTrack?.releases ?? [];
90
84
  const selectedVersionCode = versionCode ?? releases.flatMap((candidate) => candidate.versionCodes ?? [])
91
85
  .reduce((latest, code) => latest === undefined || Number(code) > Number(latest) ? code : latest, undefined);
92
86
  const release = releases.find((candidate) => selectedVersionCode && candidate.versionCodes?.includes(selectedVersionCode));
93
- trackInfo = {
87
+ const trackInfo = {
94
88
  hasTargetVersion: release !== undefined,
95
89
  selectedVersionCode,
96
90
  releaseStatus: release?.status ?? undefined,
97
91
  };
98
- return null;
92
+ const target = selectedVersionCode ? { track, versionCode: selectedVersionCode } : undefined;
93
+ const risks = await checkPlayStoreRisksInEdit(auth, packageName, editId, language, target, tracks);
94
+ return { trackInfo, target, risks };
99
95
  });
100
96
  steps.push({ state: 'done', title: 'Google Play 인증 + 트랙 조회 성공' });
101
97
  }
@@ -108,6 +104,7 @@ export async function buildPlayStoreReleasePlan(opts) {
108
104
  });
109
105
  return renderPlan({ platform: 'Play Store', identity: packageName, version: versionCode ?? 'latest', track }, steps);
110
106
  }
107
+ const { trackInfo, target, risks } = checks;
111
108
  // 2) 빌드 도착 확인
112
109
  if (trackInfo.hasTargetVersion) {
113
110
  steps.push({
@@ -127,8 +124,6 @@ export async function buildPlayStoreReleasePlan(opts) {
127
124
  });
128
125
  }
129
126
  // 3) 메타데이터 / 스크린샷 / 정책 위험 점검
130
- const target = trackInfo.selectedVersionCode ? { track, versionCode: trackInfo.selectedVersionCode } : undefined;
131
- const risks = await checkPlayStoreRisks(auth, packageName, language, target);
132
127
  if (risks.length === 0) {
133
128
  steps.push({
134
129
  state: 'done',
@@ -172,19 +167,11 @@ export async function buildAppStoreReleasePlan(opts) {
172
167
  const { appId, versionString, versionId: requestedVersionId } = opts;
173
168
  const context = { platform: 'App Store', identity: appId, version: versionString ?? requestedVersionId ?? 'latest' };
174
169
  const steps = [];
175
- // 1) 편집 가능한 버전 조회
176
- let versionId;
177
- let buildAttached = false;
170
+ // 1) 편집 가능한 버전과 포함된 빌드를 같은 응답에서 선택한다.
171
+ let version;
178
172
  try {
179
- const versions = await apiGet(`/apps/${encodePathSegment(appId)}/appStoreVersions`, {
180
- 'filter[appStoreState]': APPSTORE_EDITABLE_STATES,
181
- ...(versionString ? { 'filter[versionString]': versionString } : {}),
182
- ...(requestedVersionId ? { 'filter[id]': requestedVersionId } : {}),
183
- limit: requestedVersionId ? '1' : '5',
184
- });
185
- const matches = (versions.data ?? []).filter((version) => (!requestedVersionId || version.id === requestedVersionId)
186
- && (!versionString || version.attributes?.versionString === versionString));
187
- if (matches.length > 1 || (!requestedVersionId && versions.links?.next)) {
173
+ const selection = await selectEditableAppStoreVersion(appId, { versionString, versionId: requestedVersionId });
174
+ if (selection.status === 'ambiguous' || selection.status === 'incomplete') {
188
175
  steps.push({
189
176
  state: 'blocked',
190
177
  title: 'App Store 버전 대상을 하나로 확정할 수 없음',
@@ -193,32 +180,13 @@ export async function buildAppStoreReleasePlan(opts) {
193
180
  });
194
181
  return renderPlan(context, steps);
195
182
  }
196
- const version = matches[0];
197
- if (version) {
198
- versionId = version.id;
199
- const { versionString: actualVersion, appStoreState, platform } = version.attributes ?? {};
200
- context.version = [actualVersion ?? versionId, platform].filter(Boolean).join(' / ');
183
+ if (selection.status === 'selected') {
184
+ version = selection.version;
185
+ context.version = [version.versionString ?? version.id, version.platform].filter(Boolean).join(' / ');
201
186
  steps.push({
202
187
  state: 'done',
203
- title: `편집 가능한 버전 발견 (${actualVersion}, state=${appStoreState})`,
204
- });
205
- const build = await apiGet(`/appStoreVersions/${encodePathSegment(versionId)}/build`).catch((error) => {
206
- if (isNotFound(error))
207
- return { data: null };
208
- throw error;
188
+ title: `편집 가능한 버전 발견 (${version.versionString ?? version.id}, state=${version.state})`,
209
189
  });
210
- buildAttached = Boolean(build?.data?.id);
211
- if (buildAttached) {
212
- steps.push({ state: 'done', title: '버전에 빌드 연결됨' });
213
- }
214
- else {
215
- steps.push({
216
- state: 'blocked',
217
- title: '버전에 빌드 미연결',
218
- detail: 'TestFlight 빌드 처리 완료 후 App Store Connect에서 연결하거나 API로 attach.',
219
- tool: 'appstore_list_builds',
220
- });
221
- }
222
190
  }
223
191
  else {
224
192
  steps.push({
@@ -239,13 +207,35 @@ export async function buildAppStoreReleasePlan(opts) {
239
207
  });
240
208
  return renderPlan(context, steps);
241
209
  }
242
- // 2) 메타데이터 / 스크린샷 / 정책 위험 점검
243
- const risks = versionId ? await checkAppStoreRisks(appId, { versionId }) : [];
210
+ // 2) 선택한 버전을 재조회하지 않고 빌드와 정책 위험을 점검한다.
211
+ const versionId = version?.id;
212
+ let buildReady = false;
213
+ let risks = [];
214
+ if (version) {
215
+ const [build, versionRisks] = await Promise.all([
216
+ resolveAppStoreVersionBuild(version),
217
+ checkAppStoreVersionRisks(appId, version),
218
+ ]);
219
+ buildReady = build.status === 'ready';
220
+ risks = versionRisks;
221
+ const buildRisk = appStoreBuildRisk(build);
222
+ if (buildRisk) {
223
+ steps.push({
224
+ state: 'blocked',
225
+ title: build.status === 'missing' ? '버전에 빌드 미연결' : buildRisk.title,
226
+ detail: buildRisk.detail,
227
+ tool: 'appstore_list_builds',
228
+ });
229
+ }
230
+ else {
231
+ steps.push({ state: 'done', title: '버전에 빌드 연결됨' });
232
+ }
233
+ }
244
234
  if (!versionId) {
245
235
  steps.push({ state: 'blocked', title: '제출 위험 점검 미완료', detail: '대상 버전을 확인하세요.' });
246
236
  }
247
237
  else if (risks.length === 0) {
248
- steps.push({ state: 'done', title: '제출 위험 점검 통과 (블로커 0)' });
238
+ steps.push({ state: 'done', title: '메타데이터·스크린샷·정책 위험 점검 통과' });
249
239
  }
250
240
  else {
251
241
  const blockers = risks.filter((r) => r.level === 'blocker');
@@ -258,7 +248,7 @@ export async function buildAppStoreReleasePlan(opts) {
258
248
  steps.push(...risksToSteps(blockers, 'appstore_update_localization'));
259
249
  steps.push(...risksToSteps(warnings, 'appstore_update_localization'));
260
250
  }
261
- const canSubmit = versionId && buildAttached && !risks.some(blocksSubmission);
251
+ const canSubmit = buildReady && !risks.some(blocksSubmission);
262
252
  // 3) What's New / promotional text / reviewer notes
263
253
  steps.push({
264
254
  state: canSubmit ? 'pending' : 'blocked',