@superwall/cli 1.7.0 → 2.1.0

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.
Files changed (229) hide show
  1. package/README.md +192 -52
  2. package/dist/{setup-Bxj22rYi.js → apple-CSzNTGHM.js} +82 -76
  3. package/dist/auth.d.ts +4 -19
  4. package/dist/auth.js +4 -2
  5. package/dist/{actions-B7ym3oVS.js → billing-C3Q8DBU2.js} +98 -28
  6. package/dist/{bind-YrJvuRF9.js → bind-BumHTi9O.js} +38 -33
  7. package/dist/{build-DLoCW5Ri.js → build-Bpviiclc.js} +20 -26
  8. package/dist/client-BL0f_yGf.js +176 -0
  9. package/dist/{asc-Bf7zBbyS.js → client-BZ1UbpXz.js} +16 -15
  10. package/dist/config-BO1Y87kV.js +105 -0
  11. package/dist/create-BSfvpWoD.js +19 -0
  12. package/dist/{create-pkANt1Gs.js → create-BUcVG4Ab.js} +195 -169
  13. package/dist/{notification-url-DuKF2659.js → create-CfK3PeKA.js} +235 -539
  14. package/dist/doctor-BWqIYcMn.js +83 -0
  15. package/dist/{drivers-Qx9LxmRN.js → drivers-CPhdPkW5.js} +185 -172
  16. package/dist/entry.d.ts +0 -5
  17. package/dist/entry.js +28072 -1134
  18. package/dist/environment-eBXjELoN.js +58 -0
  19. package/dist/{existing-AVEfZu2A.js → existing-BltvQiX5.js} +12 -6
  20. package/dist/held-CPve03KJ.js +16 -0
  21. package/dist/held-DgnTFMl3.js +1112 -0
  22. package/dist/input-vi0bou04.js +42 -0
  23. package/dist/{integrate-brmhPG-S.js → integrate-BRsqoe01.js} +277 -254
  24. package/dist/log-NVhVe_oe.js +62 -0
  25. package/dist/login-BCEH5q0U.js +53 -0
  26. package/dist/login-BPOONe7n.js +16 -0
  27. package/dist/{login-Do4wFuLv.js → login-BbTIrCFT.js} +118 -55
  28. package/dist/lookup-rr1AkCJA.js +71 -0
  29. package/dist/migrate-C9X2Vz81.js +274 -0
  30. package/dist/notification-url-CV86qiKP.js +100 -0
  31. package/dist/{open-studio-DOw-6ydc.js → open-CcpXotHG.js} +34 -43
  32. package/dist/org-BQQDo7wm.js +35 -0
  33. package/dist/output-Ggzq5_-t.js +122 -0
  34. package/dist/paths-CRlU72cq.js +29 -0
  35. package/dist/playbook-DVMXN7fh.js +53 -0
  36. package/dist/{asc-products-9JXtDxI4.js → products-DH_fK9tY.js} +6 -6
  37. package/dist/promote-Da8xctzy.js +91 -0
  38. package/dist/push-BV-grvQg.js +22 -0
  39. package/dist/push-D6R9icWN.js +495 -0
  40. package/dist/registry-BYVD-_h6.js +10385 -0
  41. package/dist/{reports-CfJqoava.js → reports-D_qbl7_u.js} +7 -6
  42. package/dist/{resources-Bf9O1JNM.js → resources-DLON3-61.js} +162 -55
  43. package/dist/{run-DsVZ5snL.js → run-Co-BwhOg.js} +16 -22
  44. package/dist/scan-B88OlWOt.js +4 -0
  45. package/dist/{scan-zKsddO72.js → scan-CKuk-_6W.js} +48 -37
  46. package/dist/scope-DV22_Ufm.js +198 -0
  47. package/dist/screenshot-file-tVBfUEIi.js +16 -0
  48. package/dist/{selection-CxZoX4NT.js → selection-C2_KbLuo.js} +100 -51
  49. package/dist/server-C4f6ccUr.js +22 -0
  50. package/dist/{dev-DmB3XqaJ.js → server-D0d2oP-5.js} +86 -94
  51. package/dist/session-B-Uz0cQ7.js +40 -0
  52. package/dist/session-BuvArt1j.js +6 -0
  53. package/dist/session-C4rbE3VS.js +796 -0
  54. package/dist/skills/animate-onboarding/SKILL.md +467 -0
  55. package/dist/skills/animate-onboarding/references/engine.md +494 -0
  56. package/dist/skills/animate-onboarding/references/framework/Question.tsx +71 -0
  57. package/dist/skills/animate-onboarding/references/framework/README.md +40 -0
  58. package/dist/skills/animate-onboarding/references/framework/answers.ts +19 -0
  59. package/dist/skills/animate-onboarding/references/framework/flow.ts +80 -0
  60. package/dist/skills/animate-onboarding/references/framework/handoffs.ts +869 -0
  61. package/dist/skills/animate-onboarding/references/framework/layout.tsx +113 -0
  62. package/dist/skills/animate-onboarding/references/framework/motion.css +559 -0
  63. package/dist/skills/animate-onboarding/references/framework/useStoryRouter.ts +48 -0
  64. package/dist/skills/animate-onboarding/references/handoffs.md +375 -0
  65. package/dist/skills/animate-onboarding/references/imageReady.ts +92 -0
  66. package/dist/skills/animate-onboarding/references/morphFrame.ts +356 -0
  67. package/dist/skills/animate-onboarding/references/performance.md +41 -0
  68. package/dist/skills/animate-onboarding/references/web-runtime/README.md +17 -0
  69. package/dist/skills/animate-onboarding/references/web-runtime/handoffs.ts +858 -0
  70. package/dist/skills/animate-onboarding/references/web-runtime/story-motion.css +301 -0
  71. package/dist/skills/index.json +37 -0
  72. package/dist/skills/mobile-design/SKILL.md +447 -0
  73. package/dist/skills/mobile-design/references/responsive.md +162 -0
  74. package/dist/skills/onboarding-questions/SKILL.md +231 -0
  75. package/dist/skills/onboarding-questions/references/arpu-questions.md +139 -0
  76. package/dist/skills/onboarding-questions/references/craft.md +142 -0
  77. package/dist/skills/onboarding-questions/references/example-reflective.md +117 -0
  78. package/dist/skills/superwall/SKILL.md +82 -9
  79. package/dist/skills/superwall/references/api.md +153 -37
  80. package/dist/skills/superwall/references/apple-setup.md +316 -0
  81. package/dist/skills/superwall/references/asc.md +74 -38
  82. package/dist/skills/superwall/references/data-analytics.md +55 -21
  83. package/dist/skills/superwall/workflows/dashboard/playbook.md +3 -3
  84. package/dist/skills/superwall/workflows/dashboard/setup.md +8 -8
  85. package/dist/skills/superwall/workflows/migrate/adapty.md +6 -6
  86. package/dist/skills/superwall/workflows/migrate/playbook.md +4 -4
  87. package/dist/skills/superwall/workflows/migrate/qonversion.md +5 -5
  88. package/dist/skills/superwall/workflows/migrate/revenuecat.md +6 -6
  89. package/dist/skills/superwall/workflows/placements/android.md +2 -2
  90. package/dist/skills/superwall/workflows/placements/expo.md +2 -2
  91. package/dist/skills/superwall/workflows/placements/flutter.md +2 -2
  92. package/dist/skills/superwall/workflows/placements/ios.md +2 -2
  93. package/dist/skills/superwall/workflows/placements/playbook.md +2 -2
  94. package/dist/skills/superwall/workflows/placements/react-native.md +2 -2
  95. package/dist/skills/superwall/workflows/placements/strategy.md +2 -2
  96. package/dist/skills/superwall/workflows/review/playbook.md +1 -1
  97. package/dist/skills/superwall-editor/SKILL.md +61 -0
  98. package/dist/skills/superwall-editor/references/cli.md +135 -0
  99. package/dist/skills/superwall-editor/references/design.md +51 -0
  100. package/dist/skills/superwall-editor/references/native-elements.md +171 -0
  101. package/dist/skills/superwall-editor/references/workflow.md +65 -0
  102. package/dist/skills/superwall-editor/scripts/sw-editor.sh +662 -0
  103. package/dist/skills/superwall-framework/SKILL.md +85 -31
  104. package/dist/skills/superwall-framework/references/cli.md +58 -27
  105. package/dist/skills/superwall-framework/references/examples.md +4 -3
  106. package/dist/skills/superwall-framework/references/layout.md +64 -9
  107. package/dist/skills/superwall-framework/references/migrate-from-editor.md +1 -1
  108. package/dist/skills/superwall-framework/references/onboarding-state.md +245 -0
  109. package/dist/skills/wwdc/SKILL.md +22 -0
  110. package/dist/skills/wwdc/references/docs.md +52 -0
  111. package/dist/skills/wwdc/scripts/wwdc.sh +266 -0
  112. package/dist/skills-CLGJuMnF.js +14 -0
  113. package/dist/{skills-DPzlnfCK.js → skills-CZcpnEnG.js} +100 -122
  114. package/dist/{spawn-DSoTXy_j.js → spawn-DmmmHIP-.js} +14 -12
  115. package/dist/spinner-C2U6QBJ9.js +294 -0
  116. package/dist/storage-6h9vyiAz.js +31 -0
  117. package/dist/storage-CerJ5KLP.d.ts +16 -0
  118. package/dist/storekit-CK9JmM2D.js +16 -0
  119. package/dist/storekit-CinJra3V.js +47 -0
  120. package/dist/telemetry-DKyDhURo.js +56 -0
  121. package/dist/theme-DUsCh-Vd.js +25 -0
  122. package/dist/timing-BVxPrYq3.js +5 -0
  123. package/dist/{token-C0it-Xh7.js → token-DaxQgQkv.js} +6 -38
  124. package/dist/tools-skills/animate-onboarding/SKILL.md +467 -0
  125. package/dist/tools-skills/animate-onboarding/references/engine.md +494 -0
  126. package/dist/tools-skills/animate-onboarding/references/framework/Question.tsx +71 -0
  127. package/dist/tools-skills/animate-onboarding/references/framework/README.md +40 -0
  128. package/dist/tools-skills/animate-onboarding/references/framework/answers.ts +19 -0
  129. package/dist/tools-skills/animate-onboarding/references/framework/flow.ts +80 -0
  130. package/dist/tools-skills/animate-onboarding/references/framework/handoffs.ts +869 -0
  131. package/dist/tools-skills/animate-onboarding/references/framework/layout.tsx +113 -0
  132. package/dist/tools-skills/animate-onboarding/references/framework/motion.css +559 -0
  133. package/dist/tools-skills/animate-onboarding/references/framework/useStoryRouter.ts +48 -0
  134. package/dist/tools-skills/animate-onboarding/references/handoffs.md +375 -0
  135. package/dist/tools-skills/animate-onboarding/references/imageReady.ts +92 -0
  136. package/dist/tools-skills/animate-onboarding/references/morphFrame.ts +356 -0
  137. package/dist/tools-skills/animate-onboarding/references/performance.md +41 -0
  138. package/dist/tools-skills/animate-onboarding/references/web-runtime/README.md +17 -0
  139. package/dist/tools-skills/animate-onboarding/references/web-runtime/handoffs.ts +858 -0
  140. package/dist/tools-skills/animate-onboarding/references/web-runtime/story-motion.css +301 -0
  141. package/dist/tools-skills/mobile-design/SKILL.md +447 -0
  142. package/dist/tools-skills/mobile-design/references/responsive.md +162 -0
  143. package/dist/tools-skills/onboarding-questions/SKILL.md +231 -0
  144. package/dist/tools-skills/onboarding-questions/references/arpu-questions.md +139 -0
  145. package/dist/tools-skills/onboarding-questions/references/craft.md +142 -0
  146. package/dist/tools-skills/onboarding-questions/references/example-reflective.md +117 -0
  147. package/dist/tools-skills/superwall/SKILL.md +263 -0
  148. package/dist/tools-skills/superwall/references/api.md +303 -0
  149. package/dist/tools-skills/superwall/references/asa.md +166 -0
  150. package/dist/tools-skills/superwall/references/asc.md +95 -0
  151. package/dist/tools-skills/superwall/references/dashboard-links.md +57 -0
  152. package/dist/tools-skills/superwall/references/data-analytics.md +896 -0
  153. package/dist/tools-skills/superwall/references/docs.md +51 -0
  154. package/dist/tools-skills/superwall/references/sdk-integration.md +104 -0
  155. package/dist/tools-skills/superwall/references/sdk-source.md +18 -0
  156. package/dist/tools-skills/superwall/workflows/dashboard/playbook.md +76 -0
  157. package/dist/tools-skills/superwall/workflows/dashboard/setup.md +100 -0
  158. package/dist/tools-skills/superwall/workflows/integrate/android.md +292 -0
  159. package/dist/tools-skills/superwall/workflows/integrate/expo.md +272 -0
  160. package/dist/tools-skills/superwall/workflows/integrate/flutter.md +285 -0
  161. package/dist/tools-skills/superwall/workflows/integrate/ios.md +314 -0
  162. package/dist/tools-skills/superwall/workflows/integrate/playbook.md +83 -0
  163. package/dist/tools-skills/superwall/workflows/integrate/react-native.md +246 -0
  164. package/dist/tools-skills/superwall/workflows/migrate/adapty.md +229 -0
  165. package/dist/tools-skills/superwall/workflows/migrate/playbook.md +78 -0
  166. package/dist/tools-skills/superwall/workflows/migrate/qonversion.md +227 -0
  167. package/dist/tools-skills/superwall/workflows/migrate/revenuecat.md +414 -0
  168. package/dist/tools-skills/superwall/workflows/placements/android.md +175 -0
  169. package/dist/tools-skills/superwall/workflows/placements/expo.md +161 -0
  170. package/dist/tools-skills/superwall/workflows/placements/flutter.md +139 -0
  171. package/dist/tools-skills/superwall/workflows/placements/ios.md +165 -0
  172. package/dist/tools-skills/superwall/workflows/placements/playbook.md +69 -0
  173. package/dist/tools-skills/superwall/workflows/placements/react-native.md +145 -0
  174. package/dist/tools-skills/superwall/workflows/placements/strategy.md +222 -0
  175. package/dist/tools-skills/superwall/workflows/review/android.md +120 -0
  176. package/dist/tools-skills/superwall/workflows/review/expo.md +100 -0
  177. package/dist/tools-skills/superwall/workflows/review/flutter.md +99 -0
  178. package/dist/tools-skills/superwall/workflows/review/ios.md +108 -0
  179. package/dist/tools-skills/superwall/workflows/review/playbook.md +70 -0
  180. package/dist/tools-skills/superwall/workflows/review/react-native.md +100 -0
  181. package/dist/tools-skills/superwall-editor/SKILL.md +113 -0
  182. package/dist/tools-skills/superwall-editor/references/cli.md +135 -0
  183. package/dist/tools-skills/superwall-editor/references/design.md +51 -0
  184. package/dist/tools-skills/superwall-editor/references/native-elements.md +171 -0
  185. package/dist/tools-skills/superwall-editor/references/workflow.md +65 -0
  186. package/dist/tools-skills/superwall-editor/scripts/sw-editor.sh +662 -0
  187. package/dist/tools-skills/wwdc/SKILL.md +22 -0
  188. package/dist/tools-skills/wwdc/references/docs.md +52 -0
  189. package/dist/tools-skills/wwdc/scripts/wwdc.sh +266 -0
  190. package/dist/tools.d.ts +96 -0
  191. package/dist/tools.js +11360 -0
  192. package/dist/ui-D_qf3Gvw.js +53 -0
  193. package/dist/upgrade-DPo0a4Es.js +117 -0
  194. package/dist/upgrade-ffseQDMx.js +7 -0
  195. package/package.json +10 -5
  196. package/dist/api-CZzirVMj.js +0 -151
  197. package/dist/api-output-aJNw7Syy.js +0 -20
  198. package/dist/app-DH6U8yuI.js +0 -190
  199. package/dist/asa-C-sQzPPn.js +0 -1194
  200. package/dist/asc-1ZBJ6DwS.js +0 -778
  201. package/dist/auth-YRhlV3DE.js +0 -140
  202. package/dist/billing-CCYHdApx.js +0 -80
  203. package/dist/bundle-id-CKxl_026.js +0 -121
  204. package/dist/command-CMIz81Da.js +0 -301
  205. package/dist/dev-DZy6pOnB.js +0 -22
  206. package/dist/doctor-H-hf-Yww.js +0 -88
  207. package/dist/feedback-CKf-rpBW.js +0 -152
  208. package/dist/hosted-CXe9TrWx.js +0 -32
  209. package/dist/migrate-C9ERDR6y.js +0 -284
  210. package/dist/org-sj7uyvp-.js +0 -40
  211. package/dist/output-C4o2gJ1K.js +0 -146
  212. package/dist/params-l3CrvRtR.js +0 -51
  213. package/dist/pipeline-BqzqZhX1.js +0 -977
  214. package/dist/print-skill-ZojRSybs.js +0 -74
  215. package/dist/promote-BG8X4Nv_.js +0 -88
  216. package/dist/publish-sxLh-G4G.js +0 -35
  217. package/dist/push-bQ6Vxtg8.js +0 -35
  218. package/dist/query-_FbybaH-.js +0 -53
  219. package/dist/resource-CGIwSd29.js +0 -323
  220. package/dist/revenue-provider-ebsRINY8.js +0 -100
  221. package/dist/scope-BvzD-kO4.js +0 -223
  222. package/dist/skills-D_R-lEsK.js +0 -64
  223. package/dist/spinner-TWa0hia6.js +0 -18
  224. package/dist/storekit-Cj9Cpjcz.js +0 -29
  225. package/dist/telemetry-DeA1mvnT.js +0 -169
  226. package/dist/ui-Dy0b-9L8.js +0 -27738
  227. package/dist/update-B2fWIc4q.js +0 -59
  228. package/dist/upgrade-BmzkTKrh.js +0 -72
  229. /package/dist/{devtools-8EgLo86w.js → devtools-pBl_vt03.js} +0 -0
