@milesroxas/design-hub 0.12.0 → 0.13.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 (51) hide show
  1. package/README.md +4 -4
  2. package/core/review/service.test.ts +39 -38
  3. package/core/review/store.ts +2 -2
  4. package/core/review/suite-kv.ts +17 -0
  5. package/dist/core/review/store.js +2 -2
  6. package/dist/core/review/suite-kv.d.ts +7 -0
  7. package/dist/core/review/suite-kv.js +12 -0
  8. package/dist/scripts/client.js +3 -3
  9. package/dist/scripts/lib/cli.js +5 -0
  10. package/dist/scripts/lib/fake-host.d.ts +1 -2
  11. package/dist/scripts/lib/fake-host.js +20 -9
  12. package/dist/scripts/lib/host.d.ts +13 -25
  13. package/dist/scripts/lib/host.js +15 -324
  14. package/dist/scripts/lib/studio-deps.d.ts +16 -0
  15. package/dist/scripts/lib/studio-deps.js +41 -16
  16. package/dist/scripts/lib/studios.d.ts +14 -4
  17. package/dist/scripts/lib/studios.js +23 -5
  18. package/dist/scripts/lib/vercel-host.d.ts +17 -0
  19. package/dist/scripts/lib/vercel-host.js +410 -0
  20. package/dist/scripts/share.js +3 -2
  21. package/dist/scripts/studio.d.ts +8 -2
  22. package/dist/scripts/studio.js +38 -14
  23. package/dist/server/api.d.ts +6 -5
  24. package/dist/server/api.js +12 -10
  25. package/dist/server/gate.d.ts +97 -0
  26. package/dist/server/gate.js +537 -0
  27. package/dist/server/mark.d.ts +17 -0
  28. package/dist/server/mark.js +46 -1
  29. package/dist/server/session.d.ts +2 -1
  30. package/dist/server/session.js +2 -2
  31. package/dist/server/stores/backends.d.ts +22 -0
  32. package/dist/server/stores/backends.js +96 -0
  33. package/dist/server/{fake-upstash.js → stores/fake-upstash.js} +1 -1
  34. package/dist/server/stores/index.d.ts +41 -0
  35. package/dist/server/stores/index.js +63 -0
  36. package/dist/server/stores/pglite.d.ts +16 -0
  37. package/dist/server/stores/pglite.js +98 -0
  38. package/dist/server/stores/postgres.d.ts +63 -0
  39. package/dist/server/stores/postgres.js +153 -0
  40. package/dist/server/{upstash.d.ts → stores/upstash.d.ts} +1 -1
  41. package/dist/vercel/files.js +1 -1
  42. package/dist/vercel/proxy.d.ts +6 -82
  43. package/dist/vercel/proxy.js +18 -525
  44. package/dist/vite/plugin.js +1 -1
  45. package/package.json +3 -1
  46. package/skills/miles-deploy/SKILL.md +2 -1
  47. package/templates/studio/.env.example +3 -0
  48. package/templates/studio/README.md +13 -0
  49. package/templates/studio/package.json +1 -1
  50. /package/dist/server/{fake-upstash.d.ts → stores/fake-upstash.d.ts} +0 -0
  51. /package/dist/server/{upstash.js → stores/upstash.js} +0 -0
