@krak-stack/registry 0.1.58 → 0.1.60

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 (41) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/README.md +3 -0
  3. package/dist/components/ui/data-table.d.ts +2 -0
  4. package/dist/components/ui/data-table.js +6 -2
  5. package/dist/components/ui/item.d.ts +22 -0
  6. package/dist/components/ui/trace.d.ts +18 -0
  7. package/dist/services/agent/client/index.js +584 -434
  8. package/dist/services/agent/client/widget.d.ts +1 -0
  9. package/dist/services/events/browser.js +29 -3
  10. package/dist/services/events/client/audit-log-table.js +6 -2
  11. package/dist/services/events/client/tracking-notice.js +2 -1
  12. package/dist/services/events/index.d.ts +26 -56
  13. package/dist/services/events/index.js +118 -7
  14. package/dist/services/events/schema.d.ts +66 -24
  15. package/dist/services/events/schema.js +34 -3
  16. package/dist/services/opentelemetry/api.js +2 -1
  17. package/dist/services/opentelemetry/browser.d.ts +1 -1
  18. package/dist/services/opentelemetry/browser.js +2 -1
  19. package/dist/services/opentelemetry/events.d.ts +1 -1
  20. package/dist/services/opentelemetry/index.d.ts +1 -1
  21. package/dist/services/opentelemetry/index.js +2 -1
  22. package/dist/services/opentelemetry/schema.d.ts +3 -1
  23. package/dist/services/opentelemetry/web-vitals.js +2 -1
  24. package/dist/services/speech/api.d.ts +13 -0
  25. package/dist/services/speech/api.js +60 -0
  26. package/dist/services/speech/index.d.ts +39 -0
  27. package/dist/services/speech/index.js +105 -0
  28. package/dist/services/speech/schema.d.ts +43 -0
  29. package/dist/services/speech/schema.js +54 -0
  30. package/dist/services/webhooks/http-client.d.ts +7 -0
  31. package/dist/services/webhooks/http-client.js +57 -0
  32. package/dist/services/webhooks/index.d.ts +341 -0
  33. package/dist/services/webhooks/index.js +737 -0
  34. package/dist/services/webhooks/migrations.d.ts +5 -0
  35. package/dist/services/webhooks/migrations.js +44 -0
  36. package/dist/services/webhooks/schema.d.ts +243 -0
  37. package/dist/services/webhooks/schema.js +333 -0
  38. package/dist/services/webhooks/url.d.ts +3 -0
  39. package/dist/services/webhooks/url.js +32 -0
  40. package/package.json +37 -1
  41. package/dist/components/ui/marker.d.ts +0 -10
