@facto-to/connect 0.0.1-beta1 → 0.0.1-beta2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -71,12 +71,16 @@ const facto = createFactoConnectServer({
71
71
  appId: process.env.FACTO_APP_ID!,
72
72
  clientId: process.env.FACTO_CLIENT_ID!,
73
73
  clientSecret: process.env.FACTO_CLIENT_SECRET!,
74
- environment: 'sandbox',
75
74
  })
76
75
 
77
76
  const linked = await facto.exchangeUserLinkCode({ code, state, nonce })
78
77
  ```
79
78
 
79
+ Credentials and endpoints are one decision, not three. The client id Facto issued
80
+ you already names its environment, so the SDK reads it and resolves both the API
81
+ base URL and the Hosted Connect origin from it — there is nothing else to
82
+ configure and no URL to paste.
83
+
80
84
  The server entrypoint wraps:
81
85
 
82
86
  - `POST /api/merchant/user-links/exchange`
@@ -90,29 +94,46 @@ The public GA operation names mirror the OpenAPI contract:
90
94
  `getAuthorizationSession`, `getPaymentAuthorization`, `createMerchantPayment`, and
91
95
  `getMerchantPayment`. The pre-GA names remain as deprecated source-compatible aliases.
92
96
 
93
- `environment` is required and accepts `sandbox`, `dev`, or `production`. Per ADR-0077
97
+ ### Environment
98
+
99
+ `environment` is optional and accepts `sandbox`, `dev`, or `production`. Per ADR-0077
94
100
  (“sandbox naming, dev interface”), `sandbox` is the documented public name for the test
95
101
  environment and `dev` is the infrastructure name for the same environment: both resolve the
96
102
  same published dev endpoints (`https://dev-api.facto.to`, hosted Connect
97
- `https://dev.facto.to`) and the `/api/dev/*` route family. There is no implicit default:
98
- omitting `environment` throws at construction. The historical silent fallback — Production
99
- endpoints over the legacy `/api/external/*` routes — was removed before first publish, so a
100
- wrong environment fails loudly at construction instead of sending credentialed traffic to the
101
- wrong deployment at runtime. Exact published origins are matched fail-closed, and
102
- selector/origin or API/Hosted environment conflicts are rejected before any credential-bearing
103
- request. All operations, including the deprecated pre-GA aliases, use only the canonical
103
+ `https://dev.facto.to`) and the `/api/dev/*` route family.
104
+
105
+ Omit it and the environment is derived from `clientId`, in this order:
106
+
107
+ 1. the explicit `environment` value, when you pass one;
108
+ 2. the client id's keyspace — `dev_mcid_`/`dev_pspid_`/`dev_cpid_` resolve dev, bare
109
+ `mcid_`/`pspid_`/`cpid_` resolve production;
110
+ 3. an `apiBaseUrl` or `hostedConnectUrl` you pointed at a published Facto endpoint.
111
+
112
+ That is evidence, never a default. A client id carrying no published keyspace — internal
113
+ (`lab_`, `staging_`, `test_`), legacy (`sandbox_`), or unrecognized — derives nothing and
114
+ throws at construction. The historical silent fallback — Production endpoints over the
115
+ legacy `/api/external/*` routes — was removed before first publish, so a wrong environment
116
+ still fails loudly at construction instead of sending credentialed traffic to the wrong
117
+ deployment at runtime. An explicit `environment` that contradicts the credential is also
118
+ rejected there rather than silently preferring one of the two. Exact published origins are
119
+ matched fail-closed, and selector/origin or API/Hosted environment conflicts are rejected
120
+ before any credential-bearing request.
121
+
122
+ `factoConnectEnvironmentFromClientId(clientId)` is exported if you need the same reading
123
+ outside the client — for a config banner or a startup assertion, say. It returns `'dev'`,
124
+ `'production'`, or `undefined`. All operations, including the deprecated pre-GA aliases, use only the canonical
104
125
  `/api/connect` and `/api/merchant` families; the legacy `/api/external` aliases are gone. The
105
126
  published dev URL is a target endpoint and does not imply that a named dev deployment is
106
127
  currently available.
107
128
 
108
129
  `staging` and the former `custom` selector are retired. Local, private, and staging
109
- deployments keep any `environment` value and pass explicit `apiBaseUrl` and
110
- `hostedConnectUrl` overrides, which take precedence over the published endpoint tables:
130
+ deployments pass explicit `apiBaseUrl` and `hostedConnectUrl` overrides, which take
131
+ precedence over the published endpoint tables. A dev credential still names the environment
132
+ for the dev-only capability gates, so `environment` stays optional here too:
111
133
 
