@plasius/analytics 1.2.3 → 1.3.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/README.md CHANGED
@@ -257,6 +257,55 @@ function SaveButton() {
257
257
  }
258
258
  ```
259
259
 
260
+ ## Privacy-safe useful metrics
261
+
262
+ Compose the fixed definitions into the host's semantic catalogue, then project
263
+ one observation before tracking it with the existing bounded client:
264
+
265
+ ```ts
266
+ import {
267
+ USEFUL_METRIC_EVENT_DEFINITIONS,
268
+ defineSemanticJourneyCatalog,
269
+ projectUsefulMetric,
270
+ } from "@plasius/analytics";
271
+
272
+ const catalogue = defineSemanticJourneyCatalog(
273
+ USEFUL_METRIC_EVENT_DEFINITIONS,
274
+ { sources: ["plasius.site"] },
275
+ );
276
+ const event = projectUsefulMetric({ metric: "page.load", value: 1250 });
277
+ // Configure your host client with catalogue; if enabled and event !== null,
278
+ // call client.track(event). No direct send or flush is needed per observation.
279
+ ```
280
+
281
+ Duration keys (milliseconds): `page.load`, `route.ready`, `world.ready`,
282
+ `request.duration`, `vital.lcp`, `vital.fcp`, `vital.inp`, `vital.ttfb` and
283
+ `episode.active-duration`. `vital.cls` accepts a unitless layout-shift score.
284
+ Durations must be finite, non-negative and <=24 hours; CLS must be <=100.
285
+
286
+ Counters accept only `{ metric }`: `episode.started`, `episode.completed`,
287
+ `request.started`, `request.completed`, `request.failed`, `request.cancelled`,
288
+ `request.rejected`, `error.runtime`, `error.resource`, `error.render`, and
289
+ `error.unhandled`. All other fields/names, accessors and invalid measurements
290
+ return `null`, including legacy NFR objects containing URL/DOM/error metadata.
291
+
292
+ There are 84 fixed catalogue entries. Numeric values become bounded event-name
293
+ buckets, not attributes or raw measurements, so histograms survive the existing
294
+ aggregate format. General durations use upper-exclusive boundaries at 100, 250,
295
+ 500, 1000, 2500, 5000 and 10000 ms; active episodes at 10, 60, 300, 900 and 3600
296
+ seconds; CLS at 0.1 and 0.25. Final buckets include all remaining valid values.
297
+
298
+ The host must evaluate its remote rollout flag, cap observation frequency,
299
+ dispose collectors/client on rollback, and emit only one final web-vital
300
+ observation per measurement period. Episode counts are in-memory activity
301
+ periods, not unique users or cross-tab sessions: exclude hidden time and disclose
302
+ reload/tab duplication and lost final observations. No identifiers or persistence
303
+ are needed. Metric error categories never accept an Error object or message.
304
+
305
+ The service must approve the same fixed definitions and process these counters
306
+ before useful metric delivery can be claimed. This helper installs no collectors
307
+ or transport and does not certify legacy analytics payloads as privacy-safe.
308
+
260
309
  ## Development
261
310
 
262
311
  ```bash
