@plasius/analytics 1.3.1 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,80 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
-
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
3
19
 
4
- var _chunk5BHE32SKcjs = require('./chunk-5BHE32SK.cjs');
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ AnalyticsProvider: () => AnalyticsProvider,
24
+ SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION: () => SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION,
25
+ SEMANTIC_JOURNEY_RECEIPT_HEADER: () => SEMANTIC_JOURNEY_RECEIPT_HEADER,
26
+ SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES: () => SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES,
27
+ SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT: () => SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT,
28
+ SEMANTIC_JOURNEY_RECEIPT_VERSION: () => SEMANTIC_JOURNEY_RECEIPT_VERSION,
29
+ SEMANTIC_JOURNEY_STRICT_POLICY_VERSION: () => SEMANTIC_JOURNEY_STRICT_POLICY_VERSION,
30
+ SemanticJourneyAggregateStore: () => SemanticJourneyAggregateStore,
31
+ SemanticJourneyTransportError: () => SemanticJourneyTransportError,
32
+ SemanticJourneyValidationError: () => SemanticJourneyValidationError,
33
+ USEFUL_METRIC_EVENT_DEFINITIONS: () => USEFUL_METRIC_EVENT_DEFINITIONS,
34
+ assertSemanticSource: () => assertSemanticSource,
35
+ assertSemanticToken: () => assertSemanticToken,
36
+ createBackendAnalyticsClient: () => createBackendAnalyticsClient,
37
+ createChildJourneyContext: () => createChildJourneyContext,
38
+ createDefaultSemanticJourneyAggregateTransport: () => createDefaultSemanticJourneyAggregateTransport,
39
+ createEventId: () => createEventId,
40
+ createFrontendAnalyticsClient: () => createFrontendAnalyticsClient,
41
+ createJourneyContext: () => createJourneyContext,
42
+ createJourneyId: () => createJourneyId,
43
+ createLocalSpaceAnalyticsClient: () => createLocalSpaceAnalyticsClient,
44
+ createNoopLocalSpaceAnalyticsClient: () => createNoopLocalSpaceAnalyticsClient,
45
+ createProducerId: () => createProducerId,
46
+ createRequestJourneyContext: () => createRequestJourneyContext,
47
+ createSecureRandomHex: () => createSecureRandomHex,
48
+ createSemanticJourneyClient: () => createSemanticJourneyClient,
49
+ createSpanId: () => createSpanId,
50
+ createTraceId: () => createTraceId,
51
+ defineJourneyEvent: () => defineJourneyEvent,
52
+ defineSemanticJourneyCatalog: () => defineSemanticJourneyCatalog,
53
+ formatTraceparent: () => formatTraceparent,
54
+ getJourneyEventDefinition: () => getJourneyEventDefinition,
55
+ isEventId: () => isEventId,
56
+ isJourneyId: () => isJourneyId,
57
+ isJourneyToken: () => isJourneyToken,
58
+ isProducerId: () => isProducerId,
59
+ isSecureSemanticJourneyEndpoint: () => isSecureSemanticJourneyEndpoint,
60
+ isSemanticSource: () => isSemanticSource,
61
+ isSemanticToken: () => isSemanticToken,
62
+ isSpanId: () => isSpanId,
63
+ isTraceId: () => isTraceId,
64
+ observeSemanticJourneyInteractions: () => observeSemanticJourneyInteractions,
65
+ parseSemanticJourneyReceipts: () => parseSemanticJourneyReceipts,
66
+ parseTraceparent: () => parseTraceparent,
67
+ projectUsefulMetric: () => projectUsefulMetric,
68
+ reconstructSemanticJourney: () => reconstructSemanticJourney,
69
+ serializeSemanticJourneyReceipts: () => serializeSemanticJourneyReceipts,
70
+ useAnalytics: () => useAnalytics,
71
+ useComponentInteractionTracker: () => useComponentInteractionTracker,
72
+ validateSemanticJourneyEventInput: () => validateSemanticJourneyEventInput
73
+ });
74
+ module.exports = __toCommonJS(src_exports);
5
75
 
6
76
  // src/core/client.ts
7
- var _schema = require('@plasius/schema');
77
+ var import_schema = require("@plasius/schema");
8
78
  var DEFAULT_FLUSH_INTERVAL_MS = 5e3;
9
79
  var DEFAULT_BATCH_SIZE = 20;
10
80
  var DEFAULT_MAX_QUEUE_SIZE = 500;
@@ -34,9 +104,9 @@ var DEFAULT_ERROR_REDACT_KEYS = [
34
104
  ];
35
105
  var JSON_CONTENT_TYPE_HEADER = "application/json";
36
106
  var LOCALHOST_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
