@particle-academy/fancy-pixel 0.1.0 → 0.2.1

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/index.js CHANGED
@@ -29,6 +29,533 @@ function sendPixelBeacon(endpoint, payload) {
29
29
  return false;
30
30
  }
31
31
 
32
+ // node_modules/@particle-academy/fancy-heuristics-js/dist/chunk-3RKEJJ4Y.js
33
+ function base(kind, actor, path, ts) {
34
+ return { kind, actor, path, ts };
35
+ }
36
+ function buildPageview(path, ts, actor = "human") {
37
+ return base("pageview", actor, path, ts);
38
+ }
39
+ function buildClick(args) {
40
+ const e = base("click", args.actor ?? "human", args.path, args.ts);
41
+ e.x = args.x;
42
+ e.y = args.y;
43
+ e.vw = args.vw;
44
+ e.vh = args.vh;
45
+ if (args.targetId !== void 0) e.targetId = args.targetId;
46
+ if (args.label !== void 0) e.label = args.label;
47
+ if (args.meta !== void 0) e.meta = args.meta;
48
+ return e;
49
+ }
50
+ function buildScroll(args) {
51
+ const e = base("scroll", args.actor ?? "human", args.path, args.ts);
52
+ e.scrollPct = args.scrollPct;
53
+ return e;
54
+ }
55
+ function buildPointer(args) {
56
+ const e = base("pointer", args.actor ?? "human", args.path, args.ts);
57
+ e.x = args.x;
58
+ e.y = args.y;
59
+ e.vw = args.vw;
60
+ e.vh = args.vh;
61
+ return e;
62
+ }
63
+ function buildDwell(args) {
64
+ const e = base("dwell", args.actor ?? "human", args.path, args.ts);
65
+ e.dwellMs = args.dwellMs;
66
+ return e;
67
+ }
68
+ function scrollPercent(scrollTop, scrollable) {
69
+ if (scrollable <= 0) return 100;
70
+ const pct = scrollTop / scrollable * 100;
71
+ if (pct <= 0) return 0;
72
+ if (pct >= 100) return 100;
73
+ return Math.round(pct);
74
+ }
75
+ function mapActivityToEvent(e, path) {
76
+ const source = e.source ?? "agent";
77
+ if (source !== "agent" && source !== "flow") return void 0;
78
+ const targetId = e.target?.elementId;
79
+ const label = e.target?.label;
80
+ const dwellMs = numericMeta(e.meta, "dwellMs");
81
+ if (dwellMs !== void 0) {
82
+ const ev2 = buildDwell({ path, ts: e.timestamp, dwellMs, actor: "agent" });
83
+ if (targetId !== void 0) ev2.targetId = targetId;
84
+ if (label !== void 0) ev2.label = label;
85
+ ev2.meta = { action: e.action, agentId: e.agentId, source };
86
+ return ev2;
87
+ }
88
+ const ev = buildClick({
89
+ path,
90
+ ts: e.timestamp,
91
+ x: numericMeta(e.meta, "x") ?? 0,
92
+ y: numericMeta(e.meta, "y") ?? 0,
93
+ vw: numericMeta(e.meta, "vw") ?? 0,
94
+ vh: numericMeta(e.meta, "vh") ?? 0,
95
+ actor: "agent",
96
+ targetId,
97
+ label,
98
+ meta: { action: e.action, agentId: e.agentId, source }
99
+ });
100
+ return ev;
101
+ }
102
+ function numericMeta(meta, key) {
103
+ const v = meta?.[key];
104
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
105
+ }
106
+ async function tapAgentActivity(opts) {
107
+ const load = opts.loadModule ?? defaultLoad;
108
+ let mod;
109
+ try {
110
+ mod = await load();
111
+ } catch {
112
+ mod = void 0;
113
+ }
114
+ if (!mod || typeof mod.onActivity !== "function") return () => {
115
+ };
116
+ try {
117
+ return mod.onActivity((e) => {
118
+ const ev = mapActivityToEvent(e, opts.path());
119
+ if (ev) opts.emit(ev);
120
+ });
121
+ } catch {
122
+ return () => {
123
+ };
124
+ }
125
+ }
126
+ async function defaultLoad() {
127
+ const spec = "@particle-academy/fancy-auto-common";
128
+ try {
129
+ const mod = await import(
130
+ /* @vite-ignore */
131
+ spec
132
+ );
133
+ if (mod && typeof mod.onActivity === "function") {
134
+ return mod;
135
+ }
136
+ return void 0;
137
+ } catch {
138
+ return void 0;
139
+ }
140
+ }
141
+ var EventBuffer = class {
142
+ constructor(opts) {
143
+ this.events = [];
144
+ this.siteKey = opts.siteKey;
145
+ this.url = joinCollect(opts.endpoint);
146
+ this.sessionId = opts.sessionId;
147
+ this.context = opts.context;
148
+ this.send = opts.send ?? defaultSend;
149
+ }
150
+ /** Queue one event for the next flush. */
151
+ add(event) {
152
+ this.events.push(event);
153
+ }
154
+ /** Number of buffered (un-flushed) events. */
155
+ get size() {
156
+ return this.events.length;
157
+ }
158
+ /** The collect URL this buffer ships to. */
159
+ get collectUrl() {
160
+ return this.url;
161
+ }
162
+ /**
163
+ * Ship the buffered events as one batch. No-op when empty. On a failed
164
+ * handoff the events are kept so the next flush retries them.
165
+ */
166
+ flush() {
167
+ if (this.events.length === 0) return;
168
+ const batch = {
169
+ siteKey: this.siteKey,
170
+ sessionId: this.sessionId,
171
+ events: this.events
172
+ };
173
+ if (this.context !== void 0) batch.context = this.context;
174
+ const body = JSON.stringify(batch);
175
+ const ok = this.send(this.url, body);
176
+ if (ok) {
177
+ this.events = [];
178
+ this.context = void 0;
179
+ }
180
+ }
181
+ };
182
+ function joinCollect(endpoint) {
183
+ return endpoint.replace(/\/+$/, "") + "/collect";
184
+ }
185
+ var defaultSend = (url, body) => {
186
+ const nav = typeof navigator !== "undefined" ? navigator : void 0;
187
+ if (nav && typeof nav.sendBeacon === "function") {
188
+ try {
189
+ const blob = typeof Blob !== "undefined" ? new Blob([body], { type: "application/json" }) : body;
190
+ if (nav.sendBeacon(url, blob)) return true;
191
+ } catch {
192
+ }
193
+ }
194
+ if (typeof fetch === "function") {
195
+ try {
196
+ void fetch(url, {
197
+ method: "POST",
198
+ body,
199
+ headers: { "Content-Type": "application/json" },
200
+ keepalive: true,
201
+ // Cross-origin ingestion: the PHP routes are CSRF-exempt; we don't read
202
+ // the response, so an opaque mode is fine.
203
+ mode: "cors",
204
+ credentials: "omit"
205
+ }).catch(() => {
206
+ });
207
+ return true;
208
+ } catch {
209
+ return false;
210
+ }
211
+ }
212
+ return false;
213
+ };
214
+ var UTM_KEYS = [
215
+ ["utm_source", "source"],
216
+ ["utm_medium", "medium"],
217
+ ["utm_campaign", "campaign"],
218
+ ["utm_term", "term"],
219
+ ["utm_content", "content"]
220
+ ];
221
+ function buildContext() {
222
+ if (typeof document === "undefined" || !document) return void 0;
223
+ const ctx = {};
224
+ if (typeof document.referrer === "string") {
225
+ ctx.referrer = document.referrer;
226
+ }
227
+ const utm = parseUtm(
228
+ typeof location !== "undefined" && location ? location.search : void 0
229
+ );
230
+ if (utm) ctx.utm = utm;
231
+ const nav = typeof navigator !== "undefined" ? navigator : void 0;
232
+ if (nav && typeof nav.language === "string" && nav.language) {
233
+ ctx.lang = nav.language;
234
+ }
235
+ const tz = resolveTimeZone();
236
+ if (tz) ctx.tz = tz;
237
+ const scr = typeof screen !== "undefined" ? screen : void 0;
238
+ if (scr) {
239
+ if (typeof scr.width === "number") ctx.screenW = scr.width;
240
+ if (typeof scr.height === "number") ctx.screenH = scr.height;
241
+ }
242
+ if (typeof window !== "undefined" && typeof window.devicePixelRatio === "number") {
243
+ ctx.dpr = window.devicePixelRatio;
244
+ }
245
+ return ctx;
246
+ }
247
+ function parseUtm(search) {
248
+ if (!search || typeof URLSearchParams === "undefined") return void 0;
249
+ let params;
250
+ try {
251
+ params = new URLSearchParams(search);
252
+ } catch {
253
+ return void 0;
254
+ }
255
+ const utm = {};
256
+ let found = false;
257
+ for (const [param, field] of UTM_KEYS) {
258
+ const raw = params.get(param);
259
+ if (raw) {
260
+ utm[field] = raw;
261
+ found = true;
262
+ }
263
+ }
264
+ return found ? utm : void 0;
265
+ }
266
+ function resolveTimeZone() {
267
+ try {
268
+ if (typeof Intl === "undefined" || typeof Intl.DateTimeFormat !== "function") {
269
+ return void 0;
270
+ }
271
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
272
+ return tz || void 0;
273
+ } catch {
274
+ return void 0;
275
+ }
276
+ }
277
+ var SESSION_KEY = "fancy-heuristics:sid";
278
+ var fallbackCounter = 0;
279
+ function generateSessionId() {
280
+ const c = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
281
+ if (c && typeof c.randomUUID === "function") {
282
+ return c.randomUUID();
283
+ }
284
+ if (c && typeof c.getRandomValues === "function") {
285
+ const bytes = new Uint8Array(16);
286
+ c.getRandomValues(bytes);
287
+ bytes[6] = bytes[6] & 15 | 64;
288
+ bytes[8] = bytes[8] & 63 | 128;
289
+ const hex = [];
290
+ for (let i = 0; i < 16; i++) hex.push(bytes[i].toString(16).padStart(2, "0"));
291
+ return hex.slice(0, 4).join("") + "-" + hex.slice(4, 6).join("") + "-" + hex.slice(6, 8).join("") + "-" + hex.slice(8, 10).join("") + "-" + hex.slice(10, 16).join("");
292
+ }
293
+ fallbackCounter = fallbackCounter + 1 >>> 0;
294
+ return `fh-${Date.now().toString(36)}-${fallbackCounter.toString(36)}`;
295
+ }
296
+ function resolveSessionId(store) {
297
+ const s = safeSessionStorage();
298
+ if (!s) return generateSessionId();
299
+ try {
300
+ const existing = s.getItem(SESSION_KEY);
301
+ if (existing) return existing;
302
+ const fresh = generateSessionId();
303
+ s.setItem(SESSION_KEY, fresh);
304
+ return fresh;
305
+ } catch {
306
+ return generateSessionId();
307
+ }
308
+ }
309
+ function safeSessionStorage() {
310
+ try {
311
+ const ss = globalThis.sessionStorage;
312
+ if (!ss) return void 0;
313
+ ss.getItem(SESSION_KEY);
314
+ return ss;
315
+ } catch {
316
+ return void 0;
317
+ }
318
+ }
319
+ var DEFAULT_FLUSH_MS = 1500;
320
+ var DEFAULT_POINTER_THROTTLE_MS = 120;
321
+ var DEFAULT_SCROLL_THROTTLE_MS = 200;
322
+ function resolveTrack(track) {
323
+ return {
324
+ pageview: track?.pageview ?? true,
325
+ dwell: track?.dwell ?? true,
326
+ click: track?.click ?? true,
327
+ scroll: track?.scroll ?? true,
328
+ pointer: track?.pointer ?? true,
329
+ agent: track?.agent ?? true
330
+ };
331
+ }
332
+ function createCollector(opts) {
333
+ if (!opts || !opts.siteKey || !opts.endpoint) {
334
+ throw new Error("createCollector: { siteKey, endpoint } are required");
335
+ }
336
+ const track = resolveTrack(opts.track);
337
+ const flushMs = opts.flushMs ?? DEFAULT_FLUSH_MS;
338
+ const pointerThrottleMs = opts.pointerThrottleMs ?? DEFAULT_POINTER_THROTTLE_MS;
339
+ const scrollThrottleMs = opts.scrollThrottleMs ?? DEFAULT_SCROLL_THROTTLE_MS;
340
+ const sessionId = resolveSessionId();
341
+ const context = buildContext();
342
+ const buffer = new EventBuffer({
343
+ siteKey: opts.siteKey,
344
+ endpoint: opts.endpoint,
345
+ sessionId,
346
+ ...context !== void 0 ? { context } : {}
347
+ });
348
+ let started = false;
349
+ let flushTimer;
350
+ let agentUnsub;
351
+ const teardown = [];
352
+ let visibleSince = 0;
353
+ let accumulatedDwell = 0;
354
+ let maxScrollPct = 0;
355
+ let lastScrollAt = 0;
356
+ let lastPointerAt = 0;
357
+ const path = () => typeof location !== "undefined" && location ? location.pathname : "/";
358
+ const now = opts.now ?? (() => Date.now());
359
+ const vw = () => typeof window !== "undefined" ? window.innerWidth || 0 : 0;
360
+ const vh = () => typeof window !== "undefined" ? window.innerHeight || 0 : 0;
361
+ const emit = (e) => buffer.add(e);
362
+ const onClick = (ev) => {
363
+ const me = ev;
364
+ const targetEl = ev.target;
365
+ const { id, label } = describeTarget(targetEl);
366
+ emit(
367
+ buildClick({
368
+ path: path(),
369
+ ts: now(),
370
+ x: Math.round(me.clientX ?? 0),
371
+ y: Math.round(me.clientY ?? 0),
372
+ vw: vw(),
373
+ vh: vh(),
374
+ targetId: id,
375
+ label
376
+ })
377
+ );
378
+ };
379
+ const onScroll = () => {
380
+ const t = now();
381
+ if (t - lastScrollAt < scrollThrottleMs) return;
382
+ lastScrollAt = t;
383
+ const doc = typeof document !== "undefined" ? document.documentElement : void 0;
384
+ if (!doc) return;
385
+ const scrollTop = (typeof window !== "undefined" ? window.scrollY : 0) || doc.scrollTop || 0;
386
+ const scrollable = doc.scrollHeight - doc.clientHeight;
387
+ const pct = scrollPercent(scrollTop, scrollable);
388
+ if (pct > maxScrollPct) {
389
+ maxScrollPct = pct;
390
+ emit(buildScroll({ path: path(), ts: t, scrollPct: maxScrollPct }));
391
+ }
392
+ };
393
+ const onPointerMove = (ev) => {
394
+ const t = now();
395
+ if (t - lastPointerAt < pointerThrottleMs) return;
396
+ lastPointerAt = t;
397
+ const pe = ev;
398
+ emit(
399
+ buildPointer({
400
+ path: path(),
401
+ ts: t,
402
+ x: Math.round(pe.clientX ?? 0),
403
+ y: Math.round(pe.clientY ?? 0),
404
+ vw: vw(),
405
+ vh: vh()
406
+ })
407
+ );
408
+ };
409
+ const isVisible = () => typeof document === "undefined" || document.visibilityState !== "hidden";
410
+ const openDwellWindow = () => {
411
+ if (visibleSince === 0) visibleSince = now();
412
+ };
413
+ const closeDwellWindow = () => {
414
+ if (visibleSince !== 0) {
415
+ accumulatedDwell += now() - visibleSince;
416
+ visibleSince = 0;
417
+ }
418
+ };
419
+ const onVisibilityChange = () => {
420
+ if (isVisible()) openDwellWindow();
421
+ else closeDwellWindow();
422
+ };
423
+ const emitDwell = () => {
424
+ closeDwellWindow();
425
+ if (accumulatedDwell > 0) {
426
+ emit(buildDwell({ path: path(), ts: now(), dwellMs: accumulatedDwell }));
427
+ accumulatedDwell = 0;
428
+ }
429
+ if (isVisible()) openDwellWindow();
430
+ };
431
+ const onPageHide = () => {
432
+ if (track.dwell) {
433
+ closeDwellWindow();
434
+ if (accumulatedDwell > 0) {
435
+ emit(buildDwell({ path: path(), ts: now(), dwellMs: accumulatedDwell }));
436
+ accumulatedDwell = 0;
437
+ }
438
+ }
439
+ buffer.flush();
440
+ };
441
+ const addListener = (target, type, handler, options) => {
442
+ if (!target || typeof target.addEventListener !== "function") return;
443
+ target.addEventListener(type, handler, options);
444
+ teardown.push(() => target.removeEventListener(type, handler, options));
445
+ };
446
+ return {
447
+ start() {
448
+ if (started) return;
449
+ started = true;
450
+ const doc = typeof document !== "undefined" ? document : void 0;
451
+ const win = typeof window !== "undefined" ? window : void 0;
452
+ if (track.pageview) {
453
+ emit(buildPageview(path(), now()));
454
+ }
455
+ if (track.dwell) {
456
+ openDwellWindow();
457
+ addListener(doc, "visibilitychange", onVisibilityChange);
458
+ }
459
+ if (track.click) {
460
+ addListener(doc, "click", onClick, { capture: true, passive: true });
461
+ }
462
+ if (track.scroll) {
463
+ addListener(win, "scroll", onScroll, { passive: true });
464
+ }
465
+ if (track.pointer) {
466
+ addListener(win, "pointermove", onPointerMove, { passive: true });
467
+ }
468
+ addListener(win, "pagehide", onPageHide);
469
+ if (track.agent) {
470
+ void tapAgentActivity({ path, emit }).then((unsub) => {
471
+ if (started) agentUnsub = unsub;
472
+ else unsub();
473
+ });
474
+ }
475
+ if (typeof setInterval === "function") {
476
+ flushTimer = setInterval(() => {
477
+ if (track.dwell) emitDwell();
478
+ buffer.flush();
479
+ }, flushMs);
480
+ }
481
+ },
482
+ stop() {
483
+ if (!started) return;
484
+ started = false;
485
+ if (flushTimer !== void 0) {
486
+ clearInterval(flushTimer);
487
+ flushTimer = void 0;
488
+ }
489
+ for (const fn of teardown.splice(0)) {
490
+ try {
491
+ fn();
492
+ } catch {
493
+ }
494
+ }
495
+ if (agentUnsub) {
496
+ try {
497
+ agentUnsub();
498
+ } catch {
499
+ }
500
+ agentUnsub = void 0;
501
+ }
502
+ if (track.dwell) {
503
+ closeDwellWindow();
504
+ if (accumulatedDwell > 0) {
505
+ emit(buildDwell({ path: path(), ts: now(), dwellMs: accumulatedDwell }));
506
+ accumulatedDwell = 0;
507
+ }
508
+ }
509
+ buffer.flush();
510
+ },
511
+ flush() {
512
+ buffer.flush();
513
+ }
514
+ };
515
+ }
516
+ function describeTarget(el) {
517
+ if (!el) return {};
518
+ let node = el;
519
+ let id;
520
+ for (let depth = 0; node && depth < 5; depth++) {
521
+ const candidate = node.getAttribute?.("data-fancy-id") ?? node.getAttribute?.("data-testid") ?? (node.id || void 0);
522
+ if (candidate) {
523
+ id = candidate;
524
+ break;
525
+ }
526
+ node = node.parentElement;
527
+ }
528
+ const labelSource = node ?? el;
529
+ const label = readLabel(labelSource);
530
+ const out = {};
531
+ if (id !== void 0) out.id = id;
532
+ if (label !== void 0) out.label = label;
533
+ return out;
534
+ }
535
+ function readLabel(el) {
536
+ const aria = el.getAttribute?.("aria-label");
537
+ if (aria) return trim(aria);
538
+ const text = el.textContent;
539
+ if (text) {
540
+ const t = trim(text);
541
+ if (t) return t;
542
+ }
543
+ const tag = el.tagName ? el.tagName.toLowerCase() : void 0;
544
+ return tag;
545
+ }
546
+ function trim(s) {
547
+ return s.replace(/\s+/g, " ").trim().slice(0, 120);
548
+ }
549
+
550
+ // src/collector.ts
551
+ var factory = (opts) => createCollector({ siteKey: opts.siteKey, endpoint: opts.endpoint });
552
+ function createPixelCollector(opts) {
553
+ return factory(opts);
554
+ }
555
+ function __setCollectorFactory(next) {
556
+ factory = next ?? ((opts) => createCollector({ siteKey: opts.siteKey, endpoint: opts.endpoint }));
557
+ }
558
+
32
559
  // src/render.ts
