@milesroxas/design-hub 0.12.0 → 0.14.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 (92) hide show
  1. package/README.md +5 -5
  2. package/core/prototype.test.ts +12 -1
  3. package/core/prototype.ts +21 -2
  4. package/core/review/model.ts +71 -6
  5. package/core/review/service.test.ts +575 -39
  6. package/core/review/service.ts +452 -25
  7. package/core/review/store.ts +47 -6
  8. package/core/review/suite-kv.ts +17 -0
  9. package/dist/core/prototype.d.ts +20 -2
  10. package/dist/core/prototype.js +17 -2
  11. package/dist/core/review/model.d.ts +42 -3
  12. package/dist/core/review/model.js +52 -3
  13. package/dist/core/review/service.d.ts +81 -7
  14. package/dist/core/review/service.js +407 -23
  15. package/dist/core/review/store.d.ts +29 -2
  16. package/dist/core/review/store.js +6 -2
  17. package/dist/core/review/suite-kv.d.ts +7 -0
  18. package/dist/core/review/suite-kv.js +12 -0
  19. package/dist/scripts/client.d.ts +1 -1
  20. package/dist/scripts/client.js +4 -4
  21. package/dist/scripts/lib/cli.js +5 -0
  22. package/dist/scripts/lib/dns.d.ts +16 -2
  23. package/dist/scripts/lib/dns.js +66 -3
  24. package/dist/scripts/lib/fake-host.d.ts +17 -3
  25. package/dist/scripts/lib/fake-host.js +56 -10
  26. package/dist/scripts/lib/host.d.ts +15 -25
  27. package/dist/scripts/lib/host.js +15 -324
  28. package/dist/scripts/lib/resend.d.ts +36 -0
  29. package/dist/scripts/lib/resend.js +66 -0
  30. package/dist/scripts/lib/studio-deps.d.ts +23 -0
  31. package/dist/scripts/lib/studio-deps.js +46 -16
  32. package/dist/scripts/lib/studios.d.ts +16 -6
  33. package/dist/scripts/lib/studios.js +28 -10
  34. package/dist/scripts/lib/vercel-host.d.ts +17 -0
  35. package/dist/scripts/lib/vercel-host.js +416 -0
  36. package/dist/scripts/people.d.ts +16 -4
  37. package/dist/scripts/people.js +67 -17
  38. package/dist/scripts/share.js +3 -2
  39. package/dist/scripts/studio.d.ts +26 -4
  40. package/dist/scripts/studio.js +364 -19
  41. package/dist/server/api.d.ts +20 -7
  42. package/dist/server/api.js +83 -27
  43. package/dist/server/dev.js +21 -1
  44. package/dist/server/gate.d.ts +120 -0
  45. package/dist/server/gate.js +808 -0
  46. package/dist/server/mailer.d.ts +60 -0
  47. package/dist/server/mailer.js +104 -0
  48. package/dist/server/mailers/fake.d.ts +8 -0
  49. package/dist/server/mailers/fake.js +16 -0
  50. package/dist/server/mailers/resend.d.ts +21 -0
  51. package/dist/server/mailers/resend.js +49 -0
  52. package/dist/server/mark.d.ts +17 -0
  53. package/dist/server/mark.js +46 -1
  54. package/dist/server/session.d.ts +2 -1
  55. package/dist/server/session.js +6 -3
  56. package/dist/server/stores/backends.d.ts +22 -0
  57. package/dist/server/stores/backends.js +96 -0
  58. package/dist/server/{fake-upstash.js → stores/fake-upstash.js} +1 -1
  59. package/dist/server/stores/index.d.ts +41 -0
  60. package/dist/server/stores/index.js +63 -0
  61. package/dist/server/stores/pglite.d.ts +16 -0
  62. package/dist/server/stores/pglite.js +98 -0
  63. package/dist/server/stores/postgres.d.ts +63 -0
  64. package/dist/server/stores/postgres.js +153 -0
  65. package/dist/server/{upstash.d.ts → stores/upstash.d.ts} +1 -1
  66. package/dist/vercel/files.js +1 -1
  67. package/dist/vercel/proxy.d.ts +6 -82
  68. package/dist/vercel/proxy.js +24 -524
  69. package/dist/vite/plugin.js +4 -2
  70. package/kit/ui/Menu.tsx +29 -18
  71. package/kit/ui/layer.ts +41 -0
  72. package/package.json +3 -1
  73. package/shell/review/Bar.tsx +1 -0
  74. package/shell/review/Card.tsx +17 -7
  75. package/shell/review/People.tsx +908 -134
  76. package/shell/review/Review.tsx +2 -2
  77. package/shell/review/anchor.ts +6 -1
  78. package/shell/review/client.ts +41 -7
  79. package/shell/review/menu-place.test.ts +41 -0
  80. package/shell/review/place.test.ts +26 -1
  81. package/shell/review/place.ts +17 -0
  82. package/shell/review/review.css +97 -11
  83. package/shell/review/view.test.ts +115 -1
  84. package/shell/review/view.ts +92 -2
  85. package/shell/studio/StudioHub.tsx +1 -0
  86. package/shell/studio/hub.css +99 -13
  87. package/skills/miles-deploy/SKILL.md +26 -4
  88. package/templates/studio/.env.example +9 -0
  89. package/templates/studio/README.md +13 -0
  90. package/templates/studio/package.json +1 -1
  91. /package/dist/server/{fake-upstash.d.ts → stores/fake-upstash.d.ts} +0 -0
  92. /package/dist/server/{upstash.js → stores/upstash.js} +0 -0
