@guidelytech/sdk-core 0.15.0 → 0.17.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guidelytech/sdk-core",
3
- "version": "0.15.0",
3
+ "version": "0.17.0",
4
4
  "description": "Framework-independent Guidely browser SDK",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -38,18 +38,19 @@
38
38
  "@rrweb/record": "^2.1.7",
39
39
  "@rrweb/rrweb-plugin-console-record": "^2.1.7",
40
40
  "@rrweb/types": "^2.1.7",
41
- "@guidelytech/shared": "0.15.0",
42
- "@guidelytech/flags": "0.15.0",
43
- "@guidelytech/guide-runtime": "0.15.0"
41
+ "@guidelytech/shared": "0.17.0",
42
+ "@guidelytech/guide-runtime": "0.17.0",
43
+ "@guidelytech/flags": "0.17.0"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@eslint/js": "^9.39.5",
47
+ "@types/node": "^22.20.5",
47
48
  "eslint": "^9.39.5",
48
- "happy-dom": "^17.6.3",
49
+ "happy-dom": "^21.0.4",
49
50
  "tsup": "^8.5.1",
50
51
  "typescript": "^5.9.3",
51
52
  "typescript-eslint": "^8.46.0",
52
- "vitest": "^3.2.7"
53
+ "vitest": "^4.1.12"
53
54
  },
