@guidelytech/sdk-core 0.9.0 → 0.11.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.
Files changed (48) hide show
  1. package/README.md +15 -4
  2. package/dist/{capture-Dqd7up2n.d.ts → capture-CgN69Lxq.d.cts} +2 -1
  3. package/dist/{capture-C3faAYb7.d.cts → capture-Csz721-A.d.ts} +2 -1
  4. package/dist/capture.cjs +4 -0
  5. package/dist/capture.cjs.map +1 -1
  6. package/dist/capture.d.cts +3 -2
  7. package/dist/capture.d.ts +3 -2
  8. package/dist/capture.js +4 -6
  9. package/dist/capture.js.map +1 -1
  10. package/dist/chunk-JUSM7J5N.js +376 -0
  11. package/dist/chunk-JUSM7J5N.js.map +1 -0
  12. package/dist/{chunk-544KSOC3.js → chunk-ZAF2KRJA.js} +142 -22
  13. package/dist/chunk-ZAF2KRJA.js.map +1 -0
  14. package/dist/headless.cjs +307 -44
  15. package/dist/headless.cjs.map +1 -1
  16. package/dist/headless.d.cts +44 -3
  17. package/dist/headless.d.ts +44 -3
  18. package/dist/headless.js +21 -9
  19. package/dist/health-sbP9JwTE.d.cts +90 -0
  20. package/dist/health-sbP9JwTE.d.ts +90 -0
  21. package/dist/{http-47tiAlOM.d.ts → http-Cb6KYYFv.d.cts} +10 -35
  22. package/dist/{http-47tiAlOM.d.cts → http-D047Ngxk.d.ts} +10 -35
  23. package/dist/index.cjs +1352 -500
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +81 -8
  26. package/dist/index.d.ts +81 -8
  27. package/dist/index.js +809 -211
  28. package/dist/index.js.map +1 -1
  29. package/dist/recorder.cjs +70 -9
  30. package/dist/recorder.cjs.map +1 -1
  31. package/dist/recorder.d.cts +9 -0
  32. package/dist/recorder.d.ts +9 -0
  33. package/dist/recorder.js +57 -11
  34. package/dist/recorder.js.map +1 -1
  35. package/dist/{types-DnJW_4ck.d.ts → types-BDlebXrm.d.ts} +68 -7
  36. package/dist/{types-zM5e3loY.d.cts → types-Mtlmlj5C.d.cts} +68 -7
  37. package/package.json +4 -4
  38. package/dist/chunk-544KSOC3.js.map +0 -1
  39. package/dist/chunk-AKNE7D5M.js +0 -160
  40. package/dist/chunk-AKNE7D5M.js.map +0 -1
  41. package/dist/chunk-CYAG6ZYX.js +0 -85
  42. package/dist/chunk-CYAG6ZYX.js.map +0 -1
  43. package/dist/chunk-GDF6RCHQ.js +0 -209
  44. package/dist/chunk-GDF6RCHQ.js.map +0 -1
  45. package/dist/types-DbKQPvFt.d.cts +0 -238
  46. package/dist/types-DqhNl5Am.d.ts +0 -238
  47. package/dist/types-RyeRQd9f.d.ts +0 -226
  48. package/dist/types-d4eOerxi.d.cts +0 -226
