@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,2 +1,2 @@
1
- "use strict";var ce=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var Me=Object.prototype.hasOwnProperty;var Ve=(e,n)=>{for(var i in n)ce(e,i,{get:n[i],enumerable:!0})},Ge=(e,n,i,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let p of Ke(n))!Me.call(e,p)&&p!==i&&ce(e,p,{get:()=>n[p],enumerable:!(t=$e(n,p))||t.enumerable});return e};var He=e=>Ge(ce({},"__esModule",{value:!0}),e);var pt={};Ve(pt,{createCardClient:()=>Le,createCardConnectAdminClient:()=>ct,isCardConnectAdminErrorEnvelope:()=>at});module.exports=He(pt);var We=new Set([400,401,402,403,404,410,412,422,423,428]),Je=new Set(["idempotency_payload_mismatch","mapping_revision_not_approved","fact_type_not_allowed","managed_route_refused","ambiguous_lookup_selector","assertion_replayed","intent_sealed"]);function Ze(e){if(typeof e!="object"||e===null||Array.isArray(e))return{engineCode:void 0,requestId:void 0};let n=e;if(typeof n.error=="string"&&n.error.length>0)return{engineCode:n.error,requestId:typeof n.request_id=="string"&&n.request_id.length>0?n.request_id:void 0};if(typeof n.error=="object"&&n.error!==null&&!Array.isArray(n.error)){let i=n.error;return{engineCode:typeof i.code=="string"&&i.code.length>0?i.code:void 0,requestId:typeof i.request_id=="string"&&i.request_id.length>0?i.request_id:void 0}}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}}function Qe(e,n,i){return e==="FACTO_CONFIG_INVALID"?"config_invalid":e==="FACTO_ENGINE_RESPONSE_INVALID"||e==="FACTO_REQUEST_ABORTED"||e==="FACTO_STATUS_POLL_ABORTED"||n===void 0?"unknown":We.has(n)||n===409&&i!==void 0&&Je.has(i)?"refused":"unknown"}var pe=class extends Error{code;retryable;status;details;retryAfterSeconds;constructor(n,i,t){super(i),this.name="FactoConnectServerError",this.code=n,this.retryable=t.retryable,this.status=t.status,this.details=t.details,this.retryAfterSeconds=t.retryAfterSeconds}},w=class extends pe{outcome;engineCode;httpStatus;requestId;constructor(n,i,t){let p=t.httpStatus??t.status;super(n,i,{retryable:t.retryable,status:p,details:t.details,retryAfterSeconds:t.retryAfterSeconds}),this.name="CardError",this.httpStatus=p;let y=Ze(t.details);this.engineCode=t.engineCode??y.engineCode,this.requestId=t.requestId??y.requestId,this.outcome=t.outcome??Qe(n,p,this.engineCode)}},Xe=6e4,Ae=2147483647;function Ye(e,n){return e<=0?Promise.resolve():new Promise((i,t)=>{if(n?.aborted){t(new w("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let p=setTimeout(()=>{n?.removeEventListener("abort",y),i()},e),y=()=>{clearTimeout(p),t(new w("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};n?.addEventListener("abort",y,{once:!0})})}function Ce(e,n={}){return en(e,n,w)}async function en(e,n,i){let t=n.maxRetries??2,p=n.baseDelayMs??200,y=n.maxDelayMs??5e3,A=n.respectRetryAfter??!0,f=n.maxRetryAfterMs??Xe;if(!Number.isFinite(f)||f<0||f>Ae)throw new w("FACTO_CONFIG_INVALID",`maxRetryAfterMs must be a number from 0 to ${Ae}`,{retryable:!1});let d=n.sleep??Ye,a=0;for(;;)try{return await e()}catch(r){if(!(r instanceof i)||!r.retryable||a>=t)throw r;let _=A&&typeof r.retryAfterSeconds=="number"?r.retryAfterSeconds*1e3:void 0;if(_!==void 0&&!(_<=f))throw r;a+=1;let u=Math.min(y,p*2**(a-1)),C=u*.25*Math.random(),b=_??u+C;n.onRetry?.({attempt:a,error:r,delayMs:b}),await d(b,n.signal)}}function j(e){let n=e.headers.get("retry-after");if(!(n===null||!/^[0-9]+$/.test(n)))return Number(n)}var nn=1048576,_e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,E=/^pconn_[A-Za-z0-9_-]{16,}$/,ue=/^[a-f0-9]{64}$/,B=/^sha256:[a-f0-9]{64}$/,Q=["environment","apiBaseUrl","timeoutMs","retry","maxResponseBytes","fetch"];function I(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function c(e,n=1,i=255){return typeof e=="string"&&[...e].length>=n&&[...e].length<=i}function k(e,n=1,i=255){return c(e,n,i)&&/^[\x21-\x7e]+$/.test(e)}function h(e){return typeof e=="string"&&_e.test(e)&&e!=="00000000-0000-0000-0000-000000000000"}function R(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 g(e,n,i=[]){return I(e)&&n.every(t=>Object.hasOwn(e,t))&&Object.keys(e).every(t=>n.includes(t)||i.includes(t))}function l(e,n,i=[]){return I(e)&&n.every(t=>Object.hasOwn(e,t))}function o(e,n){if(!e)throw new w("FACTO_CONFIG_INVALID",n,{retryable:!1})}function J(e){return e===429||e>=500}function Z(e){let n=e?.headers.get("x-request-id")?.trim();return n&&n.length>0?n:void 0}function x(e,n){return new w("FACTO_ENGINE_RESPONSE_INVALID","Card API response does not match the producer contract",{retryable:J(e),status:e,retryAfterSeconds:n?j(n):void 0,requestId:Z(n)})}function Se(e,n){return new w("FACTO_ENGINE_RESPONSE_INVALID",`Card API response body exceeds maxResponseBytes (${n} bytes)`,{retryable:J(e.status),status:e.status,details:{reason:"response_body_too_large",maxResponseBytes:n},retryAfterSeconds:j(e),requestId:Z(e)})}async function tn(e,n,i){let t=e.headers.get("content-length")?.trim();if(t!==void 0&&/^\d+$/.test(t)&&Number(t)>n)throw await e.body?.cancel().catch(()=>{}),Se(e,n);if(!e.body)return"";let p=e.body.getReader(),y=[],A=0;try{for(;;){let{done:a,value:r}=await p.read();if(a)break;if(A+=r.byteLength,A>n||i.aborted)throw await p.cancel().catch(()=>{}),i.aborted?new w("FACTO_REQUEST_ABORTED","Card API request aborted or timed out",{retryable:!1}):Se(e,n);y.push(r)}}finally{p.releaseLock()}let f=new Uint8Array(A),d=0;for(let a of y)f.set(a,d),d+=a.byteLength;return new TextDecoder().decode(f)}var rn=512;function on(e){return l(e,["error","message","request_id"])&&c(e.error,1,128)&&/^[a-z][a-z0-9_]*$/.test(e.error)&&c(e.message,1,rn)&&c(e.request_id,1,128)}function le(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 an(e){e!==void 0&&(o(I(e),"retry options must be an object"),e.maxRetries!==void 0&&o(typeof e.maxRetries=="number"&&Number.isSafeInteger(e.maxRetries)&&e.maxRetries>=0,"retry.maxRetries must be a non-negative integer"),e.baseDelayMs!==void 0&&o(typeof e.baseDelayMs=="number"&&Number.isFinite(e.baseDelayMs)&&e.baseDelayMs>=0,"retry.baseDelayMs must be non-negative"),e.maxDelayMs!==void 0&&o(typeof e.maxDelayMs=="number"&&Number.isFinite(e.maxDelayMs)&&e.maxDelayMs>=0,"retry.maxDelayMs must be non-negative"),e.maxRetryAfterMs!==void 0&&o(typeof e.maxRetryAfterMs=="number"&&Number.isFinite(e.maxRetryAfterMs)&&e.maxRetryAfterMs>=0&&e.maxRetryAfterMs<=2147483647,"retry.maxRetryAfterMs is out of range"))}function X(e,n){o(typeof window>"u","Card API credentials require a server runtime"),o(e.environment==="dev"||e.environment==="production","An explicit dev or production environment is required"),an(e.retry);let i={dev:"https://dev-api.facto.to",production:"https://api.facto.to"},t;o(e.environment!=="production"||typeof e.apiBaseUrl=="string","Production requires an explicit apiBaseUrl");try{t=new URL(e.apiBaseUrl??i.dev)}catch{throw new w("FACTO_CONFIG_INVALID","apiBaseUrl must be an absolute HTTP(S) origin",{retryable:!1})}o(!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 p=`${t.protocol}//${t.hostname.replace(/\.+$/,"")}${t.port?`:${t.port}`:""}`;o(!Object.values(i).includes(p)||p===i[e.environment],"The published endpoint must match the client environment");let y=t.origin,A=e.timeoutMs??3e4;o(Number.isSafeInteger(A)&&A>0,"timeoutMs must be a positive integer");let f=e.maxResponseBytes??nn;o(Number.isSafeInteger(f)&&f>0,"maxResponseBytes must be a positive integer");let d=e.fetch??globalThis.fetch?.bind(globalThis);o(typeof d=="function","A server fetch implementation is required");let a=e.retry;return async function(s,_,u,C,b,H,N={}){let oe=typeof u=="function"?u():new Headers(u),L=N.signal&&a?.signal?AbortSignal.any([N.signal,a.signal]):N.signal??a?.signal,he=0,be=async()=>{let ae=he===0?oe:typeof u=="function"?u():new Headers(u);he+=1;let T=new AbortController,W=()=>T.abort();L?.addEventListener("abort",W,{once:!0}),L?.aborted&&W();let Ue=setTimeout(W,A),F,se=new Promise((v,de)=>{F=()=>de(new w("FACTO_REQUEST_ABORTED","Card API request aborted or timed out",{retryable:!1})),T.signal.addEventListener("abort",F,{once:!0}),T.signal.aborted&&F()});try{if(T.signal.aborted)return await se;ae.set("accept","application/json"),C!==void 0&&ae.set("content-type","application/json");let v=await Promise.race([d(`${y}${_}`,{method:s,headers:ae,redirect:"error",signal:T.signal,...C!==void 0?{body:C}:{}}),se]),de=await Promise.race([tn(v,f,T.signal),se]),O;try{O=JSON.parse(de)}catch{throw x(v.status,v)}if(b.includes(v.status)&&H(O,v.status))return O;if(!v.ok){if(on(O))throw new w("FACTO_ENGINE_REQUEST_FAILED",`Card API ${n} request failed with status ${v.status}`,{retryable:J(v.status),status:v.status,details:O,retryAfterSeconds:j(v),requestId:O.request_id||Z(v)});if(le(O))throw new w("FACTO_ENGINE_REQUEST_FAILED",`Card API ${n} request failed with status ${v.status}`,{retryable:J(v.status),status:v.status,details:O,retryAfterSeconds:j(v),requestId:O.error.request_id||Z(v)})}throw x(v.status,v)}catch(v){throw v instanceof w?v:new w("FACTO_ENGINE_REQUEST_FAILED","Card API transport failed; inspect the original operation before any new action",{retryable:!1})}finally{clearTimeout(Ue),L?.removeEventListener("abort",W),F&&T.signal.removeEventListener("abort",F)}};return a!==void 0&&(s==="GET"||oe.has("Idempotency-Key"))?Ce(be,{...a,signal:L}):be()}}var ze=require("node:crypto");var Y=require("node:crypto");var sn="facto-card-binding+jwt",dn=/^pc_[A-Za-z0-9_-]{16,}$/,cn=/^cbs_[A-Za-z0-9_-]{16,}$/,pn=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,_n=/^[A-Za-z0-9_-]+$/,un=/^[0-9]{4}$/,ve=300,we=600,ln=["card.metadata.view","card.use_for_facto_payments"],yn=["passkey","mfa","reauthenticated_session"],fn=["provider_authenticated_app","device_bound_confirmation"],gn={dev:"urn:facto:sandbox:card-program-connect:binding-proof",production:"urn:facto:production:card-program-connect:binding-proof"};function Ie(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function U(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1e9&&e<=9999999999}function xe(e){return typeof e=="string"&&_n.test(e)&&Buffer.from(e,"base64url").byteLength===32}function mn(e){return/^[0-9]{12,19}$/.test(e)||/[0-9]{13}/.test(e)}function hn(e,n){return o(I(e),"Binding assertion proof claim is required"),e.mode==="provider_reauthentication"?(o(g(e,["mode","authenticatedAtSeconds","assurance"])&&U(e.authenticatedAtSeconds)&&e.authenticatedAtSeconds<=n&&n-e.authenticatedAtSeconds<=we&&yn.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}):(o(e.mode==="provider_second_channel"&&g(e,["mode","approvedAtSeconds","approvalRef","channelType"])&&U(e.approvedAtSeconds)&&e.approvedAtSeconds<=n&&n-e.approvedAtSeconds<=we&&c(e.approvalRef,16,255)&&fn.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 bn(e){o(Array.isArray(e)&&e.length>=1&&e.length<=20,"Binding assertion requires 1 to 20 asserted cards");let n=new Set,i=0;return e.map(t=>{o(g(t,["externalCardId"],["isEntryCard","display"])&&c(t.externalCardId,8,512)&&!mn(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"),o(!n.has(t.externalCardId),"Asserted cards must have unique externalCardId values"),n.add(t.externalCardId),t.isEntryCard===!0&&(i+=1,o(i<=1,"At most one asserted card may set isEntryCard to true"));let p;if(t.display!==void 0){o(g(t.display,[],["network","cardType","last4"]),"Asserted card display accepts only network, cardType, and last4");let y=t.display;o((y.network===void 0||c(y.network,1,32))&&(y.cardType===void 0||c(y.cardType,1,32))&&(y.last4===void 0||typeof y.last4=="string"&&un.test(y.last4)),"Asserted card display fields are out of contract bounds");let A={};y.network!==void 0&&(A.network=y.network),y.cardType!==void 0&&(A.card_type=y.cardType),y.last4!==void 0&&(A.last4=y.last4),Object.keys(A).length>0&&(p=A)}return{card_ref:t.externalCardId,relationship_type:"owner",...t.isEntryCard===!0?{is_entry_card:!0}:{},...p!==void 0?{display:p}:{}}})}async function An(e,n,i){if(typeof e=="function"){let t=await e(n);return o(t instanceof Uint8Array&&t.byteLength===64,"Binding assertion signer must return a 64-byte Ed25519 signature"),t}o(g(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===i)&&xe(e.x)&&xe(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=(0,Y.createPrivateKey)({key:{kty:"OKP",crv:"Ed25519",x:e.x,d:e.d},format:"jwk"});return new Uint8Array((0,Y.sign)(null,n,t))}catch{throw new w("FACTO_CONFIG_INVALID","Invalid Ed25519 private JWK for binding assertion signing",{retryable:!1})}}async function ke(e){o(g(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"),o(e.environment==="dev"||e.environment==="production","environment must be dev or production"),o(typeof e.providerConnectionId=="string"&&dn.test(e.providerConnectionId),"providerConnectionId must be a pc_ provider connection identifier (not a pconn_ program connection identifier)"),o(c(e.programId,1,255),"programId must be 1 to 255 characters"),o(typeof e.bindingSessionId=="string"&&cn.test(e.bindingSessionId),"bindingSessionId must be a cbs_ identifier"),o(c(e.issuer,1,512),"issuer is required"),o(c(e.subject,16,512),"subject must be a pairwise opaque identifier of 16 to 512 characters"),o(c(e.jti,16,255),"jti must be 16 to 255 characters"),o(c(e.factoChallenge,1,512),"factoChallenge is required"),o(typeof e.sessionRequestDigest=="string"&&B.test(e.sessionRequestDigest),"sessionRequestDigest must be a sha256:<hex> digest"),o(c(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;o(Array.isArray(n)&&n.length>0&&new Set(n).size===n.length&&n.every(_=>ln.includes(_)),"requestedUserConsents must be a non-empty unique set of supported consent purposes");let i=e.issuedAtSeconds??Math.floor(Date.now()/1e3),t=e.notBeforeSeconds??i,p=e.expiresAtSeconds??i+ve;o(U(i)&&U(t)&&U(p)&&t<=i&&i<=p&&p-i<=ve,"Binding assertion timestamps must satisfy nbf <= iat <= exp with lifetime <= 300 seconds");let y=hn(e.proof,i),A=bn(e.cards),f=Ie({typ:sn,alg:"EdDSA",kid:e.signingKeyId}),d=Ie({iss:e.issuer,aud:gn[e.environment],sub:e.subject,iat:i,nbf:t,exp:p,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:A,requested_user_consents:[...n]}),a=new TextEncoder().encode(`${f}.${d}`),r=await An(e.signer,a,e.signingKeyId),s=`${f}.${d}.${Buffer.from(r).toString("base64url")}`;return o(s.length>=128&&s.length<=16384&&pn.test(s),"Signed binding assertion exceeds compact JWS bounds"),s}var $=require("node:crypto");var Cn=/^(?:[0-9a-fA-F]{2})+$/;function D(e){return new w("FACTO_CONFIG_INVALID",e,{retryable:!1})}function ye(e){if(typeof e=="string")throw D("apiKeySecret cannot be a bare string; pass { encoding: 'hex', value }, { encoding: 'utf8', value }, or Uint8Array");if(e instanceof Uint8Array){if(e.byteLength===0)throw D("apiKeySecret Uint8Array must not be empty");return new Uint8Array(e)}if(typeof e!="object"||e===null||Array.isArray(e))throw D("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 D("apiKeySecret must contain only { encoding: 'hex' | 'utf8', value: string }");let{encoding:i,value:t}=e;if(i==="utf8"){if(typeof t!="string"||t.length===0)throw D("apiKeySecret with encoding 'utf8' must have a non-empty string value");return new TextEncoder().encode(t)}if(i==="hex"){if(typeof t!="string"||!Cn.test(t))throw D("apiKeySecret with encoding 'hex' must be a non-empty, even-length hexadecimal string");let p=new Uint8Array(t.length/2);for(let y=0;y<t.length;y+=2)p[y/2]=Number.parseInt(t.slice(y,y+2),16);return p}throw D("apiKeySecret encoding must be 'hex' or 'utf8', or pass a Uint8Array")}function Oe(e){let n=ye(e.secret),i=(0,$.createHash)("sha256").update(e.body).digest("hex"),t=["FACTO-HMAC-V2",e.method,e.target,String(e.timestamp),e.nonce,i].join(`
2
- `),p=new Headers({"x-api-key":e.apiKeyId,"x-api-timestamp":String(e.timestamp),"x-api-nonce":e.nonce,"x-api-signature":(0,$.createHmac)("sha256",n).update(t,"utf8").digest("hex")});return e.idempotencyKey!==void 0&&p.set("Idempotency-Key",e.idempotencyKey),p}var G=/^cbs_[A-Za-z0-9_-]{16,}$/,re=/^cint_[A-Za-z0-9_-]{16,}$/,ie=/^cb_[A-Za-z0-9_-]{16,}$/,ge=/^sha256:[a-fA-F0-9]{64}$/,Te=["authorization_updated","clearing","reversal","refund","chargeback","settlement"],te=["authorization_requested",...Te],Sn=["facto_admission","durable_commit","provider_authorization","chain_finality","provider_settlement"],vn=["active","frozen","closed","replaced"],wn=/^[A-Za-z0-9_.:-]{1,64}$/,In=/^[0-9]+\.[0-9]{2,6}$/,xn=/^-?[0-9]+\.[0-9]{2,6}$/;function S(e,n){return typeof e=="string"&&n.test(e)}function P(e){return e===null||typeof e=="string"}function M(e,n=-2147483648){return typeof e=="number"&&Number.isInteger(e)&&e>=n&&e<=2147483647}function V(e,n=128){return c(e,1,n)&&!/[0-9]{13}/.test(e)}function K(e,n){return e==null||n(e)}function ne(e){return Array.isArray(e)&&e.every(n=>S(n,ie))}function De(e){return l(e,["network","type","last4"])&&P(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 kn(e){return typeof e=="string"&&wn.test(e)}function On(e){return!l(e,["snapshot_token","snapshot_at","to_at","items","next_cursor","complete"])||!c(e.snapshot_token,16,4096)||!m(e.snapshot_at)||!m(e.to_at)||typeof e.complete!="boolean"||e.next_cursor!==null&&!c(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"])&&h(n.event_id)&&typeof n.origin_connection_id=="string"&&E.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"&&ue.test(n.event_sha256)&&h(n.target_revision)&&typeof n.delivery_state=="string"&&(n.accepted_at===void 0||m(n.accepted_at)))}function Rn(e){return l(e,["replay_id","selection_id","target_revision","status"])&&h(e.replay_id)&&h(e.selection_id)&&h(e.target_revision)&&e.status==="accepted"}function En(e){o(g(e,["target_revision","page_size"],["selection_id","from_at","to_at","snapshot_token","cursor"]),"Reconciliation requires only the generated query fields"),o(h(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"),o(h(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"),o((e.snapshot_token===void 0||c(e.snapshot_token,16,4096))&&(e.cursor===void 0||c(e.cursor,16,4096)&&c(e.snapshot_token,16,4096)),"A cursor requires its original snapshot token")}function Pn(e){o(I(e),"Authorization lookup requires criteria");let n=Object.hasOwn(e,"criteria")?(o(g(e,["criteria"])&&I(e.criteria),"Authorization lookup wrapper requires only criteria"),e.criteria):e;o(I(n),"Authorization lookup requires criteria");let i=n.by==="external_authorization_id"?g(n,["by","external_authorization_id","resource_version","mapping_revision"],["fact_type"])&&c(n.external_authorization_id,1,256)&&c(n.resource_version,1,255)&&c(n.mapping_revision,1,255)&&(n.fact_type===void 0||te.includes(String(n.fact_type))):n.by==="supplier_transaction_id"?g(n,["by","supplier_transaction_id","resource_version","mapping_revision"],["fact_type"])&&typeof n.supplier_transaction_id=="string"&&c(n.supplier_transaction_id.trim(),1,256)&&c(n.resource_version,1,255)&&c(n.mapping_revision,1,255)&&(n.fact_type===void 0||te.includes(String(n.fact_type))):n.by==="idempotency_key"?g(n,["by","idempotency_key","original_credential_key_id"],["operation"])&&c(n.idempotency_key,16,255)&&c(n.original_credential_key_id,1,255)&&(n.operation===void 0||n.operation==="create_authorization"):n.by==="charge_id"&&g(n,["by","charge_id"])&&z(n.charge_id);return o(i,"Select exactly one complete external_authorization_id, supplier_transaction_id, idempotency_key, or public charge_id"),n}function zn(e){o(g(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;o(V(e.external_card_id,512)&&c(e.external_authorization_id,1,256)&&S(e.amount,In)&&(e.currency==="USD"||e.currency==="USDC")&&c(e.resource_version,1,255)&&c(e.mapping_revision,1,255)&&(e.merchant_name===void 0||c(e.merchant_name,0,256))&&(e.merchant_mcc===void 0||S(e.merchant_mcc,/^[0-9]{4}$/))&&(e.merchant_country===void 0||c(e.merchant_country,2,3))&&(e.occurred_at===void 0||m(e.occurred_at))&&[e.supplier_transaction_id,e.client_transaction_id].every(p=>p===void 0||typeof p=="string"&&c(p.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))&&g(t,["method","verified_at","evidence_id"])&&["pin","biometric","cdcvm","signature","no_cvm","provider_attested"].includes(String(t.method))&&m(t.verified_at)&&c(t.evidence_id,1,256),"Authorization fields, currency, mapping/version, or cardholder verification is invalid")}function Tn(e,n){o(c(e,1,255)&&e!=="."&&e!==".."&&!e.includes("/"),"externalId must be a valid external authorization identifier"),o(g(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"),o(Te.includes(String(n.fact_type))&&S(n.amount,xn)&&(n.currency==="USD"||n.currency==="USDC")&&c(n.resource_version,1,255)&&typeof n.predecessor_version=="string"&&c(n.predecessor_version.trim(),1,255)&&n.predecessor_version!==n.resource_version&&c(n.mapping_revision,1,255)&&m(n.recorded_at)&&(n.merchant_name===void 0||c(n.merchant_name,1,255))&&(n.merchant_mcc===void 0||S(n.merchant_mcc,/^[0-9]{4}$/))&&(n.merchant_country===void 0||c(n.merchant_country,2,3))&&[n.supplier_transaction_id,n.parent_supplier_transaction_id,n.client_transaction_id].every(p=>p===void 0||typeof p=="string"&&c(p.trim(),1,255)),"Authorization fact type, predecessor version, amount, or timestamp is invalid")}function qe(e){return Array.isArray(e)&&e.length===5&&e.every((n,i)=>l(n,["kind","state","recorded_at","source_system"],["observed_at","safe_code"])&&n.kind===Sn[i]&&["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||c(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 Dn(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"])||!h(e.receipt_event_id)||!z(e.charge_id)||!(c(e.external_authorization_id,1,256)||c(e.authorization_ref,1,256))||!c(e.mapping_revision,1,255)||!te.includes(String(e.operation_type))||!c(e.resource_version,1,255)||!m(e.finalized_at)||!qe(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 qn(e){if(e===void 0)return!0;if(!I(e)||!I(e.issuer)||!Array.isArray(e.issuer.entries)||!Array.isArray(e.refund_cases))return!1;let n=e.issuer,i=n.entries;return["state","cleared_amount","reversed_amount","refunded_amount"].every(t=>typeof n[t]=="string")&&i.every(t=>I(t)&&["operation_type","resource_version","amount","currency","recorded_at","link_status"].every(p=>typeof t[p]=="string")&&t.currency==="USDC"&&(t.unlinked_reason===void 0||typeof t.unlinked_reason=="string"))&&e.refund_cases.every(t=>I(t)&&["case_id","source_operation_type","source_resource_version","status","amount","excess_amount","updated_at"].every(p=>typeof t[p]=="string")&&(t.paid_amount===void 0||typeof t.paid_amount=="string")&&(t.not_payable_reason===void 0||typeof t.not_payable_reason=="string"))}function Ln(e,n){if(e===void 0)return!0;if(!I(e)||typeof e.fee_total!="string"||!I(e.fee_breakdown))return!1;let i=e.fee_breakdown;if(!["base_fee","fast_pay_fee","pooled_surcharge"].every(p=>typeof i[p]=="string"))return!1;let t=e.user_payment;return t!==void 0&&(!I(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(p=>I(p)&&Number.isSafeInteger(p.chain_id)&&typeof p.case_id=="string"&&typeof p.paid_amount=="string"&&typeof p.recorded_by=="string"&&typeof p.tx_hash=="string"&&/^0x[0-9a-fA-F]{64}$/.test(p.tx_hash)):!1}function Bn(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"])||!c(e.external_authorization_id,1,256)||typeof e.origin_connection_id!="string"||!E.test(e.origin_connection_id)||!c(e.resource_version,1,255)||!c(e.mapping_revision,1,255)||e.charge_id!==void 0&&e.charge_id!==null&&!z(e.charge_id)||e.supplier_transaction_id!==void 0&&!c(e.supplier_transaction_id,1,256)||e.facts!==void 0&&!qe(e.facts)||e.revision!==void 0&&!R(e.revision)||e.operation_type!==void 0&&!te.includes(String(e.operation_type))||e.decision!==void 0&&!["approved","declined","self_reversed_timeout"].includes(String(e.decision))||e.decline_reason_code!==void 0&&!kn(e.decline_reason_code)||!qn(e.lifecycle)||!Ln(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)||!Dn(e.final_receipt)||Object.hasOwn(e,"decline_reason_code"))return!1;let n=e.final_receipt,i=n.external_authorization_id??n.authorization_ref;return n.execution_outcome===e.processing_status&&n.charge_id===e.charge_id&&i===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 Nn(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:Bn(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 Fn(e){return l(e,["charge_id","status"])&&z(e.charge_id)&&["processing","approved","declined"].includes(String(e.status))&&!Object.hasOwn(e,"final_receipt")}function jn(e){return l(e,["operation_id","status"])&&h(e.operation_id)&&e.status==="recorded"}function Un(e,n){return!l(e,["deadline_at","decision_id"])||!m(e.deadline_at)||!h(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 $n(e){if(!l(e,["binding_session_id","status","binding_url","expires_at","proof_policy"])||!S(e.binding_session_id,G)||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(i=>i==="provider_reauthentication"||i==="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 Re(e){if(!I(e)||!S(e.binding_session_id,G)||!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(i=>Object.hasOwn(e,i)):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")&&ne(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(i=>Object.hasOwn(e,i))&&(!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(i=>Object.hasOwn(e,i))&&(!Object.hasOwn(e,"failure_reason")||e.failure_reason==="expired"||e.failure_reason==="proof_timeout")}function Kn(e){return l(e,["binding_session_id","status","proof_received_at"])&&S(e.binding_session_id,G)&&e.status==="consent_pending"&&m(e.proof_received_at)}function Mn(e){return l(e,["binding_session_id","facto_challenge","session_request_digest","expires_at"])&&S(e.binding_session_id,G)&&c(e.facto_challenge,1,512)&&S(e.session_request_digest,B)&&m(e.expires_at)}function Vn(e){o(g(e,["requested_user_consents","return_uri"]),"Binding session requires the generated consent and return URI fields");let n=e.requested_user_consents;o(Array.isArray(n)&&n.length>0&&new Set(n).size===n.length&&n.every(i=>i==="card.metadata.view"||i==="card.use_for_facto_payments"),"Binding session consents are invalid"),o(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 Ee(e){o(g(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 Gn(e){return l(e,["id","revision","cards"])&&S(e.id,re)&&S(e.revision,ge)&&Array.isArray(e.cards)&&e.cards.every(n=>l(n,["binding_id","status","card"])&&S(n.binding_id,ie)&&typeof n.status=="string"&&De(n.card))}function Hn(e){return l(e,["id","status","revision","added_binding_ids","removed_binding_ids","kept_binding_ids"])&&S(e.id,re)&&["applied","no_change"].includes(String(e.status))&&S(e.revision,ge)&&ne(e.added_binding_ids)&&ne(e.removed_binding_ids)&&ne(e.kept_binding_ids)}function Wn(e){return l(e,["id","status"])&&S(e.id,re)&&e.status==="cancelled"}function Jn(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 Zn(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"&&Jn(e.available_to_charge)&&(e.expires_at===void 0||e.expires_at===null||m(e.expires_at))&&(e.per_tx_limit===void 0||P(e.per_tx_limit))&&(e.period_limit===void 0||P(e.period_limit))&&(e.period_remaining===void 0||P(e.period_remaining))&&(e.period_used===void 0||P(e.period_used))}function Qn(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"&&M(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||P(e.balance))&&(e.balance_raw===void 0||P(e.balance_raw))&&(e.balance_updated_at===void 0||e.balance_updated_at===null||m(e.balance_updated_at))}function Xn(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||Zn(e.limits))&&(e.pipeline===void 0||Qn(e.pipeline))}function Yn(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"])&&S(n.id,ie)&&typeof n.status=="string"&&M(n.revision,1)&&De(n.card)&&Xn(n.funding)}function et(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"])&&S(n.id,_e)&&typeof n.event_kind=="string"&&S(n.binding_id,ie)&&M(n.binding_revision,1)&&(n.connection_sequence===null||typeof n.connection_sequence=="number"&&Number.isSafeInteger(n.connection_sequence)&&n.connection_sequence>=1)&&M(n.delivery_attempts,1)&&P(n.last_delivery_error)&&(n.dead_lettered_at===null||m(n.dead_lettered_at))&&M(n.replay_count,0))}function nt(e){return l(e,["id","status"])&&h(e.id)&&e.status==="accepted"}function tt(e){return l(e,["delivery_id","disposition","effect"])&&h(e.delivery_id)&&(e.disposition==="duplicate"?e.effect===null:e.disposition==="applied"&&["revoked","status_updated","released","none"].includes(String(e.effect)))}function rt(e){o(g(e,["intent_token","approval_id","approval_sha256","revision","cards"],["external_account_id"])&&k(e.intent_token,32,8192)&&c(e.approval_id,1,255)&&S(e.approval_sha256,ue)&&S(e.revision,ge)&&K(e.external_account_id,n=>typeof n=="string"&&n.length>0&&Buffer.byteLength(n,"utf8")<=512),"Card replacement requires the original complete approved request"),o(Array.isArray(e.cards)&&e.cards.length<=50&&e.cards.every(n=>g(n,["external_card_id"],["network","type","last4"])&&V(n.external_card_id,255)&&K(n.network,i=>V(i,40))&&K(n.type,i=>i==="virtual"||i==="physical"||i==="unknown")&&K(n.last4,i=>typeof i=="string"&&/^[0-9]{4}$/.test(i))),"Target cards must match the generated safe card projection")}function it(e){o(g(e,["delivery_id","kind","assertion_jws"],["external_card_id","lifecycle_status","external_account_id"])&&h(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=i=>i==null;o(e.kind==="account.released"?c(e.external_account_id,1,512)&&n(e.external_card_id)&&n(e.lifecycle_status):V(e.external_card_id)&&n(e.external_account_id)&&(e.kind==="card.unbound"?n(e.lifecycle_status):e.kind==="card.lifecycle_changed"&&vn.includes(String(e.lifecycle_status))),"Inbound event fields must match the declared event kind")}function q(e){return o(e&&k(e.idempotencyKey,16,255),"An explicit original Idempotency-Key of 16 to 255 characters is required"),e.idempotencyKey}function ee(e){return o(S(e,G),"id must be the original binding session identifier"),`/api/card/connect/sessions/${e}`}function fe(e){return o(S(e,re),"id must be the original connect intent identifier"),`/api/card/connect/intents/${e}`}function Pe(e){return o(e?.rawBody===void 0||typeof e?.rawBody=="string","rawBody must preserve the original authenticated request bytes"),e?.rawBody}function Le(e){o(g(e,["environment","connectionId","programId","apiKeyId","apiKeySecret"],[...Q,"nowSeconds","createNonce"]),"Card client options cannot contain human session or arbitrary authentication fields"),o(typeof e.connectionId=="string"&&E.test(e.connectionId),"connectionId must be a pconn_ connection identifier"),o(c(e.programId,1,128)&&k(e.apiKeyId),"programId and apiKeyId are required");let n=ye(e.apiKeySecret),i=X(e,"program"),t=Object.freeze({connectionId:e.connectionId,environment:e.environment,programId:e.programId}),p=e.apiKeyId,y=e.nowSeconds??(()=>Math.floor(Date.now()/1e3)),A=e.createNonce??ze.randomUUID;function f(d,a,r,s="POST"){let _=y(),u=A();return o(Number.isSafeInteger(_)&&_>=1e9&&_<=9999999999,"nowSeconds must return a ten-digit Unix timestamp in seconds"),o(k(u,1,128),"createNonce must return a bounded canonical nonce"),Oe({secret:n,apiKeyId:p,method:s,target:d,timestamp:_,nonce:u,body:a,idempotencyKey:r})}return Object.freeze({scope:t,sessions:Object.freeze({async create(d,a){Vn(d),o(g(a,["idempotencyKey"],["cardSelection","signal"]),"Binding session create options accept only idempotencyKey, optional cardSelection, and optional signal");let r=q(a);o(a.cardSelection===void 0||typeof a.cardSelection=="boolean","cardSelection must be a boolean when provided");let s={...d,program_ref:t.programId},_=JSON.stringify(s),u="/api/card/connect/sessions";return i("POST",u,()=>{let b=f(u,_,r);return a.cardSelection===!0&&b.set("x-facto-card-selection","1"),b},_,[201],$n,a)},async get(d,a){let r=ee(d),s=await i("GET",r,()=>f(r,"",void 0,"GET"),void 0,[200],Re,a);if(s.binding_session_id!==d)throw x(200);return s},async submitProof(d,a,r){let s=`${ee(d)}/provider-proof`,_=q(r);o(I(a),"Provider proof input is required");let u;if(Object.hasOwn(a,"proof_format")||Object.hasOwn(a,"binding_assertion"))Ee(a),u=a;else{o(!["environment","programId","bindingSessionId","connectionId"].some(L=>Object.hasOwn(a,L)),"Provider proof assertion inherits environment, programId, and bindingSessionId from client scope and session id, and requires explicit providerConnectionId (pc_...)");let H=a,N=H.issuedAtSeconds??y();u={proof_format:"compact-jws",binding_assertion:await ke({...H,environment:t.environment,programId:t.programId,bindingSessionId:d,issuedAtSeconds:N})},Ee(u)}let C=JSON.stringify(u),b=await i("POST",s,()=>f(s,C,_),C,[202],Kn,r);if(b.binding_session_id!==d)throw x(202);return b},async getProofChallenge(d,a){let r=`${ee(d)}/proof-challenge`,s=await i("GET",r,()=>f(r,"",void 0,"GET"),void 0,[200],Mn,a);if(s.binding_session_id!==d)throw x(200);return s},async cancel(d,a){let r=`${ee(d)}/cancel`,s=q(a),_=Pe(a)??"{}",u=await i("POST",r,()=>f(r,_,s),_,[200],Re,a);if(u.binding_session_id!==d)throw x(200);return u}}),intents:Object.freeze({async listCards(d,a){let r=`${fe(d)}/cards`;o(g(a,["intentToken"],["signal"])&&k(a.intentToken,32,8192),"intentToken must be a valid HTTP header value of at least 32 characters");let _=await i("GET",r,()=>{let u=f(r,"",void 0,"GET");return u.set("x-facto-intent-token",a.intentToken),u},void 0,[200],Gn,a);if(_.id!==d)throw x(200);return _},async replaceCards(d,a,r){let s=`${fe(d)}/cards`;rt(a);let _=q(r),u=JSON.stringify(a),C=await i("PUT",s,()=>f(s,u,_,"PUT"),u,[200],Hn,r);if(C.id!==d)throw x(200);return C},async cancel(d,a,r){let s=`${fe(d)}/cancel`;o(g(a,["intent_token"])&&k(a.intent_token,32,8192),"Cancel requires the original intent_token body of at least 32 characters");let _=JSON.stringify(a),u=await i("POST",s,()=>f(s,_),_,[200],Wn,r);if(u.id!==d)throw x(200);return u}}),bindings:Object.freeze({async lookup(d,a){o(g(d,["external_card_id"])&&V(d.external_card_id),"Binding lookup requires only an opaque external_card_id in its body");let r=JSON.stringify(d),s="/api/card/bindings/lookup";return i("POST",s,()=>f(s,r),r,[200],Yn,a)}}),authorizations:Object.freeze({create:(async(d,a)=>{zn(d);let r=q(a),s={...d,program_id:t.programId},_=JSON.stringify(s),u="/api/card/authorizations";return d.decision_mode==="synchronous"?i("POST",u,()=>f(u,_,r),_,[200,422,408],Un,a):i("POST",u,()=>f(u,_,r),_,[200],Fn,a)}),async recordFact(d,a,r){Tn(d,a);let s=q(r),_={...a,program_id:t.programId},u=JSON.stringify(_),C=`/api/card/authorizations/${encodeURIComponent(d)}/facts`;return i("POST",C,()=>f(C,u,s),u,[200],jn,r)},async lookup(d,a){let r=Pn(d),s={program_id:t.programId,criteria:r},_=JSON.stringify(s),u="/api/card/authorizations/lookup",C=await i("POST",u,()=>f(u,_),_,[200],Nn,a),b=C.authorization;if(b&&(b.origin_connection_id!==t.connectionId||r.by==="charge_id"&&b.charge_id?.toLowerCase()!==r.charge_id.toLowerCase()||r.by==="external_authorization_id"&&(b.external_authorization_id!==r.external_authorization_id||b.resource_version!==r.resource_version||b.mapping_revision!==r.mapping_revision||r.fact_type!==void 0&&b.operation_type!==void 0&&b.operation_type!==r.fact_type)||r.by==="supplier_transaction_id"&&(b.supplier_transaction_id!==r.supplier_transaction_id.trim()||b.resource_version!==r.resource_version||b.mapping_revision!==r.mapping_revision||r.fact_type!==void 0&&b.operation_type!==void 0&&b.operation_type!==r.fact_type)))throw x(200);return C}}),events:Object.freeze({async record(d,a){it(d);let r=JSON.stringify(d),s="/api/card/events",_=await i("POST",s,()=>f(s,r),r,[200],tt,a),u=d.kind==="card.unbound"?"revoked":d.kind==="card.lifecycle_changed"?"status_updated":"released";if(_.delivery_id!==d.delivery_id||_.disposition==="applied"&&_.effect!=="none"&&_.effect!==u)throw x(200);return _}}),deliveries:Object.freeze({async list(d,a){En(d);let r={...d,program_id:t.programId},s=JSON.stringify(r),_="/api/card/deliveries/reconciliations/list",u=await i("POST",_,()=>f(_,s),s,[200],On,a);if(u.items.length>d.page_size)throw x(200);return u}}),deliveryReplays:Object.freeze({async create(d,a){o(g(d,["selection_id"])&&h(d.selection_id),"Delivery replay requires a fixed selection_id UUID");let r=q(a),s={...d,program_id:t.programId},_=JSON.stringify(s),u="/api/card/deliveries/replays",C=await i("POST",u,()=>f(u,_,r),_,[202],Rn,a);if(C.selection_id!==d.selection_id)throw x(202);return C}}),deadLetters:Object.freeze({async list(d,a){o(d===void 0||g(d,[],["limit"])&&K(d.limit,u=>typeof u=="number"&&Number.isInteger(u)&&u>=1&&u<=100),"Dead-letter limit must be null, absent, or an integer from 1 to 100");let r=typeof d?.limit=="number"?d.limit:void 0,s=r!==void 0?`/api/card/deliveries/dead-letters?limit=${r}`:"/api/card/deliveries/dead-letters",_=await i("GET",s,()=>f(s,"",void 0,"GET"),void 0,[200],et,a);if(_.items.length>(r??50))throw x(200);return _},async replay(d,a){o(h(d),"The dead-letter path identifier must be a UUID");let r=`/api/card/deliveries/dead-letters/${d}/replay`,s=Pe(a),_=await i("POST",r,()=>f(r,s??""),s,[202],nt,a);if(_.id!==d)throw x(202);return _}})})}var ot=/^cprog_[A-Za-z0-9_-]{16,}$/;function at(e){return le(e)}function Be(e){if(!c(e,1,2048))return!1;try{let n=new URL(e);return n.protocol==="https:"&&!n.username&&!n.password&&!n.hash}catch{return!1}}function Ne(e){return Array.isArray(e)&&e.length>=1&&e.length<=32&&e.every(n=>c(n,1,120))&&new Set(e).size===e.length}function Fe(e){return l(e,["callback_endpoint_id","program_connection_id","provider_connection_id","environment","target_revision","endpoint_url","signing_key_id","status","principal_ref","approval_ref","event_kinds","grant_revision","registered_by_actor_ref","created_at","updated_at"],["pending_operation_receipt_id"])?h(e.callback_endpoint_id)&&typeof e.program_connection_id=="string"&&E.test(e.program_connection_id)&&typeof e.provider_connection_id=="string"&&/^pc_[A-Za-z0-9_-]{16,}$/.test(e.provider_connection_id)&&["dev","production"].includes(String(e.environment))&&h(e.target_revision)&&Be(e.endpoint_url)&&c(e.signing_key_id)&&c(e.principal_ref)&&c(e.approval_ref)&&Ne(e.event_kinds)&&R(e.grant_revision)&&c(e.registered_by_actor_ref)&&m(e.created_at)&&m(e.updated_at)&&(["stopping","indeterminate"].includes(String(e.status))?h(e.pending_operation_receipt_id):["active","disabled"].includes(String(e.status))&&!Object.hasOwn(e,"pending_operation_receipt_id")):!1}function st(e){if(!l(e,["status","operation_receipt"],["effective_at","previous_target_revision","requested_target_revision","current_receiver"]))return!1;let n=e.operation_receipt;if(!l(n,["operation_receipt_id","operation","scope_ref","request_digest","expected_revision","status","recorded_at","evidence_refs"],["result_revision","reason_code"])||!h(n.operation_receipt_id)||!c(n.operation)||typeof n.scope_ref!="string"||!E.test(n.scope_ref)||typeof n.request_digest!="string"||!B.test(n.request_digest)||!R(n.expected_revision)||!m(n.recorded_at)||!Array.isArray(n.evidence_refs)||n.evidence_refs.length>100||!n.evidence_refs.every(t=>c(t))||new Set(n.evidence_refs).size!==n.evidence_refs.length||n.reason_code!==void 0&&!c(n.reason_code,1,64))return!1;for(let t of["previous_target_revision","requested_target_revision"])if(e[t]!==void 0&&!h(e[t]))return!1;if(e.status==="effective")return n.status==="committed"&&R(n.result_revision)&&m(e.effective_at)&&(e.current_receiver===void 0||Fe(e.current_receiver));let i={pending:"accepted",indeterminate:"indeterminate",rejected:"rejected"};return typeof e.status=="string"&&Object.hasOwn(i,e.status)&&n.status===i[e.status]&&!Object.hasOwn(n,"result_revision")&&!Object.hasOwn(e,"effective_at")&&!Object.hasOwn(e,"current_receiver")}var me={"2026-10-23-green-proposal.4":{digest:"sha256:117822c07295b7b574f488dfd74a32d4edf3f648e5d2a8333916301354798367",kinds:["card_program.card_binding.linked","card_program.card_binding.relinked","card_program.card_binding.revoked","card_program.card_binding.route_association_changed","card_program.card_binding.spend_envelope_changed","card_program.card_binding.ownership_transferred","card_program.charge.finalized","card_program.charge.facts_updated"]},"2026-10-23-green-proposal.5":{digest:"sha256:b17e2170470adda15c7f02e3341f7afeab7680abcfbae6610e1eb6094bf4f6ab",kinds:["card_program.card_binding.linked","card_program.card_binding.relinked","card_program.card_binding.revoked","card_program.card_binding.route_association_changed","card_program.card_binding.spend_envelope_changed","card_program.card_binding.ownership_transferred","card_program.charge.finalized","card_program.charge.facts_updated","card_program.authorization.updated"]},"2026-11-18-card-events.1":{digest:"sha256:9fcad68499ef3f770533ad3f3a4c4950d16c0385c56b2b0af6bba5375038aa98",kinds:["card.binding.linked","card.binding.relinked","card.binding.revoked","card.binding.route_changed","card.binding.limits_changed","card.binding.ownership_transferred","card.charge.finalized","card.charge.facts_updated","card.authorization.updated"]}};function je(e){o(g(e,["endpoint_url","signing_key_id","principal_ref","approval_ref","expected_grant_revision","expected_target_revision","required_event_catalog_revision","required_event_catalog_digest","event_kinds"]),"Receiver replacement requires the complete generated request"),o(Be(e.endpoint_url)&&c(e.signing_key_id)&&c(e.principal_ref)&&c(e.approval_ref)&&R(e.expected_grant_revision)&&(e.expected_target_revision===null||h(e.expected_target_revision))&&typeof e.required_event_catalog_revision=="string"&&Object.hasOwn(me,e.required_event_catalog_revision)&&me[e.required_event_catalog_revision].digest===e.required_event_catalog_digest&&Ne(e.event_kinds)&&e.event_kinds.every(n=>me[e.required_event_catalog_revision].kinds.includes(n)),"Receiver replacement fields are invalid")}function dt(e){if(o(I(e)&&typeof e.transition=="string"&&typeof e.reason_code=="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(e.reason_code),"Grant transition must contain an exact transition and reason"),e.transition==="activate"){o(g(e,["transition","reason_code","approval_ref","expected_grant_revision","expected_target_revision"])&&c(e.approval_ref)&&R(e.expected_grant_revision)&&h(e.expected_target_revision),"Activate requires its approved grant and target revision");return}if(e.transition==="disable"||e.transition==="revoke"){o(g(e,["transition","reason_code"]),"Disable and revoke cannot inject approval or revision fields");return}o(e.transition==="handover"&&g(e,["transition","reason_code","approval_ref","new_principal_ref","new_credential_binding_id","new_credential_key_id","expected_target_revision","replacement_receiver"])&&c(e.approval_ref)&&c(e.new_principal_ref)&&h(e.new_credential_binding_id)&&c(e.new_credential_key_id)&&h(e.expected_target_revision),"Handover requires the complete approved replacement identity"),je(e.replacement_receiver),o(e.replacement_receiver.principal_ref===e.new_principal_ref&&e.replacement_receiver.expected_target_revision===e.expected_target_revision,"Handover replacement must preserve its approved principal and target revision")}function ct(e){o(g(e,["environment","cardProgramId","programConnectionId","adminSessionToken"],Q),"Admin options cannot contain Program-machine or arbitrary authentication fields"),o(typeof e.cardProgramId=="string"&&ot.test(e.cardProgramId)&&typeof e.programConnectionId=="string"&&E.test(e.programConnectionId),"Admin scope requires cardProgramId and programConnectionId"),o(k(e.adminSessionToken,1,16384),"An existing AdminSession bearer token is required");let n=X(e,"admin"),i=e.programConnectionId,t=e.environment,p=`/api/admin/card-programs/${e.cardProgramId}/program-connections/${i}`,y=`Bearer ${e.adminSessionToken}`,A=()=>new Headers({authorization:y});function f(r){o(r&&k(r.idempotencyKey,16,255)&&R(r.expectedGrantRevision)&&k(r.deploymentTarget,1,64),"Admin mutation requires Idempotency-Key, expectedGrantRevision, and deploymentTarget");let s=A();return s.set("Idempotency-Key",r.idempotencyKey),s.set("If-Match",String(r.expectedGrantRevision)),s.set("X-Facto-Target",r.deploymentTarget),s}function d(r){return st(r)&&r.operation_receipt.scope_ref===i&&(!r.current_receiver||r.current_receiver.program_connection_id===i&&r.current_receiver.environment===t)}function a(r,s){return d(r)&&(s===200?r.status==="effective":r.status==="pending"||r.status==="indeterminate")}return Object.freeze({async getCallbackEndpoint(r){let s=await n("GET",`${p}/callback-endpoint`,A(),void 0,[200],Fe,r);if(s.program_connection_id!==i||s.environment!==t)throw x(200);return s},async replaceCallbackEndpoint(r,s){je(r);let _=f(s);return o(r.expected_grant_revision===s.expectedGrantRevision,"Body and If-Match must name the same expected grant revision"),n("PUT",`${p}/callback-endpoint`,_,JSON.stringify(r),[200,202],a,s)},async transitionCallbackEndpoint(r,s){return o(g(r,["status","expected_target_revision","reason_code"])&&r.status==="disabled"&&h(r.expected_target_revision)&&typeof r.reason_code=="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(r.reason_code),"Receiver transition must name its exact target and disabled status"),n("POST",`${p}/callback-endpoint/transitions`,f(s),JSON.stringify(r),[200,202],a,s)},async transitionConnectionStatus(r,s){dt(r),r.transition==="activate"?o(r.expected_grant_revision===s.expectedGrantRevision,"Activation body and If-Match must name the same expected grant revision"):r.transition==="handover"&&o(r.replacement_receiver.expected_grant_revision===s.expectedGrantRevision,"Handover receiver and If-Match must name the same expected grant revision");let _=(u,C)=>a(u,C)&&u.operation_receipt.operation==="transition_card_program_connection_status"&&u.operation_receipt.expected_revision===s.expectedGrantRevision;return n("POST",`${p}/transitions`,f(s),JSON.stringify(r),[200,202],_,s)},async getDeliveryOperation(r,s){o(h(r),"operationReceiptId must be the original receipt UUID");let _=await n("GET",`${p}/delivery-operations/${r}`,A(),void 0,[200],d,s);if(_.operation_receipt.operation_receipt_id!==r)throw x(200);return _}})}
1
+ "use strict";var ue=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var Ge=Object.prototype.hasOwnProperty;var We=(e,n)=>{for(var t in n)ue(e,t,{get:n[t],enumerable:!0})},He=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of Ve(n))!Ge.call(e,u)&&u!==t&&ue(e,u,{get:()=>n[u],enumerable:!(r=Me(n,u))||r.enumerable});return e};var Je=e=>He(ue({},"__esModule",{value:!0}),e);var _r={};We(_r,{createCardClient:()=>Ne,createCardConnectAdminClient:()=>pr,isCardConnectAdminErrorEnvelope:()=>dr});module.exports=Je(_r);var Ze=new Set([400,401,402,403,404,410,412,422,423,428]),Ye=new Set(["idempotency_payload_mismatch","mapping_revision_not_approved","fact_type_not_allowed","managed_route_refused","ambiguous_lookup_selector","assertion_replayed","intent_sealed","history_selection_mismatch","read_snapshot_stale","read_snapshot_expired"]);function Qe(e){if(typeof e!="object"||e===null||Array.isArray(e))return{engineCode:void 0,errorCategory:void 0,requestId:void 0,wireRetryable:void 0};let n=e;if(typeof n.error=="string"&&n.error.length>0)return{engineCode:n.error,errorCategory:typeof n.category=="string"&&n.category.length>0?n.category:void 0,requestId:typeof n.request_id=="string"&&n.request_id.length>0?n.request_id:void 0,wireRetryable:typeof n.retryable=="boolean"?n.retryable:void 0};if(typeof n.error=="object"&&n.error!==null&&!Array.isArray(n.error)){let t=n.error;return{engineCode:typeof t.code=="string"&&t.code.length>0?t.code:void 0,errorCategory:typeof t.category=="string"&&t.category.length>0?t.category:void 0,requestId:typeof t.request_id=="string"&&t.request_id.length>0?t.request_id:void 0,wireRetryable:typeof t.retryable=="boolean"?t.retryable:void 0}}return{engineCode:typeof n.code=="string"&&n.code.length>0?n.code:void 0,errorCategory:typeof n.category=="string"&&n.category.length>0?n.category:void 0,requestId:typeof n.request_id=="string"&&n.request_id.length>0?n.request_id:void 0,wireRetryable:typeof n.retryable=="boolean"?n.retryable:void 0}}function Xe(e,n,t){return e==="FACTO_CONFIG_INVALID"?"config_invalid":e==="FACTO_ENGINE_RESPONSE_INVALID"||e==="FACTO_REQUEST_ABORTED"||e==="FACTO_STATUS_POLL_ABORTED"||n===void 0?"unknown":Ze.has(n)||n===409&&t!==void 0&&Ye.has(t)?"refused":"unknown"}var pe=class extends Error{code;retryable;status;details;retryAfterSeconds;engineCode;errorCategory;requestId;wireRetryable;constructor(n,t,r){super(t),this.name="FactoConnectServerError",this.code=n,this.retryable=r.retryable,this.status=r.status,this.details=r.details,this.retryAfterSeconds=r.retryAfterSeconds;let u=Qe(r.details);this.engineCode=r.engineCode??u.engineCode,this.errorCategory=r.errorCategory??u.errorCategory,this.requestId=r.requestId??u.requestId,this.wireRetryable=r.wireRetryable??u.wireRetryable}},S=class extends pe{outcome;httpStatus;constructor(n,t,r){let u=r.httpStatus??r.status;super(n,t,{retryable:r.retryable,status:u,details:r.details,retryAfterSeconds:r.retryAfterSeconds,engineCode:r.engineCode,errorCategory:r.errorCategory,requestId:r.requestId,wireRetryable:r.wireRetryable}),this.name="CardError",this.httpStatus=u,this.outcome=r.outcome??Xe(n,u,this.engineCode)}},en=6e4,Ae=2147483647;function nn(e,n){return e<=0?Promise.resolve():new Promise((t,r)=>{if(n?.aborted){r(new S("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let u=setTimeout(()=>{n?.removeEventListener("abort",g),t()},e),g=()=>{clearTimeout(u),r(new S("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};n?.addEventListener("abort",g,{once:!0})})}function Ie(e,n={}){return rn(e,n,S)}async function rn(e,n,t){let r=n.maxRetries??2,u=n.baseDelayMs??200,g=n.maxDelayMs??5e3,C=n.respectRetryAfter??!0,y=n.maxRetryAfterMs??en;if(!Number.isFinite(y)||y<0||y>Ae)throw new S("FACTO_CONFIG_INVALID",`maxRetryAfterMs must be a number from 0 to ${Ae}`,{retryable:!1});let d=n.sleep??nn,a=0;for(;;)try{return await e()}catch(i){if(!(i instanceof t)||!i.retryable||a>=r)throw i;let p=C&&typeof i.retryAfterSeconds=="number"?i.retryAfterSeconds*1e3:void 0;if(p!==void 0&&!(p<=y))throw i;a+=1;let _=Math.min(g,u*2**(a-1)),A=_*.25*Math.random(),b=p??_+A;n.onRetry?.({attempt:a,error:i,delayMs:b}),await d(b,n.signal)}}function j(e){let n=e.headers.get("retry-after");if(!(n===null||!/^[0-9]+$/.test(n)))return Number(n)}var tn=1048576,_e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,E=/^pconn_[A-Za-z0-9_-]{16,}$/,le=/^[a-f0-9]{64}$/,B=/^sha256:[a-f0-9]{64}$/,Q=["environment","apiBaseUrl","timeoutMs","retry","maxResponseBytes","fetch"];function v(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function c(e,n=1,t=255){return typeof e=="string"&&[...e].length>=n&&[...e].length<=t}function k(e,n=1,t=255){return c(e,n,t)&&/^[\x21-\x7e]+$/.test(e)}function h(e){return typeof e=="string"&&_e.test(e)&&e!=="00000000-0000-0000-0000-000000000000"}function O(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,t=[]){return v(e)&&n.every(r=>Object.hasOwn(e,r))&&Object.keys(e).every(r=>n.includes(r)||t.includes(r))}function l(e,n,t=[]){return v(e)&&n.every(r=>Object.hasOwn(e,r))}function o(e,n){if(!e)throw new S("FACTO_CONFIG_INVALID",n,{retryable:!1})}function Z(e){return e===429||e>=500}function Y(e){let n=e?.headers.get("x-request-id")?.trim();return n&&n.length>0?n:void 0}function x(e,n){return new S("FACTO_ENGINE_RESPONSE_INVALID","Card API response does not match the producer contract",{retryable:Z(e),status:e,retryAfterSeconds:n?j(n):void 0,requestId:Y(n)})}function Se(e,n){return new S("FACTO_ENGINE_RESPONSE_INVALID",`Card API response body exceeds maxResponseBytes (${n} bytes)`,{retryable:Z(e.status),status:e.status,details:{reason:"response_body_too_large",maxResponseBytes:n},retryAfterSeconds:j(e),requestId:Y(e)})}async function on(e,n,t){let r=e.headers.get("content-length")?.trim();if(r!==void 0&&/^\d+$/.test(r)&&Number(r)>n)throw await e.body?.cancel().catch(()=>{}),Se(e,n);if(!e.body)return"";let u=e.body.getReader(),g=[],C=0;try{for(;;){let{done:a,value:i}=await u.read();if(a)break;if(C+=i.byteLength,C>n||t.aborted)throw await u.cancel().catch(()=>{}),t.aborted?new S("FACTO_REQUEST_ABORTED","Card API request aborted or timed out",{retryable:!1}):Se(e,n);g.push(i)}}finally{u.releaseLock()}let y=new Uint8Array(C),d=0;for(let a of g)y.set(a,d),d+=a.byteLength;return new TextDecoder().decode(y)}var an=512;function sn(e){return l(e,["error","message","request_id"])&&c(e.error,1,128)&&/^[a-z][a-z0-9_]*$/.test(e.error)&&c(e.message,1,an)&&c(e.request_id,1,128)}function ye(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 dn(e){e!==void 0&&(o(v(e),"retry options must be an object"),e.maxRetries!==void 0&&o(typeof e.maxRetries=="number"&&Number.isSafeInteger(e.maxRetries)&&e.maxRetries>=0,"retry.maxRetries must be a non-negative integer"),e.baseDelayMs!==void 0&&o(typeof e.baseDelayMs=="number"&&Number.isFinite(e.baseDelayMs)&&e.baseDelayMs>=0,"retry.baseDelayMs must be non-negative"),e.maxDelayMs!==void 0&&o(typeof e.maxDelayMs=="number"&&Number.isFinite(e.maxDelayMs)&&e.maxDelayMs>=0,"retry.maxDelayMs must be non-negative"),e.maxRetryAfterMs!==void 0&&o(typeof e.maxRetryAfterMs=="number"&&Number.isFinite(e.maxRetryAfterMs)&&e.maxRetryAfterMs>=0&&e.maxRetryAfterMs<=2147483647,"retry.maxRetryAfterMs is out of range"))}function X(e,n){o(typeof window>"u","Card API credentials require a server runtime"),o(e.environment==="dev"||e.environment==="production","An explicit dev or production environment is required"),dn(e.retry);let t={dev:"https://dev-api.facto.to",production:"https://api.facto.to"},r;o(e.environment!=="production"||typeof e.apiBaseUrl=="string","Production requires an explicit apiBaseUrl");try{r=new URL(e.apiBaseUrl??t.dev)}catch{throw new S("FACTO_CONFIG_INVALID","apiBaseUrl must be an absolute HTTP(S) origin",{retryable:!1})}o(!r.username&&!r.password&&!r.search&&!r.hash&&r.pathname==="/"&&(r.protocol==="https:"||r.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname)),"apiBaseUrl must be an HTTPS origin or an explicit loopback HTTP origin");let u=`${r.protocol}//${r.hostname.replace(/\.+$/,"")}${r.port?`:${r.port}`:""}`;o(!Object.values(t).includes(u)||u===t[e.environment],"The published endpoint must match the client environment");let g=r.origin,C=e.timeoutMs??3e4;o(Number.isSafeInteger(C)&&C>0,"timeoutMs must be a positive integer");let y=e.maxResponseBytes??tn;o(Number.isSafeInteger(y)&&y>0,"maxResponseBytes must be a positive integer");let d=e.fetch??globalThis.fetch?.bind(globalThis);o(typeof d=="function","A server fetch implementation is required");let a=e.retry;return async function(s,p,_,A,b,H,N={}){let ae=typeof _=="function"?_():new Headers(_),L=N.signal&&a?.signal?AbortSignal.any([N.signal,a.signal]):N.signal??a?.signal,be=0,Ce=async()=>{let se=be===0?ae:typeof _=="function"?_():new Headers(_);be+=1;let z=new AbortController,J=()=>z.abort();L?.addEventListener("abort",J,{once:!0}),L?.aborted&&J();let Ke=setTimeout(J,C),F,de=new Promise((I,ce)=>{F=()=>ce(new S("FACTO_REQUEST_ABORTED","Card API request aborted or timed out",{retryable:!1})),z.signal.addEventListener("abort",F,{once:!0}),z.signal.aborted&&F()});try{if(z.signal.aborted)return await de;se.set("accept","application/json"),A!==void 0&&se.set("content-type","application/json");let I=await Promise.race([d(`${g}${p}`,{method:s,headers:se,redirect:"error",signal:z.signal,...A!==void 0?{body:A}:{}}),de]),ce=await Promise.race([on(I,y,z.signal),de]),R;try{R=JSON.parse(ce)}catch{throw x(I.status,I)}if(b.includes(I.status)&&H(R,I.status))return R;if(!I.ok){if(sn(R))throw new S("FACTO_ENGINE_REQUEST_FAILED",`Card API ${n} request failed with status ${I.status}`,{retryable:Z(I.status),status:I.status,details:R,retryAfterSeconds:j(I),requestId:R.request_id||Y(I)});if(ye(R))throw new S("FACTO_ENGINE_REQUEST_FAILED",`Card API ${n} request failed with status ${I.status}`,{retryable:Z(I.status),status:I.status,details:R,retryAfterSeconds:j(I),requestId:R.error.request_id||Y(I)})}throw x(I.status,I)}catch(I){throw I instanceof S?I:new S("FACTO_ENGINE_REQUEST_FAILED","Card API transport failed; inspect the original operation before any new action",{retryable:!1})}finally{clearTimeout(Ke),L?.removeEventListener("abort",J),F&&z.signal.removeEventListener("abort",F)}};return a!==void 0&&(s==="GET"||ae.has("Idempotency-Key"))?Ie(Ce,{...a,signal:L}):Ce()}}var ze=require("node:crypto");var ee=require("node:crypto");var cn="facto-card-binding+jwt";var un=/^pc_[A-Za-z0-9_-]{16,}$/,pn=/^cbs_[A-Za-z0-9_-]{16,}$/,_n=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,ln=/^[A-Za-z0-9_-]+$/,yn=/^[0-9]{4}$/,ve=300,we=600,gn=["card.metadata.view","card.use_for_facto_payments"],fn=["passkey","mfa","reauthenticated_session"],mn=["provider_authenticated_app","device_bound_confirmation"];var hn={dev:"urn:facto:sandbox:card-program-connect:binding-proof",production:"urn:facto:production:card-program-connect:binding-proof"};function xe(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function U(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1e9&&e<=9999999999}function ke(e){return typeof e=="string"&&ln.test(e)&&Buffer.from(e,"base64url").byteLength===32}function bn(e){return/^[0-9]{12,19}$/.test(e)||/[0-9]{13}/.test(e)}function Cn(e,n){return o(v(e),"Binding assertion proof claim is required"),e.mode==="provider_reauthentication"?(o(f(e,["mode","authenticatedAtSeconds","assurance"])&&U(e.authenticatedAtSeconds)&&e.authenticatedAtSeconds<=n&&n-e.authenticatedAtSeconds<=we&&fn.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}):(o(e.mode==="provider_second_channel"&&f(e,["mode","approvedAtSeconds","approvalRef","channelType"])&&U(e.approvedAtSeconds)&&e.approvedAtSeconds<=n&&n-e.approvedAtSeconds<=we&&c(e.approvalRef,16,255)&&mn.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 An(e){o(Array.isArray(e)&&e.length>=1&&e.length<=20,"Binding assertion requires 1 to 20 asserted cards");let n=new Set,t=0;return e.map(r=>{o(f(r,["externalCardId"],["isEntryCard","display"])&&c(r.externalCardId,8,512)&&!bn(r.externalCardId)&&(r.isEntryCard===void 0||typeof r.isEntryCard=="boolean"),"Each asserted card requires an opaque externalCardId (8-512 non-PAN chars) and optional boolean isEntryCard"),o(!n.has(r.externalCardId),"Asserted cards must have unique externalCardId values"),n.add(r.externalCardId),r.isEntryCard===!0&&(t+=1,o(t<=1,"At most one asserted card may set isEntryCard to true"));let u;if(r.display!==void 0){o(f(r.display,[],["network","cardType","last4"]),"Asserted card display accepts only network, cardType, and last4");let g=r.display;o((g.network===void 0||c(g.network,1,32))&&(g.cardType===void 0||c(g.cardType,1,32))&&(g.last4===void 0||typeof g.last4=="string"&&yn.test(g.last4)),"Asserted card display fields are out of contract bounds");let C={};g.network!==void 0&&(C.network=g.network),g.cardType!==void 0&&(C.card_type=g.cardType),g.last4!==void 0&&(C.last4=g.last4),Object.keys(C).length>0&&(u=C)}return{card_ref:r.externalCardId,relationship_type:"owner",...r.isEntryCard===!0?{is_entry_card:!0}:{},...u!==void 0?{display:u}:{}}})}async function In(e,n,t){if(typeof e=="function"){let r=await e(n);return o(r instanceof Uint8Array&&r.byteLength===64,"Binding assertion signer must return a 64-byte Ed25519 signature"),r}o(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(r=>typeof r=="string")&&e.key_ops.includes("sign"))&&(e.ext===void 0||typeof e.ext=="boolean")&&(e.kid===void 0||e.kid===t)&&ke(e.x)&&ke(e.d),"Binding assertion signer must be a valid Ed25519 private JWK (matching signingKeyId when kid is present) or async signing callback");try{let r=(0,ee.createPrivateKey)({key:{kty:"OKP",crv:"Ed25519",x:e.x,d:e.d},format:"jwk"});return new Uint8Array((0,ee.sign)(null,n,r))}catch{throw new S("FACTO_CONFIG_INVALID","Invalid Ed25519 private JWK for binding assertion signing",{retryable:!1})}}async function Re(e){o(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"),o(e.environment==="dev"||e.environment==="production","environment must be dev or production"),o(typeof e.providerConnectionId=="string"&&un.test(e.providerConnectionId),"providerConnectionId must be a pc_ provider connection identifier (not a pconn_ program connection identifier)"),o(c(e.programId,1,255),"programId must be 1 to 255 characters"),o(typeof e.bindingSessionId=="string"&&pn.test(e.bindingSessionId),"bindingSessionId must be a cbs_ identifier"),o(c(e.issuer,1,512),"issuer is required"),o(c(e.subject,16,512),"subject must be a pairwise opaque identifier of 16 to 512 characters"),o(c(e.jti,16,255),"jti must be 16 to 255 characters"),o(c(e.factoChallenge,1,512),"factoChallenge is required"),o(typeof e.sessionRequestDigest=="string"&&B.test(e.sessionRequestDigest),"sessionRequestDigest must be a sha256:<hex> digest"),o(c(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;o(Array.isArray(n)&&n.length>0&&new Set(n).size===n.length&&n.every(p=>gn.includes(p)),"requestedUserConsents must be a non-empty unique set of supported consent purposes");let t=e.issuedAtSeconds??Math.floor(Date.now()/1e3),r=e.notBeforeSeconds??t,u=e.expiresAtSeconds??t+ve;o(U(t)&&U(r)&&U(u)&&r<=t&&t<=u&&u-t<=ve,"Binding assertion timestamps must satisfy nbf <= iat <= exp with lifetime <= 300 seconds");let g=Cn(e.proof,t),C=An(e.cards),y=xe({typ:cn,alg:"EdDSA",kid:e.signingKeyId}),d=xe({iss:e.issuer,aud:hn[e.environment],sub:e.subject,iat:t,nbf:r,exp:u,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:g,cards:C,requested_user_consents:[...n]}),a=new TextEncoder().encode(`${y}.${d}`),i=await In(e.signer,a,e.signingKeyId),s=`${y}.${d}.${Buffer.from(i).toString("base64url")}`;return o(s.length>=128&&s.length<=16384&&_n.test(s),"Signed binding assertion exceeds compact JWS bounds"),s}var $=require("node:crypto");var Sn=/^(?:[0-9a-fA-F]{2})+$/;function D(e){return new S("FACTO_CONFIG_INVALID",e,{retryable:!1})}function ge(e){if(typeof e=="string")throw D("apiKeySecret cannot be a bare string; pass { encoding: 'hex', value }, { encoding: 'utf8', value }, or Uint8Array");if(e instanceof Uint8Array){if(e.byteLength===0)throw D("apiKeySecret Uint8Array must not be empty");return new Uint8Array(e)}if(typeof e!="object"||e===null||Array.isArray(e))throw D("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 D("apiKeySecret must contain only { encoding: 'hex' | 'utf8', value: string }");let{encoding:t,value:r}=e;if(t==="utf8"){if(typeof r!="string"||r.length===0)throw D("apiKeySecret with encoding 'utf8' must have a non-empty string value");return new TextEncoder().encode(r)}if(t==="hex"){if(typeof r!="string"||!Sn.test(r))throw D("apiKeySecret with encoding 'hex' must be a non-empty, even-length hexadecimal string");let u=new Uint8Array(r.length/2);for(let g=0;g<r.length;g+=2)u[g/2]=Number.parseInt(r.slice(g,g+2),16);return u}throw D("apiKeySecret encoding must be 'hex' or 'utf8', or pass a Uint8Array")}function Oe(e){let n=ge(e.secret),t=(0,$.createHash)("sha256").update(e.body).digest("hex"),r=["FACTO-HMAC-V2",e.method,e.target,String(e.timestamp),e.nonce,t].join(`
2
+ `),u=new Headers({"x-api-key":e.apiKeyId,"x-api-timestamp":String(e.timestamp),"x-api-nonce":e.nonce,"x-api-signature":(0,$.createHmac)("sha256",n).update(r,"utf8").digest("hex")});return e.idempotencyKey!==void 0&&u.set("Idempotency-Key",e.idempotencyKey),u}var W=/^cbs_[A-Za-z0-9_-]{16,}$/,ie=/^cint_[A-Za-z0-9_-]{16,}$/,oe=/^cb_[A-Za-z0-9_-]{16,}$/,me=/^sha256:[a-fA-F0-9]{64}$/,De=["authorization_updated","clearing","reversal","refund","chargeback","settlement"],te=["authorization_requested",...De],vn=["facto_admission","durable_commit","provider_authorization","chain_finality","provider_settlement"],wn=["pending","active","frozen","closed","replaced","unknown"],xn=/^[A-Za-z0-9_.:-]{1,64}$/,kn=/^[0-9]+\.[0-9]{2,6}$/,Rn=/^-?[0-9]+\.[0-9]{2,6}$/;function w(e,n){return typeof e=="string"&&n.test(e)}function P(e){return e===null||typeof e=="string"}function M(e,n=-2147483648){return typeof e=="number"&&Number.isInteger(e)&&e>=n&&e<=2147483647}function V(e,n=255){return c(e,1,n)&&!/[0-9]{13}/.test(e)}function G(e,n,t){return c(e,n,t)&&!/[\x00-\x1f\x7f]/.test(e)}function qe(e){return G(e,1,255)&&e.trim().length>0}function K(e,n){return e==null||n(e)}function re(e){return Array.isArray(e)&&e.every(n=>w(n,oe))}function Le(e){return l(e,["network","type","last4"])&&P(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 T(e){return typeof e=="string"&&/^0x0{32}[0-9a-fA-F]{32}$/.test(e)}function On(e){return typeof e=="string"&&xn.test(e)}function En(e){return!l(e,["snapshot_token","snapshot_at","to_at","items","next_cursor","complete"])||!c(e.snapshot_token,16,4096)||!m(e.snapshot_at)||!m(e.to_at)||typeof e.complete!="boolean"||e.next_cursor!==null&&!c(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"])&&h(n.event_id)&&typeof n.origin_connection_id=="string"&&E.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"&&le.test(n.event_sha256)&&h(n.target_revision)&&typeof n.delivery_state=="string"&&(n.accepted_at===void 0||m(n.accepted_at)))}function Pn(e){return l(e,["replay_id","selection_id","target_revision","status"])&&h(e.replay_id)&&h(e.selection_id)&&h(e.target_revision)&&e.status==="accepted"}function Tn(e){o(f(e,["target_revision","page_size"],["selection_id","from_at","to_at","snapshot_token","cursor"]),"Reconciliation requires only the generated query fields"),o(h(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"),o(h(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"),o((e.snapshot_token===void 0||c(e.snapshot_token,16,4096))&&(e.cursor===void 0||c(e.cursor,16,4096)&&c(e.snapshot_token,16,4096)),"A cursor requires its original snapshot token")}function zn(e){o(v(e),"Authorization lookup requires criteria");let n=Object.hasOwn(e,"criteria")?(o(f(e,["criteria"])&&v(e.criteria),"Authorization lookup wrapper requires only criteria"),e.criteria):e;o(v(n),"Authorization lookup requires criteria");let t=n.by==="external_authorization_id"?f(n,["by","external_authorization_id","resource_version","mapping_revision"],["fact_type"])&&c(n.external_authorization_id,1,256)&&c(n.resource_version,1,255)&&c(n.mapping_revision,1,255)&&(n.fact_type===void 0||te.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"&&c(n.supplier_transaction_id.trim(),1,256)&&c(n.resource_version,1,255)&&c(n.mapping_revision,1,255)&&(n.fact_type===void 0||te.includes(String(n.fact_type))):n.by==="idempotency_key"?f(n,["by","idempotency_key","original_credential_key_id"],["operation"])&&c(n.idempotency_key,16,255)&&c(n.original_credential_key_id,1,255)&&(n.operation===void 0||n.operation==="create_authorization"):n.by==="charge_id"&&f(n,["by","charge_id"])&&T(n.charge_id);return o(t,"Select exactly one complete external_authorization_id, supplier_transaction_id, idempotency_key, or public charge_id"),n}function Dn(e){o(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 r=e.cardholder_verification;o(V(e.external_card_id,512)&&c(e.external_authorization_id,1,256)&&w(e.amount,kn)&&(e.currency==="USD"||e.currency==="USDC")&&c(e.resource_version,1,255)&&c(e.mapping_revision,1,255)&&(e.merchant_name===void 0||c(e.merchant_name,0,256))&&(e.merchant_mcc===void 0||G(e.merchant_mcc,0,16))&&(e.merchant_country===void 0||G(e.merchant_country,1,8))&&(e.occurred_at===void 0||m(e.occurred_at))&&[e.supplier_transaction_id,e.client_transaction_id].every(u=>u===void 0||typeof u=="string"&&c(u.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(r,["method","verified_at","evidence_id"])&&["pin","biometric","cdcvm","signature","no_cvm","provider_attested"].includes(String(r.method))&&m(r.verified_at)&&c(r.evidence_id,1,256),"Authorization fields, currency, mapping/version, or cardholder verification is invalid")}function qn(e,n){o(c(e,1,256)&&e!=="."&&e!==".."&&!e.includes("/"),"externalId must be a valid external authorization identifier"),o(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"),o(De.includes(String(n.fact_type))&&w(n.amount,Rn)&&(n.currency==="USD"||n.currency==="USDC")&&c(n.resource_version,1,255)&&typeof n.predecessor_version=="string"&&c(n.predecessor_version.trim(),1,255)&&n.predecessor_version!==n.resource_version&&c(n.mapping_revision,1,255)&&m(n.recorded_at)&&(n.merchant_name===void 0||c(n.merchant_name,0,256))&&(n.merchant_mcc===void 0||G(n.merchant_mcc,0,16))&&(n.merchant_country===void 0||G(n.merchant_country,1,8))&&[n.supplier_transaction_id,n.parent_supplier_transaction_id,n.client_transaction_id].every(u=>u===void 0||typeof u=="string"&&c(u.trim(),1,256)),"Authorization fact type, predecessor version, amount, or timestamp is invalid")}function Be(e){return Array.isArray(e)&&e.length===5&&e.every((n,t)=>l(n,["kind","state","recorded_at","source_system"],["observed_at","safe_code"])&&n.kind===vn[t]&&["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||c(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 Ln(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"])||!h(e.receipt_event_id)||!T(e.charge_id)||!(c(e.external_authorization_id,1,256)||c(e.authorization_ref,1,256))||!c(e.mapping_revision,1,255)||!te.includes(String(e.operation_type))||!c(e.resource_version,1,255)||!m(e.finalized_at)||!Be(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 Bn(e){if(e===void 0)return!0;if(!v(e)||!v(e.issuer)||!Array.isArray(e.issuer.entries)||!Array.isArray(e.refund_cases))return!1;let n=e.issuer,t=n.entries;return["state","cleared_amount","reversed_amount","refunded_amount"].every(r=>typeof n[r]=="string")&&t.every(r=>v(r)&&["operation_type","resource_version","amount","currency","recorded_at","link_status"].every(u=>typeof r[u]=="string")&&r.currency==="USDC"&&(r.unlinked_reason===void 0||typeof r.unlinked_reason=="string"))&&e.refund_cases.every(r=>v(r)&&["case_id","source_operation_type","source_resource_version","status","amount","excess_amount","updated_at"].every(u=>typeof r[u]=="string")&&(r.paid_amount===void 0||typeof r.paid_amount=="string")&&(r.not_payable_reason===void 0||typeof r.not_payable_reason=="string"))}function Nn(e,n){if(e===void 0)return!0;if(!v(e)||typeof e.fee_total!="string"||!v(e.fee_breakdown))return!1;let t=e.fee_breakdown;if(!["base_fee","fast_pay_fee","pooled_surcharge"].every(u=>typeof t[u]=="string"))return!1;let r=e.user_payment;return r!==void 0&&(!v(r)||!Number.isSafeInteger(r.chain_id)||typeof r.tx_hash!="string"||!/^0x[0-9a-fA-F]{64}$/.test(r.tx_hash)||r.asset_symbol!==void 0&&typeof r.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(u=>v(u)&&Number.isSafeInteger(u.chain_id)&&typeof u.case_id=="string"&&typeof u.paid_amount=="string"&&typeof u.recorded_by=="string"&&typeof u.tx_hash=="string"&&/^0x[0-9a-fA-F]{64}$/.test(u.tx_hash)):!1}function Fn(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"])||!c(e.external_authorization_id,1,256)||typeof e.origin_connection_id!="string"||!E.test(e.origin_connection_id)||!c(e.resource_version,1,255)||!c(e.mapping_revision,1,255)||e.charge_id!==void 0&&e.charge_id!==null&&!T(e.charge_id)||e.supplier_transaction_id!==void 0&&!c(e.supplier_transaction_id,1,256)||e.facts!==void 0&&!Be(e.facts)||e.revision!==void 0&&!O(e.revision)||e.operation_type!==void 0&&!te.includes(String(e.operation_type))||e.decision!==void 0&&!["approved","declined","self_reversed_timeout"].includes(String(e.decision))||e.decline_reason_code!==void 0&&!On(e.decline_reason_code)||!Bn(e.lifecycle)||!Nn(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(!T(e.charge_id)||!Ln(e.final_receipt)||Object.hasOwn(e,"decline_reason_code"))return!1;let n=e.final_receipt,t=n.external_authorization_id??n.authorization_ref;return n.execution_outcome===e.processing_status&&n.charge_id===e.charge_id&&t===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||T(e.charge_id)):T(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 jn(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:Fn(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 Un(e){return l(e,["charge_id","status"])&&T(e.charge_id)&&e.status==="processing"&&!Object.hasOwn(e,"final_receipt")}function $n(e){return l(e,["operation_id","status"])&&h(e.operation_id)&&e.status==="recorded"}function Kn(e,n){return!l(e,["deadline_at","decision_id"])||!m(e.deadline_at)||!h(e.decision_id)?!1:n===200?e.decision==="approved"&&e.status==="approved"&&T(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 Mn(e){if(!l(e,["binding_session_id","status","binding_url","expires_at","proof_policy"])||!w(e.binding_session_id,W)||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(t=>t==="provider_reauthentication"||t==="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 Ee(e){if(!v(e)||!w(e.binding_session_id,W)||!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(t=>Object.hasOwn(e,t)):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")&&re(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(t=>Object.hasOwn(e,t))&&(!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(t=>Object.hasOwn(e,t))&&(!Object.hasOwn(e,"failure_reason")||e.failure_reason==="expired"||e.failure_reason==="proof_timeout")}function Vn(e){return l(e,["binding_session_id","status","proof_received_at"])&&w(e.binding_session_id,W)&&e.status==="consent_pending"&&m(e.proof_received_at)}function Gn(e){return l(e,["binding_session_id","facto_challenge","session_request_digest","expires_at"])&&w(e.binding_session_id,W)&&c(e.facto_challenge,1,512)&&w(e.session_request_digest,B)&&m(e.expires_at)}function Wn(e){o(f(e,["requested_user_consents","return_uri"]),"Binding session requires the generated consent and return URI fields");let n=e.requested_user_consents;o(Array.isArray(n)&&n.length>0&&new Set(n).size===n.length&&n.every(t=>t==="card.metadata.view"||t==="card.use_for_facto_payments"),"Binding session consents are invalid"),o(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 Pe(e){o(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 Hn(e){return l(e,["id","revision","cards"])&&w(e.id,ie)&&w(e.revision,me)&&Array.isArray(e.cards)&&e.cards.every(n=>l(n,["binding_id","status","card"])&&w(n.binding_id,oe)&&typeof n.status=="string"&&Le(n.card))}function Jn(e){return l(e,["id","status","revision","added_binding_ids","removed_binding_ids","kept_binding_ids"])&&w(e.id,ie)&&["applied","no_change"].includes(String(e.status))&&w(e.revision,me)&&re(e.added_binding_ids)&&re(e.removed_binding_ids)&&re(e.kept_binding_ids)}function Zn(e){return l(e,["id","status"])&&w(e.id,ie)&&e.status==="cancelled"}function Yn(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 Qn(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"&&Yn(e.available_to_charge)&&(e.expires_at===void 0||e.expires_at===null||m(e.expires_at))&&(e.per_tx_limit===void 0||P(e.per_tx_limit))&&(e.period_limit===void 0||P(e.period_limit))&&(e.period_remaining===void 0||P(e.period_remaining))&&(e.period_used===void 0||P(e.period_used))}function Xn(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"&&M(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||P(e.balance))&&(e.balance_raw===void 0||P(e.balance_raw))&&(e.balance_updated_at===void 0||e.balance_updated_at===null||m(e.balance_updated_at))}function er(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||Qn(e.limits))&&(e.pipeline===void 0||Xn(e.pipeline))}function nr(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"])&&w(n.id,oe)&&typeof n.status=="string"&&M(n.revision,1)&&Le(n.card)&&er(n.funding)}function rr(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"])&&w(n.id,_e)&&typeof n.event_kind=="string"&&w(n.binding_id,oe)&&M(n.binding_revision,1)&&(n.connection_sequence===null||typeof n.connection_sequence=="number"&&Number.isSafeInteger(n.connection_sequence)&&n.connection_sequence>=1)&&M(n.delivery_attempts,1)&&P(n.last_delivery_error)&&(n.dead_lettered_at===null||m(n.dead_lettered_at))&&M(n.replay_count,0))}function tr(e){return l(e,["id","status"])&&h(e.id)&&e.status==="accepted"}function ir(e){return l(e,["delivery_id","disposition","effect"])&&qe(e.delivery_id)&&(e.disposition==="duplicate"?e.effect===null:e.disposition==="applied"&&["revoked","status_updated","released","none"].includes(String(e.effect)))}function or(e){o(f(e,["intent_token","approval_id","approval_sha256","revision","cards"],["external_account_id"])&&k(e.intent_token,32,8192)&&c(e.approval_id,1,255)&&w(e.approval_sha256,le)&&w(e.revision,me)&&K(e.external_account_id,n=>typeof n=="string"&&n.length>0&&Buffer.byteLength(n,"utf8")<=512),"Card replacement requires the original complete approved request"),o(Array.isArray(e.cards)&&e.cards.length<=50&&e.cards.every(n=>f(n,["external_card_id"],["network","type","last4"])&&V(n.external_card_id,255)&&K(n.network,t=>V(t,40))&&K(n.type,t=>t==="virtual"||t==="physical"||t==="unknown")&&K(n.last4,t=>typeof t=="string"&&/^[0-9]{4}$/.test(t))),"Target cards must match the generated safe card projection")}function ar(e){o(f(e,["delivery_id","kind","assertion_jws"],["external_card_id","lifecycle_status","external_account_id"])&&qe(e.delivery_id)&&typeof e.assertion_jws=="string"&&e.assertion_jws.trim().length>=32,"Inbound event requires a printable delivery_id (1-255 chars) and signed assertion_jws");let n=t=>t==null;o(e.kind==="account.released"?c(e.external_account_id,1,512)&&n(e.external_card_id)&&n(e.lifecycle_status):V(e.external_card_id,255)&&n(e.external_account_id)&&(e.kind==="card.unbound"?n(e.lifecycle_status):e.kind==="card.lifecycle_changed"&&wn.includes(String(e.lifecycle_status))),"Inbound event fields must match the declared event kind")}function q(e){return o(e&&k(e.idempotencyKey,16,255),"An explicit original Idempotency-Key of 16 to 255 characters is required"),e.idempotencyKey}function ne(e){return o(w(e,W),"id must be the original binding session identifier"),`/api/card/connect/sessions/${e}`}function fe(e){return o(w(e,ie),"id must be the original connect intent identifier"),`/api/card/connect/intents/${e}`}function Te(e){return o(e?.rawBody===void 0||typeof e?.rawBody=="string","rawBody must preserve the original authenticated request bytes"),e?.rawBody}function Ne(e){o(f(e,["environment","connectionId","programId","apiKeyId","apiKeySecret"],[...Q,"nowSeconds","createNonce"]),"Card client options cannot contain human session or arbitrary authentication fields"),o(typeof e.connectionId=="string"&&E.test(e.connectionId),"connectionId must be a pconn_ connection identifier"),o(c(e.programId,1,255)&&k(e.apiKeyId),"programId and apiKeyId are required");let n=ge(e.apiKeySecret),t=X(e,"program"),r=Object.freeze({connectionId:e.connectionId,environment:e.environment,programId:e.programId}),u=e.apiKeyId,g=e.nowSeconds??(()=>Math.floor(Date.now()/1e3)),C=e.createNonce??ze.randomUUID;function y(d,a,i,s="POST"){let p=g(),_=C();return o(Number.isSafeInteger(p)&&p>=1e9&&p<=9999999999,"nowSeconds must return a ten-digit Unix timestamp in seconds"),o(k(_,1,128),"createNonce must return a bounded canonical nonce"),Oe({secret:n,apiKeyId:u,method:s,target:d,timestamp:p,nonce:_,body:a,idempotencyKey:i})}return Object.freeze({scope:r,sessions:Object.freeze({async create(d,a){Wn(d),o(f(a,["idempotencyKey"],["cardSelection","signal"]),"Binding session create options accept only idempotencyKey, optional cardSelection, and optional signal");let i=q(a);o(a.cardSelection===void 0||typeof a.cardSelection=="boolean","cardSelection must be a boolean when provided");let s={...d,program_ref:r.programId},p=JSON.stringify(s),_="/api/card/connect/sessions";return t("POST",_,()=>{let b=y(_,p,i);return a.cardSelection===!0&&b.set("x-facto-card-selection","1"),b},p,[201],Mn,a)},async get(d,a){let i=ne(d),s=await t("GET",i,()=>y(i,"",void 0,"GET"),void 0,[200],Ee,a);if(s.binding_session_id!==d)throw x(200);return s},async submitProof(d,a,i){let s=`${ne(d)}/provider-proof`,p=q(i);o(v(a),"Provider proof input is required");let _;if(Object.hasOwn(a,"proof_format")||Object.hasOwn(a,"binding_assertion"))Pe(a),_=a;else{o(!["environment","programId","bindingSessionId","connectionId"].some(L=>Object.hasOwn(a,L)),"Provider proof assertion inherits environment, programId, and bindingSessionId from client scope and session id, and requires explicit providerConnectionId (pc_...)");let H=a,N=H.issuedAtSeconds??g();_={proof_format:"compact-jws",binding_assertion:await Re({...H,environment:r.environment,programId:r.programId,bindingSessionId:d,issuedAtSeconds:N})},Pe(_)}let A=JSON.stringify(_),b=await t("POST",s,()=>y(s,A,p),A,[202],Vn,i);if(b.binding_session_id!==d)throw x(202);return b},async getProofChallenge(d,a){let i=`${ne(d)}/proof-challenge`,s=await t("GET",i,()=>y(i,"",void 0,"GET"),void 0,[200],Gn,a);if(s.binding_session_id!==d)throw x(200);return s},async cancel(d,a){let i=`${ne(d)}/cancel`,s=q(a),p=Te(a)??"{}",_=await t("POST",i,()=>y(i,p,s),p,[200],Ee,a);if(_.binding_session_id!==d)throw x(200);return _}}),intents:Object.freeze({async listCards(d,a){let i=`${fe(d)}/cards`;o(f(a,["intentToken"],["signal"])&&k(a.intentToken,32,8192),"intentToken must be a valid HTTP header value of at least 32 characters");let p=await t("GET",i,()=>{let _=y(i,"",void 0,"GET");return _.set("x-facto-intent-token",a.intentToken),_},void 0,[200],Hn,a);if(p.id!==d)throw x(200);return p},async replaceCards(d,a,i){let s=`${fe(d)}/cards`;or(a);let p=q(i),_=JSON.stringify(a),A=await t("PUT",s,()=>y(s,_,p,"PUT"),_,[200],Jn,i);if(A.id!==d)throw x(200);return A},async cancel(d,a,i){let s=`${fe(d)}/cancel`;o(f(a,["intent_token"])&&k(a.intent_token,32,8192),"Cancel requires the original intent_token body of at least 32 characters");let p=JSON.stringify(a),_=await t("POST",s,()=>y(s,p),p,[200],Zn,i);if(_.id!==d)throw x(200);return _}}),bindings:Object.freeze({async lookup(d,a){o(f(d,["external_card_id"])&&V(d.external_card_id),"Binding lookup requires only an opaque external_card_id in its body");let i=JSON.stringify(d),s="/api/card/bindings/lookup";return t("POST",s,()=>y(s,i),i,[200],nr,a)}}),authorizations:Object.freeze({create:(async(d,a)=>{Dn(d);let i=q(a),s={...d,program_id:r.programId},p=JSON.stringify(s),_="/api/card/authorizations";return d.decision_mode==="synchronous"?t("POST",_,()=>y(_,p,i),p,[200,422,408],Kn,a):t("POST",_,()=>y(_,p,i),p,[200],Un,a)}),async recordFact(d,a,i){qn(d,a);let s=q(i),p={...a,program_id:r.programId},_=JSON.stringify(p),A=`/api/card/authorizations/${encodeURIComponent(d)}/facts`;return t("POST",A,()=>y(A,_,s),_,[200],$n,i)},async lookup(d,a){let i=zn(d),s={program_id:r.programId,criteria:i},p=JSON.stringify(s),_="/api/card/authorizations/lookup",A=await t("POST",_,()=>y(_,p),p,[200],jn,a),b=A.authorization;if(b&&(b.origin_connection_id!==r.connectionId||i.by==="charge_id"&&b.charge_id?.toLowerCase()!==i.charge_id.toLowerCase()||i.by==="external_authorization_id"&&(b.external_authorization_id!==i.external_authorization_id||b.resource_version!==i.resource_version||b.mapping_revision!==i.mapping_revision||i.fact_type!==void 0&&b.operation_type!==void 0&&b.operation_type!==i.fact_type)||i.by==="supplier_transaction_id"&&(b.supplier_transaction_id!==i.supplier_transaction_id.trim()||b.resource_version!==i.resource_version||b.mapping_revision!==i.mapping_revision||i.fact_type!==void 0&&b.operation_type!==void 0&&b.operation_type!==i.fact_type)))throw x(200);return A}}),events:Object.freeze({async record(d,a){ar(d);let i=JSON.stringify(d),s="/api/card/events",p=await t("POST",s,()=>y(s,i),i,[200],ir,a),_=d.kind==="card.unbound"?"revoked":d.kind==="card.lifecycle_changed"?"status_updated":"released";if(p.delivery_id!==d.delivery_id||p.disposition==="applied"&&p.effect!=="none"&&p.effect!==_)throw x(200);return p}}),deliveries:Object.freeze({async list(d,a){Tn(d);let i={...d,program_id:r.programId},s=JSON.stringify(i),p="/api/card/deliveries/reconciliations/list",_=await t("POST",p,()=>y(p,s),s,[200],En,a);if(_.items.length>d.page_size)throw x(200);return _}}),deliveryReplays:Object.freeze({async create(d,a){o(f(d,["selection_id"])&&h(d.selection_id),"Delivery replay requires a fixed selection_id UUID");let i=q(a),s={...d,program_id:r.programId},p=JSON.stringify(s),_="/api/card/deliveries/replays",A=await t("POST",_,()=>y(_,p,i),p,[202],Pn,a);if(A.selection_id!==d.selection_id)throw x(202);return A}}),deadLetters:Object.freeze({async list(d,a){o(d===void 0||f(d,[],["limit"])&&K(d.limit,_=>typeof _=="number"&&Number.isInteger(_)&&_>=1&&_<=100),"Dead-letter limit must be null, absent, or an integer from 1 to 100");let i=typeof d?.limit=="number"?d.limit:void 0,s=i!==void 0?`/api/card/deliveries/dead-letters?limit=${i}`:"/api/card/deliveries/dead-letters",p=await t("GET",s,()=>y(s,"",void 0,"GET"),void 0,[200],rr,a);if(p.items.length>(i??50))throw x(200);return p},async replay(d,a){o(h(d),"The dead-letter path identifier must be a UUID");let i=`/api/card/deliveries/dead-letters/${d}/replay`,s=Te(a),p=await t("POST",i,()=>y(i,s??""),s,[202],tr,a);if(p.id!==d)throw x(202);return p}})})}var sr=/^cprog_[A-Za-z0-9_-]{16,}$/;function dr(e){return ye(e)}function Fe(e){if(!c(e,1,2048))return!1;try{let n=new URL(e);return n.protocol==="https:"&&!n.username&&!n.password&&!n.hash}catch{return!1}}function je(e){return Array.isArray(e)&&e.length>=1&&e.length<=32&&e.every(n=>c(n,1,120))&&new Set(e).size===e.length}function Ue(e){return l(e,["callback_endpoint_id","program_connection_id","provider_connection_id","environment","target_revision","endpoint_url","signing_key_id","status","principal_ref","approval_ref","event_kinds","grant_revision","registered_by_actor_ref","created_at","updated_at"],["pending_operation_receipt_id"])?h(e.callback_endpoint_id)&&typeof e.program_connection_id=="string"&&E.test(e.program_connection_id)&&typeof e.provider_connection_id=="string"&&/^pc_[A-Za-z0-9_-]{16,}$/.test(e.provider_connection_id)&&["dev","production"].includes(String(e.environment))&&h(e.target_revision)&&Fe(e.endpoint_url)&&c(e.signing_key_id)&&c(e.principal_ref)&&c(e.approval_ref)&&je(e.event_kinds)&&O(e.grant_revision)&&c(e.registered_by_actor_ref)&&m(e.created_at)&&m(e.updated_at)&&(["stopping","indeterminate"].includes(String(e.status))?h(e.pending_operation_receipt_id):["active","disabled"].includes(String(e.status))&&!Object.hasOwn(e,"pending_operation_receipt_id")):!1}function cr(e){if(!l(e,["status","operation_receipt"],["effective_at","previous_target_revision","requested_target_revision","current_receiver"]))return!1;let n=e.operation_receipt;if(!l(n,["operation_receipt_id","operation","scope_ref","request_digest","expected_revision","status","recorded_at","evidence_refs"],["result_revision","reason_code"])||!h(n.operation_receipt_id)||!c(n.operation)||typeof n.scope_ref!="string"||!E.test(n.scope_ref)||typeof n.request_digest!="string"||!B.test(n.request_digest)||!O(n.expected_revision)||!m(n.recorded_at)||!Array.isArray(n.evidence_refs)||n.evidence_refs.length>100||!n.evidence_refs.every(r=>c(r))||new Set(n.evidence_refs).size!==n.evidence_refs.length||n.reason_code!==void 0&&!c(n.reason_code,1,64))return!1;for(let r of["previous_target_revision","requested_target_revision"])if(e[r]!==void 0&&!h(e[r]))return!1;if(e.status==="effective")return n.status==="committed"&&O(n.result_revision)&&m(e.effective_at)&&(e.current_receiver===void 0||Ue(e.current_receiver));let t={pending:"accepted",indeterminate:"indeterminate",rejected:"rejected"};return typeof e.status=="string"&&Object.hasOwn(t,e.status)&&n.status===t[e.status]&&!Object.hasOwn(n,"result_revision")&&!Object.hasOwn(e,"effective_at")&&!Object.hasOwn(e,"current_receiver")}var he={"2026-10-23-green-proposal.4":{digest:"sha256:117822c07295b7b574f488dfd74a32d4edf3f648e5d2a8333916301354798367",kinds:["card_program.card_binding.linked","card_program.card_binding.relinked","card_program.card_binding.revoked","card_program.card_binding.route_association_changed","card_program.card_binding.spend_envelope_changed","card_program.card_binding.ownership_transferred","card_program.charge.finalized","card_program.charge.facts_updated"]},"2026-10-23-green-proposal.5":{digest:"sha256:b17e2170470adda15c7f02e3341f7afeab7680abcfbae6610e1eb6094bf4f6ab",kinds:["card_program.card_binding.linked","card_program.card_binding.relinked","card_program.card_binding.revoked","card_program.card_binding.route_association_changed","card_program.card_binding.spend_envelope_changed","card_program.card_binding.ownership_transferred","card_program.charge.finalized","card_program.charge.facts_updated","card_program.authorization.updated"]},"2026-11-18-card-events.1":{digest:"sha256:9fcad68499ef3f770533ad3f3a4c4950d16c0385c56b2b0af6bba5375038aa98",kinds:["card.binding.linked","card.binding.relinked","card.binding.revoked","card.binding.route_changed","card.binding.limits_changed","card.binding.ownership_transferred","card.charge.finalized","card.charge.facts_updated","card.authorization.updated"]}};function $e(e){o(f(e,["endpoint_url","signing_key_id","principal_ref","approval_ref","expected_grant_revision","expected_target_revision","required_event_catalog_revision","required_event_catalog_digest","event_kinds"]),"Receiver replacement requires the complete generated request"),o(Fe(e.endpoint_url)&&c(e.signing_key_id)&&c(e.principal_ref)&&c(e.approval_ref)&&O(e.expected_grant_revision)&&(e.expected_target_revision===null||h(e.expected_target_revision))&&typeof e.required_event_catalog_revision=="string"&&Object.hasOwn(he,e.required_event_catalog_revision)&&he[e.required_event_catalog_revision].digest===e.required_event_catalog_digest&&je(e.event_kinds)&&e.event_kinds.every(n=>he[e.required_event_catalog_revision].kinds.includes(n)),"Receiver replacement fields are invalid")}function ur(e){if(o(v(e)&&typeof e.transition=="string"&&typeof e.reason_code=="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(e.reason_code),"Grant transition must contain an exact transition and reason"),e.transition==="activate"){o(f(e,["transition","reason_code","approval_ref","expected_grant_revision","expected_target_revision"])&&c(e.approval_ref)&&O(e.expected_grant_revision)&&h(e.expected_target_revision),"Activate requires its approved grant and target revision");return}if(e.transition==="disable"||e.transition==="revoke"){o(f(e,["transition","reason_code"]),"Disable and revoke cannot inject approval or revision fields");return}o(e.transition==="handover"&&f(e,["transition","reason_code","approval_ref","new_principal_ref","new_credential_binding_id","new_credential_key_id","expected_target_revision","replacement_receiver"])&&c(e.approval_ref)&&c(e.new_principal_ref)&&h(e.new_credential_binding_id)&&c(e.new_credential_key_id)&&h(e.expected_target_revision),"Handover requires the complete approved replacement identity"),$e(e.replacement_receiver),o(e.replacement_receiver.principal_ref===e.new_principal_ref&&e.replacement_receiver.expected_target_revision===e.expected_target_revision,"Handover replacement must preserve its approved principal and target revision")}function pr(e){o(f(e,["environment","cardProgramId","programConnectionId","adminSessionToken"],Q),"Admin options cannot contain Program-machine or arbitrary authentication fields"),o(typeof e.cardProgramId=="string"&&sr.test(e.cardProgramId)&&typeof e.programConnectionId=="string"&&E.test(e.programConnectionId),"Admin scope requires cardProgramId and programConnectionId"),o(k(e.adminSessionToken,1,16384),"An existing AdminSession bearer token is required");let n=X(e,"admin"),t=e.programConnectionId,r=e.environment,u=`/api/admin/card-programs/${e.cardProgramId}/program-connections/${t}`,g=`Bearer ${e.adminSessionToken}`,C=()=>new Headers({authorization:g});function y(i){o(i&&k(i.idempotencyKey,16,255)&&O(i.expectedGrantRevision)&&k(i.deploymentTarget,1,64),"Admin mutation requires Idempotency-Key, expectedGrantRevision, and deploymentTarget");let s=C();return s.set("Idempotency-Key",i.idempotencyKey),s.set("If-Match",String(i.expectedGrantRevision)),s.set("X-Facto-Target",i.deploymentTarget),s}function d(i){return cr(i)&&i.operation_receipt.scope_ref===t&&(!i.current_receiver||i.current_receiver.program_connection_id===t&&i.current_receiver.environment===r)}function a(i,s){return d(i)&&(s===200?i.status==="effective":i.status==="pending"||i.status==="indeterminate")}return Object.freeze({async getCallbackEndpoint(i){let s=await n("GET",`${u}/callback-endpoint`,C(),void 0,[200],Ue,i);if(s.program_connection_id!==t||s.environment!==r)throw x(200);return s},async replaceCallbackEndpoint(i,s){$e(i);let p=y(s);return o(i.expected_grant_revision===s.expectedGrantRevision,"Body and If-Match must name the same expected grant revision"),n("PUT",`${u}/callback-endpoint`,p,JSON.stringify(i),[200,202],a,s)},async transitionCallbackEndpoint(i,s){return o(f(i,["status","expected_target_revision","reason_code"])&&i.status==="disabled"&&h(i.expected_target_revision)&&typeof i.reason_code=="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(i.reason_code),"Receiver transition must name its exact target and disabled status"),n("POST",`${u}/callback-endpoint/transitions`,y(s),JSON.stringify(i),[200,202],a,s)},async transitionConnectionStatus(i,s){ur(i),i.transition==="activate"?o(i.expected_grant_revision===s.expectedGrantRevision,"Activation body and If-Match must name the same expected grant revision"):i.transition==="handover"&&o(i.replacement_receiver.expected_grant_revision===s.expectedGrantRevision,"Handover receiver and If-Match must name the same expected grant revision");let p=(_,A)=>a(_,A)&&_.operation_receipt.operation==="transition_card_program_connection_status"&&_.operation_receipt.expected_revision===s.expectedGrantRevision;return n("POST",`${u}/transitions`,y(s),JSON.stringify(i),[200,202],p,s)},async getDeliveryOperation(i,s){o(h(i),"operationReceiptId must be the original receipt UUID");let p=await n("GET",`${u}/delivery-operations/${i}`,C(),void 0,[200],d,s);if(p.operation_receipt.operation_receipt_id!==i)throw x(200);return p}})}
@@ -1,5 +1,5 @@
1
- import { B as BindingSessionCreate, a as BindingSessionCreated, b as BindingSessionStatus, P as ProviderProofSubmitPayload, c as ProviderProofAccepted, d as BindingProofChallenge, I as IntentCardList$1, e as IntentCardItem$1, f as IntentCardsReplaceInput, g as IntentCardsReplaced, h as IntentCancelInput, i as IntentCancelled, j as BindingLookupInput, k as BindingLookupResult$1, l as BindingSummary$1, A as AuthorizationCreateInput$1, S as SynchronousAuthorizationApproved, m as SynchronousAuthorizationDeclined, n as AuthorizationDeadlineExceeded, o as AuthorizationAccepted, p as AuthorizationFactInput$1, q as AuthorizationFactReceipt, r as AuthorizationOperationType, s as AuthorizationLookupResult$1, t as AuthorizationProjection$1, u as AuthorizationFacts, v as AuthorizationLifecycle, C as ChargeFinalReceipt, w as CardInboundEventInput, x as CardInboundEventReceipt, D as DeliveryReconciliationListInput, y as DeliveryPage$1, z as DeliveryItem$1, F as DeliveryReplayCreateInput, G as DeliveryReplayAccepted, H as DeadLetterPage, J as DeadLetterReplayAccepted, K as DeliveryReceiverView, L as DeliveryReceiverReplacement, M as DeliveryOperationView, N as DeliveryReceiverTransition, O as DeliveryGrantTransition } from '../index.d-BikZSd0p.cjs';
2
- import { C as CardEnvironment, T as TransportOptions, a as CardRequestOptions, O as OpenVocabulary } from '../card-transport-Zh-6EMPi.cjs';
1
+ import { B as BindingSessionCreate, a as BindingSessionCreated, b as BindingSessionStatus, P as ProviderProofSubmitPayload, c as ProviderProofAccepted, d as BindingProofChallenge, I as IntentCardList$1, e as IntentCardItem$1, f as IntentCardsReplaceInput, g as IntentCardsReplaced, h as IntentCancelInput, i as IntentCancelled, j as BindingLookupInput, k as BindingLookupResult$1, l as BindingSummary$1, A as AuthorizationCreateInput$1, S as SynchronousAuthorizationApproved, m as SynchronousAuthorizationDeclined, n as AuthorizationDeadlineExceeded, o as AuthorizationAccepted, p as AuthorizationFactInput$1, q as AuthorizationFactReceipt, r as AuthorizationOperationType, s as AuthorizationLookupResult$1, t as AuthorizationProjection$1, u as AuthorizationFacts, v as AuthorizationLifecycle, C as ChargeFinalReceipt, w as CardInboundEventInput, x as CardInboundEventReceipt, D as DeliveryReconciliationListInput, y as DeliveryPage$1, z as DeliveryItem$1, F as DeliveryReplayCreateInput, G as DeliveryReplayAccepted, H as DeadLetterPage, J as DeadLetterReplayAccepted, K as DeliveryReceiverView, L as DeliveryReceiverReplacement, M as DeliveryOperationView, N as DeliveryReceiverTransition, O as DeliveryGrantTransition } from '../index.d-oRLzr8gp.cjs';
2
+ import { C as CardEnvironment, T as TransportOptions, a as CardRequestOptions, O as OpenVocabulary } from '../card-transport--tl4vJa5.cjs';
3
3
 
4
4
  declare const ALLOWED_CONSENTS: readonly ["card.metadata.view", "card.use_for_facto_payments"];
5
5
  declare const ALLOWED_ASSURANCES: readonly ["passkey", "mfa", "reauthenticated_session"];
@@ -1,5 +1,5 @@
1
- import { B as BindingSessionCreate, a as BindingSessionCreated, b as BindingSessionStatus, P as ProviderProofSubmitPayload, c as ProviderProofAccepted, d as BindingProofChallenge, I as IntentCardList$1, e as IntentCardItem$1, f as IntentCardsReplaceInput, g as IntentCardsReplaced, h as IntentCancelInput, i as IntentCancelled, j as BindingLookupInput, k as BindingLookupResult$1, l as BindingSummary$1, A as AuthorizationCreateInput$1, S as SynchronousAuthorizationApproved, m as SynchronousAuthorizationDeclined, n as AuthorizationDeadlineExceeded, o as AuthorizationAccepted, p as AuthorizationFactInput$1, q as AuthorizationFactReceipt, r as AuthorizationOperationType, s as AuthorizationLookupResult$1, t as AuthorizationProjection$1, u as AuthorizationFacts, v as AuthorizationLifecycle, C as ChargeFinalReceipt, w as CardInboundEventInput, x as CardInboundEventReceipt, D as DeliveryReconciliationListInput, y as DeliveryPage$1, z as DeliveryItem$1, F as DeliveryReplayCreateInput, G as DeliveryReplayAccepted, H as DeadLetterPage, J as DeadLetterReplayAccepted, K as DeliveryReceiverView, L as DeliveryReceiverReplacement, M as DeliveryOperationView, N as DeliveryReceiverTransition, O as DeliveryGrantTransition } from '../index.d-BikZSd0p.js';
2
- import { C as CardEnvironment, T as TransportOptions, a as CardRequestOptions, O as OpenVocabulary } from '../card-transport-Zh-6EMPi.js';
1
+ import { B as BindingSessionCreate, a as BindingSessionCreated, b as BindingSessionStatus, P as ProviderProofSubmitPayload, c as ProviderProofAccepted, d as BindingProofChallenge, I as IntentCardList$1, e as IntentCardItem$1, f as IntentCardsReplaceInput, g as IntentCardsReplaced, h as IntentCancelInput, i as IntentCancelled, j as BindingLookupInput, k as BindingLookupResult$1, l as BindingSummary$1, A as AuthorizationCreateInput$1, S as SynchronousAuthorizationApproved, m as SynchronousAuthorizationDeclined, n as AuthorizationDeadlineExceeded, o as AuthorizationAccepted, p as AuthorizationFactInput$1, q as AuthorizationFactReceipt, r as AuthorizationOperationType, s as AuthorizationLookupResult$1, t as AuthorizationProjection$1, u as AuthorizationFacts, v as AuthorizationLifecycle, C as ChargeFinalReceipt, w as CardInboundEventInput, x as CardInboundEventReceipt, D as DeliveryReconciliationListInput, y as DeliveryPage$1, z as DeliveryItem$1, F as DeliveryReplayCreateInput, G as DeliveryReplayAccepted, H as DeadLetterPage, J as DeadLetterReplayAccepted, K as DeliveryReceiverView, L as DeliveryReceiverReplacement, M as DeliveryOperationView, N as DeliveryReceiverTransition, O as DeliveryGrantTransition } from '../index.d-oRLzr8gp.js';
2
+ import { C as CardEnvironment, T as TransportOptions, a as CardRequestOptions, O as OpenVocabulary } from '../card-transport--tl4vJa5.js';
3
3
 
4
4
  declare const ALLOWED_CONSENTS: readonly ["card.metadata.view", "card.use_for_facto_payments"];
5
5
  declare const ALLOWED_ASSURANCES: readonly ["passkey", "mfa", "reauthenticated_session"];
@@ -1 +1 @@
1
- import{a as v,b as x,c as O,d as R,e as i,f,g as o,h as c,i as l,j as _,k as m,l as a,m as h,n as D,o as q,r as V}from"../chunk-MSUNZ66U.js";import"../chunk-2WJ3CACP.js";var z=/^cprog_[A-Za-z0-9_-]{16,}$/;function M(e){return D(e)}function T(e){if(!i(e,1,2048))return!1;try{let n=new URL(e);return n.protocol==="https:"&&!n.username&&!n.password&&!n.hash}catch{return!1}}function A(e){return Array.isArray(e)&&e.length>=1&&e.length<=32&&e.every(n=>i(n,1,120))&&new Set(e).size===e.length}function E(e){return m(e,["callback_endpoint_id","program_connection_id","provider_connection_id","environment","target_revision","endpoint_url","signing_key_id","status","principal_ref","approval_ref","event_kinds","grant_revision","registered_by_actor_ref","created_at","updated_at"],["pending_operation_receipt_id"])?o(e.callback_endpoint_id)&&typeof e.program_connection_id=="string"&&v.test(e.program_connection_id)&&typeof e.provider_connection_id=="string"&&/^pc_[A-Za-z0-9_-]{16,}$/.test(e.provider_connection_id)&&["dev","production"].includes(String(e.environment))&&o(e.target_revision)&&T(e.endpoint_url)&&i(e.signing_key_id)&&i(e.principal_ref)&&i(e.approval_ref)&&A(e.event_kinds)&&c(e.grant_revision)&&i(e.registered_by_actor_ref)&&l(e.created_at)&&l(e.updated_at)&&(["stopping","indeterminate"].includes(String(e.status))?o(e.pending_operation_receipt_id):["active","disabled"].includes(String(e.status))&&!Object.hasOwn(e,"pending_operation_receipt_id")):!1}function G(e){if(!m(e,["status","operation_receipt"],["effective_at","previous_target_revision","requested_target_revision","current_receiver"]))return!1;let n=e.operation_receipt;if(!m(n,["operation_receipt_id","operation","scope_ref","request_digest","expected_revision","status","recorded_at","evidence_refs"],["result_revision","reason_code"])||!o(n.operation_receipt_id)||!i(n.operation)||typeof n.scope_ref!="string"||!v.test(n.scope_ref)||typeof n.request_digest!="string"||!x.test(n.request_digest)||!c(n.expected_revision)||!l(n.recorded_at)||!Array.isArray(n.evidence_refs)||n.evidence_refs.length>100||!n.evidence_refs.every(s=>i(s))||new Set(n.evidence_refs).size!==n.evidence_refs.length||n.reason_code!==void 0&&!i(n.reason_code,1,64))return!1;for(let s of["previous_target_revision","requested_target_revision"])if(e[s]!==void 0&&!o(e[s]))return!1;if(e.status==="effective")return n.status==="committed"&&c(n.result_revision)&&l(e.effective_at)&&(e.current_receiver===void 0||E(e.current_receiver));let d={pending:"accepted",indeterminate:"indeterminate",rejected:"rejected"};return typeof e.status=="string"&&Object.hasOwn(d,e.status)&&n.status===d[e.status]&&!Object.hasOwn(n,"result_revision")&&!Object.hasOwn(e,"effective_at")&&!Object.hasOwn(e,"current_receiver")}var k={"2026-10-23-green-proposal.4":{digest:"sha256:117822c07295b7b574f488dfd74a32d4edf3f648e5d2a8333916301354798367",kinds:["card_program.card_binding.linked","card_program.card_binding.relinked","card_program.card_binding.revoked","card_program.card_binding.route_association_changed","card_program.card_binding.spend_envelope_changed","card_program.card_binding.ownership_transferred","card_program.charge.finalized","card_program.charge.facts_updated"]},"2026-10-23-green-proposal.5":{digest:"sha256:b17e2170470adda15c7f02e3341f7afeab7680abcfbae6610e1eb6094bf4f6ab",kinds:["card_program.card_binding.linked","card_program.card_binding.relinked","card_program.card_binding.revoked","card_program.card_binding.route_association_changed","card_program.card_binding.spend_envelope_changed","card_program.card_binding.ownership_transferred","card_program.charge.finalized","card_program.charge.facts_updated","card_program.authorization.updated"]},"2026-11-18-card-events.1":{digest:"sha256:9fcad68499ef3f770533ad3f3a4c4950d16c0385c56b2b0af6bba5375038aa98",kinds:["card.binding.linked","card.binding.relinked","card.binding.revoked","card.binding.route_changed","card.binding.limits_changed","card.binding.ownership_transferred","card.charge.finalized","card.charge.facts_updated","card.authorization.updated"]}};function I(e){a(_(e,["endpoint_url","signing_key_id","principal_ref","approval_ref","expected_grant_revision","expected_target_revision","required_event_catalog_revision","required_event_catalog_digest","event_kinds"]),"Receiver replacement requires the complete generated request"),a(T(e.endpoint_url)&&i(e.signing_key_id)&&i(e.principal_ref)&&i(e.approval_ref)&&c(e.expected_grant_revision)&&(e.expected_target_revision===null||o(e.expected_target_revision))&&typeof e.required_event_catalog_revision=="string"&&Object.hasOwn(k,e.required_event_catalog_revision)&&k[e.required_event_catalog_revision].digest===e.required_event_catalog_digest&&A(e.event_kinds)&&e.event_kinds.every(n=>k[e.required_event_catalog_revision].kinds.includes(n)),"Receiver replacement fields are invalid")}function $(e){if(a(R(e)&&typeof e.transition=="string"&&typeof e.reason_code=="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(e.reason_code),"Grant transition must contain an exact transition and reason"),e.transition==="activate"){a(_(e,["transition","reason_code","approval_ref","expected_grant_revision","expected_target_revision"])&&i(e.approval_ref)&&c(e.expected_grant_revision)&&o(e.expected_target_revision),"Activate requires its approved grant and target revision");return}if(e.transition==="disable"||e.transition==="revoke"){a(_(e,["transition","reason_code"]),"Disable and revoke cannot inject approval or revision fields");return}a(e.transition==="handover"&&_(e,["transition","reason_code","approval_ref","new_principal_ref","new_credential_binding_id","new_credential_key_id","expected_target_revision","replacement_receiver"])&&i(e.approval_ref)&&i(e.new_principal_ref)&&o(e.new_credential_binding_id)&&i(e.new_credential_key_id)&&o(e.expected_target_revision),"Handover requires the complete approved replacement identity"),I(e.replacement_receiver),a(e.replacement_receiver.principal_ref===e.new_principal_ref&&e.replacement_receiver.expected_target_revision===e.expected_target_revision,"Handover replacement must preserve its approved principal and target revision")}function K(e){a(_(e,["environment","cardProgramId","programConnectionId","adminSessionToken"],O),"Admin options cannot contain Program-machine or arbitrary authentication fields"),a(typeof e.cardProgramId=="string"&&z.test(e.cardProgramId)&&typeof e.programConnectionId=="string"&&v.test(e.programConnectionId),"Admin scope requires cardProgramId and programConnectionId"),a(f(e.adminSessionToken,1,16384),"An existing AdminSession bearer token is required");let n=q(e,"admin"),d=e.programConnectionId,s=e.environment,g=`/api/admin/card-programs/${e.cardProgramId}/program-connections/${d}`,S=`Bearer ${e.adminSessionToken}`,y=()=>new Headers({authorization:S});function u(r){a(r&&f(r.idempotencyKey,16,255)&&c(r.expectedGrantRevision)&&f(r.deploymentTarget,1,64),"Admin mutation requires Idempotency-Key, expectedGrantRevision, and deploymentTarget");let t=y();return t.set("Idempotency-Key",r.idempotencyKey),t.set("If-Match",String(r.expectedGrantRevision)),t.set("X-Facto-Target",r.deploymentTarget),t}function w(r){return G(r)&&r.operation_receipt.scope_ref===d&&(!r.current_receiver||r.current_receiver.program_connection_id===d&&r.current_receiver.environment===s)}function b(r,t){return w(r)&&(t===200?r.status==="effective":r.status==="pending"||r.status==="indeterminate")}return Object.freeze({async getCallbackEndpoint(r){let t=await n("GET",`${g}/callback-endpoint`,y(),void 0,[200],E,r);if(t.program_connection_id!==d||t.environment!==s)throw h(200);return t},async replaceCallbackEndpoint(r,t){I(r);let p=u(t);return a(r.expected_grant_revision===t.expectedGrantRevision,"Body and If-Match must name the same expected grant revision"),n("PUT",`${g}/callback-endpoint`,p,JSON.stringify(r),[200,202],b,t)},async transitionCallbackEndpoint(r,t){return a(_(r,["status","expected_target_revision","reason_code"])&&r.status==="disabled"&&o(r.expected_target_revision)&&typeof r.reason_code=="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(r.reason_code),"Receiver transition must name its exact target and disabled status"),n("POST",`${g}/callback-endpoint/transitions`,u(t),JSON.stringify(r),[200,202],b,t)},async transitionConnectionStatus(r,t){$(r),r.transition==="activate"?a(r.expected_grant_revision===t.expectedGrantRevision,"Activation body and If-Match must name the same expected grant revision"):r.transition==="handover"&&a(r.replacement_receiver.expected_grant_revision===t.expectedGrantRevision,"Handover receiver and If-Match must name the same expected grant revision");let p=(C,P)=>b(C,P)&&C.operation_receipt.operation==="transition_card_program_connection_status"&&C.operation_receipt.expected_revision===t.expectedGrantRevision;return n("POST",`${g}/transitions`,u(t),JSON.stringify(r),[200,202],p,t)},async getDeliveryOperation(r,t){a(o(r),"operationReceiptId must be the original receipt UUID");let p=await n("GET",`${g}/delivery-operations/${r}`,y(),void 0,[200],w,t);if(p.operation_receipt.operation_receipt_id!==r)throw h(200);return p}})}export{V as createCardClient,K as createCardConnectAdminClient,M as isCardConnectAdminErrorEnvelope};
1
+ import{a as v,b as x,c as O,d as R,e as i,f,g as o,h as c,i as l,j as _,k as m,l as a,m as h,n as D,o as q,r as V}from"../chunk-GJFQH2I6.js";import"../chunk-VQJMKCAN.js";var z=/^cprog_[A-Za-z0-9_-]{16,}$/;function M(e){return D(e)}function T(e){if(!i(e,1,2048))return!1;try{let n=new URL(e);return n.protocol==="https:"&&!n.username&&!n.password&&!n.hash}catch{return!1}}function A(e){return Array.isArray(e)&&e.length>=1&&e.length<=32&&e.every(n=>i(n,1,120))&&new Set(e).size===e.length}function E(e){return m(e,["callback_endpoint_id","program_connection_id","provider_connection_id","environment","target_revision","endpoint_url","signing_key_id","status","principal_ref","approval_ref","event_kinds","grant_revision","registered_by_actor_ref","created_at","updated_at"],["pending_operation_receipt_id"])?o(e.callback_endpoint_id)&&typeof e.program_connection_id=="string"&&v.test(e.program_connection_id)&&typeof e.provider_connection_id=="string"&&/^pc_[A-Za-z0-9_-]{16,}$/.test(e.provider_connection_id)&&["dev","production"].includes(String(e.environment))&&o(e.target_revision)&&T(e.endpoint_url)&&i(e.signing_key_id)&&i(e.principal_ref)&&i(e.approval_ref)&&A(e.event_kinds)&&c(e.grant_revision)&&i(e.registered_by_actor_ref)&&l(e.created_at)&&l(e.updated_at)&&(["stopping","indeterminate"].includes(String(e.status))?o(e.pending_operation_receipt_id):["active","disabled"].includes(String(e.status))&&!Object.hasOwn(e,"pending_operation_receipt_id")):!1}function G(e){if(!m(e,["status","operation_receipt"],["effective_at","previous_target_revision","requested_target_revision","current_receiver"]))return!1;let n=e.operation_receipt;if(!m(n,["operation_receipt_id","operation","scope_ref","request_digest","expected_revision","status","recorded_at","evidence_refs"],["result_revision","reason_code"])||!o(n.operation_receipt_id)||!i(n.operation)||typeof n.scope_ref!="string"||!v.test(n.scope_ref)||typeof n.request_digest!="string"||!x.test(n.request_digest)||!c(n.expected_revision)||!l(n.recorded_at)||!Array.isArray(n.evidence_refs)||n.evidence_refs.length>100||!n.evidence_refs.every(s=>i(s))||new Set(n.evidence_refs).size!==n.evidence_refs.length||n.reason_code!==void 0&&!i(n.reason_code,1,64))return!1;for(let s of["previous_target_revision","requested_target_revision"])if(e[s]!==void 0&&!o(e[s]))return!1;if(e.status==="effective")return n.status==="committed"&&c(n.result_revision)&&l(e.effective_at)&&(e.current_receiver===void 0||E(e.current_receiver));let d={pending:"accepted",indeterminate:"indeterminate",rejected:"rejected"};return typeof e.status=="string"&&Object.hasOwn(d,e.status)&&n.status===d[e.status]&&!Object.hasOwn(n,"result_revision")&&!Object.hasOwn(e,"effective_at")&&!Object.hasOwn(e,"current_receiver")}var k={"2026-10-23-green-proposal.4":{digest:"sha256:117822c07295b7b574f488dfd74a32d4edf3f648e5d2a8333916301354798367",kinds:["card_program.card_binding.linked","card_program.card_binding.relinked","card_program.card_binding.revoked","card_program.card_binding.route_association_changed","card_program.card_binding.spend_envelope_changed","card_program.card_binding.ownership_transferred","card_program.charge.finalized","card_program.charge.facts_updated"]},"2026-10-23-green-proposal.5":{digest:"sha256:b17e2170470adda15c7f02e3341f7afeab7680abcfbae6610e1eb6094bf4f6ab",kinds:["card_program.card_binding.linked","card_program.card_binding.relinked","card_program.card_binding.revoked","card_program.card_binding.route_association_changed","card_program.card_binding.spend_envelope_changed","card_program.card_binding.ownership_transferred","card_program.charge.finalized","card_program.charge.facts_updated","card_program.authorization.updated"]},"2026-11-18-card-events.1":{digest:"sha256:9fcad68499ef3f770533ad3f3a4c4950d16c0385c56b2b0af6bba5375038aa98",kinds:["card.binding.linked","card.binding.relinked","card.binding.revoked","card.binding.route_changed","card.binding.limits_changed","card.binding.ownership_transferred","card.charge.finalized","card.charge.facts_updated","card.authorization.updated"]}};function I(e){a(_(e,["endpoint_url","signing_key_id","principal_ref","approval_ref","expected_grant_revision","expected_target_revision","required_event_catalog_revision","required_event_catalog_digest","event_kinds"]),"Receiver replacement requires the complete generated request"),a(T(e.endpoint_url)&&i(e.signing_key_id)&&i(e.principal_ref)&&i(e.approval_ref)&&c(e.expected_grant_revision)&&(e.expected_target_revision===null||o(e.expected_target_revision))&&typeof e.required_event_catalog_revision=="string"&&Object.hasOwn(k,e.required_event_catalog_revision)&&k[e.required_event_catalog_revision].digest===e.required_event_catalog_digest&&A(e.event_kinds)&&e.event_kinds.every(n=>k[e.required_event_catalog_revision].kinds.includes(n)),"Receiver replacement fields are invalid")}function $(e){if(a(R(e)&&typeof e.transition=="string"&&typeof e.reason_code=="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(e.reason_code),"Grant transition must contain an exact transition and reason"),e.transition==="activate"){a(_(e,["transition","reason_code","approval_ref","expected_grant_revision","expected_target_revision"])&&i(e.approval_ref)&&c(e.expected_grant_revision)&&o(e.expected_target_revision),"Activate requires its approved grant and target revision");return}if(e.transition==="disable"||e.transition==="revoke"){a(_(e,["transition","reason_code"]),"Disable and revoke cannot inject approval or revision fields");return}a(e.transition==="handover"&&_(e,["transition","reason_code","approval_ref","new_principal_ref","new_credential_binding_id","new_credential_key_id","expected_target_revision","replacement_receiver"])&&i(e.approval_ref)&&i(e.new_principal_ref)&&o(e.new_credential_binding_id)&&i(e.new_credential_key_id)&&o(e.expected_target_revision),"Handover requires the complete approved replacement identity"),I(e.replacement_receiver),a(e.replacement_receiver.principal_ref===e.new_principal_ref&&e.replacement_receiver.expected_target_revision===e.expected_target_revision,"Handover replacement must preserve its approved principal and target revision")}function K(e){a(_(e,["environment","cardProgramId","programConnectionId","adminSessionToken"],O),"Admin options cannot contain Program-machine or arbitrary authentication fields"),a(typeof e.cardProgramId=="string"&&z.test(e.cardProgramId)&&typeof e.programConnectionId=="string"&&v.test(e.programConnectionId),"Admin scope requires cardProgramId and programConnectionId"),a(f(e.adminSessionToken,1,16384),"An existing AdminSession bearer token is required");let n=q(e,"admin"),d=e.programConnectionId,s=e.environment,g=`/api/admin/card-programs/${e.cardProgramId}/program-connections/${d}`,S=`Bearer ${e.adminSessionToken}`,y=()=>new Headers({authorization:S});function u(r){a(r&&f(r.idempotencyKey,16,255)&&c(r.expectedGrantRevision)&&f(r.deploymentTarget,1,64),"Admin mutation requires Idempotency-Key, expectedGrantRevision, and deploymentTarget");let t=y();return t.set("Idempotency-Key",r.idempotencyKey),t.set("If-Match",String(r.expectedGrantRevision)),t.set("X-Facto-Target",r.deploymentTarget),t}function w(r){return G(r)&&r.operation_receipt.scope_ref===d&&(!r.current_receiver||r.current_receiver.program_connection_id===d&&r.current_receiver.environment===s)}function b(r,t){return w(r)&&(t===200?r.status==="effective":r.status==="pending"||r.status==="indeterminate")}return Object.freeze({async getCallbackEndpoint(r){let t=await n("GET",`${g}/callback-endpoint`,y(),void 0,[200],E,r);if(t.program_connection_id!==d||t.environment!==s)throw h(200);return t},async replaceCallbackEndpoint(r,t){I(r);let p=u(t);return a(r.expected_grant_revision===t.expectedGrantRevision,"Body and If-Match must name the same expected grant revision"),n("PUT",`${g}/callback-endpoint`,p,JSON.stringify(r),[200,202],b,t)},async transitionCallbackEndpoint(r,t){return a(_(r,["status","expected_target_revision","reason_code"])&&r.status==="disabled"&&o(r.expected_target_revision)&&typeof r.reason_code=="string"&&/^[a-z][a-z0-9_]{1,63}$/.test(r.reason_code),"Receiver transition must name its exact target and disabled status"),n("POST",`${g}/callback-endpoint/transitions`,u(t),JSON.stringify(r),[200,202],b,t)},async transitionConnectionStatus(r,t){$(r),r.transition==="activate"?a(r.expected_grant_revision===t.expectedGrantRevision,"Activation body and If-Match must name the same expected grant revision"):r.transition==="handover"&&a(r.replacement_receiver.expected_grant_revision===t.expectedGrantRevision,"Handover receiver and If-Match must name the same expected grant revision");let p=(C,P)=>b(C,P)&&C.operation_receipt.operation==="transition_card_program_connection_status"&&C.operation_receipt.expected_revision===t.expectedGrantRevision;return n("POST",`${g}/transitions`,u(t),JSON.stringify(r),[200,202],p,t)},async getDeliveryOperation(r,t){a(o(r),"operationReceiptId must be the original receipt UUID");let p=await n("GET",`${g}/delivery-operations/${r}`,y(),void 0,[200],w,t);if(p.operation_receipt.operation_receipt_id!==r)throw h(200);return p}})}export{V as createCardClient,K as createCardConnectAdminClient,M as isCardConnectAdminErrorEnvelope};