@designtools/comments 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,19 @@
1
+ # @designtools/comments
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - bb3684c: Copy prompt: each thread copies itself as a prompt for Claude or another coding agent, with the page, what it's on and how to find that in the code, the comments, and the command that resolves it. `threadPrompt(thread)` builds the same text.
8
+
9
+ ## 0.1.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 2db9481: First release. Comments on prototypes with no account: `<Comments />` lets a reviewer choose a module, or a field inside it, with the mouse or the keyboard, and pin a thread to it, with replies, resolve and reopen, pins beside what they're about, and a panel of this page's threads or every page's, orphaned ones included. Anchors are kept by key, so a comment follows its module when the page changes, and a page that marks itself with `data-comment-page` keeps its comments when its URL changes. Comments live in the project's own database, so every preview and redeploy shows the same ones. `@designtools/comments/server` has the route handler (404 in production), the Postgres store and its migration; `designtools-comments` lists, resolves and reopens threads and runs the migration.
14
+
15
+ ### Patch Changes
16
+
17
+ - Updated dependencies [25a4813]
18
+ - Updated dependencies [2db9481]
19
+ - @designtools/widgets@0.2.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Made by Many Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,173 @@
1
- # Temporary Holding Version
1
+ # @designtools/comments
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Comments on a prototype, pinned to the part of the page they're about. Reviewers don't need an account: they type a name once, choose a module (or a field inside it) with the mouse or the keyboard, and write. The project stores its own comments in its own Postgres, and an agent works through them from the terminal.
4
+
5
+ - **Pinned to modules, not coordinates.** On a page that marks its modules, a comment is kept against the module's key and content field. It follows the module when the page is rearranged, survives a redeploy, and is listed as orphaned (never deleted) if the module goes.
6
+ - **Mouse or keyboard.** Up and Down step through the modules in reading order, Right and Left move into a module's fields and back, Enter chooses, Escape leaves. A live region names each step ("Hero, module 1 of 6"). The tool meets WCAG 2.2 AA and passes axe in every state.
7
+ - **Every page, and pages that move.** The panel shows this page's comments or every page's, grouped by page. A page that marks itself with a stable id keeps its comments when its URL changes.
8
+ - **No account.** A name typed once and remembered by the browser. Vercel's deployment protection already decides who can open a preview; anyone who can open it can comment, reply, resolve and reopen.
9
+ - **Previews only.** The route answers 404 in production, and the tool draws nothing when it does.
10
+ - **For agents too.** Each thread has a **Copy prompt** button: paste it into Claude in the project and it knows the page, what the comment is on, how to find that in the code, what was said, and how to resolve the thread when it's done. `designtools-comments list` prints every open thread; `resolve <id>` closes it.
11
+
12
+ ## Setup (Next App Router)
13
+
14
+ **1. A database.** A Postgres database of its own, apart from the CMS's, so feedback stays out of its schema and snapshots. On Neon: a second database in the project, its connection string as `COMMENTS_DATABASE_URL` for Preview and Development (not Production). Then make the tables:
15
+
16
+ ```bash
17
+ COMMENTS_DATABASE_URL=postgres://… npx designtools-comments migrate
18
+ ```
19
+
20
+ `migrate` is safe to run again. `designtools-comments migrate --print` prints the SQL instead, to run by hand.
21
+
22
+ **2. The route.**
23
+
24
+ ```ts
25
+ // app/api/comments/[[...path]]/route.ts
26
+ import { createCommentsHandler, postgresStore } from "@designtools/comments/server";
27
+
28
+ export const { GET, POST, PATCH } = createCommentsHandler({
29
+ store: postgresStore(process.env.COMMENTS_DATABASE_URL),
30
+ enabled: process.env.VERCEL_ENV !== "production",
31
+ });
32
+ ```
33
+
34
+ `enabled` defaults to exactly that (`VERCEL_ENV`, else `NODE_ENV`), so it can be left out. The deployment URL, branch and commit stored with each thread come from Vercel's system variables; pass `deployment` to set them yourself. For a local try with no database, `memoryStore()` keeps comments in memory until the server stops.
35
+
36
+ **3. The tool**, once, in the root layout or a client component it renders:
37
+
38
+ ```tsx
39
+ "use client";
40
+ import { Comments } from "@designtools/comments";
41
+
42
+ export function ReviewTools() {
43
+ return <Comments />;
44
+ }
45
+ ```
46
+
47
+ It draws a launcher in the bottom-left corner, in its own shadow root, so the page's CSS can't reach it and it can't reach the page. It asks `/api/comments` first and draws nothing unless that answers. Props: `endpoint` (default `/api/comments`), `adapter`, `enabled`, `theme` (`"system"`, `"light"`, `"dark"`) and `locale` (default: `<html lang>`).
48
+
49
+ **4. Leave it out of the page's axe runs**, so they stay about the page. The package tests the tool itself:
50
+
51
+ ```ts
52
+ await new AxeBuilder({ page }).exclude("[data-designtools-host]").analyze();
53
+ ```
54
+
55
+ ## What a comment attaches to
56
+
57
+ An anchor adapter says what can be chosen, how to describe what was chosen, and how to find it again on a later deployment:
58
+
59
+ ```ts
60
+ type Anchor = {
61
+ kind: string; // "module", "section", "element"
62
+ key: string; // stable id, such as "module:ComponentModulesHero:12"
63
+ label: string; // what people and screen readers hear: "Hero"
64
+ field?: string; // a content field inside it: "heading"
65
+ selector: string; // fallback CSS selector, recorded for when there's no key
66
+ };
67
+
68
+ interface AnchorAdapter {
69
+ candidates(doc: Document): Element[]; // in reading order
70
+ describe(el: Element): Anchor | null;
71
+ locate(anchor: Anchor, doc: Document): Element | null;
72
+ resolve?(target: Element): Element | null; // what the pointer means; by default the nearest candidate
73
+ page?(doc: Document): string | null; // the page's stable id; by default data-comment-page
74
+ }
75
+ ```
76
+
77
+ **The default adapter** reads attributes. Mark each module with a key that stays the same when the page is edited, and the fields people will comment on:
78
+
79
+ ```tsx
80
+ <section data-comment-anchor={`module:${__typename}:${id}`} data-comment-label="Hero">
81
+ <h1 data-comment-field="heading">{heading}</h1>
82
+ <div data-comment-field="content">{content}</div>
83
+ </section>
84
+ ```
85
+
86
+ The kind is the key's first segment (`module`, `section`). Where the page marks anchors, only they can be chosen, and a comment is found again by its key alone: if the module has gone, the thread is orphaned rather than moved to whatever took its place. On a page with no marks, any element can be chosen and only its selector is stored; that's fine for a quick look, and drifts when the layout changes.
87
+
88
+ **On a CMS-built page**, wrap each module where the page renders its modules, keyed by the module's type and the CMS's id for it, and mark static sections `section:<template>:<name>`. Check first that the CMS keeps a component's id when a page is edited and published; if it doesn't, add a stable key field to modules.
89
+
90
+ ## Pages whose URL changes
91
+
92
+ Comments belong to a page's path unless the page says who it is. A page whose slug can be edited, or whose route may be restructured, marks itself with an id that stays the same, such as the CMS entry's, anywhere on the page:
93
+
94
+ ```tsx
95
+ <main data-comment-page={`page:${documentId}`}>
96
+ ```
97
+
98
+ Its comments are then found by that id, wherever the page is. The first time anyone opens it at a new URL, its comments' stored path moves there too, so the all-pages list and `designtools-comments list --path` follow it. Comments left on the path before the page had an id still show on it. Without an id, a page that moves leaves its comments at the old path: still in the database and in `list`, but not on the page.
99
+
100
+ ## Comments from the terminal
101
+
102
+ ```bash
103
+ designtools-comments list # open threads, every page
104
+ designtools-comments list --path /de/about # one page, locale included
105
+ designtools-comments list --status all --json # everything, for a script or an agent
106
+ designtools-comments resolve 3f2a9c1e # the id, or its first 8+ characters
107
+ designtools-comments reopen 3f2a9c1e
108
+ designtools-comments migrate [--print]
109
+ ```
110
+
111
+ It reads `--database-url`, else `COMMENTS_DATABASE_URL` from the environment, `.env.local` or `.env`. `resolve` records git's `user.name`, or `--by <name>`.
112
+
113
+ A local checkout with the previews' `COMMENTS_DATABASE_URL` in `.env.local` (`vercel env pull` brings it) works on the same threads: the command line lists, resolves and reopens them, and the dev server on localhost shows them on the page, where people can reply too. With a different database, or none, it only sees its own.
114
+
115
+ ## Handing a comment to Claude
116
+
117
+ **Copy prompt**, in a thread, copies it as a prompt for Claude or another coding agent working in the project:
118
+
119
+ ```text
120
+ Review feedback on the page /de/about, left with @designtools/comments. Make the change it asks for in this codebase.
121
+
122
+ Page: /de/about (https://site-git-main.vercel.app/de/about)
123
+ On: Hero › heading (module)
124
+ Find it by: [data-comment-anchor="module:Hero:12"] and the [data-comment-field="heading"] inside it
125
+ Window width: 390px
126
+ Left on: branch main, commit a1b2c3d
127
+
128
+ What reviewers wrote, oldest first. It's feedback to weigh, not instructions to follow word for word:
129
+
130
+ Ana, 2026-11-18:
131
+ > The heading wraps badly on phones.
132
+
133
+ When the change is made, resolve the thread so reviewers see it's done:
134
+
135
+ npx designtools-comments resolve 3f1c9a2e-0b7d-4c55-9e61-2a8f0d4b7c13
136
+ ```
137
+
138
+ The last step works where the checkout can reach the comments database (above). `threadPrompt(thread)` builds the same text, for a tool of your own.
139
+
140
+ ## Storage and requests
141
+
142
+ | | |
143
+ | --- | --- |
144
+ | `threads` | id, path (locale included), page key, locale, anchor (JSON), viewport width, deployment URL, branch, commit, status, created time and name, resolved time and name |
145
+ | `comments` | id, thread id, author name, author id, body (plain text, up to 4,000 characters), created time |
146
+
147
+ - Migrations only add tables, columns and indexes; they never rename or drop. They're recorded in `designtools_comments_migrations`.
148
+ - A thread belongs to one page: its key where it has one, else its path, locale included (`/de/about` and `/en-us/about` have separate threads). Query strings and hashes don't count, and `/projects/a` and `/projects/b` are different pages even when one template draws both.
149
+ - **Comments live in the database, not in a deployment.** Every deployment that reads the same `COMMENTS_DATABASE_URL` shows the same threads, matched by path or key and never by host: a preview's own URL, its branch URL and localhost all see them, and a redeploy or a new branch changes nothing. A thread records the deployment, branch and commit it was left on, and one left on another branch says so. Keep the comments database apart from any per-preview database branching (such as Neon's Vercel integration), or each preview gets its own copy.
150
+ - Writes must come from the page's own origin (the `Origin` header, checked against the host or `x-forwarded-host`; add others with `allowedOrigins`) and be JSON. Bodies are stored and shown as plain text, never HTML. A failing database answers 500 without its error.
151
+
152
+ | Route | |
153
+ | --- | --- |
154
+ | `GET /api/comments?path=/about` | the page's threads with their comments, and the deployment answering |
155
+ | `GET /api/comments?path=/about&page=page:3` | the same for a page with a key: its threads, and those left on its path before it had one |
156
+ | `GET /api/comments` | every page's threads |
157
+ | `GET /api/comments/threads/<id>` | one thread |
158
+ | `POST /api/comments/threads` | start a thread: `{ path, pageKey?, locale, anchor, viewportWidth, body, author: { name, id } }` |
159
+ | `POST /api/comments/threads/<id>/comments` | reply: `{ body, author }` |
160
+ | `PATCH /api/comments/threads/<id>` | `{ status: "open" \| "resolved", by: { name, id } }` |
161
+ | `POST /api/comments/pages` | a page with a key is at a new path: `{ pageKey, path }`; its threads follow |
162
+
163
+ ## Checking it
164
+
165
+ `pnpm test` covers validation, the handler, the Postgres store (on PGlite), the CLI and the anchor adapter. `pnpm e2e` drives the tool in Chromium against the demo (`pnpm demo` running): keyboard and pointer choosing, composing, pins, anchors that move and go, the all-pages list, a page with a key moving, opening a thread on another page, plain text, and axe in every state, at desktop and phone widths. It needs Playwright with Chromium installed.
166
+
167
+ ## Not yet
168
+
169
+ Sign-in and roles, notifications (Slack, email), mentions, attachments, editing someone else's comment, and a hosted backend shared between projects. Everyone who can open the preview sees every comment.
170
+
171
+ ## Licence
172
+
173
+ MIT. `postgres` (postgres.js) is Unlicense.
@@ -0,0 +1,45 @@
1
+ /**
2
+ * What a comment can attach to. A project gives `<Comments>` an adapter: what can be chosen, how to
3
+ * describe what was chosen, and how to find it again on a later deployment. The default reads
4
+ * `data-comment-anchor` attributes, and with none on the page lets anything be chosen by selector.
5
+ */
6
+ import type { Anchor } from "./types.js";
7
+ export type { Anchor };
8
+ export interface AnchorAdapter {
9
+ /** Everything that can be chosen, in reading order. One inside another is a level below it. */
10
+ candidates(doc: Document): HTMLElement[];
11
+ /** The anchor for a chosen element, or null when it can't be commented on. */
12
+ describe(el: Element): Anchor | null;
13
+ /** The element an anchor means on this page now, or null when it has gone. */
14
+ locate(anchor: Anchor, doc: Document): HTMLElement | null;
15
+ /** The candidate the pointer means for the element under it. By default, the nearest candidate around it. */
16
+ resolve?(target: Element): HTMLElement | null;
17
+ /**
18
+ * A stable id for the page, such as the CMS entry's: "page:about:3". Threads follow it when the
19
+ * page's path changes. Null, or left out, and threads stay with the path.
20
+ */
21
+ page?(doc: Document): string | null;
22
+ }
23
+ /** "heading" → "Heading", "ctaText" → "Cta text", "hero_image" → "Hero image". */
24
+ export declare function humanize(s: string): string;
25
+ /** How an anchor is shown: "Hero", or "Hero › Heading" for a field inside it. */
26
+ export declare function anchorName(anchor: Anchor): string;
27
+ /** A selector for an element: its id where it has a good one, else its path of tags and positions from the body. */
28
+ export declare function cssPath(el: Element): string;
29
+ /** A name for an unmarked element, from what it is and what it says: `Heading "Our work"`. */
30
+ export declare function genericLabel(el: Element): string;
31
+ /**
32
+ * The default adapter. Where the page marks anchors, only they can be chosen:
33
+ *
34
+ * <section data-comment-anchor="module:Hero:12" data-comment-label="Hero">
35
+ * <h1 data-comment-field="heading">…</h1>
36
+ * </section>
37
+ *
38
+ * A comment then follows the key wherever the module moves, and is orphaned if it goes. With no
39
+ * marks on the page, any element can be chosen and only its selector is stored.
40
+ *
41
+ * A page that can change its path marks itself with a stable id, anywhere on the page:
42
+ *
43
+ * <main data-comment-page="page:about:3">
44
+ */
45
+ export declare function defaultAdapter(): AnchorAdapter;
@@ -0,0 +1,177 @@
1
+ const ANCHOR = "data-comment-anchor";
2
+ const PAGE = "data-comment-page";
3
+ const FIELD = "data-comment-field";
4
+ const LABEL = "data-comment-label";
5
+ /** "heading" → "Heading", "ctaText" → "Cta text", "hero_image" → "Hero image". */
6
+ export function humanize(s) {
7
+ const words = s
8
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
9
+ .replace(/[_-]+/g, " ")
10
+ .trim()
11
+ .toLowerCase();
12
+ return words.charAt(0).toUpperCase() + words.slice(1);
13
+ }
14
+ /** How an anchor is shown: "Hero", or "Hero › Heading" for a field inside it. */
15
+ export function anchorName(anchor) {
16
+ return anchor.field ? `${anchor.label} › ${humanize(anchor.field)}` : anchor.label;
17
+ }
18
+ const esc = (s) => (typeof CSS !== "undefined" && CSS.escape ? CSS.escape(s) : s.replace(/["\\]/g, "\\$&"));
19
+ /** Whether an id looks written by a person rather than generated (React's `:r1:`, `«r1»`, or a hash). */
20
+ const stableId = (id) => /^[A-Za-z][\w-]*$/.test(id) && !/\d{3,}|[a-f0-9]{8,}/i.test(id);
21
+ /** A selector for an element: its id where it has a good one, else its path of tags and positions from the body. */
22
+ export function cssPath(el) {
23
+ const doc = el.ownerDocument;
24
+ const parts = [];
25
+ for (let at = el; at && at !== doc.body && at !== doc.documentElement; at = at.parentElement) {
26
+ if (at.id && stableId(at.id) && doc.querySelectorAll(`#${esc(at.id)}`).length === 1) {
27
+ parts.unshift(`#${esc(at.id)}`);
28
+ return parts.join(" > ");
29
+ }
30
+ const tag = at.tagName.toLowerCase();
31
+ const parent = at.parentElement;
32
+ const same = parent ? [...parent.children].filter((c) => c.tagName === at?.tagName) : [];
33
+ parts.unshift(same.length > 1 ? `${tag}:nth-of-type(${same.indexOf(at) + 1})` : tag);
34
+ }
35
+ return parts.length ? `body > ${parts.join(" > ")}` : "body";
36
+ }
37
+ /** Elements worth stepping through on a page that marks no anchors. */
38
+ const GENERIC = "header, nav, main, section, article, aside, footer, form, figure, table, h1, h2, h3, h4, h5, h6, p, ul, ol, blockquote, pre, img, video, button, a[href], input, select, textarea";
39
+ const inTool = (el) => !!el.closest("[data-designtools-host]");
40
+ const visible = (el) => {
41
+ const r = el.getBoundingClientRect();
42
+ return r.width > 0 || r.height > 0;
43
+ };
44
+ const short = (s, max = 40) => {
45
+ const t = (s ?? "").replace(/\s+/g, " ").trim();
46
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t;
47
+ };
48
+ /** A name for an unmarked element, from what it is and what it says: `Heading "Our work"`. */
49
+ export function genericLabel(el) {
50
+ const tag = el.tagName.toLowerCase();
51
+ const named = el.getAttribute("aria-label") || el.getAttribute("title");
52
+ const kinds = {
53
+ h1: "Heading",
54
+ h2: "Heading",
55
+ h3: "Heading",
56
+ h4: "Heading",
57
+ h5: "Heading",
58
+ h6: "Heading",
59
+ p: "Paragraph",
60
+ a: "Link",
61
+ button: "Button",
62
+ img: "Image",
63
+ video: "Video",
64
+ ul: "List",
65
+ ol: "List",
66
+ li: "List item",
67
+ nav: "Navigation",
68
+ header: "Header",
69
+ footer: "Footer",
70
+ main: "Main",
71
+ section: "Section",
72
+ article: "Article",
73
+ aside: "Aside",
74
+ form: "Form",
75
+ figure: "Figure",
76
+ table: "Table",
77
+ blockquote: "Quote",
78
+ pre: "Code",
79
+ input: "Field",
80
+ select: "Field",
81
+ textarea: "Field",
82
+ };
83
+ const kind = kinds[tag] ?? humanize(tag);
84
+ let says = named;
85
+ if (!says && tag === "img")
86
+ says = el.getAttribute("alt");
87
+ if (!says && /^(section|article|aside|header|footer|main|nav|form|figure)$/.test(tag))
88
+ says = el.querySelector("h1, h2, h3, h4, h5, h6, legend, figcaption")?.textContent ?? null;
89
+ if (!says && /^(input|select|textarea)$/.test(tag)) {
90
+ const id = el.getAttribute("id");
91
+ says = (id && el.ownerDocument.querySelector(`label[for="${esc(id)}"]`)?.textContent) || el.getAttribute("placeholder") || el.getAttribute("name");
92
+ }
93
+ if (!says && !/^(ul|ol|table|video)$/.test(tag))
94
+ says = el.innerText ?? el.textContent;
95
+ const text = short(says);
96
+ return text ? `${kind} "${text}"` : kind;
97
+ }
98
+ function moduleAnchor(el) {
99
+ const key = el.getAttribute(ANCHOR) ?? "";
100
+ const kind = key.includes(":") ? key.slice(0, key.indexOf(":")) : "element";
101
+ const label = el.getAttribute(LABEL) || el.getAttribute("aria-label") || humanize(key.split(":")[1] ?? key);
102
+ return { kind, key, label };
103
+ }
104
+ /**
105
+ * The default adapter. Where the page marks anchors, only they can be chosen:
106
+ *
107
+ * <section data-comment-anchor="module:Hero:12" data-comment-label="Hero">
108
+ * <h1 data-comment-field="heading">…</h1>
109
+ * </section>
110
+ *
111
+ * A comment then follows the key wherever the module moves, and is orphaned if it goes. With no
112
+ * marks on the page, any element can be chosen and only its selector is stored.
113
+ *
114
+ * A page that can change its path marks itself with a stable id, anywhere on the page:
115
+ *
116
+ * <main data-comment-page="page:about:3">
117
+ */
118
+ export function defaultAdapter() {
119
+ const marked = (doc) => !!doc.querySelector(`[${ANCHOR}]`);
120
+ return {
121
+ page(doc) {
122
+ const el = [...doc.querySelectorAll(`[${PAGE}]`)].find((e) => !inTool(e));
123
+ return el?.getAttribute(PAGE)?.trim() || null;
124
+ },
125
+ candidates(doc) {
126
+ const els = marked(doc)
127
+ ? doc.querySelectorAll(`[${ANCHOR}], [${ANCHOR}] [${FIELD}]`)
128
+ : doc.querySelectorAll(GENERIC);
129
+ return [...els].filter((el) => !inTool(el) && visible(el));
130
+ },
131
+ resolve(target) {
132
+ if (inTool(target))
133
+ return null;
134
+ const doc = target.ownerDocument;
135
+ if (marked(doc)) {
136
+ const field = target.closest(`[${FIELD}]`);
137
+ if (field?.parentElement?.closest(`[${ANCHOR}]`))
138
+ return field;
139
+ return target.closest(`[${ANCHOR}]`);
140
+ }
141
+ if (target === doc.body || target === doc.documentElement || !(target instanceof HTMLElement))
142
+ return null;
143
+ return target;
144
+ },
145
+ describe(el) {
146
+ if (inTool(el))
147
+ return null;
148
+ const field = el.getAttribute(FIELD);
149
+ const owner = field ? el.parentElement?.closest(`[${ANCHOR}]`) : null;
150
+ if (field && owner)
151
+ return { ...moduleAnchor(owner), field, selector: cssPath(el) };
152
+ if (el.hasAttribute(ANCHOR))
153
+ return { ...moduleAnchor(el), selector: cssPath(el) };
154
+ if (el === el.ownerDocument.body || el === el.ownerDocument.documentElement)
155
+ return null;
156
+ return { kind: "element", key: "", label: genericLabel(el), selector: cssPath(el) };
157
+ },
158
+ locate(anchor, doc) {
159
+ if (anchor.key) {
160
+ // by key only: whatever moved into the module's old place isn't it
161
+ const el = doc.querySelector(`[${ANCHOR}="${esc(anchor.key)}"]`);
162
+ if (!el)
163
+ return null;
164
+ return (anchor.field && el.querySelector(`[${FIELD}="${esc(anchor.field)}"]`)) || el;
165
+ }
166
+ if (!anchor.selector)
167
+ return null;
168
+ try {
169
+ const el = doc.querySelector(anchor.selector);
170
+ return el && !inTool(el) ? el : null;
171
+ }
172
+ catch {
173
+ return null;
174
+ }
175
+ },
176
+ };
177
+ }
package/dist/api.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import type { Author, Comment, NewThread, Thread, ThreadList, ThreadStatus } from "./types.js";
2
+ export declare class CommentsError extends Error {
3
+ readonly status: number;
4
+ constructor(message: string, status: number);
5
+ }
6
+ /** The route handler, from the browser. */
7
+ export declare function commentsApi(endpoint: string): {
8
+ /** A page's threads: by its key where it has one, else by its path. */
9
+ list: (path: string, pageKey?: string | null) => Promise<ThreadList>;
10
+ /** Every page's threads. */
11
+ listAll: () => Promise<ThreadList>;
12
+ /** A page with a key is at a new path: its threads follow it. */
13
+ movePage: (pageKey: string, path: string) => Promise<{
14
+ moved: number;
15
+ }>;
16
+ createThread: (input: NewThread) => Promise<Thread>;
17
+ reply: (threadId: string, body: string, author: Author) => Promise<Comment>;
18
+ setStatus: (threadId: string, status: ThreadStatus, by: Author) => Promise<Thread>;
19
+ };
20
+ export type CommentsApi = ReturnType<typeof commentsApi>;
package/dist/api.js ADDED
@@ -0,0 +1,35 @@
1
+ export class CommentsError extends Error {
2
+ status;
3
+ constructor(message, status) {
4
+ super(message);
5
+ this.status = status;
6
+ }
7
+ }
8
+ async function call(url, init) {
9
+ let res;
10
+ try {
11
+ res = await fetch(url, { credentials: "same-origin", cache: "no-store", ...init, headers: { accept: "application/json", ...(init?.body ? { "content-type": "application/json" } : {}), ...init?.headers } });
12
+ }
13
+ catch {
14
+ throw new CommentsError("Couldn't reach comments. Check your connection and try again.", 0);
15
+ }
16
+ const data = (await res.json().catch(() => null));
17
+ if (!res.ok)
18
+ throw new CommentsError(data?.error ?? `Comments answered ${res.status}.`, res.status);
19
+ return data;
20
+ }
21
+ /** The route handler, from the browser. */
22
+ export function commentsApi(endpoint) {
23
+ const base = endpoint.replace(/\/$/, "");
24
+ return {
25
+ /** A page's threads: by its key where it has one, else by its path. */
26
+ list: (path, pageKey) => call(`${base}?path=${encodeURIComponent(path)}${pageKey ? `&page=${encodeURIComponent(pageKey)}` : ""}`),
27
+ /** Every page's threads. */
28
+ listAll: () => call(base),
29
+ /** A page with a key is at a new path: its threads follow it. */
30
+ movePage: (pageKey, path) => call(`${base}/pages`, { method: "POST", body: JSON.stringify({ pageKey, path }) }),
31
+ createThread: (input) => call(`${base}/threads`, { method: "POST", body: JSON.stringify(input) }).then((r) => r.thread),
32
+ reply: (threadId, body, author) => call(`${base}/threads/${encodeURIComponent(threadId)}/comments`, { method: "POST", body: JSON.stringify({ body, author }) }).then((r) => r.comment),
33
+ setStatus: (threadId, status, by) => call(`${base}/threads/${encodeURIComponent(threadId)}`, { method: "PATCH", body: JSON.stringify({ status, by }) }).then((r) => r.thread),
34
+ };
35
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ import { type SqlClient } from "./server/sql.js";
3
+ import type { CommentsStore, Thread, ThreadStatus } from "./types.js";
4
+ export interface CliIo {
5
+ out: (line: string) => void;
6
+ err: (line: string) => void;
7
+ /** Overrides the database, for tests. */
8
+ store?: CommentsStore;
9
+ sql?: SqlClient;
10
+ env?: Record<string, string | undefined>;
11
+ cwd?: string;
12
+ }
13
+ /** COMMENTS_DATABASE_URL from a dotenv file, the way Next reads one: KEY=value, optionally quoted. */
14
+ export declare function fromDotenv(text: string, key: string): string | undefined;
15
+ export declare const anchorLabel: (t: Thread) => string;
16
+ /** Threads as a person reads them: one block each, its comments under it. */
17
+ export declare function formatThreads(threads: Thread[], status: ThreadStatus | "all"): string;
18
+ /** Runs one command; resolves to the exit code. */
19
+ export declare function run(argv: string[], io: CliIo): Promise<number>;