@superwall/cli 2.3.1 → 2.5.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 (117) hide show
  1. package/README.md +10 -0
  2. package/dist/{apple-z2qjOzIZ.js → apple-Dyr7OFBx.js} +17 -16
  3. package/dist/approve-Czs1-JO9.js +186 -0
  4. package/dist/{assets-DXXegdDt.js → assets-BrB9jQPQ.js} +3 -3
  5. package/dist/auth.d.ts +1 -1
  6. package/dist/auth.js +3 -3
  7. package/dist/{billing-B8tOjsnY.js → billing-D5qqIlVb.js} +3 -3
  8. package/dist/{bind-Bx9K6LwP.js → bind-B3eEcRyp.js} +4 -4
  9. package/dist/browser-Bp3yRKlU.js +36 -0
  10. package/dist/{build-Bu2kkzRe.js → build-DD9pSwHX.js} +10 -8
  11. package/dist/{client-DOgk9gAS.js → client-AI9H4GGB.js} +3 -3
  12. package/dist/{config-BO1Y87kV.js → config-CGcG7GOt.js} +9 -1
  13. package/dist/{create-B03MAuPe.js → create-B4m-IKlr.js} +8 -8
  14. package/dist/create-CJljlkJK.js +20 -0
  15. package/dist/{create-DzC_89gq.js → create-ChfgWpiM.js} +41 -69
  16. package/dist/{doctor-BGZSKY_B.js → doctor-XtXW6tKE.js} +6 -6
  17. package/dist/download-2Zu2I_Og.js +58 -0
  18. package/dist/{drivers-DqLgQxkC.js → drivers-CMEL13gp.js} +4 -4
  19. package/dist/entry.js +69 -33
  20. package/dist/{environment-i8BhiBDB.js → environment-BWT2S4qC.js} +9 -2
  21. package/dist/{existing-BPOG5zLO.js → existing-b0GxFcnc.js} +2 -2
  22. package/dist/{session-BDLQUJyV.js → git-D7AVdugb.js} +97 -335
  23. package/dist/held-CX7Zf8u-.js +17 -0
  24. package/dist/{held-C56PYMRH.js → held-D3PUNky2.js} +7 -7
  25. package/dist/install-CVUXsx8c.js +103 -0
  26. package/dist/{integrate-DZ4Qvoch.js → integrate-qvKd9pVW.js} +29 -27
  27. package/dist/{log-NVhVe_oe.js → log-C0MDCfA2.js} +1 -1
  28. package/dist/{login-p9GVEKzD.js → login-COmGHrU5.js} +2 -1
  29. package/dist/login-ClnJi1Ea.js +17 -0
  30. package/dist/{login-ONZdK8vN.js → login-PMoXUGqq.js} +9 -42
  31. package/dist/{lookup-flTi0at0.js → lookup-gjcKIZvh.js} +4 -3
  32. package/dist/{migrate-DnXpbhL1.js → migrate-SkkLLdmr.js} +33 -28
  33. package/dist/{migration-DJ1uNKhk.js → migration-DS44-3Zr.js} +10 -10
  34. package/dist/{notification-url-CCDeS5S-.js → notification-url-BjQPLf4-.js} +4 -4
  35. package/dist/{open-QdsZ_N47.js → open-DQpm2yVs.js} +2 -2
  36. package/dist/{org-BiFPjoHD.js → org-C04eAO-j.js} +3 -2
  37. package/dist/organization-BOECL3vZ.js +39 -0
  38. package/dist/orgs-D6Kk96mG.js +81 -0
  39. package/dist/{paths-yRgm5Jpa.js → paths-REb-GrbX.js} +2 -2
  40. package/dist/{playbook-B-pRKNa4.js → playbook-Du4Oydbf.js} +11 -11
  41. package/dist/{products-DH_fK9tY.js → products-Cqq59DBQ.js} +1 -1
  42. package/dist/project-CP6hiHra.js +47 -0
  43. package/dist/{promote-Djzk4C81.js → promote-Dm2_b1WK.js} +24 -19
  44. package/dist/pull-DsdOoG-D.js +36 -0
  45. package/dist/{pull-BLA9XwHj.js → pull-F6pvO4To.js} +9 -28
  46. package/dist/pull-zYAbqo9n.js +106 -0
  47. package/dist/{push-gSBxGDik.js → push-BIFLhAiO.js} +9 -7
  48. package/dist/push-CJVfvFZq.js +29 -0
  49. package/dist/push-D_l9KJZN.js +290 -0
  50. package/dist/push-SVzv7fzE.js +22 -0
  51. package/dist/{registry-D3xmWk9p.js → registry-DIJB0mJa.js} +890 -158
  52. package/dist/resolve--GsHj0Q1.js +171 -0
  53. package/dist/{resources-BTnczJCA.js → resources-BaP3p_LY.js} +3 -80
  54. package/dist/{run-C1SoizcJ.js → run-C5OPwhvS.js} +2 -2
  55. package/dist/run-CgLmD2vR.js +1345 -0
  56. package/dist/{scan-Dwk_lT5q.js → scan-Bj5y0zTZ.js} +1 -1
  57. package/dist/scan-v_WTE722.js +4 -0
  58. package/dist/{scope-Db7blD-l.js → scope-Bp_zwJOo.js} +6 -5
  59. package/dist/scope-CCb_7UvN.js +89 -0
  60. package/dist/sdk-TvT0p_nO.js +71 -0
  61. package/dist/selection-BltBpyp5.js +179 -0
  62. package/dist/series-TAixFBWW.js +685 -0
  63. package/dist/{server-Cb2N75JL.js → server-CdVIboQn.js} +10 -8
  64. package/dist/server-CvJVusw3.js +29 -0
  65. package/dist/session-B8JNXkwN.js +6 -0
  66. package/dist/session-D3fgXQBt.js +219 -0
  67. package/dist/{session-CnDJp_HO.js → session-Ywim-P8M.js} +1 -1
  68. package/dist/{setup-BLahHpgy.js → setup-zzjtTy8k.js} +9 -8
  69. package/dist/skills/index.json +5 -0
  70. package/dist/skills/superwall/SKILL.md +48 -30
  71. package/dist/skills/superwall/references/api.md +3 -2
  72. package/dist/skills/superwall-editor/SKILL.md +7 -5
  73. package/dist/skills/superwall-framework/SKILL.md +11 -8
  74. package/dist/skills/superwall-framework/references/onboarding-state.md +21 -14
  75. package/dist/skills/superwall-workspaces/SKILL.md +313 -0
  76. package/dist/skills/superwall-workspaces/references/cli.md +174 -0
  77. package/dist/skills/superwall-workspaces/references/slots.md +103 -0
  78. package/dist/{skills-zebMTZyr.js → skills-2qYaUXGE.js} +15 -9
  79. package/dist/skills-8um2fBPS.js +14 -0
  80. package/dist/{source-push-DxuJuwEf.js → source-push-kAep4gPe.js} +6 -5
  81. package/dist/{spinner-BN3U1CVB.js → spinner-BANVLncC.js} +17 -5
  82. package/dist/starter-CiLrp1cN.js +190 -0
  83. package/dist/status-CoYMK7QL.js +139 -0
  84. package/dist/{storage-VagEaaJC.js → storage-DzP22xKn.js} +1 -1
  85. package/dist/storekit-D5eopLM0.js +17 -0
  86. package/dist/{storekit-CoOf4Rvh.js → storekit-n1x0bWkQ.js} +4 -4
  87. package/dist/{telemetry-CM0BDwCK.js → telemetry-CXN6f-ZX.js} +2 -2
  88. package/dist/{token-lUUOkTJA.js → token-FmeHywYt.js} +1 -1
  89. package/dist/tools-skills/superwall/SKILL.md +49 -31
  90. package/dist/tools-skills/superwall/references/api.md +3 -2
  91. package/dist/tools-skills/superwall-editor/SKILL.md +7 -5
  92. package/dist/tools.d.ts +1 -1
  93. package/dist/tools.js +575 -75
  94. package/dist/try-BWbzgelb.js +120 -0
  95. package/dist/{selection-u2KiKu_d.js → types-JdxmnCko.js} +1 -178
  96. package/dist/upgrade-Bk5boOgW.js +206 -0
  97. package/dist/upgrade-CoWCEnoi.js +7 -0
  98. package/package.json +5 -3
  99. package/prompts/commandments.xml +2 -0
  100. package/dist/create-BdZS_T68.js +0 -19
  101. package/dist/held-DSNUY-NZ.js +0 -16
  102. package/dist/login-Blrkm6oi.js +0 -16
  103. package/dist/push-BkMgOT6X.js +0 -24
  104. package/dist/scan-Kp-MAutK.js +0 -4
  105. package/dist/server-psYghr9K.js +0 -24
  106. package/dist/session-CehHJWZk.js +0 -6
  107. package/dist/skills-DDV4zcLR.js +0 -14
  108. package/dist/storekit-BcBb2jXB.js +0 -16
  109. package/dist/upgrade-CpTJv_M7.js +0 -7
  110. package/dist/upgrade-DZbKb67W.js +0 -117
  111. /package/dist/{client-BZ1UbpXz.js → client-BJQXl62Q.js} +0 -0
  112. /package/dist/{devtools-pBl_vt03.js → devtools-ByZ6XYnn.js} +0 -0
  113. /package/dist/{input-vi0bou04.js → input-MDd67UIp.js} +0 -0
  114. /package/dist/{reports-CwwKLUh0.js → reports-CuhB1_ub.js} +0 -0
  115. /package/dist/{screenshot-file-tVBfUEIi.js → screenshot-file-XAS0Xy0e.js} +0 -0
  116. /package/dist/{storage-gRyQetN9.d.ts → storage-BjQCiTuz.d.ts} +0 -0
  117. /package/dist/{timing-BVxPrYq3.js → timing-Ca0TXY-A.js} +0 -0
