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