@milesroxas/design-hub 0.13.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 (67) hide show
  1. package/README.md +1 -1
  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 +536 -1
  6. package/core/review/service.ts +452 -25
  7. package/core/review/store.ts +45 -4
  8. package/dist/core/prototype.d.ts +20 -2
  9. package/dist/core/prototype.js +17 -2
  10. package/dist/core/review/model.d.ts +42 -3
  11. package/dist/core/review/model.js +52 -3
  12. package/dist/core/review/service.d.ts +81 -7
  13. package/dist/core/review/service.js +407 -23
  14. package/dist/core/review/store.d.ts +29 -2
  15. package/dist/core/review/store.js +4 -0
  16. package/dist/scripts/client.d.ts +1 -1
  17. package/dist/scripts/client.js +1 -1
  18. package/dist/scripts/lib/dns.d.ts +16 -2
  19. package/dist/scripts/lib/dns.js +66 -3
  20. package/dist/scripts/lib/fake-host.d.ts +16 -1
  21. package/dist/scripts/lib/fake-host.js +36 -1
  22. package/dist/scripts/lib/host.d.ts +2 -0
  23. package/dist/scripts/lib/resend.d.ts +36 -0
  24. package/dist/scripts/lib/resend.js +66 -0
  25. package/dist/scripts/lib/studio-deps.d.ts +7 -0
  26. package/dist/scripts/lib/studio-deps.js +6 -1
  27. package/dist/scripts/lib/studios.d.ts +2 -2
  28. package/dist/scripts/lib/studios.js +5 -5
  29. package/dist/scripts/lib/vercel-host.js +6 -0
  30. package/dist/scripts/people.d.ts +16 -4
  31. package/dist/scripts/people.js +67 -17
  32. package/dist/scripts/studio.d.ts +19 -3
  33. package/dist/scripts/studio.js +327 -6
  34. package/dist/server/api.d.ts +14 -2
  35. package/dist/server/api.js +71 -17
  36. package/dist/server/dev.js +21 -1
  37. package/dist/server/gate.d.ts +26 -3
  38. package/dist/server/gate.js +323 -52
  39. package/dist/server/mailer.d.ts +60 -0
  40. package/dist/server/mailer.js +104 -0
  41. package/dist/server/mailers/fake.d.ts +8 -0
  42. package/dist/server/mailers/fake.js +16 -0
  43. package/dist/server/mailers/resend.d.ts +21 -0
  44. package/dist/server/mailers/resend.js +49 -0
  45. package/dist/server/session.js +4 -1
  46. package/dist/vercel/proxy.js +10 -3
  47. package/dist/vite/plugin.js +3 -1
  48. package/kit/ui/Menu.tsx +29 -18
  49. package/kit/ui/layer.ts +41 -0
  50. package/package.json +1 -1
  51. package/shell/review/Bar.tsx +1 -0
  52. package/shell/review/Card.tsx +17 -7
  53. package/shell/review/People.tsx +908 -134
  54. package/shell/review/Review.tsx +2 -2
  55. package/shell/review/anchor.ts +6 -1
  56. package/shell/review/client.ts +41 -7
  57. package/shell/review/menu-place.test.ts +41 -0
  58. package/shell/review/place.test.ts +26 -1
  59. package/shell/review/place.ts +17 -0
  60. package/shell/review/review.css +97 -11
  61. package/shell/review/view.test.ts +115 -1
  62. package/shell/review/view.ts +92 -2
  63. package/shell/studio/StudioHub.tsx +1 -0
  64. package/shell/studio/hub.css +99 -13
  65. package/skills/miles-deploy/SKILL.md +24 -3
  66. package/templates/studio/.env.example +6 -0
  67. package/templates/studio/package.json +1 -1
@@ -7,6 +7,8 @@ import { isClientSlug, isProjectSlug } from '../prototype.js';
7
7
  import { LOCAL_CLIENT } from './model.js';
8
8
  /** A comment's or a control's prototype: any kebab-case name, so reading one that is reserved finds nothing, as before. */
9
9
  const isKebab = (v) => typeof v === 'string' && SLUG.test(v);