@@ -0,0 +1,685 @@
1
+ import { i as bundleDir, o as readManifest, r as WorkspaceError, t as MANIFEST_FILE } from "./project-CP6hiHra.js";
2
+ import { createRequire } from "node:module";
3
+ import { execFile } from "node:child_process";
4
+ import * as fs from "node:fs";
5
+ import * as os$1 from "node:os";
6
+ import * as path from "node:path";
7
+ import { pathToFileURL } from "node:url";
8
+ import { promisify } from "node:util";
9
+
10
+ //#region src/core/workspaces/wire.ts
11
+ const CONTEXT_HEADER = "x-superwall-workspace-context";
12
+ const ENTRYPOINT_HEADER = "x-superwall-workspace-entrypoint";
13
+ const TRIGGER_HEADER = "x-superwall-workspace-trigger";
14
+ const WORKSPACE_HEADER_PREFIX = "x-superwall-workspace-";
15
+ const API_HOST = "api.workspace.internal";
16
+ const PLATFORM_HOST = "platform.workspace.internal";
17
+ const BRIDGE_PROTOCOL = "superwall-workspace@1";
18
+ const MOUNT_LOAD_TIMEOUT_MS = 8e3;
19
+ const WORKSPACE_COMPATIBILITY_DATE = "2026-09-01";
20
+ const METRIC_LIMITS = {
21
+ maxPoints: 5e3,
22
+ maxSeries: 50,
23
+ maxBytes: 256 * 1024,
24
+ timeoutMs: 1e4
25
+ };
26
+ const READOUT_LIMITS = {
27
+ maxBytes: 32 * 1024,
28
+ timeoutMs: 1e4
29
+ };
30
+ const DRAFT_MODULE_MAX_BYTES = 1024 * 1024;
31
+ const BUNDLE_MAX_BYTES = 10 * 1024 * 1024;
32
+ const CLIENT_BUNDLE_MODULE = "@superwall/workspace-sdk/client-bundle";
33
+ const isInternalPath = (pathname) => {
34
+ let decoded;
35
+ try {
36
+ decoded = decodeURIComponent(pathname);
37
+ } catch {
38
+ return true;
39
+ }
40
+ const normalized = decoded.toLowerCase().replace(/\\/g, "/").replace(/\/{2,}/g, "/");
41
+ return normalized === "/__sw" || normalized.startsWith("/__sw/");
42
+ };
43
+
44
+ //#endregion
45
+ //#region src/core/workspaces/wrangler-config.ts
46
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
47
+ const isDeclared = (value) => {
48
+ if (value === void 0 || value === null || value === false || value === "") return false;
49
+ if (Array.isArray(value)) return value.length > 0;
50
+ if (isRecord(value)) return Object.values(value).some(isDeclared);
51
+ return true;
52
+ };
53
+ const REFUSED_KEYS = [
54
+ [[
55
+ "durable_objects",
56
+ "migrations",
57
+ "exports"
58
+ ], "Durable Objects are not supported in workspaces: platform storage is reached through fetch."],
59
+ [["workflows"], "Workflows are not supported in workspaces."],
60
+ [["containers", "cloudchamber"], "Containers are not supported in workspaces."],
61
+ [["vars", "secrets"], "Environment variables and secrets are not supported in the wrangler config: declare secrets in superwall.json."],
62
+ [["definedEnvironments", "targetEnvironment"], "Wrangler environments are not supported in workspaces: a workspace has one config, with no `env` section."],
63
+ [[
64
+ "kv_namespaces",
65
+ "r2_buckets",
66
+ "d1_databases",
67
+ "queues",
68
+ "services",
69
+ "send_email",
70
+ "vectorize",
71
+ "ai",
72
+ "ai_search",
73
+ "ai_search_namespaces",
74
+ "hyperdrive",
75
+ "analytics",
76
+ "analytics_engine_datasets",
77
+ "browser",
78
+ "images",
79
+ "media",
80
+ "stream",
81
+ "version_metadata",
82
+ "unsafe",
83
+ "unsafe_hello_world",
84
+ "mtls_certificates",
85
+ "tail_consumers",
86
+ "streaming_tail_consumers",
87
+ "dispatch_namespaces",
88
+ "pipelines",
89
+ "secrets_store_secrets",
90
+ "artifacts",
91
+ "flagship",
92
+ "ratelimits",
93
+ "worker_loaders",
94
+ "vpc_services",
95
+ "vpc_networks",
96
+ "logfwdr",
97
+ "assets",
98
+ "agent_memory",
99
+ "k2",
100
+ "connect",
101
+ "wasm_modules",
102
+ "text_blobs",
103
+ "data_blobs"
104
+ ], "Bindings are not supported in workspaces: a workspace reaches everything through fetch."],
105
+ [[
106
+ "no_bundle",
107
+ "find_additional_modules",
108
+ "base_dir",
109
+ "preserve_file_names",
110
+ "rules"
111
+ ], "A workspace is one bundled module: remove these and let the builder bundle `main`."],
112
+ [[
113
+ "site",
114
+ "pages_build_output_dir",
115
+ "addresses",
116
+ "access",
117
+ "cache",
118
+ "previews",
119
+ "first_party_worker"
120
+ ], "The platform serves a workspace, so these Worker settings don't apply."]
121
+ ];
122
+ const ALLOWED_KEYS = [
123
+ "$schema",
124
+ "name",
125
+ "main",
126
+ "compatibility_date",
127
+ "compatibility_flags",
128
+ "configPath",
129
+ "userConfigPath",
130
+ "topLevelName",
131
+ "build",
132
+ "triggers",
133
+ "define",
134
+ "alias",
135
+ "jsx_factory",
136
+ "jsx_fragment",
137
+ "minify",
138
+ "keep_names",
139
+ "tsconfig",
140
+ "python_modules",
141
+ "dependencies_instrumentation",
142
+ "account_id",
143
+ "route",
144
+ "routes",
145
+ "workers_dev",
146
+ "preview_urls",
147
+ "observability",
148
+ "logpush",
149
+ "upload_source_maps",
150
+ "send_metrics",
151
+ "limits",
152
+ "placement",
153
+ "compliance_region",
154
+ "keep_vars",
155
+ "dev"
156
+ ];
157
+ const KNOWN_WRANGLER_KEYS = new Set([...ALLOWED_KEYS, ...REFUSED_KEYS.flatMap(([keys]) => keys)]);
158
+ const COMPATIBILITY_DATE = /^\d{4}-\d{2}-\d{2}$/;
159
+ const MIN_COMPATIBILITY_DATE = "2024-09-23";
160
+ const COMPATIBILITY_FLAGS = new Set([
161
+ "nodejs_compat",
162
+ "nodejs_compat_v2",
163
+ "nodejs_als"
164
+ ]);
165
+ function builderProblem(config) {
166
+ if (!isRecord(config)) return "No wrangler config (wrangler.jsonc, wrangler.json or wrangler.toml) was found.";
167
+ for (const [keys, message] of REFUSED_KEYS) {
168
+ const found = keys.filter((key) => isDeclared(config[key]));
169
+ if (found.length > 0) return `${message} (found: ${found.join(", ")})`;
170
+ }
171
+ const unknown = Object.keys(config).filter((key) => !KNOWN_WRANGLER_KEYS.has(key) && isDeclared(config[key]));
172
+ if (unknown.length > 0) return `The wrangler config has keys the builder doesn't support (found: ${unknown.join(", ")}).`;
173
+ if (isRecord(config.triggers) && isDeclared(config.triggers.crons)) return "Cron triggers belong in superwall.json (`crons`), not the wrangler config.";
174
+ if (isRecord(config.build) && isDeclared(config.build.command)) return "Custom build commands are not supported: the builder bundles `main` with wrangler.";
175
+ if (typeof config.main !== "string" || config.main.length === 0) return "The wrangler config needs a `main` entry point.";
176
+ if (typeof config.compatibility_date !== "string" || !COMPATIBILITY_DATE.test(config.compatibility_date)) return "The wrangler config needs a compatibility_date (YYYY-MM-DD).";
177
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
178
+ if (config.compatibility_date < MIN_COMPATIBILITY_DATE || config.compatibility_date > today) return `compatibility_date must be between ${MIN_COMPATIBILITY_DATE} and today (found: ${config.compatibility_date}).`;
179
+ const refused = (Array.isArray(config.compatibility_flags) ? config.compatibility_flags : []).filter((flag) => !COMPATIBILITY_FLAGS.has(flag));
180
+ if (refused.length > 0) return `These compatibility_flags are not supported in workspaces: ${refused.join(", ")}. Allowed: ${[...COMPATIBILITY_FLAGS].join(", ")}.`;
181
+ }
182
+ function assertBuilderAccepts(config) {
183
+ const problem = builderProblem(config);
184
+ if (problem !== void 0) throw new WorkspaceError(`This would fail on the builder. ${problem}`);
185
+ }
186
+ const isOutsideRepo = (input) => input === ".." || input.startsWith("../") || input.startsWith("/") || input === ".git" || input.startsWith(".git/");
187
+ const INPUTS_SHOWN = 5;
188
+ function outsideRepoProblem(inputs) {
189
+ if (inputs.length === 0) return void 0;
190
+ return `The bundle reads files outside the repo, which isn't allowed: ${inputs.slice(0, INPUTS_SHOWN).join(", ")}${inputs.length > INPUTS_SHOWN ? ` and ${inputs.length - INPUTS_SHOWN} more` : ""}.`;
191
+ }
192
+ const workerInputsOutside = (inputs, toolchain) => inputs.filter((input) => isOutsideRepo(input) && !toolchain(input));
193
+
194
+ //#endregion
195
+ //#region src/core/workspaces/client-build.ts
196
+ const ENTRY_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9._\-/]*\.(?:tsx|ts|jsx|js|mts|mjs)$/;
197
+ const ENTRY_MAX_LENGTH = 256;
198
+ const LARGEST_SHOWN = 5;
199
+ const megabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
200
+ function clientEntryProblem(entry) {
201
+ if (typeof entry !== "string" || entry.length > ENTRY_MAX_LENGTH || !ENTRY_PATTERN.test(entry)) return `${MANIFEST_FILE}: client.entry must be a path inside the repo to a .ts, .tsx, .js, .jsx, .mts or .mjs file`;
202
+ const segments = entry.split("/");
203
+ if (segments.some((segment) => segment === "" || segment === "." || segment === "..")) return `${MANIFEST_FILE}: client.entry must stay inside the repo`;
204
+ if (segments.includes("node_modules")) return `${MANIFEST_FILE}: client.entry must not be inside node_modules`;
205
+ }
206
+ function entryProblem(root, entry) {
207
+ const file = path.join(root, entry);
208
+ try {
209
+ if (!fs.lstatSync(file).isFile()) return `client.entry: ${entry} is not a file.`;
210
+ if (!fs.realpathSync(file).startsWith(`${root}${path.sep}`)) return `client.entry: ${entry} is outside the repo.`;
211
+ return;
212
+ } catch {
213
+ return `client.entry: ${entry} is not in the repo.`;
214
+ }
215
+ }
216
+ async function loadSdk(root) {
217
+ const project = createRequire(path.join(root, "package.json"));
218
+ try {
219
+ const [build, constants] = await Promise.all([import(pathToFileURL(project.resolve("@superwall/workspace-sdk/client-build")).href), import(pathToFileURL(project.resolve("@superwall/workspace-sdk/constants")).href)]);
220
+ if (typeof build.outsideRepoInputs !== "function") throw new Error("An early 0.2.0");
221
+ return {
222
+ ...build,
223
+ ...constants
224
+ };
225
+ } catch {
226
+ throw new WorkspaceError("This project's workspace SDK is too old for client.entry. Run `superwall workspaces update`, then `npm install`.");
227
+ }
228
+ }
229
+ function loadEsbuild(wranglerPackage) {
230
+ try {
231
+ return createRequire(wranglerPackage)("esbuild");
232
+ } catch {
233
+ throw new WorkspaceError("client.entry is bundled with the esbuild this project's wrangler brings, and it isn't installed. Run `npm install`.");
234
+ }
235
+ }
236
+ function explainBundleFailure(error, hasClient) {
237
+ if (hasClient || !error.message.includes(CLIENT_BUNDLE_MODULE)) return error;
238
+ return new WorkspaceError(`${error.message}\nDeclare the browser entry in ${MANIFEST_FILE}: "client": { "entry": "src/client.tsx" }.`);
239
+ }
240
+ async function buildClientAlias(projectRoot, entry, wranglerPackage) {
241
+ const problem = clientEntryProblem(entry);
242
+ if (problem !== void 0) throw new WorkspaceError(problem);
243
+ const root = fs.realpathSync(projectRoot);
244
+ const relative$1 = entry;
245
+ const missing = entryProblem(root, relative$1);
246
+ if (missing !== void 0) throw new WorkspaceError(missing);
247
+ const sdk = await loadSdk(root);
248
+ const esbuild = loadEsbuild(wranglerPackage);
249
+ let result;
250
+ try {
251
+ result = await sdk.buildClient(esbuild, {
252
+ root,
253
+ entry: relative$1
254
+ });
255
+ } catch (error) {
256
+ throw new WorkspaceError(`${error.message} It comes with this project's wrangler, so install the wrangler the starter pins.`);
257
+ }
258
+ if (!result.ok) throw new WorkspaceError(result.message);
259
+ const outside = outsideRepoProblem(sdk.outsideRepoInputs(result.inputPaths));
260
+ if (outside !== void 0) throw new WorkspaceError(outside);
261
+ const total = result.scriptBytes + result.styleBytes;
262
+ if (total > sdk.CLIENT_BUNDLE_MAX_BYTES) {
263
+ const largest = result.inputs.slice(0, LARGEST_SHOWN).map((input) => `${input.path} (${megabytes(input.bytes)})`).join(", ");
264
+ throw new WorkspaceError(`The client bundle is ${total} bytes (${megabytes(total)}); the limit is ${sdk.CLIENT_BUNDLE_MAX_BYTES} (${megabytes(sdk.CLIENT_BUNDLE_MAX_BYTES)}). Largest: ${largest}.`);
265
+ }
266
+ const dir = bundleDir(root);
267
+ fs.mkdirSync(dir, { recursive: true });
268
+ const file = path.join(dir, "client-bundle.mjs");
269
+ fs.writeFileSync(file, result.module);
270
+ return ["--alias", `${sdk.CLIENT_BUNDLE_MODULE}:${file}`];
271
+ }
272
+
273
+ //#endregion
274
+ //#region src/core/workspaces/bundle.ts
275
+ const run = promisify(execFile);
276
+ function resolveWranglerPackage(root) {
277
+ try {
278
+ return createRequire(path.join(root, "package.json")).resolve("wrangler/package.json");
279
+ } catch {
280
+ throw new WorkspaceError("This workspace needs wrangler installed to bundle it. Run `npm install`, or `npm install -D wrangler` if it isn't in package.json.");
281
+ }
282
+ }
283
+ const PASSED_ENV = [
284
+ "PATH",
285
+ "HOME",
286
+ "USERPROFILE",
287
+ "TMPDIR",
288
+ "TEMP",
289
+ "TMP",
290
+ "SystemRoot"
291
+ ];
292
+ const builderEnv = () => ({
293
+ ...Object.fromEntries(PASSED_ENV.filter((name) => process.env[name] !== void 0).map((name) => [name, process.env[name]])),
294
+ LANG: "C.UTF-8",
295
+ CI: "1",
296
+ NO_COLOR: "1",
297
+ WRANGLER_SEND_METRICS: "false",
298
+ WRANGLER_SEND_ERROR_REPORTS: "false"
299
+ });
300
+ const runWrangler = async (root, args) => {
301
+ const bin = path.join(path.dirname(resolveWranglerPackage(root)), "bin", "wrangler.js");
302
+ try {
303
+ await run("node", [bin, ...args], {
304
+ cwd: root,
305
+ timeout: 3e5,
306
+ maxBuffer: 16 * 1024 * 1024,
307
+ env: builderEnv()
308
+ });
309
+ } catch (error) {
310
+ const { stdout = "", stderr = "" } = error;
311
+ throw new WorkspaceError(`The workspace didn't bundle:\n${`${stdout}\n${stderr}`.trim().split("\n").slice(-30).join("\n")}`);
312
+ }
313
+ };
314
+ const READ_CONFIG_SCRIPT = `
315
+ import { writeFileSync } from "node:fs";
316
+ const [wrangler, out] = process.argv.slice(1);
317
+ const { unstable_readConfig } = await import(wrangler);
318
+ let result;
319
+ try {
320
+ const config = unstable_readConfig({}, { hideWarnings: true });
321
+ result = config.configPath ? { config } : { config: null };
322
+ } catch (error) {
323
+ result = { error: error instanceof Error ? error.message : String(error) };
324
+ }
325
+ writeFileSync(out, JSON.stringify(result));
326
+ `;
327
+ const readWranglerConfig = async (root) => {
328
+ resolveWranglerPackage(root);
329
+ const wrangler = pathToFileURL(createRequire(path.join(root, "package.json")).resolve("wrangler")).href;
330
+ const out = path.join(bundleDir(root), "config.json");
331
+ fs.mkdirSync(path.dirname(out), { recursive: true });
332
+ fs.rmSync(out, { force: true });
333
+ await run("node", [
334
+ "--input-type=module",
335
+ "-e",
336
+ READ_CONFIG_SCRIPT,
337
+ wrangler,
338
+ out
339
+ ], {
340
+ cwd: root,
341
+ timeout: 12e4,
342
+ env: builderEnv()
343
+ }).catch(() => void 0);
344
+ try {
345
+ return JSON.parse(fs.readFileSync(out, "utf8"));
346
+ } catch {
347
+ return { error: "wrangler couldn't read it." };
348
+ }
349
+ };
350
+ async function acceptedConfig(root, read) {
351
+ const { config, error } = await read(root);
352
+ if (error !== void 0) throw new WorkspaceError(`The wrangler config could not be read: ${error}`);
353
+ assertBuilderAccepts(config);
354
+ const accepted = config;
355
+ const configPath = String(accepted.configPath);
356
+ if (path.dirname(fs.realpathSync(path.resolve(root, configPath))) !== fs.realpathSync(root)) throw new WorkspaceError("This would fail on the builder. No wrangler config was read from the repo root.");
357
+ return {
358
+ configPath,
359
+ compatibility: {
360
+ date: accepted.compatibility_date,
361
+ flags: accepted.compatibility_flags ?? []
362
+ }
363
+ };
364
+ }
365
+ function assertInputsInRepo(root, meta) {
366
+ const realRoot = fs.realpathSync(root);
367
+ const inToolchain = (input) => {
368
+ const toolchain = path.dirname(fs.realpathSync(path.dirname(resolveWranglerPackage(root))));
369
+ return path.resolve(realRoot, input).startsWith(`${toolchain}${path.sep}`);
370
+ };
371
+ const problem = outsideRepoProblem(workerInputsOutside(Object.keys(meta.inputs ?? {}), inToolchain));
372
+ if (problem !== void 0) throw new WorkspaceError(problem);
373
+ }
374
+ function bundleExports(meta, output, root) {
375
+ for (const [file, info] of Object.entries(meta.outputs ?? {})) if (info.entryPoint && path.resolve(root, file) === output) return info.exports ?? [];
376
+ return null;
377
+ }
378
+ async function bundleWorkspace(root, wrangler = runWrangler) {
379
+ const dir = bundleDir(root);
380
+ const out = path.join(dir, "out");
381
+ const metafile = path.join(dir, "meta.json");
382
+ fs.rmSync(out, {
383
+ recursive: true,
384
+ force: true
385
+ });
386
+ fs.mkdirSync(out, { recursive: true });
387
+ const { client } = readManifest(root);
388
+ const { configPath, compatibility } = await acceptedConfig(root, wrangler.readConfig ?? readWranglerConfig);
389
+ const alias = client === void 0 ? [] : await buildClientAlias(root, client.entry, resolveWranglerPackage(root));
390
+ await wrangler(root, [
391
+ "deploy",
392
+ "--dry-run",
393
+ "--outdir",
394
+ out,
395
+ "--metafile",
396
+ metafile,
397
+ "--config",
398
+ configPath,
399
+ "--env-file",
400
+ os$1.devNull,
401
+ ...alias
402
+ ]).catch((error) => {
403
+ throw explainBundleFailure(error, client !== void 0);
404
+ });
405
+ const files = fs.readdirSync(out).filter((file$1) => !file$1.endsWith(".map") && file$1 !== "README.md");
406
+ const modules = files.filter((file$1) => /\.m?js$/.test(file$1));
407
+ const [file] = modules;
408
+ if (file === void 0 || modules.length !== 1 || files.length !== 1) throw new WorkspaceError(`A workspace bundles to exactly one ES module; this one made ${files.join(", ") || "nothing"}. Text, data and wasm modules aren't supported.`);
409
+ const output = path.join(out, file);
410
+ const meta = JSON.parse(fs.readFileSync(metafile, "utf8"));
411
+ assertInputsInRepo(root, meta);
412
+ const exports = bundleExports(meta, output, root);
413
+ if (exports === null || !exports.includes("default")) throw new WorkspaceError("The bundle has no default export: export defineWorkspace({ fetch }) as the module's default.");
414
+ const named = exports.filter((name) => name !== "default");
415
+ if (named.length > 0) throw new WorkspaceError(`The bundle exports ${named.join(", ")}: a workspace exports only its default handlers.`);
416
+ const module = fs.readFileSync(output, "utf8");
417
+ const bytes = Buffer.byteLength(module);
418
+ if (bytes > BUNDLE_MAX_BYTES) throw new WorkspaceError(`The bundle is ${bytes} bytes; the limit is ${BUNDLE_MAX_BYTES}.`);
419
+ return {
420
+ module,
421
+ bytes,
422
+ compatibility
423
+ };
424
+ }
425
+
426
+ //#endregion
427
+ //#region src/core/workspaces/slots.ts
428
+ const APP = ["organizationId", "applicationId"];
429
+ const USER = [
430
+ ...APP,
431
+ "appUserId",
432
+ "aliases",
433
+ "environment"
434
+ ];
435
+ const SLOTS = {
436
+ "org.page@1": {
437
+ shape: "page",
438
+ minHeight: 0,
439
+ maxHeight: null,
440
+ fields: ["organizationId"]
441
+ },
442
+ "app.page@1": {
443
+ shape: "page",
444
+ minHeight: 0,
445
+ maxHeight: null,
446
+ fields: [...APP, "environment"]
447
+ },
448
+ "app.dashboard.widget@1": {
449
+ shape: "card",
450
+ minHeight: 120,
451
+ maxHeight: 480,
452
+ fields: [
453
+ ...APP,
454
+ "environment",
455
+ "dateRange"
456
+ ]
457
+ },
458
+ "campaign.tab@1": {
459
+ shape: "tab",
460
+ minHeight: 240,
461
+ maxHeight: 4e3,
462
+ fields: [
463
+ ...APP,
464
+ "campaignId",
465
+ "audienceId",
466
+ "variantIds",
467
+ "environment",
468
+ "dateRange"
469
+ ],
470
+ optional: ["audienceId", "variantIds"]
471
+ },
472
+ "user.panel@1": {
473
+ shape: "panel",
474
+ minHeight: 80,
475
+ maxHeight: 640,
476
+ fields: USER,
477
+ optional: ["aliases"]
478
+ },
479
+ "user.action@1": {
480
+ shape: "modal",
481
+ minHeight: 120,
482
+ maxHeight: 640,
483
+ fields: USER,
484
+ optional: ["aliases"]
485
+ },
486
+ "chart.source@1": {
487
+ shape: "headless",
488
+ minHeight: 0,
489
+ maxHeight: 0,
490
+ fields: APP
491
+ },
492
+ "campaign.metric@1": {
493
+ shape: "headless",
494
+ minHeight: 0,
495
+ maxHeight: 0,
496
+ fields: [
497
+ ...APP,
498
+ "campaignId",
499
+ "audienceId",
500
+ "variantIds",
501
+ "environment"
502
+ ],
503
+ optional: ["variantIds"]
504
+ }
505
+ };
506
+ const DAY_MS = 864e5;
507
+ function defaultRange(days, now = Date.now()) {
508
+ return {
509
+ from: new Date(now - days * DAY_MS).toISOString(),
510
+ to: new Date(now).toISOString()
511
+ };
512
+ }
513
+ function slotOf(slot) {
514
+ const found = SLOTS[slot];
515
+ if (!found) throw new WorkspaceError(`This CLI doesn't know the slot \`${slot}\`. Run \`superwall upgrade\`, or pass its context with --context.`);
516
+ return found;
517
+ }
518
+ function positive(name, value) {
519
+ if (value === void 0 || value === "") return void 0;
520
+ const parsed = Number(value);
521
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) throw new WorkspaceError(`${name} must be a positive number.`);
522
+ return parsed;
523
+ }
524
+ function parseContextJson(text) {
525
+ let parsed;
526
+ try {
527
+ parsed = JSON.parse(text);
528
+ } catch (error) {
529
+ throw new WorkspaceError(`--context is not valid JSON: ${error.message}`);
530
+ }
531
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new WorkspaceError("--context must be a JSON object.");
532
+ return parsed;
533
+ }
534
+ const FIELD_LABELS = {
535
+ organizationId: "an organization (--org)",
536
+ applicationId: "an app (--app)",
537
+ environment: "an environment (--environment)",
538
+ dateRange: "a date range (--from and --to)",
539
+ campaignId: "a campaign (--campaign)",
540
+ audienceId: "an audience (--audience)",
541
+ variantIds: "variants (--variant)",
542
+ appUserId: "a user (--user)",
543
+ aliases: "aliases (--alias)"
544
+ };
545
+ const ENVIRONMENTS = ["PRODUCTION", "SANDBOX"];
546
+ function environmentOf(environment = "PRODUCTION") {
547
+ if (ENVIRONMENTS.includes(environment)) return environment;
548
+ throw new WorkspaceError(`The environment must be PRODUCTION or SANDBOX, in capitals. Got ${String(environment)}.`);
549
+ }
550
+ function fieldValue(field, input) {
551
+ switch (field) {
552
+ case "organizationId": return positive("The organization", input.organizationId);
553
+ case "applicationId": return positive("The app", input.applicationId);
554
+ case "campaignId": return positive("The campaign", input.campaignId);
555
+ case "audienceId": return positive("The audience", input.audienceId);
556
+ case "environment": return environmentOf(input.environment);
557
+ case "dateRange": {
558
+ const fallback = defaultRange(30);
559
+ const range = {
560
+ from: input.from || fallback.from,
561
+ to: input.to || fallback.to
562
+ };
563
+ if (Number.isNaN(Date.parse(range.from)) || Number.isNaN(Date.parse(range.to))) throw new WorkspaceError("The date range needs ISO 8601 date-times, like 2026-10-01T00:00:00Z.");
564
+ return {
565
+ from: new Date(range.from).toISOString(),
566
+ to: new Date(range.to).toISOString()
567
+ };
568
+ }
569
+ case "variantIds": return (input.variantIds ?? []).map((id) => positive("A variant", id));
570
+ case "appUserId": return input.appUserId || void 0;
571
+ case "aliases": return input.aliases ?? [];
572
+ }
573
+ }
574
+ function missingFields(slot, input) {
575
+ return slot.fields.filter((field) => {
576
+ if (slot.optional?.includes(field)) return false;
577
+ return fieldValue(field, input) === void 0;
578
+ }).map((field) => FIELD_LABELS[field]);
579
+ }
580
+ function buildContext(slotId, input) {
581
+ if (input.context !== void 0) {
582
+ const known = {
583
+ ...input.organizationId ? { organizationId: positive("The organization", input.organizationId) } : {},
584
+ ...input.applicationId ? { applicationId: positive("The app", input.applicationId) } : {}
585
+ };
586
+ const context$1 = parseContextJson(input.context);
587
+ if ("environment" in context$1) environmentOf(context$1.environment);
588
+ return {
589
+ ...known,
590
+ ...context$1
591
+ };
592
+ }
593
+ const slot = slotOf(slotId);
594
+ const missing = missingFields(slot, input);
595
+ if (missing.length > 0) throw new WorkspaceError(`${slotId} needs ${missing.join(", ")}.`);
596
+ const context = {};
597
+ for (const field of slot.fields) {
598
+ const value = fieldValue(field, input);
599
+ context[field] = value === void 0 && field === "audienceId" ? null : value;
600
+ }
601
+ return context;
602
+ }
603
+
604
+ //#endregion
605
+ //#region src/core/workspaces/series.ts
606
+ const ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})$/;
607
+ const isTimestamp = (value) => typeof value === "string" && ISO_TIMESTAMP.test(value) && !Number.isNaN(Date.parse(value));
608
+ const isKey = (value) => value === null || value === void 0 || typeof value === "string" && value.length >= 1 && value.length <= 128;
609
+ function seriesProblem(value) {
610
+ const points = value?.points;
611
+ if (!Array.isArray(points)) return "It must return { points: [...] }.";
612
+ if (points.length > METRIC_LIMITS.maxPoints) return `It returned ${points.length} points; the limit is ${METRIC_LIMITS.maxPoints}.`;
613
+ const bytes = Buffer.byteLength(JSON.stringify(value));
614
+ if (bytes > METRIC_LIMITS.maxBytes) return `It returned ${bytes} bytes; the limit is ${METRIC_LIMITS.maxBytes}.`;
615
+ for (const point of points) {
616
+ if (!isTimestamp(point?.t)) return `A point's t must be an ISO 8601 date-time with an offset, like 2026-10-01T00:00:00Z. Got ${JSON.stringify(point?.t)}.`;
617
+ if (typeof point.value !== "number" || !Number.isFinite(point.value)) return `The point at ${point.t} has a value that isn't a finite number: ${JSON.stringify(point.value)}.`;
618
+ if (!isKey(point.breakdown)) return `The point at ${point.t} has a breakdown that isn't 1 to 128 characters.`;
619
+ }
620
+ const series = new Set(points.map((point) => point.breakdown ?? null));
621
+ if (series.size > METRIC_LIMITS.maxSeries) return `It returned ${series.size} breakdown values; the limit is ${METRIC_LIMITS.maxSeries}.`;
622
+ }
623
+ const isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
624
+ function variantProblem(variant, seen, variantIds) {
625
+ const { variantId, value, interval } = variant ?? {};
626
+ if (typeof variantId !== "number" || !Number.isSafeInteger(variantId) || variantId <= 0) return `A variant has a variantId that isn't a positive whole number: ${JSON.stringify(variantId)}.`;
627
+ if (seen.has(variantId)) return `Variant ${variantId} appears twice.`;
628
+ seen.add(variantId);
629
+ if (variantIds.length > 0 && !variantIds.includes(variantId)) return `Variant ${variantId} isn't one of this audience's variants.`;
630
+ if (value !== null && !isFiniteNumber(value)) return `Variant ${variantId} has a value that isn't a finite number or null.`;
631
+ if (interval === void 0) return void 0;
632
+ if (!Array.isArray(interval) || interval.length !== 2 || !interval.every(isFiniteNumber)) return `Variant ${variantId} has an interval that isn't two finite numbers.`;
633
+ const [lower, upper] = interval;
634
+ if (value === null || lower > value || value > upper) return `Variant ${variantId} has an interval that doesn't hold its value.`;
635
+ }
636
+ function readoutProblem(value, variantIds) {
637
+ const variants = value?.variants;
638
+ if (!Array.isArray(variants)) return "It must return { variants: [...] }.";
639
+ const bytes = Buffer.byteLength(JSON.stringify(value));
640
+ if (bytes > READOUT_LIMITS.maxBytes) return `It returned ${bytes} bytes; the limit is ${READOUT_LIMITS.maxBytes}.`;
641
+ const seen = /* @__PURE__ */ new Set();
642
+ for (const variant of variants) {
643
+ const problem = variantProblem(variant, seen, variantIds);
644
+ if (problem) return problem;
645
+ }
646
+ }
647
+ function checkMetricQuery(metric, query) {
648
+ const breakdown = query.breakdown ?? null;
649
+ if (breakdown !== null && !(metric?.breakdowns ?? []).some((candidate) => candidate.key === breakdown)) throw new WorkspaceError(`\`${breakdown}\` is not a breakdown this metric declares.`);
650
+ for (const [key, values] of Object.entries(query.filters ?? {})) {
651
+ const filter = (metric?.filters ?? []).find((candidate) => candidate.key === key);
652
+ if (!filter || values.some((value) => !filter.values.some((option) => option.value === value))) throw new WorkspaceError(`\`${key}\` has a filter or value this metric doesn't declare.`);
653
+ }
654
+ }
655
+ function parseFilters(pairs) {
656
+ const filters = Object.create(null);
657
+ for (const pair of pairs) {
658
+ const separator = pair.indexOf("=");
659
+ if (separator <= 0 || separator === pair.length - 1) throw new WorkspaceError(`--filter takes key=value, not \`${pair}\`.`);
660
+ const key = pair.slice(0, separator);
661
+ filters[key] = [...filters[key] ?? [], pair.slice(separator + 1)];
662
+ }
663
+ return filters;
664
+ }
665
+ function summarizeSeries(series) {
666
+ const groups = /* @__PURE__ */ new Map();
667
+ for (const point of series.points) {
668
+ const breakdown = point.breakdown ?? null;
669
+ groups.set(breakdown, [...groups.get(breakdown) ?? [], point]);
670
+ }
671
+ return [...groups.entries()].map(([breakdown, points]) => {
672
+ const latest = points.reduce((best, point) => Date.parse(point.t) > Date.parse(best.t) ? point : best);
673
+ return {
674
+ name: breakdown ?? "All",
675
+ breakdown,
676
+ points: points.length,
677
+ sum: points.reduce((total, point) => total + point.value, 0),
678
+ lastAt: latest.t,
679
+ last: latest.value
680
+ };
681
+ });
682
+ }
683
+
684
+ //#endregion
685
+ export { WORKSPACE_HEADER_PREFIX as C, WORKSPACE_COMPATIBILITY_DATE as S, METRIC_LIMITS as _, summarizeSeries as a, READOUT_LIMITS as b, defaultRange as c, resolveWranglerPackage as d, API_HOST as f, ENTRYPOINT_HEADER as g, DRAFT_MODULE_MAX_BYTES as h, seriesProblem as i, parseContextJson as l, CONTEXT_HEADER as m, parseFilters as n, SLOTS as o, BRIDGE_PROTOCOL as p, readoutProblem as r, buildContext as s, checkMetricQuery as t, bundleWorkspace as u, MOUNT_LOAD_TIMEOUT_MS as v, isInternalPath as w, TRIGGER_HEADER as x, PLATFORM_HOST as y };