@superwall/cli 1.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 (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +201 -0
  3. package/dist/actions-MB-eBY64.js +140 -0
  4. package/dist/api-BF7-toqM.js +151 -0
  5. package/dist/api-output-B5hh0q4V.js +20 -0
  6. package/dist/app-K6j9Es7h.js +189 -0
  7. package/dist/asc-CArSwo5D.js +539 -0
  8. package/dist/asc-products-YQ6Oc6YO.js +93 -0
  9. package/dist/auth-CY2cO_NF.js +139 -0
  10. package/dist/auth.d.ts +30 -0
  11. package/dist/auth.js +4 -0
  12. package/dist/billing-DWyfEQ6l.js +80 -0
  13. package/dist/bind-hslFhcTR.js +213 -0
  14. package/dist/chunk-DQxbwPpZ.js +30 -0
  15. package/dist/command-Kwx4ekbo.js +283 -0
  16. package/dist/create-Bbi8BOO1.js +410 -0
  17. package/dist/dev-D0lQDCQI.js +397 -0
  18. package/dist/devtools-8EgLo86w.js +3638 -0
  19. package/dist/doctor-ByeRdMcl.js +88 -0
  20. package/dist/drivers-DVAZgone.js +413 -0
  21. package/dist/entry.d.ts +9 -0
  22. package/dist/entry.js +495 -0
  23. package/dist/existing-CcJrIIAU.js +88 -0
  24. package/dist/feedback-Z0Wk7VC5.js +73 -0
  25. package/dist/git-3OX9u3xE.js +433 -0
  26. package/dist/hosted-CHwaUqLd.js +32 -0
  27. package/dist/integrate-DqOAqK7J.js +863 -0
  28. package/dist/json-C3hPIMkI.js +7 -0
  29. package/dist/login-Dr8UN_Gx.js +290 -0
  30. package/dist/migrate-D92bJTg6.js +114 -0
  31. package/dist/org-B2gy9Pmu.js +40 -0
  32. package/dist/params-Bvq0iqQK.js +52 -0
  33. package/dist/pipeline-CHHIg6BU.js +1056 -0
  34. package/dist/print-skill-BnZAk7dV.js +74 -0
  35. package/dist/promote-CRe9170G.js +88 -0
  36. package/dist/publish-DsODvrOD.js +35 -0
  37. package/dist/push-BDkZUC0v.js +35 -0
  38. package/dist/query-DIllrSnk.js +53 -0
  39. package/dist/resource-CdP1MDla.js +483 -0
  40. package/dist/resources-CVrWwA1K.js +233 -0
  41. package/dist/run-cGGBUMs5.js +89 -0
  42. package/dist/scan-BQexuUPO.js +236 -0
  43. package/dist/skills-DhuUs28u.js +64 -0
  44. package/dist/skills-xrfXt9u0.js +205 -0
  45. package/dist/spawn-DSoTXy_j.js +69 -0
  46. package/dist/spinner-gOxIMz-V.js +18 -0
  47. package/dist/storekit-Ddvs4Ynw.js +29 -0
  48. package/dist/telemetry-CcfrtXdf.js +204 -0
  49. package/dist/token-DHRH8cxi.js +102 -0
  50. package/dist/ui-C4ncRJqd.js +27703 -0
  51. package/dist/update-BiVeR024.js +137 -0
  52. package/dist/upgrade-DYWspApv.js +72 -0
  53. package/package.json +87 -0
  54. package/prompts/actions/dashboard-setup.xml +10 -0
  55. package/prompts/actions/integrate.xml +5 -0
  56. package/prompts/actions/migrate.xml +11 -0
  57. package/prompts/actions/placements-implement.xml +20 -0
  58. package/prompts/actions/placements-review.xml +18 -0
  59. package/prompts/actions/review-fix.xml +18 -0
  60. package/prompts/actions/review.xml +18 -0
  61. package/prompts/commandments.xml +17 -0
  62. package/prompts/context.xml +9 -0
  63. package/skills/README.md +118 -0
  64. package/skills/superwall-dashboard/SKILL.md +81 -0
  65. package/skills/superwall-dashboard/references/setup.md +101 -0
  66. package/skills/superwall-integrate/SKILL.md +76 -0
  67. package/skills/superwall-integrate/references/expo.md +269 -0
  68. package/skills/superwall-integrate/references/flutter.md +285 -0
  69. package/skills/superwall-integrate/references/ios.md +314 -0
  70. package/skills/superwall-integrate/references/react-native.md +245 -0
  71. package/skills/superwall-migrate/SKILL.md +83 -0
  72. package/skills/superwall-migrate/references/adapty.md +229 -0
  73. package/skills/superwall-migrate/references/qonversion.md +227 -0
  74. package/skills/superwall-migrate/references/revenuecat.md +414 -0
  75. package/skills/superwall-placements/SKILL.md +73 -0
  76. package/skills/superwall-placements/references/expo.md +161 -0
  77. package/skills/superwall-placements/references/flutter.md +139 -0
  78. package/skills/superwall-placements/references/ios.md +165 -0
  79. package/skills/superwall-placements/references/react-native.md +145 -0
  80. package/skills/superwall-placements/references/strategy.md +221 -0
  81. package/skills/superwall-review/SKILL.md +75 -0
  82. package/skills/superwall-review/references/expo.md +100 -0
  83. package/skills/superwall-review/references/flutter.md +99 -0
  84. package/skills/superwall-review/references/ios.md +108 -0
  85. package/skills/superwall-review/references/react-native.md +100 -0
@@ -0,0 +1,1056 @@
1
+ import { b as ASSET_HOST, k as VERSION } from "./telemetry-CcfrtXdf.js";
2
+ import { n as ApiError } from "./command-Kwx4ekbo.js";
3
+ import { n as ui } from "./ui-C4ncRJqd.js";
4
+ import { S as pushPaywallVersion, T as versionProducts, a as createHeadlessPaywall, b as promotePaywallVersion, d as listAppPaywalls, g as livePaywall, m as listProjects, u as linkSourceCommit, v as mintSourceAccess, x as pushPaywallAssets, y as platformLabel } from "./resources-CVrWwA1K.js";
5
+ import { _ as writeSnapshot, c as platformFor, d as describeBindings, f as readLock, g as writeBindings, h as writeBinding, n as pushSourceTree, o as writeProjectScaffold, p as removeBinding, s as describePlatforms, t as gitAvailable, u as resolveApps } from "./git-3OX9u3xE.js";
6
+ import { createRequire } from "node:module";
7
+ import pc from "picocolors";
8
+ import * as fs from "node:fs";
9
+ import { globSync, readFileSync, statSync } from "node:fs";
10
+ import { cpus } from "node:os";
11
+ import * as path from "node:path";
12
+ import { join, resolve } from "node:path";
13
+ import { pathToFileURL } from "node:url";
14
+ import fg from "fast-glob";
15
+
16
+ //#region src/core/paywalls/project/types.ts
17
+ const TYPES_FILE = "superwall.d.ts";
18
+ const SUPERSEDED = ["superwall-env.d.ts", "superwall-routes.d.ts"];
19
+ const HEADER = `// Generated by the Superwall CLI. Commit it; don't edit it, and don't delete it.
20
+ // It is what makes \`import hero from "./assets/hero.jpg"\` typecheck and what
21
+ // makes router.push("...") autocomplete and reject typos. \`superwall dev\`
22
+ // rewrites it whenever your app/ directories change.
23
+
24
+ /// <reference types="superwall/assets" />
25
+ `;
26
+ const routeBlock = (names) => [
27
+ "declare module \"superwall/navigation\" {",
28
+ " interface SuperwallRoutes {",
29
+ ...names.map((name) => ` ${JSON.stringify(name)}: true;`),
30
+ " }",
31
+ "}",
32
+ "",
33
+ "export type SuperwallRouteName = keyof import(\"superwall/navigation\").SuperwallRoutes;"
34
+ ].join("\n");
35
+ const isStripeIdentifier = (identifier) => /^(test|live):price_[^:]+/.test(identifier);
36
+ const productBlock = (references, stripe) => [
37
+ "declare module \"superwall/hooks\" {",
38
+ " interface SuperwallProducts {",
39
+ ...references.map((name) => ` ${JSON.stringify(name)}: true;`),
40
+ " }",
41
+ "",
42
+ " interface SuperwallStripeProducts {",
43
+ ...stripe.map((name) => ` ${JSON.stringify(name)}: true;`),
44
+ " }",
45
+ "}"
46
+ ].join("\n");
47
+ const productIdsOf = (surface) => surface.productIds ?? Object.fromEntries(Object.entries(surface.products).map(([reference, id]) => [reference, [id]]));
48
+ const declaredPlatforms = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string") ? value : void 0;
49
+ async function collectProjectDeclarations(framework, root) {
50
+ const declarations = {
51
+ products: {},
52
+ platforms: {}
53
+ };
54
+ if (!framework.studioProject) return declarations;
55
+ try {
56
+ const payload = await framework.studioProject(root);
57
+ for (const surface of payload.surfaces) {
58
+ for (const [reference, ids] of Object.entries(productIdsOf(surface))) declarations.products[reference] = [...new Set([...declarations.products[reference] ?? [], ...ids])];
59
+ if (typeof surface.kind === "string" && typeof surface.id === "string") declarations.platforms[`${surface.kind}/${surface.id}`] = declaredPlatforms(surface.platforms);
60
+ }
61
+ return declarations;
62
+ } catch {
63
+ return declarations;
64
+ }
65
+ }
66
+ function projectTypes(project, products = {}) {
67
+ const names = /* @__PURE__ */ new Set();
68
+ for (const surface of project.surfaces) for (const route of surface.routes) names.add(route.name);
69
+ const sorted = [...names].sort();
70
+ const sortedProducts = Object.keys(products).sort();
71
+ const sortedStripe = sortedProducts.filter((name) => (products[name] ?? []).some((identifier) => isStripeIdentifier(identifier)));
72
+ const blocks = [sorted.length > 0 ? routeBlock(sorted) : "", sortedProducts.length > 0 ? productBlock(sortedProducts, sortedStripe) : ""].filter(Boolean);
73
+ return blocks.length === 0 ? `${HEADER}\nexport {};\n` : `${HEADER}\n${blocks.join("\n\n")}\n`;
74
+ }
75
+ function writeProjectTypes(project, products = {}) {
76
+ const file = path.join(project.superwallDir, TYPES_FILE);
77
+ const next = projectTypes(project, products);
78
+ try {
79
+ if (!fs.existsSync(file) || fs.readFileSync(file, "utf8") !== next) fs.writeFileSync(file, next);
80
+ } catch {
81
+ return;
82
+ }
83
+ for (const name of SUPERSEDED) {
84
+ const stale = path.join(project.superwallDir, name);
85
+ try {
86
+ if (fs.readFileSync(stale, "utf8").includes("Superwall CLI")) fs.rmSync(stale);
87
+ } catch {
88
+ continue;
89
+ }
90
+ }
91
+ }
92
+
93
+ //#endregion
94
+ //#region src/core/paywalls/project/framework.ts
95
+ var FrameworkNotFoundError = class extends Error {
96
+ constructor(dir) {
97
+ super(`No superwall framework found from ${dir}.\nInstall it in the project (\`npm i superwall\` / \`bun add superwall\`) and make sure you run this inside a project with a superwall/ directory.`);
98
+ }
99
+ };
100
+ async function importSubpath(packageDir, subpath) {
101
+ return import(pathToFileURL(createRequire(join(packageDir, "package.json")).resolve(subpath)).href);
102
+ }
103
+ function fn(mod, name, subpath) {
104
+ if (typeof mod !== "object" || mod === null) throw new Error(`superwall ${subpath} did not load as a module`);
105
+ const candidate = mod[name];
106
+ if (typeof candidate !== "function") throw new Error(`This project's superwall version does not export ${name} from ${subpath} — update the project's superwall dependency.`);
107
+ return candidate;
108
+ }
109
+ function resolveFrameworkDir(cwd) {
110
+ for (const anchor of [join(cwd, "superwall", "package.json"), join(cwd, "package.json")]) try {
111
+ return join(createRequire(anchor).resolve("superwall/package.json"), "..");
112
+ } catch {
113
+ continue;
114
+ }
115
+ throw new FrameworkNotFoundError(cwd);
116
+ }
117
+ function frameworkVersion(cwd) {
118
+ try {
119
+ const parsed = JSON.parse(readFileSync(join(resolveFrameworkDir(cwd), "package.json"), "utf8"));
120
+ if (typeof parsed === "object" && parsed !== null) {
121
+ const version = parsed.version;
122
+ if (typeof version === "string" && version !== "") return version;
123
+ }
124
+ } catch {
125
+ return "unknown";
126
+ }
127
+ return "unknown";
128
+ }
129
+ async function loadFramework(cwd) {
130
+ const dir = resolveFrameworkDir(cwd);
131
+ const [discover, build, preview] = await Promise.all([
132
+ importSubpath(dir, "superwall/discover"),
133
+ importSubpath(dir, "superwall/build"),
134
+ importSubpath(dir, "superwall/preview")
135
+ ]);
136
+ const studioProject = typeof preview === "object" && preview !== null && typeof preview.buildStudioProject === "function" ? preview.buildStudioProject : void 0;
137
+ return {
138
+ discoverProject: fn(discover, "discoverProject", "superwall/discover"),
139
+ buildSnapshot: fn(build, "buildSnapshot", "superwall/build"),
140
+ startPreviewServer: fn(preview, "startPreviewServer", "superwall/preview"),
141
+ studioProject
142
+ };
143
+ }
144
+
145
+ //#endregion
146
+ //#region src/core/paywalls/assets.ts
147
+ const assetBaseUrl = (applicationId) => `${ASSET_HOST}/${applicationId}`;
148
+ function requireAssets(built) {
149
+ if (!Array.isArray(built.assets)) throw new AssetSyncError("This project's superwall version builds snapshots without hosted assets — update the project's superwall dependency to push.");
150
+ return built.assets;
151
+ }
152
+ var AssetSyncError = class extends Error {};
153
+ const assetName = (asset) => asset.path.split(/[\\/]/).pop() || asset.fileName;
154
+ function uploadFailure(asset, response) {
155
+ const name = assetName(asset);
156
+ if (!response) return new AssetSyncError(`Couldn't upload ${name} — the asset store is unreachable. Check your network, then push again.`);
157
+ if (response.status === 404 || response.status === 403) return new AssetSyncError(`Couldn't upload ${name} — the asset store rejected the upload with HTTP ${response.status}. That upload URL is issued by Superwall and expires, so this usually means the storage endpoint is misconfigured or unreachable rather than anything wrong with the file.`);
158
+ return new AssetSyncError(`Couldn't upload ${name} — the asset store returned HTTP ${response.status}.`);
159
+ }
160
+ const CACHE_CONTROL = "public, max-age=31536000, immutable";
161
+ const UPLOAD_CONCURRENCY = 4;
162
+ const pool = async (items, limit, work) => {
163
+ const queue = [...items];
164
+ const runners = Array.from({ length: Math.min(limit, queue.length) }, async () => {
165
+ for (let item = queue.shift(); item !== void 0; item = queue.shift()) await work(item);
166
+ });
167
+ await Promise.all(runners);
168
+ };
169
+ async function syncAssets(input) {
170
+ const { api, paywallId, assets } = input;
171
+ const put = input.put ?? fetch;
172
+ const read = input.read ?? ((path$1) => fs.readFileSync(path$1));
173
+ const totalBytes = assets.reduce((total, asset) => total + asset.bytes, 0);
174
+ if (assets.length === 0) return {
175
+ assets: [],
176
+ uploaded: 0,
177
+ uploadedBytes: 0,
178
+ totalBytes: 0
179
+ };
180
+ const resolved = await pushPaywallAssets(api, paywallId, assets.map((asset) => ({
181
+ sha256: asset.sha256,
182
+ bytes: asset.bytes,
183
+ mime: asset.mime,
184
+ file_name: asset.fileName
185
+ }))).catch((error) => {
186
+ if (error instanceof ApiError && error.status === 404) throw new AssetSyncError("This Superwall environment does not support hosted assets yet. Keep every asset under 32 kB so the snapshot can inline it, or upgrade the platform.");
187
+ throw error;
188
+ });
189
+ const bySha = new Map(resolved.map((entry) => [entry.sha256, entry]));
190
+ const missing = [];
191
+ const hosted = /* @__PURE__ */ new Map();
192
+ for (const asset of assets) {
193
+ const entry = bySha.get(asset.sha256);
194
+ if (!entry) throw new AssetSyncError(`Superwall did not return a URL for ${assetName(asset)} — asset sync is incomplete.`);
195
+ if (!entry.url.endsWith(`/${asset.fileName}`)) throw new AssetSyncError(`Superwall hosted ${asset.fileName} at ${entry.url}, which does not match the URL baked into the snapshot. Delete superwall.lock and push again to rebind this paywall.`);
196
+ hosted.set(asset.sha256, entry.url);
197
+ if (entry.uploadUrl !== void 0) missing.push(asset);
198
+ }
199
+ let uploadedBytes = 0;
200
+ await pool(missing, UPLOAD_CONCURRENCY, async (asset) => {
201
+ const uploadUrl = bySha.get(asset.sha256)?.uploadUrl;
202
+ if (uploadUrl === void 0) return;
203
+ const body = read(asset.path);
204
+ const send = () => put(uploadUrl, {
205
+ method: "PUT",
206
+ headers: {
207
+ "content-type": asset.mime,
208
+ "cache-control": CACHE_CONTROL
209
+ },
210
+ body: new Uint8Array(body)
211
+ });
212
+ let response = await send().catch(() => void 0);
213
+ if (!response?.ok) response = await send().catch(() => void 0);
214
+ if (!response?.ok) throw uploadFailure(asset, response);
215
+ uploadedBytes += asset.bytes;
216
+ });
217
+ return {
218
+ assets: assets.map((asset) => ({
219
+ url: hosted.get(asset.sha256) ?? "",
220
+ mime_type: asset.mime
221
+ })),
222
+ uploaded: missing.length,
223
+ uploadedBytes,
224
+ totalBytes
225
+ };
226
+ }
227
+
228
+ //#endregion
229
+ //#region src/core/paywalls/binding/binding.ts
230
+ var BindingError = class extends Error {};
231
+ const describe = (surface) => `${surface.kind} \`${surface.id}\``;
232
+ const humanize = (surfaceId) => surfaceId.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
233
+ async function resolveBinding(input) {
234
+ const { api, superwallDir, surface, app } = input;
235
+ const { platform, applicationId } = app;
236
+ const create = input.create ?? true;
237
+ const lock = readLock(superwallDir);
238
+ const section = surface.kind === "paywall" ? lock.paywalls : lock.funnels;
239
+ const locked = section[surface.id]?.[platform];
240
+ if (locked) return {
241
+ paywallId: locked.paywallId,
242
+ applicationId,
243
+ platform,
244
+ source: "lock"
245
+ };
246
+ const matches = (paywalls) => {
247
+ const headless = paywalls.filter((paywall) => paywall.metadata.headless === "true");
248
+ return headless.find((paywall) => paywall.metadata.headlessSurface === surface.id) ?? headless.find((paywall) => paywall.identifier === surface.id);
249
+ };
250
+ const match = matches(await listAppPaywalls(api, applicationId));
251
+ if (match) {
252
+ writeBinding(superwallDir, surface.kind, surface.id, platform, { paywallId: match.id });
253
+ return {
254
+ paywallId: match.id,
255
+ applicationId,
256
+ platform,
257
+ source: "matched"
258
+ };
259
+ }
260
+ if (!create) throw new BindingError(`${describe(surface)} has never been pushed to \`${platform}\` — run \`superwall push\` first.`);
261
+ if (!input.renamesResolved) {
262
+ const onDisk = new Set(input.surfaces.filter((candidate) => candidate.kind === surface.kind).map((c) => c.id));
263
+ const orphans = Object.keys(section).filter((id) => !onDisk.has(id));
264
+ if (orphans.length > 0) throw new BindingError(`\`${surface.id}\` is unbound while superwall.lock still binds ${orphans.join(", ")}, which no longer exist on disk. Resolve the renames first — \`superwall push\` asks, or declare them with \`--rename <old>=<new>\`.`);
265
+ }
266
+ const archived = matches(await listAppPaywalls(api, applicationId, { archived: true }));
267
+ if (archived) throw new BindingError(`${describe(surface)} matches archived paywall ${archived.id} on \`${platform}\`. Restore it in the dashboard to push to it, or rename the directory.`);
268
+ const created = await createHeadlessPaywall(api, {
269
+ applicationId,
270
+ name: input.name?.trim() || humanize(surface.id),
271
+ identifier: surface.id
272
+ });
273
+ writeBinding(superwallDir, surface.kind, surface.id, platform, { paywallId: created.id });
274
+ return {
275
+ paywallId: created.id,
276
+ applicationId,
277
+ platform,
278
+ source: "created"
279
+ };
280
+ }
281
+
282
+ //#endregion
283
+ //#region src/core/paywalls/binding/targets.ts
284
+ var TargetError = class extends Error {};
285
+ const surfaceKey = (surface) => `${surface.kind}/${surface.id}`;
286
+ const targetLabel = (target, multi) => multi ? `${target.surface.id} · ${target.platform}` : target.surface.id;
287
+ function wantedPlatforms(surfaces, declared) {
288
+ const wanted = /* @__PURE__ */ new Set();
289
+ for (const surface of surfaces) for (const platform of declared[surfaceKey(surface)] ?? []) wanted.add(platform);
290
+ return [...wanted];
291
+ }
292
+ function parsePlatformFlags(value) {
293
+ return (Array.isArray(value) ? value : value === void 0 ? [] : [value]).flatMap((entry) => typeof entry === "string" ? entry.split(",") : []).map((entry) => entry.trim()).filter((entry) => entry.length > 0);
294
+ }
295
+ function planTargets(input) {
296
+ const { surfaces, declared, apps } = input;
297
+ const known = Object.keys(apps);
298
+ const only = (input.only ?? []).map((entry) => {
299
+ const platform = platformFor(apps, entry);
300
+ if (platform === void 0) throw new TargetError(`This project has no app for "${entry}" — its platforms are ${describePlatforms(apps) || "none"} (the keys under \`apps\` in superwall.lock). Declare it in a config.ts with \`platforms: [...]\` to bind one.`);
301
+ return platform;
302
+ });
303
+ const targets = [];
304
+ for (const surface of surfaces) {
305
+ const wanted = declared[surfaceKey(surface)];
306
+ let platforms;
307
+ if (wanted !== void 0) {
308
+ if (wanted.length === 0) throw new TargetError(`${surface.kind} \`${surface.id}\` declares \`platforms: []\` — list at least one, or remove the field.`);
309
+ for (const platform of wanted) if (!(platform in apps)) throw new TargetError(`${surface.kind} \`${surface.id}\` targets \`${platform}\`, which superwall.lock does not bind to an app.`);
310
+ platforms = [...new Set(wanted)];
311
+ } else if (known.length === 1 && known[0] !== void 0) platforms = [known[0]];
312
+ else if (known.length === 0) throw new TargetError("This project is not bound to an app yet — run `superwall push` to pick one.");
313
+ else throw new TargetError(`${surface.kind} \`${surface.id}\` doesn't say which platforms it's for, and this project pushes to several (${describePlatforms(apps)}). Add \`platforms: [...]\` to ${surface.kind}s/${surface.id}/config.ts.`);
314
+ for (const platform of platforms) {
315
+ if (only.length > 0 && !only.includes(platform)) continue;
316
+ const applicationId = apps[platform];
317
+ if (applicationId === void 0) continue;
318
+ targets.push({
319
+ surface,
320
+ platform,
321
+ applicationId
322
+ });
323
+ }
324
+ }
325
+ if (targets.length === 0 && only.length > 0) throw new TargetError(`No paywall or funnel targets ${only.map((platform) => `\`${platform}\``).join(", ")}.`);
326
+ return targets;
327
+ }
328
+
329
+ //#endregion
330
+ //#region src/core/paywalls/products.ts
331
+ const SYMBOLS = {
332
+ USD: "$",
333
+ CAD: "$",
334
+ AUD: "$",
335
+ NZD: "$",
336
+ EUR: "€",
337
+ GBP: "£",
338
+ JPY: "¥",
339
+ CNY: "¥",
340
+ INR: "₹",
341
+ KRW: "₩",
342
+ BRL: "R$",
343
+ MXN: "$",
344
+ CHF: "CHF",
345
+ SEK: "kr",
346
+ NOK: "kr",
347
+ DKK: "kr",
348
+ PLN: "zł",
349
+ TRY: "₺",
350
+ RUB: "₽",
351
+ ZAR: "R"
352
+ };
353
+ const MINOR = 100;
354
+ const PER_YEAR = {
355
+ day: 365,
356
+ week: 52,
357
+ month: 12,
358
+ year: 1
359
+ };
360
+ const symbolFor = (currency) => SYMBOLS[currency.toUpperCase()] ?? "";
361
+ const money = (amount, currency) => {
362
+ try {
363
+ return new Intl.NumberFormat("en-US", {
364
+ style: "currency",
365
+ currency
366
+ }).format(amount);
367
+ } catch {
368
+ return `${symbolFor(currency)}${amount.toFixed(2)}`;
369
+ }
370
+ };
371
+ const PERIODLY = {
372
+ day: "daily",
373
+ week: "weekly",
374
+ month: "monthly",
375
+ year: "yearly"
376
+ };
377
+ const productVariables = (product) => {
378
+ const variables = {};
379
+ if (product.identifier) variables.identifier = product.identifier;
380
+ const price = product.price;
381
+ if (!price || typeof price.amount !== "number" || !price.currency) return variables;
382
+ const currency = price.currency.toUpperCase();
383
+ const value = price.amount / MINOR;
384
+ variables.price = money(value, currency);
385
+ variables.rawPrice = value;
386
+ variables.currencyCode = currency;
387
+ variables.currencySymbol = symbolFor(currency);
388
+ const period = product.subscription?.period;
389
+ if (!period) return variables;
390
+ const count = product.subscription?.period_count ?? 1;
391
+ variables.period = period;
392
+ variables.periodly = PERIODLY[period] ?? `${period}ly`;
393
+ variables[`period${period.charAt(0).toUpperCase()}${period.slice(1)}s`] = count;
394
+ const perYear = (PER_YEAR[period] ?? 1) / count;
395
+ variables.yearlyPrice = money(value * perYear, currency);
396
+ variables.monthlyPrice = money(value * perYear / 12, currency);
397
+ variables.weeklyPrice = money(value * perYear / 52, currency);
398
+ variables.dailyPrice = money(value * perYear / 365, currency);
399
+ const trialDays = product.subscription?.trial_period_days;
400
+ if (typeof trialDays === "number" && trialDays > 0) {
401
+ variables.trialPeriodDays = trialDays;
402
+ variables.trialPeriodText = `${trialDays}-day`;
403
+ }
404
+ return variables;
405
+ };
406
+ async function fetchProducts(api, projectId) {
407
+ const rows = await api.list(`/v2/products?project_id=${encodeURIComponent(projectId)}`);
408
+ const catalogue = {};
409
+ for (const row of rows) if (row.identifier) catalogue[row.identifier] = productVariables(row);
410
+ return catalogue;
411
+ }
412
+ async function projectForApplication(api, applicationId) {
413
+ const owner = (await listProjects(api).catch(() => [])).find((project) => (project.applications ?? []).some((app) => String(app.id) === applicationId));
414
+ return owner ? String(owner.id) : void 0;
415
+ }
416
+ var MissingProductError = class extends Error {};
417
+ function requireProducts(catalogue, surfaces) {
418
+ const gaps = surfaces.flatMap((surface) => Object.entries(surface.products ?? {}).filter(([, identifier]) => catalogue[identifier] === void 0).map(([reference, identifier]) => ` ${surface.id}: ${reference} → ${identifier}`));
419
+ if (gaps.length === 0) return;
420
+ throw new MissingProductError([
421
+ gaps.length === 1 ? "This product does not exist on Superwall:" : `These ${gaps.length} products do not exist on Superwall:`,
422
+ ...gaps,
423
+ "",
424
+ "Every variable on them would be undefined on device. Add them in the",
425
+ "dashboard, or point the config at products that exist."
426
+ ].join("\n"));
427
+ }
428
+
429
+ //#endregion
430
+ //#region src/core/paywalls/source/portability.ts
431
+ const SHOWN = 5;
432
+ function portabilityWarning(external) {
433
+ const names = [...new Set(external)].filter((entry) => entry.trim() !== "").sort();
434
+ if (names.length === 0) return void 0;
435
+ const shown = names.slice(0, SHOWN).join(", ");
436
+ const rest = names.length - SHOWN;
437
+ return `${names.length} ${names.length === 1 ? "import resolves" : "imports resolve"} outside superwall/ (${shown}${rest > 0 ? `, and ${rest} more` : ""}) — this project can be edited locally only; remote editing and rebuilds won't be available. For full feature access, move them into superwall/components/ or install from a package registry.`;
438
+ }
439
+ function warnNotPortable(external) {
440
+ const message = portabilityWarning(external);
441
+ if (message) ui.warn(message);
442
+ }
443
+
444
+ //#endregion
445
+ //#region src/core/paywalls/source/source.ts
446
+ const HARD_EXCLUDES = [
447
+ ".superwall/**",
448
+ "**/node_modules/**",
449
+ ".git/**",
450
+ "**/.env*",
451
+ "**/.DS_Store"
452
+ ];
453
+ function gitignoreExcludes(superwallDir) {
454
+ let text;
455
+ try {
456
+ text = fs.readFileSync(path.join(superwallDir, ".gitignore"), "utf8");
457
+ } catch {
458
+ return [];
459
+ }
460
+ const excludes = [];
461
+ for (const raw of text.split("\n")) {
462
+ const line = raw.trim();
463
+ if (line === "" || line.startsWith("#") || line.startsWith("!")) continue;
464
+ const anchored = line.startsWith("/");
465
+ const body = (anchored ? line.slice(1) : line).replace(/\/+$/, "");
466
+ if (body === "") continue;
467
+ const base = anchored || body.includes("/") ? body : `**/${body}`;
468
+ excludes.push(base, `${base}/**`);
469
+ }
470
+ return excludes;
471
+ }
472
+ async function collectSourceFiles(superwallDir) {
473
+ const entries = await fg("**/*", {
474
+ cwd: superwallDir,
475
+ dot: true,
476
+ onlyFiles: true,
477
+ followSymbolicLinks: false,
478
+ ignore: [...HARD_EXCLUDES, ...gitignoreExcludes(superwallDir)]
479
+ });
480
+ if (entries.length === 0) return {
481
+ ok: false,
482
+ reason: `No source files found in ${superwallDir}.`
483
+ };
484
+ return {
485
+ ok: true,
486
+ files: entries.sort().map((relative$1) => ({
487
+ path: relative$1,
488
+ content: fs.readFileSync(path.join(superwallDir, relative$1))
489
+ }))
490
+ };
491
+ }
492
+
493
+ //#endregion
494
+ //#region src/core/paywalls/source/source-push.ts
495
+ var GitRequiredError = class extends Error {
496
+ constructor() {
497
+ super("superwall publish requires git for the source step — install git");
498
+ }
499
+ };
500
+ async function pushSource(input) {
501
+ if (!await (input.hasGit ?? gitAvailable)()) throw new GitRequiredError();
502
+ for (let attempt = 0;; attempt++) {
503
+ const access = await mintSourceAccess(input.api, input.paywallId);
504
+ const pushed = await pushSourceTree({
505
+ access,
506
+ files: input.files,
507
+ message: {
508
+ kind: input.kind,
509
+ surface: input.surface,
510
+ version: input.version,
511
+ paywallId: input.paywallId,
512
+ applicationId: input.applicationId,
513
+ snapshotSha: input.snapshotId,
514
+ framework: input.framework,
515
+ cli: input.cli,
516
+ note: input.note,
517
+ external: input.external
518
+ }
519
+ });
520
+ try {
521
+ await linkSourceCommit(input.api, input.paywallId, input.version, {
522
+ commitSha: pushed.commitSha,
523
+ tokenId: access.tokenId
524
+ });
525
+ return pushed;
526
+ } catch (error) {
527
+ if (attempt === 0 && worthRetrying(error)) continue;
528
+ throw error;
529
+ }
530
+ }
531
+ }
532
+ const worthRetrying = (error) => error instanceof ApiError && (error.status === 409 || error.status === 400);
533
+
534
+ //#endregion
535
+ //#region src/core/paywalls/binding/renames.ts
536
+ var RenameError = class extends Error {};
537
+ function parseRenameFlags(value) {
538
+ return (value === void 0 ? [] : Array.isArray(value) ? value : [value]).map((entry) => {
539
+ const text = typeof entry === "string" ? entry.trim() : "";
540
+ const at = text.indexOf("=");
541
+ const from = at === -1 ? "" : text.slice(0, at).trim();
542
+ const to = at === -1 ? "" : text.slice(at + 1).trim();
543
+ if (!from || !to) throw new RenameError(`--rename takes <old>=<new>, e.g. --rename plus-upgrade=pro-upgrade` + (text ? ` (got "${text}")` : ""));
544
+ return {
545
+ from,
546
+ to
547
+ };
548
+ });
549
+ }
550
+ function unresolvedError(orphans, newcomers) {
551
+ return new RenameError([
552
+ "Cannot tell whether these are new or renamed, and this run cannot ask.",
553
+ "",
554
+ "Bound in superwall.lock, but no directory on disk:",
555
+ ...orphans.map((orphan) => ` ${orphan.id} → ${describeBindings(orphan.bindings)}`),
556
+ "On disk, but not in superwall.lock:",
557
+ ...newcomers.map((newcomer) => ` ${newcomer.id}`),
558
+ "",
559
+ "Declare each rename, then run again:",
560
+ ...newcomers.flatMap((newcomer) => orphans.map((orphan) => ` --rename ${orphan.id}=${newcomer.id}`)),
561
+ "",
562
+ "If one of these paywalls is genuinely gone, remove its entry from",
563
+ "superwall.lock by hand and run again.",
564
+ "",
565
+ "Refusing to create — the bound paywalls are what production serves."
566
+ ].join("\n"));
567
+ }
568
+ async function resolveRenames(input) {
569
+ const lock = readLock(input.superwallDir);
570
+ const orphans = [];
571
+ const newcomers = [];
572
+ for (const kind of ["paywall", "funnel"]) {
573
+ const section = kind === "paywall" ? lock.paywalls : lock.funnels;
574
+ const onDisk = input.surfaces.filter((surface) => surface.kind === kind);
575
+ const ids = new Set(onDisk.map((surface) => surface.id));
576
+ for (const [id, bindings] of Object.entries(section).sort(([a], [b]) => a.localeCompare(b))) if (!ids.has(id)) orphans.push({
577
+ kind,
578
+ id,
579
+ bindings
580
+ });
581
+ for (const surface of onDisk) if (!(surface.id in section)) newcomers.push(surface);
582
+ }
583
+ const renamed = [];
584
+ const rebind = (orphan, newcomer) => {
585
+ writeBindings(input.superwallDir, newcomer.kind, newcomer.id, orphan.bindings);
586
+ removeBinding(input.superwallDir, orphan.kind, orphan.id);
587
+ renamed.push({
588
+ kind: newcomer.kind,
589
+ from: orphan.id,
590
+ to: newcomer.id,
591
+ bindings: orphan.bindings
592
+ });
593
+ orphans.splice(orphans.indexOf(orphan), 1);
594
+ newcomers.splice(newcomers.indexOf(newcomer), 1);
595
+ };
596
+ for (const declaration of input.declared ?? []) {
597
+ const newcomer = newcomers.find((candidate) => candidate.id === declaration.to);
598
+ if (!newcomer) throw new RenameError(`--rename ${declaration.from}=${declaration.to}: no unbound directory named "${declaration.to}".`);
599
+ const orphan = orphans.find((candidate) => candidate.id === declaration.from && candidate.kind === newcomer.kind);
600
+ if (!orphan) throw new RenameError(`--rename ${declaration.from}=${declaration.to}: superwall.lock has no ${newcomer.kind} "${declaration.from}" waiting to be renamed.`);
601
+ rebind(orphan, newcomer);
602
+ }
603
+ for (const newcomer of [...newcomers]) {
604
+ const candidates = orphans.filter((orphan) => orphan.kind === newcomer.kind);
605
+ if (candidates.length === 0) continue;
606
+ if (!input.choose) throw unresolvedError(candidates, [newcomer]);
607
+ const decision = await input.choose({
608
+ newcomer,
609
+ orphans: candidates
610
+ });
611
+ if (decision.kind === "rename") {
612
+ const orphan = candidates.find((candidate) => candidate.id === decision.orphanId);
613
+ if (!orphan) throw new RenameError(`No pending rename candidate named "${decision.orphanId}".`);
614
+ rebind(orphan, newcomer);
615
+ }
616
+ }
617
+ const dropped = [];
618
+ const kept = [];
619
+ for (const orphan of orphans) {
620
+ if (!input.chooseStale) {
621
+ input.notice?.(`\`${orphan.id}\` is still bound to ${describeBindings(orphan.bindings)} but no longer exists on disk — remove it from superwall.lock if that paywall is gone.`);
622
+ kept.push(orphan);
623
+ continue;
624
+ }
625
+ if (await input.chooseStale(orphan) === "remove") {
626
+ removeBinding(input.superwallDir, orphan.kind, orphan.id);
627
+ dropped.push(orphan);
628
+ } else kept.push(orphan);
629
+ }
630
+ return {
631
+ renamed,
632
+ stale: kept,
633
+ dropped
634
+ };
635
+ }
636
+
637
+ //#endregion
638
+ //#region src/commands/paywalls/pick-app.ts
639
+ async function pickApplicationOption(apps, platform) {
640
+ const picked = await ui.select({
641
+ message: platform ? `Which ${platformLabel(platform)} app do these paywalls push to? The choice is saved under apps in superwall.lock.` : "Which app do these paywalls belong to?",
642
+ options: apps.map((app) => ({
643
+ value: String(app.id),
644
+ label: app.name ?? app.bundle_id ?? String(app.id),
645
+ hint: platformLabel(app.platform)
646
+ }))
647
+ });
648
+ if (!picked) return null;
649
+ return apps.find((app) => String(app.id) === picked) ?? null;
650
+ }
651
+
652
+ //#endregion
653
+ //#region src/commands/paywalls/pick-rename.ts
654
+ const CREATE = "__create__";
655
+ async function pickRenameOption(input) {
656
+ const picked = await ui.select({
657
+ message: `\`${input.newcomer.id}\` is not in superwall.lock. Is it a new ${input.newcomer.kind}, or renamed?`,
658
+ options: [...input.orphans.map((orphan) => ({
659
+ value: orphan.id,
660
+ label: `Renamed from ${orphan.id}`,
661
+ hint: describeBindings(orphan.bindings)
662
+ })), {
663
+ value: CREATE,
664
+ label: `Create a new ${input.newcomer.kind}`
665
+ }]
666
+ });
667
+ if (picked === null) throw new RenameError("Cancelled — superwall.lock is unchanged and nothing was pushed.");
668
+ return picked === CREATE ? { kind: "create" } : {
669
+ kind: "rename",
670
+ orphanId: picked
671
+ };
672
+ }
673
+
674
+ //#endregion
675
+ //#region src/commands/paywalls/pick-stale.ts
676
+ const REMOVE = "__remove__";
677
+ const KEEP = "__keep__";
678
+ async function pickStaleOption(orphan) {
679
+ const picked = await ui.select({
680
+ message: `\`${orphan.id}\` is bound to ${describeBindings(orphan.bindings)} but no longer exists on disk. Removing only forgets it locally — the paywall stays on Superwall, keeps its campaigns, and keeps serving devices.`,
681
+ options: [{
682
+ value: REMOVE,
683
+ label: "Remove the binding",
684
+ hint: "restoring the directory re-binds it on the next push"
685
+ }, {
686
+ value: KEEP,
687
+ label: "Keep it",
688
+ hint: "superwall.lock is left as it is"
689
+ }],
690
+ initialValue: REMOVE
691
+ });
692
+ if (picked === null) throw new RenameError("Cancelled — superwall.lock is unchanged and nothing was pushed.");
693
+ return picked === REMOVE ? "remove" : "keep";
694
+ }
695
+
696
+ //#endregion
697
+ //#region src/commands/paywalls/pipeline.ts
698
+ const kb = (bytes) => `${(bytes / 1024).toFixed(1)} kB`;
699
+ const weight = (bytes) => bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : kb(bytes);
700
+ const SHORT_SHA = 7;
701
+ const shortSha = (sha) => typeof sha === "string" && sha.length >= SHORT_SHA ? sha.slice(0, SHORT_SHA) : void 0;
702
+ function pushedLine(input) {
703
+ const sha = shortSha(input.snapshotId);
704
+ const pushed = `Pushed ${input.promoting ? `version ${input.version}` : pc.yellow(`version ${input.version}`)}${sha ? ` ${pc.dim(`(${sha})`)}` : ""}`;
705
+ return input.promoting || input.live === void 0 ? pushed : `${pushed} · ${pc.dim(`live ${input.live}`)}`;
706
+ }
707
+ function transition(before, after) {
708
+ if (before === void 0) return `Promoted ${pc.green(`version ${after}`)}`;
709
+ if (before === after) return `Version ${pc.green(String(after))} already live`;
710
+ if (after < before) return `Rolled back ${pc.green(`version ${before} → ${after}`)}`;
711
+ return `Promoted ${pc.green(`version ${before} → ${after}`)}`;
712
+ }
713
+ const BIND_VERB = {
714
+ lock: "Linked to",
715
+ matched: "Linked to",
716
+ created: "Created",
717
+ renamed: "Rebound after rename to"
718
+ };
719
+ const LAYOUT_HINT = "expected superwall/{paywalls,funnels}/<id>/ with config.ts and app/index.tsx";
720
+ function projectDir(context) {
721
+ const [first] = projectDirs(context);
722
+ return first ?? process.cwd();
723
+ }
724
+ function projectDirs(context) {
725
+ const raw = context.argv.dir;
726
+ const list = (Array.isArray(raw) ? raw : raw === void 0 ? [] : [raw]).filter((entry) => typeof entry === "string" && entry.length > 0);
727
+ if (list.length === 0) return [process.cwd()];
728
+ const expanded = list.flatMap((entry) => entry.includes("*") ? expandGlob(entry) : [entry]);
729
+ return [...new Set(expanded.map((entry) => resolve(entry)))];
730
+ }
731
+ function expandGlob(pattern) {
732
+ try {
733
+ return [...globSync(pattern)].filter((entry) => statSync(entry, { throwIfNoEntry: false })?.isDirectory() ?? false).sort();
734
+ } catch {
735
+ return [pattern];
736
+ }
737
+ }
738
+ function requireProject(project, dir) {
739
+ if (!project.marker) throw new Error(`Not a superwall project: ${dir}\nExpected a package.json here (or in superwall/) that depends on superwall.`);
740
+ if (project.packageName === "superwall") throw new Error(`${project.superwallDir}/package.json is named "superwall".\nNode resolves every bare \`import "superwall"\` inside a package to that package itself, so the framework can never load. Rename it to your project's name.`);
741
+ return project;
742
+ }
743
+ function parseIds(value) {
744
+ return (Array.isArray(value) ? value : value === void 0 ? [] : [value]).flatMap((entry) => typeof entry === "string" ? entry.split(",") : []).map((entry) => entry.trim()).filter((entry) => entry.length > 0);
745
+ }
746
+ function selectSurfaces(project, ids) {
747
+ const wanted = parseIds(ids);
748
+ const known = project.surfaces.map((surface) => surface.id).join(", ");
749
+ if (wanted.length === 0) {
750
+ if (project.surfaces.length === 0) throw new Error(`No paywalls or funnels found — ${LAYOUT_HINT}.`);
751
+ return [...project.surfaces];
752
+ }
753
+ const selected = [];
754
+ for (const id of wanted) {
755
+ const matches = project.surfaces.filter((surface$1) => surface$1.id === id);
756
+ if (matches.length === 0) throw new Error(`No paywall or funnel named "${id}"` + (known ? ` — this project has: ${known}.` : ` — ${LAYOUT_HINT}.`));
757
+ if (matches.length > 1) {
758
+ const kinds = matches.map((surface$1) => `${surface$1.kind}/${surface$1.id}`).join(" and ");
759
+ throw new Error(`"${id}" is ambiguous — this project has ${kinds}.`);
760
+ }
761
+ const surface = matches[0];
762
+ if (surface && !selected.includes(surface)) selected.push(surface);
763
+ }
764
+ return selected;
765
+ }
766
+ function requireClean(surfaces) {
767
+ const problems = surfaces.flatMap((surface) => surface.diagnostics ?? []);
768
+ if (problems.length === 0) return;
769
+ throw new Error([
770
+ ...problems,
771
+ "",
772
+ "Publishing is immutable — fix these first, then push again."
773
+ ].join("\n"));
774
+ }
775
+ function needsWork(built, pushed, live) {
776
+ return built !== pushed && built !== live;
777
+ }
778
+ async function pooled(items, limit, work) {
779
+ const results = new Array(items.length);
780
+ let cursor = 0;
781
+ const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
782
+ while (cursor < items.length) {
783
+ const index = cursor++;
784
+ const item = items[index];
785
+ if (item === void 0) continue;
786
+ results[index] = await work(item, index);
787
+ }
788
+ });
789
+ await Promise.all(runners);
790
+ return results;
791
+ }
792
+ const NOTE_LIMIT = 2e3;
793
+ const PENDING_NAMES = 10;
794
+ function pendingPromoteWarning(pending, multi = false) {
795
+ if (pending.length === 0) return void 0;
796
+ const entries = pending.map((entry) => typeof entry === "string" ? { id: entry } : entry);
797
+ const ids = [...new Set(entries.map((entry) => entry.id))];
798
+ const platforms = new Set(entries.flatMap((entry) => entry.platform ? [entry.platform] : []));
799
+ const platformFlag = multi && platforms.size === 1 ? ` --platform ${[...platforms][0]}` : "";
800
+ const command = `superwall promote --id ${ids.join(",")}${platformFlag}`;
801
+ const labels = entries.map((entry) => multi && entry.platform ? `${entry.id} · ${entry.platform}` : entry.id);
802
+ if (labels.length === 1) return `${labels[0]} is pushed but not live — run \`${command}\` to publish it.`;
803
+ const shown = labels.slice(0, PENDING_NAMES).map((label) => ` ${label}`);
804
+ const rest = labels.length - shown.length;
805
+ return [
806
+ `These ${labels.length} paywalls are pushed but not live:`,
807
+ ...shown,
808
+ ...rest > 0 ? [` …and ${rest} more`] : [],
809
+ "",
810
+ ` ${command}`
811
+ ].join("\n");
812
+ }
813
+ function resolveNote(message) {
814
+ if (typeof message !== "string") return void 0;
815
+ if (message.length > NOTE_LIMIT) throw new Error(`Publish note is ${message.length} characters (limit ${NOTE_LIMIT}).`);
816
+ return message;
817
+ }
818
+ const took = (since) => {
819
+ const seconds = (Date.now() - since) / 1e3;
820
+ return pc.dim(seconds < 10 ? `(${seconds.toFixed(1)}s)` : `(${Math.round(seconds)}s)`);
821
+ };
822
+ async function timed(work) {
823
+ const at = Date.now();
824
+ return {
825
+ value: await work(),
826
+ took: took(at)
827
+ };
828
+ }
829
+ async function group(context, id, work) {
830
+ const spin = context.outputMode === "rich" ? ui.spinner() : void 0;
831
+ spin?.start(id);
832
+ try {
833
+ const lines = await work((message) => spin?.message(`${id} ${pc.dim(message)}`));
834
+ const block = [pc.bold(id), ...lines].join("\n");
835
+ if (spin) spin.stop(block);
836
+ else ui.info(block);
837
+ } catch (error) {
838
+ if (spin) spin.stop(pc.red(`${id} failed`));
839
+ else ui.info(pc.red(`${id} failed`));
840
+ throw error;
841
+ }
842
+ }
843
+ function summary(outcomes, skipped, promoted) {
844
+ const count = outcomes.length;
845
+ const noun = (n) => n === 1 ? "paywall" : "paywalls";
846
+ const unchanged = skipped > 0 ? ` · ${pc.dim(`${skipped} unchanged`)}` : "";
847
+ if (count === 0) {
848
+ ui.outro(skipped > 0 ? `Nothing to do · ${skipped} unchanged.` : "Nothing to do.");
849
+ return;
850
+ }
851
+ if (promoted) {
852
+ ui.outro(`${pc.green(`${count} ${noun(count)} live`)}${unchanged}.`);
853
+ return;
854
+ }
855
+ ui.outro(`${count} ${noun(count)} pushed${unchanged} · run \`superwall promote\` to publish ${count === 1 ? "it" : "them"}.`);
856
+ }
857
+ const BUILD_CONCURRENCY = Math.max(2, Math.min(8, cpus().length - 1));
858
+ async function prepare(context, input) {
859
+ const { framework, project, surfaces, declared } = input;
860
+ const apps = await resolveApps({
861
+ api: context.api,
862
+ superwallDir: project.superwallDir,
863
+ wanted: wantedPlatforms(surfaces, declared),
864
+ pickApplication: input.interactive ? pickApplicationOption : void 0
865
+ });
866
+ const multi = Object.keys(apps).length > 1;
867
+ const targets = planTargets({
868
+ surfaces,
869
+ declared,
870
+ apps,
871
+ only: parsePlatformFlags(context.argv.platform)
872
+ });
873
+ const spin = context.outputMode === "rich" ? ui.spinner() : void 0;
874
+ const label = targets.length === 1 && targets[0] !== void 0 ? targetLabel(targets[0], multi) : `${targets.length} paywalls`;
875
+ spin?.start(`Building ${label}`);
876
+ const at = Date.now();
877
+ try {
878
+ const builds = await pooled(targets, BUILD_CONCURRENCY, (target) => framework.buildSnapshot(project, target.surface, {
879
+ assetBaseUrl: assetBaseUrl(target.applicationId),
880
+ platform: target.platform
881
+ }));
882
+ const projectIds = /* @__PURE__ */ new Map();
883
+ for (const target of targets) {
884
+ if (projectIds.has(target.applicationId)) continue;
885
+ projectIds.set(target.applicationId, await projectForApplication(context.api, target.applicationId));
886
+ }
887
+ const catalogues = /* @__PURE__ */ new Map();
888
+ for (const projectId of new Set(projectIds.values())) {
889
+ if (projectId === void 0) continue;
890
+ catalogues.set(projectId, await fetchProducts(context.api, projectId));
891
+ }
892
+ for (const [projectId, catalogue] of catalogues) requireProducts(catalogue, targets.flatMap((target, index) => projectIds.get(target.applicationId) === projectId ? [{
893
+ id: target.surface.id,
894
+ products: builds[index]?.products
895
+ }] : []));
896
+ const bindings = [];
897
+ for (const [index, target] of targets.entries()) bindings.push(await resolveBinding({
898
+ api: context.api,
899
+ superwallDir: project.superwallDir,
900
+ surface: target.surface,
901
+ app: {
902
+ platform: target.platform,
903
+ applicationId: target.applicationId
904
+ },
905
+ name: builds[index]?.name,
906
+ surfaces: project.surfaces,
907
+ renamesResolved: true
908
+ }));
909
+ const prepared = await pooled(targets, BUILD_CONCURRENCY, async (target, index) => {
910
+ const bind = bindings[index];
911
+ const build = builds[index];
912
+ if (!bind || !build) throw new Error(`Missing binding for ${target.surface.id}`);
913
+ requireAssets(build);
914
+ const live = await livePaywall(context.api, bind.paywallId);
915
+ const lock = readLock(project.superwallDir);
916
+ const pushed = (target.surface.kind === "paywall" ? lock.paywalls : lock.funnels)[target.surface.id]?.[target.platform]?.snapshot;
917
+ return {
918
+ target,
919
+ bind,
920
+ build,
921
+ live: live.version,
922
+ changed: needsWork(build.snapshotId, pushed, live.snapshotId),
923
+ pending: !needsWork(build.snapshotId, pushed, live.snapshotId) && live.snapshotId !== build.snapshotId
924
+ };
925
+ });
926
+ const modified = prepared.filter((entry) => entry.changed).length;
927
+ spin?.stop(`${pc.bold(`Built ${label}`)} ${pc.dim(`${modified} modified · ${prepared.length - modified} unchanged`)} ${took(at)}`);
928
+ return {
929
+ prepared,
930
+ multi
931
+ };
932
+ } catch (error) {
933
+ spin?.stop(pc.red(`Building ${label} failed`));
934
+ throw error;
935
+ }
936
+ }
937
+ async function runPushPipeline(context, options) {
938
+ const dir = projectDir(context);
939
+ const framework = await (options.load ?? loadFramework)(dir);
940
+ const project = requireProject(framework.discoverProject(dir), dir);
941
+ const installed = frameworkVersion(dir);
942
+ const declarations = await collectProjectDeclarations(framework, project.root);
943
+ writeProjectTypes(project, declarations.products);
944
+ writeProjectScaffold({
945
+ root: project.root,
946
+ superwallDir: project.superwallDir,
947
+ frameworkVersion: installed
948
+ });
949
+ const surfaces = selectSurfaces(project, context.argv.id);
950
+ requireClean(surfaces);
951
+ const publishNote = resolveNote(context.argv.message);
952
+ ui.intro(`Superwall ${pc.dim(`v${VERSION}`)}`);
953
+ const renames = await resolveRenames({
954
+ superwallDir: project.superwallDir,
955
+ surfaces: project.surfaces,
956
+ declared: parseRenameFlags(context.argv.rename),
957
+ choose: context.interactive ? pickRenameOption : void 0,
958
+ chooseStale: context.interactive ? pickStaleOption : void 0,
959
+ notice: (message) => ui.warn(message)
960
+ });
961
+ for (const pair of renames.renamed) ui.step(`${pair.kind}/${pair.to} keeps ${describeBindings(pair.bindings)} (renamed from ${pair.from})`);
962
+ for (const orphan of renames.dropped) ui.step(`${orphan.kind}/${orphan.id} removed from superwall.lock · ${describeBindings(orphan.bindings)} untouched on Superwall`);
963
+ const source = await collectSourceFiles(project.superwallDir);
964
+ const outcomes = [];
965
+ const external = /* @__PURE__ */ new Set();
966
+ const { prepared, multi } = await prepare(context, {
967
+ framework,
968
+ project,
969
+ surfaces,
970
+ declared: declarations.platforms,
971
+ interactive: context.interactive,
972
+ promote: options.promote
973
+ });
974
+ for (const entry of prepared) for (const source$1 of entry.build.externalSources ?? []) external.add(source$1);
975
+ const changed = prepared.filter((entry) => entry.changed);
976
+ const skipped = prepared.length - changed.length;
977
+ const pendingHint = pendingPromoteWarning((options.promote ? prepared.filter((entry) => entry.pending) : []).map((entry) => ({
978
+ id: entry.target.surface.id,
979
+ platform: entry.target.platform
980
+ })), multi);
981
+ if (pendingHint) ui.warn(pendingHint);
982
+ for (const { target, bind, build, live: wasLive } of changed) {
983
+ const { surface } = target;
984
+ let version = 0;
985
+ let live = false;
986
+ await group(context, targetLabel(target, multi), async (note) => {
987
+ const lines = [];
988
+ const assets = requireAssets(build);
989
+ lines.push(`${BIND_VERB[bind.source]} paywall ${bind.paywallId}`);
990
+ lines.push(assets.length > 0 ? `Built ${pc.dim(`${kb(build.bytes)} html + ${weight(build.assetBytes ?? 0)} assets`)}` : `Built ${pc.dim(`${kb(build.bytes)} · ${build.snapshotId.slice(0, 8)}`)}`);
991
+ note("Syncing assets");
992
+ const synced = await timed(() => syncAssets({
993
+ api: context.api,
994
+ paywallId: bind.paywallId,
995
+ assets
996
+ }));
997
+ if (assets.length > 0) {
998
+ const noun = assets.length === 1 ? "asset" : "assets";
999
+ lines.push(synced.value.uploaded > 0 ? `${assets.length} ${noun} ${pc.dim(`(${weight(synced.value.totalBytes)})`)}, ${synced.value.uploaded} uploaded ${synced.took}` : `Assets up to date ${pc.dim(`(${assets.length} ${noun})`)} ${synced.took}`);
1000
+ }
1001
+ note("Pushing");
1002
+ const push = await timed(() => pushPaywallVersion(context.api, bind.paywallId, {
1003
+ html: build.html,
1004
+ surface: surface.id,
1005
+ assets: synced.value.assets,
1006
+ products: versionProducts(build.products, target.platform),
1007
+ settings: build.settings
1008
+ }));
1009
+ version = push.value.version;
1010
+ writeSnapshot(project.superwallDir, surface.kind, surface.id, target.platform, build.snapshotId);
1011
+ lines.push(`${pushedLine({
1012
+ version,
1013
+ snapshotId: push.value.snapshot_id ?? build.snapshotId,
1014
+ live: wasLive,
1015
+ promoting: options.promote
1016
+ })} ${push.took}`);
1017
+ note("Pushing source");
1018
+ const pushed = await timed(() => {
1019
+ if (!source.ok) throw new Error(source.reason);
1020
+ return pushSource({
1021
+ api: context.api,
1022
+ paywallId: bind.paywallId,
1023
+ applicationId: bind.applicationId,
1024
+ version,
1025
+ files: source.files,
1026
+ framework: installed,
1027
+ surface: surface.id,
1028
+ kind: surface.kind,
1029
+ snapshotId: build.snapshotId,
1030
+ cli: VERSION,
1031
+ note: publishNote,
1032
+ external: [...build.externalSources ?? []].sort()
1033
+ });
1034
+ });
1035
+ const sha = pc.dim(pushed.value.commitSha.slice(0, 7));
1036
+ lines.push(`Source ${pushed.value.status === "unchanged" ? "unchanged" : "pushed"} ${sha} ${pushed.took}`);
1037
+ if (options.promote) {
1038
+ note("Promoting");
1039
+ const promo = await timed(() => promotePaywallVersion(context.api, bind.paywallId, { version }));
1040
+ lines.push(`${transition(wasLive, promo.value.version)} ${promo.took}`);
1041
+ live = true;
1042
+ }
1043
+ return lines;
1044
+ });
1045
+ outcomes.push({
1046
+ id: targetLabel(target, multi),
1047
+ version,
1048
+ live
1049
+ });
1050
+ }
1051
+ warnNotPortable(external);
1052
+ summary(outcomes, skipped, options.promote);
1053
+ }
1054
+
1055
+ //#endregion
1056
+ export { syncAssets as C, writeProjectTypes as D, collectProjectDeclarations as E, requireAssets as S, loadFramework as T, planTargets as _, requireProject as a, resolveBinding as b, timed as c, pushSource as d, collectSourceFiles as f, parsePlatformFlags as g, projectForApplication as h, projectDirs as i, transition as l, fetchProducts as m, group as n, runPushPipeline as o, warnNotPortable as p, projectDir as r, selectSurfaces as s, LAYOUT_HINT as t, pickApplicationOption as u, targetLabel as v, frameworkVersion as w, assetBaseUrl as x, wantedPlatforms as y };