@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 ADDED
@@ -0,0 +1,32 @@
1
+ # @siteping/adapter-kit
2
+
3
+ Everything needed to build — and conformance-test — a custom [Siteping](https://siteping.dev) store adapter.
4
+
5
+ ```ts
6
+ import { createCollectionStore, type SitepingStore } from "@siteping/adapter-kit";
7
+
8
+ // A complete adapter over any snapshot backend, in ~15 lines:
9
+ export function createMyStore(): SitepingStore {
10
+ let records = load();
11
+ return createCollectionStore({
12
+ load: () => records,
13
+ persist: (next) => save((records = next)),
14
+ generateId: () => crypto.randomUUID(),
15
+ });
16
+ }
17
+ ```
18
+
19
+ Verify it with the shared conformance suite (vitest):
20
+
21
+ ```ts
22
+ import { testSitepingStore } from "@siteping/adapter-kit/testing";
23
+ import { createMyStore } from "../src/index.js";
24
+
25
+ testSitepingStore(() => createMyStore());
26
+ ```
27
+
28
+ **[Full guide → siteping.dev/docs/adapters/writing-an-adapter](https://siteping.dev/docs/adapters/writing-an-adapter)**
29
+
30
+ ## License
31
+
32
+ MIT
@@ -0,0 +1,97 @@
1
+ // ../core/src/type-utils.ts
2
+ function isRecord(value) {
3
+ return typeof value === "object" && value !== null;
4
+ }
5
+ function hasOwn(value, key) {
6
+ return isRecord(value) && key in value;
7
+ }
8
+
9
+ // ../core/src/types.ts
10
+ var FEEDBACK_TYPES = ["question", "change", "bug", "other"];
11
+ var FEEDBACK_STATUSES = ["open", "in_progress", "resolved", "wont_fix"];
12
+ var CLOSED_FEEDBACK_STATUSES = ["resolved", "wont_fix"];
13
+ var OPEN_FEEDBACK_STATUSES = ["open", "in_progress"];
14
+ function isClosedStatus(status) {
15
+ return CLOSED_FEEDBACK_STATUSES.includes(status);
16
+ }
17
+ function toFeedbackUpdate(status, closedAt = /* @__PURE__ */ new Date()) {
18
+ return isClosedStatus(status) ? { status, resolvedAt: closedAt } : { status, resolvedAt: null };
19
+ }
20
+ var StoreNotFoundError = class extends Error {
21
+ code = "STORE_NOT_FOUND";
22
+ constructor(message = "Record not found") {
23
+ super(message);
24
+ this.name = "StoreNotFoundError";
25
+ }
26
+ };
27
+ var StoreDuplicateError = class extends Error {
28
+ code = "STORE_DUPLICATE";
29
+ constructor(message = "Duplicate record") {
30
+ super(message);
31
+ this.name = "StoreDuplicateError";
32
+ }
33
+ };
34
+ var StorePersistenceError = class extends Error {
35
+ code = "STORE_PERSISTENCE";
36
+ constructor(message = "Failed to persist store mutation", options) {
37
+ super(message, options);
38
+ this.name = "StorePersistenceError";
39
+ }
40
+ };
41
+ function hasErrorCode(error, code) {
42
+ return hasOwn(error, "code") && error.code === code;
43
+ }
44
+ function isStoreNotFound(error) {
45
+ if (error instanceof StoreNotFoundError) return true;
46
+ return hasErrorCode(error, "P2025");
47
+ }
48
+ function isStoreDuplicate(error) {
49
+ if (error instanceof StoreDuplicateError) return true;
50
+ return hasErrorCode(error, "P2002");
51
+ }
52
+ function isStorePersistence(error) {
53
+ if (error instanceof StorePersistenceError) return true;
54
+ return hasErrorCode(error, "STORE_PERSISTENCE");
55
+ }
56
+ function flattenAnnotation(ann) {
57
+ return {
58
+ cssSelector: ann.anchor.cssSelector,
59
+ xpath: ann.anchor.xpath,
60
+ textSnippet: ann.anchor.textSnippet,
61
+ elementTag: ann.anchor.elementTag,
62
+ elementId: ann.anchor.elementId,
63
+ textPrefix: ann.anchor.textPrefix,
64
+ textSuffix: ann.anchor.textSuffix,
65
+ fingerprint: ann.anchor.fingerprint,
66
+ neighborText: ann.anchor.neighborText,
67
+ anchorKey: ann.anchor.anchorKey ?? null,
68
+ xPct: ann.rect.xPct,
69
+ yPct: ann.rect.yPct,
70
+ wPct: ann.rect.wPct,
71
+ hPct: ann.rect.hPct,
72
+ scrollX: ann.scrollX,
73
+ scrollY: ann.scrollY,
74
+ viewportW: ann.viewportW,
75
+ viewportH: ann.viewportH,
76
+ devicePixelRatio: ann.devicePixelRatio
77
+ };
78
+ }
79
+ var CONSOLE_DIAGNOSTIC_LEVELS = ["log", "info", "warn", "error"];
80
+
81
+ export {
82
+ FEEDBACK_TYPES,
83
+ FEEDBACK_STATUSES,
84
+ CLOSED_FEEDBACK_STATUSES,
85
+ OPEN_FEEDBACK_STATUSES,
86
+ isClosedStatus,
87
+ toFeedbackUpdate,
88
+ StoreNotFoundError,
89
+ StoreDuplicateError,
90
+ StorePersistenceError,
91
+ isStoreNotFound,
92
+ isStoreDuplicate,
93
+ isStorePersistence,
94
+ flattenAnnotation,
95
+ CONSOLE_DIAGNOSTIC_LEVELS
96
+ };
97
+ //# sourceMappingURL=chunk-YQHAD24P.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../core/src/type-utils.ts","../../core/src/types.ts"],"sourcesContent":["/**\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"],"mappings":";AAyDO,SAAS,SAAS,OAAuD;AAC9E,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAWO,SAAS,OAA8B,OAAgB,KAAqC;AACjG,SAAO,SAAS,KAAK,KAAK,OAAO;AACnC;;;ACoUO,IAAM,iBAAiB,CAAC,YAAY,UAAU,OAAO,OAAO;AAI5D,IAAM,oBAAoB,CAAC,QAAQ,eAAe,YAAY,UAAU;AASxE,IAAM,2BAA2B,CAAC,YAAY,UAAU;AAKxD,IAAM,yBAAyB,CAAC,QAAQ,aAAa;AAUrD,SAAS,eAAe,QAAwD;AACrF,SAAQ,yBAAuD,SAAS,MAAM;AAChF;AA8IO,SAAS,iBAAiB,QAAwB,WAAiB,oBAAI,KAAK,GAAwB;AACzG,SAAO,eAAe,MAAM,IAAI,EAAE,QAAQ,YAAY,SAAS,IAAI,EAAE,QAAQ,YAAY,KAAK;AAChG;AAmFO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EACnC,OAAO;AAAA,EAChB,YAAY,UAAU,oBAAoB;AACxC,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAOO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EACpC,OAAO;AAAA,EAChB,YAAY,UAAU,oBAAoB;AACxC,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAQO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EACtC,OAAO;AAAA,EAChB,YAAY,UAAU,oCAAoC,SAAwB;AAChF,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AAKA,SAAS,aAA+B,OAAgB,MAAiC;AACvF,SAAO,OAAO,OAAO,MAAM,KAAK,MAAM,SAAS;AACjD;AAGO,SAAS,gBAAgB,OAAmE;AACjG,MAAI,iBAAiB,mBAAoB,QAAO;AAEhD,SAAO,aAAa,OAAO,OAAO;AACpC;AAGO,SAAS,iBAAiB,OAAoE;AACnG,MAAI,iBAAiB,oBAAqB,QAAO;AAEjD,SAAO,aAAa,OAAO,OAAO;AACpC;AAQO,SAAS,mBAAmB,OAAkF;AACnH,MAAI,iBAAiB,sBAAuB,QAAO;AACnD,SAAO,aAAa,OAAO,mBAAmB;AAChD;AAOO,SAAS,kBAAkB,KAA+C;AAC/E,SAAO;AAAA,IACL,aAAa,IAAI,OAAO;AAAA,IACxB,OAAO,IAAI,OAAO;AAAA,IAClB,aAAa,IAAI,OAAO;AAAA,IACxB,YAAY,IAAI,OAAO;AAAA,IACvB,WAAW,IAAI,OAAO;AAAA,IACtB,YAAY,IAAI,OAAO;AAAA,IACvB,YAAY,IAAI,OAAO;AAAA,IACvB,aAAa,IAAI,OAAO;AAAA,IACxB,cAAc,IAAI,OAAO;AAAA,IACzB,WAAW,IAAI,OAAO,aAAa;AAAA,IACnC,MAAM,IAAI,KAAK;AAAA,IACf,MAAM,IAAI,KAAK;AAAA,IACf,MAAM,IAAI,KAAK;AAAA,IACf,MAAM,IAAI,KAAK;AAAA,IACf,SAAS,IAAI;AAAA,IACb,SAAS,IAAI;AAAA,IACb,WAAW,IAAI;AAAA,IACf,WAAW,IAAI;AAAA,IACf,kBAAkB,IAAI;AAAA,EACxB;AACF;AA6FO,IAAM,4BAA4B,CAAC,OAAO,QAAQ,QAAQ,OAAO;","names":[]}
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Typed error hierarchy for Siteping client/server boundaries.
3
+ *
4
+ * Consumers can `instanceof`-check or read `code` / `retryable` instead of
5
+ * pattern-matching error messages. Designed to be additive on top of the
6
+ * existing store errors (`StoreNotFoundError`, `StoreDuplicateError`) which
7
+ * remain the canonical signals for server-side store implementations.
8
+ *
9
+ * Usage on the widget side (api-client.ts):
10
+ * - fetch failures / aborts / timeouts → `SitepingNetworkError` (retryable)
11
+ * - HTTP 4xx (except 401/403) → `SitepingValidationError` (not retryable)
12
+ * - HTTP 401 / 403 → `SitepingAuthError` (not retryable)
13
+ * - everything else → `SitepingError` generic
14
+ *
15
+ * `retryable` is meta information surfaced to host apps that want to wire
16
+ * their own retry/queue/backoff strategy — the widget already retries
17
+ * network failures via its built-in retry queue.
18
+ */
19
+ /**
20
+ * Discriminant string carried by every `SitepingError`. Subclasses pin a
21
+ * literal value; the base class accepts a wider string so userland can
22
+ * extend the hierarchy without colliding with built-ins.
23
+ */
24
+ export type SitepingErrorCode = "NETWORK" | "VALIDATION" | "AUTH" | "SERVER" | (string & {});
25
+ export declare class SitepingError<TCode extends SitepingErrorCode = SitepingErrorCode> extends Error {
26
+ readonly code: TCode;
27
+ readonly retryable: boolean;
28
+ constructor(message: string, code: TCode, retryable: boolean);
29
+ }
30
+ /** Network-level failure: connection refused, DNS, CORS, timeout, abort. Retryable. */
31
+ export declare class SitepingNetworkError extends SitepingError<"NETWORK"> {
32
+ constructor(message: string);
33
+ }
34
+ /** Server rejected the request (4xx, not auth). Validation problem on the client side. */
35
+ export declare class SitepingValidationError extends SitepingError<"VALIDATION"> {
36
+ constructor(message: string);
37
+ }
38
+ /** Server rejected auth (401 or 403). Not retryable without fresh credentials. */
39
+ export declare class SitepingAuthError extends SitepingError<"AUTH"> {
40
+ constructor(message: string);
41
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Typed error hierarchy for Siteping client/server boundaries.
3
+ *
4
+ * Consumers can `instanceof`-check or read `code` / `retryable` instead of
5
+ * pattern-matching error messages. Designed to be additive on top of the
6
+ * existing store errors (`StoreNotFoundError`, `StoreDuplicateError`) which
7
+ * remain the canonical signals for server-side store implementations.
8
+ *
9
+ * Usage on the widget side (api-client.ts):
10
+ * - fetch failures / aborts / timeouts → `SitepingNetworkError` (retryable)
11
+ * - HTTP 4xx (except 401/403) → `SitepingValidationError` (not retryable)
12
+ * - HTTP 401 / 403 → `SitepingAuthError` (not retryable)
13
+ * - everything else → `SitepingError` generic
14
+ *
15
+ * `retryable` is meta information surfaced to host apps that want to wire
16
+ * their own retry/queue/backoff strategy — the widget already retries
17
+ * network failures via its built-in retry queue.
18
+ */
19
+ /**
20
+ * Discriminant string carried by every `SitepingError`. Subclasses pin a
21
+ * literal value; the base class accepts a wider string so userland can
22
+ * extend the hierarchy without colliding with built-ins.
23
+ */
24
+ export type SitepingErrorCode = "NETWORK" | "VALIDATION" | "AUTH" | "SERVER" | (string & {});
25
+ export declare class SitepingError<TCode extends SitepingErrorCode = SitepingErrorCode> extends Error {
26
+ readonly code: TCode;
27
+ readonly retryable: boolean;
28
+ constructor(message: string, code: TCode, retryable: boolean);
29
+ }
30
+ /** Network-level failure: connection refused, DNS, CORS, timeout, abort. Retryable. */
31
+ export declare class SitepingNetworkError extends SitepingError<"NETWORK"> {
32
+ constructor(message: string);
33
+ }
34
+ /** Server rejected the request (4xx, not auth). Validation problem on the client side. */
35
+ export declare class SitepingValidationError extends SitepingError<"VALIDATION"> {
36
+ constructor(message: string);
37
+ }
38
+ /** Server rejected auth (401 or 403). Not retryable without fresh credentials. */
39
+ export declare class SitepingAuthError extends SitepingError<"AUTH"> {
40
+ constructor(message: string);
41
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Shared feedback-record filtering and pagination — extracted from
3
+ * `adapter-memory` and `adapter-localstorage` which previously kept two
4
+ * near-identical copies of the same logic. Any adapter that holds an
5
+ * in-memory snapshot of feedbacks can use it.
6
+ *
7
+ * Filtering order matches the historical adapter behaviour:
8
+ * 1. projectName (always required)
9
+ * 2. type
10
+ * 3. status / statuses (`statuses` bucket wins when both are set)
11
+ * 4. url
12
+ * 5. urlPattern
13
+ * 6. search (lowercase substring match on `message`)
14
+ *
15
+ * Pagination clamps `limit` to a maximum of 100 and treats `page` as 1-based,
16
+ * matching the public API contract documented on `getFeedbacks`. A page or
17
+ * limit below 1 is clamped up to 1 rather than indexing backwards from the
18
+ * end of the match set.
19
+ */
20
+ import type { FeedbackQuery, FeedbackRecord } from "./types.cjs";
21
+ export interface FilterResult {
22
+ feedbacks: FeedbackRecord[];
23
+ total: number;
24
+ }
25
+ /**
26
+ * Apply the standard feedback filter + pagination pipeline against an
27
+ * in-memory snapshot. Used by `MemoryStore.getFeedbacks` and
28
+ * `LocalStorageStore.getFeedbacks` so the two never drift.
29
+ *
30
+ * @param items All known feedback records (already include `annotations`).
31
+ * @param query Filter and pagination options. `projectName` is required.
32
+ */
33
+ export declare function applyFeedbackFilters(items: readonly FeedbackRecord[], query: FeedbackQuery): FilterResult;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Shared feedback-record filtering and pagination — extracted from
3
+ * `adapter-memory` and `adapter-localstorage` which previously kept two
4
+ * near-identical copies of the same logic. Any adapter that holds an
5
+ * in-memory snapshot of feedbacks can use it.
6
+ *
7
+ * Filtering order matches the historical adapter behaviour:
8
+ * 1. projectName (always required)
9
+ * 2. type
10
+ * 3. status / statuses (`statuses` bucket wins when both are set)
11
+ * 4. url
12
+ * 5. urlPattern
13
+ * 6. search (lowercase substring match on `message`)
14
+ *
15
+ * Pagination clamps `limit` to a maximum of 100 and treats `page` as 1-based,
16
+ * matching the public API contract documented on `getFeedbacks`. A page or
17
+ * limit below 1 is clamped up to 1 rather than indexing backwards from the
18
+ * end of the match set.
19
+ */
20
+ import type { FeedbackQuery, FeedbackRecord } from "./types.js";
21
+ export interface FilterResult {
22
+ feedbacks: FeedbackRecord[];
23
+ total: number;
24
+ }
25
+ /**
26
+ * Apply the standard feedback filter + pagination pipeline against an
27
+ * in-memory snapshot. Used by `MemoryStore.getFeedbacks` and
28
+ * `LocalStorageStore.getFeedbacks` so the two never drift.
29
+ *
30
+ * @param items All known feedback records (already include `annotations`).
31
+ * @param query Filter and pagination options. `projectName` is required.
32
+ */
33
+ export declare function applyFeedbackFilters(items: readonly FeedbackRecord[], query: FeedbackQuery): FilterResult;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Generic i18n machinery shared by the widget and the dashboard.
3
+ *
4
+ * Each package owns its `Translations` interface (their key sets differ) and
5
+ * its locale dictionaries; everything else — locale normalization, the
6
+ * custom-locale registry, lazy loading of built-ins, the translate-function
7
+ * factory, interpolation — is identical and lives here once.
8
+ *
9
+ * The `loaders` map is typed `Record<Exclude<BuiltinLocale, "en">, …>`: the
10
+ * moment a locale code is added to {@link BUILTIN_LOCALES}, every consuming
11
+ * package fails to compile until its loader entry (and therefore its
12
+ * dictionary file) exists. Adding a locale cannot silently fall back to
13
+ * English anymore.
14
+ */
15
+ import { type BuiltinLocale } from "./types.cjs";
16
+ /**
17
+ * Lazy dictionary loaders for every non-English built-in locale. Use static
18
+ * `() => import("./xx.cjs").then((m) => m.xx)` thunks — bundlers keep
19
+ * emitting one chunk per locale, and only the requested one ships.
20
+ */
21
+ export type LocaleLoaders<T> = Record<Exclude<BuiltinLocale, "en">, () => Promise<T>>;
22
+ /** Translate function over the message catalog `T`. */
23
+ export type TranslateFunction<T> = (key: keyof T & string) => string;
24
+ /** The i18n API returned by {@link createI18n}. */
25
+ export interface I18n<T> {
26
+ /**
27
+ * Create a translation function for the given locale.
28
+ *
29
+ * Locale resolution: exact language match > English fallback, per key.
30
+ * Non-English built-in locales are lazy-loaded via `loadLocale` — call
31
+ * `await loadLocale(locale)` at init if you want the UI to render in the
32
+ * target language immediately; until the dictionary lands, keys resolve
33
+ * to English.
34
+ */
35
+ createT(locale: string): TranslateFunction<T>;
36
+ /**
37
+ * Dynamically import a built-in locale and register it. Returns the
38
+ * loaded dictionary, or `null` if the locale isn't a known built-in.
39
+ * Custom locales registered via `registerLocale` bypass this loader —
40
+ * they are already in the registry (and are returned as registered, so a
41
+ * partial custom dictionary comes back partial).
42
+ */
43
+ loadLocale(locale: string): Promise<Partial<T> | null>;
44
+ /**
45
+ * Register a custom locale at runtime. Partial dictionaries are welcome —
46
+ * missing keys fall back to English per key, so overriding a single
47
+ * string never requires copying the whole catalog.
48
+ */
49
+ registerLocale(code: string, translations: Partial<T>): void;
50
+ }
51
+ /**
52
+ * Build the i18n machinery for one message catalog.
53
+ *
54
+ * @param en — the complete English catalog, bundled synchronously as the fallback.
55
+ * @param loaders — lazy import thunks for every other built-in locale.
56
+ */
57
+ export declare function createI18n<T extends Record<keyof T & string, string>>(en: T, loaders: LocaleLoaders<T>): I18n<T>;
58
+ /**
59
+ * Interpolate `{paramName}` placeholders in a translated string with the
60
+ * values from `params`. Stringifies numbers and booleans inline so callers
61
+ * can pass `t("marker.count")` along with `{ count: 3 }` directly.
62
+ *
63
+ * Unknown placeholders are left as-is.
64
+ */
65
+ export declare function interpolate(template: string, params: Readonly<Record<string, string | number | boolean>>): string;
66
+ /** Shorthand for `interpolate(t(key), params)` — key-checked against the catalog. */
67
+ export declare function tWithParams<K extends string>(t: (key: K) => string, key: K, params: Readonly<Record<string, string | number | boolean>>): string;
package/dist/i18n.d.ts ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Generic i18n machinery shared by the widget and the dashboard.
3
+ *
4
+ * Each package owns its `Translations` interface (their key sets differ) and
5
+ * its locale dictionaries; everything else — locale normalization, the
6
+ * custom-locale registry, lazy loading of built-ins, the translate-function
7
+ * factory, interpolation — is identical and lives here once.
8
+ *
9
+ * The `loaders` map is typed `Record<Exclude<BuiltinLocale, "en">, …>`: the
10
+ * moment a locale code is added to {@link BUILTIN_LOCALES}, every consuming
11
+ * package fails to compile until its loader entry (and therefore its
12
+ * dictionary file) exists. Adding a locale cannot silently fall back to
13
+ * English anymore.
14
+ */
15
+ import { type BuiltinLocale } from "./types.js";
16
+ /**
17
+ * Lazy dictionary loaders for every non-English built-in locale. Use static
18
+ * `() => import("./xx.js").then((m) => m.xx)` thunks — bundlers keep
19
+ * emitting one chunk per locale, and only the requested one ships.
20
+ */
21
+ export type LocaleLoaders<T> = Record<Exclude<BuiltinLocale, "en">, () => Promise<T>>;
22
+ /** Translate function over the message catalog `T`. */
23
+ export type TranslateFunction<T> = (key: keyof T & string) => string;
24
+ /** The i18n API returned by {@link createI18n}. */
25
+ export interface I18n<T> {
26
+ /**
27
+ * Create a translation function for the given locale.
28
+ *
29
+ * Locale resolution: exact language match > English fallback, per key.
30
+ * Non-English built-in locales are lazy-loaded via `loadLocale` — call
31
+ * `await loadLocale(locale)` at init if you want the UI to render in the
32
+ * target language immediately; until the dictionary lands, keys resolve
33
+ * to English.
34
+ */
35
+ createT(locale: string): TranslateFunction<T>;
36
+ /**
37
+ * Dynamically import a built-in locale and register it. Returns the
38
+ * loaded dictionary, or `null` if the locale isn't a known built-in.
39
+ * Custom locales registered via `registerLocale` bypass this loader —
40
+ * they are already in the registry (and are returned as registered, so a
41
+ * partial custom dictionary comes back partial).
42
+ */
43
+ loadLocale(locale: string): Promise<Partial<T> | null>;
44
+ /**
45
+ * Register a custom locale at runtime. Partial dictionaries are welcome —
46
+ * missing keys fall back to English per key, so overriding a single
47
+ * string never requires copying the whole catalog.
48
+ */
49
+ registerLocale(code: string, translations: Partial<T>): void;
50
+ }
51
+ /**
52
+ * Build the i18n machinery for one message catalog.
53
+ *
54
+ * @param en — the complete English catalog, bundled synchronously as the fallback.
55
+ * @param loaders — lazy import thunks for every other built-in locale.
56
+ */
57
+ export declare function createI18n<T extends Record<keyof T & string, string>>(en: T, loaders: LocaleLoaders<T>): I18n<T>;
58
+ /**
59
+ * Interpolate `{paramName}` placeholders in a translated string with the
60
+ * values from `params`. Stringifies numbers and booleans inline so callers
61
+ * can pass `t("marker.count")` along with `{ count: 3 }` directly.
62
+ *
63
+ * Unknown placeholders are left as-is.
64
+ */
65
+ export declare function interpolate(template: string, params: Readonly<Record<string, string | number | boolean>>): string;
66
+ /** Shorthand for `interpolate(t(key), params)` — key-checked against the catalog. */
67
+ export declare function tWithParams<K extends string>(t: (key: K) => string, key: K, params: Readonly<Record<string, string | number | boolean>>): string;