@siteping/adapter-kit 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/README.md +32 -0
- package/dist/chunk-YQHAD24P.js +97 -0
- package/dist/chunk-YQHAD24P.js.map +1 -0
- package/dist/errors.d.cts +41 -0
- package/dist/errors.d.ts +41 -0
- package/dist/filters.d.cts +33 -0
- package/dist/filters.d.ts +33 -0
- package/dist/i18n.d.cts +67 -0
- package/dist/i18n.d.ts +67 -0
- package/dist/index.cjs +256 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +170 -0
- package/dist/index.js.map +1 -0
- package/dist/schema.d.cts +263 -0
- package/dist/schema.d.ts +263 -0
- package/dist/screenshot-storage.d.cts +61 -0
- package/dist/screenshot-storage.d.ts +61 -0
- package/dist/siteping-core-testing.d.cts +40 -0
- package/dist/siteping-core-testing.d.ts +40 -0
- package/dist/siteping-core.d.cts +16 -0
- package/dist/siteping-core.d.ts +16 -0
- package/dist/store-helpers.d.cts +87 -0
- package/dist/store-helpers.d.ts +87 -0
- package/dist/testing.cjs +484 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +1 -0
- package/dist/testing.d.ts +1 -0
- package/dist/testing.js +433 -0
- package/dist/testing.js.map +1 -0
- package/dist/type-utils.d.cts +58 -0
- package/dist/type-utils.d.ts +58 -0
- package/dist/types.d.cts +840 -0
- package/dist/types.d.ts +840 -0
- package/dist/wire.d.cts +35 -0
- package/dist/wire.d.ts +35 -0
- package/package.json +77 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
CLOSED_FEEDBACK_STATUSES: () => CLOSED_FEEDBACK_STATUSES,
|
|
24
|
+
CONSOLE_DIAGNOSTIC_LEVELS: () => CONSOLE_DIAGNOSTIC_LEVELS,
|
|
25
|
+
FEEDBACK_STATUSES: () => FEEDBACK_STATUSES,
|
|
26
|
+
FEEDBACK_TYPES: () => FEEDBACK_TYPES,
|
|
27
|
+
OPEN_FEEDBACK_STATUSES: () => OPEN_FEEDBACK_STATUSES,
|
|
28
|
+
StoreDuplicateError: () => StoreDuplicateError,
|
|
29
|
+
StoreNotFoundError: () => StoreNotFoundError,
|
|
30
|
+
StorePersistenceError: () => StorePersistenceError,
|
|
31
|
+
applyFeedbackFilters: () => applyFeedbackFilters,
|
|
32
|
+
buildAnnotationRecord: () => buildAnnotationRecord,
|
|
33
|
+
buildFeedbackRecord: () => buildFeedbackRecord,
|
|
34
|
+
createCollectionStore: () => createCollectionStore,
|
|
35
|
+
flattenAnnotation: () => flattenAnnotation,
|
|
36
|
+
isClosedStatus: () => isClosedStatus,
|
|
37
|
+
isStoreDuplicate: () => isStoreDuplicate,
|
|
38
|
+
isStoreNotFound: () => isStoreNotFound,
|
|
39
|
+
isStorePersistence: () => isStorePersistence,
|
|
40
|
+
toFeedbackUpdate: () => toFeedbackUpdate
|
|
41
|
+
});
|
|
42
|
+
module.exports = __toCommonJS(index_exports);
|
|
43
|
+
|
|
44
|
+
// ../core/src/filters.ts
|
|
45
|
+
var DEFAULT_LIMIT = 50;
|
|
46
|
+
var MAX_LIMIT = 100;
|
|
47
|
+
function applyFeedbackFilters(items, query) {
|
|
48
|
+
let results = items.filter((f) => f.projectName === query.projectName);
|
|
49
|
+
if (query.type) results = results.filter((f) => f.type === query.type);
|
|
50
|
+
if (query.statuses && query.statuses.length > 0) {
|
|
51
|
+
const allowed = query.statuses;
|
|
52
|
+
results = results.filter((f) => allowed.includes(f.status));
|
|
53
|
+
} else if (query.status) {
|
|
54
|
+
results = results.filter((f) => f.status === query.status);
|
|
55
|
+
}
|
|
56
|
+
if (query.url) results = results.filter((f) => f.url === query.url);
|
|
57
|
+
if (query.urlPattern) results = results.filter((f) => f.urlPattern === query.urlPattern);
|
|
58
|
+
if (query.search) {
|
|
59
|
+
const s = query.search.toLowerCase();
|
|
60
|
+
results = results.filter((f) => f.message.toLowerCase().includes(s));
|
|
61
|
+
}
|
|
62
|
+
results.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
|
|
63
|
+
const total = results.length;
|
|
64
|
+
const page = Math.max(1, query.page ?? 1);
|
|
65
|
+
const limit = Math.max(1, Math.min(query.limit ?? DEFAULT_LIMIT, MAX_LIMIT));
|
|
66
|
+
const start = (page - 1) * limit;
|
|
67
|
+
return { feedbacks: results.slice(start, start + limit), total };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ../core/src/type-utils.ts
|
|
71
|
+
function isRecord(value) {
|
|
72
|
+
return typeof value === "object" && value !== null;
|
|
73
|
+
}
|
|
74
|
+
function hasOwn(value, key) {
|
|
75
|
+
return isRecord(value) && key in value;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ../core/src/types.ts
|
|
79
|
+
var FEEDBACK_TYPES = ["question", "change", "bug", "other"];
|
|
80
|
+
var FEEDBACK_STATUSES = ["open", "in_progress", "resolved", "wont_fix"];
|
|
81
|
+
var CLOSED_FEEDBACK_STATUSES = ["resolved", "wont_fix"];
|
|
82
|
+
var OPEN_FEEDBACK_STATUSES = ["open", "in_progress"];
|
|
83
|
+
function isClosedStatus(status) {
|
|
84
|
+
return CLOSED_FEEDBACK_STATUSES.includes(status);
|
|
85
|
+
}
|
|
86
|
+
function toFeedbackUpdate(status, closedAt = /* @__PURE__ */ new Date()) {
|
|
87
|
+
return isClosedStatus(status) ? { status, resolvedAt: closedAt } : { status, resolvedAt: null };
|
|
88
|
+
}
|
|
89
|
+
var StoreNotFoundError = class extends Error {
|
|
90
|
+
code = "STORE_NOT_FOUND";
|
|
91
|
+
constructor(message = "Record not found") {
|
|
92
|
+
super(message);
|
|
93
|
+
this.name = "StoreNotFoundError";
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
var StoreDuplicateError = class extends Error {
|
|
97
|
+
code = "STORE_DUPLICATE";
|
|
98
|
+
constructor(message = "Duplicate record") {
|
|
99
|
+
super(message);
|
|
100
|
+
this.name = "StoreDuplicateError";
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
var StorePersistenceError = class extends Error {
|
|
104
|
+
code = "STORE_PERSISTENCE";
|
|
105
|
+
constructor(message = "Failed to persist store mutation", options) {
|
|
106
|
+
super(message, options);
|
|
107
|
+
this.name = "StorePersistenceError";
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
function hasErrorCode(error, code) {
|
|
111
|
+
return hasOwn(error, "code") && error.code === code;
|
|
112
|
+
}
|
|
113
|
+
function isStoreNotFound(error) {
|
|
114
|
+
if (error instanceof StoreNotFoundError) return true;
|
|
115
|
+
return hasErrorCode(error, "P2025");
|
|
116
|
+
}
|
|
117
|
+
function isStoreDuplicate(error) {
|
|
118
|
+
if (error instanceof StoreDuplicateError) return true;
|
|
119
|
+
return hasErrorCode(error, "P2002");
|
|
120
|
+
}
|
|
121
|
+
function isStorePersistence(error) {
|
|
122
|
+
if (error instanceof StorePersistenceError) return true;
|
|
123
|
+
return hasErrorCode(error, "STORE_PERSISTENCE");
|
|
124
|
+
}
|
|
125
|
+
function flattenAnnotation(ann) {
|
|
126
|
+
return {
|
|
127
|
+
cssSelector: ann.anchor.cssSelector,
|
|
128
|
+
xpath: ann.anchor.xpath,
|
|
129
|
+
textSnippet: ann.anchor.textSnippet,
|
|
130
|
+
elementTag: ann.anchor.elementTag,
|
|
131
|
+
elementId: ann.anchor.elementId,
|
|
132
|
+
textPrefix: ann.anchor.textPrefix,
|
|
133
|
+
textSuffix: ann.anchor.textSuffix,
|
|
134
|
+
fingerprint: ann.anchor.fingerprint,
|
|
135
|
+
neighborText: ann.anchor.neighborText,
|
|
136
|
+
anchorKey: ann.anchor.anchorKey ?? null,
|
|
137
|
+
xPct: ann.rect.xPct,
|
|
138
|
+
yPct: ann.rect.yPct,
|
|
139
|
+
wPct: ann.rect.wPct,
|
|
140
|
+
hPct: ann.rect.hPct,
|
|
141
|
+
scrollX: ann.scrollX,
|
|
142
|
+
scrollY: ann.scrollY,
|
|
143
|
+
viewportW: ann.viewportW,
|
|
144
|
+
viewportH: ann.viewportH,
|
|
145
|
+
devicePixelRatio: ann.devicePixelRatio
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
var CONSOLE_DIAGNOSTIC_LEVELS = ["log", "info", "warn", "error"];
|
|
149
|
+
|
|
150
|
+
// ../core/src/store-helpers.ts
|
|
151
|
+
function buildAnnotationRecord(input, ctx) {
|
|
152
|
+
return {
|
|
153
|
+
id: ctx.id,
|
|
154
|
+
feedbackId: ctx.feedbackId,
|
|
155
|
+
cssSelector: input.cssSelector,
|
|
156
|
+
xpath: input.xpath,
|
|
157
|
+
textSnippet: input.textSnippet,
|
|
158
|
+
elementTag: input.elementTag,
|
|
159
|
+
elementId: input.elementId ?? null,
|
|
160
|
+
textPrefix: input.textPrefix,
|
|
161
|
+
textSuffix: input.textSuffix,
|
|
162
|
+
fingerprint: input.fingerprint,
|
|
163
|
+
neighborText: input.neighborText,
|
|
164
|
+
anchorKey: input.anchorKey ?? null,
|
|
165
|
+
xPct: input.xPct,
|
|
166
|
+
yPct: input.yPct,
|
|
167
|
+
wPct: input.wPct,
|
|
168
|
+
hPct: input.hPct,
|
|
169
|
+
scrollX: input.scrollX,
|
|
170
|
+
scrollY: input.scrollY,
|
|
171
|
+
viewportW: input.viewportW,
|
|
172
|
+
viewportH: input.viewportH,
|
|
173
|
+
devicePixelRatio: input.devicePixelRatio,
|
|
174
|
+
createdAt: ctx.now
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function buildFeedbackRecord(input, ctx) {
|
|
178
|
+
const now = ctx.now ?? /* @__PURE__ */ new Date();
|
|
179
|
+
return {
|
|
180
|
+
id: ctx.id,
|
|
181
|
+
type: input.type,
|
|
182
|
+
message: input.message,
|
|
183
|
+
status: input.status,
|
|
184
|
+
projectName: input.projectName,
|
|
185
|
+
url: input.url,
|
|
186
|
+
urlPattern: input.urlPattern ?? null,
|
|
187
|
+
authorName: input.authorName,
|
|
188
|
+
authorEmail: input.authorEmail,
|
|
189
|
+
viewport: input.viewport,
|
|
190
|
+
userAgent: input.userAgent,
|
|
191
|
+
clientId: input.clientId,
|
|
192
|
+
resolvedAt: null,
|
|
193
|
+
createdAt: now,
|
|
194
|
+
updatedAt: now,
|
|
195
|
+
annotations: input.annotations.map(
|
|
196
|
+
(ann) => buildAnnotationRecord(ann, { id: ctx.annotationId(), feedbackId: ctx.id, now })
|
|
197
|
+
),
|
|
198
|
+
screenshotUrl: input.screenshotDataUrl ?? null,
|
|
199
|
+
screenshotRegion: input.screenshotRegion ?? null,
|
|
200
|
+
diagnostics: input.diagnostics ?? null
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
function createCollectionStore(backend) {
|
|
204
|
+
return {
|
|
205
|
+
async createFeedback(data) {
|
|
206
|
+
const feedbacks = await backend.load();
|
|
207
|
+
const existing = feedbacks.find((f) => f.clientId === data.clientId);
|
|
208
|
+
if (existing) return existing;
|
|
209
|
+
const record = buildFeedbackRecord(data, {
|
|
210
|
+
id: backend.generateId(),
|
|
211
|
+
annotationId: () => backend.generateId()
|
|
212
|
+
});
|
|
213
|
+
feedbacks.unshift(record);
|
|
214
|
+
try {
|
|
215
|
+
await backend.persist(feedbacks);
|
|
216
|
+
} catch (err) {
|
|
217
|
+
if (!record.screenshotUrl) throw err;
|
|
218
|
+
record.screenshotUrl = null;
|
|
219
|
+
await backend.persist(feedbacks);
|
|
220
|
+
}
|
|
221
|
+
return record;
|
|
222
|
+
},
|
|
223
|
+
async getFeedbacks(query) {
|
|
224
|
+
return applyFeedbackFilters(await backend.load(), query);
|
|
225
|
+
},
|
|
226
|
+
async findByClientId(clientId) {
|
|
227
|
+
return (await backend.load()).find((f) => f.clientId === clientId) ?? null;
|
|
228
|
+
},
|
|
229
|
+
async updateFeedback(id, data) {
|
|
230
|
+
const feedbacks = await backend.load();
|
|
231
|
+
const fb = feedbacks.find((f) => f.id === id);
|
|
232
|
+
if (!fb) throw new StoreNotFoundError();
|
|
233
|
+
fb.status = data.status;
|
|
234
|
+
fb.resolvedAt = data.resolvedAt;
|
|
235
|
+
fb.updatedAt = /* @__PURE__ */ new Date();
|
|
236
|
+
await backend.persist(feedbacks);
|
|
237
|
+
return fb;
|
|
238
|
+
},
|
|
239
|
+
async deleteFeedback(id) {
|
|
240
|
+
const feedbacks = await backend.load();
|
|
241
|
+
const idx = feedbacks.findIndex((f) => f.id === id);
|
|
242
|
+
if (idx === -1) throw new StoreNotFoundError();
|
|
243
|
+
feedbacks.splice(idx, 1);
|
|
244
|
+
await backend.persist(feedbacks);
|
|
245
|
+
},
|
|
246
|
+
async deleteAllFeedbacks(projectName) {
|
|
247
|
+
const feedbacks = await backend.load();
|
|
248
|
+
await backend.persist(feedbacks.filter((f) => f.projectName !== projectName));
|
|
249
|
+
},
|
|
250
|
+
async verifyProjectOwnership(id, projectName) {
|
|
251
|
+
const fb = (await backend.load()).find((f) => f.id === id);
|
|
252
|
+
return fb !== void 0 && fb.projectName === projectName;
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../core/src/filters.ts","../../core/src/type-utils.ts","../../core/src/types.ts","../../core/src/store-helpers.ts"],"sourcesContent":["/**\n * Everything needed to build a custom Siteping store adapter, published —\n * `@siteping/core` is an internal (unpublished) package, so this kit is the\n * supported dependency for third-party adapters.\n *\n * Two ways to implement a store:\n *\n * 1. **Snapshot backends** (KV, flat file, IndexedDB, …): hand\n * {@link createCollectionStore} a `load`/`persist`/`generateId` trio and\n * every store semantic (clientId dedup, filtering, pagination, error\n * contract) comes built-in — an adapter is ~20 lines plus its storage\n * specifics.\n * 2. **Query backends** (SQL, ORMs): implement {@link SitepingStore}\n * directly; {@link buildFeedbackRecord} / {@link buildAnnotationRecord}\n * handle input→record construction, and the JSDoc on `SitepingStore`\n * documents the exact error contract.\n *\n * Either way, verify with the conformance suite from\n * `@siteping/adapter-kit/testing`:\n *\n * @example\n * ```ts\n * import { testSitepingStore } from \"@siteping/adapter-kit/testing\";\n * import { MyStore } from \"../src/index.js\";\n *\n * testSitepingStore(() => new MyStore());\n * ```\n */\n\n// The store contract and its data model\n// Building blocks — record construction, the shared filter pipeline, and\n// the full collection-store engine\nexport type {\n AnchorData,\n AnnotationCreateInput,\n AnnotationPayload,\n AnnotationRecord,\n AnnotationResponse,\n ClosedFeedbackStatus,\n CollectionStore,\n CollectionStoreBackend,\n ConsoleDiagnosticEntry,\n ConsoleDiagnosticLevel,\n DiagnosticsSnapshot,\n FeedbackCreateInput,\n FeedbackPage,\n FeedbackPayload,\n FeedbackQuery,\n FeedbackRecord,\n FeedbackResponse,\n FeedbackResponseList,\n FeedbackStatus,\n FeedbackType,\n FeedbackUpdateInput,\n FilterResult,\n NetworkDiagnosticEntry,\n OpenFeedbackStatus,\n RectData,\n ScreenshotRegion,\n ScreenshotStorage,\n Serialized,\n SitepingStore,\n} from \"@siteping/core\";\n// Status/type constants + helpers\n// Store errors — throw these from adapter implementations\nexport {\n applyFeedbackFilters,\n buildAnnotationRecord,\n buildFeedbackRecord,\n CLOSED_FEEDBACK_STATUSES,\n CONSOLE_DIAGNOSTIC_LEVELS,\n createCollectionStore,\n FEEDBACK_STATUSES,\n FEEDBACK_TYPES,\n flattenAnnotation,\n isClosedStatus,\n isStoreDuplicate,\n isStoreNotFound,\n isStorePersistence,\n OPEN_FEEDBACK_STATUSES,\n StoreDuplicateError,\n StoreNotFoundError,\n StorePersistenceError,\n toFeedbackUpdate,\n} from \"@siteping/core\";\n","/**\n * Shared feedback-record filtering and pagination — extracted from\n * `adapter-memory` and `adapter-localstorage` which previously kept two\n * near-identical copies of the same logic. Any adapter that holds an\n * in-memory snapshot of feedbacks can use it.\n *\n * Filtering order matches the historical adapter behaviour:\n * 1. projectName (always required)\n * 2. type\n * 3. status / statuses (`statuses` bucket wins when both are set)\n * 4. url\n * 5. urlPattern\n * 6. search (lowercase substring match on `message`)\n *\n * Pagination clamps `limit` to a maximum of 100 and treats `page` as 1-based,\n * matching the public API contract documented on `getFeedbacks`. A page or\n * limit below 1 is clamped up to 1 rather than indexing backwards from the\n * end of the match set.\n */\n\nimport type { FeedbackQuery, FeedbackRecord } from \"./types.js\";\n\n/** Default page size when the caller omits `query.limit`. */\nconst DEFAULT_LIMIT = 50;\n/** Maximum allowed page size — defends against memory blow-ups on hostile callers. */\nconst MAX_LIMIT = 100;\n\nexport interface FilterResult {\n feedbacks: FeedbackRecord[];\n total: number;\n}\n\n/**\n * Apply the standard feedback filter + pagination pipeline against an\n * in-memory snapshot. Used by `MemoryStore.getFeedbacks` and\n * `LocalStorageStore.getFeedbacks` so the two never drift.\n *\n * @param items All known feedback records (already include `annotations`).\n * @param query Filter and pagination options. `projectName` is required.\n */\nexport function applyFeedbackFilters(items: readonly FeedbackRecord[], query: FeedbackQuery): FilterResult {\n let results: FeedbackRecord[] = items.filter((f) => f.projectName === query.projectName);\n\n if (query.type) results = results.filter((f) => f.type === query.type);\n // `statuses` (bucket / any-of) wins over the exact `status` filter when both\n // are present; an empty array is treated as absent.\n if (query.statuses && query.statuses.length > 0) {\n const allowed = query.statuses;\n results = results.filter((f) => allowed.includes(f.status));\n } else if (query.status) {\n results = results.filter((f) => f.status === query.status);\n }\n if (query.url) results = results.filter((f) => f.url === query.url);\n if (query.urlPattern) results = results.filter((f) => f.urlPattern === query.urlPattern);\n if (query.search) {\n const s = query.search.toLowerCase();\n results = results.filter((f) => f.message.toLowerCase().includes(s));\n }\n\n // Newest first is part of the store contract (PrismaStore orders by\n // createdAt desc) — sort explicitly instead of relying on insertion order.\n // Array.prototype.sort is stable, so same-millisecond records keep their\n // insertion order (newest inserted first).\n results.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n\n const total = results.length;\n // Both bounds are clamped from below, not just `limit` from above:\n // `(page - 1) * limit` goes negative for a non-positive page or limit, and\n // `slice` reads negative indices from the END — so `page: -1` returned a\n // window whose position depended on how many records happened to match,\n // rather than an empty page or the first one. The Prisma adapter rejects\n // these at the HTTP edge (`z.coerce.number().int().min(1)`), but the\n // in-memory adapters have no schema in front of them and call straight in.\n const page = Math.max(1, query.page ?? 1);\n const limit = Math.max(1, Math.min(query.limit ?? DEFAULT_LIMIT, MAX_LIMIT));\n const start = (page - 1) * limit;\n\n return { feedbacks: results.slice(start, start + limit), total };\n}\n","/**\n * General-purpose TypeScript utility types used across `@siteping/*`.\n *\n * These are kept dependency-free and re-exported from the package entry\n * so adapters and integrators can rely on the same primitives the core\n * uses internally.\n */\n\n/**\n * Force TypeScript to expand a computed type into a flat object literal in\n * tooltips and error messages. Purely cosmetic — same structural type, just\n * easier to read.\n *\n * @example\n * type Raw = Omit<FeedbackRecord, \"annotations\"> & { annotations: number };\n * type Pretty = Prettify<Raw>; // displayed as a flat object\n */\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n\n/**\n * Returns `Y` when `A` is exactly assignable to `B` and vice-versa,\n * otherwise `N`. Powers compile-time equality assertions.\n */\nexport type IfEquals<A, B, Y = true, N = false> =\n (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? Y : N;\n\n/**\n * Compile-time exact-type guard — resolves to `true` when `Actual` and\n * `Expected` are identical, `never` otherwise. Assign the result to a\n * `const _lock: AssertEqual<A, B> = true;` so any drift becomes a compile\n * error at the declaration site.\n */\nexport type AssertEqual<Actual, Expected> = IfEquals<Actual, Expected, true, never>;\n\n/**\n * JSON-serialized shape of `T` — the wire form produced by `Response.json()`\n * / `JSON.stringify`: `Date` becomes ISO `string` (nullability preserved),\n * arrays are serialized element-wise, everything else is untouched.\n *\n * Used to derive the `*Response` API types from the `*Record` store types so\n * the two can never drift: add a field to `FeedbackRecord` and\n * `FeedbackResponse` follows automatically.\n */\nexport type Serialized<T> = {\n [K in keyof T]: T[K] extends Date\n ? string\n : T[K] extends Date | null\n ? string | null\n : T[K] extends (infer U)[]\n ? Serialized<U>[]\n : T[K];\n};\n\n/**\n * Type guard that narrows `value` to a non-null `Record<PropertyKey, unknown>`.\n * Useful when validating arbitrary inputs before reading fields.\n */\nexport function isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * Returns true when `value` is an object that exposes the requested key.\n * Type-narrows `value` so the property can be accessed without further\n * casting — a strictly typed replacement for `\"k\" in obj`.\n *\n * Named after the standardised `Object.hasOwn` helper rather than the\n * legacy `Object.prototype.hasOwnProperty`, which the linter forbids\n * shadowing.\n */\nexport function hasOwn<K extends PropertyKey>(value: unknown, key: K): value is Record<K, unknown> {\n return isRecord(value) && key in value;\n}\n","import { type AssertEqual, hasOwn, type Prettify, type Serialized } from \"./type-utils.js\";\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\n/** FAB anchor — bottom-corner placement supported by the widget. */\nexport type SitepingPosition = \"bottom-right\" | \"bottom-left\";\n\n/** Visual theme — `auto` resolves to `light` or `dark` via system preference. */\nexport type SitepingTheme = \"light\" | \"dark\" | \"auto\";\n\n/** Built-in UI locales shipped with the widget. */\nexport const BUILTIN_LOCALES = [\"en\", \"fr\", \"de\", \"es\", \"it\", \"pt\", \"ru\"] as const;\nexport type BuiltinLocale = (typeof BUILTIN_LOCALES)[number];\n\n/**\n * Locale identifier accepted by the widget. Built-in locales are kept as\n * literal strings so editors auto-complete them, but arbitrary BCP-47 tags\n * are also accepted (custom dictionaries registered via `registerLocale`).\n */\nexport type SitepingLocale = BuiltinLocale | (string & {});\n\n/**\n * Reasons reported through `SitepingConfig.onSkip` — production environment,\n * mobile viewport, or server-side rendering (no `window`/`document`).\n */\nexport type SitepingSkipReason = \"production\" | \"mobile\" | \"ssr\";\n\n/** Per-channel + per-buffer-size diagnostics configuration. */\nexport interface DiagnosticsCaptureOptions {\n console?: boolean | undefined;\n network?: boolean | undefined;\n maxConsoleEntries?: number | undefined;\n maxNetworkEntries?: number | undefined;\n}\n\n/** Identity payload supplied by the host application — bypasses the modal. */\nexport interface SitepingIdentity {\n name: string;\n email: string;\n}\n\n/** Deep-link configuration — controls how a feedback id is read from the URL. */\nexport interface SitepingDeepLinkOptions {\n /** Query parameter name carrying the feedback id. Defaults to `\"siteping\"`. */\n param?: string | undefined;\n}\n\n/**\n * Extra request headers for HTTP mode — a static map, or a factory (sync or\n * async) invoked once per request to produce fresh values (e.g. a short-lived\n * session token).\n */\nexport type SitepingHeadersOption =\n | Record<string, string>\n | (() => Record<string, string> | Promise<Record<string, string>>);\n\n/**\n * Options shared by both widget modes (HTTP and direct store).\n *\n * Do not use this type directly — use {@link SitepingConfig}, the\n * discriminated union that adds the mode-specific fields.\n */\nexport interface SitepingBaseConfig {\n /** Required — project identifier used to scope feedbacks */\n projectName: string;\n /** FAB position — defaults to 'bottom-right' */\n position?: SitepingPosition | undefined;\n /**\n * Show the \"toggle markers visibility\" item in the FAB radial menu.\n * Defaults to `true` (current behavior). Set to `false` to hide that\n * item entirely — useful for hosts that always want markers visible\n * (e.g. dedicated review tools) or that find the eye icon redundant\n * when no marker is on screen.\n *\n * Hiding the item also removes its keyboard navigation slot — the\n * remaining two items still respond to ArrowUp/ArrowDown/Home/End.\n * The marker-visibility state itself is unaffected; markers stay\n * visible (the previous default state) and `annotations:toggle` is\n * simply never emitted from the FAB.\n */\n showAnnotationsToggle?: boolean | undefined;\n /** Accent color for the widget UI — defaults to '#0066ff' */\n accentColor?: string | undefined;\n /**\n * Render the widget even when it would normally be skipped — this bypasses\n * BOTH the production-environment guard AND the mobile-viewport guard.\n * It does NOT bypass the SSR guard: without `window`/`document` the widget\n * never renders and `onSkip(\"ssr\")` fires instead.\n * Defaults to false. Use it for dedicated review tools, staging environments,\n * or responsive testing where you always want the widget present.\n */\n forceShow?: boolean | undefined;\n /**\n * Minimum viewport width (px) at or above which the widget renders. Below it,\n * the widget is skipped and `onSkip(\"mobile\")` fires. Defaults to `768`.\n *\n * Set lower (e.g. `0`) to allow narrow/mobile viewports, or use `forceShow`\n * to bypass the viewport check entirely.\n */\n minViewportWidth?: number | undefined;\n /** Enable debug logging of lifecycle events — defaults to false */\n debug?: boolean | undefined;\n /** Color theme — defaults to 'light' */\n theme?: SitepingTheme | undefined;\n /** UI locale — defaults to 'en'. Built-in: en, fr, de, es, it, pt (Brazilian), ru. Any other string falls back to English. */\n locale?: SitepingLocale | undefined;\n /**\n * Returns the current page scope for annotations and panel filtering.\n * Called on initial markers load and on `instance.refresh()`.\n *\n * Default: `{ url: window.location.pathname, urlPattern: null }` — annotations\n * are scoped strictly to the current pathname.\n *\n * Apps with parameterized routes (e.g. React Router) should return both the\n * concrete URL and the route template (e.g. `/orders/:orderId`) so the panel\n * can offer a \"this type of page\" filter that groups feedbacks by template.\n */\n getPageScope?: (() => PageScope) | undefined;\n /**\n * When true (default), the widget filters initial markers and panel results\n * by `feedback.url === scope.url`, so annotations created on one page never\n * leak to other pages — even if their CSS selector accidentally matches.\n * Set to `false` to revert to the legacy project-wide behavior.\n */\n scopeAnnotationsByUrl?: boolean | undefined;\n /**\n * Capture a JPEG screenshot of the annotated area on submit. Defaults to\n * `false` — opt-in because:\n *\n * - it adds runtime weight (~40 KB gzip dynamic chunk for html2canvas,\n * loaded only on first capture),\n * - it embeds page content in the feedback (privacy/GDPR consideration —\n * inform end users in your widget host UI when enabling).\n *\n * `html2canvas` ships as a regular dependency of `@siteping/widget` so the\n * dynamic import always resolves; you don't need to install anything extra.\n *\n * **Masking sensitive elements:** add `data-siteping-ignore=\"true\"` to any\n * element you do NOT want captured (password fields, credit-card forms,\n * API tokens shown in the UI, etc.). The capture predicate skips matching\n * elements *and their descendants*. Do this BEFORE turning on screenshots\n * in production — once a feedback is saved, the screenshot is in your DB\n * (or object storage) regardless of what was on the page.\n */\n enableScreenshot?: boolean | undefined;\n /**\n * Enable right-click (`contextmenu`) to instantly open the comment composer\n * at the cursor location. When enabled, a document-level listener intercepts\n * right-clicks, prevents the browser's native context menu, and enters the\n * annotation flow anchored to the element under the cursor. Defaults to\n * `false` — the browser's native context menu is never hijacked unless the\n * host explicitly opts in.\n *\n * Keyboard-triggered context menus (≣ Menu key, Shift+F10) always get the\n * native menu; only mouse right-click and touch/pen long-press open the\n * composer.\n *\n * **Modifier-key escape hatch:** holding Shift, Ctrl, Alt, or Meta while\n * right-clicking always falls through to the native context menu, giving\n * users (and devtools) an escape hatch regardless of this setting.\n *\n * Right-clicks on SitePing's own UI (FAB, panel, markers, popup) are\n * ignored — the native menu is shown as expected.\n *\n * Note: on Android, `contextmenu` fires on long-press. The widget already\n * hides below `minViewportWidth` (default 768 px), but tablets above that\n * threshold will trigger this flow on long-press.\n */\n enableRightClickComment?: boolean | undefined;\n /**\n * Capture the last few `console.*` calls and failed network requests\n * (HTTP >= 400 or network error) at the moment a feedback is submitted.\n *\n * Lets reviewers replay the technical context that led to the report —\n * stack traces, 500 responses, dead third-party scripts. Great for the\n * \"the page just doesn't work\" feedback that contains zero detail.\n *\n * - `true` — capture with defaults (50 console / 20 network entries).\n * - `false` (default) — no capture, no monkey-patching.\n * - object — per-channel toggles + custom buffer sizes.\n *\n * **Privacy considerations:** console messages may contain anything the\n * host page logs, including user data. Failed network requests record the\n * URL (with query string) but never the response body. Inform end users\n * before enabling in environments where they might log sensitive values.\n */\n captureDiagnostics?: boolean | DiagnosticsCaptureOptions | undefined;\n /** Called when the widget is skipped (production mode, mobile viewport, SSR — no DOM) */\n onSkip?: (reason: SitepingSkipReason) => void;\n /**\n * Auto-focus a specific annotation when its ID appears in the URL query\n * string. Lets hosts deeplink directly into a feedback from external\n * systems (Zammad tickets, Slack notifications, dashboard rows).\n *\n * When enabled, the widget reads the configured query parameter from\n * `window.location.search` right after the initial markers load. If the\n * value matches a visible feedback ID, the widget scrolls the annotation\n * into view, pins its highlight, and pulses the marker — the same visual\n * affordance a marker click produces.\n *\n * - `false` / `undefined` (default): no URL parsing. Existing behavior\n * unchanged, no host URL inspection.\n * - `true`: enabled with default query parameter name `siteping`.\n * - object: enabled with a custom parameter name. Use this to avoid\n * clashes with host-app query keys.\n *\n * Only the initial load triggers focus. Subsequent URL changes (SPA\n * navigation, `history.pushState`, hash updates) are ignored —\n * deliberate, to avoid surprising re-scrolls during normal browsing.\n * Hosts that need re-focus on route change can call\n * `instance.focusFeedback(id)` explicitly.\n */\n deepLink?: boolean | SitepingDeepLinkOptions | undefined;\n /**\n * Automatically re-fetch feedbacks when the page changes during client-side\n * (SPA) navigation. Enabled by default.\n *\n * The widget is normally mounted once (singleton) inside a persistent layout\n * — e.g. a Next.js App Router `layout.tsx`, which does NOT remount on\n * client-side navigation. Without this, init runs a single time and both the\n * panel list and the page markers stay frozen on the page where the widget\n * first mounted. With it on, the widget patches the History API\n * (`pushState`/`replaceState`, which SPA routers call instead of triggering\n * `popstate`) and listens for `popstate`/`hashchange`, then re-fetches when\n * the scope key (`getPageScope().url` + template) actually changes.\n *\n * This re-fetches data only — it deliberately does NOT re-focus or re-scroll\n * to an annotation (deep-link focus stays initial-load only; see `deepLink`),\n * so normal browsing is never interrupted by a surprise scroll.\n *\n * - `true` (default) — watch navigation and re-fetch on route change.\n * - `false` — never touch the History API; hosts drive updates manually via\n * `instance.refresh()`.\n */\n watchNavigation?: boolean | undefined;\n /**\n * Pre-fill author identity from the host application — typically the\n * currently signed-in user. When set, the widget uses these values\n * directly and never shows the identity modal, even on first feedback.\n *\n * Use case: SSO-integrated apps where the end user is already\n * authenticated by the host. Avoids the awkward \"enter your name and\n * email\" prompt for users the host already knows.\n *\n * When unset (default), the widget falls back to localStorage and shows\n * the modal on first feedback as before — existing behavior unchanged.\n *\n * Note: `config.identity` is **not** persisted to localStorage. It is\n * read at widget init time, not on every render. Hosts that need live\n * identity updates after sign-in/sign-out should currently remount the\n * widget (e.g. via a React `key` on the wrapping component). See\n * https://github.com/NeosiaNexus/SitePing/issues/85 for tracking a\n * future enhancement that propagates identity updates without a remount.\n */\n identity?: SitepingIdentity | undefined;\n\n // Events\n /** Called when the feedback panel is opened. */\n onOpen?: (() => void) | undefined;\n /** Called when the feedback panel is closed. */\n onClose?: (() => void) | undefined;\n /** Called after a feedback is successfully submitted. */\n onFeedbackSent?: ((feedback: FeedbackResponse) => void) | undefined;\n /**\n * Called when a feedback API call fails.\n *\n * The widget always emits a `SitepingError` (or a subclass:\n * `SitepingNetworkError`, `SitepingValidationError`, `SitepingAuthError`)\n * for HTTP-mode failures — host apps can `instanceof` to drive retry\n * logic, or read `error.code` (`\"NETWORK\" | \"VALIDATION\" | \"AUTH\" |\n * \"SERVER\"`) and `error.retryable`. The type is widened to `Error` so\n * direct-store callers can still surface raw errors without breaking the\n * contract.\n */\n onError?: ((error: Error) => void) | undefined;\n /** Called when the user starts drawing an annotation. */\n onAnnotationStart?: (() => void) | undefined;\n /** Called when the user finishes drawing an annotation. */\n onAnnotationEnd?: (() => void) | undefined;\n}\n\n/**\n * HTTP mode — the widget talks to a server endpoint backed by a store\n * adapter (e.g. `@siteping/adapter-prisma` request handlers).\n */\nexport interface SitepingHttpConfig extends SitepingBaseConfig {\n /** HTTP endpoint that receives feedbacks (e.g. '/api/siteping'). */\n endpoint: string;\n /**\n * Convenience auth for HTTP mode — sent as `Authorization: Bearer <apiKey>`\n * on every request to `endpoint`.\n *\n * **WARNING: the widget runs in every visitor's browser, so a static key\n * configured here is public** — anyone can read it from your page source\n * and replay it against your API. Only use `apiKey` for internal tools\n * already behind your own login. On public sites, prefer `headers` with a\n * per-request factory returning a short-lived session token.\n */\n apiKey?: string | undefined;\n /**\n * Extra headers for every HTTP-mode request — a static map, or a factory\n * (sync or async) called once per request (e.g. to fetch a fresh session\n * token). Merged over the widget's generated headers, so an explicit\n * `Authorization` entry overrides `apiKey`. A throwing/rejecting factory\n * fails the request like a network error.\n */\n headers?: SitepingHeadersOption | undefined;\n /** Not available in HTTP mode — use either `endpoint` or `store`, never both. */\n store?: never;\n}\n\n/**\n * Store mode — the widget talks to a `SitepingStore` directly in the\n * browser, no server needed (demos, prototypes, localStorage persistence).\n */\nexport interface SitepingStoreConfig extends SitepingBaseConfig {\n /** Direct store for client-side mode. Bypasses HTTP entirely. */\n store: SitepingStore;\n /** Not available in store mode — use either `endpoint` or `store`, never both. */\n endpoint?: never;\n /** HTTP-mode only — meaningless without an `endpoint`. */\n apiKey?: never;\n /** HTTP-mode only — meaningless without an `endpoint`. */\n headers?: never;\n}\n\n/**\n * Configuration options for the Siteping widget.\n *\n * A discriminated union over the two transport modes: pass `endpoint`\n * (HTTP mode, optionally with `apiKey`/`headers`) **or** `store` (direct\n * client-side mode) — never both, never neither. Invalid combinations are\n * compile errors instead of runtime warnings.\n */\nexport type SitepingConfig = SitepingHttpConfig | SitepingStoreConfig;\n\n/** Instance returned by initSiteping() with lifecycle methods. */\nexport interface SitepingInstance {\n /** Remove the widget from the DOM and clean up all listeners. */\n destroy: () => void;\n /** Open the panel programmatically */\n open: () => void;\n /** Close the panel */\n close: () => void;\n /** Reload feedbacks from server */\n refresh: () => void;\n /**\n * Scroll the matching annotation into view, pin its highlight, and\n * pulse its marker. Returns `true` when a visible feedback matched the\n * given ID, `false` otherwise (unknown ID, feedback on another URL when\n * `scopeAnnotationsByUrl` filtered it out, or markers not yet loaded).\n *\n * Counterpart to the `deepLink` config option for hosts that prefer to\n * drive focus from JS (e.g., a notification click handler) instead of a\n * URL query parameter.\n */\n focusFeedback: (feedbackId: string) => boolean;\n /** Subscribe to a public widget event */\n on: <K extends keyof SitepingPublicEvents>(event: K, listener: SitepingPublicEventListener<K>) => SitepingUnsubscribe;\n /** Unsubscribe from a public widget event */\n off: <K extends keyof SitepingPublicEvents>(event: K, listener: SitepingPublicEventListener<K>) => void;\n}\n\n/** Listener signature for a single `SitepingPublicEvents` key. */\nexport type SitepingPublicEventListener<K extends keyof SitepingPublicEvents> = (\n ...args: SitepingPublicEvents[K]\n) => void;\n\n/** Disposer returned by `SitepingInstance.on` — call once to detach the listener. */\nexport type SitepingUnsubscribe = () => void;\n\n/** Events exposed to consumers via SitepingInstance.on / .off */\nexport interface SitepingPublicEvents {\n \"feedback:sent\": [FeedbackResponse];\n \"feedback:deleted\": [FeedbackResponse[\"id\"]];\n /**\n * A feedback API call failed. Same payload contract as\n * `SitepingConfig.onError` — a `SitepingError` subclass in HTTP mode,\n * possibly a raw `Error` in store mode.\n */\n \"feedback:error\": [Error];\n \"panel:open\": [];\n \"panel:close\": [];\n /** The user started drawing an annotation. */\n \"annotation:start\": [];\n /** The user finished drawing an annotation. */\n \"annotation:end\": [];\n}\n\n// ---------------------------------------------------------------------------\n// Feedback\n// ---------------------------------------------------------------------------\n\n/** Single source of truth for feedback types — used by both TS types and Zod schemas. */\nexport const FEEDBACK_TYPES = [\"question\", \"change\", \"bug\", \"other\"] as const;\nexport type FeedbackType = (typeof FEEDBACK_TYPES)[number];\n\n/** Single source of truth for feedback statuses. */\nexport const FEEDBACK_STATUSES = [\"open\", \"in_progress\", \"resolved\", \"wont_fix\"] as const;\nexport type FeedbackStatus = (typeof FEEDBACK_STATUSES)[number];\n\n/**\n * Terminal statuses — the feedback needs no further action. `resolvedAt` is\n * the closure timestamp: set when a feedback enters a closed status, null\n * while it is open or in progress. The derivation happens at the edge (HTTP\n * handler, dashboard) — store adapters persist whatever they are given.\n */\nexport const CLOSED_FEEDBACK_STATUSES = [\"resolved\", \"wont_fix\"] as const;\n/** A terminal status — `resolved` or `wont_fix`. */\nexport type ClosedFeedbackStatus = (typeof CLOSED_FEEDBACK_STATUSES)[number];\n\n/** Non-terminal statuses — the feedback still needs attention. */\nexport const OPEN_FEEDBACK_STATUSES = [\"open\", \"in_progress\"] as const;\n/** A non-terminal status — `open` or `in_progress`. */\nexport type OpenFeedbackStatus = (typeof OPEN_FEEDBACK_STATUSES)[number];\n\n// Adding a fifth status without assigning it to exactly one bucket is a\n// compile error here.\nconst _statusBucketsCoverAll: AssertEqual<OpenFeedbackStatus | ClosedFeedbackStatus, FeedbackStatus> = true;\nvoid _statusBucketsCoverAll;\n\n/** Whether a status is terminal (`resolved` or `wont_fix`). Narrows the status type. */\nexport function isClosedStatus(status: FeedbackStatus): status is ClosedFeedbackStatus {\n return (CLOSED_FEEDBACK_STATUSES as readonly FeedbackStatus[]).includes(status);\n}\n\n/**\n * Page scope returned by `SitepingConfig.getPageScope()`.\n *\n * - `url`: concrete page identifier — usually `window.location.pathname`,\n * used as the strict scope for marker rendering.\n * - `urlPattern`: optional parameterized template (e.g. `/orders/:orderId`)\n * used by the panel's \"this type of page\" filter to group feedbacks across\n * instances of the same page kind.\n */\nexport interface PageScope {\n url: string;\n urlPattern: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// Abstract Store — adapter pattern\n// ---------------------------------------------------------------------------\n\n/** Input for creating a feedback record in the store. */\nexport interface FeedbackCreateInput {\n projectName: string;\n type: FeedbackType;\n message: string;\n status: FeedbackStatus;\n url: string;\n /**\n * Optional parameterized URL template (e.g. `/orders/:orderId`) for the page\n * where the feedback was created. Allows the panel to filter feedbacks by\n * \"this type of page\" across different instances. Null when the host did not\n * provide a `getPageScope` callback or the route has no template.\n */\n urlPattern?: string | null | undefined;\n viewport: string;\n userAgent: string;\n authorName: string;\n authorEmail: string;\n clientId: string;\n annotations: AnnotationCreateInput[];\n /**\n * Base64 JPEG `data:` URL captured by the widget at submit time.\n *\n * Adapters with a configured `ScreenshotStorage` are expected to upload\n * this and persist the returned URL on `FeedbackRecord.screenshotUrl`.\n * Adapters without storage may persist the data URL inline (memory /\n * localStorage / dev) — the widget then renders it directly.\n */\n screenshotDataUrl?: string | null | undefined;\n /**\n * Where the client's annotation rect sits within the screenshot image,\n * as fractions [0, 1] of the image dimensions. Present when the widget\n * captured context around the drawn rect; null for legacy captures that\n * were cropped exactly to the rect (dashboards then render the image\n * without an overlay).\n */\n screenshotRegion?: ScreenshotRegion | null | undefined;\n /**\n * Optional console + failed-network snapshot captured by the widget when\n * `SitepingConfig.captureDiagnostics` is enabled. Stored as JSON on\n * `FeedbackRecord.diagnostics` so reviewers can replay the context.\n */\n diagnostics?: DiagnosticsSnapshot | null | undefined;\n}\n\n/** Input for a single annotation when creating a feedback. */\nexport interface AnnotationCreateInput {\n cssSelector: string;\n xpath: string;\n textSnippet: string;\n elementTag: string;\n elementId?: string | undefined;\n textPrefix: string;\n textSuffix: string;\n fingerprint: string;\n neighborText: string;\n /**\n * Semantic anchor identifier from the closest ancestor's `data-feedback-anchor`\n * attribute. When set, this is the most stable re-anchoring signal because\n * hosts deliberately place these on layout/section roots that survive DOM\n * refactors and viewport changes. Null when no semantic ancestor exists.\n */\n anchorKey?: string | null | undefined;\n xPct: number;\n yPct: number;\n wPct: number;\n hPct: number;\n scrollX: number;\n scrollY: number;\n viewportW: number;\n viewportH: number;\n devicePixelRatio: number;\n}\n\n/** Query parameters for fetching feedbacks. */\nexport interface FeedbackQuery {\n projectName: string;\n type?: FeedbackType | undefined;\n /** Exact single-status filter. For \"any of a set\" (bucket) semantics, use `statuses`. */\n status?: FeedbackStatus | undefined;\n /**\n * Filter to feedbacks whose status is any of the listed values — bucket\n * semantics used by the panel's binary tabs (e.g. \"Open\" passes\n * `[\"open\", \"in_progress\"]`). When both `status` and `statuses` are set,\n * `statuses` wins. An empty array is treated as absent (no status filter).\n */\n statuses?: readonly FeedbackStatus[] | undefined;\n search?: string | undefined;\n page?: number | undefined;\n limit?: number | undefined;\n /**\n * Filter to feedbacks created on this exact URL (path). Used by the panel's\n * \"this page\" filter and by the markers loader to keep page scopes isolated.\n */\n url?: string | undefined;\n /**\n * Filter to feedbacks created on this URL pattern (e.g. `/orders/:orderId`).\n * Used by the panel's \"this type of page\" filter to group feedbacks across\n * different concrete instances of the same template.\n */\n urlPattern?: string | undefined;\n}\n\n/**\n * Update payload for patching a feedback.\n *\n * A discriminated union encoding the closure invariant: a feedback entering\n * a closed status carries its closure timestamp, an open one carries `null`.\n * `{ status: \"resolved\", resolvedAt: null }` is a compile error instead of a\n * silent data bug. Build it from a plain `FeedbackStatus` with\n * {@link toFeedbackUpdate}.\n */\nexport type FeedbackUpdateInput =\n | { status: OpenFeedbackStatus; resolvedAt: null }\n | { status: ClosedFeedbackStatus; resolvedAt: Date };\n\n/**\n * Derive the {@link FeedbackUpdateInput} for a status change — the closure\n * timestamp is stamped for closed statuses and cleared otherwise. This is\n * the edge derivation described on {@link CLOSED_FEEDBACK_STATUSES}; store\n * adapters persist the result verbatim.\n */\nexport function toFeedbackUpdate(status: FeedbackStatus, closedAt: Date = new Date()): FeedbackUpdateInput {\n return isClosedStatus(status) ? { status, resolvedAt: closedAt } : { status, resolvedAt: null };\n}\n\n/** A persisted feedback record returned by the store. */\nexport interface FeedbackRecord {\n id: string;\n type: FeedbackType;\n message: string;\n status: FeedbackStatus;\n projectName: string;\n url: string;\n /**\n * Parameterized URL template the feedback was created on.\n * Null for legacy records or hosts without `getPageScope`.\n */\n urlPattern: string | null;\n authorName: string;\n authorEmail: string;\n viewport: string;\n userAgent: string;\n clientId: string;\n resolvedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n annotations: AnnotationRecord[];\n /**\n * URL the widget renders as `<img src>`. Either an `https://...` from a\n * configured `ScreenshotStorage`, or a `data:image/jpeg;base64,...` URL\n * inline-persisted by adapters without storage. Null when no screenshot\n * was captured (legacy records, capture failed, or host disabled it).\n */\n screenshotUrl: string | null;\n /**\n * Annotation rect position within the screenshot image, as fractions of\n * its dimensions. Null for legacy captures cropped exactly to the rect.\n */\n screenshotRegion: ScreenshotRegion | null;\n /**\n * Console + failed-network snapshot captured at submit time. Null when\n * diagnostics weren't enabled on the widget side.\n */\n diagnostics: DiagnosticsSnapshot | null;\n}\n\n/** A persisted annotation record returned by the store. */\nexport interface AnnotationRecord {\n id: string;\n feedbackId: string;\n cssSelector: string;\n xpath: string;\n textSnippet: string;\n elementTag: string;\n elementId: string | null;\n textPrefix: string;\n textSuffix: string;\n fingerprint: string;\n neighborText: string;\n /**\n * Semantic anchor identifier from `data-feedback-anchor`. Null for legacy\n * annotations or those drawn outside any anchored region.\n */\n anchorKey: string | null;\n xPct: number;\n yPct: number;\n wPct: number;\n hPct: number;\n scrollX: number;\n scrollY: number;\n viewportW: number;\n viewportH: number;\n devicePixelRatio: number;\n createdAt: Date;\n}\n\n// ---------------------------------------------------------------------------\n// Store errors — throw these from adapter implementations\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a record is not found during update or delete.\n *\n * Handlers translate this to HTTP 404. Adapters MUST throw this (not\n * ORM-specific errors) so the handler layer remains ORM-agnostic.\n */\nexport class StoreNotFoundError extends Error {\n readonly code = \"STORE_NOT_FOUND\" as const;\n constructor(message = \"Record not found\") {\n super(message);\n this.name = \"StoreNotFoundError\";\n }\n}\n\n/**\n * Thrown when a unique constraint is violated (e.g. duplicate `clientId`).\n *\n * Handlers use this to return the existing record instead of failing.\n */\nexport class StoreDuplicateError extends Error {\n readonly code = \"STORE_DUPLICATE\" as const;\n constructor(message = \"Duplicate record\") {\n super(message);\n this.name = \"StoreDuplicateError\";\n }\n}\n\n/**\n * Thrown when a store accepts a mutation but cannot persist it — e.g.\n * `localStorage` is full (QuotaExceededError). Adapters MUST throw this rather\n * than swallow the failure, so callers learn the write was lost instead of\n * seeing a phantom success.\n */\nexport class StorePersistenceError extends Error {\n readonly code = \"STORE_PERSISTENCE\" as const;\n constructor(message = \"Failed to persist store mutation\", options?: ErrorOptions) {\n super(message, options);\n this.name = \"StorePersistenceError\";\n }\n}\n\n/** Shape of any ORM error that carries a Prisma-style `code` field. */\ntype CodedError<C extends string = string> = { code: C };\n\nfunction hasErrorCode<C extends string>(error: unknown, code: C): error is CodedError<C> {\n return hasOwn(error, \"code\") && error.code === code;\n}\n\n/** Type guard — works for `StoreNotFoundError` and ORM-specific equivalents (e.g. Prisma P2025). */\nexport function isStoreNotFound(error: unknown): error is StoreNotFoundError | CodedError<\"P2025\"> {\n if (error instanceof StoreNotFoundError) return true;\n // Backwards compat: Prisma's P2025\n return hasErrorCode(error, \"P2025\");\n}\n\n/** Type guard — works for `StoreDuplicateError` and ORM-specific equivalents (e.g. Prisma P2002). */\nexport function isStoreDuplicate(error: unknown): error is StoreDuplicateError | CodedError<\"P2002\"> {\n if (error instanceof StoreDuplicateError) return true;\n // Backwards compat: Prisma's P2002\n return hasErrorCode(error, \"P2002\");\n}\n\n/**\n * Type guard for `StorePersistenceError`. Matches on the stable `code` field\n * in addition to `instanceof`: every consumer package bundles its own copy of\n * core (tsup `noExternal`), so an instance thrown by one package fails an\n * `instanceof` check against another package's class identity.\n */\nexport function isStorePersistence(error: unknown): error is StorePersistenceError | CodedError<\"STORE_PERSISTENCE\"> {\n if (error instanceof StorePersistenceError) return true;\n return hasErrorCode(error, \"STORE_PERSISTENCE\");\n}\n\n// ---------------------------------------------------------------------------\n// Store helpers — shared conversion logic for adapters\n// ---------------------------------------------------------------------------\n\n/** Flatten a widget `AnnotationPayload` (nested anchor + rect) into a flat `AnnotationCreateInput`. */\nexport function flattenAnnotation(ann: AnnotationPayload): AnnotationCreateInput {\n return {\n cssSelector: ann.anchor.cssSelector,\n xpath: ann.anchor.xpath,\n textSnippet: ann.anchor.textSnippet,\n elementTag: ann.anchor.elementTag,\n elementId: ann.anchor.elementId,\n textPrefix: ann.anchor.textPrefix,\n textSuffix: ann.anchor.textSuffix,\n fingerprint: ann.anchor.fingerprint,\n neighborText: ann.anchor.neighborText,\n anchorKey: ann.anchor.anchorKey ?? null,\n xPct: ann.rect.xPct,\n yPct: ann.rect.yPct,\n wPct: ann.rect.wPct,\n hPct: ann.rect.hPct,\n scrollX: ann.scrollX,\n scrollY: ann.scrollY,\n viewportW: ann.viewportW,\n viewportH: ann.viewportH,\n devicePixelRatio: ann.devicePixelRatio,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Abstract Store — adapter pattern\n// ---------------------------------------------------------------------------\n\n/** Paginated result returned by `SitepingStore.getFeedbacks`. */\nexport interface FeedbackPage {\n feedbacks: FeedbackRecord[];\n total: number;\n}\n\n/**\n * Abstract storage interface for Siteping.\n *\n * Any adapter (Prisma, Drizzle, raw SQL, localStorage, etc.) implements this\n * interface. The HTTP handler and widget `StoreClient` operate against\n * `SitepingStore`, decoupled from the storage backend.\n *\n * ## Error contract\n *\n * - **`updateFeedback` / `deleteFeedback`**: throw `StoreNotFoundError` when\n * the record does not exist.\n * - **`createFeedback`**: either return the existing record on duplicate\n * `clientId` (idempotent) or throw `StoreDuplicateError`. The handler\n * handles both patterns.\n * - **All mutations**: when a write is accepted but cannot be persisted\n * (e.g. storage quota), throw `StorePersistenceError` instead of reporting\n * a phantom success. Detect it with `isStorePersistence`.\n * - Other methods should not throw on empty results — return empty arrays or `null`.\n */\nexport interface SitepingStore {\n /** Create a feedback with its annotations. Idempotent on `clientId` — return existing record on duplicate, or throw `StoreDuplicateError`. Throws `StorePersistenceError` when the write cannot be persisted. */\n createFeedback(data: FeedbackCreateInput): Promise<FeedbackRecord>;\n /** Paginated query with optional filters. Returns empty array (not error) when no results. */\n getFeedbacks(query: FeedbackQuery): Promise<FeedbackPage>;\n /** Lookup by client-generated UUID. Returns `null` (not error) when not found. */\n findByClientId(clientId: string): Promise<FeedbackRecord | null>;\n /** Update status/resolvedAt. Throws `StoreNotFoundError` if `id` does not exist, `StorePersistenceError` when the write cannot be persisted. */\n updateFeedback(id: string, data: FeedbackUpdateInput): Promise<FeedbackRecord>;\n /** Delete a single record. Throws `StoreNotFoundError` if `id` does not exist, `StorePersistenceError` when the write cannot be persisted. */\n deleteFeedback(id: string): Promise<void>;\n /** Bulk delete all feedbacks for a project. No-op (not error) if none exist. Throws `StorePersistenceError` when the write cannot be persisted. */\n deleteAllFeedbacks(projectName: string): Promise<void>;\n /**\n * Optional — return `true` when the record with `id` belongs to\n * `projectName`, `false` otherwise (including when it does not exist).\n *\n * HTTP handlers use this to reject cross-project PATCH/DELETE requests.\n * Implement it whenever your store serves multiple projects; when absent,\n * handlers skip the ownership check and rely on `id` alone.\n */\n verifyProjectOwnership?(id: string, projectName: string): Promise<boolean>;\n}\n\n/** Payload sent from the widget to the server when submitting feedback. */\nexport interface FeedbackPayload {\n projectName: string;\n type: FeedbackType;\n message: string;\n url: string;\n /**\n * Parameterized URL template (e.g. `/orders/:orderId`) supplied by\n * `SitepingConfig.getPageScope()`. Null when the host did not provide one.\n */\n urlPattern?: string | null | undefined;\n viewport: string;\n userAgent: string;\n authorName: string;\n authorEmail: string;\n annotations: AnnotationPayload[];\n /** Client-generated UUID for deduplication */\n clientId: string;\n /**\n * Base64 JPEG `data:` URL of the annotated area. Captured by the widget\n * when `enableScreenshot: true` is set in `SitepingConfig`. Null when\n * disabled or when capture failed silently.\n */\n screenshotDataUrl?: string | null | undefined;\n /**\n * Annotation rect position within the screenshot image — see\n * `ScreenshotRegion`. Null/absent when no screenshot was captured or the\n * capture predates contextual framing.\n */\n screenshotRegion?: ScreenshotRegion | null | undefined;\n /**\n * Snapshot of the last few console messages and failed network requests\n * captured at submit time when `captureDiagnostics` is enabled.\n */\n diagnostics?: DiagnosticsSnapshot | null | undefined;\n}\n\n/** Single source of truth for console diagnostic severity levels. */\nexport const CONSOLE_DIAGNOSTIC_LEVELS = [\"log\", \"info\", \"warn\", \"error\"] as const;\n/** Severity levels persisted in `ConsoleDiagnosticEntry`. */\nexport type ConsoleDiagnosticLevel = (typeof CONSOLE_DIAGNOSTIC_LEVELS)[number];\n\n/** A single console entry captured by `ConsoleBuffer`. */\nexport interface ConsoleDiagnosticEntry {\n level: ConsoleDiagnosticLevel;\n /** ISO 8601 timestamp captured at log time. */\n timestamp: string;\n /** Best-effort string representation of the original console args. */\n message: string;\n}\n\n/** A single failed network request captured by `NetworkBuffer`. */\nexport interface NetworkDiagnosticEntry {\n url: string;\n method: string;\n /** HTTP status; 0 when the request never reached the server. */\n status: number;\n /** End-to-end duration in ms. */\n durationMs: number;\n /** ISO 8601 timestamp at the moment the request was initiated. */\n timestamp: string;\n}\n\n/**\n * Diagnostics captured by the widget when `captureDiagnostics` is enabled.\n *\n * Both arrays are bounded (default: 50 console / 20 network). Adapters that\n * support diagnostics should persist this as a JSON blob alongside the\n * feedback so reviewers can replay the context that led to the report.\n */\nexport interface DiagnosticsSnapshot {\n console: ConsoleDiagnosticEntry[];\n network: NetworkDiagnosticEntry[];\n}\n\n// ---------------------------------------------------------------------------\n// Annotation — multi-selector anchoring (Hypothesis / W3C Web Annotation)\n// ---------------------------------------------------------------------------\n\n/** DOM anchoring data for re-attaching annotations to page elements. */\nexport interface AnchorData {\n /** CSS selector generated by @medv/finder — primary anchor */\n cssSelector: string;\n /** XPath — fallback 1 */\n xpath: string;\n /** First ~120 chars of element innerText — empty string if none */\n textSnippet: string;\n /** Tag name for validation (e.g. \"DIV\", \"SECTION\") */\n elementTag: string;\n /** Element id attribute if available — most stable */\n elementId?: string | undefined;\n /** ~32 chars of text before this element in document flow (disambiguation) */\n textPrefix: string;\n /** ~32 chars of text after this element in document flow (disambiguation) */\n textSuffix: string;\n /** Structural fingerprint: \"childCount:siblingIdx:attrHash\" */\n fingerprint: string;\n /** Text content of adjacent sibling elements (context) */\n neighborText: string;\n /**\n * Semantic anchor identifier from the closest ancestor's `data-feedback-anchor`\n * attribute. When set, this is the highest-priority re-anchoring signal —\n * hosts deliberately place these on layout/section roots that survive\n * viewport changes and DOM refactors.\n */\n anchorKey?: string | null | undefined;\n}\n\n/**\n * Where the client's annotation rect sits within the captured screenshot,\n * as fractions [0, 1] of the image dimensions. The widget captures context\n * around the drawn rect and records the rect's position here so dashboards\n * can re-render the annotation on top of the image. Survives downscaling\n * (fractions are resolution-independent).\n */\nexport interface ScreenshotRegion {\n /** X offset of the rect as fraction of image width — [0, 1] */\n xPct: number;\n /** Y offset of the rect as fraction of image height — [0, 1] */\n yPct: number;\n /** Rect width as fraction of image width — [0, 1] */\n wPct: number;\n /** Rect height as fraction of image height — [0, 1] */\n hPct: number;\n}\n\n/** Drawn rectangle coordinates as percentages relative to the anchor element. */\nexport interface RectData {\n /** X offset as fraction of anchor element width — must be in range [0, 1] */\n xPct: number;\n /** Y offset as fraction of anchor element height — must be in range [0, 1] */\n yPct: number;\n /** Width as fraction of anchor element width — must be in range [0, 1] */\n wPct: number;\n /** Height as fraction of anchor element height — must be in range [0, 1] */\n hPct: number;\n}\n\n/** Annotation data sent as part of a feedback submission. */\nexport interface AnnotationPayload {\n anchor: AnchorData;\n rect: RectData;\n scrollX: number;\n scrollY: number;\n viewportW: number;\n viewportH: number;\n devicePixelRatio: number;\n}\n\n// ---------------------------------------------------------------------------\n// API responses\n// ---------------------------------------------------------------------------\n\n/**\n * Feedback record as returned by the API — derived from\n * {@link FeedbackRecord}: dates are serialized to ISO strings and `clientId`\n * is omitted (server-side dedup concern, never exposed on the wire). Adding\n * a field to `FeedbackRecord` updates this type automatically.\n *\n * Note: `authorEmail` may be an empty string — HTTP adapters redact it for\n * unauthenticated requests; the full value requires a Bearer-authenticated\n * request.\n */\nexport type FeedbackResponse = Prettify<Serialized<Omit<FeedbackRecord, \"clientId\">>>;\n\n/**\n * Annotation record as returned by the API — {@link AnnotationRecord} with\n * `createdAt` serialized to an ISO string.\n */\nexport type AnnotationResponse = Prettify<Serialized<AnnotationRecord>>;\n\n/** Paginated `FeedbackResponse` shape returned by the API. */\nexport interface FeedbackResponseList {\n feedbacks: FeedbackResponse[];\n total: number;\n}\n","/**\n * Record-construction helpers and the collection-store engine.\n *\n * Every snapshot-style adapter (memory, localStorage, flat file, KV, …)\n * needs the same three ingredients: turn a `FeedbackCreateInput` into a\n * `FeedbackRecord` (null-normalizing optional fields, stamping ids and\n * timestamps), filter/paginate with `applyFeedbackFilters`, and implement\n * the dedup/update/delete choreography of the `SitepingStore` contract.\n *\n * `buildFeedbackRecord` / `buildAnnotationRecord` cover the first part for\n * any adapter. `createCollectionStore` covers all of it: give it `load`,\n * `persist`, and `generateId`, and it returns a fully conformant\n * `SitepingStore` — writing a new snapshot adapter is ~20 lines plus its\n * storage specifics.\n */\n\nimport { applyFeedbackFilters } from \"./filters.js\";\nimport type {\n AnnotationCreateInput,\n AnnotationRecord,\n FeedbackCreateInput,\n FeedbackPage,\n FeedbackQuery,\n FeedbackRecord,\n FeedbackUpdateInput,\n SitepingStore,\n} from \"./types.js\";\nimport { StoreNotFoundError } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Record construction\n// ---------------------------------------------------------------------------\n\n/**\n * Build a persisted `AnnotationRecord` from its create input — normalizes\n * the optional anchor fields to `null` and stamps identity/timestamp.\n */\nexport function buildAnnotationRecord(\n input: AnnotationCreateInput,\n ctx: { id: string; feedbackId: string; now: Date },\n): AnnotationRecord {\n return {\n id: ctx.id,\n feedbackId: ctx.feedbackId,\n cssSelector: input.cssSelector,\n xpath: input.xpath,\n textSnippet: input.textSnippet,\n elementTag: input.elementTag,\n elementId: input.elementId ?? null,\n textPrefix: input.textPrefix,\n textSuffix: input.textSuffix,\n fingerprint: input.fingerprint,\n neighborText: input.neighborText,\n anchorKey: input.anchorKey ?? null,\n xPct: input.xPct,\n yPct: input.yPct,\n wPct: input.wPct,\n hPct: input.hPct,\n scrollX: input.scrollX,\n scrollY: input.scrollY,\n viewportW: input.viewportW,\n viewportH: input.viewportH,\n devicePixelRatio: input.devicePixelRatio,\n createdAt: ctx.now,\n };\n}\n\n/**\n * Build a persisted `FeedbackRecord` (with its annotations) from a create\n * input — normalizes every optional field to `null` and stamps ids and\n * timestamps. Adapters without external screenshot storage keep the data\n * URL inline on `screenshotUrl`, which is what this helper does; adapters\n * with a `ScreenshotStorage` upload first and override `screenshotUrl`.\n */\nexport function buildFeedbackRecord(\n input: FeedbackCreateInput,\n ctx: { id: string; annotationId: () => string; now?: Date },\n): FeedbackRecord {\n const now = ctx.now ?? new Date();\n return {\n id: ctx.id,\n type: input.type,\n message: input.message,\n status: input.status,\n projectName: input.projectName,\n url: input.url,\n urlPattern: input.urlPattern ?? null,\n authorName: input.authorName,\n authorEmail: input.authorEmail,\n viewport: input.viewport,\n userAgent: input.userAgent,\n clientId: input.clientId,\n resolvedAt: null,\n createdAt: now,\n updatedAt: now,\n annotations: input.annotations.map((ann) =>\n buildAnnotationRecord(ann, { id: ctx.annotationId(), feedbackId: ctx.id, now }),\n ),\n screenshotUrl: input.screenshotDataUrl ?? null,\n screenshotRegion: input.screenshotRegion ?? null,\n diagnostics: input.diagnostics ?? null,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Collection-store engine\n// ---------------------------------------------------------------------------\n\n/**\n * Storage primitives behind a collection store. `load`/`persist` may be\n * sync or async — the engine awaits both, so in-memory arrays, localStorage\n * and async KV stores all fit the same three functions.\n */\nexport interface CollectionStoreBackend {\n /** Return the current full snapshot of feedback records. */\n load(): FeedbackRecord[] | Promise<FeedbackRecord[]>;\n /**\n * Persist the full snapshot. Throw `StorePersistenceError` when the write\n * is lost (quota, storage disabled, …) — never swallow the failure.\n */\n persist(feedbacks: FeedbackRecord[]): void | Promise<void>;\n /** Generate a unique id for a new feedback or annotation record. */\n generateId(): string;\n}\n\n/**\n * A `SitepingStore` with the optional `verifyProjectOwnership` guaranteed —\n * what `createCollectionStore` returns.\n */\nexport type CollectionStore = SitepingStore & Required<Pick<SitepingStore, \"verifyProjectOwnership\">>;\n\n/**\n * Build a fully conformant `SitepingStore` on top of a snapshot backend.\n *\n * The engine implements the whole store contract: clientId dedup (idempotent\n * create), newest-first ordering, the standard filter/pagination pipeline,\n * `StoreNotFoundError` on missing update/delete, project-scoped bulk delete,\n * and `verifyProjectOwnership`. When `persist` fails during `createFeedback`\n * and the record carries an inline screenshot, the engine retries once\n * without the screenshot (by far the heaviest field) so the text feedback\n * survives a storage-quota hit; if that also fails, the error propagates —\n * returning the record would claim a success that was never persisted.\n *\n * @example\n * ```ts\n * export class MemoryStore implements SitepingStore {\n * private feedbacks: FeedbackRecord[] = [];\n * private readonly store = createCollectionStore({\n * load: () => this.feedbacks,\n * persist: (next) => {\n * this.feedbacks = next;\n * },\n * generateId: () => crypto.randomUUID(),\n * });\n * createFeedback = this.store.createFeedback;\n * // …delegate the remaining methods the same way\n * }\n * ```\n */\nexport function createCollectionStore(backend: CollectionStoreBackend): CollectionStore {\n return {\n async createFeedback(data: FeedbackCreateInput): Promise<FeedbackRecord> {\n const feedbacks = await backend.load();\n\n // ClientId dedup — idempotent\n const existing = feedbacks.find((f) => f.clientId === data.clientId);\n if (existing) return existing;\n\n const record = buildFeedbackRecord(data, {\n id: backend.generateId(),\n annotationId: () => backend.generateId(),\n });\n\n feedbacks.unshift(record);\n try {\n await backend.persist(feedbacks);\n } catch (err) {\n if (!record.screenshotUrl) throw err;\n record.screenshotUrl = null;\n await backend.persist(feedbacks);\n }\n return record;\n },\n\n async getFeedbacks(query: FeedbackQuery): Promise<FeedbackPage> {\n return applyFeedbackFilters(await backend.load(), query);\n },\n\n async findByClientId(clientId: string): Promise<FeedbackRecord | null> {\n return (await backend.load()).find((f) => f.clientId === clientId) ?? null;\n },\n\n async updateFeedback(id: string, data: FeedbackUpdateInput): Promise<FeedbackRecord> {\n const feedbacks = await backend.load();\n const fb = feedbacks.find((f) => f.id === id);\n if (!fb) throw new StoreNotFoundError();\n\n fb.status = data.status;\n fb.resolvedAt = data.resolvedAt;\n fb.updatedAt = new Date();\n await backend.persist(feedbacks);\n return fb;\n },\n\n async deleteFeedback(id: string): Promise<void> {\n const feedbacks = await backend.load();\n const idx = feedbacks.findIndex((f) => f.id === id);\n if (idx === -1) throw new StoreNotFoundError();\n\n feedbacks.splice(idx, 1);\n await backend.persist(feedbacks);\n },\n\n async deleteAllFeedbacks(projectName: string): Promise<void> {\n const feedbacks = await backend.load();\n await backend.persist(feedbacks.filter((f) => f.projectName !== projectName));\n },\n\n async verifyProjectOwnership(id: string, projectName: string): Promise<boolean> {\n const fb = (await backend.load()).find((f) => f.id === id);\n return fb !== undefined && fb.projectName === projectName;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACuBA,IAAM,gBAAgB;AAEtB,IAAM,YAAY;AAeX,SAAS,qBAAqB,OAAkC,OAAoC;AACzG,MAAI,UAA4B,MAAM,OAAO,CAAC,MAAM,EAAE,gBAAgB,MAAM,WAAW;AAEvF,MAAI,MAAM,KAAM,WAAU,QAAQ,OAAO,CAAC,MAAM,EAAE,SAAS,MAAM,IAAI;AAGrE,MAAI,MAAM,YAAY,MAAM,SAAS,SAAS,GAAG;AAC/C,UAAM,UAAU,MAAM;AACtB,cAAU,QAAQ,OAAO,CAAC,MAAM,QAAQ,SAAS,EAAE,MAAM,CAAC;AAAA,EAC5D,WAAW,MAAM,QAAQ;AACvB,cAAU,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,MAAM,MAAM;AAAA,EAC3D;AACA,MAAI,MAAM,IAAK,WAAU,QAAQ,OAAO,CAAC,MAAM,EAAE,QAAQ,MAAM,GAAG;AAClE,MAAI,MAAM,WAAY,WAAU,QAAQ,OAAO,CAAC,MAAM,EAAE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AAC9C,YAAM,YAAY,MAAM,QAAQ,KAAK;AACrC,YAAM,MAAM,UAAU,UAAU,CAAC,MAAM,EAAE,OAAO,EAAE;AAClD,UAAI,QAAQ,GAAI,OAAM,IAAI,mBAAmB;AAE7C,gBAAU,OAAO,KAAK,CAAC;AACvB,YAAM,QAAQ,QAAQ,SAAS;AAAA,IACjC;AAAA,IAEA,MAAM,mBAAmB,aAAoC;AAC3D,YAAM,YAAY,MAAM,QAAQ,KAAK;AACrC,YAAM,QAAQ,QAAQ,UAAU,OAAO,CAAC,MAAM,EAAE,gBAAgB,WAAW,CAAC;AAAA,IAC9E;AAAA,IAEA,MAAM,uBAAuB,IAAY,aAAuC;AAC9E,YAAM,MAAM,MAAM,QAAQ,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE;AACzD,aAAO,OAAO,UAAa,GAAG,gBAAgB;AAAA,IAChD;AAAA,EACF;AACF;","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { AnchorData, AnnotationCreateInput, AnnotationPayload, AnnotationRecord, AnnotationResponse, CLOSED_FEEDBACK_STATUSES, CONSOLE_DIAGNOSTIC_LEVELS, ClosedFeedbackStatus, CollectionStore, CollectionStoreBackend, ConsoleDiagnosticEntry, ConsoleDiagnosticLevel, DiagnosticsSnapshot, FEEDBACK_STATUSES, FEEDBACK_TYPES, FeedbackCreateInput, FeedbackPage, FeedbackPayload, FeedbackQuery, FeedbackRecord, FeedbackResponse, FeedbackResponseList, FeedbackStatus, FeedbackType, FeedbackUpdateInput, FilterResult, NetworkDiagnosticEntry, OPEN_FEEDBACK_STATUSES, OpenFeedbackStatus, RectData, ScreenshotRegion, ScreenshotStorage, Serialized, SitepingStore, StoreDuplicateError, StoreNotFoundError, StorePersistenceError, applyFeedbackFilters, buildAnnotationRecord, buildFeedbackRecord, createCollectionStore, flattenAnnotation, isClosedStatus, isStoreDuplicate, isStoreNotFound, isStorePersistence, toFeedbackUpdate } from './siteping-core.cjs';
|
|
2
|
+
import './siteping-core-testing.cjs';
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { AnchorData, AnnotationCreateInput, AnnotationPayload, AnnotationRecord, AnnotationResponse, CLOSED_FEEDBACK_STATUSES, CONSOLE_DIAGNOSTIC_LEVELS, ClosedFeedbackStatus, CollectionStore, CollectionStoreBackend, ConsoleDiagnosticEntry, ConsoleDiagnosticLevel, DiagnosticsSnapshot, FEEDBACK_STATUSES, FEEDBACK_TYPES, FeedbackCreateInput, FeedbackPage, FeedbackPayload, FeedbackQuery, FeedbackRecord, FeedbackResponse, FeedbackResponseList, FeedbackStatus, FeedbackType, FeedbackUpdateInput, FilterResult, NetworkDiagnosticEntry, OPEN_FEEDBACK_STATUSES, OpenFeedbackStatus, RectData, ScreenshotRegion, ScreenshotStorage, Serialized, SitepingStore, StoreDuplicateError, StoreNotFoundError, StorePersistenceError, applyFeedbackFilters, buildAnnotationRecord, buildFeedbackRecord, createCollectionStore, flattenAnnotation, isClosedStatus, isStoreDuplicate, isStoreNotFound, isStorePersistence, toFeedbackUpdate } from './siteping-core.js';
|
|
2
|
+
import './siteping-core-testing.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CLOSED_FEEDBACK_STATUSES,
|
|
3
|
+
CONSOLE_DIAGNOSTIC_LEVELS,
|
|
4
|
+
FEEDBACK_STATUSES,
|
|
5
|
+
FEEDBACK_TYPES,
|
|
6
|
+
OPEN_FEEDBACK_STATUSES,
|
|
7
|
+
StoreDuplicateError,
|
|
8
|
+
StoreNotFoundError,
|
|
9
|
+
StorePersistenceError,
|
|
10
|
+
flattenAnnotation,
|
|
11
|
+
isClosedStatus,
|
|
12
|
+
isStoreDuplicate,
|
|
13
|
+
isStoreNotFound,
|
|
14
|
+
isStorePersistence,
|
|
15
|
+
toFeedbackUpdate
|
|
16
|
+
} from "./chunk-YQHAD24P.js";
|
|
17
|
+
|
|
18
|
+
// ../core/src/filters.ts
|
|
19
|
+
var DEFAULT_LIMIT = 50;
|
|
20
|
+
var MAX_LIMIT = 100;
|
|
21
|
+
function applyFeedbackFilters(items, query) {
|
|
22
|
+
let results = items.filter((f) => f.projectName === query.projectName);
|
|
23
|
+
if (query.type) results = results.filter((f) => f.type === query.type);
|
|
24
|
+
if (query.statuses && query.statuses.length > 0) {
|
|
25
|
+
const allowed = query.statuses;
|
|
26
|
+
results = results.filter((f) => allowed.includes(f.status));
|
|
27
|
+
} else if (query.status) {
|
|
28
|
+
results = results.filter((f) => f.status === query.status);
|
|
29
|
+
}
|
|
30
|
+
if (query.url) results = results.filter((f) => f.url === query.url);
|
|
31
|
+
if (query.urlPattern) results = results.filter((f) => f.urlPattern === query.urlPattern);
|
|
32
|
+
if (query.search) {
|
|
33
|
+
const s = query.search.toLowerCase();
|
|
34
|
+
results = results.filter((f) => f.message.toLowerCase().includes(s));
|
|
35
|
+
}
|
|
36
|
+
results.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
|
|
37
|
+
const total = results.length;
|
|
38
|
+
const page = Math.max(1, query.page ?? 1);
|
|
39
|
+
const limit = Math.max(1, Math.min(query.limit ?? DEFAULT_LIMIT, MAX_LIMIT));
|
|
40
|
+
const start = (page - 1) * limit;
|
|
41
|
+
return { feedbacks: results.slice(start, start + limit), total };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ../core/src/store-helpers.ts
|
|
45
|
+
function buildAnnotationRecord(input, ctx) {
|
|
46
|
+
return {
|
|
47
|
+
id: ctx.id,
|
|
48
|
+
feedbackId: ctx.feedbackId,
|
|
49
|
+
cssSelector: input.cssSelector,
|
|
50
|
+
xpath: input.xpath,
|
|
51
|
+
textSnippet: input.textSnippet,
|
|
52
|
+
elementTag: input.elementTag,
|
|
53
|
+
elementId: input.elementId ?? null,
|
|
54
|
+
textPrefix: input.textPrefix,
|
|
55
|
+
textSuffix: input.textSuffix,
|
|
56
|
+
fingerprint: input.fingerprint,
|
|
57
|
+
neighborText: input.neighborText,
|
|
58
|
+
anchorKey: input.anchorKey ?? null,
|
|
59
|
+
xPct: input.xPct,
|
|
60
|
+
yPct: input.yPct,
|
|
61
|
+
wPct: input.wPct,
|
|
62
|
+
hPct: input.hPct,
|
|
63
|
+
scrollX: input.scrollX,
|
|
64
|
+
scrollY: input.scrollY,
|
|
65
|
+
viewportW: input.viewportW,
|
|
66
|
+
viewportH: input.viewportH,
|
|
67
|
+
devicePixelRatio: input.devicePixelRatio,
|
|
68
|
+
createdAt: ctx.now
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
function buildFeedbackRecord(input, ctx) {
|
|
72
|
+
const now = ctx.now ?? /* @__PURE__ */ new Date();
|
|
73
|
+
return {
|
|
74
|
+
id: ctx.id,
|
|
75
|
+
type: input.type,
|
|
76
|
+
message: input.message,
|
|
77
|
+
status: input.status,
|
|
78
|
+
projectName: input.projectName,
|
|
79
|
+
url: input.url,
|
|
80
|
+
urlPattern: input.urlPattern ?? null,
|
|
81
|
+
authorName: input.authorName,
|
|
82
|
+
authorEmail: input.authorEmail,
|
|
83
|
+
viewport: input.viewport,
|
|
84
|
+
userAgent: input.userAgent,
|
|
85
|
+
clientId: input.clientId,
|
|
86
|
+
resolvedAt: null,
|
|
87
|
+
createdAt: now,
|
|
88
|
+
updatedAt: now,
|
|
89
|
+
annotations: input.annotations.map(
|
|
90
|
+
(ann) => buildAnnotationRecord(ann, { id: ctx.annotationId(), feedbackId: ctx.id, now })
|
|
91
|
+
),
|
|
92
|
+
screenshotUrl: input.screenshotDataUrl ?? null,
|
|
93
|
+
screenshotRegion: input.screenshotRegion ?? null,
|
|
94
|
+
diagnostics: input.diagnostics ?? null
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
function createCollectionStore(backend) {
|
|
98
|
+
return {
|
|
99
|
+
async createFeedback(data) {
|
|
100
|
+
const feedbacks = await backend.load();
|
|
101
|
+
const existing = feedbacks.find((f) => f.clientId === data.clientId);
|
|
102
|
+
if (existing) return existing;
|
|
103
|
+
const record = buildFeedbackRecord(data, {
|
|
104
|
+
id: backend.generateId(),
|
|
105
|
+
annotationId: () => backend.generateId()
|
|
106
|
+
});
|
|
107
|
+
feedbacks.unshift(record);
|
|
108
|
+
try {
|
|
109
|
+
await backend.persist(feedbacks);
|
|
110
|
+
} catch (err) {
|
|
111
|
+
if (!record.screenshotUrl) throw err;
|
|
112
|
+
record.screenshotUrl = null;
|
|
113
|
+
await backend.persist(feedbacks);
|
|
114
|
+
}
|
|
115
|
+
return record;
|
|
116
|
+
},
|
|
117
|
+
async getFeedbacks(query) {
|
|
118
|
+
return applyFeedbackFilters(await backend.load(), query);
|
|
119
|
+
},
|
|
120
|
+
async findByClientId(clientId) {
|
|
121
|
+
return (await backend.load()).find((f) => f.clientId === clientId) ?? null;
|
|
122
|
+
},
|
|
123
|
+
async updateFeedback(id, data) {
|
|
124
|
+
const feedbacks = await backend.load();
|
|
125
|
+
const fb = feedbacks.find((f) => f.id === id);
|
|
126
|
+
if (!fb) throw new StoreNotFoundError();
|
|
127
|
+
fb.status = data.status;
|
|
128
|
+
fb.resolvedAt = data.resolvedAt;
|
|
129
|
+
fb.updatedAt = /* @__PURE__ */ new Date();
|
|
130
|
+
await backend.persist(feedbacks);
|
|
131
|
+
return fb;
|
|
132
|
+
},
|
|
133
|
+
async deleteFeedback(id) {
|
|
134
|
+
const feedbacks = await backend.load();
|
|
135
|
+
const idx = feedbacks.findIndex((f) => f.id === id);
|
|
136
|
+
if (idx === -1) throw new StoreNotFoundError();
|
|
137
|
+
feedbacks.splice(idx, 1);
|
|
138
|
+
await backend.persist(feedbacks);
|
|
139
|
+
},
|
|
140
|
+
async deleteAllFeedbacks(projectName) {
|
|
141
|
+
const feedbacks = await backend.load();
|
|
142
|
+
await backend.persist(feedbacks.filter((f) => f.projectName !== projectName));
|
|
143
|
+
},
|
|
144
|
+
async verifyProjectOwnership(id, projectName) {
|
|
145
|
+
const fb = (await backend.load()).find((f) => f.id === id);
|
|
146
|
+
return fb !== void 0 && fb.projectName === projectName;
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
export {
|
|
151
|
+
CLOSED_FEEDBACK_STATUSES,
|
|
152
|
+
CONSOLE_DIAGNOSTIC_LEVELS,
|
|
153
|
+
FEEDBACK_STATUSES,
|
|
154
|
+
FEEDBACK_TYPES,
|
|
155
|
+
OPEN_FEEDBACK_STATUSES,
|
|
156
|
+
StoreDuplicateError,
|
|
157
|
+
StoreNotFoundError,
|
|
158
|
+
StorePersistenceError,
|
|
159
|
+
applyFeedbackFilters,
|
|
160
|
+
buildAnnotationRecord,
|
|
161
|
+
buildFeedbackRecord,
|
|
162
|
+
createCollectionStore,
|
|
163
|
+
flattenAnnotation,
|
|
164
|
+
isClosedStatus,
|
|
165
|
+
isStoreDuplicate,
|
|
166
|
+
isStoreNotFound,
|
|
167
|
+
isStorePersistence,
|
|
168
|
+
toFeedbackUpdate
|
|
169
|
+
};
|
|
170
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../core/src/filters.ts","../../core/src/store-helpers.ts"],"sourcesContent":["/**\n * Shared feedback-record filtering and pagination — extracted from\n * `adapter-memory` and `adapter-localstorage` which previously kept two\n * near-identical copies of the same logic. Any adapter that holds an\n * in-memory snapshot of feedbacks can use it.\n *\n * Filtering order matches the historical adapter behaviour:\n * 1. projectName (always required)\n * 2. type\n * 3. status / statuses (`statuses` bucket wins when both are set)\n * 4. url\n * 5. urlPattern\n * 6. search (lowercase substring match on `message`)\n *\n * Pagination clamps `limit` to a maximum of 100 and treats `page` as 1-based,\n * matching the public API contract documented on `getFeedbacks`. A page or\n * limit below 1 is clamped up to 1 rather than indexing backwards from the\n * end of the match set.\n */\n\nimport type { FeedbackQuery, FeedbackRecord } from \"./types.js\";\n\n/** Default page size when the caller omits `query.limit`. */\nconst DEFAULT_LIMIT = 50;\n/** Maximum allowed page size — defends against memory blow-ups on hostile callers. */\nconst MAX_LIMIT = 100;\n\nexport interface FilterResult {\n feedbacks: FeedbackRecord[];\n total: number;\n}\n\n/**\n * Apply the standard feedback filter + pagination pipeline against an\n * in-memory snapshot. Used by `MemoryStore.getFeedbacks` and\n * `LocalStorageStore.getFeedbacks` so the two never drift.\n *\n * @param items All known feedback records (already include `annotations`).\n * @param query Filter and pagination options. `projectName` is required.\n */\nexport function applyFeedbackFilters(items: readonly FeedbackRecord[], query: FeedbackQuery): FilterResult {\n let results: FeedbackRecord[] = items.filter((f) => f.projectName === query.projectName);\n\n if (query.type) results = results.filter((f) => f.type === query.type);\n // `statuses` (bucket / any-of) wins over the exact `status` filter when both\n // are present; an empty array is treated as absent.\n if (query.statuses && query.statuses.length > 0) {\n const allowed = query.statuses;\n results = results.filter((f) => allowed.includes(f.status));\n } else if (query.status) {\n results = results.filter((f) => f.status === query.status);\n }\n if (query.url) results = results.filter((f) => f.url === query.url);\n if (query.urlPattern) results = results.filter((f) => f.urlPattern === query.urlPattern);\n if (query.search) {\n const s = query.search.toLowerCase();\n results = results.filter((f) => f.message.toLowerCase().includes(s));\n }\n\n // Newest first is part of the store contract (PrismaStore orders by\n // createdAt desc) — sort explicitly instead of relying on insertion order.\n // Array.prototype.sort is stable, so same-millisecond records keep their\n // insertion order (newest inserted first).\n results.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n\n const total = results.length;\n // Both bounds are clamped from below, not just `limit` from above:\n // `(page - 1) * limit` goes negative for a non-positive page or limit, and\n // `slice` reads negative indices from the END — so `page: -1` returned a\n // window whose position depended on how many records happened to match,\n // rather than an empty page or the first one. The Prisma adapter rejects\n // these at the HTTP edge (`z.coerce.number().int().min(1)`), but the\n // in-memory adapters have no schema in front of them and call straight in.\n const page = Math.max(1, query.page ?? 1);\n const limit = Math.max(1, Math.min(query.limit ?? DEFAULT_LIMIT, MAX_LIMIT));\n const start = (page - 1) * limit;\n\n return { feedbacks: results.slice(start, start + limit), total };\n}\n","/**\n * Record-construction helpers and the collection-store engine.\n *\n * Every snapshot-style adapter (memory, localStorage, flat file, KV, …)\n * needs the same three ingredients: turn a `FeedbackCreateInput` into a\n * `FeedbackRecord` (null-normalizing optional fields, stamping ids and\n * timestamps), filter/paginate with `applyFeedbackFilters`, and implement\n * the dedup/update/delete choreography of the `SitepingStore` contract.\n *\n * `buildFeedbackRecord` / `buildAnnotationRecord` cover the first part for\n * any adapter. `createCollectionStore` covers all of it: give it `load`,\n * `persist`, and `generateId`, and it returns a fully conformant\n * `SitepingStore` — writing a new snapshot adapter is ~20 lines plus its\n * storage specifics.\n */\n\nimport { applyFeedbackFilters } from \"./filters.js\";\nimport type {\n AnnotationCreateInput,\n AnnotationRecord,\n FeedbackCreateInput,\n FeedbackPage,\n FeedbackQuery,\n FeedbackRecord,\n FeedbackUpdateInput,\n SitepingStore,\n} from \"./types.js\";\nimport { StoreNotFoundError } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Record construction\n// ---------------------------------------------------------------------------\n\n/**\n * Build a persisted `AnnotationRecord` from its create input — normalizes\n * the optional anchor fields to `null` and stamps identity/timestamp.\n */\nexport function buildAnnotationRecord(\n input: AnnotationCreateInput,\n ctx: { id: string; feedbackId: string; now: Date },\n): AnnotationRecord {\n return {\n id: ctx.id,\n feedbackId: ctx.feedbackId,\n cssSelector: input.cssSelector,\n xpath: input.xpath,\n textSnippet: input.textSnippet,\n elementTag: input.elementTag,\n elementId: input.elementId ?? null,\n textPrefix: input.textPrefix,\n textSuffix: input.textSuffix,\n fingerprint: input.fingerprint,\n neighborText: input.neighborText,\n anchorKey: input.anchorKey ?? null,\n xPct: input.xPct,\n yPct: input.yPct,\n wPct: input.wPct,\n hPct: input.hPct,\n scrollX: input.scrollX,\n scrollY: input.scrollY,\n viewportW: input.viewportW,\n viewportH: input.viewportH,\n devicePixelRatio: input.devicePixelRatio,\n createdAt: ctx.now,\n };\n}\n\n/**\n * Build a persisted `FeedbackRecord` (with its annotations) from a create\n * input — normalizes every optional field to `null` and stamps ids and\n * timestamps. Adapters without external screenshot storage keep the data\n * URL inline on `screenshotUrl`, which is what this helper does; adapters\n * with a `ScreenshotStorage` upload first and override `screenshotUrl`.\n */\nexport function buildFeedbackRecord(\n input: FeedbackCreateInput,\n ctx: { id: string; annotationId: () => string; now?: Date },\n): FeedbackRecord {\n const now = ctx.now ?? new Date();\n return {\n id: ctx.id,\n type: input.type,\n message: input.message,\n status: input.status,\n projectName: input.projectName,\n url: input.url,\n urlPattern: input.urlPattern ?? null,\n authorName: input.authorName,\n authorEmail: input.authorEmail,\n viewport: input.viewport,\n userAgent: input.userAgent,\n clientId: input.clientId,\n resolvedAt: null,\n createdAt: now,\n updatedAt: now,\n annotations: input.annotations.map((ann) =>\n buildAnnotationRecord(ann, { id: ctx.annotationId(), feedbackId: ctx.id, now }),\n ),\n screenshotUrl: input.screenshotDataUrl ?? null,\n screenshotRegion: input.screenshotRegion ?? null,\n diagnostics: input.diagnostics ?? null,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Collection-store engine\n// ---------------------------------------------------------------------------\n\n/**\n * Storage primitives behind a collection store. `load`/`persist` may be\n * sync or async — the engine awaits both, so in-memory arrays, localStorage\n * and async KV stores all fit the same three functions.\n */\nexport interface CollectionStoreBackend {\n /** Return the current full snapshot of feedback records. */\n load(): FeedbackRecord[] | Promise<FeedbackRecord[]>;\n /**\n * Persist the full snapshot. Throw `StorePersistenceError` when the write\n * is lost (quota, storage disabled, …) — never swallow the failure.\n */\n persist(feedbacks: FeedbackRecord[]): void | Promise<void>;\n /** Generate a unique id for a new feedback or annotation record. */\n generateId(): string;\n}\n\n/**\n * A `SitepingStore` with the optional `verifyProjectOwnership` guaranteed —\n * what `createCollectionStore` returns.\n */\nexport type CollectionStore = SitepingStore & Required<Pick<SitepingStore, \"verifyProjectOwnership\">>;\n\n/**\n * Build a fully conformant `SitepingStore` on top of a snapshot backend.\n *\n * The engine implements the whole store contract: clientId dedup (idempotent\n * create), newest-first ordering, the standard filter/pagination pipeline,\n * `StoreNotFoundError` on missing update/delete, project-scoped bulk delete,\n * and `verifyProjectOwnership`. When `persist` fails during `createFeedback`\n * and the record carries an inline screenshot, the engine retries once\n * without the screenshot (by far the heaviest field) so the text feedback\n * survives a storage-quota hit; if that also fails, the error propagates —\n * returning the record would claim a success that was never persisted.\n *\n * @example\n * ```ts\n * export class MemoryStore implements SitepingStore {\n * private feedbacks: FeedbackRecord[] = [];\n * private readonly store = createCollectionStore({\n * load: () => this.feedbacks,\n * persist: (next) => {\n * this.feedbacks = next;\n * },\n * generateId: () => crypto.randomUUID(),\n * });\n * createFeedback = this.store.createFeedback;\n * // …delegate the remaining methods the same way\n * }\n * ```\n */\nexport function createCollectionStore(backend: CollectionStoreBackend): CollectionStore {\n return {\n async createFeedback(data: FeedbackCreateInput): Promise<FeedbackRecord> {\n const feedbacks = await backend.load();\n\n // ClientId dedup — idempotent\n const existing = feedbacks.find((f) => f.clientId === data.clientId);\n if (existing) return existing;\n\n const record = buildFeedbackRecord(data, {\n id: backend.generateId(),\n annotationId: () => backend.generateId(),\n });\n\n feedbacks.unshift(record);\n try {\n await backend.persist(feedbacks);\n } catch (err) {\n if (!record.screenshotUrl) throw err;\n record.screenshotUrl = null;\n await backend.persist(feedbacks);\n }\n return record;\n },\n\n async getFeedbacks(query: FeedbackQuery): Promise<FeedbackPage> {\n return applyFeedbackFilters(await backend.load(), query);\n },\n\n async findByClientId(clientId: string): Promise<FeedbackRecord | null> {\n return (await backend.load()).find((f) => f.clientId === clientId) ?? null;\n },\n\n async updateFeedback(id: string, data: FeedbackUpdateInput): Promise<FeedbackRecord> {\n const feedbacks = await backend.load();\n const fb = feedbacks.find((f) => f.id === id);\n if (!fb) throw new StoreNotFoundError();\n\n fb.status = data.status;\n fb.resolvedAt = data.resolvedAt;\n fb.updatedAt = new Date();\n await backend.persist(feedbacks);\n return fb;\n },\n\n async deleteFeedback(id: string): Promise<void> {\n const feedbacks = await backend.load();\n const idx = feedbacks.findIndex((f) => f.id === id);\n if (idx === -1) throw new StoreNotFoundError();\n\n feedbacks.splice(idx, 1);\n await backend.persist(feedbacks);\n },\n\n async deleteAllFeedbacks(projectName: string): Promise<void> {\n const feedbacks = await backend.load();\n await backend.persist(feedbacks.filter((f) => f.projectName !== projectName));\n },\n\n async verifyProjectOwnership(id: string, projectName: string): Promise<boolean> {\n const fb = (await backend.load()).find((f) => f.id === id);\n return fb !== undefined && fb.projectName === projectName;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuBA,IAAM,gBAAgB;AAEtB,IAAM,YAAY;AAeX,SAAS,qBAAqB,OAAkC,OAAoC;AACzG,MAAI,UAA4B,MAAM,OAAO,CAAC,MAAM,EAAE,gBAAgB,MAAM,WAAW;AAEvF,MAAI,MAAM,KAAM,WAAU,QAAQ,OAAO,CAAC,MAAM,EAAE,SAAS,MAAM,IAAI;AAGrE,MAAI,MAAM,YAAY,MAAM,SAAS,SAAS,GAAG;AAC/C,UAAM,UAAU,MAAM;AACtB,cAAU,QAAQ,OAAO,CAAC,MAAM,QAAQ,SAAS,EAAE,MAAM,CAAC;AAAA,EAC5D,WAAW,MAAM,QAAQ;AACvB,cAAU,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,MAAM,MAAM;AAAA,EAC3D;AACA,MAAI,MAAM,IAAK,WAAU,QAAQ,OAAO,CAAC,MAAM,EAAE,QAAQ,MAAM,GAAG;AAClE,MAAI,MAAM,WAAY,WAAU,QAAQ,OAAO,CAAC,MAAM,EAAE,eAAe,MAAM,UAAU;AACvF,MAAI,MAAM,QAAQ;AAChB,UAAM,IAAI,MAAM,OAAO,YAAY;AACnC,cAAU,QAAQ,OAAO,CAAC,MAAM,EAAE,QAAQ,YAAY,EAAE,SAAS,CAAC,CAAC;AAAA,EACrE;AAMA,UAAQ,KAAK,CAAC,GAAG,MAAM,EAAE,UAAU,QAAQ,IAAI,EAAE,UAAU,QAAQ,CAAC;AAEpE,QAAM,QAAQ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