10
+ /** A minute's number in a key: a whole count, never anything that could hold a `:`. */
11
+ const isCount = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
10
12
  /**
11
13
  * Every key the hub writes starts here, so a shared Redis never mixes it with
12
14
  * another app's data. Bumped when the stored shapes change without a
@@ -32,6 +34,8 @@ function part(ok, v, what) {
32
34
  const clientPrefix = (client) => `${PREFIX}c:${part(isClientSlug, client, 'client')}:`;
33
35
  const projectPrefix = (scope) => `${clientPrefix(scope.client)}p:${part(isProjectSlug, scope.project, 'project')}:`;
34
36
  export function keyOf(scope, name, prototype) {
37
+ if (scope === 'studio' && name === 'hits')
38
+ return `${PREFIX}studio:hits:${part(isCount, prototype, 'minute')}`;
35
39
  if (scope === 'studio')
36
40
  return DIRECTORY.includes(name) ? `${PREFIX}${name}` : `${PREFIX}studio:${name}`;
37
41
  if (!PROJECT_NAMES.includes(name))
@@ -10,7 +10,7 @@ export declare const spec: {
10
10
  readonly description: 'add <slug>: the client, its host and its first person’s link (Studio opens it from studio.<apex>). list: every client, with its host, state and project count. archive <slug>: remove it, its people, projects, comments and files, then its DNS record (only one this studio made) and its host on the site; run it again to finish one that stopped part way. An archived slug or host can be added again two minutes later. access [slug]: read or set (--access) the client’s default access length; without a slug, the studio’s.';
11
11
  }, {
12
12
  readonly name: 'slug';
13
- readonly description: 'The client, kebab-case; never studio, www, api or site.';
13
+ readonly description: 'The client, kebab-case; never studio, www, api, mail or site.';
14
14
  }];
15
15
  readonly flags: {
16
16
  readonly studio: {
@@ -41,7 +41,7 @@ export const spec = {
41
41
  required: true,
42
42
  description: 'add <slug>: the client, its host and its first person’s link (Studio opens it from studio.<apex>). list: every client, with its host, state and project count. archive <slug>: remove it, its people, projects, comments and files, then its DNS record (only one this studio made) and its host on the site; run it again to finish one that stopped part way. An archived slug or host can be added again two minutes later. access [slug]: read or set (--access) the client’s default access length; without a slug, the studio’s.',
43
43
  },
44
- { name: 'slug', description: 'The client, kebab-case; never studio, www, api or site.' },
44
+ { name: 'slug', description: 'The client, kebab-case; never studio, www, api, mail or site.' },
45
45
  ],
46
46
  flags: {
47
47
  studio: { type: 'string', description: 'The studio’s slug. Absent, the studio folder this runs in.' },
@@ -11,11 +11,24 @@ export type Released = {
11
11
  } | {
12
12
  record: string;
13
13
  };
14
+ /** A record a mail domain needs, its name in full (`send.mail.example.com`). */
15
+ export type DnsRecord = {
16
+ type: 'TXT' | 'MX' | 'CNAME';
17
+ name: string;
18
+ value: string;
19
+ priority?: number;
20
+ };
21
+ /** What came of the records: all written, all there already, or each `TYPE name [priority] value` for a person to add. */
22
+ export type Recorded = 'added' | 'exists' | {
23
+ records: string[];
24
+ };
14
25
  export interface Dns {
15
26
  mode: DnsMode;
16
27
  ensure(host: string): Promise<Ensured>;
17
28
  /** Takes the host's record off, once its client is archived: only one this studio made. */
18
29
  release(host: string): Promise<Released>;
30
+ /** Puts these records in the apex's zone, or names them for a person to add. Never overwrites a record. */
31
+ records(wanted: DnsRecord[]): Promise<Recorded>;
19
32
  }
20
33
  /**
21
34
  * How a command that sets up a host says what to do next: `run` is the
@@ -52,11 +65,12 @@ type Target = (host: string) => Promise<string>;
52
65
  /** The wildcard serves every host and stays: nothing to add or remove per host. */
53
66
  export declare const wildcardDns: () => Dns;
