@siglume/direct-request-payment 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.1 - 2026-06-18
4
+
5
+ Hosted Checkout rollout correction release.
6
+
7
+ - Marked Hosted Checkout as Beta / server rollout in the README and API docs so
8
+ merchants do not treat the 0.4.0 surface as universally GA while accounts are
9
+ still being enabled.
10
+ - Added `HostedCheckoutNotAvailableError` (TS + Py). `createCheckoutSession` /
11
+ `create_checkout_session` and `getCheckoutSession` / `get_checkout_session`
12
+ now map rollout 404/409 responses to this explicit error instead of exposing a
13
+ raw missing-route response.
14
+ - Bumped default SDK user agents to 0.4.1.
15
+
3
16
  ## 0.4.0 - 2026-06-18
4
17
 
5
18
  Hosted Checkout for human web shoppers ("Pay with Siglume"). The two buyer
package/README.md CHANGED
@@ -32,7 +32,7 @@ cases the buyer pays from a **Siglume wallet** (JPYC for JPY, USDC for USD) —
32
32
  is **not** a card payment — and your **merchant SDK never authenticates the
33
33
  buyer**.
34
34
 
35
- 1. **Human web shopper → Hosted Checkout.** When a person clicks "Pay with
35
+ 1. **Human web shopper → Hosted Checkout (Beta; server rollout in progress).** When a person clicks "Pay with
36
36
  Siglume" on your site, call