@@ -0,0 +1,410 @@
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 pullEnv(wanted) {
273
+ const tmp = mkdtempSync(join(tmpdir(), 'studio-env-'));
274
+ try {
275
+ await linkedMust(['env', 'pull', join(tmp, '.env'), '--environment=production', '--yes']);
276
+ const pulled = readEnv(tmp);
277
+ return Object.fromEntries(wanted.filter((n) => pulled[n]).map((n) => [n, pulled[n]]));
278
+ }
279
+ finally {
280
+ rmSync(tmp, { recursive: true, force: true });
281
+ }
282
+ },
283
+ async provisionDatabase(kind, existing) {
284
+ const have = await names();
285
+ if (hasStore(kind, (n) => have.has(n)))
286
+ return 'kept';
287
+ const other = kind === 'upstash' ? 'postgres' : 'upstash';
288
+ const others = STORE_NAMES[other].filter((n) => have.has(n));
289
+ if (others.length)
290
+ 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.`, {
291
+ fix: `On team ${team}'s Storage page on Vercel, disconnect that database from project ${project}, then run this again.`,
292
+ });
293
+ return existing === undefined ? addFree(kind) : connectExisting(kind, existing);
294
+ },
295
+ disconnectDatabase: (kind, name) => disconnect(kind, name),
296
+ async provisionFiles(region) {
297
+ if ((await names()).has(BLOB_NAME))
298
+ return 'kept';
299
+ await linkedMust([
300
+ 'blob',
301
+ 'create-store',
302
+ `${project}-files`,
303
+ '--access',
304
+ 'private',
305
+ '--region',
306
+ region,
307
+ '--yes',
308
+ ]);
309
+ return 'created';
310
+ },
311
+ async addDomain(host) {
312
+ const existing = await api(domainPath(host));
313
+ const state = existing === null
314
+ ? await api(`/v10/projects/${encodeURIComponent(project)}/domains`, 'POST', [`name=${host}`])
315
+ : existing.verified
316
+ ? existing
317
+ : await api(`${domainPath(host)}/verify`, 'POST');
318
+ return {
319
+ verified: state?.verified === true,
320
+ verification: state?.verification ?? existing?.verification ?? [],
321
+ };
322
+ },
323
+ async removeDomain(host) {
324
+ if (hostName(host) !== host)
325
+ throw new CliError(`${host} is not a host name; no domain was removed.`);
326
+ if ((await api(domainPath(host))) === null)
327
+ return 'absent';
328
+ await api(domainPath(host), 'DELETE');
329
+ return 'removed';
330
+ },
331
+ async recordFor(host) {
332
+ const config = await api(`/v6/domains/${encodeURIComponent(host)}/config?projectIdOrName=${encodeURIComponent(project)}`);
333
+ return cnameTarget(config);
334
+ },
335
+ async reaches(host, proof) {
336
+ for (let i = 0; i < HTTPS_TRIES; i++) {
337
+ if (await answers(fetcher, host, proof))
338
+ return true;
339
+ await wait(HTTPS_GAP_MS);
340
+ }
341
+ return false;
342
+ },
343
+ async deploy() {
344
+ const out = await linked(['deploy', '--prod', '--yes']);
345
+ const url = `${out.stdout}\n${out.stderr}`.match(/https:\/\/([\w.-]+\.vercel\.app)/)?.[1];
346
+ if (out.status !== 0 || !url)
347
+ throw failed(['deploy', '--prod'], out);
348
+ const found = await api(`/v13/deployments/${encodeURIComponent(url)}`);
349
+ if (!found?.id)
350
+ throw new CliError('The new deployment could not be read back.', {
351
+ fix: 'Run design-hub studio deploy again.',
352
+ });
353
+ return { id: String(found.id), state: String(found.readyState ?? found.status ?? '') };
354
+ },
355
+ async deployments() {
356
+ const all = [];
357
+ let until = '';
358
+ do {
359
+ const page = await api(`/v6/deployments?projectId=${encodeURIComponent(project)}&limit=100${until ? `&until=${until}` : ''}`);
360
+ for (const d of (page?.deployments ?? []))
361
+ all.push({ id: d.uid, state: String(d.state ?? d.readyState ?? '') });
362
+ until = page?.pagination?.next ? String(page.pagination.next) : '';
363
+ } while (until);
364
+ return all;
365
+ },
366
+ async removeDeployment(id) {
367
+ if (!DEPLOYMENT_ID.test(id))
368
+ throw new CliError(`${id} is not a deployment id; nothing was removed.`);
369
+ const out = call(['api', `/v13/deployments/${id}`, '--raw', ...DELETE]);
370
+ if (out.status !== 0)
371
+ throw new CliError(`Vercel would not delete the older deployment ${id}.`, {
372
+ stderr: out.stderr.trim().slice(-600),
373
+ fix: 'Delete it in the project’s Deployments page on Vercel, then run design-hub studio deploy again.',
374
+ });
375
+ },
376
+ };
377
+ }
378
+ function failed(args, out) {
379
+ return new CliError(`vercel ${args.slice(0, 2).join(' ')} failed.`, {
380
+ stderr: out.stderr.trim().slice(-600),
381
+ fix: /log ?in|credentials|token|not authorized/i.test(out.stderr)
382
+ ? 'design-hub signin, send the user its url, then run this again.'
383
+ : undefined,
384
+ });
385
+ }
386
+ /** Vercel's first-ranked CNAME for a host, without its trailing dot. */
387
+ export function cnameTarget(config) {
388
+ const ranked = (config?.recommendedCNAME ?? [])
389
+ .slice()
390
+ .sort((a, b) => a.rank - b.rank);
391
+ const value = ranked[0]?.value?.replace(/\.$/, '').toLowerCase();
392
+ if (!value)
393
+ throw new CliError('Vercel named no record for this host.', { fix: 'Run this again in a minute.' });
394
+ return value;
395
+ }
396
+ /**
397
+ * A host answers from this studio's site: asked the proof's path over HTTPS,
398
+ * it sends back the proof's answer, which only the gate reading this studio's
399
+ * store has. Any other answer, whatever its status or headers, is another
400
+ * server's, or a site that does not know the client yet.
401
+ */
402
+ async function answers(fetcher, host, { ask, answer }) {
403
+ try {
404
+ const res = await fetcher(`https://${host}${proofPath(ask)}`, { redirect: 'manual' });
405
+ return res.status === 200 && (await res.text()) === answer;
406
+ }
407
+ catch {
408
+ return false;
409
+ }
410
+ }
@@ -17,6 +17,7 @@ import { prototypes } from './lib/catalog.js';
17
17
  import { CliError } from './lib/cli.js';
