@plasius/analytics 1.1.17 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -21,12 +21,53 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
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
+ assertSemanticSource: () => assertSemanticSource,
34
+ assertSemanticToken: () => assertSemanticToken,
24
35
  createBackendAnalyticsClient: () => createBackendAnalyticsClient,
36
+ createChildJourneyContext: () => createChildJourneyContext,
37
+ createDefaultSemanticJourneyAggregateTransport: () => createDefaultSemanticJourneyAggregateTransport,
38
+ createEventId: () => createEventId,
25
39
  createFrontendAnalyticsClient: () => createFrontendAnalyticsClient,
40
+ createJourneyContext: () => createJourneyContext,
41
+ createJourneyId: () => createJourneyId,
26
42
  createLocalSpaceAnalyticsClient: () => createLocalSpaceAnalyticsClient,
27
43
  createNoopLocalSpaceAnalyticsClient: () => createNoopLocalSpaceAnalyticsClient,
44
+ createProducerId: () => createProducerId,
45
+ createRequestJourneyContext: () => createRequestJourneyContext,
46
+ createSecureRandomHex: () => createSecureRandomHex,
47
+ createSemanticJourneyClient: () => createSemanticJourneyClient,
48
+ createSpanId: () => createSpanId,
49
+ createTraceId: () => createTraceId,
50
+ defineJourneyEvent: () => defineJourneyEvent,
51
+ defineSemanticJourneyCatalog: () => defineSemanticJourneyCatalog,
52
+ formatTraceparent: () => formatTraceparent,
53
+ getJourneyEventDefinition: () => getJourneyEventDefinition,
54
+ isEventId: () => isEventId,
55
+ isJourneyId: () => isJourneyId,
56
+ isJourneyToken: () => isJourneyToken,
57
+ isProducerId: () => isProducerId,
58
+ isSecureSemanticJourneyEndpoint: () => isSecureSemanticJourneyEndpoint,
59
+ isSemanticSource: () => isSemanticSource,
60
+ isSemanticToken: () => isSemanticToken,
61
+ isSpanId: () => isSpanId,
62
+ isTraceId: () => isTraceId,
63
+ observeSemanticJourneyInteractions: () => observeSemanticJourneyInteractions,
64
+ parseSemanticJourneyReceipts: () => parseSemanticJourneyReceipts,
65
+ parseTraceparent: () => parseTraceparent,
66
+ reconstructSemanticJourney: () => reconstructSemanticJourney,
67
+ serializeSemanticJourneyReceipts: () => serializeSemanticJourneyReceipts,
28
68
  useAnalytics: () => useAnalytics,
29
- useComponentInteractionTracker: () => useComponentInteractionTracker
69
+ useComponentInteractionTracker: () => useComponentInteractionTracker,
70
+ validateSemanticJourneyEventInput: () => validateSemanticJourneyEventInput
30
71
  });
31
72
  module.exports = __toCommonJS(index_exports);
32
73
 
@@ -1220,6 +1261,2595 @@ function createNoopLocalSpaceAnalyticsClient(source = "noop", channel = "fronten
1220
1261
  };
1221
1262
  }
1222
1263
 
