@suqo/sdk 1.1.0 → 2.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/README.md +2 -1
- package/dist/index.cjs +334 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +489 -95
- package/dist/index.d.ts +489 -95
- package/dist/index.js +334 -51
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors/SuqoError.ts","../src/utils/isRecord.ts","../src/errors/mapHttpError.ts","../src/config/environments.ts","../src/config/SdkConfig.ts","../src/http/urlBuilder.ts","../src/http/retry.ts","../src/http/signals.ts","../src/http/HttpClient.ts","../src/pagination.ts","../src/resources/products.ts","../src/models/Subscription.ts","../src/resources/serialization.ts","../src/resources/subscriptions.ts","../src/resources/customers.ts","../src/resources/webhooks.ts","../src/client.ts","../src/index.ts"],"names":[],"mappings":";;;AAyCO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAQnC,WAAA,CAAY,OAAA,EAAiB,OAAA,GAA4B,EAAC,EAAG;AAC3D,IAAA,KAAA,CAAM,OAAA,EAAS,QAAQ,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI,MAAS,CAAA;AACjF,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AAIvB,IAAA,IAAA,CAAK,UAAU,OAAA,CAAQ,OAAA;AACvB,IAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,MAAA,EAAW,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACxD,IAAA,IAAI,OAAA,CAAQ,SAAA,KAAc,MAAA,EAAW,IAAA,CAAK,YAAY,OAAA,CAAQ,SAAA;AAE9D,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,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AA,EAWT,YAAY,OAAA,EAA4B;AACtC,IAAA,IAAA,CAAK,OAAA,GAAU,IAAI,SAAA,CAAU,OAAO,CAAA;AACpC,IAAA,MAAM,IAAA,GAAO,IAAI,UAAA,CAAW,IAAA,CAAK,OAAO,CAAA;AACxC,IAAA,IAAA,CAAK,QAAA,GAAW,IAAI,gBAAA,CAAiB,IAAI,CAAA;AACzC,IAAA,IAAA,CAAK,aAAA,GAAgB,IAAI,qBAAA,CAAsB,IAAI,CAAA;AACnD,IAAA,IAAA,CAAK,SAAA,GAAY,IAAI,iBAAA,CAAkB,IAAI,CAAA;AAC3C,IAAA,IAAA,CAAK,QAAA,GAAW,IAAI,gBAAA,EAAiB;AAAA,EACvC;AAAA;AAAA,EAGA,IAAI,WAAA,GAA+B;AACjC,IAAA,OAAO,KAAK,OAAA,CAAQ,WAAA;AAAA,EACtB;AAAA;AAAA,EAGA,IAAI,OAAA,GAAkB;AACpB,IAAA,OAAO,KAAK,OAAA,CAAQ,OAAA;AAAA,EACtB;AAAA;AAAA,EAGA,IAAI,OAAA,GAAkB;AACpB,IAAA,OAAO,KAAK,OAAA,CAAQ,OAAA;AAAA,EACtB;AAAA;AAAA,EAGA,IAAI,UAAA,GAAqB;AACvB,IAAA,OAAO,KAAK,OAAA,CAAQ,UAAA;AAAA,EACtB;AAAA;AAAA,EAGA,MAAA,GAAkC;AAChC,IAAA,OAAO,IAAA,CAAK,QAAQ,MAAA,EAAO;AAAA,EAC7B;AAAA;AAAA,EAGA,iBAAC,MAAA,CAAO,GAAA,CAAI,4BAA4B,CAAC,CAAA,GAA6B;AACpE,IAAA,OAAO,KAAK,MAAA,EAAO;AAAA,EACrB;AACF;;;ACpFO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * The full `SuqoError` hierarchy (SDK-SPEC.md §7).\n *\n * Every error thrown by this SDK is an instance of `SuqoError` — but the base class itself is\n * never thrown directly; the SDK always throws one of the subclasses below.\n *\n * @packageDocumentation\n */\n\n/** Options accepted by every {@link SuqoError} subclass constructor. */\nexport interface SuqoErrorOptions {\n /** HTTP status code this error was mapped from, if any (absent for `SuqoConfigError`/`NetworkError` — there was no response). */\n status?: number;\n /** The raw, parsed response body this error was mapped from, if any. */\n rawBody?: unknown;\n /**\n * The backend's request id for this call, if the response included one — ties a failure to a\n * specific server-side log line. Nice-to-have: SUQO backend confirmation on whether/how this is\n * exposed is still pending (docs/implementation-plan.md Ticket 0 item 3) — always optional,\n * never assumed present.\n */\n requestId?: string;\n /** The underlying cause (e.g. the original `fetch` rejection), for debugging — never surfaced to end users directly. */\n cause?: unknown;\n}\n\n/**\n * Base class for every error thrown by the SDK (SDK-SPEC.md §7). Never thrown directly — always\n * one of the subclasses below.\n *\n * @example\n * ```ts\n * try {\n * await suqo.subscriptions.create({ ... });\n * } catch (err) {\n * if (err instanceof SuqoError) {\n * console.error(err.name, err.message, err.status);\n * }\n * }\n * ```\n */\nexport class SuqoError extends Error {\n /** HTTP status code this error was mapped from, if any. */\n readonly status?: number;\n /** The raw, parsed response body this error was mapped from, if any. */\n readonly rawBody?: unknown;\n /** The backend's request id for this call, if one was returned. See {@link SuqoErrorOptions.requestId}. */\n readonly requestId?: string;\n\n constructor(message: string, options: SuqoErrorOptions = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = new.target.name;\n // rawBody's declared type is already `unknown`, so assigning it unconditionally is always\n // valid under exactOptionalPropertyTypes; status/requestId are narrower (string/number) so\n // they're only assigned when actually provided, never as an explicit `undefined`.\n this.rawBody = options.rawBody;\n if (options.status !== undefined) this.status = options.status;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n // Restore the prototype chain so `instanceof` works after transpilation.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Construction-time configuration problems: a malformed API key, or an explicit `baseUrl`\n * override that disagrees with the key's prefix (SDK-SPEC.md §2, §7). Also reused for a call-time\n * argument that would otherwise silently corrupt a request rather than reach the API at all — e.g.\n * an empty `customers.retrieve(id)` (#42) — the same \"never even attempted\" character as a bad\n * construction option. Thrown before any request is made — analogous to a syntax error in the\n * integration, not an HTTP failure. Never carries `status`/`rawBody`; there was no request to map\n * one from.\n */\nexport class SuqoConfigError extends SuqoError {\n constructor(message: string, options: { cause?: unknown } = {}) {\n super(message, options);\n }\n}\n\n/** 401 — the API key is missing, malformed, or inactive (SDK-SPEC.md §7). */\nexport class AuthenticationError extends SuqoError {}\n\n/** Options accepted by {@link KycRequiredError}. */\nexport interface KycRequiredErrorOptions extends SuqoErrorOptions {\n /**\n * The KYC status code from the response body's `status_code` field (openapi.yaml `KycError`).\n * Named `kycStatus`, not `statusCode` — per SDK Naming Map v1.1's rename register, `status_code`\n * \"reads as an HTTP status but carries a KYC status,\" and sits right next to the base class's\n * real HTTP `status` field, so the two must stay visibly distinct.\n */\n kycStatus?: string;\n}\n\n/** 403 — the owning seller has not completed KYC verification (SDK-SPEC.md §7). */\nexport class KycRequiredError extends SuqoError {\n /** The KYC status code from the response body, if present. See {@link KycRequiredErrorOptions.kycStatus}. */\n readonly kycStatus?: string;\n\n constructor(message: string, options: KycRequiredErrorOptions = {}) {\n super(message, options);\n if (options.kycStatus !== undefined) this.kycStatus = options.kycStatus;\n }\n}\n\n/** Field-keyed validation messages, normalized to string arrays regardless of wire shape. */\nexport type FieldErrors = Record<string, string[]>;\n\n/** Options accepted by {@link ValidationError}. */\nexport interface ValidationErrorOptions extends SuqoErrorOptions {\n /** Field-keyed validation messages. Empty if the 400 used the `detail` shape instead. */\n fieldErrors?: FieldErrors;\n}\n\n/**\n * 400 — request validation failed (SDK-SPEC.md §7). The API uses two different 400 body shapes;\n * {@link mapHttpError} normalizes both into this one class so consumers rely on `instanceof`,\n * never the wire shape:\n * - A field-keyed body (`{ field: [\"msg\"] }`) populates {@link fieldErrors}.\n * - A `detail`-shaped body (`{ detail: \"msg\" }`, e.g. the duplicate-active-subscription case)\n * populates `message` instead, with `fieldErrors` left empty.\n */\nexport class ValidationError extends SuqoError {\n /** Field-keyed validation messages. Empty (not undefined) when the 400 used the `detail` shape. */\n readonly fieldErrors: FieldErrors;\n\n constructor(message: string, options: ValidationErrorOptions = {}) {\n super(message, options);\n this.fieldErrors = options.fieldErrors ?? {};\n }\n}\n\n/** 404 — the resource doesn't exist, or doesn't belong to the authenticated seller (SDK-SPEC.md §7). */\nexport class NotFoundError extends SuqoError {}\n\n/** Options accepted by {@link RateLimitError}. */\nexport interface RateLimitErrorOptions extends SuqoErrorOptions {\n /**\n * Suggested backoff derived from a `Retry-After` header, in milliseconds, if present. Named\n * `retryAfter`, not `retryAfterMs` — per SDK Naming Map v1.1, SDK-surface fields drop the `Ms`\n * suffix; the unit is documented, not encoded in the name.\n */\n retryAfter?: number;\n}\n\n/**\n * 429 — rate limited (SDK-SPEC.md §7). **Reserved**: the API does not enforce rate limiting yet\n * and never emits 429 today; this class exists so the SDK is forward-ready the moment it does\n * (SDK-SPEC.md §10).\n */\nexport class RateLimitError extends SuqoError {\n /** Suggested backoff derived from a `Retry-After` header, in milliseconds, if present. See {@link RateLimitErrorOptions.retryAfter}. */\n readonly retryAfter?: number;\n\n constructor(message: string, options: RateLimitErrorOptions = {}) {\n super(message, options);\n if (options.retryAfter !== undefined) this.retryAfter = options.retryAfter;\n }\n}\n\n/** 5xx — the SUQO API failed unexpectedly (SDK-SPEC.md §7). */\nexport class ServerError extends SuqoError {}\n\n/**\n * Transport failure or timeout — the request never got a response at all (SDK-SPEC.md §7). Covers\n * timeouts too; there is no separate timeout class. Thrown directly by `http.ts` (Ticket 2) when\n * `fetch` rejects or an `AbortSignal` fires — never produced by {@link mapHttpError}, since\n * there's no HTTP status to map in that case.\n */\nexport class NetworkError extends SuqoError {}\n","/**\n * True when `value` is a plain object worth reading properties off of — `typeof null` is\n * `\"object\"` in JavaScript, so that's excluded explicitly. Shared by every layer that has to look\n * at an untyped, server-supplied value before trusting its shape (`mapHttpError`'s response\n * bodies, the resource serialization boundary's request/response bodies) — previously duplicated\n * privately in more than one of them.\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n","import {\n AuthenticationError,\n KycRequiredError,\n NotFoundError,\n RateLimitError,\n ServerError,\n SuqoError,\n ValidationError,\n type FieldErrors,\n} from \"./SuqoError.js\";\nimport { isRecord } from \"../utils/index.js\";\n\n/**\n * The shape {@link mapHttpError} needs from a completed HTTP response. Deliberately not a\n * `Response` itself — `http.ts` (Ticket 2) reads the status, parses the body, and extracts\n * headers itself, keeping this module free of any transport-layer dependency.\n */\nexport interface HttpErrorInput {\n /** The response's HTTP status code. */\n status: number;\n /** The response's HTTP status text, if available — used only for the generic fallback message. */\n statusText?: string;\n /**\n * The parsed response body, if the response had one and it parsed as JSON. Expected to be one\n * of `openapi.yaml`'s three error shapes (`FieldError`, `DetailError`, `KycError`) — the shape\n * is detected here, never assumed from the status code alone.\n */\n body?: unknown;\n /** The backend's request id for this call, if one was returned (nice-to-have — Ticket 0 item 3). */\n requestId?: string;\n /**\n * Suggested backoff derived from a `Retry-After` header, in milliseconds. Parsed for any status\n * (found in review: HttpClient's retry loop needs it on retryable 5xxs too, not just 429), but\n * only ever surfaced on the thrown error itself for `RateLimitError` (429) below.\n */\n retryAfter?: number;\n}\n\n/** True when `body` is the `DetailError` shape (`{ detail: \"msg\" }`) rather than field-keyed. */\nfunction isDetailShaped(body: unknown): body is { detail: string } {\n return isRecord(body) && typeof body.detail === \"string\" && body.detail.length > 0;\n}\n\n/**\n * Normalizes a `FieldError` body into `Record<string, string[]>`, flattening nested objects into\n * dot-path keys (`customer.phone`) and renaming the wire's root `client` key to `customer` on the\n * way — SDK Naming Map v1.1 Open Question A, resolved (2026-08-24, confirmed live against\n * `POST /subscriptions/`): a validation failure on the customer payload nests errors under\n * `client` as a real object (`{\"client\": {\"phone\": [\"This field is required.\"]}}`), not a flat\n * dotted key — so this needs path-aware rewriting, not a flat key swap, exactly as the map warned.\n *\n * Only the **root-level** `client` key is renamed (`pathPrefix === \"\"` below) — a field genuinely\n * named `client` nested somewhere else wouldn't be, though no such field exists in the documented\n * API surface today. A value that's neither a string, a string array, nor a nested object worth\n * recursing into is skipped rather than guessed at — this never fabricates a message it wasn't\n * given.\n *\n * The nested-object check explicitly excludes arrays (`!Array.isArray(value)`), even though\n * `isRecord` alone would let one through — `typeof anArray === \"object\"` in JavaScript. Without\n * that exclusion, a field value shaped as a list of objects (e.g.\n * `{\"billing\": [{\"business_name\": [\"required\"]}]}`) would get recursed into using the array's\n * numeric indices as path segments (`billing.0.business_name`) instead of being skipped, silently\n * contradicting the rule stated above (found in review, reproduced).\n */\nfunction fieldErrorsFrom(body: unknown, pathPrefix = \"\"): FieldErrors {\n if (!isRecord(body)) return {};\n const fieldErrors: FieldErrors = {};\n for (const [rawKey, value] of Object.entries(body)) {\n const key = pathPrefix === \"\" && rawKey === \"client\" ? \"customer\" : rawKey;\n const path = pathPrefix === \"\" ? key : `${pathPrefix}.${key}`;\n\n if (typeof value === \"string\") {\n fieldErrors[path] = [value];\n } else if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) {\n fieldErrors[path] = value;\n } else if (isRecord(value) && !Array.isArray(value)) {\n Object.assign(fieldErrors, fieldErrorsFrom(value, path));\n }\n }\n return fieldErrors;\n}\n\n/** Best-effort extraction of a human-readable message from a `DetailError`/`KycError` body. */\nfunction messageFrom(body: unknown, fallback: string): string {\n if (isRecord(body)) {\n if (typeof body.detail === \"string\" && body.detail.length > 0) return body.detail;\n if (typeof body.message === \"string\" && body.message.length > 0) return body.message;\n }\n return fallback;\n}\n\n/**\n * The single, centralized status-code-to-error-class mapper (SDK-SPEC.md §7). Every HTTP response\n * with a non-2xx status is mapped to the correct {@link SuqoError} subclass through this\n * function — no other place in the SDK is allowed to make that decision.\n *\n * Handles both documented 400 body shapes: a field-keyed body populates\n * `ValidationError.fieldErrors`; a `detail`-shaped body (e.g. the duplicate-active-subscription\n * case) populates `ValidationError.message` instead, with `fieldErrors` left empty. A field-keyed\n * body's `client` key (the wire name for the subscription customer payload) is renamed to\n * `customer` and flattened into dot-path keys (`customer.phone`) — SDK Naming Map v1.1 Open\n * Question A, resolved: yes, translate.\n *\n * Does not handle `fetch` throwing or an `AbortSignal` firing — those have no HTTP status and are\n * constructed directly as `NetworkError` by `http.ts` (Ticket 2).\n *\n * @example\n * ```ts\n * const response = await fetch(url);\n * if (!response.ok) {\n * throw mapHttpError({ status: response.status, body: await response.json().catch(() => undefined) });\n * }\n * ```\n */\nexport function mapHttpError(input: HttpErrorInput): SuqoError {\n const { status, statusText, body, requestId, retryAfter } = input;\n const fallbackMessage = `Request failed with status ${status}${statusText ? ` (${statusText})` : \"\"}`;\n // rawBody's declared type is `unknown`, so including it unconditionally is always valid under\n // exactOptionalPropertyTypes; requestId is narrower (string), so it's only spread in when\n // actually provided, never as an explicit `key: undefined`.\n const base = { status, rawBody: body, ...(requestId !== undefined ? { requestId } : {}) };\n\n switch (status) {\n case 401:\n return new AuthenticationError(messageFrom(body, fallbackMessage), base);\n case 403: {\n const kycStatus = isRecord(body) && typeof body.status_code === \"string\" ? body.status_code : undefined;\n const message = messageFrom(body, \"KYC verification needed to perform this action.\");\n return new KycRequiredError(message, { ...base, ...(kycStatus !== undefined ? { kycStatus } : {}) });\n }\n case 400: {\n if (isDetailShaped(body)) {\n return new ValidationError(body.detail, base);\n }\n return new ValidationError(\"Validation failed.\", { ...base, fieldErrors: fieldErrorsFrom(body) });\n }\n case 404:\n return new NotFoundError(messageFrom(body, \"Not found.\"), base);\n case 429:\n return new RateLimitError(messageFrom(body, fallbackMessage), {\n ...base,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n });\n default:\n // 5xx and any genuinely unmapped status both land here. SDK-SPEC.md §7 doesn't define a\n // class for out-of-contract codes, and the base SuqoError is never thrown directly — and\n // openapi.yaml's documented surface never returns anything outside\n // {400, 401, 403, 404, 429, 5xx} today, so this default is a safety net, not an expected path.\n return new ServerError(messageFrom(body, fallbackMessage), base);\n }\n}\n","/**\n * Key-prefix → environment/base-URL inference (SDK-SPEC.md §2).\n *\n * @packageDocumentation\n */\nimport { SuqoConfigError } from \"../errors/SuqoError.js\";\n\n/** The two environments a key prefix resolves to. Never selected explicitly — always inferred. */\nexport type SuqoEnvironment = \"sandbox\" | \"live\";\n\nconst SANDBOX_BASE_URL = \"https://test-be.suqo.ai\";\nconst LIVE_BASE_URL = \"https://be.suqo.ai\";\n\n/**\n * Ordered prefix → environment table. `su_test_key_` MUST be checked before `su_key_`\n * (SDK-SPEC.md §2 rule 4) — the spec calls this out explicitly as an ordering requirement for any\n * prefix matcher, so the order here is deliberate, not incidental.\n */\nconst KEY_PREFIXES: ReadonlyArray<{ prefix: string; environment: SuqoEnvironment; baseUrl: string }> = [\n { prefix: \"su_test_key_\", environment: \"sandbox\", baseUrl: SANDBOX_BASE_URL },\n { prefix: \"su_key_\", environment: \"live\", baseUrl: LIVE_BASE_URL },\n];\n\n/** Result of inferring an environment + base URL from an API key. */\nexport interface ResolvedEnvironment {\n environment: SuqoEnvironment;\n baseUrl: string;\n}\n\n/**\n * Infers the environment and base URL from an API key's prefix — the whole configuration in the\n * common case, no environment flag needed (SDK-SPEC.md §2).\n *\n * @param apiKey - The full API key. Matched with `startsWith`, treating the prefix as \"starts\n * with\", never a substring search anywhere in the key.\n * @param override - An explicit `baseUrl`, if the caller supplied one. Must agree with the\n * inferred base URL or this throws — silence-and-trust-one is forbidden (SDK-SPEC.md §2 rule 3).\n *\n * @throws {SuqoConfigError} if `apiKey` matches neither prefix (rule 2), or if `override` is\n * supplied and disagrees with the inferred base URL (rule 3). Thrown before any request is made.\n */\nexport function resolveEnvironment(apiKey: string, override?: string): ResolvedEnvironment {\n if (typeof apiKey !== \"string\" || apiKey.length === 0) {\n throw new SuqoConfigError(\"A SUQO API key is required.\");\n }\n\n const match = KEY_PREFIXES.find(({ prefix }) => apiKey.startsWith(prefix));\n if (!match) {\n throw new SuqoConfigError(\n 'Malformed SUQO API key: expected prefix \"su_key_\" (live) or \"su_test_key_\" (sandbox).',\n );\n }\n\n if (override !== undefined && override !== match.baseUrl) {\n throw new SuqoConfigError(\n `Environment mismatch: key implies ${match.baseUrl} but baseUrl was set to ${override}. ` +\n \"Remove baseUrl or use a matching key.\",\n );\n }\n\n return { environment: match.environment, baseUrl: override ?? match.baseUrl };\n}\n","import { resolveEnvironment, type SuqoEnvironment } from \"./environments.js\";\n\n/** Input accepted by {@link SdkConfig} — the same shape `SuqoClient`'s constructor takes (addendum §5). */\nexport interface SdkConfigInput {\n /** The seller's API key. Its prefix determines the environment (SDK-SPEC.md §2) — never passed separately. */\n apiKey: string;\n /**\n * Optional explicit override. If set AND it disagrees with the key prefix, the constructor\n * throws `SuqoConfigError`. Normally omit this.\n */\n baseUrl?: string;\n /**\n * Per-client default request timeout in milliseconds; per-call override also allowed by\n * `http.ts` (Ticket 2). Default 30_000. Named `timeout`, not `timeoutMs` — per SDK Naming Map\n * v1.1, SDK-surface fields drop the `Ms` suffix; the unit is documented, not encoded in the name.\n */\n timeout?: number;\n /** Read-retry tuning (reads only — writes are never retried, SDK-SPEC.md §8, §12). Default 2. */\n maxRetries?: number;\n /** Advanced: custom undici dispatcher for pool tuning, passed through opaquely to `fetch` (Ticket 2). */\n dispatcher?: unknown;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_RETRIES = 2;\n\n/** The `util.inspect` custom-inspection symbol, referenced by key so this file never needs to `import \"node:util\"`. */\nconst NODE_INSPECT_CUSTOM = Symbol.for(\"nodejs.util.inspect.custom\");\n\n/**\n * Resolved, immutable SDK configuration (SDK-SPEC.md §2, §4).\n *\n * Validated at construction time — a malformed key or a conflicting `baseUrl` override throws\n * `SuqoConfigError` immediately, before any request is ever made. The API key is stored in a\n * private class field, never a public/enumerable property, so it can never leak through\n * `JSON.stringify`, `console.log`, or `util.inspect` (SDK-SPEC.md §4) — `toJSON` and the\n * `util.inspect` custom-inspection symbol both redact it explicitly as well, so redaction holds\n * even if a future refactor adds an enumerable field.\n *\n * @example\n * ```ts\n * const config = new SdkConfig({ apiKey: \"su_test_key_...\" });\n * config.baseUrl; // => \"https://test-be.suqo.ai\"\n * config.environment; // => \"sandbox\"\n * ```\n */\nexport class SdkConfig {\n /** `\"sandbox\" | \"live\"` — inferred from the key prefix, never selected explicitly. */\n readonly environment: SuqoEnvironment;\n /** The resolved base URL for this environment (or the caller's override, if it agreed). */\n readonly baseUrl: string;\n /** Request timeout in milliseconds, per-client default (`http.ts` in Ticket 2 allows a per-call override). */\n readonly timeout: number;\n /** Max retry attempts for idempotent reads. Writes are never retried regardless of this value. */\n readonly maxRetries: number;\n /** Opaque custom dispatcher for pool tuning, if supplied. Passed through to `fetch` unexamined. */\n readonly dispatcher: unknown;\n\n readonly #apiKey: string;\n\n constructor(input: SdkConfigInput) {\n const { environment, baseUrl } = resolveEnvironment(input.apiKey, input.baseUrl);\n this.environment = environment;\n this.baseUrl = baseUrl;\n this.timeout = input.timeout ?? DEFAULT_TIMEOUT_MS;\n this.maxRetries = input.maxRetries ?? DEFAULT_MAX_RETRIES;\n this.dispatcher = input.dispatcher;\n this.#apiKey = input.apiKey;\n }\n\n /** The raw API key, for building the `Authorization: Bearer <key>` header (`http.ts`, Ticket 2). Never logged. */\n get apiKey(): string {\n return this.#apiKey;\n }\n\n /** Redacts the key so it never appears in `JSON.stringify` output (SDK-SPEC.md §4). */\n toJSON(): Record<string, unknown> {\n return {\n environment: this.environment,\n baseUrl: this.baseUrl,\n timeout: this.timeout,\n maxRetries: this.maxRetries,\n apiKey: \"[redacted]\",\n };\n }\n\n /** Redacts the key so it never appears in `util.inspect`/`console.log` output (SDK-SPEC.md §4). */\n [NODE_INSPECT_CUSTOM](): Record<string, unknown> {\n return this.toJSON();\n }\n}\n","/**\n * URL construction with the trailing slash structurally guaranteed (SDK-SPEC.md §3).\n *\n * @packageDocumentation\n */\n\n/** Query parameter values accepted by {@link buildUrl}. `undefined` values are omitted entirely. */\nexport type QueryParams = Record<string, string | number | boolean | undefined>;\n\n/**\n * Builds a request URL from a base URL and a path, guaranteeing the path ends in `/` — never left\n * to the caller to remember (SDK-SPEC.md §3). Query params are appended *after* the slash, e.g.\n * `/api/v1/subscriptions/?page=2&page_size=50`.\n *\n * `path` may also be an already-complete absolute URL with its own query string already attached\n * (e.g. a pagination envelope's `next` field, Ticket 3) — `baseUrl` is then ignored per the\n * `URL(path, base)` constructor's own semantics, and the existing query string is preserved\n * untouched. This only works correctly because the trailing-slash check below runs against the\n * *parsed pathname*, not the raw input string — checking the raw string (found in review: the\n * original implementation did exactly this) would append `/` after an existing query string and\n * corrupt whichever query param happened to be last (e.g. `page_size=50` silently becoming\n * `page_size=50/`).\n *\n * @param baseUrl - The resolved environment base URL (`SdkConfig.baseUrl`), no trailing slash.\n * @param path - The route path, e.g. `/api/v1/products`, OR an already-complete absolute URL to\n * use as-is (e.g. a `next` link). A missing trailing slash on the *path portion* is added here,\n * not assumed to already be correct — this is the SDK's last line of defense for SDK-SPEC.md §3,\n * not a courtesy extended to a caller who might get it wrong.\n * @param query - Optional query params, merged in on top of any the URL already carries.\n * `undefined` values are skipped, so callers can pass `{ page, pageSize }` straight through\n * without filtering first.\n */\nexport function buildUrl(baseUrl: string, path: string, query?: QueryParams): string {\n const url = new URL(path, baseUrl);\n\n if (!url.pathname.endsWith(\"/\")) {\n url.pathname = `${url.pathname}/`;\n }\n\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) url.searchParams.set(key, String(value));\n }\n }\n\n return url.toString();\n}\n","/**\n * Retry policy: which failures are retryable, bounded attempts, exponential backoff with full\n * jitter (SDK-SPEC.md §8).\n *\n * @packageDocumentation\n */\n\n/**\n * HTTP methods eligible for retry at all.\n *\n * **SINGLE SWITCH** (SDK-SPEC.md §8, §12): every read in this API is `GET` and every write is\n * `POST` or `PATCH` — reads are naturally idempotent, writes are not, and the backend doesn't\n * support idempotency keys yet, so a retried write could double-act. Flip this the moment\n * idempotency keys ship and writes carry one; until then, only `GET` retries.\n */\nconst RETRYABLE_METHODS: ReadonlySet<string> = new Set([\"GET\"]);\n\n/** True if `method` is allowed to retry at all — independent of whether a given failure qualifies. */\nexport function isRetryableMethod(method: string): boolean {\n return RETRYABLE_METHODS.has(method);\n}\n\n/** The failure shape {@link isRetryableFailure} decides on. */\nexport interface RetryableFailureInput {\n /** True if the request never got a response at all (fetch threw / timed out). */\n networkError: boolean;\n /** The HTTP status code, if a response was received. */\n status?: number;\n}\n\n/** True if a failure of this shape should be retried (SDK-SPEC.md §8): network failure, 429, or 5xx. */\nexport function isRetryableFailure(input: RetryableFailureInput): boolean {\n if (input.networkError) return true;\n if (input.status === undefined) return false;\n return input.status === 429 || (input.status >= 500 && input.status <= 599);\n}\n\nconst BASE_DELAY_MS = 500;\nconst MAX_DELAY_MS = 8_000;\n\n/**\n * \"Full jitter\" backoff (SDK-SPEC.md §8: exponential backoff + jitter, bounded attempts): a\n * random delay between 0 and an exponentially growing cap, itself bounded by `MAX_DELAY_MS` so a\n * late retry never waits unboundedly long.\n *\n * @param attempt - 0-indexed retry attempt number (0 = the first retry, after the initial try).\n */\nexport function backoffDelayMs(attempt: number): number {\n const cap = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);\n return Math.random() * cap;\n}\n\n/**\n * Generous cap on a server-supplied `Retry-After`, distinct from `MAX_DELAY_MS` (computed\n * backoff's own cap). `Retry-After` is explicit server guidance, worth respecting well past a\n * guessed backoff's ceiling — but an unbounded value (misconfigured server, or a malicious one)\n * must not stall a request indefinitely (found in review: a `Retry-After: 86400` would otherwise\n * wait a full day with nothing bounding it).\n */\nconst MAX_RETRY_AFTER_MS = 60_000;\n\n/**\n * Parses a `Retry-After` header value into milliseconds, clamped to `MAX_RETRY_AFTER_MS`. Accepts\n * both forms RFC 7231 §7.1.3 allows: the seconds-delta form (e.g. `\"5\"`) and the HTTP-date form\n * (e.g. `\"Wed, 21 Oct 2026 07:28:00 GMT\"`) — accepting only the former is a common bug (SDK Naming\n * Map v1.1), since real servers (and load balancers in front of them) send either. Returns\n * `undefined` if neither form parses, so the caller falls back to computed backoff instead of\n * guessing (SDK-SPEC.md §8: \"Respect Retry-After when present\").\n *\n * @param now - The current time in epoch ms, used to convert an HTTP-date into a delta.\n * Overridable for tests; defaults to `Date.now()`.\n */\nexport function parseRetryAfterMs(headerValue: string | null, now: number = Date.now()): number | undefined {\n if (headerValue === null) return undefined;\n // `Number(\"\")` (and whitespace-only strings) is `0` in JavaScript, not `NaN` — checked\n // explicitly so an empty-but-present header is treated as unparseable, not \"retry after 0ms\"\n // (found in review: this would otherwise hammer a server that just asked to slow down).\n const trimmed = headerValue.trim();\n if (trimmed.length === 0) return undefined;\n\n const seconds = Number(trimmed);\n if (Number.isFinite(seconds)) {\n if (seconds < 0) return undefined;\n return Math.min(seconds * 1000, MAX_RETRY_AFTER_MS);\n }\n\n // Not the delta-seconds form — try the HTTP-date form. `Date.parse` returns `NaN` for anything\n // it can't parse, which also correctly rejects plain garbage strings rather than guessing.\n const dateMs = Date.parse(trimmed);\n if (Number.isNaN(dateMs)) return undefined;\n // A date already in the past means \"retry now,\" not \"unparseable\" or a negative wait.\n const delta = Math.max(dateMs - now, 0);\n return Math.min(delta, MAX_RETRY_AFTER_MS);\n}\n","/**\n * `AbortSignal` combining, with proper listener cleanup (fixes a real leak found in review — see\n * `docs/implementation-plan.md` Ticket 2).\n *\n * @packageDocumentation\n */\n\n/** The result of {@link combineSignals}: the combined signal, plus a cleanup function callers MUST invoke once done with it. */\nexport interface CombinedSignal {\n /** Aborts as soon as any of the input signals do. */\n signal: AbortSignal;\n /**\n * Removes every listener this call attached to the input signals. Without this, a long-lived,\n * caller-supplied signal shared across many calls (e.g. paginating, each attempt retried)\n * accumulates one never-removed listener per call — a real leak, not hypothetical.\n */\n cleanup: () => void;\n}\n\n/**\n * Combines multiple signals into one that aborts as soon as any of them do, with cleanup so\n * listeners don't outlive a single use. Hand-rolled rather than the built-in `AbortSignal.any`\n * (Node 18.17+/20.3+ only) so the SDK's stated Node 18+ floor (addendum §1) holds without a\n * caveat.\n *\n * Callers MUST invoke `cleanup()` once the combined signal is no longer needed (e.g. in a\n * `finally` block) — otherwise this reintroduces the exact listener leak it was written to fix.\n */\nexport function combineSignals(signals: Array<AbortSignal | undefined>): CombinedSignal {\n const controller = new AbortController();\n const cleanupFns: Array<() => void> = [];\n\n for (const signal of signals) {\n if (!signal) continue;\n if (signal.aborted) {\n controller.abort(signal.reason);\n break;\n }\n const onAbort = () => controller.abort(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n cleanupFns.push(() => signal.removeEventListener(\"abort\", onAbort));\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n for (const fn of cleanupFns) fn();\n },\n };\n}\n","import { mapHttpError } from \"../errors/mapHttpError.js\";\nimport { NetworkError, SuqoError } from \"../errors/SuqoError.js\";\nimport type { SdkConfig } from \"../config/index.js\";\nimport { buildUrl, type QueryParams } from \"./urlBuilder.js\";\nimport { backoffDelayMs, isRetryableFailure, isRetryableMethod, parseRetryAfterMs } from \"./retry.js\";\nimport { combineSignals } from \"./signals.js\";\n\n/**\n * HTTP methods this client supports (SDK-SPEC.md §1). `GET` for every read; `POST` for every write\n * except `customers.update()`, the one `PATCH` route.\n */\nexport type HttpMethod = \"GET\" | \"POST\" | \"PATCH\";\n\n/** Fields shared by every request, regardless of method. */\ninterface HttpRequestOptionsBase {\n /** The route path, e.g. `/api/v1/products` — the trailing slash is guaranteed by `buildUrl`; don't add it yourself. */\n path: string;\n /** Query params, appended after the trailing slash. `undefined` values are skipped. */\n query?: QueryParams;\n /** Per-call timeout override, in milliseconds. Defaults to `SdkConfig.timeout`. */\n timeoutMs?: number;\n /**\n * Optional caller-supplied signal for cancelling an in-flight request — e.g. the host\n * application's own request lifecycle ending, or an overall operation deadline spanning\n * multiple SDK calls. Combined with the internal timeout signal (whichever fires first wins)\n * during the fetch itself, *and* observed during any retry backoff wait — cancelling mid-sleep\n * doesn't have to wait for the sleep to finish first. An explicit caller cancellation is never\n * retried, even for an otherwise-retryable read — retrying after the caller said \"stop\" would\n * ignore what they asked for.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Options for a `GET` request. Never carries a body — every read in this API is `GET`\n * (SDK-SPEC.md §1), and `fetch` itself rejects a body on `GET`. Enforced at the type level, not\n * just by convention, so this can't be gotten wrong from a `TBody`-typed call site by accident.\n */\nexport interface HttpGetRequestOptions extends HttpRequestOptionsBase {\n method: \"GET\";\n}\n\n/**\n * Options for a `POST` request. Generic on `TBody` so a call site can pass a concrete request\n * type (e.g. `CreateSubscriptionParams`, wired up in Ticket 4 — the SDK-surface type for\n * `openapi.yaml`'s `CreateSubscriptionRequest` schema; SDK Naming Map v1.1 renames every\n * `*Request` wire schema to `*Params` on the surface, since \"Request\" reads as an HTTP request\n * object, not an SDK input) and have it checked at compile time — `unknown` is only the *default*\n * for callers that don't specify one, never a signal that bodies go untyped by design.\n */\nexport interface HttpPostRequestOptions<TBody = unknown> extends HttpRequestOptionsBase {\n method: \"POST\";\n /** JSON-serializable request body. Omit entirely for a bodyless write (e.g. `cancel`). */\n body?: TBody;\n}\n\n/**\n * Options for a `PATCH` request — a partial update (`customers.update()`). Same body typing as\n * {@link HttpPostRequestOptions}, and like every write it is never retried (SDK-SPEC.md §8).\n */\nexport interface HttpPatchRequestOptions<TBody = unknown> extends HttpRequestOptionsBase {\n method: \"PATCH\";\n /** JSON-serializable request body — only the fields being changed. */\n body?: TBody;\n}\n\n/**\n * Options accepted by {@link HttpClient.request}. `HttpClient` itself is internal (not exported\n * from `src/index.ts`); the SDK's actual typed, consumer-facing contract lives one layer up, in\n * each resource method's own public signature.\n */\nexport type HttpRequestOptions<TBody = unknown> =\n | HttpGetRequestOptions\n | HttpPostRequestOptions<TBody>\n | HttpPatchRequestOptions<TBody>;\n\n/** `RequestInit` extended with undici's non-standard `dispatcher` option (Node's built-in `fetch`, addendum §2). */\ninterface FetchInit extends RequestInit {\n dispatcher?: unknown;\n}\n\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Best-effort JSON parse of a response body. Never throws — an empty or non-JSON body just yields\n * `undefined`, matching `mapHttpError`'s own best-effort philosophy (Ticket 1).\n */\nasync function parseJsonBody(response: Response): Promise<unknown> {\n const text = await response.text();\n if (text.length === 0) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wraps a `fetch` rejection (network failure, `AbortSignal.timeout` firing, or a caller\n * cancellation) as a `NetworkError` (SDK-SPEC.md §7 — covers timeouts too, no separate class).\n */\nfunction toNetworkError(cause: unknown, timeoutMs: number, callerCancelled: boolean): NetworkError {\n if (callerCancelled) {\n return new NetworkError(\"Request cancelled\", { cause });\n }\n if (cause instanceof Error && cause.name === \"TimeoutError\") {\n return new NetworkError(`Request timed out after ${timeoutMs}ms`, { cause });\n }\n const message = cause instanceof Error ? cause.message : String(cause);\n return new NetworkError(`Network request failed: ${message}`, { cause });\n}\n\n/** Options accepted by {@link HttpClient}'s constructor. */\nexport interface HttpClientOptions {\n /**\n * Injectable sleep implementation, so tests can skip real backoff delays. @internal — not part\n * of the public contract; defaults to a real `setTimeout`-based wait in production.\n */\n sleep?: (ms: number) => Promise<void>;\n}\n\n/**\n * The fetch wrapper every resource calls through (SDK-SPEC.md §3, §4, §8; addendum §2, §10).\n *\n * Handles, in one place: the trailing-slash URL guarantee, the `Authorization`/`Content-Type`\n * headers, per-call timeout via `AbortSignal.timeout`, caller-supplied cancellation (`options.\n * signal`, combined with the timeout during the fetch and also observed during any retry backoff\n * wait), the read-only retry policy (exponential backoff + jitter, honoring `Retry-After`,\n * clamped so a misconfigured server can't stall a request indefinitely), and feeding every\n * non-2xx response through `mapHttpError()` so callers only ever see a typed `SuqoError`\n * subclass — never a raw `fetch` rejection or an unparsed error body.\n *\n * Not wired into `SuqoClient`/any resource yet — that lands in Ticket 4.\n */\nexport class HttpClient {\n readonly #config: SdkConfig;\n readonly #sleep: (ms: number) => Promise<void>;\n\n constructor(config: SdkConfig, options: HttpClientOptions = {}) {\n this.#config = config;\n this.#sleep = options.sleep ?? defaultSleep;\n }\n\n /**\n * Sends a request and returns the parsed 2xx body, or throws the `SuqoError` subclass\n * `mapHttpError` maps a non-2xx response to. Writes are never retried (SDK-SPEC.md §8, §12);\n * reads retry on network failure, `429`, or `5xx`, bounded by `SdkConfig.maxRetries`.\n *\n * Generic on both `TResponse` and `TBody` — e.g.\n * `request<CreateSubscriptionResponse, CreateSubscriptionParams>({ body, ... })` — so a\n * resource method (Ticket 4) gets its request body checked against the exact shape it means to\n * send, not just `unknown`.\n */\n async request<TResponse, TBody = unknown>(options: HttpRequestOptions<TBody>): Promise<TResponse> {\n // Defense-in-depth beneath the type-level guarantee (HttpGetRequestOptions has no `body`\n // field at all): a caller that bypasses TypeScript (a raw JS call, or an `as` cast) fails\n // loudly here instead of either crashing deep inside fetch (the original bug) or — worse —\n // silently dropping the body with no error at all, which would be even harder to debug.\n if (options.method === \"GET\" && (options as { body?: unknown }).body !== undefined) {\n throw new TypeError(\"HttpClient.request: a GET request cannot carry a body.\");\n }\n\n // Both steps below wrapped in one try/catch, found in review: a malformed `path` (an\n // unparseable \"next\" link, say) or the off-host guard tripping are pre-flight, one-shot,\n // deterministic failures — they never touched `fetch`, so they must still surface as a typed\n // `NetworkError`, never a raw `TypeError`/`Error`, to hold the class's own documented contract\n // that a caller only ever sees a `SuqoError` subclass, and thrown directly (not fed through\n // the retry loop below) since retrying a malformed URL can never succeed.\n let url: string;\n try {\n url = buildUrl(this.#config.baseUrl, options.path, options.query);\n\n // Security guard: buildUrl accepts an already-complete absolute URL as `path` (needed so a\n // pagination `next` link, Ticket 3, can be followed as-is) — but this client attaches the\n // real API key to every request unconditionally. Without this check, a `next` link that\n // ever pointed off-host (a compromised proxy, a backend bug, tampering) would silently leak\n // the key to that host. `path` being relative always resolves to `baseUrl`'s own origin by\n // construction, so this only ever fires for an absolute `path` that's actually wrong.\n if (new URL(url).origin !== new URL(this.#config.baseUrl).origin) {\n throw new Error(\n `Refusing to send a request to ${new URL(url).origin} — it does not match the ` +\n `configured origin ${new URL(this.#config.baseUrl).origin}. This SDK never sends its ` +\n \"API key to a different host.\",\n );\n }\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n throw new NetworkError(`Invalid request URL: ${message}`, { cause });\n }\n\n const retryable = isRetryableMethod(options.method);\n const maxAttempts = retryable ? this.#config.maxRetries + 1 : 1;\n const timeoutMs = options.timeoutMs ?? this.#config.timeout;\n\n for (let attempt = 1; ; attempt++) {\n const isLastAttempt = attempt >= maxAttempts;\n\n try {\n const response = await this.#doFetch(url, options, timeoutMs);\n\n if (response.ok) {\n return (await parseJsonBody(response)) as TResponse;\n }\n\n // Reading the body can fail too (e.g. the connection resets mid-stream after headers\n // already arrived fine) — that failure needs the exact same retry-or-network-error\n // treatment as `#doFetch` itself failing, not an unmapped rejection escaping `request()`.\n // Wrapping both in the same try/catch below (found in review) is what makes that happen.\n const body = await parseJsonBody(response);\n // Honored on any status, not just 429 (found in review) — a retried 5xx (isRetryableFailure\n // covers 500-599 too) can carry the same header, e.g. a 503 during a maintenance window, and\n // ignoring it there means retrying on our own backoff instead of the wait the server asked for.\n const retryAfter = parseRetryAfterMs(response.headers.get(\"Retry-After\"));\n\n if (\n !isLastAttempt &&\n retryable &&\n isRetryableFailure({ networkError: false, status: response.status })\n ) {\n await this.#sleepOrAbort(retryAfter ?? backoffDelayMs(attempt - 1), options.signal, timeoutMs);\n continue;\n }\n\n throw mapHttpError({\n status: response.status,\n statusText: response.statusText,\n body,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n });\n } catch (cause) {\n // Already a correctly-classified SuqoError (from mapHttpError just above, or a caller\n // cancellation/timeout from #sleepOrAbort) — pass it through unchanged, don't reclassify\n // an already-final decision as a fresh network failure.\n if (cause instanceof SuqoError) throw cause;\n\n // An explicit caller cancellation is never retried, even for a normally-retryable read —\n // continuing after the caller said \"stop\" would ignore what they asked for.\n const callerCancelled = options.signal?.aborted === true;\n // Routed through isRetryableFailure (not inlined) so the retry policy for a network-level\n // failure lives in exactly one place — retry.ts — the same as the HTTP-status decision\n // below. Found in review: an earlier version inlined this as \"always true\" for\n // readability, which let this decision and retry.ts's own copy of it silently drift apart\n // if the policy ever changed in only one of the two places.\n if (!callerCancelled && !isLastAttempt && retryable && isRetryableFailure({ networkError: true })) {\n await this.#sleepOrAbort(backoffDelayMs(attempt - 1), options.signal, timeoutMs);\n continue;\n }\n throw toNetworkError(cause, timeoutMs, callerCancelled);\n }\n }\n }\n\n /**\n * Sleeps for `ms`, but rejects immediately with a \"cancelled\" `NetworkError` if `signal` aborts\n * *during* the wait — a caller cancelling mid-backoff doesn't have to wait for the sleep to\n * finish first (found in review: the previous version ignored `signal` here entirely).\n */\n async #sleepOrAbort(ms: number, signal: AbortSignal | undefined, timeoutMs: number): Promise<void> {\n if (!signal) {\n await this.#sleep(ms);\n return;\n }\n if (signal.aborted) {\n throw toNetworkError(signal.reason, timeoutMs, true);\n }\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => reject(toNetworkError(signal.reason, timeoutMs, true));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n // Clean up on BOTH branches, not just the fulfillment one (found in review) — an injected\n // `sleep` that rejects for a reason unrelated to cancellation would otherwise leave\n // `onAbort` attached to `signal` forever, since `{ once: true }` only self-removes when the\n // \"abort\" event actually fires.\n this.#sleep(ms).then(\n () => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n },\n (sleepError: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(sleepError);\n },\n );\n });\n }\n\n async #doFetch<TBody>(\n url: string,\n options: HttpRequestOptions<TBody>,\n timeoutMs: number,\n ): Promise<Response> {\n const isWrite = options.method !== \"GET\";\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#config.apiKey}`,\n };\n if (isWrite) {\n // SDK-SPEC.md §4: sent on every write, regardless of whether this particular write carries\n // a body (e.g. `cancel` has none).\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n // `body` only exists on the write (POST/PATCH) branches of the HttpRequestOptions union — a\n // GET can't carry one even at the type level (found in review: a GET-with-body used to be\n // constructible, reach fetch, throw there, and get silently retried/masked as a generic\n // NetworkError). Checked as \"not GET\" rather than \"is POST\" so a PATCH body isn't dropped.\n const body = options.method !== \"GET\" ? options.body : undefined;\n\n const { signal, cleanup } = combineSignals([AbortSignal.timeout(timeoutMs), options.signal]);\n try {\n const init: FetchInit = {\n method: options.method,\n headers,\n signal,\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n ...(this.#config.dispatcher !== undefined ? { dispatcher: this.#config.dispatcher } : {}),\n };\n\n return await fetch(url, init);\n } finally {\n // Without this, a long-lived caller-supplied signal shared across many calls/attempts\n // (e.g. paginating, each retried) accumulates one never-removed listener per attempt — a\n // real leak found in review, not hypothetical.\n cleanup();\n }\n }\n}\n","import type { QueryParams } from \"./http/urlBuilder.js\";\n\n/**\n * The common paginated-list envelope every list endpoint returns (SDK-SPEC.md §6).\n *\n * @packageDocumentation\n */\n\n/**\n * The page-number pagination envelope common to every list endpoint (SDK-SPEC.md §6).\n * Named `Page` per the cross-language SDK Naming Map v1.1 §06 (mirrors `openapi.yaml`'s\n * `PaginationEnvelope` schema, renamed on the SDK surface only — the wire shape is unaffected).\n */\nexport interface Page<T> {\n /** Total row count across every page, not just this one. */\n count: number;\n /** URL of the next page, or `null` on the last page. */\n next: string | null;\n /** URL of the previous page, or `null` on the first page. */\n previous: string | null;\n results: T[];\n}\n\n/**\n * The four extra status counts the Subscriptions list adds on top of the common envelope\n * (SDK-SPEC.md §6, `openapi.yaml`'s `SubscriptionListEnvelope`).\n */\nexport interface SubscriptionStatusCounts {\n totalSubscriptions: number;\n activeSubscriptions: number;\n dueSubscriptions: number;\n inactiveSubscriptions: number;\n}\n\n/**\n * The Subscriptions list envelope: the common shape plus the four extra counts, surfaced\n * alongside `results` rather than replacing the common envelope shape (SDK-SPEC.md §6). Generic\n * over `T` so this file doesn't need to know about the `Subscription` type — Ticket 4 supplies it.\n * Named `SubscriptionPage` per the Naming Map §06 (mirrors `openapi.yaml`'s\n * `SubscriptionListEnvelope`, renamed on the SDK surface only).\n */\nexport type SubscriptionPage<T> = Page<T> & SubscriptionStatusCounts;\n\n/** Manual pagination params a caller can pass instead of using `listAll`. */\nexport interface PageParams {\n /** 1-indexed page number. Server default is 1 if omitted. */\n page?: number;\n /** Results per page (server max 100, server default 20 if omitted). */\n pageSize?: number;\n}\n\n/**\n * Maps {@link PageParams}' camelCase fields to the wire's snake_case query params\n * (`pageSize` → `page_size`), so every future paginated resource method shares one mapping\n * instead of re-deriving it. `undefined` fields are omitted, matching `buildUrl`'s own\n * omission rule (Ticket 2) — a caller can pass `{ page, pageSize }` straight through unfiltered.\n */\nexport function toPageQuery(params?: PageParams): QueryParams {\n return {\n page: params?.page,\n page_size: params?.pageSize,\n };\n}\n\n/**\n * Maps a {@link Page}'s `results` through `deserializeItem`, leaving `count`/`next`/`previous`\n * untouched — those three field names already match the wire exactly (`openapi.yaml`\n * `PaginationEnvelope`), only `results`' items need any per-resource field mapping. Shared by\n * every paginated resource so each one only has to supply its own item deserializer, not\n * re-implement unwrapping the envelope.\n */\nexport function deserializePage<TWireItem, T>(\n wire: Page<TWireItem>,\n deserializeItem: (item: TWireItem) => T,\n): Page<T> {\n return {\n count: wire.count,\n next: wire.next,\n previous: wire.previous,\n results: wire.results.map(deserializeItem),\n };\n}\n\n/**\n * Auto-iterates every row across every page, following `next` until it's `null` (SDK-SPEC.md §6),\n * without requiring manual page math. Deliberately decoupled from `HttpClient`/any resource: the\n * caller supplies the already-fetched first page and a `fetchNext` callback that turns a `next`\n * URL into the following page. This keeps pagination testable and reusable across every future\n * paginated resource (Ticket 4) without this file needing to know how HTTP requests are made.\n *\n * Manual `page`/`pageSize` access (via {@link toPageQuery}) remains available independently —\n * this iterator is additive, not a replacement (SDK-SPEC.md §6 requires both to keep working).\n *\n * Guards against a `fetchNext` (or a server) that never reaches `next: null` — a real bug caught\n * in review, not hypothetical, since the loop would otherwise trust the sequence to terminate\n * forever. After `maxPages` pages, throws instead of hanging silently.\n *\n * @param maxPages - Safety cap on how many pages to follow before giving up. Defaults to a limit\n * generous enough for any realistic result set (10,000 pages — millions of rows at the max page\n * size) while still catching a genuine stuck loop quickly.\n *\n * @example\n * ```ts\n * const firstPage = await suqo.subscriptions.list({ pageSize: 100 });\n * for await (const subscription of listAll(firstPage, fetchNextPage)) {\n * // subscription: Subscription\n * }\n * ```\n */\nexport async function* listAll<T>(\n firstPage: Page<T>,\n fetchNext: (nextUrl: string) => Promise<Page<T>>,\n maxPages = 10_000,\n): AsyncIterableIterator<T> {\n let page: Page<T> = firstPage;\n let pagesSeen = 0;\n\n while (true) {\n pagesSeen++;\n if (pagesSeen > maxPages) {\n throw new Error(\n `listAll exceeded ${maxPages} pages without reaching next: null. This usually means the ` +\n \"server or the fetchNext callback isn't advancing — check for a stuck loop.\",\n );\n }\n\n for (const item of page.results) {\n yield item;\n }\n\n if (page.next === null) {\n return;\n }\n\n page = await fetchNext(page.next);\n }\n}\n\n/**\n * Bridges {@link listAll} to a resource's public `.autoPaging()` method (SDK Naming Map v1.1 §04\n * — the public name is `.autoPaging()`; `listAll` stays this file's own internal engine name, per\n * Ticket 3's design doc). Named `bridgeAutoPaging`, not `autoPaging`, specifically so it never\n * shares a name with the public method that calls it — the two would still resolve correctly\n * either way (a class method name isn't a lexical binding inside its own body), but a distinct\n * name means nobody has to reason through that to be sure.\n *\n * Takes the first page as a **thunk** (`() => Promise<Page<T>>`), not an already-started\n * `Promise` — this is deliberate, not a style choice. A resource method's `.autoPaging()` calls\n * `this.list(params)` to build that first request; if that call happened eagerly (i.e. the caller\n * passed the `Promise` itself), it would start firing the instant `.autoPaging()` is invoked, not\n * when the caller actually begins iterating — and a rejection sitting unhandled between those two\n * moments is a genuine `unhandledRejection`, which terminates a Node process by default (found in\n * review, reproduced: calling `.autoPaging()` then doing anything else before iterating, on a\n * request that fails, crashes the process — confirmed both with and without a handler attached).\n * Wrapping the call in a thunk (`() => this.list(params)`) defers it until the async generator\n * body actually runs `fetchFirstPage()`, which only happens once the caller starts iterating —\n * matching every other async generator's behavior for real, not just by the doc comment's claim.\n *\n * Still fully decoupled from `HttpClient`/any resource, same as {@link listAll} — this file never\n * imports anything from the HTTP layer.\n *\n * @example\n * ```ts\n * autoPaging(params?: PageParams): AsyncIterableIterator<Product> {\n * return bridgeAutoPaging(() => this.list(params), (nextUrl) =>\n * this.#http.request<Page<Product>>({ method: \"GET\", path: nextUrl }),\n * );\n * }\n * ```\n */\nexport function bridgeAutoPaging<T>(\n fetchFirstPage: () => Promise<Page<T>>,\n fetchNext: (nextUrl: string) => Promise<Page<T>>,\n maxPages = 10_000,\n): AsyncIterableIterator<T> {\n return (async function* () {\n yield* listAll(await fetchFirstPage(), fetchNext, maxPages);\n })();\n}\n","import type { HttpClient } from \"../http/HttpClient.js\";\nimport { bridgeAutoPaging, deserializePage, toPageQuery, type Page, type PageParams } from \"../pagination.js\";\nimport type { BillingPeriod, Plan, Product, ProductVat } from \"../models/index.js\";\n\n/** `GET /api/v1/products/` — no trailing slash here; `HttpClient`/`buildUrl` guarantees it (Ticket 2). */\nconst PRODUCTS_PATH = \"/api/v1/products\";\n\n/**\n * The wire shapes `openapi.yaml`'s `Product`/`Plan`/`BillingPeriod` schemas actually send —\n * snake_case, exactly as documented. `HttpClient.request()` doesn't transform response bodies at\n * all (SDK-SPEC.md §5's camelCase requirement is this file's job, not the transport layer's), so\n * every field below is deserialized explicitly rather than trusted via a type assertion alone.\n */\ninterface WireBillingPeriod {\n pbp_id: string;\n interval_type: string;\n interval_count: number;\n label: string;\n price: string;\n currency: string;\n is_current: boolean;\n is_limited: boolean;\n is_archived: boolean;\n offers: unknown[];\n}\n\ninterface WirePlan {\n plan_id: string;\n plan_name: string;\n description: string;\n // Optional, not required — `openapi.yaml`'s Product schema has no `required` list at all, so\n // omitting this key entirely is spec-legal (found in review: the deserializer used to assume\n // it was always present and crashed on `.map()` when it wasn't).\n billing_periods?: WireBillingPeriod[];\n}\n\ninterface WireProductVat {\n is_vat_active: boolean;\n vat_type: string;\n vat_percentage: string;\n}\n\ninterface WireProductImage {\n image: string;\n image_order: number;\n}\n\ninterface WireProduct {\n product_id: string;\n name: string;\n description: string;\n type: string;\n is_active: boolean;\n terms_and_conditions: string;\n features_and_benefits: string;\n // Optional (not just nullable) and `plan` optional too — same reasoning as `WirePlan.billing_periods`\n // above: no `required` list on this schema, so both are legally omittable, not just nullable.\n vat?: WireProductVat | null;\n // Objects, not URL strings — `openapi.yaml` previously declared `string[]`, which never matched\n // the wire (Swagger's `ProductImage` and a captured response both show `{ image, image_order }`).\n // Optional for the same no-`required`-list reason as `plan`.\n product_image?: WireProductImage[];\n plan?: WirePlan[];\n total_subscribers: string;\n created_at: string;\n updated_at: string;\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializeBillingPeriod(wire: WireBillingPeriod): BillingPeriod {\n return {\n pbpId: wire.pbp_id,\n intervalType: wire.interval_type,\n intervalCount: wire.interval_count,\n label: wire.label,\n price: wire.price,\n currency: wire.currency,\n isCurrent: wire.is_current,\n isLimited: wire.is_limited,\n isArchived: wire.is_archived,\n offers: wire.offers,\n };\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializePlan(wire: WirePlan): Plan {\n return {\n planId: wire.plan_id,\n planName: wire.plan_name,\n description: wire.description,\n // `openapi.yaml`'s Product schema has no `required` list at all, so `billing_periods` being\n // omitted entirely (not just an empty array) is spec-legal — `?? []` degrades to an empty\n // list instead of `.map` throwing on `undefined` (found in review, reproduced).\n billingPeriods: (wire.billing_periods ?? []).map(deserializeBillingPeriod),\n };\n}\n\nfunction deserializeProductVat(wire: WireProductVat): ProductVat {\n return {\n isVatActive: wire.is_vat_active,\n vatType: wire.vat_type,\n vatPercentage: wire.vat_percentage,\n };\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializeProduct(wire: WireProduct): Product {\n return {\n productId: wire.product_id,\n name: wire.name,\n description: wire.description,\n type: wire.type,\n isActive: wire.is_active,\n termsAndConditions: wire.terms_and_conditions,\n featuresAndBenefits: wire.features_and_benefits,\n // `== null` (not `=== null`) is deliberate — it catches both an explicit `null` and an\n // entirely omitted `vat` key. `openapi.yaml` has no `required` list for Product, so omitting\n // `vat` is spec-legal, and the old `=== null` check crashed on `deserializeProductVat(undefined)`\n // when that happened (found in review, reproduced).\n vat: wire.vat == null ? null : deserializeProductVat(wire.vat),\n productImage: (wire.product_image ?? []).map((img) => ({ image: img.image, imageOrder: img.image_order })),\n // Same reasoning as `billingPeriods` above — `plan` being omitted entirely is spec-legal.\n plan: (wire.plan ?? []).map(deserializePlan),\n totalSubscribers: wire.total_subscribers,\n createdAt: wire.created_at,\n updatedAt: wire.updated_at,\n };\n}\n\n/**\n * `client.products` (SDK-SPEC.md §5, §6; `openapi.yaml` `listProducts`). The only resource that\n * works before KYC verification — no `KycRequiredError` case to handle here.\n */\nexport class ProductsResource {\n readonly #http: HttpClient;\n\n constructor(http: HttpClient) {\n this.#http = http;\n }\n\n /** Lists the authenticated seller's active products. Paginated (SDK-SPEC.md §6). */\n async list(params?: PageParams): Promise<Page<Product>> {\n const wire = await this.#http.request<Page<WireProduct>>({\n method: \"GET\",\n path: PRODUCTS_PATH,\n query: toPageQuery(params),\n });\n return deserializePage(wire, deserializeProduct);\n }\n\n /**\n * Auto-iterates every product across every page, following `next` until it's `null`\n * (SDK-SPEC.md §6). Manual `list({ page, pageSize })` remains available independently — this is\n * additive, not a replacement.\n */\n autoPaging(params?: PageParams): AsyncIterableIterator<Product> {\n return bridgeAutoPaging(() => this.list(params), async (nextUrl) => {\n const wire = await this.#http.request<Page<WireProduct>>({ method: \"GET\", path: nextUrl });\n return deserializePage(wire, deserializeProduct);\n });\n }\n}\n","import type { SubscriptionCustomer } from \"./Customer.js\";\n\n/**\n * `Subscription`'s model types (`specs/openapi.yaml` `Subscription`/`SubscriptionProduct`/\n * `SubscriptionStatus` — SDK-SPEC.md §5).\n *\n * @packageDocumentation\n */\n\n/**\n * The subscription lifecycle enum (`openapi.yaml` `SubscriptionStatus`). Wire values are\n * invariant (R1); this is a constant object + derived union, not a TypeScript `enum` — a plain\n * union alone can't be iterated/round-tripped the way SDK Naming Map v1.1 §10 requires: \"decoders\n * must round-trip an unknown value rather than raising,\" so an unrecognized status the API adds\n * later (before this SDK's next release) passes through as a plain string instead of throwing.\n */\nexport const SubscriptionStatus = {\n /** Newly created; the buyer hasn't paid yet. */\n PendingCheckout: \"pending_checkout\",\n /** Currently active. */\n Active: \"active\",\n /** `nextBillingCycle` passed with no payment yet. */\n Due: \"due\",\n /** Cancelled immediately (user-prompted). */\n Cancelled: \"cancelled\",\n /** Scheduled to cancel at the end of the current billing cycle — see SDK-SPEC.md §5's `cancel` note. */\n PendingCancellation: \"pending_cancellation\",\n /** Auto-ended after a grace period without payment. */\n Inactive: \"inactive\",\n} as const;\n\n/**\n * Any known {@link SubscriptionStatus} wire value, OR an arbitrary string. The `& {}` intersection\n * is deliberate, not a typo — a bare `string` union member would collapse the whole type to\n * `string` and lose autocomplete for the known values; this keeps both: editor autocomplete\n * suggests the six known values, but an unrecognized one the API adds later still assigns without\n * a cast, satisfying the module doc's round-trip requirement at the type level too, not just at\n * runtime.\n */\n// This is the \"loose autocomplete\" idiom (see the doc comment above), not an accidental `{}`. The\n// lint rule's own suggested fix, `NonNullable<unknown>`, resolves to plain `unknown`, and\n// `string & unknown` collapses right back to `string` — throwing away exactly the\n// autocomplete-for-known-values this type exists to keep.\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport type SubscriptionStatus = (typeof SubscriptionStatus)[keyof typeof SubscriptionStatus] | (string & {});\n\n/** The product summary embedded on a {@link Subscription} (`openapi.yaml` `SubscriptionProduct`) — a summary, not the full {@link import(\"./Product.js\").Product} record. */\nexport interface SubscriptionProduct {\n productId: string;\n name: string;\n planName: string;\n /** Pass this to `subscriptions.create({ pbpId, ... })`. */\n pbpId: string;\n label: string;\n /** Decimal string. Never coerced to a number — SDK-SPEC.md §5. */\n price: string;\n currency: string;\n}\n\n/** A seller's subscription (`openapi.yaml` `Subscription`). */\nexport interface Subscription {\n subscriptionId: string;\n status: SubscriptionStatus;\n /** `true` iff `status === SubscriptionStatus.Active`. */\n isActive: boolean;\n /** The buyer, in the read shape — renamed from the wire's `client` (SDK Naming Map v1.1 §11). */\n customer: SubscriptionCustomer;\n /** `null` if the backend omits or nulls this field — `openapi.yaml` declares no required fields on `Subscription` (found in review). */\n product: SubscriptionProduct | null;\n currentPeriodStart: string | null;\n /** Equals `nextBillingCycle`. */\n currentPeriodEnd: string | null;\n /** The date this subscription bills next (same value as `currentPeriodEnd`). */\n nextBillingCycle: string | null;\n createdAt: string;\n}\n","import type { CustomerInput, SubscriptionCustomer } from \"../models/index.js\";\nimport { isRecord } from \"../utils/index.js\";\n\n/**\n * The customer↔client serialization boundary (SDK Naming Map v1.1 §11 \"Customer boundary\").\n * `openapi.yaml` keeps `client`; the SDK surfaces `customer` — that divergence is deliberate (the\n * wire name collides with the SDK's own client object), but it means the translation has to\n * happen *somewhere*, exactly once. This module is that one place: no resource method, no error\n * class, and no transport code (`HttpClient`) touches this mapping directly — they call through\n * here instead.\n *\n * Both directions are asymmetric on the wire, not just renamed (`specs/openapi.yaml`\n * `ClientRead`/`ClientWrite`):\n * - **Write** (`ClientWrite`, this file's {@link serializeCustomerInput}): the nested `billing`\n * object's own fields carry a `billing_` prefix (`businessName` → `billing_business_name`), but\n * `shipping`'s fields don't (`fullName` → `full_name`, no prefix). This is a real backend\n * quirk, not something to \"fix\" here — the serializer has to reproduce it exactly.\n * - **Read** (`ClientRead`, this file's {@link deserializeSubscriptionCustomer}): neither nested\n * object carries a prefix at all (`business_name`, not `billing_business_name`).\n *\n * `rawBody` is never touched by either function (R1) — this boundary only affects the typed\n * `customer`/`SubscriptionCustomer` a resource method hands back, never what a caller sees if they\n * inspect an error's `rawBody`.\n *\n * @packageDocumentation\n */\n\n/**\n * `CustomerInput` (SDK) → the wire's `ClientWrite` shape, for `subscriptions.create()`'s request\n * body. The caller is responsible for nesting the result under the wire's `client` key — this\n * function only produces the object that goes there, so it stays agnostic of where it's mounted.\n */\nexport function serializeCustomerInput(customer: CustomerInput): Record<string, unknown> {\n const wire: Record<string, unknown> = {\n phone: customer.phone,\n full_name: customer.fullName,\n email: customer.email,\n address: customer.address,\n };\n\n if (customer.billing) {\n const billing: Record<string, unknown> = {\n billing_business_name: customer.billing.businessName,\n billing_email: customer.billing.email,\n billing_address: customer.billing.address,\n };\n if (customer.billing.panVat !== undefined) billing.billing_pan_vat = customer.billing.panVat;\n wire.billing = billing;\n }\n\n if (customer.shipping) {\n const shipping: Record<string, unknown> = {\n phone: customer.shipping.phone,\n full_name: customer.shipping.fullName,\n email: customer.shipping.email,\n };\n if (customer.shipping.address !== undefined) shipping.address = customer.shipping.address;\n wire.shipping = shipping;\n }\n\n return wire;\n}\n\n/**\n * The wire's `ClientRead` shape (already unwrapped from `client`) → `SubscriptionCustomer` (SDK).\n * Best-effort, like `mapHttpError`'s own body parsing: a field of the wrong type or a\n * malformed/missing nested object is simply omitted rather than fabricated or thrown on — a\n * `Subscription` a caller already has in hand shouldn't become unusable because of one\n * unexpected field.\n */\nexport function deserializeSubscriptionCustomer(wire: unknown): SubscriptionCustomer {\n if (!isRecord(wire)) return {};\n\n const customer: SubscriptionCustomer = {};\n if (typeof wire.phone === \"string\") customer.phone = wire.phone;\n if (typeof wire.full_name === \"string\") customer.fullName = wire.full_name;\n if (typeof wire.email === \"string\") customer.email = wire.email;\n if (typeof wire.address === \"string\") customer.address = wire.address;\n\n if (isRecord(wire.billing)) {\n customer.billing = {\n ...(typeof wire.billing.business_name === \"string\" ? { businessName: wire.billing.business_name } : {}),\n ...(typeof wire.billing.email === \"string\" ? { email: wire.billing.email } : {}),\n ...(typeof wire.billing.address === \"string\" ? { address: wire.billing.address } : {}),\n ...(typeof wire.billing.pan_vat === \"string\" ? { panVat: wire.billing.pan_vat } : {}),\n };\n } else if (wire.billing === null) {\n customer.billing = null;\n }\n\n if (isRecord(wire.shipping)) {\n customer.shipping = {\n ...(typeof wire.shipping.phone === \"string\" ? { phone: wire.shipping.phone } : {}),\n ...(typeof wire.shipping.full_name === \"string\" ? { fullName: wire.shipping.full_name } : {}),\n ...(typeof wire.shipping.email === \"string\" ? { email: wire.shipping.email } : {}),\n ...(typeof wire.shipping.address === \"string\" ? { address: wire.shipping.address } : {}),\n };\n } else if (wire.shipping === null) {\n customer.shipping = null;\n }\n\n return customer;\n}\n","import type { HttpClient } from \"../http/HttpClient.js\";\nimport { bridgeAutoPaging, toPageQuery, type PageParams, type SubscriptionPage } from \"../pagination.js\";\nimport { SubscriptionStatus, type Subscription, type SubscriptionProduct } from \"../models/Subscription.js\";\nimport type {\n CreateSubscriptionParams,\n CreateSubscriptionResponse,\n MessageResponse,\n UpdateBillingCycleParams,\n} from \"../models/index.js\";\nimport { deserializeSubscriptionCustomer, serializeCustomerInput } from \"./serialization.js\";\n\n/** No trailing slash here; `HttpClient`/`buildUrl` guarantees it (Ticket 2). */\nconst SUBSCRIPTIONS_PATH = \"/api/v1/subscriptions\";\n\n/** The wire shape `openapi.yaml`'s `SubscriptionProduct` schema sends — a summary, not the full `Product`. */\ninterface WireSubscriptionProduct {\n product_id: string;\n name: string;\n plan_name: string;\n pbp_id: string;\n label: string;\n price: string;\n currency: string;\n}\n\n/**\n * The wire shape `openapi.yaml`'s `Subscription` schema sends. `client` is `unknown` here, not a\n * typed wire interface — {@link deserializeSubscriptionCustomer} (`./serialization.js`) already\n * accepts `unknown` and is best-effort about its shape, so there's no value duplicating that\n * typing here too.\n */\ninterface WireSubscription {\n subscription_id: string;\n status: string;\n is_active: boolean;\n client: unknown;\n // `WireSubscriptionProduct | null`, optional too (found in review): `openapi.yaml`'s\n // Subscription schema has no `required` list at all, the same gap already handled defensively\n // for Product's `vat` (`WireProductVat | null`, also optional) — so an omitted *or* explicitly\n // null `product` key is spec-legal here too, not just a hypothetical.\n product?: WireSubscriptionProduct | null;\n current_period_start: string | null;\n current_period_end: string | null;\n next_billing_cycle: string | null;\n created_at: string;\n}\n\n/** `openapi.yaml`'s `SubscriptionListEnvelope` — `PaginationEnvelope` plus the four extra counts. */\ninterface WireSubscriptionListEnvelope {\n count: number;\n next: string | null;\n previous: string | null;\n total_subscriptions: number;\n active_subscriptions: number;\n due_subscriptions: number;\n inactive_subscriptions: number;\n results: WireSubscription[];\n}\n\n/** `openapi.yaml`'s `CreateSubscriptionResponse` — no field renames, just casing (§06). */\ninterface WireCreateSubscriptionResponse {\n subscription_id: string;\n pbp_id: string;\n /** The wire guarantees this exact const value on every response (openapi.yaml `const: pending_checkout`). */\n status: typeof SubscriptionStatus.PendingCheckout;\n checkout_url: string;\n next_billing_cycle: string | null;\n created_at: string;\n}\n\nfunction deserializeSubscriptionProduct(wire: WireSubscriptionProduct): SubscriptionProduct {\n return {\n productId: wire.product_id,\n name: wire.name,\n planName: wire.plan_name,\n pbpId: wire.pbp_id,\n label: wire.label,\n price: wire.price,\n currency: wire.currency,\n };\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializeSubscription(wire: WireSubscription): Subscription {\n return {\n subscriptionId: wire.subscription_id,\n status: wire.status,\n isActive: wire.is_active,\n // Renamed from the wire's `client` — SDK Naming Map v1.1 §11 \"Customer boundary\".\n customer: deserializeSubscriptionCustomer(wire.client),\n // `== null` (not `=== null`) is deliberate — same reasoning as Product's `vat` field: catches\n // both an explicit `null` and an entirely omitted `product` key, either of which is spec-legal\n // since `openapi.yaml`'s Subscription schema has no `required` list. The old unconditional call\n // crashed on `deserializeSubscriptionProduct(undefined)` when the key was omitted (found in\n // review, reproduced).\n product: wire.product == null ? null : deserializeSubscriptionProduct(wire.product),\n currentPeriodStart: wire.current_period_start,\n currentPeriodEnd: wire.current_period_end,\n nextBillingCycle: wire.next_billing_cycle,\n createdAt: wire.created_at,\n };\n}\n\n/**\n * Exported for direct unit testing — not part of the SDK's public surface. Unlike\n * {@link import(\"../pagination.js\").deserializePage}, this can't be the generic helper — the four\n * extra counts aren't part of `Page<T>`'s shape at all, so this envelope needs its own mapping.\n */\nexport function deserializeSubscriptionPage(wire: WireSubscriptionListEnvelope): SubscriptionPage<Subscription> {\n return {\n count: wire.count,\n next: wire.next,\n previous: wire.previous,\n totalSubscriptions: wire.total_subscriptions,\n activeSubscriptions: wire.active_subscriptions,\n dueSubscriptions: wire.due_subscriptions,\n inactiveSubscriptions: wire.inactive_subscriptions,\n results: wire.results.map(deserializeSubscription),\n };\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializeCreateSubscriptionResponse(\n wire: WireCreateSubscriptionResponse,\n): CreateSubscriptionResponse {\n return {\n subscriptionId: wire.subscription_id,\n pbpId: wire.pbp_id,\n status: wire.status,\n checkoutUrl: wire.checkout_url,\n nextBillingCycle: wire.next_billing_cycle,\n createdAt: wire.created_at,\n };\n}\n\n/**\n * `client.subscriptions` (SDK-SPEC.md §5, §6, §7; `openapi.yaml` `listSubscriptions`/\n * `createSubscription`/`cancelSubscription`/`updateBillingCycle`/`resumeSubscription`).\n *\n * `retrieve(id)` is deliberately **not** implemented — still blocked on a real sample response\n * from backend (docs/implementation-plan.md Ticket 4). Every other operation here is confirmed.\n */\nexport class SubscriptionsResource {\n readonly #http: HttpClient;\n\n constructor(http: HttpClient) {\n this.#http = http;\n }\n\n /**\n * Lists the seller's subscriptions. Paginated, with four extra status counts alongside the\n * common envelope (SDK-SPEC.md §6).\n */\n async list(params?: PageParams): Promise<SubscriptionPage<Subscription>> {\n const wire = await this.#http.request<WireSubscriptionListEnvelope>({\n method: \"GET\",\n path: SUBSCRIPTIONS_PATH,\n query: toPageQuery(params),\n });\n return deserializeSubscriptionPage(wire);\n }\n\n /**\n * Auto-iterates every subscription across every page, following `next` until it's `null`\n * (SDK-SPEC.md §6). Manual `list({ page, pageSize })` remains available independently.\n */\n autoPaging(params?: PageParams): AsyncIterableIterator<Subscription> {\n return bridgeAutoPaging(() => this.list(params), async (nextUrl) => {\n const wire = await this.#http.request<WireSubscriptionListEnvelope>({ method: \"GET\", path: nextUrl });\n return deserializeSubscriptionPage(wire);\n });\n }\n\n /**\n * Creates a subscription in `pending_checkout` state and returns a checkout URL for the buyer\n * to pay (SDK-SPEC.md §5). Redirect the buyer to `checkoutUrl`; the return is **not** proof of\n * payment — learn the real outcome via the `checkout.succeeded`/`checkout.failed` webhooks.\n *\n * Reuse behavior: an inactive/expired subscription for the same buyer + product + billing\n * period is reactivated rather than duplicated; only a currently `active` one triggers the\n * duplicate-subscription `ValidationError`.\n *\n * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).\n */\n async create(params: CreateSubscriptionParams): Promise<CreateSubscriptionResponse> {\n const wire = await this.#http.request<WireCreateSubscriptionResponse, unknown>({\n method: \"POST\",\n path: SUBSCRIPTIONS_PATH,\n body: {\n pbp_id: params.pbpId,\n return_url: params.returnUrl,\n // Renamed from the wire's `client` — SDK Naming Map v1.1 §11 \"Customer boundary\".\n client: serializeCustomerInput(params.customer),\n },\n });\n return deserializeCreateSubscriptionResponse(wire);\n }\n\n /**\n * Schedules cancellation for the end of the current billing period — **not** immediate\n * (confirmed with backend 2026-08-17; immediate cancellation is a future capability). Status\n * moves to `pending_cancellation`; the subscription stays active until the period ends.\n *\n * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).\n */\n async cancel(id: string): Promise<MessageResponse> {\n // encodeURIComponent, found in review: an unescaped id containing `?`/`#`/`/` would otherwise\n // be parsed as URL structure by buildUrl's `new URL(path, base)`, silently corrupting the\n // path instead of erroring — e.g. `?` truncates everything after it, swallowing `/cancel`\n // into the query string.\n return this.#http.request<MessageResponse>({\n method: \"POST\",\n path: `${SUBSCRIPTIONS_PATH}/${encodeURIComponent(id)}/cancel`,\n });\n }\n\n /**\n * Sets a subscription's next billing date. Collection-level action — the subscription id\n * travels in the body, not the path, mirroring the wire (SDK Naming Map v1.1 §04).\n *\n * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).\n */\n async updateBillingCycle(params: UpdateBillingCycleParams): Promise<MessageResponse> {\n return this.#http.request<MessageResponse, unknown>({\n method: \"POST\",\n path: `${SUBSCRIPTIONS_PATH}/update-billing-cycle`,\n body: {\n subscription_id: params.subscriptionId,\n next_billing_cycle: params.nextBillingCycle,\n },\n });\n }\n\n /**\n * Resumes a subscription. Confirmed public with backend (2026-08-18); the response shape\n * follows Swagger's `{ message }` example but — unlike Customers — isn't independently\n * confirmed, so treat it as likely-correct-but-unverified (docs/implementation-plan.md Ticket 4).\n *\n * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).\n */\n async resume(id: string): Promise<MessageResponse> {\n // encodeURIComponent, found in review: same path-corruption risk as cancel() above.\n return this.#http.request<MessageResponse>({\n method: \"POST\",\n path: `${SUBSCRIPTIONS_PATH}/${encodeURIComponent(id)}/resume`,\n });\n }\n}\n","import type { HttpClient } from \"../http/HttpClient.js\";\nimport { bridgeAutoPaging, deserializePage, toPageQuery, type Page, type PageParams } from \"../pagination.js\";\nimport type { CreateCustomerParams, Customer, UpdateCustomerParams } from \"../models/index.js\";\nimport { SuqoConfigError } from \"../errors/SuqoError.js\";\n\n/** `GET /api/v1/customers/` — no trailing slash here; `HttpClient`/`buildUrl` guarantees it (Ticket 2). */\nconst CUSTOMERS_PATH = \"/api/v1/customers\";\n\n/**\n * The wire shape `openapi.yaml`'s `Customer` schema actually sends — snake_case. Uses `buyer_*`\n * prefixes, not the `client.*` nesting Subscriptions uses — carried through as its own convention,\n * not forced into the customer/client boundary's shape (that boundary is only about the\n * Subscriptions payload's embedded buyer, a genuinely different concept from this resource's own\n * record).\n *\n * `id` corrected to `string` and `address` added (Bug #42, found in review against the live\n * sandbox) — both were wrong in the version originally \"confirmed live 2026-08-18\": that\n * confirmation never actually matched what the API returns, it just went unnoticed until now.\n */\ninterface WireCustomer {\n id: string;\n // Optional, not just nullable, on all four of these (found in review, closing the class #42's\n // address fix opened): openapi.yaml's Customer schema only requires `id`/`created_at` — none of\n // these four are in `required`, and src/generated/schema.ts already reflects that (`?:` on all\n // four). This hand-written interface originally declared `address` the same required-but-wrong\n // way it still declared these three, so an entirely omitted key (spec-legal for any of them)\n // produced `undefined` here, flowing straight into a `Customer` type that promises `string |\n // null`, never `undefined`. Same class of bug as #42 itself: a declared type the wire never\n // actually promised.\n buyer_phone?: string | null;\n buyer_email?: string | null;\n full_name?: string | null;\n address?: string | null;\n created_at: string;\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializeCustomer(wire: WireCustomer): Customer {\n return {\n id: wire.id,\n // `?? null` on all four nullable fields (not a direct pass-through, found in review): catches\n // both an explicit `null` and an entirely omitted key — see the WireCustomer comment above.\n buyerPhone: wire.buyer_phone ?? null,\n buyerEmail: wire.buyer_email ?? null,\n fullName: wire.full_name ?? null,\n address: wire.address ?? null,\n createdAt: wire.created_at,\n };\n}\n\n/**\n * The fields `create()` and `update()` share (SDK) → the wire's write shape. Only keys the caller\n * actually set are sent: on `update()` an omitted field must stay untouched server-side, while\n * `\"\"` is a deliberate clear — so `undefined` is dropped and `\"\"` is passed through as-is.\n *\n * Deliberately never reads `phone` (found in review): TypeScript only checks excess properties on\n * object literals, so `update(id, formState)` compiles even when `formState` carries a phone. The\n * API rejects any phone but the current one, so passing it through would fail the whole update.\n * `create()` adds `phone` itself.\n */\nfunction serializeCustomerFields(params: UpdateCustomerParams): Record<string, unknown> {\n const wire: Record<string, unknown> = {};\n if (params.fullName !== undefined) wire.full_name = params.fullName;\n if (params.email !== undefined) wire.email = params.email;\n if (params.address !== undefined) wire.address = params.address;\n return wire;\n}\n\n/**\n * Rejects an id that would resolve to a different endpoint than the one intended. `\"\"` collapses\n * onto the collection URL (`encodeURIComponent(\"\")` is `\"\"`); `\".\"` and `\"..\"` do too, or climb\n * above it, because `encodeURIComponent` leaves dots alone and URL parsing then resolves them as\n * dot segments (found in review: `retrieve(\".\")` hit `list()`'s URL, same as `retrieve(\"\")` did).\n */\nfunction assertCustomerId(id: string, method: string): void {\n if (!id || id === \".\" || id === \"..\") {\n throw new SuqoConfigError(`customers.${method}() requires a non-empty id other than \".\" or \"..\"`);\n }\n}\n\n/**\n * `client.customers` (SDK-SPEC.md §5, §6; `openapi.yaml` `listCustomers`/`retrieveCustomer`/\n * `createCustomer`/`updateCustomer`). No delete exists on this resource.\n */\nexport class CustomersResource {\n readonly #http: HttpClient;\n\n constructor(http: HttpClient) {\n this.#http = http;\n }\n\n /** Lists the authenticated seller's customers. Paginated (SDK-SPEC.md §6). */\n async list(params?: PageParams): Promise<Page<Customer>> {\n const wire = await this.#http.request<Page<WireCustomer>>({\n method: \"GET\",\n path: CUSTOMERS_PATH,\n query: toPageQuery(params),\n });\n return deserializePage(wire, deserializeCustomer);\n }\n\n /**\n * Auto-iterates every customer across every page, following `next` until it's `null`\n * (SDK-SPEC.md §6). Manual `list({ page, pageSize })` remains available independently — this is\n * additive, not a replacement.\n */\n autoPaging(params?: PageParams): AsyncIterableIterator<Customer> {\n return bridgeAutoPaging(() => this.list(params), async (nextUrl) => {\n const wire = await this.#http.request<Page<WireCustomer>>({ method: \"GET\", path: nextUrl });\n return deserializePage(wire, deserializeCustomer);\n });\n }\n\n /**\n * Retrieves a single customer by id — an opaque prefixed string (e.g. `\"cus_1ce18d624\"`), like\n * `pbp_...` on billing periods, not an integer and not a UUID (Bug #42 corrected the previously\n * wrong `number` type/doc claim here).\n */\n async retrieve(id: string): Promise<Customer> {\n // Found in review of the string-id change (#42): an empty id isn't a path-corruption case\n // like cancel()/resume()'s \"\" (which builds a genuinely invalid, loudly-404ing double-slash\n // path) — `${CUSTOMERS_PATH}/${encodeURIComponent(\"\")}` collapses to exactly `list()`'s own\n // URL, so the request silently succeeds against the wrong endpoint. Its 200 pagination\n // envelope then feeds straight into deserializeCustomer, which reads wire.id/wire.buyer_email/\n // etc. off an object with none of them and returns a Customer of all-undefined fields with no\n // error at all — surfacing as a confusing null-pointer far from this call, not here. `id:\n // string` makes an empty id ordinary reachable input (`retrieve(req.params.id)`,\n // `retrieve(user.customerId ?? \"\")`) in a way `id: number` never could (no number stringifies\n // to \"\").\n assertCustomerId(id, \"retrieve\");\n\n // encodeURIComponent — same path-corruption risk as subscriptions.cancel()/resume(), now that\n // id is a real caller-supplied string rather than a number.\n const wire = await this.#http.request<WireCustomer>({\n method: \"GET\",\n path: `${CUSTOMERS_PATH}/${encodeURIComponent(id)}`,\n });\n return deserializeCustomer(wire);\n }\n\n /**\n * Records a customer on the seller's account without opening a subscription. `phone` identifies\n * the buyer; the name, email and address are the seller's own copy and aren't shared with other\n * sellers.\n *\n * A phone the seller already holds updates that existing customer instead of creating a second\n * one (the API answers `200` rather than `201`; both resolve to the `Customer` here). That makes\n * this call safe for the caller to retry — but, like every write, the SDK never retries it\n * automatically (SDK-SPEC.md §8, §12).\n */\n async create(params: CreateCustomerParams): Promise<Customer> {\n const wire = await this.#http.request<WireCustomer, unknown>({\n method: \"POST\",\n path: CUSTOMERS_PATH,\n body: { phone: params.phone, ...serializeCustomerFields(params) },\n });\n return deserializeCustomer(wire);\n }\n\n /**\n * Updates the seller's copy of a customer's name, email or address. Send only the fields you're\n * changing; `\"\"` clears a field. The phone can't be changed.\n *\n * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).\n */\n async update(id: string, params: UpdateCustomerParams): Promise<Customer> {\n // Same guard as retrieve(): a bad id would send the PATCH to the wrong endpoint rather than\n // failing on the intended one.\n assertCustomerId(id, \"update\");\n\n const wire = await this.#http.request<WireCustomer, unknown>({\n method: \"PATCH\",\n path: `${CUSTOMERS_PATH}/${encodeURIComponent(id)}`,\n body: serializeCustomerFields(params),\n });\n return deserializeCustomer(wire);\n }\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * `client.webhooks` (SDK-SPEC.md §5, §9). Makes **no** network calls and stores no secret — the\n * host application passes its own signing secret into every call. Verifies an inbound delivery\n * genuinely came from SUQO and hasn't been tampered with or replayed; it does **not** parse the\n * event body itself (see `models/WebhookEvent.ts` for why the event types stay snake_case).\n *\n * @packageDocumentation\n */\n\n/** Options accepted by {@link WebhooksResource.verify}. */\nexport interface VerifyWebhookOptions {\n /**\n * The **raw, unparsed** request body — exactly the bytes SUQO sent, before any JSON-parsing\n * middleware touches it. SDK-SPEC.md §9 rule 1: verifying against a parsed-then-reserialized\n * body is the single most common cause of \"signature never matches\" — whitespace, key order,\n * and number formatting can all change silently on a round-trip through `JSON.parse`/\n * `JSON.stringify`, even though the *meaning* of the body didn't change at all.\n */\n rawBody: string | Buffer;\n /** The `X-SUQO-Signature` header value, verbatim — e.g. `\"sha256=<hex>\"`. */\n signature: string;\n /** The `X-SUQO-Timestamp` header value, verbatim — Unix seconds, as a string. */\n timestamp: string;\n /** The webhook signing secret, provided by the host application. Never logged, never stored. */\n secret: string;\n /**\n * Maximum age, in seconds, before a delivery is rejected as stale (defeats replay — SDK-SPEC.md\n * §9 rule 3). Default 300 (~5 minutes).\n */\n toleranceSec?: number;\n}\n\nconst DEFAULT_TOLERANCE_SEC = 300;\nconst SIGNATURE_PREFIX = \"sha256=\";\n/**\n * A hex-encoded SHA-256 digest is always exactly 64 hex characters (32 bytes) — the `{64}` is\n * deliberate, not just `+`. `+` alone only checks *which* characters are used, not *how many*;\n * a 3-character string like `\"abc\"` would pass a `+`-based check despite `Buffer.from(\"abc\",\n * \"hex\")` still silently truncating to 1 byte, exactly the failure mode this check exists to\n * prevent (found in review: the `+` version let that through, and only \"worked\" by accident\n * because a separate, later length-equality check happened to catch the resulting mismatch —\n * this regex is now the thing that actually guarantees it, not a lucky side effect of something\n * else).\n */\nconst HEX_DIGEST_RE = /^[0-9a-f]{64}$/i;\n\nexport class WebhooksResource {\n /**\n * Verifies an inbound webhook delivery's signature. Returns `false` for any failure mode —\n * malformed signature, expired timestamp, or a genuine mismatch — never throws, so a caller\n * never needs a `try`/`catch` just to check a delivery.\n *\n * @example\n * ```ts\n * // Express: mount express.raw() on this route so req.body is a Buffer, not parsed JSON.\n * const ok = suqo.webhooks.verify({\n * rawBody: req.body,\n * signature: req.header(\"X-SUQO-Signature\")!,\n * timestamp: req.header(\"X-SUQO-Timestamp\")!,\n * secret: process.env.SUQO_WEBHOOK_SECRET!,\n * });\n * ```\n */\n verify(options: VerifyWebhookOptions): boolean {\n const { rawBody, signature, timestamp, secret, toleranceSec = DEFAULT_TOLERANCE_SEC } = options;\n\n // The types say these are always strings (or a Buffer for rawBody), but that's only a\n // compile-time promise — a caller reading a header via `req.header(...)!` (the exact pattern\n // this class's own TSDoc example recommends) gets `string | undefined` at runtime, and the\n // `!` doesn't make the value real if the header is genuinely missing. Without this guard,\n // a missing header crashed here instead of returning the documented `false` (found in\n // review, reproduced: undefined signature/timestamp/rawBody each threw a raw TypeError).\n if (typeof signature !== \"string\" || typeof timestamp !== \"string\" || typeof secret !== \"string\") {\n return false;\n }\n if (typeof rawBody !== \"string\" && !Buffer.isBuffer(rawBody)) {\n return false;\n }\n\n if (!signature.startsWith(SIGNATURE_PREFIX)) return false;\n const providedHex = signature.slice(SIGNATURE_PREFIX.length);\n // Buffer.from(str, \"hex\") silently truncates at the first invalid hex character instead of\n // throwing — checking the format explicitly first means a malformed signature is rejected\n // for being malformed, not accidentally passed through as a shorter, wrong-length buffer.\n if (!HEX_DIGEST_RE.test(providedHex)) return false;\n\n // `Number(\"\")` is 0, not NaN — an empty timestamp must not be treated as epoch 0, which would\n // always fail the freshness check anyway here, but the intent is \"reject explicitly,\" not\n // \"happen to fail for an unrelated reason.\"\n if (timestamp.trim().length === 0) return false;\n const timestampSeconds = Number(timestamp);\n if (!Number.isFinite(timestampSeconds)) return false;\n\n const nowSeconds = Date.now() / 1000;\n if (Math.abs(nowSeconds - timestampSeconds) > toleranceSec) return false;\n\n const expectedHex = createHmac(\"sha256\", secret)\n .update(`${timestamp}.`)\n .update(rawBody)\n .digest(\"hex\");\n\n const provided = Buffer.from(providedHex, \"hex\");\n const expected = Buffer.from(expectedHex, \"hex\");\n // timingSafeEqual throws on mismatched lengths rather than returning false — checked\n // explicitly first, both to avoid the throw and because the length check itself doesn't leak\n // anything meaningful (the correct length is public: always 32 bytes for SHA-256).\n if (provided.length !== expected.length) return false;\n\n return timingSafeEqual(provided, expected);\n }\n}\n","import { SdkConfig } from \"./config/index.js\";\nimport type { SuqoEnvironment } from \"./config/index.js\";\nimport { HttpClient } from \"./http/HttpClient.js\";\nimport { ProductsResource, SubscriptionsResource, CustomersResource, WebhooksResource } from \"./resources/index.js\";\n\n/** Options accepted by {@link SuqoClient}'s constructor (SDK-SPEC.md §2, §4; addendum §5). */\nexport interface SuqoClientOptions {\n /** The seller's API key. Its prefix determines sandbox vs. live — see SDK-SPEC.md §2. */\n apiKey: string;\n /**\n * Optional explicit override. If set AND it disagrees with the key's inferred environment, the\n * constructor throws `SuqoConfigError`. Normally omit this.\n */\n baseUrl?: string;\n /**\n * Per-client default request timeout in milliseconds; per-call override also allowed by\n * `http.ts` (Ticket 2). Default 30_000. Named `timeout`, not `timeoutMs` — per SDK Naming Map\n * v1.1, SDK-surface fields drop the `Ms` suffix.\n */\n timeout?: number;\n /** Max retry attempts for idempotent reads (reads only — writes are never retried, SDK-SPEC.md §8, §12). Default 2. */\n maxRetries?: number;\n /** Advanced: custom undici dispatcher for connection-pool tuning, passed through opaquely (Ticket 2). */\n dispatcher?: unknown;\n}\n\n/**\n * The SUQO SDK client (SDK-SPEC.md §5).\n *\n * ```ts\n * const suqo = new SuqoClient({ apiKey: process.env.SUQO_API_KEY! });\n * ```\n *\n * The environment (sandbox vs. live) is inferred automatically from the key's prefix — nothing\n * else to configure in the common case (SDK-SPEC.md §2). Construction throws `SuqoConfigError`\n * immediately on a malformed key, or on a `baseUrl` override that disagrees with the key.\n *\n * `.products`/`.subscriptions`/`.customers` all share this one instance's `HttpClient` — same\n * `baseUrl`/`apiKey`/`timeout`/`maxRetries` for every call, regardless of which resource makes it.\n * `.webhooks` is deliberately **not** wired to that shared `HttpClient` — it makes no network\n * call and needs no key at all (SDK-SPEC.md §9), so it's constructed independently.\n */\nexport class SuqoClient {\n readonly #config: SdkConfig;\n\n /** Browse the seller's active products (SDK-SPEC.md §5, §6). The only resource that works pre-KYC. */\n readonly products: ProductsResource;\n /** Create, list, and manage subscriptions (SDK-SPEC.md §5, §6, §7). */\n readonly subscriptions: SubscriptionsResource;\n /** List, retrieve, create and update the seller's customers (SDK-SPEC.md §5, §6). */\n readonly customers: CustomersResource;\n /** Verify inbound webhook deliveries (SDK-SPEC.md §9). Makes no network call, needs no key. */\n readonly webhooks: WebhooksResource;\n\n constructor(options: SuqoClientOptions) {\n this.#config = new SdkConfig(options);\n const http = new HttpClient(this.#config);\n this.products = new ProductsResource(http);\n this.subscriptions = new SubscriptionsResource(http);\n this.customers = new CustomersResource(http);\n this.webhooks = new WebhooksResource();\n }\n\n /** `\"sandbox\" | \"live\"` — inferred from the key prefix, never selected explicitly (SDK-SPEC.md §2). */\n get environment(): SuqoEnvironment {\n return this.#config.environment;\n }\n\n /** The resolved base URL this client sends requests to. */\n get baseUrl(): string {\n return this.#config.baseUrl;\n }\n\n /** The effective request timeout in milliseconds (default 30_000). */\n get timeout(): number {\n return this.#config.timeout;\n }\n\n /** The effective max retry count for idempotent reads (default 2). */\n get maxRetries(): number {\n return this.#config.maxRetries;\n }\n\n /** Redacts the key so it never appears in `JSON.stringify` output (SDK-SPEC.md §4). */\n toJSON(): Record<string, unknown> {\n return this.#config.toJSON();\n }\n\n /** Redacts the key so it never appears in `util.inspect`/`console.log` output (SDK-SPEC.md §4). */\n [Symbol.for(\"nodejs.util.inspect.custom\")](): Record<string, unknown> {\n return this.toJSON();\n }\n}\n","/**\n * SDK entry point — the single, complete public export surface (SDK-SPEC.md §5).\n * Nothing outside this file's exports is part of the public contract.\n *\n * @packageDocumentation\n */\n\n/** SDK version, stamped into request headers (keep in sync with package.json). */\nexport const VERSION = \"1.1.0\";\n\nexport {\n SuqoError,\n SuqoConfigError,\n AuthenticationError,\n KycRequiredError,\n ValidationError,\n NotFoundError,\n RateLimitError,\n ServerError,\n NetworkError,\n mapHttpError,\n type SuqoErrorOptions,\n type KycRequiredErrorOptions,\n type ValidationErrorOptions,\n type FieldErrors,\n type RateLimitErrorOptions,\n type HttpErrorInput,\n} from \"./errors/index.js\";\n\nexport { SuqoClient, type SuqoClientOptions } from \"./client.js\";\nexport type { SuqoEnvironment } from \"./config/index.js\";\n\nexport {\n bridgeAutoPaging,\n deserializePage,\n listAll,\n toPageQuery,\n type Page,\n type PageParams,\n type SubscriptionPage,\n type SubscriptionStatusCounts,\n} from \"./pagination.js\";\n\nexport {\n SubscriptionStatus,\n type Product,\n type ProductVat,\n type ProductImage,\n type Plan,\n type BillingPeriod,\n type Subscription,\n type SubscriptionProduct,\n type SubscriptionCustomer,\n type SubscriptionCustomerBilling,\n type SubscriptionCustomerShipping,\n type CustomerInput,\n type CustomerInputBilling,\n type CustomerInputShipping,\n type Customer,\n type CreateCustomerParams,\n type UpdateCustomerParams,\n type CreateSubscriptionParams,\n type CreateSubscriptionResponse,\n type UpdateBillingCycleParams,\n type MessageResponse,\n type CheckoutSucceededEvent,\n type CheckoutFailedEvent,\n type SubscriptionStatusChangedEvent,\n type ApiKeyCreatedEvent,\n type ApiKeyDeletedEvent,\n type ApiKeyExpiredEvent,\n type ApiKeyExpiringSoonEvent,\n type WebhookEvent,\n type WebhookEventType,\n} from \"./models/index.js\";\n\nexport type { VerifyWebhookOptions } from \"./resources/webhooks.js\";\n\n// ProductsResource/SubscriptionsResource/CustomersResource/WebhooksResource are intentionally NOT\n// exported here — consumers reach them through suqo.products/.subscriptions/.customers/.webhooks,\n// never by constructing one directly (SDK-SPEC.md §5's public surface never shows a resource\n// class being constructed).\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors/SuqoError.ts","../src/utils/isRecord.ts","../src/utils/assertPathId.ts","../src/errors/mapHttpError.ts","../src/config/environments.ts","../src/config/SdkConfig.ts","../src/http/urlBuilder.ts","../src/http/retry.ts","../src/http/signals.ts","../src/http/HttpClient.ts","../src/pagination.ts","../src/resources/products.ts","../src/models/Subscription.ts","../src/resources/serialization.ts","../src/resources/subscriptions.ts","../src/resources/customers.ts","../src/resources/checkoutSessions.ts","../src/resources/webhooks.ts","../src/client.ts","../src/index.ts"],"names":[],"mappings":";;;AAyCO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAQnC,WAAA,CAAY,OAAA,EAAiB,OAAA,GAA4B,EAAC,EAAG;AAC3D,IAAA,KAAA,CAAM,OAAA,EAAS,QAAQ,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI,MAAS,CAAA;AACjF,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AAIvB,IAAA,IAAA,CAAK,UAAU,OAAA,CAAQ,OAAA;AACvB,IAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,MAAA,EAAW,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACxD,IAAA,IAAI,OAAA,CAAQ,SAAA,KAAc,MAAA,EAAW,IAAA,CAAK,YAAY,OAAA,CAAQ,SAAA;AAE9D,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF;AAWO,IAAM,eAAA,GAAN,cAA8B,SAAA,CAAU;AAAA,EAC7C,WAAA,CAAY,OAAA,EAAiB,OAAA,GAA+B,EAAC,EAAG;AAC9D,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AAAA,EACxB;AACF;AAGO,IAAM,mBAAA,GAAN,cAAkC,SAAA,CAAU;AAAC;AAc7C,IAAM,gBAAA,GAAN,cAA+B,SAAA,CAAU;AAAA,EAI9C,WAAA,CAAY,OAAA,EAAiB,OAAA,GAAmC,EAAC,EAAG;AAClE,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAI,OAA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IAAI,OAAA,GAAkB;AACpB,IAAA,OAAO,KAAK,OAAA,CAAQ,OAAA;AAAA,EACtB;AAAA;AAAA,EAGA,IAAI,UAAA,GAAqB;AACvB,IAAA,OAAO,KAAK,OAAA,CAAQ,UAAA;AAAA,EACtB;AAAA;AAAA,EAGA,MAAA,GAAkC;AAChC,IAAA,OAAO,IAAA,CAAK,QAAQ,MAAA,EAAO;AAAA,EAC7B;AAAA;AAAA,EAGA,iBAAC,MAAA,CAAO,GAAA,CAAI,4BAA4B,CAAC,CAAA,GAA6B;AACpE,IAAA,OAAO,KAAK,MAAA,EAAO;AAAA,EACrB;AACF;;;AC/FO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * The full `SuqoError` hierarchy (SDK-SPEC.md §7).\n *\n * Every error thrown by this SDK is an instance of `SuqoError` — but the base class itself is\n * never thrown directly; the SDK always throws one of the subclasses below.\n *\n * @packageDocumentation\n */\n\n/** Options accepted by every {@link SuqoError} subclass constructor. */\nexport interface SuqoErrorOptions {\n /** HTTP status code this error was mapped from, if any (absent for `SuqoConfigError`/`NetworkError` — there was no response). */\n status?: number;\n /** The response body this error was mapped from, if any: parsed JSON, or the raw text when it wasn't JSON. */\n rawBody?: unknown;\n /**\n * The backend's request id for this call, if the response included one — ties a failure to a\n * specific server-side log line. Nice-to-have: SUQO backend confirmation on whether/how this is\n * exposed is still pending (docs/implementation-plan.md Ticket 0 item 3) — always optional,\n * never assumed present.\n */\n requestId?: string;\n /** The underlying cause (e.g. the original `fetch` rejection), for debugging — never surfaced to end users directly. */\n cause?: unknown;\n}\n\n/**\n * Base class for every error thrown by the SDK (SDK-SPEC.md §7). Never thrown directly — always\n * one of the subclasses below.\n *\n * @example\n * ```ts\n * try {\n * await suqo.subscriptions.create({ ... });\n * } catch (err) {\n * if (err instanceof SuqoError) {\n * console.error(err.name, err.message, err.status);\n * }\n * }\n * ```\n */\nexport class SuqoError extends Error {\n /** HTTP status code this error was mapped from, if any. */\n readonly status?: number;\n /** The response body this error was mapped from, if any: parsed JSON, or the raw text when it wasn't JSON. */\n readonly rawBody?: unknown;\n /** The backend's request id for this call, if one was returned. See {@link SuqoErrorOptions.requestId}. */\n readonly requestId?: string;\n\n constructor(message: string, options: SuqoErrorOptions = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = new.target.name;\n // rawBody's declared type is already `unknown`, so assigning it unconditionally is always\n // valid under exactOptionalPropertyTypes; status/requestId are narrower (string/number) so\n // they're only assigned when actually provided, never as an explicit `undefined`.\n this.rawBody = options.rawBody;\n if (options.status !== undefined) this.status = options.status;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n // Restore the prototype chain so `instanceof` works after transpilation.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Construction-time configuration problems: a malformed API key, or an explicit `baseUrl`\n * override that disagrees with the key's prefix (SDK-SPEC.md §2, §7). Also reused for a call-time\n * argument that would otherwise silently corrupt a request rather than reach the API at all — e.g.\n * an empty `customers.retrieve(id)` (#42) — the same \"never even attempted\" character as a bad\n * construction option. Thrown before any request is made — analogous to a syntax error in the\n * integration, not an HTTP failure. Never carries `status`/`rawBody`; there was no request to map\n * one from.\n */\nexport class SuqoConfigError extends SuqoError {\n constructor(message: string, options: { cause?: unknown } = {}) {\n super(message, options);\n }\n}\n\n/** 401 — the API key is missing, malformed, or inactive (SDK-SPEC.md §7). */\nexport class AuthenticationError extends SuqoError {}\n\n/** Options accepted by {@link KycRequiredError}. */\nexport interface KycRequiredErrorOptions extends SuqoErrorOptions {\n /**\n * The KYC status code from the response body's `status_code` field (openapi.yaml `KycError`).\n * Named `kycStatus`, not `statusCode` — per SDK Naming Map v1.1's rename register, `status_code`\n * \"reads as an HTTP status but carries a KYC status,\" and sits right next to the base class's\n * real HTTP `status` field, so the two must stay visibly distinct.\n */\n kycStatus?: string;\n}\n\n/** 403 — the owning seller has not completed KYC verification (SDK-SPEC.md §7). */\nexport class KycRequiredError extends SuqoError {\n /** The KYC status code from the response body, if present. See {@link KycRequiredErrorOptions.kycStatus}. */\n readonly kycStatus?: string;\n\n constructor(message: string, options: KycRequiredErrorOptions = {}) {\n super(message, options);\n if (options.kycStatus !== undefined) this.kycStatus = options.kycStatus;\n }\n}\n\n/** Field-keyed validation messages, normalized to string arrays regardless of wire shape. */\nexport type FieldErrors = Record<string, string[]>;\n\n/** Options accepted by {@link ValidationError}. */\nexport interface ValidationErrorOptions extends SuqoErrorOptions {\n /** Field-keyed validation messages. Empty if the 400 used the `detail` shape instead. */\n fieldErrors?: FieldErrors;\n}\n\n/**\n * 403 — the key is valid but may not perform this action, for a reason other than KYC (SDK-SPEC.md\n * §7). The API answers with `{ \"detail\": \"…\" }` alone, e.g. a key that doesn't belong to the\n * account. A KYC-shaped 403 (with `status_code`) is {@link KycRequiredError} instead.\n *\n * Also thrown for a 403 that isn't JSON at all — usually a firewall in front of the API (e.g.\n * Cloudflare's `error code: 1010`, which blocks some HTTP clients by `User-Agent`). Its message is\n * just `Request failed with status 403`; read {@link SuqoError.rawBody} (the page's text) for the\n * real cause.\n *\n * Named `PermissionDeniedError`, not `PermissionError`: the stem must be identical in every port\n * (SDK Naming Map R2, R6), and `PermissionError` is a Python builtin.\n */\nexport class PermissionDeniedError extends SuqoError {}\n\n/**\n * 400 — request validation failed (SDK-SPEC.md §7). The API uses two different 400 body shapes;\n * {@link mapHttpError} normalizes both into this one class so consumers rely on `instanceof`,\n * never the wire shape:\n * - A field-keyed body (`{ field: [\"msg\"] }`) populates {@link fieldErrors}.\n * - A `detail`-shaped body (`{ detail: \"msg\" }`, e.g. the duplicate-active-subscription case)\n * populates `message` instead, with `fieldErrors` left empty.\n */\nexport class ValidationError extends SuqoError {\n /** Field-keyed validation messages. Empty (not undefined) when the 400 used the `detail` shape. */\n readonly fieldErrors: FieldErrors;\n\n constructor(message: string, options: ValidationErrorOptions = {}) {\n super(message, options);\n this.fieldErrors = options.fieldErrors ?? {};\n }\n}\n\n/** 404 — the resource doesn't exist, or doesn't belong to the authenticated seller (SDK-SPEC.md §7). */\nexport class NotFoundError extends SuqoError {}\n\n/** Options accepted by {@link RateLimitError}. */\nexport interface RateLimitErrorOptions extends SuqoErrorOptions {\n /**\n * Suggested backoff derived from a `Retry-After` header, in milliseconds, if present. Named\n * `retryAfter`, not `retryAfterMs` — per SDK Naming Map v1.1, SDK-surface fields drop the `Ms`\n * suffix; the unit is documented, not encoded in the name.\n */\n retryAfter?: number;\n}\n\n/**\n * 429 — rate limited (SDK-SPEC.md §7, §10). Live on `checkoutSessions.create()`, the API's one\n * rate-limited endpoint (20 sessions a minute per account). That call is a write, so the SDK never\n * retries it on its own — read {@link RateLimitError.retryAfter} and retry yourself.\n */\nexport class RateLimitError extends SuqoError {\n /**\n * Suggested backoff in milliseconds, if the API named one: the `Retry-After` header when present,\n * otherwise the wait the API writes into `detail` (\"…available in 41 seconds\"). Capped at 60 s.\n */\n readonly retryAfter?: number;\n\n constructor(message: string, options: RateLimitErrorOptions = {}) {\n super(message, options);\n if (options.retryAfter !== undefined) this.retryAfter = options.retryAfter;\n }\n}\n\n/** 5xx — the SUQO API failed unexpectedly (SDK-SPEC.md §7). */\nexport class ServerError extends SuqoError {}\n\n/**\n * Transport failure or timeout — the request never got a response at all (SDK-SPEC.md §7). Covers\n * timeouts too; there is no separate timeout class. Thrown directly by `http.ts` (Ticket 2) when\n * `fetch` rejects or an `AbortSignal` fires — never produced by {@link mapHttpError}, since\n * there's no HTTP status to map in that case.\n */\nexport class NetworkError extends SuqoError {}\n","/**\n * True when `value` is a plain object worth reading properties off of — `typeof null` is\n * `\"object\"` in JavaScript, so that's excluded explicitly. Shared by every layer that has to look\n * at an untyped, server-supplied value before trusting its shape (`mapHttpError`'s response\n * bodies, the resource serialization boundary's request/response bodies) — previously duplicated\n * privately in more than one of them.\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n","import { SuqoConfigError } from \"../errors/SuqoError.js\";\n\n/**\n * Rejects an id that would send a request to a different endpoint than the one intended, before\n * any request is made. `\"\"` collapses onto the collection URL (`encodeURIComponent(\"\")` is `\"\"`),\n * so `retrieve(\"\")` would silently hit `list()`; `\".\"` and `\"..\"` do the same or climb above it,\n * because `encodeURIComponent` leaves dots alone and URL parsing resolves them as dot segments.\n *\n * `method` names the caller in the error, e.g. `\"customers.retrieve\"`. `reserved` lists sibling\n * route segments an id must not equal — `webhooks.retrieve(\"secret\")` would otherwise land on\n * `GET /webhooks/secret/`, minting and returning the signing secret instead of a webhook.\n */\nexport function assertPathId(id: string, method: string, reserved: readonly string[] = []): void {\n if (!id || id === \".\" || id === \"..\") {\n throw new SuqoConfigError(`${method}() requires a non-empty id other than \".\" or \"..\"`);\n }\n if (reserved.includes(id)) {\n throw new SuqoConfigError(`${method}() was given \"${id}\", which is a route name, not an id`);\n }\n}\n","import {\n AuthenticationError,\n KycRequiredError,\n NotFoundError,\n PermissionDeniedError,\n RateLimitError,\n ServerError,\n SuqoError,\n ValidationError,\n type FieldErrors,\n} from \"./SuqoError.js\";\nimport { isRecord } from \"../utils/index.js\";\n\n/**\n * The shape {@link mapHttpError} needs from a completed HTTP response. Deliberately not a\n * `Response` itself — `http.ts` (Ticket 2) reads the status, parses the body, and extracts\n * headers itself, keeping this module free of any transport-layer dependency.\n */\nexport interface HttpErrorInput {\n /** The response's HTTP status code. */\n status: number;\n /** The response's HTTP status text, if available — used only for the generic fallback message. */\n statusText?: string;\n /**\n * The response body: parsed JSON when it parsed, otherwise the raw text. Expected to be one\n * of `openapi.yaml`'s three error shapes (`FieldError`, `DetailError`, `KycError`) — the shape\n * is detected here, never assumed from the status code alone. A non-JSON body (a proxy/WAF\n * page) gets the generic status message, never a SUQO-specific one.\n */\n body?: unknown;\n /** The backend's request id for this call, if one was returned (nice-to-have — Ticket 0 item 3). */\n requestId?: string;\n /**\n * Suggested backoff derived from a `Retry-After` header, in milliseconds. Parsed for any status\n * (found in review: HttpClient's retry loop needs it on retryable 5xxs too, not just 429), but\n * only ever surfaced on the thrown error itself for `RateLimitError` (429) below.\n */\n retryAfter?: number;\n}\n\n/**\n * True when `body` is a bare list of messages (`[\"msg\", …]`) — what the API sends for a 400 on an\n * endpoint with no request body to key a field on (cancel, resume, renew), and for the\n * duplicate-subscription error on create.\n */\nfunction isMessageList(body: unknown): body is string[] {\n return Array.isArray(body) && body.length > 0 && body.every((item) => typeof item === \"string\");\n}\n\n/** True when `body` is the `DetailError` shape (`{ detail: \"msg\" }`) rather than field-keyed. */\nfunction isDetailShaped(body: unknown): body is { detail: string } {\n return isRecord(body) && typeof body.detail === \"string\" && body.detail.length > 0;\n}\n\n/**\n * Normalizes a `FieldError` body into `Record<string, string[]>`, flattening nested objects into\n * dot-path keys (`customer.phone`) and renaming the wire's root `client` key to `customer` on the\n * way — SDK Naming Map v1.1 Open Question A, resolved (2026-08-24, confirmed live against\n * `POST /subscriptions/`): a validation failure on the customer payload nests errors under\n * `client` as a real object (`{\"client\": {\"phone\": [\"This field is required.\"]}}`), not a flat\n * dotted key — so this needs path-aware rewriting, not a flat key swap, exactly as the map warned.\n *\n * Only the **root-level** `client` key is renamed (`pathPrefix === \"\"` below) — a field genuinely\n * named `client` nested somewhere else wouldn't be, though no such field exists in the documented\n * API surface today. A value that's neither a string, a string array, nor a nested object worth\n * recursing into is skipped rather than guessed at — this never fabricates a message it wasn't\n * given.\n *\n * The nested-object check explicitly excludes arrays (`!Array.isArray(value)`), even though\n * `isRecord` alone would let one through — `typeof anArray === \"object\"` in JavaScript. Without\n * that exclusion, a field value shaped as a list of objects (e.g.\n * `{\"billing\": [{\"business_name\": [\"required\"]}]}`) would get recursed into using the array's\n * numeric indices as path segments (`billing.0.business_name`) instead of being skipped, silently\n * contradicting the rule stated above (found in review, reproduced).\n */\nfunction fieldErrorsFrom(body: unknown, pathPrefix = \"\"): FieldErrors {\n if (!isRecord(body)) return {};\n const fieldErrors: FieldErrors = {};\n for (const [rawKey, value] of Object.entries(body)) {\n const key = pathPrefix === \"\" && rawKey === \"client\" ? \"customer\" : rawKey;\n const path = pathPrefix === \"\" ? key : `${pathPrefix}.${key}`;\n\n if (typeof value === \"string\") {\n fieldErrors[path] = [value];\n } else if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) {\n fieldErrors[path] = value;\n } else if (isRecord(value) && !Array.isArray(value)) {\n Object.assign(fieldErrors, fieldErrorsFrom(value, path));\n }\n }\n return fieldErrors;\n}\n\n/** Best-effort extraction of a human-readable message from a `DetailError`/`KycError` body. */\nfunction messageFrom(body: unknown, fallback: string): string {\n if (isRecord(body)) {\n if (typeof body.detail === \"string\" && body.detail.length > 0) return body.detail;\n if (typeof body.message === \"string\" && body.message.length > 0) return body.message;\n }\n return fallback;\n}\n\n/**\n * The single, centralized status-code-to-error-class mapper (SDK-SPEC.md §7). Every HTTP response\n * with a non-2xx status is mapped to the correct {@link SuqoError} subclass through this\n * function — no other place in the SDK is allowed to make that decision.\n *\n * Handles both documented 400 body shapes: a field-keyed body populates\n * `ValidationError.fieldErrors`; a `detail`-shaped body (e.g. the duplicate-active-subscription\n * case) populates `ValidationError.message` instead, with `fieldErrors` left empty. A field-keyed\n * body's `client` key (the wire name for the subscription customer payload) is renamed to\n * `customer` and flattened into dot-path keys (`customer.phone`) — SDK Naming Map v1.1 Open\n * Question A, resolved: yes, translate.\n *\n * Does not handle `fetch` throwing or an `AbortSignal` firing — those have no HTTP status and are\n * constructed directly as `NetworkError` by `http.ts` (Ticket 2).\n *\n * @example\n * ```ts\n * const response = await fetch(url);\n * if (!response.ok) {\n * const text = await response.text();\n * let body: unknown = text || undefined;\n * try {\n * body = JSON.parse(text); // a SUQO error body; a proxy/WAF page stays text\n * } catch {}\n * throw mapHttpError({ status: response.status, body });\n * }\n * ```\n */\nexport function mapHttpError(input: HttpErrorInput): SuqoError {\n const { status, statusText, body, requestId, retryAfter } = input;\n const fallbackMessage = `Request failed with status ${status}${statusText ? ` (${statusText})` : \"\"}`;\n // rawBody's declared type is `unknown`, so including it unconditionally is always valid under\n // exactOptionalPropertyTypes; requestId is narrower (string), so it's only spread in when\n // actually provided, never as an explicit `key: undefined`.\n const base = { status, rawBody: body, ...(requestId !== undefined ? { requestId } : {}) };\n // The friendly per-status fallbacks below describe SUQO's own refusals; a text body (e.g.\n // Cloudflare's HTML \"error code: 1010\") came from something in front of the API, so it gets the\n // neutral status message and the caller reads the cause in `rawBody`. An empty body keeps the\n // friendly fallback.\n const fallback = (suqoMessage: string): string => (typeof body === \"string\" ? fallbackMessage : suqoMessage);\n\n switch (status) {\n case 401:\n return new AuthenticationError(messageFrom(body, fallbackMessage), base);\n case 403: {\n // Two 403 shapes, told apart by the body, never the status alone: KYC carries\n // `status_code` + `message` and no `detail`; any other refusal carries `detail` alone.\n if (isRecord(body) && typeof body.status_code === \"string\") {\n const message = messageFrom(body, \"KYC verification needed to perform this action.\");\n return new KycRequiredError(message, { ...base, kycStatus: body.status_code });\n }\n return new PermissionDeniedError(messageFrom(body, fallback(\"You do not have permission to perform this action.\")), base);\n }\n case 400: {\n if (isDetailShaped(body)) {\n return new ValidationError(body.detail, base);\n }\n // A bare list carries no field to key on: surface its messages as the error message,\n // with an empty `fieldErrors` — same as a `detail`-shaped 400 (Naming Map §7).\n if (isMessageList(body)) {\n return new ValidationError(body.join(\" \"), { ...base, fieldErrors: {} });\n }\n return new ValidationError(fallback(\"Validation failed.\"), { ...base, fieldErrors: fieldErrorsFrom(body) });\n }\n case 404:\n return new NotFoundError(messageFrom(body, fallback(\"Not found.\")), base);\n case 429:\n return new RateLimitError(messageFrom(body, fallbackMessage), {\n ...base,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n });\n default:\n // 5xx and any genuinely unmapped status both land here. SDK-SPEC.md §7 doesn't define a\n // class for out-of-contract codes, and the base SuqoError is never thrown directly — and\n // openapi.yaml's documented surface never returns anything outside\n // {400, 401, 403, 404, 429, 5xx} today, so this default is a safety net, not an expected path.\n return new ServerError(messageFrom(body, fallbackMessage), base);\n }\n}\n","/**\n * Key-prefix → environment/base-URL inference (SDK-SPEC.md §2).\n *\n * @packageDocumentation\n */\nimport { SuqoConfigError } from \"../errors/SuqoError.js\";\n\n/** The two environments a key prefix resolves to. Never selected explicitly — always inferred. */\nexport type SuqoEnvironment = \"sandbox\" | \"live\";\n\nconst SANDBOX_BASE_URL = \"https://test-be.suqo.ai\";\nconst LIVE_BASE_URL = \"https://be.suqo.ai\";\n\n/**\n * Ordered prefix → environment table. `su_test_key_` MUST be checked before `su_key_`\n * (SDK-SPEC.md §2 rule 4) — the spec calls this out explicitly as an ordering requirement for any\n * prefix matcher, so the order here is deliberate, not incidental.\n */\nconst KEY_PREFIXES: ReadonlyArray<{ prefix: string; environment: SuqoEnvironment; baseUrl: string }> = [\n { prefix: \"su_test_key_\", environment: \"sandbox\", baseUrl: SANDBOX_BASE_URL },\n { prefix: \"su_key_\", environment: \"live\", baseUrl: LIVE_BASE_URL },\n];\n\n/** Result of inferring an environment + base URL from an API key. */\nexport interface ResolvedEnvironment {\n environment: SuqoEnvironment;\n baseUrl: string;\n}\n\n/**\n * Infers the environment and base URL from an API key's prefix — the whole configuration in the\n * common case, no environment flag needed (SDK-SPEC.md §2).\n *\n * @param apiKey - The full API key. Matched with `startsWith`, treating the prefix as \"starts\n * with\", never a substring search anywhere in the key.\n * @param override - An explicit `baseUrl`, if the caller supplied one. Must agree with the\n * inferred base URL or this throws — silence-and-trust-one is forbidden (SDK-SPEC.md §2 rule 3).\n *\n * @throws {SuqoConfigError} if `apiKey` matches neither prefix (rule 2), or if `override` is\n * supplied and disagrees with the inferred base URL (rule 3). Thrown before any request is made.\n */\nexport function resolveEnvironment(apiKey: string, override?: string): ResolvedEnvironment {\n if (typeof apiKey !== \"string\" || apiKey.length === 0) {\n throw new SuqoConfigError(\"A SUQO API key is required.\");\n }\n\n const match = KEY_PREFIXES.find(({ prefix }) => apiKey.startsWith(prefix));\n if (!match) {\n throw new SuqoConfigError(\n 'Malformed SUQO API key: expected prefix \"su_key_\" (live) or \"su_test_key_\" (sandbox).',\n );\n }\n\n if (override !== undefined && override !== match.baseUrl) {\n throw new SuqoConfigError(\n `Environment mismatch: key implies ${match.baseUrl} but baseUrl was set to ${override}. ` +\n \"Remove baseUrl or use a matching key.\",\n );\n }\n\n return { environment: match.environment, baseUrl: override ?? match.baseUrl };\n}\n","import { resolveEnvironment, type SuqoEnvironment } from \"./environments.js\";\n\n/** Input accepted by {@link SdkConfig} — the same shape `SuqoClient`'s constructor takes (addendum §5). */\nexport interface SdkConfigInput {\n /** The seller's API key. Its prefix determines the environment (SDK-SPEC.md §2) — never passed separately. */\n apiKey: string;\n /**\n * Optional explicit override. If set AND it disagrees with the key prefix, the constructor\n * throws `SuqoConfigError`. Normally omit this.\n */\n baseUrl?: string;\n /**\n * Per-client default request timeout in milliseconds; per-call override also allowed by\n * `http.ts` (Ticket 2). Default 30_000. Named `timeout`, not `timeoutMs` — per SDK Naming Map\n * v1.1, SDK-surface fields drop the `Ms` suffix; the unit is documented, not encoded in the name.\n */\n timeout?: number;\n /** Read-retry tuning (reads only — writes are never retried, SDK-SPEC.md §8, §12). Default 2. */\n maxRetries?: number;\n /** Advanced: custom undici dispatcher for pool tuning, passed through opaquely to `fetch` (Ticket 2). */\n dispatcher?: unknown;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_RETRIES = 2;\n\n/** The `util.inspect` custom-inspection symbol, referenced by key so this file never needs to `import \"node:util\"`. */\nconst NODE_INSPECT_CUSTOM = Symbol.for(\"nodejs.util.inspect.custom\");\n\n/**\n * Resolved, immutable SDK configuration (SDK-SPEC.md §2, §4).\n *\n * Validated at construction time — a malformed key or a conflicting `baseUrl` override throws\n * `SuqoConfigError` immediately, before any request is ever made. The API key is stored in a\n * private class field, never a public/enumerable property, so it can never leak through\n * `JSON.stringify`, `console.log`, or `util.inspect` (SDK-SPEC.md §4) — `toJSON` and the\n * `util.inspect` custom-inspection symbol both redact it explicitly as well, so redaction holds\n * even if a future refactor adds an enumerable field.\n *\n * @example\n * ```ts\n * const config = new SdkConfig({ apiKey: \"su_test_key_...\" });\n * config.baseUrl; // => \"https://test-be.suqo.ai\"\n * config.environment; // => \"sandbox\"\n * ```\n */\nexport class SdkConfig {\n /** `\"sandbox\" | \"live\"` — inferred from the key prefix, never selected explicitly. */\n readonly environment: SuqoEnvironment;\n /** The resolved base URL for this environment (or the caller's override, if it agreed). */\n readonly baseUrl: string;\n /** Request timeout in milliseconds, per-client default (`http.ts` in Ticket 2 allows a per-call override). */\n readonly timeout: number;\n /** Max retry attempts for idempotent reads. Writes are never retried regardless of this value. */\n readonly maxRetries: number;\n /** Opaque custom dispatcher for pool tuning, if supplied. Passed through to `fetch` unexamined. */\n readonly dispatcher: unknown;\n\n readonly #apiKey: string;\n\n constructor(input: SdkConfigInput) {\n const { environment, baseUrl } = resolveEnvironment(input.apiKey, input.baseUrl);\n this.environment = environment;\n this.baseUrl = baseUrl;\n this.timeout = input.timeout ?? DEFAULT_TIMEOUT_MS;\n this.maxRetries = input.maxRetries ?? DEFAULT_MAX_RETRIES;\n this.dispatcher = input.dispatcher;\n this.#apiKey = input.apiKey;\n }\n\n /** The raw API key, for building the `Authorization: Bearer <key>` header (`http.ts`, Ticket 2). Never logged. */\n get apiKey(): string {\n return this.#apiKey;\n }\n\n /** Redacts the key so it never appears in `JSON.stringify` output (SDK-SPEC.md §4). */\n toJSON(): Record<string, unknown> {\n return {\n environment: this.environment,\n baseUrl: this.baseUrl,\n timeout: this.timeout,\n maxRetries: this.maxRetries,\n apiKey: \"[redacted]\",\n };\n }\n\n /** Redacts the key so it never appears in `util.inspect`/`console.log` output (SDK-SPEC.md §4). */\n [NODE_INSPECT_CUSTOM](): Record<string, unknown> {\n return this.toJSON();\n }\n}\n","/**\n * URL construction with the trailing slash structurally guaranteed (SDK-SPEC.md §3).\n *\n * @packageDocumentation\n */\n\n/** Query parameter values accepted by {@link buildUrl}. `undefined` values are omitted entirely. */\nexport type QueryParams = Record<string, string | number | boolean | undefined>;\n\n/**\n * Builds a request URL from a base URL and a path, guaranteeing the path ends in `/` — never left\n * to the caller to remember (SDK-SPEC.md §3). Query params are appended *after* the slash, e.g.\n * `/api/v1/subscriptions/?page=2&page_size=50`.\n *\n * `path` may also be an already-complete absolute URL with its own query string already attached\n * (e.g. a pagination envelope's `next` field, Ticket 3) — `baseUrl` is then ignored per the\n * `URL(path, base)` constructor's own semantics, and the existing query string is preserved\n * untouched. This only works correctly because the trailing-slash check below runs against the\n * *parsed pathname*, not the raw input string — checking the raw string (found in review: the\n * original implementation did exactly this) would append `/` after an existing query string and\n * corrupt whichever query param happened to be last (e.g. `page_size=50` silently becoming\n * `page_size=50/`).\n *\n * @param baseUrl - The resolved environment base URL (`SdkConfig.baseUrl`), no trailing slash.\n * @param path - The route path, e.g. `/api/v1/products`, OR an already-complete absolute URL to\n * use as-is (e.g. a `next` link). A missing trailing slash on the *path portion* is added here,\n * not assumed to already be correct — this is the SDK's last line of defense for SDK-SPEC.md §3,\n * not a courtesy extended to a caller who might get it wrong.\n * @param query - Optional query params, merged in on top of any the URL already carries.\n * `undefined` values are skipped, so callers can pass `{ page, pageSize }` straight through\n * without filtering first.\n */\nexport function buildUrl(baseUrl: string, path: string, query?: QueryParams): string {\n const url = new URL(path, baseUrl);\n\n if (!url.pathname.endsWith(\"/\")) {\n url.pathname = `${url.pathname}/`;\n }\n\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) url.searchParams.set(key, String(value));\n }\n }\n\n return url.toString();\n}\n","import { isRecord } from \"../utils/index.js\";\n\n/**\n * Retry policy: which failures are retryable, bounded attempts, exponential backoff with full\n * jitter (SDK-SPEC.md §8).\n *\n * @packageDocumentation\n */\n\n/**\n * HTTP methods eligible for retry at all.\n *\n * **SINGLE SWITCH** (SDK-SPEC.md §8, §12): every read in this API is `GET` and every write is\n * `POST`, `PATCH`, `PUT` or `DELETE` — reads are naturally idempotent, writes are not, and the\n * backend doesn't support idempotency keys yet, so a retried write could double-act. Flip this the\n * moment idempotency keys ship and writes carry one; until then, only `GET` retries.\n */\nconst RETRYABLE_METHODS: ReadonlySet<string> = new Set([\"GET\"]);\n\n/** True if `method` is allowed to retry at all — independent of whether a given failure qualifies. */\nexport function isRetryableMethod(method: string): boolean {\n return RETRYABLE_METHODS.has(method);\n}\n\n/** The failure shape {@link isRetryableFailure} decides on. */\nexport interface RetryableFailureInput {\n /** True if the request never got a response at all (fetch threw / timed out). */\n networkError: boolean;\n /** The HTTP status code, if a response was received. */\n status?: number;\n}\n\n/** True if a failure of this shape should be retried (SDK-SPEC.md §8): network failure, 429, or 5xx. */\nexport function isRetryableFailure(input: RetryableFailureInput): boolean {\n if (input.networkError) return true;\n if (input.status === undefined) return false;\n return input.status === 429 || (input.status >= 500 && input.status <= 599);\n}\n\nconst BASE_DELAY_MS = 500;\nconst MAX_DELAY_MS = 8_000;\n\n/**\n * \"Full jitter\" backoff (SDK-SPEC.md §8: exponential backoff + jitter, bounded attempts): a\n * random delay between 0 and an exponentially growing cap, itself bounded by `MAX_DELAY_MS` so a\n * late retry never waits unboundedly long.\n *\n * @param attempt - 0-indexed retry attempt number (0 = the first retry, after the initial try).\n */\nexport function backoffDelayMs(attempt: number): number {\n const cap = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);\n return Math.random() * cap;\n}\n\n/**\n * Generous cap on a server-supplied `Retry-After`, distinct from `MAX_DELAY_MS` (computed\n * backoff's own cap). `Retry-After` is explicit server guidance, worth respecting well past a\n * guessed backoff's ceiling — but an unbounded value (misconfigured server, or a malicious one)\n * must not stall a request indefinitely (found in review: a `Retry-After: 86400` would otherwise\n * wait a full day with nothing bounding it).\n */\nconst MAX_RETRY_AFTER_MS = 60_000;\n\n/**\n * Parses a `Retry-After` header value into milliseconds, clamped to `MAX_RETRY_AFTER_MS`. Accepts\n * both forms RFC 7231 §7.1.3 allows: the seconds-delta form (e.g. `\"5\"`) and the HTTP-date form\n * (e.g. `\"Wed, 21 Oct 2026 07:28:00 GMT\"`) — accepting only the former is a common bug (SDK Naming\n * Map v1.1), since real servers (and load balancers in front of them) send either. Returns\n * `undefined` if neither form parses, so the caller falls back to computed backoff instead of\n * guessing (SDK-SPEC.md §8: \"Respect Retry-After when present\").\n *\n * @param now - The current time in epoch ms, used to convert an HTTP-date into a delta.\n * Overridable for tests; defaults to `Date.now()`.\n */\nexport function parseRetryAfterMs(headerValue: string | null, now: number = Date.now()): number | undefined {\n if (headerValue === null) return undefined;\n // `Number(\"\")` (and whitespace-only strings) is `0` in JavaScript, not `NaN` — checked\n // explicitly so an empty-but-present header is treated as unparseable, not \"retry after 0ms\"\n // (found in review: this would otherwise hammer a server that just asked to slow down).\n const trimmed = headerValue.trim();\n if (trimmed.length === 0) return undefined;\n\n const seconds = Number(trimmed);\n if (Number.isFinite(seconds)) {\n if (seconds < 0) return undefined;\n return Math.min(seconds * 1000, MAX_RETRY_AFTER_MS);\n }\n\n // Not the delta-seconds form — try the HTTP-date form. `Date.parse` returns `NaN` for anything\n // it can't parse, which also correctly rejects plain garbage strings rather than guessing.\n const dateMs = Date.parse(trimmed);\n if (Number.isNaN(dateMs)) return undefined;\n // A date already in the past means \"retry now,\" not \"unparseable\" or a negative wait.\n const delta = Math.max(dateMs - now, 0);\n return Math.min(delta, MAX_RETRY_AFTER_MS);\n}\n\n/**\n * The wait the API writes into a 429's `detail` — `\"Request was throttled. Expected available in\n * 41 seconds.\"` — in milliseconds, capped like the header. The API sends no `Retry-After` header on\n * its rate limit today, so this is the fallback {@link HttpClient} uses when the header is absent.\n * Returns `undefined` for anything it doesn't recognise rather than guessing.\n */\nexport function parseRetryAfterDetailMs(body: unknown): number | undefined {\n if (!isRecord(body) || typeof body.detail !== \"string\") return undefined;\n const match = /available in (\\d+(?:\\.\\d+)?) seconds?/i.exec(body.detail);\n if (!match) return undefined;\n return Math.min(Number(match[1]) * 1000, MAX_RETRY_AFTER_MS);\n}\n","/**\n * `AbortSignal` combining, with proper listener cleanup (fixes a real leak found in review — see\n * `docs/implementation-plan.md` Ticket 2).\n *\n * @packageDocumentation\n */\n\n/** The result of {@link combineSignals}: the combined signal, plus a cleanup function callers MUST invoke once done with it. */\nexport interface CombinedSignal {\n /** Aborts as soon as any of the input signals do. */\n signal: AbortSignal;\n /**\n * Removes every listener this call attached to the input signals. Without this, a long-lived,\n * caller-supplied signal shared across many calls (e.g. paginating, each attempt retried)\n * accumulates one never-removed listener per call — a real leak, not hypothetical.\n */\n cleanup: () => void;\n}\n\n/**\n * Combines multiple signals into one that aborts as soon as any of them do, with cleanup so\n * listeners don't outlive a single use. Hand-rolled rather than the built-in `AbortSignal.any`\n * (Node 18.17+/20.3+ only) so the SDK's stated Node 18+ floor (addendum §1) holds without a\n * caveat.\n *\n * Callers MUST invoke `cleanup()` once the combined signal is no longer needed (e.g. in a\n * `finally` block) — otherwise this reintroduces the exact listener leak it was written to fix.\n */\nexport function combineSignals(signals: Array<AbortSignal | undefined>): CombinedSignal {\n const controller = new AbortController();\n const cleanupFns: Array<() => void> = [];\n\n for (const signal of signals) {\n if (!signal) continue;\n if (signal.aborted) {\n controller.abort(signal.reason);\n break;\n }\n const onAbort = () => controller.abort(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n cleanupFns.push(() => signal.removeEventListener(\"abort\", onAbort));\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n for (const fn of cleanupFns) fn();\n },\n };\n}\n","import { mapHttpError } from \"../errors/mapHttpError.js\";\nimport { NetworkError, SuqoError } from \"../errors/SuqoError.js\";\nimport type { SdkConfig } from \"../config/index.js\";\nimport { buildUrl, type QueryParams } from \"./urlBuilder.js\";\nimport {\n backoffDelayMs,\n isRetryableFailure,\n isRetryableMethod,\n parseRetryAfterDetailMs,\n parseRetryAfterMs,\n} from \"./retry.js\";\nimport { combineSignals } from \"./signals.js\";\n\n/**\n * HTTP methods this client supports (SDK-SPEC.md §1). `GET` for every read; every other method is\n * a write — `POST` for most, `PATCH` for partial updates (`customers.update()`,\n * `webhooks.update()`), `PUT` for `webhooks.replace()` and `DELETE` for `webhooks.delete()`.\n */\nexport type HttpMethod = \"GET\" | \"POST\" | \"PATCH\" | \"PUT\" | \"DELETE\";\n\n/** Fields shared by every request, regardless of method. */\ninterface HttpRequestOptionsBase {\n /** The route path, e.g. `/api/v1/products` — the trailing slash is guaranteed by `buildUrl`; don't add it yourself. */\n path: string;\n /** Query params, appended after the trailing slash. `undefined` values are skipped. */\n query?: QueryParams;\n /** Per-call timeout override, in milliseconds. Defaults to `SdkConfig.timeout`. */\n timeoutMs?: number;\n /**\n * Optional caller-supplied signal for cancelling an in-flight request — e.g. the host\n * application's own request lifecycle ending, or an overall operation deadline spanning\n * multiple SDK calls. Combined with the internal timeout signal (whichever fires first wins)\n * during the fetch itself, *and* observed during any retry backoff wait — cancelling mid-sleep\n * doesn't have to wait for the sleep to finish first. An explicit caller cancellation is never\n * retried, even for an otherwise-retryable read — retrying after the caller said \"stop\" would\n * ignore what they asked for.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Options for a `GET` request. Never carries a body — every read in this API is `GET`\n * (SDK-SPEC.md §1), and `fetch` itself rejects a body on `GET`. Enforced at the type level, not\n * just by convention, so this can't be gotten wrong from a `TBody`-typed call site by accident.\n */\nexport interface HttpGetRequestOptions extends HttpRequestOptionsBase {\n method: \"GET\";\n}\n\n/**\n * Options for a `POST` request. Generic on `TBody` so a call site can pass a concrete request\n * type (e.g. `CreateSubscriptionParams`, wired up in Ticket 4 — the SDK-surface type for\n * `openapi.yaml`'s `CreateSubscriptionRequest` schema; SDK Naming Map v1.1 renames every\n * `*Request` wire schema to `*Params` on the surface, since \"Request\" reads as an HTTP request\n * object, not an SDK input) and have it checked at compile time — `unknown` is only the *default*\n * for callers that don't specify one, never a signal that bodies go untyped by design.\n */\nexport interface HttpPostRequestOptions<TBody = unknown> extends HttpRequestOptionsBase {\n method: \"POST\";\n /** JSON-serializable request body. Omit entirely for a bodyless write (e.g. `cancel`). */\n body?: TBody;\n}\n\n/**\n * Options for a `PATCH` request — a partial update (`customers.update()`). Same body typing as\n * {@link HttpPostRequestOptions}, and like every write it is never retried (SDK-SPEC.md §8).\n */\nexport interface HttpPatchRequestOptions<TBody = unknown> extends HttpRequestOptionsBase {\n method: \"PATCH\";\n /** JSON-serializable request body — only the fields being changed. */\n body?: TBody;\n}\n\n/**\n * Options for a `PUT` request — a full replacement (`webhooks.replace()`). Never retried, like\n * every write (SDK-SPEC.md §8).\n */\nexport interface HttpPutRequestOptions<TBody = unknown> extends HttpRequestOptionsBase {\n method: \"PUT\";\n /** JSON-serializable request body — the complete new representation. */\n body?: TBody;\n}\n\n/**\n * Options for a `DELETE` request (`webhooks.delete()`). Carries no body. Never retried, like\n * every write (SDK-SPEC.md §8) — the API answers `204` with an empty body, which\n * {@link HttpClient.request} resolves as `undefined`.\n */\nexport interface HttpDeleteRequestOptions extends HttpRequestOptionsBase {\n method: \"DELETE\";\n}\n\n/**\n * Options accepted by {@link HttpClient.request}. `HttpClient` itself is internal (not exported\n * from `src/index.ts`); the SDK's actual typed, consumer-facing contract lives one layer up, in\n * each resource method's own public signature.\n */\nexport type HttpRequestOptions<TBody = unknown> =\n | HttpGetRequestOptions\n | HttpPostRequestOptions<TBody>\n | HttpPatchRequestOptions<TBody>\n | HttpPutRequestOptions<TBody>\n | HttpDeleteRequestOptions;\n\n/** `RequestInit` extended with undici's non-standard `dispatcher` option (Node's built-in `fetch`, addendum §2). */\ninterface FetchInit extends RequestInit {\n dispatcher?: unknown;\n}\n\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Best-effort JSON parse of a response body. Never throws — an empty body yields `undefined`. A\n * non-JSON body yields `undefined` too, unless `keepText` is set: the error path sets it so a\n * proxy/WAF page (e.g. Cloudflare's \"error code: 1010\") reaches the error's `rawBody` as text\n * instead of being dropped. A 2xx keeps the old `undefined`.\n */\nasync function parseJsonBody(response: Response, keepText = false): Promise<unknown> {\n const text = await response.text();\n if (text.length === 0) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return keepText ? text : undefined;\n }\n}\n\n/**\n * Wraps a `fetch` rejection (network failure, `AbortSignal.timeout` firing, or a caller\n * cancellation) as a `NetworkError` (SDK-SPEC.md §7 — covers timeouts too, no separate class).\n */\nfunction toNetworkError(cause: unknown, timeoutMs: number, callerCancelled: boolean): NetworkError {\n if (callerCancelled) {\n return new NetworkError(\"Request cancelled\", { cause });\n }\n if (cause instanceof Error && cause.name === \"TimeoutError\") {\n return new NetworkError(`Request timed out after ${timeoutMs}ms`, { cause });\n }\n const message = cause instanceof Error ? cause.message : String(cause);\n return new NetworkError(`Network request failed: ${message}`, { cause });\n}\n\n/** Options accepted by {@link HttpClient}'s constructor. */\nexport interface HttpClientOptions {\n /**\n * Injectable sleep implementation, so tests can skip real backoff delays. @internal — not part\n * of the public contract; defaults to a real `setTimeout`-based wait in production.\n */\n sleep?: (ms: number) => Promise<void>;\n}\n\n/**\n * The fetch wrapper every resource calls through (SDK-SPEC.md §3, §4, §8; addendum §2, §10).\n *\n * Handles, in one place: the trailing-slash URL guarantee, the `Authorization`/`Content-Type`\n * headers, per-call timeout via `AbortSignal.timeout`, caller-supplied cancellation (`options.\n * signal`, combined with the timeout during the fetch and also observed during any retry backoff\n * wait), the read-only retry policy (exponential backoff + jitter, honoring `Retry-After`,\n * clamped so a misconfigured server can't stall a request indefinitely), and feeding every\n * non-2xx response through `mapHttpError()` so callers only ever see a typed `SuqoError`\n * subclass — never a raw `fetch` rejection or an unparsed error body.\n *\n * Not wired into `SuqoClient`/any resource yet — that lands in Ticket 4.\n */\nexport class HttpClient {\n readonly #config: SdkConfig;\n readonly #sleep: (ms: number) => Promise<void>;\n\n constructor(config: SdkConfig, options: HttpClientOptions = {}) {\n this.#config = config;\n this.#sleep = options.sleep ?? defaultSleep;\n }\n\n /**\n * Sends a request and returns the parsed 2xx body, or throws the `SuqoError` subclass\n * `mapHttpError` maps a non-2xx response to. Writes are never retried (SDK-SPEC.md §8, §12);\n * reads retry on network failure, `429`, or `5xx`, bounded by `SdkConfig.maxRetries`.\n *\n * Generic on both `TResponse` and `TBody` — e.g.\n * `request<CreateSubscriptionResponse, CreateSubscriptionParams>({ body, ... })` — so a\n * resource method (Ticket 4) gets its request body checked against the exact shape it means to\n * send, not just `unknown`.\n */\n async request<TResponse, TBody = unknown>(options: HttpRequestOptions<TBody>): Promise<TResponse> {\n // Defense-in-depth beneath the type-level guarantee (HttpGetRequestOptions has no `body`\n // field at all): a caller that bypasses TypeScript (a raw JS call, or an `as` cast) fails\n // loudly here instead of either crashing deep inside fetch (the original bug) or — worse —\n // silently dropping the body with no error at all, which would be even harder to debug.\n if (\n (options.method === \"GET\" || options.method === \"DELETE\") &&\n (options as { body?: unknown }).body !== undefined\n ) {\n throw new TypeError(`HttpClient.request: a ${options.method} request cannot carry a body.`);\n }\n\n // Both steps below wrapped in one try/catch, found in review: a malformed `path` (an\n // unparseable \"next\" link, say) or the off-host guard tripping are pre-flight, one-shot,\n // deterministic failures — they never touched `fetch`, so they must still surface as a typed\n // `NetworkError`, never a raw `TypeError`/`Error`, to hold the class's own documented contract\n // that a caller only ever sees a `SuqoError` subclass, and thrown directly (not fed through\n // the retry loop below) since retrying a malformed URL can never succeed.\n let url: string;\n try {\n url = buildUrl(this.#config.baseUrl, options.path, options.query);\n\n // Security guard: buildUrl accepts an already-complete absolute URL as `path` (needed so a\n // pagination `next` link, Ticket 3, can be followed as-is) — but this client attaches the\n // real API key to every request unconditionally. Without this check, a `next` link that\n // ever pointed off-host (a compromised proxy, a backend bug, tampering) would silently leak\n // the key to that host. `path` being relative always resolves to `baseUrl`'s own origin by\n // construction, so this only ever fires for an absolute `path` that's actually wrong.\n if (new URL(url).origin !== new URL(this.#config.baseUrl).origin) {\n throw new Error(\n `Refusing to send a request to ${new URL(url).origin} — it does not match the ` +\n `configured origin ${new URL(this.#config.baseUrl).origin}. This SDK never sends its ` +\n \"API key to a different host.\",\n );\n }\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n throw new NetworkError(`Invalid request URL: ${message}`, { cause });\n }\n\n const retryable = isRetryableMethod(options.method);\n const maxAttempts = retryable ? this.#config.maxRetries + 1 : 1;\n const timeoutMs = options.timeoutMs ?? this.#config.timeout;\n\n for (let attempt = 1; ; attempt++) {\n const isLastAttempt = attempt >= maxAttempts;\n\n try {\n const response = await this.#doFetch(url, options, timeoutMs);\n\n if (response.ok) {\n return (await parseJsonBody(response)) as TResponse;\n }\n\n // Reading the body can fail too (e.g. the connection resets mid-stream after headers\n // already arrived fine) — that failure needs the exact same retry-or-network-error\n // treatment as `#doFetch` itself failing, not an unmapped rejection escaping `request()`.\n // Wrapping both in the same try/catch below (found in review) is what makes that happen.\n const body = await parseJsonBody(response, true);\n // Honored on any status, not just 429 (found in review) — a retried 5xx (isRetryableFailure\n // covers 500-599 too) can carry the same header, e.g. a 503 during a maintenance window, and\n // ignoring it there means retrying on our own backoff instead of the wait the server asked for.\n // The header wins when present; the API's own rate limit names its wait only inside a\n // 429's `detail`, so that is the fallback.\n const retryAfter =\n parseRetryAfterMs(response.headers.get(\"Retry-After\")) ??\n (response.status === 429 ? parseRetryAfterDetailMs(body) : undefined);\n\n if (\n !isLastAttempt &&\n retryable &&\n isRetryableFailure({ networkError: false, status: response.status })\n ) {\n await this.#sleepOrAbort(retryAfter ?? backoffDelayMs(attempt - 1), options.signal, timeoutMs);\n continue;\n }\n\n throw mapHttpError({\n status: response.status,\n statusText: response.statusText,\n body,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n });\n } catch (cause) {\n // Already a correctly-classified SuqoError (from mapHttpError just above, or a caller\n // cancellation/timeout from #sleepOrAbort) — pass it through unchanged, don't reclassify\n // an already-final decision as a fresh network failure.\n if (cause instanceof SuqoError) throw cause;\n\n // An explicit caller cancellation is never retried, even for a normally-retryable read —\n // continuing after the caller said \"stop\" would ignore what they asked for.\n const callerCancelled = options.signal?.aborted === true;\n // Routed through isRetryableFailure (not inlined) so the retry policy for a network-level\n // failure lives in exactly one place — retry.ts — the same as the HTTP-status decision\n // below. Found in review: an earlier version inlined this as \"always true\" for\n // readability, which let this decision and retry.ts's own copy of it silently drift apart\n // if the policy ever changed in only one of the two places.\n if (!callerCancelled && !isLastAttempt && retryable && isRetryableFailure({ networkError: true })) {\n await this.#sleepOrAbort(backoffDelayMs(attempt - 1), options.signal, timeoutMs);\n continue;\n }\n throw toNetworkError(cause, timeoutMs, callerCancelled);\n }\n }\n }\n\n /**\n * Sleeps for `ms`, but rejects immediately with a \"cancelled\" `NetworkError` if `signal` aborts\n * *during* the wait — a caller cancelling mid-backoff doesn't have to wait for the sleep to\n * finish first (found in review: the previous version ignored `signal` here entirely).\n */\n async #sleepOrAbort(ms: number, signal: AbortSignal | undefined, timeoutMs: number): Promise<void> {\n if (!signal) {\n await this.#sleep(ms);\n return;\n }\n if (signal.aborted) {\n throw toNetworkError(signal.reason, timeoutMs, true);\n }\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => reject(toNetworkError(signal.reason, timeoutMs, true));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n // Clean up on BOTH branches, not just the fulfillment one (found in review) — an injected\n // `sleep` that rejects for a reason unrelated to cancellation would otherwise leave\n // `onAbort` attached to `signal` forever, since `{ once: true }` only self-removes when the\n // \"abort\" event actually fires.\n this.#sleep(ms).then(\n () => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n },\n (sleepError: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(sleepError);\n },\n );\n });\n }\n\n async #doFetch<TBody>(\n url: string,\n options: HttpRequestOptions<TBody>,\n timeoutMs: number,\n ): Promise<Response> {\n const isWrite = options.method !== \"GET\";\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#config.apiKey}`,\n };\n if (isWrite) {\n // SDK-SPEC.md §4: sent on every write, regardless of whether this particular write carries\n // a body (e.g. `cancel` has none).\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n // `body` only exists on the POST/PATCH/PUT branches of the HttpRequestOptions union — GET and\n // DELETE can't carry one even at the type level (found in review: a GET-with-body used to be\n // constructible, reach fetch, throw there, and get silently retried/masked as a generic\n // NetworkError). Checked per method rather than \"is POST\" so a PATCH/PUT body isn't dropped.\n const body = \"body\" in options ? options.body : undefined;\n\n const { signal, cleanup } = combineSignals([AbortSignal.timeout(timeoutMs), options.signal]);\n try {\n const init: FetchInit = {\n method: options.method,\n headers,\n signal,\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n ...(this.#config.dispatcher !== undefined ? { dispatcher: this.#config.dispatcher } : {}),\n };\n\n return await fetch(url, init);\n } finally {\n // Without this, a long-lived caller-supplied signal shared across many calls/attempts\n // (e.g. paginating, each retried) accumulates one never-removed listener per attempt — a\n // real leak found in review, not hypothetical.\n cleanup();\n }\n }\n}\n","import type { QueryParams } from \"./http/urlBuilder.js\";\n\n/**\n * The common paginated-list envelope every list endpoint returns (SDK-SPEC.md §6).\n *\n * @packageDocumentation\n */\n\n/**\n * The page-number pagination envelope common to every list endpoint (SDK-SPEC.md §6).\n * Named `Page` per the cross-language SDK Naming Map v1.1 §06 (mirrors `openapi.yaml`'s\n * `PaginationEnvelope` schema, renamed on the SDK surface only — the wire shape is unaffected).\n */\nexport interface Page<T> {\n /** Total row count across every page, not just this one. */\n count: number;\n /** URL of the next page, or `null` on the last page. */\n next: string | null;\n /** URL of the previous page, or `null` on the first page. */\n previous: string | null;\n results: T[];\n}\n\n/**\n * The four extra status counts the Subscriptions list adds on top of the common envelope\n * (SDK-SPEC.md §6, `openapi.yaml`'s `SubscriptionListEnvelope`).\n */\nexport interface SubscriptionStatusCounts {\n totalSubscriptions: number;\n activeSubscriptions: number;\n dueSubscriptions: number;\n inactiveSubscriptions: number;\n}\n\n/**\n * The Subscriptions list envelope: the common shape plus the four extra counts, surfaced\n * alongside `results` rather than replacing the common envelope shape (SDK-SPEC.md §6). Generic\n * over `T` so this file doesn't need to know about the `Subscription` type — Ticket 4 supplies it.\n * Named `SubscriptionPage` per the Naming Map §06 (mirrors `openapi.yaml`'s\n * `SubscriptionListEnvelope`, renamed on the SDK surface only).\n */\nexport type SubscriptionPage<T> = Page<T> & SubscriptionStatusCounts;\n\n/** Manual pagination params a caller can pass instead of using `listAll`. */\nexport interface PageParams {\n /** 1-indexed page number. Server default is 1 if omitted. */\n page?: number;\n /** Results per page (server max 100, server default 20 if omitted). */\n pageSize?: number;\n}\n\n/**\n * Maps {@link PageParams}' camelCase fields to the wire's snake_case query params\n * (`pageSize` → `page_size`), so every future paginated resource method shares one mapping\n * instead of re-deriving it. `undefined` fields are omitted, matching `buildUrl`'s own\n * omission rule (Ticket 2) — a caller can pass `{ page, pageSize }` straight through unfiltered.\n */\nexport function toPageQuery(params?: PageParams): QueryParams {\n return {\n page: params?.page,\n page_size: params?.pageSize,\n };\n}\n\n/**\n * Maps a {@link Page}'s `results` through `deserializeItem`, leaving `count`/`next`/`previous`\n * untouched — those three field names already match the wire exactly (`openapi.yaml`\n * `PaginationEnvelope`), only `results`' items need any per-resource field mapping. Shared by\n * every paginated resource so each one only has to supply its own item deserializer, not\n * re-implement unwrapping the envelope.\n */\nexport function deserializePage<TWireItem, T>(\n wire: Page<TWireItem>,\n deserializeItem: (item: TWireItem) => T,\n): Page<T> {\n return {\n count: wire.count,\n next: wire.next,\n previous: wire.previous,\n results: wire.results.map(deserializeItem),\n };\n}\n\n/**\n * Auto-iterates every row across every page, following `next` until it's `null` (SDK-SPEC.md §6),\n * without requiring manual page math. Deliberately decoupled from `HttpClient`/any resource: the\n * caller supplies the already-fetched first page and a `fetchNext` callback that turns a `next`\n * URL into the following page. This keeps pagination testable and reusable across every future\n * paginated resource (Ticket 4) without this file needing to know how HTTP requests are made.\n *\n * Manual `page`/`pageSize` access (via {@link toPageQuery}) remains available independently —\n * this iterator is additive, not a replacement (SDK-SPEC.md §6 requires both to keep working).\n *\n * Guards against a `fetchNext` (or a server) that never reaches `next: null` — a real bug caught\n * in review, not hypothetical, since the loop would otherwise trust the sequence to terminate\n * forever. After `maxPages` pages, throws instead of hanging silently.\n *\n * @param maxPages - Safety cap on how many pages to follow before giving up. Defaults to a limit\n * generous enough for any realistic result set (10,000 pages — millions of rows at the max page\n * size) while still catching a genuine stuck loop quickly.\n *\n * @example\n * ```ts\n * const firstPage = await suqo.subscriptions.list({ pageSize: 100 });\n * for await (const subscription of listAll(firstPage, fetchNextPage)) {\n * // subscription: Subscription\n * }\n * ```\n */\nexport async function* listAll<T>(\n firstPage: Page<T>,\n fetchNext: (nextUrl: string) => Promise<Page<T>>,\n maxPages = 10_000,\n): AsyncIterableIterator<T> {\n let page: Page<T> = firstPage;\n let pagesSeen = 0;\n\n while (true) {\n pagesSeen++;\n if (pagesSeen > maxPages) {\n throw new Error(\n `listAll exceeded ${maxPages} pages without reaching next: null. This usually means the ` +\n \"server or the fetchNext callback isn't advancing — check for a stuck loop.\",\n );\n }\n\n for (const item of page.results) {\n yield item;\n }\n\n if (page.next === null) {\n return;\n }\n\n page = await fetchNext(page.next);\n }\n}\n\n/**\n * Bridges {@link listAll} to a resource's public `.autoPaging()` method (SDK Naming Map v1.1 §04\n * — the public name is `.autoPaging()`; `listAll` stays this file's own internal engine name, per\n * Ticket 3's design doc). Named `bridgeAutoPaging`, not `autoPaging`, specifically so it never\n * shares a name with the public method that calls it — the two would still resolve correctly\n * either way (a class method name isn't a lexical binding inside its own body), but a distinct\n * name means nobody has to reason through that to be sure.\n *\n * Takes the first page as a **thunk** (`() => Promise<Page<T>>`), not an already-started\n * `Promise` — this is deliberate, not a style choice. A resource method's `.autoPaging()` calls\n * `this.list(params)` to build that first request; if that call happened eagerly (i.e. the caller\n * passed the `Promise` itself), it would start firing the instant `.autoPaging()` is invoked, not\n * when the caller actually begins iterating — and a rejection sitting unhandled between those two\n * moments is a genuine `unhandledRejection`, which terminates a Node process by default (found in\n * review, reproduced: calling `.autoPaging()` then doing anything else before iterating, on a\n * request that fails, crashes the process — confirmed both with and without a handler attached).\n * Wrapping the call in a thunk (`() => this.list(params)`) defers it until the async generator\n * body actually runs `fetchFirstPage()`, which only happens once the caller starts iterating —\n * matching every other async generator's behavior for real, not just by the doc comment's claim.\n *\n * Still fully decoupled from `HttpClient`/any resource, same as {@link listAll} — this file never\n * imports anything from the HTTP layer.\n *\n * @example\n * ```ts\n * autoPaging(params?: PageParams): AsyncIterableIterator<Product> {\n * return bridgeAutoPaging(() => this.list(params), (nextUrl) =>\n * this.#http.request<Page<Product>>({ method: \"GET\", path: nextUrl }),\n * );\n * }\n * ```\n */\nexport function bridgeAutoPaging<T>(\n fetchFirstPage: () => Promise<Page<T>>,\n fetchNext: (nextUrl: string) => Promise<Page<T>>,\n maxPages = 10_000,\n): AsyncIterableIterator<T> {\n return (async function* () {\n yield* listAll(await fetchFirstPage(), fetchNext, maxPages);\n })();\n}\n","import type { HttpClient } from \"../http/HttpClient.js\";\nimport { bridgeAutoPaging, deserializePage, toPageQuery, type Page, type PageParams } from \"../pagination.js\";\nimport type { BillingPeriod, Offer, Plan, Product, ProductVat } from \"../models/index.js\";\n\n/** `GET /api/v1/products/` — no trailing slash here; `HttpClient`/`buildUrl` guarantees it (Ticket 2). */\nconst PRODUCTS_PATH = \"/api/v1/products\";\n\n/**\n * The wire shapes `openapi.yaml`'s `Product`/`Plan`/`BillingPeriod` schemas actually send —\n * snake_case, exactly as documented. `HttpClient.request()` doesn't transform response bodies at\n * all (SDK-SPEC.md §5's camelCase requirement is this file's job, not the transport layer's), so\n * every field below is deserialized explicitly rather than trusted via a type assertion alone.\n */\ninterface WireBillingPeriod {\n pbp_id: string;\n interval_type: string;\n interval_count: number;\n label: string;\n price: string;\n currency: string;\n is_current: boolean;\n is_limited: boolean;\n is_archived: boolean;\n offers?: WireOffer[];\n}\n\ninterface WireOffer {\n id: string;\n discount_amount: number;\n starts_at?: string | null;\n valid_until?: string | null;\n is_active: boolean;\n}\n\ninterface WirePlan {\n plan_id: string;\n plan_name: string;\n description?: string | null;\n // Optional, not required — `openapi.yaml`'s Product schema has no `required` list at all, so\n // omitting this key entirely is spec-legal (found in review: the deserializer used to assume\n // it was always present and crashed on `.map()` when it wasn't).\n billing_periods?: WireBillingPeriod[];\n}\n\ninterface WireProductVat {\n is_vat_active: boolean;\n vat_type?: string | null;\n vat_percentage?: string | null;\n}\n\ninterface WireProductImage {\n image: string;\n image_order: number;\n}\n\ninterface WireProduct {\n product_id: string;\n name: string;\n // Nullable on the wire (openapi.yaml), and optional because the schema doesn't list them as\n // required — `?? null` below turns an omitted key into the documented `null`.\n description?: string | null;\n type: string;\n is_active: boolean;\n terms_and_conditions?: string | null;\n features_and_benefits?: string | null;\n // Optional (not just nullable) and `plan` optional too — same reasoning as `WirePlan.billing_periods`\n // above: no `required` list on this schema, so both are legally omittable, not just nullable.\n vat?: WireProductVat | null;\n // Objects, not URL strings — `openapi.yaml` previously declared `string[]`, which never matched\n // the wire (Swagger's `ProductImage` and a captured response both show `{ image, image_order }`).\n // Optional for the same no-`required`-list reason as `plan`.\n product_image?: WireProductImage[];\n plan?: WirePlan[];\n total_subscribers: string;\n created_at: string;\n updated_at: string;\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializeBillingPeriod(wire: WireBillingPeriod): BillingPeriod {\n return {\n pbpId: wire.pbp_id,\n intervalType: wire.interval_type,\n intervalCount: wire.interval_count,\n label: wire.label,\n price: wire.price,\n currency: wire.currency,\n isCurrent: wire.is_current,\n isLimited: wire.is_limited,\n isArchived: wire.is_archived,\n offers: (wire.offers ?? []).map(deserializeOffer),\n };\n}\n\nfunction deserializeOffer(wire: WireOffer): Offer {\n return {\n id: wire.id,\n discountAmount: wire.discount_amount,\n startsAt: wire.starts_at ?? null,\n validUntil: wire.valid_until ?? null,\n isActive: wire.is_active,\n };\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializePlan(wire: WirePlan): Plan {\n return {\n planId: wire.plan_id,\n planName: wire.plan_name,\n description: wire.description ?? null,\n // `openapi.yaml`'s Product schema has no `required` list at all, so `billing_periods` being\n // omitted entirely (not just an empty array) is spec-legal — `?? []` degrades to an empty\n // list instead of `.map` throwing on `undefined` (found in review, reproduced).\n billingPeriods: (wire.billing_periods ?? []).map(deserializeBillingPeriod),\n };\n}\n\nfunction deserializeProductVat(wire: WireProductVat): ProductVat {\n return {\n isVatActive: wire.is_vat_active,\n vatType: wire.vat_type ?? null,\n vatPercentage: wire.vat_percentage ?? null,\n };\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializeProduct(wire: WireProduct): Product {\n return {\n productId: wire.product_id,\n name: wire.name,\n description: wire.description ?? null,\n type: wire.type,\n isActive: wire.is_active,\n termsAndConditions: wire.terms_and_conditions ?? null,\n featuresAndBenefits: wire.features_and_benefits ?? null,\n // `== null` (not `=== null`) is deliberate — it catches both an explicit `null` and an\n // entirely omitted `vat` key. `openapi.yaml` has no `required` list for Product, so omitting\n // `vat` is spec-legal, and the old `=== null` check crashed on `deserializeProductVat(undefined)`\n // when that happened (found in review, reproduced).\n vat: wire.vat == null ? null : deserializeProductVat(wire.vat),\n productImage: (wire.product_image ?? []).map((img) => ({ image: img.image, imageOrder: img.image_order })),\n // Same reasoning as `billingPeriods` above — `plan` being omitted entirely is spec-legal.\n plan: (wire.plan ?? []).map(deserializePlan),\n totalSubscribers: wire.total_subscribers,\n createdAt: wire.created_at,\n updatedAt: wire.updated_at,\n };\n}\n\n/**\n * `client.products` (SDK-SPEC.md §5, §6; `openapi.yaml` `listProducts`). The only resource that\n * works before KYC verification — no `KycRequiredError` case to handle here.\n */\nexport class ProductsResource {\n readonly #http: HttpClient;\n\n constructor(http: HttpClient) {\n this.#http = http;\n }\n\n /** Lists the authenticated seller's active products. Paginated (SDK-SPEC.md §6). */\n async list(params?: PageParams): Promise<Page<Product>> {\n const wire = await this.#http.request<Page<WireProduct>>({\n method: \"GET\",\n path: PRODUCTS_PATH,\n query: toPageQuery(params),\n });\n return deserializePage(wire, deserializeProduct);\n }\n\n /**\n * Auto-iterates every product across every page, following `next` until it's `null`\n * (SDK-SPEC.md §6). Manual `list({ page, pageSize })` remains available independently — this is\n * additive, not a replacement.\n */\n autoPaging(params?: PageParams): AsyncIterableIterator<Product> {\n return bridgeAutoPaging(() => this.list(params), async (nextUrl) => {\n const wire = await this.#http.request<Page<WireProduct>>({ method: \"GET\", path: nextUrl });\n return deserializePage(wire, deserializeProduct);\n });\n }\n}\n","import type { SubscriptionCustomer } from \"./Customer.js\";\n\n/**\n * `Subscription`'s model types (`specs/openapi.yaml` `Subscription`/`SubscriptionProduct`/\n * `SubscriptionStatus` — SDK-SPEC.md §5).\n *\n * @packageDocumentation\n */\n\n/**\n * The subscription lifecycle enum (`openapi.yaml` `SubscriptionStatus`). Wire values are\n * invariant (R1); this is a constant object + derived union, not a TypeScript `enum` — a plain\n * union alone can't be iterated/round-tripped the way SDK Naming Map v1.1 §10 requires: \"decoders\n * must round-trip an unknown value rather than raising,\" so an unrecognized status the API adds\n * later (before this SDK's next release) passes through as a plain string instead of throwing.\n */\nexport const SubscriptionStatus = {\n /** Newly created; the buyer hasn't paid yet. */\n PendingCheckout: \"pending_checkout\",\n /** Currently active. */\n Active: \"active\",\n /** `nextBillingCycle` passed with no payment yet. */\n Due: \"due\",\n /** Cancelled immediately (user-prompted). */\n Cancelled: \"cancelled\",\n /** Scheduled to cancel at the end of the current billing cycle — see SDK-SPEC.md §5's `cancel` note. */\n PendingCancellation: \"pending_cancellation\",\n /** Auto-ended after a grace period without payment. */\n Inactive: \"inactive\",\n} as const;\n\n/**\n * Any known {@link SubscriptionStatus} wire value, OR an arbitrary string. The `& {}` intersection\n * is deliberate, not a typo — a bare `string` union member would collapse the whole type to\n * `string` and lose autocomplete for the known values; this keeps both: editor autocomplete\n * suggests the six known values, but an unrecognized one the API adds later still assigns without\n * a cast, satisfying the module doc's round-trip requirement at the type level too, not just at\n * runtime.\n */\n// This is the \"loose autocomplete\" idiom (see the doc comment above), not an accidental `{}`. The\n// lint rule's own suggested fix, `NonNullable<unknown>`, resolves to plain `unknown`, and\n// `string & unknown` collapses right back to `string` — throwing away exactly the\n// autocomplete-for-known-values this type exists to keep.\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport type SubscriptionStatus = (typeof SubscriptionStatus)[keyof typeof SubscriptionStatus] | (string & {});\n\n/**\n * The product summary embedded on a {@link Subscription} (`openapi.yaml` `SubscriptionProduct`) — a\n * summary, not the full {@link import(\"./Product.js\").Product} record. The API may send `null` for\n * any field, and an omitted field also comes back `null`.\n */\nexport interface SubscriptionProduct {\n productId: string | null;\n name: string | null;\n planName: string | null;\n /** Pass this to `subscriptions.create({ pbpId, ... })`. */\n pbpId: string | null;\n label: string | null;\n /** Decimal string. Never coerced to a number — SDK-SPEC.md §5. */\n price: string | null;\n currency: string | null;\n}\n\n/** A seller's subscription (`openapi.yaml` `Subscription`). */\nexport interface Subscription {\n subscriptionId: string;\n status: SubscriptionStatus;\n /** `true` iff `status === SubscriptionStatus.Active`. */\n isActive: boolean;\n /** The buyer, in the read shape — renamed from the wire's `client` (SDK Naming Map v1.1 §11). */\n customer: SubscriptionCustomer;\n /** `null` if the backend omits or nulls this field — `openapi.yaml` declares no required fields on `Subscription` (found in review). */\n product: SubscriptionProduct | null;\n currentPeriodStart: string | null;\n /** Equals `nextBillingCycle`. */\n currentPeriodEnd: string | null;\n /** The date this subscription bills next (same value as `currentPeriodEnd`). */\n nextBillingCycle: string | null;\n createdAt: string;\n}\n","import type { CheckoutSessionResponse, CustomerInput, SubscriptionCustomer } from \"../models/index.js\";\nimport { isRecord } from \"../utils/index.js\";\n\n/**\n * The customer↔client serialization boundary (SDK Naming Map v1.1 §11 \"Customer boundary\").\n * `openapi.yaml` keeps `client`; the SDK surfaces `customer` — that divergence is deliberate (the\n * wire name collides with the SDK's own client object), but it means the translation has to\n * happen *somewhere*, exactly once. This module is that one place: no resource method, no error\n * class, and no transport code (`HttpClient`) touches this mapping directly — they call through\n * here instead.\n *\n * Both directions are asymmetric on the wire, not just renamed (`specs/openapi.yaml`\n * `ClientRead`/`ClientWrite`):\n * - **Write** (`ClientWrite`, this file's {@link serializeCustomerInput}): the nested `billing`\n * object's own fields carry a `billing_` prefix (`businessName` → `billing_business_name`), but\n * `shipping`'s fields don't (`fullName` → `full_name`, no prefix). This is a real backend\n * quirk, not something to \"fix\" here — the serializer has to reproduce it exactly.\n * - **Read** (`ClientRead`, this file's {@link deserializeSubscriptionCustomer}): neither nested\n * object carries a prefix at all (`business_name`, not `billing_business_name`).\n *\n * `rawBody` is never touched by either function (R1) — this boundary only affects the typed\n * `customer`/`SubscriptionCustomer` a resource method hands back, never what a caller sees if they\n * inspect an error's `rawBody`.\n *\n * @packageDocumentation\n */\n\n/**\n * `CustomerInput` (SDK) → the wire's `ClientWrite` shape, for `subscriptions.create()`'s request\n * body. The caller is responsible for nesting the result under the wire's `client` key — this\n * function only produces the object that goes there, so it stays agnostic of where it's mounted.\n */\nexport function serializeCustomerInput(customer: CustomerInput): Record<string, unknown> {\n const wire: Record<string, unknown> = {\n phone: customer.phone,\n full_name: customer.fullName,\n email: customer.email,\n address: customer.address,\n };\n\n if (customer.billing) {\n const billing: Record<string, unknown> = {\n billing_business_name: customer.billing.businessName,\n billing_email: customer.billing.email,\n billing_address: customer.billing.address,\n };\n if (customer.billing.panVat !== undefined) billing.billing_pan_vat = customer.billing.panVat;\n wire.billing = billing;\n }\n\n if (customer.shipping) {\n const shipping: Record<string, unknown> = {\n phone: customer.shipping.phone,\n full_name: customer.shipping.fullName,\n email: customer.shipping.email,\n };\n if (customer.shipping.address !== undefined) shipping.address = customer.shipping.address;\n wire.shipping = shipping;\n }\n\n return wire;\n}\n\n/**\n * The wire's `ClientRead` shape (already unwrapped from `client`) → `SubscriptionCustomer` (SDK).\n * Best-effort, like `mapHttpError`'s own body parsing: a field of the wrong type or a\n * malformed/missing nested object is simply omitted rather than fabricated or thrown on — a\n * `Subscription` a caller already has in hand shouldn't become unusable because of one\n * unexpected field.\n */\nexport function deserializeSubscriptionCustomer(wire: unknown): SubscriptionCustomer {\n if (!isRecord(wire)) return {};\n\n const customer: SubscriptionCustomer = {};\n if (typeof wire.phone === \"string\") customer.phone = wire.phone;\n if (typeof wire.full_name === \"string\") customer.fullName = wire.full_name;\n if (typeof wire.email === \"string\") customer.email = wire.email;\n if (typeof wire.address === \"string\") customer.address = wire.address;\n\n if (isRecord(wire.billing)) {\n customer.billing = {\n ...(typeof wire.billing.business_name === \"string\" ? { businessName: wire.billing.business_name } : {}),\n ...(typeof wire.billing.email === \"string\" ? { email: wire.billing.email } : {}),\n ...(typeof wire.billing.address === \"string\" ? { address: wire.billing.address } : {}),\n ...(typeof wire.billing.pan_vat === \"string\" ? { panVat: wire.billing.pan_vat } : {}),\n };\n } else if (wire.billing === null) {\n customer.billing = null;\n }\n\n if (isRecord(wire.shipping)) {\n customer.shipping = {\n ...(typeof wire.shipping.phone === \"string\" ? { phone: wire.shipping.phone } : {}),\n ...(typeof wire.shipping.full_name === \"string\" ? { fullName: wire.shipping.full_name } : {}),\n ...(typeof wire.shipping.email === \"string\" ? { email: wire.shipping.email } : {}),\n ...(typeof wire.shipping.address === \"string\" ? { address: wire.shipping.address } : {}),\n };\n } else if (wire.shipping === null) {\n customer.shipping = null;\n }\n\n return customer;\n}\n\n/** `openapi.yaml`'s `CheckoutSessionResponse` — what both opening and renewing return. */\nexport interface WireCheckoutSessionResponse {\n public_id: string;\n expires_at: string;\n checkout_url: string;\n}\n\n/**\n * The checkout link both `checkoutSessions.create()` and `subscriptions.renew()` return — shared\n * here rather than in either resource so neither depends on the other.\n */\nexport function deserializeCheckoutSessionResponse(wire: WireCheckoutSessionResponse): CheckoutSessionResponse {\n return {\n publicId: wire.public_id,\n expiresAt: wire.expires_at,\n checkoutUrl: wire.checkout_url,\n };\n}\n","import type { HttpClient } from \"../http/HttpClient.js\";\nimport { bridgeAutoPaging, toPageQuery, type PageParams, type SubscriptionPage } from \"../pagination.js\";\nimport { SubscriptionStatus, type Subscription, type SubscriptionProduct } from \"../models/Subscription.js\";\nimport type {\n CheckoutSessionResponse,\n CreateSubscriptionParams,\n CreateSubscriptionResponse,\n MessageResponse,\n UpdateBillingCycleParams,\n} from \"../models/index.js\";\nimport { assertPathId } from \"../utils/index.js\";\nimport {\n deserializeCheckoutSessionResponse,\n deserializeSubscriptionCustomer,\n serializeCustomerInput,\n type WireCheckoutSessionResponse,\n} from \"./serialization.js\";\n\n/** No trailing slash here; `HttpClient`/`buildUrl` guarantees it (Ticket 2). */\nconst SUBSCRIPTIONS_PATH = \"/api/v1/subscriptions\";\n/** Singular `subscription`, unlike every other subscription route — that is the real wire path (R1). */\nconst RENEW_PATH = \"/api/v1/subscription/renew\";\n\n/** The wire shape `openapi.yaml`'s `SubscriptionProduct` schema sends — a summary, not the full `Product`. */\ninterface WireSubscriptionProduct {\n product_id?: string | null;\n name?: string | null;\n plan_name?: string | null;\n pbp_id?: string | null;\n label?: string | null;\n price?: string | null;\n currency?: string | null;\n}\n\n/**\n * The wire shape `openapi.yaml`'s `Subscription` schema sends. `client` is `unknown` here, not a\n * typed wire interface — {@link deserializeSubscriptionCustomer} (`./serialization.js`) already\n * accepts `unknown` and is best-effort about its shape, so there's no value duplicating that\n * typing here too.\n */\ninterface WireSubscription {\n subscription_id: string;\n status: string;\n is_active: boolean;\n client: unknown;\n // `WireSubscriptionProduct | null`, optional too (found in review): `openapi.yaml`'s\n // Subscription schema has no `required` list at all, the same gap already handled defensively\n // for Product's `vat` (`WireProductVat | null`, also optional) — so an omitted *or* explicitly\n // null `product` key is spec-legal here too, not just a hypothetical.\n product?: WireSubscriptionProduct | null;\n current_period_start: string | null;\n current_period_end: string | null;\n next_billing_cycle: string | null;\n created_at: string;\n}\n\n/** `openapi.yaml`'s `SubscriptionListEnvelope` — `PaginationEnvelope` plus the four extra counts. */\ninterface WireSubscriptionListEnvelope {\n count: number;\n next: string | null;\n previous: string | null;\n total_subscriptions: number;\n active_subscriptions: number;\n due_subscriptions: number;\n inactive_subscriptions: number;\n results: WireSubscription[];\n}\n\n/** `openapi.yaml`'s `CreateSubscriptionResponse` — no field renames, just casing (§06). */\ninterface WireCreateSubscriptionResponse {\n subscription_id: string;\n pbp_id: string;\n /** The wire guarantees this exact const value on every response (openapi.yaml `const: pending_checkout`). */\n status: typeof SubscriptionStatus.PendingCheckout;\n checkout_url: string;\n next_billing_cycle: string | null;\n created_at: string;\n}\n\nfunction deserializeSubscriptionProduct(wire: WireSubscriptionProduct): SubscriptionProduct {\n return {\n productId: wire.product_id ?? null,\n name: wire.name ?? null,\n planName: wire.plan_name ?? null,\n pbpId: wire.pbp_id ?? null,\n label: wire.label ?? null,\n price: wire.price ?? null,\n currency: wire.currency ?? null,\n };\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializeSubscription(wire: WireSubscription): Subscription {\n return {\n subscriptionId: wire.subscription_id,\n status: wire.status,\n isActive: wire.is_active,\n // Renamed from the wire's `client` — SDK Naming Map v1.1 §11 \"Customer boundary\".\n customer: deserializeSubscriptionCustomer(wire.client),\n // `== null` (not `=== null`) is deliberate — same reasoning as Product's `vat` field: catches\n // both an explicit `null` and an entirely omitted `product` key, either of which is spec-legal\n // since `openapi.yaml`'s Subscription schema has no `required` list. The old unconditional call\n // crashed on `deserializeSubscriptionProduct(undefined)` when the key was omitted (found in\n // review, reproduced).\n product: wire.product == null ? null : deserializeSubscriptionProduct(wire.product),\n currentPeriodStart: wire.current_period_start,\n currentPeriodEnd: wire.current_period_end,\n nextBillingCycle: wire.next_billing_cycle,\n createdAt: wire.created_at,\n };\n}\n\n/**\n * Exported for direct unit testing — not part of the SDK's public surface. Unlike\n * {@link import(\"../pagination.js\").deserializePage}, this can't be the generic helper — the four\n * extra counts aren't part of `Page<T>`'s shape at all, so this envelope needs its own mapping.\n */\nexport function deserializeSubscriptionPage(wire: WireSubscriptionListEnvelope): SubscriptionPage<Subscription> {\n return {\n count: wire.count,\n next: wire.next,\n previous: wire.previous,\n totalSubscriptions: wire.total_subscriptions,\n activeSubscriptions: wire.active_subscriptions,\n dueSubscriptions: wire.due_subscriptions,\n inactiveSubscriptions: wire.inactive_subscriptions,\n results: wire.results.map(deserializeSubscription),\n };\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializeCreateSubscriptionResponse(\n wire: WireCreateSubscriptionResponse,\n): CreateSubscriptionResponse {\n return {\n subscriptionId: wire.subscription_id,\n pbpId: wire.pbp_id,\n status: wire.status,\n checkoutUrl: wire.checkout_url,\n nextBillingCycle: wire.next_billing_cycle,\n createdAt: wire.created_at,\n };\n}\n\n/**\n * `client.subscriptions` (SDK-SPEC.md §5, §6, §7; `openapi.yaml` `listSubscriptions`/\n * `retrieveSubscription`/`createSubscription`/`cancelSubscription`/`updateBillingCycle`/\n * `resumeSubscription`/`renewSubscription`).\n *\n * One-time purchases (a billing period whose `intervalType` is `one_time`) appear in `list()` but\n * can't be cancelled, resumed, rescheduled or renewed — those calls throw `ValidationError`.\n */\nexport class SubscriptionsResource {\n readonly #http: HttpClient;\n\n constructor(http: HttpClient) {\n this.#http = http;\n }\n\n /**\n * Lists the seller's subscriptions. Paginated, with four extra status counts alongside the\n * common envelope (SDK-SPEC.md §6).\n */\n async list(params?: PageParams): Promise<SubscriptionPage<Subscription>> {\n const wire = await this.#http.request<WireSubscriptionListEnvelope>({\n method: \"GET\",\n path: SUBSCRIPTIONS_PATH,\n query: toPageQuery(params),\n });\n return deserializeSubscriptionPage(wire);\n }\n\n /**\n * Auto-iterates every subscription across every page, following `next` until it's `null`\n * (SDK-SPEC.md §6). Manual `list({ page, pageSize })` remains available independently.\n */\n autoPaging(params?: PageParams): AsyncIterableIterator<Subscription> {\n return bridgeAutoPaging(() => this.list(params), async (nextUrl) => {\n const wire = await this.#http.request<WireSubscriptionListEnvelope>({ method: \"GET\", path: nextUrl });\n return deserializeSubscriptionPage(wire);\n });\n }\n\n /**\n * Retrieves one of your own subscriptions by id. Built from Swagger's schema; not yet checked\n * against a captured response.\n */\n async retrieve(id: string): Promise<Subscription> {\n // Same guard as customers.retrieve(): \"\" would collapse onto list()'s URL.\n assertPathId(id, \"subscriptions.retrieve\");\n const wire = await this.#http.request<WireSubscription>({\n method: \"GET\",\n path: `${SUBSCRIPTIONS_PATH}/${encodeURIComponent(id)}`,\n });\n return deserializeSubscription(wire);\n }\n\n /**\n * **Legacy** — prefer `checkoutSessions.create()`, which takes up to ten items in one payment\n * and doesn't need a full customer object. Still supported; existing integrations keep working.\n *\n * Creates a subscription in `pending_checkout` state and returns a checkout URL for the buyer\n * to pay (SDK-SPEC.md §5). Redirect the buyer to `checkoutUrl`; the return is **not** proof of\n * payment — learn the real outcome via the `checkout.succeeded`/`checkout.failed` webhooks.\n *\n * `customer.email` identifies the buyer. A buyer may hold only one live recurring subscription\n * per product: a second one on any billing period of the same product throws `ValidationError`.\n * To restart an inactive subscription, use `renew()` rather than creating a new one.\n *\n * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).\n */\n async create(params: CreateSubscriptionParams): Promise<CreateSubscriptionResponse> {\n const wire = await this.#http.request<WireCreateSubscriptionResponse, unknown>({\n method: \"POST\",\n path: SUBSCRIPTIONS_PATH,\n body: {\n pbp_id: params.pbpId,\n return_url: params.returnUrl,\n // Renamed from the wire's `client` — SDK Naming Map v1.1 §11 \"Customer boundary\".\n client: serializeCustomerInput(params.customer),\n },\n });\n return deserializeCreateSubscriptionResponse(wire);\n }\n\n /**\n * Schedules cancellation for the end of the current billing period — **not** immediate\n * (confirmed with backend 2026-08-17; immediate cancellation is a future capability). Status\n * moves to `pending_cancellation`; the subscription stays active until the period ends. Calling\n * it on a subscription already cancelled or pending cancellation returns it unchanged, so a\n * retry by the caller is safe.\n *\n * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).\n */\n async cancel(id: string): Promise<MessageResponse> {\n // \"\", \".\" and \"..\" would POST to a different route (e.g. \"..\" -> /api/v1/cancel/).\n assertPathId(id, \"subscriptions.cancel\");\n // encodeURIComponent, found in review: an unescaped id containing `?`/`#`/`/` would otherwise\n // be parsed as URL structure by buildUrl's `new URL(path, base)`, silently corrupting the\n // path instead of erroring — e.g. `?` truncates everything after it, swallowing `/cancel`\n // into the query string.\n return this.#http.request<MessageResponse>({\n method: \"POST\",\n path: `${SUBSCRIPTIONS_PATH}/${encodeURIComponent(id)}/cancel`,\n });\n }\n\n /**\n * Sets a subscription's next billing date. Collection-level action — the subscription id\n * travels in the body, not the path, mirroring the wire (SDK Naming Map v1.1 §04).\n *\n * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).\n */\n async updateBillingCycle(params: UpdateBillingCycleParams): Promise<MessageResponse> {\n return this.#http.request<MessageResponse, unknown>({\n method: \"POST\",\n path: `${SUBSCRIPTIONS_PATH}/update-billing-cycle`,\n body: {\n subscription_id: params.subscriptionId,\n next_billing_cycle: params.nextBillingCycle,\n },\n });\n }\n\n /**\n * Undoes a scheduled cancellation and returns the subscription to `active`. An already-active\n * subscription is returned unchanged. Once a subscription is `cancelled` there is nothing to\n * resume — use `renew()`.\n *\n * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).\n */\n async resume(id: string): Promise<MessageResponse> {\n assertPathId(id, \"subscriptions.resume\");\n // encodeURIComponent, found in review: same path-corruption risk as cancel() above.\n return this.#http.request<MessageResponse>({\n method: \"POST\",\n path: `${SUBSCRIPTIONS_PATH}/${encodeURIComponent(id)}/resume`,\n });\n }\n\n /**\n * Opens a checkout session for the next payment on one of your own subscriptions, reusing its\n * customer and billing period (or partner-priced item) rather than resubmitting them — how an\n * inactive subscription is restarted. Send the buyer to the returned `checkoutUrl`, and learn\n * the outcome from the `checkout.*` webhooks, matched on `publicId`.\n *\n * A cancelled or archived subscription, or a paid one-time purchase, can't be renewed: that\n * throws `ValidationError`. Not auto-retryable — writes never retry until idempotency ships\n * (SDK-SPEC.md §8, §12).\n */\n async renew(subscriptionId: string): Promise<CheckoutSessionResponse> {\n const wire = await this.#http.request<WireCheckoutSessionResponse, unknown>({\n method: \"POST\",\n path: RENEW_PATH,\n body: { subscription_id: subscriptionId },\n });\n return deserializeCheckoutSessionResponse(wire);\n }\n}\n","import type { HttpClient } from \"../http/HttpClient.js\";\nimport { bridgeAutoPaging, deserializePage, toPageQuery, type Page, type PageParams } from \"../pagination.js\";\nimport type { CreateCustomerParams, Customer, UpdateCustomerParams } from \"../models/index.js\";\nimport { assertPathId } from \"../utils/index.js\";\n\n/** `GET /api/v1/customers/` — no trailing slash here; `HttpClient`/`buildUrl` guarantees it (Ticket 2). */\nconst CUSTOMERS_PATH = \"/api/v1/customers\";\n\n/**\n * The wire shape `openapi.yaml`'s `Customer` schema actually sends — snake_case. Uses `buyer_*`\n * prefixes, not the `client.*` nesting Subscriptions uses — carried through as its own convention,\n * not forced into the customer/client boundary's shape (that boundary is only about the\n * Subscriptions payload's embedded buyer, a genuinely different concept from this resource's own\n * record).\n *\n * `id` corrected to `string` and `address` added (Bug #42, found in review against the live\n * sandbox) — both were wrong in the version originally \"confirmed live 2026-08-18\": that\n * confirmation never actually matched what the API returns, it just went unnoticed until now.\n */\ninterface WireCustomer {\n id: string;\n // Optional, not just nullable, on all four of these (found in review, closing the class #42's\n // address fix opened): openapi.yaml's Customer schema only requires `id`/`created_at` — none of\n // these four are in `required`, and src/generated/schema.ts already reflects that (`?:` on all\n // four). This hand-written interface originally declared `address` the same required-but-wrong\n // way it still declared these three, so an entirely omitted key (spec-legal for any of them)\n // produced `undefined` here, flowing straight into a `Customer` type that promises `string |\n // null`, never `undefined`. Same class of bug as #42 itself: a declared type the wire never\n // actually promised.\n buyer_phone?: string | null;\n buyer_email?: string | null;\n full_name?: string | null;\n address?: string | null;\n created_at: string;\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializeCustomer(wire: WireCustomer): Customer {\n return {\n id: wire.id,\n // `?? null` on all four nullable fields (not a direct pass-through, found in review): catches\n // both an explicit `null` and an entirely omitted key — see the WireCustomer comment above.\n buyerPhone: wire.buyer_phone ?? null,\n buyerEmail: wire.buyer_email ?? null,\n fullName: wire.full_name ?? null,\n address: wire.address ?? null,\n createdAt: wire.created_at,\n };\n}\n\n/**\n * The fields `create()` and `update()` share (SDK) → the wire's write shape. Only keys the caller\n * actually set are sent: on `update()` an omitted field must stay untouched server-side, while\n * `\"\"` is a deliberate clear — so `undefined` is dropped and `\"\"` is passed through as-is.\n *\n * Deliberately never reads `phone` (found in review): TypeScript only checks excess properties on\n * object literals, so `update(id, formState)` compiles even when `formState` carries a phone. The\n * API rejects any phone but the current one, so passing it through would fail the whole update.\n * `create()` adds `phone` itself.\n */\nfunction serializeCustomerFields(params: UpdateCustomerParams): Record<string, unknown> {\n const wire: Record<string, unknown> = {};\n if (params.fullName !== undefined) wire.full_name = params.fullName;\n if (params.email !== undefined) wire.email = params.email;\n if (params.address !== undefined) wire.address = params.address;\n return wire;\n}\n\n/**\n * `client.customers` (SDK-SPEC.md §5, §6; `openapi.yaml` `listCustomers`/`retrieveCustomer`/\n * `createCustomer`/`updateCustomer`). No delete exists on this resource.\n */\nexport class CustomersResource {\n readonly #http: HttpClient;\n\n constructor(http: HttpClient) {\n this.#http = http;\n }\n\n /** Lists the authenticated seller's customers. Paginated (SDK-SPEC.md §6). */\n async list(params?: PageParams): Promise<Page<Customer>> {\n const wire = await this.#http.request<Page<WireCustomer>>({\n method: \"GET\",\n path: CUSTOMERS_PATH,\n query: toPageQuery(params),\n });\n return deserializePage(wire, deserializeCustomer);\n }\n\n /**\n * Auto-iterates every customer across every page, following `next` until it's `null`\n * (SDK-SPEC.md §6). Manual `list({ page, pageSize })` remains available independently — this is\n * additive, not a replacement.\n */\n autoPaging(params?: PageParams): AsyncIterableIterator<Customer> {\n return bridgeAutoPaging(() => this.list(params), async (nextUrl) => {\n const wire = await this.#http.request<Page<WireCustomer>>({ method: \"GET\", path: nextUrl });\n return deserializePage(wire, deserializeCustomer);\n });\n }\n\n /**\n * Retrieves a single customer by id — an opaque prefixed string (e.g. `\"cus_1ce18d624\"`), like\n * `pbp_...` on billing periods, not an integer and not a UUID (Bug #42 corrected the previously\n * wrong `number` type/doc claim here).\n */\n async retrieve(id: string): Promise<Customer> {\n // Found in review of the string-id change (#42): an empty id isn't a path-corruption case\n // like cancel()/resume()'s \"\" (which builds a genuinely invalid, loudly-404ing double-slash\n // path) — `${CUSTOMERS_PATH}/${encodeURIComponent(\"\")}` collapses to exactly `list()`'s own\n // URL, so the request silently succeeds against the wrong endpoint. Its 200 pagination\n // envelope then feeds straight into deserializeCustomer, which reads wire.id/wire.buyer_email/\n // etc. off an object with none of them and returns a Customer of all-undefined fields with no\n // error at all — surfacing as a confusing null-pointer far from this call, not here. `id:\n // string` makes an empty id ordinary reachable input (`retrieve(req.params.id)`,\n // `retrieve(user.customerId ?? \"\")`) in a way `id: number` never could (no number stringifies\n // to \"\").\n assertPathId(id, \"customers.retrieve\");\n\n // encodeURIComponent — same path-corruption risk as subscriptions.cancel()/resume(), now that\n // id is a real caller-supplied string rather than a number.\n const wire = await this.#http.request<WireCustomer>({\n method: \"GET\",\n path: `${CUSTOMERS_PATH}/${encodeURIComponent(id)}`,\n });\n return deserializeCustomer(wire);\n }\n\n /**\n * Records a customer on the seller's account without opening a subscription. `email` identifies\n * the buyer and is required; `phone` is optional. The name and address are the seller's own copy\n * and aren't shared with other sellers. Pass the returned `id` to `checkoutSessions.create()` as\n * `customerId` to send the buyer straight to payment.\n *\n * An email or phone the seller already holds updates that existing customer instead of creating\n * a second one (the API answers `200` rather than `201`; both resolve to the `Customer` here).\n * That makes this call safe for the caller to retry — but, like every write, the SDK never\n * retries it automatically (SDK-SPEC.md §8, §12).\n */\n async create(params: CreateCustomerParams): Promise<Customer> {\n const wire = await this.#http.request<WireCustomer, unknown>({\n method: \"POST\",\n path: CUSTOMERS_PATH,\n body: {\n ...serializeCustomerFields(params),\n ...(params.phone !== undefined ? { phone: params.phone } : {}),\n },\n });\n return deserializeCustomer(wire);\n }\n\n /**\n * Updates the seller's copy of a customer's name, email or address. Send only the fields you're\n * changing; `\"\"` clears a field. The phone can't be changed.\n *\n * Not auto-retryable — writes never retry until idempotency ships (SDK-SPEC.md §8, §12).\n */\n async update(id: string, params: UpdateCustomerParams): Promise<Customer> {\n // Same guard as retrieve(): a bad id would send the PATCH to the wrong endpoint rather than\n // failing on the intended one.\n assertPathId(id, \"customers.update\");\n\n const wire = await this.#http.request<WireCustomer, unknown>({\n method: \"PATCH\",\n path: `${CUSTOMERS_PATH}/${encodeURIComponent(id)}`,\n body: serializeCustomerFields(params),\n });\n return deserializeCustomer(wire);\n }\n}\n","import type { HttpClient } from \"../http/HttpClient.js\";\nimport type {\n CheckoutItemInput,\n CheckoutLineItem,\n CheckoutSession,\n CheckoutSessionResponse,\n CreateCheckoutSessionParams,\n} from \"../models/index.js\";\nimport { assertPathId } from \"../utils/index.js\";\nimport { deserializeCheckoutSessionResponse, type WireCheckoutSessionResponse } from \"./serialization.js\";\n\n/** No trailing slash here; `HttpClient`/`buildUrl` guarantees it (Ticket 2). */\nconst CHECKOUT_SESSIONS_PATH = \"/api/v1/checkout-sessions\";\n\n/**\n * `openapi.yaml`'s `CheckoutLineItem`, confirmed against a captured `GET` response (2026-10-05).\n * Keys absent from a captured item are optional here, and the deserializer turns them into `null`.\n */\ninterface WireCheckoutLineItem {\n name: string;\n amount: string;\n pbp_id?: string | null;\n currency: string;\n vat_type?: string | null;\n vat_percentage?: string | null;\n discount_amount?: string | null;\n interval_type: string;\n interval_count: number;\n display_label: string;\n current_period_end?: string | null;\n extends_to?: string | null;\n next_payment_due?: string | null;\n /** Catalogue items only. */\n image_urls?: string[];\n /** Partner-priced items only. */\n plan_name?: string | null;\n /** The subscription this line pays for; on every item. Absent only on pre-release sessions. Missing from Swagger. */\n subscription_id?: string;\n}\n\ninterface WireCheckoutSeller {\n id: string;\n phone: string;\n business_logo?: string | null;\n business_name: string;\n}\n\ninterface WireCheckoutSession {\n public_id: string;\n line_items?: WireCheckoutLineItem[];\n customer_id?: string | null;\n seller_details: WireCheckoutSeller;\n return_url: string;\n expires_at: string;\n completed_at?: string | null;\n is_expired: boolean;\n session_type?: string | null;\n}\n\nfunction deserializeLineItem(wire: WireCheckoutLineItem): CheckoutLineItem {\n return {\n name: wire.name,\n amount: wire.amount,\n pbpId: wire.pbp_id ?? null,\n currency: wire.currency,\n vatType: wire.vat_type ?? null,\n vatPercentage: wire.vat_percentage ?? null,\n discountAmount: wire.discount_amount ?? null,\n intervalType: wire.interval_type,\n intervalCount: wire.interval_count,\n displayLabel: wire.display_label,\n currentPeriodEnd: wire.current_period_end ?? null,\n extendsTo: wire.extends_to ?? null,\n nextPaymentDue: wire.next_payment_due ?? null,\n // Each kind carries one of these and not the other, so they stay absent rather than null.\n ...(wire.image_urls !== undefined ? { imageUrls: wire.image_urls } : {}),\n ...(wire.plan_name !== undefined ? { planName: wire.plan_name } : {}),\n // Every item carries it; absent (not null) only on sessions created before the API added it.\n ...(wire.subscription_id !== undefined ? { subscriptionId: wire.subscription_id } : {}),\n };\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializeCheckoutSession(wire: WireCheckoutSession): CheckoutSession {\n return {\n publicId: wire.public_id,\n lineItems: (wire.line_items ?? []).map(deserializeLineItem),\n customerId: wire.customer_id ?? null,\n sellerDetails: {\n id: wire.seller_details.id,\n phone: wire.seller_details.phone,\n businessLogo: wire.seller_details.business_logo ?? null,\n businessName: wire.seller_details.business_name,\n },\n returnUrl: wire.return_url,\n expiresAt: wire.expires_at,\n completedAt: wire.completed_at ?? null,\n isExpired: wire.is_expired,\n sessionType: wire.session_type ?? null,\n };\n}\n\n/**\n * A {@link CheckoutItemInput} (SDK) → the wire's item shape. Only one of the two forms is sent:\n * catalogue (`pbp_id` alone) or partner-priced (`name`/`amount`/`interval_type`/`interval_count`).\n */\nfunction serializeItem(item: CheckoutItemInput): Record<string, unknown> {\n if (item.pbpId !== undefined) return { pbp_id: item.pbpId };\n return {\n name: item.name,\n amount: item.amount,\n interval_type: item.intervalType,\n interval_count: item.intervalCount,\n };\n}\n\n/**\n * `client.checkoutSessions` (SDK-SPEC.md §5; `openapi.yaml` `createCheckoutSession`/\n * `retrieveCheckoutSession`). The recommended way to collect payment: up to ten items in one\n * checkout, replacing the legacy `subscriptions.create()`.\n */\nexport class CheckoutSessionsResource {\n readonly #http: HttpClient;\n\n constructor(http: HttpClient) {\n this.#http = http;\n }\n\n /**\n * Opens a checkout session for one to ten items and returns a URL for the buyer to pay. Prices\n * are snapshotted now, so a plan edited later can't change what the buyer was shown. Redirect\n * the buyer to `checkoutUrl`; the return to `returnUrl` is **not** proof of payment — learn the\n * outcome from `checkout.succeeded`/`checkout.failed`, matched on `publicId` (`session_id`).\n *\n * The API's one rate-limited endpoint: 20 sessions a minute per account. Past that it throws\n * `RateLimitError` with `retryAfter` set. Never retried automatically — writes don't retry until\n * idempotency ships (SDK-SPEC.md §8, §12) — so open a session when the buyer commits to paying,\n * not on page load.\n */\n async create(params: CreateCheckoutSessionParams): Promise<CheckoutSessionResponse> {\n const wire = await this.#http.request<WireCheckoutSessionResponse, unknown>({\n method: \"POST\",\n path: CHECKOUT_SESSIONS_PATH,\n body: {\n items: params.items.map(serializeItem),\n return_url: params.returnUrl,\n ...(params.customerId !== undefined ? { customer_id: params.customerId } : {}),\n },\n });\n return deserializeCheckoutSessionResponse(wire);\n }\n\n /**\n * Reads one of your own open sessions: its line items, customer, seller and expiry. Once paid,\n * expired, unknown or someone else's, it throws `NotFoundError`.\n */\n async retrieve(id: string): Promise<CheckoutSession> {\n assertPathId(id, \"checkoutSessions.retrieve\");\n const wire = await this.#http.request<WireCheckoutSession>({\n method: \"GET\",\n path: `${CHECKOUT_SESSIONS_PATH}/${encodeURIComponent(id)}`,\n });\n return deserializeCheckoutSession(wire);\n }\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\nimport type { HttpClient } from \"../http/HttpClient.js\";\nimport type {\n CreateWebhookParams,\n ReplaceWebhookParams,\n UpdateWebhookParams,\n Webhook,\n WebhookSecret,\n} from \"../models/index.js\";\nimport { assertPathId } from \"../utils/index.js\";\n\n/**\n * `client.webhooks` (SDK-SPEC.md §5, §9). Two jobs on one object:\n *\n * - **`verify()`** makes **no** network call and stores no secret — the host application passes\n * its own signing secret into every call. It checks an inbound delivery genuinely came from SUQO\n * and hasn't been tampered with or replayed; it does **not** parse the event body (see\n * `models/WebhookEvent.ts` for why the event types stay snake_case).\n * - **`list`/`create`/`retrieve`/`replace`/`update`/`delete`/`retrieveSecret`/`testDelivery`**\n * call the API to manage which endpoint receives which event. They need the client's key, and\n * work before KYC verification.\n *\n * @packageDocumentation\n */\n\n/** No trailing slash here; `HttpClient`/`buildUrl` guarantees it (Ticket 2). */\nconst WEBHOOKS_PATH = \"/api/v1/webhooks\";\n/** Sibling routes under `/webhooks/` that an id must never collide with. */\nconst RESERVED_SEGMENTS = [\"secret\"] as const;\n\ninterface WireWebhook {\n id: string;\n event: string;\n endpoint_url: string;\n is_active: boolean;\n created_at: string;\n}\n\n/** Exported for direct unit testing — not part of the SDK's public surface. */\nexport function deserializeWebhook(wire: WireWebhook): Webhook {\n return {\n id: wire.id,\n event: wire.event,\n endpointUrl: wire.endpoint_url,\n isActive: wire.is_active,\n createdAt: wire.created_at,\n };\n}\n\n/** Only keys the caller set are sent, so `update()` leaves everything else untouched. */\nfunction serializeWebhookWrite(params: UpdateWebhookParams): Record<string, unknown> {\n const wire: Record<string, unknown> = {};\n if (params.event !== undefined) wire.event = params.event;\n if (params.endpointUrl !== undefined) wire.endpoint_url = params.endpointUrl;\n if (params.isActive !== undefined) wire.is_active = params.isActive;\n return wire;\n}\n\n/** Options accepted by {@link WebhooksResource.verify}. */\nexport interface VerifyWebhookOptions {\n /**\n * The **raw, unparsed** request body — exactly the bytes SUQO sent, before any JSON-parsing\n * middleware touches it. SDK-SPEC.md §9 rule 1: verifying against a parsed-then-reserialized\n * body is the single most common cause of \"signature never matches\" — whitespace, key order,\n * and number formatting can all change silently on a round-trip through `JSON.parse`/\n * `JSON.stringify`, even though the *meaning* of the body didn't change at all.\n */\n rawBody: string | Buffer;\n /** The `X-SUQO-Signature` header value, verbatim — e.g. `\"sha256=<hex>\"`. */\n signature: string;\n /** The `X-SUQO-Timestamp` header value, verbatim — Unix seconds, as a string. */\n timestamp: string;\n /** The webhook signing secret, provided by the host application. Never logged, never stored. */\n secret: string;\n /**\n * Maximum age, in seconds, before a delivery is rejected as stale (defeats replay — SDK-SPEC.md\n * §9 rule 3). Default 300 (~5 minutes).\n */\n toleranceSec?: number;\n}\n\nconst DEFAULT_TOLERANCE_SEC = 300;\nconst SIGNATURE_PREFIX = \"sha256=\";\n/**\n * A hex-encoded SHA-256 digest is always exactly 64 hex characters (32 bytes) — the `{64}` is\n * deliberate, not just `+`. `+` alone only checks *which* characters are used, not *how many*;\n * a 3-character string like `\"abc\"` would pass a `+`-based check despite `Buffer.from(\"abc\",\n * \"hex\")` still silently truncating to 1 byte, exactly the failure mode this check exists to\n * prevent (found in review: the `+` version let that through, and only \"worked\" by accident\n * because a separate, later length-equality check happened to catch the resulting mismatch —\n * this regex is now the thing that actually guarantees it, not a lucky side effect of something\n * else).\n */\nconst HEX_DIGEST_RE = /^[0-9a-f]{64}$/i;\n\nexport class WebhooksResource {\n readonly #http: HttpClient;\n\n constructor(http: HttpClient) {\n this.#http = http;\n }\n\n /** Every webhook registered by your account. Not paginated — the API returns them all. */\n async list(): Promise<Webhook[]> {\n const wire = await this.#http.request<WireWebhook[]>({ method: \"GET\", path: WEBHOOKS_PATH });\n return wire.map(deserializeWebhook);\n }\n\n /**\n * Subscribes an `https` endpoint to one event. An account holds at most one webhook per event,\n * and the endpoint must resolve only to public addresses — either failing throws\n * `ValidationError`. Not auto-retryable (SDK-SPEC.md §8, §12).\n */\n async create(params: CreateWebhookParams): Promise<Webhook> {\n const wire = await this.#http.request<WireWebhook, unknown>({\n method: \"POST\",\n path: WEBHOOKS_PATH,\n body: serializeWebhookWrite(params),\n });\n return deserializeWebhook(wire);\n }\n\n /** Retrieves one of your own webhooks by id (`whk_…`). */\n async retrieve(id: string): Promise<Webhook> {\n assertPathId(id, \"webhooks.retrieve\", RESERVED_SEGMENTS);\n const wire = await this.#http.request<WireWebhook>({\n method: \"GET\",\n path: `${WEBHOOKS_PATH}/${encodeURIComponent(id)}`,\n });\n return deserializeWebhook(wire);\n }\n\n /**\n * Overwrites a webhook's event, endpoint and active flag (`PUT`). `event` and `endpointUrl` are\n * both required; to change one field on its own, use {@link WebhooksResource.update}. Not\n * auto-retryable (SDK-SPEC.md §8, §12).\n */\n async replace(id: string, params: ReplaceWebhookParams): Promise<Webhook> {\n assertPathId(id, \"webhooks.replace\", RESERVED_SEGMENTS);\n const wire = await this.#http.request<WireWebhook, unknown>({\n method: \"PUT\",\n path: `${WEBHOOKS_PATH}/${encodeURIComponent(id)}`,\n body: serializeWebhookWrite(params),\n });\n return deserializeWebhook(wire);\n }\n\n /**\n * Changes only the fields you send (`PATCH`) — e.g. `{ isActive: false }` pauses deliveries\n * without deleting the webhook. Not auto-retryable (SDK-SPEC.md §8, §12).\n */\n async update(id: string, params: UpdateWebhookParams): Promise<Webhook> {\n assertPathId(id, \"webhooks.update\", RESERVED_SEGMENTS);\n const wire = await this.#http.request<WireWebhook, unknown>({\n method: \"PATCH\",\n path: `${WEBHOOKS_PATH}/${encodeURIComponent(id)}`,\n body: serializeWebhookWrite(params),\n });\n return deserializeWebhook(wire);\n }\n\n /** Removes a webhook. Past delivery records are kept for debugging. Not auto-retryable (SDK-SPEC.md §8, §12). */\n async delete(id: string): Promise<void> {\n assertPathId(id, \"webhooks.delete\", RESERVED_SEGMENTS);\n await this.#http.request<undefined>({\n method: \"DELETE\",\n path: `${WEBHOOKS_PATH}/${encodeURIComponent(id)}`,\n });\n }\n\n /**\n * Returns the account's signing secret — the `secret` to pass to {@link WebhooksResource.verify}.\n * The API creates it on the first call; it can't be rotated through the API. Treat it like a\n * password: never log it.\n */\n async retrieveSecret(): Promise<WebhookSecret> {\n const wire = await this.#http.request<{ signing_secret: string }>({\n method: \"GET\",\n path: `${WEBHOOKS_PATH}/secret`,\n });\n return { signingSecret: wire.signing_secret };\n }\n\n /**\n * Queues a signed test delivery to the webhook's endpoint so you can check your receiver. It\n * resolves once the job is queued; the delivery itself arrives asynchronously. Note a test\n * delivery's body differs from a real event's (fields under `data`) — use it to check\n * `verify()`, not your payload parsing. Not auto-retryable (SDK-SPEC.md §8, §12).\n */\n async testDelivery(id: string): Promise<void> {\n assertPathId(id, \"webhooks.testDelivery\", RESERVED_SEGMENTS);\n await this.#http.request<unknown>({\n method: \"POST\",\n path: `${WEBHOOKS_PATH}/${encodeURIComponent(id)}/test-delivery`,\n });\n }\n\n /**\n * Verifies an inbound webhook delivery's signature. Returns `false` for any failure mode —\n * malformed signature, expired timestamp, or a genuine mismatch — never throws, so a caller\n * never needs a `try`/`catch` just to check a delivery.\n *\n * @example\n * ```ts\n * // Express: mount express.raw() on this route so req.body is a Buffer, not parsed JSON.\n * const ok = suqo.webhooks.verify({\n * rawBody: req.body,\n * signature: req.header(\"X-SUQO-Signature\")!,\n * timestamp: req.header(\"X-SUQO-Timestamp\")!,\n * secret: process.env.SUQO_WEBHOOK_SECRET!,\n * });\n * ```\n */\n verify(options: VerifyWebhookOptions): boolean {\n const { rawBody, signature, timestamp, secret, toleranceSec = DEFAULT_TOLERANCE_SEC } = options;\n\n // The types say these are always strings (or a Buffer for rawBody), but that's only a\n // compile-time promise — a caller reading a header via `req.header(...)!` (the exact pattern\n // this class's own TSDoc example recommends) gets `string | undefined` at runtime, and the\n // `!` doesn't make the value real if the header is genuinely missing. Without this guard,\n // a missing header crashed here instead of returning the documented `false` (found in\n // review, reproduced: undefined signature/timestamp/rawBody each threw a raw TypeError).\n if (typeof signature !== \"string\" || typeof timestamp !== \"string\" || typeof secret !== \"string\") {\n return false;\n }\n if (typeof rawBody !== \"string\" && !Buffer.isBuffer(rawBody)) {\n return false;\n }\n\n if (!signature.startsWith(SIGNATURE_PREFIX)) return false;\n const providedHex = signature.slice(SIGNATURE_PREFIX.length);\n // Buffer.from(str, \"hex\") silently truncates at the first invalid hex character instead of\n // throwing — checking the format explicitly first means a malformed signature is rejected\n // for being malformed, not accidentally passed through as a shorter, wrong-length buffer.\n if (!HEX_DIGEST_RE.test(providedHex)) return false;\n\n // `Number(\"\")` is 0, not NaN — an empty timestamp must not be treated as epoch 0, which would\n // always fail the freshness check anyway here, but the intent is \"reject explicitly,\" not\n // \"happen to fail for an unrelated reason.\"\n if (timestamp.trim().length === 0) return false;\n const timestampSeconds = Number(timestamp);\n if (!Number.isFinite(timestampSeconds)) return false;\n\n const nowSeconds = Date.now() / 1000;\n if (Math.abs(nowSeconds - timestampSeconds) > toleranceSec) return false;\n\n const expectedHex = createHmac(\"sha256\", secret)\n .update(`${timestamp}.`)\n .update(rawBody)\n .digest(\"hex\");\n\n const provided = Buffer.from(providedHex, \"hex\");\n const expected = Buffer.from(expectedHex, \"hex\");\n // timingSafeEqual throws on mismatched lengths rather than returning false — checked\n // explicitly first, both to avoid the throw and because the length check itself doesn't leak\n // anything meaningful (the correct length is public: always 32 bytes for SHA-256).\n if (provided.length !== expected.length) return false;\n\n return timingSafeEqual(provided, expected);\n }\n}\n","import { SdkConfig } from \"./config/index.js\";\nimport type { SuqoEnvironment } from \"./config/index.js\";\nimport { HttpClient } from \"./http/HttpClient.js\";\nimport {\n ProductsResource,\n SubscriptionsResource,\n CustomersResource,\n CheckoutSessionsResource,\n WebhooksResource,\n} from \"./resources/index.js\";\n\n/** Options accepted by {@link SuqoClient}'s constructor (SDK-SPEC.md §2, §4; addendum §5). */\nexport interface SuqoClientOptions {\n /** The seller's API key. Its prefix determines sandbox vs. live — see SDK-SPEC.md §2. */\n apiKey: string;\n /**\n * Optional explicit override. If set AND it disagrees with the key's inferred environment, the\n * constructor throws `SuqoConfigError`. Normally omit this.\n */\n baseUrl?: string;\n /**\n * Per-client default request timeout in milliseconds; per-call override also allowed by\n * `http.ts` (Ticket 2). Default 30_000. Named `timeout`, not `timeoutMs` — per SDK Naming Map\n * v1.1, SDK-surface fields drop the `Ms` suffix.\n */\n timeout?: number;\n /** Max retry attempts for idempotent reads (reads only — writes are never retried, SDK-SPEC.md §8, §12). Default 2. */\n maxRetries?: number;\n /** Advanced: custom undici dispatcher for connection-pool tuning, passed through opaquely (Ticket 2). */\n dispatcher?: unknown;\n}\n\n/**\n * The SUQO SDK client (SDK-SPEC.md §5).\n *\n * ```ts\n * const suqo = new SuqoClient({ apiKey: process.env.SUQO_API_KEY! });\n * ```\n *\n * The environment (sandbox vs. live) is inferred automatically from the key's prefix — nothing\n * else to configure in the common case (SDK-SPEC.md §2). Construction throws `SuqoConfigError`\n * immediately on a malformed key, or on a `baseUrl` override that disagrees with the key.\n *\n * Every resource shares this one instance's `HttpClient` — same `baseUrl`/`apiKey`/`timeout`/\n * `maxRetries` for every call, regardless of which resource makes it. `webhooks.verify()` is the\n * one method that makes no network call (SDK-SPEC.md §9).\n */\nexport class SuqoClient {\n readonly #config: SdkConfig;\n\n /** Browse the seller's active products (SDK-SPEC.md §5, §6). The only resource that works pre-KYC. */\n readonly products: ProductsResource;\n /** Create, list, and manage subscriptions (SDK-SPEC.md §5, §6, §7). */\n readonly subscriptions: SubscriptionsResource;\n /** List, retrieve, create and update the seller's customers (SDK-SPEC.md §5, §6). */\n readonly customers: CustomersResource;\n /** Open and read checkout sessions — the recommended way to collect payment (SDK-SPEC.md §5). */\n readonly checkoutSessions: CheckoutSessionsResource;\n /**\n * Manage webhook registrations, and verify inbound deliveries (SDK-SPEC.md §5, §9). `verify()`\n * makes no network call; the management methods do.\n */\n readonly webhooks: WebhooksResource;\n\n constructor(options: SuqoClientOptions) {\n this.#config = new SdkConfig(options);\n const http = new HttpClient(this.#config);\n this.products = new ProductsResource(http);\n this.subscriptions = new SubscriptionsResource(http);\n this.customers = new CustomersResource(http);\n this.checkoutSessions = new CheckoutSessionsResource(http);\n this.webhooks = new WebhooksResource(http);\n }\n\n /** `\"sandbox\" | \"live\"` — inferred from the key prefix, never selected explicitly (SDK-SPEC.md §2). */\n get environment(): SuqoEnvironment {\n return this.#config.environment;\n }\n\n /** The resolved base URL this client sends requests to. */\n get baseUrl(): string {\n return this.#config.baseUrl;\n }\n\n /** The effective request timeout in milliseconds (default 30_000). */\n get timeout(): number {\n return this.#config.timeout;\n }\n\n /** The effective max retry count for idempotent reads (default 2). */\n get maxRetries(): number {\n return this.#config.maxRetries;\n }\n\n /** Redacts the key so it never appears in `JSON.stringify` output (SDK-SPEC.md §4). */\n toJSON(): Record<string, unknown> {\n return this.#config.toJSON();\n }\n\n /** Redacts the key so it never appears in `util.inspect`/`console.log` output (SDK-SPEC.md §4). */\n [Symbol.for(\"nodejs.util.inspect.custom\")](): Record<string, unknown> {\n return this.toJSON();\n }\n}\n","/**\n * SDK entry point — the single, complete public export surface (SDK-SPEC.md §5).\n * Nothing outside this file's exports is part of the public contract.\n *\n * @packageDocumentation\n */\n\n/** SDK version, stamped into request headers (keep in sync with package.json). */\nexport const VERSION = \"2.1.0\";\n\nexport {\n SuqoError,\n SuqoConfigError,\n AuthenticationError,\n KycRequiredError,\n PermissionDeniedError,\n ValidationError,\n NotFoundError,\n RateLimitError,\n ServerError,\n NetworkError,\n mapHttpError,\n type SuqoErrorOptions,\n type KycRequiredErrorOptions,\n type ValidationErrorOptions,\n type FieldErrors,\n type RateLimitErrorOptions,\n type HttpErrorInput,\n} from \"./errors/index.js\";\n\nexport { SuqoClient, type SuqoClientOptions } from \"./client.js\";\nexport type { SuqoEnvironment } from \"./config/index.js\";\n\nexport {\n bridgeAutoPaging,\n deserializePage,\n listAll,\n toPageQuery,\n type Page,\n type PageParams,\n type SubscriptionPage,\n type SubscriptionStatusCounts,\n} from \"./pagination.js\";\n\nexport {\n SubscriptionStatus,\n type Product,\n type ProductVat,\n type ProductImage,\n type Offer,\n type Plan,\n type BillingPeriod,\n type Subscription,\n type SubscriptionProduct,\n type SubscriptionCustomer,\n type SubscriptionCustomerBilling,\n type SubscriptionCustomerShipping,\n type CustomerInput,\n type CustomerInputBilling,\n type CustomerInputShipping,\n type Customer,\n type CreateCustomerParams,\n type UpdateCustomerParams,\n type CatalogueItemInput,\n type PartnerPricedItemInput,\n type CheckoutItemInput,\n type CreateCheckoutSessionParams,\n type CheckoutSessionResponse,\n type CheckoutLineItem,\n type CheckoutSeller,\n type CheckoutSession,\n type Webhook,\n type CreateWebhookParams,\n type ReplaceWebhookParams,\n type UpdateWebhookParams,\n type WebhookSecret,\n type CreateSubscriptionParams,\n type CreateSubscriptionResponse,\n type UpdateBillingCycleParams,\n type MessageResponse,\n type CheckoutSucceededEvent,\n type CheckoutFailedEvent,\n type SubscriptionStatusChangedEvent,\n type ApiKeyCreatedEvent,\n type ApiKeyDeletedEvent,\n type ApiKeyExpiredEvent,\n type ApiKeyExpiringSoonEvent,\n type WebhookEvent,\n type WebhookEventType,\n} from \"./models/index.js\";\n\nexport type { VerifyWebhookOptions } from \"./resources/webhooks.js\";\n\n// ProductsResource/SubscriptionsResource/CustomersResource/WebhooksResource are intentionally NOT\n// exported here — consumers reach them through suqo.products/.subscriptions/.customers/.webhooks,\n// never by constructing one directly (SDK-SPEC.md §5's public surface never shows a resource\n// class being constructed).\n"]}
|