112
134
  ```ts
113
135
  createFactoConnectServer({
114
136
  ...credentials,
115
- environment: 'sandbox',
116
137
  apiBaseUrl: 'http://127.0.0.1:8080',
117
138
  hostedConnectUrl: 'http://127.0.0.1:5173',
118
139
  })
@@ -1 +1 @@
1
- "use strict";var z=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var ve=Object.prototype.hasOwnProperty;var Ee=(t,e)=>{for(var n in e)z(t,n,{get:e[n],enumerable:!0})},we=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _e(e))!ve.call(t,o)&&o!==n&&z(t,o,{get:()=>e[o],enumerable:!(a=Ie(e,o))||a.enumerable});return t};var Pe=t=>we(z({},"__esModule",{value:!0}),t);var tn={};Ee(tn,{FACTO_CONNECT_API_BASE_URLS:()=>F,FACTO_CONNECT_HOSTED_URLS:()=>E,FactoConnectHintError:()=>l,FactoConnectServerError:()=>S,buildHostedConnectUrl:()=>fe,createFactoConnectServer:()=>pe,default:()=>en,isTerminalMandatePaymentStatus:()=>ge,signWebhookPayload:()=>Dt,verifyFactoCardProgramConnectHint:()=>zt,verifyWebhookSignature:()=>Ft,withServerRetry:()=>me});module.exports=Pe(tn);var L=require("node:crypto");var X=["mandate_inactive","mandate_revoked","mandate_expired","use_case_not_allowed","mandate_limit_exceeded","mandate_period_limit_exceeded","user_limit_exceeded","limit_check_unavailable","payment_path_unavailable","payment_option_not_pinned","idempotency_conflict"];var ee=["payment_route_not_provisioned","protocol_config_incomplete"];function G(t){return t==="sandbox"?"dev":t}var F=Object.freeze({dev:"https://dev-api.facto.to",production:"https://api.facto.to"}),E=Object.freeze({dev:"https://dev.facto.to",production:"https://app.facto.to"}),h=Object.freeze({exchangeLinkCode:"/api/merchant/user-links/exchange",paymentCapability:"/api/merchant/payment-readiness",checkoutSessions:"/api/merchant/checkout-sessions",authorizationSessions:"/api/merchant/authorization-sessions",paymentAuthorizations:"/api/merchant/payment-authorizations",paymentOptions:"/api/merchant/payment-options",payments:"/api/merchant/payments"}),S=class extends Error{code;retryable;status;details;retryAfterSeconds;constructor(e,n,a){super(n),this.name="FactoConnectServerError",this.code=e,this.retryable=a.retryable,this.status=a.status,this.details=a.details,this.retryAfterSeconds=a.retryAfterSeconds}};function Te(t){let e=t.headers.get("retry-after");if(!e)return;let n=Number(e.trim());return Number.isFinite(n)&&n>=0?n:void 0}function ke(t,e){return t<=0?Promise.resolve():new Promise((n,a)=>{if(e?.aborted){a(new S("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new S("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};e?.addEventListener("abort",s,{once:!0})})}async function me(t,e={}){let n=e.maxRetries??2,a=e.baseDelayMs??200,o=e.maxDelayMs??5e3,s=e.respectRetryAfter??!0,d=e.sleep??ke,u=0;for(;;)try{return await t()}catch(m){if(!(m instanceof S)||!m.retryable||u>=n)throw m;u+=1;let r=s&&typeof m.retryAfterSeconds=="number"?m.retryAfterSeconds*1e3:void 0,i=Math.min(o,a*2**(u-1)),y=i*.25*Math.random(),U=r??i+y;e.onRetry?.({attempt:u,error:m,delayMs:U}),await d(U,e.signal)}}function fe(t){t.appId||f("appId is required"),t.state||f("state is required"),t.nonce||f("nonce is required"),t.hostedConnectUrl||f("hostedConnectUrl is required and has no implicit default: pass the Hosted Connect origin for the target environment (e.g. FACTO_CONNECT_HOSTED_URLS.dev)");let e=j(t.hostedConnectUrl);v(e,E,"hostedConnectUrl",!0);let n=new URL("/connect",`${e}/`);n.searchParams.set("external_app_id",t.appId),n.searchParams.set("external_state",t.state),n.searchParams.set("external_nonce",t.nonce);let a=new URLSearchParams;t.customerEmail!==void 0&&a.set("customer_email",t.customerEmail),t.customerUsername!==void 0&&a.set("customer_username",t.customerUsername);let o=a.toString();return o&&(n.hash=o),n.toString()}function pe(t){let e=Oe(t),n=`Basic ${Ot(`${e.clientId}:${e.clientSecret}`)}`,a=(r,i)=>R(e,r,{code:i.code,state:i.state,nonce:i.nonce},n,st),o=(r,i)=>R(e,r,ot(e,i),n,it),s=(r,i)=>R(e,r,{appId:e.appId,externalCustomerRef:i.externalCustomerRef,requestedUseCases:i.requestedUseCases,defaultLimits:i.defaultLimits,returnUrl:i.returnUrl,state:i.state,...i.customerEmail===void 0?{}:{customerEmail:i.customerEmail},...i.customerUsername===void 0?{}:{customerUsername:i.customerUsername}},n,de),d=(r,i)=>b(e,`${r}/${encodeURIComponent(i)}`,n,de),u=(r,i)=>b(e,`${r}/${encodeURIComponent(i)}`,n,ce),m=(r,i)=>{let y={mandateId:i.mandateId,merchantPaymentRef:i.merchantPaymentRef,amount:i.amount,currency:i.currency,useCase:i.useCase};return i.paymentOptionId!==void 0&&(y.paymentOptionId=i.paymentOptionId),i.description!==void 0&&(y.description=i.description),i.metadata!==void 0&&(y.metadata=i.metadata),R(e,r,y,n,O,{"Idempotency-Key":i.idempotencyKey},[402])},p=(r,i)=>b(e,`${r}/${encodeURIComponent(i)}`,n,O);return{createHostedConnectUrl(r){let i=r.hostedConnectUrl??e.hostedConnectUrl;if(r.hostedConnectUrl!==void 0){let y=v(r.hostedConnectUrl,E,"hostedConnectUrl",!0);y!==void 0&&y!==e.environment&&f("hostedConnectUrl conflicts with the configured environment")}return fe({appId:e.appId,state:r.state,nonce:r.nonce,customerEmail:r.customerEmail,customerUsername:r.customerUsername,hostedConnectUrl:i})},exchangeUserLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentReadiness(r){return o(h.paymentCapability,r)},createAuthorizationSession(r){return s(h.authorizationSessions,r)},getAuthorizationSession(r){return d(h.authorizationSessions,r)},getPaymentAuthorization(r){return u(h.paymentAuthorizations,r)},createMerchantPayment(r){return m(h.payments,r)},getMerchantPayment(r){return p(h.payments,r)},exchangeLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentCapability(r){return o(h.paymentCapability,r)},createCheckoutSession(r){return r.userLinkRef!==void 0&&_(r.userLinkRef,"ul_","userLinkRef"),R(e,h.checkoutSessions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{app_id:e.appId,facto_server_wallet_address:r.factoServerWalletAddress},amount:r.amount,asset_symbol:r.assetSymbol,order_ref:r.orderRef,return_url:r.returnUrl},n,dt)},getCheckoutSession(r){return b(e,`${h.checkoutSessions}/${encodeURIComponent(r)}`,n,ct)},createMandateAuthorizationSession(r){return s(h.authorizationSessions,r)},getMandateAuthorizationSession(r){return d(h.authorizationSessions,r)},getMerchantMandate(r){return u(h.paymentAuthorizations,r)},listPaymentOptions(r){return r.userLinkRef!==void 0&&_(r.userLinkRef,"ul_","userLinkRef"),R(e,h.paymentOptions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{appId:e.appId,grantRef:r.grantRef},...r.amount!==void 0?{amount:r.amount}:{},...r.assetSymbol!==void 0?{assetSymbol:r.assetSymbol}:{}},n,mt)},createMandatePayment(r){return m(h.payments,r)},getMandatePayment(r){return p(h.payments,r)},onStatus(r,i,y){return xe(()=>b(e,`${h.payments}/${encodeURIComponent(r)}`,n,O),i,y)},revokeUserLink(r){return ae(e,`/api/merchant/user-links/${encodeURIComponent(r)}`,n)},listMerchantPayments(r={}){return b(e,H("/api/merchant/payments",{limit:r.limit,startingAfter:r.startingAfter,createdAfter:r.createdAfter,createdBefore:r.createdBefore,authorizationId:r.authorizationId,status:r.status}),n,i=>$(i,O))},listPaymentAuthorizations(r={}){return b(e,H("/api/merchant/payment-authorizations",{limit:r.limit,startingAfter:r.startingAfter,userLinkRef:r.userLinkRef,status:r.status}),n,i=>$(i,ce))},createRefund(r){let i={paymentId:r.paymentId};return r.amount!==void 0&&(i.amount=r.amount),r.reason!==void 0&&(i.reason=r.reason),r.merchantRefundRef!==void 0&&(i.merchantRefundRef=r.merchantRefundRef),R(e,"/api/merchant/refunds",i,n,q,{"Idempotency-Key":r.idempotencyKey},[402])},getRefund(r){return b(e,`/api/merchant/refunds/${encodeURIComponent(r)}`,n,q)},listRefunds(r={}){return b(e,H("/api/merchant/refunds",{limit:r.limit,startingAfter:r.startingAfter,paymentId:r.paymentId}),n,i=>$(i,q))},createWebhookEndpoint(r){return R(e,"/api/merchant/webhook-endpoints",{url:r.url,enabledEvents:r.enabledEvents},n,oe)},listWebhookEndpoints(){return b(e,"/api/merchant/webhook-endpoints",n,r=>{let y=g(r).data;if(!Array.isArray(y))throw new Error("expected data array");return y.map(K)})},getWebhookEndpoint(r){return b(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n,K)},deleteWebhookEndpoint(r){return ae(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n)},rotateWebhookSecret(r){return R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}/rotate-secret`,{},n,oe)},getDevCapabilities(){return N(e,"getDevCapabilities"),b(e,"/api/dev/capabilities",n,Xe)},fundDevUser(r){return N(e,"fundDevUser"),te(r.userLinkRef),ne(r.amount),re(r.idempotencyKey),R(e,"/api/dev/faucet/usdc",{userLinkRef:r.userLinkRef,amount:r.amount},n,nt,{"Idempotency-Key":r.idempotencyKey})},simulateDevCharge(r){return N(e,"simulateDevCharge"),te(r.userLinkRef),r.cardRef!==void 0&&_(r.cardRef,"card_","cardRef"),ne(r.amount),We(r.scenario),r.merchantReference!==void 0&&(typeof r.merchantReference!="string"||r.merchantReference.length>120)&&f("merchantReference must not exceed 120 characters"),re(r.idempotencyKey),R(e,"/api/dev/simulate/charge",{userLinkRef:r.userLinkRef,...r.cardRef===void 0?{}:{cardRef:r.cardRef},amount:r.amount,scenario:r.scenario,...r.merchantReference===void 0?{}:{merchantReference:r.merchantReference}},n,se,{"Idempotency-Key":r.idempotencyKey})},getDevSimulation(r){return N(e,"getDevSimulation"),_(r,"sim_","simulationId"),b(e,`/api/dev/simulations/${encodeURIComponent(r)}`,n,se)},sendWebhookTestDelivery(r){return De(e),Fe(r.webhookEndpointId),r.message!==void 0&&(typeof r.message!="string"||r.message.length>120)&&f("webhook test message must not exceed 120 characters"),R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r.webhookEndpointId)}/test-delivery`,r.message===void 0?{}:{message:r.message},n,rt)}}}var Me=new Set(["declined","succeeded","paid_via_coverage","failed","canceled"]);function ge(t){return Me.has(t)}async function xe(t,e,n={}){let a=Math.max(0,n.initialIntervalMs??1e3),o=Math.max(a,n.maxIntervalMs??8e3),s=n.backoffFactor??1.5,d=n.timeoutMs??3e5,u=n.signal,m=Date.now()+d,p=a,r;for(;;){Le(u);let i=await t();if(i.status!==r&&(r=i.status,e(i)),ge(i.status))return i;let y=m-Date.now();if(y<=0)return i;await Ue(Math.min(p,y),u),p=Math.min(p*s,o)}}function Le(t){if(t?.aborted)throw new S("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1})}function Ue(t,e){return new Promise((n,a)=>{let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new S("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1}))};if(e){if(e.aborted){clearTimeout(o),s();return}e.addEventListener("abort",s,{once:!0})}})}var Ne=Object.freeze(["dev","production","sandbox"]);function Oe(t){t.appId||f("appId is required"),t.clientId||f("clientId is required"),t.clientSecret||f("clientSecret is required");let e=t.environment;(e===void 0||!Ne.includes(e))&&f("environment is required and must be 'dev', 'production', or 'sandbox' ('sandbox' is the documented public test environment name and targets the same dev endpoints \u2014 ADR-0077). 'staging' and the former 'custom' selector are retired: pass explicit apiBaseUrl and hostedConnectUrl overrides (valid with any environment) for a local, private, or staging deployment. There is no implicit default; the legacy production fallback over /api/external/* routes was removed. See https://docs.facto.to/reference/sdk"),t.transport!==void 0&&t.fetch!==void 0&&f("provide either transport or fetch, not both"),t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0)&&f("timeoutMs must be a positive safe integer");let n=t.apiBaseUrl?v(t.apiBaseUrl,F,"apiBaseUrl",!1):void 0,a=t.hostedConnectUrl?v(t.hostedConnectUrl,E,"hostedConnectUrl",!0):void 0;n!==void 0&&a!==void 0&&n!==a&&f("apiBaseUrl and hostedConnectUrl target different Facto environments");let o=e,s=G(o);for(let p of[n,a])p!==void 0&&p!==s&&f("environment selector conflicts with a published Facto endpoint");let d=j(t.apiBaseUrl??F[s]),u=j(t.hostedConnectUrl??E[s]),m=v(d,F,"apiBaseUrl",!1);return v(u,E,"hostedConnectUrl",!0),ze(t.clientId,m),{appId:t.appId,clientId:t.clientId,clientSecret:t.clientSecret,environment:o,apiBaseUrl:d,hostedConnectUrl:u,transport:t.transport??t.fetch??((p,r)=>globalThis.fetch(p,r)),...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.retry===void 0?{}:{retry:t.retry},...t.signal===void 0?{}:{signal:t.signal}}}function N(t,e){G(t.environment)!=="dev"&&f(`${e} is available only in the sandbox/dev environment`)}function De(t){G(t.environment)!=="dev"&&f("sendWebhookTestDelivery is available only in the sandbox/dev environment")}function _(t,e,n){(typeof t!="string"||!new RegExp(`^${e}[A-Za-z0-9_-]+$`).test(t))&&f(`${n} must be an opaque ${e} reference`)}function te(t){_(t,"ul_","userLinkRef")}function Fe(t){(typeof t!="string"||!/^we_[A-Za-z0-9]+$/.test(t))&&f("webhookEndpointId must be an opaque we_ reference")}function ne(t){(typeof t!="object"||t===null||t.currency!=="USDC"||typeof t.amount!="string"||!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(t.amount))&&f("Dev amount must be a USDC decimal with at most six fractional digits")}function We(t){(typeof t!="string"||!he.includes(t))&&f("unknown Dev simulation scenario")}function re(t){(typeof t!="string"||t.trim()!==t||t.length<16||t.length>255)&&f("idempotencyKey must be 16 to 255 non-whitespace-trimmed characters")}function ze(t,e){let n=e==="dev",a=e==="production";t.startsWith("dev_")&&e!==void 0&&!n&&f("a dev credential can target only the sandbox/dev environment"),(n||a)&&(t.startsWith("staging_")||t.startsWith("test_")||t.startsWith("lab_")||t.startsWith("sandbox_"))&&f("internal or legacy (staging_/test_/lab_/sandbox_) credentials cannot target a published Facto environment")}function v(t,e,n,a){let o;try{o=new URL(t)}catch{f(`${n} must be an absolute URL`)}let s=o.hostname.toLowerCase().replace(/\.$/,"");for(let d of["dev","production"]){let u=new URL(e[d]);if(s!==u.hostname.toLowerCase())continue;let m=o.pathname==="/"||a&&o.pathname==="/connect";return(o.origin!==u.origin||o.username!==""||o.password!==""||!m||o.search!==""||o.hash!=="")&&f(`${n} is not the exact published ${d} endpoint`),d}}async function R(t,e,n,a,o,s={},d=[]){let u=await ye(t,async()=>{let m=await Z(t,`${t.apiBaseUrl}${e}`,{method:"POST",headers:{authorization:a,"content-type":"application/json",...s},body:JSON.stringify(n)});if(!m.ok&&!d.includes(m.status))throw await Y(m);return m},s["Idempotency-Key"]!==void 0);try{return o(await u.json())}catch(m){throw new S("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:m})}}async function b(t,e,n,a){let o=await ye(t,async()=>{let s=await Z(t,`${t.apiBaseUrl}${e}`,{method:"GET",headers:{authorization:n}});if(!s.ok)throw await Y(s);return s},!0);try{return a(await o.json())}catch(s){throw new S("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:s})}}async function ae(t,e,n){let a=await Z(t,`${t.apiBaseUrl}${e}`,{method:"DELETE",headers:{authorization:n}});if(!a.ok)throw await Y(a)}async function Y(t){return new S("FACTO_ENGINE_REQUEST_FAILED",`Facto Engine request failed with status ${t.status}`,{retryable:t.status===429||t.status>=500,status:t.status,details:await Nt(t),retryAfterSeconds:Te(t)})}function ye(t,e,n){return n?me(e,{...t.retry,signal:t.signal??t.retry?.signal}):e()}function Z(t,e,n){return t.timeoutMs===void 0?t.transport(e,{...n,signal:t.signal}):He(t,e,n)}function He(t,e,n){let a=new AbortController,o=()=>a.abort();return t.signal?.aborted?Promise.reject(new S("FACTO_REQUEST_ABORTED","Facto Engine request aborted",{retryable:!1})):(t.signal?.addEventListener("abort",o,{once:!0}),new Promise((s,d)=>{let u=setTimeout(()=>{a.abort(),d(new S("FACTO_REQUEST_ABORTED","Facto Engine request timed out",{retryable:!1}))},t.timeoutMs);t.transport(e,{...n,signal:a.signal}).then(s,d).finally(()=>{clearTimeout(u),t.signal?.removeEventListener("abort",o)})}))}function H(t,e){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))s!==void 0&&s!==""&&n.set(o,String(s));let a=n.toString();return a?`${t}?${a}`:t}function $(t,e){let n=g(t),a=n.data;if(!Array.isArray(a))throw new Error("expected data array");return{data:a.map(e),hasMore:P(n,"hasMore")}}var $e=["pending","succeeded","failed"],qe=["requested_by_customer","duplicate","fraudulent","other"];function Ve(t,e){let n=t[e];if(typeof n!="string"||!$e.includes(n))throw new Error(`expected refund status at ${e}`);return n}function Be(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||!qe.includes(n))throw new Error(`expected refund reason at ${e}`);return n}}function q(t){let e=g(t),n=Be(e,"reason"),a=A(e,"merchantRefundRef");return{refundId:c(e,"refundId"),paymentId:c(e,"paymentId"),status:Ve(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),...n===void 0?{}:{reason:n},...a===void 0?{}:{merchantRefundRef:a},createdAt:c(e,"createdAt")}}var Je=["user_link.revoked","payment_authorization.activated","payment_authorization.updated","payment_authorization.revoked","checkout_session.completed","checkout_session.expired","payment.succeeded","payment.failed","refund.succeeded","refund.failed"];function Ke(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected event-type array at ${e}`);return n.map(a=>{if(typeof a!="string"||!Je.includes(a))throw new Error(`unknown webhook event type: ${String(a)}`);return a})}function K(t){let e=g(t),n=e.status;if(n!=="enabled"&&n!=="disabled")throw new Error("expected webhook endpoint status");return{webhookEndpointId:c(e,"webhookEndpointId"),url:c(e,"url"),enabledEvents:Ke(e,"enabledEvents"),status:n,createdAt:c(e,"createdAt")}}function oe(t){let e=K(t),n=g(t);return{...e,secret:c(n,"secret")}}var W=["fixtures","synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"],je=["unavailable","degraded","ready"],Ge=["contract","implemented","deployed","verified"],he=["approved","declined_setup","declined_limit","payment_failed"],Ye=["pre_admission","onchain_test_assets"],Ze=["accepted","processing","succeeded","failed","declined"],Qe=["accepted","broadcast","confirmed","failed"];function Xe(t){let e=g(t),n=e.capabilities;if(!Array.isArray(n)||n.length!==W.length)throw new Error("expected exactly six Dev capabilities");let a=n.map(et),o=new Set(a.map(s=>s.name));if(o.size!==W.length)throw new Error("expected each Dev capability exactly once");for(let s of W)if(!o.has(s))throw new Error(`missing Dev capability: ${s}`);return{environment:x(e,"environment","dev"),contractVersion:x(e,"contractVersion","2026-07-09"),capabilities:a,checkedAt:c(e,"checkedAt")}}function et(t){let e=g(t),n=C(e,"name",W,"Dev capability name"),a=C(e,"status",je,"Dev capability status"),o=C(e,"evidenceLevel",Ge,"Dev evidence level"),s=w(e,"reasonCode"),d=w(e,"verifiedAt");if(a==="ready"&&(o!=="verified"||d===null))throw new Error("ready Dev capability requires verified evidence");let u=at(e,"limits");return{name:n,status:a,evidenceLevel:o,...s===void 0?{}:{reasonCode:s},...d===void 0?{}:{verifiedAt:d},...u===void 0?{}:{limits:u}}}function tt(t){let e=g(t),n=c(e,"amount");if(!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(n))throw new Error("expected Dev USDC decimal amount");return{amount:n,currency:x(e,"currency","USDC")}}function nt(t){let e=g(t);return{faucetTransferId:M(e,"faucetTransferId","sft_"),userLinkRef:M(e,"userLinkRef","ul_"),amount:tt(e.amount),status:C(e,"status",Qe,"Dev faucet status"),createdAt:c(e,"createdAt")}}function se(t){let e=g(t);return{simulationId:M(e,"simulationId","sim_"),scenario:C(e,"scenario",he,"Dev scenario"),executionMode:C(e,"executionMode",Ye,"Dev execution mode"),status:C(e,"status",Ze,"Dev simulation status"),reasonCode:V(e,"reasonCode"),authorizationRef:V(e,"authorizationRef"),chargeRef:V(e,"chargeRef"),createdAt:c(e,"createdAt"),updatedAt:c(e,"updatedAt")}}function rt(t){let e=g(t);return{eventId:ie(e,"eventId","evt_"),deliveryId:ie(e,"deliveryId","wd_"),status:x(e,"status","queued"),createdAt:c(e,"createdAt")}}function at(t,e){if(t[e]===void 0)return;let n=g(t[e]);for(let a of Object.values(n))if(a!==null&&typeof a!="string"&&typeof a!="number"&&typeof a!="boolean")throw new Error(`expected scalar Dev limit at ${e}`);return n}function M(t,e,n){let a=c(t,e);if(!new RegExp(`^${n}[A-Za-z0-9_-]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function ie(t,e,n){let a=c(t,e);if(!new RegExp(`^${n}[A-Za-z0-9]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function ot(t,e){return e.userLinkRef===void 0&&e.factoServerWalletAddress===void 0&&f("payment readiness requires userLinkRef, factoServerWalletAddress, or both"),e.userLinkRef!==void 0&&_(e.userLinkRef,"ul_","userLinkRef"),e.factoServerWalletAddress!==void 0&&typeof e.factoServerWalletAddress!="string"&&f("factoServerWalletAddress must be a string"),{...e.userLinkRef===void 0?{}:{userLinkRef:e.userLinkRef},...e.factoServerWalletAddress===void 0?{}:{app_id:t.appId,facto_server_wallet_address:e.factoServerWalletAddress}}}function k(t,e){let n=t[e];if(n==null)return n;if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string or null at ${e}`);return n}function st(t){let e=g(t),n=k(e,"cardRef"),a=k(e,"factoUserId"),o=k(e,"factoServerWalletAddress");if(n!=null&&(_(n,"card_","cardRef"),a!=null||o!=null))throw new Error("synthetic Dev links must not expose canonical identity");return{appId:c(e,"appId"),userLinkRef:M(e,"userLinkRef","ul_"),grantStatus:c(e,"grantStatus"),pipelineReady:P(e,"pipelineReady"),scopes:Ut(e,"scopes"),...n===void 0?{}:{cardRef:n},...a===void 0?{}:{factoUserId:a},...o===void 0?{}:{factoServerWalletAddress:o}}}function it(t){let e=g(t),n=P(e,"pipelineReady"),a=e.notReadyReason,o=a==null?a:C(e,"notReadyReason",ee,"payment readiness not-ready reason");if(n&&o!==void 0&&o!==null)throw new Error("expected notReadyReason only when pipelineReady is false");let s=k(e,"factoUserId"),d=k(e,"factoServerWalletAddress");return{appId:c(e,"appId"),userLinkRef:M(e,"userLinkRef","ul_"),selectedPipelineId:c(e,"selectedPipelineId"),chainId:Se(e,"chainId"),protocolId:c(e,"protocolId"),assetSymbol:c(e,"assetSymbol"),spendMode:c(e,"spendMode"),pipelineReady:n,...o===void 0?{}:{notReadyReason:o},...s===void 0?{}:{factoUserId:s},...d===void 0?{}:{factoServerWalletAddress:d}}}function dt(t){let e=g(t);return{sessionId:c(e,"sessionId"),checkoutUrl:c(e,"checkoutUrl"),status:x(e,"status","pending"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:w(e,"orderRef")}}function ct(t){let e=g(t);return{sessionId:c(e,"sessionId"),status:Et(e,"status"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:w(e,"orderRef"),chargeId:w(e,"chargeId"),confirmedAt:w(e,"confirmedAt")}}function de(t){let e=g(t),n=A(e,"mandateId"),a=A(e,"userLinkRef");return{sessionId:c(e,"sessionId"),authorizationUrl:c(e,"authorizationUrl"),status:kt(e,"status"),...n===void 0?{}:{mandateId:n},...a===void 0?{}:{userLinkRef:a},expiresAt:c(e,"expiresAt"),state:c(e,"state")}}function ce(t){let e=g(t),n=A(e,"expiresAt");return{mandateId:c(e,"mandateId"),appId:c(e,"appId"),status:Tt(e,"status"),allowedUseCases:Lt(e,"allowedUseCases"),limits:ht(e.limits),paymentPath:Ct(e.paymentPath),createdAt:c(e,"createdAt"),...n===void 0?{}:{expiresAt:n}}}var ut="direct",lt="defaultPaymentOptionId";function mt(t){let e=g(t);Re(e,"payment options");let n=e.paymentOptions;if(!Array.isArray(n))throw new Error("expected paymentOptions array");let a=n.map(gt).filter(d=>d.settlementPath===ut),o=St(e,lt),s=ft(a,o);return{paymentOptions:a,...s===void 0?{}:{selectedPaymentOptionId:s}}}function ft(t,e){return e!==void 0&&t.some(a=>a.paymentOptionId===e)?e:(t.find(a=>a.ready)??t[0])?.paymentOptionId}function pt(t){let e=A(t,"settlementPath"),n=A(t,"spendMode"),a=e??n;if(a===void 0)throw new Error("expected settlementPath or the deprecated spendMode on a payment option");return{settlementPath:a,spendMode:n??a}}function gt(t){let e=g(t);Re(e,"payment option");let n=A(e,"blockingReason"),a=c(e,"assetSymbol"),o=c(e,"chainLabel"),s=c(e,"protocolLabel"),{settlementPath:d,spendMode:u}=pt(e);return{paymentOptionId:Ce(e,"paymentOptionId"),label:yt({assetSymbol:a,protocolLabel:s,chainLabel:o},c(e,"label")),ready:P(e,"ready"),isDefault:P(e,"isDefault"),chainId:Se(e,"chainId"),chainLabel:o,protocolLabel:s,assetSymbol:a,spendMode:u,settlementPath:d,...n===void 0?{}:{blockingReason:n}}}function yt(t,e){let n=[t.assetSymbol,t.protocolLabel,t.chainLabel].map(a=>a.trim()).filter(a=>a.length>0);return n.length>0?n.join(" \xB7 "):e}function O(t){let e=g(t),n=A(e,"chargeId"),a=A(e,"txHash"),o=xt(e,"declineReason"),s=bt(e,"finalityEtaSeconds"),d=A(e,"terminalAt"),u=A(e,"updatedAt");return{paymentId:c(e,"paymentId"),mandateId:c(e,"mandateId"),merchantPaymentRef:c(e,"merchantPaymentRef"),status:Mt(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),useCase:wt(e,"useCase"),...n===void 0?{}:{chargeId:n},...a===void 0?{}:{txHash:a},...o===void 0?{}:{declineReason:o},...s===void 0?{}:{finalityEtaSeconds:s},...d===void 0?{}:{terminalAt:d},createdAt:c(e,"createdAt"),...u===void 0?{}:{updatedAt:u}}}function ht(t){let e=g(t);return{perTxAmount:c(e,"perTxAmount"),periodAmount:c(e,"periodAmount"),period:Pt(e,"period")}}function Ct(t){let e=g(t),n=A(e,"blockingReason");return{ready:P(e,"ready"),summary:c(e,"summary"),...n===void 0?{}:{blockingReason:n}}}function g(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("expected object");return t}function c(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}function A(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}}function Ce(t,e){let n=c(t,e);if(!n.startsWith("fpo_"))throw new Error(`expected opaque Facto payment option id at ${e}`);return n}function St(t,e){if(!(t[e]===void 0||t[e]===null))return Ce(t,e)}function x(t,e,n){if(t[e]!==n)throw new Error(`expected ${n} at ${e}`);return n}function P(t,e){let n=t[e];if(typeof n!="boolean")throw new Error(`expected boolean at ${e}`);return n}function Se(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}function bt(t,e){let n=t[e];if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}}var Rt=["pending","charged","expired","cancelled"],be=["immediate","recurring","top_up","metered"],At=["daily","weekly","monthly"],It=["pending","active","paused","revoked","expired","suspended"],_t=["created","authorized","declined","expired"],vt=["accepted","declined","charging","finalizing","succeeded","paid_via_coverage","failed","canceled"];function Et(t,e){let n=t[e];if(typeof n!="string"||!Rt.includes(n))throw new Error(`expected checkout status at ${e}`);return n}function wt(t,e){return C(t,e,be,"mandate use case")}function Pt(t,e){return C(t,e,At,"mandate limit period")}function Tt(t,e){return C(t,e,It,"mandate status")}function kt(t,e){return C(t,e,_t,"mandate authorization status")}function Mt(t,e){return C(t,e,vt,"mandate payment status")}function xt(t,e){if(t[e]!==void 0)return C(t,e,X,"mandate decline reason")}function Lt(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected mandate use case array at ${e}`);return n.map(a=>{if(typeof a!="string"||!be.includes(a))throw new Error(`expected mandate use case array at ${e}`);return a})}function C(t,e,n,a){let o=t[e];if(typeof o!="string"||!n.includes(o))throw new Error(`expected ${a} at ${e}`);return o}function w(t,e){let n=t[e];if(n==null)return null;if(typeof n!="string")throw new Error(`expected string or null at ${e}`);return n}function V(t,e){let n=t[e];if(n===null)return null;if(typeof n!="string")throw new Error(`expected required string or null at ${e}`);return n}function Ut(t,e){let n=t[e];if(!Array.isArray(n)||n.some(a=>typeof a!="string"))throw new Error(`expected string array at ${e}`);return n}function Re(t,e){let a=["userId","factoUserId","cardId","routeId","vaultKind","serverWallet","factoServerWalletAddress","pathSnapshot","paymentPathSnapshot","pipelineId","selectedPipelineId","paymentRouteId","routeSelector"].find(o=>t[o]!==void 0);if(a)throw new Error(`unsafe ${e} field: ${a}`)}async function Nt(t){try{return await t.json()}catch{return await t.text().catch(()=>null)}}function j(t){return t.replace(/\/+$/,"")}function f(t){throw new S("FACTO_CONFIG_INVALID",t,{retryable:!1})}function Ot(t){let e=globalThis.btoa;if(e)return e(t);let n=globalThis.Buffer;if(n)return n.from(t).toString("base64");f("No base64 encoder is available in this runtime")}function Dt(t,e,n=Math.floor(Date.now()/1e3)){e||f("webhook secret is required"),(!Number.isSafeInteger(n)||n<0)&&f("webhook timestamp must be a non-negative safe integer");let a=(0,L.createHmac)("sha256",e).update(`${n}.`).update(t).digest("hex");return`t=${n},v1=${a}`}function Ft(t,e,n,a=300){n||f("webhook secret is required");let o=e.split(",").map(m=>m.trim()),s,d=[];for(let m of o){let p=m.indexOf("=");if(p===-1)continue;let r=m.slice(0,p),i=m.slice(p+1);r==="t"?s=Number(i):r==="v1"&&d.push(i)}if(s===void 0||!Number.isFinite(s)||Math.abs(Date.now()/1e3-s)>a||d.length===0)return!1;let u=(0,L.createHmac)("sha256",n).update(`${s}.`).update(t).digest();return d.some(m=>{let p;try{p=Buffer.from(m,"hex")}catch{return!1}return p.length===u.length&&(0,L.timingSafeEqual)(p,u)})}var l=class extends Error{code;details;constructor(e,n,a={}){super(n),this.name="FactoConnectHintError",this.code=e,this.details=a.details}},Wt="facto";async function zt(t){if(t===null||typeof t!="object")throw new l("FACTO_HINT_INPUT_INVALID","verifyFactoCardProgramConnectHint requires an input object");let e=J(t.connectHint,"connectHint"),n=J(t.audience,"audience"),a=t.issuer===void 0?Wt:J(t.issuer,"issuer"),o=Gt(t.clockToleranceSeconds),s=Math.floor(Yt(t.now)/1e3),{headerB64:d,payloadB64:u,signature:m}=Ht(e),p=Q(ue(d,"header"),"FACTO_HINT_MALFORMED","connect hint header");if(p.alg!=="EdDSA")throw new l("FACTO_HINT_UNSUPPORTED_ALG","connect hint JWS alg must be EdDSA",{details:{alg:p.alg}});let r=typeof p.kid=="string"?p.kid:void 0,i=await $t(t.jwks),y=Jt(i,r),U=Qt(`${d}.${u}`);if(!await Kt(U,m,y))throw new l("FACTO_HINT_SIGNATURE_INVALID","connect hint signature does not verify against the Facto JWKS");let I=jt(ue(u,"payload"));if(I.iss!==a)throw new l("FACTO_HINT_ISSUER_MISMATCH","connect hint issuer mismatch",{details:{expected:a,actual:I.iss}});if(I.aud!==n)throw new l("FACTO_HINT_AUDIENCE_MISMATCH","connect hint audience mismatch",{details:{expected:n,actual:I.aud}});if(s>I.exp+o)throw new l("FACTO_HINT_EXPIRED","connect hint has expired",{details:{exp:I.exp,now:s}});return{programRef:I.program_ref,pairwiseSubject:I.sub,nonce:I.nonce,expiresAt:new Date(I.exp*1e3).toISOString()}}function Ht(t){let e=t.split(".");if(e.length!==3)throw new l("FACTO_HINT_MALFORMED","connect hint is not a compact JWS (expected three segments)");let[n,a,o]=e;if(!n||!a||!o)throw new l("FACTO_HINT_MALFORMED","connect hint has an empty JWS segment");return{headerB64:n,payloadB64:a,signature:Ae(o,"signature")}}function ue(t,e){let n=new TextDecoder().decode(Ae(t,e));try{return JSON.parse(n)}catch(a){throw new l("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid JSON`,{details:a})}}async function $t(t){if(t==null)throw new l("FACTO_HINT_INPUT_INVALID","jwks is required");return B(typeof t=="function"?await t():typeof t=="string"?await Vt(t):t)}var qt=5e3,D=64*1024;async function Vt(t){let e;try{e=new URL(t)}catch{throw new l("FACTO_HINT_JWKS_INVALID",`JWKS url is not a valid URL: ${t}`)}if(e.protocol!=="https:")throw new l("FACTO_HINT_JWKS_INVALID",`JWKS url must use https: (got ${e.protocol})`,{details:{protocol:e.protocol}});let n=new AbortController,a=setTimeout(()=>n.abort(),qt),o,s;try{try{o=await fetch(t,{method:"GET",headers:{accept:"application/json"},redirect:"follow",signal:n.signal})}catch(u){throw new l("FACTO_HINT_JWKS_INVALID",`failed to fetch Facto JWKS from ${t}`,{details:u})}if(!o.ok)throw new l("FACTO_HINT_JWKS_INVALID",`Facto JWKS request failed with status ${o.status}`,{details:{status:o.status}});let d=Number(o.headers.get("content-length"));if(Number.isFinite(d)&&d>D)throw new l("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${D} bytes`,{details:{contentLength:d}});try{s=await o.text()}catch(u){throw new l("FACTO_HINT_JWKS_INVALID","Facto JWKS response could not be read",{details:u})}}finally{clearTimeout(a)}if(s.length>D)throw new l("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${D} bytes`,{details:{bytes:s.length}});try{return JSON.parse(s)}catch(d){throw new l("FACTO_HINT_JWKS_INVALID","Facto JWKS response was not valid JSON",{details:d})}}function B(t){let e=Q(t,"FACTO_HINT_JWKS_INVALID","JWKS");if(!Array.isArray(e.keys))throw new l("FACTO_HINT_JWKS_INVALID",'JWKS "keys" must be an array');return{keys:e.keys.map(Bt)}}function Bt(t){let e=typeof t=="object"&&t!==null?t:{};return{kty:typeof e.kty=="string"?e.kty:"",crv:typeof e.crv=="string"?e.crv:"",x:typeof e.x=="string"?e.x:"",...typeof e.kid=="string"?{kid:e.kid}:{},...typeof e.alg=="string"?{alg:e.alg}:{},...typeof e.use=="string"?{use:e.use}:{}}}function Jt(t,e){let n=t.keys.filter(a=>a.kty==="OKP"&&a.crv==="Ed25519"&&a.x.length>0);if(n.length===0)throw new l("FACTO_HINT_JWKS_INVALID","Facto JWKS has no usable Ed25519 signing key");if(e!==void 0){let a=n.filter(o=>o.kid===e);if(a.length>0)return a}return n}async function Kt(t,e,n){let a=Xt();for(let o of n){let s;try{s=await a.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:o.x},{name:"Ed25519"},!1,["verify"])}catch{continue}try{if(await a.verify({name:"Ed25519"},s,e,t))return!0}catch{continue}}return!1}function jt(t){let e=Q(t,"FACTO_HINT_CLAIMS_INVALID","connect hint claims");return{iss:T(e,"iss"),aud:T(e,"aud"),sub:T(e,"sub"),program_ref:T(e,"program_ref"),nonce:T(e,"nonce"),iat:le(e,"iat"),exp:le(e,"exp")}}function J(t,e){if(typeof t!="string"||t.length===0)throw new l("FACTO_HINT_INPUT_INVALID",`${e} must be a non-empty string`);return t}function Gt(t){if(t===void 0)return 0;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new l("FACTO_HINT_INPUT_INVALID","clockToleranceSeconds must be a non-negative finite number");return t}function Yt(t){if(t===void 0)return Date.now();if(t instanceof Date){let e=t.getTime();if(Number.isNaN(e))throw new l("FACTO_HINT_INPUT_INVALID","now is an invalid Date");return e}if(typeof t=="number"&&Number.isFinite(t))return t;throw new l("FACTO_HINT_INPUT_INVALID","now must be a Date or unix milliseconds number")}function Q(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new l(e,`${n} must be a JSON object`);return t}function T(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new l("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a non-empty string`);return n}function le(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new l("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a finite number`);return n}function Ae(t,e){if(!/^[A-Za-z0-9_-]*$/.test(t))throw new l("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`);let n=t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4);return Zt(n,e)}function Zt(t,e){let n=globalThis.atob;if(n){let o;try{o=n(t)}catch(d){throw new l("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`,{details:d})}let s=new Uint8Array(o.length);for(let d=0;d<o.length;d+=1)s[d]=o.charCodeAt(d);return s}let a=globalThis.Buffer;if(a)return new Uint8Array(a.from(t,"base64"));throw new l("FACTO_HINT_INPUT_INVALID","No base64 decoder is available in this runtime")}function Qt(t){let e=new TextEncoder().encode(t),n=new Uint8Array(e.length);return n.set(e),n}function Xt(){let t=globalThis.crypto;if(t?.subtle)return t.subtle;throw new l("FACTO_HINT_INPUT_INVALID","Web Crypto (crypto.subtle) is not available in this runtime")}var en=pe;
1
+ "use strict";var H=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var Le=Object.prototype.hasOwnProperty;var Ne=(t,e)=>{for(var n in e)H(t,n,{get:e[n],enumerable:!0})},Ue=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of xe(e))!Le.call(t,o)&&o!==n&&H(t,o,{get:()=>e[o],enumerable:!(a=ke(e,o))||a.enumerable});return t};var Oe=t=>Ue(H({},"__esModule",{value:!0}),t);var ln={};Ne(ln,{FACTO_CONNECT_API_BASE_URLS:()=>F,FACTO_CONNECT_HOSTED_URLS:()=>E,FactoConnectHintError:()=>m,FactoConnectServerError:()=>b,PSP_CAPABILITY_TEMPLATES:()=>ne,PSP_CREDENTIAL_KEYSPACE:()=>ae,PSP_CREDENTIAL_SCOPES:()=>$,PSP_PARTNER_ROLE_TYPE:()=>oe,buildHostedConnectUrl:()=>Re,carriesMoneyVerb:()=>re,createFactoConnectServer:()=>Ae,default:()=>un,factoConnectEnvironmentFromClientId:()=>be,isTerminalMandatePaymentStatus:()=>_e,signWebhookPayload:()=>Kt,subMerchantOf:()=>ie,verifyFactoCardProgramConnectHint:()=>Yt,verifyWebhookSignature:()=>Jt,withServerRetry:()=>Se,withSubMerchant:()=>se});module.exports=Oe(ln);var L=require("node:crypto");var ee=["mandate_inactive","mandate_revoked","mandate_expired","use_case_not_allowed","mandate_limit_exceeded","mandate_period_limit_exceeded","user_limit_exceeded","limit_check_unavailable","payment_path_unavailable","payment_option_not_pinned","idempotency_conflict"];var te=["payment_route_not_provisioned","protocol_config_incomplete"];var ne=["psp_connect_sandbox","psp_mandate_sandbox"],$={psp_connect_sandbox:["readiness.read","authorizations.request"],psp_mandate_sandbox:["readiness.read","authorizations.request","payments.execute","refunds.execute"]};function re(t){return $[t].includes("payments.execute")}var ae={dev:{clientIdPrefix:"dev_pspid_",clientSecretPrefix:"dev_pspsk_"},lab:{clientIdPrefix:"lab_pspid_"}},oe="psp";function se(t,e){return{...t,...e.ref===void 0?{}:{subMerchantRef:e.ref},...e.displayName===void 0?{}:{subMerchantDisplayName:e.displayName}}}function ie(t){return{...t.subMerchantRef==null?{}:{ref:t.subMerchantRef},...t.subMerchantDisplayName==null?{}:{displayName:t.subMerchantDisplayName}}}function z(t){return t==="sandbox"?"dev":t}var F=Object.freeze({dev:"https://dev-api.facto.to",production:"https://api.facto.to"}),E=Object.freeze({dev:"https://dev.facto.to",production:"https://app.facto.to"}),De=Object.freeze({dev:Object.freeze(["dev_mcid_","dev_pspid_","dev_cpid_"]),production:Object.freeze(["mcid_","pspid_","cpid_"])});function be(t){if(typeof t=="string"){for(let e of["dev","production"])for(let n of De[e])if(t.startsWith(n))return e}}var h=Object.freeze({exchangeLinkCode:"/api/merchant/user-links/exchange",paymentCapability:"/api/merchant/payment-readiness",checkoutSessions:"/api/merchant/checkout-sessions",authorizationSessions:"/api/merchant/authorization-sessions",paymentAuthorizations:"/api/merchant/payment-authorizations",paymentOptions:"/api/merchant/payment-options",payments:"/api/merchant/payments"}),b=class extends Error{code;retryable;status;details;retryAfterSeconds;constructor(e,n,a){super(n),this.name="FactoConnectServerError",this.code=e,this.retryable=a.retryable,this.status=a.status,this.details=a.details,this.retryAfterSeconds=a.retryAfterSeconds}};function Fe(t){let e=t.headers.get("retry-after");if(!e)return;let n=Number(e.trim());return Number.isFinite(n)&&n>=0?n:void 0}function We(t,e){return t<=0?Promise.resolve():new Promise((n,a)=>{if(e?.aborted){a(new b("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new b("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};e?.addEventListener("abort",s,{once:!0})})}async function Se(t,e={}){let n=e.maxRetries??2,a=e.baseDelayMs??200,o=e.maxDelayMs??5e3,s=e.respectRetryAfter??!0,d=e.sleep??We,u=0;for(;;)try{return await t()}catch(p){if(!(p instanceof b)||!p.retryable||u>=n)throw p;u+=1;let r=s&&typeof p.retryAfterSeconds=="number"?p.retryAfterSeconds*1e3:void 0,i=Math.min(o,a*2**(u-1)),g=i*.25*Math.random(),N=r??i+g;e.onRetry?.({attempt:u,error:p,delayMs:N}),await d(N,e.signal)}}function Re(t){t.appId||l("appId is required"),t.state||l("state is required"),t.nonce||l("nonce is required"),t.hostedConnectUrl||l("hostedConnectUrl is required and has no implicit default: pass the Hosted Connect origin for the target environment (e.g. FACTO_CONNECT_HOSTED_URLS.dev)");let e=G(t.hostedConnectUrl);v(e,E,"hostedConnectUrl",!0);let n=new URL("/connect",`${e}/`);n.searchParams.set("external_app_id",t.appId),n.searchParams.set("external_state",t.state),n.searchParams.set("external_nonce",t.nonce);let a=new URLSearchParams;t.customerEmail!==void 0&&a.set("customer_email",t.customerEmail),t.customerUsername!==void 0&&a.set("customer_username",t.customerUsername);let o=a.toString();return o&&(n.hash=o),n.toString()}function Ae(t){let e=Be(t),n=`Basic ${Bt(`${e.clientId}:${e.clientSecret}`)}`,a=(r,i)=>R(e,r,{code:i.code,state:i.state,nonce:i.nonce},n,yt),o=(r,i)=>R(e,r,ft(e,i),n,gt),s=(r,i)=>R(e,r,{appId:e.appId,externalCustomerRef:i.externalCustomerRef,requestedUseCases:i.requestedUseCases,defaultLimits:i.defaultLimits,returnUrl:i.returnUrl,state:i.state,...i.customerEmail===void 0?{}:{customerEmail:i.customerEmail},...i.customerUsername===void 0?{}:{customerUsername:i.customerUsername}},n,ye),d=(r,i)=>S(e,`${r}/${encodeURIComponent(i)}`,n,ye),u=(r,i)=>S(e,`${r}/${encodeURIComponent(i)}`,n,ge),p=(r,i)=>{let g={mandateId:i.mandateId,merchantPaymentRef:i.merchantPaymentRef,amount:i.amount,currency:i.currency,useCase:i.useCase};return i.paymentOptionId!==void 0&&(g.paymentOptionId=i.paymentOptionId),i.description!==void 0&&(g.description=i.description),i.metadata!==void 0&&(g.metadata=i.metadata),R(e,r,g,n,O,{"Idempotency-Key":i.idempotencyKey},[402])},y=(r,i)=>S(e,`${r}/${encodeURIComponent(i)}`,n,O);return{createHostedConnectUrl(r){let i=r.hostedConnectUrl??e.hostedConnectUrl;if(r.hostedConnectUrl!==void 0){let g=v(r.hostedConnectUrl,E,"hostedConnectUrl",!0);g!==void 0&&g!==z(e.environment)&&l("hostedConnectUrl conflicts with the configured environment")}return Re({appId:e.appId,state:r.state,nonce:r.nonce,customerEmail:r.customerEmail,customerUsername:r.customerUsername,hostedConnectUrl:i})},exchangeUserLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentReadiness(r){return o(h.paymentCapability,r)},createAuthorizationSession(r){return s(h.authorizationSessions,r)},getAuthorizationSession(r){return d(h.authorizationSessions,r)},getPaymentAuthorization(r){return u(h.paymentAuthorizations,r)},createMerchantPayment(r){return p(h.payments,r)},getMerchantPayment(r){return y(h.payments,r)},exchangeLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentCapability(r){return o(h.paymentCapability,r)},createCheckoutSession(r){return r.userLinkRef!==void 0&&I(r.userLinkRef,"ul_","userLinkRef"),R(e,h.checkoutSessions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{app_id:e.appId,facto_server_wallet_address:r.factoServerWalletAddress},amount:r.amount,asset_symbol:r.assetSymbol,order_ref:r.orderRef,return_url:r.returnUrl},n,ht)},getCheckoutSession(r){return S(e,`${h.checkoutSessions}/${encodeURIComponent(r)}`,n,Ct)},createMandateAuthorizationSession(r){return s(h.authorizationSessions,r)},getMandateAuthorizationSession(r){return d(h.authorizationSessions,r)},getMerchantMandate(r){return u(h.paymentAuthorizations,r)},listPaymentOptions(r){return r.userLinkRef!==void 0&&I(r.userLinkRef,"ul_","userLinkRef"),R(e,h.paymentOptions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{appId:e.appId,grantRef:r.grantRef},...r.amount!==void 0?{amount:r.amount}:{},...r.assetSymbol!==void 0?{assetSymbol:r.assetSymbol}:{}},n,Rt)},createMandatePayment(r){return p(h.payments,r)},getMandatePayment(r){return y(h.payments,r)},onStatus(r,i,g){return He(()=>S(e,`${h.payments}/${encodeURIComponent(r)}`,n,O),i,g)},revokeUserLink(r){return le(e,`/api/merchant/user-links/${encodeURIComponent(r)}`,n)},listMerchantPayments(r={}){return S(e,q("/api/merchant/payments",{limit:r.limit,startingAfter:r.startingAfter,createdAfter:r.createdAfter,createdBefore:r.createdBefore,authorizationId:r.authorizationId,status:r.status}),n,i=>V(i,O))},listPaymentAuthorizations(r={}){return S(e,q("/api/merchant/payment-authorizations",{limit:r.limit,startingAfter:r.startingAfter,userLinkRef:r.userLinkRef,status:r.status}),n,i=>V(i,ge))},createRefund(r){let i={paymentId:r.paymentId};return r.amount!==void 0&&(i.amount=r.amount),r.reason!==void 0&&(i.reason=r.reason),r.merchantRefundRef!==void 0&&(i.merchantRefundRef=r.merchantRefundRef),R(e,"/api/merchant/refunds",i,n,B,{"Idempotency-Key":r.idempotencyKey},[402])},getRefund(r){return S(e,`/api/merchant/refunds/${encodeURIComponent(r)}`,n,B)},listRefunds(r={}){return S(e,q("/api/merchant/refunds",{limit:r.limit,startingAfter:r.startingAfter,paymentId:r.paymentId}),n,i=>V(i,B))},createWebhookEndpoint(r){return R(e,"/api/merchant/webhook-endpoints",{url:r.url,enabledEvents:r.enabledEvents},n,me)},listWebhookEndpoints(){return S(e,"/api/merchant/webhook-endpoints",n,r=>{let g=f(r).data;if(!Array.isArray(g))throw new Error("expected data array");return g.map(Y)})},getWebhookEndpoint(r){return S(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n,Y)},deleteWebhookEndpoint(r){return le(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n)},rotateWebhookSecret(r){return R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}/rotate-secret`,{},n,me)},getDevCapabilities(){return U(e,"getDevCapabilities"),S(e,"/api/dev/capabilities",n,dt)},fundDevUser(r){return U(e,"fundDevUser"),de(r.userLinkRef),ce(r.amount),ue(r.idempotencyKey),R(e,"/api/dev/faucet/usdc",{userLinkRef:r.userLinkRef,amount:r.amount},n,lt,{"Idempotency-Key":r.idempotencyKey})},simulateDevCharge(r){return U(e,"simulateDevCharge"),de(r.userLinkRef),r.cardRef!==void 0&&I(r.cardRef,"card_","cardRef"),ce(r.amount),je(r.scenario),r.merchantReference!==void 0&&(typeof r.merchantReference!="string"||r.merchantReference.length>120)&&l("merchantReference must not exceed 120 characters"),ue(r.idempotencyKey),R(e,"/api/dev/simulate/charge",{userLinkRef:r.userLinkRef,...r.cardRef===void 0?{}:{cardRef:r.cardRef},amount:r.amount,scenario:r.scenario,...r.merchantReference===void 0?{}:{merchantReference:r.merchantReference}},n,pe,{"Idempotency-Key":r.idempotencyKey})},getDevSimulation(r){return U(e,"getDevSimulation"),I(r,"sim_","simulationId"),S(e,`/api/dev/simulations/${encodeURIComponent(r)}`,n,pe)},sendWebhookTestDelivery(r){return Ke(e),Je(r.webhookEndpointId),r.message!==void 0&&(typeof r.message!="string"||r.message.length>120)&&l("webhook test message must not exceed 120 characters"),R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r.webhookEndpointId)}/test-delivery`,r.message===void 0?{}:{message:r.message},n,mt)}}}var ze=new Set(["declined","succeeded","paid_via_coverage","failed","canceled"]);function _e(t){return ze.has(t)}async function He(t,e,n={}){let a=Math.max(0,n.initialIntervalMs??1e3),o=Math.max(a,n.maxIntervalMs??8e3),s=n.backoffFactor??1.5,d=n.timeoutMs??3e5,u=n.signal,p=Date.now()+d,y=a,r;for(;;){$e(u);let i=await t();if(i.status!==r&&(r=i.status,e(i)),_e(i.status))return i;let g=p-Date.now();if(g<=0)return i;await qe(Math.min(y,g),u),y=Math.min(y*s,o)}}function $e(t){if(t?.aborted)throw new b("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1})}function qe(t,e){return new Promise((n,a)=>{let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new b("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1}))};if(e){if(e.aborted){clearTimeout(o),s();return}e.addEventListener("abort",s,{once:!0})}})}var Ve=Object.freeze(["dev","production","sandbox"]);function Be(t){t.appId||l("appId is required"),t.clientId||l("clientId is required"),t.clientSecret||l("clientSecret is required");let e=t.environment;e!==void 0&&!Ve.includes(e)&&l("environment must be 'dev', 'production', or 'sandbox' ('sandbox' is the documented public test environment name and targets the same dev endpoints \u2014 ADR-0077). 'staging' and the former 'custom' selector are retired: pass explicit apiBaseUrl and hostedConnectUrl overrides (valid with any environment) for a local, private, or staging deployment. See https://docs.facto.to/reference/sdk"),t.transport!==void 0&&t.fetch!==void 0&&l("provide either transport or fetch, not both"),t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0)&&l("timeoutMs must be a positive safe integer");let n=t.apiBaseUrl?v(t.apiBaseUrl,F,"apiBaseUrl",!1):void 0,a=t.hostedConnectUrl?v(t.hostedConnectUrl,E,"hostedConnectUrl",!0):void 0;n!==void 0&&a!==void 0&&n!==a&&l("apiBaseUrl and hostedConnectUrl target different Facto environments");let o=be(t.clientId),s=e??o??n??a;s===void 0&&l("environment could not be resolved: pass it explicitly as 'dev', 'production', or 'sandbox' ('sandbox' is the documented public test environment name and targets the same dev endpoints \u2014 ADR-0077). It is normally derived from clientId, but this one carries no published keyspace: dev credentials are issued as dev_mcid_/dev_pspid_/dev_cpid_ and production credentials as mcid_/pspid_/cpid_. Internal (lab_/staging_/test_) and legacy (sandbox_) credentials never derive a published environment. See https://docs.facto.to/reference/sdk");let d=z(s);e!==void 0&&o!==void 0&&o!==d&&l(`environment '${e}' conflicts with the clientId keyspace, which is ${o} material`);for(let r of[n,a])r!==void 0&&r!==d&&l("environment selector conflicts with a published Facto endpoint");let u=G(t.apiBaseUrl??F[d]),p=G(t.hostedConnectUrl??E[d]),y=v(u,F,"apiBaseUrl",!1);return v(p,E,"hostedConnectUrl",!0),Ye(t.clientId,y),{appId:t.appId,clientId:t.clientId,clientSecret:t.clientSecret,environment:s,apiBaseUrl:u,hostedConnectUrl:p,transport:t.transport??t.fetch??((r,i)=>globalThis.fetch(r,i)),...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.retry===void 0?{}:{retry:t.retry},...t.signal===void 0?{}:{signal:t.signal}}}function U(t,e){z(t.environment)!=="dev"&&l(`${e} is available only in the sandbox/dev environment`)}function Ke(t){z(t.environment)!=="dev"&&l("sendWebhookTestDelivery is available only in the sandbox/dev environment")}function I(t,e,n){(typeof t!="string"||!new RegExp(`^${e}[A-Za-z0-9_-]+$`).test(t))&&l(`${n} must be an opaque ${e} reference`)}function de(t){I(t,"ul_","userLinkRef")}function Je(t){(typeof t!="string"||!/^we_[A-Za-z0-9]+$/.test(t))&&l("webhookEndpointId must be an opaque we_ reference")}function ce(t){(typeof t!="object"||t===null||t.currency!=="USDC"||typeof t.amount!="string"||!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(t.amount))&&l("Dev amount must be a USDC decimal with at most six fractional digits")}function je(t){(typeof t!="string"||!ve.includes(t))&&l("unknown Dev simulation scenario")}function ue(t){(typeof t!="string"||t.trim()!==t||t.length<16||t.length>255)&&l("idempotencyKey must be 16 to 255 non-whitespace-trimmed characters")}function Ye(t,e){let n=e==="dev",a=e==="production";t.startsWith("dev_")&&e!==void 0&&!n&&l("a dev credential can target only the sandbox/dev environment"),(n||a)&&(t.startsWith("staging_")||t.startsWith("test_")||t.startsWith("lab_")||t.startsWith("sandbox_"))&&l("internal or legacy (staging_/test_/lab_/sandbox_) credentials cannot target a published Facto environment")}function v(t,e,n,a){let o;try{o=new URL(t)}catch{l(`${n} must be an absolute URL`)}let s=o.hostname.toLowerCase().replace(/\.$/,"");for(let d of["dev","production"]){let u=new URL(e[d]);if(s!==u.hostname.toLowerCase())continue;let p=o.pathname==="/"||a&&o.pathname==="/connect";return(o.origin!==u.origin||o.username!==""||o.password!==""||!p||o.search!==""||o.hash!=="")&&l(`${n} is not the exact published ${d} endpoint`),d}}async function R(t,e,n,a,o,s={},d=[]){let u=await Ie(t,async()=>{let p=await Q(t,`${t.apiBaseUrl}${e}`,{method:"POST",headers:{authorization:a,"content-type":"application/json",...s},body:JSON.stringify(n)});if(!p.ok&&!d.includes(p.status))throw await Z(p);return p},s["Idempotency-Key"]!==void 0);try{return o(await u.json())}catch(p){throw new b("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:p})}}async function S(t,e,n,a){let o=await Ie(t,async()=>{let s=await Q(t,`${t.apiBaseUrl}${e}`,{method:"GET",headers:{authorization:n}});if(!s.ok)throw await Z(s);return s},!0);try{return a(await o.json())}catch(s){throw new b("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:s})}}async function le(t,e,n){let a=await Q(t,`${t.apiBaseUrl}${e}`,{method:"DELETE",headers:{authorization:n}});if(!a.ok)throw await Z(a)}async function Z(t){return new b("FACTO_ENGINE_REQUEST_FAILED",`Facto Engine request failed with status ${t.status}`,{retryable:t.status===429||t.status>=500,status:t.status,details:await Vt(t),retryAfterSeconds:Fe(t)})}function Ie(t,e,n){return n?Se(e,{...t.retry,signal:t.signal??t.retry?.signal}):e()}function Q(t,e,n){return t.timeoutMs===void 0?t.transport(e,{...n,signal:t.signal}):Ge(t,e,n)}function Ge(t,e,n){let a=new AbortController,o=()=>a.abort();return t.signal?.aborted?Promise.reject(new b("FACTO_REQUEST_ABORTED","Facto Engine request aborted",{retryable:!1})):(t.signal?.addEventListener("abort",o,{once:!0}),new Promise((s,d)=>{let u=setTimeout(()=>{a.abort(),d(new b("FACTO_REQUEST_ABORTED","Facto Engine request timed out",{retryable:!1}))},t.timeoutMs);t.transport(e,{...n,signal:a.signal}).then(s,d).finally(()=>{clearTimeout(u),t.signal?.removeEventListener("abort",o)})}))}function q(t,e){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))s!==void 0&&s!==""&&n.set(o,String(s));let a=n.toString();return a?`${t}?${a}`:t}function V(t,e){let n=f(t),a=n.data;if(!Array.isArray(a))throw new Error("expected data array");return{data:a.map(e),hasMore:w(n,"hasMore")}}var Ze=["pending","succeeded","failed"],Qe=["requested_by_customer","duplicate","fraudulent","other"];function Xe(t,e){let n=t[e];if(typeof n!="string"||!Ze.includes(n))throw new Error(`expected refund status at ${e}`);return n}function et(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||!Qe.includes(n))throw new Error(`expected refund reason at ${e}`);return n}}function B(t){let e=f(t),n=et(e,"reason"),a=A(e,"merchantRefundRef");return{refundId:c(e,"refundId"),paymentId:c(e,"paymentId"),status:Xe(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),...n===void 0?{}:{reason:n},...a===void 0?{}:{merchantRefundRef:a},createdAt:c(e,"createdAt")}}var tt=["user_link.revoked","payment_authorization.activated","payment_authorization.updated","payment_authorization.revoked","checkout_session.completed","checkout_session.expired","payment.succeeded","payment.failed","refund.succeeded","refund.failed"];function nt(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected event-type array at ${e}`);return n.map(a=>{if(typeof a!="string"||!tt.includes(a))throw new Error(`unknown webhook event type: ${String(a)}`);return a})}function Y(t){let e=f(t),n=e.status;if(n!=="enabled"&&n!=="disabled")throw new Error("expected webhook endpoint status");return{webhookEndpointId:c(e,"webhookEndpointId"),url:c(e,"url"),enabledEvents:nt(e,"enabledEvents"),status:n,createdAt:c(e,"createdAt")}}function me(t){let e=Y(t),n=f(t);return{...e,secret:c(n,"secret")}}var W=["fixtures","synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"],rt=["unavailable","degraded","ready"],at=["contract","implemented","deployed","verified"],ve=["approved","declined_setup","declined_limit","payment_failed"],ot=["pre_admission","onchain_test_assets"],st=["accepted","processing","succeeded","failed","declined"],it=["accepted","broadcast","confirmed","failed"];function dt(t){let e=f(t),n=e.capabilities;if(!Array.isArray(n)||n.length!==W.length)throw new Error("expected exactly six Dev capabilities");let a=n.map(ct),o=new Set(a.map(s=>s.name));if(o.size!==W.length)throw new Error("expected each Dev capability exactly once");for(let s of W)if(!o.has(s))throw new Error(`missing Dev capability: ${s}`);return{environment:x(e,"environment","dev"),contractVersion:x(e,"contractVersion","2026-07-09"),capabilities:a,checkedAt:c(e,"checkedAt")}}function ct(t){let e=f(t),n=C(e,"name",W,"Dev capability name"),a=C(e,"status",rt,"Dev capability status"),o=C(e,"evidenceLevel",at,"Dev evidence level"),s=P(e,"reasonCode"),d=P(e,"verifiedAt");if(a==="ready"&&(o!=="verified"||d===null))throw new Error("ready Dev capability requires verified evidence");let u=pt(e,"limits");return{name:n,status:a,evidenceLevel:o,...s===void 0?{}:{reasonCode:s},...d===void 0?{}:{verifiedAt:d},...u===void 0?{}:{limits:u}}}function ut(t){let e=f(t),n=c(e,"amount");if(!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(n))throw new Error("expected Dev USDC decimal amount");return{amount:n,currency:x(e,"currency","USDC")}}function lt(t){let e=f(t);return{faucetTransferId:k(e,"faucetTransferId","sft_"),userLinkRef:k(e,"userLinkRef","ul_"),amount:ut(e.amount),status:C(e,"status",it,"Dev faucet status"),createdAt:c(e,"createdAt")}}function pe(t){let e=f(t);return{simulationId:k(e,"simulationId","sim_"),scenario:C(e,"scenario",ve,"Dev scenario"),executionMode:C(e,"executionMode",ot,"Dev execution mode"),status:C(e,"status",st,"Dev simulation status"),reasonCode:K(e,"reasonCode"),authorizationRef:K(e,"authorizationRef"),chargeRef:K(e,"chargeRef"),createdAt:c(e,"createdAt"),updatedAt:c(e,"updatedAt")}}function mt(t){let e=f(t);return{eventId:fe(e,"eventId","evt_"),deliveryId:fe(e,"deliveryId","wd_"),status:x(e,"status","queued"),createdAt:c(e,"createdAt")}}function pt(t,e){if(t[e]===void 0)return;let n=f(t[e]);for(let a of Object.values(n))if(a!==null&&typeof a!="string"&&typeof a!="number"&&typeof a!="boolean")throw new Error(`expected scalar Dev limit at ${e}`);return n}function k(t,e,n){let a=c(t,e);if(!new RegExp(`^${n}[A-Za-z0-9_-]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function fe(t,e,n){let a=c(t,e);if(!new RegExp(`^${n}[A-Za-z0-9]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function ft(t,e){return e.userLinkRef===void 0&&e.factoServerWalletAddress===void 0&&l("payment readiness requires userLinkRef, factoServerWalletAddress, or both"),e.userLinkRef!==void 0&&I(e.userLinkRef,"ul_","userLinkRef"),e.factoServerWalletAddress!==void 0&&typeof e.factoServerWalletAddress!="string"&&l("factoServerWalletAddress must be a string"),{...e.userLinkRef===void 0?{}:{userLinkRef:e.userLinkRef},...e.factoServerWalletAddress===void 0?{}:{app_id:t.appId,facto_server_wallet_address:e.factoServerWalletAddress}}}function M(t,e){let n=t[e];if(n==null)return n;if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string or null at ${e}`);return n}function yt(t){let e=f(t),n=M(e,"cardRef"),a=M(e,"factoUserId"),o=M(e,"factoServerWalletAddress");if(n!=null&&(I(n,"card_","cardRef"),a!=null||o!=null))throw new Error("synthetic Dev links must not expose canonical identity");return{appId:c(e,"appId"),userLinkRef:k(e,"userLinkRef","ul_"),grantStatus:c(e,"grantStatus"),pipelineReady:w(e,"pipelineReady"),scopes:qt(e,"scopes"),...n===void 0?{}:{cardRef:n},...a===void 0?{}:{factoUserId:a},...o===void 0?{}:{factoServerWalletAddress:o}}}function gt(t){let e=f(t),n=w(e,"pipelineReady"),a=e.notReadyReason,o=a==null?a:C(e,"notReadyReason",te,"payment readiness not-ready reason");if(n&&o!==void 0&&o!==null)throw new Error("expected notReadyReason only when pipelineReady is false");let s=M(e,"factoUserId"),d=M(e,"factoServerWalletAddress");return{appId:c(e,"appId"),userLinkRef:k(e,"userLinkRef","ul_"),selectedPipelineId:c(e,"selectedPipelineId"),chainId:Pe(e,"chainId"),protocolId:c(e,"protocolId"),assetSymbol:c(e,"assetSymbol"),spendMode:c(e,"spendMode"),pipelineReady:n,...o===void 0?{}:{notReadyReason:o},...s===void 0?{}:{factoUserId:s},...d===void 0?{}:{factoServerWalletAddress:d}}}function ht(t){let e=f(t);return{sessionId:c(e,"sessionId"),checkoutUrl:c(e,"checkoutUrl"),status:x(e,"status","pending"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:P(e,"orderRef")}}function Ct(t){let e=f(t);return{sessionId:c(e,"sessionId"),status:Ut(e,"status"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:P(e,"orderRef"),chargeId:P(e,"chargeId"),confirmedAt:P(e,"confirmedAt")}}function ye(t){let e=f(t),n=A(e,"mandateId"),a=A(e,"userLinkRef");return{sessionId:c(e,"sessionId"),authorizationUrl:c(e,"authorizationUrl"),status:Wt(e,"status"),...n===void 0?{}:{mandateId:n},...a===void 0?{}:{userLinkRef:a},expiresAt:c(e,"expiresAt"),state:c(e,"state")}}function ge(t){let e=f(t),n=A(e,"expiresAt");return{mandateId:c(e,"mandateId"),appId:c(e,"appId"),status:Ft(e,"status"),allowedUseCases:$t(e,"allowedUseCases"),limits:Et(e.limits),paymentPath:Pt(e.paymentPath),createdAt:c(e,"createdAt"),...n===void 0?{}:{expiresAt:n}}}var bt="direct",St="defaultPaymentOptionId";function Rt(t){let e=f(t);Te(e,"payment options");let n=e.paymentOptions;if(!Array.isArray(n))throw new Error("expected paymentOptions array");let a=n.map(It).filter(d=>d.settlementPath===bt),o=wt(e,St),s=At(a,o);return{paymentOptions:a,...s===void 0?{}:{selectedPaymentOptionId:s}}}function At(t,e){return e!==void 0&&t.some(a=>a.paymentOptionId===e)?e:(t.find(a=>a.ready)??t[0])?.paymentOptionId}function _t(t){let e=A(t,"settlementPath"),n=A(t,"spendMode"),a=e??n;if(a===void 0)throw new Error("expected settlementPath or the deprecated spendMode on a payment option");return{settlementPath:a,spendMode:n??a}}function It(t){let e=f(t);Te(e,"payment option");let n=A(e,"blockingReason"),a=c(e,"assetSymbol"),o=c(e,"chainLabel"),s=c(e,"protocolLabel"),{settlementPath:d,spendMode:u}=_t(e);return{paymentOptionId:Ee(e,"paymentOptionId"),label:vt({assetSymbol:a,protocolLabel:s,chainLabel:o},c(e,"label")),ready:w(e,"ready"),isDefault:w(e,"isDefault"),chainId:Pe(e,"chainId"),chainLabel:o,protocolLabel:s,assetSymbol:a,spendMode:u,settlementPath:d,...n===void 0?{}:{blockingReason:n}}}function vt(t,e){let n=[t.assetSymbol,t.protocolLabel,t.chainLabel].map(a=>a.trim()).filter(a=>a.length>0);return n.length>0?n.join(" \xB7 "):e}function O(t){let e=f(t),n=A(e,"chargeId"),a=A(e,"txHash"),o=Ht(e,"declineReason"),s=Tt(e,"finalityEtaSeconds"),d=A(e,"terminalAt"),u=A(e,"updatedAt");return{paymentId:c(e,"paymentId"),mandateId:c(e,"mandateId"),merchantPaymentRef:c(e,"merchantPaymentRef"),status:zt(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),useCase:Ot(e,"useCase"),...n===void 0?{}:{chargeId:n},...a===void 0?{}:{txHash:a},...o===void 0?{}:{declineReason:o},...s===void 0?{}:{finalityEtaSeconds:s},...d===void 0?{}:{terminalAt:d},createdAt:c(e,"createdAt"),...u===void 0?{}:{updatedAt:u}}}function Et(t){let e=f(t);return{perTxAmount:c(e,"perTxAmount"),periodAmount:c(e,"periodAmount"),period:Dt(e,"period")}}function Pt(t){let e=f(t),n=A(e,"blockingReason");return{ready:w(e,"ready"),summary:c(e,"summary"),...n===void 0?{}:{blockingReason:n}}}function f(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("expected object");return t}function c(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}function A(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}}function Ee(t,e){let n=c(t,e);if(!n.startsWith("fpo_"))throw new Error(`expected opaque Facto payment option id at ${e}`);return n}function wt(t,e){if(!(t[e]===void 0||t[e]===null))return Ee(t,e)}function x(t,e,n){if(t[e]!==n)throw new Error(`expected ${n} at ${e}`);return n}function w(t,e){let n=t[e];if(typeof n!="boolean")throw new Error(`expected boolean at ${e}`);return n}function Pe(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}function Tt(t,e){let n=t[e];if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}}var Mt=["pending","charged","expired","cancelled"],we=["immediate","recurring","top_up","metered"],kt=["daily","weekly","monthly"],xt=["pending","active","paused","revoked","expired","suspended"],Lt=["created","authorized","declined","expired"],Nt=["accepted","declined","charging","finalizing","succeeded","paid_via_coverage","failed","canceled"];function Ut(t,e){let n=t[e];if(typeof n!="string"||!Mt.includes(n))throw new Error(`expected checkout status at ${e}`);return n}function Ot(t,e){return C(t,e,we,"mandate use case")}function Dt(t,e){return C(t,e,kt,"mandate limit period")}function Ft(t,e){return C(t,e,xt,"mandate status")}function Wt(t,e){return C(t,e,Lt,"mandate authorization status")}function zt(t,e){return C(t,e,Nt,"mandate payment status")}function Ht(t,e){if(t[e]!==void 0)return C(t,e,ee,"mandate decline reason")}function $t(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected mandate use case array at ${e}`);return n.map(a=>{if(typeof a!="string"||!we.includes(a))throw new Error(`expected mandate use case array at ${e}`);return a})}function C(t,e,n,a){let o=t[e];if(typeof o!="string"||!n.includes(o))throw new Error(`expected ${a} at ${e}`);return o}function P(t,e){let n=t[e];if(n==null)return null;if(typeof n!="string")throw new Error(`expected string or null at ${e}`);return n}function K(t,e){let n=t[e];if(n===null)return null;if(typeof n!="string")throw new Error(`expected required string or null at ${e}`);return n}function qt(t,e){let n=t[e];if(!Array.isArray(n)||n.some(a=>typeof a!="string"))throw new Error(`expected string array at ${e}`);return n}function Te(t,e){let a=["userId","factoUserId","cardId","routeId","vaultKind","serverWallet","factoServerWalletAddress","pathSnapshot","paymentPathSnapshot","pipelineId","selectedPipelineId","paymentRouteId","routeSelector"].find(o=>t[o]!==void 0);if(a)throw new Error(`unsafe ${e} field: ${a}`)}async function Vt(t){try{return await t.json()}catch{return await t.text().catch(()=>null)}}function G(t){return t.replace(/\/+$/,"")}function l(t){throw new b("FACTO_CONFIG_INVALID",t,{retryable:!1})}function Bt(t){let e=globalThis.btoa;if(e)return e(t);let n=globalThis.Buffer;if(n)return n.from(t).toString("base64");l("No base64 encoder is available in this runtime")}function Kt(t,e,n=Math.floor(Date.now()/1e3)){e||l("webhook secret is required"),(!Number.isSafeInteger(n)||n<0)&&l("webhook timestamp must be a non-negative safe integer");let a=(0,L.createHmac)("sha256",e).update(`${n}.`).update(t).digest("hex");return`t=${n},v1=${a}`}function Jt(t,e,n,a=300){n||l("webhook secret is required");let o=e.split(",").map(p=>p.trim()),s,d=[];for(let p of o){let y=p.indexOf("=");if(y===-1)continue;let r=p.slice(0,y),i=p.slice(y+1);r==="t"?s=Number(i):r==="v1"&&d.push(i)}if(s===void 0||!Number.isFinite(s)||Math.abs(Date.now()/1e3-s)>a||d.length===0)return!1;let u=(0,L.createHmac)("sha256",n).update(`${s}.`).update(t).digest();return d.some(p=>{let y;try{y=Buffer.from(p,"hex")}catch{return!1}return y.length===u.length&&(0,L.timingSafeEqual)(y,u)})}var m=class extends Error{code;details;constructor(e,n,a={}){super(n),this.name="FactoConnectHintError",this.code=e,this.details=a.details}},jt="facto";async function Yt(t){if(t===null||typeof t!="object")throw new m("FACTO_HINT_INPUT_INVALID","verifyFactoCardProgramConnectHint requires an input object");let e=j(t.connectHint,"connectHint"),n=j(t.audience,"audience"),a=t.issuer===void 0?jt:j(t.issuer,"issuer"),o=an(t.clockToleranceSeconds),s=Math.floor(on(t.now)/1e3),{headerB64:d,payloadB64:u,signature:p}=Gt(e),y=X(he(d,"header"),"FACTO_HINT_MALFORMED","connect hint header");if(y.alg!=="EdDSA")throw new m("FACTO_HINT_UNSUPPORTED_ALG","connect hint JWS alg must be EdDSA",{details:{alg:y.alg}});let r=typeof y.kid=="string"?y.kid:void 0,i=await Zt(t.jwks),g=tn(i,r),N=dn(`${d}.${u}`);if(!await nn(N,p,g))throw new m("FACTO_HINT_SIGNATURE_INVALID","connect hint signature does not verify against the Facto JWKS");let _=rn(he(u,"payload"));if(_.iss!==a)throw new m("FACTO_HINT_ISSUER_MISMATCH","connect hint issuer mismatch",{details:{expected:a,actual:_.iss}});if(_.aud!==n)throw new m("FACTO_HINT_AUDIENCE_MISMATCH","connect hint audience mismatch",{details:{expected:n,actual:_.aud}});if(s>_.exp+o)throw new m("FACTO_HINT_EXPIRED","connect hint has expired",{details:{exp:_.exp,now:s}});return{programRef:_.program_ref,pairwiseSubject:_.sub,nonce:_.nonce,expiresAt:new Date(_.exp*1e3).toISOString()}}function Gt(t){let e=t.split(".");if(e.length!==3)throw new m("FACTO_HINT_MALFORMED","connect hint is not a compact JWS (expected three segments)");let[n,a,o]=e;if(!n||!a||!o)throw new m("FACTO_HINT_MALFORMED","connect hint has an empty JWS segment");return{headerB64:n,payloadB64:a,signature:Me(o,"signature")}}function he(t,e){let n=new TextDecoder().decode(Me(t,e));try{return JSON.parse(n)}catch(a){throw new m("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid JSON`,{details:a})}}async function Zt(t){if(t==null)throw new m("FACTO_HINT_INPUT_INVALID","jwks is required");return J(typeof t=="function"?await t():typeof t=="string"?await Xt(t):t)}var Qt=5e3,D=64*1024;async function Xt(t){let e;try{e=new URL(t)}catch{throw new m("FACTO_HINT_JWKS_INVALID",`JWKS url is not a valid URL: ${t}`)}if(e.protocol!=="https:")throw new m("FACTO_HINT_JWKS_INVALID",`JWKS url must use https: (got ${e.protocol})`,{details:{protocol:e.protocol}});let n=new AbortController,a=setTimeout(()=>n.abort(),Qt),o,s;try{try{o=await fetch(t,{method:"GET",headers:{accept:"application/json"},redirect:"follow",signal:n.signal})}catch(u){throw new m("FACTO_HINT_JWKS_INVALID",`failed to fetch Facto JWKS from ${t}`,{details:u})}if(!o.ok)throw new m("FACTO_HINT_JWKS_INVALID",`Facto JWKS request failed with status ${o.status}`,{details:{status:o.status}});let d=Number(o.headers.get("content-length"));if(Number.isFinite(d)&&d>D)throw new m("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${D} bytes`,{details:{contentLength:d}});try{s=await o.text()}catch(u){throw new m("FACTO_HINT_JWKS_INVALID","Facto JWKS response could not be read",{details:u})}}finally{clearTimeout(a)}if(s.length>D)throw new m("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${D} bytes`,{details:{bytes:s.length}});try{return JSON.parse(s)}catch(d){throw new m("FACTO_HINT_JWKS_INVALID","Facto JWKS response was not valid JSON",{details:d})}}function J(t){let e=X(t,"FACTO_HINT_JWKS_INVALID","JWKS");if(!Array.isArray(e.keys))throw new m("FACTO_HINT_JWKS_INVALID",'JWKS "keys" must be an array');return{keys:e.keys.map(en)}}function en(t){let e=typeof t=="object"&&t!==null?t:{};return{kty:typeof e.kty=="string"?e.kty:"",crv:typeof e.crv=="string"?e.crv:"",x:typeof e.x=="string"?e.x:"",...typeof e.kid=="string"?{kid:e.kid}:{},...typeof e.alg=="string"?{alg:e.alg}:{},...typeof e.use=="string"?{use:e.use}:{}}}function tn(t,e){let n=t.keys.filter(a=>a.kty==="OKP"&&a.crv==="Ed25519"&&a.x.length>0);if(n.length===0)throw new m("FACTO_HINT_JWKS_INVALID","Facto JWKS has no usable Ed25519 signing key");if(e!==void 0){let a=n.filter(o=>o.kid===e);if(a.length>0)return a}return n}async function nn(t,e,n){let a=cn();for(let o of n){let s;try{s=await a.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:o.x},{name:"Ed25519"},!1,["verify"])}catch{continue}try{if(await a.verify({name:"Ed25519"},s,e,t))return!0}catch{continue}}return!1}function rn(t){let e=X(t,"FACTO_HINT_CLAIMS_INVALID","connect hint claims");return{iss:T(e,"iss"),aud:T(e,"aud"),sub:T(e,"sub"),program_ref:T(e,"program_ref"),nonce:T(e,"nonce"),iat:Ce(e,"iat"),exp:Ce(e,"exp")}}function j(t,e){if(typeof t!="string"||t.length===0)throw new m("FACTO_HINT_INPUT_INVALID",`${e} must be a non-empty string`);return t}function an(t){if(t===void 0)return 0;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new m("FACTO_HINT_INPUT_INVALID","clockToleranceSeconds must be a non-negative finite number");return t}function on(t){if(t===void 0)return Date.now();if(t instanceof Date){let e=t.getTime();if(Number.isNaN(e))throw new m("FACTO_HINT_INPUT_INVALID","now is an invalid Date");return e}if(typeof t=="number"&&Number.isFinite(t))return t;throw new m("FACTO_HINT_INPUT_INVALID","now must be a Date or unix milliseconds number")}function X(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new m(e,`${n} must be a JSON object`);return t}function T(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new m("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a non-empty string`);return n}function Ce(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new m("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a finite number`);return n}function Me(t,e){if(!/^[A-Za-z0-9_-]*$/.test(t))throw new m("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`);let n=t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4);return sn(n,e)}function sn(t,e){let n=globalThis.atob;if(n){let o;try{o=n(t)}catch(d){throw new m("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`,{details:d})}let s=new Uint8Array(o.length);for(let d=0;d<o.length;d+=1)s[d]=o.charCodeAt(d);return s}let a=globalThis.Buffer;if(a)return new Uint8Array(a.from(t,"base64"));throw new m("FACTO_HINT_INPUT_INVALID","No base64 decoder is available in this runtime")}function dn(t){let e=new TextEncoder().encode(t),n=new Uint8Array(e.length);return n.set(e),n}function cn(){let t=globalThis.crypto;if(t?.subtle)return t.subtle;throw new m("FACTO_HINT_INPUT_INVALID","Web Crypto (crypto.subtle) is not available in this runtime")}var un=Ae;
@@ -1,6 +1,83 @@
1
- import { MandateUseCase, MandateLimitPeriod, ExchangeLinkCodeResponse, PaymentCapabilityRequestProperties, PaymentCapabilityResponse, MandateAuthorizationSessionStatus, MandateStatus, MandatePaymentStatus, MandateDeclineReason } from '@facto-to/engine-wire';
1
+ import { MandatePayment as MandatePayment$1, CreateMandatePaymentRequest as CreateMandatePaymentRequest$1, MandateUseCase, MandateLimitPeriod, ExchangeLinkCodeResponse, PaymentCapabilityRequestProperties, PaymentCapabilityResponse, MandateAuthorizationSessionStatus, MandateStatus, MandatePaymentStatus, MandateDeclineReason } from '@facto-to/engine-wire';
2
2
  export { MandateAuthorizationSessionStatus as MandateAuthorizationStatus, MandateDeclineReason, MandateLimitPeriod, MandatePaymentStatus, MandateStatus, MandateUseCase, PaymentReadinessNotReadyReason } from '@facto-to/engine-wire';
