@plasius/analytics 1.3.2 → 1.4.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
@@ -215,7 +215,8 @@ async function defaultTransport({
215
215
  endpoint,
216
216
  body,
217
217
  headers,
218
- keepalive
218
+ keepalive,
219
+ signal
219
220
  }) {
220
221
  if (typeof fetch !== "function") {
221
222
  return;
@@ -224,7 +225,8 @@ async function defaultTransport({
224
225
  method: "POST",
225
226
  headers,
226
227
  body,
227
- keepalive
228
+ keepalive,
229
+ signal
228
230
  });
229
231
  if (!response.ok) {
230
232
  throw new Error(`Analytics transport failed with status ${response.status}.`);
@@ -398,8 +400,8 @@ function sanitizeMultiline(value, maxLength) {
398
400
  function isPlainObject(value) {
399
401
  return value !== null && typeof value === "object" && !Array.isArray(value);
400
402
  }
401
- function shouldRedactContextKey(key, resolvedErrorReporting) {
402
- const loweredKey = key.trim().toLowerCase();
403
+ function shouldRedactContextKey(key2, resolvedErrorReporting) {
404
+ const loweredKey = key2.trim().toLowerCase();
403
405
  if (!loweredKey) {
404
406
  return false;
405
407
  }
@@ -479,10 +481,10 @@ function sanitizeContextValue(value, resolvedErrorReporting, depth, seen, identi
479
481
  }
480
482
  const sanitized = {};
481
483
  const entries = Object.entries(value).slice(0, resolvedErrorReporting.maxContextBreadth);
482
- for (const [key, nestedValue] of entries) {
483
- const childPath = keyPath ? `${keyPath}.${key}` : key;
484
- if (shouldRedactContextKey(key, resolvedErrorReporting)) {
485
- sanitized[key] = applySchemaLogHandling(String(nestedValue ?? ""), true) || REDACTED_VALUE;
484
+ for (const [key2, nestedValue] of entries) {
485
+ const childPath = keyPath ? `${keyPath}.${key2}` : key2;
486
+ if (shouldRedactContextKey(key2, resolvedErrorReporting)) {
487
+ sanitized[key2] = applySchemaLogHandling(String(nestedValue ?? ""), true) || REDACTED_VALUE;
486
488
  pushIdentifier(
487
489
  identifiers,
488
490
  childPath,
@@ -491,7 +493,7 @@ function sanitizeContextValue(value, resolvedErrorReporting, depth, seen, identi
491
493
  );
492
494
  continue;
493
495
  }
494
- sanitized[key] = sanitizeContextValue(
496
+ sanitized[key2] = sanitizeContextValue(
495
497
  nestedValue,
496
498
  resolvedErrorReporting,
497
499
  depth + 1,
@@ -512,19 +514,19 @@ function sanitizeErrorContext(context, resolvedErrorReporting) {
512
514
  const identifiers = [];
513
515
  const seen = /* @__PURE__ */ new WeakSet();
514
516
  const entries = Object.entries(context).slice(0, resolvedErrorReporting.maxContextBreadth);
515
- for (const [key, value] of entries) {
516
- if (shouldRedactContextKey(key, resolvedErrorReporting)) {
517
- sanitized[key] = applySchemaLogHandling(String(value ?? ""), true) || REDACTED_VALUE;
518
- pushIdentifier(identifiers, key, value, resolvedErrorReporting.maxMessageLength);
517
+ for (const [key2, value] of entries) {
518
+ if (shouldRedactContextKey(key2, resolvedErrorReporting)) {
519
+ sanitized[key2] = applySchemaLogHandling(String(value ?? ""), true) || REDACTED_VALUE;
520
+ pushIdentifier(identifiers, key2, value, resolvedErrorReporting.maxMessageLength);
519
521
  continue;
520
522
  }
521
- sanitized[key] = sanitizeContextValue(
523
+ sanitized[key2] = sanitizeContextValue(
522
524
  value,
523
525
  resolvedErrorReporting,
524
526
  1,
525
527
  seen,
526
528
  identifiers,
527
- key
529
+ key2
528
530
  );
529
531
  }
530
532
  return {
@@ -708,7 +710,7 @@ function readQueue(storageKey, fallbackConfig) {
708
710
  if (!Array.isArray(parsed)) {
709
711
  return [];
710
712
  }
711
- return parsed.filter(isStoredRecordCandidate).map((record) => normalizeStoredRecord(record, fallbackConfig));
713
+ return parsed.filter(isStoredRecordCandidate).map((record2) => normalizeStoredRecord(record2, fallbackConfig));
712
714
  } catch {
713
715
  return [];
714
716
  }
@@ -778,6 +780,7 @@ function createLocalSpaceAnalyticsClient(config) {
778
780
  let isFlushing = false;
779
781
  let flushQueuedAfterCurrent = false;
780
782
  let isDestroyed = false;
783
+ const transportController = new AbortController();
781
784
  const issueAggregates = /* @__PURE__ */ new Map();
782
785
  const persistQueue = () => writeQueue(resolvedConfig.storageKey, queue);
783
786
  const trimQueue = () => {
@@ -872,12 +875,12 @@ function createLocalSpaceAnalyticsClient(config) {
872
875
  return right.lastSeen - left.lastSeen;
873
876
  });
874
877
  };
875
- const enqueueRecord = (record) => {
876
- queue.push(record);
878
+ const enqueueRecord = (record2) => {
879
+ queue.push(record2);
877
880
  trimQueue();
878
881
  persistQueue();
879
- if (record.kind === "error" && record.error) {
880
- recordIssue(record.error, record.timestamp, true);
882
+ if (record2.kind === "error" && record2.error) {
883
+ recordIssue(record2.error, record2.timestamp, true);
881
884
  }
882
885
  if (queue.length >= resolvedConfig.batchSize) {
883
886
  void flush();
@@ -944,12 +947,14 @@ function createLocalSpaceAnalyticsClient(config) {
944
947
  body,
945
948
  headers: resolvedConfig.headers,
946
949
  // Normal flushes do not need fetch keepalive; unload/pagehide uses sendBeacon.
947
- keepalive: false
950
+ keepalive: false,
951
+ signal: transportController.signal
948
952
  });
953
+ if (transportController.signal.aborted) return;
949
954
  queue = queue.slice(events.length);
950
955
  persistQueue();
951
956
  } catch (error) {
952
- resolvedConfig.onError?.(error);
957
+ if (!transportController.signal.aborted) resolvedConfig.onError?.(error);
953
958
  } finally {
954
959
  isFlushing = false;
955
960
  if (flushQueuedAfterCurrent) {
@@ -992,9 +997,9 @@ function createLocalSpaceAnalyticsClient(config) {
992
997
  document.addEventListener("visibilitychange", handleVisibilityChange);
993
998
  window.addEventListener("pagehide", handlePageHide);
994
999
  }
995
- for (const record of queue) {
996
- if (record.kind === "error" && record.error) {
997
- recordIssue(record.error, record.timestamp, false);
1000
+ for (const record2 of queue) {
1001
+ if (record2.kind === "error" && record2.error) {
1002
+ recordIssue(record2.error, record2.timestamp, false);
998
1003
  }
999
1004
  }
1000
1005
  startFlushTimer();
@@ -1013,7 +1018,7 @@ function createLocalSpaceAnalyticsClient(config) {
1013
1018
  const requestId = typeof event.requestId === "string" && event.requestId.trim() ? event.requestId.trim() : void 0;
1014
1019
  const kind = event.kind === "error" ? "error" : "interaction";
1015
1020
  const normalizedError = kind === "error" && isErrorDetailsCandidate(event.error) ? normalizeStoredErrorDetails(event.error, resolvedConfig.errorReporting) : void 0;
1016
- const record = {
1021
+ const record2 = {
1017
1022
  id: createId("event"),
1018
1023
  component: event.component,
1019
1024
  action: event.action,
@@ -1030,7 +1035,7 @@ function createLocalSpaceAnalyticsClient(config) {
1030
1035
  context: createMergedContext(resolvedConfig, eventChannel, event.context),
1031
1036
  error: normalizedError
1032
1037
  };
1033
- enqueueRecord(record);
1038
+ enqueueRecord(record2);
1034
1039
  };
1035
1040
  const reportError = (report) => {
1036
1041
  if (isDestroyed || !resolvedConfig.enabled) {
@@ -1064,7 +1069,7 @@ function createLocalSpaceAnalyticsClient(config) {
1064
1069
  if (normalizedError.tags && normalizedError.tags.length > 0) {
1065
1070
  errorContext.errorTags = normalizedError.tags;
1066
1071
  }
1067
- const record = {
1072
+ const record2 = {
1068
1073
  id: createId("event"),
1069
1074
  component: normalizedError.boundary,
1070
1075
  action: normalizedError.handled ? "error_boundary_caught" : "unhandled_error",
@@ -1078,7 +1083,7 @@ function createLocalSpaceAnalyticsClient(config) {
1078
1083
  context: createMergedContext(resolvedConfig, eventChannel, errorContext),
1079
1084
  error: normalizedError
1080
1085
  };
1081
- enqueueRecord(record);
1086
+ enqueueRecord(record2);
1082
1087
  };
1083
1088
  return {
1084
1089
  get source() {
@@ -1122,7 +1127,14 @@ function createLocalSpaceAnalyticsClient(config) {
1122
1127
  getConfig() {
1123
1128
  return resolvedConfig;
1124
1129
  },
1125
- destroy() {
1130
+ destroy(options) {
1131
+ if (options?.discard) {
1132
+ transportController.abort();
1133
+ queue = [];
1134
+ flushQueuedAfterCurrent = false;
1135
+ issueAggregates.clear();
1136
+ writeQueue(resolvedConfig.storageKey, []);
1137
+ }
1126
1138
  if (isDestroyed) {
1127
1139
  return;
1128
1140
  }
@@ -1339,13 +1351,13 @@ function isRecord(value) {
1339
1351
  }
1340
1352
  function getOwnStringKeys(value) {
1341
1353
  const keys = Reflect.ownKeys(value);
1342
- if (keys.some((key) => typeof key !== "string")) {
1354
+ if (keys.some((key2) => typeof key2 !== "string")) {
1343
1355
  return null;
1344
1356
  }
1345
1357
  return keys;
1346
1358
  }
1347
1359
  function hasOnlyFields(keys, allowed) {
1348
- return keys.every((key) => allowed.has(key));
1360
+ return keys.every((key2) => allowed.has(key2));
1349
1361
  }
1350
1362
  function sensitivityWords(value) {
1351
1363
  return value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.toLowerCase());
@@ -1465,11 +1477,11 @@ function normalizeEventDefinition(candidate) {
1465
1477
  if (targetKeys === null || targetKeys.length !== 2 || !hasOnlyFields(targetKeys, TARGET_FIELDS) || !isSemanticToken(target.type) || !isSemanticToken(target.id) || looksSensitive(target.type) || looksSensitive(target.id)) {
1466
1478
  return invalidDefinition();
1467
1479
  }
1468
- const key = `${target.type}\0${target.id}`;
1469
- if (seenTargets.has(key)) {
1480
+ const key2 = `${target.type}\0${target.id}`;
1481
+ if (seenTargets.has(key2)) {
1470
1482
  return invalidDefinition();
1471
1483
  }
1472
- seenTargets.add(key);
1484
+ seenTargets.add(key2);
1473
1485
  targets.push(Object.freeze({ type: target.type, id: target.id }));
1474
1486
  }
1475
1487
  }
@@ -1651,12 +1663,12 @@ function createSecureRandomHex(byteLength2, randomBytes = webCryptoRandomBytes)
1651
1663
  if (!Number.isSafeInteger(byteLength2) || byteLength2 <= 0 || byteLength2 > MAX_RANDOM_BYTE_LENGTH) {
1652
1664
  throw new Error("Secure random byte length is invalid.");
1653
1665
  }
1654
- const bytes = randomBytes(byteLength2);
1655
- if (!(bytes instanceof Uint8Array) || bytes.byteLength !== byteLength2) {
1666
+ const bytes2 = randomBytes(byteLength2);
1667
+ if (!(bytes2 instanceof Uint8Array) || bytes2.byteLength !== byteLength2) {
1656
1668
  throw new Error("Secure random source returned invalid bytes.");
1657
1669
  }
1658
1670
  let result = "";
1659
- for (const byte of bytes) {
1671
+ for (const byte of bytes2) {
1660
1672
  result += byte.toString(16).padStart(2, "0");
1661
1673
  }
1662
1674
  return result;
@@ -1823,29 +1835,29 @@ var SemanticJourneyAggregateStore = class {
1823
1835
  }
1824
1836
  this.options = Object.freeze({ ...options });
1825
1837
  }
1826
- record(eventName, outcome, count = 1) {
1838
+ record(eventName, outcome, count2 = 1) {
1827
1839
  if (!isSemanticToken(eventName) || getJourneyEventDefinition(this.options.catalogue, eventName) === void 0 || !OUTCOMES2.has(outcome)) {
1828
1840
  invalidAggregate();
1829
1841
  }
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({
1842
+ normalizeLimit(count2, 1, "counter increment");
1843
+ const key2 = toCounterKey(eventName, outcome);
1844
+ const existing = this.counters.get(key2);
1845
+ this.counters.set(key2, Object.freeze({
1834
1846
  eventName,
1835
1847
  outcome,
1836
- count: addSafeCount(existing?.count ?? 0, count)
1848
+ count: addSafeCount(existing?.count ?? 0, count2)
1837
1849
  }));
1838
1850
  }
1839
- recordDropped(count = 1) {
1851
+ recordDropped(count2 = 1) {
1840
1852
  this.dropped = addSafeCount(
1841
1853
  this.dropped,
1842
- normalizeLimit(count, 1, "dropped increment")
1854
+ normalizeLimit(count2, 1, "dropped increment")
1843
1855
  );
1844
1856
  }
1845
- recordCoalesced(count = 1) {
1857
+ recordCoalesced(count2 = 1) {
1846
1858
  this.coalesced = addSafeCount(
1847
1859
  this.coalesced,
1848
- normalizeLimit(count, 1, "coalesced increment")
1860
+ normalizeLimit(count2, 1, "coalesced increment")
1849
1861
  );
1850
1862
  }
1851
1863
  snapshot() {
@@ -1901,16 +1913,16 @@ var SemanticJourneyAggregateStore = class {
1901
1913
  }
1902
1914
  acknowledge(batch) {
1903
1915
  for (const acknowledged of batch.counters) {
1904
- const key = toCounterKey(acknowledged.eventName, acknowledged.outcome);
1905
- const current = this.counters.get(key);
1916
+ const key2 = toCounterKey(acknowledged.eventName, acknowledged.outcome);
1917
+ const current = this.counters.get(key2);
1906
1918
  if (!current) {
1907
1919
  continue;
1908
1920
  }
1909
1921
  const remaining = current.count - acknowledged.count;
1910
1922
  if (remaining > 0) {
1911
- this.counters.set(key, Object.freeze({ ...current, count: remaining }));
1923
+ this.counters.set(key2, Object.freeze({ ...current, count: remaining }));
1912
1924
  } else {
1913
- this.counters.delete(key);
1925
+ this.counters.delete(key2);
1914
1926
  }
1915
1927
  }
1916
1928
  this.dropped = Math.max(0, this.dropped - batch.dropped);
@@ -1929,6 +1941,395 @@ var SemanticJourneyAggregateStore = class {
1929
1941
  }
1930
1942
  };
1931
1943
 
1944
+ // src/journey/aggregate-policy.ts
1945
+ var SEMANTIC_JOURNEY_PROJECTED_AGGREGATE_SCHEMA_VERSION = "2.1-aggregate";
1946
+ var SEMANTIC_JOURNEY_AGGREGATE_MAX_BYTES = 64 * 1024;
1947
+ var policies = /* @__PURE__ */ new WeakSet();
1948
+ var outcomes = /* @__PURE__ */ new Set(["unknown", "success", "failure", "cancelled", "denied"]);
1949
+ var envelopeFields = ["schemaVersion", "batchId", "source", "channel", "runtime", "timeBucket", "policyVersion", "dropped", "coalesced", "counters"];
1950
+ var counterFields = ["eventName", "outcome", "count"];
1951
+ var projectedFields = [...counterFields, "view", "dimensions"];
1952
+ var encoder = new TextEncoder();
1953
+ function invalidPolicy() {
1954
+ throw new Error("Semantic aggregate policy is invalid.");
1955
+ }
1956
+ function invalidInput2() {
1957
+ throw new Error("Semantic aggregate input is invalid.");
1958
+ }
1959
+ function record(value, maxKeys = 32) {
1960
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1961
+ const prototype = Object.getPrototypeOf(value);
1962
+ if (prototype !== Object.prototype && prototype !== null) return false;
1963
+ const keys = Reflect.ownKeys(value);
1964
+ return keys.length <= maxKeys && keys.every((key2) => {
1965
+ const descriptor = Object.getOwnPropertyDescriptor(value, key2);
1966
+ return typeof key2 === "string" && descriptor?.enumerable && "value" in descriptor;
1967
+ });
1968
+ }
1969
+ function array(value, maximum) {
1970
+ if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype || value.length > maximum) return false;
1971
+ if (Reflect.ownKeys(value).length !== value.length + 1) return false;
1972
+ for (let index = 0; index < value.length; index++) {
1973
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
1974
+ if (!descriptor || !descriptor.enumerable || !("value" in descriptor)) return false;
1975
+ }
1976
+ return true;
1977
+ }
1978
+ function exact(value, fields) {
1979
+ const keys = Object.keys(value);
1980
+ return keys.length === fields.length && keys.every((key2) => fields.includes(key2));
1981
+ }
1982
+ function count(value, minimum = 0) {
1983
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum;
1984
+ }
1985
+ function bindingKey(binding) {
1986
+ return `${binding.source}\0${binding.channel}\0${binding.runtime}`;
1987
+ }
1988
+ function isSemanticJourneyAggregatePolicy(value) {
1989
+ return typeof value === "object" && value !== null && policies.has(value);
1990
+ }
1991
+ function defineSemanticJourneyAggregatePolicy(catalogue, options) {
1992
+ try {
1993
+ if (!record(options) || Object.keys(options).some((key2) => !["bindings", "projections"].includes(key2)) || !array(options.bindings, 128) || options.bindings.length === 0) return invalidPolicy();
1994
+ const frozenCatalogue = defineSemanticJourneyCatalog(catalogue.definitions, { sources: catalogue.sources });
1995
+ const bindings = [];
1996
+ const seenBindings = /* @__PURE__ */ new Set();
1997
+ for (const candidate of options.bindings) {
1998
+ if (!record(candidate) || !exact(candidate, ["source", "channel", "runtime"]) || typeof candidate.source !== "string" || !frozenCatalogue.sources.includes(candidate.source) || !(candidate.channel === "frontend" && candidate.runtime === "browser" || candidate.channel === "backend" && candidate.runtime === "server")) return invalidPolicy();
1999
+ const binding = candidate;
2000
+ const key2 = bindingKey(binding);
2001
+ if (seenBindings.has(key2)) return invalidPolicy();
2002
+ seenBindings.add(key2);
2003
+ bindings.push(Object.freeze({ ...binding }));
2004
+ }
2005
+ const projections = /* @__PURE__ */ Object.create(null);
2006
+ const candidates = options.projections ?? {};
2007
+ if (!record(candidates, 2048)) return invalidPolicy();
2008
+ for (const [eventName, views] of Object.entries(candidates)) {
2009
+ const definition = getJourneyEventDefinition(frozenCatalogue, eventName);
2010
+ if (!definition || !record(views, 8) || Object.keys(views).length === 0) return invalidPolicy();
2011
+ const normalized = /* @__PURE__ */ Object.create(null);
2012
+ for (const [view, dimensions] of Object.entries(views)) {
2013
+ if (view === "total" || !array(dimensions, 4) || dimensions.length === 0 || new Set(dimensions).size !== dimensions.length) return invalidPolicy();
2014
+ defineSemanticJourneyCatalog({ "aggregate.view": {
2015
+ category: "state",
2016
+ attributes: { [view]: { type: "enum", values: ["registered"] } }
2017
+ } }, { sources: frozenCatalogue.sources });
2018
+ let cardinality = 1;
2019
+ const names = [];
2020
+ for (const dimension of dimensions) {
2021
+ const attribute = typeof dimension === "string" ? definition.attributes?.[dimension] : void 0;
2022
+ if (!attribute || attribute.type !== "enum") return invalidPolicy();
2023
+ cardinality *= attribute.values.length;
2024
+ if (cardinality > 4096) return invalidPolicy();
2025
+ names.push(dimension);
2026
+ }
2027
+ normalized[view] = Object.freeze(names.sort());
2028
+ }
2029
+ projections[eventName] = Object.freeze(normalized);
2030
+ }
2031
+ const policy = Object.freeze({ catalogue: frozenCatalogue, bindings: Object.freeze(bindings), projections: Object.freeze(projections) });
2032
+ policies.add(policy);
2033
+ return policy;
2034
+ } catch {
2035
+ return invalidPolicy();
2036
+ }
2037
+ }
2038
+ function projectSemanticJourneyAggregateCounters(policy, input, increment = 1) {
2039
+ try {
2040
+ if (!isSemanticJourneyAggregatePolicy(policy) || !count(increment, 1)) return invalidInput2();
2041
+ const event = validateSemanticJourneyEventInput(policy.catalogue, input);
2042
+ const base = { eventName: event.name, outcome: event.outcome, count: increment };
2043
+ const rows = [Object.freeze({ ...base, view: "total", dimensions: Object.freeze({}) })];
2044
+ for (const view of Object.keys(policy.projections[event.name] ?? {}).sort()) {
2045
+ const dimensions = /* @__PURE__ */ Object.create(null);
2046
+ const names = policy.projections[event.name][view];
2047
+ if (names.some((name) => event.attributes[name] === void 0)) continue;
2048
+ for (const name of names) dimensions[name] = event.attributes[name];
2049
+ rows.push(Object.freeze({ ...base, view, dimensions: Object.freeze(dimensions) }));
2050
+ }
2051
+ return Object.freeze(rows);
2052
+ } catch {
2053
+ return invalidInput2();
2054
+ }
2055
+ }
2056
+ function semanticJourneyAggregateCounterKey(counter) {
2057
+ if (!("view" in counter)) return JSON.stringify([counter.eventName, counter.outcome]);
2058
+ return JSON.stringify([
2059
+ counter.eventName,
2060
+ counter.outcome,
2061
+ counter.view,
2062
+ Object.keys(counter.dimensions).sort().map((key2) => [key2, counter.dimensions[key2]])
2063
+ ]);
2064
+ }
2065
+ function validCounter(policy, value, projected) {
2066
+ if (!record(value) || !exact(value, projected ? projectedFields : counterFields) || typeof value.eventName !== "string" || typeof value.outcome !== "string" || !outcomes.has(value.outcome) || !count(value.count, 1)) return false;
2067
+ const definition = getJourneyEventDefinition(policy.catalogue, value.eventName);
2068
+ if (!definition) return false;
2069
+ if (!projected) return true;
2070
+ if (typeof value.view !== "string" || !record(value.dimensions, 4)) return false;
2071
+ const dimensions = value.view === "total" ? [] : policy.projections[value.eventName]?.[value.view];
2072
+ if (!dimensions || !exact(value.dimensions, dimensions)) return false;
2073
+ for (const dimension of dimensions) {
2074
+ const attribute = definition.attributes?.[dimension];
2075
+ const supplied = value.dimensions[dimension];
2076
+ if (attribute?.type !== "enum" || typeof supplied !== "string" || !attribute.values.includes(supplied)) return false;
2077
+ }
2078
+ return true;
2079
+ }
2080
+ function createSemanticJourneyAggregateValidator(policy) {
2081
+ if (!isSemanticJourneyAggregatePolicy(policy)) return invalidPolicy();
2082
+ const bindings = new Set(policy.bindings.map(bindingKey));
2083
+ return (value) => {
2084
+ try {
2085
+ if (!record(value) || !exact(value, envelopeFields) || !["2.0-aggregate", "2.1-aggregate"].includes(value.schemaVersion) || !isEventId(value.batchId) || value.policyVersion !== "strict.v1" || typeof value.source !== "string" || value.source.length > 64 || !["frontend", "backend"].includes(value.channel) || !["browser", "server"].includes(value.runtime) || !bindings.has(bindingKey(value)) || typeof value.timeBucket !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:00:00\.000Z$/.test(value.timeBucket) || new Date(value.timeBucket).toISOString() !== value.timeBucket || !count(value.dropped) || !count(value.coalesced) || !array(value.counters, 500)) return false;
2086
+ const keys = /* @__PURE__ */ new Set();
2087
+ for (const counter of value.counters) {
2088
+ if (!validCounter(policy, counter, value.schemaVersion === "2.1-aggregate")) return false;
2089
+ const key2 = semanticJourneyAggregateCounterKey(counter);
2090
+ if (keys.has(key2)) return false;
2091
+ keys.add(key2);
2092
+ }
2093
+ return encoder.encode(JSON.stringify(value)).byteLength <= SEMANTIC_JOURNEY_AGGREGATE_MAX_BYTES;
2094
+ } catch {
2095
+ return false;
2096
+ }
2097
+ };
2098
+ }
2099
+
2100
+ // src/journey/projected-aggregate-store.ts
2101
+ var encoder2 = new TextEncoder();
2102
+ function invalid() {
2103
+ throw new Error("Semantic aggregate input is invalid.");
2104
+ }
2105
+ function bytes(value) {
2106
+ return encoder2.encode(JSON.stringify(value)).length;
2107
+ }
2108
+ function limit(value, fallback, minimum, maximum) {
2109
+ const selected = value ?? fallback;
2110
+ if (!Number.isSafeInteger(selected) || selected < minimum || selected > maximum) return invalid();
2111
+ return selected;
2112
+ }
2113
+ function hour(now) {
2114
+ if (!Number.isSafeInteger(now) || now < 0 || now > 253402300799999) return invalid();
2115
+ return new Date(Math.floor(now / 36e5) * 36e5).toISOString();
2116
+ }
2117
+ function add(left, right) {
2118
+ if (!Number.isSafeInteger(right) || right < 1 || !Number.isSafeInteger(left + right)) return invalid();
2119
+ return left + right;
2120
+ }
2121
+ function key(timeBucket, counter) {
2122
+ return `${timeBucket}\0${semanticJourneyAggregateCounterKey(counter)}`;
2123
+ }
2124
+ function minimumBatchBytes(options) {
2125
+ const envelope = {
2126
+ schemaVersion: "2.1-aggregate",
2127
+ batchId: "a".repeat(32),
2128
+ source: options.source,
2129
+ channel: options.channel,
2130
+ runtime: options.runtime,
2131
+ timeBucket: "9999-12-31T23:00:00.000Z",
2132
+ policyVersion: "strict.v1",
2133
+ dropped: Number.MAX_SAFE_INTEGER,
2134
+ coalesced: Number.MAX_SAFE_INTEGER
2135
+ };
2136
+ let minimum = bytes({ ...envelope, counters: [] });
2137
+ for (const [eventName, definition] of Object.entries(options.policy.catalogue.definitions)) {
2138
+ const base = { eventName, outcome: "cancelled", count: Number.MAX_SAFE_INTEGER };
2139
+ minimum = Math.max(minimum, bytes({ ...envelope, counters: [{ ...base, view: "total", dimensions: {} }] }));
2140
+ for (const [view, names] of Object.entries(options.policy.projections[eventName] ?? {})) {
2141
+ const dimensions = /* @__PURE__ */ Object.create(null);
2142
+ for (const name of names) {
2143
+ const attribute = definition.attributes?.[name];
2144
+ if (attribute?.type !== "enum") return invalid();
2145
+ dimensions[name] = attribute.values.reduce((longest, value) => bytes(value) > bytes(longest) ? value : longest);
2146
+ }
2147
+ minimum = Math.max(minimum, bytes({ ...envelope, counters: [{ ...base, view, dimensions }] }));
2148
+ }
2149
+ }
2150
+ return minimum;
2151
+ }
2152
+ var ProjectedSemanticJourneyAggregateStore = class {
2153
+ options;
2154
+ maxCounters;
2155
+ maxBytes;
2156
+ maxBatchBytes;
2157
+ minimumBatchBytes;
2158
+ maxAge;
2159
+ counters = /* @__PURE__ */ new Map();
2160
+ pendingBytes = 0;
2161
+ dropped = 0;
2162
+ coalesced = 0;
2163
+ diagnosticHour;
2164
+ diagnosticExpiry = 0;
2165
+ pending;
2166
+ constructor(options) {
2167
+ if (!isSemanticJourneyAggregatePolicy(options.policy) || !options.policy.bindings.some((binding) => binding.source === options.source && binding.channel === options.channel && binding.runtime === options.runtime)) invalid();
2168
+ this.maxCounters = limit(options.maxPendingCounters, 1e3, 1, 5e3);
2169
+ this.maxBytes = limit(options.maxPendingBytes, 1024 * 1024, 512, 8 * 1024 * 1024);
2170
+ this.minimumBatchBytes = minimumBatchBytes(options);
2171
+ this.maxBatchBytes = limit(options.maxBatchBytes, 48 * 1024, Math.max(512, this.minimumBatchBytes), 60 * 1024);
2172
+ this.maxAge = limit(options.maxAgeMs, 30 * 60 * 1e3, 1, 864e5);
2173
+ if (options.now !== void 0 && typeof options.now !== "function") invalid();
2174
+ this.options = Object.freeze({ ...options });
2175
+ }
2176
+ /** Return false on capacity pressure; never retain a partial set of views. */
2177
+ recordEvent(input, observedAt, increment = 1) {
2178
+ const timeBucket = hour(observedAt);
2179
+ const rows = projectSemanticJourneyAggregateCounters(this.options.policy, input, increment);
2180
+ this.prune(observedAt);
2181
+ const updates = [];
2182
+ let size = this.pendingBytes;
2183
+ let additions = 0;
2184
+ for (const row of rows) {
2185
+ const id = key(timeBucket, row);
2186
+ const existing = this.counters.get(id);
2187
+ const counter = Object.freeze({ ...row, count: add(existing?.counter.count ?? 0, increment) });
2188
+ const entry = {
2189
+ timeBucket,
2190
+ expiresAt: Math.min(existing?.expiresAt ?? Infinity, observedAt + this.maxAge),
2191
+ counter,
2192
+ // Conservative accounting includes duplicated key text and map bookkeeping.
2193
+ bytes: bytes(counter) + encoder2.encode(id).length + 64
2194
+ };
2195
+ size += entry.bytes - (existing?.bytes ?? 0);
2196
+ if (!existing) additions++;
2197
+ updates.push([id, entry]);
2198
+ }
2199
+ if (this.counters.size + additions > this.maxCounters || size > this.maxBytes) {
2200
+ this.diagnostic("dropped", increment, observedAt);
2201
+ return false;
2202
+ }
2203
+ for (const [id, entry] of updates) this.counters.set(id, entry);
2204
+ this.pendingBytes = size;
2205
+ return true;
2206
+ }
2207
+ recordDropped(increment = 1) {
2208
+ this.diagnostic("dropped", increment, this.now());
2209
+ }
2210
+ recordCoalesced(increment = 1) {
2211
+ this.diagnostic("coalesced", increment, this.now());
2212
+ }
2213
+ /** Read-only bounded diagnostics; never a persistence interface. */
2214
+ snapshot() {
2215
+ return Object.freeze({
2216
+ dropped: this.dropped,
2217
+ coalesced: this.coalesced,
2218
+ pendingCounters: this.counters.size,
2219
+ pendingBytes: this.pendingBytes,
2220
+ counters: Object.freeze(this.sorted().map((entry) => entry.counter))
2221
+ });
2222
+ }
2223
+ createBatch(options) {
2224
+ hour(options.nowEpochMs);
2225
+ if (!isEventId(options.batchId)) return invalid();
2226
+ const maxCounters = limit(options.maxCounters, 50, 1, 500);
2227
+ const maxBytes = limit(options.maxBytes, this.maxBatchBytes, Math.max(512, this.minimumBatchBytes), this.maxBatchBytes);
2228
+ this.prune(options.nowEpochMs);
2229
+ if (this.pending) return this.pending.batch;
2230
+ const entries = this.sorted();
2231
+ const earliest = entries[0]?.timeBucket;
2232
+ const timeBucket = earliest && this.diagnosticHour ? earliest < this.diagnosticHour ? earliest : this.diagnosticHour : earliest ?? this.diagnosticHour;
2233
+ if (!timeBucket) return null;
2234
+ const includeDiagnostics = timeBucket === this.diagnosticHour;
2235
+ const base = {
2236
+ schemaVersion: "2.1-aggregate",
2237
+ batchId: options.batchId,
2238
+ source: this.options.source,
2239
+ channel: this.options.channel,
2240
+ runtime: this.options.runtime,
2241
+ timeBucket,
2242
+ policyVersion: "strict.v1",
2243
+ dropped: includeDiagnostics ? this.dropped : 0,
2244
+ coalesced: includeDiagnostics ? this.coalesced : 0
2245
+ };
2246
+ const selected = [];
2247
+ let expiresAt = includeDiagnostics ? this.diagnosticExpiry : Infinity;
2248
+ for (const entry of entries) {
2249
+ if (entry.timeBucket !== timeBucket) continue;
2250
+ if (selected.length >= maxCounters || bytes({ ...base, counters: [...selected, entry.counter] }) > maxBytes) break;
2251
+ selected.push(entry.counter);
2252
+ expiresAt = Math.min(expiresAt, entry.expiresAt);
2253
+ }
2254
+ if (entries.some((entry) => entry.timeBucket === timeBucket) && selected.length === 0 || bytes({ ...base, counters: selected }) > maxBytes) return invalid();
2255
+ const batch = Object.freeze({ ...base, counters: Object.freeze(selected) });
2256
+ this.pending = { batch, expiresAt };
2257
+ return batch;
2258
+ }
2259
+ /** Check retry eligibility without extending the original snapshot's expiry. */
2260
+ isPendingBatch(batch, now) {
2261
+ this.prune(now);
2262
+ return this.pending?.batch === batch;
2263
+ }
2264
+ /** Only the exact issued snapshot may subtract counts, and only once. */
2265
+ acknowledge(batch) {
2266
+ if (this.pending?.batch !== batch) return;
2267
+ for (const counter of batch.counters) {
2268
+ const id = key(batch.timeBucket, counter);
2269
+ const current = this.counters.get(id);
2270
+ if (!current) continue;
2271
+ this.pendingBytes -= current.bytes;
2272
+ const remaining = current.counter.count - counter.count;
2273
+ if (remaining <= 0) this.counters.delete(id);
2274
+ else {
2275
+ const updatedCounter = Object.freeze({ ...current.counter, count: remaining });
2276
+ const updated = {
2277
+ ...current,
2278
+ counter: updatedCounter,
2279
+ bytes: bytes(updatedCounter) + encoder2.encode(id).length + 64
2280
+ };
2281
+ this.counters.set(id, updated);
2282
+ this.pendingBytes += updated.bytes;
2283
+ }
2284
+ }
2285
+ this.dropped = Math.max(0, this.dropped - batch.dropped);
2286
+ this.coalesced = Math.max(0, this.coalesced - batch.coalesced);
2287
+ if (!this.dropped && !this.coalesced) this.diagnosticHour = void 0;
2288
+ this.pending = void 0;
2289
+ }
2290
+ /** Discard aggregates and in-flight snapshot ownership; never flush. */
2291
+ clear() {
2292
+ this.counters.clear();
2293
+ this.pendingBytes = this.dropped = this.coalesced = this.diagnosticExpiry = 0;
2294
+ this.diagnosticHour = void 0;
2295
+ this.pending = void 0;
2296
+ }
2297
+ now() {
2298
+ return (this.options.now ?? Date.now)();
2299
+ }
2300
+ diagnostic(kind, increment, now) {
2301
+ const timeBucket = hour(now);
2302
+ this[kind] = add(this[kind], increment);
2303
+ if (!this.diagnosticHour) {
2304
+ this.diagnosticHour = timeBucket;
2305
+ this.diagnosticExpiry = now + this.maxAge;
2306
+ }
2307
+ }
2308
+ prune(now) {
2309
+ hour(now);
2310
+ if (this.pending && now >= this.pending.expiresAt) this.pending = void 0;
2311
+ if (this.diagnosticHour && now >= this.diagnosticExpiry) {
2312
+ this.dropped = this.coalesced = 0;
2313
+ this.diagnosticHour = void 0;
2314
+ }
2315
+ const expiredHours = new Set([...this.counters.values()].filter((entry) => now >= entry.expiresAt).map((entry) => entry.timeBucket));
2316
+ if (this.pending && expiredHours.has(this.pending.batch.timeBucket)) this.pending = void 0;
2317
+ for (const [id, entry] of this.counters) {
2318
+ if (!expiredHours.has(entry.timeBucket)) continue;
2319
+ this.counters.delete(id);
2320
+ this.pendingBytes -= entry.bytes;
2321
+ if (entry.counter.view === "total") this.diagnostic("dropped", entry.counter.count, now);
2322
+ }
2323
+ }
2324
+ sorted() {
2325
+ return [...this.counters.values()].sort((a, b) => {
2326
+ const left = key(a.timeBucket, a.counter);
2327
+ const right = key(b.timeBucket, b.counter);
2328
+ return left < right ? -1 : left > right ? 1 : 0;
2329
+ });
2330
+ }
2331
+ };
2332
+
1932
2333
  // src/journey/metrics.ts
1933
2334
  var durationBuckets = [
1934
2335
  [100, "lt100ms"],
@@ -1996,7 +2397,7 @@ function projectUsefulMetric(input) {
1996
2397
  const prototype = Object.getPrototypeOf(input);
1997
2398
  if (prototype !== Object.prototype && prototype !== null) return null;
1998
2399
  const keys = Reflect.ownKeys(input);
1999
- if (keys.length < 1 || keys.length > 2 || keys.some((key) => key !== "metric" && key !== "value")) return null;
2400
+ if (keys.length < 1 || keys.length > 2 || keys.some((key2) => key2 !== "metric" && key2 !== "value")) return null;
2000
2401
  const descriptors = Object.getOwnPropertyDescriptors(input);
2001
2402
  const metric = descriptors.metric;
2002
2403
  if (!metric || !("value" in metric) || typeof metric.value !== "string" || !Object.hasOwn(metrics, metric.value)) return null;
@@ -2416,20 +2817,20 @@ function readDataRecord(value, allowedFields, requiredFields = /* @__PURE__ */ n
2416
2817
  return invalidRuntimeEvidence();
2417
2818
  }
2418
2819
  const keys = Reflect.ownKeys(value);
2419
- if (keys.length > maximumFields || keys.some((key) => typeof key !== "string")) {
2820
+ if (keys.length > maximumFields || keys.some((key2) => typeof key2 !== "string")) {
2420
2821
  return invalidRuntimeEvidence();
2421
2822
  }
2422
2823
  const stringKeys = keys;
2423
- if (allowedFields && stringKeys.some((key) => !allowedFields.has(key)) || [...requiredFields].some((field2) => !stringKeys.includes(field2))) {
2824
+ if (allowedFields && stringKeys.some((key2) => !allowedFields.has(key2)) || [...requiredFields].some((field2) => !stringKeys.includes(field2))) {
2424
2825
  return invalidRuntimeEvidence();
2425
2826
  }
2426
2827
  const result = /* @__PURE__ */ Object.create(null);
2427
- for (const key of stringKeys) {
2428
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
2828
+ for (const key2 of stringKeys) {
2829
+ const descriptor = Object.getOwnPropertyDescriptor(value, key2);
2429
2830
  if (descriptor === void 0 || !("value" in descriptor)) {
2430
2831
  return invalidRuntimeEvidence();
2431
2832
  }
2432
- result[key] = descriptor.value;
2833
+ result[key2] = descriptor.value;
2433
2834
  }
2434
2835
  return result;
2435
2836
  }
@@ -2487,28 +2888,28 @@ function readOptionalIdentifier(value, validator) {
2487
2888
  return validator(value) ? value : invalidRuntimeEvidence();
2488
2889
  }
2489
2890
  function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
2490
- const record = readDataRecord(
2891
+ const record2 = readDataRecord(
2491
2892
  candidate,
2492
2893
  EVENT_FIELDS,
2493
2894
  EVENT_REQUIRED_FIELDS,
2494
2895
  EVENT_FIELDS.size
2495
2896
  );
2496
- 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)) {
2897
+ if (record2.schemaVersion !== "2.0" || !isEventId(record2.eventId) || !isJourneyId(record2.journeyId) || !isTraceId(record2.traceId) || !isSpanId(record2.spanId) || !isProducerId(record2.producerId) || !Number.isSafeInteger(record2.producerSequence) || record2.producerSequence < 1 || !Number.isSafeInteger(record2.occurredAtEpochMs) || record2.occurredAtEpochMs < 0 || !isSemanticSource(record2.source) || !allowedSources.has(record2.source) || !isValidChannelRuntime(record2.channel, record2.runtime)) {
2497
2898
  return invalidRuntimeEvidence();
2498
2899
  }
2499
- const parentSpanId = readOptionalIdentifier(record.parentSpanId, isSpanId);
2900
+ const parentSpanId = readOptionalIdentifier(record2.parentSpanId, isSpanId);
2500
2901
  const causedByEventId = readOptionalIdentifier(
2501
- record.causedByEventId,
2902
+ record2.causedByEventId,
2502
2903
  isEventId
2503
2904
  );
2504
2905
  const attributes = readDataRecord(
2505
- record.attributes,
2906
+ record2.attributes,
2506
2907
  void 0,
2507
2908
  /* @__PURE__ */ new Set(),
2508
2909
  MAX_EVENT_ATTRIBUTES2
2509
2910
  );
2510
2911
  const privacy = readDataRecord(
2511
- record.privacy,
2912
+ record2.privacy,
2512
2913
  PRIVACY_FIELDS,
2513
2914
  PRIVACY_FIELDS,
2514
2915
  PRIVACY_FIELDS.size
@@ -2517,9 +2918,9 @@ function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
2517
2918
  return invalidRuntimeEvidence();
2518
2919
  }
2519
2920
  let target;
2520
- if (record.target !== void 0) {
2921
+ if (record2.target !== void 0) {
2521
2922
  const targetRecord = readDataRecord(
2522
- record.target,
2923
+ record2.target,
2523
2924
  TARGET_FIELDS2,
2524
2925
  TARGET_FIELDS2,
2525
2926
  TARGET_FIELDS2.size
@@ -2530,29 +2931,29 @@ function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
2530
2931
  target = { type: targetRecord.type, id: targetRecord.id };
2531
2932
  }
2532
2933
  const input = {
2533
- name: record.name,
2534
- category: record.category,
2535
- phase: record.phase,
2536
- outcome: record.outcome,
2537
- ...record.modality === void 0 ? {} : { modality: record.modality },
2934
+ name: record2.name,
2935
+ category: record2.category,
2936
+ phase: record2.phase,
2937
+ outcome: record2.outcome,
2938
+ ...record2.modality === void 0 ? {} : { modality: record2.modality },
2538
2939
  ...target === void 0 ? {} : { target },
2539
2940
  attributes
2540
2941
  };
2541
2942
  const validated = validateSemanticJourneyEventInput(catalogue, input);
2542
2943
  return Object.freeze({
2543
2944
  schemaVersion: "2.0",
2544
- eventId: record.eventId,
2545
- journeyId: record.journeyId,
2546
- traceId: record.traceId,
2547
- spanId: record.spanId,
2945
+ eventId: record2.eventId,
2946
+ journeyId: record2.journeyId,
2947
+ traceId: record2.traceId,
2948
+ spanId: record2.spanId,
2548
2949
  ...parentSpanId === void 0 ? {} : { parentSpanId },
2549
2950
  ...causedByEventId === void 0 ? {} : { causedByEventId },
2550
- producerId: record.producerId,
2551
- producerSequence: record.producerSequence,
2552
- occurredAtEpochMs: record.occurredAtEpochMs,
2553
- source: record.source,
2554
- channel: record.channel,
2555
- runtime: record.runtime,
2951
+ producerId: record2.producerId,
2952
+ producerSequence: record2.producerSequence,
2953
+ occurredAtEpochMs: record2.occurredAtEpochMs,
2954
+ source: record2.source,
2955
+ channel: record2.channel,
2956
+ runtime: record2.runtime,
2556
2957
  name: validated.name,
2557
2958
  category: validated.category,
2558
2959
  phase: validated.phase,
@@ -2571,7 +2972,7 @@ function attributesEqual(left, right) {
2571
2972
  const leftKeys = Object.keys(left).sort(compareTokens);
2572
2973
  const rightKeys = Object.keys(right).sort(compareTokens);
2573
2974
  return leftKeys.length === rightKeys.length && leftKeys.every(
2574
- (key, index) => key === rightKeys[index] && Object.is(left[key], right[key])
2975
+ (key2, index) => key2 === rightKeys[index] && Object.is(left[key2], right[key2])
2575
2976
  );
2576
2977
  }
2577
2978
  function eventsEqual(left, right) {
@@ -2885,7 +3286,7 @@ function condensedCausalOrder(components) {
2885
3286
  }
2886
3287
  ready.sort(compareComponents);
2887
3288
  }
2888
- if (ordered.length !== components.reduce((count, item) => count + item.nodes.length, 0)) {
3289
+ if (ordered.length !== components.reduce((count2, item) => count2 + item.nodes.length, 0)) {
2889
3290
  return invalidRuntimeEvidence();
2890
3291
  }
2891
3292
  return ordered;
@@ -3217,6 +3618,7 @@ function resolveConfig2(config) {
3217
3618
  if (!config.catalogue.sources.includes(config.source)) {
3218
3619
  return invalidConfig();
3219
3620
  }
3621
+ if (config.aggregatePolicy !== void 0 && (!isSemanticJourneyAggregatePolicy(config.aggregatePolicy) || JSON.stringify(config.aggregatePolicy.catalogue) !== JSON.stringify(config.catalogue))) return invalidConfig();
3220
3622
  if (config.aggregateEndpoint !== void 0 && !isAllowedEndpoint(config.aggregateEndpoint, config.aggregateBaseUrl)) {
3221
3623
  return invalidConfig();
3222
3624
  }
@@ -3235,6 +3637,7 @@ function resolveConfig2(config) {
3235
3637
  );
3236
3638
  return {
3237
3639
  catalogue: config.catalogue,
3640
+ ...config.aggregatePolicy ? { aggregatePolicy: config.aggregatePolicy } : {},
3238
3641
  source: config.source,
3239
3642
  channel: resolveChannel2(config.channel, runtime),
3240
3643
  runtime,
@@ -3265,7 +3668,7 @@ function resolveConfig2(config) {
3265
3668
  ),
3266
3669
  maxBatchesPerFlush: resolveInteger(
3267
3670
  config.maxBatchesPerFlush,
3268
- DEFAULT_MAX_BATCHES_PER_FLUSH,
3671
+ config.aggregatePolicy ? 2 : DEFAULT_MAX_BATCHES_PER_FLUSH,
3269
3672
  1,
3270
3673
  MAX_BATCHES_PER_FLUSH
3271
3674
  ),
@@ -3343,11 +3746,11 @@ function jitteredDelay(attempt, config) {
3343
3746
  config.retryMaxDelayMs,
3344
3747
  config.retryBaseDelayMs * 2 ** attempt
3345
3748
  );
3346
- const bytes = config.randomBytes ? config.randomBytes(2) : globalThis.crypto.getRandomValues(new Uint8Array(2));
3347
- if (!(bytes instanceof Uint8Array) || bytes.byteLength !== 2) {
3749
+ const bytes2 = config.randomBytes ? config.randomBytes(2) : globalThis.crypto.getRandomValues(new Uint8Array(2));
3750
+ if (!(bytes2 instanceof Uint8Array) || bytes2.byteLength !== 2) {
3348
3751
  throw new Error("Semantic journey retry random source is invalid.");
3349
3752
  }
3350
- const sample = (bytes[0] ?? 0) << 8 | (bytes[1] ?? 0);
3753
+ const sample = (bytes2[0] ?? 0) << 8 | (bytes2[1] ?? 0);
3351
3754
  const factor = 0.5 + sample / 65535;
3352
3755
  return Math.min(config.retryMaxDelayMs, Math.max(1, Math.round(exponential * factor)));
3353
3756
  }
@@ -3358,12 +3761,16 @@ function createSemanticJourneyClient(inputConfig) {
3358
3761
  } catch {
3359
3762
  return invalidConfig();
3360
3763
  }
3361
- const aggregateStore = new SemanticJourneyAggregateStore({
3362
- catalogue: config.catalogue,
3363
- source: config.source,
3364
- channel: config.channel,
3365
- runtime: config.runtime
3366
- });
3764
+ const binding = { source: config.source, channel: config.channel, runtime: config.runtime };
3765
+ const aggregateStore = config.aggregatePolicy ? new ProjectedSemanticJourneyAggregateStore({
3766
+ ...binding,
3767
+ policy: config.aggregatePolicy,
3768
+ maxPendingCounters: config.maxQueueEvents,
3769
+ maxPendingBytes: config.maxQueueBytes,
3770
+ maxBatchBytes: config.aggregateMaxBytes,
3771
+ maxAgeMs: config.maxEventAgeMs,
3772
+ now: config.now
3773
+ }) : new SemanticJourneyAggregateStore({ ...binding, catalogue: config.catalogue });
3367
3774
  const queue = [];
3368
3775
  const contextByEventId = /* @__PURE__ */ new Map();
3369
3776
  let episode;
@@ -3460,7 +3867,15 @@ function createSemanticJourneyClient(inputConfig) {
3460
3867
  droppedAttributeCount: validated.droppedAttributeCount
3461
3868
  })
3462
3869
  });
3463
- aggregateStore.record(event.name, event.outcome);
3870
+ if (aggregateStore instanceof ProjectedSemanticJourneyAggregateStore) {
3871
+ if (!aggregateStore.recordEvent({
3872
+ name: validated.name,
3873
+ category: validated.category,
3874
+ phase: validated.phase,
3875
+ outcome: validated.outcome,
3876
+ attributes: validated.attributes
3877
+ }, nowEpochMs)) notifyDrop("queue-limit");
3878
+ } else aggregateStore.record(event.name, event.outcome);
3464
3879
  if (shouldCoalesce(
3465
3880
  queue[queue.length - 1]?.event,
3466
3881
  event,
@@ -3469,17 +3884,17 @@ function createSemanticJourneyClient(inputConfig) {
3469
3884
  aggregateStore.recordCoalesced();
3470
3885
  return void 0;
3471
3886
  }
3472
- const bytes = eventBytes(event);
3473
- if (bytes > config.maxQueueBytes) {
3887
+ const bytes2 = eventBytes(event);
3888
+ if (bytes2 > config.maxQueueBytes) {
3474
3889
  aggregateStore.recordDropped();
3475
3890
  notifyDrop("queue-limit");
3476
3891
  return void 0;
3477
3892
  }
3478
- while (queue.length >= config.maxQueueEvents || queueBytes + bytes > config.maxQueueBytes) {
3893
+ while (queue.length >= config.maxQueueEvents || queueBytes + bytes2 > config.maxQueueBytes) {
3479
3894
  removeFirstQueued("queue-limit");
3480
3895
  }
3481
- queue.push({ event, context: options.context, bytes });
3482
- queueBytes += bytes;
3896
+ queue.push({ event, context: options.context, bytes: bytes2 });
3897
+ queueBytes += bytes2;
3483
3898
  contextByEventId.set(event.eventId, options.context);
3484
3899
  if (usesLocalProducer) {
3485
3900
  currentEpisode.producerSequence = producerSequence;
@@ -3721,6 +4136,10 @@ function createSemanticJourneyClient(inputConfig) {
3721
4136
  if (destroyed || signal.aborted) {
3722
4137
  return "retained";
3723
4138
  }
4139
+ if (aggregateStore instanceof ProjectedSemanticJourneyAggregateStore && batch.schemaVersion === "2.1-aggregate" && !aggregateStore.isPendingBatch(batch, config.now())) {
4140
+ notifyDrop("expired");
4141
+ return "discarded";
4142
+ }
3724
4143
  try {
3725
4144
  await sendWithTimeout(batch, keepalive);
3726
4145
  return "sent";
@@ -3751,6 +4170,7 @@ function createSemanticJourneyClient(inputConfig) {
3751
4170
  const generation = aggregateGeneration;
3752
4171
  const signal = aggregateController.signal;
3753
4172
  for (let sentBatchCount = 0; sentBatchCount < config.maxBatchesPerFlush; sentBatchCount += 1) {
4173
+ if (aggregateStore instanceof ProjectedSemanticJourneyAggregateStore && pendingBatch?.schemaVersion === "2.1-aggregate" && !aggregateStore.isPendingBatch(pendingBatch, config.now())) pendingBatch = void 0;
3754
4174
  const batch = pendingBatch ?? aggregateStore.createBatch({
3755
4175
  batchId: createEventId(config.randomBytes),
3756
4176
  nowEpochMs: config.now(),
@@ -3768,7 +4188,9 @@ function createSemanticJourneyClient(inputConfig) {
3768
4188
  if (result === "retained") {
3769
4189
  return;
3770
4190
  }
3771
- aggregateStore.acknowledge(batch);
4191
+ if (aggregateStore instanceof ProjectedSemanticJourneyAggregateStore) {
4192
+ if (batch.schemaVersion === "2.1-aggregate") aggregateStore.acknowledge(batch);
4193
+ } else if (batch.schemaVersion === "2.0-aggregate") aggregateStore.acknowledge(batch);
3772
4194
  pendingBatch = void 0;
3773
4195
  }
3774
4196
  };
@@ -3992,7 +4414,10 @@ function useComponentInteractionTracker(component, baseContext = {}) {
3992
4414
  }
3993
4415
  export {
3994
4416
  AnalyticsProvider,
4417
+ ProjectedSemanticJourneyAggregateStore,
4418
+ SEMANTIC_JOURNEY_AGGREGATE_MAX_BYTES,
3995
4419
  SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION,
4420
+ SEMANTIC_JOURNEY_PROJECTED_AGGREGATE_SCHEMA_VERSION,
3996
4421
  SEMANTIC_JOURNEY_RECEIPT_HEADER,
3997
4422
  SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES,
3998
4423
  SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT,
@@ -4016,10 +4441,12 @@ export {
4016
4441
  createProducerId,
4017
4442
  createRequestJourneyContext,
4018
4443
  createSecureRandomHex,
4444
+ createSemanticJourneyAggregateValidator,
4019
4445
  createSemanticJourneyClient,
4020
4446
  createSpanId,
4021
4447
  createTraceId,
4022
4448
  defineJourneyEvent,
4449
+ defineSemanticJourneyAggregatePolicy,
4023
4450
  defineSemanticJourneyCatalog,
4024
4451
  formatTraceparent,
4025
4452
  getJourneyEventDefinition,
@@ -4028,6 +4455,7 @@ export {
4028
4455
  isJourneyToken,
4029
4456
  isProducerId,
4030
4457
  isSecureSemanticJourneyEndpoint,
4458
+ isSemanticJourneyAggregatePolicy,
4031
4459
  isSemanticSource,
4032
4460
  isSemanticToken,
4033
4461
  isSpanId,
@@ -4035,8 +4463,10 @@ export {
4035
4463
  observeSemanticJourneyInteractions,
4036
4464
  parseSemanticJourneyReceipts,
4037
4465
  parseTraceparent,
4466
+ projectSemanticJourneyAggregateCounters,
4038
4467
  projectUsefulMetric,
4039
4468
  reconstructSemanticJourney,
4469
+ semanticJourneyAggregateCounterKey,
4040
4470
  serializeSemanticJourneyReceipts,
4041
4471
  useAnalytics,
4042
4472
  useComponentInteractionTracker,