@krak-stack/registry 0.1.50 → 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.
Files changed (31) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +16 -424
  3. package/dist/components/ui/data-table.d.ts +20 -1
  4. package/dist/components/ui/data-table.js +52 -1
  5. package/dist/lib/docs.js +2 -2
  6. package/dist/services/agent/client/index.js +1 -1
  7. package/dist/services/events/browser.d.ts +26 -0
  8. package/dist/services/events/browser.js +579 -0
  9. package/dist/services/events/client/audit-log-table.d.ts +53 -0
  10. package/dist/services/events/client/audit-log-table.js +3655 -0
  11. package/dist/services/events/index.d.ts +215 -0
  12. package/dist/services/events/index.js +1046 -0
  13. package/dist/services/events/migrations.d.ts +4 -0
  14. package/dist/services/events/migrations.js +42 -0
  15. package/dist/services/events/record.d.ts +3 -0
  16. package/dist/services/events/record.js +14 -0
  17. package/dist/services/events/request-context.d.ts +6 -0
  18. package/dist/services/events/schema.d.ts +237 -0
  19. package/dist/services/events/schema.js +361 -0
  20. package/dist/services/opentelemetry/api.d.ts +3 -1
  21. package/dist/services/opentelemetry/api.js +133 -64
  22. package/dist/services/opentelemetry/browser.d.ts +17 -20
  23. package/dist/services/opentelemetry/browser.js +58 -162
  24. package/dist/services/opentelemetry/events.d.ts +3 -1
  25. package/dist/services/opentelemetry/{server.d.ts → index.d.ts} +8 -5
  26. package/dist/services/opentelemetry/{server.js → index.js} +66 -48
  27. package/dist/services/opentelemetry/processor.d.ts +19 -0
  28. package/dist/services/opentelemetry/schema.d.ts +8 -20
  29. package/dist/services/opentelemetry/web-vitals.d.ts +15 -0
  30. package/dist/services/opentelemetry/web-vitals.js +229 -0
  31. package/package.json +35 -5