@@ -0,0 +1,737 @@
1
+ // ../../src/services/webhooks/index.ts
2
+ import { PgClient } from "@effect/sql-pg";
3
+ import {
4
+ Cause,
5
+ Context,
6
+ DateTime as DateTime2,
7
+ Duration,
8
+ Effect as Effect4,
9
+ Layer as Layer3,
10
+ Option as Option2,
11
+ Schedule,
12
+ Schema as Schema3
13
+ } from "effect";
14
+ import { HttpClient as HttpClient2, HttpClientRequest } from "effect/http";
15
+ import { Activity, DurableClock, Workflow } from "effect/workflow";
16
+ import { SqlClient as SqlClient2, SqlSchema } from "effect/sql";
17
+ import { Mac, SecureRandom } from "effect/crypto";
18
+ import { Hex } from "effect/encoding";
19
+
20
+ // ../../src/services/webhooks/migrations.ts
21
+ import { Effect, Layer } from "effect";
22
+ import { Migrator, SqlClient } from "effect/sql";
23
+ var webhookMigrations = Migrator.fromRecord({
24
+ "1_webhooks_initial": Effect.gen(function* () {
25
+ const sql = yield* SqlClient.SqlClient;
26
+ yield* sql`CREATE TABLE IF NOT EXISTS webhooks (
27
+ id text PRIMARY KEY, organization_id text NOT NULL, url text NOT NULL,
28
+ description text, headers jsonb, events jsonb, secret text NOT NULL,
29
+ enabled boolean NOT NULL DEFAULT true,
30
+ created_at timestamp NOT NULL DEFAULT now(), updated_at timestamp NOT NULL DEFAULT now()
31
+ )`;
32
+ yield* sql`CREATE TABLE IF NOT EXISTS webhook_deliveries (
33
+ id text PRIMARY KEY, webhook_id text NOT NULL REFERENCES webhooks(id) ON DELETE CASCADE,
34
+ event text NOT NULL, data jsonb NOT NULL DEFAULT '{}', status text NOT NULL DEFAULT 'pending',
35
+ completed_at timestamp, retry_at timestamp NOT NULL DEFAULT now(), retries integer NOT NULL DEFAULT 0,
36
+ created_at timestamp NOT NULL DEFAULT now(), updated_at timestamp NOT NULL DEFAULT now()
37
+ )`;
38
+ yield* sql`ALTER TABLE webhook_deliveries ADD COLUMN IF NOT EXISTS event_id text`;
39
+ yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS krakstack_webhook_event_endpoint ON webhook_deliveries (webhook_id, event_id) WHERE event_id IS NOT NULL`;
40
+ yield* sql`CREATE INDEX IF NOT EXISTS krakstack_webhook_pending ON webhook_deliveries (retry_at) WHERE status = 'pending'`;
41
+ yield* sql`CREATE INDEX IF NOT EXISTS krakstack_webhook_organization ON webhooks (organization_id)`;
42
+ yield* sql`CREATE TABLE IF NOT EXISTS webhook_publications (
43
+ organization_id text NOT NULL, event_id text NOT NULL, event text NOT NULL, data jsonb NOT NULL,
44
+ PRIMARY KEY (organization_id, event_id)
45
+ )`;
46
+ }),
47
+ "2_webhook_names": Effect.gen(function* () {
48
+ const sql = yield* SqlClient.SqlClient;
49
+ yield* sql`ALTER TABLE webhooks ADD COLUMN name text`;
50
+ yield* sql`UPDATE webhooks SET name = url WHERE name IS NULL`;
51
+ yield* sql`ALTER TABLE webhook_deliveries ADD COLUMN error text`;
52
+ })
53
+ });
54
+ var migrateWebhooks = Migrator.make({})({
55
+ loader: webhookMigrations,
56
+ table: "krakstack_webhook_migrations"
57
+ });
58
+ var webhookMigrationsLayer = Layer.effectDiscard(migrateWebhooks);
59
+
60
+ // ../../src/services/webhooks/url.ts
61
+ var hostname = (value) => value.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
62
+ var isPublicIpAddress = (value) => {
63
+ const address = hostname(value);
64
+ const octets = address.split(".");
65
+ if (octets.length === 4 && octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255)) {
66
+ const [a = 0, b = 0, c = 0] = octets.map(Number);
67
+ return !(a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && (b === 0 || b === 168 || b === 88 && c === 99) || a === 198 && (b === 18 || b === 19 || b === 51) || a === 203 && b === 0 || a >= 224);
68
+ }
69
+ const first = Number.parseInt(address.split(":")[0] ?? "", 16);
70
+ return address.includes(":") && first >= 8192 && first <= 16383 && !address.startsWith("2001:") && !address.startsWith("2002:") && !address.startsWith("3fff:");
71
+ };
72
+ var isPublicWebhookUrl = (url) => {
73
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password)
74
+ return false;
75
+ const host = hostname(url.hostname);
76
+ if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local"))
77
+ return false;
78
+ return !(host.includes(":") || /^\d+(?:\.\d+){3}$/.test(host)) || isPublicIpAddress(host);
79
+ };
80
+ var isPublicWebhookUrlString = (value) => {
81
+ try {
82
+ return isPublicWebhookUrl(new URL(value));
83
+ } catch {
84
+ return false;
85
+ }
86
+ };
87
+
88
+ // ../../src/services/webhooks/http-client.ts
89
+ import { Effect as Effect2, Layer as Layer2, Result } from "effect";
90
+ import { Dns, NetAddress } from "effect/net";
91
+ import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http";
92
+ var isPublicWebhookDestination = Effect2.fn("Webhooks.isPublicDestination")(function* (url) {
93
+ if (!isPublicWebhookUrl(url))
94
+ return false;
95
+ const hostname = url.hostname.replace(/^\[|\]$/g, "");
96
+ if (Result.isSuccess(NetAddress.ipFromString(hostname)))
97
+ return true;
98
+ const dns = yield* Dns.Dns;
99
+ return yield* dns.lookup(hostname).pipe(Effect2.map((addresses) => addresses.every((address) => isPublicIpAddress(NetAddress.formatIp(address)))), Effect2.catch(() => Effect2.succeed(false)));
100
+ });
101
+ var layer = Layer2.effect(HttpClient.HttpClient, Effect2.gen(function* () {
102
+ const client = yield* HttpClient.HttpClient;
103
+ const dns = yield* Dns.Dns;
104
+ return client.pipe(HttpClient.transform((response, request) => Effect2.gen(function* () {
105
+ if (!(yield* isPublicWebhookDestination(new URL(request.url)).pipe(Effect2.provideService(Dns.Dns, dns)))) {
106
+ return yield* new HttpClientError.HttpClientError({
107
+ reason: new HttpClientError.TransportError({
108
+ request,
109
+ description: "Webhook destination is not public"
110
+ })
111
+ });
112
+ }
113
+ return yield* response.pipe(Effect2.provideService(FetchHttpClient.RequestInit, {
114
+ redirect: "error"
115
+ }));
116
+ })));
117
+ })).pipe(Layer2.provide(FetchHttpClient.layer));
118
+
119
+ // ../../src/services/webhooks/schema.ts
120
+ import { Schema as Schema2 } from "effect";
121
+
122
+ // ../../src/lib/query.ts
123
+ import {
124
+ DateTime,
125
+ Effect as Effect3,
126
+ Option,
127
+ Schema,
128
+ SchemaGetter,
129
+ SchemaIssue,
130
+ SchemaTransformation
131
+ } from "effect";
132
+ var parseSortParam = (sort) => {
133
+ const id = sort.startsWith("-") ? sort.slice(1) : sort;
134
+ if (!id || id.includes(",") || id.includes(":")) {
135
+ return null;
136
+ }
137
+ return { id, direction: sort.startsWith("-") ? "desc" : "asc" };
138
+ };
139
+ var SortDirection = Schema.Union([
140
+ Schema.Literal("asc"),
141
+ Schema.Literal("desc")
142
+ ]).pipe(Schema.annotate({
143
+ identifier: "SortDirection",
144
+ title: "Sort Direction",
145
+ description: "Sort direction for list query results.",
146
+ examples: ["asc", "desc"]
147
+ }));
148
+ var SortParam = Schema.Struct({
149
+ id: Schema.NonEmptyString,
150
+ direction: SortDirection
151
+ }).pipe(Schema.annotate({
152
+ identifier: "SortParam",
153
+ title: "Sort Parameter",
154
+ description: "Decoded sort parameter with a field id and direction.",
155
+ examples: [{ id: "publicName", direction: "asc" }]
156
+ }));
157
+ var SortParamFromString = Schema.String.pipe(Schema.decodeTo(SortParam, SchemaTransformation.transformEffect({
158
+ decode: (sort) => {
159
+ const sortParam = parseSortParam(sort);
160
+ if (!sortParam) {
161
+ return Effect3.fail(new SchemaIssue.InvalidValue({ message: 'Expected sort in the format "field" or "-field"' }, sort));
162
+ }
163
+ return Effect3.succeed(sortParam);
164
+ },
165
+ encode: (sort) => Effect3.succeed(sort.direction === "desc" ? `-${sort.id}` : sort.id)
166
+ })), Schema.annotate({
167
+ identifier: "SortParamFromString",
168
+ title: "Sort Parameter From String",
169
+ description: 'URL encoded single sort parameter where descending fields are prefixed with "-".',
170
+ examples: [{ id: "publicName", direction: "asc" }]
171
+ }));
172
+ var SortParamsFromString = Schema.String.pipe(Schema.decodeTo(Schema.Array(SortParam), SchemaTransformation.transformEffect({
173
+ decode: (sort) => {
174
+ if (sort === "")
175
+ return Effect3.succeed([]);
176
+ const parts = sort.split(",");
177
+ const sortParams = [];
178
+ for (const part of parts) {
179
+ const sortParam = parseSortParam(part);
180
+ if (!sortParam) {
181
+ return Effect3.fail(new SchemaIssue.InvalidValue({ message: 'Expected sort in the format "field,-otherField"' }, sort));
182
+ }
183
+ sortParams.push(sortParam);
184
+ }
185
+ return Effect3.succeed(sortParams);
186
+ },
187
+ encode: (sort) => Effect3.succeed(sort.map((part) => Schema.encodeSync(SortParamFromString)(part)).join(","))
188
+ })), Schema.annotate({
189
+ identifier: "SortParamsFromString",
190
+ title: "Sort Parameters From String",
191
+ description: 'URL encoded sort parameters where descending fields are prefixed with "-" and multiple fields are comma-separated.',
192
+ examples: [
193
+ [
194
+ { id: "name", direction: "desc" },
195
+ { id: "age", direction: "asc" }
196
+ ]
197
+ ]
198
+ }));
199
+ var SortParamsArray = Schema.Array(SortParam);
200
+ var SortParams = Schema.declare(Schema.is(SortParamsArray), {
201
+ identifier: "SortParams",
202
+ toCodec: () => Schema.link()(SortParamsArray, SchemaTransformation.passthrough()),
203
+ toCodecStringTree: () => Schema.link()(SortParamsFromString, SchemaTransformation.passthrough())
204
+ });
205
+ var TextFilterOperator = Schema.Literals([
206
+ "contains",
207
+ "equals",
208
+ "startsWith",
209
+ "endsWith"
210
+ ]).annotate({ identifier: "TextFilterOperator" });
211
+ var FilterCalendarDate = Schema.String.check(Schema.isPattern(/^\d{4}-\d{2}-\d{2}$/), Schema.makeFilter((value) => Option.exists(DateTime.make(value), (date) => DateTime.formatIsoDateUtc(date) === value))).annotate({ identifier: "FilterCalendarDate" });
212
+ var ColumnFilter = Schema.Union([
213
+ Schema.Struct({
214
+ id: Schema.NonEmptyString,
215
+ kind: Schema.Literal("text"),
216
+ operator: TextFilterOperator,
217
+ value: Schema.NonEmptyString
218
+ }),
219
+ Schema.Struct({
220
+ id: Schema.NonEmptyString,
221
+ kind: Schema.Literal("number"),
222
+ min: Schema.optional(Schema.Finite),
223
+ max: Schema.optional(Schema.Finite)
224
+ }).check(Schema.makeFilter((range) => (range.min !== undefined || range.max !== undefined) && (range.min === undefined || range.max === undefined || range.min <= range.max))),
225
+ Schema.Struct({
226
+ id: Schema.NonEmptyString,
227
+ kind: Schema.Literal("date"),
228
+ from: Schema.optional(FilterCalendarDate),
229
+ to: Schema.optional(FilterCalendarDate)
230
+ }).check(Schema.makeFilter((range) => (range.from !== undefined || range.to !== undefined) && (range.from === undefined || range.to === undefined || range.from <= range.to))),
231
+ Schema.Struct({
232
+ id: Schema.NonEmptyString,
233
+ kind: Schema.Literal("boolean"),
234
+ value: Schema.Boolean
235
+ }),
236
+ Schema.Struct({
237
+ id: Schema.NonEmptyString,
238
+ kind: Schema.Literal("values"),
239
+ values: Schema.NonEmptyArray(Schema.String)
240
+ })
241
+ ]).annotate({ identifier: "ColumnFilter" });
242
+ var ColumnFiltersArray = Schema.Array(ColumnFilter);
243
+ var ColumnFilters = Schema.declare(Schema.is(ColumnFiltersArray), {
244
+ identifier: "ColumnFilters",
245
+ toCodec: () => Schema.link()(ColumnFiltersArray, SchemaTransformation.passthrough()),
246
+ toCodecStringTree: () => Schema.link()(Schema.fromJsonString(ColumnFiltersArray), SchemaTransformation.passthrough())
247
+ });
248
+ var Query = Schema.Struct({
249
+ page: Schema.optional(Schema.Union([Schema.Number, Schema.NumberFromString]).check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))).pipe(Schema.decodeTo(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), {
250
+ decode: SchemaGetter.withDefault(Effect3.succeed(0)),
251
+ encode: SchemaGetter.transformOptional(Option.filter((page) => page !== 0))
252
+ })),
253
+ pageSize: Schema.optional(Schema.Union([Schema.Number, Schema.NumberFromString]).check(Schema.isInt(), Schema.isBetween({ minimum: 1, maximum: 100 }))).pipe(Schema.decodeTo(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 })), {
254
+ decode: SchemaGetter.withDefault(Effect3.succeed(20)),
255
+ encode: SchemaGetter.transformOptional(Option.filter((pageSize) => pageSize !== 20))
256
+ })),
257
+ globalFilter: Schema.optional(Schema.String),
258
+ sort: Schema.optional(SortParams),
259
+ filters: Schema.optional(ColumnFilters)
260
+ }).annotate({
261
+ identifier: "Query",
262
+ title: "Query",
263
+ description: "Zero-based page request parameters with optional filtering and sorting for list endpoints.",
264
+ examples: [
265
+ {
266
+ page: 0,
267
+ pageSize: 20,
268
+ globalFilter: "housing",
269
+ sort: [
270
+ { id: "publicName", direction: "desc" },
271
+ { id: "createdAt", direction: "asc" }
272
+ ]
273
+ }
274
+ ]
275
+ });
276
+ var QueryStandard = Schema.toStandardSchemaV1(Query);
277
+ var PaginationMeta = Schema.Struct({
278
+ page: Schema.Int,
279
+ pageSize: Schema.Int,
280
+ total: Schema.Int,
281
+ pageCount: Schema.Int
282
+ }).pipe(Schema.annotate({
283
+ identifier: "PaginationMeta",
284
+ title: "Pagination Metadata",
285
+ description: "Pagination metadata returned with a paginated list response.",
286
+ examples: [{ page: 0, pageSize: 20, total: 125, pageCount: 7 }]
287
+ }));
288
+ var PaginatedResponse = (items) => Schema.Struct({
289
+ data: Schema.Array(items),
290
+ meta: PaginationMeta
291
+ });
292
+
293
+ // ../../src/services/webhooks/schema.ts
294
+ var webhookColumns = 'id, organization_id AS "organizationId", COALESCE(name, url) AS name, url, description, headers, events, secret, enabled, created_at AS "createdAt", updated_at AS "updatedAt"';
295
+ var deliveryColumns = 'd.id, d.webhook_id AS "webhookId", d.event, d.data, d.status, d.error, d.completed_at AS "completedAt", d.retry_at AS "retryAt", d.retries, d.created_at AS "createdAt", d.updated_at AS "updatedAt"';
296
+ var WebhookScope = Schema2.Struct({
297
+ organizationId: Schema2.NonEmptyString
298
+ }).annotate({ identifier: "WebhookScope" });
299
+ var WebhookRequest = Schema2.Struct({
300
+ organizationId: Schema2.NonEmptyString,
301
+ id: Schema2.NonEmptyString
302
+ }).annotate({ identifier: "WebhookRequest" });
303
+ var WebhookStatisticsInterval = Schema2.Literals([
304
+ "hour",
305
+ "day"
306
+ ]).annotate({ identifier: "WebhookStatisticsInterval" });
307
+ var WebhookStatisticsRequest = Schema2.Struct({
308
+ ...WebhookRequest.fields,
309
+ interval: WebhookStatisticsInterval
310
+ }).annotate({ identifier: "WebhookStatisticsRequest" });
311
+ var WebhookDeliveryCounts = Schema2.Struct({
312
+ total: Schema2.Int,
313
+ success: Schema2.Int,
314
+ failed: Schema2.Int
315
+ }).annotate({ identifier: "WebhookDeliveryCounts" });
316
+ var WebhookEventCount = Schema2.Struct({
317
+ event: Schema2.String,
318
+ total: Schema2.Int
319
+ }).annotate({ identifier: "WebhookEventCount" });
320
+ var WebhookDeliveryBucket = Schema2.Struct({
321
+ ...WebhookDeliveryCounts.fields,
322
+ bucket: Schema2.Date,
323
+ events: Schema2.Array(WebhookEventCount)
324
+ }).annotate({ identifier: "WebhookDeliveryBucket" });
325
+ var WebhookStatistics = Schema2.Struct({
326
+ ...WebhookDeliveryCounts.fields,
327
+ buckets: Schema2.Array(WebhookDeliveryBucket)
328
+ }).annotate({ identifier: "WebhookStatistics" });
329
+ var WebhookName = Schema2.Trim.check(Schema2.isMinLength(1), Schema2.isMaxLength(200)).annotate({ identifier: "WebhookName" });
330
+ var WebhookPayload = Schema2.Struct({
331
+ name: Schema2.optional(WebhookName),
332
+ url: Schema2.String.check(Schema2.makeFilter(isPublicWebhookUrlString, {
333
+ expected: "a public HTTP or HTTPS URL without credentials"
334
+ })),
335
+ description: Schema2.NullOr(Schema2.String),
336
+ enabled: Schema2.Boolean,
337
+ events: Schema2.NullOr(Schema2.Array(Schema2.NonEmptyString)),
338
+ customHeaders: Schema2.NullOr(Schema2.Record(Schema2.String, Schema2.String)).check(Schema2.makeFilter((headers) => Object.keys(headers ?? {}).every((name) => ![
339
+ "content-type",
340
+ "webhook-id",
341
+ "webhook-timestamp",
342
+ "webhook-signature"
343
+ ].includes(name.toLowerCase())), { expected: "headers that do not override webhook protocol headers" }))
344
+ }).annotate({ identifier: "WebhookPayload" });
345
+ var Webhook = Schema2.Struct({
346
+ id: Schema2.String,
347
+ name: Schema2.String,
348
+ organizationId: Schema2.String,
349
+ url: Schema2.String,
350
+ description: Schema2.NullOr(Schema2.String),
351
+ headers: Schema2.NullOr(Schema2.Record(Schema2.String, Schema2.String)),
352
+ events: Schema2.NullOr(Schema2.Array(Schema2.String)),
353
+ secret: Schema2.String,
354
+ enabled: Schema2.Boolean,
355
+ createdAt: Schema2.Date,
356
+ updatedAt: Schema2.Date
357
+ }).annotate({ identifier: "Webhook" });
358
+ var WebhookDelivery = Schema2.Struct({
359
+ id: Schema2.String,
360
+ webhookId: Schema2.String,
361
+ event: Schema2.String,
362
+ data: Schema2.Json,
363
+ status: Schema2.Literals(["pending", "success", "failed"]),
364
+ error: Schema2.NullOr(Schema2.String),
365
+ completedAt: Schema2.NullOr(Schema2.Date),
366
+ retryAt: Schema2.Date,
367
+ retries: Schema2.Int,
368
+ createdAt: Schema2.Date,
369
+ updatedAt: Schema2.Date
370
+ }).annotate({ identifier: "WebhookDelivery" });
371
+ var WebhookDeliverySortId = Schema2.Literals([
372
+ "id",
373
+ "event",
374
+ "status",
375
+ "createdAt",
376
+ "completedAt"
377
+ ]).annotate({ identifier: "WebhookDeliverySortId" });
378
+ var DeliveryFilter = ColumnFilter.check(Schema2.makeFilter((filter) => filter.id === "id" ? filter.kind === "text" : filter.id === "event" ? filter.kind === "values" : filter.id === "status" ? filter.kind === "values" && filter.values.every((value) => ["pending", "success", "failed"].includes(value)) : ["createdAt", "completedAt"].includes(filter.id) && filter.kind === "date")).annotate({ identifier: "WebhookDeliveryFilter" });
379
+ var WebhookDeliveriesQuery = Schema2.Struct({
380
+ ...Query.fields,
381
+ filters: Schema2.optional(ColumnFilters.check(Schema2.makeFilter((filters) => filters.every(Schema2.is(DeliveryFilter))))),
382
+ sort: Schema2.optional(SortParams.check(Schema2.makeFilter((sort) => sort.every((part) => Schema2.is(WebhookDeliverySortId)(part.id)))))
383
+ }).annotate({ identifier: "WebhookDeliveriesQuery" });
384
+ var ListWebhookDeliveries = Schema2.Struct({
385
+ ...WebhookRequest.fields,
386
+ ...WebhookDeliveriesQuery.fields
387
+ }).annotate({ identifier: "ListWebhookDeliveries" });
388
+ var WebhookDeliveries = PaginatedResponse(WebhookDelivery).annotate({
389
+ identifier: "WebhookDeliveries"
390
+ });
391
+ var PublishWebhook = Schema2.Struct({
392
+ organizationId: Schema2.NonEmptyString,
393
+ eventId: Schema2.NonEmptyString,
394
+ event: Schema2.NonEmptyString,
395
+ data: Schema2.Json
396
+ }).annotate({ identifier: "PublishWebhook" });
397
+
398
+ class WebhookError extends Schema2.TaggedError()("WebhookError", {
399
+ message: Schema2.String
400
+ }) {
401
+ }
402
+
403
+ // ../../src/services/webhooks/index.ts
404
+ var maxDeliveryAttempts = 8;
405
+ var retrySchedule = Schedule.min([
406
+ Schedule.exponential("5 seconds", 4),
407
+ Schedule.spaced("10 hours")
408
+ ]);
409
+ var processDelivery = Effect4.fn("Webhooks.processDelivery")(function* (input) {
410
+ const sql = (yield* SqlClient2.SqlClient).withoutTransforms();
411
+ const client = yield* HttpClient2.HttpClient;
412
+ const row = yield* SqlSchema.findOneOption({
413
+ Request: WebhookRequest,
414
+ Result: WebhookDelivery,
415
+ execute: ({
416
+ id,
417
+ organizationId
418
+ }) => sql`SELECT ${sql.literal(deliveryColumns)} FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
419
+ WHERE d.id = ${id} AND w.organization_id = ${organizationId}`
420
+ })(input);
421
+ if (Option2.isNone(row) || row.value.status !== "pending")
422
+ return null;
423
+ const delivery = row.value;
424
+ const now = yield* DateTime2.now;
425
+ const remaining = delivery.retryAt.getTime() - DateTime2.toEpochMillis(now);
426
+ if (remaining > 0)
427
+ return remaining;
428
+ const found = yield* SqlSchema.findOneOption({
429
+ Request: WebhookRequest,
430
+ Result: Webhook,
431
+ execute: ({ organizationId, id }) => sql`SELECT ${sql.literal(webhookColumns)} FROM webhooks WHERE organization_id = ${organizationId} AND id = ${id}`
432
+ })({ organizationId: input.organizationId, id: delivery.webhookId });
433
+ if (Option2.isNone(found))
434
+ return null;
435
+ const endpoint = found.value;
436
+ if (!endpoint.enabled || delivery.retries >= maxDeliveryAttempts) {
437
+ const error = !endpoint.enabled ? "Webhook endpoint is disabled" : delivery.error ?? "Delivery attempt limit reached";
438
+ yield* sql`UPDATE webhook_deliveries SET status = 'failed', error = ${error}, completed_at = now(), updated_at = now() WHERE id = ${input.id}`;
439
+ return null;
440
+ }
441
+ const body = yield* Schema3.encodeEffect(Schema3.fromJsonString(Schema3.Json))({
442
+ event: delivery.event,
443
+ data: delivery.data
444
+ });
445
+ const timestamp = DateTime2.formatIso(now);
446
+ const mac = yield* Mac.Mac.pipe(Effect4.provide(Mac.layerWebCrypto.pipe(Layer3.provide(SecureRandom.layerWebCrypto))));
447
+ const key = yield* Mac.key(Mac.hmacSha256, new TextEncoder().encode(endpoint.secret));
448
+ const signature = Hex.encode(yield* mac.sign(key, new TextEncoder().encode(`${timestamp}.${body}`)));
449
+ const error = isPublicWebhookUrlString(endpoint.url) ? yield* client.execute(HttpClientRequest.post(endpoint.url).pipe(HttpClientRequest.setHeaders({
450
+ ...endpoint.headers,
451
+ "Content-Type": "application/json",
452
+ "webhook-id": delivery.id,
453
+ "webhook-timestamp": timestamp,
454
+ "webhook-signature": signature
455
+ }), HttpClientRequest.bodyText(body, "application/json"))).pipe(Effect4.map((response) => response.status >= 200 && response.status < 300 ? null : `HTTP ${response.status}`), Effect4.timeout("30 seconds"), Effect4.catch((error) => Effect4.succeed(error._tag === "TimeoutError" ? "Request timed out after 30 seconds" : error.reason._tag === "TransportError" && error.reason.description === "Webhook destination is not public" ? "Webhook destination is not public" : error.reason._tag === "InvalidUrlError" ? "Invalid webhook URL" : "Webhook network request failed")), Effect4.scoped) : "Webhook destination is not public";
456
+ if (error === null) {
457
+ yield* sql`UPDATE webhook_deliveries SET status = 'success', error = NULL, completed_at = now(), updated_at = now() WHERE id = ${input.id}`;
458
+ return null;
459
+ }
460
+ if (delivery.retries + 1 >= maxDeliveryAttempts) {
461
+ yield* sql`UPDATE webhook_deliveries SET status = 'failed', error = ${error}, retries = retries + 1, completed_at = now(), updated_at = now() WHERE id = ${input.id}`;
462
+ return null;
463
+ }
464
+ const step = yield* Schedule.toStep(retrySchedule);
465
+ let duration = Duration.zero;
466
+ for (let attempt = 0;attempt <= delivery.retries; attempt++) {
467
+ const [, delay] = yield* step(DateTime2.toEpochMillis(now), undefined).pipe(Effect4.orDie);
468
+ duration = delay;
469
+ }
470
+ const delay = Duration.toMillis(duration);
471
+ yield* sql`UPDATE webhook_deliveries SET retries = retries + 1, error = ${error}, retry_at = now() + ${delay} * interval '1 millisecond', updated_at = now() WHERE id = ${input.id}`;
472
+ return delay;
473
+ });
474
+ var DeliverWebhookV1 = Workflow.make("KrakstackDeliverWebhookV1", {
475
+ payload: { organizationId: Schema3.String, id: Schema3.String },
476
+ success: Schema3.Void,
477
+ error: WebhookError,
478
+ idempotencyKey: ({ organizationId, id }) => `${organizationId}:${id}`
479
+ });
480
+ var workflowLayer = DeliverWebhookV1.toLayer((input) => Effect4.gen(function* () {
481
+ for (let step = 0;; step++) {
482
+ const wait = yield* Activity.make({
483
+ name: `DeliverWebhookAttemptV1-${step}`,
484
+ success: Schema3.NullOr(Schema3.Number),
485
+ error: WebhookError,
486
+ execute: processDelivery(input).pipe(Effect4.mapError(() => new WebhookError({
487
+ message: "Webhook delivery persistence failed"
488
+ })), Effect4.tapError(() => Effect4.logError("Webhook delivery persistence failed")), Effect4.retry(Schedule.spaced("5 seconds")))
489
+ });
490
+ if (wait === null)
491
+ return;
492
+ yield* DurableClock.sleep({
493
+ name: `WebhookRetryV1-${step}`,
494
+ duration: wait,
495
+ inMemoryThreshold: 0
496
+ });
497
+ }
498
+ }));
499
+ var dispatchPending = Effect4.gen(function* () {
500
+ const sql = (yield* SqlClient2.SqlClient).withoutTransforms();
501
+ const pending = yield* SqlSchema.findAll({
502
+ Request: Schema3.Void,
503
+ Result: Schema3.Struct({
504
+ id: Schema3.String,
505
+ organizationId: Schema3.String
506
+ }).annotate({ identifier: "PendingWebhookDelivery" }),
507
+ execute: () => sql`SELECT d.id, w.organization_id AS "organizationId" FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
508
+ WHERE d.status = 'pending' AND d.retry_at <= now() ORDER BY d.retry_at LIMIT 100`
509
+ })();
510
+ yield* Effect4.forEach(pending, (input) => DeliverWebhookV1.execute(input, { discard: true }), { concurrency: 4, discard: true });
511
+ });
512
+ var dispatchLayer = Layer3.effectDiscard(Effect4.repeat(dispatchPending.pipe(Effect4.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect4.interrupt : Effect4.logError("Webhook dispatch failed"))), Schedule.spaced("5 seconds")).pipe(Effect4.forkScoped)).pipe(Layer3.provide(workflowLayer));
513
+
514
+ class Webhooks extends Context.Service()("krakstack/webhooks/Webhooks", {
515
+ make: Effect4.gen(function* () {
516
+ const sql = (yield* SqlClient2.SqlClient).withoutTransforms();
517
+ const pg = yield* PgClient.PgClient;
518
+ const random = yield* SecureRandom.SecureRandom.pipe(Effect4.provide(SecureRandom.layerWebCrypto));
519
+ const list = SqlSchema.findAll({
520
+ Request: WebhookScope,
521
+ Result: Webhook,
522
+ execute: ({ organizationId }) => sql`SELECT ${sql.literal(webhookColumns)} FROM webhooks WHERE organization_id = ${organizationId} ORDER BY created_at, id`
523
+ });
524
+ const find = SqlSchema.findOneOption({
525
+ Request: WebhookRequest,
526
+ Result: Webhook,
527
+ execute: ({ organizationId, id }) => sql`SELECT ${sql.literal(webhookColumns)} FROM webhooks WHERE organization_id = ${organizationId} AND id = ${id}`
528
+ });
529
+ const deliveries = SqlSchema.findAll({
530
+ Request: WebhookRequest,
531
+ Result: WebhookDelivery,
532
+ execute: ({ organizationId, id }) => sql`SELECT ${sql.literal(deliveryColumns)} FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id WHERE w.organization_id = ${organizationId} AND w.id = ${id} ORDER BY d.created_at DESC LIMIT 100`
533
+ });
534
+ const get = Effect4.fn("Webhooks.get")(function* (input) {
535
+ const found = yield* find(input);
536
+ if (Option2.isNone(found))
537
+ return;
538
+ return { ...found.value, deliveries: yield* deliveries(input) };
539
+ });
540
+ const status = sql`CASE WHEN d.status = 'pending' AND d.retries > 0 THEN 'failed' ELSE d.status END`;
541
+ const listDeliveries = Effect4.fn("Webhooks.listDeliveries")(function* (input) {
542
+ const request = yield* Schema3.decodeUnknownEffect(ListWebhookDeliveries)(input);
543
+ if (Option2.isNone(yield* find(request)))
544
+ return;
545
+ const columns = {
546
+ id: sql`d.id`,
547
+ event: sql`d.event`,
548
+ status,
549
+ createdAt: sql`d.created_at`,
550
+ completedAt: sql`d.completed_at`
551
+ };
552
+ const predicates = yield* Effect4.forEach(request.filters ?? [], (filter) => Effect4.gen(function* () {
553
+ const id = yield* Schema3.decodeUnknownEffect(WebhookDeliverySortId)(filter.id);
554
+ const column = columns[id];
555
+ if (filter.kind === "values")
556
+ return sql`AND ${sql.or(filter.values.map((value) => sql`${column} = ${value}`))}`;
557
+ if (filter.kind === "date")
558
+ return sql`${filter.from ? sql`AND ${column} >= ${filter.from}::timestamp` : sql``}
559
+ ${filter.to ? sql`AND ${column} < ${filter.to}::timestamp + interval '1 day'` : sql``}`;
560
+ if (filter.kind === "text") {
561
+ const value = filter.value.toLowerCase();
562
+ if (filter.operator === "equals")
563
+ return sql`AND LOWER(${column}) = ${value}`;
564
+ const escaped = value.replace(/[\\%_]/g, "\\$&");
565
+ const pattern = filter.operator === "startsWith" ? `${escaped}%` : filter.operator === "endsWith" ? `%${escaped}` : `%${escaped}%`;
566
+ return sql`AND LOWER(${column}) LIKE ${pattern} ESCAPE ${"\\"}`;
567
+ }
568
+ return sql``;
569
+ }));
570
+ const search = request.globalFilter?.trim().toLowerCase().replace(/[\\%_]/g, "\\$&");
571
+ const predicate = sql`w.id = ${request.id} AND w.organization_id = ${request.organizationId}
572
+ ${sql.join(" ", false)(predicates)}
573
+ ${search ? sql`AND LOWER(d.id || ' ' || d.event || ' ' || ${status} || ' ' || COALESCE(d.error, '') || ' ' || d.data::text) LIKE ${`%${search}%`} ESCAPE ${"\\"}` : sql``}`;
574
+ const sorts = yield* Effect4.forEach(request.sort ?? [], (part) => Effect4.gen(function* () {
575
+ const id = yield* Schema3.decodeUnknownEffect(WebhookDeliverySortId)(part.id);
576
+ return sql`${columns[id]} ${sql.literal(part.direction === "desc" ? "DESC" : "ASC")} NULLS LAST`;
577
+ }));
578
+ const count = yield* SqlSchema.findOne({
579
+ Request: Schema3.Void,
580
+ Result: Schema3.Struct({ total: Schema3.Int }).annotate({
581
+ identifier: "WebhookDeliveryCount"
582
+ }),
583
+ execute: () => sql`SELECT count(*)::int AS total FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id WHERE ${predicate}`
584
+ })();
585
+ const data = yield* SqlSchema.findAll({
586
+ Request: Schema3.Void,
587
+ Result: WebhookDelivery,
588
+ execute: () => sql`SELECT ${sql.literal(deliveryColumns)} FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
589
+ WHERE ${predicate} ORDER BY ${sql.join(", ", false)(sorts.length ? [...sorts, sql`d.id DESC`] : [sql`d.created_at DESC`, sql`d.id DESC`])}
590
+ LIMIT ${request.pageSize} OFFSET ${request.page * request.pageSize}`
591
+ })();
592
+ return {
593
+ data,
594
+ meta: {
595
+ page: request.page,
596
+ pageSize: request.pageSize,
597
+ total: count.total,
598
+ pageCount: Math.ceil(count.total / request.pageSize)
599
+ }
600
+ };
601
+ });
602
+ const statistics = Effect4.fn("Webhooks.statistics")(function* (input) {
603
+ const request = yield* Schema3.decodeUnknownEffect(WebhookStatisticsRequest)(input);
604
+ if (Option2.isNone(yield* find(request)))
605
+ return;
606
+ const totals = yield* SqlSchema.findOne({
607
+ Request: WebhookRequest,
608
+ Result: WebhookDeliveryCounts,
609
+ execute: ({
610
+ organizationId,
611
+ id
612
+ }) => sql`SELECT count(*)::float8 AS total,
613
+ count(*) FILTER (WHERE d.status = 'success')::float8 AS success,
614
+ count(*) FILTER (WHERE ${status} = 'failed')::float8 AS failed
615
+ FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
616
+ WHERE w.id = ${id} AND w.organization_id = ${organizationId}`
617
+ })(request);
618
+ const windows = {
619
+ hour: { start: "day", step: "1 hour" },
620
+ day: { start: "month", step: "1 day" }
621
+ };
622
+ const window = windows[request.interval];
623
+ const buckets = yield* SqlSchema.findAll({
624
+ Request: WebhookStatisticsRequest,
625
+ Result: WebhookDeliveryBucket,
626
+ execute: ({ organizationId, id, interval }) => sql`WITH bounds AS (
627
+ SELECT date_trunc(${window.start}, now() AT TIME ZONE 'UTC') AS start,
628
+ date_trunc(${interval}, now() AT TIME ZONE 'UTC') AS finish, ${window.step}::interval AS step
629
+ ), buckets AS (
630
+ SELECT generate_series(start, finish, step) AS bucket, step FROM bounds
631
+ ), scoped AS (
632
+ SELECT d.id, d.event, ${status} AS status, d.created_at FROM webhook_deliveries d JOIN webhooks w ON w.id = d.webhook_id
633
+ WHERE w.id = ${id} AND w.organization_id = ${organizationId}
634
+ AND d.created_at >= (SELECT min(bucket) FROM buckets)
635
+ ), counts AS (SELECT b.bucket, d.event, count(d.id)::float8 AS total,
636
+ count(d.id) FILTER (WHERE d.status = 'success')::float8 AS success,
637
+ count(d.id) FILTER (WHERE d.status = 'failed')::float8 AS failed
638
+ FROM buckets b LEFT JOIN scoped d ON d.created_at >= b.bucket AND d.created_at < b.bucket + b.step
639
+ GROUP BY b.bucket, d.event)
640
+ SELECT bucket, sum(total)::float8 AS total, sum(success)::float8 AS success, sum(failed)::float8 AS failed,
641
+ COALESCE(jsonb_agg(jsonb_build_object('event', event, 'total', total) ORDER BY event)
642
+ FILTER (WHERE event IS NOT NULL), '[]'::jsonb) AS events
643
+ FROM counts GROUP BY bucket ORDER BY bucket`
644
+ })(request);
645
+ return { ...totals, buckets };
646
+ });
647
+ const create = Effect4.fn("Webhooks.create")(function* (input) {
648
+ const { organizationId } = yield* Schema3.decodeUnknownEffect(WebhookScope)(input);
649
+ const payload = yield* Schema3.decodeUnknownEffect(WebhookPayload)(input.payload);
650
+ const id = yield* random.uuidV7();
651
+ const secret = Hex.encode(yield* random.randomBytes(32));
652
+ yield* sql`INSERT INTO webhooks (id, organization_id, name, url, description, enabled, events, headers, secret)
653
+ VALUES (${id}, ${organizationId}, ${payload.name ?? payload.url}, ${payload.url}, ${payload.description}, ${payload.enabled},
654
+ ${payload.events === null ? null : pg.json(payload.events)}, ${payload.customHeaders === null ? null : pg.json(payload.customHeaders)}, ${secret})`;
655
+ return { id };
656
+ });
657
+ const update = Effect4.fn("Webhooks.update")(function* (input) {
658
+ const { organizationId, id } = yield* Schema3.decodeUnknownEffect(WebhookRequest)(input);
659
+ const payload = yield* Schema3.decodeUnknownEffect(WebhookPayload)(input.payload);
660
+ return yield* SqlSchema.findOneOption({
661
+ Request: Schema3.Void,
662
+ Result: Webhook,
663
+ execute: () => sql`UPDATE webhooks SET name = COALESCE(${payload.name ?? null}, name), url = ${payload.url}, description = ${payload.description}, enabled = ${payload.enabled},
664
+ events = ${payload.events === null ? null : pg.json(payload.events)}, headers = ${payload.customHeaders === null ? null : pg.json(payload.customHeaders)}, updated_at = now()
665
+ WHERE organization_id = ${organizationId} AND id = ${id} RETURNING ${sql.literal(webhookColumns)}`
666
+ })().pipe(Effect4.map(Option2.getOrNull));
667
+ });
668
+ const remove = Effect4.fn("Webhooks.delete")(function* (input) {
669
+ const { organizationId, id } = yield* Schema3.decodeUnknownEffect(WebhookRequest)(input);
670
+ const rows = yield* sql`DELETE FROM webhooks WHERE organization_id = ${organizationId} AND id = ${id} RETURNING id`;
671
+ return rows.length ? { success: true } : null;
672
+ });
673
+ const publish = Effect4.fn("Webhooks.publish")(function* (input) {
674
+ const { organizationId, eventId, event, data } = yield* Schema3.decodeUnknownEffect(PublishWebhook)(input);
675
+ const inserted = yield* sql`INSERT INTO webhook_publications (organization_id, event_id, event, data)
676
+ VALUES (${organizationId}, ${eventId}, ${event}, ${pg.json(data)}) ON CONFLICT DO NOTHING RETURNING event_id`;
677
+ if (!inserted.length) {
678
+ const match = yield* sql`SELECT event_id FROM webhook_publications WHERE organization_id = ${organizationId}
679
+ AND event_id = ${eventId} AND event = ${event} AND data = ${pg.json(data)}::jsonb`;
680
+ if (!match.length)
681
+ return yield* new WebhookError({
682
+ message: "Webhook event id was reused with different content"
683
+ });
684
+ return;
685
+ }
686
+ const endpoints = yield* list({ organizationId });
687
+ for (const endpoint of endpoints) {
688
+ if (!endpoint.enabled || endpoint.events !== null && !endpoint.events.includes(event))
689
+ continue;
690
+ const id = yield* random.uuidV7();
691
+ yield* sql`INSERT INTO webhook_deliveries (id, webhook_id, event_id, event, data, status, retry_at)
692
+ VALUES (${id}, ${endpoint.id}, ${eventId}, ${event}, ${pg.json(data)}, 'pending', now())`;
693
+ }
694
+ }, sql.withTransaction);
695
+ const cleanup = Effect4.fn("Webhooks.cleanup")(function* () {
696
+ yield* sql`DELETE FROM webhook_deliveries WHERE completed_at <= now() - interval '7 days'`;
697
+ });
698
+ return {
699
+ list,
700
+ get,
701
+ listDeliveries,
702
+ statistics,
703
+ create,
704
+ update,
705
+ delete: remove,
706
+ publish,
707
+ cleanup
708
+ };
709
+ })
710
+ }) {
711
+ static layerWithoutMigrations = Layer3.effect(this, this.make).pipe(Layer3.provide(dispatchLayer));
712
+ static layer = this.layerWithoutMigrations.pipe(Layer3.provide(layer), Layer3.provide(webhookMigrationsLayer));
713
+ }
714
+ export {
715
+ DeliverWebhookV1,
716
+ ListWebhookDeliveries,
717
+ PublishWebhook,
718
+ Webhook,
719
+ WebhookDeliveries,
720
+ WebhookDeliveriesQuery,
721
+ WebhookDelivery,
722
+ WebhookDeliveryBucket,
723
+ WebhookDeliveryCounts,
724
+ WebhookDeliverySortId,
725
+ WebhookError,
726
+ WebhookEventCount,
727
+ WebhookName,
728
+ WebhookPayload,
729
+ WebhookRequest,
730
+ WebhookScope,
731
+ WebhookStatistics,
732
+ WebhookStatisticsInterval,
733
+ WebhookStatisticsRequest,
734
+ Webhooks,
735
+ deliveryColumns,
736
+ webhookColumns
737
+ };