@facto-to/connect 0.0.1-beta.13 → 0.0.1-beta.14

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.
@@ -1 +1 @@
1
- "use strict";var P=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var H=(e,t)=>{for(var i in t)P(e,i,{get:t[i],enumerable:!0})},V=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of $(t))!Z.call(e,c)&&c!==i&&P(e,c,{get:()=>t[c],enumerable:!(s=G(t,c))||s.enumerable});return e};var B=e=>V(P({},"__esModule",{value:!0}),e);var ae={};H(ae,{MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS:()=>O,MerchantPartnerWorkspaceMockError:()=>d,createFactoConnectFixtureTransport:()=>N,createFactoTestTransport:()=>ne,createMerchantPartnerWorkspaceMock:()=>D,devFixtures:()=>y,devScenarios:()=>re,merchantDevAppFixture:()=>F,merchantFutureTemplateProjectionFixture:()=>L,merchantProductionAppNegativeFixture:()=>q});module.exports=B(ae);var O=["listMerchantWorkspaceApps","createMerchantDevApp","rotateMerchantWorkspaceCredential"],J=new Set(["merchant_connect_dev","merchant_webhook_dev"]),d=class extends Error{status;constructor(t,i){super(t),this.name="MerchantPartnerWorkspaceMockError",this.status=i}};function D(e={}){let t=[],i=(e.initialApps??[]).map(v),s=new Set(e.authenticatedSession?.scopes??[]),c=e.now??(()=>new Date),o=new Map,r=new Map,n=i.length+1;return{client:{async listMerchantWorkspaceApps({environment:p}){if(t.push({operationId:"listMerchantWorkspaceApps",method:"GET",path:"/api/partner-workspace/merchant/apps",query:{environment:p}}),p!=="dev")throw new d("Environment filter is outside the mock server-derived context.",403);return{items:i.filter(h=>h.environment===p).map(v)}},async createMerchantDevApp({idempotencyKey:p,body:h}){let g=C(p),m=I(h,["display_name","capability_template","allowed_origins"]),k=E(m.display_name,"Display name",1,160);if(!Y(m.capability_template))throw new d("Capability template is not approved for Merchant dev app creation.",400);let l={display_name:k,capability_template:m.capability_template,allowed_origins:Q(m.allowed_origins)};t.push({operationId:"createMerchantDevApp",method:"POST",path:"/api/partner-workspace/merchant/apps",headers:{"Idempotency-Key":g},body:l});let u=ee(l),w=o.get(g);if(w){if(w.fingerprint!==u)throw W("createMerchantDevApp");return v(w.response)}let x={app_id:`dev_mcid_mock_${String(n).padStart(2,"0")}`,display_name:l.display_name,environment:"dev",capability_template:l.capability_template,status:"draft",allowed_origins:[...l.allowed_origins]};return n+=1,i.push(x),o.set(g,{fingerprint:u,response:v(x)}),v(x)},async rotateMerchantWorkspaceCredential(p){let h=C(p.idempotencyKey),g=I(p.body,["reason"]),m=E(g.reason,"Rotation reason",3,500);t.push({operationId:"rotateMerchantWorkspaceCredential",method:"POST",path:`/api/partner-workspace/merchant/apps/${encodeURIComponent(p.appId)}/credential-rotations`,headers:{"Idempotency-Key":h},authorization:"partnerSession:step_up",body:{reason:m}});let k=te(p.appId,m),l=r.get(h);if(l){if(l.fingerprint!==k)throw W("rotateMerchantWorkspaceCredential");return{...l.response}}if(!s.has("step_up"))throw new d("Recent step-up authentication is required.",403);let u=i.find(K=>K.app_id===p.appId);if(!u)throw new d("Merchant app is not visible in the active server-derived context.",409);if(u.environment!=="dev")throw new d("Merchant app is outside the mock server-derived context.",403);let w=u.credential_version??0;u.credential_version=w+1;let x=new Date(c().getTime()+300*1e3).toISOString(),S={credential_id:`credential:${u.app_id}`,new_version:u.credential_version,old_version_expires_at:x,retrieval_mode:"protected_retrieval_handle",retrieval_handle:`mock-retrieval:${u.app_id}:${u.credential_version}`};return r.set(h,{fingerprint:k,response:{...S}}),S}},requests:t}}function v(e){return{...e,allowed_origins:[...e.allowed_origins]}}function Y(e){return J.has(e)}function C(e){if(typeof e!="string")throw _("Idempotency-Key must contain between 16 and 128 characters.");let t=e.trim();if(t.length<16||t.length>128)throw _("Idempotency-Key must contain between 16 and 128 characters.");return t}function I(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw _("Request body must be an object.");let i=new Set(t);if(Reflect.ownKeys(e).some(s=>typeof s!="string"||!i.has(s)))throw _("Request body contains an unsupported property.");return e}function E(e,t,i,s){if(typeof e!="string")throw _(`${t} must be a string.`);let c=e.trim(),o=Array.from(c).length;if(o<i||o>s)throw _(`${t} must contain between ${i} and ${s} characters.`);return c}function Q(e){if(!Array.isArray(e)||e.length>20)throw f("Allowed origins must be an array with at most 20 entries.");let t=[],i=new Set;for(let s of e){if(typeof s!="string"||s.length===0||/\s/.test(s))throw f("Each allowed origin must be a non-empty exact URL origin.");let c=/^(https?):\/\/([^/?#\\]+)\/?$/i.exec(s);if(!c)throw f("Allowed origins cannot include a path, query, or fragment.");let o;try{o=new URL(s)}catch{throw f("Allowed origin URL parsing failed.")}if(o.protocol!=="https:"&&o.protocol!=="http:"||o.username!==""||o.password!==""||o.pathname!=="/"||o.search!==""||o.hash!=="")throw f("Allowed origins must be credential-free exact HTTP(S) origins.");if(o.protocol==="http:"){let r=X(c[2]??"").toLowerCase();if(!(r==="localhost"||r==="127.0.0.1"||r==="[::1]"))throw f("Plain HTTP is allowed only for exact loopback origins.")}if(i.has(o.origin))throw f("Allowed origins must be unique after canonicalization.");i.add(o.origin),t.push(o.origin)}return t}function X(e){if(e.startsWith("[")){let i=e.indexOf("]");return i===-1?e:e.slice(0,i+1)}let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function f(e){return new d(e,400)}function _(e){return new d(e,400)}function ee(e){return JSON.stringify({display_name:e.display_name,capability_template:e.capability_template,allowed_origins:[...e.allowed_origins].sort()})}function te(e,t){return JSON.stringify({app_id:e,reason:t})}function W(e){return new d(`Idempotency key was already used for a different ${e} request.`,409)}var F={app_id:"dev_mcid_fixture_01",display_name:"Fixture storefront",environment:"dev",capability_template:"merchant_connect_dev",status:"draft",allowed_origins:["https://merchant.example"]},q={app_id:"production_mcid_fixture_01",display_name:"Production boundary fixture",environment:"production",capability_template:"merchant_connect_dev",status:"active",allowed_origins:["https://merchant.example"],credential_version:3},L={app_id:"app_fixture_future",display_name:"Future template fixture",environment:"dev",capability_template:"merchant_connect_dev_with_diagnostics",status:"active",allowed_origins:["https://merchant.example"],credential_version:1};var re=Object.freeze(["approved","declined_setup","declined_limit","payment_failed"]),y=Object.freeze({capabilities:{environment:"dev",contractVersion:"2026-07-09",checkedAt:"2026-07-10T00:00:00.000Z",capabilities:[{name:"fixtures",status:"ready",evidenceLevel:"verified",reasonCode:null,verifiedAt:"2026-07-10T00:00:00.000Z",limits:{networkCalls:0}},...["synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"].map(e=>({name:e,status:"unavailable",evidenceLevel:"contract",reasonCode:"DEV_NOT_DEPLOYED",verifiedAt:null,limits:{}}))]},faucetTransfer:{faucetTransferId:"sft_fixture_1001",userLinkRef:"ul_fixture_buyer_01",amount:{amount:"10.00",currency:"USDC"},status:"accepted",createdAt:"2026-07-10T00:00:00.000Z"},simulation:{simulationId:"sim_fixture_1001",scenario:"approved",executionMode:"pre_admission",status:"accepted",reasonCode:null,authorizationRef:null,chargeRef:null,createdAt:"2026-07-10T00:00:00.000Z",updatedAt:"2026-07-10T00:00:00.000Z"},webhookTestDelivery:{eventId:"evt_fixturetestping1001",deliveryId:"wd_fixturetestping1001",status:"queued",createdAt:"2026-07-10T00:00:00.000Z"}}),b="2026-07-10T00:00:00.000Z",j="0x1111111111111111111111111111111111111111";function N(e={}){let t=e.scenario??"happy_path",i=0;return async(s,c)=>{let o=new URL(s),r=(c?.method??"GET").toUpperCase(),n=o.pathname;if(r==="POST"&&n==="/api/merchant/user-links/exchange")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:j,grantStatus:"active",pipelineReady:t!=="setup_required",scopes:["wallet.read","payments.write"]});if(r==="POST"&&n==="/api/merchant/payment-readiness")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:j,readinessScope:"account_default",chainId:84532,protocolId:"aave-v3",assetSymbol:"USDC",spendMode:"direct",pipelineReady:t!=="setup_required",...t==="setup_required"?{notReadyReason:"payment_route_not_provisioned"}:{}});if(r==="POST"&&n==="/api/merchant/checkout-sessions")return a({sessionId:"checkout_fixture",checkoutUrl:"https://dev.facto.to/checkout/checkout_fixture",status:"pending",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture"});if(r==="GET"&&n.startsWith("/api/merchant/checkout-sessions/"))return a({sessionId:"checkout_fixture",status:"charged",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture",chargeId:"charge_fixture",confirmedAt:b});if(r==="POST"&&n==="/api/merchant/authorization-sessions")return a(z("created"));if(r==="GET"&&n.startsWith("/api/merchant/authorization-sessions/"))return a(z("authorized"));if(r==="GET"&&n.startsWith("/api/merchant/payment-authorizations/"))return a(U());if(r==="POST"&&n==="/api/merchant/payment-options")return a({paymentOptions:[{paymentOptionId:"fpo_fixture",label:"Fixture Direct",ready:t!=="setup_required",isDefault:!0,chainId:84532,chainLabel:"Base Sepolia",protocolLabel:"Aave V3",assetSymbol:"USDC",spendMode:"direct",settlementPath:"direct",...t==="setup_required"?{blockingReason:"setup_required"}:{}}],defaultPaymentOptionId:"fpo_fixture"});if(r==="POST"&&n==="/api/merchant/payments")return t==="idempotency_conflict"?a({code:"idempotency_conflict",message:"fixture idempotency conflict"},409):a(A(t==="declined_before_money"?"declined":"charging"));if(r==="GET"&&n.startsWith("/api/merchant/payments/")){let M=t==="status_progression"?["charging","finalizing","succeeded"]:["succeeded"],p=M[Math.min(i,M.length-1)]??"succeeded";return i+=1,a(A(p))}return r==="DELETE"&&n.startsWith("/api/merchant/user-links/")?new Response(null,{status:204}):r==="GET"&&n==="/api/merchant/payments"?a({data:[A("succeeded")],hasMore:!1}):r==="GET"&&n==="/api/merchant/payment-authorizations"?a({data:[U()],hasMore:!1}):r==="POST"&&n==="/api/merchant/refunds"?a(R()):r==="GET"&&n==="/api/merchant/refunds"?a({data:[R()],hasMore:!1}):r==="GET"&&n.startsWith("/api/merchant/refunds/")?a(R()):r==="POST"&&n==="/api/merchant/webhook-endpoints"?a({...T(),secret:"whsec_fixture_only"}):r==="GET"&&n==="/api/dev/capabilities"?a(y.capabilities):r==="POST"&&n==="/api/dev/faucet/usdc"?a(y.faucetTransfer,202):r==="POST"&&n==="/api/dev/simulate/charge"?a(y.simulation,202):r==="GET"&&n.startsWith("/api/dev/simulations/")?a(y.simulation):r==="POST"&&n.endsWith("/test-delivery")&&n.startsWith("/api/merchant/webhook-endpoints/")?a(y.webhookTestDelivery,202):r==="GET"&&n==="/api/merchant/webhook-endpoints"?a({data:[T()]}):r==="POST"&&n.endsWith("/rotate-secret")&&n.startsWith("/api/merchant/webhook-endpoints/")?a({...T(),secret:"whsec_fixture_rotated"}):r==="GET"&&n.startsWith("/api/merchant/webhook-endpoints/")?a(T()):r==="DELETE"&&n.startsWith("/api/merchant/webhook-endpoints/")?new Response(null,{status:204}):a({code:"fixture_route_not_found",method:r,path:n},404)}}var ne=N;function z(e){return{sessionId:"mauth_fixture",authorizationUrl:"https://dev.facto.to/merchant-mandates/authorize?session=mauth_fixture",status:e,...e==="authorized"?{mandateId:"mandate_fixture"}:{},expiresAt:"2026-07-10T00:15:00.000Z",state:"state_fixture"}}function U(){return{mandateId:"mandate_fixture",appId:"app_fixture",status:"active",allowedUseCases:["immediate","recurring","metered"],limits:{perTxAmount:"100.00",periodAmount:"500.00",period:"monthly"},paymentPath:{ready:!0,summary:"Fixture payment path ready"},createdAt:b}}function A(e){return{paymentId:"mpay_fixture",mandateId:"mandate_fixture",merchantPaymentRef:"payment_fixture",status:e,amount:e==="declined"?"75.00":"9.99",currency:"USDC",useCase:e==="declined"?"metered":"recurring",...e==="declined"?{declineReason:"mandate_limit_exceeded"}:{},...e==="succeeded"?{chargeId:"charge_fixture",txHash:`0x${"1".repeat(64)}`,terminalAt:"2026-07-10T00:00:03.000Z"}:{},createdAt:b,updatedAt:"2026-07-10T00:00:03.000Z"}}function R(){return{refundId:"refund_fixture",paymentId:"mpay_fixture",status:"succeeded",amount:"9.99",currency:"USDC",reason:"requested_by_customer",merchantRefundRef:"merchant_refund_fixture",createdAt:b}}function T(){return{webhookEndpointId:"webhook_fixture",url:"https://merchant.example/facto-webhooks",enabledEvents:["payment.succeeded","payment.failed"],status:"enabled",createdAt:b}}function a(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json"}})}
1
+ "use strict";var M=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var V=(e,t)=>{for(var i in t)M(e,i,{get:t[i],enumerable:!0})},Y=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of Z(t))!B.call(e,c)&&c!==i&&M(e,c,{get:()=>t[c],enumerable:!(s=$(t,c))||s.enumerable});return e};var J=e=>Y(M({},"__esModule",{value:!0}),e);var oe={};V(oe,{CANONICAL_MERCHANT_CAPABILITY_TEMPLATES:()=>P,MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS:()=>D,MerchantPartnerWorkspaceMockError:()=>u,createFactoConnectFixtureTransport:()=>K,createFactoTestTransport:()=>ie,createMerchantPartnerWorkspaceMock:()=>q,devFixtures:()=>g,devScenarios:()=>ae,merchantDevAppFixture:()=>L,merchantFutureTemplateProjectionFixture:()=>N,merchantProductionAppNegativeFixture:()=>F});module.exports=J(oe);var D=["listMerchantWorkspaceApps","createMerchantDevApp","rotateMerchantWorkspaceCredential"],P=["merchant_connect_sandbox","merchant_webhook_sandbox","merchant_mandate_sandbox","merchant_storefront_sandbox"],Q=new Set([...P,"merchant_connect_dev","merchant_webhook_dev"]),u=class extends Error{status;constructor(t,i){super(t),this.name="MerchantPartnerWorkspaceMockError",this.status=i}};function q(e={}){let t=[],i=(e.initialApps??[]).map(T),s=new Set(e.authenticatedSession?.scopes??[]),c=e.now??(()=>new Date),o=new Map,r=new Map,n=i.length+1;return{client:{async listMerchantWorkspaceApps({environment:p}){if(t.push({operationId:"listMerchantWorkspaceApps",method:"GET",path:"/api/partner-workspace/merchant/apps",query:{environment:p}}),p!=="dev")throw new u("Environment filter is outside the mock server-derived context.",403);return{items:i.filter(h=>h.environment===p).map(T)}},async createMerchantDevApp({idempotencyKey:p,body:h}){let x=I(p),f=E(h,["display_name","capability_template","allowed_origins"]),k=W(f.display_name,"Display name",1,160);if(!X(f.capability_template))throw new u("Capability template is not approved for Merchant dev app creation.",400);let m={display_name:k,capability_template:f.capability_template,allowed_origins:ee(f.allowed_origins)};t.push({operationId:"createMerchantDevApp",method:"POST",path:"/api/partner-workspace/merchant/apps",headers:{"Idempotency-Key":x},body:m});let l=ne(m),w=o.get(x);if(w){if(w.fingerprint!==l)throw O("createMerchantDevApp");return T(w.response)}let v={app_id:`dev_mcid_mock_${String(n).padStart(2,"0")}`,display_name:m.display_name,environment:"dev",capability_template:m.capability_template,status:"draft",allowed_origins:[...m.allowed_origins]};return n+=1,i.push(v),o.set(x,{fingerprint:l,response:T(v)}),T(v)},async rotateMerchantWorkspaceCredential(p){let h=I(p.idempotencyKey),x=E(p.body,["reason"]),f=W(x.reason,"Rotation reason",3,500);t.push({operationId:"rotateMerchantWorkspaceCredential",method:"POST",path:`/api/partner-workspace/merchant/apps/${encodeURIComponent(p.appId)}/credential-rotations`,headers:{"Idempotency-Key":h},authorization:"partnerSession:step_up",body:{reason:f}});let k=re(p.appId,f),m=r.get(h);if(m){if(m.fingerprint!==k)throw O("rotateMerchantWorkspaceCredential");return{...m.response}}if(!s.has("step_up"))throw new u("Recent step-up authentication is required.",403);let l=i.find(H=>H.app_id===p.appId);if(!l)throw new u("Merchant app is not visible in the active server-derived context.",409);if(l.environment!=="dev")throw new u("Merchant app is outside the mock server-derived context.",403);let w=l.credential_version??0;l.credential_version=w+1;let v=new Date(c().getTime()+300*1e3).toISOString(),S={credential_id:`credential:${l.app_id}`,new_version:l.credential_version,old_version_expires_at:v,retrieval_mode:"protected_retrieval_handle",retrieval_handle:`mock-retrieval:${l.app_id}:${l.credential_version}`};return r.set(h,{fingerprint:k,response:{...S}}),S}},requests:t}}function T(e){return{...e,allowed_origins:[...e.allowed_origins]}}function X(e){return Q.has(e)}function I(e){if(typeof e!="string")throw y("Idempotency-Key must contain between 16 and 128 characters.");let t=e.trim();if(t.length<16||t.length>128)throw y("Idempotency-Key must contain between 16 and 128 characters.");return t}function E(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw y("Request body must be an object.");let i=new Set(t);if(Reflect.ownKeys(e).some(s=>typeof s!="string"||!i.has(s)))throw y("Request body contains an unsupported property.");return e}function W(e,t,i,s){if(typeof e!="string")throw y(`${t} must be a string.`);let c=e.trim(),o=Array.from(c).length;if(o<i||o>s)throw y(`${t} must contain between ${i} and ${s} characters.`);return c}function ee(e){if(!Array.isArray(e)||e.length>20)throw _("Allowed origins must be an array with at most 20 entries.");let t=[],i=new Set;for(let s of e){if(typeof s!="string"||s.length===0||/\s/.test(s))throw _("Each allowed origin must be a non-empty exact URL origin.");let c=/^(https?):\/\/([^/?#\\]+)\/?$/i.exec(s);if(!c)throw _("Allowed origins cannot include a path, query, or fragment.");let o;try{o=new URL(s)}catch{throw _("Allowed origin URL parsing failed.")}if(o.protocol!=="https:"&&o.protocol!=="http:"||o.username!==""||o.password!==""||o.pathname!=="/"||o.search!==""||o.hash!=="")throw _("Allowed origins must be credential-free exact HTTP(S) origins.");if(o.protocol==="http:"){let r=te(c[2]??"").toLowerCase();if(!(r==="localhost"||r==="127.0.0.1"||r==="[::1]"))throw _("Plain HTTP is allowed only for exact loopback origins.")}if(i.has(o.origin))throw _("Allowed origins must be unique after canonicalization.");i.add(o.origin),t.push(o.origin)}return t}function te(e){if(e.startsWith("[")){let i=e.indexOf("]");return i===-1?e:e.slice(0,i+1)}let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function _(e){return new u(e,400)}function y(e){return new u(e,400)}function ne(e){return JSON.stringify({display_name:e.display_name,capability_template:e.capability_template,allowed_origins:[...e.allowed_origins].sort()})}function re(e,t){return JSON.stringify({app_id:e,reason:t})}function O(e){return new u(`Idempotency key was already used for a different ${e} request.`,409)}var L={app_id:"dev_mcid_fixture_01",display_name:"Fixture storefront",environment:"dev",capability_template:"merchant_connect_sandbox",status:"draft",allowed_origins:["https://merchant.example"]},F={app_id:"production_mcid_fixture_01",display_name:"Production boundary fixture",environment:"production",capability_template:"merchant_connect_sandbox",status:"active",allowed_origins:["https://merchant.example"],credential_version:3},N={app_id:"app_fixture_future",display_name:"Future template fixture",environment:"dev",capability_template:"merchant_connect_dev_with_diagnostics",status:"active",allowed_origins:["https://merchant.example"],credential_version:1};var ae=Object.freeze(["approved","declined_setup","declined_limit","payment_failed"]),g=Object.freeze({capabilities:{environment:"dev",contractVersion:"2026-07-09",checkedAt:"2026-07-10T00:00:00.000Z",capabilities:[{name:"fixtures",status:"ready",evidenceLevel:"verified",reasonCode:null,verifiedAt:"2026-07-10T00:00:00.000Z",limits:{networkCalls:0}},...["synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"].map(e=>({name:e,status:"unavailable",evidenceLevel:"contract",reasonCode:"DEV_NOT_DEPLOYED",verifiedAt:null,limits:{}}))]},faucetTransfer:{faucetTransferId:"sft_fixture_1001",userLinkRef:"ul_fixture_buyer_01",amount:{amount:"10.00",currency:"USDC"},status:"accepted",createdAt:"2026-07-10T00:00:00.000Z"},simulation:{simulationId:"sim_fixture_1001",scenario:"approved",executionMode:"pre_admission",status:"accepted",reasonCode:null,authorizationRef:null,chargeRef:null,createdAt:"2026-07-10T00:00:00.000Z",updatedAt:"2026-07-10T00:00:00.000Z"},webhookTestDelivery:{eventId:"evt_fixturetestping1001",deliveryId:"wd_fixturetestping1001",status:"queued",createdAt:"2026-07-10T00:00:00.000Z"}}),b="2026-07-10T00:00:00.000Z",z="0x1111111111111111111111111111111111111111";function K(e={}){let t=e.scenario??"happy_path",i=0;return async(s,c)=>{let o=new URL(s),r=(c?.method??"GET").toUpperCase(),n=o.pathname;if(r==="POST"&&n==="/api/merchant/user-links/exchange")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:z,grantStatus:"active",pipelineReady:t!=="setup_required",scopes:["wallet.read","payments.write"]});if(r==="POST"&&n==="/api/merchant/payment-readiness")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:z,readinessScope:"account_default",chainId:84532,protocolId:"aave-v3",assetSymbol:"USDC",spendMode:"direct",pipelineReady:t!=="setup_required",...t==="setup_required"?{notReadyReason:"payment_route_not_provisioned"}:{}});if(r==="POST"&&n==="/api/merchant/checkout-sessions")return a({sessionId:"checkout_fixture",checkoutUrl:"https://dev.facto.to/checkout/checkout_fixture",status:"pending",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture"});if(r==="GET"&&n.startsWith("/api/merchant/checkout-sessions/"))return a({sessionId:"checkout_fixture",status:"charged",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture",chargeId:"charge_fixture",confirmedAt:b});if(r==="POST"&&n==="/api/merchant/authorization-sessions")return a(j("created"));if(r==="GET"&&n.startsWith("/api/merchant/authorization-sessions/"))return a(j("authorized"));if(r==="GET"&&n.startsWith("/api/merchant/payment-authorizations/"))return a(U());if(r==="DELETE"&&n.startsWith("/api/merchant/payment-authorizations/")){let d=decodeURIComponent(n.slice(37));return a({mandateId:d||"mandate_fixture",status:"revoked",revokedByThisRequest:!0})}if(r==="POST"&&n==="/api/merchant/mandate-path-change-sessions")return a(G("pending"));if(r==="GET"&&n.startsWith("/api/merchant/mandate-path-change-sessions/"))return a(G("completed"));if(r==="POST"&&n==="/api/merchant/payment-options")return a({paymentOptions:[{paymentOptionId:"fpo_fixture",label:"Fixture Direct",ready:t!=="setup_required",isDefault:!0,chainId:84532,chainLabel:"Base Sepolia",protocolLabel:"Aave V3",assetSymbol:"USDC",spendMode:"direct",settlementPath:"direct",...t==="setup_required"?{blockingReason:"setup_required"}:{}}],defaultPaymentOptionId:"fpo_fixture"});if(r==="POST"&&n==="/api/merchant/payments")return t==="idempotency_conflict"?a({error:{category:"conflict",code:"conflict",message:"fixture idempotency conflict",request_id:"req_fixture_idempotency_conflict",retryable:!1}},409):t==="declined_before_money"?a(A("declined"),402):a(A("charging"));if(r==="GET"&&n.startsWith("/api/merchant/payments/")){let d=t==="status_progression"?["charging","finalizing","succeeded"]:["succeeded"],p=d[Math.min(i,d.length-1)]??"succeeded";return i+=1,a(A(p))}if(r==="GET"&&n.startsWith("/api/merchant/user-links/")){let d=decodeURIComponent(n.slice(25));return a({appId:"app_fixture",userLinkRef:d||"ul_fixture_buyer_01",grantStatus:"active",paymentReady:t!=="setup_required",scopes:["wallet.read","payments.write"]})}if(r==="DELETE"&&n.startsWith("/api/merchant/user-links/"))return new Response(null,{status:204});if(r==="GET"&&n==="/api/merchant/payments")return a({data:[A("succeeded")],hasMore:!1});if(r==="GET"&&n==="/api/merchant/payment-authorizations")return a({data:[U()],hasMore:!1});if(r==="POST"&&n==="/api/merchant/refunds")return a(C());if(r==="GET"&&n==="/api/merchant/refunds")return a({data:[C()],hasMore:!1});if(r==="GET"&&n.startsWith("/api/merchant/refunds/"))return a(C());if(r==="POST"&&n==="/api/merchant/webhook-endpoints")return a({...R(),secret:"whsec_fixture_only"});if(r==="GET"&&n==="/api/dev/capabilities")return a(g.capabilities);if(r==="POST"&&n==="/api/dev/faucet/usdc")return a(g.faucetTransfer,202);if(r==="POST"&&n==="/api/dev/simulate/charge")return a(g.simulation,202);if(r==="GET"&&n.startsWith("/api/dev/simulations/"))return a(g.simulation);if(r==="POST"&&n==="/api/dev/test-mandates")return a({mandateId:"mandate_fixture",settlementMode:"simulated"},201);if(r==="POST"&&n.startsWith("/api/dev/test-mandates/")&&n.endsWith("/settle")){let d={};if(typeof c?.body=="string")try{d=JSON.parse(c.body)}catch{d={}}let p=d.outcome==="failed"?"failed":"succeeded",h=A(p);return p==="failed"&&d.declineReason&&(h.declineReason=d.declineReason),a(h)}return r==="POST"&&n.endsWith("/test-delivery")&&n.startsWith("/api/merchant/webhook-endpoints/")?a(g.webhookTestDelivery,202):r==="GET"&&n==="/api/merchant/webhook-endpoints"?a({data:[R()]}):r==="POST"&&n.endsWith("/rotate-secret")&&n.startsWith("/api/merchant/webhook-endpoints/")?a({...R(),secret:"whsec_fixture_rotated"}):r==="GET"&&n.startsWith("/api/merchant/webhook-endpoints/")?a(R()):r==="DELETE"&&n.startsWith("/api/merchant/webhook-endpoints/")?new Response(null,{status:204}):a({code:"fixture_route_not_found",method:r,path:n},404)}}var ie=K;function j(e){return{sessionId:"mauth_fixture",authorizationUrl:"https://dev.facto.to/merchant-mandates/authorize?session=mauth_fixture",status:e,...e==="authorized"?{mandateId:"mandate_fixture"}:{},expiresAt:"2026-07-10T00:15:00.000Z",state:"state_fixture"}}function U(){return{mandateId:"mandate_fixture",appId:"app_fixture",status:"active",allowedUseCases:["immediate","recurring","metered"],limits:{perTxAmount:"100.00",periodAmount:"500.00",period:"monthly"},paymentPath:{ready:!0,summary:"Fixture payment path ready"},createdAt:b}}function A(e){return{paymentId:"mpay_fixture",mandateId:"mandate_fixture",merchantPaymentRef:"payment_fixture",status:e,amount:e==="declined"?"75.00":"9.99",currency:"USDC",useCase:e==="declined"?"metered":"recurring",...e==="declined"?{declineReason:"mandate_limit_exceeded"}:{},...e==="succeeded"?{chargeId:"charge_fixture",txHash:`0x${"1".repeat(64)}`,terminalAt:"2026-07-10T00:00:03.000Z"}:{},createdAt:b,updatedAt:"2026-07-10T00:00:03.000Z"}}function G(e){return{sessionId:"mpcs_fixture00000000000000000001",pathChangeUrl:"https://dev.facto.to/mandates/change-path?session=mpcs_fixture00000000000000000001",status:e,state:"state_path_change_fixture_000001",targetOrigin:"https://merchant.example",expiresAt:"2026-07-10T00:15:00.000Z"}}function C(){return{refundId:"re_fixture000000000000000000000001",paymentId:"mpay_fixture",status:"succeeded",amount:"9.99",currency:"USDC",reason:"requested_by_customer",merchantRefundRef:"merchant_refund_fixture",createdAt:b}}function R(){return{webhookEndpointId:"we_fixture000000000000000000000001",url:"https://merchant.example/facto-webhooks",enabledEvents:["payment.succeeded","payment.failed"],status:"enabled",createdAt:b}}function a(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json"}})}
@@ -1,11 +1,13 @@
1
1
  import { FactoConnectTransport, DevCapabilities, DevFaucetTransfer, DevSimulation, WebhookTestDeliveryAccepted } from '../server/index.cjs';
2
- import '../card-transport-Zh-6EMPi.cjs';
3
- import '../index.d-BikZSd0p.cjs';
2
+ import '../card-transport--tl4vJa5.cjs';
3
+ import '../index.d-oRLzr8gp.cjs';
4
4
 
5
5
  declare const MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS: readonly ["listMerchantWorkspaceApps", "createMerchantDevApp", "rotateMerchantWorkspaceCredential"];
6
6
  type MerchantPartnerWorkspaceOperationId = (typeof MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS)[number];
7
7
  type PartnerWorkspaceEnvironment = 'dev' | 'mainnet_staging' | 'production';
8
- type MerchantCapabilityTemplate = 'merchant_connect_dev' | 'merchant_webhook_dev';
8
+ declare const CANONICAL_MERCHANT_CAPABILITY_TEMPLATES: readonly ["merchant_connect_sandbox", "merchant_webhook_sandbox", "merchant_mandate_sandbox", "merchant_storefront_sandbox"];
9
+ type CanonicalMerchantCapabilityTemplate = (typeof CANONICAL_MERCHANT_CAPABILITY_TEMPLATES)[number];
10
+ type MerchantCapabilityTemplate = CanonicalMerchantCapabilityTemplate | 'merchant_connect_dev' | 'merchant_webhook_dev';
9
11
  interface MerchantAppProjection {
10
12
  app_id: string;
11
13
  display_name: string;
@@ -130,4 +132,4 @@ declare const devFixtures: Readonly<{
130
132
  declare function createFactoConnectFixtureTransport(options?: FactoConnectFixtureTransportOptions): FactoConnectTransport;
131
133
  declare const createFactoTestTransport: typeof createFactoConnectFixtureTransport;
132
134
 
133
- export { type CreateMerchantDevAppRequest, type CredentialRotationResult, type FactoConnectFixtureScenario, type FactoConnectFixtureTransportOptions, MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS, type MerchantAppProjection, type MerchantCapabilityTemplate, type MerchantPartnerWorkspaceClient, MerchantPartnerWorkspaceMockError, type MerchantPartnerWorkspaceOperationId, type MerchantPartnerWorkspaceRequest, type PartnerSessionScope, type PartnerWorkspaceEnvironment, createFactoConnectFixtureTransport, createFactoTestTransport, createMerchantPartnerWorkspaceMock, devFixtures, devScenarios, merchantDevAppFixture, merchantFutureTemplateProjectionFixture, merchantProductionAppNegativeFixture };
135
+ export { CANONICAL_MERCHANT_CAPABILITY_TEMPLATES, type CanonicalMerchantCapabilityTemplate, type CreateMerchantDevAppRequest, type CredentialRotationResult, type FactoConnectFixtureScenario, type FactoConnectFixtureTransportOptions, MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS, type MerchantAppProjection, type MerchantCapabilityTemplate, type MerchantPartnerWorkspaceClient, MerchantPartnerWorkspaceMockError, type MerchantPartnerWorkspaceOperationId, type MerchantPartnerWorkspaceRequest, type PartnerSessionScope, type PartnerWorkspaceEnvironment, createFactoConnectFixtureTransport, createFactoTestTransport, createMerchantPartnerWorkspaceMock, devFixtures, devScenarios, merchantDevAppFixture, merchantFutureTemplateProjectionFixture, merchantProductionAppNegativeFixture };
@@ -1,11 +1,13 @@
1
1
  import { FactoConnectTransport, DevCapabilities, DevFaucetTransfer, DevSimulation, WebhookTestDeliveryAccepted } from '../server/index.js';
2
- import '../card-transport-Zh-6EMPi.js';
3
- import '../index.d-BikZSd0p.js';
2
+ import '../card-transport--tl4vJa5.js';
3
+ import '../index.d-oRLzr8gp.js';
4
4
 
5
5
  declare const MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS: readonly ["listMerchantWorkspaceApps", "createMerchantDevApp", "rotateMerchantWorkspaceCredential"];
6
6
  type MerchantPartnerWorkspaceOperationId = (typeof MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS)[number];
7
7
  type PartnerWorkspaceEnvironment = 'dev' | 'mainnet_staging' | 'production';
8
- type MerchantCapabilityTemplate = 'merchant_connect_dev' | 'merchant_webhook_dev';
8
+ declare const CANONICAL_MERCHANT_CAPABILITY_TEMPLATES: readonly ["merchant_connect_sandbox", "merchant_webhook_sandbox", "merchant_mandate_sandbox", "merchant_storefront_sandbox"];
9
+ type CanonicalMerchantCapabilityTemplate = (typeof CANONICAL_MERCHANT_CAPABILITY_TEMPLATES)[number];
10
+ type MerchantCapabilityTemplate = CanonicalMerchantCapabilityTemplate | 'merchant_connect_dev' | 'merchant_webhook_dev';
9
11
  interface MerchantAppProjection {
10
12
  app_id: string;
11
13
  display_name: string;
@@ -130,4 +132,4 @@ declare const devFixtures: Readonly<{
130
132
  declare function createFactoConnectFixtureTransport(options?: FactoConnectFixtureTransportOptions): FactoConnectTransport;
131
133
  declare const createFactoTestTransport: typeof createFactoConnectFixtureTransport;
132
134
 
133
- export { type CreateMerchantDevAppRequest, type CredentialRotationResult, type FactoConnectFixtureScenario, type FactoConnectFixtureTransportOptions, MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS, type MerchantAppProjection, type MerchantCapabilityTemplate, type MerchantPartnerWorkspaceClient, MerchantPartnerWorkspaceMockError, type MerchantPartnerWorkspaceOperationId, type MerchantPartnerWorkspaceRequest, type PartnerSessionScope, type PartnerWorkspaceEnvironment, createFactoConnectFixtureTransport, createFactoTestTransport, createMerchantPartnerWorkspaceMock, devFixtures, devScenarios, merchantDevAppFixture, merchantFutureTemplateProjectionFixture, merchantProductionAppNegativeFixture };
135
+ export { CANONICAL_MERCHANT_CAPABILITY_TEMPLATES, type CanonicalMerchantCapabilityTemplate, type CreateMerchantDevAppRequest, type CredentialRotationResult, type FactoConnectFixtureScenario, type FactoConnectFixtureTransportOptions, MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS, type MerchantAppProjection, type MerchantCapabilityTemplate, type MerchantPartnerWorkspaceClient, MerchantPartnerWorkspaceMockError, type MerchantPartnerWorkspaceOperationId, type MerchantPartnerWorkspaceRequest, type PartnerSessionScope, type PartnerWorkspaceEnvironment, createFactoConnectFixtureTransport, createFactoTestTransport, createMerchantPartnerWorkspaceMock, devFixtures, devScenarios, merchantDevAppFixture, merchantFutureTemplateProjectionFixture, merchantProductionAppNegativeFixture };
@@ -1 +1 @@
1
- var q=["listMerchantWorkspaceApps","createMerchantDevApp","rotateMerchantWorkspaceCredential"],L=new Set(["merchant_connect_dev","merchant_webhook_dev"]),d=class extends Error{status;constructor(t,i){super(t),this.name="MerchantPartnerWorkspaceMockError",this.status=i}};function j(e={}){let t=[],i=(e.initialApps??[]).map(x),s=new Set(e.authenticatedSession?.scopes??[]),u=e.now??(()=>new Date),o=new Map,r=new Map,n=i.length+1;return{client:{async listMerchantWorkspaceApps({environment:c}){if(t.push({operationId:"listMerchantWorkspaceApps",method:"GET",path:"/api/partner-workspace/merchant/apps",query:{environment:c}}),c!=="dev")throw new d("Environment filter is outside the mock server-derived context.",403);return{items:i.filter(h=>h.environment===c).map(x)}},async createMerchantDevApp({idempotencyKey:c,body:h}){let y=S(c),m=C(h,["display_name","capability_template","allowed_origins"]),k=I(m.display_name,"Display name",1,160);if(!z(m.capability_template))throw new d("Capability template is not approved for Merchant dev app creation.",400);let l={display_name:k,capability_template:m.capability_template,allowed_origins:U(m.allowed_origins)};t.push({operationId:"createMerchantDevApp",method:"POST",path:"/api/partner-workspace/merchant/apps",headers:{"Idempotency-Key":y},body:l});let p=K(l),g=o.get(y);if(g){if(g.fingerprint!==p)throw E("createMerchantDevApp");return x(g.response)}let w={app_id:`dev_mcid_mock_${String(n).padStart(2,"0")}`,display_name:l.display_name,environment:"dev",capability_template:l.capability_template,status:"draft",allowed_origins:[...l.allowed_origins]};return n+=1,i.push(w),o.set(y,{fingerprint:p,response:x(w)}),x(w)},async rotateMerchantWorkspaceCredential(c){let h=S(c.idempotencyKey),y=C(c.body,["reason"]),m=I(y.reason,"Rotation reason",3,500);t.push({operationId:"rotateMerchantWorkspaceCredential",method:"POST",path:`/api/partner-workspace/merchant/apps/${encodeURIComponent(c.appId)}/credential-rotations`,headers:{"Idempotency-Key":h},authorization:"partnerSession:step_up",body:{reason:m}});let k=G(c.appId,m),l=r.get(h);if(l){if(l.fingerprint!==k)throw E("rotateMerchantWorkspaceCredential");return{...l.response}}if(!s.has("step_up"))throw new d("Recent step-up authentication is required.",403);let p=i.find(F=>F.app_id===c.appId);if(!p)throw new d("Merchant app is not visible in the active server-derived context.",409);if(p.environment!=="dev")throw new d("Merchant app is outside the mock server-derived context.",403);let g=p.credential_version??0;p.credential_version=g+1;let w=new Date(u().getTime()+300*1e3).toISOString(),R={credential_id:`credential:${p.app_id}`,new_version:p.credential_version,old_version_expires_at:w,retrieval_mode:"protected_retrieval_handle",retrieval_handle:`mock-retrieval:${p.app_id}:${p.credential_version}`};return r.set(h,{fingerprint:k,response:{...R}}),R}},requests:t}}function x(e){return{...e,allowed_origins:[...e.allowed_origins]}}function z(e){return L.has(e)}function S(e){if(typeof e!="string")throw _("Idempotency-Key must contain between 16 and 128 characters.");let t=e.trim();if(t.length<16||t.length>128)throw _("Idempotency-Key must contain between 16 and 128 characters.");return t}function C(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw _("Request body must be an object.");let i=new Set(t);if(Reflect.ownKeys(e).some(s=>typeof s!="string"||!i.has(s)))throw _("Request body contains an unsupported property.");return e}function I(e,t,i,s){if(typeof e!="string")throw _(`${t} must be a string.`);let u=e.trim(),o=Array.from(u).length;if(o<i||o>s)throw _(`${t} must contain between ${i} and ${s} characters.`);return u}function U(e){if(!Array.isArray(e)||e.length>20)throw f("Allowed origins must be an array with at most 20 entries.");let t=[],i=new Set;for(let s of e){if(typeof s!="string"||s.length===0||/\s/.test(s))throw f("Each allowed origin must be a non-empty exact URL origin.");let u=/^(https?):\/\/([^/?#\\]+)\/?$/i.exec(s);if(!u)throw f("Allowed origins cannot include a path, query, or fragment.");let o;try{o=new URL(s)}catch{throw f("Allowed origin URL parsing failed.")}if(o.protocol!=="https:"&&o.protocol!=="http:"||o.username!==""||o.password!==""||o.pathname!=="/"||o.search!==""||o.hash!=="")throw f("Allowed origins must be credential-free exact HTTP(S) origins.");if(o.protocol==="http:"){let r=N(u[2]??"").toLowerCase();if(!(r==="localhost"||r==="127.0.0.1"||r==="[::1]"))throw f("Plain HTTP is allowed only for exact loopback origins.")}if(i.has(o.origin))throw f("Allowed origins must be unique after canonicalization.");i.add(o.origin),t.push(o.origin)}return t}function N(e){if(e.startsWith("[")){let i=e.indexOf("]");return i===-1?e:e.slice(0,i+1)}let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function f(e){return new d(e,400)}function _(e){return new d(e,400)}function K(e){return JSON.stringify({display_name:e.display_name,capability_template:e.capability_template,allowed_origins:[...e.allowed_origins].sort()})}function G(e,t){return JSON.stringify({app_id:e,reason:t})}function E(e){return new d(`Idempotency key was already used for a different ${e} request.`,409)}var $={app_id:"dev_mcid_fixture_01",display_name:"Fixture storefront",environment:"dev",capability_template:"merchant_connect_dev",status:"draft",allowed_origins:["https://merchant.example"]},Z={app_id:"production_mcid_fixture_01",display_name:"Production boundary fixture",environment:"production",capability_template:"merchant_connect_dev",status:"active",allowed_origins:["https://merchant.example"],credential_version:3},H={app_id:"app_fixture_future",display_name:"Future template fixture",environment:"dev",capability_template:"merchant_connect_dev_with_diagnostics",status:"active",allowed_origins:["https://merchant.example"],credential_version:1};var Y=Object.freeze(["approved","declined_setup","declined_limit","payment_failed"]),v=Object.freeze({capabilities:{environment:"dev",contractVersion:"2026-07-09",checkedAt:"2026-07-10T00:00:00.000Z",capabilities:[{name:"fixtures",status:"ready",evidenceLevel:"verified",reasonCode:null,verifiedAt:"2026-07-10T00:00:00.000Z",limits:{networkCalls:0}},...["synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"].map(e=>({name:e,status:"unavailable",evidenceLevel:"contract",reasonCode:"DEV_NOT_DEPLOYED",verifiedAt:null,limits:{}}))]},faucetTransfer:{faucetTransferId:"sft_fixture_1001",userLinkRef:"ul_fixture_buyer_01",amount:{amount:"10.00",currency:"USDC"},status:"accepted",createdAt:"2026-07-10T00:00:00.000Z"},simulation:{simulationId:"sim_fixture_1001",scenario:"approved",executionMode:"pre_admission",status:"accepted",reasonCode:null,authorizationRef:null,chargeRef:null,createdAt:"2026-07-10T00:00:00.000Z",updatedAt:"2026-07-10T00:00:00.000Z"},webhookTestDelivery:{eventId:"evt_fixturetestping1001",deliveryId:"wd_fixturetestping1001",status:"queued",createdAt:"2026-07-10T00:00:00.000Z"}}),b="2026-07-10T00:00:00.000Z",W="0x1111111111111111111111111111111111111111";function V(e={}){let t=e.scenario??"happy_path",i=0;return async(s,u)=>{let o=new URL(s),r=(u?.method??"GET").toUpperCase(),n=o.pathname;if(r==="POST"&&n==="/api/merchant/user-links/exchange")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:W,grantStatus:"active",pipelineReady:t!=="setup_required",scopes:["wallet.read","payments.write"]});if(r==="POST"&&n==="/api/merchant/payment-readiness")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:W,readinessScope:"account_default",chainId:84532,protocolId:"aave-v3",assetSymbol:"USDC",spendMode:"direct",pipelineReady:t!=="setup_required",...t==="setup_required"?{notReadyReason:"payment_route_not_provisioned"}:{}});if(r==="POST"&&n==="/api/merchant/checkout-sessions")return a({sessionId:"checkout_fixture",checkoutUrl:"https://dev.facto.to/checkout/checkout_fixture",status:"pending",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture"});if(r==="GET"&&n.startsWith("/api/merchant/checkout-sessions/"))return a({sessionId:"checkout_fixture",status:"charged",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture",chargeId:"charge_fixture",confirmedAt:b});if(r==="POST"&&n==="/api/merchant/authorization-sessions")return a(O("created"));if(r==="GET"&&n.startsWith("/api/merchant/authorization-sessions/"))return a(O("authorized"));if(r==="GET"&&n.startsWith("/api/merchant/payment-authorizations/"))return a(D());if(r==="POST"&&n==="/api/merchant/payment-options")return a({paymentOptions:[{paymentOptionId:"fpo_fixture",label:"Fixture Direct",ready:t!=="setup_required",isDefault:!0,chainId:84532,chainLabel:"Base Sepolia",protocolLabel:"Aave V3",assetSymbol:"USDC",spendMode:"direct",settlementPath:"direct",...t==="setup_required"?{blockingReason:"setup_required"}:{}}],defaultPaymentOptionId:"fpo_fixture"});if(r==="POST"&&n==="/api/merchant/payments")return t==="idempotency_conflict"?a({code:"idempotency_conflict",message:"fixture idempotency conflict"},409):a(A(t==="declined_before_money"?"declined":"charging"));if(r==="GET"&&n.startsWith("/api/merchant/payments/")){let M=t==="status_progression"?["charging","finalizing","succeeded"]:["succeeded"],c=M[Math.min(i,M.length-1)]??"succeeded";return i+=1,a(A(c))}return r==="DELETE"&&n.startsWith("/api/merchant/user-links/")?new Response(null,{status:204}):r==="GET"&&n==="/api/merchant/payments"?a({data:[A("succeeded")],hasMore:!1}):r==="GET"&&n==="/api/merchant/payment-authorizations"?a({data:[D()],hasMore:!1}):r==="POST"&&n==="/api/merchant/refunds"?a(P()):r==="GET"&&n==="/api/merchant/refunds"?a({data:[P()],hasMore:!1}):r==="GET"&&n.startsWith("/api/merchant/refunds/")?a(P()):r==="POST"&&n==="/api/merchant/webhook-endpoints"?a({...T(),secret:"whsec_fixture_only"}):r==="GET"&&n==="/api/dev/capabilities"?a(v.capabilities):r==="POST"&&n==="/api/dev/faucet/usdc"?a(v.faucetTransfer,202):r==="POST"&&n==="/api/dev/simulate/charge"?a(v.simulation,202):r==="GET"&&n.startsWith("/api/dev/simulations/")?a(v.simulation):r==="POST"&&n.endsWith("/test-delivery")&&n.startsWith("/api/merchant/webhook-endpoints/")?a(v.webhookTestDelivery,202):r==="GET"&&n==="/api/merchant/webhook-endpoints"?a({data:[T()]}):r==="POST"&&n.endsWith("/rotate-secret")&&n.startsWith("/api/merchant/webhook-endpoints/")?a({...T(),secret:"whsec_fixture_rotated"}):r==="GET"&&n.startsWith("/api/merchant/webhook-endpoints/")?a(T()):r==="DELETE"&&n.startsWith("/api/merchant/webhook-endpoints/")?new Response(null,{status:204}):a({code:"fixture_route_not_found",method:r,path:n},404)}}var Q=V;function O(e){return{sessionId:"mauth_fixture",authorizationUrl:"https://dev.facto.to/merchant-mandates/authorize?session=mauth_fixture",status:e,...e==="authorized"?{mandateId:"mandate_fixture"}:{},expiresAt:"2026-07-10T00:15:00.000Z",state:"state_fixture"}}function D(){return{mandateId:"mandate_fixture",appId:"app_fixture",status:"active",allowedUseCases:["immediate","recurring","metered"],limits:{perTxAmount:"100.00",periodAmount:"500.00",period:"monthly"},paymentPath:{ready:!0,summary:"Fixture payment path ready"},createdAt:b}}function A(e){return{paymentId:"mpay_fixture",mandateId:"mandate_fixture",merchantPaymentRef:"payment_fixture",status:e,amount:e==="declined"?"75.00":"9.99",currency:"USDC",useCase:e==="declined"?"metered":"recurring",...e==="declined"?{declineReason:"mandate_limit_exceeded"}:{},...e==="succeeded"?{chargeId:"charge_fixture",txHash:`0x${"1".repeat(64)}`,terminalAt:"2026-07-10T00:00:03.000Z"}:{},createdAt:b,updatedAt:"2026-07-10T00:00:03.000Z"}}function P(){return{refundId:"refund_fixture",paymentId:"mpay_fixture",status:"succeeded",amount:"9.99",currency:"USDC",reason:"requested_by_customer",merchantRefundRef:"merchant_refund_fixture",createdAt:b}}function T(){return{webhookEndpointId:"webhook_fixture",url:"https://merchant.example/facto-webhooks",enabledEvents:["payment.succeeded","payment.failed"],status:"enabled",createdAt:b}}function a(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json"}})}export{q as MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS,d as MerchantPartnerWorkspaceMockError,V as createFactoConnectFixtureTransport,Q as createFactoTestTransport,j as createMerchantPartnerWorkspaceMock,v as devFixtures,Y as devScenarios,$ as merchantDevAppFixture,H as merchantFutureTemplateProjectionFixture,Z as merchantProductionAppNegativeFixture};
1
+ var N=["listMerchantWorkspaceApps","createMerchantDevApp","rotateMerchantWorkspaceCredential"],W=["merchant_connect_sandbox","merchant_webhook_sandbox","merchant_mandate_sandbox","merchant_storefront_sandbox"],z=new Set([...W,"merchant_connect_dev","merchant_webhook_dev"]),l=class extends Error{status;constructor(r,i){super(r),this.name="MerchantPartnerWorkspaceMockError",this.status=i}};function j(e={}){let r=[],i=(e.initialApps??[]).map(v),c=new Set(e.authenticatedSession?.scopes??[]),d=e.now??(()=>new Date),o=new Map,n=new Map,t=i.length+1;return{client:{async listMerchantWorkspaceApps({environment:s}){if(r.push({operationId:"listMerchantWorkspaceApps",method:"GET",path:"/api/partner-workspace/merchant/apps",query:{environment:s}}),s!=="dev")throw new l("Environment filter is outside the mock server-derived context.",403);return{items:i.filter(h=>h.environment===s).map(v)}},async createMerchantDevApp({idempotencyKey:s,body:h}){let g=C(s),f=S(h,["display_name","capability_template","allowed_origins"]),k=I(f.display_name,"Display name",1,160);if(!U(f.capability_template))throw new l("Capability template is not approved for Merchant dev app creation.",400);let m={display_name:k,capability_template:f.capability_template,allowed_origins:G(f.allowed_origins)};r.push({operationId:"createMerchantDevApp",method:"POST",path:"/api/partner-workspace/merchant/apps",headers:{"Idempotency-Key":g},body:m});let u=H(m),x=o.get(g);if(x){if(x.fingerprint!==u)throw E("createMerchantDevApp");return v(x.response)}let w={app_id:`dev_mcid_mock_${String(t).padStart(2,"0")}`,display_name:m.display_name,environment:"dev",capability_template:m.capability_template,status:"draft",allowed_origins:[...m.allowed_origins]};return t+=1,i.push(w),o.set(g,{fingerprint:u,response:v(w)}),v(w)},async rotateMerchantWorkspaceCredential(s){let h=C(s.idempotencyKey),g=S(s.body,["reason"]),f=I(g.reason,"Rotation reason",3,500);r.push({operationId:"rotateMerchantWorkspaceCredential",method:"POST",path:`/api/partner-workspace/merchant/apps/${encodeURIComponent(s.appId)}/credential-rotations`,headers:{"Idempotency-Key":h},authorization:"partnerSession:step_up",body:{reason:f}});let k=$(s.appId,f),m=n.get(h);if(m){if(m.fingerprint!==k)throw E("rotateMerchantWorkspaceCredential");return{...m.response}}if(!c.has("step_up"))throw new l("Recent step-up authentication is required.",403);let u=i.find(F=>F.app_id===s.appId);if(!u)throw new l("Merchant app is not visible in the active server-derived context.",409);if(u.environment!=="dev")throw new l("Merchant app is outside the mock server-derived context.",403);let x=u.credential_version??0;u.credential_version=x+1;let w=new Date(d().getTime()+300*1e3).toISOString(),P={credential_id:`credential:${u.app_id}`,new_version:u.credential_version,old_version_expires_at:w,retrieval_mode:"protected_retrieval_handle",retrieval_handle:`mock-retrieval:${u.app_id}:${u.credential_version}`};return n.set(h,{fingerprint:k,response:{...P}}),P}},requests:r}}function v(e){return{...e,allowed_origins:[...e.allowed_origins]}}function U(e){return z.has(e)}function C(e){if(typeof e!="string")throw y("Idempotency-Key must contain between 16 and 128 characters.");let r=e.trim();if(r.length<16||r.length>128)throw y("Idempotency-Key must contain between 16 and 128 characters.");return r}function S(e,r){if(e===null||typeof e!="object"||Array.isArray(e))throw y("Request body must be an object.");let i=new Set(r);if(Reflect.ownKeys(e).some(c=>typeof c!="string"||!i.has(c)))throw y("Request body contains an unsupported property.");return e}function I(e,r,i,c){if(typeof e!="string")throw y(`${r} must be a string.`);let d=e.trim(),o=Array.from(d).length;if(o<i||o>c)throw y(`${r} must contain between ${i} and ${c} characters.`);return d}function G(e){if(!Array.isArray(e)||e.length>20)throw _("Allowed origins must be an array with at most 20 entries.");let r=[],i=new Set;for(let c of e){if(typeof c!="string"||c.length===0||/\s/.test(c))throw _("Each allowed origin must be a non-empty exact URL origin.");let d=/^(https?):\/\/([^/?#\\]+)\/?$/i.exec(c);if(!d)throw _("Allowed origins cannot include a path, query, or fragment.");let o;try{o=new URL(c)}catch{throw _("Allowed origin URL parsing failed.")}if(o.protocol!=="https:"&&o.protocol!=="http:"||o.username!==""||o.password!==""||o.pathname!=="/"||o.search!==""||o.hash!=="")throw _("Allowed origins must be credential-free exact HTTP(S) origins.");if(o.protocol==="http:"){let n=K(d[2]??"").toLowerCase();if(!(n==="localhost"||n==="127.0.0.1"||n==="[::1]"))throw _("Plain HTTP is allowed only for exact loopback origins.")}if(i.has(o.origin))throw _("Allowed origins must be unique after canonicalization.");i.add(o.origin),r.push(o.origin)}return r}function K(e){if(e.startsWith("[")){let i=e.indexOf("]");return i===-1?e:e.slice(0,i+1)}let r=e.lastIndexOf(":");return r===-1?e:e.slice(0,r)}function _(e){return new l(e,400)}function y(e){return new l(e,400)}function H(e){return JSON.stringify({display_name:e.display_name,capability_template:e.capability_template,allowed_origins:[...e.allowed_origins].sort()})}function $(e,r){return JSON.stringify({app_id:e,reason:r})}function E(e){return new l(`Idempotency key was already used for a different ${e} request.`,409)}var Z={app_id:"dev_mcid_fixture_01",display_name:"Fixture storefront",environment:"dev",capability_template:"merchant_connect_sandbox",status:"draft",allowed_origins:["https://merchant.example"]},B={app_id:"production_mcid_fixture_01",display_name:"Production boundary fixture",environment:"production",capability_template:"merchant_connect_sandbox",status:"active",allowed_origins:["https://merchant.example"],credential_version:3},V={app_id:"app_fixture_future",display_name:"Future template fixture",environment:"dev",capability_template:"merchant_connect_dev_with_diagnostics",status:"active",allowed_origins:["https://merchant.example"],credential_version:1};var X=Object.freeze(["approved","declined_setup","declined_limit","payment_failed"]),T=Object.freeze({capabilities:{environment:"dev",contractVersion:"2026-07-09",checkedAt:"2026-07-10T00:00:00.000Z",capabilities:[{name:"fixtures",status:"ready",evidenceLevel:"verified",reasonCode:null,verifiedAt:"2026-07-10T00:00:00.000Z",limits:{networkCalls:0}},...["synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"].map(e=>({name:e,status:"unavailable",evidenceLevel:"contract",reasonCode:"DEV_NOT_DEPLOYED",verifiedAt:null,limits:{}}))]},faucetTransfer:{faucetTransferId:"sft_fixture_1001",userLinkRef:"ul_fixture_buyer_01",amount:{amount:"10.00",currency:"USDC"},status:"accepted",createdAt:"2026-07-10T00:00:00.000Z"},simulation:{simulationId:"sim_fixture_1001",scenario:"approved",executionMode:"pre_admission",status:"accepted",reasonCode:null,authorizationRef:null,chargeRef:null,createdAt:"2026-07-10T00:00:00.000Z",updatedAt:"2026-07-10T00:00:00.000Z"},webhookTestDelivery:{eventId:"evt_fixturetestping1001",deliveryId:"wd_fixturetestping1001",status:"queued",createdAt:"2026-07-10T00:00:00.000Z"}}),b="2026-07-10T00:00:00.000Z",O="0x1111111111111111111111111111111111111111";function Y(e={}){let r=e.scenario??"happy_path",i=0;return async(c,d)=>{let o=new URL(c),n=(d?.method??"GET").toUpperCase(),t=o.pathname;if(n==="POST"&&t==="/api/merchant/user-links/exchange")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:O,grantStatus:"active",pipelineReady:r!=="setup_required",scopes:["wallet.read","payments.write"]});if(n==="POST"&&t==="/api/merchant/payment-readiness")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:O,readinessScope:"account_default",chainId:84532,protocolId:"aave-v3",assetSymbol:"USDC",spendMode:"direct",pipelineReady:r!=="setup_required",...r==="setup_required"?{notReadyReason:"payment_route_not_provisioned"}:{}});if(n==="POST"&&t==="/api/merchant/checkout-sessions")return a({sessionId:"checkout_fixture",checkoutUrl:"https://dev.facto.to/checkout/checkout_fixture",status:"pending",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture"});if(n==="GET"&&t.startsWith("/api/merchant/checkout-sessions/"))return a({sessionId:"checkout_fixture",status:"charged",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture",chargeId:"charge_fixture",confirmedAt:b});if(n==="POST"&&t==="/api/merchant/authorization-sessions")return a(D("created"));if(n==="GET"&&t.startsWith("/api/merchant/authorization-sessions/"))return a(D("authorized"));if(n==="GET"&&t.startsWith("/api/merchant/payment-authorizations/"))return a(q());if(n==="DELETE"&&t.startsWith("/api/merchant/payment-authorizations/")){let p=decodeURIComponent(t.slice(37));return a({mandateId:p||"mandate_fixture",status:"revoked",revokedByThisRequest:!0})}if(n==="POST"&&t==="/api/merchant/mandate-path-change-sessions")return a(L("pending"));if(n==="GET"&&t.startsWith("/api/merchant/mandate-path-change-sessions/"))return a(L("completed"));if(n==="POST"&&t==="/api/merchant/payment-options")return a({paymentOptions:[{paymentOptionId:"fpo_fixture",label:"Fixture Direct",ready:r!=="setup_required",isDefault:!0,chainId:84532,chainLabel:"Base Sepolia",protocolLabel:"Aave V3",assetSymbol:"USDC",spendMode:"direct",settlementPath:"direct",...r==="setup_required"?{blockingReason:"setup_required"}:{}}],defaultPaymentOptionId:"fpo_fixture"});if(n==="POST"&&t==="/api/merchant/payments")return r==="idempotency_conflict"?a({error:{category:"conflict",code:"conflict",message:"fixture idempotency conflict",request_id:"req_fixture_idempotency_conflict",retryable:!1}},409):r==="declined_before_money"?a(A("declined"),402):a(A("charging"));if(n==="GET"&&t.startsWith("/api/merchant/payments/")){let p=r==="status_progression"?["charging","finalizing","succeeded"]:["succeeded"],s=p[Math.min(i,p.length-1)]??"succeeded";return i+=1,a(A(s))}if(n==="GET"&&t.startsWith("/api/merchant/user-links/")){let p=decodeURIComponent(t.slice(25));return a({appId:"app_fixture",userLinkRef:p||"ul_fixture_buyer_01",grantStatus:"active",paymentReady:r!=="setup_required",scopes:["wallet.read","payments.write"]})}if(n==="DELETE"&&t.startsWith("/api/merchant/user-links/"))return new Response(null,{status:204});if(n==="GET"&&t==="/api/merchant/payments")return a({data:[A("succeeded")],hasMore:!1});if(n==="GET"&&t==="/api/merchant/payment-authorizations")return a({data:[q()],hasMore:!1});if(n==="POST"&&t==="/api/merchant/refunds")return a(M());if(n==="GET"&&t==="/api/merchant/refunds")return a({data:[M()],hasMore:!1});if(n==="GET"&&t.startsWith("/api/merchant/refunds/"))return a(M());if(n==="POST"&&t==="/api/merchant/webhook-endpoints")return a({...R(),secret:"whsec_fixture_only"});if(n==="GET"&&t==="/api/dev/capabilities")return a(T.capabilities);if(n==="POST"&&t==="/api/dev/faucet/usdc")return a(T.faucetTransfer,202);if(n==="POST"&&t==="/api/dev/simulate/charge")return a(T.simulation,202);if(n==="GET"&&t.startsWith("/api/dev/simulations/"))return a(T.simulation);if(n==="POST"&&t==="/api/dev/test-mandates")return a({mandateId:"mandate_fixture",settlementMode:"simulated"},201);if(n==="POST"&&t.startsWith("/api/dev/test-mandates/")&&t.endsWith("/settle")){let p={};if(typeof d?.body=="string")try{p=JSON.parse(d.body)}catch{p={}}let s=p.outcome==="failed"?"failed":"succeeded",h=A(s);return s==="failed"&&p.declineReason&&(h.declineReason=p.declineReason),a(h)}return n==="POST"&&t.endsWith("/test-delivery")&&t.startsWith("/api/merchant/webhook-endpoints/")?a(T.webhookTestDelivery,202):n==="GET"&&t==="/api/merchant/webhook-endpoints"?a({data:[R()]}):n==="POST"&&t.endsWith("/rotate-secret")&&t.startsWith("/api/merchant/webhook-endpoints/")?a({...R(),secret:"whsec_fixture_rotated"}):n==="GET"&&t.startsWith("/api/merchant/webhook-endpoints/")?a(R()):n==="DELETE"&&t.startsWith("/api/merchant/webhook-endpoints/")?new Response(null,{status:204}):a({code:"fixture_route_not_found",method:n,path:t},404)}}var ee=Y;function D(e){return{sessionId:"mauth_fixture",authorizationUrl:"https://dev.facto.to/merchant-mandates/authorize?session=mauth_fixture",status:e,...e==="authorized"?{mandateId:"mandate_fixture"}:{},expiresAt:"2026-07-10T00:15:00.000Z",state:"state_fixture"}}function q(){return{mandateId:"mandate_fixture",appId:"app_fixture",status:"active",allowedUseCases:["immediate","recurring","metered"],limits:{perTxAmount:"100.00",periodAmount:"500.00",period:"monthly"},paymentPath:{ready:!0,summary:"Fixture payment path ready"},createdAt:b}}function A(e){return{paymentId:"mpay_fixture",mandateId:"mandate_fixture",merchantPaymentRef:"payment_fixture",status:e,amount:e==="declined"?"75.00":"9.99",currency:"USDC",useCase:e==="declined"?"metered":"recurring",...e==="declined"?{declineReason:"mandate_limit_exceeded"}:{},...e==="succeeded"?{chargeId:"charge_fixture",txHash:`0x${"1".repeat(64)}`,terminalAt:"2026-07-10T00:00:03.000Z"}:{},createdAt:b,updatedAt:"2026-07-10T00:00:03.000Z"}}function L(e){return{sessionId:"mpcs_fixture00000000000000000001",pathChangeUrl:"https://dev.facto.to/mandates/change-path?session=mpcs_fixture00000000000000000001",status:e,state:"state_path_change_fixture_000001",targetOrigin:"https://merchant.example",expiresAt:"2026-07-10T00:15:00.000Z"}}function M(){return{refundId:"re_fixture000000000000000000000001",paymentId:"mpay_fixture",status:"succeeded",amount:"9.99",currency:"USDC",reason:"requested_by_customer",merchantRefundRef:"merchant_refund_fixture",createdAt:b}}function R(){return{webhookEndpointId:"we_fixture000000000000000000000001",url:"https://merchant.example/facto-webhooks",enabledEvents:["payment.succeeded","payment.failed"],status:"enabled",createdAt:b}}function a(e,r=200){return new Response(JSON.stringify(e),{status:r,headers:{"content-type":"application/json"}})}export{W as CANONICAL_MERCHANT_CAPABILITY_TEMPLATES,N as MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS,l as MerchantPartnerWorkspaceMockError,Y as createFactoConnectFixtureTransport,ee as createFactoTestTransport,j as createMerchantPartnerWorkspaceMock,T as devFixtures,X as devScenarios,Z as merchantDevAppFixture,V as merchantFutureTemplateProjectionFixture,B as merchantProductionAppNegativeFixture};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@facto-to/connect",
3
- "version": "0.0.1-beta.13",
3
+ "version": "0.0.1-beta.14",
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)",
@@ -102,7 +102,7 @@
102
102
  "prepublishOnly": "npm run build"
103
103
  },
104
104
  "devDependencies": {
105
- "@facto-to/chains": "0.0.1-beta.13",
105
+ "@facto-to/chains": "0.0.1-beta.14",
106
106
  "@facto-to/engine-wire": "0.2.0",
107
107
  "@types/node": "^26.4.0",
108
108
  "jsdom": "^30.0.1",
@@ -1 +0,0 @@
1
- function h(r){let e=r.headers.get("retry-after");if(!(e===null||!/^[0-9]+$/.test(e)))return Number(e)}var b=new Set([400,401,402,403,404,410,412,422,423,428]),T=new Set(["idempotency_payload_mismatch","mapping_revision_not_approved","fact_type_not_allowed","managed_route_refused","ambiguous_lookup_selector","assertion_replayed","intent_sealed"]);function C(r){if(typeof r!="object"||r===null||Array.isArray(r))return{engineCode:void 0,requestId:void 0};let e=r;if(typeof e.error=="string"&&e.error.length>0)return{engineCode:e.error,requestId:typeof e.request_id=="string"&&e.request_id.length>0?e.request_id:void 0};if(typeof e.error=="object"&&e.error!==null&&!Array.isArray(e.error)){let n=e.error;return{engineCode:typeof n.code=="string"&&n.code.length>0?n.code:void 0,requestId:typeof n.request_id=="string"&&n.request_id.length>0?n.request_id:void 0}}return{engineCode:typeof e.code=="string"&&e.code.length>0?e.code:void 0,requestId:typeof e.request_id=="string"&&e.request_id.length>0?e.request_id:void 0}}function g(r,e,n){return r==="FACTO_CONFIG_INVALID"?"config_invalid":r==="FACTO_ENGINE_RESPONSE_INVALID"||r==="FACTO_REQUEST_ABORTED"||r==="FACTO_STATUS_POLL_ABORTED"||e===void 0?"unknown":b.has(e)||e===409&&n!==void 0&&T.has(n)?"refused":"unknown"}var c=class extends Error{code;retryable;status;details;retryAfterSeconds;constructor(e,n,t){super(n),this.name="FactoConnectServerError",this.code=e,this.retryable=t.retryable,this.status=t.status,this.details=t.details,this.retryAfterSeconds=t.retryAfterSeconds}},d=class extends c{outcome;engineCode;httpStatus;requestId;constructor(e,n,t){let o=t.httpStatus??t.status;super(e,n,{retryable:t.retryable,status:o,details:t.details,retryAfterSeconds:t.retryAfterSeconds}),this.name="CardError",this.httpStatus=o;let s=C(t.details);this.engineCode=t.engineCode??s.engineCode,this.requestId=t.requestId??s.requestId,this.outcome=t.outcome??g(e,o,this.engineCode)}},R=6e4,_=2147483647;function O(r,e){return r<=0?Promise.resolve():new Promise((n,t)=>{if(e?.aborted){t(new d("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},r),s=()=>{clearTimeout(o),t(new d("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};e?.addEventListener("abort",s,{once:!0})})}function v(r,e={}){return m(r,e,c)}function I(r,e={}){return m(r,e,d)}async function m(r,e,n){let t=e.maxRetries??2,o=e.baseDelayMs??200,s=e.maxDelayMs??5e3,A=e.respectRetryAfter??!0,i=e.maxRetryAfterMs??R;if(!Number.isFinite(i)||i<0||i>_)throw new d("FACTO_CONFIG_INVALID",`maxRetryAfterMs must be a number from 0 to ${_}`,{retryable:!1});let E=e.sleep??O,u=0;for(;;)try{return await r()}catch(a){if(!(a instanceof n)||!a.retryable||u>=t)throw a;let f=A&&typeof a.retryAfterSeconds=="number"?a.retryAfterSeconds*1e3:void 0;if(f!==void 0&&!(f<=i))throw a;u+=1;let y=Math.min(s,o*2**(u-1)),S=y*.25*Math.random(),l=f??y+S;e.onRetry?.({attempt:u,error:a,delayMs:l}),await E(l,e.signal)}}export{h as a,c as b,d as c,v as d,I as e};
@@ -1,2 +0,0 @@
1
- import{a as L,c as k,e as _e}from"./chunk-2WJ3CACP.js";var ze=1048576,oe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,V=/^pconn_[A-Za-z0-9_-]{16,}$/,se=/^[a-f0-9]{64}$/,G=/^sha256:[a-f0-9]{64}$/,ye=["environment","apiBaseUrl","timeoutMs","retry","maxResponseBytes","fetch"];function S(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function d(e,n=1,r=255){return typeof e=="string"&&[...e].length>=n&&[...e].length<=r}function v(e,n=1,r=255){return d(e,n,r)&&/^[\x21-\x7e]+$/.test(e)}function x(e){return typeof e=="string"&&oe.test(e)&&e!=="00000000-0000-0000-0000-000000000000"}function fe(e){return typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=2147483647}function m(e){return typeof e=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(e)&&Number.isFinite(Date.parse(e))}function f(e,n,r=[]){return S(e)&&n.every(t=>Object.hasOwn(e,t))&&Object.keys(e).every(t=>n.includes(t)||r.includes(t))}function l(e,n,r=[]){return S(e)&&n.every(t=>Object.hasOwn(e,t))}function i(e,n){if(!e)throw new k("FACTO_CONFIG_INVALID",n,{retryable:!1})}function W(e){return e===429||e>=500}function H(e){let n=e?.headers.get("x-request-id")?.trim();return n&&n.length>0?n:void 0}function w(e,n){return new k("FACTO_ENGINE_RESPONSE_INVALID","Card API response does not match the producer contract",{retryable:W(e),status:e,retryAfterSeconds:n?L(n):void 0,requestId:H(n)})}function le(e,n){return new k("FACTO_ENGINE_RESPONSE_INVALID",`Card API response body exceeds maxResponseBytes (${n} bytes)`,{retryable:W(e.status),status:e.status,details:{reason:"response_body_too_large",maxResponseBytes:n},retryAfterSeconds:L(e),requestId:H(e)})}async function Pe(e,n,r){let t=e.headers.get("content-length")?.trim();if(t!==void 0&&/^\d+$/.test(t)&&Number(t)>n)throw await e.body?.cancel().catch(()=>{}),le(e,n);if(!e.body)return"";let _=e.body.getReader(),y=[],C=0;try{for(;;){let{done:s,value:a}=await _.read();if(s)break;if(C+=a.byteLength,C>n||r.aborted)throw await _.cancel().catch(()=>{}),r.aborted?new k("FACTO_REQUEST_ABORTED","Card API request aborted or timed out",{retryable:!1}):le(e,n);y.push(a)}}finally{_.releaseLock()}let g=new Uint8Array(C),o=0;for(let s of y)g.set(s,o),o+=s.byteLength;return new TextDecoder().decode(g)}var ve=512;function Ee(e){return l(e,["error","message","request_id"])&&d(e.error,1,128)&&/^[a-z][a-z0-9_]*$/.test(e.error)&&d(e.message,1,ve)&&d(e.request_id,1,128)}function Te(e){if(!l(e,["error"])||!l(e.error,["category","code","message","request_id","retryable"],["details"]))return!1;let n=e.error;return!(typeof n.category!="string"||typeof n.code!="string"||typeof n.message!="string"||typeof n.request_id!="string"||typeof n.retryable!="boolean")}function De(e){e!==void 0&&(i(S(e),"retry options must be an object"),e.maxRetries!==void 0&&i(typeof e.maxRetries=="number"&&Number.isSafeInteger(e.maxRetries)&&e.maxRetries>=0,"retry.maxRetries must be a non-negative integer"),e.baseDelayMs!==void 0&&i(typeof e.baseDelayMs=="number"&&Number.isFinite(e.baseDelayMs)&&e.baseDelayMs>=0,"retry.baseDelayMs must be non-negative"),e.maxDelayMs!==void 0&&i(typeof e.maxDelayMs=="number"&&Number.isFinite(e.maxDelayMs)&&e.maxDelayMs>=0,"retry.maxDelayMs must be non-negative"),e.maxRetryAfterMs!==void 0&&i(typeof e.maxRetryAfterMs=="number"&&Number.isFinite(e.maxRetryAfterMs)&&e.maxRetryAfterMs>=0&&e.maxRetryAfterMs<=2147483647,"retry.maxRetryAfterMs is out of range"))}function ge(e,n){i(typeof window>"u","Card API credentials require a server runtime"),i(e.environment==="dev"||e.environment==="production","An explicit dev or production environment is required"),De(e.retry);let r={dev:"https://dev-api.facto.to",production:"https://api.facto.to"},t;i(e.environment!=="production"||typeof e.apiBaseUrl=="string","Production requires an explicit apiBaseUrl");try{t=new URL(e.apiBaseUrl??r.dev)}catch{throw new k("FACTO_CONFIG_INVALID","apiBaseUrl must be an absolute HTTP(S) origin",{retryable:!1})}i(!t.username&&!t.password&&!t.search&&!t.hash&&t.pathname==="/"&&(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)),"apiBaseUrl must be an HTTPS origin or an explicit loopback HTTP origin");let _=`${t.protocol}//${t.hostname.replace(/\.+$/,"")}${t.port?`:${t.port}`:""}`;i(!Object.values(r).includes(_)||_===r[e.environment],"The published endpoint must match the client environment");let y=t.origin,C=e.timeoutMs??3e4;i(Number.isSafeInteger(C)&&C>0,"timeoutMs must be a positive integer");let g=e.maxResponseBytes??ze;i(Number.isSafeInteger(g)&&g>0,"maxResponseBytes must be a positive integer");let o=e.fetch??globalThis.fetch?.bind(globalThis);i(typeof o=="function","A server fetch implementation is required");let s=e.retry;return async function(u,p,c,I,A,K,B={}){let ne=typeof c=="function"?c():new Headers(c),D=B.signal&&s?.signal?AbortSignal.any([B.signal,s.signal]):B.signal??s?.signal,ue=0,pe=async()=>{let te=ue===0?ne:typeof c=="function"?c():new Headers(c);ue+=1;let P=new AbortController,M=()=>P.abort();D?.addEventListener("abort",M,{once:!0}),D?.aborted&&M();let Re=setTimeout(M,C),q,re=new Promise((b,ie)=>{q=()=>ie(new k("FACTO_REQUEST_ABORTED","Card API request aborted or timed out",{retryable:!1})),P.signal.addEventListener("abort",q,{once:!0}),P.signal.aborted&&q()});try{if(P.signal.aborted)return await re;te.set("accept","application/json"),I!==void 0&&te.set("content-type","application/json");let b=await Promise.race([o(`${y}${p}`,{method:u,headers:te,redirect:"error",signal:P.signal,...I!==void 0?{body:I}:{}}),re]),ie=await Promise.race([Pe(b,g,P.signal),re]),O;try{O=JSON.parse(ie)}catch{throw w(b.status,b)}if(A.includes(b.status)&&K(O,b.status))return O;if(!b.ok){if(Ee(O))throw new k("FACTO_ENGINE_REQUEST_FAILED",`Card API ${n} request failed with status ${b.status}`,{retryable:W(b.status),status:b.status,details:O,retryAfterSeconds:L(b),requestId:O.request_id||H(b)});if(Te(O))throw new k("FACTO_ENGINE_REQUEST_FAILED",`Card API ${n} request failed with status ${b.status}`,{retryable:W(b.status),status:b.status,details:O,retryAfterSeconds:L(b),requestId:O.error.request_id||H(b)})}throw w(b.status,b)}catch(b){throw b instanceof k?b:new k("FACTO_ENGINE_REQUEST_FAILED","Card API transport failed; inspect the original operation before any new action",{retryable:!1})}finally{clearTimeout(Re),D?.removeEventListener("abort",M),q&&P.signal.removeEventListener("abort",q)}};return s!==void 0&&(u==="GET"||ne.has("Idempotency-Key"))?_e(pe,{...s,signal:D}):pe()}}import{randomUUID as nn}from"node:crypto";import{createPrivateKey as Be,sign as qe}from"node:crypto";var Le="facto-card-binding+jwt",Ne=/^pc_[A-Za-z0-9_-]{16,}$/,je=/^cbs_[A-Za-z0-9_-]{16,}$/,Fe=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Ue=/^[A-Za-z0-9_-]+$/,$e=/^[0-9]{4}$/,me=300,he=600,Ke=["card.metadata.view","card.use_for_facto_payments"],Me=["passkey","mfa","reauthenticated_session"],We=["provider_authenticated_app","device_bound_confirmation"],He={dev:"urn:facto:sandbox:card-program-connect:binding-proof",production:"urn:facto:production:card-program-connect:binding-proof"};function be(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function N(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1e9&&e<=9999999999}function Ae(e){return typeof e=="string"&&Ue.test(e)&&Buffer.from(e,"base64url").byteLength===32}function Ve(e){return/^[0-9]{12,19}$/.test(e)||/[0-9]{13}/.test(e)}function Ge(e,n){return i(S(e),"Binding assertion proof claim is required"),e.mode==="provider_reauthentication"?(i(f(e,["mode","authenticatedAtSeconds","assurance"])&&N(e.authenticatedAtSeconds)&&e.authenticatedAtSeconds<=n&&n-e.authenticatedAtSeconds<=he&&Me.includes(e.assurance),"Reauthentication proof requires valid authenticatedAtSeconds (within 600 seconds before issuedAtSeconds) and assurance"),{mode:"provider_reauthentication",authenticated_at:e.authenticatedAtSeconds,assurance:e.assurance}):(i(e.mode==="provider_second_channel"&&f(e,["mode","approvedAtSeconds","approvalRef","channelType"])&&N(e.approvedAtSeconds)&&e.approvedAtSeconds<=n&&n-e.approvedAtSeconds<=he&&d(e.approvalRef,16,255)&&We.includes(e.channelType),"Second-channel proof requires valid approvedAtSeconds (within 600 seconds before issuedAtSeconds), approvalRef (16-255 chars), and channelType"),{mode:"provider_second_channel",approved_at:e.approvedAtSeconds,approval_ref:e.approvalRef,channel_type:e.channelType})}function Je(e){i(Array.isArray(e)&&e.length>=1&&e.length<=20,"Binding assertion requires 1 to 20 asserted cards");let n=new Set,r=0;return e.map(t=>{i(f(t,["externalCardId"],["isEntryCard","display"])&&d(t.externalCardId,8,512)&&!Ve(t.externalCardId)&&(t.isEntryCard===void 0||typeof t.isEntryCard=="boolean"),"Each asserted card requires an opaque externalCardId (8-512 non-PAN chars) and optional boolean isEntryCard"),i(!n.has(t.externalCardId),"Asserted cards must have unique externalCardId values"),n.add(t.externalCardId),t.isEntryCard===!0&&(r+=1,i(r<=1,"At most one asserted card may set isEntryCard to true"));let _;if(t.display!==void 0){i(f(t.display,[],["network","cardType","last4"]),"Asserted card display accepts only network, cardType, and last4");let y=t.display;i((y.network===void 0||d(y.network,1,32))&&(y.cardType===void 0||d(y.cardType,1,32))&&(y.last4===void 0||typeof y.last4=="string"&&$e.test(y.last4)),"Asserted card display fields are out of contract bounds");let C={};y.network!==void 0&&(C.network=y.network),y.cardType!==void 0&&(C.card_type=y.cardType),y.last4!==void 0&&(C.last4=y.last4),Object.keys(C).length>0&&(_=C)}return{card_ref:t.externalCardId,relationship_type:"owner",...t.isEntryCard===!0?{is_entry_card:!0}:{},..._!==void 0?{display:_}:{}}})}async function Ze(e,n,r){if(typeof e=="function"){let t=await e(n);return i(t instanceof Uint8Array&&t.byteLength===64,"Binding assertion signer must return a 64-byte Ed25519 signature"),t}i(f(e,["kty","crv","x","d"],["kid","alg","use","key_ops","ext"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&(e.alg===void 0||e.alg==="EdDSA"||e.alg==="Ed25519")&&(e.use===void 0||e.use==="sig")&&(e.key_ops===void 0||Array.isArray(e.key_ops)&&e.key_ops.every(t=>typeof t=="string")&&e.key_ops.includes("sign"))&&(e.ext===void 0||typeof e.ext=="boolean")&&(e.kid===void 0||e.kid===r)&&Ae(e.x)&&Ae(e.d),"Binding assertion signer must be a valid Ed25519 private JWK (matching signingKeyId when kid is present) or async signing callback");try{let t=Be({key:{kty:"OKP",crv:"Ed25519",x:e.x,d:e.d},format:"jwk"});return new Uint8Array(qe(null,n,t))}catch{throw new k("FACTO_CONFIG_INVALID","Invalid Ed25519 private JWK for binding assertion signing",{retryable:!1})}}async function Ce(e){i(f(e,["environment","providerConnectionId","programId","bindingSessionId","issuer","subject","jti","factoChallenge","sessionRequestDigest","requestedUserConsents","proof","cards","signingKeyId","signer"],["issuedAtSeconds","notBeforeSeconds","expiresAtSeconds"]),"Binding assertion input contains missing or unknown fields"),i(e.environment==="dev"||e.environment==="production","environment must be dev or production"),i(typeof e.providerConnectionId=="string"&&Ne.test(e.providerConnectionId),"providerConnectionId must be a pc_ provider connection identifier (not a pconn_ program connection identifier)"),i(d(e.programId,1,255),"programId must be 1 to 255 characters"),i(typeof e.bindingSessionId=="string"&&je.test(e.bindingSessionId),"bindingSessionId must be a cbs_ identifier"),i(d(e.issuer,1,512),"issuer is required"),i(d(e.subject,16,512),"subject must be a pairwise opaque identifier of 16 to 512 characters"),i(d(e.jti,16,255),"jti must be 16 to 255 characters"),i(d(e.factoChallenge,1,512),"factoChallenge is required"),i(typeof e.sessionRequestDigest=="string"&&G.test(e.sessionRequestDigest),"sessionRequestDigest must be a sha256:<hex> digest"),i(d(e.signingKeyId,1,255)&&e.signingKeyId.trim()===e.signingKeyId&&!e.signingKeyId.includes("\0"),"signingKeyId must be a non-empty trimmed identifier without NUL bytes");let n=e.requestedUserConsents;i(Array.isArray(n)&&n.length>0&&new Set(n).size===n.length&&n.every(p=>Ke.includes(p)),"requestedUserConsents must be a non-empty unique set of supported consent purposes");let r=e.issuedAtSeconds??Math.floor(Date.now()/1e3),t=e.notBeforeSeconds??r,_=e.expiresAtSeconds??r+me;i(N(r)&&N(t)&&N(_)&&t<=r&&r<=_&&_-r<=me,"Binding assertion timestamps must satisfy nbf <= iat <= exp with lifetime <= 300 seconds");let y=Ge(e.proof,r),C=Je(e.cards),g=be({typ:Le,alg:"EdDSA",kid:e.signingKeyId}),o=be({iss:e.issuer,aud:He[e.environment],sub:e.subject,iat:r,nbf:t,exp:_,jti:e.jti,binding_session_id:e.bindingSessionId,facto_challenge:e.factoChallenge,session_request_digest:e.sessionRequestDigest,connection_id:e.providerConnectionId,environment:e.environment,program_ref:e.programId,proof:y,cards:C,requested_user_consents:[...n]}),s=new TextEncoder().encode(`${g}.${o}`),a=await Ze(e.signer,s,e.signingKeyId),u=`${g}.${o}.${Buffer.from(a).toString("base64url")}`;return i(u.length>=128&&u.length<=16384&&Fe.test(u),"Signed binding assertion exceeds compact JWS bounds"),u}import{createHash as Qe,createHmac as Xe,timingSafeEqual as Ye}from"node:crypto";var en=/^(?:[0-9a-fA-F]{2})+$/;function E(e){return new k("FACTO_CONFIG_INVALID",e,{retryable:!1})}function J(e){if(typeof e=="string")throw E("apiKeySecret cannot be a bare string; pass { encoding: 'hex', value }, { encoding: 'utf8', value }, or Uint8Array");if(e instanceof Uint8Array){if(e.byteLength===0)throw E("apiKeySecret Uint8Array must not be empty");return new Uint8Array(e)}if(typeof e!="object"||e===null||Array.isArray(e))throw E("apiKeySecret must be { encoding: 'hex', value }, { encoding: 'utf8', value }, or Uint8Array");if(Object.keys(e).length!==2||!Object.hasOwn(e,"encoding")||!Object.hasOwn(e,"value"))throw E("apiKeySecret must contain only { encoding: 'hex' | 'utf8', value: string }");let{encoding:r,value:t}=e;if(r==="utf8"){if(typeof t!="string"||t.length===0)throw E("apiKeySecret with encoding 'utf8' must have a non-empty string value");return new TextEncoder().encode(t)}if(r==="hex"){if(typeof t!="string"||!en.test(t))throw E("apiKeySecret with encoding 'hex' must be a non-empty, even-length hexadecimal string");let _=new Uint8Array(t.length/2);for(let y=0;y<t.length;y+=2)_[y/2]=Number.parseInt(t.slice(y,y+2),16);return _}throw E("apiKeySecret encoding must be 'hex' or 'utf8', or pass a Uint8Array")}function ae(e){let n=J(e.secret),r=Qe("sha256").update(e.body).digest("hex"),t=["FACTO-HMAC-V2",e.method,e.target,String(e.timestamp),e.nonce,r].join(`
2
- `),_=new Headers({"x-api-key":e.apiKeyId,"x-api-timestamp":String(e.timestamp),"x-api-nonce":e.nonce,"x-api-signature":Xe("sha256",n).update(t,"utf8").digest("hex")});return e.idempotencyKey!==void 0&&_.set("Idempotency-Key",e.idempotencyKey),_}function Zn(e){let n=J(e.secret),r=new Headers(e.headers),t=r.get("x-api-timestamp"),_=r.get("x-api-nonce"),y=r.get("x-api-signature");if(r.get("x-api-key")!==e.apiKeyId||!t||!/^\d{10}$/.test(t)||!_||!/^[\x21-\x7e]{1,128}$/.test(_)||!y||!/^[a-f0-9]{64}$/.test(y))return!1;let C=ae({...e,secret:n,timestamp:Number(t),nonce:_}).get("x-api-signature");return Ye(Buffer.from(y,"hex"),Buffer.from(C,"hex"))}var $=/^cbs_[A-Za-z0-9_-]{16,}$/,Y=/^cint_[A-Za-z0-9_-]{16,}$/,ee=/^cb_[A-Za-z0-9_-]{16,}$/,ce=/^sha256:[a-fA-F0-9]{64}$/,xe=["authorization_updated","clearing","reversal","refund","chargeback","settlement"],X=["authorization_requested",...xe],tn=["facto_admission","durable_commit","provider_authorization","chain_finality","provider_settlement"],rn=["active","frozen","closed","replaced"],on=/^[A-Za-z0-9_.:-]{1,64}$/,sn=/^[0-9]+\.[0-9]{2,6}$/,an=/^-?[0-9]+\.[0-9]{2,6}$/;function h(e,n){return typeof e=="string"&&n.test(e)}function R(e){return e===null||typeof e=="string"}function F(e,n=-2147483648){return typeof e=="number"&&Number.isInteger(e)&&e>=n&&e<=2147483647}function U(e,n=128){return d(e,1,n)&&!/[0-9]{13}/.test(e)}function j(e,n){return e==null||n(e)}function Q(e){return Array.isArray(e)&&e.every(n=>h(n,ee))}function ke(e){return l(e,["network","type","last4"])&&R(e.network)&&(e.type===null||["virtual","physical","unknown"].includes(String(e.type)))&&(e.last4===null||typeof e.last4=="string"&&/^[0-9]{4}$/.test(e.last4))}function z(e){return typeof e=="string"&&/^0x0{32}[0-9a-fA-F]{32}$/.test(e)}function dn(e){return typeof e=="string"&&on.test(e)}function cn(e){return!l(e,["snapshot_token","snapshot_at","to_at","items","next_cursor","complete"])||!d(e.snapshot_token,16,4096)||!m(e.snapshot_at)||!m(e.to_at)||typeof e.complete!="boolean"||e.next_cursor!==null&&!d(e.next_cursor,1,4096)||e.complete&&e.next_cursor!==null||!Array.isArray(e.items)||e.items.length>100?!1:e.items.every(n=>l(n,["event_id","origin_connection_id","connection_sequence","event_sha256","target_revision","delivery_state"],["accepted_at"])&&x(n.event_id)&&typeof n.origin_connection_id=="string"&&V.test(n.origin_connection_id)&&(n.connection_sequence===null||typeof n.connection_sequence=="number"&&Number.isSafeInteger(n.connection_sequence)&&n.connection_sequence>=1)&&typeof n.event_sha256=="string"&&se.test(n.event_sha256)&&x(n.target_revision)&&typeof n.delivery_state=="string"&&(n.accepted_at===void 0||m(n.accepted_at)))}function un(e){return l(e,["replay_id","selection_id","target_revision","status"])&&x(e.replay_id)&&x(e.selection_id)&&x(e.target_revision)&&e.status==="accepted"}function pn(e){i(f(e,["target_revision","page_size"],["selection_id","from_at","to_at","snapshot_token","cursor"]),"Reconciliation requires only the generated query fields"),i(x(e.target_revision)&&typeof e.page_size=="number"&&Number.isInteger(e.page_size)&&e.page_size>=1&&e.page_size<=100,"Reconciliation target_revision and page_size are invalid"),i(x(e.selection_id)&&!Object.hasOwn(e,"from_at")&&!Object.hasOwn(e,"to_at")||!Object.hasOwn(e,"selection_id")&&m(e.from_at)&&m(e.to_at)&&Date.parse(e.from_at)<=Date.parse(e.to_at),"Select exactly one fixed selection or explicit time window"),i((e.snapshot_token===void 0||d(e.snapshot_token,16,4096))&&(e.cursor===void 0||d(e.cursor,16,4096)&&d(e.snapshot_token,16,4096)),"A cursor requires its original snapshot token")}function _n(e){i(S(e),"Authorization lookup requires criteria");let n=Object.hasOwn(e,"criteria")?(i(f(e,["criteria"])&&S(e.criteria),"Authorization lookup wrapper requires only criteria"),e.criteria):e;i(S(n),"Authorization lookup requires criteria");let r=n.by==="external_authorization_id"?f(n,["by","external_authorization_id","resource_version","mapping_revision"],["fact_type"])&&d(n.external_authorization_id,1,256)&&d(n.resource_version,1,255)&&d(n.mapping_revision,1,255)&&(n.fact_type===void 0||X.includes(String(n.fact_type))):n.by==="supplier_transaction_id"?f(n,["by","supplier_transaction_id","resource_version","mapping_revision"],["fact_type"])&&typeof n.supplier_transaction_id=="string"&&d(n.supplier_transaction_id.trim(),1,256)&&d(n.resource_version,1,255)&&d(n.mapping_revision,1,255)&&(n.fact_type===void 0||X.includes(String(n.fact_type))):n.by==="idempotency_key"?f(n,["by","idempotency_key","original_credential_key_id"],["operation"])&&d(n.idempotency_key,16,255)&&d(n.original_credential_key_id,1,255)&&(n.operation===void 0||n.operation==="create_authorization"):n.by==="charge_id"&&f(n,["by","charge_id"])&&z(n.charge_id);return i(r,"Select exactly one complete external_authorization_id, supplier_transaction_id, idempotency_key, or public charge_id"),n}function ln(e){i(f(e,["external_card_id","external_authorization_id","amount","currency","resource_version","mapping_revision","cardholder_verification"],["supplier_transaction_id","client_transaction_id","merchant_name","merchant_mcc","merchant_country","occurred_at","decision_mode","decision_timeout_ms","deadline_at"]),"Authorization create requires the complete generated request");let t=e.cardholder_verification;i(U(e.external_card_id,512)&&d(e.external_authorization_id,1,256)&&h(e.amount,sn)&&(e.currency==="USD"||e.currency==="USDC")&&d(e.resource_version,1,255)&&d(e.mapping_revision,1,255)&&(e.merchant_name===void 0||d(e.merchant_name,0,256))&&(e.merchant_mcc===void 0||h(e.merchant_mcc,/^[0-9]{4}$/))&&(e.merchant_country===void 0||d(e.merchant_country,2,3))&&(e.occurred_at===void 0||m(e.occurred_at))&&[e.supplier_transaction_id,e.client_transaction_id].every(_=>_===void 0||typeof _=="string"&&d(_.trim(),1,256))&&(e.decision_mode===void 0||e.decision_mode==="asynchronous"||e.decision_mode==="synchronous")&&(e.decision_timeout_ms===void 0||e.decision_mode==="synchronous"&&typeof e.decision_timeout_ms=="number"&&Number.isInteger(e.decision_timeout_ms)&&e.decision_timeout_ms>=50&&e.decision_timeout_ms<=5e3)&&(e.deadline_at===void 0||e.decision_mode==="synchronous"&&m(e.deadline_at))&&f(t,["method","verified_at","evidence_id"])&&["pin","biometric","cdcvm","signature","no_cvm","provider_attested"].includes(String(t.method))&&m(t.verified_at)&&d(t.evidence_id,1,256),"Authorization fields, currency, mapping/version, or cardholder verification is invalid")}function yn(e,n){i(d(e,1,255)&&e!=="."&&e!==".."&&!e.includes("/"),"externalId must be a valid external authorization identifier"),i(f(n,["fact_type","amount","currency","resource_version","predecessor_version","mapping_revision","recorded_at"],["supplier_transaction_id","parent_supplier_transaction_id","client_transaction_id","merchant_name","merchant_mcc","merchant_country"]),"Authorization fact requires the complete generated request"),i(xe.includes(String(n.fact_type))&&h(n.amount,an)&&(n.currency==="USD"||n.currency==="USDC")&&d(n.resource_version,1,255)&&typeof n.predecessor_version=="string"&&d(n.predecessor_version.trim(),1,255)&&n.predecessor_version!==n.resource_version&&d(n.mapping_revision,1,255)&&m(n.recorded_at)&&(n.merchant_name===void 0||d(n.merchant_name,1,255))&&(n.merchant_mcc===void 0||h(n.merchant_mcc,/^[0-9]{4}$/))&&(n.merchant_country===void 0||d(n.merchant_country,2,3))&&[n.supplier_transaction_id,n.parent_supplier_transaction_id,n.client_transaction_id].every(_=>_===void 0||typeof _=="string"&&d(_.trim(),1,255)),"Authorization fact type, predecessor version, amount, or timestamp is invalid")}function Oe(e){return Array.isArray(e)&&e.length===5&&e.every((n,r)=>l(n,["kind","state","recorded_at","source_system"],["observed_at","safe_code"])&&n.kind===tn[r]&&["unobserved","pending","confirmed","rejected","indeterminate"].includes(String(n.state))&&m(n.recorded_at)&&["facto","provider","chain"].includes(String(n.source_system))&&(n.safe_code===void 0||d(n.safe_code,1,64))&&(n.observed_at===void 0||m(n.observed_at))&&(n.state!=="confirmed"||m(n.observed_at))&&(n.state!=="unobserved"||!Object.hasOwn(n,"observed_at")))}function fn(e){return!l(e,["receipt_event_id","charge_id","mapping_revision","operation_type","resource_version","execution_outcome","terminal_action","finalized_at","facts_at_finality"],["external_authorization_id","authorization_ref"])||!x(e.receipt_event_id)||!z(e.charge_id)||!(d(e.external_authorization_id,1,256)||d(e.authorization_ref,1,256))||!d(e.mapping_revision,1,255)||!X.includes(String(e.operation_type))||!d(e.resource_version,1,255)||!m(e.finalized_at)||!Oe(e.facts_at_finality)||e.facts_at_finality[3].state!=="confirmed"?!1:e.terminal_action==="releaseFor"?e.execution_outcome==="succeeded"&&e.facts_at_finality[0].state==="confirmed"&&e.facts_at_finality[1].state==="confirmed":e.terminal_action==="cancelReservation"&&e.execution_outcome==="failed"}function gn(e){if(e===void 0)return!0;if(!S(e)||!S(e.issuer)||!Array.isArray(e.issuer.entries)||!Array.isArray(e.refund_cases))return!1;let n=e.issuer,r=n.entries;return["state","cleared_amount","reversed_amount","refunded_amount"].every(t=>typeof n[t]=="string")&&r.every(t=>S(t)&&["operation_type","resource_version","amount","currency","recorded_at","link_status"].every(_=>typeof t[_]=="string")&&t.currency==="USDC"&&(t.unlinked_reason===void 0||typeof t.unlinked_reason=="string"))&&e.refund_cases.every(t=>S(t)&&["case_id","source_operation_type","source_resource_version","status","amount","excess_amount","updated_at"].every(_=>typeof t[_]=="string")&&(t.paid_amount===void 0||typeof t.paid_amount=="string")&&(t.not_payable_reason===void 0||typeof t.not_payable_reason=="string"))}function mn(e,n){if(e===void 0)return!0;if(!S(e)||typeof e.fee_total!="string"||!S(e.fee_breakdown))return!1;let r=e.fee_breakdown;if(!["base_fee","fast_pay_fee","pooled_surcharge"].every(_=>typeof r[_]=="string"))return!1;let t=e.user_payment;return t!==void 0&&(!S(t)||!Number.isSafeInteger(t.chain_id)||typeof t.tx_hash!="string"||!/^0x[0-9a-fA-F]{64}$/.test(t.tx_hash)||t.asset_symbol!==void 0&&typeof t.asset_symbol!="string")?!1:e.refund_payments===void 0?!0:Array.isArray(e.refund_payments)?e.refund_payments.length===0?!0:n&&e.refund_payments.every(_=>S(_)&&Number.isSafeInteger(_.chain_id)&&typeof _.case_id=="string"&&typeof _.paid_amount=="string"&&typeof _.recorded_by=="string"&&typeof _.tx_hash=="string"&&/^0x[0-9a-fA-F]{64}$/.test(_.tx_hash)):!1}function hn(e){if(!l(e,["external_authorization_id","processing_status","origin_connection_id","resource_version","mapping_revision"],["charge_id","final_receipt","decline_reason_code","supplier_transaction_id","facts","revision","operation_type","decision","lifecycle","payment_details"])||!d(e.external_authorization_id,1,256)||typeof e.origin_connection_id!="string"||!V.test(e.origin_connection_id)||!d(e.resource_version,1,255)||!d(e.mapping_revision,1,255)||e.charge_id!==void 0&&e.charge_id!==null&&!z(e.charge_id)||e.supplier_transaction_id!==void 0&&!d(e.supplier_transaction_id,1,256)||e.facts!==void 0&&!Oe(e.facts)||e.revision!==void 0&&!fe(e.revision)||e.operation_type!==void 0&&!X.includes(String(e.operation_type))||e.decision!==void 0&&!["approved","declined","self_reversed_timeout"].includes(String(e.decision))||e.decline_reason_code!==void 0&&!dn(e.decline_reason_code)||!gn(e.lifecycle)||!mn(e.payment_details,e.lifecycle!==void 0))return!1;if(e.processing_status==="succeeded"||e.processing_status==="failed"){if(Object.hasOwn(e,"final_receipt")&&e.final_receipt!==void 0){if(!z(e.charge_id)||!fn(e.final_receipt)||Object.hasOwn(e,"decline_reason_code"))return!1;let n=e.final_receipt,r=n.external_authorization_id??n.authorization_ref;return n.execution_outcome===e.processing_status&&n.charge_id===e.charge_id&&r===e.external_authorization_id&&n.mapping_revision===e.mapping_revision&&n.resource_version===e.resource_version&&(e.operation_type===void 0||n.operation_type===e.operation_type)}return e.processing_status==="succeeded"?!Object.hasOwn(e,"decline_reason_code")&&(e.charge_id===void 0||z(e.charge_id)):z(e.charge_id)||(e.charge_id===void 0||e.charge_id===null)&&(e.decision==="declined"||e.decision==="self_reversed_timeout"||e.decline_reason_code!==void 0)}return!Object.hasOwn(e,"final_receipt")&&!Object.hasOwn(e,"decline_reason_code")&&(e.processing_status==="processing"||e.processing_status==="indeterminate"&&(e.charge_id===void 0||e.charge_id===null))}function bn(e){return!l(e,["observed_at","resolution"],["authorization"])||!m(e.observed_at)?!1:e.resolution==="not_observed"?!Object.hasOwn(e,"authorization")||e.authorization===void 0:hn(e.authorization)?e.resolution==="resolved"?["succeeded","failed"].includes(e.authorization.processing_status):e.resolution==="pending"?e.authorization.processing_status==="processing":e.resolution==="unknown"&&e.authorization.processing_status==="indeterminate":!1}function An(e){return l(e,["charge_id","status"])&&z(e.charge_id)&&["processing","approved","declined"].includes(String(e.status))&&!Object.hasOwn(e,"final_receipt")}function Cn(e){return l(e,["operation_id","status"])&&x(e.operation_id)&&e.status==="recorded"}function In(e,n){return!l(e,["deadline_at","decision_id"])||!m(e.deadline_at)||!x(e.decision_id)?!1:n===200?e.decision==="approved"&&e.status==="approved"&&z(e.charge_id)&&m(e.decided_at):typeof e.error!="string"||typeof e.message!="string"||typeof e.request_id!="string"?!1:n===408&&e.error==="decision_deadline_exceeded"&&!Object.hasOwn(e,"decision")?!0:m(e.decided_at)&&(n===422&&e.decision==="declined"||n===408&&e.decision==="self_reversed_timeout")}function Sn(e){if(!l(e,["binding_session_id","status","binding_url","expires_at","proof_policy"])||!h(e.binding_session_id,$)||e.status!=="pending"||typeof e.binding_url!="string"||!m(e.expires_at))return!1;let n=e.proof_policy;return l(n,["allowed_modes","challenge_after_facto_auth","challenge_delivery"],["card_selection_supported"])&&Array.isArray(n.allowed_modes)&&n.allowed_modes.length>0&&new Set(n.allowed_modes).size===n.allowed_modes.length&&n.allowed_modes.every(r=>r==="provider_reauthentication"||r==="provider_second_channel")&&n.challenge_after_facto_auth===!0&&(n.challenge_delivery==="browser_handoff"||n.challenge_delivery==="provider_backend")&&(n.card_selection_supported===void 0||n.card_selection_supported===!0)}function Ie(e){if(!S(e)||!h(e.binding_session_id,$)||!m(e.expires_at))return!1;let n=["binding_session_id","status","expires_at"];return["pending","proof_pending","consent_pending"].includes(String(e.status))?l(e,n)&&!["outcome","binding_ids","failure_reason","completed_at"].some(r=>Object.hasOwn(e,r)):e.status==="completed"?Object.hasOwn(e,"completed_at")&&!m(e.completed_at)?!1:e.outcome==="bound"?l(e,[...n,"outcome","binding_ids"],["completed_at"])&&!Object.hasOwn(e,"failure_reason")&&Q(e.binding_ids):e.outcome==="declined"&&l(e,[...n,"outcome","failure_reason"],["completed_at"])&&!Object.hasOwn(e,"binding_ids")&&e.failure_reason==="declined_by_user":e.status==="cancelled"?l(e,n,["completed_at","failure_reason"])&&!["outcome","binding_ids"].some(r=>Object.hasOwn(e,r))&&(!Object.hasOwn(e,"completed_at")||m(e.completed_at))&&(!Object.hasOwn(e,"failure_reason")||["cancelled_by_user","cancelled_by_partner","proof_rejected","admission_closed","no_eligible_cards","integrity_conflict"].includes(String(e.failure_reason))):e.status==="expired"&&l(e,n,["failure_reason"])&&!["completed_at","outcome","binding_ids"].some(r=>Object.hasOwn(e,r))&&(!Object.hasOwn(e,"failure_reason")||e.failure_reason==="expired"||e.failure_reason==="proof_timeout")}function wn(e){return l(e,["binding_session_id","status","proof_received_at"])&&h(e.binding_session_id,$)&&e.status==="consent_pending"&&m(e.proof_received_at)}function xn(e){return l(e,["binding_session_id","facto_challenge","session_request_digest","expires_at"])&&h(e.binding_session_id,$)&&d(e.facto_challenge,1,512)&&h(e.session_request_digest,G)&&m(e.expires_at)}function kn(e){i(f(e,["requested_user_consents","return_uri"]),"Binding session requires the generated consent and return URI fields");let n=e.requested_user_consents;i(Array.isArray(n)&&n.length>0&&new Set(n).size===n.length&&n.every(r=>r==="card.metadata.view"||r==="card.use_for_facto_payments"),"Binding session consents are invalid"),i(typeof e.return_uri=="string"&&Buffer.byteLength(e.return_uri,"utf8")<=2048&&e.return_uri.startsWith("https://")&&!/[#\r\n]/.test(e.return_uri)&&e.return_uri.slice(8).split(/[/?]/,1)[0].length>0&&!e.return_uri.slice(8).split(/[/?]/,1)[0].includes("@"),"An exact registered HTTPS return URI is required")}function Se(e){i(f(e,["proof_format","binding_assertion"])&&e.proof_format==="compact-jws"&&typeof e.binding_assertion=="string"&&e.binding_assertion.length>=128&&e.binding_assertion.length<=16384&&/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e.binding_assertion),"The original compact JWS provider proof is required")}function On(e){return l(e,["id","revision","cards"])&&h(e.id,Y)&&h(e.revision,ce)&&Array.isArray(e.cards)&&e.cards.every(n=>l(n,["binding_id","status","card"])&&h(n.binding_id,ee)&&typeof n.status=="string"&&ke(n.card))}function Rn(e){return l(e,["id","status","revision","added_binding_ids","removed_binding_ids","kept_binding_ids"])&&h(e.id,Y)&&["applied","no_change"].includes(String(e.status))&&h(e.revision,ce)&&Q(e.added_binding_ids)&&Q(e.removed_binding_ids)&&Q(e.kept_binding_ids)}function zn(e){return l(e,["id","status"])&&h(e.id,Y)&&e.status==="cancelled"}function Pn(e){return l(e,["state"],["amount","constrained_by","currency","reason"])&&["available","not_chargeable","unavailable"].includes(String(e.state))&&(e.amount===void 0||typeof e.amount=="string")&&(e.constrained_by===void 0||typeof e.constrained_by=="string")&&(e.currency===void 0||typeof e.currency=="string")&&(e.reason===void 0||typeof e.reason=="string")}function vn(e){return l(e,["currency","period","available_to_charge"],["expires_at","per_tx_limit","period_limit","period_remaining","period_used"])&&typeof e.currency=="string"&&typeof e.period=="string"&&Pn(e.available_to_charge)&&(e.expires_at===void 0||e.expires_at===null||m(e.expires_at))&&(e.per_tx_limit===void 0||R(e.per_tx_limit))&&(e.period_limit===void 0||R(e.period_limit))&&(e.period_remaining===void 0||R(e.period_remaining))&&(e.period_used===void 0||R(e.period_used))}function En(e){return l(e,["account_ref","asset_decimals","asset_symbol","chain_id","name","protocol","spend_mode","yield_token_symbol"],["balance","balance_raw","balance_updated_at"])&&typeof e.account_ref=="string"&&F(e.asset_decimals,0)&&typeof e.asset_symbol=="string"&&typeof e.chain_id=="number"&&Number.isSafeInteger(e.chain_id)&&e.chain_id>=0&&typeof e.name=="string"&&typeof e.protocol=="string"&&typeof e.spend_mode=="string"&&typeof e.yield_token_symbol=="string"&&(e.balance===void 0||R(e.balance))&&(e.balance_raw===void 0||R(e.balance_raw))&&(e.balance_updated_at===void 0||e.balance_updated_at===null||m(e.balance_updated_at))}function Tn(e){return e===void 0||l(e,["configured","state"],["reason","limits","pipeline"])&&typeof e.configured=="boolean"&&["ready","not_configured","unavailable"].includes(String(e.state))&&(e.reason===void 0||e.reason===null||typeof e.reason=="string")&&(e.limits===void 0||vn(e.limits))&&(e.pipeline===void 0||En(e.pipeline))}function Dn(e){if(!l(e,["binding"],["found"])||e.found!==void 0&&typeof e.found!="boolean")return!1;let n=e.binding;return n===null?e.found!==!0:(e.found===void 0||e.found===!0)&&l(n,["id","status","revision","card"],["funding"])&&h(n.id,ee)&&typeof n.status=="string"&&F(n.revision,1)&&ke(n.card)&&Tn(n.funding)}function Bn(e){return l(e,["items"])&&Array.isArray(e.items)&&e.items.every(n=>l(n,["id","event_kind","binding_id","binding_revision","connection_sequence","delivery_attempts","last_delivery_error","dead_lettered_at","replay_count"])&&h(n.id,oe)&&typeof n.event_kind=="string"&&h(n.binding_id,ee)&&F(n.binding_revision,1)&&(n.connection_sequence===null||typeof n.connection_sequence=="number"&&Number.isSafeInteger(n.connection_sequence)&&n.connection_sequence>=1)&&F(n.delivery_attempts,1)&&R(n.last_delivery_error)&&(n.dead_lettered_at===null||m(n.dead_lettered_at))&&F(n.replay_count,0))}function qn(e){return l(e,["id","status"])&&x(e.id)&&e.status==="accepted"}function Ln(e){return l(e,["delivery_id","disposition","effect"])&&x(e.delivery_id)&&(e.disposition==="duplicate"?e.effect===null:e.disposition==="applied"&&["revoked","status_updated","released","none"].includes(String(e.effect)))}function Nn(e){i(f(e,["intent_token","approval_id","approval_sha256","revision","cards"],["external_account_id"])&&v(e.intent_token,32,8192)&&d(e.approval_id,1,255)&&h(e.approval_sha256,se)&&h(e.revision,ce)&&j(e.external_account_id,n=>typeof n=="string"&&n.length>0&&Buffer.byteLength(n,"utf8")<=512),"Card replacement requires the original complete approved request"),i(Array.isArray(e.cards)&&e.cards.length<=50&&e.cards.every(n=>f(n,["external_card_id"],["network","type","last4"])&&U(n.external_card_id,255)&&j(n.network,r=>U(r,40))&&j(n.type,r=>r==="virtual"||r==="physical"||r==="unknown")&&j(n.last4,r=>typeof r=="string"&&/^[0-9]{4}$/.test(r))),"Target cards must match the generated safe card projection")}function jn(e){i(f(e,["delivery_id","kind","assertion_jws"],["external_card_id","lifecycle_status","external_account_id"])&&x(e.delivery_id)&&typeof e.assertion_jws=="string"&&e.assertion_jws.trim().length>=32,"Inbound event requires a UUID delivery_id and signed assertion_jws");let n=r=>r==null;i(e.kind==="account.released"?d(e.external_account_id,1,512)&&n(e.external_card_id)&&n(e.lifecycle_status):U(e.external_card_id)&&n(e.external_account_id)&&(e.kind==="card.unbound"?n(e.lifecycle_status):e.kind==="card.lifecycle_changed"&&rn.includes(String(e.lifecycle_status))),"Inbound event fields must match the declared event kind")}function T(e){return i(e&&v(e.idempotencyKey,16,255),"An explicit original Idempotency-Key of 16 to 255 characters is required"),e.idempotencyKey}function Z(e){return i(h(e,$),"id must be the original binding session identifier"),`/api/card/connect/sessions/${e}`}function de(e){return i(h(e,Y),"id must be the original connect intent identifier"),`/api/card/connect/intents/${e}`}function we(e){return i(e?.rawBody===void 0||typeof e?.rawBody=="string","rawBody must preserve the original authenticated request bytes"),e?.rawBody}function tt(e){i(f(e,["environment","connectionId","programId","apiKeyId","apiKeySecret"],[...ye,"nowSeconds","createNonce"]),"Card client options cannot contain human session or arbitrary authentication fields"),i(typeof e.connectionId=="string"&&V.test(e.connectionId),"connectionId must be a pconn_ connection identifier"),i(d(e.programId,1,128)&&v(e.apiKeyId),"programId and apiKeyId are required");let n=J(e.apiKeySecret),r=ge(e,"program"),t=Object.freeze({connectionId:e.connectionId,environment:e.environment,programId:e.programId}),_=e.apiKeyId,y=e.nowSeconds??(()=>Math.floor(Date.now()/1e3)),C=e.createNonce??nn;function g(o,s,a,u="POST"){let p=y(),c=C();return i(Number.isSafeInteger(p)&&p>=1e9&&p<=9999999999,"nowSeconds must return a ten-digit Unix timestamp in seconds"),i(v(c,1,128),"createNonce must return a bounded canonical nonce"),ae({secret:n,apiKeyId:_,method:u,target:o,timestamp:p,nonce:c,body:s,idempotencyKey:a})}return Object.freeze({scope:t,sessions:Object.freeze({async create(o,s){kn(o),i(f(s,["idempotencyKey"],["cardSelection","signal"]),"Binding session create options accept only idempotencyKey, optional cardSelection, and optional signal");let a=T(s);i(s.cardSelection===void 0||typeof s.cardSelection=="boolean","cardSelection must be a boolean when provided");let u={...o,program_ref:t.programId},p=JSON.stringify(u),c="/api/card/connect/sessions";return r("POST",c,()=>{let A=g(c,p,a);return s.cardSelection===!0&&A.set("x-facto-card-selection","1"),A},p,[201],Sn,s)},async get(o,s){let a=Z(o),u=await r("GET",a,()=>g(a,"",void 0,"GET"),void 0,[200],Ie,s);if(u.binding_session_id!==o)throw w(200);return u},async submitProof(o,s,a){let u=`${Z(o)}/provider-proof`,p=T(a);i(S(s),"Provider proof input is required");let c;if(Object.hasOwn(s,"proof_format")||Object.hasOwn(s,"binding_assertion"))Se(s),c=s;else{i(!["environment","programId","bindingSessionId","connectionId"].some(D=>Object.hasOwn(s,D)),"Provider proof assertion inherits environment, programId, and bindingSessionId from client scope and session id, and requires explicit providerConnectionId (pc_...)");let K=s,B=K.issuedAtSeconds??y();c={proof_format:"compact-jws",binding_assertion:await Ce({...K,environment:t.environment,programId:t.programId,bindingSessionId:o,issuedAtSeconds:B})},Se(c)}let I=JSON.stringify(c),A=await r("POST",u,()=>g(u,I,p),I,[202],wn,a);if(A.binding_session_id!==o)throw w(202);return A},async getProofChallenge(o,s){let a=`${Z(o)}/proof-challenge`,u=await r("GET",a,()=>g(a,"",void 0,"GET"),void 0,[200],xn,s);if(u.binding_session_id!==o)throw w(200);return u},async cancel(o,s){let a=`${Z(o)}/cancel`,u=T(s),p=we(s)??"{}",c=await r("POST",a,()=>g(a,p,u),p,[200],Ie,s);if(c.binding_session_id!==o)throw w(200);return c}}),intents:Object.freeze({async listCards(o,s){let a=`${de(o)}/cards`;i(f(s,["intentToken"],["signal"])&&v(s.intentToken,32,8192),"intentToken must be a valid HTTP header value of at least 32 characters");let p=await r("GET",a,()=>{let c=g(a,"",void 0,"GET");return c.set("x-facto-intent-token",s.intentToken),c},void 0,[200],On,s);if(p.id!==o)throw w(200);return p},async replaceCards(o,s,a){let u=`${de(o)}/cards`;Nn(s);let p=T(a),c=JSON.stringify(s),I=await r("PUT",u,()=>g(u,c,p,"PUT"),c,[200],Rn,a);if(I.id!==o)throw w(200);return I},async cancel(o,s,a){let u=`${de(o)}/cancel`;i(f(s,["intent_token"])&&v(s.intent_token,32,8192),"Cancel requires the original intent_token body of at least 32 characters");let p=JSON.stringify(s),c=await r("POST",u,()=>g(u,p),p,[200],zn,a);if(c.id!==o)throw w(200);return c}}),bindings:Object.freeze({async lookup(o,s){i(f(o,["external_card_id"])&&U(o.external_card_id),"Binding lookup requires only an opaque external_card_id in its body");let a=JSON.stringify(o),u="/api/card/bindings/lookup";return r("POST",u,()=>g(u,a),a,[200],Dn,s)}}),authorizations:Object.freeze({create:(async(o,s)=>{ln(o);let a=T(s),u={...o,program_id:t.programId},p=JSON.stringify(u),c="/api/card/authorizations";return o.decision_mode==="synchronous"?r("POST",c,()=>g(c,p,a),p,[200,422,408],In,s):r("POST",c,()=>g(c,p,a),p,[200],An,s)}),async recordFact(o,s,a){yn(o,s);let u=T(a),p={...s,program_id:t.programId},c=JSON.stringify(p),I=`/api/card/authorizations/${encodeURIComponent(o)}/facts`;return r("POST",I,()=>g(I,c,u),c,[200],Cn,a)},async lookup(o,s){let a=_n(o),u={program_id:t.programId,criteria:a},p=JSON.stringify(u),c="/api/card/authorizations/lookup",I=await r("POST",c,()=>g(c,p),p,[200],bn,s),A=I.authorization;if(A&&(A.origin_connection_id!==t.connectionId||a.by==="charge_id"&&A.charge_id?.toLowerCase()!==a.charge_id.toLowerCase()||a.by==="external_authorization_id"&&(A.external_authorization_id!==a.external_authorization_id||A.resource_version!==a.resource_version||A.mapping_revision!==a.mapping_revision||a.fact_type!==void 0&&A.operation_type!==void 0&&A.operation_type!==a.fact_type)||a.by==="supplier_transaction_id"&&(A.supplier_transaction_id!==a.supplier_transaction_id.trim()||A.resource_version!==a.resource_version||A.mapping_revision!==a.mapping_revision||a.fact_type!==void 0&&A.operation_type!==void 0&&A.operation_type!==a.fact_type)))throw w(200);return I}}),events:Object.freeze({async record(o,s){jn(o);let a=JSON.stringify(o),u="/api/card/events",p=await r("POST",u,()=>g(u,a),a,[200],Ln,s),c=o.kind==="card.unbound"?"revoked":o.kind==="card.lifecycle_changed"?"status_updated":"released";if(p.delivery_id!==o.delivery_id||p.disposition==="applied"&&p.effect!=="none"&&p.effect!==c)throw w(200);return p}}),deliveries:Object.freeze({async list(o,s){pn(o);let a={...o,program_id:t.programId},u=JSON.stringify(a),p="/api/card/deliveries/reconciliations/list",c=await r("POST",p,()=>g(p,u),u,[200],cn,s);if(c.items.length>o.page_size)throw w(200);return c}}),deliveryReplays:Object.freeze({async create(o,s){i(f(o,["selection_id"])&&x(o.selection_id),"Delivery replay requires a fixed selection_id UUID");let a=T(s),u={...o,program_id:t.programId},p=JSON.stringify(u),c="/api/card/deliveries/replays",I=await r("POST",c,()=>g(c,p,a),p,[202],un,s);if(I.selection_id!==o.selection_id)throw w(202);return I}}),deadLetters:Object.freeze({async list(o,s){i(o===void 0||f(o,[],["limit"])&&j(o.limit,c=>typeof c=="number"&&Number.isInteger(c)&&c>=1&&c<=100),"Dead-letter limit must be null, absent, or an integer from 1 to 100");let a=typeof o?.limit=="number"?o.limit:void 0,u=a!==void 0?`/api/card/deliveries/dead-letters?limit=${a}`:"/api/card/deliveries/dead-letters",p=await r("GET",u,()=>g(u,"",void 0,"GET"),void 0,[200],Bn,s);if(p.items.length>(a??50))throw w(200);return p},async replay(o,s){i(x(o),"The dead-letter path identifier must be a UUID");let a=`/api/card/deliveries/dead-letters/${o}/replay`,u=we(s),p=await r("POST",a,()=>g(a,u??""),u,[202],qn,s);if(p.id!==o)throw w(202);return p}})})}export{V as a,G as b,ye as c,S as d,d as e,v as f,x as g,fe as h,m as i,f as j,l as k,i as l,w as m,Te as n,ge as o,ae as p,Zn as q,tt as r};