37
37
  [`createCheckoutSession(...)`](#hosted-checkout-human-web-shoppers) and
38
38
  redirect them to the returned `checkout_url`. They sign into Siglume (passkey
@@ -62,6 +62,12 @@ card-style "instant" checkout for first-time buyers.
62
62
 
63
63
  ## Hosted Checkout (Human Web Shoppers)
64
64
 
65
+ **Beta / server rollout:** Hosted Checkout is rolling out account by account.
66
+ Some merchant accounts may not have the server endpoint enabled yet. In that
67
+ case `createCheckoutSession(...)` / `getCheckoutSession(...)` raises
68
+ `HostedCheckoutNotAvailableError` instead of exposing the raw rollout 404/409.
69
+ Keep fulfilling only from the signed `direct_payment.confirmed` webhook.
70
+
65
71
  Hosted Checkout is a Siglume-hosted page that turns a "Pay with Siglume" button
66
72
  into a completed wallet payment, then returns the shopper to your store. It
67
73
  orchestrates the same rails as the agent flow — there is no new money movement
package/dist/index.cjs CHANGED
@@ -40,6 +40,7 @@ __export(src_exports, {
40
40
  DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE: () => DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE,
41
41
  DirectRequestPaymentClient: () => DirectRequestPaymentClient,
42
42
  DirectRequestPaymentMerchantClient: () => DirectRequestPaymentMerchantClient,
43
+ HostedCheckoutNotAvailableError: () => HostedCheckoutNotAvailableError,
43
44
  SiglumeApiError: () => SiglumeApiError,
44
45
  SiglumeDirectRequestPaymentError: () => SiglumeDirectRequestPaymentError,
45
46
  SiglumeWebhookPayloadError: () => SiglumeWebhookPayloadError,
@@ -93,6 +94,12 @@ var SiglumeApiError = class extends SiglumeDirectRequestPaymentError {
93
94
  this.data = options.data;
94
95
  }
95
96
  };
97
+ var HostedCheckoutNotAvailableError = class extends SiglumeApiError {
98
+ constructor(message = "Hosted Checkout is not enabled for this account yet (server rollout in progress).") {
99
+ super(message, { status: 409, code: "HOSTED_CHECKOUT_NOT_ENABLED" });
100
+ this.name = "HostedCheckoutNotAvailableError";
101
+ }
102
+ };
96
103
  var SiglumeWebhookSignatureError = class extends SiglumeDirectRequestPaymentError {
97
104
  constructor(message) {
98
105
  super(message);
@@ -125,7 +132,7 @@ var DirectRequestPaymentClient = class {
125
132
  this.auth_token = authToken;
126
133
  this.base_url = (options.base_url ?? envValue("SIGLUME_API_BASE") ?? DEFAULT_SIGLUME_API_BASE).replace(/\/+$/, "");
127
134
  this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15e3));
128
- this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.4.0";
135
+ this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.4.1";
129
136
  this.fetch_impl = fetchImpl;
130
137
  }
131
138
  async createPaymentRequirement(input) {
@@ -230,7 +237,7 @@ var DirectRequestPaymentMerchantClient = class {
230
237
  this.auth_token = authToken;
231
238
  this.base_url = (options.base_url ?? envValue("SIGLUME_API_BASE") ?? DEFAULT_SIGLUME_API_BASE).replace(/\/+$/, "");
232
239
  this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15e3));
233
- this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.4.0";
240
+ this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.4.1";
234
241
  this.fetch_impl = fetchImpl;
235
242
  }
236
243
  async setupMerchant(input) {
@@ -275,14 +282,14 @@ var DirectRequestPaymentMerchantClient = class {
275
282
  merchant: normalizeSelfServiceMerchant(input.merchant),
276
283
  amount_minor: positiveInteger(input.amount_minor, "amount_minor"),
277
284
  currency: normalizeCurrency(input.currency),
278
- nonce: requireNonEmpty(input.nonce, "nonce"),
285
+ nonce: normalizeChallengeNonce(input.nonce),
279
286
  success_url: requireNonEmpty(input.success_url, "success_url"),
280
287
  cancel_url: requireNonEmpty(input.cancel_url, "cancel_url")
281
288
  };
282
289
  if (input.metadata !== void 0) {
283
290
  payload.metadata = cloneJsonObject(input.metadata, "metadata");
284
291
  }
285
- return this.request(
292
+ return this.requestHostedCheckout(
286
293
  "POST",
287
294
  "/sdrp/direct-payments/checkout-sessions",
288
295
  payload
@@ -290,7 +297,7 @@ var DirectRequestPaymentMerchantClient = class {
290
297
  }
291
298
  /** Read a Hosted Checkout session's status (open / authenticated / paid / expired / cancelled / failed). */
292
299
  async getCheckoutSession(session_id) {
293
- return this.request(
300
+ return this.requestHostedCheckout(
294
301
  "GET",
295
302
  `/sdrp/direct-payments/checkout-sessions/${encodeURIComponent(requireNonEmpty(session_id, "session_id"))}`
296
303
  );
@@ -399,6 +406,16 @@ var DirectRequestPaymentMerchantClient = class {
399
406
  clearTimeout(timeout);
400
407
  }
401
408
  }
409
+ async requestHostedCheckout(method, path, json_body) {
410
+ try {
411
+ return await this.request(method, path, json_body);
412
+ } catch (error) {
413
+ if (isHostedCheckoutUnavailable(error)) {
414
+ throw new HostedCheckoutNotAvailableError();
415
+ }
416
+ throw error;
417
+ }
418
+ }
402
419
  };
403
420
  async function createDirectRequestPaymentChallenge(input) {
404
421
  const merchant = normalizeMerchant(input.merchant);
@@ -745,6 +762,16 @@ function stringOrNull(value) {
745
762
  const text = value.trim();
746
763
  return text ? text : null;
747
764
  }
765
+ function isHostedCheckoutUnavailable(error) {
766
+ if (!(error instanceof SiglumeApiError)) {
767
+ return false;
768
+ }
769
+ const code = error.code.toUpperCase();
770
+ if (error.status === 409 && (code === "HOSTED_CHECKOUT_NOT_ENABLED" || code === "FEATURE_DISABLED")) {
771
+ return true;
772
+ }
773
+ return error.status === 404 && (code === "HTTP_404" || code === "NOT_FOUND" || code === "ROUTE_NOT_FOUND" || code === "FEATURE_DISABLED");
774
+ }
748
775
  function isRecord(value) {
749
776
  return typeof value === "object" && value !== null && !Array.isArray(value);
750
777
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_SIGLUME_API_BASE = \"https://siglume.com/v1\";\nexport const DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME = \"siglume-external-402-v1\";\n// Recurring (subscription / scheduled autopay) approval uses a DISTINCT scheme\n// with cadence bound into the HMAC, so a one-time checkout challenge can never\n// be replayed as a recurring authorization and vice versa.\nexport const DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME = \"siglume-external-402-recurring-v1\";\nexport const DIRECT_REQUEST_PAYMENT_MODE = \"external_402\";\nexport const DIRECT_REQUEST_PAYMENT_RECEIPT_KIND = \"sdrp_direct_payment\";\nexport const DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND = \"sdrp_direct_payment_allowance\";\nexport const DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE = \"sdrp_direct_payment_requirement\";\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n\nexport type DirectRequestPaymentCurrency = \"JPY\" | \"USD\";\nexport type DirectRequestPaymentToken = \"JPYC\" | \"USDC\";\n\nexport interface DirectRequestPaymentChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface ParsedDirectRequestPaymentChallenge {\n scheme: string;\n nonce: string;\n signature: string;\n}\n\n/** \"monthly\" authorizes a Siglume-swept subscription; \"daily\" authorizes\n * merchant-triggered scheduled autopay. It is an approval tag, not a\n * run-count limiter. */\nexport type DirectRequestPaymentRecurringCadence = \"monthly\" | \"daily\";\n\nexport interface DirectRequestPaymentRecurringChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentRecurringChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n cadence: DirectRequestPaymentRecurringCadence;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface Web3TransactionRequest {\n network?: string;\n chain_id?: number;\n from?: string;\n to?: string;\n data?: string;\n value?: string | number;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectPaymentRequirement {\n direct_payment_requirement_id: string;\n requirement_id: string;\n id: string;\n mode: string;\n merchant?: string | null;\n challenge_hash?: string | null;\n buyer_user_id: string;\n agent_id?: string | null;\n product_listing_id: string;\n listing_id: string;\n access_grant_id?: string | null;\n capability_key: string;\n requirement_hash: string;\n request_hash: string;\n siglume_signature: string;\n token_symbol: string;\n currency: string;\n amount_minor: number;\n fee_bps: number;\n status: string;\n expires_at?: string | null;\n confirmed_at?: string | null;\n spent_at?: string | null;\n chain_receipt_id?: string | null;\n transaction_request: Web3TransactionRequest;\n approve_transaction_request?: Web3TransactionRequest | null;\n buyer_confirmation?: string | null;\n non_custodial: boolean;\n metadata_jsonb?: Record<string, unknown>;\n created_at?: string | null;\n updated_at?: string | null;\n}\n\nexport interface DirectPaymentRequirementCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n token_symbol?: DirectRequestPaymentToken | string;\n allowance_amount_minor?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectPaymentVerifyInput {\n receipt_id?: string | null;\n chain_receipt_id?: string | null;\n await_finality?: boolean;\n await_required_status?: string | null;\n await_timeout_seconds?: number;\n await_poll_seconds?: number;\n}\n\nexport interface Web3PreparedTransactionExecutePayload {\n transaction_request: Web3TransactionRequest;\n receipt_kind: string;\n reference_type: typeof DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE;\n reference_id: string;\n metadata?: Record<string, unknown>;\n await_finality?: boolean;\n}\n\nexport interface Web3PreparedTransactionExecuteResult {\n receipt?: Record<string, unknown>;\n finalization?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentClientOptions {\n auth_token?: string;\n base_url?: string;\n fetch?: typeof fetch;\n timeout_ms?: number;\n user_agent?: string;\n}\n\nexport type DirectRequestPaymentBillingPlan = \"launch\" | \"free\" | \"starter\" | \"growth\" | \"pro\";\n\nexport interface DirectRequestPaymentMerchantAccount {\n merchant_account_id: string;\n merchant: string;\n merchant_user_id: string;\n user_wallet_id?: string | null;\n billing_mandate_id?: string | null;\n display_name?: string | null;\n status?: string | null;\n billing_status?: string | null;\n billing_plan?: string | null;\n billing_currency?: string | null;\n token_symbol?: string | null;\n monthly_fee_minor?: number | null;\n settlement_fee_bps?: number | null;\n settlement_fee_min_minor?: number | null;\n included_monthly_payments?: number | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantSetupInput {\n merchant: string;\n display_name?: string;\n billing_plan?: DirectRequestPaymentBillingPlan | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n allowed_currencies?: Record<string, string> | Array<DirectRequestPaymentCurrency | string>;\n webhook_callback_url?: string;\n billing_mandate_cap_minor?: number;\n max_amount_minor?: number;\n // Hosted Checkout return-URL origin allowlist (open-redirect defense). Each\n // entry is an absolute origin such as \"https://shop.example.com\". The origin\n // of webhook_callback_url is auto-allowed in addition to these.\n checkout_allowed_origins?: string[];\n}\n\nexport interface HostedCheckoutSessionCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n success_url: string;\n cancel_url: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface HostedCheckoutSessionCreateResult {\n checkout_url: string;\n session_id: string;\n challenge_hash: string;\n status?: string;\n expires_at?: string | null;\n}\n\nexport interface HostedCheckoutSession {\n session_id: string;\n merchant: string;\n currency: string;\n token_symbol: string;\n amount_minor: number;\n status: string;\n challenge_hash: string;\n requirement_id?: string | null;\n success_url: string;\n cancel_url: string;\n expires_at?: string | null;\n authenticated_at?: string | null;\n paid_at?: string | null;\n cancelled_at?: string | null;\n created_at?: string | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantBillingMandateInput {\n currency?: DirectRequestPaymentCurrency | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantResponse {\n merchant_account: DirectRequestPaymentMerchantAccount;\n challenge_secret?: string | null;\n challenge_secret_created?: boolean;\n created?: boolean | null;\n listing_id?: string | null;\n mandate?: Record<string, unknown> | null;\n next_steps?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscriptionInput {\n callback_url: string;\n description?: string;\n event_types?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscription {\n webhook_subscription_id?: string;\n subscription_id?: string;\n id?: string;\n callback_url?: string;\n signing_secret?: string;\n status?: string;\n event_types?: string[];\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupInput extends DirectRequestPaymentMerchantSetupInput {\n create_webhook_subscription?: boolean;\n prepare_billing_mandate?: boolean;\n webhook_event_types?: string[];\n webhook_description?: string;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupResult {\n merchant: DirectRequestPaymentMerchantResponse;\n billing_mandate?: DirectRequestPaymentMerchantResponse | null;\n webhook_subscription?: DirectRequestPaymentWebhookSubscription | null;\n env: Record<string, string>;\n}\n\nexport interface SiglumeEnvelopeMeta {\n request_id?: string | null;\n trace_id?: string | null;\n [key: string]: unknown;\n}\n\nexport interface WebhookSignatureVerification {\n timestamp: number;\n signature: string;\n}\n\nexport interface DirectRequestPaymentWebhookEvent {\n id: string;\n type: \"direct_payment.confirmed\" | string;\n api_version: string;\n occurred_at: string;\n data: {\n mode?: string;\n merchant?: string;\n direct_payment_requirement_id?: string;\n requirement_id?: string;\n challenge_hash?: string;\n amount_minor?: number;\n currency?: string;\n token_symbol?: string;\n status?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport class SiglumeDirectRequestPaymentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeDirectRequestPaymentError\";\n }\n}\n\nexport class SiglumeApiError extends SiglumeDirectRequestPaymentError {\n readonly status: number;\n readonly code: string;\n readonly data: unknown;\n\n constructor(message: string, options: { status: number; code?: string; data?: unknown }) {\n super(message);\n this.name = \"SiglumeApiError\";\n this.status = options.status;\n this.code = options.code ?? \"SIGLUME_API_ERROR\";\n this.data = options.data;\n }\n}\n\nexport class SiglumeWebhookSignatureError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookSignatureError\";\n }\n}\n\nexport class SiglumeWebhookPayloadError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookPayloadError\";\n }\n}\n\nexport class DirectRequestPaymentClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A buyer Siglume bearer token is required for Direct Request Payment API calls. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.4.0\";\n this.fetch_impl = fetchImpl;\n }\n\n async createPaymentRequirement(input: DirectPaymentRequirementCreateInput): Promise<DirectPaymentRequirement> {\n const payload: Record<string, unknown> = {\n mode: DIRECT_REQUEST_PAYMENT_MODE,\n merchant: normalizeMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n challenge: requireNonEmpty(input.challenge, \"challenge\"),\n };\n if (input.token_symbol !== undefined) {\n payload.token_symbol = normalizeToken(input.token_symbol);\n }\n if (input.allowance_amount_minor !== undefined) {\n payload.allowance_amount_minor = positiveInteger(input.allowance_amount_minor, \"allowance_amount_minor\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectPaymentRequirement>(\"POST\", \"/sdrp/direct-payments/requirements\", payload);\n }\n\n async getPaymentRequirement(requirement_id: string): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"GET\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}`,\n );\n }\n\n async verifyPaymentRequirement(\n requirement_id: string,\n input: DirectPaymentVerifyInput,\n ): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"POST\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}/verify`,\n input,\n );\n }\n\n async executePreparedTransaction(\n payload: Web3PreparedTransactionExecutePayload,\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.request<Web3PreparedTransactionExecuteResult>(\n \"POST\",\n \"/market/web3/transactions/execute-prepared\",\n payload,\n );\n }\n\n async executePaymentTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildPaymentExecutionPayload(requirement, options));\n }\n\n async executeAllowanceTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildAllowanceExecutionPayload(requirement, options));\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class DirectRequestPaymentMerchantClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_MERCHANT_AUTH_TOKEN\") ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A merchant Siglume bearer token is required for Direct Request Payment merchant setup. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.4.0\";\n this.fetch_impl = fetchImpl;\n }\n\n async setupMerchant(input: DirectRequestPaymentMerchantSetupInput): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n billing_plan: normalizeBillingPlan(input.billing_plan ?? \"launch\"),\n billing_currency: normalizeCurrency(input.billing_currency ?? \"JPY\"),\n };\n if (input.display_name !== undefined) {\n payload.display_name = requireNonEmpty(input.display_name, \"display_name\");\n }\n if (input.allowed_currencies !== undefined) {\n payload.allowed_currencies = normalizeAllowedCurrencies(input.allowed_currencies);\n }\n if (input.webhook_callback_url !== undefined) {\n payload.webhook_callback_url = requireNonEmpty(input.webhook_callback_url, \"webhook_callback_url\");\n }\n if (input.billing_mandate_cap_minor !== undefined) {\n payload.billing_mandate_cap_minor = positiveInteger(input.billing_mandate_cap_minor, \"billing_mandate_cap_minor\");\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n if (input.checkout_allowed_origins !== undefined) {\n payload.checkout_allowed_origins = normalizeOriginList(input.checkout_allowed_origins);\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\"POST\", \"/sdrp/direct-payments/merchants\", payload);\n }\n\n /**\n * Create a Hosted Checkout session (Stripe-Checkout-equivalent for human web\n * shoppers). Siglume authors the challenge server-side, persists a single-use\n * expiring session, and returns a `checkout_url`. Redirect the shopper there;\n * they log into Siglume, approve, and pay from their own wallet, then return\n * to your `success_url`. Fulfill on the `direct_payment.confirmed` webhook\n * (the source of truth), exactly as with the agent flow.\n *\n * `success_url`/`cancel_url` must be on an origin you registered via\n * `checkout_allowed_origins` (or your `webhook_callback_url` origin).\n */\n async createCheckoutSession(input: HostedCheckoutSessionCreateInput): Promise<HostedCheckoutSessionCreateResult> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n nonce: requireNonEmpty(input.nonce, \"nonce\"),\n success_url: requireNonEmpty(input.success_url, \"success_url\"),\n cancel_url: requireNonEmpty(input.cancel_url, \"cancel_url\"),\n };\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<HostedCheckoutSessionCreateResult>(\n \"POST\",\n \"/sdrp/direct-payments/checkout-sessions\",\n payload,\n );\n }\n\n /** Read a Hosted Checkout session's status (open / authenticated / paid / expired / cancelled / failed). */\n async getCheckoutSession(session_id: string): Promise<HostedCheckoutSession> {\n return this.request<HostedCheckoutSession>(\n \"GET\",\n `/sdrp/direct-payments/checkout-sessions/${encodeURIComponent(requireNonEmpty(session_id, \"session_id\"))}`,\n );\n }\n\n async getMerchant(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"GET\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}`,\n );\n }\n\n async rotateChallengeSecret(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/challenge-secret/rotate`,\n );\n }\n\n async prepareBillingMandate(\n merchant: string,\n input: DirectRequestPaymentMerchantBillingMandateInput = {},\n ): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {};\n if (input.currency !== undefined) {\n payload.currency = normalizeCurrency(input.currency);\n }\n if (input.billing_currency !== undefined) {\n payload.billing_currency = normalizeCurrency(input.billing_currency);\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/billing-mandate`,\n payload,\n );\n }\n\n async createWebhookSubscription(\n input: DirectRequestPaymentWebhookSubscriptionInput,\n ): Promise<DirectRequestPaymentWebhookSubscription> {\n const payload: Record<string, unknown> = {\n callback_url: requireNonEmpty(input.callback_url, \"callback_url\"),\n event_types: input.event_types?.length\n ? input.event_types.map((eventType) => requireNonEmpty(eventType, \"event_type\"))\n : [\"direct_payment.confirmed\", \"direct_payment.spent\"],\n };\n if (input.description !== undefined) {\n payload.description = requireNonEmpty(input.description, \"description\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectRequestPaymentWebhookSubscription>(\"POST\", \"/market/webhooks/subscriptions\", payload);\n }\n\n async setupCheckout(input: DirectRequestPaymentCheckoutSetupInput): Promise<DirectRequestPaymentCheckoutSetupResult> {\n const merchant = await this.setupMerchant(input);\n const merchantKey = merchant.merchant_account.merchant;\n const billing_mandate = input.prepare_billing_mandate === false\n ? null\n : await this.prepareBillingMandate(merchantKey, {\n billing_currency: merchant.merchant_account.billing_currency ?? input.billing_currency ?? \"JPY\",\n max_amount_minor: input.max_amount_minor ?? input.billing_mandate_cap_minor,\n });\n const shouldCreateWebhook = input.create_webhook_subscription ?? Boolean(input.webhook_callback_url);\n const webhook_subscription = shouldCreateWebhook && input.webhook_callback_url\n ? await this.createWebhookSubscription({\n callback_url: input.webhook_callback_url,\n description: input.webhook_description ?? `${merchantKey} Direct Request Payment`,\n event_types: input.webhook_event_types,\n metadata: { merchant: merchantKey, sdk: \"@siglume/direct-request-payment\" },\n })\n : null;\n const env: Record<string, string> = {\n SIGLUME_DIRECT_PAYMENT_MERCHANT: merchantKey,\n };\n if (merchant.challenge_secret) {\n env.SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET = merchant.challenge_secret;\n }\n const webhookSecret = stringOrNull(webhook_subscription?.signing_secret);\n if (webhookSecret) {\n env.SIGLUME_WEBHOOK_SECRET = webhookSecret;\n }\n return { merchant, billing_mandate, webhook_subscription, env };\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport async function createDirectRequestPaymentChallenge(\n input: DirectRequestPaymentChallengeInput,\n): Promise<DirectRequestPaymentChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = normalizeChallengeNonce(input.nonce);\n const material = `${merchant}:${amount}:${currency}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport function parseDirectRequestPaymentChallenge(challenge: string): ParsedDirectRequestPaymentChallenge {\n const parts = requireNonEmpty(challenge, \"challenge\").split(\":\");\n if (parts.length !== 3) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge must be scheme:nonce:signature.\");\n }\n const [scheme, nonce, signature] = parts;\n if (!scheme || !nonce || !signature) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge is incomplete.\");\n }\n return { scheme, nonce, signature };\n}\n\n/** Merchant-side, ONE-TIME approval of a recurring authorization: amount +\n * currency + cadence are bound into the HMAC. Recurring charges afterwards\n * are deliberately challenge-free; the recurring authorization and the\n * buyer's mandate/budget caps are the per-charge integrity checks. Cadence\n * \"monthly\" = subscription, \"daily\" = scheduled autopay approval tag. */\nexport async function createDirectRequestPaymentRecurringChallenge(\n input: DirectRequestPaymentRecurringChallengeInput,\n): Promise<DirectRequestPaymentRecurringChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentRecurringChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentRecurringChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = normalizeChallengeNonce(input.nonce);\n // MUST stay byte-identical to the server's\n // _external_402_recurring_challenge_signature — both sides change together.\n const material = `${merchant}:${amount}:${currency}:${cadence}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport async function verifyDirectRequestPaymentRecurringChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentRecurringChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n cadence: input.cadence,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function verifyDirectRequestPaymentChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function directRequestPaymentChallengeHash(challenge: string): Promise<string> {\n return sha256Prefixed(requireNonEmpty(challenge, \"challenge\"));\n}\n\nexport async function directRequestPaymentRequestHash(input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n}): Promise<string> {\n const material = `${normalizeMerchant(input.merchant)}${positiveInteger(input.amount_minor, \"amount_minor\")}${normalizeCurrency(input.currency)}${requireNonEmpty(input.challenge, \"challenge\")}`;\n return sha256Prefixed(material);\n}\n\nexport function buildPaymentExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n return buildPreparedTransactionExecutionPayload(requirement, requirement.transaction_request, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildAllowanceExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n const approveRequest = requirement.approve_transaction_request;\n if (!approveRequest || Object.keys(approveRequest).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"This payment requirement does not include an allowance approval transaction.\");\n }\n return buildPreparedTransactionExecutionPayload(requirement, approveRequest, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildPreparedTransactionExecutionPayload(\n requirement: DirectPaymentRequirement,\n transaction_request: Web3TransactionRequest,\n options: {\n receipt_kind: string;\n await_finality?: boolean;\n metadata?: Record<string, unknown>;\n },\n): Web3PreparedTransactionExecutePayload {\n const metadata = {\n ...(isRecord(transaction_request.metadata_jsonb) ? transaction_request.metadata_jsonb : {}),\n ...(options.metadata ?? {}),\n };\n return {\n transaction_request,\n receipt_kind: requireNonEmpty(options.receipt_kind, \"receipt_kind\"),\n reference_type: DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE,\n reference_id: requirement.requirement_id,\n metadata,\n await_finality: Boolean(options.await_finality),\n };\n}\n\nexport async function computeWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp: number },\n): Promise<string> {\n if (!signing_secret) {\n throw new SiglumeWebhookSignatureError(\"SIGLUME webhook signing secret is required.\");\n }\n const timestamp = Math.trunc(options.timestamp);\n const bytes = bodyBytes(body);\n const prefix = new TextEncoder().encode(`${timestamp}.`);\n const payload = new Uint8Array(prefix.length + bytes.length);\n payload.set(prefix, 0);\n payload.set(bytes, prefix.length);\n return hmacSha256Hex(signing_secret, payload);\n}\n\nexport async function buildWebhookSignatureHeader(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = Math.trunc(options.timestamp ?? Date.now() / 1000);\n const signature = await computeWebhookSignature(signing_secret, body, { timestamp });\n return `t=${timestamp},v1=${signature}`;\n}\n\nexport async function verifyWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<WebhookSignatureVerification> {\n const { timestamp, signature } = parseSignatureHeader(signature_header);\n const toleranceSeconds = Math.max(1, Math.trunc(options.tolerance_seconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS));\n const nowSeconds = Math.trunc(options.now ?? Date.now() / 1000);\n if (Math.abs(nowSeconds - timestamp) > toleranceSeconds) {\n throw new SiglumeWebhookSignatureError(\"Webhook timestamp is outside the allowed tolerance window.\");\n }\n const expected = await computeWebhookSignature(signing_secret, body, { timestamp });\n if (!(await timingSafeEqualHex(expected, signature))) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature did not match.\");\n }\n return { timestamp, signature };\n}\n\nexport function parseDirectRequestPaymentWebhookEvent(payload: unknown): DirectRequestPaymentWebhookEvent {\n const event = requireRecord(payload, \"webhook event\");\n const data = requireRecord(event.data, \"webhook event data\");\n const parsed = {\n ...event,\n id: requireNonEmpty(stringOrNull(event.id) ?? \"\", \"webhook event id\"),\n type: requireNonEmpty(stringOrNull(event.type) ?? \"\", \"webhook event type\"),\n api_version: requireNonEmpty(stringOrNull(event.api_version) ?? \"\", \"webhook api_version\"),\n occurred_at: requireNonEmpty(stringOrNull(event.occurred_at) ?? \"\", \"webhook occurred_at\"),\n data: { ...data },\n } as DirectRequestPaymentWebhookEvent;\n if (parsed.type === \"direct_payment.confirmed\" && parsed.data.mode !== DIRECT_REQUEST_PAYMENT_MODE) {\n throw new SiglumeWebhookPayloadError(\"direct_payment.confirmed webhook must carry data.mode='external_402'.\");\n }\n return parsed;\n}\n\nexport async function verifyDirectRequestPaymentWebhook(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<{ event: DirectRequestPaymentWebhookEvent; verification: WebhookSignatureVerification }> {\n const verification = await verifyWebhookSignature(signing_secret, body, signature_header, options);\n const text = new TextDecoder().decode(bodyBytes(body));\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new SiglumeWebhookPayloadError(\"Webhook body must contain valid JSON.\");\n }\n return { event: parseDirectRequestPaymentWebhookEvent(parsed), verification };\n}\n\nexport const createExternal402Challenge = createDirectRequestPaymentChallenge;\nexport const verifyExternal402Challenge = verifyDirectRequestPaymentChallenge;\nexport const createExternal402RecurringChallenge = createDirectRequestPaymentRecurringChallenge;\nexport const verifyExternal402RecurringChallenge = verifyDirectRequestPaymentRecurringChallenge;\n\nfunction normalizeMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be a lowercase key using letters, numbers, dot, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeSelfServiceMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9_-]{2,63}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be 3-64 chars using lowercase letters, numbers, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeBillingPlan(value: string): DirectRequestPaymentBillingPlan {\n const plan = requireNonEmpty(value, \"billing_plan\").toLowerCase();\n if (plan === \"launch\" || plan === \"free\" || plan === \"starter\" || plan === \"growth\" || plan === \"pro\") {\n return plan;\n }\n throw new SiglumeDirectRequestPaymentError(\"billing_plan must be launch, starter, growth, or pro.\");\n}\n\nfunction normalizeCurrency(value: string): DirectRequestPaymentCurrency {\n const currency = requireNonEmpty(value, \"currency\").toUpperCase();\n if (currency !== \"JPY\" && currency !== \"USD\") {\n throw new SiglumeDirectRequestPaymentError(\"currency must be JPY or USD.\");\n }\n return currency;\n}\n\nfunction normalizeToken(value: string): DirectRequestPaymentToken {\n const token = requireNonEmpty(value, \"token_symbol\").toUpperCase();\n if (token !== \"JPYC\" && token !== \"USDC\") {\n throw new SiglumeDirectRequestPaymentError(\"token_symbol must be JPYC or USDC.\");\n }\n return token;\n}\n\nfunction normalizeAllowedCurrencies(value: Record<string, string> | Array<DirectRequestPaymentCurrency | string>): Record<string, string> {\n const normalized: Record<string, string> = {};\n if (Array.isArray(value)) {\n for (const item of value) {\n const currency = normalizeCurrency(item);\n normalized[currency] = defaultTokenForCurrency(currency);\n }\n } else if (isRecord(value)) {\n for (const [rawCurrency, rawToken] of Object.entries(value)) {\n normalized[normalizeCurrency(rawCurrency)] = normalizeToken(String(rawToken));\n }\n } else {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must be an array or a currency-to-token object.\");\n }\n if (Object.keys(normalized).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must include at least one currency.\");\n }\n return normalized;\n}\n\nfunction defaultTokenForCurrency(currency: DirectRequestPaymentCurrency): DirectRequestPaymentToken {\n return currency === \"JPY\" ? \"JPYC\" : \"USDC\";\n}\n\nfunction normalizeOriginList(value: string[]): string[] {\n if (!Array.isArray(value)) {\n throw new SiglumeDirectRequestPaymentError(\"checkout_allowed_origins must be an array of origin URLs.\");\n }\n const seen = new Set<string>();\n const origins: string[] = [];\n for (const item of value) {\n let url: URL;\n try {\n url = new URL(requireNonEmpty(String(item), \"checkout_allowed_origins entry\"));\n } catch {\n throw new SiglumeDirectRequestPaymentError(\n \"each checkout_allowed_origins entry must be an absolute origin such as https://shop.example.com.\",\n );\n }\n const origin = `${url.protocol.toLowerCase()}//${url.host.toLowerCase()}`;\n if (!seen.has(origin)) {\n seen.add(origin);\n origins.push(origin);\n }\n }\n return origins;\n}\n\nfunction positiveInteger(value: number, name: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a positive safe integer.`);\n }\n return parsed;\n}\n\nfunction requireNonEmpty(value: string, name: string): string {\n const text = String(value ?? \"\").trim();\n if (!text) {\n throw new SiglumeDirectRequestPaymentError(`${name} is required.`);\n }\n return text;\n}\n\nfunction normalizeChallengeNonce(value: string): string {\n const nonce = requireNonEmpty(value, \"nonce\");\n if (nonce.includes(\":\")) {\n throw new SiglumeDirectRequestPaymentError(\"nonce must not contain ':'.\");\n }\n return nonce;\n}\n\nfunction normalizeRecurringCadence(value: string): DirectRequestPaymentRecurringCadence {\n const cadence = requireNonEmpty(value, \"cadence\").toLowerCase();\n if (cadence !== \"monthly\" && cadence !== \"daily\") {\n throw new SiglumeDirectRequestPaymentError(\n 'cadence must be \"monthly\" (subscription) or \"daily\" (scheduled autopay).',\n );\n }\n return cadence;\n}\n\nfunction cloneJsonObject(value: Record<string, unknown>, name: string): Record<string, unknown> {\n try {\n const cloned = JSON.parse(JSON.stringify(value)) as unknown;\n if (!isRecord(cloned)) {\n throw new Error(\"not an object\");\n }\n return cloned;\n } catch (error) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a JSON-serializable object.`);\n }\n}\n\nfunction parseJson(rawText: string): unknown {\n try {\n return JSON.parse(rawText);\n } catch (error) {\n throw new SiglumeApiError(\"Siglume API returned invalid JSON.\", {\n status: 502,\n code: \"INVALID_JSON_RESPONSE\",\n data: rawText,\n });\n }\n}\n\nfunction stringOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const text = value.trim();\n return text ? text : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requireRecord(value: unknown, name: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new SiglumeWebhookPayloadError(`${name} must be an object.`);\n }\n return value;\n}\n\nfunction envValue(name: string): string | undefined {\n if (typeof process === \"undefined\") {\n return undefined;\n }\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nfunction bodyBytes(body: Uint8Array | ArrayBuffer | string | Record<string, unknown>): Uint8Array {\n if (body instanceof Uint8Array) {\n return body;\n }\n if (body instanceof ArrayBuffer) {\n return new Uint8Array(body);\n }\n if (typeof body === \"string\") {\n return new TextEncoder().encode(body);\n }\n if (isRecord(body)) {\n return new TextEncoder().encode(JSON.stringify(body));\n }\n throw new SiglumeWebhookPayloadError(\"Webhook body must be raw bytes, a string, or a JSON object.\");\n}\n\nfunction parseSignatureHeader(signatureHeader: string): { timestamp: number; signature: string } {\n let timestamp: number | null = null;\n let signature: string | null = null;\n for (const item of String(signatureHeader ?? \"\").split(\",\")) {\n const [key, value] = item.trim().split(\"=\", 2);\n if (key === \"t\") {\n const parsed = Number.parseInt(value ?? \"\", 10);\n if (!Number.isFinite(parsed)) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature timestamp is invalid.\");\n }\n timestamp = parsed;\n }\n if (key === \"v1\") {\n signature = String(value ?? \"\").trim();\n }\n }\n if (timestamp === null || !signature) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature header is incomplete.\");\n }\n return { timestamp, signature };\n}\n\nasync function randomNonce(): Promise<string> {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(bytes);\n } else if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n bytes.set(crypto.randomBytes(16));\n } else {\n throw new SiglumeDirectRequestPaymentError(\"Crypto random number generation is unavailable in this runtime.\");\n }\n return bytesToHex(bytes);\n}\n\nasync function hmacSha256Hex(secret: string, payload: Uint8Array): Promise<string> {\n if (globalThis.crypto?.subtle) {\n const stablePayload = new Uint8Array(payload.byteLength);\n stablePayload.set(payload);\n const key = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const digest = await globalThis.crypto.subtle.sign(\"HMAC\", key, stablePayload);\n return bytesToHex(new Uint8Array(digest));\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return crypto.createHmac(\"sha256\", secret).update(Buffer.from(payload)).digest(\"hex\");\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for HMAC-SHA256 in this runtime.\");\n}\n\nasync function sha256Prefixed(material: string): Promise<string> {\n const bytes = new TextEncoder().encode(material);\n if (globalThis.crypto?.subtle) {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return `sha256:${bytesToHex(new Uint8Array(digest))}`;\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return `sha256:${crypto.createHash(\"sha256\").update(Buffer.from(bytes)).digest(\"hex\")}`;\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for SHA-256 in this runtime.\");\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return [...bytes].map((item) => item.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const normalized = String(hex ?? \"\").trim().toLowerCase();\n if (normalized.length % 2 !== 0 || !/^[0-9a-f]*$/.test(normalized)) {\n throw new SiglumeWebhookSignatureError(\"Hex digest is invalid.\");\n }\n const bytes = new Uint8Array(normalized.length / 2);\n for (let index = 0; index < normalized.length; index += 2) {\n bytes[index / 2] = Number.parseInt(normalized.slice(index, index + 2), 16);\n }\n return bytes;\n}\n\nasync function timingSafeEqualHex(left: string, right: string): Promise<boolean> {\n const leftBytes = hexToBytes(left);\n const rightBytes = hexToBytes(right);\n if (leftBytes.length !== rightBytes.length) {\n return false;\n }\n let diff = 0;\n for (let index = 0; index < leftBytes.length; index += 1) {\n diff |= leftBytes[index]! ^ rightBytes[index]!;\n }\n return diff === 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,IAAM,2BAA2B;AACjC,IAAM,0CAA0C;AAIhD,IAAM,oDAAoD;AAC1D,IAAM,8BAA8B;AACpC,IAAM,sCAAsC;AAC5C,IAAM,gDAAgD;AACtD,IAAM,wCAAwC;AAC9C,IAAM,oCAAoC;AAyS1C,IAAM,mCAAN,cAA+C,MAAM;AAAA,EAC1D,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAAN,cAA8B,iCAAiC;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,SAA4D;AACvF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ;AACtB,SAAK,OAAO,QAAQ,QAAQ;AAC5B,SAAK,OAAO,QAAQ;AAAA,EACtB;AACF;AAEO,IAAM,+BAAN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RECT_REQUEST_PAYMENT_CHALLENGE_SCHEME = \"siglume-external-402-v1\";\n// Recurring (subscription / scheduled autopay) approval uses a DISTINCT scheme\n// with cadence bound into the HMAC, so a one-time checkout challenge can never\n// be replayed as a recurring authorization and vice versa.\nexport const DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME = \"siglume-external-402-recurring-v1\";\nexport const DIRECT_REQUEST_PAYMENT_MODE = \"external_402\";\nexport const DIRECT_REQUEST_PAYMENT_RECEIPT_KIND = \"sdrp_direct_payment\";\nexport const DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND = \"sdrp_direct_payment_allowance\";\nexport const DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE = \"sdrp_direct_payment_requirement\";\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n\nexport type DirectRequestPaymentCurrency = \"JPY\" | \"USD\";\nexport type DirectRequestPaymentToken = \"JPYC\" | \"USDC\";\n\nexport interface DirectRequestPaymentChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface ParsedDirectRequestPaymentChallenge {\n scheme: string;\n nonce: string;\n signature: string;\n}\n\n/** \"monthly\" authorizes a Siglume-swept subscription; \"daily\" authorizes\n * merchant-triggered scheduled autopay. It is an approval tag, not a\n * run-count limiter. */\nexport type DirectRequestPaymentRecurringCadence = \"monthly\" | \"daily\";\n\nexport interface DirectRequestPaymentRecurringChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentRecurringChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n cadence: DirectRequestPaymentRecurringCadence;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface Web3TransactionRequest {\n network?: string;\n chain_id?: number;\n from?: string;\n to?: string;\n data?: string;\n value?: string | number;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectPaymentRequirement {\n direct_payment_requirement_id: string;\n requirement_id: string;\n id: string;\n mode: string;\n merchant?: string | null;\n challenge_hash?: string | null;\n buyer_user_id: string;\n agent_id?: string | null;\n product_listing_id: string;\n listing_id: string;\n access_grant_id?: string | null;\n capability_key: string;\n requirement_hash: string;\n request_hash: string;\n siglume_signature: string;\n token_symbol: string;\n currency: string;\n amount_minor: number;\n fee_bps: number;\n status: string;\n expires_at?: string | null;\n confirmed_at?: string | null;\n spent_at?: string | null;\n chain_receipt_id?: string | null;\n transaction_request: Web3TransactionRequest;\n approve_transaction_request?: Web3TransactionRequest | null;\n buyer_confirmation?: string | null;\n non_custodial: boolean;\n metadata_jsonb?: Record<string, unknown>;\n created_at?: string | null;\n updated_at?: string | null;\n}\n\nexport interface DirectPaymentRequirementCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n token_symbol?: DirectRequestPaymentToken | string;\n allowance_amount_minor?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectPaymentVerifyInput {\n receipt_id?: string | null;\n chain_receipt_id?: string | null;\n await_finality?: boolean;\n await_required_status?: string | null;\n await_timeout_seconds?: number;\n await_poll_seconds?: number;\n}\n\nexport interface Web3PreparedTransactionExecutePayload {\n transaction_request: Web3TransactionRequest;\n receipt_kind: string;\n reference_type: typeof DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE;\n reference_id: string;\n metadata?: Record<string, unknown>;\n await_finality?: boolean;\n}\n\nexport interface Web3PreparedTransactionExecuteResult {\n receipt?: Record<string, unknown>;\n finalization?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentClientOptions {\n auth_token?: string;\n base_url?: string;\n fetch?: typeof fetch;\n timeout_ms?: number;\n user_agent?: string;\n}\n\nexport type DirectRequestPaymentBillingPlan = \"launch\" | \"free\" | \"starter\" | \"growth\" | \"pro\";\n\nexport interface DirectRequestPaymentMerchantAccount {\n merchant_account_id: string;\n merchant: string;\n merchant_user_id: string;\n user_wallet_id?: string | null;\n billing_mandate_id?: string | null;\n display_name?: string | null;\n status?: string | null;\n billing_status?: string | null;\n billing_plan?: string | null;\n billing_currency?: string | null;\n token_symbol?: string | null;\n monthly_fee_minor?: number | null;\n settlement_fee_bps?: number | null;\n settlement_fee_min_minor?: number | null;\n included_monthly_payments?: number | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantSetupInput {\n merchant: string;\n display_name?: string;\n billing_plan?: DirectRequestPaymentBillingPlan | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n allowed_currencies?: Record<string, string> | Array<DirectRequestPaymentCurrency | string>;\n webhook_callback_url?: string;\n billing_mandate_cap_minor?: number;\n max_amount_minor?: number;\n // Hosted Checkout return-URL origin allowlist (open-redirect defense). Each\n // entry is an absolute origin such as \"https://shop.example.com\". The origin\n // of webhook_callback_url is auto-allowed in addition to these.\n checkout_allowed_origins?: string[];\n}\n\nexport interface HostedCheckoutSessionCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n success_url: string;\n cancel_url: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface HostedCheckoutSessionCreateResult {\n checkout_url: string;\n session_id: string;\n challenge_hash: string;\n status?: string;\n expires_at?: string | null;\n}\n\nexport interface HostedCheckoutSession {\n session_id: string;\n merchant: string;\n currency: string;\n token_symbol: string;\n amount_minor: number;\n status: string;\n challenge_hash: string;\n requirement_id?: string | null;\n success_url: string;\n cancel_url: string;\n expires_at?: string | null;\n authenticated_at?: string | null;\n paid_at?: string | null;\n cancelled_at?: string | null;\n created_at?: string | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantBillingMandateInput {\n currency?: DirectRequestPaymentCurrency | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantResponse {\n merchant_account: DirectRequestPaymentMerchantAccount;\n challenge_secret?: string | null;\n challenge_secret_created?: boolean;\n created?: boolean | null;\n listing_id?: string | null;\n mandate?: Record<string, unknown> | null;\n next_steps?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscriptionInput {\n callback_url: string;\n description?: string;\n event_types?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscription {\n webhook_subscription_id?: string;\n subscription_id?: string;\n id?: string;\n callback_url?: string;\n signing_secret?: string;\n status?: string;\n event_types?: string[];\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupInput extends DirectRequestPaymentMerchantSetupInput {\n create_webhook_subscription?: boolean;\n prepare_billing_mandate?: boolean;\n webhook_event_types?: string[];\n webhook_description?: string;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupResult {\n merchant: DirectRequestPaymentMerchantResponse;\n billing_mandate?: DirectRequestPaymentMerchantResponse | null;\n webhook_subscription?: DirectRequestPaymentWebhookSubscription | null;\n env: Record<string, string>;\n}\n\nexport interface SiglumeEnvelopeMeta {\n request_id?: string | null;\n trace_id?: string | null;\n [key: string]: unknown;\n}\n\nexport interface WebhookSignatureVerification {\n timestamp: number;\n signature: string;\n}\n\nexport interface DirectRequestPaymentWebhookEvent {\n id: string;\n type: \"direct_payment.confirmed\" | string;\n api_version: string;\n occurred_at: string;\n data: {\n mode?: string;\n merchant?: string;\n direct_payment_requirement_id?: string;\n requirement_id?: string;\n challenge_hash?: string;\n amount_minor?: number;\n currency?: string;\n token_symbol?: string;\n status?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport class SiglumeDirectRequestPaymentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeDirectRequestPaymentError\";\n }\n}\n\nexport class SiglumeApiError extends SiglumeDirectRequestPaymentError {\n readonly status: number;\n readonly code: string;\n readonly data: unknown;\n\n constructor(message: string, options: { status: number; code?: string; data?: unknown }) {\n super(message);\n this.name = \"SiglumeApiError\";\n this.status = options.status;\n this.code = options.code ?? \"SIGLUME_API_ERROR\";\n this.data = options.data;\n }\n}\n\nexport class HostedCheckoutNotAvailableError extends SiglumeApiError {\n constructor(message = \"Hosted Checkout is not enabled for this account yet (server rollout in progress).\") {\n super(message, { status: 409, code: \"HOSTED_CHECKOUT_NOT_ENABLED\" });\n this.name = \"HostedCheckoutNotAvailableError\";\n }\n}\n\nexport class SiglumeWebhookSignatureError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookSignatureError\";\n }\n}\n\nexport class SiglumeWebhookPayloadError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookPayloadError\";\n }\n}\n\nexport class DirectRequestPaymentClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A buyer Siglume bearer token is required for Direct Request Payment API calls. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.4.1\";\n this.fetch_impl = fetchImpl;\n }\n\n async createPaymentRequirement(input: DirectPaymentRequirementCreateInput): Promise<DirectPaymentRequirement> {\n const payload: Record<string, unknown> = {\n mode: DIRECT_REQUEST_PAYMENT_MODE,\n merchant: normalizeMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n challenge: requireNonEmpty(input.challenge, \"challenge\"),\n };\n if (input.token_symbol !== undefined) {\n payload.token_symbol = normalizeToken(input.token_symbol);\n }\n if (input.allowance_amount_minor !== undefined) {\n payload.allowance_amount_minor = positiveInteger(input.allowance_amount_minor, \"allowance_amount_minor\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectPaymentRequirement>(\"POST\", \"/sdrp/direct-payments/requirements\", payload);\n }\n\n async getPaymentRequirement(requirement_id: string): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"GET\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}`,\n );\n }\n\n async verifyPaymentRequirement(\n requirement_id: string,\n input: DirectPaymentVerifyInput,\n ): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"POST\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}/verify`,\n input,\n );\n }\n\n async executePreparedTransaction(\n payload: Web3PreparedTransactionExecutePayload,\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.request<Web3PreparedTransactionExecuteResult>(\n \"POST\",\n \"/market/web3/transactions/execute-prepared\",\n payload,\n );\n }\n\n async executePaymentTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildPaymentExecutionPayload(requirement, options));\n }\n\n async executeAllowanceTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildAllowanceExecutionPayload(requirement, options));\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class DirectRequestPaymentMerchantClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_MERCHANT_AUTH_TOKEN\") ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A merchant Siglume bearer token is required for Direct Request Payment merchant setup. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.4.1\";\n this.fetch_impl = fetchImpl;\n }\n\n async setupMerchant(input: DirectRequestPaymentMerchantSetupInput): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n billing_plan: normalizeBillingPlan(input.billing_plan ?? \"launch\"),\n billing_currency: normalizeCurrency(input.billing_currency ?? \"JPY\"),\n };\n if (input.display_name !== undefined) {\n payload.display_name = requireNonEmpty(input.display_name, \"display_name\");\n }\n if (input.allowed_currencies !== undefined) {\n payload.allowed_currencies = normalizeAllowedCurrencies(input.allowed_currencies);\n }\n if (input.webhook_callback_url !== undefined) {\n payload.webhook_callback_url = requireNonEmpty(input.webhook_callback_url, \"webhook_callback_url\");\n }\n if (input.billing_mandate_cap_minor !== undefined) {\n payload.billing_mandate_cap_minor = positiveInteger(input.billing_mandate_cap_minor, \"billing_mandate_cap_minor\");\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n if (input.checkout_allowed_origins !== undefined) {\n payload.checkout_allowed_origins = normalizeOriginList(input.checkout_allowed_origins);\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\"POST\", \"/sdrp/direct-payments/merchants\", payload);\n }\n\n /**\n * Create a Hosted Checkout session (Stripe-Checkout-equivalent for human web\n * shoppers). Siglume authors the challenge server-side, persists a single-use\n * expiring session, and returns a `checkout_url`. Redirect the shopper there;\n * they log into Siglume, approve, and pay from their own wallet, then return\n * to your `success_url`. Fulfill on the `direct_payment.confirmed` webhook\n * (the source of truth), exactly as with the agent flow.\n *\n * `success_url`/`cancel_url` must be on an origin you registered via\n * `checkout_allowed_origins` (or your `webhook_callback_url` origin).\n */\n async createCheckoutSession(input: HostedCheckoutSessionCreateInput): Promise<HostedCheckoutSessionCreateResult> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n nonce: normalizeChallengeNonce(input.nonce),\n success_url: requireNonEmpty(input.success_url, \"success_url\"),\n cancel_url: requireNonEmpty(input.cancel_url, \"cancel_url\"),\n };\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.requestHostedCheckout<HostedCheckoutSessionCreateResult>(\n \"POST\",\n \"/sdrp/direct-payments/checkout-sessions\",\n payload,\n );\n }\n\n /** Read a Hosted Checkout session's status (open / authenticated / paid / expired / cancelled / failed). */\n async getCheckoutSession(session_id: string): Promise<HostedCheckoutSession> {\n return this.requestHostedCheckout<HostedCheckoutSession>(\n \"GET\",\n `/sdrp/direct-payments/checkout-sessions/${encodeURIComponent(requireNonEmpty(session_id, \"session_id\"))}`,\n );\n }\n\n async getMerchant(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"GET\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}`,\n );\n }\n\n async rotateChallengeSecret(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/challenge-secret/rotate`,\n );\n }\n\n async prepareBillingMandate(\n merchant: string,\n input: DirectRequestPaymentMerchantBillingMandateInput = {},\n ): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {};\n if (input.currency !== undefined) {\n payload.currency = normalizeCurrency(input.currency);\n }\n if (input.billing_currency !== undefined) {\n payload.billing_currency = normalizeCurrency(input.billing_currency);\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/billing-mandate`,\n payload,\n );\n }\n\n async createWebhookSubscription(\n input: DirectRequestPaymentWebhookSubscriptionInput,\n ): Promise<DirectRequestPaymentWebhookSubscription> {\n const payload: Record<string, unknown> = {\n callback_url: requireNonEmpty(input.callback_url, \"callback_url\"),\n event_types: input.event_types?.length\n ? input.event_types.map((eventType) => requireNonEmpty(eventType, \"event_type\"))\n : [\"direct_payment.confirmed\", \"direct_payment.spent\"],\n };\n if (input.description !== undefined) {\n payload.description = requireNonEmpty(input.description, \"description\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectRequestPaymentWebhookSubscription>(\"POST\", \"/market/webhooks/subscriptions\", payload);\n }\n\n async setupCheckout(input: DirectRequestPaymentCheckoutSetupInput): Promise<DirectRequestPaymentCheckoutSetupResult> {\n const merchant = await this.setupMerchant(input);\n const merchantKey = merchant.merchant_account.merchant;\n const billing_mandate = input.prepare_billing_mandate === false\n ? null\n : await this.prepareBillingMandate(merchantKey, {\n billing_currency: merchant.merchant_account.billing_currency ?? input.billing_currency ?? \"JPY\",\n max_amount_minor: input.max_amount_minor ?? input.billing_mandate_cap_minor,\n });\n const shouldCreateWebhook = input.create_webhook_subscription ?? Boolean(input.webhook_callback_url);\n const webhook_subscription = shouldCreateWebhook && input.webhook_callback_url\n ? await this.createWebhookSubscription({\n callback_url: input.webhook_callback_url,\n description: input.webhook_description ?? `${merchantKey} Direct Request Payment`,\n event_types: input.webhook_event_types,\n metadata: { merchant: merchantKey, sdk: \"@siglume/direct-request-payment\" },\n })\n : null;\n const env: Record<string, string> = {\n SIGLUME_DIRECT_PAYMENT_MERCHANT: merchantKey,\n };\n if (merchant.challenge_secret) {\n env.SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET = merchant.challenge_secret;\n }\n const webhookSecret = stringOrNull(webhook_subscription?.signing_secret);\n if (webhookSecret) {\n env.SIGLUME_WEBHOOK_SECRET = webhookSecret;\n }\n return { merchant, billing_mandate, webhook_subscription, env };\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n private async requestHostedCheckout<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n try {\n return await this.request<T>(method, path, json_body);\n } catch (error) {\n if (isHostedCheckoutUnavailable(error)) {\n throw new HostedCheckoutNotAvailableError();\n }\n throw error;\n }\n }\n}\n\nexport async function createDirectRequestPaymentChallenge(\n input: DirectRequestPaymentChallengeInput,\n): Promise<DirectRequestPaymentChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = normalizeChallengeNonce(input.nonce);\n const material = `${merchant}:${amount}:${currency}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport function parseDirectRequestPaymentChallenge(challenge: string): ParsedDirectRequestPaymentChallenge {\n const parts = requireNonEmpty(challenge, \"challenge\").split(\":\");\n if (parts.length !== 3) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge must be scheme:nonce:signature.\");\n }\n const [scheme, nonce, signature] = parts;\n if (!scheme || !nonce || !signature) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge is incomplete.\");\n }\n return { scheme, nonce, signature };\n}\n\n/** Merchant-side, ONE-TIME approval of a recurring authorization: amount +\n * currency + cadence are bound into the HMAC. Recurring charges afterwards\n * are deliberately challenge-free; the recurring authorization and the\n * buyer's mandate/budget caps are the per-charge integrity checks. Cadence\n * \"monthly\" = subscription, \"daily\" = scheduled autopay approval tag. */\nexport async function createDirectRequestPaymentRecurringChallenge(\n input: DirectRequestPaymentRecurringChallengeInput,\n): Promise<DirectRequestPaymentRecurringChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentRecurringChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentRecurringChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = normalizeChallengeNonce(input.nonce);\n // MUST stay byte-identical to the server's\n // _external_402_recurring_challenge_signature — both sides change together.\n const material = `${merchant}:${amount}:${currency}:${cadence}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport async function verifyDirectRequestPaymentRecurringChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentRecurringChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n cadence: input.cadence,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function verifyDirectRequestPaymentChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function directRequestPaymentChallengeHash(challenge: string): Promise<string> {\n return sha256Prefixed(requireNonEmpty(challenge, \"challenge\"));\n}\n\nexport async function directRequestPaymentRequestHash(input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n}): Promise<string> {\n const material = `${normalizeMerchant(input.merchant)}${positiveInteger(input.amount_minor, \"amount_minor\")}${normalizeCurrency(input.currency)}${requireNonEmpty(input.challenge, \"challenge\")}`;\n return sha256Prefixed(material);\n}\n\nexport function buildPaymentExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n return buildPreparedTransactionExecutionPayload(requirement, requirement.transaction_request, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildAllowanceExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n const approveRequest = requirement.approve_transaction_request;\n if (!approveRequest || Object.keys(approveRequest).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"This payment requirement does not include an allowance approval transaction.\");\n }\n return buildPreparedTransactionExecutionPayload(requirement, approveRequest, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildPreparedTransactionExecutionPayload(\n requirement: DirectPaymentRequirement,\n transaction_request: Web3TransactionRequest,\n options: {\n receipt_kind: string;\n await_finality?: boolean;\n metadata?: Record<string, unknown>;\n },\n): Web3PreparedTransactionExecutePayload {\n const metadata = {\n ...(isRecord(transaction_request.metadata_jsonb) ? transaction_request.metadata_jsonb : {}),\n ...(options.metadata ?? {}),\n };\n return {\n transaction_request,\n receipt_kind: requireNonEmpty(options.receipt_kind, \"receipt_kind\"),\n reference_type: DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE,\n reference_id: requirement.requirement_id,\n metadata,\n await_finality: Boolean(options.await_finality),\n };\n}\n\nexport async function computeWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp: number },\n): Promise<string> {\n if (!signing_secret) {\n throw new SiglumeWebhookSignatureError(\"SIGLUME webhook signing secret is required.\");\n }\n const timestamp = Math.trunc(options.timestamp);\n const bytes = bodyBytes(body);\n const prefix = new TextEncoder().encode(`${timestamp}.`);\n const payload = new Uint8Array(prefix.length + bytes.length);\n payload.set(prefix, 0);\n payload.set(bytes, prefix.length);\n return hmacSha256Hex(signing_secret, payload);\n}\n\nexport async function buildWebhookSignatureHeader(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = Math.trunc(options.timestamp ?? Date.now() / 1000);\n const signature = await computeWebhookSignature(signing_secret, body, { timestamp });\n return `t=${timestamp},v1=${signature}`;\n}\n\nexport async function verifyWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<WebhookSignatureVerification> {\n const { timestamp, signature } = parseSignatureHeader(signature_header);\n const toleranceSeconds = Math.max(1, Math.trunc(options.tolerance_seconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS));\n const nowSeconds = Math.trunc(options.now ?? Date.now() / 1000);\n if (Math.abs(nowSeconds - timestamp) > toleranceSeconds) {\n throw new SiglumeWebhookSignatureError(\"Webhook timestamp is outside the allowed tolerance window.\");\n }\n const expected = await computeWebhookSignature(signing_secret, body, { timestamp });\n if (!(await timingSafeEqualHex(expected, signature))) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature did not match.\");\n }\n return { timestamp, signature };\n}\n\nexport function parseDirectRequestPaymentWebhookEvent(payload: unknown): DirectRequestPaymentWebhookEvent {\n const event = requireRecord(payload, \"webhook event\");\n const data = requireRecord(event.data, \"webhook event data\");\n const parsed = {\n ...event,\n id: requireNonEmpty(stringOrNull(event.id) ?? \"\", \"webhook event id\"),\n type: requireNonEmpty(stringOrNull(event.type) ?? \"\", \"webhook event type\"),\n api_version: requireNonEmpty(stringOrNull(event.api_version) ?? \"\", \"webhook api_version\"),\n occurred_at: requireNonEmpty(stringOrNull(event.occurred_at) ?? \"\", \"webhook occurred_at\"),\n data: { ...data },\n } as DirectRequestPaymentWebhookEvent;\n if (parsed.type === \"direct_payment.confirmed\" && parsed.data.mode !== DIRECT_REQUEST_PAYMENT_MODE) {\n throw new SiglumeWebhookPayloadError(\"direct_payment.confirmed webhook must carry data.mode='external_402'.\");\n }\n return parsed;\n}\n\nexport async function verifyDirectRequestPaymentWebhook(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<{ event: DirectRequestPaymentWebhookEvent; verification: WebhookSignatureVerification }> {\n const verification = await verifyWebhookSignature(signing_secret, body, signature_header, options);\n const text = new TextDecoder().decode(bodyBytes(body));\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new SiglumeWebhookPayloadError(\"Webhook body must contain valid JSON.\");\n }\n return { event: parseDirectRequestPaymentWebhookEvent(parsed), verification };\n}\n\nexport const createExternal402Challenge = createDirectRequestPaymentChallenge;\nexport const verifyExternal402Challenge = verifyDirectRequestPaymentChallenge;\nexport const createExternal402RecurringChallenge = createDirectRequestPaymentRecurringChallenge;\nexport const verifyExternal402RecurringChallenge = verifyDirectRequestPaymentRecurringChallenge;\n\nfunction normalizeMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be a lowercase key using letters, numbers, dot, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeSelfServiceMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9_-]{2,63}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be 3-64 chars using lowercase letters, numbers, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeBillingPlan(value: string): DirectRequestPaymentBillingPlan {\n const plan = requireNonEmpty(value, \"billing_plan\").toLowerCase();\n if (plan === \"launch\" || plan === \"free\" || plan === \"starter\" || plan === \"growth\" || plan === \"pro\") {\n return plan;\n }\n throw new SiglumeDirectRequestPaymentError(\"billing_plan must be launch, starter, growth, or pro.\");\n}\n\nfunction normalizeCurrency(value: string): DirectRequestPaymentCurrency {\n const currency = requireNonEmpty(value, \"currency\").toUpperCase();\n if (currency !== \"JPY\" && currency !== \"USD\") {\n throw new SiglumeDirectRequestPaymentError(\"currency must be JPY or USD.\");\n }\n return currency;\n}\n\nfunction normalizeToken(value: string): DirectRequestPaymentToken {\n const token = requireNonEmpty(value, \"token_symbol\").toUpperCase();\n if (token !== \"JPYC\" && token !== \"USDC\") {\n throw new SiglumeDirectRequestPaymentError(\"token_symbol must be JPYC or USDC.\");\n }\n return token;\n}\n\nfunction normalizeAllowedCurrencies(value: Record<string, string> | Array<DirectRequestPaymentCurrency | string>): Record<string, string> {\n const normalized: Record<string, string> = {};\n if (Array.isArray(value)) {\n for (const item of value) {\n const currency = normalizeCurrency(item);\n normalized[currency] = defaultTokenForCurrency(currency);\n }\n } else if (isRecord(value)) {\n for (const [rawCurrency, rawToken] of Object.entries(value)) {\n normalized[normalizeCurrency(rawCurrency)] = normalizeToken(String(rawToken));\n }\n } else {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must be an array or a currency-to-token object.\");\n }\n if (Object.keys(normalized).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must include at least one currency.\");\n }\n return normalized;\n}\n\nfunction defaultTokenForCurrency(currency: DirectRequestPaymentCurrency): DirectRequestPaymentToken {\n return currency === \"JPY\" ? \"JPYC\" : \"USDC\";\n}\n\nfunction normalizeOriginList(value: string[]): string[] {\n if (!Array.isArray(value)) {\n throw new SiglumeDirectRequestPaymentError(\"checkout_allowed_origins must be an array of origin URLs.\");\n }\n const seen = new Set<string>();\n const origins: string[] = [];\n for (const item of value) {\n let url: URL;\n try {\n url = new URL(requireNonEmpty(String(item), \"checkout_allowed_origins entry\"));\n } catch {\n throw new SiglumeDirectRequestPaymentError(\n \"each checkout_allowed_origins entry must be an absolute origin such as https://shop.example.com.\",\n );\n }\n const origin = `${url.protocol.toLowerCase()}//${url.host.toLowerCase()}`;\n if (!seen.has(origin)) {\n seen.add(origin);\n origins.push(origin);\n }\n }\n return origins;\n}\n\nfunction positiveInteger(value: number, name: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a positive safe integer.`);\n }\n return parsed;\n}\n\nfunction requireNonEmpty(value: string, name: string): string {\n const text = String(value ?? \"\").trim();\n if (!text) {\n throw new SiglumeDirectRequestPaymentError(`${name} is required.`);\n }\n return text;\n}\n\nfunction normalizeChallengeNonce(value: string): string {\n const nonce = requireNonEmpty(value, \"nonce\");\n if (nonce.includes(\":\")) {\n throw new SiglumeDirectRequestPaymentError(\"nonce must not contain ':'.\");\n }\n return nonce;\n}\n\nfunction normalizeRecurringCadence(value: string): DirectRequestPaymentRecurringCadence {\n const cadence = requireNonEmpty(value, \"cadence\").toLowerCase();\n if (cadence !== \"monthly\" && cadence !== \"daily\") {\n throw new SiglumeDirectRequestPaymentError(\n 'cadence must be \"monthly\" (subscription) or \"daily\" (scheduled autopay).',\n );\n }\n return cadence;\n}\n\nfunction cloneJsonObject(value: Record<string, unknown>, name: string): Record<string, unknown> {\n try {\n const cloned = JSON.parse(JSON.stringify(value)) as unknown;\n if (!isRecord(cloned)) {\n throw new Error(\"not an object\");\n }\n return cloned;\n } catch (error) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a JSON-serializable object.`);\n }\n}\n\nfunction parseJson(rawText: string): unknown {\n try {\n return JSON.parse(rawText);\n } catch (error) {\n throw new SiglumeApiError(\"Siglume API returned invalid JSON.\", {\n status: 502,\n code: \"INVALID_JSON_RESPONSE\",\n data: rawText,\n });\n }\n}\n\nfunction stringOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const text = value.trim();\n return text ? text : null;\n}\n\nfunction isHostedCheckoutUnavailable(error: unknown): boolean {\n if (!(error instanceof SiglumeApiError)) {\n return false;\n }\n const code = error.code.toUpperCase();\n if (error.status === 409 && (code === \"HOSTED_CHECKOUT_NOT_ENABLED\" || code === \"FEATURE_DISABLED\")) {\n return true;\n }\n return (\n error.status === 404 &&\n (code === \"HTTP_404\" || code === \"NOT_FOUND\" || code === \"ROUTE_NOT_FOUND\" || code === \"FEATURE_DISABLED\")\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requireRecord(value: unknown, name: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new SiglumeWebhookPayloadError(`${name} must be an object.`);\n }\n return value;\n}\n\nfunction envValue(name: string): string | undefined {\n if (typeof process === \"undefined\") {\n return undefined;\n }\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nfunction bodyBytes(body: Uint8Array | ArrayBuffer | string | Record<string, unknown>): Uint8Array {\n if (body instanceof Uint8Array) {\n return body;\n }\n if (body instanceof ArrayBuffer) {\n return new Uint8Array(body);\n }\n if (typeof body === \"string\") {\n return new TextEncoder().encode(body);\n }\n if (isRecord(body)) {\n return new TextEncoder().encode(JSON.stringify(body));\n }\n throw new SiglumeWebhookPayloadError(\"Webhook body must be raw bytes, a string, or a JSON object.\");\n}\n\nfunction parseSignatureHeader(signatureHeader: string): { timestamp: number; signature: string } {\n let timestamp: number | null = null;\n let signature: string | null = null;\n for (const item of String(signatureHeader ?? \"\").split(\",\")) {\n const [key, value] = item.trim().split(\"=\", 2);\n if (key === \"t\") {\n const parsed = Number.parseInt(value ?? \"\", 10);\n if (!Number.isFinite(parsed)) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature timestamp is invalid.\");\n }\n timestamp = parsed;\n }\n if (key === \"v1\") {\n signature = String(value ?? \"\").trim();\n }\n }\n if (timestamp === null || !signature) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature header is incomplete.\");\n }\n return { timestamp, signature };\n}\n\nasync function randomNonce(): Promise<string> {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(bytes);\n } else if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n bytes.set(crypto.randomBytes(16));\n } else {\n throw new SiglumeDirectRequestPaymentError(\"Crypto random number generation is unavailable in this runtime.\");\n }\n return bytesToHex(bytes);\n}\n\nasync function hmacSha256Hex(secret: string, payload: Uint8Array): Promise<string> {\n if (globalThis.crypto?.subtle) {\n const stablePayload = new Uint8Array(payload.byteLength);\n stablePayload.set(payload);\n const key = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const digest = await globalThis.crypto.subtle.sign(\"HMAC\", key, stablePayload);\n return bytesToHex(new Uint8Array(digest));\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return crypto.createHmac(\"sha256\", secret).update(Buffer.from(payload)).digest(\"hex\");\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for HMAC-SHA256 in this runtime.\");\n}\n\nasync function sha256Prefixed(material: string): Promise<string> {\n const bytes = new TextEncoder().encode(material);\n if (globalThis.crypto?.subtle) {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return `sha256:${bytesToHex(new Uint8Array(digest))}`;\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return `sha256:${crypto.createHash(\"sha256\").update(Buffer.from(bytes)).digest(\"hex\")}`;\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for SHA-256 in this runtime.\");\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return [...bytes].map((item) => item.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const normalized = String(hex ?? \"\").trim().toLowerCase();\n if (normalized.length % 2 !== 0 || !/^[0-9a-f]*$/.test(normalized)) {\n throw new SiglumeWebhookSignatureError(\"Hex digest is invalid.\");\n }\n const bytes = new Uint8Array(normalized.length / 2);\n for (let index = 0; index < normalized.length; index += 2) {\n bytes[index / 2] = Number.parseInt(normalized.slice(index, index + 2), 16);\n }\n return bytes;\n}\n\nasync function timingSafeEqualHex(left: string, right: string): Promise<boolean> {\n const leftBytes = hexToBytes(left);\n const rightBytes = hexToBytes(right);\n if (leftBytes.length !== rightBytes.length) {\n return false;\n }\n let diff = 0;\n for (let index = 0; index < leftBytes.length; index += 1) {\n diff |= leftBytes[index]! ^ rightBytes[index]!;\n }\n return diff === 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,IAAM,2BAA2B;AACjC,IAAM,0CAA0C;AAIhD,IAAM,oDAAoD;AAC1D,IAAM,8BAA8B;AACpC,IAAM,sCAAsC;AAC5C,IAAM,gDAAgD;AACtD,IAAM,wCAAwC;AAC9C,IAAM,oCAAoC;AAyS1C,IAAM,mCAAN,cAA+C,MAAM;AAAA,EAC1D,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAAN,cAA8B,iCAAiC;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,SAA4D;AACvF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ;AACtB,SAAK,OAAO,QAAQ,QAAQ;AAC5B,SAAK,OAAO,QAAQ;AAAA,EACtB;AACF;AAEO,IAAM,kCAAN,cAA8C,gBAAgB;AAAA,EACnE,YAAY,UAAU,qFAAqF;AACzG,UAAM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AAI,WAAW,WAAW,SAAS,CAAC;AAClD,WAAS,QAAQ,GAAG,QAAQ,WAAW,QAAQ,SAAS,GAAG;AACzD,UAAM,QAAQ,CAAC,IAAI,OAAO,SAAS,WAAW,MAAM,OAAO,QAAQ,CAAC,GAAG,EAAE;AAAA,EAC3E;AACA,SAAO;AACT;AAEA,eAAe,mBAAmB,MAAc,OAAiC;AAC/E,QAAM,YAAY,WAAW,IAAI;AACjC,QAAM,aAAa,WAAW,KAAK;AACnC,MAAI,UAAU,WAAW,WAAW,QAAQ;AAC1C,WAAO;AAAA,EACT;AACA,MAAI,OAAO;AACX,WAAS,QAAQ,GAAG,QAAQ,UAAU,QAAQ,SAAS,GAAG;AACxD,YAAQ,UAAU,KAAK,IAAK,WAAW,KAAK;AAAA,EAC9C;AACA,SAAO,SAAS;AAClB;","names":[]}
package/dist/index.d.cts CHANGED
@@ -282,6 +282,9 @@ declare class SiglumeApiError extends SiglumeDirectRequestPaymentError {
282
282
  data?: unknown;
283
283
  });
284
284
  }
285
+ declare class HostedCheckoutNotAvailableError extends SiglumeApiError {
286
+ constructor(message?: string);
287
+ }
285
288
  declare class SiglumeWebhookSignatureError extends SiglumeDirectRequestPaymentError {
286
289
  constructor(message: string);
287
290
  }
@@ -337,6 +340,7 @@ declare class DirectRequestPaymentMerchantClient {
337
340
  createWebhookSubscription(input: DirectRequestPaymentWebhookSubscriptionInput): Promise<DirectRequestPaymentWebhookSubscription>;
338
341
  setupCheckout(input: DirectRequestPaymentCheckoutSetupInput): Promise<DirectRequestPaymentCheckoutSetupResult>;
339
342
  request<T>(method: string, path: string, json_body?: unknown): Promise<T>;
343
+ private requestHostedCheckout;
340
344
  }
341
345
  declare function createDirectRequestPaymentChallenge(input: DirectRequestPaymentChallengeInput): Promise<DirectRequestPaymentChallenge>;
342
346
  declare function createDirectRequestPaymentChallengeSignature(secret: string, input: {
@@ -415,4 +419,4 @@ declare const verifyExternal402Challenge: typeof verifyDirectRequestPaymentChall
415
419
  declare const createExternal402RecurringChallenge: typeof createDirectRequestPaymentRecurringChallenge;
416
420
  declare const verifyExternal402RecurringChallenge: typeof verifyDirectRequestPaymentRecurringChallenge;
417
421
 
418
- export { DEFAULT_SIGLUME_API_BASE, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND, DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME, DIRECT_REQUEST_PAYMENT_MODE, DIRECT_REQUEST_PAYMENT_RECEIPT_KIND, DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME, DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE, type DirectPaymentRequirement, type DirectPaymentRequirementCreateInput, type DirectPaymentVerifyInput, type DirectRequestPaymentBillingPlan, type DirectRequestPaymentChallenge, type DirectRequestPaymentChallengeInput, type DirectRequestPaymentCheckoutSetupInput, type DirectRequestPaymentCheckoutSetupResult, DirectRequestPaymentClient, type DirectRequestPaymentClientOptions, type DirectRequestPaymentCurrency, type DirectRequestPaymentMerchantAccount, type DirectRequestPaymentMerchantBillingMandateInput, DirectRequestPaymentMerchantClient, type DirectRequestPaymentMerchantResponse, type DirectRequestPaymentMerchantSetupInput, type DirectRequestPaymentRecurringCadence, type DirectRequestPaymentRecurringChallenge, type DirectRequestPaymentRecurringChallengeInput, type DirectRequestPaymentToken, type DirectRequestPaymentWebhookEvent, type DirectRequestPaymentWebhookSubscription, type DirectRequestPaymentWebhookSubscriptionInput, type HostedCheckoutSession, type HostedCheckoutSessionCreateInput, type HostedCheckoutSessionCreateResult, type ParsedDirectRequestPaymentChallenge, SiglumeApiError, SiglumeDirectRequestPaymentError, type SiglumeEnvelopeMeta, SiglumeWebhookPayloadError, SiglumeWebhookSignatureError, type Web3PreparedTransactionExecutePayload, type Web3PreparedTransactionExecuteResult, type Web3TransactionRequest, type WebhookSignatureVerification, buildAllowanceExecutionPayload, buildPaymentExecutionPayload, buildPreparedTransactionExecutionPayload, buildWebhookSignatureHeader, computeWebhookSignature, createDirectRequestPaymentChallenge, createDirectRequestPaymentChallengeSignature, createDirectRequestPaymentRecurringChallenge, createDirectRequestPaymentRecurringChallengeSignature, createExternal402Challenge, createExternal402RecurringChallenge, directRequestPaymentChallengeHash, directRequestPaymentRequestHash, parseDirectRequestPaymentChallenge, parseDirectRequestPaymentWebhookEvent, verifyDirectRequestPaymentChallenge, verifyDirectRequestPaymentRecurringChallenge, verifyDirectRequestPaymentWebhook, verifyExternal402Challenge, verifyExternal402RecurringChallenge, verifyWebhookSignature };
422
+ export { DEFAULT_SIGLUME_API_BASE, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND, DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME, DIRECT_REQUEST_PAYMENT_MODE, DIRECT_REQUEST_PAYMENT_RECEIPT_KIND, DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME, DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE, type DirectPaymentRequirement, type DirectPaymentRequirementCreateInput, type DirectPaymentVerifyInput, type DirectRequestPaymentBillingPlan, type DirectRequestPaymentChallenge, type DirectRequestPaymentChallengeInput, type DirectRequestPaymentCheckoutSetupInput, type DirectRequestPaymentCheckoutSetupResult, DirectRequestPaymentClient, type DirectRequestPaymentClientOptions, type DirectRequestPaymentCurrency, type DirectRequestPaymentMerchantAccount, type DirectRequestPaymentMerchantBillingMandateInput, DirectRequestPaymentMerchantClient, type DirectRequestPaymentMerchantResponse, type DirectRequestPaymentMerchantSetupInput, type DirectRequestPaymentRecurringCadence, type DirectRequestPaymentRecurringChallenge, type DirectRequestPaymentRecurringChallengeInput, type DirectRequestPaymentToken, type DirectRequestPaymentWebhookEvent, type DirectRequestPaymentWebhookSubscription, type DirectRequestPaymentWebhookSubscriptionInput, HostedCheckoutNotAvailableError, type HostedCheckoutSession, type HostedCheckoutSessionCreateInput, type HostedCheckoutSessionCreateResult, type ParsedDirectRequestPaymentChallenge, SiglumeApiError, SiglumeDirectRequestPaymentError, type SiglumeEnvelopeMeta, SiglumeWebhookPayloadError, SiglumeWebhookSignatureError, type Web3PreparedTransactionExecutePayload, type Web3PreparedTransactionExecuteResult, type Web3TransactionRequest, type WebhookSignatureVerification, buildAllowanceExecutionPayload, buildPaymentExecutionPayload, buildPreparedTransactionExecutionPayload, buildWebhookSignatureHeader, computeWebhookSignature, createDirectRequestPaymentChallenge, createDirectRequestPaymentChallengeSignature, createDirectRequestPaymentRecurringChallenge, createDirectRequestPaymentRecurringChallengeSignature, createExternal402Challenge, createExternal402RecurringChallenge, directRequestPaymentChallengeHash, directRequestPaymentRequestHash, parseDirectRequestPaymentChallenge, parseDirectRequestPaymentWebhookEvent, verifyDirectRequestPaymentChallenge, verifyDirectRequestPaymentRecurringChallenge, verifyDirectRequestPaymentWebhook, verifyExternal402Challenge, verifyExternal402RecurringChallenge, verifyWebhookSignature };
package/dist/index.d.ts CHANGED
@@ -282,6 +282,9 @@ declare class SiglumeApiError extends SiglumeDirectRequestPaymentError {
282
282
  data?: unknown;
283
283
  });
284
284
  }
285
+ declare class HostedCheckoutNotAvailableError extends SiglumeApiError {
286
+ constructor(message?: string);
287
+ }
285
288
  declare class SiglumeWebhookSignatureError extends SiglumeDirectRequestPaymentError {
286
289
  constructor(message: string);
287
290
  }
@@ -337,6 +340,7 @@ declare class DirectRequestPaymentMerchantClient {
337
340
  createWebhookSubscription(input: DirectRequestPaymentWebhookSubscriptionInput): Promise<DirectRequestPaymentWebhookSubscription>;
338
341
  setupCheckout(input: DirectRequestPaymentCheckoutSetupInput): Promise<DirectRequestPaymentCheckoutSetupResult>;
339
342
  request<T>(method: string, path: string, json_body?: unknown): Promise<T>;
343
+ private requestHostedCheckout;
340
344
  }
341
345
  declare function createDirectRequestPaymentChallenge(input: DirectRequestPaymentChallengeInput): Promise<DirectRequestPaymentChallenge>;
342
346
  declare function createDirectRequestPaymentChallengeSignature(secret: string, input: {
@@ -415,4 +419,4 @@ declare const verifyExternal402Challenge: typeof verifyDirectRequestPaymentChall
415
419
  declare const createExternal402RecurringChallenge: typeof createDirectRequestPaymentRecurringChallenge;
416
420
  declare const verifyExternal402RecurringChallenge: typeof verifyDirectRequestPaymentRecurringChallenge;
417
421
 
418
- export { DEFAULT_SIGLUME_API_BASE, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND, DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME, DIRECT_REQUEST_PAYMENT_MODE, DIRECT_REQUEST_PAYMENT_RECEIPT_KIND, DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME, DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE, type DirectPaymentRequirement, type DirectPaymentRequirementCreateInput, type DirectPaymentVerifyInput, type DirectRequestPaymentBillingPlan, type DirectRequestPaymentChallenge, type DirectRequestPaymentChallengeInput, type DirectRequestPaymentCheckoutSetupInput, type DirectRequestPaymentCheckoutSetupResult, DirectRequestPaymentClient, type DirectRequestPaymentClientOptions, type DirectRequestPaymentCurrency, type DirectRequestPaymentMerchantAccount, type DirectRequestPaymentMerchantBillingMandateInput, DirectRequestPaymentMerchantClient, type DirectRequestPaymentMerchantResponse, type DirectRequestPaymentMerchantSetupInput, type DirectRequestPaymentRecurringCadence, type DirectRequestPaymentRecurringChallenge, type DirectRequestPaymentRecurringChallengeInput, type DirectRequestPaymentToken, type DirectRequestPaymentWebhookEvent, type DirectRequestPaymentWebhookSubscription, type DirectRequestPaymentWebhookSubscriptionInput, type HostedCheckoutSession, type HostedCheckoutSessionCreateInput, type HostedCheckoutSessionCreateResult, type ParsedDirectRequestPaymentChallenge, SiglumeApiError, SiglumeDirectRequestPaymentError, type SiglumeEnvelopeMeta, SiglumeWebhookPayloadError, SiglumeWebhookSignatureError, type Web3PreparedTransactionExecutePayload, type Web3PreparedTransactionExecuteResult, type Web3TransactionRequest, type WebhookSignatureVerification, buildAllowanceExecutionPayload, buildPaymentExecutionPayload, buildPreparedTransactionExecutionPayload, buildWebhookSignatureHeader, computeWebhookSignature, createDirectRequestPaymentChallenge, createDirectRequestPaymentChallengeSignature, createDirectRequestPaymentRecurringChallenge, createDirectRequestPaymentRecurringChallengeSignature, createExternal402Challenge, createExternal402RecurringChallenge, directRequestPaymentChallengeHash, directRequestPaymentRequestHash, parseDirectRequestPaymentChallenge, parseDirectRequestPaymentWebhookEvent, verifyDirectRequestPaymentChallenge, verifyDirectRequestPaymentRecurringChallenge, verifyDirectRequestPaymentWebhook, verifyExternal402Challenge, verifyExternal402RecurringChallenge, verifyWebhookSignature };
422
+ export { DEFAULT_SIGLUME_API_BASE, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND, DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME, DIRECT_REQUEST_PAYMENT_MODE, DIRECT_REQUEST_PAYMENT_RECEIPT_KIND, DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME, DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE, type DirectPaymentRequirement, type DirectPaymentRequirementCreateInput, type DirectPaymentVerifyInput, type DirectRequestPaymentBillingPlan, type DirectRequestPaymentChallenge, type DirectRequestPaymentChallengeInput, type DirectRequestPaymentCheckoutSetupInput, type DirectRequestPaymentCheckoutSetupResult, DirectRequestPaymentClient, type DirectRequestPaymentClientOptions, type DirectRequestPaymentCurrency, type DirectRequestPaymentMerchantAccount, type DirectRequestPaymentMerchantBillingMandateInput, DirectRequestPaymentMerchantClient, type DirectRequestPaymentMerchantResponse, type DirectRequestPaymentMerchantSetupInput, type DirectRequestPaymentRecurringCadence, type DirectRequestPaymentRecurringChallenge, type DirectRequestPaymentRecurringChallengeInput, type DirectRequestPaymentToken, type DirectRequestPaymentWebhookEvent, type DirectRequestPaymentWebhookSubscription, type DirectRequestPaymentWebhookSubscriptionInput, HostedCheckoutNotAvailableError, type HostedCheckoutSession, type HostedCheckoutSessionCreateInput, type HostedCheckoutSessionCreateResult, type ParsedDirectRequestPaymentChallenge, SiglumeApiError, SiglumeDirectRequestPaymentError, type SiglumeEnvelopeMeta, SiglumeWebhookPayloadError, SiglumeWebhookSignatureError, type Web3PreparedTransactionExecutePayload, type Web3PreparedTransactionExecuteResult, type Web3TransactionRequest, type WebhookSignatureVerification, buildAllowanceExecutionPayload, buildPaymentExecutionPayload, buildPreparedTransactionExecutionPayload, buildWebhookSignatureHeader, computeWebhookSignature, createDirectRequestPaymentChallenge, createDirectRequestPaymentChallengeSignature, createDirectRequestPaymentRecurringChallenge, createDirectRequestPaymentRecurringChallengeSignature, createExternal402Challenge, createExternal402RecurringChallenge, directRequestPaymentChallengeHash, directRequestPaymentRequestHash, parseDirectRequestPaymentChallenge, parseDirectRequestPaymentWebhookEvent, verifyDirectRequestPaymentChallenge, verifyDirectRequestPaymentRecurringChallenge, verifyDirectRequestPaymentWebhook, verifyExternal402Challenge, verifyExternal402RecurringChallenge, verifyWebhookSignature };
package/dist/index.js CHANGED
@@ -25,6 +25,12 @@ var SiglumeApiError = class extends SiglumeDirectRequestPaymentError {
25
25
  this.data = options.data;
26
26
  }
27
27
  };
28
+ var HostedCheckoutNotAvailableError = class extends SiglumeApiError {
29
+ constructor(message = "Hosted Checkout is not enabled for this account yet (server rollout in progress).") {
30
+ super(message, { status: 409, code: "HOSTED_CHECKOUT_NOT_ENABLED" });
31
+ this.name = "HostedCheckoutNotAvailableError";
32
+ }
33
+ };
28
34
  var SiglumeWebhookSignatureError = class extends SiglumeDirectRequestPaymentError {
29
35
  constructor(message) {
30
36
  super(message);
@@ -57,7 +63,7 @@ var DirectRequestPaymentClient = class {
57
63
  this.auth_token = authToken;
58
64
  this.base_url = (options.base_url ?? envValue("SIGLUME_API_BASE") ?? DEFAULT_SIGLUME_API_BASE).replace(/\/+$/, "");
59
65
  this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15e3));
60
- this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.4.0";
66
+ this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.4.1";
61
67
  this.fetch_impl = fetchImpl;
62
68
  }
63
69
  async createPaymentRequirement(input) {
@@ -162,7 +168,7 @@ var DirectRequestPaymentMerchantClient = class {
162
168
  this.auth_token = authToken;
163
169
  this.base_url = (options.base_url ?? envValue("SIGLUME_API_BASE") ?? DEFAULT_SIGLUME_API_BASE).replace(/\/+$/, "");
164
170
  this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15e3));
165
- this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.4.0";
171
+ this.user_agent = options.user_agent ?? "@siglume/direct-request-payment/0.4.1";
166
172
  this.fetch_impl = fetchImpl;
167
173
  }
168
174
  async setupMerchant(input) {
@@ -207,14 +213,14 @@ var DirectRequestPaymentMerchantClient = class {
207
213
  merchant: normalizeSelfServiceMerchant(input.merchant),
208
214
  amount_minor: positiveInteger(input.amount_minor, "amount_minor"),
209
215
  currency: normalizeCurrency(input.currency),
210
- nonce: requireNonEmpty(input.nonce, "nonce"),
216
+ nonce: normalizeChallengeNonce(input.nonce),
211
217
  success_url: requireNonEmpty(input.success_url, "success_url"),
212
218
  cancel_url: requireNonEmpty(input.cancel_url, "cancel_url")
213
219
  };
214
220
  if (input.metadata !== void 0) {
215
221
  payload.metadata = cloneJsonObject(input.metadata, "metadata");
216
222
  }
217
- return this.request(
223
+ return this.requestHostedCheckout(
218
224
  "POST",
219
225
  "/sdrp/direct-payments/checkout-sessions",
220
226
  payload
@@ -222,7 +228,7 @@ var DirectRequestPaymentMerchantClient = class {
222
228
  }
223
229
  /** Read a Hosted Checkout session's status (open / authenticated / paid / expired / cancelled / failed). */
224
230
  async getCheckoutSession(session_id) {
225
- return this.request(
231
+ return this.requestHostedCheckout(
226
232
  "GET",
227
233
  `/sdrp/direct-payments/checkout-sessions/${encodeURIComponent(requireNonEmpty(session_id, "session_id"))}`
228
234
  );
@@ -331,6 +337,16 @@ var DirectRequestPaymentMerchantClient = class {
331
337
  clearTimeout(timeout);
332
338
  }
333
339
  }
340
+ async requestHostedCheckout(method, path, json_body) {
341
+ try {
342
+ return await this.request(method, path, json_body);
343
+ } catch (error) {
344
+ if (isHostedCheckoutUnavailable(error)) {
345
+ throw new HostedCheckoutNotAvailableError();
346
+ }
347
+ throw error;
348
+ }
349
+ }
334
350
  };
335
351
  async function createDirectRequestPaymentChallenge(input) {
336
352
  const merchant = normalizeMerchant(input.merchant);
@@ -677,6 +693,16 @@ function stringOrNull(value) {
677
693
  const text = value.trim();
678
694
  return text ? text : null;
679
695
  }
696
+ function isHostedCheckoutUnavailable(error) {
697
+ if (!(error instanceof SiglumeApiError)) {
698
+ return false;
699
+ }
700
+ const code = error.code.toUpperCase();
701
+ if (error.status === 409 && (code === "HOSTED_CHECKOUT_NOT_ENABLED" || code === "FEATURE_DISABLED")) {
702
+ return true;
703
+ }
704
+ return error.status === 404 && (code === "HTTP_404" || code === "NOT_FOUND" || code === "ROUTE_NOT_FOUND" || code === "FEATURE_DISABLED");
705
+ }
680
706
  function isRecord(value) {
681
707
  return typeof value === "object" && value !== null && !Array.isArray(value);
682
708
  }
@@ -813,6 +839,7 @@ export {
813
839
  DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE,
814
840
  DirectRequestPaymentClient,
815
841
  DirectRequestPaymentMerchantClient,
842
+ HostedCheckoutNotAvailableError,
816
843
  SiglumeApiError,
817
844
  SiglumeDirectRequestPaymentError,
818
845
  SiglumeWebhookPayloadError,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_SIGLUME_API_BASE = \"https://siglume.com/v1\";\nexport const DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME = \"siglume-external-402-v1\";\n// Recurring (subscription / scheduled autopay) approval uses a DISTINCT scheme\n// with cadence bound into the HMAC, so a one-time checkout challenge can never\n// be replayed as a recurring authorization and vice versa.\nexport const DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME = \"siglume-external-402-recurring-v1\";\nexport const DIRECT_REQUEST_PAYMENT_MODE = \"external_402\";\nexport const DIRECT_REQUEST_PAYMENT_RECEIPT_KIND = \"sdrp_direct_payment\";\nexport const DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND = \"sdrp_direct_payment_allowance\";\nexport const DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE = \"sdrp_direct_payment_requirement\";\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n\nexport type DirectRequestPaymentCurrency = \"JPY\" | \"USD\";\nexport type DirectRequestPaymentToken = \"JPYC\" | \"USDC\";\n\nexport interface DirectRequestPaymentChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface ParsedDirectRequestPaymentChallenge {\n scheme: string;\n nonce: string;\n signature: string;\n}\n\n/** \"monthly\" authorizes a Siglume-swept subscription; \"daily\" authorizes\n * merchant-triggered scheduled autopay. It is an approval tag, not a\n * run-count limiter. */\nexport type DirectRequestPaymentRecurringCadence = \"monthly\" | \"daily\";\n\nexport interface DirectRequestPaymentRecurringChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentRecurringChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n cadence: DirectRequestPaymentRecurringCadence;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface Web3TransactionRequest {\n network?: string;\n chain_id?: number;\n from?: string;\n to?: string;\n data?: string;\n value?: string | number;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectPaymentRequirement {\n direct_payment_requirement_id: string;\n requirement_id: string;\n id: string;\n mode: string;\n merchant?: string | null;\n challenge_hash?: string | null;\n buyer_user_id: string;\n agent_id?: string | null;\n product_listing_id: string;\n listing_id: string;\n access_grant_id?: string | null;\n capability_key: string;\n requirement_hash: string;\n request_hash: string;\n siglume_signature: string;\n token_symbol: string;\n currency: string;\n amount_minor: number;\n fee_bps: number;\n status: string;\n expires_at?: string | null;\n confirmed_at?: string | null;\n spent_at?: string | null;\n chain_receipt_id?: string | null;\n transaction_request: Web3TransactionRequest;\n approve_transaction_request?: Web3TransactionRequest | null;\n buyer_confirmation?: string | null;\n non_custodial: boolean;\n metadata_jsonb?: Record<string, unknown>;\n created_at?: string | null;\n updated_at?: string | null;\n}\n\nexport interface DirectPaymentRequirementCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n token_symbol?: DirectRequestPaymentToken | string;\n allowance_amount_minor?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectPaymentVerifyInput {\n receipt_id?: string | null;\n chain_receipt_id?: string | null;\n await_finality?: boolean;\n await_required_status?: string | null;\n await_timeout_seconds?: number;\n await_poll_seconds?: number;\n}\n\nexport interface Web3PreparedTransactionExecutePayload {\n transaction_request: Web3TransactionRequest;\n receipt_kind: string;\n reference_type: typeof DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE;\n reference_id: string;\n metadata?: Record<string, unknown>;\n await_finality?: boolean;\n}\n\nexport interface Web3PreparedTransactionExecuteResult {\n receipt?: Record<string, unknown>;\n finalization?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentClientOptions {\n auth_token?: string;\n base_url?: string;\n fetch?: typeof fetch;\n timeout_ms?: number;\n user_agent?: string;\n}\n\nexport type DirectRequestPaymentBillingPlan = \"launch\" | \"free\" | \"starter\" | \"growth\" | \"pro\";\n\nexport interface DirectRequestPaymentMerchantAccount {\n merchant_account_id: string;\n merchant: string;\n merchant_user_id: string;\n user_wallet_id?: string | null;\n billing_mandate_id?: string | null;\n display_name?: string | null;\n status?: string | null;\n billing_status?: string | null;\n billing_plan?: string | null;\n billing_currency?: string | null;\n token_symbol?: string | null;\n monthly_fee_minor?: number | null;\n settlement_fee_bps?: number | null;\n settlement_fee_min_minor?: number | null;\n included_monthly_payments?: number | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantSetupInput {\n merchant: string;\n display_name?: string;\n billing_plan?: DirectRequestPaymentBillingPlan | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n allowed_currencies?: Record<string, string> | Array<DirectRequestPaymentCurrency | string>;\n webhook_callback_url?: string;\n billing_mandate_cap_minor?: number;\n max_amount_minor?: number;\n // Hosted Checkout return-URL origin allowlist (open-redirect defense). Each\n // entry is an absolute origin such as \"https://shop.example.com\". The origin\n // of webhook_callback_url is auto-allowed in addition to these.\n checkout_allowed_origins?: string[];\n}\n\nexport interface HostedCheckoutSessionCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n success_url: string;\n cancel_url: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface HostedCheckoutSessionCreateResult {\n checkout_url: string;\n session_id: string;\n challenge_hash: string;\n status?: string;\n expires_at?: string | null;\n}\n\nexport interface HostedCheckoutSession {\n session_id: string;\n merchant: string;\n currency: string;\n token_symbol: string;\n amount_minor: number;\n status: string;\n challenge_hash: string;\n requirement_id?: string | null;\n success_url: string;\n cancel_url: string;\n expires_at?: string | null;\n authenticated_at?: string | null;\n paid_at?: string | null;\n cancelled_at?: string | null;\n created_at?: string | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantBillingMandateInput {\n currency?: DirectRequestPaymentCurrency | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantResponse {\n merchant_account: DirectRequestPaymentMerchantAccount;\n challenge_secret?: string | null;\n challenge_secret_created?: boolean;\n created?: boolean | null;\n listing_id?: string | null;\n mandate?: Record<string, unknown> | null;\n next_steps?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscriptionInput {\n callback_url: string;\n description?: string;\n event_types?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscription {\n webhook_subscription_id?: string;\n subscription_id?: string;\n id?: string;\n callback_url?: string;\n signing_secret?: string;\n status?: string;\n event_types?: string[];\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupInput extends DirectRequestPaymentMerchantSetupInput {\n create_webhook_subscription?: boolean;\n prepare_billing_mandate?: boolean;\n webhook_event_types?: string[];\n webhook_description?: string;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupResult {\n merchant: DirectRequestPaymentMerchantResponse;\n billing_mandate?: DirectRequestPaymentMerchantResponse | null;\n webhook_subscription?: DirectRequestPaymentWebhookSubscription | null;\n env: Record<string, string>;\n}\n\nexport interface SiglumeEnvelopeMeta {\n request_id?: string | null;\n trace_id?: string | null;\n [key: string]: unknown;\n}\n\nexport interface WebhookSignatureVerification {\n timestamp: number;\n signature: string;\n}\n\nexport interface DirectRequestPaymentWebhookEvent {\n id: string;\n type: \"direct_payment.confirmed\" | string;\n api_version: string;\n occurred_at: string;\n data: {\n mode?: string;\n merchant?: string;\n direct_payment_requirement_id?: string;\n requirement_id?: string;\n challenge_hash?: string;\n amount_minor?: number;\n currency?: string;\n token_symbol?: string;\n status?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport class SiglumeDirectRequestPaymentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeDirectRequestPaymentError\";\n }\n}\n\nexport class SiglumeApiError extends SiglumeDirectRequestPaymentError {\n readonly status: number;\n readonly code: string;\n readonly data: unknown;\n\n constructor(message: string, options: { status: number; code?: string; data?: unknown }) {\n super(message);\n this.name = \"SiglumeApiError\";\n this.status = options.status;\n this.code = options.code ?? \"SIGLUME_API_ERROR\";\n this.data = options.data;\n }\n}\n\nexport class SiglumeWebhookSignatureError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookSignatureError\";\n }\n}\n\nexport class SiglumeWebhookPayloadError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookPayloadError\";\n }\n}\n\nexport class DirectRequestPaymentClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A buyer Siglume bearer token is required for Direct Request Payment API calls. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.4.0\";\n this.fetch_impl = fetchImpl;\n }\n\n async createPaymentRequirement(input: DirectPaymentRequirementCreateInput): Promise<DirectPaymentRequirement> {\n const payload: Record<string, unknown> = {\n mode: DIRECT_REQUEST_PAYMENT_MODE,\n merchant: normalizeMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n challenge: requireNonEmpty(input.challenge, \"challenge\"),\n };\n if (input.token_symbol !== undefined) {\n payload.token_symbol = normalizeToken(input.token_symbol);\n }\n if (input.allowance_amount_minor !== undefined) {\n payload.allowance_amount_minor = positiveInteger(input.allowance_amount_minor, \"allowance_amount_minor\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectPaymentRequirement>(\"POST\", \"/sdrp/direct-payments/requirements\", payload);\n }\n\n async getPaymentRequirement(requirement_id: string): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"GET\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}`,\n );\n }\n\n async verifyPaymentRequirement(\n requirement_id: string,\n input: DirectPaymentVerifyInput,\n ): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"POST\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}/verify`,\n input,\n );\n }\n\n async executePreparedTransaction(\n payload: Web3PreparedTransactionExecutePayload,\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.request<Web3PreparedTransactionExecuteResult>(\n \"POST\",\n \"/market/web3/transactions/execute-prepared\",\n payload,\n );\n }\n\n async executePaymentTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildPaymentExecutionPayload(requirement, options));\n }\n\n async executeAllowanceTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildAllowanceExecutionPayload(requirement, options));\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class DirectRequestPaymentMerchantClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_MERCHANT_AUTH_TOKEN\") ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A merchant Siglume bearer token is required for Direct Request Payment merchant setup. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.4.0\";\n this.fetch_impl = fetchImpl;\n }\n\n async setupMerchant(input: DirectRequestPaymentMerchantSetupInput): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n billing_plan: normalizeBillingPlan(input.billing_plan ?? \"launch\"),\n billing_currency: normalizeCurrency(input.billing_currency ?? \"JPY\"),\n };\n if (input.display_name !== undefined) {\n payload.display_name = requireNonEmpty(input.display_name, \"display_name\");\n }\n if (input.allowed_currencies !== undefined) {\n payload.allowed_currencies = normalizeAllowedCurrencies(input.allowed_currencies);\n }\n if (input.webhook_callback_url !== undefined) {\n payload.webhook_callback_url = requireNonEmpty(input.webhook_callback_url, \"webhook_callback_url\");\n }\n if (input.billing_mandate_cap_minor !== undefined) {\n payload.billing_mandate_cap_minor = positiveInteger(input.billing_mandate_cap_minor, \"billing_mandate_cap_minor\");\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n if (input.checkout_allowed_origins !== undefined) {\n payload.checkout_allowed_origins = normalizeOriginList(input.checkout_allowed_origins);\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\"POST\", \"/sdrp/direct-payments/merchants\", payload);\n }\n\n /**\n * Create a Hosted Checkout session (Stripe-Checkout-equivalent for human web\n * shoppers). Siglume authors the challenge server-side, persists a single-use\n * expiring session, and returns a `checkout_url`. Redirect the shopper there;\n * they log into Siglume, approve, and pay from their own wallet, then return\n * to your `success_url`. Fulfill on the `direct_payment.confirmed` webhook\n * (the source of truth), exactly as with the agent flow.\n *\n * `success_url`/`cancel_url` must be on an origin you registered via\n * `checkout_allowed_origins` (or your `webhook_callback_url` origin).\n */\n async createCheckoutSession(input: HostedCheckoutSessionCreateInput): Promise<HostedCheckoutSessionCreateResult> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n nonce: requireNonEmpty(input.nonce, \"nonce\"),\n success_url: requireNonEmpty(input.success_url, \"success_url\"),\n cancel_url: requireNonEmpty(input.cancel_url, \"cancel_url\"),\n };\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<HostedCheckoutSessionCreateResult>(\n \"POST\",\n \"/sdrp/direct-payments/checkout-sessions\",\n payload,\n );\n }\n\n /** Read a Hosted Checkout session's status (open / authenticated / paid / expired / cancelled / failed). */\n async getCheckoutSession(session_id: string): Promise<HostedCheckoutSession> {\n return this.request<HostedCheckoutSession>(\n \"GET\",\n `/sdrp/direct-payments/checkout-sessions/${encodeURIComponent(requireNonEmpty(session_id, \"session_id\"))}`,\n );\n }\n\n async getMerchant(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"GET\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}`,\n );\n }\n\n async rotateChallengeSecret(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/challenge-secret/rotate`,\n );\n }\n\n async prepareBillingMandate(\n merchant: string,\n input: DirectRequestPaymentMerchantBillingMandateInput = {},\n ): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {};\n if (input.currency !== undefined) {\n payload.currency = normalizeCurrency(input.currency);\n }\n if (input.billing_currency !== undefined) {\n payload.billing_currency = normalizeCurrency(input.billing_currency);\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/billing-mandate`,\n payload,\n );\n }\n\n async createWebhookSubscription(\n input: DirectRequestPaymentWebhookSubscriptionInput,\n ): Promise<DirectRequestPaymentWebhookSubscription> {\n const payload: Record<string, unknown> = {\n callback_url: requireNonEmpty(input.callback_url, \"callback_url\"),\n event_types: input.event_types?.length\n ? input.event_types.map((eventType) => requireNonEmpty(eventType, \"event_type\"))\n : [\"direct_payment.confirmed\", \"direct_payment.spent\"],\n };\n if (input.description !== undefined) {\n payload.description = requireNonEmpty(input.description, \"description\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectRequestPaymentWebhookSubscription>(\"POST\", \"/market/webhooks/subscriptions\", payload);\n }\n\n async setupCheckout(input: DirectRequestPaymentCheckoutSetupInput): Promise<DirectRequestPaymentCheckoutSetupResult> {\n const merchant = await this.setupMerchant(input);\n const merchantKey = merchant.merchant_account.merchant;\n const billing_mandate = input.prepare_billing_mandate === false\n ? null\n : await this.prepareBillingMandate(merchantKey, {\n billing_currency: merchant.merchant_account.billing_currency ?? input.billing_currency ?? \"JPY\",\n max_amount_minor: input.max_amount_minor ?? input.billing_mandate_cap_minor,\n });\n const shouldCreateWebhook = input.create_webhook_subscription ?? Boolean(input.webhook_callback_url);\n const webhook_subscription = shouldCreateWebhook && input.webhook_callback_url\n ? await this.createWebhookSubscription({\n callback_url: input.webhook_callback_url,\n description: input.webhook_description ?? `${merchantKey} Direct Request Payment`,\n event_types: input.webhook_event_types,\n metadata: { merchant: merchantKey, sdk: \"@siglume/direct-request-payment\" },\n })\n : null;\n const env: Record<string, string> = {\n SIGLUME_DIRECT_PAYMENT_MERCHANT: merchantKey,\n };\n if (merchant.challenge_secret) {\n env.SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET = merchant.challenge_secret;\n }\n const webhookSecret = stringOrNull(webhook_subscription?.signing_secret);\n if (webhookSecret) {\n env.SIGLUME_WEBHOOK_SECRET = webhookSecret;\n }\n return { merchant, billing_mandate, webhook_subscription, env };\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport async function createDirectRequestPaymentChallenge(\n input: DirectRequestPaymentChallengeInput,\n): Promise<DirectRequestPaymentChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = normalizeChallengeNonce(input.nonce);\n const material = `${merchant}:${amount}:${currency}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport function parseDirectRequestPaymentChallenge(challenge: string): ParsedDirectRequestPaymentChallenge {\n const parts = requireNonEmpty(challenge, \"challenge\").split(\":\");\n if (parts.length !== 3) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge must be scheme:nonce:signature.\");\n }\n const [scheme, nonce, signature] = parts;\n if (!scheme || !nonce || !signature) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge is incomplete.\");\n }\n return { scheme, nonce, signature };\n}\n\n/** Merchant-side, ONE-TIME approval of a recurring authorization: amount +\n * currency + cadence are bound into the HMAC. Recurring charges afterwards\n * are deliberately challenge-free; the recurring authorization and the\n * buyer's mandate/budget caps are the per-charge integrity checks. Cadence\n * \"monthly\" = subscription, \"daily\" = scheduled autopay approval tag. */\nexport async function createDirectRequestPaymentRecurringChallenge(\n input: DirectRequestPaymentRecurringChallengeInput,\n): Promise<DirectRequestPaymentRecurringChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentRecurringChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentRecurringChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = normalizeChallengeNonce(input.nonce);\n // MUST stay byte-identical to the server's\n // _external_402_recurring_challenge_signature — both sides change together.\n const material = `${merchant}:${amount}:${currency}:${cadence}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport async function verifyDirectRequestPaymentRecurringChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentRecurringChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n cadence: input.cadence,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function verifyDirectRequestPaymentChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function directRequestPaymentChallengeHash(challenge: string): Promise<string> {\n return sha256Prefixed(requireNonEmpty(challenge, \"challenge\"));\n}\n\nexport async function directRequestPaymentRequestHash(input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n}): Promise<string> {\n const material = `${normalizeMerchant(input.merchant)}${positiveInteger(input.amount_minor, \"amount_minor\")}${normalizeCurrency(input.currency)}${requireNonEmpty(input.challenge, \"challenge\")}`;\n return sha256Prefixed(material);\n}\n\nexport function buildPaymentExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n return buildPreparedTransactionExecutionPayload(requirement, requirement.transaction_request, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildAllowanceExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n const approveRequest = requirement.approve_transaction_request;\n if (!approveRequest || Object.keys(approveRequest).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"This payment requirement does not include an allowance approval transaction.\");\n }\n return buildPreparedTransactionExecutionPayload(requirement, approveRequest, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildPreparedTransactionExecutionPayload(\n requirement: DirectPaymentRequirement,\n transaction_request: Web3TransactionRequest,\n options: {\n receipt_kind: string;\n await_finality?: boolean;\n metadata?: Record<string, unknown>;\n },\n): Web3PreparedTransactionExecutePayload {\n const metadata = {\n ...(isRecord(transaction_request.metadata_jsonb) ? transaction_request.metadata_jsonb : {}),\n ...(options.metadata ?? {}),\n };\n return {\n transaction_request,\n receipt_kind: requireNonEmpty(options.receipt_kind, \"receipt_kind\"),\n reference_type: DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE,\n reference_id: requirement.requirement_id,\n metadata,\n await_finality: Boolean(options.await_finality),\n };\n}\n\nexport async function computeWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp: number },\n): Promise<string> {\n if (!signing_secret) {\n throw new SiglumeWebhookSignatureError(\"SIGLUME webhook signing secret is required.\");\n }\n const timestamp = Math.trunc(options.timestamp);\n const bytes = bodyBytes(body);\n const prefix = new TextEncoder().encode(`${timestamp}.`);\n const payload = new Uint8Array(prefix.length + bytes.length);\n payload.set(prefix, 0);\n payload.set(bytes, prefix.length);\n return hmacSha256Hex(signing_secret, payload);\n}\n\nexport async function buildWebhookSignatureHeader(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = Math.trunc(options.timestamp ?? Date.now() / 1000);\n const signature = await computeWebhookSignature(signing_secret, body, { timestamp });\n return `t=${timestamp},v1=${signature}`;\n}\n\nexport async function verifyWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<WebhookSignatureVerification> {\n const { timestamp, signature } = parseSignatureHeader(signature_header);\n const toleranceSeconds = Math.max(1, Math.trunc(options.tolerance_seconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS));\n const nowSeconds = Math.trunc(options.now ?? Date.now() / 1000);\n if (Math.abs(nowSeconds - timestamp) > toleranceSeconds) {\n throw new SiglumeWebhookSignatureError(\"Webhook timestamp is outside the allowed tolerance window.\");\n }\n const expected = await computeWebhookSignature(signing_secret, body, { timestamp });\n if (!(await timingSafeEqualHex(expected, signature))) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature did not match.\");\n }\n return { timestamp, signature };\n}\n\nexport function parseDirectRequestPaymentWebhookEvent(payload: unknown): DirectRequestPaymentWebhookEvent {\n const event = requireRecord(payload, \"webhook event\");\n const data = requireRecord(event.data, \"webhook event data\");\n const parsed = {\n ...event,\n id: requireNonEmpty(stringOrNull(event.id) ?? \"\", \"webhook event id\"),\n type: requireNonEmpty(stringOrNull(event.type) ?? \"\", \"webhook event type\"),\n api_version: requireNonEmpty(stringOrNull(event.api_version) ?? \"\", \"webhook api_version\"),\n occurred_at: requireNonEmpty(stringOrNull(event.occurred_at) ?? \"\", \"webhook occurred_at\"),\n data: { ...data },\n } as DirectRequestPaymentWebhookEvent;\n if (parsed.type === \"direct_payment.confirmed\" && parsed.data.mode !== DIRECT_REQUEST_PAYMENT_MODE) {\n throw new SiglumeWebhookPayloadError(\"direct_payment.confirmed webhook must carry data.mode='external_402'.\");\n }\n return parsed;\n}\n\nexport async function verifyDirectRequestPaymentWebhook(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<{ event: DirectRequestPaymentWebhookEvent; verification: WebhookSignatureVerification }> {\n const verification = await verifyWebhookSignature(signing_secret, body, signature_header, options);\n const text = new TextDecoder().decode(bodyBytes(body));\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new SiglumeWebhookPayloadError(\"Webhook body must contain valid JSON.\");\n }\n return { event: parseDirectRequestPaymentWebhookEvent(parsed), verification };\n}\n\nexport const createExternal402Challenge = createDirectRequestPaymentChallenge;\nexport const verifyExternal402Challenge = verifyDirectRequestPaymentChallenge;\nexport const createExternal402RecurringChallenge = createDirectRequestPaymentRecurringChallenge;\nexport const verifyExternal402RecurringChallenge = verifyDirectRequestPaymentRecurringChallenge;\n\nfunction normalizeMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be a lowercase key using letters, numbers, dot, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeSelfServiceMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9_-]{2,63}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be 3-64 chars using lowercase letters, numbers, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeBillingPlan(value: string): DirectRequestPaymentBillingPlan {\n const plan = requireNonEmpty(value, \"billing_plan\").toLowerCase();\n if (plan === \"launch\" || plan === \"free\" || plan === \"starter\" || plan === \"growth\" || plan === \"pro\") {\n return plan;\n }\n throw new SiglumeDirectRequestPaymentError(\"billing_plan must be launch, starter, growth, or pro.\");\n}\n\nfunction normalizeCurrency(value: string): DirectRequestPaymentCurrency {\n const currency = requireNonEmpty(value, \"currency\").toUpperCase();\n if (currency !== \"JPY\" && currency !== \"USD\") {\n throw new SiglumeDirectRequestPaymentError(\"currency must be JPY or USD.\");\n }\n return currency;\n}\n\nfunction normalizeToken(value: string): DirectRequestPaymentToken {\n const token = requireNonEmpty(value, \"token_symbol\").toUpperCase();\n if (token !== \"JPYC\" && token !== \"USDC\") {\n throw new SiglumeDirectRequestPaymentError(\"token_symbol must be JPYC or USDC.\");\n }\n return token;\n}\n\nfunction normalizeAllowedCurrencies(value: Record<string, string> | Array<DirectRequestPaymentCurrency | string>): Record<string, string> {\n const normalized: Record<string, string> = {};\n if (Array.isArray(value)) {\n for (const item of value) {\n const currency = normalizeCurrency(item);\n normalized[currency] = defaultTokenForCurrency(currency);\n }\n } else if (isRecord(value)) {\n for (const [rawCurrency, rawToken] of Object.entries(value)) {\n normalized[normalizeCurrency(rawCurrency)] = normalizeToken(String(rawToken));\n }\n } else {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must be an array or a currency-to-token object.\");\n }\n if (Object.keys(normalized).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must include at least one currency.\");\n }\n return normalized;\n}\n\nfunction defaultTokenForCurrency(currency: DirectRequestPaymentCurrency): DirectRequestPaymentToken {\n return currency === \"JPY\" ? \"JPYC\" : \"USDC\";\n}\n\nfunction normalizeOriginList(value: string[]): string[] {\n if (!Array.isArray(value)) {\n throw new SiglumeDirectRequestPaymentError(\"checkout_allowed_origins must be an array of origin URLs.\");\n }\n const seen = new Set<string>();\n const origins: string[] = [];\n for (const item of value) {\n let url: URL;\n try {\n url = new URL(requireNonEmpty(String(item), \"checkout_allowed_origins entry\"));\n } catch {\n throw new SiglumeDirectRequestPaymentError(\n \"each checkout_allowed_origins entry must be an absolute origin such as https://shop.example.com.\",\n );\n }\n const origin = `${url.protocol.toLowerCase()}//${url.host.toLowerCase()}`;\n if (!seen.has(origin)) {\n seen.add(origin);\n origins.push(origin);\n }\n }\n return origins;\n}\n\nfunction positiveInteger(value: number, name: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a positive safe integer.`);\n }\n return parsed;\n}\n\nfunction requireNonEmpty(value: string, name: string): string {\n const text = String(value ?? \"\").trim();\n if (!text) {\n throw new SiglumeDirectRequestPaymentError(`${name} is required.`);\n }\n return text;\n}\n\nfunction normalizeChallengeNonce(value: string): string {\n const nonce = requireNonEmpty(value, \"nonce\");\n if (nonce.includes(\":\")) {\n throw new SiglumeDirectRequestPaymentError(\"nonce must not contain ':'.\");\n }\n return nonce;\n}\n\nfunction normalizeRecurringCadence(value: string): DirectRequestPaymentRecurringCadence {\n const cadence = requireNonEmpty(value, \"cadence\").toLowerCase();\n if (cadence !== \"monthly\" && cadence !== \"daily\") {\n throw new SiglumeDirectRequestPaymentError(\n 'cadence must be \"monthly\" (subscription) or \"daily\" (scheduled autopay).',\n );\n }\n return cadence;\n}\n\nfunction cloneJsonObject(value: Record<string, unknown>, name: string): Record<string, unknown> {\n try {\n const cloned = JSON.parse(JSON.stringify(value)) as unknown;\n if (!isRecord(cloned)) {\n throw new Error(\"not an object\");\n }\n return cloned;\n } catch (error) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a JSON-serializable object.`);\n }\n}\n\nfunction parseJson(rawText: string): unknown {\n try {\n return JSON.parse(rawText);\n } catch (error) {\n throw new SiglumeApiError(\"Siglume API returned invalid JSON.\", {\n status: 502,\n code: \"INVALID_JSON_RESPONSE\",\n data: rawText,\n });\n }\n}\n\nfunction stringOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const text = value.trim();\n return text ? text : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requireRecord(value: unknown, name: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new SiglumeWebhookPayloadError(`${name} must be an object.`);\n }\n return value;\n}\n\nfunction envValue(name: string): string | undefined {\n if (typeof process === \"undefined\") {\n return undefined;\n }\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nfunction bodyBytes(body: Uint8Array | ArrayBuffer | string | Record<string, unknown>): Uint8Array {\n if (body instanceof Uint8Array) {\n return body;\n }\n if (body instanceof ArrayBuffer) {\n return new Uint8Array(body);\n }\n if (typeof body === \"string\") {\n return new TextEncoder().encode(body);\n }\n if (isRecord(body)) {\n return new TextEncoder().encode(JSON.stringify(body));\n }\n throw new SiglumeWebhookPayloadError(\"Webhook body must be raw bytes, a string, or a JSON object.\");\n}\n\nfunction parseSignatureHeader(signatureHeader: string): { timestamp: number; signature: string } {\n let timestamp: number | null = null;\n let signature: string | null = null;\n for (const item of String(signatureHeader ?? \"\").split(\",\")) {\n const [key, value] = item.trim().split(\"=\", 2);\n if (key === \"t\") {\n const parsed = Number.parseInt(value ?? \"\", 10);\n if (!Number.isFinite(parsed)) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature timestamp is invalid.\");\n }\n timestamp = parsed;\n }\n if (key === \"v1\") {\n signature = String(value ?? \"\").trim();\n }\n }\n if (timestamp === null || !signature) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature header is incomplete.\");\n }\n return { timestamp, signature };\n}\n\nasync function randomNonce(): Promise<string> {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(bytes);\n } else if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n bytes.set(crypto.randomBytes(16));\n } else {\n throw new SiglumeDirectRequestPaymentError(\"Crypto random number generation is unavailable in this runtime.\");\n }\n return bytesToHex(bytes);\n}\n\nasync function hmacSha256Hex(secret: string, payload: Uint8Array): Promise<string> {\n if (globalThis.crypto?.subtle) {\n const stablePayload = new Uint8Array(payload.byteLength);\n stablePayload.set(payload);\n const key = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const digest = await globalThis.crypto.subtle.sign(\"HMAC\", key, stablePayload);\n return bytesToHex(new Uint8Array(digest));\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return crypto.createHmac(\"sha256\", secret).update(Buffer.from(payload)).digest(\"hex\");\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for HMAC-SHA256 in this runtime.\");\n}\n\nasync function sha256Prefixed(material: string): Promise<string> {\n const bytes = new TextEncoder().encode(material);\n if (globalThis.crypto?.subtle) {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return `sha256:${bytesToHex(new Uint8Array(digest))}`;\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return `sha256:${crypto.createHash(\"sha256\").update(Buffer.from(bytes)).digest(\"hex\")}`;\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for SHA-256 in this runtime.\");\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return [...bytes].map((item) => item.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const normalized = String(hex ?? \"\").trim().toLowerCase();\n if (normalized.length % 2 !== 0 || !/^[0-9a-f]*$/.test(normalized)) {\n throw new SiglumeWebhookSignatureError(\"Hex digest is invalid.\");\n }\n const bytes = new Uint8Array(normalized.length / 2);\n for (let index = 0; index < normalized.length; index += 2) {\n bytes[index / 2] = Number.parseInt(normalized.slice(index, index + 2), 16);\n }\n return bytes;\n}\n\nasync function timingSafeEqualHex(left: string, right: string): Promise<boolean> {\n const leftBytes = hexToBytes(left);\n const rightBytes = hexToBytes(right);\n if (leftBytes.length !== rightBytes.length) {\n return false;\n }\n let diff = 0;\n for (let index = 0; index < leftBytes.length; index += 1) {\n diff |= leftBytes[index]! ^ rightBytes[index]!;\n }\n return diff === 0;\n}\n"],"mappings":";AAAO,IAAM,2BAA2B;AACjC,IAAM,0CAA0C;AAIhD,IAAM,oDAAoD;AAC1D,IAAM,8BAA8B;AACpC,IAAM,sCAAsC;AAC5C,IAAM,gDAAgD;AACtD,IAAM,wCAAwC;AAC9C,IAAM,oCAAoC;AAyS1C,IAAM,mCAAN,cAA+C,MAAM;AAAA,EAC1D,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAAN,cAA8B,iCAAiC;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,SAA4D;AACvF,UAAM,OAAO;AACb,SAAK,OAAO;A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SAAO,SAAS;AAClB;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export const DEFAULT_SIGLUME_API_BASE = \"https://siglume.com/v1\";\nexport const DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME = \"siglume-external-402-v1\";\n// Recurring (subscription / scheduled autopay) approval uses a DISTINCT scheme\n// with cadence bound into the HMAC, so a one-time checkout challenge can never\n// be replayed as a recurring authorization and vice versa.\nexport const DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME = \"siglume-external-402-recurring-v1\";\nexport const DIRECT_REQUEST_PAYMENT_MODE = \"external_402\";\nexport const DIRECT_REQUEST_PAYMENT_RECEIPT_KIND = \"sdrp_direct_payment\";\nexport const DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND = \"sdrp_direct_payment_allowance\";\nexport const DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE = \"sdrp_direct_payment_requirement\";\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n\nexport type DirectRequestPaymentCurrency = \"JPY\" | \"USD\";\nexport type DirectRequestPaymentToken = \"JPYC\" | \"USDC\";\n\nexport interface DirectRequestPaymentChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface ParsedDirectRequestPaymentChallenge {\n scheme: string;\n nonce: string;\n signature: string;\n}\n\n/** \"monthly\" authorizes a Siglume-swept subscription; \"daily\" authorizes\n * merchant-triggered scheduled autopay. It is an approval tag, not a\n * run-count limiter. */\nexport type DirectRequestPaymentRecurringCadence = \"monthly\" | \"daily\";\n\nexport interface DirectRequestPaymentRecurringChallengeInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n secret: string;\n nonce?: string;\n}\n\nexport interface DirectRequestPaymentRecurringChallenge {\n scheme: typeof DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME;\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency;\n cadence: DirectRequestPaymentRecurringCadence;\n nonce: string;\n signature: string;\n challenge: string;\n challenge_hash: string;\n}\n\nexport interface Web3TransactionRequest {\n network?: string;\n chain_id?: number;\n from?: string;\n to?: string;\n data?: string;\n value?: string | number;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectPaymentRequirement {\n direct_payment_requirement_id: string;\n requirement_id: string;\n id: string;\n mode: string;\n merchant?: string | null;\n challenge_hash?: string | null;\n buyer_user_id: string;\n agent_id?: string | null;\n product_listing_id: string;\n listing_id: string;\n access_grant_id?: string | null;\n capability_key: string;\n requirement_hash: string;\n request_hash: string;\n siglume_signature: string;\n token_symbol: string;\n currency: string;\n amount_minor: number;\n fee_bps: number;\n status: string;\n expires_at?: string | null;\n confirmed_at?: string | null;\n spent_at?: string | null;\n chain_receipt_id?: string | null;\n transaction_request: Web3TransactionRequest;\n approve_transaction_request?: Web3TransactionRequest | null;\n buyer_confirmation?: string | null;\n non_custodial: boolean;\n metadata_jsonb?: Record<string, unknown>;\n created_at?: string | null;\n updated_at?: string | null;\n}\n\nexport interface DirectPaymentRequirementCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n token_symbol?: DirectRequestPaymentToken | string;\n allowance_amount_minor?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectPaymentVerifyInput {\n receipt_id?: string | null;\n chain_receipt_id?: string | null;\n await_finality?: boolean;\n await_required_status?: string | null;\n await_timeout_seconds?: number;\n await_poll_seconds?: number;\n}\n\nexport interface Web3PreparedTransactionExecutePayload {\n transaction_request: Web3TransactionRequest;\n receipt_kind: string;\n reference_type: typeof DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE;\n reference_id: string;\n metadata?: Record<string, unknown>;\n await_finality?: boolean;\n}\n\nexport interface Web3PreparedTransactionExecuteResult {\n receipt?: Record<string, unknown>;\n finalization?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentClientOptions {\n auth_token?: string;\n base_url?: string;\n fetch?: typeof fetch;\n timeout_ms?: number;\n user_agent?: string;\n}\n\nexport type DirectRequestPaymentBillingPlan = \"launch\" | \"free\" | \"starter\" | \"growth\" | \"pro\";\n\nexport interface DirectRequestPaymentMerchantAccount {\n merchant_account_id: string;\n merchant: string;\n merchant_user_id: string;\n user_wallet_id?: string | null;\n billing_mandate_id?: string | null;\n display_name?: string | null;\n status?: string | null;\n billing_status?: string | null;\n billing_plan?: string | null;\n billing_currency?: string | null;\n token_symbol?: string | null;\n monthly_fee_minor?: number | null;\n settlement_fee_bps?: number | null;\n settlement_fee_min_minor?: number | null;\n included_monthly_payments?: number | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantSetupInput {\n merchant: string;\n display_name?: string;\n billing_plan?: DirectRequestPaymentBillingPlan | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n allowed_currencies?: Record<string, string> | Array<DirectRequestPaymentCurrency | string>;\n webhook_callback_url?: string;\n billing_mandate_cap_minor?: number;\n max_amount_minor?: number;\n // Hosted Checkout return-URL origin allowlist (open-redirect defense). Each\n // entry is an absolute origin such as \"https://shop.example.com\". The origin\n // of webhook_callback_url is auto-allowed in addition to these.\n checkout_allowed_origins?: string[];\n}\n\nexport interface HostedCheckoutSessionCreateInput {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n success_url: string;\n cancel_url: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface HostedCheckoutSessionCreateResult {\n checkout_url: string;\n session_id: string;\n challenge_hash: string;\n status?: string;\n expires_at?: string | null;\n}\n\nexport interface HostedCheckoutSession {\n session_id: string;\n merchant: string;\n currency: string;\n token_symbol: string;\n amount_minor: number;\n status: string;\n challenge_hash: string;\n requirement_id?: string | null;\n success_url: string;\n cancel_url: string;\n expires_at?: string | null;\n authenticated_at?: string | null;\n paid_at?: string | null;\n cancelled_at?: string | null;\n created_at?: string | null;\n metadata_jsonb?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentMerchantBillingMandateInput {\n currency?: DirectRequestPaymentCurrency | string;\n billing_currency?: DirectRequestPaymentCurrency | string;\n max_amount_minor?: number;\n}\n\nexport interface DirectRequestPaymentMerchantResponse {\n merchant_account: DirectRequestPaymentMerchantAccount;\n challenge_secret?: string | null;\n challenge_secret_created?: boolean;\n created?: boolean | null;\n listing_id?: string | null;\n mandate?: Record<string, unknown> | null;\n next_steps?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscriptionInput {\n callback_url: string;\n description?: string;\n event_types?: string[];\n metadata?: Record<string, unknown>;\n}\n\nexport interface DirectRequestPaymentWebhookSubscription {\n webhook_subscription_id?: string;\n subscription_id?: string;\n id?: string;\n callback_url?: string;\n signing_secret?: string;\n status?: string;\n event_types?: string[];\n [key: string]: unknown;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupInput extends DirectRequestPaymentMerchantSetupInput {\n create_webhook_subscription?: boolean;\n prepare_billing_mandate?: boolean;\n webhook_event_types?: string[];\n webhook_description?: string;\n}\n\nexport interface DirectRequestPaymentCheckoutSetupResult {\n merchant: DirectRequestPaymentMerchantResponse;\n billing_mandate?: DirectRequestPaymentMerchantResponse | null;\n webhook_subscription?: DirectRequestPaymentWebhookSubscription | null;\n env: Record<string, string>;\n}\n\nexport interface SiglumeEnvelopeMeta {\n request_id?: string | null;\n trace_id?: string | null;\n [key: string]: unknown;\n}\n\nexport interface WebhookSignatureVerification {\n timestamp: number;\n signature: string;\n}\n\nexport interface DirectRequestPaymentWebhookEvent {\n id: string;\n type: \"direct_payment.confirmed\" | string;\n api_version: string;\n occurred_at: string;\n data: {\n mode?: string;\n merchant?: string;\n direct_payment_requirement_id?: string;\n requirement_id?: string;\n challenge_hash?: string;\n amount_minor?: number;\n currency?: string;\n token_symbol?: string;\n status?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport class SiglumeDirectRequestPaymentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeDirectRequestPaymentError\";\n }\n}\n\nexport class SiglumeApiError extends SiglumeDirectRequestPaymentError {\n readonly status: number;\n readonly code: string;\n readonly data: unknown;\n\n constructor(message: string, options: { status: number; code?: string; data?: unknown }) {\n super(message);\n this.name = \"SiglumeApiError\";\n this.status = options.status;\n this.code = options.code ?? \"SIGLUME_API_ERROR\";\n this.data = options.data;\n }\n}\n\nexport class HostedCheckoutNotAvailableError extends SiglumeApiError {\n constructor(message = \"Hosted Checkout is not enabled for this account yet (server rollout in progress).\") {\n super(message, { status: 409, code: \"HOSTED_CHECKOUT_NOT_ENABLED\" });\n this.name = \"HostedCheckoutNotAvailableError\";\n }\n}\n\nexport class SiglumeWebhookSignatureError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookSignatureError\";\n }\n}\n\nexport class SiglumeWebhookPayloadError extends SiglumeDirectRequestPaymentError {\n constructor(message: string) {\n super(message);\n this.name = \"SiglumeWebhookPayloadError\";\n }\n}\n\nexport class DirectRequestPaymentClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A buyer Siglume bearer token is required for Direct Request Payment API calls. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.4.1\";\n this.fetch_impl = fetchImpl;\n }\n\n async createPaymentRequirement(input: DirectPaymentRequirementCreateInput): Promise<DirectPaymentRequirement> {\n const payload: Record<string, unknown> = {\n mode: DIRECT_REQUEST_PAYMENT_MODE,\n merchant: normalizeMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n challenge: requireNonEmpty(input.challenge, \"challenge\"),\n };\n if (input.token_symbol !== undefined) {\n payload.token_symbol = normalizeToken(input.token_symbol);\n }\n if (input.allowance_amount_minor !== undefined) {\n payload.allowance_amount_minor = positiveInteger(input.allowance_amount_minor, \"allowance_amount_minor\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectPaymentRequirement>(\"POST\", \"/sdrp/direct-payments/requirements\", payload);\n }\n\n async getPaymentRequirement(requirement_id: string): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"GET\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}`,\n );\n }\n\n async verifyPaymentRequirement(\n requirement_id: string,\n input: DirectPaymentVerifyInput,\n ): Promise<DirectPaymentRequirement> {\n return this.request<DirectPaymentRequirement>(\n \"POST\",\n `/sdrp/direct-payments/requirements/${encodeURIComponent(requireNonEmpty(requirement_id, \"requirement_id\"))}/verify`,\n input,\n );\n }\n\n async executePreparedTransaction(\n payload: Web3PreparedTransactionExecutePayload,\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.request<Web3PreparedTransactionExecuteResult>(\n \"POST\",\n \"/market/web3/transactions/execute-prepared\",\n payload,\n );\n }\n\n async executePaymentTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildPaymentExecutionPayload(requirement, options));\n }\n\n async executeAllowanceTransaction(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n ): Promise<Web3PreparedTransactionExecuteResult> {\n return this.executePreparedTransaction(buildAllowanceExecutionPayload(requirement, options));\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport class DirectRequestPaymentMerchantClient {\n readonly auth_token: string;\n readonly base_url: string;\n readonly timeout_ms: number;\n readonly user_agent: string;\n private readonly fetch_impl: typeof fetch;\n\n constructor(options: DirectRequestPaymentClientOptions = {}) {\n const authToken = options.auth_token ?? envValue(\"SIGLUME_MERCHANT_AUTH_TOKEN\") ?? envValue(\"SIGLUME_AUTH_TOKEN\");\n if (!authToken) {\n throw new SiglumeDirectRequestPaymentError(\n \"A merchant Siglume bearer token is required for Direct Request Payment merchant setup. Developer Portal API keys are not accepted.\",\n );\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new SiglumeDirectRequestPaymentError(\"A fetch implementation is required in this runtime.\");\n }\n this.auth_token = authToken;\n this.base_url = (options.base_url ?? envValue(\"SIGLUME_API_BASE\") ?? DEFAULT_SIGLUME_API_BASE).replace(/\\/+$/, \"\");\n this.timeout_ms = Math.max(1, Math.trunc(options.timeout_ms ?? 15000));\n this.user_agent = options.user_agent ?? \"@siglume/direct-request-payment/0.4.1\";\n this.fetch_impl = fetchImpl;\n }\n\n async setupMerchant(input: DirectRequestPaymentMerchantSetupInput): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n billing_plan: normalizeBillingPlan(input.billing_plan ?? \"launch\"),\n billing_currency: normalizeCurrency(input.billing_currency ?? \"JPY\"),\n };\n if (input.display_name !== undefined) {\n payload.display_name = requireNonEmpty(input.display_name, \"display_name\");\n }\n if (input.allowed_currencies !== undefined) {\n payload.allowed_currencies = normalizeAllowedCurrencies(input.allowed_currencies);\n }\n if (input.webhook_callback_url !== undefined) {\n payload.webhook_callback_url = requireNonEmpty(input.webhook_callback_url, \"webhook_callback_url\");\n }\n if (input.billing_mandate_cap_minor !== undefined) {\n payload.billing_mandate_cap_minor = positiveInteger(input.billing_mandate_cap_minor, \"billing_mandate_cap_minor\");\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n if (input.checkout_allowed_origins !== undefined) {\n payload.checkout_allowed_origins = normalizeOriginList(input.checkout_allowed_origins);\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\"POST\", \"/sdrp/direct-payments/merchants\", payload);\n }\n\n /**\n * Create a Hosted Checkout session (Stripe-Checkout-equivalent for human web\n * shoppers). Siglume authors the challenge server-side, persists a single-use\n * expiring session, and returns a `checkout_url`. Redirect the shopper there;\n * they log into Siglume, approve, and pay from their own wallet, then return\n * to your `success_url`. Fulfill on the `direct_payment.confirmed` webhook\n * (the source of truth), exactly as with the agent flow.\n *\n * `success_url`/`cancel_url` must be on an origin you registered via\n * `checkout_allowed_origins` (or your `webhook_callback_url` origin).\n */\n async createCheckoutSession(input: HostedCheckoutSessionCreateInput): Promise<HostedCheckoutSessionCreateResult> {\n const payload: Record<string, unknown> = {\n merchant: normalizeSelfServiceMerchant(input.merchant),\n amount_minor: positiveInteger(input.amount_minor, \"amount_minor\"),\n currency: normalizeCurrency(input.currency),\n nonce: normalizeChallengeNonce(input.nonce),\n success_url: requireNonEmpty(input.success_url, \"success_url\"),\n cancel_url: requireNonEmpty(input.cancel_url, \"cancel_url\"),\n };\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.requestHostedCheckout<HostedCheckoutSessionCreateResult>(\n \"POST\",\n \"/sdrp/direct-payments/checkout-sessions\",\n payload,\n );\n }\n\n /** Read a Hosted Checkout session's status (open / authenticated / paid / expired / cancelled / failed). */\n async getCheckoutSession(session_id: string): Promise<HostedCheckoutSession> {\n return this.requestHostedCheckout<HostedCheckoutSession>(\n \"GET\",\n `/sdrp/direct-payments/checkout-sessions/${encodeURIComponent(requireNonEmpty(session_id, \"session_id\"))}`,\n );\n }\n\n async getMerchant(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"GET\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}`,\n );\n }\n\n async rotateChallengeSecret(merchant: string): Promise<DirectRequestPaymentMerchantResponse> {\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/challenge-secret/rotate`,\n );\n }\n\n async prepareBillingMandate(\n merchant: string,\n input: DirectRequestPaymentMerchantBillingMandateInput = {},\n ): Promise<DirectRequestPaymentMerchantResponse> {\n const payload: Record<string, unknown> = {};\n if (input.currency !== undefined) {\n payload.currency = normalizeCurrency(input.currency);\n }\n if (input.billing_currency !== undefined) {\n payload.billing_currency = normalizeCurrency(input.billing_currency);\n }\n if (input.max_amount_minor !== undefined) {\n payload.max_amount_minor = positiveInteger(input.max_amount_minor, \"max_amount_minor\");\n }\n return this.request<DirectRequestPaymentMerchantResponse>(\n \"POST\",\n `/sdrp/direct-payments/merchants/${encodeURIComponent(normalizeSelfServiceMerchant(merchant))}/billing-mandate`,\n payload,\n );\n }\n\n async createWebhookSubscription(\n input: DirectRequestPaymentWebhookSubscriptionInput,\n ): Promise<DirectRequestPaymentWebhookSubscription> {\n const payload: Record<string, unknown> = {\n callback_url: requireNonEmpty(input.callback_url, \"callback_url\"),\n event_types: input.event_types?.length\n ? input.event_types.map((eventType) => requireNonEmpty(eventType, \"event_type\"))\n : [\"direct_payment.confirmed\", \"direct_payment.spent\"],\n };\n if (input.description !== undefined) {\n payload.description = requireNonEmpty(input.description, \"description\");\n }\n if (input.metadata !== undefined) {\n payload.metadata = cloneJsonObject(input.metadata, \"metadata\");\n }\n return this.request<DirectRequestPaymentWebhookSubscription>(\"POST\", \"/market/webhooks/subscriptions\", payload);\n }\n\n async setupCheckout(input: DirectRequestPaymentCheckoutSetupInput): Promise<DirectRequestPaymentCheckoutSetupResult> {\n const merchant = await this.setupMerchant(input);\n const merchantKey = merchant.merchant_account.merchant;\n const billing_mandate = input.prepare_billing_mandate === false\n ? null\n : await this.prepareBillingMandate(merchantKey, {\n billing_currency: merchant.merchant_account.billing_currency ?? input.billing_currency ?? \"JPY\",\n max_amount_minor: input.max_amount_minor ?? input.billing_mandate_cap_minor,\n });\n const shouldCreateWebhook = input.create_webhook_subscription ?? Boolean(input.webhook_callback_url);\n const webhook_subscription = shouldCreateWebhook && input.webhook_callback_url\n ? await this.createWebhookSubscription({\n callback_url: input.webhook_callback_url,\n description: input.webhook_description ?? `${merchantKey} Direct Request Payment`,\n event_types: input.webhook_event_types,\n metadata: { merchant: merchantKey, sdk: \"@siglume/direct-request-payment\" },\n })\n : null;\n const env: Record<string, string> = {\n SIGLUME_DIRECT_PAYMENT_MERCHANT: merchantKey,\n };\n if (merchant.challenge_secret) {\n env.SIGLUME_DIRECT_PAYMENT_CHALLENGE_SECRET = merchant.challenge_secret;\n }\n const webhookSecret = stringOrNull(webhook_subscription?.signing_secret);\n if (webhookSecret) {\n env.SIGLUME_WEBHOOK_SECRET = webhookSecret;\n }\n return { merchant, billing_mandate, webhook_subscription, env };\n }\n\n async request<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeout_ms);\n try {\n const headers: Record<string, string> = {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${this.auth_token}`,\n \"User-Agent\": this.user_agent,\n };\n let body: string | undefined;\n if (json_body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(json_body);\n }\n const response = await this.fetch_impl(`${this.base_url}${path}`, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n const rawText = await response.text();\n const parsed = rawText ? parseJson(rawText) : {};\n if (!response.ok) {\n const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : {};\n const code = stringOrNull(error.code) ?? stringOrNull((parsed as Record<string, unknown>).code) ?? `HTTP_${response.status}`;\n const message = stringOrNull(error.message) ?? stringOrNull((parsed as Record<string, unknown>).message) ?? response.statusText;\n throw new SiglumeApiError(message, { status: response.status, code, data: parsed });\n }\n if (isRecord(parsed) && \"data\" in parsed) {\n return parsed.data as T;\n }\n return parsed as T;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n private async requestHostedCheckout<T>(method: string, path: string, json_body?: unknown): Promise<T> {\n try {\n return await this.request<T>(method, path, json_body);\n } catch (error) {\n if (isHostedCheckoutUnavailable(error)) {\n throw new HostedCheckoutNotAvailableError();\n }\n throw error;\n }\n }\n}\n\nexport async function createDirectRequestPaymentChallenge(\n input: DirectRequestPaymentChallengeInput,\n): Promise<DirectRequestPaymentChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const nonce = normalizeChallengeNonce(input.nonce);\n const material = `${merchant}:${amount}:${currency}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport function parseDirectRequestPaymentChallenge(challenge: string): ParsedDirectRequestPaymentChallenge {\n const parts = requireNonEmpty(challenge, \"challenge\").split(\":\");\n if (parts.length !== 3) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge must be scheme:nonce:signature.\");\n }\n const [scheme, nonce, signature] = parts;\n if (!scheme || !nonce || !signature) {\n throw new SiglumeDirectRequestPaymentError(\"Direct Request Payment challenge is incomplete.\");\n }\n return { scheme, nonce, signature };\n}\n\n/** Merchant-side, ONE-TIME approval of a recurring authorization: amount +\n * currency + cadence are bound into the HMAC. Recurring charges afterwards\n * are deliberately challenge-free; the recurring authorization and the\n * buyer's mandate/budget caps are the per-charge integrity checks. Cadence\n * \"monthly\" = subscription, \"daily\" = scheduled autopay approval tag. */\nexport async function createDirectRequestPaymentRecurringChallenge(\n input: DirectRequestPaymentRecurringChallengeInput,\n): Promise<DirectRequestPaymentRecurringChallenge> {\n const merchant = normalizeMerchant(input.merchant);\n const amount_minor = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = input.nonce ? normalizeChallengeNonce(input.nonce) : await randomNonce();\n const signature = await createDirectRequestPaymentRecurringChallengeSignature(input.secret, {\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n });\n const challenge = `${DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME}:${nonce}:${signature}`;\n return {\n scheme: DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME,\n merchant,\n amount_minor,\n currency,\n cadence,\n nonce,\n signature,\n challenge,\n challenge_hash: await sha256Prefixed(challenge),\n };\n}\n\nexport async function createDirectRequestPaymentRecurringChallengeSignature(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n nonce: string;\n },\n): Promise<string> {\n const normalizedSecret = requireNonEmpty(secret, \"secret\");\n const merchant = normalizeMerchant(input.merchant);\n const amount = positiveInteger(input.amount_minor, \"amount_minor\");\n const currency = normalizeCurrency(input.currency);\n const cadence = normalizeRecurringCadence(input.cadence);\n const nonce = normalizeChallengeNonce(input.nonce);\n // MUST stay byte-identical to the server's\n // _external_402_recurring_challenge_signature — both sides change together.\n const material = `${merchant}:${amount}:${currency}:${cadence}:${nonce}`;\n return hmacSha256Hex(normalizedSecret, new TextEncoder().encode(material));\n}\n\nexport async function verifyDirectRequestPaymentRecurringChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n cadence: DirectRequestPaymentRecurringCadence | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_RECURRING_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentRecurringChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n cadence: input.cadence,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function verifyDirectRequestPaymentChallenge(\n secret: string,\n input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n },\n): Promise<boolean> {\n const parsed = parseDirectRequestPaymentChallenge(input.challenge);\n if (parsed.scheme !== DIRECT_REQUEST_PAYMENT_CHALLENGE_SCHEME) {\n return false;\n }\n const expected = await createDirectRequestPaymentChallengeSignature(secret, {\n merchant: input.merchant,\n amount_minor: input.amount_minor,\n currency: input.currency,\n nonce: parsed.nonce,\n });\n return timingSafeEqualHex(expected, parsed.signature);\n}\n\nexport async function directRequestPaymentChallengeHash(challenge: string): Promise<string> {\n return sha256Prefixed(requireNonEmpty(challenge, \"challenge\"));\n}\n\nexport async function directRequestPaymentRequestHash(input: {\n merchant: string;\n amount_minor: number;\n currency: DirectRequestPaymentCurrency | string;\n challenge: string;\n}): Promise<string> {\n const material = `${normalizeMerchant(input.merchant)}${positiveInteger(input.amount_minor, \"amount_minor\")}${normalizeCurrency(input.currency)}${requireNonEmpty(input.challenge, \"challenge\")}`;\n return sha256Prefixed(material);\n}\n\nexport function buildPaymentExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n return buildPreparedTransactionExecutionPayload(requirement, requirement.transaction_request, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildAllowanceExecutionPayload(\n requirement: DirectPaymentRequirement,\n options: { await_finality?: boolean; metadata?: Record<string, unknown> } = {},\n): Web3PreparedTransactionExecutePayload {\n const approveRequest = requirement.approve_transaction_request;\n if (!approveRequest || Object.keys(approveRequest).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"This payment requirement does not include an allowance approval transaction.\");\n }\n return buildPreparedTransactionExecutionPayload(requirement, approveRequest, {\n receipt_kind: DIRECT_REQUEST_PAYMENT_ALLOWANCE_RECEIPT_KIND,\n await_finality: options.await_finality,\n metadata: options.metadata,\n });\n}\n\nexport function buildPreparedTransactionExecutionPayload(\n requirement: DirectPaymentRequirement,\n transaction_request: Web3TransactionRequest,\n options: {\n receipt_kind: string;\n await_finality?: boolean;\n metadata?: Record<string, unknown>;\n },\n): Web3PreparedTransactionExecutePayload {\n const metadata = {\n ...(isRecord(transaction_request.metadata_jsonb) ? transaction_request.metadata_jsonb : {}),\n ...(options.metadata ?? {}),\n };\n return {\n transaction_request,\n receipt_kind: requireNonEmpty(options.receipt_kind, \"receipt_kind\"),\n reference_type: DIRECT_REQUEST_PAYMENT_REFERENCE_TYPE,\n reference_id: requirement.requirement_id,\n metadata,\n await_finality: Boolean(options.await_finality),\n };\n}\n\nexport async function computeWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp: number },\n): Promise<string> {\n if (!signing_secret) {\n throw new SiglumeWebhookSignatureError(\"SIGLUME webhook signing secret is required.\");\n }\n const timestamp = Math.trunc(options.timestamp);\n const bytes = bodyBytes(body);\n const prefix = new TextEncoder().encode(`${timestamp}.`);\n const payload = new Uint8Array(prefix.length + bytes.length);\n payload.set(prefix, 0);\n payload.set(bytes, prefix.length);\n return hmacSha256Hex(signing_secret, payload);\n}\n\nexport async function buildWebhookSignatureHeader(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n options: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = Math.trunc(options.timestamp ?? Date.now() / 1000);\n const signature = await computeWebhookSignature(signing_secret, body, { timestamp });\n return `t=${timestamp},v1=${signature}`;\n}\n\nexport async function verifyWebhookSignature(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<WebhookSignatureVerification> {\n const { timestamp, signature } = parseSignatureHeader(signature_header);\n const toleranceSeconds = Math.max(1, Math.trunc(options.tolerance_seconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS));\n const nowSeconds = Math.trunc(options.now ?? Date.now() / 1000);\n if (Math.abs(nowSeconds - timestamp) > toleranceSeconds) {\n throw new SiglumeWebhookSignatureError(\"Webhook timestamp is outside the allowed tolerance window.\");\n }\n const expected = await computeWebhookSignature(signing_secret, body, { timestamp });\n if (!(await timingSafeEqualHex(expected, signature))) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature did not match.\");\n }\n return { timestamp, signature };\n}\n\nexport function parseDirectRequestPaymentWebhookEvent(payload: unknown): DirectRequestPaymentWebhookEvent {\n const event = requireRecord(payload, \"webhook event\");\n const data = requireRecord(event.data, \"webhook event data\");\n const parsed = {\n ...event,\n id: requireNonEmpty(stringOrNull(event.id) ?? \"\", \"webhook event id\"),\n type: requireNonEmpty(stringOrNull(event.type) ?? \"\", \"webhook event type\"),\n api_version: requireNonEmpty(stringOrNull(event.api_version) ?? \"\", \"webhook api_version\"),\n occurred_at: requireNonEmpty(stringOrNull(event.occurred_at) ?? \"\", \"webhook occurred_at\"),\n data: { ...data },\n } as DirectRequestPaymentWebhookEvent;\n if (parsed.type === \"direct_payment.confirmed\" && parsed.data.mode !== DIRECT_REQUEST_PAYMENT_MODE) {\n throw new SiglumeWebhookPayloadError(\"direct_payment.confirmed webhook must carry data.mode='external_402'.\");\n }\n return parsed;\n}\n\nexport async function verifyDirectRequestPaymentWebhook(\n signing_secret: string,\n body: Uint8Array | ArrayBuffer | string | Record<string, unknown>,\n signature_header: string,\n options: { tolerance_seconds?: number; now?: number } = {},\n): Promise<{ event: DirectRequestPaymentWebhookEvent; verification: WebhookSignatureVerification }> {\n const verification = await verifyWebhookSignature(signing_secret, body, signature_header, options);\n const text = new TextDecoder().decode(bodyBytes(body));\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new SiglumeWebhookPayloadError(\"Webhook body must contain valid JSON.\");\n }\n return { event: parseDirectRequestPaymentWebhookEvent(parsed), verification };\n}\n\nexport const createExternal402Challenge = createDirectRequestPaymentChallenge;\nexport const verifyExternal402Challenge = verifyDirectRequestPaymentChallenge;\nexport const createExternal402RecurringChallenge = createDirectRequestPaymentRecurringChallenge;\nexport const verifyExternal402RecurringChallenge = verifyDirectRequestPaymentRecurringChallenge;\n\nfunction normalizeMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be a lowercase key using letters, numbers, dot, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeSelfServiceMerchant(value: string): string {\n const merchant = requireNonEmpty(value, \"merchant\").toLowerCase();\n if (!/^[a-z0-9][a-z0-9_-]{2,63}$/.test(merchant)) {\n throw new SiglumeDirectRequestPaymentError(\"merchant must be 3-64 chars using lowercase letters, numbers, underscore, or hyphen.\");\n }\n return merchant;\n}\n\nfunction normalizeBillingPlan(value: string): DirectRequestPaymentBillingPlan {\n const plan = requireNonEmpty(value, \"billing_plan\").toLowerCase();\n if (plan === \"launch\" || plan === \"free\" || plan === \"starter\" || plan === \"growth\" || plan === \"pro\") {\n return plan;\n }\n throw new SiglumeDirectRequestPaymentError(\"billing_plan must be launch, starter, growth, or pro.\");\n}\n\nfunction normalizeCurrency(value: string): DirectRequestPaymentCurrency {\n const currency = requireNonEmpty(value, \"currency\").toUpperCase();\n if (currency !== \"JPY\" && currency !== \"USD\") {\n throw new SiglumeDirectRequestPaymentError(\"currency must be JPY or USD.\");\n }\n return currency;\n}\n\nfunction normalizeToken(value: string): DirectRequestPaymentToken {\n const token = requireNonEmpty(value, \"token_symbol\").toUpperCase();\n if (token !== \"JPYC\" && token !== \"USDC\") {\n throw new SiglumeDirectRequestPaymentError(\"token_symbol must be JPYC or USDC.\");\n }\n return token;\n}\n\nfunction normalizeAllowedCurrencies(value: Record<string, string> | Array<DirectRequestPaymentCurrency | string>): Record<string, string> {\n const normalized: Record<string, string> = {};\n if (Array.isArray(value)) {\n for (const item of value) {\n const currency = normalizeCurrency(item);\n normalized[currency] = defaultTokenForCurrency(currency);\n }\n } else if (isRecord(value)) {\n for (const [rawCurrency, rawToken] of Object.entries(value)) {\n normalized[normalizeCurrency(rawCurrency)] = normalizeToken(String(rawToken));\n }\n } else {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must be an array or a currency-to-token object.\");\n }\n if (Object.keys(normalized).length === 0) {\n throw new SiglumeDirectRequestPaymentError(\"allowed_currencies must include at least one currency.\");\n }\n return normalized;\n}\n\nfunction defaultTokenForCurrency(currency: DirectRequestPaymentCurrency): DirectRequestPaymentToken {\n return currency === \"JPY\" ? \"JPYC\" : \"USDC\";\n}\n\nfunction normalizeOriginList(value: string[]): string[] {\n if (!Array.isArray(value)) {\n throw new SiglumeDirectRequestPaymentError(\"checkout_allowed_origins must be an array of origin URLs.\");\n }\n const seen = new Set<string>();\n const origins: string[] = [];\n for (const item of value) {\n let url: URL;\n try {\n url = new URL(requireNonEmpty(String(item), \"checkout_allowed_origins entry\"));\n } catch {\n throw new SiglumeDirectRequestPaymentError(\n \"each checkout_allowed_origins entry must be an absolute origin such as https://shop.example.com.\",\n );\n }\n const origin = `${url.protocol.toLowerCase()}//${url.host.toLowerCase()}`;\n if (!seen.has(origin)) {\n seen.add(origin);\n origins.push(origin);\n }\n }\n return origins;\n}\n\nfunction positiveInteger(value: number, name: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a positive safe integer.`);\n }\n return parsed;\n}\n\nfunction requireNonEmpty(value: string, name: string): string {\n const text = String(value ?? \"\").trim();\n if (!text) {\n throw new SiglumeDirectRequestPaymentError(`${name} is required.`);\n }\n return text;\n}\n\nfunction normalizeChallengeNonce(value: string): string {\n const nonce = requireNonEmpty(value, \"nonce\");\n if (nonce.includes(\":\")) {\n throw new SiglumeDirectRequestPaymentError(\"nonce must not contain ':'.\");\n }\n return nonce;\n}\n\nfunction normalizeRecurringCadence(value: string): DirectRequestPaymentRecurringCadence {\n const cadence = requireNonEmpty(value, \"cadence\").toLowerCase();\n if (cadence !== \"monthly\" && cadence !== \"daily\") {\n throw new SiglumeDirectRequestPaymentError(\n 'cadence must be \"monthly\" (subscription) or \"daily\" (scheduled autopay).',\n );\n }\n return cadence;\n}\n\nfunction cloneJsonObject(value: Record<string, unknown>, name: string): Record<string, unknown> {\n try {\n const cloned = JSON.parse(JSON.stringify(value)) as unknown;\n if (!isRecord(cloned)) {\n throw new Error(\"not an object\");\n }\n return cloned;\n } catch (error) {\n throw new SiglumeDirectRequestPaymentError(`${name} must be a JSON-serializable object.`);\n }\n}\n\nfunction parseJson(rawText: string): unknown {\n try {\n return JSON.parse(rawText);\n } catch (error) {\n throw new SiglumeApiError(\"Siglume API returned invalid JSON.\", {\n status: 502,\n code: \"INVALID_JSON_RESPONSE\",\n data: rawText,\n });\n }\n}\n\nfunction stringOrNull(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const text = value.trim();\n return text ? text : null;\n}\n\nfunction isHostedCheckoutUnavailable(error: unknown): boolean {\n if (!(error instanceof SiglumeApiError)) {\n return false;\n }\n const code = error.code.toUpperCase();\n if (error.status === 409 && (code === \"HOSTED_CHECKOUT_NOT_ENABLED\" || code === \"FEATURE_DISABLED\")) {\n return true;\n }\n return (\n error.status === 404 &&\n (code === \"HTTP_404\" || code === \"NOT_FOUND\" || code === \"ROUTE_NOT_FOUND\" || code === \"FEATURE_DISABLED\")\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requireRecord(value: unknown, name: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new SiglumeWebhookPayloadError(`${name} must be an object.`);\n }\n return value;\n}\n\nfunction envValue(name: string): string | undefined {\n if (typeof process === \"undefined\") {\n return undefined;\n }\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nfunction bodyBytes(body: Uint8Array | ArrayBuffer | string | Record<string, unknown>): Uint8Array {\n if (body instanceof Uint8Array) {\n return body;\n }\n if (body instanceof ArrayBuffer) {\n return new Uint8Array(body);\n }\n if (typeof body === \"string\") {\n return new TextEncoder().encode(body);\n }\n if (isRecord(body)) {\n return new TextEncoder().encode(JSON.stringify(body));\n }\n throw new SiglumeWebhookPayloadError(\"Webhook body must be raw bytes, a string, or a JSON object.\");\n}\n\nfunction parseSignatureHeader(signatureHeader: string): { timestamp: number; signature: string } {\n let timestamp: number | null = null;\n let signature: string | null = null;\n for (const item of String(signatureHeader ?? \"\").split(\",\")) {\n const [key, value] = item.trim().split(\"=\", 2);\n if (key === \"t\") {\n const parsed = Number.parseInt(value ?? \"\", 10);\n if (!Number.isFinite(parsed)) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature timestamp is invalid.\");\n }\n timestamp = parsed;\n }\n if (key === \"v1\") {\n signature = String(value ?? \"\").trim();\n }\n }\n if (timestamp === null || !signature) {\n throw new SiglumeWebhookSignatureError(\"Webhook signature header is incomplete.\");\n }\n return { timestamp, signature };\n}\n\nasync function randomNonce(): Promise<string> {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n const bytes = new Uint8Array(16);\n if (globalThis.crypto?.getRandomValues) {\n globalThis.crypto.getRandomValues(bytes);\n } else if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n bytes.set(crypto.randomBytes(16));\n } else {\n throw new SiglumeDirectRequestPaymentError(\"Crypto random number generation is unavailable in this runtime.\");\n }\n return bytesToHex(bytes);\n}\n\nasync function hmacSha256Hex(secret: string, payload: Uint8Array): Promise<string> {\n if (globalThis.crypto?.subtle) {\n const stablePayload = new Uint8Array(payload.byteLength);\n stablePayload.set(payload);\n const key = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const digest = await globalThis.crypto.subtle.sign(\"HMAC\", key, stablePayload);\n return bytesToHex(new Uint8Array(digest));\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return crypto.createHmac(\"sha256\", secret).update(Buffer.from(payload)).digest(\"hex\");\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for HMAC-SHA256 in this runtime.\");\n}\n\nasync function sha256Prefixed(material: string): Promise<string> {\n const bytes = new TextEncoder().encode(material);\n if (globalThis.crypto?.subtle) {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return `sha256:${bytesToHex(new Uint8Array(digest))}`;\n }\n if (typeof process !== \"undefined\" && process.versions?.node) {\n const crypto = await import(\"node:crypto\");\n return `sha256:${crypto.createHash(\"sha256\").update(Buffer.from(bytes)).digest(\"hex\")}`;\n }\n throw new SiglumeDirectRequestPaymentError(\"Web Crypto is required for SHA-256 in this runtime.\");\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return [...bytes].map((item) => item.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const normalized = String(hex ?? \"\").trim().toLowerCase();\n if (normalized.length % 2 !== 0 || !/^[0-9a-f]*$/.test(normalized)) {\n throw new SiglumeWebhookSignatureError(\"Hex digest is invalid.\");\n }\n const bytes = new Uint8Array(normalized.length / 2);\n for (let index = 0; index < normalized.length; index += 2) {\n bytes[index / 2] = Number.parseInt(normalized.slice(index, index + 2), 16);\n }\n return bytes;\n}\n\nasync function timingSafeEqualHex(left: string, right: string): Promise<boolean> {\n const leftBytes = hexToBytes(left);\n const rightBytes = hexToBytes(right);\n if (leftBytes.length !== rightBytes.length) {\n return false;\n }\n let diff = 0;\n for (let index = 0; index < leftBytes.length; index += 1) {\n diff |= leftBytes[index]! ^ rightBytes[index]!;\n }\n return diff === 0;\n}\n"],"mappings":";AAAO,IAAM,2BAA2B;AACjC,IAAM,0CAA0C;AAIhD,IAAM,oDAAoD;AAC1D,IAAM,8BAA8B;AACpC,IAAM,sCAAsC;AAC5C,IAAM,gDAAgD;AACtD,IAAM,wCAAwC;AAC9C,IAAM,oCAAoC;AAyS1C,IAAM,mCAAN,cAA+C,MAAM;AAAA,EAC1D,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,kBAAN,cAA8B,iCAAiC;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,SAA4D;AACvF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ;AACtB,SAAK,OAAO,QAAQ,QAAQ;AAC5B,SAAK,OAAO,QAAQ;AAAA,EACtB;AACF;AAEO,IAAM,kCAAN,cAA8C,gBAAgB;AAAA,EACnE,YAAY,UAAU,qFAAqF;AACzG,UAAM,SAAS,EAAE,QAAQ,KAAK,MAAM,8BAA8B,CAAC;AACnE,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,+BAAN,cAA2C,iCAAiC;AAAA,EACjF,YAAY,SAAiB;AAC3B,UAAM,OAA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AC,GAAG,EAAE;AAAA,EAC3E;AACA,SAAO;AACT;AAEA,eAAe,mBAAmB,MAAc,OAAiC;AAC/E,QAAM,YAAY,WAAW,IAAI;AACjC,QAAM,aAAa,WAAW,KAAK;AACnC,MAAI,UAAU,WAAW,WAAW,QAAQ;AAC1C,WAAO;AAAA,EACT;AACA,MAAI,OAAO;AACX,WAAS,QAAQ,GAAG,QAAQ,UAAU,QAAQ,SAAS,GAAG;AACxD,YAAQ,UAAU,KAAK,IAAK,WAAW,KAAK;AAAA,EAC9C;AACA,SAAO,SAAS;AAClB;","names":[]}
@@ -6,6 +6,8 @@ Siglume Direct Request Payment 向けの外部事業者用SDKを公開しまし
6
6
  - PyPI: https://pypi.org/project/siglume-direct-request-payment/
7
7
  - GitHub: https://github.com/taihei-05/siglume-direct-request-payment
8
8
 
9
+ > **Beta / サーバーロールアウト中**: Hosted Checkout はアカウントごとに段階提供中です。未提供アカウントでは `createCheckoutSession(...)` / `getCheckoutSession(...)` が `HostedCheckoutNotAvailableError` を返します。生の 404/409 をそのまま利用者へ見せず、提供開始まで既存の agent/API 経路を利用してください。
10
+
9
11
  このSDKは、外部EC、予約サービス、会員制サービス、有料API、scheduled autopay などで、SDRP の Standard Payment / 通常決済を自社プロダクトに組み込むためのSDKです。
10
12
 
11
13
  ## できること
@@ -60,17 +62,17 @@ Standard Payment は1決済ごとに精算します。Micro / Nano は金額帯
60
62
  | 帯 | 周期 | 締め期間 | 着金タイミング |
61
63
  | --- | --- | --- | --- |
62
64
  | Standard Payment | 都度 | — | 各決済の確定直後にオンチェーン精算 |
63
- | Micro Payment | 週次 | カレンダー週(現状は月曜 00:00 〜 翌週月曜 00:00) | 週が締まった後、受取先・出品ごとに集約してオンチェーン精算(1件以上) |
64
- | Nano Payment | 月次 | カレンダー月(現状は1日 00:00 〜 翌月1日 00:00) | 月が締まった後、受取先・出品ごとに集約してオンチェーン精算(1件以上) |
65
+ | Micro Payment | 週次 | アカウント別に割り当てられた固定の週次スロット | 締め後、確定通知と約3日の事前通知サイトを置いてから、受取先・出品ごとに集約してオンチェーン精算(1件以上) |
66
+ | Nano Payment | 月次 | アカウント別に割り当てられた固定の月次スロット | 締め後、確定通知と約3日の事前通知サイトを置いてから、受取先・出品ごとに集約してオンチェーン精算(1件以上) |
65
67
 
66
- - **締め期間**: Micro は1カレンダー週(月曜始まり)、Nano は1カレンダー月(1日始まり)でまとめます。正確な締め時刻はプラットフォーム管理で変更されうるため、下記「確定事項と可変事項」を参照してください。
67
- - **タイムゾーン**: 締めの境界は購入者が設定した精算タイムゾーン(現状の既定は UTC)で判定され、購入者ごとに境界が少しずれることがあります。既定タイムゾーンはプラットフォーム管理で変更されることがあります。
68
- - **精算バッチ/支払い実行**: 期間が締まった後、その期間分を受取先・出品・トークンごとに集約し(1件以上)、次の精算パスで自動的にオンチェーン送金します。締めと送金の間には短い(プラットフォーム管理の)遅延があります。
68
+ - **締め期間**: Micro は週次、Nano は月次でまとめます。具体的な締め曜日・日・時刻は、負荷分散のためアカウントごとに固定スロットとして割り当てられます。
69
+ - **タイムゾーン**: 締めの境界は購入者が設定した精算タイムゾーン(既定は UTC)で判定されます。割り当て済みスロットは、予告なくオンザフライで再計算されません。
70
+ - **精算バッチ/支払い実行**: 期間が締まった後、その期間分を受取先・出品・トークンごとに集約し(1件以上)、購入者へ確定通知を送ります。実際の引き落としは締め後おおむね3日の事前通知サイト後、`not_before_attempt_at` 以降の精算パスで実行されます。
69
71
  - **売上として確認できる時点**: Micro/Nano の支払いはオンチェーン精算が確定して初めて確定売上になります。それまでは「未精算」です。プラットフォームの精算ステータス/Webhook を正本としてください。
70
72
  - **休日・失敗・再試行・繰越**: オンチェーン精算のため銀行休業日の影響はなく、曜日に関係なくカレンダー境界で締まります。精算が失敗した場合(例: 精算時に購入者ウォレットの予算が不足/無効)は自動で再試行され、その購入者の同一トークンの Micro/Nano は未解決の精算が片付くまで一時停止します。未精算額が消えることはなく、失敗した精算に紐づいたまま、再試行成功時に支払われます。
71
73
  - **rejected / 課金なし**: 購入者ウォレットの予算は **グロス額**(料金+プロトコルフィー)で消費され、受理時から精算確定まで確保されます。予算・scope・金額帯が満たされない場合は **課金なしで拒否**され、リクエストは実行されず、精算にも計上されません。
72
74
 
73
- **確定事項と可変事項**: 周期は固定です(**Micro は週次、Nano は月次**。確定はオンチェーン精算後)。正確な締め時刻、既定タイムゾーン、締めから送金までの遅延、再試行間隔はプラットフォーム側で管理され変更されうるため、暦をハードコードせずプラットフォームの精算ステータスと `fee_bps` を正本としてください。
75
+ **確定事項と可変事項**: 周期は固定です(**Micro は週次、Nano は月次**。確定はオンチェーン精算後)。具体的な締めスロット、予定引き落とし時刻、再試行間隔はプラットフォーム側で管理されるため、暦をハードコードせずプラットフォームの精算ステータスと `fee_bps` を正本としてください。
74
76
 
75
77
  ## 最短導入
76
78
 
@@ -10,7 +10,7 @@ SDRP serves two kinds of buyer, and you integrate each differently. In both
10
10
  cases the buyer pays from a Siglume wallet (JPYC for JPY, USDC for USD) — not a
11
11
  card — and the merchant SDK never authenticates the buyer.
12
12
 
13
- - **Human web shopper → Hosted Checkout.** Call
13
+ - **Human web shopper → Hosted Checkout (Beta; server rollout in progress).** Call
14
14
  [`createCheckoutSession`](#createcheckoutsessioninput--create_checkout_session)
15
15
  on `DirectRequestPaymentMerchantClient` and redirect the shopper to the
16
16
  returned `checkout_url`. The shopper signs into Siglume on the hosted page,
@@ -216,6 +216,12 @@ webhook-origin auto-allow apply.
216
216
 
217
217
  ### `createCheckoutSession(input)` / `create_checkout_session(...)`
218
218
 
219
+ Beta / server rollout: Hosted Checkout is rolling out account by account. If the
220
+ server endpoint is not enabled for the merchant yet, the SDK raises
221
+ `HostedCheckoutNotAvailableError` (TS + Py) rather than leaking a raw rollout
222
+ 404/409. Fulfillment must still key off the signed `direct_payment.confirmed`
223
+ webhook.
224
+
219
225
  Creates a single-use, expiring Hosted Checkout session for a human web shopper
220
226
  and returns the URL to redirect them to. Requires the merchant's Siglume bearer
221
227
  token. The server authors the challenge from the merchant's challenge secret —
@@ -447,6 +453,7 @@ TypeScript exports:
447
453
 
448
454
  - `SiglumeDirectRequestPaymentError`
449
455
  - `SiglumeApiError`
456
+ - `HostedCheckoutNotAvailableError`
450
457
  - `SiglumeWebhookSignatureError`
451
458
  - `SiglumeWebhookPayloadError`
452
459
 
@@ -454,8 +461,11 @@ Python exports:
454
461
 
455
462
  - `DirectRequestPaymentError`
456
463
  - `SiglumeApiError`
464
+ - `HostedCheckoutNotAvailableError`
457
465
  - `SiglumeWebhookSignatureError`
458
466
  - `SiglumeWebhookPayloadError`
459
467
 
460
468
  `SiglumeApiError` includes the HTTP status, platform error code, and parsed
461
469
  response data where available.
470
+ `HostedCheckoutNotAvailableError` is raised when the Hosted Checkout server
471
+ surface is not enabled for the account yet during the rollout.
@@ -24,7 +24,7 @@ revenue remains unsettled until the later on-chain settlement succeeds.
24
24
 
25
25
  There are two ways a buyer reaches you, and you integrate each differently:
26
26
 
27
- - **Human web shopper → Hosted Checkout.** Create a checkout session and
27
+ - **Human web shopper → Hosted Checkout (Beta; server rollout in progress).** Create a checkout session and
28
28
  redirect the shopper to the Siglume-hosted page (the
29
29
  [section below](#hosted-checkout-human-web-shoppers)). This is the path that
30
30
  resembles a Stripe-style hosted checkout.
@@ -38,6 +38,10 @@ the merchant SDK never authenticates the buyer, and you fulfill on the same
38
38
 
39
39
  ## Hosted Checkout (Human Web Shoppers)
40
40
 
41
+ **Beta / server rollout:** Hosted Checkout is rolling out account by account.
42
+ Some merchant accounts may not have the server endpoint enabled yet. The SDK
43
+ raises `HostedCheckoutNotAvailableError` for rollout 404/409 responses.
44
+
41
45
  When a person clicks "Pay with Siglume" on your site, create a session and
42
46
  redirect them to the returned `checkout_url`. They sign into Siglume on the
43
47
  hosted page, approve, and pay from their own wallet, then return to your
package/docs/pricing.md CHANGED
@@ -59,34 +59,38 @@ confirmed payment turns into money in your settlement wallet.
59
59
  | Band | Cadence | Period | You are paid |
60
60
  | --- | --- | --- | --- |
61
61
  | Standard Payment | Per payment | n/a | On-chain, immediately after each payment confirms |
62
- | Micro Payment | Weekly | Buyer settlement timezone Monday 00:00 to the next Monday 00:00; default timezone is UTC | After the week closes, in aggregated on-chain settlement(s) grouped per buyer, payee, token, and period |
63
- | Nano Payment | Monthly | Buyer settlement timezone 1st 00:00 to the 1st of the next month 00:00; default timezone is UTC | After the month closes, in aggregated on-chain settlement(s) grouped per buyer, payee, token, and period |
62
+ | Micro Payment | Weekly | Fixed weekly slot assigned per account | After the period closes, after the final notice and an approximately 3-day pre-debit notice site, in aggregated on-chain settlement(s) grouped per buyer, payee, token, and period |
63
+ | Nano Payment | Monthly | Fixed monthly slot assigned per account | After the period closes, after the final notice and an approximately 3-day pre-debit notice site, in aggregated on-chain settlement(s) grouped per buyer, payee, token, and period |
64
64
 
65
65
  ### Micro weekly settlement
66
66
 
67
- - **Closing period.** Micro-band payments accrue across one calendar week:
68
- Monday 00:00 to the following Monday 00:00 in the buyer settlement timezone.
67
+ - **Closing period.** Micro-band payments accrue across one weekly period. The
68
+ specific closing weekday and time are assigned as a fixed slot per account to
69
+ spread settlement load.
69
70
  - **Timezone.** Period boundaries are evaluated in the buyer's configured
70
- settlement timezone, defaulting to UTC, so different buyers can close on
71
- slightly different local boundaries.
71
+ settlement timezone, defaulting to UTC. Assigned slots are persisted and are
72
+ not recalculated on the fly.
72
73
  - **Settlement.** After the week closes, Siglume aggregates that week's Micro
73
74
  payments — grouped per buyer, payee, token, and period — into on-chain
74
- settlement(s). Aggregation and payment run automatically on the next settlement
75
- pass after the period closes; there is a short, platform-managed lag between
76
- the close and the on-chain transaction.
75
+ settlement(s). Siglume sends the final debit notice first; the on-chain debit
76
+ is not attempted until the scheduled attempt time after an approximately
77
+ 3-day pre-debit notice site (`not_before_attempt_at`).
77
78
  - **Revenue recognition.** A Micro payment is final only once its weekly
78
79
  settlement confirms on-chain. Until then it is accrued, not settled.
79
80
 
80
81
  ### Nano monthly settlement
81
82
 
82
- - **Closing period.** Nano-band payments accrue across one calendar month:
83
- the 1st at 00:00 to the 1st of the next month at 00:00 in the buyer
84
- settlement timezone.
83
+ - **Closing period.** Nano-band payments accrue across one monthly period. The
84
+ specific closing day and time are assigned as a fixed slot per account to
85
+ spread settlement load.
85
86
  - **Timezone.** As with Micro, period boundaries use the buyer's configured
86
- settlement timezone, defaulting to UTC.
87
+ settlement timezone, defaulting to UTC. Assigned slots are persisted and are
88
+ not recalculated on the fly.
87
89
  - **Settlement.** After the month closes, Siglume aggregates that month's Nano
88
90
  payments — grouped per buyer, payee, token, and period — into on-chain
89
- settlement(s), on the next settlement pass after the period closes.
91
+ settlement(s). Siglume sends the final debit notice first; the on-chain debit
92
+ is not attempted until the scheduled attempt time after an approximately
93
+ 3-day pre-debit notice site (`not_before_attempt_at`).
90
94
  - **Revenue recognition.** A Nano payment is final only once its monthly
91
95
  settlement confirms on-chain.
92
96
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@siglume/direct-request-payment",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "SDK for the Siglume Direct Request Payment SDRP payment protocol",
5
5
  "keywords": [
6
6
  "siglume",