@briefkasten/adapter-posthog 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lukas Mateffy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # @briefkasten/adapter-posthog
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The PostHog adapter for [briefkasten](https://www.npmjs.com/package/briefkasten): PostHog's error
4
+ tracking alerts, signed in the [Standard Webhooks](https://www.standardwebhooks.com) format, as
5
+ typed error events. A delivery more than five minutes old is refused.
6
+
7
+ ```bash
8
+ npm install briefkasten @briefkasten/adapter-posthog
9
+ ```
10
+
11
+ ```ts
12
+ import { briefkasten } from "briefkasten";
13
+ import { posthog } from "@briefkasten/adapter-posthog";
14
+
15
+ const hooks = briefkasten({
16
+ sources: { posthog: posthog({ secret: process.env.POSTHOG_WEBHOOK_SECRET ?? "" }) },
17
+ });
18
+
19
+ hooks.on("posthog:error", async (event) => {
20
+ console.log(event.body.action, event.body.title);
21
+ });
22
+
23
+ // Mount it: a fetch handler, or `hooks.node` for Express and node:http.
24
+ app.post("/webhooks/*", (c) => hooks.fetch(c.req.raw));
25
+ ```
26
+
27
+ Docs: <https://briefkasten.fabrik.computer/docs/adapters/posthog>
28
+
29
+ MIT licensed.
@@ -0,0 +1,120 @@
1
+ import { z } from "zod";
2
+ import { Adapter, AdapterBinding, AdapterInstance, AdapterSample, NewEvent, NoOptions } from "briefkasten";
3
+ //#region src/posthog-schemas.d.ts
4
+ /**
5
+ * What a PostHog error tracking alert posts to briefkasten.
6
+ *
7
+ * PostHog has no fixed webhook payload for error tracking: an alert ("Issue created",
8
+ * "Issue reopened", …) is an HTTP Webhook destination (`template-webhook`, a Hog function) that
9
+ * runs on one of error tracking's internal events (`$error_tracking_issue_created`,
10
+ * `$error_tracking_issue_reopened`, `$error_tracking_issue_resolved`, …) and posts the JSON body
11
+ * its **JSON Body** input templates. So the body is the one `docs/posthog.md` tells to paste:
12
+ *
13
+ * { "event": "{event.event}", "issue": "{event.distinct_id}", "project": "{project.id}",
14
+ * "title": "{event.properties.name}", "status": "{event.properties.status}",
15
+ * "fingerprint": "{event.properties.fingerprint}" }
16
+ *
17
+ * On these events `event.distinct_id` is the issue's id (PostHog's own alert templates key on it),
18
+ * and `project.id` is the project's numeric id. `title`, `status` and `fingerprint` are hints
19
+ * for people reading the event; `status` is missing on `_spiking`. Anything else passes through.
20
+ */
21
+ /** The prefix of error tracking's internal issue events. */
22
+ declare const EVENT_PREFIX = "$error_tracking_issue_";
23
+ declare const alertBodySchema: z.ZodObject<{
24
+ event: z.ZodString;
25
+ issue: z.ZodString;
26
+ project: z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<string, string | number>>;
27
+ title: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | undefined, string | null | undefined>>;
28
+ status: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | undefined, string | null | undefined>>;
29
+ fingerprint: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | undefined, string | null | undefined>>;
30
+ }, z.core.$loose>;
31
+ type PostHogAlertBody = z.infer<typeof alertBodySchema>;
32
+ /** The body of the `error` event this adapter publishes; the target is `<project>.<issue>`. */
33
+ declare const errorEventSchema: z.ZodObject<{
34
+ action: z.ZodString;
35
+ project: z.ZodString;
36
+ issue: z.ZodString;
37
+ title: z.ZodOptional<z.ZodString>;
38
+ status: z.ZodOptional<z.ZodString>;
39
+ fingerprint: z.ZodOptional<z.ZodString>;
40
+ delivery: z.ZodString;
41
+ at: z.ZodString;
42
+ }, z.core.$strip>;
43
+ type PostHogErrorEvent = z.infer<typeof errorEventSchema>;
44
+ /** The events this adapter publishes. */
45
+ declare const events: {
46
+ error: z.ZodObject<{
47
+ action: z.ZodString;
48
+ project: z.ZodString;
49
+ issue: z.ZodString;
50
+ title: z.ZodOptional<z.ZodString>;
51
+ status: z.ZodOptional<z.ZodString>;
52
+ fingerprint: z.ZodOptional<z.ZodString>;
53
+ delivery: z.ZodString;
54
+ at: z.ZodString;
55
+ }, z.core.$strip>;
56
+ };
57
+ //#endregion
58
+ //#region src/posthog.d.ts
59
+ /** How far a delivery's `webhook-timestamp` may be from now, either way: the spec's tolerance. */
60
+ declare const DELIVERY_WINDOW_MS: number;
61
+ /**
62
+ * PostHog needs no options: the destination's Signing secret is the source's secret, a Standard
63
+ * Webhooks secret (`whsec_` and the base64 of at least 24 bytes). The gateway makes one in that
64
+ * form when it makes a source's secret, to paste into PostHog.
65
+ */
66
+ declare const posthogOptionsSchema: z.ZodObject<{}, z.core.$strip>;
67
+ type PostHogOptions = NoOptions;
68
+ /** Whether `seconds` (a `webhook-timestamp`) is within `windowMs` of `now`. */
69
+ declare function isFresh(seconds: string, now: number, windowMs: number): boolean;
70
+ /** The action of an error tracking event (`$error_tracking_issue_reopened` → `reopened`). */
71
+ declare function actionOf(event: string): string | undefined;
72
+ /**
73
+ * The target of an issue: its project and its id. A client may treat it as the issue's key:
74
+ * fabrik's PostHog tracker keys an error the same way (`errorKey` in `fabrik-plugin-posthog`),
75
+ * and its gateway plugin reads the target as that key.
76
+ */
77
+ declare function targetOf(project: string, issue: string): string;
78
+ /** The `error` event of an alert the schema accepted. */
79
+ declare function toErrorEvent(action: string, alert: PostHogAlertBody, delivery: string, at: string): NewEvent;
80
+ /** One PostHog destination, verified with its signing secret. */
81
+ declare function posthogInstance(secret: string, now?: () => number): AdapterInstance;
82
+ /** The `posthog` adapter's definition, which a JSON config names as `"adapter": "posthog"`. */
83
+ declare const adapter: Adapter<PostHogOptions>;
84
+ /**
85
+ * The `posthog` adapter builder, for a source in a TypeScript config:
86
+ *
87
+ * sources: { posthog: posthog({ secret: env("POSTHOG_WEBHOOK_SECRET") }) }
88
+ */
89
+ declare const posthog: ((input: PostHogOptions & {
90
+ readonly secret: string | undefined;
91
+ }) => AdapterBinding<"posthog", typeof events>) & {
92
+ events: {
93
+ readonly errorTrackingIssue: {
94
+ readonly created: import("briefkasten").DeliveryBuilder;
95
+ readonly resolved: import("briefkasten").DeliveryBuilder;
96
+ };
97
+ };
98
+ };
99
+ /** The PostHog adapter's event tables, for a client's typed handlers. */
100
+ type PostHogEvents = typeof events;
101
+ //#endregion
102
+ //#region src/samples.d.ts
103
+ declare const samples: readonly AdapterSample[];
104
+ //#endregion
105
+ //#region src/signature.d.ts
106
+ /** The fewest bytes a signing secret has: the Standard Webhooks spec's, and PostHog's own check. */
107
+ declare const MIN_SECRET_BYTES = 24;
108
+ /** The key a Standard Webhooks secret stands for, or none when it is not one. */
109
+ declare function keyOf(secret: string): Buffer | undefined;
110
+ /** The `v1` signature of a delivery, base64, as PostHog computes it. */
111
+ declare function signatureOf(key: Uint8Array, id: string, timestamp: string, body: Uint8Array): string;
112
+ /** Constant-time comparison, so a near-miss signature cannot be found byte by byte. */
113
+ declare function signaturesEqual(expected: string, provided: string): boolean;
114
+ /**
115
+ * Whether `header` (space-separated `v1,<base64>` signatures: a sender rotating its secret sends
116
+ * several) holds `expected`. Each is compared, none skipped, in constant time.
117
+ */
118
+ declare function signedWith(header: string, expected: string): boolean;
119
+ //#endregion
120
+ export { DELIVERY_WINDOW_MS, EVENT_PREFIX, MIN_SECRET_BYTES, type PostHogAlertBody, type PostHogErrorEvent, type PostHogEvents, type PostHogOptions, actionOf, adapter, alertBodySchema, errorEventSchema, events, isFresh, keyOf, posthog, posthogInstance, posthogOptionsSchema, samples, signatureOf, signaturesEqual, signedWith, targetOf, toErrorEvent };
package/dist/index.mjs ADDED
@@ -0,0 +1,294 @@
1
+ import { z } from "zod";
2
+ import { builtSample, defineBinding } from "briefkasten";
3
+ import { createHmac, timingSafeEqual } from "node:crypto";
4
+ //#region src/posthog-schemas.ts
5
+ /**
6
+ * What a PostHog error tracking alert posts to briefkasten.
7
+ *
8
+ * PostHog has no fixed webhook payload for error tracking: an alert ("Issue created",
9
+ * "Issue reopened", …) is an HTTP Webhook destination (`template-webhook`, a Hog function) that
10
+ * runs on one of error tracking's internal events (`$error_tracking_issue_created`,
11
+ * `$error_tracking_issue_reopened`, `$error_tracking_issue_resolved`, …) and posts the JSON body
12
+ * its **JSON Body** input templates. So the body is the one `docs/posthog.md` tells to paste:
13
+ *
14
+ * { "event": "{event.event}", "issue": "{event.distinct_id}", "project": "{project.id}",
15
+ * "title": "{event.properties.name}", "status": "{event.properties.status}",
16
+ * "fingerprint": "{event.properties.fingerprint}" }
17
+ *
18
+ * On these events `event.distinct_id` is the issue's id (PostHog's own alert templates key on it),
19
+ * and `project.id` is the project's numeric id. `title`, `status` and `fingerprint` are hints
20
+ * for people reading the event; `status` is missing on `_spiking`. Anything else passes through.
21
+ */
22
+ /** The prefix of error tracking's internal issue events. */
23
+ const EVENT_PREFIX = "$error_tracking_issue_";
24
+ const UUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
25
+ const PROJECT$1 = /^[0-9]+$/;
26
+ /** An optional text a template may render empty: empty is absent. */
27
+ const hint = z.string().nullish().transform((value) => value === "" || value === null ? void 0 : value);
28
+ const alertBodySchema = z.object({
29
+ /** The internal event: `$error_tracking_issue_created`, `…_reopened`, `…_resolved`, … */
30
+ event: z.string().min(1),
31
+ /** The issue's id (`event.distinct_id`). */
32
+ issue: z.string().regex(UUID),
33
+ /** The project's id (`project.id`): a number, or its digits as text. */
34
+ project: z.union([z.number().int().nonnegative(), z.string().regex(PROJECT$1)]).transform((value) => String(value)),
35
+ title: hint,
36
+ status: hint,
37
+ fingerprint: hint
38
+ }).passthrough();
39
+ /** The body of the `error` event this adapter publishes; the target is `<project>.<issue>`. */
40
+ const errorEventSchema = z.object({
41
+ /** The event's last part: `created`, `reopened`, `resolved`, `suppressed`, `spiking`, … */
42
+ action: z.string(),
43
+ project: z.string(),
44
+ issue: z.string(),
45
+ title: z.string().optional(),
46
+ status: z.string().optional(),
47
+ fingerprint: z.string().optional(),
48
+ /** The delivery's `webhook-id`: the same across PostHog's retries of one delivery. */
49
+ delivery: z.string(),
50
+ /** When PostHog signed it (ISO 8601). */
51
+ at: z.string()
52
+ });
53
+ /** The events this adapter publishes. */
54
+ const events = { error: errorEventSchema };
55
+ //#endregion
56
+ //#region src/signature.ts
57
+ /**
58
+ * Standard Webhooks signatures (https://www.standardwebhooks.com), as PostHog's HTTP Webhook
59
+ * destination makes them: HMAC-SHA256, keyed with the base64-decoded secret (`whsec_` prefix
60
+ * optional), over `<webhook-id>.<webhook-timestamp>.<raw body>`, base64, sent as `v1,<base64>`.
61
+ */
62
+ const SECRET_PREFIX = "whsec_";
63
+ const SIGNATURE_VERSION = "v1,";
64
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
65
+ /** The fewest bytes a signing secret has: the Standard Webhooks spec's, and PostHog's own check. */
66
+ const MIN_SECRET_BYTES = 24;
67
+ /** The key a Standard Webhooks secret stands for, or none when it is not one. */
68
+ function keyOf(secret) {
69
+ const encoded = secret.startsWith(SECRET_PREFIX) ? secret.slice(6) : secret;
70
+ if (!BASE64.test(encoded)) return;
71
+ const key = Buffer.from(encoded, "base64");
72
+ return key.length >= 24 ? key : void 0;
73
+ }
74
+ /** The `v1` signature of a delivery, base64, as PostHog computes it. */
75
+ function signatureOf(key, id, timestamp, body) {
76
+ return createHmac("sha256", key).update(`${id}.${timestamp}.`).update(body).digest("base64");
77
+ }
78
+ /** Constant-time comparison, so a near-miss signature cannot be found byte by byte. */
79
+ function signaturesEqual(expected, provided) {
80
+ const left = Buffer.from(expected, "utf8");
81
+ const right = Buffer.from(provided, "utf8");
82
+ return left.length === right.length && timingSafeEqual(left, right);
83
+ }
84
+ /**
85
+ * Whether `header` (space-separated `v1,<base64>` signatures: a sender rotating its secret sends
86
+ * several) holds `expected`. Each is compared, none skipped, in constant time.
87
+ */
88
+ function signedWith(header, expected) {
89
+ let found = false;
90
+ for (const part of header.split(" ")) if (part.startsWith(SIGNATURE_VERSION)) found = signaturesEqual(expected, part.slice(3)) || found;
91
+ return found;
92
+ }
93
+ //#endregion
94
+ //#region src/samples.ts
95
+ /**
96
+ * PostHog's error tracking deliveries, typed: the JSON Body `docs/posthog.md` tells to paste,
97
+ * rendered for an issue (invented ids), with the fields a caller gives (`title`), signed the way
98
+ * PostHog signs (Standard Webhooks: `webhook-id`, `webhook-timestamp` in seconds,
99
+ * `webhook-signature: v1,…`), so it passes the adapter's verification and freshness check. A
100
+ * secret that is not a Standard Webhooks one gives no signature, and the adapter refuses the
101
+ * delivery as it would PostHog's.
102
+ */
103
+ const PROJECT = 12345;
104
+ const ISSUE = "01936f3a-4b5c-7d8e-9f00-112233445566";
105
+ const TITLE = "TypeError: Cannot read properties of undefined (reading 'total')";
106
+ const MS_PER_SECOND$1 = 1e3;
107
+ const sign = (payload, context) => {
108
+ const body = JSON.stringify(payload);
109
+ const timestamp = String(Math.floor(context.now / MS_PER_SECOND$1));
110
+ const key = keyOf(context.secret);
111
+ const signature = key === void 0 ? "" : signatureOf(key, context.id, timestamp, new TextEncoder().encode(body));
112
+ return {
113
+ headers: {
114
+ "content-type": "application/json",
115
+ "user-agent": "PostHog",
116
+ "webhook-id": context.id,
117
+ "webhook-timestamp": timestamp,
118
+ "webhook-signature": `v1,${signature}`
119
+ },
120
+ body
121
+ };
122
+ };
123
+ function issue(event, status) {
124
+ return (fields = {}) => ({
125
+ adapter: "posthog",
126
+ event: "error",
127
+ payload: {
128
+ event,
129
+ issue: ISSUE,
130
+ project: PROJECT,
131
+ title: fields.title ?? TITLE,
132
+ status,
133
+ fingerprint: "c0ffee"
134
+ },
135
+ sign
136
+ });
137
+ }
138
+ /** PostHog's typed event builders: `posthog.events.errorTrackingIssue.created({ title })`. */
139
+ const deliveries = { errorTrackingIssue: {
140
+ created: issue("$error_tracking_issue_created", "active"),
141
+ resolved: issue("$error_tracking_issue_resolved", "resolved")
142
+ } };
143
+ const samples = [builtSample("$error_tracking_issue_created", "A new error tracking issue was created", deliveries.errorTrackingIssue.created), builtSample("$error_tracking_issue_resolved", "An issue was resolved", deliveries.errorTrackingIssue.resolved)];
144
+ //#endregion
145
+ //#region src/posthog.ts
146
+ /**
147
+ * The PostHog adapter: an error tracking alert (an issue created, reopened, resolved, …) becomes
148
+ * an `error` event, addressed `<project>.<issue>`.
149
+ *
150
+ * PostHog's HTTP Webhook destination signs a request when it has a **Signing secret**, in one of
151
+ * two formats. This adapter takes the default one, **Standard Webhooks**
152
+ * (https://www.standardwebhooks.com), because it signs a timestamp too: `webhook-signature:
153
+ * v1,<base64>` is HMAC-SHA256, keyed with the base64-decoded secret (`whsec_` prefix optional),
154
+ * over `<webhook-id>.<webhook-timestamp>.<raw body>`; `webhook-timestamp` is in seconds, and a
155
+ * delivery more than `DELIVERY_WINDOW_MS` away from now is refused, so a captured one cannot be
156
+ * replayed later. A request with no signature, or none that matches, fails closed. The other
157
+ * format (`X-Hub-Signature-256`, the body alone) signs no time, and is not accepted.
158
+ */
159
+ const ID_HEADER = "webhook-id";
160
+ const TIMESTAMP_HEADER = "webhook-timestamp";
161
+ const SIGNATURE_HEADER = "webhook-signature";
162
+ const SECONDS = /^[0-9]+$/;
163
+ const MS_PER_SECOND = 1e3;
164
+ const ACCEPTED = 202;
165
+ const BAD_REQUEST = 400;
166
+ const UNAUTHORIZED = 401;
167
+ /** How far a delivery's `webhook-timestamp` may be from now, either way: the spec's tolerance. */
168
+ const DELIVERY_WINDOW_MS = 3e5;
169
+ /**
170
+ * PostHog needs no options: the destination's Signing secret is the source's secret, a Standard
171
+ * Webhooks secret (`whsec_` and the base64 of at least 24 bytes). The gateway makes one in that
172
+ * form when it makes a source's secret, to paste into PostHog.
173
+ */
174
+ const posthogOptionsSchema = z.object({});
175
+ /** Whether `seconds` (a `webhook-timestamp`) is within `windowMs` of `now`. */
176
+ function isFresh(seconds, now, windowMs) {
177
+ return SECONDS.test(seconds) && Math.abs(now - Number(seconds) * MS_PER_SECOND) <= windowMs;
178
+ }
179
+ /** The action of an error tracking event (`$error_tracking_issue_reopened` → `reopened`). */
180
+ function actionOf(event) {
181
+ const action = event.startsWith("$error_tracking_issue_") ? event.slice(22) : "";
182
+ return /^[a-z][a-z_]*$/.test(action) ? action : void 0;
183
+ }
184
+ /**
185
+ * The target of an issue: its project and its id. A client may treat it as the issue's key:
186
+ * fabrik's PostHog tracker keys an error the same way (`errorKey` in `fabrik-plugin-posthog`),
187
+ * and its gateway plugin reads the target as that key.
188
+ */
189
+ function targetOf(project, issue) {
190
+ return `${project}.${issue}`;
191
+ }
192
+ /** The `error` event of an alert the schema accepted. */
193
+ function toErrorEvent(action, alert, delivery, at) {
194
+ return {
195
+ event: "error",
196
+ target: targetOf(alert.project, alert.issue),
197
+ body: {
198
+ action,
199
+ project: alert.project,
200
+ issue: alert.issue,
201
+ ...alert.title === void 0 ? {} : { title: alert.title },
202
+ ...alert.status === void 0 ? {} : { status: alert.status },
203
+ ...alert.fingerprint === void 0 ? {} : { fingerprint: alert.fingerprint },
204
+ delivery,
205
+ at
206
+ }
207
+ };
208
+ }
209
+ function json(body, status) {
210
+ return new Response(JSON.stringify(body), {
211
+ status,
212
+ headers: { "content-type": "application/json" }
213
+ });
214
+ }
215
+ function refused(status, body) {
216
+ return {
217
+ response: json(body, status),
218
+ events: []
219
+ };
220
+ }
221
+ /** The fields a rejected body got wrong, path by path: no values. */
222
+ function issuesOf(error) {
223
+ return error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`);
224
+ }
225
+ /** The headers a signed delivery carries, or none when one is missing. */
226
+ function signedHeaders(request) {
227
+ const id = request.headers.get(ID_HEADER);
228
+ const timestamp = request.headers.get(TIMESTAMP_HEADER);
229
+ const signature = request.headers.get(SIGNATURE_HEADER);
230
+ return id === null || id === "" || timestamp === null || signature === null ? void 0 : {
231
+ id,
232
+ timestamp,
233
+ signature
234
+ };
235
+ }
236
+ /** One PostHog destination, verified with its signing secret. */
237
+ function posthogInstance(secret, now = () => Date.now()) {
238
+ const key = keyOf(secret);
239
+ return { async handleWebhook(request) {
240
+ const raw = new Uint8Array(await request.arrayBuffer());
241
+ const signed = signedHeaders(request);
242
+ if (key === void 0 || signed === void 0 || !signedWith(signed.signature, signatureOf(key, signed.id, signed.timestamp, raw))) return refused(UNAUTHORIZED, { error: "invalid signature" });
243
+ if (!isFresh(signed.timestamp, now(), 3e5)) return refused(UNAUTHORIZED, { error: "stale delivery" });
244
+ let decoded;
245
+ try {
246
+ decoded = JSON.parse(new TextDecoder().decode(raw));
247
+ } catch {
248
+ return refused(BAD_REQUEST, { error: "payload is not JSON" });
249
+ }
250
+ const event = z.object({ event: z.string() }).safeParse(decoded);
251
+ const action = event.success ? actionOf(event.data.event) : void 0;
252
+ if (action === void 0) return {
253
+ response: json({ ignored: event.success ? event.data.event : "unknown" }, ACCEPTED),
254
+ events: []
255
+ };
256
+ const alert = alertBodySchema.safeParse(decoded);
257
+ if (!alert.success) return refused(BAD_REQUEST, {
258
+ error: "unreadable alert",
259
+ at: issuesOf(alert.error)
260
+ });
261
+ const at = (/* @__PURE__ */ new Date(Number(signed.timestamp) * MS_PER_SECOND)).toISOString();
262
+ return {
263
+ response: json({ ok: true }, ACCEPTED),
264
+ events: [toErrorEvent(action, alert.data, signed.id, at)]
265
+ };
266
+ } };
267
+ }
268
+ /** The `posthog` adapter's definition, which a JSON config names as `"adapter": "posthog"`. */
269
+ const adapter = {
270
+ id: "posthog",
271
+ name: "PostHog",
272
+ samples,
273
+ optionsSchema: posthogOptionsSchema,
274
+ events,
275
+ targetDescription: "a PostHog error tracking issue: <project id>.<issue id>",
276
+ create: (_options, context) => posthogInstance(context.secret)
277
+ };
278
+ /**
279
+ * The `posthog` adapter builder, for a source in a TypeScript config:
280
+ *
281
+ * sources: { posthog: posthog({ secret: env("POSTHOG_WEBHOOK_SECRET") }) }
282
+ */
283
+ const posthog = Object.assign((input) => {
284
+ const { secret, ...options } = input;
285
+ return defineBinding({
286
+ id: "posthog",
287
+ events,
288
+ options,
289
+ secret,
290
+ definition: adapter
291
+ });
292
+ }, { events: deliveries });
293
+ //#endregion
294
+ export { DELIVERY_WINDOW_MS, EVENT_PREFIX, MIN_SECRET_BYTES, actionOf, adapter, alertBodySchema, errorEventSchema, events, isFresh, keyOf, posthog, posthogInstance, posthogOptionsSchema, samples, signatureOf, signaturesEqual, signedWith, targetOf, toErrorEvent };
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@briefkasten/adapter-posthog",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "PostHog adapter for briefkasten: Standard Webhooks-signed error tracking alerts as typed error events",
5
+ "keywords": [
6
+ "adapter",
7
+ "briefkasten",
8
+ "errors",
9
+ "posthog",
10
+ "standard-webhooks",
11
+ "typescript",
12
+ "webhooks"
13
+ ],
14
+ "homepage": "https://briefkasten.fabrik.computer/docs",
15
+ "bugs": {
16
+ "url": "https://github.com/mateffy/fabrik/issues"
17
+ },
18
+ "license": "MIT",
19
+ "author": "Lukas Mateffy",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/mateffy/fabrik.git",
23
+ "directory": "packages/briefkasten-adapter-posthog"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "type": "module",
31
+ "sideEffects": false,
32
+ "main": "./dist/index.mjs",
33
+ "types": "./dist/index.d.mts",
34
+ "exports": {
35
+ ".": {
36
+ "types": "./dist/index.d.mts",
37
+ "import": "./dist/index.mjs",
38
+ "default": "./dist/index.mjs"
39
+ }
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "dependencies": {
45
+ "zod": "^4.4.3",
46
+ "briefkasten": "0.1.0"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "^22.0.0",
50
+ "tsdown": "^0.22.3",
51
+ "typescript": "^5.8.0",
52
+ "vitest": "^4.0.0"
53
+ },
54
+ "engines": {
55
+ "node": ">=22"
56
+ },
57
+ "scripts": {
58
+ "build": "tsdown",
59
+ "typecheck": "tsc --noEmit",
60
+ "test": "vitest run"
61
+ }
6
62
  }