54
55
  "publishConfig": {
55
56
  "access": "public"
@@ -1,100 +0,0 @@
1
- import { CaptureStepInput } from '@guidelytech/shared';
2
- import { A as Api } from './http-Cb6KYYFv.cjs';
3
- import { K as KeyValueStore } from './health-sbP9JwTE.cjs';
4
-
5
- /** What the SDK remembers about a capture session in this tab (`guidely:capture` in sessionStorage). */
6
- interface CaptureMarker {
7
- token: string;
8
- /** Recording has started (a page load continues it instead of showing "Start recording"). */
9
- started?: boolean;
10
- /** The user chose to take screenshots. */
11
- screenshots?: boolean;
12
- /** Epoch ms and action of the last recorded step. */
13
- lastStepAt?: number;
14
- lastAction?: string;
15
- }
16
-
17
- /**
18
- * How-to capture bridge (loaded on demand): verifies the capture session, runs the runtime's
19
- * recorder toolbar, uploads steps with their screenshots in capture order and tells the dashboard
20
- * window (`window.opener`) about progress.
21
- */
22
- /** Keeps the capture session alive on the server (same cadence as authoring). */
23
- declare const CAPTURE_HEARTBEAT_MS = 15000;
24
- /** A full page load this soon after a recorded interaction was caused by it: no navigate step. */
25
- declare const LOAD_AFTER_ACTION_MS = 8000;
26
- /** How long Done waits for queued uploads before finishing anyway. */
27
- declare const FINISH_DRAIN_MS = 20000;
28
- /** Pause before retrying uploads after every attempt failed (offline, server down). */
29
- declare const UPLOAD_RETRY_LATER_MS = 10000;
30
- /** Messages the SDK posts to the dashboard window (`window.opener`, target origin `dashboardOrigin`). */
31
- type CaptureOutgoingMessage = {
32
- type: "guidely:capture-ready";
33
- sessionId: string;
34
- url: string;
35
- } | {
36
- type: "guidely:capture-step";
37
- sessionId: string;
38
- stepCount: number;
39
- } | {
40
- type: "guidely:capture-finished";
41
- sessionId: string;
42
- howToId: string;
43
- cancelled: boolean;
44
- };
45
- interface CaptureBridgeOptions {
46
- api: Api;
47
- sessionStore: KeyValueStore;
48
- marker: CaptureMarker;
49
- /** Comma-joined mask selectors (project setting + SDK option). */
50
- maskSelector: string;
51
- onError: (err: unknown) => void;
52
- onActive: (active: boolean) => void;
53
- }
54
- /** After a full page load: was it caused by the last recorded interaction (so no navigate step)? */
55
- declare function loadFollowsAction(marker: Pick<CaptureMarker, "lastAction" | "lastStepAt">, now?: number): boolean;
56
- /** Multipart body for `POST /capture/steps`: `step` (JSON) and optional `screenshot`. */
57
- declare function captureStepForm(step: CaptureStepInput, screenshot: Blob | null): FormData;
58
- declare class CaptureBridge {
59
- private readonly opts;
60
- private info;
61
- private session;
62
- private heartbeat;
63
- private retryTimer;
64
- private queue;
65
- private pumping;
66
- private active;
67
- private finishing;
68
- private marker;
69
- private readonly onPageHide;
70
- constructor(opts: CaptureBridgeOptions);
71
- isActive(): boolean;
72
- private get token();
73
- /** Verifies the session and starts recording. Resolves once the toolbar is up (or the session was rejected). */
74
- start(): Promise<void>;
75
- private reject;
76
- private saveMarker;
77
- private clearMarker;
78
- /** Persists the steps still to upload (JSON only; screenshots are added on page hide). */
79
- private savePending;
80
- /** The page is unloading with uploads in flight: keep their screenshots for the next page. */
81
- private saveForReload;
82
- private enqueue;
83
- /** Uploads queued steps one at a time, in capture order. */
84
- private pump;
85
- private upload;
86
- private beat;
87
- /** Done (waits for queued uploads) or Cancel (drops them); either way the dashboard is told. */
88
- private finish;
89
- private post;
90
- private teardown;
91
- /** Removes the toolbar and stops uploading but keeps the session marker (the SDK was destroyed; a new client resumes). */
92
- destroy(): void;
93
- }
94
- /** What the on-demand capture chunk provides (`window.__guidelyCapture` in the script-tag build). */
95
- interface CaptureApi {
96
- createBridge(options: CaptureBridgeOptions): CaptureBridge;
97
- }
98
- declare const capture: CaptureApi;
99
-
100
- export { type CaptureMarker as C, FINISH_DRAIN_MS as F, LOAD_AFTER_ACTION_MS as L, UPLOAD_RETRY_LATER_MS as U, type CaptureOutgoingMessage as a, CAPTURE_HEARTBEAT_MS as b, type CaptureApi as c, CaptureBridge as d, type CaptureBridgeOptions as e, capture as f, captureStepForm as g, loadFollowsAction as l };
@@ -1,100 +0,0 @@
1
- import { CaptureStepInput } from '@guidelytech/shared';
2
- import { A as Api } from './http-D047Ngxk.js';
3
- import { K as KeyValueStore } from './health-sbP9JwTE.js';
4
-
5
- /** What the SDK remembers about a capture session in this tab (`guidely:capture` in sessionStorage). */
6
- interface CaptureMarker {
7
- token: string;
8
- /** Recording has started (a page load continues it instead of showing "Start recording"). */
9
- started?: boolean;
10
- /** The user chose to take screenshots. */
11
- screenshots?: boolean;
12
- /** Epoch ms and action of the last recorded step. */
13
- lastStepAt?: number;
14
- lastAction?: string;
15
- }
16
-
17
- /**
18
- * How-to capture bridge (loaded on demand): verifies the capture session, runs the runtime's
19
- * recorder toolbar, uploads steps with their screenshots in capture order and tells the dashboard
20
- * window (`window.opener`) about progress.
21
- */
22
- /** Keeps the capture session alive on the server (same cadence as authoring). */
23
- declare const CAPTURE_HEARTBEAT_MS = 15000;
24
- /** A full page load this soon after a recorded interaction was caused by it: no navigate step. */
25
- declare const LOAD_AFTER_ACTION_MS = 8000;
26
- /** How long Done waits for queued uploads before finishing anyway. */
27
- declare const FINISH_DRAIN_MS = 20000;
28
- /** Pause before retrying uploads after every attempt failed (offline, server down). */
29
- declare const UPLOAD_RETRY_LATER_MS = 10000;
30
- /** Messages the SDK posts to the dashboard window (`window.opener`, target origin `dashboardOrigin`). */
31
- type CaptureOutgoingMessage = {
32
- type: "guidely:capture-ready";
33
- sessionId: string;
34
- url: string;
35
- } | {
36
- type: "guidely:capture-step";
37
- sessionId: string;
38
- stepCount: number;
39
- } | {
40
- type: "guidely:capture-finished";
41
- sessionId: string;
42
- howToId: string;
43
- cancelled: boolean;
44
- };
45
- interface CaptureBridgeOptions {
46
- api: Api;
47
- sessionStore: KeyValueStore;
48
- marker: CaptureMarker;
49
- /** Comma-joined mask selectors (project setting + SDK option). */
50
- maskSelector: string;
51
- onError: (err: unknown) => void;
52
- onActive: (active: boolean) => void;
53
- }
54
- /** After a full page load: was it caused by the last recorded interaction (so no navigate step)? */
55
- declare function loadFollowsAction(marker: Pick<CaptureMarker, "lastAction" | "lastStepAt">, now?: number): boolean;
56
- /** Multipart body for `POST /capture/steps`: `step` (JSON) and optional `screenshot`. */
57
- declare function captureStepForm(step: CaptureStepInput, screenshot: Blob | null): FormData;
58
- declare class CaptureBridge {
59
- private readonly opts;
60
- private info;
61
- private session;
62
- private heartbeat;
63
- private retryTimer;
64
- private queue;
65
- private pumping;
66
- private active;
67
- private finishing;
68
- private marker;
69
- private readonly onPageHide;
70
- constructor(opts: CaptureBridgeOptions);
71
- isActive(): boolean;
72
- private get token();
73
- /** Verifies the session and starts recording. Resolves once the toolbar is up (or the session was rejected). */
74
- start(): Promise<void>;
75
- private reject;
76
- private saveMarker;
77
- private clearMarker;
78
- /** Persists the steps still to upload (JSON only; screenshots are added on page hide). */
79
- private savePending;
80
- /** The page is unloading with uploads in flight: keep their screenshots for the next page. */
81
- private saveForReload;
82
- private enqueue;
83
- /** Uploads queued steps one at a time, in capture order. */
84
- private pump;
85
- private upload;
86
- private beat;
87
- /** Done (waits for queued uploads) or Cancel (drops them); either way the dashboard is told. */
88
- private finish;
89
- private post;
90
- private teardown;
91
- /** Removes the toolbar and stops uploading but keeps the session marker (the SDK was destroyed; a new client resumes). */
92
- destroy(): void;
93
- }
94
- /** What the on-demand capture chunk provides (`window.__guidelyCapture` in the script-tag build). */
95
- interface CaptureApi {
96
- createBridge(options: CaptureBridgeOptions): CaptureBridge;
97
- }
98
- declare const capture: CaptureApi;
99
-
100
- export { type CaptureMarker as C, FINISH_DRAIN_MS as F, LOAD_AFTER_ACTION_MS as L, UPLOAD_RETRY_LATER_MS as U, type CaptureOutgoingMessage as a, CAPTURE_HEARTBEAT_MS as b, type CaptureApi as c, CaptureBridge as d, type CaptureBridgeOptions as e, capture as f, captureStepForm as g, loadFollowsAction as l };
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/queue.ts","../src/outbox.ts","../src/emitter.ts","../src/frequency.ts"],"sourcesContent":["import type { SdkEvent } from \"@guidelytech/shared\";\nimport type { ServerHealth } from \"./health\";\nimport { backoffMs } from \"./http\";\nimport { readJson, writeJson, type KeyValueStore } from \"./storage\";\n\nexport interface EventQueueOptions {\n store: KeyValueStore;\n storageKey: string;\n /** Sends one batch. Resolve `{ ok: true }` on success, `{ ok: false, retry }` otherwise. */\n send: (events: SdkEvent[]) => Promise<{ ok: boolean; retry?: boolean }>;\n /** Synchronous best-effort send used on page hide. */\n beacon?: (events: SdkEvent[]) => boolean;\n /** Should events be flushed right now? (analytics enabled + consent granted). */\n enabled: () => boolean;\n /** API reachability: sends wait while its circuit is open, and beaconed events are only forgotten while it is reachable. */\n health?: ServerHealth;\n flushIntervalMs?: number;\n maxQueue?: number;\n batchSize?: number;\n maxAttempts?: number;\n onError?: (err: unknown) => void;\n}\n\n/**\n * Bounded, persisted event queue. Batches ≤50 events every 2s (or on demand), dedupes by\n * `eventId`, and keeps failed events (also across page loads) until the server takes them:\n * retries back off 1s→60s, wait while the API's circuit is open, and start again as soon as it\n * recovers. Drops the oldest events once the queue exceeds 500.\n */\nexport class EventQueue {\n private events: SdkEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private retryTimer: ReturnType<typeof setTimeout> | null = null;\n private inflight = false;\n private inflightIds = new Set<string>();\n private attempt = 0;\n private destroyed = false;\n private offRecover: (() => void) | null = null;\n private readonly flushIntervalMs: number;\n private readonly maxQueue: number;\n private readonly batchSize: number;\n private readonly maxAttempts: number;\n\n constructor(private readonly opts: EventQueueOptions) {\n this.flushIntervalMs = opts.flushIntervalMs ?? 2000;\n this.maxQueue = opts.maxQueue ?? 500;\n this.batchSize = opts.batchSize ?? 50;\n this.maxAttempts = opts.maxAttempts ?? 5;\n const persisted = readJson<SdkEvent[]>(opts.store, opts.storageKey, []);\n if (Array.isArray(persisted)) this.events = persisted.filter((e) => e && typeof e.eventId === \"string\").slice(-this.maxQueue);\n // Events left over from a previous page load are flushed on the next tick.\n if (this.events.length) this.schedule();\n this.offRecover = opts.health?.onRecover(() => this.retryNow()) ?? null;\n }\n\n /** The API is back: drop any pending backoff and send what is queued. */\n private retryNow(): void {\n if (this.destroyed) return;\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.retryTimer = null;\n this.attempt = 0;\n void this.flush();\n }\n\n private retryIn(ms: number): void {\n if (this.retryTimer || this.destroyed) return;\n this.retryTimer = setTimeout(() => {\n this.retryTimer = null;\n void this.flush();\n }, ms);\n }\n\n get size(): number {\n return this.events.length;\n }\n\n /** Pending events (read-only copy, for debugging). */\n peek(): SdkEvent[] {\n return this.events.slice();\n }\n\n enqueue(event: SdkEvent): void {\n if (this.destroyed) return;\n if (this.events.some((e) => e.eventId === event.eventId)) return;\n this.events.push(event);\n if (this.events.length > this.maxQueue) this.events.splice(0, this.events.length - this.maxQueue);\n this.persist();\n this.schedule();\n }\n\n private persist(): void {\n writeJson(this.opts.store, this.opts.storageKey, this.events);\n }\n\n private schedule(): void {\n if (this.timer || this.retryTimer || this.destroyed) return;\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.flush();\n }, this.flushIntervalMs);\n }\n\n /** Sends queued events now (one batch at a time). Safe to call at any time. */\n async flush(): Promise<void> {\n if (this.destroyed || this.inflight || !this.events.length || !this.opts.enabled()) return;\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n const wait = this.opts.health?.waitMs() ?? 0;\n if (wait > 0) return this.retryIn(wait);\n this.inflight = true;\n const batch = this.events.slice(0, this.batchSize);\n this.inflightIds = new Set(batch.map((e) => e.eventId));\n let ok = false;\n let retry = true;\n try {\n const res = await this.opts.send(batch);\n ok = res.ok;\n retry = res.retry ?? !res.ok;\n } catch (err) {\n this.opts.onError?.(err);\n }\n this.inflight = false;\n this.inflightIds.clear();\n if (this.destroyed) return;\n if (ok || !retry) {\n const ids = new Set(batch.map((e) => e.eventId));\n this.events = this.events.filter((e) => !ids.has(e.eventId));\n this.attempt = 0;\n this.persist();\n if (this.events.length) this.schedule();\n return;\n }\n // Fast retries first, then about once a minute until the server takes the events (or the\n // API's circuit says to wait longer); a recovery or the next page load sends them sooner.\n this.attempt = Math.min(this.attempt + 1, this.maxAttempts);\n const delay = this.attempt >= this.maxAttempts ? 60_000 : backoffMs(this.attempt - 1);\n this.retryIn(Math.max(delay, this.opts.health?.waitMs() ?? 0));\n }\n\n /** Best-effort synchronous flush on unload using `sendBeacon`. */\n flushSync(): void {\n if (this.destroyed || !this.opts.enabled() || !this.opts.beacon) return;\n // Events already in flight (fetch with keepalive) survive unload; only beacon the rest to avoid duplicate batches.\n const batch = this.events.filter((e) => !this.inflightIds.has(e.eventId)).slice(0, this.batchSize);\n if (!batch.length) return;\n // A beacon that was queued may still never arrive (the server is down), and nothing reports\n // back. Only forget its events while the API is answering; otherwise they stay persisted and the\n // next page load sends them again (the server drops events it already has, by eventId).\n if (this.opts.beacon(batch) && (this.opts.health?.reachable ?? true)) {\n const ids = new Set(batch.map((e) => e.eventId));\n this.events = this.events.filter((e) => !ids.has(e.eventId));\n }\n this.persist();\n }\n\n clear(): void {\n this.events = [];\n this.persist();\n }\n\n destroy(): void {\n this.destroyed = true;\n this.offRecover?.();\n if (this.timer) clearTimeout(this.timer);\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.timer = null;\n this.retryTimer = null;\n this.persist();\n }\n}\n","import type { ServerHealth } from \"./health\";\nimport { backoffMs, type Api } from \"./http\";\nimport { readJson, writeJson, type KeyValueStore } from \"./storage\";\n\n/** One request waiting to reach the server. */\ninterface OutboxItem {\n /** Same key → the newer request replaces the older one (e.g. a checklist's latest progress). */\n key: string;\n path: string;\n body: unknown;\n createdAt: number;\n}\n\nexport interface OutboxOptions {\n api: Api;\n store: KeyValueStore;\n storageKey: string;\n health?: ServerHealth;\n maxItems?: number;\n maxAgeMs?: number;\n onError?: (err: unknown) => void;\n}\n\n/**\n * Persisted queue for writes that must not be lost when the API is down: survey answers, guide\n * completions and checklist progress. Each request is kept (also across page loads) until the\n * server answers it; 5xx, 429 and network errors are retried with backoff, waiting while the API's\n * circuit is open. Every request is idempotent on the server (survey answers dedupe by\n * `responseId`, progress merges), so sending one twice is harmless. Bounded to 50 requests and 7 days.\n */\nexport class Outbox {\n private items: OutboxItem[];\n private sending = false;\n private attempt = 0;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private destroyed = false;\n private readonly offRecover: (() => void) | null;\n private readonly maxItems: number;\n private readonly maxAgeMs: number;\n\n constructor(private readonly opts: OutboxOptions) {\n this.maxItems = opts.maxItems ?? 50;\n this.maxAgeMs = opts.maxAgeMs ?? 7 * 24 * 60 * 60 * 1000;\n const stored = readJson<OutboxItem[]>(opts.store, opts.storageKey, []);\n const cutoff = Date.now() - this.maxAgeMs;\n this.items = Array.isArray(stored) ? stored.filter((i) => i && typeof i.path === \"string\" && typeof i.key === \"string\" && i.createdAt > cutoff).slice(-this.maxItems) : [];\n this.offRecover = opts.health?.onRecover(() => {\n this.attempt = 0;\n this.retryIn(0);\n }) ?? null;\n if (this.items.length) this.retryIn(0);\n }\n\n get size(): number {\n return this.items.length;\n }\n\n /** Queues `POST path` and sends it now (or as soon as the API is reachable). */\n add(key: string, path: string, body: unknown): void {\n if (this.destroyed) return;\n this.items = this.items.filter((i) => i.key !== key);\n this.items.push({ key, path, body, createdAt: Date.now() });\n if (this.items.length > this.maxItems) this.items.splice(0, this.items.length - this.maxItems);\n this.persist();\n void this.flush();\n }\n\n private persist(): void {\n writeJson(this.opts.store, this.opts.storageKey, this.items);\n }\n\n private retryIn(ms: number): void {\n if (this.destroyed) return;\n if (this.timer) clearTimeout(this.timer);\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.flush();\n }, ms);\n }\n\n /** Sends queued requests in order, one at a time. */\n async flush(): Promise<void> {\n if (this.destroyed || this.sending || !this.items.length) return;\n const wait = this.opts.health?.waitMs() ?? 0;\n if (wait > 0) return this.retryIn(wait);\n this.sending = true;\n try {\n while (this.items.length && !this.destroyed) {\n const item = this.items[0] as OutboxItem;\n let retry = false;\n try {\n const res = await this.opts.api.post(item.path, item.body);\n retry = !res.ok && (res.status === 429 || res.status >= 500);\n } catch (err) {\n retry = true;\n this.opts.onError?.(err);\n }\n if (retry) {\n this.attempt += 1;\n this.retryIn(Math.max(backoffMs(this.attempt - 1, 1000, 60_000), this.opts.health?.waitMs() ?? 0));\n return;\n }\n // Answered (or refused for good, e.g. the survey was deleted): done with it. A newer request\n // under the same key may have replaced it while this one was in flight; keep that one.\n this.attempt = 0;\n this.items = this.items.filter((i) => i !== item);\n this.persist();\n }\n } finally {\n this.sending = false;\n }\n }\n\n destroy(): void {\n this.destroyed = true;\n this.offRecover?.();\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n }\n}\n","type AnyFn = (...args: any[]) => void;\n\n/** Tiny typed event emitter. Listener errors are reported, never thrown into the caller. */\nexport class Emitter<Events extends { [K in keyof Events]: AnyFn }> {\n private listeners = new Map<keyof Events, Set<AnyFn>>();\n constructor(private readonly onError?: (err: unknown) => void) {}\n\n on<K extends keyof Events>(event: K, cb: Events[K]): () => void {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(cb);\n return () => this.off(event, cb);\n }\n\n off<K extends keyof Events>(event: K, cb: Events[K]): void {\n this.listeners.get(event)?.delete(cb);\n }\n\n emit<K extends keyof Events>(event: K, ...args: Parameters<Events[K]>): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const cb of Array.from(set)) {\n try {\n cb(...args);\n } catch (err) {\n this.onError?.(err);\n }\n }\n }\n\n clear(): void {\n this.listeners.clear();\n }\n}\n","import type { FrequencyConfig, GuideThrottlingSettings, PublishedGuide } from \"@guidelytech/shared\";\n\n/** Per-guide state kept locally and merged with the server's `IdentifyResponse.guideState`. */\nexport interface GuideLocalState {\n impressions: number;\n completedAt?: string | null;\n dismissedAt?: string | null;\n lastShownAt?: string | null;\n /** Last step reached in a multi-step flow (local only), so the messenger can offer to resume it. */\n lastStepId?: string | null;\n}\n\nconst HOUR = 3600 * 1000;\n\n/**\n * Pure frequency evaluation. `shownThisSession` comes from session storage.\n * - `once`: a single impression ever (unless `reshowAfterDismiss` and it was only dismissed).\n * - `once_per_session`: at most once per browser session.\n * - `every_time`: on every trigger (still blocked by completion/dismissal rules below).\n * - `interval`: at most once every `intervalHours`.\n * `maxImpressions` caps total impressions; dismissal blocks re-showing unless `reshowAfterDismiss`\n * (then `cooldownHours` must have elapsed); completion blocks unless mode is `every_time`.\n */\nexport function isFrequencyEligible(freq: FrequencyConfig, state: GuideLocalState | undefined, shownThisSession: boolean, now: number = Date.now()): boolean {\n const s = state ?? { impressions: 0 };\n if (freq.maxImpressions != null && s.impressions >= freq.maxImpressions) return false;\n if (s.completedAt && freq.mode !== \"every_time\") return false;\n if (s.dismissedAt) {\n if (!freq.reshowAfterDismiss) return false;\n if (freq.cooldownHours > 0 && now - Date.parse(s.dismissedAt) < freq.cooldownHours * HOUR) return false;\n }\n switch (freq.mode) {\n case \"once\":\n return s.impressions === 0 || (!!s.dismissedAt && freq.reshowAfterDismiss);\n case \"once_per_session\":\n return !shownThisSession;\n case \"interval\": {\n if (!s.lastShownAt) return true;\n const hours = freq.intervalHours ?? 24;\n return now - Date.parse(s.lastShownAt) >= hours * HOUR;\n }\n case \"every_time\":\n default:\n return true;\n }\n}\n\n/**\n * Exclusive guides (flows, modals, tooltips, announcements, surveys) run one at a time.\n * Banners, checklists and hotspot-only tooltips can coexist with an active flow.\n */\nexport function isExclusiveGuide(guide: PublishedGuide): boolean {\n if (guide.kind === \"banner\" || guide.kind === \"checklist\") return false;\n const steps = guide.config.steps;\n if (steps.length > 0 && steps.every((s) => s.type === \"hotspot\" || s.type === \"banner\")) return false;\n return true;\n}\n\n/** Is `a` mutually exclusive with `b` (by id or key, in either direction)? */\nexport function areMutuallyExclusive(a: PublishedGuide, b: PublishedGuide): boolean {\n const la = a.config.frequency.mutuallyExclusiveWith;\n const lb = b.config.frequency.mutuallyExclusiveWith;\n return la.includes(b.id) || la.includes(b.key) || lb.includes(a.id) || lb.includes(a.key);\n}\n\n/**\n * Scheduling window: the guide's `schedule` (any kind) and, for surveys, `survey.startAt` / `endAt`.\n * Unparsable dates are ignored.\n */\nexport function isWithinSchedule(guide: Pick<PublishedGuide, \"config\">, now: number = Date.now()): boolean {\n for (const w of [guide.config.schedule, guide.config.survey]) {\n if (!w) continue;\n if (w.startAt && now < Date.parse(w.startAt)) return false;\n if (w.endAt && now > Date.parse(w.endAt)) return false;\n }\n return true;\n}\n\nconst MINUTE = 60 * 1000;\n\n/**\n * Does showing this guide automatically count toward (and get limited by) the project's guide\n * throttling? Only exclusive guides (flows, modals, tooltips, announcements, surveys) interrupt;\n * banners, checklists and hotspot-only guides never count, nor does a guide set to ignore throttling.\n * Guides started by the visitor or the app (`startGuide`, buttons, Help) are never throttled.\n */\nexport function countsTowardThrottle(guide: PublishedGuide): boolean {\n return isExclusiveGuide(guide) && !guide.config.frequency.ignoreThrottling;\n}\n\n/**\n * Pure throttling check. `launches` = ISO times of this visitor's earlier automatic launches of\n * counted guides (any order). Disabled or missing settings never throttle.\n */\nexport function isThrottleEligible(settings: GuideThrottlingSettings | null | undefined, launches: readonly string[], now: number = Date.now()): boolean {\n if (!settings || !settings.enabled) return true;\n const times = launches.map((l) => Date.parse(l)).filter((t) => !Number.isNaN(t));\n const windowMs = Math.max(1, settings.windowHours) * HOUR;\n if (times.filter((t) => now - t < windowMs).length >= Math.max(1, settings.maxGuides)) return false;\n if (settings.minGapMinutes > 0 && times.some((t) => now - t < settings.minGapMinutes * MINUTE)) return false;\n return true;\n}\n\n/** Launch times worth keeping: those still inside the window or the minimum gap (at most 100). */\nexport function pruneLaunches(launches: readonly string[], settings: GuideThrottlingSettings | null | undefined, now: number = Date.now()): string[] {\n const keepMs = Math.max(settings?.windowHours ?? 24, 1) * HOUR + (settings?.minGapMinutes ?? 0) * MINUTE;\n return launches.filter((l) => { const t = Date.parse(l); return !Number.isNaN(t) && now - t < keepMs; }).slice(-100);\n}\n\n/**\n * A checklist's dismissal after merging server state. A local dismissal normally wins (it may not have\n * synced yet), but when the server reports a reset this device hasn't applied, the server's value wins:\n * null, or a dismissal made on another device after the reset. Compared as tokens, not times, so a\n * skewed device clock can't keep a reset dismissal.\n */\nexport function dismissedAfterMerge(local: { dismissedAt?: string | null; dismissResetAt?: string | null } | undefined, server: { dismissedAt?: string | null; dismissResetAt?: string | null }): string | null {\n if (server.dismissResetAt && server.dismissResetAt !== local?.dismissResetAt) return server.dismissedAt ?? null;\n return local?.dismissedAt ?? server.dismissedAt ?? null;\n}\n"],"mappings":";;;;;;;;AA6BO,IAAM,aAAN,MAAiB;AAAA,EActB,YAA6B,MAAyB;AAAzB;AAb7B,wBAAQ,UAAqB,CAAC;AAC9B,wBAAQ,SAA8C;AACtD,wBAAQ,cAAm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C,MAAM,OAAO,UAAU;AAC5D;AAMO,SAAS,mBAAmB,UAAsD,UAA6B,MAAc,KAAK,IAAI,GAAY;AACvJ,MAAI,CAAC,YAAY,CAAC,SAAS,QAAS,QAAO;AAC3C,QAAM,QAAQ,SAAS,IAAI,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,OAAO,MAAM,CAAC,CAAC;AAC/E,QAAM,WAAW,KAAK,IAAI,GAAG,SAAS,WAAW,IAAI;AACrD,MAAI,MAAM,OAAO,CAAC,MAAM,MAAM,IAAI,QAAQ,EAAE,UAAU,KAAK,IAAI,GAAG,SAAS,SAAS,EAAG,QAAO;AAC9F,MAAI,SAAS,gBAAgB,KAAK,MAAM,KAAK,CAAC,MAAM,MAAM,IAAI,SAAS,gBAAgB,MAAM,EAAG,QAAO;AACvG,SAAO;AACT;AAGO,SAAS,cAAc,UAA6B,UAAsD,MAAc,KAAK,IAAI,GAAa;AACnJ,QAAM,SAAS,KAAK,IAAI,UAAU,eAAe,IAAI,CAAC,IAAI,QAAQ,UAAU,iBAAiB,KAAK;AAClG,SAAO,SAAS,OAAO,CAAC,MAAM;AAAE,UAAM,IAAI,KAAK,MAAM,CAAC;AAAG,WAAO,CAAC,OAAO,MAAM,CAAC,KAAK,MAAM,IAAI;AAAA,EAAQ,CAAC,EAAE,MAAM,IAAI;AACrH;AAQO,SAAS,oBAAoB,OAAoF,QAAwF;AAC9M,MAAI,OAAO,kBAAkB,OAAO,mBAAmB,OAAO,eAAgB,QAAO,OAAO,eAAe;AAC3G,SAAO,OAAO,eAAe,OAAO,eAAe;AACrD;","names":[]}
@@ -1,376 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
-
5
- // src/health.ts
6
- var MAX_RETRY_AFTER_MS = 60 * 60 * 1e3;
7
- var OFFLINE_WAIT_MS = 3e4;
8
- var ServerHealth = class {
9
- constructor(opts = {}) {
10
- __publicField(this, "failures", 0);
11
- __publicField(this, "openUntil", 0);
12
- __publicField(this, "lastOkAt", 0);
13
- __publicField(this, "listeners", /* @__PURE__ */ new Set());
14
- __publicField(this, "threshold");
15
- __publicField(this, "baseMs");
16
- __publicField(this, "maxMs");
17
- __publicField(this, "now");
18
- __publicField(this, "random");
19
- this.threshold = opts.threshold ?? 3;
20
- this.baseMs = opts.baseMs ?? 5e3;
21
- this.maxMs = opts.maxMs ?? 5 * 60 * 1e3;
22
- this.now = opts.now ?? Date.now;
23
- this.random = opts.random ?? Math.random;
24
- }
25
- /** The server answered (2xx, 3xx, or a 4xx other than 429): it is up. */
26
- success() {
27
- const wasDown = this.failures > 0 || this.openUntil > 0;
28
- this.failures = 0;
29
- this.openUntil = 0;
30
- this.lastOkAt = this.now();
31
- if (wasDown) this.notify();
32
- }
33
- /** The request failed or the server is overloaded. `retryAfterMs` comes from a `Retry-After` header. */
34
- failure(retryAfterMs) {
35
- this.failures += 1;
36
- const now = this.now();
37
- if (retryAfterMs != null && retryAfterMs > 0) {
38
- this.openUntil = Math.max(this.openUntil, now + Math.min(retryAfterMs, MAX_RETRY_AFTER_MS));
39
- return;
40
- }
41
- if (this.failures < this.threshold) return;
42
- const cooldown = Math.min(this.maxMs, this.baseMs * 2 ** (this.failures - this.threshold));
43
- this.openUntil = Math.max(this.openUntil, now + cooldown * (0.8 + this.random() * 0.4));
44
- }
45
- /** Milliseconds background traffic should wait before trying again (0: send now). */
46
- waitMs() {
47
- if (typeof navigator !== "undefined" && navigator.onLine === false) return OFFLINE_WAIT_MS;
48
- return Math.max(0, this.openUntil - this.now());
49
- }
50
- canSend() {
51
- return this.waitMs() === 0;
52
- }
53
- /**
54
- * The last request got an answer. Unload beacons can't report back, so what they carry is only
55
- * forgotten while this holds; otherwise it stays queued and is sent again (the server drops duplicates).
56
- */
57
- get reachable() {
58
- return this.failures === 0 && this.lastOkAt > 0;
59
- }
60
- /** The browser came back online: end the cooldown and let queued traffic try straight away. */
61
- online() {
62
- this.openUntil = 0;
63
- this.notify();
64
- }
65
- /** Called when the server answers again after failures, or the browser comes back online. */
66
- onRecover(cb) {
67
- this.listeners.add(cb);
68
- return () => this.listeners.delete(cb);
69
- }
70
- notify() {
71
- for (const cb of Array.from(this.listeners)) {
72
- try {
73
- cb();
74
- } catch {
75
- }
76
- }
77
- }
78
- };
79
- function parseRetryAfter(value, now = Date.now()) {
80
- if (!value) return null;
81
- const trimmed = value.trim();
82
- if (/^\d+$/.test(trimmed)) return Number(trimmed) * 1e3;
83
- const at = Date.parse(trimmed);
84
- return Number.isNaN(at) ? null : Math.max(0, at - now);
85
- }
86
- function isServerFailure(status) {
87
- return status === 429 || status >= 500;
88
- }
89
-
90
- // src/http.ts
91
- var STREAM_RESPONSE_TIMEOUT_MS = 3e4;
92
- var STREAM_IDLE_TIMEOUT_MS = 6e4;
93
- var Api = class {
94
- constructor(baseUrl, key, fetchImpl, health) {
95
- __publicField(this, "baseUrl", baseUrl);
96
- __publicField(this, "key", key);
97
- __publicField(this, "fetchImpl", fetchImpl);
98
- /** Reachability of the API, fed by every answer (see {@link ServerHealth}). */
99
- __publicField(this, "health");
100
- this.health = health ?? new ServerHealth();
101
- }
102
- /** Feeds an answer (or a failed request, `null`) into {@link health}. */
103
- observe(res) {
104
- if (!res) this.health.failure();
105
- else if (isServerFailure(res.status)) this.health.failure(parseRetryAfter(res.headers?.get?.("retry-after")));
106
- else this.health.success();
107
- }
108
- url(path, params = {}) {
109
- const query = Object.entries({ key: this.key, ...params }).filter((e) => e[1] != null).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&");
110
- return `${this.baseUrl.replace(/\/$/, "")}/api/v1/sdk${path}?${query}`;
111
- }
112
- get fetcher() {
113
- if (this.fetchImpl) return this.fetchImpl;
114
- return typeof fetch === "function" ? fetch.bind(globalThis) : null;
115
- }
116
- async request(method, path, options = {}) {
117
- const f = this.fetcher;
118
- if (!f) throw new Error("fetch is not available");
119
- const headers = { ...options.headers, "X-Guidely-Key": this.key, Accept: "application/json" };
120
- const form = typeof FormData !== "undefined" && options.body instanceof FormData;
121
- if (options.body !== void 0 && !form) headers["Content-Type"] = "application/json";
122
- if (options.etag) headers["If-None-Match"] = options.etag;
123
- const ac = typeof AbortController !== "undefined" ? new AbortController() : null;
124
- const timer = ac ? setTimeout(() => ac.abort(), options.timeoutMs ?? 1e4) : null;
125
- try {
126
- let res;
127
- try {
128
- res = await f(this.url(path, options.params), {
129
- method,
130
- headers,
131
- body: options.body === void 0 ? void 0 : form ? options.body : JSON.stringify(options.body),
132
- keepalive: options.keepalive,
133
- signal: ac?.signal,
134
- credentials: "omit",
135
- mode: "cors"
136
- });
137
- } catch (err) {
138
- this.observe(null);
139
- throw err;
140
- }
141
- this.observe(res);
142
- let data = null;
143
- if (res.status !== 304 && res.status !== 204) {
144
- try {
145
- data = await res.json();
146
- } catch {
147
- data = null;
148
- }
149
- }
150
- return { status: res.status, ok: res.ok, data, etag: res.headers?.get?.("etag") ?? null };
151
- } finally {
152
- if (timer) clearTimeout(timer);
153
- }
154
- }
155
- get(path, options) {
156
- return this.request("GET", path, options);
157
- }
158
- post(path, body, options) {
159
- return this.request("POST", path, { body, ...options });
160
- }
161
- /** Multipart POST (file uploads). No Content-Type header: the browser adds it with the boundary. */
162
- postForm(path, form, options) {
163
- return this.request("POST", path, { body: form, ...options });
164
- }
165
- /**
166
- * POST that may answer with server-sent events. Each event is passed to `onEvent`; a JSON answer is
167
- * returned instead. Scout replies can take a while, so there is no overall timeout: the response
168
- * must start within 30 s and then never go quiet for more than 60 s (the server sends keepalives),
169
- * otherwise the request is aborted and rejects.
170
- */
171
- async stream(path, body, onEvent, headers = {}) {
172
- const f = this.fetcher;
173
- if (!f) throw new Error("fetch is not available");
174
- const ac = typeof AbortController !== "undefined" ? new AbortController() : null;
175
- let timer = null;
176
- const arm = (ms) => {
177
- if (!ac) return;
178
- if (timer) clearTimeout(timer);
179
- timer = setTimeout(() => ac.abort(), ms);
180
- };
181
- arm(STREAM_RESPONSE_TIMEOUT_MS);
182
- try {
183
- let res;
184
- try {
185
- res = await f(this.url(path), {
186
- method: "POST",
187
- headers: { ...headers, "X-Guidely-Key": this.key, Accept: "text/event-stream, application/json", "Content-Type": "application/json" },
188
- body: JSON.stringify(body),
189
- signal: ac?.signal,
190
- credentials: "omit",
191
- mode: "cors"
192
- });
193
- } catch (err) {
194
- this.observe(null);
195
- throw err;
196
- }
197
- this.observe(res);
198
- const type = res.headers?.get?.("content-type") ?? "";
199
- if (!type.includes("text/event-stream") || !res.body) {
200
- let data = null;
201
- try {
202
- data = await res.json();
203
- } catch {
204
- data = null;
205
- }
206
- return { status: res.status, ok: res.ok, data, etag: null };
207
- }
208
- arm(STREAM_IDLE_TIMEOUT_MS);
209
- await readEventStream(res.body, onEvent, () => arm(STREAM_IDLE_TIMEOUT_MS));
210
- return { status: res.status, ok: res.ok, data: null, etag: null };
211
- } finally {
212
- if (timer) clearTimeout(timer);
213
- }
214
- }
215
- /** `navigator.sendBeacon` when available (page unload); returns false when it could not be queued. */
216
- beacon(path, body) {
217
- try {
218
- if (typeof navigator === "undefined" || typeof navigator.sendBeacon !== "function") return false;
219
- const blob = new Blob([JSON.stringify(body)], { type: "text/plain;charset=UTF-8" });
220
- return navigator.sendBeacon(this.url(path), blob);
221
- } catch {
222
- return false;
223
- }
224
- }
225
- };
226
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
227
- function backoffMs(attempt, baseMs = 1e3, maxMs = 3e4) {
228
- return Math.min(maxMs, baseMs * 2 ** Math.max(0, attempt));
229
- }
230
- async function withRetry(send, attempts = 3, baseMs = 500) {
231
- for (let i = 0; i < attempts; i++) {
232
- try {
233
- const res = await send();
234
- if (res.ok || res.status >= 400 && res.status < 500 && res.status !== 429) return res;
235
- } catch {
236
- }
237
- if (i < attempts - 1) await sleep(backoffMs(i, baseMs, 8e3));
238
- }
239
- return null;
240
- }
241
- function postWithRetry(api, path, body, attempts = 3, baseMs = 500) {
242
- return withRetry(() => api.post(path, body), attempts, baseMs);
243
- }
244
- async function readEventStream(body, onEvent, onChunk) {
245
- const reader = body.getReader();
246
- const decoder = new TextDecoder();
247
- let buffer = "";
248
- const dispatch = (raw) => {
249
- let event = "message";
250
- const data = [];
251
- for (const line of raw.split("\n")) {
252
- if (!line || line.startsWith(":")) continue;
253
- const i = line.indexOf(":");
254
- const field = i < 0 ? line : line.slice(0, i);
255
- const value = i < 0 ? "" : line.slice(i + 1).replace(/^ /, "");
256
- if (field === "event") event = value;
257
- else if (field === "data") data.push(value);
258
- }
259
- if (!data.length) return;
260
- try {
261
- onEvent(event, JSON.parse(data.join("\n")));
262
- } catch {
263
- }
264
- };
265
- for (; ; ) {
266
- const { done, value } = await reader.read();
267
- if (value) onChunk?.();
268
- if (value) buffer += decoder.decode(value, { stream: true }).replace(/\r\n?/g, "\n");
269
- let sep;
270
- while ((sep = buffer.indexOf("\n\n")) >= 0) {
271
- dispatch(buffer.slice(0, sep));
272
- buffer = buffer.slice(sep + 2);
273
- }
274
- if (done) break;
275
- }
276
- if (buffer.trim()) dispatch(buffer);
277
- }
278
-
279
- // src/storage.ts
280
- function memoryStore() {
281
- const map = /* @__PURE__ */ new Map();
282
- return { get: (k) => map.get(k) ?? null, set: (k, v) => void map.set(k, v), remove: (k) => void map.delete(k) };
283
- }
284
- function webStore(area) {
285
- try {
286
- if (typeof window === "undefined") return null;
287
- const s = window[area];
288
- if (!s) return null;
289
- const probe = "__guidely_probe__";
290
- s.setItem(probe, "1");
291
- s.removeItem(probe);
292
- return {
293
- get: (k) => {
294
- try {
295
- return s.getItem(k);
296
- } catch {
297
- return null;
298
- }
299
- },
300
- set: (k, v) => {
301
- try {
302
- s.setItem(k, v);
303
- } catch {
304
- }
305
- },
306
- remove: (k) => {
307
- try {
308
- s.removeItem(k);
309
- } catch {
310
- }
311
- }
312
- };
313
- } catch {
314
- return null;
315
- }
316
- }
317
- function createStorage(kind = "local") {
318
- if (kind === "memory") return memoryStore();
319
- return webStore(kind === "local" ? "localStorage" : "sessionStorage") ?? memoryStore();
320
- }
321
- function readJson(store, key, fallback) {
322
- const raw = store.get(key);
323
- if (raw == null) return fallback;
324
- try {
325
- return JSON.parse(raw);
326
- } catch {
327
- return fallback;
328
- }
329
- }
330
- function writeJson(store, key, value) {
331
- try {
332
- store.set(key, JSON.stringify(value));
333
- } catch {
334
- }
335
- }
336
- var KEYS = {
337
- anon: "guidely:anon",
338
- seen: "guidely:seen",
339
- config: (key) => `guidely:config:${key}`,
340
- etag: (key) => `guidely:etag:${key}`,
341
- state: (key) => `guidely:state:${key}`,
342
- user: (key) => `guidely:user:${key}`,
343
- queue: (key) => `guidely:queue:${key}`,
344
- /** Survey answers and guide/checklist progress not yet accepted by the server. */
345
- outbox: (key) => `guidely:outbox:${key}`,
346
- /** Agent Analytics turns not yet accepted by the server. */
347
- agentOutbox: (key) => `guidely:agents:${key}`,
348
- session: "guidely:session",
349
- active: "guidely:active",
350
- authoring: "guidely:authoring",
351
- /** How-to capture session marker ({ token, … }) and its not-yet-uploaded steps. */
352
- capture: "guidely:capture",
353
- capturePending: "guidely:capture:pending",
354
- /** Messenger conversations this browser can read: [{ id, token }]. */
355
- conversations: (key) => `guidely:conversations:${key}`,
356
- /** Announcement ids opened in the messenger's News tab. */
357
- newsSeen: (key) => `guidely:news:${key}`
358
- };
359
-
360
- export {
361
- __publicField,
362
- ServerHealth,
363
- parseRetryAfter,
364
- isServerFailure,
365
- Api,
366
- sleep,
367
- backoffMs,
368
- withRetry,
369
- postWithRetry,
370
- memoryStore,
371
- createStorage,
372
- readJson,
373
- writeJson,
374
- KEYS
375
- };
376
- //# sourceMappingURL=chunk-JUSM7J5N.js.map