@guidelytech/sdk-core 0.10.0 → 0.12.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/dist/{capture-DVJyQ2JZ.d.cts → capture-4EgpjK6Z.d.cts} +2 -2
- package/dist/{capture-369s4YYT.d.ts → capture-C-4R56G0.d.ts} +2 -2
- package/dist/capture-CgN69Lxq.d.cts +100 -0
- package/dist/capture-Csz721-A.d.ts +100 -0
- package/dist/capture.cjs +5 -1
- package/dist/capture.cjs.map +1 -1
- package/dist/capture.d.cts +3 -3
- package/dist/capture.d.ts +3 -3
- package/dist/capture.js +1 -1
- package/dist/{chunk-GDJB466J.js → chunk-2E2YUQAG.js} +29 -6
- package/dist/chunk-2E2YUQAG.js.map +1 -0
- package/dist/{chunk-C4WWSF67.js → chunk-JUSM7J5N.js} +3 -1
- package/dist/{chunk-C4WWSF67.js.map → chunk-JUSM7J5N.js.map} +1 -1
- package/dist/chunk-XML74K2P.js +378 -0
- package/dist/chunk-XML74K2P.js.map +1 -0
- package/dist/chunk-ZAF2KRJA.js +334 -0
- package/dist/chunk-ZAF2KRJA.js.map +1 -0
- package/dist/headless.cjs +35 -5
- package/dist/headless.cjs.map +1 -1
- package/dist/headless.d.cts +6 -5
- package/dist/headless.d.ts +6 -5
- package/dist/headless.js +9 -3
- package/dist/health-DjZ2gwYa.d.cts +92 -0
- package/dist/health-DjZ2gwYa.d.ts +92 -0
- package/dist/{health-DFHUstWd.d.cts → health-sbP9JwTE.d.cts} +2 -0
- package/dist/{health-DFHUstWd.d.ts → health-sbP9JwTE.d.ts} +2 -0
- package/dist/{http-DJd8jRhK.d.ts → http-BXys2d-j.d.ts} +1 -1
- package/dist/{http-D0dCcpLN.d.cts → http-Cb6KYYFv.d.cts} +1 -1
- package/dist/http-D047Ngxk.d.ts +61 -0
- package/dist/http-zOI8d2c2.d.cts +61 -0
- package/dist/index.cjs +1638 -1047
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +77 -9
- package/dist/index.d.ts +77 -9
- package/dist/index.js +763 -202
- package/dist/index.js.map +1 -1
- package/dist/recorder.cjs.map +1 -1
- package/dist/recorder.d.cts +1 -1
- package/dist/recorder.d.ts +1 -1
- package/dist/recorder.js +1 -1
- package/dist/{types-B5ecgHUV.d.cts → types-BDlebXrm.d.ts} +59 -5
- package/dist/types-Bkw8ErmO.d.cts +314 -0
- package/dist/{types-BtPovimB.d.ts → types-Dy_uPu6S.d.ts} +59 -5
- package/dist/types-Mtlmlj5C.d.cts +314 -0
- package/package.json +4 -4
- package/dist/chunk-GDJB466J.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CaptureStepInput } from '@guidelytech/shared';
|
|
2
|
-
import { A as Api } from './http-
|
|
3
|
-
import { K as KeyValueStore } from './health-
|
|
2
|
+
import { A as Api } from './http-zOI8d2c2.cjs';
|
|
3
|
+
import { K as KeyValueStore } from './health-DjZ2gwYa.cjs';
|
|
4
4
|
|
|
5
5
|
/** What the SDK remembers about a capture session in this tab (`guidely:capture` in sessionStorage). */
|
|
6
6
|
interface CaptureMarker {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CaptureStepInput } from '@guidelytech/shared';
|
|
2
|
-
import { A as Api } from './http-
|
|
3
|
-
import { K as KeyValueStore } from './health-
|
|
2
|
+
import { A as Api } from './http-BXys2d-j.js';
|
|
3
|
+
import { K as KeyValueStore } from './health-DjZ2gwYa.js';
|
|
4
4
|
|
|
5
5
|
/** What the SDK remembers about a capture session in this tab (`guidely:capture` in sessionStorage). */
|
|
6
6
|
interface CaptureMarker {
|
|
@@ -0,0 +1,100 @@
|
|
|
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 };
|
|
@@ -0,0 +1,100 @@
|
|
|
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 };
|
package/dist/capture.cjs
CHANGED
|
@@ -78,6 +78,8 @@ var KEYS = {
|
|
|
78
78
|
queue: (key) => `guidely:queue:${key}`,
|
|
79
79
|
/** Survey answers and guide/checklist progress not yet accepted by the server. */
|
|
80
80
|
outbox: (key) => `guidely:outbox:${key}`,
|
|
81
|
+
/** Agent Analytics turns not yet accepted by the server. */
|
|
82
|
+
agentOutbox: (key) => `guidely:agents:${key}`,
|
|
81
83
|
session: "guidely:session",
|
|
82
84
|
active: "guidely:active",
|
|
83
85
|
authoring: "guidely:authoring",
|
|
@@ -87,7 +89,9 @@ var KEYS = {
|
|
|
87
89
|
/** Messenger conversations this browser can read: [{ id, token }]. */
|
|
88
90
|
conversations: (key) => `guidely:conversations:${key}`,
|
|
89
91
|
/** Announcement ids opened in the messenger's News tab. */
|
|
90
|
-
newsSeen: (key) => `guidely:news:${key}
|
|
92
|
+
newsSeen: (key) => `guidely:news:${key}`,
|
|
93
|
+
/** Where the visitor dragged the messenger launcher ({ side, y }). */
|
|
94
|
+
launcher: (key) => `guidely:launcher:${key}`
|
|
91
95
|
};
|
|
92
96
|
|
|
93
97
|
// src/capture.ts
|
package/dist/capture.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/capture.ts","../src/http.ts","../src/storage.ts"],"sourcesContent":["import type { CaptureSessionInfo, CaptureStepInput } from \"@guidelytech/shared\";\nimport { CAPTURE_SCREENSHOT_MAX_BYTES, randomId } from \"@guidelytech/shared/runtime\";\nimport { encodeScreenshot, screenshotDataUrl, startCapture, type CapturedStep, type CaptureSession } from \"@guidelytech/guide-runtime/capture\";\nimport type { CaptureMarker } from \"./capture-token\";\nimport { sleep, withRetry, type Api, type ApiResponse } from \"./http\";\nimport { KEYS, readJson, writeJson, type KeyValueStore } from \"./storage\";\n\n/**\n * How-to capture bridge (loaded on demand): verifies the capture session, runs the runtime's\n * recorder toolbar, uploads steps with their screenshots in capture order and tells the dashboard\n * window (`window.opener`) about progress.\n */\n\n/** Keeps the capture session alive on the server (same cadence as authoring). */\nexport const CAPTURE_HEARTBEAT_MS = 15000;\n\n/** A full page load this soon after a recorded interaction was caused by it: no navigate step. */\nexport const LOAD_AFTER_ACTION_MS = 8000;\n/** How long Done waits for queued uploads before finishing anyway. */\nexport const FINISH_DRAIN_MS = 20000;\n/** Pause before retrying uploads after every attempt failed (offline, server down). */\nexport const UPLOAD_RETRY_LATER_MS = 10000;\n\n/** Messages the SDK posts to the dashboard window (`window.opener`, target origin `dashboardOrigin`). */\nexport type CaptureOutgoingMessage =\n | { type: \"guidely:capture-ready\"; sessionId: string; url: string }\n | { type: \"guidely:capture-step\"; sessionId: string; stepCount: number }\n | { type: \"guidely:capture-finished\"; sessionId: string; howToId: string; cancelled: boolean };\n\nexport interface CaptureBridgeOptions {\n api: Api;\n sessionStore: KeyValueStore;\n marker: CaptureMarker;\n /** Comma-joined mask selectors (project setting + SDK option). */\n maskSelector: string;\n onError: (err: unknown) => void;\n onActive: (active: boolean) => void;\n}\n\ninterface QueuedStep {\n step: CaptureStepInput;\n frame: CapturedStep[\"frame\"];\n blob?: Blob | null;\n /** Screenshot saved while the page unloaded (uploaded after the next page load). */\n shot?: string;\n}\n\ninterface PendingStep {\n step: CaptureStepInput;\n shot?: string;\n}\n\n/** After a full page load: was it caused by the last recorded interaction (so no navigate step)? */\nexport function loadFollowsAction(marker: Pick<CaptureMarker, \"lastAction\" | \"lastStepAt\">, now = Date.now()): boolean {\n return !!marker.lastAction && marker.lastAction !== \"navigate\" && now - (marker.lastStepAt ?? 0) < LOAD_AFTER_ACTION_MS;\n}\n\nfunction dataUrlToBlob(url: string): Blob | null {\n try {\n const comma = url.indexOf(\",\");\n const type = /^data:([^;,]+)/.exec(url)?.[1] || \"image/jpeg\";\n const bin = atob(url.slice(comma + 1));\n const bytes = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);\n return new Blob([bytes], { type });\n } catch {\n return null;\n }\n}\n\nconst EXT: Record<string, string> = { \"image/webp\": \"webp\", \"image/jpeg\": \"jpg\", \"image/png\": \"png\" };\n\n/** Multipart body for `POST /capture/steps`: `step` (JSON) and optional `screenshot`. */\nexport function captureStepForm(step: CaptureStepInput, screenshot: Blob | null): FormData {\n const form = new FormData();\n form.append(\"step\", JSON.stringify(step));\n if (screenshot) form.append(\"screenshot\", screenshot, `step.${EXT[screenshot.type] ?? \"webp\"}`);\n return form;\n}\n\nexport class CaptureBridge {\n private info: CaptureSessionInfo | null = null;\n private session: CaptureSession | null = null;\n private heartbeat: ReturnType<typeof setInterval> | null = null;\n private retryTimer: ReturnType<typeof setTimeout> | null = null;\n private queue: QueuedStep[] = [];\n private pumping = false;\n private active = false;\n private finishing = false;\n private marker: CaptureMarker;\n private readonly onPageHide = () => this.saveForReload();\n\n constructor(private readonly opts: CaptureBridgeOptions) {\n this.marker = { ...opts.marker };\n }\n\n isActive(): boolean {\n return this.active;\n }\n\n private get token(): string {\n return this.marker.token;\n }\n\n /** Verifies the session and starts recording. Resolves once the toolbar is up (or the session was rejected). */\n async start(): Promise<void> {\n try {\n const res = await this.opts.api.get<CaptureSessionInfo>(\"/capture/session\", { params: { token: this.token } });\n if (!res.ok || !res.data) return this.reject(`[Guidely] capture session invalid or expired (${res.status})`);\n this.info = res.data;\n if (Date.parse(this.info.expiresAt) < Date.now()) return this.reject(\"[Guidely] capture session expired\");\n const pending = readJson<PendingStep[]>(this.opts.sessionStore, KEYS.capturePending, []);\n this.queue = (Array.isArray(pending) ? pending : []).filter((p) => p && p.step).map((p) => ({ step: p.step, frame: null, shot: p.shot }));\n this.active = true;\n this.opts.onActive(true);\n this.session = startCapture({\n title: this.info.howToTitle,\n stepCount: this.info.stepCount + this.queue.length,\n screenshots: this.info.screenshots,\n maskSelector: this.opts.maskSelector,\n resume: this.marker.started ? { navigate: !loadFollowsAction(this.marker), screenshots: !!this.marker.screenshots } : undefined,\n onStart: ({ screenshots }) => this.saveMarker({ started: true, screenshots }),\n onStep: (s) => this.enqueue(s),\n onFinish: () => void this.finish(false),\n onCancel: () => void this.finish(true),\n });\n this.heartbeat = setInterval(() => void this.beat(), CAPTURE_HEARTBEAT_MS);\n window.addEventListener(\"pagehide\", this.onPageHide);\n this.post({ type: \"guidely:capture-ready\", sessionId: this.info.id, url: window.location.href });\n void this.pump();\n } catch (err) {\n this.opts.onError(err);\n }\n }\n\n private reject(message: string): void {\n this.clearMarker();\n this.opts.onError(new Error(message));\n }\n\n private saveMarker(patch: Partial<CaptureMarker>): void {\n this.marker = { ...this.marker, ...patch };\n writeJson(this.opts.sessionStore, KEYS.capture, this.marker);\n }\n\n private clearMarker(): void {\n this.opts.sessionStore.remove(KEYS.capture);\n this.opts.sessionStore.remove(KEYS.capturePending);\n }\n\n /** Persists the steps still to upload (JSON only; screenshots are added on page hide). */\n private savePending(): void {\n if (!this.queue.length) this.opts.sessionStore.remove(KEYS.capturePending);\n else writeJson(this.opts.sessionStore, KEYS.capturePending, this.queue.map((q): PendingStep => (q.shot ? { step: q.step, shot: q.shot } : { step: q.step })));\n }\n\n /** The page is unloading with uploads in flight: keep their screenshots for the next page. */\n private saveForReload(): void {\n if (!this.active || !this.queue.length) return;\n for (const q of this.queue) if (!q.shot && q.frame && !(q.frame instanceof Promise)) q.shot = screenshotDataUrl(q.frame) ?? undefined;\n this.savePending();\n }\n\n private enqueue(captured: CapturedStep): void {\n if (this.finishing) return;\n // Same object: a deferred frame still updates its highlight and redaction count before upload.\n const step: CaptureStepInput = Object.assign(captured.step, { clientId: randomId(16) });\n this.queue.push({ step, frame: captured.frame });\n this.saveMarker({ lastStepAt: Date.now(), lastAction: step.action });\n this.savePending();\n void this.pump();\n }\n\n /** Uploads queued steps one at a time, in capture order. */\n private async pump(): Promise<void> {\n if (this.pumping || !this.info) return;\n this.pumping = true;\n try {\n while (this.queue.length && this.info) {\n const item = this.queue[0]!;\n if (item.frame instanceof Promise) item.frame = await item.frame.catch(() => null);\n if (item.blob === undefined) item.blob = item.shot ? dataUrlToBlob(item.shot) : item.frame ? await encodeScreenshot(item.frame, { maxBytes: CAPTURE_SCREENSHOT_MAX_BYTES }) : null;\n const res = await this.upload(item);\n if (!this.info) return;\n if (!res) {\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.retryTimer = setTimeout(() => void this.pump(), UPLOAD_RETRY_LATER_MS);\n return;\n }\n this.queue.shift();\n this.savePending();\n if (res.status === 401 || res.status === 403 || res.status === 404 || res.status === 410) {\n this.opts.onError(new Error(`[Guidely] capture session ended (${res.status})`));\n this.teardown(true);\n return;\n }\n if (res.ok && res.data) this.post({ type: \"guidely:capture-step\", sessionId: this.info.id, stepCount: res.data.stepCount });\n else if (!res.ok) this.opts.onError(new Error(`[Guidely] capture step rejected (${res.status})`));\n }\n } catch (err) {\n this.opts.onError(err);\n } finally {\n this.pumping = false;\n }\n }\n\n private async upload(item: QueuedStep): Promise<ApiResponse<{ id: string; position: number; stepCount: number }> | null> {\n const send = (shot: Blob | null) =>\n withRetry(() => this.opts.api.postForm<{ id: string; position: number; stepCount: number }>(\"/capture/steps\", captureStepForm(item.step, shot), { params: { token: this.token }, timeoutMs: 60000 }), 4, 1000);\n const res = await send(item.blob ?? null);\n // Too large or unreadable image: keep the step without it.\n if (res && item.blob && (res.status === 413 || res.status === 415)) return send(null);\n return res;\n }\n\n private async beat(): Promise<void> {\n try {\n const res = await this.opts.api.post(\"/capture/session/heartbeat\", {}, { params: { token: this.token } });\n if (res.status === 401 || res.status === 410) {\n this.opts.onError(new Error(`[Guidely] capture session ended (${res.status})`));\n this.teardown(true);\n }\n } catch {\n /* offline: the next beat retries */\n }\n }\n\n /** Done (waits for queued uploads) or Cancel (drops them); either way the dashboard is told. */\n private async finish(cancelled: boolean): Promise<void> {\n if (this.finishing || !this.info) return;\n this.finishing = true;\n const info = this.info;\n if (cancelled) {\n this.queue = [];\n this.savePending();\n } else {\n this.session?.setSaving(true);\n if (this.retryTimer) clearTimeout(this.retryTimer);\n void this.pump();\n const deadline = Date.now() + FINISH_DRAIN_MS;\n while ((this.queue.length || this.pumping) && this.info && Date.now() < deadline) await sleep(100);\n }\n let howToId = info.howToId;\n try {\n const res = await withRetry(() => this.opts.api.post<{ ok: boolean; howToId?: string }>(\"/capture/session/finish\", { cancelled }, { params: { token: this.token } }), 3, 500);\n if (res?.data?.howToId) howToId = res.data.howToId;\n } catch (err) {\n this.opts.onError(err);\n }\n this.post({ type: \"guidely:capture-finished\", sessionId: info.id, howToId, cancelled });\n this.teardown(true);\n }\n\n private post(message: CaptureOutgoingMessage): void {\n if (!this.info) return;\n try {\n window.opener?.postMessage(message, this.info.dashboardOrigin);\n } catch {\n /* opener may be gone */\n }\n }\n\n private teardown(clearMarker: boolean): void {\n if (this.heartbeat) clearInterval(this.heartbeat);\n this.heartbeat = null;\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.retryTimer = null;\n window.removeEventListener(\"pagehide\", this.onPageHide);\n this.session?.stop();\n this.session = null;\n if (clearMarker) this.clearMarker();\n this.info = null;\n this.queue = [];\n if (!this.active) return;\n this.active = false;\n this.opts.onActive(false);\n }\n\n /** Removes the toolbar and stops uploading but keeps the session marker (the SDK was destroyed; a new client resumes). */\n destroy(): void {\n this.saveForReload();\n this.teardown(false);\n }\n}\n\n/** What the on-demand capture chunk provides (`window.__guidelyCapture` in the script-tag build). */\nexport interface CaptureApi {\n createBridge(options: CaptureBridgeOptions): CaptureBridge;\n}\n\nexport const capture: CaptureApi = { createBridge: (options) => new CaptureBridge(options) };\n","import { isServerFailure, parseRetryAfter, ServerHealth } from \"./health\";\n\nexport interface ApiResponse<T> {\n status: number;\n ok: boolean;\n data: T | null;\n etag: string | null;\n}\n\nexport type FetchLike = typeof fetch;\n\n/** Reply streams: the response must start within this long, and then never go quiet longer than the idle limit (the server sends a keepalive every 15 s). */\nexport const STREAM_RESPONSE_TIMEOUT_MS = 30_000;\nexport const STREAM_IDLE_TIMEOUT_MS = 60_000;\n\n/** Thin HTTP client for the public SDK API. Adds the public key as query + header. */\nexport class Api {\n /** Reachability of the API, fed by every answer (see {@link ServerHealth}). */\n readonly health: ServerHealth;\n\n constructor(\n private readonly baseUrl: string,\n private readonly key: string,\n private readonly fetchImpl?: FetchLike,\n health?: ServerHealth,\n ) {\n this.health = health ?? new ServerHealth();\n }\n\n /** Feeds an answer (or a failed request, `null`) into {@link health}. */\n private observe(res: Response | null): void {\n if (!res) this.health.failure();\n else if (isServerFailure(res.status)) this.health.failure(parseRetryAfter(res.headers?.get?.(\"retry-after\")));\n else this.health.success();\n }\n\n url(path: string, params: Record<string, string | undefined> = {}): string {\n // Built by hand rather than with URL/searchParams, which React Native does not implement.\n const query = Object.entries({ key: this.key, ...params })\n .filter((e): e is [string, string] => e[1] != null)\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join(\"&\");\n return `${this.baseUrl.replace(/\\/$/, \"\")}/api/v1/sdk${path}?${query}`;\n }\n\n private get fetcher(): FetchLike | null {\n if (this.fetchImpl) return this.fetchImpl;\n return typeof fetch === \"function\" ? fetch.bind(globalThis) : null;\n }\n\n async request<T>(method: \"GET\" | \"POST\", path: string, options: { body?: unknown; etag?: string | null; params?: Record<string, string | undefined>; keepalive?: boolean; timeoutMs?: number; headers?: Record<string, string> } = {}): Promise<ApiResponse<T>> {\n const f = this.fetcher;\n if (!f) throw new Error(\"fetch is not available\");\n const headers: Record<string, string> = { ...options.headers, \"X-Guidely-Key\": this.key, Accept: \"application/json\" };\n // Multipart bodies set their own Content-Type (with the boundary).\n const form = typeof FormData !== \"undefined\" && options.body instanceof FormData;\n if (options.body !== undefined && !form) headers[\"Content-Type\"] = \"application/json\";\n if (options.etag) headers[\"If-None-Match\"] = options.etag;\n const ac = typeof AbortController !== \"undefined\" ? new AbortController() : null;\n const timer = ac ? setTimeout(() => ac.abort(), options.timeoutMs ?? 10000) : null;\n try {\n let res: Response;\n try {\n res = await f(this.url(path, options.params), {\n method,\n headers,\n body: options.body === undefined ? undefined : form ? (options.body as FormData) : JSON.stringify(options.body),\n keepalive: options.keepalive,\n signal: ac?.signal,\n credentials: \"omit\",\n mode: \"cors\",\n });\n } catch (err) {\n this.observe(null);\n throw err;\n }\n this.observe(res);\n let data: T | null = null;\n if (res.status !== 304 && res.status !== 204) {\n try {\n data = (await res.json()) as T;\n } catch {\n data = null;\n }\n }\n return { status: res.status, ok: res.ok, data, etag: res.headers?.get?.(\"etag\") ?? null };\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n\n get<T>(path: string, options?: { etag?: string | null; params?: Record<string, string | undefined>; headers?: Record<string, string> }): Promise<ApiResponse<T>> {\n return this.request<T>(\"GET\", path, options);\n }\n\n post<T>(path: string, body: unknown, options?: { params?: Record<string, string | undefined>; keepalive?: boolean; headers?: Record<string, string> }): Promise<ApiResponse<T>> {\n return this.request<T>(\"POST\", path, { body, ...options });\n }\n\n /** Multipart POST (file uploads). No Content-Type header: the browser adds it with the boundary. */\n postForm<T>(path: string, form: FormData, options?: { params?: Record<string, string | undefined>; timeoutMs?: number }): Promise<ApiResponse<T>> {\n return this.request<T>(\"POST\", path, { body: form, ...options });\n }\n\n /**\n * POST that may answer with server-sent events. Each event is passed to `onEvent`; a JSON answer is\n * returned instead. Scout replies can take a while, so there is no overall timeout: the response\n * must start within 30 s and then never go quiet for more than 60 s (the server sends keepalives),\n * otherwise the request is aborted and rejects.\n */\n async stream<T>(path: string, body: unknown, onEvent: (event: string, data: unknown) => void, headers: Record<string, string> = {}): Promise<ApiResponse<T>> {\n const f = this.fetcher;\n if (!f) throw new Error(\"fetch is not available\");\n const ac = typeof AbortController !== \"undefined\" ? new AbortController() : null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const arm = (ms: number) => {\n if (!ac) return;\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => ac.abort(), ms);\n };\n arm(STREAM_RESPONSE_TIMEOUT_MS);\n try {\n let res: Response;\n try {\n res = await f(this.url(path), {\n method: \"POST\",\n headers: { ...headers, \"X-Guidely-Key\": this.key, Accept: \"text/event-stream, application/json\", \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: ac?.signal,\n credentials: \"omit\",\n mode: \"cors\",\n });\n } catch (err) {\n this.observe(null);\n throw err;\n }\n this.observe(res);\n const type = res.headers?.get?.(\"content-type\") ?? \"\";\n if (!type.includes(\"text/event-stream\") || !res.body) {\n let data: T | null = null;\n try {\n data = (await res.json()) as T;\n } catch {\n data = null;\n }\n return { status: res.status, ok: res.ok, data, etag: null };\n }\n arm(STREAM_IDLE_TIMEOUT_MS);\n await readEventStream(res.body, onEvent, () => arm(STREAM_IDLE_TIMEOUT_MS));\n return { status: res.status, ok: res.ok, data: null, etag: null };\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n\n /** `navigator.sendBeacon` when available (page unload); returns false when it could not be queued. */\n beacon(path: string, body: unknown): boolean {\n try {\n if (typeof navigator === \"undefined\" || typeof navigator.sendBeacon !== \"function\") return false;\n // text/plain is a CORS-safelisted type: cross-origin beacons need no preflight (which\n // browsers drop during unload). The API parses the body regardless of content type.\n const blob = new Blob([JSON.stringify(body)], { type: \"text/plain;charset=UTF-8\" });\n return navigator.sendBeacon(this.url(path), blob);\n } catch {\n return false;\n }\n }\n}\n\nexport const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n\n/** Exponential backoff helper: 1s → 2s → 4s … capped. */\nexport function backoffMs(attempt: number, baseMs = 1000, maxMs = 30000): number {\n return Math.min(maxMs, baseMs * 2 ** Math.max(0, attempt));\n}\n\n/**\n * Sends with bounded retries: network errors, 429 and 5xx are retried with backoff; success and\n * other 4xx answers are returned as they are. Null when every attempt failed.\n */\nexport async function withRetry<T>(send: () => Promise<ApiResponse<T>>, attempts = 3, baseMs = 500): Promise<ApiResponse<T> | null> {\n for (let i = 0; i < attempts; i++) {\n try {\n const res = await send();\n if (res.ok || (res.status >= 400 && res.status < 500 && res.status !== 429)) return res;\n } catch {\n /* network error → retry */\n }\n if (i < attempts - 1) await sleep(backoffMs(i, baseMs, 8000));\n }\n return null;\n}\n\n/** Fire-and-forget POST with bounded retries (used for state sync; never blocks UI). */\nexport function postWithRetry<T>(api: Api, path: string, body: unknown, attempts = 3, baseMs = 500): Promise<ApiResponse<T> | null> {\n return withRetry(() => api.post<T>(path, body), attempts, baseMs);\n}\n\n/** Parses a `text/event-stream` body (`event:` + single-line JSON `data:`; comment lines ignored). `onChunk` runs whenever bytes arrive. */\nexport async function readEventStream(body: ReadableStream<Uint8Array>, onEvent: (event: string, data: unknown) => void, onChunk?: () => void): Promise<void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n const dispatch = (raw: string) => {\n let event = \"message\";\n const data: string[] = [];\n for (const line of raw.split(\"\\n\")) {\n if (!line || line.startsWith(\":\")) continue;\n const i = line.indexOf(\":\");\n const field = i < 0 ? line : line.slice(0, i);\n const value = i < 0 ? \"\" : line.slice(i + 1).replace(/^ /, \"\");\n if (field === \"event\") event = value;\n else if (field === \"data\") data.push(value);\n }\n if (!data.length) return;\n try {\n onEvent(event, JSON.parse(data.join(\"\\n\")));\n } catch {\n /* ignore malformed events */\n }\n };\n for (;;) {\n const { done, value } = await reader.read();\n if (value) onChunk?.();\n if (value) buffer += decoder.decode(value, { stream: true }).replace(/\\r\\n?/g, \"\\n\");\n let sep: number;\n while ((sep = buffer.indexOf(\"\\n\\n\")) >= 0) {\n dispatch(buffer.slice(0, sep));\n buffer = buffer.slice(sep + 2);\n }\n if (done) break;\n }\n if (buffer.trim()) dispatch(buffer);\n}\n","export type StorageKind = \"local\" | \"session\" | \"memory\";\n\n/** Minimal synchronous key/value store; never throws (private mode, quota, SSR). */\nexport interface KeyValueStore {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n}\n\nexport function memoryStore(): KeyValueStore {\n const map = new Map<string, string>();\n return { get: (k) => map.get(k) ?? null, set: (k, v) => void map.set(k, v), remove: (k) => void map.delete(k) };\n}\n\nfunction webStore(area: \"localStorage\" | \"sessionStorage\"): KeyValueStore | null {\n try {\n if (typeof window === \"undefined\") return null;\n const s = window[area];\n if (!s) return null;\n const probe = \"__guidely_probe__\";\n s.setItem(probe, \"1\");\n s.removeItem(probe);\n return {\n get: (k) => {\n try {\n return s.getItem(k);\n } catch {\n return null;\n }\n },\n set: (k, v) => {\n try {\n s.setItem(k, v);\n } catch {\n /* quota / private mode */\n }\n },\n remove: (k) => {\n try {\n s.removeItem(k);\n } catch {\n /* ignore */\n }\n },\n };\n } catch {\n return null;\n }\n}\n\n/** Creates a store of the requested kind, degrading to memory when unavailable. */\nexport function createStorage(kind: StorageKind = \"local\"): KeyValueStore {\n if (kind === \"memory\") return memoryStore();\n return webStore(kind === \"local\" ? \"localStorage\" : \"sessionStorage\") ?? memoryStore();\n}\n\nexport function readJson<T>(store: KeyValueStore, key: string, fallback: T): T {\n const raw = store.get(key);\n if (raw == null) return fallback;\n try {\n return JSON.parse(raw) as T;\n } catch {\n return fallback;\n }\n}\n\nexport function writeJson(store: KeyValueStore, key: string, value: unknown): void {\n try {\n store.set(key, JSON.stringify(value));\n } catch {\n /* ignore */\n }\n}\n\n/** Storage keys used by the SDK (documented for integrators). */\nexport const KEYS = {\n anon: \"guidely:anon\",\n seen: \"guidely:seen\",\n config: (key: string) => `guidely:config:${key}`,\n etag: (key: string) => `guidely:etag:${key}`,\n state: (key: string) => `guidely:state:${key}`,\n user: (key: string) => `guidely:user:${key}`,\n queue: (key: string) => `guidely:queue:${key}`,\n /** Survey answers and guide/checklist progress not yet accepted by the server. */\n outbox: (key: string) => `guidely:outbox:${key}`,\n session: \"guidely:session\",\n active: \"guidely:active\",\n authoring: \"guidely:authoring\",\n /** How-to capture session marker ({ token, … }) and its not-yet-uploaded steps. */\n capture: \"guidely:capture\",\n capturePending: \"guidely:capture:pending\",\n /** Messenger conversations this browser can read: [{ id, token }]. */\n conversations: (key: string) => `guidely:conversations:${key}`,\n /** Announcement ids opened in the messenger's News tab. */\n newsSeen: (key: string) => `guidely:news:${key}`,\n}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eAAe;AAAA,IAC/D,QAAQ;AAAA,IAER;AAAA,EACF;AAAA,EAEQ,SAAS,aAA4B;AAC3C,QAAI,KAAK,UAAW,eAAc,KAAK,SAAS;AAChD,SAAK,YAAY;AACjB,QAAI,KAAK,WAAY,cAAa,KAAK,UAAU;AACjD,SAAK,aAAa;AAClB,WAAO,oBAAoB,YAAY,KAAK,UAAU;AACtD,SAAK,SAAS,KAAK;AACnB,SAAK,UAAU;AACf,QAAI,YAAa,MAAK,YAAY;AAClC,SAAK,OAAO;AACZ,SAAK,QAAQ,CAAC;AACd,QAAI,CAAC,KAAK,OAAQ;AAClB,SAAK,SAAS;AACd,SAAK,KAAK,SAAS,KAAK;AAAA,EAC1B;AAAA;AAAA,EAGA,UAAgB;AACd,SAAK,cAAc;AACnB,SAAK,SAAS,KAAK;AAAA,EACrB;AACF;AAOO,IAAM,UAAsB,EAAE,cAAc,CAAC,YAAY,IAAI,cAAc,OAAO,EAAE;","names":["import_runtime"]}
|
|
1
|
+
{"version":3,"sources":["../src/capture.ts","../src/http.ts","../src/storage.ts"],"sourcesContent":["import type { CaptureSessionInfo, CaptureStepInput } from \"@guidelytech/shared\";\nimport { CAPTURE_SCREENSHOT_MAX_BYTES, randomId } from \"@guidelytech/shared/runtime\";\nimport { encodeScreenshot, screenshotDataUrl, startCapture, type CapturedStep, type CaptureSession } from \"@guidelytech/guide-runtime/capture\";\nimport type { CaptureMarker } from \"./capture-token\";\nimport { sleep, withRetry, type Api, type ApiResponse } from \"./http\";\nimport { KEYS, readJson, writeJson, type KeyValueStore } from \"./storage\";\n\n/**\n * How-to capture bridge (loaded on demand): verifies the capture session, runs the runtime's\n * recorder toolbar, uploads steps with their screenshots in capture order and tells the dashboard\n * window (`window.opener`) about progress.\n */\n\n/** Keeps the capture session alive on the server (same cadence as authoring). */\nexport const CAPTURE_HEARTBEAT_MS = 15000;\n\n/** A full page load this soon after a recorded interaction was caused by it: no navigate step. */\nexport const LOAD_AFTER_ACTION_MS = 8000;\n/** How long Done waits for queued uploads before finishing anyway. */\nexport const FINISH_DRAIN_MS = 20000;\n/** Pause before retrying uploads after every attempt failed (offline, server down). */\nexport const UPLOAD_RETRY_LATER_MS = 10000;\n\n/** Messages the SDK posts to the dashboard window (`window.opener`, target origin `dashboardOrigin`). */\nexport type CaptureOutgoingMessage =\n | { type: \"guidely:capture-ready\"; sessionId: string; url: string }\n | { type: \"guidely:capture-step\"; sessionId: string; stepCount: number }\n | { type: \"guidely:capture-finished\"; sessionId: string; howToId: string; cancelled: boolean };\n\nexport interface CaptureBridgeOptions {\n api: Api;\n sessionStore: KeyValueStore;\n marker: CaptureMarker;\n /** Comma-joined mask selectors (project setting + SDK option). */\n maskSelector: string;\n onError: (err: unknown) => void;\n onActive: (active: boolean) => void;\n}\n\ninterface QueuedStep {\n step: CaptureStepInput;\n frame: CapturedStep[\"frame\"];\n blob?: Blob | null;\n /** Screenshot saved while the page unloaded (uploaded after the next page load). */\n shot?: string;\n}\n\ninterface PendingStep {\n step: CaptureStepInput;\n shot?: string;\n}\n\n/** After a full page load: was it caused by the last recorded interaction (so no navigate step)? */\nexport function loadFollowsAction(marker: Pick<CaptureMarker, \"lastAction\" | \"lastStepAt\">, now = Date.now()): boolean {\n return !!marker.lastAction && marker.lastAction !== \"navigate\" && now - (marker.lastStepAt ?? 0) < LOAD_AFTER_ACTION_MS;\n}\n\nfunction dataUrlToBlob(url: string): Blob | null {\n try {\n const comma = url.indexOf(\",\");\n const type = /^data:([^;,]+)/.exec(url)?.[1] || \"image/jpeg\";\n const bin = atob(url.slice(comma + 1));\n const bytes = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);\n return new Blob([bytes], { type });\n } catch {\n return null;\n }\n}\n\nconst EXT: Record<string, string> = { \"image/webp\": \"webp\", \"image/jpeg\": \"jpg\", \"image/png\": \"png\" };\n\n/** Multipart body for `POST /capture/steps`: `step` (JSON) and optional `screenshot`. */\nexport function captureStepForm(step: CaptureStepInput, screenshot: Blob | null): FormData {\n const form = new FormData();\n form.append(\"step\", JSON.stringify(step));\n if (screenshot) form.append(\"screenshot\", screenshot, `step.${EXT[screenshot.type] ?? \"webp\"}`);\n return form;\n}\n\nexport class CaptureBridge {\n private info: CaptureSessionInfo | null = null;\n private session: CaptureSession | null = null;\n private heartbeat: ReturnType<typeof setInterval> | null = null;\n private retryTimer: ReturnType<typeof setTimeout> | null = null;\n private queue: QueuedStep[] = [];\n private pumping = false;\n private active = false;\n private finishing = false;\n private marker: CaptureMarker;\n private readonly onPageHide = () => this.saveForReload();\n\n constructor(private readonly opts: CaptureBridgeOptions) {\n this.marker = { ...opts.marker };\n }\n\n isActive(): boolean {\n return this.active;\n }\n\n private get token(): string {\n return this.marker.token;\n }\n\n /** Verifies the session and starts recording. Resolves once the toolbar is up (or the session was rejected). */\n async start(): Promise<void> {\n try {\n const res = await this.opts.api.get<CaptureSessionInfo>(\"/capture/session\", { params: { token: this.token } });\n if (!res.ok || !res.data) return this.reject(`[Guidely] capture session invalid or expired (${res.status})`);\n this.info = res.data;\n if (Date.parse(this.info.expiresAt) < Date.now()) return this.reject(\"[Guidely] capture session expired\");\n const pending = readJson<PendingStep[]>(this.opts.sessionStore, KEYS.capturePending, []);\n this.queue = (Array.isArray(pending) ? pending : []).filter((p) => p && p.step).map((p) => ({ step: p.step, frame: null, shot: p.shot }));\n this.active = true;\n this.opts.onActive(true);\n this.session = startCapture({\n title: this.info.howToTitle,\n stepCount: this.info.stepCount + this.queue.length,\n screenshots: this.info.screenshots,\n maskSelector: this.opts.maskSelector,\n resume: this.marker.started ? { navigate: !loadFollowsAction(this.marker), screenshots: !!this.marker.screenshots } : undefined,\n onStart: ({ screenshots }) => this.saveMarker({ started: true, screenshots }),\n onStep: (s) => this.enqueue(s),\n onFinish: () => void this.finish(false),\n onCancel: () => void this.finish(true),\n });\n this.heartbeat = setInterval(() => void this.beat(), CAPTURE_HEARTBEAT_MS);\n window.addEventListener(\"pagehide\", this.onPageHide);\n this.post({ type: \"guidely:capture-ready\", sessionId: this.info.id, url: window.location.href });\n void this.pump();\n } catch (err) {\n this.opts.onError(err);\n }\n }\n\n private reject(message: string): void {\n this.clearMarker();\n this.opts.onError(new Error(message));\n }\n\n private saveMarker(patch: Partial<CaptureMarker>): void {\n this.marker = { ...this.marker, ...patch };\n writeJson(this.opts.sessionStore, KEYS.capture, this.marker);\n }\n\n private clearMarker(): void {\n this.opts.sessionStore.remove(KEYS.capture);\n this.opts.sessionStore.remove(KEYS.capturePending);\n }\n\n /** Persists the steps still to upload (JSON only; screenshots are added on page hide). */\n private savePending(): void {\n if (!this.queue.length) this.opts.sessionStore.remove(KEYS.capturePending);\n else writeJson(this.opts.sessionStore, KEYS.capturePending, this.queue.map((q): PendingStep => (q.shot ? { step: q.step, shot: q.shot } : { step: q.step })));\n }\n\n /** The page is unloading with uploads in flight: keep their screenshots for the next page. */\n private saveForReload(): void {\n if (!this.active || !this.queue.length) return;\n for (const q of this.queue) if (!q.shot && q.frame && !(q.frame instanceof Promise)) q.shot = screenshotDataUrl(q.frame) ?? undefined;\n this.savePending();\n }\n\n private enqueue(captured: CapturedStep): void {\n if (this.finishing) return;\n // Same object: a deferred frame still updates its highlight and redaction count before upload.\n const step: CaptureStepInput = Object.assign(captured.step, { clientId: randomId(16) });\n this.queue.push({ step, frame: captured.frame });\n this.saveMarker({ lastStepAt: Date.now(), lastAction: step.action });\n this.savePending();\n void this.pump();\n }\n\n /** Uploads queued steps one at a time, in capture order. */\n private async pump(): Promise<void> {\n if (this.pumping || !this.info) return;\n this.pumping = true;\n try {\n while (this.queue.length && this.info) {\n const item = this.queue[0]!;\n if (item.frame instanceof Promise) item.frame = await item.frame.catch(() => null);\n if (item.blob === undefined) item.blob = item.shot ? dataUrlToBlob(item.shot) : item.frame ? await encodeScreenshot(item.frame, { maxBytes: CAPTURE_SCREENSHOT_MAX_BYTES }) : null;\n const res = await this.upload(item);\n if (!this.info) return;\n if (!res) {\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.retryTimer = setTimeout(() => void this.pump(), UPLOAD_RETRY_LATER_MS);\n return;\n }\n this.queue.shift();\n this.savePending();\n if (res.status === 401 || res.status === 403 || res.status === 404 || res.status === 410) {\n this.opts.onError(new Error(`[Guidely] capture session ended (${res.status})`));\n this.teardown(true);\n return;\n }\n if (res.ok && res.data) this.post({ type: \"guidely:capture-step\", sessionId: this.info.id, stepCount: res.data.stepCount });\n else if (!res.ok) this.opts.onError(new Error(`[Guidely] capture step rejected (${res.status})`));\n }\n } catch (err) {\n this.opts.onError(err);\n } finally {\n this.pumping = false;\n }\n }\n\n private async upload(item: QueuedStep): Promise<ApiResponse<{ id: string; position: number; stepCount: number }> | null> {\n const send = (shot: Blob | null) =>\n withRetry(() => this.opts.api.postForm<{ id: string; position: number; stepCount: number }>(\"/capture/steps\", captureStepForm(item.step, shot), { params: { token: this.token }, timeoutMs: 60000 }), 4, 1000);\n const res = await send(item.blob ?? null);\n // Too large or unreadable image: keep the step without it.\n if (res && item.blob && (res.status === 413 || res.status === 415)) return send(null);\n return res;\n }\n\n private async beat(): Promise<void> {\n try {\n const res = await this.opts.api.post(\"/capture/session/heartbeat\", {}, { params: { token: this.token } });\n if (res.status === 401 || res.status === 410) {\n this.opts.onError(new Error(`[Guidely] capture session ended (${res.status})`));\n this.teardown(true);\n }\n } catch {\n /* offline: the next beat retries */\n }\n }\n\n /** Done (waits for queued uploads) or Cancel (drops them); either way the dashboard is told. */\n private async finish(cancelled: boolean): Promise<void> {\n if (this.finishing || !this.info) return;\n this.finishing = true;\n const info = this.info;\n if (cancelled) {\n this.queue = [];\n this.savePending();\n } else {\n this.session?.setSaving(true);\n if (this.retryTimer) clearTimeout(this.retryTimer);\n void this.pump();\n const deadline = Date.now() + FINISH_DRAIN_MS;\n while ((this.queue.length || this.pumping) && this.info && Date.now() < deadline) await sleep(100);\n }\n let howToId = info.howToId;\n try {\n const res = await withRetry(() => this.opts.api.post<{ ok: boolean; howToId?: string }>(\"/capture/session/finish\", { cancelled }, { params: { token: this.token } }), 3, 500);\n if (res?.data?.howToId) howToId = res.data.howToId;\n } catch (err) {\n this.opts.onError(err);\n }\n this.post({ type: \"guidely:capture-finished\", sessionId: info.id, howToId, cancelled });\n this.teardown(true);\n }\n\n private post(message: CaptureOutgoingMessage): void {\n if (!this.info) return;\n try {\n window.opener?.postMessage(message, this.info.dashboardOrigin);\n } catch {\n /* opener may be gone */\n }\n }\n\n private teardown(clearMarker: boolean): void {\n if (this.heartbeat) clearInterval(this.heartbeat);\n this.heartbeat = null;\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.retryTimer = null;\n window.removeEventListener(\"pagehide\", this.onPageHide);\n this.session?.stop();\n this.session = null;\n if (clearMarker) this.clearMarker();\n this.info = null;\n this.queue = [];\n if (!this.active) return;\n this.active = false;\n this.opts.onActive(false);\n }\n\n /** Removes the toolbar and stops uploading but keeps the session marker (the SDK was destroyed; a new client resumes). */\n destroy(): void {\n this.saveForReload();\n this.teardown(false);\n }\n}\n\n/** What the on-demand capture chunk provides (`window.__guidelyCapture` in the script-tag build). */\nexport interface CaptureApi {\n createBridge(options: CaptureBridgeOptions): CaptureBridge;\n}\n\nexport const capture: CaptureApi = { createBridge: (options) => new CaptureBridge(options) };\n","import { isServerFailure, parseRetryAfter, ServerHealth } from \"./health\";\n\nexport interface ApiResponse<T> {\n status: number;\n ok: boolean;\n data: T | null;\n etag: string | null;\n}\n\nexport type FetchLike = typeof fetch;\n\n/** Reply streams: the response must start within this long, and then never go quiet longer than the idle limit (the server sends a keepalive every 15 s). */\nexport const STREAM_RESPONSE_TIMEOUT_MS = 30_000;\nexport const STREAM_IDLE_TIMEOUT_MS = 60_000;\n\n/** Thin HTTP client for the public SDK API. Adds the public key as query + header. */\nexport class Api {\n /** Reachability of the API, fed by every answer (see {@link ServerHealth}). */\n readonly health: ServerHealth;\n\n constructor(\n private readonly baseUrl: string,\n private readonly key: string,\n private readonly fetchImpl?: FetchLike,\n health?: ServerHealth,\n ) {\n this.health = health ?? new ServerHealth();\n }\n\n /** Feeds an answer (or a failed request, `null`) into {@link health}. */\n private observe(res: Response | null): void {\n if (!res) this.health.failure();\n else if (isServerFailure(res.status)) this.health.failure(parseRetryAfter(res.headers?.get?.(\"retry-after\")));\n else this.health.success();\n }\n\n url(path: string, params: Record<string, string | undefined> = {}): string {\n // Built by hand rather than with URL/searchParams, which React Native does not implement.\n const query = Object.entries({ key: this.key, ...params })\n .filter((e): e is [string, string] => e[1] != null)\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join(\"&\");\n return `${this.baseUrl.replace(/\\/$/, \"\")}/api/v1/sdk${path}?${query}`;\n }\n\n private get fetcher(): FetchLike | null {\n if (this.fetchImpl) return this.fetchImpl;\n return typeof fetch === \"function\" ? fetch.bind(globalThis) : null;\n }\n\n async request<T>(method: \"GET\" | \"POST\", path: string, options: { body?: unknown; etag?: string | null; params?: Record<string, string | undefined>; keepalive?: boolean; timeoutMs?: number; headers?: Record<string, string> } = {}): Promise<ApiResponse<T>> {\n const f = this.fetcher;\n if (!f) throw new Error(\"fetch is not available\");\n const headers: Record<string, string> = { ...options.headers, \"X-Guidely-Key\": this.key, Accept: \"application/json\" };\n // Multipart bodies set their own Content-Type (with the boundary).\n const form = typeof FormData !== \"undefined\" && options.body instanceof FormData;\n if (options.body !== undefined && !form) headers[\"Content-Type\"] = \"application/json\";\n if (options.etag) headers[\"If-None-Match\"] = options.etag;\n const ac = typeof AbortController !== \"undefined\" ? new AbortController() : null;\n const timer = ac ? setTimeout(() => ac.abort(), options.timeoutMs ?? 10000) : null;\n try {\n let res: Response;\n try {\n res = await f(this.url(path, options.params), {\n method,\n headers,\n body: options.body === undefined ? undefined : form ? (options.body as FormData) : JSON.stringify(options.body),\n keepalive: options.keepalive,\n signal: ac?.signal,\n credentials: \"omit\",\n mode: \"cors\",\n });\n } catch (err) {\n this.observe(null);\n throw err;\n }\n this.observe(res);\n let data: T | null = null;\n if (res.status !== 304 && res.status !== 204) {\n try {\n data = (await res.json()) as T;\n } catch {\n data = null;\n }\n }\n return { status: res.status, ok: res.ok, data, etag: res.headers?.get?.(\"etag\") ?? null };\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n\n get<T>(path: string, options?: { etag?: string | null; params?: Record<string, string | undefined>; headers?: Record<string, string> }): Promise<ApiResponse<T>> {\n return this.request<T>(\"GET\", path, options);\n }\n\n post<T>(path: string, body: unknown, options?: { params?: Record<string, string | undefined>; keepalive?: boolean; headers?: Record<string, string> }): Promise<ApiResponse<T>> {\n return this.request<T>(\"POST\", path, { body, ...options });\n }\n\n /** Multipart POST (file uploads). No Content-Type header: the browser adds it with the boundary. */\n postForm<T>(path: string, form: FormData, options?: { params?: Record<string, string | undefined>; timeoutMs?: number }): Promise<ApiResponse<T>> {\n return this.request<T>(\"POST\", path, { body: form, ...options });\n }\n\n /**\n * POST that may answer with server-sent events. Each event is passed to `onEvent`; a JSON answer is\n * returned instead. Scout replies can take a while, so there is no overall timeout: the response\n * must start within 30 s and then never go quiet for more than 60 s (the server sends keepalives),\n * otherwise the request is aborted and rejects.\n */\n async stream<T>(path: string, body: unknown, onEvent: (event: string, data: unknown) => void, headers: Record<string, string> = {}): Promise<ApiResponse<T>> {\n const f = this.fetcher;\n if (!f) throw new Error(\"fetch is not available\");\n const ac = typeof AbortController !== \"undefined\" ? new AbortController() : null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const arm = (ms: number) => {\n if (!ac) return;\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => ac.abort(), ms);\n };\n arm(STREAM_RESPONSE_TIMEOUT_MS);\n try {\n let res: Response;\n try {\n res = await f(this.url(path), {\n method: \"POST\",\n headers: { ...headers, \"X-Guidely-Key\": this.key, Accept: \"text/event-stream, application/json\", \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: ac?.signal,\n credentials: \"omit\",\n mode: \"cors\",\n });\n } catch (err) {\n this.observe(null);\n throw err;\n }\n this.observe(res);\n const type = res.headers?.get?.(\"content-type\") ?? \"\";\n if (!type.includes(\"text/event-stream\") || !res.body) {\n let data: T | null = null;\n try {\n data = (await res.json()) as T;\n } catch {\n data = null;\n }\n return { status: res.status, ok: res.ok, data, etag: null };\n }\n arm(STREAM_IDLE_TIMEOUT_MS);\n await readEventStream(res.body, onEvent, () => arm(STREAM_IDLE_TIMEOUT_MS));\n return { status: res.status, ok: res.ok, data: null, etag: null };\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n\n /** `navigator.sendBeacon` when available (page unload); returns false when it could not be queued. */\n beacon(path: string, body: unknown): boolean {\n try {\n if (typeof navigator === \"undefined\" || typeof navigator.sendBeacon !== \"function\") return false;\n // text/plain is a CORS-safelisted type: cross-origin beacons need no preflight (which\n // browsers drop during unload). The API parses the body regardless of content type.\n const blob = new Blob([JSON.stringify(body)], { type: \"text/plain;charset=UTF-8\" });\n return navigator.sendBeacon(this.url(path), blob);\n } catch {\n return false;\n }\n }\n}\n\nexport const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n\n/** Exponential backoff helper: 1s → 2s → 4s … capped. */\nexport function backoffMs(attempt: number, baseMs = 1000, maxMs = 30000): number {\n return Math.min(maxMs, baseMs * 2 ** Math.max(0, attempt));\n}\n\n/**\n * Sends with bounded retries: network errors, 429 and 5xx are retried with backoff; success and\n * other 4xx answers are returned as they are. Null when every attempt failed.\n */\nexport async function withRetry<T>(send: () => Promise<ApiResponse<T>>, attempts = 3, baseMs = 500): Promise<ApiResponse<T> | null> {\n for (let i = 0; i < attempts; i++) {\n try {\n const res = await send();\n if (res.ok || (res.status >= 400 && res.status < 500 && res.status !== 429)) return res;\n } catch {\n /* network error → retry */\n }\n if (i < attempts - 1) await sleep(backoffMs(i, baseMs, 8000));\n }\n return null;\n}\n\n/** Fire-and-forget POST with bounded retries (used for state sync; never blocks UI). */\nexport function postWithRetry<T>(api: Api, path: string, body: unknown, attempts = 3, baseMs = 500): Promise<ApiResponse<T> | null> {\n return withRetry(() => api.post<T>(path, body), attempts, baseMs);\n}\n\n/** Parses a `text/event-stream` body (`event:` + single-line JSON `data:`; comment lines ignored). `onChunk` runs whenever bytes arrive. */\nexport async function readEventStream(body: ReadableStream<Uint8Array>, onEvent: (event: string, data: unknown) => void, onChunk?: () => void): Promise<void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n const dispatch = (raw: string) => {\n let event = \"message\";\n const data: string[] = [];\n for (const line of raw.split(\"\\n\")) {\n if (!line || line.startsWith(\":\")) continue;\n const i = line.indexOf(\":\");\n const field = i < 0 ? line : line.slice(0, i);\n const value = i < 0 ? \"\" : line.slice(i + 1).replace(/^ /, \"\");\n if (field === \"event\") event = value;\n else if (field === \"data\") data.push(value);\n }\n if (!data.length) return;\n try {\n onEvent(event, JSON.parse(data.join(\"\\n\")));\n } catch {\n /* ignore malformed events */\n }\n };\n for (;;) {\n const { done, value } = await reader.read();\n if (value) onChunk?.();\n if (value) buffer += decoder.decode(value, { stream: true }).replace(/\\r\\n?/g, \"\\n\");\n let sep: number;\n while ((sep = buffer.indexOf(\"\\n\\n\")) >= 0) {\n dispatch(buffer.slice(0, sep));\n buffer = buffer.slice(sep + 2);\n }\n if (done) break;\n }\n if (buffer.trim()) dispatch(buffer);\n}\n","export type StorageKind = \"local\" | \"session\" | \"memory\";\n\n/** Minimal synchronous key/value store; never throws (private mode, quota, SSR). */\nexport interface KeyValueStore {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n}\n\nexport function memoryStore(): KeyValueStore {\n const map = new Map<string, string>();\n return { get: (k) => map.get(k) ?? null, set: (k, v) => void map.set(k, v), remove: (k) => void map.delete(k) };\n}\n\nfunction webStore(area: \"localStorage\" | \"sessionStorage\"): KeyValueStore | null {\n try {\n if (typeof window === \"undefined\") return null;\n const s = window[area];\n if (!s) return null;\n const probe = \"__guidely_probe__\";\n s.setItem(probe, \"1\");\n s.removeItem(probe);\n return {\n get: (k) => {\n try {\n return s.getItem(k);\n } catch {\n return null;\n }\n },\n set: (k, v) => {\n try {\n s.setItem(k, v);\n } catch {\n /* quota / private mode */\n }\n },\n remove: (k) => {\n try {\n s.removeItem(k);\n } catch {\n /* ignore */\n }\n },\n };\n } catch {\n return null;\n }\n}\n\n/** Creates a store of the requested kind, degrading to memory when unavailable. */\nexport function createStorage(kind: StorageKind = \"local\"): KeyValueStore {\n if (kind === \"memory\") return memoryStore();\n return webStore(kind === \"local\" ? \"localStorage\" : \"sessionStorage\") ?? memoryStore();\n}\n\nexport function readJson<T>(store: KeyValueStore, key: string, fallback: T): T {\n const raw = store.get(key);\n if (raw == null) return fallback;\n try {\n return JSON.parse(raw) as T;\n } catch {\n return fallback;\n }\n}\n\nexport function writeJson(store: KeyValueStore, key: string, value: unknown): void {\n try {\n store.set(key, JSON.stringify(value));\n } catch {\n /* ignore */\n }\n}\n\n/** Storage keys used by the SDK (documented for integrators). */\nexport const KEYS = {\n anon: \"guidely:anon\",\n seen: \"guidely:seen\",\n config: (key: string) => `guidely:config:${key}`,\n etag: (key: string) => `guidely:etag:${key}`,\n state: (key: string) => `guidely:state:${key}`,\n user: (key: string) => `guidely:user:${key}`,\n queue: (key: string) => `guidely:queue:${key}`,\n /** Survey answers and guide/checklist progress not yet accepted by the server. */\n outbox: (key: string) => `guidely:outbox:${key}`,\n /** Agent Analytics turns not yet accepted by the server. */\n agentOutbox: (key: string) => `guidely:agents:${key}`,\n session: \"guidely:session\",\n active: \"guidely:active\",\n authoring: \"guidely:authoring\",\n /** How-to capture session marker ({ token, … }) and its not-yet-uploaded steps. */\n capture: \"guidely:capture\",\n capturePending: \"guidely:capture:pending\",\n /** Messenger conversations this browser can read: [{ id, token }]. */\n conversations: (key: string) => `guidely:conversations:${key}`,\n /** Announcement ids opened in the messenger's News tab. */\n newsSeen: (key: string) => `guidely:news:${key}`,\n /** Where the visitor dragged the messenger launcher ({ side, y }). */\n launcher: (key: string) => `guidely:launcher:${key}`,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;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AC,KAAK,KAAM;AAChB,QAAI;AACF,aAAO,QAAQ,YAAY,SAAS,KAAK,KAAK,eAAe;AAAA,IAC/D,QAAQ;AAAA,IAER;AAAA,EACF;AAAA,EAEQ,SAAS,aAA4B;AAC3C,QAAI,KAAK,UAAW,eAAc,KAAK,SAAS;AAChD,SAAK,YAAY;AACjB,QAAI,KAAK,WAAY,cAAa,KAAK,UAAU;AACjD,SAAK,aAAa;AAClB,WAAO,oBAAoB,YAAY,KAAK,UAAU;AACtD,SAAK,SAAS,KAAK;AACnB,SAAK,UAAU;AACf,QAAI,YAAa,MAAK,YAAY;AAClC,SAAK,OAAO;AACZ,SAAK,QAAQ,CAAC;AACd,QAAI,CAAC,KAAK,OAAQ;AAClB,SAAK,SAAS;AACd,SAAK,KAAK,SAAS,KAAK;AAAA,EAC1B;AAAA;AAAA,EAGA,UAAgB;AACd,SAAK,cAAc;AACnB,SAAK,SAAS,KAAK;AAAA,EACrB;AACF;AAOO,IAAM,UAAsB,EAAE,cAAc,CAAC,YAAY,IAAI,cAAc,OAAO,EAAE;","names":["import_runtime"]}
|
package/dist/capture.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import '@guidelytech/shared';
|
|
2
|
-
export { b as CAPTURE_HEARTBEAT_MS, c as CaptureApi, d as CaptureBridge, e as CaptureBridgeOptions, a as CaptureOutgoingMessage, F as FINISH_DRAIN_MS, L as LOAD_AFTER_ACTION_MS, U as UPLOAD_RETRY_LATER_MS, f as capture, g as captureStepForm, l as loadFollowsAction } from './capture-
|
|
3
|
-
import './http-
|
|
4
|
-
import './health-
|
|
2
|
+
export { b as CAPTURE_HEARTBEAT_MS, c as CaptureApi, d as CaptureBridge, e as CaptureBridgeOptions, a as CaptureOutgoingMessage, F as FINISH_DRAIN_MS, L as LOAD_AFTER_ACTION_MS, U as UPLOAD_RETRY_LATER_MS, f as capture, g as captureStepForm, l as loadFollowsAction } from './capture-4EgpjK6Z.cjs';
|
|
3
|
+
import './http-zOI8d2c2.cjs';
|
|
4
|
+
import './health-DjZ2gwYa.cjs';
|
package/dist/capture.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import '@guidelytech/shared';
|
|
2
|
-
export { b as CAPTURE_HEARTBEAT_MS, c as CaptureApi, d as CaptureBridge, e as CaptureBridgeOptions, a as CaptureOutgoingMessage, F as FINISH_DRAIN_MS, L as LOAD_AFTER_ACTION_MS, U as UPLOAD_RETRY_LATER_MS, f as capture, g as captureStepForm, l as loadFollowsAction } from './capture-
|
|
3
|
-
import './http-
|
|
4
|
-
import './health-
|
|
2
|
+
export { b as CAPTURE_HEARTBEAT_MS, c as CaptureApi, d as CaptureBridge, e as CaptureBridgeOptions, a as CaptureOutgoingMessage, F as FINISH_DRAIN_MS, L as LOAD_AFTER_ACTION_MS, U as UPLOAD_RETRY_LATER_MS, f as capture, g as captureStepForm, l as loadFollowsAction } from './capture-C-4R56G0.js';
|
|
3
|
+
import './http-BXys2d-j.js';
|
|
4
|
+
import './health-DjZ2gwYa.js';
|
package/dist/capture.js
CHANGED
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
backoffMs,
|
|
4
4
|
readJson,
|
|
5
5
|
writeJson
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-XML74K2P.js";
|
|
7
7
|
|
|
8
8
|
// src/queue.ts
|
|
9
9
|
var EventQueue = class {
|
|
@@ -287,12 +287,32 @@ function areMutuallyExclusive(a, b) {
|
|
|
287
287
|
return la.includes(b.id) || la.includes(b.key) || lb.includes(a.id) || lb.includes(a.key);
|
|
288
288
|
}
|
|
289
289
|
function isWithinSchedule(guide, now = Date.now()) {
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
290
|
+
for (const w of [guide.config.schedule, guide.config.survey]) {
|
|
291
|
+
if (!w) continue;
|
|
292
|
+
if (w.startAt && now < Date.parse(w.startAt)) return false;
|
|
293
|
+
if (w.endAt && now > Date.parse(w.endAt)) return false;
|
|
294
|
+
}
|
|
294
295
|
return true;
|
|
295
296
|
}
|
|
297
|
+
var MINUTE = 60 * 1e3;
|
|
298
|
+
function countsTowardThrottle(guide) {
|
|
299
|
+
return isExclusiveGuide(guide) && !guide.config.frequency.ignoreThrottling;
|
|
300
|
+
}
|
|
301
|
+
function isThrottleEligible(settings, launches, now = Date.now()) {
|
|
302
|
+
if (!settings || !settings.enabled) return true;
|
|
303
|
+
const times = launches.map((l) => Date.parse(l)).filter((t) => !Number.isNaN(t));
|
|
304
|
+
const windowMs = Math.max(1, settings.windowHours) * HOUR;
|
|
305
|
+
if (times.filter((t) => now - t < windowMs).length >= Math.max(1, settings.maxGuides)) return false;
|
|
306
|
+
if (settings.minGapMinutes > 0 && times.some((t) => now - t < settings.minGapMinutes * MINUTE)) return false;
|
|
307
|
+
return true;
|
|
308
|
+
}
|
|
309
|
+
function pruneLaunches(launches, settings, now = Date.now()) {
|
|
310
|
+
const keepMs = Math.max(settings?.windowHours ?? 24, 1) * HOUR + (settings?.minGapMinutes ?? 0) * MINUTE;
|
|
311
|
+
return launches.filter((l) => {
|
|
312
|
+
const t = Date.parse(l);
|
|
313
|
+
return !Number.isNaN(t) && now - t < keepMs;
|
|
314
|
+
}).slice(-100);
|
|
315
|
+
}
|
|
296
316
|
function dismissedAfterMerge(local, server) {
|
|
297
317
|
if (server.dismissResetAt && server.dismissResetAt !== local?.dismissResetAt) return server.dismissedAt ?? null;
|
|
298
318
|
return local?.dismissedAt ?? server.dismissedAt ?? null;
|
|
@@ -306,6 +326,9 @@ export {
|
|
|
306
326
|
isExclusiveGuide,
|
|
307
327
|
areMutuallyExclusive,
|
|
308
328
|
isWithinSchedule,
|
|
329
|
+
countsTowardThrottle,
|
|
330
|
+
isThrottleEligible,
|
|
331
|
+
pruneLaunches,
|
|
309
332
|
dismissedAfterMerge
|
|
310
333
|
};
|
|
311
|
-
//# sourceMappingURL=chunk-
|
|
334
|
+
//# sourceMappingURL=chunk-2E2YUQAG.js.map
|
|
@@ -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,KAAK,mBAAmB;AAC/C,SAAK,WAAW,KAAK,YAAY;AACjC,SAAK,YAAY,KAAK,aAAa;AACnC,SAAK,cAAc,KAAK,eAAe;AACvC,UAAM,YAAY,SAAqB,KAAK,OAAO,KAAK,YAAY,CAAC,CAAC;AACtE,QAAI,MAAM,QAAQ,SAAS,EAAG,MAAK,SAAS,UAAU,OAAO,CAAC,MAAM,KAAK,OAAO,EAAE,YAAY,QAAQ,EAAE,MAAM,CAAC,KAAK,QAAQ;AAE5H,QAAI,KAAK,OAAO,OAAQ,MAAK,SAAS;AACtC,SAAK,aAAa,KAAK,QAAQ,UAAU,MAAM,KAAK,SAAS,CAAC,KAAK;AAAA,EACrE;AAAA;AAAA,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Ae,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":[]}
|
|
@@ -343,6 +343,8 @@ var KEYS = {
|
|
|
343
343
|
queue: (key) => `guidely:queue:${key}`,
|
|
344
344
|
/** Survey answers and guide/checklist progress not yet accepted by the server. */
|
|
345
345
|
outbox: (key) => `guidely:outbox:${key}`,
|
|
346
|
+
/** Agent Analytics turns not yet accepted by the server. */
|
|
347
|
+
agentOutbox: (key) => `guidely:agents:${key}`,
|
|
346
348
|
session: "guidely:session",
|
|
347
349
|
active: "guidely:active",
|
|
348
350
|
authoring: "guidely:authoring",
|
|
@@ -371,4 +373,4 @@ export {
|
|
|
371
373
|
writeJson,
|
|
372
374
|
KEYS
|
|
373
375
|
};
|
|
374
|
-
//# sourceMappingURL=chunk-
|
|
376
|
+
//# sourceMappingURL=chunk-JUSM7J5N.js.map
|