@superwall/cli 1.4.0 → 1.6.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 (103) hide show
  1. package/README.md +21 -5
  2. package/dist/{actions-EfP8phmb.js → actions-Dt35nIi8.js} +3 -2
  3. package/dist/{api-CEwXCCoC.js → api-BOR-uXZe.js} +9 -9
  4. package/dist/{app-D8mEVlQo.js → app-BU27SLPX.js} +9 -9
  5. package/dist/{asa-BFWehnTA.js → asa-2ykGnjaV.js} +11 -11
  6. package/dist/{asc-DJqQmtmR.js → asc-r3xmFT0L.js} +14 -14
  7. package/dist/{auth-CT2DWX8r.js → auth-BWZfguI8.js} +9 -9
  8. package/dist/auth.js +2 -2
  9. package/dist/{billing-BzEnVPD2.js → billing-BsQgXXYh.js} +1 -1
  10. package/dist/{bind-BZxVyt9P.js → bind-BSTAinn6.js} +5 -4
  11. package/dist/{command-DP96_gmP.js → command-DMoMn7uc.js} +39 -16
  12. package/dist/{create-Q8TqqjZt.js → create-CSo6XjSm.js} +118 -91
  13. package/dist/dev-B0MF6z3L.js +21 -0
  14. package/dist/{dev-DlCcwFu5.js → dev-CuXa3J4Z.js} +29 -24
  15. package/dist/{doctor-CJsjHpCZ.js → doctor-DXJaDqsx.js} +10 -10
  16. package/dist/{drivers-UT36AnOw.js → drivers-Cr252DOJ.js} +3 -3
  17. package/dist/entry.js +84 -50
  18. package/dist/{existing-Cak1WxWB.js → existing-Ckx_g7Be.js} +6 -3
  19. package/dist/{feedback-DDRzoqPx.js → feedback-Dt5yebMS.js} +6 -6
  20. package/dist/{hosted-CEH78QVn.js → hosted-Cjekn8oJ.js} +2 -2
  21. package/dist/{integrate-D8jyhDzk.js → integrate-DVqhvPVq.js} +25 -66
  22. package/dist/{login-kneYhhk0.js → login-Bjj8QvIN.js} +6 -6
  23. package/dist/migrate-qmvOtp3l.js +283 -0
  24. package/dist/open-studio-CpHqjovS.js +1299 -0
  25. package/dist/{org-Cg25bcsj.js → org-CV8c849b.js} +3 -3
  26. package/dist/{output-csAtR6kJ.js → output-CiELrN8w.js} +15 -2
  27. package/dist/{pipeline-DAeI9tHs.js → pipeline-DSCHL9KA.js} +482 -9
  28. package/dist/{print-skill-BHVPP9cX.js → print-skill-CaHRJ8xW.js} +7 -7
  29. package/dist/{promote-Boek5K2d.js → promote-UMTh8Q33.js} +17 -18
  30. package/dist/publish-DWX8S9yZ.js +34 -0
  31. package/dist/push-Dox4_5Dq.js +34 -0
  32. package/dist/{query-B8G6T8Ba.js → query-CnSsDZ7Q.js} +10 -10
  33. package/dist/reports-C0xHCLnt.js +27 -0
  34. package/dist/{resource-DjsWVka-.js → resource-5bgyyL9B.js} +15 -15
  35. package/dist/{resources-s64mBHaC.js → resources-Bf9O1JNM.js} +28 -2
  36. package/dist/{run-BtcQJCP8.js → run-BVeZWbXx.js} +39 -22
  37. package/dist/{scan-DJixvuHn.js → scan-CAObNRgc.js} +44 -4
  38. package/dist/skills/superwall/SKILL.md +146 -0
  39. package/dist/skills/superwall/references/api.md +275 -0
  40. package/dist/skills/superwall/references/asa.md +160 -0
  41. package/dist/skills/superwall/references/asc.md +96 -0
  42. package/dist/skills/superwall/references/dashboard-links.md +57 -0
  43. package/dist/skills/superwall/references/data-analytics.md +893 -0
  44. package/dist/skills/superwall/references/docs.md +51 -0
  45. package/dist/skills/superwall/references/sdk-integration.md +105 -0
  46. package/dist/skills/superwall/references/sdk-source.md +18 -0
  47. package/{skills/superwall-dashboard/SKILL.md → dist/skills/superwall/workflows/dashboard/playbook.md} +3 -9
  48. package/{skills/superwall-dashboard/references → dist/skills/superwall/workflows/dashboard}/setup.md +1 -3
  49. package/dist/skills/superwall/workflows/integrate/android.md +292 -0
  50. package/{skills/superwall-integrate/SKILL.md → dist/skills/superwall/workflows/integrate/playbook.md} +16 -11
  51. package/{skills/superwall-migrate/references → dist/skills/superwall/workflows/migrate}/adapty.md +4 -4
  52. package/{skills/superwall-migrate/SKILL.md → dist/skills/superwall/workflows/migrate/playbook.md} +4 -10
  53. package/{skills/superwall-migrate/references → dist/skills/superwall/workflows/migrate}/qonversion.md +4 -4
  54. package/{skills/superwall-migrate/references → dist/skills/superwall/workflows/migrate}/revenuecat.md +4 -4
  55. package/dist/skills/superwall/workflows/placements/android.md +175 -0
  56. package/{skills/superwall-placements/references → dist/skills/superwall/workflows/placements}/expo.md +1 -1
  57. package/{skills/superwall-placements/references → dist/skills/superwall/workflows/placements}/flutter.md +1 -1
  58. package/{skills/superwall-placements/references → dist/skills/superwall/workflows/placements}/ios.md +1 -1
  59. package/{skills/superwall-placements/SKILL.md → dist/skills/superwall/workflows/placements/playbook.md} +6 -10
  60. package/{skills/superwall-placements/references → dist/skills/superwall/workflows/placements}/react-native.md +2 -2
  61. package/{skills/superwall-placements/references → dist/skills/superwall/workflows/placements}/strategy.md +4 -3
  62. package/dist/skills/superwall/workflows/review/android.md +120 -0
  63. package/{skills/superwall-review/references → dist/skills/superwall/workflows/review}/expo.md +1 -1
  64. package/{skills/superwall-review/references → dist/skills/superwall/workflows/review}/flutter.md +1 -1
  65. package/{skills/superwall-review/references → dist/skills/superwall/workflows/review}/ios.md +1 -1
  66. package/{skills/superwall-review/SKILL.md → dist/skills/superwall/workflows/review/playbook.md} +2 -7
  67. package/{skills/superwall-review/references → dist/skills/superwall/workflows/review}/react-native.md +1 -1
  68. package/dist/skills/superwall-framework/SKILL.md +253 -0
  69. package/dist/skills/superwall-framework/references/cli.md +340 -0
  70. package/dist/skills/superwall-framework/references/examples.md +123 -0
  71. package/dist/skills/superwall-framework/references/layout.md +295 -0
  72. package/dist/skills/superwall-framework/references/migrate-from-editor.md +208 -0
  73. package/dist/skills/superwall-framework/references/migrate-from-native.md +193 -0
  74. package/dist/skills/superwall-framework/references/mobile-design.md +371 -0
  75. package/dist/skills/superwall-framework/references/native/android.md +83 -0
  76. package/dist/skills/superwall-framework/references/native/flutter.md +65 -0
  77. package/dist/skills/superwall-framework/references/native/ios.md +77 -0
  78. package/dist/skills/superwall-framework/references/native/react-native.md +67 -0
  79. package/dist/skills/superwall-framework/references/responsive.md +162 -0
  80. package/dist/{skills-CRG1xk0G.js → skills-Cu41i-Az.js} +12 -12
  81. package/dist/{skills-CODut1Hn.js → skills-grTDuHlc.js} +134 -36
  82. package/dist/{spinner-B9dT3DBY.js → spinner-DFctF_Jw.js} +1 -1
  83. package/dist/{telemetry-BtkMdT-5.js → telemetry-BuCbmoux.js} +3 -3
  84. package/dist/{token-hM7V1KMG.js → token-mju3Q-vc.js} +3 -3
  85. package/dist/{ui-Lqt_zFOr.js → ui-4gLyfrgl.js} +76 -46
  86. package/dist/{update-CeylIjx5.js → update-DnGfpCD7.js} +2 -2
  87. package/dist/{upgrade-DRqUfCBT.js → upgrade-PMoj3yqJ.js} +6 -6
  88. package/package.json +8 -7
  89. package/prompts/actions/paywall-migrate.xml +24 -0
  90. package/prompts/actions/screen-migrate.xml +26 -0
  91. package/dist/git-ZwA3Mx8m.js +0 -433
  92. package/dist/migrate-D_x1oyTk.js +0 -114
  93. package/dist/publish-C-zEUnO9.js +0 -35
  94. package/dist/push-DUDQG-EO.js +0 -35
  95. package/skills/README.md +0 -118
  96. /package/dist/{api-output-D9ggXQIr.js → api-output-CEhN-U_N.js} +0 -0
  97. /package/dist/{asc-products-C6MvSy8H.js → asc-products-1e1DoGeL.js} +0 -0
  98. /package/dist/{params-B1zeElGa.js → params-BxgTuCzr.js} +0 -0
  99. /package/{skills/superwall-integrate/references → dist/skills/superwall/workflows/integrate}/expo.md +0 -0
  100. /package/{skills/superwall-integrate/references → dist/skills/superwall/workflows/integrate}/flutter.md +0 -0
  101. /package/{skills/superwall-integrate/references → dist/skills/superwall/workflows/integrate}/ios.md +0 -0
  102. /package/{skills/superwall-integrate/references → dist/skills/superwall/workflows/integrate}/react-native.md +0 -0
  103. /package/dist/{storekit-DPonXSwe.js → storekit-Dlpbq5Wv.js} +0 -0
