@designtools/comments 0.0.0-stage → 0.1.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/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +145 -2
- package/dist/adapter.d.ts +45 -0
- package/dist/adapter.js +177 -0
- package/dist/api.d.ts +20 -0
- package/dist/api.js +35 -0
- package/dist/cli.d.ts +19 -0
- package/dist/cli.js +216 -0
- package/dist/comments.d.ts +24 -0
- package/dist/comments.js +567 -0
- package/dist/css.d.ts +2 -0
- package/dist/css.js +2 -0
- package/dist/identity.d.ts +6 -0
- package/dist/identity.js +66 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/server/handler.d.ts +45 -0
- package/dist/server/handler.js +169 -0
- package/dist/server/index.d.ts +11 -0
- package/dist/server/index.js +10 -0
- package/dist/server/memory.d.ts +6 -0
- package/dist/server/memory.js +81 -0
- package/dist/server/migrations.d.ts +17 -0
- package/dist/server/migrations.js +61 -0
- package/dist/server/postgres.d.ts +7 -0
- package/dist/server/postgres.js +100 -0
- package/dist/server/sql.d.ts +14 -0
- package/dist/server/sql.js +36 -0
- package/dist/types.d.ts +112 -0
- package/dist/types.js +5 -0
- package/dist/validate.d.ts +40 -0
- package/dist/validate.js +144 -0
- package/package.json +80 -3
package/dist/identity.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who's commenting, on trust: a name typed once and a random id, kept by this browser. Nothing
|
|
3
|
+
* checks them; Vercel's protection decides who can open the preview at all.
|
|
4
|
+
*/
|
|
5
|
+
import { useCallback, useSyncExternalStore } from "react";
|
|
6
|
+
const KEY = "designtools:comments:author";
|
|
7
|
+
const listeners = new Set();
|
|
8
|
+
let cached = null;
|
|
9
|
+
// where the author is kept when the browser won't store it (blocked site data): for this page's life
|
|
10
|
+
let memory = null;
|
|
11
|
+
function storage() {
|
|
12
|
+
try {
|
|
13
|
+
return typeof window === "undefined" ? null : window.localStorage;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function newId() {
|
|
20
|
+
return typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
21
|
+
}
|
|
22
|
+
/** The remembered author, or null before a name has been given. */
|
|
23
|
+
export function readAuthor() {
|
|
24
|
+
let raw = null;
|
|
25
|
+
try {
|
|
26
|
+
raw = storage()?.getItem(KEY) ?? null;
|
|
27
|
+
}
|
|
28
|
+
catch { }
|
|
29
|
+
if (cached && cached.raw === raw && cached.memory === memory)
|
|
30
|
+
return cached.author;
|
|
31
|
+
let author = null;
|
|
32
|
+
try {
|
|
33
|
+
const parsed = raw ? JSON.parse(raw) : null;
|
|
34
|
+
if (parsed && typeof parsed.name === "string" && parsed.name.trim() && typeof parsed.id === "string" && parsed.id)
|
|
35
|
+
author = { name: parsed.name, id: parsed.id };
|
|
36
|
+
}
|
|
37
|
+
catch { }
|
|
38
|
+
author ??= memory;
|
|
39
|
+
cached = { raw, memory, author };
|
|
40
|
+
return author;
|
|
41
|
+
}
|
|
42
|
+
/** Remember a name, keeping the id this browser already has. Kept in memory when storage is blocked. */
|
|
43
|
+
export function rememberName(name) {
|
|
44
|
+
const author = { name: name.trim(), id: readAuthor()?.id ?? newId() };
|
|
45
|
+
memory = author;
|
|
46
|
+
try {
|
|
47
|
+
storage()?.setItem(KEY, JSON.stringify(author));
|
|
48
|
+
}
|
|
49
|
+
catch { }
|
|
50
|
+
for (const l of listeners)
|
|
51
|
+
l();
|
|
52
|
+
return author;
|
|
53
|
+
}
|
|
54
|
+
function subscribe(cb) {
|
|
55
|
+
listeners.add(cb);
|
|
56
|
+
const onStorage = (e) => e.key === KEY && cb();
|
|
57
|
+
window.addEventListener("storage", onStorage);
|
|
58
|
+
return () => {
|
|
59
|
+
listeners.delete(cb);
|
|
60
|
+
window.removeEventListener("storage", onStorage);
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
export function useAuthor() {
|
|
64
|
+
const author = useSyncExternalStore(subscribe, readAuthor, () => null);
|
|
65
|
+
return [author, useCallback(rememberName, [])];
|
|
66
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { type Anchor, type AnchorAdapter, anchorName, cssPath, defaultAdapter, genericLabel, humanize } from "./adapter.js";
|
|
2
|
+
export { CommentsError, commentsApi, type CommentsApi } from "./api.js";
|
|
3
|
+
export { Comments, type CommentsProps } from "./comments.js";
|
|
4
|
+
export { readAuthor, rememberName, useAuthor } from "./identity.js";
|
|
5
|
+
export type { Author, Comment, Deployment, Thread, ThreadList, ThreadStatus } from "./types.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { CommentsStore, Deployment } from "../types.js";
|
|
2
|
+
export interface CommentsHandlerOptions {
|
|
3
|
+
store: CommentsStore;
|
|
4
|
+
/**
|
|
5
|
+
* Whether comments are on. Off, every request is answered 404 and the tool draws nothing. By
|
|
6
|
+
* default: on for preview deployments and local development, off in production (`VERCEL_ENV`,
|
|
7
|
+
* else `NODE_ENV`).
|
|
8
|
+
*/
|
|
9
|
+
enabled?: boolean;
|
|
10
|
+
/** The deployment threads are left on. By default from Vercel's system variables. */
|
|
11
|
+
deployment?: Partial<Deployment>;
|
|
12
|
+
/** Origins allowed to write besides the page's own, such as a proxy's: "https://review.example.com". */
|
|
13
|
+
allowedOrigins?: string[];
|
|
14
|
+
}
|
|
15
|
+
type Handler = (request: Request) => Promise<Response>;
|
|
16
|
+
export declare function defaultEnabled(env?: Record<string, string | undefined>): boolean;
|
|
17
|
+
export declare function defaultDeployment(env?: Record<string, string | undefined>): Deployment;
|
|
18
|
+
/** What comes after the route's base: `threads`, `threads/<id>`, `threads/<id>/comments`, `pages`, or nothing. */
|
|
19
|
+
export declare function routeOf(url: string): {
|
|
20
|
+
threads: boolean;
|
|
21
|
+
id?: string;
|
|
22
|
+
comments?: boolean;
|
|
23
|
+
pages?: boolean;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* The route handler for comments, as a Next route's `GET`, `POST` and `PATCH`. Mount it on an
|
|
27
|
+
* optional catch-all, `app/api/comments/[[...path]]/route.ts`:
|
|
28
|
+
*
|
|
29
|
+
* GET /api/comments?path=/about threads on a page, with the deployment answering
|
|
30
|
+
* GET /api/comments?path=/about&page=page:about:3 the same for a page with a key
|
|
31
|
+
* GET /api/comments every page's threads
|
|
32
|
+
* GET /api/comments/threads/<id> one thread
|
|
33
|
+
* POST /api/comments/threads start a thread
|
|
34
|
+
* POST /api/comments/threads/<id>/comments reply
|
|
35
|
+
* PATCH /api/comments/threads/<id> resolve or reopen
|
|
36
|
+
* POST /api/comments/pages a page with a key is at a new path: { pageKey, path }
|
|
37
|
+
*
|
|
38
|
+
* Writes must come from the page's own origin and be JSON. Text is stored as plain text.
|
|
39
|
+
*/
|
|
40
|
+
export declare function createCommentsHandler(options: CommentsHandlerOptions): {
|
|
41
|
+
GET: Handler;
|
|
42
|
+
POST: Handler;
|
|
43
|
+
PATCH: Handler;
|
|
44
|
+
};
|
|
45
|
+
export {};
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { checkNewComment, checkNewThread, checkPageKey, checkPageMove, checkPath, checkStatusChange, isId } from "../validate.js";
|
|
2
|
+
const MAX_BODY = 32 * 1024;
|
|
3
|
+
const json = (data, status = 200) => new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff" } });
|
|
4
|
+
const error = (status, message) => json({ error: message }, status);
|
|
5
|
+
export function defaultEnabled(env = process.env) {
|
|
6
|
+
if (env.VERCEL_ENV)
|
|
7
|
+
return env.VERCEL_ENV !== "production";
|
|
8
|
+
return env.NODE_ENV !== "production";
|
|
9
|
+
}
|
|
10
|
+
export function defaultDeployment(env = process.env) {
|
|
11
|
+
return {
|
|
12
|
+
url: env.VERCEL_URL ? `https://${env.VERCEL_URL}` : null,
|
|
13
|
+
branch: env.VERCEL_GIT_COMMIT_REF || null,
|
|
14
|
+
commit: env.VERCEL_GIT_COMMIT_SHA || null,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/** What comes after the route's base: `threads`, `threads/<id>`, `threads/<id>/comments`, `pages`, or nothing. */
|
|
18
|
+
export function routeOf(url) {
|
|
19
|
+
const pathname = new URL(url).pathname;
|
|
20
|
+
if (/(?:^|\/)pages\/?$/.test(pathname))
|
|
21
|
+
return { threads: false, pages: true };
|
|
22
|
+
const m = pathname.match(/(?:^|\/)threads(?:\/([^/]+))?(?:\/(comments))?\/?$/);
|
|
23
|
+
if (!m)
|
|
24
|
+
return { threads: false };
|
|
25
|
+
return { threads: true, id: m[1] ? decodeURIComponent(m[1]) : undefined, comments: !!m[2] };
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The route handler for comments, as a Next route's `GET`, `POST` and `PATCH`. Mount it on an
|
|
29
|
+
* optional catch-all, `app/api/comments/[[...path]]/route.ts`:
|
|
30
|
+
*
|
|
31
|
+
* GET /api/comments?path=/about threads on a page, with the deployment answering
|
|
32
|
+
* GET /api/comments?path=/about&page=page:about:3 the same for a page with a key
|
|
33
|
+
* GET /api/comments every page's threads
|
|
34
|
+
* GET /api/comments/threads/<id> one thread
|
|
35
|
+
* POST /api/comments/threads start a thread
|
|
36
|
+
* POST /api/comments/threads/<id>/comments reply
|
|
37
|
+
* PATCH /api/comments/threads/<id> resolve or reopen
|
|
38
|
+
* POST /api/comments/pages a page with a key is at a new path: { pageKey, path }
|
|
39
|
+
*
|
|
40
|
+
* Writes must come from the page's own origin and be JSON. Text is stored as plain text.
|
|
41
|
+
*/
|
|
42
|
+
export function createCommentsHandler(options) {
|
|
43
|
+
const { store } = options;
|
|
44
|
+
const enabled = () => options.enabled ?? defaultEnabled();
|
|
45
|
+
const deployment = () => ({ ...defaultDeployment(), ...options.deployment });
|
|
46
|
+
const allowed = new Set((options.allowedOrigins ?? []).map((o) => o.replace(/\/$/, "")));
|
|
47
|
+
function sameOrigin(request) {
|
|
48
|
+
const origin = request.headers.get("origin");
|
|
49
|
+
if (!origin)
|
|
50
|
+
return false;
|
|
51
|
+
let from;
|
|
52
|
+
try {
|
|
53
|
+
from = new URL(origin);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
if (allowed.has(from.origin))
|
|
59
|
+
return true;
|
|
60
|
+
const host = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || request.headers.get("host") || new URL(request.url).host;
|
|
61
|
+
return from.host === host;
|
|
62
|
+
}
|
|
63
|
+
/** A write's JSON body, or the response refusing it. */
|
|
64
|
+
async function readJson(request) {
|
|
65
|
+
if (!sameOrigin(request))
|
|
66
|
+
return error(403, "Comments can only be written from the site itself.");
|
|
67
|
+
if (!/^application\/json\b/i.test(request.headers.get("content-type") ?? ""))
|
|
68
|
+
return error(415, "Send JSON.");
|
|
69
|
+
const raw = await request.text();
|
|
70
|
+
if (raw.length > MAX_BODY)
|
|
71
|
+
return error(413, "Too long.");
|
|
72
|
+
try {
|
|
73
|
+
return { data: JSON.parse(raw) };
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return error(400, "That isn't JSON.");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const guard = (fn) => async (request) => {
|
|
80
|
+
if (!enabled())
|
|
81
|
+
return error(404, "Not found.");
|
|
82
|
+
try {
|
|
83
|
+
return await fn(request);
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
console.error("[@designtools/comments]", e);
|
|
87
|
+
return error(500, "Comments couldn't be reached. Try again in a moment.");
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
const checked = (c, then) => (c.ok ? then(c.value) : Promise.resolve(error(400, c.error)));
|
|
91
|
+
const GET = guard(async (request) => {
|
|
92
|
+
const route = routeOf(request.url);
|
|
93
|
+
if (route.pages)
|
|
94
|
+
return error(405, "Not allowed.");
|
|
95
|
+
if (route.threads) {
|
|
96
|
+
if (!route.id || route.comments)
|
|
97
|
+
return error(405, "Not allowed.");
|
|
98
|
+
if (!isId(route.id))
|
|
99
|
+
return error(404, "No such thread.");
|
|
100
|
+
const thread = await store.get(route.id);
|
|
101
|
+
return thread ? json({ thread }) : error(404, "No such thread.");
|
|
102
|
+
}
|
|
103
|
+
const params = new URL(request.url).searchParams;
|
|
104
|
+
const filter = {};
|
|
105
|
+
const path = params.get("path");
|
|
106
|
+
if (path !== null) {
|
|
107
|
+
const p = checkPath(path);
|
|
108
|
+
if (!p.ok)
|
|
109
|
+
return error(400, p.error);
|
|
110
|
+
filter.path = p.value;
|
|
111
|
+
}
|
|
112
|
+
const page = params.get("page");
|
|
113
|
+
if (page !== null) {
|
|
114
|
+
const k = checkPageKey(page);
|
|
115
|
+
if (!k.ok)
|
|
116
|
+
return error(400, k.error);
|
|
117
|
+
filter.page = k.value;
|
|
118
|
+
}
|
|
119
|
+
const status = params.get("status");
|
|
120
|
+
if (status === "open" || status === "resolved")
|
|
121
|
+
filter.status = status;
|
|
122
|
+
else if (status !== null && status !== "all")
|
|
123
|
+
return error(400, 'status must be "open", "resolved" or "all"');
|
|
124
|
+
const list = { threads: await store.list(filter), deployment: deployment() };
|
|
125
|
+
return json(list);
|
|
126
|
+
});
|
|
127
|
+
const POST = guard(async (request) => {
|
|
128
|
+
const route = routeOf(request.url);
|
|
129
|
+
if (route.pages) {
|
|
130
|
+
const body = await readJson(request);
|
|
131
|
+
if (body instanceof Response)
|
|
132
|
+
return body;
|
|
133
|
+
return checked(checkPageMove(body.data), async ({ pageKey, path }) => json({ moved: await store.movePage(pageKey, path) }));
|
|
134
|
+
}
|
|
135
|
+
if (!route.threads)
|
|
136
|
+
return error(405, "Not allowed.");
|
|
137
|
+
if (route.id && !route.comments)
|
|
138
|
+
return error(405, "Not allowed.");
|
|
139
|
+
const body = await readJson(request);
|
|
140
|
+
if (body instanceof Response)
|
|
141
|
+
return body;
|
|
142
|
+
if (!route.id) {
|
|
143
|
+
return checked(checkNewThread(body.data), async (input) => json({ thread: await store.createThread({ ...input, deployment: deployment() }) }, 201));
|
|
144
|
+
}
|
|
145
|
+
if (!isId(route.id))
|
|
146
|
+
return error(404, "No such thread.");
|
|
147
|
+
const id = route.id;
|
|
148
|
+
return checked(checkNewComment(body.data), async (input) => {
|
|
149
|
+
const comment = await store.addComment(id, input);
|
|
150
|
+
return comment ? json({ comment }, 201) : error(404, "No such thread.");
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
const PATCH = guard(async (request) => {
|
|
154
|
+
const route = routeOf(request.url);
|
|
155
|
+
if (!route.threads || !route.id || route.comments)
|
|
156
|
+
return error(405, "Not allowed.");
|
|
157
|
+
const body = await readJson(request);
|
|
158
|
+
if (body instanceof Response)
|
|
159
|
+
return body;
|
|
160
|
+
if (!isId(route.id))
|
|
161
|
+
return error(404, "No such thread.");
|
|
162
|
+
const id = route.id;
|
|
163
|
+
return checked(checkStatusChange(body.data), async (change) => {
|
|
164
|
+
const thread = await store.setStatus(id, change.status, change.by.name);
|
|
165
|
+
return thread ? json({ thread }) : error(404, "No such thread.");
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
return { GET, POST, PATCH };
|
|
169
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server half: the route handler, the stores and the schema. Import it only from server code,
|
|
3
|
+
* a route handler or a script; the browser half is `@designtools/comments`.
|
|
4
|
+
*/
|
|
5
|
+
export { type CommentsHandlerOptions, createCommentsHandler, defaultDeployment, defaultEnabled } from "./handler.js";
|
|
6
|
+
export { memoryStore } from "./memory.js";
|
|
7
|
+
export { type Migration, MIGRATIONS, migrate, schemaSql } from "./migrations.js";
|
|
8
|
+
export { postgresStore } from "./postgres.js";
|
|
9
|
+
export { connect, type SqlClient } from "./sql.js";
|
|
10
|
+
export type { Anchor, Author, Comment, CommentsStore, CreateThread, Deployment, NewComment, NewThread, Thread, ThreadList, ThreadStatus } from "../types.js";
|
|
11
|
+
export { LIMITS } from "../validate.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server half: the route handler, the stores and the schema. Import it only from server code,
|
|
3
|
+
* a route handler or a script; the browser half is `@designtools/comments`.
|
|
4
|
+
*/
|
|
5
|
+
export { createCommentsHandler, defaultDeployment, defaultEnabled } from "./handler.js";
|
|
6
|
+
export { memoryStore } from "./memory.js";
|
|
7
|
+
export { MIGRATIONS, migrate, schemaSql } from "./migrations.js";
|
|
8
|
+
export { postgresStore } from "./postgres.js";
|
|
9
|
+
export { connect } from "./sql.js";
|
|
10
|
+
export { LIMITS } from "../validate.js";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CommentsStore, Thread } from "../types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Comments kept in memory: for tests, and for trying the tool out locally with no database. Gone
|
|
4
|
+
* when the server restarts, and not shared between serverless instances, so never for a real review.
|
|
5
|
+
*/
|
|
6
|
+
export declare function memoryStore(seed?: Thread[]): CommentsStore;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
const copy = (t) => ({ ...t, anchor: { ...t.anchor }, comments: t.comments.map((c) => ({ ...c })) });
|
|
2
|
+
/**
|
|
3
|
+
* Comments kept in memory: for tests, and for trying the tool out locally with no database. Gone
|
|
4
|
+
* when the server restarts, and not shared between serverless instances, so never for a real review.
|
|
5
|
+
*/
|
|
6
|
+
export function memoryStore(seed = []) {
|
|
7
|
+
const threads = new Map(seed.map((t) => [t.id, copy(t)]));
|
|
8
|
+
// two writes in the same millisecond still sort in the order they were made
|
|
9
|
+
let last = 0;
|
|
10
|
+
const now = () => {
|
|
11
|
+
last = Math.max(Date.now(), last + 1);
|
|
12
|
+
return new Date(last).toISOString();
|
|
13
|
+
};
|
|
14
|
+
return {
|
|
15
|
+
async list(filter = {}) {
|
|
16
|
+
const onPage = (t) => {
|
|
17
|
+
if (filter.page !== undefined)
|
|
18
|
+
return t.pageKey === filter.page || (t.pageKey === null && filter.path !== undefined && t.path === filter.path);
|
|
19
|
+
return filter.path === undefined || t.path === filter.path;
|
|
20
|
+
};
|
|
21
|
+
return [...threads.values()]
|
|
22
|
+
.filter((t) => onPage(t) && (filter.status === undefined || t.status === filter.status))
|
|
23
|
+
.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
|
|
24
|
+
.map(copy);
|
|
25
|
+
},
|
|
26
|
+
async movePage(pageKey, path) {
|
|
27
|
+
let moved = 0;
|
|
28
|
+
for (const t of threads.values()) {
|
|
29
|
+
if (t.pageKey !== pageKey || t.path === path)
|
|
30
|
+
continue;
|
|
31
|
+
t.path = path;
|
|
32
|
+
moved++;
|
|
33
|
+
}
|
|
34
|
+
return moved;
|
|
35
|
+
},
|
|
36
|
+
async get(id) {
|
|
37
|
+
const t = threads.get(id);
|
|
38
|
+
return t ? copy(t) : null;
|
|
39
|
+
},
|
|
40
|
+
async createThread(input) {
|
|
41
|
+
const id = crypto.randomUUID();
|
|
42
|
+
const at = now();
|
|
43
|
+
const thread = {
|
|
44
|
+
id,
|
|
45
|
+
path: input.path,
|
|
46
|
+
pageKey: input.pageKey ?? null,
|
|
47
|
+
locale: input.locale,
|
|
48
|
+
anchor: { ...input.anchor },
|
|
49
|
+
viewportWidth: input.viewportWidth,
|
|
50
|
+
deploymentUrl: input.deployment.url,
|
|
51
|
+
branch: input.deployment.branch,
|
|
52
|
+
commit: input.deployment.commit,
|
|
53
|
+
status: "open",
|
|
54
|
+
createdAt: at,
|
|
55
|
+
createdBy: input.author.name,
|
|
56
|
+
resolvedAt: null,
|
|
57
|
+
resolvedBy: null,
|
|
58
|
+
comments: [{ id: crypto.randomUUID(), threadId: id, authorName: input.author.name, authorId: input.author.id, body: input.body, createdAt: at }],
|
|
59
|
+
};
|
|
60
|
+
threads.set(id, thread);
|
|
61
|
+
return copy(thread);
|
|
62
|
+
},
|
|
63
|
+
async addComment(threadId, input) {
|
|
64
|
+
const t = threads.get(threadId);
|
|
65
|
+
if (!t)
|
|
66
|
+
return null;
|
|
67
|
+
const comment = { id: crypto.randomUUID(), threadId, authorName: input.author.name, authorId: input.author.id, body: input.body, createdAt: now() };
|
|
68
|
+
t.comments.push(comment);
|
|
69
|
+
return { ...comment };
|
|
70
|
+
},
|
|
71
|
+
async setStatus(threadId, status, by) {
|
|
72
|
+
const t = threads.get(threadId);
|
|
73
|
+
if (!t)
|
|
74
|
+
return null;
|
|
75
|
+
t.status = status;
|
|
76
|
+
t.resolvedAt = status === "resolved" ? now() : null;
|
|
77
|
+
t.resolvedBy = status === "resolved" ? by : null;
|
|
78
|
+
return copy(t);
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The comments schema, as numbered migrations. Each is run once and recorded. They only ever add:
|
|
3
|
+
* a later one adds a table, a column or an index, and never renames or drops, so an older version of
|
|
4
|
+
* the package keeps working against a newer database.
|
|
5
|
+
*/
|
|
6
|
+
import type { SqlClient } from "./sql.js";
|
|
7
|
+
export interface Migration {
|
|
8
|
+
id: number;
|
|
9
|
+
name: string;
|
|
10
|
+
/** One statement per entry. */
|
|
11
|
+
statements: string[];
|
|
12
|
+
}
|
|
13
|
+
export declare const MIGRATIONS: Migration[];
|
|
14
|
+
/** The whole schema as one SQL script, for someone who'd rather run it by hand. */
|
|
15
|
+
export declare function schemaSql(): string;
|
|
16
|
+
/** Bring a database up to date. Safe to run again: returns the ids of the migrations it applied, none if it was current. */
|
|
17
|
+
export declare function migrate(sql: SqlClient): Promise<number[]>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export const MIGRATIONS = [
|
|
2
|
+
{
|
|
3
|
+
id: 1,
|
|
4
|
+
name: "threads and comments",
|
|
5
|
+
statements: [
|
|
6
|
+
`create table if not exists threads (
|
|
7
|
+
id uuid primary key,
|
|
8
|
+
path text not null,
|
|
9
|
+
page_key text,
|
|
10
|
+
locale text,
|
|
11
|
+
anchor jsonb not null,
|
|
12
|
+
viewport_width integer,
|
|
13
|
+
deployment_url text,
|
|
14
|
+
branch text,
|
|
15
|
+
commit_sha text,
|
|
16
|
+
status text not null default 'open' check (status in ('open', 'resolved')),
|
|
17
|
+
created_at timestamptz not null default now(),
|
|
18
|
+
created_by text not null,
|
|
19
|
+
resolved_at timestamptz,
|
|
20
|
+
resolved_by text
|
|
21
|
+
)`,
|
|
22
|
+
"create index if not exists threads_path on threads (path, created_at desc)",
|
|
23
|
+
// a page's stable id, so its threads follow it when its path changes
|
|
24
|
+
"create index if not exists threads_page_key on threads (page_key, created_at desc)",
|
|
25
|
+
`create table if not exists comments (
|
|
26
|
+
id uuid primary key,
|
|
27
|
+
thread_id uuid not null references threads (id) on delete cascade,
|
|
28
|
+
author_name text not null,
|
|
29
|
+
author_id text not null,
|
|
30
|
+
body text not null check (char_length(body) between 1 and 4000),
|
|
31
|
+
created_at timestamptz not null default now()
|
|
32
|
+
)`,
|
|
33
|
+
"create index if not exists comments_thread on comments (thread_id, created_at)",
|
|
34
|
+
],
|
|
35
|
+
},
|
|
36
|
+
];
|
|
37
|
+
const LEDGER = "designtools_comments_migrations";
|
|
38
|
+
/** The whole schema as one SQL script, for someone who'd rather run it by hand. */
|
|
39
|
+
export function schemaSql() {
|
|
40
|
+
return [
|
|
41
|
+
`create table if not exists ${LEDGER} (id integer primary key, name text not null, applied_at timestamptz not null default now());`,
|
|
42
|
+
...MIGRATIONS.flatMap((m) => [`-- ${m.id}: ${m.name}`, ...m.statements.map((s) => `${s};`), `insert into ${LEDGER} (id, name) values (${m.id}, '${m.name}') on conflict do nothing;`]),
|
|
43
|
+
].join("\n\n");
|
|
44
|
+
}
|
|
45
|
+
/** Bring a database up to date. Safe to run again: returns the ids of the migrations it applied, none if it was current. */
|
|
46
|
+
export async function migrate(sql) {
|
|
47
|
+
await sql.query(`create table if not exists ${LEDGER} (id integer primary key, name text not null, applied_at timestamptz not null default now())`);
|
|
48
|
+
const done = new Set((await sql.query(`select id from ${LEDGER}`)).map((r) => Number(r.id)));
|
|
49
|
+
const applied = [];
|
|
50
|
+
for (const m of MIGRATIONS) {
|
|
51
|
+
if (done.has(m.id))
|
|
52
|
+
continue;
|
|
53
|
+
await sql.transaction(async (tx) => {
|
|
54
|
+
for (const s of m.statements)
|
|
55
|
+
await tx.query(s);
|
|
56
|
+
await tx.query(`insert into ${LEDGER} (id, name) values ($1, $2)`, [m.id, m.name]);
|
|
57
|
+
});
|
|
58
|
+
applied.push(m.id);
|
|
59
|
+
}
|
|
60
|
+
return applied;
|
|
61
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { CommentsStore } from "../types.js";
|
|
2
|
+
import { type SqlClient } from "./sql.js";
|
|
3
|
+
/**
|
|
4
|
+
* Comments in Postgres: a connection string (or a client), and the tables `designtools-comments
|
|
5
|
+
* migrate` makes. Its own database, apart from the CMS's, so feedback never reaches its snapshots.
|
|
6
|
+
*/
|
|
7
|
+
export declare function postgresStore(database: string | SqlClient | undefined): CommentsStore;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { connect } from "./sql.js";
|
|
2
|
+
const iso = (d) => (d instanceof Date ? d : new Date(d)).toISOString();
|
|
3
|
+
const toComment = (r) => ({ id: r.id, threadId: r.thread_id, authorName: r.author_name, authorId: r.author_id, body: r.body, createdAt: iso(r.created_at) });
|
|
4
|
+
const toThread = (r, comments) => ({
|
|
5
|
+
id: r.id,
|
|
6
|
+
path: r.path,
|
|
7
|
+
pageKey: r.page_key,
|
|
8
|
+
locale: r.locale,
|
|
9
|
+
anchor: typeof r.anchor === "string" ? JSON.parse(r.anchor) : r.anchor,
|
|
10
|
+
viewportWidth: r.viewport_width,
|
|
11
|
+
deploymentUrl: r.deployment_url,
|
|
12
|
+
branch: r.branch,
|
|
13
|
+
commit: r.commit_sha,
|
|
14
|
+
status: r.status,
|
|
15
|
+
createdAt: iso(r.created_at),
|
|
16
|
+
createdBy: r.created_by,
|
|
17
|
+
resolvedAt: r.resolved_at ? iso(r.resolved_at) : null,
|
|
18
|
+
resolvedBy: r.resolved_by,
|
|
19
|
+
comments,
|
|
20
|
+
});
|
|
21
|
+
const THREAD = "id, path, page_key, locale, anchor, viewport_width, deployment_url, branch, commit_sha, status, created_at, created_by, resolved_at, resolved_by";
|
|
22
|
+
const COMMENT = "id, thread_id, author_name, author_id, body, created_at";
|
|
23
|
+
/**
|
|
24
|
+
* Comments in Postgres: a connection string (or a client), and the tables `designtools-comments
|
|
25
|
+
* migrate` makes. Its own database, apart from the CMS's, so feedback never reaches its snapshots.
|
|
26
|
+
*/
|
|
27
|
+
export function postgresStore(database) {
|
|
28
|
+
const sql = typeof database === "object" ? database : connect(database);
|
|
29
|
+
async function withComments(rows) {
|
|
30
|
+
if (!rows.length)
|
|
31
|
+
return [];
|
|
32
|
+
const comments = await sql.query(`select ${COMMENT} from comments where thread_id = any($1::uuid[]) order by created_at, id`, [rows.map((r) => r.id)]);
|
|
33
|
+
const by = new Map();
|
|
34
|
+
for (const c of comments) {
|
|
35
|
+
const list = by.get(c.thread_id) ?? [];
|
|
36
|
+
list.push(toComment(c));
|
|
37
|
+
by.set(c.thread_id, list);
|
|
38
|
+
}
|
|
39
|
+
return rows.map((r) => toThread(r, by.get(r.id) ?? []));
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
async list(filter = {}) {
|
|
43
|
+
const where = [];
|
|
44
|
+
const params = [];
|
|
45
|
+
if (filter.page !== undefined) {
|
|
46
|
+
params.push(filter.page);
|
|
47
|
+
const page = `page_key = $${params.length}`;
|
|
48
|
+
if (filter.path !== undefined) {
|
|
49
|
+
// and what was left on its path before it had a key
|
|
50
|
+
params.push(filter.path);
|
|
51
|
+
where.push(`(${page} or (page_key is null and path = $${params.length}))`);
|
|
52
|
+
}
|
|
53
|
+
else
|
|
54
|
+
where.push(page);
|
|
55
|
+
}
|
|
56
|
+
else if (filter.path !== undefined) {
|
|
57
|
+
params.push(filter.path);
|
|
58
|
+
where.push(`path = $${params.length}`);
|
|
59
|
+
}
|
|
60
|
+
if (filter.status !== undefined) {
|
|
61
|
+
params.push(filter.status);
|
|
62
|
+
where.push(`status = $${params.length}`);
|
|
63
|
+
}
|
|
64
|
+
const rows = await sql.query(`select ${THREAD} from threads ${where.length ? `where ${where.join(" and ")}` : ""} order by created_at desc, id`, params);
|
|
65
|
+
return withComments(rows);
|
|
66
|
+
},
|
|
67
|
+
async movePage(pageKey, path) {
|
|
68
|
+
const rows = await sql.query("update threads set path = $2 where page_key = $1 and path <> $2 returning id", [pageKey, path]);
|
|
69
|
+
return rows.length;
|
|
70
|
+
},
|
|
71
|
+
async get(id) {
|
|
72
|
+
const rows = await sql.query(`select ${THREAD} from threads where id = $1`, [id]);
|
|
73
|
+
return (await withComments(rows))[0] ?? null;
|
|
74
|
+
},
|
|
75
|
+
async createThread(input) {
|
|
76
|
+
const id = crypto.randomUUID();
|
|
77
|
+
return sql.transaction(async (tx) => {
|
|
78
|
+
const [row] = await tx.query(`insert into threads (id, path, page_key, locale, anchor, viewport_width, deployment_url, branch, commit_sha, created_by)
|
|
79
|
+
values ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10) returning ${THREAD}`, [id, input.path, input.pageKey ?? null, input.locale, JSON.stringify(input.anchor), input.viewportWidth, input.deployment.url, input.deployment.branch, input.deployment.commit, input.author.name]);
|
|
80
|
+
const [comment] = await tx.query(`insert into comments (id, thread_id, author_name, author_id, body, created_at) values ($1, $2, $3, $4, $5, $6) returning ${COMMENT}`, [crypto.randomUUID(), id, input.author.name, input.author.id, input.body, row.created_at]);
|
|
81
|
+
return toThread(row, [toComment(comment)]);
|
|
82
|
+
});
|
|
83
|
+
},
|
|
84
|
+
async addComment(threadId, input) {
|
|
85
|
+
const rows = await sql.query(`insert into comments (id, thread_id, author_name, author_id, body)
|
|
86
|
+
select $1, id, $3, $4, $5 from threads where id = $2 returning ${COMMENT}`, [crypto.randomUUID(), threadId, input.author.name, input.author.id, input.body]);
|
|
87
|
+
return rows[0] ? toComment(rows[0]) : null;
|
|
88
|
+
},
|
|
89
|
+
async setStatus(threadId, status, by) {
|
|
90
|
+
const rows = await sql.query(`update threads set status = $2,
|
|
91
|
+
resolved_at = case when $2 = 'resolved' then now() else null end,
|
|
92
|
+
resolved_by = case when $2 = 'resolved' then $3 else null end
|
|
93
|
+
where id = $1 returning id`, [threadId, status, by]);
|
|
94
|
+
return rows[0] ? this.get(threadId) : null;
|
|
95
|
+
},
|
|
96
|
+
async close() {
|
|
97
|
+
await sql.end?.();
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The little the store needs from Postgres: a query with numbered parameters, and a transaction.
|
|
3
|
+
* `connect` makes one from a connection string with postgres.js; tests hand in PGlite the same way.
|
|
4
|
+
*/
|
|
5
|
+
export interface SqlClient {
|
|
6
|
+
query<T = Record<string, unknown>>(text: string, params?: unknown[]): Promise<T[]>;
|
|
7
|
+
transaction<R>(fn: (tx: SqlClient) => Promise<R>): Promise<R>;
|
|
8
|
+
end?(): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* A client for a connection string, connected on first use, so a route module can be loaded where
|
|
12
|
+
* the string isn't set (a production build, with comments switched off) without failing.
|
|
13
|
+
*/
|
|
14
|
+
export declare function connect(url: string | undefined): SqlClient;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import postgres from "postgres";
|
|
2
|
+
function wrap(sql) {
|
|
3
|
+
return {
|
|
4
|
+
async query(text, params = []) {
|
|
5
|
+
return [...(await sql.unsafe(text, params))];
|
|
6
|
+
},
|
|
7
|
+
async transaction(fn) {
|
|
8
|
+
if (!sql.begin)
|
|
9
|
+
return fn(this);
|
|
10
|
+
return (await sql.begin((tx) => fn(wrap(tx))));
|
|
11
|
+
},
|
|
12
|
+
end: sql.end ? () => sql.end?.() ?? Promise.resolve() : undefined,
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A client for a connection string, connected on first use, so a route module can be loaded where
|
|
17
|
+
* the string isn't set (a production build, with comments switched off) without failing.
|
|
18
|
+
*/
|
|
19
|
+
export function connect(url) {
|
|
20
|
+
let sql = null;
|
|
21
|
+
const get = () => {
|
|
22
|
+
if (!url)
|
|
23
|
+
throw new Error("No database for comments: set COMMENTS_DATABASE_URL, or pass a connection string to postgresStore.");
|
|
24
|
+
// no prepared statements, so a pooled connection (Neon's -pooler host, PgBouncer) works too
|
|
25
|
+
sql ??= postgres(url, { prepare: false, max: 5, idle_timeout: 20, onnotice: () => { } });
|
|
26
|
+
return wrap(sql);
|
|
27
|
+
};
|
|
28
|
+
return {
|
|
29
|
+
query: (text, params) => get().query(text, params),
|
|
30
|
+
transaction: (fn) => get().transaction(fn),
|
|
31
|
+
async end() {
|
|
32
|
+
await sql?.end({ timeout: 5 });
|
|
33
|
+
sql = null;
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|