payweave 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +272 -0
- package/dist/_tsup-dts-rollup.d.ts +19470 -0
- package/dist/chunk-4R5OGOCC.js +94 -0
- package/dist/chunk-4R5OGOCC.js.map +1 -0
- package/dist/chunk-535Q3GUN.js +175 -0
- package/dist/chunk-535Q3GUN.js.map +1 -0
- package/dist/chunk-67NRYGRC.js +192 -0
- package/dist/chunk-67NRYGRC.js.map +1 -0
- package/dist/chunk-CGQ73I4I.js +568 -0
- package/dist/chunk-CGQ73I4I.js.map +1 -0
- package/dist/chunk-CJEYDHY6.js +18 -0
- package/dist/chunk-CJEYDHY6.js.map +1 -0
- package/dist/chunk-CR63JAAS.js +3 -0
- package/dist/chunk-CR63JAAS.js.map +1 -0
- package/dist/chunk-E633MKVX.js +1507 -0
- package/dist/chunk-E633MKVX.js.map +1 -0
- package/dist/chunk-FBPOCXRZ.js +1135 -0
- package/dist/chunk-FBPOCXRZ.js.map +1 -0
- package/dist/chunk-HTRGMZFH.js +267 -0
- package/dist/chunk-HTRGMZFH.js.map +1 -0
- package/dist/chunk-IUVGM3K7.js +765 -0
- package/dist/chunk-IUVGM3K7.js.map +1 -0
- package/dist/chunk-JD4OZHRI.js +326 -0
- package/dist/chunk-JD4OZHRI.js.map +1 -0
- package/dist/chunk-NV3MZF7L.js +139 -0
- package/dist/chunk-NV3MZF7L.js.map +1 -0
- package/dist/chunk-NXQBP35U.js +13 -0
- package/dist/chunk-NXQBP35U.js.map +1 -0
- package/dist/chunk-QJHXDZYC.js +412 -0
- package/dist/chunk-QJHXDZYC.js.map +1 -0
- package/dist/chunk-TWZK62TZ.js +83 -0
- package/dist/chunk-TWZK62TZ.js.map +1 -0
- package/dist/cli/index.js +35381 -0
- package/dist/core/index.d.ts +85 -0
- package/dist/core/index.js +6 -0
- package/dist/core/index.js.map +1 -0
- package/dist/db/drizzle/index.d.ts +6 -0
- package/dist/db/drizzle/index.js +1532 -0
- package/dist/db/drizzle/index.js.map +1 -0
- package/dist/db/index.d.ts +43 -0
- package/dist/db/index.js +3 -0
- package/dist/db/index.js.map +1 -0
- package/dist/db/mongodb/index.d.ts +3 -0
- package/dist/db/mongodb/index.js +934 -0
- package/dist/db/mongodb/index.js.map +1 -0
- package/dist/db/mysql/index.d.ts +1 -0
- package/dist/db/mysql/index.js +12 -0
- package/dist/db/mysql/index.js.map +1 -0
- package/dist/db/postgres/index.d.ts +5 -0
- package/dist/db/postgres/index.js +791 -0
- package/dist/db/postgres/index.js.map +1 -0
- package/dist/db/prisma/index.d.ts +1 -0
- package/dist/db/prisma/index.js +12 -0
- package/dist/db/prisma/index.js.map +1 -0
- package/dist/db/sqlite/index.d.ts +5 -0
- package/dist/db/sqlite/index.js +750 -0
- package/dist/db/sqlite/index.js.map +1 -0
- package/dist/express/index.d.ts +1 -0
- package/dist/express/index.js +3 -0
- package/dist/express/index.js.map +1 -0
- package/dist/fastify/index.d.ts +1 -0
- package/dist/fastify/index.js +3 -0
- package/dist/fastify/index.js.map +1 -0
- package/dist/flutterwave/index.d.ts +27 -0
- package/dist/flutterwave/index.js +9 -0
- package/dist/flutterwave/index.js.map +1 -0
- package/dist/index.d.ts +85 -0
- package/dist/index.js +3677 -0
- package/dist/index.js.map +1 -0
- package/dist/next/index.d.ts +1 -0
- package/dist/next/index.js +3 -0
- package/dist/next/index.js.map +1 -0
- package/dist/paystack/index.d.ts +33 -0
- package/dist/paystack/index.js +9 -0
- package/dist/paystack/index.js.map +1 -0
- package/dist/products/index.d.ts +22 -0
- package/dist/products/index.js +7 -0
- package/dist/products/index.js.map +1 -0
- package/dist/testing/index.d.ts +11 -0
- package/dist/testing/index.js +69 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/unified/index.d.ts +41 -0
- package/dist/unified/index.js +6 -0
- package/dist/unified/index.js.map +1 -0
- package/dist/webhooks/index.d.ts +8 -0
- package/dist/webhooks/index.js +8 -0
- package/dist/webhooks/index.js.map +1 -0
- package/package.json +164 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/webhooks/dispatch.ts","../src/stripe/form-encoding.ts","../src/stripe/http-options.ts","../src/stripe/types.ts","../src/stripe/schemas/checkout-sessions.ts","../src/stripe/resources/checkout-sessions.ts","../src/stripe/schemas/customers.ts","../src/stripe/resources/customers.ts","../src/stripe/schemas/payment-intents.ts","../src/stripe/resources/payment-intents.ts","../src/stripe/schemas/prices.ts","../src/stripe/resources/prices.ts","../src/stripe/schemas/products.ts","../src/stripe/resources/products.ts","../src/stripe/schemas/refunds.ts","../src/stripe/resources/refunds.ts","../src/stripe/schemas/subscription-items.ts","../src/stripe/resources/subscription-items.ts","../src/stripe/schemas/subscriptions.ts","../src/stripe/resources/subscriptions.ts","../src/stripe/schemas/webhook-endpoints.ts","../src/stripe/resources/webhook-endpoints.ts","../src/stripe/client.ts","../src/products/sync.ts","../src/products/usage.ts","../src/index.ts"],"names":["z","bodyIfNonEmpty","customUnitAmountInput","recurring","plan","price","subscription","inclusion"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA2EA,IAAM,sBAAA,GAAyD;AAAA,EAC7D,EAAE,UAAA,EAAY,sBAAA,EAAwB,QAAA,EAAU,UAAA,EAAW;AAAA,EAC3D,EAAE,UAAA,EAAY,YAAA,EAAc,QAAA,EAAU,aAAA,EAAe,oBAAoB,IAAA,EAAK;AAAA,EAC9E,EAAE,UAAA,EAAY,uBAAA,EAAyB,QAAA,EAAU,aAAA,EAAe,oBAAoB,IAAA,EAAK;AAAA,EACzF,EAAE,UAAA,EAAY,kBAAA,EAAoB,QAAA,EAAU,QAAA;AAC9C,CAAA;AAEA,IAAM,kBAAA,GAAqB,uBAAuB,GAAA,CAAI,CAAC,SAAS,IAAA,CAAK,UAAU,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA;AAc1F,SAAS,sBAAsB,OAAA,EAA0C;AACvE,EAAA,MAAM,Q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GACrB;AAEA,EAAA,MAAM,MAAA,GAAS;AAAA,IACb,WAAW,QAAA,CAAS,SAAA;AAAA,IACpB,iBAAiB,QAAA,CAAS,eAAA;AAAA,IAC1B,aAAa,QAAA,CAAS,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOtB,QAAA,EAAU,qBAAA,CAAsB,QAAA,EAAU,cAAc,CAAA;AAAA,IACxD,UAAU,OAAA,CAAQ,QAAA;AAAA,IAClB,QAAQ,OAAA,CAAQ,MAAA;AAAA,IAChB,SAAS,OAAA,CAAQ,OAAA;AAAA,IACjB,WAAW,OAAA,CAAQ,SAAA;AAAA,IACnB,OAAO,OAAA,CAAQ,KAAA;AAAA,IACf,YAAA;AAAA;AAAA,IAEA,UAAU,QAAA,CAAS,QAAA;AAAA,IACnB,UAAU,QAAA,CAAS,QAAA;AAAA,IACnB,SAAA,EAAW,CAAC,KAAA,KAAiC,SAAA,CAAiB,gBAAgB,KAAK,CAAA;AAAA;AAAA,IAEnF,IAAA,EAAM,MAAM,IAAA,CAAY,cAAc,CAAA;AAAA;AAAA,IAEtC,KAAA,EAAO,CAAC,KAAA,KAA6B,KAAA,CAAa,gBAAgB,KAAK,CAAA;AAAA,IACvE,MAAA,EAAQ,CAAC,KAAA,KAA8B,MAAA,CAAc,gBAAgB,KAAK,CAAA;AAAA,IAC1E,GAAG;AAAA,GACL;AAEA,EAAA,OAAO,MAAA,CAAO,OAAO,MAAM,CAAA;AAC7B","file":"index.js","sourcesContent":["/**\n * webhooks/dispatch.ts — multi-provider header dispatch for `createPayweave`\n * clients. One endpoint serves every configured\n * provider: the provider is detected from the signature header NAME ONLY (the\n * body is NEVER parsed before verification succeeds), then the request is\n * handed to that provider's existing timing-safe verifier and the untouched\n * verify→parse→normalize pipeline in `webhooks/index.ts`.\n *\n * Fail-closed rejections, all {@link PayweaveWebhookVerificationError}, never\n * falling through to another provider's verifier:\n *\n * - a signature header for a provider NOT configured on this client;\n * - more than one known signature header on one request (ambiguous, likely\n * forged — rejected even if one of the signatures would verify);\n * - no known signature header at all;\n * - a Flutterwave header for the WRONG configured `version` — a client\n * verifies only with its own version's scheme (AGENTS.md rule 11).\n *\n * A configured provider whose webhook secret is missing at verify time throws\n * {@link PayweaveConfigError} (same conventions as the single-provider\n * namespace: Paystack falls back to its API secret key; Flutterwave and Stripe\n * require `webhookSecret`).\n */\nimport { PayweaveConfigError, PayweaveWebhookVerificationError } from \"../core/errors\";\nimport type { ResolvedPayweaveConfig, ResolvedProviderConfig } from \"../core/config\";\nimport { readHeader, type HeaderLookup } from \"../core/provider\";\nimport type { BillingApplyContext } from \"../products/apply\";\nimport { verifyPaystack } from \"./paystack\";\nimport { verifyFlutterwaveV3 } from \"./flutterwave\";\nimport { verifyFlutterwaveV4 } from \"./flutterwave-v4\";\nimport { verifyStripe } from \"./stripe\";\nimport { constructEvent, type WebhookEvent } from \"./index\";\n\n/** Raw-body + headers input accepted by every dispatch operation. */\nexport interface WebhookDispatchInput {\n /** Exact received bytes — never a re-serialized object. */\n rawBody: string | Uint8Array;\n /** `Headers` or a plain/array header map; looked up case-insensitively. */\n headers: HeaderLookup;\n}\n\n/**\n * The multi-provider `payweave.webhooks` surface. `verify` returns the\n * signature verdict as a boolean but still THROWS for the detection\n * rejections above (they are structural failures, not signature mismatches)\n * and for missing-secret config errors — matching the single-provider\n * namespace, whose `verify` also throws {@link PayweaveConfigError}.\n */\nexport interface WebhookDispatchNamespace {\n /** Detect the provider from the signature header, then verify (timing-safe, fails closed). */\n verify(input: WebhookDispatchInput): boolean;\n /** {@link verify}, but a signature mismatch throws {@link PayweaveWebhookVerificationError}. */\n verifyOrThrow(input: WebhookDispatchInput): void;\n /** Detect + verify + parse + normalize into a typed {@link WebhookEvent}. */\n constructEvent(input: WebhookDispatchInput): WebhookEvent;\n}\n\n/**\n * One row of the header→provider table below. Flutterwave rows carry the version\n * their header belongs to (v3/v4 never share a scheme — AGENTS.md rule 11).\n * `headerName` is canonical lower-case and matched case-insensitively.\n */\ntype SignatureHeaderSpec =\n | { readonly headerName: string; readonly provider: \"paystack\" | \"stripe\" }\n | {\n readonly headerName: string;\n readonly provider: \"flutterwave\";\n readonly flutterwaveVersion: \"v3\" | \"v4\";\n };\n\n/**\n * The header→provider table. Detection is on header NAMES only; the two\n * Flutterwave rows are distinct because the version is decided by which header\n * arrives — and must then match the configured version.\n */\nconst SIGNATURE_HEADER_TABLE: readonly SignatureHeaderSpec[] = [\n { headerName: \"x-paystack-signature\", provider: \"paystack\" },\n { headerName: \"verif-hash\", provider: \"flutterwave\", flutterwaveVersion: \"v3\" },\n { headerName: \"flutterwave-signature\", provider: \"flutterwave\", flutterwaveVersion: \"v4\" },\n { headerName: \"stripe-signature\", provider: \"stripe\" },\n];\n\nconst KNOWN_HEADER_NAMES = SIGNATURE_HEADER_TABLE.map((spec) => spec.headerName).join(\", \");\n\n/** A detected signature header: its table row plus the received value. */\ninterface DetectedSignature {\n readonly spec: SignatureHeaderSpec;\n readonly value: string;\n}\n\n/**\n * Detect the provider from the signature-header NAMES present on the request.\n * Exactly one known header must be present: zero and more-than-one both\n * throw {@link PayweaveWebhookVerificationError} — an ambiguous request is\n * rejected even when one of its signatures would verify.\n */\nfunction detectSignatureHeader(headers: HeaderLookup): DetectedSignature {\n const found: DetectedSignature[] = [];\n for (const spec of SIGNATURE_HEADER_TABLE) {\n const value = readHeader(headers, spec.headerName);\n if (value !== undefined) found.push({ spec, value });\n }\n const [only, ...rest] = found;\n if (only === undefined) {\n throw new PayweaveWebhookVerificationError(\n `No known webhook signature header on the request — expected exactly one of: ${KNOWN_HEADER_NAMES}.`,\n { provider: \"unknown\", isRetryable: false },\n );\n }\n if (rest.length > 0) {\n const names = found.map((f) => f.spec.headerName).join(\", \");\n throw new PayweaveWebhookVerificationError(\n `Multiple known webhook signature headers on one request (${names}) — ambiguous and likely forged; rejecting.`,\n { provider: \"unknown\", isRetryable: false },\n );\n }\n return only;\n}\n\n/**\n * Resolve the detected provider's config entry, failing closed when the header\n * belongs to a provider this client does not have configured or to the\n * wrong Flutterwave version (AGENTS.md rule 11) — never falling through to\n * another provider's verifier.\n */\nfunction requireConfigured(\n resolved: ResolvedPayweaveConfig,\n spec: SignatureHeaderSpec,\n): ResolvedProviderConfig {\n const entry = resolved.providerConfigs[spec.provider];\n if (entry === undefined) {\n throw new PayweaveWebhookVerificationError(\n `Received a \"${spec.headerName}\" header but ${spec.provider} is not configured on this ` +\n `client (configured: ${resolved.providers.join(\", \")}) — failing closed.`,\n { provider: spec.provider, isRetryable: false },\n );\n }\n if (spec.provider === \"flutterwave\") {\n const configuredVersion = entry.version === \"v4\" ? \"v4\" : \"v3\";\n if (spec.flutterwaveVersion !== configuredVersion) {\n throw new PayweaveWebhookVerificationError(\n `Received the Flutterwave ${spec.flutterwaveVersion} signature header ` +\n `(\"${spec.headerName}\") but this client is configured for Flutterwave ${configuredVersion} — ` +\n \"a client verifies webhooks only with its own version's scheme; failing closed.\",\n { provider: \"flutterwave\", isRetryable: false },\n );\n }\n }\n return entry;\n}\n\n/**\n * Verify with the DETECTED provider's own scheme and secret, mirroring the\n * single-provider namespace's secret conventions exactly: Paystack keys the\n * HMAC with `webhookSecret ?? secretKey`; Flutterwave (both versions) and\n * Stripe require `webhookSecret` and throw {@link PayweaveConfigError} without\n * it (fail closed — Stripe's HMAC key is the endpoint signing secret\n * `whsec_*`, never the API secret key). Verification itself stays in the\n * timing-safe primitives; `verifyStripe` never throws, so a `false` becomes a\n * {@link PayweaveWebhookVerificationError} in the callers above.\n */\nfunction verifyDetected(\n entry: ResolvedProviderConfig,\n spec: SignatureHeaderSpec,\n input: WebhookDispatchInput,\n): boolean {\n if (spec.provider === \"paystack\") {\n // Paystack: webhookSecret is unsupported; the API secret key is the HMAC key.\n const secret = entry.webhookSecret ?? entry.secretKey;\n if (!secret) {\n throw new PayweaveConfigError(\"Missing Paystack secret key for webhook verification.\", {\n provider: \"paystack\",\n });\n }\n return verifyPaystack(input.rawBody, readHeader(input.headers, spec.headerName), secret);\n }\n if (spec.provider === \"flutterwave\") {\n // Flutterwave (v3 + v4): the dashboard secret hash is REQUIRED — fail closed.\n if (!entry.webhookSecret) {\n throw new PayweaveConfigError(\n \"Flutterwave webhook verification requires `webhookSecret` (the dashboard secret hash).\",\n { provider: \"flutterwave\" },\n );\n }\n if (spec.flutterwaveVersion === \"v4\") {\n return verifyFlutterwaveV4(\n input.rawBody,\n readHeader(input.headers, spec.headerName),\n entry.webhookSecret,\n );\n }\n return verifyFlutterwaveV3(readHeader(input.headers, spec.headerName), entry.webhookSecret);\n }\n // Stripe: the endpoint signing secret (`whsec_*`) is REQUIRED — the API\n // secret key is NEVER a fallback HMAC key (fail closed).\n if (!entry.webhookSecret) {\n throw new PayweaveConfigError(\n \"Stripe webhook verification requires `webhookSecret` (the endpoint signing secret, `whsec_*`).\",\n { provider: \"stripe\" },\n );\n }\n return verifyStripe(input.rawBody, readHeader(input.headers, spec.headerName), entry.webhookSecret);\n}\n\n/**\n * Build the multi-provider `payweave.webhooks` namespace for a resolved keyed\n * config. Detection runs IN FRONT of the existing\n * verifiers on header names only; verification and normalization are the\n * pre-existing pipeline, unchanged — a single-provider client behaves\n * byte-identically for its own header, with the same rejection rules on top.\n *\n * `billing` is the `database`/`products` slice every constructed\n * event's `.apply()` runs against — `src/index.ts` passes the SAME\n * `billingContext` object it already builds for `subscribe`/\n * `check`/`report`. Omitted (or database-less), `.apply()` still exists on\n * every returned event but throws `PayweaveConfigError` when called.\n */\nexport function createWebhookDispatch(\n resolved: ResolvedPayweaveConfig,\n billing?: BillingApplyContext,\n): WebhookDispatchNamespace {\n /** Detect → enforce configured-provider/version → hand back the bound entry. */\n function dispatch(headers: HeaderLookup): {\n spec: SignatureHeaderSpec;\n entry: ResolvedProviderConfig;\n } {\n const { spec } = detectSignatureHeader(headers);\n return { spec, entry: requireConfigured(resolved, spec) };\n }\n\n function verify(input: WebhookDispatchInput): boolean {\n const { spec, entry } = dispatch(input.headers);\n return verifyDetected(entry, spec, input);\n }\n\n return {\n verify,\n verifyOrThrow(input) {\n const { spec, entry } = dispatch(input.headers);\n if (!verifyDetected(entry, spec, input)) {\n throw new PayweaveWebhookVerificationError(\"Webhook signature verification failed.\", {\n provider: spec.provider,\n isRetryable: false,\n });\n }\n },\n constructEvent(input) {\n const { spec, entry } = dispatch(input.headers);\n const version =\n spec.provider === \"flutterwave\" ? (entry.version === \"v4\" ? \"v4\" : \"v3\") : undefined;\n // Hand off to the untouched verify→parse→normalize pipeline with the\n // DETECTED provider bound; raw bytes pass through unmodified.\n return constructEvent({\n rawBody: input.rawBody,\n headers: input.headers,\n provider: spec.provider,\n version,\n verify: (i) => verifyDetected(entry, spec, i),\n logger: entry.logger,\n billing,\n });\n },\n };\n}\n","/**\n * Deterministic `application/x-www-form-urlencoded` serializer for Stripe\n * request bodies (PW-601, providers.md §3.1). Stripe \"accepts form-encoded\n * request bodies\" (https://docs.stripe.com/api — verified 2026-07-12); it does\n * NOT accept JSON. Structure is expressed with Rack-style bracket notation:\n *\n * - nested dictionaries: `metadata[order_id]=6735`\n * (https://docs.stripe.com/api/metadata — verified 2026-07-12)\n * - arrays of objects: `line_items[0][price]=...&line_items[0][quantity]=2`\n * (https://docs.stripe.com/api/checkout/sessions/create curl example —\n * verified 2026-07-12)\n * - arrays of scalars: `expand[0]=customer&expand[1]=payment_intent.customer`\n * — the docs' curl examples show the empty-bracket form (`expand[]=customer`,\n * https://docs.stripe.com/api/expanding_objects — verified 2026-07-12);\n * Stripe's server parses both, and we always emit EXPLICIT indices (the\n * convention of Stripe's official libraries) so output is deterministic and\n * element order is unambiguous.\n *\n * Determinism rule: INSERTION ORDER. Object keys are emitted in their JS\n * insertion order (the order the Zod request schema / caller built them) and\n * array elements in ascending index order — encoding the same value always\n * yields the same bytes, and no re-sorting ever reorders a payload.\n *\n * Value semantics:\n * - strings pass through; numbers/booleans are stringified (`500`, `true`);\n * - `null`/`undefined` entries are OMITTED entirely — Stripe's convention for\n * unsetting a field is an EMPTY STRING value (e.g. `description=`), which\n * callers express explicitly with `\"\"`; we never invent an unset;\n * - empty objects/arrays contribute no pairs;\n * - non-finite numbers and non-JSON values (Date, function, symbol, bigint)\n * throw {@link PayweaveValidationError} naming the offending key path —\n * request Zod schemas validate shapes BEFORE encoding, so hitting this is a\n * programming error, not provider drift.\n *\n * Percent-encoding: `encodeURIComponent` (RFC 3986) on every key segment and\n * value — space → `%20`, `+` → `%2B`, `&` → `%26`, `=` → `%3D`, `%` → `%25`,\n * non-ASCII → UTF-8 escapes. Structural brackets are emitted literally,\n * matching the exact wire format of the docs' own curl examples.\n */\nimport { PayweaveValidationError } from \"../core/errors\";\nimport type { EncodedBody } from \"../core/http\";\n\n/** The Content-Type every Stripe request body is sent with. */\nexport const STRIPE_FORM_CONTENT_TYPE = \"application/x-www-form-urlencoded\";\n\n/** Plain-object check — accepts null-prototype objects, rejects class instances. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === \"number\") return `non-finite number ${String(value)}`;\n if (value instanceof Date) return \"Date (pass a Unix timestamp in seconds instead)\";\n return `unsupported value of type ${typeof value}`;\n}\n\nfunction unsupported(path: string, value: unknown): PayweaveValidationError {\n return new PayweaveValidationError(\n `Cannot form-encode \"${path}\" for Stripe: ${describe(value)}.`,\n { provider: \"stripe\" },\n );\n}\n\n/**\n * Append the `key=value` pairs for one value under an already-bracketed key.\n * Recurses depth-first so nested order mirrors the input's insertion order.\n */\nfunction appendPairs(pairs: string[], key: string, value: unknown): void {\n // null/undefined are omitted at EVERY depth (see module JSDoc — unsetting is\n // an explicit empty string in Stripe's API, never an implicit null).\n if (value === undefined || value === null) return;\n switch (typeof value) {\n case \"string\":\n pairs.push(`${key}=${encodeURIComponent(value)}`);\n return;\n case \"boolean\":\n pairs.push(`${key}=${value ? \"true\" : \"false\"}`);\n return;\n case \"number\":\n if (!Number.isFinite(value)) throw unsupported(key, value);\n pairs.push(`${key}=${encodeURIComponent(String(value))}`);\n return;\n default:\n break;\n }\n if (Array.isArray(value)) {\n // Explicit ascending indices; an omitted (null/undefined) element keeps\n // later elements at their POSITIONAL index so pairs stay unambiguous.\n for (let i = 0; i < value.length; i += 1) {\n appendPairs(pairs, `${key}[${i}]`, value[i]);\n }\n return;\n }\n if (isPlainObject(value)) {\n for (const [childKey, childValue] of Object.entries(value)) {\n appendPairs(pairs, `${key}[${encodeURIComponent(childKey)}]`, childValue);\n }\n return;\n }\n throw unsupported(key, value);\n}\n\n/**\n * Encode a Stripe request body as deterministic bracket-notation form data.\n * This is the `BodyEncoder` the Stripe `HttpClient` is constructed with (see\n * `src/stripe/http-options`) — with it in place, no JSON body ever leaves the\n * Stripe client.\n *\n * @example\n * encodeStripeForm({ mode: \"payment\", line_items: [{ price: \"price_1\", quantity: 2 }] });\n * // → { contentType: \"application/x-www-form-urlencoded\",\n * // body: \"mode=payment&line_items[0][price]=price_1&line_items[0][quantity]=2\" }\n */\nexport function encodeStripeForm(body: unknown): EncodedBody {\n if (!isPlainObject(body)) {\n throw new PayweaveValidationError(\n \"Stripe request bodies must be plain objects (validated by the request schema before encoding).\",\n { provider: \"stripe\" },\n );\n }\n const pairs: string[] = [];\n for (const [key, value] of Object.entries(body)) {\n appendPairs(pairs, encodeURIComponent(key), value);\n }\n return { contentType: STRIPE_FORM_CONTENT_TYPE, body: pairs.join(\"&\") };\n}\n","/**\n * Stripe HttpClient construction pieces: auth strategy + fully-wired\n * `HttpClientOptions`. PW-602's `StripeClient` consumes {@link stripeHttpOptions}\n * so every Stripe request carries the right headers and the form-encoded body\n * transport — no JSON body ever leaves the Stripe client.\n */\nimport { STRIPE_API_VERSION, type ResolvedProviderConfig } from \"../core/config\";\nimport { PayweaveConfigError } from \"../core/errors\";\nimport type { AuthStrategy, HttpClientOptions } from \"../core/http\";\nimport { encodeStripeForm } from \"./form-encoding\";\n\n/** Options for {@link stripeAuth}. */\nexport interface StripeAuthOptions {\n /** Standard (`sk_test_`/`sk_live_`) or restricted (`rk_test_`/`rk_live_`) secret key. */\n secretKey: string;\n /** Overrides the SDK-pinned {@link STRIPE_API_VERSION} for the `Stripe-Version` header. */\n apiVersion?: string | undefined;\n /** Connect platforms — connected account id (`acct_*`) for the `Stripe-Account` header. */\n accountId?: string | undefined;\n}\n\n/**\n * Stripe auth strategy: sets Stripe's per-request identity + versioning\n * headers together on every attempt.\n *\n * - `Authorization: Bearer sk_...` — bearer auth per\n * https://docs.stripe.com/api/authentication (verified 2026-07-12; Stripe\n * documents basic auth with the key as username and bearer auth as\n * equivalent — we use bearer, matching the other Payweave providers).\n * - `Stripe-Version: <pinned>` — pins the API version on EVERY request so\n * provider-side version drift cannot change payload shapes under us\n * (https://docs.stripe.com/api/versioning — verified 2026-07-12). Defaults\n * to {@link STRIPE_API_VERSION}; overridable via `stripe.apiVersion`.\n * - `Stripe-Account: acct_...` — only when `accountId` is configured; makes\n * calls act on that connected account\n * (https://docs.stripe.com/connect/authentication — verified 2026-07-12).\n */\nexport function stripeAuth(opts: StripeAuthOptions): AuthStrategy {\n const version = opts.apiVersion ?? STRIPE_API_VERSION;\n return {\n async applyAuth(init) {\n init.headers.set(\"Authorization\", `Bearer ${opts.secretKey}`);\n init.headers.set(\"Stripe-Version\", version);\n if (opts.accountId !== undefined) {\n init.headers.set(\"Stripe-Account\", opts.accountId);\n }\n },\n };\n}\n\n/**\n * Build the `HttpClientOptions` for a Stripe `HttpClient` from a resolved\n * provider config: base URL + transport options pass through, auth is\n * {@link stripeAuth}, and the body encoder is {@link encodeStripeForm}\n * (`application/x-www-form-urlencoded` — Stripe rejects JSON bodies).\n *\n * @example\n * const resolved = resolvePayweaveConfig({ stripe: { secretKey: \"sk_test_...\" } });\n * const http = new HttpClient(stripeHttpOptions(resolved.providerConfigs.stripe!));\n */\nexport function stripeHttpOptions(resolved: ResolvedProviderConfig): HttpClientOptions {\n if (resolved.provider !== \"stripe\") {\n throw new PayweaveConfigError(\n `stripeHttpOptions received a \"${resolved.provider}\" config — expected provider \"stripe\".`,\n { provider: \"stripe\" },\n );\n }\n if (resolved.secretKey === undefined) {\n // Unreachable via resolvePayweaveConfig (the stripe schema requires\n // secretKey); guards hand-built ResolvedProviderConfig objects.\n throw new PayweaveConfigError(\"Stripe config resolved without a secretKey.\", {\n provider: \"stripe\",\n });\n }\n return {\n baseUrl: resolved.baseUrl,\n provider: \"stripe\",\n auth: stripeAuth({\n secretKey: resolved.secretKey,\n apiVersion: resolved.apiVersion,\n accountId: resolved.accountId,\n }),\n bodyEncoder: encodeStripeForm,\n timeoutMs: resolved.timeoutMs,\n maxRetries: resolved.maxRetries,\n fetch: resolved.fetch,\n logger: resolved.logger,\n };\n}\n","/**\n * Shared Stripe schema primitives: request-parse helper, the\n * `{ object: \"list\", data, has_more }` list schema, the cursor iterator every\n * Stripe list endpoint reuses, and the query flattener for nested filters.\n *\n * Stripe has NO response envelope — resources come back bare, so unlike\n * `paystack/types.ts` there are no `{status, message, data}`\n * unwrapping helpers here. Response schemas are LOOSE (`z.looseObject`) so\n * unknown provider fields pass straight through — drift is logged by the\n * HttpClient, never thrown.\n *\n * Pagination (verified 2026-07-12 against https://docs.stripe.com/api/pagination):\n * list endpoints take `limit` (1–100, default 10), `starting_after` and\n * `ending_before` cursors, and respond with\n * `{ object: \"list\", data: [...], has_more, url }`. The iterator walks\n * `has_more` pages forward by passing the LAST item's `id` as `starting_after`.\n */\nimport { z } from \"zod\";\nimport { PayweaveValidationError } from \"../core/errors\";\nimport type { QueryValue } from \"../core/http\";\n\n/**\n * Parse request input with a Zod schema, converting a {@link z.ZodError} into a\n * {@link PayweaveValidationError} so public methods only ever throw a\n * `PayweaveError` subclass. Runs BEFORE any network call — and\n * therefore before the form encoder ever sees the body.\n */\nexport function parseRequest<S extends z.ZodType>(schema: S, input: unknown): z.infer<S> {\n try {\n return schema.parse(input) as z.infer<S>;\n } catch (err) {\n if (err instanceof z.ZodError) {\n const detail = err.issues\n .map((i) => `${i.path.join(\".\") || \"(root)\"}: ${i.message}`)\n .join(\"; \");\n throw new PayweaveValidationError(`stripe request validation failed — ${detail}`, {\n provider: \"stripe\",\n cause: err,\n });\n }\n throw err;\n }\n}\n\n/**\n * Stripe `metadata` request map. Values reach Stripe as strings (the form\n * encoder stringifies numbers/booleans); ≤50 keys, keys ≤40 chars, values ≤500\n * chars, square brackets forbidden in keys — enforced provider-side\n * (https://docs.stripe.com/api/metadata — verified 2026-07-12).\n */\nexport const metadataSchema = z.record(\n z.string(),\n z.union([z.string(), z.number(), z.boolean()]),\n);\n\n/**\n * `created` range filter used by Stripe list endpoints — a dictionary of Unix\n * timestamps (https://docs.stripe.com/api/payment_intents/list — verified\n * 2026-07-12). Flattened to `created[gte]=...` query params by\n * {@link flattenQuery}.\n */\nexport const createdRange = z.object({\n gt: z.number().int().optional(),\n gte: z.number().int().optional(),\n lt: z.number().int().optional(),\n lte: z.number().int().optional(),\n});\n\n/** Cursor-pagination fields shared by every Stripe list request. */\nexport const listCursorFields = {\n /** Page size, 1–100 (Stripe default 10). */\n limit: z.number().int().min(1).max(100).optional(),\n /** Cursor: object id — return items AFTER this id (next page). */\n starting_after: z.string().optional(),\n /** Cursor: object id — return items BEFORE this id (previous page). */\n ending_before: z.string().optional(),\n};\n\n/** The shape every Stripe list response parses to. */\nexport interface StripeList<TItem> {\n object: string;\n data: TItem[];\n has_more: boolean;\n url?: string;\n}\n\n/**\n * Loose schema for Stripe's `{ object: \"list\", data, has_more, url }` list\n * response. `object` stays `z.string()` — response schemas tolerate drift,\n * never throw.\n */\nexport const stripeList = <T extends z.ZodTypeAny>(\n item: T,\n): z.ZodType<StripeList<z.infer<T>>> =>\n z.looseObject({\n object: z.string(),\n data: z.array(item),\n has_more: z.boolean(),\n url: z.string().optional(),\n }) as unknown as z.ZodType<StripeList<z.infer<T>>>;\n\n/**\n * Walk a Stripe cursor-paginated list to exhaustion: yield every item of every\n * page, requesting the next page with `starting_after = <last item's id>` while\n * `has_more` is true (https://docs.stripe.com/api/pagination — verified\n * 2026-07-12). `fetchPage` receives the cursor for the page to load\n * (`undefined` for the first page).\n */\nexport async function* iterateStripeList<T extends { id: string }>(\n fetchPage: (startingAfter: string | undefined) => Promise<StripeList<T>>,\n): AsyncGenerator<T, void, undefined> {\n let startingAfter: string | undefined;\n for (;;) {\n const page = await fetchPage(startingAfter);\n for (const item of page.data) yield item;\n const last = page.data[page.data.length - 1];\n if (!page.has_more || last === undefined) return;\n startingAfter = last.id;\n }\n}\n\n/**\n * Flatten an already-validated query object for the URL: scalars pass through,\n * ONE level of nested dictionary (e.g. `created: { gte }`,\n * `customer_details: { email }`) becomes bracket keys (`created[gte]`) —\n * Stripe's GET-parameter convention, mirroring the body encoder's bracket\n * notation. `undefined`/`null` entries are dropped (matching HttpClient's own\n * query handling).\n */\nexport function flattenQuery(query: Record<string, unknown>): Record<string, QueryValue> {\n const out: Record<string, QueryValue> = {};\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n if (typeof value === \"object\" && !Array.isArray(value)) {\n for (const [childKey, childValue] of Object.entries(value as Record<string, unknown>)) {\n if (childValue === undefined || childValue === null) continue;\n out[`${key}[${childKey}]`] = childValue as QueryValue;\n }\n continue;\n }\n out[key] = value as QueryValue;\n }\n return out;\n}\n\n/** Options accepted by Stripe POST methods that support idempotent replay. */\nexport interface StripeRequestOptions {\n /**\n * `Idempotency-Key` header value (https://docs.stripe.com/api/idempotent_requests\n * — verified 2026-07-12: POST-only, ≤255 chars, keys stored 24h, replay\n * returns the original response). Providing one ALSO makes the POST\n * retry-eligible under Payweave's retry policy — bare\n * POSTs are never auto-retried.\n */\n idempotencyKey?: string;\n}\n\n/** Validate a non-empty Stripe object id, throwing PayweaveValidationError. */\nexport function requireId(value: string, what: string): string {\n return parseRequest(z.string().min(1, `${what} id must be a non-empty string`), value);\n}\n\n/**\n * The shape every Stripe SEARCH response parses to\n * (https://docs.stripe.com/api/pagination/search — verified 2026-07-12).\n * `total_count` appears only when explicitly expanded (accurate up to 10,000).\n */\nexport interface StripeSearchPage<TItem> {\n object: string;\n data: TItem[];\n has_more: boolean;\n /** Token for the next page — pass as `page`. Absent/null on the last page. */\n next_page?: string | null;\n url?: string;\n /** Only present when expanded; accurate up to 10,000. */\n total_count?: number;\n}\n\n/**\n * Loose schema for Stripe's `{ object: \"search_result\", data, has_more,\n * next_page }` search response (see {@link StripeSearchPage}). `object` stays\n * `z.string()` — response schemas tolerate drift, never throw.\n */\nexport const stripeSearchResult = <T extends z.ZodTypeAny>(\n item: T,\n): z.ZodType<StripeSearchPage<z.infer<T>>> =>\n z.looseObject({\n object: z.string(),\n data: z.array(item),\n has_more: z.boolean(),\n next_page: z.string().nullable().optional(),\n url: z.string().optional(),\n total_count: z.number().optional(),\n }) as unknown as z.ZodType<StripeSearchPage<z.infer<T>>>;\n\n/**\n * Walk a Stripe SEARCH result to exhaustion: yield every item of every page,\n * requesting the next page with `page = <next_page token>` while `has_more`\n * is true (https://docs.stripe.com/api/pagination/search — verified\n * 2026-07-12). Search pagination is token-based — deliberately separate from\n * `iterateStripeList`'s `starting_after` cursor walk. `fetchPage` receives\n * the token for the page to load (`undefined` for the first page).\n */\nexport async function* iterateStripeSearch<T>(\n fetchPage: (page: string | undefined) => Promise<StripeSearchPage<T>>,\n): AsyncGenerator<T, void, undefined> {\n let page: string | undefined;\n for (;;) {\n const result = await fetchPage(page);\n for (const item of result.data) yield item;\n if (!result.has_more || result.next_page == null) return;\n page = result.next_page;\n }\n}\n","/**\n * Zod schemas for the Stripe Checkout Sessions module. Request fields\n * are sourced verbatim from the official API reference (all verified\n * 2026-07-12):\n * - Create: https://docs.stripe.com/api/checkout/sessions/create\n * - Retrieve: https://docs.stripe.com/api/checkout/sessions/retrieve\n * - List: https://docs.stripe.com/api/checkout/sessions/list\n * - Expire: https://docs.stripe.com/api/checkout/sessions/expire\n * - Line items: https://docs.stripe.com/api/checkout/sessions/line_items\n *\n * Amounts (`unit_amount`, `amount_total`, …) are integer MINOR units on both\n * sides — no conversion anywhere. Response schemas are\n * LOOSE: unknown provider fields pass through, drift is logged, never thrown.\n */\nimport { z } from \"zod\";\nimport { createdRange, listCursorFields, metadataSchema } from \"../types\";\n\n/**\n * `line_items[].price_data.product_data` — inline Product creation\n * (https://docs.stripe.com/api/checkout/sessions/create — verified 2026-07-12).\n */\nconst productData = z.object({\n /** Product name — required by Stripe when creating a product inline. */\n name: z.string(),\n description: z.string().optional(),\n images: z.array(z.string()).optional(),\n metadata: metadataSchema.optional(),\n tax_code: z.string().optional(),\n});\n\n/**\n * `line_items[].price_data.recurring` — subscription-mode interval\n * (https://docs.stripe.com/api/checkout/sessions/create — verified 2026-07-12).\n */\nconst recurring = z.object({\n interval: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n interval_count: z.number().int().optional(),\n});\n\n/**\n * `line_items[].price_data` — inline Price creation, the alternative to a\n * saved `price` id (https://docs.stripe.com/api/checkout/sessions/create —\n * verified 2026-07-12). `unit_amount` is integer minor units.\n */\nconst priceData = z.object({\n /** Three-letter ISO currency code, lowercase (e.g. `usd`). */\n currency: z.string(),\n /** Amount in the smallest currency unit (minor units) — integer, unchanged. */\n unit_amount: z.number().int().nonnegative().optional(),\n /** Decimal string alternative to `unit_amount` (e.g. fractional cents). */\n unit_amount_decimal: z.string().optional(),\n /** Existing Product id (`prod_*`) the price belongs to. */\n product: z.string().optional(),\n /** Inline Product creation (alternative to `product`). */\n product_data: productData.optional(),\n /** Present only for `subscription` mode line items. */\n recurring: recurring.optional(),\n tax_behavior: z.enum([\"inclusive\", \"exclusive\", \"unspecified\"]).optional(),\n});\n\n/**\n * One `line_items[]` entry (https://docs.stripe.com/api/checkout/sessions/create\n * — verified 2026-07-12). This array is the form encoder's nested-array acid\n * test: it goes to the wire as `line_items[0][price]=...` bracket pairs.\n */\nconst lineItemInput = z.object({\n /** Saved Price (or Plan) id (`price_*`). Alternative to `price_data`. */\n price: z.string().optional(),\n /** Inline price definition. Alternative to `price`. */\n price_data: priceData.optional(),\n quantity: z.number().int().optional(),\n /** Let the customer adjust the quantity in Checkout. */\n adjustable_quantity: z\n .object({\n enabled: z.boolean(),\n minimum: z.number().int().optional(),\n maximum: z.number().int().optional(),\n })\n .optional(),\n /** Tax Rate ids applied to this line item. */\n tax_rates: z.array(z.string()).optional(),\n metadata: metadataSchema.optional(),\n});\n\n/**\n * `payment_intent_data` — configuration forwarded to the PaymentIntent a\n * `payment`-mode session creates\n * (https://docs.stripe.com/api/checkout/sessions/create — verified 2026-07-12;\n * only the documented children verified there are typed here).\n */\nconst paymentIntentData = z.object({\n capture_method: z.enum([\"automatic\", \"automatic_async\", \"manual\"]).optional(),\n setup_future_usage: z.enum([\"on_session\", \"off_session\"]).optional(),\n statement_descriptor: z.string().optional(),\n statement_descriptor_suffix: z.string().optional(),\n receipt_email: z.string().optional(),\n metadata: metadataSchema.optional(),\n});\n\n/**\n * POST /v1/checkout/sessions — request\n * (https://docs.stripe.com/api/checkout/sessions/create — verified 2026-07-12).\n *\n * `ui_mode` values are those of the SDK's pinned API version\n * (`2026-06-24.dahlia`): `hosted_page` (default), `embedded_page`, `elements`\n * — the pre-2026-03-25 names `hosted`/`embedded`/`custom` were REMOVED by\n * https://docs.stripe.com/changelog/dahlia/2026-03-25/updates-available-checkout-session-ui-modes\n * (verified 2026-07-12).\n */\nexport const sessionCreateReq = z.object({\n /** Session mode — determines what the session sets up. Required. */\n mode: z.enum([\"payment\", \"setup\", \"subscription\"]),\n /** Items being purchased. Required for `payment`/`subscription` modes. */\n line_items: z.array(lineItemInput).optional(),\n /** Redirect target after a successful session (hosted page). */\n success_url: z.string().optional(),\n /** Redirect target when the customer cancels (hosted page). */\n cancel_url: z.string().optional(),\n /** Return target for embedded UI modes. */\n return_url: z.string().optional(),\n /** Checkout UI surface (see the JSDoc above for version-pinned values). */\n ui_mode: z.enum([\"hosted_page\", \"embedded_page\", \"elements\"]).optional(),\n /** Your internal reference for this session (≤200 chars). */\n client_reference_id: z.string().max(200).optional(),\n /** Existing Customer id (`cus_*`) to prefill. */\n customer: z.string().optional(),\n /** Email to prefill when no `customer` is given (≤800 chars). */\n customer_email: z.string().max(800).optional(),\n customer_creation: z.enum([\"always\", \"if_required\"]).optional(),\n /** Three-letter ISO currency code — required in some `setup`-mode cases. */\n currency: z.string().optional(),\n /** Payment method types to accept (e.g. `[\"card\"]`). Provider-validated. */\n payment_method_types: z.array(z.string()).optional(),\n metadata: metadataSchema.optional(),\n /** Unix timestamp — 30 minutes to 24 hours after creation. */\n expires_at: z.number().int().optional(),\n payment_intent_data: paymentIntentData.optional(),\n billing_address_collection: z.enum([\"auto\", \"required\"]).optional(),\n allow_promotion_codes: z.boolean().optional(),\n});\nexport type SessionCreateReq = z.input<typeof sessionCreateReq>;\n\n/**\n * A Checkout Session as returned by create/retrieve/list/expire\n * (https://docs.stripe.com/api/checkout/sessions/object). LOOSE: only stable\n * documented fields are named; everything else passes through. `url` IS null\n * in non-open states (e.g. completed/expired sessions) — tolerated, never\n * thrown (PW-602 contract note).\n */\nexport const checkoutSession = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n /** `open` | `complete` | `expired` (normalization is the unified layer's job). */\n status: z.string().nullable().optional(),\n /** `paid` | `unpaid` | `no_payment_required`. */\n payment_status: z.string().optional(),\n mode: z.string().optional(),\n /** Hosted checkout URL — null once the session is no longer open. */\n url: z.string().nullable().optional(),\n client_reference_id: z.string().nullable().optional(),\n /** Customer id string, or an expanded object — kept unknown. */\n customer: z.unknown().optional(),\n customer_email: z.string().nullable().optional(),\n /** PaymentIntent id string, or an expanded object — kept unknown. */\n payment_intent: z.unknown().optional(),\n /** Integer minor units. */\n amount_subtotal: z.number().nullable().optional(),\n /** Integer minor units. */\n amount_total: z.number().nullable().optional(),\n currency: z.string().nullable().optional(),\n metadata: z.record(z.string(), z.string()).nullable().optional(),\n success_url: z.string().nullable().optional(),\n cancel_url: z.string().nullable().optional(),\n created: z.number().optional(),\n expires_at: z.number().optional(),\n livemode: z.boolean().optional(),\n});\n\n/**\n * GET /v1/checkout/sessions — query params\n * (https://docs.stripe.com/api/checkout/sessions/list — verified 2026-07-12).\n * `created` and `customer_details` are nested dictionaries and reach the URL\n * as bracket keys (`created[gte]`, `customer_details[email]`).\n */\nexport const sessionListQuery = z.object({\n ...listCursorFields,\n /** Filter by Customer id. */\n customer: z.string().optional(),\n /** Filter by customer email (`customer_details[email]`, ≤800 chars). */\n customer_details: z.object({ email: z.string().max(800) }).optional(),\n /** Filter by PaymentIntent id. */\n payment_intent: z.string().optional(),\n /** Filter by Payment Link id. */\n payment_link: z.string().optional(),\n /** Filter by Subscription id. */\n subscription: z.string().optional(),\n status: z.enum([\"open\", \"complete\", \"expired\"]).optional(),\n /** Creation-date window (Unix timestamps). */\n created: createdRange.optional(),\n});\nexport type SessionListQuery = z.input<typeof sessionListQuery>;\n\n/**\n * A line item of a completed session\n * (https://docs.stripe.com/api/checkout/sessions/line_items — verified\n * 2026-07-12). All `amount_*` fields are integer minor units.\n */\nexport const sessionLineItem = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n amount_discount: z.number().optional(),\n amount_subtotal: z.number().optional(),\n amount_tax: z.number().optional(),\n amount_total: z.number().optional(),\n currency: z.string().optional(),\n description: z.string().nullable().optional(),\n /** The Price object backing this item — kept loose. */\n price: z.looseObject({}).nullable().optional(),\n quantity: z.number().nullable().optional(),\n});\n\n/**\n * GET /v1/checkout/sessions/{id}/line_items — query params\n * (https://docs.stripe.com/api/checkout/sessions/line_items — verified\n * 2026-07-12): cursor pagination only.\n */\nexport const lineItemsQuery = z.object({ ...listCursorFields });\nexport type LineItemsQuery = z.input<typeof lineItemsQuery>;\n","/**\n * Stripe Checkout Sessions resource (Surface A, `payweave.stripe.checkout.sessions`).\n * Every method validates its input with a request schema (throws\n * {@link PayweaveValidationError} before the network call — and therefore\n * before the form encoder runs) and passes a loose response schema to the\n * HttpClient (drift is logged, never thrown). Requests go to the wire as\n * `application/x-www-form-urlencoded` bracket notation; responses are bare\n * JSON resources — no envelope. All amounts are integer\n * minor units.\n *\n * Docs: https://docs.stripe.com/api/checkout/sessions\n */\nimport type { HttpClient } from \"../../core/http\";\nimport {\n flattenQuery,\n iterateStripeList,\n parseRequest,\n requireId,\n stripeList,\n type StripeRequestOptions,\n} from \"../types\";\nimport {\n checkoutSession,\n lineItemsQuery,\n sessionCreateReq,\n sessionLineItem,\n sessionListQuery,\n type LineItemsQuery,\n type SessionCreateReq,\n type SessionListQuery,\n} from \"../schemas/checkout-sessions\";\n\nconst sessionListRes = stripeList(checkoutSession);\nconst lineItemListRes = stripeList(sessionLineItem);\n\nexport class CheckoutSessions {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a Checkout Session. `session.url` is the hosted checkout page to\n * redirect the customer to. Amounts (`price_data.unit_amount`) are integer\n * minor units, sent to Stripe unchanged. Pass `idempotencyKey` to make the\n * POST safely replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/checkout/sessions/create\n *\n * @example\n * const session = await payweave.stripe.checkout.sessions.create({\n * mode: \"payment\",\n * line_items: [{ price: \"price_123\", quantity: 2 }],\n * success_url: \"https://example.com/success\",\n * cancel_url: \"https://example.com/cancel\",\n * }, { idempotencyKey: \"order-8123-checkout\" });\n * console.log(session.url);\n */\n async create(input: SessionCreateReq, opts: StripeRequestOptions = {}) {\n const body = parseRequest(sessionCreateReq, input);\n return this.http.request({\n method: \"POST\",\n path: \"/v1/checkout/sessions\",\n body,\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: checkoutSession,\n });\n }\n\n /**\n * Retrieve a Checkout Session by id (`cs_*`). A 404 for an unknown id\n * surfaces as {@link PayweaveNotFoundError}. Note `session.url` is null once\n * the session is no longer open.\n *\n * Docs: https://docs.stripe.com/api/checkout/sessions/retrieve\n *\n * @example\n * const session = await payweave.stripe.checkout.sessions.retrieve(\"cs_test_123\");\n * if (session.payment_status === \"paid\") { }\n */\n async retrieve(id: string) {\n const sessionId = requireId(id, \"checkout session\");\n return this.http.request({\n method: \"GET\",\n path: `/v1/checkout/sessions/${encodeURIComponent(sessionId)}`,\n schema: checkoutSession,\n });\n }\n\n /**\n * List Checkout Sessions (newest first). Cursor pagination: `limit` +\n * `starting_after`/`ending_before`; nested filters (`created`,\n * `customer_details`) become bracket query keys.\n *\n * Docs: https://docs.stripe.com/api/checkout/sessions/list\n *\n * @example\n * const page = await payweave.stripe.checkout.sessions.list({ status: \"complete\", limit: 50 });\n * console.log(page.data.length, page.has_more);\n */\n async list(query: SessionListQuery = {}) {\n const q = parseRequest(sessionListQuery, query);\n return this.http.request({\n method: \"GET\",\n path: \"/v1/checkout/sessions\",\n query: flattenQuery(q),\n schema: sessionListRes,\n });\n }\n\n /**\n * Async iterator over ALL sessions matching `query`, transparently following\n * `has_more` with `starting_after = <last id>`.\n *\n * Docs: https://docs.stripe.com/api/checkout/sessions/list\n *\n * @example\n * for await (const session of payweave.stripe.checkout.sessions.iterate({ status: \"open\" })) {\n * console.log(session.id);\n * }\n */\n async *iterate(query: SessionListQuery = {}) {\n const base = parseRequest(sessionListQuery, query);\n yield* iterateStripeList((startingAfter) =>\n this.http.request({\n method: \"GET\",\n path: \"/v1/checkout/sessions\",\n query: flattenQuery({ ...base, starting_after: startingAfter }),\n schema: sessionListRes,\n }),\n );\n }\n\n /**\n * Expire an OPEN Checkout Session so it can no longer be paid — Stripe\n * errors when the session is not `open` (surfaced as\n * {@link PayweaveValidationError} on the 400). Returns the session with\n * `status: \"expired\"`.\n *\n * Docs: https://docs.stripe.com/api/checkout/sessions/expire\n *\n * @example\n * const expired = await payweave.stripe.checkout.sessions.expire(\"cs_test_123\");\n * console.log(expired.status); // \"expired\"\n */\n async expire(id: string) {\n const sessionId = requireId(id, \"checkout session\");\n return this.http.request({\n method: \"POST\",\n path: `/v1/checkout/sessions/${encodeURIComponent(sessionId)}/expire`,\n schema: checkoutSession,\n });\n }\n\n /**\n * List a session's line items (cursor-paginated; `amount_*` are integer\n * minor units).\n *\n * Docs: https://docs.stripe.com/api/checkout/sessions/line_items\n *\n * @example\n * const items = await payweave.stripe.checkout.sessions.lineItems(\"cs_test_123\", { limit: 20 });\n * console.log(items.data[0]?.amount_total);\n */\n async lineItems(id: string, query: LineItemsQuery = {}) {\n const sessionId = requireId(id, \"checkout session\");\n const q = parseRequest(lineItemsQuery, query);\n return this.http.request({\n method: \"GET\",\n path: `/v1/checkout/sessions/${encodeURIComponent(sessionId)}/line_items`,\n query: flattenQuery(q),\n schema: lineItemListRes,\n });\n }\n\n /**\n * Async iterator over ALL line items of a session, following `has_more`\n * with `starting_after = <last id>` — line items are themselves a paginated\n * list (PW-602 work order).\n *\n * Docs: https://docs.stripe.com/api/checkout/sessions/line_items\n *\n * @example\n * for await (const item of payweave.stripe.checkout.sessions.iterateLineItems(\"cs_test_123\")) {\n * console.log(item.description, item.quantity);\n * }\n */\n async *iterateLineItems(id: string, query: LineItemsQuery = {}) {\n const sessionId = requireId(id, \"checkout session\");\n const base = parseRequest(lineItemsQuery, query);\n yield* iterateStripeList((startingAfter) =>\n this.http.request({\n method: \"GET\",\n path: `/v1/checkout/sessions/${encodeURIComponent(sessionId)}/line_items`,\n query: flattenQuery({ ...base, starting_after: startingAfter }),\n schema: lineItemListRes,\n }),\n );\n }\n}\n","/**\n * Zod schemas for the Stripe Customers module. Request fields are\n * sourced verbatim from the official API reference (all verified 2026-07-12):\n * - Create: https://docs.stripe.com/api/customers/create\n * - Retrieve: https://docs.stripe.com/api/customers/retrieve\n * - Update: https://docs.stripe.com/api/customers/update\n * - Delete: https://docs.stripe.com/api/customers/delete\n * - List: https://docs.stripe.com/api/customers/list\n * - Search: https://docs.stripe.com/api/customers/search\n *\n * `balance` is an integer in MINOR units — no conversion\n * anywhere. `tax_id_data[].type` is deliberately `z.string()` (the reference\n * lists 100+ country-specific enum values — provider-validated rather than\n * transcribed; conservative per AGENTS.md §8). Response schemas are LOOSE:\n * unknown fields pass through, drift is logged, never thrown.\n *\n * Search pagination (verified 2026-07-12 against\n * https://docs.stripe.com/api/pagination/search) is DIFFERENT from list\n * pagination: `query` (required) + `limit` + `page` request params, and a\n * `{ object: \"search_result\", data, has_more, next_page, url, total_count? }`\n * response — the next page is requested with `page = <next_page token>`, NOT\n * `starting_after`. The shared `iterateStripeList` therefore does not fit;\n * search endpoints get their own iterator (see the resource files).\n */\nimport { z } from \"zod\";\nimport { createdRange, listCursorFields, metadataSchema } from \"../types\";\n\n/**\n * Postal address dictionary — same child fields on `address` and\n * `shipping.address` (https://docs.stripe.com/api/customers/create — verified\n * 2026-07-12).\n */\nconst addressInput = z.object({\n city: z.string().optional(),\n /** Two-letter country code (ISO 3166-1 alpha-2). */\n country: z.string().optional(),\n line1: z.string().optional(),\n line2: z.string().optional(),\n postal_code: z.string().optional(),\n /** State/county/province/region (ISO 3166-2 recommended). */\n state: z.string().optional(),\n});\n\n/** `cash_balance.settings` — verified 2026-07-12. */\nconst cashBalanceInput = z.object({\n settings: z\n .object({\n reconciliation_mode: z.enum([\"automatic\", \"manual\", \"merchant_default\"]).optional(),\n })\n .optional(),\n});\n\n/** `invoice_settings` on create/update — verified 2026-07-12. */\nconst invoiceSettingsInput = z.object({\n /** Up to 4 custom fields shown on invoices. */\n custom_fields: z\n .array(\n z.object({\n /** ≤40 chars. */\n name: z.string().max(40),\n /** ≤140 chars. */\n value: z.string().max(140),\n }),\n )\n .optional(),\n default_payment_method: z.string().optional(),\n footer: z.string().optional(),\n rendering_options: z\n .object({\n amount_tax_display: z.enum([\"exclude_tax\", \"include_inclusive_tax\"]).optional(),\n template: z.string().optional(),\n })\n .optional(),\n});\n\n/** `shipping` — `address` and `name` are required when shipping is given. */\nconst shippingInput = z.object({\n address: addressInput,\n name: z.string(),\n phone: z.string().optional(),\n});\n\n/**\n * Fields shared verbatim by create and update\n * (https://docs.stripe.com/api/customers/create +\n * https://docs.stripe.com/api/customers/update — verified 2026-07-12).\n */\nconst customerSharedFields = {\n /** Required when calculating taxes. */\n address: addressInput.optional(),\n /** Integer MINOR units — a credit/debit applied to future invoices. */\n balance: z.number().int().optional(),\n /** ≤150 chars. */\n business_name: z.string().max(150).optional(),\n cash_balance: cashBalanceInput.optional(),\n description: z.string().optional(),\n /** ≤512 chars. */\n email: z.string().max(512).optional(),\n /** ≤150 chars. */\n individual_name: z.string().max(150).optional(),\n /** 3–12 uppercase letters or numbers (provider-validated). */\n invoice_prefix: z.string().optional(),\n invoice_settings: invoiceSettingsInput.optional(),\n metadata: metadataSchema.optional(),\n /** ≤256 chars. */\n name: z.string().max(256).optional(),\n next_invoice_sequence: z.number().int().optional(),\n /** ≤20 chars. */\n phone: z.string().max(20).optional(),\n preferred_locales: z.array(z.string()).optional(),\n shipping: shippingInput.optional(),\n /** Payment source id; on update it becomes the new default source. */\n source: z.string().optional(),\n tax_exempt: z.enum([\"none\", \"exempt\", \"reverse\"]).optional(),\n};\n\n/**\n * POST /v1/customers — request\n * (https://docs.stripe.com/api/customers/create — verified 2026-07-12).\n * Every field is optional — Stripe allows creating an empty customer.\n */\nexport const customerCreateReq = z.object({\n ...customerSharedFields,\n /** PaymentMethod id (`pm_*`) to attach to the new customer. */\n payment_method: z.string().optional(),\n /** Tax details — recommended when calculating taxes. */\n tax: z\n .object({\n ip_address: z.string().optional(),\n /** Create documents `deferred` (default) | `immediately`. */\n validate_location: z.enum([\"deferred\", \"immediately\"]).optional(),\n })\n .optional(),\n /**\n * The customer's tax IDs. `type` is a country-specific code (e.g. `eu_vat`,\n * `us_ein`) — 100+ documented values, provider-validated (kept `string`).\n */\n tax_id_data: z.array(z.object({ type: z.string(), value: z.string() })).optional(),\n /** Test clock id to attach (test mode). */\n test_clock: z.string().optional(),\n});\nexport type CustomerCreateReq = z.input<typeof customerCreateReq>;\n\n/**\n * POST /v1/customers/{id} — request\n * (https://docs.stripe.com/api/customers/update — verified 2026-07-12).\n * Fields not provided remain unchanged; individual `metadata` keys unset by\n * posting an empty string value.\n */\nexport const customerUpdateReq = z.object({\n ...customerSharedFields,\n /** Payment source id to make the customer's new default (≤500 chars). */\n default_source: z.string().max(500).optional(),\n /** Tax details — recommended when calculating taxes. */\n tax: z\n .object({\n ip_address: z.string().optional(),\n /** Update documents `auto` (default) | `deferred` | `immediately`. */\n validate_location: z.enum([\"auto\", \"deferred\", \"immediately\"]).optional(),\n })\n .optional(),\n});\nexport type CustomerUpdateReq = z.input<typeof customerUpdateReq>;\n\n/**\n * GET /v1/customers — query params\n * (https://docs.stripe.com/api/customers/list — verified 2026-07-12).\n * `created` reaches the URL as bracket keys (`created[gte]`).\n */\nexport const customerListQuery = z.object({\n ...listCursorFields,\n /** Creation-date window (Unix timestamps). */\n created: createdRange.optional(),\n /** Case-sensitive exact-match filter on email (≤512 chars). */\n email: z.string().max(512).optional(),\n /** Filter by test clock id. */\n test_clock: z.string().optional(),\n});\nexport type CustomerListQuery = z.input<typeof customerListQuery>;\n\n/**\n * Request params shared by every Stripe search endpoint\n * (https://docs.stripe.com/api/pagination/search — verified 2026-07-12):\n * `query` uses Stripe's search query language\n * (https://docs.stripe.com/search#search-query-language); `page` is the\n * `next_page` token of the previous response — never sent on the first call.\n */\nexport const searchReqFields = {\n /** Search query string, e.g. `name:'Jane' AND metadata['foo']:'bar'`. */\n query: z.string().min(1, \"search query must be a non-empty string\"),\n /** Page size, 1–100 (Stripe default 10). */\n limit: z.number().int().min(1).max(100).optional(),\n /** Pagination token from the previous page's `next_page` — omit initially. */\n page: z.string().optional(),\n};\n\n/**\n * GET /v1/customers/search — request\n * (https://docs.stripe.com/api/customers/search — verified 2026-07-12).\n */\nexport const customerSearchReq = z.object({ ...searchReqFields });\nexport type CustomerSearchReq = z.input<typeof customerSearchReq>;\n\n/**\n * A Customer as returned by every endpoint\n * (https://docs.stripe.com/api/customers/object). LOOSE: only stable\n * documented fields are named; everything else passes through. `balance` is\n * integer minor units.\n */\nexport const customer = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n address: z.looseObject({}).nullable().optional(),\n /** Integer minor units. */\n balance: z.number().optional(),\n created: z.number().optional(),\n currency: z.string().nullable().optional(),\n /** Source id string, or an expanded object — kept unknown. */\n default_source: z.unknown().optional(),\n delinquent: z.boolean().nullable().optional(),\n description: z.string().nullable().optional(),\n email: z.string().nullable().optional(),\n invoice_prefix: z.string().nullable().optional(),\n invoice_settings: z.looseObject({}).optional(),\n livemode: z.boolean().optional(),\n metadata: z.record(z.string(), z.string()).nullable().optional(),\n name: z.string().nullable().optional(),\n next_invoice_sequence: z.number().optional(),\n phone: z.string().nullable().optional(),\n preferred_locales: z.array(z.string()).nullable().optional(),\n shipping: z.looseObject({}).nullable().optional(),\n /** `none` | `exempt` | `reverse`. */\n tax_exempt: z.string().nullable().optional(),\n /** Test clock id string, or an expanded object — kept unknown. */\n test_clock: z.unknown().optional(),\n /**\n * `true` only on the reduced stub `retrieve` returns for a DELETED customer\n * (https://docs.stripe.com/api/customers/retrieve — verified 2026-07-12:\n * deleted customers stay retrievable \"to be able to track their history\").\n */\n deleted: z.boolean().optional(),\n});\n\n/**\n * DELETE /v1/customers/{id} response — the deletion stub\n * `{ id, object: \"customer\", deleted: true }`\n * (https://docs.stripe.com/api/customers/delete — verified 2026-07-12).\n */\nexport const deletedCustomer = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n deleted: z.boolean(),\n});\n","/**\n * Stripe Customers resource (Surface A, `payweave.stripe.customers`).\n * Every method validates its input with a request schema (throws\n * {@link PayweaveValidationError} before the network call — and therefore\n * before the form encoder runs) and passes a loose response schema to the\n * HttpClient (drift is logged, never thrown). Requests go to the wire as\n * `application/x-www-form-urlencoded` bracket notation; responses are bare\n * JSON resources — no envelope.\n *\n * PW-803 upserts customers here during `subscribe()` — `metadata` (with the\n * `pwv_` reference) and `email` are the fields its create-or-adopt loop keys\n * on.\n *\n * Docs: https://docs.stripe.com/api/customers\n */\nimport type { HttpClient } from \"../../core/http\";\nimport {\n flattenQuery,\n iterateStripeList,\n parseRequest,\n requireId,\n stripeList,\n type StripeRequestOptions,\n iterateStripeSearch,\n stripeSearchResult,\n} from \"../types\";\nimport {\n customer,\n customerCreateReq,\n customerListQuery,\n customerSearchReq,\n customerUpdateReq,\n deletedCustomer,\n type CustomerCreateReq,\n type CustomerListQuery,\n type CustomerSearchReq,\n type CustomerUpdateReq,\n} from \"../schemas/customers\";\n\nconst customerListRes = stripeList(customer);\nconst customerSearchRes = stripeSearchResult(customer);\n\n/** Spread-helper: include `body` only when the parsed input has any pairs. */\nfunction bodyIfNonEmpty(body: Record<string, unknown>): { body?: unknown } {\n return Object.keys(body).length > 0 ? { body } : {};\n}\n\nexport class Customers {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a Customer. Every field is optional — Stripe allows an empty\n * customer. `metadata` maps go to the wire as bracket pairs\n * (`metadata[pwv_reference]=...`). Pass `idempotencyKey` to make the POST\n * safely replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/customers/create\n *\n * @example\n * const cus = await payweave.stripe.customers.create({\n * email: \"jenny.rosen@example.com\",\n * name: \"Jenny Rosen\",\n * metadata: { pwv_reference: \"pwv_ref_0001\" },\n * }, { idempotencyKey: \"signup-8123-customer\" });\n * console.log(cus.id);\n */\n async create(input: CustomerCreateReq = {}, opts: StripeRequestOptions = {}) {\n const body = parseRequest(customerCreateReq, input);\n return this.http.request({\n method: \"POST\",\n path: \"/v1/customers\",\n ...bodyIfNonEmpty(body),\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: customer,\n });\n }\n\n /**\n * Retrieve a Customer by id (`cus_*`). A 404 for an unknown id surfaces as\n * {@link PayweaveNotFoundError}. DELETED customers stay retrievable (to\n * track history) and come back as a reduced stub with `deleted: true` —\n * check that flag before using other fields.\n *\n * Docs: https://docs.stripe.com/api/customers/retrieve\n *\n * @example\n * const cus = await payweave.stripe.customers.retrieve(\"cus_123\");\n * if (!cus.deleted) console.log(cus.email);\n */\n async retrieve(id: string) {\n const customerId = requireId(id, \"customer\");\n return this.http.request({\n method: \"GET\",\n path: `/v1/customers/${encodeURIComponent(customerId)}`,\n schema: customer,\n });\n }\n\n /**\n * Update a Customer. Fields not provided remain unchanged; unset an\n * individual `metadata` key by posting an empty string value for it. Pass\n * `idempotencyKey` to make the POST safely replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/customers/update\n *\n * @example\n * const cus = await payweave.stripe.customers.update(\"cus_123\", {\n * metadata: { pwv_reference: \"pwv_ref_0001\", legacy_id: \"\" }, // \"\" unsets\n * });\n */\n async update(id: string, input: CustomerUpdateReq = {}, opts: StripeRequestOptions = {}) {\n const customerId = requireId(id, \"customer\");\n const body = parseRequest(customerUpdateReq, input);\n return this.http.request({\n method: \"POST\",\n path: `/v1/customers/${encodeURIComponent(customerId)}`,\n ...bodyIfNonEmpty(body),\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: customer,\n });\n }\n\n /**\n * PERMANENTLY delete a Customer — cannot be undone. Immediately cancels\n * any active subscriptions, removes all stored payment details, and blocks\n * further operations on the customer. Returns the deletion stub\n * `{ id, object: \"customer\", deleted: true }`; the customer remains\n * retrievable afterwards (as a deleted stub) for history.\n *\n * Docs: https://docs.stripe.com/api/customers/delete\n *\n * @example\n * const gone = await payweave.stripe.customers.delete(\"cus_123\");\n * console.log(gone.deleted); // true\n */\n async delete(id: string) {\n const customerId = requireId(id, \"customer\");\n return this.http.request({\n method: \"DELETE\",\n path: `/v1/customers/${encodeURIComponent(customerId)}`,\n schema: deletedCustomer,\n });\n }\n\n /**\n * List Customers (newest first). Cursor pagination: `limit` +\n * `starting_after`/`ending_before`; the `created` window becomes bracket\n * query keys (`created[gte]`).\n *\n * Docs: https://docs.stripe.com/api/customers/list\n *\n * @example\n * const page = await payweave.stripe.customers.list({ email: \"jenny.rosen@example.com\" });\n * console.log(page.data.length, page.has_more);\n */\n async list(query: CustomerListQuery = {}) {\n const q = parseRequest(customerListQuery, query);\n return this.http.request({\n method: \"GET\",\n path: \"/v1/customers\",\n query: flattenQuery(q),\n schema: customerListRes,\n });\n }\n\n /**\n * Async iterator over ALL Customers matching `query`, transparently\n * following `has_more` with `starting_after = <last id>`.\n *\n * Docs: https://docs.stripe.com/api/customers/list\n *\n * @example\n * for await (const cus of payweave.stripe.customers.iterate({ email: \"a@example.com\" })) {\n * console.log(cus.id);\n * }\n */\n async *iterate(query: CustomerListQuery = {}) {\n const base = parseRequest(customerListQuery, query);\n yield* iterateStripeList((startingAfter) =>\n this.http.request({\n method: \"GET\",\n path: \"/v1/customers\",\n query: flattenQuery({ ...base, starting_after: startingAfter }),\n schema: customerListRes,\n }),\n );\n }\n\n /**\n * Search Customers with Stripe's search query language (e.g.\n * `name:'Jane Doe' AND metadata['foo']:'bar'`). Pagination is TOKEN-based:\n * pass the previous page's `next_page` as `page` (never `starting_after`).\n * Search is eventually consistent (typically <1 minute; up to an hour\n * during outages) — don't use it in read-after-write flows.\n *\n * Docs: https://docs.stripe.com/api/customers/search\n *\n * @example\n * const found = await payweave.stripe.customers.search({\n * query: \"metadata['pwv_reference']:'pwv_ref_0001'\",\n * });\n * console.log(found.data[0]?.id, found.next_page);\n */\n async search(input: CustomerSearchReq) {\n const q = parseRequest(customerSearchReq, input);\n return this.http.request({\n method: \"GET\",\n path: \"/v1/customers/search\",\n query: flattenQuery(q),\n schema: customerSearchRes,\n });\n }\n\n /**\n * Async iterator over ALL Customers matching a search query, transparently\n * following `has_more` with `page = <next_page token>` — search pagination\n * differs from list pagination (https://docs.stripe.com/api/pagination/search).\n *\n * Docs: https://docs.stripe.com/api/customers/search\n *\n * @example\n * for await (const cus of payweave.stripe.customers.iterateSearch({\n * query: \"email:'jenny.rosen@example.com'\",\n * })) {\n * console.log(cus.id);\n * }\n */\n async *iterateSearch(input: CustomerSearchReq) {\n const base = parseRequest(customerSearchReq, input);\n yield* iterateStripeSearch((page) =>\n this.http.request({\n method: \"GET\",\n path: \"/v1/customers/search\",\n query: flattenQuery({ ...base, page }),\n schema: customerSearchRes,\n }),\n );\n }\n}\n","/**\n * Zod schemas for the Stripe PaymentIntents module. Request fields are\n * sourced verbatim from the official API reference (all verified 2026-07-12):\n * - Create: https://docs.stripe.com/api/payment_intents/create\n * - Retrieve: https://docs.stripe.com/api/payment_intents/retrieve\n * - Confirm: https://docs.stripe.com/api/payment_intents/confirm\n * - Capture: https://docs.stripe.com/api/payment_intents/capture\n * - Cancel: https://docs.stripe.com/api/payment_intents/cancel\n * - List: https://docs.stripe.com/api/payment_intents/list\n *\n * `amount`/`amount_to_capture` are integer MINOR units end to end (providers.md\n * §3.1) — no conversion anywhere. Documented params whose child shapes we have\n * not verified against the reference (`shipping`, `transfer_data`,\n * `payment_method_options`, `payment_method_data`) are deliberately NOT typed\n * in this P0 subset (conservative wins, AGENTS.md §8) — they can be added once\n * enumerated from the docs. Response schemas are LOOSE: unknown fields pass\n * through, drift is logged, never thrown.\n */\nimport { z } from \"zod\";\nimport { createdRange, listCursorFields, metadataSchema } from \"../types\";\n\n/** `automatic_payment_methods` on create — verified 2026-07-12. */\nconst automaticPaymentMethods = z.object({\n enabled: z.boolean(),\n allow_redirects: z.enum([\"always\", \"never\"]).optional(),\n});\n\n/**\n * POST /v1/payment_intents — request\n * (https://docs.stripe.com/api/payment_intents/create — verified 2026-07-12).\n */\nexport const paymentIntentCreateReq = z.object({\n /** Positive integer in the smallest currency unit (minor units) — unchanged. */\n amount: z.number().int().positive(),\n /** Three-letter ISO currency code, lowercase. Required. */\n currency: z.string(),\n automatic_payment_methods: automaticPaymentMethods.optional(),\n /** `true` = create + confirm in one call. Defaults to false. */\n confirm: z.boolean().optional(),\n /** Customer id (`cus_*`) this intent belongs to. */\n customer: z.string().optional(),\n description: z.string().optional(),\n metadata: metadataSchema.optional(),\n /** PaymentMethod id (`pm_*`) to attach. */\n payment_method: z.string().optional(),\n /** Payment method types to accept (e.g. `[\"card\", \"link\"]`). */\n payment_method_types: z.array(z.string()).optional(),\n receipt_email: z.string().optional(),\n /** `automatic` | `automatic_async` (default) | `manual`. */\n capture_method: z.enum([\"automatic\", \"automatic_async\", \"manual\"]).optional(),\n confirmation_method: z.enum([\"automatic\", \"manual\"]).optional(),\n setup_future_usage: z.enum([\"on_session\", \"off_session\"]).optional(),\n /** ≤22 chars — statement text for non-card charges. */\n statement_descriptor: z.string().max(22).optional(),\n /** ≤22 chars — suffix appended to the account descriptor for card charges. */\n statement_descriptor_suffix: z.string().max(22).optional(),\n /** Redirect URL after off-page authentication (use with `confirm: true`). */\n return_url: z.string().optional(),\n /** Customer is not in the checkout flow (docs type: boolean or string). */\n off_session: z.union([z.boolean(), z.string()]).optional(),\n /** Transaction-group identifier for Connect. */\n transfer_group: z.string().optional(),\n /** Connect application fee, integer minor units. */\n application_fee_amount: z.number().int().optional(),\n});\nexport type PaymentIntentCreateReq = z.input<typeof paymentIntentCreateReq>;\n\n/**\n * POST /v1/payment_intents/{id}/confirm — request\n * (https://docs.stripe.com/api/payment_intents/confirm — verified 2026-07-12).\n */\nexport const paymentIntentConfirmReq = z.object({\n /** PaymentMethod id (`pm_*`) to use for this confirmation attempt. */\n payment_method: z.string().optional(),\n /** Redirect URL after authentication for redirect-based methods. */\n return_url: z.string().optional(),\n receipt_email: z.string().optional(),\n setup_future_usage: z.enum([\"on_session\", \"off_session\"]).optional(),\n capture_method: z.enum([\"automatic\", \"automatic_async\", \"manual\"]).optional(),\n /** Customer is not in the checkout flow (docs type: boolean or string). */\n off_session: z.union([z.boolean(), z.string()]).optional(),\n /** ConfirmationToken id capturing client-collected payment details. */\n confirmation_token: z.string().optional(),\n /** Fail (instead of returning `requires_action`) when an action is needed. */\n error_on_requires_action: z.boolean().optional(),\n /** Mandate id to use for this confirmation. */\n mandate: z.string().optional(),\n});\nexport type PaymentIntentConfirmReq = z.input<typeof paymentIntentConfirmReq>;\n\n/**\n * POST /v1/payment_intents/{id}/capture — request\n * (https://docs.stripe.com/api/payment_intents/capture — verified 2026-07-12).\n */\nexport const paymentIntentCaptureReq = z.object({\n /** Integer minor units to capture; defaults to full `amount_capturable`. */\n amount_to_capture: z.number().int().positive().optional(),\n /** Connect application fee, integer minor units. */\n application_fee_amount: z.number().int().optional(),\n /** Default true. `false` retains uncaptured funds (multicapture accounts). */\n final_capture: z.boolean().optional(),\n metadata: metadataSchema.optional(),\n /** ≤22 chars — statement text for non-card charges. */\n statement_descriptor: z.string().max(22).optional(),\n /** ≤22 chars — suffix appended to the account descriptor for card charges. */\n statement_descriptor_suffix: z.string().max(22).optional(),\n});\nexport type PaymentIntentCaptureReq = z.input<typeof paymentIntentCaptureReq>;\n\n/**\n * POST /v1/payment_intents/{id}/cancel — request\n * (https://docs.stripe.com/api/payment_intents/cancel — verified 2026-07-12).\n */\nexport const paymentIntentCancelReq = z.object({\n cancellation_reason: z\n .enum([\"duplicate\", \"fraudulent\", \"requested_by_customer\", \"abandoned\"])\n .optional(),\n});\nexport type PaymentIntentCancelReq = z.input<typeof paymentIntentCancelReq>;\n\n/**\n * GET /v1/payment_intents — query params\n * (https://docs.stripe.com/api/payment_intents/list — verified 2026-07-12).\n * `created` reaches the URL as bracket keys (`created[gte]`).\n */\nexport const paymentIntentListQuery = z.object({\n ...listCursorFields,\n /** Filter by Customer id. */\n customer: z.string().optional(),\n /** Creation-date window (Unix timestamps). */\n created: createdRange.optional(),\n});\nexport type PaymentIntentListQuery = z.input<typeof paymentIntentListQuery>;\n\n/**\n * A PaymentIntent as returned by every endpoint\n * (https://docs.stripe.com/api/payment_intents/object). LOOSE: only stable\n * documented fields are named; everything else passes through. All amounts are\n * integer minor units.\n */\nexport const paymentIntent = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n amount: z.number().optional(),\n amount_capturable: z.number().optional(),\n amount_received: z.number().optional(),\n currency: z.string().optional(),\n /**\n * `requires_payment_method` | `requires_confirmation` | `requires_action` |\n * `processing` | `requires_capture` | `canceled` | `succeeded` —\n * normalization is the unified layer's job.\n */\n status: z.string().optional(),\n client_secret: z.string().nullable().optional(),\n capture_method: z.string().optional(),\n confirmation_method: z.string().optional(),\n /** Customer id string, or an expanded object — kept unknown. */\n customer: z.unknown().optional(),\n description: z.string().nullable().optional(),\n /** Latest Charge id string, or an expanded object — kept unknown. */\n latest_charge: z.unknown().optional(),\n metadata: z.record(z.string(), z.string()).nullable().optional(),\n /** PaymentMethod id string, or an expanded object — kept unknown. */\n payment_method: z.unknown().optional(),\n receipt_email: z.string().nullable().optional(),\n /** Client-side action required to continue — kept loose. */\n next_action: z.looseObject({}).nullable().optional(),\n cancellation_reason: z.string().nullable().optional(),\n canceled_at: z.number().nullable().optional(),\n created: z.number().optional(),\n livemode: z.boolean().optional(),\n});\n","/**\n * Stripe PaymentIntents resource (Surface A, `payweave.stripe.paymentIntents`).\n * Every method validates its input with a request schema (throws\n * {@link PayweaveValidationError} before the network call — and therefore\n * before the form encoder runs) and passes a loose response schema to the\n * HttpClient (drift is logged, never thrown). Requests go to the wire as\n * `application/x-www-form-urlencoded` bracket notation; responses are bare\n * JSON resources — no envelope. All amounts are integer\n * minor units.\n *\n * Docs: https://docs.stripe.com/api/payment_intents\n */\nimport type { HttpClient } from \"../../core/http\";\nimport {\n flattenQuery,\n iterateStripeList,\n parseRequest,\n requireId,\n stripeList,\n type StripeRequestOptions,\n} from \"../types\";\nimport {\n paymentIntent,\n paymentIntentCancelReq,\n paymentIntentCaptureReq,\n paymentIntentConfirmReq,\n paymentIntentCreateReq,\n paymentIntentListQuery,\n type PaymentIntentCancelReq,\n type PaymentIntentCaptureReq,\n type PaymentIntentConfirmReq,\n type PaymentIntentCreateReq,\n type PaymentIntentListQuery,\n} from \"../schemas/payment-intents\";\n\nconst paymentIntentListRes = stripeList(paymentIntent);\n\n/** Spread-helper: include `body` only when the parsed input has any pairs. */\nfunction bodyIfNonEmpty(body: Record<string, unknown>): { body?: unknown } {\n return Object.keys(body).length > 0 ? { body } : {};\n}\n\nexport class PaymentIntents {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a PaymentIntent. `amount` is a positive integer in MINOR units\n * (e.g. 2000 = $20.00) and is sent to Stripe unchanged. Pass\n * `idempotencyKey` to make the POST safely replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/payment_intents/create\n *\n * @example\n * const pi = await payweave.stripe.paymentIntents.create({\n * amount: 2000,\n * currency: \"usd\",\n * automatic_payment_methods: { enabled: true },\n * }, { idempotencyKey: \"order-8123-intent\" });\n * console.log(pi.client_secret);\n */\n async create(input: PaymentIntentCreateReq, opts: StripeRequestOptions = {}) {\n const body = parseRequest(paymentIntentCreateReq, input);\n return this.http.request({\n method: \"POST\",\n path: \"/v1/payment_intents\",\n body,\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: paymentIntent,\n });\n }\n\n /**\n * Retrieve a PaymentIntent by id (`pi_*`). A 404 for an unknown id surfaces\n * as {@link PayweaveNotFoundError}.\n *\n * Docs: https://docs.stripe.com/api/payment_intents/retrieve\n *\n * @example\n * const pi = await payweave.stripe.paymentIntents.retrieve(\"pi_123\");\n * if (pi.status === \"succeeded\") { }\n */\n async retrieve(id: string) {\n const intentId = requireId(id, \"payment intent\");\n return this.http.request({\n method: \"GET\",\n path: `/v1/payment_intents/${encodeURIComponent(intentId)}`,\n schema: paymentIntent,\n });\n }\n\n /**\n * Confirm a PaymentIntent (attempt payment with the attached/provided\n * payment method). On success the status moves to `succeeded` — or\n * `requires_capture` when `capture_method` is `manual`, or\n * `requires_action` when authentication is needed. Pass `idempotencyKey`\n * to make the POST safely replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/payment_intents/confirm\n *\n * @example\n * const pi = await payweave.stripe.paymentIntents.confirm(\"pi_123\", {\n * payment_method: \"pm_card_visa\",\n * return_url: \"https://example.com/return\",\n * }, { idempotencyKey: \"order-8123-confirm\" });\n */\n async confirm(\n id: string,\n input: PaymentIntentConfirmReq = {},\n opts: StripeRequestOptions = {},\n ) {\n const intentId = requireId(id, \"payment intent\");\n const body = parseRequest(paymentIntentConfirmReq, input);\n return this.http.request({\n method: \"POST\",\n path: `/v1/payment_intents/${encodeURIComponent(intentId)}/confirm`,\n ...bodyIfNonEmpty(body),\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: paymentIntent,\n });\n }\n\n /**\n * Capture the funds of a `requires_capture` PaymentIntent (manual capture\n * flow — uncaptured intents cancel after 7 days by default).\n * `amount_to_capture` is integer minor units and defaults to the full\n * `amount_capturable`. Pass `idempotencyKey` to make the POST safely\n * replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/payment_intents/capture\n *\n * @example\n * const pi = await payweave.stripe.paymentIntents.capture(\"pi_123\", {\n * amount_to_capture: 1500,\n * }, { idempotencyKey: \"order-8123-capture\" });\n * console.log(pi.status); // \"succeeded\"\n */\n async capture(\n id: string,\n input: PaymentIntentCaptureReq = {},\n opts: StripeRequestOptions = {},\n ) {\n const intentId = requireId(id, \"payment intent\");\n const body = parseRequest(paymentIntentCaptureReq, input);\n return this.http.request({\n method: \"POST\",\n path: `/v1/payment_intents/${encodeURIComponent(intentId)}/capture`,\n ...bodyIfNonEmpty(body),\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: paymentIntent,\n });\n }\n\n /**\n * Cancel a PaymentIntent. Valid only for statuses\n * `requires_payment_method`, `requires_capture`, `requires_confirmation`,\n * `requires_action` and (rarely) `processing` — Stripe errors otherwise\n * (surfaced as {@link PayweaveValidationError} on the 400). For\n * `requires_capture` intents the remaining `amount_capturable` is\n * automatically refunded.\n *\n * Docs: https://docs.stripe.com/api/payment_intents/cancel\n *\n * @example\n * const pi = await payweave.stripe.paymentIntents.cancel(\"pi_123\", {\n * cancellation_reason: \"requested_by_customer\",\n * });\n * console.log(pi.status); // \"canceled\"\n */\n async cancel(id: string, input: PaymentIntentCancelReq = {}) {\n const intentId = requireId(id, \"payment intent\");\n const body = parseRequest(paymentIntentCancelReq, input);\n return this.http.request({\n method: \"POST\",\n path: `/v1/payment_intents/${encodeURIComponent(intentId)}/cancel`,\n ...bodyIfNonEmpty(body),\n schema: paymentIntent,\n });\n }\n\n /**\n * List PaymentIntents (newest first). Cursor pagination: `limit` +\n * `starting_after`/`ending_before`; the `created` window becomes bracket\n * query keys (`created[gte]`).\n *\n * Docs: https://docs.stripe.com/api/payment_intents/list\n *\n * @example\n * const page = await payweave.stripe.paymentIntents.list({ customer: \"cus_123\", limit: 50 });\n * console.log(page.data.length, page.has_more);\n */\n async list(query: PaymentIntentListQuery = {}) {\n const q = parseRequest(paymentIntentListQuery, query);\n return this.http.request({\n method: \"GET\",\n path: \"/v1/payment_intents\",\n query: flattenQuery(q),\n schema: paymentIntentListRes,\n });\n }\n\n /**\n * Async iterator over ALL PaymentIntents matching `query`, transparently\n * following `has_more` with `starting_after = <last id>`.\n *\n * Docs: https://docs.stripe.com/api/payment_intents/list\n *\n * @example\n * for await (const pi of payweave.stripe.paymentIntents.iterate({ customer: \"cus_123\" })) {\n * console.log(pi.id, pi.status);\n * }\n */\n async *iterate(query: PaymentIntentListQuery = {}) {\n const base = parseRequest(paymentIntentListQuery, query);\n yield* iterateStripeList((startingAfter) =>\n this.http.request({\n method: \"GET\",\n path: \"/v1/payment_intents\",\n query: flattenQuery({ ...base, starting_after: startingAfter }),\n schema: paymentIntentListRes,\n }),\n );\n }\n}\n","/**\n * Zod schemas for the Stripe Prices module. Request fields are\n * sourced verbatim from the official API reference (all verified 2026-07-12):\n * - Create: https://docs.stripe.com/api/prices/create\n * - Retrieve: https://docs.stripe.com/api/prices/retrieve\n * - Update: https://docs.stripe.com/api/prices/update\n * - List: https://docs.stripe.com/api/prices/list\n * - Search: https://docs.stripe.com/api/prices/search\n *\n * Prices are PW-803's sync target for Payweave plan pricing (`payweave push`,\n * plans-and-features.md §12). Two facts the push loop leans on (both verified\n * 2026-07-12 on the pages above):\n * 1. Prices are largely IMMUTABLE — `unit_amount`, `currency`, `product`,\n * `recurring`, `billing_scheme`, `tiers` etc. cannot change after\n * creation. The update endpoint accepts ONLY `active`, `lookup_key`,\n * `metadata`, `nickname`, `tax_behavior` (until set to\n * inclusive/exclusive), `transfer_lookup_key` and `currency_options`.\n * A price change means a NEW Price + archiving the old one\n * (`active: false`) — there is NO delete endpoint for prices.\n * 2. `lookup_key` (≤200 chars) + `transfer_lookup_key: true` atomically\n * move a stable identifier onto the replacement price.\n *\n * `unit_amount` is integer MINOR units end to end — no\n * conversion anywhere. `currency_options` (per-currency amounts keyed by a\n * dynamic currency code) is deliberately NOT typed in this P0 subset\n * (conservative per AGENTS.md §8, PW-602 precedent) — add it with a docs\n * re-check when multi-currency sync is needed. Response schemas are LOOSE:\n * unknown fields pass through, drift is logged, never thrown.\n */\nimport { z } from \"zod\";\nimport { createdRange, listCursorFields, metadataSchema } from \"../types\";\nimport { searchReqFields } from \"./customers\";\n\n/**\n * `custom_unit_amount` — customer-adjustable amounts during Checkout/Payment\n * Links (verified 2026-07-12). All amounts integer minor units.\n */\nconst customUnitAmountInput = z.object({\n /** Pass `true` to enable — otherwise omit the whole object. */\n enabled: z.boolean(),\n maximum: z.number().int().optional(),\n minimum: z.number().int().optional(),\n preset: z.number().int().optional(),\n});\n\n/**\n * `recurring` — the components of a recurring price\n * (https://docs.stripe.com/api/prices/create — verified 2026-07-12).\n */\nconst recurringInput = z.object({\n interval: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n /** Intervals between billings — max 3 years (36 months, 156 weeks). */\n interval_count: z.number().int().optional(),\n /** Defaults to `licensed`. */\n usage_type: z.enum([\"licensed\", \"metered\"]).optional(),\n /** Billing Meter id tracking usage for a metered price. */\n meter: z.string().optional(),\n});\n\n/**\n * One `tiers[]` element — required when `billing_scheme=tiered`\n * (verified 2026-07-12). `up_to` is an integer bound or the literal `\"inf\"`\n * for the fallback tier; amounts are integer minor units (`*_decimal`\n * variants are decimal strings).\n */\nconst tierInput = z.object({\n /** Upper bound of this tier — `\"inf\"` for the fallback tier. Required. */\n up_to: z.union([z.literal(\"inf\"), z.number().int()]),\n /** Flat amount for the whole tier, integer minor units. */\n flat_amount: z.number().int().optional(),\n /** Decimal-string alternative to `flat_amount` (only one of the two). */\n flat_amount_decimal: z.string().optional(),\n /** Per-unit amount, integer minor units. */\n unit_amount: z.number().int().optional(),\n /** Decimal-string alternative to `unit_amount` (only one of the two). */\n unit_amount_decimal: z.string().optional(),\n});\n\n/**\n * `product_data` — create the backing Product in the same call (alternative\n * to `product`; https://docs.stripe.com/api/prices/create — verified\n * 2026-07-12).\n */\nconst productDataInput = z.object({\n /** Displayable product name. Required. */\n name: z.string(),\n /** Defaults to true. */\n active: z.boolean().optional(),\n metadata: metadataSchema.optional(),\n /** ≤22 chars; may not include `<`, `>`, `\\`, `\"`, `'`. */\n statement_descriptor: z.string().max(22).optional(),\n /** Tax code id — recommended when calculating taxes. */\n tax_code: z.string().optional(),\n tax_details: z\n .object({\n tax_code: z.string().optional(),\n /** Tax location id — required/optional/unsupported per tax code. */\n performance_location: z.string().optional(),\n })\n .optional(),\n /** ≤12 chars. */\n unit_label: z.string().max(12).optional(),\n});\n\n/**\n * POST /v1/prices — request\n * (https://docs.stripe.com/api/prices/create — verified 2026-07-12).\n * One of `unit_amount` / `unit_amount_decimal` / `custom_unit_amount` is\n * required unless `billing_scheme=tiered`; one of `product` / `product_data`\n * is always required — both provider-validated. `currency_options` is\n * deliberately untyped (see module JSDoc).\n */\nexport const priceCreateReq = z.object({\n /** Three-letter ISO currency code, lowercase. Required. */\n currency: z.string(),\n /** Integer minor units (or 0 for a free price). */\n unit_amount: z.number().int().nonnegative().optional(),\n /** Decimal string alternative to `unit_amount` (≤12 decimal places). */\n unit_amount_decimal: z.string().optional(),\n custom_unit_amount: customUnitAmountInput.optional(),\n /** Usable for new purchases. Defaults to true; `false` = archived. */\n active: z.boolean().optional(),\n /** Defaults to `per_unit`. */\n billing_scheme: z.enum([\"per_unit\", \"tiered\"]).optional(),\n /** Stable retrieval key (≤200 chars) — PW-803's price identifier. */\n lookup_key: z.string().max(200).optional(),\n /** Atomically move `lookup_key` off the price currently holding it. */\n transfer_lookup_key: z.boolean().optional(),\n metadata: metadataSchema.optional(),\n /** Internal description, hidden from customers. */\n nickname: z.string().optional(),\n /** Existing Product id (`prod_*`). Alternative to `product_data`. */\n product: z.string().optional(),\n /** Inline Product creation. Alternative to `product`. */\n product_data: productDataInput.optional(),\n recurring: recurringInput.optional(),\n /** Cannot be changed after being set to `inclusive`/`exclusive`. */\n tax_behavior: z.enum([\"inclusive\", \"exclusive\", \"unspecified\"]).optional(),\n /** Required when `billing_scheme=tiered`. */\n tiers: z.array(tierInput).optional(),\n /** Required when `billing_scheme=tiered`. */\n tiers_mode: z.enum([\"graduated\", \"volume\"]).optional(),\n /** Transform reported quantity before billing — cannot combine with tiers. */\n transform_quantity: z\n .object({\n divide_by: z.number().int(),\n round: z.enum([\"up\", \"down\"]),\n })\n .optional(),\n});\nexport type PriceCreateReq = z.input<typeof priceCreateReq>;\n\n/**\n * POST /v1/prices/{id} — request\n * (https://docs.stripe.com/api/prices/update — verified 2026-07-12).\n * ONLY these fields are updatable — amount/currency/product/recurring are\n * immutable after creation (see module JSDoc; a price change = new Price +\n * `active: false` on the old one). `currency_options` is deliberately\n * untyped (see module JSDoc).\n */\nexport const priceUpdateReq = z.object({\n /** `false` archives the price for new purchases (PW-803 price rotation). */\n active: z.boolean().optional(),\n /** Stable retrieval key (≤200 chars). */\n lookup_key: z.string().max(200).optional(),\n /** Atomically move `lookup_key` off the price currently holding it. */\n transfer_lookup_key: z.boolean().optional(),\n metadata: metadataSchema.optional(),\n /** Internal description, hidden from customers. */\n nickname: z.string().optional(),\n /** Cannot be changed after being set to `inclusive`/`exclusive`. */\n tax_behavior: z.enum([\"inclusive\", \"exclusive\", \"unspecified\"]).optional(),\n});\nexport type PriceUpdateReq = z.input<typeof priceUpdateReq>;\n\n/**\n * GET /v1/prices — query params\n * (https://docs.stripe.com/api/prices/list — verified 2026-07-12).\n * `created`/`recurring` reach the URL as bracket keys (`recurring[interval]`);\n * `lookup_keys` as explicit indices (`lookup_keys[0]=...`).\n */\nexport const priceListQuery = z.object({\n ...listCursorFields,\n /** Only active (or only archived) prices. */\n active: z.boolean().optional(),\n /** Creation-date window (Unix timestamps). */\n created: createdRange.optional(),\n /** Filter by currency code. */\n currency: z.string().optional(),\n /** Only prices with these lookup_keys (up to 10). */\n lookup_keys: z.array(z.string()).optional(),\n /** Filter by Product id. */\n product: z.string().optional(),\n /** Filter by recurring components. */\n recurring: z\n .object({\n interval: z.enum([\"day\", \"week\", \"month\", \"year\"]).optional(),\n /** Filter by the price's Billing Meter id. */\n meter: z.string().optional(),\n usage_type: z.enum([\"licensed\", \"metered\"]).optional(),\n })\n .optional(),\n type: z.enum([\"one_time\", \"recurring\"]).optional(),\n});\nexport type PriceListQuery = z.input<typeof priceListQuery>;\n\n/**\n * GET /v1/prices/search — request\n * (https://docs.stripe.com/api/prices/search — verified 2026-07-12).\n */\nexport const priceSearchReq = z.object({ ...searchReqFields });\nexport type PriceSearchReq = z.input<typeof priceSearchReq>;\n\n/**\n * A Price as returned by every endpoint\n * (https://docs.stripe.com/api/prices/object). LOOSE: only stable documented\n * fields are named; everything else passes through. `unit_amount` is integer\n * minor units (null for tiered/custom-amount prices).\n */\nexport const price = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n active: z.boolean().optional(),\n /** `per_unit` | `tiered`. */\n billing_scheme: z.string().optional(),\n created: z.number().optional(),\n currency: z.string().optional(),\n custom_unit_amount: z.looseObject({}).nullable().optional(),\n livemode: z.boolean().optional(),\n lookup_key: z.string().nullable().optional(),\n metadata: z.record(z.string(), z.string()).nullable().optional(),\n nickname: z.string().nullable().optional(),\n /** Product id string, or an expanded object — kept unknown. */\n product: z.unknown().optional(),\n recurring: z\n .looseObject({\n interval: z.string().optional(),\n interval_count: z.number().nullable().optional(),\n trial_period_days: z.number().nullable().optional(),\n usage_type: z.string().optional(),\n meter: z.string().nullable().optional(),\n })\n .nullable()\n .optional(),\n tax_behavior: z.string().nullable().optional(),\n /** `graduated` | `volume` — null unless tiered. */\n tiers_mode: z.string().nullable().optional(),\n transform_quantity: z.looseObject({}).nullable().optional(),\n /** `one_time` | `recurring`. */\n type: z.string().optional(),\n /** Integer minor units — null for tiered/custom-amount prices. */\n unit_amount: z.number().nullable().optional(),\n unit_amount_decimal: z.string().nullable().optional(),\n});\n","/**\n * Stripe Prices resource (Surface A, `payweave.stripe.prices`).\n * Every method validates its input with a request schema (throws\n * {@link PayweaveValidationError} before the network call — and therefore\n * before the form encoder runs) and passes a loose response schema to the\n * HttpClient (drift is logged, never thrown). Requests go to the wire as\n * `application/x-www-form-urlencoded` bracket notation; responses are bare\n * JSON resources — no envelope. All `unit_amount`s are\n * integer minor units.\n *\n * PW-803 syncs Payweave plan pricing onto prices (`payweave push`,\n * plans-and-features.md §12). Prices are largely IMMUTABLE — amount,\n * currency, product and recurring cannot change after creation, and there is\n * NO delete endpoint: a price change means creating a NEW Price and archiving\n * the old one (`update(id, { active: false })`), optionally moving the\n * `lookup_key` across with `transfer_lookup_key: true`.\n *\n * Docs: https://docs.stripe.com/api/prices\n */\nimport type { HttpClient } from \"../../core/http\";\nimport type { QueryValue } from \"../../core/http\";\nimport {\n flattenQuery,\n iterateStripeList,\n parseRequest,\n requireId,\n stripeList,\n type StripeRequestOptions,\n iterateStripeSearch,\n stripeSearchResult,\n} from \"../types\";\nimport {\n price,\n priceCreateReq,\n priceListQuery,\n priceSearchReq,\n priceUpdateReq,\n type PriceCreateReq,\n type PriceListQuery,\n type PriceSearchReq,\n type PriceUpdateReq,\n} from \"../schemas/prices\";\n\nconst priceListRes = stripeList(price);\nconst priceSearchRes = stripeSearchResult(price);\n\n/** Spread-helper: include `body` only when the parsed input has any pairs. */\nfunction bodyIfNonEmpty(body: Record<string, unknown>): { body?: unknown } {\n return Object.keys(body).length > 0 ? { body } : {};\n}\n\nexport class Prices {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a Price. `unit_amount` is integer MINOR units (e.g. 1500 = $15.00)\n * and is sent to Stripe unchanged; `recurring` makes it a subscription\n * price; `lookup_key` (+ `transfer_lookup_key`) gives it a stable\n * identifier that survives price rotation. Amount, currency, product and\n * recurring are IMMUTABLE afterwards. Pass `idempotencyKey` to make the\n * POST safely replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/prices/create\n *\n * @example\n * const pr = await payweave.stripe.prices.create({\n * currency: \"usd\",\n * unit_amount: 1500,\n * product: \"prod_123\",\n * recurring: { interval: \"month\" },\n * lookup_key: \"pro-monthly\",\n * }, { idempotencyKey: \"push-pro-monthly-v2\" });\n * console.log(pr.id);\n */\n async create(input: PriceCreateReq, opts: StripeRequestOptions = {}) {\n const body = parseRequest(priceCreateReq, input);\n return this.http.request({\n method: \"POST\",\n path: \"/v1/prices\",\n body,\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: price,\n });\n }\n\n /**\n * Retrieve a Price by id (`price_*`). A 404 for an unknown id surfaces as\n * {@link PayweaveNotFoundError}.\n *\n * Docs: https://docs.stripe.com/api/prices/retrieve\n *\n * @example\n * const pr = await payweave.stripe.prices.retrieve(\"price_123\");\n * console.log(pr.unit_amount, pr.currency);\n */\n async retrieve(id: string) {\n const priceId = requireId(id, \"price\");\n return this.http.request({\n method: \"GET\",\n path: `/v1/prices/${encodeURIComponent(priceId)}`,\n schema: price,\n });\n }\n\n /**\n * Update a Price. ONLY `active`, `lookup_key`/`transfer_lookup_key`,\n * `metadata`, `nickname` and `tax_behavior` (until set) are updatable —\n * amount/currency/product/recurring are immutable, and prices cannot be\n * deleted: rotate by creating a new Price and archiving this one with\n * `active: false` (PW-803's price-change flow). Pass `idempotencyKey` to\n * make the POST safely replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/prices/update\n *\n * @example\n * const archived = await payweave.stripe.prices.update(\"price_123\", {\n * active: false,\n * });\n * console.log(archived.active); // false\n */\n async update(id: string, input: PriceUpdateReq = {}, opts: StripeRequestOptions = {}) {\n const priceId = requireId(id, \"price\");\n const body = parseRequest(priceUpdateReq, input);\n return this.http.request({\n method: \"POST\",\n path: `/v1/prices/${encodeURIComponent(priceId)}`,\n ...bodyIfNonEmpty(body),\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: price,\n });\n }\n\n /**\n * List Prices (newest first). Cursor pagination: `limit` +\n * `starting_after`/`ending_before`; `created`/`recurring` become bracket\n * query keys (`recurring[interval]`) and `lookup_keys` explicit indices\n * (`lookup_keys[0]=...`).\n *\n * Docs: https://docs.stripe.com/api/prices/list\n *\n * @example\n * const page = await payweave.stripe.prices.list({ product: \"prod_123\", active: true });\n * console.log(page.data.length, page.has_more);\n */\n async list(query: PriceListQuery = {}) {\n const { lookup_keys, ...rest } = parseRequest(priceListQuery, query);\n const q: Record<string, QueryValue> = flattenQuery(rest);\n lookup_keys?.forEach((key, i) => {\n q[`lookup_keys[${i}]`] = key;\n });\n return this.http.request({\n method: \"GET\",\n path: \"/v1/prices\",\n query: q,\n schema: priceListRes,\n });\n }\n\n /**\n * Async iterator over ALL Prices matching `query`, transparently following\n * `has_more` with `starting_after = <last id>`.\n *\n * Docs: https://docs.stripe.com/api/prices/list\n *\n * @example\n * for await (const pr of payweave.stripe.prices.iterate({ product: \"prod_123\" })) {\n * console.log(pr.id, pr.unit_amount);\n * }\n */\n async *iterate(query: PriceListQuery = {}) {\n const { lookup_keys, ...base } = parseRequest(priceListQuery, query);\n const lookupPairs: Record<string, QueryValue> = {};\n lookup_keys?.forEach((key, i) => {\n lookupPairs[`lookup_keys[${i}]`] = key;\n });\n yield* iterateStripeList((startingAfter) =>\n this.http.request({\n method: \"GET\",\n path: \"/v1/prices\",\n query: {\n ...flattenQuery({ ...base, starting_after: startingAfter }),\n ...lookupPairs,\n },\n schema: priceListRes,\n }),\n );\n }\n\n /**\n * Search Prices with Stripe's search query language (e.g.\n * `active:'true' AND lookup_key:'pro-monthly'`). Pagination is TOKEN-based:\n * pass the previous page's `next_page` as `page` (never `starting_after`).\n * Search is eventually consistent — don't use it in read-after-write flows.\n *\n * Docs: https://docs.stripe.com/api/prices/search\n *\n * @example\n * const found = await payweave.stripe.prices.search({\n * query: \"metadata['pwv_reference']:'pwv_plan_pro'\",\n * });\n * console.log(found.data[0]?.id, found.next_page);\n */\n async search(input: PriceSearchReq) {\n const q = parseRequest(priceSearchReq, input);\n return this.http.request({\n method: \"GET\",\n path: \"/v1/prices/search\",\n query: flattenQuery(q),\n schema: priceSearchRes,\n });\n }\n\n /**\n * Async iterator over ALL Prices matching a search query, transparently\n * following `has_more` with `page = <next_page token>` — search pagination\n * differs from list pagination (https://docs.stripe.com/api/pagination/search).\n *\n * Docs: https://docs.stripe.com/api/prices/search\n *\n * @example\n * for await (const pr of payweave.stripe.prices.iterateSearch({\n * query: \"type:'recurring'\",\n * })) {\n * console.log(pr.id);\n * }\n */\n async *iterateSearch(input: PriceSearchReq) {\n const base = parseRequest(priceSearchReq, input);\n yield* iterateStripeSearch((page) =>\n this.http.request({\n method: \"GET\",\n path: \"/v1/prices/search\",\n query: flattenQuery({ ...base, page }),\n schema: priceSearchRes,\n }),\n );\n }\n}\n","/**\n * Zod schemas for the Stripe Products module. Request fields are\n * sourced verbatim from the official API reference (all verified 2026-07-12):\n * - Create: https://docs.stripe.com/api/products/create\n * - Retrieve: https://docs.stripe.com/api/products/retrieve\n * - Update: https://docs.stripe.com/api/products/update\n * - Delete: https://docs.stripe.com/api/products/delete\n * - List: https://docs.stripe.com/api/products/list\n * - Search: https://docs.stripe.com/api/products/search\n *\n * Products are PW-803's sync target for Payweave plans (`payweave push`,\n * plans-and-features.md §12): in sync flows a product is ARCHIVED\n * (`update({ active: false })`) rather than deleted — DELETE only succeeds\n * for products with no prices attached. `name`, `metadata` and `active` are\n * the fields the push loop leans on.\n *\n * `default_price_data.unit_amount` is integer MINOR units (providers.md\n * §3.1). `default_price_data.currency_options` (per-currency amounts keyed\n * by a dynamic currency code) is deliberately NOT typed in this P0 subset\n * (conservative per AGENTS.md §8, PW-602 precedent) — add it with a docs\n * re-check when multi-currency sync is needed. Response schemas are LOOSE:\n * unknown fields pass through, drift is logged, never thrown.\n */\nimport { z } from \"zod\";\nimport { createdRange, listCursorFields, metadataSchema } from \"../types\";\nimport { searchReqFields } from \"./customers\";\n\n/** `marketing_features[]` — up to 15 entries, `name` ≤80 chars. */\nconst marketingFeatureInput = z.object({\n /** ≤80 chars. */\n name: z.string().max(80),\n});\n\n/** `package_dimensions` — all four measurements required when given. */\nconst packageDimensionsInput = z.object({\n /** Inches, ≤2 decimal places. */\n height: z.number(),\n /** Inches, ≤2 decimal places. */\n length: z.number(),\n /** Ounces, ≤2 decimal places. */\n weight: z.number(),\n /** Inches, ≤2 decimal places. */\n width: z.number(),\n});\n\n/** `tax_details` — recommended when calculating taxes (verified 2026-07-12). */\nconst taxDetailsInput = z.object({\n tax_code: z.string().optional(),\n /** Tax location id — required/optional/unsupported depending on tax code. */\n performance_location: z.string().optional(),\n});\n\n/**\n * `default_price_data.custom_unit_amount` — customer-adjustable amounts\n * (verified 2026-07-12). All amounts integer minor units.\n */\nconst customUnitAmountInput = z.object({\n /** Pass `true` to enable — otherwise omit the whole object. */\n enabled: z.boolean(),\n maximum: z.number().int().optional(),\n minimum: z.number().int().optional(),\n preset: z.number().int().optional(),\n});\n\n/**\n * `default_price_data` — generates the product's default Price in the same\n * call (https://docs.stripe.com/api/products/create — verified 2026-07-12).\n * `currency_options` is deliberately untyped here (see module JSDoc).\n */\nconst defaultPriceDataInput = z.object({\n /** Three-letter ISO currency code, lowercase. Required. */\n currency: z.string(),\n /** Integer minor units (or 0 for a free price). */\n unit_amount: z.number().int().nonnegative().optional(),\n /** Decimal string alternative to `unit_amount` (≤12 decimal places). */\n unit_amount_decimal: z.string().optional(),\n custom_unit_amount: customUnitAmountInput.optional(),\n metadata: metadataSchema.optional(),\n recurring: z\n .object({\n interval: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n /** Intervals between billings — max 3 years (36 months, 156 weeks). */\n interval_count: z.number().int().optional(),\n })\n .optional(),\n /** Cannot be changed after being set to `inclusive`/`exclusive`. */\n tax_behavior: z.enum([\"inclusive\", \"exclusive\", \"unspecified\"]).optional(),\n});\n\n/**\n * Fields shared verbatim by create and update\n * (https://docs.stripe.com/api/products/create +\n * https://docs.stripe.com/api/products/update — verified 2026-07-12).\n */\nconst productSharedFields = {\n /** Available for purchase. Defaults to true; `false` = archived. */\n active: z.boolean().optional(),\n description: z.string().optional(),\n /** Up to 8 image URLs. */\n images: z.array(z.string()).optional(),\n /** Up to 15 marketing features (pricing tables). */\n marketing_features: z.array(marketingFeatureInput).optional(),\n metadata: metadataSchema.optional(),\n package_dimensions: packageDimensionsInput.optional(),\n /** Whether the product is shipped (physical goods). */\n shippable: z.boolean().optional(),\n /** ≤22 chars, `type=service` subscriptions only. */\n statement_descriptor: z.string().max(22).optional(),\n /** Tax code id — recommended when calculating taxes. */\n tax_code: z.string().optional(),\n tax_details: taxDetailsInput.optional(),\n /** ≤12 chars, `type=service` only. */\n unit_label: z.string().max(12).optional(),\n /** Publicly-accessible webpage for the product. */\n url: z.string().optional(),\n};\n\n/**\n * POST /v1/products — request\n * (https://docs.stripe.com/api/products/create — verified 2026-07-12).\n */\nexport const productCreateReq = z.object({\n /** Displayable product name. Required. */\n name: z.string(),\n ...productSharedFields,\n /** Custom unique id (`prod_*` generated when omitted). */\n id: z.string().optional(),\n /** Create the product's default Price in the same call. */\n default_price_data: defaultPriceDataInput.optional(),\n});\nexport type ProductCreateReq = z.input<typeof productCreateReq>;\n\n/**\n * POST /v1/products/{id} — request\n * (https://docs.stripe.com/api/products/update — verified 2026-07-12).\n * Fields not provided remain unchanged. `active: false` ARCHIVES the product\n * — the sync-flow alternative to deletion.\n */\nexport const productUpdateReq = z.object({\n ...productSharedFields,\n /** Existing Price id (`price_*`) to make the default for this product. */\n default_price: z.string().optional(),\n name: z.string().optional(),\n});\nexport type ProductUpdateReq = z.input<typeof productUpdateReq>;\n\n/**\n * GET /v1/products — query params\n * (https://docs.stripe.com/api/products/list — verified 2026-07-12).\n * `created` reaches the URL as bracket keys; `ids` as explicit indices\n * (`ids[0]=...`).\n */\nexport const productListQuery = z.object({\n ...listCursorFields,\n /** Only active (or only archived) products. */\n active: z.boolean().optional(),\n /** Creation-date window (Unix timestamps). */\n created: createdRange.optional(),\n /** Only these product ids — cannot combine with the cursor params. */\n ids: z.array(z.string()).optional(),\n /** Only shippable (physical) products. */\n shippable: z.boolean().optional(),\n /** Only products with this url. */\n url: z.string().optional(),\n});\nexport type ProductListQuery = z.input<typeof productListQuery>;\n\n/**\n * GET /v1/products/search — request\n * (https://docs.stripe.com/api/products/search — verified 2026-07-12).\n * Example query: `active:'true' AND metadata['order_id']:'6735'`.\n */\nexport const productSearchReq = z.object({ ...searchReqFields });\nexport type ProductSearchReq = z.input<typeof productSearchReq>;\n\n/**\n * A Product as returned by every endpoint\n * (https://docs.stripe.com/api/products/object). LOOSE: only stable\n * documented fields are named; everything else passes through.\n */\nexport const product = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n active: z.boolean().optional(),\n created: z.number().optional(),\n /** Price id string, or an expanded object — kept unknown. */\n default_price: z.unknown().optional(),\n description: z.string().nullable().optional(),\n images: z.array(z.string()).optional(),\n marketing_features: z.array(z.looseObject({})).optional(),\n livemode: z.boolean().optional(),\n metadata: z.record(z.string(), z.string()).nullable().optional(),\n name: z.string().optional(),\n package_dimensions: z.looseObject({}).nullable().optional(),\n shippable: z.boolean().nullable().optional(),\n statement_descriptor: z.string().nullable().optional(),\n /** Tax code id string, or an expanded object — kept unknown. */\n tax_code: z.unknown().optional(),\n unit_label: z.string().nullable().optional(),\n updated: z.number().optional(),\n url: z.string().nullable().optional(),\n});\n\n/**\n * DELETE /v1/products/{id} response — the deletion stub\n * `{ id, object: \"product\", deleted: true }`\n * (https://docs.stripe.com/api/products/delete — verified 2026-07-12).\n */\nexport const deletedProduct = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n deleted: z.boolean(),\n});\n","/**\n * Stripe Products resource (Surface A, `payweave.stripe.products`).\n * Every method validates its input with a request schema (throws\n * {@link PayweaveValidationError} before the network call — and therefore\n * before the form encoder runs) and passes a loose response schema to the\n * HttpClient (drift is logged, never thrown). Requests go to the wire as\n * `application/x-www-form-urlencoded` bracket notation; responses are bare\n * JSON resources — no envelope.\n *\n * PW-803 syncs Payweave plans onto products (`payweave push`,\n * plans-and-features.md §12): sync flows ARCHIVE a product\n * (`update(id, { active: false })`) instead of deleting it — DELETE only\n * succeeds for products with no prices attached. `name`, `metadata` and\n * `active` are the fields the push loop keys on.\n *\n * Docs: https://docs.stripe.com/api/products\n */\nimport type { HttpClient } from \"../../core/http\";\nimport type { QueryValue } from \"../../core/http\";\nimport {\n flattenQuery,\n iterateStripeList,\n parseRequest,\n requireId,\n stripeList,\n type StripeRequestOptions,\n iterateStripeSearch,\n stripeSearchResult,\n} from \"../types\";\nimport {\n deletedProduct,\n product,\n productCreateReq,\n productListQuery,\n productSearchReq,\n productUpdateReq,\n type ProductCreateReq,\n type ProductListQuery,\n type ProductSearchReq,\n type ProductUpdateReq,\n} from \"../schemas/products\";\n\nconst productListRes = stripeList(product);\nconst productSearchRes = stripeSearchResult(product);\n\n/** Spread-helper: include `body` only when the parsed input has any pairs. */\nfunction bodyIfNonEmpty(body: Record<string, unknown>): { body?: unknown } {\n return Object.keys(body).length > 0 ? { body } : {};\n}\n\nexport class Products {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a Product. `default_price_data` creates the product's default\n * Price in the same call — its `unit_amount` is integer MINOR units, sent\n * to Stripe unchanged. Pass `idempotencyKey` to make the POST safely\n * replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/products/create\n *\n * @example\n * const prod = await payweave.stripe.products.create({\n * name: \"Pro Plan\",\n * metadata: { pwv_reference: \"pwv_plan_pro\" },\n * default_price_data: {\n * currency: \"usd\",\n * unit_amount: 1500, // $15.00 in minor units\n * recurring: { interval: \"month\" },\n * },\n * }, { idempotencyKey: \"push-pro-plan-v1\" });\n * console.log(prod.id, prod.default_price);\n */\n async create(input: ProductCreateReq, opts: StripeRequestOptions = {}) {\n const body = parseRequest(productCreateReq, input);\n return this.http.request({\n method: \"POST\",\n path: \"/v1/products\",\n body,\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: product,\n });\n }\n\n /**\n * Retrieve a Product by id (`prod_*`). A 404 for an unknown id surfaces as\n * {@link PayweaveNotFoundError}.\n *\n * Docs: https://docs.stripe.com/api/products/retrieve\n *\n * @example\n * const prod = await payweave.stripe.products.retrieve(\"prod_123\");\n * console.log(prod.name, prod.active);\n */\n async retrieve(id: string) {\n const productId = requireId(id, \"product\");\n return this.http.request({\n method: \"GET\",\n path: `/v1/products/${encodeURIComponent(productId)}`,\n schema: product,\n });\n }\n\n /**\n * Update a Product. Fields not provided remain unchanged. `active: false`\n * ARCHIVES the product (no new purchases) — the sync-flow alternative to\n * deletion, since products with prices cannot be deleted (PW-803 relies on\n * this). Pass `idempotencyKey` to make the POST safely replayable (and\n * retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/products/update\n *\n * @example\n * const archived = await payweave.stripe.products.update(\"prod_123\", { active: false });\n * console.log(archived.active); // false\n */\n async update(id: string, input: ProductUpdateReq = {}, opts: StripeRequestOptions = {}) {\n const productId = requireId(id, \"product\");\n const body = parseRequest(productUpdateReq, input);\n return this.http.request({\n method: \"POST\",\n path: `/v1/products/${encodeURIComponent(productId)}`,\n ...bodyIfNonEmpty(body),\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: product,\n });\n }\n\n /**\n * Delete a Product. Only succeeds when the product has NO prices attached\n * (and, for `type=good`, no SKUs) — otherwise Stripe rejects with a 400\n * (surfaced as {@link PayweaveValidationError}). Sync flows should archive\n * with `update(id, { active: false })` instead. Returns the deletion stub\n * `{ id, object: \"product\", deleted: true }`.\n *\n * Docs: https://docs.stripe.com/api/products/delete\n *\n * @example\n * const gone = await payweave.stripe.products.delete(\"prod_123\");\n * console.log(gone.deleted); // true\n */\n async delete(id: string) {\n const productId = requireId(id, \"product\");\n return this.http.request({\n method: \"DELETE\",\n path: `/v1/products/${encodeURIComponent(productId)}`,\n schema: deletedProduct,\n });\n }\n\n /**\n * List Products (newest first). Cursor pagination: `limit` +\n * `starting_after`/`ending_before`; `created` becomes bracket query keys\n * and `ids` explicit indices (`ids[0]=...` — cannot combine `ids` with the\n * cursor params).\n *\n * Docs: https://docs.stripe.com/api/products/list\n *\n * @example\n * const page = await payweave.stripe.products.list({ active: true, limit: 50 });\n * console.log(page.data.length, page.has_more);\n */\n async list(query: ProductListQuery = {}) {\n const { ids, ...rest } = parseRequest(productListQuery, query);\n const q: Record<string, QueryValue> = flattenQuery(rest);\n ids?.forEach((id, i) => {\n q[`ids[${i}]`] = id;\n });\n return this.http.request({\n method: \"GET\",\n path: \"/v1/products\",\n query: q,\n schema: productListRes,\n });\n }\n\n /**\n * Async iterator over ALL Products matching `query`, transparently\n * following `has_more` with `starting_after = <last id>` (providers.md\n * §3.1). `ids` is not supported here — Stripe forbids combining it with\n * cursors; use {@link Products.list}.\n *\n * Docs: https://docs.stripe.com/api/products/list\n *\n * @example\n * for await (const prod of payweave.stripe.products.iterate({ active: true })) {\n * console.log(prod.id, prod.name);\n * }\n */\n async *iterate(query: Omit<ProductListQuery, \"ids\"> = {}) {\n const base = parseRequest(productListQuery, query);\n yield* iterateStripeList((startingAfter) =>\n this.http.request({\n method: \"GET\",\n path: \"/v1/products\",\n query: flattenQuery({ ...base, starting_after: startingAfter }),\n schema: productListRes,\n }),\n );\n }\n\n /**\n * Search Products with Stripe's search query language (e.g.\n * `active:'true' AND metadata['order_id']:'6735'`). Pagination is\n * TOKEN-based: pass the previous page's `next_page` as `page` (never\n * `starting_after`). Search is eventually consistent — don't use it in\n * read-after-write flows.\n *\n * Docs: https://docs.stripe.com/api/products/search\n *\n * @example\n * const found = await payweave.stripe.products.search({\n * query: \"metadata['pwv_reference']:'pwv_plan_pro'\",\n * });\n * console.log(found.data[0]?.id, found.has_more);\n */\n async search(input: ProductSearchReq) {\n const q = parseRequest(productSearchReq, input);\n return this.http.request({\n method: \"GET\",\n path: \"/v1/products/search\",\n query: flattenQuery(q),\n schema: productSearchRes,\n });\n }\n\n /**\n * Async iterator over ALL Products matching a search query, transparently\n * following `has_more` with `page = <next_page token>` — search pagination\n * differs from list pagination (https://docs.stripe.com/api/pagination/search).\n *\n * Docs: https://docs.stripe.com/api/products/search\n *\n * @example\n * for await (const prod of payweave.stripe.products.iterateSearch({\n * query: \"active:'true'\",\n * })) {\n * console.log(prod.id);\n * }\n */\n async *iterateSearch(input: ProductSearchReq) {\n const base = parseRequest(productSearchReq, input);\n yield* iterateStripeSearch((page) =>\n this.http.request({\n method: \"GET\",\n path: \"/v1/products/search\",\n query: flattenQuery({ ...base, page }),\n schema: productSearchRes,\n }),\n );\n }\n}\n","/**\n * Zod schemas for the Stripe Refunds module. Request fields are\n * sourced verbatim from the official API reference (all verified 2026-07-12):\n * - Create: https://docs.stripe.com/api/refunds/create\n * - Retrieve: https://docs.stripe.com/api/refunds/retrieve\n * - Update: https://docs.stripe.com/api/refunds/update\n * - Cancel: https://docs.stripe.com/api/refunds/cancel\n * - List: https://docs.stripe.com/api/refunds/list\n * - Object: https://docs.stripe.com/api/refunds/object\n *\n * `amount` is integer MINOR units end to end — no\n * conversion anywhere. Documented response fields whose child shapes we have\n * not fully verified against the reference (`destination_details`'s ~40\n * payment-method-specific hashes, `next_action.display_details`) are\n * deliberately kept loose/untyped in this P0 subset (conservative wins,\n * AGENTS.md §8). Response schemas are LOOSE: unknown fields pass through,\n * drift is logged, never thrown.\n */\nimport { z } from \"zod\";\nimport { createdRange, listCursorFields, metadataSchema } from \"../types\";\n\n/**\n * POST /v1/refunds — request\n * (https://docs.stripe.com/api/refunds/create — verified 2026-07-12).\n *\n * Per the docs, a Charge or PaymentIntent identifier is required unless\n * `origin: \"customer_balance\"` is provided — enforced here so an untargeted\n * refund fails BEFORE any network call (refunds move money; parse-before-send).\n */\nexport const refundCreateReq = z\n .object({\n /**\n * Positive integer in the smallest currency unit (minor units) — \"can\n * refund only up to the remaining, unrefunded amount of the charge\".\n * Omit to refund in full.\n */\n amount: z.number().int().positive().optional(),\n /** The identifier of the charge to refund (`ch_*`). */\n charge: z.string().optional(),\n /**\n * The identifier of the PaymentIntent to refund (`pi_*`) — the path the\n * unified layer uses (providers.md §3.3: refunds go against the payment\n * intent).\n */\n payment_intent: z.string().optional(),\n /**\n * Reason for the refund. If set: `duplicate` | `fraudulent` |\n * `requested_by_customer`.\n */\n reason: z.enum([\"duplicate\", \"fraudulent\", \"requested_by_customer\"]).optional(),\n /**\n * For payment methods without native refund support (e.g. Konbini,\n * PromptPay) — customer email to receive refund instructions.\n */\n instructions_email: z.string().optional(),\n metadata: metadataSchema.optional(),\n /**\n * Origin of the refund. `customer_balance` refunds from a Customer\n * Balance instead of a Charge/PaymentIntent — when provided, a\n * Charge/PaymentIntent identifier is not required.\n */\n origin: z.enum([\"customer_balance\"]).optional(),\n /**\n * Whether the application fee should be refunded too (refundable only by\n * the application that created the charge — Connect).\n */\n refund_application_fee: z.boolean().optional(),\n /**\n * Whether the transfer should be reversed when refunding (reversible only\n * by the application that created the charge — Connect).\n */\n reverse_transfer: z.boolean().optional(),\n })\n .refine(\n (v) =>\n v.charge !== undefined || v.payment_intent !== undefined || v.origin !== undefined,\n {\n message:\n \"one of charge, payment_intent, or origin is required \" +\n \"(https://docs.stripe.com/api/refunds/create)\",\n },\n );\nexport type RefundCreateReq = z.input<typeof refundCreateReq>;\n\n/**\n * POST /v1/refunds/{id} — request\n * (https://docs.stripe.com/api/refunds/update — verified 2026-07-12).\n * `metadata` is the ONLY updatable field on a refund; individual keys are\n * unset by posting an empty string value.\n */\nexport const refundUpdateReq = z.object({\n metadata: metadataSchema.optional(),\n});\nexport type RefundUpdateReq = z.input<typeof refundUpdateReq>;\n\n/**\n * GET /v1/refunds — query params\n * (https://docs.stripe.com/api/refunds/list — verified 2026-07-12).\n * `created` reaches the URL as bracket keys (`created[gte]`).\n */\nexport const refundListQuery = z.object({\n ...listCursorFields,\n /** Only return refunds for this Charge id. */\n charge: z.string().optional(),\n /** Only return refunds for this PaymentIntent id. */\n payment_intent: z.string().optional(),\n /** Creation-date window (Unix timestamps). */\n created: createdRange.optional(),\n});\nexport type RefundListQuery = z.input<typeof refundListQuery>;\n\n/**\n * A Refund as returned by every endpoint\n * (https://docs.stripe.com/api/refunds/object — verified 2026-07-12). LOOSE:\n * only stable documented fields are named; everything else passes through.\n * All amounts are integer minor units.\n *\n * Conservative-untyped child shapes: `destination_details`\n * (~40 payment-method-specific hashes, e.g. `card.reference_status`) and\n * `next_action` (`display_details.email_sent` etc.) stay loose objects;\n * expandable references (`balance_transaction`, `charge`, `payment_intent`,\n * `failure_balance_transaction`, `source_transfer_reversal`,\n * `transfer_reversal`) are id string OR expanded object — kept `unknown`.\n */\nexport const refund = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n amount: z.number().optional(),\n /** Balance transaction id string, or an expanded object — kept unknown. */\n balance_transaction: z.unknown().optional(),\n /** Charge id string, or an expanded object — kept unknown. */\n charge: z.unknown().optional(),\n created: z.number().optional(),\n currency: z.string().optional(),\n /** Non-card refunds only. */\n description: z.string().nullable().optional(),\n /** Transaction-specific details — child hashes deliberately untyped. */\n destination_details: z.looseObject({}).nullable().optional(),\n /** Balance transaction reversing the initial one after a failed refund. */\n failure_balance_transaction: z.unknown().optional(),\n /**\n * `lost_or_stolen_card` | `expired_or_canceled_card` |\n * `charge_for_pending_refund_disputed` | `insufficient_funds` | `declined` |\n * `merchant_request` | `unknown` — kept loose (drift logs, never throws).\n */\n failure_reason: z.string().nullable().optional(),\n instructions_email: z.string().nullable().optional(),\n metadata: z.record(z.string(), z.string()).nullable().optional(),\n /** Present when status is `requires_action` — child shape kept loose. */\n next_action: z.looseObject({}).nullable().optional(),\n /** PaymentIntent id string, or an expanded object — kept unknown. */\n payment_intent: z.unknown().optional(),\n /** `processing` | `insufficient_funds` | `charge_pending` — kept loose. */\n pending_reason: z.string().nullable().optional(),\n /**\n * `duplicate` | `fraudulent` | `requested_by_customer` or Stripe-generated\n * `expired_uncaptured_charge` — kept loose.\n */\n reason: z.string().nullable().optional(),\n receipt_number: z.string().nullable().optional(),\n /** Transfer reversal id string, or an expanded object — kept unknown. */\n source_transfer_reversal: z.unknown().optional(),\n /**\n * `pending` | `requires_action` | `succeeded` | `failed` | `canceled` —\n * normalization is the unified layer's job.\n */\n status: z.string().nullable().optional(),\n /** Transfer reversal id string, or an expanded object — kept unknown. */\n transfer_reversal: z.unknown().optional(),\n});\n","/**\n * Stripe Refunds resource (Surface A, `payweave.stripe.refunds`). Every method\n * validates its input with a request schema (throws\n * {@link PayweaveValidationError} before the network call — and therefore\n * before the form encoder runs) and passes a loose response schema to the\n * HttpClient (drift is logged, never thrown). Requests go to the wire as\n * `application/x-www-form-urlencoded` bracket notation; responses are bare\n * JSON resources — no envelope. All amounts are integer\n * minor units.\n *\n * Refunds MOVE MONEY: `create` is a bare POST and is therefore never\n * auto-retried — pass `idempotencyKey` to make it safely\n * replayable and retry-eligible.\n *\n * Docs: https://docs.stripe.com/api/refunds\n */\nimport type { HttpClient } from \"../../core/http\";\nimport {\n flattenQuery,\n iterateStripeList,\n parseRequest,\n requireId,\n stripeList,\n type StripeRequestOptions,\n} from \"../types\";\nimport {\n refund,\n refundCreateReq,\n refundListQuery,\n refundUpdateReq,\n type RefundCreateReq,\n type RefundListQuery,\n type RefundUpdateReq,\n} from \"../schemas/refunds\";\n\nconst refundListRes = stripeList(refund);\n\n/** Spread-helper: include `body` only when the parsed input has any pairs. */\nfunction bodyIfNonEmpty(body: Record<string, unknown>): { body?: unknown } {\n return Object.keys(body).length > 0 ? { body } : {};\n}\n\nexport class Refunds {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a refund. Target either a `charge` or a `payment_intent` (the\n * unified layer refunds against the payment intent — providers.md §3.3);\n * one of the two is required unless `origin: \"customer_balance\"`. `amount`\n * is integer MINOR units and defaults to the full remaining unrefunded\n * amount. Stripe errors if the target is already fully refunded (surfaced\n * as {@link PayweaveValidationError} with providerCode\n * `charge_already_refunded` on the 400).\n *\n * Money-moving POST: never auto-retried bare — pass `idempotencyKey` to\n * make it safely replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/refunds/create\n *\n * @example\n * const re = await payweave.stripe.refunds.create({\n * payment_intent: \"pi_123\",\n * amount: 500, // partial refund, minor units\n * reason: \"requested_by_customer\",\n * }, { idempotencyKey: \"order-8123-refund\" });\n * console.log(re.status); // \"succeeded\" | \"pending\" | ...\n */\n async create(input: RefundCreateReq, opts: StripeRequestOptions = {}) {\n const body = parseRequest(refundCreateReq, input);\n return this.http.request({\n method: \"POST\",\n path: \"/v1/refunds\",\n body,\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: refund,\n });\n }\n\n /**\n * Retrieve a refund by id (`re_*`). A 404 for an unknown id surfaces as\n * {@link PayweaveNotFoundError}.\n *\n * Docs: https://docs.stripe.com/api/refunds/retrieve\n *\n * @example\n * const re = await payweave.stripe.refunds.retrieve(\"re_123\");\n * if (re.status === \"succeeded\") { }\n */\n async retrieve(id: string) {\n const refundId = requireId(id, \"refund\");\n return this.http.request({\n method: \"GET\",\n path: `/v1/refunds/${encodeURIComponent(refundId)}`,\n schema: refund,\n });\n }\n\n /**\n * Update a refund. `metadata` is the ONLY updatable field; unset individual\n * keys by posting an empty string value.\n *\n * Docs: https://docs.stripe.com/api/refunds/update\n *\n * @example\n * const re = await payweave.stripe.refunds.update(\"re_123\", {\n * metadata: { order_id: \"6735\" },\n * });\n */\n async update(id: string, input: RefundUpdateReq = {}) {\n const refundId = requireId(id, \"refund\");\n const body = parseRequest(refundUpdateReq, input);\n return this.http.request({\n method: \"POST\",\n path: `/v1/refunds/${encodeURIComponent(refundId)}`,\n ...bodyIfNonEmpty(body),\n schema: refund,\n });\n }\n\n /**\n * Cancel a refund. ONLY valid while the refund's status is\n * `requires_action` — \"you can't cancel refunds in other states\" (only\n * refunds for payment methods that require customer action ever enter that\n * state); Stripe raises an error otherwise (surfaced as\n * {@link PayweaveValidationError} on the 400). Takes no body parameters.\n *\n * Docs: https://docs.stripe.com/api/refunds/cancel\n *\n * @example\n * const re = await payweave.stripe.refunds.cancel(\"re_123\");\n * console.log(re.status); // \"canceled\"\n */\n async cancel(id: string) {\n const refundId = requireId(id, \"refund\");\n return this.http.request({\n method: \"POST\",\n path: `/v1/refunds/${encodeURIComponent(refundId)}/cancel`,\n schema: refund,\n });\n }\n\n /**\n * List refunds (newest first). Filter by `charge` or `payment_intent`;\n * cursor pagination via `limit` + `starting_after`/`ending_before`; the\n * `created` window becomes bracket query keys (`created[gte]`).\n *\n * Docs: https://docs.stripe.com/api/refunds/list\n *\n * @example\n * const page = await payweave.stripe.refunds.list({ payment_intent: \"pi_123\", limit: 50 });\n * console.log(page.data.length, page.has_more);\n */\n async list(query: RefundListQuery = {}) {\n const q = parseRequest(refundListQuery, query);\n return this.http.request({\n method: \"GET\",\n path: \"/v1/refunds\",\n query: flattenQuery(q),\n schema: refundListRes,\n });\n }\n\n /**\n * Async iterator over ALL refunds matching `query`, transparently following\n * `has_more` with `starting_after = <last id>`.\n *\n * Docs: https://docs.stripe.com/api/refunds/list\n *\n * @example\n * for await (const re of payweave.stripe.refunds.iterate({ charge: \"ch_123\" })) {\n * console.log(re.id, re.status);\n * }\n */\n async *iterate(query: RefundListQuery = {}) {\n const base = parseRequest(refundListQuery, query);\n yield* iterateStripeList((startingAfter) =>\n this.http.request({\n method: \"GET\",\n path: \"/v1/refunds\",\n query: flattenQuery({ ...base, starting_after: startingAfter }),\n schema: refundListRes,\n }),\n );\n }\n}\n","/**\n * Zod schemas for the Stripe Subscription Items module. Request\n * fields are sourced verbatim from the official API reference (all verified\n * 2026-07-12):\n * - Create: https://docs.stripe.com/api/subscription_items/create\n * - Retrieve: https://docs.stripe.com/api/subscription_items/retrieve\n * - Update: https://docs.stripe.com/api/subscription_items/update\n * - Delete: https://docs.stripe.com/api/subscription_items/delete\n * - List: https://docs.stripe.com/api/subscription_items/list\n *\n * `unit_amount` is integer MINOR units end to end — no\n * conversion anywhere. Proration parameter names are copied EXACTLY from the\n * docs and never abstracted (PW-604 contract note). Response schemas are\n * LOOSE: unknown provider fields pass through, drift is logged, never thrown.\n *\n * This file also exports the request-param building blocks shared with the\n * `subscriptions` schemas (`price_data`, `discounts`, item\n * `billing_thresholds`) so the two modules never fork their shapes.\n */\nimport { z } from \"zod\";\nimport { listCursorFields, metadataSchema } from \"../types\";\n\n/**\n * `price_data.recurring` — billing frequency for an inline price\n * (https://docs.stripe.com/api/subscription_items/create — verified\n * 2026-07-12). Required inside `price_data`; `interval_count` maximum is\n * three years (3 years / 36 months / 156 weeks).\n */\nconst recurring = z.object({\n interval: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n interval_count: z.number().int().optional(),\n});\n\n/**\n * `price_data` — inline Price creation, the alternative to a saved `price` id\n * (https://docs.stripe.com/api/subscription_items/create — verified\n * 2026-07-12). Unlike Checkout's variant, `recurring` is REQUIRED here and\n * there is no inline `product_data`. `unit_amount` is integer minor units\n * (0 allowed for a free price); only one of `unit_amount` /\n * `unit_amount_decimal` may be set (enforced provider-side).\n */\nexport const subscriptionItemPriceData = z.object({\n /** Three-letter ISO currency code, lowercase (e.g. `usd`). Required. */\n currency: z.string(),\n /** Existing Product id (`prod_*`) this price belongs to. Required. */\n product: z.string(),\n /** Billing frequency. Required. */\n recurring,\n tax_behavior: z.enum([\"exclusive\", \"inclusive\", \"unspecified\"]).optional(),\n /** Amount in the smallest currency unit (minor units) — integer, unchanged. */\n unit_amount: z.number().int().nonnegative().optional(),\n /** Decimal string alternative to `unit_amount` (≤12 decimal places). */\n unit_amount_decimal: z.string().optional(),\n});\n\n/**\n * One `discounts[]` entry — a coupon, existing discount, or promotion code to\n * redeem (https://docs.stripe.com/api/subscription_items/create — verified\n * 2026-07-12). Exactly one of the three ids is expected provider-side.\n */\nexport const discountParam = z.object({\n /** Coupon id to create a new discount from. */\n coupon: z.string().optional(),\n /** Existing Discount id to reuse. */\n discount: z.string().optional(),\n /** Promotion code id to create a new discount from. */\n promotion_code: z.string().optional(),\n});\n\n/**\n * Per-item `billing_thresholds` — usage threshold that advances the\n * subscription to a new billing period\n * (https://docs.stripe.com/api/subscription_items/create — verified\n * 2026-07-12).\n */\nexport const itemBillingThresholds = z.object({\n usage_gte: z.number().int(),\n});\n\n/**\n * `payment_behavior` — how Stripe handles a payment required by the change\n * when `collection_method=charge_automatically`\n * (https://docs.stripe.com/api/subscription_items/create — verified\n * 2026-07-12).\n */\nconst paymentBehavior = z.enum([\n \"allow_incomplete\",\n \"default_incomplete\",\n \"error_if_incomplete\",\n \"pending_if_incomplete\",\n]);\n\n/**\n * `proration_behavior` — how to handle prorations resulting from the change\n * (https://docs.stripe.com/api/subscription_items/create — verified\n * 2026-07-12). Copied exactly; the default is `create_prorations`.\n */\nconst prorationBehavior = z.enum([\"always_invoice\", \"create_prorations\", \"none\"]);\n\n/**\n * POST /v1/subscription_items — request\n * (https://docs.stripe.com/api/subscription_items/create — verified\n * 2026-07-12).\n */\nexport const subscriptionItemCreateReq = z.object({\n /** Subscription id (`sub_*`) to add the item to. Required. */\n subscription: z.string().min(1),\n /** Saved Price id (`price_*`). Alternative to `price_data`. */\n price: z.string().optional(),\n /** Inline price definition. Alternative to `price`. */\n price_data: subscriptionItemPriceData.optional(),\n quantity: z.number().int().nonnegative().optional(),\n metadata: metadataSchema.optional(),\n billing_thresholds: itemBillingThresholds.optional(),\n /** Coupons/promotion codes to redeem into discounts for this item. */\n discounts: z.array(discountParam).optional(),\n payment_behavior: paymentBehavior.optional(),\n proration_behavior: prorationBehavior.optional(),\n /** Unix timestamp — prorate as though the update happened at this time. */\n proration_date: z.number().int().optional(),\n /** Tax Rate ids overriding the subscription's `default_tax_rates`. */\n tax_rates: z.array(z.string()).optional(),\n});\nexport type SubscriptionItemCreateReq = z.input<typeof subscriptionItemCreateReq>;\n\n/**\n * POST /v1/subscription_items/{id} — request\n * (https://docs.stripe.com/api/subscription_items/update — verified\n * 2026-07-12).\n */\nexport const subscriptionItemUpdateReq = z.object({\n /** Saved Price id (`price_*`). Alternative to `price_data`. */\n price: z.string().optional(),\n /** Inline price definition. Alternative to `price`. */\n price_data: subscriptionItemPriceData.optional(),\n quantity: z.number().int().nonnegative().optional(),\n metadata: metadataSchema.optional(),\n billing_thresholds: itemBillingThresholds.optional(),\n /** Coupons/promotion codes to redeem into discounts for this item. */\n discounts: z.array(discountParam).optional(),\n /** Customer is not in the flow — attempt payment immediately off-session. */\n off_session: z.boolean().optional(),\n payment_behavior: paymentBehavior.optional(),\n proration_behavior: prorationBehavior.optional(),\n /** Unix timestamp — prorate as though the update happened at this time. */\n proration_date: z.number().int().optional(),\n /** Tax Rate ids overriding the subscription's `default_tax_rates`. */\n tax_rates: z.array(z.string()).optional(),\n});\nexport type SubscriptionItemUpdateReq = z.input<typeof subscriptionItemUpdateReq>;\n\n/**\n * DELETE /v1/subscription_items/{id} — request\n * (https://docs.stripe.com/api/subscription_items/delete — verified\n * 2026-07-12). Deleting removes the price from the subscription; params ride\n * the DELETE as a form body, exactly like the docs' curl example.\n */\nexport const subscriptionItemDeleteReq = z.object({\n /** Delete all usage for the item — only when the price's `usage_type` is `metered`. */\n clear_usage: z.boolean().optional(),\n payment_behavior: paymentBehavior.optional(),\n proration_behavior: prorationBehavior.optional(),\n /** Unix timestamp — prorate as though the update happened at this time. */\n proration_date: z.number().int().optional(),\n});\nexport type SubscriptionItemDeleteReq = z.input<typeof subscriptionItemDeleteReq>;\n\n/**\n * GET /v1/subscription_items — query params\n * (https://docs.stripe.com/api/subscription_items/list — verified 2026-07-12).\n * `subscription` is REQUIRED — subscription items can only be listed per\n * subscription. Plain cursor pagination otherwise.\n */\nexport const subscriptionItemListQuery = z.object({\n ...listCursorFields,\n /** Subscription id (`sub_*`) whose items to list. Required. */\n subscription: z.string().min(1),\n});\nexport type SubscriptionItemListQuery = z.input<typeof subscriptionItemListQuery>;\n\n/**\n * A Subscription Item as returned by create/retrieve/update/list — and\n * embedded in `subscription.items.data[]`\n * (https://docs.stripe.com/api/subscription_items/object — verified\n * 2026-07-12). LOOSE: only stable documented fields are named; everything\n * else passes through.\n *\n * On the SDK's pinned API version (`2026-06-24.dahlia`),\n * `current_period_start`/`current_period_end` live HERE on the item — not on\n * the parent subscription object. EPIC 8's local billing state (PW-804/805)\n * reads the period boundaries from `items.data[].current_period_*`.\n */\nexport const subscriptionItem = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n /** Parent subscription id (`sub_*`). */\n subscription: z.string().optional(),\n /** The Price the customer is subscribed to — kept loose beyond its id. */\n price: z.looseObject({ id: z.string().optional() }).nullable().optional(),\n quantity: z.number().nullable().optional(),\n metadata: z.record(z.string(), z.string()).nullable().optional(),\n created: z.number().optional(),\n /** Start of the item's current billing period (Unix timestamp). */\n current_period_start: z.number().optional(),\n /** End of the item's current billing period (Unix timestamp). */\n current_period_end: z.number().optional(),\n /** Time period the item has been billed for — nullable, expandable. */\n billed_until: z.unknown().optional(),\n billing_thresholds: z.looseObject({}).nullable().optional(),\n /** Discount ids (or expanded objects) — kept unknown. */\n discounts: z.unknown().optional(),\n /** Tax Rate objects applied to this item — kept unknown. */\n tax_rates: z.unknown().optional(),\n});\n\n/**\n * DELETE /v1/subscription_items/{id} — response: the deletion\n * acknowledgement `{ id, object: \"subscription_item\", deleted: true }`\n * (https://docs.stripe.com/api/subscription_items/delete — verified\n * 2026-07-12). LOOSE like every response schema.\n */\nexport const subscriptionItemDeleted = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n deleted: z.boolean().optional(),\n});\n","/**\n * Stripe Subscription Items resource (Surface A,\n * `payweave.stripe.subscriptionItems`). Every method validates its input with\n * a request schema (throws {@link PayweaveValidationError} before the network\n * call — and therefore before the form encoder runs) and passes a loose\n * response schema to the HttpClient (drift is logged, never thrown). Requests\n * go to the wire as `application/x-www-form-urlencoded` bracket notation;\n * responses are bare JSON resources — no envelope. All\n * amounts are integer minor units.\n *\n * On the SDK's pinned API version, each item carries the billing-period\n * boundaries (`current_period_start`/`current_period_end`) that EPIC 8's\n * billing loop consumes — they are NOT on the parent subscription object.\n *\n * Docs: https://docs.stripe.com/api/subscription_items\n */\nimport type { HttpClient } from \"../../core/http\";\nimport {\n flattenQuery,\n iterateStripeList,\n parseRequest,\n requireId,\n stripeList,\n type StripeRequestOptions,\n} from \"../types\";\nimport {\n subscriptionItem,\n subscriptionItemCreateReq,\n subscriptionItemDeleted,\n subscriptionItemDeleteReq,\n subscriptionItemListQuery,\n subscriptionItemUpdateReq,\n type SubscriptionItemCreateReq,\n type SubscriptionItemDeleteReq,\n type SubscriptionItemListQuery,\n type SubscriptionItemUpdateReq,\n} from \"../schemas/subscription-items\";\n\nconst subscriptionItemListRes = stripeList(subscriptionItem);\n\n/** Spread-helper: include `body` only when the parsed input has any pairs. */\nfunction bodyIfNonEmpty(body: Record<string, unknown>): { body?: unknown } {\n return Object.keys(body).length > 0 ? { body } : {};\n}\n\nexport class SubscriptionItems {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Add a new item (price) to an existing subscription. Prorations follow\n * `proration_behavior` (default `create_prorations`). Pass `idempotencyKey`\n * to make the POST safely replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/subscription_items/create\n *\n * @example\n * const item = await payweave.stripe.subscriptionItems.create({\n * subscription: \"sub_123\",\n * price: \"price_123\",\n * quantity: 2,\n * }, { idempotencyKey: \"sub_123-addon-seat\" });\n * console.log(item.id, item.current_period_end);\n */\n async create(input: SubscriptionItemCreateReq, opts: StripeRequestOptions = {}) {\n const body = parseRequest(subscriptionItemCreateReq, input);\n return this.http.request({\n method: \"POST\",\n path: \"/v1/subscription_items\",\n body,\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: subscriptionItem,\n });\n }\n\n /**\n * Retrieve a subscription item by id (`si_*`). A 404 for an unknown id\n * surfaces as {@link PayweaveNotFoundError}.\n *\n * Docs: https://docs.stripe.com/api/subscription_items/retrieve\n *\n * @example\n * const item = await payweave.stripe.subscriptionItems.retrieve(\"si_123\");\n * console.log(item.price?.id, item.quantity);\n */\n async retrieve(id: string) {\n const itemId = requireId(id, \"subscription item\");\n return this.http.request({\n method: \"GET\",\n path: `/v1/subscription_items/${encodeURIComponent(itemId)}`,\n schema: subscriptionItem,\n });\n }\n\n /**\n * Update a subscription item — switch its `price`, change `quantity`, etc.\n * Proration parameters (`proration_behavior`, `proration_date`) are passed\n * through exactly as documented. Pass `idempotencyKey` to make the POST\n * safely replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/subscription_items/update\n *\n * @example\n * const item = await payweave.stripe.subscriptionItems.update(\"si_123\", {\n * quantity: 5,\n * proration_behavior: \"create_prorations\",\n * });\n */\n async update(\n id: string,\n input: SubscriptionItemUpdateReq = {},\n opts: StripeRequestOptions = {},\n ) {\n const itemId = requireId(id, \"subscription item\");\n const body = parseRequest(subscriptionItemUpdateReq, input);\n return this.http.request({\n method: \"POST\",\n path: `/v1/subscription_items/${encodeURIComponent(itemId)}`,\n ...bodyIfNonEmpty(body),\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: subscriptionItem,\n });\n }\n\n /**\n * Delete an item from its subscription — removing a price the customer was\n * subscribed to. Optional form params ride the DELETE (`clear_usage` only\n * for metered prices; prorations per `proration_behavior`). Returns the\n * `{ id, object, deleted: true }` acknowledgement. A subscription cannot\n * lose its last item this way — Stripe rejects that with a 400\n * (surfaced as {@link PayweaveValidationError}); cancel the subscription\n * instead.\n *\n * Docs: https://docs.stripe.com/api/subscription_items/delete\n *\n * @example\n * const gone = await payweave.stripe.subscriptionItems.delete(\"si_123\", {\n * proration_behavior: \"none\",\n * });\n * console.log(gone.deleted); // true\n */\n async delete(id: string, input: SubscriptionItemDeleteReq = {}) {\n const itemId = requireId(id, \"subscription item\");\n const body = parseRequest(subscriptionItemDeleteReq, input);\n return this.http.request({\n method: \"DELETE\",\n path: `/v1/subscription_items/${encodeURIComponent(itemId)}`,\n ...bodyIfNonEmpty(body),\n schema: subscriptionItemDeleted,\n });\n }\n\n /**\n * List the items of ONE subscription — `subscription` is required by the\n * API. Cursor pagination: `limit` + `starting_after`/`ending_before`.\n *\n * Docs: https://docs.stripe.com/api/subscription_items/list\n *\n * @example\n * const page = await payweave.stripe.subscriptionItems.list({\n * subscription: \"sub_123\",\n * limit: 10,\n * });\n * console.log(page.data.length, page.has_more);\n */\n async list(query: SubscriptionItemListQuery) {\n const q = parseRequest(subscriptionItemListQuery, query);\n return this.http.request({\n method: \"GET\",\n path: \"/v1/subscription_items\",\n query: flattenQuery(q),\n schema: subscriptionItemListRes,\n });\n }\n\n /**\n * Async iterator over ALL items of a subscription, transparently following\n * `has_more` with `starting_after = <last id>`.\n *\n * Docs: https://docs.stripe.com/api/subscription_items/list\n *\n * @example\n * for await (const item of payweave.stripe.subscriptionItems.iterate({ subscription: \"sub_123\" })) {\n * console.log(item.id, item.price?.id);\n * }\n */\n async *iterate(query: SubscriptionItemListQuery) {\n const base = parseRequest(subscriptionItemListQuery, query);\n yield* iterateStripeList((startingAfter) =>\n this.http.request({\n method: \"GET\",\n path: \"/v1/subscription_items\",\n query: flattenQuery({ ...base, starting_after: startingAfter }),\n schema: subscriptionItemListRes,\n }),\n );\n }\n}\n","/**\n * Zod schemas for the Stripe Subscriptions module. Request fields\n * are sourced verbatim from the official Billing API reference (all verified\n * 2026-07-12):\n * - Create: https://docs.stripe.com/api/subscriptions/create\n * - Retrieve: https://docs.stripe.com/api/subscriptions/retrieve\n * - Update: https://docs.stripe.com/api/subscriptions/update\n * - Cancel: https://docs.stripe.com/api/subscriptions/cancel\n * - Resume: https://docs.stripe.com/api/subscriptions/resume\n * - List: https://docs.stripe.com/api/subscriptions/list\n *\n * Cancel semantics (verified 2026-07-12): Stripe has\n * TWO cancellation shapes and this module exposes both faithfully —\n * 1. IMMEDIATE cancellation: `DELETE /v1/subscriptions/{id}`\n * (`subscriptions.cancel()`; optional `invoice_now` / `prorate` /\n * `cancellation_details` form params).\n * 2. END-OF-PERIOD cancellation: `cancel_at_period_end: true` via\n * `POST /v1/subscriptions/{id}` (`subscriptions.update()`) — the\n * subscription stays `active` until the period closes.\n * The local billing state machine depends on the distinction; they are never merged.\n *\n * Proration parameter names (`proration_behavior`, `proration_date`) are\n * copied EXACTLY from the docs, never abstracted.\n * Amounts are integer minor units end to end. Response\n * schemas are LOOSE: unknown provider fields pass through, drift is logged,\n * never thrown.\n *\n * Documented params whose child shapes we have NOT verified against the\n * reference are deliberately untyped in this P0 subset (conservative wins):\n * `add_invoice_items`,\n * `billing_cycle_anchor_config`, `billing_mode`, `billing_schedules`,\n * `invoice_settings`, `payment_settings`, `transfer_data`, `on_behalf_of`,\n * `application_fee_percent`, `customer_account`, and the list filters\n * `automatic_tax` / `customer_account` / `test_clock`. Add them with a docs\n * re-check when needed.\n */\nimport { z } from \"zod\";\nimport { createdRange, listCursorFields, metadataSchema, stripeList } from \"../types\";\nimport {\n discountParam,\n itemBillingThresholds,\n subscriptionItem,\n subscriptionItemPriceData,\n} from \"./subscription-items\";\n\n/**\n * One `items[]` entry on subscription CREATE — up to 20 items, each with an\n * attached price (https://docs.stripe.com/api/subscriptions/create — verified\n * 2026-07-12).\n */\nconst createItemParam = z.object({\n /** Saved Price id (`price_*`). Alternative to `price_data`. */\n price: z.string().optional(),\n /** Inline price definition (recurring required). Alternative to `price`. */\n price_data: subscriptionItemPriceData.optional(),\n quantity: z.number().int().nonnegative().optional(),\n metadata: metadataSchema.optional(),\n billing_thresholds: itemBillingThresholds.optional(),\n /** Coupons/promotion codes to redeem into discounts for this item. */\n discounts: z.array(discountParam).optional(),\n /** Tax Rate ids overriding the subscription's `default_tax_rates`. */\n tax_rates: z.array(z.string()).optional(),\n});\n\n/**\n * One `items[]` entry on subscription UPDATE\n * (https://docs.stripe.com/api/subscriptions/update — verified 2026-07-12).\n * `id` targets an existing subscription item; `deleted: true` removes it;\n * `clear_usage` drops accumulated usage for a metered price.\n */\nconst updateItemParam = z.object({\n /** Existing SubscriptionItem id (`si_*`) to update. */\n id: z.string().optional(),\n /** Saved Price id (`price_*`). Alternative to `price_data`. */\n price: z.string().optional(),\n /** Inline price definition (recurring required). Alternative to `price`. */\n price_data: subscriptionItemPriceData.optional(),\n quantity: z.number().int().nonnegative().optional(),\n metadata: metadataSchema.optional(),\n /** Set to `true` to delete the specified item. */\n deleted: z.boolean().optional(),\n /** Delete all usage for the item (metered prices). */\n clear_usage: z.boolean().optional(),\n billing_thresholds: itemBillingThresholds.optional(),\n /** Coupons/promotion codes to redeem into discounts for this item. */\n discounts: z.array(discountParam).optional(),\n /** Tax Rate ids overriding the subscription's `default_tax_rates`. */\n tax_rates: z.array(z.string()).optional(),\n});\n\n/**\n * `cancel_at` — Unix timestamp, or one of the documented symbolic values\n * (https://docs.stripe.com/api/subscriptions/create — verified 2026-07-12).\n */\nconst cancelAt = z.union([\n z.number().int(),\n z.enum([\"max_billed_until\", \"max_period_end\", \"min_period_end\"]),\n]);\n\n/**\n * `cancellation_details` — why the subscription is being canceled\n * (https://docs.stripe.com/api/subscriptions/cancel — verified 2026-07-12).\n */\nconst cancellationDetails = z.object({\n /** Additional comments about why the user canceled. */\n comment: z.string().optional(),\n /** The customer-submitted reason for cancellation. */\n feedback: z\n .enum([\n \"customer_service\",\n \"low_quality\",\n \"missing_features\",\n \"other\",\n \"switched_service\",\n \"too_complex\",\n \"too_expensive\",\n \"unused\",\n ])\n .optional(),\n});\n\n/**\n * `trial_end` — Unix timestamp, or the literal `\"now\"` to end the trial\n * immediately (https://docs.stripe.com/api/subscriptions/create — verified\n * 2026-07-12).\n */\nconst trialEnd = z.union([z.literal(\"now\"), z.number().int()]);\n\n/**\n * POST /v1/subscriptions — request\n * (https://docs.stripe.com/api/subscriptions/create — verified 2026-07-12).\n *\n * `payment_behavior` on CREATE is `allow_incomplete` | `default_incomplete` |\n * `error_if_incomplete` (`pending_if_incomplete` is update-only), and\n * `proration_behavior` on CREATE is `create_prorations` | `none`\n * (`always_invoice` is not available at creation) — both narrower than their\n * update counterparts, copied exactly from the create page.\n */\nexport const subscriptionCreateReq = z.object({\n /**\n * Customer id (`cus_*`) to subscribe. Stripe requires a customer (the\n * unverified `customer_account` alternative is untyped in this P0 subset).\n */\n customer: z.string().optional(),\n /** Items being subscribed to — up to 20, each with an attached price. Required. */\n items: z.array(createItemParam).max(20),\n /** Past Unix timestamp to backdate the subscription's start date to. */\n backdate_start_date: z.number().int().optional(),\n /** Future Unix timestamp anchoring the billing cycle (first full invoice). */\n billing_cycle_anchor: z.number().int().optional(),\n /** Unix timestamp or symbolic value at which to auto-cancel. */\n cancel_at: cancelAt.optional(),\n /** Cancel at the end of the current period instead of immediately. Default false. */\n cancel_at_period_end: z.boolean().optional(),\n collection_method: z.enum([\"charge_automatically\", \"send_invoice\"]).optional(),\n /** Three-letter ISO currency code, lowercase. */\n currency: z.string().optional(),\n /** Days until invoices are due — `send_invoice` collection only. */\n days_until_due: z.number().int().optional(),\n /** PaymentMethod id (`pm_*`) used as this subscription's default. */\n default_payment_method: z.string().optional(),\n /** Source id used as this subscription's default payment source. */\n default_source: z.string().optional(),\n /** Tax Rate ids applied by default to the subscription's items. */\n default_tax_rates: z.array(z.string()).optional(),\n /** ≤500 chars, displayable to customers. */\n description: z.string().max(500).optional(),\n /** Coupons/promotion codes to redeem into discounts for the subscription. */\n discounts: z.array(discountParam).optional(),\n metadata: metadataSchema.optional(),\n /** Customer is not in the checkout flow. Default false. */\n off_session: z.boolean().optional(),\n payment_behavior: z\n .enum([\"allow_incomplete\", \"default_incomplete\", \"error_if_incomplete\"])\n .optional(),\n /** Invoice-pending-items schedule between billing cycles. */\n pending_invoice_item_interval: z\n .object({\n interval: z.enum([\"day\", \"month\", \"week\", \"year\"]),\n interval_count: z.number().int().optional(),\n })\n .optional(),\n proration_behavior: z.enum([\"create_prorations\", \"none\"]).optional(),\n /** Unix timestamp or `\"now\"` — when the trial ends. */\n trial_end: trialEnd.optional(),\n /** Use the price's/plan's trial period. Default false. */\n trial_from_plan: z.boolean().optional(),\n /** Trial length in days (alternative to `trial_end`). */\n trial_period_days: z.number().int().optional(),\n /** What happens at trial end when no payment method is present. */\n trial_settings: z\n .object({\n end_behavior: z.object({\n missing_payment_method: z.enum([\"cancel\", \"create_invoice\", \"pause\"]),\n }),\n })\n .optional(),\n});\nexport type SubscriptionCreateReq = z.input<typeof subscriptionCreateReq>;\n\n/**\n * `pause_collection` — pause PAYMENT COLLECTION while the subscription stays\n * `active` (https://docs.stripe.com/api/subscriptions/update — verified\n * 2026-07-12). Distinct from the `paused` subscription STATUS, which is what\n * `subscriptions.resume()` acts on. Pass the empty string `\"\"` to unset and\n * resume collection (https://docs.stripe.com/billing/subscriptions/pause-payment\n * — verified 2026-07-12: \"update the subscription and unset\n * `pause_collection`\", curl `-d \"pause_collection\"=`).\n */\nconst pauseCollection = z.union([\n z.object({\n behavior: z.enum([\"keep_as_draft\", \"mark_uncollectible\", \"void\"]),\n /** Unix timestamp at which collection automatically resumes. */\n resumes_at: z.number().int().optional(),\n }),\n z.literal(\"\"),\n]);\n\n/**\n * POST /v1/subscriptions/{id} — request\n * (https://docs.stripe.com/api/subscriptions/update — verified 2026-07-12).\n *\n * `{ cancel_at_period_end: true }` here is the END-OF-PERIOD cancellation\n * path; `subscriptions.cancel()` (DELETE) is the immediate one — see the\n * module JSDoc.\n */\nexport const subscriptionUpdateReq = z.object({\n /** Item changes: update by `id`, add by `price`, remove with `deleted: true`. */\n items: z.array(updateItemParam).optional(),\n /** Unix timestamp or symbolic value at which to auto-cancel. */\n cancel_at: cancelAt.optional(),\n /** `true` = cancel when the current period ends; `false` = clear a pending one. */\n cancel_at_period_end: z.boolean().optional(),\n cancellation_details: cancellationDetails.optional(),\n /** `now` resets the billing cycle anchor; `unchanged` keeps it. */\n billing_cycle_anchor: z.enum([\"now\", \"unchanged\"]).optional(),\n collection_method: z.enum([\"charge_automatically\", \"send_invoice\"]).optional(),\n /** Days until invoices are due — `send_invoice` collection only. */\n days_until_due: z.number().int().optional(),\n /** PaymentMethod id (`pm_*`) used as this subscription's default. */\n default_payment_method: z.string().optional(),\n /** ≤500 chars, displayable to customers. */\n description: z.string().max(500).optional(),\n /** Coupons/promotion codes to redeem into discounts for the subscription. */\n discounts: z.array(discountParam).optional(),\n metadata: metadataSchema.optional(),\n /** Customer is not in the checkout flow. Default false. */\n off_session: z.boolean().optional(),\n /** Pause payment collection (subscription stays `active`); `\"\"` unsets. */\n pause_collection: pauseCollection.optional(),\n payment_behavior: z\n .enum([\n \"allow_incomplete\",\n \"default_incomplete\",\n \"error_if_incomplete\",\n \"pending_if_incomplete\",\n ])\n .optional(),\n proration_behavior: z.enum([\"always_invoice\", \"create_prorations\", \"none\"]).optional(),\n /** Unix timestamp — prorate as though the update happened at this time. */\n proration_date: z.number().int().optional(),\n /** Unix timestamp or `\"now\"` — when the trial ends. */\n trial_end: trialEnd.optional(),\n});\nexport type SubscriptionUpdateReq = z.input<typeof subscriptionUpdateReq>;\n\n/**\n * DELETE /v1/subscriptions/{id} — request (IMMEDIATE cancellation,\n * https://docs.stripe.com/api/subscriptions/cancel — verified 2026-07-12).\n * Params ride the DELETE as a form body, exactly like the docs' curl example.\n */\nexport const subscriptionCancelReq = z.object({\n cancellation_details: cancellationDetails.optional(),\n /** Generate a final invoice for un-invoiced metered usage and pending prorations. Default false. */\n invoice_now: z.boolean().optional(),\n /** Credit remaining unused time until the period end via a proration item. Default false. */\n prorate: z.boolean().optional(),\n});\nexport type SubscriptionCancelReq = z.input<typeof subscriptionCancelReq>;\n\n/**\n * POST /v1/subscriptions/{id}/resume — request\n * (https://docs.stripe.com/api/subscriptions/resume — verified 2026-07-12).\n * Only for subscriptions with STATUS `paused` (e.g. a trial that ended under\n * `trial_settings.end_behavior.missing_payment_method: \"pause\"`) using\n * `charge_automatically` collection. `billing_cycle_anchor` defaults to\n * `now`; when it is `now`, no prorations are generated.\n */\nexport const subscriptionResumeReq = z.object({\n /** `now` resets the anchor and starts a new period; `unchanged` keeps it. Default `now`. */\n billing_cycle_anchor: z.enum([\"now\", \"unchanged\"]).optional(),\n proration_behavior: z.enum([\"always_invoice\", \"create_prorations\", \"none\"]).optional(),\n /** Unix timestamp — prorate as though resumed at this time. */\n proration_date: z.number().int().optional(),\n});\nexport type SubscriptionResumeReq = z.input<typeof subscriptionResumeReq>;\n\n/**\n * GET /v1/subscriptions — query params\n * (https://docs.stripe.com/api/subscriptions/list — verified 2026-07-12).\n * Range filters (`created`, `current_period_start`, `current_period_end`)\n * reach the URL as bracket keys (`created[gte]`); list filters are QUERY\n * params, never form body.\n */\nexport const subscriptionListQuery = z.object({\n ...listCursorFields,\n /** Filter by Customer id. */\n customer: z.string().optional(),\n /** Filter by recurring Price id. */\n price: z.string().optional(),\n /**\n * Status filter. Documented special values (verified 2026-07-12):\n * `canceled` (includes deleted customers' subscriptions), `ended` (canceled\n * + expired due to incomplete payment), `all`; omitted = all non-canceled\n * subscriptions. Kept as an open string — the docs page does not enumerate\n * a closed value set for this filter (conservative); Stripe\n * validates server-side.\n */\n status: z.string().optional(),\n collection_method: z.enum([\"charge_automatically\", \"send_invoice\"]).optional(),\n /** Creation-date window (Unix timestamps). */\n created: createdRange.optional(),\n /** Current-period-start window (Unix timestamps). */\n current_period_start: createdRange.optional(),\n /** Current-period-end window (Unix timestamps). */\n current_period_end: createdRange.optional(),\n});\nexport type SubscriptionListQuery = z.input<typeof subscriptionListQuery>;\n\n/**\n * A Subscription as returned by every endpoint\n * (https://docs.stripe.com/api/subscriptions/object — verified 2026-07-12).\n * LOOSE: only stable documented fields are named; everything else passes\n * through. `status` and the period boundaries feed the local billing\n * state and correlate with the `customer.subscription.*` webhook\n * payloads.\n *\n * NOTE (verified 2026-07-12): on the SDK's pinned API version\n * (`2026-06-24.dahlia`) `current_period_start`/`current_period_end` are NOT\n * top-level subscription fields — they live on each embedded item at\n * `items.data[].current_period_start/end` (`schemas/subscription-items.ts`).\n */\nexport const subscription = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n /**\n * `incomplete` | `incomplete_expired` | `trialing` | `active` | `past_due`\n * | `canceled` | `unpaid` | `paused` — normalization is the unified layer's\n * job.\n */\n status: z.string().optional(),\n /** Customer id string, or an expanded object — kept unknown. */\n customer: z.unknown().optional(),\n /** Embedded (paginated) list of the subscription's items. */\n items: stripeList(subscriptionItem).optional(),\n currency: z.string().optional(),\n collection_method: z.string().optional(),\n /** Unix timestamp at which the subscription will auto-cancel. */\n cancel_at: z.number().nullable().optional(),\n /** Whether the subscription cancels when the current period ends. */\n cancel_at_period_end: z.boolean().optional(),\n /** When the cancellation was requested (Unix timestamp). */\n canceled_at: z.number().nullable().optional(),\n /** `{ reason, feedback, comment }` — kept loose. */\n cancellation_details: z.looseObject({}).nullable().optional(),\n created: z.number().optional(),\n /** Start of the subscription (may differ from `created` when backdated). */\n start_date: z.number().optional(),\n /** Anchor aligning future billing cycle dates (Unix timestamp). */\n billing_cycle_anchor: z.number().optional(),\n trial_start: z.number().nullable().optional(),\n trial_end: z.number().nullable().optional(),\n /** When the subscription ended (Unix timestamp). */\n ended_at: z.number().nullable().optional(),\n /** Latest Invoice id string, or an expanded object — kept unknown. */\n latest_invoice: z.unknown().optional(),\n /** Default PaymentMethod id string, or an expanded object — kept unknown. */\n default_payment_method: z.unknown().optional(),\n days_until_due: z.number().nullable().optional(),\n /** Payment-collection pause state — `{ behavior, resumes_at }`, kept loose. */\n pause_collection: z.looseObject({}).nullable().optional(),\n metadata: z.record(z.string(), z.string()).nullable().optional(),\n description: z.string().nullable().optional(),\n livemode: z.boolean().optional(),\n});\n","/**\n * Stripe Subscriptions resource (Surface A, `payweave.stripe.subscriptions`).\n * Every method validates its input with a request schema (throws\n * {@link PayweaveValidationError} before the network call — and therefore\n * before the form encoder runs) and passes a loose response schema to the\n * HttpClient (drift is logged, never thrown). Requests go to the wire as\n * `application/x-www-form-urlencoded` bracket notation; responses are bare\n * JSON resources — no envelope. All amounts are integer\n * minor units.\n *\n * Cancellation is exposed as Stripe documents it, never merged (PW-604\n * contract note):\n * - `cancel(id)` — IMMEDIATE: `DELETE /v1/subscriptions/{id}`.\n * - `update(id, { cancel_at_period_end: true })` — END-OF-PERIOD: the\n * subscription stays `active` until the period closes.\n * - `resume(id)` — only for STATUS `paused` subscriptions; unpausing payment\n * COLLECTION is `update(id, { pause_collection: \"\" })` instead.\n *\n * Docs: https://docs.stripe.com/api/subscriptions\n */\nimport type { HttpClient } from \"../../core/http\";\nimport {\n flattenQuery,\n iterateStripeList,\n parseRequest,\n requireId,\n stripeList,\n type StripeRequestOptions,\n} from \"../types\";\nimport {\n subscription,\n subscriptionCancelReq,\n subscriptionCreateReq,\n subscriptionListQuery,\n subscriptionResumeReq,\n subscriptionUpdateReq,\n type SubscriptionCancelReq,\n type SubscriptionCreateReq,\n type SubscriptionListQuery,\n type SubscriptionResumeReq,\n type SubscriptionUpdateReq,\n} from \"../schemas/subscriptions\";\n\nconst subscriptionListRes = stripeList(subscription);\n\n/** Spread-helper: include `body` only when the parsed input has any pairs. */\nfunction bodyIfNonEmpty(body: Record<string, unknown>): { body?: unknown } {\n return Object.keys(body).length > 0 ? { body } : {};\n}\n\nexport class Subscriptions {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a subscription for an existing customer — the first invoice is\n * attempted immediately unless a trial or `billing_cycle_anchor` defers it.\n * `items` (up to 20, each with a `price` or inline `price_data`) is\n * required. Pass `idempotencyKey` to make the POST safely replayable (and\n * retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/subscriptions/create\n *\n * @example\n * const sub = await payweave.stripe.subscriptions.create({\n * customer: \"cus_123\",\n * items: [{ price: \"price_123\", quantity: 1 }],\n * metadata: { pwv_plan: \"pro\" },\n * }, { idempotencyKey: \"sub-cus_123-pro\" });\n * console.log(sub.status, sub.items?.data[0]?.current_period_end);\n */\n async create(input: SubscriptionCreateReq, opts: StripeRequestOptions = {}) {\n const body = parseRequest(subscriptionCreateReq, input);\n return this.http.request({\n method: \"POST\",\n path: \"/v1/subscriptions\",\n body,\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: subscription,\n });\n }\n\n /**\n * Retrieve a subscription by id (`sub_*`). A 404 for an unknown id surfaces\n * as {@link PayweaveNotFoundError}. Period boundaries live on the embedded\n * items (`sub.items.data[].current_period_start/end`) on the SDK's pinned\n * API version.\n *\n * Docs: https://docs.stripe.com/api/subscriptions/retrieve\n *\n * @example\n * const sub = await payweave.stripe.subscriptions.retrieve(\"sub_123\");\n * if (sub.status === \"active\") { }\n */\n async retrieve(id: string) {\n const subscriptionId = requireId(id, \"subscription\");\n return this.http.request({\n method: \"GET\",\n path: `/v1/subscriptions/${encodeURIComponent(subscriptionId)}`,\n schema: subscription,\n });\n }\n\n /**\n * Update a subscription: change items/quantities (proration per\n * `proration_behavior`), schedule an END-OF-PERIOD cancellation with\n * `cancel_at_period_end: true` (or clear one with `false`), pause payment\n * collection with `pause_collection` (unset with `\"\"` to resume\n * collection), etc. For IMMEDIATE cancellation use {@link cancel} instead.\n * Pass `idempotencyKey` to make the POST safely replayable (and\n * retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/subscriptions/update\n *\n * @example\n * // Cancel when the current billing period ends — NOT immediate:\n * const sub = await payweave.stripe.subscriptions.update(\"sub_123\", {\n * cancel_at_period_end: true,\n * });\n * console.log(sub.status, sub.cancel_at_period_end); // \"active\", true\n */\n async update(\n id: string,\n input: SubscriptionUpdateReq = {},\n opts: StripeRequestOptions = {},\n ) {\n const subscriptionId = requireId(id, \"subscription\");\n const body = parseRequest(subscriptionUpdateReq, input);\n return this.http.request({\n method: \"POST\",\n path: `/v1/subscriptions/${encodeURIComponent(subscriptionId)}`,\n ...bodyIfNonEmpty(body),\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: subscription,\n });\n }\n\n /**\n * Cancel a subscription IMMEDIATELY (`DELETE /v1/subscriptions/{id}`) —\n * the customer is not charged again, and pending prorations are dropped\n * unless `invoice_now`/`prorate` say otherwise. To cancel at the END of the\n * current period instead, use\n * `update(id, { cancel_at_period_end: true })` — the two shapes are\n * distinct on Stripe and PW-805's state machine relies on that.\n *\n * Docs: https://docs.stripe.com/api/subscriptions/cancel\n *\n * @example\n * const sub = await payweave.stripe.subscriptions.cancel(\"sub_123\", {\n * invoice_now: true,\n * prorate: true,\n * cancellation_details: { feedback: \"too_expensive\" },\n * });\n * console.log(sub.status); // \"canceled\"\n */\n async cancel(id: string, input: SubscriptionCancelReq = {}) {\n const subscriptionId = requireId(id, \"subscription\");\n const body = parseRequest(subscriptionCancelReq, input);\n return this.http.request({\n method: \"DELETE\",\n path: `/v1/subscriptions/${encodeURIComponent(subscriptionId)}`,\n ...bodyIfNonEmpty(body),\n schema: subscription,\n });\n }\n\n /**\n * Resume a subscription whose STATUS is `paused` (e.g. a trial that ended\n * with `trial_settings.end_behavior.missing_payment_method: \"pause\"`) —\n * only available under `charge_automatically` collection. Not for paused\n * payment COLLECTION: unset that via\n * `update(id, { pause_collection: \"\" })`. `billing_cycle_anchor` defaults\n * to `now` (resets the cycle; no prorations); `unchanged` keeps the anchor\n * and prorates per `proration_behavior`. Pass `idempotencyKey` to make the\n * POST safely replayable (and retry-eligible).\n *\n * Docs: https://docs.stripe.com/api/subscriptions/resume\n *\n * @example\n * const sub = await payweave.stripe.subscriptions.resume(\"sub_123\", {\n * billing_cycle_anchor: \"now\",\n * });\n * console.log(sub.status); // \"active\"\n */\n async resume(\n id: string,\n input: SubscriptionResumeReq = {},\n opts: StripeRequestOptions = {},\n ) {\n const subscriptionId = requireId(id, \"subscription\");\n const body = parseRequest(subscriptionResumeReq, input);\n return this.http.request({\n method: \"POST\",\n path: `/v1/subscriptions/${encodeURIComponent(subscriptionId)}/resume`,\n ...bodyIfNonEmpty(body),\n ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),\n schema: subscription,\n });\n }\n\n /**\n * List subscriptions. By default only non-canceled subscriptions are\n * returned — pass `status: \"canceled\"`, `\"ended\"`, or `\"all\"` to widen.\n * Filters are query params; range filters become bracket keys\n * (`current_period_end[gte]`).\n *\n * Docs: https://docs.stripe.com/api/subscriptions/list\n *\n * @example\n * const page = await payweave.stripe.subscriptions.list({\n * customer: \"cus_123\",\n * status: \"all\",\n * limit: 50,\n * });\n * console.log(page.data.length, page.has_more);\n */\n async list(query: SubscriptionListQuery = {}) {\n const q = parseRequest(subscriptionListQuery, query);\n return this.http.request({\n method: \"GET\",\n path: \"/v1/subscriptions\",\n query: flattenQuery(q),\n schema: subscriptionListRes,\n });\n }\n\n /**\n * Async iterator over ALL subscriptions matching `query`, transparently\n * following `has_more` with `starting_after = <last id>`.\n *\n * Docs: https://docs.stripe.com/api/subscriptions/list\n *\n * @example\n * for await (const sub of payweave.stripe.subscriptions.iterate({ customer: \"cus_123\" })) {\n * console.log(sub.id, sub.status);\n * }\n */\n async *iterate(query: SubscriptionListQuery = {}) {\n const base = parseRequest(subscriptionListQuery, query);\n yield* iterateStripeList((startingAfter) =>\n this.http.request({\n method: \"GET\",\n path: \"/v1/subscriptions\",\n query: flattenQuery({ ...base, starting_after: startingAfter }),\n schema: subscriptionListRes,\n }),\n );\n }\n}\n","/**\n * Zod schemas for the Stripe WebhookEndpoints module. Request fields\n * are sourced verbatim from the official API reference (all verified\n * 2026-07-12):\n * - Create: https://docs.stripe.com/api/webhook_endpoints/create\n * - Retrieve: https://docs.stripe.com/api/webhook_endpoints/retrieve\n * - Update: https://docs.stripe.com/api/webhook_endpoints/update\n * - Delete: https://docs.stripe.com/api/webhook_endpoints/delete\n * - List: https://docs.stripe.com/api/webhook_endpoints/list\n * - Object: https://docs.stripe.com/api/webhook_endpoints/object\n *\n * SECRET HANDLING: the endpoint's signing secret (`whsec_*`)\n * is \"Only returned at creation\" (object docs, verified 2026-07-12) — the\n * response schema names `secret` so `create` callers can capture it ONCE;\n * retrieve/update/list responses never carry it. Core `redact` masks any\n * `secret`-named key (`/secret/i`), so the value never survives into logs or\n * `PayweaveError.toJSON()`. Fixtures only ever contain clearly-fake\n * placeholders. Response schemas are LOOSE: unknown fields pass through,\n * drift is logged, never thrown.\n */\nimport { z } from \"zod\";\nimport { listCursorFields, metadataSchema } from \"../types\";\n\n/**\n * `enabled_events` — the list of event types to enable (`[\"*\"]` enables all\n * events except those that require explicit selection). Event names are an\n * open, version-dependent enum on Stripe's side — kept `string` here\n * (conservative, AGENTS.md §8). Non-empty: an endpoint must listen to\n * something, and the form encoder emits no pairs for an empty array.\n */\nconst enabledEvents = z.array(z.string()).min(1);\n\n/**\n * POST /v1/webhook_endpoints — request\n * (https://docs.stripe.com/api/webhook_endpoints/create — verified 2026-07-12).\n */\nexport const webhookEndpointCreateReq = z.object({\n /** The URL of the webhook endpoint. Required. */\n url: z.string(),\n /**\n * The list of events to enable for this endpoint; `[\"*\"]` enables all\n * events except those that require explicit selection. Required. Encodes as\n * `enabled_events[0]=...`.\n */\n enabled_events: enabledEvents,\n /**\n * Events sent to this endpoint are rendered with this Stripe version\n * instead of the account default.\n */\n api_version: z.string().optional(),\n /**\n * `true` = receive events from connected accounts; `false` (default) = from\n * your own account.\n */\n connect: z.boolean().optional(),\n /** Optional description of what the webhook is used for. */\n description: z.string().optional(),\n metadata: metadataSchema.optional(),\n});\nexport type WebhookEndpointCreateReq = z.input<typeof webhookEndpointCreateReq>;\n\n/**\n * POST /v1/webhook_endpoints/{id} — request\n * (https://docs.stripe.com/api/webhook_endpoints/update — verified 2026-07-12).\n */\nexport const webhookEndpointUpdateReq = z.object({\n /** Optional description of what the webhook is used for. */\n description: z.string().optional(),\n /** Disable the webhook endpoint if set to true. */\n disabled: z.boolean().optional(),\n /** Replacement list of enabled events (`[\"*\"]` = all). */\n enabled_events: enabledEvents.optional(),\n metadata: metadataSchema.optional(),\n /** The URL of the webhook endpoint. */\n url: z.string().optional(),\n});\nexport type WebhookEndpointUpdateReq = z.input<typeof webhookEndpointUpdateReq>;\n\n/**\n * GET /v1/webhook_endpoints — query params\n * (https://docs.stripe.com/api/webhook_endpoints/list — verified 2026-07-12).\n * Cursor pagination only — no other documented filters.\n */\nexport const webhookEndpointListQuery = z.object({\n ...listCursorFields,\n});\nexport type WebhookEndpointListQuery = z.input<typeof webhookEndpointListQuery>;\n\n/**\n * A WebhookEndpoint as returned by create/retrieve/update/list\n * (https://docs.stripe.com/api/webhook_endpoints/object — verified\n * 2026-07-12). LOOSE: only stable documented fields are named; everything\n * else passes through.\n */\nexport const webhookEndpoint = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n /** API version events are rendered as for this endpoint. */\n api_version: z.string().nullable().optional(),\n /** ID of the associated Connect application. */\n application: z.string().nullable().optional(),\n created: z.number().optional(),\n description: z.string().nullable().optional(),\n /** `[\"*\"]` indicates all events (except explicit-selection ones). */\n enabled_events: z.array(z.string()).optional(),\n livemode: z.boolean().optional(),\n metadata: z.record(z.string(), z.string()).nullable().optional(),\n /**\n * The endpoint's signing secret (`whsec_*`), used to verify webhook\n * signatures. ⚠️ \"Only returned at creation\"\n * (https://docs.stripe.com/api/webhook_endpoints/object — verified\n * 2026-07-12) — capture it from the `create` response or it is gone;\n * retrieve/update/list never include it. Store it as the provider config's\n * `webhookSecret`; core `redact` masks it from all logs.\n */\n secret: z.string().optional(),\n /** `enabled` | `disabled` — kept loose (drift logs, never throws). */\n status: z.string().optional(),\n url: z.string().optional(),\n});\n\n/**\n * DELETE /v1/webhook_endpoints/{id} — response\n * (https://docs.stripe.com/api/webhook_endpoints/delete — verified\n * 2026-07-12): \"An object with the deleted webhook endpoint's ID\"\n * (`{ id, object, deleted: true }`).\n */\nexport const webhookEndpointDeleted = z.looseObject({\n id: z.string(),\n object: z.string().optional(),\n deleted: z.boolean().optional(),\n});\n","/**\n * Stripe WebhookEndpoints resource (Surface A,\n * `payweave.stripe.webhookEndpoints`). Plain REST management of webhook\n * endpoints — signature VERIFICATION lives in `src/webhooks/stripe.ts`\n * and is deliberately kept apart. `payweave listen`\n * provisions endpoints through `create` and tears them down through `delete`.\n *\n * Every method validates its input with a request schema (throws\n * {@link PayweaveValidationError} before the network call) and passes a loose\n * response schema to the HttpClient (drift is logged, never thrown). Requests\n * go to the wire as `application/x-www-form-urlencoded` bracket notation;\n * responses are bare JSON resources — no envelope.\n *\n * ⚠️ SECRET: the `create` response is the ONLY one carrying the endpoint's\n * `whsec_*` signing secret (\"Only returned at creation\" —\n * https://docs.stripe.com/api/webhook_endpoints/object, verified 2026-07-12).\n * Capture it immediately; core `redact` keeps it out of logs.\n *\n * Docs: https://docs.stripe.com/api/webhook_endpoints\n */\nimport type { HttpClient } from \"../../core/http\";\nimport {\n flattenQuery,\n iterateStripeList,\n parseRequest,\n requireId,\n stripeList,\n} from \"../types\";\nimport {\n webhookEndpoint,\n webhookEndpointCreateReq,\n webhookEndpointDeleted,\n webhookEndpointListQuery,\n webhookEndpointUpdateReq,\n type WebhookEndpointCreateReq,\n type WebhookEndpointListQuery,\n type WebhookEndpointUpdateReq,\n} from \"../schemas/webhook-endpoints\";\n\nconst webhookEndpointListRes = stripeList(webhookEndpoint);\n\n/** Spread-helper: include `body` only when the parsed input has any pairs. */\nfunction bodyIfNonEmpty(body: Record<string, unknown>): { body?: unknown } {\n return Object.keys(body).length > 0 ? { body } : {};\n}\n\nexport class WebhookEndpoints {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a webhook endpoint. `url` and `enabled_events` are required;\n * `enabled_events` bracket-encodes as `enabled_events[0]=...` and `[\"*\"]`\n * enables all events (except those requiring explicit selection).\n *\n * ⚠️ The response is the ONLY place the endpoint's `whsec_*` signing\n * `secret` is ever returned (\"Only returned at creation\") — persist it\n * immediately (e.g. as the `stripe.webhookSecret` config) or it cannot be\n * recovered; retrieve/update/list responses never include it.\n *\n * Docs: https://docs.stripe.com/api/webhook_endpoints/create\n *\n * @example\n * const we = await payweave.stripe.webhookEndpoints.create({\n * url: \"https://example.com/payweave/webhooks\",\n * enabled_events: [\"checkout.session.completed\", \"payment_intent.succeeded\"],\n * });\n * const signingSecret = we.secret; // whsec_* — shown ONCE, store it now\n */\n async create(input: WebhookEndpointCreateReq) {\n const body = parseRequest(webhookEndpointCreateReq, input);\n return this.http.request({\n method: \"POST\",\n path: \"/v1/webhook_endpoints\",\n body,\n schema: webhookEndpoint,\n });\n }\n\n /**\n * Retrieve a webhook endpoint by id (`we_*`). The response does NOT include\n * the signing `secret` (create-only). A 404 for an unknown id surfaces as\n * {@link PayweaveNotFoundError}.\n *\n * Docs: https://docs.stripe.com/api/webhook_endpoints/retrieve\n *\n * @example\n * const we = await payweave.stripe.webhookEndpoints.retrieve(\"we_123\");\n * console.log(we.status, we.enabled_events);\n */\n async retrieve(id: string) {\n const endpointId = requireId(id, \"webhook endpoint\");\n return this.http.request({\n method: \"GET\",\n path: `/v1/webhook_endpoints/${encodeURIComponent(endpointId)}`,\n schema: webhookEndpoint,\n });\n }\n\n /**\n * Update a webhook endpoint (`description`, `enabled_events`, `url`,\n * `metadata`, or `disabled: true` to disable it). The response does NOT\n * include the signing `secret` (create-only).\n *\n * Docs: https://docs.stripe.com/api/webhook_endpoints/update\n *\n * @example\n * const we = await payweave.stripe.webhookEndpoints.update(\"we_123\", {\n * disabled: true,\n * });\n * console.log(we.status); // \"disabled\"\n */\n async update(id: string, input: WebhookEndpointUpdateReq = {}) {\n const endpointId = requireId(id, \"webhook endpoint\");\n const body = parseRequest(webhookEndpointUpdateReq, input);\n return this.http.request({\n method: \"POST\",\n path: `/v1/webhook_endpoints/${encodeURIComponent(endpointId)}`,\n ...bodyIfNonEmpty(body),\n schema: webhookEndpoint,\n });\n }\n\n /**\n * Delete a webhook endpoint. Returns `{ id, object, deleted: true }`;\n * deleting an already-deleted endpoint raises a Stripe error (404 →\n * {@link PayweaveNotFoundError}). `payweave listen` calls this on\n * teardown.\n *\n * Docs: https://docs.stripe.com/api/webhook_endpoints/delete\n *\n * @example\n * const gone = await payweave.stripe.webhookEndpoints.delete(\"we_123\");\n * console.log(gone.deleted); // true\n */\n async delete(id: string) {\n const endpointId = requireId(id, \"webhook endpoint\");\n return this.http.request({\n method: \"DELETE\",\n path: `/v1/webhook_endpoints/${encodeURIComponent(endpointId)}`,\n schema: webhookEndpointDeleted,\n });\n }\n\n /**\n * List webhook endpoints. Cursor pagination only (`limit` +\n * `starting_after`/`ending_before`) — no other documented filters.\n * Responses never include signing secrets.\n *\n * Docs: https://docs.stripe.com/api/webhook_endpoints/list\n *\n * @example\n * const page = await payweave.stripe.webhookEndpoints.list({ limit: 20 });\n * console.log(page.data.map((we) => we.url));\n */\n async list(query: WebhookEndpointListQuery = {}) {\n const q = parseRequest(webhookEndpointListQuery, query);\n return this.http.request({\n method: \"GET\",\n path: \"/v1/webhook_endpoints\",\n query: flattenQuery(q),\n schema: webhookEndpointListRes,\n });\n }\n\n /**\n * Async iterator over ALL webhook endpoints, transparently following\n * `has_more` with `starting_after = <last id>`.\n *\n * Docs: https://docs.stripe.com/api/webhook_endpoints/list\n *\n * @example\n * for await (const we of payweave.stripe.webhookEndpoints.iterate()) {\n * console.log(we.id, we.url, we.status);\n * }\n */\n async *iterate(query: WebhookEndpointListQuery = {}) {\n const base = parseRequest(webhookEndpointListQuery, query);\n yield* iterateStripeList((startingAfter) =>\n this.http.request({\n method: \"GET\",\n path: \"/v1/webhook_endpoints\",\n query: flattenQuery({ ...base, starting_after: startingAfter }),\n schema: webhookEndpointListRes,\n }),\n );\n }\n}\n","/**\n * StripeClient — Surface A for the `stripe` config key\n * (`payweave.stripe.*`, providers.md §3.2). Holds the provider's shared\n * {@link HttpClient} (constructed from PW-601's `stripeHttpOptions`:\n * form-encoded bodies, pinned `Stripe-Version`) and exposes each resource as\n * a `public readonly` field, exactly like the Paystack and Flutterwave\n * clients.\n *\n * Mounted: checkout.sessions + paymentIntents, customers/products/\n * prices, subscriptions + subscriptionItems, refunds +\n * webhookEndpoints — the complete P0 module table.\n */\nimport { HttpClient } from \"../core/http\";\nimport { defineProvider, readHeader, type ProviderAdapter } from \"../core/provider\";\nimport {\n STRIPE_BASE_URL,\n stripeProviderConfigSchema,\n inferEnvironment as inferEnvironmentFromKey,\n type ResolvedProviderConfig,\n} from \"../core/config\";\nimport { verifyStripe } from \"../webhooks/stripe\";\nimport { toUnifiedEventType } from \"../unified/mappings\";\nimport { stripeHttpOptions } from \"./http-options\";\nimport { CheckoutSessions } from \"./resources/checkout-sessions\";\nimport { Customers } from \"./resources/customers\";\nimport { PaymentIntents } from \"./resources/payment-intents\";\nimport { Prices } from \"./resources/prices\";\nimport { Products } from \"./resources/products\";\nimport { Refunds } from \"./resources/refunds\";\nimport { SubscriptionItems } from \"./resources/subscription-items\";\nimport { Subscriptions } from \"./resources/subscriptions\";\nimport { WebhookEndpoints } from \"./resources/webhook-endpoints\";\n\n/**\n * The `payweave.stripe.checkout.*` namespace — mirrors Stripe's own API\n * grouping (`/v1/checkout/sessions`, https://docs.stripe.com/api/checkout/sessions).\n */\nexport interface StripeCheckoutNamespace {\n /** Checkout Sessions: create, retrieve, list/iterate, expire, lineItems. */\n readonly sessions: CheckoutSessions;\n}\n\nexport class StripeClient {\n /** Shared HTTP client every Stripe resource is constructed with. */\n readonly http: HttpClient;\n\n /** Checkout namespace (`payweave.stripe.checkout.sessions.create(...)`). */\n readonly checkout: StripeCheckoutNamespace;\n /** PaymentIntents: create, retrieve, confirm, capture, cancel, list/iterate. */\n readonly paymentIntents: PaymentIntents;\n /** Customers: create, retrieve, update, delete, list/iterate, search/iterateSearch. */\n readonly customers: Customers;\n /** Products: create, retrieve, update, delete, list/iterate, search/iterateSearch. */\n readonly products: Products;\n /** Prices: create, retrieve, update, list/iterate, search/iterateSearch (no delete — prices are archived). */\n readonly prices: Prices;\n /** Subscriptions: create, retrieve, update, cancel, resume, list/iterate. */\n readonly subscriptions: Subscriptions;\n /** SubscriptionItems: create, retrieve, update, delete, list/iterate. */\n readonly subscriptionItems: SubscriptionItems;\n /** Refunds: create (idempotencyKey), retrieve, update, cancel, list/iterate. */\n readonly refunds: Refunds;\n /** WebhookEndpoints: create (secret shown ONCE), retrieve, update, delete, list/iterate. */\n readonly webhookEndpoints: WebhookEndpoints;\n\n constructor(http: HttpClient) {\n this.http = http;\n this.checkout = { sessions: new CheckoutSessions(this.http) };\n this.paymentIntents = new PaymentIntents(this.http);\n this.customers = new Customers(this.http);\n this.products = new Products(this.http);\n this.prices = new Prices(this.http);\n this.subscriptions = new Subscriptions(this.http);\n this.subscriptionItems = new SubscriptionItems(this.http);\n this.refunds = new Refunds(this.http);\n this.webhookEndpoints = new WebhookEndpoints(this.http);\n }\n}\n\n// ── Provider adapter contract v2 (PW-608, providers.md §4) ──────────────────\n// `stripeAdapter` is additive metadata alongside the direct wiring in\n// `src/index.ts` (`createPayweave` still builds `StripeClient` via\n// `stripeHttpOptions` directly, unchanged). `createHttp` below REUSES\n// `stripeHttpOptions` so the form-encoded body transport and\n// `Stripe-Version`/`Stripe-Account` headers are byte-identical to the real\n// wiring, not a re-implementation. `unified`/`billing` are intentionally left\n// unset: the real unified ops are HttpClient-bound (and, for stripe, not\n// implemented yet — `stripeUnifiedNamespace` in `src/index.ts`); billing is an\n// unimplemented PW-803/804 placeholder.\n\nfunction stripeHttp(cfg: ResolvedProviderConfig): HttpClient {\n return new HttpClient(stripeHttpOptions(cfg));\n}\n\nexport const stripeAdapter: ProviderAdapter = defineProvider({\n id: \"stripe\",\n configKey: \"stripe\",\n configSchema: stripeProviderConfigSchema,\n environments: {\n // One host for both — Stripe's environment is key-derived, not host-derived.\n test: { baseUrl: STRIPE_BASE_URL },\n live: { baseUrl: STRIPE_BASE_URL },\n },\n inferEnvironment: (secretKey) => {\n try {\n return inferEnvironmentFromKey(\"stripe\", secretKey);\n } catch {\n return null;\n }\n },\n createHttp: stripeHttp,\n webhooks: {\n signatureHeader: \"stripe-signature\",\n verify: ({ rawBody, headers, secret }) =>\n verifyStripe(rawBody, readHeader(headers, \"stripe-signature\"), secret),\n parse: (rawBody) => {\n const root = JSON.parse(rawBody) as Record<string, unknown>;\n return {\n type: typeof root.type === \"string\" ? root.type : \"unknown\",\n data: root.data,\n raw: root,\n ...(typeof root.id === \"string\" ? { id: root.id } : {}),\n };\n },\n toUnified: (e) => ({\n provider: \"stripe\",\n type: e.type,\n unifiedType: toUnifiedEventType(\"stripe\", undefined, e.type, e.data),\n data: e.data,\n raw: e.raw,\n }),\n },\n});\n","/**\n * `BillingSync` — pushes locally-defined plans to the database and every\n * configured billing-capable provider (via `payweave push`). This file\n * MIRRORS `./subscribe.ts`'s shape on purpose (same {@link BillingContext}\n * seam, same \"operate ONLY through `DatabaseAdapter` + the existing Surface A\n * resource classes, no raw HTTP\" rule) — it imports `subscribe.ts`'s exports\n * rather than re-declaring them.\n *\n * ── The two-layer idempotency story ─────────────────────────────────────────\n * 1. **Hash match → skip the provider entirely.** Every paid plan's\n * provider-relevant content is hashed (sha256 over canonical JSON;\n * deliberately NEVER `includes`/features — a feature is Payweave-side\n * state, never a provider object, so a features-only change must produce\n * a new `pw_plans` version with ZERO provider calls) and compared against\n * what's already recorded in the ACTIVE version's `provider_refs`\n * (`pw_plans.providerRefs[provider].hash` — an ordinary string entry in\n * the existing `Record<string, Record<string,string>>` column; no schema\n * change). Stripe's Product (`name`) and Price\n * (`amount`/`currency`/`interval`) are hashed/diffed INDEPENDENTLY\n * ({@link planPriceHash} covers price only; `name` is compared directly\n * against the stored row) so a display-name-only edit refreshes the\n * Product in place with zero Price churn — Paystack has no such split (one\n * Plan object carries both, {@link planPaystackHash}). Nothing differing\n * → zero HTTP calls for that provider (the double-push acceptance\n * criterion).\n * 2. **Hash miss → adopt-or-create.** Before ANY provider create, search for\n * an object already tagged with our `pwv_plan` (+, where it disambiguates\n * a price rotation, `pwv_hash`) reference and ADOPT it instead of\n * creating a duplicate — the crash-between-create-and-`pushVersion` case.\n * Genuinely new content (first push, or a real price change) finds\n * nothing and creates fresh; a crash-resumed run finds the object an\n * earlier, interrupted run already created and reuses its id.\n *\n * `plans.pushVersion` is ALSO its own no-op on unchanged content\n * (`src/db/sqlite/adapter.ts`'s `planContentEquals`) — this module still\n * calls it unconditionally after resolving `provider_refs` (\"belt and\n * braces\"), relying on that DB-level check rather than skipping the call\n * itself.\n *\n * ── Free / default plans ───────────────────────────────────────────────\n * Never touch a provider — `providerRefs` is always `{}` for a plan with no\n * `price`, regardless of any provider's configuration state.\n *\n * ── ⚠️ Flutterwave — verified 2026-07-13, deferred ──────────────────────────\n * Verified against developer.flutterwave.com (v3 Payment Plans, 2026-07-13):\n * `POST /v3/payment-plans` accepts `amount`, `name`, `interval` (`monthly`/\n * `yearly`/etc.) and an optional `duration`; `PUT /v3/payment-plans/{id}`\n * updates ONLY `name` and `status` — `amount` is confirmed immutable after\n * creation, so a price change requires a new payment plan, the same shape\n * Stripe/Paystack already use here. That much IS confidently resolved.\n *\n * What blocks shipping it today: (a) neither the create nor update endpoint\n * documents a `metadata`/tagging field of any kind, so there is no\n * provider-native place to stamp `pwv_plan`/`pwv_hash` for crash-resume\n * adoption (the `description`-field workaround this module uses for Paystack\n * — see below — has no Flutterwave equivalent to fall back to); (b) no\n * Flutterwave \"payment plans\" resource/schema module exists anywhere in this\n * codebase yet (`src/flutterwave/v3/resources/*` has banks/beneficiaries/\n * charges/payments/refunds/transactions/transfers — no payment-plans) —\n * building one is a new Surface A provider module. Consistent with\n * `subscribe.ts`'s `BILLING_CAPABLE_PROVIDERS` (which already excludes\n * flutterwave pending this exact verification), `sync()` silently skips a\n * configured `flutterwave` key (reported back via `SyncResult.\n * skippedProviders`) rather than attempting a guessed mapping or erroring\n * the whole push. {@link pushPlanToProvider} — the per-provider dispatch\n * `sync()`'s loop calls only for billing-capable providers — throws a typed\n * {@link PayweaveConfigError} if ever invoked directly for flutterwave (or\n * any other non-billing-capable key), so the \"not yet supported\" path is a\n * real, testable code path, not just a silent omission.\n *\n * ── Paystack: verified 2026-07-13 ───────────────────────────────────────────\n * Paystack's real Plan API DOES support in-place amount mutation —\n * `PUT /plan/{id_or_code}` accepts `name`, `amount`, `interval`, and\n * `update_existing_subscriptions` (whether the new price applies to\n * subscribers already on the plan) — a genuinely different mechanism from\n * Stripe's immutable-price model. However `src/paystack/resources/plans.ts`\n * (a \"use it, don't change it\" surface here) only exposes\n * `create`/`list`/`iterate`/`fetch` — no `update` method — and its\n * `createPlanReq` has no `metadata` field (confirmed: `name`, `amount`,\n * `interval`, `description`, `send_invoices`, `send_sms`, `currency`,\n * `invoice_limit` only). Given those two real constraints, this module:\n * (1) treats any Paystack-relevant content change as \"create a NEW Plan\"\n * (paralleling Stripe's new-Price pattern) rather than PUT-updating in place\n * — the old Paystack plan is left as-is (no archive/cancel call is available\n * through this resource surface either); (2) tags the new Plan for\n * crash-resume adoption by JSON-encoding `{ pwv_plan, pwv_hash }` into the\n * documented, genuinely-supported `description` field (NOT a new/invented\n * API field — `description` is real, free-text, and round-trips through\n * `list`/`fetch`) rather than a dedicated metadata mechanism Paystack's Plan\n * API does not have. FOLLOW-UP flagged, not fixed here: adding\n * `plans.update()` to the Paystack resource would let this module do a true\n * in-place price rotation instead.\n */\nimport { createHash } from \"node:crypto\";\nimport type { PayweaveProviderKey, ResolvedProduct } from \"../core/config\";\nimport { PayweaveConfigError, PayweaveProviderError } from \"../core/errors\";\nimport type {\n DatabaseAdapter,\n PwFeatureInclusion,\n PwPlanVersion,\n PwPlanVersionInput,\n} from \"../db/index\";\nimport type { PaystackClient } from \"../paystack/client\";\nimport type { StripeClient } from \"../stripe/client\";\nimport {\n BILLING_CAPABLE_PROVIDERS,\n resolvePlanGroup,\n type BillingCapableProvider,\n type BillingContext,\n} from \"./subscribe\";\n\n/** Same check as `subscribe.ts`'s (module-private there, so re-declared here — see that file's doc comment). */\nfunction isBillingCapableProvider(provider: PayweaveProviderKey): provider is BillingCapableProvider {\n return (BILLING_CAPABLE_PROVIDERS as readonly string[]).includes(provider);\n}\n\n// ── Content hashing ──────────────────────────────────────────────────────────\n\n/** Stable (sorted-key) JSON for order-independent structural comparison — mirrors `src/db/sqlite/adapter.ts`'s private helper (not exported/importable from that forbidden file). */\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n if (value !== null && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n );\n return `{${entries.map(([key, val]) => `${JSON.stringify(key)}:${stableStringify(val)}`).join(\",\")}}`;\n }\n return JSON.stringify(value);\n}\n\n/**\n * Just a plan's `price` — hashed with sha256 over canonical JSON and\n * stamped into both `pw_plans.providerRefs.stripe.hash` and the Stripe\n * Price's own `pwv_hash` metadata, so a crash-resumed run can recognize\n * \"this is the Price object for THIS exact amount/currency/interval\" without\n * a read-after-write race on the local DB. Deliberately NOT `name` — Stripe\n * separates Product (display `name`) from Price (the immutable amount), so\n * a display-name-only change must refresh the Product in place rather than\n * rotate the Price (see {@link syncStripe}); `includes`/features are never\n * hashed here either — they never become provider objects at all.\n */\nfunction planPriceHash(plan: ResolvedProduct): string {\n const price = plan.price;\n const payload = price ? { amount: price.amount, currency: price.currency, interval: price.interval } : null;\n return createHash(\"sha256\").update(stableStringify(payload)).digest(\"hex\");\n}\n\n/**\n * `name` + `price` together — Paystack has no Stripe-style\n * Product/Price split (one Plan object carries both), so ANY change to\n * either requires a new Plan (module doc comment: no update endpoint is\n * available through the in-scope resource surface either way).\n */\nfunction planPaystackHash(plan: ResolvedProduct): string {\n const price = plan.price;\n const payload = {\n name: plan.name ?? null,\n price: price ? { amount: price.amount, currency: price.currency, interval: price.interval } : null,\n };\n return createHash(\"sha256\").update(stableStringify(payload)).digest(\"hex\");\n}\n\n/** One resolved plan's `includes` converted to the `pw_plans.features` JSON shape. Never touches providers. */\nfunction buildFeatures(plan: ResolvedProduct): Record<string, PwFeatureInclusion> {\n const out: Record<string, PwFeatureInclusion> = {};\n for (const inclusion of plan.includes) {\n out[inclusion.featureId] =\n inclusion.type === \"boolean\"\n ? { type: \"boolean\" }\n : { type: \"metered\", limit: inclusion.limit, reset: inclusion.reset };\n }\n return out;\n}\n\n/** What one provider push produced, for {@link SyncPlanResult} reporting (informational only — never used to decide behavior). */\nexport type SyncProviderAction = \"created\" | \"adopted\" | \"unchanged\";\n\n/** Per-plan outcome of one {@link sync} run. */\nexport interface SyncPlanResult {\n readonly planId: string;\n /** The plan's active `pw_plans` version AFTER this run (unchanged if nothing differed). */\n readonly version: number;\n /** Whether this run appended a NEW `pw_plans` version (false = `pushVersion`'s own no-op fired). */\n readonly versionChanged: boolean;\n /** Per-billing-capable-provider action taken — empty for a free/default plan (zero provider objects). */\n readonly providers: Readonly<Partial<Record<BillingCapableProvider, SyncProviderAction>>>;\n}\n\n/** `sync()`'s result (`payweave.sync()` / `payweave push`). */\nexport interface SyncResult {\n readonly plans: readonly SyncPlanResult[];\n /**\n * Configured provider keys that are NOT billing-capable and were therefore\n * never pushed to (e.g. `flutterwave` — see this module's doc comment for\n * the verified-but-deferred ⚠️ resolution).\n */\n readonly skippedProviders: readonly PayweaveProviderKey[];\n}\n\n// ── Stripe (Products + Prices) ──────────────────────────────────────────────\n\ninterface StripeProductLike {\n id: string;\n}\ninterface StripePriceLike {\n id: string;\n}\n\n/** Search Products tagged for this plan (crash-resume adoption) — matches by `pwv_plan` ALONE: a plan's Product is never recreated across price changes, so at most one live match is expected. */\nasync function findStripeProduct(\n stripe: StripeClient,\n planId: string,\n): Promise<StripeProductLike | undefined> {\n const found = await stripe.products.search({ query: `metadata['pwv_plan']:'${planId}'` });\n return found.data[0];\n}\n\n/** Search Prices tagged for THIS exact content hash — `pwv_plan` alone is not enough here: an old, still-active price from a prior price generation would also carry it. */\nasync function findStripePrice(\n stripe: StripeClient,\n planId: string,\n hash: string,\n): Promise<StripePriceLike | undefined> {\n const found = await stripe.prices.search({\n query: `metadata['pwv_plan']:'${planId}' AND metadata['pwv_hash']:'${hash}'`,\n });\n return found.data[0];\n}\n\n/**\n * Push one paid plan onto Stripe Products + Prices. `existingVersion`\n * is the plan's CURRENT active `pw_plans` row (or `null` before any push) —\n * the source of both the \"unchanged, skip entirely\" fast path and the prior\n * `name`/price-id to diff/archive against.\n *\n * Product (`name`) and Price (`amount`/`currency`/`interval`) are diffed\n * INDEPENDENTLY, matching how Stripe itself separates the two objects: a\n * display-name-only change refreshes the Product in place with ZERO Price\n * churn, and a price-only change rotates the Price with zero Product calls.\n * Only when NEITHER differs does this skip Stripe entirely.\n */\nasync function syncStripe(\n stripe: StripeClient,\n plan: ResolvedProduct,\n existingVersion: PwPlanVersion | null,\n): Promise<{ refs: Record<string, string>; action: SyncProviderAction }> {\n const price = plan.price;\n /* istanbul ignore next -- defensive: only paid plans reach this function (see `sync`). */\n if (!price) throw new PayweaveConfigError(`plan \"${plan.id}\" has no price to sync to stripe.`);\n\n const priceHash = planPriceHash(plan);\n const prevRefs = existingVersion?.providerRefs.stripe;\n const prevProductId = prevRefs?.productId;\n const prevPriceId = prevRefs?.priceId;\n const nameChanged = (existingVersion?.name ?? null) !== (plan.name ?? null);\n const priceChanged = prevRefs?.hash !== priceHash;\n\n // Layer 1 — neither sub-object differs and both refs are already on file: zero stripe calls.\n if (prevProductId !== undefined && prevPriceId !== undefined && !nameChanged && !priceChanged) {\n return { refs: { productId: prevProductId, priceId: prevPriceId, hash: priceHash }, action: \"unchanged\" };\n }\n\n let created = false;\n let adopted = false;\n\n // Product: adopt-or-create (only when we don't already know its id), else a\n // cheap name-only refresh when the display name changed but the id is known\n // — no Price work is triggered by a name change alone.\n let productId = prevProductId;\n if (productId === undefined) {\n const found = await findStripeProduct(stripe, plan.id);\n if (found) {\n productId = found.id;\n adopted = true;\n } else {\n const createdProduct = await stripe.products.create(\n { name: plan.name ?? plan.id, metadata: { pwv_plan: plan.id } },\n { idempotencyKey: `pwv-push-product-${plan.id}` },\n );\n productId = createdProduct.id;\n created = true;\n }\n } else if (nameChanged) {\n await stripe.products.update(productId, {\n name: plan.name ?? plan.id,\n metadata: { pwv_plan: plan.id },\n });\n }\n\n // Price: layer-2 adopt-or-create against the CURRENT hash, but ONLY when\n // the price itself changed (or is unknown yet) — a genuine first push /\n // price change finds nothing (creates fresh); a crash-resumed run finds\n // the price an earlier, interrupted run already created.\n let priceId = prevPriceId;\n if (priceId === undefined || priceChanged) {\n const foundPrice = await findStripePrice(stripe, plan.id, priceHash);\n if (foundPrice) {\n priceId = foundPrice.id;\n adopted = true;\n } else {\n const createdPrice = await stripe.prices.create(\n {\n currency: price.currency.toLowerCase(),\n unit_amount: price.amount,\n recurring: { interval: price.interval },\n product: productId,\n metadata: { pwv_plan: plan.id, pwv_hash: priceHash },\n },\n { idempotencyKey: `pwv-push-price-${plan.id}-${priceHash}` },\n );\n priceId = createdPrice.id;\n created = true;\n }\n\n // Price change: archive the OLD price for new sales — never\n // delete, never touched again once superseded.\n if (prevPriceId !== undefined && prevPriceId !== priceId) {\n await stripe.prices.update(prevPriceId, { active: false });\n }\n }\n\n return {\n refs: { productId, priceId, hash: priceHash },\n action: adopted ? \"adopted\" : created ? \"created\" : \"unchanged\",\n };\n}\n\n// ── Paystack (Plans) ─────────────────────────────────────────────────────────\n\nconst PAYSTACK_INTERVAL: Record<\"month\" | \"year\", \"monthly\" | \"annually\"> = {\n month: \"monthly\",\n year: \"annually\",\n};\n\n/** The `{ pwv_plan, pwv_hash }` tag this module round-trips through Paystack's `description` field (module doc comment — no native metadata field exists on Paystack Plans). */\ninterface PaystackTag {\n readonly pwv_plan: string;\n readonly pwv_hash: string;\n}\n\nfunction encodePaystackTag(tag: PaystackTag): string {\n return JSON.stringify(tag);\n}\n\nfunction decodePaystackTag(description: string | null | undefined): PaystackTag | undefined {\n if (description === null || description === undefined) return undefined;\n try {\n const parsed: unknown = JSON.parse(description);\n if (\n parsed !== null &&\n typeof parsed === \"object\" &&\n typeof (parsed as Record<string, unknown>).pwv_plan === \"string\" &&\n typeof (parsed as Record<string, unknown>).pwv_hash === \"string\"\n ) {\n return parsed as unknown as PaystackTag;\n }\n } catch {\n // Not our tag — an ordinary human-written description. Not adoptable.\n }\n return undefined;\n}\n\n/**\n * Scan every Paystack plan for one tagged with this EXACT (`planId`, `hash`)\n * pair (crash-resume adoption — module doc comment: no `search`/`metadata`\n * mechanism exists on this resource, so a full list scan via the existing\n * `iterate()` is the only adoption path available through it).\n */\nasync function findAdoptablePaystackPlan(\n paystack: PaystackClient,\n planId: string,\n hash: string,\n): Promise<string | undefined> {\n for await (const candidate of paystack.plans.iterate()) {\n const tag = decodePaystackTag(candidate.description ?? undefined);\n if (tag?.pwv_plan === planId && tag.pwv_hash === hash) {\n const code = candidate.plan_code;\n if (code !== undefined) return code;\n }\n }\n return undefined;\n}\n\n/** Push one paid plan onto a Paystack Plan — see the module doc comment for why this always creates a NEW plan on any content change rather than mutating in place. */\nasync function syncPaystack(\n paystack: PaystackClient,\n plan: ResolvedProduct,\n existingVersion: PwPlanVersion | null,\n): Promise<{ refs: Record<string, string>; action: SyncProviderAction }> {\n const price = plan.price;\n /* istanbul ignore next -- defensive: only paid plans reach this function (see `sync`). */\n if (!price) throw new PayweaveConfigError(`plan \"${plan.id}\" has no price to sync to paystack.`);\n\n const hash = planPaystackHash(plan);\n const prevRefs = existingVersion?.providerRefs.paystack;\n const prevPlanCode = prevRefs?.planCode;\n\n // Layer 1 — hash match + ref already on file: zero paystack calls.\n if (prevPlanCode !== undefined && prevRefs?.hash === hash) {\n return { refs: { planCode: prevPlanCode, hash }, action: \"unchanged\" };\n }\n\n // Layer 2 — adopt-or-create against the CURRENT hash.\n const adoptedCode = await findAdoptablePaystackPlan(paystack, plan.id, hash);\n if (adoptedCode !== undefined) {\n return { refs: { planCode: adoptedCode, hash }, action: \"adopted\" };\n }\n\n const created = await paystack.plans.create({\n name: plan.name ?? plan.id,\n amount: price.amount,\n interval: PAYSTACK_INTERVAL[price.interval],\n currency: price.currency,\n description: encodePaystackTag({ pwv_plan: plan.id, pwv_hash: hash }),\n });\n const planCode = created.data.plan_code;\n if (planCode === undefined) {\n throw new PayweaveProviderError(\"paystack created a plan without a plan_code\", {\n provider: \"paystack\",\n });\n }\n return { refs: { planCode, hash }, action: \"created\" };\n}\n\n// ── Per-provider dispatch ────────────────────────────────────────────────────\n\n/**\n * Push one paid plan to ONE provider. `sync()`'s own loop only ever calls\n * this for a billing-capable, configured provider — the `else` branch below\n * (flutterwave, or any future non-billing-capable key) is therefore normally\n * unreachable through the public surface, but stays a REAL, directly-callable\n * function (not folded into `sync()`'s loop body) precisely so the\n * \"Flutterwave payment-plan sync is not supported yet\" path is a typed,\n * testable error rather than a silent gap (module doc comment).\n */\nexport async function pushPlanToProvider(\n ctx: BillingContext,\n provider: PayweaveProviderKey,\n plan: ResolvedProduct,\n existingVersion: PwPlanVersion | null,\n): Promise<{ refs: Record<string, string>; action: SyncProviderAction }> {\n if (provider === \"stripe\") {\n /* istanbul ignore next -- defensive: `sync()` only calls this for configured providers. */\n if (!ctx.stripe) throw new PayweaveConfigError(\"stripe is not configured on this client.\");\n return syncStripe(ctx.stripe, plan, existingVersion);\n }\n if (provider === \"paystack\") {\n /* istanbul ignore next -- defensive: `sync()` only calls this for configured providers. */\n if (!ctx.paystack) throw new PayweaveConfigError(\"paystack is not configured on this client.\");\n return syncPaystack(ctx.paystack, plan, existingVersion);\n }\n throw new PayweaveConfigError(\n `payweave.sync() does not support pushing plans to \"${provider}\" yet — its payment-plan mapping ` +\n `is deferred pending further API verification; billing-capable providers: ` +\n `${BILLING_CAPABLE_PROVIDERS.join(\", \")}.`,\n );\n}\n\n// ── The engine ───────────────────────────────────────────────────────────────\n\n/** Build the `plans.pushVersion` input for one plan, given its already-resolved `providerRefs`. */\nfunction planVersionInput(plan: ResolvedProduct, providerRefs: Record<string, Record<string, string>>): PwPlanVersionInput {\n return {\n planId: plan.id,\n group: resolvePlanGroup(plan),\n isDefault: plan.default,\n name: plan.name ?? null,\n priceMinor: plan.price?.amount ?? null,\n priceCurrency: plan.price?.currency ?? null,\n priceInterval: plan.price?.interval ?? null,\n features: buildFeatures(plan),\n providerRefs,\n };\n}\n\n/**\n * `BillingSync` — push every configured plan/feature definition to the\n * database and each configured billing-capable provider.\n * Mounted as `payweave.sync()`; `payweave push` drives this same function.\n *\n * Runtime guard (mirrors `subscribe()`'s pattern):\n * `database` AND `products` must both be configured — `sync()` has nothing to\n * push without a products array, and nowhere to push it without a database.\n */\nexport async function sync(ctx: BillingContext): Promise<SyncResult> {\n const database: DatabaseAdapter | undefined = ctx.database;\n if (!database) {\n throw new PayweaveConfigError(\n \"payweave.sync() needs a database — pass a payweave/db/* adapter to createPayweave().\",\n );\n }\n const products = ctx.products;\n if (!products) {\n throw new PayweaveConfigError(\n \"payweave.sync() needs products — pass a `products` array to createPayweave().\",\n );\n }\n\n const billingProviders = ctx.providers.filter(isBillingCapableProvider);\n const skippedProviders = ctx.providers.filter((provider) => !isBillingCapableProvider(provider));\n\n const plans: SyncPlanResult[] = [];\n for (const plan of products) {\n const existingVersion = await database.plans.getActiveVersion(plan.id);\n\n // Free/default plans: DB only, zero provider objects, zero provider calls.\n const providerRefs: Record<string, Record<string, string>> = {};\n const providerActions: Partial<Record<BillingCapableProvider, SyncProviderAction>> = {};\n\n if (plan.price !== undefined) {\n for (const provider of billingProviders) {\n const result = await pushPlanToProvider(ctx, provider, plan, existingVersion);\n providerRefs[provider] = result.refs;\n providerActions[provider] = result.action;\n }\n }\n\n const pushed = await database.plans.pushVersion(planVersionInput(plan, providerRefs));\n\n plans.push({\n planId: plan.id,\n version: pushed.version,\n versionChanged: existingVersion === null || existingVersion.version !== pushed.version,\n providers: providerActions,\n });\n }\n\n return { plans, skippedProviders };\n}\n","/**\n * `check()` + `report()` — the metered-usage surface. Mirrors `subscribe.ts`'s\n * structure/seams on purpose (same {@link BillingContext}, same \"non-generic\n * module, generic facade\" split with `src/index.ts`) — this file never\n * imports `../index` (avoids a circular import back into the facade).\n *\n * Both `check` and `report` bottom out in EXACTLY ONE\n * `database.balances.consume` call: the SDK layer adds zero atomicity of its\n * own — no read-modify-write, no retry, no rollback machinery. `check` is\n * `consume(amount: 0)` (a peek that still performs the lazy reset — \"amount:\n * 0 must still trigger row creation + reset\"); `report` is `consume(amount:\n * n, conditional: false)` (unconditional — never throws for \"over limit\");\n * `check({ consume: true })` is `consume(amount: 1, conditional: true)` — the\n * documented atomic gate.\n *\n * ── Resolution order ────────────────────────────────────────────────────\n * 1. Find the feature across `ctx.products` to learn its `type` and its\n * \"home\" group (`resolvePlanGroup` of the first plan that includes it —\n * spec-silent: a config where the SAME feature id appears under more than\n * one group is unspecified; the first occurrence in array order wins,\n * deterministically).\n * 2. The customer's active subscription in that group (`subscriptions.getActive`)\n * → resolve its `planId` back against `ctx.products` (NOT a\n * `database.plans.getActiveVersion` round trip — see the spec-silent note\n * below) and read that plan's inclusion of the feature.\n * 3. No active subscription → the group's default plan's inclusion (no rows\n * required).\n * 4. Feature not included in whichever plan answered → `allowed: false` /\n * `balance: null` / `limit: null` / `resetsAt: null` for metered, and\n * `allowed: false` for boolean — a normal \"upsell\" answer, never an error.\n *\n * ── Spec-silent decision: resolving limits from `ctx.products`, not `pw_plans` ─\n * The active-subscription path resolves \"that plan version's inclusion of the\n * feature,\" which could be read as a `database.plans.\n * getActiveVersion(planId)` round trip against the persisted, pushed\n * `features` JSON. This module resolves the feature's `limit`/`reset` from the\n * in-memory `ctx.products` (keyed by `subscription.planId`) instead, for two\n * reasons: (1) `DatabaseAdapter.plans` only exposes the LATEST pushed version\n * per plan id (no lookup by a specific historical version number), so a DB\n * round trip would answer with the exact same \"latest known definition\" that\n * `ctx.products` already holds from the source-controlled config — at the\n * cost of a network round trip on every `check`/`report` call; (2) this\n * mirrors `subscribe()`'s own `findPlan(ctx.products, planId)` pattern for its\n * free/default branches (`./subscribe.ts`). `subscription.planId`/\n * `planVersion` remain the authoritative \"what was pushed and paid for at\n * subscribe time\" record on the row itself; the limits `check`/`report`\n * *enforce* follow the code's current `products` definition — which is\n * expected to be pushed (`payweave push`) whenever it changes. `database.\n * plans.getActiveVersion` is still consulted, but only to stamp a real\n * `planVersion` int onto a LAZILY-CREATED balance row for a plan with no\n * active subscription (the default-plan path) — see {@link buildMeteredInit}.\n *\n * ── Spec-silent decision: a group with no default plan, no active subscription ─\n * \"No subscription → the group's default plan inclusion (no rows required)\"\n * assumes a default plan exists. A group that legitimately has none (e.g. an\n * opt-in-only `addons` group, see `subscribe.ts`'s own `teamAddonPlan`\n * fixture) has no plan to answer from when nobody has subscribed.\n * Conservative reading: this is a configuration gap, not a normal \"no access\"\n * answer (which is what `allowed: false` already means for a\n * plan-that-lacks-the-feature) — `check`/`report` throw\n * {@link PayweaveConfigError} naming the group, rather than silently guessing.\n *\n * ── Spec-silent decision: anchor seeding, paid vs free ─────────────────\n * \"Paid subscriptions seed [the anchor] from the subscription's\n * `current_period_start`; default-plan (and free-plan) balances seed it at\n * first use.\" Read literally: the split is on the RESOLVED PLAN'S price, not\n * on subscription-existence — a free, NON-default plan (e.g. `team-addon`)\n * still gets a `pw_subscriptions` row from `subscribe()` (`nominalPeriod`'s\n * placeholder bounds, not a real provider cycle), but its metered balances\n * anchor at the customer's own first `check`/`report` call, exactly like the\n * default-plan path — because a free plan's \"period start\" is a locally\n * invented placeholder, not a real billing date worth aligning to. Only a\n * plan with an actual `price` anchors from `subscription.currentPeriodStart`.\n *\n * ── Spec-silent decision: `report()` on a feature the current plan excludes ──\n * `report`'s public shape has no `allowed` field to express \"not\n * included\" the way `check` does — there is also no `limit`/`reset` to build\n * an `init` template from. `report()` throws {@link PayweaveValidationError}\n * pointing the caller at `check()` (whose `allowed: false` IS the documented\n * answer for this case) rather than guessing a limit.\n */\nimport { PayweaveConfigError, PayweaveValidationError } from \"../core/errors\";\nimport type { ResolvedProduct } from \"../core/config\";\nimport type {\n DatabaseAdapter,\n PwCustomer,\n PwFeatureBalanceInit,\n PwSubscription,\n} from \"../db/index\";\nimport type { FeatureInclusion, FeatureType, MeteredFeatureInclusion } from \"./feature\";\nimport type { BillingContext } from \"./subscribe\";\nimport { resolvePlanGroup } from \"./subscribe\";\n\n/**\n * `check()`'s input. Mirrors `CheckInput<C>` in\n * `src/index.ts` field-for-field, but non-generic — the compile-time\n * `FeatureIds<C>` narrowing is the client facade's job (it widens back to\n * this plain type before calling in here).\n */\nexport interface CheckInput {\n customerId: string;\n featureId: string;\n /** Atomic gate: consume 1 unit iff allowed, in the SAME operation. */\n consume?: boolean;\n}\n\n/**\n * `check()`'s result (matched verbatim — this shape becomes the docs page).\n * `balance`/`limit`/`resetsAt` are `null` for boolean features (no usage to\n * track) and for a metered feature the resolved plan doesn't include (the\n * normal \"upsell\" answer).\n */\nexport interface CheckResult {\n /** Boolean feature: plan includes it. Metered: remaining balance > 0. */\n allowed: boolean;\n /** Remaining units this period; `null` for boolean features or a plan lacking the feature. */\n balance: number | null;\n /** The plan's configured limit; `null` alongside `balance`. */\n limit: number | null;\n /** End of the current billing period; `null` alongside `balance`. */\n resetsAt: Date | null;\n /** The plan that answered — may be the group's default plan id. */\n planId: string;\n}\n\n/**\n * `report()`'s input. Mirrors `ReportInput<C>` in\n * `src/index.ts`, non-generic. `amount` defaults to `1` when omitted.\n */\nexport interface ReportInput {\n customerId: string;\n featureId: string;\n amount?: number;\n}\n\n/** `report()`'s result — the post-decrement balance snapshot. */\nexport interface ReportResult {\n balance: number;\n resetsAt: Date;\n}\n\nfunction requireDatabase(ctx: BillingContext, method: \"check\" | \"report\"): DatabaseAdapter {\n if (!ctx.database) {\n throw new PayweaveConfigError(\n `payweave.${method}() needs a database — pass a payweave/db/* adapter to createPayweave().`,\n );\n }\n return ctx.database;\n}\n\nfunction assertPositiveSafeInteger(value: number, name: string): void {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new PayweaveValidationError(`${name} must be a positive safe integer — got ${value}`);\n }\n}\n\n/** Resolved answer to \"which plan/group/subscription governs this (customer, feature) pair\". */\ninterface FeatureContext {\n group: string;\n type: FeatureType;\n /** The plan that answered — the active subscription's plan, or the group's default. */\n plan: ResolvedProduct;\n /** `undefined` when the resolved plan doesn't include this feature. */\n inclusion: FeatureInclusion | undefined;\n /** The active subscription row, or `null` on the default-plan path. */\n subscription: PwSubscription | null;\n customerRow: PwCustomer;\n}\n\n/** Resolution order — shared by `check` and `report`. */\nasync function resolveFeatureContext(\n ctx: BillingContext,\n database: DatabaseAdapter,\n customerId: string,\n featureId: string,\n): Promise<FeatureContext> {\n const products = ctx.products ?? [];\n\n let type: FeatureType | undefined;\n let group: string | undefined;\n for (const p of products) {\n const inc = p.includes.find((i) => i.featureId === featureId);\n if (inc) {\n type = inc.type;\n group = resolvePlanGroup(p);\n break;\n }\n }\n if (type === undefined || group === undefined) {\n throw new PayweaveValidationError(\n `unknown feature \"${featureId}\" — configure it in \\`products\\`.`,\n );\n }\n\n // Resolve the customer's internal `pwv_` id (every store keys\n // balances on it). Read first and upsert only when the customer is absent, so\n // the metering hot path avoids a write on the common (already-exists) case;\n // the read→upsert gap is safe because `upsert` is idempotent.\n let customerRow = await database.customers.getByExternalId(customerId);\n if (customerRow === null) {\n customerRow = await database.customers.upsert({ externalId: customerId });\n }\n const subscription = await database.subscriptions.getActive(customerRow.id, group);\n\n if (subscription) {\n const plan = products.find((p) => p.id === subscription.planId);\n if (!plan) {\n throw new PayweaveValidationError(\n `customer's active subscription references plan \"${subscription.planId}\", which is no longer in ` +\n \"`products` — was it renamed or removed?\",\n );\n }\n const inclusion = plan.includes.find((i) => i.featureId === featureId);\n return { group, type, plan, inclusion, subscription, customerRow };\n }\n\n const defaultPlan = products.find((p) => p.default && resolvePlanGroup(p) === group);\n if (!defaultPlan) {\n throw new PayweaveConfigError(\n `group \"${group}\" has no default plan — check()/report() need one to answer for a customer with no ` +\n \"active subscription in that group.\",\n );\n }\n const inclusion = defaultPlan.includes.find((i) => i.featureId === featureId);\n return { group, type, plan: defaultPlan, inclusion, subscription: null, customerRow };\n}\n\n/** Builds `balances.consume`'s creation-time `init` template — ignored when the row already exists. */\nasync function buildMeteredInit(\n database: DatabaseAdapter,\n resolved: FeatureContext,\n inclusion: MeteredFeatureInclusion,\n now: Date,\n): Promise<PwFeatureBalanceInit> {\n const isPaid = resolved.plan.price !== undefined;\n const anchor = isPaid && resolved.subscription ? resolved.subscription.currentPeriodStart : now;\n const planVersion = resolved.subscription\n ? resolved.subscription.planVersion\n : ((await database.plans.getActiveVersion(resolved.plan.id))?.version ?? 1);\n\n return {\n limit: inclusion.limit,\n resetInterval: inclusion.reset,\n anchor,\n planId: resolved.plan.id,\n planVersion,\n };\n}\n\n/**\n * `check()`. Never mutates the balance except the\n * lazy reset; `consume: true` makes it the atomic gate.\n */\nexport async function check(ctx: BillingContext, input: CheckInput): Promise<CheckResult> {\n const database = requireDatabase(ctx, \"check\");\n const resolved = await resolveFeatureContext(ctx, database, input.customerId, input.featureId);\n\n if (resolved.type === \"boolean\") {\n return {\n allowed: resolved.inclusion !== undefined,\n balance: null,\n limit: null,\n resetsAt: null,\n planId: resolved.plan.id,\n };\n }\n\n if (!resolved.inclusion) {\n // Feature not included in the resolved plan. Normal answer.\n return { allowed: false, balance: null, limit: null, resetsAt: null, planId: resolved.plan.id };\n }\n\n const inclusion = resolved.inclusion as MeteredFeatureInclusion;\n const now = new Date();\n const init = await buildMeteredInit(database, resolved, inclusion, now);\n const conditional = input.consume === true;\n const amount = conditional ? 1 : 0;\n\n const result = await database.balances.consume({\n customerId: resolved.customerRow.id,\n featureId: input.featureId,\n group: resolved.group,\n amount,\n conditional,\n init,\n now,\n });\n\n const balance = result.limit - result.used;\n return {\n allowed: conditional ? result.applied : balance > 0,\n balance,\n limit: result.limit,\n resetsAt: result.periodEnd,\n planId: resolved.plan.id,\n };\n}\n\n/**\n * `report()`. Unconditional decrement — never throws for \"over limit\";\n * `check` is the hard-blocking gate.\n */\nexport async function report(ctx: BillingContext, input: ReportInput): Promise<ReportResult> {\n const database = requireDatabase(ctx, \"report\");\n\n const amount = input.amount ?? 1;\n assertPositiveSafeInteger(amount, \"amount\");\n\n const resolved = await resolveFeatureContext(ctx, database, input.customerId, input.featureId);\n\n if (resolved.type === \"boolean\") {\n throw new PayweaveValidationError(\n `report() only accepts metered features — \"${input.featureId}\" is a boolean feature.`,\n );\n }\n\n if (!resolved.inclusion) {\n throw new PayweaveValidationError(\n `report(): feature \"${input.featureId}\" is not included in customer \"${input.customerId}\"'s current ` +\n `plan \"${resolved.plan.id}\" — call check() first, which answers { allowed: false } for a plan ` +\n \"lacking a feature.\",\n );\n }\n\n const inclusion = resolved.inclusion as MeteredFeatureInclusion;\n const now = new Date();\n const init = await buildMeteredInit(database, resolved, inclusion, now);\n\n const result = await database.balances.consume({\n customerId: resolved.customerRow.id,\n featureId: input.featureId,\n group: resolved.group,\n amount,\n conditional: false,\n init,\n now,\n });\n\n return { balance: result.limit - result.used, resetsAt: result.periodEnd };\n}\n","/**\n * Payweave — one SDK, every provider, woven together.\n *\n * Public facade: `createPayweave` (`PayweaveClient`) with config-key-presence\n * narrowing — pass the provider(s) you want as keys on the config object and\n * get a fully-typed client back.\n */\nimport { PayweaveError, PayweaveConfigError, type PayweaveProvider } from \"./core/errors\";\nimport {\n resolvePayweaveConfig,\n type ResolvedConfig,\n type PayweaveConfig,\n type PayweaveProviderKey,\n type ResolvedProduct,\n} from \"./core/config\";\nimport { HttpClient, bearer, oauthClientCredentials, type AuthStrategy } from \"./core/http\";\nimport type { HeaderLookup } from \"./core/provider\";\nimport { SDK_VERSION } from \"./core/version\";\nimport type { WebhookEvent } from \"./webhooks/index\";\nimport { createWebhookDispatch } from \"./webhooks/dispatch\";\nimport { PaystackClient } from \"./paystack/client\";\nimport { FlutterwaveClient } from \"./flutterwave/client\";\nimport { StripeClient } from \"./stripe/client\";\nimport { stripeHttpOptions } from \"./stripe/http-options\";\nimport type { DatabaseAdapter, PwSubscription } from \"./db/index\";\nimport type { FeatureType } from \"./products/index\";\nimport {\n subscribe as billingSubscribe,\n type BillingContext,\n type SubscribeInput as BillingSubscribeInput,\n} from \"./products/subscribe\";\nimport { sync as billingSync, type SyncResult } from \"./products/sync\";\nimport {\n check as billingCheck,\n report as billingReport,\n type CheckInput as BillingCheckInput,\n type ReportInput as BillingReportInput,\n} from \"./products/usage\";\nimport {\n createPaystackUnified,\n createFlutterwaveUnified,\n UNIFIED_CAPABILITY_MATRIX,\n assertUnifiedCapability,\n type UnifiedNamespace,\n type CheckoutCreateInput,\n type CheckoutCreateResult,\n type VerifyInput,\n type VerifyResult,\n type RefundCreateInput,\n type RefundCreateResult,\n type TransferCreateInput,\n type TransferCreateResult,\n type BanksListInput,\n type UnifiedBank,\n type ResolveAccountInput,\n type ResolvedAccountResult,\n type UnifiedOpName,\n type UnifiedOpCapability,\n} from \"./unified/index\";\n\nexport { SDK_VERSION as VERSION } from \"./core/version\";\n\n// Re-export the unified-layer (Surface B) op types so consumers can type their\n// unified integration code.\nexport type {\n UnifiedNamespace,\n CheckoutCreateInput,\n CheckoutCreateResult,\n VerifyInput,\n VerifyResult,\n RefundCreateInput,\n RefundCreateResult,\n TransferRecipient,\n TransferCreateInput,\n TransferCreateResult,\n BanksListInput,\n UnifiedBank,\n ResolveAccountInput,\n ResolvedAccountResult,\n UnifiedAmount,\n UnifiedCustomer,\n UnifiedCustomerInput,\n // Capability matrix — the shape `capabilities()` returns.\n UnifiedOpName,\n UnifiedOpCapability,\n} from \"./unified/index\";\n\n// Re-export the config types + core errors consumers need to type their code.\nexport type {\n SDKConfig,\n PaystackConfig,\n FlutterwaveConfig,\n FlutterwaveV3Config,\n FlutterwaveV4Config,\n ResolvedConfig,\n // Provider-keyed root — what `createPayweave` takes.\n PayweaveConfig,\n PayweaveProviderKey,\n StripeProviderConfig,\n PaystackProviderConfig,\n FlutterwaveProviderConfig,\n ResolvedPayweaveConfig,\n ResolvedProviderConfig,\n // Cross-plan-validated, minor-units-resolved `products`.\n ResolvedProduct,\n} from \"./core/config\";\nexport {\n PayweaveError,\n PayweaveConfigError,\n PayweaveAuthError,\n PayweaveValidationError,\n PayweaveNotFoundError,\n PayweaveRateLimitError,\n PayweaveProviderError,\n PayweaveNetworkError,\n PayweaveWebhookVerificationError,\n} from \"./core/errors\";\nexport type { Money } from \"./core/money\";\nexport { PaystackClient } from \"./paystack/client\";\nexport { FlutterwaveClient } from \"./flutterwave/client\";\nexport { StripeClient } from \"./stripe/client\";\nexport type { WebhookEvent } from \"./webhooks/index\";\n\n// ── Products ─────────────────────────────────────────────────────────────────\n// `feature`/`plan` are re-exported from the package root. Full domain\n// surface (period math, `resolvePlanPricing`, …) stays on the\n// `payweave/products` subpath; only the two definition primitives + the types\n// needed to type a hand-written `products.ts` are duplicated here.\nexport { feature, plan } from \"./products/index\";\nexport type {\n BooleanFeatureInclusion,\n FeatureDef,\n FeatureDefInput,\n FeatureFn,\n FeatureInclusion,\n FeatureType,\n MeteredFeatureArg,\n MeteredFeatureInclusion,\n Plan,\n PlanDefInput,\n PlanPrice,\n PlanPriceInput,\n ResolvedPlanPrice,\n} from \"./products/index\";\n\n// `payweave.sync()`'s result shape — see\n// `./products/sync` for the full `BillingSync` engine this re-exports from.\nexport type { SyncResult, SyncPlanResult, SyncProviderAction } from \"./products/sync\";\n\n// ── Webhooks namespace ───────────────────────────────────────────────────────\n/** Raw-body + headers input shared by every webhook operation. */\nexport interface WebhookInput {\n /** Exact received bytes — never a re-serialized object. */\n rawBody: string | Uint8Array;\n /** `Headers` or a plain/array header map; looked up case-insensitively. */\n headers: HeaderLookup;\n}\n\n/** The `payweave.webhooks` surface — multi-provider signature dispatch. */\nexport interface WebhooksNamespace {\n /** Verify a webhook signature (timing-safe, fails closed). */\n verify(input: WebhookInput): boolean;\n /** Verify or throw {@link PayweaveWebhookVerificationError}. */\n verifyOrThrow(input: WebhookInput): void;\n /** Verify + parse + normalize into a typed {@link WebhookEvent}. */\n constructEvent(input: WebhookInput): WebhookEvent;\n}\n\n// ── HTTP wiring ──────────────────────────────────────────────────────────────\n/**\n * What the transport builders need: the legacy {@link ResolvedConfig} and the\n * keyed root's per-provider {@link ResolvedProviderConfig} are both this shape,\n * so `createPayweave` reuses the exact same wiring per configured provider.\n */\ntype ResolvedTransportConfig = Omit<ResolvedConfig, \"provider\"> & { provider: PayweaveProvider };\n\nfunction buildAuth(resolved: ResolvedTransportConfig): AuthStrategy {\n if (resolved.provider === \"flutterwave\" && resolved.version === \"v4\") {\n if (!resolved.clientId || !resolved.clientSecret || !resolved.tokenUrl) {\n throw new PayweaveConfigError(\"Flutterwave v4 requires clientId, clientSecret, and a token URL.\", {\n provider: \"flutterwave\",\n });\n }\n return oauthClientCredentials({\n clientId: resolved.clientId,\n clientSecret: resolved.clientSecret,\n tokenUrl: resolved.tokenUrl,\n ...(resolved.fetch ? { fetch: resolved.fetch } : {}),\n ...(resolved.logger ? { logger: resolved.logger } : {}),\n });\n }\n if (!resolved.secretKey) {\n throw new PayweaveConfigError(`Missing secret key for ${resolved.provider}.`, {\n provider: resolved.provider,\n });\n }\n return bearer(resolved.secretKey);\n}\n\nfunction buildHttpClient(resolved: ResolvedTransportConfig): HttpClient {\n return new HttpClient({\n baseUrl: resolved.baseUrl,\n auth: buildAuth(resolved),\n provider: resolved.provider,\n version: resolved.version,\n timeoutMs: resolved.timeoutMs,\n maxRetries: resolved.maxRetries,\n fetch: resolved.fetch,\n logger: resolved.logger,\n userAgent: `payweave/${SDK_VERSION} (${resolved.provider})`,\n });\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// createPayweave — the unified entry point. Providers are config KEYS;\n// narrowing comes from key PRESENCE, not a `provider` discriminator.\n// ═════════════════════════════════════════════════════════════════════════════\n\n/**\n * Provider keys actually configured (present and not `undefined`) on a config\n * `C` — the union `defaultProvider`, per-call `provider` overrides, and the\n * mounted Surface A namespaces are all typed from.\n */\nexport type ConfiguredProvider<C extends PayweaveConfig> = {\n [K in PayweaveProviderKey]: C extends Record<K, object> ? K : never;\n}[PayweaveProviderKey];\n\n/** Per-call routing override accepted by every unified op on the client root. */\nexport interface ProviderOverride<P extends PayweaveProviderKey = PayweaveProviderKey> {\n /** Route THIS call to a specific configured provider instead of `defaultProvider`. */\n provider?: P;\n}\n\n/**\n * The unified ops (Surface B) as they appear on the `PayweaveClient` ROOT: the\n * {@link UnifiedNamespace} signatures widened with a per-call `provider`\n * override typed to the CONFIGURED keys only.\n */\nexport interface PayweaveUnifiedOps<P extends PayweaveProviderKey = PayweaveProviderKey> {\n checkout: {\n create(input: CheckoutCreateInput & ProviderOverride<P>): Promise<CheckoutCreateResult>;\n };\n verify(input: VerifyInput & ProviderOverride<P>): Promise<VerifyResult>;\n refunds: {\n create(input: RefundCreateInput & ProviderOverride<P>): Promise<RefundCreateResult>;\n };\n transfers: {\n create(input: TransferCreateInput & ProviderOverride<P>): Promise<TransferCreateResult>;\n };\n banks: {\n list(input: BanksListInput & ProviderOverride<P>): Promise<UnifiedBank[]>;\n resolveAccount(\n input: ResolveAccountInput & ProviderOverride<P>,\n ): Promise<ResolvedAccountResult>;\n };\n}\n\n/** The Surface A namespace at `payweave.flutterwave` when `version` is omitted or `\"v3\"`. */\nexport type FlutterwaveV3Client = FlutterwaveClient & { readonly version: \"v3\" };\n\n/**\n * The Surface A namespace at `payweave.flutterwave` for `version: \"v4\"`\n * configs. v4 resources are a later wave — v3/v4 are version-isolated and\n * never shared, so today this exposes only the shared transport. The type\n * deliberately hides the v3-only resource fields the class leaves unmounted at\n * runtime for v4.\n */\nexport type FlutterwaveV4Client = Pick<FlutterwaveClient, \"http\"> & { readonly version: \"v4\" };\n\n// ── Billing surface type inference ──────\n// `products` becomes type-safe through these three extraction types: every\n// plan id, every feature id, and feature ids narrowed to one `type` (powers\n// `report`'s metered-only compile-time guard). All three resolve to `never`\n// when `C` has no `products` key at all — `never` is only satisfiable by\n// nothing, so `subscribe`/`check`/`report` become uncallable with a real id;\n// calling `subscribe` with no `products` configured is a type error.\n// `const C extends PayweaveConfig` on `createPayweave` (below) is what keeps\n// every literal id intact through here — including when `products` is\n// defined in, and imported from, another module entirely.\n\n/** Every plan id declared in `C[\"products\"]` — `never` when `products` is not configured. */\nexport type PlanIds<C extends PayweaveConfig> = C extends { products: readonly (infer P)[] }\n ? P extends { id: infer Id extends string }\n ? Id\n : never\n : never;\n\n/** Every feature id used across `C[\"products\"]`'s `includes` arrays — `never` when `products` is not configured. */\nexport type FeatureIds<C extends PayweaveConfig> = C extends { products: readonly (infer P)[] }\n ? P extends { includes: readonly (infer Inc)[] }\n ? Inc extends { featureId: infer Id extends string }\n ? Id\n : never\n : never\n : never;\n\n/**\n * {@link FeatureIds} narrowed to inclusions of one feature `type` —\n * `FeatureIdsOf<C, \"metered\">` is intended to make `report`'s `featureId` a\n * compile-time error for a boolean feature id.\n *\n * KNOWN LIMITATION (flagged, not hidden):\n * `Plan<Id, Group, FeatureIds>[\"includes\"]` (`src/products/plan.ts`) is\n * declared as `readonly FeatureInclusion<FeatureIds>[]` — ONE bare string\n * union shared identically by BOTH `BooleanFeatureInclusion<FeatureIds>` and\n * `MeteredFeatureInclusion<FeatureIds>`, with no per-id type tag anywhere\n * accessible. Concretely: for a plan with feature ids `\"a\" | \"b\"`, its\n * `includes` type structurally allows a `type: \"metered\"` reading of `\"a\"`\n * AND `\"b\"` (and independently a `type: \"boolean\"` reading of both) whether\n * or not that combination was ever actually constructed — the ACTUAL\n * per-item correlation between one feature id and its one true type exists\n * only transiently at `plan()`'s own call site (`Def[\"includes\"]`, before\n * `plan()`'s return-type cast erases it) and cannot be recovered from a\n * `Plan` VALUE afterwards. The practical effect, verified empirically: this\n * type currently resolves to the SAME set as {@link FeatureIds} for EITHER\n * `Type`, regardless of which ids are genuinely boolean vs metered — it does\n * not yet narrow. This is the exact case a compile-time error would need the\n * products array to make the type known for — the runtime\n * {@link PayweaveValidationError} guard is therefore the reliable,\n * UNCONDITIONAL enforcement of \"report only accepts metered features,\" not\n * this type. The definition below is kept (rather than being collapsed to a\n * plain alias of `FeatureIds`) so `report`'s signature — and this type's\n * name/shape — need not change if a follow-up widens `Plan.includes` to\n * carry per-id type correlation; this logic would then start narrowing\n * correctly with zero call-site changes.\n */\nexport type FeatureIdsOf<C extends PayweaveConfig, Type extends FeatureType> = C extends {\n products: readonly (infer P)[];\n}\n ? P extends { includes: readonly (infer Inc)[] }\n ? Inc extends { featureId: infer Id extends string; type: Type }\n ? Id\n : never\n : never\n : never;\n\n/**\n * `subscribe()`'s input. `planId` is typed to\n * {@link PlanIds}; `provider` defaults to `defaultProvider` and must be a\n * configured, billing-capable provider.\n */\nexport interface SubscribeInput<C extends PayweaveConfig> {\n /** YOUR user id (external id) — Payweave maps it to provider customers. */\n customerId: string;\n planId: PlanIds<C>;\n /** Defaults to `defaultProvider`; must be a configured, billing-capable provider. */\n provider?: ConfiguredProvider<C>;\n /** Checkout redirect target on success (provider-dependent). */\n successUrl?: string;\n /** Checkout redirect target on cancel (provider-dependent). */\n cancelUrl?: string;\n}\n\n/**\n * `subscribe()`'s discriminated result: a paid plan returns a checkout\n * redirect; a free or default plan activates (or no-ops) locally with no\n * provider object.\n */\nexport type SubscribeResult =\n | { status: \"checkout\"; checkoutUrl: string; reference: string }\n | { status: \"active\"; planId: string; subscription: PwSubscription | null };\n\n/**\n * `check()`'s input. `featureId` is typed to {@link FeatureIds} — any\n * feature, boolean or metered.\n */\nexport interface CheckInput<C extends PayweaveConfig> {\n customerId: string;\n featureId: FeatureIds<C>;\n /** Atomic gate: consume 1 unit iff allowed, in ONE operation. */\n consume?: boolean;\n}\n\n/**\n * `check()`'s result. `balance`/`limit`/`resetsAt` are `null` for boolean\n * features (no usage to track) and for a metered feature the resolved plan\n * doesn't include — a normal \"upsell\" answer, never an error.\n */\nexport interface CheckResult {\n /** Boolean feature: plan includes it. Metered: remaining balance > 0. */\n allowed: boolean;\n /** Remaining units this period; `null` for boolean features or a plan lacking the feature. */\n balance: number | null;\n /** The plan's configured limit; `null` alongside `balance`. */\n limit: number | null;\n /** End of the current billing period; `null` alongside `balance`. */\n resetsAt: Date | null;\n /** The plan that answered — may be the group's default plan id. */\n planId: string;\n}\n\n/**\n * `report()`'s input. `featureId` is typed to {@link FeatureIdsOf}`<C,\n * \"metered\">`, which is INTENDED to make a boolean feature id a compile-time\n * error here — see that type's doc comment for a currently-known gap (it\n * does not yet narrow, given `Plan.includes`'s type shape). The RUNTIME\n * {@link PayweaveValidationError} guard unconditionally rejects a\n * boolean feature id regardless of what the compiler can prove.\n */\nexport interface ReportInput<C extends PayweaveConfig> {\n customerId: string;\n featureId: FeatureIdsOf<C, \"metered\">;\n /** Positive safe integer; defaults to `1` when omitted. */\n amount?: number;\n}\n\n/** `report()`'s result — the post-decrement balance snapshot. */\nexport interface ReportResult {\n balance: number;\n resetsAt: Date;\n}\n\n/**\n * The always-present part of a {@link PayweaveClient}: root props, webhooks,\n * and the unified ops on the ROOT. Provider namespaces are added by the\n * conditional intersections in {@link PayweaveClient}.\n */\nexport interface PayweaveClientBase<C extends PayweaveConfig> {\n /** Configured provider ids in canonical order, e.g. `[\"stripe\", \"paystack\"]`. */\n readonly providers: readonly ConfiguredProvider<C>[];\n /** Resolved routing default for unified ops. */\n readonly defaultProvider: ConfiguredProvider<C>;\n /** Single client-wide environment — mixed test/live is rejected at construction. */\n readonly environment: \"test\" | \"live\";\n /**\n * One namespace for ALL configured providers — the provider is auto-detected\n * from the signature header name and dispatched to its own verifier;\n * unconfigured, ambiguous, or unknown headers fail closed.\n */\n readonly webhooks: WebhooksNamespace;\n /**\n * The unified-ops capability matrix — which of the six unified ops each\n * CONFIGURED provider supports; data, not prose. No argument returns one\n * entry per configured provider; a provider argument returns just that\n * provider's per-op matrix. This is read-only introspection — it never\n * throws for an unsupported op (that's `assertUnifiedCapability`'s job on\n * the actual call path); it DOES throw {@link PayweaveConfigError} if\n * `provider` names a key this client does not have configured.\n */\n capabilities(): Readonly<\n Partial<Record<ConfiguredProvider<C>, Readonly<Record<UnifiedOpName, UnifiedOpCapability>>>>\n >;\n capabilities(\n provider: ConfiguredProvider<C>,\n ): Readonly<Record<UnifiedOpName, UnifiedOpCapability>>;\n /**\n * The `payweave/db/*` adapter passed as `database`, or `undefined` when the\n * billing surface isn't configured.\n */\n readonly database?: DatabaseAdapter | undefined;\n /**\n * Cross-plan-validated, minor-units-resolved `products`, or `undefined`\n * when not configured. See {@link database}'s doc comment.\n */\n readonly products?: readonly ResolvedProduct[] | undefined;\n /**\n * `BillingSync` — push `products`' plan/feature definitions to the\n * database and every configured billing-capable provider (Stripe:\n * Products + Prices; Paystack: Plans; Flutterwave: deferred, see\n * `src/products/sync.ts`'s doc comment for the verified ⚠️ resolution).\n * Idempotent: re-running with unchanged content makes zero provider API\n * writes; a crash mid-push is resumable via `pwv_`-tagged adoption instead\n * of blind-creating duplicates. Exists on the client ALWAYS; throws\n * {@link PayweaveConfigError} at runtime without both `database` and\n * `products` configured. The `payweave push` CLI command drives this same\n * function.\n */\n sync(): Promise<SyncResult>;\n /**\n * Billing surface — exists on the client ALWAYS, but `planId`/`featureId`\n * are typed to `products`: with no `products` configured, {@link PlanIds}\n * is `never` and this is a compile-time error to call with a real plan id.\n * Throws {@link PayweaveConfigError} at runtime when `database` isn't\n * configured — implemented in `src/products/subscribe.ts`.\n */\n subscribe(input: SubscribeInput<C>): Promise<SubscribeResult>;\n /**\n * Billing surface — `featureId` is typed to every feature id across\n * `products`. Throws {@link PayweaveConfigError} at runtime when\n * `database` isn't configured — implemented in `src/products/usage.ts`.\n */\n check(input: CheckInput<C>): Promise<CheckResult>;\n /**\n * Billing surface — `featureId` is intended to be typed to only the\n * METERED feature ids across `products`; see {@link FeatureIdsOf}'s doc\n * comment for a currently-known gap in that narrowing. The RUNTIME\n * {@link PayweaveValidationError} guard enforces metered-only\n * unconditionally regardless of what the compiler can prove; throws\n * {@link PayweaveConfigError} when `database` isn't configured —\n * implemented in `src/products/usage.ts`.\n */\n report(input: ReportInput<C>): Promise<ReportResult>;\n}\n\n/**\n * The readonly client `createPayweave` returns: unified ops on the root\n * routed to `defaultProvider`, plus one Surface A namespace per CONFIGURED\n * provider — an absent config key is a compile-time AND runtime absence, and\n * `flutterwave.version: \"v4\"` narrows its namespace to the v4 surface.\n */\nexport type PayweaveClient<C extends PayweaveConfig> = PayweaveClientBase<C> &\n PayweaveUnifiedOps<ConfiguredProvider<C>> &\n (C extends Record<\"stripe\", object> ? { readonly stripe: StripeClient } : unknown) &\n (C extends Record<\"paystack\", object> ? { readonly paystack: PaystackClient } : unknown) &\n (C extends { flutterwave: { version: \"v4\" } }\n ? { readonly flutterwave: FlutterwaveV4Client }\n : C extends Record<\"flutterwave\", object>\n ? { readonly flutterwave: FlutterwaveV3Client }\n : unknown);\n\n/**\n * Compile-time check that an inline `defaultProvider` must name a CONFIGURED\n * key. The resolver enforces the same rule at runtime for configs assembled\n * dynamically (where `C` is too wide to check).\n */\ntype ValidatePayweaveInput<C extends PayweaveConfig> = C extends { defaultProvider: infer D }\n ? [D] extends [ConfiguredProvider<C> | undefined]\n ? unknown\n : { defaultProvider: ConfiguredProvider<C> }\n : unknown;\n\n/**\n * Unified ops for a configured `stripe` key. The capability matrix\n * (`unified/mappings.ts`'s `UNIFIED_CAPABILITY_MATRIX`) says stripe does NOT\n * support `transfers.create`/`banks.*` — the `guardedRoute` wrapper in\n * `createPayweave` asserts that BEFORE a call ever reaches this namespace, so\n * the two branches below are unreachable through the public surface; they\n * still throw the same typed capability error defensively, in case that\n * guard is ever bypassed.\n *\n * `checkout.create`/`verify`/`refunds.create` ARE capability-supported on\n * stripe (mapped onto `checkout.sessions`/`paymentIntents`/`refunds`) but the\n * unified implementation that actually calls those Stripe resources\n * (`src/unified/stripe.ts`) has not shipped yet — that is separate follow-up\n * work. Calling them today rejects with an honest \"not implemented yet\"\n * error, distinct from a capability gap.\n */\nfunction stripeUnifiedNamespace(): UnifiedNamespace {\n const notImplemented = (op: UnifiedOpName): Promise<never> =>\n Promise.reject(\n new PayweaveError(\n `stripe unified \"${op}\" is supported in principle but not implemented ` +\n \"yet — the resource endpoints landed, but the unified mapping \" +\n \"(`src/unified/stripe.ts`) has not. Use the per-call `provider` override to route to \" +\n \"another configured provider, or call the Surface A `payweave.stripe.*` resources directly.\",\n { provider: \"stripe\", isRetryable: false },\n ),\n );\n const capabilityGap = (op: UnifiedOpName): Promise<never> => {\n try {\n assertUnifiedCapability(\"stripe\", op);\n } catch (err) {\n return Promise.reject(err);\n }\n /* istanbul ignore next -- defensive: unreachable while the matrix marks this op unsupported */\n return Promise.reject(new PayweaveError(`${op} is not supported on stripe.`, { provider: \"stripe\" }));\n };\n return {\n checkout: { create: () => notImplemented(\"checkout.create\") },\n verify: () => notImplemented(\"verify\"),\n refunds: { create: () => notImplemented(\"refunds.create\") },\n transfers: { create: () => capabilityGap(\"transfers.create\") },\n banks: {\n list: () => capabilityGap(\"banks.list\"),\n resolveAccount: () => capabilityGap(\"banks.resolveAccount\"),\n },\n };\n}\n\n/**\n * Create the unified Payweave client.\n *\n * Providers are optional top-level config KEYS (`stripe` / `paystack` /\n * `flutterwave`); at least one is required. The returned client is readonly and\n * fully constructed up front — one {@link HttpClient} per configured provider,\n * no lazy provider init. Unified ops sit on the client root and route to\n * `defaultProvider` unless overridden per call; Surface A namespaces exist\n * ONLY for configured keys (compile-time and runtime).\n *\n * Throws {@link PayweaveConfigError} synchronously for invalid config.\n *\n * @example\n * const payweave = createPayweave({\n * paystack: { secretKey: process.env.PAYSTACK_SECRET_KEY! },\n * flutterwave: { secretKey: process.env.FLW_SECRET_KEY! },\n * defaultProvider: \"paystack\",\n * });\n * await payweave.checkout.create({ amount: { value: 500_000, currency: \"NGN\" }, customer: { email } });\n * await payweave.banks.list({ provider: \"flutterwave\", country: \"NG\" }); // per-call override\n * payweave.paystack.transactions.initialize({ ... }); // Surface A\n */\nexport function createPayweave<const C extends PayweaveConfig>(\n config: C & ValidatePayweaveInput<C>,\n): PayweaveClient<C> {\n const resolved = resolvePayweaveConfig(config);\n\n // One HttpClient per configured provider, built with the exact same\n // wiring as the legacy facade; Surface A namespaces and unified routing\n // share the instance.\n const surfaces: {\n stripe?: StripeClient;\n paystack?: PaystackClient;\n flutterwave?: FlutterwaveClient;\n } = {};\n const unifiedByProvider: Partial<Record<PayweaveProviderKey, UnifiedNamespace>> = {};\n\n for (const key of resolved.providers) {\n const entry = resolved.providerConfigs[key];\n if (entry === undefined) continue; // unreachable — the resolver populates every configured key\n if (key === \"paystack\") {\n const http = buildHttpClient(entry);\n surfaces.paystack = new PaystackClient(http);\n unifiedByProvider.paystack = createPaystackUnified(http);\n } else if (key === \"flutterwave\") {\n const http = buildHttpClient(entry);\n const version = entry.version === \"v4\" ? \"v4\" : \"v3\";\n surfaces.flutterwave = new FlutterwaveClient(http, version, entry.encryptionKey);\n unifiedByProvider.flutterwave = createFlutterwaveUnified(http, version);\n } else {\n // Stripe's transport uses its own options — form-encoded bodies +\n // pinned Stripe-Version — never the JSON default.\n surfaces.stripe = new StripeClient(new HttpClient(stripeHttpOptions(entry)));\n unifiedByProvider.stripe = stripeUnifiedNamespace();\n }\n }\n\n const routeTo = (override: PayweaveProviderKey | undefined): UnifiedNamespace => {\n const key = override ?? resolved.defaultProvider;\n const ns = unifiedByProvider[key];\n if (ns === undefined) {\n // Compile-time-impossible via ConfiguredProvider<C>; reachable when the\n // override comes from untyped/dynamic code — fail with a config error.\n throw new PayweaveConfigError(\n `provider \"${key}\" is not configured on this client — configured: ${resolved.providers.join(\", \")}.`,\n { provider: key },\n );\n }\n return ns;\n };\n\n /**\n * Resolve + capability-guard a unified op call:\n * confirm the target provider is CONFIGURED first (existing `routeTo`\n * behavior, unchanged — a config problem is more fundamental than a\n * capability gap), THEN assert the op is capability-supported on it —\n * throwing the typed `PayweaveValidationError` from\n * `unified/mappings.ts#assertUnifiedCapability` naming the provider + op\n * (e.g. `transfers.create` on stripe) BEFORE any request would be sent.\n */\n const guardedRoute = (\n op: UnifiedOpName,\n override: PayweaveProviderKey | undefined,\n ): UnifiedNamespace => {\n const ns = routeTo(override);\n assertUnifiedCapability(override ?? resolved.defaultProvider, op);\n return ns;\n };\n\n // The root unified ops strip the per-call `provider` override before\n // delegating so it can never leak into an outgoing request body.\n const unified: PayweaveUnifiedOps = {\n checkout: {\n create: ({ provider, ...input }) =>\n guardedRoute(\"checkout.create\", provider).checkout.create(input),\n },\n verify: ({ provider, ...input }) => guardedRoute(\"verify\", provider).verify(input),\n refunds: {\n create: ({ provider, ...input }) =>\n guardedRoute(\"refunds.create\", provider).refunds.create(input),\n },\n transfers: {\n create: ({ provider, ...input }) =>\n guardedRoute(\"transfers.create\", provider).transfers.create(input),\n },\n banks: {\n list: ({ provider, ...input }) => guardedRoute(\"banks.list\", provider).banks.list(input),\n resolveAccount: ({ provider, ...input }) =>\n guardedRoute(\"banks.resolveAccount\", provider).banks.resolveAccount(input),\n },\n };\n\n // `payweave.capabilities()` — read-only\n // introspection over the CONFIGURED providers' slice of\n // `UNIFIED_CAPABILITY_MATRIX`. Overloaded: no-arg returns one entry per\n // configured provider; a provider name returns just that provider's matrix\n // (and throws `PayweaveConfigError` for an unconfigured provider, mirroring\n // `routeTo`'s \"not configured\" behavior).\n function capabilities(): Readonly<\n Partial<Record<PayweaveProviderKey, Readonly<Record<UnifiedOpName, UnifiedOpCapability>>>>\n >;\n function capabilities(\n provider: PayweaveProviderKey,\n ): Readonly<Record<UnifiedOpName, UnifiedOpCapability>>;\n function capabilities(\n provider?: PayweaveProviderKey,\n ):\n | Readonly<Record<UnifiedOpName, UnifiedOpCapability>>\n | Readonly<Partial<Record<PayweaveProviderKey, Readonly<Record<UnifiedOpName, UnifiedOpCapability>>>>> {\n if (provider !== undefined) {\n if (!resolved.providers.includes(provider)) {\n throw new PayweaveConfigError(\n `provider \"${provider}\" is not configured on this client — configured: ${resolved.providers.join(\", \")}.`,\n { provider },\n );\n }\n return UNIFIED_CAPABILITY_MATRIX[provider];\n }\n const out: Partial<Record<PayweaveProviderKey, Readonly<Record<UnifiedOpName, UnifiedOpCapability>>>> =\n {};\n for (const key of resolved.providers) out[key] = UNIFIED_CAPABILITY_MATRIX[key];\n return out;\n }\n\n // Billing surface: the methods exist on the client ALWAYS — `planId`/\n // `featureId` are typed to `products` at compile time (PlanIds/FeatureIds/\n // FeatureIdsOf above). `subscribe` is implemented in\n // `src/products/subscribe.ts`; `check`/`report` are implemented in\n // `src/products/usage.ts` — both throw `PayweaveConfigError` at call time\n // when `database` isn't configured, regardless of what the type system\n // could prove statically.\n\n // The billing module only needs the resolved database/products +\n // provider routing info + the mounted Surface A clients it drives checkout\n // through — never the full `PayweaveClient<C>` (would be circular: this\n // function is still building it). `src/products/usage.ts` reuses the exact\n // same shape.\n const billingContext: BillingContext = {\n database: resolved.database,\n products: resolved.products,\n providers: resolved.providers,\n defaultProvider: resolved.defaultProvider,\n stripe: surfaces.stripe,\n paystack: surfaces.paystack,\n };\n\n const client = {\n providers: resolved.providers,\n defaultProvider: resolved.defaultProvider,\n environment: resolved.environment,\n // Multi-provider header dispatch: the\n // provider is detected from the signature header NAME, then verified with\n // that provider's existing timing-safe verifier — fail closed on\n // unconfigured/ambiguous/unknown headers. `billingContext` (below) is\n // threaded through so every constructed event's `.apply()` can\n // reach the database — the same object the billing surface below uses.\n webhooks: createWebhookDispatch(resolved, billingContext),\n checkout: unified.checkout,\n verify: unified.verify,\n refunds: unified.refunds,\n transfers: unified.transfers,\n banks: unified.banks,\n capabilities,\n // See `PayweaveClientBase.database`'s doc comment.\n database: resolved.database,\n products: resolved.products,\n subscribe: (input: BillingSubscribeInput) => billingSubscribe(billingContext, input),\n // BillingSync push.\n sync: () => billingSync(billingContext),\n // metered usage (real implementations, not stubs).\n check: (input: BillingCheckInput) => billingCheck(billingContext, input),\n report: (input: BillingReportInput) => billingReport(billingContext, input),\n ...surfaces,\n };\n\n return Object.freeze(client) as unknown as PayweaveClient<C>;\n}\n"]}
|