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