@facto-to/connect 0.0.1-beta.5 → 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 +1 -84
- package/dist/browser/index.cjs +5 -5
- package/dist/browser/index.d.cts +31 -1
- package/dist/browser/index.d.ts +31 -1
- package/dist/browser/index.js +4 -4
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.d.cts +303 -9
- package/dist/server/index.d.ts +303 -9
- package/dist/server/index.js +1 -1
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.d.cts +12 -1
- package/dist/testing/index.d.ts +12 -1
- package/dist/testing/index.js +1 -1
- package/package.json +5 -8
- package/dist/index.d-DE9GmLfU.d.cts +0 -114
- package/dist/index.d-DE9GmLfU.d.ts +0 -114
package/dist/server/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var H=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Ne=Object.prototype.hasOwnProperty;var Oe=(t,e)=>{for(var n in e)H(t,n,{get:e[n],enumerable:!0})},De=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ue(e))!Ne.call(t,o)&&o!==n&&H(t,o,{get:()=>e[o],enumerable:!(a=Le(e,o))||a.enumerable});return t};var Fe=t=>De(H({},"__esModule",{value:!0}),t);var yn={};Oe(yn,{FACTO_CONNECT_API_BASE_URLS:()=>F,FACTO_CONNECT_HOSTED_URLS:()=>v,FactoConnectHintError:()=>m,FactoConnectServerError:()=>R,PSP_CAPABILITY_TEMPLATES:()=>re,PSP_CREDENTIAL_KEYSPACE:()=>oe,PSP_CREDENTIAL_SCOPES:()=>q,PSP_PARTNER_ROLE_TYPE:()=>se,buildHostedConnectUrl:()=>Ae,carriesMoneyVerb:()=>ae,createFactoConnectServer:()=>_e,default:()=>fn,factoConnectEnvironmentFromClientId:()=>Re,isTerminalMandatePaymentStatus:()=>Ie,signWebhookPayload:()=>Gt,subMerchantOf:()=>de,verifyFactoCardProgramConnectHint:()=>Qt,verifyWebhookSignature:()=>Zt,withServerRetry:()=>be,withSubMerchant:()=>ie});module.exports=Fe(yn);var U=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","funding_source_not_authorized","payment_option_not_pinned","settlement_reverted","idempotency_conflict"];var te=["payment_route_not_provisioned","protocol_config_incomplete"],ne=["account_default","mandate_pinned"];var re=["psp_connect_sandbox","psp_mandate_sandbox","psp_billing_sandbox"],q={psp_connect_sandbox:["readiness.read","authorizations.request"],psp_mandate_sandbox:["readiness.read","authorizations.request","payments.execute","refunds.execute"],psp_billing_sandbox:["readiness.read","authorizations.request","payments.execute","refunds.execute","checkout.write"]};function ae(t){return q[t].includes("payments.execute")}var oe={dev:{clientIdPrefix:"dev_pspid_",clientSecretPrefix:"dev_pspsk_"},test:{clientIdPrefix:"test_pspid_"},lab:{clientIdPrefix:"lab_pspid_"}},se="psp";function ie(t,e){return{...t,...e.ref===void 0?{}:{subMerchantRef:e.ref},...e.displayName===void 0?{}:{subMerchantDisplayName:e.displayName}}}function de(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"}),v=Object.freeze({dev:"https://dev.facto.to",production:"https://app.facto.to"}),We=Object.freeze({dev:Object.freeze(["dev_mcid_","dev_pspid_","dev_cpid_"]),production:Object.freeze(["mcid_","pspid_","cpid_"])});function Re(t){if(typeof t=="string"){for(let e of["dev","production"])for(let n of We[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"}),R=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 ze(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 He(t,e){return t<=0?Promise.resolve():new Promise((n,a)=>{if(e?.aborted){a(new R("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new R("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};e?.addEventListener("abort",s,{once:!0})})}async function be(t,e={}){let n=e.maxRetries??2,a=e.baseDelayMs??200,o=e.maxDelayMs??5e3,s=e.respectRetryAfter??!0,d=e.sleep??He,u=0;for(;;)try{return await t()}catch(p){if(!(p instanceof R)||!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)),y=i*.25*Math.random(),E=r??i+y;e.onRetry?.({attempt:u,error:p,delayMs:E}),await d(E,e.signal)}}function Ae(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)"),t.merchantOrigin||l("merchantOrigin is required and has no implicit default: pass the origin of the browsing context that will open this URL (the merchant page origin for this single call)");let e=jt(t.merchantOrigin),n=G(t.hostedConnectUrl);P(n,v,"hostedConnectUrl",!0);let a=new URL("/connect",`${n}/`);a.searchParams.set("external_app_id",t.appId),a.searchParams.set("external_state",t.state),a.searchParams.set("external_nonce",t.nonce),a.searchParams.set("external_origin",e);let o=new URLSearchParams;t.customerEmail!==void 0&&o.set("customer_email",t.customerEmail),t.customerUsername!==void 0&&o.set("customer_username",t.customerUsername);let s=o.toString();return s&&(a.hash=s),a.toString()}function _e(t){let e=Je(t),n=`Basic ${Yt(`${e.clientId}:${e.clientSecret}`)}`,a=(r,i)=>b(e,r,{code:i.code,state:i.state,nonce:i.nonce},n,ht),o=(r,i)=>b(e,r,gt(e,i),n,St),s=(r,i)=>b(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,ge),d=(r,i)=>C(e,`${r}/${encodeURIComponent(i)}`,n,ge),u=(r,i)=>C(e,`${r}/${encodeURIComponent(i)}`,n,he),p=(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),b(e,r,y,n,O,{"Idempotency-Key":i.idempotencyKey},[402])},f=(r,i)=>C(e,`${r}/${encodeURIComponent(i)}`,n,O);return{createHostedConnectUrl(r){let i=r.hostedConnectUrl??e.hostedConnectUrl;if(r.hostedConnectUrl!==void 0){let y=P(r.hostedConnectUrl,v,"hostedConnectUrl",!0);y!==void 0&&y!==z(e.environment)&&l("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,merchantOrigin:r.merchantOrigin})},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 f(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"),b(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,Ct)},getCheckoutSession(r){return C(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&&I(r.userLinkRef,"ul_","userLinkRef"),b(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,_t)},createMandatePayment(r){return p(h.payments,r)},getMandatePayment(r){return f(h.payments,r)},onStatus(r,i,y){return $e(()=>C(e,`${h.payments}/${encodeURIComponent(r)}`,n,O),i,y)},revokeUserLink(r){return me(e,`/api/merchant/user-links/${encodeURIComponent(r)}`,n)},listMerchantPayments(r={}){return C(e,$("/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 C(e,$("/api/merchant/payment-authorizations",{limit:r.limit,startingAfter:r.startingAfter,userLinkRef:r.userLinkRef,status:r.status}),n,i=>V(i,he))},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),b(e,"/api/merchant/refunds",i,n,B,{"Idempotency-Key":r.idempotencyKey},[402])},getRefund(r){return C(e,`/api/merchant/refunds/${encodeURIComponent(r)}`,n,B)},listRefunds(r={}){return C(e,$("/api/merchant/refunds",{limit:r.limit,startingAfter:r.startingAfter,paymentId:r.paymentId}),n,i=>V(i,B))},createWebhookEndpoint(r){return b(e,"/api/merchant/webhook-endpoints",{url:r.url,enabledEvents:r.enabledEvents},n,pe)},listWebhookEndpoints(){return C(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(Y)})},getWebhookEndpoint(r){return C(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n,Y)},deleteWebhookEndpoint(r){return me(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n)},rotateWebhookSecret(r){return b(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}/rotate-secret`,{},n,pe)},getDevCapabilities(){return N(e,"getDevCapabilities"),C(e,"/api/dev/capabilities",n,ut)},fundDevUser(r){return N(e,"fundDevUser"),ce(r.userLinkRef),ue(r.amount),le(r.idempotencyKey),b(e,"/api/dev/faucet/usdc",{userLinkRef:r.userLinkRef,amount:r.amount},n,pt,{"Idempotency-Key":r.idempotencyKey})},simulateDevCharge(r){return N(e,"simulateDevCharge"),ce(r.userLinkRef),r.cardRef!==void 0&&I(r.cardRef,"card_","cardRef"),ue(r.amount),Ge(r.scenario),r.merchantReference!==void 0&&(typeof r.merchantReference!="string"||r.merchantReference.length>120)&&l("merchantReference must not exceed 120 characters"),le(r.idempotencyKey),b(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,fe,{"Idempotency-Key":r.idempotencyKey})},getDevSimulation(r){return N(e,"getDevSimulation"),I(r,"sim_","simulationId"),C(e,`/api/dev/simulations/${encodeURIComponent(r)}`,n,fe)},sendWebhookTestDelivery(r){return je(e),Ye(r.webhookEndpointId),r.message!==void 0&&(typeof r.message!="string"||r.message.length>120)&&l("webhook test message must not exceed 120 characters"),b(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r.webhookEndpointId)}/test-delivery`,r.message===void 0?{}:{message:r.message},n,ft)}}}var qe=new Set(["declined","succeeded","paid_via_coverage","failed","canceled"]);function Ie(t){return qe.has(t)}async function $e(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,f=a,r;for(;;){Ve(u);let i=await t();if(i.status!==r&&(r=i.status,e(i)),Ie(i.status))return i;let y=p-Date.now();if(y<=0)return i;await Be(Math.min(f,y),u),f=Math.min(f*s,o)}}function Ve(t){if(t?.aborted)throw new R("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1})}function Be(t,e){return new Promise((n,a)=>{let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new R("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 Ke=Object.freeze(["dev","production","sandbox"]);function Je(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&&!Ke.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/merchants/quickstart"),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?P(t.apiBaseUrl,F,"apiBaseUrl",!1):void 0,a=t.hostedConnectUrl?P(t.hostedConnectUrl,v,"hostedConnectUrl",!0):void 0;n!==void 0&&a!==void 0&&n!==a&&l("apiBaseUrl and hostedConnectUrl target different Facto environments");let o=Re(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/merchants/quickstart");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??v[d]),f=P(u,F,"apiBaseUrl",!1);return P(p,v,"hostedConnectUrl",!0),Ze(t.clientId,f),{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 N(t,e){z(t.environment)!=="dev"&&l(`${e} is available only in the sandbox/dev environment`)}function je(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 ce(t){I(t,"ul_","userLinkRef")}function Ye(t){(typeof t!="string"||!/^we_[A-Za-z0-9]+$/.test(t))&&l("webhookEndpointId must be an opaque we_ reference")}function ue(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 Ge(t){(typeof t!="string"||!ve.includes(t))&&l("unknown Dev simulation scenario")}function le(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 Ze(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 P(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 b(t,e,n,a,o,s={},d=[]){return Pe(t,()=>X(t,`${t.apiBaseUrl}${e}`,{method:"POST",headers:{authorization:a,"content-type":"application/json",...s},body:JSON.stringify(n)},async u=>{if(!u.ok&&!d.includes(u.status))throw await Z(u);return Ee(u,o)}),s["Idempotency-Key"]!==void 0)}async function C(t,e,n,a){return Pe(t,()=>X(t,`${t.apiBaseUrl}${e}`,{method:"GET",headers:{authorization:n}},async o=>{if(!o.ok)throw await Z(o);return Ee(o,a)}),!0)}async function Ee(t,e){try{return e(await t.json())}catch(n){throw new R("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:n})}}async function me(t,e,n){return X(t,`${t.apiBaseUrl}${e}`,{method:"DELETE",headers:{authorization:n}},async a=>{if(!a.ok)throw await Z(a)})}async function Z(t){return new R("FACTO_ENGINE_REQUEST_FAILED",`Facto Engine request failed with status ${t.status}`,{retryable:t.status===429||t.status>=500,status:t.status,details:await Jt(t),retryAfterSeconds:ze(t)})}function Pe(t,e,n){return n?be(e,{...t.retry,signal:t.signal??t.retry?.signal}):e()}async function X(t,e,n,a){return t.timeoutMs===void 0&&t.signal===void 0?a(await t.transport(e,n)):Xe(t,e,n,a)}function Xe(t,e,n,a){let o=new AbortController;return t.signal?.aborted?Promise.reject(new R("FACTO_REQUEST_ABORTED","Facto Engine request aborted",{retryable:!1})):new Promise((s,d)=>{let u=!1,p,f=()=>{p!==void 0&&clearTimeout(p),t.signal?.removeEventListener("abort",i)},r=y=>{u||(u=!0,f(),d(new R("FACTO_REQUEST_ABORTED",y,{retryable:!1})),o.abort())},i=()=>r("Facto Engine request aborted");t.signal?.addEventListener("abort",i,{once:!0}),t.timeoutMs!==void 0&&(p=setTimeout(()=>r("Facto Engine request timed out"),t.timeoutMs)),(async()=>{try{let y=await t.transport(e,{...n,signal:o.signal});if(u){y.body?.cancel().catch(()=>{});return}let E=await a(y);u||(u=!0,f(),s(E))}catch(y){u||(u=!0,f(),d(y))}})()})}function $(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=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 Qe=["pending","succeeded","failed"],et=["requested_by_customer","duplicate","fraudulent","other"];function tt(t,e){let n=t[e];if(typeof n!="string"||!Qe.includes(n))throw new Error(`expected refund status at ${e}`);return n}function nt(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||!et.includes(n))throw new Error(`expected refund reason at ${e}`);return n}}function B(t){let e=g(t),n=nt(e,"reason"),a=A(e,"merchantRefundRef");return{refundId:c(e,"refundId"),paymentId:c(e,"paymentId"),status:tt(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 rt=["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 at(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"||!rt.includes(a))throw new Error(`unknown webhook event type: ${String(a)}`);return a})}function Y(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:at(e,"enabledEvents"),status:n,createdAt:c(e,"createdAt")}}function pe(t){let e=Y(t),n=g(t);return{...e,secret:c(n,"secret")}}var W=["fixtures","synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"],ot=["unavailable","degraded","ready"],st=["contract","implemented","deployed","verified"],ve=["approved","declined_setup","declined_limit","payment_failed"],it=["pre_admission","onchain_test_assets"],dt=["accepted","processing","succeeded","failed","declined"],ct=["accepted","broadcast","confirmed","failed"];function ut(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(lt),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:L(e,"environment","dev"),contractVersion:L(e,"contractVersion","2026-07-09"),capabilities:a,checkedAt:c(e,"checkedAt")}}function lt(t){let e=g(t),n=S(e,"name",W,"Dev capability name"),a=S(e,"status",ot,"Dev capability status"),o=S(e,"evidenceLevel",st,"Dev evidence level"),s=T(e,"reasonCode"),d=T(e,"verifiedAt");if(a==="ready"&&(o!=="verified"||d===null))throw new Error("ready Dev capability requires verified evidence");let u=yt(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 mt(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:L(e,"currency","USDC")}}function pt(t){let e=g(t);return{faucetTransferId:x(e,"faucetTransferId","sft_"),userLinkRef:x(e,"userLinkRef","ul_"),amount:mt(e.amount),status:S(e,"status",ct,"Dev faucet status"),createdAt:c(e,"createdAt")}}function fe(t){let e=g(t);return{simulationId:x(e,"simulationId","sim_"),scenario:S(e,"scenario",ve,"Dev scenario"),executionMode:S(e,"executionMode",it,"Dev execution mode"),status:S(e,"status",dt,"Dev simulation status"),reasonCode:K(e,"reasonCode"),authorizationRef:K(e,"authorizationRef"),chargeRef:K(e,"chargeRef"),createdAt:c(e,"createdAt"),updatedAt:c(e,"updatedAt")}}function ft(t){let e=g(t);return{eventId:ye(e,"eventId","evt_"),deliveryId:ye(e,"deliveryId","wd_"),status:L(e,"status","queued"),createdAt:c(e,"createdAt")}}function yt(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 x(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 ye(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 gt(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 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 ht(t){let e=g(t),n=k(e,"cardRef"),a=k(e,"factoUserId"),o=k(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:x(e,"userLinkRef","ul_"),grantStatus:c(e,"grantStatus"),pipelineReady:w(e,"pipelineReady"),scopes:Bt(e,"scopes"),...n===void 0?{}:{cardRef:n},...a===void 0?{}:{factoUserId:a},...o===void 0?{}:{factoServerWalletAddress:o}}}function St(t){let e=g(t),n=w(e,"pipelineReady"),a=e.notReadyReason,o=a==null?a:S(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=k(e,"factoUserId"),d=k(e,"factoServerWalletAddress");return Kt(e,"payment readiness"),{appId:c(e,"appId"),userLinkRef:x(e,"userLinkRef","ul_"),readinessScope:S(e,"readinessScope",ne,"payment readiness scope"),chainId:we(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 Ct(t){let e=g(t);return{sessionId:c(e,"sessionId"),checkoutUrl:c(e,"checkoutUrl"),status:L(e,"status","pending"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:T(e,"orderRef")}}function Rt(t){let e=g(t);return{sessionId:c(e,"sessionId"),status:Dt(e,"status"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:T(e,"orderRef"),chargeId:T(e,"chargeId"),confirmedAt:T(e,"confirmedAt")}}function ge(t){let e=g(t),n=A(e,"mandateId"),a=A(e,"userLinkRef");return{sessionId:c(e,"sessionId"),authorizationUrl:c(e,"authorizationUrl"),status:Ht(e,"status"),...n===void 0?{}:{mandateId:n},...a===void 0?{}:{userLinkRef:a},expiresAt:c(e,"expiresAt"),state:c(e,"state")}}function he(t){let e=g(t),n=A(e,"expiresAt");return{mandateId:c(e,"mandateId"),appId:c(e,"appId"),status:zt(e,"status"),allowedUseCases:Vt(e,"allowedUseCases"),limits:Tt(e.limits),paymentPath:wt(e.paymentPath),createdAt:c(e,"createdAt"),...n===void 0?{}:{expiresAt:n}}}var bt="direct",At="defaultPaymentOptionId";function _t(t){let e=g(t);ke(e,"payment options");let n=e.paymentOptions;if(!Array.isArray(n))throw new Error("expected paymentOptions array");let a=n.map(Pt).filter(d=>d.settlementPath===bt),o=Mt(e,At),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 Et(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 Pt(t){let e=g(t);ke(e,"payment option");let n=A(e,"blockingReason"),a=c(e,"assetSymbol"),o=c(e,"chainLabel"),s=c(e,"protocolLabel"),{settlementPath:d,spendMode:u}=Et(e);return{paymentOptionId:Te(e,"paymentOptionId"),label:vt({assetSymbol:a,protocolLabel:s,chainLabel:o},c(e,"label")),ready:w(e,"ready"),isDefault:w(e,"isDefault"),chainId:we(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=g(t),n=A(e,"chargeId"),a=A(e,"txHash"),o=$t(e,"declineReason"),s=kt(e,"finalityEtaSeconds"),d=A(e,"terminalAt"),u=A(e,"updatedAt");return{paymentId:c(e,"paymentId"),mandateId:c(e,"mandateId"),merchantPaymentRef:c(e,"merchantPaymentRef"),status:qt(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),useCase:Ft(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 Tt(t){let e=g(t);return{perTxAmount:c(e,"perTxAmount"),periodAmount:c(e,"periodAmount"),period:Wt(e,"period")}}function wt(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 Te(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 Mt(t,e){if(!(t[e]===void 0||t[e]===null))return Te(t,e)}function L(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 we(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}function kt(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 xt=["pending","charged","expired","cancelled"],Me=["immediate","recurring","top_up","metered"],Lt=["daily","weekly","monthly"],Ut=["pending","active","paused","revoked","expired","suspended"],Nt=["created","authorized","declined","expired"],Ot=["accepted","declined","charging","finalizing","succeeded","paid_via_coverage","failed","canceled"];function Dt(t,e){let n=t[e];if(typeof n!="string"||!xt.includes(n))throw new Error(`expected checkout status at ${e}`);return n}function Ft(t,e){return S(t,e,Me,"mandate use case")}function Wt(t,e){return S(t,e,Lt,"mandate limit period")}function zt(t,e){return S(t,e,Ut,"mandate status")}function Ht(t,e){return S(t,e,Nt,"mandate authorization status")}function qt(t,e){return S(t,e,Ot,"mandate payment status")}function $t(t,e){if(t[e]!==void 0)return S(t,e,ee,"mandate decline reason")}function Vt(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"||!Me.includes(a))throw new Error(`expected mandate use case array at ${e}`);return a})}function S(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 T(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 Bt(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 Kt(t,e){let a=["pipelineId","selectedPipelineId","paymentRouteId","routeId","routeSelector"].find(o=>t[o]!==void 0);if(a)throw new Error(`unsafe ${e} field: ${a}`)}function ke(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 Jt(t){try{return await t.json()}catch{return await t.text().catch(()=>null)}}function G(t){return t.replace(/\/+$/,"")}function jt(t){let e;try{e=new URL(t)}catch{l("merchantOrigin must be an absolute http(s) origin")}e.protocol!=="http:"&&e.protocol!=="https:"&&l("merchantOrigin must be an absolute http(s) origin");let n=e.origin;return t!==n&&t!==`${n}/`&&l("merchantOrigin must be an absolute http(s) origin"),n}function l(t){throw new R("FACTO_CONFIG_INVALID",t,{retryable:!1})}function Yt(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 Gt(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,U.createHmac)("sha256",e).update(`${n}.`).update(t).digest("hex");return`t=${n},v1=${a}`}function Zt(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 f=p.indexOf("=");if(f===-1)continue;let r=p.slice(0,f),i=p.slice(f+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,U.createHmac)("sha256",n).update(`${s}.`).update(t).digest();return d.some(p=>{let f;try{f=Buffer.from(p,"hex")}catch{return!1}return f.length===u.length&&(0,U.timingSafeEqual)(f,u)})}var m=class extends Error{code;details;constructor(e,n,a={}){super(n),this.name="FactoConnectHintError",this.code=e,this.details=a.details}},Xt="facto";async function Qt(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?Xt:j(t.issuer,"issuer"),o=cn(t.clockToleranceSeconds),s=Math.floor(un(t.now)/1e3),{headerB64:d,payloadB64:u,signature:p}=en(e),f=Q(Se(d,"header"),"FACTO_HINT_MALFORMED","connect hint header");if(f.alg!=="EdDSA")throw new m("FACTO_HINT_UNSUPPORTED_ALG","connect hint JWS alg must be EdDSA",{details:{alg:f.alg}});let r=typeof f.kid=="string"?f.kid:void 0,i=await tn(t.jwks),y=on(i,r),E=mn(`${d}.${u}`);if(!await sn(E,p,y))throw new m("FACTO_HINT_SIGNATURE_INVALID","connect hint signature does not verify against the Facto JWKS");let _=dn(Se(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 en(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:xe(o,"signature")}}function Se(t,e){let n=new TextDecoder().decode(xe(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 tn(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 rn(t):t)}var nn=5e3,D=64*1024;async function rn(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(),nn),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=Q(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(an)}}function an(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 on(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 sn(t,e,n){let a=pn();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 dn(t){let e=Q(t,"FACTO_HINT_CLAIMS_INVALID","connect hint claims");return{iss:M(e,"iss"),aud:M(e,"aud"),sub:M(e,"sub"),program_ref:M(e,"program_ref"),nonce:M(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 cn(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 un(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 Q(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 M(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 xe(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 ln(n,e)}function ln(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 mn(t){let e=new TextEncoder().encode(t),n=new Uint8Array(e.length);return n.set(e),n}function pn(){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 fn=_e;
|
|
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;
|