@superwall/cli 2.2.1 → 2.3.1

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 (87) hide show
  1. package/README.md +24 -11
  2. package/dist/{apple-DaqaI4vD.js → apple-z2qjOzIZ.js} +13 -13
  3. package/dist/assets-DXXegdDt.js +89 -0
  4. package/dist/auth.d.ts +1 -1
  5. package/dist/auth.js +3 -3
  6. package/dist/{billing-DyKr2kmd.js → billing-B8tOjsnY.js} +3 -3
  7. package/dist/{bind-BpxebZf4.js → bind-Bx9K6LwP.js} +4 -4
  8. package/dist/{build-DzbdRThf.js → build-Bu2kkzRe.js} +7 -6
  9. package/dist/{client-BF9rCULI.js → client-DOgk9gAS.js} +3 -3
  10. package/dist/{create-D7AZHYGH.js → create-B03MAuPe.js} +6 -6
  11. package/dist/create-BdZS_T68.js +19 -0
  12. package/dist/{create-B55V99TD.js → create-DzC_89gq.js} +28 -226
  13. package/dist/{doctor-B2mPKiaJ.js → doctor-BGZSKY_B.js} +6 -6
  14. package/dist/{drivers-DOMky8Ug.js → drivers-DqLgQxkC.js} +3 -3
  15. package/dist/entry.js +19 -19
  16. package/dist/{environment-DBwo79dy.js → environment-i8BhiBDB.js} +1 -1
  17. package/dist/{existing-B4VK4BCL.js → existing-BPOG5zLO.js} +2 -2
  18. package/dist/{held-DjcZPCwn.js → held-C56PYMRH.js} +6 -6
  19. package/dist/held-DSNUY-NZ.js +16 -0
  20. package/dist/{integrate-B8oHbvwz.js → integrate-DZ4Qvoch.js} +22 -22
  21. package/dist/login-Blrkm6oi.js +16 -0
  22. package/dist/{login-DfhqWY9C.js → login-ONZdK8vN.js} +6 -6
  23. package/dist/{login-B8hgMLhS.js → login-p9GVEKzD.js} +1 -1
  24. package/dist/{lookup-r8p6H2ZC.js → lookup-flTi0at0.js} +2 -2
  25. package/dist/{migrate-DQf2Fosc.js → migrate-DnXpbhL1.js} +25 -22
  26. package/dist/{open-CrEnSL4v.js → migration-DJ1uNKhk.js} +11 -49
  27. package/dist/{notification-url-BxPTEmkv.js → notification-url-CCDeS5S-.js} +2 -2
  28. package/dist/open-QdsZ_N47.js +41 -0
  29. package/dist/{org-Cc2WGvl1.js → org-BiFPjoHD.js} +2 -2
  30. package/dist/{paths-BcNbJfpw.js → paths-yRgm5Jpa.js} +1 -1
  31. package/dist/{playbook-D9J8frkE.js → playbook-B-pRKNa4.js} +10 -10
  32. package/dist/{promote-C8T7DCFF.js → promote-Djzk4C81.js} +18 -16
  33. package/dist/pull-BLA9XwHj.js +303 -0
  34. package/dist/push-BkMgOT6X.js +24 -0
  35. package/dist/{push-Bzs1l_5C.js → push-gSBxGDik.js} +8 -6
  36. package/dist/{registry-CpxZbmxp.js → registry-D3xmWk9p.js} +230 -115
  37. package/dist/{resources-Bo6i7wBi.js → resources-BTnczJCA.js} +21 -7
  38. package/dist/{run-BUp4r8Kk.js → run-C1SoizcJ.js} +2 -2
  39. package/dist/{scan-8cxu2fx0.js → scan-Dwk_lT5q.js} +1 -1
  40. package/dist/scan-Kp-MAutK.js +4 -0
  41. package/dist/{scope-CPG_wWXL.js → scope-Db7blD-l.js} +5 -4
  42. package/dist/{selection-CMA4aG4V.js → selection-u2KiKu_d.js} +16 -96
  43. package/dist/{server-Xb3wp-mx.js → server-Cb2N75JL.js} +9 -7
  44. package/dist/server-psYghr9K.js +24 -0
  45. package/dist/{session-eZeXR9xU.js → session-BDLQUJyV.js} +444 -243
  46. package/dist/session-CehHJWZk.js +6 -0
  47. package/dist/{session-DOZV1TP6.js → session-CnDJp_HO.js} +1 -1
  48. package/dist/setup-BLahHpgy.js +216 -0
  49. package/dist/skills/animate-onboarding/SKILL.md +1 -1
  50. package/dist/skills/mobile-design/SKILL.md +1 -1
  51. package/dist/skills/onboarding-questions/SKILL.md +1 -1
  52. package/dist/skills/superwall/SKILL.md +6 -7
  53. package/dist/skills/superwall/references/api.md +8 -3
  54. package/dist/skills/superwall/workflows/dashboard/playbook.md +4 -3
  55. package/dist/skills/superwall/workflows/dashboard/setup.md +7 -4
  56. package/dist/skills/superwall/workflows/migrate/adapty.md +4 -3
  57. package/dist/skills/superwall/workflows/migrate/playbook.md +2 -2
  58. package/dist/skills/superwall/workflows/migrate/qonversion.md +4 -3
  59. package/dist/skills/superwall/workflows/migrate/revenuecat.md +4 -3
  60. package/dist/skills/superwall-editor/SKILL.md +2 -3
  61. package/dist/skills/superwall-framework/SKILL.md +83 -13
  62. package/dist/skills/superwall-framework/references/cli.md +92 -21
  63. package/dist/skills/superwall-framework/references/migrate-from-editor.md +5 -1
  64. package/dist/{skills-BI19OGlS.js → skills-DDV4zcLR.js} +8 -8
  65. package/dist/{skills-DDf10ufO.js → skills-zebMTZyr.js} +4 -4
  66. package/dist/source-push-DxuJuwEf.js +205 -0
  67. package/dist/{spinner-BClMQGGN.js → spinner-BN3U1CVB.js} +3 -3
  68. package/dist/{storage-Po9E-CHL.js → storage-VagEaaJC.js} +1 -1
  69. package/dist/storekit-BcBb2jXB.js +16 -0
  70. package/dist/{storekit-Cbn9DBLA.js → storekit-CoOf4Rvh.js} +3 -3
  71. package/dist/{telemetry-s6dag6tb.js → telemetry-CM0BDwCK.js} +1 -1
  72. package/dist/{token-CPplNMVa.js → token-lUUOkTJA.js} +1 -1
  73. package/dist/tools.d.ts +1 -1
  74. package/dist/tools.js +215 -89
  75. package/dist/{upgrade-1OYm5NQU.js → upgrade-CpTJv_M7.js} +2 -2
  76. package/dist/{upgrade-ahapZeex.js → upgrade-DZbKb67W.js} +1 -1
  77. package/package.json +2 -2
  78. package/dist/create-BYAPuhhf.js +0 -19
  79. package/dist/held-C9FqvNbn.js +0 -16
  80. package/dist/login-D-a7oS_8.js +0 -16
  81. package/dist/push-snV3SrnH.js +0 -22
  82. package/dist/scan-nUeXs9a1.js +0 -4
  83. package/dist/server-Boqa8jh_.js +0 -22
  84. package/dist/session-DtBpdlF-.js +0 -6
  85. package/dist/storekit-BU6Eq_UO.js +0 -16
  86. /package/dist/{reports-D_qbl7_u.js → reports-CwwKLUh0.js} +0 -0
  87. /package/dist/{storage-BbJF7z3l.d.ts → storage-gRyQetN9.d.ts} +0 -0
