@journium/react 0.1.0-alpha.1

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