@extn/segi-js 0.1.0 → 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,480 @@
1
+ // 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 (cur.classList?.contains(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 = el.tagName?.toLowerCase();
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 {
26
+ return void 0;
27
+ }
28
+ }
29
+ function startHeatmap(args) {
30
+ const maskClass = args.options.mask?.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
+ document.body?.scrollWidth ?? 0,
52
+ 1
53
+ );
54
+ const docH = Math.max(
55
+ document.documentElement.scrollHeight,
56
+ document.body?.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: target.tagName?.toLowerCase().slice(0, 32),
77
+ text: (target.textContent ?? void 0)?.trim().slice(0, 128) || void 0
78
+ };
79
+ buffer.push(row);
80
+ if (buffer.length >= FLUSH_CLICK_BUFFER) flushClicks();
81
+ } catch {
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
+ document.body?.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 {
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(sessionStorage.getItem(UID_TS_KEY) ?? "0");
162
+ if (!uid || !at) return null;
163
+ return { uid, at };
164
+ } catch {
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 {
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 {
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 {
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 {
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 new URLSearchParams(location.search).get(name) ?? void 0;
260
+ } catch {
261
+ return void 0;
262
+ }
263
+ }
264
+ function isPathBlocked(opts, path) {
265
+ const list = 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, 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: 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: navigator.userAgent?.slice(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 {
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 import("../rrweb-JCHV7B75.mjs").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
+ active.rrweb?.stop();
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
+ active.rrweb?.flush(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
+ active?.heatmap?.pause();
404
+ active?.rrweb?.pause();
405
+ if (active) active.paused = true;
406
+ },
407
+ resume() {
408
+ active?.heatmap?.resume();
409
+ active?.rrweb?.resume();
410
+ if (active) active.paused = false;
411
+ bumpSessionActivity();
412
+ },
413
+ setUser(user) {
414
+ if (!active) return;
415
+ active.userId = user?.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
+ active.heatmap?.pause();
449
+ active.rrweb?.pause();
450
+ active.paused = true;
451
+ return;
452
+ }
453
+ if (active.paused) {
454
+ active.heatmap?.resume();
455
+ active.rrweb?.resume();
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: url ?? location.href,
466
+ title: title ?? document.title
467
+ }
468
+ ]
469
+ });
470
+ },
471
+ /** Test seam: returns null when replay was not activated for this session. */
472
+ _sessionUid() {
473
+ return active?.sessionUid ?? null;
474
+ }
475
+ };
476
+ export {
477
+ activateReplay,
478
+ replayApi,
479
+ withReplay
480
+ };
@@ -0,0 +1,126 @@
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/rrweb.ts
2
+ var CHECKOUT_EVERY_MS = 3e4;
3
+ var FLUSH_INTERVAL_MS = 1e4;
4
+ var FLUSH_BYTES = 100 * 1024;
5
+ var IDLE_PAUSE_MS = 3 * 6e4;
6
+ var IDLE_CHECK_MS = 15e3;
7
+ var ACTIVITY_EVENTS = [
8
+ "mousemove",
9
+ "mousedown",
10
+ "keydown",
11
+ "touchstart",
12
+ "scroll",
13
+ "wheel"
14
+ ];
15
+ async function startRrweb(args) {
16
+ if (typeof window === "undefined") return null;
17
+ let rrweb;
18
+ try {
19
+ rrweb = await Promise.resolve().then(() => _interopRequireWildcard(require("rrweb")));
20
+ } catch (e) {
21
+ return null;
22
+ }
23
+ const maskClass = _nullishCoalesce(_optionalChain([args, 'access', _ => _.options, 'access', _2 => _2.mask, 'optionalAccess', _3 => _3.class]), () => ( "segi-mask"));
24
+ const inputMode = _nullishCoalesce(_optionalChain([args, 'access', _4 => _4.options, 'access', _5 => _5.mask, 'optionalAccess', _6 => _6.inputs]), () => ( "all"));
25
+ const maskInputOptions = inputMode === "all" ? {
26
+ password: true,
27
+ email: true,
28
+ tel: true,
29
+ number: true,
30
+ text: true,
31
+ textarea: true
32
+ } : inputMode === "sensitive" ? { password: true, email: true, tel: true, number: true } : { password: true };
33
+ let buffer = [];
34
+ let bufferBytes = 0;
35
+ let stopFn = null;
36
+ let lastActivityAt = Date.now();
37
+ let paused = false;
38
+ let stopped = false;
39
+ const flushTimer = setInterval(() => {
40
+ if (paused || stopped) return;
41
+ flush();
42
+ }, FLUSH_INTERVAL_MS);
43
+ const idleTimer = setInterval(() => {
44
+ if (paused || stopped) return;
45
+ if (Date.now() - lastActivityAt >= IDLE_PAUSE_MS) {
46
+ stopRrwebOnly();
47
+ }
48
+ }, IDLE_CHECK_MS);
49
+ function startRecorder() {
50
+ if (stopFn) return;
51
+ const stop = rrweb.record({
52
+ emit(event) {
53
+ if (paused || stopped) return;
54
+ buffer.push(event);
55
+ try {
56
+ bufferBytes += JSON.stringify(event).length;
57
+ } catch (e2) {
58
+ }
59
+ if (bufferBytes >= FLUSH_BYTES) flush();
60
+ },
61
+ sampling: { mousemove: 20, scroll: 150 },
62
+ maskAllInputs: inputMode === "all",
63
+ maskInputOptions,
64
+ blockClass: maskClass,
65
+ ignoreClass: maskClass,
66
+ maskTextClass: maskClass,
67
+ recordCanvas: false,
68
+ collectFonts: false,
69
+ checkoutEveryNms: CHECKOUT_EVERY_MS
70
+ });
71
+ stopFn = typeof stop === "function" ? stop : null;
72
+ }
73
+ function stopRrwebOnly() {
74
+ try {
75
+ _optionalChain([stopFn, 'optionalCall', _7 => _7()]);
76
+ } finally {
77
+ stopFn = null;
78
+ }
79
+ flush();
80
+ }
81
+ function flush(useBeacon = false) {
82
+ if (buffer.length === 0) return;
83
+ const chunk = buffer;
84
+ buffer = [];
85
+ bufferBytes = 0;
86
+ try {
87
+ args.sendChunk(chunk, useBeacon);
88
+ } catch (e3) {
89
+ }
90
+ }
91
+ function onActivity() {
92
+ lastActivityAt = Date.now();
93
+ if (!stopFn && !paused && !stopped) startRecorder();
94
+ }
95
+ for (const ev of ACTIVITY_EVENTS) {
96
+ window.addEventListener(ev, onActivity, { passive: true });
97
+ }
98
+ const onPageHide = () => flush(true);
99
+ window.addEventListener("pagehide", onPageHide);
100
+ startRecorder();
101
+ return {
102
+ pause() {
103
+ paused = true;
104
+ stopRrwebOnly();
105
+ },
106
+ resume() {
107
+ paused = false;
108
+ lastActivityAt = Date.now();
109
+ startRecorder();
110
+ },
111
+ stop() {
112
+ stopped = true;
113
+ stopRrwebOnly();
114
+ clearInterval(flushTimer);
115
+ clearInterval(idleTimer);
116
+ for (const ev of ACTIVITY_EVENTS) {
117
+ window.removeEventListener(ev, onActivity);
118
+ }
119
+ window.removeEventListener("pagehide", onPageHide);
120
+ },
121
+ flush
122
+ };
123
+ }
124
+
125
+
126
+ exports.startRrweb = startRrweb;