@@ -1,19 +1,16 @@
1
- import { l as ENV_API_KEY, t as API_HOST, y as apiKeyFromEnv } from "./environment-DBwo79dy.js";
2
- import { n as readSession } from "./storage-Po9E-CHL.js";
3
- import { n as ApiUnreachableError, r as createSuperwallApi, t as ApiError } from "./client-BF9rCULI.js";
1
+ import { l as ENV_API_KEY, t as API_HOST, y as apiKeyFromEnv } from "./environment-i8BhiBDB.js";
2
+ import { n as readSession } from "./storage-VagEaaJC.js";
3
+ import { r as createSuperwallApi } from "./client-DOgk9gAS.js";
4
4
  import { n as ui } from "./ui-D_qf3Gvw.js";
5
- import { O as isRecord, _ as mintSourceAccess, a as createHeadlessPaywall, d as listAppPaywalls, f as listApplications, u as linkSourceCommit, v as platformLabel } from "./resources-Bo6i7wBi.js";
6
- import { n as findApplication } from "./lookup-r8p6H2ZC.js";
7
- import { C as parseSources, D as writeBinding, E as writeApp, j as writeSources, w as readLock, x as formatSharedLock } from "./selection-CMA4aG4V.js";
8
- import { n as performLoginWithUi } from "./login-B8hgMLhS.js";
5
+ import { k as isRecord, p as listApplications, y as platformLabel } from "./resources-BTnczJCA.js";
6
+ import { C as formatLock, D as parseLock, E as originKey, L as writeSources, O as parseSources, j as writeApp, k as readLock, v as TYPES_FILE, w as formatSharedLock, x as NewerLockError } from "./selection-u2KiKu_d.js";
7
+ import { n as performLoginWithUi } from "./login-p9GVEKzD.js";
9
8
  import { execFile } from "node:child_process";
10
9
  import * as fs from "node:fs";
11
10
  import * as path from "node:path";
12
11
  import { promisify } from "node:util";
13
12
  import * as os$1 from "node:os";
14
13
  import fg from "fast-glob";
15
- import { setTimeout } from "node:timers/promises";
16
- import { productVariables } from "@superwall/studio/products";
17
14
 
18
15
  //#region src/core/paywalls/binding/apps.ts
19
16
  const PLATFORMS = [
@@ -77,76 +74,6 @@ async function resolveApps(input) {
77
74
  throw new AppBindingError(apps.length === 0 ? "Your account has no apps yet — create one with `superwall apps create` or in the dashboard." : "Several apps in your account — run `superwall push` interactively once to pick one; the choice is saved to superwall.lock.");
78
75
  }
79
76
 
80
- //#endregion
81
- //#region src/core/paywalls/binding/binding.ts
82
- var BindingError = class extends Error {};
83
- const describe = (surface) => `${surface.kind} \`${surface.id}\``;
84
- const humanize = (surfaceId) => surfaceId.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
85
- async function resolveBinding(input) {
86
- const { api, superwallDir, surface, app } = input;
87
- const { platform, applicationId } = app;
88
- const create = input.create ?? true;
89
- const lock = readLock(superwallDir);
90
- const section = surface.kind === "paywall" ? lock.paywalls : lock.funnels;
91
- const locked = section[surface.id]?.[platform];
92
- if (locked) return {
93
- paywallId: locked.paywallId,
94
- applicationId,
95
- platform,
96
- source: "lock"
97
- };
98
- const matches = (paywalls) => {
99
- const headless = paywalls.filter((paywall) => paywall.metadata.headless === "true");
100
- return headless.find((paywall) => paywall.metadata.headlessSurface === surface.id) ?? headless.find((paywall) => paywall.identifier === surface.id);
101
- };
102
- const match = matches(await listAppPaywalls(api, applicationId));
103
- if (match) {
104
- await requireAdoption(input.confirmAdopt, {
105
- surface,
106
- paywallId: match.id,
107
- applicationId,
108
- platform
109
- });
110
- writeBinding(superwallDir, surface.kind, surface.id, platform, { paywallId: match.id });
111
- return {
112
- paywallId: match.id,
113
- applicationId,
114
- platform,
115
- source: "matched"
116
- };
117
- }
118
- if (!create) throw new BindingError(`${describe(surface)} has never been pushed to \`${platform}\` — run \`superwall push\` first.`);
119
- if (!input.renamesResolved) {
120
- const onDisk = new Set(input.surfaces.filter((candidate) => candidate.kind === surface.kind).map((c) => c.id));
121
- const orphans = Object.keys(section).filter((id) => !onDisk.has(id));
122
- 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>\`.`);
123
- }
124
- const archived = matches(await listAppPaywalls(api, applicationId, { archived: true }));
125
- 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.`);
126
- const created = await createHeadlessPaywall(api, {
127
- applicationId,
128
- name: input.name?.trim() || humanize(surface.id),
129
- identifier: surface.id
130
- });
131
- writeBinding(superwallDir, surface.kind, surface.id, platform, { paywallId: created.id });
132
- return {
133
- paywallId: created.id,
134
- applicationId,
135
- platform,
136
- source: "created"
137
- };
138
- }
139
- async function requireAdoption(confirm, candidate) {
140
- if (confirm && await confirm(candidate)) return;
141
- const { surface, paywallId, applicationId, platform } = candidate;
142
- const lockLine = `"${surface.id}": { "${platform}": { "paywallId": "${paywallId}" } }`;
143
- throw new BindingError([
144
- `App ${applicationId} already has a paywall \`${surface.id}\` (${paywallId}) that superwall.lock doesn't bind, so nothing was pushed.`,
145
- ` - It's yours: run \`superwall push\` interactively and confirm, or add ${lockLine} under "${surface.kind === "paywall" ? "paywalls" : "funnels"}" in superwall.lock.`,
146
- ` - It isn't: rename the directory, and the next push creates a new paywall.`
147
- ].join("\n"));
148
- }
149
-
150
77
  //#endregion
