@acryldev/feedback 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/lib/index.js ADDED
@@ -0,0 +1,291 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { Acryl } from "@acryldev/router";
4
+ import { randomUUID } from "node:crypto";
5
+ import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
6
+ //#region store.ts
7
+ /**
8
+ * The notes people sent, in the app's own data: one JSON line per note in `notes.jsonl`, the ids the builder has seen in `seen.json`, and a note's
9
+ * screenshot as a file in `shots/`. Appending never rewrites a note, so a crash loses at most the note being written; an image is written before its
10
+ * note, so a note never names a missing file.
11
+ */
12
+ const LIMITS = {
13
+ text: 2e3,
14
+ page: 500,
15
+ selector: 500,
16
+ label: 120,
17
+ /** Decoded image bytes; the page downscales and re-encodes below this. */
18
+ screenshotBytes: 512 * 1024,
19
+ screenshotSide: 2e3
20
+ };
21
+ const DATA_URL = /^data:(image\/(?:webp|png));base64,([A-Za-z0-9+/]+={0,2})$/u;
22
+ const NOTE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
23
+ /** One screenshot from the page: a WebP or PNG data URL, its size, and the bytes. A string says what is wrong. */
24
+ function parseScreenshot(value) {
25
+ if (typeof value !== "object" || value === null) return "the screenshot must be an object";
26
+ const { data, width, height } = value;
27
+ if (typeof data !== "string") return "the screenshot has no image";
28
+ const match = DATA_URL.exec(data);
29
+ if (match === null || match[1] === void 0 || match[2] === void 0) return "the screenshot must be a WebP or PNG data URL";
30
+ const mediaType = match[1];
31
+ const bytes = Buffer.from(match[2], "base64");
32
+ if (bytes.length === 0) return "the screenshot is empty";
33
+ if (bytes.length > LIMITS.screenshotBytes) return `a screenshot is at most ${String(Math.round(LIMITS.screenshotBytes / 1024))} KB`;
34
+ const webp = bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP";
35
+ const png = bytes[0] === 137 && bytes.subarray(1, 4).toString() === "PNG";
36
+ if (mediaType === "image/webp" && !webp || mediaType === "image/png" && !png) return "the screenshot is not the image its type names";
37
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > LIMITS.screenshotSide || height > LIMITS.screenshotSide) return `the screenshot needs its size, up to ${String(LIMITS.screenshotSide)} px a side`;
38
+ return {
39
+ mediaType,
40
+ width,
41
+ height,
42
+ data: bytes
43
+ };
44
+ }
45
+ /** A note as a page sent it, checked; a string says what is wrong. */
46
+ function parseNewNote(body) {
47
+ if (body === null || typeof body !== "object") return "send a JSON object";
48
+ const { text, page, element, screenshot } = body;
49
+ if (typeof text !== "string" || text.trim() === "") return "write a note";
50
+ if (text.length > LIMITS.text) return `a note has at most ${LIMITS.text} characters`;
51
+ if (typeof page !== "string" || !page.startsWith("/") || page.length > LIMITS.page) return "the page must be a path";
52
+ let pinned;
53
+ if (element !== void 0 && element !== null) {
54
+ if (typeof element !== "object") return "the element must be an object";
55
+ const { selector, label } = element;
56
+ if (typeof selector !== "string" || selector === "" || selector.length > LIMITS.selector) return "the element needs a selector";
57
+ if (typeof label !== "string" || label === "" || label.length > LIMITS.label) return "the element needs a name";
58
+ pinned = {
59
+ selector,
60
+ label
61
+ };
62
+ }
63
+ let shot;
64
+ if (screenshot !== void 0 && screenshot !== null) {
65
+ const parsed = parseScreenshot(screenshot);
66
+ if (typeof parsed === "string") return parsed;
67
+ shot = parsed;
68
+ }
69
+ return {
70
+ text: text.trim(),
71
+ page,
72
+ ...pinned === void 0 ? {} : { element: pinned },
73
+ ...shot === void 0 ? {} : { screenshot: shot }
74
+ };
75
+ }
76
+ function storedScreenshot(raw) {
77
+ if (raw === null || typeof raw !== "object") return void 0;
78
+ const { file, mediaType, width, height, bytes } = raw;
79
+ if (typeof file !== "string" || mediaType !== "image/webp" && mediaType !== "image/png" || !Number.isInteger(width) || !Number.isInteger(height) || !Number.isInteger(bytes)) return void 0;
80
+ return {
81
+ file,
82
+ mediaType,
83
+ width,
84
+ height,
85
+ bytes
86
+ };
87
+ }
88
+ var FeedbackStore = class {
89
+ notesFile;
90
+ seenFile;
91
+ shotsDir;
92
+ /** Writes one after another, so two notes never interleave in the file. */
93
+ queue = Promise.resolve();
94
+ constructor(dir) {
95
+ this.notesFile = join(dir, "notes.jsonl");
96
+ this.seenFile = join(dir, "seen.json");
97
+ this.shotsDir = join(dir, "shots");
98
+ }
99
+ add(note, now = /* @__PURE__ */ new Date()) {
100
+ const id = randomUUID();
101
+ const shot = note.screenshot;
102
+ const stored = {
103
+ id,
104
+ at: now.toISOString(),
105
+ text: note.text,
106
+ page: note.page,
107
+ ...note.element === void 0 ? {} : { element: note.element },
108
+ ...shot === void 0 ? {} : { screenshot: {
109
+ file: `${id}.${shot.mediaType === "image/webp" ? "webp" : "png"}`,
110
+ mediaType: shot.mediaType,
111
+ width: shot.width,
112
+ height: shot.height,
113
+ bytes: shot.data.length
114
+ } }
115
+ };
116
+ return this.serial(async () => {
117
+ await mkdir(join(this.notesFile, ".."), { recursive: true });
118
+ if (shot !== void 0) {
119
+ await mkdir(this.shotsDir, { recursive: true });
120
+ await writeFile(join(this.shotsDir, `${id}.${shot.mediaType === "image/webp" ? "webp" : "png"}`), shot.data);
121
+ }
122
+ await appendFile(this.notesFile, `${JSON.stringify(stored)}\n`);
123
+ return {
124
+ ...stored,
125
+ seen: false
126
+ };
127
+ });
128
+ }
129
+ /** One note's screenshot, when it has one and the file is still there. */
130
+ async screenshot(id) {
131
+ if (!NOTE_ID.test(id)) return void 0;
132
+ for (const [ext, mediaType] of [["webp", "image/webp"], ["png", "image/png"]]) try {
133
+ return {
134
+ bytes: await readFile(join(this.shotsDir, `${id}.${ext}`)),
135
+ mediaType
136
+ };
137
+ } catch {}
138
+ }
139
+ /**
140
+ * The pins of one page, for the badges its visitors see: the elements a note was pinned on, numbered in the order their first note came,
141
+ * oldest first. One pin per element, so two notes on the same element share its badge, and the number of a pin never moves once it is given.
142
+ */
143
+ async pins(page) {
144
+ const pins = [];
145
+ const taken = /* @__PURE__ */ new Set();
146
+ for (const note of (await this.list()).reverse()) {
147
+ const element = note.element;
148
+ if (note.page !== page || element === void 0 || taken.has(element.selector)) continue;
149
+ taken.add(element.selector);
150
+ pins.push({
151
+ selector: element.selector,
152
+ number: pins.length + 1
153
+ });
154
+ }
155
+ return pins;
156
+ }
157
+ /** Every note, newest first. A line that is not a note is skipped. */
158
+ async list() {
159
+ if (!existsSync(this.notesFile)) return [];
160
+ const seen = await this.seen();
161
+ const notes = [];
162
+ for (const line of (await readFile(this.notesFile, "utf8")).split("\n")) {
163
+ if (line.trim() === "") continue;
164
+ try {
165
+ const raw = JSON.parse(line);
166
+ if (typeof raw.id === "string" && typeof raw.at === "string" && typeof raw.text === "string" && typeof raw.page === "string") {
167
+ const { screenshot, ...rest } = raw;
168
+ const shot = storedScreenshot(screenshot);
169
+ notes.push({
170
+ ...rest,
171
+ seen: seen.has(raw.id),
172
+ ...shot === void 0 ? {} : { screenshot: shot }
173
+ });
174
+ }
175
+ } catch {}
176
+ }
177
+ return notes.reverse();
178
+ }
179
+ markSeen(ids) {
180
+ return this.serial(async () => {
181
+ const seen = await this.seen();
182
+ for (const id of ids) seen.add(id);
183
+ await mkdir(join(this.seenFile, ".."), { recursive: true });
184
+ await writeFile(this.seenFile, JSON.stringify([...seen]));
185
+ });
186
+ }
187
+ async seen() {
188
+ try {
189
+ const ids = JSON.parse(await readFile(this.seenFile, "utf8"));
190
+ return new Set(Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : []);
191
+ } catch {
192
+ return /* @__PURE__ */ new Set();
193
+ }
194
+ }
195
+ serial(work) {
196
+ const next = this.queue.then(work, work);
197
+ this.queue = next.catch(() => {});
198
+ return next;
199
+ }
200
+ };
201
+ //#endregion
202
+ //#region index.ts
203
+ /**
204
+ * Feedback from the people who use the app (docs/design/blends-frame-mockup.html, scenario 9): a Feedback button on every page of the app, in
205
+ * production too. Pressing it turns a picker on: the person clicks the element where they hit a problem or had an idea, or chooses "Nothing
206
+ * specific", writes a note and sends it. The notes are kept in the app's own data and read through the `feedback` service, which the ACRYL frame
207
+ * shows in the builder's left panel ("Feedback from users"), where one click hands a note to an agent.
208
+ *
209
+ * - A middleware appends one script tag (`<mount>/api/feedback/feedback.js`) to every HTML response, so no page is edited (agent-panel's way).
210
+ * - In the ACRYL frame's canvas the button follows the frame's view: Build hides it (the builder has its own left panel for notes), and Preview shows it as
211
+ * production does. A page opened directly keeps it on every page.
212
+ * - `POST <mount>/api/feedback/notes` takes one note from the app's own page (same origin), at most 30 a minute across the app. The form offers
213
+ * "Attach a screenshot of this page" (checked) and says the browser will ask to share the tab; the page adds the tab capture with the picker's
214
+ * outline, downscaled and capped. Only Chromium is offered the option (Firefox and Safari ignore preferCurrentTab and would share the whole
215
+ * screen); unchecking it or a refused capture still sends the note.
216
+ * - `GET <mount>/api/feedback/pins?page=...` answers the numbered badges a page draws on the elements people commented on (the mockup's
217
+ * production feedback): each selector with its number, and no note text, since anyone who opens the page can read this route.
218
+ * - Nobody reads the notes over HTTP here: the builder reads them through the service. Opt-in: `acrylblends add feedback`.
219
+ */
220
+ const name = "feedback";
221
+ const inject = ["router", "appInstance"];
222
+ const NOTES_PER_MINUTE = 30;
223
+ const MOUNT = /^\/[A-Za-z0-9._~\-/]*[A-Za-z0-9._~-]$/u;
224
+ const CLIENT = readFileSync(join(import.meta.dirname, "client.js"), "utf8");
225
+ /** A request from the app's own page: a browser sends Origin on a POST, and it must name this host. */
226
+ function fromOwnPage(headers) {
227
+ const origin = headers.get("origin");
228
+ const host = headers.get("host");
229
+ if (origin === null || host === null) return false;
230
+ try {
231
+ return new URL(origin).host === host;
232
+ } catch {
233
+ return false;
234
+ }
235
+ }
236
+ function apply(ctx, config = {}) {
237
+ const mount = config.mount ?? "";
238
+ if (mount !== "" && !MOUNT.test(mount)) throw new TypeError(`feedback: the app's mount "${mount}" must be empty or an absolute path such as "/app"`);
239
+ const FEEDBACK_PATH = "/api/feedback";
240
+ const PREFIX = `${mount}${FEEDBACK_PATH}`;
241
+ const APP_MOUNT = mount;
242
+ const store = new FeedbackStore(join(ctx.appInstance.home, "feedback"));
243
+ ctx.effect(() => ctx.reflect.provide("feedback", {
244
+ list: () => store.list(),
245
+ markSeen: (ids) => store.markSeen(ids),
246
+ screenshot: (id) => store.screenshot(id)
247
+ }), "feedback: service");
248
+ const tag = `<script type="module" src="${PREFIX}/feedback.js"><\/script>`;
249
+ const addScript = async (c, next) => {
250
+ await next();
251
+ if (!(c.res.headers.get("content-type") ?? "").includes("text/html")) return;
252
+ const html = await c.res.text();
253
+ const headers = new Headers(c.res.headers);
254
+ headers.delete("content-length");
255
+ const body = html.includes(`${PREFIX}/feedback.js`) ? html : html.includes("</body>") ? html.replace("</body>", `${tag}</body>`) : html + tag;
256
+ c.res = new Response(body, {
257
+ status: c.res.status,
258
+ headers
259
+ });
260
+ };
261
+ const router = ctx.router;
262
+ const wrapped = typeof router.wrap === "function";
263
+ if (wrapped) router.wrap?.(addScript);
264
+ const sent = [];
265
+ const app = new Acryl().use("*", async (c, next) => {
266
+ if (wrapped) return next();
267
+ await addScript(c, next);
268
+ }).get(`${FEEDBACK_PATH}/feedback.js`, (c) => c.body(`${CLIENT}\nstart(${JSON.stringify(PREFIX)})\n`, 200, {
269
+ "content-type": "text/javascript; charset=utf-8",
270
+ "cache-control": "no-cache"
271
+ })).get(`${FEEDBACK_PATH}/pins`, async (c) => {
272
+ const page = c.req.query("page");
273
+ if (typeof page !== "string" || !page.startsWith("/") || page.length > LIMITS.page) return c.json({ error: "the page must be a path" }, 400);
274
+ return c.json({ pins: await store.pins(page) }, 200, { "cache-control": "no-store" });
275
+ }).post(`${FEEDBACK_PATH}/notes`, async (c) => {
276
+ if (!fromOwnPage(c.req.raw.headers)) return c.json({ error: "only the app's own page may send feedback" }, 403);
277
+ const now = Date.now();
278
+ while (sent.length > 0 && sent[0] < now - 6e4) sent.shift();
279
+ if (sent.length >= NOTES_PER_MINUTE) return c.json({ error: "too much feedback at once; try again in a minute" }, 429);
280
+ const note = parseNewNote(await c.req.json().catch(() => void 0));
281
+ if (typeof note === "string") return c.json({ error: note }, 400);
282
+ sent.push(now);
283
+ const stored = await store.add(note);
284
+ return c.json({ id: stored.id }, 201);
285
+ });
286
+ ctx.router.route(APP_MOUNT === "" ? "/" : APP_MOUNT, app);
287
+ }
288
+ //#endregion
289
+ export { apply, inject, name };
290
+
291
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../store.ts","../index.ts"],"sourcesContent":["/**\n * The notes people sent, in the app's own data: one JSON line per note in `notes.jsonl`, the ids the builder has seen in `seen.json`, and a note's\n * screenshot as a file in `shots/`. Appending never rewrites a note, so a crash loses at most the note being written; an image is written before its\n * note, so a note never names a missing file.\n */\nimport { randomUUID } from 'node:crypto'\nimport { existsSync } from 'node:fs'\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\n/** The element a note was pinned on: a CSS selector to find it again, and a short name to show. */\nexport interface PinnedElement {\n readonly selector: string\n readonly label: string\n}\n\nexport type ScreenshotMediaType = 'image/webp' | 'image/png'\n\n/** A note's screenshot, as stored beside the notes. */\nexport interface FeedbackScreenshot {\n /** The file under `shots/`. */\n readonly file: string\n readonly mediaType: ScreenshotMediaType\n readonly width: number\n readonly height: number\n readonly bytes: number\n}\n\n/**\n * A note already pinned on an element of a page, as that page's own script sees it: where to find the element again and the number its badge\n * shows. It carries no note text, because anyone who opens the page can read this.\n */\nexport interface FeedbackPin {\n readonly selector: string\n readonly number: number\n}\n\nexport interface FeedbackNote {\n readonly id: string\n /** ISO time it was sent. */\n readonly at: string\n readonly text: string\n /** The page's path (and query) it was sent from. */\n readonly page: string\n /** Absent for \"Nothing specific\". */\n readonly element?: PinnedElement\n /** What the person saw when they sent it; absent when the browser refused the capture. */\n readonly screenshot?: FeedbackScreenshot\n /** The builder has seen it in the frame. */\n readonly seen: boolean\n}\n\n/** One screenshot as the page sent it, decoded and checked. */\nexport interface NewScreenshot {\n readonly mediaType: ScreenshotMediaType\n readonly width: number\n readonly height: number\n readonly data: Buffer\n}\n\nexport interface NewNote {\n readonly text: string\n readonly page: string\n readonly element?: PinnedElement\n readonly screenshot?: NewScreenshot\n}\n\n/** A stored screenshot's bytes and type. */\nexport interface StoredScreenshot {\n readonly bytes: Buffer\n readonly mediaType: ScreenshotMediaType\n}\n\nexport const LIMITS = {\n text: 2000,\n page: 500,\n selector: 500,\n label: 120,\n /** Decoded image bytes; the page downscales and re-encodes below this. */\n screenshotBytes: 512 * 1024,\n screenshotSide: 2000,\n} as const\n\nconst DATA_URL = /^data:(image\\/(?:webp|png));base64,([A-Za-z0-9+/]+={0,2})$/u\nconst NOTE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u\n\n/** One screenshot from the page: a WebP or PNG data URL, its size, and the bytes. A string says what is wrong. */\nexport function parseScreenshot(value: unknown): NewScreenshot | string {\n if (typeof value !== 'object' || value === null) return 'the screenshot must be an object'\n const { data, width, height } = value as Record<string, unknown>\n if (typeof data !== 'string') return 'the screenshot has no image'\n const match = DATA_URL.exec(data)\n if (match === null || match[1] === undefined || match[2] === undefined)\n return 'the screenshot must be a WebP or PNG data URL'\n const mediaType = match[1] as ScreenshotMediaType\n const bytes = Buffer.from(match[2], 'base64')\n if (bytes.length === 0) return 'the screenshot is empty'\n if (bytes.length > LIMITS.screenshotBytes)\n return `a screenshot is at most ${String(Math.round(LIMITS.screenshotBytes / 1024))} KB`\n const webp =\n bytes.subarray(0, 4).toString() === 'RIFF' && bytes.subarray(8, 12).toString() === 'WEBP'\n const png = bytes[0] === 0x89 && bytes.subarray(1, 4).toString() === 'PNG'\n if ((mediaType === 'image/webp' && !webp) || (mediaType === 'image/png' && !png))\n return 'the screenshot is not the image its type names'\n if (\n !Number.isInteger(width) ||\n !Number.isInteger(height) ||\n (width as number) < 1 ||\n (height as number) < 1 ||\n (width as number) > LIMITS.screenshotSide ||\n (height as number) > LIMITS.screenshotSide\n )\n return `the screenshot needs its size, up to ${String(LIMITS.screenshotSide)} px a side`\n return { mediaType, width: width as number, height: height as number, data: bytes }\n}\n\n/** A note as a page sent it, checked; a string says what is wrong. */\nexport function parseNewNote(body: unknown): NewNote | string {\n if (body === null || typeof body !== 'object') return 'send a JSON object'\n const { text, page, element, screenshot } = body as Record<string, unknown>\n if (typeof text !== 'string' || text.trim() === '') return 'write a note'\n if (text.length > LIMITS.text) return `a note has at most ${LIMITS.text} characters`\n if (typeof page !== 'string' || !page.startsWith('/') || page.length > LIMITS.page)\n return 'the page must be a path'\n let pinned: PinnedElement | undefined\n if (element !== undefined && element !== null) {\n if (typeof element !== 'object') return 'the element must be an object'\n const { selector, label } = element as Record<string, unknown>\n if (typeof selector !== 'string' || selector === '' || selector.length > LIMITS.selector)\n return 'the element needs a selector'\n if (typeof label !== 'string' || label === '' || label.length > LIMITS.label)\n return 'the element needs a name'\n pinned = { selector, label }\n }\n let shot: NewScreenshot | undefined\n if (screenshot !== undefined && screenshot !== null) {\n const parsed = parseScreenshot(screenshot)\n if (typeof parsed === 'string') return parsed\n shot = parsed\n }\n return {\n text: text.trim(),\n page,\n ...(pinned === undefined ? {} : { element: pinned }),\n ...(shot === undefined ? {} : { screenshot: shot }),\n }\n}\n\nfunction storedScreenshot(raw: unknown): FeedbackScreenshot | undefined {\n if (raw === null || typeof raw !== 'object') return undefined\n const { file, mediaType, width, height, bytes } = raw as Record<string, unknown>\n if (\n typeof file !== 'string' ||\n (mediaType !== 'image/webp' && mediaType !== 'image/png') ||\n !Number.isInteger(width) ||\n !Number.isInteger(height) ||\n !Number.isInteger(bytes)\n )\n return undefined\n return {\n file,\n mediaType,\n width: width as number,\n height: height as number,\n bytes: bytes as number,\n }\n}\n\nexport class FeedbackStore {\n private readonly notesFile: string\n private readonly seenFile: string\n private readonly shotsDir: string\n /** Writes one after another, so two notes never interleave in the file. */\n private queue: Promise<unknown> = Promise.resolve()\n\n constructor(dir: string) {\n this.notesFile = join(dir, 'notes.jsonl')\n this.seenFile = join(dir, 'seen.json')\n this.shotsDir = join(dir, 'shots')\n }\n\n add(note: NewNote, now: Date = new Date()): Promise<FeedbackNote> {\n const id = randomUUID()\n const shot = note.screenshot\n const stored = {\n id,\n at: now.toISOString(),\n text: note.text,\n page: note.page,\n ...(note.element === undefined ? {} : { element: note.element }),\n ...(shot === undefined\n ? {}\n : {\n screenshot: {\n file: `${id}.${shot.mediaType === 'image/webp' ? 'webp' : 'png'}`,\n mediaType: shot.mediaType,\n width: shot.width,\n height: shot.height,\n bytes: shot.data.length,\n },\n }),\n }\n return this.serial(async () => {\n await mkdir(join(this.notesFile, '..'), { recursive: true })\n if (shot !== undefined) {\n // The image first: a note in the file always has its screenshot.\n await mkdir(this.shotsDir, { recursive: true })\n await writeFile(\n join(this.shotsDir, `${id}.${shot.mediaType === 'image/webp' ? 'webp' : 'png'}`),\n shot.data,\n )\n }\n await appendFile(this.notesFile, `${JSON.stringify(stored)}\\n`)\n return { ...stored, seen: false }\n })\n }\n\n /** One note's screenshot, when it has one and the file is still there. */\n async screenshot(id: string): Promise<StoredScreenshot | undefined> {\n if (!NOTE_ID.test(id)) return undefined\n for (const [ext, mediaType] of [\n ['webp', 'image/webp'],\n ['png', 'image/png'],\n ] as const) {\n try {\n return { bytes: await readFile(join(this.shotsDir, `${id}.${ext}`)), mediaType }\n } catch {\n // Not this type; try the other.\n }\n }\n return undefined\n }\n\n /**\n * The pins of one page, for the badges its visitors see: the elements a note was pinned on, numbered in the order their first note came,\n * oldest first. One pin per element, so two notes on the same element share its badge, and the number of a pin never moves once it is given.\n */\n async pins(page: string): Promise<FeedbackPin[]> {\n const pins: FeedbackPin[] = []\n const taken = new Set<string>()\n for (const note of (await this.list()).reverse()) {\n const element = note.element\n if (note.page !== page || element === undefined || taken.has(element.selector)) continue\n taken.add(element.selector)\n pins.push({ selector: element.selector, number: pins.length + 1 })\n }\n return pins\n }\n\n /** Every note, newest first. A line that is not a note is skipped. */\n async list(): Promise<FeedbackNote[]> {\n if (!existsSync(this.notesFile)) return []\n const seen = await this.seen()\n const notes: FeedbackNote[] = []\n for (const line of (await readFile(this.notesFile, 'utf8')).split('\\n')) {\n if (line.trim() === '') continue\n try {\n const raw = JSON.parse(line) as Omit<FeedbackNote, 'seen'> & {\n readonly screenshot?: unknown\n }\n if (\n typeof raw.id === 'string' &&\n typeof raw.at === 'string' &&\n typeof raw.text === 'string' &&\n typeof raw.page === 'string'\n ) {\n const { screenshot, ...rest } = raw\n const shot = storedScreenshot(screenshot)\n notes.push({\n ...rest,\n seen: seen.has(raw.id),\n ...(shot === undefined ? {} : { screenshot: shot }),\n })\n }\n } catch {\n // A torn last line: skipped.\n }\n }\n return notes.reverse()\n }\n\n markSeen(ids: readonly string[]): Promise<void> {\n return this.serial(async () => {\n const seen = await this.seen()\n for (const id of ids) seen.add(id)\n await mkdir(join(this.seenFile, '..'), { recursive: true })\n await writeFile(this.seenFile, JSON.stringify([...seen]))\n })\n }\n\n private async seen(): Promise<Set<string>> {\n try {\n const ids: unknown = JSON.parse(await readFile(this.seenFile, 'utf8'))\n return new Set(\n Array.isArray(ids) ? ids.filter((id): id is string => typeof id === 'string') : [],\n )\n } catch {\n return new Set()\n }\n }\n\n private serial<T>(work: () => Promise<T>): Promise<T> {\n const next = this.queue.then(work, work)\n this.queue = next.catch(() => {})\n return next\n }\n}\n","/**\n * Feedback from the people who use the app (docs/design/blends-frame-mockup.html, scenario 9): a Feedback button on every page of the app, in\n * production too. Pressing it turns a picker on: the person clicks the element where they hit a problem or had an idea, or chooses \"Nothing\n * specific\", writes a note and sends it. The notes are kept in the app's own data and read through the `feedback` service, which the ACRYL frame\n * shows in the builder's left panel (\"Feedback from users\"), where one click hands a note to an agent.\n *\n * - A middleware appends one script tag (`<mount>/api/feedback/feedback.js`) to every HTML response, so no page is edited (agent-panel's way).\n * - In the ACRYL frame's canvas the button follows the frame's view: Build hides it (the builder has its own left panel for notes), and Preview shows it as\n * production does. A page opened directly keeps it on every page.\n * - `POST <mount>/api/feedback/notes` takes one note from the app's own page (same origin), at most 30 a minute across the app. The form offers\n * \"Attach a screenshot of this page\" (checked) and says the browser will ask to share the tab; the page adds the tab capture with the picker's\n * outline, downscaled and capped. Only Chromium is offered the option (Firefox and Safari ignore preferCurrentTab and would share the whole\n * screen); unchecking it or a refused capture still sends the note.\n * - `GET <mount>/api/feedback/pins?page=...` answers the numbered badges a page draws on the elements people commented on (the mockup's\n * production feedback): each selector with its number, and no note text, since anyone who opens the page can read this route.\n * - Nobody reads the notes over HTTP here: the builder reads them through the service. Opt-in: `acrylblends add feedback`.\n */\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type {} from '@acryldev/instance'\nimport { Acryl } from '@acryldev/router'\nimport type { Context } from '@deepseek-ai/cordis'\nimport {\n type FeedbackNote,\n FeedbackStore,\n LIMITS,\n parseNewNote,\n type StoredScreenshot,\n} from './store.ts'\n\nexport type { FeedbackNote, FeedbackPin, PinnedElement } from './store.ts'\n\nexport const name = 'feedback'\nexport const inject = ['router', 'appInstance']\n\n/** What the builder's tools read: every note, newest first, and marking notes seen. */\nexport interface Feedback {\n list(): Promise<FeedbackNote[]>\n markSeen(ids: readonly string[]): Promise<void>\n /** A note's screenshot, when it has one and the file is still there. */\n screenshot(id: string): Promise<StoredScreenshot | undefined>\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n feedback: Feedback\n }\n}\n\nexport interface FeedbackConfig {\n /** The URL prefix the app is mounted at: empty on the app's own server, `/app` when the ACRYL frame hosts it (agent-panel's `mount`). */\n mount?: string\n}\n\nconst NOTES_PER_MINUTE = 30\nconst MOUNT = /^\\/[A-Za-z0-9._~\\-/]*[A-Za-z0-9._~-]$/u\nconst CLIENT = readFileSync(join(import.meta.dirname, 'client.js'), 'utf8')\n\n/** A request from the app's own page: a browser sends Origin on a POST, and it must name this host. */\nfunction fromOwnPage(headers: Headers): boolean {\n const origin = headers.get('origin')\n const host = headers.get('host')\n if (origin === null || host === null) return false\n try {\n return new URL(origin).host === host\n } catch {\n return false\n }\n}\n\nexport function apply(ctx: Context, config: FeedbackConfig = {}): void {\n const mount = config.mount ?? ''\n if (mount !== '' && !MOUNT.test(mount))\n throw new TypeError(\n `feedback: the app's mount \"${mount}\" must be empty or an absolute path such as \"/app\"`,\n )\n const FEEDBACK_PATH = '/api/feedback'\n const PREFIX = `${mount}${FEEDBACK_PATH}`\n // The routes mount at the app's own mount and keep the fixed feedback path inside (the frame's router prefixes the mount, not the routes).\n const APP_MOUNT = mount\n const store = new FeedbackStore(join(ctx.appInstance.home, 'feedback'))\n ctx.effect(\n () =>\n ctx.reflect.provide('feedback', {\n list: () => store.list(),\n markSeen: (ids) => store.markSeen(ids),\n screenshot: (id) => store.screenshot(id),\n } satisfies Feedback),\n 'feedback: service',\n )\n\n const tag = `<script type=\"module\" src=\"${PREFIX}/feedback.js\"></script>`\n const addScript = async (c: { res: Response }, next: () => Promise<void>): Promise<void> => {\n await next()\n if (!(c.res.headers.get('content-type') ?? '').includes('text/html')) return\n const html = await c.res.text()\n const headers = new Headers(c.res.headers)\n headers.delete('content-length')\n const body = html.includes(`${PREFIX}/feedback.js`)\n ? html\n : html.includes('</body>')\n ? html.replace('</body>', `${tag}</body>`)\n : html + tag\n c.res = new Response(body, { status: c.res.status, headers })\n }\n const router = ctx.router as unknown as { wrap?: (middleware: typeof addScript) => unknown }\n const wrapped = typeof router.wrap === 'function'\n if (wrapped) router.wrap?.(addScript)\n\n const sent: number[] = []\n const app = new Acryl()\n .use('*', async (c, next) => {\n if (wrapped) return next()\n await addScript(c, next)\n })\n .get(`${FEEDBACK_PATH}/feedback.js`, (c) =>\n c.body(`${CLIENT}\\nstart(${JSON.stringify(PREFIX)})\\n`, 200, {\n 'content-type': 'text/javascript; charset=utf-8',\n 'cache-control': 'no-cache',\n }),\n )\n .get(`${FEEDBACK_PATH}/pins`, async (c) => {\n const page = c.req.query('page')\n if (typeof page !== 'string' || !page.startsWith('/') || page.length > LIMITS.page)\n return c.json({ error: 'the page must be a path' }, 400)\n // The page's visitors can read this route: it says where the commented elements are and nothing the notes say.\n return c.json({ pins: await store.pins(page) }, 200, { 'cache-control': 'no-store' })\n })\n .post(`${FEEDBACK_PATH}/notes`, async (c) => {\n if (!fromOwnPage(c.req.raw.headers))\n return c.json({ error: \"only the app's own page may send feedback\" }, 403)\n const now = Date.now()\n while (sent.length > 0 && (sent[0] as number) < now - 60_000) sent.shift()\n if (sent.length >= NOTES_PER_MINUTE)\n return c.json({ error: 'too much feedback at once; try again in a minute' }, 429)\n const note = parseNewNote(await c.req.json().catch(() => undefined))\n if (typeof note === 'string') return c.json({ error: note }, 400)\n sent.push(now)\n const stored = await store.add(note)\n return c.json({ id: stored.id }, 201)\n })\n ctx.router.route(APP_MOUNT === '' ? '/' : APP_MOUNT, app)\n}\n"],"mappings":";;;;;;;;;;;AAyEA,MAAa,SAAS;CACpB,MAAM;CACN,MAAM;CACN,UAAU;CACV,OAAO;;CAEP,iBAAiB,MAAM;CACvB,gBAAgB;AAClB;AAEA,MAAM,WAAW;AACjB,MAAM,UAAU;;AAGhB,SAAgB,gBAAgB,OAAwC;CACtE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,EAAE,MAAM,OAAO,WAAW;CAChC,IAAI,OAAO,SAAS,UAAU,OAAO;CACrC,MAAM,QAAQ,SAAS,KAAK,IAAI;CAChC,IAAI,UAAU,QAAQ,MAAM,OAAO,KAAA,KAAa,MAAM,OAAO,KAAA,GAC3D,OAAO;CACT,MAAM,YAAY,MAAM;CACxB,MAAM,QAAQ,OAAO,KAAK,MAAM,IAAI,QAAQ;CAC5C,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,IAAI,MAAM,SAAS,OAAO,iBACxB,OAAO,2BAA2B,OAAO,K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M,KAAQ,KAAK,MAAM;EACzE,IAAI,KAAK,UAAU,kBACjB,OAAO,EAAE,KAAK,EAAE,OAAO,mDAAmD,GAAG,GAAG;EAClF,MAAM,OAAO,aAAa,MAAM,EAAE,IAAI,KAAK,CAAC,CAAC,YAAY,KAAA,CAAS,CAAC;EACnE,IAAI,OAAO,SAAS,UAAU,OAAO,EAAE,KAAK,EAAE,OAAO,KAAK,GAAG,GAAG;EAChE,KAAK,KAAK,GAAG;EACb,MAAM,SAAS,MAAM,MAAM,IAAI,IAAI;EACnC,OAAO,EAAE,KAAK,EAAE,IAAI,OAAO,GAAG,GAAG,GAAG;CACtC,CAAC;CACH,IAAI,OAAO,MAAM,cAAc,KAAK,MAAM,WAAW,GAAG;AAC1D"}
@@ -0,0 +1,22 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { type FeedbackNote, type StoredScreenshot } from './store.ts';
3
+ export type { FeedbackNote, FeedbackPin, PinnedElement } from './store.ts';
4
+ export declare const name = "feedback";
5
+ export declare const inject: string[];
6
+ /** What the builder's tools read: every note, newest first, and marking notes seen. */
7
+ export interface Feedback {
8
+ list(): Promise<FeedbackNote[]>;
9
+ markSeen(ids: readonly string[]): Promise<void>;
10
+ /** A note's screenshot, when it has one and the file is still there. */
11
+ screenshot(id: string): Promise<StoredScreenshot | undefined>;
12
+ }
13
+ declare module '@deepseek-ai/cordis' {
14
+ interface Context {
15
+ feedback: Feedback;
16
+ }
17
+ }
18
+ export interface FeedbackConfig {
19
+ /** The URL prefix the app is mounted at: empty on the app's own server, `/app` when the ACRYL frame hosts it (agent-panel's `mount`). */
20
+ mount?: string;
21
+ }
22
+ export declare function apply(ctx: Context, config?: FeedbackConfig): void;
@@ -0,0 +1,89 @@
1
+ /** The element a note was pinned on: a CSS selector to find it again, and a short name to show. */
2
+ export interface PinnedElement {
3
+ readonly selector: string;
4
+ readonly label: string;
5
+ }
6
+ export type ScreenshotMediaType = 'image/webp' | 'image/png';
7
+ /** A note's screenshot, as stored beside the notes. */
8
+ export interface FeedbackScreenshot {
9
+ /** The file under `shots/`. */
10
+ readonly file: string;
11
+ readonly mediaType: ScreenshotMediaType;
12
+ readonly width: number;
13
+ readonly height: number;
14
+ readonly bytes: number;
15
+ }
16
+ /**
17
+ * A note already pinned on an element of a page, as that page's own script sees it: where to find the element again and the number its badge
18
+ * shows. It carries no note text, because anyone who opens the page can read this.
19
+ */
20
+ export interface FeedbackPin {
21
+ readonly selector: string;
22
+ readonly number: number;
23
+ }
24
+ export interface FeedbackNote {
25
+ readonly id: string;
26
+ /** ISO time it was sent. */
27
+ readonly at: string;
28
+ readonly text: string;
29
+ /** The page's path (and query) it was sent from. */
30
+ readonly page: string;
31
+ /** Absent for "Nothing specific". */
32
+ readonly element?: PinnedElement;
33
+ /** What the person saw when they sent it; absent when the browser refused the capture. */
34
+ readonly screenshot?: FeedbackScreenshot;
35
+ /** The builder has seen it in the frame. */
36
+ readonly seen: boolean;
37
+ }
38
+ /** One screenshot as the page sent it, decoded and checked. */
39
+ export interface NewScreenshot {
40
+ readonly mediaType: ScreenshotMediaType;
41
+ readonly width: number;
42
+ readonly height: number;
43
+ readonly data: Buffer;
44
+ }
45
+ export interface NewNote {
46
+ readonly text: string;
47
+ readonly page: string;
48
+ readonly element?: PinnedElement;
49
+ readonly screenshot?: NewScreenshot;
50
+ }
51
+ /** A stored screenshot's bytes and type. */
52
+ export interface StoredScreenshot {
53
+ readonly bytes: Buffer;
54
+ readonly mediaType: ScreenshotMediaType;
55
+ }
56
+ export declare const LIMITS: {
57
+ readonly text: 2000;
58
+ readonly page: 500;
59
+ readonly selector: 500;
60
+ readonly label: 120;
61
+ /** Decoded image bytes; the page downscales and re-encodes below this. */
62
+ readonly screenshotBytes: number;
63
+ readonly screenshotSide: 2000;
64
+ };
65
+ /** One screenshot from the page: a WebP or PNG data URL, its size, and the bytes. A string says what is wrong. */
66
+ export declare function parseScreenshot(value: unknown): NewScreenshot | string;
67
+ /** A note as a page sent it, checked; a string says what is wrong. */
68
+ export declare function parseNewNote(body: unknown): NewNote | string;
69
+ export declare class FeedbackStore {
70
+ private readonly notesFile;
71
+ private readonly seenFile;
72
+ private readonly shotsDir;
73
+ /** Writes one after another, so two notes never interleave in the file. */
74
+ private queue;
75
+ constructor(dir: string);
76
+ add(note: NewNote, now?: Date): Promise<FeedbackNote>;
77
+ /** One note's screenshot, when it has one and the file is still there. */
78
+ screenshot(id: string): Promise<StoredScreenshot | undefined>;
79
+ /**
80
+ * The pins of one page, for the badges its visitors see: the elements a note was pinned on, numbered in the order their first note came,
81
+ * oldest first. One pin per element, so two notes on the same element share its badge, and the number of a pin never moves once it is given.
82
+ */
83
+ pins(page: string): Promise<FeedbackPin[]>;
84
+ /** Every note, newest first. A line that is not a note is skipped. */
85
+ list(): Promise<FeedbackNote[]>;
86
+ markSeen(ids: readonly string[]): Promise<void>;
87
+ private seen;
88
+ private serial;
89
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("tsdown").UserConfig;
2
+ export default _default;
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@acryldev/feedback",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Feedback from the people who use the app: a Feedback button on every page, in production too, that lets them pinpoint the element they mean (or choose \"Nothing specific\") and send a note; the ACRYL frame shows the notes in the builder's left panel.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/acryldev/acryl.git",
9
+ "directory": "plugins/feedback"
10
+ },
11
+ "homepage": "https://github.com/acryldev/acryl/tree/main/plugins/feedback#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/acryldev/acryl/issues"
14
+ },
15
+ "type": "module",
16
+ "engines": {
17
+ "node": "^22.19.0 || >=24.0.0"
18
+ },
19
+ "main": "./lib/index.js",
20
+ "types": "./lib/types/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./lib/types/index.d.ts",
24
+ "default": "./lib/index.js"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "dependencies": {
29
+ "@acryldev/instance": "0.1.1",
30
+ "@acryldev/router": "0.1.0"
31
+ },
32
+ "peerDependencies": {
33
+ "@deepseek-ai/cordis": "^4.0.2"
34
+ },
35
+ "devDependencies": {
36
+ "@deepseek-ai/cordis": "4.0.4",
37
+ "@types/node": "^22.20.0",
38
+ "tsdown": "0.22.2",
39
+ "typescript": "6.0.3"
40
+ },
41
+ "scripts": {
42
+ "build": "tsdown && tsc -p tsconfig.json --emitDeclarationOnly && node scripts/copy-assets.mjs"
43
+ }
6
44
  }
package/plugin.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "feedback",
3
+ "description": "Feedback from the people who use the app: a Feedback button on every page, in production too, that lets them pinpoint the element they mean (or choose \"Nothing specific\") and send a note; the ACRYL frame shows the notes in the builder's left panel.",
4
+ "requires": ["router", "instance"],
5
+ "inject": ["router", "appInstance"],
6
+ "provides": ["feedback"],
7
+ "dependencies": {
8
+ "@deepseek-ai/cordis": "4.0.4"
9
+ },
10
+ "mount": "add a row `- id: feedback` / `name: feedback` to blend.yaml BEFORE the `routes` row (its middleware adds one script tag to every HTML page the routes after it answer) and register it in src/app.ts: 'feedback': feedback",
11
+ "entries": {
12
+ "": "index.ts"
13
+ }
14
+ }
@@ -0,0 +1,3 @@
1
+ import { cpSync } from 'node:fs'
2
+
3
+ cpSync(new URL('../client.js', import.meta.url), new URL('../lib/client.js', import.meta.url))