@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
@@ -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'];
@@ -21,8 +21,19 @@ export const MODE_OF = {
21
21
  manual: 'manual',
22
22
  };
23
23
  export const STUDIO_FILE = 'studio.json';
24
- /** The secrets a studio folder's `.env` holds. Studios share none of them. */
25
- export const STORE_NAMES = ['KV_REST_API_URL', 'KV_REST_API_TOKEN'];
24
+ /** The kinds of database a studio can have. */
25
+ export const KV_PROVIDERS = ['upstash', 'postgres'];
26
+ /**
27
+ * The names a studio's database comes in as, by kind, in its `.env` and the
28
+ * site's env. Studios share none of them. Upstash needs both; Postgres
29
+ * either, since Neon's integration sets both and Supabase's POSTGRES_URL only.
30
+ */
31
+ export const STORE_NAMES = {
32
+ upstash: ['KV_REST_API_URL', 'KV_REST_API_TOKEN'],
33
+ postgres: ['DATABASE_URL', 'POSTGRES_URL'],
34
+ };
35
+ /** Whether the names `has` says are there make a database of this kind. */
36
+ export const hasStore = (kind, has) => kind === 'upstash' ? STORE_NAMES.upstash.every(has) : STORE_NAMES.postgres.some(has);
26
37
  export const BLOB_NAME = 'BLOB_READ_WRITE_TOKEN';
27
38
  export const CLOUDFLARE_NAME = 'CLOUDFLARE_API_TOKEN';
28
39
  /** A Vercel team or project name as the CLI takes it: lower-case letters, digits, `-`, `_` and `.`. */
@@ -49,12 +60,19 @@ export function studioProblems(c) {
49
60
  problems.push('vercel.team: the Vercel team slug');
50
61
  if (!isVercelName(c.vercel?.project))
51
62
  problems.push('vercel.project: the Vercel project name');
52
- const provider = c.dns?.provider;
63
+ if (!KV_PROVIDERS.includes(c.providers?.kv))
64
+ problems.push(`providers.kv: one of ${KV_PROVIDERS.join(', ')}`);
65
+ return [...problems, ...dnsProblems(c.dns)];
66
+ }
67
+ /** The problems with a studio.json's `dns`. */
68
+ function dnsProblems(dns) {
69
+ const provider = dns?.provider;
70
+ const problems = [];
53
71
  if (!DNS_PROVIDERS.includes(provider))
54
72
  problems.push(`dns.provider: one of ${DNS_PROVIDERS.join(', ')}`);
55
- else if (c.dns?.mode !== MODE_OF[provider])
73
+ else if (dns?.mode !== MODE_OF[provider])
56
74
  problems.push(`dns.mode: ${MODE_OF[provider]} for ${provider}`);
57
- if (c.dns?.zone != null && !/^[a-f0-9]{32}$/.test(c.dns.zone))
75
+ if (dns?.zone != null && !/^[a-f0-9]{32}$/.test(dns.zone))
58
76
  problems.push('dns.zone: a Cloudflare zone id');
59
77
  return problems;
60
78
  }
@@ -157,15 +175,15 @@ export function findStudio(home, named, cwd) {
157
175
  }
158
176
  /** The studio's own host, where Studio signs in and sees every client: `studio.<apex>`. */
159
177
  export const studioHost = (apex) => `studio.${apex}`;
160
- /** The first labels the studio keeps for itself, never a client's host. */
161
- 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;
162
180
  /** One DNS label: lower-case letters, digits and inner hyphens. */
163
181
  const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
164
182
  /**
165
183
  * The host a client is served on: `<slug>.<apex>`, or a codename
166
184
  * (`--host atlas` is `atlas.<apex>`). A client's host is exactly one label
167
- * under the apex, and that label is never studio, www or api, which the
168
- * 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
169
187
  * down (`a.studio.<apex>`) are refused.
170
188
  */