151
78
  //#region src/core/paywalls/binding/targets.ts
152
79
  var TargetError = class extends Error {};
@@ -194,59 +121,6 @@ function planTargets(input) {
194
121
  return targets;
195
122
  }
196
123
 
197
- //#endregion
198
- //#region src/core/paywalls/products.ts
199
- function storeOf(row) {
200
- if (row.platform === "stripe") return "stripe";
201
- if (row.store === "custom" || row.platform === "custom") return "custom";
202
- if (row.store === "app_store") return "app-store";
203
- if (row.store === "play_store") return "play-store";
204
- }
205
- async function listProjectCatalogue(api, projectId) {
206
- const rows = await api.list(`/v2/products?project_id=${encodeURIComponent(projectId)}`);
207
- const variables = /* @__PURE__ */ new Map();
208
- const stores = /* @__PURE__ */ new Map();
209
- for (const row of rows) {
210
- if (!row.identifier) continue;
211
- variables.set(row.identifier, productVariables(row));
212
- const store = storeOf(row);
213
- if (store === void 0) continue;
214
- const known = stores.get(row.identifier) ?? [];
215
- if (!known.includes(store)) stores.set(row.identifier, [...known, store]);
216
- }
217
- return {
218
- variables: Object.fromEntries(variables),
219
- stores: Object.fromEntries(stores)
220
- };
221
- }
222
- async function listProjectProducts(api, projectId) {
223
- return (await listProjectCatalogue(api, projectId)).variables;
224
- }
225
- async function listApplicationCatalogue(api, applicationId) {
226
- const projectId = await projectForApplication(api, applicationId);
227
- if (projectId === void 0) return {
228
- variables: {},
229
- stores: {}
230
- };
231
- return listProjectCatalogue(api, projectId);
232
- }
233
- async function projectForApplication(api, applicationId) {
234
- const found = await findApplication(api, applicationId).catch(() => void 0);
235
- return found ? String(found.project.id) : void 0;
236
- }
237
- var MissingProductError = class extends Error {};
238
- function requireProducts(catalogue, surfaces) {
239
- const gaps = surfaces.flatMap((surface) => Object.entries(surface.products ?? {}).filter(([, identifier]) => !Object.hasOwn(catalogue, identifier)).map(([reference, identifier]) => ` ${surface.id}: ${reference} → ${identifier}`));
240
- if (gaps.length === 0) return;
241
- throw new MissingProductError([
242
- gaps.length === 1 ? "This product does not exist on Superwall:" : `These ${gaps.length} products do not exist on Superwall:`,
243
- ...gaps,
244
- "",
245
- "Every variable on them would be undefined on device. Add them in the",
246
- "dashboard, or point the config at products that exist."
247
- ].join("\n"));
248
- }
249
-
250
124
  //#endregion
251
125
  //#region src/core/paywalls/project/scaffold.ts
252
126
  const REACT_VERSION = "19.1.0";
@@ -289,21 +163,6 @@ function writeProjectScaffold(options) {
289
163
  writeIfAbsent(path.join(options.superwallDir, ".gitignore"), GITIGNORE);
290
164
  }
291
165
 
