@extn/segi-js 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,61 @@
1
+ import { R as ReplayConfig, a as ReplayOptions } from '../types-DfmnOA9D.js';
2
+
3
+ /**
4
+ * Replay orchestrator. Exposed at `@extn/segi-js/replay`.
5
+ *
6
+ * Usage:
7
+ * import Segi from "@extn/segi-js";
8
+ * import { withReplay } from "@extn/segi-js/replay";
9
+ *
10
+ * Segi.init({
11
+ * projectKey: "segi_pk_live_...",
12
+ * endpoint: "https://segiapi.extn.ai",
13
+ * replay: withReplay({ enabled: true, sample: 100 }),
14
+ * });
15
+ *
16
+ * // anywhere after init:
17
+ * Segi.replay.pause();
18
+ * Segi.replay.setUser({ id: "u_123" });
19
+ * Segi.replay.event("checkout_started", { amount: 9900 });
20
+ * Segi.replay.notifyRouteChange();
21
+ *
22
+ * Activation is async because:
23
+ * - we POST /api/trace/session/start before any heatmap listener attaches,
24
+ * so the server can short-circuit a recording-off project
25
+ * - this also lets the client honor the project-level recording toggle
26
+ * without redeploying the SDK
27
+ *
28
+ * No rrweb in this pass. DOM replay lands when the server-side /api/trace/
29
+ * replay path (currently 501) gets its S3 backend.
30
+ */
31
+
32
+ declare function withReplay(options?: ReplayOptions): ReplayConfig;
33
+ /**
34
+ * Internal entry-point invoked by Segi.init() when a ReplayConfig was
35
+ * passed. Not part of the public surface.
36
+ */
37
+ declare function activateReplay(args: {
38
+ projectKey: string;
39
+ /** Optional — replay transport defaults to https://segiapi.extn.ai. */
40
+ endpoint?: string;
41
+ config: ReplayConfig;
42
+ }): Promise<void>;
43
+ /** Public Segi.replay namespace, attached by the main index.ts. */
44
+ declare const replayApi: {
45
+ pause(): void;
46
+ resume(): void;
47
+ setUser(user: {
48
+ id?: string;
49
+ email?: string;
50
+ } | null): void;
51
+ event(name: string, meta?: Record<string, unknown>): void;
52
+ /**
53
+ * Call this on SPA route changes (e.g. from a Next.js usePathname() effect).
54
+ * Bumps the page-views counter and emits a fresh page_view event.
55
+ */
56
+ notifyRouteChange(url?: string, title?: string): void;
57
+ /** Test seam: returns null when replay was not activated for this session. */
58
+ _sessionUid(): string | null;
59
+ };
60
+
61
+ export { ReplayConfig, ReplayOptions, activateReplay, replayApi, withReplay };
@@ -0,0 +1,480 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/replay/heatmap.ts
2
+ var FLUSH_CLICK_INTERVAL_MS = 5e3;
3
+ var FLUSH_CLICK_BUFFER = 50;
4
+ var SCROLL_THROTTLE_MS = 1e3;
5
+ function deviceClass(w) {
6
+ if (w < 640) return "mobile";
7
+ if (w < 1024) return "tablet";
8
+ return "desktop";
9
+ }
10
+ function isMaskedElement(el, maskClass) {
11
+ let cur = el;
12
+ while (cur) {
13
+ if (_optionalChain([cur, 'access', _ => _.classList, 'optionalAccess', _2 => _2.contains, 'call', _3 => _3(maskClass)])) return true;
14
+ cur = cur.parentElement;
15
+ }
16
+ return false;
17
+ }
18
+ function buildSelector(el) {
19
+ try {
20
+ if (el.id) return `#${el.id}`;
21
+ const tag = _optionalChain([el, 'access', _4 => _4.tagName, 'optionalAccess', _5 => _5.toLowerCase, 'call', _6 => _6()]);
22
+ if (!tag) return void 0;
23
+ const cls = (el.className && typeof el.className === "string" ? el.className.split(/\s+/).filter(Boolean).slice(0, 2) : []).map((c) => `.${c}`);
24
+ return `${tag}${cls.join("")}`.slice(0, 512);
25
+ } catch (e2) {
26
+ return void 0;
27
+ }
28
+ }
29
+ function startHeatmap(args) {
30
+ const maskClass = _nullishCoalesce(_optionalChain([args, 'access', _7 => _7.options, 'access', _8 => _8.mask, 'optionalAccess', _9 => _9.class]), () => ( "segi-mask"));
31
+ let paused = false;
32
+ const buffer = [];
33
+ let lastScrollPct = -1;
34
+ let lastScrollPostAt = 0;
35
+ const flushClicks = (opts = {}) => {
36
+ if (buffer.length === 0) return;
37
+ const batch = buffer.splice(0, buffer.length);
38
+ args.sendClicks(batch, Boolean(opts.useBeacon));
39
+ };
40
+ const interval = setInterval(() => {
41
+ if (!paused) flushClicks();
42
+ }, FLUSH_CLICK_INTERVAL_MS);
43
+ const onClick = (e) => {
44
+ if (paused) return;
45
+ try {
46
+ const target = e.target;
47
+ if (!target) return;
48
+ if (isMaskedElement(target, maskClass)) return;
49
+ const docW = Math.max(
50
+ document.documentElement.scrollWidth,
51
+ _nullishCoalesce(_optionalChain([document, 'access', _10 => _10.body, 'optionalAccess', _11 => _11.scrollWidth]), () => ( 0)),
52
+ 1
53
+ );
54
+ const docH = Math.max(
55
+ document.documentElement.scrollHeight,
56
+ _nullishCoalesce(_optionalChain([document, 'access', _12 => _12.body, 'optionalAccess', _13 => _13.scrollHeight]), () => ( 0)),
57
+ 1
58
+ );
59
+ const pageX = e.pageX;
60
+ const pageY = e.pageY;
61
+ const w = window.innerWidth;
62
+ const row = {
63
+ sessionUid: args.sessionUid,
64
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
65
+ urlPath: location.pathname.slice(0, 255),
66
+ device: deviceClass(w),
67
+ viewportW: w,
68
+ viewportH: window.innerHeight,
69
+ x: Math.round(e.clientX),
70
+ y: Math.round(e.clientY),
71
+ pageX: Math.round(pageX),
72
+ pageY: Math.round(pageY),
73
+ relX: Math.max(0, Math.min(1, pageX / docW)),
74
+ relY: Math.max(0, Math.min(1, pageY / docH)),
75
+ selector: buildSelector(target),
76
+ tag: _optionalChain([target, 'access', _14 => _14.tagName, 'optionalAccess', _15 => _15.toLowerCase, 'call', _16 => _16(), 'access', _17 => _17.slice, 'call', _18 => _18(0, 32)]),
77
+ text: _optionalChain([(_nullishCoalesce(target.textContent, () => ( void 0))), 'optionalAccess', _19 => _19.trim, 'call', _20 => _20(), 'access', _21 => _21.slice, 'call', _22 => _22(0, 128)]) || void 0
78
+ };
79
+ buffer.push(row);
80
+ if (buffer.length >= FLUSH_CLICK_BUFFER) flushClicks();
81
+ } catch (e3) {
82
+ }
83
+ };
84
+ const onScroll = () => {
85
+ if (paused) return;
86
+ const now = Date.now();
87
+ if (now - lastScrollPostAt < SCROLL_THROTTLE_MS) return;
88
+ try {
89
+ const docH = Math.max(
90
+ document.documentElement.scrollHeight,
91
+ _nullishCoalesce(_optionalChain([document, 'access', _23 => _23.body, 'optionalAccess', _24 => _24.scrollHeight]), () => ( 0)),
92
+ 1
93
+ );
94
+ const viewH = window.innerHeight;
95
+ const maxY = Math.round(window.scrollY + viewH);
96
+ const pct = Math.max(0, Math.min(100, Math.round(maxY / docH * 100)));
97
+ if (pct <= lastScrollPct) return;
98
+ lastScrollPct = pct;
99
+ lastScrollPostAt = now;
100
+ const w = window.innerWidth;
101
+ args.sendScroll(
102
+ {
103
+ sessionUid: args.sessionUid,
104
+ urlPath: location.pathname.slice(0, 255),
105
+ device: deviceClass(w),
106
+ viewportH: viewH,
107
+ docH,
108
+ maxScrollY: maxY,
109
+ maxScrollPct: pct
110
+ },
111
+ false
112
+ );
113
+ } catch (e4) {
114
+ }
115
+ };
116
+ const onPageHide = () => {
117
+ flushClicks({ useBeacon: true });
118
+ };
119
+ window.addEventListener("click", onClick, true);
120
+ window.addEventListener("scroll", onScroll, { capture: true, passive: true });
121
+ window.addEventListener("pagehide", onPageHide);
122
+ return {
123
+ pause() {
124
+ paused = true;
125
+ },
126
+ resume() {
127
+ paused = false;
128
+ },
129
+ stop() {
130
+ clearInterval(interval);
131
+ window.removeEventListener("click", onClick, true);
132
+ window.removeEventListener("scroll", onScroll, true);
133
+ window.removeEventListener("pagehide", onPageHide);
134
+ flushClicks({ useBeacon: true });
135
+ },
136
+ flushClicks
137
+ };
138
+ }
139
+
140
+ // src/replay/session.ts
141
+ var UID_KEY = "_bd_session_uid";
142
+ var UID_TS_KEY = "_bd_session_at";
143
+ var ANON_KEY = "_bd_anon";
144
+ var IDLE_MS = 30 * 6e4;
145
+ var memUid = null;
146
+ var memAnon = null;
147
+ function uuid() {
148
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
149
+ return crypto.randomUUID();
150
+ }
151
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
152
+ const r = Math.random() * 16 | 0;
153
+ const v = c === "x" ? r : r & 3 | 8;
154
+ return v.toString(16);
155
+ });
156
+ }
157
+ function readSession() {
158
+ try {
159
+ if (typeof sessionStorage === "undefined") return null;
160
+ const uid = sessionStorage.getItem(UID_KEY);
161
+ const at = Number(_nullishCoalesce(sessionStorage.getItem(UID_TS_KEY), () => ( "0")));
162
+ if (!uid || !at) return null;
163
+ return { uid, at };
164
+ } catch (e5) {
165
+ return null;
166
+ }
167
+ }
168
+ function writeSession(uid, at) {
169
+ try {
170
+ if (typeof sessionStorage === "undefined") return;
171
+ sessionStorage.setItem(UID_KEY, uid);
172
+ sessionStorage.setItem(UID_TS_KEY, String(at));
173
+ } catch (e6) {
174
+ }
175
+ }
176
+ function getOrCreateSessionUid() {
177
+ const now = Date.now();
178
+ const existing = readSession();
179
+ if (existing && now - existing.at < IDLE_MS) {
180
+ writeSession(existing.uid, now);
181
+ return existing.uid;
182
+ }
183
+ const uid = uuid();
184
+ writeSession(uid, now);
185
+ memUid = uid;
186
+ return uid;
187
+ }
188
+ function bumpSessionActivity() {
189
+ const existing = readSession();
190
+ if (existing) writeSession(existing.uid, Date.now());
191
+ }
192
+ function getOrCreateAnonId() {
193
+ try {
194
+ if (typeof localStorage === "undefined") {
195
+ if (!memAnon) memAnon = uuid();
196
+ return memAnon;
197
+ }
198
+ const existing = localStorage.getItem(ANON_KEY);
199
+ if (existing) return existing;
200
+ const fresh = uuid();
201
+ localStorage.setItem(ANON_KEY, fresh);
202
+ return fresh;
203
+ } catch (e7) {
204
+ if (!memAnon) memAnon = uuid();
205
+ return memAnon;
206
+ }
207
+ }
208
+
209
+ // src/replay/transport.ts
210
+ var DEFAULT_API_BASE = "https://segiapi.extn.ai";
211
+ function normalizeBase(endpoint) {
212
+ const raw = endpoint && endpoint.trim() || DEFAULT_API_BASE;
213
+ return raw.replace(/\/+$/, "").replace(/\/api\/ingest\/events$/, "").replace(/\/api\/ingest$/, "").replace(/\/api$/, "");
214
+ }
215
+ async function postTrace(cfg, path, body) {
216
+ const url = `${normalizeBase(cfg.endpoint)}/api/trace${path}`;
217
+ try {
218
+ const res = await fetch(url, {
219
+ method: "POST",
220
+ headers: {
221
+ "Content-Type": "application/json",
222
+ "X-Segi-Project-Key": cfg.projectKey
223
+ },
224
+ body: JSON.stringify(body),
225
+ // Keep the request alive past page unload (best-effort flush).
226
+ keepalive: true
227
+ });
228
+ return res;
229
+ } catch (e8) {
230
+ return null;
231
+ }
232
+ }
233
+ function beaconTrace(cfg, path, body) {
234
+ try {
235
+ if (typeof navigator === "undefined" || !navigator.sendBeacon) return false;
236
+ const url = `${normalizeBase(cfg.endpoint)}/api/trace${path}?pk=${encodeURIComponent(cfg.projectKey)}`;
237
+ const blob = new Blob([JSON.stringify(body)], { type: "application/json" });
238
+ return navigator.sendBeacon(url, blob);
239
+ } catch (e9) {
240
+ return false;
241
+ }
242
+ }
243
+
244
+ // src/replay/index.ts
245
+ function withReplay(options = {}) {
246
+ return { __segi_replay: true, options };
247
+ }
248
+ var active = null;
249
+ function deviceClass2() {
250
+ if (typeof window === "undefined") return "desktop";
251
+ const w = window.innerWidth;
252
+ if (w < 640) return "mobile";
253
+ if (w < 1024) return "tablet";
254
+ return "desktop";
255
+ }
256
+ function readQuery(name) {
257
+ if (typeof location === "undefined") return void 0;
258
+ try {
259
+ return _nullishCoalesce(new URLSearchParams(location.search).get(name), () => ( void 0));
260
+ } catch (e10) {
261
+ return void 0;
262
+ }
263
+ }
264
+ function isPathBlocked(opts, path) {
265
+ const list = _nullishCoalesce(opts.blockRoutes, () => ( []));
266
+ return list.some((p) => path.startsWith(p));
267
+ }
268
+ async function activateReplay(args) {
269
+ if (active) return;
270
+ if (typeof window === "undefined") return;
271
+ const options = args.config.options;
272
+ if (options.enabled === false) return;
273
+ const sample = Math.max(0, Math.min(100, _nullishCoalesce(options.sample, () => ( 100))));
274
+ if (Math.random() * 100 >= sample) return;
275
+ if (isPathBlocked(options, location.pathname)) return;
276
+ const sessionUid = getOrCreateSessionUid();
277
+ const anonId = getOrCreateAnonId();
278
+ const transportCfg = {
279
+ endpoint: _nullishCoalesce(options.endpoint, () => ( args.endpoint)),
280
+ projectKey: args.projectKey
281
+ };
282
+ const dto = {
283
+ sessionUid,
284
+ anonId,
285
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
286
+ device: deviceClass2(),
287
+ viewportW: window.innerWidth,
288
+ viewportH: window.innerHeight,
289
+ ua: _optionalChain([navigator, 'access', _25 => _25.userAgent, 'optionalAccess', _26 => _26.slice, 'call', _27 => _27(0, 512)]),
290
+ referrer: document.referrer || void 0,
291
+ landingUrl: location.href.slice(0, 512),
292
+ utmSource: readQuery("utm_source"),
293
+ utmMedium: readQuery("utm_medium"),
294
+ utmCampaign: readQuery("utm_campaign"),
295
+ utmContent: readQuery("utm_content"),
296
+ utmTerm: readQuery("utm_term"),
297
+ fbclid: readQuery("fbclid"),
298
+ gclid: readQuery("gclid")
299
+ };
300
+ let recordingEnabled = true;
301
+ try {
302
+ const res = await postTrace(transportCfg, "/session/start", dto);
303
+ if (res && res.ok) {
304
+ const body = await res.json().catch(() => ({}));
305
+ if (body.recordingEnabled === false) recordingEnabled = false;
306
+ }
307
+ } catch (e11) {
308
+ }
309
+ if (!recordingEnabled) {
310
+ active = {
311
+ sessionUid,
312
+ config: transportCfg,
313
+ options,
314
+ heatmap: null,
315
+ rrweb: null,
316
+ replayBlocked: false,
317
+ paused: true,
318
+ userId: null,
319
+ startedAt: dto.startedAt,
320
+ pagesVisited: 0,
321
+ clickCount: 0,
322
+ recordingEnabled: false
323
+ };
324
+ return;
325
+ }
326
+ const heatmap = startHeatmap({
327
+ sessionUid,
328
+ options,
329
+ sendClicks: (rows, useBeacon) => {
330
+ if (useBeacon) beaconTrace(transportCfg, "/heatmap/clicks", { clicks: rows });
331
+ else void postTrace(transportCfg, "/heatmap/clicks", { clicks: rows });
332
+ },
333
+ sendScroll: (row) => {
334
+ void postTrace(transportCfg, "/heatmap/scroll", row);
335
+ }
336
+ });
337
+ active = {
338
+ sessionUid,
339
+ config: transportCfg,
340
+ options,
341
+ heatmap,
342
+ rrweb: null,
343
+ replayBlocked: false,
344
+ paused: false,
345
+ userId: null,
346
+ startedAt: dto.startedAt,
347
+ pagesVisited: 1,
348
+ clickCount: 0,
349
+ recordingEnabled: true
350
+ };
351
+ void Promise.resolve().then(() => _interopRequireWildcard(require("../rrweb-H4UUMFZ5.js"))).then(
352
+ ({ startRrweb }) => startRrweb({
353
+ sessionUid,
354
+ options,
355
+ sendChunk: async (chunk, useBeacon) => {
356
+ if (!active || active.replayBlocked) return;
357
+ if (useBeacon) {
358
+ beaconTrace(transportCfg, "/replay", { sessionUid, chunk });
359
+ return;
360
+ }
361
+ const res = await postTrace(transportCfg, "/replay", {
362
+ sessionUid,
363
+ chunk
364
+ });
365
+ if (res && res.status === 429) {
366
+ if (active) {
367
+ active.replayBlocked = true;
368
+ _optionalChain([active, 'access', _28 => _28.rrweb, 'optionalAccess', _29 => _29.stop, 'call', _30 => _30()]);
369
+ active.rrweb = null;
370
+ }
371
+ }
372
+ }
373
+ })
374
+ ).then((handles) => {
375
+ if (handles && active) active.rrweb = handles;
376
+ }).catch(() => {
377
+ });
378
+ void postTrace(transportCfg, "/events", {
379
+ events: [
380
+ {
381
+ sessionUid,
382
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
383
+ type: "page_view",
384
+ url: location.href,
385
+ title: document.title
386
+ }
387
+ ]
388
+ });
389
+ window.addEventListener("pagehide", () => {
390
+ if (!active) return;
391
+ _optionalChain([active, 'access', _31 => _31.rrweb, 'optionalAccess', _32 => _32.flush, 'call', _33 => _33(true)]);
392
+ beaconTrace(active.config, "/session/end", {
393
+ sessionUid: active.sessionUid,
394
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
395
+ durationMs: Date.now() - new Date(active.startedAt).getTime(),
396
+ pagesVisited: active.pagesVisited,
397
+ clickCount: active.clickCount
398
+ });
399
+ });
400
+ }
401
+ var replayApi = {
402
+ pause() {
403
+ _optionalChain([active, 'optionalAccess', _34 => _34.heatmap, 'optionalAccess', _35 => _35.pause, 'call', _36 => _36()]);
404
+ _optionalChain([active, 'optionalAccess', _37 => _37.rrweb, 'optionalAccess', _38 => _38.pause, 'call', _39 => _39()]);
405
+ if (active) active.paused = true;
406
+ },
407
+ resume() {
408
+ _optionalChain([active, 'optionalAccess', _40 => _40.heatmap, 'optionalAccess', _41 => _41.resume, 'call', _42 => _42()]);
409
+ _optionalChain([active, 'optionalAccess', _43 => _43.rrweb, 'optionalAccess', _44 => _44.resume, 'call', _45 => _45()]);
410
+ if (active) active.paused = false;
411
+ bumpSessionActivity();
412
+ },
413
+ setUser(user) {
414
+ if (!active) return;
415
+ active.userId = _nullishCoalesce(_optionalChain([user, 'optionalAccess', _46 => _46.id]), () => ( null));
416
+ void postTrace(active.config, "/session/start", {
417
+ sessionUid: active.sessionUid,
418
+ anonId: getOrCreateAnonId(),
419
+ userId: active.userId,
420
+ startedAt: active.startedAt,
421
+ device: deviceClass2(),
422
+ viewportW: window.innerWidth,
423
+ viewportH: window.innerHeight
424
+ });
425
+ },
426
+ event(name, meta) {
427
+ if (!active || active.paused) return;
428
+ void postTrace(active.config, "/events", {
429
+ events: [
430
+ {
431
+ sessionUid: active.sessionUid,
432
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
433
+ type: "custom",
434
+ name: name.slice(0, 64),
435
+ url: location.href,
436
+ meta
437
+ }
438
+ ]
439
+ });
440
+ },
441
+ /**
442
+ * Call this on SPA route changes (e.g. from a Next.js usePathname() effect).
443
+ * Bumps the page-views counter and emits a fresh page_view event.
444
+ */
445
+ notifyRouteChange(url, title) {
446
+ if (!active || active.paused) return;
447
+ if (isPathBlocked(active.options, location.pathname)) {
448
+ _optionalChain([active, 'access', _47 => _47.heatmap, 'optionalAccess', _48 => _48.pause, 'call', _49 => _49()]);
449
+ _optionalChain([active, 'access', _50 => _50.rrweb, 'optionalAccess', _51 => _51.pause, 'call', _52 => _52()]);
450
+ active.paused = true;
451
+ return;
452
+ }
453
+ if (active.paused) {
454
+ _optionalChain([active, 'access', _53 => _53.heatmap, 'optionalAccess', _54 => _54.resume, 'call', _55 => _55()]);
455
+ _optionalChain([active, 'access', _56 => _56.rrweb, 'optionalAccess', _57 => _57.resume, 'call', _58 => _58()]);
456
+ active.paused = false;
457
+ }
458
+ active.pagesVisited += 1;
459
+ void postTrace(active.config, "/events", {
460
+ events: [
461
+ {
462
+ sessionUid: active.sessionUid,
463
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
464
+ type: "page_view",
465
+ url: _nullishCoalesce(url, () => ( location.href)),
466
+ title: _nullishCoalesce(title, () => ( document.title))
467
+ }
468
+ ]
469
+ });
470
+ },
471
+ /** Test seam: returns null when replay was not activated for this session. */
472
+ _sessionUid() {
473
+ return _nullishCoalesce(_optionalChain([active, 'optionalAccess', _59 => _59.sessionUid]), () => ( null));
474
+ }
475
+ };
476
+
477
+
478
+
479
+
480
+ exports.activateReplay = activateReplay; exports.replayApi = replayApi; exports.withReplay = withReplay;