@milesroxas/design-hub 0.11.2 → 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.
- package/README.md +8 -6
- package/core/prototype.test.ts +52 -0
- package/core/prototype.ts +59 -0
- package/core/review/model.ts +20 -0
- package/core/review/service.test.ts +262 -37
- package/core/review/service.ts +276 -52
- package/core/review/store.ts +12 -6
- package/core/review/suite-kv.ts +17 -0
- package/dist/core/prototype.d.ts +50 -0
- package/dist/core/prototype.js +38 -0
- package/dist/core/review/model.d.ts +22 -0
- package/dist/core/review/model.js +8 -0
- package/dist/core/review/service.d.ts +98 -18
- package/dist/core/review/service.js +248 -46
- package/dist/core/review/store.d.ts +10 -4
- package/dist/core/review/store.js +2 -2
- package/dist/core/review/suite-kv.d.ts +7 -0
- package/dist/core/review/suite-kv.js +12 -0
- package/dist/scripts/client.d.ts +3 -3
- package/dist/scripts/client.js +55 -69
- package/dist/scripts/lib/cli.js +5 -0
- package/dist/scripts/lib/dns.d.ts +32 -0
- package/dist/scripts/lib/dns.js +69 -1
- package/dist/scripts/lib/fake-host.d.ts +35 -11
- package/dist/scripts/lib/fake-host.js +27 -13
- package/dist/scripts/lib/host.d.ts +13 -25
- package/dist/scripts/lib/host.js +15 -324
- package/dist/scripts/lib/studio-deps.d.ts +16 -0
- package/dist/scripts/lib/studio-deps.js +41 -16
- package/dist/scripts/lib/studios.d.ts +17 -5
- package/dist/scripts/lib/studios.js +25 -5
- package/dist/scripts/lib/vercel-host.d.ts +17 -0
- package/dist/scripts/lib/vercel-host.js +410 -0
- package/dist/scripts/people.d.ts +7 -4
- package/dist/scripts/people.js +147 -39
- package/dist/scripts/share.js +3 -2
- package/dist/scripts/studio.d.ts +10 -4
- package/dist/scripts/studio.js +136 -22
- package/dist/server/api.d.ts +12 -13
- package/dist/server/api.js +141 -52
- package/dist/server/gate.d.ts +97 -0
- package/dist/server/gate.js +537 -0
- package/dist/server/hosts.d.ts +3 -3
- package/dist/server/hosts.js +10 -10
- package/dist/server/mark.d.ts +17 -0
- package/dist/server/mark.js +46 -1
- package/dist/server/session.d.ts +9 -1
- package/dist/server/session.js +10 -3
- package/dist/server/stores/backends.d.ts +22 -0
- package/dist/server/stores/backends.js +96 -0
- package/dist/server/{fake-upstash.js → stores/fake-upstash.js} +1 -1
- package/dist/server/stores/index.d.ts +41 -0
- package/dist/server/stores/index.js +63 -0
- package/dist/server/stores/pglite.d.ts +16 -0
- package/dist/server/stores/pglite.js +98 -0
- package/dist/server/stores/postgres.d.ts +63 -0
- package/dist/server/stores/postgres.js +153 -0
- package/dist/server/{upstash.d.ts → stores/upstash.d.ts} +1 -1
- package/dist/vercel/files.js +1 -1
- package/dist/vercel/proxy.d.ts +6 -78
- package/dist/vercel/proxy.js +18 -359
- package/dist/vite/plugin.d.ts +6 -2
- package/dist/vite/plugin.js +22 -4
- package/package.json +3 -1
- package/shell/Index.tsx +29 -0
- package/shell/review/People.tsx +79 -49
- package/shell/review/Review.tsx +49 -1
- package/shell/review/ThreadCard.tsx +13 -1
- package/shell/review/client.ts +54 -21
- package/shell/review/review.css +1 -0
- package/shell/review/unsent.test.ts +63 -0
- package/shell/review/unsent.ts +64 -0
- package/shell/review/view.ts +22 -6
- package/shell/studio/ClientHub.tsx +9 -36
- package/shell/studio/StudioHub.tsx +293 -0
- package/shell/studio/hub.css +80 -5
- package/shell/studio/page.tsx +57 -0
- package/shell/studio/studio.html +14 -0
- package/shell/studio/studio.tsx +19 -0
- package/skills/miles-deploy/SKILL.md +17 -6
- package/skills/miles-design-hub/SKILL.md +3 -3
- package/skills/miles-review/SKILL.md +1 -1
- package/templates/studio/.env.example +3 -0
- package/templates/studio/README.md +45 -13
- package/templates/studio/package.json +1 -1
- /package/dist/server/{fake-upstash.d.ts → stores/fake-upstash.d.ts} +0 -0
- /package/dist/server/{upstash.js → stores/upstash.js} +0 -0
package/dist/server/mark.js
CHANGED
|
@@ -31,7 +31,7 @@ export class MarkError extends Error {
|
|
|
31
31
|
}
|
|
32
32
|
/** What every refusal says: whose database this must be, and how to give the studio one of its own. */
|
|
33
33
|
function ownDatabase({ dir, config }) {
|
|
34
|
-
return `A database serves one studio only; never connect one another studio uses. On team ${config.vercel.team}'s Storage page on Vercel, disconnect this one from project ${config.vercel.project},
|
|
34
|
+
return `A database serves one studio only; never connect one another studio uses. On team ${config.vercel.team}'s Storage page on Vercel, disconnect this one from project ${config.vercel.project}, take its names (KV_REST_API_URL and KV_REST_API_TOKEN, or DATABASE_URL and POSTGRES_URL) out of ${join(dir, '.env')}, 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>.`;
|
|
35
35
|
}
|
|
36
36
|
/**
|
|
37
37
|
* Whether a database marked as no studio's is free for this one: it holds no
|
|
@@ -109,3 +109,48 @@ export async function mustBeOwnDatabase(kv, studio) {
|
|
|
109
109
|
fix: ownDatabase(studio),
|
|
110
110
|
});
|
|
111
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* The file store's mark: one file at a fixed path, outside every client's
|
|
114
|
+
* `c/` folder, holding the id of the studio the store serves. No request
|
|
115
|
+
* reaches it: the studio site serves only paths under a build.
|
|
116
|
+
*/
|
|
117
|
+
export const FILES_MARK = 'studio/id.txt';
|
|
118
|
+
/**
|
|
119
|
+
* Marks the file store as this studio's, or finds it is: 'claimed' when it
|
|
120
|
+
* held no mark, 'kept' when the mark is this studio's id. A store marked by
|
|
121
|
+
* another studio is refused with nothing written. `studio create` runs this,
|
|
122
|
+
* and so does every command that writes or removes files (openFiles in
|
|
123
|
+
* scripts/lib/studio-deps.ts), so a store from before the mark gets it on
|
|
124
|
+
* its first use. Two at once: the store never overwrites a file, so the
|
|
125
|
+
* second write fails and the mark is read again.
|
|
126
|
+
*/
|
|
127
|
+
export async function claimFiles(files, studio) {
|
|
128
|
+
const { id, slug } = studio.config;
|
|
129
|
+
if (!id)
|
|
130
|
+
throw new Error('A studio is given its id before its file store is claimed.');
|
|
131
|
+
const read = async () => {
|
|
132
|
+
const found = await files.get(FILES_MARK);
|
|
133
|
+
return found ? (await new Response(found.body).text()).trim() : null;
|
|
134
|
+
};
|
|
135
|
+
const mark = await read();
|
|
136
|
+
if (mark === id)
|
|
137
|
+
return 'kept';
|
|
138
|
+
if (mark === null) {
|
|
139
|
+
try {
|
|
140
|
+
await files.put(FILES_MARK, new TextEncoder().encode(id), 'text/plain; charset=utf-8');
|
|
141
|
+
return 'claimed';
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
const now = await read();
|
|
145
|
+
if (now === id)
|
|
146
|
+
return 'kept';
|
|
147
|
+
if (now === null)
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
throw new MarkError(`The file store in studio ${slug}'s .env is another studio's; nothing was changed.`, {
|
|
152
|
+
code: 'files_not_this_studios',
|
|
153
|
+
studio: slug,
|
|
154
|
+
fix: `A file store serves one studio only. Put this studio's own BLOB_READ_WRITE_TOKEN in ${join(studio.dir, '.env')} (design-hub studio link --dir ${studio.dir} reads it back from the site's Production env), then run this again.`,
|
|
155
|
+
});
|
|
156
|
+
}
|
package/dist/server/session.d.ts
CHANGED
|
@@ -3,7 +3,8 @@ export declare const PERSON_COOKIE = "__Host-hub_person";
|
|
|
3
3
|
/** How long the store's last yes is trusted before the gate asks again. */
|
|
4
4
|
export declare const CHECK_SECONDS: number;
|
|
5
5
|
/**
|
|
6
|
-
* `site` is the review store's
|
|
6
|
+
* `site` is the review store's address: Upstash's URL, or Postgres's host,
|
|
7
|
+
* port and database with no credential (server/stores/). It is signed into every token, so two
|
|
7
8
|
* studios that share one GATE_SECRET (a copied folder keeps its .env) never
|
|
8
9
|
* accept each other's cookies.
|
|
9
10
|
* `client` is the client of the host the gate answers, or `studio` for the
|
|
@@ -21,6 +22,13 @@ export type Gate = {
|
|
|
21
22
|
};
|
|
22
23
|
/** What the studio's env gives every gate: the secret and the store it signs to. The host gives the rest. */
|
|
23
24
|
export type GateKeys = Pick<Gate, 'secret' | 'site'>;
|
|
25
|
+
/**
|
|
26
|
+
* The gate on the studio's own host (`studio.<apex>`): its tokens are signed
|
|
27
|
+
* to `studio`, which no client's slug is, so none verifies on a client's
|
|
28
|
+
* host and no client's verifies here. The studio's host is never archived
|
|
29
|
+
* and added again, so it has no `since` to tell two apart.
|
|
30
|
+
*/
|
|
31
|
+
export declare const studioGate: (keys: GateKeys) => Gate;
|
|
24
32
|
/** The gate's keys, or null when GATE_SECRET is missing or short (the gate then fails closed). */
|
|
25
33
|
export declare function readGate(env: Record<string, string | undefined>): GateKeys | null;
|
|
26
34
|
/**
|
package/dist/server/session.js
CHANGED
|
@@ -14,16 +14,23 @@
|
|
|
14
14
|
// Every function that reads the clock takes `at`, so tests need not wait.
|
|
15
15
|
import { base64url } from '../core/bytes.js';
|
|
16
16
|
import { SLUG } from '../core/feature.js';
|
|
17
|
-
import { PERSON_KINDS } from '../core/review/model.js';
|
|
17
|
+
import { PERSON_KINDS, STUDIO_SITE } from '../core/review/model.js';
|
|
18
|
+
import { storeSite } from './stores/index.js';
|
|
18
19
|
export const PERSON_COOKIE = '__Host-hub_person';
|
|
19
20
|
const MAX_SESSION_SECONDS = 60 * 60 * 24 * 400;
|
|
20
21
|
/** How long the store's last yes is trusted before the gate asks again. */
|
|
21
22
|
export const CHECK_SECONDS = 5 * 60;
|
|
23
|
+
/**
|
|
24
|
+
* The gate on the studio's own host (`studio.<apex>`): its tokens are signed
|
|
25
|
+
* to `studio`, which no client's slug is, so none verifies on a client's
|
|
26
|
+
* host and no client's verifies here. The studio's host is never archived
|
|
27
|
+
* and added again, so it has no `since` to tell two apart.
|
|
28
|
+
*/
|
|
29
|
+
export const studioGate = (keys) => ({ ...keys, client: STUDIO_SITE, since: '' });
|
|
22
30
|
/** The gate's keys, or null when GATE_SECRET is missing or short (the gate then fails closed). */
|
|
23
31
|
export function readGate(env) {
|
|
24
32
|
const secret = env.GATE_SECRET ?? '';
|
|
25
|
-
|
|
26
|
-
return secret.length >= 32 ? { secret, site } : null;
|
|
33
|
+
return secret.length >= 32 ? { secret, site: storeSite(env) } : null;
|
|
27
34
|
}
|
|
28
35
|
const encoder = new TextEncoder();
|
|
29
36
|
async function hmac(secret, message) {
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export type TestStore = {
|
|
2
|
+
name: 'upstash' | 'postgres';
|
|
3
|
+
/** The env names that point a site at this store. */
|
|
4
|
+
env: Record<string, string>;
|
|
5
|
+
/** The names of another store of the same kind: another site, the same rows. */
|
|
6
|
+
other: Record<string, string>;
|
|
7
|
+
/** A store of the other kind, which beside this one names two databases. */
|
|
8
|
+
rival: Record<string, string>;
|
|
9
|
+
/** Before each test: an empty store, answering. */
|
|
10
|
+
start(): Promise<void>;
|
|
11
|
+
/** After each test. */
|
|
12
|
+
stop(): void;
|
|
13
|
+
/** Every store call fails until `up`. */
|
|
14
|
+
down(): void;
|
|
15
|
+
up(): void;
|
|
16
|
+
/** From now on, every store call by its Redis name and key (`HGET hub4:…`), in order. */
|
|
17
|
+
watch(): string[];
|
|
18
|
+
};
|
|
19
|
+
/** For a test file that runs a suite on Postgres: call before the suite loads. */
|
|
20
|
+
export declare function onPostgres(): void;
|
|
21
|
+
/** The store the suites of this test file run on. */
|
|
22
|
+
export declare const testStore: () => TestStore;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
// The review store a studio site's tests run on, picked once per test file:
|
|
3
|
+
// the fake Upstash (by default) or the embedded Postgres, each reached the
|
|
4
|
+
// way the site reaches it, from the env, through chooseStore. A suite is
|
|
5
|
+
// written once against this and run on each: vercel/gate.postgres.test.ts
|
|
6
|
+
// picks Postgres, then loads the gate suite.
|
|
7
|
+
import { fakeUpstash } from './fake-upstash.js';
|
|
8
|
+
import { postgresThrough } from './index.js';
|
|
9
|
+
import { pgliteQuery } from './pglite.js';
|
|
10
|
+
import { createTable, STATEMENTS, TABLE } from './postgres.js';
|
|
11
|
+
/** The fake Upstash behind the global fetch, as the site's adapter calls it. */
|
|
12
|
+
function upstash() {
|
|
13
|
+
const real = globalThis.fetch;
|
|
14
|
+
let failing = false;
|
|
15
|
+
let seen = null;
|
|
16
|
+
let store = fakeUpstash();
|
|
17
|
+
return {
|
|
18
|
+
name: 'upstash',
|
|
19
|
+
env: { KV_REST_API_URL: 'https://kv.test', KV_REST_API_TOKEN: 't' },
|
|
20
|
+
other: { KV_REST_API_URL: 'https://kv-other.test', KV_REST_API_TOKEN: 't' },
|
|
21
|
+
rival: { DATABASE_URL: 'postgres://studio:pw@db.test/hub' },
|
|
22
|
+
async start() {
|
|
23
|
+
store = fakeUpstash();
|
|
24
|
+
failing = false;
|
|
25
|
+
seen = null;
|
|
26
|
+
globalThis.fetch = ((url, init) => {
|
|
27
|
+
if (failing)
|
|
28
|
+
return Promise.resolve(new Response('{"error":"down"}', { status: 500 }));
|
|
29
|
+
const [cmd, key] = JSON.parse(String(init?.body));
|
|
30
|
+
seen?.push(`${cmd} ${key}`);
|
|
31
|
+
return store(url, init);
|
|
32
|
+
});
|
|
33
|
+
},
|
|
34
|
+
stop() {
|
|
35
|
+
globalThis.fetch = real;
|
|
36
|
+
},
|
|
37
|
+
down() {
|
|
38
|
+
failing = true;
|
|
39
|
+
},
|
|
40
|
+
up() {
|
|
41
|
+
failing = false;
|
|
42
|
+
},
|
|
43
|
+
watch() {
|
|
44
|
+
seen = [];
|
|
45
|
+
return seen;
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** Which op a statement is, by the adapter's own SQL. */
|
|
50
|
+
const OPS = Object.entries(STATEMENTS).map(([op, text]) => [text.replace('$t', TABLE), op.toUpperCase()]);
|
|
51
|
+
/** The embedded Postgres behind every connection string, as the site's adapter queries it. */
|
|
52
|
+
function postgres() {
|
|
53
|
+
let failing = false;
|
|
54
|
+
let seen = null;
|
|
55
|
+
let query;
|
|
56
|
+
return {
|
|
57
|
+
name: 'postgres',
|
|
58
|
+
env: { DATABASE_URL: 'postgres://studio:pw@db.test/hub?sslmode=require' },
|
|
59
|
+
other: { DATABASE_URL: 'postgres://studio:pw@db-other.test/hub?sslmode=require' },
|
|
60
|
+
rival: { KV_REST_API_URL: 'https://kv.test' },
|
|
61
|
+
async start() {
|
|
62
|
+
query ??= await pgliteQuery();
|
|
63
|
+
const db = query;
|
|
64
|
+
failing = false;
|
|
65
|
+
seen = null;
|
|
66
|
+
await createTable(db);
|
|
67
|
+
await db(`TRUNCATE ${TABLE}`, []);
|
|
68
|
+
postgresThrough(() => async (text, params) => {
|
|
69
|
+
if (failing)
|
|
70
|
+
throw new Error('the store is down');
|
|
71
|
+
const op = OPS.find(([sql]) => sql === text)?.[1];
|
|
72
|
+
if (op)
|
|
73
|
+
seen?.push(`${op} ${params[0]}`);
|
|
74
|
+
return db(text, params);
|
|
75
|
+
});
|
|
76
|
+
},
|
|
77
|
+
stop() { },
|
|
78
|
+
down() {
|
|
79
|
+
failing = true;
|
|
80
|
+
},
|
|
81
|
+
up() {
|
|
82
|
+
failing = false;
|
|
83
|
+
},
|
|
84
|
+
watch() {
|
|
85
|
+
seen = [];
|
|
86
|
+
return seen;
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
let picked = 'upstash';
|
|
91
|
+
/** For a test file that runs a suite on Postgres: call before the suite loads. */
|
|
92
|
+
export function onPostgres() {
|
|
93
|
+
picked = 'postgres';
|
|
94
|
+
}
|
|
95
|
+
/** The store the suites of this test file run on. */
|
|
96
|
+
export const testStore = () => (picked === 'postgres' ? postgres() : upstash());
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
2
|
// A fetch that answers like Upstash's REST API from memory, for tests that
|
|
3
3
|
// exercise a studio site's code path (its gate and functions) without an account.
|
|
4
|
-
import { memoryKV } from '
|
|
4
|
+
import { memoryKV } from '../../core/review/store.js';
|
|
5
5
|
/** How many keys one SCAN call looks at: few, so a walk takes many calls, some of them finding nothing. */
|
|
6
6
|
const SCAN_PAGE = 2;
|
|
7
7
|
/** A Redis glob as a RegExp: `*`, `?`, `[…]`, and `\` before a character that stands for itself. */
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { KV } from '../../core/review/store.ts';
|
|
2
|
+
import { type Query } from './postgres.ts';
|
|
3
|
+
export type StoreKind = 'upstash' | 'postgres';
|
|
4
|
+
/**
|
|
5
|
+
* The store an env names: its kind, the site its tokens are signed to, how
|
|
6
|
+
* to open it, and how to make what it needs before its first write (the
|
|
7
|
+
* Postgres table), which only `studio create` runs.
|
|
8
|
+
*/
|
|
9
|
+
export type StoreChoice = {
|
|
10
|
+
kind: StoreKind;
|
|
11
|
+
site: string;
|
|
12
|
+
open(): KV;
|
|
13
|
+
prepare(): Promise<void>;
|
|
14
|
+
};
|
|
15
|
+
type Env = Record<string, string | undefined>;
|
|
16
|
+
/**
|
|
17
|
+
* How a connection string becomes a Query: the driver, one pool per string
|
|
18
|
+
* per instance, kept for the life of the instance so every request reuses
|
|
19
|
+
* its connections. Tests put an embedded Postgres here (postgresThrough).
|
|
20
|
+
*/
|
|
21
|
+
type Pool = Query & {
|
|
22
|
+
end?(): Promise<void>;
|
|
23
|
+
};
|
|
24
|
+
/** For tests: every connection string opens `to` from here on, until another call. */
|
|
25
|
+
export declare function postgresThrough(to: (url: string) => Pool): void;
|
|
26
|
+
/**
|
|
27
|
+
* Closes every pool this process opened, for a command once it is done: an
|
|
28
|
+
* idle connection would otherwise keep the process alive until it times out.
|
|
29
|
+
*/
|
|
30
|
+
export declare function closeStores(): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* The review store the env names, null when it names none, or why none can
|
|
33
|
+
* be opened: a store of each kind, or two Postgres databases. Nothing is
|
|
34
|
+
* connected until `open` is called.
|
|
35
|
+
*/
|
|
36
|
+
export declare function chooseStore(env: Env): StoreChoice | {
|
|
37
|
+
error: string;
|
|
38
|
+
} | null;
|
|
39
|
+
/** The site the env's store gives the gate to sign tokens to; empty when it names none, or two. */
|
|
40
|
+
export declare function storeSite(env: Env): string;
|
|
41
|
+
export {};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createTable, driverQuery, isPostgresUrl, postgresKV, postgresSite } from './postgres.js';
|
|
2
|
+
import { storeConfig, upstashKV } from './upstash.js';
|
|
3
|
+
/** The env names each kind of store is read from. */
|
|
4
|
+
const STORE_ENV = {
|
|
5
|
+
upstash: ['KV_REST_API_URL', 'KV_REST_API_TOKEN', 'UPSTASH_REDIS_REST_URL', 'UPSTASH_REDIS_REST_TOKEN'],
|
|
6
|
+
postgres: ['DATABASE_URL', 'POSTGRES_URL'],
|
|
7
|
+
};
|
|
8
|
+
let connect = driverQuery;
|
|
9
|
+
const pools = new Map();
|
|
10
|
+
const pool = (url) => pools.get(url) ?? pools.set(url, connect(url)).get(url);
|
|
11
|
+
/** For tests: every connection string opens `to` from here on, until another call. */
|
|
12
|
+
export function postgresThrough(to) {
|
|
13
|
+
connect = to;
|
|
14
|
+
pools.clear();
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Closes every pool this process opened, for a command once it is done: an
|
|
18
|
+
* idle connection would otherwise keep the process alive until it times out.
|
|
19
|
+
*/
|
|
20
|
+
export async function closeStores() {
|
|
21
|
+
const open = [...pools.values()];
|
|
22
|
+
pools.clear();
|
|
23
|
+
await Promise.all(open.map((p) => p.end?.()));
|
|
24
|
+
}
|
|
25
|
+
/** The Postgres connection string an env names, the names it was read from, or why it is refused. */
|
|
26
|
+
function postgresUrl(env) {
|
|
27
|
+
const [a, b] = STORE_ENV.postgres.map((name) => (isPostgresUrl(env[name]) ? env[name] : undefined));
|
|
28
|
+
if (a && b && postgresSite(a) !== postgresSite(b))
|
|
29
|
+
return { error: 'DATABASE_URL and POSTGRES_URL name two different databases.' };
|
|
30
|
+
const url = a ?? b;
|
|
31
|
+
return url ? { url } : null;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The review store the env names, null when it names none, or why none can
|
|
35
|
+
* be opened: a store of each kind, or two Postgres databases. Nothing is
|
|
36
|
+
* connected until `open` is called.
|
|
37
|
+
*/
|
|
38
|
+
export function chooseStore(env) {
|
|
39
|
+
const upstash = storeConfig(env);
|
|
40
|
+
const pg = postgresUrl(env);
|
|
41
|
+
if (pg && 'error' in pg)
|
|
42
|
+
return pg;
|
|
43
|
+
// An Upstash URL alone, with no token, still names a store: never a reason to take the Postgres one.
|
|
44
|
+
if ((upstash || env.KV_REST_API_URL || env.UPSTASH_REDIS_REST_URL) && pg)
|
|
45
|
+
return {
|
|
46
|
+
error: 'Both an Upstash store (KV_REST_API_URL) and a Postgres one (DATABASE_URL or POSTGRES_URL) are set, and a studio has one database.',
|
|
47
|
+
};
|
|
48
|
+
if (upstash)
|
|
49
|
+
return { kind: 'upstash', site: upstash.url, open: () => upstashKV(upstash), prepare: async () => { } };
|
|
50
|
+
if (pg)
|
|
51
|
+
return {
|
|
52
|
+
kind: 'postgres',
|
|
53
|
+
site: postgresSite(pg.url),
|
|
54
|
+
open: () => postgresKV(pool(pg.url)),
|
|
55
|
+
prepare: () => createTable(pool(pg.url)),
|
|
56
|
+
};
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
/** The site the env's store gives the gate to sign tokens to; empty when it names none, or two. */
|
|
60
|
+
export function storeSite(env) {
|
|
61
|
+
const chosen = chooseStore(env);
|
|
62
|
+
return chosen && 'site' in chosen ? chosen.site : '';
|
|
63
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { KV, Snapshot } from '../../core/review/store.ts';
|
|
2
|
+
import { type Query } from './postgres.ts';
|
|
3
|
+
/** The process's one embedded Postgres, as a Query. */
|
|
4
|
+
export declare function pgliteQuery(): Promise<Query>;
|
|
5
|
+
/**
|
|
6
|
+
* A store made at once and ready on its first call, so a test builds it
|
|
7
|
+
* where it built a memory store. `after` runs after every op, with its name
|
|
8
|
+
* and arguments, before the op answers.
|
|
9
|
+
*/
|
|
10
|
+
export declare function deferredKV(ready: Promise<KV>, after?: (op: keyof KV, args: string[]) => Promise<void>): KV;
|
|
11
|
+
/**
|
|
12
|
+
* The memory store's shape on the embedded Postgres: a store on a new table
|
|
13
|
+
* of its own, holding `initial`, that calls `onChange` with every key after
|
|
14
|
+
* each write, as memoryKV does.
|
|
15
|
+
*/
|
|
16
|
+
export declare function pgliteKV(initial?: Snapshot, onChange?: (s: Snapshot) => void): KV;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
// A real Postgres in this process (PGlite, Postgres compiled to WebAssembly),
|
|
3
|
+
// for the tests that run the Postgres adapter's own SQL with no server to
|
|
4
|
+
// install: the conformance suite, the gate's and the service's. Each store
|
|
5
|
+
// it hands out is a table of its own, so no test sees another's rows.
|
|
6
|
+
import { after } from 'node:test';
|
|
7
|
+
import { PGlite } from '@electric-sql/pglite';
|
|
8
|
+
import { createTable, postgresKV } from './postgres.js';
|
|
9
|
+
let db;
|
|
10
|
+
let tables = 0;
|
|
11
|
+
// Closed when the file's tests end, or it holds the process open for seconds after. Registered as
|
|
12
|
+
// the module loads, so on the file's root, never on whichever test happened to open it first.
|
|
13
|
+
after(async () => (await db)?.close());
|
|
14
|
+
/** The process's one embedded Postgres, as a Query. */
|
|
15
|
+
export async function pgliteQuery() {
|
|
16
|
+
db ??= PGlite.create();
|
|
17
|
+
const pg = await db;
|
|
18
|
+
return async (text, params) => {
|
|
19
|
+
const result = await pg.query(text, params);
|
|
20
|
+
return { rows: result.rows, count: result.affectedRows ?? 0 };
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** A new, empty table in the embedded Postgres, made, and its name. */
|
|
24
|
+
async function freshTable(query) {
|
|
25
|
+
const table = `kv_test_${++tables}`;
|
|
26
|
+
await createTable(query, table);
|
|
27
|
+
return table;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Every key, hash or set, as the memory store's Snapshot; a key with members
|
|
31
|
+
* is a set when `sets` names it. As in the memory store, a hash written to
|
|
32
|
+
* and emptied by hdel is still listed, empty, until del or delPrefix.
|
|
33
|
+
*/
|
|
34
|
+
async function snapshotOf(query, table, sets, hashes) {
|
|
35
|
+
const { rows } = await query(`SELECT key, field, value FROM ${table} ORDER BY key, field`, []);
|
|
36
|
+
const out = { hashes: Object.fromEntries([...hashes].map((k) => [k, {}])), sets: {} };
|
|
37
|
+
for (const { key, field, value } of rows) {
|
|
38
|
+
if (sets.has(key))
|
|
39
|
+
out.sets[key] = [...(out.sets[key] ?? []), field];
|
|
40
|
+
else
|
|
41
|
+
out.hashes[key] = { ...out.hashes[key], [field]: value };
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
const WRITES = ['hset', 'hdel', 'hsetnx', 'hincrby', 'sadd', 'del', 'delPrefix'];
|
|
46
|
+
const OPS = Object.keys(postgresKV(async () => ({ rows: [], count: 0 })));
|
|
47
|
+
/**
|
|
48
|
+
* A store made at once and ready on its first call, so a test builds it
|
|
49
|
+
* where it built a memory store. `after` runs after every op, with its name
|
|
50
|
+
* and arguments, before the op answers.
|
|
51
|
+
*/
|
|
52
|
+
export function deferredKV(ready, after) {
|
|
53
|
+
const kv = {};
|
|
54
|
+
for (const op of OPS)
|
|
55
|
+
kv[op] = async (...args) => {
|
|
56
|
+
const out = await (await ready)[op](...args);
|
|
57
|
+
await after?.(op, args);
|
|
58
|
+
return out;
|
|
59
|
+
};
|
|
60
|
+
return kv;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The memory store's shape on the embedded Postgres: a store on a new table
|
|
64
|
+
* of its own, holding `initial`, that calls `onChange` with every key after
|
|
65
|
+
* each write, as memoryKV does.
|
|
66
|
+
*/
|
|
67
|
+
export function pgliteKV(initial, onChange) {
|
|
68
|
+
const sets = new Set(Object.keys(initial?.sets ?? {}));
|
|
69
|
+
const hashes = new Set(Object.keys(initial?.hashes ?? {}));
|
|
70
|
+
const made = (async () => {
|
|
71
|
+
const query = await pgliteQuery();
|
|
72
|
+
const table = await freshTable(query);
|
|
73
|
+
const kv = postgresKV(query, table);
|
|
74
|
+
for (const [key, fields] of Object.entries(initial?.hashes ?? {}))
|
|
75
|
+
for (const [field, value] of Object.entries(fields))
|
|
76
|
+
await kv.hset(key, field, value);
|
|
77
|
+
for (const [key, members] of Object.entries(initial?.sets ?? {}))
|
|
78
|
+
for (const member of members)
|
|
79
|
+
await kv.sadd(key, member);
|
|
80
|
+
return { query, table, kv };
|
|
81
|
+
})();
|
|
82
|
+
return deferredKV(made.then((m) => m.kv), async (op, args) => {
|
|
83
|
+
if (op === 'sadd')
|
|
84
|
+
sets.add(args[0]);
|
|
85
|
+
if (op === 'hset' || op === 'hsetnx' || op === 'hincrby')
|
|
86
|
+
hashes.add(args[0]);
|
|
87
|
+
if (op === 'del')
|
|
88
|
+
hashes.delete(args[0]);
|
|
89
|
+
if (op === 'delPrefix')
|
|
90
|
+
for (const k of hashes)
|
|
91
|
+
if (k.startsWith(args[0]))
|
|
92
|
+
hashes.delete(k);
|
|
93
|
+
if (!onChange || !WRITES.includes(op))
|
|
94
|
+
return;
|
|
95
|
+
const { query, table } = await made;
|
|
96
|
+
onChange(await snapshotOf(query, table, sets, hashes));
|
|
97
|
+
});
|
|
98
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { KV } from '../../core/review/store.ts';
|
|
2
|
+
/** One statement with its parameters: the rows it returned and how many it changed. */
|
|
3
|
+
export type Query = (text: string, params: string[]) => Promise<{
|
|
4
|
+
rows: Record<string, string>[];
|
|
5
|
+
count: number;
|
|
6
|
+
}>;
|
|
7
|
+
/** The table a studio's store is, unless a test names its own. */
|
|
8
|
+
export declare const TABLE = "design_hub_kv";
|
|
9
|
+
/** The statements, by op: the adapter's whole SQL, in one place. `$t` is the table. */
|
|
10
|
+
export declare const STATEMENTS: {
|
|
11
|
+
readonly hget: 'SELECT value FROM $t WHERE key = $1 AND field = $2';
|
|
12
|
+
readonly hset: 'INSERT INTO $t (key, field, value) VALUES ($1, $2, $3) ON CONFLICT (key, field) DO UPDATE SET value = EXCLUDED.value';
|
|
13
|
+
readonly hdel: 'DELETE FROM $t WHERE key = $1 AND field = $2';
|
|
14
|
+
readonly hsetnx: 'INSERT INTO $t (key, field, value) VALUES ($1, $2, $3) ON CONFLICT (key, field) DO NOTHING RETURNING 1 AS won';
|
|
15
|
+
readonly hgetall: 'SELECT field, value FROM $t WHERE key = $1';
|
|
16
|
+
readonly hincrby: 'INSERT INTO $t AS t (key, field, value) VALUES ($1, $2, ($3::bigint)::text) ON CONFLICT (key, field) DO UPDATE SET value = (t.value::bigint + $3::bigint)::text RETURNING value';
|
|
17
|
+
readonly sadd: "INSERT INTO $t (key, field, value) VALUES ($1, $2, '') ON CONFLICT (key, field) DO NOTHING";
|
|
18
|
+
readonly smembers: 'SELECT field FROM $t WHERE key = $1';
|
|
19
|
+
readonly del: 'DELETE FROM $t WHERE key = $1';
|
|
20
|
+
readonly delPrefix: "DELETE FROM $t WHERE key LIKE $1 ESCAPE '\\'";
|
|
21
|
+
};
|
|
22
|
+
/** The prefix as a LIKE pattern that matches only keys starting with its own text: `\`, `%` and `_` stand for themselves. */
|
|
23
|
+
export declare const likePrefix: (prefix: string) => string;
|
|
24
|
+
/**
|
|
25
|
+
* Makes the table when it is not there, and closes it to every role but its
|
|
26
|
+
* owner: row level security on, with no policy. The owner, the role the
|
|
27
|
+
* adapter connects as, is not subject to it; any other role reads and writes
|
|
28
|
+
* nothing, whatever it was granted. That matters on Supabase, whose default
|
|
29
|
+
* grants give every new table in `public` to `anon` and serve it over the
|
|
30
|
+
* project's Data API to anyone with its anon key. Both steps hold for a table
|
|
31
|
+
* already there, so `studio deploy` closes one made before. Run by `studio
|
|
32
|
+
* create` and `studio deploy`, the setup path, never by a visitor's request:
|
|
33
|
+
* the gate and the functions only read and write rows.
|
|
34
|
+
*/
|
|
35
|
+
export declare function createTable(query: Query, table?: string): Promise<void>;
|
|
36
|
+
export declare function postgresKV(query: Query, table?: string): KV;
|
|
37
|
+
export declare const isPostgresUrl: (url: string | undefined) => url is string;
|
|
38
|
+
/**
|
|
39
|
+
* Which database a connection string names, with no credential in it:
|
|
40
|
+
* `postgres://<host>:<port>/<database>`. The gate signs it into every token
|
|
41
|
+
* (server/session.ts), as it does Upstash's URL, so two studios with one
|
|
42
|
+
* GATE_SECRET never take each other's cookies.
|
|
43
|
+
*/
|
|
44
|
+
export declare function postgresSite(url: string): string;
|
|
45
|
+
/**
|
|
46
|
+
* TLS for a connection: always for a host other than this machine, whatever
|
|
47
|
+
* the string says, verified against the system's authorities when its
|
|
48
|
+
* `sslmode` is verify-full or verify-ca, and otherwise encrypted unverified,
|
|
49
|
+
* as libpq does for `sslmode=require` (what Neon's and Supabase's strings
|
|
50
|
+
* say). This machine's own server is plain unless the string asks for TLS.
|
|
51
|
+
*/
|
|
52
|
+
export declare function tlsFor(url: string): false | 'require' | 'verify-full';
|
|
53
|
+
/**
|
|
54
|
+
* A Query on the driver (postgres.js) for one connection string. The string's
|
|
55
|
+
* query parameters are dropped (the driver would send `channel_binding` and
|
|
56
|
+
* the like to the server as settings) and TLS set by tlsFor. Unnamed
|
|
57
|
+
* statements only (`prepare: false`), so a transaction-mode pooler can run
|
|
58
|
+
* each on any server connection; no type lookup on connect; no notices
|
|
59
|
+
* printed, since a command's stdout is its one JSON object.
|
|
60
|
+
*/
|
|
61
|
+
export declare function driverQuery(url: string): Query & {
|
|
62
|
+
end(): Promise<void>;
|
|
63
|
+
};
|