171
189
  export function clientHost(slug, apex, given) {
@@ -0,0 +1,17 @@
1
+ import type { Host } from './host.ts';
2
+ import { type Run } from './vercel.ts';
3
+ type VercelOptions = {
4
+ dir: string;
5
+ team: string;
6
+ project: string;
7
+ run?: (cwd: string, args: string[], input?: string) => Run | null;
8
+ fetcher?: typeof fetch;
9
+ wait?: (ms: number) => Promise<unknown>;
10
+ };
11
+ /** The env vars the Vercel CLI (59.x) reads to pick a project or team over the folder's link and `--scope`. */
12
+ export declare const PICKERS: string[];
13
+ /** The Vercel adapter. Every call goes through `call`, which adds `--scope <team>`. */
14
+ export declare function vercelHost({ dir, team, project, run, fetcher, wait, }: VercelOptions): Host;
15
+ /** Vercel's first-ranked CNAME for a host, without its trailing dot. */
16
+ export declare function cnameTarget(config: Record<string, any> | null): string;
17
+ export {};
@@ -0,0 +1,416 @@
1
+ /// <reference types="node" />
2
+ // The host port's Vercel adapter (scripts/lib/host.ts), through its CLI. Every call names the
3
+ // studio's team (`--scope`), so no command ever acts in whichever team the CLI
4
+ // last switched to. A call that acts through the folder's link (deploy, env,
5
+ // the stores) runs only once the link is the studio's project in that team,
6
+ // and the CLI never sees the env vars that would pick another. No call prints
7
+ // a value: secrets go in on stdin and come back only into the folder's `.env`.
8
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
9
+ import { tmpdir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import { hostName, proofPath } from '../../core/prototype.js';
12
+ import { readEnv } from '../../server/env.js';
13
+ import { CliError } from './cli.js';
14
+ import { upstashTerms } from './deploy.js';
15
+ import { BLOB_NAME, hasStore, STORE_NAMES } from './studios.js';
16
+ import { vercel } from './vercel.js';
17
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
18
+ const HTTPS_TRIES = 20;
19
+ const HTTPS_GAP_MS = 3000;
20
+ /**
21
+ * A DELETE through `vercel api`. The CLI (59.x) asks before every DELETE and,
22
+ * with no terminal (as every design-hub command runs), refuses one unless it is
23
+ * told to skip that question. Only the two removals send it, each on a path
24
+ * built from a checked deployment id or host. `vercel remove` is not used: it
25
+ * also looks its argument up as a project and deletes any project it matches.
26
+ * No CLI command takes one host off one project (`vercel domains rm` takes the
27
+ * domain off the whole team).
28
+ */
29
+ const DELETE = ['-X', 'DELETE', '--dangerously-skip-permissions'];
30
+ const DEPLOYMENT_ID = /^dpl_[A-Za-z0-9]+$/;
31
+ /** A Marketplace resource's name, as `vercel integration resource connect` takes it. */
32
+ const RESOURCE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
33
+ /** What the Marketplace answers a plan the team cannot have (studios-findings.md, section 5). */
34
+ const PLAN_NOT_FOUND = /billing plan not found|plan[^\n]*not (found|available)/i;
35
+ /**
36
+ * The plan the Marketplace labels exactly Free, from the plans its refusal of
37
+ * an unknown plan id lists (`Available plans: free_v3 (Free), launch_v3
38
+ * (Launch), …`), or null when it lists none so labelled.
39
+ */
40
+ function freePlanOf(stderr) {
41
+ const listed = stderr.split(/Available plans:/i)[1]?.split(/\.\s|\n/)[0] ?? '';
42
+ for (const [, id, label] of listed.matchAll(/([A-Za-z0-9_-]+) \(([^)]*)\)/g))
43
+ if (label === 'Free')
44
+ return id;
45
+ return null;
46
+ }
47
+ /** The Marketplace product a new review store of each kind is made from, and its free plan's id as last seen. */
48
+ const MARKETPLACE = {
49
+ upstash: { product: 'upstash/upstash-kv', label: 'Upstash for Redis', plan: 'free' },
50
+ postgres: { product: 'neon', label: 'Neon Postgres', plan: 'free_v3' },
51
+ };
52
+ /**
53
+ * Why no new free database was added: the free plan's id refused again (the
54
+ * team may still have one), no plan labelled Free (the team cannot have
55
+ * one), or anything else, most often the terms (addFailed).
56
+ */
57
+ function notAdded(kind, stderr, free, team) {
58
+ const { label } = MARKETPLACE[kind];
59
+ const tail = stderr.trim().slice(-600);
60
+ const own = `If team ${team} has a database no studio uses (its Storage page on Vercel), run this again with --database <its name>.`;
61
+ if (!PLAN_NOT_FOUND.test(stderr))
62
+ return addFailed(kind, stderr, team);
63
+ if (free)
64
+ return new CliError(`The Marketplace did not take ${label}'s free plan (${free}); nothing was bought.`, {
65
+ stderr: tail,
66
+ fix: `Run this again in a few minutes. ${own}`,
67
+ });
68
+ return new CliError(`Team ${team} cannot have a free review store (${label}): the Marketplace offers it no free plan; nothing was bought.`, {
69
+ stderr: tail,
70
+ fix: `A database serves one studio only: never connect one another studio uses. ${own} Else give this studio a team or a ${label} account of its own.`,
71
+ });
72
+ }
73
+ /**
74
+ * Why a new review store could not be added, most often terms the team has
75
+ * not accepted: for Upstash the words to send the user (upstashTerms), for
76
+ * Neon the link the CLI printed, else its Marketplace page.
77
+ */
78
+ function addFailed(kind, stderr, team) {
79
+ const tail = stderr.trim().slice(-600);
80
+ const or = 'or connect a database the team has that no studio uses with --database <its name>.';
81
+ if (kind === 'upstash') {
82
+ const terms = upstashTerms(stderr, team);
83
+ return new CliError('Could not add the review store (Upstash for Redis) to the studio project.', {
84
+ stderr: tail,
85
+ terms: terms.url,
86
+ fix: `Most often the team has not accepted the Upstash terms. Tell the user, word for word: "${terms.say}" Then run this again; ${or}`,
87
+ });
88
+ }
89
+ const url = stderr.match(/https:\/\/vercel\.com\/\S*accept-terms\S*/)?.[0] ?? 'https://vercel.com/marketplace/neon';
90
+ return new CliError('Could not add the review store (Neon Postgres) to the studio project.', {
91
+ stderr: tail,
92
+ terms: url,
93
+ fix: `Most often the team has not accepted the Neon terms. Tell the user, word for word: "Open ${url} for the ${team} team and accept the Neon terms. Stop once they are accepted: the rerun creates the database and connects it to this project." Then run this again; ${or}`,
94
+ });
95
+ }
96
+ /** The env vars the Vercel CLI (59.x) reads to pick a project or team over the folder's link and `--scope`. */
97
+ export const PICKERS = [
98
+ 'VERCEL_ORG_ID',
99
+ 'VERCEL_PROJECT_ID',
100
+ 'NOW_ORG_ID',
101
+ 'NOW_PROJECT_ID',
102
+ 'VERCEL_TEAM_ID',
103
+ ];
104
+ /** The caller's env without the names that would send a studio command to another project or team. */
105
+ function studioCliEnv(env) {
106
+ const out = { ...env };
107
+ for (const name of PICKERS)
108
+ delete out[name];
109
+ return out;
110
+ }
111
+ const studioCli = (cwd, args, input) => vercel(cwd, args, input, studioCliEnv(process.env));
112
+ /** The ids `.vercel/project.json` links the folder to, or none when it is missing or unreadable. */
113
+ function linkOf(dir) {
114
+ try {
115
+ return JSON.parse(readFileSync(join(dir, '.vercel', 'project.json'), 'utf8'));
116
+ }
117
+ catch {
118
+ return {};
119
+ }
120
+ }
121
+ /** The Vercel adapter. Every call goes through `call`, which adds `--scope <team>`. */
122
+ export function vercelHost({ dir, team, project, run = studioCli, fetcher = fetch, wait = sleep, }) {
123
+ const call = (args, input) => {
124
+ const out = run(dir, [...args, '--scope', team], input);
125
+ if (!out)
126
+ throw new CliError('The Vercel CLI is not installed.', {
127
+ fix: 'npm i -g vercel, then design-hub signin.',
128
+ });
129
+ return out;
130
+ };
131
+ const must = (args, input) => {
132
+ const out = call(args, input);
133
+ if (out.status !== 0)
134
+ throw failed(args, out);
135
+ return out.stdout;
136
+ };
137
+ const api = async (path, method = 'GET', fields = []) => {
138
+ const verb = method === 'GET' ? [] : method === 'DELETE' ? DELETE : ['-X', method];
139
+ const args = ['api', path, '--raw', ...verb];
140
+ const out = call([...args, ...fields.flatMap((f) => ['-F', f])]);
141
+ if (out.status !== 0) {
142
+ if (/\b404\b|not[_ ]found/i.test(`${out.stdout}\n${out.stderr}`))
143
+ return null;
144
+ throw failed(['api', method, path], out);
145
+ }
146
+ return out.stdout.trim() ? JSON.parse(out.stdout) : {};
147
+ };
148
+ /** The studio's project on its team, as ids, or null when the team has none of that name. */
149
+ const studioProject = async () => {
150
+ const found = await api(`/v9/projects/${encodeURIComponent(project)}`);
151
+ return found ? { id: found.id, org: found.accountId } : null;
152
+ };
153
+ /** Whether `.vercel/project.json` is that project, in that team, by id: a name alone can be another team's. */
154
+ const linkedTo = (want) => {
155
+ const have = linkOf(dir);
156
+ return (!!want &&
157
+ typeof want.id === 'string' &&
158
+ typeof want.org === 'string' &&
159
+ have.projectId === want.id &&
160
+ have.orgId === want.org);
161
+ };
162
+ /** A call the CLI sends wherever the folder is linked: refused, before it runs, unless that is the studio. */
163
+ const linked = async (args, input) => {
164
+ if (!linkedTo(await studioProject()))
165
+ throw new CliError(`The studio folder is not linked to project ${project} in team ${team}; nothing was changed.`, {
166
+ dir,
167
+ fix: `design-hub studio link --dir ${dir}, then run this again.`,
168
+ });
169
+ return call(args, input);
170
+ };
171
+ const linkedMust = async (args, input) => {
172
+ const out = await linked(args, input);
173
+ if (out.status !== 0)
174
+ throw failed(args, out);
175
+ return out.stdout;
176
+ };
177
+ const names = async () => new Set([...(await linkedMust(['env', 'ls', 'production'])).matchAll(/^\s*([A-Z][A-Z0-9_]*)\s/gm)].map((m) => m[1]));
178
+ /**
179
+ * The team's database of this name, connected. One of another kind brings
180
+ * none of this kind's names: this run connected it, so this run lets it go.
181
+ */
182
+ const connectExisting = async (kind, existing) => {
183
+ if (!RESOURCE_NAME.test(existing))
184
+ throw new CliError('--database takes the name of a database the team has.', { got: existing });
185
+ const out = await linked(['integration', 'resource', 'connect', existing, project, '--yes']);
186
+ if (out.status !== 0)
187
+ throw new CliError(`Could not connect the database ${existing} to the studio project.`, {
188
+ stderr: out.stderr.trim().slice(-600),
189
+ fix: `Check the name on team ${team}'s Storage page on Vercel, then run this again.`,
190
+ });
191
+ const now = await names();
192
+ if (hasStore(kind, (n) => now.has(n)))
193
+ return 'connected';
194
+ const gone = await disconnect(kind === 'upstash' ? 'postgres' : 'upstash', existing);
195
+ throw new CliError(`${existing} is not ${kind === 'upstash' ? 'an Upstash for Redis' : 'a Postgres'} database; ${gone ? 'it was disconnected again from' : 'it is still connected to'} project ${project}, and nothing was written to it.`, {
196
+ fix: gone
197
+ ? `Run this again with --database <a ${kind} database the team has>, or without --database for a new free one.`
198
+ : `Disconnect ${existing} from project ${project} on team ${team}'s Storage page on Vercel, then run this again with --database <a ${kind} database the team has>, or without it.`,
199
+ });
200
+ };
201
+ /**
202
+ * A new database on the free plan only: a team without one is refused by
203
+ * the Marketplace, and nothing is bought. The plan id changes now and then,
204
+ * so a refused id is asked once more by the plan the Marketplace labels
205
+ * Free, never by another.
206
+ */
207
+ const addFree = async (kind) => {
208
+ const { product, plan } = MARKETPLACE[kind];
209
+ const add = (id) => linked([
210
+ 'integration',
211
+ 'add',
212
+ product,
213
+ '--name',
214
+ `${project}-review`,
215
+ '--plan',
216
+ id,
217
+ '-e',
218
+ 'production',
219
+ '--no-env-pull',
220
+ ]);
221
+ let out = await add(plan);
222
+ const free = PLAN_NOT_FOUND.test(out.stderr) ? freePlanOf(out.stderr) : null;
223
+ if (out.status !== 0 && free && free !== plan)
224
+ out = await add(free);
225
+ if (out.status !== 0)
226
+ throw notAdded(kind, out.stderr, free, team);
227
+ return 'created';
228
+ };
229
+ /** Takes a team database off the project; true once Production holds none of the kind's names. */
230
+ const disconnect = async (kind, name) => {
231
+ if (!RESOURCE_NAME.test(name))
232
+ return false;
233
+ const out = await linked(['integration', 'resource', 'disconnect', name, project, '--yes']);
234
+ if (out.status !== 0)
235
+ return false;
236
+ const have = await names();
237
+ return !STORE_NAMES[kind].some((n) => have.has(n));
238
+ };
239
+ const domainPath = (host) => `/v9/projects/${encodeURIComponent(project)}/domains/${encodeURIComponent(host)}`;
240
+ return {
241
+ async link(create) {
242
+ const want = await studioProject();
243
+ if (linkedTo(want))
244
+ return 'kept';
245
+ if (create && want)
246
+ throw new CliError(`Team ${team} already has a project named ${project}.`, {
247
+ fix: 'Pick another --project, or run design-hub studio link on the folder that made it.',
248
+ });
249
+ if (!create && !want)
250
+ throw new CliError(`Team ${team} has no project named ${project}.`, {
251
+ fix: 'Check vercel.team and vercel.project in studio.json.',
252
+ });
253
+ if (create)
254
+ must(['project', 'add', project]);
255
+ must(['link', '--yes', '--project', project]);
256
+ if (!linkedTo(await studioProject()))
257
+ throw new CliError(`vercel link did not link the studio folder to project ${project} in team ${team}.`, {
258
+ dir,
259
+ fix: `Delete ${join(dir, '.vercel')}, then run this again.`,
260
+ });
261
+ return create ? 'created' : 'linked';
262
+ },
263
+ async hasEnv(name) {
264
+ return (await names()).has(name);
265
+ },
266
+ async setSecret(name, value) {
267
+ if ((await names()).has(name))
268
+ return 'kept';
269
+ await linkedMust(['env', 'add', name, 'production', '--sensitive', '--yes'], value);
270
+ return 'set';
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
+ },
278
+ async pullEnv(wanted) {
279
+ const tmp = mkdtempSync(join(tmpdir(), 'studio-env-'));
280
+ try {
281
+ await linkedMust(['env', 'pull', join(tmp, '.env'), '--environment=production', '--yes']);
282
+ const pulled = readEnv(tmp);
283
+ return Object.fromEntries(wanted.filter((n) => pulled[n]).map((n) => [n, pulled[n]]));
284
+ }
285
+ finally {
286
+ rmSync(tmp, { recursive: true, force: true });
287
+ }
288
+ },
289
+ async provisionDatabase(kind, existing) {
290
+ const have = await names();
291
+ if (hasStore(kind, (n) => have.has(n)))
292
+ return 'kept';
293
+ const other = kind === 'upstash' ? 'postgres' : 'upstash';
294
+ const others = STORE_NAMES[other].filter((n) => have.has(n));
295
+ if (others.length)
296
+ throw new CliError(`Production on project ${project} holds another database's names (${others.join(', ')}), and the studio site refuses to guess between two; nothing was connected.`, {
297
+ fix: `On team ${team}'s Storage page on Vercel, disconnect that database from project ${project}, then run this again.`,
298
+ });
299
+ return existing === undefined ? addFree(kind) : connectExisting(kind, existing);
300
+ },
301
+ disconnectDatabase: (kind, name) => disconnect(kind, name),
302
+ async provisionFiles(region) {
303
+ if ((await names()).has(BLOB_NAME))
304
+ return 'kept';
305
+ await linkedMust([
306
+ 'blob',
307
+ 'create-store',
308
+ `${project}-files`,
309
+ '--access',
310
+ 'private',
311
+ '--region',
312
+ region,
313
+ '--yes',
314
+ ]);
315
+ return 'created';
316
+ },
317
+ async addDomain(host) {
318
+ const existing = await api(domainPath(host));
319
+ const state = existing === null
320
+ ? await api(`/v10/projects/${encodeURIComponent(project)}/domains`, 'POST', [`name=${host}`])
321
+ : existing.verified
322
+ ? existing
323
+ : await api(`${domainPath(host)}/verify`, 'POST');
324
+ return {
325
+ verified: state?.verified === true,
326
+ verification: state?.verification ?? existing?.verification ?? [],
327
+ };
328
+ },
329
+ async removeDomain(host) {
330
+ if (hostName(host) !== host)
331
+ throw new CliError(`${host} is not a host name; no domain was removed.`);
332
+ if ((await api(domainPath(host))) === null)
333
+ return 'absent';
334
+ await api(domainPath(host), 'DELETE');
335
+ return 'removed';
336
+ },
337
+ async recordFor(host) {
338
+ const config = await api(`/v6/domains/${encodeURIComponent(host)}/config?projectIdOrName=${encodeURIComponent(project)}`);
339
+ return cnameTarget(config);
340
+ },
341
+ async reaches(host, proof) {
342
+ for (let i = 0; i < HTTPS_TRIES; i++) {
343
+ if (await answers(fetcher, host, proof))
344
+ return true;
345
+ await wait(HTTPS_GAP_MS);
346
+ }
347
+ return false;
348
+ },
349
+ async deploy() {
350
+ const out = await linked(['deploy', '--prod', '--yes']);
351
+ const url = `${out.stdout}\n${out.stderr}`.match(/https:\/\/([\w.-]+\.vercel\.app)/)?.[1];
352
+ if (out.status !== 0 || !url)
353
+ throw failed(['deploy', '--prod'], out);
354
+ const found = await api(`/v13/deployments/${encodeURIComponent(url)}`);
355
+ if (!found?.id)
356
+ throw new CliError('The new deployment could not be read back.', {
357
+ fix: 'Run design-hub studio deploy again.',
358
+ });
359
+ return { id: String(found.id), state: String(found.readyState ?? found.status ?? '') };
360
+ },
361
+ async deployments() {
362
+ const all = [];
363
+ let until = '';
364
+ do {
365
+ const page = await api(`/v6/deployments?projectId=${encodeURIComponent(project)}&limit=100${until ? `&until=${until}` : ''}`);
366
+ for (const d of (page?.deployments ?? []))
367
+ all.push({ id: d.uid, state: String(d.state ?? d.readyState ?? '') });
368
+ until = page?.pagination?.next ? String(page.pagination.next) : '';
369
+ } while (until);
370
+ return all;
371
+ },
372
+ async removeDeployment(id) {
373
+ if (!DEPLOYMENT_ID.test(id))
374
+ throw new CliError(`${id} is not a deployment id; nothing was removed.`);
375
+ const out = call(['api', `/v13/deployments/${id}`, '--raw', ...DELETE]);
376
+ if (out.status !== 0)
377
+ throw new CliError(`Vercel would not delete the older deployment ${id}.`, {
378
+ stderr: out.stderr.trim().slice(-600),
379
+ fix: 'Delete it in the project’s Deployments page on Vercel, then run design-hub studio deploy again.',
380
+ });
381
+ },
382
+ };
383
+ }
384
+ function failed(args, out) {
385
+ return new CliError(`vercel ${args.slice(0, 2).join(' ')} failed.`, {
386
+ stderr: out.stderr.trim().slice(-600),
387
+ fix: /log ?in|credentials|token|not authorized/i.test(out.stderr)
388
+ ? 'design-hub signin, send the user its url, then run this again.'
389
+ : undefined,
390
+ });
391
+ }
392
+ /** Vercel's first-ranked CNAME for a host, without its trailing dot. */
393
+ export function cnameTarget(config) {
394
+ const ranked = (config?.recommendedCNAME ?? [])
395
+ .slice()
396
+ .sort((a, b) => a.rank - b.rank);
397
+ const value = ranked[0]?.value?.replace(/\.$/, '').toLowerCase();
398
+ if (!value)
399
+ throw new CliError('Vercel named no record for this host.', { fix: 'Run this again in a minute.' });
400
+ return value;
401
+ }
402
+ /**
403
+ * A host answers from this studio's site: asked the proof's path over HTTPS,
404
+ * it sends back the proof's answer, which only the gate reading this studio's
405
+ * store has. Any other answer, whatever its status or headers, is another
406
+ * server's, or a site that does not know the client yet.
407
+ */
408
+ async function answers(fetcher, host, { ask, answer }) {
409
+ try {
410
+ const res = await fetcher(`https://${host}${proofPath(ask)}`, { redirect: 'manual' });
411
+ return res.status === 200 && (await res.text()) === answer;
412
+ }
413
+ catch {
414
+ return false;
415
+ }
416
+ }
@@ -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>>;