18
18
  import { addressOf, LINK_FILE, openLinked, readLink, realProjectDeps, } from './lib/linked.js';
19
19
  import { cliActor } from './lib/review.js';
20
+ import { openFiles } from './lib/studio-deps.js';
20
21
  import * as preflight from './preflight.js';
21
22
  export const spec = {
22
23
  name: 'share',
@@ -63,9 +64,9 @@ export async function run({ flags }, deps) {
63
64
  code: 'not_linked',
64
65
  fix: 'design-hub project link --studio <slug> --client <slug> --project <slug>, then share again.',
65
66
  });
66
- // The studio must agree with the link before anything is built, and its file store's token is the studio folder's.
67
+ // The studio must agree with the link before anything is built, and its file store must be its own (its mark).
67
68
  const { review, scope, client, studio } = await openLinked(deps, link);
68
- const files = deps.files(studio);
69
+ const files = await openFiles(deps, studio);
69
70
  const checked = await deps.preflight(flags.skip);
70
71
  if (!checked.ok)
71
72
  return {
@@ -56,9 +56,15 @@ export declare const spec: {
56
56
  readonly default: 'iad1';
57
57
  readonly description: 'For create: the file store’s region, the site’s function region.';
58
58
  };
59
+ readonly kv: {
60
+ readonly type: 'string';
61
+ readonly choices: readonly ["upstash", "postgres"];
62
+ readonly default: 'upstash';
63
+ readonly description: 'For create: the studio’s database. upstash: Upstash for Redis. postgres: Postgres, a new Neon database on its free plan, or with --database any Postgres the team has from the Vercel Marketplace (Neon, Supabase). Kept in studio.json; a rerun must give the same.';
64
+ };
59
65
  readonly database: {
60
66
  readonly type: 'string';
61
- readonly description: 'For create: the name of a database (Upstash for Redis) the team already has and no studio uses, connected to the studio in place of a new one. A database serves one studio only: create marks it as this studio’s, and refuses one that is another studio’s or already holds a studio’s data, before writing to it, disconnecting it again and keeping none of its credentials. Absent, a new one is made, only ever on the free plan; a team refused the free plan stops here with nothing bought.';
67
+ readonly description: 'For create: the name of a database (of the --kv kind) the team already has and no studio uses, connected to the studio in place of a new one. A database serves one studio only: create marks it as this studio’s, and refuses one that is another studio’s or already holds a studio’s data, before writing to it, disconnecting it again and keeping none of its credentials. Absent, a new one is made, only ever on the free plan; a team refused the free plan stops here with nothing bought.';
62
68
  };
63
69
  readonly package: {
64
70
  readonly type: 'string';
@@ -69,7 +75,7 @@ export declare const spec: {
69
75
  readonly description: 'For deploy: the studio’s slug. Absent, the studio folder this runs in.';
70
76
  };
71
77
  };
72
- readonly output: 'create: { ok, studio, dir, folder, list, package, vercel, env: { GATE_SECRET: set | kept, database: created | connected | kept, files: created | kept, pulled }, mark: claimed | kept (the database marked as this studio’s), dns, owner, deployment, removed, studioHost: { host, state: ready | waiting, error?, fix?, record? }, link? (the owner’s, on the studio’s host, the run it first answers), next }. deploy: { ok, studio, package, deployment, removed, studioHost, link? }. The deploy is done whatever studioHost says; while it is waiting, its fix says what to do (a record to add, a certificate still coming) and the next deploy finishes it. package is what the folder’s package.json names for @milesroxas/design-hub. link: { ok, studio, dir, list, env, warnings }';
78
+ readonly output: 'create: { ok, studio, dir, folder, list, package, vercel, env: { GATE_SECRET: set | kept, database: created | connected | kept, files: created | kept, pulled }, mark: claimed | kept (the database marked as this studio’s), filesMark: claimed | kept (the file store, the same), dns, owner, deployment, removed, studioHost: { host, state: ready | waiting, error?, fix?, record? }, link? (the owner’s, on the studio’s host, the run it first answers), next }. deploy: { ok, studio, package, deployment, removed, studioHost, link? }. The deploy is done whatever studioHost says; while it is waiting, its fix says what to do (a record to add, a certificate still coming) and the next deploy finishes it. package is what the folder’s package.json names for @milesroxas/design-hub. link: { ok, studio, dir, list, env, warnings }';
73
79
  };