@@ -0,0 +1,1299 @@
1
+ import { f as DASHBOARD_URL } from "./output-CiELrN8w.js";
2
+ import { n as executeCommand, r as ApiError } from "./command-DMoMn7uc.js";
3
+ import { i as stripReport } from "./ui-4gLyfrgl.js";
4
+ import { i as loadBundledSkill } from "./skills-grTDuHlc.js";
5
+ import { n as allDeps, r as readPackageJson } from "./scan-CAObNRgc.js";
6
+ import { t as detectDrivers } from "./drivers-Cr252DOJ.js";
7
+ import { c as getPaywall, p as listApplications, x as projectOrganizationId } from "./resources-Bf9O1JNM.js";
8
+ import { F as isScreenOrigin, I as readLock, L as writeApp, R as writeOrigin, j as projectPackageName } from "./pipeline-DSCHL9KA.js";
9
+ import { a as copyToClipboard, i as loadPrompt, n as runWithDriverFallback } from "./run-BVeZWbXx.js";
10
+ import { t as runDev } from "./dev-CuXa3J4Z.js";
11
+ import * as path from "node:path";
12
+ import * as fs from "node:fs";
13
+ import fg from "fast-glob";
14
+
15
+ //#region src/core/paywalls/project/origin.ts
16
+ const ACTIONS = [
17
+ "purchase",
18
+ "restore",
19
+ "close",
20
+ "open-url",
21
+ "navigate-page",
22
+ "set-state",
23
+ "set-attribute",
24
+ "set-product-index",
25
+ "custom-placement",
26
+ "custom-in-app",
27
+ "request-permission",
28
+ "request-store-review",
29
+ "redeem-discount",
30
+ "redeem-purchase",
31
+ "select-choice",
32
+ "select-indicator",
33
+ "focus-input",
34
+ "scroll-to-element",
35
+ "teleport-to-web"
36
+ ];
37
+ const DOCUMENT_SCRIPT = /<script id="vike_pageContext" type="application\/json">([\s\S]*?)<\/script>/;
38
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
39
+ const findStore = (value, depth = 0) => {
40
+ if (depth > 8 || !isRecord(value)) return void 0;
41
+ if (isRecord(value.store) && isRecord(value.schema)) return value.store;
42
+ for (const entry of Object.values(value)) {
43
+ const found = findStore(entry, depth + 1);
44
+ if (found) return found;
45
+ }
46
+ };
47
+ const hex = (value) => value.length === 9 && value.toLowerCase().endsWith("ff") ? value.slice(0, 7) : value;
48
+ const backgroundOf = (html) => {
49
+ const light = /html\s*\{\s*background-color:\s*(#[0-9a-fA-F]{6,8})/.exec(html)?.[1];
50
+ if (!light) return void 0;
51
+ const dark = /html\.dark\s*\{\s*background-color:\s*(#[0-9a-fA-F]{6,8})/.exec(html)?.[1];
52
+ return dark && dark !== light ? {
53
+ light: hex(light),
54
+ dark: hex(dark)
55
+ } : { light: hex(light) };
56
+ };
57
+ const presentationOf = (value) => {
58
+ if (!isRecord(value) || typeof value.type !== "string") return void 0;
59
+ const number = (entry) => typeof entry === "number" ? entry : void 0;
60
+ switch (value.type) {
61
+ case "FULLSCREEN": return { style: "fullscreen" };
62
+ case "MODAL": return { style: "modal" };
63
+ case "PUSH": return { style: "push" };
64
+ case "NO_ANIMATION": return { style: "noAnimation" };
65
+ case "DRAWER": return {
66
+ style: "drawer",
67
+ height: number(value.height),
68
+ cornerRadius: number(value.cornerRadius)
69
+ };
70
+ case "POPUP": return {
71
+ style: "popup",
72
+ width: number(value.width),
73
+ height: number(value.height),
74
+ cornerRadius: number(value.cornerRadius)
75
+ };
76
+ default: return;
77
+ }
78
+ };
79
+ const enabled = (value) => value === "ENABLED" ? true : value === "DISABLED" ? false : void 0;
80
+ function parseOriginDocument(html) {
81
+ const json = DOCUMENT_SCRIPT.exec(html)?.[1];
82
+ if (json === void 0) return void 0;
83
+ let context;
84
+ try {
85
+ context = JSON.parse(json);
86
+ } catch {
87
+ return;
88
+ }
89
+ const store = findStore(context);
90
+ if (!store) return void 0;
91
+ const records = Object.values(store).filter(isRecord);
92
+ const ofType = (typeName) => records.filter((record) => record.typeName === typeName);
93
+ const paywall = ofType("paywall")[0];
94
+ const nodes = ofType("node");
95
+ const settings = {};
96
+ if (paywall) {
97
+ const presentation = presentationOf(paywall.presentationStyleV3) ?? presentationOf({ type: paywall.presentationStyle });
98
+ if (presentation) settings.presentation = presentation;
99
+ if (paywall.featureGating === "GATED") settings.featureGating = "gated";
100
+ if (paywall.featureGating === "NON_GATED") settings.featureGating = "nonGated";
101
+ const scroll = enabled(paywall.isScrollEnabled);
102
+ if (scroll !== void 0) settings.scrollEnabled = scroll;
103
+ const controller = enabled(paywall.gameControllerSupport);
104
+ if (controller !== void 0) settings.gameControllerEnabled = controller;
105
+ const cache = enabled(paywall.onDeviceCache);
106
+ if (cache !== void 0) settings.onDeviceCacheEnabled = cache;
107
+ if (typeof paywall.webCheckoutDestination === "string") settings.webCheckoutDestination = paywall.webCheckoutDestination;
108
+ }
109
+ const locales = ofType("paywall_language").map((record) => typeof record.id === "string" ? record.id.split(":")[1] : void 0).filter((locale) => typeof locale === "string" && locale !== "").sort();
110
+ const nodeCounts = {};
111
+ for (const node of nodes) {
112
+ if (typeof node.type !== "string") continue;
113
+ nodeCounts[node.type] = (nodeCounts[node.type] ?? 0) + 1;
114
+ }
115
+ const navigationIds = new Set(nodes.filter((node) => node.type === "navigation").map((node) => node.id));
116
+ const pages = nodes.filter((node) => navigationIds.has(node.parentId)).length;
117
+ const serialized = JSON.stringify(store);
118
+ const actions = {};
119
+ for (const action of ACTIONS) {
120
+ const count = serialized.split(`"type":"${action}"`).length - 1;
121
+ if (count > 0) actions[action] = count;
122
+ }
123
+ const seen = /* @__PURE__ */ new Set();
124
+ serialized.replace(/\{\{\s*([^}]*?)\s*\}\}/g, (_match, expression) => {
125
+ seen.add(expression.replace(/\\"/g, "\"").trim());
126
+ return "";
127
+ });
128
+ const variables = [...seen].sort();
129
+ return {
130
+ settings,
131
+ background: backgroundOf(html),
132
+ locales,
133
+ inventory: {
134
+ pages: Math.max(pages, 1),
135
+ drawers: nodeCounts.drawer ?? 0,
136
+ nodes: nodeCounts,
137
+ actions,
138
+ variables
139
+ }
140
+ };
141
+ }
142
+ const PLATFORMS = new Set([
143
+ "ios",
144
+ "android",
145
+ "web"
146
+ ]);
147
+ const platformOf = (value) => value !== void 0 && PLATFORMS.has(value) ? value : void 0;
148
+ const apiPresentation = (value) => {
149
+ switch (value) {
150
+ case "modal": return { style: "modal" };
151
+ case "push": return { style: "push" };
152
+ case "no_animation": return { style: "noAnimation" };
153
+ case "drawer": return { style: "drawer" };
154
+ case "popup": return { style: "popup" };
155
+ default: return { style: "fullscreen" };
156
+ }
157
+ };
158
+ function slugOf(value) {
159
+ const slug = value.toLowerCase().replace(/\([^)]*\)/g, " ").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
160
+ return slug === "" ? "paywall" : slug;
161
+ }
162
+ function originOf(detail, document) {
163
+ const name = detail.name ?? `Paywall ${detail.id}`;
164
+ return {
165
+ id: detail.id,
166
+ name,
167
+ slug: slugOf(name),
168
+ identifier: detail.identifier,
169
+ applicationId: detail.applicationId,
170
+ projectId: detail.projectId,
171
+ platform: platformOf(detail.platform),
172
+ url: detail.url,
173
+ previewUrl: detail.previewUrl,
174
+ products: detail.products,
175
+ settings: {
176
+ presentation: document?.settings.presentation ?? apiPresentation(detail.presentationStyle),
177
+ featureGating: document?.settings.featureGating ?? (detail.featureGating === "gated" ? "gated" : "nonGated"),
178
+ scrollEnabled: document?.settings.scrollEnabled ?? true,
179
+ gameControllerEnabled: document?.settings.gameControllerEnabled ?? false,
180
+ onDeviceCacheEnabled: document?.settings.onDeviceCacheEnabled ?? true,
181
+ ...document?.settings.webCheckoutDestination === void 0 ? {} : { webCheckoutDestination: document.settings.webCheckoutDestination }
182
+ },
183
+ background: document?.background,
184
+ locales: document?.locales ?? [],
185
+ inventory: document?.inventory
186
+ };
187
+ }
188
+ const literal$1 = (value) => JSON.stringify(value);
189
+ const presentationSource = (presentation) => {
190
+ if (presentation.style === "fullscreen") return void 0;
191
+ if (presentation.style === "drawer") {
192
+ const geometry = [presentation.height === void 0 ? void 0 : `height: ${presentation.height}`, presentation.cornerRadius === void 0 ? void 0 : `cornerRadius: ${presentation.cornerRadius}`].filter((entry) => entry !== void 0);
193
+ return geometry.length === 0 ? `{ style: "drawer" }` : `{ style: "drawer", drawer: { ${geometry.join(", ")} } }`;
194
+ }
195
+ if (presentation.style === "popup") {
196
+ const geometry = [
197
+ presentation.width === void 0 ? void 0 : `width: ${presentation.width}`,
198
+ presentation.height === void 0 ? void 0 : `height: ${presentation.height}`,
199
+ presentation.cornerRadius === void 0 ? void 0 : `cornerRadius: ${presentation.cornerRadius}`
200
+ ].filter((entry) => entry !== void 0);
201
+ return geometry.length === 0 ? `{ style: "popup" }` : `{ style: "popup", popup: { ${geometry.join(", ")} } }`;
202
+ }
203
+ return `{ style: ${literal$1(presentation.style)} }`;
204
+ };
205
+ const checkoutSource = (origin) => {
206
+ if (origin.platform !== "web") return void 0;
207
+ if (origin.settings.webCheckoutDestination === "PAYWALL_APPLE_PAY") return `"applePay"`;
208
+ if (origin.settings.webCheckoutDestination === "PAYWALL_EMBEDDED") return `"sheet"`;
209
+ };
210
+ function originConfigSource(origin) {
211
+ const lines = [` name: ${literal$1(origin.name)},`];
212
+ if (origin.platform) lines.push(` platforms: [${literal$1(origin.platform)}],`);
213
+ if (origin.products.length > 0) {
214
+ lines.push(` products: {`);
215
+ for (const product of origin.products) {
216
+ const key = /^[A-Za-z_$][\w$]*$/.test(product.reference) ? product.reference : literal$1(product.reference);
217
+ lines.push(` ${key}: ${literal$1(product.identifier)},`);
218
+ }
219
+ lines.push(` },`);
220
+ }
221
+ const checkout = checkoutSource(origin);
222
+ if (checkout) lines.push(` checkout: ${checkout},`);
223
+ const presentation = presentationSource(origin.settings.presentation);
224
+ if (presentation) lines.push(` presentation: ${presentation},`);
225
+ if (origin.background) lines.push(origin.background.dark ? ` background: { light: ${literal$1(origin.background.light)}, dark: ${literal$1(origin.background.dark)} },` : ` background: ${literal$1(origin.background.light)},`);
226
+ if (origin.settings.featureGating === "gated") lines.push(` featureGating: "gated",`);
227
+ if (!origin.settings.scrollEnabled) lines.push(` scrollEnabled: false,`);
228
+ if (origin.settings.gameControllerEnabled) lines.push(` gameControllerEnabled: true,`);
229
+ if (!origin.settings.onDeviceCacheEnabled) lines.push(` onDeviceCacheEnabled: false,`);
230
+ return `import { definePaywall } from "superwall/config";\n\nexport default definePaywall({\n${lines.join("\n")}\n});\n`;
231
+ }
232
+ const table$1 = (rows) => rows.map((row) => `| ${row.join(" | ")} |`).join("\n");
233
+ function originBrief(origin) {
234
+ const products = origin.products.length === 0 ? "_The dashboard lists no products for this paywall._" : `${table$1([
235
+ [
236
+ "Reference",
237
+ "Store",
238
+ "Identifier"
239
+ ],
240
+ [
241
+ "---",
242
+ "---",
243
+ "---"
244
+ ],
245
+ ...origin.products.map((product) => [
246
+ `\`${product.reference}\``,
247
+ product.store ?? "",
248
+ product.identifier === "missing" ? "**missing** — pick a real product before pushing" : `\`${product.identifier}\``
249
+ ])
250
+ ])}`;
251
+ const inventory = origin.inventory;
252
+ const counts = (record) => Object.entries(record).sort(([, a], [, b]) => b - a).map(([key, count]) => `${key} ×${count}`).join(", ");
253
+ const inventoryText = inventory ? [
254
+ `- Pages: ${inventory.pages}${inventory.pages > 1 ? " (children of the editor's navigation element — one route each)" : ""}`,
255
+ `- Drawers: ${inventory.drawers}`,
256
+ `- Elements: ${counts(inventory.nodes) || "none"}`,
257
+ `- Actions: ${counts(inventory.actions) || "none"}`,
258
+ `- Product variables in text: ${inventory.variables.length === 0 ? "none" : inventory.variables.map((entry) => `\`{{ ${entry} }}\``).join(", ")}`,
259
+ `- Locales: ${origin.locales.length === 0 ? "none beyond the default" : origin.locales.join(", ")}`
260
+ ].join("\n") : "_The served document could not be read; inventory it from the URL above before building._";
261
+ return `# Migrating "${origin.name}" to code
262
+
263
+ Rebuild this dashboard paywall as a framework paywall. Follow the
264
+ \`superwall-framework\` skill's migration playbook
265
+ (\`references/migrate-from-editor.md\`); this file is its input and is
266
+ deleted when the migration is done.
267
+
268
+ ## Source
269
+
270
+ - Dashboard paywall: ${origin.id}${origin.identifier ? ` (\`${origin.identifier}\`)` : ""}
271
+ - Served document: ${origin.url ?? "unknown"}
272
+ - Screenshot: ${origin.previewUrl ?? "none"}
273
+ - Platform: ${origin.platform ?? "unknown"}
274
+ - Presentation: ${origin.settings.presentation.style}
275
+
276
+ ## Products
277
+
278
+ ${products}
279
+
280
+ ## Inventory
281
+
282
+ ${inventoryText}
283
+
284
+ ## What \`config.ts\` already carries
285
+
286
+ Name, platform, products, presentation, feature gating, scrolling, game
287
+ controller, on-device cache${origin.background ? ", background" : ""}${origin.locales.length > 0 ? ", and the locales to provide catalogs for" : ""}. Everything under \`app/\` is the
288
+ starter and has to be rebuilt from the source.
289
+
290
+ ## Done when
291
+
292
+ - Every page, state and locale of the source is rebuilt, verified side by
293
+ side against **Original** in the studio's Compare menu, in both schemes.
294
+ - The user has reviewed it and asked for the push.
295
+ - This file is deleted. The dashboard paywall keeps serving until a campaign
296
+ points at the new one.
297
+ `;
298
+ }
299
+
300
+ //#endregion
301
+ //#region src/core/paywalls/project/template.ts
302
+ const packageJson = (name) => `${JSON.stringify({
303
+ name,
304
+ private: true,
305
+ type: "module",
306
+ scripts: {
307
+ dev: "superwall dev",
308
+ push: "superwall push",
309
+ promote: "superwall promote",
310
+ ship: "superwall publish",
311
+ typecheck: "tsc -p tsconfig.json"
312
+ },
313
+ dependencies: {
314
+ react: "19.1.0",
315
+ "react-dom": "19.1.0",
316
+ superwall: "latest"
317
+ },
318
+ devDependencies: {
319
+ "@types/react": "^19.1.0",
320
+ "@types/react-dom": "^19.1.0",
321
+ typescript: "5.8.3"
322
+ }
323
+ }, null, 2)}\n`;
324
+ const README = `# Your paywalls
325
+
326
+ Each directory under \`paywalls/\` is one paywall — React pages in \`app/\`,
327
+ products and name in \`config.ts\`.
328
+
329
+ \`\`\`bash
330
+ bun dev # open the studio and preview live
331
+ bun run push # push versions to Superwall (production untouched)
332
+ bun run ship # push and promote to production
333
+ \`\`\`
334
+
335
+ ## For coding agents
336
+
337
+ The \`superwall-framework\` skill is the playbook for this directory: the
338
+ layout and inset system, mobile design, the CLI, and where the docs are.
339
+ \`superwall login\` installs it; otherwise:
340
+
341
+ \`\`\`bash
342
+ npx skills add https://github.com/superwall/skills/tree/next --skill superwall-framework --global --yes --agent claude-code universal --full-depth
343
+ \`\`\`
344
+
345
+ The framework is on the \`next\` channel: its commands exist only while
346
+ \`SUPERWALL_CHANNEL=next\` is set in the environment.
347
+
348
+ Docs: \`curl -sL https://superwall.com/docs/framework/llms.txt\`
349
+ `;
350
+ const TSCONFIG = "{\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"lib\": [\"ES2023\", \"DOM\", \"DOM.Iterable\"],\n \"module\": \"ESNext\",\n \"moduleResolution\": \"bundler\",\n \"jsx\": \"react-jsx\",\n \"strict\": true,\n \"isolatedModules\": true,\n \"resolveJsonModule\": true,\n \"skipLibCheck\": true,\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true,\n \"noFallthroughCasesInSwitch\": true,\n \"noEmit\": true,\n \"paths\": {\n \"@/*\": [\"./*\"]\n }\n },\n \"include\": [\".\"]\n}\n";
351
+ const SUPERWALL_DTS = "// Generated by the Superwall CLI. Commit it; don't edit it, and don't delete it.\n// It is what makes `import hero from \"./assets/hero.jpg\"` typecheck and what\n// makes router.push(\"...\") autocomplete and reject typos. `superwall dev`\n// rewrites it whenever your app/ directories change.\n\n/// <reference types=\"superwall/assets\" />\n\ndeclare module \"superwall/navigation\" {\n interface SuperwallRoutes {\n index: true;\n }\n}\n\nexport type SuperwallRouteName = keyof import(\"superwall/navigation\").SuperwallRoutes;\n";
352
+ const GITIGNORE = "node_modules/\n.superwall\n.env\n";
353
+ const CONFIG = "import { definePaywall } from \"superwall/config\";\n\nexport default definePaywall({\n /** What this paywall is called on Superwall. Defaults to the directory name. */\n name: \"Pro\",\n\n /**\n * The products this paywall sells, as `reference: \"store identifier\"`.\n *\n * The identifiers below are placeholders — replace them with products that\n * exist in your Superwall dashboard. Nothing about a product is stored here:\n * price, period and trial all come from the store at runtime, which is why\n * `useProducts()` returns nothing until these match. Run `superwall dev`\n * against a connected app and the real prices appear, locally and on device.\n *\n * A reference the dashboard has no product for blocks publishing, so a\n * paywall can never ship with prices it cannot render.\n */\n products: {\n monthly: \"pro_999_month\",\n },\n});\n";
354
+ const MESSAGES = "export default {\n paywall: {\n title: \"Go Pro\",\n subtitle: \"Everything unlocked, cancel whenever you like.\",\n cta: \"Subscribe · {price}\",\n ctaBare: \"Subscribe\",\n restore: \"Restore purchases\",\n close: \"Close\",\n },\n footer: {\n builtWith: \"Built with\",\n superwall: \"Superwall\",\n },\n} as const;\n";
355
+ const INDEX = "import { useActions, useHaptics, useProducts, usePurchase, useTranslation } from \"superwall/hooks\";\n\nexport default function Index() {\n const { close, restore } = useActions();\n const { getProduct } = useProducts();\n const { purchase } = usePurchase();\n const { t } = useTranslation();\n const haptics = useHaptics();\n\n const monthly = getProduct(\"monthly\");\n const price = monthly?.variables.price;\n\n return (\n <main className=\"page\">\n <button type=\"button\" className=\"close\" aria-label={t(\"paywall.close\")} onClick={close}>\n ✕\n </button>\n\n <div className=\"lede\">\n <h1>{t(\"paywall.title\")}</h1>\n <p>{t(\"paywall.subtitle\")}</p>\n </div>\n\n <div className=\"actions\">\n <button\n type=\"button\"\n className=\"button button--primary\"\n onClick={() => {\n haptics.light();\n purchase(\"monthly\");\n }}\n >\n {price ? t(\"paywall.cta\", { price }) : t(\"paywall.ctaBare\")}\n </button>\n <button\n type=\"button\"\n className=\"link\"\n onClick={() => {\n haptics.light();\n restore();\n }}\n >\n {t(\"paywall.restore\")}\n </button>\n </div>\n </main>\n );\n}\n";
356
+ const LAYOUT = "import type { PropsWithChildren } from \"react\";\nimport { useActions, useHaptics, useTranslation } from \"superwall/hooks\";\nimport \"./theme.css\";\n\nexport default function Layout({ children }: PropsWithChildren) {\n const { openUrl } = useActions();\n const { t } = useTranslation();\n const haptics = useHaptics();\n\n return (\n <div className=\"shell\">\n {children}\n <footer className=\"built\">\n {t(\"footer.builtWith\")}\n <button\n type=\"button\"\n className=\"wordmark\"\n aria-label={t(\"footer.superwall\")}\n onClick={() => {\n haptics.light();\n openUrl(\"https://superwall.com\");\n }}\n >\n <span className=\"wordmark-accent\">$UPER</span>WALL\n </button>\n </footer>\n </div>\n );\n}\n";
357
+ const THEME = "@import url(\"https://fonts.googleapis.com/css2?family=Manrope:wght@200..800&family=Roboto+Mono:wght@400..500&display=swap\");\n\n:root {\n --bg: #fdfef6;\n --surface: #f6f7ef;\n --elevated: #fff;\n --fg: #0c0b0a;\n --accent: #46d7d4;\n\n --fg-body: color-mix(in srgb, var(--fg) 70%, transparent);\n --fg-muted: color-mix(in srgb, var(--fg) 55%, transparent);\n --fg-caption: color-mix(in srgb, var(--fg) 50%, transparent);\n --border: color-mix(in srgb, var(--fg) 12%, transparent);\n --wash: color-mix(in srgb, var(--fg) 5%, transparent);\n\n --sans: Manrope, ui-sans-serif, system-ui, sans-serif;\n --mono: \"Roboto Mono\", ui-monospace, monospace;\n\n --sw-background: var(--bg);\n --sw-page-inset-bottom: 0px;\n color-scheme: light;\n}\n\n:root.dark {\n --bg: #1c1b19;\n --surface: #232220;\n --elevated: #2a2926;\n --fg: #fdfef6;\n color-scheme: dark;\n}\n\n* {\n box-sizing: border-box;\n}\n\nbody {\n margin: 0;\n background: var(--bg);\n color: var(--fg);\n font-family: var(--sans);\n font-size: 0.9375rem;\n font-weight: 400;\n line-height: 1.5;\n letter-spacing: -0.01em;\n -webkit-font-smoothing: antialiased;\n}\n\nh1,\nh2,\nh3 {\n margin: 0;\n font-weight: 500;\n}\n\nh1 {\n font-size: clamp(2rem, 7vw, 2.5rem);\n line-height: 1.1;\n letter-spacing: -0.03em;\n}\n\nh2 {\n font-size: 1.5rem;\n line-height: 1.25;\n letter-spacing: -0.02em;\n}\n\nh3 {\n font-size: 1.25rem;\n line-height: 1.3;\n letter-spacing: -0.015em;\n}\n\np {\n margin: 0;\n color: var(--fg-body);\n}\n\ncode {\n font-family: var(--mono);\n font-size: 0.8125rem;\n}\n\n.shell {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n}\n\n.page {\n display: flex;\n min-height: 100%;\n flex-direction: column;\n gap: 24px;\n width: 100%;\n max-width: 44rem;\n margin: 0 auto;\n padding: 16px 20px 24px;\n}\n\n.lede {\n display: flex;\n flex-direction: column;\n gap: 10px;\n}\n\n.actions {\n display: flex;\n flex-direction: column;\n gap: 8px;\n margin-top: auto;\n padding-top: 20px;\n}\n\n.button {\n display: flex;\n width: 100%;\n align-items: center;\n justify-content: center;\n min-height: 44px;\n border: 1px solid var(--border);\n background: transparent;\n padding: 0 16px;\n color: var(--fg);\n font: inherit;\n font-size: 0.9375rem;\n font-weight: 500;\n cursor: pointer;\n transition:\n background-color 150ms ease,\n border-color 150ms ease;\n}\n\n.button:hover {\n background: var(--wash);\n}\n\n.button:focus-visible {\n outline: 2px solid var(--accent);\n outline-offset: -2px;\n}\n\n.button:disabled {\n cursor: default;\n opacity: 0.5;\n}\n\n.button--primary {\n border-color: var(--fg);\n background: var(--fg);\n color: var(--bg);\n}\n\n.button--primary:hover:not(:disabled) {\n background: color-mix(in srgb, var(--fg) 85%, transparent);\n}\n\n.link {\n align-self: center;\n border: 0;\n background: none;\n padding: 8px;\n color: var(--fg-muted);\n font: inherit;\n font-size: 0.8125rem;\n cursor: pointer;\n}\n\n.link:hover {\n color: var(--fg);\n}\n\n.link:focus-visible {\n outline: 2px solid var(--accent);\n outline-offset: -2px;\n}\n\n.close {\n align-self: flex-end;\n display: flex;\n width: 32px;\n height: 32px;\n align-items: center;\n justify-content: center;\n border: 0;\n background: none;\n padding: 0;\n color: var(--fg-muted);\n font: inherit;\n font-size: 1.25rem;\n line-height: 1;\n cursor: pointer;\n}\n\n.close:hover {\n color: var(--fg);\n}\n\n.close:focus-visible {\n outline: 2px solid var(--accent);\n outline-offset: -2px;\n}\n\n.built {\n display: flex;\n flex: none;\n align-items: center;\n justify-content: center;\n gap: 6px;\n border-top: 1px solid var(--border);\n padding: 14px 20px;\n font-size: 0.75rem;\n color: var(--fg-caption);\n}\n\n.wordmark {\n border: 0;\n background: transparent;\n padding: 0;\n color: var(--fg);\n font: inherit;\n font-weight: 600;\n letter-spacing: 0.01em;\n cursor: pointer;\n}\n\n.wordmark:focus-visible {\n outline: 2px solid var(--accent);\n outline-offset: 2px;\n}\n\n.wordmark-accent {\n color: var(--accent);\n}\n\n@media (prefers-reduced-motion: reduce) {\n * {\n transition-duration: 1ms !important;\n }\n}\n";
358
+ const writer = (target) => (relative$1, content) => {
359
+ const destination = path.join(target, relative$1);
360
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
361
+ fs.writeFileSync(destination, content);
362
+ };
363
+ function writeProjectFiles(target, name) {
364
+ const file = writer(target);
365
+ file("package.json", packageJson(name ?? projectPackageName(target)));
366
+ file("tsconfig.json", TSCONFIG);
367
+ file("superwall.d.ts", SUPERWALL_DTS);
368
+ file(".gitignore", GITIGNORE);
369
+ file("README.md", README);
370
+ }
371
+ function writeSurfaceFiles(target, surfaceId, config) {
372
+ const file = writer(target);
373
+ file(`paywalls/${surfaceId}/config.ts`, config);
374
+ file(`paywalls/${surfaceId}/messages/en.ts`, MESSAGES);
375
+ file(`paywalls/${surfaceId}/app/index.tsx`, INDEX);
376
+ file(`paywalls/${surfaceId}/app/layout.tsx`, LAYOUT);
377
+ file(`paywalls/${surfaceId}/app/theme.css`, THEME);
378
+ }
379
+ function starterConfig(name) {
380
+ return CONFIG.replace("name: \"Pro\"", `name: ${JSON.stringify(name)}`);
381
+ }
382
+ function writeTemplate(target, name) {
383
+ writeProjectFiles(target, name);
384
+ writeSurfaceFiles(target, "pro", CONFIG);
385
+ }
386
+
387
+ //#endregion
388
+ //#region src/core/paywalls/screen.ts
389
+ const SCREEN_EXTENSIONS = {
390
+ ".swift": "swift",
391
+ ".kt": "kotlin",
392
+ ".tsx": "js",
393
+ ".jsx": "js",
394
+ ".ts": "js",
395
+ ".js": "js",
396
+ ".dart": "dart"
397
+ };
398
+ const NAME_SUFFIXES = /^(View|Screen|Controller|Page|Sheet|Modal|Widget|Route|Scene|Component|Activity|Fragment|Dialog)$/;
399
+ function screenNameOf(file) {
400
+ const words = path.basename(file).replace(/\.[^.]+$/, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s_\-.]+/).filter((word) => word !== "");
401
+ while (words.length > 1 && NAME_SUFFIXES.test(words[words.length - 1].replace(/^./, (c) => c.toUpperCase()))) words.pop();
402
+ if (words.length === 0) return "Screen";
403
+ return words.map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
404
+ }
405
+ const slugOfName = (name) => name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "screen";
406
+ const placementOfName = (name) => slugOfName(name).replace(/-/g, "_");
407
+ function screenFrameworkOf(file, source) {
408
+ const language = SCREEN_EXTENSIONS[path.extname(file).toLowerCase()];
409
+ if (language === "swift") {
410
+ if (/\bimport SwiftUI\b/.test(source) && /:\s*(some\s+)?View\b/.test(source)) return "swiftui";
411
+ if (/UIViewController|UIView\b/.test(source)) return "uikit";
412
+ throw new Error(`\`${path.basename(file)}\` has no SwiftUI View or UIViewController in it — pass the file that draws the screen.`);
413
+ }
414
+ if (language === "kotlin") {
415
+ if (/@Composable\b/.test(source)) return "compose";
416
+ if (/\b(Activity|Fragment|DialogFragment|BottomSheetDialogFragment)\b|setContentView\(/.test(source)) return "android-views";
417
+ throw new Error(`\`${path.basename(file)}\` has no Composable, Activity or Fragment in it — pass the file that draws the screen.`);
418
+ }
419
+ if (language === "js") {
420
+ if (/<[A-Za-z][\w.]*[\s/>]/.test(source)) return "react-native";
421
+ throw new Error(`\`${path.basename(file)}\` renders no JSX — pass the component file that draws the screen.`);
422
+ }
423
+ if (language === "dart") {
424
+ if (/Widget\b/.test(source)) return "flutter";
425
+ throw new Error(`\`${path.basename(file)}\` builds no Widget — pass the file that draws the screen.`);
426
+ }
427
+ throw new Error(`Can't read \`${path.basename(file)}\` as a screen — pass a SwiftUI or UIKit (.swift), Kotlin (.kt), React Native (.tsx) or Flutter (.dart) file.`);
428
+ }
429
+ const CONTEXT = 48;
430
+ const quotesOf = (framework) => framework === "swiftui" || framework === "uikit" || framework === "compose" || framework === "android-views" ? ["\"\"\"", "\""] : [
431
+ "'''",
432
+ "\"\"\"",
433
+ "'",
434
+ "\"",
435
+ "`"
436
+ ];
437
+ function literalsOf(source, framework) {
438
+ const quotes = quotesOf(framework);
439
+ const literals = [];
440
+ let code = "";
441
+ let index = 0;
442
+ while (index < source.length) {
443
+ if (source.startsWith("//", index)) {
444
+ const end = source.indexOf("\n", index);
445
+ index = end === -1 ? source.length : end;
446
+ continue;
447
+ }
448
+ if (source.startsWith("/*", index)) {
449
+ const end = source.indexOf("*/", index + 2);
450
+ index = end === -1 ? source.length : end + 2;
451
+ continue;
452
+ }
453
+ const quote = quotes.find((candidate) => source.startsWith(candidate, index));
454
+ if (quote === void 0) {
455
+ code += source[index];
456
+ index += 1;
457
+ continue;
458
+ }
459
+ let cursor = index + quote.length;
460
+ let value = "";
461
+ let closed = false;
462
+ while (cursor < source.length) {
463
+ if (source[cursor] === "\\") {
464
+ value += source.slice(cursor, cursor + 2);
465
+ cursor += 2;
466
+ continue;
467
+ }
468
+ if (source.startsWith(quote, cursor)) {
469
+ closed = true;
470
+ break;
471
+ }
472
+ if (quote.length === 1 && source[cursor] === "\n") break;
473
+ value += source[cursor];
474
+ cursor += 1;
475
+ }
476
+ if (closed) literals.push({
477
+ value: value.trim(),
478
+ before: code.slice(-CONTEXT)
479
+ });
480
+ code += " ";
481
+ index = closed ? cursor + quote.length : cursor;
482
+ }
483
+ return {
484
+ literals,
485
+ code
486
+ };
487
+ }
488
+ const COPY_CONTEXT = /(Text|Button|Label|Link|Toggle|Section|Alert|NavigationLink|TextField|SecureField|Menu|Picker|DisclosureGroup|String\(localized|NSLocalizedString|\.navigationTitle|\.accessibilityLabel|\.accessibilityHint|\.help|UILabel|setTitle|\.text\s*=|\.title\s*=|title|message|subtitle|placeholder|label|semanticsLabel|tooltip|hintText|labelText|accessibilityLabel|contentDescription|headerText|children)\s*[:=(]?\s*(\{|\()?\s*$/;
489
+ const ASSET_CONTEXT = /(Image|UIImage\(named|Image\.asset|AssetImage|require|uri|ImageResource|\.font\(\.custom|Lottie|LottieView|source)\s*[:=(]?\s*(\{)?\s*$/;
490
+ const SYMBOL_CONTEXT = /(systemName|UIImage\(systemName|Icon|name)\s*[:=(]?\s*$/;
491
+ const PRODUCT_CONTEXT = /(product|sku|identifier|subscription|purchase|plan|offering|package|entitlement|ids)\w*\s*(:\s*\w+)?\s*[:=(\[]?\s*(\[)?\s*$|,\s*$/i;
492
+ const REVERSE_DNS = /^[a-z][a-z0-9]*(\.[a-z0-9_-]+){2,}$/;
493
+ const SNAKE_ID = /^[a-z0-9]+(_[a-z0-9.]+)+$/;
494
+ const IDENTIFIER_LIKE = /^[A-Za-z_$][\w$.\-/]*$/;
495
+ const interpolationsIn = (value, framework) => {
496
+ const pattern = framework === "swiftui" || framework === "uikit" ? /\\\(([^)]*)\)/g : framework === "flutter" || framework === "compose" || framework === "android-views" ? /\$\{([^}]*)\}|\$([A-Za-z_]\w*)/g : /\$\{([^}]*)\}/g;
497
+ return [...value.matchAll(pattern)].map((match) => (match[1] ?? match[2] ?? "").trim());
498
+ };
499
+ const MODULE_CONTEXT = /\b(import|from|package)\s*$/;
500
+ const looksLikeCopy = (value) => /[A-Za-z]/.test(value) && !/^https?:|^itms-apps:|^mailto:|^tel:/.test(value) && !IDENTIFIER_LIKE.test(value) && !(/^\S+$/.test(value) && /[/:@]/.test(value)) && !/<\/?[A-Za-z]|\/>/.test(value) && !/^[%\\]/.test(value) && !/^#[0-9a-fA-F]{3,8}$/.test(value) && !/^[\d.\s+\-*/()%]+$/.test(value);
501
+ const unique = (values) => [...new Set(values.filter((value) => value !== ""))];
502
+ const ACTION_PATTERNS = {
503
+ swiftui: {
504
+ purchase: /\.purchase\(|Product\.purchase|SKPaymentQueue|\.buy\(/g,
505
+ restore: /restorePurchases|restoreCompletedTransactions|AppStore\.sync\(/g,
506
+ "open-url": /openURL|UIApplication\.shared\.open\(|\bLink\(/g,
507
+ "store-review": /requestReview|SKStoreReviewController/g,
508
+ notifications: /requestAuthorization\(options|UNUserNotificationCenter/g,
509
+ dismiss: /\bdismiss\(\)|presentationMode\.wrappedValue\.dismiss|isPresented\s*=\s*false/g,
510
+ navigate: /NavigationLink|navigationDestination|\.sheet\(|\.fullScreenCover\(/g,
511
+ tap: /\bButton\s*[({]|\.onTapGesture/g
512
+ },
513
+ uikit: {
514
+ purchase: /\.purchase\(|Product\.purchase|SKPaymentQueue|\.buy\(/g,
515
+ restore: /restorePurchases|restoreCompletedTransactions|AppStore\.sync\(/g,
516
+ "open-url": /UIApplication\.shared\.open\(|openURL/g,
517
+ "store-review": /requestReview|SKStoreReviewController/g,
518
+ notifications: /requestAuthorization\(options|UNUserNotificationCenter/g,
519
+ dismiss: /\.dismiss\(animated|popViewController/g,
520
+ navigate: /pushViewController|\.present\(/g,
521
+ tap: /addTarget\(|UIAction\s*[({]|UITapGestureRecognizer/g
522
+ },
523
+ compose: {
524
+ purchase: /launchBillingFlow|purchasePackage|purchaseWith|\.purchase\(/g,
525
+ restore: /queryPurchasesAsync|restorePurchases|queryPurchases/g,
526
+ "open-url": /Intent\.ACTION_VIEW|CustomTabsIntent|uriHandler\.openUri|LocalUriHandler/g,
527
+ "store-review": /ReviewManager|requestReviewFlow|launchReviewFlow/g,
528
+ notifications: /POST_NOTIFICATIONS|RequestPermission\(\)|requestPermission\(|rememberPermissionState/g,
529
+ dismiss: /onBackPressed|popBackStack\(|\bfinish\(\)|onDismiss/g,
530
+ navigate: /navController\.navigate\(|Intent\((?:this|context|activity),|NavHost/g,
531
+ tap: /onClick\s*=|\.clickable\b/g
532
+ },
533
+ "android-views": {
534
+ purchase: /launchBillingFlow|purchasePackage|purchaseWith|\.purchase\(/g,
535
+ restore: /queryPurchasesAsync|restorePurchases|queryPurchases/g,
536
+ "open-url": /Intent\.ACTION_VIEW|CustomTabsIntent/g,
537
+ "store-review": /ReviewManager|requestReviewFlow|launchReviewFlow/g,
538
+ notifications: /POST_NOTIFICATIONS|RequestPermission\(\)|requestPermissions?\(/g,
539
+ dismiss: /onBackPressed|popBackStack\(|\bfinish\(\)|\bdismiss\(\)/g,
540
+ navigate: /navController\.navigate\(|Intent\((?:this|context|activity|requireContext\(\)),|findNavController/g,
541
+ tap: /setOnClickListener|onClick\s*=|OnClickListener/g
542
+ },
543
+ "react-native": {
544
+ purchase: /requestPurchase|requestSubscription|purchasePackage|purchaseStoreProduct|\bpurchase\(/g,
545
+ restore: /restorePurchases|getAvailablePurchases/g,
546
+ "open-url": /Linking\.openURL|openBrowserAsync|openAuthSessionAsync/g,
547
+ "store-review": /StoreReview|requestReview/g,
548
+ notifications: /requestPermissionsAsync|requestPermissions\(|requestPermission\(/g,
549
+ dismiss: /goBack\(\)|\.dismiss\(\)|\bpop\(\)/g,
550
+ navigate: /navigation\.(navigate|push|replace)\(|router\.(push|replace|navigate)\(/g,
551
+ tap: /onPress=/g
552
+ },
553
+ flutter: {
554
+ purchase: /buyNonConsumable|buyConsumable|purchasePackage|\.purchase\(/g,
555
+ restore: /restorePurchases/g,
556
+ "open-url": /launchUrl\(|launchUrlString\(|\blaunch\(/g,
557
+ "store-review": /InAppReview|requestReview/g,
558
+ notifications: /Permission\.notification|requestPermission\(/g,
559
+ dismiss: /Navigator\.(of\(context\)\.)?pop\(|context\.pop\(/g,
560
+ navigate: /Navigator\.(of\(context\)\.)?push|context\.(go|push)\(/g,
561
+ tap: /onPressed:|onTap:/g
562
+ }
563
+ };
564
+ const jsxText = (source) => [...source.matchAll(/>\s*([^<>{}\n]*[A-Za-z][^<>{}\n]*?)\s*</g)].map((match) => match[1].trim()).filter((value) => looksLikeCopy(value) || /\s/.test(value));
565
+ function scanScreen(source, framework) {
566
+ const { literals, code } = literalsOf(source, framework);
567
+ const copy = [];
568
+ const assets = [];
569
+ const symbols = [];
570
+ const urls = [];
571
+ const productIds = [];
572
+ for (const { value, before } of literals) {
573
+ if (value === "" || MODULE_CONTEXT.test(before) || /<\/?[A-Za-z]|\/>/.test(value)) continue;
574
+ if (/^(https?:|itms-apps:|mailto:|tel:|market:)/.test(value)) {
575
+ urls.push(value);
576
+ continue;
577
+ }
578
+ if (SYMBOL_CONTEXT.test(before) && /^[a-z0-9]+(\.[a-z0-9]+)*$/i.test(value)) {
579
+ symbols.push(value);
580
+ continue;
581
+ }
582
+ if (ASSET_CONTEXT.test(before) || /\.(png|jpe?g|gif|webp|svg|json|lottie|riv|mp4|ttf|otf)$/i.test(value)) {
583
+ assets.push(value);
584
+ continue;
585
+ }
586
+ if (PRODUCT_CONTEXT.test(before) && !/\s/.test(value) && (REVERSE_DNS.test(value) || SNAKE_ID.test(value) || /\./.test(value))) {
587
+ productIds.push(value);
588
+ continue;
589
+ }
590
+ if (COPY_CONTEXT.test(before) ? /[A-Za-z]/.test(value) : looksLikeCopy(value)) copy.push(value);
591
+ }
592
+ if (framework === "react-native") copy.push(...jsxText(source));
593
+ const actions = [];
594
+ const lines = code.split("\n").filter((line) => !/^\s*(import|package)\b/.test(line)).map((line) => line.replace(/@Environment(Object)?\([^)]*\)\s*(private\s+)?var\s+\w+/g, "").replace(/^\s*(?:(?:private|public|internal|override|@objc)\s+)*(?:func|fun|def)\s+\w+\s*\([^)]*\)\s*(?:->\s*[\w<>?]+\s*)?/, ""));
595
+ for (const [kind, pattern] of Object.entries(ACTION_PATTERNS[framework])) {
596
+ const count = lines.filter((line) => new RegExp(pattern.source).test(line)).length;
597
+ if (count > 0) actions.push({
598
+ kind,
599
+ count
600
+ });
601
+ }
602
+ const uniqueCopy = unique(copy);
603
+ return {
604
+ copy: uniqueCopy,
605
+ interpolations: unique(uniqueCopy.flatMap((value) => interpolationsIn(value, framework))),
606
+ assets: unique(assets),
607
+ symbols: unique(symbols),
608
+ urls: unique(urls),
609
+ productIds: unique(productIds),
610
+ actions
611
+ };
612
+ }
613
+ const mergeInventories = (inventories) => {
614
+ const counts = /* @__PURE__ */ new Map();
615
+ for (const inventory of inventories) for (const action of inventory.actions) counts.set(action.kind, (counts.get(action.kind) ?? 0) + action.count);
616
+ return {
617
+ copy: unique(inventories.flatMap((entry) => entry.copy)),
618
+ interpolations: unique(inventories.flatMap((entry) => entry.interpolations)),
619
+ assets: unique(inventories.flatMap((entry) => entry.assets)),
620
+ symbols: unique(inventories.flatMap((entry) => entry.symbols)),
621
+ urls: unique(inventories.flatMap((entry) => entry.urls)),
622
+ productIds: unique(inventories.flatMap((entry) => entry.productIds)),
623
+ actions: [...counts.entries()].map(([kind, count]) => ({
624
+ kind,
625
+ count
626
+ }))
627
+ };
628
+ };
629
+ const decodeXml = (value) => value.replace(/&quot;/g, "\"").replace(/&apos;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&#10;/g, "\n").replace(/&amp;/g, "&");
630
+ function scanInterfaceBuilder(xml, classes) {
631
+ const text = (xml.includes("<scene") ? [...xml.matchAll(/<scene[\s\S]*?<\/scene>/g)].map((match) => match[0]).filter((scene) => classes.some((name) => scene.includes(`customClass="${name}"`))) : [xml]).join("\n");
632
+ const copy = [...text.matchAll(/\b(?:text|title|placeholder|normalTitle|value)="([^"]*)"/g)].map((match) => decodeXml(match[1]).trim()).filter((value) => /[A-Za-z]/.test(value));
633
+ const assets = [...text.matchAll(/\bimage="([^"]*)"/g)].map((match) => match[1]);
634
+ const symbols = [...text.matchAll(/\bcatalog="system"[^>]*\bimage="([^"]*)"|\bimage="([^"]*)"[^>]*\bcatalog="system"/g)].map((match) => match[1] ?? match[2] ?? "");
635
+ const taps = (text.match(/<button\b/g) ?? []).length;
636
+ return {
637
+ copy: unique(copy),
638
+ interpolations: [],
639
+ assets: unique(assets.filter((asset) => !symbols.includes(asset))),
640
+ symbols: unique(symbols),
641
+ urls: [],
642
+ productIds: [],
643
+ actions: taps > 0 ? [{
644
+ kind: "tap",
645
+ count: taps
646
+ }] : []
647
+ };
648
+ }
649
+ const COMPANION_TYPES = /\b([A-Z][A-Za-z0-9]*(?:View|ViewModel|Cell|Presenter|Model))\b/g;
650
+ const SYSTEM_PREFIX = /^(UI|NS|SwiftUI|Any|Some|CG|CA|SK|AV|WK|MK)/;
651
+ const MAX_COMPANIONS = 8;
652
+ function companionsOf(searchRoot, primary, source) {
653
+ const stem = path.basename(primary).replace(/\.[^.]+$/, "");
654
+ const names = unique([...source.matchAll(COMPANION_TYPES)].map((match) => match[1])).filter((name) => name !== stem && !SYSTEM_PREFIX.test(name));
655
+ const options = {
656
+ cwd: searchRoot,
657
+ ignore: CANDIDATE_IGNORE,
658
+ onlyFiles: true,
659
+ followSymbolicLinks: false
660
+ };
661
+ const swift = names.length === 0 ? [] : fg.sync(`**/@(${names.join("|")}).swift`, options).map((file) => path.join(searchRoot, file));
662
+ const classes = [stem, ...names];
663
+ const interfaceBuilder = fg.sync("**/*.{xib,storyboard}", options).map((file) => path.join(searchRoot, file)).filter((file) => {
664
+ try {
665
+ if (fs.statSync(file).size > MAX_CANDIDATE_BYTES * 5) return false;
666
+ const xml = fs.readFileSync(file, "utf8");
667
+ return classes.some((name) => xml.includes(`customClass="${name}"`));
668
+ } catch {
669
+ return false;
670
+ }
671
+ });
672
+ return unique([...swift, ...interfaceBuilder]).filter((file) => file !== primary).sort().slice(0, MAX_COMPANIONS);
673
+ }
674
+ const EMPTY_INVENTORY = {
675
+ copy: [],
676
+ interpolations: [],
677
+ assets: [],
678
+ symbols: [],
679
+ urls: [],
680
+ productIds: [],
681
+ actions: []
682
+ };
683
+ const ANDROID_RESOURCE_TYPES = /\b(ViewModel|Presenter|State|Model)\b/;
684
+ function androidCompanionsOf(searchRoot, primary, source) {
685
+ const options = {
686
+ cwd: searchRoot,
687
+ ignore: CANDIDATE_IGNORE,
688
+ onlyFiles: true,
689
+ followSymbolicLinks: false
690
+ };
691
+ const stem = path.basename(primary, ".kt");
692
+ const layouts = unique([...source.matchAll(/R\.layout\.(\w+)/g)].map((match) => match[1]));
693
+ const layoutFiles = layouts.length === 0 ? [] : fg.sync(`**/res/layout*/@(${layouts.join("|")}).xml`, options);
694
+ const names = unique([...source.matchAll(COMPANION_TYPES)].map((match) => match[1])).filter((name) => name !== stem && !SYSTEM_PREFIX.test(name) && ANDROID_RESOURCE_TYPES.test(name));
695
+ const kotlin = names.length === 0 ? [] : fg.sync(`**/@(${names.join("|")}).kt`, options);
696
+ const strings = /R\.string\.\w+/.test(source) || layoutFiles.length > 0 ? fg.sync("**/res/values/strings.xml", options) : [];
697
+ return unique([
698
+ ...layoutFiles,
699
+ ...kotlin,
700
+ ...strings
701
+ ].map((file) => path.join(searchRoot, file))).filter((file) => file !== primary).sort().slice(0, MAX_COMPANIONS);
702
+ }
703
+ function androidStringsOf(companions) {
704
+ const strings = /* @__PURE__ */ new Map();
705
+ for (const file of companions) {
706
+ if (!file.endsWith("strings.xml")) continue;
707
+ let xml;
708
+ try {
709
+ xml = fs.readFileSync(file, "utf8");
710
+ } catch {
711
+ continue;
712
+ }
713
+ for (const match of xml.matchAll(/<string\s+name="([^"]+)"[^>]*>([\s\S]*?)<\/string>/g)) strings.set(match[1], decodeXml(match[2].trim()).replace(/^"|"$/g, "").replace(/\\'/g, "'"));
714
+ }
715
+ return strings;
716
+ }
717
+ const withResolvedStrings = (inventory, source, strings) => {
718
+ const resolved = [...source.matchAll(/R\.string\.(\w+)/g)].map((match) => strings.get(match[1])).filter((value) => value !== void 0);
719
+ const assets = [...source.matchAll(/R\.(?:drawable|mipmap|raw|font)\.(\w+)/g)].map((match) => match[1]);
720
+ const symbols = [...source.matchAll(/Icons\.(?:Default|Filled|Outlined|Rounded|Sharp|TwoTone|AutoMirrored\.\w+)\.(\w+)/g)].map((match) => match[1]);
721
+ return {
722
+ ...inventory,
723
+ copy: unique([...inventory.copy, ...resolved]),
724
+ interpolations: unique([...inventory.interpolations, ...resolved.flatMap((value) => interpolationsIn(value, "compose"))]),
725
+ assets: unique([...inventory.assets, ...assets]),
726
+ symbols: unique([...inventory.symbols, ...symbols])
727
+ };
728
+ };
729
+ function scanAndroidLayout(xml, strings) {
730
+ const resolve$1 = (value) => {
731
+ const reference = /^@string\/(\w+)$/.exec(value);
732
+ if (reference) return strings.get(reference[1]);
733
+ return value.startsWith("@") ? void 0 : decodeXml(value);
734
+ };
735
+ const copy = [...xml.matchAll(/\b(?:android:text|android:hint|android:contentDescription|android:title|app:title|tools:text)="([^"]*)"/g)].map((match) => resolve$1(match[1])).filter((value) => value !== void 0 && /[A-Za-z]/.test(value));
736
+ const assets = [...xml.matchAll(/\b(?:android:src|app:srcCompat|android:background|app:lottie_rawRes|android:drawable\w*)="@(?:drawable|mipmap|raw)\/(\w+)"/g)].map((match) => match[1]);
737
+ const taps = (xml.match(/<(?:Button|ImageButton|com\.google\.android\.material\.button\.MaterialButton)\b|android:onClick=/g) ?? []).length;
738
+ return {
739
+ ...EMPTY_INVENTORY,
740
+ copy: unique(copy),
741
+ assets: unique(assets),
742
+ actions: taps > 0 ? [{
743
+ kind: "tap",
744
+ count: taps
745
+ }] : []
746
+ };
747
+ }
748
+ function readScreen(root, file, searchRoot) {
749
+ const absolute = path.resolve(root, file);
750
+ if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) throw new Error(`No file at \`${file}\`.`);
751
+ const source = fs.readFileSync(absolute, "utf8");
752
+ const framework = screenFrameworkOf(absolute, source);
753
+ const name = screenNameOf(absolute);
754
+ const relative$1 = (target) => path.relative(root, target).split(path.sep).join("/");
755
+ const android = framework === "compose" || framework === "android-views";
756
+ const companions = searchRoot === void 0 ? [] : framework === "uikit" || framework === "swiftui" ? companionsOf(searchRoot, absolute, source) : android ? androidCompanionsOf(searchRoot, absolute, source) : [];
757
+ const strings = android ? androidStringsOf(companions) : /* @__PURE__ */ new Map();
758
+ const inventories = [android ? withResolvedStrings(scanScreen(source, framework), source, strings) : scanScreen(source, framework), ...companions.map((companion) => {
759
+ const content = fs.readFileSync(companion, "utf8");
760
+ if (companion.endsWith(".swift") || companion.endsWith(".kt")) {
761
+ const inventory = scanScreen(content, framework);
762
+ return android ? withResolvedStrings(inventory, content, strings) : inventory;
763
+ }
764
+ if (android) return path.basename(path.dirname(companion)).startsWith("values") ? EMPTY_INVENTORY : scanAndroidLayout(content, strings);
765
+ return scanInterfaceBuilder(content, [path.basename(absolute).replace(/\.[^.]+$/, ""), ...companions.map((entry) => path.basename(entry, ".swift"))]);
766
+ })];
767
+ return {
768
+ file: absolute,
769
+ path: relative$1(absolute),
770
+ framework,
771
+ name,
772
+ slug: slugOfName(name),
773
+ placement: placementOfName(name),
774
+ inventory: mergeInventories(inventories),
775
+ companions: companions.map(relative$1)
776
+ };
777
+ }
778
+ const CANDIDATE_IGNORE = [
779
+ "**/node_modules/**",
780
+ "**/.git/**",
781
+ "**/.build/**",
782
+ "**/DerivedData/**",
783
+ "**/Pods/**",
784
+ "**/build/**",
785
+ "**/dist/**",
786
+ "**/.expo/**",
787
+ "**/vendor/**",
788
+ "**/superwall/**",
789
+ "**/paywalls/**",
790
+ "**/*Tests/**",
791
+ "**/*.test.*",
792
+ "**/*.spec.*",
793
+ "**/*.stories.*",
794
+ "**/*.d.ts"
795
+ ];
796
+ const NAME_SIGNALS = [
797
+ {
798
+ pattern: /\b(update|upgrade|force|forced|outdated|version)\b/,
799
+ weight: 3,
800
+ reason: "named like an update-required screen"
801
+ },
802
+ {
803
+ pattern: /\b(onboarding|onboard|welcome|intro|get started|tutorial|quiz)\b/,
804
+ weight: 2,
805
+ reason: "named like an onboarding screen"
806
+ },
807
+ {
808
+ pattern: /\b(paywall|subscribe|subscription|premium|pro|plan|plans|pricing|offer|trial|checkout|unlock)\b/,
809
+ weight: 2,
810
+ reason: "named like a paywall or offer"
811
+ },
812
+ {
813
+ pattern: /\b(rate|rating|review|feedback)\b/,
814
+ weight: 2,
815
+ reason: "named like a rate-us prompt"
816
+ },
817
+ {
818
+ pattern: /\b(notification|notifications|permission|permissions|push)\b/,
819
+ weight: 2,
820
+ reason: "named like a permission prompt"
821
+ },
822
+ {
823
+ pattern: /\b(announcement|whats new|changelog|news|promo|banner)\b/,
824
+ weight: 2,
825
+ reason: "named like an announcement"
826
+ },
827
+ {
828
+ pattern: /\b(consent|privacy|terms|legal|gdpr)\b/,
829
+ weight: 1,
830
+ reason: "named like a consent screen"
831
+ },
832
+ {
833
+ pattern: /\b(winback|win back|discount|cancel|churn|retention)\b/,
834
+ weight: 2,
835
+ reason: "named like a win-back screen"
836
+ },
837
+ {
838
+ pattern: /\b(maintenance|outage|downtime)\b/,
839
+ weight: 2,
840
+ reason: "named like a maintenance screen"
841
+ }
842
+ ];
843
+ const nameWords = (file) => path.basename(file).replace(/\.[^.]+$/, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/[_\-.]+/g, " ").toLowerCase();
844
+ const CONTENT_SIGNALS = [
845
+ {
846
+ pattern: /itms-apps:|apps\.apple\.com|play\.google\.com/i,
847
+ weight: 3,
848
+ reason: "links to the app store"
849
+ },
850
+ {
851
+ pattern: /requestReview|SKStoreReviewController|InAppReview|StoreReview|ReviewManager/i,
852
+ weight: 2,
853
+ reason: "asks for a store review"
854
+ },
855
+ {
856
+ pattern: /requestAuthorization|requestPermissionsAsync|Permission\.notification/i,
857
+ weight: 2,
858
+ reason: "asks for a permission"
859
+ },
860
+ {
861
+ pattern: /StoreKit|Product\.products|requestPurchase|purchasePackage|buyNonConsumable|BillingClient|launchBillingFlow/i,
862
+ weight: 2,
863
+ reason: "sells a product"
864
+ },
865
+ {
866
+ pattern: /\b(update|upgrade)\s+(now|required|app|to continue)/i,
867
+ weight: 2,
868
+ reason: "update-required copy"
869
+ }
870
+ ];
871
+ const SCREEN_SHAPE = {
872
+ swift: /:\s*(some\s+)?View\b|UIViewController/,
873
+ kotlin: /@Composable\b|\b(Activity|Fragment)\b|setContentView\(/,
874
+ js: /<[A-Za-z][\w.]*[\s/>]/,
875
+ dart: /Widget\b/
876
+ };
877
+ const MAX_CANDIDATE_BYTES = 2e5;
878
+ function findScreenCandidates(root, limit = 10) {
879
+ const files = fg.sync("**/*.{swift,kt,tsx,jsx,dart}", {
880
+ cwd: root,
881
+ ignore: CANDIDATE_IGNORE,
882
+ onlyFiles: true,
883
+ dot: false,
884
+ followSymbolicLinks: false
885
+ });
886
+ const candidates = [];
887
+ for (const file of files) {
888
+ const absolute = path.join(root, file);
889
+ let source;
890
+ try {
891
+ if (fs.statSync(absolute).size > MAX_CANDIDATE_BYTES) continue;
892
+ source = fs.readFileSync(absolute, "utf8");
893
+ } catch {
894
+ continue;
895
+ }
896
+ const language = SCREEN_EXTENSIONS[path.extname(file).toLowerCase()];
897
+ if (language === void 0 || !SCREEN_SHAPE[language].test(source)) continue;
898
+ const stem = nameWords(file);
899
+ const reasons = [];
900
+ let score = 0;
901
+ for (const signal of NAME_SIGNALS) if (signal.pattern.test(stem)) {
902
+ score += signal.weight * 3;
903
+ reasons.push(signal.reason);
904
+ }
905
+ for (const signal of CONTENT_SIGNALS) if (signal.pattern.test(source)) {
906
+ score += signal.weight;
907
+ reasons.push(signal.reason);
908
+ }
909
+ if (score === 0) continue;
910
+ let framework;
911
+ try {
912
+ framework = screenFrameworkOf(absolute, source);
913
+ } catch {
914
+ continue;
915
+ }
916
+ candidates.push({
917
+ path: file,
918
+ framework,
919
+ name: screenNameOf(file),
920
+ reason: unique(reasons).join("; "),
921
+ score
922
+ });
923
+ }
924
+ return candidates.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path)).slice(0, limit);
925
+ }
926
+ const literal = (value) => JSON.stringify(value);
927
+ const productKeyOf = (id, taken) => {
928
+ const segments = id.split(/[._\-/]+/).filter((segment) => /^[A-Za-z]/.test(segment));
929
+ let key = segments[segments.length - 1] ?? "";
930
+ if (!/^[A-Za-z_$][\w$]*$/.test(key) || key === "") key = "product";
931
+ let candidate = key;
932
+ let counter = 2;
933
+ while (taken.has(candidate)) candidate = `${key}${counter++}`;
934
+ taken.add(candidate);
935
+ return candidate;
936
+ };
937
+ function screenConfigSource(screen) {
938
+ const lines = [` name: ${literal(screen.name)},`];
939
+ if (screen.inventory.productIds.length > 0) {
940
+ const taken = /* @__PURE__ */ new Set();
941
+ lines.push(` products: {`);
942
+ for (const id of screen.inventory.productIds) lines.push(` ${productKeyOf(id, taken)}: ${literal(id)},`);
943
+ lines.push(` },`);
944
+ }
945
+ return `import { definePaywall } from "superwall/config";\n\nexport default definePaywall({\n${lines.join("\n")}\n});\n`;
946
+ }
947
+ const FRAMEWORK_LABEL = {
948
+ swiftui: "SwiftUI",
949
+ uikit: "UIKit",
950
+ compose: "Jetpack Compose",
951
+ "android-views": "Android Views",
952
+ "react-native": "React Native",
953
+ flutter: "Flutter"
954
+ };
955
+ const screenFrameworkLabel = (framework) => FRAMEWORK_LABEL[framework];
956
+ const ACTION_MAPPING = {
957
+ purchase: ["a purchase", "`usePurchase()` with the product from `useProducts()`"],
958
+ restore: ["a restore", "`useActions().restore()`"],
959
+ "open-url": ["opening a URL (App Store links included)", "`useActions().openUrl(url)`"],
960
+ "store-review": ["a store review request", "`useActions().requestStoreReview()`"],
961
+ notifications: ["a permission request", "`useActions().requestPermission(\"notification\")`"],
962
+ dismiss: ["dismissing the screen", "`useActions().close()`"],
963
+ navigate: ["navigation to another screen", "`useRouter().push()` for a page inside this surface; otherwise close and let the app route"],
964
+ tap: ["a tappable control", "a `<button>` calling one of the hooks above"]
965
+ };
966
+ const table = (rows) => rows.map((row) => `| ${row.join(" | ")} |`).join("\n");
967
+ const bulletsOr = (values, empty, format = (value) => `\`${value}\``) => values.length === 0 ? `_${empty}_` : values.map((value) => `- ${format(value)}`).join("\n");
968
+ function screenBrief(screen, screenshot) {
969
+ const { inventory } = screen;
970
+ const copy = inventory.copy.length === 0 ? "_No user-visible strings were found in the file; read it for text drawn elsewhere (localized string tables, view models)._" : table([
971
+ ["#", "Text"],
972
+ ["---", "---"],
973
+ ...inventory.copy.map((value, index) => [String(index + 1), value.replace(/\|/g, "\\|")])
974
+ ]);
975
+ const actions = inventory.actions.length === 0 ? "_No actions were detected; read the file for what its controls do._" : table([
976
+ [
977
+ "In the source",
978
+ "Count",
979
+ "Becomes"
980
+ ],
981
+ [
982
+ "---",
983
+ "---",
984
+ "---"
985
+ ],
986
+ ...inventory.actions.map(({ kind, count }) => [
987
+ ACTION_MAPPING[kind][0],
988
+ `×${count}`,
989
+ ACTION_MAPPING[kind][1]
990
+ ])
991
+ ]);
992
+ return `# Migrating "${screen.name}" to Superwall
993
+
994
+ Rebuild this ${FRAMEWORK_LABEL[screen.framework]} screen as a framework surface so
995
+ the app can change it without a release. Follow the \`superwall-framework\`
996
+ skill's \`references/migrate-from-native.md\` and its \`native/\` file for
997
+ ${FRAMEWORK_LABEL[screen.framework]}; this file is their input and is
998
+ deleted when the migration is done.
999
+
1000
+ ## Source
1001
+
1002
+ - File: \`${screen.path}\` (${FRAMEWORK_LABEL[screen.framework]})${screen.companions.length === 0 ? "" : `\n- Also read (what this screen draws from: its view, view model, storyboard scene, layout or string resources; their strings and assets are in the inventory below): ${screen.companions.map((entry) => `\`${entry}\``).join(", ")}`}
1003
+ - Screenshot of the original: ${screenshot ? `\`${screenshot}\` (Compare › Original in the studio)` : "none — take one in the simulator before reviewing, or pass `--screenshot` to `superwall migrate --screen`"}
1004
+ - Placement to register in the app: \`${screen.placement}\`
1005
+
1006
+ ## Copy
1007
+
1008
+ Every string becomes a \`messages/en.ts\` entry read with \`t()\`; dynamic
1009
+ values become interpolations.
1010
+
1011
+ ${copy}
1012
+ ${inventory.interpolations.length === 0 ? "" : `\nDynamic values in that copy: ${inventory.interpolations.map((value) => `\`${value}\``).join(", ")}. Each is a \`t()\` parameter; source it from a variable (\`useVariables()\`), a product (\`useProducts()\`), or a placement param.\n`}
1013
+ ## Assets
1014
+
1015
+ ${bulletsOr(inventory.assets, "No image or media assets referenced.")}
1016
+ ${inventory.symbols.length === 0 ? "" : `\nSystem symbols: ${inventory.symbols.map((value) => `\`${value}\``).join(", ")} — replace with an SVG in \`assets/\`; there are no SF Symbols on the web.\n`}
1017
+ ## Links
1018
+
1019
+ ${bulletsOr(inventory.urls, "No URLs.")}
1020
+
1021
+ ## Products
1022
+
1023
+ ${inventory.productIds.length === 0 ? "_No store product identifiers found; this screen sells nothing._" : `${bulletsOr(inventory.productIds, "")}\n\nThese are already slots in \`config.ts\`. Each must exist on the dashboard for the app it pushes to, or the push is refused; the user confirms the identifiers.`}
1024
+
1025
+ ## Actions
1026
+
1027
+ ${actions}
1028
+
1029
+ ## Done when
1030
+
1031
+ - Every state and string of the source is rebuilt as pages under \`app/\`
1032
+ with the framework's hooks, and reviewed side by side against the
1033
+ screenshot in the studio, in both schemes.
1034
+ - \`${screen.path}\` is untouched. Wiring the app —
1035
+ \`register("${screen.placement}")\` where it used to present this screen,
1036
+ the campaign, then deleting the native screen — is the next step, in the
1037
+ app, after the user has reviewed the rebuild.
1038
+ - This file is deleted by the user after review.
1039
+ `;
1040
+ }
1041
+
1042
+ //#endregion
1043
+ //#region src/core/paywalls/migration.ts
1044
+ const screenFileOf = (migration, origin) => path.resolve(migration.superwallDir, origin.path);
1045
+ const migrationSource = (migration, from = process.cwd()) => isScreenOrigin(migration.origin) ? path.relative(from, screenFileOf(migration, migration.origin)) || "." : migration.origin.paywallId;
1046
+ const migrationCommand = (migration, from = process.cwd()) => isScreenOrigin(migration.origin) ? `superwall migrate --screen ${migrationSource(migration, from)}` : `superwall migrate ${migration.origin.paywallId}`;
1047
+ const hasOriginal = (migration) => !isScreenOrigin(migration.origin) || migration.origin.screenshot !== void 0;
1048
+ function isSuperwallProject(dir) {
1049
+ if (fs.existsSync(path.join(dir, "superwall.lock"))) return true;
1050
+ const parsed = readPackageJson(dir);
1051
+ return parsed !== void 0 && parsed !== null && "superwall" in allDeps(parsed);
1052
+ }
1053
+ function projectDirOf(root) {
1054
+ const nested = path.join(root, "superwall");
1055
+ if (isSuperwallProject(nested)) return nested;
1056
+ if (isSuperwallProject(root)) return root;
1057
+ }
1058
+ const briefOf = (superwallDir, surfaceId) => {
1059
+ const file = path.join(superwallDir, "paywalls", surfaceId, "MIGRATION.md");
1060
+ return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
1061
+ };
1062
+ function migrationsOf(superwallDir) {
1063
+ const lock = readLock(superwallDir);
1064
+ return Object.entries(lock.origins ?? {}).filter(([key]) => key.startsWith("paywall/")).map(([key, origin]) => {
1065
+ const surfaceId = key.slice(8);
1066
+ return {
1067
+ superwallDir,
1068
+ surfaceId,
1069
+ origin,
1070
+ brief: briefOf(superwallDir, surfaceId)
1071
+ };
1072
+ });
1073
+ }
1074
+ function migrationFor(superwallDir, paywallId) {
1075
+ return migrationsOf(superwallDir).find((entry) => !isScreenOrigin(entry.origin) && entry.origin.paywallId === paywallId);
1076
+ }
1077
+ function screenMigrationFor(superwallDir, file) {
1078
+ const absolute = path.resolve(file);
1079
+ return migrationsOf(superwallDir).find((entry) => isScreenOrigin(entry.origin) && screenFileOf(entry, entry.origin) === absolute);
1080
+ }
1081
+ const ORIGINAL_SCREENSHOT = "original.png";
1082
+ function scaffoldFromScreen(ui, options) {
1083
+ const { root, target, file } = options;
1084
+ const screen = readScreen(target, path.resolve(root, file), root);
1085
+ const { inventory } = screen;
1086
+ const surfaceDir = path.join(target, "paywalls", screen.slug);
1087
+ if (fs.existsSync(path.join(surfaceDir, "config.ts"))) throw new Error(`\`paywalls/${screen.slug}\` already exists in ${path.relative(root, target) || "."} — rename or remove it first.`);
1088
+ if (options.newProject) writeProjectFiles(target, projectPackageName(root));
1089
+ writeSurfaceFiles(target, screen.slug, screenConfigSource(screen));
1090
+ let screenshot;
1091
+ if (options.screenshot !== void 0) {
1092
+ fs.copyFileSync(options.screenshot, path.join(surfaceDir, ORIGINAL_SCREENSHOT));
1093
+ screenshot = ORIGINAL_SCREENSHOT;
1094
+ }
1095
+ fs.writeFileSync(path.join(surfaceDir, "MIGRATION.md"), screenBrief(screen, screenshot));
1096
+ const origin = {
1097
+ path: screen.path,
1098
+ framework: screen.framework,
1099
+ ...screenshot === void 0 ? {} : { screenshot }
1100
+ };
1101
+ writeOrigin(target, "paywall", screen.slug, origin);
1102
+ const found = [
1103
+ `${inventory.copy.length} string${inventory.copy.length === 1 ? "" : "s"}`,
1104
+ `${inventory.assets.length} asset${inventory.assets.length === 1 ? "" : "s"}`,
1105
+ `${inventory.productIds.length} product${inventory.productIds.length === 1 ? "" : "s"}`,
1106
+ `${inventory.actions.reduce((sum, action) => sum + action.count, 0)} action${inventory.actions.length === 1 ? "" : "s"}`
1107
+ ].join(", ");
1108
+ ui.step(`Read \`${screen.path}\` (${screenFrameworkLabel(screen.framework)}): ${found}`);
1109
+ ui.step(`Created ${path.relative(root, target) || "."}/paywalls/${screen.slug} for \`${screen.name}\``);
1110
+ if (inventory.productIds.length > 0) ui.warn("Product identifiers were lifted from the source — confirm each exists on the dashboard before pushing.");
1111
+ return screen;
1112
+ }
1113
+ const fetchDocument = (url) => fetch(url).then((response) => response.ok ? response.text() : void 0).catch(() => void 0);
1114
+ async function scaffoldFromPaywall(ui, api, options) {
1115
+ const { root, target, paywallId } = options;
1116
+ const spin = ui.spinner();
1117
+ spin.start(`Reading paywall ${paywallId}`);
1118
+ const detail = await getPaywall(api, paywallId).catch((error) => {
1119
+ spin.stop(`Could not read paywall ${paywallId}`);
1120
+ if (error instanceof ApiError && [
1121
+ 401,
1122
+ 403,
1123
+ 404
1124
+ ].includes(error.status)) throw new Error(`Paywall ${paywallId} isn't visible to this account. Check the id in the dashboard URL, and if it belongs to another organization, switch with \`superwall orgs use <id>\` first.`);
1125
+ throw error;
1126
+ });
1127
+ if (detail.headless) {
1128
+ spin.stop(`\`${detail.name ?? paywallId}\` is already code`);
1129
+ throw new Error(`Paywall ${paywallId} is built with the framework already — pull its source from the dashboard instead of migrating it.`);
1130
+ }
1131
+ const html = detail.url === void 0 ? void 0 : await (options.fetchText ?? fetchDocument)(detail.url);
1132
+ const document = html === void 0 ? void 0 : parseOriginDocument(html);
1133
+ const origin = originOf(detail, document);
1134
+ const pages = origin.inventory?.pages ?? 1;
1135
+ spin.stop(document ? `Read \`${origin.name}\`: ${origin.products.length} products, ${pages} page${pages === 1 ? "" : "s"}` : `Read \`${origin.name}\` from the API only — its served document could not be fetched, so inventory it by hand`);
1136
+ if (fs.existsSync(path.join(target, "paywalls", origin.slug, "config.ts"))) throw new Error(`\`paywalls/${origin.slug}\` already exists in ${path.relative(root, target) || "."} — rename or remove it first.`);
1137
+ if (options.newProject) writeProjectFiles(target, projectPackageName(root));
1138
+ writeSurfaceFiles(target, origin.slug, originConfigSource(origin));
1139
+ fs.writeFileSync(path.join(target, "paywalls", origin.slug, "MIGRATION.md"), originBrief(origin));
1140
+ if (origin.url !== void 0) writeOrigin(target, "paywall", origin.slug, {
1141
+ paywallId: origin.id,
1142
+ url: origin.url
1143
+ });
1144
+ ui.step(`Created ${path.relative(root, target) || "."}/paywalls/${origin.slug} from \`${origin.name}\``);
1145
+ if (origin.products.some((product) => product.identifier === "missing")) ui.warn("Some product slots have no store product on the dashboard — fix them in config.ts before pushing.");
1146
+ if (origin.applicationId !== void 0 && origin.platform !== void 0) {
1147
+ if (readLock(target).apps[origin.platform] === void 0) {
1148
+ writeApp(target, origin.platform, origin.applicationId);
1149
+ const app = (await listApplications(api).catch(() => [])).find((candidate) => String(candidate.id) === origin.applicationId);
1150
+ if (app) ui.success(`Pushes go to \`${app.name ?? app.id}\`, the paywall's app — saved in superwall.lock, so commit that file.`);
1151
+ else {
1152
+ const organization = origin.projectId === void 0 ? void 0 : await projectOrganizationId(api, origin.projectId).catch(() => void 0);
1153
+ ui.success(`Pushes go to app ${origin.applicationId}, the paywall's app — saved in superwall.lock.`);
1154
+ ui.warn(organization === void 0 ? "That app is in another organization: run `superwall orgs use <id>` before pushing." : `That app is in another organization: run \`superwall orgs use ${organization}\` before pushing.`);
1155
+ }
1156
+ }
1157
+ }
1158
+ return origin;
1159
+ }
1160
+ const SCREEN_REFERENCE = {
1161
+ swiftui: "ios",
1162
+ uikit: "ios",
1163
+ compose: "android",
1164
+ "android-views": "android",
1165
+ "react-native": "react-native",
1166
+ flutter: "flutter"
1167
+ };
1168
+ const screenPrompt = (migration, origin) => loadPrompt("actions/screen-migrate.xml", {
1169
+ project_dir: migration.superwallDir,
1170
+ surface_dir: `paywalls/${migration.surfaceId}`,
1171
+ source_path: origin.path,
1172
+ framework: screenFrameworkLabel(origin.framework),
1173
+ screenshot: origin.screenshot === void 0 ? "none" : `paywalls/${migration.surfaceId}/${origin.screenshot}`,
1174
+ dashboard_url: DASHBOARD_URL,
1175
+ skill: loadBundledSkill("superwall-screen-migrate", SCREEN_REFERENCE[origin.framework]),
1176
+ brief: migration.brief || "(MIGRATION.md is missing — inventory the source file first.)"
1177
+ });
1178
+ const paywallPrompt = (migration, origin) => loadPrompt("actions/paywall-migrate.xml", {
1179
+ project_dir: migration.superwallDir,
1180
+ surface_dir: `paywalls/${migration.surfaceId}`,
1181
+ paywall_id: origin.paywallId,
1182
+ source_url: origin.url,
1183
+ dashboard_url: DASHBOARD_URL,
1184
+ skill: loadBundledSkill("superwall-paywall-migrate"),
1185
+ brief: migration.brief || "(MIGRATION.md is missing — inventory the source from its URL first.)"
1186
+ });
1187
+ function buildMigrationPrompt(migration) {
1188
+ return isScreenOrigin(migration.origin) ? screenPrompt(migration, migration.origin) : paywallPrompt(migration, migration.origin);
1189
+ }
1190
+ function buildMigrationCopyPrompt(migration) {
1191
+ return buildMigrationPrompt(migration).split("\n").filter((line) => !line.includes("[STATUS]")).join("\n").trimEnd();
1192
+ }
1193
+ const runtime = {
1194
+ detectDrivers,
1195
+ run: runWithDriverFallback,
1196
+ copyToClipboard
1197
+ };
1198
+ async function runMigration(migration, onEvent, deps = runtime) {
1199
+ const drivers = await deps.detectDrivers();
1200
+ if (drivers.length === 0) throw new Error("No coding agent found (Claude Code or Codex) — copy the prompt instead.");
1201
+ return deps.run(drivers.map((detected) => detected.driver), {
1202
+ prompt: buildMigrationPrompt(migration),
1203
+ cwd: migration.superwallDir,
1204
+ capabilities: {
1205
+ filesystem: "write",
1206
+ network: true,
1207
+ shell: "unrestricted"
1208
+ },
1209
+ onEvent
1210
+ });
1211
+ }
1212
+ async function offerMigration(ui, interactive, migration, forced, deps = runtime) {
1213
+ const agentName = (await deps.detectDrivers())[0]?.info.displayName;
1214
+ let choice = forced ?? "later";
1215
+ if (forced === void 0 && interactive) {
1216
+ const picked = await ui.select({
1217
+ message: "Rebuild the pages now?",
1218
+ options: [
1219
+ ...agentName === void 0 ? [] : [{
1220
+ value: "agent",
1221
+ label: `With ${agentName}`,
1222
+ hint: "runs here, headless; you review in the studio after"
1223
+ }],
1224
+ {
1225
+ value: "copy",
1226
+ label: "Copy the prompt",
1227
+ hint: "paste it into Claude Code, Codex, Cursor, or another agent"
1228
+ },
1229
+ {
1230
+ value: "later",
1231
+ label: "Not now",
1232
+ hint: `${migrationCommand(migration)} picks this up later`
1233
+ }
1234
+ ],
1235
+ initialValue: agentName === void 0 ? "copy" : "agent"
1236
+ });
1237
+ choice = picked === "agent" || picked === "copy" ? picked : "later";
1238
+ }
1239
+ if (choice === "copy") {
1240
+ const prompt = buildMigrationCopyPrompt(migration);
1241
+ if (await deps.copyToClipboard(prompt)) ui.note(isScreenOrigin(migration.origin) ? "Paste it into Claude Code, Codex, Cursor, or another coding agent, opened in the app's root so it can read the source screen." : "Paste it into Claude Code, Codex, Cursor, or another coding agent, opened in the superwall/ directory.", "Migration prompt copied to clipboard");
1242
+ else ui.note(prompt, "Migration prompt (copy it manually)");
1243
+ } else if (choice === "agent") {
1244
+ const spin = ui.spinner();
1245
+ spin.start(`Rebuilding paywalls/${migration.surfaceId}`);
1246
+ const result = await runMigration(migration, (event) => {
1247
+ if (event.type === "status") spin.message(event.text);
1248
+ }, deps);
1249
+ if (!result.ok) {
1250
+ spin.stop("The agent stopped before finishing.");
1251
+ if (result.finalText) ui.report(stripReport(result.finalText).slice(0, 1500));
1252
+ throw new Error("The rebuild did not complete.");
1253
+ }
1254
+ spin.stop(`Rebuilt paywalls/${migration.surfaceId}`);
1255
+ if (result.finalText) ui.report(stripReport(result.finalText).slice(0, 1500));
1256
+ }
1257
+ return choice;
1258
+ }
1259
+
1260
+ //#endregion
1261
+ //#region src/commands/paywalls/open-studio.ts
1262
+ async function askStudio(ui, interactive, surfaceId, original = true) {
1263
+ if (!interactive) return false;
1264
+ return await ui.confirm({
1265
+ message: original ? `Open the studio now, on paywall/${surfaceId} next to the original?` : `Open the studio now, on paywall/${surfaceId}?`,
1266
+ initial: true
1267
+ }) === true;
1268
+ }
1269
+ async function startStudio(superwallDir, surfaceId, original = true) {
1270
+ await executeCommand(runDev.definition, {
1271
+ _: [],
1272
+ $0: "superwall",
1273
+ dir: [superwallDir],
1274
+ port: 6100,
1275
+ host: "0.0.0.0",
1276
+ open: original ? `paywall/${surfaceId}?compare=origin` : `paywall/${surfaceId}`
1277
+ }, {});
1278
+ }
1279
+ function migrationNextSteps(studioOpening, superwallDir, paywallId, choice) {
1280
+ const compare = studioOpening ? "The studio opens on the rebuilt paywall with the original beside it. Walk every page in both schemes (the toolbar's Compare menu switches the right pane)." : `Run \`superwall dev\` in ${superwallDir}, open the paywall, and pick Compare › Original in the toolbar. Walk every page in both schemes.`;
1281
+ return [
1282
+ ...choice === "later" ? [`superwall migrate ${paywallId} — rebuild with your agent, or copy the prompt for one.`] : [],
1283
+ compare,
1284
+ "It's your code now: anything that doesn't match, ask your agent to tweak in paywalls/, and the studio reloads live.",
1285
+ "Push when it's right. The dashboard paywall keeps serving until a campaign points at the new one."
1286
+ ];
1287
+ }
1288
+ function screenNextSteps(input) {
1289
+ const review = input.studioOpening ? input.screenshot ? "The studio opens on the rebuilt screen with the simulator screenshot beside it. Check every state in both schemes." : "The studio opens on the rebuilt screen. Keep the original open in the simulator and check every state in both schemes." : `Run \`superwall dev\` in ${input.superwallDir} and open the screen${input.screenshot ? "; Compare › Original shows the simulator screenshot" : " next to the original running in the simulator"}. Check every state in both schemes.`;
1290
+ return [
1291
+ ...input.choice === "later" ? [`superwall migrate --screen ${input.screenPath} — rebuild with your agent, or copy the prompt for one.`] : [],
1292
+ review,
1293
+ "It's your code now: anything that doesn't match, ask your agent to tweak in paywalls/, and the studio reloads live.",
1294
+ `Push when it's right, then wire the app: register("${input.placement}") where it presented ${input.screenPath}, a campaign for that placement (\`superwall integrate\` covers it), and delete the native screen.`
1295
+ ];
1296
+ }
1297
+
1298
+ //#endregion
1299
+ export { screenNameOf as _, buildMigrationCopyPrompt as a, writeTemplate as b, migrationFor as c, projectDirOf as d, scaffoldFromPaywall as f, placementOfName as g, findScreenCandidates as h, startStudio as i, migrationSource as l, screenMigrationFor as m, migrationNextSteps as n, hasOriginal as o, scaffoldFromScreen as p, screenNextSteps as r, isSuperwallProject as s, askStudio as t, offerMigration as u, starterConfig as v, slugOf as x, writeSurfaceFiles as y };