292
- //#endregion
293
- //#region src/core/paywalls/source/portability.ts
294
- const SHOWN = 5;
295
- function portabilityWarning(external) {
296
- const names = [...new Set(external)].filter((entry) => entry.trim() !== "").sort();
297
- if (names.length === 0) return void 0;
298
- const shown = names.slice(0, SHOWN).join(", ");
299
- const rest = names.length - SHOWN;
300
- 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.`;
301
- }
302
- function warnNotPortable(external) {
303
- const message = portabilityWarning(external);
304
- if (message) ui.warn(message);
305
- }
306
-
307
166
  //#endregion
308
167
  //#region src/core/paywalls/source/source.ts
309
168
  const HARD_EXCLUDES = [
@@ -323,7 +182,7 @@ const HARD_EXCLUDES = [
323
182
  "**/google-services.json",
324
183
  "**/GoogleService-Info.plist"
325
184
  ];
326
- const LOCK_FILE = "superwall.lock";
185
+ const LOCK_FILE$1 = "superwall.lock";
327
186
  const SOURCE_LIMIT_BYTES = 250 * 1024 * 1024;
328
187
  const LARGEST_SHOWN = 3;
329
188
  const megabytes = (bytes) => `${(bytes / 1024 / 1024).toFixed(1)} MB`;
@@ -374,7 +233,7 @@ async function collectSourceFiles(superwallDir) {
374
233
  ok: true,
375
234
  files: entries.sort().map((relative$1) => ({
376
235
  path: relative$1,
377
- content: relative$1 === LOCK_FILE ? Buffer.from(formatSharedLock(superwallDir)) : fs.readFileSync(path.join(superwallDir, relative$1))
236
+ content: relative$1 === LOCK_FILE$1 ? Buffer.from(formatSharedLock(superwallDir)) : fs.readFileSync(path.join(superwallDir, relative$1))
378
237
  }))
379
238
  };
380
239
  }
@@ -437,6 +296,87 @@ const redact = (text, ...secrets) => {
437
296
  return safe;
438
297
  };
439
298
 
299
+ //#endregion
300
+ //#region src/core/paywalls/source/scope.ts
301
+ const LOCK_FILE = "superwall.lock";
302
+ const DERIVED_FILES = new Set([LOCK_FILE, TYPES_FILE]);
303
+ const SURFACE_DIRS = {
304
+ paywalls: "paywall",
305
+ funnels: "funnel"
306
+ };
307
+ function surfaceOf(relative$1) {
308
+ const [top, id, ...rest] = relative$1.split("/");
309
+ const kind = top === void 0 ? void 0 : SURFACE_DIRS[top];
310
+ if (!kind || !id || rest.length === 0) return void 0;
311
+ return {
312
+ kind,
313
+ id
314
+ };
315
+ }
316
+ function classifyPath(relative$1, scope) {
317
+ if (DERIVED_FILES.has(relative$1)) return "derived";
318
+ const surface = surfaceOf(relative$1);
319
+ if (!surface) return "shared";
320
+ return surface.kind === scope.kind && surface.id === scope.id ? "own" : "other";
321
+ }
322
+ const isSurfaceRoot = (top) => SURFACE_DIRS[top] !== void 0;
323
+ const isOtherSurfaceDir = (top, child, scope) => {
324
+ const kind = SURFACE_DIRS[top];
325
+ return kind !== void 0 && !(kind === scope.kind && child === scope.id);
326
+ };
327
+ var SourceLockUnreadableError = class extends Error {
328
+ constructor(reason) {
329
+ super(`The source repo's superwall.lock can't be read (${reason}), so its bindings for other paywalls can't be kept. Rerun with --overwrite-source to replace it with yours.`);
330
+ }
331
+ };
332
+ const readable = (text) => {
333
+ try {
334
+ return { lock: parseLock(text, LOCK_FILE) };
335
+ } catch (error) {
336
+ if (error instanceof NewerLockError) throw error;
337
+ return { reason: error instanceof Error ? error.message : String(error) };
338
+ }
339
+ };
340
+ function mergeLockText(theirs, mine, scope, options = {}) {
341
+ const own = readable(mine);
342
+ if (!("lock" in own)) return mine;
343
+ if (theirs === void 0) return formatLock(withoutSources(own.lock));
344
+ const read = readable(theirs);
345
+ if (!("lock" in read)) {
346
+ if (!options.replaceUnreadable) throw new SourceLockUnreadableError(read.reason);
347
+ return formatLock(withoutSources(own.lock));
348
+ }
349
+ return mergeLocks(read.lock, own.lock, scope);
350
+ }
351
+ function mergeLocks(other, own, scope) {
352
+ const section = (lock) => scope.kind === "paywall" ? lock.paywalls : lock.funnels;
353
+ const conflicting = new Set(Object.entries(own.apps).filter(([platform, app]) => other.apps[platform] !== void 0 && other.apps[platform] !== app).map(([platform]) => platform));
354
+ const ownApps = Object.fromEntries(Object.entries(own.apps).filter(([platform]) => !conflicting.has(platform)));
355
+ const merged = {
356
+ version: 1,
357
+ apps: {
358
+ ...other.apps,
359
+ ...ownApps
360
+ },
361
+ paywalls: { ...other.paywalls },
362
+ funnels: { ...other.funnels }
363
+ };
364
+ const target = section(merged);
365
+ const theirEntry = section(other)[scope.id] ?? {};
366
+ const mineEntry = section(own)[scope.id] ?? {};
367
+ const entry = Object.fromEntries([...Object.entries(theirEntry).filter(([platform]) => conflicting.has(platform)), ...Object.entries(mineEntry).filter(([platform]) => !conflicting.has(platform))]);
368
+ if (Object.keys(entry).length > 0) target[scope.id] = entry;
369
+ else delete target[scope.id];
370
+ const key = originKey(scope.kind, scope.id);
371
+ const origins = { ...other.origins };
372
+ const mineOrigin = own.origins?.[key];
373
+ if (mineOrigin) origins[key] = mineOrigin;
374
+ else delete origins[key];
375
+ if (Object.keys(origins).length > 0) merged.origins = origins;
376
+ return formatLock(merged);
377
+ }
378
+ const withoutSources = ({ sources: _,...lock }) => lock;
379
+
440
380
  //#endregion
441
381
  //#region src/core/paywalls/source/git.ts
442
382
  const run = promisify(execFile);
@@ -500,24 +440,54 @@ async function gitAvailable() {
500
440
  }
501
441
  }
502
442
  const LARGE_FILE_BYTES = 50 * 1024 * 1024;
