@entrolytics/svelte-sdk 2.2.0 → 3.0.2

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
@@ -1,866 +1,630 @@
1
- import { onMount } from 'svelte';
2
- import { writable } from 'svelte/store';
1
+ import { API_ROUTES } from "@entrolytics/shared";
2
+ import { onMount } from "svelte";
3
+ import { writable } from "svelte/store";
3
4
 
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __esm = (fn, res) => function __init() {
7
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
- };
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
-
14
- // node_modules/.pnpm/web-vitals@5.1.0/node_modules/web-vitals/dist/web-vitals.attribution.js
15
- var web_vitals_attribution_exports = {};
16
- __export(web_vitals_attribution_exports, {
17
- CLSThresholds: () => L,
18
- FCPThresholds: () => E,
19
- INPThresholds: () => q,
20
- LCPThresholds: () => H,
21
- TTFBThresholds: () => U,
22
- onCLS: () => S,
23
- onFCP: () => w,
24
- onINP: () => x,
25
- onLCP: () => R,
26
- onTTFB: () => $
27
- });
28
- function s(t2, e2) {
29
- return r.get(t2) || r.set(t2, new e2()), r.get(t2);
30
- }
31
- var t, e, n, o, i, r, a, c, f, u, d, l, h, m, p, g, y, v, b, M, T, E, D, L, P, S, w, _, F, k, B, C, O, j, I, A, W, q, x, N, H, R, U, V, $;
32
- var init_web_vitals_attribution = __esm({
33
- "node_modules/.pnpm/web-vitals@5.1.0/node_modules/web-vitals/dist/web-vitals.attribution.js"() {
34
- t = class {
35
- t;
36
- o = 0;
37
- i = [];
38
- u(t2) {
39
- if (t2.hadRecentInput) return;
40
- const e2 = this.i[0], n2 = this.i.at(-1);
41
- this.o && e2 && n2 && t2.startTime - n2.startTime < 1e3 && t2.startTime - e2.startTime < 5e3 ? (this.o += t2.value, this.i.push(t2)) : (this.o = t2.value, this.i = [t2]), this.t?.(t2);
42
- }
43
- };
44
- e = () => {
45
- const t2 = performance.getEntriesByType("navigation")[0];
46
- if (t2 && t2.responseStart > 0 && t2.responseStart < performance.now()) return t2;
47
- };
48
- n = (t2) => {
49
- if ("loading" === document.readyState) return "loading";
50
- {
51
- const n2 = e();
52
- if (n2) {
53
- if (t2 < n2.domInteractive) return "loading";
54
- if (0 === n2.domContentLoadedEventStart || t2 < n2.domContentLoadedEventStart) return "dom-interactive";
55
- if (0 === n2.domComplete || t2 < n2.domComplete) return "dom-content-loaded";
56
- }
57
- }
58
- return "complete";
59
- };
60
- o = (t2) => {
61
- const e2 = t2.nodeName;
62
- return 1 === t2.nodeType ? e2.toLowerCase() : e2.toUpperCase().replace(/^#/, "");
63
- };
64
- i = (t2) => {
65
- let e2 = "";
66
- try {
67
- for (; 9 !== t2?.nodeType; ) {
68
- const n2 = t2, i2 = n2.id ? "#" + n2.id : [o(n2), ...Array.from(n2.classList).sort()].join(".");
69
- if (e2.length + i2.length > 99) return e2 || i2;
70
- if (e2 = e2 ? i2 + ">" + e2 : i2, n2.id) break;
71
- t2 = n2.parentNode;
72
- }
73
- } catch {
74
- }
75
- return e2;
76
- };
77
- r = /* @__PURE__ */ new WeakMap();
78
- a = -1;
79
- c = () => a;
80
- f = (t2) => {
81
- addEventListener("pageshow", ((e2) => {
82
- e2.persisted && (a = e2.timeStamp, t2(e2));
83
- }), true);
84
- };
85
- u = (t2, e2, n2, o2) => {
86
- let i2, r2;
87
- return (s2) => {
88
- e2.value >= 0 && (s2 || o2) && (r2 = e2.value - (i2 ?? 0), (r2 || void 0 === i2) && (i2 = e2.value, e2.delta = r2, e2.rating = ((t3, e3) => t3 > e3[1] ? "poor" : t3 > e3[0] ? "needs-improvement" : "good")(e2.value, n2), t2(e2)));
89
- };
90
- };
91
- d = (t2) => {
92
- requestAnimationFrame((() => requestAnimationFrame((() => t2()))));
93
- };
94
- l = () => {
95
- const t2 = e();
96
- return t2?.activationStart ?? 0;
97
- };
98
- h = (t2, n2 = -1) => {
99
- const o2 = e();
100
- let i2 = "navigate";
101
- c() >= 0 ? i2 = "back-forward-cache" : o2 && (document.prerendering || l() > 0 ? i2 = "prerender" : document.wasDiscarded ? i2 = "restore" : o2.type && (i2 = o2.type.replace(/_/g, "-")));
102
- return { name: t2, value: n2, rating: "good", delta: 0, entries: [], id: `v5-${Date.now()}-${Math.floor(8999999999999 * Math.random()) + 1e12}`, navigationType: i2 };
103
- };
104
- m = (t2, e2, n2 = {}) => {
105
- try {
106
- if (PerformanceObserver.supportedEntryTypes.includes(t2)) {
107
- const o2 = new PerformanceObserver(((t3) => {
108
- Promise.resolve().then((() => {
109
- e2(t3.getEntries());
110
- }));
111
- }));
112
- return o2.observe({ type: t2, buffered: true, ...n2 }), o2;
113
- }
114
- } catch {
115
- }
116
- };
117
- p = (t2) => {
118
- let e2 = false;
119
- return () => {
120
- e2 || (t2(), e2 = true);
121
- };
122
- };
123
- g = -1;
124
- y = /* @__PURE__ */ new Set();
125
- v = () => "hidden" !== document.visibilityState || document.prerendering ? 1 / 0 : 0;
126
- b = (t2) => {
127
- if ("hidden" === document.visibilityState) {
128
- if ("visibilitychange" === t2.type) for (const t3 of y) t3();
129
- isFinite(g) || (g = "visibilitychange" === t2.type ? t2.timeStamp : 0, removeEventListener("prerenderingchange", b, true));
130
- }
131
- };
132
- M = () => {
133
- if (g < 0) {
134
- const t2 = l(), e2 = document.prerendering ? void 0 : globalThis.performance.getEntriesByType("visibility-state").filter(((e3) => "hidden" === e3.name && e3.startTime > t2))[0]?.startTime;
135
- g = e2 ?? v(), addEventListener("visibilitychange", b, true), addEventListener("prerenderingchange", b, true), f((() => {
136
- setTimeout((() => {
137
- g = v();
138
- }));
139
- }));
140
- }
141
- return { get firstHiddenTime() {
142
- return g;
143
- }, onHidden(t2) {
144
- y.add(t2);
145
- } };
146
- };
147
- T = (t2) => {
148
- document.prerendering ? addEventListener("prerenderingchange", (() => t2()), true) : t2();
149
- };
150
- E = [1800, 3e3];
151
- D = (t2, e2 = {}) => {
152
- T((() => {
153
- const n2 = M();
154
- let o2, i2 = h("FCP");
155
- const r2 = m("paint", ((t3) => {
156
- for (const e3 of t3) "first-contentful-paint" === e3.name && (r2.disconnect(), e3.startTime < n2.firstHiddenTime && (i2.value = Math.max(e3.startTime - l(), 0), i2.entries.push(e3), o2(true)));
157
- }));
158
- r2 && (o2 = u(t2, i2, E, e2.reportAllChanges), f(((n3) => {
159
- i2 = h("FCP"), o2 = u(t2, i2, E, e2.reportAllChanges), d((() => {
160
- i2.value = performance.now() - n3.timeStamp, o2(true);
161
- }));
162
- })));
163
- }));
164
- };
165
- L = [0.1, 0.25];
166
- P = (t2) => t2.find(((t3) => 1 === t3.node?.nodeType)) || t2[0];
167
- S = (e2, o2 = {}) => {
168
- const r2 = s(o2 = Object.assign({}, o2), t), a2 = /* @__PURE__ */ new WeakMap();
169
- r2.t = (t2) => {
170
- if (t2?.sources?.length) {
171
- const e3 = P(t2.sources), n2 = e3?.node;
172
- if (n2) {
173
- const t3 = o2.generateTarget?.(n2) ?? i(n2);
174
- a2.set(e3, t3);
175
- }
176
- }
177
- };
178
- ((e3, n2 = {}) => {
179
- const o3 = M();
180
- D(p((() => {
181
- let i2, r3 = h("CLS", 0);
182
- const a3 = s(n2, t), c2 = (t2) => {
183
- for (const e4 of t2) a3.u(e4);
184
- a3.o > r3.value && (r3.value = a3.o, r3.entries = a3.i, i2());
185
- }, l2 = m("layout-shift", c2);
186
- l2 && (i2 = u(e3, r3, L, n2.reportAllChanges), o3.onHidden((() => {
187
- c2(l2.takeRecords()), i2(true);
188
- })), f((() => {
189
- a3.o = 0, r3 = h("CLS", 0), i2 = u(e3, r3, L, n2.reportAllChanges), d((() => i2()));
190
- })), setTimeout(i2));
191
- })));
192
- })(((t2) => {
193
- const o3 = ((t3) => {
194
- let e3 = {};
195
- if (t3.entries.length) {
196
- const o4 = t3.entries.reduce(((t4, e4) => t4.value > e4.value ? t4 : e4));
197
- if (o4?.sources?.length) {
198
- const t4 = P(o4.sources);
199
- t4 && (e3 = { largestShiftTarget: a2.get(t4), largestShiftTime: o4.startTime, largestShiftValue: o4.value, largestShiftSource: t4, largestShiftEntry: o4, loadState: n(o4.startTime) });
200
- }
201
- }
202
- return Object.assign(t3, { attribution: e3 });
203
- })(t2);
204
- e2(o3);
205
- }), o2);
206
- };
207
- w = (t2, o2 = {}) => {
208
- D(((o3) => {
209
- const i2 = ((t3) => {
210
- let o4 = { timeToFirstByte: 0, firstByteToFCP: t3.value, loadState: n(c()) };
211
- if (t3.entries.length) {
212
- const i3 = e(), r2 = t3.entries.at(-1);
213
- if (i3) {
214
- const e2 = i3.activationStart || 0, s2 = Math.max(0, i3.responseStart - e2);
215
- o4 = { timeToFirstByte: s2, firstByteToFCP: t3.value - s2, loadState: n(t3.entries[0].startTime), navigationEntry: i3, fcpEntry: r2 };
216
- }
217
- }
218
- return Object.assign(t3, { attribution: o4 });
219
- })(o3);
220
- t2(i2);
221
- }), o2);
222
- };
223
- _ = 0;
224
- F = 1 / 0;
225
- k = 0;
226
- B = (t2) => {
227
- for (const e2 of t2) e2.interactionId && (F = Math.min(F, e2.interactionId), k = Math.max(k, e2.interactionId), _ = k ? (k - F) / 7 + 1 : 0);
228
- };
229
- O = () => C ? _ : performance.interactionCount ?? 0;
230
- j = () => {
231
- "interactionCount" in performance || C || (C = m("event", B, { type: "event", buffered: true, durationThreshold: 0 }));
232
- };
233
- I = 0;
234
- A = class {
235
- l = [];
236
- h = /* @__PURE__ */ new Map();
237
- m;
238
- p;
239
- v() {
240
- I = O(), this.l.length = 0, this.h.clear();
241
- }
242
- M() {
243
- const t2 = Math.min(this.l.length - 1, Math.floor((O() - I) / 50));
244
- return this.l[t2];
245
- }
246
- u(t2) {
247
- if (this.m?.(t2), !t2.interactionId && "first-input" !== t2.entryType) return;
248
- const e2 = this.l.at(-1);
249
- let n2 = this.h.get(t2.interactionId);
250
- if (n2 || this.l.length < 10 || t2.duration > e2.T) {
251
- if (n2 ? t2.duration > n2.T ? (n2.entries = [t2], n2.T = t2.duration) : t2.duration === n2.T && t2.startTime === n2.entries[0].startTime && n2.entries.push(t2) : (n2 = { id: t2.interactionId, entries: [t2], T: t2.duration }, this.h.set(n2.id, n2), this.l.push(n2)), this.l.sort(((t3, e3) => e3.T - t3.T)), this.l.length > 10) {
252
- const t3 = this.l.splice(10);
253
- for (const e3 of t3) this.h.delete(e3.id);
254
- }
255
- this.p?.(n2);
256
- }
257
- }
258
- };
259
- W = (t2) => {
260
- const e2 = globalThis.requestIdleCallback || setTimeout;
261
- "hidden" === document.visibilityState ? t2() : (t2 = p(t2), addEventListener("visibilitychange", t2, { once: true, capture: true }), e2((() => {
262
- t2(), removeEventListener("visibilitychange", t2, { capture: true });
263
- })));
264
- };
265
- q = [200, 500];
266
- x = (t2, e2 = {}) => {
267
- const o2 = s(e2 = Object.assign({}, e2), A);
268
- let r2 = [], a2 = [], c2 = 0;
269
- const d2 = /* @__PURE__ */ new WeakMap(), l2 = /* @__PURE__ */ new WeakMap();
270
- let p2 = false;
271
- const g2 = () => {
272
- p2 || (W(y2), p2 = true);
273
- }, y2 = () => {
274
- const t3 = o2.l.map(((t4) => d2.get(t4.entries[0]))), e3 = a2.length - 50;
275
- a2 = a2.filter(((n3, o3) => o3 >= e3 || t3.includes(n3)));
276
- const n2 = /* @__PURE__ */ new Set();
277
- for (const t4 of a2) {
278
- const e4 = v2(t4.startTime, t4.processingEnd);
279
- for (const t5 of e4) n2.add(t5);
280
- }
281
- const i2 = r2.length - 1 - 50;
282
- r2 = r2.filter(((t4, e4) => t4.startTime > c2 && e4 > i2 || n2.has(t4))), p2 = false;
283
- };
284
- o2.m = (t3) => {
285
- const e3 = t3.startTime + t3.duration;
286
- let n2;
287
- c2 = Math.max(c2, t3.processingEnd);
288
- for (let o3 = a2.length - 1; o3 >= 0; o3--) {
289
- const i2 = a2[o3];
290
- if (Math.abs(e3 - i2.renderTime) <= 8) {
291
- n2 = i2, n2.startTime = Math.min(t3.startTime, n2.startTime), n2.processingStart = Math.min(t3.processingStart, n2.processingStart), n2.processingEnd = Math.max(t3.processingEnd, n2.processingEnd), n2.entries.push(t3);
292
- break;
293
- }
294
- }
295
- n2 || (n2 = { startTime: t3.startTime, processingStart: t3.processingStart, processingEnd: t3.processingEnd, renderTime: e3, entries: [t3] }, a2.push(n2)), (t3.interactionId || "first-input" === t3.entryType) && d2.set(t3, n2), g2();
296
- }, o2.p = (t3) => {
297
- if (!l2.get(t3)) {
298
- const n2 = t3.entries[0].target;
299
- if (n2) {
300
- const o3 = e2.generateTarget?.(n2) ?? i(n2);
301
- l2.set(t3, o3);
302
- }
303
- }
304
- };
305
- const v2 = (t3, e3) => {
306
- const n2 = [];
307
- for (const o3 of r2) if (!(o3.startTime + o3.duration < t3)) {
308
- if (o3.startTime > e3) break;
309
- n2.push(o3);
310
- }
311
- return n2;
312
- }, b2 = (t3) => {
313
- const e3 = t3.entries[0], i2 = d2.get(e3), r3 = e3.processingStart, s2 = Math.max(e3.startTime + e3.duration, r3), a3 = Math.min(i2.processingEnd, s2), c3 = i2.entries.sort(((t4, e4) => t4.processingStart - e4.processingStart)), f2 = v2(e3.startTime, a3), u2 = o2.h.get(e3.interactionId), h2 = { interactionTarget: l2.get(u2), interactionType: e3.name.startsWith("key") ? "keyboard" : "pointer", interactionTime: e3.startTime, nextPaintTime: s2, processedEventEntries: c3, longAnimationFrameEntries: f2, inputDelay: r3 - e3.startTime, processingDuration: a3 - r3, presentationDelay: s2 - a3, loadState: n(e3.startTime), longestScript: void 0, totalScriptDuration: void 0, totalStyleAndLayoutDuration: void 0, totalPaintDuration: void 0, totalUnattributedDuration: void 0 };
314
- ((t4) => {
315
- if (!t4.longAnimationFrameEntries?.length) return;
316
- const e4 = t4.interactionTime, n2 = t4.inputDelay, o3 = t4.processingDuration;
317
- let i3, r4, s3 = 0, a4 = 0, c4 = 0, f3 = 0;
318
- for (const c5 of t4.longAnimationFrameEntries) {
319
- a4 = a4 + c5.startTime + c5.duration - c5.styleAndLayoutStart;
320
- for (const t5 of c5.scripts) {
321
- const c6 = t5.startTime + t5.duration;
322
- if (c6 < e4) continue;
323
- const u4 = c6 - Math.max(e4, t5.startTime), d4 = t5.duration ? u4 / t5.duration * t5.forcedStyleAndLayoutDuration : 0;
324
- s3 += u4 - d4, a4 += d4, u4 > f3 && (r4 = t5.startTime < e4 + n2 ? "input-delay" : t5.startTime >= e4 + n2 + o3 ? "presentation-delay" : "processing-duration", i3 = t5, f3 = u4);
325
- }
326
- }
327
- const u3 = t4.longAnimationFrameEntries.at(-1), d3 = u3 ? u3.startTime + u3.duration : 0;
328
- d3 >= e4 + n2 + o3 && (c4 = t4.nextPaintTime - d3), i3 && r4 && (t4.longestScript = { entry: i3, subpart: r4, intersectingDuration: f3 }), t4.totalScriptDuration = s3, t4.totalStyleAndLayoutDuration = a4, t4.totalPaintDuration = c4, t4.totalUnattributedDuration = t4.nextPaintTime - e4 - s3 - a4 - c4;
329
- })(h2);
330
- return Object.assign(t3, { attribution: h2 });
331
- };
332
- m("long-animation-frame", ((t3) => {
333
- r2 = r2.concat(t3), g2();
334
- })), ((t3, e3 = {}) => {
335
- if (!globalThis.PerformanceEventTiming || !("interactionId" in PerformanceEventTiming.prototype)) return;
336
- const n2 = M();
337
- T((() => {
338
- j();
339
- let o3, i2 = h("INP");
340
- const r3 = s(e3, A), a3 = (t4) => {
341
- W((() => {
342
- for (const e5 of t4) r3.u(e5);
343
- const e4 = r3.M();
344
- e4 && e4.T !== i2.value && (i2.value = e4.T, i2.entries = e4.entries, o3());
345
- }));
346
- }, c3 = m("event", a3, { durationThreshold: e3.durationThreshold ?? 40 });
347
- o3 = u(t3, i2, q, e3.reportAllChanges), c3 && (c3.observe({ type: "first-input", buffered: true }), n2.onHidden((() => {
348
- a3(c3.takeRecords()), o3(true);
349
- })), f((() => {
350
- r3.v(), i2 = h("INP"), o3 = u(t3, i2, q, e3.reportAllChanges);
351
- })));
352
- }));
353
- })(((e3) => {
354
- const n2 = b2(e3);
355
- t2(n2);
356
- }), e2);
357
- };
358
- N = class {
359
- m;
360
- u(t2) {
361
- this.m?.(t2);
362
- }
363
- };
364
- H = [2500, 4e3];
365
- R = (t2, n2 = {}) => {
366
- const o2 = s(n2 = Object.assign({}, n2), N), r2 = /* @__PURE__ */ new WeakMap();
367
- o2.m = (t3) => {
368
- const e2 = t3.element;
369
- if (e2) {
370
- const o3 = n2.generateTarget?.(e2) ?? i(e2);
371
- r2.set(t3, o3);
372
- }
373
- };
374
- ((t3, e2 = {}) => {
375
- T((() => {
376
- const n3 = M();
377
- let o3, i2 = h("LCP");
378
- const r3 = s(e2, N), a2 = (t4) => {
379
- e2.reportAllChanges || (t4 = t4.slice(-1));
380
- for (const e3 of t4) r3.u(e3), e3.startTime < n3.firstHiddenTime && (i2.value = Math.max(e3.startTime - l(), 0), i2.entries = [e3], o3());
381
- }, c2 = m("largest-contentful-paint", a2);
382
- if (c2) {
383
- o3 = u(t3, i2, H, e2.reportAllChanges);
384
- const n4 = p((() => {
385
- a2(c2.takeRecords()), c2.disconnect(), o3(true);
386
- })), r4 = (t4) => {
387
- t4.isTrusted && (W(n4), removeEventListener(t4.type, r4, { capture: true }));
388
- };
389
- for (const t4 of ["keydown", "click", "visibilitychange"]) addEventListener(t4, r4, { capture: true });
390
- f(((n5) => {
391
- i2 = h("LCP"), o3 = u(t3, i2, H, e2.reportAllChanges), d((() => {
392
- i2.value = performance.now() - n5.timeStamp, o3(true);
393
- }));
394
- }));
395
- }
396
- }));
397
- })(((n3) => {
398
- const o3 = ((t3) => {
399
- let n4 = { timeToFirstByte: 0, resourceLoadDelay: 0, resourceLoadDuration: 0, elementRenderDelay: t3.value };
400
- if (t3.entries.length) {
401
- const o4 = e();
402
- if (o4) {
403
- const e2 = o4.activationStart || 0, i2 = t3.entries.at(-1), s2 = i2.url && performance.getEntriesByType("resource").filter(((t4) => t4.name === i2.url))[0], a2 = Math.max(0, o4.responseStart - e2), c2 = Math.max(a2, s2 ? (s2.requestStart || s2.startTime) - e2 : 0), f2 = Math.min(t3.value, Math.max(c2, s2 ? s2.responseEnd - e2 : 0));
404
- n4 = { target: r2.get(i2), timeToFirstByte: a2, resourceLoadDelay: c2 - a2, resourceLoadDuration: f2 - c2, elementRenderDelay: t3.value - f2, navigationEntry: o4, lcpEntry: i2 }, i2.url && (n4.url = i2.url), s2 && (n4.lcpResourceEntry = s2);
405
- }
406
- }
407
- return Object.assign(t3, { attribution: n4 });
408
- })(n3);
409
- t2(o3);
410
- }), n2);
411
- };
412
- U = [800, 1800];
413
- V = (t2) => {
414
- document.prerendering ? T((() => V(t2))) : "complete" !== document.readyState ? addEventListener("load", (() => V(t2)), true) : setTimeout(t2);
415
- };
416
- $ = (t2, n2 = {}) => {
417
- ((t3, n3 = {}) => {
418
- let o2 = h("TTFB"), i2 = u(t3, o2, U, n3.reportAllChanges);
419
- V((() => {
420
- const r2 = e();
421
- r2 && (o2.value = Math.max(r2.responseStart - l(), 0), o2.entries = [r2], i2(true), f((() => {
422
- o2 = h("TTFB", 0), i2 = u(t3, o2, U, n3.reportAllChanges), i2(true);
423
- })));
424
- }));
425
- })(((e2) => {
426
- const n3 = ((t3) => {
427
- let e3 = { waitingDuration: 0, cacheDuration: 0, dnsDuration: 0, connectionDuration: 0, requestDuration: 0 };
428
- if (t3.entries.length) {
429
- const n4 = t3.entries[0], o2 = n4.activationStart || 0, i2 = Math.max((n4.workerStart || n4.fetchStart) - o2, 0), r2 = Math.max(n4.domainLookupStart - o2, 0), s2 = Math.max(n4.connectStart - o2, 0), a2 = Math.max(n4.connectEnd - o2, 0);
430
- e3 = { waitingDuration: i2, cacheDuration: r2 - i2, dnsDuration: s2 - r2, connectionDuration: a2 - s2, requestDuration: t3.value - a2, navigationEntry: n4 };
431
- }
432
- return Object.assign(t3, { attribution: e3 });
433
- })(e2);
434
- t2(n3);
435
- }), n2);
436
- };
437
- }
438
- });
439
- var DEFAULT_HOST = "https://entrolytics.click";
440
- var SCRIPT_ID = "entrolytics-script";
441
- var isLoaded = writable(false);
442
- var isReady = writable(false);
443
- var initialized = false;
444
- var currentOptions = null;
445
- var currentTag;
5
+ // src/index.ts
6
+ const DEFAULT_HOST = "https://api.entrolytics.dev";
7
+ const SCRIPT_ID = "entrolytics-script";
8
+ const isLoaded = writable(false);
9
+ const isReady = writable(false);
10
+ let initialized = false;
11
+ let currentOptions = null;
12
+ let currentTag;
446
13
  function waitForTracker(callback) {
447
- if (typeof window === "undefined") return;
448
- const tryExecute = () => {
449
- if (window.entrolytics) {
450
- callback();
451
- } else {
452
- setTimeout(tryExecute, 100);
453
- }
454
- };
455
- tryExecute();
14
+ if (typeof window === "undefined") return;
15
+ const tryExecute = () => {
16
+ if (window.entrolytics) callback();
17
+ else setTimeout(tryExecute, 100);
18
+ };
19
+ tryExecute();
456
20
  }
21
+ /**
22
+ * Initialize Entrolytics tracking
23
+ *
24
+ * Call this in your root +layout.svelte
25
+ *
26
+ * @example
27
+ * Zero-config (reads from env):
28
+ * ```svelte
29
+ * <script>
30
+ * import { initEntrolytics } from '@entrolytics/svelte';
31
+ * initEntrolytics();
32
+ * <\/script>
33
+ * ```
34
+ *
35
+ * @example
36
+ * Explicit config:
37
+ * ```svelte
38
+ * <script>
39
+ * import { initEntrolytics } from '@entrolytics/svelte';
40
+ * initEntrolytics({ websiteId: 'your-website-id' });
41
+ * <\/script>
42
+ * ```
43
+ */
457
44
  function initEntrolytics(options = {}) {
458
- if (typeof window === "undefined") return;
459
- if (initialized) return;
460
- const env = import.meta.env || {};
461
- const websiteId = options.websiteId || env.VITE_ENTROLYTICS_WEBSITE_ID || env.PUBLIC_ENTROLYTICS_WEBSITE_ID;
462
- const host = options.host || env.VITE_ENTROLYTICS_HOST || env.PUBLIC_ENTROLYTICS_HOST;
463
- if (!websiteId) {
464
- if (env.DEV) {
465
- console.warn(
466
- "[@entrolytics/svelte] Missing websiteId. Add VITE_ENTROLYTICS_WEBSITE_ID or PUBLIC_ENTROLYTICS_WEBSITE_ID to your .env file."
467
- );
468
- }
469
- throw new Error("[@entrolytics/svelte] websiteId is required");
470
- }
471
- const finalOptions = {
472
- ...options,
473
- websiteId,
474
- host: host || DEFAULT_HOST
475
- };
476
- initialized = true;
477
- currentOptions = finalOptions;
478
- currentTag = finalOptions.tag;
479
- const {
480
- websiteId: finalWebsiteId,
481
- host: finalHost = DEFAULT_HOST,
482
- autoTrack = true,
483
- respectDnt = false,
484
- domains,
485
- useEdgeRuntime = true,
486
- tag,
487
- excludeSearch = false,
488
- excludeHash = false
489
- } = finalOptions;
490
- if (document.getElementById(SCRIPT_ID)) {
491
- isLoaded.set(true);
492
- isReady.set(true);
493
- return;
494
- }
495
- const script = document.createElement("script");
496
- script.id = SCRIPT_ID;
497
- const scriptPath = useEdgeRuntime ? "/script-edge.js" : "/script.js";
498
- script.src = `${finalHost.replace(/\/$/, "")}${scriptPath}`;
499
- script.defer = true;
500
- script.dataset.websiteId = finalWebsiteId;
501
- if (!autoTrack) {
502
- script.dataset.autoTrack = "false";
503
- }
504
- if (respectDnt) {
505
- script.dataset.doNotTrack = "true";
506
- }
507
- if (domains && domains.length > 0) {
508
- script.dataset.domains = domains.join(",");
509
- }
510
- if (tag) {
511
- script.dataset.tag = tag;
512
- }
513
- if (excludeSearch) {
514
- script.dataset.excludeSearch = "true";
515
- }
516
- if (excludeHash) {
517
- script.dataset.excludeHash = "true";
518
- }
519
- script.onload = () => {
520
- isLoaded.set(true);
521
- isReady.set(true);
522
- };
523
- document.head.appendChild(script);
45
+ if (typeof window === "undefined") return;
46
+ if (initialized) return;
47
+ const env = import.meta.env || {};
48
+ const websiteId = options.websiteId || env.VITE_ENTROLYTICS_WEBSITE_ID || env.PUBLIC_ENTROLYTICS_WEBSITE_ID;
49
+ const host = options.host || env.VITE_ENTROLYTICS_HOST || env.PUBLIC_ENTROLYTICS_HOST;
50
+ if (!websiteId) {
51
+ if (env.DEV) console.warn("[@entrolytics/svelte] Missing websiteId. Add VITE_ENTROLYTICS_WEBSITE_ID or PUBLIC_ENTROLYTICS_WEBSITE_ID to your .env file.");
52
+ throw new Error("[@entrolytics/svelte] websiteId is required");
53
+ }
54
+ const finalOptions = {
55
+ ...options,
56
+ websiteId,
57
+ host: host || DEFAULT_HOST
58
+ };
59
+ initialized = true;
60
+ currentOptions = finalOptions;
61
+ currentTag = finalOptions.tag;
62
+ const { websiteId: finalWebsiteId, host: finalHost = DEFAULT_HOST, autoTrack = true, respectDnt = false, domains, tag, excludeSearch = false, excludeHash = false } = finalOptions;
63
+ if (document.getElementById(SCRIPT_ID)) {
64
+ isLoaded.set(true);
65
+ isReady.set(true);
66
+ return;
67
+ }
68
+ const script = document.createElement("script");
69
+ script.id = SCRIPT_ID;
70
+ script.src = `${finalHost.replace(/\/$/, "")}/script.js`;
71
+ script.defer = true;
72
+ script.dataset.websiteId = finalWebsiteId;
73
+ if (!autoTrack) script.dataset.autoTrack = "false";
74
+ if (respectDnt) script.dataset.doNotTrack = "true";
75
+ if (domains && domains.length > 0) script.dataset.domains = domains.join(",");
76
+ if (tag) script.dataset.tag = tag;
77
+ if (excludeSearch) script.dataset.excludeSearch = "true";
78
+ if (excludeHash) script.dataset.excludeHash = "true";
79
+ script.onload = () => {
80
+ isLoaded.set(true);
81
+ isReady.set(true);
82
+ };
83
+ document.head.appendChild(script);
524
84
  }
85
+ /**
86
+ * Track a custom event
87
+ *
88
+ * @example
89
+ * ```svelte
90
+ * <script>
91
+ * import { trackEvent } from '@entrolytics/svelte';
92
+ *
93
+ * function handleClick() {
94
+ * trackEvent('button_click', { variant: 'primary' });
95
+ * }
96
+ * <\/script>
97
+ *
98
+ * <button on:click={handleClick}>Click me</button>
99
+ * ```
100
+ */
525
101
  function trackEvent(eventName, eventData) {
526
- waitForTracker(() => {
527
- let payload = { name: eventName, data: eventData };
528
- if (currentOptions?.beforeSend) {
529
- payload = currentOptions.beforeSend("event", payload);
530
- if (payload === null) return;
531
- }
532
- if (currentTag) {
533
- payload.tag = currentTag;
534
- }
535
- window.entrolytics?.track(eventName, eventData);
536
- });
102
+ waitForTracker(() => {
103
+ let payload = {
104
+ name: eventName,
105
+ data: eventData
106
+ };
107
+ if (currentOptions?.beforeSend) {
108
+ payload = currentOptions.beforeSend("event", payload);
109
+ if (payload === null) return;
110
+ }
111
+ if (currentTag) payload.tag = currentTag;
112
+ window.entrolytics?.track(eventName, eventData);
113
+ });
537
114
  }
115
+ /**
116
+ * Track revenue event
117
+ *
118
+ * @example
119
+ * ```svelte
120
+ * <script>
121
+ * import { trackRevenue } from '@entrolytics/svelte';
122
+ *
123
+ * async function handlePurchase(product) {
124
+ * await processPayment();
125
+ * trackRevenue('purchase', product.price, 'USD', {
126
+ * productId: product.id,
127
+ * productName: product.name
128
+ * });
129
+ * }
130
+ * <\/script>
131
+ * ```
132
+ */
538
133
  function trackRevenue(eventName, revenue, currency = "USD", data) {
539
- waitForTracker(() => {
540
- const eventData = {
541
- ...data,
542
- revenue,
543
- currency
544
- };
545
- if (currentTag) {
546
- eventData.tag = currentTag;
547
- }
548
- window.entrolytics?.track(eventName, eventData);
549
- });
134
+ waitForTracker(() => {
135
+ const eventData = {
136
+ ...data,
137
+ revenue,
138
+ currency
139
+ };
140
+ if (currentTag) eventData.tag = currentTag;
141
+ window.entrolytics?.track(eventName, eventData);
142
+ });
550
143
  }
144
+ /**
145
+ * Track outbound link click
146
+ *
147
+ * @example
148
+ * ```svelte
149
+ * <script>
150
+ * import { trackOutboundLink } from '@entrolytics/svelte';
151
+ *
152
+ * function handleExternalClick(url: string) {
153
+ * trackOutboundLink(url, { placement: 'sidebar' });
154
+ * }
155
+ * <\/script>
156
+ * ```
157
+ */
551
158
  function trackOutboundLink(url, data) {
552
- waitForTracker(() => {
553
- window.entrolytics?.track("outbound-link-click", {
554
- ...data,
555
- url
556
- });
557
- });
159
+ waitForTracker(() => {
160
+ window.entrolytics?.track("outbound-link-click", {
161
+ ...data,
162
+ url
163
+ });
164
+ });
558
165
  }
166
+ /**
167
+ * Identify with custom data
168
+ *
169
+ * @example
170
+ * ```svelte
171
+ * <script>
172
+ * import { identify } from '@entrolytics/svelte';
173
+ *
174
+ * identify({ company: 'Acme Corp', plan: 'enterprise' });
175
+ * <\/script>
176
+ * ```
177
+ */
559
178
  function identify(data) {
560
- waitForTracker(() => {
561
- window.entrolytics?.identify(data);
562
- });
179
+ waitForTracker(() => {
180
+ window.entrolytics?.identify(data);
181
+ });
563
182
  }
183
+ /**
184
+ * Identify a user by ID
185
+ *
186
+ * @example
187
+ * ```svelte
188
+ * <script>
189
+ * import { identifyUser } from '@entrolytics/svelte';
190
+ *
191
+ * // When user logs in
192
+ * identifyUser(user.id, { email: user.email, plan: user.plan });
193
+ * <\/script>
194
+ * ```
195
+ */
564
196
  function identifyUser(userId, traits) {
565
- waitForTracker(() => {
566
- window.entrolytics?.identify({ id: userId, ...traits });
567
- });
197
+ waitForTracker(() => {
198
+ window.entrolytics?.identify({
199
+ id: userId,
200
+ ...traits
201
+ });
202
+ });
568
203
  }
204
+ /**
205
+ * Set tag for A/B testing
206
+ */
569
207
  function setTag(tag) {
570
- currentTag = tag;
208
+ currentTag = tag;
571
209
  }
210
+ /**
211
+ * Track page view manually
212
+ * Useful for SPA navigation
213
+ */
572
214
  function trackPageView(url, referrer) {
573
- waitForTracker(() => {
574
- const payload = {};
575
- if (url) payload.url = url;
576
- if (referrer) payload.referrer = referrer;
577
- if (currentTag) payload.tag = currentTag;
578
- window.entrolytics?.track(payload);
579
- });
215
+ waitForTracker(() => {
216
+ const payload = {};
217
+ if (url) payload.url = url;
218
+ if (referrer) payload.referrer = referrer;
219
+ if (currentTag) payload.tag = currentTag;
220
+ window.entrolytics?.track(payload);
221
+ });
580
222
  }
223
+ /**
224
+ * Svelte action for tracking clicks
225
+ *
226
+ * @example
227
+ * ```svelte
228
+ * <script>
229
+ * import { trackClick } from '@entrolytics/svelte';
230
+ * <\/script>
231
+ *
232
+ * <button use:trackClick={{ event: 'cta_click', data: { variant: 'hero' } }}>
233
+ * Click me
234
+ * </button>
235
+ * ```
236
+ */
581
237
  function trackClick(node, params) {
582
- const handleClick = () => {
583
- trackEvent(params.event, params.data);
584
- };
585
- node.addEventListener("click", handleClick);
586
- return {
587
- update(newParams) {
588
- params = newParams;
589
- },
590
- destroy() {
591
- node.removeEventListener("click", handleClick);
592
- }
593
- };
238
+ const handleClick = () => {
239
+ trackEvent(params.event, params.data);
240
+ };
241
+ node.addEventListener("click", handleClick);
242
+ return {
243
+ update(newParams) {
244
+ params = newParams;
245
+ },
246
+ destroy() {
247
+ node.removeEventListener("click", handleClick);
248
+ }
249
+ };
594
250
  }
251
+ /**
252
+ * Svelte action for tracking outbound links
253
+ *
254
+ * @example
255
+ * ```svelte
256
+ * <a href="https://example.com" use:outboundLink={{ data: { placement: 'footer' } }}>
257
+ * Visit Example
258
+ * </a>
259
+ * ```
260
+ */
595
261
  function outboundLink(node, params) {
596
- const handleClick = () => {
597
- const url = node.href;
598
- if (url) {
599
- trackOutboundLink(url, params?.data);
600
- }
601
- };
602
- node.addEventListener("click", handleClick);
603
- return {
604
- update(newParams) {
605
- params = newParams;
606
- },
607
- destroy() {
608
- node.removeEventListener("click", handleClick);
609
- }
610
- };
262
+ const handleClick = () => {
263
+ const url = node.href;
264
+ if (url) trackOutboundLink(url, params?.data);
265
+ };
266
+ node.addEventListener("click", handleClick);
267
+ return {
268
+ update(newParams) {
269
+ params = newParams;
270
+ },
271
+ destroy() {
272
+ node.removeEventListener("click", handleClick);
273
+ }
274
+ };
611
275
  }
276
+ /**
277
+ * Hook for tracking page views in SvelteKit
278
+ *
279
+ * Use in +layout.svelte to auto-track navigation
280
+ *
281
+ * @example
282
+ * ```svelte
283
+ * <script>
284
+ * import { page } from '$app/stores';
285
+ * import { usePageView } from '@entrolytics/svelte';
286
+ *
287
+ * usePageView(page);
288
+ * <\/script>
289
+ * ```
290
+ */
612
291
  function usePageView(pageStore) {
613
- let lastPath = "";
614
- onMount(() => {
615
- const unsubscribe = pageStore.subscribe(($page) => {
616
- const currentPath = $page.url.pathname;
617
- if (currentPath !== lastPath) {
618
- lastPath = currentPath;
619
- if (lastPath !== "") {
620
- trackPageView(currentPath);
621
- }
622
- }
623
- });
624
- return unsubscribe;
625
- });
292
+ let lastPath = "";
293
+ onMount(() => {
294
+ return pageStore.subscribe(($page) => {
295
+ const currentPath = $page.url.pathname;
296
+ if (currentPath !== lastPath) {
297
+ lastPath = currentPath;
298
+ if (lastPath !== "") trackPageView(currentPath);
299
+ }
300
+ });
301
+ });
302
+ }
303
+ function isRecord(value) {
304
+ return typeof value === "object" && value !== null && !Array.isArray(value);
626
305
  }
306
+ /**
307
+ * Track a Web Vital metric
308
+ *
309
+ * @example
310
+ * ```svelte
311
+ * <script>
312
+ * import { onLCP, onINP, onCLS } from 'web-vitals';
313
+ * import { trackVital } from '@entrolytics/svelte';
314
+ *
315
+ * onMount(() => {
316
+ * onLCP((metric) => trackVital({
317
+ * metric: 'LCP',
318
+ * value: metric.value,
319
+ * rating: metric.rating
320
+ * }));
321
+ * });
322
+ * <\/script>
323
+ * ```
324
+ */
627
325
  async function trackVital(data) {
628
- if (typeof window === "undefined" || !currentOptions) return;
629
- const payload = {
630
- website: currentOptions.websiteId,
631
- metric: data.metric,
632
- value: data.value,
633
- rating: data.rating,
634
- delta: data.delta,
635
- id: data.id,
636
- navigationType: data.navigationType,
637
- attribution: data.attribution,
638
- url: window.location.href,
639
- path: window.location.pathname
640
- };
641
- const host = currentOptions.host || DEFAULT_HOST;
642
- try {
643
- await fetch(`${host}/api/collect/vitals`, {
644
- method: "POST",
645
- headers: { "Content-Type": "application/json" },
646
- body: JSON.stringify(payload),
647
- keepalive: true
648
- });
649
- } catch (err) {
650
- console.error("[Entrolytics] Failed to track vital:", err);
651
- }
326
+ if (typeof window === "undefined" || !currentOptions) return;
327
+ const payload = {
328
+ websiteId: currentOptions.websiteId,
329
+ metricName: data.metric,
330
+ metricValue: data.value,
331
+ rating: data.rating,
332
+ delta: data.delta,
333
+ id: data.id,
334
+ navigationType: data.navigationType,
335
+ attribution: data.attribution,
336
+ url: window.location.href,
337
+ path: window.location.pathname
338
+ };
339
+ const host = currentOptions.host || DEFAULT_HOST;
340
+ try {
341
+ await fetch(`${host}${API_ROUTES.collectVitals}`, {
342
+ method: "POST",
343
+ headers: { "Content-Type": "application/json" },
344
+ body: JSON.stringify(payload),
345
+ keepalive: true
346
+ });
347
+ } catch (err) {
348
+ console.error("[Entrolytics] Failed to track vital:", err);
349
+ }
652
350
  }
351
+ /**
352
+ * Initialize automatic Web Vitals tracking
353
+ * Call this in your root +layout.svelte
354
+ *
355
+ * @example
356
+ * ```svelte
357
+ * <script>
358
+ * import { initWebVitals } from '@entrolytics/svelte';
359
+ * import { onMount } from 'svelte';
360
+ *
361
+ * onMount(() => {
362
+ * initWebVitals();
363
+ * });
364
+ * <\/script>
365
+ * ```
366
+ */
653
367
  async function initWebVitals() {
654
- if (typeof window === "undefined") return;
655
- try {
656
- const { onCLS, onINP, onLCP, onFCP, onTTFB } = await Promise.resolve().then(() => (init_web_vitals_attribution(), web_vitals_attribution_exports));
657
- onLCP(
658
- (m2) => trackVital({
659
- metric: "LCP",
660
- value: m2.value,
661
- rating: m2.rating,
662
- delta: m2.delta,
663
- id: m2.id,
664
- navigationType: m2.navigationType,
665
- attribution: m2.attribution
666
- })
667
- );
668
- onINP(
669
- (m2) => trackVital({
670
- metric: "INP",
671
- value: m2.value,
672
- rating: m2.rating,
673
- delta: m2.delta,
674
- id: m2.id,
675
- navigationType: m2.navigationType,
676
- attribution: m2.attribution
677
- })
678
- );
679
- onCLS(
680
- (m2) => trackVital({
681
- metric: "CLS",
682
- value: m2.value,
683
- rating: m2.rating,
684
- delta: m2.delta,
685
- id: m2.id,
686
- navigationType: m2.navigationType,
687
- attribution: m2.attribution
688
- })
689
- );
690
- onFCP(
691
- (m2) => trackVital({
692
- metric: "FCP",
693
- value: m2.value,
694
- rating: m2.rating,
695
- delta: m2.delta,
696
- id: m2.id,
697
- navigationType: m2.navigationType,
698
- attribution: m2.attribution
699
- })
700
- );
701
- onTTFB(
702
- (m2) => trackVital({
703
- metric: "TTFB",
704
- value: m2.value,
705
- rating: m2.rating,
706
- delta: m2.delta,
707
- id: m2.id,
708
- navigationType: m2.navigationType,
709
- attribution: m2.attribution
710
- })
711
- );
712
- } catch {
713
- console.debug("[Entrolytics] web-vitals not installed. Use trackVital() for manual tracking.");
714
- }
368
+ if (typeof window === "undefined") return;
369
+ try {
370
+ const { onCLS, onINP, onLCP, onFCP, onTTFB } = await import("web-vitals/attribution");
371
+ onLCP((m) => trackVital({
372
+ metric: "LCP",
373
+ value: m.value,
374
+ rating: m.rating,
375
+ delta: m.delta,
376
+ id: m.id,
377
+ navigationType: m.navigationType,
378
+ attribution: isRecord(m.attribution) ? m.attribution : void 0
379
+ }));
380
+ onINP((m) => trackVital({
381
+ metric: "INP",
382
+ value: m.value,
383
+ rating: m.rating,
384
+ delta: m.delta,
385
+ id: m.id,
386
+ navigationType: m.navigationType,
387
+ attribution: isRecord(m.attribution) ? m.attribution : void 0
388
+ }));
389
+ onCLS((m) => trackVital({
390
+ metric: "CLS",
391
+ value: m.value,
392
+ rating: m.rating,
393
+ delta: m.delta,
394
+ id: m.id,
395
+ navigationType: m.navigationType,
396
+ attribution: isRecord(m.attribution) ? m.attribution : void 0
397
+ }));
398
+ onFCP((m) => trackVital({
399
+ metric: "FCP",
400
+ value: m.value,
401
+ rating: m.rating,
402
+ delta: m.delta,
403
+ id: m.id,
404
+ navigationType: m.navigationType,
405
+ attribution: isRecord(m.attribution) ? m.attribution : void 0
406
+ }));
407
+ onTTFB((m) => trackVital({
408
+ metric: "TTFB",
409
+ value: m.value,
410
+ rating: m.rating,
411
+ delta: m.delta,
412
+ id: m.id,
413
+ navigationType: m.navigationType,
414
+ attribution: isRecord(m.attribution) ? m.attribution : void 0
415
+ }));
416
+ } catch {
417
+ console.debug("[Entrolytics] web-vitals not installed. Use trackVital() for manual tracking.");
418
+ }
715
419
  }
420
+ /**
421
+ * Track a form event
422
+ *
423
+ * @example
424
+ * ```svelte
425
+ * <script>
426
+ * import { trackFormEvent } from '@entrolytics/svelte';
427
+ *
428
+ * async function handleSubmit() {
429
+ * const success = await submitForm();
430
+ * trackFormEvent({
431
+ * eventType: 'submit',
432
+ * formId: 'contact-form',
433
+ * success
434
+ * });
435
+ * }
436
+ * <\/script>
437
+ * ```
438
+ */
716
439
  async function trackFormEvent(data) {
717
- if (typeof window === "undefined" || !currentOptions) return;
718
- const host = currentOptions.host || DEFAULT_HOST;
719
- const payload = {
720
- website: currentOptions.websiteId,
721
- eventType: data.eventType,
722
- formId: data.formId,
723
- formName: data.formName,
724
- urlPath: data.urlPath || window.location.pathname,
725
- fieldName: data.fieldName,
726
- fieldType: data.fieldType,
727
- fieldIndex: data.fieldIndex,
728
- timeOnField: data.timeOnField,
729
- timeSinceStart: data.timeSinceStart,
730
- errorMessage: data.errorMessage,
731
- success: data.success
732
- };
733
- try {
734
- await fetch(`${host}/api/collect/forms`, {
735
- method: "POST",
736
- headers: { "Content-Type": "application/json" },
737
- body: JSON.stringify(payload),
738
- keepalive: true
739
- });
740
- } catch (err) {
741
- console.error("[Entrolytics] Failed to track form event:", err);
742
- }
440
+ if (typeof window === "undefined" || !currentOptions) return;
441
+ const host = currentOptions.host || DEFAULT_HOST;
442
+ const payload = {
443
+ websiteId: currentOptions.websiteId,
444
+ eventType: data.eventType,
445
+ formId: data.formId,
446
+ formName: data.formName,
447
+ urlPath: data.urlPath || window.location.pathname,
448
+ fieldName: data.fieldName,
449
+ fieldType: data.fieldType,
450
+ fieldIndex: data.fieldIndex,
451
+ timeOnField: data.timeOnField,
452
+ timeSinceStart: data.timeSinceStart,
453
+ errorMessage: data.errorMessage,
454
+ success: data.success
455
+ };
456
+ try {
457
+ await fetch(`${host}${API_ROUTES.collectForms}`, {
458
+ method: "POST",
459
+ headers: { "Content-Type": "application/json" },
460
+ body: JSON.stringify(payload),
461
+ keepalive: true
462
+ });
463
+ } catch (err) {
464
+ console.error("[Entrolytics] Failed to track form event:", err);
465
+ }
743
466
  }
467
+ /**
468
+ * Create a form tracker for a specific form
469
+ *
470
+ * @example
471
+ * ```svelte
472
+ * <script>
473
+ * import { createFormTracker } from '@entrolytics/svelte';
474
+ *
475
+ * const tracker = createFormTracker('signup-form', 'Signup Form');
476
+ *
477
+ * function handleSubmit() {
478
+ * const success = await submit();
479
+ * tracker.trackSubmit(success);
480
+ * }
481
+ * <\/script>
482
+ *
483
+ * <form on:submit|preventDefault={handleSubmit}>
484
+ * <input
485
+ * name="email"
486
+ * on:focus={() => tracker.trackFieldFocus('email', 'email', 0)}
487
+ * on:blur={() => tracker.trackFieldBlur('email', 'email', 0)}
488
+ * />
489
+ * </form>
490
+ * ```
491
+ */
744
492
  function createFormTracker(formId, formName) {
745
- let startTime = null;
746
- const fieldStartTimes = /* @__PURE__ */ new Map();
747
- return {
748
- trackStart: () => {
749
- startTime = Date.now();
750
- trackFormEvent({ eventType: "start", formId, formName });
751
- },
752
- trackFieldFocus: (fieldName, fieldType, fieldIndex) => {
753
- if (!startTime) {
754
- startTime = Date.now();
755
- trackFormEvent({ eventType: "start", formId, formName });
756
- }
757
- fieldStartTimes.set(fieldName, Date.now());
758
- trackFormEvent({
759
- eventType: "field_focus",
760
- formId,
761
- formName,
762
- fieldName,
763
- fieldType,
764
- fieldIndex,
765
- timeSinceStart: Date.now() - startTime
766
- });
767
- },
768
- trackFieldBlur: (fieldName, fieldType, fieldIndex) => {
769
- const fieldStart = fieldStartTimes.get(fieldName);
770
- trackFormEvent({
771
- eventType: "field_blur",
772
- formId,
773
- formName,
774
- fieldName,
775
- fieldType,
776
- fieldIndex,
777
- timeOnField: fieldStart ? Date.now() - fieldStart : void 0,
778
- timeSinceStart: startTime ? Date.now() - startTime : void 0
779
- });
780
- },
781
- trackFieldError: (fieldName, errorMessage, fieldType, fieldIndex) => {
782
- trackFormEvent({
783
- eventType: "field_error",
784
- formId,
785
- formName,
786
- fieldName,
787
- fieldType,
788
- fieldIndex,
789
- errorMessage,
790
- timeSinceStart: startTime ? Date.now() - startTime : void 0
791
- });
792
- },
793
- trackSubmit: (success) => {
794
- trackFormEvent({
795
- eventType: "submit",
796
- formId,
797
- formName,
798
- success,
799
- timeSinceStart: startTime ? Date.now() - startTime : void 0
800
- });
801
- startTime = null;
802
- fieldStartTimes.clear();
803
- },
804
- trackAbandon: () => {
805
- trackFormEvent({
806
- eventType: "abandon",
807
- formId,
808
- formName,
809
- timeSinceStart: startTime ? Date.now() - startTime : void 0
810
- });
811
- }
812
- };
493
+ let startTime = null;
494
+ const fieldStartTimes = /* @__PURE__ */ new Map();
495
+ return {
496
+ trackStart: () => {
497
+ startTime = Date.now();
498
+ trackFormEvent({
499
+ eventType: "start",
500
+ formId,
501
+ formName
502
+ });
503
+ },
504
+ trackFieldFocus: (fieldName, fieldType, fieldIndex) => {
505
+ if (!startTime) {
506
+ startTime = Date.now();
507
+ trackFormEvent({
508
+ eventType: "start",
509
+ formId,
510
+ formName
511
+ });
512
+ }
513
+ fieldStartTimes.set(fieldName, Date.now());
514
+ trackFormEvent({
515
+ eventType: "field_focus",
516
+ formId,
517
+ formName,
518
+ fieldName,
519
+ fieldType,
520
+ fieldIndex,
521
+ timeSinceStart: Date.now() - startTime
522
+ });
523
+ },
524
+ trackFieldBlur: (fieldName, fieldType, fieldIndex) => {
525
+ const fieldStart = fieldStartTimes.get(fieldName);
526
+ trackFormEvent({
527
+ eventType: "field_blur",
528
+ formId,
529
+ formName,
530
+ fieldName,
531
+ fieldType,
532
+ fieldIndex,
533
+ timeOnField: fieldStart ? Date.now() - fieldStart : void 0,
534
+ timeSinceStart: startTime ? Date.now() - startTime : void 0
535
+ });
536
+ },
537
+ trackFieldError: (fieldName, errorMessage, fieldType, fieldIndex) => {
538
+ trackFormEvent({
539
+ eventType: "field_error",
540
+ formId,
541
+ formName,
542
+ fieldName,
543
+ fieldType,
544
+ fieldIndex,
545
+ errorMessage,
546
+ timeSinceStart: startTime ? Date.now() - startTime : void 0
547
+ });
548
+ },
549
+ trackSubmit: (success) => {
550
+ trackFormEvent({
551
+ eventType: "submit",
552
+ formId,
553
+ formName,
554
+ success,
555
+ timeSinceStart: startTime ? Date.now() - startTime : void 0
556
+ });
557
+ startTime = null;
558
+ fieldStartTimes.clear();
559
+ },
560
+ trackAbandon: () => {
561
+ trackFormEvent({
562
+ eventType: "abandon",
563
+ formId,
564
+ formName,
565
+ timeSinceStart: startTime ? Date.now() - startTime : void 0
566
+ });
567
+ }
568
+ };
813
569
  }
570
+ /**
571
+ * Svelte action for automatic form tracking
572
+ *
573
+ * @example
574
+ * ```svelte
575
+ * <script>
576
+ * import { trackForm } from '@entrolytics/svelte';
577
+ * <\/script>
578
+ *
579
+ * <form use:trackForm={{ formId: 'contact', formName: 'Contact Form' }}>
580
+ * <input name="email" type="email" />
581
+ * <button type="submit">Send</button>
582
+ * </form>
583
+ * ```
584
+ */
814
585
  function trackForm(node, params) {
815
- const tracker = createFormTracker(params.formId, params.formName);
816
- let hasInteracted = false;
817
- const handleFocus = (e2) => {
818
- const target = e2.target;
819
- if (!target.name && !target.id) return;
820
- const fieldName = target.name || target.id;
821
- const fieldType = target.type || target.tagName.toLowerCase();
822
- const fields = Array.from(node.elements);
823
- const fieldIndex = fields.indexOf(target);
824
- if (!hasInteracted) {
825
- hasInteracted = true;
826
- }
827
- tracker.trackFieldFocus(fieldName, fieldType, fieldIndex >= 0 ? fieldIndex : void 0);
828
- };
829
- const handleBlur = (e2) => {
830
- const target = e2.target;
831
- if (!target.name && !target.id) return;
832
- const fieldName = target.name || target.id;
833
- const fieldType = target.type || target.tagName.toLowerCase();
834
- const fields = Array.from(node.elements);
835
- const fieldIndex = fields.indexOf(target);
836
- tracker.trackFieldBlur(fieldName, fieldType, fieldIndex >= 0 ? fieldIndex : void 0);
837
- };
838
- const handleSubmit = () => {
839
- tracker.trackSubmit(true);
840
- hasInteracted = false;
841
- };
842
- const handleBeforeUnload = () => {
843
- if (hasInteracted) {
844
- tracker.trackAbandon();
845
- }
846
- };
847
- node.addEventListener("focusin", handleFocus);
848
- node.addEventListener("focusout", handleBlur);
849
- node.addEventListener("submit", handleSubmit);
850
- window.addEventListener("beforeunload", handleBeforeUnload);
851
- return {
852
- update(newParams) {
853
- params = newParams;
854
- },
855
- destroy() {
856
- node.removeEventListener("focusin", handleFocus);
857
- node.removeEventListener("focusout", handleBlur);
858
- node.removeEventListener("submit", handleSubmit);
859
- window.removeEventListener("beforeunload", handleBeforeUnload);
860
- }
861
- };
586
+ const tracker = createFormTracker(params.formId, params.formName);
587
+ let hasInteracted = false;
588
+ const handleFocus = (e) => {
589
+ const target = e.target;
590
+ if (!target.name && !target.id) return;
591
+ const fieldName = target.name || target.id;
592
+ const fieldType = target.type || target.tagName.toLowerCase();
593
+ const fieldIndex = Array.from(node.elements).indexOf(target);
594
+ if (!hasInteracted) hasInteracted = true;
595
+ tracker.trackFieldFocus(fieldName, fieldType, fieldIndex >= 0 ? fieldIndex : void 0);
596
+ };
597
+ const handleBlur = (e) => {
598
+ const target = e.target;
599
+ if (!target.name && !target.id) return;
600
+ const fieldName = target.name || target.id;
601
+ const fieldType = target.type || target.tagName.toLowerCase();
602
+ const fieldIndex = Array.from(node.elements).indexOf(target);
603
+ tracker.trackFieldBlur(fieldName, fieldType, fieldIndex >= 0 ? fieldIndex : void 0);
604
+ };
605
+ const handleSubmit = () => {
606
+ tracker.trackSubmit(true);
607
+ hasInteracted = false;
608
+ };
609
+ const handleBeforeUnload = () => {
610
+ if (hasInteracted) tracker.trackAbandon();
611
+ };
612
+ node.addEventListener("focusin", handleFocus);
613
+ node.addEventListener("focusout", handleBlur);
614
+ node.addEventListener("submit", handleSubmit);
615
+ window.addEventListener("beforeunload", handleBeforeUnload);
616
+ return {
617
+ update(newParams) {
618
+ params = newParams;
619
+ },
620
+ destroy() {
621
+ node.removeEventListener("focusin", handleFocus);
622
+ node.removeEventListener("focusout", handleBlur);
623
+ node.removeEventListener("submit", handleSubmit);
624
+ window.removeEventListener("beforeunload", handleBeforeUnload);
625
+ }
626
+ };
862
627
  }
863
628
 
864
629
  export { createFormTracker, identify, identifyUser, initEntrolytics, initWebVitals, isLoaded, isReady, outboundLink, setTag, trackClick, trackEvent, trackForm, trackFormEvent, trackOutboundLink, trackPageView, trackRevenue, trackVital, usePageView };
865
- //# sourceMappingURL=index.js.map
866
630
  //# sourceMappingURL=index.js.map