1264
+ // src/journey/types.ts
1265
+ var SEMANTIC_JOURNEY_STRICT_POLICY_VERSION = "strict.v1";
1266
+
1267
+ // src/journey/catalog.ts
1268
+ var MAX_TOKEN_LENGTH = 64;
1269
+ var MAX_TOKEN_SEGMENTS = 8;
1270
+ var MAX_TOKEN_SEGMENT_LENGTH = MAX_TOKEN_LENGTH;
1271
+ var MAX_CATALOG_EVENTS = 2048;
1272
+ var MAX_EVENT_ATTRIBUTES = 32;
1273
+ var MAX_ENUM_VALUES = 64;
1274
+ var MAX_CATALOG_SOURCES = 64;
1275
+ var MAX_EVENT_TARGETS = 64;
1276
+ var MAX_EVENT_EFFECTS = 64;
1277
+ var TOKEN_PATTERN = /^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;
1278
+ var HIGH_ENTROPY_HEX_PATTERN = /^[a-f0-9]{16,}$/i;
1279
+ var HIGH_ENTROPY_TOKEN_PATTERN = /^(?=[A-Za-z0-9_-]*[A-Za-z])(?=[A-Za-z0-9_-]*[0-9])[A-Za-z0-9_-]{24,}$/;
1280
+ var CATEGORIES = /* @__PURE__ */ new Set([
1281
+ "interaction",
1282
+ "navigation",
1283
+ "request",
1284
+ "command",
1285
+ "state",
1286
+ "presentation",
1287
+ "dependency",
1288
+ "error"
1289
+ ]);
1290
+ var PHASES = /* @__PURE__ */ new Set([
1291
+ "intent",
1292
+ "start",
1293
+ "progress",
1294
+ "end",
1295
+ "effect"
1296
+ ]);
1297
+ var OUTCOMES = /* @__PURE__ */ new Set([
1298
+ "unknown",
1299
+ "success",
1300
+ "failure",
1301
+ "cancelled",
1302
+ "denied"
1303
+ ]);
1304
+ var MODALITIES = /* @__PURE__ */ new Set([
1305
+ "pointer",
1306
+ "keyboard",
1307
+ "touch",
1308
+ "voice",
1309
+ "gesture",
1310
+ "system"
1311
+ ]);
1312
+ var SENSITIVE_WORDS = /* @__PURE__ */ new Set([
1313
+ "account",
1314
+ "address",
1315
+ "auth",
1316
+ "authentication",
1317
+ "authorization",
1318
+ "body",
1319
+ "browser",
1320
+ "chat",
1321
+ "clipboard",
1322
+ "content",
1323
+ "cookie",
1324
+ "credential",
1325
+ "database",
1326
+ "device",
1327
+ "digest",
1328
+ "dob",
1329
+ "editor",
1330
+ "email",
1331
+ "exception",
1332
+ "file",
1333
+ "fingerprint",
1334
+ "fragment",
1335
+ "generated",
1336
+ "hash",
1337
+ "html",
1338
+ "href",
1339
+ "input",
1340
+ "ip",
1341
+ "label",
1342
+ "latitude",
1343
+ "location",
1344
+ "log",
1345
+ "longitude",
1346
+ "message",
1347
+ "name",
1348
+ "password",
1349
+ "payload",
1350
+ "phone",
1351
+ "prompt",
1352
+ "query",
1353
+ "recording",
1354
+ "referrer",
1355
+ "requestbody",
1356
+ "responsebody",
1357
+ "screenshot",
1358
+ "secret",
1359
+ "selector",
1360
+ "session",
1361
+ "stack",
1362
+ "telephone",
1363
+ "textarea",
1364
+ "token",
1365
+ "transcript",
1366
+ "uri",
1367
+ "url",
1368
+ "user",
1369
+ "userid",
1370
+ "useragent",
1371
+ "username"
1372
+ ]);
1373
+ var EVENT_INPUT_FIELDS = /* @__PURE__ */ new Set([
1374
+ "name",
1375
+ "category",
1376
+ "phase",
1377
+ "outcome",
1378
+ "modality",
1379
+ "target",
1380
+ "attributes"
1381
+ ]);
1382
+ var EVENT_DEFINITION_FIELDS = /* @__PURE__ */ new Set([
1383
+ "category",
1384
+ "attributes",
1385
+ "targets",
1386
+ "effects"
1387
+ ]);
1388
+ var TARGET_FIELDS = /* @__PURE__ */ new Set(["type", "id"]);
1389
+ var CATALOG_OPTIONS_FIELDS = /* @__PURE__ */ new Set(["sources"]);
1390
+ var SemanticJourneyValidationError = class extends Error {
1391
+ code;
1392
+ constructor(code) {
1393
+ super(
1394
+ code === "invalid-token" ? "Semantic journey token is invalid." : "Semantic journey input is invalid."
1395
+ );
1396
+ this.name = "SemanticJourneyValidationError";
1397
+ this.code = code;
1398
+ }
1399
+ };
1400
+ function invalidDefinition() {
1401
+ throw new Error("Semantic journey catalogue definition is invalid.");
1402
+ }
1403
+ function invalidInput() {
1404
+ throw new SemanticJourneyValidationError("invalid-input");
1405
+ }
1406
+ function isRecord(value) {
1407
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1408
+ return false;
1409
+ }
1410
+ const prototype = Object.getPrototypeOf(value);
1411
+ return prototype === Object.prototype || prototype === null;
1412
+ }
1413
+ function getOwnStringKeys(value) {
1414
+ const keys = Reflect.ownKeys(value);
1415
+ if (keys.some((key) => typeof key !== "string")) {
1416
+ return null;
1417
+ }
1418
+ return keys;
1419
+ }
1420
+ function hasOnlyFields(keys, allowed) {
1421
+ return keys.every((key) => allowed.has(key));
1422
+ }
1423
+ function sensitivityWords(value) {
1424
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.toLowerCase());
1425
+ }
1426
+ function looksSensitive(value) {
1427
+ const words = sensitivityWords(value);
1428
+ const collapsed = words.join("");
1429
+ if (words.some((word) => SENSITIVE_WORDS.has(word)) || SENSITIVE_WORDS.has(collapsed)) {
1430
+ return true;
1431
+ }
1432
+ return value.includes("@") || value.includes("://") || HIGH_ENTROPY_HEX_PATTERN.test(value) || HIGH_ENTROPY_TOKEN_PATTERN.test(value);
1433
+ }
1434
+ function isSemanticToken(value) {
1435
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_TOKEN_LENGTH || !TOKEN_PATTERN.test(value)) {
1436
+ return false;
1437
+ }
1438
+ const segments = value.split(/[._-]/);
1439
+ return segments.length <= MAX_TOKEN_SEGMENTS && segments.every(
1440
+ (segment) => segment.length > 0 && segment.length <= MAX_TOKEN_SEGMENT_LENGTH
1441
+ );
1442
+ }
1443
+ var isJourneyToken = isSemanticToken;
1444
+ var isSemanticSource = isSemanticToken;
1445
+ function assertSemanticToken(value, _field) {
1446
+ if (!isSemanticToken(value)) {
1447
+ throw new SemanticJourneyValidationError("invalid-token");
1448
+ }
1449
+ }
1450
+ var assertSemanticSource = assertSemanticToken;
1451
+ function normalizeAttributeDefinition(attributeName, candidate) {
1452
+ if (!isSemanticToken(attributeName) || looksSensitive(attributeName)) {
1453
+ return invalidDefinition();
1454
+ }
1455
+ if (!isRecord(candidate)) {
1456
+ return invalidDefinition();
1457
+ }
1458
+ const keys = getOwnStringKeys(candidate);
1459
+ if (keys === null || typeof candidate.type !== "string") {
1460
+ return invalidDefinition();
1461
+ }
1462
+ if (candidate.type === "boolean") {
1463
+ if (keys.length !== 1 || keys[0] !== "type") {
1464
+ return invalidDefinition();
1465
+ }
1466
+ return Object.freeze({ type: "boolean" });
1467
+ }
1468
+ if (candidate.type === "enum") {
1469
+ if (!hasOnlyFields(keys, /* @__PURE__ */ new Set(["type", "values"])) || keys.length !== 2 || !Array.isArray(candidate.values) || candidate.values.length === 0 || candidate.values.length > MAX_ENUM_VALUES) {
1470
+ return invalidDefinition();
1471
+ }
1472
+ const values = [];
1473
+ const seen = /* @__PURE__ */ new Set();
1474
+ for (const value of candidate.values) {
1475
+ if (!isSemanticToken(value) || looksSensitive(value) || seen.has(value)) {
1476
+ return invalidDefinition();
1477
+ }
1478
+ seen.add(value);
1479
+ values.push(value);
1480
+ }
1481
+ return Object.freeze({
1482
+ type: "enum",
1483
+ values: Object.freeze(values)
1484
+ });
1485
+ }
1486
+ if (candidate.type === "number") {
1487
+ if (!hasOnlyFields(keys, /* @__PURE__ */ new Set(["type", "min", "max", "integer"])) || !keys.includes("min") || !keys.includes("max") || typeof candidate.min !== "number" || !Number.isFinite(candidate.min) || typeof candidate.max !== "number" || !Number.isFinite(candidate.max) || candidate.min > candidate.max || candidate.integer !== void 0 && typeof candidate.integer !== "boolean") {
1488
+ return invalidDefinition();
1489
+ }
1490
+ if (candidate.integer === true && (!Number.isSafeInteger(candidate.min) || !Number.isSafeInteger(candidate.max))) {
1491
+ return invalidDefinition();
1492
+ }
1493
+ return Object.freeze({
1494
+ type: "number",
1495
+ min: candidate.min,
1496
+ max: candidate.max,
1497
+ ...candidate.integer === void 0 ? {} : { integer: candidate.integer }
1498
+ });
1499
+ }
1500
+ return invalidDefinition();
1501
+ }
1502
+ function normalizeEventDefinition(candidate) {
1503
+ if (!isRecord(candidate)) {
1504
+ return invalidDefinition();
1505
+ }
1506
+ const keys = getOwnStringKeys(candidate);
1507
+ if (keys === null || !hasOnlyFields(keys, EVENT_DEFINITION_FIELDS) || !CATEGORIES.has(candidate.category)) {
1508
+ return invalidDefinition();
1509
+ }
1510
+ const attributes = /* @__PURE__ */ Object.create(null);
1511
+ const candidateAttributes = candidate.attributes;
1512
+ if (candidateAttributes !== void 0) {
1513
+ if (!isRecord(candidateAttributes)) {
1514
+ return invalidDefinition();
1515
+ }
1516
+ const attributeNames = getOwnStringKeys(candidateAttributes);
1517
+ if (attributeNames === null || attributeNames.length > MAX_EVENT_ATTRIBUTES) {
1518
+ return invalidDefinition();
1519
+ }
1520
+ for (const attributeName of attributeNames) {
1521
+ attributes[attributeName] = normalizeAttributeDefinition(
1522
+ attributeName,
1523
+ candidateAttributes[attributeName]
1524
+ );
1525
+ }
1526
+ }
1527
+ const targets = [];
1528
+ if (candidate.targets !== void 0) {
1529
+ if (!Array.isArray(candidate.targets) || candidate.targets.length > MAX_EVENT_TARGETS) {
1530
+ return invalidDefinition();
1531
+ }
1532
+ const seenTargets = /* @__PURE__ */ new Set();
1533
+ for (const target of candidate.targets) {
1534
+ if (!isRecord(target)) {
1535
+ return invalidDefinition();
1536
+ }
1537
+ const targetKeys = getOwnStringKeys(target);
1538
+ if (targetKeys === null || targetKeys.length !== 2 || !hasOnlyFields(targetKeys, TARGET_FIELDS) || !isSemanticToken(target.type) || !isSemanticToken(target.id) || looksSensitive(target.type) || looksSensitive(target.id)) {
1539
+ return invalidDefinition();
1540
+ }
1541
+ const key = `${target.type}\0${target.id}`;
1542
+ if (seenTargets.has(key)) {
1543
+ return invalidDefinition();
1544
+ }
1545
+ seenTargets.add(key);
1546
+ targets.push(Object.freeze({ type: target.type, id: target.id }));
1547
+ }
1548
+ }
1549
+ const effects = [];
1550
+ if (candidate.effects !== void 0) {
1551
+ if (!Array.isArray(candidate.effects) || candidate.effects.length > MAX_EVENT_EFFECTS) {
1552
+ return invalidDefinition();
1553
+ }
1554
+ const seenEffects = /* @__PURE__ */ new Set();
1555
+ for (const effect of candidate.effects) {
1556
+ if (!isSemanticToken(effect) || looksSensitive(effect) || seenEffects.has(effect)) {
1557
+ return invalidDefinition();
1558
+ }
1559
+ seenEffects.add(effect);
1560
+ effects.push(effect);
1561
+ }
1562
+ }
1563
+ return Object.freeze({
1564
+ category: candidate.category,
1565
+ attributes: Object.freeze(attributes),
1566
+ targets: Object.freeze(targets),
1567
+ effects: Object.freeze(effects)
1568
+ });
1569
+ }
1570
+ function defineSemanticJourneyCatalogUnsafe(definitions, options) {
1571
+ if (!isRecord(definitions) || !isRecord(options)) {
1572
+ return invalidDefinition();
1573
+ }
1574
+ const optionKeys = getOwnStringKeys(options);
1575
+ if (optionKeys === null || optionKeys.length !== 1 || !hasOnlyFields(optionKeys, CATALOG_OPTIONS_FIELDS) || !Array.isArray(options.sources) || options.sources.length === 0 || options.sources.length > MAX_CATALOG_SOURCES) {
1576
+ return invalidDefinition();
1577
+ }
1578
+ const sources = [];
1579
+ const seenSources = /* @__PURE__ */ new Set();
1580
+ for (const source of options.sources) {
1581
+ if (!isSemanticSource(source) || looksSensitive(source) || seenSources.has(source)) {
1582
+ return invalidDefinition();
1583
+ }
1584
+ seenSources.add(source);
1585
+ sources.push(source);
1586
+ }
1587
+ const names = getOwnStringKeys(definitions);
1588
+ if (names === null || names.length > MAX_CATALOG_EVENTS) {
1589
+ return invalidDefinition();
1590
+ }
1591
+ const normalized = /* @__PURE__ */ Object.create(null);
1592
+ for (const name of names) {
1593
+ if (!isSemanticToken(name)) {
1594
+ return invalidDefinition();
1595
+ }
1596
+ normalized[name] = normalizeEventDefinition(definitions[name]);
1597
+ }
1598
+ return Object.freeze({
1599
+ sources: Object.freeze(sources),
1600
+ definitions: Object.freeze(normalized)
1601
+ });
1602
+ }
1603
+ function defineSemanticJourneyCatalog(definitions, options) {
1604
+ try {
1605
+ return defineSemanticJourneyCatalogUnsafe(definitions, options);
1606
+ } catch {
1607
+ return invalidDefinition();
1608
+ }
1609
+ }
1610
+ function defineJourneyEvent(name, definition, options) {
1611
+ return defineSemanticJourneyCatalog({ [name]: definition }, options);
1612
+ }
1613
+ function getJourneyEventDefinition(catalogue, name) {
1614
+ if (!isSemanticToken(name)) {
1615
+ return void 0;
1616
+ }
1617
+ return Object.prototype.hasOwnProperty.call(catalogue.definitions, name) ? catalogue.definitions[name] : void 0;
1618
+ }
1619
+ function validateTarget(candidate, definition) {
1620
+ if (!isRecord(candidate)) {
1621
+ return invalidInput();
1622
+ }
1623
+ const keys = getOwnStringKeys(candidate);
1624
+ if (keys === null || keys.length !== 2 || !hasOnlyFields(keys, TARGET_FIELDS) || !isSemanticToken(candidate.type) || !isSemanticToken(candidate.id) || looksSensitive(candidate.type) || looksSensitive(candidate.id)) {
1625
+ return invalidInput();
1626
+ }
1627
+ const allowedTarget = (definition.targets ?? []).some(
1628
+ (target) => target.type === candidate.type && target.id === candidate.id
1629
+ );
1630
+ const allowedEffect = candidate.type === "effect" && (definition.effects ?? []).includes(candidate.id);
1631
+ if (!allowedTarget && !allowedEffect) {
1632
+ return invalidInput();
1633
+ }
1634
+ return Object.freeze({ type: candidate.type, id: candidate.id });
1635
+ }
1636
+ function validateAttributeValue(definition, candidate) {
1637
+ if (definition.type === "boolean") {
1638
+ return typeof candidate === "boolean" ? candidate : invalidInput();
1639
+ }
1640
+ if (definition.type === "enum") {
1641
+ return typeof candidate === "string" && definition.values.includes(candidate) ? candidate : invalidInput();
1642
+ }
1643
+ if (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < definition.min || candidate > definition.max || definition.integer === true && !Number.isSafeInteger(candidate)) {
1644
+ return invalidInput();
1645
+ }
1646
+ return candidate;
1647
+ }
1648
+ function validateSemanticJourneyEventInputUnsafe(catalogue, input) {
1649
+ if (!isRecord(input)) {
1650
+ return invalidInput();
1651
+ }
1652
+ const keys = getOwnStringKeys(input);
1653
+ if (keys === null || !hasOnlyFields(keys, EVENT_INPUT_FIELDS)) {
1654
+ return invalidInput();
1655
+ }
1656
+ const definition = getJourneyEventDefinition(catalogue, input.name);
1657
+ if (definition === void 0 || input.category !== definition.category || !PHASES.has(input.phase) || !OUTCOMES.has(input.outcome) || input.modality !== void 0 && !MODALITIES.has(input.modality)) {
1658
+ return invalidInput();
1659
+ }
1660
+ const target = input.target === void 0 ? void 0 : validateTarget(input.target, definition);
1661
+ const candidateAttributes = input.attributes ?? {};
1662
+ if (!isRecord(candidateAttributes)) {
1663
+ return invalidInput();
1664
+ }
1665
+ const attributeNames = getOwnStringKeys(candidateAttributes);
1666
+ if (attributeNames === null || attributeNames.length > MAX_EVENT_ATTRIBUTES) {
1667
+ return invalidInput();
1668
+ }
1669
+ const registeredAttributes = definition.attributes ?? {};
1670
+ for (const attributeName of attributeNames) {
1671
+ if (!Object.prototype.hasOwnProperty.call(registeredAttributes, attributeName)) {
1672
+ return invalidInput();
1673
+ }
1674
+ }
1675
+ const attributes = /* @__PURE__ */ Object.create(null);
1676
+ for (const attributeName of attributeNames) {
1677
+ const attributeDefinition = registeredAttributes[attributeName];
1678
+ if (attributeDefinition === void 0) {
1679
+ return invalidInput();
1680
+ }
1681
+ attributes[attributeName] = validateAttributeValue(
1682
+ attributeDefinition,
1683
+ candidateAttributes[attributeName]
1684
+ );
1685
+ }
1686
+ return Object.freeze({
1687
+ name: input.name,
1688
+ category: input.category,
1689
+ phase: input.phase,
1690
+ outcome: input.outcome,
1691
+ ...input.modality === void 0 ? {} : { modality: input.modality },
1692
+ ...target === void 0 ? {} : { target },
1693
+ attributes: Object.freeze(attributes),
1694
+ droppedAttributeCount: 0
1695
+ });
1696
+ }
1697
+ function validateSemanticJourneyEventInput(catalogue, input) {
1698
+ try {
1699
+ return validateSemanticJourneyEventInputUnsafe(catalogue, input);
1700
+ } catch (error) {
1701
+ if (error instanceof SemanticJourneyValidationError) {
1702
+ throw error;
1703
+ }
1704
+ return invalidInput();
1705
+ }
1706
+ }
1707
+
1708
+ // src/journey/context.ts
1709
+ var MAX_RANDOM_BYTE_LENGTH = 64;
1710
+ var MAX_IDENTIFIER_ATTEMPTS = 8;
1711
+ var TRACE_ID_HEX_LENGTH = 32;
1712
+ var SPAN_ID_HEX_LENGTH = 16;
1713
+ var ALL_ZERO_TRACE_ID = "0".repeat(TRACE_ID_HEX_LENGTH);
1714
+ var ALL_ZERO_SPAN_ID = "0".repeat(SPAN_ID_HEX_LENGTH);
1715
+ var TRACEPARENT_PATTERN = /^00-([0-9a-f]{32})-([0-9a-f]{16})-(00|01)$/;
1716
+ function webCryptoRandomBytes(byteLength2) {
1717
+ const webCrypto = globalThis.crypto;
1718
+ if (webCrypto === void 0 || typeof webCrypto.getRandomValues !== "function") {
1719
+ throw new Error("Secure random source is unavailable.");
1720
+ }
1721
+ return webCrypto.getRandomValues(new Uint8Array(byteLength2));
1722
+ }
1723
+ function createSecureRandomHex(byteLength2, randomBytes = webCryptoRandomBytes) {
1724
+ if (!Number.isSafeInteger(byteLength2) || byteLength2 <= 0 || byteLength2 > MAX_RANDOM_BYTE_LENGTH) {
1725
+ throw new Error("Secure random byte length is invalid.");
1726
+ }
1727
+ const bytes = randomBytes(byteLength2);
1728
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength !== byteLength2) {
1729
+ throw new Error("Secure random source returned invalid bytes.");
1730
+ }
1731
+ let result = "";
1732
+ for (const byte of bytes) {
1733
+ result += byte.toString(16).padStart(2, "0");
1734
+ }
1735
+ return result;
1736
+ }
1737
+ function createNonZeroIdentifier(byteLength2, randomBytes) {
1738
+ for (let attempt = 0; attempt < MAX_IDENTIFIER_ATTEMPTS; attempt += 1) {
1739
+ const identifier = createSecureRandomHex(
1740
+ byteLength2,
1741
+ randomBytes ?? webCryptoRandomBytes
1742
+ );
1743
+ if (!/^0+$/.test(identifier)) {
1744
+ return identifier;
1745
+ }
1746
+ }
1747
+ throw new Error("Secure random source did not produce a valid identifier.");
1748
+ }
1749
+ function isNonZeroLowerHex(value, length) {
1750
+ return typeof value === "string" && value.length === length && /^[0-9a-f]+$/.test(value) && !/^0+$/.test(value);
1751
+ }
1752
+ function createJourneyId(randomBytes) {
1753
+ return createNonZeroIdentifier(16, randomBytes);
1754
+ }
1755
+ function createTraceId(randomBytes) {
1756
+ return createNonZeroIdentifier(16, randomBytes);
1757
+ }
1758
+ function createEventId(randomBytes) {
1759
+ return createNonZeroIdentifier(16, randomBytes);
1760
+ }
1761
+ function createSpanId(randomBytes) {
1762
+ return createNonZeroIdentifier(8, randomBytes);
1763
+ }
1764
+ function createProducerId(randomBytes) {
1765
+ return createNonZeroIdentifier(8, randomBytes);
1766
+ }
1767
+ function isJourneyId(value) {
1768
+ return isNonZeroLowerHex(value, TRACE_ID_HEX_LENGTH);
1769
+ }
1770
+ function isTraceId(value) {
1771
+ return isNonZeroLowerHex(value, TRACE_ID_HEX_LENGTH);
1772
+ }
1773
+ function isEventId(value) {
1774
+ return isNonZeroLowerHex(value, TRACE_ID_HEX_LENGTH);
1775
+ }
1776
+ function isSpanId(value) {
1777
+ return isNonZeroLowerHex(value, SPAN_ID_HEX_LENGTH);
1778
+ }
1779
+ function isProducerId(value) {
1780
+ return isNonZeroLowerHex(value, SPAN_ID_HEX_LENGTH);
1781
+ }
1782
+ function isTraceFlags(value) {
1783
+ return value === "00" || value === "01";
1784
+ }
1785
+ function assertLocalContext(context) {
1786
+ if (!isJourneyId(context.journeyId) || !isTraceId(context.traceId) || !isSpanId(context.spanId) || context.parentSpanId !== void 0 && !isSpanId(context.parentSpanId) || !isTraceFlags(context.traceFlags)) {
1787
+ throw new Error("Semantic journey causal context is invalid.");
1788
+ }
1789
+ }
1790
+ function createJourneyContext(randomBytes, traceFlags = "00") {
1791
+ if (!isTraceFlags(traceFlags)) {
1792
+ throw new Error("Semantic journey causal context is invalid.");
1793
+ }
1794
+ return Object.freeze({
1795
+ journeyId: createJourneyId(randomBytes),
1796
+ traceId: createTraceId(randomBytes),
1797
+ spanId: createSpanId(randomBytes),
1798
+ traceFlags
1799
+ });
1800
+ }
1801
+ function createChildJourneyContext(parent, randomBytes) {
1802
+ assertLocalContext(parent);
1803
+ return Object.freeze({
1804
+ journeyId: parent.journeyId,
1805
+ traceId: parent.traceId,
1806
+ spanId: createSpanId(randomBytes),
1807
+ parentSpanId: parent.spanId,
1808
+ traceFlags: parent.traceFlags
1809
+ });
1810
+ }
1811
+ function createRequestJourneyContext(parent, randomBytes) {
1812
+ assertLocalContext(parent);
1813
+ return Object.freeze({
1814
+ journeyId: parent.journeyId,
1815
+ traceId: createTraceId(randomBytes),
1816
+ spanId: createSpanId(randomBytes),
1817
+ traceFlags: parent.traceFlags
1818
+ });
1819
+ }
1820
+ function formatTraceparent(context) {
1821
+ if (!isTraceId(context.traceId) || !isSpanId(context.spanId) || !isTraceFlags(context.traceFlags)) {
1822
+ throw new Error("Semantic journey trace context is invalid.");
1823
+ }
1824
+ return `00-${context.traceId}-${context.spanId}-${context.traceFlags}`;
1825
+ }
1826
+ function parseTraceparent(value) {
1827
+ if (typeof value !== "string") {
1828
+ return null;
1829
+ }
1830
+ const match = TRACEPARENT_PATTERN.exec(value);
1831
+ if (match === null) {
1832
+ return null;
1833
+ }
1834
+ const traceId = match[1];
1835
+ const spanId = match[2];
1836
+ const traceFlags = match[3];
1837
+ if (traceId === void 0 || spanId === void 0 || traceFlags === void 0 || traceId === ALL_ZERO_TRACE_ID || spanId === ALL_ZERO_SPAN_ID || !isTraceId(traceId) || !isSpanId(spanId) || !isTraceFlags(traceFlags)) {
1838
+ return null;
1839
+ }
1840
+ return Object.freeze({
1841
+ version: "00",
1842
+ traceId,
1843
+ spanId,
1844
+ traceFlags
1845
+ });
1846
+ }
1847
+
1848
+ // src/journey/aggregate.ts
1849
+ var SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION = "2.0-aggregate";
1850
+ var textEncoder = new TextEncoder();
1851
+ var OUTCOMES2 = /* @__PURE__ */ new Set([
1852
+ "unknown",
1853
+ "success",
1854
+ "failure",
1855
+ "cancelled",
1856
+ "denied"
1857
+ ]);
1858
+ function invalidAggregate() {
1859
+ throw new Error("semantic journey aggregate input is invalid");
1860
+ }
1861
+ function toCounterKey(eventName, outcome) {
1862
+ return `${eventName}\0${outcome}`;
1863
+ }
1864
+ function toHourBucket(epochMs) {
1865
+ const date = new Date(epochMs);
1866
+ if (!Number.isFinite(date.getTime())) {
1867
+ throw new Error("semantic journey aggregate time is invalid");
1868
+ }
1869
+ date.setUTCMinutes(0, 0, 0);
1870
+ return date.toISOString();
1871
+ }
1872
+ function byteLength(value) {
1873
+ return textEncoder.encode(JSON.stringify(value)).byteLength;
1874
+ }
1875
+ function normalizeLimit(value, minimum, name) {
1876
+ if (!Number.isSafeInteger(value) || value < minimum) {
1877
+ throw new Error(`semantic journey aggregate ${name} is invalid`);
1878
+ }
1879
+ return value;
1880
+ }
1881
+ function addSafeCount(current, increment) {
1882
+ const next = current + increment;
1883
+ if (!Number.isSafeInteger(next)) {
1884
+ return invalidAggregate();
1885
+ }
1886
+ return next;
1887
+ }
1888
+ var SemanticJourneyAggregateStore = class {
1889
+ counters = /* @__PURE__ */ new Map();
1890
+ options;
1891
+ dropped = 0;
1892
+ coalesced = 0;
1893
+ constructor(options) {
1894
+ if (!isSemanticSource(options.source) || !options.catalogue.sources.includes(options.source) || options.channel !== "frontend" && options.channel !== "backend" || options.runtime !== "browser" && options.runtime !== "server") {
1895
+ invalidAggregate();
1896
+ }
1897
+ this.options = Object.freeze({ ...options });
1898
+ }
1899
+ record(eventName, outcome, count = 1) {
1900
+ if (!isSemanticToken(eventName) || getJourneyEventDefinition(this.options.catalogue, eventName) === void 0 || !OUTCOMES2.has(outcome)) {
1901
+ invalidAggregate();
1902
+ }
1903
+ normalizeLimit(count, 1, "counter increment");
1904
+ const key = toCounterKey(eventName, outcome);
1905
+ const existing = this.counters.get(key);
1906
+ this.counters.set(key, Object.freeze({
1907
+ eventName,
1908
+ outcome,
1909
+ count: addSafeCount(existing?.count ?? 0, count)
1910
+ }));
1911
+ }
1912
+ recordDropped(count = 1) {
1913
+ this.dropped = addSafeCount(
1914
+ this.dropped,
1915
+ normalizeLimit(count, 1, "dropped increment")
1916
+ );
1917
+ }
1918
+ recordCoalesced(count = 1) {
1919
+ this.coalesced = addSafeCount(
1920
+ this.coalesced,
1921
+ normalizeLimit(count, 1, "coalesced increment")
1922
+ );
1923
+ }
1924
+ snapshot() {
1925
+ return Object.freeze({
1926
+ dropped: this.dropped,
1927
+ coalesced: this.coalesced,
1928
+ counters: this.sortedCounters()
1929
+ });
1930
+ }
1931
+ createBatch(options) {
1932
+ if (!isEventId(options.batchId)) {
1933
+ invalidAggregate();
1934
+ }
1935
+ const maxCounters = normalizeLimit(options.maxCounters, 1, "counter limit");
1936
+ const maxBytes = normalizeLimit(options.maxBytes, 512, "byte limit");
1937
+ const availableCounters = this.sortedCounters();
1938
+ if (availableCounters.length === 0 && this.dropped === 0 && this.coalesced === 0) {
1939
+ return null;
1940
+ }
1941
+ const selected = [];
1942
+ const base = {
1943
+ schemaVersion: SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION,
1944
+ batchId: options.batchId,
1945
+ source: this.options.source,
1946
+ channel: this.options.channel,
1947
+ runtime: this.options.runtime,
1948
+ timeBucket: toHourBucket(options.nowEpochMs),
1949
+ policyVersion: SEMANTIC_JOURNEY_STRICT_POLICY_VERSION,
1950
+ dropped: this.dropped,
1951
+ coalesced: this.coalesced
1952
+ };
1953
+ for (const counter of availableCounters) {
1954
+ if (selected.length >= maxCounters) {
1955
+ break;
1956
+ }
1957
+ const candidate = { ...base, counters: [...selected, counter] };
1958
+ if (byteLength(candidate) > maxBytes) {
1959
+ break;
1960
+ }
1961
+ selected.push(counter);
1962
+ }
1963
+ const batch = Object.freeze({
1964
+ ...base,
1965
+ counters: Object.freeze([...selected])
1966
+ });
1967
+ if (byteLength(batch) > maxBytes) {
1968
+ throw new Error("semantic journey aggregate batch limit is too small");
1969
+ }
1970
+ if (availableCounters.length > 0 && selected.length === 0) {
1971
+ throw new Error("semantic journey aggregate counter exceeds batch limit");
1972
+ }
1973
+ return batch;
1974
+ }
1975
+ acknowledge(batch) {
1976
+ for (const acknowledged of batch.counters) {
1977
+ const key = toCounterKey(acknowledged.eventName, acknowledged.outcome);
1978
+ const current = this.counters.get(key);
1979
+ if (!current) {
1980
+ continue;
1981
+ }
1982
+ const remaining = current.count - acknowledged.count;
1983
+ if (remaining > 0) {
1984
+ this.counters.set(key, Object.freeze({ ...current, count: remaining }));
1985
+ } else {
1986
+ this.counters.delete(key);
1987
+ }
1988
+ }
1989
+ this.dropped = Math.max(0, this.dropped - batch.dropped);
1990
+ this.coalesced = Math.max(0, this.coalesced - batch.coalesced);
1991
+ }
1992
+ clear() {
1993
+ this.counters.clear();
1994
+ this.dropped = 0;
1995
+ this.coalesced = 0;
1996
+ }
1997
+ sortedCounters() {
1998
+ return Object.freeze(Array.from(this.counters.values()).sort((left, right) => {
1999
+ const byName = left.eventName.localeCompare(right.eventName);
2000
+ return byName !== 0 ? byName : left.outcome.localeCompare(right.outcome);
2001
+ }));
2002
+ }
2003
+ };
2004
+
2005
+ // src/journey/transport.ts
2006
+ var SemanticJourneyTransportError = class extends Error {
2007
+ constructor(code, retryable, status, retryAfterMs) {
2008
+ super(`semantic journey aggregate transport ${code}`);
2009
+ this.code = code;
2010
+ this.retryable = retryable;
2011
+ this.status = status;
2012
+ this.retryAfterMs = retryAfterMs;
2013
+ this.name = "SemanticJourneyTransportError";
2014
+ }
2015
+ code;
2016
+ retryable;
2017
+ status;
2018
+ retryAfterMs;
2019
+ };
2020
+ var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
2021
+ var MAX_RETRY_AFTER_MS = 5 * 60 * 1e3;
2022
+ var RELATIVE_ENDPOINT_PATTERN = /^\/(?!\/)[\x21-\x7e]*$/;
2023
+ function resolveBaseUrl(explicitBaseUrl) {
2024
+ if (explicitBaseUrl) {
2025
+ return explicitBaseUrl;
2026
+ }
2027
+ if (typeof window !== "undefined" && window.location?.origin) {
2028
+ return window.location.origin;
2029
+ }
2030
+ return void 0;
2031
+ }
2032
+ function isSecureSemanticJourneyEndpoint(endpoint, baseUrl) {
2033
+ const trimmed = endpoint.trim();
2034
+ if (!trimmed || trimmed !== endpoint || trimmed.length > 2048) {
2035
+ return false;
2036
+ }
2037
+ const resolvedBaseUrl = resolveBaseUrl(baseUrl);
2038
+ const isRelativePath = trimmed.startsWith("/");
2039
+ if (isRelativePath && (!RELATIVE_ENDPOINT_PATTERN.test(trimmed) || trimmed.includes("\\") || !resolvedBaseUrl)) {
2040
+ return false;
2041
+ }
2042
+ try {
2043
+ const parsedBase = resolvedBaseUrl ? new URL(resolvedBaseUrl) : void 0;
2044
+ const parsed = resolvedBaseUrl ? new URL(trimmed, resolvedBaseUrl) : new URL(trimmed);
2045
+ if (isRelativePath && parsedBase && parsed.origin !== parsedBase.origin) {
2046
+ return false;
2047
+ }
2048
+ if (parsed.protocol === "https:") {
2049
+ return true;
2050
+ }
2051
+ return parsed.protocol === "http:" && LOCAL_HOSTS.has(parsed.hostname);
2052
+ } catch {
2053
+ return false;
2054
+ }
2055
+ }
2056
+ function parseRetryAfter(value, nowEpochMs) {
2057
+ if (!value) {
2058
+ return void 0;
2059
+ }
2060
+ const seconds = Number(value.trim());
2061
+ if (Number.isFinite(seconds) && seconds >= 0) {
2062
+ return Math.min(MAX_RETRY_AFTER_MS, Math.round(seconds * 1e3));
2063
+ }
2064
+ const dateEpochMs = Date.parse(value);
2065
+ if (!Number.isFinite(dateEpochMs)) {
2066
+ return void 0;
2067
+ }
2068
+ return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, dateEpochMs - nowEpochMs));
2069
+ }
2070
+ function isRetryableStatus(status) {
2071
+ return status === 408 || status === 425 || status === 429 || status >= 500;
2072
+ }
2073
+ function createDefaultSemanticJourneyAggregateTransport(options = {}) {
2074
+ const fetchImplementation = options.fetch ?? globalThis.fetch;
2075
+ const now = options.now ?? (() => Date.now());
2076
+ return async (request) => {
2077
+ if (!isSecureSemanticJourneyEndpoint(request.endpoint, options.baseUrl)) {
2078
+ throw new SemanticJourneyTransportError("rejected", false);
2079
+ }
2080
+ if (typeof fetchImplementation !== "function") {
2081
+ throw new SemanticJourneyTransportError("network_failure", true);
2082
+ }
2083
+ let resolvedEndpoint = request.endpoint;
2084
+ if (request.endpoint.startsWith("/")) {
2085
+ const base = resolveBaseUrl(options.baseUrl);
2086
+ if (!base) {
2087
+ throw new SemanticJourneyTransportError("rejected", false);
2088
+ }
2089
+ try {
2090
+ resolvedEndpoint = new URL(request.endpoint, base).toString();
2091
+ } catch {
2092
+ throw new SemanticJourneyTransportError("rejected", false);
2093
+ }
2094
+ }
2095
+ let response;
2096
+ try {
2097
+ response = await fetchImplementation(resolvedEndpoint, {
2098
+ method: "POST",
2099
+ body: request.body,
2100
+ headers: request.headers,
2101
+ keepalive: request.keepalive ?? false,
2102
+ signal: request.signal,
2103
+ credentials: "omit",
2104
+ referrerPolicy: "no-referrer",
2105
+ redirect: "error"
2106
+ });
2107
+ } catch {
2108
+ if (request.signal.aborted) {
2109
+ throw new SemanticJourneyTransportError("aborted", true);
2110
+ }
2111
+ throw new SemanticJourneyTransportError("network_failure", true);
2112
+ }
2113
+ if (!response.ok) {
2114
+ throw new SemanticJourneyTransportError(
2115
+ "rejected",
2116
+ isRetryableStatus(response.status),
2117
+ response.status,
2118
+ parseRetryAfter(response.headers.get("retry-after"), now())
2119
+ );
2120
+ }
2121
+ };
2122
+ }
2123
+
2124
+ // src/journey/receipt.ts
2125
+ var SEMANTIC_JOURNEY_RECEIPT_HEADER = "x-plasius-journey-receipt";
2126
+ var SEMANTIC_JOURNEY_RECEIPT_VERSION = "1";
2127
+ var SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT = 4;
2128
+ var SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES = 512;
2129
+ var RECEIPT_FIELDS = [
2130
+ "version",
2131
+ "name",
2132
+ "outcome",
2133
+ "phase",
2134
+ "effect"
2135
+ ];
2136
+ var RECEIPT_OUTCOMES = [
2137
+ "unknown",
2138
+ "success",
2139
+ "failure",
2140
+ "cancelled",
2141
+ "denied"
2142
+ ];
2143
+ var RECEIPT_PHASES = [
2144
+ "intent",
2145
+ "start",
2146
+ "progress",
2147
+ "end",
2148
+ "effect"
2149
+ ];
2150
+ var VISIBLE_ASCII = /^[\x21-\x7e]+$/;
2151
+ var SERIALIZE_ERROR_MESSAGE = "Invalid semantic journey receipt.";
2152
+ function isReceiptOutcome(value) {
2153
+ return typeof value === "string" && RECEIPT_OUTCOMES.includes(value);
2154
+ }
2155
+ function isReceiptPhase(value) {
2156
+ return typeof value === "string" && RECEIPT_PHASES.includes(value);
2157
+ }
2158
+ function hasCanonicalFields(value) {
2159
+ const keys = Object.keys(value);
2160
+ return keys.length === RECEIPT_FIELDS.length && RECEIPT_FIELDS.every((field2) => keys.includes(field2));
2161
+ }
2162
+ function isValidReceipt(value, catalogue) {
2163
+ if (typeof value !== "object" || value === null || Array.isArray(value) || !hasCanonicalFields(value)) {
2164
+ return false;
2165
+ }
2166
+ const receipt = value;
2167
+ const definition = isJourneyToken(receipt.name) ? getJourneyEventDefinition(catalogue, receipt.name) : void 0;
2168
+ return receipt.version === SEMANTIC_JOURNEY_RECEIPT_VERSION && definition !== void 0 && isReceiptOutcome(receipt.outcome) && isReceiptPhase(receipt.phase) && isJourneyToken(receipt.effect) && (definition.effects ?? []).includes(receipt.effect);
2169
+ }
2170
+ function serializeReceipt(receipt) {
2171
+ return `version=${receipt.version};name=${receipt.name};outcome=${receipt.outcome};phase=${receipt.phase};effect=${receipt.effect}`;
2172
+ }
2173
+ function parseCanonicalField(field2, expectedName) {
2174
+ const prefix = `${expectedName}=`;
2175
+ if (!field2.startsWith(prefix)) {
2176
+ return void 0;
2177
+ }
2178
+ const value = field2.slice(prefix.length);
2179
+ return value.length > 0 && !value.includes("=") ? value : void 0;
2180
+ }
2181
+ function parseReceipt(encoded, catalogue) {
2182
+ const fields = encoded.split(";");
2183
+ if (fields.length !== RECEIPT_FIELDS.length) {
2184
+ return void 0;
2185
+ }
2186
+ const version = parseCanonicalField(fields[0] ?? "", "version");
2187
+ const name = parseCanonicalField(fields[1] ?? "", "name");
2188
+ const outcome = parseCanonicalField(fields[2] ?? "", "outcome");
2189
+ const phase = parseCanonicalField(fields[3] ?? "", "phase");
2190
+ const effect = parseCanonicalField(fields[4] ?? "", "effect");
2191
+ const candidate = { version, name, outcome, phase, effect };
2192
+ return isValidReceipt(candidate, catalogue) ? candidate : void 0;
2193
+ }
2194
+ function serializeSemanticJourneyReceipts(receipts, catalogue) {
2195
+ try {
2196
+ if (!Array.isArray(receipts) || receipts.length > SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT || !receipts.every((receipt) => isValidReceipt(receipt, catalogue))) {
2197
+ throw new Error(SERIALIZE_ERROR_MESSAGE);
2198
+ }
2199
+ const header = receipts.map(serializeReceipt).join(",");
2200
+ if (header.length > SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES) {
2201
+ throw new Error(SERIALIZE_ERROR_MESSAGE);
2202
+ }
2203
+ return header;
2204
+ } catch {
2205
+ throw new Error(SERIALIZE_ERROR_MESSAGE);
2206
+ }
2207
+ }
2208
+ function parseSemanticJourneyReceipts(header, catalogue) {
2209
+ if (typeof header !== "string" || header.length === 0) {
2210
+ return [];
2211
+ }
2212
+ if (header.length > SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES || !VISIBLE_ASCII.test(header)) {
2213
+ return [];
2214
+ }
2215
+ try {
2216
+ const encodedReceipts = header.split(",");
2217
+ if (encodedReceipts.length > SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT) {
2218
+ return [];
2219
+ }
2220
+ const receipts = [];
2221
+ for (const encoded of encodedReceipts) {
2222
+ const receipt = parseReceipt(encoded, catalogue);
2223
+ if (!receipt) {
2224
+ return [];
2225
+ }
2226
+ receipts.push(receipt);
2227
+ }
2228
+ return receipts;
2229
+ } catch {
2230
+ return [];
2231
+ }
2232
+ }
2233
+
2234
+ // src/journey/replay.ts
2235
+ var MAX_EVENTS = 5e3;
2236
+ var MAX_GROUP_NODES = 32;
2237
+ var MAX_EVENT_ATTRIBUTES2 = 32;
2238
+ var MAX_CATALOG_SOURCES2 = 64;
2239
+ var MAX_GRAPH_EDGES = 25e4;
2240
+ var MAX_EVIDENCE_ITEMS = 5e3;
2241
+ var MAX_EVIDENCE_EVENT_IDS = 32;
2242
+ var EVENT_REQUIRED_FIELDS = /* @__PURE__ */ new Set([
2243
+ "schemaVersion",
2244
+ "eventId",
2245
+ "journeyId",
2246
+ "traceId",
2247
+ "spanId",
2248
+ "producerId",
2249
+ "producerSequence",
2250
+ "occurredAtEpochMs",
2251
+ "source",
2252
+ "channel",
2253
+ "runtime",
2254
+ "name",
2255
+ "category",
2256
+ "phase",
2257
+ "outcome",
2258
+ "attributes",
2259
+ "privacy"
2260
+ ]);
2261
+ var EVENT_FIELDS = /* @__PURE__ */ new Set([
2262
+ ...EVENT_REQUIRED_FIELDS,
2263
+ "parentSpanId",
2264
+ "causedByEventId",
2265
+ "modality",
2266
+ "target"
2267
+ ]);
2268
+ var TARGET_FIELDS2 = /* @__PURE__ */ new Set(["type", "id"]);
2269
+ var PRIVACY_FIELDS = /* @__PURE__ */ new Set([
2270
+ "mode",
2271
+ "policyVersion",
2272
+ "droppedAttributeCount"
2273
+ ]);
2274
+ var CATALOG_FIELDS = /* @__PURE__ */ new Set(["sources", "definitions"]);
2275
+ var EVIDENCE_EXPLANATIONS = {
2276
+ "empty-journey": "No semantic journey evidence was supplied",
2277
+ "invalid-event": "Semantic journey evidence failed strict validation",
2278
+ "evidence-limit": "Semantic journey evidence exceeded a safety limit",
2279
+ "missing-parent": "Parent span evidence is missing",
2280
+ "missing-cause": "Caused-by event evidence is missing",
2281
+ "sequence-gap": "Producer sequence evidence has a gap",
2282
+ "sequence-fork": "Producer sequence evidence has a fork",
2283
+ cycle: "Causal evidence contains a cycle",
2284
+ "mixed-journey": "Evidence contains more than one journey"
2285
+ };
2286
+ var INVALID_EVIDENCE_CODES = /* @__PURE__ */ new Set([
2287
+ "empty-journey",
2288
+ "invalid-event",
2289
+ "evidence-limit",
2290
+ "cycle",
2291
+ "mixed-journey"
2292
+ ]);
2293
+ var PHASE_RANK = {
2294
+ intent: 0,
2295
+ start: 1,
2296
+ progress: 2,
2297
+ effect: 3,
2298
+ end: 4
2299
+ };
2300
+ var InvalidRuntimeEvidenceError = class extends Error {
2301
+ };
2302
+ var EvidenceLimitError = class extends Error {
2303
+ };
2304
+ function invalidRuntimeEvidence() {
2305
+ throw new InvalidRuntimeEvidenceError();
2306
+ }
2307
+ function evidenceLimit() {
2308
+ throw new EvidenceLimitError();
2309
+ }
2310
+ function compareTokens(left, right) {
2311
+ if (left < right) {
2312
+ return -1;
2313
+ }
2314
+ if (left > right) {
2315
+ return 1;
2316
+ }
2317
+ return 0;
2318
+ }
2319
+ function compareOptionalTokens(left, right) {
2320
+ return compareTokens(left ?? "", right ?? "");
2321
+ }
2322
+ function compareEventsForOrder(left, right) {
2323
+ const timestampComparison = left.occurredAtEpochMs - right.occurredAtEpochMs;
2324
+ return timestampComparison || compareTokens(left.eventId, right.eventId);
2325
+ }
2326
+ function compareNodes(left, right) {
2327
+ return compareEventsForOrder(left.event, right.event);
2328
+ }
2329
+ function evidence(code, details = {}) {
2330
+ return {
2331
+ code,
2332
+ severity: INVALID_EVIDENCE_CODES.has(code) ? "invalid" : "partial",
2333
+ explanation: EVIDENCE_EXPLANATIONS[code],
2334
+ ...details
2335
+ };
2336
+ }
2337
+ function invalidReplay(code) {
2338
+ return {
2339
+ completeness: "invalid",
2340
+ steps: [],
2341
+ evidence: [evidence(code)]
2342
+ };
2343
+ }
2344
+ function appendEvidence(items, item) {
2345
+ if (items.length >= MAX_EVIDENCE_ITEMS) {
2346
+ evidenceLimit();
2347
+ }
2348
+ items.push(item);
2349
+ }
2350
+ function compareEvidence(left, right) {
2351
+ const codeComparison = compareTokens(left.code, right.code);
2352
+ if (codeComparison !== 0) {
2353
+ return codeComparison;
2354
+ }
2355
+ const tokenComparisons = [
2356
+ compareOptionalTokens(left.eventId, right.eventId),
2357
+ compareOptionalTokens(left.relatedEventId, right.relatedEventId),
2358
+ compareOptionalTokens(left.spanId, right.spanId),
2359
+ compareOptionalTokens(left.producerId, right.producerId),
2360
+ compareTokens(
2361
+ left.eventIds?.join(":") ?? "",
2362
+ right.eventIds?.join(":") ?? ""
2363
+ )
2364
+ ];
2365
+ const tokenComparison = tokenComparisons.find((comparison) => comparison !== 0) ?? 0;
2366
+ if (tokenComparison !== 0) {
2367
+ return tokenComparison;
2368
+ }
2369
+ const numericFields = [
2370
+ "producerSequence",
2371
+ "expectedSequence",
2372
+ "observedSequence",
2373
+ "observedCount"
2374
+ ];
2375
+ for (const field2 of numericFields) {
2376
+ const comparison = (left[field2] ?? -1) - (right[field2] ?? -1);
2377
+ if (comparison !== 0) {
2378
+ return comparison;
2379
+ }
2380
+ }
2381
+ return 0;
2382
+ }
2383
+ function isPlainRecord(value) {
2384
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
2385
+ return false;
2386
+ }
2387
+ const prototype = Object.getPrototypeOf(value);
2388
+ return prototype === Object.prototype || prototype === null;
2389
+ }
2390
+ function readDataRecord(value, allowedFields, requiredFields = /* @__PURE__ */ new Set(), maximumFields = Number.MAX_SAFE_INTEGER) {
2391
+ if (!isPlainRecord(value)) {
2392
+ return invalidRuntimeEvidence();
2393
+ }
2394
+ const keys = Reflect.ownKeys(value);
2395
+ if (keys.length > maximumFields || keys.some((key) => typeof key !== "string")) {
2396
+ return invalidRuntimeEvidence();
2397
+ }
2398
+ const stringKeys = keys;
2399
+ if (allowedFields && stringKeys.some((key) => !allowedFields.has(key)) || [...requiredFields].some((field2) => !stringKeys.includes(field2))) {
2400
+ return invalidRuntimeEvidence();
2401
+ }
2402
+ const result = /* @__PURE__ */ Object.create(null);
2403
+ for (const key of stringKeys) {
2404
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
2405
+ if (descriptor === void 0 || !("value" in descriptor)) {
2406
+ return invalidRuntimeEvidence();
2407
+ }
2408
+ result[key] = descriptor.value;
2409
+ }
2410
+ return result;
2411
+ }
2412
+ function readDataArray(value, maximumItems) {
2413
+ if (!Array.isArray(value)) {
2414
+ return invalidRuntimeEvidence();
2415
+ }
2416
+ const lengthDescriptor = Object.getOwnPropertyDescriptor(value, "length");
2417
+ if (lengthDescriptor === void 0 || !("value" in lengthDescriptor) || !Number.isSafeInteger(lengthDescriptor.value) || lengthDescriptor.value < 0) {
2418
+ return invalidRuntimeEvidence();
2419
+ }
2420
+ if (lengthDescriptor.value > maximumItems) {
2421
+ return evidenceLimit();
2422
+ }
2423
+ const result = [];
2424
+ for (let index = 0; index < lengthDescriptor.value; index += 1) {
2425
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
2426
+ if (descriptor === void 0 || !("value" in descriptor)) {
2427
+ return invalidRuntimeEvidence();
2428
+ }
2429
+ result.push(descriptor.value);
2430
+ }
2431
+ return result;
2432
+ }
2433
+ function readAllowedSources(catalogue) {
2434
+ const catalogRecord = readDataRecord(
2435
+ catalogue,
2436
+ CATALOG_FIELDS,
2437
+ CATALOG_FIELDS,
2438
+ CATALOG_FIELDS.size
2439
+ );
2440
+ const sourceValues = readDataArray(
2441
+ catalogRecord.sources,
2442
+ MAX_CATALOG_SOURCES2
2443
+ );
2444
+ if (sourceValues.length === 0) {
2445
+ return invalidRuntimeEvidence();
2446
+ }
2447
+ const sources = /* @__PURE__ */ new Set();
2448
+ for (const source of sourceValues) {
2449
+ if (!isSemanticSource(source) || sources.has(source)) {
2450
+ return invalidRuntimeEvidence();
2451
+ }
2452
+ sources.add(source);
2453
+ }
2454
+ return sources;
2455
+ }
2456
+ function isValidChannelRuntime(channel, runtime) {
2457
+ return channel === "frontend" && runtime === "browser" || channel === "backend" && runtime === "server";
2458
+ }
2459
+ function readOptionalIdentifier(value, validator) {
2460
+ if (value === void 0) {
2461
+ return void 0;
2462
+ }
2463
+ return validator(value) ? value : invalidRuntimeEvidence();
2464
+ }
2465
+ function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
2466
+ const record = readDataRecord(
2467
+ candidate,
2468
+ EVENT_FIELDS,
2469
+ EVENT_REQUIRED_FIELDS,
2470
+ EVENT_FIELDS.size
2471
+ );
2472
+ if (record.schemaVersion !== "2.0" || !isEventId(record.eventId) || !isJourneyId(record.journeyId) || !isTraceId(record.traceId) || !isSpanId(record.spanId) || !isProducerId(record.producerId) || !Number.isSafeInteger(record.producerSequence) || record.producerSequence < 1 || !Number.isSafeInteger(record.occurredAtEpochMs) || record.occurredAtEpochMs < 0 || !isSemanticSource(record.source) || !allowedSources.has(record.source) || !isValidChannelRuntime(record.channel, record.runtime)) {
2473
+ return invalidRuntimeEvidence();
2474
+ }
2475
+ const parentSpanId = readOptionalIdentifier(record.parentSpanId, isSpanId);
2476
+ const causedByEventId = readOptionalIdentifier(
2477
+ record.causedByEventId,
2478
+ isEventId
2479
+ );
2480
+ const attributes = readDataRecord(
2481
+ record.attributes,
2482
+ void 0,
2483
+ /* @__PURE__ */ new Set(),
2484
+ MAX_EVENT_ATTRIBUTES2
2485
+ );
2486
+ const privacy = readDataRecord(
2487
+ record.privacy,
2488
+ PRIVACY_FIELDS,
2489
+ PRIVACY_FIELDS,
2490
+ PRIVACY_FIELDS.size
2491
+ );
2492
+ if (privacy.mode !== "strict" || privacy.policyVersion !== SEMANTIC_JOURNEY_STRICT_POLICY_VERSION || privacy.droppedAttributeCount !== 0) {
2493
+ return invalidRuntimeEvidence();
2494
+ }
2495
+ let target;
2496
+ if (record.target !== void 0) {
2497
+ const targetRecord = readDataRecord(
2498
+ record.target,
2499
+ TARGET_FIELDS2,
2500
+ TARGET_FIELDS2,
2501
+ TARGET_FIELDS2.size
2502
+ );
2503
+ if (!isSemanticToken(targetRecord.type) || !isSemanticToken(targetRecord.id)) {
2504
+ return invalidRuntimeEvidence();
2505
+ }
2506
+ target = { type: targetRecord.type, id: targetRecord.id };
2507
+ }
2508
+ const input = {
2509
+ name: record.name,
2510
+ category: record.category,
2511
+ phase: record.phase,
2512
+ outcome: record.outcome,
2513
+ ...record.modality === void 0 ? {} : { modality: record.modality },
2514
+ ...target === void 0 ? {} : { target },
2515
+ attributes
2516
+ };
2517
+ const validated = validateSemanticJourneyEventInput(catalogue, input);
2518
+ return Object.freeze({
2519
+ schemaVersion: "2.0",
2520
+ eventId: record.eventId,
2521
+ journeyId: record.journeyId,
2522
+ traceId: record.traceId,
2523
+ spanId: record.spanId,
2524
+ ...parentSpanId === void 0 ? {} : { parentSpanId },
2525
+ ...causedByEventId === void 0 ? {} : { causedByEventId },
2526
+ producerId: record.producerId,
2527
+ producerSequence: record.producerSequence,
2528
+ occurredAtEpochMs: record.occurredAtEpochMs,
2529
+ source: record.source,
2530
+ channel: record.channel,
2531
+ runtime: record.runtime,
2532
+ name: validated.name,
2533
+ category: validated.category,
2534
+ phase: validated.phase,
2535
+ outcome: validated.outcome,
2536
+ ...validated.modality === void 0 ? {} : { modality: validated.modality },
2537
+ ...validated.target === void 0 ? {} : { target: validated.target },
2538
+ attributes: Object.freeze({ ...validated.attributes }),
2539
+ privacy: Object.freeze({
2540
+ mode: "strict",
2541
+ policyVersion: privacy.policyVersion,
2542
+ droppedAttributeCount: 0
2543
+ })
2544
+ });
2545
+ }
2546
+ function attributesEqual(left, right) {
2547
+ const leftKeys = Object.keys(left).sort(compareTokens);
2548
+ const rightKeys = Object.keys(right).sort(compareTokens);
2549
+ return leftKeys.length === rightKeys.length && leftKeys.every(
2550
+ (key, index) => key === rightKeys[index] && Object.is(left[key], right[key])
2551
+ );
2552
+ }
2553
+ function eventsEqual(left, right) {
2554
+ 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);
2555
+ }
2556
+ function deduplicateEvents(events) {
2557
+ const byEventId = /* @__PURE__ */ new Map();
2558
+ for (const event of events) {
2559
+ const existing = byEventId.get(event.eventId);
2560
+ if (existing && !eventsEqual(existing, event)) {
2561
+ return invalidRuntimeEvidence();
2562
+ }
2563
+ byEventId.set(event.eventId, existing ?? event);
2564
+ }
2565
+ return [...byEventId.values()].sort(compareEventsForOrder);
2566
+ }
2567
+ function addEdge(from, to, limits) {
2568
+ if (from.successors.has(to.event.eventId)) {
2569
+ return;
2570
+ }
2571
+ if (limits.edgeCount >= MAX_GRAPH_EDGES) {
2572
+ evidenceLimit();
2573
+ }
2574
+ limits.edgeCount += 1;
2575
+ from.successors.add(to.event.eventId);
2576
+ to.predecessors.add(from.event.eventId);
2577
+ }
2578
+ function addBoundedNode(group, node) {
2579
+ if (group.length >= MAX_GROUP_NODES) {
2580
+ evidenceLimit();
2581
+ }
2582
+ group.push(node);
2583
+ }
2584
+ function compareSpanAnchors(left, right) {
2585
+ const phaseComparison = PHASE_RANK[left.event.phase] - PHASE_RANK[right.event.phase];
2586
+ return phaseComparison || compareNodes(left, right);
2587
+ }
2588
+ function buildReferenceEdges(nodes, nodesByEventId, reconstructionEvidence, limits) {
2589
+ const spansByTrace = /* @__PURE__ */ new Map();
2590
+ for (const node of nodes) {
2591
+ let spans = spansByTrace.get(node.event.traceId);
2592
+ if (!spans) {
2593
+ spans = /* @__PURE__ */ new Map();
2594
+ spansByTrace.set(node.event.traceId, spans);
2595
+ }
2596
+ const spanNodes = spans.get(node.event.spanId) ?? [];
2597
+ addBoundedNode(spanNodes, node);
2598
+ spans.set(node.event.spanId, spanNodes);
2599
+ }
2600
+ for (const node of nodes) {
2601
+ const { event } = node;
2602
+ if (event.causedByEventId) {
2603
+ const cause = nodesByEventId.get(event.causedByEventId);
2604
+ if (cause) {
2605
+ addEdge(cause, node, limits);
2606
+ } else {
2607
+ appendEvidence(
2608
+ reconstructionEvidence,
2609
+ evidence("missing-cause", {
2610
+ eventId: event.eventId,
2611
+ relatedEventId: event.causedByEventId
2612
+ })
2613
+ );
2614
+ }
2615
+ }
2616
+ if (!event.parentSpanId) {
2617
+ continue;
2618
+ }
2619
+ if (event.parentSpanId === event.spanId) {
2620
+ addEdge(node, node, limits);
2621
+ continue;
2622
+ }
2623
+ const parentCandidates = spansByTrace.get(event.traceId)?.get(event.parentSpanId);
2624
+ if (!parentCandidates || parentCandidates.length === 0) {
2625
+ appendEvidence(
2626
+ reconstructionEvidence,
2627
+ evidence("missing-parent", {
2628
+ eventId: event.eventId,
2629
+ spanId: event.parentSpanId
2630
+ })
2631
+ );
2632
+ continue;
2633
+ }
2634
+ const parent = [...parentCandidates].sort(compareSpanAnchors)[0];
2635
+ if (parent) {
2636
+ addEdge(parent, node, limits);
2637
+ }
2638
+ }
2639
+ }
2640
+ function sortedEventIds(nodes) {
2641
+ if (nodes.length > MAX_EVIDENCE_EVENT_IDS) {
2642
+ return evidenceLimit();
2643
+ }
2644
+ return nodes.map((node) => node.event.eventId).sort(compareTokens);
2645
+ }
2646
+ function buildProducerEdges(nodes, reconstructionEvidence, limits) {
2647
+ const producers = /* @__PURE__ */ new Map();
2648
+ for (const node of nodes) {
2649
+ let sequences = producers.get(node.event.producerId);
2650
+ if (!sequences) {
2651
+ sequences = /* @__PURE__ */ new Map();
2652
+ producers.set(node.event.producerId, sequences);
2653
+ }
2654
+ const sequenceNodes = sequences.get(node.event.producerSequence) ?? [];
2655
+ addBoundedNode(sequenceNodes, node);
2656
+ sequences.set(node.event.producerSequence, sequenceNodes);
2657
+ }
2658
+ const producerEntries = [...producers.entries()].sort(
2659
+ ([left], [right]) => compareTokens(left, right)
2660
+ );
2661
+ for (const [producerId, sequences] of producerEntries) {
2662
+ const sequenceEntries = [...sequences.entries()].sort(
2663
+ ([left], [right]) => left - right
2664
+ );
2665
+ const firstSequence = sequenceEntries[0]?.[0];
2666
+ if (firstSequence !== void 0 && firstSequence > 1) {
2667
+ appendEvidence(
2668
+ reconstructionEvidence,
2669
+ evidence("sequence-gap", {
2670
+ producerId,
2671
+ expectedSequence: 1,
2672
+ observedSequence: firstSequence
2673
+ })
2674
+ );
2675
+ }
2676
+ for (const [sequence, sequenceNodes] of sequenceEntries) {
2677
+ if (sequenceNodes.length > 1) {
2678
+ appendEvidence(
2679
+ reconstructionEvidence,
2680
+ evidence("sequence-fork", {
2681
+ producerId,
2682
+ producerSequence: sequence,
2683
+ eventIds: sortedEventIds(sequenceNodes)
2684
+ })
2685
+ );
2686
+ }
2687
+ }
2688
+ for (let index = 1; index < sequenceEntries.length; index += 1) {
2689
+ const previousEntry = sequenceEntries[index - 1];
2690
+ const currentEntry = sequenceEntries[index];
2691
+ if (!previousEntry || !currentEntry) {
2692
+ continue;
2693
+ }
2694
+ const [previousSequence, previousNodes] = previousEntry;
2695
+ const [currentSequence, currentNodes] = currentEntry;
2696
+ if (currentSequence > previousSequence + 1) {
2697
+ appendEvidence(
2698
+ reconstructionEvidence,
2699
+ evidence("sequence-gap", {
2700
+ producerId,
2701
+ expectedSequence: previousSequence + 1,
2702
+ observedSequence: currentSequence
2703
+ })
2704
+ );
2705
+ }
2706
+ for (const previous of previousNodes) {
2707
+ for (const current of currentNodes) {
2708
+ addEdge(previous, current, limits);
2709
+ }
2710
+ }
2711
+ }
2712
+ }
2713
+ }
2714
+ function adjacency(identifiers, nodesByEventId) {
2715
+ const result = [];
2716
+ for (const identifier of identifiers) {
2717
+ const node = nodesByEventId.get(identifier);
2718
+ if (!node) {
2719
+ return invalidRuntimeEvidence();
2720
+ }
2721
+ result.push(node);
2722
+ }
2723
+ return result.sort(compareNodes);
2724
+ }
2725
+ function stronglyConnectedComponents(nodes, nodesByEventId) {
2726
+ const successors = new Map(
2727
+ nodes.map((node) => [
2728
+ node.event.eventId,
2729
+ adjacency(node.successors, nodesByEventId)
2730
+ ])
2731
+ );
2732
+ const predecessors = new Map(
2733
+ nodes.map((node) => [
2734
+ node.event.eventId,
2735
+ adjacency(node.predecessors, nodesByEventId)
2736
+ ])
2737
+ );
2738
+ const finished = [];
2739
+ const visited = /* @__PURE__ */ new Set();
2740
+ for (const root of [...nodes].sort(compareNodes)) {
2741
+ if (visited.has(root.event.eventId)) {
2742
+ continue;
2743
+ }
2744
+ visited.add(root.event.eventId);
2745
+ const stack = [
2746
+ {
2747
+ node: root,
2748
+ adjacent: successors.get(root.event.eventId) ?? [],
2749
+ next: 0
2750
+ }
2751
+ ];
2752
+ while (stack.length > 0) {
2753
+ const frame = stack[stack.length - 1];
2754
+ if (!frame) {
2755
+ return invalidRuntimeEvidence();
2756
+ }
2757
+ const next = frame.adjacent[frame.next];
2758
+ if (next) {
2759
+ frame.next += 1;
2760
+ if (!visited.has(next.event.eventId)) {
2761
+ visited.add(next.event.eventId);
2762
+ stack.push({
2763
+ node: next,
2764
+ adjacent: successors.get(next.event.eventId) ?? [],
2765
+ next: 0
2766
+ });
2767
+ }
2768
+ } else {
2769
+ finished.push(frame.node);
2770
+ stack.pop();
2771
+ }
2772
+ }
2773
+ }
2774
+ const assigned = /* @__PURE__ */ new Set();
2775
+ const componentNodes = [];
2776
+ for (let index = finished.length - 1; index >= 0; index -= 1) {
2777
+ const root = finished[index];
2778
+ if (!root || assigned.has(root.event.eventId)) {
2779
+ continue;
2780
+ }
2781
+ const members = [];
2782
+ const stack = [root];
2783
+ assigned.add(root.event.eventId);
2784
+ while (stack.length > 0) {
2785
+ const current = stack.pop();
2786
+ if (!current) {
2787
+ return invalidRuntimeEvidence();
2788
+ }
2789
+ members.push(current);
2790
+ const adjacentNodes = predecessors.get(current.event.eventId) ?? [];
2791
+ for (let adjacentIndex = adjacentNodes.length - 1; adjacentIndex >= 0; adjacentIndex -= 1) {
2792
+ const predecessor = adjacentNodes[adjacentIndex];
2793
+ if (predecessor && !assigned.has(predecessor.event.eventId)) {
2794
+ assigned.add(predecessor.event.eventId);
2795
+ stack.push(predecessor);
2796
+ }
2797
+ }
2798
+ }
2799
+ componentNodes.push(members.sort(compareNodes));
2800
+ }
2801
+ const componentByEventId = /* @__PURE__ */ new Map();
2802
+ componentNodes.forEach((members, componentIndex) => {
2803
+ for (const member of members) {
2804
+ componentByEventId.set(member.event.eventId, componentIndex);
2805
+ }
2806
+ });
2807
+ const components = componentNodes.map((members, index) => ({
2808
+ index,
2809
+ nodes: members,
2810
+ predecessors: /* @__PURE__ */ new Set(),
2811
+ successors: /* @__PURE__ */ new Set()
2812
+ }));
2813
+ for (const node of nodes) {
2814
+ const fromIndex = componentByEventId.get(node.event.eventId);
2815
+ if (fromIndex === void 0) {
2816
+ return invalidRuntimeEvidence();
2817
+ }
2818
+ for (const successorId of node.successors) {
2819
+ const toIndex = componentByEventId.get(successorId);
2820
+ if (toIndex === void 0) {
2821
+ return invalidRuntimeEvidence();
2822
+ }
2823
+ if (fromIndex !== toIndex) {
2824
+ components[fromIndex]?.successors.add(toIndex);
2825
+ components[toIndex]?.predecessors.add(fromIndex);
2826
+ }
2827
+ }
2828
+ }
2829
+ return components;
2830
+ }
2831
+ function compareComponents(left, right) {
2832
+ const leftAnchor = left.nodes[0];
2833
+ const rightAnchor = right.nodes[0];
2834
+ if (!leftAnchor || !rightAnchor) {
2835
+ return left.index - right.index;
2836
+ }
2837
+ return compareNodes(leftAnchor, rightAnchor) || left.index - right.index;
2838
+ }
2839
+ function condensedCausalOrder(components) {
2840
+ const indegrees = new Map(
2841
+ components.map((component) => [
2842
+ component.index,
2843
+ component.predecessors.size
2844
+ ])
2845
+ );
2846
+ const ready = components.filter((component) => component.predecessors.size === 0).sort(compareComponents);
2847
+ const ordered = [];
2848
+ while (ready.length > 0) {
2849
+ const current = ready.shift();
2850
+ if (!current) {
2851
+ return invalidRuntimeEvidence();
2852
+ }
2853
+ ordered.push(...current.nodes);
2854
+ const successors = [...current.successors].map((index) => components[index]).filter((component) => component !== void 0).sort(compareComponents);
2855
+ for (const successor of successors) {
2856
+ const remaining = (indegrees.get(successor.index) ?? 0) - 1;
2857
+ indegrees.set(successor.index, remaining);
2858
+ if (remaining === 0) {
2859
+ ready.push(successor);
2860
+ }
2861
+ }
2862
+ ready.sort(compareComponents);
2863
+ }
2864
+ if (ordered.length !== components.reduce((count, item) => count + item.nodes.length, 0)) {
2865
+ return invalidRuntimeEvidence();
2866
+ }
2867
+ return ordered;
2868
+ }
2869
+ function addCycleEvidence(components, reconstructionEvidence) {
2870
+ for (const component of components) {
2871
+ const first = component.nodes[0];
2872
+ const isCycle = component.nodes.length > 1 || first !== void 0 && first.successors.has(first.event.eventId);
2873
+ if (isCycle) {
2874
+ appendEvidence(
2875
+ reconstructionEvidence,
2876
+ evidence("cycle", { eventIds: sortedEventIds(component.nodes) })
2877
+ );
2878
+ }
2879
+ }
2880
+ }
2881
+ function semanticToken(value) {
2882
+ return isSemanticToken(value) ? value : "unknown";
2883
+ }
2884
+ function genericExplanation(event) {
2885
+ const tokens = [
2886
+ event.channel,
2887
+ event.category,
2888
+ semanticToken(event.name),
2889
+ event.phase
2890
+ ];
2891
+ if (event.modality) {
2892
+ tokens.push("by", event.modality);
2893
+ }
2894
+ if (event.target) {
2895
+ tokens.push(
2896
+ "target",
2897
+ semanticToken(event.target.type),
2898
+ semanticToken(event.target.id)
2899
+ );
2900
+ }
2901
+ tokens.push("outcome", event.outcome);
2902
+ return tokens.join(" ");
2903
+ }
2904
+ function toStep(node) {
2905
+ const { event } = node;
2906
+ return {
2907
+ eventId: event.eventId,
2908
+ traceId: event.traceId,
2909
+ spanId: event.spanId,
2910
+ ...event.parentSpanId ? { parentSpanId: event.parentSpanId } : {},
2911
+ ...event.causedByEventId ? { causedByEventId: event.causedByEventId } : {},
2912
+ producerId: event.producerId,
2913
+ producerSequence: event.producerSequence,
2914
+ occurredAtEpochMs: event.occurredAtEpochMs,
2915
+ source: semanticToken(event.source),
2916
+ channel: event.channel,
2917
+ runtime: event.runtime,
2918
+ name: semanticToken(event.name),
2919
+ category: event.category,
2920
+ phase: event.phase,
2921
+ outcome: event.outcome,
2922
+ ...event.modality ? { modality: event.modality } : {},
2923
+ ...event.target ? {
2924
+ target: {
2925
+ type: semanticToken(event.target.type),
2926
+ id: semanticToken(event.target.id)
2927
+ }
2928
+ } : {},
2929
+ predecessorEventIds: [...node.predecessors].sort(compareTokens),
2930
+ explanation: genericExplanation(event)
2931
+ };
2932
+ }
2933
+ function completenessFromEvidence(reconstructionEvidence) {
2934
+ if (reconstructionEvidence.some((item) => item.severity === "invalid")) {
2935
+ return "invalid";
2936
+ }
2937
+ return reconstructionEvidence.length > 0 ? "partial" : "complete";
2938
+ }
2939
+ function reconstructSemanticJourneyUnsafe(catalogue, events) {
2940
+ const allowedSources = readAllowedSources(catalogue);
2941
+ const candidates = readDataArray(events, MAX_EVENTS);
2942
+ if (candidates.length === 0) {
2943
+ return {
2944
+ completeness: "invalid",
2945
+ steps: [],
2946
+ evidence: [evidence("empty-journey", { observedCount: 0 })]
2947
+ };
2948
+ }
2949
+ const normalized = candidates.map(
2950
+ (candidate) => normalizeRuntimeEvent(catalogue, allowedSources, candidate)
2951
+ );
2952
+ const journeyIds = new Set(normalized.map((event) => event.journeyId));
2953
+ if (journeyIds.size !== 1) {
2954
+ return {
2955
+ completeness: "invalid",
2956
+ steps: [],
2957
+ evidence: [
2958
+ evidence("mixed-journey", {
2959
+ observedCount: journeyIds.size
2960
+ })
2961
+ ]
2962
+ };
2963
+ }
2964
+ const deduplicatedEvents = deduplicateEvents(normalized);
2965
+ const nodes = deduplicatedEvents.map((event) => ({
2966
+ event,
2967
+ predecessors: /* @__PURE__ */ new Set(),
2968
+ successors: /* @__PURE__ */ new Set()
2969
+ }));
2970
+ const nodesByEventId = new Map(
2971
+ nodes.map((node) => [node.event.eventId, node])
2972
+ );
2973
+ const reconstructionEvidence = [];
2974
+ const limits = { edgeCount: 0 };
2975
+ buildReferenceEdges(
2976
+ nodes,
2977
+ nodesByEventId,
2978
+ reconstructionEvidence,
2979
+ limits
2980
+ );
2981
+ buildProducerEdges(nodes, reconstructionEvidence, limits);
2982
+ const components = stronglyConnectedComponents(nodes, nodesByEventId);
2983
+ addCycleEvidence(components, reconstructionEvidence);
2984
+ const ordered = condensedCausalOrder(components);
2985
+ reconstructionEvidence.sort(compareEvidence);
2986
+ const journeyId = normalized[0]?.journeyId;
2987
+ if (!journeyId) {
2988
+ return invalidRuntimeEvidence();
2989
+ }
2990
+ return {
2991
+ journeyId,
2992
+ completeness: completenessFromEvidence(reconstructionEvidence),
2993
+ steps: ordered.map(toStep),
2994
+ evidence: reconstructionEvidence
2995
+ };
2996
+ }
2997
+ function reconstructSemanticJourney(catalogue, events) {
2998
+ try {
2999
+ return reconstructSemanticJourneyUnsafe(catalogue, events);
3000
+ } catch (error) {
3001
+ return error instanceof EvidenceLimitError ? invalidReplay("evidence-limit") : invalidReplay("invalid-event");
3002
+ }
3003
+ }
3004
+
3005
+ // src/journey/browser.ts
3006
+ var EVENT_ATTRIBUTE = "data-plasius-event";
3007
+ var TARGET_TYPE_ATTRIBUTE = "data-plasius-target-type";
3008
+ var TARGET_ID_ATTRIBUTE = "data-plasius-target-id";
3009
+ var OBSERVED_EVENT_TYPES = [
3010
+ "click",
3011
+ "submit",
3012
+ "change",
3013
+ "toggle",
3014
+ "play",
3015
+ "pause",
3016
+ "ended",
3017
+ "drop"
3018
+ ];
3019
+ var EVENT_SEMANTICS = {
3020
+ click: { phase: "intent", outcome: "unknown" },
3021
+ submit: { phase: "intent", outcome: "unknown" },
3022
+ change: { phase: "effect", outcome: "success" },
3023
+ toggle: { phase: "effect", outcome: "success" },
3024
+ play: { phase: "start", outcome: "unknown" },
3025
+ pause: { phase: "progress", outcome: "success" },
3026
+ ended: { phase: "end", outcome: "success" },
3027
+ drop: { phase: "effect", outcome: "success" }
3028
+ };
3029
+ function isElement(value) {
3030
+ return typeof Element !== "undefined" && value instanceof Element;
3031
+ }
3032
+ function findAnnotatedElement(event, root) {
3033
+ const path = typeof event.composedPath === "function" ? event.composedPath() : [event.target].filter((candidate) => candidate !== null);
3034
+ for (const candidate of path) {
3035
+ if (isElement(candidate)) {
3036
+ const eventName = candidate.getAttribute(EVENT_ATTRIBUTE);
3037
+ if (eventName !== null) {
3038
+ return { element: candidate, eventName };
3039
+ }
3040
+ }
3041
+ if (candidate === root) {
3042
+ break;
3043
+ }
3044
+ }
3045
+ return void 0;
3046
+ }
3047
+ function readTarget(element) {
3048
+ const type = element.getAttribute(TARGET_TYPE_ATTRIBUTE);
3049
+ const id = element.getAttribute(TARGET_ID_ATTRIBUTE);
3050
+ if (type === null && id === null) {
3051
+ return void 0;
3052
+ }
3053
+ if (type === null || id === null || !isJourneyToken(type) || !isJourneyToken(id)) {
3054
+ return null;
3055
+ }
3056
+ return { type, id };
3057
+ }
3058
+ function inferClickModality(event) {
3059
+ if (event.type !== "click" || typeof MouseEvent === "undefined" || !(event instanceof MouseEvent)) {
3060
+ return void 0;
3061
+ }
3062
+ if (typeof PointerEvent !== "undefined" && event instanceof PointerEvent) {
3063
+ return event.pointerType === "touch" ? "touch" : "pointer";
3064
+ }
3065
+ return event.detail === 0 ? "keyboard" : "pointer";
3066
+ }
3067
+ function isObservedEventType(value) {
3068
+ return Object.hasOwn(EVENT_SEMANTICS, value);
3069
+ }
3070
+ function observeSemanticJourneyInteractions(config) {
3071
+ if (config.enabled !== true) {
3072
+ return () => void 0;
3073
+ }
3074
+ const root = config.root ?? (typeof document === "undefined" ? void 0 : document);
3075
+ if (!root) {
3076
+ return () => void 0;
3077
+ }
3078
+ const handleEvent = (event) => {
3079
+ if (!isObservedEventType(event.type)) {
3080
+ return;
3081
+ }
3082
+ const annotated = findAnnotatedElement(event, root);
3083
+ if (!annotated || !isJourneyToken(annotated.eventName)) {
3084
+ return;
3085
+ }
3086
+ const definition = getJourneyEventDefinition(config.catalogue, annotated.eventName);
3087
+ if (!definition) {
3088
+ return;
3089
+ }
3090
+ const semantics = EVENT_SEMANTICS[event.type];
3091
+ const target = readTarget(annotated.element);
3092
+ if (target === null) {
3093
+ return;
3094
+ }
3095
+ const modality = inferClickModality(event);
3096
+ const input = {
3097
+ name: annotated.eventName,
3098
+ category: definition.category,
3099
+ phase: semantics.phase,
3100
+ outcome: semantics.outcome,
3101
+ ...target ? { target } : {},
3102
+ ...modality ? { modality } : {}
3103
+ };
3104
+ try {
3105
+ validateSemanticJourneyEventInput(config.catalogue, input);
3106
+ config.onEvent(input);
3107
+ } catch {
3108
+ }
3109
+ };
3110
+ for (const eventType of OBSERVED_EVENT_TYPES) {
3111
+ root.addEventListener(eventType, handleEvent, true);
3112
+ }
3113
+ return () => {
3114
+ for (const eventType of OBSERVED_EVENT_TYPES) {
3115
+ root.removeEventListener(eventType, handleEvent, true);
3116
+ }
3117
+ };
3118
+ }
3119
+
3120
+ // src/journey/client.ts
3121
+ var DEFAULT_AGGREGATE_FLUSH_INTERVAL_MS = 6e4;
3122
+ var DEFAULT_AGGREGATE_MAX_COUNTERS = 50;
3123
+ var DEFAULT_AGGREGATE_MAX_BYTES = 48 * 1024;
3124
+ var DEFAULT_MAX_BATCHES_PER_FLUSH = 10;
3125
+ var DEFAULT_MAX_QUEUE_EVENTS = 1e3;
3126
+ var DEFAULT_MAX_QUEUE_BYTES = 1024 * 1024;
3127
+ var DEFAULT_MAX_EVENT_AGE_MS = 30 * 60 * 1e3;
3128
+ var DEFAULT_EPISODE_IDLE_MS = 30 * 60 * 1e3;
3129
+ var DEFAULT_COALESCE_WINDOW_MS = 1e3;
3130
+ var DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
3131
+ var DEFAULT_MAX_RETRIES = 2;
3132
+ var DEFAULT_RETRY_BASE_DELAY_MS = 250;
3133
+ var DEFAULT_RETRY_MAX_DELAY_MS = 3e4;
3134
+ var MIN_AGGREGATE_BYTES = 512;
3135
+ var MIN_QUEUE_BYTES = 512;
3136
+ var MAX_AGGREGATE_FLUSH_INTERVAL_MS = 10 * 60 * 1e3;
3137
+ var MAX_AGGREGATE_COUNTERS = 500;
3138
+ var MAX_AGGREGATE_BYTES = 60 * 1024;
3139
+ var MAX_BATCHES_PER_FLUSH = 20;
3140
+ var MAX_QUEUE_EVENTS = 5e3;
3141
+ var MAX_QUEUE_BYTES = 8 * 1024 * 1024;
3142
+ var MAX_EVENT_AGE_MS = 24 * 60 * 60 * 1e3;
3143
+ var MAX_EPISODE_IDLE_MS = 2 * 60 * 60 * 1e3;
3144
+ var MAX_COALESCE_WINDOW_MS = 6e4;
3145
+ var MAX_REQUEST_TIMEOUT_MS = 3e4;
3146
+ var MAX_RETRIES = 5;
3147
+ var MAX_RETRY_BASE_DELAY_MS = 3e4;
3148
+ var MAX_RETRY_DELAY_MS = 5 * 60 * 1e3;
3149
+ var CONTENT_TYPE = "application/json";
3150
+ var textEncoder2 = new TextEncoder();
3151
+ function invalidConfig() {
3152
+ throw new Error("Semantic journey client configuration is invalid.");
3153
+ }
3154
+ function resolveInteger(value, fallback, minimum, maximum) {
3155
+ const resolved = value ?? fallback;
3156
+ if (!Number.isSafeInteger(resolved) || resolved < minimum || resolved > maximum) {
3157
+ return invalidConfig();
3158
+ }
3159
+ return resolved;
3160
+ }
3161
+ function resolveRuntime2(runtime) {
3162
+ if (runtime) {
3163
+ return runtime;
3164
+ }
3165
+ return typeof window === "undefined" ? "server" : "browser";
3166
+ }
3167
+ function resolveChannel2(channel, runtime) {
3168
+ return channel ?? (runtime === "server" ? "backend" : "frontend");
3169
+ }
3170
+ function defaultRetryDelay(delayMs, signal) {
3171
+ if (signal.aborted) {
3172
+ return Promise.reject(new SemanticJourneyTransportError("aborted", true));
3173
+ }
3174
+ return new Promise((resolve, reject) => {
3175
+ const timer = globalThis.setTimeout(() => {
3176
+ signal.removeEventListener("abort", onAbort);
3177
+ resolve();
3178
+ }, delayMs);
3179
+ const onAbort = () => {
3180
+ globalThis.clearTimeout(timer);
3181
+ reject(new SemanticJourneyTransportError("aborted", true));
3182
+ };
3183
+ signal.addEventListener("abort", onAbort, { once: true });
3184
+ });
3185
+ }
3186
+ function isAllowedEndpoint(endpoint, baseUrl) {
3187
+ return isSecureSemanticJourneyEndpoint(endpoint, baseUrl);
3188
+ }
3189
+ function resolveConfig2(config) {
3190
+ if (!isSemanticSource(config.source)) {
3191
+ return invalidConfig();
3192
+ }
3193
+ if (!config.catalogue.sources.includes(config.source)) {
3194
+ return invalidConfig();
3195
+ }
3196
+ if (config.aggregateEndpoint !== void 0 && !isAllowedEndpoint(config.aggregateEndpoint, config.aggregateBaseUrl)) {
3197
+ return invalidConfig();
3198
+ }
3199
+ const runtime = resolveRuntime2(config.runtime);
3200
+ const retryBaseDelayMs = resolveInteger(
3201
+ config.retryBaseDelayMs,
3202
+ DEFAULT_RETRY_BASE_DELAY_MS,
3203
+ 1,
3204
+ MAX_RETRY_BASE_DELAY_MS
3205
+ );
3206
+ const retryMaxDelayMs = resolveInteger(
3207
+ config.retryMaxDelayMs,
3208
+ DEFAULT_RETRY_MAX_DELAY_MS,
3209
+ retryBaseDelayMs,
3210
+ MAX_RETRY_DELAY_MS
3211
+ );
3212
+ return {
3213
+ catalogue: config.catalogue,
3214
+ source: config.source,
3215
+ channel: resolveChannel2(config.channel, runtime),
3216
+ runtime,
3217
+ enabled: config.enabled ?? false,
3218
+ ...config.aggregateEndpoint ? { aggregateEndpoint: config.aggregateEndpoint } : {},
3219
+ aggregateTransport: config.aggregateTransport ?? createDefaultSemanticJourneyAggregateTransport({
3220
+ ...config.aggregateBaseUrl ? { baseUrl: config.aggregateBaseUrl } : {},
3221
+ ...config.now ? { now: config.now } : {}
3222
+ }),
3223
+ autoFlush: config.autoFlush ?? true,
3224
+ aggregateFlushIntervalMs: resolveInteger(
3225
+ config.aggregateFlushIntervalMs,
3226
+ DEFAULT_AGGREGATE_FLUSH_INTERVAL_MS,
3227
+ 1e3,
3228
+ MAX_AGGREGATE_FLUSH_INTERVAL_MS
3229
+ ),
3230
+ aggregateMaxCounters: resolveInteger(
3231
+ config.aggregateMaxCounters,
3232
+ DEFAULT_AGGREGATE_MAX_COUNTERS,
3233
+ 1,
3234
+ MAX_AGGREGATE_COUNTERS
3235
+ ),
3236
+ aggregateMaxBytes: resolveInteger(
3237
+ config.aggregateMaxBytes,
3238
+ DEFAULT_AGGREGATE_MAX_BYTES,
3239
+ MIN_AGGREGATE_BYTES,
3240
+ MAX_AGGREGATE_BYTES
3241
+ ),
3242
+ maxBatchesPerFlush: resolveInteger(
3243
+ config.maxBatchesPerFlush,
3244
+ DEFAULT_MAX_BATCHES_PER_FLUSH,
3245
+ 1,
3246
+ MAX_BATCHES_PER_FLUSH
3247
+ ),
3248
+ maxQueueEvents: resolveInteger(
3249
+ config.maxQueueEvents,
3250
+ DEFAULT_MAX_QUEUE_EVENTS,
3251
+ 1,
3252
+ MAX_QUEUE_EVENTS
3253
+ ),
3254
+ maxQueueBytes: resolveInteger(
3255
+ config.maxQueueBytes,
3256
+ DEFAULT_MAX_QUEUE_BYTES,
3257
+ MIN_QUEUE_BYTES,
3258
+ MAX_QUEUE_BYTES
3259
+ ),
3260
+ maxEventAgeMs: resolveInteger(
3261
+ config.maxEventAgeMs,
3262
+ DEFAULT_MAX_EVENT_AGE_MS,
3263
+ 1,
3264
+ MAX_EVENT_AGE_MS
3265
+ ),
3266
+ episodeIdleMs: resolveInteger(
3267
+ config.episodeIdleMs,
3268
+ DEFAULT_EPISODE_IDLE_MS,
3269
+ 1,
3270
+ MAX_EPISODE_IDLE_MS
3271
+ ),
3272
+ coalesceWindowMs: resolveInteger(
3273
+ config.coalesceWindowMs,
3274
+ DEFAULT_COALESCE_WINDOW_MS,
3275
+ 0,
3276
+ MAX_COALESCE_WINDOW_MS
3277
+ ),
3278
+ requestTimeoutMs: resolveInteger(
3279
+ config.requestTimeoutMs,
3280
+ DEFAULT_REQUEST_TIMEOUT_MS,
3281
+ 1,
3282
+ MAX_REQUEST_TIMEOUT_MS
3283
+ ),
3284
+ maxRetries: resolveInteger(
3285
+ config.maxRetries,
3286
+ DEFAULT_MAX_RETRIES,
3287
+ 0,
3288
+ MAX_RETRIES
3289
+ ),
3290
+ retryBaseDelayMs,
3291
+ retryMaxDelayMs,
3292
+ ...config.randomBytes ? { randomBytes: config.randomBytes } : {},
3293
+ now: config.now ?? (() => Date.now()),
3294
+ retryDelay: config.retryDelay ?? defaultRetryDelay,
3295
+ ...config.onDrop ? { onDrop: config.onDrop } : {}
3296
+ };
3297
+ }
3298
+ function copyEvent(event) {
3299
+ return Object.freeze({
3300
+ ...event,
3301
+ ...event.target ? { target: Object.freeze({ ...event.target }) } : {},
3302
+ attributes: Object.freeze({ ...event.attributes }),
3303
+ privacy: Object.freeze({ ...event.privacy })
3304
+ });
3305
+ }
3306
+ function eventBytes(event) {
3307
+ return textEncoder2.encode(JSON.stringify(event)).byteLength;
3308
+ }
3309
+ function sameTarget(left, right) {
3310
+ return left?.type === right?.type && left?.id === right?.id;
3311
+ }
3312
+ function shouldCoalesce(previous, next, windowMs) {
3313
+ return Boolean(
3314
+ previous && next.phase === "progress" && previous.phase === "progress" && previous.name === next.name && previous.outcome === next.outcome && sameTarget(previous.target, next.target) && next.occurredAtEpochMs - previous.occurredAtEpochMs <= windowMs
3315
+ );
3316
+ }
3317
+ function jitteredDelay(attempt, config) {
3318
+ const exponential = Math.min(
3319
+ config.retryMaxDelayMs,
3320
+ config.retryBaseDelayMs * 2 ** attempt
3321
+ );
3322
+ const bytes = config.randomBytes ? config.randomBytes(2) : globalThis.crypto.getRandomValues(new Uint8Array(2));
3323
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength !== 2) {
3324
+ throw new Error("Semantic journey retry random source is invalid.");
3325
+ }
3326
+ const sample = (bytes[0] ?? 0) << 8 | (bytes[1] ?? 0);
3327
+ const factor = 0.5 + sample / 65535;
3328
+ return Math.min(config.retryMaxDelayMs, Math.max(1, Math.round(exponential * factor)));
3329
+ }
3330
+ function createSemanticJourneyClient(inputConfig) {
3331
+ let config;
3332
+ try {
3333
+ config = resolveConfig2(inputConfig);
3334
+ } catch {
3335
+ return invalidConfig();
3336
+ }
3337
+ const aggregateStore = new SemanticJourneyAggregateStore({
3338
+ catalogue: config.catalogue,
3339
+ source: config.source,
3340
+ channel: config.channel,
3341
+ runtime: config.runtime
3342
+ });
3343
+ const queue = [];
3344
+ const contextByEventId = /* @__PURE__ */ new Map();
3345
+ let episode;
3346
+ let queueBytes = 0;
3347
+ let destroyed = false;
3348
+ let aggregateGeneration = 0;
3349
+ let aggregateController = new AbortController();
3350
+ let pendingBatch;
3351
+ let flushInFlight;
3352
+ let activeTransportController;
3353
+ let interval;
3354
+ const notifyDrop = (reason) => {
3355
+ try {
3356
+ config.onDrop?.(reason);
3357
+ } catch {
3358
+ }
3359
+ };
3360
+ const newEpisode = (nowEpochMs) => ({
3361
+ root: createJourneyContext(config.randomBytes),
3362
+ producerId: createProducerId(config.randomBytes),
3363
+ producerSequence: 0,
3364
+ lastActivityEpochMs: nowEpochMs
3365
+ });
3366
+ const clearLocalQueue = () => {
3367
+ queue.length = 0;
3368
+ queueBytes = 0;
3369
+ contextByEventId.clear();
3370
+ };
3371
+ const rotateAt = (nowEpochMs) => {
3372
+ clearLocalQueue();
3373
+ episode = newEpisode(nowEpochMs);
3374
+ };
3375
+ const removeFirstQueued = (reason) => {
3376
+ const removed = queue.shift();
3377
+ if (!removed) {
3378
+ return;
3379
+ }
3380
+ queueBytes -= removed.bytes;
3381
+ contextByEventId.delete(removed.event.eventId);
3382
+ aggregateStore.recordDropped();
3383
+ notifyDrop(reason);
3384
+ };
3385
+ const pruneExpired = (nowEpochMs) => {
3386
+ while (queue[0] && nowEpochMs - queue[0].event.occurredAtEpochMs > config.maxEventAgeMs) {
3387
+ removeFirstQueued("expired");
3388
+ }
3389
+ };
3390
+ const ensureEpisode = (nowEpochMs) => {
3391
+ if (!episode) {
3392
+ episode = newEpisode(nowEpochMs);
3393
+ } else if (nowEpochMs - episode.lastActivityEpochMs >= config.episodeIdleMs) {
3394
+ rotateAt(nowEpochMs);
3395
+ }
3396
+ pruneExpired(nowEpochMs);
3397
+ episode.lastActivityEpochMs = nowEpochMs;
3398
+ return episode;
3399
+ };
3400
+ const appendValidated = (validated, options, nowEpochMs) => {
3401
+ const currentEpisode = ensureEpisode(nowEpochMs);
3402
+ if (options.context.journeyId !== currentEpisode.root.journeyId) {
3403
+ notifyDrop("expired");
3404
+ return void 0;
3405
+ }
3406
+ const usesLocalProducer = options.producerId === void 0;
3407
+ const producerSequence = usesLocalProducer ? currentEpisode.producerSequence + 1 : options.producerSequence;
3408
+ if (!Number.isSafeInteger(producerSequence) || (producerSequence ?? 0) < 1) {
3409
+ notifyDrop("invalid");
3410
+ return void 0;
3411
+ }
3412
+ const event = Object.freeze({
3413
+ schemaVersion: "2.0",
3414
+ eventId: createEventId(config.randomBytes),
3415
+ journeyId: options.context.journeyId,
3416
+ traceId: options.context.traceId,
3417
+ spanId: options.context.spanId,
3418
+ ...options.context.parentSpanId ? { parentSpanId: options.context.parentSpanId } : {},
3419
+ ...options.causedByEventId ? { causedByEventId: options.causedByEventId } : {},
3420
+ producerId: options.producerId ?? currentEpisode.producerId,
3421
+ producerSequence,
3422
+ occurredAtEpochMs: nowEpochMs,
3423
+ source: options.source ?? config.source,
3424
+ channel: options.channel ?? config.channel,
3425
+ runtime: options.runtime ?? config.runtime,
3426
+ name: validated.name,
3427
+ category: validated.category,
3428
+ phase: validated.phase,
3429
+ outcome: validated.outcome,
3430
+ ...validated.modality ? { modality: validated.modality } : {},
3431
+ ...validated.target ? { target: Object.freeze({ ...validated.target }) } : {},
3432
+ attributes: Object.freeze({ ...validated.attributes }),
3433
+ privacy: Object.freeze({
3434
+ mode: "strict",
3435
+ policyVersion: SEMANTIC_JOURNEY_STRICT_POLICY_VERSION,
3436
+ droppedAttributeCount: validated.droppedAttributeCount
3437
+ })
3438
+ });
3439
+ aggregateStore.record(event.name, event.outcome);
3440
+ if (shouldCoalesce(
3441
+ queue[queue.length - 1]?.event,
3442
+ event,
3443
+ config.coalesceWindowMs
3444
+ )) {
3445
+ aggregateStore.recordCoalesced();
3446
+ return void 0;
3447
+ }
3448
+ const bytes = eventBytes(event);
3449
+ if (bytes > config.maxQueueBytes) {
3450
+ aggregateStore.recordDropped();
3451
+ notifyDrop("queue-limit");
3452
+ return void 0;
3453
+ }
3454
+ while (queue.length >= config.maxQueueEvents || queueBytes + bytes > config.maxQueueBytes) {
3455
+ removeFirstQueued("queue-limit");
3456
+ }
3457
+ queue.push({ event, context: options.context, bytes });
3458
+ queueBytes += bytes;
3459
+ contextByEventId.set(event.eventId, options.context);
3460
+ if (usesLocalProducer) {
3461
+ currentEpisode.producerSequence = producerSequence;
3462
+ }
3463
+ return copyEvent(event);
3464
+ };
3465
+ const validateInput = (input) => {
3466
+ try {
3467
+ return validateSemanticJourneyEventInput(config.catalogue, input);
3468
+ } catch {
3469
+ notifyDrop("invalid");
3470
+ return void 0;
3471
+ }
3472
+ };
3473
+ const createIndependentContext = (currentEpisode) => Object.freeze({
3474
+ journeyId: currentEpisode.root.journeyId,
3475
+ traceId: currentEpisode.root.traceId,
3476
+ spanId: createSpanId(config.randomBytes),
3477
+ traceFlags: currentEpisode.root.traceFlags
3478
+ });
3479
+ const contextForCause = (currentEpisode, causedByEventId, request) => {
3480
+ const causeContext = causedByEventId ? contextByEventId.get(causedByEventId) : void 0;
3481
+ if (request) {
3482
+ return createRequestJourneyContext(
3483
+ causeContext ?? currentEpisode.root,
3484
+ config.randomBytes
3485
+ );
3486
+ }
3487
+ if (!causeContext) {
3488
+ return createIndependentContext(currentEpisode);
3489
+ }
3490
+ return createChildJourneyContext(causeContext, config.randomBytes);
3491
+ };
3492
+ const track = (input, options = {}) => {
3493
+ if (!config.enabled || destroyed) {
3494
+ return void 0;
3495
+ }
3496
+ try {
3497
+ const causedByEventId = options.causedByEventId;
3498
+ if (causedByEventId !== void 0 && !isEventId(causedByEventId)) {
3499
+ notifyDrop("invalid");
3500
+ return void 0;
3501
+ }
3502
+ const validated = validateInput(input);
3503
+ if (!validated) {
3504
+ return void 0;
3505
+ }
3506
+ const nowEpochMs = config.now();
3507
+ const currentEpisode = ensureEpisode(nowEpochMs);
3508
+ const context = contextForCause(
3509
+ currentEpisode,
3510
+ causedByEventId,
3511
+ false
3512
+ );
3513
+ return appendValidated(
3514
+ validated,
3515
+ {
3516
+ context,
3517
+ ...causedByEventId ? { causedByEventId } : {}
3518
+ },
3519
+ nowEpochMs
3520
+ );
3521
+ } catch {
3522
+ notifyDrop("invalid");
3523
+ return void 0;
3524
+ }
3525
+ };
3526
+ const addConsequence = (receipt, parentContext, causedByEventId, producerId, producerSequence) => {
3527
+ const definition = config.catalogue.definitions[receipt.name];
3528
+ if (!definition) {
3529
+ return void 0;
3530
+ }
3531
+ const validated = validateInput({
3532
+ name: receipt.name,
3533
+ category: definition.category,
3534
+ phase: receipt.phase,
3535
+ outcome: receipt.outcome,
3536
+ target: { type: "effect", id: receipt.effect }
3537
+ });
3538
+ if (!validated) {
3539
+ return void 0;
3540
+ }
3541
+ const context = createChildJourneyContext(parentContext, config.randomBytes);
3542
+ return appendValidated(
3543
+ validated,
3544
+ {
3545
+ context,
3546
+ causedByEventId,
3547
+ channel: "backend",
3548
+ runtime: "server",
3549
+ producerId,
3550
+ producerSequence
3551
+ },
3552
+ config.now()
3553
+ );
3554
+ };
3555
+ const beginRequest = (input, options = {}) => {
3556
+ if (!config.enabled || destroyed) {
3557
+ return void 0;
3558
+ }
3559
+ try {
3560
+ const causedByEventId = options.causedByEventId;
3561
+ if (causedByEventId !== void 0 && !isEventId(causedByEventId)) {
3562
+ notifyDrop("invalid");
3563
+ return void 0;
3564
+ }
3565
+ const validated = validateInput(input);
3566
+ if (!validated) {
3567
+ return void 0;
3568
+ }
3569
+ const nowEpochMs = config.now();
3570
+ const currentEpisode = ensureEpisode(nowEpochMs);
3571
+ const requestContext = contextForCause(
3572
+ currentEpisode,
3573
+ causedByEventId,
3574
+ true
3575
+ );
3576
+ const requestEvent = appendValidated(
3577
+ validated,
3578
+ {
3579
+ context: requestContext,
3580
+ ...causedByEventId ? { causedByEventId } : {}
3581
+ },
3582
+ nowEpochMs
3583
+ );
3584
+ if (!requestEvent) {
3585
+ return void 0;
3586
+ }
3587
+ const requestEventId = requestEvent.eventId;
3588
+ const traceparent = formatTraceparent(requestContext);
3589
+ let completed = false;
3590
+ return Object.freeze({
3591
+ requestEvent,
3592
+ traceparent,
3593
+ complete: (consequenceReceiptHeader) => {
3594
+ if (completed || destroyed) {
3595
+ return [];
3596
+ }
3597
+ completed = true;
3598
+ try {
3599
+ const receipts = parseSemanticJourneyReceipts(
3600
+ consequenceReceiptHeader,
3601
+ config.catalogue
3602
+ );
3603
+ if (receipts.length === 0) {
3604
+ return [];
3605
+ }
3606
+ const producerId = createProducerId(config.randomBytes);
3607
+ const added = [];
3608
+ let parentContext = requestContext;
3609
+ let causeEventId = requestEventId;
3610
+ let producerSequence = 1;
3611
+ for (const receipt of receipts) {
3612
+ const consequence = addConsequence(
3613
+ receipt,
3614
+ parentContext,
3615
+ causeEventId,
3616
+ producerId,
3617
+ producerSequence
3618
+ );
3619
+ if (!consequence) {
3620
+ continue;
3621
+ }
3622
+ const storedContext = contextByEventId.get(consequence.eventId);
3623
+ if (storedContext) {
3624
+ parentContext = storedContext;
3625
+ }
3626
+ causeEventId = consequence.eventId;
3627
+ producerSequence += 1;
3628
+ added.push(consequence);
3629
+ }
3630
+ return added;
3631
+ } catch {
3632
+ notifyDrop("invalid");
3633
+ return [];
3634
+ }
3635
+ }
3636
+ });
3637
+ } catch {
3638
+ notifyDrop("invalid");
3639
+ return void 0;
3640
+ }
3641
+ };
3642
+ const sendWithTimeout = async (batch, keepalive) => {
3643
+ if (!config.aggregateEndpoint) {
3644
+ return;
3645
+ }
3646
+ const controller = new AbortController();
3647
+ activeTransportController = controller;
3648
+ await new Promise((resolve, reject) => {
3649
+ let timer;
3650
+ function cleanup() {
3651
+ globalThis.clearTimeout(timer);
3652
+ controller.signal.removeEventListener("abort", rejectAborted);
3653
+ }
3654
+ function rejectAborted() {
3655
+ cleanup();
3656
+ reject(new SemanticJourneyTransportError("aborted", true));
3657
+ }
3658
+ timer = globalThis.setTimeout(() => {
3659
+ controller.abort();
3660
+ }, config.requestTimeoutMs);
3661
+ controller.signal.addEventListener("abort", rejectAborted, { once: true });
3662
+ let transportPromise;
3663
+ try {
3664
+ transportPromise = Promise.resolve(config.aggregateTransport({
3665
+ endpoint: config.aggregateEndpoint,
3666
+ body: JSON.stringify(batch),
3667
+ headers: {
3668
+ "content-type": CONTENT_TYPE,
3669
+ "x-idempotency-key": batch.batchId
3670
+ },
3671
+ signal: controller.signal,
3672
+ keepalive
3673
+ }));
3674
+ } catch (error) {
3675
+ cleanup();
3676
+ reject(error);
3677
+ return;
3678
+ }
3679
+ void transportPromise.then(
3680
+ () => {
3681
+ cleanup();
3682
+ resolve();
3683
+ },
3684
+ (error) => {
3685
+ cleanup();
3686
+ reject(error);
3687
+ }
3688
+ );
3689
+ }).finally(() => {
3690
+ if (activeTransportController === controller) {
3691
+ activeTransportController = void 0;
3692
+ }
3693
+ });
3694
+ };
3695
+ const sendBatch = async (batch, keepalive, signal) => {
3696
+ for (let attempt = 0; attempt <= config.maxRetries; attempt += 1) {
3697
+ if (destroyed || signal.aborted) {
3698
+ return "retained";
3699
+ }
3700
+ try {
3701
+ await sendWithTimeout(batch, keepalive);
3702
+ return "sent";
3703
+ } catch (error) {
3704
+ const transportError = error instanceof SemanticJourneyTransportError ? error : void 0;
3705
+ if (transportError && !transportError.retryable) {
3706
+ notifyDrop("transport-rejected");
3707
+ return "discarded";
3708
+ }
3709
+ if (attempt >= config.maxRetries) {
3710
+ return "retained";
3711
+ }
3712
+ const retryAfterMs = transportError?.retryAfterMs;
3713
+ const delayMs = retryAfterMs === void 0 ? jitteredDelay(attempt, config) : Math.min(config.retryMaxDelayMs, Math.max(0, retryAfterMs));
3714
+ try {
3715
+ await config.retryDelay(delayMs, signal);
3716
+ } catch {
3717
+ return "retained";
3718
+ }
3719
+ }
3720
+ }
3721
+ return "retained";
3722
+ };
3723
+ const flushInternal = async (keepalive) => {
3724
+ if (!config.enabled || destroyed || !config.aggregateEndpoint) {
3725
+ return;
3726
+ }
3727
+ const generation = aggregateGeneration;
3728
+ const signal = aggregateController.signal;
3729
+ for (let sentBatchCount = 0; sentBatchCount < config.maxBatchesPerFlush; sentBatchCount += 1) {
3730
+ const batch = pendingBatch ?? aggregateStore.createBatch({
3731
+ batchId: createEventId(config.randomBytes),
3732
+ nowEpochMs: config.now(),
3733
+ maxCounters: config.aggregateMaxCounters,
3734
+ maxBytes: config.aggregateMaxBytes
3735
+ });
3736
+ if (!batch) {
3737
+ return;
3738
+ }
3739
+ pendingBatch = batch;
3740
+ const result = await sendBatch(batch, keepalive, signal);
3741
+ if (generation !== aggregateGeneration || signal.aborted) {
3742
+ return;
3743
+ }
3744
+ if (result === "retained") {
3745
+ return;
3746
+ }
3747
+ aggregateStore.acknowledge(batch);
3748
+ pendingBatch = void 0;
3749
+ }
3750
+ };
3751
+ const startFlush = (keepalive) => {
3752
+ if (flushInFlight) {
3753
+ return flushInFlight;
3754
+ }
3755
+ flushInFlight = flushInternal(keepalive).catch(() => void 0).finally(() => {
3756
+ flushInFlight = void 0;
3757
+ });
3758
+ return flushInFlight;
3759
+ };
3760
+ const flush = () => startFlush(false);
3761
+ const getEvents = () => {
3762
+ if (!config.enabled || destroyed) {
3763
+ return [];
3764
+ }
3765
+ try {
3766
+ pruneExpired(config.now());
3767
+ return queue.map(({ event }) => copyEvent(event));
3768
+ } catch {
3769
+ return [];
3770
+ }
3771
+ };
3772
+ const reconstruct = () => reconstructSemanticJourney(config.catalogue, getEvents());
3773
+ const rotate = () => {
3774
+ if (!config.enabled || destroyed) {
3775
+ return;
3776
+ }
3777
+ rotateAt(config.now());
3778
+ };
3779
+ const clear = () => {
3780
+ if (destroyed) {
3781
+ return;
3782
+ }
3783
+ aggregateGeneration += 1;
3784
+ aggregateController.abort();
3785
+ aggregateController = new AbortController();
3786
+ activeTransportController?.abort();
3787
+ pendingBatch = void 0;
3788
+ clearLocalQueue();
3789
+ aggregateStore.clear();
3790
+ episode = void 0;
3791
+ };
3792
+ const onLifecycleFlush = () => {
3793
+ void startFlush(true);
3794
+ };
3795
+ const onVisibilityChange = () => {
3796
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") {
3797
+ void startFlush(true);
3798
+ }
3799
+ };
3800
+ if (config.enabled && config.autoFlush && config.aggregateEndpoint && !destroyed) {
3801
+ interval = globalThis.setInterval(
3802
+ () => void flush(),
3803
+ config.aggregateFlushIntervalMs
3804
+ );
3805
+ if (typeof interval === "object" && interval && "unref" in interval) {
3806
+ interval.unref();
3807
+ }
3808
+ if (typeof window !== "undefined") {
3809
+ window.addEventListener("pagehide", onLifecycleFlush);
3810
+ }
3811
+ if (typeof document !== "undefined") {
3812
+ document.addEventListener("visibilitychange", onVisibilityChange);
3813
+ }
3814
+ }
3815
+ const destroy = () => {
3816
+ if (destroyed) {
3817
+ return;
3818
+ }
3819
+ destroyed = true;
3820
+ aggregateGeneration += 1;
3821
+ aggregateController.abort();
3822
+ activeTransportController?.abort();
3823
+ pendingBatch = void 0;
3824
+ if (interval !== void 0) {
3825
+ globalThis.clearInterval(interval);
3826
+ interval = void 0;
3827
+ }
3828
+ if (typeof window !== "undefined") {
3829
+ window.removeEventListener("pagehide", onLifecycleFlush);
3830
+ }
3831
+ if (typeof document !== "undefined") {
3832
+ document.removeEventListener("visibilitychange", onVisibilityChange);
3833
+ }
3834
+ clearLocalQueue();
3835
+ aggregateStore.clear();
3836
+ episode = void 0;
3837
+ };
3838
+ return Object.freeze({
3839
+ source: config.source,
3840
+ channel: config.channel,
3841
+ runtime: config.runtime,
3842
+ track,
3843
+ beginRequest,
3844
+ getEvents,
3845
+ reconstruct,
3846
+ flush,
3847
+ rotate,
3848
+ clear,
3849
+ destroy
3850
+ });
3851
+ }
3852
+
1223
3853
  // src/react/provider.tsx