503
- function materializeSourceTree(dir, files) {
443
+ function materializeSourceTree(dir, files, scope, options = {}) {
444
+ const theirs = /* @__PURE__ */ new Map();
445
+ for (const derived of DERIVED_FILES) {
446
+ const existing = path.join(dir, derived);
447
+ if (fs.existsSync(existing)) theirs.set(derived, fs.readFileSync(existing));
448
+ }
449
+ const remove = (target) => fs.rmSync(target, {
450
+ recursive: true,
451
+ force: true
452
+ });
453
+ const keepShared = options.onRemote === true;
504
454
  for (const entry of fs.readdirSync(dir)) {
505
455
  if (entry === ".git") continue;
506
- fs.rmSync(path.join(dir, entry), {
507
- recursive: true,
508
- force: true
509
- });
456
+ const top = path.join(dir, entry);
457
+ const isDir = fs.lstatSync(top).isDirectory();
458
+ if (keepShared && !(isDir && isSurfaceRoot(entry))) continue;
459
+ if (!isDir) {
460
+ remove(top);
461
+ continue;
462
+ }
463
+ for (const child of fs.readdirSync(top)) {
464
+ const inner = path.join(top, child);
465
+ const childIsDir = fs.lstatSync(inner).isDirectory();
466
+ if (isOtherSurfaceDir(entry, child, scope) && childIsDir) continue;
467
+ if (keepShared && !childIsDir) continue;
468
+ remove(inner);
469
+ }
510
470
  }
511
471
  const write = (relative$1, data) => {
512
472
  const file = path.join(dir, relative$1);
473
+ const parts = relative$1.split("/");
474
+ for (let depth = 1; depth < parts.length; depth++) {
475
+ const ancestor = path.join(dir, ...parts.slice(0, depth));
476
+ if (fs.existsSync(ancestor) && !fs.lstatSync(ancestor).isDirectory()) remove(ancestor);
477
+ }
478
+ if (fs.existsSync(file) && fs.lstatSync(file).isDirectory()) remove(file);
513
479
  fs.mkdirSync(path.dirname(file), { recursive: true });
514
480
  fs.writeFileSync(file, data);
515
481
  };
516
482
  const large = [];
517
483
  for (const file of files) {
484
+ if (classifyPath(file.path, scope) === "other") continue;
518
485
  if (file.content.byteLength > LARGE_FILE_BYTES) large.push(file.path);
519
- write(file.path, file.content);
486
+ if (file.path === LOCK_FILE) write(file.path, mergeLockText(theirs.get(LOCK_FILE)?.toString("utf8"), file.content.toString("utf8"), scope, { replaceUnreadable: options.overwrite }));
487
+ else write(file.path, file.content);
488
+ theirs.delete(file.path);
520
489
  }
490
+ for (const [derived, content] of theirs) write(derived, content);
521
491
  if (large.length > 0) ui.warn(`Committing ${large.length > 1 ? `${large.length} files` : large[0]} over 50 MB — every future clone of this app's source repo pays for it.`);
522
492
  }
523
493
  const SHOWN_FILES = 5;
@@ -528,13 +498,13 @@ const listFiles = (files) => {
528
498
  };
529
499
  var SourceConflictError = class extends Error {
530
500
  constructor(files) {
531
- super(`Someone else published changes to ${listFiles(files)} since this project last synced. Pull their commits into this project, then publish again — or rerun with --overwrite-source to replace their version with yours.`);
501
+ super(`Someone else published changes to ${listFiles(files)} since this project last synced. Run \`superwall pull\` to bring their changes into this project, then publish again — or rerun with --overwrite-source to replace this paywall's source with yours.`);
532
502
  this.files = files;
533
503
  }
534
504
  };
535
505
  var SourceDivergedError = class extends Error {
536
506
  constructor(files) {
537
- super(`The source repo differs from this project in ${listFiles(files)}, and superwall.lock records no sync point to merge from. Pull the latest superwall.lock, or rerun with --overwrite-source to replace the remote source with yours.`);
507
+ super(`The source repo differs from this project in ${listFiles(files)}, and superwall.lock records no sync point to merge from. Run \`superwall pull\` to merge the source repo into this project, then publish again — or rerun with --overwrite-source to replace this paywall's source with yours.`);
538
508
  this.files = files;
539
509
  }
540
510
  };
@@ -566,6 +536,10 @@ async function pushSourceTree(input) {
566
536
  env,
567
537
  secrets
568
538
  });
539
+ const scope = {
540
+ kind: input.message.kind,
541
+ id: input.message.surface
542
+ };
569
543
  const head = await revParse("HEAD");
570
544
  const base = input.base && head && !input.overwrite ? await revParse(input.base) : void 0;