package/dist/index.cjs CHANGED
@@ -30,6 +30,7 @@ __export(index_exports, {
30
30
  SemanticJourneyAggregateStore: () => SemanticJourneyAggregateStore,
31
31
  SemanticJourneyTransportError: () => SemanticJourneyTransportError,
32
32
  SemanticJourneyValidationError: () => SemanticJourneyValidationError,
33
+ USEFUL_METRIC_EVENT_DEFINITIONS: () => USEFUL_METRIC_EVENT_DEFINITIONS,
33
34
  assertSemanticSource: () => assertSemanticSource,
34
35
  assertSemanticToken: () => assertSemanticToken,
35
36
  createBackendAnalyticsClient: () => createBackendAnalyticsClient,
@@ -63,6 +64,7 @@ __export(index_exports, {
63
64
  observeSemanticJourneyInteractions: () => observeSemanticJourneyInteractions,
64
65
  parseSemanticJourneyReceipts: () => parseSemanticJourneyReceipts,
65
66
  parseTraceparent: () => parseTraceparent,
67
+ projectUsefulMetric: () => projectUsefulMetric,
66
68
  reconstructSemanticJourney: () => reconstructSemanticJourney,
67
69
  serializeSemanticJourneyReceipts: () => serializeSemanticJourneyReceipts,
68
70
  useAnalytics: () => useAnalytics,
@@ -2002,6 +2004,99 @@ var SemanticJourneyAggregateStore = class {
2002
2004
  }
2003
2005
  };
2004
2006
 
2007
+ // src/journey/metrics.ts
2008
+ var durationBuckets = [
2009
+ [100, "lt100ms"],
2010
+ [250, "lt250ms"],
2011
+ [500, "lt500ms"],
2012
+ [1e3, "lt1000ms"],
2013
+ [2500, "lt2500ms"],
2014
+ [5e3, "lt5000ms"],
2015
+ [1e4, "lt10000ms"],
2016
+ [Infinity, "gte10000ms"]
2017
+ ];
2018
+ var duration = (category) => ({
2019
+ category,
2020
+ outcome: "unknown",
2021
+ buckets: durationBuckets,
2022
+ maximum: 864e5
2023
+ });
2024
+ var metrics = {
2025
+ "page.load": duration("presentation"),
2026
+ "route.ready": duration("presentation"),
2027
+ "world.ready": duration("presentation"),
2028
+ "request.duration": duration("request"),
2029
+ "vital.lcp": duration("presentation"),
2030
+ "vital.fcp": duration("presentation"),
2031
+ "vital.inp": duration("interaction"),
2032
+ "vital.ttfb": duration("request"),
2033
+ "vital.cls": {
2034
+ category: "presentation",
2035
+ outcome: "unknown",
2036
+ maximum: 100,
2037
+ buckets: [[0.1, "lt01"], [0.25, "lt025"], [Infinity, "gte025"]]
2038
+ },
2039
+ "episode.active-duration": {
2040
+ category: "state",
2041
+ outcome: "unknown",
2042
+ maximum: 864e5,
2043
+ buckets: [
2044
+ [1e4, "lt10s"],
2045
+ [6e4, "lt60s"],
2046
+ [3e5, "lt300s"],
2047
+ [9e5, "lt900s"],
2048
+ [36e5, "lt3600s"],
2049
+ [Infinity, "gte3600s"]
2050
+ ]
2051
+ },
2052
+ "episode.started": { category: "state", outcome: "unknown" },
2053
+ "episode.completed": { category: "state", outcome: "unknown" },
2054
+ "request.started": { category: "request", outcome: "unknown" },
2055
+ "request.completed": { category: "request", outcome: "success" },
2056
+ "request.failed": { category: "request", outcome: "failure" },
2057
+ "request.cancelled": { category: "request", outcome: "cancelled" },
2058
+ "request.rejected": { category: "request", outcome: "denied" },
2059
+ "error.runtime": { category: "error", outcome: "failure" },
2060
+ "error.resource": { category: "error", outcome: "failure" },
2061
+ "error.render": { category: "error", outcome: "failure" },
2062
+ "error.unhandled": { category: "error", outcome: "failure" }
2063
+ };
2064
+ var USEFUL_METRIC_EVENT_DEFINITIONS = Object.freeze(Object.fromEntries(Object.entries(metrics).flatMap(([metric, definition]) => {
2065
+ const names = definition.buckets ? definition.buckets.map(([, bucket]) => `metric.${metric}.${bucket}`) : [`metric.${metric}`];
2066
+ return names.map((name) => [name, Object.freeze({ category: definition.category })]);
2067
+ })));
2068
+ function projectUsefulMetric(input) {
2069
+ try {
2070
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return null;
2071
+ const prototype = Object.getPrototypeOf(input);
2072
+ if (prototype !== Object.prototype && prototype !== null) return null;
2073
+ const keys = Reflect.ownKeys(input);
2074
+ if (keys.length < 1 || keys.length > 2 || keys.some((key) => key !== "metric" && key !== "value")) return null;
2075
+ const descriptors = Object.getOwnPropertyDescriptors(input);
2076
+ const metric = descriptors.metric;
2077
+ if (!metric || !("value" in metric) || typeof metric.value !== "string" || !Object.hasOwn(metrics, metric.value)) return null;
2078
+ const definition = metrics[metric.value];
2079
+ let name = `metric.${metric.value}`;
2080
+ if (definition.buckets) {
2081
+ const value = descriptors.value;
2082
+ if (keys.length !== 2 || !value || !("value" in value) || typeof value.value !== "number" || !Number.isFinite(value.value) || value.value < 0 || value.value > definition.maximum) return null;
2083
+ const bucket = definition.buckets.find(([upper]) => value.value < upper);
2084
+ name += `.${bucket[1]}`;
2085
+ } else if (keys.length !== 1) {
2086
+ return null;
2087
+ }
2088
+ return Object.freeze({
2089
+ name,
2090
+ category: definition.category,
2091
+ phase: metric.value.endsWith(".started") ? "start" : "end",
2092
+ outcome: definition.outcome,
2093
+ modality: "system"
2094
+ });
2095
+ } catch {
2096
+ return null;
2097
+ }
2098
+ }
2099
+
2005
2100
  // src/journey/transport.ts
2006
2101
  var SemanticJourneyTransportError = class extends Error {
2007
2102
  constructor(code, retryable, status, retryAfterMs) {
@@ -3982,6 +4077,7 @@ function useComponentInteractionTracker(component, baseContext = {}) {
3982
4077
  SemanticJourneyAggregateStore,
3983
4078
  SemanticJourneyTransportError,
3984
4079
  SemanticJourneyValidationError,
4080
+ USEFUL_METRIC_EVENT_DEFINITIONS,
3985
4081
  assertSemanticSource,
3986
4082
  assertSemanticToken,
3987
4083
  createBackendAnalyticsClient,
@@ -4015,6 +4111,7 @@ function useComponentInteractionTracker(component, baseContext = {}) {
4015
4111
  observeSemanticJourneyInteractions,
4016
4112
  parseSemanticJourneyReceipts,
4017
4113
  parseTraceparent,
4114
+ projectUsefulMetric,
4018
4115
  reconstructSemanticJourney,
4019
4116
  serializeSemanticJourneyReceipts,
4020
4117
  useAnalytics,