@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.
@@ -4,13 +4,13 @@ import {
4
4
  Context as Context4,
5
5
  Crypto,
6
6
  DateTime as DateTime2,
7
- Effect as Effect7,
7
+ Effect as Effect8,
8
8
  Layer as Layer3,
9
- Option as Option5,
9
+ Option as Option6,
10
10
  Predicate,
11
11
  Redacted,
12
12
  References as References2,
13
- Schema as Schema8
13
+ Schema as Schema9
14
14
  } from "effect";
15
15
  import { HttpServerRequest } from "effect/http";
16
16
  import { SqlClient as SqlClient2, SqlSchema } from "effect/sql";
@@ -57,6 +57,16 @@ import {
57
57
 
58
58
  // ../../src/services/opentelemetry/schema.ts
59
59
  import { Schema as Schema2 } from "effect";
60
+ var BrowserAnalyticsPreference = Schema2.Struct({
61
+ version: Schema2.String,
62
+ choice: Schema2.Literals(["accepted", "declined"]),
63
+ revision: Schema2.String,
64
+ issuedAt: Schema2.Finite,
65
+ expiresAt: Schema2.Finite
66
+ }).annotate({ identifier: "BrowserAnalyticsPreference" });
67
+ var BrowserPrivacySignals = Schema2.Struct({
68
+ globalPrivacyControl: Schema2.optional(Schema2.Boolean)
69
+ }).annotate({ identifier: "BrowserPrivacySignals" });
60
70
  var BrowserWebVital = Schema2.Struct({
61
71
  name: Schema2.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
62
72
  id: Schema2.NonEmptyString.check(Schema2.isMaxLength(64)),
@@ -106,7 +116,9 @@ class OtlpEvents extends Context2.Service()("krakstack/opentelemetry/Events") {
106
116
  label: "OtlpEvents",
107
117
  body: (logRecords) => {
108
118
  const scopes = new Map;
109
- for (const { scopeName, ...record } of logRecords) {
119
+ for (const { scopeName, canExport, ...record } of logRecords) {
120
+ if (canExport && !canExport())
121
+ continue;
110
122
  const name = scopeName ?? options.scopeName ?? "krakstack.events";
111
123
  const records = scopes.get(name);
112
124
  if (records)
@@ -498,15 +510,15 @@ var cloudflareGeolocation = (headers) => ({
498
510
  region: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventRegion)(headers["cf-region-code"])),
499
511
  city: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventCity)(headers["cf-ipcity"]))
500
512
  });
501
- var geolocationAttributes = (location) => {
513
+ var geolocationAttributes = (location2) => {
502
514
  const attributes = {};
503
- if (location?.country) {
504
- attributes["geo.country.iso_code"] = location.country;
505
- if (location.region)
506
- attributes["geo.region.iso_code"] = `${location.country}-${location.region}`;
515
+ if (location2?.country) {
516
+ attributes["geo.country.iso_code"] = location2.country;
517
+ if (location2.region)
518
+ attributes["geo.region.iso_code"] = `${location2.country}-${location2.region}`;
507
519
  }
508
- if (location?.city)
509
- attributes["geo.locality.name"] = location.city;
520
+ if (location2?.city)
521
+ attributes["geo.locality.name"] = location2.city;
510
522
  return attributes;
511
523
  };
512
524
  var deviceContext = (userAgent) => {
@@ -557,6 +569,25 @@ var migrateEvents = Migrator.make({})({
557
569
  table: "events_migrations"
558
570
  });
559
571
 
572
+ // ../../src/services/opentelemetry/consent.ts
573
+ import { Effect as Effect7, Option as Option5, Schema as Schema8 } from "effect";
574
+ var ANALYTICS_CONSENT_COOKIE = "krakstack_analytics_consent";
575
+ var ANALYTICS_NOTICE_VERSION = "1";
576
+ var lifetime = 180 * 24 * 60 * 60 * 1000;
577
+ var codec = Schema8.StringFromUriComponent.pipe(Schema8.decodeTo(Schema8.fromJsonString(BrowserAnalyticsPreference)));
578
+ var readCookie = (cookie) => cookie.split(";").map((part) => part.trim()).find((part) => part.startsWith(`${ANALYTICS_CONSENT_COOKIE}=`))?.slice(ANALYTICS_CONSENT_COOKIE.length + 1);
579
+ var analyticsPreference = (cookie, now = Date.now()) => {
580
+ const value = readCookie(cookie);
581
+ if (!value)
582
+ return;
583
+ const decoded = Schema8.decodeUnknownOption(codec)(value);
584
+ if (Option5.isNone(decoded))
585
+ return;
586
+ const preference = decoded.value;
587
+ return preference.version === ANALYTICS_NOTICE_VERSION && preference.issuedAt <= now && preference.expiresAt > now && preference.expiresAt - preference.issuedAt <= lifetime ? preference : undefined;
588
+ };
589
+ var hasAnalyticsConsent = (cookie, headers = {}) => analyticsPreference(cookie)?.choice === "accepted" && headers.dnt !== "1" && headers.dnt !== "yes" && headers["sec-gpc"] !== "1";
590
+
560
591
  // ../../src/services/events/index.ts
561
592
  var SESSION_TIMEOUT_MS = 30 * 60 * 1000;
562
593
  var identityAttributes = (identity) => {
@@ -576,19 +607,19 @@ var actorAttributeKeys = [
576
607
  "user.roles"
577
608
  ];
578
609
  var reservedBrowserAttribute = (key) => key.startsWith("app.user.") || key.startsWith("user.") || key.startsWith("app.actor.") || key.startsWith("app.auth.") || key.startsWith("app.audit.") || key.startsWith("app.executor.") || key === "app.access.channel";
579
- var Configuration = Schema8.Struct({
580
- serviceName: Schema8.NonEmptyString,
581
- origin: Schema8.URLFromString.check(Schema8.makeFilter((url) => (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash || "Expected an HTTP origin")),
582
- geolocation: Schema8.optional(Schema8.Union([
583
- Schema8.Literal("cloudflare"),
584
- Schema8.declare((value) => Predicate.isFunction(value))
610
+ var Configuration = Schema9.Struct({
611
+ serviceName: Schema9.NonEmptyString,
612
+ origin: Schema9.URLFromString.check(Schema9.makeFilter((url) => (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash || "Expected an HTTP origin")),
613
+ geolocation: Schema9.optional(Schema9.Union([
614
+ Schema9.Literal("cloudflare"),
615
+ Schema9.declare((value) => Predicate.isFunction(value))
585
616
  ])),
586
- secret: Schema8.String.check(Schema8.isMinLength(32))
617
+ secret: Schema9.String.check(Schema9.isMinLength(32))
587
618
  }).annotate({ identifier: "EventsConfiguration" });
588
619
 
589
- class EventsConfigurationError extends Schema8.TaggedError()("EventsConfigurationError", { message: Schema8.String }) {
620
+ class EventsConfigurationError extends Schema9.TaggedError()("EventsConfigurationError", { message: Schema9.String }) {
590
621
  }
591
- var codec = Schema8.fromJsonString(OtlpLogs);
622
+ var codec2 = Schema9.fromJsonString(OtlpLogs);
592
623
  var textAttribute = (record, key) => {
593
624
  const value = record.attributes.find((attribute) => attribute.key === key)?.value;
594
625
  return value && "stringValue" in value ? value.stringValue : undefined;
@@ -618,16 +649,16 @@ var eventContent = (record, source, compareTimestamp = source === "browser") =>
618
649
  "app.event.schema.version"
619
650
  ].includes(key) || key === "user.id" || key === "organization.id").sort((a, b) => a.key.localeCompare(b.key))
620
651
  });
621
- var dailyVisitorId = Effect7.fnUntraced(function* (input) {
622
- const crypto = yield* Crypto.Crypto;
652
+ var dailyVisitorId = Effect8.fnUntraced(function* (input) {
653
+ const crypto2 = yield* Crypto.Crypto;
623
654
  const encoder = new TextEncoder;
624
- const salt = yield* crypto.digest("SHA-256", encoder.encode(JSON.stringify([
655
+ const salt = yield* crypto2.digest("SHA-256", encoder.encode(JSON.stringify([
625
656
  "analytics.visitor.salt.v2",
626
657
  Redacted.value(input.secret),
627
658
  input.serviceName,
628
659
  input.day
629
660
  ])));
630
- const digest = yield* crypto.digest("SHA-256", encoder.encode(JSON.stringify([
661
+ const digest = yield* crypto2.digest("SHA-256", encoder.encode(JSON.stringify([
631
662
  "analytics.visitor.v2",
632
663
  input.serviceName,
633
664
  input.day,
@@ -639,19 +670,20 @@ var dailyVisitorId = Effect7.fnUntraced(function* (input) {
639
670
  });
640
671
 
641
672
  class Events extends Context4.Service()("krakstack/events/Events", {
642
- make: (options) => Effect7.gen(function* () {
643
- const crypto = yield* Crypto.Crypto;
673
+ make: (options) => Effect8.gen(function* () {
674
+ const crypto2 = yield* Crypto.Crypto;
644
675
  const telemetry = yield* Otlp;
676
+ const exporter = yield* OtlpEvents;
645
677
  const resource = options.serviceName ? yield* OtlpResource3.fromConfig({ serviceName: options.serviceName }) : yield* telemetry.resource;
646
- const configuration = yield* Schema8.decodeUnknownEffect(Configuration)({
678
+ const configuration = yield* Schema9.decodeUnknownEffect(Configuration)({
647
679
  ...options,
648
680
  serviceName: OtlpResource3.serviceNameUnsafe(resource),
649
681
  secret: Redacted.value(options.secret)
650
- }).pipe(Effect7.mapError(() => new EventsConfigurationError({
682
+ }).pipe(Effect8.mapError(() => new EventsConfigurationError({
651
683
  message: "Events requires an OTel service name, HTTP origin, and server secret of at least 32 characters"
652
684
  })));
653
- const client = yield* Effect7.serviceOption(SqlClient2.SqlClient);
654
- const storage = Option5.isSome(client) ? yield* Effect7.gen(function* () {
685
+ const client = yield* Effect8.serviceOption(SqlClient2.SqlClient);
686
+ const storage = Option6.isSome(client) ? yield* Effect8.gen(function* () {
655
687
  const sql = client.value.withoutTransforms();
656
688
  if (!sql.onDialectOrElse({
657
689
  pg: () => true,
@@ -692,10 +724,10 @@ class Events extends Context4.Service()("krakstack/events/Events", {
692
724
  ON CONFLICT (service_name, source, event_id) DO NOTHING RETURNING event_id
693
725
  `
694
726
  });
695
- const persist = Effect7.fnUntraced(function* (input) {
727
+ const persist = Effect8.fnUntraced(function* (input) {
696
728
  const { record, payload, now, source } = input;
697
729
  const eventId = textAttribute(record, "log.record.uid");
698
- const payloadJson = yield* Schema8.encodeEffect(codec)(payload);
730
+ const payloadJson = yield* Schema9.encodeEffect(codec2)(payload);
699
731
  const inserted = yield* insertEvent({
700
732
  source,
701
733
  event_id: eventId,
@@ -709,10 +741,10 @@ class Events extends Context4.Service()("krakstack/events/Events", {
709
741
  anonymous_id: textAttribute(record, "analytics.anonymous_id") ?? null,
710
742
  payload_json: payloadJson
711
743
  });
712
- if (Option5.isSome(inserted))
744
+ if (Option6.isSome(inserted))
713
745
  return { eventId, inserted: true, record };
714
746
  const existing = yield* existingEvent({ source, eventId });
715
- const original = yield* Schema8.decodeUnknownEffect(EventLogRecord)(existing.payload_json.resourceLogs[0]?.scopeLogs[0]?.logRecords[0]);
747
+ const original = yield* Schema9.decodeUnknownEffect(EventLogRecord)(existing.payload_json.resourceLogs[0]?.scopeLogs[0]?.logRecords[0]);
716
748
  const identityChanged = source === "browser" && ["user.id", "organization.id"].some((key) => textAttribute(original, key) !== textAttribute(record, key));
717
749
  if (identityChanged || eventContent(original, source, input.compareTimestamp) !== eventContent(record, source, input.compareTimestamp)) {
718
750
  return yield* new EventConflictError({ eventId });
@@ -726,24 +758,24 @@ class Events extends Context4.Service()("krakstack/events/Events", {
726
758
  lockVisitor
727
759
  };
728
760
  }) : undefined;
729
- const resolveGeolocation = Effect7.fnUntraced(function* (request) {
730
- const location = configuration.geolocation === "cloudflare" ? cloudflareGeolocation(request.headers) : configuration.geolocation ? yield* configuration.geolocation(request) : null;
731
- return yield* Schema8.decodeUnknownEffect(Schema8.NullOr(EventGeolocation))(location);
732
- }, Effect7.mapError(() => new EventGeolocationError({})));
733
- const resolveRequestContext = Effect7.fnUntraced(function* (request, now, location) {
761
+ const resolveGeolocation = Effect8.fnUntraced(function* (request) {
762
+ const location2 = configuration.geolocation === "cloudflare" ? cloudflareGeolocation(request.headers) : configuration.geolocation ? yield* configuration.geolocation(request) : null;
763
+ return yield* Schema9.decodeUnknownEffect(Schema9.NullOr(EventGeolocation))(location2);
764
+ }, Effect8.mapError(() => new EventGeolocationError({})));
765
+ const resolveRequestContext = Effect8.fnUntraced(function* (request, now, location2) {
734
766
  const userAgent = request.headers["user-agent"]?.slice(0, 2048) ?? "";
735
- const visitorId = location?.ip && userAgent ? yield* dailyVisitorId({
767
+ const visitorId = location2?.ip && userAgent ? yield* dailyVisitorId({
736
768
  serviceName: configuration.serviceName,
737
769
  secret: options.secret,
738
- ip: location.ip,
770
+ ip: location2.ip,
739
771
  userAgent,
740
772
  day: DateTime2.formatIsoDate(now)
741
- }).pipe(Effect7.provideService(Crypto.Crypto, crypto)) : undefined;
773
+ }).pipe(Effect8.provideService(Crypto.Crypto, crypto2)) : undefined;
742
774
  let sessionId;
743
775
  if (visitorId && storage) {
744
776
  yield* storage.lockVisitor(visitorId);
745
777
  const latest = yield* storage.latestSession({ visitorId });
746
- sessionId = Option5.isSome(latest) && latest.value.received_at > DateTime2.toEpochMillis(now) - SESSION_TIMEOUT_MS ? latest.value.session_id : yield* crypto.randomUUIDv7;
778
+ sessionId = Option6.isSome(latest) && latest.value.received_at > DateTime2.toEpochMillis(now) - SESSION_TIMEOUT_MS ? latest.value.session_id : yield* crypto2.randomUUIDv7;
747
779
  }
748
780
  const identity = {};
749
781
  if (visitorId)
@@ -752,34 +784,33 @@ class Events extends Context4.Service()("krakstack/events/Events", {
752
784
  identity["session.id"] = sessionId;
753
785
  return {
754
786
  ...deviceContext(userAgent),
755
- ...geolocationAttributes(location),
787
+ ...geolocationAttributes(location2),
756
788
  "analytics.identity.mode": visitorId ? "daily" : "unattributed",
757
789
  ...identity
758
790
  };
759
791
  });
760
- const track = Effect7.fn("Events.track")(function* (input) {
761
- const event = yield* Schema8.decodeUnknownEffect(TrackEvent)(input);
762
- const eventId = event.eventId ?? (yield* crypto.randomUUIDv7);
792
+ const track = Effect8.fn("Events.track")(function* (input) {
793
+ const event = yield* Schema9.decodeUnknownEffect(TrackEvent)(input);
794
+ const eventId = event.eventId ?? (yield* crypto2.randomUUIDv7);
763
795
  const category = event.category ?? "analytics";
764
- if (!storage)
765
- return yield* new EventsPersistenceError({
766
- operation: "persistence-disabled"
767
- });
768
796
  const receivedAt = yield* DateTime2.now;
769
797
  const now = DateTime2.toEpochMillis(receivedAt);
770
- const request = yield* Effect7.serviceOption(HttpServerRequest.HttpServerRequest);
798
+ const request = yield* Effect8.serviceOption(HttpServerRequest.HttpServerRequest);
771
799
  const annotations = yield* References2.CurrentLogAnnotations;
800
+ if (category === "analytics" && options.requireConsent && (Option6.isNone(request) || !hasAnalyticsConsent(request.value.headers.cookie ?? "", request.value.headers))) {
801
+ return { eventId, inserted: false };
802
+ }
772
803
  const hasIdentity = [
773
804
  "user.id",
774
805
  "organization.id",
775
806
  ...actorAttributeKeys
776
807
  ].some((key) => annotations[key] !== undefined);
777
- const identity = hasIdentity ? yield* Schema8.decodeUnknownEffect(EventIdentity)({
808
+ const identity = hasIdentity ? yield* Schema9.decodeUnknownEffect(EventIdentity)({
778
809
  userId: annotations["user.id"],
779
810
  organizationId: annotations["organization.id"]
780
811
  }) : event.identity;
781
812
  if (category === "audit") {
782
- yield* Schema8.decodeUnknownEffect(AuditAttribution)(annotations);
813
+ yield* Schema9.decodeUnknownEffect(AuditAttribution)(annotations);
783
814
  }
784
815
  const attributes = {};
785
816
  for (const [key, value] of Object.entries(event.properties ?? {})) {
@@ -799,22 +830,22 @@ class Events extends Context4.Service()("krakstack/events/Events", {
799
830
  attributes["app.event.type"] = "track";
800
831
  attributes["app.event.source"] = "server";
801
832
  attributes["app.event.category"] = category;
802
- const span = yield* Effect7.currentSpan.pipe(Effect7.option);
803
- const location = Option5.isSome(request) ? yield* resolveGeolocation(request.value).pipe(Effect7.mapError(() => new EventsPersistenceError({ operation: "geolocation" }))) : null;
833
+ const span = yield* Effect8.currentSpan.pipe(Effect8.option);
834
+ const location2 = Option6.isSome(request) && (!options.requireConsent || hasAnalyticsConsent(request.value.headers.cookie ?? "", request.value.headers)) ? yield* resolveGeolocation(request.value).pipe(Effect8.mapError(() => new EventsPersistenceError({ operation: "geolocation" }))) : null;
804
835
  const entry = {
805
836
  eventName: event.name,
806
837
  timeUnixNano: (BigInt(event.timestamp ? DateTime2.toEpochMillis(event.timestamp) : now) * 1000000n).toString(),
807
838
  observedTimeUnixNano: (BigInt(now) * 1000000n).toString()
808
839
  };
809
- return yield* Effect7.gen(function* () {
810
- const requestContext = Option5.isSome(request) ? yield* resolveRequestContext(request.value, receivedAt, location) : {};
811
- const validated = yield* Schema8.decodeUnknownEffect(EventLogRecord)({
840
+ return yield* Effect8.gen(function* () {
841
+ const requestContext = Option6.isSome(request) && (!options.requireConsent || hasAnalyticsConsent(request.value.headers.cookie ?? "", request.value.headers)) ? yield* resolveRequestContext(request.value, receivedAt, location2) : {};
842
+ const validated = yield* Schema9.decodeUnknownEffect(EventLogRecord)({
812
843
  ...entry,
813
844
  attributes: OtlpResource3.entriesToAttributes(Object.entries({ ...requestContext, ...attributes })),
814
- traceId: Option5.isSome(span) ? span.value.traceId : undefined,
815
- spanId: Option5.isSome(span) ? span.value.spanId : undefined
845
+ traceId: Option6.isSome(span) ? span.value.traceId : undefined,
846
+ spanId: Option6.isSome(span) ? span.value.spanId : undefined
816
847
  });
817
- return yield* storage.persist({
848
+ const result = storage ? yield* storage.persist({
818
849
  source: "server",
819
850
  compareTimestamp: event.timestamp !== undefined,
820
851
  record: validated,
@@ -832,13 +863,25 @@ class Events extends Context4.Service()("krakstack/events/Events", {
832
863
  }
833
864
  ]
834
865
  }
835
- });
836
- }).pipe(storage.sql.withTransaction, Effect7.map(({ eventId, inserted }) => ({ eventId, inserted })), Effect7.mapError((error) => error._tag === "EventConflictError" ? error : new EventsPersistenceError({
866
+ }) : { eventId, inserted: false };
867
+ return {
868
+ ...result,
869
+ attributes: { ...requestContext, ...attributes }
870
+ };
871
+ }).pipe((effect) => storage ? storage.sql.withTransaction(effect) : effect, Effect8.tap((result) => !storage || result.inserted ? Otlp.event(event.name, result.attributes, {
872
+ messageId: result.eventId,
873
+ timestamp: event.timestamp ?? receivedAt
874
+ }).pipe(Effect8.provideService(OtlpEvents, {
875
+ push: (record) => exporter.push({
876
+ ...record,
877
+ scopeName: "krakstack.application.events"
878
+ })
879
+ }), Effect8.provideService(References2.CurrentLogAnnotations, {})) : Effect8.void), Effect8.map(({ eventId, inserted }) => ({ eventId, inserted })), Effect8.mapError((error) => error._tag === "EventConflictError" ? error : new EventsPersistenceError({
837
880
  operation: "track"
838
881
  })));
839
882
  });
840
- const listAudit = Effect7.fn("Events.listAudit")(function* (input) {
841
- const request = yield* Schema8.decodeUnknownEffect(ListAudit)(input);
883
+ const listAudit = Effect8.fn("Events.listAudit")(function* (input) {
884
+ const request = yield* Schema9.decodeUnknownEffect(ListAudit)(input);
842
885
  if (!storage)
843
886
  return yield* new EventsPersistenceError({
844
887
  operation: "persistence-disabled"
@@ -861,8 +904,8 @@ class Events extends Context4.Service()("krakstack/events/Events", {
861
904
  actorType: text("app.actor.type"),
862
905
  actorId: text("app.actor.id")
863
906
  };
864
- const sort = yield* Effect7.forEach(request.sort ?? [], (part) => Effect7.gen(function* () {
865
- const id = yield* Schema8.decodeUnknownEffect(AuditSortId)(part.id);
907
+ const sort = yield* Effect8.forEach(request.sort ?? [], (part) => Effect8.gen(function* () {
908
+ const id = yield* Schema9.decodeUnknownEffect(AuditSortId)(part.id);
866
909
  return sql`${sortColumns[id]} ${sql.literal(part.direction === "desc" ? "DESC" : "ASC")}`;
867
910
  }));
868
911
  const category = sql.onDialectOrElse({
@@ -906,7 +949,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
906
949
  `
907
950
  });
908
951
  const rows = yield* find(request);
909
- const data = yield* Effect7.forEach(rows, (row) => Schema8.decodeUnknownEffect(EventLogRecord)(row.payload_json.resourceLogs.flatMap((resource) => resource.scopeLogs.flatMap((scope) => scope.logRecords))[0]));
952
+ const data = yield* Effect8.forEach(rows, (row) => Schema9.decodeUnknownEffect(EventLogRecord)(row.payload_json.resourceLogs.flatMap((resource) => resource.scopeLogs.flatMap((scope) => scope.logRecords))[0]));
910
953
  return {
911
954
  data,
912
955
  meta: {
@@ -917,9 +960,30 @@ class Events extends Context4.Service()("krakstack/events/Events", {
917
960
  }
918
961
  };
919
962
  });
920
- const process = Effect7.fnUntraced(function* (body) {
963
+ const process = Effect8.fnUntraced(function* (body) {
921
964
  const request = yield* HttpServerRequest.HttpServerRequest;
922
- const payload = yield* Schema8.decodeUnknownEffect(codec)(new TextDecoder().decode(body)).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 400 })));
965
+ let payload = yield* Schema9.decodeUnknownEffect(codec2)(new TextDecoder().decode(body)).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 400 })));
966
+ if (options.requireConsent && !hasAnalyticsConsent(request.headers.cookie ?? "", request.headers)) {
967
+ payload = {
968
+ ...payload,
969
+ resourceLogs: payload.resourceLogs.map((resource) => ({
970
+ ...resource,
971
+ scopeLogs: resource.scopeLogs.filter((scope) => scope.scope?.name !== "krakstack.application.events").map((scope) => ({
972
+ ...scope,
973
+ logRecords: scope.logRecords.filter((record) => {
974
+ const parsed = Schema9.decodeUnknownOption(Schema9.Struct({
975
+ eventName: Schema9.optional(Schema9.String)
976
+ }))(record);
977
+ return Option6.isNone(parsed) || parsed.value.eventName !== "browser.web_vital";
978
+ })
979
+ }))
980
+ }))
981
+ };
982
+ return {
983
+ body: new TextEncoder().encode(yield* Schema9.encodeEffect(codec2)(payload).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 503 })))),
984
+ persisted: false
985
+ };
986
+ }
923
987
  const analyticsScopes = payload.resourceLogs.flatMap((resource) => resource.scopeLogs).filter((scope) => scope.scope?.name === "krakstack.application.events");
924
988
  if (analyticsScopes.length === 0)
925
989
  return { body, persisted: false };
@@ -927,12 +991,12 @@ class Events extends Context4.Service()("krakstack/events/Events", {
927
991
  return yield* new OtlpProcessingError({ status: 403 });
928
992
  }
929
993
  const rawRecords = analyticsScopes.flatMap((scope) => scope.logRecords);
930
- const records = yield* Schema8.decodeUnknownEffect(Schema8.Array(EventLogRecord).check(Schema8.isMinLength(1), Schema8.isMaxLength(100)))(rawRecords).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 400 })));
994
+ const records = yield* Schema9.decodeUnknownEffect(Schema9.Array(EventLogRecord).check(Schema9.isMinLength(1), Schema9.isMaxLength(100)))(rawRecords).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 400 })));
931
995
  const now = yield* DateTime2.now;
932
996
  const nowMillis = DateTime2.toEpochMillis(now);
933
997
  for (const record of records) {
934
998
  const timestamp = BigInt(record.timeUnixNano) / 1000000n;
935
- if (timestamp < BigInt(nowMillis - 60 * 60 * 1000) || timestamp > BigInt(nowMillis + 60000) || textAttribute(record, "app.event.schema.version") !== "1" || Option5.isNone(Schema8.decodeUnknownOption(EventUuid)(textAttribute(record, "analytics.page_view.id"))) || Option5.isNone(Schema8.decodeUnknownOption(EventId)(textAttribute(record, "log.record.uid"))) || Option5.isNone(Schema8.decodeUnknownOption(BrowserEventPath)(textAttribute(record, "url.path")))) {
999
+ if (timestamp < BigInt(nowMillis - 60 * 60 * 1000) || timestamp > BigInt(nowMillis + 60000) || textAttribute(record, "app.event.schema.version") !== "1" || Option6.isNone(Schema9.decodeUnknownOption(EventUuid)(textAttribute(record, "analytics.page_view.id"))) || Option6.isNone(Schema9.decodeUnknownOption(EventId)(textAttribute(record, "log.record.uid"))) || Option6.isNone(Schema9.decodeUnknownOption(BrowserEventPath)(textAttribute(record, "url.path")))) {
936
1000
  return yield* new OtlpProcessingError({ status: 400 });
937
1001
  }
938
1002
  }
@@ -942,18 +1006,18 @@ class Events extends Context4.Service()("krakstack/events/Events", {
942
1006
  "organization.id",
943
1007
  ...actorAttributeKeys
944
1008
  ].some((key) => annotations[key] !== undefined);
945
- const trustedIdentity = yield* (hasIdentity ? Schema8.decodeUnknownEffect(EventIdentity)({
1009
+ const trustedIdentity = yield* (hasIdentity ? Schema9.decodeUnknownEffect(EventIdentity)({
946
1010
  userId: annotations["user.id"],
947
1011
  organizationId: annotations["organization.id"]
948
- }) : options.identity ? options.identity(request).pipe(Effect7.flatMap(Schema8.decodeUnknownEffect(Schema8.NullOr(EventIdentity)))) : Effect7.succeed(null)).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 503 })));
949
- const trustedActor = actorAttributeKeys.some((key) => annotations[key] !== undefined) ? yield* Schema8.decodeUnknownEffect(RequestActorAttribution)(Object.fromEntries(actorAttributeKeys.filter((key) => annotations[key] !== undefined).map((key) => [key, annotations[key]]))).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 503 }))) : {};
1012
+ }) : options.identity ? options.identity(request).pipe(Effect8.flatMap(Schema9.decodeUnknownEffect(Schema9.NullOr(EventIdentity)))) : Effect8.succeed(null)).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 503 })));
1013
+ const trustedActor = actorAttributeKeys.some((key) => annotations[key] !== undefined) ? yield* Schema9.decodeUnknownEffect(RequestActorAttribution)(Object.fromEntries(actorAttributeKeys.filter((key) => annotations[key] !== undefined).map((key) => [key, annotations[key]]))).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 503 }))) : {};
950
1014
  const trustedAttributes = {
951
1015
  ...identityAttributes(trustedIdentity),
952
1016
  ...trustedActor
953
1017
  };
954
- const location = yield* resolveGeolocation(request).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 503 })));
955
- const ingest = Effect7.gen(function* () {
956
- const requestContext = yield* resolveRequestContext(request, now, location);
1018
+ const location2 = yield* resolveGeolocation(request).pipe(Effect8.mapError(() => new OtlpProcessingError({ status: 503 })));
1019
+ const ingest = Effect8.gen(function* () {
1020
+ const requestContext = yield* resolveRequestContext(request, now, location2);
957
1021
  let index = 0;
958
1022
  const resourceLogs = payload.resourceLogs.map((resource) => ({
959
1023
  ...resource,
@@ -991,7 +1055,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
991
1055
  if (scope.scope?.name !== "krakstack.application.events")
992
1056
  continue;
993
1057
  for (const raw of scope.logRecords) {
994
- const record = yield* Schema8.decodeUnknownEffect(EventLogRecord)(raw);
1058
+ const record = yield* Schema9.decodeUnknownEffect(EventLogRecord)(raw);
995
1059
  const persisted = yield* storage.persist({
996
1060
  source: "browser",
997
1061
  record,
@@ -1011,7 +1075,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
1011
1075
  }
1012
1076
  }
1013
1077
  }
1014
- const encoded = yield* Schema8.encodeEffect(codec)({
1078
+ const encoded = yield* Schema9.encodeEffect(codec2)({
1015
1079
  ...payload,
1016
1080
  resourceLogs: resourceLogs.map((resource) => ({
1017
1081
  ...resource,
@@ -1024,22 +1088,22 @@ class Events extends Context4.Service()("krakstack/events/Events", {
1024
1088
  const persisted = Boolean(storage) && payload.resourceLogs.every((resource) => resource.scopeLogs.every((scope) => scope.scope?.name === "krakstack.application.events" || scope.logRecords.length === 0));
1025
1089
  return { body: new TextEncoder().encode(encoded), persisted };
1026
1090
  });
1027
- return yield* (storage ? ingest.pipe(storage.sql.withTransaction) : ingest).pipe(Effect7.mapError((error) => new OtlpProcessingError({
1091
+ return yield* (storage ? ingest.pipe(storage.sql.withTransaction) : ingest).pipe(Effect8.mapError((error) => new OtlpProcessingError({
1028
1092
  status: error._tag === "EventConflictError" ? 409 : 503
1029
1093
  })));
1030
1094
  });
1031
1095
  return { process, track, listAudit };
1032
1096
  })
1033
1097
  }) {
1034
- static baseLayerWith = (options = {}) => Layer3.effect(this, Effect7.gen(function* () {
1098
+ static baseLayerWith = (options = {}) => Layer3.effect(this, Effect8.gen(function* () {
1035
1099
  const origin = options.origin ?? (yield* Config2.URL("VITE_SITE_URL").pipe(Config2.map((url) => url.origin)));
1036
1100
  const secret = options.secret ?? (yield* Config2.Redacted("APP_SECRET"));
1037
1101
  return yield* Events.make({ ...options, origin, secret });
1038
1102
  }));
1039
1103
  static baseLayer = this.baseLayerWith();
1040
- static layerWith = (options = {}) => this.baseLayerWith(options).pipe(Layer3.provide(Layer3.effectDiscard(Effect7.gen(function* () {
1041
- const client = yield* Effect7.serviceOption(SqlClient2.SqlClient);
1042
- if (Option5.isNone(client))
1104
+ static layerWith = (options = {}) => this.baseLayerWith(options).pipe(Layer3.provide(Layer3.effectDiscard(Effect8.gen(function* () {
1105
+ const client = yield* Effect8.serviceOption(SqlClient2.SqlClient);
1106
+ if (Option6.isNone(client))
1043
1107
  return;
1044
1108
  if (!client.value.onDialectOrElse({
1045
1109
  pg: () => true,
@@ -1050,7 +1114,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
1050
1114
  message: "Events supports PostgreSQL and SQLite"
1051
1115
  });
1052
1116
  }
1053
- yield* migrateEvents.pipe(Effect7.provideService(SqlClient2.SqlClient, client.value));
1117
+ yield* migrateEvents.pipe(Effect8.provideService(SqlClient2.SqlClient, client.value));
1054
1118
  }))));
1055
1119
  static layer = this.layerWith();
1056
1120
  static ingestionLayer = Layer3.effect(OtlpLogsProcessor, Events);
@@ -3,6 +3,16 @@ import { Effect as Effect2, Option as Option2, Schema as Schema3 } from "effect"
3
3
 
4
4
  // ../../src/services/opentelemetry/schema.ts
5
5
  import { Schema } from "effect";
6
+ var BrowserAnalyticsPreference = Schema.Struct({
7
+ version: Schema.String,
8
+ choice: Schema.Literals(["accepted", "declined"]),
9
+ revision: Schema.String,
10
+ issuedAt: Schema.Finite,
11
+ expiresAt: Schema.Finite
12
+ }).annotate({ identifier: "BrowserAnalyticsPreference" });
13
+ var BrowserPrivacySignals = Schema.Struct({
14
+ globalPrivacyControl: Schema.optional(Schema.Boolean)
15
+ }).annotate({ identifier: "BrowserPrivacySignals" });
6
16
  var BrowserWebVital = Schema.Struct({
7
17
  name: Schema.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
8
18
  id: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
@@ -40,6 +40,16 @@ import {
40
40
 
41
41
  // ../../src/services/opentelemetry/schema.ts
42
42
  import { Schema } from "effect";
43
+ var BrowserAnalyticsPreference = Schema.Struct({
44
+ version: Schema.String,
45
+ choice: Schema.Literals(["accepted", "declined"]),
46
+ revision: Schema.String,
47
+ issuedAt: Schema.Finite,
48
+ expiresAt: Schema.Finite
49
+ }).annotate({ identifier: "BrowserAnalyticsPreference" });
50
+ var BrowserPrivacySignals = Schema.Struct({
51
+ globalPrivacyControl: Schema.optional(Schema.Boolean)
52
+ }).annotate({ identifier: "BrowserPrivacySignals" });
43
53
  var BrowserWebVital = Schema.Struct({
44
54
  name: Schema.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
45
55
  id: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
@@ -89,7 +99,9 @@ class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
89
99
  label: "OtlpEvents",
90
100
  body: (logRecords) => {
91
101
  const scopes = new Map;
92
- for (const { scopeName, ...record } of logRecords) {
102
+ for (const { scopeName, canExport, ...record } of logRecords) {
103
+ if (canExport && !canExport())
104
+ continue;
93
105
  const name = scopeName ?? options.scopeName ?? "krakstack.events";
94
106
  const records = scopes.get(name);
95
107
  if (records)
@@ -2,6 +2,14 @@ import { Effect, Layer, Schema } from "effect";
2
2
  import { type Otlp, OtlpExporter, OtlpLogger, OtlpMetrics, OtlpTracer } from "effect/observability";
3
3
  import { OtlpEvents, type EventExportOptions } from "./events.js";
4
4
  export type { EventAttributes, EventOptions } from "./schema.js";
5
+ /** Essential diagnostics omit arbitrary messages, functions, URL queries and directories. */
6
+ export declare const sanitizeBrowserException: (input: {
7
+ readonly type: string;
8
+ readonly stack?: string;
9
+ }) => {
10
+ message: string;
11
+ stack: string | undefined;
12
+ };
5
13
  type OtlpOptions = Parameters<typeof Otlp.layerJson>[0];
6
14
  type SignalOptions<Options> = Omit<Options, "url" | "resource" | "headers">;
7
15
  export interface BrowserOtlpOptions {
@@ -28,6 +28,16 @@ import {
28
28
 
29
29
  // ../../src/services/opentelemetry/schema.ts
30
30
  import { Schema } from "effect";
31
+ var BrowserAnalyticsPreference = Schema.Struct({
32
+ version: Schema.String,
33
+ choice: Schema.Literals(["accepted", "declined"]),
34
+ revision: Schema.String,
35
+ issuedAt: Schema.Finite,
36
+ expiresAt: Schema.Finite
37
+ }).annotate({ identifier: "BrowserAnalyticsPreference" });
38
+ var BrowserPrivacySignals = Schema.Struct({
39
+ globalPrivacyControl: Schema.optional(Schema.Boolean)
40
+ }).annotate({ identifier: "BrowserPrivacySignals" });
31
41
  var BrowserWebVital = Schema.Struct({
32
42
  name: Schema.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
33
43
  id: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
@@ -77,7 +87,9 @@ class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
77
87
  label: "OtlpEvents",
78
88
  body: (logRecords) => {
79
89
  const scopes = new Map;
80
- for (const { scopeName, ...record } of logRecords) {
90
+ for (const { scopeName, canExport, ...record } of logRecords) {
91
+ if (canExport && !canExport())
92
+ continue;
81
93
  const name = scopeName ?? options.scopeName ?? "krakstack.events";
82
94
  const records = scopes.get(name);
83
95
  if (records)
@@ -146,15 +158,27 @@ class BrowserReportedError extends Schema3.TaggedError()("BrowserReportedError",
146
158
  stack: Schema3.optional(Schema3.String)
147
159
  }) {
148
160
  }
149
- var reportBrowserException = (exception) => Effect2.fail(exception).pipe(Effect2.withSpan("browser.exception", {
150
- root: true,
151
- sampled: true,
152
- attributes: {
153
- "exception.type": exception.type,
154
- "exception.message": exception.message,
155
- "exception.stacktrace": exception.stack ?? ""
156
- }
157
- }), Effect2.ignoreCause);
161
+ var reportBrowserException = (exception) => {
162
+ const sanitized = sanitizeBrowserException(exception);
163
+ return Effect2.fail(new BrowserReportedError({ type: exception.type, ...sanitized })).pipe(Effect2.withSpan("browser.exception", {
164
+ root: true,
165
+ sampled: true,
166
+ attributes: {
167
+ "exception.type": exception.type,
168
+ "exception.message": sanitized.message,
169
+ "exception.stacktrace": sanitized.stack ?? ""
170
+ }
171
+ }), Effect2.ignoreCause);
172
+ };
173
+ var sanitizeBrowserException = (input) => ({
174
+ message: input.type === "window.error" ? "Browser error" : "Unhandled promise rejection",
175
+ stack: input.stack?.split(`
176
+ `).slice(1, 21).flatMap((line) => {
177
+ const match = line.match(/([a-zA-Z0-9_.-]+\.(?:m?js|tsx?)):(\d+):(\d+)/);
178
+ return match ? [`${match[1]}:${match[2]}:${match[3]}`] : [];
179
+ }).join(`
180
+ `)
181
+ });
158
182
  var BrowserExceptionTrackingLive = Layer2.effectDiscard(Stream.merge(Stream.fromEventListener(globalThis, "error", {
159
183
  bufferSize: 100
160
184
  }).pipe(Stream.map((event) => {
@@ -246,5 +270,6 @@ class BrowserOtlp {
246
270
  };
247
271
  }
248
272
  export {
249
- BrowserOtlp
273
+ BrowserOtlp,
274
+ sanitizeBrowserException
250
275
  };
@@ -0,0 +1,21 @@
1
+ export declare const ANALYTICS_CONSENT_COOKIE = "krakstack_analytics_consent";
2
+ export declare const ANALYTICS_NOTICE_VERSION = "1";
3
+ export declare const analyticsPreference: (cookie: string, now?: number) => {
4
+ readonly version: string;
5
+ readonly choice: "accepted" | "declined";
6
+ readonly revision: string;
7
+ readonly issuedAt: number;
8
+ readonly expiresAt: number;
9
+ } | undefined;
10
+ /** Server-side check; request headers are opt-out signals, never proof of consent. */
11
+ export declare const hasAnalyticsConsent: (cookie: string, headers?: Readonly<Record<string, string | undefined>>) => boolean;
12
+ export declare const browserPrivacyEnabled: () => boolean;
13
+ export declare const analyticsConsentSnapshot: () => string;
14
+ export declare const analyticsAllowed: () => boolean;
15
+ /** Document-wide measurements require acceptance before navigation began. */
16
+ export declare const analyticsAcceptedBefore: (timestamp: number) => boolean;
17
+ /** A queued event is invalid forever if consent changes before export. */
18
+ export declare const analyticsExportGuard: () => () => boolean;
19
+ export declare const saveAnalyticsPreference: (choice: "accepted" | "declined") => boolean;
20
+ /** Polling covers cross-tab cookie changes, expiry and browser signal changes. */
21
+ export declare const subscribeAnalyticsConsent: (listener: () => void) => () => void;