571
545
  if (base && base !== head) await run$1([
@@ -574,23 +548,48 @@ async function pushSourceTree(input) {
574
548
  "--detach",
575
549
  base
576
550
  ]);
577
- materializeSourceTree(dir, input.files);
551
+ const messageFile = path.join(dir, ".git", "SUPERWALL_COMMITMSG");
552
+ fs.writeFileSync(messageFile, buildCommitMessage(input.message));
553
+ const onRemote = head !== void 0 && !base;
554
+ const local = onRemote ? await snapshotLocal(run$1, dir, input.files, scope, head, committing) : void 0;
555
+ materializeSourceTree(dir, input.files, scope, {
556
+ onRemote,
557
+ overwrite: input.overwrite
558
+ });
578
559
  await run$1(["add", "-A"]);
579
- if ((await run$1(["status", "--porcelain"])).trim() === "") return {
560
+ const dirty = (await run$1(["status", "--porcelain"])).trim();
561
+ if (dirty === "" && local === void 0) return {
580
562
  commitSha: head ?? "",
581
563
  status: "unchanged",
582
564
  syncedTo: base ?? head
583
565
  };
584
- if (head && !base && !input.overwrite) throw new SourceDivergedError((await run$1([
585
- "diff",
586
- "--cached",
587
- "--name-only",
588
- "-z",
589
- "HEAD"
590
- ])).split("\0").filter(Boolean));
591
- const messageFile = path.join(dir, ".git", "SUPERWALL_COMMITMSG");
592
- fs.writeFileSync(messageFile, buildCommitMessage(input.message));
593
- await run$1([
566
+ if (onRemote && !input.overwrite) {
567
+ const refused = overwrittenPaths(await run$1([
568
+ "diff",
569
+ "--cached",
570
+ "--name-status",
571
+ "--no-renames",
572
+ "-z",
573
+ "HEAD"
574
+ ]));
575
+ if (refused.length > 0) throw new SourceDivergedError(refused);
576
+ }
577
+ if (local !== void 0 && head !== void 0) await run$1([
578
+ "reset",
579
+ "--quiet",
580
+ "--hard",
581
+ (await run$1([
582
+ "commit-tree",
583
+ (await run$1(["write-tree"])).trim(),
584
+ "-p",
585
+ head,
586
+ "-p",
587
+ local,
588
+ "-F",
589
+ messageFile
590
+ ], { env: committing })).trim()
591
+ ]);
592
+ else await run$1([
594
593
  "commit",
595
594
  "--quiet",
596
595
  "--no-verify",
@@ -599,19 +598,22 @@ async function pushSourceTree(input) {
599
598
  ], { env: committing });
600
599
  const own = await revParse("HEAD");
601
600
  if (!own) throw new Error("The source commit was not created.");
601
+ const syncedTo = local ?? own;
602
+ const status = dirty === "" ? "unchanged" : "committed";
602
603
  const isAncestor = (ancestor, of) => run$1([
603
604
  "merge-base",
604
605
  "--is-ancestor",
605
606
  ancestor,
606
607
  of
607
608
  ]).then(() => true, () => false);
609
+ const parent = base ?? head;
608
610
  for (let attempt = 1;; attempt++) {
609
- const upstream = base ? await revParse(`origin/${access.branch}`) : void 0;
610
- if (upstream && upstream !== base) {
611
+ const upstream = parent ? await revParse(`origin/${access.branch}`) : void 0;
612
+ if (upstream && upstream !== parent) {
611
613
  if (await isAncestor(own, upstream)) return {
612
614
  commitSha: upstream,
613
615
  status: "unchanged",
614
- syncedTo: own
616
+ syncedTo
615
617
  };
616
618
  await run$1([
617
619
  "reset",
@@ -621,7 +623,10 @@ async function pushSourceTree(input) {
621
623
  ]);
622
624
  await mergeUpstream(`origin/${access.branch}`, messageFile, {
623
625
  run: run$1,
624
- committing
626
+ committing,
627
+ dir,
628
+ own,
629
+ scope
625
630
  });
626
631
  }
627
632
  try {
@@ -632,11 +637,11 @@ async function pushSourceTree(input) {
632
637
  ]);
633
638
  return {
634
639
  commitSha: await revParse("HEAD") ?? own,
635
- status: "committed",
636
- syncedTo: own
640
+ status,
641
+ syncedTo
637
642
  };
638
643
  } catch (error) {
639
- if (!base || attempt >= PUSH_ATTEMPTS || !isRejected(error)) throw error;
644
+ if (!parent || attempt >= PUSH_ATTEMPTS || !isRejected(error)) throw error;
640
645
  await run$1([
641
646
  "fetch",
642
647
  "--quiet",
@@ -652,6 +657,63 @@ async function pushSourceTree(input) {
652
657
  });
653
658
  }
654
659
  }
660
+ function statIfPresent(file) {
661
+ try {
662
+ return fs.lstatSync(file, { throwIfNoEntry: false });
663
+ } catch (error) {
664
+ if (error.code === "ENOTDIR") return void 0;
665
+ throw error;
666
+ }
667
+ }
668
+ async function snapshotLocal(run$1, dir, files, scope, head, committing) {
669
+ const kept = [];
670
+ for (const file of files) {
671
+ if (classifyPath(file.path, scope) !== "other") {
672
+ kept.push(file);
673
+ continue;
674
+ }
675
+ const remote$1 = path.join(dir, file.path);
676
+ if (statIfPresent(remote$1)?.isFile()) kept.push({
677
+ ...file,
678
+ content: fs.readFileSync(remote$1)
679
+ });
680
+ }
681
+ replaceTree(dir, kept);
682
+ await run$1(["add", "-A"]);
683
+ const tree = (await run$1(["write-tree"])).trim();
684
+ const remote = (await run$1(["rev-parse", `${head}^{tree}`])).trim();
685
+ await run$1([
686
+ "reset",
687
+ "--quiet",
688
+ "--hard",
689
+ head
690
+ ]);
691
+ await run$1([
692
+ "clean",
693
+ "--quiet",
694
+ "-d",
695
+ "-x",
696
+ "--force"
697
+ ]);
698
+ if (tree === remote) return void 0;
699
+ return (await run$1([
700
+ "commit-tree",
701
+ tree,
702
+ "-m",
703
+ "superwall: the project this push was made from"
704
+ ], { env: committing })).trim();
705
+ }
706
+ function overwrittenPaths(nameStatus) {
707
+ const fields = nameStatus.split("\0").filter(Boolean);
708
+ const paths = [];
709
+ for (let index = 0; index + 1 < fields.length; index += 2) {
710
+ const status = fields[index];
711
+ const file = fields[index + 1];
712
+ if (file === void 0 || status === "A" || DERIVED_FILES.has(file)) continue;
713
+ paths.push(file);
714
+ }
715
+ return paths;
716
+ }
655
717
  const CLONE_ATTEMPTS = [
656
718
  ["--filter=blob:none", "--branch"],
657
719
  ["--branch"],
@@ -685,85 +747,224 @@ async function cloneSource(access, dir, options) {
685
747
  }
686
748
  throw first;
687
749
  }
688
- async function mergeUpstream(upstream, messageFile, { run: run$1, committing }) {
750
+ async function mergeUpstream(upstream, messageFile, { run: run$1, committing, dir, own, scope }) {
751
+ let failure;
752
+ await run$1([
753
+ "merge",
754
+ "--quiet",
755
+ "--no-ff",
756
+ "--no-commit",
757
+ upstream
758
+ ], { env: committing }).catch((error) => {
759
+ failure = error;
760
+ });
761
+ const conflicted = (await run$1([
762
+ "diff",
763
+ "--name-only",
764
+ "--diff-filter=U",
765
+ "-z"
766
+ ]).catch(() => "")).split("\0").filter(Boolean);
767
+ const blocking = conflicted.filter((file) => !DERIVED_FILES.has(file));
768
+ const merging = await run$1([
769
+ "rev-parse",
770
+ "--verify",
771
+ "--quiet",
772
+ "MERGE_HEAD"
773
+ ]).then(() => true, () => false);
774
+ if (blocking.length > 0 || failure !== void 0 && conflicted.length === 0) {
775
+ await run$1(["merge", "--abort"]).catch(() => void 0);
776
+ if (blocking.length > 0) throw new SourceConflictError(blocking);
777
+ throw failure;
778
+ }
779
+ if (!merging) return;
780
+ const show = (ref, file) => run$1(["show", `${ref}:${file}`]).then((text) => text, () => void 0);
781
+ const theirsLock = await show(upstream, LOCK_FILE);
782
+ const mineLock = await show(own, LOCK_FILE);
783
+ await settle(run$1, dir, LOCK_FILE, mineLock === void 0 ? theirsLock : mergeLockText(theirsLock, mineLock, scope));
784
+ for (const file of DERIVED_FILES) if (file !== LOCK_FILE) await settle(run$1, dir, file, await show(own, file));
785
+ await run$1([
786
+ "commit",
787
+ "--quiet",
788
+ "--no-verify",
789
+ "-F",
790
+ messageFile
791
+ ], { env: committing });
792
+ }
793
+ async function settle(run$1, dir, file, content) {
794
+ if (content === void 0) return;
795
+ fs.writeFileSync(path.join(dir, file), content);
796
+ await run$1([
797
+ "add",
798
+ "--",
799
+ file
800
+ ]);
801
+ }
802
+ var PullConflictError = class extends Error {
803
+ constructor(files) {
804
+ super(`Your project and the source repo both changed ${listFiles(files)}, so nothing was pulled. To keep your edits, copy those files somewhere first; then rerun with --theirs to take the source repo's version of them.`);
805
+ this.files = files;
806
+ }
807
+ };
808
+ async function pullSourceTree(input) {
809
+ const { access } = input;
810
+ const secrets = [access.token, tokenSecret(access.token)];
811
+ const dir = fs.mkdtempSync(path.join(os$1.tmpdir(), "superwall-pull-"));
812
+ const env = gitEnv(access.token, {
813
+ GIT_AUTHOR_NAME: AUTHOR.name,
814
+ GIT_AUTHOR_EMAIL: AUTHOR.email,
815
+ GIT_COMMITTER_NAME: AUTHOR.name,
816
+ GIT_COMMITTER_EMAIL: AUTHOR.email
817
+ });
818
+ const run$1 = (args) => git(args, {
819
+ cwd: dir,
820
+ env,
821
+ secrets
822
+ });
823
+ const revParse = (ref) => run$1([
824
+ "rev-parse",
825
+ "--verify",
826
+ "--quiet",
827
+ `${ref}^{commit}`
828
+ ]).then((out) => out.trim(), () => void 0);
689
829
  try {
830
+ await cloneSource(access, dir, {
831
+ env,
832
+ secrets
833
+ });
834
+ const head = await revParse("HEAD");
835
+ if (!head) return { status: "empty" };
836
+ const base = input.base ? await revParse(input.base) : void 0;
837
+ if (base) await run$1([
838
+ "checkout",
839
+ "--quiet",
840
+ "--detach",
841
+ base
842
+ ]);
843
+ else await run$1([
844
+ "checkout",
845
+ "--quiet",
846
+ "--orphan",
847
+ "superwall-local"
848
+ ]);
849
+ replaceTree(dir, input.files);
850
+ await run$1(["add", "-A"]);
851
+ await run$1([
852
+ "commit",
853
+ "--quiet",
854
+ "--no-verify",
855
+ "--allow-empty",
856
+ "-m",
857
+ "Local project"
858
+ ]);
859
+ const own = await revParse("HEAD");
860
+ if (!own) throw new Error("The local snapshot commit was not created.");
861
+ let failure;
690
862
  await run$1([
691
863
  "merge",
692
864
  "--quiet",
693
865
  "--no-ff",
694
- "-F",
695
- messageFile,
696
- upstream
697
- ], { env: committing });
698
- } catch (error) {
699
- const conflicted = await run$1([
866
+ "--no-commit",
867
+ ...base ? [] : ["--allow-unrelated-histories"],
868
+ head
869
+ ]).catch((error) => {
870
+ failure = error;
871
+ });
872
+ const conflicted = changedPaths(await run$1([
700
873
  "diff",
701
874
  "--name-only",
702
- "--diff-filter=U"
703
- ]).then((out) => out.split("\n").map((line) => line.trim()).filter(Boolean), () => []);
704
- await run$1(["merge", "--abort"]).catch(() => void 0);
705
- if (conflicted.length > 0) throw new SourceConflictError(conflicted);
706
- throw error;
707
- }
708
- }
709
- const isRejected = (error) => error instanceof GitError && /rejected|non-fast-forward|fetch first|stale info|failed to push some refs/i.test(error.message);
710
-
711
- //#endregion
712
- //#region src/core/paywalls/source/source-push.ts
713
- var GitRequiredError = class extends Error {
714
- constructor() {
715
- super("superwall publish requires git for the source step — install git");
716
- }
717
- };
718
- async function assertGit(hasGit = gitAvailable) {
719
- if (!await hasGit()) throw new GitRequiredError();
720
- }
721
- async function pushSource(input) {
722
- for (let attempt = 0;; attempt++) {
723
- const access = await mintSourceAccess(input.api, input.paywallId);
724
- const pushed = await pushSourceTree({
725
- access,
726
- base: readSourceBase(input.superwallDir, access.repo),
727
- overwrite: input.overwrite,
728
- files: input.files,
729
- message: {
730
- kind: input.kind,
731
- surface: input.surface,
732
- version: input.version,
733
- paywallId: input.paywallId,
734
- applicationId: input.applicationId,
735
- snapshotSha: input.snapshotId,
736
- framework: input.framework,
737
- cli: input.cli,
738
- note: input.note,
739
- external: input.external
875
+ "--diff-filter=U",
876
+ "-z"
877
+ ]));
878
+ if (failure !== void 0 && conflicted.length === 0) throw failure;
879
+ const blocking = conflicted.filter((file) => !DERIVED_FILES.has(file));
880
+ if (blocking.length > 0 && !input.theirs) throw new PullConflictError(blocking);
881
+ const present = new Set((await run$1([
882
+ "ls-tree",
883
+ "-r",
884
+ "--name-only",
885
+ "-z",
886
+ head
887
+ ])).split("\0").filter(Boolean));
888
+ for (const file of conflicted) if (present.has(file)) await run$1([
889
+ "--literal-pathspecs",
890
+ "checkout",
891
+ head,
892
+ "--",
893
+ file
894
+ ]);
895
+ else await run$1([
896
+ "--literal-pathspecs",
897
+ "rm",
898
+ "--quiet",
899
+ "--force",
900
+ "--",
901
+ file
902
+ ]);
903
+ const unresolved = changedPaths(await run$1([
904
+ "diff",
905
+ "--name-only",
906
+ "--diff-filter=U",
907
+ "-z"
908
+ ]));
909
+ if (unresolved.length > 0) throw new PullConflictError(unresolved);
910
+ const changes = [];
911
+ const staged = (await run$1([
912
+ "diff",
913
+ "--cached",
914
+ "--name-status",
915
+ "--no-renames",
916
+ "-z",
917
+ own
918
+ ])).split("\0").filter(Boolean);
919
+ const removed = [];
920
+ for (let index = 0; index + 1 < staged.length; index += 2) {
921
+ const status = staged[index];
922
+ const file = staged[index + 1];
923
+ if (file === void 0 || DERIVED_FILES.has(file)) continue;
924
+ if (status === "D") {
925
+ removed.push({
926
+ path: file,
927
+ content: void 0
928
+ });
929
+ continue;
740
930
  }
741
- });
742
- if (pushed.syncedTo) writeSourceBase(input.superwallDir, access.repo, pushed.syncedTo);
743
- try {
744
- await linkCommit(input, access, pushed.commitSha);
745
- return pushed;
746
- } catch (error) {
747
- if (attempt === 0 && error instanceof ApiError && error.status === 409) continue;
748
- throw error;
931
+ const stat = fs.lstatSync(path.join(dir, file), { throwIfNoEntry: false });
932
+ if (stat?.isSymbolicLink()) throw new Error(`The source repo has ${file} as a symlink — the CLI only pulls regular files.`);
933
+ changes.push({
934
+ path: file,
935
+ content: stat ? fs.readFileSync(path.join(dir, file)) : void 0
936
+ });
749
937
  }
938
+ changes.sort((a, b) => a.path.localeCompare(b.path));
939
+ changes.unshift(...removed.sort((a, b) => a.path.localeCompare(b.path)));
940
+ const shown = (name) => present.has(name) ? run$1(["show", `${head}:${name}`]) : void 0;
941
+ return {
942
+ status: "pulled",
943
+ head,
944
+ changes,
945
+ lock: await shown(LOCK_FILE),
946
+ types: await shown(TYPES_FILE)
947
+ };
948
+ } finally {
949
+ fs.rmSync(dir, {
950
+ recursive: true,
951
+ force: true
952
+ });
750
953
  }
751
954
  }
752
- const LINK_ATTEMPTS = 2;
753
- const LINK_RETRY_DELAY_MS = 300;
754
- async function linkCommit(input, access, commitSha) {
755
- for (let attempt = 1;; attempt++) try {
756
- await linkSourceCommit(input.api, input.paywallId, input.version, {
757
- commitSha,
758
- tokenId: access.tokenId
759
- });
760
- return;
761
- } catch (error) {
762
- if (attempt >= LINK_ATTEMPTS || !isTransient(error)) throw error;
763
- await setTimeout(LINK_RETRY_DELAY_MS);
955
+ const changedPaths = (output) => output.split("\0").filter(Boolean).sort();
956
+ function replaceTree(dir, files) {
957
+ for (const entry of fs.readdirSync(dir)) if (entry !== ".git") fs.rmSync(path.join(dir, entry), {
958
+ recursive: true,
959
+ force: true
960
+ });
961
+ for (const file of files) {
962
+ const target = path.join(dir, file.path);
963
+ fs.mkdirSync(path.dirname(target), { recursive: true });
964
+ fs.writeFileSync(target, file.content);
764
965
  }
765
966
  }
766
- const isTransient = (error) => error instanceof ApiUnreachableError || error instanceof ApiError && error.status >= 500;
967
+ const isRejected = (error) => error instanceof GitError && /rejected|non-fast-forward|fetch first|stale info|failed to push some refs/i.test(error.message);
767
968
 
768
969
  //#endregion
769
970
  //#region src/core/paywalls/project/session.ts
@@ -794,4 +995,4 @@ async function requireApi(interactive, login = performLoginWithUi) {
794
995
  }
795
996
 
796
997
  //#endregion
797
- export { targetLabel as _, gitAvailable as a, requirePlatform as b, projectPackageName as c, listProjectCatalogue as d, listProjectProducts as f, planTargets as g, parsePlatformFlags as h, pushSource as i, writeProjectScaffold as l, requireProducts as m, requireApi as n, collectSourceFiles as o, projectForApplication as p, assertGit as r, warnNotPortable as s, LoginRequiredError as t, listApplicationCatalogue as u, wantedPlatforms as v, resolveApps as x, resolveBinding as y };
998
+ export { requirePlatform as _, pushSourceTree as a, writeSourceBase as c, writeProjectScaffold as d, parsePlatformFlags as f, PLATFORMS as g, wantedPlatforms as h, pullSourceTree as i, collectSourceFiles as l, targetLabel as m, requireApi as n, statIfPresent as o, planTargets as p, gitAvailable as r, readSourceBase as s, LoginRequiredError as t, projectPackageName as u, resolveApps as v };