@@ -0,0 +1,1112 @@
1
+ import { l as readJson, o as cache } from "./output-Ggzq5_-t.js";
2
+ import { t as ApiError } from "./client-BL0f_yGf.js";
3
+ import { d as readInput, t as apiCall } from "./spinner-C2U6QBJ9.js";
4
+ import { D as field, O as isRecord, j as textField, k as listField, n as createApplication, p as listProjects, s as createProject } from "./resources-DLON3-61.js";
5
+ import { n as orgForNewProject } from "./org-BQQDo7wm.js";
6
+ import { n as findApplication } from "./lookup-rr1AkCJA.js";
7
+ import { r as pickOrganization } from "./scope-DV22_Ufm.js";
8
+ import { a as listAscConfigs, c as replaceAppPurchaseKey, l as replaceAscConfig, r as createAscConfig, s as replaceAppAscKey, t as ascProxy } from "./client-BZ1UbpXz.js";
9
+
10
+ //#region src/core/app-store-connect/api/spec.ts
11
+ const REFRESH_TTL_MS = 10080 * 60 * 1e3;
12
+ const CACHE_FILE = "asc-index.json";
13
+ let mem;
14
+ let refresh = () => {};
15
+ function useAscRefresh(start) {
16
+ refresh = start;
17
+ }
18
+ function findCachedIndex() {
19
+ return mem ??= readJson(cache(), CACHE_FILE);
20
+ }
21
+ function readCachedIndex() {
22
+ const index = findCachedIndex();
23
+ if (!index) throw new Error("No App Store Connect schema yet. Run `superwall asc docs --refresh`.");
24
+ return index;
25
+ }
26
+ function indexIsStale(index) {
27
+ return !index.fetchedAt || Date.now() - index.fetchedAt > REFRESH_TTL_MS;
28
+ }
29
+ function writeCachedIndex(index) {
30
+ cache().write(CACHE_FILE, JSON.stringify(index));
31
+ mem = index;
32
+ }
33
+ function refreshInBackground() {
34
+ refresh();
35
+ }
36
+ async function inflateRaw(data) {
37
+ const stream = new Blob([data]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
38
+ return new Uint8Array(await new Response(stream).arrayBuffer());
39
+ }
40
+ async function unzipSingleJson(zip) {
41
+ const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
42
+ const u32 = (offset) => view.getUint32(offset, true);
43
+ const u16 = (offset) => view.getUint16(offset, true);
44
+ let eocd = zip.length - 22;
45
+ while (eocd >= 0 && u32(eocd) !== 101010256) eocd--;
46
+ if (eocd < 0) throw new Error("App Store Connect spec: no zip directory found.");
47
+ let entry = u32(eocd + 16);
48
+ const count = u16(eocd + 10);
49
+ for (let i = 0; i < count; i++) {
50
+ if (u32(entry) !== 33639248) throw new Error("App Store Connect spec: malformed zip directory.");
51
+ const method = u16(entry + 10);
52
+ const compSize = u32(entry + 20);
53
+ const nameLen = u16(entry + 28);
54
+ const extraLen = u16(entry + 30);
55
+ const commentLen = u16(entry + 32);
56
+ const localOff = u32(entry + 42);
57
+ if (new TextDecoder().decode(zip.subarray(entry + 46, entry + 46 + nameLen)).endsWith(".json")) {
58
+ const start = localOff + 30 + u16(localOff + 26) + u16(localOff + 28);
59
+ const data = zip.subarray(start, start + compSize);
60
+ return new TextDecoder().decode(method === 0 ? data : await inflateRaw(data));
61
+ }
62
+ entry += 46 + nameLen + extraLen + commentLen;
63
+ }
64
+ throw new Error("App Store Connect spec: no JSON entry in archive.");
65
+ }
66
+ const METHODS = [
67
+ "get",
68
+ "post",
69
+ "patch",
70
+ "delete",
71
+ "put"
72
+ ];
73
+ function deriveIndex(spec) {
74
+ const schemas = spec.components?.schemas ?? {};
75
+ const deref = (node) => {
76
+ if (!node?.$ref) return node;
77
+ return schemas[node.$ref.split("/").pop()];
78
+ };
79
+ const fields = (schema) => {
80
+ const out = {};
81
+ if (!schema) return out;
82
+ const required = new Set(schema.required ?? []);
83
+ for (const [name, raw] of Object.entries(schema.properties ?? {})) {
84
+ const p = deref(raw);
85
+ const f = { required: required.has(name) };
86
+ if (Array.isArray(p.enum)) f.enum = p.enum;
87
+ else if (p.type) f.type = p.type;
88
+ out[name] = f;
89
+ }
90
+ return out;
91
+ };
92
+ const relationships = (schema) => {
93
+ const out = {};
94
+ if (!schema) return out;
95
+ const required = new Set(schema.required ?? []);
96
+ for (const [name, raw] of Object.entries(schema.properties ?? {})) {
97
+ const data = deref(deref(raw)?.properties?.data);
98
+ const rel = { required: required.has(name) };
99
+ const ident = data?.type === "array" ? deref(data.items) : data;
100
+ rel.many = data?.type === "array";
101
+ const t = deref(ident?.properties?.type);
102
+ if (Array.isArray(t?.enum)) rel.target = t.enum[0];
103
+ out[name] = rel;
104
+ }
105
+ return out;
106
+ };
107
+ const paths = {};
108
+ for (const [path, ops] of Object.entries(spec.paths ?? {})) for (const method of METHODS) {
109
+ const op = ops[method];
110
+ if (!op) continue;
111
+ const entry = {
112
+ opId: op.operationId,
113
+ summary: op.summary,
114
+ ...op.deprecated ? { deprecated: true } : {}
115
+ };
116
+ const bodySchema = deref(deref(op.requestBody)?.content?.["application/json"]?.schema);
117
+ if (bodySchema) {
118
+ const data = deref(bodySchema.properties?.data);
119
+ const type = deref(data?.properties?.type);
120
+ if (Array.isArray(type?.enum)) entry.dataType = type.enum[0];
121
+ const attrs = fields(deref(data?.properties?.attributes));
122
+ const rels = relationships(deref(data?.properties?.relationships));
123
+ if (Object.keys(attrs).length) entry.attributes = attrs;
124
+ if (Object.keys(rels).length) entry.relationships = rels;
125
+ }
126
+ const query = (op.parameters ?? []).map(deref).filter((p) => p?.in === "query").map((p) => p.name);
127
+ if (query.length) entry.query = query;
128
+ (paths[path] ??= {})[method] = entry;
129
+ }
130
+ return {
131
+ specVersion: String(spec.info?.version ?? "unknown"),
132
+ openapi: String(spec.openapi ?? "unknown"),
133
+ paths
134
+ };
135
+ }
136
+ async function downloadAscIndex() {
137
+ const res = await fetch("https://developer.apple.com/sample-code/app-store-connect/app-store-connect-openapi-specification.zip");
138
+ if (!res.ok) throw new Error(`Couldn't fetch the App Store Connect schema (HTTP ${res.status}). Check your connection and retry.`);
139
+ const index = deriveIndex(JSON.parse(await unzipSingleJson(new Uint8Array(await res.arrayBuffer()))));
140
+ index.fetchedAt = Date.now();
141
+ return index;
142
+ }
143
+
144
+ //#endregion
145
+ //#region src/core/api/integrations.ts
146
+ const REVENUE_INTEGRATIONS = {
147
+ open_revenue: [
148
+ "app_store_connect",
149
+ "google_play",
150
+ "stripe"
151
+ ],
152
+ revenue_cat: ["revenue_cat", "stripe"],
153
+ none: [
154
+ "app_store_connect",
155
+ "google_play",
156
+ "stripe",
157
+ "revenue_cat"
158
+ ]
159
+ };
160
+ const KEY_KINDS = ["api_key", "purchase_key"];
161
+ const KEY_LABEL = {
162
+ api_key: "App Store Connect API key",
163
+ purchase_key: "In-App Purchase key"
164
+ };
165
+ function keyKind(value) {
166
+ return KEY_KINDS.find((kind) => kind === value);
167
+ }
168
+ var RefusedByApi = class extends Error {};
169
+ function integrations(applicationId) {
170
+ return `/internal/v2/applications/${applicationId}/integrations`;
171
+ }
172
+ async function supported(what, api, work) {
173
+ try {
174
+ return await work();
175
+ } catch (error) {
176
+ if (error instanceof ApiError && error.status === 404 && !error.envelope) throw new RefusedByApi(`The Superwall API at ${api.host} can't ${what} yet. Nothing was changed.`);
177
+ throw error;
178
+ }
179
+ }
180
+ function findIntegrations(api, applicationId) {
181
+ return api.get(`${integrations(applicationId)}/overview`);
182
+ }
183
+ async function replaceRevenueProvider(api, applicationId, provider) {
184
+ return (await api.patch(`${integrations(applicationId)}/revenue-provider`, { revenue_provider: provider })).revenue_provider;
185
+ }
186
+ function listKeySources(api, applicationId) {
187
+ return supported("list the keys on your other apps", api, () => {
188
+ return api.get(`${integrations(applicationId)}/app-store-keys/copy-sources`);
189
+ });
190
+ }
191
+ function copyAppKey(api, applicationId, input) {
192
+ return supported("copy a key from another app", api, () => {
193
+ return api.post(`${integrations(applicationId)}/app-store-keys/copy`, {
194
+ kind: input.kind,
195
+ source_application_id: input.from,
196
+ ...input.confirmed ? { confirmed: true } : {}
197
+ });
198
+ });
199
+ }
200
+ function importAppKey(api, applicationId, kind) {
201
+ return supported("import a key your organization already has", api, () => {
202
+ return api.post(`${integrations(applicationId)}/app-store-keys/import`, { kind });
203
+ });
204
+ }
205
+ async function removeAppKey(api, applicationId, kind) {
206
+ await supported("remove an app's key", api, () => {
207
+ return api.del(`${integrations(applicationId)}/app-store-keys/${kind}`);
208
+ });
209
+ }
210
+ function serverNotificationsPath(app) {
211
+ return `/v2/projects/${app.projectId}/applications/${app.applicationId}/integrations/app-store-connect/notification-url/apple`;
212
+ }
213
+ function checkServerNotifications(api, app) {
214
+ return supported("read Apple's server notification URLs", api, () => {
215
+ return api.get(serverNotificationsPath(app));
216
+ });
217
+ }
218
+ function updateServerNotifications(api, app, options) {
219
+ return supported("set Apple's server notification URLs", api, () => {
220
+ return api.put(serverNotificationsPath(app), options.setRevenueProvider ? { set_revenue_provider: true } : {});
221
+ });
222
+ }
223
+ function listBundleIdSuggestions(api, applicationId) {
224
+ return supported("suggest a bundle ID", api, () => {
225
+ return api.get(`/internal/v2/applications/${applicationId}/bundle-id-suggestions`);
226
+ });
227
+ }
228
+ function updateBundleId(api, applicationId, input) {
229
+ return supported("save a bundle ID", api, () => {
230
+ return api.post(`/internal/v2/applications/${applicationId}/bundle-id`, {
231
+ bundle_id: input.bundleId,
232
+ ...input.appStoreId ? { app_store_id: input.appStoreId } : {},
233
+ ...input.replace ? { replace: true } : {}
234
+ });
235
+ });
236
+ }
237
+
238
+ //#endregion
239
+ //#region src/core/api/params.ts
240
+ function parseParams(pairs) {
241
+ const root = {};
242
+ for (const pair of pairs ?? []) {
243
+ const eq = pair.indexOf("=");
244
+ if (eq < 0) throw new Error(`Invalid -d "${pair}" - expected key=value (or key:=jsonValue).`);
245
+ const typed = pair[eq - 1] === ":";
246
+ const key = pair.slice(0, typed ? eq - 1 : eq);
247
+ const raw = pair.slice(eq + 1);
248
+ const value = typed ? parseTyped(raw, pair) : raw;
249
+ assignPath(root, splitKey(key), value);
250
+ }
251
+ return root;
252
+ }
253
+ function parseTyped(raw, pair) {
254
+ try {
255
+ return JSON.parse(raw);
256
+ } catch {
257
+ throw new Error(`Invalid -d "${pair}" - value after := must be JSON (number, true/false, null, "quoted", [...], {...}).`);
258
+ }
259
+ }
260
+ function splitKey(key) {
261
+ return key.replace(/\]/g, "").split("[").filter((p) => p !== "");
262
+ }
263
+ function assignPath(root, parts, value) {
264
+ let cur = root;
265
+ for (const [i, key] of parts.entries()) {
266
+ const nextKey = parts[i + 1];
267
+ if (nextKey === void 0) {
268
+ assign(cur, key, value);
269
+ return;
270
+ }
271
+ let next = childOf(cur, key);
272
+ if (next === void 0) {
273
+ next = /^\d+$/.test(nextKey) ? [] : {};
274
+ assign(cur, key, next);
275
+ }
276
+ cur = next;
277
+ }
278
+ }
279
+ function childOf(container, key) {
280
+ return Array.isArray(container) ? container[Number(key)] : container[key];
281
+ }
282
+ function assign(container, key, value) {
283
+ if (Array.isArray(container)) container[Number(key)] = value;
284
+ else container[key] = value;
285
+ }
286
+
287
+ //#endregion
288
+ //#region src/core/app-store-connect/api/replaced.ts
289
+ const REVIEW_SUBMISSIONS = "/v1/reviewSubmissions with /v1/reviewSubmissionItems";
290
+ const ASSET_LIBRARY_IMAGES = "/v1/appAssetLibraryImages with /v1/appAssetLibraryPlacements";
291
+ const ASSET_LIBRARY_VIDEOS = "/v1/appAssetLibraryVideos with /v1/appAssetLibraryPlacements";
292
+ const REPLACED = [
293
+ {
294
+ path: "/v1/subscriptionLocalizations",
295
+ use: "/v2/subscriptionLocalizations, on a subscription version",
296
+ since: "4.4.1"
297
+ },
298
+ {
299
+ path: "/v1/subscriptions/{id}/subscriptionLocalizations",
300
+ use: "/v1/subscriptionVersions/{id}/localizations",
301
+ since: "4.4.1"
302
+ },
303
+ {
304
+ path: "/v1/subscriptionGroupLocalizations",
305
+ use: "/v2/subscriptionGroupLocalizations, on a group version",
306
+ since: "4.4.1"
307
+ },
308
+ {
309
+ path: "/v1/subscriptionGroups/{id}/subscriptionGroupLocalizations",
310
+ use: "/v1/subscriptionGroupVersions/{id}/localizations",
311
+ since: "4.4.1"
312
+ },
313
+ {
314
+ path: "/v1/inAppPurchaseLocalizations",
315
+ use: "/v2/inAppPurchaseLocalizations, on an in-app purchase version",
316
+ since: "4.4.1"
317
+ },
318
+ {
319
+ path: "/v2/inAppPurchases/{id}/inAppPurchaseLocalizations",
320
+ use: "/v1/inAppPurchaseVersions/{id}/localizations",
321
+ since: "4.4.1"
322
+ },
323
+ {
324
+ path: "/v1/subscriptionImages",
325
+ use: "/v2/subscriptionImages",
326
+ since: "4.4.1"
327
+ },
328
+ {
329
+ path: "/v1/subscriptions/{id}/images",
330
+ use: "/v1/subscriptionVersions/{id}/images",
331
+ since: "4.4.1"
332
+ },
333
+ {
334
+ path: "/v1/inAppPurchaseImages",
335
+ use: "/v2/inAppPurchaseImages",
336
+ since: "4.4.1"
337
+ },
338
+ {
339
+ path: "/v2/inAppPurchases/{id}/images",
340
+ use: "/v1/inAppPurchaseVersions/{id}/images",
341
+ since: "4.4.1"
342
+ },
343
+ {
344
+ path: "/v1/subscriptionSubmissions",
345
+ use: REVIEW_SUBMISSIONS,
346
+ since: "4.4.1"
347
+ },
348
+ {
349
+ path: "/v1/subscriptionGroupSubmissions",
350
+ use: REVIEW_SUBMISSIONS,
351
+ since: "4.4.1"
352
+ },
353
+ {
354
+ path: "/v1/inAppPurchaseSubmissions",
355
+ use: REVIEW_SUBMISSIONS,
356
+ since: "4.4.1"
357
+ },
358
+ {
359
+ path: "/v1/subscriptionAvailabilities",
360
+ use: "/v1/subscriptionPlanAvailabilities",
361
+ since: "4.4"
362
+ },
363
+ {
364
+ path: "/v1/subscriptions/{id}/subscriptionAvailability",
365
+ use: "/v1/subscriptions/{id}/planAvailabilities",
366
+ since: "4.4"
367
+ },
368
+ {
369
+ path: "/v1/inAppPurchases",
370
+ use: "/v2/inAppPurchases",
371
+ since: "3.0"
372
+ },
373
+ {
374
+ path: "/v1/apps/{id}/inAppPurchases",
375
+ use: "/v1/apps/{id}/inAppPurchasesV2",
376
+ since: "2.0"
377
+ },
378
+ {
379
+ path: "/v1/appStoreVersionSubmissions",
380
+ use: REVIEW_SUBMISSIONS,
381
+ since: "1.7"
382
+ },
383
+ {
384
+ path: "/v1/appStoreVersions/{id}/appStoreVersionSubmission",
385
+ use: "/v1/reviewSubmissions?filter[app]=…",
386
+ since: "1.7"
387
+ },
388
+ {
389
+ path: "/v1/appStoreVersionExperiments",
390
+ use: "/v2/appStoreVersionExperiments",
391
+ since: "2.4"
392
+ },
393
+ {
394
+ path: "/v1/appStoreVersions/{id}/appStoreVersionExperiments",
395
+ use: "/v1/appStoreVersions/{id}/appStoreVersionExperimentsV2",
396
+ since: "2.4"
397
+ },
398
+ {
399
+ path: "/v1/apps/{id}/appStoreVersions",
400
+ query: "filter[appStoreState]",
401
+ use: "filter[appVersionState] (the appStoreState attribute is replaced by appVersionState)",
402
+ since: "3.7"
403
+ },
404
+ {
405
+ path: "/v1/appScreenshotSets",
406
+ use: ASSET_LIBRARY_IMAGES,
407
+ since: "4.5"
408
+ },
409
+ {
410
+ path: "/v1/appScreenshots",
411
+ use: ASSET_LIBRARY_IMAGES,
412
+ since: "4.5"
413
+ },
414
+ {
415
+ path: "/v1/appPreviewSets",
416
+ use: ASSET_LIBRARY_VIDEOS,
417
+ since: "4.5"
418
+ },
419
+ {
420
+ path: "/v1/appPreviews",
421
+ use: ASSET_LIBRARY_VIDEOS,
422
+ since: "4.5"
423
+ },
424
+ {
425
+ path: "/v1/appStoreVersionLocalizations/{id}/appScreenshotSets",
426
+ use: "/v1/appStoreVersionLocalizations/{id}/placements",
427
+ since: "4.5"
428
+ },
429
+ {
430
+ path: "/v1/appStoreVersionLocalizations/{id}/appPreviewSets",
431
+ use: "/v1/appStoreVersionLocalizations/{id}/placements",
432
+ since: "4.5"
433
+ },
434
+ {
435
+ path: "/v1/builds/{id}/relationships/appEncryptionDeclaration",
436
+ methods: ["PATCH"],
437
+ use: "PATCH /v1/builds/{id} with the appEncryptionDeclaration relationship",
438
+ since: "4.0"
439
+ }
440
+ ];
441
+ function segmentsOf(path) {
442
+ const [bare = ""] = path.split("?");
443
+ return bare.split("/").filter(Boolean);
444
+ }
445
+ function matches$1(rule, method, path) {
446
+ if (rule.methods && !rule.methods.includes(method.toUpperCase())) return false;
447
+ const query = (path.split("?")[1] ?? "").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
448
+ if (rule.query && !query.includes(rule.query)) return false;
449
+ const pattern = segmentsOf(rule.path);
450
+ const keepsRelationships = pattern.includes("relationships");
451
+ const concrete = segmentsOf(path).filter((segment, index) => keepsRelationships || !(segment === "relationships" && index === 3));
452
+ if (concrete.length < pattern.length) return false;
453
+ return pattern.every((segment, index) => segment === "{id}" || segment === concrete[index]);
454
+ }
455
+ function selectReplacement(method, path) {
456
+ return REPLACED.find((rule) => matches$1(rule, method, path));
457
+ }
458
+ function formatReplacement(rule) {
459
+ return `Apple replaced ${rule.query ? `${rule.query} on ${rule.path}` : rule.path} in API ${rule.since}: use ${rule.use}.`;
460
+ }
461
+
462
+ //#endregion
463
+ //#region src/core/app-store-connect/api/schema.ts
464
+ function segments(path) {
465
+ const [pathOnly = ""] = path.split("?");
466
+ return pathOnly.split("/").filter(Boolean);
467
+ }
468
+ function matches(tmpl, concrete) {
469
+ if (tmpl.length !== concrete.length) return false;
470
+ return tmpl.every((s, i) => {
471
+ return s.startsWith("{") || concrete[i]?.startsWith("{") || s === concrete[i];
472
+ });
473
+ }
474
+ function lookupAscOp(method, rawPath) {
475
+ const m = method.toLowerCase();
476
+ const concrete = segments(rawPath);
477
+ for (const [tmpl, ops] of Object.entries(readCachedIndex().paths)) {
478
+ const op = ops[m];
479
+ if (op && matches(segments(tmpl), concrete)) return {
480
+ path: tmpl,
481
+ op
482
+ };
483
+ }
484
+ }
485
+ function castAttr(field$1, v) {
486
+ if (typeof v !== "string" || !field$1) return v;
487
+ if (field$1.type === "boolean") {
488
+ if (v === "true") return true;
489
+ if (v === "false") return false;
490
+ }
491
+ if ((field$1.type === "integer" || field$1.type === "number") && v.trim() !== "") {
492
+ const n = Number(v);
493
+ if (!Number.isNaN(n)) return n;
494
+ }
495
+ return v;
496
+ }
497
+ function lastId(rawPath) {
498
+ const segs = segments(rawPath);
499
+ const last = segs[segs.length - 1];
500
+ return last && !last.startsWith("{") ? last : void 0;
501
+ }
502
+ function buildAscBody(op, method, rawPath, flat) {
503
+ if (!op.dataType) return flat;
504
+ if (flat.data && typeof flat.data === "object") return flat;
505
+ const attributes = {};
506
+ const relationships = {};
507
+ for (const [k, v] of Object.entries(flat)) {
508
+ const rel = op.relationships?.[k];
509
+ if (rel) {
510
+ const ids = Array.isArray(v) ? v : [v];
511
+ relationships[k] = { data: rel.many ? ids.map((id) => ({
512
+ type: rel.target,
513
+ id: String(id)
514
+ })) : {
515
+ type: rel.target,
516
+ id: String(v)
517
+ } };
518
+ } else attributes[k] = castAttr(op.attributes?.[k], v);
519
+ }
520
+ const data = { type: op.dataType };
521
+ if (method.toLowerCase() === "patch") {
522
+ const id = lastId(rawPath);
523
+ if (id) data.id = id;
524
+ }
525
+ if (Object.keys(attributes).length) data.attributes = attributes;
526
+ if (Object.keys(relationships).length) data.relationships = relationships;
527
+ return { data };
528
+ }
529
+ function validateAscBody(op, method, body) {
530
+ const problems = [];
531
+ const data = isRecord(body.data) ? body.data : {};
532
+ const attrs = isRecord(data.attributes) ? data.attributes : {};
533
+ const rels = isRecord(data.relationships) ? data.relationships : {};
534
+ const isPatch = method.toLowerCase() === "patch";
535
+ for (const [name, f] of Object.entries(op.attributes ?? {})) {
536
+ if (f.required && !isPatch && !(name in attrs)) problems.push(`missing required attribute: ${name}`);
537
+ const val = attrs[name];
538
+ if (f.enum && typeof val === "string" && !f.enum.includes(val)) problems.push(`${name} "${val}" not allowed — use ${f.enum.join("|")}`);
539
+ }
540
+ for (const [name, r] of Object.entries(op.relationships ?? {})) if (r.required && !isPatch && !(name in rels)) problems.push(`missing required relationship: ${name}${r.target ? ` → ${r.target}` : ""}`);
541
+ return problems;
542
+ }
543
+ function exampleInvocation(method, path, op) {
544
+ const parts = [`superwall asc ${method.toLowerCase()} ${path}`];
545
+ for (const [name, f] of Object.entries(op.attributes ?? {})) {
546
+ if (!f.required) continue;
547
+ parts.push(`-d ${name}=${f.enum ? f.enum[0] : `<${f.type ?? "value"}>`}`);
548
+ }
549
+ for (const [name, r] of Object.entries(op.relationships ?? {})) if (r.required) parts.push(`-d ${name}=<${r.target ?? "id"} id>`);
550
+ return parts.join(" ");
551
+ }
552
+ function renderOp(method, path, op) {
553
+ const lines = [];
554
+ lines.push(`### ${method.toUpperCase()} ${path}`);
555
+ if (op.summary) lines.push(op.summary);
556
+ const replaced = selectReplacement(method, path);
557
+ if (replaced) lines.push(`> ⚠ ${formatReplacement(replaced)}`);
558
+ else if (op.deprecated) lines.push("> ⚠ Deprecated in the App Store Connect API.");
559
+ const attrs = Object.entries(op.attributes ?? {});
560
+ const rels = Object.entries(op.relationships ?? {});
561
+ if (op.dataType) lines.push("", `Body → \`data.type: ${op.dataType}\``);
562
+ if (attrs.length) {
563
+ lines.push("", "Attributes:");
564
+ for (const [name, f] of attrs) {
565
+ const kind = f.enum ? f.enum.join("|") : f.type ?? "";
566
+ lines.push(` - ${name} ${kind}${f.required ? " (required)" : ""}`);
567
+ }
568
+ }
569
+ if (rels.length) {
570
+ lines.push("", "Relationships:");
571
+ for (const [name, r] of rels) lines.push(` - ${name} → ${r.target ?? "?"}${r.many ? "[]" : ""}${r.required ? " (required)" : ""}`);
572
+ }
573
+ if (op.query?.length) lines.push("", `Query: ${op.query.map((q) => `\`${q}\``).join(", ")}`);
574
+ lines.push("", "Example:", ` ${exampleInvocation(method, path, op)}`);
575
+ return lines.join("\n");
576
+ }
577
+ function renderAscDocs(query, verb) {
578
+ const idx = readCachedIndex();
579
+ const header = `App Store Connect API — spec ${idx.specVersion}\n`;
580
+ if (!query.trim()) {
581
+ const roots = /* @__PURE__ */ new Set();
582
+ for (const tmpl of Object.keys(idx.paths)) if (segments(tmpl).length === 2) roots.add(tmpl);
583
+ const list = [...roots].sort();
584
+ return `${header}\n${list.length} top-level resources. Run \`asc docs <path> [verb]\` for a schema, or \`asc docs <search term>\` to filter.
585
+
586
+ ` + list.join("\n");
587
+ }
588
+ if (query.startsWith("/")) {
589
+ const concrete = segments(query);
590
+ const out = [];
591
+ for (const [tmpl, ops] of Object.entries(idx.paths)) {
592
+ if (!matches(segments(tmpl), concrete)) continue;
593
+ for (const [method, op] of Object.entries(ops)) {
594
+ if (verb && method !== verb.toLowerCase()) continue;
595
+ out.push(renderOp(method, tmpl, op));
596
+ }
597
+ }
598
+ if (!out.length) return `${header}\nNo operation matches ${query}. Try \`asc docs <search term>\`.`;
599
+ return `${header}\n${out.join("\n\n")}`;
600
+ }
601
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
602
+ const hits = [];
603
+ for (const [tmpl, ops] of Object.entries(idx.paths)) for (const [method, op] of Object.entries(ops)) {
604
+ const hay = `${tmpl} ${op.summary ?? ""} ${op.opId ?? ""}`.toLowerCase();
605
+ if (!terms.every((t) => hay.includes(t))) continue;
606
+ const replaced = selectReplacement(method, tmpl);
607
+ hits.push(`${method.toUpperCase().padEnd(6)} ${tmpl}${op.summary ? ` — ${op.summary}` : ""}${replaced ? ` ⚠ replaced: use ${replaced.use}` : ""}`);
608
+ }
609
+ if (!hits.length) return `${header}\nNothing matches "${query}".`;
610
+ return `${header}\n${hits.slice(0, 60).join("\n")}${hits.length > 60 ? `\n… ${hits.length - 60} more` : ""}\n\nRun \`asc docs <path> [verb]\` for a full schema.`;
611
+ }
612
+ async function runAscDocs(ctx, { args, flags }) {
613
+ const [first = "", second] = args.query;
614
+ const path = first.startsWith("/");
615
+ const query = path ? first : args.query.join(" ");
616
+ const verb = path ? second : void 0;
617
+ if (flags.refresh && flags.quiet) {
618
+ writeCachedIndex(await downloadAscIndex());
619
+ if (!query) return;
620
+ } else if (flags.refresh) {
621
+ const index = await apiCall(ctx, "Updating App Store Connect schema", () => downloadAscIndex());
622
+ writeCachedIndex(index);
623
+ if (!query && ctx.json) return ctx.output.data({ specVersion: index.specVersion });
624
+ if (!query) return void process.stdout.write(`App Store Connect schema updated — spec ${index.specVersion}\n`);
625
+ }
626
+ await ensureAscIndex(ctx);
627
+ const md = renderAscDocs(query, verb);
628
+ if (ctx.json) return ctx.output.data({ markdown: md });
629
+ process.stdout.write(`${md}\n`);
630
+ }
631
+
632
+ //#endregion
633
+ //#region src/core/app-store-connect/api/request.ts
634
+ async function ensureAscIndex(ctx) {
635
+ const cached = findCachedIndex();
636
+ if (!cached) {
637
+ writeCachedIndex(await apiCall(ctx, "Fetching App Store Connect schema", () => downloadAscIndex()));
638
+ return;
639
+ }
640
+ if (indexIsStale(cached)) refreshInBackground();
641
+ }
642
+ async function resolveAscOrgApi(ctx) {
643
+ return ctx.api.forOrg(await pickOrganization(ctx, ctx.api));
644
+ }
645
+ async function resolveAscTeam(ctx, api, team) {
646
+ if (team) return team;
647
+ const configs = await apiCall(ctx, "Finding App Store Connect", () => listAscConfigs(api));
648
+ const [first] = configs;
649
+ if (!first) throw new Error("App Store Connect isn't connected. Run `superwall asc keys create --help`.");
650
+ if (configs.length > 1) {
651
+ const teams = configs.map((c) => String(c.team_id ?? c.id ?? "")).join(", ");
652
+ throw new Error(`Multiple App Store Connect teams (${teams}). Pass --team <id>.`);
653
+ }
654
+ return String(first.team_id ?? first.id ?? "");
655
+ }
656
+ async function sendAscRequest(ctx, verb, path, options) {
657
+ const api = await resolveAscOrgApi(ctx);
658
+ if (!path.startsWith("/")) throw new Error(`Path must start with "/", e.g. /v1/apps`);
659
+ const replaced = selectReplacement(verb, path);
660
+ if (replaced) ctx.ui.warn(formatReplacement(replaced));
661
+ let body = parseParams(options.data);
662
+ if (verb === "post" || verb === "patch") {
663
+ await ensureAscIndex(ctx);
664
+ const found = lookupAscOp(verb, path);
665
+ if (found) {
666
+ body = buildAscBody(found.op, verb, path, body);
667
+ const problems = validateAscBody(found.op, verb, body);
668
+ if (problems.length && !options.force) throw new Error(`Invalid ${verb.toUpperCase()} ${path} body:\n` + problems.map((p) => ` • ${p}`).join("\n") + `\nFix and retry, run \`superwall asc docs ${path} ${verb}\`, or pass --force to send as-is.`);
669
+ }
670
+ }
671
+ const teamId = await resolveAscTeam(ctx, api, options.team);
672
+ return apiCall(ctx, `${verb.toUpperCase()} ${path}`, () => ascProxy(api, teamId, verb, path, body));
673
+ }
674
+
675
+ //#endregion
676
+ //#region src/core/app-store-connect/apple-web/apps.ts
677
+ function readApps(body) {
678
+ return listField(body, "data").flatMap((app) => {
679
+ const id = textField(app, "id");
680
+ if (!id) return [];
681
+ const attributes = field(app, "attributes");
682
+ return [{
683
+ id,
684
+ name: textField(attributes, "name"),
685
+ bundleId: textField(attributes, "bundleId")
686
+ }];
687
+ });
688
+ }
689
+ async function listApps(session) {
690
+ return readApps(await session.iris("GET", "/apps", { query: { limit: "200" } }));
691
+ }
692
+ async function findApp(session, bundleId) {
693
+ return readApps(await session.iris("GET", "/apps", { query: {
694
+ "filter[bundleId]": bundleId,
695
+ limit: "10"
696
+ } })).find((app) => app.bundleId === bundleId);
697
+ }
698
+
699
+ //#endregion
700
+ //#region src/core/app-store-connect/superwall-app.ts
701
+ const NEW_APP = "__new__";
702
+ const LISTED_APPS = 8;
703
+ const isIos = (app) => (app.platform ?? "").toLowerCase() === "ios";
704
+ async function reachIosApp(api, ref, scoped, project) {
705
+ const found = await findApplication(api, ref, scoped);
706
+ if (!found || !isIos(found.app)) return void 0;
707
+ return project === void 0 || String(found.project.id) === project ? found : void 0;
708
+ }
709
+ async function listIosApps(ctx, api, flags) {
710
+ const projects = await apiCall(ctx, "Loading your apps", () => listProjects(api));
711
+ const scoped = flags.project ? projects.filter((project) => String(project.id) === flags.project) : projects;
712
+ if (flags.project && scoped.length === 0) throw new Error(`No project ${flags.project} in this organization.`);
713
+ const candidates = scoped.flatMap((project) => (project.applications ?? []).filter(isIos).map((app) => ({
714
+ project,
715
+ app
716
+ })));
717
+ if (!flags.app) return {
718
+ scoped,
719
+ candidates
720
+ };
721
+ const named = candidates.find(({ app }) => String(app.id) === flags.app || app.name === flags.app) ?? await reachIosApp(api, flags.app, scoped, flags.project);
722
+ if (!named) throw new Error(`No iOS app ${flags.app} in this organization.`);
723
+ return {
724
+ scoped,
725
+ candidates,
726
+ named
727
+ };
728
+ }
729
+ function severalApps(candidates) {
730
+ const shown = candidates.slice(0, LISTED_APPS).map(({ app }) => `${app.id} (${app.name ?? "unnamed"})`).join(", ");
731
+ const more = candidates.length > LISTED_APPS ? `, and ${candidates.length - LISTED_APPS} more (\`superwall apps\` lists them all)` : "";
732
+ return /* @__PURE__ */ new Error(`Several iOS apps found: ${shown}${more}. Pass --app <id>.`);
733
+ }
734
+ const appOptions = (candidates) => candidates.map(({ app, project }) => ({
735
+ value: String(app.id),
736
+ label: app.name ?? String(app.id),
737
+ hint: app.bundle_id ?? project.name
738
+ }));
739
+ async function chooseIosApp(ctx, api, flags) {
740
+ const { candidates, named } = await listIosApps(ctx, api, flags);
741
+ if (named) return named;
742
+ const [first] = candidates;
743
+ if (!first) throw new Error("There's no iOS app in Superwall yet. Create one with `superwall apps create`, or run `superwall setup apple`.");
744
+ if (candidates.length === 1) return first;
745
+ if (!ctx.interactive) throw severalApps(candidates);
746
+ const picked = await ctx.ui.select({
747
+ message: "Which Superwall app?",
748
+ options: appOptions(candidates)
749
+ });
750
+ const found = candidates.find(({ app }) => String(app.id) === picked);
751
+ if (!found) throw new Error("Cancelled.");
752
+ return found;
753
+ }
754
+ async function chooseAppIntent(ctx, api, flags) {
755
+ const { scoped, candidates, named } = await listIosApps(ctx, api, flags);
756
+ if (named) return {
757
+ kind: "existing",
758
+ ...named
759
+ };
760
+ const createIn = scoped.length === 1 ? scoped[0] : void 0;
761
+ if (candidates.length === 0) {
762
+ if (!ctx.interactive && !flags.bundleId) throw new Error("There's no iOS app in Superwall yet. Pass --bundle-id <id> to create one for that App Store Connect app.");
763
+ return {
764
+ kind: "create",
765
+ project: createIn
766
+ };
767
+ }
768
+ if (flags.bundleId) {
769
+ const found$1 = candidates.find(({ app }) => app.bundle_id === flags.bundleId);
770
+ return found$1 ? {
771
+ kind: "existing",
772
+ ...found$1
773
+ } : {
774
+ kind: "create",
775
+ project: createIn
776
+ };
777
+ }
778
+ const [first] = candidates;
779
+ if (!ctx.interactive) {
780
+ if (first && candidates.length === 1) return {
781
+ kind: "existing",
782
+ ...first
783
+ };
784
+ throw severalApps(candidates);
785
+ }
786
+ const picked = await ctx.ui.select({
787
+ message: "Which Superwall app is this for?",
788
+ options: [...appOptions(candidates), {
789
+ value: NEW_APP,
790
+ label: "Create a new iOS app"
791
+ }]
792
+ });
793
+ if (picked === NEW_APP) return {
794
+ kind: "create",
795
+ project: createIn
796
+ };
797
+ const found = candidates.find(({ app }) => String(app.id) === picked);
798
+ if (!found) throw new Error("Cancelled.");
799
+ return {
800
+ kind: "existing",
801
+ ...found
802
+ };
803
+ }
804
+ async function chooseAppleApp(ctx, session, bundleId) {
805
+ const hasBundle = (app) => app.bundleId !== void 0;
806
+ const team = session.team().name;
807
+ if (bundleId) {
808
+ const found$1 = await apiCall(ctx, "Finding the App Store Connect app", () => {
809
+ return findApp(session, bundleId);
810
+ });
811
+ if (found$1 && hasBundle(found$1)) return found$1;
812
+ const others = (await listApps(session)).filter(hasBundle).map((app) => app.bundleId);
813
+ const shown = others.slice(0, LISTED_APPS).join(", ");
814
+ const more = others.length > LISTED_APPS ? `, and ${others.length - LISTED_APPS} more` : "";
815
+ throw new Error(`No App Store Connect app with bundle ID ${bundleId} on the Apple team "${team}". Nothing was created.` + (others.length > 0 ? `\nThis team's apps: ${shown}${more}.` : "\nThis team has no apps yet.") + "\nCheck the bundle ID, sign in with an Apple Account on the right team, or create the app in App Store Connect.");
816
+ }
817
+ const apps = (await apiCall(ctx, "Loading App Store Connect apps", () => listApps(session))).filter(hasBundle);
818
+ if (apps.length === 0) throw new Error(`The Apple team "${team}" has no apps in App Store Connect yet. Create the app there, then run this again.`);
819
+ if (!ctx.interactive) throw new Error(`Pass --bundle-id <id>. This team's apps: ${apps.map((app) => app.bundleId).join(", ")}.`);
820
+ const picked = await ctx.ui.select({
821
+ message: "Which App Store Connect app?",
822
+ options: apps.map((app) => ({
823
+ value: app.id,
824
+ label: app.name ?? app.bundleId,
825
+ hint: app.bundleId
826
+ }))
827
+ });
828
+ const found = apps.find((app) => app.id === picked);
829
+ if (!found) throw new Error("Cancelled.");
830
+ return found;
831
+ }
832
+ async function resolveProjectForNewApp(ctx, api, intent, name) {
833
+ if (intent.project) return String(intent.project.id);
834
+ const projects = await listProjects(api);
835
+ if (projects.length === 0) {
836
+ const organizationId = await orgForNewProject(api, ctx.interactive);
837
+ const created = await apiCall(ctx, "Creating a project", () => {
838
+ return createProject(api, name, organizationId);
839
+ });
840
+ return String(created.id);
841
+ }
842
+ if (!ctx.interactive) throw new Error(`Several projects found: ${projects.map((project) => `${project.id} (${project.name ?? "unnamed"})`).join(", ")}. Pass --project <id>.`);
843
+ const picked = await ctx.ui.select({
844
+ message: "Which project should the new app go in?",
845
+ options: projects.map((project) => ({
846
+ value: String(project.id),
847
+ label: project.name ?? String(project.id)
848
+ }))
849
+ });
850
+ if (picked === null) throw new Error("Cancelled.");
851
+ return picked;
852
+ }
853
+ async function resolveApp(ctx, api, session, intent, flags) {
854
+ if (intent.kind === "existing") {
855
+ const { app, project } = intent;
856
+ const name$1 = app.name ?? String(app.id);
857
+ const saved = savedBundleId(app);
858
+ if (flags.bundleId && saved && flags.bundleId !== saved) throw new Error(differentBundleId(name$1, String(app.id), saved, flags.bundleId));
859
+ const chosen$1 = await chooseAppleApp(ctx, session, flags.bundleId ?? saved ?? void 0);
860
+ return {
861
+ projectId: String(project.id),
862
+ applicationId: String(app.id),
863
+ name: name$1,
864
+ bundleId: chosen$1.bundleId,
865
+ savedBundleId: saved,
866
+ ascAppId: chosen$1.id,
867
+ created: false
868
+ };
869
+ }
870
+ const chosen = await chooseAppleApp(ctx, session, flags.bundleId);
871
+ const name = chosen.name ?? chosen.bundleId;
872
+ const projectId = await resolveProjectForNewApp(ctx, api, intent, name);
873
+ const created = ((await apiCall(ctx, `Creating ${name} in Superwall`, () => {
874
+ return createApplication(api, { projectId }, {
875
+ name,
876
+ platform: "ios",
877
+ bundleId: chosen.bundleId
878
+ });
879
+ })).applications ?? []).filter(isIos).find((app) => app.bundle_id === chosen.bundleId);
880
+ if (!created) throw new Error(`Superwall created ${name} but didn't return it. Nothing was created at Apple. Run this again with --app <id> (\`superwall apps\` lists ids).`);
881
+ return {
882
+ projectId,
883
+ applicationId: String(created.id),
884
+ name,
885
+ bundleId: chosen.bundleId,
886
+ savedBundleId: chosen.bundleId,
887
+ ascAppId: chosen.id,
888
+ created: true
889
+ };
890
+ }
891
+ function savedBundleId(app) {
892
+ const value = app.bundle_id?.trim();
893
+ return value ? value : null;
894
+ }
895
+ function differentBundleId(name, applicationId, saved, wanted) {
896
+ return `\`${name}\` has the bundle ID ${saved} in Superwall, not ${wanted}. Nothing was created or saved. To change it, run \`superwall apps update ${applicationId} --bundle-id ${wanted}\` first, once a person has agreed.`;
897
+ }
898
+
899
+ //#endregion
900
+ //#region src/core/app-store-connect/keys/app.ts
901
+ async function chooseKeyApp(ctx, flags) {
902
+ const chosen = await chooseIosApp(ctx, ctx.api, flags);
903
+ return {
904
+ app: {
905
+ projectId: String(chosen.project.id),
906
+ applicationId: String(chosen.app.id)
907
+ },
908
+ name: chosen.app.name ?? String(chosen.app.id),
909
+ savedBundleId: savedBundleId(chosen.app)
910
+ };
911
+ }
912
+ const savedKey = (saved, kind) => (kind === "api_key" ? saved.app_store_connect_configuration : saved.in_app_purchase_configuration) ?? void 0;
913
+
914
+ //#endregion
915
+ //#region src/core/main/bundle-id.ts
916
+ function testModeExposure(chosen, candidates) {
917
+ const exposed = candidates.filter((candidate) => candidate.production_devices > 0 && candidate.bundle_id !== chosen && !candidate.bundle_id.startsWith(`${chosen}.`));
918
+ return {
919
+ devices: exposed.reduce((sum, candidate) => sum + candidate.production_devices, 0),
920
+ bundleIds: exposed.map((candidate) => candidate.bundle_id)
921
+ };
922
+ }
923
+ async function suggestions(ctx, api, applicationId) {
924
+ try {
925
+ return await apiCall(ctx, "Reading what the SDK reported", () => listBundleIdSuggestions(api, applicationId));
926
+ } catch (error) {
927
+ if (error instanceof RefusedByApi) return null;
928
+ throw error;
929
+ }
930
+ }
931
+ function exposureLine(exposure, windowDays) {
932
+ return `${exposure.devices} production device${exposure.devices === 1 ? "" : "s"} in the last ${windowDays} days used ${exposure.bundleIds.join(", ")}, and would run in test mode.`;
933
+ }
934
+ async function testModeWarning(ctx, api, applicationId, bundleId) {
935
+ const read = await suggestions(ctx, api, applicationId);
936
+ if (!read?.available) return void 0;
937
+ const exposure = testModeExposure(bundleId, read.candidates);
938
+ if (exposure.devices === 0) return void 0;
939
+ return `Saving the bundle ID ${bundleId}: ${exposureLine(exposure, read.window_days)}`;
940
+ }
941
+
942
+ //#endregion
943
+ //#region src/core/app-store-connect/keys/held.ts
944
+ function readKeyFile(path) {
945
+ try {
946
+ return readInput(path);
947
+ } catch {
948
+ return;
949
+ }
950
+ }
951
+ async function upsertHeldKey(ctx, request) {
952
+ const { action, team: teamId, app } = request;
953
+ if (!app && action === "update" && !teamId) throw new Error("Usage: superwall asc keys update --team <team id> --key-id <id> --issuer <id> --key-file <path.p8>");
954
+ if (!app && action === "create" && teamId) throw new Error("To replace a team's key, run `superwall asc keys update --team <team id> ...`.");
955
+ const input = await resolveKeyInput(ctx, request.key, app !== void 0, action);
956
+ if (!input) return void ctx.ui.warn("Cancelled.");
957
+ if (app) return upsertAppKey(ctx, input, action, request.kind ?? "api_key", app);
958
+ const { keyId, issuerId, keyFile, privateKey, accountName } = input;
959
+ if (ctx.dryRun) {
960
+ const plan = {
961
+ dryRun: true,
962
+ action,
963
+ keyId,
964
+ issuerId,
965
+ keyFile,
966
+ ...teamId ? { teamId } : {}
967
+ };
968
+ if (ctx.json) return ctx.output.data(plan);
969
+ ctx.ui.info(`[dry-run] would upload ASC key ${keyId} (issuer ${issuerId}) from ${keyFile}`);
970
+ return;
971
+ }
972
+ const credentials = {
973
+ keyId,
974
+ issuerId,
975
+ privateKey,
976
+ accountName
977
+ };
978
+ const api = request.orgApi ?? await resolveAscOrgApi(ctx);
979
+ const created = await apiCall(ctx, "Connecting App Store Connect", () => {
980
+ if (teamId) return replaceAscConfig(api, teamId, credentials);
981
+ return createAscConfig(api, {
982
+ ...credentials,
983
+ accountName: accountName ?? "App Store Connect"
984
+ });
985
+ });
986
+ if (ctx.json) return ctx.output.data(created);
987
+ ctx.ui.success(`App Store Connect connected ${created.team_id ?? created.id ?? ""}`);
988
+ }
989
+ function purchaseKeyBundleId({ app, name, savedBundleId: saved }, wanted) {
990
+ if (!wanted) {
991
+ if (saved) return {
992
+ bundleId: saved,
993
+ setApplicationBundleId: false
994
+ };
995
+ throw new Error(`\`${name}\` has no bundle ID in Superwall. Pass --bundle-id <id> to save it with the key, or set it first with \`superwall apps update ${app.applicationId} --bundle-id <id>\`.`);
996
+ }
997
+ if (saved && saved !== wanted) throw new Error(differentBundleId(name, app.applicationId, saved, wanted));
998
+ return {
999
+ bundleId: wanted,
1000
+ setApplicationBundleId: saved === null
1001
+ };
1002
+ }
1003
+ async function upsertAppKey(ctx, input, action, kind, flags) {
1004
+ const chosen = await chooseKeyApp(ctx, flags);
1005
+ const { app, name } = chosen;
1006
+ const bundle = kind === "purchase_key" ? purchaseKeyBundleId(chosen, flags.bundleId) : void 0;
1007
+ if (ctx.dryRun) {
1008
+ const plan = {
1009
+ dryRun: true,
1010
+ action,
1011
+ kind,
1012
+ application_id: app.applicationId,
1013
+ keyId: input.keyId,
1014
+ ...bundle ? {
1015
+ bundle_id: bundle.bundleId,
1016
+ set_application_bundle_id: bundle.setApplicationBundleId
1017
+ } : {}
1018
+ };
1019
+ if (ctx.json) return ctx.output.data(plan);
1020
+ const alsoBundle = bundle?.setApplicationBundleId ? ` and its bundle ID ${bundle.bundleId}` : "";
1021
+ ctx.ui.info(`[dry-run] would save ${KEY_LABEL[kind]} ${input.keyId}${alsoBundle} on ${name}`);
1022
+ return;
1023
+ }
1024
+ if (bundle?.setApplicationBundleId) {
1025
+ const warning = await testModeWarning(ctx, ctx.api, app.applicationId, bundle.bundleId);
1026
+ if (warning) ctx.ui.warn(warning);
1027
+ }
1028
+ const credentials = {
1029
+ keyId: input.keyId,
1030
+ issuerId: input.issuerId,
1031
+ privateKey: input.privateKey
1032
+ };
1033
+ const verdict = await apiCall(ctx, `Saving the ${KEY_LABEL[kind]}`, () => {
1034
+ if (!bundle) return replaceAppAscKey(ctx.api, app, credentials);
1035
+ return replaceAppPurchaseKey(ctx.api, app, {
1036
+ ...credentials,
1037
+ ...bundle
1038
+ });
1039
+ });
1040
+ if (ctx.json) ctx.output.data({
1041
+ application_id: app.applicationId,
1042
+ kind,
1043
+ key_id: input.keyId,
1044
+ ...verdict,
1045
+ ...bundle ? {
1046
+ bundle_id: bundle.bundleId,
1047
+ bundle_id_saved: verdict.valid && bundle.setApplicationBundleId
1048
+ } : {}
1049
+ });
1050
+ else if (verdict.valid) ctx.ui.success(bundle?.setApplicationBundleId ? `${KEY_LABEL[kind]} ${input.keyId} and the bundle ID ${bundle.bundleId} saved on \`${name}\`.` : `${KEY_LABEL[kind]} ${input.keyId} saved on \`${name}\`.`);
1051
+ else ctx.ui.error(`Apple didn't accept ${KEY_LABEL[kind]} ${input.keyId}${verdict.error ? `: ${verdict.error}` : "."}`);
1052
+ if (!verdict.valid) ctx.fail();
1053
+ }
1054
+ async function resolveKeyInput(ctx, held, forApp, action) {
1055
+ const { ui, interactive } = ctx;
1056
+ let { keyId, issuer: issuerId, keyFile, name } = held;
1057
+ if (interactive && (!keyId || !issuerId || !keyFile)) {
1058
+ ui.note(forApp ? "You'll need the key's Key ID, its Issuer ID, and the downloaded .p8 file,\nfrom App Store Connect → Users and Access → Integrations." : "Create a key in App Store Connect → Users and Access → Integrations →\nApp Store Connect API. You'll need its Key ID, the Issuer ID, and the\ndownloaded .p8 file. This is stored org-wide for the signed proxy.", forApp ? "Save an Apple key on the app" : "Connect App Store Connect");
1059
+ if (!keyId) {
1060
+ const v = await ui.text({
1061
+ message: "Key ID",
1062
+ placeholder: "2X9R4HXF34",
1063
+ validate: (s) => s?.trim() ? void 0 : "Required"
1064
+ });
1065
+ if (v === null) return null;
1066
+ keyId = v.trim();
1067
+ }
1068
+ if (!issuerId) {
1069
+ const v = await ui.text({
1070
+ message: "Issuer ID",
1071
+ placeholder: "57246542-96fe-1a63-e053-0824d011072a",
1072
+ validate: (s) => s?.trim() ? void 0 : "Required"
1073
+ });
1074
+ if (v === null) return null;
1075
+ issuerId = v.trim();
1076
+ }
1077
+ if (!keyFile) {
1078
+ const v = await ui.text({
1079
+ message: "Path to the .p8 key file",
1080
+ placeholder: "~/Downloads/AuthKey_2X9R4HXF34.p8",
1081
+ validate: (s) => {
1082
+ const path = s?.trim() ?? "";
1083
+ if (!path) return "Required";
1084
+ return readKeyFile(path) === void 0 ? "No file at that path" : void 0;
1085
+ }
1086
+ });
1087
+ if (v === null) return null;
1088
+ keyFile = v.trim();
1089
+ }
1090
+ if (!name && !forApp) {
1091
+ const v = await ui.text({
1092
+ message: "Name (optional)",
1093
+ placeholder: "App Store Connect"
1094
+ });
1095
+ if (v === null) return null;
1096
+ name = v.trim();
1097
+ }
1098
+ }
1099
+ if (!keyId || !issuerId || !keyFile) throw new Error(forApp ? `Usage: superwall asc keys ${action} [api_key | purchase_key] --app <id> --key-id <id> --issuer <id> --key-file <path.p8>` : `Usage: superwall asc keys ${action} --key-id <id> --issuer <id> --key-file <path.p8>${action === "update" ? " --team <id>" : " [--name <name>]"}`);
1100
+ const privateKey = readKeyFile(keyFile);
1101
+ if (privateKey === void 0) throw new Error(`Couldn't find the .p8 key file at ${keyFile}`);
1102
+ return {
1103
+ keyId,
1104
+ issuerId,
1105
+ keyFile,
1106
+ privateKey,
1107
+ ...name ? { accountName: name } : {}
1108
+ };
1109
+ }
1110
+
1111
+ //#endregion
1112
+ export { listKeySources as C, updateServerNotifications as D, updateBundleId as E, useAscRefresh as O, listBundleIdSuggestions as S, replaceRevenueProvider as T, checkServerNotifications as _, chooseAppIntent as a, importAppKey as b, resolveAscOrgApi as c, runAscDocs as d, parseParams as f, RefusedByApi as g, REVENUE_INTEGRATIONS as h, savedKey as i, resolveAscTeam as l, KEY_LABEL as m, testModeWarning as n, chooseIosApp as o, KEY_KINDS as p, chooseKeyApp as r, resolveApp as s, upsertHeldKey as t, sendAscRequest as u, copyAppKey as v, removeAppKey as w, keyKind as x, findIntegrations as y };