@@ -0,0 +1,26 @@
1
+ import type { EventAttributes } from "../opentelemetry/schema.js";
2
+ import { OtlpEvents } from "../opentelemetry/events.js";
3
+ import { Context, Effect, Layer, Schema } from "effect";
4
+ import { BrowserEventOptions, type BrowserPageOptions } from "./schema.js";
5
+ export type { BrowserEventOptions, BrowserPageOptions } from "./schema.js";
6
+ export type { EventAttributes } from "../opentelemetry/schema.js";
7
+ export interface BrowserEventsOptions {
8
+ readonly enabled?: boolean;
9
+ readonly respectDoNotTrack?: boolean;
10
+ readonly pageViews?: boolean;
11
+ readonly locale?: () => string;
12
+ /** Replace paths containing personal identifiers with route templates. */
13
+ readonly sanitizePath?: (path: string) => string;
14
+ }
15
+ declare const BrowserEventsClient_base: Context.ServiceClass<BrowserEventsClient, "krakstack/events/BrowserEventsClient", {
16
+ readonly events: OtlpEvents["Service"];
17
+ readonly context: (name: string, properties?: EventAttributes) => EventAttributes;
18
+ }>;
19
+ declare class BrowserEventsClient extends BrowserEventsClient_base {
20
+ }
21
+ export declare class BrowserEvents {
22
+ static readonly track: (name: string, properties?: EventAttributes, options?: BrowserEventOptions) => Effect.Effect<void, Schema.SchemaError, never>;
23
+ static readonly page: (options?: BrowserPageOptions) => Effect.Effect<void, Schema.SchemaError, never>;
24
+ /** Requires BrowserOtlp; no identifiers are persisted. */
25
+ static readonly layer: ({ enabled, respectDoNotTrack, pageViews, locale, sanitizePath, }?: BrowserEventsOptions) => Layer.Layer<BrowserEventsClient, never, OtlpEvents>;
26
+ }
@@ -0,0 +1,579 @@
1
+ // ../../src/services/opentelemetry/events.ts
2
+ import {
3
+ Clock,
4
+ Context,
5
+ DateTime,
6
+ Effect,
7
+ Layer,
8
+ Option,
9
+ References,
10
+ Schema as Schema2
11
+ } from "effect";
12
+ import {
13
+ OtlpExporter,
14
+ OtlpResource,
15
+ OtlpSerialization
16
+ } from "effect/observability";
17
+
18
+ // ../../src/services/opentelemetry/schema.ts
19
+ import { Schema } from "effect";
20
+ var BrowserWebVital = Schema.Struct({
21
+ name: Schema.Literals(["LCP", "INP", "CLS", "FCP", "TTFB"]),
22
+ id: Schema.NonEmptyString.check(Schema.isMaxLength(64)),
23
+ value: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
24
+ delta: Schema.Finite,
25
+ rating: Schema.Literals(["good", "needs-improvement", "poor"]),
26
+ navigationType: Schema.Literals([
27
+ "navigate",
28
+ "reload",
29
+ "back-forward",
30
+ "back-forward-cache",
31
+ "prerender",
32
+ "restore"
33
+ ])
34
+ }).annotate({ identifier: "BrowserWebVital" });
35
+ var EventAttributeValue = Schema.Union([
36
+ Schema.String,
37
+ Schema.Finite,
38
+ Schema.Boolean,
39
+ Schema.Array(Schema.String),
40
+ Schema.Array(Schema.Finite),
41
+ Schema.Array(Schema.Boolean)
42
+ ]);
43
+ var EventAttributesSchema = Schema.Record(Schema.String, EventAttributeValue).annotate({ identifier: "EventAttributes" });
44
+ var EventOptionsSchema = Schema.Struct({
45
+ userId: Schema.optional(Schema.NonEmptyString),
46
+ anonymousId: Schema.optional(Schema.NonEmptyString),
47
+ sessionId: Schema.optional(Schema.NonEmptyString),
48
+ messageId: Schema.optional(Schema.NonEmptyString),
49
+ timestamp: Schema.optional(Schema.DateTimeUtc),
50
+ context: Schema.optional(EventAttributesSchema)
51
+ }).annotate({ identifier: "EventOptions" });
52
+ var TelemetryEvent = Schema.Struct({
53
+ name: Schema.NonEmptyString,
54
+ properties: Schema.optional(EventAttributesSchema),
55
+ options: Schema.optional(EventOptionsSchema)
56
+ }).annotate({ identifier: "TelemetryEvent" });
57
+
58
+ // ../../src/services/opentelemetry/events.ts
59
+ class OtlpEvents extends Context.Service()("krakstack/opentelemetry/Events") {
60
+ static disabledLayer = Layer.succeed(this, { push: () => {} });
61
+ static layer = (options) => Layer.effect(this, Effect.gen(function* () {
62
+ const serialization = yield* OtlpSerialization.OtlpSerialization;
63
+ const resource = yield* OtlpResource.fromConfig(options.resource);
64
+ return yield* OtlpExporter.make({
65
+ ...options,
66
+ label: "OtlpEvents",
67
+ body: (logRecords) => {
68
+ const scopes = new Map;
69
+ for (const { scopeName, ...record } of logRecords) {
70
+ const name = scopeName ?? options.scopeName ?? "krakstack.events";
71
+ const records = scopes.get(name);
72
+ if (records)
73
+ records.push(record);
74
+ else
75
+ scopes.set(name, [record]);
76
+ }
77
+ return [
78
+ serialization.logs({
79
+ resourceLogs: [
80
+ {
81
+ resource,
82
+ scopeLogs: Array.from(scopes, ([name, records]) => ({
83
+ scope: { name },
84
+ logRecords: records
85
+ }))
86
+ }
87
+ ]
88
+ }),
89
+ Effect.void
90
+ ];
91
+ }
92
+ });
93
+ }));
94
+ }
95
+ var event = Effect.fnUntraced(function* (name, properties, options) {
96
+ const decoded = yield* Schema2.decodeUnknownEffect(TelemetryEvent)({
97
+ name,
98
+ properties,
99
+ options
100
+ });
101
+ const events = yield* OtlpEvents;
102
+ const clock = yield* Clock.Clock;
103
+ const observedTime = clock.currentTimeNanosUnsafe().toString();
104
+ const timestamp = decoded.options?.timestamp ? (BigInt(DateTime.toEpochMillis(decoded.options.timestamp)) * 1000000n).toString() : observedTime;
105
+ const span = yield* Effect.currentSpan.pipe(Effect.option);
106
+ const attributes = { ...decoded.options?.context, ...decoded.properties };
107
+ if (decoded.options?.userId)
108
+ attributes["user.id"] = decoded.options.userId;
109
+ if (decoded.options?.anonymousId)
110
+ attributes["analytics.anonymous_id"] = decoded.options.anonymousId;
111
+ if (decoded.options?.sessionId)
112
+ attributes["session.id"] = decoded.options.sessionId;
113
+ if (decoded.options?.messageId)
114
+ attributes["log.record.uid"] = decoded.options.messageId;
115
+ const annotations = yield* References.CurrentLogAnnotations;
116
+ events.push({
117
+ eventName: decoded.name,
118
+ timeUnixNano: timestamp,
119
+ observedTimeUnixNano: observedTime,
120
+ severityNumber: 9,
121
+ attributes: OtlpResource.entriesToAttributes(Object.entries({
122
+ ...attributes,
123
+ ...annotations
124
+ })),
125
+ droppedAttributesCount: 0,
126
+ traceId: Option.isSome(span) ? span.value.traceId : undefined,
127
+ spanId: Option.isSome(span) ? span.value.spanId : undefined
128
+ });
129
+ });
130
+
131
+ // ../../src/services/events/browser.ts
132
+ import { Context as Context2, Effect as Effect4, FiberSet, Layer as Layer2, Option as Option4, Schema as Schema5 } from "effect";
133
+
134
+ // ../../src/services/events/schema.ts
135
+ import { Effect as Effect3, Option as Option3, Schema as Schema4 } from "effect";
136
+
137
+ // ../../src/lib/query.ts
138
+ import {
139
+ Effect as Effect2,
140
+ Option as Option2,
141
+ Schema as Schema3,
142
+ SchemaGetter,
143
+ SchemaIssue,
144
+ SchemaTransformation
145
+ } from "effect";
146
+ var parseSortParam = (sort) => {
147
+ const id = sort.startsWith("-") ? sort.slice(1) : sort;
148
+ if (!id || id.includes(",") || id.includes(":")) {
149
+ return null;
150
+ }
151
+ return { id, direction: sort.startsWith("-") ? "desc" : "asc" };
152
+ };
153
+ var SortDirection = Schema3.Union([
154
+ Schema3.Literal("asc"),
155
+ Schema3.Literal("desc")
156
+ ]).pipe(Schema3.annotate({
157
+ identifier: "SortDirection",
158
+ title: "Sort Direction",
159
+ description: "Sort direction for list query results.",
160
+ examples: ["asc", "desc"]
161
+ }));
162
+ var SortParam = Schema3.Struct({
163
+ id: Schema3.NonEmptyString,
164
+ direction: SortDirection
165
+ }).pipe(Schema3.annotate({
166
+ identifier: "SortParam",
167
+ title: "Sort Parameter",
168
+ description: "Decoded sort parameter with a field id and direction.",
169
+ examples: [{ id: "publicName", direction: "asc" }]
170
+ }));
171
+ var SortParamFromString = Schema3.String.pipe(Schema3.decodeTo(SortParam, SchemaTransformation.transformEffect({
172
+ decode: (sort) => {
173
+ const sortParam = parseSortParam(sort);
174
+ if (!sortParam) {
175
+ return Effect2.fail(new SchemaIssue.InvalidValue({ message: 'Expected sort in the format "field" or "-field"' }, sort));
176
+ }
177
+ return Effect2.succeed(sortParam);
178
+ },
179
+ encode: (sort) => Effect2.succeed(sort.direction === "desc" ? `-${sort.id}` : sort.id)
180
+ })), Schema3.annotate({
181
+ identifier: "SortParamFromString",
182
+ title: "Sort Parameter From String",
183
+ description: 'URL encoded single sort parameter where descending fields are prefixed with "-".',
184
+ examples: [{ id: "publicName", direction: "asc" }]
185
+ }));
186
+ var SortParamsFromString = Schema3.String.pipe(Schema3.decodeTo(Schema3.Array(SortParam), SchemaTransformation.transformEffect({
187
+ decode: (sort) => {
188
+ if (sort === "")
189
+ return Effect2.succeed([]);
190
+ const parts = sort.split(",");
191
+ const sortParams = [];
192
+ for (const part of parts) {
193
+ const sortParam = parseSortParam(part);
194
+ if (!sortParam) {
195
+ return Effect2.fail(new SchemaIssue.InvalidValue({ message: 'Expected sort in the format "field,-otherField"' }, sort));
196
+ }
197
+ sortParams.push(sortParam);
198
+ }
199
+ return Effect2.succeed(sortParams);
200
+ },
201
+ encode: (sort) => Effect2.succeed(sort.map((part) => Schema3.encodeSync(SortParamFromString)(part)).join(","))
202
+ })), Schema3.annotate({
203
+ identifier: "SortParamsFromString",
204
+ title: "Sort Parameters From String",
205
+ description: 'URL encoded sort parameters where descending fields are prefixed with "-" and multiple fields are comma-separated.',
206
+ examples: [
207
+ [
208
+ { id: "name", direction: "desc" },
209
+ { id: "age", direction: "asc" }
210
+ ]
211
+ ]
212
+ }));
213
+ var SortParamsArray = Schema3.Array(SortParam);
214
+ var SortParams = Schema3.declare(Schema3.is(SortParamsArray), {
215
+ identifier: "SortParams",
216
+ toCodec: () => Schema3.link()(SortParamsArray, SchemaTransformation.passthrough()),
217
+ toCodecStringTree: () => Schema3.link()(SortParamsFromString, SchemaTransformation.passthrough())
218
+ });
219
+ var Query = Schema3.Struct({
220
+ page: Schema3.optional(Schema3.Union([Schema3.Number, Schema3.NumberFromString]).check(Schema3.isInt(), Schema3.isGreaterThanOrEqualTo(0))).pipe(Schema3.decodeTo(Schema3.Int.check(Schema3.isGreaterThanOrEqualTo(0)), {
221
+ decode: SchemaGetter.withDefault(Effect2.succeed(0)),
222
+ encode: SchemaGetter.transformOptional(Option2.filter((page) => page !== 0))
223
+ })),
224
+ pageSize: Schema3.optional(Schema3.Union([Schema3.Number, Schema3.NumberFromString]).check(Schema3.isInt(), Schema3.isBetween({ minimum: 1, maximum: 100 }))).pipe(Schema3.decodeTo(Schema3.Int.check(Schema3.isBetween({ minimum: 1, maximum: 100 })), {
225
+ decode: SchemaGetter.withDefault(Effect2.succeed(20)),
226
+ encode: SchemaGetter.transformOptional(Option2.filter((pageSize) => pageSize !== 20))
227
+ })),
228
+ globalFilter: Schema3.optional(Schema3.String),
229
+ sort: Schema3.optional(SortParams)
230
+ }).annotate({
231
+ identifier: "Query",
232
+ title: "Query",
233
+ description: "Zero-based page request parameters with optional filtering and sorting for list endpoints.",
234
+ examples: [
235
+ {
236
+ page: 0,
237
+ pageSize: 20,
238
+ globalFilter: "housing",
239
+ sort: [
240
+ { id: "publicName", direction: "desc" },
241
+ { id: "createdAt", direction: "asc" }
242
+ ]
243
+ }
244
+ ]
245
+ });
246
+ var QueryStandard = Schema3.toStandardSchemaV1(Query);
247
+ var PaginationMeta = Schema3.Struct({
248
+ page: Schema3.Int,
249
+ pageSize: Schema3.Int,
250
+ total: Schema3.Int,
251
+ pageCount: Schema3.Int
252
+ }).pipe(Schema3.annotate({
253
+ identifier: "PaginationMeta",
254
+ title: "Pagination Metadata",
255
+ description: "Pagination metadata returned with a paginated list response.",
256
+ examples: [{ page: 0, pageSize: 20, total: 125, pageCount: 7 }]
257
+ }));
258
+
259
+ // ../../src/services/events/schema.ts
260
+ var EventUuid = Schema4.String.check(Schema4.isUUID());
261
+ var EventId = Schema4.NonEmptyString.check(Schema4.isMaxLength(100));
262
+ var BrowserEventPath = Schema4.String.check(Schema4.isMaxLength(2048), Schema4.isPattern(/^\/(?!\/)[^?#]*$/));
263
+ var EventIdentity = Schema4.Struct({
264
+ userId: Schema4.optional(Schema4.NonEmptyString),
265
+ organizationId: Schema4.optional(Schema4.NonEmptyString)
266
+ }).annotate({ identifier: "EventIdentity" });
267
+ var EventIpAddress = Schema4.String.check(Schema4.makeFilter((value) => Option3.isSome(Schema4.decodeUnknownOption(Schema4.IpAddressFromString)(value)) || "Invalid IP address")).annotate({ identifier: "EventIpAddress" });
268
+ var EventCountry = Schema4.String.check(Schema4.isPattern(/^[A-Z]{2}$/), Schema4.makeFilter((value) => !["XX", "T1"].includes(value) || "Unknown country")).annotate({ identifier: "EventCountry" });
269
+ var EventRegion = Schema4.String.check(Schema4.isPattern(/^[A-Z0-9]{1,3}$/)).annotate({ identifier: "EventRegion" });
270
+ var EventCity = Schema4.NonEmptyString.check(Schema4.isMaxLength(128)).annotate({ identifier: "EventCity" });
271
+ var EventGeolocation = Schema4.Struct({
272
+ ip: Schema4.optional(EventIpAddress),
273
+ country: Schema4.optional(EventCountry),
274
+ region: Schema4.optional(EventRegion),
275
+ city: Schema4.optional(EventCity)
276
+ }).annotate({ identifier: "EventGeolocation" });
277
+
278
+ class EventGeolocationError extends Schema4.TaggedError()("EventGeolocationError", {}) {
279
+ }
280
+ var BrowserEventOptions = Schema4.Struct({
281
+ messageId: Schema4.optional(EventId),
282
+ timestamp: Schema4.optional(Schema4.DateTimeUtc),
283
+ context: Schema4.optional(EventAttributesSchema)
284
+ }).annotate({ identifier: "BrowserEventOptions" });
285
+ var BrowserPage = Schema4.Struct({
286
+ name: Schema4.optional(Schema4.NonEmptyString),
287
+ category: Schema4.optional(Schema4.NonEmptyString),
288
+ path: Schema4.optional(Schema4.NonEmptyString),
289
+ properties: Schema4.optional(EventAttributesSchema),
290
+ options: Schema4.optional(BrowserEventOptions)
291
+ }).annotate({ identifier: "BrowserPage" });
292
+ var AuditTarget = Schema4.Struct({
293
+ id: Schema4.NonEmptyString.check(Schema4.isMaxLength(256)),
294
+ name: Schema4.NonEmptyString.check(Schema4.isMaxLength(2048)),
295
+ type: Schema4.NonEmptyString.check(Schema4.isMaxLength(128))
296
+ }).annotate({ identifier: "AuditTarget" });
297
+ var trackEventFields = {
298
+ eventId: Schema4.optional(EventId),
299
+ name: Schema4.NonEmptyString.check(Schema4.isMaxLength(128)),
300
+ properties: Schema4.optional(EventAttributesSchema),
301
+ identity: Schema4.optional(EventIdentity),
302
+ timestamp: Schema4.optional(Schema4.DateTimeUtc)
303
+ };
304
+ var TrackEvent = Schema4.Union([
305
+ Schema4.Struct({
306
+ ...trackEventFields,
307
+ category: Schema4.optional(Schema4.Literal("analytics"))
308
+ }),
309
+ Schema4.Struct({
310
+ ...trackEventFields,
311
+ category: Schema4.Literal("audit"),
312
+ target: AuditTarget
313
+ })
314
+ ]).annotate({ identifier: "TrackEvent" });
315
+ var ListAudit = Schema4.Struct({
316
+ organizationId: Schema4.NonEmptyString,
317
+ ...Query.fields
318
+ }).annotate({ identifier: "ListAudit" });
319
+ var AuditSortId = Schema4.Literals([
320
+ "time",
321
+ "eventName",
322
+ "recordType",
323
+ "record",
324
+ "actorType",
325
+ "actorId"
326
+ ]).annotate({ identifier: "AuditSortId" });
327
+ var AuditCount = Schema4.Struct({ total: Schema4.Int }).annotate({
328
+ identifier: "AuditCount"
329
+ });
330
+ var AuditAttribution = Schema4.Struct({
331
+ "app.actor.type": Schema4.NonEmptyString,
332
+ "app.actor.id": Schema4.NonEmptyString
333
+ }).annotate({ identifier: "AuditAttribution" });
334
+ var RequestActorAttribution = Schema4.Struct({
335
+ ...AuditAttribution.fields,
336
+ "app.auth.method": Schema4.optional(Schema4.NonEmptyString),
337
+ "app.auth.credential.id": Schema4.optional(Schema4.NonEmptyString),
338
+ "app.auth.impersonator.id": Schema4.optional(Schema4.NonEmptyString),
339
+ "user.roles": Schema4.optional(Schema4.Array(Schema4.String))
340
+ }).annotate({ identifier: "RequestActorAttribution" });
341
+
342
+ class EventsPersistenceError extends Schema4.TaggedError()("EventsPersistenceError", { operation: Schema4.String }) {
343
+ }
344
+
345
+ class EventConflictError extends Schema4.TaggedError()("EventConflictError", { eventId: EventId }) {
346
+ }
347
+ var EventSource = Schema4.Literals(["browser", "server"]).annotate({
348
+ identifier: "EventSource"
349
+ });
350
+ var ExistingEventRequest = Schema4.Struct({
351
+ eventId: EventId,
352
+ source: EventSource
353
+ }).annotate({ identifier: "ExistingEventRequest" });
354
+ var StoredEventRequest = Schema4.Struct({
355
+ source: EventSource,
356
+ event_id: EventId,
357
+ event_name: Schema4.NonEmptyString,
358
+ event_type: Schema4.Literals(["page", "track"]),
359
+ occurred_at: Schema4.Finite,
360
+ received_at: Schema4.Finite,
361
+ organization_id: Schema4.NullOr(Schema4.NonEmptyString),
362
+ user_id: Schema4.NullOr(Schema4.NonEmptyString),
363
+ session_id: Schema4.NullOr(Schema4.NonEmptyString),
364
+ anonymous_id: Schema4.NullOr(Schema4.NonEmptyString),
365
+ payload_json: Schema4.String
366
+ }).annotate({ identifier: "StoredEventRequest" });
367
+ var StoredEventId = Schema4.Struct({
368
+ event_id: EventId
369
+ }).annotate({ identifier: "StoredEventId" });
370
+ var PrimitiveValue = Schema4.Union([
371
+ Schema4.Struct({ stringValue: Schema4.String.check(Schema4.isMaxLength(2048)) }),
372
+ Schema4.Struct({
373
+ intValue: Schema4.Union([
374
+ Schema4.String.check(Schema4.isPattern(/^-?\d{1,20}$/)),
375
+ Schema4.Int
376
+ ])
377
+ }),
378
+ Schema4.Struct({ doubleValue: Schema4.Finite }),
379
+ Schema4.Struct({ boolValue: Schema4.Boolean })
380
+ ]);
381
+ var AttributeValue = Schema4.Union([
382
+ PrimitiveValue,
383
+ Schema4.Struct({
384
+ arrayValue: Schema4.Struct({
385
+ values: Schema4.Array(PrimitiveValue).check(Schema4.isMaxLength(32))
386
+ })
387
+ })
388
+ ]);
389
+ var EventAttribute = Schema4.Struct({
390
+ key: Schema4.NonEmptyString.check(Schema4.isMaxLength(128)),
391
+ value: AttributeValue
392
+ }).annotate({ identifier: "EventAttribute" });
393
+ var EventLogRecord = Schema4.Struct({
394
+ eventName: Schema4.NonEmptyString.check(Schema4.isMaxLength(128), Schema4.isPattern(/^[^\r\n]+$/)),
395
+ timeUnixNano: Schema4.String.check(Schema4.isPattern(/^\d{1,20}$/)),
396
+ observedTimeUnixNano: Schema4.optional(Schema4.String.check(Schema4.isPattern(/^\d{1,20}$/))),
397
+ severityNumber: Schema4.optional(Schema4.Int),
398
+ traceId: Schema4.optional(Schema4.String.check(Schema4.isPattern(/^[a-f0-9]{32}$/))),
399
+ spanId: Schema4.optional(Schema4.String.check(Schema4.isPattern(/^[a-f0-9]{16}$/))),
400
+ attributes: Schema4.Array(EventAttribute).check(Schema4.isMaxLength(64), Schema4.makeFilter((values) => new Set(values.map(({ key }) => key)).size === values.length || "Duplicate attribute keys"))
401
+ }).annotate({ identifier: "EventLogRecord" });
402
+ var extensions = Schema4.Record(Schema4.String, Schema4.Unknown);
403
+ var OtlpLogs = Schema4.StructWithRest(Schema4.Struct({
404
+ resourceLogs: Schema4.Array(Schema4.StructWithRest(Schema4.Struct({
405
+ scopeLogs: Schema4.Array(Schema4.StructWithRest(Schema4.Struct({
406
+ scope: Schema4.optional(Schema4.StructWithRest(Schema4.Struct({ name: Schema4.optional(Schema4.String) }), [extensions])),
407
+ logRecords: Schema4.Array(Schema4.Unknown).pipe(Schema4.withDecodingDefaultKey(Effect3.succeed([])))
408
+ }), [extensions])).pipe(Schema4.withDecodingDefaultKey(Effect3.succeed([])))
409
+ }), [extensions])).pipe(Schema4.withDecodingDefaultKey(Effect3.succeed([])))
410
+ }), [extensions]).annotate({ identifier: "EventsOtlpLogs" });
411
+ var StoredEventPayload = Schema4.Struct({
412
+ payload_json: Schema4.Union([OtlpLogs, Schema4.fromJsonString(OtlpLogs)])
413
+ }).annotate({ identifier: "StoredEventPayload" });
414
+ var VisitorEventsRequest = Schema4.Struct({
415
+ visitorId: Schema4.NonEmptyString
416
+ }).annotate({ identifier: "VisitorEventsRequest" });
417
+ var VisitorEventSession = Schema4.Struct({
418
+ event_id: EventId,
419
+ session_id: Schema4.NullOr(Schema4.NonEmptyString),
420
+ received_at: Schema4.Finite
421
+ }).annotate({ identifier: "VisitorEventSession" });
422
+
423
+ // ../../src/services/events/browser.ts
424
+ var eventProperties = (properties) => Object.fromEntries(Object.entries(properties ?? {}).map(([key, value]) => [
425
+ key.startsWith("app.") ? key : `app.${key}`,
426
+ value
427
+ ]));
428
+
429
+ class BrowserEventsClient extends Context2.Service()("krakstack/events/BrowserEventsClient") {
430
+ }
431
+ var emit = Effect4.fnUntraced(function* (name, properties, options) {
432
+ const client = yield* BrowserEventsClient;
433
+ const decoded = yield* Schema5.decodeUnknownEffect(BrowserEventOptions)(options ?? {});
434
+ yield* event(name, { ...properties, ...client.context(name, properties) }, decoded).pipe(Effect4.provideService(OtlpEvents, client.events));
435
+ });
436
+ var page = Effect4.fnUntraced(function* (input = {}) {
437
+ const decoded = yield* Schema5.decodeUnknownEffect(BrowserPage)(input);
438
+ const properties = eventProperties(decoded.properties);
439
+ if (decoded.name)
440
+ properties["analytics.page.name"] = decoded.name;
441
+ if (decoded.category)
442
+ properties["analytics.page.category"] = decoded.category;
443
+ properties["url.path"] = (decoded.path ?? location.pathname).split(/[?#]/, 1)[0] ?? "/";
444
+ yield* emit("browser.page_view", properties, decoded.options);
445
+ });
446
+ var clients = [];
447
+ var runBrowser = (program) => Effect4.suspend(() => {
448
+ const client = clients.at(-1);
449
+ return client ? program.pipe(Effect4.provideService(BrowserEventsClient, client)) : Effect4.void;
450
+ });
451
+ var BrowserClientLive = Layer2.effectDiscard(Effect4.gen(function* () {
452
+ const client = yield* BrowserEventsClient;
453
+ yield* Effect4.acquireRelease(Effect4.sync(() => {
454
+ clients.push(client);
455
+ return client;
456
+ }), (client) => Effect4.sync(() => {
457
+ const index = clients.indexOf(client);
458
+ if (index !== -1)
459
+ clients.splice(index, 1);
460
+ }));
461
+ }));
462
+ var pageViewListeners = new Set;
463
+ var stopPageViewTracking;
464
+ var subscribePageViews = (listener) => {
465
+ if (pageViewListeners.size === 0) {
466
+ const pushState = history.pushState;
467
+ const replaceState = history.replaceState;
468
+ const notify = () => {
469
+ for (const onPage of pageViewListeners)
470
+ onPage();
471
+ };
472
+ const trackedPushState = (...args) => {
473
+ pushState.apply(history, args);
474
+ notify();
475
+ };
476
+ const trackedReplaceState = (...args) => {
477
+ replaceState.apply(history, args);
478
+ notify();
479
+ };
480
+ history.pushState = trackedPushState;
481
+ history.replaceState = trackedReplaceState;
482
+ globalThis.addEventListener("popstate", notify);
483
+ stopPageViewTracking = () => {
484
+ globalThis.removeEventListener("popstate", notify);
485
+ if (history.pushState === trackedPushState)
486
+ history.pushState = pushState;
487
+ if (history.replaceState === trackedReplaceState)
488
+ history.replaceState = replaceState;
489
+ };
490
+ }
491
+ pageViewListeners.add(listener);
492
+ return () => {
493
+ pageViewListeners.delete(listener);
494
+ if (pageViewListeners.size === 0) {
495
+ stopPageViewTracking?.();
496
+ stopPageViewTracking = undefined;
497
+ }
498
+ };
499
+ };
500
+ var BrowserPageViewsLive = Layer2.effectDiscard(Effect4.gen(function* () {
501
+ const fibers = yield* FiberSet.make();
502
+ const run = yield* FiberSet.runtime(fibers)();
503
+ let previousPath = location.pathname;
504
+ yield* Effect4.acquireRelease(Effect4.sync(() => subscribePageViews(() => {
505
+ const path = location.pathname;
506
+ if (path === previousPath)
507
+ return;
508
+ previousPath = path;
509
+ run(page({ path }).pipe(Effect4.ignore));
510
+ })), (unsubscribe) => Effect4.sync(unsubscribe));
511
+ yield* page({ path: previousPath }).pipe(Effect4.ignore);
512
+ }));
513
+
514
+ class BrowserEvents {
515
+ static track = (name, properties, options) => runBrowser(emit(name, eventProperties(properties), options));
516
+ static page = (options) => runBrowser(page(options));
517
+ static layer = ({
518
+ enabled = true,
519
+ respectDoNotTrack = true,
520
+ pageViews = true,
521
+ locale,
522
+ sanitizePath
523
+ } = {}) => {
524
+ const privacy = Schema5.decodeUnknownSync(Schema5.Struct({ globalPrivacyControl: Schema5.optional(Schema5.Boolean) }))(navigator);
525
+ const disabled = !enabled || respectDoNotTrack && (navigator.doNotTrack === "1" || navigator.doNotTrack === "yes" || privacy.globalPrivacyControl === true);
526
+ let previousPath;
527
+ let pageViewId = crypto.randomUUID();
528
+ const context = (name, properties) => {
529
+ const explicitPath = Schema5.decodeUnknownOption(Schema5.String)(properties?.["url.path"]);
530
+ const path = Option4.getOrElse(explicitPath, () => location.pathname);
531
+ if (location.pathname !== previousPath || name === "browser.page_view") {
532
+ previousPath = location.pathname;
533
+ pageViewId = crypto.randomUUID();
534
+ }
535
+ const attributes = {
536
+ "app.event.schema.version": "1",
537
+ "analytics.page_view.id": pageViewId,
538
+ "log.record.uid": crypto.randomUUID(),
539
+ "url.path": sanitizePath?.(path) ?? path,
540
+ "browser.language": navigator.language.slice(0, 256)
541
+ };
542
+ const optional = {};
543
+ if (locale)
544
+ optional["analytics.locale"] = locale();
545
+ if (document.referrer) {
546
+ const referrer = URL.parse(document.referrer);
547
+ if (referrer && referrer.hostname !== location.hostname)
548
+ optional["url.referrer"] = referrer.hostname;
549
+ }
550
+ const search = new URLSearchParams(location.search);
551
+ for (const key of ["source", "medium", "campaign", "content", "term"]) {
552
+ const value = search.get(`utm_${key}`);
553
+ if (value)
554
+ optional[`utm.${key}`] = value.slice(0, 256);
555
+ }
556
+ return { ...attributes, ...optional };
557
+ };
558
+ const client = Layer2.effect(BrowserEventsClient, Effect4.gen(function* () {
559
+ const exporter = yield* OtlpEvents;
560
+ return {
561
+ events: {
562
+ push: (record) => {
563
+ if (!disabled)
564
+ exporter.push({
565
+ ...record,
566
+ scopeName: "krakstack.application.events"
567
+ });
568
+ }
569
+ },
570
+ context: disabled ? () => ({}) : context
571
+ };
572
+ }));
573
+ const browser = Layer2.mergeAll(BrowserClientLive, !disabled && pageViews ? BrowserPageViewsLive : Layer2.empty).pipe(Layer2.provideMerge(client));
574
+ return browser;
575
+ };
576
+ }
577
+ export {
578
+ BrowserEvents
579
+ };
@@ -0,0 +1,53 @@
1
+ import type { ReactNode } from "react";
2
+ import { type DataTableProps, type DataTableStatus, type DataTableReferenceItem } from "../../../components/ui/data-table.js";
3
+ import type { EventLogRecord } from "../schema.js";
4
+ declare const translations: {
5
+ en: {
6
+ title: string;
7
+ time: string;
8
+ action: string;
9
+ target: string;
10
+ actor: string;
11
+ method: string;
12
+ actorMember: string;
13
+ impersonatedBy: string;
14
+ actorOrganization: string;
15
+ methodApiKey: string;
16
+ methodSession: string;
17
+ methodUnknown: string;
18
+ };
19
+ fr: {
20
+ title: string;
21
+ time: string;
22
+ action: string;
23
+ target: string;
24
+ actor: string;
25
+ method: string;
26
+ actorMember: string;
27
+ impersonatedBy: string;
28
+ actorOrganization: string;
29
+ methodApiKey: string;
30
+ methodSession: string;
31
+ methodUnknown: string;
32
+ };
33
+ };
34
+ export type AuditLogMessages = typeof translations.en;
35
+ export type AuditActor = DataTableReferenceItem & {
36
+ type: "user" | "organization";
37
+ id: string;
38
+ };
39
+ export type AuditLogTableProps = DataTableStatus & Pick<DataTableProps<EventLogRecord>, "state" | "onStateChange"> & {
40
+ entries: readonly EventLogRecord[];
41
+ /** Total matching records from the query response; paging lives in state. */
42
+ rowCount: number;
43
+ /** Overrides the shared KrakstackProvider locale when supplied. */
44
+ locale?: string;
45
+ messages?: Readonly<Record<string, Partial<AuditLogMessages>>>;
46
+ /** Current profiles the viewer may access. Matched by type and ID, including user impersonators.
47
+ * Missing profiles use neutral labels: the list may be loading, incomplete, or unavailable.
48
+ */
49
+ actors?: readonly AuditActor[];
50
+ renderAction?: (entry: EventLogRecord) => ReactNode;
51
+ };
52
+ export declare const AuditLogTable: ({ entries, rowCount, locale: localeOverride, messages, actors, renderAction, state, onStateChange, ...status }: AuditLogTableProps) => import("react").JSX.Element;
53
+ export {};