@beezping/adapter-memory 0.6.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.
@@ -0,0 +1,947 @@
1
+ import { type Prettify, type Serialized } from "./type-utils.cjs";
2
+ /** FAB anchor — bottom-corner placement supported by the widget. */
3
+ export type SitepingPosition = "bottom-right" | "bottom-left";
4
+ /** Visual theme — `auto` resolves to `light` or `dark` via system preference. */
5
+ export type SitepingTheme = "light" | "dark" | "auto";
6
+ /** Built-in UI locales shipped with the widget. */
7
+ export declare const BUILTIN_LOCALES: readonly ["en", "fr", "de", "es", "it", "pt", "ru"];
8
+ export type BuiltinLocale = (typeof BUILTIN_LOCALES)[number];
9
+ /**
10
+ * Locale identifier accepted by the widget. Built-in locales are kept as
11
+ * literal strings so editors auto-complete them, but arbitrary BCP-47 tags
12
+ * are also accepted (custom dictionaries registered via `registerLocale`).
13
+ */
14
+ export type SitepingLocale = BuiltinLocale | (string & {});
15
+ /**
16
+ * Reasons reported through `SitepingConfig.onSkip` — production environment,
17
+ * mobile viewport, or server-side rendering (no `window`/`document`).
18
+ */
19
+ export type SitepingSkipReason = "production" | "mobile" | "ssr";
20
+ /** Per-channel + per-buffer-size diagnostics configuration. */
21
+ export interface DiagnosticsCaptureOptions {
22
+ console?: boolean | undefined;
23
+ network?: boolean | undefined;
24
+ maxConsoleEntries?: number | undefined;
25
+ maxNetworkEntries?: number | undefined;
26
+ }
27
+ /** Identity payload supplied by the host application — bypasses the modal. */
28
+ export interface SitepingIdentity {
29
+ name: string;
30
+ email: string;
31
+ }
32
+ /** Deep-link configuration — controls how a feedback id is read from the URL. */
33
+ export interface SitepingDeepLinkOptions {
34
+ /** Query parameter name carrying the feedback id. Defaults to `"siteping"`. */
35
+ param?: string | undefined;
36
+ }
37
+ /**
38
+ * Extra request headers for HTTP mode — a static map, or a factory (sync or
39
+ * async) invoked once per request to produce fresh values (e.g. a short-lived
40
+ * session token).
41
+ */
42
+ export type SitepingHeadersOption = Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
43
+ /**
44
+ * Cookie policy for HTTP-mode requests — forwarded verbatim as the
45
+ * `credentials` option of every `fetch` the widget (or the dashboard's
46
+ * endpoint source) makes. Mirrors the DOM `RequestCredentials` union,
47
+ * declared here so core stays free of DOM lib types.
48
+ *
49
+ * - `"same-origin"` (default): cookies only when the endpoint shares the
50
+ * page's origin — the browser's own default.
51
+ * - `"include"`: also send cookies to a cross-origin endpoint. Required when a
52
+ * server on another origin authenticates with a session cookie; the server
53
+ * must answer with credentialed CORS (the page's exact origin plus
54
+ * `Access-Control-Allow-Credentials: true`, e.g. `@beezping/server`'s
55
+ * `allowedOrigins`).
56
+ * - `"omit"`: never send cookies, even same-origin.
57
+ */
58
+ export type SitepingRequestCredentials = "omit" | "same-origin" | "include";
59
+ /** Every accepted {@link SitepingRequestCredentials} value — runtime guard source for untyped (script-tag) consumers. */
60
+ export declare const REQUEST_CREDENTIALS_MODES: readonly ["omit", "same-origin", "include"];
61
+ /**
62
+ * Credentials mode used when none is configured — the browser's own `fetch`
63
+ * default, so leaving the option unset never changes cookie behavior (and
64
+ * never opts a cross-origin endpoint into cookie-carrying, CSRF-prone requests).
65
+ */
66
+ export declare const DEFAULT_REQUEST_CREDENTIALS = "same-origin";
67
+ /**
68
+ * Narrow an untyped config value to a {@link SitepingRequestCredentials} mode.
69
+ *
70
+ * @param value - Raw `credentials` option (may come from an untyped script-tag config).
71
+ * @returns `true` when `value` is one of {@link REQUEST_CREDENTIALS_MODES}.
72
+ */
73
+ export declare function isRequestCredentials(value: unknown): value is SitepingRequestCredentials;
74
+ /**
75
+ * Actionable description of a rejected `credentials` option — shared by the
76
+ * widget init guard and the dashboard's endpoint source so both report the
77
+ * same wording.
78
+ *
79
+ * @param value - The rejected raw value (a config value, never user content).
80
+ * @returns e.g. `invalid \`credentials\` "all". Expected one of "omit", "same-origin", "include".`
81
+ */
82
+ export declare function describeInvalidRequestCredentials(value: unknown): string;
83
+ /**
84
+ * Options shared by both widget modes (HTTP and direct store).
85
+ *
86
+ * Do not use this type directly — use {@link SitepingConfig}, the
87
+ * discriminated union that adds the mode-specific fields.
88
+ */
89
+ export interface SitepingBaseConfig {
90
+ /** Required — project identifier used to scope feedbacks */
91
+ projectName: string;
92
+ /** FAB position — defaults to 'bottom-right' */
93
+ position?: SitepingPosition | undefined;
94
+ /**
95
+ * Show the "toggle markers visibility" item in the FAB radial menu.
96
+ * Defaults to `true` (current behavior). Set to `false` to hide that
97
+ * item entirely — useful for hosts that always want markers visible
98
+ * (e.g. dedicated review tools) or that find the eye icon redundant
99
+ * when no marker is on screen.
100
+ *
101
+ * Hiding the item also removes its keyboard navigation slot — the
102
+ * remaining two items still respond to ArrowUp/ArrowDown/Home/End.
103
+ * The marker-visibility state itself is unaffected; markers stay
104
+ * visible (the previous default state) and `annotations:toggle` is
105
+ * simply never emitted from the FAB.
106
+ */
107
+ showAnnotationsToggle?: boolean | undefined;
108
+ /** Accent color for the widget UI — defaults to '#0066ff' */
109
+ accentColor?: string | undefined;
110
+ /**
111
+ * Render the widget even when it would normally be skipped — this bypasses
112
+ * BOTH the production-environment guard AND the mobile-viewport guard.
113
+ * It does NOT bypass the SSR guard: without `window`/`document` the widget
114
+ * never renders and `onSkip("ssr")` fires instead.
115
+ * Defaults to false. Use it for dedicated review tools, staging environments,
116
+ * or responsive testing where you always want the widget present.
117
+ */
118
+ forceShow?: boolean | undefined;
119
+ /**
120
+ * Minimum viewport width (px) at or above which the widget renders. Below it,
121
+ * the widget is skipped and `onSkip("mobile")` fires. Defaults to `768`.
122
+ *
123
+ * Set lower (e.g. `0`) to allow narrow/mobile viewports, or use `forceShow`
124
+ * to bypass the viewport check entirely.
125
+ */
126
+ minViewportWidth?: number | undefined;
127
+ /** Enable debug logging of lifecycle events — defaults to false */
128
+ debug?: boolean | undefined;
129
+ /** Color theme — defaults to 'light' */
130
+ theme?: SitepingTheme | undefined;
131
+ /** UI locale — defaults to 'en'. Built-in: en, fr, de, es, it, pt (Brazilian), ru. Any other string falls back to English. */
132
+ locale?: SitepingLocale | undefined;
133
+ /**
134
+ * Returns the current page scope for annotations and panel filtering.
135
+ * Called on initial markers load and on `instance.refresh()`.
136
+ *
137
+ * Default: `{ url: window.location.pathname, urlPattern: null }` — annotations
138
+ * are scoped strictly to the current pathname.
139
+ *
140
+ * Apps with parameterized routes (e.g. React Router) should return both the
141
+ * concrete URL and the route template (e.g. `/orders/:orderId`) so the panel
142
+ * can offer a "this type of page" filter that groups feedbacks by template.
143
+ */
144
+ getPageScope?: (() => PageScope) | undefined;
145
+ /**
146
+ * When true (default), the widget filters initial markers and panel results
147
+ * by `feedback.url === scope.url`, so annotations created on one page never
148
+ * leak to other pages — even if their CSS selector accidentally matches.
149
+ * Set to `false` to revert to the legacy project-wide behavior.
150
+ */
151
+ scopeAnnotationsByUrl?: boolean | undefined;
152
+ /**
153
+ * Capture a JPEG screenshot of the annotated area on submit. Defaults to
154
+ * `false` — opt-in because:
155
+ *
156
+ * - it adds runtime weight (~60 KB gzip dynamic chunk for html2canvas-pro,
157
+ * loaded only on first capture),
158
+ * - it embeds page content in the feedback (privacy/GDPR consideration —
159
+ * inform end users in your widget host UI when enabling).
160
+ *
161
+ * `html2canvas-pro` ships as a regular dependency of `@beezping/widget` so the
162
+ * dynamic import always resolves; you don't need to install anything extra.
163
+ *
164
+ * **Masking sensitive elements:** add `data-siteping-ignore="true"` to any
165
+ * element you do NOT want captured (password fields, credit-card forms,
166
+ * API tokens shown in the UI, etc.). The capture predicate skips matching
167
+ * elements *and their descendants*. Do this BEFORE turning on screenshots
168
+ * in production — once a feedback is saved, the screenshot is in your DB
169
+ * (or object storage) regardless of what was on the page.
170
+ */
171
+ enableScreenshot?: boolean | undefined;
172
+ /**
173
+ * Enable right-click (`contextmenu`) to instantly open the comment composer
174
+ * at the cursor location. When enabled, a document-level listener intercepts
175
+ * right-clicks, prevents the browser's native context menu, and enters the
176
+ * annotation flow anchored to the element under the cursor. Defaults to
177
+ * `false` — the browser's native context menu is never hijacked unless the
178
+ * host explicitly opts in.
179
+ *
180
+ * Keyboard-triggered context menus (≣ Menu key, Shift+F10) always get the
181
+ * native menu; only mouse right-click and touch/pen long-press open the
182
+ * composer.
183
+ *
184
+ * **Modifier-key escape hatch:** holding Shift, Ctrl, Alt, or Meta while
185
+ * right-clicking always falls through to the native context menu, giving
186
+ * users (and devtools) an escape hatch regardless of this setting.
187
+ *
188
+ * Right-clicks on SitePing's own UI (FAB, panel, markers, popup) are
189
+ * ignored — the native menu is shown as expected.
190
+ *
191
+ * Note: on Android, `contextmenu` fires on long-press. The widget already
192
+ * hides below `minViewportWidth` (default 768 px), but tablets above that
193
+ * threshold will trigger this flow on long-press.
194
+ */
195
+ enableRightClickComment?: boolean | undefined;
196
+ /**
197
+ * Capture the last few `console.*` calls and failed network requests
198
+ * (HTTP >= 400 or network error) at the moment a feedback is submitted.
199
+ *
200
+ * Lets reviewers replay the technical context that led to the report —
201
+ * stack traces, 500 responses, dead third-party scripts. Great for the
202
+ * "the page just doesn't work" feedback that contains zero detail.
203
+ *
204
+ * - `true` — capture with defaults (50 console / 20 network entries).
205
+ * - `false` (default) — no capture, no monkey-patching.
206
+ * - object — per-channel toggles + custom buffer sizes.
207
+ *
208
+ * **Privacy considerations:** console messages may contain anything the
209
+ * host page logs, including user data. Failed network requests record the
210
+ * URL (with query string) but never the response body. Inform end users
211
+ * before enabling in environments where they might log sensitive values.
212
+ */
213
+ captureDiagnostics?: boolean | DiagnosticsCaptureOptions | undefined;
214
+ /** Called when the widget is skipped (production mode, mobile viewport, SSR — no DOM) */
215
+ onSkip?: (reason: SitepingSkipReason) => void;
216
+ /**
217
+ * Auto-focus a specific annotation when its ID appears in the URL query
218
+ * string. Lets hosts deeplink directly into a feedback from external
219
+ * systems (Zammad tickets, Slack notifications, dashboard rows).
220
+ *
221
+ * When enabled, the widget reads the configured query parameter from
222
+ * `window.location.search` right after the initial markers load. If the
223
+ * value matches a visible feedback ID, the widget scrolls the annotation
224
+ * into view, pins its highlight, and pulses the marker — the same visual
225
+ * affordance a marker click produces.
226
+ *
227
+ * - `false` / `undefined` (default): no URL parsing. Existing behavior
228
+ * unchanged, no host URL inspection.
229
+ * - `true`: enabled with default query parameter name `siteping`.
230
+ * - object: enabled with a custom parameter name. Use this to avoid
231
+ * clashes with host-app query keys.
232
+ *
233
+ * Only the initial load triggers focus. Subsequent URL changes (SPA
234
+ * navigation, `history.pushState`, hash updates) are ignored —
235
+ * deliberate, to avoid surprising re-scrolls during normal browsing.
236
+ * Hosts that need re-focus on route change can call
237
+ * `instance.focusFeedback(id)` explicitly.
238
+ */
239
+ deepLink?: boolean | SitepingDeepLinkOptions | undefined;
240
+ /**
241
+ * Automatically re-fetch feedbacks when the page changes during client-side
242
+ * (SPA) navigation. Enabled by default.
243
+ *
244
+ * The widget is normally mounted once (singleton) inside a persistent layout
245
+ * — e.g. a Next.js App Router `layout.tsx`, which does NOT remount on
246
+ * client-side navigation. Without this, init runs a single time and both the
247
+ * panel list and the page markers stay frozen on the page where the widget
248
+ * first mounted. With it on, the widget patches the History API
249
+ * (`pushState`/`replaceState`, which SPA routers call instead of triggering
250
+ * `popstate`) and listens for `popstate`/`hashchange`, then re-fetches when
251
+ * the scope key (`getPageScope().url` + template) actually changes.
252
+ *
253
+ * This re-fetches data only — it deliberately does NOT re-focus or re-scroll
254
+ * to an annotation (deep-link focus stays initial-load only; see `deepLink`),
255
+ * so normal browsing is never interrupted by a surprise scroll.
256
+ *
257
+ * - `true` (default) — watch navigation and re-fetch on route change.
258
+ * - `false` — never touch the History API; hosts drive updates manually via
259
+ * `instance.refresh()`.
260
+ */
261
+ watchNavigation?: boolean | undefined;
262
+ /**
263
+ * Pre-fill author identity from the host application — typically the
264
+ * currently signed-in user. When set, the widget uses these values
265
+ * directly and never shows the identity modal, even on first feedback.
266
+ *
267
+ * Use case: SSO-integrated apps where the end user is already
268
+ * authenticated by the host. Avoids the awkward "enter your name and
269
+ * email" prompt for users the host already knows.
270
+ *
271
+ * When unset (default), the widget falls back to localStorage and shows
272
+ * the modal on first feedback as before — existing behavior unchanged.
273
+ *
274
+ * Note: `config.identity` is **not** persisted to localStorage. It is
275
+ * read at widget init time, not on every render. Hosts that need live
276
+ * identity updates after sign-in/sign-out should currently remount the
277
+ * widget (e.g. via a React `key` on the wrapping component). See
278
+ * https://github.com/NeosiaNexus/SitePing/issues/85 for tracking a
279
+ * future enhancement that propagates identity updates without a remount.
280
+ */
281
+ identity?: SitepingIdentity | undefined;
282
+ /** Called when the feedback panel is opened. */
283
+ onOpen?: (() => void) | undefined;
284
+ /** Called when the feedback panel is closed. */
285
+ onClose?: (() => void) | undefined;
286
+ /** Called after a feedback is successfully submitted. */
287
+ onFeedbackSent?: ((feedback: FeedbackResponse) => void) | undefined;
288
+ /**
289
+ * Called when a feedback API call fails.
290
+ *
291
+ * The widget always emits a `SitepingError` (or a subclass:
292
+ * `SitepingNetworkError`, `SitepingValidationError`, `SitepingAuthError`)
293
+ * for HTTP-mode failures — host apps can `instanceof` to drive retry
294
+ * logic, or read `error.code` (`"NETWORK" | "VALIDATION" | "AUTH" |
295
+ * "SERVER"`) and `error.retryable`. The type is widened to `Error` so
296
+ * direct-store callers can still surface raw errors without breaking the
297
+ * contract.
298
+ */
299
+ onError?: ((error: Error) => void) | undefined;
300
+ /** Called when the user starts drawing an annotation. */
301
+ onAnnotationStart?: (() => void) | undefined;
302
+ /** Called when the user finishes drawing an annotation. */
303
+ onAnnotationEnd?: (() => void) | undefined;
304
+ }
305
+ /**
306
+ * HTTP mode — the widget talks to a server endpoint backed by a store
307
+ * adapter (e.g. `@beezping/adapter-prisma` request handlers).
308
+ */
309
+ export interface SitepingHttpConfig extends SitepingBaseConfig {
310
+ /** HTTP endpoint that receives feedbacks (e.g. '/api/siteping'). */
311
+ endpoint: string;
312
+ /**
313
+ * Convenience auth for HTTP mode — sent as `Authorization: Bearer <apiKey>`
314
+ * on every request to `endpoint`.
315
+ *
316
+ * **WARNING: the widget runs in every visitor's browser, so a static key
317
+ * configured here is public** — anyone can read it from your page source
318
+ * and replay it against your API. Only use `apiKey` for internal tools
319
+ * already behind your own login. On public sites, prefer `headers` with a
320
+ * per-request factory returning a short-lived session token.
321
+ */
322
+ apiKey?: string | undefined;
323
+ /**
324
+ * Extra headers for every HTTP-mode request — a static map, or a factory
325
+ * (sync or async) called once per request (e.g. to fetch a fresh session
326
+ * token). Merged over the widget's generated headers, so an explicit
327
+ * `Authorization` entry overrides `apiKey`. A throwing/rejecting factory
328
+ * fails the request like a network error.
329
+ */
330
+ headers?: SitepingHeadersOption | undefined;
331
+ /**
332
+ * Cookie policy for every HTTP-mode request (submit, list, update, delete
333
+ * and the offline retry-queue replay). Defaults to `"same-origin"` — the
334
+ * browser default, so existing setups are unchanged.
335
+ *
336
+ * Set `"include"` when `endpoint` lives on **another origin** and the
337
+ * server authenticates with a session cookie (e.g. a custom
338
+ * `access.authenticate` in `@beezping/server`): without it the browser
339
+ * never attaches the cookie and every request is rejected as
340
+ * unauthenticated. The server must allow the page's origin explicitly with
341
+ * credentialed CORS (`allowedOrigins`) — a wildcard origin never works
342
+ * with cookies. Only opt in for origins you trust: cookie-authenticated
343
+ * cross-origin requests rely on the server's CSRF defenses (strict origin
344
+ * allowlist, `SameSite` cookies).
345
+ *
346
+ * An unknown value (untyped script-tag config) is rejected at init: the
347
+ * widget logs an error and does not load.
348
+ */
349
+ credentials?: SitepingRequestCredentials | undefined;
350
+ /** Not available in HTTP mode — use either `endpoint` or `store`, never both. */
351
+ store?: never;
352
+ }
353
+ /**
354
+ * Store mode — the widget talks to a `SitepingStore` directly in the
355
+ * browser, no server needed (demos, prototypes, localStorage persistence).
356
+ */
357
+ export interface SitepingStoreConfig extends SitepingBaseConfig {
358
+ /** Direct store for client-side mode. Bypasses HTTP entirely. */
359
+ store: SitepingStore;
360
+ /** Not available in store mode — use either `endpoint` or `store`, never both. */
361
+ endpoint?: never;
362
+ /** HTTP-mode only — meaningless without an `endpoint`. */
363
+ apiKey?: never;
364
+ /** HTTP-mode only — meaningless without an `endpoint`. */
365
+ headers?: never;
366
+ /** HTTP-mode only — meaningless without an `endpoint`. */
367
+ credentials?: never;
368
+ }
369
+ /**
370
+ * Configuration options for the Siteping widget.
371
+ *
372
+ * A discriminated union over the two transport modes: pass `endpoint`
373
+ * (HTTP mode, optionally with `apiKey`/`headers`/`credentials`) **or** `store` (direct
374
+ * client-side mode) — never both, never neither. Invalid combinations are
375
+ * compile errors instead of runtime warnings.
376
+ */
377
+ export type SitepingConfig = SitepingHttpConfig | SitepingStoreConfig;
378
+ /** Instance returned by initSiteping() with lifecycle methods. */
379
+ export interface SitepingInstance {
380
+ /** Remove the widget from the DOM and clean up all listeners. */
381
+ destroy: () => void;
382
+ /** Open the panel programmatically */
383
+ open: () => void;
384
+ /** Close the panel */
385
+ close: () => void;
386
+ /** Reload feedbacks from server */
387
+ refresh: () => void;
388
+ /**
389
+ * Scroll the matching annotation into view, pin its highlight, and
390
+ * pulse its marker. Returns `true` when a visible feedback matched the
391
+ * given ID, `false` otherwise (unknown ID, feedback on another URL when
392
+ * `scopeAnnotationsByUrl` filtered it out, or markers not yet loaded).
393
+ *
394
+ * Counterpart to the `deepLink` config option for hosts that prefer to
395
+ * drive focus from JS (e.g., a notification click handler) instead of a
396
+ * URL query parameter.
397
+ */
398
+ focusFeedback: (feedbackId: string) => boolean;
399
+ /** Subscribe to a public widget event */
400
+ on: <K extends keyof SitepingPublicEvents>(event: K, listener: SitepingPublicEventListener<K>) => SitepingUnsubscribe;
401
+ /** Unsubscribe from a public widget event */
402
+ off: <K extends keyof SitepingPublicEvents>(event: K, listener: SitepingPublicEventListener<K>) => void;
403
+ }
404
+ /** Listener signature for a single `SitepingPublicEvents` key. */
405
+ export type SitepingPublicEventListener<K extends keyof SitepingPublicEvents> = (...args: SitepingPublicEvents[K]) => void;
406
+ /** Disposer returned by `SitepingInstance.on` — call once to detach the listener. */
407
+ export type SitepingUnsubscribe = () => void;
408
+ /** Events exposed to consumers via SitepingInstance.on / .off */
409
+ export interface SitepingPublicEvents {
410
+ "feedback:sent": [FeedbackResponse];
411
+ "feedback:deleted": [FeedbackResponse["id"]];
412
+ /**
413
+ * A feedback API call failed. Same payload contract as
414
+ * `SitepingConfig.onError` — a `SitepingError` subclass in HTTP mode,
415
+ * possibly a raw `Error` in store mode.
416
+ */
417
+ "feedback:error": [Error];
418
+ "panel:open": [];
419
+ "panel:close": [];
420
+ /** The user started drawing an annotation. */
421
+ "annotation:start": [];
422
+ /** The user finished drawing an annotation. */
423
+ "annotation:end": [];
424
+ }
425
+ /** Single source of truth for feedback types — used by both TS types and Zod schemas. */
426
+ export declare const FEEDBACK_TYPES: readonly ["question", "change", "bug", "other"];
427
+ export type FeedbackType = (typeof FEEDBACK_TYPES)[number];
428
+ /** Single source of truth for feedback statuses. */
429
+ export declare const FEEDBACK_STATUSES: readonly ["open", "in_progress", "resolved", "wont_fix"];
430
+ export type FeedbackStatus = (typeof FEEDBACK_STATUSES)[number];
431
+ /**
432
+ * Terminal statuses — the feedback needs no further action. `resolvedAt` is
433
+ * the closure timestamp: set when a feedback enters a closed status, null
434
+ * while it is open or in progress. The derivation happens at the edge (HTTP
435
+ * handler, dashboard) — store adapters persist whatever they are given.
436
+ */
437
+ export declare const CLOSED_FEEDBACK_STATUSES: readonly ["resolved", "wont_fix"];
438
+ /** A terminal status — `resolved` or `wont_fix`. */
439
+ export type ClosedFeedbackStatus = (typeof CLOSED_FEEDBACK_STATUSES)[number];
440
+ /** Non-terminal statuses — the feedback still needs attention. */
441
+ export declare const OPEN_FEEDBACK_STATUSES: readonly ["open", "in_progress"];
442
+ /** A non-terminal status — `open` or `in_progress`. */
443
+ export type OpenFeedbackStatus = (typeof OPEN_FEEDBACK_STATUSES)[number];
444
+ /** Whether a status is terminal (`resolved` or `wont_fix`). Narrows the status type. */
445
+ export declare function isClosedStatus(status: FeedbackStatus): status is ClosedFeedbackStatus;
446
+ /**
447
+ * Page scope returned by `SitepingConfig.getPageScope()`.
448
+ *
449
+ * - `url`: concrete page identifier — usually `window.location.pathname`,
450
+ * used as the strict scope for marker rendering.
451
+ * - `urlPattern`: optional parameterized template (e.g. `/orders/:orderId`)
452
+ * used by the panel's "this type of page" filter to group feedbacks across
453
+ * instances of the same page kind.
454
+ */
455
+ export interface PageScope {
456
+ url: string;
457
+ urlPattern: string | null;
458
+ }
459
+ /** Input for creating a feedback record in the store. */
460
+ export interface FeedbackCreateInput {
461
+ projectName: string;
462
+ type: FeedbackType;
463
+ message: string;
464
+ status: FeedbackStatus;
465
+ url: string;
466
+ /**
467
+ * Optional parameterized URL template (e.g. `/orders/:orderId`) for the page
468
+ * where the feedback was created. Allows the panel to filter feedbacks by
469
+ * "this type of page" across different instances. Null when the host did not
470
+ * provide a `getPageScope` callback or the route has no template.
471
+ */
472
+ urlPattern?: string | null | undefined;
473
+ viewport: string;
474
+ userAgent: string;
475
+ authorName: string;
476
+ authorEmail: string;
477
+ clientId: string;
478
+ annotations: AnnotationCreateInput[];
479
+ /**
480
+ * Base64 JPEG `data:` URL captured by the widget at submit time.
481
+ *
482
+ * Adapters with a configured `ScreenshotStorage` are expected to upload
483
+ * this and persist the returned URL on `FeedbackRecord.screenshotUrl`.
484
+ * Adapters without storage may persist the data URL inline (memory /
485
+ * localStorage / dev) — the widget then renders it directly.
486
+ */
487
+ screenshotDataUrl?: string | null | undefined;
488
+ /**
489
+ * Where the client's annotation rect sits within the screenshot image,
490
+ * as fractions [0, 1] of the image dimensions. Present when the widget
491
+ * captured context around the drawn rect; null for legacy captures that
492
+ * were cropped exactly to the rect (dashboards then render the image
493
+ * without an overlay).
494
+ */
495
+ screenshotRegion?: ScreenshotRegion | null | undefined;
496
+ /**
497
+ * Optional console + failed-network snapshot captured by the widget when
498
+ * `SitepingConfig.captureDiagnostics` is enabled. Stored as JSON on
499
+ * `FeedbackRecord.diagnostics` so reviewers can replay the context.
500
+ */
501
+ diagnostics?: DiagnosticsSnapshot | null | undefined;
502
+ }
503
+ /** Input for a single annotation when creating a feedback. */
504
+ export interface AnnotationCreateInput {
505
+ cssSelector: string;
506
+ xpath: string;
507
+ textSnippet: string;
508
+ elementTag: string;
509
+ elementId?: string | undefined;
510
+ textPrefix: string;
511
+ textSuffix: string;
512
+ fingerprint: string;
513
+ neighborText: string;
514
+ /**
515
+ * Semantic anchor identifier from the closest ancestor's `data-feedback-anchor`
516
+ * attribute. When set, this is the most stable re-anchoring signal because
517
+ * hosts deliberately place these on layout/section roots that survive DOM
518
+ * refactors and viewport changes. Null when no semantic ancestor exists.
519
+ */
520
+ anchorKey?: string | null | undefined;
521
+ xPct: number;
522
+ yPct: number;
523
+ wPct: number;
524
+ hPct: number;
525
+ scrollX: number;
526
+ scrollY: number;
527
+ viewportW: number;
528
+ viewportH: number;
529
+ devicePixelRatio: number;
530
+ }
531
+ /** Query parameters for fetching feedbacks. */
532
+ export interface FeedbackQuery {
533
+ projectName: string;
534
+ type?: FeedbackType | undefined;
535
+ /** Exact single-status filter. For "any of a set" (bucket) semantics, use `statuses`. */
536
+ status?: FeedbackStatus | undefined;
537
+ /**
538
+ * Filter to feedbacks whose status is any of the listed values — bucket
539
+ * semantics used by the panel's binary tabs (e.g. "Open" passes
540
+ * `["open", "in_progress"]`). When both `status` and `statuses` are set,
541
+ * `statuses` wins. An empty array is treated as absent (no status filter).
542
+ */
543
+ statuses?: readonly FeedbackStatus[] | undefined;
544
+ search?: string | undefined;
545
+ page?: number | undefined;
546
+ limit?: number | undefined;
547
+ /**
548
+ * Filter to feedbacks created on this exact URL (path). Used by the panel's
549
+ * "this page" filter and by the markers loader to keep page scopes isolated.
550
+ */
551
+ url?: string | undefined;
552
+ /**
553
+ * Filter to feedbacks created on this URL pattern (e.g. `/orders/:orderId`).
554
+ * Used by the panel's "this type of page" filter to group feedbacks across
555
+ * different concrete instances of the same template.
556
+ */
557
+ urlPattern?: string | undefined;
558
+ }
559
+ /**
560
+ * Update payload for patching a feedback.
561
+ *
562
+ * A discriminated union encoding the closure invariant: a feedback entering
563
+ * a closed status carries its closure timestamp, an open one carries `null`.
564
+ * `{ status: "resolved", resolvedAt: null }` is a compile error instead of a
565
+ * silent data bug. Build it from a plain `FeedbackStatus` with
566
+ * {@link toFeedbackUpdate}.
567
+ */
568
+ export type FeedbackUpdateInput = {
569
+ status: OpenFeedbackStatus;
570
+ resolvedAt: null;
571
+ } | {
572
+ status: ClosedFeedbackStatus;
573
+ resolvedAt: Date;
574
+ };
575
+ /**
576
+ * Derive the {@link FeedbackUpdateInput} for a status change — the closure
577
+ * timestamp is stamped for closed statuses and cleared otherwise. This is
578
+ * the edge derivation described on {@link CLOSED_FEEDBACK_STATUSES}; store
579
+ * adapters persist the result verbatim.
580
+ */
581
+ export declare function toFeedbackUpdate(status: FeedbackStatus, closedAt?: Date): FeedbackUpdateInput;
582
+ /** A persisted feedback record returned by the store. */
583
+ export interface FeedbackRecord {
584
+ id: string;
585
+ type: FeedbackType;
586
+ message: string;
587
+ status: FeedbackStatus;
588
+ projectName: string;
589
+ url: string;
590
+ /**
591
+ * Parameterized URL template the feedback was created on.
592
+ * Null for legacy records or hosts without `getPageScope`.
593
+ */
594
+ urlPattern: string | null;
595
+ authorName: string;
596
+ authorEmail: string;
597
+ viewport: string;
598
+ userAgent: string;
599
+ clientId: string;
600
+ resolvedAt: Date | null;
601
+ createdAt: Date;
602
+ updatedAt: Date;
603
+ annotations: AnnotationRecord[];
604
+ /**
605
+ * URL the widget renders as `<img src>`. Either an `https://...` from a
606
+ * configured `ScreenshotStorage`, or a `data:image/jpeg;base64,...` URL
607
+ * inline-persisted by adapters without storage. Null when no screenshot
608
+ * was captured (legacy records, capture failed, or host disabled it).
609
+ */
610
+ screenshotUrl: string | null;
611
+ /**
612
+ * Annotation rect position within the screenshot image, as fractions of
613
+ * its dimensions. Null for legacy captures cropped exactly to the rect.
614
+ */
615
+ screenshotRegion: ScreenshotRegion | null;
616
+ /**
617
+ * Console + failed-network snapshot captured at submit time. Null when
618
+ * diagnostics weren't enabled on the widget side.
619
+ */
620
+ diagnostics: DiagnosticsSnapshot | null;
621
+ }
622
+ /** A persisted annotation record returned by the store. */
623
+ export interface AnnotationRecord {
624
+ id: string;
625
+ feedbackId: string;
626
+ cssSelector: string;
627
+ xpath: string;
628
+ textSnippet: string;
629
+ elementTag: string;
630
+ elementId: string | null;
631
+ textPrefix: string;
632
+ textSuffix: string;
633
+ fingerprint: string;
634
+ neighborText: string;
635
+ /**
636
+ * Semantic anchor identifier from `data-feedback-anchor`. Null for legacy
637
+ * annotations or those drawn outside any anchored region.
638
+ */
639
+ anchorKey: string | null;
640
+ xPct: number;
641
+ yPct: number;
642
+ wPct: number;
643
+ hPct: number;
644
+ scrollX: number;
645
+ scrollY: number;
646
+ viewportW: number;
647
+ viewportH: number;
648
+ devicePixelRatio: number;
649
+ createdAt: Date;
650
+ }
651
+ /**
652
+ * Thrown when a record is not found during update or delete.
653
+ *
654
+ * Handlers translate this to HTTP 404. Adapters MUST throw this (not
655
+ * ORM-specific errors) so the handler layer remains ORM-agnostic.
656
+ */
657
+ export declare class StoreNotFoundError extends Error {
658
+ readonly code: "STORE_NOT_FOUND";
659
+ constructor(message?: string, options?: ErrorOptions);
660
+ }
661
+ /**
662
+ * Thrown when a unique constraint is violated (e.g. duplicate `clientId`).
663
+ *
664
+ * Handlers use this to return the existing record instead of failing.
665
+ */
666
+ export declare class StoreDuplicateError extends Error {
667
+ readonly code: "STORE_DUPLICATE";
668
+ constructor(message?: string, options?: ErrorOptions);
669
+ }
670
+ /**
671
+ * Thrown when a store accepts a mutation but cannot persist it — e.g.
672
+ * `localStorage` is full (QuotaExceededError). Adapters MUST throw this rather
673
+ * than swallow the failure, so callers learn the write was lost instead of
674
+ * seeing a phantom success.
675
+ */
676
+ export declare class StorePersistenceError extends Error {
677
+ readonly code: "STORE_PERSISTENCE";
678
+ constructor(message?: string, options?: ErrorOptions);
679
+ }
680
+ /** Shape of any ORM error that carries a Prisma-style `code` field. */
681
+ type CodedError<C extends string = string> = {
682
+ code: C;
683
+ };
684
+ /**
685
+ * Type guard — works for `StoreNotFoundError` and ORM-specific equivalents
686
+ * (e.g. Prisma P2025). Matches the stable `STORE_NOT_FOUND` code as well as
687
+ * `instanceof`: every consumer package bundles its own copy of core (tsup
688
+ * `noExternal`), so an adapter's instance fails `instanceof` against the
689
+ * server's class identity.
690
+ */
691
+ export declare function isStoreNotFound(error: unknown): error is StoreNotFoundError | CodedError<"STORE_NOT_FOUND"> | CodedError<"P2025">;
692
+ /**
693
+ * Type guard — works for `StoreDuplicateError` and ORM-specific equivalents
694
+ * (e.g. Prisma P2002). Matches the stable `STORE_DUPLICATE` code as well as
695
+ * `instanceof`, for the same cross-bundle reason as {@link isStoreNotFound}.
696
+ */
697
+ export declare function isStoreDuplicate(error: unknown): error is StoreDuplicateError | CodedError<"STORE_DUPLICATE"> | CodedError<"P2002">;
698
+ /**
699
+ * Type guard for `StorePersistenceError`. Matches on the stable `code` field
700
+ * in addition to `instanceof`: every consumer package bundles its own copy of
701
+ * core (tsup `noExternal`), so an instance thrown by one package fails an
702
+ * `instanceof` check against another package's class identity.
703
+ */
704
+ export declare function isStorePersistence(error: unknown): error is StorePersistenceError | CodedError<"STORE_PERSISTENCE">;
705
+ /** Flatten a widget `AnnotationPayload` (nested anchor + rect) into a flat `AnnotationCreateInput`. */
706
+ export declare function flattenAnnotation(ann: AnnotationPayload): AnnotationCreateInput;
707
+ /**
708
+ * Outcome of `SitepingStore.createFeedbackIfAbsent` — the record plus whether
709
+ * this very call inserted it.
710
+ */
711
+ export interface FeedbackCreateOutcome {
712
+ feedback: FeedbackRecord;
713
+ /**
714
+ * `true` when this call inserted the record, `false` when a record with the
715
+ * same `clientId` already existed and is returned instead (a replay, or a
716
+ * concurrent request that won the race).
717
+ */
718
+ created: boolean;
719
+ }
720
+ /** Paginated result returned by `SitepingStore.getFeedbacks`. */
721
+ export interface FeedbackPage {
722
+ feedbacks: FeedbackRecord[];
723
+ total: number;
724
+ }
725
+ /**
726
+ * Abstract storage interface for Siteping.
727
+ *
728
+ * Any adapter (Prisma, Drizzle, raw SQL, localStorage, etc.) implements this
729
+ * interface. The HTTP handler and widget `StoreClient` operate against
730
+ * `SitepingStore`, decoupled from the storage backend.
731
+ *
732
+ * ## Error contract
733
+ *
734
+ * - **`updateFeedback` / `deleteFeedback`**: throw `StoreNotFoundError` when
735
+ * the record does not exist.
736
+ * - **`createFeedback`**: either return the existing record on duplicate
737
+ * `clientId` (idempotent) or throw `StoreDuplicateError`. The handler
738
+ * handles both patterns — but only a throw, or the optional
739
+ * `createFeedbackIfAbsent`, tells it the record was not inserted by this
740
+ * call; stores that return the existing record should implement
741
+ * `createFeedbackIfAbsent` so creation side effects never run twice.
742
+ * - **All mutations**: when a write is accepted but cannot be persisted
743
+ * (e.g. storage quota), throw `StorePersistenceError` instead of reporting
744
+ * a phantom success. Detect it with `isStorePersistence`.
745
+ * - Other methods should not throw on empty results — return empty arrays or `null`.
746
+ */
747
+ export interface SitepingStore {
748
+ /** 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. */
749
+ createFeedback(data: FeedbackCreateInput): Promise<FeedbackRecord>;
750
+ /** Paginated query with optional filters. Returns empty array (not error) when no results. */
751
+ getFeedbacks(query: FeedbackQuery): Promise<FeedbackPage>;
752
+ /** Lookup by client-generated UUID. Returns `null` (not error) when not found. */
753
+ findByClientId(clientId: string): Promise<FeedbackRecord | null>;
754
+ /** Update status/resolvedAt. Throws `StoreNotFoundError` if `id` does not exist, `StorePersistenceError` when the write cannot be persisted. */
755
+ updateFeedback(id: string, data: FeedbackUpdateInput): Promise<FeedbackRecord>;
756
+ /** Delete a single record. Throws `StoreNotFoundError` if `id` does not exist, `StorePersistenceError` when the write cannot be persisted. */
757
+ deleteFeedback(id: string): Promise<void>;
758
+ /** Bulk delete all feedbacks for a project. No-op (not error) if none exist. Throws `StorePersistenceError` when the write cannot be persisted. */
759
+ deleteAllFeedbacks(projectName: string): Promise<void>;
760
+ /**
761
+ * Optional — return `true` when the record with `id` belongs to
762
+ * `projectName`, `false` otherwise (including when it does not exist).
763
+ *
764
+ * HTTP handlers use this to reject cross-project PATCH/DELETE requests.
765
+ * Implement it whenever your store serves multiple projects. When absent,
766
+ * handlers rely on `id` alone — so `createSitepingHandler` refuses to start
767
+ * with a custom `access.authorize` (which may scope callers to projects)
768
+ * over a store that lacks it.
769
+ */
770
+ verifyProjectOwnership?(id: string, projectName: string): Promise<boolean>;
771
+ /**
772
+ * Optional — `createFeedback` that reports whether this call inserted the
773
+ * record (`created: true`) or found an existing one with the same
774
+ * `clientId` (`created: false`). The dedup check and the insert must be
775
+ * atomic, like `createFeedback`'s: of N concurrent calls with the same
776
+ * `clientId`, exactly one may report `created: true`, and all must return
777
+ * that same record. `createCollectionStore` guarantees this within one
778
+ * store instance by serializing its mutations; stores shared across
779
+ * processes need an atomic backend primitive (unique constraint,
780
+ * transaction, compare-and-set).
781
+ *
782
+ * HTTP handlers prefer it over `createFeedback` to fire creation side
783
+ * effects (webhooks, `onCreated`) exactly once when concurrent requests
784
+ * race on the same `clientId`. Stores whose `createFeedback` throws
785
+ * `StoreDuplicateError` on a duplicate already give that signal and may
786
+ * leave it out.
787
+ */
788
+ createFeedbackIfAbsent?(data: FeedbackCreateInput): Promise<FeedbackCreateOutcome>;
789
+ }
790
+ /** Payload sent from the widget to the server when submitting feedback. */
791
+ export interface FeedbackPayload {
792
+ projectName: string;
793
+ type: FeedbackType;
794
+ message: string;
795
+ url: string;
796
+ /**
797
+ * Parameterized URL template (e.g. `/orders/:orderId`) supplied by
798
+ * `SitepingConfig.getPageScope()`. Null when the host did not provide one.
799
+ */
800
+ urlPattern?: string | null | undefined;
801
+ viewport: string;
802
+ userAgent: string;
803
+ authorName: string;
804
+ authorEmail: string;
805
+ annotations: AnnotationPayload[];
806
+ /** Client-generated UUID for deduplication */
807
+ clientId: string;
808
+ /**
809
+ * Base64 JPEG `data:` URL of the annotated area. Captured by the widget
810
+ * when `enableScreenshot: true` is set in `SitepingConfig`. Null when
811
+ * disabled or when capture failed silently.
812
+ */
813
+ screenshotDataUrl?: string | null | undefined;
814
+ /**
815
+ * Annotation rect position within the screenshot image — see
816
+ * `ScreenshotRegion`. Null/absent when no screenshot was captured or the
817
+ * capture predates contextual framing.
818
+ */
819
+ screenshotRegion?: ScreenshotRegion | null | undefined;
820
+ /**
821
+ * Snapshot of the last few console messages and failed network requests
822
+ * captured at submit time when `captureDiagnostics` is enabled.
823
+ */
824
+ diagnostics?: DiagnosticsSnapshot | null | undefined;
825
+ }
826
+ /** Single source of truth for console diagnostic severity levels. */
827
+ export declare const CONSOLE_DIAGNOSTIC_LEVELS: readonly ["log", "info", "warn", "error"];
828
+ /** Severity levels persisted in `ConsoleDiagnosticEntry`. */
829
+ export type ConsoleDiagnosticLevel = (typeof CONSOLE_DIAGNOSTIC_LEVELS)[number];
830
+ /** A single console entry captured by `ConsoleBuffer`. */
831
+ export interface ConsoleDiagnosticEntry {
832
+ level: ConsoleDiagnosticLevel;
833
+ /** ISO 8601 timestamp captured at log time. */
834
+ timestamp: string;
835
+ /** Best-effort string representation of the original console args. */
836
+ message: string;
837
+ }
838
+ /** A single failed network request captured by `NetworkBuffer`. */
839
+ export interface NetworkDiagnosticEntry {
840
+ url: string;
841
+ method: string;
842
+ /** HTTP status; 0 when the request never reached the server. */
843
+ status: number;
844
+ /** End-to-end duration in ms. */
845
+ durationMs: number;
846
+ /** ISO 8601 timestamp at the moment the request was initiated. */
847
+ timestamp: string;
848
+ }
849
+ /**
850
+ * Diagnostics captured by the widget when `captureDiagnostics` is enabled.
851
+ *
852
+ * Both arrays are bounded (default: 50 console / 20 network). Adapters that
853
+ * support diagnostics should persist this as a JSON blob alongside the
854
+ * feedback so reviewers can replay the context that led to the report.
855
+ */
856
+ export interface DiagnosticsSnapshot {
857
+ console: ConsoleDiagnosticEntry[];
858
+ network: NetworkDiagnosticEntry[];
859
+ }
860
+ /** DOM anchoring data for re-attaching annotations to page elements. */
861
+ export interface AnchorData {
862
+ /** CSS selector generated by @medv/finder — primary anchor */
863
+ cssSelector: string;
864
+ /** XPath — fallback 1 */
865
+ xpath: string;
866
+ /** First ~120 chars of element innerText — empty string if none */
867
+ textSnippet: string;
868
+ /** Tag name for validation (e.g. "DIV", "SECTION") */
869
+ elementTag: string;
870
+ /** Element id attribute if available — most stable */
871
+ elementId?: string | undefined;
872
+ /** ~32 chars of text before this element in document flow (disambiguation) */
873
+ textPrefix: string;
874
+ /** ~32 chars of text after this element in document flow (disambiguation) */
875
+ textSuffix: string;
876
+ /** Structural fingerprint: "childCount:siblingIdx:attrHash" */
877
+ fingerprint: string;
878
+ /** Text content of adjacent sibling elements (context) */
879
+ neighborText: string;
880
+ /**
881
+ * Semantic anchor identifier from the closest ancestor's `data-feedback-anchor`
882
+ * attribute. When set, this is the highest-priority re-anchoring signal —
883
+ * hosts deliberately place these on layout/section roots that survive
884
+ * viewport changes and DOM refactors.
885
+ */
886
+ anchorKey?: string | null | undefined;
887
+ }
888
+ /**
889
+ * Where the client's annotation rect sits within the captured screenshot,
890
+ * as fractions [0, 1] of the image dimensions. The widget captures context
891
+ * around the drawn rect and records the rect's position here so dashboards
892
+ * can re-render the annotation on top of the image. Survives downscaling
893
+ * (fractions are resolution-independent).
894
+ */
895
+ export interface ScreenshotRegion {
896
+ /** X offset of the rect as fraction of image width — [0, 1] */
897
+ xPct: number;
898
+ /** Y offset of the rect as fraction of image height — [0, 1] */
899
+ yPct: number;
900
+ /** Rect width as fraction of image width — [0, 1] */
901
+ wPct: number;
902
+ /** Rect height as fraction of image height — [0, 1] */
903
+ hPct: number;
904
+ }
905
+ /** Drawn rectangle coordinates as percentages relative to the anchor element. */
906
+ export interface RectData {
907
+ /** X offset as fraction of anchor element width — must be in range [0, 1] */
908
+ xPct: number;
909
+ /** Y offset as fraction of anchor element height — must be in range [0, 1] */
910
+ yPct: number;
911
+ /** Width as fraction of anchor element width — must be in range [0, 1] */
912
+ wPct: number;
913
+ /** Height as fraction of anchor element height — must be in range [0, 1] */
914
+ hPct: number;
915
+ }
916
+ /** Annotation data sent as part of a feedback submission. */
917
+ export interface AnnotationPayload {
918
+ anchor: AnchorData;
919
+ rect: RectData;
920
+ scrollX: number;
921
+ scrollY: number;
922
+ viewportW: number;
923
+ viewportH: number;
924
+ devicePixelRatio: number;
925
+ }
926
+ /**
927
+ * Feedback record as returned by the API — derived from
928
+ * {@link FeedbackRecord}: dates are serialized to ISO strings and `clientId`
929
+ * is omitted (server-side dedup concern, never exposed on the wire). Adding
930
+ * a field to `FeedbackRecord` updates this type automatically.
931
+ *
932
+ * Note: `authorEmail` may be an empty string — HTTP adapters redact it for
933
+ * unauthenticated requests; the full value requires a Bearer-authenticated
934
+ * request.
935
+ */
936
+ export type FeedbackResponse = Prettify<Serialized<Omit<FeedbackRecord, "clientId">>>;
937
+ /**
938
+ * Annotation record as returned by the API — {@link AnnotationRecord} with
939
+ * `createdAt` serialized to an ISO string.
940
+ */
941
+ export type AnnotationResponse = Prettify<Serialized<AnnotationRecord>>;
942
+ /** Paginated `FeedbackResponse` shape returned by the API. */
943
+ export interface FeedbackResponseList {
944
+ feedbacks: FeedbackResponse[];
945
+ total: number;
946
+ }
947
+ export {};