@journium/js 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1425 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * uuidv7: A JavaScript implementation of UUID version 7
5
+ *
6
+ * Copyright 2021-2024 LiosK
7
+ *
8
+ * @license Apache-2.0
9
+ * @packageDocumentation
10
+ */
11
+ const DIGITS = "0123456789abcdef";
12
+ /** Represents a UUID as a 16-byte byte array. */
13
+ class UUID {
14
+ /** @param bytes - The 16-byte byte array representation. */
15
+ constructor(bytes) {
16
+ this.bytes = bytes;
17
+ }
18
+ /**
19
+ * Creates an object from the internal representation, a 16-byte byte array
20
+ * containing the binary UUID representation in the big-endian byte order.
21
+ *
22
+ * This method does NOT shallow-copy the argument, and thus the created object
23
+ * holds the reference to the underlying buffer.
24
+ *
25
+ * @throws TypeError if the length of the argument is not 16.
26
+ */
27
+ static ofInner(bytes) {
28
+ if (bytes.length !== 16) {
29
+ throw new TypeError("not 128-bit length");
30
+ }
31
+ else {
32
+ return new UUID(bytes);
33
+ }
34
+ }
35
+ /**
36
+ * Builds a byte array from UUIDv7 field values.
37
+ *
38
+ * @param unixTsMs - A 48-bit `unix_ts_ms` field value.
39
+ * @param randA - A 12-bit `rand_a` field value.
40
+ * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.
41
+ * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
42
+ * @throws RangeError if any field value is out of the specified range.
43
+ */
44
+ static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
45
+ if (!Number.isInteger(unixTsMs) ||
46
+ !Number.isInteger(randA) ||
47
+ !Number.isInteger(randBHi) ||
48
+ !Number.isInteger(randBLo) ||
49
+ unixTsMs < 0 ||
50
+ randA < 0 ||
51
+ randBHi < 0 ||
52
+ randBLo < 0 ||
53
+ unixTsMs > 281474976710655 ||
54
+ randA > 0xfff ||
55
+ randBHi > 1073741823 ||
56
+ randBLo > 4294967295) {
57
+ throw new RangeError("invalid field value");
58
+ }
59
+ const bytes = new Uint8Array(16);
60
+ bytes[0] = unixTsMs / 2 ** 40;
61
+ bytes[1] = unixTsMs / 2 ** 32;
62
+ bytes[2] = unixTsMs / 2 ** 24;
63
+ bytes[3] = unixTsMs / 2 ** 16;
64
+ bytes[4] = unixTsMs / 2 ** 8;
65
+ bytes[5] = unixTsMs;
66
+ bytes[6] = 0x70 | (randA >>> 8);
67
+ bytes[7] = randA;
68
+ bytes[8] = 0x80 | (randBHi >>> 24);
69
+ bytes[9] = randBHi >>> 16;
70
+ bytes[10] = randBHi >>> 8;
71
+ bytes[11] = randBHi;
72
+ bytes[12] = randBLo >>> 24;
73
+ bytes[13] = randBLo >>> 16;
74
+ bytes[14] = randBLo >>> 8;
75
+ bytes[15] = randBLo;
76
+ return new UUID(bytes);
77
+ }
78
+ /**
79
+ * Builds a byte array from a string representation.
80
+ *
81
+ * This method accepts the following formats:
82
+ *
83
+ * - 32-digit hexadecimal format without hyphens: `0189dcd553117d408db09496a2eef37b`
84
+ * - 8-4-4-4-12 hyphenated format: `0189dcd5-5311-7d40-8db0-9496a2eef37b`
85
+ * - Hyphenated format with surrounding braces: `{0189dcd5-5311-7d40-8db0-9496a2eef37b}`
86
+ * - RFC 9562 URN format: `urn:uuid:0189dcd5-5311-7d40-8db0-9496a2eef37b`
87
+ *
88
+ * Leading and trailing whitespaces represents an error.
89
+ *
90
+ * @throws SyntaxError if the argument could not parse as a valid UUID string.
91
+ */
92
+ static parse(uuid) {
93
+ var _a, _b, _c, _d;
94
+ let hex = undefined;
95
+ switch (uuid.length) {
96
+ case 32:
97
+ hex = (_a = /^[0-9a-f]{32}$/i.exec(uuid)) === null || _a === void 0 ? void 0 : _a[0];
98
+ break;
99
+ case 36:
100
+ hex =
101
+ (_b = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
102
+ .exec(uuid)) === null || _b === void 0 ? void 0 : _b.slice(1, 6).join("");
103
+ break;
104
+ case 38:
105
+ hex =
106
+ (_c = /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i
107
+ .exec(uuid)) === null || _c === void 0 ? void 0 : _c.slice(1, 6).join("");
108
+ break;
109
+ case 45:
110
+ hex =
111
+ (_d = /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
112
+ .exec(uuid)) === null || _d === void 0 ? void 0 : _d.slice(1, 6).join("");
113
+ break;
114
+ }
115
+ if (hex) {
116
+ const inner = new Uint8Array(16);
117
+ for (let i = 0; i < 16; i += 4) {
118
+ const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
119
+ inner[i + 0] = n >>> 24;
120
+ inner[i + 1] = n >>> 16;
121
+ inner[i + 2] = n >>> 8;
122
+ inner[i + 3] = n;
123
+ }
124
+ return new UUID(inner);
125
+ }
126
+ else {
127
+ throw new SyntaxError("could not parse UUID string");
128
+ }
129
+ }
130
+ /**
131
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
132
+ * (`0189dcd5-5311-7d40-8db0-9496a2eef37b`).
133
+ */
134
+ toString() {
135
+ let text = "";
136
+ for (let i = 0; i < this.bytes.length; i++) {
137
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
138
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
139
+ if (i === 3 || i === 5 || i === 7 || i === 9) {
140
+ text += "-";
141
+ }
142
+ }
143
+ return text;
144
+ }
145
+ /**
146
+ * @returns The 32-digit hexadecimal representation without hyphens
147
+ * (`0189dcd553117d408db09496a2eef37b`).
148
+ */
149
+ toHex() {
150
+ let text = "";
151
+ for (let i = 0; i < this.bytes.length; i++) {
152
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
153
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
154
+ }
155
+ return text;
156
+ }
157
+ /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
158
+ toJSON() {
159
+ return this.toString();
160
+ }
161
+ /**
162
+ * Reports the variant field value of the UUID or, if appropriate, "NIL" or
163
+ * "MAX".
164
+ *
165
+ * For convenience, this method reports "NIL" or "MAX" if `this` represents
166
+ * the Nil or Max UUID, although the Nil and Max UUIDs are technically
167
+ * subsumed under the variants `0b0` and `0b111`, respectively.
168
+ */
169
+ getVariant() {
170
+ const n = this.bytes[8] >>> 4;
171
+ if (n < 0) {
172
+ throw new Error("unreachable");
173
+ }
174
+ else if (n <= 0b0111) {
175
+ return this.bytes.every((e) => e === 0) ? "NIL" : "VAR_0";
176
+ }
177
+ else if (n <= 0b1011) {
178
+ return "VAR_10";
179
+ }
180
+ else if (n <= 0b1101) {
181
+ return "VAR_110";
182
+ }
183
+ else if (n <= 0b1111) {
184
+ return this.bytes.every((e) => e === 0xff) ? "MAX" : "VAR_RESERVED";
185
+ }
186
+ else {
187
+ throw new Error("unreachable");
188
+ }
189
+ }
190
+ /**
191
+ * Returns the version field value of the UUID or `undefined` if the UUID does
192
+ * not have the variant field value of `0b10`.
193
+ */
194
+ getVersion() {
195
+ return this.getVariant() === "VAR_10" ? this.bytes[6] >>> 4 : undefined;
196
+ }
197
+ /** Creates an object from `this`. */
198
+ clone() {
199
+ return new UUID(this.bytes.slice(0));
200
+ }
201
+ /** Returns true if `this` is equivalent to `other`. */
202
+ equals(other) {
203
+ return this.compareTo(other) === 0;
204
+ }
205
+ /**
206
+ * Returns a negative integer, zero, or positive integer if `this` is less
207
+ * than, equal to, or greater than `other`, respectively.
208
+ */
209
+ compareTo(other) {
210
+ for (let i = 0; i < 16; i++) {
211
+ const diff = this.bytes[i] - other.bytes[i];
212
+ if (diff !== 0) {
213
+ return Math.sign(diff);
214
+ }
215
+ }
216
+ return 0;
217
+ }
218
+ }
219
+ /**
220
+ * Encapsulates the monotonic counter state.
221
+ *
222
+ * This class provides APIs to utilize a separate counter state from that of the
223
+ * global generator used by {@link uuidv7} and {@link uuidv7obj}. In addition to
224
+ * the default {@link generate} method, this class has {@link generateOrAbort}
225
+ * that is useful to absolutely guarantee the monotonically increasing order of
226
+ * generated UUIDs. See their respective documentation for details.
227
+ */
228
+ class V7Generator {
229
+ /**
230
+ * Creates a generator object with the default random number generator, or
231
+ * with the specified one if passed as an argument. The specified random
232
+ * number generator should be cryptographically strong and securely seeded.
233
+ */
234
+ constructor(randomNumberGenerator) {
235
+ this.timestamp = 0;
236
+ this.counter = 0;
237
+ this.random = randomNumberGenerator !== null && randomNumberGenerator !== void 0 ? randomNumberGenerator : getDefaultRandom();
238
+ }
239
+ /**
240
+ * Generates a new UUIDv7 object from the current timestamp, or resets the
241
+ * generator upon significant timestamp rollback.
242
+ *
243
+ * This method returns a monotonically increasing UUID by reusing the previous
244
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
245
+ * preceding UUID's. However, when such a clock rollback is considered
246
+ * significant (i.e., by more than ten seconds), this method resets the
247
+ * generator and returns a new UUID based on the given timestamp, breaking the
248
+ * increasing order of UUIDs.
249
+ *
250
+ * See {@link generateOrAbort} for the other mode of generation and
251
+ * {@link generateOrResetCore} for the low-level primitive.
252
+ */
253
+ generate() {
254
+ return this.generateOrResetCore(Date.now(), 10000);
255
+ }
256
+ /**
257
+ * Generates a new UUIDv7 object from the current timestamp, or returns
258
+ * `undefined` upon significant timestamp rollback.
259
+ *
260
+ * This method returns a monotonically increasing UUID by reusing the previous
261
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
262
+ * preceding UUID's. However, when such a clock rollback is considered
263
+ * significant (i.e., by more than ten seconds), this method aborts and
264
+ * returns `undefined` immediately.
265
+ *
266
+ * See {@link generate} for the other mode of generation and
267
+ * {@link generateOrAbortCore} for the low-level primitive.
268
+ */
269
+ generateOrAbort() {
270
+ return this.generateOrAbortCore(Date.now(), 10000);
271
+ }
272
+ /**
273
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or resets the
274
+ * generator upon significant timestamp rollback.
275
+ *
276
+ * This method is equivalent to {@link generate} except that it takes a custom
277
+ * timestamp and clock rollback allowance.
278
+ *
279
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
280
+ * considered significant. A suggested value is `10_000` (milliseconds).
281
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
282
+ */
283
+ generateOrResetCore(unixTsMs, rollbackAllowance) {
284
+ let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
285
+ if (value === undefined) {
286
+ // reset state and resume
287
+ this.timestamp = 0;
288
+ value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
289
+ }
290
+ return value;
291
+ }
292
+ /**
293
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or returns
294
+ * `undefined` upon significant timestamp rollback.
295
+ *
296
+ * This method is equivalent to {@link generateOrAbort} except that it takes a
297
+ * custom timestamp and clock rollback allowance.
298
+ *
299
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
300
+ * considered significant. A suggested value is `10_000` (milliseconds).
301
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
302
+ */
303
+ generateOrAbortCore(unixTsMs, rollbackAllowance) {
304
+ const MAX_COUNTER = 4398046511103;
305
+ if (!Number.isInteger(unixTsMs) ||
306
+ unixTsMs < 1 ||
307
+ unixTsMs > 281474976710655) {
308
+ throw new RangeError("`unixTsMs` must be a 48-bit positive integer");
309
+ }
310
+ else if (rollbackAllowance < 0 || rollbackAllowance > 281474976710655) {
311
+ throw new RangeError("`rollbackAllowance` out of reasonable range");
312
+ }
313
+ if (unixTsMs > this.timestamp) {
314
+ this.timestamp = unixTsMs;
315
+ this.resetCounter();
316
+ }
317
+ else if (unixTsMs + rollbackAllowance >= this.timestamp) {
318
+ // go on with previous timestamp if new one is not much smaller
319
+ this.counter++;
320
+ if (this.counter > MAX_COUNTER) {
321
+ // increment timestamp at counter overflow
322
+ this.timestamp++;
323
+ this.resetCounter();
324
+ }
325
+ }
326
+ else {
327
+ // abort if clock went backwards to unbearable extent
328
+ return undefined;
329
+ }
330
+ return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & (2 ** 30 - 1), this.random.nextUint32());
331
+ }
332
+ /** Initializes the counter at a 42-bit random integer. */
333
+ resetCounter() {
334
+ this.counter =
335
+ this.random.nextUint32() * 0x400 + (this.random.nextUint32() & 0x3ff);
336
+ }
337
+ /**
338
+ * Generates a new UUIDv4 object utilizing the random number generator inside.
339
+ *
340
+ * @internal
341
+ */
342
+ generateV4() {
343
+ const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
344
+ bytes[6] = 0x40 | (bytes[6] >>> 4);
345
+ bytes[8] = 0x80 | (bytes[8] >>> 2);
346
+ return UUID.ofInner(bytes);
347
+ }
348
+ }
349
+ /** Returns the default random number generator available in the environment. */
350
+ const getDefaultRandom = () => {
351
+ // detect Web Crypto API
352
+ if (typeof crypto !== "undefined" &&
353
+ typeof crypto.getRandomValues !== "undefined") {
354
+ return new BufferedCryptoRandom();
355
+ }
356
+ else {
357
+ // fall back on Math.random() unless the flag is set to true
358
+ if (typeof UUIDV7_DENY_WEAK_RNG !== "undefined" && UUIDV7_DENY_WEAK_RNG) {
359
+ throw new Error("no cryptographically strong RNG available");
360
+ }
361
+ return {
362
+ nextUint32: () => Math.trunc(Math.random() * 65536) * 65536 +
363
+ Math.trunc(Math.random() * 65536),
364
+ };
365
+ }
366
+ };
367
+ /**
368
+ * Wraps `crypto.getRandomValues()` to enable buffering; this uses a small
369
+ * buffer by default to avoid both unbearable throughput decline in some
370
+ * environments and the waste of time and space for unused values.
371
+ */
372
+ class BufferedCryptoRandom {
373
+ constructor() {
374
+ this.buffer = new Uint32Array(8);
375
+ this.cursor = 0xffff;
376
+ }
377
+ nextUint32() {
378
+ if (this.cursor >= this.buffer.length) {
379
+ crypto.getRandomValues(this.buffer);
380
+ this.cursor = 0;
381
+ }
382
+ return this.buffer[this.cursor++];
383
+ }
384
+ }
385
+ let defaultGenerator;
386
+ /**
387
+ * Generates a UUIDv7 string.
388
+ *
389
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
390
+ * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
391
+ */
392
+ const uuidv7 = () => uuidv7obj().toString();
393
+ /** Generates a UUIDv7 object. */
394
+ const uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
395
+
396
+ const generateId = () => {
397
+ return Math.random().toString(36).substring(2) + Date.now().toString(36);
398
+ };
399
+ const generateUuidv7 = () => {
400
+ return uuidv7();
401
+ };
402
+ const getCurrentTimestamp = () => {
403
+ return new Date().toISOString();
404
+ };
405
+ const getCurrentUrl = () => {
406
+ if (typeof window !== 'undefined') {
407
+ return window.location.href;
408
+ }
409
+ return '';
410
+ };
411
+ const getPageTitle = () => {
412
+ if (typeof document !== 'undefined') {
413
+ return document.title;
414
+ }
415
+ return '';
416
+ };
417
+ const getReferrer = () => {
418
+ if (typeof document !== 'undefined') {
419
+ return document.referrer;
420
+ }
421
+ return '';
422
+ };
423
+ const isBrowser = () => {
424
+ return typeof window !== 'undefined';
425
+ };
426
+ const isNode = () => {
427
+ var _a;
428
+ return typeof process !== 'undefined' && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
429
+ };
430
+ const fetchRemoteConfig = async (apiHost, token, fetchFn) => {
431
+ const endpoint = '/v1/configs';
432
+ const url = `${apiHost}${endpoint}?ingestion_key=${encodeURIComponent(token)}`;
433
+ try {
434
+ let fetch = fetchFn;
435
+ if (!fetch) {
436
+ if (isNode()) {
437
+ // For Node.js environments, expect fetch to be passed in
438
+ throw new Error('Fetch function must be provided in Node.js environment');
439
+ }
440
+ else {
441
+ // Use native fetch in browser
442
+ fetch = window.fetch;
443
+ }
444
+ }
445
+ const response = await fetch(url, {
446
+ method: 'GET',
447
+ headers: {
448
+ 'Content-Type': 'application/json',
449
+ },
450
+ });
451
+ if (!response.ok) {
452
+ throw new Error(`Config fetch failed: ${response.status} ${response.statusText}`);
453
+ }
454
+ const data = await response.json();
455
+ return data;
456
+ }
457
+ catch (error) {
458
+ console.warn('Failed to fetch remote config:', error);
459
+ return null;
460
+ }
461
+ };
462
+ const mergeConfigs = (localConfig, remoteConfig) => {
463
+ if (!remoteConfig) {
464
+ return localConfig;
465
+ }
466
+ // Deep merge remote config into local config
467
+ // Remote config takes precedence over local config
468
+ const merged = { ...localConfig };
469
+ // Handle primitive values
470
+ Object.keys(remoteConfig).forEach(key => {
471
+ if (remoteConfig[key] !== undefined && remoteConfig[key] !== null) {
472
+ if (typeof remoteConfig[key] === 'object' && !Array.isArray(remoteConfig[key])) {
473
+ // Deep merge objects
474
+ merged[key] = {
475
+ ...(merged[key] || {}),
476
+ ...remoteConfig[key]
477
+ };
478
+ }
479
+ else {
480
+ // Override primitive values and arrays
481
+ merged[key] = remoteConfig[key];
482
+ }
483
+ }
484
+ });
485
+ return merged;
486
+ };
487
+
488
+ const DEFAULT_SESSION_TIMEOUT = 30 * 60 * 1000; // 30 minutes in ms
489
+ class BrowserIdentityManager {
490
+ constructor(sessionTimeout, token) {
491
+ this.identity = null;
492
+ this.sessionTimeout = DEFAULT_SESSION_TIMEOUT;
493
+ if (sessionTimeout) {
494
+ this.sessionTimeout = sessionTimeout;
495
+ }
496
+ // Generate storage key with token pattern: jrnm_<token>_journium
497
+ this.storageKey = token ? `jrnm_${token}_journium` : '__journium_identity';
498
+ this.loadOrCreateIdentity();
499
+ }
500
+ loadOrCreateIdentity() {
501
+ if (!this.isBrowser())
502
+ return;
503
+ try {
504
+ const stored = localStorage.getItem(this.storageKey);
505
+ if (stored) {
506
+ const parsedIdentity = JSON.parse(stored);
507
+ // Check if session is expired
508
+ const now = Date.now();
509
+ const sessionAge = now - parsedIdentity.session_timestamp;
510
+ if (sessionAge > this.sessionTimeout) {
511
+ // Session expired, create new session but keep device and distinct IDs
512
+ this.identity = {
513
+ distinct_id: parsedIdentity.distinct_id,
514
+ $device_id: parsedIdentity.$device_id,
515
+ $session_id: generateUuidv7(),
516
+ session_timestamp: now,
517
+ $user_state: parsedIdentity.$user_state || 'anonymous',
518
+ };
519
+ }
520
+ else {
521
+ // Session still valid
522
+ this.identity = parsedIdentity;
523
+ // Ensure $user_state exists for backward compatibility
524
+ if (!this.identity.$user_state) {
525
+ this.identity.$user_state = 'anonymous';
526
+ }
527
+ }
528
+ }
529
+ else {
530
+ // First time, create all new IDs
531
+ const newId = generateUuidv7();
532
+ this.identity = {
533
+ distinct_id: newId,
534
+ $device_id: newId,
535
+ $session_id: newId,
536
+ session_timestamp: Date.now(),
537
+ $user_state: 'anonymous',
538
+ };
539
+ }
540
+ // Save to localStorage
541
+ this.saveIdentity();
542
+ }
543
+ catch (error) {
544
+ console.warn('Journium: Failed to load/create identity:', error);
545
+ // Fallback: create temporary identity without localStorage
546
+ const newId = generateUuidv7();
547
+ this.identity = {
548
+ distinct_id: newId,
549
+ $device_id: newId,
550
+ $session_id: newId,
551
+ session_timestamp: Date.now(),
552
+ $user_state: 'anonymous',
553
+ };
554
+ }
555
+ }
556
+ saveIdentity() {
557
+ if (!this.isBrowser() || !this.identity)
558
+ return;
559
+ try {
560
+ localStorage.setItem(this.storageKey, JSON.stringify(this.identity));
561
+ }
562
+ catch (error) {
563
+ console.warn('Journium: Failed to save identity to localStorage:', error);
564
+ }
565
+ }
566
+ isBrowser() {
567
+ return typeof window !== 'undefined' && typeof localStorage !== 'undefined';
568
+ }
569
+ getIdentity() {
570
+ return this.identity;
571
+ }
572
+ updateSessionTimeout(timeoutMs) {
573
+ this.sessionTimeout = timeoutMs;
574
+ }
575
+ refreshSession() {
576
+ if (!this.identity)
577
+ return;
578
+ this.identity = {
579
+ ...this.identity,
580
+ $session_id: generateUuidv7(),
581
+ session_timestamp: Date.now(),
582
+ };
583
+ this.saveIdentity();
584
+ }
585
+ identify(distinctId, attributes = {}) {
586
+ if (!this.identity)
587
+ return { previousDistinctId: null };
588
+ const previousDistinctId = this.identity.distinct_id;
589
+ // Update the distinct ID and mark user as identified
590
+ this.identity = {
591
+ ...this.identity,
592
+ distinct_id: distinctId,
593
+ $user_state: 'identified',
594
+ };
595
+ this.saveIdentity();
596
+ return { previousDistinctId };
597
+ }
598
+ reset() {
599
+ if (!this.identity)
600
+ return;
601
+ // Generate new distinct ID but keep device ID
602
+ this.identity = {
603
+ ...this.identity,
604
+ distinct_id: generateUuidv7(),
605
+ $user_state: 'anonymous',
606
+ };
607
+ this.saveIdentity();
608
+ }
609
+ getUserAgentInfo() {
610
+ if (!this.isBrowser()) {
611
+ return {
612
+ $raw_user_agent: '',
613
+ $browser: 'Unknown',
614
+ $os: 'Unknown',
615
+ $device_type: 'Unknown',
616
+ };
617
+ }
618
+ const userAgent = navigator.userAgent;
619
+ return {
620
+ $raw_user_agent: userAgent,
621
+ $browser: this.parseBrowser(userAgent),
622
+ $os: this.parseOS(userAgent),
623
+ $device_type: this.parseDeviceType(userAgent),
624
+ };
625
+ }
626
+ parseBrowser(userAgent) {
627
+ if (userAgent.includes('Chrome') && !userAgent.includes('Edg'))
628
+ return 'Chrome';
629
+ if (userAgent.includes('Firefox'))
630
+ return 'Firefox';
631
+ if (userAgent.includes('Safari') && !userAgent.includes('Chrome'))
632
+ return 'Safari';
633
+ if (userAgent.includes('Edg'))
634
+ return 'Edge';
635
+ if (userAgent.includes('Opera') || userAgent.includes('OPR'))
636
+ return 'Opera';
637
+ return 'Unknown';
638
+ }
639
+ parseOS(userAgent) {
640
+ if (userAgent.includes('Windows'))
641
+ return 'Windows';
642
+ if (userAgent.includes('Macintosh') || userAgent.includes('Mac OS'))
643
+ return 'Mac OS';
644
+ if (userAgent.includes('Linux'))
645
+ return 'Linux';
646
+ if (userAgent.includes('Android'))
647
+ return 'Android';
648
+ if (userAgent.includes('iPhone') || userAgent.includes('iPad'))
649
+ return 'iOS';
650
+ return 'Unknown';
651
+ }
652
+ parseDeviceType(userAgent) {
653
+ if (userAgent.includes('Mobile') || userAgent.includes('Android') || userAgent.includes('iPhone')) {
654
+ return 'Mobile';
655
+ }
656
+ if (userAgent.includes('iPad') || userAgent.includes('Tablet')) {
657
+ return 'Tablet';
658
+ }
659
+ return 'Desktop';
660
+ }
661
+ }
662
+
663
+ class JourniumClient {
664
+ constructor(config) {
665
+ this.queue = [];
666
+ this.flushTimer = null;
667
+ this.initialized = false;
668
+ // Validate required configuration
669
+ if (!config.token) {
670
+ console.error('Journium: token is required but not provided. SDK will not function.');
671
+ return;
672
+ }
673
+ if (!config.apiHost) {
674
+ console.error('Journium: apiHost is required but not provided. SDK will not function.');
675
+ return;
676
+ }
677
+ this.config = config;
678
+ // Generate storage key for config caching
679
+ this.configStorageKey = `jrnm_${config.token}_config`;
680
+ // Initialize identity manager
681
+ this.identityManager = new BrowserIdentityManager(this.config.sessionTimeout, this.config.token);
682
+ // Initialize synchronously with cached config, fetch fresh config in background
683
+ this.initializeSync();
684
+ this.fetchRemoteConfigAsync();
685
+ }
686
+ loadCachedConfig() {
687
+ if (typeof window === 'undefined' || !window.localStorage) {
688
+ return null;
689
+ }
690
+ try {
691
+ const cached = window.localStorage.getItem(this.configStorageKey);
692
+ return cached ? JSON.parse(cached) : null;
693
+ }
694
+ catch (error) {
695
+ if (this.config.debug) {
696
+ console.warn('Journium: Failed to load cached config:', error);
697
+ }
698
+ return null;
699
+ }
700
+ }
701
+ saveCachedConfig(config) {
702
+ if (typeof window === 'undefined' || !window.localStorage) {
703
+ return;
704
+ }
705
+ try {
706
+ window.localStorage.setItem(this.configStorageKey, JSON.stringify(config));
707
+ }
708
+ catch (error) {
709
+ if (this.config.debug) {
710
+ console.warn('Journium: Failed to save config to cache:', error);
711
+ }
712
+ }
713
+ }
714
+ initializeSync() {
715
+ var _a, _b, _c;
716
+ // Step 1: Load cached config from localStorage (synchronous)
717
+ const cachedConfig = this.loadCachedConfig();
718
+ // Step 2: Apply cached config immediately, or use defaults
719
+ const localOnlyConfig = {
720
+ apiHost: this.config.apiHost,
721
+ token: this.config.token,
722
+ };
723
+ if (cachedConfig) {
724
+ // Use cached remote config
725
+ this.config = {
726
+ ...localOnlyConfig,
727
+ ...cachedConfig,
728
+ };
729
+ if (this.config.debug) {
730
+ console.log('Journium: Using cached configuration:', cachedConfig);
731
+ }
732
+ }
733
+ else {
734
+ // Use defaults for first-time initialization
735
+ this.config = {
736
+ ...this.config,
737
+ debug: (_a = this.config.debug) !== null && _a !== void 0 ? _a : false,
738
+ flushAt: (_b = this.config.flushAt) !== null && _b !== void 0 ? _b : 20,
739
+ flushInterval: (_c = this.config.flushInterval) !== null && _c !== void 0 ? _c : 10000,
740
+ };
741
+ if (this.config.debug) {
742
+ console.log('Journium: No cached config found, using defaults');
743
+ }
744
+ }
745
+ // Update session timeout from config
746
+ if (this.config.sessionTimeout) {
747
+ this.identityManager.updateSessionTimeout(this.config.sessionTimeout);
748
+ }
749
+ // Step 3: Mark as initialized immediately - no need to wait for remote fetch
750
+ this.initialized = true;
751
+ // Step 4: Start flush timer immediately
752
+ if (this.config.flushInterval && this.config.flushInterval > 0) {
753
+ this.startFlushTimer();
754
+ }
755
+ if (this.config.debug) {
756
+ console.log('Journium: Client initialized and ready to track events');
757
+ }
758
+ }
759
+ async fetchRemoteConfigAsync() {
760
+ // Fetch fresh config in background
761
+ if (this.config.token) {
762
+ await this.fetchAndCacheRemoteConfig();
763
+ }
764
+ }
765
+ async fetchAndCacheRemoteConfig() {
766
+ try {
767
+ if (this.config.debug) {
768
+ console.log('Journium: Fetching remote configuration in background...');
769
+ }
770
+ const remoteConfigResponse = await fetchRemoteConfig(this.config.apiHost, this.config.token);
771
+ if (remoteConfigResponse && remoteConfigResponse.success) {
772
+ // Save to cache for next session
773
+ this.saveCachedConfig(remoteConfigResponse.config);
774
+ // Apply fresh config to current session
775
+ const localOnlyConfig = {
776
+ apiHost: this.config.apiHost,
777
+ token: this.config.token,
778
+ };
779
+ this.config = {
780
+ ...localOnlyConfig,
781
+ ...remoteConfigResponse.config,
782
+ };
783
+ // Update session timeout if provided in fresh config
784
+ if (remoteConfigResponse.config.sessionTimeout) {
785
+ this.identityManager.updateSessionTimeout(remoteConfigResponse.config.sessionTimeout);
786
+ }
787
+ if (this.config.debug) {
788
+ console.log('Journium: Background remote configuration applied:', remoteConfigResponse.config);
789
+ }
790
+ }
791
+ }
792
+ catch (error) {
793
+ if (this.config.debug) {
794
+ console.warn('Journium: Background remote config fetch failed:', error);
795
+ }
796
+ }
797
+ }
798
+ startFlushTimer() {
799
+ if (this.flushTimer) {
800
+ clearInterval(this.flushTimer);
801
+ }
802
+ // Use universal setInterval (works in both browser and Node.js)
803
+ this.flushTimer = setInterval(() => {
804
+ this.flush();
805
+ }, this.config.flushInterval);
806
+ }
807
+ async sendEvents(events) {
808
+ if (!events.length)
809
+ return;
810
+ try {
811
+ const response = await fetch(`${this.config.apiHost}/v1/ingest_event`, {
812
+ method: 'POST',
813
+ headers: {
814
+ 'Content-Type': 'application/json',
815
+ 'Authorization': `Bearer ${this.config.token}`,
816
+ },
817
+ body: JSON.stringify({
818
+ events,
819
+ }),
820
+ });
821
+ if (!response.ok) {
822
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
823
+ }
824
+ if (this.config.debug) {
825
+ console.log('Journium: Successfully sent events', events);
826
+ }
827
+ }
828
+ catch (error) {
829
+ if (this.config.debug) {
830
+ console.error('Journium: Failed to send events', error);
831
+ }
832
+ throw error;
833
+ }
834
+ }
835
+ identify(distinctId, attributes = {}) {
836
+ var _a;
837
+ // Don't identify if SDK is not properly configured
838
+ if (!this.config || !this.config.token || !this.config.apiHost || !this.initialized) {
839
+ if ((_a = this.config) === null || _a === void 0 ? void 0 : _a.debug) {
840
+ console.warn('Journium: identify() call rejected - SDK not ready');
841
+ }
842
+ return;
843
+ }
844
+ // Call identify on identity manager to get previous distinct ID
845
+ const { previousDistinctId } = this.identityManager.identify(distinctId, attributes);
846
+ // Track $identify event with previous distinct ID
847
+ const identifyProperties = {
848
+ ...attributes,
849
+ $anon_distinct_id: previousDistinctId,
850
+ };
851
+ this.track('$identify', identifyProperties);
852
+ if (this.config.debug) {
853
+ console.log('Journium: User identified', { distinctId, attributes, previousDistinctId });
854
+ }
855
+ }
856
+ reset() {
857
+ var _a;
858
+ // Don't reset if SDK is not properly configured
859
+ if (!this.config || !this.config.token || !this.config.apiHost || !this.initialized) {
860
+ if ((_a = this.config) === null || _a === void 0 ? void 0 : _a.debug) {
861
+ console.warn('Journium: reset() call rejected - SDK not ready');
862
+ }
863
+ return;
864
+ }
865
+ // Reset identity in identity manager
866
+ this.identityManager.reset();
867
+ if (this.config.debug) {
868
+ console.log('Journium: User identity reset');
869
+ }
870
+ }
871
+ track(event, properties = {}) {
872
+ var _a;
873
+ // Don't track if SDK is not properly configured
874
+ if (!this.config || !this.config.token || !this.config.apiHost || !this.initialized) {
875
+ if ((_a = this.config) === null || _a === void 0 ? void 0 : _a.debug) {
876
+ console.warn('Journium: track() call rejected - SDK not ready');
877
+ }
878
+ return;
879
+ }
880
+ const identity = this.identityManager.getIdentity();
881
+ const userAgentInfo = this.identityManager.getUserAgentInfo();
882
+ // Create standardized event properties
883
+ const eventProperties = {
884
+ $device_id: identity === null || identity === void 0 ? void 0 : identity.$device_id,
885
+ distinct_id: identity === null || identity === void 0 ? void 0 : identity.distinct_id,
886
+ $session_id: identity === null || identity === void 0 ? void 0 : identity.$session_id,
887
+ $is_identified: (identity === null || identity === void 0 ? void 0 : identity.$user_state) === 'identified',
888
+ $current_url: typeof window !== 'undefined' ? window.location.href : '',
889
+ $pathname: typeof window !== 'undefined' ? window.location.pathname : '',
890
+ ...userAgentInfo,
891
+ $lib_version: '0.1.0', // TODO: Get from package.json
892
+ $platform: 'web',
893
+ ...properties, // User-provided properties override defaults
894
+ };
895
+ const journiumEvent = {
896
+ uuid: generateUuidv7(),
897
+ ingestion_key: this.config.token,
898
+ client_timestamp: getCurrentTimestamp(),
899
+ event,
900
+ properties: eventProperties,
901
+ };
902
+ this.queue.push(journiumEvent);
903
+ if (this.config.debug) {
904
+ console.log('Journium: Event tracked', journiumEvent);
905
+ }
906
+ if (this.queue.length >= this.config.flushAt) {
907
+ this.flush();
908
+ }
909
+ }
910
+ async flush() {
911
+ // Don't flush if SDK is not properly configured
912
+ if (!this.config || !this.config.token || !this.config.apiHost) {
913
+ return;
914
+ }
915
+ if (this.queue.length === 0)
916
+ return;
917
+ const events = [...this.queue];
918
+ this.queue = [];
919
+ try {
920
+ await this.sendEvents(events);
921
+ }
922
+ catch (error) {
923
+ this.queue.unshift(...events);
924
+ throw error;
925
+ }
926
+ }
927
+ destroy() {
928
+ if (this.flushTimer) {
929
+ clearInterval(this.flushTimer);
930
+ this.flushTimer = null;
931
+ }
932
+ this.flush();
933
+ }
934
+ }
935
+
936
+ class PageviewTracker {
937
+ constructor(client) {
938
+ this.lastUrl = '';
939
+ this.originalPushState = null;
940
+ this.originalReplaceState = null;
941
+ this.popStateHandler = null;
942
+ this.client = client;
943
+ }
944
+ capturePageview(customProperties = {}) {
945
+ const currentUrl = getCurrentUrl();
946
+ const url = new URL(currentUrl);
947
+ const properties = {
948
+ $current_url: currentUrl,
949
+ $host: url.host,
950
+ $pathname: url.pathname,
951
+ $search: url.search,
952
+ $title: getPageTitle(),
953
+ $referrer: getReferrer(),
954
+ ...customProperties,
955
+ };
956
+ this.client.track('$pageview', properties);
957
+ this.lastUrl = currentUrl;
958
+ }
959
+ startAutoCapture() {
960
+ this.capturePageview();
961
+ if (typeof window !== 'undefined') {
962
+ // Store original methods for cleanup
963
+ this.originalPushState = window.history.pushState;
964
+ this.originalReplaceState = window.history.replaceState;
965
+ window.history.pushState = (...args) => {
966
+ this.originalPushState.apply(window.history, args);
967
+ setTimeout(() => this.capturePageview(), 0);
968
+ };
969
+ window.history.replaceState = (...args) => {
970
+ this.originalReplaceState.apply(window.history, args);
971
+ setTimeout(() => this.capturePageview(), 0);
972
+ };
973
+ this.popStateHandler = () => {
974
+ setTimeout(() => this.capturePageview(), 0);
975
+ };
976
+ window.addEventListener('popstate', this.popStateHandler);
977
+ }
978
+ }
979
+ stopAutoCapture() {
980
+ if (typeof window !== 'undefined') {
981
+ // Restore original methods
982
+ if (this.originalPushState) {
983
+ window.history.pushState = this.originalPushState;
984
+ this.originalPushState = null;
985
+ }
986
+ if (this.originalReplaceState) {
987
+ window.history.replaceState = this.originalReplaceState;
988
+ this.originalReplaceState = null;
989
+ }
990
+ if (this.popStateHandler) {
991
+ window.removeEventListener('popstate', this.popStateHandler);
992
+ this.popStateHandler = null;
993
+ }
994
+ }
995
+ }
996
+ }
997
+
998
+ class AutocaptureTracker {
999
+ constructor(client, config = {}) {
1000
+ this.listeners = new Map();
1001
+ this.isActive = false;
1002
+ this.client = client;
1003
+ this.config = {
1004
+ captureClicks: true,
1005
+ captureFormSubmits: true,
1006
+ captureFormChanges: true,
1007
+ captureTextSelection: false,
1008
+ ignoreClasses: ['journium-ignore'],
1009
+ ignoreElements: ['script', 'style', 'noscript'],
1010
+ captureContentText: true,
1011
+ ...config,
1012
+ };
1013
+ }
1014
+ start() {
1015
+ if (!isBrowser() || this.isActive) {
1016
+ return;
1017
+ }
1018
+ this.isActive = true;
1019
+ if (this.config.captureClicks) {
1020
+ this.addClickListener();
1021
+ }
1022
+ if (this.config.captureFormSubmits) {
1023
+ this.addFormSubmitListener();
1024
+ }
1025
+ if (this.config.captureFormChanges) {
1026
+ this.addFormChangeListener();
1027
+ }
1028
+ if (this.config.captureTextSelection) {
1029
+ this.addTextSelectionListener();
1030
+ }
1031
+ }
1032
+ stop() {
1033
+ if (!isBrowser() || !this.isActive) {
1034
+ return;
1035
+ }
1036
+ this.isActive = false;
1037
+ this.listeners.forEach((listener, event) => {
1038
+ document.removeEventListener(event, listener, true);
1039
+ });
1040
+ this.listeners.clear();
1041
+ }
1042
+ addClickListener() {
1043
+ const clickListener = (event) => {
1044
+ const target = event.target;
1045
+ if (this.shouldIgnoreElement(target)) {
1046
+ return;
1047
+ }
1048
+ const properties = this.getElementProperties(target, 'click');
1049
+ this.client.track('$autocapture', {
1050
+ $event_type: 'click',
1051
+ ...properties,
1052
+ });
1053
+ };
1054
+ document.addEventListener('click', clickListener, true);
1055
+ this.listeners.set('click', clickListener);
1056
+ }
1057
+ addFormSubmitListener() {
1058
+ const submitListener = (event) => {
1059
+ const target = event.target;
1060
+ if (this.shouldIgnoreElement(target)) {
1061
+ return;
1062
+ }
1063
+ const properties = this.getFormProperties(target, 'submit');
1064
+ this.client.track('$autocapture', {
1065
+ $event_type: 'submit',
1066
+ ...properties,
1067
+ });
1068
+ };
1069
+ document.addEventListener('submit', submitListener, true);
1070
+ this.listeners.set('submit', submitListener);
1071
+ }
1072
+ addFormChangeListener() {
1073
+ const changeListener = (event) => {
1074
+ const target = event.target;
1075
+ if (this.shouldIgnoreElement(target) || !this.isFormElement(target)) {
1076
+ return;
1077
+ }
1078
+ const properties = this.getInputProperties(target, 'change');
1079
+ this.client.track('$autocapture', {
1080
+ $event_type: 'change',
1081
+ ...properties,
1082
+ });
1083
+ };
1084
+ document.addEventListener('change', changeListener, true);
1085
+ this.listeners.set('change', changeListener);
1086
+ }
1087
+ addTextSelectionListener() {
1088
+ const selectionListener = () => {
1089
+ const selection = window.getSelection();
1090
+ if (!selection || selection.toString().trim().length === 0) {
1091
+ return;
1092
+ }
1093
+ const selectedText = selection.toString().trim();
1094
+ if (selectedText.length < 3) { // Ignore very short selections
1095
+ return;
1096
+ }
1097
+ this.client.track('$autocapture', {
1098
+ $event_type: 'text_selection',
1099
+ $selected_text: selectedText.substring(0, 200), // Limit text length
1100
+ $selection_length: selectedText.length,
1101
+ });
1102
+ };
1103
+ document.addEventListener('mouseup', selectionListener);
1104
+ this.listeners.set('mouseup', selectionListener);
1105
+ }
1106
+ shouldIgnoreElement(element) {
1107
+ var _a, _b, _c;
1108
+ if (!element || !element.tagName) {
1109
+ return true;
1110
+ }
1111
+ // Check if element should be ignored by tag name
1112
+ if ((_a = this.config.ignoreElements) === null || _a === void 0 ? void 0 : _a.includes(element.tagName.toLowerCase())) {
1113
+ return true;
1114
+ }
1115
+ // Check if element has ignore classes
1116
+ if ((_b = this.config.ignoreClasses) === null || _b === void 0 ? void 0 : _b.some(cls => element.classList.contains(cls))) {
1117
+ return true;
1118
+ }
1119
+ // Check parent elements for ignore classes
1120
+ let parent = element.parentElement;
1121
+ while (parent) {
1122
+ if ((_c = this.config.ignoreClasses) === null || _c === void 0 ? void 0 : _c.some(cls => parent.classList.contains(cls))) {
1123
+ return true;
1124
+ }
1125
+ parent = parent.parentElement;
1126
+ }
1127
+ return false;
1128
+ }
1129
+ isFormElement(element) {
1130
+ const formElements = ['input', 'select', 'textarea'];
1131
+ return formElements.includes(element.tagName.toLowerCase());
1132
+ }
1133
+ getElementProperties(element, eventType) {
1134
+ const properties = {
1135
+ $element_tag: element.tagName.toLowerCase(),
1136
+ $element_type: this.getElementType(element),
1137
+ };
1138
+ // Element identifiers
1139
+ if (element.id) {
1140
+ properties.$element_id = element.id;
1141
+ }
1142
+ if (element.className) {
1143
+ properties.$element_classes = Array.from(element.classList);
1144
+ }
1145
+ // Element attributes
1146
+ const relevantAttributes = ['name', 'role', 'aria-label', 'data-testid', 'data-track'];
1147
+ relevantAttributes.forEach(attr => {
1148
+ const value = element.getAttribute(attr);
1149
+ if (value) {
1150
+ properties[`$element_${attr.replace('-', '_')}`] = value;
1151
+ }
1152
+ });
1153
+ // Element content
1154
+ if (this.config.captureContentText) {
1155
+ const text = this.getElementText(element);
1156
+ if (text) {
1157
+ properties.$element_text = text.substring(0, 200); // Limit text length
1158
+ }
1159
+ }
1160
+ // Elements chain data
1161
+ const elementsChain = this.getElementsChain(element);
1162
+ properties.$elements_chain = elementsChain.chain;
1163
+ properties.$elements_chain_href = elementsChain.href;
1164
+ properties.$elements_chain_elements = elementsChain.elements;
1165
+ properties.$elements_chain_texts = elementsChain.texts;
1166
+ properties.$elements_chain_ids = elementsChain.ids;
1167
+ // Position information
1168
+ const rect = element.getBoundingClientRect();
1169
+ properties.$element_position = {
1170
+ x: Math.round(rect.left),
1171
+ y: Math.round(rect.top),
1172
+ width: Math.round(rect.width),
1173
+ height: Math.round(rect.height),
1174
+ };
1175
+ // Parent information
1176
+ if (element.parentElement) {
1177
+ properties.$parent_tag = element.parentElement.tagName.toLowerCase();
1178
+ if (element.parentElement.id) {
1179
+ properties.$parent_id = element.parentElement.id;
1180
+ }
1181
+ }
1182
+ // URL information
1183
+ properties.$current_url = window.location.href;
1184
+ properties.$host = window.location.host;
1185
+ properties.$pathname = window.location.pathname;
1186
+ return properties;
1187
+ }
1188
+ getFormProperties(form, eventType) {
1189
+ const properties = this.getElementProperties(form, eventType);
1190
+ // Form-specific properties
1191
+ properties.$form_method = form.method || 'get';
1192
+ properties.$form_action = form.action || '';
1193
+ // Count form elements
1194
+ const inputs = form.querySelectorAll('input, select, textarea');
1195
+ properties.$form_elements_count = inputs.length;
1196
+ // Form element types
1197
+ const elementTypes = {};
1198
+ inputs.forEach(input => {
1199
+ const type = this.getElementType(input);
1200
+ elementTypes[type] = (elementTypes[type] || 0) + 1;
1201
+ });
1202
+ properties.$form_element_types = elementTypes;
1203
+ return properties;
1204
+ }
1205
+ getInputProperties(input, eventType) {
1206
+ const properties = this.getElementProperties(input, eventType);
1207
+ // Input-specific properties
1208
+ properties.$input_type = input.type || 'text';
1209
+ if (input.name) {
1210
+ properties.$input_name = input.name;
1211
+ }
1212
+ if (input.placeholder) {
1213
+ properties.$input_placeholder = input.placeholder;
1214
+ }
1215
+ // Value information (be careful with sensitive data)
1216
+ if (this.isSafeInputType(input.type)) {
1217
+ if (input.type === 'checkbox' || input.type === 'radio') {
1218
+ properties.$input_checked = input.checked;
1219
+ }
1220
+ else if (input.value) {
1221
+ // For safe inputs, capture value length and basic characteristics
1222
+ properties.$input_value_length = input.value.length;
1223
+ properties.$input_has_value = input.value.length > 0;
1224
+ // For select elements, capture the selected value
1225
+ if (input.tagName.toLowerCase() === 'select') {
1226
+ properties.$input_selected_value = input.value;
1227
+ }
1228
+ }
1229
+ }
1230
+ // Form context
1231
+ const form = input.closest('form');
1232
+ if (form && form.id) {
1233
+ properties.$form_id = form.id;
1234
+ }
1235
+ return properties;
1236
+ }
1237
+ getElementType(element) {
1238
+ const tag = element.tagName.toLowerCase();
1239
+ if (tag === 'input') {
1240
+ return element.type || 'text';
1241
+ }
1242
+ if (tag === 'button') {
1243
+ return element.type || 'button';
1244
+ }
1245
+ return tag;
1246
+ }
1247
+ getElementText(element) {
1248
+ var _a, _b;
1249
+ // For buttons and links, get the visible text
1250
+ if (['button', 'a'].includes(element.tagName.toLowerCase())) {
1251
+ return ((_a = element.textContent) === null || _a === void 0 ? void 0 : _a.trim()) || '';
1252
+ }
1253
+ // For inputs, get placeholder or label
1254
+ if (element.tagName.toLowerCase() === 'input') {
1255
+ const input = element;
1256
+ return input.placeholder || input.value || '';
1257
+ }
1258
+ // For other elements, get text content but limit it
1259
+ const text = ((_b = element.textContent) === null || _b === void 0 ? void 0 : _b.trim()) || '';
1260
+ return text.length > 50 ? text.substring(0, 47) + '...' : text;
1261
+ }
1262
+ getElementsChain(element) {
1263
+ var _a;
1264
+ const elements = [];
1265
+ const texts = [];
1266
+ const ids = [];
1267
+ let href = '';
1268
+ let current = element;
1269
+ while (current && current !== document.body) {
1270
+ // Element selector
1271
+ let selector = current.tagName.toLowerCase();
1272
+ // Add ID if present
1273
+ if (current.id) {
1274
+ selector += `#${current.id}`;
1275
+ ids.push(current.id);
1276
+ }
1277
+ else {
1278
+ ids.push('');
1279
+ }
1280
+ // Add classes if present
1281
+ if (current.className && typeof current.className === 'string') {
1282
+ const classes = current.className.trim().split(/\s+/).slice(0, 3); // Limit to first 3 classes
1283
+ if (classes.length > 0 && classes[0] !== '') {
1284
+ selector += '.' + classes.join('.');
1285
+ }
1286
+ }
1287
+ // Add nth-child if no ID (to make selector more specific)
1288
+ if (!current.id && current.parentElement) {
1289
+ const siblings = Array.from(current.parentElement.children)
1290
+ .filter(child => child.tagName === current.tagName);
1291
+ if (siblings.length > 1) {
1292
+ const index = siblings.indexOf(current) + 1;
1293
+ selector += `:nth-child(${index})`;
1294
+ }
1295
+ }
1296
+ elements.push(selector);
1297
+ // Extract text content
1298
+ let text = '';
1299
+ if (current.tagName.toLowerCase() === 'a') {
1300
+ text = ((_a = current.textContent) === null || _a === void 0 ? void 0 : _a.trim()) || '';
1301
+ // Capture href for links
1302
+ if (!href && current.getAttribute('href')) {
1303
+ href = current.getAttribute('href') || '';
1304
+ }
1305
+ }
1306
+ else if (['button', 'span', 'div'].includes(current.tagName.toLowerCase())) {
1307
+ // For buttons and text elements, get direct text content (not including children)
1308
+ const directText = Array.from(current.childNodes)
1309
+ .filter(node => node.nodeType === Node.TEXT_NODE)
1310
+ .map(node => { var _a; return (_a = node.textContent) === null || _a === void 0 ? void 0 : _a.trim(); })
1311
+ .join(' ')
1312
+ .trim();
1313
+ text = directText || '';
1314
+ }
1315
+ else if (current.tagName.toLowerCase() === 'input') {
1316
+ const input = current;
1317
+ text = input.placeholder || input.value || '';
1318
+ }
1319
+ // Limit text length and clean it
1320
+ text = text.substring(0, 100).replace(/\s+/g, ' ').trim();
1321
+ texts.push(text);
1322
+ current = current.parentElement;
1323
+ }
1324
+ // Build the chain string (reverse order so it goes from parent to child)
1325
+ const chain = elements.reverse().join(' > ');
1326
+ return {
1327
+ chain,
1328
+ href,
1329
+ elements: elements,
1330
+ texts: texts.reverse(),
1331
+ ids: ids.reverse()
1332
+ };
1333
+ }
1334
+ isSafeInputType(type) {
1335
+ // Don't capture values for sensitive input types
1336
+ const sensitiveTypes = ['password', 'email', 'tel', 'credit-card-number'];
1337
+ return !sensitiveTypes.includes(type.toLowerCase());
1338
+ }
1339
+ }
1340
+
1341
+ class Journium {
1342
+ constructor(config) {
1343
+ this.config = config;
1344
+ this.client = new JourniumClient(config);
1345
+ this.pageviewTracker = new PageviewTracker(this.client);
1346
+ const autocaptureConfig = this.resolveAutocaptureConfig(config.autocapture);
1347
+ this.autocaptureTracker = new AutocaptureTracker(this.client, autocaptureConfig);
1348
+ // Store resolved autocapture state for startAutoCapture method
1349
+ this.autocaptureEnabled = config.autocapture !== false;
1350
+ }
1351
+ resolveAutocaptureConfig(autocapture) {
1352
+ if (autocapture === false) {
1353
+ return {
1354
+ captureClicks: false,
1355
+ captureFormSubmits: false,
1356
+ captureFormChanges: false,
1357
+ captureTextSelection: false,
1358
+ };
1359
+ }
1360
+ if (autocapture === true || autocapture === undefined) {
1361
+ return {}; // Use default configuration (enabled by default)
1362
+ }
1363
+ return autocapture;
1364
+ }
1365
+ track(event, properties) {
1366
+ this.client.track(event, properties);
1367
+ }
1368
+ identify(distinctId, attributes) {
1369
+ this.client.identify(distinctId, attributes);
1370
+ }
1371
+ reset() {
1372
+ this.client.reset();
1373
+ }
1374
+ capturePageview(properties) {
1375
+ this.pageviewTracker.capturePageview(properties);
1376
+ }
1377
+ startAutoCapture() {
1378
+ this.pageviewTracker.startAutoCapture();
1379
+ if (this.autocaptureEnabled) {
1380
+ this.autocaptureTracker.start();
1381
+ }
1382
+ }
1383
+ stopAutoCapture() {
1384
+ this.pageviewTracker.stopAutoCapture();
1385
+ this.autocaptureTracker.stop();
1386
+ }
1387
+ // Aliases for consistency (deprecated - use startAutoCapture)
1388
+ /** @deprecated Use startAutoCapture() instead */
1389
+ startAutocapture() {
1390
+ this.startAutoCapture();
1391
+ }
1392
+ /** @deprecated Use stopAutoCapture() instead */
1393
+ stopAutocapture() {
1394
+ this.stopAutoCapture();
1395
+ }
1396
+ async flush() {
1397
+ return this.client.flush();
1398
+ }
1399
+ destroy() {
1400
+ this.pageviewTracker.stopAutoCapture();
1401
+ this.autocaptureTracker.stop();
1402
+ this.client.destroy();
1403
+ }
1404
+ }
1405
+ const init = (config) => {
1406
+ return new Journium(config);
1407
+ };
1408
+
1409
+ exports.AutocaptureTracker = AutocaptureTracker;
1410
+ exports.BrowserIdentityManager = BrowserIdentityManager;
1411
+ exports.Journium = Journium;
1412
+ exports.JourniumClient = JourniumClient;
1413
+ exports.PageviewTracker = PageviewTracker;
1414
+ exports.fetchRemoteConfig = fetchRemoteConfig;
1415
+ exports.generateId = generateId;
1416
+ exports.generateUuidv7 = generateUuidv7;
1417
+ exports.getCurrentTimestamp = getCurrentTimestamp;
1418
+ exports.getCurrentUrl = getCurrentUrl;
1419
+ exports.getPageTitle = getPageTitle;
1420
+ exports.getReferrer = getReferrer;
1421
+ exports.init = init;
1422
+ exports.isBrowser = isBrowser;
1423
+ exports.isNode = isNode;
1424
+ exports.mergeConfigs = mergeConfigs;
1425
+ //# sourceMappingURL=index.cjs.map