@krak-stack/registry 0.1.51 → 0.1.52

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.
@@ -3,13 +3,13 @@ import { createHmac, randomUUID } from "node:crypto";
3
3
  import {
4
4
  Context as Context4,
5
5
  DateTime as DateTime2,
6
- Effect as Effect6,
6
+ Effect as Effect7,
7
7
  Layer as Layer3,
8
- Option as Option4,
8
+ Option as Option5,
9
9
  Predicate,
10
10
  Redacted,
11
11
  References as References2,
12
- Schema as Schema7
12
+ Schema as Schema8
13
13
  } from "effect";
14
14
  import { HttpServerRequest } from "effect/http";
15
15
  import { SqlClient as SqlClient2, SqlSchema } from "effect/sql";
@@ -198,147 +198,303 @@ class Otlp extends Context3.Service()("krakstack/opentelemetry/Otlp") {
198
198
 
199
199
  // ../../src/services/events/request-context.ts
200
200
  import Bowser from "bowser";
201
- import { Option as Option3, Schema as Schema6 } from "effect";
201
+ import { Option as Option4, Schema as Schema7 } from "effect";
202
202
 
203
203
  // ../../src/services/events/schema.ts
204
- import { Effect as Effect4, Option as Option2, Schema as Schema5 } from "effect";
205
- var EventUuid = Schema5.String.check(Schema5.isUUID());
206
- var EventId = Schema5.NonEmptyString.check(Schema5.isMaxLength(100));
207
- var BrowserEventPath = Schema5.String.check(Schema5.isMaxLength(2048), Schema5.isPattern(/^\/(?!\/)[^?#]*$/));
208
- var EventIdentity = Schema5.Struct({
209
- userId: Schema5.optional(Schema5.NonEmptyString),
210
- organizationId: Schema5.optional(Schema5.NonEmptyString)
204
+ import { Effect as Effect5, Option as Option3, Schema as Schema6 } from "effect";
205
+
206
+ // ../../src/lib/query.ts
207
+ import {
208
+ Effect as Effect4,
209
+ Option as Option2,
210
+ Schema as Schema5,
211
+ SchemaGetter,
212
+ SchemaIssue,
213
+ SchemaTransformation
214
+ } from "effect";
215
+ var parseSortParam = (sort) => {
216
+ const id = sort.startsWith("-") ? sort.slice(1) : sort;
217
+ if (!id || id.includes(",") || id.includes(":")) {
218
+ return null;
219
+ }
220
+ return { id, direction: sort.startsWith("-") ? "desc" : "asc" };
221
+ };
222
+ var SortDirection = Schema5.Union([
223
+ Schema5.Literal("asc"),
224
+ Schema5.Literal("desc")
225
+ ]).pipe(Schema5.annotate({
226
+ identifier: "SortDirection",
227
+ title: "Sort Direction",
228
+ description: "Sort direction for list query results.",
229
+ examples: ["asc", "desc"]
230
+ }));
231
+ var SortParam = Schema5.Struct({
232
+ id: Schema5.NonEmptyString,
233
+ direction: SortDirection
234
+ }).pipe(Schema5.annotate({
235
+ identifier: "SortParam",
236
+ title: "Sort Parameter",
237
+ description: "Decoded sort parameter with a field id and direction.",
238
+ examples: [{ id: "publicName", direction: "asc" }]
239
+ }));
240
+ var SortParamFromString = Schema5.String.pipe(Schema5.decodeTo(SortParam, SchemaTransformation.transformEffect({
241
+ decode: (sort) => {
242
+ const sortParam = parseSortParam(sort);
243
+ if (!sortParam) {
244
+ return Effect4.fail(new SchemaIssue.InvalidValue({ message: 'Expected sort in the format "field" or "-field"' }, sort));
245
+ }
246
+ return Effect4.succeed(sortParam);
247
+ },
248
+ encode: (sort) => Effect4.succeed(sort.direction === "desc" ? `-${sort.id}` : sort.id)
249
+ })), Schema5.annotate({
250
+ identifier: "SortParamFromString",
251
+ title: "Sort Parameter From String",
252
+ description: 'URL encoded single sort parameter where descending fields are prefixed with "-".',
253
+ examples: [{ id: "publicName", direction: "asc" }]
254
+ }));
255
+ var SortParamsFromString = Schema5.String.pipe(Schema5.decodeTo(Schema5.Array(SortParam), SchemaTransformation.transformEffect({
256
+ decode: (sort) => {
257
+ if (sort === "")
258
+ return Effect4.succeed([]);
259
+ const parts = sort.split(",");
260
+ const sortParams = [];
261
+ for (const part of parts) {
262
+ const sortParam = parseSortParam(part);
263
+ if (!sortParam) {
264
+ return Effect4.fail(new SchemaIssue.InvalidValue({ message: 'Expected sort in the format "field,-otherField"' }, sort));
265
+ }
266
+ sortParams.push(sortParam);
267
+ }
268
+ return Effect4.succeed(sortParams);
269
+ },
270
+ encode: (sort) => Effect4.succeed(sort.map((part) => Schema5.encodeSync(SortParamFromString)(part)).join(","))
271
+ })), Schema5.annotate({
272
+ identifier: "SortParamsFromString",
273
+ title: "Sort Parameters From String",
274
+ description: 'URL encoded sort parameters where descending fields are prefixed with "-" and multiple fields are comma-separated.',
275
+ examples: [
276
+ [
277
+ { id: "name", direction: "desc" },
278
+ { id: "age", direction: "asc" }
279
+ ]
280
+ ]
281
+ }));
282
+ var SortParamsArray = Schema5.Array(SortParam);
283
+ var SortParams = Schema5.declare(Schema5.is(SortParamsArray), {
284
+ identifier: "SortParams",
285
+ toCodec: () => Schema5.link()(SortParamsArray, SchemaTransformation.passthrough()),
286
+ toCodecStringTree: () => Schema5.link()(SortParamsFromString, SchemaTransformation.passthrough())
287
+ });
288
+ var Query = Schema5.Struct({
289
+ page: Schema5.optional(Schema5.Union([Schema5.Number, Schema5.NumberFromString]).check(Schema5.isInt(), Schema5.isGreaterThanOrEqualTo(0))).pipe(Schema5.decodeTo(Schema5.Int.check(Schema5.isGreaterThanOrEqualTo(0)), {
290
+ decode: SchemaGetter.withDefault(Effect4.succeed(0)),
291
+ encode: SchemaGetter.transformOptional(Option2.filter((page) => page !== 0))
292
+ })),
293
+ pageSize: Schema5.optional(Schema5.Union([Schema5.Number, Schema5.NumberFromString]).check(Schema5.isInt(), Schema5.isBetween({ minimum: 1, maximum: 100 }))).pipe(Schema5.decodeTo(Schema5.Int.check(Schema5.isBetween({ minimum: 1, maximum: 100 })), {
294
+ decode: SchemaGetter.withDefault(Effect4.succeed(20)),
295
+ encode: SchemaGetter.transformOptional(Option2.filter((pageSize) => pageSize !== 20))
296
+ })),
297
+ globalFilter: Schema5.optional(Schema5.String),
298
+ sort: Schema5.optional(SortParams)
299
+ }).annotate({
300
+ identifier: "Query",
301
+ title: "Query",
302
+ description: "Zero-based page request parameters with optional filtering and sorting for list endpoints.",
303
+ examples: [
304
+ {
305
+ page: 0,
306
+ pageSize: 20,
307
+ globalFilter: "housing",
308
+ sort: [
309
+ { id: "publicName", direction: "desc" },
310
+ { id: "createdAt", direction: "asc" }
311
+ ]
312
+ }
313
+ ]
314
+ });
315
+ var QueryStandard = Schema5.toStandardSchemaV1(Query);
316
+ var PaginationMeta = Schema5.Struct({
317
+ page: Schema5.Int,
318
+ pageSize: Schema5.Int,
319
+ total: Schema5.Int,
320
+ pageCount: Schema5.Int
321
+ }).pipe(Schema5.annotate({
322
+ identifier: "PaginationMeta",
323
+ title: "Pagination Metadata",
324
+ description: "Pagination metadata returned with a paginated list response.",
325
+ examples: [{ page: 0, pageSize: 20, total: 125, pageCount: 7 }]
326
+ }));
327
+
328
+ // ../../src/services/events/schema.ts
329
+ var EventUuid = Schema6.String.check(Schema6.isUUID());
330
+ var EventId = Schema6.NonEmptyString.check(Schema6.isMaxLength(100));
331
+ var BrowserEventPath = Schema6.String.check(Schema6.isMaxLength(2048), Schema6.isPattern(/^\/(?!\/)[^?#]*$/));
332
+ var EventIdentity = Schema6.Struct({
333
+ userId: Schema6.optional(Schema6.NonEmptyString),
334
+ organizationId: Schema6.optional(Schema6.NonEmptyString)
211
335
  }).annotate({ identifier: "EventIdentity" });
212
- var EventIpAddress = Schema5.String.check(Schema5.makeFilter((value) => Option2.isSome(Schema5.decodeUnknownOption(Schema5.IpAddressFromString)(value)) || "Invalid IP address")).annotate({ identifier: "EventIpAddress" });
213
- var EventCountry = Schema5.String.check(Schema5.isPattern(/^[A-Z]{2}$/), Schema5.makeFilter((value) => !["XX", "T1"].includes(value) || "Unknown country")).annotate({ identifier: "EventCountry" });
214
- var EventRegion = Schema5.String.check(Schema5.isPattern(/^[A-Z0-9]{1,3}$/)).annotate({ identifier: "EventRegion" });
215
- var EventCity = Schema5.NonEmptyString.check(Schema5.isMaxLength(128)).annotate({ identifier: "EventCity" });
216
- var EventGeolocation = Schema5.Struct({
217
- ip: Schema5.optional(EventIpAddress),
218
- country: Schema5.optional(EventCountry),
219
- region: Schema5.optional(EventRegion),
220
- city: Schema5.optional(EventCity)
336
+ var EventIpAddress = Schema6.String.check(Schema6.makeFilter((value) => Option3.isSome(Schema6.decodeUnknownOption(Schema6.IpAddressFromString)(value)) || "Invalid IP address")).annotate({ identifier: "EventIpAddress" });
337
+ var EventCountry = Schema6.String.check(Schema6.isPattern(/^[A-Z]{2}$/), Schema6.makeFilter((value) => !["XX", "T1"].includes(value) || "Unknown country")).annotate({ identifier: "EventCountry" });
338
+ var EventRegion = Schema6.String.check(Schema6.isPattern(/^[A-Z0-9]{1,3}$/)).annotate({ identifier: "EventRegion" });
339
+ var EventCity = Schema6.NonEmptyString.check(Schema6.isMaxLength(128)).annotate({ identifier: "EventCity" });
340
+ var EventGeolocation = Schema6.Struct({
341
+ ip: Schema6.optional(EventIpAddress),
342
+ country: Schema6.optional(EventCountry),
343
+ region: Schema6.optional(EventRegion),
344
+ city: Schema6.optional(EventCity)
221
345
  }).annotate({ identifier: "EventGeolocation" });
222
346
 
223
- class EventGeolocationError extends Schema5.TaggedError()("EventGeolocationError", {}) {
347
+ class EventGeolocationError extends Schema6.TaggedError()("EventGeolocationError", {}) {
224
348
  }
225
- var BrowserEventOptions = Schema5.Struct({
226
- messageId: Schema5.optional(EventId),
227
- timestamp: Schema5.optional(Schema5.DateTimeUtc),
228
- context: Schema5.optional(EventAttributesSchema)
349
+ var BrowserEventOptions = Schema6.Struct({
350
+ messageId: Schema6.optional(EventId),
351
+ timestamp: Schema6.optional(Schema6.DateTimeUtc),
352
+ context: Schema6.optional(EventAttributesSchema)
229
353
  }).annotate({ identifier: "BrowserEventOptions" });
230
- var BrowserPage = Schema5.Struct({
231
- name: Schema5.optional(Schema5.NonEmptyString),
232
- category: Schema5.optional(Schema5.NonEmptyString),
233
- path: Schema5.optional(Schema5.NonEmptyString),
234
- properties: Schema5.optional(EventAttributesSchema),
235
- options: Schema5.optional(BrowserEventOptions)
354
+ var BrowserPage = Schema6.Struct({
355
+ name: Schema6.optional(Schema6.NonEmptyString),
356
+ category: Schema6.optional(Schema6.NonEmptyString),
357
+ path: Schema6.optional(Schema6.NonEmptyString),
358
+ properties: Schema6.optional(EventAttributesSchema),
359
+ options: Schema6.optional(BrowserEventOptions)
236
360
  }).annotate({ identifier: "BrowserPage" });
237
- var TrackEvent = Schema5.Struct({
238
- eventId: EventId,
239
- name: Schema5.NonEmptyString.check(Schema5.isMaxLength(128)),
240
- properties: Schema5.optional(EventAttributesSchema),
241
- identity: Schema5.optional(EventIdentity),
242
- timestamp: Schema5.optional(Schema5.DateTimeUtc),
243
- category: Schema5.optional(Schema5.Literals(["analytics", "audit"]))
244
- }).annotate({ identifier: "TrackEvent" });
245
- var AuditAttribution = Schema5.Struct({
246
- "app.actor.type": Schema5.NonEmptyString,
247
- "app.actor.id": Schema5.NonEmptyString
361
+ var AuditTarget = Schema6.Struct({
362
+ id: Schema6.NonEmptyString.check(Schema6.isMaxLength(256)),
363
+ name: Schema6.NonEmptyString.check(Schema6.isMaxLength(2048)),
364
+ type: Schema6.NonEmptyString.check(Schema6.isMaxLength(128))
365
+ }).annotate({ identifier: "AuditTarget" });
366
+ var trackEventFields = {
367
+ eventId: Schema6.optional(EventId),
368
+ name: Schema6.NonEmptyString.check(Schema6.isMaxLength(128)),
369
+ properties: Schema6.optional(EventAttributesSchema),
370
+ identity: Schema6.optional(EventIdentity),
371
+ timestamp: Schema6.optional(Schema6.DateTimeUtc)
372
+ };
373
+ var TrackEvent = Schema6.Union([
374
+ Schema6.Struct({
375
+ ...trackEventFields,
376
+ category: Schema6.optional(Schema6.Literal("analytics"))
377
+ }),
378
+ Schema6.Struct({
379
+ ...trackEventFields,
380
+ category: Schema6.Literal("audit"),
381
+ target: AuditTarget
382
+ })
383
+ ]).annotate({ identifier: "TrackEvent" });
384
+ var ListAudit = Schema6.Struct({
385
+ organizationId: Schema6.NonEmptyString,
386
+ ...Query.fields
387
+ }).annotate({ identifier: "ListAudit" });
388
+ var AuditSortId = Schema6.Literals([
389
+ "time",
390
+ "eventName",
391
+ "recordType",
392
+ "record",
393
+ "actorType",
394
+ "actorId"
395
+ ]).annotate({ identifier: "AuditSortId" });
396
+ var AuditCount = Schema6.Struct({ total: Schema6.Int }).annotate({
397
+ identifier: "AuditCount"
398
+ });
399
+ var AuditAttribution = Schema6.Struct({
400
+ "app.actor.type": Schema6.NonEmptyString,
401
+ "app.actor.id": Schema6.NonEmptyString
248
402
  }).annotate({ identifier: "AuditAttribution" });
249
- var RequestActorAttribution = Schema5.Struct({
403
+ var RequestActorAttribution = Schema6.Struct({
250
404
  ...AuditAttribution.fields,
251
- "app.actor.owner.type": Schema5.optional(Schema5.NonEmptyString),
252
- "app.actor.owner.id": Schema5.optional(Schema5.NonEmptyString)
405
+ "app.auth.method": Schema6.optional(Schema6.NonEmptyString),
406
+ "app.auth.credential.id": Schema6.optional(Schema6.NonEmptyString),
407
+ "app.auth.impersonator.id": Schema6.optional(Schema6.NonEmptyString),
408
+ "user.roles": Schema6.optional(Schema6.Array(Schema6.String))
253
409
  }).annotate({ identifier: "RequestActorAttribution" });
254
410
 
255
- class EventsPersistenceError extends Schema5.TaggedError()("EventsPersistenceError", { operation: Schema5.String }) {
411
+ class EventsPersistenceError extends Schema6.TaggedError()("EventsPersistenceError", { operation: Schema6.String }) {
256
412
  }
257
413
 
258
- class EventConflictError extends Schema5.TaggedError()("EventConflictError", { eventId: EventId }) {
414
+ class EventConflictError extends Schema6.TaggedError()("EventConflictError", { eventId: EventId }) {
259
415
  }
260
- var EventSource = Schema5.Literals(["browser", "server"]).annotate({
416
+ var EventSource = Schema6.Literals(["browser", "server"]).annotate({
261
417
  identifier: "EventSource"
262
418
  });
263
- var ExistingEventRequest = Schema5.Struct({
419
+ var ExistingEventRequest = Schema6.Struct({
264
420
  eventId: EventId,
265
421
  source: EventSource
266
422
  }).annotate({ identifier: "ExistingEventRequest" });
267
- var StoredEventRequest = Schema5.Struct({
423
+ var StoredEventRequest = Schema6.Struct({
268
424
  source: EventSource,
269
425
  event_id: EventId,
270
- event_name: Schema5.NonEmptyString,
271
- event_type: Schema5.Literals(["page", "track"]),
272
- occurred_at: Schema5.Finite,
273
- received_at: Schema5.Finite,
274
- organization_id: Schema5.NullOr(Schema5.NonEmptyString),
275
- user_id: Schema5.NullOr(Schema5.NonEmptyString),
276
- session_id: Schema5.NullOr(Schema5.NonEmptyString),
277
- anonymous_id: Schema5.NullOr(Schema5.NonEmptyString),
278
- payload_json: Schema5.String
426
+ event_name: Schema6.NonEmptyString,
427
+ event_type: Schema6.Literals(["page", "track"]),
428
+ occurred_at: Schema6.Finite,
429
+ received_at: Schema6.Finite,
430
+ organization_id: Schema6.NullOr(Schema6.NonEmptyString),
431
+ user_id: Schema6.NullOr(Schema6.NonEmptyString),
432
+ session_id: Schema6.NullOr(Schema6.NonEmptyString),
433
+ anonymous_id: Schema6.NullOr(Schema6.NonEmptyString),
434
+ payload_json: Schema6.String
279
435
  }).annotate({ identifier: "StoredEventRequest" });
280
- var StoredEventId = Schema5.Struct({
436
+ var StoredEventId = Schema6.Struct({
281
437
  event_id: EventId
282
438
  }).annotate({ identifier: "StoredEventId" });
283
- var PrimitiveValue = Schema5.Union([
284
- Schema5.Struct({ stringValue: Schema5.String.check(Schema5.isMaxLength(2048)) }),
285
- Schema5.Struct({
286
- intValue: Schema5.Union([
287
- Schema5.String.check(Schema5.isPattern(/^-?\d{1,20}$/)),
288
- Schema5.Int
439
+ var PrimitiveValue = Schema6.Union([
440
+ Schema6.Struct({ stringValue: Schema6.String.check(Schema6.isMaxLength(2048)) }),
441
+ Schema6.Struct({
442
+ intValue: Schema6.Union([
443
+ Schema6.String.check(Schema6.isPattern(/^-?\d{1,20}$/)),
444
+ Schema6.Int
289
445
  ])
290
446
  }),
291
- Schema5.Struct({ doubleValue: Schema5.Finite }),
292
- Schema5.Struct({ boolValue: Schema5.Boolean })
447
+ Schema6.Struct({ doubleValue: Schema6.Finite }),
448
+ Schema6.Struct({ boolValue: Schema6.Boolean })
293
449
  ]);
294
- var AttributeValue = Schema5.Union([
450
+ var AttributeValue = Schema6.Union([
295
451
  PrimitiveValue,
296
- Schema5.Struct({
297
- arrayValue: Schema5.Struct({
298
- values: Schema5.Array(PrimitiveValue).check(Schema5.isMaxLength(32))
452
+ Schema6.Struct({
453
+ arrayValue: Schema6.Struct({
454
+ values: Schema6.Array(PrimitiveValue).check(Schema6.isMaxLength(32))
299
455
  })
300
456
  })
301
457
  ]);
302
- var EventAttribute = Schema5.Struct({
303
- key: Schema5.NonEmptyString.check(Schema5.isMaxLength(128)),
458
+ var EventAttribute = Schema6.Struct({
459
+ key: Schema6.NonEmptyString.check(Schema6.isMaxLength(128)),
304
460
  value: AttributeValue
305
461
  }).annotate({ identifier: "EventAttribute" });
306
- var EventLogRecord = Schema5.Struct({
307
- eventName: Schema5.NonEmptyString.check(Schema5.isMaxLength(128), Schema5.isPattern(/^[^\r\n]+$/)),
308
- timeUnixNano: Schema5.String.check(Schema5.isPattern(/^\d{1,20}$/)),
309
- observedTimeUnixNano: Schema5.optional(Schema5.String.check(Schema5.isPattern(/^\d{1,20}$/))),
310
- severityNumber: Schema5.optional(Schema5.Int),
311
- traceId: Schema5.optional(Schema5.String.check(Schema5.isPattern(/^[a-f0-9]{32}$/))),
312
- spanId: Schema5.optional(Schema5.String.check(Schema5.isPattern(/^[a-f0-9]{16}$/))),
313
- attributes: Schema5.Array(EventAttribute).check(Schema5.isMaxLength(64), Schema5.makeFilter((values) => new Set(values.map(({ key }) => key)).size === values.length || "Duplicate attribute keys"))
462
+ var EventLogRecord = Schema6.Struct({
463
+ eventName: Schema6.NonEmptyString.check(Schema6.isMaxLength(128), Schema6.isPattern(/^[^\r\n]+$/)),
464
+ timeUnixNano: Schema6.String.check(Schema6.isPattern(/^\d{1,20}$/)),
465
+ observedTimeUnixNano: Schema6.optional(Schema6.String.check(Schema6.isPattern(/^\d{1,20}$/))),
466
+ severityNumber: Schema6.optional(Schema6.Int),
467
+ traceId: Schema6.optional(Schema6.String.check(Schema6.isPattern(/^[a-f0-9]{32}$/))),
468
+ spanId: Schema6.optional(Schema6.String.check(Schema6.isPattern(/^[a-f0-9]{16}$/))),
469
+ attributes: Schema6.Array(EventAttribute).check(Schema6.isMaxLength(64), Schema6.makeFilter((values) => new Set(values.map(({ key }) => key)).size === values.length || "Duplicate attribute keys"))
314
470
  }).annotate({ identifier: "EventLogRecord" });
315
- var extensions = Schema5.Record(Schema5.String, Schema5.Unknown);
316
- var OtlpLogs = Schema5.StructWithRest(Schema5.Struct({
317
- resourceLogs: Schema5.Array(Schema5.StructWithRest(Schema5.Struct({
318
- scopeLogs: Schema5.Array(Schema5.StructWithRest(Schema5.Struct({
319
- scope: Schema5.optional(Schema5.StructWithRest(Schema5.Struct({ name: Schema5.optional(Schema5.String) }), [extensions])),
320
- logRecords: Schema5.Array(Schema5.Unknown).pipe(Schema5.withDecodingDefaultKey(Effect4.succeed([])))
321
- }), [extensions])).pipe(Schema5.withDecodingDefaultKey(Effect4.succeed([])))
322
- }), [extensions])).pipe(Schema5.withDecodingDefaultKey(Effect4.succeed([])))
471
+ var extensions = Schema6.Record(Schema6.String, Schema6.Unknown);
472
+ var OtlpLogs = Schema6.StructWithRest(Schema6.Struct({
473
+ resourceLogs: Schema6.Array(Schema6.StructWithRest(Schema6.Struct({
474
+ scopeLogs: Schema6.Array(Schema6.StructWithRest(Schema6.Struct({
475
+ scope: Schema6.optional(Schema6.StructWithRest(Schema6.Struct({ name: Schema6.optional(Schema6.String) }), [extensions])),
476
+ logRecords: Schema6.Array(Schema6.Unknown).pipe(Schema6.withDecodingDefaultKey(Effect5.succeed([])))
477
+ }), [extensions])).pipe(Schema6.withDecodingDefaultKey(Effect5.succeed([])))
478
+ }), [extensions])).pipe(Schema6.withDecodingDefaultKey(Effect5.succeed([])))
323
479
  }), [extensions]).annotate({ identifier: "EventsOtlpLogs" });
324
- var StoredEventPayload = Schema5.Struct({
325
- payload_json: Schema5.Union([OtlpLogs, Schema5.fromJsonString(OtlpLogs)])
480
+ var StoredEventPayload = Schema6.Struct({
481
+ payload_json: Schema6.Union([OtlpLogs, Schema6.fromJsonString(OtlpLogs)])
326
482
  }).annotate({ identifier: "StoredEventPayload" });
327
- var VisitorEventsRequest = Schema5.Struct({
328
- visitorId: Schema5.NonEmptyString
483
+ var VisitorEventsRequest = Schema6.Struct({
484
+ visitorId: Schema6.NonEmptyString
329
485
  }).annotate({ identifier: "VisitorEventsRequest" });
330
- var VisitorEventSession = Schema5.Struct({
486
+ var VisitorEventSession = Schema6.Struct({
331
487
  event_id: EventId,
332
- session_id: Schema5.NullOr(Schema5.NonEmptyString),
333
- received_at: Schema5.Finite
488
+ session_id: Schema6.NullOr(Schema6.NonEmptyString),
489
+ received_at: Schema6.Finite
334
490
  }).annotate({ identifier: "VisitorEventSession" });
335
491
 
336
492
  // ../../src/services/events/request-context.ts
337
493
  var cloudflareGeolocation = (headers) => ({
338
- ip: Option3.getOrUndefined(Schema6.decodeUnknownOption(EventIpAddress)(headers["cf-connecting-ip"])),
339
- country: Option3.getOrUndefined(Schema6.decodeUnknownOption(EventCountry)(headers["cf-ipcountry"])),
340
- region: Option3.getOrUndefined(Schema6.decodeUnknownOption(EventRegion)(headers["cf-region-code"])),
341
- city: Option3.getOrUndefined(Schema6.decodeUnknownOption(EventCity)(headers["cf-ipcity"]))
494
+ ip: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventIpAddress)(headers["cf-connecting-ip"])),
495
+ country: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventCountry)(headers["cf-ipcountry"])),
496
+ region: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventRegion)(headers["cf-region-code"])),
497
+ city: Option4.getOrUndefined(Schema7.decodeUnknownOption(EventCity)(headers["cf-ipcity"]))
342
498
  });
343
499
  var geolocationAttributes = (location) => {
344
500
  const attributes = {};
@@ -361,10 +517,10 @@ var deviceContext = (userAgent) => {
361
517
  };
362
518
 
363
519
  // ../../src/services/events/migrations.ts
364
- import { Effect as Effect5 } from "effect";
520
+ import { Effect as Effect6 } from "effect";
365
521
  import { Migrator, SqlClient } from "effect/sql";
366
522
  var eventsMigrations = Migrator.fromRecord({
367
- "1_events_initial": Effect5.gen(function* () {
523
+ "1_events_initial": Effect6.gen(function* () {
368
524
  const sql = yield* SqlClient.SqlClient;
369
525
  const payloadType = sql.onDialectOrElse({
370
526
  pg: () => sql.literal("jsonb"),
@@ -390,7 +546,7 @@ var eventsMigrations = Migrator.fromRecord({
390
546
  yield* sql`CREATE INDEX events_session_time ON events (service_name, session_id, occurred_at, event_id)`;
391
547
  yield* sql.onDialectOrElse({
392
548
  pg: () => sql`CREATE INDEX events_payload ON events USING gin (payload_json jsonb_path_ops)`,
393
- orElse: () => Effect5.void
549
+ orElse: () => Effect6.void
394
550
  });
395
551
  })
396
552
  });
@@ -412,23 +568,25 @@ var identityAttributes = (identity) => {
412
568
  var actorAttributeKeys = [
413
569
  "app.actor.type",
414
570
  "app.actor.id",
415
- "app.actor.owner.type",
416
- "app.actor.owner.id"
571
+ "app.auth.method",
572
+ "app.auth.credential.id",
573
+ "app.auth.impersonator.id",
574
+ "user.roles"
417
575
  ];
418
- var reservedBrowserAttribute = (key) => key.startsWith("app.actor.") || key.startsWith("app.audit.") || key.startsWith("app.executor.") || key === "app.access.channel";
419
- var Configuration = Schema7.Struct({
420
- serviceName: Schema7.NonEmptyString,
421
- origin: Schema7.URLFromString.check(Schema7.makeFilter((url) => (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash || "Expected an HTTP origin")),
422
- geolocation: Schema7.optional(Schema7.Union([
423
- Schema7.Literal("cloudflare"),
424
- Schema7.declare((value) => Predicate.isFunction(value))
576
+ 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";
577
+ var Configuration = Schema8.Struct({
578
+ serviceName: Schema8.NonEmptyString,
579
+ 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")),
580
+ geolocation: Schema8.optional(Schema8.Union([
581
+ Schema8.Literal("cloudflare"),
582
+ Schema8.declare((value) => Predicate.isFunction(value))
425
583
  ])),
426
- secret: Schema7.String.check(Schema7.isMinLength(32))
584
+ secret: Schema8.String.check(Schema8.isMinLength(32))
427
585
  }).annotate({ identifier: "EventsConfiguration" });
428
586
 
429
- class EventsConfigurationError extends Schema7.TaggedError()("EventsConfigurationError", { message: Schema7.String }) {
587
+ class EventsConfigurationError extends Schema8.TaggedError()("EventsConfigurationError", { message: Schema8.String }) {
430
588
  }
431
- var codec = Schema7.fromJsonString(OtlpLogs);
589
+ var codec = Schema8.fromJsonString(OtlpLogs);
432
590
  var textAttribute = (record, key) => {
433
591
  const value = record.attributes.find((attribute) => attribute.key === key)?.value;
434
592
  return value && "stringValue" in value ? value.stringValue : undefined;
@@ -467,18 +625,18 @@ var dailyVisitorId = (input) => createHmac("sha256", Redacted.value(input.secret
467
625
  ])).digest("hex");
468
626
 
469
627
  class Events extends Context4.Service()("krakstack/events/Events", {
470
- make: (options) => Effect6.gen(function* () {
628
+ make: (options) => Effect7.gen(function* () {
471
629
  const telemetry = yield* Otlp;
472
630
  const resource = options.serviceName ? yield* OtlpResource3.fromConfig({ serviceName: options.serviceName }) : yield* telemetry.resource;
473
- const configuration = yield* Schema7.decodeUnknownEffect(Configuration)({
631
+ const configuration = yield* Schema8.decodeUnknownEffect(Configuration)({
474
632
  ...options,
475
633
  serviceName: OtlpResource3.serviceNameUnsafe(resource),
476
634
  secret: Redacted.value(options.secret)
477
- }).pipe(Effect6.mapError(() => new EventsConfigurationError({
635
+ }).pipe(Effect7.mapError(() => new EventsConfigurationError({
478
636
  message: "Events requires an OTel service name, HTTP origin, and server secret of at least 32 characters"
479
637
  })));
480
- const client = yield* Effect6.serviceOption(SqlClient2.SqlClient);
481
- const storage = Option4.isSome(client) ? yield* Effect6.gen(function* () {
638
+ const client = yield* Effect7.serviceOption(SqlClient2.SqlClient);
639
+ const storage = Option5.isSome(client) ? yield* Effect7.gen(function* () {
482
640
  const sql = client.value.withoutTransforms();
483
641
  if (!sql.onDialectOrElse({
484
642
  pg: () => true,
@@ -519,10 +677,10 @@ class Events extends Context4.Service()("krakstack/events/Events", {
519
677
  ON CONFLICT (service_name, source, event_id) DO NOTHING RETURNING event_id
520
678
  `
521
679
  });
522
- const persist = Effect6.fnUntraced(function* (input) {
680
+ const persist = Effect7.fnUntraced(function* (input) {
523
681
  const { record, payload, now, source } = input;
524
682
  const eventId = textAttribute(record, "log.record.uid");
525
- const payloadJson = yield* Schema7.encodeEffect(codec)(payload);
683
+ const payloadJson = yield* Schema8.encodeEffect(codec)(payload);
526
684
  const inserted = yield* insertEvent({
527
685
  source,
528
686
  event_id: eventId,
@@ -536,10 +694,10 @@ class Events extends Context4.Service()("krakstack/events/Events", {
536
694
  anonymous_id: textAttribute(record, "analytics.anonymous_id") ?? null,
537
695
  payload_json: payloadJson
538
696
  });
539
- if (Option4.isSome(inserted))
697
+ if (Option5.isSome(inserted))
540
698
  return { eventId, inserted: true, record };
541
699
  const existing = yield* existingEvent({ source, eventId });
542
- const original = yield* Schema7.decodeUnknownEffect(EventLogRecord)(existing.payload_json.resourceLogs[0]?.scopeLogs[0]?.logRecords[0]);
700
+ const original = yield* Schema8.decodeUnknownEffect(EventLogRecord)(existing.payload_json.resourceLogs[0]?.scopeLogs[0]?.logRecords[0]);
543
701
  const identityChanged = source === "browser" && ["user.id", "organization.id"].some((key) => textAttribute(original, key) !== textAttribute(record, key));
544
702
  if (identityChanged || eventContent(original, source, input.compareTimestamp) !== eventContent(record, source, input.compareTimestamp)) {
545
703
  return yield* new EventConflictError({ eventId });
@@ -553,11 +711,11 @@ class Events extends Context4.Service()("krakstack/events/Events", {
553
711
  lockVisitor
554
712
  };
555
713
  }) : undefined;
556
- const resolveGeolocation = Effect6.fnUntraced(function* (request) {
714
+ const resolveGeolocation = Effect7.fnUntraced(function* (request) {
557
715
  const location = configuration.geolocation === "cloudflare" ? cloudflareGeolocation(request.headers) : configuration.geolocation ? yield* configuration.geolocation(request) : null;
558
- return yield* Schema7.decodeUnknownEffect(Schema7.NullOr(EventGeolocation))(location);
559
- }, Effect6.mapError(() => new EventGeolocationError({})));
560
- const resolveRequestContext = Effect6.fnUntraced(function* (request, now, location) {
716
+ return yield* Schema8.decodeUnknownEffect(Schema8.NullOr(EventGeolocation))(location);
717
+ }, Effect7.mapError(() => new EventGeolocationError({})));
718
+ const resolveRequestContext = Effect7.fnUntraced(function* (request, now, location) {
561
719
  const userAgent = request.headers["user-agent"]?.slice(0, 2048) ?? "";
562
720
  const visitorId = location?.ip && userAgent ? dailyVisitorId({
563
721
  serviceName: configuration.serviceName,
@@ -570,7 +728,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
570
728
  if (visitorId && storage) {
571
729
  yield* storage.lockVisitor(visitorId);
572
730
  const latest = yield* storage.latestSession({ visitorId });
573
- sessionId = Option4.isSome(latest) && latest.value.received_at > DateTime2.toEpochMillis(now) - SESSION_TIMEOUT_MS ? latest.value.session_id : randomUUID();
731
+ sessionId = Option5.isSome(latest) && latest.value.received_at > DateTime2.toEpochMillis(now) - SESSION_TIMEOUT_MS ? latest.value.session_id : randomUUID();
574
732
  }
575
733
  const identity = {};
576
734
  if (visitorId)
@@ -584,8 +742,9 @@ class Events extends Context4.Service()("krakstack/events/Events", {
584
742
  ...identity
585
743
  };
586
744
  });
587
- const track = Effect6.fn("Events.track")(function* (input) {
588
- const event = yield* Schema7.decodeUnknownEffect(TrackEvent)(input);
745
+ const track = Effect7.fn("Events.track")(function* (input) {
746
+ const event = yield* Schema8.decodeUnknownEffect(TrackEvent)(input);
747
+ const eventId = event.eventId ?? randomUUID();
589
748
  const category = event.category ?? "analytics";
590
749
  if (!storage)
591
750
  return yield* new EventsPersistenceError({
@@ -593,19 +752,19 @@ class Events extends Context4.Service()("krakstack/events/Events", {
593
752
  });
594
753
  const receivedAt = yield* DateTime2.now;
595
754
  const now = DateTime2.toEpochMillis(receivedAt);
596
- const request = yield* Effect6.serviceOption(HttpServerRequest.HttpServerRequest);
755
+ const request = yield* Effect7.serviceOption(HttpServerRequest.HttpServerRequest);
597
756
  const annotations = yield* References2.CurrentLogAnnotations;
598
757
  const hasIdentity = [
599
758
  "user.id",
600
759
  "organization.id",
601
760
  ...actorAttributeKeys
602
761
  ].some((key) => annotations[key] !== undefined);
603
- const identity = hasIdentity ? yield* Schema7.decodeUnknownEffect(EventIdentity)({
762
+ const identity = hasIdentity ? yield* Schema8.decodeUnknownEffect(EventIdentity)({
604
763
  userId: annotations["user.id"],
605
764
  organizationId: annotations["organization.id"]
606
765
  }) : event.identity;
607
766
  if (category === "audit") {
608
- yield* Schema7.decodeUnknownEffect(AuditAttribution)(annotations);
767
+ yield* Schema8.decodeUnknownEffect(AuditAttribution)(annotations);
609
768
  }
610
769
  const attributes = {};
611
770
  for (const [key, value] of Object.entries(event.properties ?? {})) {
@@ -614,26 +773,31 @@ class Events extends Context4.Service()("krakstack/events/Events", {
614
773
  attributes[name] = value;
615
774
  }
616
775
  Object.assign(attributes, identityAttributes(identity));
617
- Object.assign(attributes, annotations);
618
- attributes["log.record.uid"] = event.eventId;
776
+ Object.assign(attributes, Object.fromEntries(Object.entries(annotations).filter(([key]) => key !== "user.full_name" && key !== "user.name" && key !== "user.image" && key !== "app.user.image")));
777
+ attributes["log.record.uid"] = eventId;
778
+ if (event.category === "audit") {
779
+ attributes["app.audit.target.id"] = event.target.id;
780
+ attributes["app.audit.target.name"] = event.target.name;
781
+ attributes["app.audit.target.type"] = event.target.type;
782
+ }
619
783
  attributes["app.event.schema.version"] = "1";
620
784
  attributes["app.event.type"] = "track";
621
785
  attributes["app.event.source"] = "server";
622
786
  attributes["app.event.category"] = category;
623
- const span = yield* Effect6.currentSpan.pipe(Effect6.option);
624
- const location = Option4.isSome(request) ? yield* resolveGeolocation(request.value).pipe(Effect6.mapError(() => new EventsPersistenceError({ operation: "geolocation" }))) : null;
787
+ const span = yield* Effect7.currentSpan.pipe(Effect7.option);
788
+ const location = Option5.isSome(request) ? yield* resolveGeolocation(request.value).pipe(Effect7.mapError(() => new EventsPersistenceError({ operation: "geolocation" }))) : null;
625
789
  const entry = {
626
790
  eventName: event.name,
627
791
  timeUnixNano: (BigInt(event.timestamp ? DateTime2.toEpochMillis(event.timestamp) : now) * 1000000n).toString(),
628
792
  observedTimeUnixNano: (BigInt(now) * 1000000n).toString()
629
793
  };
630
- return yield* Effect6.gen(function* () {
631
- const requestContext = Option4.isSome(request) ? yield* resolveRequestContext(request.value, receivedAt, location) : {};
632
- const validated = yield* Schema7.decodeUnknownEffect(EventLogRecord)({
794
+ return yield* Effect7.gen(function* () {
795
+ const requestContext = Option5.isSome(request) ? yield* resolveRequestContext(request.value, receivedAt, location) : {};
796
+ const validated = yield* Schema8.decodeUnknownEffect(EventLogRecord)({
633
797
  ...entry,
634
798
  attributes: OtlpResource3.entriesToAttributes(Object.entries({ ...requestContext, ...attributes })),
635
- traceId: Option4.isSome(span) ? span.value.traceId : undefined,
636
- spanId: Option4.isSome(span) ? span.value.spanId : undefined
799
+ traceId: Option5.isSome(span) ? span.value.traceId : undefined,
800
+ spanId: Option5.isSome(span) ? span.value.spanId : undefined
637
801
  });
638
802
  return yield* storage.persist({
639
803
  source: "server",
@@ -654,13 +818,93 @@ class Events extends Context4.Service()("krakstack/events/Events", {
654
818
  ]
655
819
  }
656
820
  });
657
- }).pipe(storage.sql.withTransaction, Effect6.map(({ eventId, inserted }) => ({ eventId, inserted })), Effect6.mapError((error) => error._tag === "EventConflictError" ? error : new EventsPersistenceError({
821
+ }).pipe(storage.sql.withTransaction, Effect7.map(({ eventId, inserted }) => ({ eventId, inserted })), Effect7.mapError((error) => error._tag === "EventConflictError" ? error : new EventsPersistenceError({
658
822
  operation: "track"
659
823
  })));
660
824
  });
661
- const process = Effect6.fnUntraced(function* (body) {
825
+ const listAudit = Effect7.fn("Events.listAudit")(function* (input) {
826
+ const request = yield* Schema8.decodeUnknownEffect(ListAudit)(input);
827
+ if (!storage)
828
+ return yield* new EventsPersistenceError({
829
+ operation: "persistence-disabled"
830
+ });
831
+ const sql = storage.sql;
832
+ const text = (key) => sql.onDialectOrElse({
833
+ pg: () => sql`jsonb_path_query_first(payload_json, ${`$.resourceLogs[*].scopeLogs[*].logRecords[*].attributes[*] ? (@.key == ${JSON.stringify(key)}).value.stringValue`}::jsonpath) #>> '{}'`,
834
+ orElse: () => sql`(SELECT json_extract(attribute.value, '$.value.stringValue')
835
+ FROM json_each(payload_json, '$.resourceLogs') AS resource,
836
+ json_each(resource.value, '$.scopeLogs') AS scope,
837
+ json_each(scope.value, '$.logRecords') AS record,
838
+ json_each(record.value, '$.attributes') AS attribute
839
+ WHERE json_extract(attribute.value, '$.key') = ${key} LIMIT 1)`
840
+ });
841
+ const sortColumns = {
842
+ time: sql`occurred_at`,
843
+ eventName: sql`event_name`,
844
+ recordType: text("app.audit.target.type"),
845
+ record: text("app.audit.target.name"),
846
+ actorType: text("app.actor.type"),
847
+ actorId: text("app.actor.id")
848
+ };
849
+ const sort = yield* Effect7.forEach(request.sort ?? [], (part) => Effect7.gen(function* () {
850
+ const id = yield* Schema8.decodeUnknownEffect(AuditSortId)(part.id);
851
+ return sql`${sortColumns[id]} ${sql.literal(part.direction === "desc" ? "DESC" : "ASC")}`;
852
+ }));
853
+ const category = sql.onDialectOrElse({
854
+ pg: () => sql`jsonb_path_exists(payload_json, '$.resourceLogs[*].scopeLogs[*].logRecords[*].attributes[*] ? (@.key == "app.event.category" && @.value.stringValue == "audit")')`,
855
+ orElse: () => sql`EXISTS (
856
+ SELECT 1 FROM json_each(payload_json, '$.resourceLogs') AS resource,
857
+ json_each(resource.value, '$.scopeLogs') AS scope,
858
+ json_each(scope.value, '$.logRecords') AS record,
859
+ json_each(record.value, '$.attributes') AS attribute
860
+ WHERE json_extract(attribute.value, '$.key') = 'app.event.category'
861
+ AND json_extract(attribute.value, '$.value.stringValue') = 'audit'
862
+ )`
863
+ });
864
+ const search = request.globalFilter?.trim();
865
+ const filter = search ? sql`AND ${sql.or([
866
+ sql`LOWER(event_name) LIKE ${`%${search.toLowerCase()}%`}`,
867
+ ...[
868
+ "app.audit.target.id",
869
+ "app.audit.target.name",
870
+ "app.audit.target.type",
871
+ "app.actor.id",
872
+ "app.actor.type",
873
+ "user.id"
874
+ ].map((key) => sql`LOWER(${text(key)}) LIKE ${`%${search.toLowerCase()}%`}`)
875
+ ])}` : sql``;
876
+ const predicate = sql`service_name = ${configuration.serviceName} AND organization_id = ${request.organizationId}
877
+ AND source = 'server' AND ${category} ${filter}`;
878
+ const total = yield* SqlSchema.findOne({
879
+ Request: ListAudit,
880
+ Result: AuditCount,
881
+ execute: () => sql`SELECT CAST(COUNT(*) AS INTEGER) AS total FROM events WHERE ${predicate}`
882
+ })(request);
883
+ const find = SqlSchema.findAll({
884
+ Request: ListAudit,
885
+ Result: StoredEventPayload,
886
+ execute: () => sql`
887
+ SELECT payload_json FROM events
888
+ WHERE ${predicate}
889
+ ORDER BY ${sql.join(", ", false)(sort.length ? [...sort, sql`event_id DESC`] : [sql`occurred_at DESC`, sql`event_id DESC`])}
890
+ LIMIT ${request.pageSize} OFFSET ${request.page * request.pageSize}
891
+ `
892
+ });
893
+ const rows = yield* find(request);
894
+ const data = yield* Effect7.forEach(rows, (row) => Schema8.decodeUnknownEffect(EventLogRecord)(row.payload_json.resourceLogs.flatMap((resource) => resource.scopeLogs.flatMap((scope) => scope.logRecords))[0]));
895
+ return {
896
+ data,
897
+ meta: {
898
+ page: request.page,
899
+ pageSize: request.pageSize,
900
+ total: total.total,
901
+ pageCount: Math.ceil(total.total / request.pageSize)
902
+ }
903
+ };
904
+ });
905
+ const process = Effect7.fnUntraced(function* (body) {
662
906
  const request = yield* HttpServerRequest.HttpServerRequest;
663
- const payload = yield* Schema7.decodeUnknownEffect(codec)(new TextDecoder().decode(body)).pipe(Effect6.mapError(() => new OtlpProcessingError({ status: 400 })));
907
+ const payload = yield* Schema8.decodeUnknownEffect(codec)(new TextDecoder().decode(body)).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 400 })));
664
908
  const analyticsScopes = payload.resourceLogs.flatMap((resource) => resource.scopeLogs).filter((scope) => scope.scope?.name === "krakstack.application.events");
665
909
  if (analyticsScopes.length === 0)
666
910
  return { body, persisted: false };
@@ -668,12 +912,12 @@ class Events extends Context4.Service()("krakstack/events/Events", {
668
912
  return yield* new OtlpProcessingError({ status: 403 });
669
913
  }
670
914
  const rawRecords = analyticsScopes.flatMap((scope) => scope.logRecords);
671
- const records = yield* Schema7.decodeUnknownEffect(Schema7.Array(EventLogRecord).check(Schema7.isMinLength(1), Schema7.isMaxLength(100)))(rawRecords).pipe(Effect6.mapError(() => new OtlpProcessingError({ status: 400 })));
915
+ const records = yield* Schema8.decodeUnknownEffect(Schema8.Array(EventLogRecord).check(Schema8.isMinLength(1), Schema8.isMaxLength(100)))(rawRecords).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 400 })));
672
916
  const now = yield* DateTime2.now;
673
917
  const nowMillis = DateTime2.toEpochMillis(now);
674
918
  for (const record of records) {
675
919
  const timestamp = BigInt(record.timeUnixNano) / 1000000n;
676
- if (timestamp < BigInt(nowMillis - 60 * 60 * 1000) || timestamp > BigInt(nowMillis + 60000) || textAttribute(record, "app.event.schema.version") !== "1" || Option4.isNone(Schema7.decodeUnknownOption(EventUuid)(textAttribute(record, "analytics.page_view.id"))) || Option4.isNone(Schema7.decodeUnknownOption(EventId)(textAttribute(record, "log.record.uid"))) || Option4.isNone(Schema7.decodeUnknownOption(BrowserEventPath)(textAttribute(record, "url.path")))) {
920
+ 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")))) {
677
921
  return yield* new OtlpProcessingError({ status: 400 });
678
922
  }
679
923
  }
@@ -683,17 +927,17 @@ class Events extends Context4.Service()("krakstack/events/Events", {
683
927
  "organization.id",
684
928
  ...actorAttributeKeys
685
929
  ].some((key) => annotations[key] !== undefined);
686
- const trustedIdentity = yield* (hasIdentity ? Schema7.decodeUnknownEffect(EventIdentity)({
930
+ const trustedIdentity = yield* (hasIdentity ? Schema8.decodeUnknownEffect(EventIdentity)({
687
931
  userId: annotations["user.id"],
688
932
  organizationId: annotations["organization.id"]
689
- }) : options.identity ? options.identity(request).pipe(Effect6.flatMap(Schema7.decodeUnknownEffect(Schema7.NullOr(EventIdentity)))) : Effect6.succeed(null)).pipe(Effect6.mapError(() => new OtlpProcessingError({ status: 503 })));
690
- const trustedActor = actorAttributeKeys.some((key) => annotations[key] !== undefined) ? yield* Schema7.decodeUnknownEffect(RequestActorAttribution)(Object.fromEntries(actorAttributeKeys.filter((key) => annotations[key] !== undefined).map((key) => [key, annotations[key]]))).pipe(Effect6.mapError(() => new OtlpProcessingError({ status: 503 }))) : {};
933
+ }) : options.identity ? options.identity(request).pipe(Effect7.flatMap(Schema8.decodeUnknownEffect(Schema8.NullOr(EventIdentity)))) : Effect7.succeed(null)).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 503 })));
934
+ 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 }))) : {};
691
935
  const trustedAttributes = {
692
936
  ...identityAttributes(trustedIdentity),
693
937
  ...trustedActor
694
938
  };
695
- const location = yield* resolveGeolocation(request).pipe(Effect6.mapError(() => new OtlpProcessingError({ status: 503 })));
696
- const ingest = Effect6.gen(function* () {
939
+ const location = yield* resolveGeolocation(request).pipe(Effect7.mapError(() => new OtlpProcessingError({ status: 503 })));
940
+ const ingest = Effect7.gen(function* () {
697
941
  const requestContext = yield* resolveRequestContext(request, now, location);
698
942
  let index = 0;
699
943
  const resourceLogs = payload.resourceLogs.map((resource) => ({
@@ -732,7 +976,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
732
976
  if (scope.scope?.name !== "krakstack.application.events")
733
977
  continue;
734
978
  for (const raw of scope.logRecords) {
735
- const record = yield* Schema7.decodeUnknownEffect(EventLogRecord)(raw);
979
+ const record = yield* Schema8.decodeUnknownEffect(EventLogRecord)(raw);
736
980
  const persisted = yield* storage.persist({
737
981
  source: "browser",
738
982
  record,
@@ -752,7 +996,7 @@ class Events extends Context4.Service()("krakstack/events/Events", {
752
996
  }
753
997
  }
754
998
  }
755
- const encoded = yield* Schema7.encodeEffect(codec)({
999
+ const encoded = yield* Schema8.encodeEffect(codec)({
756
1000
  ...payload,
757
1001
  resourceLogs: resourceLogs.map((resource) => ({
758
1002
  ...resource,
@@ -765,17 +1009,17 @@ class Events extends Context4.Service()("krakstack/events/Events", {
765
1009
  const persisted = Boolean(storage) && payload.resourceLogs.every((resource) => resource.scopeLogs.every((scope) => scope.scope?.name === "krakstack.application.events" || scope.logRecords.length === 0));
766
1010
  return { body: new TextEncoder().encode(encoded), persisted };
767
1011
  });
768
- return yield* (storage ? ingest.pipe(storage.sql.withTransaction) : ingest).pipe(Effect6.mapError((error) => new OtlpProcessingError({
1012
+ return yield* (storage ? ingest.pipe(storage.sql.withTransaction) : ingest).pipe(Effect7.mapError((error) => new OtlpProcessingError({
769
1013
  status: error._tag === "EventConflictError" ? 409 : 503
770
1014
  })));
771
1015
  });
772
- return { process, track };
1016
+ return { process, track, listAudit };
773
1017
  })
774
1018
  }) {
775
1019
  static baseLayer = (options) => Layer3.effect(this, this.make(options));
776
- static layer = (options) => this.baseLayer(options).pipe(Layer3.provide(Layer3.effectDiscard(Effect6.gen(function* () {
777
- const client = yield* Effect6.serviceOption(SqlClient2.SqlClient);
778
- if (Option4.isNone(client))
1020
+ static layer = (options) => this.baseLayer(options).pipe(Layer3.provide(Layer3.effectDiscard(Effect7.gen(function* () {
1021
+ const client = yield* Effect7.serviceOption(SqlClient2.SqlClient);
1022
+ if (Option5.isNone(client))
779
1023
  return;
780
1024
  if (!client.value.onDialectOrElse({
781
1025
  pg: () => true,
@@ -786,13 +1030,17 @@ class Events extends Context4.Service()("krakstack/events/Events", {
786
1030
  message: "Events supports PostgreSQL and SQLite"
787
1031
  });
788
1032
  }
789
- yield* migrateEvents.pipe(Effect6.provideService(SqlClient2.SqlClient, client.value));
1033
+ yield* migrateEvents.pipe(Effect7.provideService(SqlClient2.SqlClient, client.value));
790
1034
  }))));
791
1035
  static ingestionLayer = Layer3.effect(OtlpLogsProcessor, Events);
792
1036
  }
793
1037
  export {
1038
+ AuditTarget,
1039
+ EventLogRecord,
794
1040
  Events,
795
1041
  EventsConfigurationError,
1042
+ ListAudit,
796
1043
  SESSION_TIMEOUT_MS,
1044
+ TrackEvent,
797
1045
  dailyVisitorId
798
1046
  };