@plasius/analytics 1.3.3 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -1
- package/dist/index.cjs +524 -98
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +103 -3
- package/dist/index.d.ts +103 -3
- package/dist/index.js +513 -95
- package/dist/index.js.map +1 -1
- package/dist/{metrics-B7L9phdM.d.cts → metrics-DhAg1PSO.d.cts} +1 -1
- package/dist/{metrics-B7L9phdM.d.ts → metrics-DhAg1PSO.d.ts} +1 -1
- package/dist/metrics.d.cts +1 -1
- package/dist/metrics.d.ts +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -400,8 +400,8 @@ function sanitizeMultiline(value, maxLength) {
|
|
|
400
400
|
function isPlainObject(value) {
|
|
401
401
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
402
402
|
}
|
|
403
|
-
function shouldRedactContextKey(
|
|
404
|
-
const loweredKey =
|
|
403
|
+
function shouldRedactContextKey(key2, resolvedErrorReporting) {
|
|
404
|
+
const loweredKey = key2.trim().toLowerCase();
|
|
405
405
|
if (!loweredKey) {
|
|
406
406
|
return false;
|
|
407
407
|
}
|
|
@@ -481,10 +481,10 @@ function sanitizeContextValue(value, resolvedErrorReporting, depth, seen, identi
|
|
|
481
481
|
}
|
|
482
482
|
const sanitized = {};
|
|
483
483
|
const entries = Object.entries(value).slice(0, resolvedErrorReporting.maxContextBreadth);
|
|
484
|
-
for (const [
|
|
485
|
-
const childPath = keyPath ? `${keyPath}.${
|
|
486
|
-
if (shouldRedactContextKey(
|
|
487
|
-
sanitized[
|
|
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;
|
|
488
488
|
pushIdentifier(
|
|
489
489
|
identifiers,
|
|
490
490
|
childPath,
|
|
@@ -493,7 +493,7 @@ function sanitizeContextValue(value, resolvedErrorReporting, depth, seen, identi
|
|
|
493
493
|
);
|
|
494
494
|
continue;
|
|
495
495
|
}
|
|
496
|
-
sanitized[
|
|
496
|
+
sanitized[key2] = sanitizeContextValue(
|
|
497
497
|
nestedValue,
|
|
498
498
|
resolvedErrorReporting,
|
|
499
499
|
depth + 1,
|
|
@@ -514,19 +514,19 @@ function sanitizeErrorContext(context, resolvedErrorReporting) {
|
|
|
514
514
|
const identifiers = [];
|
|
515
515
|
const seen = /* @__PURE__ */ new WeakSet();
|
|
516
516
|
const entries = Object.entries(context).slice(0, resolvedErrorReporting.maxContextBreadth);
|
|
517
|
-
for (const [
|
|
518
|
-
if (shouldRedactContextKey(
|
|
519
|
-
sanitized[
|
|
520
|
-
pushIdentifier(identifiers,
|
|
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);
|
|
521
521
|
continue;
|
|
522
522
|
}
|
|
523
|
-
sanitized[
|
|
523
|
+
sanitized[key2] = sanitizeContextValue(
|
|
524
524
|
value,
|
|
525
525
|
resolvedErrorReporting,
|
|
526
526
|
1,
|
|
527
527
|
seen,
|
|
528
528
|
identifiers,
|
|
529
|
-
|
|
529
|
+
key2
|
|
530
530
|
);
|
|
531
531
|
}
|
|
532
532
|
return {
|
|
@@ -710,7 +710,7 @@ function readQueue(storageKey, fallbackConfig) {
|
|
|
710
710
|
if (!Array.isArray(parsed)) {
|
|
711
711
|
return [];
|
|
712
712
|
}
|
|
713
|
-
return parsed.filter(isStoredRecordCandidate).map((
|
|
713
|
+
return parsed.filter(isStoredRecordCandidate).map((record2) => normalizeStoredRecord(record2, fallbackConfig));
|
|
714
714
|
} catch {
|
|
715
715
|
return [];
|
|
716
716
|
}
|
|
@@ -875,12 +875,12 @@ function createLocalSpaceAnalyticsClient(config) {
|
|
|
875
875
|
return right.lastSeen - left.lastSeen;
|
|
876
876
|
});
|
|
877
877
|
};
|
|
878
|
-
const enqueueRecord = (
|
|
879
|
-
queue.push(
|
|
878
|
+
const enqueueRecord = (record2) => {
|
|
879
|
+
queue.push(record2);
|
|
880
880
|
trimQueue();
|
|
881
881
|
persistQueue();
|
|
882
|
-
if (
|
|
883
|
-
recordIssue(
|
|
882
|
+
if (record2.kind === "error" && record2.error) {
|
|
883
|
+
recordIssue(record2.error, record2.timestamp, true);
|
|
884
884
|
}
|
|
885
885
|
if (queue.length >= resolvedConfig.batchSize) {
|
|
886
886
|
void flush();
|
|
@@ -997,9 +997,9 @@ function createLocalSpaceAnalyticsClient(config) {
|
|
|
997
997
|
document.addEventListener("visibilitychange", handleVisibilityChange);
|
|
998
998
|
window.addEventListener("pagehide", handlePageHide);
|
|
999
999
|
}
|
|
1000
|
-
for (const
|
|
1001
|
-
if (
|
|
1002
|
-
recordIssue(
|
|
1000
|
+
for (const record2 of queue) {
|
|
1001
|
+
if (record2.kind === "error" && record2.error) {
|
|
1002
|
+
recordIssue(record2.error, record2.timestamp, false);
|
|
1003
1003
|
}
|
|
1004
1004
|
}
|
|
1005
1005
|
startFlushTimer();
|
|
@@ -1018,7 +1018,7 @@ function createLocalSpaceAnalyticsClient(config) {
|
|
|
1018
1018
|
const requestId = typeof event.requestId === "string" && event.requestId.trim() ? event.requestId.trim() : void 0;
|
|
1019
1019
|
const kind = event.kind === "error" ? "error" : "interaction";
|
|
1020
1020
|
const normalizedError = kind === "error" && isErrorDetailsCandidate(event.error) ? normalizeStoredErrorDetails(event.error, resolvedConfig.errorReporting) : void 0;
|
|
1021
|
-
const
|
|
1021
|
+
const record2 = {
|
|
1022
1022
|
id: createId("event"),
|
|
1023
1023
|
component: event.component,
|
|
1024
1024
|
action: event.action,
|
|
@@ -1035,7 +1035,7 @@ function createLocalSpaceAnalyticsClient(config) {
|
|
|
1035
1035
|
context: createMergedContext(resolvedConfig, eventChannel, event.context),
|
|
1036
1036
|
error: normalizedError
|
|
1037
1037
|
};
|
|
1038
|
-
enqueueRecord(
|
|
1038
|
+
enqueueRecord(record2);
|
|
1039
1039
|
};
|
|
1040
1040
|
const reportError = (report) => {
|
|
1041
1041
|
if (isDestroyed || !resolvedConfig.enabled) {
|
|
@@ -1069,7 +1069,7 @@ function createLocalSpaceAnalyticsClient(config) {
|
|
|
1069
1069
|
if (normalizedError.tags && normalizedError.tags.length > 0) {
|
|
1070
1070
|
errorContext.errorTags = normalizedError.tags;
|
|
1071
1071
|
}
|
|
1072
|
-
const
|
|
1072
|
+
const record2 = {
|
|
1073
1073
|
id: createId("event"),
|
|
1074
1074
|
component: normalizedError.boundary,
|
|
1075
1075
|
action: normalizedError.handled ? "error_boundary_caught" : "unhandled_error",
|
|
@@ -1083,7 +1083,7 @@ function createLocalSpaceAnalyticsClient(config) {
|
|
|
1083
1083
|
context: createMergedContext(resolvedConfig, eventChannel, errorContext),
|
|
1084
1084
|
error: normalizedError
|
|
1085
1085
|
};
|
|
1086
|
-
enqueueRecord(
|
|
1086
|
+
enqueueRecord(record2);
|
|
1087
1087
|
};
|
|
1088
1088
|
return {
|
|
1089
1089
|
get source() {
|
|
@@ -1351,13 +1351,13 @@ function isRecord(value) {
|
|
|
1351
1351
|
}
|
|
1352
1352
|
function getOwnStringKeys(value) {
|
|
1353
1353
|
const keys = Reflect.ownKeys(value);
|
|
1354
|
-
if (keys.some((
|
|
1354
|
+
if (keys.some((key2) => typeof key2 !== "string")) {
|
|
1355
1355
|
return null;
|
|
1356
1356
|
}
|
|
1357
1357
|
return keys;
|
|
1358
1358
|
}
|
|
1359
1359
|
function hasOnlyFields(keys, allowed) {
|
|
1360
|
-
return keys.every((
|
|
1360
|
+
return keys.every((key2) => allowed.has(key2));
|
|
1361
1361
|
}
|
|
1362
1362
|
function sensitivityWords(value) {
|
|
1363
1363
|
return value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.toLowerCase());
|
|
@@ -1477,11 +1477,11 @@ function normalizeEventDefinition(candidate) {
|
|
|
1477
1477
|
if (targetKeys === null || targetKeys.length !== 2 || !hasOnlyFields(targetKeys, TARGET_FIELDS) || !isSemanticToken(target.type) || !isSemanticToken(target.id) || looksSensitive(target.type) || looksSensitive(target.id)) {
|
|
1478
1478
|
return invalidDefinition();
|
|
1479
1479
|
}
|
|
1480
|
-
const
|
|
1481
|
-
if (seenTargets.has(
|
|
1480
|
+
const key2 = `${target.type}\0${target.id}`;
|
|
1481
|
+
if (seenTargets.has(key2)) {
|
|
1482
1482
|
return invalidDefinition();
|
|
1483
1483
|
}
|
|
1484
|
-
seenTargets.add(
|
|
1484
|
+
seenTargets.add(key2);
|
|
1485
1485
|
targets.push(Object.freeze({ type: target.type, id: target.id }));
|
|
1486
1486
|
}
|
|
1487
1487
|
}
|
|
@@ -1663,12 +1663,12 @@ function createSecureRandomHex(byteLength2, randomBytes = webCryptoRandomBytes)
|
|
|
1663
1663
|
if (!Number.isSafeInteger(byteLength2) || byteLength2 <= 0 || byteLength2 > MAX_RANDOM_BYTE_LENGTH) {
|
|
1664
1664
|
throw new Error("Secure random byte length is invalid.");
|
|
1665
1665
|
}
|
|
1666
|
-
const
|
|
1667
|
-
if (!(
|
|
1666
|
+
const bytes2 = randomBytes(byteLength2);
|
|
1667
|
+
if (!(bytes2 instanceof Uint8Array) || bytes2.byteLength !== byteLength2) {
|
|
1668
1668
|
throw new Error("Secure random source returned invalid bytes.");
|
|
1669
1669
|
}
|
|
1670
1670
|
let result = "";
|
|
1671
|
-
for (const byte of
|
|
1671
|
+
for (const byte of bytes2) {
|
|
1672
1672
|
result += byte.toString(16).padStart(2, "0");
|
|
1673
1673
|
}
|
|
1674
1674
|
return result;
|
|
@@ -1835,29 +1835,29 @@ var SemanticJourneyAggregateStore = class {
|
|
|
1835
1835
|
}
|
|
1836
1836
|
this.options = Object.freeze({ ...options });
|
|
1837
1837
|
}
|
|
1838
|
-
record(eventName, outcome,
|
|
1838
|
+
record(eventName, outcome, count2 = 1) {
|
|
1839
1839
|
if (!isSemanticToken(eventName) || getJourneyEventDefinition(this.options.catalogue, eventName) === void 0 || !OUTCOMES2.has(outcome)) {
|
|
1840
1840
|
invalidAggregate();
|
|
1841
1841
|
}
|
|
1842
|
-
normalizeLimit(
|
|
1843
|
-
const
|
|
1844
|
-
const existing = this.counters.get(
|
|
1845
|
-
this.counters.set(
|
|
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({
|
|
1846
1846
|
eventName,
|
|
1847
1847
|
outcome,
|
|
1848
|
-
count: addSafeCount(existing?.count ?? 0,
|
|
1848
|
+
count: addSafeCount(existing?.count ?? 0, count2)
|
|
1849
1849
|
}));
|
|
1850
1850
|
}
|
|
1851
|
-
recordDropped(
|
|
1851
|
+
recordDropped(count2 = 1) {
|
|
1852
1852
|
this.dropped = addSafeCount(
|
|
1853
1853
|
this.dropped,
|
|
1854
|
-
normalizeLimit(
|
|
1854
|
+
normalizeLimit(count2, 1, "dropped increment")
|
|
1855
1855
|
);
|
|
1856
1856
|
}
|
|
1857
|
-
recordCoalesced(
|
|
1857
|
+
recordCoalesced(count2 = 1) {
|
|
1858
1858
|
this.coalesced = addSafeCount(
|
|
1859
1859
|
this.coalesced,
|
|
1860
|
-
normalizeLimit(
|
|
1860
|
+
normalizeLimit(count2, 1, "coalesced increment")
|
|
1861
1861
|
);
|
|
1862
1862
|
}
|
|
1863
1863
|
snapshot() {
|
|
@@ -1913,16 +1913,16 @@ var SemanticJourneyAggregateStore = class {
|
|
|
1913
1913
|
}
|
|
1914
1914
|
acknowledge(batch) {
|
|
1915
1915
|
for (const acknowledged of batch.counters) {
|
|
1916
|
-
const
|
|
1917
|
-
const current = this.counters.get(
|
|
1916
|
+
const key2 = toCounterKey(acknowledged.eventName, acknowledged.outcome);
|
|
1917
|
+
const current = this.counters.get(key2);
|
|
1918
1918
|
if (!current) {
|
|
1919
1919
|
continue;
|
|
1920
1920
|
}
|
|
1921
1921
|
const remaining = current.count - acknowledged.count;
|
|
1922
1922
|
if (remaining > 0) {
|
|
1923
|
-
this.counters.set(
|
|
1923
|
+
this.counters.set(key2, Object.freeze({ ...current, count: remaining }));
|
|
1924
1924
|
} else {
|
|
1925
|
-
this.counters.delete(
|
|
1925
|
+
this.counters.delete(key2);
|
|
1926
1926
|
}
|
|
1927
1927
|
}
|
|
1928
1928
|
this.dropped = Math.max(0, this.dropped - batch.dropped);
|
|
@@ -1941,6 +1941,395 @@ var SemanticJourneyAggregateStore = class {
|
|
|
1941
1941
|
}
|
|
1942
1942
|
};
|
|
1943
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
|
+
|
|
1944
2333
|
// src/journey/metrics.ts
|
|
1945
2334
|
var durationBuckets = [
|
|
1946
2335
|
[100, "lt100ms"],
|
|
@@ -2008,7 +2397,7 @@ function projectUsefulMetric(input) {
|
|
|
2008
2397
|
const prototype = Object.getPrototypeOf(input);
|
|
2009
2398
|
if (prototype !== Object.prototype && prototype !== null) return null;
|
|
2010
2399
|
const keys = Reflect.ownKeys(input);
|
|
2011
|
-
if (keys.length < 1 || keys.length > 2 || keys.some((
|
|
2400
|
+
if (keys.length < 1 || keys.length > 2 || keys.some((key2) => key2 !== "metric" && key2 !== "value")) return null;
|
|
2012
2401
|
const descriptors = Object.getOwnPropertyDescriptors(input);
|
|
2013
2402
|
const metric = descriptors.metric;
|
|
2014
2403
|
if (!metric || !("value" in metric) || typeof metric.value !== "string" || !Object.hasOwn(metrics, metric.value)) return null;
|
|
@@ -2428,20 +2817,20 @@ function readDataRecord(value, allowedFields, requiredFields = /* @__PURE__ */ n
|
|
|
2428
2817
|
return invalidRuntimeEvidence();
|
|
2429
2818
|
}
|
|
2430
2819
|
const keys = Reflect.ownKeys(value);
|
|
2431
|
-
if (keys.length > maximumFields || keys.some((
|
|
2820
|
+
if (keys.length > maximumFields || keys.some((key2) => typeof key2 !== "string")) {
|
|
2432
2821
|
return invalidRuntimeEvidence();
|
|
2433
2822
|
}
|
|
2434
2823
|
const stringKeys = keys;
|
|
2435
|
-
if (allowedFields && stringKeys.some((
|
|
2824
|
+
if (allowedFields && stringKeys.some((key2) => !allowedFields.has(key2)) || [...requiredFields].some((field2) => !stringKeys.includes(field2))) {
|
|
2436
2825
|
return invalidRuntimeEvidence();
|
|
2437
2826
|
}
|
|
2438
2827
|
const result = /* @__PURE__ */ Object.create(null);
|
|
2439
|
-
for (const
|
|
2440
|
-
const descriptor = Object.getOwnPropertyDescriptor(value,
|
|
2828
|
+
for (const key2 of stringKeys) {
|
|
2829
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key2);
|
|
2441
2830
|
if (descriptor === void 0 || !("value" in descriptor)) {
|
|
2442
2831
|
return invalidRuntimeEvidence();
|
|
2443
2832
|
}
|
|
2444
|
-
result[
|
|
2833
|
+
result[key2] = descriptor.value;
|
|
2445
2834
|
}
|
|
2446
2835
|
return result;
|
|
2447
2836
|
}
|
|
@@ -2499,28 +2888,28 @@ function readOptionalIdentifier(value, validator) {
|
|
|
2499
2888
|
return validator(value) ? value : invalidRuntimeEvidence();
|
|
2500
2889
|
}
|
|
2501
2890
|
function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
|
|
2502
|
-
const
|
|
2891
|
+
const record2 = readDataRecord(
|
|
2503
2892
|
candidate,
|
|
2504
2893
|
EVENT_FIELDS,
|
|
2505
2894
|
EVENT_REQUIRED_FIELDS,
|
|
2506
2895
|
EVENT_FIELDS.size
|
|
2507
2896
|
);
|
|
2508
|
-
if (
|
|
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)) {
|
|
2509
2898
|
return invalidRuntimeEvidence();
|
|
2510
2899
|
}
|
|
2511
|
-
const parentSpanId = readOptionalIdentifier(
|
|
2900
|
+
const parentSpanId = readOptionalIdentifier(record2.parentSpanId, isSpanId);
|
|
2512
2901
|
const causedByEventId = readOptionalIdentifier(
|
|
2513
|
-
|
|
2902
|
+
record2.causedByEventId,
|
|
2514
2903
|
isEventId
|
|
2515
2904
|
);
|
|
2516
2905
|
const attributes = readDataRecord(
|
|
2517
|
-
|
|
2906
|
+
record2.attributes,
|
|
2518
2907
|
void 0,
|
|
2519
2908
|
/* @__PURE__ */ new Set(),
|
|
2520
2909
|
MAX_EVENT_ATTRIBUTES2
|
|
2521
2910
|
);
|
|
2522
2911
|
const privacy = readDataRecord(
|
|
2523
|
-
|
|
2912
|
+
record2.privacy,
|
|
2524
2913
|
PRIVACY_FIELDS,
|
|
2525
2914
|
PRIVACY_FIELDS,
|
|
2526
2915
|
PRIVACY_FIELDS.size
|
|
@@ -2529,9 +2918,9 @@ function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
|
|
|
2529
2918
|
return invalidRuntimeEvidence();
|
|
2530
2919
|
}
|
|
2531
2920
|
let target;
|
|
2532
|
-
if (
|
|
2921
|
+
if (record2.target !== void 0) {
|
|
2533
2922
|
const targetRecord = readDataRecord(
|
|
2534
|
-
|
|
2923
|
+
record2.target,
|
|
2535
2924
|
TARGET_FIELDS2,
|
|
2536
2925
|
TARGET_FIELDS2,
|
|
2537
2926
|
TARGET_FIELDS2.size
|
|
@@ -2542,29 +2931,29 @@ function normalizeRuntimeEvent(catalogue, allowedSources, candidate) {
|
|
|
2542
2931
|
target = { type: targetRecord.type, id: targetRecord.id };
|
|
2543
2932
|
}
|
|
2544
2933
|
const input = {
|
|
2545
|
-
name:
|
|
2546
|
-
category:
|
|
2547
|
-
phase:
|
|
2548
|
-
outcome:
|
|
2549
|
-
...
|
|
2934
|
+
name: record2.name,
|
|
2935
|
+
category: record2.category,
|
|
2936
|
+
phase: record2.phase,
|
|
2937
|
+
outcome: record2.outcome,
|
|
2938
|
+
...record2.modality === void 0 ? {} : { modality: record2.modality },
|
|
2550
2939
|
...target === void 0 ? {} : { target },
|
|
2551
2940
|
attributes
|
|
2552
2941
|
};
|
|
2553
2942
|
const validated = validateSemanticJourneyEventInput(catalogue, input);
|
|
2554
2943
|
return Object.freeze({
|
|
2555
2944
|
schemaVersion: "2.0",
|
|
2556
|
-
eventId:
|
|
2557
|
-
journeyId:
|
|
2558
|
-
traceId:
|
|
2559
|
-
spanId:
|
|
2945
|
+
eventId: record2.eventId,
|
|
2946
|
+
journeyId: record2.journeyId,
|
|
2947
|
+
traceId: record2.traceId,
|
|
2948
|
+
spanId: record2.spanId,
|
|
2560
2949
|
...parentSpanId === void 0 ? {} : { parentSpanId },
|
|
2561
2950
|
...causedByEventId === void 0 ? {} : { causedByEventId },
|
|
2562
|
-
producerId:
|
|
2563
|
-
producerSequence:
|
|
2564
|
-
occurredAtEpochMs:
|
|
2565
|
-
source:
|
|
2566
|
-
channel:
|
|
2567
|
-
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,
|
|
2568
2957
|
name: validated.name,
|
|
2569
2958
|
category: validated.category,
|
|
2570
2959
|
phase: validated.phase,
|
|
@@ -2583,7 +2972,7 @@ function attributesEqual(left, right) {
|
|
|
2583
2972
|
const leftKeys = Object.keys(left).sort(compareTokens);
|
|
2584
2973
|
const rightKeys = Object.keys(right).sort(compareTokens);
|
|
2585
2974
|
return leftKeys.length === rightKeys.length && leftKeys.every(
|
|
2586
|
-
(
|
|
2975
|
+
(key2, index) => key2 === rightKeys[index] && Object.is(left[key2], right[key2])
|
|
2587
2976
|
);
|
|
2588
2977
|
}
|
|
2589
2978
|
function eventsEqual(left, right) {
|
|
@@ -2897,7 +3286,7 @@ function condensedCausalOrder(components) {
|
|
|
2897
3286
|
}
|
|
2898
3287
|
ready.sort(compareComponents);
|
|
2899
3288
|
}
|
|
2900
|
-
if (ordered.length !== components.reduce((
|
|
3289
|
+
if (ordered.length !== components.reduce((count2, item) => count2 + item.nodes.length, 0)) {
|
|
2901
3290
|
return invalidRuntimeEvidence();
|
|
2902
3291
|
}
|
|
2903
3292
|
return ordered;
|
|
@@ -3229,6 +3618,7 @@ function resolveConfig2(config) {
|
|
|
3229
3618
|
if (!config.catalogue.sources.includes(config.source)) {
|
|
3230
3619
|
return invalidConfig();
|
|
3231
3620
|
}
|
|
3621
|
+
if (config.aggregatePolicy !== void 0 && (!isSemanticJourneyAggregatePolicy(config.aggregatePolicy) || JSON.stringify(config.aggregatePolicy.catalogue) !== JSON.stringify(config.catalogue))) return invalidConfig();
|
|
3232
3622
|
if (config.aggregateEndpoint !== void 0 && !isAllowedEndpoint(config.aggregateEndpoint, config.aggregateBaseUrl)) {
|
|
3233
3623
|
return invalidConfig();
|
|
3234
3624
|
}
|
|
@@ -3247,6 +3637,7 @@ function resolveConfig2(config) {
|
|
|
3247
3637
|
);
|
|
3248
3638
|
return {
|
|
3249
3639
|
catalogue: config.catalogue,
|
|
3640
|
+
...config.aggregatePolicy ? { aggregatePolicy: config.aggregatePolicy } : {},
|
|
3250
3641
|
source: config.source,
|
|
3251
3642
|
channel: resolveChannel2(config.channel, runtime),
|
|
3252
3643
|
runtime,
|
|
@@ -3277,7 +3668,7 @@ function resolveConfig2(config) {
|
|
|
3277
3668
|
),
|
|
3278
3669
|
maxBatchesPerFlush: resolveInteger(
|
|
3279
3670
|
config.maxBatchesPerFlush,
|
|
3280
|
-
DEFAULT_MAX_BATCHES_PER_FLUSH,
|
|
3671
|
+
config.aggregatePolicy ? 2 : DEFAULT_MAX_BATCHES_PER_FLUSH,
|
|
3281
3672
|
1,
|
|
3282
3673
|
MAX_BATCHES_PER_FLUSH
|
|
3283
3674
|
),
|
|
@@ -3355,11 +3746,11 @@ function jitteredDelay(attempt, config) {
|
|
|
3355
3746
|
config.retryMaxDelayMs,
|
|
3356
3747
|
config.retryBaseDelayMs * 2 ** attempt
|
|
3357
3748
|
);
|
|
3358
|
-
const
|
|
3359
|
-
if (!(
|
|
3749
|
+
const bytes2 = config.randomBytes ? config.randomBytes(2) : globalThis.crypto.getRandomValues(new Uint8Array(2));
|
|
3750
|
+
if (!(bytes2 instanceof Uint8Array) || bytes2.byteLength !== 2) {
|
|
3360
3751
|
throw new Error("Semantic journey retry random source is invalid.");
|
|
3361
3752
|
}
|
|
3362
|
-
const sample = (
|
|
3753
|
+
const sample = (bytes2[0] ?? 0) << 8 | (bytes2[1] ?? 0);
|
|
3363
3754
|
const factor = 0.5 + sample / 65535;
|
|
3364
3755
|
return Math.min(config.retryMaxDelayMs, Math.max(1, Math.round(exponential * factor)));
|
|
3365
3756
|
}
|
|
@@ -3370,12 +3761,16 @@ function createSemanticJourneyClient(inputConfig) {
|
|
|
3370
3761
|
} catch {
|
|
3371
3762
|
return invalidConfig();
|
|
3372
3763
|
}
|
|
3373
|
-
const
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
|
|
3377
|
-
|
|
3378
|
-
|
|
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 });
|
|
3379
3774
|
const queue = [];
|
|
3380
3775
|
const contextByEventId = /* @__PURE__ */ new Map();
|
|
3381
3776
|
let episode;
|
|
@@ -3472,7 +3867,15 @@ function createSemanticJourneyClient(inputConfig) {
|
|
|
3472
3867
|
droppedAttributeCount: validated.droppedAttributeCount
|
|
3473
3868
|
})
|
|
3474
3869
|
});
|
|
3475
|
-
aggregateStore
|
|
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);
|
|
3476
3879
|
if (shouldCoalesce(
|
|
3477
3880
|
queue[queue.length - 1]?.event,
|
|
3478
3881
|
event,
|
|
@@ -3481,17 +3884,17 @@ function createSemanticJourneyClient(inputConfig) {
|
|
|
3481
3884
|
aggregateStore.recordCoalesced();
|
|
3482
3885
|
return void 0;
|
|
3483
3886
|
}
|
|
3484
|
-
const
|
|
3485
|
-
if (
|
|
3887
|
+
const bytes2 = eventBytes(event);
|
|
3888
|
+
if (bytes2 > config.maxQueueBytes) {
|
|
3486
3889
|
aggregateStore.recordDropped();
|
|
3487
3890
|
notifyDrop("queue-limit");
|
|
3488
3891
|
return void 0;
|
|
3489
3892
|
}
|
|
3490
|
-
while (queue.length >= config.maxQueueEvents || queueBytes +
|
|
3893
|
+
while (queue.length >= config.maxQueueEvents || queueBytes + bytes2 > config.maxQueueBytes) {
|
|
3491
3894
|
removeFirstQueued("queue-limit");
|
|
3492
3895
|
}
|
|
3493
|
-
queue.push({ event, context: options.context, bytes });
|
|
3494
|
-
queueBytes +=
|
|
3896
|
+
queue.push({ event, context: options.context, bytes: bytes2 });
|
|
3897
|
+
queueBytes += bytes2;
|
|
3495
3898
|
contextByEventId.set(event.eventId, options.context);
|
|
3496
3899
|
if (usesLocalProducer) {
|
|
3497
3900
|
currentEpisode.producerSequence = producerSequence;
|
|
@@ -3733,6 +4136,10 @@ function createSemanticJourneyClient(inputConfig) {
|
|
|
3733
4136
|
if (destroyed || signal.aborted) {
|
|
3734
4137
|
return "retained";
|
|
3735
4138
|
}
|
|
4139
|
+
if (aggregateStore instanceof ProjectedSemanticJourneyAggregateStore && batch.schemaVersion === "2.1-aggregate" && !aggregateStore.isPendingBatch(batch, config.now())) {
|
|
4140
|
+
notifyDrop("expired");
|
|
4141
|
+
return "discarded";
|
|
4142
|
+
}
|
|
3736
4143
|
try {
|
|
3737
4144
|
await sendWithTimeout(batch, keepalive);
|
|
3738
4145
|
return "sent";
|
|
@@ -3763,6 +4170,7 @@ function createSemanticJourneyClient(inputConfig) {
|
|
|
3763
4170
|
const generation = aggregateGeneration;
|
|
3764
4171
|
const signal = aggregateController.signal;
|
|
3765
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;
|
|
3766
4174
|
const batch = pendingBatch ?? aggregateStore.createBatch({
|
|
3767
4175
|
batchId: createEventId(config.randomBytes),
|
|
3768
4176
|
nowEpochMs: config.now(),
|
|
@@ -3780,7 +4188,9 @@ function createSemanticJourneyClient(inputConfig) {
|
|
|
3780
4188
|
if (result === "retained") {
|
|
3781
4189
|
return;
|
|
3782
4190
|
}
|
|
3783
|
-
aggregateStore
|
|
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);
|
|
3784
4194
|
pendingBatch = void 0;
|
|
3785
4195
|
}
|
|
3786
4196
|
};
|
|
@@ -4004,7 +4414,10 @@ function useComponentInteractionTracker(component, baseContext = {}) {
|
|
|
4004
4414
|
}
|
|
4005
4415
|
export {
|
|
4006
4416
|
AnalyticsProvider,
|
|
4417
|
+
ProjectedSemanticJourneyAggregateStore,
|
|
4418
|
+
SEMANTIC_JOURNEY_AGGREGATE_MAX_BYTES,
|
|
4007
4419
|
SEMANTIC_JOURNEY_AGGREGATE_SCHEMA_VERSION,
|
|
4420
|
+
SEMANTIC_JOURNEY_PROJECTED_AGGREGATE_SCHEMA_VERSION,
|
|
4008
4421
|
SEMANTIC_JOURNEY_RECEIPT_HEADER,
|
|
4009
4422
|
SEMANTIC_JOURNEY_RECEIPT_MAX_BYTES,
|
|
4010
4423
|
SEMANTIC_JOURNEY_RECEIPT_MAX_COUNT,
|
|
@@ -4028,10 +4441,12 @@ export {
|
|
|
4028
4441
|
createProducerId,
|
|
4029
4442
|
createRequestJourneyContext,
|
|
4030
4443
|
createSecureRandomHex,
|
|
4444
|
+
createSemanticJourneyAggregateValidator,
|
|
4031
4445
|
createSemanticJourneyClient,
|
|
4032
4446
|
createSpanId,
|
|
4033
4447
|
createTraceId,
|
|
4034
4448
|
defineJourneyEvent,
|
|
4449
|
+
defineSemanticJourneyAggregatePolicy,
|
|
4035
4450
|
defineSemanticJourneyCatalog,
|
|
4036
4451
|
formatTraceparent,
|
|
4037
4452
|
getJourneyEventDefinition,
|
|
@@ -4040,6 +4455,7 @@ export {
|
|
|
4040
4455
|
isJourneyToken,
|
|
4041
4456
|
isProducerId,
|
|
4042
4457
|
isSecureSemanticJourneyEndpoint,
|
|
4458
|
+
isSemanticJourneyAggregatePolicy,
|
|
4043
4459
|
isSemanticSource,
|
|
4044
4460
|
isSemanticToken,
|
|
4045
4461
|
isSpanId,
|
|
@@ -4047,8 +4463,10 @@ export {
|
|
|
4047
4463
|
observeSemanticJourneyInteractions,
|
|
4048
4464
|
parseSemanticJourneyReceipts,
|
|
4049
4465
|
parseTraceparent,
|
|
4466
|
+
projectSemanticJourneyAggregateCounters,
|
|
4050
4467
|
projectUsefulMetric,
|
|
4051
4468
|
reconstructSemanticJourney,
|
|
4469
|
+
semanticJourneyAggregateCounterKey,
|
|
4052
4470
|
serializeSemanticJourneyReceipts,
|
|
4053
4471
|
useAnalytics,
|
|
4054
4472
|
useComponentInteractionTracker,
|