@krak-stack/registry 0.1.50 → 0.1.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +16 -424
- package/dist/lib/docs.js +2 -2
- package/dist/services/agent/client/index.js +1 -1
- package/dist/services/events/browser.d.ts +26 -0
- package/dist/services/events/browser.js +423 -0
- package/dist/services/events/index.d.ts +82 -0
- package/dist/services/events/index.js +798 -0
- package/dist/services/events/migrations.d.ts +4 -0
- package/dist/services/events/migrations.js +42 -0
- package/dist/services/events/request-context.d.ts +6 -0
- package/dist/services/events/schema.d.ts +196 -0
- package/dist/services/opentelemetry/api.d.ts +3 -1
- package/dist/services/opentelemetry/api.js +133 -64
- package/dist/services/opentelemetry/browser.d.ts +17 -20
- package/dist/services/opentelemetry/browser.js +58 -162
- package/dist/services/opentelemetry/events.d.ts +3 -1
- package/dist/services/opentelemetry/{server.d.ts → index.d.ts} +8 -5
- package/dist/services/opentelemetry/{server.js → index.js} +66 -48
- package/dist/services/opentelemetry/processor.d.ts +19 -0
- package/dist/services/opentelemetry/schema.d.ts +8 -20
- package/dist/services/opentelemetry/web-vitals.d.ts +15 -0
- package/dist/services/opentelemetry/web-vitals.js +229 -0
- package/package.json +23 -5
|
@@ -0,0 +1,423 @@
|
|
|
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 Effect3, FiberSet, Layer as Layer2, Option as Option3, Schema as Schema4 } from "effect";
|
|
133
|
+
|
|
134
|
+
// ../../src/services/events/schema.ts
|
|
135
|
+
import { Effect as Effect2, Option as Option2, Schema as Schema3 } from "effect";
|
|
136
|
+
var EventUuid = Schema3.String.check(Schema3.isUUID());
|
|
137
|
+
var EventId = Schema3.NonEmptyString.check(Schema3.isMaxLength(100));
|
|
138
|
+
var BrowserEventPath = Schema3.String.check(Schema3.isMaxLength(2048), Schema3.isPattern(/^\/(?!\/)[^?#]*$/));
|
|
139
|
+
var EventIdentity = Schema3.Struct({
|
|
140
|
+
userId: Schema3.optional(Schema3.NonEmptyString),
|
|
141
|
+
organizationId: Schema3.optional(Schema3.NonEmptyString)
|
|
142
|
+
}).annotate({ identifier: "EventIdentity" });
|
|
143
|
+
var EventIpAddress = Schema3.String.check(Schema3.makeFilter((value) => Option2.isSome(Schema3.decodeUnknownOption(Schema3.IpAddressFromString)(value)) || "Invalid IP address")).annotate({ identifier: "EventIpAddress" });
|
|
144
|
+
var EventCountry = Schema3.String.check(Schema3.isPattern(/^[A-Z]{2}$/), Schema3.makeFilter((value) => !["XX", "T1"].includes(value) || "Unknown country")).annotate({ identifier: "EventCountry" });
|
|
145
|
+
var EventRegion = Schema3.String.check(Schema3.isPattern(/^[A-Z0-9]{1,3}$/)).annotate({ identifier: "EventRegion" });
|
|
146
|
+
var EventCity = Schema3.NonEmptyString.check(Schema3.isMaxLength(128)).annotate({ identifier: "EventCity" });
|
|
147
|
+
var EventGeolocation = Schema3.Struct({
|
|
148
|
+
ip: Schema3.optional(EventIpAddress),
|
|
149
|
+
country: Schema3.optional(EventCountry),
|
|
150
|
+
region: Schema3.optional(EventRegion),
|
|
151
|
+
city: Schema3.optional(EventCity)
|
|
152
|
+
}).annotate({ identifier: "EventGeolocation" });
|
|
153
|
+
|
|
154
|
+
class EventGeolocationError extends Schema3.TaggedError()("EventGeolocationError", {}) {
|
|
155
|
+
}
|
|
156
|
+
var BrowserEventOptions = Schema3.Struct({
|
|
157
|
+
messageId: Schema3.optional(EventId),
|
|
158
|
+
timestamp: Schema3.optional(Schema3.DateTimeUtc),
|
|
159
|
+
context: Schema3.optional(EventAttributesSchema)
|
|
160
|
+
}).annotate({ identifier: "BrowserEventOptions" });
|
|
161
|
+
var BrowserPage = Schema3.Struct({
|
|
162
|
+
name: Schema3.optional(Schema3.NonEmptyString),
|
|
163
|
+
category: Schema3.optional(Schema3.NonEmptyString),
|
|
164
|
+
path: Schema3.optional(Schema3.NonEmptyString),
|
|
165
|
+
properties: Schema3.optional(EventAttributesSchema),
|
|
166
|
+
options: Schema3.optional(BrowserEventOptions)
|
|
167
|
+
}).annotate({ identifier: "BrowserPage" });
|
|
168
|
+
var TrackEvent = Schema3.Struct({
|
|
169
|
+
eventId: EventId,
|
|
170
|
+
name: Schema3.NonEmptyString.check(Schema3.isMaxLength(128)),
|
|
171
|
+
properties: Schema3.optional(EventAttributesSchema),
|
|
172
|
+
identity: Schema3.optional(EventIdentity),
|
|
173
|
+
timestamp: Schema3.optional(Schema3.DateTimeUtc),
|
|
174
|
+
category: Schema3.optional(Schema3.Literals(["analytics", "audit"]))
|
|
175
|
+
}).annotate({ identifier: "TrackEvent" });
|
|
176
|
+
var AuditAttribution = Schema3.Struct({
|
|
177
|
+
"app.actor.type": Schema3.NonEmptyString,
|
|
178
|
+
"app.actor.id": Schema3.NonEmptyString
|
|
179
|
+
}).annotate({ identifier: "AuditAttribution" });
|
|
180
|
+
var RequestActorAttribution = Schema3.Struct({
|
|
181
|
+
...AuditAttribution.fields,
|
|
182
|
+
"app.actor.owner.type": Schema3.optional(Schema3.NonEmptyString),
|
|
183
|
+
"app.actor.owner.id": Schema3.optional(Schema3.NonEmptyString)
|
|
184
|
+
}).annotate({ identifier: "RequestActorAttribution" });
|
|
185
|
+
|
|
186
|
+
class EventsPersistenceError extends Schema3.TaggedError()("EventsPersistenceError", { operation: Schema3.String }) {
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
class EventConflictError extends Schema3.TaggedError()("EventConflictError", { eventId: EventId }) {
|
|
190
|
+
}
|
|
191
|
+
var EventSource = Schema3.Literals(["browser", "server"]).annotate({
|
|
192
|
+
identifier: "EventSource"
|
|
193
|
+
});
|
|
194
|
+
var ExistingEventRequest = Schema3.Struct({
|
|
195
|
+
eventId: EventId,
|
|
196
|
+
source: EventSource
|
|
197
|
+
}).annotate({ identifier: "ExistingEventRequest" });
|
|
198
|
+
var StoredEventRequest = Schema3.Struct({
|
|
199
|
+
source: EventSource,
|
|
200
|
+
event_id: EventId,
|
|
201
|
+
event_name: Schema3.NonEmptyString,
|
|
202
|
+
event_type: Schema3.Literals(["page", "track"]),
|
|
203
|
+
occurred_at: Schema3.Finite,
|
|
204
|
+
received_at: Schema3.Finite,
|
|
205
|
+
organization_id: Schema3.NullOr(Schema3.NonEmptyString),
|
|
206
|
+
user_id: Schema3.NullOr(Schema3.NonEmptyString),
|
|
207
|
+
session_id: Schema3.NullOr(Schema3.NonEmptyString),
|
|
208
|
+
anonymous_id: Schema3.NullOr(Schema3.NonEmptyString),
|
|
209
|
+
payload_json: Schema3.String
|
|
210
|
+
}).annotate({ identifier: "StoredEventRequest" });
|
|
211
|
+
var StoredEventId = Schema3.Struct({
|
|
212
|
+
event_id: EventId
|
|
213
|
+
}).annotate({ identifier: "StoredEventId" });
|
|
214
|
+
var PrimitiveValue = Schema3.Union([
|
|
215
|
+
Schema3.Struct({ stringValue: Schema3.String.check(Schema3.isMaxLength(2048)) }),
|
|
216
|
+
Schema3.Struct({
|
|
217
|
+
intValue: Schema3.Union([
|
|
218
|
+
Schema3.String.check(Schema3.isPattern(/^-?\d{1,20}$/)),
|
|
219
|
+
Schema3.Int
|
|
220
|
+
])
|
|
221
|
+
}),
|
|
222
|
+
Schema3.Struct({ doubleValue: Schema3.Finite }),
|
|
223
|
+
Schema3.Struct({ boolValue: Schema3.Boolean })
|
|
224
|
+
]);
|
|
225
|
+
var AttributeValue = Schema3.Union([
|
|
226
|
+
PrimitiveValue,
|
|
227
|
+
Schema3.Struct({
|
|
228
|
+
arrayValue: Schema3.Struct({
|
|
229
|
+
values: Schema3.Array(PrimitiveValue).check(Schema3.isMaxLength(32))
|
|
230
|
+
})
|
|
231
|
+
})
|
|
232
|
+
]);
|
|
233
|
+
var EventAttribute = Schema3.Struct({
|
|
234
|
+
key: Schema3.NonEmptyString.check(Schema3.isMaxLength(128)),
|
|
235
|
+
value: AttributeValue
|
|
236
|
+
}).annotate({ identifier: "EventAttribute" });
|
|
237
|
+
var EventLogRecord = Schema3.Struct({
|
|
238
|
+
eventName: Schema3.NonEmptyString.check(Schema3.isMaxLength(128), Schema3.isPattern(/^[^\r\n]+$/)),
|
|
239
|
+
timeUnixNano: Schema3.String.check(Schema3.isPattern(/^\d{1,20}$/)),
|
|
240
|
+
observedTimeUnixNano: Schema3.optional(Schema3.String.check(Schema3.isPattern(/^\d{1,20}$/))),
|
|
241
|
+
severityNumber: Schema3.optional(Schema3.Int),
|
|
242
|
+
traceId: Schema3.optional(Schema3.String.check(Schema3.isPattern(/^[a-f0-9]{32}$/))),
|
|
243
|
+
spanId: Schema3.optional(Schema3.String.check(Schema3.isPattern(/^[a-f0-9]{16}$/))),
|
|
244
|
+
attributes: Schema3.Array(EventAttribute).check(Schema3.isMaxLength(64), Schema3.makeFilter((values) => new Set(values.map(({ key }) => key)).size === values.length || "Duplicate attribute keys"))
|
|
245
|
+
}).annotate({ identifier: "EventLogRecord" });
|
|
246
|
+
var extensions = Schema3.Record(Schema3.String, Schema3.Unknown);
|
|
247
|
+
var OtlpLogs = Schema3.StructWithRest(Schema3.Struct({
|
|
248
|
+
resourceLogs: Schema3.Array(Schema3.StructWithRest(Schema3.Struct({
|
|
249
|
+
scopeLogs: Schema3.Array(Schema3.StructWithRest(Schema3.Struct({
|
|
250
|
+
scope: Schema3.optional(Schema3.StructWithRest(Schema3.Struct({ name: Schema3.optional(Schema3.String) }), [extensions])),
|
|
251
|
+
logRecords: Schema3.Array(Schema3.Unknown).pipe(Schema3.withDecodingDefaultKey(Effect2.succeed([])))
|
|
252
|
+
}), [extensions])).pipe(Schema3.withDecodingDefaultKey(Effect2.succeed([])))
|
|
253
|
+
}), [extensions])).pipe(Schema3.withDecodingDefaultKey(Effect2.succeed([])))
|
|
254
|
+
}), [extensions]).annotate({ identifier: "EventsOtlpLogs" });
|
|
255
|
+
var StoredEventPayload = Schema3.Struct({
|
|
256
|
+
payload_json: Schema3.Union([OtlpLogs, Schema3.fromJsonString(OtlpLogs)])
|
|
257
|
+
}).annotate({ identifier: "StoredEventPayload" });
|
|
258
|
+
var VisitorEventsRequest = Schema3.Struct({
|
|
259
|
+
visitorId: Schema3.NonEmptyString
|
|
260
|
+
}).annotate({ identifier: "VisitorEventsRequest" });
|
|
261
|
+
var VisitorEventSession = Schema3.Struct({
|
|
262
|
+
event_id: EventId,
|
|
263
|
+
session_id: Schema3.NullOr(Schema3.NonEmptyString),
|
|
264
|
+
received_at: Schema3.Finite
|
|
265
|
+
}).annotate({ identifier: "VisitorEventSession" });
|
|
266
|
+
|
|
267
|
+
// ../../src/services/events/browser.ts
|
|
268
|
+
var eventProperties = (properties) => Object.fromEntries(Object.entries(properties ?? {}).map(([key, value]) => [
|
|
269
|
+
key.startsWith("app.") ? key : `app.${key}`,
|
|
270
|
+
value
|
|
271
|
+
]));
|
|
272
|
+
|
|
273
|
+
class BrowserEventsClient extends Context2.Service()("krakstack/events/BrowserEventsClient") {
|
|
274
|
+
}
|
|
275
|
+
var emit = Effect3.fnUntraced(function* (name, properties, options) {
|
|
276
|
+
const client = yield* BrowserEventsClient;
|
|
277
|
+
const decoded = yield* Schema4.decodeUnknownEffect(BrowserEventOptions)(options ?? {});
|
|
278
|
+
yield* event(name, { ...properties, ...client.context(name, properties) }, decoded).pipe(Effect3.provideService(OtlpEvents, client.events));
|
|
279
|
+
});
|
|
280
|
+
var page = Effect3.fnUntraced(function* (input = {}) {
|
|
281
|
+
const decoded = yield* Schema4.decodeUnknownEffect(BrowserPage)(input);
|
|
282
|
+
const properties = eventProperties(decoded.properties);
|
|
283
|
+
if (decoded.name)
|
|
284
|
+
properties["analytics.page.name"] = decoded.name;
|
|
285
|
+
if (decoded.category)
|
|
286
|
+
properties["analytics.page.category"] = decoded.category;
|
|
287
|
+
properties["url.path"] = (decoded.path ?? location.pathname).split(/[?#]/, 1)[0] ?? "/";
|
|
288
|
+
yield* emit("browser.page_view", properties, decoded.options);
|
|
289
|
+
});
|
|
290
|
+
var clients = [];
|
|
291
|
+
var runBrowser = (program) => Effect3.suspend(() => {
|
|
292
|
+
const client = clients.at(-1);
|
|
293
|
+
return client ? program.pipe(Effect3.provideService(BrowserEventsClient, client)) : Effect3.void;
|
|
294
|
+
});
|
|
295
|
+
var BrowserClientLive = Layer2.effectDiscard(Effect3.gen(function* () {
|
|
296
|
+
const client = yield* BrowserEventsClient;
|
|
297
|
+
yield* Effect3.acquireRelease(Effect3.sync(() => {
|
|
298
|
+
clients.push(client);
|
|
299
|
+
return client;
|
|
300
|
+
}), (client) => Effect3.sync(() => {
|
|
301
|
+
const index = clients.indexOf(client);
|
|
302
|
+
if (index !== -1)
|
|
303
|
+
clients.splice(index, 1);
|
|
304
|
+
}));
|
|
305
|
+
}));
|
|
306
|
+
var pageViewListeners = new Set;
|
|
307
|
+
var stopPageViewTracking;
|
|
308
|
+
var subscribePageViews = (listener) => {
|
|
309
|
+
if (pageViewListeners.size === 0) {
|
|
310
|
+
const pushState = history.pushState;
|
|
311
|
+
const replaceState = history.replaceState;
|
|
312
|
+
const notify = () => {
|
|
313
|
+
for (const onPage of pageViewListeners)
|
|
314
|
+
onPage();
|
|
315
|
+
};
|
|
316
|
+
const trackedPushState = (...args) => {
|
|
317
|
+
pushState.apply(history, args);
|
|
318
|
+
notify();
|
|
319
|
+
};
|
|
320
|
+
const trackedReplaceState = (...args) => {
|
|
321
|
+
replaceState.apply(history, args);
|
|
322
|
+
notify();
|
|
323
|
+
};
|
|
324
|
+
history.pushState = trackedPushState;
|
|
325
|
+
history.replaceState = trackedReplaceState;
|
|
326
|
+
globalThis.addEventListener("popstate", notify);
|
|
327
|
+
stopPageViewTracking = () => {
|
|
328
|
+
globalThis.removeEventListener("popstate", notify);
|
|
329
|
+
if (history.pushState === trackedPushState)
|
|
330
|
+
history.pushState = pushState;
|
|
331
|
+
if (history.replaceState === trackedReplaceState)
|
|
332
|
+
history.replaceState = replaceState;
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
pageViewListeners.add(listener);
|
|
336
|
+
return () => {
|
|
337
|
+
pageViewListeners.delete(listener);
|
|
338
|
+
if (pageViewListeners.size === 0) {
|
|
339
|
+
stopPageViewTracking?.();
|
|
340
|
+
stopPageViewTracking = undefined;
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
};
|
|
344
|
+
var BrowserPageViewsLive = Layer2.effectDiscard(Effect3.gen(function* () {
|
|
345
|
+
const fibers = yield* FiberSet.make();
|
|
346
|
+
const run = yield* FiberSet.runtime(fibers)();
|
|
347
|
+
let previousPath = location.pathname;
|
|
348
|
+
yield* Effect3.acquireRelease(Effect3.sync(() => subscribePageViews(() => {
|
|
349
|
+
const path = location.pathname;
|
|
350
|
+
if (path === previousPath)
|
|
351
|
+
return;
|
|
352
|
+
previousPath = path;
|
|
353
|
+
run(page({ path }).pipe(Effect3.ignore));
|
|
354
|
+
})), (unsubscribe) => Effect3.sync(unsubscribe));
|
|
355
|
+
yield* page({ path: previousPath }).pipe(Effect3.ignore);
|
|
356
|
+
}));
|
|
357
|
+
|
|
358
|
+
class BrowserEvents {
|
|
359
|
+
static track = (name, properties, options) => runBrowser(emit(name, eventProperties(properties), options));
|
|
360
|
+
static page = (options) => runBrowser(page(options));
|
|
361
|
+
static layer = ({
|
|
362
|
+
enabled = true,
|
|
363
|
+
respectDoNotTrack = true,
|
|
364
|
+
pageViews = true,
|
|
365
|
+
locale,
|
|
366
|
+
sanitizePath
|
|
367
|
+
} = {}) => {
|
|
368
|
+
const privacy = Schema4.decodeUnknownSync(Schema4.Struct({ globalPrivacyControl: Schema4.optional(Schema4.Boolean) }))(navigator);
|
|
369
|
+
const disabled = !enabled || respectDoNotTrack && (navigator.doNotTrack === "1" || navigator.doNotTrack === "yes" || privacy.globalPrivacyControl === true);
|
|
370
|
+
let previousPath;
|
|
371
|
+
let pageViewId = crypto.randomUUID();
|
|
372
|
+
const context = (name, properties) => {
|
|
373
|
+
const explicitPath = Schema4.decodeUnknownOption(Schema4.String)(properties?.["url.path"]);
|
|
374
|
+
const path = Option3.getOrElse(explicitPath, () => location.pathname);
|
|
375
|
+
if (location.pathname !== previousPath || name === "browser.page_view") {
|
|
376
|
+
previousPath = location.pathname;
|
|
377
|
+
pageViewId = crypto.randomUUID();
|
|
378
|
+
}
|
|
379
|
+
const attributes = {
|
|
380
|
+
"app.event.schema.version": "1",
|
|
381
|
+
"analytics.page_view.id": pageViewId,
|
|
382
|
+
"log.record.uid": crypto.randomUUID(),
|
|
383
|
+
"url.path": sanitizePath?.(path) ?? path,
|
|
384
|
+
"browser.language": navigator.language.slice(0, 256)
|
|
385
|
+
};
|
|
386
|
+
const optional = {};
|
|
387
|
+
if (locale)
|
|
388
|
+
optional["analytics.locale"] = locale();
|
|
389
|
+
if (document.referrer) {
|
|
390
|
+
const referrer = URL.parse(document.referrer);
|
|
391
|
+
if (referrer && referrer.hostname !== location.hostname)
|
|
392
|
+
optional["url.referrer"] = referrer.hostname;
|
|
393
|
+
}
|
|
394
|
+
const search = new URLSearchParams(location.search);
|
|
395
|
+
for (const key of ["source", "medium", "campaign", "content", "term"]) {
|
|
396
|
+
const value = search.get(`utm_${key}`);
|
|
397
|
+
if (value)
|
|
398
|
+
optional[`utm.${key}`] = value.slice(0, 256);
|
|
399
|
+
}
|
|
400
|
+
return { ...attributes, ...optional };
|
|
401
|
+
};
|
|
402
|
+
const client = Layer2.effect(BrowserEventsClient, Effect3.gen(function* () {
|
|
403
|
+
const exporter = yield* OtlpEvents;
|
|
404
|
+
return {
|
|
405
|
+
events: {
|
|
406
|
+
push: (record) => {
|
|
407
|
+
if (!disabled)
|
|
408
|
+
exporter.push({
|
|
409
|
+
...record,
|
|
410
|
+
scopeName: "krakstack.application.events"
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
},
|
|
414
|
+
context: disabled ? () => ({}) : context
|
|
415
|
+
};
|
|
416
|
+
}));
|
|
417
|
+
const browser = Layer2.mergeAll(BrowserClientLive, !disabled && pageViews ? BrowserPageViewsLive : Layer2.empty).pipe(Layer2.provideMerge(client));
|
|
418
|
+
return browser;
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
export {
|
|
422
|
+
BrowserEvents
|
|
423
|
+
};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { Context, DateTime, Effect, Layer, Redacted, Schema } from "effect";
|
|
2
|
+
import { HttpServerRequest } from "effect/http";
|
|
3
|
+
import { OtlpLogsProcessor, OtlpProcessingError } from "../opentelemetry/processor.js";
|
|
4
|
+
import { Otlp } from "../opentelemetry/index.js";
|
|
5
|
+
import { EventIdentity, EventGeolocation, EventConflictError, EventsPersistenceError } from "./schema.js";
|
|
6
|
+
export declare const SESSION_TIMEOUT_MS: number;
|
|
7
|
+
export type { EventGeolocation } from "./schema.js";
|
|
8
|
+
export type EventGeolocationResolver = (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<EventGeolocation | null, unknown>;
|
|
9
|
+
export interface EventsOptions {
|
|
10
|
+
/** Defaults to the server's OTEL_SERVICE_NAME / OTEL_RESOURCE_ATTRIBUTES. */
|
|
11
|
+
readonly serviceName?: string;
|
|
12
|
+
readonly origin: string;
|
|
13
|
+
/** Reuse a stable application secret; never sent to the browser. */
|
|
14
|
+
readonly secret: Redacted.Redacted<string>;
|
|
15
|
+
/** Omit to disable. Cloudflare requires verified ingress with origin-bypass protection. */
|
|
16
|
+
readonly geolocation?: "cloudflare" | EventGeolocationResolver;
|
|
17
|
+
/** Optional fallback for non-annotation auth integrations. Request auth annotations take precedence. */
|
|
18
|
+
readonly identity?: (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<EventIdentity | null, unknown>;
|
|
19
|
+
}
|
|
20
|
+
declare const EventsConfigurationError_base: Schema.Class<EventsConfigurationError, Schema.TaggedStruct<"EventsConfigurationError", {
|
|
21
|
+
readonly message: Schema.String;
|
|
22
|
+
}>, import("effect/Cause").YieldableError>;
|
|
23
|
+
export declare class EventsConfigurationError extends EventsConfigurationError_base {
|
|
24
|
+
}
|
|
25
|
+
export declare const dailyVisitorId: (input: {
|
|
26
|
+
readonly serviceName: string;
|
|
27
|
+
readonly ip: string;
|
|
28
|
+
readonly userAgent: string;
|
|
29
|
+
readonly day: string;
|
|
30
|
+
readonly secret: Redacted.Redacted<string>;
|
|
31
|
+
}) => string;
|
|
32
|
+
declare const Events_base: Context.ServiceClass<Events, "krakstack/events/Events", {
|
|
33
|
+
process: (body: Uint8Array<ArrayBufferLike>) => Effect.Effect<{
|
|
34
|
+
body: Uint8Array<ArrayBufferLike>;
|
|
35
|
+
persisted: boolean;
|
|
36
|
+
}, OtlpProcessingError, HttpServerRequest.HttpServerRequest>;
|
|
37
|
+
track: (input: {
|
|
38
|
+
readonly eventId: string;
|
|
39
|
+
readonly name: string;
|
|
40
|
+
readonly properties?: {
|
|
41
|
+
readonly [x: string]: string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
|
|
42
|
+
} | undefined;
|
|
43
|
+
readonly identity?: {
|
|
44
|
+
readonly userId?: string | undefined;
|
|
45
|
+
readonly organizationId?: string | undefined;
|
|
46
|
+
} | undefined;
|
|
47
|
+
readonly timestamp?: DateTime.Utc | undefined;
|
|
48
|
+
readonly category?: "analytics" | "audit" | undefined;
|
|
49
|
+
}) => Effect.Effect<{
|
|
50
|
+
eventId: string;
|
|
51
|
+
inserted: boolean;
|
|
52
|
+
}, EventConflictError | EventsPersistenceError | Schema.SchemaError, never>;
|
|
53
|
+
}> & {
|
|
54
|
+
readonly make: (options: EventsOptions) => Effect.Effect<{
|
|
55
|
+
process: (body: Uint8Array<ArrayBufferLike>) => Effect.Effect<{
|
|
56
|
+
body: Uint8Array<ArrayBufferLike>;
|
|
57
|
+
persisted: boolean;
|
|
58
|
+
}, OtlpProcessingError, HttpServerRequest.HttpServerRequest>;
|
|
59
|
+
track: (input: {
|
|
60
|
+
readonly eventId: string;
|
|
61
|
+
readonly name: string;
|
|
62
|
+
readonly properties?: {
|
|
63
|
+
readonly [x: string]: string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
|
|
64
|
+
} | undefined;
|
|
65
|
+
readonly identity?: {
|
|
66
|
+
readonly userId?: string | undefined;
|
|
67
|
+
readonly organizationId?: string | undefined;
|
|
68
|
+
} | undefined;
|
|
69
|
+
readonly timestamp?: DateTime.Utc | undefined;
|
|
70
|
+
readonly category?: "analytics" | "audit" | undefined;
|
|
71
|
+
}) => Effect.Effect<{
|
|
72
|
+
eventId: string;
|
|
73
|
+
inserted: boolean;
|
|
74
|
+
}, EventConflictError | EventsPersistenceError | Schema.SchemaError, never>;
|
|
75
|
+
}, EventsConfigurationError, Otlp>;
|
|
76
|
+
};
|
|
77
|
+
export declare class Events extends Events_base {
|
|
78
|
+
static readonly baseLayer: (options: EventsOptions) => Layer.Layer<Events, EventsConfigurationError, Otlp>;
|
|
79
|
+
/** An injected PostgreSQL/SQLite SqlClient enables persistence and the initial migration. */
|
|
80
|
+
static readonly layer: (options: EventsOptions) => Layer.Layer<Events, EventsConfigurationError | import("effect/sql/Migrator").MigrationError | import("effect/sql/SqlError").SqlError, Otlp>;
|
|
81
|
+
static readonly ingestionLayer: Layer.Layer<OtlpLogsProcessor, never, Events>;
|
|
82
|
+
}
|