54
67
  export declare const manualDns: (target: Target) => Dns;
55
- type DnsRecord = {
68
+ type CfRecord = {
56
69
  id?: string;
57
70
  type: string;
58
71
  name: string;
59
72
  content: string;
73
+ priority?: number;
60
74
  proxied?: boolean;
61
75
  comment?: string | null;
62
76
  };
@@ -66,7 +80,7 @@ type DnsRecord = {
66
80
  * another CNAME, a proxied one) is a person's to change, so it is refused
67
81
  * with what is there, never overwritten.
68
82
  */
69
- export declare function classify(found: DnsRecord[], target: string): 'exists';
83
+ export declare function classify(found: CfRecord[], target: string): 'exists';
70
84
  type CloudflareOptions = {
71
85
  token: string;
72
86
  apex: string;
@@ -1,6 +1,7 @@
1
1
  /// <reference types="node" />
2
- // The DNS port: how a new client's host comes to point at the studio site.
3
- // Three adapters (studios-findings.md, sections 2 and 3):
2
+ // The DNS port: how a new client's host comes to point at the studio site,
3
+ // and how the records a mail domain needs reach the apex's zone (records,
4
+ // for `studio email`). Three adapters (studios-findings.md, sections 2 and 3):
4
5
  //
5
6
  // wildcard Vercel DNS: `*.<apex>` is on the studio project once, at
6
7
  // `studio create`, so every host already resolves; no call.
@@ -10,10 +11,17 @@
10
11
  // manual any other provider: the record, for a person to add, and on
11
12
  // archive, to remove.
12
13
  //
14
+ // A mail domain's records are written by Cloudflare's API alone; Vercel DNS
15
+ // and manual print them for a person to add (email.md, E11: Vercel DNS
16
+ // writes only once a real run there is recorded).
17
+ //
13
18
  // The Cloudflare token edits one zone's DNS. It lives in the studio folder's
14
19
  // gitignored `.env` and is sent only in the Authorization header; no error
15
20
  // here repeats it.
16
21
  import { CliError } from './cli.js';
22
+ /** A wanted record as a person adds it: `MX send.mail.example.com 10 feedback-smtp.example.net`. */
23
+ const recordLine = (r) => [r.type, r.name, ...(r.priority === undefined ? [] : [String(r.priority)]), r.value].join(' ');
24
+ const printed = async (wanted) => ({ records: wanted.map(recordLine) });
17
25
  const cap = (text) => text.charAt(0).toUpperCase() + text.slice(1);
18
26
  /**
19
27
  * Points a host at the studio site: its DNS record and, unless the wildcard
@@ -84,10 +92,11 @@ export const wildcardDns = () => ({
84
92
  mode: 'wildcard',
85
93
  ensure: async () => 'exists',
86
94
  release: async () => ({ removed: [], left: [] }),
95
+ records: printed,
87
96
  });
88
97
  export const manualDns = (target) => {
89
98
  const record = async (host) => ({ record: `CNAME ${host} ${await target(host)}` });
90
- return { mode: 'manual', ensure: record, release: record };
99
+ return { mode: 'manual', ensure: record, release: record, records: printed };
91
100
  };
92
101
  const CF = 'https://api.cloudflare.com/client/v4';
93
102
  /** What Vercel accepts a host pointing at: its own target, or the generic name. */
@@ -118,6 +127,24 @@ export function classify(found, target) {
118
127
  fix: `Point it at ${target} with one DNS-only CNAME at Cloudflare.`,
119
128
  });
120
129
  }