33
560
  function logoGlyph(size) {
34
561
  return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" aria-hidden="true" focusable="false" style="display:block;flex:0 0 auto;">
@@ -189,6 +716,7 @@ function mountPixel(opts = {}) {
189
716
  const mode = MODES.includes(opts.mode) ? opts.mode : "floating";
190
717
  const siteKey = opts.siteKey ?? "";
191
718
  const endpoint = opts.endpoint ?? "";
719
+ const collect = opts.collect !== false;
192
720
  const href = opts.href ?? DEFAULT_HREF;
193
721
  const target = opts.target ?? null;
194
722
  const host = createPixelHost(style, mode, href);
@@ -242,11 +770,21 @@ function mountPixel(opts = {}) {
242
770
  setVisible(true);
243
771
  }
244
772
  beacon();
773
+ let collector = null;
774
+ if (endpoint && collect) {
775
+ try {
776
+ collector = createPixelCollector({ siteKey, endpoint });
777
+ collector.start();
778
+ } catch {
779
+ collector = null;
780
+ }
781
+ }
245
782
  const resolved = {
246
783
  style,
247
784
  mode,
248
785
  siteKey,
249
786
  endpoint,
787
+ collect,
250
788
  href,
251
789
  target
252
790
  };
@@ -255,12 +793,22 @@ function mountPixel(opts = {}) {
255
793
  get visible() {
256
794
  return visible;
257
795
  },
796
+ get collector() {
797
+ return collector;
798
+ },
258
799
  options: resolved,
259
800
  destroy() {
260
801
  if (destroyed) return;
261
802
  destroyed = true;
262
803
  observer?.disconnect();
263
804
  observer = null;
805
+ if (collector) {
806
+ try {
807
+ collector.stop();
808
+ } catch {
809
+ }
810
+ collector = null;
811
+ }
264
812
  host.remove();
265
813
  }
266
814
  };
@@ -278,14 +826,16 @@ function readScriptConfig() {
278
826
  }
279
827
  if (!el) return null;
280
828
  const ds = el.dataset;
281
- if (ds.style === void 0 && ds.mode === void 0 && ds.site === void 0 && ds.endpoint === void 0 && ds.fancyPixel === void 0) {
829
+ if (ds.style === void 0 && ds.mode === void 0 && ds.site === void 0 && ds.endpoint === void 0 && ds.collect === void 0 && ds.fancyPixel === void 0) {
282
830
  return null;
283
831
  }
832
+ const collect = ds.collect !== void 0 ? ds.collect !== "false" : void 0;
284
833
  return {
285
834
  style: ds.style,
286
835
  mode: ds.mode,
287
836
  siteKey: ds.site,
288
837
  endpoint: ds.endpoint,
838
+ collect,
289
839
  target: ds.target ?? null,
290
840
  href: ds.href
291
841
  };
@@ -308,6 +858,6 @@ function autoInit() {
308
858
  return run();
309
859
  }
310
860
 
311
- export { autoInit, createPixelHost, hostStyleFor, mountPixel, sendPixelBeacon };
861
+ export { __setCollectorFactory, autoInit, createPixelCollector, createPixelHost, hostStyleFor, mountPixel, sendPixelBeacon };
312
862
  //# sourceMappingURL=index.js.map
313
863
  //# sourceMappingURL=index.js.map