@@ -0,0 +1 @@
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,cAAmD;AAC3D,wBAAQ,YAAW;AACnB,wBAAQ,eAAc,oBAAI,IAAY;AACtC,wBAAQ,WAAU;AAClB,wBAAQ,aAAY;AACpB,wBAAQ,cAAkC;AAC1C,wBAAiB;AACjB,wBAAiB;AACjB,wBAAiB;AACjB,wBAAiB;AAGf,SAAK,kBAAkB,KAA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,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":[]}
package/dist/headless.cjs CHANGED
@@ -26,26 +26,129 @@ __export(headless_exports, {
26
26
  Emitter: () => Emitter,
27
27
  EventQueue: () => EventQueue,
28
28
  KEYS: () => KEYS,
29
+ Outbox: () => Outbox,
30
+ ServerHealth: () => ServerHealth,
29
31
  areMutuallyExclusive: () => areMutuallyExclusive,
30
32
  backoffMs: () => backoffMs,
33
+ countsTowardThrottle: () => countsTowardThrottle,
31
34
  dismissedAfterMerge: () => dismissedAfterMerge,
32
35
  isExclusiveGuide: () => isExclusiveGuide,
33
36
  isFrequencyEligible: () => isFrequencyEligible,
37
+ isServerFailure: () => isServerFailure,
38
+ isThrottleEligible: () => isThrottleEligible,
34
39
  isWithinSchedule: () => isWithinSchedule,
35
40
  memoryStore: () => memoryStore,
41
+ parseRetryAfter: () => parseRetryAfter,
36
42
  postWithRetry: () => postWithRetry,
43
+ pruneLaunches: () => pruneLaunches,
37
44
  readJson: () => readJson,
38
45
  sleep: () => sleep,
39
46
  writeJson: () => writeJson
40
47
  });
41
48
  module.exports = __toCommonJS(headless_exports);
42
49
 
50
+ // src/health.ts
51
+ var MAX_RETRY_AFTER_MS = 60 * 60 * 1e3;
52
+ var OFFLINE_WAIT_MS = 3e4;
53
+ var ServerHealth = class {
54
+ constructor(opts = {}) {
55
+ __publicField(this, "failures", 0);
56
+ __publicField(this, "openUntil", 0);
57
+ __publicField(this, "lastOkAt", 0);
58
+ __publicField(this, "listeners", /* @__PURE__ */ new Set());
59
+ __publicField(this, "threshold");
60
+ __publicField(this, "baseMs");
61
+ __publicField(this, "maxMs");
62
+ __publicField(this, "now");
63
+ __publicField(this, "random");
64
+ this.threshold = opts.threshold ?? 3;
65
+ this.baseMs = opts.baseMs ?? 5e3;
66
+ this.maxMs = opts.maxMs ?? 5 * 60 * 1e3;
67
+ this.now = opts.now ?? Date.now;
68
+ this.random = opts.random ?? Math.random;
69
+ }
70
+ /** The server answered (2xx, 3xx, or a 4xx other than 429): it is up. */
71
+ success() {
72
+ const wasDown = this.failures > 0 || this.openUntil > 0;
73
+ this.failures = 0;
74
+ this.openUntil = 0;
75
+ this.lastOkAt = this.now();
76
+ if (wasDown) this.notify();
77
+ }
78
+ /** The request failed or the server is overloaded. `retryAfterMs` comes from a `Retry-After` header. */
79
+ failure(retryAfterMs) {
80
+ this.failures += 1;
81
+ const now = this.now();
82
+ if (retryAfterMs != null && retryAfterMs > 0) {
83
+ this.openUntil = Math.max(this.openUntil, now + Math.min(retryAfterMs, MAX_RETRY_AFTER_MS));
84
+ return;
85
+ }
86
+ if (this.failures < this.threshold) return;
87
+ const cooldown = Math.min(this.maxMs, this.baseMs * 2 ** (this.failures - this.threshold));
88
+ this.openUntil = Math.max(this.openUntil, now + cooldown * (0.8 + this.random() * 0.4));
89
+ }
90
+ /** Milliseconds background traffic should wait before trying again (0: send now). */
91
+ waitMs() {
92
+ if (typeof navigator !== "undefined" && navigator.onLine === false) return OFFLINE_WAIT_MS;
93
+ return Math.max(0, this.openUntil - this.now());
94
+ }
95
+ canSend() {
96
+ return this.waitMs() === 0;
97
+ }
98
+ /**
99
+ * The last request got an answer. Unload beacons can't report back, so what they carry is only
100
+ * forgotten while this holds; otherwise it stays queued and is sent again (the server drops duplicates).
101
+ */
102
+ get reachable() {
103
+ return this.failures === 0 && this.lastOkAt > 0;
104
+ }
105
+ /** The browser came back online: end the cooldown and let queued traffic try straight away. */
106
+ online() {
107
+ this.openUntil = 0;
108
+ this.notify();
109
+ }
110
+ /** Called when the server answers again after failures, or the browser comes back online. */
111
+ onRecover(cb) {
112
+ this.listeners.add(cb);
113
+ return () => this.listeners.delete(cb);
114
+ }
115
+ notify() {
116
+ for (const cb of Array.from(this.listeners)) {
117
+ try {
118
+ cb();
119
+ } catch {
120
+ }
121
+ }
122
+ }
123
+ };
124
+ function parseRetryAfter(value, now = Date.now()) {
125
+ if (!value) return null;
126
+ const trimmed = value.trim();
127
+ if (/^\d+$/.test(trimmed)) return Number(trimmed) * 1e3;
128
+ const at = Date.parse(trimmed);
129
+ return Number.isNaN(at) ? null : Math.max(0, at - now);
130
+ }
131
+ function isServerFailure(status) {
132
+ return status === 429 || status >= 500;
133
+ }
134
+
43
135
  // src/http.ts