130
+ /** A value as Cloudflare holds it and as Resend gives it, read alike: a TXT without its quotes, any other without its last dot, in lower case. */
131
+ const readValue = (type, value) => type === 'TXT' ? value.replace(/^"(.*)"$/s, '$1') : bare(value);
132
+ /** The record at the name is the wanted one: its type, its value and, for an MX, its priority. */
133
+ const same = (want, have) => have.type === want.type &&
134
+ readValue(have.type, have.content) === readValue(want.type, want.value) &&
135
+ (want.type !== 'MX' || have.priority === want.priority);
136
+ /** A record the wanted one would stand beside wrongly: another of its type, a CNAME, or anything where a CNAME is wanted. */
137
+ const clashes = (want, have) => !same(want, have) && (want.type === 'CNAME' || have.type === 'CNAME' || have.type === want.type);
138
+ /** A mail record as Cloudflare takes it (email-findings.md, b): automatic TTL, a TXT in quotes, DNS-only, marked with the studio. */
139
+ const cfBody = (r, studio) => ({
140
+ type: r.type,
141
+ name: r.name,
142
+ content: r.type === 'TXT' ? `"${r.value}"` : r.value,
143
+ ttl: 1,
144
+ ...(r.priority === undefined ? {} : { priority: r.priority }),
145
+ ...(r.type === 'CNAME' ? { proxied: false } : {}),
146
+ comment: madeBy(studio),
147
+ });
121
148
  export function cloudflareDns({ token, apex, zone, studio, target, fetcher = fetch, }) {
122
149
  async function cf(path, init = {}) {
123
150
  const res = await fetcher(`${CF}${path}`, {
@@ -205,5 +232,41 @@ export function cloudflareDns({ token, apex, zone, studio, target, fetcher = fet
205
232
  }
206
233
  return { removed, left: found.filter((r) => !ours(r)).map(shown) };
207
234
  },
235
+ /**
236
+ * Adds each wanted record the zone lacks, after every name is looked up.
237
+ * A name holding a record that differs (another of the type, or a CNAME)
238
+ * stops it before anything is written: that record is a person's to
239
+ * change, never overwritten here, even one this studio made.
240
+ */
241
+ async records(wanted) {
242
+ const id = await zoneId();
243
+ const found = new Map();
244
+ for (const name of new Set(wanted.map((w) => bare(w.name))))
245
+ found.set(name, await look(id, name));
246
+ const at = (w) => found.get(bare(w.name)) ?? [];
247
+ const clashing = new Set(wanted.flatMap((w) => at(w)
248
+ .filter((h) => clashes(w, h))
249
+ .map(shown)));
250
+ if (clashing.size)
251
+ throw new CliError('The mail domain already has DNS records that differ from what Resend asks for; nothing was changed.', {
252
+ found: [...clashing],
253
+ wanted: wanted.map(recordLine),
254
+ fix: 'Remove those records at Cloudflare, or send from another domain under the apex, then run this again.',
255
+ });
256
+ const missing = wanted.filter((w) => !at(w).some((h) => same(w, h)));
257
+ for (const w of missing) {
258
+ const made = await cf(`/zones/${id}/dns_records`, {
259
+ method: 'POST',
260
+ body: JSON.stringify(cfBody(w, studio)),
261
+ });
262
+ if (!made.success)
263
+ throw new CliError('Cloudflare would not add a mail record.', {
264
+ record: recordLine(w),
265
+ errors: made.errors ?? [],
266
+ fix: 'Check that the token has DNS edit on the zone, then run this again.',
267
+ });
268
+ }
269
+ return missing.length ? 'added' : 'exists';
270
+ },
208
271
  };
209
272
  }
@@ -1,4 +1,5 @@
1
1
  import { type Review } from '../../core/review/service.ts';
2
+ import { type DnsRecord, type Recorded } from './dns.ts';
2
3
  import type { Deployment, DomainState, Host } from './host.ts';
3
4
  import type { StudioDeps } from './studio-deps.ts';
4
5
  export type FakeHost = {
@@ -108,6 +109,7 @@ export declare function fakeDeps(home: string, cwd?: string): {
108
109
  }>;
109
110
  revoke(scope: import("../../core/review/service.ts").HostScope, actor: import("../../core/review/model.ts").Person | null, id: string): Promise<import("../../core/review/model.ts").Person>;
110
111
  setAccess(scope: import("../../core/review/service.ts").HostScope, actor: import("../../core/review/model.ts").Person | null, id: string, access: unknown): Promise<import("../../core/review/model.ts").Person>;
112
+ setEmail(at: import("../../core/review/service.ts").HostScope, actor: import("../../core/review/model.ts").Person | null, id: string, email: unknown): Promise<import("../../core/review/model.ts").Person>;
111
113
  defaultAccess(scope: import("../../core/review/model.ts").Scope, actor: import("../../core/review/model.ts").Person | null): Promise<import("../../core/review/model.ts").Access>;
112
114
  setDefaultAccess(scope: import("../../core/review/model.ts").Scope, actor: import("../../core/review/model.ts").Person | null, access: unknown): Promise<import("../../core/review/model.ts").Access>;
113
115
  addStudioPerson(actor: import("../../core/review/model.ts").Person | null, input: unknown): Promise<import("../../core/review/model.ts").Person>;
@@ -118,7 +120,16 @@ export declare function fakeDeps(home: string, cwd?: string): {
118
120
  studioAccess(actor: import("../../core/review/model.ts").Person | null): Promise<import("../../core/review/model.ts").Access>;
119
121
  setStudioAccess(actor: import("../../core/review/model.ts").Person | null, access: unknown): Promise<import("../../core/review/model.ts").Access>;
120
122
  peekLink(at: import("../../core/review/service.ts").HostScope, token: string): Promise<import("../../core/review/model.ts").Person | null>;
121
- useLink(at: import("../../core/review/service.ts").HostScope, token: string): Promise<import("../../core/review/model.ts").Person | null>;
123
+ useLink(at: import("../../core/review/service.ts").HostScope, token: string, browser?: string | null): Promise<import("../../core/review/model.ts").Person | null>;
124
+ askCode(at: import("../../core/review/service.ts").HostScope, email: unknown): Promise<{
125
+ person: import("../../core/review/model.ts").Person;
126
+ code: string;
127
+ hash: string;
128
+ } | null>;
129
+ hit(kind: import("../../core/review/service.ts").CapKind, address: string): Promise<boolean>;
130
+ recordMail(answer: import("../../core/review/service.ts").Sent): Promise<void>;
131
+ mailRecord(): Promise<import("../../core/review/service.ts").MailRecord>;
132
+ useCode(at: import("../../core/review/service.ts").HostScope, email: unknown, code: unknown, browser?: string | null): Promise<import("../../core/review/model.ts").Person | null>;
122
133
  listComments(scope: import("../../core/review/model.ts").Scope, actor: import("../../core/review/model.ts").Person | null, prototype: string, viewAs?: unknown): Promise<import("../../core/review/model.ts").Comment[]>;
123
134
  allComments(scope: import("../../core/review/model.ts").Scope, actor: import("../../core/review/model.ts").Person | null): Promise<import("../../core/review/model.ts").Comment[]>;
124
135
  add(scope: import("../../core/review/model.ts").Scope, actor: import("../../core/review/model.ts").Person | null, input: {
@@ -179,6 +190,10 @@ export declare function fakeDeps(home: string, cwd?: string): {
179
190
  files: import("../../core/files.ts").Files;
180
191
  ensured: string[];
181
192
  released: string[];
193
+ recorded: DnsRecord[][];
194
+ records: {
195
+ answer: Recorded | Error;
196
+ };
182
197
  hosts: string[];
183
198
  clock: {
184
199
  at: number;
@@ -56,6 +56,10 @@ export function fakeHost(older = ['dpl_old1', 'dpl_old2']) {
56
56
  fake.env.set(name, value);
57
57
  return 'set';
58
58
  },
59
+ async removeSecret(name) {
60
+ log(`removeSecret ${name}`);
61
+ return fake.env.delete(name) ? 'removed' : 'absent';
62
+ },
59
63
  async hasEnv(name) {
60
64
  log(`hasEnv ${name}`);
61
65
  return fake.env.has(name);
@@ -179,6 +183,9 @@ export function fakeDeps(home, cwd = home) {
179
183
  };
180
184
  const ensured = [];
181
185
  const released = [];
186
+ /** Each set of mail records the per-host DNS was asked for, and what it answers. */
187
+ const recorded = [];
188
+ const records = { answer: 'added' };
182
189
  const perHost = {
183
190
  mode: 'per-host',
184
191
  ensure: async (host) => {
@@ -189,6 +196,13 @@ export function fakeDeps(home, cwd = home) {
189
196
  released.push(host);
190
197
  return { removed: [`CNAME ${host} abc123.vercel-dns-016.com`], left: [] };
191
198
  },
199
+ records: async (wanted) => {
200
+ fake.calls.push(`dns records ${wanted.length}`);
201
+ recorded.push(wanted);
202
+ if (records.answer instanceof Error)
203
+ throw records.answer;
204
+ return records.answer;
205
+ },
192
206
  };
193
207
  /**
194
208
  * The host's DNS as its zone's nameservers and this machine's resolver see
@@ -253,6 +267,27 @@ export function fakeDeps(home, cwd = home) {
253
267
  writeFileSync(join(dir, 'pnpm-lock.yaml'), "lockfileVersion: '9.0'\n");
254
268
  return { status: 0, stdout: '', stderr: '' };
255
269
  },
270
+ // No mail key in a fake studio's .env: a test that mails sets one.
271
+ mailer: () => null,
272
+ // No network: a test that reaches Resend hands its own.
273
+ fetcher: async () => {
274
+ throw new Error('No network in the command tests.');
275
+ },
276
+ wait: async () => { },
277
+ };
278
+ return {
279
+ deps,
280
+ fake,
281
+ kv,
282
+ review,
283
+ files,
284
+ ensured,
285
+ released,
286
+ recorded,
287
+ records,
288
+ hosts,
289
+ clock,
290
+ pnpmFails,
291
+ dns,
256
292
  };
257
- return { deps, fake, kv, review, files, ensured, released, hosts, clock, pnpmFails, dns };
258
293
  }
@@ -23,6 +23,8 @@ export interface Host {
23
23
  link(create: boolean): Promise<'created' | 'linked' | 'kept'>;
24
24
  /** Sets a production secret that is not there yet, its value on stdin. */
25
25
  setSecret(name: string, value: string): Promise<'set' | 'kept'>;
26
+ /** Takes a production env var off, so a new value can be set in its place (setSecret keeps one there). */
27
+ removeSecret(name: string): Promise<'removed' | 'absent'>;
26
28
  /** Whether Production has an env var of this name; its value is never read. */
27
29
  hasEnv(name: string): Promise<boolean>;
28
30
  /** Production values of these names, read into memory, never into a file left behind. */
@@ -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,7 @@ 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';
5
6
  import { type StoreChoice } from '../../server/stores/index.ts';
6
7
  import { type Dns } from './dns.ts';
7
8
  import { type Host } from './host.ts';
@@ -27,6 +28,12 @@ export type StudioDeps = {
27
28
  files(studio: Studio): Files;
28
29
  /** pnpm with these arguments in the studio folder, its output captured; null when pnpm is missing. */
29
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>;
30
37
  };
31
38
  /**
32
39
  * The review store a studio's `.env` names, by the one rule the site uses
@@ -3,7 +3,8 @@
3
3
  // folder: its host (the adapter studio.json names, in its own team), its DNS
4
4
  // adapter, its review store (Upstash or Postgres, as studio.json says) and
5
5
  // its file store, each from the folder's own `.env`, how a host is seen to
6
- // be served by its DNS, and pnpm in the folder. Tests hand the commands
6
+ // be served by its DNS, pnpm in the folder, and the network for Resend's
7
+ // API. Tests hand the commands
7
8
  // fakes of the same shape instead. A command reaches the review store only
8
9
  // through openReview, and writes or removes files only through openFiles,
9
10
  // each of which first checks that the store is this studio's
@@ -13,6 +14,7 @@ import { createReview, ReviewError } from '../../core/review/service.js';
13
14
  import { blobFiles } from '../../server/blob.js';
14
15
  import { readEnv } from '../../server/env.js';
15
16
  import { localStudio } from '../../server/local.js';
17
+ import { chooseMailer } from '../../server/mailer.js';
16
18
  import { claimFiles, mustBeOwnDatabase } from '../../server/mark.js';
17
19
  import { chooseStore } from '../../server/stores/index.js';
18
20
  import { CliError } from './cli.js';
@@ -74,6 +76,9 @@ export function realDeps() {
74
76
  return null;
75
77
  return { status: out.status ?? 1, stdout: out.stdout ?? '', stderr: out.stderr ?? '' };
76
78
  },
79
+ mailer: ({ dir }) => chooseMailer(readEnv(dir)),
80
+ fetcher: (input, init) => fetch(input, init),
81
+ wait: (ms) => new Promise((r) => setTimeout(r, ms)),
77
82
  };
78
83
  }
79
84
  /**
@@ -75,8 +75,8 @@ export declare const studioHost: (apex: string) => string;
75
75
  /**
76
76
  * The host a client is served on: `<slug>.<apex>`, or a codename
77
77
  * (`--host atlas` is `atlas.<apex>`). A client's host is exactly one label
78
- * under the apex, and that label is never studio, www or api, which the
79
- * 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
80
80
  * down (`a.studio.<apex>`) are refused.
81
81
  */
82
82
  export declare function clientHost(slug: string, apex: string, given: string | undefined): string;
@@ -10,7 +10,7 @@ import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from
10
10
  import { homedir } from 'node:os';
11
11
  import { join, resolve } from 'node:path';
12
12
  import { SLUG } from '../../core/feature.js';
13
- import { hostName } from '../../core/prototype.js';
13
+ import { hostName, RESERVED_CLIENTS } from '../../core/prototype.js';
14
14
  import { CliError } from './cli.js';
15
15
  /** Who serves DNS for the apex, and so how a client's host gets its record. */
16
16
  export const DNS_PROVIDERS = ['vercel', 'cloudflare', 'manual'];
@@ -175,15 +175,15 @@ export function findStudio(home, named, cwd) {
175
175
  }
176
176
  /** The studio's own host, where Studio signs in and sees every client: `studio.<apex>`. */
177
177
  export const studioHost = (apex) => `studio.${apex}`;
178
- /** The first labels the studio keeps for itself, never a client's host. */
179
- const KEPT_LABELS = ['studio', 'www', 'api'];
178
+ /** The first labels the studio keeps for itself, never a client's host: the names no client may have, `mail` (the default sender's domain) among them. */
179
+ const KEPT_LABELS = RESERVED_CLIENTS;
180
180
  /** One DNS label: lower-case letters, digits and inner hyphens. */
181
181
  const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
182
182
  /**
183
183
  * The host a client is served on: `<slug>.<apex>`, or a codename
184
184
  * (`--host atlas` is `atlas.<apex>`). A client's host is exactly one label
185
- * under the apex, and that label is never studio, www or api, which the
186
- * studio keeps. So the apex itself, a host not under it, and one two labels
185
+ * under the apex, and that label is never studio, www, api or mail, which
186
+ * the studio keeps. So the apex itself, a host not under it, and one two labels
187
187
  * down (`a.studio.<apex>`) are refused.
188
188
  */
189
189
  export function clientHost(slug, apex, given) {
@@ -269,6 +269,12 @@ export function vercelHost({ dir, team, project, run = studioCli, fetcher = fetc
269
269
  await linkedMust(['env', 'add', name, 'production', '--sensitive', '--yes'], value);
270
270
  return 'set';
271
271
  },
272
+ async removeSecret(name) {
273
+ if (!(await names()).has(name))
274
+ return 'absent';
275
+ await linkedMust(['env', 'rm', name, 'production', '--yes']);
276
+ return 'removed';
277
+ },
272
278
  async pullEnv(wanted) {
273
279
  const tmp = mkdtempSync(join(tmpdir(), 'studio-env-'));
274
280
  try {
@@ -3,13 +3,13 @@ import { type Args } from './lib/cli.ts';
3
3
  import { type ProjectDeps } from './lib/linked.ts';
4
4
  export declare const spec: {
5
5
  readonly name: 'people';
6
- readonly summary: 'List or add the people who comment on the deployed prototypes, give them sign-in links, sign them out, revoke them, and set how long they keep access.';
6
+ readonly summary: 'List or add the people who comment on the deployed prototypes, give them sign-in links, sign them out, revoke them, set how long they keep access, and set the address they sign in with by email.';
7
7
  readonly positionals: [{
8
8
  readonly name: 'action';
9
- readonly description: 'list (default): everyone. add: a new person and their link. link <id>: another one-time link, for another device. sign-out <id>: ends every session and unused link, and gives one new link. revoke <id>: ends their access everywhere. access [id]: with an id and --access, sets that person’s access from now; without an id, reads the default a new Client gets (in a project the client’s own, else the studio’s; in the studio folder or with --studio the studio’s), or sets it with --access.';
9
+ readonly description: 'list (default): everyone. add: a new person and their link. link <id>: another one-time link, for another device. sign-out <id>: ends every session and unused link, and gives one new link. revoke <id>: ends their access everywhere. email <id>: sets or changes their address with --email, or clears it with --clear. access [id]: with an id and --access, sets that person’s access from now; without an id, reads the default a new Client gets (in a project the client’s own, else the studio’s; in the studio folder or with --studio the studio’s), or sets it with --access.';
10
10
  }, {
11
11
  readonly name: 'id';
12
- readonly description: 'The person, for link, sign-out, revoke and access';
12
+ readonly description: 'The person, for link, sign-out, revoke, email and access';
13
13
  }];
14
14
  readonly flags: {
15
15
  readonly name: {
@@ -30,6 +30,18 @@ export declare const spec: {
30
30
  readonly choices: readonly ["3m", "6m", "open"];
31
31
  readonly description: 'How long they keep access: 3m, 6m or open. For add, absent means the client’s default for a client (people access reads it) and open for studio.';
32
32
  };
33
+ readonly email: {
34
+ readonly type: 'string';
35
+ readonly description: 'For add and email: the address they sign in with by email, kept lower case. Optional: without one they sign in by link only. Within one client, or the studio’s own people, one person holds an address.';
36
+ };
37
+ readonly clear: {
38
+ readonly type: 'boolean';
39
+ readonly description: 'For email: removes their address, so they sign in by link only.';
40
+ };
41
+ readonly 'no-mail': {
42
+ readonly type: 'boolean';
43
+ readonly description: 'For add: do not email them their link. Absent, a person with --email is mailed it when the studio sends mail (RESEND_API_KEY and MAIL_FROM in its .env), and mailed says how that went.';
44
+ };
33
45
  readonly studio: {
34
46
  readonly type: 'string';
35
47
  readonly description: 'The studio whose own people these are, by slug, from anywhere on this machine; in the studio folder it is that studio. Their links are on studio.<apex>. Client people are a project’s: run people in the project linked to their client.';
@@ -39,7 +51,7 @@ export declare const spec: {
39
51
  readonly description: 'Use this machine’s dev store, even in a project linked to a studio.';
40
52
  };
41
53
  };
42
- readonly output: '{ ok, store, studio?, people } or { ok, store, studio?, person, link, next?, notice? } or { ok, store, studio?, person } or { ok, store, studio?, access }; store is studio in a linked project, with studio: { studio, client, host, project }, and notice when a Studio person is added there; store is studio with studio: { studio, host } for the studio’s own people (the studio folder or --studio); local otherwise. A Studio person’s link is on studio.<apex> once it answers.';
54
+ readonly output: '{ ok, store, studio?, people } or { ok, store, studio?, person, link, mailed?, next?, notice? } or { ok, store, studio?, person } or { ok, store, studio?, access }; store is studio in a linked project, with studio: { studio, client, host, project }, and notice when a Studio person is added there; store is studio with studio: { studio, host } for the studio’s own people (the studio folder or --studio); local otherwise. A Studio person’s link is on studio.<apex> once it answers. mailed, on add: sent (Resend took the invite; have them check spam if it does not show), refused or down (it did not go: send the link yourself), or off (none was sent).';
43
55
  };
44
56
  export declare function run({ positionals: [action, id], flags }: Args<typeof spec>, deps: ProjectDeps): Promise<Record<string, unknown>>;
45
57
  export declare const main: (args: Args<typeof spec>) => Promise<Record<string, unknown>>;