@@ -1,20 +1,5 @@
1
- /// <reference types="node" />
2
- // The host port: what the studio commands ask of the account that runs the
3
- // studio site. One adapter, Vercel, through its CLI. Every call names the
4
- // studio's team (`--scope`), so no command ever acts in whichever team the CLI
5
- // last switched to. A call that acts through the folder's link (deploy, env,
6
- // the stores) runs only once the link is the studio's project in that team,
7
- // and the CLI never sees the env vars that would pick another. No call prints
8
- // a value: secrets go in on stdin and come back only into the folder's `.env`.
9
- import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
10
- import { tmpdir } from 'node:os';
11
- import { join } from 'node:path';
12
- import { hostName, proofPath } from '../../core/prototype.js';
13
- import { readEnv } from '../../server/env.js';
14
1
  import { CliError } from './cli.js';
15
- import { upstashTerms } from './deploy.js';
16
- import { BLOB_NAME, STORE_NAMES } from './studios.js';
17
- import { vercel } from './vercel.js';
2
+ import { vercelHost } from './vercel-host.js';
18
3
  /**
19
4
  * Deploys the studio site and then puts every older deployment out of reach,
20
5
  * since a request can name a deployment by its id and be served by that
@@ -51,312 +36,18 @@ export async function deployAlone(host) {
51
36
  });
52
37
  return { deployment: live.id, removed: older };
53
38
  }
54
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
55
- const HTTPS_TRIES = 20;
56
- const HTTPS_GAP_MS = 3000;
57
- /**
58
- * A DELETE through `vercel api`. The CLI (59.x) asks before every DELETE and,
59
- * with no terminal (as every design-hub command runs), refuses one unless it is
60
- * told to skip that question. Only the two removals send it, each on a path
61
- * built from a checked deployment id or host. `vercel remove` is not used: it
62
- * also looks its argument up as a project and deletes any project it matches.
63
- * No CLI command takes one host off one project (`vercel domains rm` takes the
64
- * domain off the whole team).
65
- */
66
- const DELETE = ['-X', 'DELETE', '--dangerously-skip-permissions'];
67
- const DEPLOYMENT_ID = /^dpl_[A-Za-z0-9]+$/;
68
- /** A Marketplace resource's name, as `vercel integration resource connect` takes it. */
69
- const RESOURCE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
70
- /** What the Marketplace answers a plan the team cannot have (studios-findings.md, section 5). */
71
- const NO_FREE_PLAN = /billing plan not found|plan[^\n]*not (found|available)/i;
72
- /** The env vars the Vercel CLI (59.x) reads to pick a project or team over the folder's link and `--scope`. */
73
- export const PICKERS = [
74
- 'VERCEL_ORG_ID',
75
- 'VERCEL_PROJECT_ID',
76
- 'NOW_ORG_ID',
77
- 'NOW_PROJECT_ID',
78
- 'VERCEL_TEAM_ID',
79
- ];
80
- /** The caller's env without the names that would send a studio command to another project or team. */
81
- function studioCliEnv(env) {
82
- const out = { ...env };
83
- for (const name of PICKERS)
84
- delete out[name];
85
- return out;
86
- }
87
- const studioCli = (cwd, args, input) => vercel(cwd, args, input, studioCliEnv(process.env));
88
- /** The ids `.vercel/project.json` links the folder to, or none when it is missing or unreadable. */
89
- function linkOf(dir) {
90
- try {
91
- return JSON.parse(readFileSync(join(dir, '.vercel', 'project.json'), 'utf8'));
92
- }
93
- catch {
94
- return {};
95
- }
96
- }
97
- /** The Vercel adapter. Every call goes through `call`, which adds `--scope <team>`. */
98
- export function vercelHost({ dir, team, project, run = studioCli, fetcher = fetch, wait = sleep, }) {
99
- const call = (args, input) => {
100
- const out = run(dir, [...args, '--scope', team], input);
101
- if (!out)
102
- throw new CliError('The Vercel CLI is not installed.', {
103
- fix: 'npm i -g vercel, then design-hub signin.',
104
- });
105
- return out;
106
- };
107
- const must = (args, input) => {
108
- const out = call(args, input);
109
- if (out.status !== 0)
110
- throw failed(args, out);
111
- return out.stdout;
112
- };
113
- const api = async (path, method = 'GET', fields = []) => {
114
- const verb = method === 'GET' ? [] : method === 'DELETE' ? DELETE : ['-X', method];
115
- const args = ['api', path, '--raw', ...verb];
116
- const out = call([...args, ...fields.flatMap((f) => ['-F', f])]);
117
- if (out.status !== 0) {
118
- if (/\b404\b|not[_ ]found/i.test(`${out.stdout}\n${out.stderr}`))
119
- return null;
120
- throw failed(['api', method, path], out);
121
- }
122
- return out.stdout.trim() ? JSON.parse(out.stdout) : {};
123
- };
124
- /** The studio's project on its team, as ids, or null when the team has none of that name. */
125
- const studioProject = async () => {
126
- const found = await api(`/v9/projects/${encodeURIComponent(project)}`);
127
- return found ? { id: found.id, org: found.accountId } : null;
128
- };
129
- /** Whether `.vercel/project.json` is that project, in that team, by id: a name alone can be another team's. */
130
- const linkedTo = (want) => {
131
- const have = linkOf(dir);
132
- return (!!want &&
133
- typeof want.id === 'string' &&
134
- typeof want.org === 'string' &&
135
- have.projectId === want.id &&
136
- have.orgId === want.org);
137
- };
138
- /** A call the CLI sends wherever the folder is linked: refused, before it runs, unless that is the studio. */
139
- const linked = async (args, input) => {
140
- if (!linkedTo(await studioProject()))
141
- throw new CliError(`The studio folder is not linked to project ${project} in team ${team}; nothing was changed.`, {
142
- dir,
143
- fix: `design-hub studio link --dir ${dir}, then run this again.`,
144
- });
145
- return call(args, input);
146
- };
147
- const linkedMust = async (args, input) => {
148
- const out = await linked(args, input);
149
- if (out.status !== 0)
150
- throw failed(args, out);
151
- return out.stdout;
152
- };
153
- const names = async () => new Set([...(await linkedMust(['env', 'ls', 'production'])).matchAll(/^\s*([A-Z][A-Z0-9_]*)\s/gm)].map((m) => m[1]));
154
- const domainPath = (host) => `/v9/projects/${encodeURIComponent(project)}/domains/${encodeURIComponent(host)}`;
155
- return {
156
- async link(create) {
157
- const want = await studioProject();
158
- if (linkedTo(want))
159
- return 'kept';
160
- if (create && want)
161
- throw new CliError(`Team ${team} already has a project named ${project}.`, {
162
- fix: 'Pick another --project, or run design-hub studio link on the folder that made it.',
163
- });
164
- if (!create && !want)
165
- throw new CliError(`Team ${team} has no project named ${project}.`, {
166
- fix: 'Check vercel.team and vercel.project in studio.json.',
167
- });
168
- if (create)
169
- must(['project', 'add', project]);
170
- must(['link', '--yes', '--project', project]);
171
- if (!linkedTo(await studioProject()))
172
- throw new CliError(`vercel link did not link the studio folder to project ${project} in team ${team}.`, {
173
- dir,
174
- fix: `Delete ${join(dir, '.vercel')}, then run this again.`,
175
- });
176
- return create ? 'created' : 'linked';
177
- },
178
- async hasEnv(name) {
179
- return (await names()).has(name);
180
- },
181
- async setSecret(name, value) {
182
- if ((await names()).has(name))
183
- return 'kept';
184
- await linkedMust(['env', 'add', name, 'production', '--sensitive', '--yes'], value);
185
- return 'set';
186
- },
187
- async pullEnv(wanted) {
188
- const tmp = mkdtempSync(join(tmpdir(), 'studio-env-'));
189
- try {
190
- await linkedMust(['env', 'pull', join(tmp, '.env'), '--environment=production', '--yes']);
191
- const pulled = readEnv(tmp);
192
- return Object.fromEntries(wanted.filter((n) => pulled[n]).map((n) => [n, pulled[n]]));
193
- }
194
- finally {
195
- rmSync(tmp, { recursive: true, force: true });
196
- }
197
- },
198
- async provisionDatabase(existing) {
199
- const have = await names();
200
- if (STORE_NAMES.every((n) => have.has(n)))
201
- return 'kept';
202
- if (existing !== undefined) {
203
- if (!RESOURCE_NAME.test(existing))
204
- throw new CliError('--database takes the name of a database the team has.', { got: existing });
205
- const out = await linked(['integration', 'resource', 'connect', existing, project, '--yes']);
206
- if (out.status !== 0)
207
- throw new CliError(`Could not connect the database ${existing} to the studio project.`, {
208
- stderr: out.stderr.trim().slice(-600),
209
- fix: `Check the name on team ${team}'s Storage page on Vercel, then run this again.`,
210
- });
211
- return 'connected';
212
- }
213
- // Only ever the free plan: a team without one is refused by the Marketplace, and nothing is bought.
214
- const args = [
215
- 'integration',
216
- 'add',
217
- 'upstash/upstash-kv',
218
- '--name',
219
- `${project}-review`,
220
- '--plan',
221
- 'free',
222
- ];
223
- const out = await linked([...args, '-e', 'production', '--no-env-pull']);
224
- if (out.status !== 0) {
225
- if (NO_FREE_PLAN.test(out.stderr))
226
- throw new CliError(`Team ${team} cannot have a free review store (Upstash for Redis); nothing was bought.`, {
227
- stderr: out.stderr.trim().slice(-600),
228
- fix: `A team gets one free database from the Marketplace, and a database serves one studio only: never connect one another studio uses. If team ${team} has a database no studio uses (its Storage page on Vercel), run this again with --database <its name>; else give this studio a team or an Upstash account of its own.`,
229
- });
230
- const terms = upstashTerms(out.stderr, team);
231
- throw new CliError('Could not add the review store (Upstash for Redis) to the studio project.', {
232
- stderr: out.stderr.trim().slice(-600),
233
- terms: terms.url,
234
- fix: `Most often the team has not accepted the Upstash terms. Tell the user, word for word: "${terms.say}" Then run this again; or connect a database the team has that no studio uses with --database <its name>.`,
235
- });
236
- }
237
- return 'created';
238
- },
239
- async disconnectDatabase(name) {
240
- if (!RESOURCE_NAME.test(name))
241
- return false;
242
- const out = await linked(['integration', 'resource', 'disconnect', name, project, '--yes']);
243
- if (out.status !== 0)
244
- return false;
245
- const have = await names();
246
- return !STORE_NAMES.some((n) => have.has(n));
247
- },
248
- async provisionFiles(region) {
249
- if ((await names()).has(BLOB_NAME))
250
- return 'kept';
251
- await linkedMust([
252
- 'blob',
253
- 'create-store',
254
- `${project}-files`,
255
- '--access',
256
- 'private',
257
- '--region',
258
- region,
259
- '--yes',
260
- ]);
261
- return 'created';
262
- },
263
- async addDomain(host) {
264
- const existing = await api(domainPath(host));
265
- const state = existing === null
266
- ? await api(`/v10/projects/${encodeURIComponent(project)}/domains`, 'POST', [`name=${host}`])
267
- : existing.verified
268
- ? existing
269
- : await api(`${domainPath(host)}/verify`, 'POST');
270
- return {
271
- verified: state?.verified === true,
272
- verification: state?.verification ?? existing?.verification ?? [],
273
- };
274
- },
275
- async removeDomain(host) {
276
- if (hostName(host) !== host)
277
- throw new CliError(`${host} is not a host name; no domain was removed.`);
278
- if ((await api(domainPath(host))) === null)
279
- return 'absent';
280
- await api(domainPath(host), 'DELETE');
281
- return 'removed';
282
- },
283
- async recordFor(host) {
284
- const config = await api(`/v6/domains/${encodeURIComponent(host)}/config?projectIdOrName=${encodeURIComponent(project)}`);
285
- return cnameTarget(config);
286
- },
287
- async reaches(host, proof) {
288
- for (let i = 0; i < HTTPS_TRIES; i++) {
289
- if (await answers(fetcher, host, proof))
290
- return true;
291
- await wait(HTTPS_GAP_MS);
292
- }
293
- return false;
294
- },
295
- async deploy() {
296
- const out = await linked(['deploy', '--prod', '--yes']);
297
- const url = `${out.stdout}\n${out.stderr}`.match(/https:\/\/([\w.-]+\.vercel\.app)/)?.[1];
298
- if (out.status !== 0 || !url)
299
- throw failed(['deploy', '--prod'], out);
300
- const found = await api(`/v13/deployments/${encodeURIComponent(url)}`);
301
- if (!found?.id)
302
- throw new CliError('The new deployment could not be read back.', {
303
- fix: 'Run design-hub studio deploy again.',
304
- });
305
- return { id: String(found.id), state: String(found.readyState ?? found.status ?? '') };
306
- },
307
- async deployments() {
308
- const all = [];
309
- let until = '';
310
- do {
311
- const page = await api(`/v6/deployments?projectId=${encodeURIComponent(project)}&limit=100${until ? `&until=${until}` : ''}`);
312
- for (const d of (page?.deployments ?? []))
313
- all.push({ id: d.uid, state: String(d.state ?? d.readyState ?? '') });
314
- until = page?.pagination?.next ? String(page.pagination.next) : '';
315
- } while (until);
316
- return all;
317
- },
318
- async removeDeployment(id) {
319
- if (!DEPLOYMENT_ID.test(id))
320
- throw new CliError(`${id} is not a deployment id; nothing was removed.`);
321
- const out = call(['api', `/v13/deployments/${id}`, '--raw', ...DELETE]);
322
- if (out.status !== 0)
323
- throw new CliError(`Vercel would not delete the older deployment ${id}.`, {
324
- stderr: out.stderr.trim().slice(-600),
325
- fix: 'Delete it in the project’s Deployments page on Vercel, then run design-hub studio deploy again.',
326
- });
327
- },
328
- };
329
- }
330
- function failed(args, out) {
331
- return new CliError(`vercel ${args.slice(0, 2).join(' ')} failed.`, {
332
- stderr: out.stderr.trim().slice(-600),
333
- fix: /log ?in|credentials|token|not authorized/i.test(out.stderr)
334
- ? 'design-hub signin, send the user its url, then run this again.'
335
- : undefined,
336
- });
337
- }
338
- /** Vercel's first-ranked CNAME for a host, without its trailing dot. */
339
- export function cnameTarget(config) {
340
- const ranked = (config?.recommendedCNAME ?? [])
341
- .slice()
342
- .sort((a, b) => a.rank - b.rank);
343
- const value = ranked[0]?.value?.replace(/\.$/, '').toLowerCase();
344
- if (!value)
345
- throw new CliError('Vercel named no record for this host.', { fix: 'Run this again in a minute.' });
346
- return value;
347
- }
348
- /**
349
- * A host answers from this studio's site: asked the proof's path over HTTPS,
350
- * it sends back the proof's answer, which only the gate reading this studio's
351
- * store has. Any other answer, whatever its status or headers, is another
352
- * server's, or a site that does not know the client yet.
353
- */
354
- async function answers(fetcher, host, { ask, answer }) {
355
- try {
356
- const res = await fetcher(`https://${host}${proofPath(ask)}`, { redirect: 'manual' });
357
- return res.status === 200 && (await res.text()) === answer;
358
- }
359
- catch {
360
- return false;
361
- }
39
+ /** Every host adapter, by the name studio.json gives it in `providers.host`. */
40
+ const HOSTS = {
41
+ vercel: (dir, { vercel }) => vercelHost({ dir, team: vercel.team, project: vercel.project }),
42
+ };
43
+ /** The host adapter a studio names, or a refusal that names the ones there are. */
44
+ export function hostFor(dir, config, hosts = HOSTS) {
45
+ const name = config.providers?.host;
46
+ const make = typeof name === 'string' && Object.hasOwn(hosts, name) ? hosts[name] : undefined;
47
+ if (!make)
48
+ throw new CliError(`Studio ${config.slug} names ${JSON.stringify(name)} as its host, which Design Hub has no adapter for; nothing was changed.`, {
49
+ hosts: Object.keys(hosts),
50
+ fix: `Set providers.host in ${dir}/studio.json to one of: ${Object.keys(hosts).join(', ')}.`,
51
+ });
52
+ return make(dir, config);
362
53
  }
@@ -0,0 +1,36 @@
1
+ export type ResendRecord = {
2
+ record?: string;
3
+ name: string;
4
+ type: string;
5
+ value: string;
6
+ priority?: number;
7
+ };
8
+ export type ResendDomain = {
9
+ id: string;
10
+ name: string;
11
+ status: string;
12
+ records?: ResendRecord[];
13
+ };
14
+ export type ResendKey = {
15
+ id: string;
16
+ name: string;
17
+ };
18
+ export type ResendAccount = {
19
+ domains(): Promise<ResendDomain[]>;
20
+ domain(id: string): Promise<ResendDomain>;
21
+ /** Makes a domain; Resend answers it with its records. Made twice is refused (403), so read `domains` first. */
22
+ createDomain(name: string): Promise<ResendDomain>;
23
+ /** Starts Resend's check of the domain's records; its answer says nothing of the result. */
24
+ verify(id: string): Promise<void>;
25
+ keys(): Promise<ResendKey[]>;
26
+ /** A key that can only send, and only from this domain. Its token is in this answer alone. */
27
+ createKey(name: string, domain: string): Promise<{
28
+ id: string;
29
+ token: string;
30
+ }>;
31
+ deleteKey(id: string): Promise<void>;
32
+ };
33
+ export declare function resendAccount({ key, fetcher }: {
34
+ key: string;
35
+ fetcher: typeof fetch;
36
+ }): ResendAccount;
@@ -0,0 +1,66 @@
1
+ /// <reference types="node" />
2
+ // Resend's account API, as `studio email` uses it with the full key: the
3
+ // domains, their DNS records and verification, and the send-only keys
4
+ // (email-findings.md, a, b, c and f). Every request is `fetch` with the key
5
+ // in the Authorization header alone; no error here repeats it. Sending is
6
+ // not here: the test mail goes through the site's own adapter
7
+ // (server/mailers/resend.ts), with the send-only key the site gets.
8
+ import { CliError } from './cli.js';
9
+ const API = 'https://api.resend.com';
10
+ const TIMEOUT_MS = 15_000;
11
+ /** What to do about a refusal, by its status: a key that is not a full one, or anything else. */
12
+ const fixFor = (status) => status === 401 || status === 403
13
+ ? 'The key in RESEND_FULL_KEY was refused: make a full-access key at resend.com/api-keys, put it in a file, and run this again with --resend-key-file <file>.'
14
+ : 'Run this again in a minute. If it stops here again, read the message: it is Resend’s.';
15
+ export function resendAccount({ key, fetcher }) {
16
+ async function call(method, path, body) {
17
+ const what = `${method} ${path}`;
18
+ let res;
19
+ try {
20
+ res = await fetcher(`${API}${path}`, {
21
+ method,
22
+ headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
23
+ ...(body ? { body: JSON.stringify(body) } : {}),
24
+ signal: AbortSignal.timeout(TIMEOUT_MS),
25
+ });
26
+ }
27
+ catch {
28
+ throw new CliError(`Resend did not answer ${what}.`, {
29
+ fix: 'Check the network, then run this again.',
30
+ });
31
+ }
32
+ const json = (await res.json().catch(() => null));
33
+ if (!res.ok)
34
+ throw new CliError(`Resend refused ${what} (${res.status}).`, {
35
+ status: res.status,
36
+ message: typeof json?.message === 'string' ? json.message : null,
37
+ fix: fixFor(res.status),
38
+ });
39
+ return (json ?? {});
40
+ }
41
+ const id = (value) => encodeURIComponent(value);
42
+ return {
43
+ domains: async () => (await call('GET', '/domains')).data ?? [],
44
+ domain: (domain) => call('GET', `/domains/${id(domain)}`),
45
+ createDomain: (name) => call('POST', '/domains', { name }),
46
+ verify: async (domain) => {
47
+ await call('POST', `/domains/${id(domain)}/verify`);
48
+ },
49
+ keys: async () => (await call('GET', '/api-keys')).data ?? [],
50
+ async createKey(name, domain) {
51
+ const made = await call('POST', '/api-keys', {
52
+ name,
53
+ permission: 'sending_access',
54
+ domain_id: domain,
55
+ });
56
+ if (typeof made.id !== 'string' || typeof made.token !== 'string')
57
+ throw new CliError('Resend made a key but did not answer with it.', {
58
+ fix: 'Run this again: a key this run made is removed by the next run that finishes.',
59
+ });
60
+ return { id: made.id, token: made.token };
61
+ },
62
+ deleteKey: async (key) => {
63
+ await call('DELETE', `/api-keys/${id(key)}`);
64
+ },
65
+ };
66
+ }
@@ -2,6 +2,8 @@ import type { Files } from '../../core/files.ts';
2
2
  import type { Client } from '../../core/review/model.ts';
3
3
  import { type Review } from '../../core/review/service.ts';
4
4
  import type { KV } from '../../core/review/store.ts';
5
+ import { type Mailer } from '../../server/mailer.ts';
6
+ import { type StoreChoice } from '../../server/stores/index.ts';
5
7
  import { type Dns } from './dns.ts';
6
8
  import { type Host } from './host.ts';
7
9
  import { type Names } from './names.ts';
@@ -18,12 +20,27 @@ export type StudioDeps = {
18
20
  names: Names;
19
21
  /** The studio's review store, as its `.env` names it, unchecked: a command opens it with openReview. */
20
22
  store(studio: Studio): KV;
23
+ /** Makes what the review store needs before its first write (Postgres: its table); for `studio create`. */
24
+ prepareStore(studio: Studio): Promise<void>;
21
25
  /** The review service's clock; tests move it. */
22
26
  now?: () => Date;
27
+ /** The studio's file store, unchecked: a command that writes or removes files opens it with openFiles. */
23
28
  files(studio: Studio): Files;
24
29
  /** pnpm with these arguments in the studio folder, its output captured; null when pnpm is missing. */
25
30
  pnpm(dir: string, args: string[]): Run | null;
31
+ /** The studio's mailer, by the site's own rule (chooseMailer) on the studio's `.env`: null without its mail key and sender. */
32
+ mailer(studio: Studio): Mailer | null;
33
+ /** How `studio email` reaches Resend's API; tests hand a Resend from memory. */
34
+ fetcher: typeof fetch;
35
+ /** A pause between two looks at something that takes time (a domain's verification); tests skip it. */
36
+ wait(ms: number): Promise<unknown>;
26
37
  };
38
+ /**
39
+ * The review store a studio's `.env` names, by the one rule the site uses
40
+ * (chooseStore), and only when it is the kind studio.json says: a folder
41
+ * whose `.env` names none, two, or the other kind is refused, never guessed.
42
+ */
43
+ export declare function studioStore({ dir, config }: Studio): StoreChoice;
27
44
  export declare function realDeps(): StudioDeps;
28
45
  /**
29
46
  * The studio's review service, once its database is shown to be this
@@ -31,5 +48,11 @@ export declare function realDeps(): StudioDeps;
31
48
  * people and links, so none can act on another studio's.
32
49
  */
33
50
  export declare function openReview(deps: StudioDeps, studio: Studio): Promise<Review>;
51
+ /**
52
+ * The studio's file store, once its mark shows it is this studio's, or once
53
+ * it is marked so when it had none (claimFiles): the way a command that
54
+ * writes or removes files reaches the store.
55
+ */
56
+ export declare function openFiles(deps: StudioDeps, studio: Studio): Promise<Files>;
34
57
  /** The client's record, or null when the studio has none; a store that does not answer is an error, never "none". */
35
58
  export declare const recordOf: (review: Review, slug: string) => Promise<Client | null>;
@@ -1,31 +1,52 @@
1
1
  /// <reference types="node" />
2
2
  // What the studio and client commands run against, built from a studio's
3
- // folder: its host (Vercel, in its own team), its DNS adapter, its review
4
- // store and its file store, each from the folder's own `.env`, how a host is
5
- // seen to be served by its DNS, and pnpm in the folder. Tests hand the
6
- // commands fakes of the same shape instead. A command reaches the review
7
- // store only through openReview, which first checks that the database is
8
- // this studio's (server/mark.ts).
3
+ // folder: its host (the adapter studio.json names, in its own team), its DNS
4
+ // adapter, its review store (Upstash or Postgres, as studio.json says) and
5
+ // its file store, each from the folder's own `.env`, how a host is seen to
6
+ // be served by its DNS, pnpm in the folder, and the network for Resend's
7
+ // API. Tests hand the commands
8
+ // fakes of the same shape instead. A command reaches the review store only
9
+ // through openReview, and writes or removes files only through openFiles,
10
+ // each of which first checks that the store is this studio's
11
+ // (server/mark.ts).
9
12
  import { spawnSync } from 'node:child_process';
10
13
  import { createReview, ReviewError } from '../../core/review/service.js';
11
14
  import { blobFiles } from '../../server/blob.js';
12
15
  import { readEnv } from '../../server/env.js';
13
16
  import { localStudio } from '../../server/local.js';
14
- import { mustBeOwnDatabase } from '../../server/mark.js';
15
- import { storeConfig, upstashKV } from '../../server/upstash.js';
17
+ import { chooseMailer } from '../../server/mailer.js';
18
+ import { claimFiles, mustBeOwnDatabase } from '../../server/mark.js';
19
+ import { chooseStore } from '../../server/stores/index.js';
16
20
  import { CliError } from './cli.js';
17
21
  import { cloudflareDns, manualDns, wildcardDns } from './dns.js';
18
- import { vercelHost } from './host.js';
22
+ import { hostFor } from './host.js';
19
23
  import { authoritativeNames } from './names.js';
20
24
  import { BLOB_NAME, CLOUDFLARE_NAME, homeDir } from './studios.js';
21
25
  const pull = (dir) => ({
22
26
  fix: `design-hub studio link --dir ${dir} reads it back from the studio's Production env.`,
23
27
  });
28
+ /**
29
+ * The review store a studio's `.env` names, by the one rule the site uses
30
+ * (chooseStore), and only when it is the kind studio.json says: a folder
31
+ * whose `.env` names none, two, or the other kind is refused, never guessed.
32
+ */
33
+ export function studioStore({ dir, config }) {
34
+ const chosen = chooseStore(readEnv(dir));
35
+ if (!chosen)
36
+ throw new CliError("No review store in the studio's .env.", pull(dir));
37
+ if ('error' in chosen)
38
+ throw new CliError(`${chosen.error} Nothing was changed.`, {
39
+ fix: `Keep only the ${config.providers.kv} database's names in ${dir}/.env, and on the site's Production env.`,
40
+ });
41
+ if (chosen.kind !== config.providers.kv)
42
+ throw new CliError(`studio.json says studio ${config.slug}'s database is ${config.providers.kv}, and its .env names a ${chosen.kind} one; nothing was changed.`, { fix: `Put the ${config.providers.kv} database's names in ${dir}/.env in place of the others.` });
43
+ return chosen;
44
+ }
24
45
  export function realDeps() {
25
46
  return {
26
47
  home: homeDir(),
27
48
  cwd: process.cwd(),
28
- host: (dir, { vercel }) => vercelHost({ dir, team: vercel.team, project: vercel.project }),
49
+ host: hostFor,
29
50
  dns({ dir, config }, host) {
30
51
  const target = (h) => host.recordFor(h);
31
52
  if (config.dns.provider === 'vercel')
@@ -40,12 +61,8 @@ export function realDeps() {
40
61
  return cloudflareDns({ token, apex: config.apex, zone: config.dns.zone, studio: config.slug, target });
41
62
  },
42
63
  names: authoritativeNames(),
43
- store({ dir }) {
44
- const store = storeConfig(readEnv(dir));
45
- if (!store)
46
- throw new CliError("No review store in the studio's .env.", pull(dir));
47
- return upstashKV(store);
48
- },
64
+ store: (studio) => studioStore(studio).open(),
65
+ prepareStore: (studio) => studioStore(studio).prepare(),
49
66
  files({ dir }) {
50
67
  const token = readEnv(dir)[BLOB_NAME];
51
68
  if (!token)
@@ -59,6 +76,9 @@ export function realDeps() {
59
76
  return null;
60
77
  return { status: out.status ?? 1, stdout: out.stdout ?? '', stderr: out.stderr ?? '' };
61
78
  },
79
+ mailer: ({ dir }) => chooseMailer(readEnv(dir)),
80
+ fetcher: (input, init) => fetch(input, init),
81
+ wait: (ms) => new Promise((r) => setTimeout(r, ms)),
62
82
  };
63
83
  }
64
84
  /**
@@ -71,6 +91,16 @@ export async function openReview(deps, studio) {
71
91
  await mustBeOwnDatabase(kv, studio);
72
92
  return createReview(kv, deps.now ? { now: deps.now } : {});
73
93
  }
94
+ /**
95
+ * The studio's file store, once its mark shows it is this studio's, or once
96
+ * it is marked so when it had none (claimFiles): the way a command that
97
+ * writes or removes files reaches the store.
98
+ */
99
+ export async function openFiles(deps, studio) {
100
+ const files = deps.files(studio);
101
+ await claimFiles(files, studio);
102
+ return files;
103
+ }
74
104
  /** The client's record, or null when the studio has none; a store that does not answer is an error, never "none". */
75
105
  export const recordOf = (review, slug) => review.clientRecord({ client: slug }, localStudio('cli', 'CLI')).catch((error) => {
76
106
  if (error instanceof ReviewError && error.code === 'not_found')
@@ -1,3 +1,4 @@
1
+ import type { StoreKind } from '../../server/stores/index.ts';
1
2
  /** Who serves DNS for the apex, and so how a client's host gets its record. */
2
3
  export declare const DNS_PROVIDERS: readonly ['vercel', 'cloudflare', 'manual'];
3
4
  export type DnsProvider = (typeof DNS_PROVIDERS)[number];
@@ -28,15 +29,24 @@ export type StudioConfig = {
28
29
  };
29
30
  /** The first Studio person, who gets the first link, on the studio's own host. */
30
31
  owner: string | null;
32
+ /** The database's kind, chosen at `studio create` (`--kv`), and the host the adapter is picked by (host.ts, hostFor). */
31
33
  providers: {
32
- kv: 'upstash';
34
+ kv: StoreKind;
33
35
  files: 'vercel-blob';
34
- host: 'vercel';
36
+ host: string;
35
37
  };
36
38
  };
37
39
  export declare const STUDIO_FILE = "studio.json";
38
- /** The secrets a studio folder's `.env` holds. Studios share none of them. */
39
- export declare const STORE_NAMES: readonly ['KV_REST_API_URL', 'KV_REST_API_TOKEN'];
40
+ /** The kinds of database a studio can have. */
41
+ export declare const KV_PROVIDERS: readonly ["upstash", "postgres"];
42
+ /**
43
+ * The names a studio's database comes in as, by kind, in its `.env` and the
44
+ * site's env. Studios share none of them. Upstash needs both; Postgres
45
+ * either, since Neon's integration sets both and Supabase's POSTGRES_URL only.
46
+ */
47
+ export declare const STORE_NAMES: Record<StoreKind, readonly string[]>;
48
+ /** Whether the names `has` says are there make a database of this kind. */
49
+ export declare const hasStore: (kind: StoreKind, has: (name: string) => boolean) => boolean;
40
50
  export declare const BLOB_NAME = "BLOB_READ_WRITE_TOKEN";
41
51
  export declare const CLOUDFLARE_NAME = "CLOUDFLARE_API_TOKEN";
42
52
  /** The problems with a studio.json, by path; none for a well-formed one. */
@@ -65,8 +75,8 @@ export declare const studioHost: (apex: string) => string;
65
75
  /**
66
76
  * The host a client is served on: `<slug>.<apex>`, or a codename
67
77
  * (`--host atlas` is `atlas.<apex>`). A client's host is exactly one label
68
- * under the apex, and that label is never studio, www or api, which the
69
- * studio keeps. So the apex itself, a host not under it, and one two labels
78
+ * under the apex, and that label is never studio, www, api or mail, which
79
+ * the studio keeps. So the apex itself, a host not under it, and one two labels
70
80
  * down (`a.studio.<apex>`) are refused.
71
81
  */
72
82
  export declare function clientHost(slug: string, apex: string, given: string | undefined): string;