136
+ var STREAM_RESPONSE_TIMEOUT_MS = 3e4;
137
+ var STREAM_IDLE_TIMEOUT_MS = 6e4;
44
138
  var Api = class {
45
- constructor(baseUrl, key, fetchImpl) {
139
+ constructor(baseUrl, key, fetchImpl, health) {
46
140
  __publicField(this, "baseUrl", baseUrl);
47
141
  __publicField(this, "key", key);
48
142
  __publicField(this, "fetchImpl", fetchImpl);
143
+ /** Reachability of the API, fed by every answer (see {@link ServerHealth}). */
144
+ __publicField(this, "health");
145
+ this.health = health ?? new ServerHealth();
146
+ }
147
+ /** Feeds an answer (or a failed request, `null`) into {@link health}. */
148
+ observe(res) {
149
+ if (!res) this.health.failure();
150
+ else if (isServerFailure(res.status)) this.health.failure(parseRetryAfter(res.headers?.get?.("retry-after")));
151
+ else this.health.success();
49
152
  }
50
153
  url(path, params = {}) {
51
154
  const query = Object.entries({ key: this.key, ...params }).filter((e) => e[1] != null).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&");
@@ -65,15 +168,22 @@ var Api = class {
65
168
  const ac = typeof AbortController !== "undefined" ? new AbortController() : null;
66
169
  const timer = ac ? setTimeout(() => ac.abort(), options.timeoutMs ?? 1e4) : null;
67
170
  try {
68
- const res = await f(this.url(path, options.params), {
69
- method,
70
- headers,
71
- body: options.body === void 0 ? void 0 : form ? options.body : JSON.stringify(options.body),
72
- keepalive: options.keepalive,
73
- signal: ac?.signal,
74
- credentials: "omit",
75
- mode: "cors"
76
- });
171
+ let res;
172
+ try {
173
+ res = await f(this.url(path, options.params), {
174
+ method,
175
+ headers,
176
+ body: options.body === void 0 ? void 0 : form ? options.body : JSON.stringify(options.body),
177
+ keepalive: options.keepalive,
178
+ signal: ac?.signal,
179
+ credentials: "omit",
180
+ mode: "cors"
181
+ });
182
+ } catch (err) {
183
+ this.observe(null);
184
+ throw err;
185
+ }
186
+ this.observe(res);
77
187
  let data = null;
78
188
  if (res.status !== 304 && res.status !== 204) {
79
189
  try {
@@ -99,30 +209,53 @@ var Api = class {
99
209
  }
100
210
  /**
101
211
  * POST that may answer with server-sent events. Each event is passed to `onEvent`; a JSON answer is
102
- * returned instead. No timeout: Scout replies can take a while and the server keeps the stream alive.
212
+ * returned instead. Scout replies can take a while, so there is no overall timeout: the response
213
+ * must start within 30 s and then never go quiet for more than 60 s (the server sends keepalives),
214
+ * otherwise the request is aborted and rejects.
103
215
  */
104
216
  async stream(path, body, onEvent, headers = {}) {
105
217
  const f = this.fetcher;
106
218
  if (!f) throw new Error("fetch is not available");
107
- const res = await f(this.url(path), {
108
- method: "POST",
109
- headers: { ...headers, "X-Guidely-Key": this.key, Accept: "text/event-stream, application/json", "Content-Type": "application/json" },
110
- body: JSON.stringify(body),
111
- credentials: "omit",
112
- mode: "cors"
113
- });
114
- const type = res.headers?.get?.("content-type") ?? "";
115
- if (!type.includes("text/event-stream") || !res.body) {
116
- let data = null;
219
+ const ac = typeof AbortController !== "undefined" ? new AbortController() : null;
220
+ let timer = null;
221
+ const arm = (ms) => {
222
+ if (!ac) return;
223
+ if (timer) clearTimeout(timer);
224
+ timer = setTimeout(() => ac.abort(), ms);
225
+ };
226
+ arm(STREAM_RESPONSE_TIMEOUT_MS);
227
+ try {
228
+ let res;
117
229
  try {
118
- data = await res.json();
119
- } catch {
120
- data = null;
230
+ res = await f(this.url(path), {
231
+ method: "POST",
232
+ headers: { ...headers, "X-Guidely-Key": this.key, Accept: "text/event-stream, application/json", "Content-Type": "application/json" },
233
+ body: JSON.stringify(body),
234
+ signal: ac?.signal,
235
+ credentials: "omit",
236
+ mode: "cors"
237
+ });
238
+ } catch (err) {
239
+ this.observe(null);
240
+ throw err;
241
+ }
242
+ this.observe(res);
243
+ const type = res.headers?.get?.("content-type") ?? "";
244
+ if (!type.includes("text/event-stream") || !res.body) {
245
+ let data = null;
246
+ try {
247
+ data = await res.json();
248
+ } catch {
249
+ data = null;
250
+ }
251
+ return { status: res.status, ok: res.ok, data, etag: null };
121
252
  }
122
- return { status: res.status, ok: res.ok, data, etag: null };
253
+ arm(STREAM_IDLE_TIMEOUT_MS);
254
+ await readEventStream(res.body, onEvent, () => arm(STREAM_IDLE_TIMEOUT_MS));
255
+ return { status: res.status, ok: res.ok, data: null, etag: null };
256
+ } finally {
257
+ if (timer) clearTimeout(timer);
123
258
  }
124
- await readEventStream(res.body, onEvent);
125
- return { status: res.status, ok: res.ok, data: null, etag: null };
126
259
  }
127
260
  /** `navigator.sendBeacon` when available (page unload); returns false when it could not be queued. */
128
261
  beacon(path, body) {
@@ -153,7 +286,7 @@ async function withRetry(send, attempts = 3, baseMs = 500) {
153
286
  function postWithRetry(api, path, body, attempts = 3, baseMs = 500) {
154
287
  return withRetry(() => api.post(path, body), attempts, baseMs);
155
288
  }
156
- async function readEventStream(body, onEvent) {
289
+ async function readEventStream(body, onEvent, onChunk) {
157
290
  const reader = body.getReader();
158
291
  const decoder = new TextDecoder();
159
292
  let buffer = "";
@@ -176,6 +309,7 @@ async function readEventStream(body, onEvent) {
176
309
  };
177
310
  for (; ; ) {
178
311
  const { done, value } = await reader.read();
312
+ if (value) onChunk?.();
179
313
  if (value) buffer += decoder.decode(value, { stream: true }).replace(/\r\n?/g, "\n");
180
314
  let sep;
181
315
  while ((sep = buffer.indexOf("\n\n")) >= 0) {
@@ -215,6 +349,10 @@ var KEYS = {
215
349
  state: (key) => `guidely:state:${key}`,
216
350
  user: (key) => `guidely:user:${key}`,
217
351
  queue: (key) => `guidely:queue:${key}`,
352
+ /** Survey answers and guide/checklist progress not yet accepted by the server. */
353
+ outbox: (key) => `guidely:outbox:${key}`,
354
+ /** Agent Analytics turns not yet accepted by the server. */
355
+ agentOutbox: (key) => `guidely:agents:${key}`,
218
356
  session: "guidely:session",
219
357
  active: "guidely:active",
220
358
  authoring: "guidely:authoring",
@@ -238,17 +376,34 @@ var EventQueue = class {
238
376
  __publicField(this, "inflightIds", /* @__PURE__ */ new Set());
239
377
  __publicField(this, "attempt", 0);
240
378
  __publicField(this, "destroyed", false);
379
+ __publicField(this, "offRecover", null);
241
380
  __publicField(this, "flushIntervalMs");
242
381
  __publicField(this, "maxQueue");
243
382
  __publicField(this, "batchSize");
244
383
  __publicField(this, "maxAttempts");
245
384
  this.flushIntervalMs = opts.flushIntervalMs ?? 2e3;
246
- this.maxQueue = opts.maxQueue ?? 200;
385
+ this.maxQueue = opts.maxQueue ?? 500;
247
386
  this.batchSize = opts.batchSize ?? 50;
248
387
  this.maxAttempts = opts.maxAttempts ?? 5;
249
388
  const persisted = readJson(opts.store, opts.storageKey, []);
250
389
  if (Array.isArray(persisted)) this.events = persisted.filter((e) => e && typeof e.eventId === "string").slice(-this.maxQueue);
251
390
  if (this.events.length) this.schedule();
391
+ this.offRecover = opts.health?.onRecover(() => this.retryNow()) ?? null;
392
+ }
393
+ /** The API is back: drop any pending backoff and send what is queued. */
394
+ retryNow() {
395
+ if (this.destroyed) return;
396
+ if (this.retryTimer) clearTimeout(this.retryTimer);
397
+ this.retryTimer = null;
398
+ this.attempt = 0;
399
+ void this.flush();
400
+ }
401
+ retryIn(ms) {
402
+ if (this.retryTimer || this.destroyed) return;
403
+ this.retryTimer = setTimeout(() => {
404
+ this.retryTimer = null;
405
+ void this.flush();
406
+ }, ms);
252
407
  }
253
408
  get size() {
254
409
  return this.events.length;
@@ -282,6 +437,8 @@ var EventQueue = class {
282
437
  clearTimeout(this.timer);
283
438
  this.timer = null;
284
439
  }
440
+ const wait = this.opts.health?.waitMs() ?? 0;
441
+ if (wait > 0) return this.retryIn(wait);
285
442
  this.inflight = true;
286
443
  const batch = this.events.slice(0, this.batchSize);
287
444
  this.inflightIds = new Set(batch.map((e) => e.eventId));
@@ -305,26 +462,20 @@ var EventQueue = class {
305
462
  if (this.events.length) this.schedule();
306
463
  return;
307
464
  }
308
- this.attempt += 1;
309
- if (this.attempt >= this.maxAttempts) {
310
- this.attempt = 0;
311
- return;
312
- }
313
- this.retryTimer = setTimeout(() => {
314
- this.retryTimer = null;
315
- void this.flush();
316
- }, backoffMs(this.attempt - 1));
465
+ this.attempt = Math.min(this.attempt + 1, this.maxAttempts);
466
+ const delay = this.attempt >= this.maxAttempts ? 6e4 : backoffMs(this.attempt - 1);
467
+ this.retryIn(Math.max(delay, this.opts.health?.waitMs() ?? 0));
317
468
  }
318
469
  /** Best-effort synchronous flush on unload using `sendBeacon`. */
319
470
  flushSync() {
320
471
  if (this.destroyed || !this.opts.enabled() || !this.opts.beacon) return;
321
472
  const batch = this.events.filter((e) => !this.inflightIds.has(e.eventId)).slice(0, this.batchSize);
322
473
  if (!batch.length) return;
323
- if (this.opts.beacon(batch)) {
474
+ if (this.opts.beacon(batch) && (this.opts.health?.reachable ?? true)) {
324
475
  const ids = new Set(batch.map((e) => e.eventId));
325
476
  this.events = this.events.filter((e) => !ids.has(e.eventId));
326
- this.persist();
327
477
  }
478
+ this.persist();
328
479
  }
329
480
  clear() {
330
481
  this.events = [];
@@ -332,6 +483,7 @@ var EventQueue = class {
332
483
  }
333
484
  destroy() {
334
485
  this.destroyed = true;
486
+ this.offRecover?.();
335
487
  if (this.timer) clearTimeout(this.timer);
336
488
  if (this.retryTimer) clearTimeout(this.retryTimer);
337
489
  this.timer = null;
@@ -340,6 +492,90 @@ var EventQueue = class {
340
492
  }
341
493
  };
342
494
 
495
+ // src/outbox.ts
496
+ var Outbox = class {
497
+ constructor(opts) {
498
+ __publicField(this, "opts", opts);
499
+ __publicField(this, "items");
500
+ __publicField(this, "sending", false);
501
+ __publicField(this, "attempt", 0);
502
+ __publicField(this, "timer", null);
503
+ __publicField(this, "destroyed", false);
504
+ __publicField(this, "offRecover");
505
+ __publicField(this, "maxItems");
506
+ __publicField(this, "maxAgeMs");
507
+ this.maxItems = opts.maxItems ?? 50;
508
+ this.maxAgeMs = opts.maxAgeMs ?? 7 * 24 * 60 * 60 * 1e3;
509
+ const stored = readJson(opts.store, opts.storageKey, []);
510
+ const cutoff = Date.now() - this.maxAgeMs;
511
+ this.items = Array.isArray(stored) ? stored.filter((i) => i && typeof i.path === "string" && typeof i.key === "string" && i.createdAt > cutoff).slice(-this.maxItems) : [];
512
+ this.offRecover = opts.health?.onRecover(() => {
513
+ this.attempt = 0;
514
+ this.retryIn(0);
515
+ }) ?? null;
516
+ if (this.items.length) this.retryIn(0);
517
+ }
518
+ get size() {
519
+ return this.items.length;
520
+ }
521
+ /** Queues `POST path` and sends it now (or as soon as the API is reachable). */
522
+ add(key, path, body) {
523
+ if (this.destroyed) return;
524
+ this.items = this.items.filter((i) => i.key !== key);
525
+ this.items.push({ key, path, body, createdAt: Date.now() });
526
+ if (this.items.length > this.maxItems) this.items.splice(0, this.items.length - this.maxItems);
527
+ this.persist();
528
+ void this.flush();
529
+ }
530
+ persist() {
531
+ writeJson(this.opts.store, this.opts.storageKey, this.items);
532
+ }
533
+ retryIn(ms) {
534
+ if (this.destroyed) return;
535
+ if (this.timer) clearTimeout(this.timer);
536
+ this.timer = setTimeout(() => {
537
+ this.timer = null;
538
+ void this.flush();
539
+ }, ms);
540
+ }
541
+ /** Sends queued requests in order, one at a time. */
542
+ async flush() {
543
+ if (this.destroyed || this.sending || !this.items.length) return;
544
+ const wait = this.opts.health?.waitMs() ?? 0;
545
+ if (wait > 0) return this.retryIn(wait);
546
+ this.sending = true;
547
+ try {
548
+ while (this.items.length && !this.destroyed) {
549
+ const item = this.items[0];
550
+ let retry = false;
551
+ try {
552
+ const res = await this.opts.api.post(item.path, item.body);
553
+ retry = !res.ok && (res.status === 429 || res.status >= 500);
554
+ } catch (err) {
555
+ retry = true;
556
+ this.opts.onError?.(err);
557
+ }
558
+ if (retry) {
559
+ this.attempt += 1;
560
+ this.retryIn(Math.max(backoffMs(this.attempt - 1, 1e3, 6e4), this.opts.health?.waitMs() ?? 0));
561
+ return;
562
+ }
563
+ this.attempt = 0;
564
+ this.items = this.items.filter((i) => i !== item);
565
+ this.persist();
566
+ }
567
+ } finally {
568
+ this.sending = false;
569
+ }
570
+ }
571
+ destroy() {
572
+ this.destroyed = true;
573
+ this.offRecover?.();
574
+ if (this.timer) clearTimeout(this.timer);
575
+ this.timer = null;
576
+ }
577
+ };
578
+
343
579
  // src/emitter.ts
344
580
  var Emitter = class {
345
581
  constructor(onError) {
@@ -411,12 +647,32 @@ function areMutuallyExclusive(a, b) {
411
647
  return la.includes(b.id) || la.includes(b.key) || lb.includes(a.id) || lb.includes(a.key);
412
648
  }
413
649
  function isWithinSchedule(guide, now = Date.now()) {
414
- const s = guide.config.survey;
415
- if (!s) return true;
416
- if (s.startAt && now < Date.parse(s.startAt)) return false;
417
- if (s.endAt && now > Date.parse(s.endAt)) return false;
650
+ for (const w of [guide.config.schedule, guide.config.survey]) {
651
+ if (!w) continue;
652
+ if (w.startAt && now < Date.parse(w.startAt)) return false;
653
+ if (w.endAt && now > Date.parse(w.endAt)) return false;
654
+ }
655
+ return true;
656
+ }
657
+ var MINUTE = 60 * 1e3;
658
+ function countsTowardThrottle(guide) {
659
+ return isExclusiveGuide(guide) && !guide.config.frequency.ignoreThrottling;
660
+ }
661
+ function isThrottleEligible(settings, launches, now = Date.now()) {
662
+ if (!settings || !settings.enabled) return true;
663
+ const times = launches.map((l) => Date.parse(l)).filter((t) => !Number.isNaN(t));
664
+ const windowMs = Math.max(1, settings.windowHours) * HOUR;
665
+ if (times.filter((t) => now - t < windowMs).length >= Math.max(1, settings.maxGuides)) return false;
666
+ if (settings.minGapMinutes > 0 && times.some((t) => now - t < settings.minGapMinutes * MINUTE)) return false;
418
667
  return true;
419
668
  }
669
+ function pruneLaunches(launches, settings, now = Date.now()) {
670
+ const keepMs = Math.max(settings?.windowHours ?? 24, 1) * HOUR + (settings?.minGapMinutes ?? 0) * MINUTE;
671
+ return launches.filter((l) => {
672
+ const t = Date.parse(l);
673
+ return !Number.isNaN(t) && now - t < keepMs;
674
+ }).slice(-100);
675
+ }
420
676
  function dismissedAfterMerge(local, server) {
421
677
  if (server.dismissResetAt && server.dismissResetAt !== local?.dismissResetAt) return server.dismissedAt ?? null;
422
678
  return local?.dismissedAt ?? server.dismissedAt ?? null;
@@ -427,14 +683,21 @@ function dismissedAfterMerge(local, server) {
427
683
  Emitter,
428
684
  EventQueue,
429
685
  KEYS,
686
+ Outbox,
687
+ ServerHealth,
430
688
  areMutuallyExclusive,
431
689
  backoffMs,
690
+ countsTowardThrottle,
432
691
  dismissedAfterMerge,
433
692
  isExclusiveGuide,
434
693
  isFrequencyEligible,
694
+ isServerFailure,
695
+ isThrottleEligible,
435
696
  isWithinSchedule,
436
697
  memoryStore,
698
+ parseRetryAfter,
437
699
  postWithRetry,
700
+ pruneLaunches,
438
701
  readJson,
439
702
  sleep,
440
703
  writeJson