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