usebecky 0.0.0-stage → 0.2.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 (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
@@ -0,0 +1,718 @@
1
+ // `npx usebecky config <pull|push>`: the project's settings as one file in git, usebecky/config.json.
2
+ //
3
+ // config pull writes the project's settings to usebecky/config.json (secrets are never written)
4
+ // config push [--dry-run] applies the file: only what it names, nothing it leaves out (no bucket, product or
5
+ // provider is ever deleted). --dry-run lists the changes and changes nothing.
6
+ //
7
+ // Sections (each optional): auth (site URL, redirect URLs, sign-in methods and providers), captcha, emails (sender,
8
+ // languages, texts of the built-in emails), storage (buckets
9
+ // with their access presets), realtime (tables), analytics (on/off, goals, allowed hosts, switches), payments
10
+ // (products and prices). A secret is written as "${NAME}": push reads NAME from the environment or the app's
11
+ // .env.local / .env. Together with `db push` (the schema) and `functions deploy`, a project can be rebuilt from git.
12
+ //
13
+ // Server side: the dashboard's own routes (/platform/v1/projects/:ref/...). Guide: docs/guide/guides/project-config.md.
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { parseEnv } from "./framework.js";
17
+ import { c } from "./ui.js";
18
+ export const CONFIG_FILE = path.join('usebecky', 'config.json');
19
+ const HELP = `
20
+ ${c.bold('npx usebecky config')}: the project's settings as one file in git, ${c.cyan('usebecky/config.json')}
21
+
22
+ ${c.cyan('config pull')} Write the project's settings to the file (secrets are never written)
23
+ ${c.cyan('config push')} Apply the file to the project: only what it names, nothing is deleted
24
+ ${c.cyan('config push --dry-run')} Show what would change, change nothing
25
+
26
+ Sections: auth (site_url, redirect_urls, email_password, magic_link, providers.google…), captcha, emails (from_name,
27
+ reply_to, default_locale, locales, templates.signup.de {subject, body, …}), storage.buckets
28
+ (public, file_size_limit, allowed_mime_types, presets: public_read | user_folder | authenticated_read |
29
+ authenticated_upload), realtime.tables, analytics (enabled, goals, allowed_hosts…), payments.products (with prices).
30
+ A secret is written as "\${GOOGLE_CLIENT_SECRET}": push reads it from the environment or .env.local / .env.
31
+
32
+ Options: --project <ref>, --dry-run, --force (pull: replace a changed file), -y (don't ask)
33
+ `;
34
+ /** What a config file may contain. */
35
+ const SECTIONS = ['auth', 'captcha', 'emails', 'storage', 'realtime', 'analytics', 'payments'];
36
+ /** emails: the sender and languages (PATCH /auth/emails/settings), and texts of the built-in emails per language. */
37
+ const EMAIL_SETTING_KEYS = ['from_name', 'from_email', 'reply_to', 'default_locale', 'locales'];
38
+ const EMAIL_CONTENT_KEYS = ['subject', 'heading', 'body', 'button_text', 'footer'];
39
+ const LOCALE_RE = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
40
+ const AUTH_KEYS = ['site_url', 'redirect_urls', 'signup_enabled', 'email_password', 'magic_link', 'mfa', 'jwt_expiry_seconds', 'app_name', 'providers', 'passkeys', 'phone', 'anonymous'];
41
+ const CAPTCHA_KEYS = ['enabled', 'provider', 'site_key', 'secret', 'features'];
42
+ const BUCKET_KEYS = ['public', 'file_size_limit', 'allowed_mime_types', 'presets'];
43
+ const PRESETS = ['public_read', 'user_folder', 'authenticated_read', 'authenticated_upload'];
44
+ const ANALYTICS_KEYS = [
45
+ 'enabled',
46
+ 'collect_country',
47
+ 'collect_city',
48
+ 'collect_language',
49
+ 'collect_utm',
50
+ 'remember_visitors',
51
+ 'track_scroll',
52
+ 'track_outbound',
53
+ 'track_downloads',
54
+ 'track_search',
55
+ 'track_404',
56
+ 'weekly_report',
57
+ 'traffic_alerts',
58
+ 'goals',
59
+ 'allowed_hosts',
60
+ 'download_extensions',
61
+ 'search_params',
62
+ 'consent_source',
63
+ ];
64
+ const PRODUCT_KEYS = ['name', 'description', 'type', 'features', 'image_url', 'shipping', 'active', 'download', 'prices'];
65
+ const PRICE_KEYS = ['amount', 'currency', 'interval', 'trial_days', 'name', 'sku', 'stock'];
66
+ /** Provider fields that are secrets: always sent when the file has them (their stored value can't be read back). */
67
+ const SECRET_FIELDS = ['client_secret', 'secret'];
68
+ // ---- Small helpers ----------------------------------------------------------------------------------------------
69
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
70
+ /** Deep equality for JSON values (arrays in order, objects by key). */
71
+ export function same(a, b) {
72
+ if (a === b)
73
+ return true;
74
+ if ((a === null || a === undefined) && (b === null || b === undefined))
75
+ return true;
76
+ if (Array.isArray(a) || Array.isArray(b))
77
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => same(x, b[i]));
78
+ if (isObj(a) && isObj(b)) {
79
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
80
+ return [...keys].every((k) => same(a[k], b[k]));
81
+ }
82
+ return false;
83
+ }
84
+ /** Does the project already have what the file asks for? Only the keys the file names count, also inside lists (goals
85
+ * written without an id); null and missing are the same. */
86
+ export function matches(want, have) {
87
+ if (want === have)
88
+ return true;
89
+ if ((want === null || want === undefined) && (have === null || have === undefined))
90
+ return true;
91
+ if (Array.isArray(want))
92
+ return Array.isArray(have) && want.length === have.length && want.every((x, i) => matches(x, have[i]));
93
+ if (isObj(want))
94
+ return isObj(have) && Object.keys(want).every((k) => matches(want[k], have[k]));
95
+ return false;
96
+ }
97
+ /** Only the keys of `want` the project doesn't have yet (secrets always: their stored value can't be read back). */
98
+ function changedKeys(want, have) {
99
+ return Object.keys(want).filter((k) => SECRET_FIELDS.includes(k) || !matches(want[k], have?.[k]));
100
+ }
101
+ function pickKeys(v, keys) {
102
+ const out = {};
103
+ if (!isObj(v))
104
+ return out;
105
+ for (const k of keys)
106
+ if (k in v)
107
+ out[k] = v[k];
108
+ return out;
109
+ }
110
+ const show = (v) => {
111
+ if (v === undefined || v === null)
112
+ return c.dim('none');
113
+ const s = typeof v === 'string' ? v : JSON.stringify(v);
114
+ return s.length > 60 ? `${s.slice(0, 57)}…` : s;
115
+ };
116
+ const ENV_REF = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
117
+ /** The values for "${NAME}": the environment first, then the app's .env.local and .env. A value there is one line, so a
118
+ * key file (Apple's .p8) is written with \n for its line breaks, like dotenv does: they become real ones here. */
119
+ function envLookup(ctx) {
120
+ const files = [];
121
+ for (const f of ['.env.local', '.env']) {
122
+ const p = path.join(ctx.cwd, f);
123
+ if (fs.existsSync(p))
124
+ files.push(parseEnv(fs.readFileSync(p, 'utf8')));
125
+ }
126
+ return (name) => ctx.env[name] ?? files.find((f) => f[name] !== undefined)?.[name]?.replace(/\\n/g, '\n');
127
+ }
128
+ /** Replace every "${NAME}" string; the names without a value are collected in `missing`. */
129
+ export function resolveEnv(v, lookup, missing) {
130
+ if (typeof v === 'string') {
131
+ const m = ENV_REF.exec(v);
132
+ if (!m)
133
+ return v;
134
+ const value = lookup(m[1]);
135
+ if (value === undefined || value === '')
136
+ missing.add(m[1]);
137
+ return value;
138
+ }
139
+ if (Array.isArray(v))
140
+ return v.map((x) => resolveEnv(x, lookup, missing));
141
+ if (isObj(v))
142
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, resolveEnv(x, lookup, missing)]));
143
+ return v;
144
+ }
145
+ /** Secrets the file takes from the environment, by path (for "from $NAME" in the plan). */
146
+ function envNames(v, at = '', out = new Map()) {
147
+ if (typeof v === 'string') {
148
+ const m = ENV_REF.exec(v);
149
+ if (m)
150
+ out.set(at, m[1]);
151
+ }
152
+ else if (isObj(v))
153
+ for (const [k, x] of Object.entries(v))
154
+ envNames(x, at ? `${at}.${k}` : k, out);
155
+ return out;
156
+ }
157
+ class ConfigError extends Error {
158
+ hint;
159
+ constructor(message, hint) {
160
+ super(message);
161
+ this.hint = hint;
162
+ }
163
+ }
164
+ function onlyKeys(v, allowed, where) {
165
+ for (const k of Object.keys(v)) {
166
+ if (!allowed.includes(k))
167
+ throw new ConfigError(`Unknown setting "${where}${k}" in ${CONFIG_FILE}.`, `Settings here: ${allowed.join(', ')}.`);
168
+ }
169
+ }
170
+ function needObj(v, where) {
171
+ if (!isObj(v))
172
+ throw new ConfigError(`"${where}" in ${CONFIG_FILE} must be an object.`);
173
+ return v;
174
+ }
175
+ /** Check the file's shape before anything is read or changed (the server checks the values). */
176
+ export function validateConfig(file) {
177
+ const cfg = needObj(file, 'the file');
178
+ for (const k of Object.keys(cfg)) {
179
+ if (k === '$schema')
180
+ continue;
181
+ if (!SECTIONS.includes(k))
182
+ throw new ConfigError(`Unknown section "${k}" in ${CONFIG_FILE}.`, `Sections: ${SECTIONS.join(', ')}.`);
183
+ needObj(cfg[k], k);
184
+ }
185
+ if (cfg.auth) {
186
+ onlyKeys(cfg.auth, AUTH_KEYS, 'auth.');
187
+ if (cfg.auth.providers !== undefined)
188
+ for (const [name, p] of Object.entries(needObj(cfg.auth.providers, 'auth.providers')))
189
+ needObj(p, `auth.providers.${name}`);
190
+ }
191
+ if (cfg.captcha)
192
+ onlyKeys(cfg.captcha, CAPTCHA_KEYS, 'captcha.');
193
+ if (cfg.storage) {
194
+ onlyKeys(cfg.storage, ['buckets'], 'storage.');
195
+ for (const [id, b] of Object.entries(needObj(cfg.storage.buckets ?? {}, 'storage.buckets'))) {
196
+ onlyKeys(needObj(b, `storage.buckets.${id}`), BUCKET_KEYS, `storage.buckets.${id}.`);
197
+ for (const p of b.presets ?? []) {
198
+ if (!PRESETS.includes(p))
199
+ throw new ConfigError(`Unknown preset "${p}" for bucket "${id}".`, `Presets: ${PRESETS.join(', ')}.`);
200
+ }
201
+ }
202
+ }
203
+ if (cfg.realtime) {
204
+ onlyKeys(cfg.realtime, ['tables'], 'realtime.');
205
+ if (!Array.isArray(cfg.realtime.tables ?? []) || (cfg.realtime.tables ?? []).some((t) => typeof t !== 'string'))
206
+ throw new ConfigError('"realtime.tables" must be a list of table names, like ["messages"].');
207
+ }
208
+ if (cfg.analytics)
209
+ onlyKeys(cfg.analytics, ANALYTICS_KEYS, 'analytics.');
210
+ if (cfg.emails) {
211
+ onlyKeys(cfg.emails, [...EMAIL_SETTING_KEYS, 'templates'], 'emails.');
212
+ for (const [id, tpl] of Object.entries(needObj(cfg.emails.templates ?? {}, 'emails.templates'))) {
213
+ for (const [k, v] of Object.entries(needObj(tpl, `emails.templates.${id}`))) {
214
+ if (k === 'enabled')
215
+ continue;
216
+ if (!LOCALE_RE.test(k))
217
+ throw new ConfigError(`"emails.templates.${id}.${k}" is not a language code.`, 'Write each language\'s text under its code, like "en" or "de": {"subject": …, "body": …}. Or "enabled" (welcome).');
218
+ onlyKeys(needObj(v, `emails.templates.${id}.${k}`), EMAIL_CONTENT_KEYS, `emails.templates.${id}.${k}.`);
219
+ }
220
+ }
221
+ }
222
+ if (cfg.payments) {
223
+ onlyKeys(cfg.payments, ['products'], 'payments.');
224
+ for (const [key, p] of Object.entries(needObj(cfg.payments.products ?? {}, 'payments.products'))) {
225
+ onlyKeys(needObj(p, `payments.products.${key}`), PRODUCT_KEYS, `payments.products.${key}.`);
226
+ for (const [pk, price] of Object.entries(needObj(p.prices ?? {}, `payments.products.${key}.prices`))) {
227
+ onlyKeys(needObj(price, `payments.products.${key}.prices.${pk}`), PRICE_KEYS, `payments.products.${key}.prices.${pk}.`);
228
+ }
229
+ }
230
+ }
231
+ return cfg;
232
+ }
233
+ // ---- Reading the project ----------------------------------------------------------------------------------------
234
+ /** One section's current state, or null when this server has no such module (404) — then the section is skipped. */
235
+ async function load(ctx, p) {
236
+ const r = await ctx.api('GET', p);
237
+ if (r.error?.status === 404 && r.error.code === 'route_not_found')
238
+ return null;
239
+ if (r.error)
240
+ throw r.error;
241
+ return r.data;
242
+ }
243
+ /** Presets whose policies are on the bucket (storage/policies.ts names them "<bucket>: …"). */
244
+ export function presetsOf(bucket, policies) {
245
+ const names = new Set(policies.map((p) => p.name));
246
+ const has = (s) => names.has(`${bucket}: ${s}`);
247
+ const out = [];
248
+ if (has('public read'))
249
+ out.push('public_read');
250
+ if (['select', 'insert', 'update', 'delete'].every((op) => has(`own folder ${op}`)))
251
+ out.push('user_folder');
252
+ if (has('authenticated read'))
253
+ out.push('authenticated_read');
254
+ if (has('authenticated upload'))
255
+ out.push('authenticated_upload');
256
+ return out;
257
+ }
258
+ /** The settings as stored: GET answers consent_source "auto" with what it means right now (manual or cmp). */
259
+ function analyticsView(s) {
260
+ return s && s.consent_source_auto === true ? { ...s, consent_source: 'auto' } : s;
261
+ }
262
+ const productPrices = (p) => Object.fromEntries((p.prices ?? []).filter((x) => x.active !== false).map((x) => [x.key, x]));
263
+ /** Every change the file asks for, against what the project has now. `cfg` has its secrets resolved; `raw` is the file
264
+ * as written (for "from $NAME"). */
265
+ export async function planConfig(ctx, cfg, raw) {
266
+ const plan = { steps: [], untouched: [], skipped: [], notes: [] };
267
+ const fromEnv = envNames(raw);
268
+ const secretLine = (at) => `${at.split('.').slice(-1)[0]}: set${fromEnv.has(at) ? ` from $${fromEnv.get(at)}` : ''} ${c.dim('(a secret: always sent)')}`;
269
+ if (cfg.auth) {
270
+ const cur = await load(ctx, '/auth/config');
271
+ if (!cur)
272
+ plan.skipped.push('auth');
273
+ else {
274
+ const body = {};
275
+ const lines = [];
276
+ for (const k of Object.keys(cfg.auth)) {
277
+ if (k === 'providers') {
278
+ for (const [name, want] of Object.entries(cfg.auth.providers)) {
279
+ const have = cur.providers?.[name];
280
+ const keys = changedKeys(want, have);
281
+ if (!keys.length)
282
+ continue;
283
+ body.providers ??= {};
284
+ body.providers[name] = pickKeys(want, keys);
285
+ for (const f of keys)
286
+ lines.push(SECRET_FIELDS.includes(f) ? `providers.${name}.${secretLine(`auth.providers.${name}.${f}`)}` : `providers.${name}.${f}: ${show(have?.[f])} → ${show(want[f])}`);
287
+ }
288
+ }
289
+ else if (isObj(cfg.auth[k])) {
290
+ const keys = changedKeys(cfg.auth[k], cur[k]);
291
+ if (!keys.length)
292
+ continue;
293
+ body[k] = cfg.auth[k];
294
+ for (const f of keys)
295
+ lines.push(`${k}.${f}: ${show(cur[k]?.[f])} → ${show(cfg.auth[k][f])}`);
296
+ }
297
+ else if (!same(cfg.auth[k], cur[k])) {
298
+ body[k] = cfg.auth[k];
299
+ lines.push(Array.isArray(cfg.auth[k]) ? listChange(k, cur[k] ?? [], cfg.auth[k]) : `${k}: ${show(cur[k])} → ${show(cfg.auth[k])}`);
300
+ }
301
+ }
302
+ if (lines.length)
303
+ plan.steps.push({ section: 'auth', lines, method: 'PATCH', path: '/auth/config', body });
304
+ }
305
+ }
306
+ if (cfg.captcha) {
307
+ const cur = await load(ctx, '/auth/captcha');
308
+ if (!cur)
309
+ plan.skipped.push('captcha');
310
+ else {
311
+ const keys = changedKeys(cfg.captcha, cur);
312
+ if (keys.length) {
313
+ plan.steps.push({
314
+ section: 'captcha',
315
+ lines: keys.map((k) => (SECRET_FIELDS.includes(k) ? secretLine(`captcha.${k}`) : `${k}: ${show(cur[k])} → ${show(cfg.captcha[k])}`)),
316
+ method: 'PATCH',
317
+ path: '/auth/captcha',
318
+ body: pickKeys(cfg.captcha, keys),
319
+ });
320
+ }
321
+ }
322
+ }
323
+ if (cfg.emails) {
324
+ const cur = await load(ctx, '/auth/emails');
325
+ if (!cur)
326
+ plan.skipped.push('emails');
327
+ else {
328
+ // The sender and languages first: a new language has to be on before its texts are saved.
329
+ const settings = pickKeys(cfg.emails, EMAIL_SETTING_KEYS);
330
+ const keys = changedKeys(settings, cur.settings);
331
+ if (keys.length)
332
+ plan.steps.push({ section: 'emails', lines: keys.map((k) => `${k}: ${show(cur.settings?.[k])} → ${show(settings[k])}`), method: 'PATCH', path: '/auth/emails/settings', body: pickKeys(settings, keys) });
333
+ for (const [id, tpl] of Object.entries((cfg.emails.templates ?? {}))) {
334
+ const have = cur.templates?.find((x) => x.id === id);
335
+ if (!have)
336
+ throw new ConfigError(`There is no email "${id}" (emails.templates).`, `Emails: ${(cur.templates ?? []).map((x) => x.id).join(', ')}.`);
337
+ if (tpl.enabled !== undefined && tpl.enabled !== have.enabled) {
338
+ plan.steps.push({ section: 'emails', lines: [`${id}: ${tpl.enabled ? 'send it' : 'don’t send it'}`], method: 'PUT', path: `/auth/emails/templates/${encodeURIComponent(id)}`, body: { enabled: tpl.enabled } });
339
+ }
340
+ for (const [locale, content] of Object.entries(tpl)) {
341
+ if (locale === 'enabled')
342
+ continue;
343
+ const now = have.translations?.[locale]?.content;
344
+ const changed = changedKeys(content, now);
345
+ if (changed.length)
346
+ plan.steps.push({ section: 'emails', lines: [`${id} (${locale}): ${changed.join(', ')}`], method: 'PUT', path: `/auth/emails/templates/${encodeURIComponent(id)}?locale=${encodeURIComponent(locale)}`, body: content });
347
+ }
348
+ }
349
+ }
350
+ }
351
+ if (cfg.storage) {
352
+ const cur = await load(ctx, '/storage/buckets');
353
+ if (!cur)
354
+ plan.skipped.push('storage');
355
+ else {
356
+ const want = (cfg.storage.buckets ?? {});
357
+ for (const b of cur)
358
+ if (!(b.id in want))
359
+ plan.untouched.push(`bucket ${b.id}`);
360
+ for (const [id, b] of Object.entries(want)) {
361
+ const have = cur.find((x) => x.id === id);
362
+ const fields = pickKeys(b, ['public', 'file_size_limit', 'allowed_mime_types']);
363
+ if (!have) {
364
+ plan.steps.push({ section: 'storage', lines: [`create bucket ${id} (${b.public ? 'public' : 'private'})`], method: 'POST', path: '/storage/buckets', body: { id, public: false, ...fields } });
365
+ }
366
+ else {
367
+ const keys = changedKeys(fields, have);
368
+ if (keys.length)
369
+ plan.steps.push({ section: 'storage', lines: keys.map((k) => `bucket ${id} ${k}: ${show(have[k])} → ${show(fields[k])}`), method: 'PATCH', path: `/storage/buckets/${encodeURIComponent(id)}`, body: pickKeys(fields, keys) });
370
+ }
371
+ const applied = have ? presetsOf(id, (await load(ctx, `/storage/buckets/${encodeURIComponent(id)}/policies`)) ?? []) : [];
372
+ for (const preset of (b.presets ?? [])) {
373
+ if (!applied.includes(preset))
374
+ plan.steps.push({ section: 'storage', lines: [`bucket ${id}: add access preset ${preset}`], method: 'POST', path: `/storage/buckets/${encodeURIComponent(id)}/policies`, body: { preset } });
375
+ }
376
+ for (const preset of applied)
377
+ if (b.presets && !b.presets.includes(preset))
378
+ plan.untouched.push(`preset ${preset} on bucket ${id}`);
379
+ }
380
+ }
381
+ }
382
+ if (cfg.realtime) {
383
+ const cur = await load(ctx, '/realtime/tables');
384
+ if (!cur)
385
+ plan.skipped.push('realtime');
386
+ else {
387
+ const on = new Set(cur.filter((t) => t.enabled).map((t) => t.table));
388
+ const want = (cfg.realtime.tables ?? []);
389
+ for (const table of want)
390
+ if (!on.has(table))
391
+ plan.steps.push({ section: 'realtime', lines: [`turn on realtime for ${table}`], method: 'POST', path: '/realtime/tables', body: { table } });
392
+ for (const table of on)
393
+ if (!want.includes(table))
394
+ plan.untouched.push(`realtime on ${table}`);
395
+ }
396
+ }
397
+ if (cfg.analytics) {
398
+ const cur = analyticsView(await load(ctx, '/analytics/settings'));
399
+ if (!cur)
400
+ plan.skipped.push('analytics');
401
+ else {
402
+ const keys = changedKeys(cfg.analytics, cur);
403
+ if (keys.length)
404
+ plan.steps.push({ section: 'analytics', lines: keys.map((k) => `${k}: ${show(cur[k])} → ${show(cfg.analytics[k])}`), method: 'PATCH', path: '/analytics/settings', body: pickKeys(cfg.analytics, keys) });
405
+ }
406
+ }
407
+ if (cfg.payments) {
408
+ const cur = await load(ctx, '/payments/products');
409
+ if (!cur)
410
+ plan.skipped.push('payments');
411
+ else {
412
+ const want = (cfg.payments.products ?? {});
413
+ for (const p of cur)
414
+ if (!(p.key in want) && p.active !== false)
415
+ plan.untouched.push(`product ${p.key}`);
416
+ for (const [key, p] of Object.entries(want)) {
417
+ // Currencies are stored lowercase ("EUR" is "eur").
418
+ const prices = Object.entries((p.prices ?? {})).map(([pk, x]) => ({ key: pk, ...x, ...(typeof x.currency === 'string' ? { currency: x.currency.toLowerCase() } : {}) }));
419
+ const fields = pickKeys(p, PRODUCT_KEYS.filter((k) => k !== 'prices'));
420
+ const have = cur.find((x) => x.key === key);
421
+ if (!have) {
422
+ if (p.type !== 'subscription' && p.type !== 'one_time')
423
+ throw new ConfigError(`Product "${key}" needs "type": "subscription" or "one_time" in ${CONFIG_FILE}.`, 'A product’s type is set when it is created and can’t change later.');
424
+ plan.steps.push({
425
+ section: 'payments',
426
+ lines: [`create product ${key} (${p.type}) with ${prices.length} price${prices.length === 1 ? '' : 's'}: ${prices.map((x) => x.key).join(', ') || c.dim('none')}`],
427
+ method: 'POST',
428
+ path: '/payments/products',
429
+ body: { key, ...fields, prices },
430
+ });
431
+ continue;
432
+ }
433
+ if (have.active === false && p.active === undefined)
434
+ plan.notes.push(`Product ${key} is archived: add "active": true to sell it again.`);
435
+ const keys = changedKeys(fields, have);
436
+ const havePrices = productPrices(have);
437
+ // Stock only counts for a new price: sales lower it on the project, so the file's number would undo them.
438
+ const changedPrices = prices
439
+ .filter((x) => !havePrices[x.key] || changedKeys(pickKeys(x, PRICE_KEYS.filter((k) => k !== 'stock')), havePrices[x.key]).length)
440
+ .map((x) => (havePrices[x.key] ? Object.fromEntries(Object.entries(x).filter(([k]) => k !== 'stock')) : x));
441
+ for (const x of prices) {
442
+ if (havePrices[x.key] && x.stock !== undefined && !matches(x.stock, havePrices[x.key].stock))
443
+ plan.notes.push(`Stock of ${x.key} is left at ${show(havePrices[x.key].stock)}: sales change it, so change it in the dashboard (Payments → Products).`);
444
+ }
445
+ const lines = keys.map((k) => `product ${key} ${k}: ${show(have[k])} → ${show(fields[k])}`);
446
+ for (const x of changedPrices) {
447
+ const old = havePrices[x.key];
448
+ lines.push(old ? `product ${key} price ${x.key}: ${priceText(old)} → ${priceText({ ...old, ...x })}${x.amount !== undefined && x.amount !== old.amount ? c.dim(' (a new Stripe price; the old one is archived, running subscriptions keep it)') : ''}` : `product ${key}: add price ${x.key} (${priceText(x)})`);
449
+ }
450
+ for (const pk of Object.keys(havePrices))
451
+ if (!prices.some((x) => x.key === pk))
452
+ plan.untouched.push(`price ${pk} of product ${key}`);
453
+ if (lines.length) {
454
+ plan.steps.push({
455
+ section: 'payments',
456
+ lines,
457
+ method: 'PATCH',
458
+ path: `/payments/products/${encodeURIComponent(have.id)}`,
459
+ body: { ...pickKeys(fields, keys), ...(changedPrices.length ? { prices: changedPrices.map((x) => ({ ...pickKeys(havePrices[x.key], ['amount', 'currency', 'interval', 'trial_days']), ...x })) } : {}) },
460
+ });
461
+ }
462
+ }
463
+ }
464
+ }
465
+ return plan;
466
+ }
467
+ function priceText(p) {
468
+ const amount = typeof p.amount === 'number' ? (p.amount / 100).toFixed(2) : '?';
469
+ return `${amount} ${String(p.currency ?? '').toUpperCase()}${p.interval ? ` / ${p.interval}` : ' once'}`;
470
+ }
471
+ function listChange(k, have, want) {
472
+ const added = want.filter((x) => !have.some((y) => same(x, y)));
473
+ const removed = have.filter((x) => !want.some((y) => same(x, y)));
474
+ const parts = [...added.map((x) => c.green(`+ ${show(x)}`)), ...removed.map((x) => c.red(`- ${show(x)}`))];
475
+ return `${k}: ${parts.length ? parts.join(', ') : 'new order'}`;
476
+ }
477
+ // ---- pull -------------------------------------------------------------------------------------------------------
478
+ /** The project's settings as a config file (secrets left out). */
479
+ export async function readProjectConfig(ctx) {
480
+ const config = {};
481
+ const skipped = [];
482
+ const secrets = [];
483
+ const auth = await load(ctx, '/auth/config');
484
+ if (!auth)
485
+ skipped.push('auth');
486
+ else {
487
+ const out = pickKeys(auth, ['site_url', 'redirect_urls', 'signup_enabled', 'email_password', 'magic_link', 'mfa', 'jwt_expiry_seconds']);
488
+ const providers = {};
489
+ for (const [name, p] of Object.entries((auth.providers ?? {}))) {
490
+ if (!p.enabled && !p.client_id)
491
+ continue;
492
+ const { client_secret: _secret, has_client_secret, ...rest } = p;
493
+ for (const [k, v] of Object.entries(rest))
494
+ if (Array.isArray(v) && !v.length)
495
+ delete rest[k];
496
+ if (has_client_secret)
497
+ secrets.push(`auth.providers.${name}.client_secret`);
498
+ providers[name] = rest;
499
+ }
500
+ if (Object.keys(providers).length)
501
+ out.providers = providers;
502
+ if (auth.passkeys?.enabled)
503
+ out.passkeys = pickKeys(auth.passkeys, ['enabled', 'rp_id', 'origins']);
504
+ config.auth = out;
505
+ }
506
+ const captcha = await load(ctx, '/auth/captcha');
507
+ if (!captcha)
508
+ skipped.push('captcha');
509
+ else {
510
+ config.captcha = captcha.enabled || captcha.provider ? pickKeys(captcha, ['enabled', 'provider', 'site_key', 'features']) : { enabled: false };
511
+ if (captcha.secret_set)
512
+ secrets.push('captcha.secret');
513
+ }
514
+ const emails = await load(ctx, '/auth/emails');
515
+ if (!emails)
516
+ skipped.push('emails');
517
+ else {
518
+ const out = {};
519
+ for (const k of EMAIL_SETTING_KEYS)
520
+ if (emails.settings?.[k] !== null && emails.settings?.[k] !== undefined)
521
+ out[k] = emails.settings[k];
522
+ // Only the texts written for this project (the built-in ones change with usebecky's releases).
523
+ const templates = {};
524
+ for (const tpl of (emails.templates ?? [])) {
525
+ const entry = {};
526
+ if (tpl.can_disable && tpl.enabled)
527
+ entry.enabled = true;
528
+ for (const [locale, tr] of Object.entries((tpl.translations ?? {})))
529
+ if (tr?.customized)
530
+ entry[locale] = pickKeys(tr.content, EMAIL_CONTENT_KEYS);
531
+ if (Object.keys(entry).length)
532
+ templates[tpl.id] = entry;
533
+ }
534
+ if (Object.keys(templates).length)
535
+ out.templates = templates;
536
+ config.emails = out;
537
+ }
538
+ const buckets = await load(ctx, '/storage/buckets');
539
+ if (!buckets)
540
+ skipped.push('storage');
541
+ else {
542
+ const out = {};
543
+ for (const b of buckets) {
544
+ const policies = (await load(ctx, `/storage/buckets/${encodeURIComponent(b.id)}/policies`)) ?? [];
545
+ out[b.id] = { public: !!b.public, file_size_limit: b.file_size_limit ?? null, allowed_mime_types: b.allowed_mime_types ?? null, presets: presetsOf(b.id, policies) };
546
+ }
547
+ config.storage = { buckets: out };
548
+ }
549
+ const tables = await load(ctx, '/realtime/tables');
550
+ if (!tables)
551
+ skipped.push('realtime');
552
+ else
553
+ config.realtime = { tables: tables.filter((t) => t.enabled).map((t) => t.table) };
554
+ const analytics = analyticsView(await load(ctx, '/analytics/settings'));
555
+ if (!analytics)
556
+ skipped.push('analytics');
557
+ else
558
+ config.analytics = pickKeys(analytics, ANALYTICS_KEYS);
559
+ const products = await load(ctx, '/payments/products');
560
+ if (!products)
561
+ skipped.push('payments');
562
+ else {
563
+ const out = {};
564
+ for (const p of products) {
565
+ if (p.active === false)
566
+ continue;
567
+ const fields = pickKeys(p, ['name', 'description', 'type', 'features', 'image_url', 'shipping', 'download']);
568
+ for (const k of ['description', 'image_url', 'download'])
569
+ if (fields[k] === null)
570
+ delete fields[k];
571
+ if (fields.shipping === false)
572
+ delete fields.shipping;
573
+ const prices = {};
574
+ for (const [pk, x] of Object.entries(productPrices(p))) {
575
+ const price = pickKeys(x, ['amount', 'currency', 'interval', 'trial_days', 'name']);
576
+ if (price.interval === null)
577
+ delete price.interval;
578
+ if (!price.trial_days)
579
+ delete price.trial_days;
580
+ if (price.name === null)
581
+ delete price.name;
582
+ prices[pk] = price;
583
+ }
584
+ out[p.key] = { ...fields, prices };
585
+ }
586
+ config.payments = { products: out };
587
+ }
588
+ return { config, skipped, secrets };
589
+ }
590
+ async function pull(ctx) {
591
+ const { ui } = ctx;
592
+ const { config, skipped, secrets } = await readProjectConfig(ctx);
593
+ const text = JSON.stringify(config, null, 2) + '\n';
594
+ const file = path.join(ctx.cwd, CONFIG_FILE);
595
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
596
+ if (existing === text) {
597
+ ui.success(`${CONFIG_FILE} already matches project ${ctx.ref}.`);
598
+ return 0;
599
+ }
600
+ if (existing !== null && !ctx.force) {
601
+ if (ctx.yes) {
602
+ ui.error(`${CONFIG_FILE} has other settings than the project.`);
603
+ ui.write(` ${c.dim('Run `npx usebecky config push --dry-run` to see them, or `config pull --force` to replace the file.')}`);
604
+ return 1;
605
+ }
606
+ if (!(await ui.confirm(`Replace ${CONFIG_FILE} with the project's settings? Secrets written as \${NAME} are lost.`, false)))
607
+ return 1;
608
+ }
609
+ fs.mkdirSync(path.dirname(file), { recursive: true });
610
+ fs.writeFileSync(file, text);
611
+ ui.success(`Wrote ${c.bold(CONFIG_FILE)} from project ${ctx.ref}.`);
612
+ if (skipped.length)
613
+ ui.write(c.dim(` Not on this server: ${skipped.join(', ')}.`));
614
+ if (secrets.length) {
615
+ ui.write(c.dim(` Secrets are never written. To set them from the file, add for example`));
616
+ ui.write(c.dim(` "client_secret": "\${GOOGLE_CLIENT_SECRET}" and keep the value in .env (${secrets.join(', ')} ${secrets.length === 1 ? 'is' : 'are'} set now).`));
617
+ }
618
+ ui.write(c.dim(' Commit it. `npx usebecky config push` applies it to a project.'));
619
+ return 0;
620
+ }
621
+ // ---- push -------------------------------------------------------------------------------------------------------
622
+ async function push(ctx) {
623
+ const { ui } = ctx;
624
+ const file = path.join(ctx.cwd, CONFIG_FILE);
625
+ if (!fs.existsSync(file)) {
626
+ ui.error(`There is no ${CONFIG_FILE} yet.`);
627
+ ui.write(` ${c.dim('Write the project’s settings to it first: npx usebecky config pull')}`);
628
+ return 1;
629
+ }
630
+ let raw;
631
+ try {
632
+ raw = validateConfig(JSON.parse(fs.readFileSync(file, 'utf8')));
633
+ }
634
+ catch (e) {
635
+ if (e instanceof SyntaxError)
636
+ return ctx.printError({ message: `${CONFIG_FILE} is not valid JSON: ${e.message}` });
637
+ throw e;
638
+ }
639
+ const missing = new Set();
640
+ const cfg = resolveEnv(raw, envLookup(ctx), missing);
641
+ if (missing.size) {
642
+ ui.error(`No value for ${[...missing].map((n) => `$${n}`).join(', ')} (named in ${CONFIG_FILE}).`);
643
+ ui.write(` ${c.dim('Set it in the environment or in .env / .env.local. Nothing was changed.')}`);
644
+ return 1;
645
+ }
646
+ const plan = await planConfig(ctx, cfg, raw);
647
+ if (plan.skipped.length)
648
+ ui.warn(`Not on this server, skipped: ${plan.skipped.join(', ')}.`);
649
+ for (const note of plan.notes)
650
+ ui.warn(note);
651
+ if (!plan.steps.length) {
652
+ ui.success(`Project ${ctx.ref} already has the settings in ${CONFIG_FILE}.`);
653
+ untouched(ui, plan);
654
+ return 0;
655
+ }
656
+ const count = plan.steps.reduce((n, s) => n + s.lines.length, 0);
657
+ ui.write(`${ctx.dryRun ? 'Would change' : 'Changes'} (${count}):`);
658
+ for (const s of plan.steps)
659
+ for (const [i, line] of s.lines.entries())
660
+ ui.write(` ${i === 0 ? c.cyan(s.section.padEnd(10)) : ' '.repeat(10)} ${line}`);
661
+ untouched(ui, plan);
662
+ if (ctx.dryRun) {
663
+ ui.write('');
664
+ ui.success('Nothing was changed (--dry-run).');
665
+ return 0;
666
+ }
667
+ if (!ctx.yes && !(await ui.confirm(`Apply ${count === 1 ? 'it' : `these ${count} changes`} to project ${ctx.ref}?`, true)))
668
+ return 1;
669
+ ui.write('');
670
+ for (const [i, s] of plan.steps.entries()) {
671
+ const r = await ctx.api(s.method, s.path, s.body);
672
+ if (r.error) {
673
+ ui.error(`${s.section}: ${s.lines[0]}`);
674
+ ctx.printError(r.error);
675
+ if (i)
676
+ ui.write(c.dim(` ${i} change${i === 1 ? ' was' : 's were'} applied before this one. Fix the file and push again: the rest follows.`));
677
+ return 1;
678
+ }
679
+ ui.success(`${s.section}: ${s.lines.length === 1 ? s.lines[0] : `${s.lines.length} settings`}`);
680
+ }
681
+ ui.write('');
682
+ ui.success(`Project ${ctx.ref} has the settings in ${CONFIG_FILE}.`);
683
+ return 0;
684
+ }
685
+ function untouched(ui, plan) {
686
+ if (!plan.untouched.length)
687
+ return;
688
+ const list = plan.untouched.slice(0, 8).join(', ') + (plan.untouched.length > 8 ? ` and ${plan.untouched.length - 8} more` : '');
689
+ ui.write(c.dim(` Not in the file, left as they are: ${list}.`));
690
+ }
691
+ export async function configCommand(ctx) {
692
+ const { ui } = ctx;
693
+ const sub = ctx.args[0];
694
+ if (!sub || sub === 'help') {
695
+ ui.write(HELP);
696
+ return sub ? 0 : 1;
697
+ }
698
+ if (sub !== 'pull' && sub !== 'push') {
699
+ ui.error(`Unknown command "config ${sub}".`);
700
+ ui.write(HELP);
701
+ return 1;
702
+ }
703
+ if (!ctx.ref)
704
+ return ctx.noProject();
705
+ if (!(await ctx.signIn()))
706
+ return 1;
707
+ ui.write(`\n${c.bold(c.magenta('usebecky'))} ${c.dim(`config ${sub}`)} ${c.dim(`(project ${ctx.ref})`)}\n`);
708
+ try {
709
+ return sub === 'pull' ? await pull(ctx) : await push(ctx);
710
+ }
711
+ catch (e) {
712
+ if (e instanceof ConfigError)
713
+ return ctx.printError({ message: e.message, hint: e.hint });
714
+ if (e && typeof e === 'object' && 'message' in e && 'code' in e)
715
+ return ctx.printError(e);
716
+ throw e;
717
+ }
718
+ }