@hookieai/node 0.0.0-stage → 0.1.2

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 ADDED
@@ -0,0 +1,11 @@
1
+ # @hookieai/node changelog
2
+
3
+ ## 0.1.2 — 2026-11-29
4
+
5
+ The package's repository and StackBlitz links point at the docs repository's new home, Cusack-Enterprise-Software/Hookie-Docs. No code changes.
6
+
7
+ ## 0.1.1
8
+
9
+ The first release provides event ingestion, webhook signature verification and workspace management for Node 22+ and compatible runtimes. Receivers can use an atomic replay store to reject concurrent retries of a signed delivery.
10
+
11
+ The first release also includes Express, Hono and Next.js receiver helpers. They verify the original request bytes and pass the parsed JSON to your handler.
package/README.md CHANGED
@@ -1,3 +1,162 @@
1
- # Temporary Holding Version
1
+ # @hookieai/node
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
+ Send events to [Hookie](https://hookie.ai), verify the webhooks it delivers, and manage your workspace, from a server, a Cloudflare Worker, Deno or Bun. No dependencies, no Node-only APIs: it is `fetch` and WebCrypto, so the same code runs on Node 22+, Workers, Deno and Bun. MIT licensed.
4
+
5
+ ```sh
6
+ npm i @hookieai/node
7
+ ```
8
+
9
+ Browser forms have their own client: [`@hookieai/forms`](https://www.npmjs.com/package/@hookieai/forms).
10
+
11
+ ## Verify a webhook Hookie sent you
12
+
13
+ **Worker receiver** · [Try it in StackBlitz](https://stackblitz.com/github/Cusack-Enterprise-Software/Hookie-Docs/tree/main/examples?startScript=worker&file=worker/receiver.mjs). Its preview signs a sample with a fresh local key. Send a valid or modified sample to see Standard Webhooks verification in action.
14
+
15
+ Hookie signs every delivery twice over one timestamp, and this package checks either: `Hookie-Signature` (`t=<unix>,v1=<hex>`) and the [Standard Webhooks](https://www.standardwebhooks.com) headers (`webhook-id`, `webhook-timestamp`, `webhook-signature`). Use the destination's `whsec_...` secret (console: destination, signing secret, or `admin.destinations.getSecret(id)`).
16
+
17
+ Verify the **raw** body, exactly as received. A body you parsed and re-serialised will not verify.
18
+
19
+ ```js
20
+ import { verifyWebhook, createMemoryReplayStore } from "@hookieai/node"; // or "@hookieai/node/verify"
21
+
22
+ const replayStore = createMemoryReplayStore(); // one process; see "Replay protection"
23
+
24
+ // Cloudflare Workers, Deno, Bun, Next.js route handlers: a Request
25
+ export default {
26
+ async fetch(request, env) {
27
+ const body = await request.text();
28
+ try {
29
+ const hook = await verifyWebhook(body, request.headers, env.HOOKIE_SIGNING_SECRET, { replayStore, scheme: "standard" });
30
+ const event = JSON.parse(body);
31
+ // Deduplicate business operations on a stable id in the signed event body.
32
+ // hook.eventId is unsigned metadata, so it is not a security boundary.
33
+ return new Response("ok");
34
+ } catch (err) {
35
+ return new Response(err.reason ?? "bad request", { status: 400 }); // HookieSignatureError
36
+ }
37
+ },
38
+ };
39
+ ```
40
+
41
+
42
+ - **Timing-safe.** Comparison is `crypto.subtle.verify`, and every candidate signature is checked whether or not an earlier one matched.
43
+ - **Tolerance window.** A timestamp more than 300 s from now, in either direction, is refused (`timestamp_too_old` / `timestamp_too_new`). Tune with `toleranceSeconds`.
44
+ - **Secret rotation.** After a rotation Hookie signs with the new and the previous secret for a day. Pass both, `[current, previous]`, or either alone.
45
+ - **Replay protection.** Pass a `replayStore` (`has(id)`, `add(id, ttlSeconds)`) and a signed delivery id (Standard Webhooks) or signed timestamp/body fingerprint (Hookie) that already verified is refused (`replayed`). Hookie-only signatures do not authenticate `Hookie-Delivery-Id`, so that header is never used as the replay key. Both `Hookie-Delivery-Id` and `Hookie-Event-Id` are unsigned metadata; do not use them for security decisions. Pin `scheme: "standard"` when your sender provides Standard Webhooks, so dropping those headers cannot switch verification schemes. `createMemoryReplayStore()` is bounded and expiring but lives in one process or isolate; behind several instances, implement `claim(id, ttlSeconds)` as an atomic check-and-insert in a Durable Object, Redis (`SET NX` with expiry), or a database transaction/unique constraint. It must return `true` only for the first claimant. Separate KV reads and writes are not atomic. Stores with only `has`/`add` remain supported, but concurrent claims are serialized only within one SDK instance using the same store object. By default a key is atomically claimed as soon as its signature verifies. Hookie retries a failed delivery under the same `webhook-id`, so if you would rather accept the retry of a delivery your handler failed, use `commitReplay: "manual"` and call `await hook.commitReplay()` after you succeed. Manual mode does not reserve the key during processing; use transactional business deduplication to prevent concurrent side effects. A manual commit rejects with `replayed` if another request has already claimed the key; repeated calls on the same result share one commitment.
46
+ - **Reasons.** `HookieSignatureError.reason` is one of `missing_headers`, `malformed_signature`, `bad_timestamp`, `timestamp_too_old`, `timestamp_too_new`, `no_valid_signature`, `replayed`, `bad_secret`.
47
+
48
+ The tests check the verifier against vectors produced by Hookie's real outbound signer, and the Hookie repository fails if that signer ever changes them.
49
+
50
+ ## Receive JSON webhooks in a framework
51
+
52
+ Each adapter takes the destination signing secret and an async callback. It checks the
53
+ original request bytes using Standard Webhooks, parses the verified JSON and calls
54
+ `onEvent(event, delivery)`. Check the event's application-specific fields inside the
55
+ callback. The route returns 204 when the callback completes, 401 for a rejected
56
+ signature or replay, 400 for signed invalid JSON and 413 for an oversized body.
57
+ Exceptions from the callback go to the framework's normal error handler.
58
+
59
+ **Express** — mount this route before global JSON middleware so the handler gets a
60
+ Buffer. Set the parser's limit to match the adapter's byte limit. [Try the Express receiver in StackBlitz](https://stackblitz.com/github/Cusack-Enterprise-Software/Hookie-Docs/tree/main/receiver-examples?startScript=express&file=express.mjs)
61
+
62
+ ```js
63
+ import express from "express";
64
+ import { createWebhookHandler } from "@hookieai/node/express";
65
+
66
+ const app = express();
67
+ app.post("/hooks/hookie", express.raw({ type: "*/*", limit: "1mb", inflate: false }),
68
+ createWebhookHandler(process.env.HOOKIE_SIGNING_SECRET, async (event, delivery) => {
69
+ await saveOrder(event, delivery.id);
70
+ }));
71
+ app.use(express.json());
72
+ ```
73
+
74
+ **Hono** — the handler reads the original `c.req.raw` request. Mount it before
75
+ middleware that consumes the body. On Workers, read the secret from the request's
76
+ environment. [Try the Hono receiver in StackBlitz](https://stackblitz.com/github/Cusack-Enterprise-Software/Hookie-Docs/tree/main/receiver-examples?startScript=hono&file=hono.mjs)
77
+
78
+ ```js
79
+ import { Hono } from "hono";
80
+ import { createWebhookHandler } from "@hookieai/node/hono";
81
+
82
+ const app = new Hono();
83
+ app.post("/hooks/hookie", c =>
84
+ createWebhookHandler(c.env.HOOKIE_SIGNING_SECRET, async event => {
85
+ await saveOrder(event);
86
+ })(c));
87
+ export default app;
88
+ ```
89
+
90
+ **Next.js App Router** — export the handler directly from a route file. Next passes
91
+ the unread Fetch Request to the handler. [Try the Next.js receiver in StackBlitz](https://stackblitz.com/github/Cusack-Enterprise-Software/Hookie-Docs/tree/main/receiver-examples?startScript=next&file=next/app/api/hooks/hookie/route.js)
92
+
93
+ ```js
94
+ // app/api/hooks/hookie/route.js
95
+ import { createWebhookHandler } from "@hookieai/node/next";
96
+
97
+ export const POST = createWebhookHandler(process.env.HOOKIE_SIGNING_SECRET, async event => {
98
+ await saveOrder(event);
99
+ });
100
+ ```
101
+
102
+ All three accept a third options argument. Set `maxBodyBytes` to change the default
103
+ 1 MiB limit. Set `scheme: "hookie"` for a sender that uses only Hookie-Signature.
104
+ The `replayStore`, `toleranceSeconds` and `commitReplay` options work like
105
+ `verifyWebhook`, including calling `delivery.commitReplay()` yourself in manual mode.
106
+
107
+ ## Send events
108
+
109
+ ```js
110
+ import { Hookie } from "@hookieai/node";
111
+
112
+ const hookie = new Hookie({ ingestKey: process.env.HOOKIE_INGEST_KEY }); // ik_live_...
113
+
114
+ const r = await hookie.ingest.send({ order: "A-1", total: 42.5 }, { dataset: "orders" });
115
+ r.submissionId; // "sub_..."
116
+ r.duplicate; // true if Hookie had already stored this idempotency key
117
+ ```
118
+
119
+ - **Response timeouts.** `timeoutMs` covers receiving headers and reading the complete response body. Body transport failures are retried with the same idempotency key; they are never reported as success.
120
+ - **Idempotent by default.** Every call carries one `Idempotency-Key`, generated if you do not pass `idempotencyKey`, and the SDK's retries (network error, 5xx, burst 429; 2 by default) reuse it, so a flaky network stores one event. Pass your own key (a job id, an order id) to make your own retries safe too.
121
+ - **Endpoint URLs** are their own credential: `await hookie.ingest.sendToEndpoint("https://app.hookie.ai/acme/site/<slug>", payload)`, or `sendToEndpoint(url, payload)` with no client. https only.
122
+ - **Signed ingest.** For a key that requires signed requests, pass `signingSecret` and `X-Hookie-Signature` is added.
123
+ - `new HookieIngest({ ingestKey })` is the same client without the `Hookie` wrapper. `hookie.ingest.sendMany(payloads, { concurrency: 5 })` returns one `{ ok, result | error }` per payload.
124
+
125
+ ## Manage your workspace
126
+
127
+ ```js
128
+ const hookie = new Hookie({ apiKey: process.env.HOOKIE_API_KEY, projectId: "proj_..." }); // hk_... (Settings, API keys)
129
+
130
+ const { projects } = await hookie.admin.projects.list();
131
+ const { deliveries } = await hookie.admin.deliveries.list({ status: "dead", limit: 50 });
132
+ await hookie.admin.deliveries.replay(deliveries[0].id);
133
+ await hookie.admin.deliveries.replayMany({ status: ["dead"], since: "2026-11-01T00:00:00Z", dry_run: true });
134
+ const hits = await hookie.admin.search.events({ dataset: "orders", q: "A-1" });
135
+
136
+ for await (const d of hookie.admin.paginate((p) => hookie.admin.deliveries.list({ ...p, status: "failed" }), "deliveries")) console.log(d.id);
137
+ ```
138
+
139
+ `new HookieAdmin({ apiKey, projectId })` is the same client on its own. Helpers cover projects, webhooks (endpoints), destinations (including `getSecret` / `rotateSecret`), deliveries (`list`, `get`, `replay`, `replayMany`, `metrics`) and search (`events`, `deliveries`, `submissions`). Responses are the API's own JSON with the wire field names, and fields you do not know are yours to ignore. `hookie.admin.request(method, path, { body, query })` reaches any other `/admin/api/*` route. Every helper maps to an operation in Hookie's [OpenAPI document](https://hookie.ai/openapi.json); the repository's tests check each one against it.
140
+
141
+ Every POST carries an `Idempotency-Key` (Hookie stores the response for 24 hours). Pin an API version with `hookieVersion: "2026-09-29"`.
142
+
143
+ ## Errors
144
+
145
+ Everything the SDK throws is a `HookieError` with `status`, `reason`, `retryAfter`, `body` and `idempotencyKey`. Branch on the class:
146
+
147
+ | Class | When |
148
+ |---|---|
149
+ | `HookieNetworkError` | no answer: `reason` is `network`, `timeout` or `aborted` |
150
+ | `HookieAuthError` | 401 / 403: wrong, revoked or under-scoped key, a suspended workspace |
151
+ | `HookieValidationError` | 400 / 413 / 415 / 422; `fieldErrors` for a form endpoint's 422 |
152
+ | `HookieNotFoundError`, `HookieConflictError` | 404, 409 |
153
+ | `HookieRateLimitError` | 429; `isQuota` is true for the monthly plan quota (retrying will not help) |
154
+ | `HookieServerError` | 5xx after the retries run out |
155
+
156
+ ## Runtimes
157
+
158
+ Pass `fetch` in the options where there is no global one. `baseUrl` defaults to `https://app.hookie.ai` and must be https (http only for localhost).
159
+
160
+ ## For AI agents
161
+
162
+ The machine-readable guide is https://hookie.ai/llms.txt. An agent can register itself on the Free plan with no person involved: https://hookie.ai/agents.
package/admin.d.ts ADDED
@@ -0,0 +1,159 @@
1
+ import type { ClientOptions } from "./ingest.js";
2
+
3
+ export interface AdminClientOptions extends ClientOptions {
4
+ /** An `hk_...` admin API key (Settings -> API keys). */
5
+ apiKey: string;
6
+ /** Default project for the project-scoped helpers. */
7
+ projectId?: string;
8
+ /** Pin a dated API version, e.g. "2026-09-29" (sent as Hookie-Version). */
9
+ hookieVersion?: string;
10
+ }
11
+
12
+ export interface RequestOptions {
13
+ /** Project override for project-scoped helpers. */
14
+ projectId?: string;
15
+ idempotencyKey?: string;
16
+ signal?: AbortSignal;
17
+ retries?: number;
18
+ timeoutMs?: number;
19
+ }
20
+ export interface PageOptions extends RequestOptions {
21
+ limit?: number;
22
+ offset?: number;
23
+ }
24
+
25
+ // The shapes below name the fields the API documents (docs/openapi.json) that
26
+ // callers use most; every object also carries fields not listed, and a
27
+ // response can grow new ones. Treat unknown fields as ignorable.
28
+ export interface Project {
29
+ id: string;
30
+ name: string;
31
+ slug: string;
32
+ type: "webhook" | "ai_trigger";
33
+ ip_allowlist: string[] | null;
34
+ created_at: string;
35
+ updated_at: string;
36
+ webhook_count?: number;
37
+ [k: string]: unknown;
38
+ }
39
+ export interface Webhook {
40
+ id: string;
41
+ name?: string;
42
+ base_slug?: string;
43
+ version?: string | number;
44
+ dataset?: string;
45
+ enabled?: boolean | number;
46
+ public_url?: string;
47
+ [k: string]: unknown;
48
+ }
49
+ export interface CreatedWebhook {
50
+ id: string;
51
+ slug: string;
52
+ webhook_slug: string;
53
+ base_slug?: string;
54
+ version?: string | number;
55
+ public_path?: string;
56
+ /** The URL that is this endpoint's credential. */
57
+ public_url?: string;
58
+ [k: string]: unknown;
59
+ }
60
+ export interface Destination {
61
+ id: string;
62
+ name: string;
63
+ url?: string;
64
+ enabled?: boolean | number;
65
+ [k: string]: unknown;
66
+ }
67
+ export interface Delivery {
68
+ id: string;
69
+ destination_id: string;
70
+ destination_name: string;
71
+ event_id: string;
72
+ status: string;
73
+ [k: string]: unknown;
74
+ }
75
+ export interface SearchPage<T> {
76
+ entity: string;
77
+ count: number;
78
+ total: number;
79
+ limit: number;
80
+ offset: number;
81
+ results: T[];
82
+ }
83
+ export interface DeliveryFilter {
84
+ /** e.g. "dead", "failed", "delivered". */
85
+ status?: string;
86
+ destination_id?: string;
87
+ since?: string;
88
+ until?: string;
89
+ }
90
+ export interface ReplayFilter {
91
+ destination_id?: string;
92
+ /** dead, failed, or both (the default). */
93
+ status?: string | Array<"dead" | "failed">;
94
+ since?: string;
95
+ until?: string;
96
+ limit?: number;
97
+ /** Count what would be replayed without replaying it. */
98
+ dry_run?: boolean;
99
+ }
100
+
101
+ export type OperationId =
102
+ | "getMe" | "listProjects" | "createProject" | "getProject" | "updateProject" | "deleteProject"
103
+ | "listWebhooks" | "createWebhook" | "getWebhook" | "updateWebhook" | "deleteWebhook" | "rotateWebhookUrl"
104
+ | "listDestinations" | "createDestination" | "getDestination" | "updateDestination" | "deleteDestination"
105
+ | "getDestinationSecret" | "rotateDestinationSecret" | "expireDestinationPreviousSecret"
106
+ | "listDeliveries" | "getDelivery" | "replayDelivery" | "replayDeliveries" | "getDeliveryMetrics"
107
+ | "searchEvents" | "searchDeliveries" | "searchSubmissions";
108
+
109
+ export const OPERATIONS: Readonly<Record<OperationId, readonly [method: string, path: string]>>;
110
+
111
+ export class HookieAdmin {
112
+ constructor(options: AdminClientOptions);
113
+ projectId?: string;
114
+
115
+ projects: {
116
+ list(o?: RequestOptions): Promise<{ projects: Project[] }>;
117
+ get(projectId: string, o?: RequestOptions): Promise<{ project: Project }>;
118
+ create(body: { name: string; type: "webhook" | "ai_trigger"; [k: string]: unknown }, o?: RequestOptions): Promise<{ project: Project; webhook?: CreatedWebhook }>;
119
+ update(projectId: string, body: { name?: string; ip_allowlist?: string[] | null }, o?: RequestOptions): Promise<{ ok: boolean }>;
120
+ delete(projectId: string, o?: RequestOptions): Promise<unknown>;
121
+ };
122
+ webhooks: {
123
+ list(o?: PageOptions): Promise<{ webhooks: Webhook[]; total?: number; limit?: number; offset?: number }>;
124
+ get(id: string, o?: RequestOptions): Promise<{ webhook: Webhook }>;
125
+ create(body: { name: string; slug?: string; dataset?: string; enabled?: boolean; [k: string]: unknown }, o?: RequestOptions): Promise<CreatedWebhook>;
126
+ update(id: string, body: Record<string, unknown>, o?: RequestOptions): Promise<{ ok: boolean; [k: string]: unknown }>;
127
+ delete(id: string, o?: RequestOptions): Promise<unknown>;
128
+ rotate(id: string, o?: RequestOptions): Promise<unknown>;
129
+ };
130
+ destinations: {
131
+ list(o?: PageOptions): Promise<{ destinations: Destination[]; total?: number; limit?: number; offset?: number }>;
132
+ get(id: string, o?: RequestOptions): Promise<{ destination: Destination }>;
133
+ create(body: { name: string; url?: string; [k: string]: unknown }, o?: RequestOptions): Promise<{ id: string; [k: string]: unknown }>;
134
+ update(id: string, body: Record<string, unknown>, o?: RequestOptions): Promise<{ ok: boolean; [k: string]: unknown }>;
135
+ delete(id: string, o?: RequestOptions): Promise<unknown>;
136
+ getSecret(id: string, o?: RequestOptions): Promise<{ signing_secret: string }>;
137
+ rotateSecret(id: string, o?: RequestOptions): Promise<{ signing_secret: string; previous_secret_expires_at: string }>;
138
+ expirePreviousSecret(id: string, o?: RequestOptions): Promise<unknown>;
139
+ };
140
+ deliveries: {
141
+ list(o?: PageOptions & DeliveryFilter): Promise<{ deliveries: Delivery[]; total?: number }>;
142
+ get(id: string, o?: RequestOptions): Promise<{ delivery: Delivery; attempts: unknown[]; attempts_not_recorded: number }>;
143
+ /** Queues a new delivery; answers its id. */
144
+ replay(id: string, o?: RequestOptions): Promise<{ id: string }>;
145
+ replayMany(filter?: ReplayFilter, o?: RequestOptions): Promise<Record<string, unknown>>;
146
+ metrics(o?: RequestOptions & { query?: Record<string, string | number> }): Promise<Record<string, unknown>>;
147
+ };
148
+ search: {
149
+ events(filter?: { dataset?: string; q?: string; since?: string; until?: string; limit?: number; offset?: number }, o?: RequestOptions): Promise<SearchPage<Record<string, unknown>>>;
150
+ deliveries(filter?: DeliveryFilter & { response_code?: number; min_latency_ms?: number; limit?: number; offset?: number }, o?: RequestOptions): Promise<SearchPage<Delivery>>;
151
+ submissions(filter?: { q?: string; source?: string; status?: string; endpoint_id?: string; since?: string; until?: string; limit?: number; offset?: number }, o?: RequestOptions): Promise<SearchPage<Record<string, unknown>>>;
152
+ };
153
+ me(o?: RequestOptions): Promise<Record<string, unknown>>;
154
+
155
+ call(operationId: OperationId, pathParams?: Record<string, string>, o?: RequestOptions & { body?: unknown; query?: Record<string, unknown> }): Promise<any>;
156
+ /** Any /admin/api/* route, returning the parsed JSON body. */
157
+ request(method: string, path: string, o?: RequestOptions & { body?: unknown; query?: Record<string, unknown> }): Promise<any>;
158
+ paginate<T = unknown>(fetchPage: (page: { limit: number; offset: number }) => Promise<any>, key: string, pageSize?: number): AsyncGenerator<T>;
159
+ }
package/admin.mjs ADDED
@@ -0,0 +1,179 @@
1
+ // @hookieai/node: the admin API client (#471).
2
+ //
3
+ // Typed helpers over the existing /admin/api/* routes with an `hk_...` admin
4
+ // API key (Settings -> API keys). `OPERATIONS` is the table of what this client
5
+ // calls, by the operationId in docs/openapi.json; test/admin.test.mjs checks
6
+ // every entry against that file, so a renamed or removed route fails the build
7
+ // instead of failing a customer. `request()` reaches any route not wrapped here.
8
+ //
9
+ // Every POST carries an Idempotency-Key (generated when you do not pass one),
10
+ // which Hookie stores for 24 hours, so a retried create runs once. Responses
11
+ // are the API's own JSON, unchanged: field names are the wire names.
12
+
13
+ import { HookieError } from "./errors.mjs";
14
+ import { DEFAULT_BASE_URL, newIdempotencyKey, normalizeBaseUrl, send } from "./http.mjs";
15
+
16
+ const P = "/admin/api/projects/{project_id}";
17
+
18
+ /** operationId -> [method, path template]. Checked against docs/openapi.json in CI. */
19
+ export const OPERATIONS = {
20
+ getMe: ["GET", "/admin/api/me"],
21
+ listProjects: ["GET", "/admin/api/projects"],
22
+ createProject: ["POST", "/admin/api/projects"],
23
+ getProject: ["GET", `${P}`],
24
+ updateProject: ["PATCH", `${P}`],
25
+ deleteProject: ["DELETE", `${P}`],
26
+ listWebhooks: ["GET", `${P}/webhooks`],
27
+ createWebhook: ["POST", `${P}/webhooks`],
28
+ getWebhook: ["GET", `${P}/webhooks/{id}`],
29
+ updateWebhook: ["PATCH", `${P}/webhooks/{id}`],
30
+ deleteWebhook: ["DELETE", `${P}/webhooks/{id}`],
31
+ rotateWebhookUrl: ["POST", `${P}/webhooks/{id}/rotate`],
32
+ listDestinations: ["GET", `${P}/destinations`],
33
+ createDestination: ["POST", `${P}/destinations`],
34
+ getDestination: ["GET", `${P}/destinations/{id}`],
35
+ updateDestination: ["PATCH", `${P}/destinations/{id}`],
36
+ deleteDestination: ["DELETE", `${P}/destinations/{id}`],
37
+ getDestinationSecret: ["GET", `${P}/destinations/{id}/secret`],
38
+ rotateDestinationSecret: ["POST", `${P}/destinations/{id}/rotate-secret`],
39
+ expireDestinationPreviousSecret: ["POST", `${P}/destinations/{id}/expire-previous-secret`],
40
+ listDeliveries: ["GET", `${P}/deliveries`],
41
+ getDelivery: ["GET", `${P}/deliveries/{id}`],
42
+ replayDelivery: ["POST", `${P}/deliveries/{id}/replay`],
43
+ replayDeliveries: ["POST", `${P}/deliveries/replay`],
44
+ getDeliveryMetrics: ["GET", `${P}/deliveries/metrics`],
45
+ searchEvents: ["POST", `${P}/search/events`],
46
+ searchDeliveries: ["POST", `${P}/search/deliveries`],
47
+ searchSubmissions: ["POST", `${P}/search/submissions`],
48
+ };
49
+ // EXTENSION POINT (#468 delivery controls, #469 transforms): their routes and
50
+ // fields are added to OPERATIONS and to the resource helpers below (and to
51
+ // admin.d.ts) by those issues, once their API shapes exist in docs/openapi.json.
52
+ // `HookieAdmin#request()` already reaches them in the meantime.
53
+
54
+ function fill(template, params) {
55
+ return template.replace(/\{(\w+)\}/g, (_, name) => {
56
+ const v = params[name];
57
+ if (v === undefined || v === null || v === "") throw new HookieError(`Missing path parameter: ${name}`);
58
+ return encodeURIComponent(String(v));
59
+ });
60
+ }
61
+
62
+ function qs(query) {
63
+ const u = new URLSearchParams();
64
+ for (const [k, v] of Object.entries(query ?? {})) {
65
+ if (v === undefined || v === null) continue;
66
+ u.set(k, Array.isArray(v) ? v.join(",") : String(v));
67
+ }
68
+ const s = u.toString();
69
+ return s ? `?${s}` : "";
70
+ }
71
+
72
+ export class HookieAdmin {
73
+ /** @param {import("./admin.d.ts").AdminClientOptions} options */
74
+ constructor(options) {
75
+ if (!options?.apiKey) throw new HookieError("An admin API key is required: new HookieAdmin({ apiKey: 'hk_...' }).");
76
+ this.config = { ...options, baseUrl: normalizeBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL) };
77
+ this.projectId = options.projectId;
78
+ this.hookieVersion = options.hookieVersion;
79
+
80
+ const proj = (o) => o?.projectId ?? this.projectId;
81
+ const op = (id, params, o, extra = {}) => this.call(id, { ...params, project_id: params.project_id ?? proj(o) }, { ...o, ...extra });
82
+
83
+ this.projects = {
84
+ list: (o) => this.call("listProjects", {}, o),
85
+ get: (projectId, o) => this.call("getProject", { project_id: projectId }, o),
86
+ create: (body, o) => this.call("createProject", {}, { ...o, body }),
87
+ update: (projectId, body, o) => this.call("updateProject", { project_id: projectId }, { ...o, body }),
88
+ delete: (projectId, o) => this.call("deleteProject", { project_id: projectId }, o),
89
+ };
90
+ this.webhooks = {
91
+ list: (o) => op("listWebhooks", {}, o, { query: { limit: o?.limit, offset: o?.offset } }),
92
+ get: (id, o) => op("getWebhook", { id }, o),
93
+ create: (body, o) => op("createWebhook", {}, o, { body }),
94
+ update: (id, body, o) => op("updateWebhook", { id }, o, { body }),
95
+ delete: (id, o) => op("deleteWebhook", { id }, o),
96
+ /** Issues a new public URL; the response carries it. */
97
+ rotate: (id, o) => op("rotateWebhookUrl", { id }, o),
98
+ };
99
+ this.destinations = {
100
+ list: (o) => op("listDestinations", {}, o, { query: { limit: o?.limit, offset: o?.offset } }),
101
+ get: (id, o) => op("getDestination", { id }, o),
102
+ create: (body, o) => op("createDestination", {}, o, { body }),
103
+ update: (id, body, o) => op("updateDestination", { id }, o, { body }),
104
+ delete: (id, o) => op("deleteDestination", { id }, o),
105
+ /** The `whsec_...` secret to hand to `verifyWebhook`. Not available to connected agents. */
106
+ getSecret: (id, o) => op("getDestinationSecret", { id }, o),
107
+ rotateSecret: (id, o) => op("rotateDestinationSecret", { id }, o),
108
+ expirePreviousSecret: (id, o) => op("expireDestinationPreviousSecret", { id }, o),
109
+ };
110
+ this.deliveries = {
111
+ /** @param {{ status?: string, destination_id?: string, since?: string, until?: string, limit?: number, offset?: number, projectId?: string }} [o] */
112
+ list: (o) => op("listDeliveries", {}, o, { query: { status: o?.status, destination_id: o?.destination_id, since: o?.since, until: o?.until, limit: o?.limit, offset: o?.offset } }),
113
+ get: (id, o) => op("getDelivery", { id }, o),
114
+ replay: (id, o) => op("replayDelivery", { id }, o),
115
+ /** Replay every dead/failed delivery matching the filter. Use `dry_run: true` to count first. */
116
+ replayMany: (filter, o) => op("replayDeliveries", {}, o, { body: filter ?? {} }),
117
+ metrics: (o) => op("getDeliveryMetrics", {}, o, { query: o?.query }),
118
+ };
119
+ this.search = {
120
+ events: (filter, o) => op("searchEvents", {}, o, { body: filter ?? {} }),
121
+ deliveries: (filter, o) => op("searchDeliveries", {}, o, { body: filter ?? {} }),
122
+ submissions: (filter, o) => op("searchSubmissions", {}, o, { body: filter ?? {} }),
123
+ };
124
+ this.me = (o) => this.call("getMe", {}, o);
125
+ }
126
+
127
+ /**
128
+ * Call an operation from OPERATIONS by operationId.
129
+ * @param {keyof typeof OPERATIONS} operationId
130
+ * @param {Record<string, string>} pathParams
131
+ * @param {{ body?: unknown, query?: Record<string, unknown>, idempotencyKey?: string, signal?: AbortSignal, retries?: number, timeoutMs?: number }} [o]
132
+ */
133
+ async call(operationId, pathParams = {}, o = {}) {
134
+ const def = OPERATIONS[operationId];
135
+ if (!def) throw new HookieError(`Unknown operation: ${operationId}`);
136
+ return this.request(def[0], fill(def[1], pathParams), o);
137
+ }
138
+
139
+ /**
140
+ * Any admin API route: `admin.request("GET", "/admin/api/audit", { query: { limit: 10 } })`.
141
+ * Returns the parsed JSON body.
142
+ */
143
+ async request(method, path, o = {}) {
144
+ if (!path.startsWith("/")) throw new HookieError("path must start with /");
145
+ const headers = { Authorization: `Bearer ${this.config.apiKey}` };
146
+ if (this.hookieVersion) headers["Hookie-Version"] = this.hookieVersion;
147
+ let body;
148
+ if (o.body !== undefined) {
149
+ body = JSON.stringify(o.body);
150
+ headers["Content-Type"] = "application/json";
151
+ }
152
+ const idempotencyKey = method === "POST" ? (o.idempotencyKey ?? newIdempotencyKey()) : undefined;
153
+ const res = await send(this.config, {
154
+ method,
155
+ url: this.config.baseUrl + path + qs(o.query),
156
+ headers,
157
+ body,
158
+ signal: o.signal,
159
+ idempotencyKey,
160
+ retries: o.retries,
161
+ timeoutMs: o.timeoutMs,
162
+ });
163
+ return res.body;
164
+ }
165
+
166
+ /**
167
+ * Walk a paged list: `for await (const d of admin.paginate((p) => admin.deliveries.list({ ...p, status: "dead" }), "deliveries"))`.
168
+ * @param {(page: { limit: number, offset: number }) => Promise<any>} fetchPage
169
+ * @param {string} key the array's property in the response
170
+ */
171
+ async *paginate(fetchPage, key, pageSize = 100) {
172
+ for (let offset = 0; ; offset += pageSize) {
173
+ const page = await fetchPage({ limit: pageSize, offset });
174
+ const rows = page?.[key] ?? [];
175
+ yield* rows;
176
+ if (rows.length < pageSize) return;
177
+ }
178
+ }
179
+ }
package/errors.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ export interface HookieErrorInfo {
2
+ status?: number;
3
+ reason?: string;
4
+ retryAfter?: number;
5
+ body?: unknown;
6
+ cause?: unknown;
7
+ idempotencyKey?: string;
8
+ }
9
+
10
+ export class HookieError extends Error {
11
+ constructor(message: string, info?: HookieErrorInfo);
12
+ /** HTTP status; 0 when no answer arrived. */
13
+ status: number;
14
+ /** Hookie's machine reason (quota_exceeded, form_invalid, workspace_suspended, ...), or timeout / aborted / network for a HookieNetworkError. */
15
+ reason?: string;
16
+ /** Seconds, from a 429. */
17
+ retryAfter?: number;
18
+ body: any;
19
+ idempotencyKey?: string;
20
+ }
21
+ export class HookieNetworkError extends HookieError {}
22
+ export class HookieAuthError extends HookieError {}
23
+ export class HookieValidationError extends HookieError {
24
+ /** From a form endpoint's 422: field name to what is wrong with it. */
25
+ fieldErrors?: Record<string, string>;
26
+ }
27
+ export class HookieNotFoundError extends HookieError {}
28
+ export class HookieConflictError extends HookieError {}
29
+ export class HookieRateLimitError extends HookieError {
30
+ /** True for the monthly plan quota, where retrying will not help. */
31
+ readonly isQuota: boolean;
32
+ }
33
+ export class HookieServerError extends HookieError {}
34
+
35
+ export type SignatureFailureReason =
36
+ | "missing_headers"
37
+ | "malformed_signature"
38
+ | "bad_timestamp"
39
+ | "timestamp_too_old"
40
+ | "timestamp_too_new"
41
+ | "no_valid_signature"
42
+ | "replayed"
43
+ | "bad_secret";
44
+
45
+ export class HookieSignatureError extends Error {
46
+ constructor(reason: SignatureFailureReason, message: string);
47
+ reason: SignatureFailureReason;
48
+ }
49
+
50
+ export function errorFromResponse(status: number, body: unknown, headers?: Headers, idempotencyKey?: string): HookieError;