74
80
  export declare function run({ positionals: [action], flags }: Args<typeof spec>, deps: StudioDeps): Promise<Record<string, unknown>>;
75
81
  export declare const main: (args: Args<typeof spec>) => Promise<Record<string, unknown>>;
@@ -22,14 +22,14 @@ import { copyFileSync, cpSync, existsSync, readdirSync, readFileSync, renameSync
22
22
  import { basename, join, resolve } from 'node:path';
23
23
  import { readEnv, removeEnv, writeEnv } from '../server/env.js';
24
24
  import { localStudio } from '../server/local.js';
25
- import { claimDatabase, MarkError } from '../server/mark.js';
25
+ import { claimDatabase, claimFiles, MarkError } from '../server/mark.js';
26
26
  import { PACKAGE, TEMPLATES } from '../server/paths.js';
27
27
  import { CliError } from './lib/cli.js';
28
28
  import { keepingGitignore } from './lib/deploy.js';
29
29
  import { pointHost, waitServed } from './lib/dns.js';
30
30
  import { deployAlone } from './lib/host.js';
31
31
  import { openReview, realDeps } from './lib/studio-deps.js';
32
- import { addToList, BLOB_NAME, CLOUDFLARE_NAME, DNS_PROVIDERS, findStudio, MODE_OF, readStudio, STORE_NAMES, STUDIO_FILE, studioHost, studioProblems, writeStudio, } from './lib/studios.js';
32
+ import { addToList, BLOB_NAME, CLOUDFLARE_NAME, DNS_PROVIDERS, findStudio, hasStore, KV_PROVIDERS, MODE_OF, readStudio, STORE_NAMES, STUDIO_FILE, studioHost, studioProblems, writeStudio, } from './lib/studios.js';
33
33
  export const spec = {
34
34
  name: 'studio',
35
35
  summary: 'Create a studio (its folder, its site on a Vercel team, its stores), deploy it again, or list an existing studio folder on this machine.',
@@ -78,9 +78,15 @@ export const spec = {
78
78
  default: 'iad1',
79
79
  description: 'For create: the file store’s region, the site’s function region.',
80
80
  },
81
+ kv: {
82
+ type: 'string',
83
+ choices: KV_PROVIDERS,
84
+ default: 'upstash',
85
+ description: 'For create: the studio’s database. upstash: Upstash for Redis. postgres: Postgres, a new Neon database on its free plan, or with --database any Postgres the team has from the Vercel Marketplace (Neon, Supabase). Kept in studio.json; a rerun must give the same.',
86
+ },
81
87
  database: {
82
88
  type: 'string',
83
- description: 'For create: the name of a database (Upstash for Redis) the team already has and no studio uses, connected to the studio in place of a new one. A database serves one studio only: create marks it as this studio’s, and refuses one that is another studio’s or already holds a studio’s data, before writing to it, disconnecting it again and keeping none of its credentials. Absent, a new one is made, only ever on the free plan; a team refused the free plan stops here with nothing bought.',
89
+ description: 'For create: the name of a database (of the --kv kind) the team already has and no studio uses, connected to the studio in place of a new one. A database serves one studio only: create marks it as this studio’s, and refuses one that is another studio’s or already holds a studio’s data, before writing to it, disconnecting it again and keeping none of its credentials. Absent, a new one is made, only ever on the free plan; a team refused the free plan stops here with nothing bought.',
84
90
  },
85
91
  package: {
86
92
  type: 'string',
@@ -91,7 +97,7 @@ export const spec = {
91
97
  description: 'For deploy: the studio’s slug. Absent, the studio folder this runs in.',
92
98
  },
93
99
  },
94
- output: 'create: { ok, studio, dir, folder, list, package, vercel, env: { GATE_SECRET: set | kept, database: created | connected | kept, files: created | kept, pulled }, mark: claimed | kept (the database marked as this studio’s), dns, owner, deployment, removed, studioHost: { host, state: ready | waiting, error?, fix?, record? }, link? (the owner’s, on the studio’s host, the run it first answers), next }. deploy: { ok, studio, package, deployment, removed, studioHost, link? }. The deploy is done whatever studioHost says; while it is waiting, its fix says what to do (a record to add, a certificate still coming) and the next deploy finishes it. package is what the folder’s package.json names for @milesroxas/design-hub. link: { ok, studio, dir, list, env, warnings }',
100
+ output: 'create: { ok, studio, dir, folder, list, package, vercel, env: { GATE_SECRET: set | kept, database: created | connected | kept, files: created | kept, pulled }, mark: claimed | kept (the database marked as this studio’s), filesMark: claimed | kept (the file store, the same), dns, owner, deployment, removed, studioHost: { host, state: ready | waiting, error?, fix?, record? }, link? (the owner’s, on the studio’s host, the run it first answers), next }. deploy: { ok, studio, package, deployment, removed, studioHost, link? }. The deploy is done whatever studioHost says; while it is waiting, its fix says what to do (a record to add, a certificate still coming) and the next deploy finishes it. package is what the folder’s package.json names for @milesroxas/design-hub. link: { ok, studio, dir, list, env, warnings }',
95
101
  };
96
102
  const need = (value, flag, action) => {
97
103
  if (!value)
@@ -109,7 +115,7 @@ function configFrom(flags) {
109
115
  vercel: { team: need(flags.team, 'team', 'create'), project: flags.project ?? flags.slug ?? '' },
110
116
  dns: { provider, mode: MODE_OF[provider], zone: flags.zone ?? null },
111
117
  owner: null,
112
- providers: { kv: 'upstash', files: 'vercel-blob', host: 'vercel' },
118
+ providers: { kv: (flags.kv ?? 'upstash'), files: 'vercel-blob', host: 'vercel' },
113
119
  };
114
120
  need(flags.owner, 'owner', 'create');
115
121
  const problems = studioProblems(config);
@@ -129,6 +135,7 @@ function sameStudio(kept, asked) {
129
135
  ['team', kept.vercel.team, asked.vercel.team],
130
136
  ['project', kept.vercel.project, asked.vercel.project],
131
137
  ['dns', kept.dns.provider, asked.dns.provider],
138
+ ['kv', kept.providers.kv, asked.providers.kv],
132
139
  ];
133
140
  const differs = pairs.filter(([, a, b]) => a !== b).map(([flag]) => flag);
134
141
  if (differs.length)
@@ -242,15 +249,22 @@ function tokenFrom(file) {
242
249
  throw new CliError('--cloudflare-token-file does not hold one API token on one line.', { got: file });
243
250
  return token;
244
251
  }
245
- /** The store and file credentials the CLI needs, read back from Production into .env where missing. */
246
- async function pullMissing(dir, host) {
252
+ /**
253
+ * The store and file credentials the CLI needs, read back from Production
254
+ * into .env where missing: the database's names of the studio's kind (for
255
+ * Postgres, whichever of DATABASE_URL and POSTGRES_URL the site has) and the
256
+ * file store's token.
257
+ */
258
+ async function pullMissing(dir, host, kind) {
247
259
  const env = readEnv(dir);
248
- const missing = [...STORE_NAMES, BLOB_NAME].filter((n) => !env[n]);
260
+ const store = hasStore(kind, (n) => !!env[n]) ? [] : STORE_NAMES[kind].filter((n) => !env[n]);
261
+ const missing = [...store, ...(env[BLOB_NAME] ? [] : [BLOB_NAME])];
249
262
  if (!missing.length)
250
263
  return [];
251
264
  const values = await host.pullEnv(missing);
252
265
  writeEnv(dir, values);
253
- const still = missing.filter((n) => !values[n]);
266
+ const now = { ...env, ...values };
267
+ const still = [...(hasStore(kind, (n) => !!now[n]) ? [] : store), ...(now[BLOB_NAME] ? [] : [BLOB_NAME])];
254
268
  if (still.length)
255
269
  throw new CliError(`Could not read ${still.join(', ')} back from the studio's Production env.`, {
256
270
  fix: 'Copy them from the store’s page on Vercel into the studio’s .env, then run this again.',
@@ -294,14 +308,15 @@ async function wildcard(host, apex) {
294
308
  * database of its own starts clean.
295
309
  */
296
310
  async function claimOrLetGo(deps, host, studio, connected) {
311
+ const kind = studio.config.providers.kv;
297
312
  try {
298
313
  return await claimDatabase(deps.store(studio), studio);
299
314
  }
300
315
  catch (error) {
301
316
  if (!(error instanceof MarkError))
302
317
  throw error;
303
- removeEnv(studio.dir, STORE_NAMES);
304
- const gone = connected !== null && (await host.disconnectDatabase(connected));
318
+ removeEnv(studio.dir, STORE_NAMES[kind]);
319
+ const gone = connected !== null && (await host.disconnectDatabase(kind, connected));
305
320
  const { dir, config } = studio;
306
321
  const rerun = `then run design-hub studio create again in ${dir} with the same flags, without --database (a new free one) or with --database <a database no studio uses>.`;
307
322
  throw new CliError(error.message, {
@@ -398,16 +413,21 @@ async function create(flags, deps) {
398
413
  const pkg = installAndBuild(dir, deps);
399
414
  const host = deps.host(dir, config);
400
415
  const link = await keepingGitignore(dir, () => host.link(true));
416
+ const kind = config.providers.kv;
401
417
  const env = {
402
418
  GATE_SECRET: await gateSecret(dir, host),
403
- database: await host.provisionDatabase(flags.database),
419
+ database: await host.provisionDatabase(kind, flags.database),
404
420
  files: await host.provisionFiles(flags.region),
405
- pulled: await pullMissing(dir, host),
421
+ pulled: await pullMissing(dir, host, kind),
406
422
  };
407
423
  const studio = { dir, config };
424
+ // Postgres's table, made here and only here, never by a visitor's request.
425
+ await deps.prepareStore(studio);
408
426
  // Before anything is written to the database: it serves this studio only, or nothing goes on.
409
427
  const connected = env.database === 'connected' ? (flags.database ?? null) : null;
410
428
  const mark = await claimOrLetGo(deps, host, studio, connected);
429
+ // The file store too: one marked as another studio's is refused before a file is written.
430
+ const filesMark = await claimFiles(deps.files(studio), studio);
411
431
  const dns = { provider: config.dns.provider, mode: config.dns.mode };
412
432
  if (config.dns.mode === 'wildcard')
413
433
  dns.wildcard = await wildcard(host, config.apex);
@@ -431,6 +451,7 @@ async function create(flags, deps) {
431
451
  vercel: { team: config.vercel.team, project: config.vercel.project, link },
432
452
  env,
433
453
  mark,
454
+ filesMark,
434
455
  dns,
435
456
  owner: config.owner,
436
457
  ...deployed,
@@ -446,6 +467,9 @@ async function deploy(flags, deps) {
446
467
  namePackage(dir, tgz);
447
468
  const pkg = installAndBuild(dir, deps);
448
469
  const studio = { dir, config };
470
+ // A Postgres studio's table, made or closed to other roles again, so an upgrade applies what a newer package needs.
471
+ if (config.providers.kv === 'postgres')
472
+ await deps.prepareStore(studio);
449
473
  const host = deps.host(dir, config);
450
474
  const deployed = await deployAlone(host);
451
475
  // For a studio made before it had one, the owner's first link on the studio's host comes the run it answers.
@@ -469,7 +493,7 @@ async function link(flags, deps) {
469
493
  // folder can hold a full .env and no link, and a deploy follows the link.
470
494
  const host = deps.host(dir, config);
471
495
  await keepingGitignore(dir, () => host.link(false));
472
- const pulled = await pullMissing(dir, host);
496
+ const pulled = await pullMissing(dir, host, config.providers.kv);
473
497
  const warnings = config.dns.provider === 'cloudflare' && !readEnv(dir)[CLOUDFLARE_NAME]
474
498
  ? [
475
499
  `No ${CLOUDFLARE_NAME} in .env: client add needs it, and studio deploy until studio.${config.apex} answers. Run this again with --cloudflare-token-file <file>.`,
@@ -21,11 +21,12 @@ export type Deployed = {
21
21
  error: string;
22
22
  };
23
23
  /**
24
- * A studio site's review service: Upstash for the store, Jev for triage
25
- * when its key is set and `checks` is given. `now` is the clock, so the gate
26
- * and the service it asks run on one (the gate's tests move it). Without the
27
- * gate's secret or the store, the cause goes to the site's log and a visitor
28
- * gets SITE_NOT_SET_UP.
24
+ * A studio site's review service: the store its env names (chooseStore:
25
+ * Upstash or Postgres, never a guess between them), Jev for triage when its
26
+ * key is set and `checks` is given. `now` is the clock, so the gate and the
27
+ * service it asks run on one (the gate's tests move it). Without the gate's
28
+ * secret or one store, the cause goes to the site's log and a visitor gets
29
+ * SITE_NOT_SET_UP.
29
30
  */
30
31
  export declare function studioReview(env: Record<string, string | undefined>, checks?: Checks | null, now?: () => Date): Deployed;
31
32
  /**