@1st-flock/donations-embed-node 1.0.1 → 1.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/dist/index.cjs +16 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +27 -3
- package/dist/index.d.ts +27 -3
- package/dist/index.js +16 -7
- package/dist/index.js.map +1 -1
- package/dist/{webhooks-DBoxlrQm.d.cts → webhooks-Dp_QzFm7.d.cts} +1 -1
- package/dist/{webhooks-DBoxlrQm.d.ts → webhooks-Dp_QzFm7.d.ts} +1 -1
- package/dist/webhooks.cjs.map +1 -1
- package/dist/webhooks.d.cts +1 -1
- package/dist/webhooks.d.ts +1 -1
- package/dist/webhooks.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -4,7 +4,7 @@ var crypto = require('crypto');
|
|
|
4
4
|
var buffer = require('buffer');
|
|
5
5
|
|
|
6
6
|
// src/_const.ts
|
|
7
|
-
var SDK_VERSION = "1.
|
|
7
|
+
var SDK_VERSION = "1.1.0";
|
|
8
8
|
var DEFAULT_BASE_URL = "https://api.1stflock.com";
|
|
9
9
|
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
10
10
|
var DEFAULT_MAX_RETRIES = 3;
|
|
@@ -362,20 +362,29 @@ var HttpTransport = class {
|
|
|
362
362
|
};
|
|
363
363
|
|
|
364
364
|
// src/client.ts
|
|
365
|
-
function
|
|
365
|
+
function environmentFromSecretKey(apiKey) {
|
|
366
366
|
if (typeof apiKey !== "string" || apiKey.length === 0) {
|
|
367
367
|
throw new TypeError("apiKey must be a non-empty string");
|
|
368
368
|
}
|
|
369
|
-
if (
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
369
|
+
if (apiKey.startsWith("sk_live_")) {
|
|
370
|
+
return "live";
|
|
371
|
+
}
|
|
372
|
+
if (apiKey.startsWith("sk_test_")) {
|
|
373
|
+
return "test";
|
|
373
374
|
}
|
|
375
|
+
throw new TypeError(
|
|
376
|
+
"apiKey must be a secret key (sk_live_\u2026 or sk_test_\u2026); publishable keys (pk_\u2026) are browser-only and not accepted server-side"
|
|
377
|
+
);
|
|
374
378
|
}
|
|
375
379
|
var Client = class {
|
|
380
|
+
/**
|
|
381
|
+
* Resolved environment (`"live"` or `"test"`) derived from the
|
|
382
|
+
* supplied secret key. Read-only; set once in the constructor.
|
|
383
|
+
*/
|
|
384
|
+
environment;
|
|
376
385
|
transport;
|
|
377
386
|
constructor(options) {
|
|
378
|
-
|
|
387
|
+
this.environment = environmentFromSecretKey(options.apiKey);
|
|
379
388
|
this.transport = new HttpTransport({
|
|
380
389
|
apiKey: options.apiKey,
|
|
381
390
|
baseUrl: options.baseUrl,
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/_const.ts","../src/_idempotency.ts","../src/errors.ts","../src/_http.ts","../src/client.ts","../src/models/events.ts","../src/webhooks.ts"],"names":["randomUUID","idempotencyKey","createHmac","Buffer","timingSafeEqual"],"mappings":";;;;;;AAYO,IAAM,WAAA,GAAc;AAGpB,IAAM,gBAAA,GAAmB,0BAAA;AAGzB,IAAM,kBAAA,GAAqB,GAAA;AAG3B,IAAM,mBAAA,GAAsB,CAAA;AAU5B,IAAM,iCAAA,GAAoC;ACdjD,IAAM,cAAA,GAAiB,GAAA;AAMvB,IAAM,WAAA,GAAc,yBAAA;AAeb,SAAS,eAAe,KAAA,EAAwB;AACtD,EAAA,MAAM,OAAOA,iBAAA,EAAW;AACxB,EAAA,IAAI,UAAU,MAAA,EAAW;AACxB,IAAA,OAAO,IAAA;AAAA,EACR;AACA,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,CAAC,WAAA,CAAY,IAAA,CAAK,KAAK,CAAA,EAAG;AAC1D,IAAA,MAAM,IAAI,SAAA;AAAA,MACT;AAAA,KACD;AAAA,EACD;AACA,EAAA,MAAM,GAAA,GAAM,CAAA,EAAG,KAAK,CA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,EAAA,KAAA,MAAW,KAAK,OAAA,EAAS;AAIxB,IAAA,IAAI,oBAAA,CAAqB,QAAA,EAAU,CAAC,CAAA,EAAG;AACtC,MAAA,OAAA,GAAU,IAAA;AAAA,IACX;AAAA,EACD;AACA,EAAA,IAAI,CAAC,OAAA,EAAS;AACb,IAAA,MAAM,IAAI,qBAAA;AAAA,MACT;AAAA,KACD;AAAA,EACD;AAIA,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACH,IAAA,OAAA,GAAUA,aAAAA,CAAO,IAAA,CAAK,SAAS,CAAA,CAAE,SAAS,MAAM,CAAA;AAAA,EACjD,SAAS,GAAA,EAAK;AACb,IAAA,MAAM,IAAI,kBAAA;AAAA,MACT,CAAA,iCAAA,EAAqC,IAAc,OAAO,CAAA;AAAA,KAC3D;AAAA,EACD;AACA,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI;AACH,IAAA,OAAA,GAAU,IAAA,CAAK,MAAM,OAAO,CAAA;AAAA,EAC7B,SAAS,GAAA,EAAK;AACb,IAAA,MAAM,IAAI,kBAAA;AAAA,MACT,CAAA,oCAAA,EAAwC,IAAc,OAAO,CAAA;AAAA,KAC9D;AAAA,EACD;AAEA,EAAA,IAAI,CAAC,cAAA,CAAe,OAAO,CAAA,EAAG;AAC7B,IAAA,MAAM,IAAI,kBAAA;AAAA,MACT;AAAA,KACD;AAAA,EACD;AACA,EAAA,OAAO,OAAA;AACR","file":"index.cjs","sourcesContent":["/**\n * Internal constants shared across the SDK.\n *\n * Kept in a tiny module so internal modules (HTTP transport, webhook\n * verifier) can import without dragging in the public surface.\n */\n\n/**\n * Single source of truth for the SDK's marketed version. Every outbound\n * request advertises this in the User-Agent header so the platform can\n * attribute traffic and warn customers running EOL versions.\n */\nexport const SDK_VERSION = \"1.0.0\";\n\n/** Default platform API base URL; overridable per-Client. */\nexport const DEFAULT_BASE_URL = \"https://api.1stflock.com\";\n\n/** Per-request timeout in milliseconds. */\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\n/** Number of additional attempts on retryable failures (5xx + transient). */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * Webhook timestamp tolerance in seconds — per spec §6.7.\n *\n * The verifier rejects deliveries whose timestamp falls outside this\n * window even if the HMAC matches. Customers should not need to override\n * this in production; the parameter exists so unit tests can simulate\n * clock drift.\n */\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n","/**\n * Idempotency-key helper.\n *\n * The platform's idempotency contract: replaying a request with the same\n * `Idempotency-Key` returns the original response without performing the\n * side effect a second time. Keys are scoped per (`api_key`, `endpoint`)\n * and persisted for 24 hours.\n *\n * This module exposes {@link idempotencyKey}, a tiny convenience wrapper\n * that prefixes a fresh UUID4 with a use-case tag so observability tooling\n * can group related retries (e.g. all `refund:*` keys belong to the\n * refund flow). Callers MAY also supply their own keys directly.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\n/** Match the OpenAPI `Idempotency-Key` schema constraint (max 255 chars). */\nconst MAX_KEY_LENGTH = 255;\n\n/**\n * Conservative validation for the use-case tag — keep it printable ASCII\n * so the resulting key fits cleanly in HTTP headers and log lines.\n */\nconst USE_CASE_RE = /^[a-z0-9][a-z0-9_\\-.]*$/;\n\n/**\n * Generate a fresh idempotency key tagged with a use-case prefix.\n *\n * The returned key has the form `\"<usage>:<uuid4>\"`, e.g.\n * `\"refund:1f2dab36-2a55-4f11-bdc8-2a2a4a95b001\"`. When `usage` is\n * omitted, returns a bare UUID4 with no prefix.\n *\n * @param usage - Optional short tag describing the operation\n * (`\"refund\"`, `\"cancel-recurring\"`, `\"replay-confirm\"`). When\n * supplied, must match `^[a-z0-9][a-z0-9_\\-.]*$`; an oddly-shaped\n * tag throws a `TypeError`.\n * @returns A string suitable for the `Idempotency-Key` HTTP header.\n */\nexport function idempotencyKey(usage?: string): string {\n\tconst uuid = randomUUID();\n\tif (usage === undefined) {\n\t\treturn uuid;\n\t}\n\tif (typeof usage !== \"string\" || !USE_CASE_RE.test(usage)) {\n\t\tthrow new TypeError(\n\t\t\t\"idempotency usage must be a non-empty lowercase ASCII tag matching /^[a-z0-9][a-z0-9_\\\\-.]*$/\",\n\t\t);\n\t}\n\tconst key = `${usage}:${uuid}`;\n\tif (key.length > MAX_KEY_LENGTH) {\n\t\t// Practically impossible (use_case + UUID4 is well under 255), but\n\t\t// we enforce the contract explicitly so a future caller can't blow\n\t\t// past the limit by passing a 250-char tag.\n\t\tthrow new RangeError(\n\t\t\t`generated idempotency key exceeds ${MAX_KEY_LENGTH} chars`,\n\t\t);\n\t}\n\treturn key;\n}\n","/**\n * Typed error hierarchy raised by the SDK.\n *\n * The base type is {@link ApiError}. All transport-level failures (4xx /\n * 5xx) surface as concrete subclasses so caller code can branch on type\n * rather than parsing status codes directly. Webhook verification has its\n * own dedicated exceptions ({@link WebhookSignatureError},\n * {@link WebhookTimestampError}) so middleware can return a single\n * `401 Unauthorized` without leaking which check failed.\n *\n * Every exception captures the raw error code + message returned by the\n * service when one is available, so callers can pivot on\n * `error.code === \"invalid_cursor\"` without re-deserializing the body.\n */\n\n/** Base class for every exception raised by this SDK. */\nexport class DonationsEmbedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"DonationsEmbedError\";\n\t\t// Restore the prototype chain after the super call so `instanceof`\n\t\t// works across module / bundle boundaries on older Node versions.\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/** Optional structured init bag accepted by every {@link ApiError} subclass. */\nexport interface ApiErrorInit {\n\t/** Stable, machine-readable error identifier (e.g. `\"invalid_cursor\"`). */\n\tcode?: string | null;\n\t/** Optional, error-specific extra data the service emitted. */\n\tdetails?: Record<string, unknown> | null;\n\t/** Server-issued correlation ID from the `x-request-id` response header. */\n\trequestId?: string | null;\n}\n\n/**\n * Raised when the API returns a non-2xx status code.\n *\n * Concrete subclasses below ({@link AuthError}, {@link NotFoundError},\n * etc.) cover the common status codes; an `ApiError` instance is returned\n * for any other non-2xx response.\n */\nexport class ApiError extends DonationsEmbedError {\n\treadonly statusCode: number;\n\treadonly code: string | null;\n\toverride readonly message: string;\n\treadonly details: Record<string, unknown> | null;\n\treadonly requestId: string | null;\n\n\tconstructor(statusCode: number, message: string, init: ApiErrorInit = {}) {\n\t\tconst code = init.code ?? null;\n\t\tconst requestId = init.requestId ?? null;\n\t\tconst prefix =\n\t\t\tcode !== null ? `[${statusCode} ${code}]` : `[${statusCode}]`;\n\t\tconst formatted =\n\t\t\trequestId !== null\n\t\t\t\t? `${prefix} ${message} (request_id=${requestId})`\n\t\t\t\t: `${prefix} ${message}`;\n\t\t// Pass the bare message to `Error` so `err.message` reads cleanly,\n\t\t// then override `toString()` to produce the formatted version with\n\t\t// the bracketed prefix and request id. Production callers typically\n\t\t// log `String(err)` (which calls `toString`) — they get the rich\n\t\t// form. Code that introspects `err.message` directly gets the bare\n\t\t// human string without prefix noise.\n\t\tsuper(message);\n\t\tthis.name = \"ApiError\";\n\t\tthis.statusCode = statusCode;\n\t\tthis.code = code;\n\t\tthis.message = message;\n\t\tthis.details = init.details ?? null;\n\t\tthis.requestId = requestId;\n\t\t// Stash the formatted form so `toString()` can return it.\n\t\tObject.defineProperty(this, \"_formatted\", {\n\t\t\tvalue: formatted,\n\t\t\tenumerable: false,\n\t\t\twritable: false,\n\t\t});\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n\n\toverride toString(): string {\n\t\t// `Error.prototype.toString()` returns \"<name>: <message>\". For our\n\t\t// API errors, callers want the bracketed prefix + request id so\n\t\t// they can grep logs. We synthesize the rich form here.\n\t\tconst formatted = (this as unknown as { _formatted?: string })._formatted;\n\t\treturn formatted ? `${this.name}: ${formatted}` : super.toString();\n\t}\n}\n\n/**\n * Raised on a `401 Unauthorized` response.\n *\n * Common causes: revoked secret key, malformed bearer token, expired\n * session, or the token was issued for a different environment (test vs.\n * live) than the URL being called.\n */\nexport class AuthError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"AuthError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised on a `403 Forbidden` response.\n *\n * Common causes: the secret key has been frozen by automatic protection,\n * the caller's RBAC scope is insufficient, or the action is disabled for\n * the organization.\n */\nexport class ForbiddenError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"ForbiddenError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised on a `404 Not Found` response.\n *\n * Note: cross-organization lookups collapse to `404` to avoid confirming\n * that an object exists in another tenant.\n */\nexport class NotFoundError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"NotFoundError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised on `400 Bad Request` or `422 Unprocessable Entity`.\n *\n * The originating request body failed schema validation. Inspect\n * `details` for the offending field path (e.g.\n * `{ loc: [\"body\", \"amount_cents\"] }`).\n */\nexport class ValidationError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"ValidationError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised on a `409 Conflict` response.\n *\n * Common causes: attempting to refund a donation that is already fully\n * refunded, or cancelling a recurring schedule whose state forbids the\n * transition.\n */\nexport class ConflictError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"ConflictError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/** Raised on a `410 Gone` response (terminal session error). */\nexport class GoneError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"GoneError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised on a `429 Too Many Requests` response.\n *\n * The caller should wait `retryAfterSeconds` before retrying. The SDK\n * does not auto-retry rate-limited requests by default — back-pressure\n * is a caller-controlled concern.\n */\nexport class RateLimitError extends ApiError {\n\treadonly retryAfterSeconds: number | null;\n\n\tconstructor(\n\t\tstatusCode: number,\n\t\tmessage: string,\n\t\tinit: ApiErrorInit & { retryAfterSeconds?: number | null } = {},\n\t) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"RateLimitError\";\n\t\tthis.retryAfterSeconds = init.retryAfterSeconds ?? null;\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised on a `502 Bad Gateway` response.\n *\n * Indicates an upstream payment-processor failure. The original request\n * is safe to retry — it has not been performed.\n */\nexport class BadGatewayError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"BadGatewayError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/** Raised on a `503 Service Unavailable` response. */\nexport class ServiceUnavailableError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"ServiceUnavailableError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/** Base class for webhook signature-verification failures. */\nexport class WebhookError extends DonationsEmbedError {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"WebhookError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised when webhook signature verification fails.\n *\n * This may indicate a wrong shared secret, a tampered request body, or\n * that the signature header was not produced by 1st Flock. Callers MUST\n * return an HTTP 401 (or drop the request) without enqueueing the event.\n */\nexport class WebhookSignatureError extends WebhookError {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"WebhookSignatureError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised when the webhook timestamp is outside the 5-minute tolerance.\n *\n * This is a replay-prevention check; callers MUST treat it as a\n * verification failure and return `401` without processing the event.\n */\nexport class WebhookTimestampError extends WebhookError {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"WebhookTimestampError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised when the signature header is structurally malformed.\n *\n * Examples: missing `t=` segment, no `v1=` segments, non-integer\n * timestamp, etc. The request did not parse as a signed delivery.\n */\nexport class WebhookFormatError extends WebhookError {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"WebhookFormatError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n","/**\n * Internal HTTP transport — typed errors, retry, and idempotency forwarding.\n *\n * The {@link HttpTransport} class wraps Node 18+'s native global `fetch`\n * and applies the SDK's cross-cutting policies on every request:\n *\n * - Adds the `Authorization: Bearer <api_key>` header.\n * - Adds a `User-Agent` header identifying the SDK + Node version so the\n * platform can attribute traffic and warn customers running EOL\n * versions.\n * - Forwards an optional `Idempotency-Key` header.\n * - Maps non-2xx responses to typed exceptions\n * ({@link ApiError} and subclasses).\n * - Retries 5xx responses with exponential backoff + jitter; honors the\n * `Retry-After` header on `429` (no auto-retry — back-pressure is a\n * caller-controlled concern).\n *\n * The transport is internal — public callers always interact through\n * {@link Client} from `client.ts`.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport {\n\tDEFAULT_BASE_URL,\n\tDEFAULT_MAX_RETRIES,\n\tDEFAULT_TIMEOUT_MS,\n\tSDK_VERSION,\n} from \"./_const.js\";\nimport {\n\tApiError,\n\ttype ApiErrorInit,\n\tAuthError,\n\tBadGatewayError,\n\tConflictError,\n\tForbiddenError,\n\tGoneError,\n\tNotFoundError,\n\tRateLimitError,\n\tServiceUnavailableError,\n\tValidationError,\n} from \"./errors.js\";\n\n/** Status codes the transport will retry (idempotently). */\nconst RETRYABLE_STATUS_CODES = new Set([500, 502, 503, 504]);\n\n/**\n * Logger interface matching the subset of `console` we use. Allows\n * callers to plug in pino / winston / a no-op logger without depending\n * on a particular logging library.\n */\nexport interface Logger {\n\tdebug(message: string, ...args: unknown[]): void;\n}\n\n/**\n * The portion of WHATWG `fetch` we rely on. Typed loosely so callers\n * can inject a mock without bringing in `undici-types` if they don't\n * need to.\n */\nexport type FetchLike = typeof globalThis.fetch;\n\n/** Options accepted by {@link HttpTransport}. */\nexport interface HttpTransportOptions {\n\tapiKey: string;\n\tbaseUrl?: string;\n\tfetch?: FetchLike;\n\tmaxRetries?: number;\n\t/** Per-request timeout in milliseconds. */\n\ttimeoutMs?: number;\n\tlogger?: Logger;\n}\n\n/** Per-request inputs to {@link HttpTransport.request}. */\nexport interface RequestOptions {\n\tmethod: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\tpath: string;\n\tquery?: Record<string, string | number | boolean | null | undefined>;\n\tbody?: unknown;\n\tidempotencyKey?: string;\n}\n\n/** Build the SDK's `User-Agent` string. */\nfunction buildUserAgent(): string {\n\tconst nodeVersion = process.versions.node;\n\treturn `@1st-flock/donations-embed-node/${SDK_VERSION} node/${nodeVersion}`;\n}\n\n/**\n * Drop `null` / `undefined` entries from the query bag before they get\n * serialized into the literal strings `\"null\"` / `\"undefined\"`.\n */\nfunction buildQueryString(query: RequestOptions[\"query\"]): string {\n\tif (!query) return \"\";\n\tconst params = new URLSearchParams();\n\tfor (const [k, v] of Object.entries(query)) {\n\t\tif (v === null || v === undefined) continue;\n\t\tparams.append(k, String(v));\n\t}\n\tconst s = params.toString();\n\treturn s.length === 0 ? \"\" : `?${s}`;\n}\n\n/**\n * Parse a numeric `Retry-After` header into seconds. The HTTP spec also\n * permits an HTTP-date format; we accept seconds (as integer or float)\n * and silently return `null` for date-based values rather than\n * synthesizing a delay.\n */\nfunction parseRetryAfter(value: string | null): number | null {\n\tif (value === null) return null;\n\tconst n = Number.parseFloat(value.trim());\n\treturn Number.isFinite(n) ? n : null;\n}\n\n/**\n * Sleep with jitter for `delayMs` milliseconds. Exposed via a function so\n * tests can spy on retry timing without `setTimeout` polluting the test\n * runtime.\n */\nfunction sleep(delayMs: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, delayMs));\n}\n\n/**\n * Compute the next backoff delay in milliseconds using exponential\n * backoff with jitter. `attempt` is 1-indexed; the first retry waits\n * roughly 250-500ms, the second 500-1000ms, etc., capped at 20 seconds.\n */\nfunction backoffDelayMs(attempt: number): number {\n\tconst base = Math.min(20_000, 250 * 2 ** (attempt - 1));\n\t// Half-jitter — between 50% and 100% of the base delay.\n\treturn base / 2 + Math.random() * (base / 2);\n}\n\n/** Internal HTTP transport. Not exported from the package surface. */\nexport class HttpTransport {\n\tprivate readonly apiKey: string;\n\tprivate readonly baseUrl: string;\n\tprivate readonly fetchFn: FetchLike;\n\tprivate readonly maxRetries: number;\n\tprivate readonly timeoutMs: number;\n\tprivate readonly logger: Logger;\n\tprivate readonly userAgent: string;\n\n\tconstructor(opts: HttpTransportOptions) {\n\t\tthis.apiKey = opts.apiKey;\n\t\tthis.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n\t\tthis.fetchFn = opts.fetch ?? globalThis.fetch;\n\t\tif (typeof this.fetchFn !== \"function\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"global fetch is unavailable; pass `fetch` explicitly or run on Node 18+\",\n\t\t\t);\n\t\t}\n\t\tthis.maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES;\n\t\tthis.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\t\tthis.logger = opts.logger ?? { debug: () => undefined };\n\t\tthis.userAgent = buildUserAgent();\n\t}\n\n\t/**\n\t * Send a request and return the parsed JSON response body.\n\t *\n\t * Returns `null` for `204 No Content`; throws a typed\n\t * {@link ApiError} subclass on every non-2xx status code that\n\t * survives the retry policy.\n\t */\n\tasync request<T>(opts: RequestOptions): Promise<T> {\n\t\tconst url = `${this.baseUrl}${opts.path}${buildQueryString(opts.query)}`;\n\t\tconst headers = this.buildHeaders(\n\t\t\topts.idempotencyKey,\n\t\t\topts.body !== undefined,\n\t\t);\n\t\tconst bodyJson =\n\t\t\topts.body !== undefined ? JSON.stringify(opts.body) : undefined;\n\n\t\tlet lastResponse: Response | null = null;\n\t\tlet attempt = 0;\n\t\t// The total budget is 1 initial attempt + maxRetries follow-ups.\n\t\tconst totalAttempts = Math.max(1, this.maxRetries + 1);\n\t\twhile (attempt < totalAttempts) {\n\t\t\tattempt += 1;\n\t\t\ttry {\n\t\t\t\tconst res = await this.sendOnce(url, opts.method, headers, bodyJson);\n\t\t\t\tlastResponse = res;\n\t\t\t\tif (RETRYABLE_STATUS_CODES.has(res.status)) {\n\t\t\t\t\tif (attempt < totalAttempts) {\n\t\t\t\t\t\tconst delay = backoffDelayMs(attempt);\n\t\t\t\t\t\tthis.logger.debug(\n\t\t\t\t\t\t\t`donations-embed: retrying ${opts.method} ${opts.path} after ${res.status} (attempt ${attempt})`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait sleep(delay);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (res.status >= 400) {\n\t\t\t\t\tthrow await this.buildErrorFromResponse(res);\n\t\t\t\t}\n\t\t\t\treturn (await this.parseResponseBody(res)) as T;\n\t\t\t} catch (err) {\n\t\t\t\t// `fetch` throws on network errors / aborts — those are\n\t\t\t\t// retryable. ApiError instances we threw ourselves above are\n\t\t\t\t// final and should propagate.\n\t\t\t\tif (err instanceof ApiError) throw err;\n\t\t\t\tif (attempt < totalAttempts) {\n\t\t\t\t\tconst delay = backoffDelayMs(attempt);\n\t\t\t\t\tthis.logger.debug(\n\t\t\t\t\t\t`donations-embed: retrying ${opts.method} ${opts.path} after transport error (attempt ${attempt}): ${(err as Error).message}`,\n\t\t\t\t\t);\n\t\t\t\t\tawait sleep(delay);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\t// Should never reach here — the loop always returns or throws — but\n\t\t// TypeScript's flow analysis can't see that.\n\t\tif (lastResponse !== null) {\n\t\t\tthrow await this.buildErrorFromResponse(lastResponse);\n\t\t}\n\t\tthrow new ApiError(0, \"request did not produce a response\");\n\t}\n\n\tprivate buildHeaders(\n\t\tidempotencyKey: string | undefined,\n\t\thasBody: boolean,\n\t): Record<string, string> {\n\t\tconst headers: Record<string, string> = {\n\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t\"User-Agent\": this.userAgent,\n\t\t\tAccept: \"application/json\",\n\t\t};\n\t\tif (hasBody) {\n\t\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\t}\n\t\tif (idempotencyKey !== undefined) {\n\t\t\theaders[\"Idempotency-Key\"] = idempotencyKey;\n\t\t}\n\t\treturn headers;\n\t}\n\n\tprivate async sendOnce(\n\t\turl: string,\n\t\tmethod: RequestOptions[\"method\"],\n\t\theaders: Record<string, string>,\n\t\tbody: string | undefined,\n\t): Promise<Response> {\n\t\tconst controller = new AbortController();\n\t\tconst timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\t\ttry {\n\t\t\treturn await this.fetchFn(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody,\n\t\t\t\tsignal: controller.signal,\n\t\t\t});\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t}\n\n\tprivate async parseResponseBody(res: Response): Promise<unknown> {\n\t\tif (res.status === 204) return null;\n\t\tconst text = await res.text();\n\t\tif (text.length === 0) return null;\n\t\ttry {\n\t\t\treturn JSON.parse(text);\n\t\t} catch (err) {\n\t\t\tthrow new ApiError(\n\t\t\t\tres.status,\n\t\t\t\t`response body did not parse as JSON: ${(err as Error).message}`,\n\t\t\t\t{ requestId: res.headers.get(\"x-request-id\") },\n\t\t\t);\n\t\t}\n\t}\n\n\t/** Map a 4xx / 5xx response onto the right {@link ApiError} subclass. */\n\tprivate async buildErrorFromResponse(res: Response): Promise<ApiError> {\n\t\tconst requestId = res.headers.get(\"x-request-id\");\n\t\tconst retryAfter = parseRetryAfter(res.headers.get(\"retry-after\"));\n\n\t\tlet code: string | null = null;\n\t\tlet message = res.statusText || `HTTP ${res.status}`;\n\t\tlet details: Record<string, unknown> | null = null;\n\t\ttry {\n\t\t\tconst text = await res.text();\n\t\t\tif (text.length > 0) {\n\t\t\t\tconst payload = JSON.parse(text) as Record<string, unknown>;\n\t\t\t\tif (typeof payload === \"object\" && payload !== null) {\n\t\t\t\t\tif (typeof payload.code === \"string\") code = payload.code;\n\t\t\t\t\tif (typeof payload.message === \"string\") message = payload.message;\n\t\t\t\t\tconst rawDetails = payload.details;\n\t\t\t\t\tif (\n\t\t\t\t\t\ttypeof rawDetails === \"object\" &&\n\t\t\t\t\t\trawDetails !== null &&\n\t\t\t\t\t\t!Array.isArray(rawDetails)\n\t\t\t\t\t) {\n\t\t\t\t\t\tdetails = rawDetails as Record<string, unknown>;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Non-JSON error body — fall through with the statusText.\n\t\t}\n\n\t\tconst init: ApiErrorInit = { code, details, requestId };\n\t\tconst status = res.status;\n\t\tswitch (status) {\n\t\t\tcase 401:\n\t\t\t\treturn new AuthError(status, message, init);\n\t\t\tcase 403:\n\t\t\t\treturn new ForbiddenError(status, message, init);\n\t\t\tcase 404:\n\t\t\t\treturn new NotFoundError(status, message, init);\n\t\t\tcase 400:\n\t\t\tcase 422:\n\t\t\t\treturn new ValidationError(status, message, init);\n\t\t\tcase 409:\n\t\t\t\treturn new ConflictError(status, message, init);\n\t\t\tcase 410:\n\t\t\t\treturn new GoneError(status, message, init);\n\t\t\tcase 429:\n\t\t\t\treturn new RateLimitError(status, message, {\n\t\t\t\t\t...init,\n\t\t\t\t\tretryAfterSeconds: retryAfter,\n\t\t\t\t});\n\t\t\tcase 502:\n\t\t\t\treturn new BadGatewayError(status, message, init);\n\t\t\tcase 503:\n\t\t\t\treturn new ServiceUnavailableError(status, message, init);\n\t\t\tdefault:\n\t\t\t\treturn new ApiError(status, message, init);\n\t\t}\n\t}\n}\n\n/**\n * Internal helper exposed for tests — convert anything that quacks like a\n * `Response` body into a `Buffer`. Currently unused outside tests but\n * kept here so the test surface doesn't reach into Node-only utilities.\n */\nexport function toBuffer(value: ArrayBuffer | Uint8Array | string): Buffer {\n\tif (typeof value === \"string\") return Buffer.from(value, \"utf8\");\n\tif (value instanceof Uint8Array) return Buffer.from(value);\n\treturn Buffer.from(value);\n}\n","/**\n * `Client` — entry point for the Donations Embed Customer SDK.\n *\n * Every method maps to a documented endpoint under the `/v1/embed/` path\n * prefix. All inputs and outputs are typed via the shapes in\n * `models/`. Errors surface as typed exceptions from `errors.ts`.\n *\n * Example:\n * ```ts\n * import { Client } from \"@1st-flock/donations-embed-node\";\n *\n * const client = new Client({ apiKey: process.env.FLOCK_SECRET_KEY! });\n * const page = await client.listDonations({ limit: 20 });\n * for (const donation of page.donations) {\n * console.log(donation.id, donation.gross_amount_cents);\n * }\n * ```\n */\n\nimport { type FetchLike, HttpTransport, type Logger } from \"./_http.js\";\nimport type {\n\tDonation,\n\tDonationListResponse,\n\tRefundResponse,\n} from \"./models/donations.js\";\nimport type {\n\tRecurringCancelResponse,\n\tRecurringListResponse,\n\tRecurringStatus,\n} from \"./models/recurring.js\";\nimport type {\n\tTestableWebhookEventType,\n\tWebhookTestResponse,\n} from \"./models/webhook-test.js\";\n\n/** Constructor options for {@link Client}. */\nexport interface ClientOptions {\n\t/** Secret API key (`sk_live_*` or `sk_test_*`). */\n\tapiKey: string;\n\t/**\n\t * API base URL. Defaults to `https://api.1stflock.com`; point at\n\t * `https://api.sandbox.1stflock.com` to hit the sandbox environment.\n\t */\n\tbaseUrl?: string;\n\t/**\n\t * Optional `fetch` implementation override. Defaults to the global\n\t * `fetch` shipped in Node 18+. Useful for tests, custom retry/proxy\n\t * stacks, or alternative runtimes.\n\t */\n\tfetch?: FetchLike;\n\t/**\n\t * Number of retries on retryable failures (5xx + transient network\n\t * errors). The original attempt counts separately — `retries: 3`\n\t * performs at most 4 requests. Defaults to 3.\n\t */\n\tretries?: number;\n\t/** Per-request timeout in milliseconds. Defaults to 30000. */\n\ttimeout?: number;\n\t/**\n\t * Optional logger. Used at DEBUG for transient transport errors that\n\t * trigger a retry. Defaults to a no-op.\n\t */\n\tlogger?: Logger;\n}\n\n/** Optional inputs supported by `listDonations`. */\nexport interface ListDonationsParams {\n\tcursor?: string;\n\tlimit?: number;\n\tfundId?: string;\n\tdonorEmail?: string;\n}\n\n/** Optional inputs supported by `refundDonation`. */\nexport interface RefundDonationParams {\n\t/**\n\t * Refund amount in cents. Omit (or pass `null` / `undefined`) to\n\t * refund the full donation. When supplied, must be >= 1.\n\t */\n\tamountCents?: number;\n\t/** Optional internal note attached to the refund record. */\n\treason?: string;\n}\n\n/** Optional inputs supported by `listRecurring`. */\nexport interface ListRecurringParams {\n\tcursor?: string;\n\tlimit?: number;\n\tstatus?: RecurringStatus;\n}\n\n/** Per-call options that can carry an idempotency key. */\nexport interface IdempotentCallOptions {\n\tidempotencyKey?: string;\n}\n\n/**\n * Reject `pk_*` keys, missing keys, and other obviously-wrong inputs.\n *\n * The customer SDK requires a secret key (`sk_live_*` or `sk_test_*`).\n * We catch the wrong shape at construction time so callers don't see a\n * confusing 401 from the platform.\n */\nfunction validateSecretKeyFormat(apiKey: unknown): asserts apiKey is string {\n\tif (typeof apiKey !== \"string\" || apiKey.length === 0) {\n\t\tthrow new TypeError(\"apiKey must be a non-empty string\");\n\t}\n\tif (!apiKey.startsWith(\"sk_live_\") && !apiKey.startsWith(\"sk_test_\")) {\n\t\tthrow new TypeError(\n\t\t\t\"apiKey must be a secret key (sk_live_… or sk_test_…); publishable keys (pk_…) are browser-only and not accepted server-side\",\n\t\t);\n\t}\n}\n\n/**\n * `Client` — typed access to the Donations Embed Customer SDK endpoints.\n */\nexport class Client {\n\tprivate readonly transport: HttpTransport;\n\n\tconstructor(options: ClientOptions) {\n\t\tvalidateSecretKeyFormat(options.apiKey);\n\t\tthis.transport = new HttpTransport({\n\t\t\tapiKey: options.apiKey,\n\t\t\tbaseUrl: options.baseUrl,\n\t\t\tfetch: options.fetch,\n\t\t\tmaxRetries: options.retries,\n\t\t\ttimeoutMs: options.timeout,\n\t\t\tlogger: options.logger,\n\t\t});\n\t}\n\n\t// ---------------------------------------------------------------- donations\n\n\t/**\n\t * List donations, ordered `(created_at DESC, id DESC)`.\n\t *\n\t * @param params - Optional cursor / limit / fund / donor filters.\n\t * @returns A page of donations plus an optional `next_cursor`.\n\t */\n\tlistDonations(\n\t\tparams: ListDonationsParams = {},\n\t): Promise<DonationListResponse> {\n\t\treturn this.transport.request<DonationListResponse>({\n\t\t\tmethod: \"GET\",\n\t\t\tpath: \"/v1/embed/donations\",\n\t\t\tquery: {\n\t\t\t\tcursor: params.cursor,\n\t\t\t\tlimit: params.limit,\n\t\t\t\tfund_id: params.fundId,\n\t\t\t\tdonor_email: params.donorEmail,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Fetch a single donation by ID.\n\t *\n\t * Cross-organization access collapses to `404` (raises\n\t * {@link NotFoundError}).\n\t */\n\tgetDonation(donationId: string): Promise<Donation> {\n\t\treturn this.transport.request<Donation>({\n\t\t\tmethod: \"GET\",\n\t\t\tpath: `/v1/embed/donations/${encodeURIComponent(donationId)}`,\n\t\t});\n\t}\n\n\t/**\n\t * Refund a donation in full or part.\n\t *\n\t * @param donationId - The donation to refund.\n\t * @param params - Optional amount + reason.\n\t * @param options - Optional idempotency key (use\n\t * {@link idempotencyKey} to generate one tagged with a use-case\n\t * prefix).\n\t * @returns The {@link RefundResponse} describing the issued refund.\n\t * Idempotent replays return the original response without\n\t * re-contacting the gateway.\n\t */\n\trefundDonation(\n\t\tdonationId: string,\n\t\tparams: RefundDonationParams = {},\n\t\toptions: IdempotentCallOptions = {},\n\t): Promise<RefundResponse> {\n\t\tconst body: Record<string, unknown> = {};\n\t\tif (params.amountCents !== undefined) {\n\t\t\tbody.amount_cents = params.amountCents;\n\t\t}\n\t\tif (params.reason !== undefined) {\n\t\t\tbody.reason = params.reason;\n\t\t}\n\t\treturn this.transport.request<RefundResponse>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: `/v1/embed/donations/${encodeURIComponent(donationId)}/refund`,\n\t\t\tbody,\n\t\t\tidempotencyKey: options.idempotencyKey,\n\t\t});\n\t}\n\n\t// ----------------------------------------------------------------- recurring\n\n\t/**\n\t * List recurring schedules, ordered `(created_at DESC, id DESC)`.\n\t *\n\t * @returns A page of recurring schedules plus an optional `next_cursor`.\n\t */\n\tlistRecurring(\n\t\tparams: ListRecurringParams = {},\n\t): Promise<RecurringListResponse> {\n\t\treturn this.transport.request<RecurringListResponse>({\n\t\t\tmethod: \"GET\",\n\t\t\tpath: \"/v1/embed/recurring\",\n\t\t\tquery: {\n\t\t\t\tcursor: params.cursor,\n\t\t\t\tlimit: params.limit,\n\t\t\t\tstatus: params.status,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Cancel a recurring schedule.\n\t *\n\t * Idempotent: a second call against an already-cancelled schedule\n\t * returns `already_cancelled: true` without re-emitting a webhook.\n\t */\n\tcancelRecurring(\n\t\trecurringId: string,\n\t\toptions: IdempotentCallOptions = {},\n\t): Promise<RecurringCancelResponse> {\n\t\treturn this.transport.request<RecurringCancelResponse>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: `/v1/embed/recurring/${encodeURIComponent(recurringId)}/cancel`,\n\t\t\tidempotencyKey: options.idempotencyKey,\n\t\t});\n\t}\n\n\t// ------------------------------------------------------------------ webhooks\n\n\t/**\n\t * Queue a synthetic webhook event for delivery.\n\t *\n\t * The synthetic event's `data.object.synthetic` flag is set so\n\t * downstream code can branch on it during integration testing.\n\t *\n\t * @param eventType - Which event type to fire. Defaults to\n\t * `\"donation.created\"`.\n\t */\n\ttestWebhook(\n\t\teventType: TestableWebhookEventType = \"donation.created\",\n\t): Promise<WebhookTestResponse> {\n\t\treturn this.transport.request<WebhookTestResponse>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: \"/v1/embed/webhooks/test\",\n\t\t\tbody: { event_type: eventType },\n\t\t});\n\t}\n}\n","/**\n * Webhook event payload models — discriminated union over `type`.\n *\n * Each concrete event extends {@link WebhookEnvelopeBase} (the canonical\n * envelope) and adds a `data` field whose shape varies per event type.\n * {@link WebhookEvent} is the discriminated union of every concrete event,\n * so a `switch (event.type)` block narrows `event.data.object` to the\n * right shape automatically.\n *\n * Example:\n * ```ts\n * import { verifyWebhook } from \"@1st-flock/donations-embed-node\";\n *\n * const event = verifyWebhook(rawBody, signatureHeader, secret);\n * switch (event.type) {\n * case \"donation.completed\":\n * // event.data.object is DonationEventObject — typed.\n * enqueueReceipt(event.data.object);\n * break;\n * case \"donation.refunded\":\n * // event.data.object includes refund_amount_cents.\n * reverseReceipt(event.data.object);\n * break;\n * }\n * ```\n */\n\nimport type { DonationStatus, PaymentMethodType } from \"./donations.js\";\nimport type { RecurringInterval, RecurringStatus } from \"./recurring.js\";\n\n/** Stable union of every event type emitted by the platform. */\nexport type WebhookEventType =\n\t| \"donation.created\"\n\t| \"donation.completed\"\n\t| \"donation.failed\"\n\t| \"donation.refunded\"\n\t| \"recurring.activated\"\n\t| \"recurring.payment_succeeded\"\n\t| \"recurring.payment_failed\"\n\t| \"recurring.cancelled\"\n\t| \"key.frozen\";\n\n/** Reason a key pair was automatically frozen by abuse-detection. */\nexport type KeyFrozenReason = \"card_testing_detected\";\n\n// ---------------------------------------------------------------------------\n// Inline sub-objects shared by multiple event payloads\n// ---------------------------------------------------------------------------\n\n/**\n * Donor identity carried inside donation event payloads.\n *\n * Inline subset of the donor model; does not include the address since\n * webhook payloads omit it for compactness.\n */\nexport interface DonationEventDonor {\n\tname: string;\n\temail: string;\n}\n\n/** Payment-method snapshot inside a donation event payload. */\nexport interface EventPaymentMethod {\n\ttype: PaymentMethodType;\n\tlast4: string;\n\t/** Card brand; null for ACH. */\n\tbrand?: string | null;\n}\n\n/** Per-fund allocation inside a donation event payload (no fund name). */\nexport interface DonationEventFundAllocation {\n\tfund_id: string;\n\tamount_cents: number;\n}\n\n// ---------------------------------------------------------------------------\n// Per-event `data.object` payload shapes\n// ---------------------------------------------------------------------------\n\n/** Donation-shaped payload — used by completed / failed events. */\nexport interface DonationEventObject {\n\tid: string;\n\tconfirmation_id: string;\n\tdonor: DonationEventDonor;\n\tgross_amount_cents: number;\n\tfee_amount_cents: number;\n\tnet_amount_cents: number;\n\tpayment_method: EventPaymentMethod;\n\tprocessor_transaction_id?: string | null;\n\tstatus: DonationStatus;\n\tcreated_at?: string | null;\n\tfunds?: DonationEventFundAllocation[];\n}\n\n/** Refund variant — extends donation payload with refund metadata. */\nexport interface DonationRefundedEventObject extends DonationEventObject {\n\trefund_amount_cents: number;\n\t/** Vendor-neutral refund identifier. */\n\trefund_transaction_id?: string | null;\n}\n\n/**\n * Session-shaped payload for the `donation.created` event.\n *\n * Note: at this point there is no donation row yet — the embed has only\n * just opened a session. Correlate to the eventual donation via the\n * `donation_id` returned by `/v1/embed/sessions/{id}/confirm`.\n */\nexport interface DonationCreatedEventObject {\n\tsession_id: string;\n\torganization_id: string;\n\tamount_cents?: number | null;\n\tfund_ids?: string[];\n}\n\n/**\n * Recurring-schedule payload — used by `recurring.activated`,\n * `recurring.payment_succeeded`, `recurring.payment_failed`.\n */\nexport interface RecurringEventObject {\n\tid: string;\n\tdonor: DonationEventDonor;\n\tamount_cents: number;\n\tinterval: RecurringInterval;\n\tinterval_count: number;\n\tstatus: RecurringStatus;\n\tprocessor_subscription_id?: string | null;\n\tcreated_at?: string | null;\n}\n\n/** Minimal payload for `recurring.cancelled`. */\nexport interface RecurringCancelledEventObject {\n\trecurring_id: string;\n\tprocessor_subscription_id?: string | null;\n}\n\n/** Payload for `key.frozen` — emitted by automatic protection. */\nexport interface KeyFrozenEventObject {\n\tkey_pair_id: string;\n\t/** Truncated prefix of the publishable key (safe to log). */\n\tpk_prefix: string;\n\treason: KeyFrozenReason;\n\tdecline_count_window?: number | null;\n\twindow_seconds?: number | null;\n\tfrozen_at: string;\n}\n\n// ---------------------------------------------------------------------------\n// Concrete event envelopes (discriminated by `type`)\n// ---------------------------------------------------------------------------\n\n/**\n * Fields shared by every webhook event envelope. Mirrors OpenAPI\n * `WebhookEnvelope`; concrete subclasses pin `type` to a literal so the\n * discriminator can route correctly.\n */\nexport interface WebhookEnvelopeBase {\n\t/** Globally unique event ID. Echoed in `Flock-Event-Id` for dedup. */\n\tid: string;\n\t/** Unix epoch seconds at event creation. */\n\tcreated: number;\n\t/** True for live-mode events; false for test-mode. */\n\tlive_mode: boolean;\n}\n\n/** Donor opened the embed and a session was created (no donation row yet). */\nexport interface DonationCreatedEvent extends WebhookEnvelopeBase {\n\ttype: \"donation.created\";\n\tdata: { object: DonationCreatedEventObject };\n}\n\n/** Donation succeeded. */\nexport interface DonationCompletedEvent extends WebhookEnvelopeBase {\n\ttype: \"donation.completed\";\n\tdata: { object: DonationEventObject };\n}\n\n/** Donation declined or terminated before completion. */\nexport interface DonationFailedEvent extends WebhookEnvelopeBase {\n\ttype: \"donation.failed\";\n\tdata: { object: DonationEventObject };\n}\n\n/** Refund (full or partial) succeeded. */\nexport interface DonationRefundedEvent extends WebhookEnvelopeBase {\n\ttype: \"donation.refunded\";\n\tdata: { object: DonationRefundedEventObject };\n}\n\n/** Recurring schedule created and the first charge succeeded. */\nexport interface RecurringActivatedEvent extends WebhookEnvelopeBase {\n\ttype: \"recurring.activated\";\n\tdata: {\n\t\tobject: RecurringEventObject;\n\t\t/** The first underlying charge that activated this schedule. */\n\t\tdonation?: DonationEventObject | null;\n\t};\n}\n\n/** Per-cycle charge against a recurring schedule succeeded. */\nexport interface RecurringPaymentSucceededEvent extends WebhookEnvelopeBase {\n\ttype: \"recurring.payment_succeeded\";\n\tdata: {\n\t\tobject: RecurringEventObject;\n\t\t/** The successful per-cycle charge. */\n\t\tdonation?: DonationEventObject | null;\n\t};\n}\n\n/** Per-cycle charge against a recurring schedule failed. */\nexport interface RecurringPaymentFailedEvent extends WebhookEnvelopeBase {\n\ttype: \"recurring.payment_failed\";\n\tdata: {\n\t\tobject: RecurringEventObject;\n\t\t/** The failed per-cycle charge attempt, if available. */\n\t\tdonation?: DonationEventObject | null;\n\t};\n}\n\n/** Recurring schedule was cancelled (by customer, donor, or platform). */\nexport interface RecurringCancelledEvent extends WebhookEnvelopeBase {\n\ttype: \"recurring.cancelled\";\n\tdata: { object: RecurringCancelledEventObject };\n}\n\n/** Key pair was automatically frozen by abuse-detection. */\nexport interface KeyFrozenEvent extends WebhookEnvelopeBase {\n\ttype: \"key.frozen\";\n\tdata: { object: KeyFrozenEventObject };\n}\n\n/**\n * Discriminated union of every concrete webhook event type.\n *\n * The `type` field acts as a discriminator. A `switch` block on\n * `event.type` narrows `event.data.object` to the correct shape for the\n * branch.\n */\nexport type WebhookEvent =\n\t| DonationCreatedEvent\n\t| DonationCompletedEvent\n\t| DonationFailedEvent\n\t| DonationRefundedEvent\n\t| RecurringActivatedEvent\n\t| RecurringPaymentSucceededEvent\n\t| RecurringPaymentFailedEvent\n\t| RecurringCancelledEvent\n\t| KeyFrozenEvent;\n\n/** Alias for {@link WebhookEvent} matching the OpenAPI `WebhookEnvelope` name. */\nexport type WebhookEnvelope = WebhookEvent;\n\n// ---------------------------------------------------------------------------\n// Runtime parsing helpers\n// ---------------------------------------------------------------------------\n\n/**\n * The set of recognized event-type discriminator strings, exposed for\n * runtime checks (e.g. logging unknown types). Kept in sync with\n * {@link WebhookEventType} by construction.\n */\nexport const WEBHOOK_EVENT_TYPES: readonly WebhookEventType[] = [\n\t\"donation.created\",\n\t\"donation.completed\",\n\t\"donation.failed\",\n\t\"donation.refunded\",\n\t\"recurring.activated\",\n\t\"recurring.payment_succeeded\",\n\t\"recurring.payment_failed\",\n\t\"recurring.cancelled\",\n\t\"key.frozen\",\n] as const;\n\n/**\n * Type guard: returns `true` when `value` is structurally a\n * {@link WebhookEvent} (has the required envelope fields plus a known\n * discriminator and a `data.object` payload).\n *\n * This is intentionally a *shape* check and not a deep schema validation —\n * the discriminated union does not exist at runtime, and we keep the SDK\n * dependency-free (no Zod). Callers that need exhaustive validation can\n * pivot on `event.type` after the guard returns true.\n */\nexport function isWebhookEvent(value: unknown): value is WebhookEvent {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst v = value as Record<string, unknown>;\n\tif (typeof v.id !== \"string\") return false;\n\tif (typeof v.created !== \"number\") return false;\n\tif (typeof v.live_mode !== \"boolean\") return false;\n\tif (typeof v.type !== \"string\") return false;\n\tif (!WEBHOOK_EVENT_TYPES.includes(v.type as WebhookEventType)) return false;\n\tif (typeof v.data !== \"object\" || v.data === null) return false;\n\tconst data = v.data as Record<string, unknown>;\n\tif (typeof data.object !== \"object\" || data.object === null) return false;\n\treturn true;\n}\n","/**\n * HMAC-SHA256 webhook signature verification.\n *\n * Wire format on the `Flock-Signature` header (per spec §6.7):\n * ```\n * t=<unix_ts>,v1=<hmac_sha256_hex>[,v1=<hmac_sha256_hex>]\n * ```\n *\n * A second `v1=` segment is present during a key-rotation grace window so\n * verifiers MAY check either signature without coordinating with the\n * platform. A 5-minute timestamp tolerance prevents replay; payloads\n * outside that window are rejected even when the HMAC matches.\n *\n * This module is byte-compatible with the platform-side signer at\n * `app/services/finance/embed/webhook_signer.py` — any drift is a bug,\n * and the cross-SDK fixtures in `tests/fixtures/webhook-events.ts` mirror\n * the equivalent fixtures in the Python and Go SDKs to guarantee a\n * signature produced by one SDK verifies correctly under the others.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\nimport {\n\tWebhookFormatError,\n\tWebhookSignatureError,\n\tWebhookTimestampError,\n} from \"./errors.js\";\nimport { type WebhookEvent, isWebhookEvent } from \"./models/events.js\";\n\nimport { DEFAULT_WEBHOOK_TOLERANCE_SECONDS } from \"./_const.js\";\n\n/** Re-export so callers can import the canonical default tolerance. */\nexport { DEFAULT_WEBHOOK_TOLERANCE_SECONDS } from \"./_const.js\";\n\n/** Optional knobs accepted by {@link verifyWebhook}; useful for tests. */\nexport interface VerifyWebhookOptions {\n\t/**\n\t * Maximum allowed clock skew between the platform and the receiver,\n\t * in seconds. Defaults to 5 minutes (per spec §6.7); only override\n\t * for unit tests.\n\t */\n\ttoleranceSeconds?: number;\n\t/**\n\t * Wall-clock seconds-since-epoch to compare against. Defaults to the\n\t * current time (`Date.now() / 1000`); override in tests for\n\t * determinism.\n\t */\n\tnow?: number;\n}\n\ninterface ParsedSignatureHeader {\n\ttimestamp: number;\n\tdigests: string[];\n}\n\n/**\n * Parse `t=<ts>,v1=<hex>[,v1=<hex>]` into `{ timestamp, digests }`.\n *\n * Throws {@link WebhookFormatError} on any structural problem (missing\n * `t=`, missing `v1=`, non-integer timestamp, etc.). We never silently\n * downgrade to a \"did not verify\" outcome — a malformed header is its own\n * failure mode the caller may want to log distinctly from a real\n * signature mismatch.\n */\nfunction parseSignatureHeader(header: string): ParsedSignatureHeader {\n\tif (!header) {\n\t\tthrow new WebhookFormatError(\"Flock-Signature header is missing or empty\");\n\t}\n\tlet timestamp: number | null = null;\n\tconst digests: string[] = [];\n\tfor (const raw of header.split(\",\")) {\n\t\tconst part = raw.trim();\n\t\tif (part.startsWith(\"t=\")) {\n\t\t\tconst tsRaw = part.slice(2);\n\t\t\t// Reject leading whitespace, empty string, signs, decimals — the\n\t\t\t// platform always emits a non-negative integer.\n\t\t\tif (!/^\\d+$/.test(tsRaw)) {\n\t\t\t\tthrow new WebhookFormatError(\n\t\t\t\t\t`timestamp segment in Flock-Signature is not an integer: ${JSON.stringify(part)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\ttimestamp = Number.parseInt(tsRaw, 10);\n\t\t} else if (part.startsWith(\"v1=\")) {\n\t\t\tconst digest = part.slice(3);\n\t\t\tif (!/^[0-9a-f]{64}$/.test(digest)) {\n\t\t\t\tthrow new WebhookFormatError(\n\t\t\t\t\t`v1 signature segment is not a 64-char hex digest: ${JSON.stringify(part)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tdigests.push(digest);\n\t\t}\n\t\t// Unknown segments (e.g. future `v2=`) are intentionally ignored so\n\t\t// the platform can introduce new signature versions without\n\t\t// breaking older verifiers.\n\t}\n\tif (timestamp === null) {\n\t\tthrow new WebhookFormatError(\n\t\t\t\"Flock-Signature is missing the required t=<unix_ts> segment\",\n\t\t);\n\t}\n\tif (digests.length === 0) {\n\t\tthrow new WebhookFormatError(\"Flock-Signature has no v1=<hex> segments\");\n\t}\n\treturn { timestamp, digests };\n}\n\n/**\n * Compute `HMAC-SHA256(secret, \"<ts>.\" + body)` as lowercase hex.\n *\n * The dot delimiter is concatenated as raw ASCII bytes so binary bodies\n * never pass through a string-decode step. Mirrors `sign(secret, ts, body)`\n * in the platform-side signer.\n */\nfunction computeExpected(\n\tsecret: string,\n\ttimestamp: number,\n\tbody: Uint8Array,\n): string {\n\tconst hmac = createHmac(\"sha256\", secret);\n\thmac.update(`${timestamp}.`, \"utf8\");\n\thmac.update(body);\n\treturn hmac.digest(\"hex\");\n}\n\n/**\n * Constant-time compare two equal-length hex digests using\n * `timingSafeEqual`. Returns `false` on any length mismatch (which\n * `timingSafeEqual` would otherwise throw on); the regex in\n * {@link parseSignatureHeader} guarantees both inputs are 64 chars in\n * the happy path, but we belt-and-brace the length check anyway.\n */\nfunction constantTimeEqualHex(a: string, b: string): boolean {\n\tif (a.length !== b.length) return false;\n\tconst aBuf = Buffer.from(a, \"utf8\");\n\tconst bBuf = Buffer.from(b, \"utf8\");\n\treturn timingSafeEqual(aBuf, bBuf);\n}\n\n/**\n * Coerce the body parameter to bytes. The verifier accepts either a\n * string (which we encode as UTF-8 — the platform always emits UTF-8)\n * or a `Uint8Array` / `Buffer` from frameworks that buffer the raw body.\n *\n * **Do not re-serialize JSON** before calling: even a single whitespace\n * difference will invalidate the signature.\n */\nfunction coerceBody(body: string | Uint8Array): Uint8Array {\n\tif (typeof body === \"string\") {\n\t\treturn Buffer.from(body, \"utf8\");\n\t}\n\treturn body;\n}\n\n/**\n * Verify a webhook delivery and return the parsed event.\n *\n * @param body - The raw request body as received off the wire. **Do not\n * re-serialize** the JSON before passing it in — even a single\n * whitespace difference will invalidate the signature. Frameworks that\n * buffer the body (Express with `express.raw()`, Fastify\n * `request.rawBody`) provide the bytes directly.\n * @param signature - Value of the `Flock-Signature` request header.\n * @param secret - The HMAC signing secret returned by the platform when\n * the webhook endpoint was created or its URL was last changed.\n * @param options - Optional tolerance / clock overrides for tests.\n * @returns The parsed {@link WebhookEvent} (a discriminated union member\n * selected by the `type` discriminator).\n * @throws {@link WebhookFormatError} The signature header does not parse,\n * or the body is not UTF-8 JSON matching a known event shape.\n * @throws {@link WebhookTimestampError} The timestamp falls outside the\n * tolerance window. Reject as a replay attempt.\n * @throws {@link WebhookSignatureError} No `v1=` digest matched under\n * the supplied secret. The body may have been tampered with, the\n * secret may be wrong, or the request did not originate from\n * 1st Flock.\n */\nexport function verifyWebhook(\n\tbody: string | Uint8Array,\n\tsignature: string,\n\tsecret: string,\n\toptions: VerifyWebhookOptions = {},\n): WebhookEvent {\n\tconst tolerance =\n\t\toptions.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS;\n\tif (typeof secret !== \"string\" || secret.length === 0) {\n\t\tthrow new WebhookFormatError(\"secret must be a non-empty string\");\n\t}\n\n\tconst { timestamp, digests } = parseSignatureHeader(signature);\n\n\tconst current = options.now ?? Date.now() / 1000;\n\tif (Math.abs(current - timestamp) > tolerance) {\n\t\tthrow new WebhookTimestampError(\n\t\t\t`webhook timestamp ${timestamp} is outside the ${tolerance}s tolerance (current=${Math.floor(current)})`,\n\t\t);\n\t}\n\n\tconst bodyBytes = coerceBody(body);\n\tconst expected = computeExpected(secret, timestamp, bodyBytes);\n\tlet matched = false;\n\tfor (const d of digests) {\n\t\t// Iterate ALL digests rather than short-circuiting on the first\n\t\t// match so the comparison time is independent of which (if any)\n\t\t// digest matched.\n\t\tif (constantTimeEqualHex(expected, d)) {\n\t\t\tmatched = true;\n\t\t}\n\t}\n\tif (!matched) {\n\t\tthrow new WebhookSignatureError(\n\t\t\t\"webhook signature did not match — wrong secret or tampered body\",\n\t\t);\n\t}\n\n\t// Decode the body only after the signature passes — never feed\n\t// untrusted JSON through a parser before authenticating it.\n\tlet decoded: string;\n\ttry {\n\t\tdecoded = Buffer.from(bodyBytes).toString(\"utf8\");\n\t} catch (err) {\n\t\tthrow new WebhookFormatError(\n\t\t\t`webhook body is not valid UTF-8: ${(err as Error).message}`,\n\t\t);\n\t}\n\tlet payload: unknown;\n\ttry {\n\t\tpayload = JSON.parse(decoded);\n\t} catch (err) {\n\t\tthrow new WebhookFormatError(\n\t\t\t`webhook body did not parse as JSON: ${(err as Error).message}`,\n\t\t);\n\t}\n\n\tif (!isWebhookEvent(payload)) {\n\t\tthrow new WebhookFormatError(\n\t\t\t\"webhook body did not match any known event schema\",\n\t\t);\n\t}\n\treturn payload;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/_const.ts","../src/_idempotency.ts","../src/errors.ts","../src/_http.ts","../src/client.ts","../src/models/events.ts","../src/webhooks.ts"],"names":["randomUUID","idempotencyKey","createHmac","Buffer","timingSafeEqual"],"mappings":";;;;;;AAYO,IAAM,WAAA,GAAc;AAGpB,IAAM,gBAAA,GAAmB,0BAAA;AAGzB,IAAM,kBAAA,GAAqB,GAAA;AAG3B,IAAM,mBAAA,GAAsB,CAAA;AAU5B,IAAM,iCAAA,GAAoC;ACdjD,IAAM,cAAA,GAAiB,GAAA;AAMvB,IAAM,WAAA,GAAc,yBAAA;AAeb,SAAS,eAAe,KAAA,EAAwB;AACtD,EAAA,MAAM,OAAOA,iBAAA,EAAW;AACxB,EAAA,IAAI,UAAU,MAAA,EAAW;AACxB,IAA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;AAAA,EACD;AACA,EAAA,OAAO,OAAA;AACR","file":"index.cjs","sourcesContent":["/**\n * Internal constants shared across the SDK.\n *\n * Kept in a tiny module so internal modules (HTTP transport, webhook\n * verifier) can import without dragging in the public surface.\n */\n\n/**\n * Single source of truth for the SDK's marketed version. Every outbound\n * request advertises this in the User-Agent header so the platform can\n * attribute traffic and warn customers running EOL versions.\n */\nexport const SDK_VERSION = \"1.1.0\";\n\n/** Default platform API base URL; overridable per-Client. */\nexport const DEFAULT_BASE_URL = \"https://api.1stflock.com\";\n\n/** Per-request timeout in milliseconds. */\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\n/** Number of additional attempts on retryable failures (5xx + transient). */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * Webhook timestamp tolerance in seconds — per spec §6.7.\n *\n * The verifier rejects deliveries whose timestamp falls outside this\n * window even if the HMAC matches. Customers should not need to override\n * this in production; the parameter exists so unit tests can simulate\n * clock drift.\n */\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n","/**\n * Idempotency-key helper.\n *\n * The platform's idempotency contract: replaying a request with the same\n * `Idempotency-Key` returns the original response without performing the\n * side effect a second time. Keys are scoped per (`api_key`, `endpoint`)\n * and persisted for 24 hours.\n *\n * This module exposes {@link idempotencyKey}, a tiny convenience wrapper\n * that prefixes a fresh UUID4 with a use-case tag so observability tooling\n * can group related retries (e.g. all `refund:*` keys belong to the\n * refund flow). Callers MAY also supply their own keys directly.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\n/** Match the OpenAPI `Idempotency-Key` schema constraint (max 255 chars). */\nconst MAX_KEY_LENGTH = 255;\n\n/**\n * Conservative validation for the use-case tag — keep it printable ASCII\n * so the resulting key fits cleanly in HTTP headers and log lines.\n */\nconst USE_CASE_RE = /^[a-z0-9][a-z0-9_\\-.]*$/;\n\n/**\n * Generate a fresh idempotency key tagged with a use-case prefix.\n *\n * The returned key has the form `\"<usage>:<uuid4>\"`, e.g.\n * `\"refund:1f2dab36-2a55-4f11-bdc8-2a2a4a95b001\"`. When `usage` is\n * omitted, returns a bare UUID4 with no prefix.\n *\n * @param usage - Optional short tag describing the operation\n * (`\"refund\"`, `\"cancel-recurring\"`, `\"replay-confirm\"`). When\n * supplied, must match `^[a-z0-9][a-z0-9_\\-.]*$`; an oddly-shaped\n * tag throws a `TypeError`.\n * @returns A string suitable for the `Idempotency-Key` HTTP header.\n */\nexport function idempotencyKey(usage?: string): string {\n\tconst uuid = randomUUID();\n\tif (usage === undefined) {\n\t\treturn uuid;\n\t}\n\tif (typeof usage !== \"string\" || !USE_CASE_RE.test(usage)) {\n\t\tthrow new TypeError(\n\t\t\t\"idempotency usage must be a non-empty lowercase ASCII tag matching /^[a-z0-9][a-z0-9_\\\\-.]*$/\",\n\t\t);\n\t}\n\tconst key = `${usage}:${uuid}`;\n\tif (key.length > MAX_KEY_LENGTH) {\n\t\t// Practically impossible (use_case + UUID4 is well under 255), but\n\t\t// we enforce the contract explicitly so a future caller can't blow\n\t\t// past the limit by passing a 250-char tag.\n\t\tthrow new RangeError(\n\t\t\t`generated idempotency key exceeds ${MAX_KEY_LENGTH} chars`,\n\t\t);\n\t}\n\treturn key;\n}\n","/**\n * Typed error hierarchy raised by the SDK.\n *\n * The base type is {@link ApiError}. All transport-level failures (4xx /\n * 5xx) surface as concrete subclasses so caller code can branch on type\n * rather than parsing status codes directly. Webhook verification has its\n * own dedicated exceptions ({@link WebhookSignatureError},\n * {@link WebhookTimestampError}) so middleware can return a single\n * `401 Unauthorized` without leaking which check failed.\n *\n * Every exception captures the raw error code + message returned by the\n * service when one is available, so callers can pivot on\n * `error.code === \"invalid_cursor\"` without re-deserializing the body.\n */\n\n/** Base class for every exception raised by this SDK. */\nexport class DonationsEmbedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"DonationsEmbedError\";\n\t\t// Restore the prototype chain after the super call so `instanceof`\n\t\t// works across module / bundle boundaries on older Node versions.\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/** Optional structured init bag accepted by every {@link ApiError} subclass. */\nexport interface ApiErrorInit {\n\t/** Stable, machine-readable error identifier (e.g. `\"invalid_cursor\"`). */\n\tcode?: string | null;\n\t/** Optional, error-specific extra data the service emitted. */\n\tdetails?: Record<string, unknown> | null;\n\t/** Server-issued correlation ID from the `x-request-id` response header. */\n\trequestId?: string | null;\n}\n\n/**\n * Raised when the API returns a non-2xx status code.\n *\n * Concrete subclasses below ({@link AuthError}, {@link NotFoundError},\n * etc.) cover the common status codes; an `ApiError` instance is returned\n * for any other non-2xx response.\n */\nexport class ApiError extends DonationsEmbedError {\n\treadonly statusCode: number;\n\treadonly code: string | null;\n\toverride readonly message: string;\n\treadonly details: Record<string, unknown> | null;\n\treadonly requestId: string | null;\n\n\tconstructor(statusCode: number, message: string, init: ApiErrorInit = {}) {\n\t\tconst code = init.code ?? null;\n\t\tconst requestId = init.requestId ?? null;\n\t\tconst prefix =\n\t\t\tcode !== null ? `[${statusCode} ${code}]` : `[${statusCode}]`;\n\t\tconst formatted =\n\t\t\trequestId !== null\n\t\t\t\t? `${prefix} ${message} (request_id=${requestId})`\n\t\t\t\t: `${prefix} ${message}`;\n\t\t// Pass the bare message to `Error` so `err.message` reads cleanly,\n\t\t// then override `toString()` to produce the formatted version with\n\t\t// the bracketed prefix and request id. Production callers typically\n\t\t// log `String(err)` (which calls `toString`) — they get the rich\n\t\t// form. Code that introspects `err.message` directly gets the bare\n\t\t// human string without prefix noise.\n\t\tsuper(message);\n\t\tthis.name = \"ApiError\";\n\t\tthis.statusCode = statusCode;\n\t\tthis.code = code;\n\t\tthis.message = message;\n\t\tthis.details = init.details ?? null;\n\t\tthis.requestId = requestId;\n\t\t// Stash the formatted form so `toString()` can return it.\n\t\tObject.defineProperty(this, \"_formatted\", {\n\t\t\tvalue: formatted,\n\t\t\tenumerable: false,\n\t\t\twritable: false,\n\t\t});\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n\n\toverride toString(): string {\n\t\t// `Error.prototype.toString()` returns \"<name>: <message>\". For our\n\t\t// API errors, callers want the bracketed prefix + request id so\n\t\t// they can grep logs. We synthesize the rich form here.\n\t\tconst formatted = (this as unknown as { _formatted?: string })._formatted;\n\t\treturn formatted ? `${this.name}: ${formatted}` : super.toString();\n\t}\n}\n\n/**\n * Raised on a `401 Unauthorized` response.\n *\n * Common causes: revoked secret key, malformed bearer token, expired\n * session, or the token was issued for a different environment (test vs.\n * live) than the URL being called.\n */\nexport class AuthError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"AuthError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised on a `403 Forbidden` response.\n *\n * Common causes: the secret key has been frozen by automatic protection,\n * the caller's RBAC scope is insufficient, or the action is disabled for\n * the organization.\n */\nexport class ForbiddenError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"ForbiddenError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised on a `404 Not Found` response.\n *\n * Note: cross-organization lookups collapse to `404` to avoid confirming\n * that an object exists in another tenant.\n */\nexport class NotFoundError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"NotFoundError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised on `400 Bad Request` or `422 Unprocessable Entity`.\n *\n * The originating request body failed schema validation. Inspect\n * `details` for the offending field path (e.g.\n * `{ loc: [\"body\", \"amount_cents\"] }`).\n */\nexport class ValidationError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"ValidationError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised on a `409 Conflict` response.\n *\n * Common causes: attempting to refund a donation that is already fully\n * refunded, or cancelling a recurring schedule whose state forbids the\n * transition.\n */\nexport class ConflictError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"ConflictError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/** Raised on a `410 Gone` response (terminal session error). */\nexport class GoneError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"GoneError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised on a `429 Too Many Requests` response.\n *\n * The caller should wait `retryAfterSeconds` before retrying. The SDK\n * does not auto-retry rate-limited requests by default — back-pressure\n * is a caller-controlled concern.\n */\nexport class RateLimitError extends ApiError {\n\treadonly retryAfterSeconds: number | null;\n\n\tconstructor(\n\t\tstatusCode: number,\n\t\tmessage: string,\n\t\tinit: ApiErrorInit & { retryAfterSeconds?: number | null } = {},\n\t) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"RateLimitError\";\n\t\tthis.retryAfterSeconds = init.retryAfterSeconds ?? null;\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised on a `502 Bad Gateway` response.\n *\n * Indicates an upstream payment-processor failure. The original request\n * is safe to retry — it has not been performed.\n */\nexport class BadGatewayError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"BadGatewayError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/** Raised on a `503 Service Unavailable` response. */\nexport class ServiceUnavailableError extends ApiError {\n\tconstructor(statusCode: number, message: string, init?: ApiErrorInit) {\n\t\tsuper(statusCode, message, init);\n\t\tthis.name = \"ServiceUnavailableError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/** Base class for webhook signature-verification failures. */\nexport class WebhookError extends DonationsEmbedError {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"WebhookError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised when webhook signature verification fails.\n *\n * This may indicate a wrong shared secret, a tampered request body, or\n * that the signature header was not produced by 1st Flock. Callers MUST\n * return an HTTP 401 (or drop the request) without enqueueing the event.\n */\nexport class WebhookSignatureError extends WebhookError {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"WebhookSignatureError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised when the webhook timestamp is outside the 5-minute tolerance.\n *\n * This is a replay-prevention check; callers MUST treat it as a\n * verification failure and return `401` without processing the event.\n */\nexport class WebhookTimestampError extends WebhookError {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"WebhookTimestampError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n\n/**\n * Raised when the signature header is structurally malformed.\n *\n * Examples: missing `t=` segment, no `v1=` segments, non-integer\n * timestamp, etc. The request did not parse as a signed delivery.\n */\nexport class WebhookFormatError extends WebhookError {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"WebhookFormatError\";\n\t\tObject.setPrototypeOf(this, new.target.prototype);\n\t}\n}\n","/**\n * Internal HTTP transport — typed errors, retry, and idempotency forwarding.\n *\n * The {@link HttpTransport} class wraps Node 18+'s native global `fetch`\n * and applies the SDK's cross-cutting policies on every request:\n *\n * - Adds the `Authorization: Bearer <api_key>` header.\n * - Adds a `User-Agent` header identifying the SDK + Node version so the\n * platform can attribute traffic and warn customers running EOL\n * versions.\n * - Forwards an optional `Idempotency-Key` header.\n * - Maps non-2xx responses to typed exceptions\n * ({@link ApiError} and subclasses).\n * - Retries 5xx responses with exponential backoff + jitter; honors the\n * `Retry-After` header on `429` (no auto-retry — back-pressure is a\n * caller-controlled concern).\n *\n * The transport is internal — public callers always interact through\n * {@link Client} from `client.ts`.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport {\n\tDEFAULT_BASE_URL,\n\tDEFAULT_MAX_RETRIES,\n\tDEFAULT_TIMEOUT_MS,\n\tSDK_VERSION,\n} from \"./_const.js\";\nimport {\n\tApiError,\n\ttype ApiErrorInit,\n\tAuthError,\n\tBadGatewayError,\n\tConflictError,\n\tForbiddenError,\n\tGoneError,\n\tNotFoundError,\n\tRateLimitError,\n\tServiceUnavailableError,\n\tValidationError,\n} from \"./errors.js\";\n\n/** Status codes the transport will retry (idempotently). */\nconst RETRYABLE_STATUS_CODES = new Set([500, 502, 503, 504]);\n\n/**\n * Logger interface matching the subset of `console` we use. Allows\n * callers to plug in pino / winston / a no-op logger without depending\n * on a particular logging library.\n */\nexport interface Logger {\n\tdebug(message: string, ...args: unknown[]): void;\n}\n\n/**\n * The portion of WHATWG `fetch` we rely on. Typed loosely so callers\n * can inject a mock without bringing in `undici-types` if they don't\n * need to.\n */\nexport type FetchLike = typeof globalThis.fetch;\n\n/** Options accepted by {@link HttpTransport}. */\nexport interface HttpTransportOptions {\n\tapiKey: string;\n\tbaseUrl?: string;\n\tfetch?: FetchLike;\n\tmaxRetries?: number;\n\t/** Per-request timeout in milliseconds. */\n\ttimeoutMs?: number;\n\tlogger?: Logger;\n}\n\n/** Per-request inputs to {@link HttpTransport.request}. */\nexport interface RequestOptions {\n\tmethod: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\tpath: string;\n\tquery?: Record<string, string | number | boolean | null | undefined>;\n\tbody?: unknown;\n\tidempotencyKey?: string;\n}\n\n/** Build the SDK's `User-Agent` string. */\nfunction buildUserAgent(): string {\n\tconst nodeVersion = process.versions.node;\n\treturn `@1st-flock/donations-embed-node/${SDK_VERSION} node/${nodeVersion}`;\n}\n\n/**\n * Drop `null` / `undefined` entries from the query bag before they get\n * serialized into the literal strings `\"null\"` / `\"undefined\"`.\n */\nfunction buildQueryString(query: RequestOptions[\"query\"]): string {\n\tif (!query) return \"\";\n\tconst params = new URLSearchParams();\n\tfor (const [k, v] of Object.entries(query)) {\n\t\tif (v === null || v === undefined) continue;\n\t\tparams.append(k, String(v));\n\t}\n\tconst s = params.toString();\n\treturn s.length === 0 ? \"\" : `?${s}`;\n}\n\n/**\n * Parse a numeric `Retry-After` header into seconds. The HTTP spec also\n * permits an HTTP-date format; we accept seconds (as integer or float)\n * and silently return `null` for date-based values rather than\n * synthesizing a delay.\n */\nfunction parseRetryAfter(value: string | null): number | null {\n\tif (value === null) return null;\n\tconst n = Number.parseFloat(value.trim());\n\treturn Number.isFinite(n) ? n : null;\n}\n\n/**\n * Sleep with jitter for `delayMs` milliseconds. Exposed via a function so\n * tests can spy on retry timing without `setTimeout` polluting the test\n * runtime.\n */\nfunction sleep(delayMs: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, delayMs));\n}\n\n/**\n * Compute the next backoff delay in milliseconds using exponential\n * backoff with jitter. `attempt` is 1-indexed; the first retry waits\n * roughly 250-500ms, the second 500-1000ms, etc., capped at 20 seconds.\n */\nfunction backoffDelayMs(attempt: number): number {\n\tconst base = Math.min(20_000, 250 * 2 ** (attempt - 1));\n\t// Half-jitter — between 50% and 100% of the base delay.\n\treturn base / 2 + Math.random() * (base / 2);\n}\n\n/** Internal HTTP transport. Not exported from the package surface. */\nexport class HttpTransport {\n\tprivate readonly apiKey: string;\n\tprivate readonly baseUrl: string;\n\tprivate readonly fetchFn: FetchLike;\n\tprivate readonly maxRetries: number;\n\tprivate readonly timeoutMs: number;\n\tprivate readonly logger: Logger;\n\tprivate readonly userAgent: string;\n\n\tconstructor(opts: HttpTransportOptions) {\n\t\tthis.apiKey = opts.apiKey;\n\t\tthis.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n\t\tthis.fetchFn = opts.fetch ?? globalThis.fetch;\n\t\tif (typeof this.fetchFn !== \"function\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"global fetch is unavailable; pass `fetch` explicitly or run on Node 18+\",\n\t\t\t);\n\t\t}\n\t\tthis.maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES;\n\t\tthis.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\t\tthis.logger = opts.logger ?? { debug: () => undefined };\n\t\tthis.userAgent = buildUserAgent();\n\t}\n\n\t/**\n\t * Send a request and return the parsed JSON response body.\n\t *\n\t * Returns `null` for `204 No Content`; throws a typed\n\t * {@link ApiError} subclass on every non-2xx status code that\n\t * survives the retry policy.\n\t */\n\tasync request<T>(opts: RequestOptions): Promise<T> {\n\t\tconst url = `${this.baseUrl}${opts.path}${buildQueryString(opts.query)}`;\n\t\tconst headers = this.buildHeaders(\n\t\t\topts.idempotencyKey,\n\t\t\topts.body !== undefined,\n\t\t);\n\t\tconst bodyJson =\n\t\t\topts.body !== undefined ? JSON.stringify(opts.body) : undefined;\n\n\t\tlet lastResponse: Response | null = null;\n\t\tlet attempt = 0;\n\t\t// The total budget is 1 initial attempt + maxRetries follow-ups.\n\t\tconst totalAttempts = Math.max(1, this.maxRetries + 1);\n\t\twhile (attempt < totalAttempts) {\n\t\t\tattempt += 1;\n\t\t\ttry {\n\t\t\t\tconst res = await this.sendOnce(url, opts.method, headers, bodyJson);\n\t\t\t\tlastResponse = res;\n\t\t\t\tif (RETRYABLE_STATUS_CODES.has(res.status)) {\n\t\t\t\t\tif (attempt < totalAttempts) {\n\t\t\t\t\t\tconst delay = backoffDelayMs(attempt);\n\t\t\t\t\t\tthis.logger.debug(\n\t\t\t\t\t\t\t`donations-embed: retrying ${opts.method} ${opts.path} after ${res.status} (attempt ${attempt})`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait sleep(delay);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (res.status >= 400) {\n\t\t\t\t\tthrow await this.buildErrorFromResponse(res);\n\t\t\t\t}\n\t\t\t\treturn (await this.parseResponseBody(res)) as T;\n\t\t\t} catch (err) {\n\t\t\t\t// `fetch` throws on network errors / aborts — those are\n\t\t\t\t// retryable. ApiError instances we threw ourselves above are\n\t\t\t\t// final and should propagate.\n\t\t\t\tif (err instanceof ApiError) throw err;\n\t\t\t\tif (attempt < totalAttempts) {\n\t\t\t\t\tconst delay = backoffDelayMs(attempt);\n\t\t\t\t\tthis.logger.debug(\n\t\t\t\t\t\t`donations-embed: retrying ${opts.method} ${opts.path} after transport error (attempt ${attempt}): ${(err as Error).message}`,\n\t\t\t\t\t);\n\t\t\t\t\tawait sleep(delay);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\t// Should never reach here — the loop always returns or throws — but\n\t\t// TypeScript's flow analysis can't see that.\n\t\tif (lastResponse !== null) {\n\t\t\tthrow await this.buildErrorFromResponse(lastResponse);\n\t\t}\n\t\tthrow new ApiError(0, \"request did not produce a response\");\n\t}\n\n\tprivate buildHeaders(\n\t\tidempotencyKey: string | undefined,\n\t\thasBody: boolean,\n\t): Record<string, string> {\n\t\tconst headers: Record<string, string> = {\n\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t\"User-Agent\": this.userAgent,\n\t\t\tAccept: \"application/json\",\n\t\t};\n\t\tif (hasBody) {\n\t\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\t}\n\t\tif (idempotencyKey !== undefined) {\n\t\t\theaders[\"Idempotency-Key\"] = idempotencyKey;\n\t\t}\n\t\treturn headers;\n\t}\n\n\tprivate async sendOnce(\n\t\turl: string,\n\t\tmethod: RequestOptions[\"method\"],\n\t\theaders: Record<string, string>,\n\t\tbody: string | undefined,\n\t): Promise<Response> {\n\t\tconst controller = new AbortController();\n\t\tconst timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\t\ttry {\n\t\t\treturn await this.fetchFn(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody,\n\t\t\t\tsignal: controller.signal,\n\t\t\t});\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t}\n\n\tprivate async parseResponseBody(res: Response): Promise<unknown> {\n\t\tif (res.status === 204) return null;\n\t\tconst text = await res.text();\n\t\tif (text.length === 0) return null;\n\t\ttry {\n\t\t\treturn JSON.parse(text);\n\t\t} catch (err) {\n\t\t\tthrow new ApiError(\n\t\t\t\tres.status,\n\t\t\t\t`response body did not parse as JSON: ${(err as Error).message}`,\n\t\t\t\t{ requestId: res.headers.get(\"x-request-id\") },\n\t\t\t);\n\t\t}\n\t}\n\n\t/** Map a 4xx / 5xx response onto the right {@link ApiError} subclass. */\n\tprivate async buildErrorFromResponse(res: Response): Promise<ApiError> {\n\t\tconst requestId = res.headers.get(\"x-request-id\");\n\t\tconst retryAfter = parseRetryAfter(res.headers.get(\"retry-after\"));\n\n\t\tlet code: string | null = null;\n\t\tlet message = res.statusText || `HTTP ${res.status}`;\n\t\tlet details: Record<string, unknown> | null = null;\n\t\ttry {\n\t\t\tconst text = await res.text();\n\t\t\tif (text.length > 0) {\n\t\t\t\tconst payload = JSON.parse(text) as Record<string, unknown>;\n\t\t\t\tif (typeof payload === \"object\" && payload !== null) {\n\t\t\t\t\tif (typeof payload.code === \"string\") code = payload.code;\n\t\t\t\t\tif (typeof payload.message === \"string\") message = payload.message;\n\t\t\t\t\tconst rawDetails = payload.details;\n\t\t\t\t\tif (\n\t\t\t\t\t\ttypeof rawDetails === \"object\" &&\n\t\t\t\t\t\trawDetails !== null &&\n\t\t\t\t\t\t!Array.isArray(rawDetails)\n\t\t\t\t\t) {\n\t\t\t\t\t\tdetails = rawDetails as Record<string, unknown>;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Non-JSON error body — fall through with the statusText.\n\t\t}\n\n\t\tconst init: ApiErrorInit = { code, details, requestId };\n\t\tconst status = res.status;\n\t\tswitch (status) {\n\t\t\tcase 401:\n\t\t\t\treturn new AuthError(status, message, init);\n\t\t\tcase 403:\n\t\t\t\treturn new ForbiddenError(status, message, init);\n\t\t\tcase 404:\n\t\t\t\treturn new NotFoundError(status, message, init);\n\t\t\tcase 400:\n\t\t\tcase 422:\n\t\t\t\treturn new ValidationError(status, message, init);\n\t\t\tcase 409:\n\t\t\t\treturn new ConflictError(status, message, init);\n\t\t\tcase 410:\n\t\t\t\treturn new GoneError(status, message, init);\n\t\t\tcase 429:\n\t\t\t\treturn new RateLimitError(status, message, {\n\t\t\t\t\t...init,\n\t\t\t\t\tretryAfterSeconds: retryAfter,\n\t\t\t\t});\n\t\t\tcase 502:\n\t\t\t\treturn new BadGatewayError(status, message, init);\n\t\t\tcase 503:\n\t\t\t\treturn new ServiceUnavailableError(status, message, init);\n\t\t\tdefault:\n\t\t\t\treturn new ApiError(status, message, init);\n\t\t}\n\t}\n}\n\n/**\n * Internal helper exposed for tests — convert anything that quacks like a\n * `Response` body into a `Buffer`. Currently unused outside tests but\n * kept here so the test surface doesn't reach into Node-only utilities.\n */\nexport function toBuffer(value: ArrayBuffer | Uint8Array | string): Buffer {\n\tif (typeof value === \"string\") return Buffer.from(value, \"utf8\");\n\tif (value instanceof Uint8Array) return Buffer.from(value);\n\treturn Buffer.from(value);\n}\n","/**\n * `Client` — entry point for the Donations Embed Customer SDK.\n *\n * Every method maps to a documented endpoint under the `/v1/embed/` path\n * prefix. All inputs and outputs are typed via the shapes in\n * `models/`. Errors surface as typed exceptions from `errors.ts`.\n *\n * Example:\n * ```ts\n * import { Client } from \"@1st-flock/donations-embed-node\";\n *\n * const client = new Client({ apiKey: process.env.FLOCK_SECRET_KEY! });\n * const page = await client.listDonations({ limit: 20 });\n * for (const donation of page.donations) {\n * console.log(donation.id, donation.gross_amount_cents);\n * }\n * ```\n */\n\nimport { type FetchLike, HttpTransport, type Logger } from \"./_http.js\";\nimport type {\n\tDonation,\n\tDonationListResponse,\n\tRefundResponse,\n} from \"./models/donations.js\";\nimport type {\n\tRecurringCancelResponse,\n\tRecurringListResponse,\n\tRecurringStatus,\n} from \"./models/recurring.js\";\nimport type {\n\tTestableWebhookEventType,\n\tWebhookTestResponse,\n} from \"./models/webhook-test.js\";\n\n/**\n * Resolved environment for a {@link Client}. Derived from the secret-key\n * prefix at construction time and surfaced via\n * {@link Client.environment}.\n *\n * - `\"live\"` — constructed with a `sk_live_*` production key. All API\n * traffic, NMI charges, Plaid transfers, and webhook deliveries on\n * this client target production.\n * - `\"test\"` — constructed with a `sk_test_*` sandbox key. All API\n * traffic, processor activity, and webhook deliveries target the\n * sandbox environment.\n */\nexport type Environment = \"live\" | \"test\";\n\n/** Constructor options for {@link Client}. */\nexport interface ClientOptions {\n\t/** Secret API key (`sk_live_*` or `sk_test_*`). */\n\tapiKey: string;\n\t/**\n\t * API base URL. Defaults to `https://api.1stflock.com`; point at\n\t * `https://api.sandbox.1stflock.com` to hit the sandbox environment.\n\t */\n\tbaseUrl?: string;\n\t/**\n\t * Optional `fetch` implementation override. Defaults to the global\n\t * `fetch` shipped in Node 18+. Useful for tests, custom retry/proxy\n\t * stacks, or alternative runtimes.\n\t */\n\tfetch?: FetchLike;\n\t/**\n\t * Number of retries on retryable failures (5xx + transient network\n\t * errors). The original attempt counts separately — `retries: 3`\n\t * performs at most 4 requests. Defaults to 3.\n\t */\n\tretries?: number;\n\t/** Per-request timeout in milliseconds. Defaults to 30000. */\n\ttimeout?: number;\n\t/**\n\t * Optional logger. Used at DEBUG for transient transport errors that\n\t * trigger a retry. Defaults to a no-op.\n\t */\n\tlogger?: Logger;\n}\n\n/** Optional inputs supported by `listDonations`. */\nexport interface ListDonationsParams {\n\tcursor?: string;\n\tlimit?: number;\n\tfundId?: string;\n\tdonorEmail?: string;\n}\n\n/** Optional inputs supported by `refundDonation`. */\nexport interface RefundDonationParams {\n\t/**\n\t * Refund amount in cents. Omit (or pass `null` / `undefined`) to\n\t * refund the full donation. When supplied, must be >= 1.\n\t */\n\tamountCents?: number;\n\t/** Optional internal note attached to the refund record. */\n\treason?: string;\n}\n\n/** Optional inputs supported by `listRecurring`. */\nexport interface ListRecurringParams {\n\tcursor?: string;\n\tlimit?: number;\n\tstatus?: RecurringStatus;\n}\n\n/** Per-call options that can carry an idempotency key. */\nexport interface IdempotentCallOptions {\n\tidempotencyKey?: string;\n}\n\n/**\n * Reject `pk_*` keys, missing keys, and other obviously-wrong inputs,\n * and resolve the environment from the key prefix.\n *\n * The customer SDK requires a secret key (`sk_live_*` or `sk_test_*`).\n * We catch the wrong shape at construction time so callers don't see a\n * confusing 401 from the platform.\n *\n * @returns The resolved {@link Environment} for this key.\n * @throws {TypeError} If `apiKey` is not a non-empty string starting\n * with `sk_live_` or `sk_test_`.\n */\nfunction environmentFromSecretKey(apiKey: unknown): Environment {\n\tif (typeof apiKey !== \"string\" || apiKey.length === 0) {\n\t\tthrow new TypeError(\"apiKey must be a non-empty string\");\n\t}\n\tif (apiKey.startsWith(\"sk_live_\")) {\n\t\treturn \"live\";\n\t}\n\tif (apiKey.startsWith(\"sk_test_\")) {\n\t\treturn \"test\";\n\t}\n\tthrow new TypeError(\n\t\t\"apiKey must be a secret key (sk_live_… or sk_test_…); publishable keys (pk_…) are browser-only and not accepted server-side\",\n\t);\n}\n\n/**\n * `Client` — typed access to the Donations Embed Customer SDK endpoints.\n *\n * The constructor parses the secret-key prefix and exposes the resolved\n * environment via {@link Client.environment}. The same API host\n * (`api.1stflock.com`) is used in both environments — the platform\n * routes between production and sandbox processors based on the\n * supplied secret key.\n */\nexport class Client {\n\t/**\n\t * Resolved environment (`\"live\"` or `\"test\"`) derived from the\n\t * supplied secret key. Read-only; set once in the constructor.\n\t */\n\treadonly environment: Environment;\n\n\tprivate readonly transport: HttpTransport;\n\n\tconstructor(options: ClientOptions) {\n\t\tthis.environment = environmentFromSecretKey(options.apiKey);\n\t\tthis.transport = new HttpTransport({\n\t\t\tapiKey: options.apiKey,\n\t\t\tbaseUrl: options.baseUrl,\n\t\t\tfetch: options.fetch,\n\t\t\tmaxRetries: options.retries,\n\t\t\ttimeoutMs: options.timeout,\n\t\t\tlogger: options.logger,\n\t\t});\n\t}\n\n\t// ---------------------------------------------------------------- donations\n\n\t/**\n\t * List donations, ordered `(created_at DESC, id DESC)`.\n\t *\n\t * @param params - Optional cursor / limit / fund / donor filters.\n\t * @returns A page of donations plus an optional `next_cursor`.\n\t */\n\tlistDonations(\n\t\tparams: ListDonationsParams = {},\n\t): Promise<DonationListResponse> {\n\t\treturn this.transport.request<DonationListResponse>({\n\t\t\tmethod: \"GET\",\n\t\t\tpath: \"/v1/embed/donations\",\n\t\t\tquery: {\n\t\t\t\tcursor: params.cursor,\n\t\t\t\tlimit: params.limit,\n\t\t\t\tfund_id: params.fundId,\n\t\t\t\tdonor_email: params.donorEmail,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Fetch a single donation by ID.\n\t *\n\t * Cross-organization access collapses to `404` (raises\n\t * {@link NotFoundError}).\n\t */\n\tgetDonation(donationId: string): Promise<Donation> {\n\t\treturn this.transport.request<Donation>({\n\t\t\tmethod: \"GET\",\n\t\t\tpath: `/v1/embed/donations/${encodeURIComponent(donationId)}`,\n\t\t});\n\t}\n\n\t/**\n\t * Refund a donation in full or part.\n\t *\n\t * @param donationId - The donation to refund.\n\t * @param params - Optional amount + reason.\n\t * @param options - Optional idempotency key (use\n\t * {@link idempotencyKey} to generate one tagged with a use-case\n\t * prefix).\n\t * @returns The {@link RefundResponse} describing the issued refund.\n\t * Idempotent replays return the original response without\n\t * re-contacting the gateway.\n\t */\n\trefundDonation(\n\t\tdonationId: string,\n\t\tparams: RefundDonationParams = {},\n\t\toptions: IdempotentCallOptions = {},\n\t): Promise<RefundResponse> {\n\t\tconst body: Record<string, unknown> = {};\n\t\tif (params.amountCents !== undefined) {\n\t\t\tbody.amount_cents = params.amountCents;\n\t\t}\n\t\tif (params.reason !== undefined) {\n\t\t\tbody.reason = params.reason;\n\t\t}\n\t\treturn this.transport.request<RefundResponse>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: `/v1/embed/donations/${encodeURIComponent(donationId)}/refund`,\n\t\t\tbody,\n\t\t\tidempotencyKey: options.idempotencyKey,\n\t\t});\n\t}\n\n\t// ----------------------------------------------------------------- recurring\n\n\t/**\n\t * List recurring schedules, ordered `(created_at DESC, id DESC)`.\n\t *\n\t * @returns A page of recurring schedules plus an optional `next_cursor`.\n\t */\n\tlistRecurring(\n\t\tparams: ListRecurringParams = {},\n\t): Promise<RecurringListResponse> {\n\t\treturn this.transport.request<RecurringListResponse>({\n\t\t\tmethod: \"GET\",\n\t\t\tpath: \"/v1/embed/recurring\",\n\t\t\tquery: {\n\t\t\t\tcursor: params.cursor,\n\t\t\t\tlimit: params.limit,\n\t\t\t\tstatus: params.status,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Cancel a recurring schedule.\n\t *\n\t * Idempotent: a second call against an already-cancelled schedule\n\t * returns `already_cancelled: true` without re-emitting a webhook.\n\t */\n\tcancelRecurring(\n\t\trecurringId: string,\n\t\toptions: IdempotentCallOptions = {},\n\t): Promise<RecurringCancelResponse> {\n\t\treturn this.transport.request<RecurringCancelResponse>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: `/v1/embed/recurring/${encodeURIComponent(recurringId)}/cancel`,\n\t\t\tidempotencyKey: options.idempotencyKey,\n\t\t});\n\t}\n\n\t// ------------------------------------------------------------------ webhooks\n\n\t/**\n\t * Queue a synthetic webhook event for delivery.\n\t *\n\t * The synthetic event's `data.object.synthetic` flag is set so\n\t * downstream code can branch on it during integration testing.\n\t *\n\t * @param eventType - Which event type to fire. Defaults to\n\t * `\"donation.created\"`.\n\t */\n\ttestWebhook(\n\t\teventType: TestableWebhookEventType = \"donation.created\",\n\t): Promise<WebhookTestResponse> {\n\t\treturn this.transport.request<WebhookTestResponse>({\n\t\t\tmethod: \"POST\",\n\t\t\tpath: \"/v1/embed/webhooks/test\",\n\t\t\tbody: { event_type: eventType },\n\t\t});\n\t}\n}\n","/**\n * Webhook event payload models — discriminated union over `type`.\n *\n * Each concrete event extends {@link WebhookEnvelopeBase} (the canonical\n * envelope) and adds a `data` field whose shape varies per event type.\n * {@link WebhookEvent} is the discriminated union of every concrete event,\n * so a `switch (event.type)` block narrows `event.data.object` to the\n * right shape automatically.\n *\n * Example:\n * ```ts\n * import { verifyWebhook } from \"@1st-flock/donations-embed-node\";\n *\n * const event = verifyWebhook(rawBody, signatureHeader, secret);\n * switch (event.type) {\n * case \"donation.completed\":\n * // event.data.object is DonationEventObject — typed.\n * enqueueReceipt(event.data.object);\n * break;\n * case \"donation.refunded\":\n * // event.data.object includes refund_amount_cents.\n * reverseReceipt(event.data.object);\n * break;\n * }\n * ```\n */\n\nimport type { DonationStatus, PaymentMethodType } from \"./donations.js\";\nimport type { RecurringInterval, RecurringStatus } from \"./recurring.js\";\n\n/** Stable union of every event type emitted by the platform. */\nexport type WebhookEventType =\n\t| \"donation.created\"\n\t| \"donation.completed\"\n\t| \"donation.failed\"\n\t| \"donation.refunded\"\n\t| \"recurring.activated\"\n\t| \"recurring.payment_succeeded\"\n\t| \"recurring.payment_failed\"\n\t| \"recurring.cancelled\"\n\t| \"key.frozen\";\n\n/** Reason a key pair was automatically frozen by abuse-detection. */\nexport type KeyFrozenReason = \"card_testing_detected\";\n\n// ---------------------------------------------------------------------------\n// Inline sub-objects shared by multiple event payloads\n// ---------------------------------------------------------------------------\n\n/**\n * Donor identity carried inside donation event payloads.\n *\n * Inline subset of the donor model; does not include the address since\n * webhook payloads omit it for compactness.\n */\nexport interface DonationEventDonor {\n\tname: string;\n\temail: string;\n}\n\n/** Payment-method snapshot inside a donation event payload. */\nexport interface EventPaymentMethod {\n\ttype: PaymentMethodType;\n\tlast4: string;\n\t/** Card brand; null for ACH. */\n\tbrand?: string | null;\n}\n\n/** Per-fund allocation inside a donation event payload (no fund name). */\nexport interface DonationEventFundAllocation {\n\tfund_id: string;\n\tamount_cents: number;\n}\n\n// ---------------------------------------------------------------------------\n// Per-event `data.object` payload shapes\n// ---------------------------------------------------------------------------\n\n/** Donation-shaped payload — used by completed / failed events. */\nexport interface DonationEventObject {\n\tid: string;\n\tconfirmation_id: string;\n\tdonor: DonationEventDonor;\n\tgross_amount_cents: number;\n\tfee_amount_cents: number;\n\tnet_amount_cents: number;\n\tpayment_method: EventPaymentMethod;\n\tprocessor_transaction_id?: string | null;\n\tstatus: DonationStatus;\n\tcreated_at?: string | null;\n\tfunds?: DonationEventFundAllocation[];\n}\n\n/** Refund variant — extends donation payload with refund metadata. */\nexport interface DonationRefundedEventObject extends DonationEventObject {\n\trefund_amount_cents: number;\n\t/** Vendor-neutral refund identifier. */\n\trefund_transaction_id?: string | null;\n}\n\n/**\n * Session-shaped payload for the `donation.created` event.\n *\n * Note: at this point there is no donation row yet — the embed has only\n * just opened a session. Correlate to the eventual donation via the\n * `donation_id` returned by `/v1/embed/sessions/{id}/confirm`.\n */\nexport interface DonationCreatedEventObject {\n\tsession_id: string;\n\torganization_id: string;\n\tamount_cents?: number | null;\n\tfund_ids?: string[];\n}\n\n/**\n * Recurring-schedule payload — used by `recurring.activated`,\n * `recurring.payment_succeeded`, `recurring.payment_failed`.\n */\nexport interface RecurringEventObject {\n\tid: string;\n\tdonor: DonationEventDonor;\n\tamount_cents: number;\n\tinterval: RecurringInterval;\n\tinterval_count: number;\n\tstatus: RecurringStatus;\n\tprocessor_subscription_id?: string | null;\n\tcreated_at?: string | null;\n}\n\n/** Minimal payload for `recurring.cancelled`. */\nexport interface RecurringCancelledEventObject {\n\trecurring_id: string;\n\tprocessor_subscription_id?: string | null;\n}\n\n/** Payload for `key.frozen` — emitted by automatic protection. */\nexport interface KeyFrozenEventObject {\n\tkey_pair_id: string;\n\t/** Truncated prefix of the publishable key (safe to log). */\n\tpk_prefix: string;\n\treason: KeyFrozenReason;\n\tdecline_count_window?: number | null;\n\twindow_seconds?: number | null;\n\tfrozen_at: string;\n}\n\n// ---------------------------------------------------------------------------\n// Concrete event envelopes (discriminated by `type`)\n// ---------------------------------------------------------------------------\n\n/**\n * Fields shared by every webhook event envelope. Mirrors OpenAPI\n * `WebhookEnvelope`; concrete subclasses pin `type` to a literal so the\n * discriminator can route correctly.\n */\nexport interface WebhookEnvelopeBase {\n\t/** Globally unique event ID. Echoed in `Flock-Event-Id` for dedup. */\n\tid: string;\n\t/** Unix epoch seconds at event creation. */\n\tcreated: number;\n\t/** True for live-mode events; false for test-mode. */\n\tlive_mode: boolean;\n}\n\n/** Donor opened the embed and a session was created (no donation row yet). */\nexport interface DonationCreatedEvent extends WebhookEnvelopeBase {\n\ttype: \"donation.created\";\n\tdata: { object: DonationCreatedEventObject };\n}\n\n/** Donation succeeded. */\nexport interface DonationCompletedEvent extends WebhookEnvelopeBase {\n\ttype: \"donation.completed\";\n\tdata: { object: DonationEventObject };\n}\n\n/** Donation declined or terminated before completion. */\nexport interface DonationFailedEvent extends WebhookEnvelopeBase {\n\ttype: \"donation.failed\";\n\tdata: { object: DonationEventObject };\n}\n\n/** Refund (full or partial) succeeded. */\nexport interface DonationRefundedEvent extends WebhookEnvelopeBase {\n\ttype: \"donation.refunded\";\n\tdata: { object: DonationRefundedEventObject };\n}\n\n/** Recurring schedule created and the first charge succeeded. */\nexport interface RecurringActivatedEvent extends WebhookEnvelopeBase {\n\ttype: \"recurring.activated\";\n\tdata: {\n\t\tobject: RecurringEventObject;\n\t\t/** The first underlying charge that activated this schedule. */\n\t\tdonation?: DonationEventObject | null;\n\t};\n}\n\n/** Per-cycle charge against a recurring schedule succeeded. */\nexport interface RecurringPaymentSucceededEvent extends WebhookEnvelopeBase {\n\ttype: \"recurring.payment_succeeded\";\n\tdata: {\n\t\tobject: RecurringEventObject;\n\t\t/** The successful per-cycle charge. */\n\t\tdonation?: DonationEventObject | null;\n\t};\n}\n\n/** Per-cycle charge against a recurring schedule failed. */\nexport interface RecurringPaymentFailedEvent extends WebhookEnvelopeBase {\n\ttype: \"recurring.payment_failed\";\n\tdata: {\n\t\tobject: RecurringEventObject;\n\t\t/** The failed per-cycle charge attempt, if available. */\n\t\tdonation?: DonationEventObject | null;\n\t};\n}\n\n/** Recurring schedule was cancelled (by customer, donor, or platform). */\nexport interface RecurringCancelledEvent extends WebhookEnvelopeBase {\n\ttype: \"recurring.cancelled\";\n\tdata: { object: RecurringCancelledEventObject };\n}\n\n/** Key pair was automatically frozen by abuse-detection. */\nexport interface KeyFrozenEvent extends WebhookEnvelopeBase {\n\ttype: \"key.frozen\";\n\tdata: { object: KeyFrozenEventObject };\n}\n\n/**\n * Discriminated union of every concrete webhook event type.\n *\n * The `type` field acts as a discriminator. A `switch` block on\n * `event.type` narrows `event.data.object` to the correct shape for the\n * branch.\n */\nexport type WebhookEvent =\n\t| DonationCreatedEvent\n\t| DonationCompletedEvent\n\t| DonationFailedEvent\n\t| DonationRefundedEvent\n\t| RecurringActivatedEvent\n\t| RecurringPaymentSucceededEvent\n\t| RecurringPaymentFailedEvent\n\t| RecurringCancelledEvent\n\t| KeyFrozenEvent;\n\n/** Alias for {@link WebhookEvent} matching the OpenAPI `WebhookEnvelope` name. */\nexport type WebhookEnvelope = WebhookEvent;\n\n// ---------------------------------------------------------------------------\n// Runtime parsing helpers\n// ---------------------------------------------------------------------------\n\n/**\n * The set of recognized event-type discriminator strings, exposed for\n * runtime checks (e.g. logging unknown types). Kept in sync with\n * {@link WebhookEventType} by construction.\n */\nexport const WEBHOOK_EVENT_TYPES: readonly WebhookEventType[] = [\n\t\"donation.created\",\n\t\"donation.completed\",\n\t\"donation.failed\",\n\t\"donation.refunded\",\n\t\"recurring.activated\",\n\t\"recurring.payment_succeeded\",\n\t\"recurring.payment_failed\",\n\t\"recurring.cancelled\",\n\t\"key.frozen\",\n] as const;\n\n/**\n * Type guard: returns `true` when `value` is structurally a\n * {@link WebhookEvent} (has the required envelope fields plus a known\n * discriminator and a `data.object` payload).\n *\n * This is intentionally a *shape* check and not a deep schema validation —\n * the discriminated union does not exist at runtime, and we keep the SDK\n * dependency-free (no Zod). Callers that need exhaustive validation can\n * pivot on `event.type` after the guard returns true.\n */\nexport function isWebhookEvent(value: unknown): value is WebhookEvent {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst v = value as Record<string, unknown>;\n\tif (typeof v.id !== \"string\") return false;\n\tif (typeof v.created !== \"number\") return false;\n\tif (typeof v.live_mode !== \"boolean\") return false;\n\tif (typeof v.type !== \"string\") return false;\n\tif (!WEBHOOK_EVENT_TYPES.includes(v.type as WebhookEventType)) return false;\n\tif (typeof v.data !== \"object\" || v.data === null) return false;\n\tconst data = v.data as Record<string, unknown>;\n\tif (typeof data.object !== \"object\" || data.object === null) return false;\n\treturn true;\n}\n","/**\n * HMAC-SHA256 webhook signature verification.\n *\n * Wire format on the `Flock-Signature` header (per spec §6.7):\n * ```\n * t=<unix_ts>,v1=<hmac_sha256_hex>[,v1=<hmac_sha256_hex>]\n * ```\n *\n * A second `v1=` segment is present during a key-rotation grace window so\n * verifiers MAY check either signature without coordinating with the\n * platform. A 5-minute timestamp tolerance prevents replay; payloads\n * outside that window are rejected even when the HMAC matches.\n *\n * This module is byte-compatible with the platform-side signer at\n * `app/services/finance/embed/webhook_signer.py` — any drift is a bug,\n * and the cross-SDK fixtures in `tests/fixtures/webhook-events.ts` mirror\n * the equivalent fixtures in the Python and Go SDKs to guarantee a\n * signature produced by one SDK verifies correctly under the others.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\nimport {\n\tWebhookFormatError,\n\tWebhookSignatureError,\n\tWebhookTimestampError,\n} from \"./errors.js\";\nimport { type WebhookEvent, isWebhookEvent } from \"./models/events.js\";\n\nimport { DEFAULT_WEBHOOK_TOLERANCE_SECONDS } from \"./_const.js\";\n\n/** Re-export so callers can import the canonical default tolerance. */\nexport { DEFAULT_WEBHOOK_TOLERANCE_SECONDS } from \"./_const.js\";\n\n/** Optional knobs accepted by {@link verifyWebhook}; useful for tests. */\nexport interface VerifyWebhookOptions {\n\t/**\n\t * Maximum allowed clock skew between the platform and the receiver,\n\t * in seconds. Defaults to 5 minutes (per spec §6.7); only override\n\t * for unit tests.\n\t */\n\ttoleranceSeconds?: number;\n\t/**\n\t * Wall-clock seconds-since-epoch to compare against. Defaults to the\n\t * current time (`Date.now() / 1000`); override in tests for\n\t * determinism.\n\t */\n\tnow?: number;\n}\n\ninterface ParsedSignatureHeader {\n\ttimestamp: number;\n\tdigests: string[];\n}\n\n/**\n * Parse `t=<ts>,v1=<hex>[,v1=<hex>]` into `{ timestamp, digests }`.\n *\n * Throws {@link WebhookFormatError} on any structural problem (missing\n * `t=`, missing `v1=`, non-integer timestamp, etc.). We never silently\n * downgrade to a \"did not verify\" outcome — a malformed header is its own\n * failure mode the caller may want to log distinctly from a real\n * signature mismatch.\n */\nfunction parseSignatureHeader(header: string): ParsedSignatureHeader {\n\tif (!header) {\n\t\tthrow new WebhookFormatError(\"Flock-Signature header is missing or empty\");\n\t}\n\tlet timestamp: number | null = null;\n\tconst digests: string[] = [];\n\tfor (const raw of header.split(\",\")) {\n\t\tconst part = raw.trim();\n\t\tif (part.startsWith(\"t=\")) {\n\t\t\tconst tsRaw = part.slice(2);\n\t\t\t// Reject leading whitespace, empty string, signs, decimals — the\n\t\t\t// platform always emits a non-negative integer.\n\t\t\tif (!/^\\d+$/.test(tsRaw)) {\n\t\t\t\tthrow new WebhookFormatError(\n\t\t\t\t\t`timestamp segment in Flock-Signature is not an integer: ${JSON.stringify(part)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\ttimestamp = Number.parseInt(tsRaw, 10);\n\t\t} else if (part.startsWith(\"v1=\")) {\n\t\t\tconst digest = part.slice(3);\n\t\t\tif (!/^[0-9a-f]{64}$/.test(digest)) {\n\t\t\t\tthrow new WebhookFormatError(\n\t\t\t\t\t`v1 signature segment is not a 64-char hex digest: ${JSON.stringify(part)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tdigests.push(digest);\n\t\t}\n\t\t// Unknown segments (e.g. future `v2=`) are intentionally ignored so\n\t\t// the platform can introduce new signature versions without\n\t\t// breaking older verifiers.\n\t}\n\tif (timestamp === null) {\n\t\tthrow new WebhookFormatError(\n\t\t\t\"Flock-Signature is missing the required t=<unix_ts> segment\",\n\t\t);\n\t}\n\tif (digests.length === 0) {\n\t\tthrow new WebhookFormatError(\"Flock-Signature has no v1=<hex> segments\");\n\t}\n\treturn { timestamp, digests };\n}\n\n/**\n * Compute `HMAC-SHA256(secret, \"<ts>.\" + body)` as lowercase hex.\n *\n * The dot delimiter is concatenated as raw ASCII bytes so binary bodies\n * never pass through a string-decode step. Mirrors `sign(secret, ts, body)`\n * in the platform-side signer.\n */\nfunction computeExpected(\n\tsecret: string,\n\ttimestamp: number,\n\tbody: Uint8Array,\n): string {\n\tconst hmac = createHmac(\"sha256\", secret);\n\thmac.update(`${timestamp}.`, \"utf8\");\n\thmac.update(body);\n\treturn hmac.digest(\"hex\");\n}\n\n/**\n * Constant-time compare two equal-length hex digests using\n * `timingSafeEqual`. Returns `false` on any length mismatch (which\n * `timingSafeEqual` would otherwise throw on); the regex in\n * {@link parseSignatureHeader} guarantees both inputs are 64 chars in\n * the happy path, but we belt-and-brace the length check anyway.\n */\nfunction constantTimeEqualHex(a: string, b: string): boolean {\n\tif (a.length !== b.length) return false;\n\tconst aBuf = Buffer.from(a, \"utf8\");\n\tconst bBuf = Buffer.from(b, \"utf8\");\n\treturn timingSafeEqual(aBuf, bBuf);\n}\n\n/**\n * Coerce the body parameter to bytes. The verifier accepts either a\n * string (which we encode as UTF-8 — the platform always emits UTF-8)\n * or a `Uint8Array` / `Buffer` from frameworks that buffer the raw body.\n *\n * **Do not re-serialize JSON** before calling: even a single whitespace\n * difference will invalidate the signature.\n */\nfunction coerceBody(body: string | Uint8Array): Uint8Array {\n\tif (typeof body === \"string\") {\n\t\treturn Buffer.from(body, \"utf8\");\n\t}\n\treturn body;\n}\n\n/**\n * Verify a webhook delivery and return the parsed event.\n *\n * @param body - The raw request body as received off the wire. **Do not\n * re-serialize** the JSON before passing it in — even a single\n * whitespace difference will invalidate the signature. Frameworks that\n * buffer the body (Express with `express.raw()`, Fastify\n * `request.rawBody`) provide the bytes directly.\n * @param signature - Value of the `Flock-Signature` request header.\n * @param secret - The HMAC signing secret returned by the platform when\n * the webhook endpoint was created or its URL was last changed.\n * @param options - Optional tolerance / clock overrides for tests.\n * @returns The parsed {@link WebhookEvent} (a discriminated union member\n * selected by the `type` discriminator).\n * @throws {@link WebhookFormatError} The signature header does not parse,\n * or the body is not UTF-8 JSON matching a known event shape.\n * @throws {@link WebhookTimestampError} The timestamp falls outside the\n * tolerance window. Reject as a replay attempt.\n * @throws {@link WebhookSignatureError} No `v1=` digest matched under\n * the supplied secret. The body may have been tampered with, the\n * secret may be wrong, or the request did not originate from\n * 1st Flock.\n */\nexport function verifyWebhook(\n\tbody: string | Uint8Array,\n\tsignature: string,\n\tsecret: string,\n\toptions: VerifyWebhookOptions = {},\n): WebhookEvent {\n\tconst tolerance =\n\t\toptions.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS;\n\tif (typeof secret !== \"string\" || secret.length === 0) {\n\t\tthrow new WebhookFormatError(\"secret must be a non-empty string\");\n\t}\n\n\tconst { timestamp, digests } = parseSignatureHeader(signature);\n\n\tconst current = options.now ?? Date.now() / 1000;\n\tif (Math.abs(current - timestamp) > tolerance) {\n\t\tthrow new WebhookTimestampError(\n\t\t\t`webhook timestamp ${timestamp} is outside the ${tolerance}s tolerance (current=${Math.floor(current)})`,\n\t\t);\n\t}\n\n\tconst bodyBytes = coerceBody(body);\n\tconst expected = computeExpected(secret, timestamp, bodyBytes);\n\tlet matched = false;\n\tfor (const d of digests) {\n\t\t// Iterate ALL digests rather than short-circuiting on the first\n\t\t// match so the comparison time is independent of which (if any)\n\t\t// digest matched.\n\t\tif (constantTimeEqualHex(expected, d)) {\n\t\t\tmatched = true;\n\t\t}\n\t}\n\tif (!matched) {\n\t\tthrow new WebhookSignatureError(\n\t\t\t\"webhook signature did not match — wrong secret or tampered body\",\n\t\t);\n\t}\n\n\t// Decode the body only after the signature passes — never feed\n\t// untrusted JSON through a parser before authenticating it.\n\tlet decoded: string;\n\ttry {\n\t\tdecoded = Buffer.from(bodyBytes).toString(\"utf8\");\n\t} catch (err) {\n\t\tthrow new WebhookFormatError(\n\t\t\t`webhook body is not valid UTF-8: ${(err as Error).message}`,\n\t\t);\n\t}\n\tlet payload: unknown;\n\ttry {\n\t\tpayload = JSON.parse(decoded);\n\t} catch (err) {\n\t\tthrow new WebhookFormatError(\n\t\t\t`webhook body did not parse as JSON: ${(err as Error).message}`,\n\t\t);\n\t}\n\n\tif (!isWebhookEvent(payload)) {\n\t\tthrow new WebhookFormatError(\n\t\t\t\"webhook body did not match any known event schema\",\n\t\t);\n\t}\n\treturn payload;\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { D as DonationListResponse, a as Donation, R as RefundResponse, b as RecurringStatus, c as RecurringListResponse, d as RecurringCancelResponse } from './webhooks-
|
|
2
|
-
export { e as DEFAULT_WEBHOOK_TOLERANCE_SECONDS, f as DonationCompletedEvent, g as DonationCreatedEvent, h as DonationCreatedEventObject, i as DonationEventDonor, j as DonationEventFundAllocation, k as DonationEventObject, l as DonationFailedEvent, m as DonationRefundedEvent, n as DonationRefundedEventObject, o as DonationStatus, E as EventPaymentMethod, F as FundAllocation, K as KeyFrozenEvent, p as KeyFrozenEventObject, q as KeyFrozenReason, P as PaymentMethodType, r as Recurring, s as RecurringActivatedEvent, t as RecurringCancelledEvent, u as RecurringCancelledEventObject, v as RecurringEventObject, w as RecurringInterval, x as RecurringPaymentFailedEvent, y as RecurringPaymentSucceededEvent, z as RefundRequest, S as VERSION, V as VerifyWebhookOptions, W as WEBHOOK_EVENT_TYPES, A as WebhookEnvelope, B as WebhookEnvelopeBase, C as WebhookEvent, G as WebhookEventType, H as isWebhookEvent, I as verifyWebhook } from './webhooks-
|
|
1
|
+
import { D as DonationListResponse, a as Donation, R as RefundResponse, b as RecurringStatus, c as RecurringListResponse, d as RecurringCancelResponse } from './webhooks-Dp_QzFm7.cjs';
|
|
2
|
+
export { e as DEFAULT_WEBHOOK_TOLERANCE_SECONDS, f as DonationCompletedEvent, g as DonationCreatedEvent, h as DonationCreatedEventObject, i as DonationEventDonor, j as DonationEventFundAllocation, k as DonationEventObject, l as DonationFailedEvent, m as DonationRefundedEvent, n as DonationRefundedEventObject, o as DonationStatus, E as EventPaymentMethod, F as FundAllocation, K as KeyFrozenEvent, p as KeyFrozenEventObject, q as KeyFrozenReason, P as PaymentMethodType, r as Recurring, s as RecurringActivatedEvent, t as RecurringCancelledEvent, u as RecurringCancelledEventObject, v as RecurringEventObject, w as RecurringInterval, x as RecurringPaymentFailedEvent, y as RecurringPaymentSucceededEvent, z as RefundRequest, S as VERSION, V as VerifyWebhookOptions, W as WEBHOOK_EVENT_TYPES, A as WebhookEnvelope, B as WebhookEnvelopeBase, C as WebhookEvent, G as WebhookEventType, H as isWebhookEvent, I as verifyWebhook } from './webhooks-Dp_QzFm7.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Idempotency-key helper.
|
|
@@ -109,6 +109,19 @@ interface WebhookTestResponse {
|
|
|
109
109
|
* ```
|
|
110
110
|
*/
|
|
111
111
|
|
|
112
|
+
/**
|
|
113
|
+
* Resolved environment for a {@link Client}. Derived from the secret-key
|
|
114
|
+
* prefix at construction time and surfaced via
|
|
115
|
+
* {@link Client.environment}.
|
|
116
|
+
*
|
|
117
|
+
* - `"live"` — constructed with a `sk_live_*` production key. All API
|
|
118
|
+
* traffic, NMI charges, Plaid transfers, and webhook deliveries on
|
|
119
|
+
* this client target production.
|
|
120
|
+
* - `"test"` — constructed with a `sk_test_*` sandbox key. All API
|
|
121
|
+
* traffic, processor activity, and webhook deliveries target the
|
|
122
|
+
* sandbox environment.
|
|
123
|
+
*/
|
|
124
|
+
type Environment = "live" | "test";
|
|
112
125
|
/** Constructor options for {@link Client}. */
|
|
113
126
|
interface ClientOptions {
|
|
114
127
|
/** Secret API key (`sk_live_*` or `sk_test_*`). */
|
|
@@ -167,8 +180,19 @@ interface IdempotentCallOptions {
|
|
|
167
180
|
}
|
|
168
181
|
/**
|
|
169
182
|
* `Client` — typed access to the Donations Embed Customer SDK endpoints.
|
|
183
|
+
*
|
|
184
|
+
* The constructor parses the secret-key prefix and exposes the resolved
|
|
185
|
+
* environment via {@link Client.environment}. The same API host
|
|
186
|
+
* (`api.1stflock.com`) is used in both environments — the platform
|
|
187
|
+
* routes between production and sandbox processors based on the
|
|
188
|
+
* supplied secret key.
|
|
170
189
|
*/
|
|
171
190
|
declare class Client {
|
|
191
|
+
/**
|
|
192
|
+
* Resolved environment (`"live"` or `"test"`) derived from the
|
|
193
|
+
* supplied secret key. Read-only; set once in the constructor.
|
|
194
|
+
*/
|
|
195
|
+
readonly environment: Environment;
|
|
172
196
|
private readonly transport;
|
|
173
197
|
constructor(options: ClientOptions);
|
|
174
198
|
/**
|
|
@@ -378,4 +402,4 @@ declare class WebhookFormatError extends WebhookError {
|
|
|
378
402
|
constructor(message: string);
|
|
379
403
|
}
|
|
380
404
|
|
|
381
|
-
export { ApiError, type ApiErrorInit, AuthError, BadGatewayError, Client, type ClientOptions, ConflictError, Donation, DonationListResponse, DonationsEmbedError, type FetchLike, ForbiddenError, GoneError, type IdempotentCallOptions, type ListDonationsParams, type ListRecurringParams, type Logger, NotFoundError, RateLimitError, RecurringCancelResponse, RecurringListResponse, RecurringStatus, type RefundDonationParams, RefundResponse, ServiceUnavailableError, type TestableWebhookEventType, ValidationError, WebhookError, WebhookFormatError, WebhookSignatureError, type WebhookTestRequest, type WebhookTestResponse, WebhookTimestampError, idempotencyKey };
|
|
405
|
+
export { ApiError, type ApiErrorInit, AuthError, BadGatewayError, Client, type ClientOptions, ConflictError, Donation, DonationListResponse, DonationsEmbedError, type Environment, type FetchLike, ForbiddenError, GoneError, type IdempotentCallOptions, type ListDonationsParams, type ListRecurringParams, type Logger, NotFoundError, RateLimitError, RecurringCancelResponse, RecurringListResponse, RecurringStatus, type RefundDonationParams, RefundResponse, ServiceUnavailableError, type TestableWebhookEventType, ValidationError, WebhookError, WebhookFormatError, WebhookSignatureError, type WebhookTestRequest, type WebhookTestResponse, WebhookTimestampError, idempotencyKey };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { D as DonationListResponse, a as Donation, R as RefundResponse, b as RecurringStatus, c as RecurringListResponse, d as RecurringCancelResponse } from './webhooks-
|
|
2
|
-
export { e as DEFAULT_WEBHOOK_TOLERANCE_SECONDS, f as DonationCompletedEvent, g as DonationCreatedEvent, h as DonationCreatedEventObject, i as DonationEventDonor, j as DonationEventFundAllocation, k as DonationEventObject, l as DonationFailedEvent, m as DonationRefundedEvent, n as DonationRefundedEventObject, o as DonationStatus, E as EventPaymentMethod, F as FundAllocation, K as KeyFrozenEvent, p as KeyFrozenEventObject, q as KeyFrozenReason, P as PaymentMethodType, r as Recurring, s as RecurringActivatedEvent, t as RecurringCancelledEvent, u as RecurringCancelledEventObject, v as RecurringEventObject, w as RecurringInterval, x as RecurringPaymentFailedEvent, y as RecurringPaymentSucceededEvent, z as RefundRequest, S as VERSION, V as VerifyWebhookOptions, W as WEBHOOK_EVENT_TYPES, A as WebhookEnvelope, B as WebhookEnvelopeBase, C as WebhookEvent, G as WebhookEventType, H as isWebhookEvent, I as verifyWebhook } from './webhooks-
|
|
1
|
+
import { D as DonationListResponse, a as Donation, R as RefundResponse, b as RecurringStatus, c as RecurringListResponse, d as RecurringCancelResponse } from './webhooks-Dp_QzFm7.js';
|
|
2
|
+
export { e as DEFAULT_WEBHOOK_TOLERANCE_SECONDS, f as DonationCompletedEvent, g as DonationCreatedEvent, h as DonationCreatedEventObject, i as DonationEventDonor, j as DonationEventFundAllocation, k as DonationEventObject, l as DonationFailedEvent, m as DonationRefundedEvent, n as DonationRefundedEventObject, o as DonationStatus, E as EventPaymentMethod, F as FundAllocation, K as KeyFrozenEvent, p as KeyFrozenEventObject, q as KeyFrozenReason, P as PaymentMethodType, r as Recurring, s as RecurringActivatedEvent, t as RecurringCancelledEvent, u as RecurringCancelledEventObject, v as RecurringEventObject, w as RecurringInterval, x as RecurringPaymentFailedEvent, y as RecurringPaymentSucceededEvent, z as RefundRequest, S as VERSION, V as VerifyWebhookOptions, W as WEBHOOK_EVENT_TYPES, A as WebhookEnvelope, B as WebhookEnvelopeBase, C as WebhookEvent, G as WebhookEventType, H as isWebhookEvent, I as verifyWebhook } from './webhooks-Dp_QzFm7.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Idempotency-key helper.
|
|
@@ -109,6 +109,19 @@ interface WebhookTestResponse {
|
|
|
109
109
|
* ```
|
|
110
110
|
*/
|
|
111
111
|
|
|
112
|
+
/**
|
|
113
|
+
* Resolved environment for a {@link Client}. Derived from the secret-key
|
|
114
|
+
* prefix at construction time and surfaced via
|
|
115
|
+
* {@link Client.environment}.
|
|
116
|
+
*
|
|
117
|
+
* - `"live"` — constructed with a `sk_live_*` production key. All API
|
|
118
|
+
* traffic, NMI charges, Plaid transfers, and webhook deliveries on
|
|
119
|
+
* this client target production.
|
|
120
|
+
* - `"test"` — constructed with a `sk_test_*` sandbox key. All API
|
|
121
|
+
* traffic, processor activity, and webhook deliveries target the
|
|
122
|
+
* sandbox environment.
|
|
123
|
+
*/
|
|
124
|
+
type Environment = "live" | "test";
|
|
112
125
|
/** Constructor options for {@link Client}. */
|
|
113
126
|
interface ClientOptions {
|
|
114
127
|
/** Secret API key (`sk_live_*` or `sk_test_*`). */
|
|
@@ -167,8 +180,19 @@ interface IdempotentCallOptions {
|
|
|
167
180
|
}
|
|
168
181
|
/**
|
|
169
182
|
* `Client` — typed access to the Donations Embed Customer SDK endpoints.
|
|
183
|
+
*
|
|
184
|
+
* The constructor parses the secret-key prefix and exposes the resolved
|
|
185
|
+
* environment via {@link Client.environment}. The same API host
|
|
186
|
+
* (`api.1stflock.com`) is used in both environments — the platform
|
|
187
|
+
* routes between production and sandbox processors based on the
|
|
188
|
+
* supplied secret key.
|
|
170
189
|
*/
|
|
171
190
|
declare class Client {
|
|
191
|
+
/**
|
|
192
|
+
* Resolved environment (`"live"` or `"test"`) derived from the
|
|
193
|
+
* supplied secret key. Read-only; set once in the constructor.
|
|
194
|
+
*/
|
|
195
|
+
readonly environment: Environment;
|
|
172
196
|
private readonly transport;
|
|
173
197
|
constructor(options: ClientOptions);
|
|
174
198
|
/**
|
|
@@ -378,4 +402,4 @@ declare class WebhookFormatError extends WebhookError {
|
|
|
378
402
|
constructor(message: string);
|
|
379
403
|
}
|
|
380
404
|
|
|
381
|
-
export { ApiError, type ApiErrorInit, AuthError, BadGatewayError, Client, type ClientOptions, ConflictError, Donation, DonationListResponse, DonationsEmbedError, type FetchLike, ForbiddenError, GoneError, type IdempotentCallOptions, type ListDonationsParams, type ListRecurringParams, type Logger, NotFoundError, RateLimitError, RecurringCancelResponse, RecurringListResponse, RecurringStatus, type RefundDonationParams, RefundResponse, ServiceUnavailableError, type TestableWebhookEventType, ValidationError, WebhookError, WebhookFormatError, WebhookSignatureError, type WebhookTestRequest, type WebhookTestResponse, WebhookTimestampError, idempotencyKey };
|
|
405
|
+
export { ApiError, type ApiErrorInit, AuthError, BadGatewayError, Client, type ClientOptions, ConflictError, Donation, DonationListResponse, DonationsEmbedError, type Environment, type FetchLike, ForbiddenError, GoneError, type IdempotentCallOptions, type ListDonationsParams, type ListRecurringParams, type Logger, NotFoundError, RateLimitError, RecurringCancelResponse, RecurringListResponse, RecurringStatus, type RefundDonationParams, RefundResponse, ServiceUnavailableError, type TestableWebhookEventType, ValidationError, WebhookError, WebhookFormatError, WebhookSignatureError, type WebhookTestRequest, type WebhookTestResponse, WebhookTimestampError, idempotencyKey };
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import { randomUUID, createHmac, timingSafeEqual } from 'crypto';
|
|
|
2
2
|
import { Buffer } from 'buffer';
|
|
3
3
|
|
|
4
4
|
// src/_const.ts
|
|
5
|
-
var SDK_VERSION = "1.
|
|
5
|
+
var SDK_VERSION = "1.1.0";
|
|
6
6
|
var DEFAULT_BASE_URL = "https://api.1stflock.com";
|
|
7
7
|
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
8
8
|
var DEFAULT_MAX_RETRIES = 3;
|
|
@@ -360,20 +360,29 @@ var HttpTransport = class {
|
|
|
360
360
|
};
|
|
361
361
|
|
|
362
362
|
// src/client.ts
|
|
363
|
-
function
|
|
363
|
+
function environmentFromSecretKey(apiKey) {
|
|
364
364
|
if (typeof apiKey !== "string" || apiKey.length === 0) {
|
|
365
365
|
throw new TypeError("apiKey must be a non-empty string");
|
|
366
366
|
}
|
|
367
|
-
if (
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
367
|
+
if (apiKey.startsWith("sk_live_")) {
|
|
368
|
+
return "live";
|
|
369
|
+
}
|
|
370
|
+
if (apiKey.startsWith("sk_test_")) {
|
|
371
|
+
return "test";
|
|
371
372
|
}
|
|
373
|
+
throw new TypeError(
|
|
374
|
+
"apiKey must be a secret key (sk_live_\u2026 or sk_test_\u2026); publishable keys (pk_\u2026) are browser-only and not accepted server-side"
|
|
375
|
+
);
|
|
372
376
|
}
|
|
373
377
|
var Client = class {
|
|
378
|
+
/**
|
|
379
|
+
* Resolved environment (`"live"` or `"test"`) derived from the
|
|
380
|
+
* supplied secret key. Read-only; set once in the constructor.
|
|
381
|
+
*/
|
|
382
|
+
environment;
|
|
374
383
|
transport;
|
|
375
384
|
constructor(options) {
|
|
376
|
-
|
|
385
|
+
this.environment = environmentFromSecretKey(options.apiKey);
|
|
377
386
|
this.transport = new HttpTransport({
|
|
378
387
|
apiKey: options.apiKey,
|
|
379
388
|
baseUrl: options.baseUrl,
|