1224
3854
  var import_react = require("react");
1225
3855
  var import_jsx_runtime = require("react/jsx-runtime");
@@ -1339,11 +3969,52 @@ function useComponentInteractionTracker(component, baseContext = {}) {
1339
3969
  // Annotate the CommonJS export names for ESM import in node:
1340
3970
  0 && (module.exports = {
1341
3971
  AnalyticsProvider,
3972
+ SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION,
3973
+ SEMANTIC_JOURNEY_RECEIPT_HEADER,
3974
+ SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES,
3975
+ SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT,
3976
+ SEMANTIC_JOURNEY_RECEIPT_VERSION,
3977
+ SEMANTIC_JOURNEY_STRICT_POLICY_VERSION,
3978
+ SemanticJourneyAggregateStore,
3979
+ SemanticJourneyTransportError,
3980
+ SemanticJourneyValidationError,
3981
+ assertSemanticSource,
3982
+ assertSemanticToken,
1342
3983
  createBackendAnalyticsClient,
3984
+ createChildJourneyContext,
3985
+ createDefaultSemanticJourneyAggregateTransport,
3986
+ createEventId,
1343
3987
  createFrontendAnalyticsClient,
3988
+ createJourneyContext,
3989
+ createJourneyId,
1344
3990
  createLocalSpaceAnalyticsClient,
1345
3991
  createNoopLocalSpaceAnalyticsClient,
3992
+ createProducerId,
3993
+ createRequestJourneyContext,
3994
+ createSecureRandomHex,
3995
+ createSemanticJourneyClient,
3996
+ createSpanId,
3997
+ createTraceId,
3998
+ defineJourneyEvent,
3999
+ defineSemanticJourneyCatalog,
4000
+ formatTraceparent,
4001
+ getJourneyEventDefinition,
4002
+ isEventId,
4003
+ isJourneyId,
4004
+ isJourneyToken,
4005
+ isProducerId,
4006
+ isSecureSemanticJourneyEndpoint,
4007
+ isSemanticSource,
4008
+ isSemanticToken,
4009
+ isSpanId,
4010
+ isTraceId,
4011
+ observeSemanticJourneyInteractions,
4012
+ parseSemanticJourneyReceipts,
4013
+ parseTraceparent,
4014
+ reconstructSemanticJourney,
4015
+ serializeSemanticJourneyReceipts,
1346
4016
  useAnalytics,
1347
- useComponentInteractionTracker
4017
+ useComponentInteractionTracker,
4018
+ validateSemanticJourneyEventInput
1348
4019
  });
1349
4020
  //# sourceMappingURL=index.cjs.map