37
- var PlainLogValueSchema = _schema.createSchema.call(void 0,
107
+ var PlainLogValueSchema = (0, import_schema.createSchema)(
38
108
  {
39
- value: _schema.field.generalText().PID({
109
+ value: import_schema.field.generalText().PID({
40
110
  classification: "none",
41
111
  action: "none",
42
112
  logHandling: "plain",
@@ -46,9 +116,9 @@ var PlainLogValueSchema = _schema.createSchema.call(void 0,
46
116
  "analytics-log-safe-value",
47
117
  { version: "1.0.0", piiEnforcement: "none" }
48
118
  );
49
- var SensitiveLogValueSchema = _schema.createSchema.call(void 0,
119
+ var SensitiveLogValueSchema = (0, import_schema.createSchema)(
50
120
  {
51
- value: _schema.field.generalText().PID({
121
+ value: import_schema.field.generalText().PID({
52
122
  classification: "high",
53
123
  action: "none",
54
124
  logHandling: "redact",
@@ -60,105 +130,105 @@ var SensitiveLogValueSchema = _schema.createSchema.call(void 0,
60
130
  );
61
131
  function applySchemaLogHandling(value, sensitive) {
62
132
  const schema = sensitive ? SensitiveLogValueSchema : PlainLogValueSchema;
63
- const sanitized = schema.sanitizeForLog({ value }, (input) => `p(${String(_nullishCoalesce(input, () => ( "")))})`);
133
+ const sanitized = schema.sanitizeForLog({ value }, (input) => `p(${String(input ?? "")})`);
64
134
  return typeof sanitized.value === "string" ? sanitized.value : "";
65
135
  }
66
136
  var REDACTED_VALUE = applySchemaLogHandling("sensitive", true) || "[REDACTED]";
67
- var CrashIdentitySchema = _schema.createSchema.call(void 0,
137
+ var CrashIdentitySchema = (0, import_schema.createSchema)(
68
138
  {
69
- source: _schema.field.generalText().PID({
139
+ source: import_schema.field.generalText().PID({
70
140
  classification: "none",
71
141
  action: "none",
72
142
  logHandling: "plain",
73
143
  purpose: "analytics source identifier"
74
144
  }).optional(),
75
- channel: _schema.field.generalText().PID({
145
+ channel: import_schema.field.generalText().PID({
76
146
  classification: "none",
77
147
  action: "none",
78
148
  logHandling: "plain",
79
149
  purpose: "analytics channel identifier"
80
150
  }).optional(),
81
- runtime: _schema.field.generalText().PID({
151
+ runtime: import_schema.field.generalText().PID({
82
152
  classification: "none",
83
153
  action: "none",
84
154
  logHandling: "plain",
85
155
  purpose: "analytics runtime identifier"
86
156
  }).optional(),
87
- sessionId: _schema.field.generalText().PID({
157
+ sessionId: import_schema.field.generalText().PID({
88
158
  classification: "high",
89
159
  action: "hash",
90
160
  logHandling: "redact",
91
161
  purpose: "client session identifier"
92
162
  }).optional(),
93
- userAgent: _schema.field.generalText().PID({
163
+ userAgent: import_schema.field.generalText().PID({
94
164
  classification: "low",
95
165
  action: "hash",
96
166
  logHandling: "pseudonym",
97
167
  purpose: "browser user agent"
98
168
  }).optional(),
99
- platform: _schema.field.generalText().PID({
169
+ platform: import_schema.field.generalText().PID({
100
170
  classification: "low",
101
171
  action: "hash",
102
172
  logHandling: "pseudonym",
103
173
  purpose: "client platform"
104
174
  }).optional(),
105
- language: _schema.field.generalText().PID({
175
+ language: import_schema.field.generalText().PID({
106
176
  classification: "low",
107
177
  action: "hash",
108
178
  logHandling: "pseudonym",
109
179
  purpose: "client language"
110
180
  }).optional(),
111
- timezone: _schema.field.generalText().PID({
181
+ timezone: import_schema.field.generalText().PID({
112
182
  classification: "low",
113
183
  action: "hash",
114
184
  logHandling: "pseudonym",
115
185
  purpose: "client timezone"
116
186
  }).optional(),
117
- origin: _schema.field.generalText().PID({
187
+ origin: import_schema.field.generalText().PID({
118
188
  classification: "low",
119
189
  action: "hash",
120
190
  logHandling: "pseudonym",
121
191
  purpose: "client origin"
122
192
  }).optional(),
123
- pathname: _schema.field.generalText().PID({
193
+ pathname: import_schema.field.generalText().PID({
124
194
  classification: "low",
125
195
  action: "hash",
126
196
  logHandling: "pseudonym",
127
197
  purpose: "client route path"
128
198
  }).optional(),
129
- screenWidth: _schema.field.number().PID({
199
+ screenWidth: import_schema.field.number().PID({
130
200
  classification: "none",
131
201
  action: "none",
132
202
  logHandling: "plain",
133
203
  purpose: "viewport width"
134
204
  }).optional(),
135
- screenHeight: _schema.field.number().PID({
205
+ screenHeight: import_schema.field.number().PID({
136
206
  classification: "none",
137
207
  action: "none",
138
208
  logHandling: "plain",
139
209
  purpose: "viewport height"
140
210
  }).optional(),
141
- colorDepth: _schema.field.number().PID({
211
+ colorDepth: import_schema.field.number().PID({
142
212
  classification: "none",
143
213
  action: "none",
144
214
  logHandling: "plain",
145
215
  purpose: "screen color depth"
146
216
  }).optional(),
147
- hardwareConcurrency: _schema.field.number().PID({
217
+ hardwareConcurrency: import_schema.field.number().PID({
148
218
  classification: "none",
149
219
  action: "none",
150
220
  logHandling: "plain",
151
221
  purpose: "cpu concurrency"
152
222
  }).optional(),
153
- identifiers: _schema.field.array(
154
- _schema.field.object({
155
- key: _schema.field.generalText().PID({
223
+ identifiers: import_schema.field.array(
224
+ import_schema.field.object({
225
+ key: import_schema.field.generalText().PID({
156
226
  classification: "none",
157
227
  action: "none",
158
228
  logHandling: "plain",
159
229
  purpose: "identifier field key"
160
230
  }),
161
- value: _schema.field.generalText().PID({
231
+ value: import_schema.field.generalText().PID({
162
232
  classification: "high",
163
233
  action: "hash",
164
234
  logHandling: "redact",
@@ -202,7 +272,7 @@ function buildDefaultStorageKey(source, channel) {
202
272
  return `${DEFAULT_STORAGE_KEY_PREFIX}.${channel}.${sanitizeStorageSourceSegment(source)}`;
203
273
  }
204
274
  function resolveStorageKey(configStorageKey, source, channel, previous) {
205
- const explicitStorageKey = _optionalChain([configStorageKey, 'optionalAccess', _ => _.trim, 'call', _2 => _2()]);
275
+ const explicitStorageKey = configStorageKey?.trim();
206
276
  if (explicitStorageKey) {
207
277
  return explicitStorageKey;
208
278
  }
@@ -246,7 +316,7 @@ function toNumberWithMinimum(value, fallback, minimum) {
246
316
  return Math.max(toPositiveInteger(value, fallback), minimum);
247
317
  }
248
318
  function resolveSessionId(configSessionId, previousSessionId) {
249
- const explicitSessionId = _optionalChain([configSessionId, 'optionalAccess', _3 => _3.trim, 'call', _4 => _4()]);
319
+ const explicitSessionId = configSessionId?.trim();
250
320
  if (explicitSessionId) {
251
321
  return explicitSessionId;
252
322
  }
@@ -256,7 +326,7 @@ function resolveSessionId(configSessionId, previousSessionId) {
256
326
  return createId("session");
257
327
  }
258
328
  function normalizeRedactKeys(keys, previousKeys) {
259
- const values = _nullishCoalesce(_nullishCoalesce(keys, () => ( previousKeys)), () => ( DEFAULT_ERROR_REDACT_KEYS));
329
+ const values = keys ?? previousKeys ?? DEFAULT_ERROR_REDACT_KEYS;
260
330
  const normalized = values.map((value) => value.trim().toLowerCase()).filter((value) => value.length > 0);
261
331
  if (normalized.length === 0) {
262
332
  return [...DEFAULT_ERROR_REDACT_KEYS];
@@ -265,97 +335,97 @@ function normalizeRedactKeys(keys, previousKeys) {
265
335
  }
266
336
  function resolveErrorReportingConfig(config, previous) {
267
337
  return {
268
- enabled: _nullishCoalesce(_nullishCoalesce(_optionalChain([config, 'optionalAccess', _5 => _5.enabled]), () => ( _optionalChain([previous, 'optionalAccess', _6 => _6.enabled]))), () => ( true)),
269
- secureEndpointOnly: _nullishCoalesce(_nullishCoalesce(_optionalChain([config, 'optionalAccess', _7 => _7.secureEndpointOnly]), () => ( _optionalChain([previous, 'optionalAccess', _8 => _8.secureEndpointOnly]))), () => ( true)),
338
+ enabled: config?.enabled ?? previous?.enabled ?? true,
339
+ secureEndpointOnly: config?.secureEndpointOnly ?? previous?.secureEndpointOnly ?? true,
270
340
  maxMessageLength: toNumberWithMinimum(
271
- _nullishCoalesce(_optionalChain([config, 'optionalAccess', _9 => _9.maxMessageLength]), () => ( _optionalChain([previous, 'optionalAccess', _10 => _10.maxMessageLength]))),
341
+ config?.maxMessageLength ?? previous?.maxMessageLength,
272
342
  DEFAULT_ERROR_MESSAGE_LENGTH,
273
343
  16
274
344
  ),
275
345
  maxStackLength: toNumberWithMinimum(
276
- _nullishCoalesce(_optionalChain([config, 'optionalAccess', _11 => _11.maxStackLength]), () => ( _optionalChain([previous, 'optionalAccess', _12 => _12.maxStackLength]))),
346
+ config?.maxStackLength ?? previous?.maxStackLength,
277
347
  DEFAULT_ERROR_STACK_LENGTH,
278
348
  32
279
349
  ),
280
350
  maxComponentStackLength: toNumberWithMinimum(
281
- _nullishCoalesce(_optionalChain([config, 'optionalAccess', _13 => _13.maxComponentStackLength]), () => ( _optionalChain([previous, 'optionalAccess', _14 => _14.maxComponentStackLength]))),
351
+ config?.maxComponentStackLength ?? previous?.maxComponentStackLength,
282
352
  DEFAULT_ERROR_COMPONENT_STACK_LENGTH,
283
353
  32
284
354
  ),
285
355
  maxContextDepth: toNumberWithMinimum(
286
- _nullishCoalesce(_optionalChain([config, 'optionalAccess', _15 => _15.maxContextDepth]), () => ( _optionalChain([previous, 'optionalAccess', _16 => _16.maxContextDepth]))),
356
+ config?.maxContextDepth ?? previous?.maxContextDepth,
287
357
  DEFAULT_ERROR_CONTEXT_DEPTH,
288
358
  1
289
359
  ),
290
360
  maxContextBreadth: toNumberWithMinimum(
291
- _nullishCoalesce(_optionalChain([config, 'optionalAccess', _17 => _17.maxContextBreadth]), () => ( _optionalChain([previous, 'optionalAccess', _18 => _18.maxContextBreadth]))),
361
+ config?.maxContextBreadth ?? previous?.maxContextBreadth,
292
362
  DEFAULT_ERROR_CONTEXT_BREADTH,
293
363
  1
294
364
  ),
295
365
  maxTagCount: toNumberWithMinimum(
296
- _nullishCoalesce(_optionalChain([config, 'optionalAccess', _19 => _19.maxTagCount]), () => ( _optionalChain([previous, 'optionalAccess', _20 => _20.maxTagCount]))),
366
+ config?.maxTagCount ?? previous?.maxTagCount,
297
367
  DEFAULT_ERROR_TAG_COUNT,
298
368
  1
299
369
  ),
300
370
  thresholdCount: toNumberWithMinimum(
301
- _nullishCoalesce(_optionalChain([config, 'optionalAccess', _21 => _21.thresholdCount]), () => ( _optionalChain([previous, 'optionalAccess', _22 => _22.thresholdCount]))),
371
+ config?.thresholdCount ?? previous?.thresholdCount,
302
372
  DEFAULT_ERROR_THRESHOLD_COUNT,
303
373
  1
304
374
  ),
305
375
  thresholdWindowMs: toNumberWithMinimum(
306
- _nullishCoalesce(_optionalChain([config, 'optionalAccess', _23 => _23.thresholdWindowMs]), () => ( _optionalChain([previous, 'optionalAccess', _24 => _24.thresholdWindowMs]))),
376
+ config?.thresholdWindowMs ?? previous?.thresholdWindowMs,
307
377
  DEFAULT_ERROR_THRESHOLD_WINDOW_MS,
308
378
  1e3
309
379
  ),
310
- redactKeys: normalizeRedactKeys(_optionalChain([config, 'optionalAccess', _25 => _25.redactKeys]), _optionalChain([previous, 'optionalAccess', _26 => _26.redactKeys])),
311
- onThresholdReached: _nullishCoalesce(_optionalChain([config, 'optionalAccess', _27 => _27.onThresholdReached]), () => ( _optionalChain([previous, 'optionalAccess', _28 => _28.onThresholdReached])))
380
+ redactKeys: normalizeRedactKeys(config?.redactKeys, previous?.redactKeys),
381
+ onThresholdReached: config?.onThresholdReached ?? previous?.onThresholdReached
312
382
  };
313
383
  }
314
384
  function resolveConfig(config, previous) {
315
- const source = (_nullishCoalesce(_nullishCoalesce(config.source, () => ( _optionalChain([previous, 'optionalAccess', _29 => _29.source]))), () => ( ""))).trim();
385
+ const source = (config.source ?? previous?.source ?? "").trim();
316
386
  if (!source) {
317
387
  throw new Error("Local space analytics requires a non-empty source.");
318
388
  }
319
- const runtime = resolveRuntime(config.runtime, _optionalChain([previous, 'optionalAccess', _30 => _30.runtime]));
320
- const channel = resolveChannel(config.channel, runtime, _optionalChain([previous, 'optionalAccess', _31 => _31.channel]));
321
- const endpointCandidate = config.endpoint !== void 0 ? config.endpoint : _optionalChain([previous, 'optionalAccess', _32 => _32.endpoint]);
322
- const endpoint = _optionalChain([endpointCandidate, 'optionalAccess', _33 => _33.trim, 'call', _34 => _34()]) || void 0;
389
+ const runtime = resolveRuntime(config.runtime, previous?.runtime);
390
+ const channel = resolveChannel(config.channel, runtime, previous?.channel);
391
+ const endpointCandidate = config.endpoint !== void 0 ? config.endpoint : previous?.endpoint;
392
+ const endpoint = endpointCandidate?.trim() || void 0;
323
393
  return {
324
394
  source,
325
395
  endpoint,
326
396
  channel,
327
397
  runtime,
328
- sessionId: resolveSessionId(config.sessionId, _optionalChain([previous, 'optionalAccess', _35 => _35.sessionId])),
329
- injectChannelContext: _nullishCoalesce(_nullishCoalesce(config.injectChannelContext, () => ( _optionalChain([previous, 'optionalAccess', _36 => _36.injectChannelContext]))), () => ( true)),
330
- enabled: _nullishCoalesce(_nullishCoalesce(config.enabled, () => ( _optionalChain([previous, 'optionalAccess', _37 => _37.enabled]))), () => ( true)),
398
+ sessionId: resolveSessionId(config.sessionId, previous?.sessionId),
399
+ injectChannelContext: config.injectChannelContext ?? previous?.injectChannelContext ?? true,
400
+ enabled: config.enabled ?? previous?.enabled ?? true,
331
401
  defaultContext: {
332
- ..._nullishCoalesce(_optionalChain([previous, 'optionalAccess', _38 => _38.defaultContext]), () => ( {})),
333
- ..._nullishCoalesce(config.defaultContext, () => ( {}))
402
+ ...previous?.defaultContext ?? {},
403
+ ...config.defaultContext ?? {}
334
404
  },
335
405
  headers: {
336
406
  "content-type": JSON_CONTENT_TYPE_HEADER,
337
- ..._nullishCoalesce(_optionalChain([previous, 'optionalAccess', _39 => _39.headers]), () => ( {})),
338
- ..._nullishCoalesce(config.headers, () => ( {}))
407
+ ...previous?.headers ?? {},
408
+ ...config.headers ?? {}
339
409
  },
340
410
  flushIntervalMs: toPositiveInteger(
341
- _nullishCoalesce(config.flushIntervalMs, () => ( _optionalChain([previous, 'optionalAccess', _40 => _40.flushIntervalMs]))),
411
+ config.flushIntervalMs ?? previous?.flushIntervalMs,
342
412
  DEFAULT_FLUSH_INTERVAL_MS
343
413
  ),
344
414
  batchSize: toPositiveInteger(
345
- _nullishCoalesce(config.batchSize, () => ( _optionalChain([previous, 'optionalAccess', _41 => _41.batchSize]))),
415
+ config.batchSize ?? previous?.batchSize,
346
416
  DEFAULT_BATCH_SIZE
347
417
  ),
348
418
  maxQueueSize: toPositiveInteger(
349
- _nullishCoalesce(config.maxQueueSize, () => ( _optionalChain([previous, 'optionalAccess', _42 => _42.maxQueueSize]))),
419
+ config.maxQueueSize ?? previous?.maxQueueSize,
350
420
  DEFAULT_MAX_QUEUE_SIZE
351
421
  ),
352
422
  storageKey: resolveStorageKey(config.storageKey, source, channel, previous),
353
423
  errorReporting: resolveErrorReportingConfig(
354
424
  config.errorReporting,
355
- _optionalChain([previous, 'optionalAccess', _43 => _43.errorReporting])
425
+ previous?.errorReporting
356
426
  ),
357
- transport: _nullishCoalesce(_nullishCoalesce(config.transport, () => ( _optionalChain([previous, 'optionalAccess', _44 => _44.transport]))), () => ( defaultTransport)),
358
- onError: _nullishCoalesce(config.onError, () => ( _optionalChain([previous, 'optionalAccess', _45 => _45.onError])))
427
+ transport: config.transport ?? previous?.transport ?? defaultTransport,
428
+ onError: config.onError ?? previous?.onError
359
429
  };
360
430
  }
361
431
  function isStoredRecordCandidate(value) {
@@ -382,7 +452,7 @@ function redactSensitiveText(value) {
382
452
  );
383
453
  }
384
454
  function sanitizeSingleLine(value, maxLength) {
385
- const raw = typeof value === "string" ? value : String(_nullishCoalesce(value, () => ( "")));
455
+ const raw = typeof value === "string" ? value : String(value ?? "");
386
456
  const flattened = raw.replace(/\p{Cc}/gu, " ").replace(/\s+/g, " ").trim();
387
457
  if (!flattened) {
388
458
  return "";
@@ -391,7 +461,7 @@ function sanitizeSingleLine(value, maxLength) {
391
461
  return applySchemaLogHandling(redacted, false).slice(0, maxLength);
392
462
  }
393
463
  function sanitizeMultiline(value, maxLength) {
394
- const raw = typeof value === "string" ? value : String(_nullishCoalesce(value, () => ( "")));
464
+ const raw = typeof value === "string" ? value : String(value ?? "");
395
465
  const normalized = raw.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
396
466
  const sanitized = redactSensitiveText(normalized).split("\n").map((line) => line.trim()).filter((line) => line.length > 0).join("\n");
397
467
  if (!sanitized) {
@@ -487,7 +557,7 @@ function sanitizeContextValue(value, resolvedErrorReporting, depth, seen, identi
487
557
  for (const [key, nestedValue] of entries) {
488
558
  const childPath = keyPath ? `${keyPath}.${key}` : key;
489
559
  if (shouldRedactContextKey(key, resolvedErrorReporting)) {
490
- sanitized[key] = applySchemaLogHandling(String(_nullishCoalesce(nestedValue, () => ( ""))), true) || REDACTED_VALUE;
560
+ sanitized[key] = applySchemaLogHandling(String(nestedValue ?? ""), true) || REDACTED_VALUE;
491
561
  pushIdentifier(
492
562
  identifiers,
493
563
  childPath,
@@ -519,7 +589,7 @@ function sanitizeErrorContext(context, resolvedErrorReporting) {
519
589
  const entries = Object.entries(context).slice(0, resolvedErrorReporting.maxContextBreadth);
520
590
  for (const [key, value] of entries) {
521
591
  if (shouldRedactContextKey(key, resolvedErrorReporting)) {
522
- sanitized[key] = applySchemaLogHandling(String(_nullishCoalesce(value, () => ( ""))), true) || REDACTED_VALUE;
592
+ sanitized[key] = applySchemaLogHandling(String(value ?? ""), true) || REDACTED_VALUE;
523
593
  pushIdentifier(identifiers, key, value, resolvedErrorReporting.maxMessageLength);
524
594
  continue;
525
595
  }
@@ -603,7 +673,7 @@ function normalizeTags(tags, maxTagCount, maxTagLength) {
603
673
  function safeSerialize(value) {
604
674
  try {
605
675
  return JSON.stringify(value);
606
- } catch (e) {
676
+ } catch {
607
677
  return "[unserializable]";
608
678
  }
609
679
  }
@@ -646,13 +716,13 @@ function normalizeErrorReport(report, resolvedErrorReporting, existingFingerprin
646
716
  resolvedErrorReporting.maxComponentStackLength
647
717
  ) : void 0;
648
718
  const severity = report.severity === "fatal" ? "fatal" : "error";
649
- const handled = _nullishCoalesce(report.handled, () => ( true));
719
+ const handled = report.handled ?? true;
650
720
  const tags = normalizeTags(
651
721
  report.tags,
652
722
  resolvedErrorReporting.maxTagCount,
653
723
  resolvedErrorReporting.maxMessageLength
654
724
  );
655
- const fingerprintBase = `${boundary}|${name}|${message}|${_nullishCoalesce(_optionalChain([stack, 'optionalAccess', _46 => _46.split, 'call', _47 => _47("\n"), 'access', _48 => _48[0]]), () => ( ""))}|${severity}`;
725
+ const fingerprintBase = `${boundary}|${name}|${message}|${stack?.split("\n")[0] ?? ""}|${severity}`;
656
726
  const fallbackFingerprint = `err_${hashString(fingerprintBase).toString(16)}`;
657
727
  const fingerprint = sanitizeSingleLine(existingFingerprint, 120) || fallbackFingerprint;
658
728
  return {
@@ -714,7 +784,7 @@ function readQueue(storageKey, fallbackConfig) {
714
784
  return [];
715
785
  }
716
786
  return parsed.filter(isStoredRecordCandidate).map((record) => normalizeStoredRecord(record, fallbackConfig));
717
- } catch (e2) {
787
+ } catch {
718
788
  return [];
719
789
  }
720
790
  }
@@ -728,7 +798,7 @@ function writeQueue(storageKey, queue) {
728
798
  return;
729
799
  }
730
800
  window.localStorage.setItem(storageKey, JSON.stringify(queue));
731
- } catch (e3) {
801
+ } catch {
732
802
  }
733
803
  }
734
804
  function createPayload(config, events) {
@@ -743,7 +813,7 @@ function createPayload(config, events) {
743
813
  function createMergedContext(config, eventChannel, eventContext) {
744
814
  const mergedContext = {
745
815
  ...config.defaultContext,
746
- ..._nullishCoalesce(eventContext, () => ( {}))
816
+ ...eventContext ?? {}
747
817
  };
748
818
  if (config.injectChannelContext) {
749
819
  if (mergedContext.analyticsChannel === void 0) {
@@ -770,7 +840,7 @@ function isSecureEndpoint(endpoint) {
770
840
  return true;
771
841
  }
772
842
  return parsedUrl.protocol === "http:" && LOCALHOST_HOSTS.has(parsedUrl.hostname);
773
- } catch (e4) {
843
+ } catch {
774
844
  return false;
775
845
  }
776
846
  }
@@ -804,8 +874,8 @@ function createLocalSpaceAnalyticsClient(config) {
804
874
  fingerprint,
805
875
  boundary: state.sample.boundary,
806
876
  count: sortedTimestamps.length,
807
- firstSeen: _nullishCoalesce(sortedTimestamps[0], () => ( Date.now())),
808
- lastSeen: _nullishCoalesce(sortedTimestamps[sortedTimestamps.length - 1], () => ( Date.now())),
877
+ firstSeen: sortedTimestamps[0] ?? Date.now(),
878
+ lastSeen: sortedTimestamps[sortedTimestamps.length - 1] ?? Date.now(),
809
879
  severity: state.sample.severity,
810
880
  sample: state.sample
811
881
  };
@@ -859,7 +929,7 @@ function createLocalSpaceAnalyticsClient(config) {
859
929
  report
860
930
  });
861
931
  } catch (error) {
862
- _optionalChain([resolvedConfig, 'access', _49 => _49.onError, 'optionalCall', _50 => _50(error)]);
932
+ resolvedConfig.onError?.(error);
863
933
  }
864
934
  };
865
935
  const getIssueReports = () => {
@@ -895,11 +965,11 @@ function createLocalSpaceAnalyticsClient(config) {
895
965
  if (!events.some((event) => event.kind === "error")) {
896
966
  return true;
897
967
  }
898
- _optionalChain([resolvedConfig, 'access', _51 => _51.onError, 'optionalCall', _52 => _52(
968
+ resolvedConfig.onError?.(
899
969
  new Error(
900
970
  `Error reporting requires an https or localhost endpoint. Refused endpoint: ${resolvedConfig.endpoint}`
901
971
  )
902
- )]);
972
+ );
903
973
  return false;
904
974
  };
905
975
  const flushWithBeacon = () => {
@@ -922,7 +992,7 @@ function createLocalSpaceAnalyticsClient(config) {
922
992
  persistQueue();
923
993
  }
924
994
  return sent;
925
- } catch (e5) {
995
+ } catch {
926
996
  return false;
927
997
  }
928
998
  };
@@ -954,7 +1024,7 @@ function createLocalSpaceAnalyticsClient(config) {
954
1024
  queue = queue.slice(events.length);
955
1025
  persistQueue();
956
1026
  } catch (error) {
957
- _optionalChain([resolvedConfig, 'access', _53 => _53.onError, 'optionalCall', _54 => _54(error)]);
1027
+ resolvedConfig.onError?.(error);
958
1028
  } finally {
959
1029
  isFlushing = false;
960
1030
  if (flushQueuedAfterCurrent) {
@@ -1014,7 +1084,7 @@ function createLocalSpaceAnalyticsClient(config) {
1014
1084
  if (isDestroyed || !resolvedConfig.enabled) {
1015
1085
  return;
1016
1086
  }
1017
- const eventChannel = _nullishCoalesce(event.channel, () => ( resolvedConfig.channel));
1087
+ const eventChannel = event.channel ?? resolvedConfig.channel;
1018
1088
  const requestId = typeof event.requestId === "string" && event.requestId.trim() ? event.requestId.trim() : void 0;
1019
1089
  const kind = event.kind === "error" ? "error" : "interaction";
1020
1090
  const normalizedError = kind === "error" && isErrorDetailsCandidate(event.error) ? normalizeStoredErrorDetails(event.error, resolvedConfig.errorReporting) : void 0;
@@ -1031,7 +1101,7 @@ function createLocalSpaceAnalyticsClient(config) {
1031
1101
  requestId,
1032
1102
  source: resolvedConfig.source,
1033
1103
  sessionId: resolvedConfig.sessionId,
1034
- timestamp: _nullishCoalesce(event.timestamp, () => ( Date.now())),
1104
+ timestamp: event.timestamp ?? Date.now(),
1035
1105
  context: createMergedContext(resolvedConfig, eventChannel, event.context),
1036
1106
  error: normalizedError
1037
1107
  };
@@ -1045,15 +1115,15 @@ function createLocalSpaceAnalyticsClient(config) {
1045
1115
  return;
1046
1116
  }
1047
1117
  if (resolvedConfig.errorReporting.secureEndpointOnly && resolvedConfig.endpoint && !isSecureEndpoint(resolvedConfig.endpoint)) {
1048
- _optionalChain([resolvedConfig, 'access', _55 => _55.onError, 'optionalCall', _56 => _56(
1118
+ resolvedConfig.onError?.(
1049
1119
  new Error(
1050
1120
  `Error reporting requires an https or localhost endpoint. Refused endpoint: ${resolvedConfig.endpoint}`
1051
1121
  )
1052
- )]);
1122
+ );
1053
1123
  return;
1054
1124
  }
1055
- const eventChannel = _nullishCoalesce(report.channel, () => ( resolvedConfig.channel));
1056
- const timestamp = _nullishCoalesce(report.timestamp, () => ( Date.now()));
1125
+ const eventChannel = report.channel ?? resolvedConfig.channel;
1126
+ const timestamp = report.timestamp ?? Date.now();
1057
1127
  const normalizedError = normalizeErrorReport(report, resolvedConfig.errorReporting);
1058
1128
  const {
1059
1129
  context: errorContext,
@@ -1111,7 +1181,7 @@ function createLocalSpaceAnalyticsClient(config) {
1111
1181
  {
1112
1182
  ...resolvedConfig,
1113
1183
  ...nextConfig,
1114
- source: _nullishCoalesce(nextConfig.source, () => ( resolvedConfig.source))
1184
+ source: nextConfig.source ?? resolvedConfig.source
1115
1185
  },
1116
1186
  resolvedConfig
1117
1187
  );
@@ -1148,14 +1218,14 @@ function createFrontendAnalyticsClient(config) {
1148
1218
  return createLocalSpaceAnalyticsClient({
1149
1219
  ...config,
1150
1220
  channel: "frontend",
1151
- runtime: _nullishCoalesce(config.runtime, () => ( "browser"))
1221
+ runtime: config.runtime ?? "browser"
1152
1222
  });
1153
1223
  }
1154
1224
  function createBackendAnalyticsClient(config) {
1155
1225
  return createLocalSpaceAnalyticsClient({
1156
1226
  ...config,
1157
1227
  channel: "backend",
1158
- runtime: _nullishCoalesce(config.runtime, () => ( "server"))
1228
+ runtime: config.runtime ?? "server"
1159
1229
  });
1160
1230
  }
1161
1231
  function createNoopLocalSpaceAnalyticsClient(source = "noop", channel = "frontend") {
@@ -1320,7 +1390,7 @@ var EVENT_DEFINITION_FIELDS = /* @__PURE__ */ new Set([
1320
1390
  var TARGET_FIELDS = /* @__PURE__ */ new Set(["type", "id"]);
1321
1391
  var CATALOG_OPTIONS_FIELDS = /* @__PURE__ */ new Set(["sources"]);
1322
1392
  var SemanticJourneyValidationError = class extends Error {
1323
-
1393
+ code;
1324
1394
  constructor(code) {
1325
1395
  super(
1326
1396
  code === "invalid-token" ? "Semantic journey token is invalid." : "Semantic journey input is invalid."
@@ -1535,7 +1605,7 @@ function defineSemanticJourneyCatalogUnsafe(definitions, options) {
1535
1605
  function defineSemanticJourneyCatalog(definitions, options) {
1536
1606
  try {
1537
1607
  return defineSemanticJourneyCatalogUnsafe(definitions, options);
1538
- } catch (e6) {
1608
+ } catch {
1539
1609
  return invalidDefinition();
1540
1610
  }
1541
1611
  }
@@ -1556,10 +1626,10 @@ function validateTarget(candidate, definition) {
1556
1626
  if (keys === null || keys.length !== 2 || !hasOnlyFields(keys, TARGET_FIELDS) || !isSemanticToken(candidate.type) || !isSemanticToken(candidate.id) || looksSensitive(candidate.type) || looksSensitive(candidate.id)) {
1557
1627
  return invalidInput();
1558
1628
  }
1559
- const allowedTarget = (_nullishCoalesce(definition.targets, () => ( []))).some(
1629
+ const allowedTarget = (definition.targets ?? []).some(
1560
1630
  (target) => target.type === candidate.type && target.id === candidate.id
1561
1631
  );
1562
- const allowedEffect = candidate.type === "effect" && (_nullishCoalesce(definition.effects, () => ( []))).includes(candidate.id);
1632
+ const allowedEffect = candidate.type === "effect" && (definition.effects ?? []).includes(candidate.id);
1563
1633
  if (!allowedTarget && !allowedEffect) {
1564
1634
  return invalidInput();
1565
1635
  }
@@ -1590,7 +1660,7 @@ function validateSemanticJourneyEventInputUnsafe(catalogue, input) {
1590
1660
  return invalidInput();
1591
1661
  }
1592
1662
  const target = input.target === void 0 ? void 0 : validateTarget(input.target, definition);
1593
- const candidateAttributes = _nullishCoalesce(input.attributes, () => ( {}));
1663
+ const candidateAttributes = input.attributes ?? {};
1594
1664
  if (!isRecord(candidateAttributes)) {
1595
1665
  return invalidInput();
1596
1666
  }
@@ -1598,7 +1668,7 @@ function validateSemanticJourneyEventInputUnsafe(catalogue, input) {
1598
1668
  if (attributeNames === null || attributeNames.length > MAX_EVENT_ATTRIBUTES) {
1599
1669
  return invalidInput();
1600
1670
  }
1601
- const registeredAttributes = _nullishCoalesce(definition.attributes, () => ( {}));
1671
+ const registeredAttributes = definition.attributes ?? {};
1602
1672
  for (const attributeName of attributeNames) {
1603
1673
  if (!Object.prototype.hasOwnProperty.call(registeredAttributes, attributeName)) {
1604
1674
  return invalidInput();
@@ -1670,7 +1740,7 @@ function createNonZeroIdentifier(byteLength2, randomBytes) {
1670
1740
  for (let attempt = 0; attempt < MAX_IDENTIFIER_ATTEMPTS; attempt += 1) {
1671
1741
  const identifier = createSecureRandomHex(
1672
1742
  byteLength2,
1673
- _nullishCoalesce(randomBytes, () => ( webCryptoRandomBytes))
1743
+ randomBytes ?? webCryptoRandomBytes
1674
1744
  );
1675
1745
  if (!/^0+$/.test(identifier)) {
1676
1746
  return identifier;
@@ -1817,12 +1887,12 @@ function addSafeCount(current, increment) {
1817
1887
  }
1818
1888
  return next;
1819
1889
  }
1820
- var SemanticJourneyAggregateStore = (_class = class {
1821
- __init() {this.counters = /* @__PURE__ */ new Map()}
1822
-
1823
- __init2() {this.dropped = 0}
1824
- __init3() {this.coalesced = 0}
1825
- constructor(options) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);
1890
+ var SemanticJourneyAggregateStore = class {
1891
+ counters = /* @__PURE__ */ new Map();
1892
+ options;
1893
+ dropped = 0;
1894
+ coalesced = 0;
1895
+ constructor(options) {
1826
1896
  if (!isSemanticSource(options.source) || !options.catalogue.sources.includes(options.source) || options.channel !== "frontend" && options.channel !== "backend" || options.runtime !== "browser" && options.runtime !== "server") {
1827
1897
  invalidAggregate();
1828
1898
  }
@@ -1838,7 +1908,7 @@ var SemanticJourneyAggregateStore = (_class = class {
1838
1908
  this.counters.set(key, Object.freeze({
1839
1909
  eventName,
1840
1910
  outcome,
1841
- count: addSafeCount(_nullishCoalesce(_optionalChain([existing, 'optionalAccess', _57 => _57.count]), () => ( 0)), count)
1911
+ count: addSafeCount(existing?.count ?? 0, count)
1842
1912
  }));
1843
1913
  }
1844
1914
  recordDropped(count = 1) {
@@ -1932,7 +2002,100 @@ var SemanticJourneyAggregateStore = (_class = class {
1932
2002
  return byName !== 0 ? byName : left.outcome.localeCompare(right.outcome);
1933
2003
  }));
1934
2004
  }
1935
- }, _class);
2005
+ };
2006
+
2007
+ // src/journey/metrics.ts
2008
+ var durationBuckets = [
2009
+ [100, "lt100ms"],
2010
+ [250, "lt250ms"],
2011
+ [500, "lt500ms"],
2012
+ [1e3, "lt1000ms"],
2013
+ [2500, "lt2500ms"],
2014
+ [5e3, "lt5000ms"],
2015
+ [1e4, "lt10000ms"],
2016
+ [Infinity, "gte10000ms"]
2017
+ ];
2018
+ var duration = (category) => ({
2019
+ category,
2020
+ outcome: "unknown",
2021
+ buckets: durationBuckets,
2022
+ maximum: 864e5
2023
+ });
2024
+ var metrics = /* @__PURE__ */ (() => ({
2025
+ "page.load": duration("presentation"),
2026
+ "route.ready": duration("presentation"),
2027
+ "world.ready": duration("presentation"),
2028
+ "request.duration": duration("request"),
2029
+ "vital.lcp": duration("presentation"),
2030
+ "vital.fcp": duration("presentation"),
2031
+ "vital.inp": duration("interaction"),
2032
+ "vital.ttfb": duration("request"),
2033
+ "vital.cls": {
2034
+ category: "presentation",
2035
+ outcome: "unknown",
2036
+ maximum: 100,
2037
+ buckets: [[0.1, "lt01"], [0.25, "lt025"], [Infinity, "gte025"]]
2038
+ },
2039
+ "episode.active-duration": {
2040
+ category: "state",
2041
+ outcome: "unknown",
2042
+ maximum: 864e5,
2043
+ buckets: [
2044
+ [1e4, "lt10s"],
2045
+ [6e4, "lt60s"],
2046
+ [3e5, "lt300s"],
2047
+ [9e5, "lt900s"],
2048
+ [36e5, "lt3600s"],
2049
+ [Infinity, "gte3600s"]
2050
+ ]
2051
+ },
2052
+ "episode.started": { category: "state", outcome: "unknown" },
2053
+ "episode.completed": { category: "state", outcome: "unknown" },
2054
+ "request.started": { category: "request", outcome: "unknown" },
2055
+ "request.completed": { category: "request", outcome: "success" },
2056
+ "request.failed": { category: "request", outcome: "failure" },
2057
+ "request.cancelled": { category: "request", outcome: "cancelled" },
2058
+ "request.rejected": { category: "request", outcome: "denied" },
2059
+ "error.runtime": { category: "error", outcome: "failure" },
2060
+ "error.resource": { category: "error", outcome: "failure" },
2061
+ "error.render": { category: "error", outcome: "failure" },
2062
+ "error.unhandled": { category: "error", outcome: "failure" }
2063
+ }))();
2064
+ var USEFUL_METRIC_EVENT_DEFINITIONS = /* @__PURE__ */ (() => Object.freeze(Object.fromEntries(Object.entries(metrics).flatMap(([metric, definition]) => {
2065
+ const names = definition.buckets ? definition.buckets.map(([, bucket]) => `metric.${metric}.${bucket}`) : [`metric.${metric}`];
2066
+ return names.map((name) => [name, Object.freeze({ category: definition.category })]);
2067
+ }))))();
2068
+ function projectUsefulMetric(input) {
2069
+ try {
2070
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return null;
2071
+ const prototype = Object.getPrototypeOf(input);
2072
+ if (prototype !== Object.prototype && prototype !== null) return null;
2073
+ const keys = Reflect.ownKeys(input);
2074
+ if (keys.length < 1 || keys.length > 2 || keys.some((key) => key !== "metric" && key !== "value")) return null;
2075
+ const descriptors = Object.getOwnPropertyDescriptors(input);
2076
+ const metric = descriptors.metric;
2077
+ if (!metric || !("value" in metric) || typeof metric.value !== "string" || !Object.hasOwn(metrics, metric.value)) return null;
2078
+ const definition = metrics[metric.value];
2079
+ let name = `metric.${metric.value}`;
2080
+ if (definition.buckets) {
2081
+ const value = descriptors.value;
2082
+ if (keys.length !== 2 || !value || !("value" in value) || typeof value.value !== "number" || !Number.isFinite(value.value) || value.value < 0 || value.value > definition.maximum) return null;
2083
+ const bucket = definition.buckets.find(([upper]) => value.value < upper);
2084
+ name += `.${bucket[1]}`;
2085
+ } else if (keys.length !== 1) {
2086
+ return null;
2087
+ }
2088
+ return Object.freeze({
2089
+ name,
2090
+ category: definition.category,
2091
+ phase: metric.value.endsWith(".started") ? "start" : "end",
2092
+ outcome: definition.outcome,
2093
+ modality: "system"
2094
+ });
2095
+ } catch {
2096
+ return null;
2097
+ }
2098
+ }
1936
2099
 
1937
2100
  // src/journey/transport.ts
1938
2101
  var SemanticJourneyTransportError = class extends Error {
@@ -1944,10 +2107,10 @@ var SemanticJourneyTransportError = class extends Error {
1944
2107
  this.retryAfterMs = retryAfterMs;
1945
2108
  this.name = "SemanticJourneyTransportError";
1946
2109
  }
1947
-
1948
-
1949
-
1950
-
2110
+ code;
2111
+ retryable;
2112
+ status;
2113
+ retryAfterMs;
1951
2114
  };
1952
2115
  var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
1953
2116
  var MAX_RETRY_AFTER_MS = 5 * 60 * 1e3;
@@ -1956,7 +2119,7 @@ function resolveBaseUrl(explicitBaseUrl) {
1956
2119
  if (explicitBaseUrl) {
1957
2120
  return explicitBaseUrl;
1958
2121
  }
1959
- if (typeof window !== "undefined" && _optionalChain([window, 'access', _58 => _58.location, 'optionalAccess', _59 => _59.origin])) {
2122
+ if (typeof window !== "undefined" && window.location?.origin) {
1960
2123
  return window.location.origin;
1961
2124
  }
1962
2125
  return void 0;
@@ -1981,7 +2144,7 @@ function isSecureSemanticJourneyEndpoint(endpoint, baseUrl) {
1981
2144
  return true;
1982
2145
  }
1983
2146
  return parsed.protocol === "http:" && LOCAL_HOSTS.has(parsed.hostname);
1984
- } catch (e7) {
2147
+ } catch {
1985
2148
  return false;
1986
2149
  }
1987
2150
  }
@@ -2007,8 +2170,8 @@ function isRetryableStatus(status) {
2007
2170
  return status === 408 || status === 425 || status === 429 || status >= 500;
2008
2171
  }
2009
2172
  function createDefaultSemanticJourneyAggregateTransport(options = {}) {
2010
- const fetchImplementation = _nullishCoalesce(options.fetch, () => ( globalThis.fetch));
2011
- const now = _nullishCoalesce(options.now, () => ( (() => Date.now())));
2173
+ const fetchImplementation = options.fetch ?? globalThis.fetch;
2174
+ const now = options.now ?? (() => Date.now());
2012
2175
  return async (request) => {
2013
2176
  if (!isSecureSemanticJourneyEndpoint(request.endpoint, options.baseUrl)) {
2014
2177
  throw new SemanticJourneyTransportError("rejected", false);
@@ -2024,7 +2187,7 @@ function createDefaultSemanticJourneyAggregateTransport(options = {}) {
2024
2187
  }
2025
2188
  try {
2026
2189
  resolvedEndpoint = new URL(request.endpoint, base).toString();
2027
- } catch (e8) {
2190
+ } catch {
2028
2191
  throw new SemanticJourneyTransportError("rejected", false);
2029
2192
  }
2030
2193
  }
@@ -2034,13 +2197,13 @@ function createDefaultSemanticJourneyAggregateTransport(options = {}) {
2034
2197
  method: "POST",
2035
2198
  body: request.body,
2036
2199
  headers: request.headers,
2037
- keepalive: _nullishCoalesce(request.keepalive, () => ( false)),
2200
+ keepalive: request.keepalive ?? false,
2038
2201
  signal: request.signal,
2039
2202
  credentials: "omit",
2040
2203
  referrerPolicy: "no-referrer",
2041
2204
  redirect: "error"
2042
2205
  });
2043
- } catch (e9) {
2206
+ } catch {
2044
2207
  if (request.signal.aborted) {
2045
2208
  throw new SemanticJourneyTransportError("aborted", true);
2046
2209
  }
@@ -2101,7 +2264,7 @@ function isValidReceipt(value, catalogue) {
2101
2264
  }
2102
2265
  const receipt = value;
2103
2266
  const definition = isJourneyToken(receipt.name) ? getJourneyEventDefinition(catalogue, receipt.name) : void 0;
2104
- return receipt.version === SEMANTIC_JOURNEY_RECEIPT_VERSION && definition !== void 0 && isReceiptOutcome(receipt.outcome) && isReceiptPhase(receipt.phase) && isJourneyToken(receipt.effect) && (_nullishCoalesce(definition.effects, () => ( []))).includes(receipt.effect);
2267
+ return receipt.version === SEMANTIC_JOURNEY_RECEIPT_VERSION && definition !== void 0 && isReceiptOutcome(receipt.outcome) && isReceiptPhase(receipt.phase) && isJourneyToken(receipt.effect) && (definition.effects ?? []).includes(receipt.effect);
2105
2268
  }
2106
2269
  function serializeReceipt(receipt) {
2107
2270
  return `version=${receipt.version};name=${receipt.name};outcome=${receipt.outcome};phase=${receipt.phase};effect=${receipt.effect}`;
@@ -2119,11 +2282,11 @@ function parseReceipt(encoded, catalogue) {
2119
2282
  if (fields.length !== RECEIPT_FIELDS.length) {
2120
2283
  return void 0;
2121
2284
  }
2122
- const version = parseCanonicalField(_nullishCoalesce(fields[0], () => ( "")), "version");
2123
- const name = parseCanonicalField(_nullishCoalesce(fields[1], () => ( "")), "name");
2124
- const outcome = parseCanonicalField(_nullishCoalesce(fields[2], () => ( "")), "outcome");
2125
- const phase = parseCanonicalField(_nullishCoalesce(fields[3], () => ( "")), "phase");
2126
- const effect = parseCanonicalField(_nullishCoalesce(fields[4], () => ( "")), "effect");
2285
+ const version = parseCanonicalField(fields[0] ?? "", "version");
2286
+ const name = parseCanonicalField(fields[1] ?? "", "name");
2287
+ const outcome = parseCanonicalField(fields[2] ?? "", "outcome");
2288
+ const phase = parseCanonicalField(fields[3] ?? "", "phase");
2289
+ const effect = parseCanonicalField(fields[4] ?? "", "effect");
2127
2290
  const candidate = { version, name, outcome, phase, effect };
2128
2291
  return isValidReceipt(candidate, catalogue) ? candidate : void 0;
2129
2292
  }
@@ -2137,7 +2300,7 @@ function serializeSemanticJourneyReceipts(receipts, catalogue) {
2137
2300
  throw new Error(SERIALIZE_ERROR_MESSAGE);
2138
2301
  }
2139
2302
  return header;
2140
- } catch (e10) {
2303
+ } catch {
2141
2304
  throw new Error(SERIALIZE_ERROR_MESSAGE);
2142
2305
  }
2143
2306
  }
@@ -2162,7 +2325,7 @@ function parseSemanticJourneyReceipts(header, catalogue) {
2162
2325
  receipts.push(receipt);
2163
2326
  }
2164
2327
  return receipts;
2165
- } catch (e11) {
2328
+ } catch {
2166
2329
  return [];
2167
2330
  }
2168
2331
  }
@@ -2253,7 +2416,7 @@ function compareTokens(left, right) {
2253
2416
  return 0;
2254
2417
  }
2255
2418
  function compareOptionalTokens(left, right) {
2256
- return compareTokens(_nullishCoalesce(left, () => ( "")), _nullishCoalesce(right, () => ( "")));
2419
+ return compareTokens(left ?? "", right ?? "");
2257
2420
  }
2258
2421
  function compareEventsForOrder(left, right) {
2259
2422
  const timestampComparison = left.occurredAtEpochMs - right.occurredAtEpochMs;
@@ -2294,11 +2457,11 @@ function compareEvidence(left, right) {
2294
2457
  compareOptionalTokens(left.spanId, right.spanId),
2295
2458
  compareOptionalTokens(left.producerId, right.producerId),
2296
2459
  compareTokens(
2297
- _nullishCoalesce(_optionalChain([left, 'access', _60 => _60.eventIds, 'optionalAccess', _61 => _61.join, 'call', _62 => _62(":")]), () => ( "")),
2298
- _nullishCoalesce(_optionalChain([right, 'access', _63 => _63.eventIds, 'optionalAccess', _64 => _64.join, 'call', _65 => _65(":")]), () => ( ""))
2460
+ left.eventIds?.join(":") ?? "",
2461
+ right.eventIds?.join(":") ?? ""
2299
2462
  )
2300
2463
  ];
2301
- const tokenComparison = _nullishCoalesce(tokenComparisons.find((comparison) => comparison !== 0), () => ( 0));
2464
+ const tokenComparison = tokenComparisons.find((comparison) => comparison !== 0) ?? 0;
2302
2465
  if (tokenComparison !== 0) {
2303
2466
  return tokenComparison;
2304
2467
  }
@@ -2309,7 +2472,7 @@ function compareEvidence(left, right) {
2309
2472
  "observedCount"
2310
2473
  ];
2311
2474
  for (const field2 of numericFields) {
2312
- const comparison = (_nullishCoalesce(left[field2], () => ( -1))) - (_nullishCoalesce(right[field2], () => ( -1)));
2475
+ const comparison = (left[field2] ?? -1) - (right[field2] ?? -1);
2313
2476
  if (comparison !== 0) {
2314
2477
  return comparison;
2315
2478
  }
@@ -2487,7 +2650,7 @@ function attributesEqual(left, right) {
2487
2650
  );
2488
2651
  }
2489
2652
  function eventsEqual(left, right) {
2490
- return left.schemaVersion === right.schemaVersion && left.eventId === right.eventId && left.journeyId === right.journeyId && left.traceId === right.traceId && left.spanId === right.spanId && left.parentSpanId === right.parentSpanId && left.causedByEventId === right.causedByEventId && left.producerId === right.producerId && left.producerSequence === right.producerSequence && left.occurredAtEpochMs === right.occurredAtEpochMs && left.source === right.source && left.channel === right.channel && left.runtime === right.runtime && left.name === right.name && left.category === right.category && left.phase === right.phase && left.outcome === right.outcome && left.modality === right.modality && _optionalChain([left, 'access', _66 => _66.target, 'optionalAccess', _67 => _67.type]) === _optionalChain([right, 'access', _68 => _68.target, 'optionalAccess', _69 => _69.type]) && _optionalChain([left, 'access', _70 => _70.target, 'optionalAccess', _71 => _71.id]) === _optionalChain([right, 'access', _72 => _72.target, 'optionalAccess', _73 => _73.id]) && left.privacy.mode === right.privacy.mode && left.privacy.policyVersion === right.privacy.policyVersion && left.privacy.droppedAttributeCount === right.privacy.droppedAttributeCount && attributesEqual(left.attributes, right.attributes);
2653
+ return left.schemaVersion === right.schemaVersion && left.eventId === right.eventId && left.journeyId === right.journeyId && left.traceId === right.traceId && left.spanId === right.spanId && left.parentSpanId === right.parentSpanId && left.causedByEventId === right.causedByEventId && left.producerId === right.producerId && left.producerSequence === right.producerSequence && left.occurredAtEpochMs === right.occurredAtEpochMs && left.source === right.source && left.channel === right.channel && left.runtime === right.runtime && left.name === right.name && left.category === right.category && left.phase === right.phase && left.outcome === right.outcome && left.modality === right.modality && left.target?.type === right.target?.type && left.target?.id === right.target?.id && left.privacy.mode === right.privacy.mode && left.privacy.policyVersion === right.privacy.policyVersion && left.privacy.droppedAttributeCount === right.privacy.droppedAttributeCount && attributesEqual(left.attributes, right.attributes);
2491
2654
  }
2492
2655
  function deduplicateEvents(events) {
2493
2656
  const byEventId = /* @__PURE__ */ new Map();
@@ -2496,7 +2659,7 @@ function deduplicateEvents(events) {
2496
2659
  if (existing && !eventsEqual(existing, event)) {
2497
2660
  return invalidRuntimeEvidence();
2498
2661
  }
2499
- byEventId.set(event.eventId, _nullishCoalesce(existing, () => ( event)));
2662
+ byEventId.set(event.eventId, existing ?? event);
2500
2663
  }
2501
2664
  return [...byEventId.values()].sort(compareEventsForOrder);
2502
2665
  }
@@ -2529,7 +2692,7 @@ function buildReferenceEdges(nodes, nodesByEventId, reconstructionEvidence, limi
2529
2692
  spans = /* @__PURE__ */ new Map();
2530
2693
  spansByTrace.set(node.event.traceId, spans);
2531
2694
  }
2532
- const spanNodes = _nullishCoalesce(spans.get(node.event.spanId), () => ( []));
2695
+ const spanNodes = spans.get(node.event.spanId) ?? [];
2533
2696
  addBoundedNode(spanNodes, node);
2534
2697
  spans.set(node.event.spanId, spanNodes);
2535
2698
  }
@@ -2556,7 +2719,7 @@ function buildReferenceEdges(nodes, nodesByEventId, reconstructionEvidence, limi
2556
2719
  addEdge(node, node, limits);
2557
2720
  continue;
2558
2721
  }
2559
- const parentCandidates = _optionalChain([spansByTrace, 'access', _74 => _74.get, 'call', _75 => _75(event.traceId), 'optionalAccess', _76 => _76.get, 'call', _77 => _77(event.parentSpanId)]);
2722
+ const parentCandidates = spansByTrace.get(event.traceId)?.get(event.parentSpanId);
2560
2723
  if (!parentCandidates || parentCandidates.length === 0) {
2561
2724
  appendEvidence(
2562
2725
  reconstructionEvidence,
@@ -2587,7 +2750,7 @@ function buildProducerEdges(nodes, reconstructionEvidence, limits) {
2587
2750
  sequences = /* @__PURE__ */ new Map();
2588
2751
  producers.set(node.event.producerId, sequences);
2589
2752
  }
2590
- const sequenceNodes = _nullishCoalesce(sequences.get(node.event.producerSequence), () => ( []));
2753
+ const sequenceNodes = sequences.get(node.event.producerSequence) ?? [];
2591
2754
  addBoundedNode(sequenceNodes, node);
2592
2755
  sequences.set(node.event.producerSequence, sequenceNodes);
2593
2756
  }
@@ -2598,7 +2761,7 @@ function buildProducerEdges(nodes, reconstructionEvidence, limits) {
2598
2761
  const sequenceEntries = [...sequences.entries()].sort(
2599
2762
  ([left], [right]) => left - right
2600
2763
  );
2601
- const firstSequence = _optionalChain([sequenceEntries, 'access', _78 => _78[0], 'optionalAccess', _79 => _79[0]]);
2764
+ const firstSequence = sequenceEntries[0]?.[0];
2602
2765
  if (firstSequence !== void 0 && firstSequence > 1) {
2603
2766
  appendEvidence(
2604
2767
  reconstructionEvidence,
@@ -2681,7 +2844,7 @@ function stronglyConnectedComponents(nodes, nodesByEventId) {
2681
2844
  const stack = [
2682
2845
  {
2683
2846
  node: root,
2684
- adjacent: _nullishCoalesce(successors.get(root.event.eventId), () => ( [])),
2847
+ adjacent: successors.get(root.event.eventId) ?? [],
2685
2848
  next: 0
2686
2849
  }
2687
2850
  ];
@@ -2697,7 +2860,7 @@ function stronglyConnectedComponents(nodes, nodesByEventId) {
2697
2860
  visited.add(next.event.eventId);
2698
2861
  stack.push({
2699
2862
  node: next,
2700
- adjacent: _nullishCoalesce(successors.get(next.event.eventId), () => ( [])),
2863
+ adjacent: successors.get(next.event.eventId) ?? [],
2701
2864
  next: 0
2702
2865
  });
2703
2866
  }
@@ -2723,7 +2886,7 @@ function stronglyConnectedComponents(nodes, nodesByEventId) {
2723
2886
  return invalidRuntimeEvidence();
2724
2887
  }
2725
2888
  members.push(current);
2726
- const adjacentNodes = _nullishCoalesce(predecessors.get(current.event.eventId), () => ( []));
2889
+ const adjacentNodes = predecessors.get(current.event.eventId) ?? [];
2727
2890
  for (let adjacentIndex = adjacentNodes.length - 1; adjacentIndex >= 0; adjacentIndex -= 1) {
2728
2891
  const predecessor = adjacentNodes[adjacentIndex];
2729
2892
  if (predecessor && !assigned.has(predecessor.event.eventId)) {
@@ -2757,8 +2920,8 @@ function stronglyConnectedComponents(nodes, nodesByEventId) {
2757
2920
  return invalidRuntimeEvidence();
2758
2921
  }
2759
2922
  if (fromIndex !== toIndex) {
2760
- _optionalChain([components, 'access', _80 => _80[fromIndex], 'optionalAccess', _81 => _81.successors, 'access', _82 => _82.add, 'call', _83 => _83(toIndex)]);
2761
- _optionalChain([components, 'access', _84 => _84[toIndex], 'optionalAccess', _85 => _85.predecessors, 'access', _86 => _86.add, 'call', _87 => _87(fromIndex)]);
2923
+ components[fromIndex]?.successors.add(toIndex);
2924
+ components[toIndex]?.predecessors.add(fromIndex);
2762
2925
  }
2763
2926
  }
2764
2927
  }
@@ -2789,7 +2952,7 @@ function condensedCausalOrder(components) {
2789
2952
  ordered.push(...current.nodes);
2790
2953
  const successors = [...current.successors].map((index) => components[index]).filter((component) => component !== void 0).sort(compareComponents);
2791
2954
  for (const successor of successors) {
2792
- const remaining = (_nullishCoalesce(indegrees.get(successor.index), () => ( 0))) - 1;
2955
+ const remaining = (indegrees.get(successor.index) ?? 0) - 1;
2793
2956
  indegrees.set(successor.index, remaining);
2794
2957
  if (remaining === 0) {
2795
2958
  ready.push(successor);
@@ -2919,7 +3082,7 @@ function reconstructSemanticJourneyUnsafe(catalogue, events) {
2919
3082
  addCycleEvidence(components, reconstructionEvidence);
2920
3083
  const ordered = condensedCausalOrder(components);
2921
3084
  reconstructionEvidence.sort(compareEvidence);
2922
- const journeyId = _optionalChain([normalized, 'access', _88 => _88[0], 'optionalAccess', _89 => _89.journeyId]);
3085
+ const journeyId = normalized[0]?.journeyId;
2923
3086
  if (!journeyId) {
2924
3087
  return invalidRuntimeEvidence();
2925
3088
  }
@@ -3007,7 +3170,7 @@ function observeSemanticJourneyInteractions(config) {
3007
3170
  if (config.enabled !== true) {
3008
3171
  return () => void 0;
3009
3172
  }
3010
- const root = _nullishCoalesce(config.root, () => ( (typeof document === "undefined" ? void 0 : document)));
3173
+ const root = config.root ?? (typeof document === "undefined" ? void 0 : document);
3011
3174
  if (!root) {
3012
3175
  return () => void 0;
3013
3176
  }
@@ -3040,7 +3203,7 @@ function observeSemanticJourneyInteractions(config) {
3040
3203
  try {
3041
3204
  validateSemanticJourneyEventInput(config.catalogue, input);
3042
3205
  config.onEvent(input);
3043
- } catch (e12) {
3206
+ } catch {
3044
3207
  }
3045
3208
  };
3046
3209
  for (const eventType of OBSERVED_EVENT_TYPES) {
@@ -3088,7 +3251,7 @@ function invalidConfig() {
3088
3251
  throw new Error("Semantic journey client configuration is invalid.");
3089
3252
  }
3090
3253
  function resolveInteger(value, fallback, minimum, maximum) {
3091
- const resolved = _nullishCoalesce(value, () => ( fallback));
3254
+ const resolved = value ?? fallback;
3092
3255
  if (!Number.isSafeInteger(resolved) || resolved < minimum || resolved > maximum) {
3093
3256
  return invalidConfig();
3094
3257
  }
@@ -3101,7 +3264,7 @@ function resolveRuntime2(runtime) {
3101
3264
  return typeof window === "undefined" ? "server" : "browser";
3102
3265
  }
3103
3266
  function resolveChannel2(channel, runtime) {
3104
- return _nullishCoalesce(channel, () => ( (runtime === "server" ? "backend" : "frontend")));
3267
+ return channel ?? (runtime === "server" ? "backend" : "frontend");
3105
3268
  }
3106
3269
  function defaultRetryDelay(delayMs, signal) {
3107
3270
  if (signal.aborted) {
@@ -3150,13 +3313,13 @@ function resolveConfig2(config) {
3150
3313
  source: config.source,
3151
3314
  channel: resolveChannel2(config.channel, runtime),
3152
3315
  runtime,
3153
- enabled: _nullishCoalesce(config.enabled, () => ( false)),
3316
+ enabled: config.enabled ?? false,
3154
3317
  ...config.aggregateEndpoint ? { aggregateEndpoint: config.aggregateEndpoint } : {},
3155
- aggregateTransport: _nullishCoalesce(config.aggregateTransport, () => ( createDefaultSemanticJourneyAggregateTransport({
3318
+ aggregateTransport: config.aggregateTransport ?? createDefaultSemanticJourneyAggregateTransport({
3156
3319
  ...config.aggregateBaseUrl ? { baseUrl: config.aggregateBaseUrl } : {},
3157
3320
  ...config.now ? { now: config.now } : {}
3158
- }))),
3159
- autoFlush: _nullishCoalesce(config.autoFlush, () => ( true)),
3321
+ }),
3322
+ autoFlush: config.autoFlush ?? true,
3160
3323
  aggregateFlushIntervalMs: resolveInteger(
3161
3324
  config.aggregateFlushIntervalMs,
3162
3325
  DEFAULT_AGGREGATE_FLUSH_INTERVAL_MS,
@@ -3226,8 +3389,8 @@ function resolveConfig2(config) {
3226
3389
  retryBaseDelayMs,
3227
3390
  retryMaxDelayMs,
3228
3391
  ...config.randomBytes ? { randomBytes: config.randomBytes } : {},
3229
- now: _nullishCoalesce(config.now, () => ( (() => Date.now()))),
3230
- retryDelay: _nullishCoalesce(config.retryDelay, () => ( defaultRetryDelay)),
3392
+ now: config.now ?? (() => Date.now()),
3393
+ retryDelay: config.retryDelay ?? defaultRetryDelay,
3231
3394
  ...config.onDrop ? { onDrop: config.onDrop } : {}
3232
3395
  };
3233
3396
  }
@@ -3243,7 +3406,7 @@ function eventBytes(event) {
3243
3406
  return textEncoder2.encode(JSON.stringify(event)).byteLength;
3244
3407
  }
3245
3408
  function sameTarget(left, right) {
3246
- return _optionalChain([left, 'optionalAccess', _90 => _90.type]) === _optionalChain([right, 'optionalAccess', _91 => _91.type]) && _optionalChain([left, 'optionalAccess', _92 => _92.id]) === _optionalChain([right, 'optionalAccess', _93 => _93.id]);
3409
+ return left?.type === right?.type && left?.id === right?.id;
3247
3410
  }
3248
3411
  function shouldCoalesce(previous, next, windowMs) {
3249
3412
  return Boolean(
@@ -3259,7 +3422,7 @@ function jitteredDelay(attempt, config) {
3259
3422
  if (!(bytes instanceof Uint8Array) || bytes.byteLength !== 2) {
3260
3423
  throw new Error("Semantic journey retry random source is invalid.");
3261
3424
  }
3262
- const sample = (_nullishCoalesce(bytes[0], () => ( 0))) << 8 | (_nullishCoalesce(bytes[1], () => ( 0)));
3425
+ const sample = (bytes[0] ?? 0) << 8 | (bytes[1] ?? 0);
3263
3426
  const factor = 0.5 + sample / 65535;
3264
3427
  return Math.min(config.retryMaxDelayMs, Math.max(1, Math.round(exponential * factor)));
3265
3428
  }
@@ -3267,7 +3430,7 @@ function createSemanticJourneyClient(inputConfig) {
3267
3430
  let config;
3268
3431
  try {
3269
3432
  config = resolveConfig2(inputConfig);
3270
- } catch (e13) {
3433
+ } catch {
3271
3434
  return invalidConfig();
3272
3435
  }
3273
3436
  const aggregateStore = new SemanticJourneyAggregateStore({
@@ -3289,8 +3452,8 @@ function createSemanticJourneyClient(inputConfig) {
3289
3452
  let interval;
3290
3453
  const notifyDrop = (reason) => {
3291
3454
  try {
3292
- _optionalChain([config, 'access', _94 => _94.onDrop, 'optionalCall', _95 => _95(reason)]);
3293
- } catch (e14) {
3455
+ config.onDrop?.(reason);
3456
+ } catch {
3294
3457
  }
3295
3458
  };
3296
3459
  const newEpisode = (nowEpochMs) => ({
@@ -3341,7 +3504,7 @@ function createSemanticJourneyClient(inputConfig) {
3341
3504
  }
3342
3505
  const usesLocalProducer = options.producerId === void 0;
3343
3506
  const producerSequence = usesLocalProducer ? currentEpisode.producerSequence + 1 : options.producerSequence;
3344
- if (!Number.isSafeInteger(producerSequence) || (_nullishCoalesce(producerSequence, () => ( 0))) < 1) {
3507
+ if (!Number.isSafeInteger(producerSequence) || (producerSequence ?? 0) < 1) {
3345
3508
  notifyDrop("invalid");
3346
3509
  return void 0;
3347
3510
  }
@@ -3353,12 +3516,12 @@ function createSemanticJourneyClient(inputConfig) {
3353
3516
  spanId: options.context.spanId,
3354
3517
  ...options.context.parentSpanId ? { parentSpanId: options.context.parentSpanId } : {},
3355
3518
  ...options.causedByEventId ? { causedByEventId: options.causedByEventId } : {},
3356
- producerId: _nullishCoalesce(options.producerId, () => ( currentEpisode.producerId)),
3519
+ producerId: options.producerId ?? currentEpisode.producerId,
3357
3520
  producerSequence,
3358
3521
  occurredAtEpochMs: nowEpochMs,
3359
- source: _nullishCoalesce(options.source, () => ( config.source)),
3360
- channel: _nullishCoalesce(options.channel, () => ( config.channel)),
3361
- runtime: _nullishCoalesce(options.runtime, () => ( config.runtime)),
3522
+ source: options.source ?? config.source,
3523
+ channel: options.channel ?? config.channel,
3524
+ runtime: options.runtime ?? config.runtime,
3362
3525
  name: validated.name,
3363
3526
  category: validated.category,
3364
3527
  phase: validated.phase,
@@ -3374,7 +3537,7 @@ function createSemanticJourneyClient(inputConfig) {
3374
3537
  });
3375
3538
  aggregateStore.record(event.name, event.outcome);
3376
3539
  if (shouldCoalesce(
3377
- _optionalChain([queue, 'access', _96 => _96[queue.length - 1], 'optionalAccess', _97 => _97.event]),
3540
+ queue[queue.length - 1]?.event,
3378
3541
  event,
3379
3542
  config.coalesceWindowMs
3380
3543
  )) {
@@ -3401,7 +3564,7 @@ function createSemanticJourneyClient(inputConfig) {
3401
3564
  const validateInput = (input) => {
3402
3565
  try {
3403
3566
  return validateSemanticJourneyEventInput(config.catalogue, input);
3404
- } catch (e15) {
3567
+ } catch {
3405
3568
  notifyDrop("invalid");
3406
3569
  return void 0;
3407
3570
  }
@@ -3416,7 +3579,7 @@ function createSemanticJourneyClient(inputConfig) {
3416
3579
  const causeContext = causedByEventId ? contextByEventId.get(causedByEventId) : void 0;
3417
3580
  if (request) {
3418
3581
  return createRequestJourneyContext(
3419
- _nullishCoalesce(causeContext, () => ( currentEpisode.root)),
3582
+ causeContext ?? currentEpisode.root,
3420
3583
  config.randomBytes
3421
3584
  );
3422
3585
  }
@@ -3454,7 +3617,7 @@ function createSemanticJourneyClient(inputConfig) {
3454
3617
  },
3455
3618
  nowEpochMs
3456
3619
  );
3457
- } catch (e16) {
3620
+ } catch {
3458
3621
  notifyDrop("invalid");
3459
3622
  return void 0;
3460
3623
  }
@@ -3564,13 +3727,13 @@ function createSemanticJourneyClient(inputConfig) {
3564
3727
  added.push(consequence);
3565
3728
  }
3566
3729
  return added;
3567
- } catch (e17) {
3730
+ } catch {
3568
3731
  notifyDrop("invalid");
3569
3732
  return [];
3570
3733
  }
3571
3734
  }
3572
3735
  });
3573
- } catch (e18) {
3736
+ } catch {
3574
3737
  notifyDrop("invalid");
3575
3738
  return void 0;
3576
3739
  }
@@ -3645,11 +3808,11 @@ function createSemanticJourneyClient(inputConfig) {
3645
3808
  if (attempt >= config.maxRetries) {
3646
3809
  return "retained";
3647
3810
  }
3648
- const retryAfterMs = _optionalChain([transportError, 'optionalAccess', _98 => _98.retryAfterMs]);
3811
+ const retryAfterMs = transportError?.retryAfterMs;
3649
3812
  const delayMs = retryAfterMs === void 0 ? jitteredDelay(attempt, config) : Math.min(config.retryMaxDelayMs, Math.max(0, retryAfterMs));
3650
3813
  try {
3651
3814
  await config.retryDelay(delayMs, signal);
3652
- } catch (e19) {
3815
+ } catch {
3653
3816
  return "retained";
3654
3817
  }
3655
3818
  }
@@ -3663,12 +3826,12 @@ function createSemanticJourneyClient(inputConfig) {
3663
3826
  const generation = aggregateGeneration;
3664
3827
  const signal = aggregateController.signal;
3665
3828
  for (let sentBatchCount = 0; sentBatchCount < config.maxBatchesPerFlush; sentBatchCount += 1) {
3666
- const batch = _nullishCoalesce(pendingBatch, () => ( aggregateStore.createBatch({
3829
+ const batch = pendingBatch ?? aggregateStore.createBatch({
3667
3830
  batchId: createEventId(config.randomBytes),
3668
3831
  nowEpochMs: config.now(),
3669
3832
  maxCounters: config.aggregateMaxCounters,
3670
3833
  maxBytes: config.aggregateMaxBytes
3671
- })));
3834
+ });
3672
3835
  if (!batch) {
3673
3836
  return;
3674
3837
  }
@@ -3701,7 +3864,7 @@ function createSemanticJourneyClient(inputConfig) {
3701
3864
  try {
3702
3865
  pruneExpired(config.now());
3703
3866
  return queue.map(({ event }) => copyEvent(event));
3704
- } catch (e20) {
3867
+ } catch {
3705
3868
  return [];
3706
3869
  }
3707
3870
  };
@@ -3719,7 +3882,7 @@ function createSemanticJourneyClient(inputConfig) {
3719
3882
  aggregateGeneration += 1;
3720
3883
  aggregateController.abort();
3721
3884
  aggregateController = new AbortController();
3722
- _optionalChain([activeTransportController, 'optionalAccess', _99 => _99.abort, 'call', _100 => _100()]);
3885
+ activeTransportController?.abort();
3723
3886
  pendingBatch = void 0;
3724
3887
  clearLocalQueue();
3725
3888
  aggregateStore.clear();
@@ -3755,7 +3918,7 @@ function createSemanticJourneyClient(inputConfig) {
3755
3918
  destroyed = true;
3756
3919
  aggregateGeneration += 1;
3757
3920
  aggregateController.abort();
3758
- _optionalChain([activeTransportController, 'optionalAccess', _101 => _101.abort, 'call', _102 => _102()]);
3921
+ activeTransportController?.abort();
3759
3922
  pendingBatch = void 0;
3760
3923
  if (interval !== void 0) {
3761
3924
  globalThis.clearInterval(interval);
@@ -3787,9 +3950,9 @@ function createSemanticJourneyClient(inputConfig) {
3787
3950
  }
3788
3951
 
3789
3952
  // src/react/provider.tsx
3790
- var _react = require('react');
3791
- var _jsxruntime = require('react/jsx-runtime');
3792
- var AnalyticsContext = _react.createContext.call(void 0, null);
3953
+ var import_react = require("react");
3954
+ var import_jsx_runtime = require("react/jsx-runtime");
3955
+ var AnalyticsContext = (0, import_react.createContext)(null);
3793
3956
  function AnalyticsProvider({
3794
3957
  children,
3795
3958
  source = "react-app",
@@ -3809,7 +3972,7 @@ function AnalyticsProvider({
3809
3972
  onError,
3810
3973
  client
3811
3974
  }) {
3812
- const managedClient = _react.useMemo.call(void 0, () => {
3975
+ const managedClient = (0, import_react.useMemo)(() => {
3813
3976
  if (client) {
3814
3977
  return client;
3815
3978
  }
@@ -3851,14 +4014,14 @@ function AnalyticsProvider({
3851
4014
  transport,
3852
4015
  onError
3853
4016
  ]);
3854
- _react.useEffect.call(void 0, () => {
4017
+ (0, import_react.useEffect)(() => {
3855
4018
  return () => {
3856
4019
  if (!client) {
3857
4020
  managedClient.destroy();
3858
4021
  }
3859
4022
  };
3860
4023
  }, [client, managedClient]);
3861
- const value = _react.useMemo.call(void 0,
4024
+ const value = (0, import_react.useMemo)(
3862
4025
  () => ({
3863
4026
  client: managedClient,
3864
4027
  trackInteraction: (event) => {
@@ -3868,10 +4031,10 @@ function AnalyticsProvider({
3868
4031
  }),
3869
4032
  [managedClient]
3870
4033
  );
3871
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, AnalyticsContext.Provider, { value, children });
4034
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AnalyticsContext.Provider, { value, children });
3872
4035
  }
3873
4036
  function useAnalytics() {
3874
- const context = _react.useContext.call(void 0, AnalyticsContext);
4037
+ const context = (0, import_react.useContext)(AnalyticsContext);
3875
4038
  if (!context) {
3876
4039
  throw new Error("useAnalytics must be used within AnalyticsProvider.");
3877
4040
  }
@@ -3879,79 +4042,80 @@ function useAnalytics() {
3879
4042
  }
3880
4043
 
3881
4044
  // src/react/hooks.ts
3882
-
4045
+ var import_react2 = require("react");
3883
4046
  function useComponentInteractionTracker(component, baseContext = {}) {
3884
4047
  const { trackInteraction } = useAnalytics();
3885
- return _react.useCallback.call(void 0,
4048
+ return (0, import_react2.useCallback)(
3886
4049
  (action, details) => {
3887
4050
  trackInteraction({
3888
4051
  component,
3889
4052
  action,
3890
- channel: _optionalChain([details, 'optionalAccess', _103 => _103.channel]),
3891
- label: _optionalChain([details, 'optionalAccess', _104 => _104.label]),
3892
- href: _optionalChain([details, 'optionalAccess', _105 => _105.href]),
3893
- variant: _optionalChain([details, 'optionalAccess', _106 => _106.variant]),
3894
- requestId: _optionalChain([details, 'optionalAccess', _107 => _107.requestId]),
3895
- timestamp: _optionalChain([details, 'optionalAccess', _108 => _108.timestamp]),
4053
+ channel: details?.channel,
4054
+ label: details?.label,
4055
+ href: details?.href,
4056
+ variant: details?.variant,
4057
+ requestId: details?.requestId,
4058
+ timestamp: details?.timestamp,
3896
4059
  context: {
3897
4060
  ...baseContext,
3898
- ..._nullishCoalesce(_optionalChain([details, 'optionalAccess', _109 => _109.context]), () => ( {}))
4061
+ ...details?.context ?? {}
3899
4062
  }
3900
4063
  });
3901
4064
  },
3902
4065
  [baseContext, component, trackInteraction]
3903
4066
  );
3904
4067
  }
3905
-
3906
-
3907
-
3908
-
3909
-
3910
-
3911
-
3912
-
3913
-
3914
-
3915
-
3916
-
3917
-
3918
-
3919
-
3920
-
3921
-
3922
-
3923
-
3924
-
3925
-
3926
-
3927
-
3928
-
3929
-
3930
-
3931
-
3932
-
3933
-
3934
-
3935
-
3936
-
3937
-
3938
-
3939
-
3940
-
3941
-
3942
-
3943
-
3944
-
3945
-
3946
-
3947
-
3948
-
3949
-
3950
-
3951
-
3952
-
3953
-
3954
-
3955
-
3956
- exports.AnalyticsProvider = AnalyticsProvider; exports.SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION = SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION; exports.SEMANTIC_JOURNEY_RECEIPT_HEADER = SEMANTIC_JOURNEY_RECEIPT_HEADER; exports.SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES = SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES; exports.SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT = SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT; exports.SEMANTIC_JOURNEY_RECEIPT_VERSION = SEMANTIC_JOURNEY_RECEIPT_VERSION; exports.SEMANTIC_JOURNEY_STRICT_POLICY_VERSION = SEMANTIC_JOURNEY_STRICT_POLICY_VERSION; exports.SemanticJourneyAggregateStore = SemanticJourneyAggregateStore; exports.SemanticJourneyTransportError = SemanticJourneyTransportError; exports.SemanticJourneyValidationError = SemanticJourneyValidationError; exports.USEFUL_METRIC_EVENT_DEFINITIONS = _chunk5BHE32SKcjs.USEFUL_METRIC_EVENT_DEFINITIONS; exports.assertSemanticSource = assertSemanticSource; exports.assertSemanticToken = assertSemanticToken; exports.createBackendAnalyticsClient = createBackendAnalyticsClient; exports.createChildJourneyContext = createChildJourneyContext; exports.createDefaultSemanticJourneyAggregateTransport = createDefaultSemanticJourneyAggregateTransport; exports.createEventId = createEventId; exports.createFrontendAnalyticsClient = createFrontendAnalyticsClient; exports.createJourneyContext = createJourneyContext; exports.createJourneyId = createJourneyId; exports.createLocalSpaceAnalyticsClient = createLocalSpaceAnalyticsClient; exports.createNoopLocalSpaceAnalyticsClient = createNoopLocalSpaceAnalyticsClient; exports.createProducerId = createProducerId; exports.createRequestJourneyContext = createRequestJourneyContext; exports.createSecureRandomHex = createSecureRandomHex; exports.createSemanticJourneyClient = createSemanticJourneyClient; exports.createSpanId = createSpanId; exports.createTraceId = createTraceId; exports.defineJourneyEvent = defineJourneyEvent; exports.defineSemanticJourneyCatalog = defineSemanticJourneyCatalog; exports.formatTraceparent = formatTraceparent; exports.getJourneyEventDefinition = getJourneyEventDefinition; exports.isEventId = isEventId; exports.isJourneyId = isJourneyId; exports.isJourneyToken = isJourneyToken; exports.isProducerId = isProducerId; exports.isSecureSemanticJourneyEndpoint = isSecureSemanticJourneyEndpoint; exports.isSemanticSource = isSemanticSource; exports.isSemanticToken = isSemanticToken; exports.isSpanId = isSpanId; exports.isTraceId = isTraceId; exports.observeSemanticJourneyInteractions = observeSemanticJourneyInteractions; exports.parseSemanticJourneyReceipts = parseSemanticJourneyReceipts; exports.parseTraceparent = parseTraceparent; exports.projectUsefulMetric = _chunk5BHE32SKcjs.projectUsefulMetric; exports.reconstructSemanticJourney = reconstructSemanticJourney; exports.serializeSemanticJourneyReceipts = serializeSemanticJourneyReceipts; exports.useAnalytics = useAnalytics; exports.useComponentInteractionTracker = useComponentInteractionTracker; exports.validateSemanticJourneyEventInput = validateSemanticJourneyEventInput;
4068
+ // Annotate the CommonJS export names for ESM import in node:
4069
+ 0 && (module.exports = {
4070
+ AnalyticsProvider,
4071
+ SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION,
4072
+ SEMANTIC_JOURNEY_RECEIPT_HEADER,
4073
+ SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES,
4074
+ SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT,
4075
+ SEMANTIC_JOURNEY_RECEIPT_VERSION,
4076
+ SEMANTIC_JOURNEY_STRICT_POLICY_VERSION,
4077
+ SemanticJourneyAggregateStore,
4078
+ SemanticJourneyTransportError,
4079
+ SemanticJourneyValidationError,
4080
+ USEFUL_METRIC_EVENT_DEFINITIONS,
4081
+ assertSemanticSource,
4082
+ assertSemanticToken,
4083
+ createBackendAnalyticsClient,
4084
+ createChildJourneyContext,
4085
+ createDefaultSemanticJourneyAggregateTransport,
4086
+ createEventId,
4087
+ createFrontendAnalyticsClient,
4088
+ createJourneyContext,
4089
+ createJourneyId,
4090
+ createLocalSpaceAnalyticsClient,
4091
+ createNoopLocalSpaceAnalyticsClient,
4092
+ createProducerId,
4093
+ createRequestJourneyContext,
4094
+ createSecureRandomHex,
4095
+ createSemanticJourneyClient,
4096
+ createSpanId,
4097
+ createTraceId,
4098
+ defineJourneyEvent,
4099
+ defineSemanticJourneyCatalog,
4100
+ formatTraceparent,
4101
+ getJourneyEventDefinition,
4102
+ isEventId,
4103
+ isJourneyId,
4104
+ isJourneyToken,
4105
+ isProducerId,
4106
+ isSecureSemanticJourneyEndpoint,
4107
+ isSemanticSource,
4108
+ isSemanticToken,
4109
+ isSpanId,
4110
+ isTraceId,
4111
+ observeSemanticJourneyInteractions,
4112
+ parseSemanticJourneyReceipts,
4113
+ parseTraceparent,
4114
+ projectUsefulMetric,
4115
+ reconstructSemanticJourney,
4116
+ serializeSemanticJourneyReceipts,
4117
+ useAnalytics,
4118
+ useComponentInteractionTracker,
4119
+ validateSemanticJourneyEventInput
4120
+ });
3957
4121
  //# sourceMappingURL=index.cjs.map