3
3
 
4
+ /**
5
+ * PSP scenario surface (spec 032 FR-021).
6
+ *
7
+ * The wrapper is deliberately thin: there is no per-PSP code anywhere in this
8
+ * package, and everything a PSP sends or receives is a generated
9
+ * `@facto-to/engine-wire` type. What lives here is only what codegen cannot
10
+ * express — the value sets the engine keeps in Rust constants and migration
11
+ * CHECK constraints rather than in `openapi.gen.json`.
12
+ */
13
+
14
+ /** The two reviewed PSP capability templates (spec 032 S3). */
15
+ declare const PSP_CAPABILITY_TEMPLATES: readonly ["psp_connect_sandbox", "psp_mandate_sandbox"];
16
+ type PspCapabilityTemplate = (typeof PSP_CAPABILITY_TEMPLATES)[number];
17
+ /**
18
+ * Credential scopes per template, IN ORDER.
19
+ *
20
+ * Order is part of the contract, not a formatting preference. The engine's
21
+ * `external_app_clients_partner_template_check` compares with `=` and Postgres
22
+ * compares arrays element-wise, so a reordered list is rejected at mint time
23
+ * with a bare `23514` and no explanation. Build request payloads from these
24
+ * arrays rather than assembling scope lists by hand.
25
+ */
26
+ declare const PSP_CREDENTIAL_SCOPES: Record<PspCapabilityTemplate, readonly string[]>;
27
+ /**
28
+ * Which template carries a money verb.
29
+ *
30
+ * FR-003's whole content: the read surface is grantable WITHOUT the ability to
31
+ * move money. `psp_connect_sandbox` carries neither `payments.execute` nor
32
+ * `refunds.execute`.
33
+ */
34
+ declare function carriesMoneyVerb(template: PspCapabilityTemplate): boolean;
35
+ /** Client-id / client-secret prefixes, per environment. */
36
+ declare const PSP_CREDENTIAL_KEYSPACE: {
37
+ readonly dev: {
38
+ readonly clientIdPrefix: "dev_pspid_";
39
+ readonly clientSecretPrefix: "dev_pspsk_";
40
+ };
41
+ readonly lab: {
42
+ readonly clientIdPrefix: "lab_pspid_";
43
+ };
44
+ };
45
+ /** The value `partnerRoleType` carries for a PSP on the consumer projections. */
46
+ declare const PSP_PARTNER_ROLE_TYPE = "psp";
47
+ /**
48
+ * Attach sub-merchant metadata to a payment request (spec 032 FR-011/FR-012).
49
+ *
50
+ * A helper rather than a note in the docs, because the two fields are NOT
51
+ * interchangeable and the difference is invisible from the type — both are
52
+ * `string`:
53
+ *
54
+ * - `ref` is your reconciliation anchor. It rides the payment webhook, so you
55
+ * can reconcile from webhooks without calling back per event.
56
+ * - `displayName` is what the shopper sees on their billing line. It is
57
+ * deliberately absent from webhook payloads: Facto signs those bodies, and a
58
+ * signature must not vouch for a string a third party wrote. Read it from the
59
+ * authenticated payment GET.
60
+ *
61
+ * Neither is an identifier. Facto never keys, joins, groups or deduplicates on
62
+ * `subMerchantRef` — two payments differing only in it resolve the same mandate
63
+ * and the same route.
64
+ */
65
+ declare function withSubMerchant(request: CreateMandatePaymentRequest$1, subMerchant: {
66
+ ref?: string;
67
+ displayName?: string;
68
+ }): CreateMandatePaymentRequest$1;
69
+ /**
70
+ * Read the sub-merchant back off a payment.
71
+ *
72
+ * `displayName` is `undefined` on anything sourced from a webhook and present
73
+ * on an authenticated read — see {@link withSubMerchant}. Reading through this
74
+ * helper keeps that asymmetry in one place instead of at every call site.
75
+ */
76
+ declare function subMerchantOf(payment: MandatePayment$1): {
77
+ ref?: string;
78
+ displayName?: string;
79
+ };
80
+
4
81
  /**
5
82
  * Customer-facing environment vocabulary (ADR-0077): the published Facto
6
83
  * environments are `dev` and `production`, and `'sandbox'` is the documented
@@ -22,19 +99,36 @@ type PublishedFactoConnectEnvironment = 'dev' | 'production';
22
99
  type FactoConnectTransport = (input: string, init?: RequestInit) => Promise<Response>;
23
100
  declare const FACTO_CONNECT_API_BASE_URLS: Readonly<Record<PublishedFactoConnectEnvironment, string>>;
24
101
  declare const FACTO_CONNECT_HOSTED_URLS: Readonly<Record<PublishedFactoConnectEnvironment, string>>;
102
+ /**
103
+ * Read the published environment a client id belongs to, or `undefined` when
104
+ * the id carries no recognized keyspace.
105
+ *
106
+ * `undefined` covers the internal (`lab_`/`staging_`/`test_`) and legacy
107
+ * (`sandbox_`) keyspaces as well as anything unrecognized. Those never derive
108
+ * an environment: an unrecognized id must not silently resolve to production,
109
+ * which is the failure mode the removed implicit default used to cause.
110
+ */
111
+ declare function factoConnectEnvironmentFromClientId(clientId: string): PublishedFactoConnectEnvironment | undefined;
25
112
  interface FactoConnectServerOptions {
26
113
  appId: string;
27
114
  clientId: string;
28
115
  clientSecret: string;
29
116
  /**
30
- * Required. `'sandbox'` (the documented public test environment name) and
117
+ * Optional. `'sandbox'` (the documented public test environment name) and
31
118
  * `'dev'` select the same environment and resolve the same published dev
32
119
  * endpoints; `'production'` resolves the production endpoints. ADR-0077:
33
- * "sandbox naming, dev interface". There is no default: omission throws at
34
- * construction instead of silently targeting production over the retired
35
- * legacy `/api/external/*` routes, and `'staging'` is retired from the
120
+ * "sandbox naming, dev interface". `'staging'` is retired from the
36
121
  * customer-facing vocabulary.
37
122
  *
123
+ * Omit it and the environment is derived from `clientId`'s keyspace —
124
+ * `dev_mcid_`/`dev_pspid_`/`dev_cpid_` resolve the dev endpoints, bare
125
+ * `mcid_`/`pspid_`/`cpid_` resolve production. This is evidence, not a
126
+ * default: an unrecognized client id derives nothing and still throws at
127
+ * construction rather than silently targeting production, which is what the
128
+ * removed implicit fallback used to do. Passing it explicitly is still
129
+ * supported and is checked against the credential, so a mismatch fails at
130
+ * construction.
131
+ *
38
132
  * The former `'custom'` selector is retired. For a local, private, or
39
133
  * staging deployment keep any environment value and pass both explicit
40
134
  * URL overrides, e.g.:
@@ -48,7 +142,7 @@ interface FactoConnectServerOptions {
48
142
  * })
49
143
  * ```
50
144
  */
51
- environment: FactoConnectEnvironment;
145
+ environment?: FactoConnectEnvironment;
52
146
  /**
53
147
  * Explicit endpoint overrides for local, private, or staging deployments.
54
148
  * Valid with any `environment` value and take precedence over the
@@ -637,4 +731,4 @@ declare class FactoConnectHintError extends Error {
637
731
  */
638
732
  declare function verifyFactoCardProgramConnectHint(input: VerifyFactoCardProgramConnectHintInput): Promise<FactoCardProgramConnectHint>;
639
733
 
640
- export { type CheckoutSession, type CheckoutSessionStatus, type CheckoutStatus, type CreateCheckoutSessionInput, type CreateHostedConnectUrlInput, type CreateMandateAuthorizationSessionInput, type CreateMandateAuthorizationSessionRequest, type CreateMandatePaymentInput, type CreateMandatePaymentRequest, type CreateRefundInput, type CreateWebhookEndpointInput, type CursorListFilter, type DevCapabilities, type DevCapability, type DevCapabilityName, type DevCapabilityStatus, type DevEvidenceLevel, type DevFaucetTransfer, type DevMoney, type DevSimulation, type DevSimulationExecutionMode, type DevSimulationScenario, type DevSimulationStatus, type ExchangeLinkCodeInput, type ExchangeLinkCodeResult, FACTO_CONNECT_API_BASE_URLS, FACTO_CONNECT_HOSTED_URLS, type FactoCardProgramConnectHint, type FactoCardProgramConnectJwk, type FactoCardProgramConnectJwks, type FactoCardProgramConnectJwksInput, type FactoConnectEnvironment, FactoConnectHintError, type FactoConnectHintErrorCode, type FactoConnectServerClient, FactoConnectServerError, type FactoConnectServerErrorCode, type FactoConnectServerOptions, type FactoConnectTransport, type FundDevUserInput, type HostedConnectUrlInput, type MandateAuthorizationSession, type MandateLimits, type MandatePayment, type MandatePaymentStatusListener, type MerchantMandate, type MerchantPaymentListFilter, type MerchantPaymentOption, type MerchantPaymentOptions, type MerchantPaymentPathProjection, type OnMandatePaymentStatusOptions, type Page, type PaymentAuthorizationListFilter, type PaymentCapability, type PaymentCapabilityInput, type PaymentOptionsInput, type Refund, type RefundListFilter, type RefundReason, type RefundStatus, type SendWebhookTestDeliveryInput, type ServerRetryOptions, type SimulateDevChargeInput, type VerifyFactoCardProgramConnectHintInput, type WebhookEndpoint, type WebhookEndpointWithSecret, type WebhookEventType, type WebhookTestDeliveryAccepted, buildHostedConnectUrl, createFactoConnectServer, createFactoConnectServer as default, isTerminalMandatePaymentStatus, signWebhookPayload, verifyFactoCardProgramConnectHint, verifyWebhookSignature, withServerRetry };
734
+ export { type CheckoutSession, type CheckoutSessionStatus, type CheckoutStatus, type CreateCheckoutSessionInput, type CreateHostedConnectUrlInput, type CreateMandateAuthorizationSessionInput, type CreateMandateAuthorizationSessionRequest, type CreateMandatePaymentInput, type CreateMandatePaymentRequest, type CreateRefundInput, type CreateWebhookEndpointInput, type CursorListFilter, type DevCapabilities, type DevCapability, type DevCapabilityName, type DevCapabilityStatus, type DevEvidenceLevel, type DevFaucetTransfer, type DevMoney, type DevSimulation, type DevSimulationExecutionMode, type DevSimulationScenario, type DevSimulationStatus, type ExchangeLinkCodeInput, type ExchangeLinkCodeResult, FACTO_CONNECT_API_BASE_URLS, FACTO_CONNECT_HOSTED_URLS, type FactoCardProgramConnectHint, type FactoCardProgramConnectJwk, type FactoCardProgramConnectJwks, type FactoCardProgramConnectJwksInput, type FactoConnectEnvironment, FactoConnectHintError, type FactoConnectHintErrorCode, type FactoConnectServerClient, FactoConnectServerError, type FactoConnectServerErrorCode, type FactoConnectServerOptions, type FactoConnectTransport, type FundDevUserInput, type HostedConnectUrlInput, type MandateAuthorizationSession, type MandateLimits, type MandatePayment, type MandatePaymentStatusListener, type MerchantMandate, type MerchantPaymentListFilter, type MerchantPaymentOption, type MerchantPaymentOptions, type MerchantPaymentPathProjection, type OnMandatePaymentStatusOptions, PSP_CAPABILITY_TEMPLATES, PSP_CREDENTIAL_KEYSPACE, PSP_CREDENTIAL_SCOPES, PSP_PARTNER_ROLE_TYPE, type Page, type PaymentAuthorizationListFilter, type PaymentCapability, type PaymentCapabilityInput, type PaymentOptionsInput, type PspCapabilityTemplate, type Refund, type RefundListFilter, type RefundReason, type RefundStatus, type SendWebhookTestDeliveryInput, type ServerRetryOptions, type SimulateDevChargeInput, type VerifyFactoCardProgramConnectHintInput, type WebhookEndpoint, type WebhookEndpointWithSecret, type WebhookEventType, type WebhookTestDeliveryAccepted, buildHostedConnectUrl, carriesMoneyVerb, createFactoConnectServer, createFactoConnectServer as default, factoConnectEnvironmentFromClientId, isTerminalMandatePaymentStatus, signWebhookPayload, subMerchantOf, verifyFactoCardProgramConnectHint, verifyWebhookSignature, withServerRetry, withSubMerchant };
@@ -1,6 +1,83 @@
1
- import { MandateUseCase, MandateLimitPeriod, ExchangeLinkCodeResponse, PaymentCapabilityRequestProperties, PaymentCapabilityResponse, MandateAuthorizationSessionStatus, MandateStatus, MandatePaymentStatus, MandateDeclineReason } from '@facto-to/engine-wire';
1
+ import { MandatePayment as MandatePayment$1, CreateMandatePaymentRequest as CreateMandatePaymentRequest$1, MandateUseCase, MandateLimitPeriod, ExchangeLinkCodeResponse, PaymentCapabilityRequestProperties, PaymentCapabilityResponse, MandateAuthorizationSessionStatus, MandateStatus, MandatePaymentStatus, MandateDeclineReason } from '@facto-to/engine-wire';
2
2
  export { MandateAuthorizationSessionStatus as MandateAuthorizationStatus, MandateDeclineReason, MandateLimitPeriod, MandatePaymentStatus, MandateStatus, MandateUseCase, PaymentReadinessNotReadyReason } from '@facto-to/engine-wire';
3
3
 
4
+ /**
5
+ * PSP scenario surface (spec 032 FR-021).
6
+ *
7
+ * The wrapper is deliberately thin: there is no per-PSP code anywhere in this
8
+ * package, and everything a PSP sends or receives is a generated
9
+ * `@facto-to/engine-wire` type. What lives here is only what codegen cannot
10
+ * express — the value sets the engine keeps in Rust constants and migration
11
+ * CHECK constraints rather than in `openapi.gen.json`.
12
+ */
13
+
14
+ /** The two reviewed PSP capability templates (spec 032 S3). */
15
+ declare const PSP_CAPABILITY_TEMPLATES: readonly ["psp_connect_sandbox", "psp_mandate_sandbox"];
16
+ type PspCapabilityTemplate = (typeof PSP_CAPABILITY_TEMPLATES)[number];
17
+ /**
18
+ * Credential scopes per template, IN ORDER.
19
+ *
20
+ * Order is part of the contract, not a formatting preference. The engine's
21
+ * `external_app_clients_partner_template_check` compares with `=` and Postgres
22
+ * compares arrays element-wise, so a reordered list is rejected at mint time
23
+ * with a bare `23514` and no explanation. Build request payloads from these
24
+ * arrays rather than assembling scope lists by hand.
25
+ */
26
+ declare const PSP_CREDENTIAL_SCOPES: Record<PspCapabilityTemplate, readonly string[]>;
27
+ /**
28
+ * Which template carries a money verb.
29
+ *
30
+ * FR-003's whole content: the read surface is grantable WITHOUT the ability to
31
+ * move money. `psp_connect_sandbox` carries neither `payments.execute` nor
32
+ * `refunds.execute`.
33
+ */
34
+ declare function carriesMoneyVerb(template: PspCapabilityTemplate): boolean;
35
+ /** Client-id / client-secret prefixes, per environment. */
36
+ declare const PSP_CREDENTIAL_KEYSPACE: {
37
+ readonly dev: {
38
+ readonly clientIdPrefix: "dev_pspid_";
39
+ readonly clientSecretPrefix: "dev_pspsk_";
40
+ };
41
+ readonly lab: {
42
+ readonly clientIdPrefix: "lab_pspid_";
43
+ };
44
+ };
45
+ /** The value `partnerRoleType` carries for a PSP on the consumer projections. */
46
+ declare const PSP_PARTNER_ROLE_TYPE = "psp";
47
+ /**
48
+ * Attach sub-merchant metadata to a payment request (spec 032 FR-011/FR-012).
49
+ *
50
+ * A helper rather than a note in the docs, because the two fields are NOT
51
+ * interchangeable and the difference is invisible from the type — both are
52
+ * `string`:
53
+ *
54
+ * - `ref` is your reconciliation anchor. It rides the payment webhook, so you
55
+ * can reconcile from webhooks without calling back per event.
56
+ * - `displayName` is what the shopper sees on their billing line. It is
57
+ * deliberately absent from webhook payloads: Facto signs those bodies, and a
58
+ * signature must not vouch for a string a third party wrote. Read it from the
59
+ * authenticated payment GET.
60
+ *
61
+ * Neither is an identifier. Facto never keys, joins, groups or deduplicates on
62
+ * `subMerchantRef` — two payments differing only in it resolve the same mandate
63
+ * and the same route.
64
+ */
65
+ declare function withSubMerchant(request: CreateMandatePaymentRequest$1, subMerchant: {
66
+ ref?: string;
67
+ displayName?: string;
68
+ }): CreateMandatePaymentRequest$1;
69
+ /**
70
+ * Read the sub-merchant back off a payment.
71
+ *
72
+ * `displayName` is `undefined` on anything sourced from a webhook and present
73
+ * on an authenticated read — see {@link withSubMerchant}. Reading through this
74
+ * helper keeps that asymmetry in one place instead of at every call site.
75
+ */
76
+ declare function subMerchantOf(payment: MandatePayment$1): {
77
+ ref?: string;
78
+ displayName?: string;
79
+ };
80
+
4
81
  /**
5
82
  * Customer-facing environment vocabulary (ADR-0077): the published Facto
6
83
  * environments are `dev` and `production`, and `'sandbox'` is the documented
@@ -22,19 +99,36 @@ type PublishedFactoConnectEnvironment = 'dev' | 'production';
22
99
  type FactoConnectTransport = (input: string, init?: RequestInit) => Promise<Response>;
23
100
  declare const FACTO_CONNECT_API_BASE_URLS: Readonly<Record<PublishedFactoConnectEnvironment, string>>;
24
101
  declare const FACTO_CONNECT_HOSTED_URLS: Readonly<Record<PublishedFactoConnectEnvironment, string>>;
102
+ /**
103
+ * Read the published environment a client id belongs to, or `undefined` when
104
+ * the id carries no recognized keyspace.
105
+ *
106
+ * `undefined` covers the internal (`lab_`/`staging_`/`test_`) and legacy
107
+ * (`sandbox_`) keyspaces as well as anything unrecognized. Those never derive
108
+ * an environment: an unrecognized id must not silently resolve to production,
109
+ * which is the failure mode the removed implicit default used to cause.
110
+ */
111
+ declare function factoConnectEnvironmentFromClientId(clientId: string): PublishedFactoConnectEnvironment | undefined;
25
112
  interface FactoConnectServerOptions {
26
113
  appId: string;
27
114
  clientId: string;
28
115
  clientSecret: string;
29
116
  /**
30
- * Required. `'sandbox'` (the documented public test environment name) and
117
+ * Optional. `'sandbox'` (the documented public test environment name) and
31
118
  * `'dev'` select the same environment and resolve the same published dev
32
119
  * endpoints; `'production'` resolves the production endpoints. ADR-0077:
33
- * "sandbox naming, dev interface". There is no default: omission throws at
34
- * construction instead of silently targeting production over the retired
35
- * legacy `/api/external/*` routes, and `'staging'` is retired from the
120
+ * "sandbox naming, dev interface". `'staging'` is retired from the
36
121
  * customer-facing vocabulary.
37
122
  *
123
+ * Omit it and the environment is derived from `clientId`'s keyspace —
124
+ * `dev_mcid_`/`dev_pspid_`/`dev_cpid_` resolve the dev endpoints, bare
125
+ * `mcid_`/`pspid_`/`cpid_` resolve production. This is evidence, not a
126
+ * default: an unrecognized client id derives nothing and still throws at
127
+ * construction rather than silently targeting production, which is what the
128
+ * removed implicit fallback used to do. Passing it explicitly is still
129
+ * supported and is checked against the credential, so a mismatch fails at
130
+ * construction.
131
+ *
38
132
  * The former `'custom'` selector is retired. For a local, private, or
39
133
  * staging deployment keep any environment value and pass both explicit
40
134
  * URL overrides, e.g.:
@@ -48,7 +142,7 @@ interface FactoConnectServerOptions {
48
142
  * })
49
143
  * ```
50
144
  */
51
- environment: FactoConnectEnvironment;
145
+ environment?: FactoConnectEnvironment;
52
146
  /**
53
147
  * Explicit endpoint overrides for local, private, or staging deployments.
54
148
  * Valid with any `environment` value and take precedence over the
@@ -637,4 +731,4 @@ declare class FactoConnectHintError extends Error {
637
731
  */
638
732
  declare function verifyFactoCardProgramConnectHint(input: VerifyFactoCardProgramConnectHintInput): Promise<FactoCardProgramConnectHint>;
639
733
 
640
- export { type CheckoutSession, type CheckoutSessionStatus, type CheckoutStatus, type CreateCheckoutSessionInput, type CreateHostedConnectUrlInput, type CreateMandateAuthorizationSessionInput, type CreateMandateAuthorizationSessionRequest, type CreateMandatePaymentInput, type CreateMandatePaymentRequest, type CreateRefundInput, type CreateWebhookEndpointInput, type CursorListFilter, type DevCapabilities, type DevCapability, type DevCapabilityName, type DevCapabilityStatus, type DevEvidenceLevel, type DevFaucetTransfer, type DevMoney, type DevSimulation, type DevSimulationExecutionMode, type DevSimulationScenario, type DevSimulationStatus, type ExchangeLinkCodeInput, type ExchangeLinkCodeResult, FACTO_CONNECT_API_BASE_URLS, FACTO_CONNECT_HOSTED_URLS, type FactoCardProgramConnectHint, type FactoCardProgramConnectJwk, type FactoCardProgramConnectJwks, type FactoCardProgramConnectJwksInput, type FactoConnectEnvironment, FactoConnectHintError, type FactoConnectHintErrorCode, type FactoConnectServerClient, FactoConnectServerError, type FactoConnectServerErrorCode, type FactoConnectServerOptions, type FactoConnectTransport, type FundDevUserInput, type HostedConnectUrlInput, type MandateAuthorizationSession, type MandateLimits, type MandatePayment, type MandatePaymentStatusListener, type MerchantMandate, type MerchantPaymentListFilter, type MerchantPaymentOption, type MerchantPaymentOptions, type MerchantPaymentPathProjection, type OnMandatePaymentStatusOptions, type Page, type PaymentAuthorizationListFilter, type PaymentCapability, type PaymentCapabilityInput, type PaymentOptionsInput, type Refund, type RefundListFilter, type RefundReason, type RefundStatus, type SendWebhookTestDeliveryInput, type ServerRetryOptions, type SimulateDevChargeInput, type VerifyFactoCardProgramConnectHintInput, type WebhookEndpoint, type WebhookEndpointWithSecret, type WebhookEventType, type WebhookTestDeliveryAccepted, buildHostedConnectUrl, createFactoConnectServer, createFactoConnectServer as default, isTerminalMandatePaymentStatus, signWebhookPayload, verifyFactoCardProgramConnectHint, verifyWebhookSignature, withServerRetry };
734
+ export { type CheckoutSession, type CheckoutSessionStatus, type CheckoutStatus, type CreateCheckoutSessionInput, type CreateHostedConnectUrlInput, type CreateMandateAuthorizationSessionInput, type CreateMandateAuthorizationSessionRequest, type CreateMandatePaymentInput, type CreateMandatePaymentRequest, type CreateRefundInput, type CreateWebhookEndpointInput, type CursorListFilter, type DevCapabilities, type DevCapability, type DevCapabilityName, type DevCapabilityStatus, type DevEvidenceLevel, type DevFaucetTransfer, type DevMoney, type DevSimulation, type DevSimulationExecutionMode, type DevSimulationScenario, type DevSimulationStatus, type ExchangeLinkCodeInput, type ExchangeLinkCodeResult, FACTO_CONNECT_API_BASE_URLS, FACTO_CONNECT_HOSTED_URLS, type FactoCardProgramConnectHint, type FactoCardProgramConnectJwk, type FactoCardProgramConnectJwks, type FactoCardProgramConnectJwksInput, type FactoConnectEnvironment, FactoConnectHintError, type FactoConnectHintErrorCode, type FactoConnectServerClient, FactoConnectServerError, type FactoConnectServerErrorCode, type FactoConnectServerOptions, type FactoConnectTransport, type FundDevUserInput, type HostedConnectUrlInput, type MandateAuthorizationSession, type MandateLimits, type MandatePayment, type MandatePaymentStatusListener, type MerchantMandate, type MerchantPaymentListFilter, type MerchantPaymentOption, type MerchantPaymentOptions, type MerchantPaymentPathProjection, type OnMandatePaymentStatusOptions, PSP_CAPABILITY_TEMPLATES, PSP_CREDENTIAL_KEYSPACE, PSP_CREDENTIAL_SCOPES, PSP_PARTNER_ROLE_TYPE, type Page, type PaymentAuthorizationListFilter, type PaymentCapability, type PaymentCapabilityInput, type PaymentOptionsInput, type PspCapabilityTemplate, type Refund, type RefundListFilter, type RefundReason, type RefundStatus, type SendWebhookTestDeliveryInput, type ServerRetryOptions, type SimulateDevChargeInput, type VerifyFactoCardProgramConnectHintInput, type WebhookEndpoint, type WebhookEndpointWithSecret, type WebhookEventType, type WebhookTestDeliveryAccepted, buildHostedConnectUrl, carriesMoneyVerb, createFactoConnectServer, createFactoConnectServer as default, factoConnectEnvironmentFromClientId, isTerminalMandatePaymentStatus, signWebhookPayload, subMerchantOf, verifyFactoCardProgramConnectHint, verifyWebhookSignature, withServerRetry, withSubMerchant };
@@ -1 +1 @@
1
- import{createHmac as ue,timingSafeEqual as Ce}from"node:crypto";var Z=["mandate_inactive","mandate_revoked","mandate_expired","use_case_not_allowed","mandate_limit_exceeded","mandate_period_limit_exceeded","user_limit_exceeded","limit_check_unavailable","payment_path_unavailable","payment_option_not_pinned","idempotency_conflict"];var Q=["payment_route_not_provisioned","protocol_config_incomplete"];function K(t){return t==="sandbox"?"dev":t}var F=Object.freeze({dev:"https://dev-api.facto.to",production:"https://api.facto.to"}),T=Object.freeze({dev:"https://dev.facto.to",production:"https://app.facto.to"}),h=Object.freeze({exchangeLinkCode:"/api/merchant/user-links/exchange",paymentCapability:"/api/merchant/payment-readiness",checkoutSessions:"/api/merchant/checkout-sessions",authorizationSessions:"/api/merchant/authorization-sessions",paymentAuthorizations:"/api/merchant/payment-authorizations",paymentOptions:"/api/merchant/payment-options",payments:"/api/merchant/payments"}),b=class extends Error{code;retryable;status;details;retryAfterSeconds;constructor(e,n,a){super(n),this.name="FactoConnectServerError",this.code=e,this.retryable=a.retryable,this.status=a.status,this.details=a.details,this.retryAfterSeconds=a.retryAfterSeconds}};function Se(t){let e=t.headers.get("retry-after");if(!e)return;let n=Number(e.trim());return Number.isFinite(n)&&n>=0?n:void 0}function be(t,e){return t<=0?Promise.resolve():new Promise((n,a)=>{if(e?.aborted){a(new b("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new b("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};e?.addEventListener("abort",s,{once:!0})})}async function Re(t,e={}){let n=e.maxRetries??2,a=e.baseDelayMs??200,o=e.maxDelayMs??5e3,s=e.respectRetryAfter??!0,d=e.sleep??be,u=0;for(;;)try{return await t()}catch(m){if(!(m instanceof b)||!m.retryable||u>=n)throw m;u+=1;let r=s&&typeof m.retryAfterSeconds=="number"?m.retryAfterSeconds*1e3:void 0,i=Math.min(o,a*2**(u-1)),y=i*.25*Math.random(),L=r??i+y;e.onRetry?.({attempt:u,error:m,delayMs:L}),await d(L,e.signal)}}function Ae(t){t.appId||f("appId is required"),t.state||f("state is required"),t.nonce||f("nonce is required"),t.hostedConnectUrl||f("hostedConnectUrl is required and has no implicit default: pass the Hosted Connect origin for the target environment (e.g. FACTO_CONNECT_HOSTED_URLS.dev)");let e=J(t.hostedConnectUrl);v(e,T,"hostedConnectUrl",!0);let n=new URL("/connect",`${e}/`);n.searchParams.set("external_app_id",t.appId),n.searchParams.set("external_state",t.state),n.searchParams.set("external_nonce",t.nonce);let a=new URLSearchParams;t.customerEmail!==void 0&&a.set("customer_email",t.customerEmail),t.customerUsername!==void 0&&a.set("customer_username",t.customerUsername);let o=a.toString();return o&&(n.hash=o),n.toString()}function Ie(t){let e=ke(t),n=`Basic ${kt(`${e.clientId}:${e.clientSecret}`)}`,a=(r,i)=>R(e,r,{code:i.code,state:i.state,nonce:i.nonce},n,et),o=(r,i)=>R(e,r,Xe(e,i),n,tt),s=(r,i)=>R(e,r,{appId:e.appId,externalCustomerRef:i.externalCustomerRef,requestedUseCases:i.requestedUseCases,defaultLimits:i.defaultLimits,returnUrl:i.returnUrl,state:i.state,...i.customerEmail===void 0?{}:{customerEmail:i.customerEmail},...i.customerUsername===void 0?{}:{customerUsername:i.customerUsername}},n,se),d=(r,i)=>S(e,`${r}/${encodeURIComponent(i)}`,n,se),u=(r,i)=>S(e,`${r}/${encodeURIComponent(i)}`,n,ie),m=(r,i)=>{let y={mandateId:i.mandateId,merchantPaymentRef:i.merchantPaymentRef,amount:i.amount,currency:i.currency,useCase:i.useCase};return i.paymentOptionId!==void 0&&(y.paymentOptionId=i.paymentOptionId),i.description!==void 0&&(y.description=i.description),i.metadata!==void 0&&(y.metadata=i.metadata),R(e,r,y,n,N,{"Idempotency-Key":i.idempotencyKey},[402])},p=(r,i)=>S(e,`${r}/${encodeURIComponent(i)}`,n,N);return{createHostedConnectUrl(r){let i=r.hostedConnectUrl??e.hostedConnectUrl;if(r.hostedConnectUrl!==void 0){let y=v(r.hostedConnectUrl,T,"hostedConnectUrl",!0);y!==void 0&&y!==e.environment&&f("hostedConnectUrl conflicts with the configured environment")}return Ae({appId:e.appId,state:r.state,nonce:r.nonce,customerEmail:r.customerEmail,customerUsername:r.customerUsername,hostedConnectUrl:i})},exchangeUserLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentReadiness(r){return o(h.paymentCapability,r)},createAuthorizationSession(r){return s(h.authorizationSessions,r)},getAuthorizationSession(r){return d(h.authorizationSessions,r)},getPaymentAuthorization(r){return u(h.paymentAuthorizations,r)},createMerchantPayment(r){return m(h.payments,r)},getMerchantPayment(r){return p(h.payments,r)},exchangeLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentCapability(r){return o(h.paymentCapability,r)},createCheckoutSession(r){return r.userLinkRef!==void 0&&_(r.userLinkRef,"ul_","userLinkRef"),R(e,h.checkoutSessions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{app_id:e.appId,facto_server_wallet_address:r.factoServerWalletAddress},amount:r.amount,asset_symbol:r.assetSymbol,order_ref:r.orderRef,return_url:r.returnUrl},n,nt)},getCheckoutSession(r){return S(e,`${h.checkoutSessions}/${encodeURIComponent(r)}`,n,rt)},createMandateAuthorizationSession(r){return s(h.authorizationSessions,r)},getMandateAuthorizationSession(r){return d(h.authorizationSessions,r)},getMerchantMandate(r){return u(h.paymentAuthorizations,r)},listPaymentOptions(r){return r.userLinkRef!==void 0&&_(r.userLinkRef,"ul_","userLinkRef"),R(e,h.paymentOptions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{appId:e.appId,grantRef:r.grantRef},...r.amount!==void 0?{amount:r.amount}:{},...r.assetSymbol!==void 0?{assetSymbol:r.assetSymbol}:{}},n,st)},createMandatePayment(r){return m(h.payments,r)},getMandatePayment(r){return p(h.payments,r)},onStatus(r,i,y){return Ee(()=>S(e,`${h.payments}/${encodeURIComponent(r)}`,n,N),i,y)},revokeUserLink(r){return ne(e,`/api/merchant/user-links/${encodeURIComponent(r)}`,n)},listMerchantPayments(r={}){return S(e,W("/api/merchant/payments",{limit:r.limit,startingAfter:r.startingAfter,createdAfter:r.createdAfter,createdBefore:r.createdBefore,authorizationId:r.authorizationId,status:r.status}),n,i=>z(i,N))},listPaymentAuthorizations(r={}){return S(e,W("/api/merchant/payment-authorizations",{limit:r.limit,startingAfter:r.startingAfter,userLinkRef:r.userLinkRef,status:r.status}),n,i=>z(i,ie))},createRefund(r){let i={paymentId:r.paymentId};return r.amount!==void 0&&(i.amount=r.amount),r.reason!==void 0&&(i.reason=r.reason),r.merchantRefundRef!==void 0&&(i.merchantRefundRef=r.merchantRefundRef),R(e,"/api/merchant/refunds",i,n,H,{"Idempotency-Key":r.idempotencyKey},[402])},getRefund(r){return S(e,`/api/merchant/refunds/${encodeURIComponent(r)}`,n,H)},listRefunds(r={}){return S(e,W("/api/merchant/refunds",{limit:r.limit,startingAfter:r.startingAfter,paymentId:r.paymentId}),n,i=>z(i,H))},createWebhookEndpoint(r){return R(e,"/api/merchant/webhook-endpoints",{url:r.url,enabledEvents:r.enabledEvents},n,re)},listWebhookEndpoints(){return S(e,"/api/merchant/webhook-endpoints",n,r=>{let y=g(r).data;if(!Array.isArray(y))throw new Error("expected data array");return y.map(B)})},getWebhookEndpoint(r){return S(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n,B)},deleteWebhookEndpoint(r){return ne(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n)},rotateWebhookSecret(r){return R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}/rotate-secret`,{},n,re)},getDevCapabilities(){return U(e,"getDevCapabilities"),S(e,"/api/dev/capabilities",n,Ke)},fundDevUser(r){return U(e,"fundDevUser"),X(r.userLinkRef),ee(r.amount),te(r.idempotencyKey),R(e,"/api/dev/faucet/usdc",{userLinkRef:r.userLinkRef,amount:r.amount},n,Ye,{"Idempotency-Key":r.idempotencyKey})},simulateDevCharge(r){return U(e,"simulateDevCharge"),X(r.userLinkRef),r.cardRef!==void 0&&_(r.cardRef,"card_","cardRef"),ee(r.amount),Le(r.scenario),r.merchantReference!==void 0&&(typeof r.merchantReference!="string"||r.merchantReference.length>120)&&f("merchantReference must not exceed 120 characters"),te(r.idempotencyKey),R(e,"/api/dev/simulate/charge",{userLinkRef:r.userLinkRef,...r.cardRef===void 0?{}:{cardRef:r.cardRef},amount:r.amount,scenario:r.scenario,...r.merchantReference===void 0?{}:{merchantReference:r.merchantReference}},n,ae,{"Idempotency-Key":r.idempotencyKey})},getDevSimulation(r){return U(e,"getDevSimulation"),_(r,"sim_","simulationId"),S(e,`/api/dev/simulations/${encodeURIComponent(r)}`,n,ae)},sendWebhookTestDelivery(r){return Me(e),xe(r.webhookEndpointId),r.message!==void 0&&(typeof r.message!="string"||r.message.length>120)&&f("webhook test message must not exceed 120 characters"),R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r.webhookEndpointId)}/test-delivery`,r.message===void 0?{}:{message:r.message},n,Ze)}}}var _e=new Set(["declined","succeeded","paid_via_coverage","failed","canceled"]);function ve(t){return _e.has(t)}async function Ee(t,e,n={}){let a=Math.max(0,n.initialIntervalMs??1e3),o=Math.max(a,n.maxIntervalMs??8e3),s=n.backoffFactor??1.5,d=n.timeoutMs??3e5,u=n.signal,m=Date.now()+d,p=a,r;for(;;){we(u);let i=await t();if(i.status!==r&&(r=i.status,e(i)),ve(i.status))return i;let y=m-Date.now();if(y<=0)return i;await Pe(Math.min(p,y),u),p=Math.min(p*s,o)}}function we(t){if(t?.aborted)throw new b("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1})}function Pe(t,e){return new Promise((n,a)=>{let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new b("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1}))};if(e){if(e.aborted){clearTimeout(o),s();return}e.addEventListener("abort",s,{once:!0})}})}var Te=Object.freeze(["dev","production","sandbox"]);function ke(t){t.appId||f("appId is required"),t.clientId||f("clientId is required"),t.clientSecret||f("clientSecret is required");let e=t.environment;(e===void 0||!Te.includes(e))&&f("environment is required and must be 'dev', 'production', or 'sandbox' ('sandbox' is the documented public test environment name and targets the same dev endpoints \u2014 ADR-0077). 'staging' and the former 'custom' selector are retired: pass explicit apiBaseUrl and hostedConnectUrl overrides (valid with any environment) for a local, private, or staging deployment. There is no implicit default; the legacy production fallback over /api/external/* routes was removed. See https://docs.facto.to/reference/sdk"),t.transport!==void 0&&t.fetch!==void 0&&f("provide either transport or fetch, not both"),t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0)&&f("timeoutMs must be a positive safe integer");let n=t.apiBaseUrl?v(t.apiBaseUrl,F,"apiBaseUrl",!1):void 0,a=t.hostedConnectUrl?v(t.hostedConnectUrl,T,"hostedConnectUrl",!0):void 0;n!==void 0&&a!==void 0&&n!==a&&f("apiBaseUrl and hostedConnectUrl target different Facto environments");let o=e,s=K(o);for(let p of[n,a])p!==void 0&&p!==s&&f("environment selector conflicts with a published Facto endpoint");let d=J(t.apiBaseUrl??F[s]),u=J(t.hostedConnectUrl??T[s]),m=v(d,F,"apiBaseUrl",!1);return v(u,T,"hostedConnectUrl",!0),Ue(t.clientId,m),{appId:t.appId,clientId:t.clientId,clientSecret:t.clientSecret,environment:o,apiBaseUrl:d,hostedConnectUrl:u,transport:t.transport??t.fetch??((p,r)=>globalThis.fetch(p,r)),...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.retry===void 0?{}:{retry:t.retry},...t.signal===void 0?{}:{signal:t.signal}}}function U(t,e){K(t.environment)!=="dev"&&f(`${e} is available only in the sandbox/dev environment`)}function Me(t){K(t.environment)!=="dev"&&f("sendWebhookTestDelivery is available only in the sandbox/dev environment")}function _(t,e,n){(typeof t!="string"||!new RegExp(`^${e}[A-Za-z0-9_-]+$`).test(t))&&f(`${n} must be an opaque ${e} reference`)}function X(t){_(t,"ul_","userLinkRef")}function xe(t){(typeof t!="string"||!/^we_[A-Za-z0-9]+$/.test(t))&&f("webhookEndpointId must be an opaque we_ reference")}function ee(t){(typeof t!="object"||t===null||t.currency!=="USDC"||typeof t.amount!="string"||!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(t.amount))&&f("Dev amount must be a USDC decimal with at most six fractional digits")}function Le(t){(typeof t!="string"||!me.includes(t))&&f("unknown Dev simulation scenario")}function te(t){(typeof t!="string"||t.trim()!==t||t.length<16||t.length>255)&&f("idempotencyKey must be 16 to 255 non-whitespace-trimmed characters")}function Ue(t,e){let n=e==="dev",a=e==="production";t.startsWith("dev_")&&e!==void 0&&!n&&f("a dev credential can target only the sandbox/dev environment"),(n||a)&&(t.startsWith("staging_")||t.startsWith("test_")||t.startsWith("lab_")||t.startsWith("sandbox_"))&&f("internal or legacy (staging_/test_/lab_/sandbox_) credentials cannot target a published Facto environment")}function v(t,e,n,a){let o;try{o=new URL(t)}catch{f(`${n} must be an absolute URL`)}let s=o.hostname.toLowerCase().replace(/\.$/,"");for(let d of["dev","production"]){let u=new URL(e[d]);if(s!==u.hostname.toLowerCase())continue;let m=o.pathname==="/"||a&&o.pathname==="/connect";return(o.origin!==u.origin||o.username!==""||o.password!==""||!m||o.search!==""||o.hash!=="")&&f(`${n} is not the exact published ${d} endpoint`),d}}async function R(t,e,n,a,o,s={},d=[]){let u=await le(t,async()=>{let m=await G(t,`${t.apiBaseUrl}${e}`,{method:"POST",headers:{authorization:a,"content-type":"application/json",...s},body:JSON.stringify(n)});if(!m.ok&&!d.includes(m.status))throw await j(m);return m},s["Idempotency-Key"]!==void 0);try{return o(await u.json())}catch(m){throw new b("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:m})}}async function S(t,e,n,a){let o=await le(t,async()=>{let s=await G(t,`${t.apiBaseUrl}${e}`,{method:"GET",headers:{authorization:n}});if(!s.ok)throw await j(s);return s},!0);try{return a(await o.json())}catch(s){throw new b("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:s})}}async function ne(t,e,n){let a=await G(t,`${t.apiBaseUrl}${e}`,{method:"DELETE",headers:{authorization:n}});if(!a.ok)throw await j(a)}async function j(t){return new b("FACTO_ENGINE_REQUEST_FAILED",`Facto Engine request failed with status ${t.status}`,{retryable:t.status===429||t.status>=500,status:t.status,details:await Tt(t),retryAfterSeconds:Se(t)})}function le(t,e,n){return n?Re(e,{...t.retry,signal:t.signal??t.retry?.signal}):e()}function G(t,e,n){return t.timeoutMs===void 0?t.transport(e,{...n,signal:t.signal}):Ne(t,e,n)}function Ne(t,e,n){let a=new AbortController,o=()=>a.abort();return t.signal?.aborted?Promise.reject(new b("FACTO_REQUEST_ABORTED","Facto Engine request aborted",{retryable:!1})):(t.signal?.addEventListener("abort",o,{once:!0}),new Promise((s,d)=>{let u=setTimeout(()=>{a.abort(),d(new b("FACTO_REQUEST_ABORTED","Facto Engine request timed out",{retryable:!1}))},t.timeoutMs);t.transport(e,{...n,signal:a.signal}).then(s,d).finally(()=>{clearTimeout(u),t.signal?.removeEventListener("abort",o)})}))}function W(t,e){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))s!==void 0&&s!==""&&n.set(o,String(s));let a=n.toString();return a?`${t}?${a}`:t}function z(t,e){let n=g(t),a=n.data;if(!Array.isArray(a))throw new Error("expected data array");return{data:a.map(e),hasMore:w(n,"hasMore")}}var Oe=["pending","succeeded","failed"],De=["requested_by_customer","duplicate","fraudulent","other"];function Fe(t,e){let n=t[e];if(typeof n!="string"||!Oe.includes(n))throw new Error(`expected refund status at ${e}`);return n}function We(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||!De.includes(n))throw new Error(`expected refund reason at ${e}`);return n}}function H(t){let e=g(t),n=We(e,"reason"),a=A(e,"merchantRefundRef");return{refundId:c(e,"refundId"),paymentId:c(e,"paymentId"),status:Fe(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),...n===void 0?{}:{reason:n},...a===void 0?{}:{merchantRefundRef:a},createdAt:c(e,"createdAt")}}var ze=["user_link.revoked","payment_authorization.activated","payment_authorization.updated","payment_authorization.revoked","checkout_session.completed","checkout_session.expired","payment.succeeded","payment.failed","refund.succeeded","refund.failed"];function He(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected event-type array at ${e}`);return n.map(a=>{if(typeof a!="string"||!ze.includes(a))throw new Error(`unknown webhook event type: ${String(a)}`);return a})}function B(t){let e=g(t),n=e.status;if(n!=="enabled"&&n!=="disabled")throw new Error("expected webhook endpoint status");return{webhookEndpointId:c(e,"webhookEndpointId"),url:c(e,"url"),enabledEvents:He(e,"enabledEvents"),status:n,createdAt:c(e,"createdAt")}}function re(t){let e=B(t),n=g(t);return{...e,secret:c(n,"secret")}}var D=["fixtures","synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"],$e=["unavailable","degraded","ready"],qe=["contract","implemented","deployed","verified"],me=["approved","declined_setup","declined_limit","payment_failed"],Ve=["pre_admission","onchain_test_assets"],Be=["accepted","processing","succeeded","failed","declined"],Je=["accepted","broadcast","confirmed","failed"];function Ke(t){let e=g(t),n=e.capabilities;if(!Array.isArray(n)||n.length!==D.length)throw new Error("expected exactly six Dev capabilities");let a=n.map(je),o=new Set(a.map(s=>s.name));if(o.size!==D.length)throw new Error("expected each Dev capability exactly once");for(let s of D)if(!o.has(s))throw new Error(`missing Dev capability: ${s}`);return{environment:x(e,"environment","dev"),contractVersion:x(e,"contractVersion","2026-07-09"),capabilities:a,checkedAt:c(e,"checkedAt")}}function je(t){let e=g(t),n=C(e,"name",D,"Dev capability name"),a=C(e,"status",$e,"Dev capability status"),o=C(e,"evidenceLevel",qe,"Dev evidence level"),s=E(e,"reasonCode"),d=E(e,"verifiedAt");if(a==="ready"&&(o!=="verified"||d===null))throw new Error("ready Dev capability requires verified evidence");let u=Qe(e,"limits");return{name:n,status:a,evidenceLevel:o,...s===void 0?{}:{reasonCode:s},...d===void 0?{}:{verifiedAt:d},...u===void 0?{}:{limits:u}}}function Ge(t){let e=g(t),n=c(e,"amount");if(!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(n))throw new Error("expected Dev USDC decimal amount");return{amount:n,currency:x(e,"currency","USDC")}}function Ye(t){let e=g(t);return{faucetTransferId:M(e,"faucetTransferId","sft_"),userLinkRef:M(e,"userLinkRef","ul_"),amount:Ge(e.amount),status:C(e,"status",Je,"Dev faucet status"),createdAt:c(e,"createdAt")}}function ae(t){let e=g(t);return{simulationId:M(e,"simulationId","sim_"),scenario:C(e,"scenario",me,"Dev scenario"),executionMode:C(e,"executionMode",Ve,"Dev execution mode"),status:C(e,"status",Be,"Dev simulation status"),reasonCode:$(e,"reasonCode"),authorizationRef:$(e,"authorizationRef"),chargeRef:$(e,"chargeRef"),createdAt:c(e,"createdAt"),updatedAt:c(e,"updatedAt")}}function Ze(t){let e=g(t);return{eventId:oe(e,"eventId","evt_"),deliveryId:oe(e,"deliveryId","wd_"),status:x(e,"status","queued"),createdAt:c(e,"createdAt")}}function Qe(t,e){if(t[e]===void 0)return;let n=g(t[e]);for(let a of Object.values(n))if(a!==null&&typeof a!="string"&&typeof a!="number"&&typeof a!="boolean")throw new Error(`expected scalar Dev limit at ${e}`);return n}function M(t,e,n){let a=c(t,e);if(!new RegExp(`^${n}[A-Za-z0-9_-]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function oe(t,e,n){let a=c(t,e);if(!new RegExp(`^${n}[A-Za-z0-9]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function Xe(t,e){return e.userLinkRef===void 0&&e.factoServerWalletAddress===void 0&&f("payment readiness requires userLinkRef, factoServerWalletAddress, or both"),e.userLinkRef!==void 0&&_(e.userLinkRef,"ul_","userLinkRef"),e.factoServerWalletAddress!==void 0&&typeof e.factoServerWalletAddress!="string"&&f("factoServerWalletAddress must be a string"),{...e.userLinkRef===void 0?{}:{userLinkRef:e.userLinkRef},...e.factoServerWalletAddress===void 0?{}:{app_id:t.appId,facto_server_wallet_address:e.factoServerWalletAddress}}}function k(t,e){let n=t[e];if(n==null)return n;if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string or null at ${e}`);return n}function et(t){let e=g(t),n=k(e,"cardRef"),a=k(e,"factoUserId"),o=k(e,"factoServerWalletAddress");if(n!=null&&(_(n,"card_","cardRef"),a!=null||o!=null))throw new Error("synthetic Dev links must not expose canonical identity");return{appId:c(e,"appId"),userLinkRef:M(e,"userLinkRef","ul_"),grantStatus:c(e,"grantStatus"),pipelineReady:w(e,"pipelineReady"),scopes:Pt(e,"scopes"),...n===void 0?{}:{cardRef:n},...a===void 0?{}:{factoUserId:a},...o===void 0?{}:{factoServerWalletAddress:o}}}function tt(t){let e=g(t),n=w(e,"pipelineReady"),a=e.notReadyReason,o=a==null?a:C(e,"notReadyReason",Q,"payment readiness not-ready reason");if(n&&o!==void 0&&o!==null)throw new Error("expected notReadyReason only when pipelineReady is false");let s=k(e,"factoUserId"),d=k(e,"factoServerWalletAddress");return{appId:c(e,"appId"),userLinkRef:M(e,"userLinkRef","ul_"),selectedPipelineId:c(e,"selectedPipelineId"),chainId:pe(e,"chainId"),protocolId:c(e,"protocolId"),assetSymbol:c(e,"assetSymbol"),spendMode:c(e,"spendMode"),pipelineReady:n,...o===void 0?{}:{notReadyReason:o},...s===void 0?{}:{factoUserId:s},...d===void 0?{}:{factoServerWalletAddress:d}}}function nt(t){let e=g(t);return{sessionId:c(e,"sessionId"),checkoutUrl:c(e,"checkoutUrl"),status:x(e,"status","pending"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:E(e,"orderRef")}}function rt(t){let e=g(t);return{sessionId:c(e,"sessionId"),status:bt(e,"status"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:E(e,"orderRef"),chargeId:E(e,"chargeId"),confirmedAt:E(e,"confirmedAt")}}function se(t){let e=g(t),n=A(e,"mandateId"),a=A(e,"userLinkRef");return{sessionId:c(e,"sessionId"),authorizationUrl:c(e,"authorizationUrl"),status:_t(e,"status"),...n===void 0?{}:{mandateId:n},...a===void 0?{}:{userLinkRef:a},expiresAt:c(e,"expiresAt"),state:c(e,"state")}}function ie(t){let e=g(t),n=A(e,"expiresAt");return{mandateId:c(e,"mandateId"),appId:c(e,"appId"),status:It(e,"status"),allowedUseCases:wt(e,"allowedUseCases"),limits:lt(e.limits),paymentPath:mt(e.paymentPath),createdAt:c(e,"createdAt"),...n===void 0?{}:{expiresAt:n}}}var at="direct",ot="defaultPaymentOptionId";function st(t){let e=g(t);ye(e,"payment options");let n=e.paymentOptions;if(!Array.isArray(n))throw new Error("expected paymentOptions array");let a=n.map(ct).filter(d=>d.settlementPath===at),o=ft(e,ot),s=it(a,o);return{paymentOptions:a,...s===void 0?{}:{selectedPaymentOptionId:s}}}function it(t,e){return e!==void 0&&t.some(a=>a.paymentOptionId===e)?e:(t.find(a=>a.ready)??t[0])?.paymentOptionId}function dt(t){let e=A(t,"settlementPath"),n=A(t,"spendMode"),a=e??n;if(a===void 0)throw new Error("expected settlementPath or the deprecated spendMode on a payment option");return{settlementPath:a,spendMode:n??a}}function ct(t){let e=g(t);ye(e,"payment option");let n=A(e,"blockingReason"),a=c(e,"assetSymbol"),o=c(e,"chainLabel"),s=c(e,"protocolLabel"),{settlementPath:d,spendMode:u}=dt(e);return{paymentOptionId:fe(e,"paymentOptionId"),label:ut({assetSymbol:a,protocolLabel:s,chainLabel:o},c(e,"label")),ready:w(e,"ready"),isDefault:w(e,"isDefault"),chainId:pe(e,"chainId"),chainLabel:o,protocolLabel:s,assetSymbol:a,spendMode:u,settlementPath:d,...n===void 0?{}:{blockingReason:n}}}function ut(t,e){let n=[t.assetSymbol,t.protocolLabel,t.chainLabel].map(a=>a.trim()).filter(a=>a.length>0);return n.length>0?n.join(" \xB7 "):e}function N(t){let e=g(t),n=A(e,"chargeId"),a=A(e,"txHash"),o=Et(e,"declineReason"),s=pt(e,"finalityEtaSeconds"),d=A(e,"terminalAt"),u=A(e,"updatedAt");return{paymentId:c(e,"paymentId"),mandateId:c(e,"mandateId"),merchantPaymentRef:c(e,"merchantPaymentRef"),status:vt(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),useCase:Rt(e,"useCase"),...n===void 0?{}:{chargeId:n},...a===void 0?{}:{txHash:a},...o===void 0?{}:{declineReason:o},...s===void 0?{}:{finalityEtaSeconds:s},...d===void 0?{}:{terminalAt:d},createdAt:c(e,"createdAt"),...u===void 0?{}:{updatedAt:u}}}function lt(t){let e=g(t);return{perTxAmount:c(e,"perTxAmount"),periodAmount:c(e,"periodAmount"),period:At(e,"period")}}function mt(t){let e=g(t),n=A(e,"blockingReason");return{ready:w(e,"ready"),summary:c(e,"summary"),...n===void 0?{}:{blockingReason:n}}}function g(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("expected object");return t}function c(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}function A(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}}function fe(t,e){let n=c(t,e);if(!n.startsWith("fpo_"))throw new Error(`expected opaque Facto payment option id at ${e}`);return n}function ft(t,e){if(!(t[e]===void 0||t[e]===null))return fe(t,e)}function x(t,e,n){if(t[e]!==n)throw new Error(`expected ${n} at ${e}`);return n}function w(t,e){let n=t[e];if(typeof n!="boolean")throw new Error(`expected boolean at ${e}`);return n}function pe(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}function pt(t,e){let n=t[e];if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}}var gt=["pending","charged","expired","cancelled"],ge=["immediate","recurring","top_up","metered"],yt=["daily","weekly","monthly"],ht=["pending","active","paused","revoked","expired","suspended"],Ct=["created","authorized","declined","expired"],St=["accepted","declined","charging","finalizing","succeeded","paid_via_coverage","failed","canceled"];function bt(t,e){let n=t[e];if(typeof n!="string"||!gt.includes(n))throw new Error(`expected checkout status at ${e}`);return n}function Rt(t,e){return C(t,e,ge,"mandate use case")}function At(t,e){return C(t,e,yt,"mandate limit period")}function It(t,e){return C(t,e,ht,"mandate status")}function _t(t,e){return C(t,e,Ct,"mandate authorization status")}function vt(t,e){return C(t,e,St,"mandate payment status")}function Et(t,e){if(t[e]!==void 0)return C(t,e,Z,"mandate decline reason")}function wt(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected mandate use case array at ${e}`);return n.map(a=>{if(typeof a!="string"||!ge.includes(a))throw new Error(`expected mandate use case array at ${e}`);return a})}function C(t,e,n,a){let o=t[e];if(typeof o!="string"||!n.includes(o))throw new Error(`expected ${a} at ${e}`);return o}function E(t,e){let n=t[e];if(n==null)return null;if(typeof n!="string")throw new Error(`expected string or null at ${e}`);return n}function $(t,e){let n=t[e];if(n===null)return null;if(typeof n!="string")throw new Error(`expected required string or null at ${e}`);return n}function Pt(t,e){let n=t[e];if(!Array.isArray(n)||n.some(a=>typeof a!="string"))throw new Error(`expected string array at ${e}`);return n}function ye(t,e){let a=["userId","factoUserId","cardId","routeId","vaultKind","serverWallet","factoServerWalletAddress","pathSnapshot","paymentPathSnapshot","pipelineId","selectedPipelineId","paymentRouteId","routeSelector"].find(o=>t[o]!==void 0);if(a)throw new Error(`unsafe ${e} field: ${a}`)}async function Tt(t){try{return await t.json()}catch{return await t.text().catch(()=>null)}}function J(t){return t.replace(/\/+$/,"")}function f(t){throw new b("FACTO_CONFIG_INVALID",t,{retryable:!1})}function kt(t){let e=globalThis.btoa;if(e)return e(t);let n=globalThis.Buffer;if(n)return n.from(t).toString("base64");f("No base64 encoder is available in this runtime")}function Gt(t,e,n=Math.floor(Date.now()/1e3)){e||f("webhook secret is required"),(!Number.isSafeInteger(n)||n<0)&&f("webhook timestamp must be a non-negative safe integer");let a=ue("sha256",e).update(`${n}.`).update(t).digest("hex");return`t=${n},v1=${a}`}function Yt(t,e,n,a=300){n||f("webhook secret is required");let o=e.split(",").map(m=>m.trim()),s,d=[];for(let m of o){let p=m.indexOf("=");if(p===-1)continue;let r=m.slice(0,p),i=m.slice(p+1);r==="t"?s=Number(i):r==="v1"&&d.push(i)}if(s===void 0||!Number.isFinite(s)||Math.abs(Date.now()/1e3-s)>a||d.length===0)return!1;let u=ue("sha256",n).update(`${s}.`).update(t).digest();return d.some(m=>{let p;try{p=Buffer.from(m,"hex")}catch{return!1}return p.length===u.length&&Ce(p,u)})}var l=class extends Error{code;details;constructor(e,n,a={}){super(n),this.name="FactoConnectHintError",this.code=e,this.details=a.details}},Mt="facto";async function Zt(t){if(t===null||typeof t!="object")throw new l("FACTO_HINT_INPUT_INVALID","verifyFactoCardProgramConnectHint requires an input object");let e=V(t.connectHint,"connectHint"),n=V(t.audience,"audience"),a=t.issuer===void 0?Mt:V(t.issuer,"issuer"),o=zt(t.clockToleranceSeconds),s=Math.floor(Ht(t.now)/1e3),{headerB64:d,payloadB64:u,signature:m}=xt(e),p=Y(de(d,"header"),"FACTO_HINT_MALFORMED","connect hint header");if(p.alg!=="EdDSA")throw new l("FACTO_HINT_UNSUPPORTED_ALG","connect hint JWS alg must be EdDSA",{details:{alg:p.alg}});let r=typeof p.kid=="string"?p.kid:void 0,i=await Lt(t.jwks),y=Dt(i,r),L=qt(`${d}.${u}`);if(!await Ft(L,m,y))throw new l("FACTO_HINT_SIGNATURE_INVALID","connect hint signature does not verify against the Facto JWKS");let I=Wt(de(u,"payload"));if(I.iss!==a)throw new l("FACTO_HINT_ISSUER_MISMATCH","connect hint issuer mismatch",{details:{expected:a,actual:I.iss}});if(I.aud!==n)throw new l("FACTO_HINT_AUDIENCE_MISMATCH","connect hint audience mismatch",{details:{expected:n,actual:I.aud}});if(s>I.exp+o)throw new l("FACTO_HINT_EXPIRED","connect hint has expired",{details:{exp:I.exp,now:s}});return{programRef:I.program_ref,pairwiseSubject:I.sub,nonce:I.nonce,expiresAt:new Date(I.exp*1e3).toISOString()}}function xt(t){let e=t.split(".");if(e.length!==3)throw new l("FACTO_HINT_MALFORMED","connect hint is not a compact JWS (expected three segments)");let[n,a,o]=e;if(!n||!a||!o)throw new l("FACTO_HINT_MALFORMED","connect hint has an empty JWS segment");return{headerB64:n,payloadB64:a,signature:he(o,"signature")}}function de(t,e){let n=new TextDecoder().decode(he(t,e));try{return JSON.parse(n)}catch(a){throw new l("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid JSON`,{details:a})}}async function Lt(t){if(t==null)throw new l("FACTO_HINT_INPUT_INVALID","jwks is required");return q(typeof t=="function"?await t():typeof t=="string"?await Nt(t):t)}var Ut=5e3,O=64*1024;async function Nt(t){let e;try{e=new URL(t)}catch{throw new l("FACTO_HINT_JWKS_INVALID",`JWKS url is not a valid URL: ${t}`)}if(e.protocol!=="https:")throw new l("FACTO_HINT_JWKS_INVALID",`JWKS url must use https: (got ${e.protocol})`,{details:{protocol:e.protocol}});let n=new AbortController,a=setTimeout(()=>n.abort(),Ut),o,s;try{try{o=await fetch(t,{method:"GET",headers:{accept:"application/json"},redirect:"follow",signal:n.signal})}catch(u){throw new l("FACTO_HINT_JWKS_INVALID",`failed to fetch Facto JWKS from ${t}`,{details:u})}if(!o.ok)throw new l("FACTO_HINT_JWKS_INVALID",`Facto JWKS request failed with status ${o.status}`,{details:{status:o.status}});let d=Number(o.headers.get("content-length"));if(Number.isFinite(d)&&d>O)throw new l("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${O} bytes`,{details:{contentLength:d}});try{s=await o.text()}catch(u){throw new l("FACTO_HINT_JWKS_INVALID","Facto JWKS response could not be read",{details:u})}}finally{clearTimeout(a)}if(s.length>O)throw new l("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${O} bytes`,{details:{bytes:s.length}});try{return JSON.parse(s)}catch(d){throw new l("FACTO_HINT_JWKS_INVALID","Facto JWKS response was not valid JSON",{details:d})}}function q(t){let e=Y(t,"FACTO_HINT_JWKS_INVALID","JWKS");if(!Array.isArray(e.keys))throw new l("FACTO_HINT_JWKS_INVALID",'JWKS "keys" must be an array');return{keys:e.keys.map(Ot)}}function Ot(t){let e=typeof t=="object"&&t!==null?t:{};return{kty:typeof e.kty=="string"?e.kty:"",crv:typeof e.crv=="string"?e.crv:"",x:typeof e.x=="string"?e.x:"",...typeof e.kid=="string"?{kid:e.kid}:{},...typeof e.alg=="string"?{alg:e.alg}:{},...typeof e.use=="string"?{use:e.use}:{}}}function Dt(t,e){let n=t.keys.filter(a=>a.kty==="OKP"&&a.crv==="Ed25519"&&a.x.length>0);if(n.length===0)throw new l("FACTO_HINT_JWKS_INVALID","Facto JWKS has no usable Ed25519 signing key");if(e!==void 0){let a=n.filter(o=>o.kid===e);if(a.length>0)return a}return n}async function Ft(t,e,n){let a=Vt();for(let o of n){let s;try{s=await a.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:o.x},{name:"Ed25519"},!1,["verify"])}catch{continue}try{if(await a.verify({name:"Ed25519"},s,e,t))return!0}catch{continue}}return!1}function Wt(t){let e=Y(t,"FACTO_HINT_CLAIMS_INVALID","connect hint claims");return{iss:P(e,"iss"),aud:P(e,"aud"),sub:P(e,"sub"),program_ref:P(e,"program_ref"),nonce:P(e,"nonce"),iat:ce(e,"iat"),exp:ce(e,"exp")}}function V(t,e){if(typeof t!="string"||t.length===0)throw new l("FACTO_HINT_INPUT_INVALID",`${e} must be a non-empty string`);return t}function zt(t){if(t===void 0)return 0;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new l("FACTO_HINT_INPUT_INVALID","clockToleranceSeconds must be a non-negative finite number");return t}function Ht(t){if(t===void 0)return Date.now();if(t instanceof Date){let e=t.getTime();if(Number.isNaN(e))throw new l("FACTO_HINT_INPUT_INVALID","now is an invalid Date");return e}if(typeof t=="number"&&Number.isFinite(t))return t;throw new l("FACTO_HINT_INPUT_INVALID","now must be a Date or unix milliseconds number")}function Y(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new l(e,`${n} must be a JSON object`);return t}function P(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new l("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a non-empty string`);return n}function ce(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new l("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a finite number`);return n}function he(t,e){if(!/^[A-Za-z0-9_-]*$/.test(t))throw new l("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`);let n=t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4);return $t(n,e)}function $t(t,e){let n=globalThis.atob;if(n){let o;try{o=n(t)}catch(d){throw new l("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`,{details:d})}let s=new Uint8Array(o.length);for(let d=0;d<o.length;d+=1)s[d]=o.charCodeAt(d);return s}let a=globalThis.Buffer;if(a)return new Uint8Array(a.from(t,"base64"));throw new l("FACTO_HINT_INPUT_INVALID","No base64 decoder is available in this runtime")}function qt(t){let e=new TextEncoder().encode(t),n=new Uint8Array(e.length);return n.set(e),n}function Vt(){let t=globalThis.crypto;if(t?.subtle)return t.subtle;throw new l("FACTO_HINT_INPUT_INVALID","Web Crypto (crypto.subtle) is not available in this runtime")}var Qt=Ie;export{F as FACTO_CONNECT_API_BASE_URLS,T as FACTO_CONNECT_HOSTED_URLS,l as FactoConnectHintError,b as FactoConnectServerError,Ae as buildHostedConnectUrl,Ie as createFactoConnectServer,Qt as default,ve as isTerminalMandatePaymentStatus,Gt as signWebhookPayload,Zt as verifyFactoCardProgramConnectHint,Yt as verifyWebhookSignature,Re as withServerRetry};
1
+ import{createHmac as le,timingSafeEqual as ve}from"node:crypto";var Z=["mandate_inactive","mandate_revoked","mandate_expired","use_case_not_allowed","mandate_limit_exceeded","mandate_period_limit_exceeded","user_limit_exceeded","limit_check_unavailable","payment_path_unavailable","payment_option_not_pinned","idempotency_conflict"];var Q=["payment_route_not_provisioned","protocol_config_incomplete"];var be=["psp_connect_sandbox","psp_mandate_sandbox"],X={psp_connect_sandbox:["readiness.read","authorizations.request"],psp_mandate_sandbox:["readiness.read","authorizations.request","payments.execute","refunds.execute"]};function Se(t){return X[t].includes("payments.execute")}var Re={dev:{clientIdPrefix:"dev_pspid_",clientSecretPrefix:"dev_pspsk_"},lab:{clientIdPrefix:"lab_pspid_"}},Ae="psp";function _e(t,e){return{...t,...e.ref===void 0?{}:{subMerchantRef:e.ref},...e.displayName===void 0?{}:{subMerchantDisplayName:e.displayName}}}function Ie(t){return{...t.subMerchantRef==null?{}:{ref:t.subMerchantRef},...t.subMerchantDisplayName==null?{}:{displayName:t.subMerchantDisplayName}}}function F(t){return t==="sandbox"?"dev":t}var W=Object.freeze({dev:"https://dev-api.facto.to",production:"https://api.facto.to"}),T=Object.freeze({dev:"https://dev.facto.to",production:"https://app.facto.to"}),Ee=Object.freeze({dev:Object.freeze(["dev_mcid_","dev_pspid_","dev_cpid_"]),production:Object.freeze(["mcid_","pspid_","cpid_"])});function Pe(t){if(typeof t=="string"){for(let e of["dev","production"])for(let n of Ee[e])if(t.startsWith(n))return e}}var h=Object.freeze({exchangeLinkCode:"/api/merchant/user-links/exchange",paymentCapability:"/api/merchant/payment-readiness",checkoutSessions:"/api/merchant/checkout-sessions",authorizationSessions:"/api/merchant/authorization-sessions",paymentAuthorizations:"/api/merchant/payment-authorizations",paymentOptions:"/api/merchant/payment-options",payments:"/api/merchant/payments"}),S=class extends Error{code;retryable;status;details;retryAfterSeconds;constructor(e,n,a){super(n),this.name="FactoConnectServerError",this.code=e,this.retryable=a.retryable,this.status=a.status,this.details=a.details,this.retryAfterSeconds=a.retryAfterSeconds}};function we(t){let e=t.headers.get("retry-after");if(!e)return;let n=Number(e.trim());return Number.isFinite(n)&&n>=0?n:void 0}function Te(t,e){return t<=0?Promise.resolve():new Promise((n,a)=>{if(e?.aborted){a(new S("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new S("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};e?.addEventListener("abort",s,{once:!0})})}async function Me(t,e={}){let n=e.maxRetries??2,a=e.baseDelayMs??200,o=e.maxDelayMs??5e3,s=e.respectRetryAfter??!0,d=e.sleep??Te,u=0;for(;;)try{return await t()}catch(m){if(!(m instanceof S)||!m.retryable||u>=n)throw m;u+=1;let r=s&&typeof m.retryAfterSeconds=="number"?m.retryAfterSeconds*1e3:void 0,i=Math.min(o,a*2**(u-1)),g=i*.25*Math.random(),L=r??i+g;e.onRetry?.({attempt:u,error:m,delayMs:L}),await d(L,e.signal)}}function ke(t){t.appId||l("appId is required"),t.state||l("state is required"),t.nonce||l("nonce is required"),t.hostedConnectUrl||l("hostedConnectUrl is required and has no implicit default: pass the Hosted Connect origin for the target environment (e.g. FACTO_CONNECT_HOSTED_URLS.dev)");let e=J(t.hostedConnectUrl);v(e,T,"hostedConnectUrl",!0);let n=new URL("/connect",`${e}/`);n.searchParams.set("external_app_id",t.appId),n.searchParams.set("external_state",t.state),n.searchParams.set("external_nonce",t.nonce);let a=new URLSearchParams;t.customerEmail!==void 0&&a.set("customer_email",t.customerEmail),t.customerUsername!==void 0&&a.set("customer_username",t.customerUsername);let o=a.toString();return o&&(n.hash=o),n.toString()}function xe(t){let e=We(t),n=`Basic ${Wt(`${e.clientId}:${e.clientSecret}`)}`,a=(r,i)=>R(e,r,{code:i.code,state:i.state,nonce:i.nonce},n,ct),o=(r,i)=>R(e,r,dt(e,i),n,ut),s=(r,i)=>R(e,r,{appId:e.appId,externalCustomerRef:i.externalCustomerRef,requestedUseCases:i.requestedUseCases,defaultLimits:i.defaultLimits,returnUrl:i.returnUrl,state:i.state,...i.customerEmail===void 0?{}:{customerEmail:i.customerEmail},...i.customerUsername===void 0?{}:{customerUsername:i.customerUsername}},n,ie),d=(r,i)=>b(e,`${r}/${encodeURIComponent(i)}`,n,ie),u=(r,i)=>b(e,`${r}/${encodeURIComponent(i)}`,n,de),m=(r,i)=>{let g={mandateId:i.mandateId,merchantPaymentRef:i.merchantPaymentRef,amount:i.amount,currency:i.currency,useCase:i.useCase};return i.paymentOptionId!==void 0&&(g.paymentOptionId=i.paymentOptionId),i.description!==void 0&&(g.description=i.description),i.metadata!==void 0&&(g.metadata=i.metadata),R(e,r,g,n,U,{"Idempotency-Key":i.idempotencyKey},[402])},y=(r,i)=>b(e,`${r}/${encodeURIComponent(i)}`,n,U);return{createHostedConnectUrl(r){let i=r.hostedConnectUrl??e.hostedConnectUrl;if(r.hostedConnectUrl!==void 0){let g=v(r.hostedConnectUrl,T,"hostedConnectUrl",!0);g!==void 0&&g!==F(e.environment)&&l("hostedConnectUrl conflicts with the configured environment")}return ke({appId:e.appId,state:r.state,nonce:r.nonce,customerEmail:r.customerEmail,customerUsername:r.customerUsername,hostedConnectUrl:i})},exchangeUserLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentReadiness(r){return o(h.paymentCapability,r)},createAuthorizationSession(r){return s(h.authorizationSessions,r)},getAuthorizationSession(r){return d(h.authorizationSessions,r)},getPaymentAuthorization(r){return u(h.paymentAuthorizations,r)},createMerchantPayment(r){return m(h.payments,r)},getMerchantPayment(r){return y(h.payments,r)},exchangeLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentCapability(r){return o(h.paymentCapability,r)},createCheckoutSession(r){return r.userLinkRef!==void 0&&I(r.userLinkRef,"ul_","userLinkRef"),R(e,h.checkoutSessions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{app_id:e.appId,facto_server_wallet_address:r.factoServerWalletAddress},amount:r.amount,asset_symbol:r.assetSymbol,order_ref:r.orderRef,return_url:r.returnUrl},n,lt)},getCheckoutSession(r){return b(e,`${h.checkoutSessions}/${encodeURIComponent(r)}`,n,mt)},createMandateAuthorizationSession(r){return s(h.authorizationSessions,r)},getMandateAuthorizationSession(r){return d(h.authorizationSessions,r)},getMerchantMandate(r){return u(h.paymentAuthorizations,r)},listPaymentOptions(r){return r.userLinkRef!==void 0&&I(r.userLinkRef,"ul_","userLinkRef"),R(e,h.paymentOptions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{appId:e.appId,grantRef:r.grantRef},...r.amount!==void 0?{amount:r.amount}:{},...r.assetSymbol!==void 0?{assetSymbol:r.assetSymbol}:{}},n,yt)},createMandatePayment(r){return m(h.payments,r)},getMandatePayment(r){return y(h.payments,r)},onStatus(r,i,g){return Ue(()=>b(e,`${h.payments}/${encodeURIComponent(r)}`,n,U),i,g)},revokeUserLink(r){return re(e,`/api/merchant/user-links/${encodeURIComponent(r)}`,n)},listMerchantPayments(r={}){return b(e,z("/api/merchant/payments",{limit:r.limit,startingAfter:r.startingAfter,createdAfter:r.createdAfter,createdBefore:r.createdBefore,authorizationId:r.authorizationId,status:r.status}),n,i=>H(i,U))},listPaymentAuthorizations(r={}){return b(e,z("/api/merchant/payment-authorizations",{limit:r.limit,startingAfter:r.startingAfter,userLinkRef:r.userLinkRef,status:r.status}),n,i=>H(i,de))},createRefund(r){let i={paymentId:r.paymentId};return r.amount!==void 0&&(i.amount=r.amount),r.reason!==void 0&&(i.reason=r.reason),r.merchantRefundRef!==void 0&&(i.merchantRefundRef=r.merchantRefundRef),R(e,"/api/merchant/refunds",i,n,$,{"Idempotency-Key":r.idempotencyKey},[402])},getRefund(r){return b(e,`/api/merchant/refunds/${encodeURIComponent(r)}`,n,$)},listRefunds(r={}){return b(e,z("/api/merchant/refunds",{limit:r.limit,startingAfter:r.startingAfter,paymentId:r.paymentId}),n,i=>H(i,$))},createWebhookEndpoint(r){return R(e,"/api/merchant/webhook-endpoints",{url:r.url,enabledEvents:r.enabledEvents},n,ae)},listWebhookEndpoints(){return b(e,"/api/merchant/webhook-endpoints",n,r=>{let g=f(r).data;if(!Array.isArray(g))throw new Error("expected data array");return g.map(K)})},getWebhookEndpoint(r){return b(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n,K)},deleteWebhookEndpoint(r){return re(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n)},rotateWebhookSecret(r){return R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}/rotate-secret`,{},n,ae)},getDevCapabilities(){return N(e,"getDevCapabilities"),b(e,"/api/dev/capabilities",n,nt)},fundDevUser(r){return N(e,"fundDevUser"),ee(r.userLinkRef),te(r.amount),ne(r.idempotencyKey),R(e,"/api/dev/faucet/usdc",{userLinkRef:r.userLinkRef,amount:r.amount},n,ot,{"Idempotency-Key":r.idempotencyKey})},simulateDevCharge(r){return N(e,"simulateDevCharge"),ee(r.userLinkRef),r.cardRef!==void 0&&I(r.cardRef,"card_","cardRef"),te(r.amount),$e(r.scenario),r.merchantReference!==void 0&&(typeof r.merchantReference!="string"||r.merchantReference.length>120)&&l("merchantReference must not exceed 120 characters"),ne(r.idempotencyKey),R(e,"/api/dev/simulate/charge",{userLinkRef:r.userLinkRef,...r.cardRef===void 0?{}:{cardRef:r.cardRef},amount:r.amount,scenario:r.scenario,...r.merchantReference===void 0?{}:{merchantReference:r.merchantReference}},n,oe,{"Idempotency-Key":r.idempotencyKey})},getDevSimulation(r){return N(e,"getDevSimulation"),I(r,"sim_","simulationId"),b(e,`/api/dev/simulations/${encodeURIComponent(r)}`,n,oe)},sendWebhookTestDelivery(r){return ze(e),He(r.webhookEndpointId),r.message!==void 0&&(typeof r.message!="string"||r.message.length>120)&&l("webhook test message must not exceed 120 characters"),R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r.webhookEndpointId)}/test-delivery`,r.message===void 0?{}:{message:r.message},n,st)}}}var Le=new Set(["declined","succeeded","paid_via_coverage","failed","canceled"]);function Ne(t){return Le.has(t)}async function Ue(t,e,n={}){let a=Math.max(0,n.initialIntervalMs??1e3),o=Math.max(a,n.maxIntervalMs??8e3),s=n.backoffFactor??1.5,d=n.timeoutMs??3e5,u=n.signal,m=Date.now()+d,y=a,r;for(;;){Oe(u);let i=await t();if(i.status!==r&&(r=i.status,e(i)),Ne(i.status))return i;let g=m-Date.now();if(g<=0)return i;await De(Math.min(y,g),u),y=Math.min(y*s,o)}}function Oe(t){if(t?.aborted)throw new S("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1})}function De(t,e){return new Promise((n,a)=>{let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new S("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1}))};if(e){if(e.aborted){clearTimeout(o),s();return}e.addEventListener("abort",s,{once:!0})}})}var Fe=Object.freeze(["dev","production","sandbox"]);function We(t){t.appId||l("appId is required"),t.clientId||l("clientId is required"),t.clientSecret||l("clientSecret is required");let e=t.environment;e!==void 0&&!Fe.includes(e)&&l("environment must be 'dev', 'production', or 'sandbox' ('sandbox' is the documented public test environment name and targets the same dev endpoints \u2014 ADR-0077). 'staging' and the former 'custom' selector are retired: pass explicit apiBaseUrl and hostedConnectUrl overrides (valid with any environment) for a local, private, or staging deployment. See https://docs.facto.to/reference/sdk"),t.transport!==void 0&&t.fetch!==void 0&&l("provide either transport or fetch, not both"),t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0)&&l("timeoutMs must be a positive safe integer");let n=t.apiBaseUrl?v(t.apiBaseUrl,W,"apiBaseUrl",!1):void 0,a=t.hostedConnectUrl?v(t.hostedConnectUrl,T,"hostedConnectUrl",!0):void 0;n!==void 0&&a!==void 0&&n!==a&&l("apiBaseUrl and hostedConnectUrl target different Facto environments");let o=Pe(t.clientId),s=e??o??n??a;s===void 0&&l("environment could not be resolved: pass it explicitly as 'dev', 'production', or 'sandbox' ('sandbox' is the documented public test environment name and targets the same dev endpoints \u2014 ADR-0077). It is normally derived from clientId, but this one carries no published keyspace: dev credentials are issued as dev_mcid_/dev_pspid_/dev_cpid_ and production credentials as mcid_/pspid_/cpid_. Internal (lab_/staging_/test_) and legacy (sandbox_) credentials never derive a published environment. See https://docs.facto.to/reference/sdk");let d=F(s);e!==void 0&&o!==void 0&&o!==d&&l(`environment '${e}' conflicts with the clientId keyspace, which is ${o} material`);for(let r of[n,a])r!==void 0&&r!==d&&l("environment selector conflicts with a published Facto endpoint");let u=J(t.apiBaseUrl??W[d]),m=J(t.hostedConnectUrl??T[d]),y=v(u,W,"apiBaseUrl",!1);return v(m,T,"hostedConnectUrl",!0),qe(t.clientId,y),{appId:t.appId,clientId:t.clientId,clientSecret:t.clientSecret,environment:s,apiBaseUrl:u,hostedConnectUrl:m,transport:t.transport??t.fetch??((r,i)=>globalThis.fetch(r,i)),...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.retry===void 0?{}:{retry:t.retry},...t.signal===void 0?{}:{signal:t.signal}}}function N(t,e){F(t.environment)!=="dev"&&l(`${e} is available only in the sandbox/dev environment`)}function ze(t){F(t.environment)!=="dev"&&l("sendWebhookTestDelivery is available only in the sandbox/dev environment")}function I(t,e,n){(typeof t!="string"||!new RegExp(`^${e}[A-Za-z0-9_-]+$`).test(t))&&l(`${n} must be an opaque ${e} reference`)}function ee(t){I(t,"ul_","userLinkRef")}function He(t){(typeof t!="string"||!/^we_[A-Za-z0-9]+$/.test(t))&&l("webhookEndpointId must be an opaque we_ reference")}function te(t){(typeof t!="object"||t===null||t.currency!=="USDC"||typeof t.amount!="string"||!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(t.amount))&&l("Dev amount must be a USDC decimal with at most six fractional digits")}function $e(t){(typeof t!="string"||!pe.includes(t))&&l("unknown Dev simulation scenario")}function ne(t){(typeof t!="string"||t.trim()!==t||t.length<16||t.length>255)&&l("idempotencyKey must be 16 to 255 non-whitespace-trimmed characters")}function qe(t,e){let n=e==="dev",a=e==="production";t.startsWith("dev_")&&e!==void 0&&!n&&l("a dev credential can target only the sandbox/dev environment"),(n||a)&&(t.startsWith("staging_")||t.startsWith("test_")||t.startsWith("lab_")||t.startsWith("sandbox_"))&&l("internal or legacy (staging_/test_/lab_/sandbox_) credentials cannot target a published Facto environment")}function v(t,e,n,a){let o;try{o=new URL(t)}catch{l(`${n} must be an absolute URL`)}let s=o.hostname.toLowerCase().replace(/\.$/,"");for(let d of["dev","production"]){let u=new URL(e[d]);if(s!==u.hostname.toLowerCase())continue;let m=o.pathname==="/"||a&&o.pathname==="/connect";return(o.origin!==u.origin||o.username!==""||o.password!==""||!m||o.search!==""||o.hash!=="")&&l(`${n} is not the exact published ${d} endpoint`),d}}async function R(t,e,n,a,o,s={},d=[]){let u=await me(t,async()=>{let m=await Y(t,`${t.apiBaseUrl}${e}`,{method:"POST",headers:{authorization:a,"content-type":"application/json",...s},body:JSON.stringify(n)});if(!m.ok&&!d.includes(m.status))throw await j(m);return m},s["Idempotency-Key"]!==void 0);try{return o(await u.json())}catch(m){throw new S("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:m})}}async function b(t,e,n,a){let o=await me(t,async()=>{let s=await Y(t,`${t.apiBaseUrl}${e}`,{method:"GET",headers:{authorization:n}});if(!s.ok)throw await j(s);return s},!0);try{return a(await o.json())}catch(s){throw new S("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:s})}}async function re(t,e,n){let a=await Y(t,`${t.apiBaseUrl}${e}`,{method:"DELETE",headers:{authorization:n}});if(!a.ok)throw await j(a)}async function j(t){return new S("FACTO_ENGINE_REQUEST_FAILED",`Facto Engine request failed with status ${t.status}`,{retryable:t.status===429||t.status>=500,status:t.status,details:await Ft(t),retryAfterSeconds:we(t)})}function me(t,e,n){return n?Me(e,{...t.retry,signal:t.signal??t.retry?.signal}):e()}function Y(t,e,n){return t.timeoutMs===void 0?t.transport(e,{...n,signal:t.signal}):Ve(t,e,n)}function Ve(t,e,n){let a=new AbortController,o=()=>a.abort();return t.signal?.aborted?Promise.reject(new S("FACTO_REQUEST_ABORTED","Facto Engine request aborted",{retryable:!1})):(t.signal?.addEventListener("abort",o,{once:!0}),new Promise((s,d)=>{let u=setTimeout(()=>{a.abort(),d(new S("FACTO_REQUEST_ABORTED","Facto Engine request timed out",{retryable:!1}))},t.timeoutMs);t.transport(e,{...n,signal:a.signal}).then(s,d).finally(()=>{clearTimeout(u),t.signal?.removeEventListener("abort",o)})}))}function z(t,e){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))s!==void 0&&s!==""&&n.set(o,String(s));let a=n.toString();return a?`${t}?${a}`:t}function H(t,e){let n=f(t),a=n.data;if(!Array.isArray(a))throw new Error("expected data array");return{data:a.map(e),hasMore:P(n,"hasMore")}}var Be=["pending","succeeded","failed"],Ke=["requested_by_customer","duplicate","fraudulent","other"];function Je(t,e){let n=t[e];if(typeof n!="string"||!Be.includes(n))throw new Error(`expected refund status at ${e}`);return n}function je(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||!Ke.includes(n))throw new Error(`expected refund reason at ${e}`);return n}}function $(t){let e=f(t),n=je(e,"reason"),a=A(e,"merchantRefundRef");return{refundId:c(e,"refundId"),paymentId:c(e,"paymentId"),status:Je(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),...n===void 0?{}:{reason:n},...a===void 0?{}:{merchantRefundRef:a},createdAt:c(e,"createdAt")}}var Ye=["user_link.revoked","payment_authorization.activated","payment_authorization.updated","payment_authorization.revoked","checkout_session.completed","checkout_session.expired","payment.succeeded","payment.failed","refund.succeeded","refund.failed"];function Ge(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected event-type array at ${e}`);return n.map(a=>{if(typeof a!="string"||!Ye.includes(a))throw new Error(`unknown webhook event type: ${String(a)}`);return a})}function K(t){let e=f(t),n=e.status;if(n!=="enabled"&&n!=="disabled")throw new Error("expected webhook endpoint status");return{webhookEndpointId:c(e,"webhookEndpointId"),url:c(e,"url"),enabledEvents:Ge(e,"enabledEvents"),status:n,createdAt:c(e,"createdAt")}}function ae(t){let e=K(t),n=f(t);return{...e,secret:c(n,"secret")}}var D=["fixtures","synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"],Ze=["unavailable","degraded","ready"],Qe=["contract","implemented","deployed","verified"],pe=["approved","declined_setup","declined_limit","payment_failed"],Xe=["pre_admission","onchain_test_assets"],et=["accepted","processing","succeeded","failed","declined"],tt=["accepted","broadcast","confirmed","failed"];function nt(t){let e=f(t),n=e.capabilities;if(!Array.isArray(n)||n.length!==D.length)throw new Error("expected exactly six Dev capabilities");let a=n.map(rt),o=new Set(a.map(s=>s.name));if(o.size!==D.length)throw new Error("expected each Dev capability exactly once");for(let s of D)if(!o.has(s))throw new Error(`missing Dev capability: ${s}`);return{environment:x(e,"environment","dev"),contractVersion:x(e,"contractVersion","2026-07-09"),capabilities:a,checkedAt:c(e,"checkedAt")}}function rt(t){let e=f(t),n=C(e,"name",D,"Dev capability name"),a=C(e,"status",Ze,"Dev capability status"),o=C(e,"evidenceLevel",Qe,"Dev evidence level"),s=E(e,"reasonCode"),d=E(e,"verifiedAt");if(a==="ready"&&(o!=="verified"||d===null))throw new Error("ready Dev capability requires verified evidence");let u=it(e,"limits");return{name:n,status:a,evidenceLevel:o,...s===void 0?{}:{reasonCode:s},...d===void 0?{}:{verifiedAt:d},...u===void 0?{}:{limits:u}}}function at(t){let e=f(t),n=c(e,"amount");if(!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(n))throw new Error("expected Dev USDC decimal amount");return{amount:n,currency:x(e,"currency","USDC")}}function ot(t){let e=f(t);return{faucetTransferId:k(e,"faucetTransferId","sft_"),userLinkRef:k(e,"userLinkRef","ul_"),amount:at(e.amount),status:C(e,"status",tt,"Dev faucet status"),createdAt:c(e,"createdAt")}}function oe(t){let e=f(t);return{simulationId:k(e,"simulationId","sim_"),scenario:C(e,"scenario",pe,"Dev scenario"),executionMode:C(e,"executionMode",Xe,"Dev execution mode"),status:C(e,"status",et,"Dev simulation status"),reasonCode:q(e,"reasonCode"),authorizationRef:q(e,"authorizationRef"),chargeRef:q(e,"chargeRef"),createdAt:c(e,"createdAt"),updatedAt:c(e,"updatedAt")}}function st(t){let e=f(t);return{eventId:se(e,"eventId","evt_"),deliveryId:se(e,"deliveryId","wd_"),status:x(e,"status","queued"),createdAt:c(e,"createdAt")}}function it(t,e){if(t[e]===void 0)return;let n=f(t[e]);for(let a of Object.values(n))if(a!==null&&typeof a!="string"&&typeof a!="number"&&typeof a!="boolean")throw new Error(`expected scalar Dev limit at ${e}`);return n}function k(t,e,n){let a=c(t,e);if(!new RegExp(`^${n}[A-Za-z0-9_-]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function se(t,e,n){let a=c(t,e);if(!new RegExp(`^${n}[A-Za-z0-9]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function dt(t,e){return e.userLinkRef===void 0&&e.factoServerWalletAddress===void 0&&l("payment readiness requires userLinkRef, factoServerWalletAddress, or both"),e.userLinkRef!==void 0&&I(e.userLinkRef,"ul_","userLinkRef"),e.factoServerWalletAddress!==void 0&&typeof e.factoServerWalletAddress!="string"&&l("factoServerWalletAddress must be a string"),{...e.userLinkRef===void 0?{}:{userLinkRef:e.userLinkRef},...e.factoServerWalletAddress===void 0?{}:{app_id:t.appId,facto_server_wallet_address:e.factoServerWalletAddress}}}function M(t,e){let n=t[e];if(n==null)return n;if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string or null at ${e}`);return n}function ct(t){let e=f(t),n=M(e,"cardRef"),a=M(e,"factoUserId"),o=M(e,"factoServerWalletAddress");if(n!=null&&(I(n,"card_","cardRef"),a!=null||o!=null))throw new Error("synthetic Dev links must not expose canonical identity");return{appId:c(e,"appId"),userLinkRef:k(e,"userLinkRef","ul_"),grantStatus:c(e,"grantStatus"),pipelineReady:P(e,"pipelineReady"),scopes:Dt(e,"scopes"),...n===void 0?{}:{cardRef:n},...a===void 0?{}:{factoUserId:a},...o===void 0?{}:{factoServerWalletAddress:o}}}function ut(t){let e=f(t),n=P(e,"pipelineReady"),a=e.notReadyReason,o=a==null?a:C(e,"notReadyReason",Q,"payment readiness not-ready reason");if(n&&o!==void 0&&o!==null)throw new Error("expected notReadyReason only when pipelineReady is false");let s=M(e,"factoUserId"),d=M(e,"factoServerWalletAddress");return{appId:c(e,"appId"),userLinkRef:k(e,"userLinkRef","ul_"),selectedPipelineId:c(e,"selectedPipelineId"),chainId:ye(e,"chainId"),protocolId:c(e,"protocolId"),assetSymbol:c(e,"assetSymbol"),spendMode:c(e,"spendMode"),pipelineReady:n,...o===void 0?{}:{notReadyReason:o},...s===void 0?{}:{factoUserId:s},...d===void 0?{}:{factoServerWalletAddress:d}}}function lt(t){let e=f(t);return{sessionId:c(e,"sessionId"),checkoutUrl:c(e,"checkoutUrl"),status:x(e,"status","pending"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:E(e,"orderRef")}}function mt(t){let e=f(t);return{sessionId:c(e,"sessionId"),status:Tt(e,"status"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:E(e,"orderRef"),chargeId:E(e,"chargeId"),confirmedAt:E(e,"confirmedAt")}}function ie(t){let e=f(t),n=A(e,"mandateId"),a=A(e,"userLinkRef");return{sessionId:c(e,"sessionId"),authorizationUrl:c(e,"authorizationUrl"),status:Lt(e,"status"),...n===void 0?{}:{mandateId:n},...a===void 0?{}:{userLinkRef:a},expiresAt:c(e,"expiresAt"),state:c(e,"state")}}function de(t){let e=f(t),n=A(e,"expiresAt");return{mandateId:c(e,"mandateId"),appId:c(e,"appId"),status:xt(e,"status"),allowedUseCases:Ot(e,"allowedUseCases"),limits:St(e.limits),paymentPath:Rt(e.paymentPath),createdAt:c(e,"createdAt"),...n===void 0?{}:{expiresAt:n}}}var pt="direct",ft="defaultPaymentOptionId";function yt(t){let e=f(t);he(e,"payment options");let n=e.paymentOptions;if(!Array.isArray(n))throw new Error("expected paymentOptions array");let a=n.map(Ct).filter(d=>d.settlementPath===pt),o=At(e,ft),s=gt(a,o);return{paymentOptions:a,...s===void 0?{}:{selectedPaymentOptionId:s}}}function gt(t,e){return e!==void 0&&t.some(a=>a.paymentOptionId===e)?e:(t.find(a=>a.ready)??t[0])?.paymentOptionId}function ht(t){let e=A(t,"settlementPath"),n=A(t,"spendMode"),a=e??n;if(a===void 0)throw new Error("expected settlementPath or the deprecated spendMode on a payment option");return{settlementPath:a,spendMode:n??a}}function Ct(t){let e=f(t);he(e,"payment option");let n=A(e,"blockingReason"),a=c(e,"assetSymbol"),o=c(e,"chainLabel"),s=c(e,"protocolLabel"),{settlementPath:d,spendMode:u}=ht(e);return{paymentOptionId:fe(e,"paymentOptionId"),label:bt({assetSymbol:a,protocolLabel:s,chainLabel:o},c(e,"label")),ready:P(e,"ready"),isDefault:P(e,"isDefault"),chainId:ye(e,"chainId"),chainLabel:o,protocolLabel:s,assetSymbol:a,spendMode:u,settlementPath:d,...n===void 0?{}:{blockingReason:n}}}function bt(t,e){let n=[t.assetSymbol,t.protocolLabel,t.chainLabel].map(a=>a.trim()).filter(a=>a.length>0);return n.length>0?n.join(" \xB7 "):e}function U(t){let e=f(t),n=A(e,"chargeId"),a=A(e,"txHash"),o=Ut(e,"declineReason"),s=_t(e,"finalityEtaSeconds"),d=A(e,"terminalAt"),u=A(e,"updatedAt");return{paymentId:c(e,"paymentId"),mandateId:c(e,"mandateId"),merchantPaymentRef:c(e,"merchantPaymentRef"),status:Nt(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),useCase:Mt(e,"useCase"),...n===void 0?{}:{chargeId:n},...a===void 0?{}:{txHash:a},...o===void 0?{}:{declineReason:o},...s===void 0?{}:{finalityEtaSeconds:s},...d===void 0?{}:{terminalAt:d},createdAt:c(e,"createdAt"),...u===void 0?{}:{updatedAt:u}}}function St(t){let e=f(t);return{perTxAmount:c(e,"perTxAmount"),periodAmount:c(e,"periodAmount"),period:kt(e,"period")}}function Rt(t){let e=f(t),n=A(e,"blockingReason");return{ready:P(e,"ready"),summary:c(e,"summary"),...n===void 0?{}:{blockingReason:n}}}function f(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("expected object");return t}function c(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}function A(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}}function fe(t,e){let n=c(t,e);if(!n.startsWith("fpo_"))throw new Error(`expected opaque Facto payment option id at ${e}`);return n}function At(t,e){if(!(t[e]===void 0||t[e]===null))return fe(t,e)}function x(t,e,n){if(t[e]!==n)throw new Error(`expected ${n} at ${e}`);return n}function P(t,e){let n=t[e];if(typeof n!="boolean")throw new Error(`expected boolean at ${e}`);return n}function ye(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}function _t(t,e){let n=t[e];if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}}var It=["pending","charged","expired","cancelled"],ge=["immediate","recurring","top_up","metered"],vt=["daily","weekly","monthly"],Et=["pending","active","paused","revoked","expired","suspended"],Pt=["created","authorized","declined","expired"],wt=["accepted","declined","charging","finalizing","succeeded","paid_via_coverage","failed","canceled"];function Tt(t,e){let n=t[e];if(typeof n!="string"||!It.includes(n))throw new Error(`expected checkout status at ${e}`);return n}function Mt(t,e){return C(t,e,ge,"mandate use case")}function kt(t,e){return C(t,e,vt,"mandate limit period")}function xt(t,e){return C(t,e,Et,"mandate status")}function Lt(t,e){return C(t,e,Pt,"mandate authorization status")}function Nt(t,e){return C(t,e,wt,"mandate payment status")}function Ut(t,e){if(t[e]!==void 0)return C(t,e,Z,"mandate decline reason")}function Ot(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected mandate use case array at ${e}`);return n.map(a=>{if(typeof a!="string"||!ge.includes(a))throw new Error(`expected mandate use case array at ${e}`);return a})}function C(t,e,n,a){let o=t[e];if(typeof o!="string"||!n.includes(o))throw new Error(`expected ${a} at ${e}`);return o}function E(t,e){let n=t[e];if(n==null)return null;if(typeof n!="string")throw new Error(`expected string or null at ${e}`);return n}function q(t,e){let n=t[e];if(n===null)return null;if(typeof n!="string")throw new Error(`expected required string or null at ${e}`);return n}function Dt(t,e){let n=t[e];if(!Array.isArray(n)||n.some(a=>typeof a!="string"))throw new Error(`expected string array at ${e}`);return n}function he(t,e){let a=["userId","factoUserId","cardId","routeId","vaultKind","serverWallet","factoServerWalletAddress","pathSnapshot","paymentPathSnapshot","pipelineId","selectedPipelineId","paymentRouteId","routeSelector"].find(o=>t[o]!==void 0);if(a)throw new Error(`unsafe ${e} field: ${a}`)}async function Ft(t){try{return await t.json()}catch{return await t.text().catch(()=>null)}}function J(t){return t.replace(/\/+$/,"")}function l(t){throw new S("FACTO_CONFIG_INVALID",t,{retryable:!1})}function Wt(t){let e=globalThis.btoa;if(e)return e(t);let n=globalThis.Buffer;if(n)return n.from(t).toString("base64");l("No base64 encoder is available in this runtime")}function on(t,e,n=Math.floor(Date.now()/1e3)){e||l("webhook secret is required"),(!Number.isSafeInteger(n)||n<0)&&l("webhook timestamp must be a non-negative safe integer");let a=le("sha256",e).update(`${n}.`).update(t).digest("hex");return`t=${n},v1=${a}`}function sn(t,e,n,a=300){n||l("webhook secret is required");let o=e.split(",").map(m=>m.trim()),s,d=[];for(let m of o){let y=m.indexOf("=");if(y===-1)continue;let r=m.slice(0,y),i=m.slice(y+1);r==="t"?s=Number(i):r==="v1"&&d.push(i)}if(s===void 0||!Number.isFinite(s)||Math.abs(Date.now()/1e3-s)>a||d.length===0)return!1;let u=le("sha256",n).update(`${s}.`).update(t).digest();return d.some(m=>{let y;try{y=Buffer.from(m,"hex")}catch{return!1}return y.length===u.length&&ve(y,u)})}var p=class extends Error{code;details;constructor(e,n,a={}){super(n),this.name="FactoConnectHintError",this.code=e,this.details=a.details}},zt="facto";async function dn(t){if(t===null||typeof t!="object")throw new p("FACTO_HINT_INPUT_INVALID","verifyFactoCardProgramConnectHint requires an input object");let e=B(t.connectHint,"connectHint"),n=B(t.audience,"audience"),a=t.issuer===void 0?zt:B(t.issuer,"issuer"),o=Yt(t.clockToleranceSeconds),s=Math.floor(Gt(t.now)/1e3),{headerB64:d,payloadB64:u,signature:m}=Ht(e),y=G(ce(d,"header"),"FACTO_HINT_MALFORMED","connect hint header");if(y.alg!=="EdDSA")throw new p("FACTO_HINT_UNSUPPORTED_ALG","connect hint JWS alg must be EdDSA",{details:{alg:y.alg}});let r=typeof y.kid=="string"?y.kid:void 0,i=await $t(t.jwks),g=Kt(i,r),L=Qt(`${d}.${u}`);if(!await Jt(L,m,g))throw new p("FACTO_HINT_SIGNATURE_INVALID","connect hint signature does not verify against the Facto JWKS");let _=jt(ce(u,"payload"));if(_.iss!==a)throw new p("FACTO_HINT_ISSUER_MISMATCH","connect hint issuer mismatch",{details:{expected:a,actual:_.iss}});if(_.aud!==n)throw new p("FACTO_HINT_AUDIENCE_MISMATCH","connect hint audience mismatch",{details:{expected:n,actual:_.aud}});if(s>_.exp+o)throw new p("FACTO_HINT_EXPIRED","connect hint has expired",{details:{exp:_.exp,now:s}});return{programRef:_.program_ref,pairwiseSubject:_.sub,nonce:_.nonce,expiresAt:new Date(_.exp*1e3).toISOString()}}function Ht(t){let e=t.split(".");if(e.length!==3)throw new p("FACTO_HINT_MALFORMED","connect hint is not a compact JWS (expected three segments)");let[n,a,o]=e;if(!n||!a||!o)throw new p("FACTO_HINT_MALFORMED","connect hint has an empty JWS segment");return{headerB64:n,payloadB64:a,signature:Ce(o,"signature")}}function ce(t,e){let n=new TextDecoder().decode(Ce(t,e));try{return JSON.parse(n)}catch(a){throw new p("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid JSON`,{details:a})}}async function $t(t){if(t==null)throw new p("FACTO_HINT_INPUT_INVALID","jwks is required");return V(typeof t=="function"?await t():typeof t=="string"?await Vt(t):t)}var qt=5e3,O=64*1024;async function Vt(t){let e;try{e=new URL(t)}catch{throw new p("FACTO_HINT_JWKS_INVALID",`JWKS url is not a valid URL: ${t}`)}if(e.protocol!=="https:")throw new p("FACTO_HINT_JWKS_INVALID",`JWKS url must use https: (got ${e.protocol})`,{details:{protocol:e.protocol}});let n=new AbortController,a=setTimeout(()=>n.abort(),qt),o,s;try{try{o=await fetch(t,{method:"GET",headers:{accept:"application/json"},redirect:"follow",signal:n.signal})}catch(u){throw new p("FACTO_HINT_JWKS_INVALID",`failed to fetch Facto JWKS from ${t}`,{details:u})}if(!o.ok)throw new p("FACTO_HINT_JWKS_INVALID",`Facto JWKS request failed with status ${o.status}`,{details:{status:o.status}});let d=Number(o.headers.get("content-length"));if(Number.isFinite(d)&&d>O)throw new p("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${O} bytes`,{details:{contentLength:d}});try{s=await o.text()}catch(u){throw new p("FACTO_HINT_JWKS_INVALID","Facto JWKS response could not be read",{details:u})}}finally{clearTimeout(a)}if(s.length>O)throw new p("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${O} bytes`,{details:{bytes:s.length}});try{return JSON.parse(s)}catch(d){throw new p("FACTO_HINT_JWKS_INVALID","Facto JWKS response was not valid JSON",{details:d})}}function V(t){let e=G(t,"FACTO_HINT_JWKS_INVALID","JWKS");if(!Array.isArray(e.keys))throw new p("FACTO_HINT_JWKS_INVALID",'JWKS "keys" must be an array');return{keys:e.keys.map(Bt)}}function Bt(t){let e=typeof t=="object"&&t!==null?t:{};return{kty:typeof e.kty=="string"?e.kty:"",crv:typeof e.crv=="string"?e.crv:"",x:typeof e.x=="string"?e.x:"",...typeof e.kid=="string"?{kid:e.kid}:{},...typeof e.alg=="string"?{alg:e.alg}:{},...typeof e.use=="string"?{use:e.use}:{}}}function Kt(t,e){let n=t.keys.filter(a=>a.kty==="OKP"&&a.crv==="Ed25519"&&a.x.length>0);if(n.length===0)throw new p("FACTO_HINT_JWKS_INVALID","Facto JWKS has no usable Ed25519 signing key");if(e!==void 0){let a=n.filter(o=>o.kid===e);if(a.length>0)return a}return n}async function Jt(t,e,n){let a=Xt();for(let o of n){let s;try{s=await a.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:o.x},{name:"Ed25519"},!1,["verify"])}catch{continue}try{if(await a.verify({name:"Ed25519"},s,e,t))return!0}catch{continue}}return!1}function jt(t){let e=G(t,"FACTO_HINT_CLAIMS_INVALID","connect hint claims");return{iss:w(e,"iss"),aud:w(e,"aud"),sub:w(e,"sub"),program_ref:w(e,"program_ref"),nonce:w(e,"nonce"),iat:ue(e,"iat"),exp:ue(e,"exp")}}function B(t,e){if(typeof t!="string"||t.length===0)throw new p("FACTO_HINT_INPUT_INVALID",`${e} must be a non-empty string`);return t}function Yt(t){if(t===void 0)return 0;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new p("FACTO_HINT_INPUT_INVALID","clockToleranceSeconds must be a non-negative finite number");return t}function Gt(t){if(t===void 0)return Date.now();if(t instanceof Date){let e=t.getTime();if(Number.isNaN(e))throw new p("FACTO_HINT_INPUT_INVALID","now is an invalid Date");return e}if(typeof t=="number"&&Number.isFinite(t))return t;throw new p("FACTO_HINT_INPUT_INVALID","now must be a Date or unix milliseconds number")}function G(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new p(e,`${n} must be a JSON object`);return t}function w(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new p("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a non-empty string`);return n}function ue(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new p("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a finite number`);return n}function Ce(t,e){if(!/^[A-Za-z0-9_-]*$/.test(t))throw new p("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`);let n=t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4);return Zt(n,e)}function Zt(t,e){let n=globalThis.atob;if(n){let o;try{o=n(t)}catch(d){throw new p("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`,{details:d})}let s=new Uint8Array(o.length);for(let d=0;d<o.length;d+=1)s[d]=o.charCodeAt(d);return s}let a=globalThis.Buffer;if(a)return new Uint8Array(a.from(t,"base64"));throw new p("FACTO_HINT_INPUT_INVALID","No base64 decoder is available in this runtime")}function Qt(t){let e=new TextEncoder().encode(t),n=new Uint8Array(e.length);return n.set(e),n}function Xt(){let t=globalThis.crypto;if(t?.subtle)return t.subtle;throw new p("FACTO_HINT_INPUT_INVALID","Web Crypto (crypto.subtle) is not available in this runtime")}var cn=xe;export{W as FACTO_CONNECT_API_BASE_URLS,T as FACTO_CONNECT_HOSTED_URLS,p as FactoConnectHintError,S as FactoConnectServerError,be as PSP_CAPABILITY_TEMPLATES,Re as PSP_CREDENTIAL_KEYSPACE,X as PSP_CREDENTIAL_SCOPES,Ae as PSP_PARTNER_ROLE_TYPE,ke as buildHostedConnectUrl,Se as carriesMoneyVerb,xe as createFactoConnectServer,cn as default,Pe as factoConnectEnvironmentFromClientId,Ne as isTerminalMandatePaymentStatus,on as signWebhookPayload,Ie as subMerchantOf,dn as verifyFactoCardProgramConnectHint,sn as verifyWebhookSignature,Me as withServerRetry,_e as withSubMerchant};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@facto-to/connect",
3
- "version": "0.0.1-beta1",
3
+ "version": "0.0.1-beta2",
4
4
  "description": "Facto Connect SDK for linking partner users to Facto accounts and payment routes.",
5
5
  "homepage": "https://facto.to",
6
6
  "author": "Facto (https://facto.to)",
@@ -89,7 +89,7 @@
89
89
  "prepublishOnly": "npm run build"
90
90
  },
91
91
  "devDependencies": {
92
- "@facto-to/chains": "0.0.1-beta1",
92
+ "@facto-to/chains": "0.0.1-beta2",
93
93
  "@facto-to/engine-wire": "0.2.0",
94
94
  "@types/node": "^25.9.3",
95
95
  "jsdom": "^27.1.0",