@krak-stack/registry 0.1.53 → 0.1.54

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.
@@ -13,6 +13,8 @@ export declare class OtlpEvents extends OtlpEvents_base {
13
13
  static readonly layer: (options: ExporterOptions) => Layer.Layer<OtlpEvents, never, OtlpExporter.Flusher | import("effect/http/HttpClient").HttpClient | OtlpSerialization.OtlpSerialization>;
14
14
  }
15
15
  interface EventRecord {
16
+ /** Local-only revocation check; never serialized into OTLP. */
17
+ readonly canExport?: () => boolean;
16
18
  readonly scopeName?: string;
17
19
  readonly eventName: string;
18
20
  readonly timeUnixNano: string;
@@ -27,6 +27,16 @@ import {
27
27
 
28
28
  // ../../src/services/opentelemetry/schema.ts
29
29
  import { Schema } from "effect";
30
+ var BrowserAnalyticsPreference = Schema.Struct({
31
+ version: Schema.String,
32
+ choice: Schema.Literals(["accepted", "declined"]),
33
+ revision: Schema.String,
34
+ issuedAt: Schema.Finite,
35
+ expiresAt: Schema.Finite
36
+ }).annotate({ identifier: "BrowserAnalyticsPreference" });
37
+ var BrowserPrivacySignals = Schema.Struct({
38
+ globalPrivacyControl: Schema.optional(Schema.Boolean)
39
+ }).annotate({ identifier: "BrowserPrivacySignals" });
30
40
  var BrowserWebVital = Schema.Struct({
31
41
  name: Schema.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
32
42
  id: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
@@ -76,7 +86,9 @@ class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
76
86
  label: "OtlpEvents",
77
87
  body: (logRecords) => {
78
88
  const scopes = new Map;
79
- for (const { scopeName, ...record } of logRecords) {
89
+ for (const { scopeName, canExport, ...record } of logRecords) {
90
+ if (canExport && !canExport())
91
+ continue;
80
92
  const name = scopeName ?? options.scopeName ?? "krakstack.events";
81
93
  const records = scopes.get(name);
82
94
  if (records)
@@ -1,4 +1,15 @@
1
1
  import { Schema } from "effect";
2
+ export declare const BrowserAnalyticsPreference: Schema.Struct<{
3
+ readonly version: Schema.String;
4
+ readonly choice: Schema.Literals<readonly ["accepted", "declined"]>;
5
+ /** A consent revision, not a visitor identifier; never exported with telemetry. */
6
+ readonly revision: Schema.String;
7
+ readonly issuedAt: Schema.Finite;
8
+ readonly expiresAt: Schema.Finite;
9
+ }>;
10
+ export declare const BrowserPrivacySignals: Schema.Struct<{
11
+ readonly globalPrivacyControl: Schema.optional<Schema.Boolean>;
12
+ }>;
2
13
  export declare const BrowserWebVital: Schema.Struct<{
3
14
  readonly name: Schema.Literals<readonly ["LCP", "INP", "CLS", "FCP", "TTFB"]>;
4
15
  readonly id: Schema.NonEmptyString;
@@ -1,5 +1,5 @@
1
1
  import { type Metric } from "web-vitals";
2
- import { Context, Layer, Schema } from "effect";
2
+ import { Context, Layer } from "effect";
3
3
  import { OtlpEvents } from "./events.js";
4
4
  /** web-vitals observers are document-scoped; only subscribers retain application state. */
5
5
  export declare const subscribeWebVitals: (subscriber: (metric: Metric) => void) => () => void;
@@ -7,9 +7,10 @@ export declare const WebVitals: Context.Reference<{
7
7
  readonly subscribe: typeof subscribeWebVitals;
8
8
  }>;
9
9
  export interface BrowserWebVitalsOptions {
10
+ readonly requireConsent?: boolean;
10
11
  readonly respectDoNotTrack?: boolean;
11
12
  }
12
13
  export declare class BrowserWebVitals {
13
14
  /** Provide a browser telemetry layer with events enabled; no exporter is created here. */
14
- static readonly layer: ({ respectDoNotTrack, }?: BrowserWebVitalsOptions) => Layer.Layer<never, Schema.SchemaError, OtlpEvents>;
15
+ static readonly layer: ({ respectDoNotTrack, requireConsent, }?: BrowserWebVitalsOptions) => Layer.Layer<never, never, OtlpEvents>;
15
16
  }
@@ -1,6 +1,6 @@
1
1
  // ../../src/services/opentelemetry/web-vitals.ts
2
2
  import { onCLS, onFCP, onINP, onLCP, onTTFB } from "web-vitals";
3
- import { Clock as Clock2, Context as Context2, Effect as Effect2, Layer as Layer2, Schema as Schema3 } from "effect";
3
+ import { Clock as Clock2, Context as Context2, Effect as Effect3, Layer as Layer2, Schema as Schema4 } from "effect";
4
4
 
5
5
  // ../../src/services/opentelemetry/events.ts
6
6
  import {
@@ -21,6 +21,16 @@ import {
21
21
 
22
22
  // ../../src/services/opentelemetry/schema.ts
23
23
  import { Schema } from "effect";
24
+ var BrowserAnalyticsPreference = Schema.Struct({
25
+ version: Schema.String,
26
+ choice: Schema.Literals(["accepted", "declined"]),
27
+ revision: Schema.String,
28
+ issuedAt: Schema.Finite,
29
+ expiresAt: Schema.Finite
30
+ }).annotate({ identifier: "BrowserAnalyticsPreference" });
31
+ var BrowserPrivacySignals = Schema.Struct({
32
+ globalPrivacyControl: Schema.optional(Schema.Boolean)
33
+ }).annotate({ identifier: "BrowserPrivacySignals" });
24
34
  var BrowserWebVital = Schema.Struct({
25
35
  name: Schema.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
26
36
  id: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
@@ -70,7 +80,9 @@ class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
70
80
  label: "OtlpEvents",
71
81
  body: (logRecords) => {
72
82
  const scopes = new Map;
73
- for (const { scopeName, ...record } of logRecords) {
83
+ for (const { scopeName, canExport, ...record } of logRecords) {
84
+ if (canExport && !canExport())
85
+ continue;
74
86
  const name = scopeName ?? options.scopeName ?? "krakstack.events";
75
87
  const records = scopes.get(name);
76
88
  if (records)
@@ -132,6 +144,78 @@ var event = Effect.fnUntraced(function* (name, properties, options) {
132
144
  });
133
145
  });
134
146
 
147
+ // ../../src/services/opentelemetry/consent.ts
148
+ import { Effect as Effect2, Option as Option2, Schema as Schema3 } from "effect";
149
+ var ANALYTICS_CONSENT_COOKIE = "krakstack_analytics_consent";
150
+ var ANALYTICS_NOTICE_VERSION = "1";
151
+ var changedEvent = "krakstack:analytics-consent";
152
+ var lifetime = 180 * 24 * 60 * 60 * 1000;
153
+ var codec = Schema3.StringFromUriComponent.pipe(Schema3.decodeTo(Schema3.fromJsonString(BrowserAnalyticsPreference)));
154
+ var readCookie = (cookie) => cookie.split(";").map((part) => part.trim()).find((part) => part.startsWith(`${ANALYTICS_CONSENT_COOKIE}=`))?.slice(ANALYTICS_CONSENT_COOKIE.length + 1);
155
+ var analyticsPreference = (cookie, now = Date.now()) => {
156
+ const value = readCookie(cookie);
157
+ if (!value)
158
+ return;
159
+ const decoded = Schema3.decodeUnknownOption(codec)(value);
160
+ if (Option2.isNone(decoded))
161
+ return;
162
+ const preference = decoded.value;
163
+ return preference.version === ANALYTICS_NOTICE_VERSION && preference.issuedAt <= now && preference.expiresAt > now && preference.expiresAt - preference.issuedAt <= lifetime ? preference : undefined;
164
+ };
165
+ var browserPrivacyEnabled = () => {
166
+ if (globalThis.navigator === undefined)
167
+ return false;
168
+ const value = Schema3.decodeUnknownOption(BrowserPrivacySignals)(navigator);
169
+ return navigator.doNotTrack === "1" || navigator.doNotTrack === "yes" || Option2.isSome(value) && value.value.globalPrivacyControl === true;
170
+ };
171
+ var browserPreference = () => {
172
+ if (globalThis.document === undefined)
173
+ return;
174
+ const cookie = Effect2.runSync(Effect2.try({
175
+ try: () => document.cookie,
176
+ catch: () => new Error("Analytics preference storage unavailable")
177
+ }).pipe(Effect2.catch(() => Effect2.succeed(""))));
178
+ return analyticsPreference(cookie);
179
+ };
180
+ var consentGeneration = 0;
181
+ var previousSnapshot;
182
+ var analyticsConsentSnapshot = () => {
183
+ const preference = browserPreference();
184
+ const snapshot = browserPrivacyEnabled() ? "blocked" : preference ? `${preference.choice}:${preference.revision}` : "pending";
185
+ if (snapshot !== previousSnapshot) {
186
+ consentGeneration++;
187
+ previousSnapshot = snapshot;
188
+ }
189
+ return snapshot;
190
+ };
191
+ var analyticsAllowed = () => analyticsConsentSnapshot().startsWith("accepted:");
192
+ var analyticsAcceptedBefore = (timestamp) => analyticsAllowed() && (browserPreference()?.issuedAt ?? Infinity) <= timestamp;
193
+ var analyticsExportGuard = () => {
194
+ const snapshot = analyticsConsentSnapshot();
195
+ const generation = consentGeneration;
196
+ return () => snapshot.startsWith("accepted:") && analyticsConsentSnapshot() === snapshot && consentGeneration === generation;
197
+ };
198
+ var subscribeAnalyticsConsent = (listener) => {
199
+ let previous = analyticsConsentSnapshot();
200
+ const notify = () => {
201
+ const next = analyticsConsentSnapshot();
202
+ if (next === previous)
203
+ return;
204
+ previous = next;
205
+ listener();
206
+ };
207
+ const timer = globalThis.setInterval(notify, 1000);
208
+ globalThis.addEventListener(changedEvent, notify);
209
+ globalThis.addEventListener("focus", notify);
210
+ document.addEventListener("visibilitychange", notify);
211
+ return () => {
212
+ globalThis.clearInterval(timer);
213
+ globalThis.removeEventListener(changedEvent, notify);
214
+ globalThis.removeEventListener("focus", notify);
215
+ document.removeEventListener("visibilitychange", notify);
216
+ };
217
+ };
218
+
135
219
  // ../../src/services/opentelemetry/web-vitals.ts
136
220
  var subscribers = new Set;
137
221
  var started = false;
@@ -156,71 +240,90 @@ var subscribeWebVitals = (subscriber) => {
156
240
  var WebVitals = Context2.Reference("krakstack/opentelemetry/WebVitals", {
157
241
  defaultValue: () => ({ subscribe: subscribeWebVitals })
158
242
  });
159
- var WebVitalsLive = Layer2.effectDiscard(Effect2.gen(function* () {
243
+ var WebVitalsLive = (requireConsent, respectDoNotTrack) => Layer2.effectDiscard(Effect3.gen(function* () {
160
244
  const vitals = yield* WebVitals;
161
245
  const events = yield* OtlpEvents;
162
246
  const clock = yield* Clock2.Clock;
163
247
  const seen = new Map;
164
- yield* Effect2.acquireRelease(Effect2.sync(() => vitals.subscribe((input) => {
165
- const parsed = Schema3.decodeUnknownOption(BrowserWebVital)(input);
166
- if (parsed._tag === "None")
167
- return;
168
- const metric = parsed.value;
169
- const key = `${metric.name}:${metric.id}`;
170
- if (seen.get(key) === metric.value)
171
- return;
172
- seen.set(key, metric.value);
173
- const timestamp = clock.currentTimeNanosUnsafe().toString();
174
- events.push({
175
- eventName: "browser.web_vital",
176
- timeUnixNano: timestamp,
177
- observedTimeUnixNano: timestamp,
178
- severityNumber: 9,
179
- droppedAttributesCount: 0,
180
- attributes: [
181
- {
182
- key: "browser.web_vital.name",
183
- value: { stringValue: metric.name.toLowerCase() }
184
- },
185
- {
186
- key: "browser.web_vital.id",
187
- value: { stringValue: metric.id }
188
- },
189
- {
190
- key: "browser.web_vital.value",
191
- value: { doubleValue: metric.value }
192
- },
193
- {
194
- key: "browser.web_vital.delta",
195
- value: { doubleValue: metric.delta }
196
- },
197
- {
198
- key: "browser.web_vital.rating",
199
- value: { stringValue: metric.rating }
200
- },
201
- {
202
- key: "browser.web_vital.navigation_type",
203
- value: { stringValue: metric.navigationType }
204
- },
205
- {
206
- key: "log.record.uid",
207
- value: { stringValue: `${metric.id}:${metric.value}` }
208
- }
209
- ]
248
+ if (requireConsent && !analyticsAcceptedBefore(performance.timeOrigin))
249
+ return;
250
+ const consentGuard = requireConsent ? analyticsExportGuard() : () => true;
251
+ let active = true;
252
+ const canExport = () => {
253
+ active = active && consentGuard() && (!respectDoNotTrack || !browserPrivacyEnabled());
254
+ return active;
255
+ };
256
+ if (!canExport())
257
+ return;
258
+ yield* Effect3.acquireRelease(Effect3.sync(() => {
259
+ const report = (input) => {
260
+ if (!canExport())
261
+ return;
262
+ const parsed = Schema4.decodeUnknownOption(BrowserWebVital)(input);
263
+ if (parsed._tag === "None")
264
+ return;
265
+ const metric = parsed.value;
266
+ const key = `${metric.name}:${metric.id}`;
267
+ if (seen.get(key) === metric.value)
268
+ return;
269
+ seen.set(key, metric.value);
270
+ const timestamp = clock.currentTimeNanosUnsafe().toString();
271
+ events.push({
272
+ canExport,
273
+ eventName: "browser.web_vital",
274
+ timeUnixNano: timestamp,
275
+ observedTimeUnixNano: timestamp,
276
+ severityNumber: 9,
277
+ droppedAttributesCount: 0,
278
+ attributes: [
279
+ {
280
+ key: "browser.web_vital.name",
281
+ value: { stringValue: metric.name.toLowerCase() }
282
+ },
283
+ {
284
+ key: "browser.web_vital.id",
285
+ value: { stringValue: metric.id }
286
+ },
287
+ {
288
+ key: "browser.web_vital.value",
289
+ value: { doubleValue: metric.value }
290
+ },
291
+ {
292
+ key: "browser.web_vital.delta",
293
+ value: { doubleValue: metric.delta }
294
+ },
295
+ {
296
+ key: "browser.web_vital.rating",
297
+ value: { stringValue: metric.rating }
298
+ },
299
+ {
300
+ key: "browser.web_vital.navigation_type",
301
+ value: { stringValue: metric.navigationType }
302
+ },
303
+ {
304
+ key: "log.record.uid",
305
+ value: { stringValue: `${metric.id}:${metric.value}` }
306
+ }
307
+ ]
308
+ });
309
+ };
310
+ const unsubscribe = vitals.subscribe(report);
311
+ const stop = subscribeAnalyticsConsent(() => {
312
+ if (!canExport())
313
+ unsubscribe();
210
314
  });
211
- })), (unsubscribe) => Effect2.sync(unsubscribe));
315
+ return () => {
316
+ stop();
317
+ unsubscribe();
318
+ };
319
+ }), (unsubscribe) => Effect3.sync(unsubscribe));
212
320
  }));
213
321
 
214
322
  class BrowserWebVitals {
215
323
  static layer = ({
216
- respectDoNotTrack = true
217
- } = {}) => Layer2.unwrap(Effect2.gen(function* () {
218
- const privacy = yield* Schema3.decodeUnknownEffect(Schema3.Struct({
219
- globalPrivacyControl: Schema3.optional(Schema3.Boolean)
220
- }))(navigator);
221
- const optedOut = respectDoNotTrack && (navigator.doNotTrack === "1" || navigator.doNotTrack === "yes" || privacy.globalPrivacyControl === true);
222
- return optedOut ? Layer2.empty : WebVitalsLive;
223
- }));
324
+ respectDoNotTrack = true,
325
+ requireConsent = true
326
+ } = {}) => WebVitalsLive(requireConsent, respectDoNotTrack);
224
327
  }
225
328
  export {
226
329
  BrowserWebVitals,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krak-stack/registry",
3
- "version": "0.1.53",
3
+ "version": "0.1.54",
4
4
  "description": "Tree-shakable KrakStack components and Effect services.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -17,6 +17,10 @@
17
17
  "type": "module",
18
18
  "sideEffects": false,
19
19
  "exports": {
20
+ "./events/tracking-notice": {
21
+ "types": "./dist/services/events/client/tracking-notice.d.ts",
22
+ "import": "./dist/services/events/client/tracking-notice.js"
23
+ },
20
24
  "./events/client": {
21
25
  "types": "./dist/services/events/client/audit-log-table.d.ts",
22
26
  "import": "./dist/services/events/client/audit-log-table.js"